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
jeffcampbellmakesgames/Genesis
3,295
Unity/Assets/JCMG/Genesis/Scripts/Editor/Tools/AssetDatabaseTools.cs
/* MIT License Copyright (c) Jeff Campbell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace JCMG.Genesis.Editor { /// <summary> /// Helper methods for the AssetDatabase /// </summary> public static class AssetDatabaseTools { private static readonly Type SCRIPTABLE_OBJECT_TYPE; private static readonly Dictionary<Type, ScriptableObject> SCRIPTABLE_ASSET_LOOKUP; private const string FILTER_TYPE_SEARCH = "t:{0}"; static AssetDatabaseTools() { SCRIPTABLE_OBJECT_TYPE = typeof(ScriptableObject); SCRIPTABLE_ASSET_LOOKUP = new Dictionary<Type, ScriptableObject>(); } /// <summary> /// Returns the first <see cref="ScriptableObject"/> asset found of Type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="asset"></param> /// <returns></returns> public static bool TryGetSingleScriptableAsset<T>(out T asset) where T : ScriptableObject { asset = null; var type = typeof(T); if (SCRIPTABLE_ASSET_LOOKUP.ContainsKey(type)) { asset = (T)SCRIPTABLE_ASSET_LOOKUP[type]; } else { var assetGUIDs = AssetDatabase.FindAssets(string.Format(FILTER_TYPE_SEARCH, type.Name)); if (assetGUIDs.Length > 0) { var firstAssetGUID = assetGUIDs[0]; var firstAssetPath = AssetDatabase.GUIDToAssetPath(firstAssetGUID); asset = (T)AssetDatabase.LoadAssetAtPath(firstAssetPath, SCRIPTABLE_OBJECT_TYPE); if (asset != null) { SCRIPTABLE_ASSET_LOOKUP.Add(type, asset); } } } return asset != null; } /// <summary> /// Returns all assets of type <typeparamref name="T"/> found in the Project. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T[] GetAssets<T>() where T : UnityEngine.Object { var assets = new List<T>(); var assetGUIDs = AssetDatabase.FindAssets(string.Format(FILTER_TYPE_SEARCH, typeof(T).Name)); for (var i = 0; i < assetGUIDs.Length; i++) { var assetPath = AssetDatabase.GUIDToAssetPath(assetGUIDs[i]); var asset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(T)) as T; if (asset != null) { assets.Add(asset); } } return assets.ToArray(); } } }
0
0.802783
1
0.802783
game-dev
MEDIA
0.97629
game-dev
0.931272
1
0.931272
tsunamods-codes/Junction-VIII
5,852
AppWrapper/Data.cs
/* This source is subject to the Microsoft Public License. See LICENSE.TXT for details. The original developer is Iros <irosff@outlook.com> */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProcMonParser { public class DataItem { public string Name { get; set; } public long Start { get; set; } public int Length { get; set; } public int Index { get; set; } } public class DataFile { public List<DataItem> Items { get; set; } public string Filename { get; set; } public DataFile() { Items = new List<DataItem>(); } public void Freeze() { Items = Items.OrderBy(i => i.Start).ToList(); } public DataItem Get(int offset) { if (offset < Items[0].Start) return null; int min = 0, max = Items.Count - 1; while (min <= max) { int check = (min + max + 1) / 2; if (offset < Items[check].Start) max = check - 1; else if (offset >= (Items[check].Start + Items[check].Length)) min = check + 1; else { return Items[check]; } } if (min > 0) { AppWrapper.DebugLogger.WriteLine("Mid read from " + Filename + " at offset " + offset); } return null; } } public static class FF8Files { public static int ReadInt(this System.IO.Stream s) { byte[] data = new byte[4]; s.ReadExactly(data, 0, 4); return BitConverter.ToInt32(data, 0); } public static uint ReadUInt(this System.IO.Stream s) { byte[] data = new byte[4]; s.ReadExactly(data, 0, 4); return BitConverter.ToUInt32(data, 0); } public static ushort ReadUShort(this System.IO.Stream s) { byte[] data = new byte[2]; s.ReadExactly(data, 0, 2); return BitConverter.ToUInt16(data, 0); } public static DataFile LoadSounds(string ff8folder) { int count = 0; DataFile df = new DataFile() { Filename = System.IO.Path.Combine(ff8folder, "sound\\audio.dat") }; using (var fmtFile = new System.IO.FileStream(System.IO.Path.Combine(ff8folder, "sound\\audio.fmt"), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { while (fmtFile.Position < fmtFile.Length) { int length = fmtFile.ReadInt(); if (length == 0) { fmtFile.Seek(38, System.IO.SeekOrigin.Current); continue; } df.Items.Add(new DataItem() { Name = "SOUND" + (count++), Length = length, Start = fmtFile.ReadInt() }); fmtFile.Seek(66, System.IO.SeekOrigin.Current); } } return df; } public static DataFile LoadLGP(System.IO.Stream fs, string file) { DataFile df = new DataFile() { Filename = file }; if (fs.ReadUShort() != 0) throw new Exception(file + " - not a valid LGP archive"); byte[] header = new byte[10]; fs.ReadExactly(header, 0, 10); if (!Encoding.ASCII.GetString(header).Equals("SQUARESOFT")) throw new Exception(file + " - not a valid LGP archive"); int count = fs.ReadInt(); byte[] fname = new byte[20]; List<Tuple<string, uint, ushort, int>> files = new List<Tuple<string, uint, ushort, int>>(); for (int i = 0; i < count; i++) { fs.ReadExactly(fname, 0, 20); uint offset = fs.ReadUInt(); fs.ReadByte(); ushort dupe = fs.ReadUShort(); string lgpFile = Encoding.ASCII.GetString(fname); int nPos = lgpFile.IndexOf('\0'); if (nPos >= 0) lgpFile = lgpFile.Substring(0, nPos); files.Add(new Tuple<string, uint, ushort, int>(lgpFile, offset, dupe, i)); } if (files.Any(t => t.Item3 != 0)) { fs.Seek(3600, System.IO.SeekOrigin.Current); //skip lookup table ushort entries = fs.ReadUShort(); byte[] pname = new byte[128]; foreach (int i in Enumerable.Range(0, entries)) { foreach (int j in Enumerable.Range(0, fs.ReadUShort())) { fs.ReadExactly(pname, 0, 128); ushort toc = fs.ReadUShort(); string ppname = Encoding.ASCII.GetString(pname); ppname = ppname.Substring(0, ppname.IndexOf('\0')); files[toc] = new Tuple<string, uint, ushort, int>( ppname.Replace("/", "\\") + "\\" + files[toc].Item1, files[toc].Item2, files[toc].Item3, files[toc].Item4 ); } } } df.Items = files.Select(t => new DataItem() { Name = t.Item1, Start = t.Item2, Index = t.Item4 }).ToList(); foreach (var item in df.Items) { fs.Position = item.Start + 20; item.Length = fs.ReadInt() + 24; //item.Start = item.Start; } df.Freeze(); return df; } public static DataFile LoadLGP(string file) { using (var fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { return LoadLGP(fs, file); } } } }
0
0.856119
1
0.856119
game-dev
MEDIA
0.698924
game-dev
0.983017
1
0.983017
I-asked/downbge
32,366
extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.h
//Bullet Continuous Collision Detection and Physics Library //Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ // // btAxisSweep3.h // // Copyright (c) 2006 Simon Hobbs // // This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. #ifndef BT_AXIS_SWEEP_3_H #define BT_AXIS_SWEEP_3_H #include "LinearMath/btVector3.h" #include "btOverlappingPairCache.h" #include "btBroadphaseInterface.h" #include "btBroadphaseProxy.h" #include "btOverlappingPairCallback.h" #include "btDbvtBroadphase.h" //#define DEBUG_BROADPHASE 1 #define USE_OVERLAP_TEST_ON_REMOVES 1 /// The internal templace class btAxisSweep3Internal implements the sweep and prune broadphase. /// It uses quantized integers to represent the begin and end points for each of the 3 axis. /// Dont use this class directly, use btAxisSweep3 or bt32BitAxisSweep3 instead. template <typename BP_FP_INT_TYPE> class btAxisSweep3Internal : public btBroadphaseInterface { protected: BP_FP_INT_TYPE m_bpHandleMask; BP_FP_INT_TYPE m_handleSentinel; public: BT_DECLARE_ALIGNED_ALLOCATOR(); class Edge { public: BP_FP_INT_TYPE m_pos; // low bit is min/max BP_FP_INT_TYPE m_handle; BP_FP_INT_TYPE IsMax() const {return static_cast<BP_FP_INT_TYPE>(m_pos & 1);} }; public: class Handle : public btBroadphaseProxy { public: BT_DECLARE_ALIGNED_ALLOCATOR(); // indexes into the edge arrays BP_FP_INT_TYPE m_minEdges[3], m_maxEdges[3]; // 6 * 2 = 12 // BP_FP_INT_TYPE m_uniqueId; btBroadphaseProxy* m_dbvtProxy;//for faster raycast //void* m_pOwner; this is now in btBroadphaseProxy.m_clientObject SIMD_FORCE_INLINE void SetNextFree(BP_FP_INT_TYPE next) {m_minEdges[0] = next;} SIMD_FORCE_INLINE BP_FP_INT_TYPE GetNextFree() const {return m_minEdges[0];} }; // 24 bytes + 24 for Edge structures = 44 bytes total per entry protected: btVector3 m_worldAabbMin; // overall system bounds btVector3 m_worldAabbMax; // overall system bounds btVector3 m_quantize; // scaling factor for quantization BP_FP_INT_TYPE m_numHandles; // number of active handles BP_FP_INT_TYPE m_maxHandles; // max number of handles Handle* m_pHandles; // handles pool BP_FP_INT_TYPE m_firstFreeHandle; // free handles list Edge* m_pEdges[3]; // edge arrays for the 3 axes (each array has m_maxHandles * 2 + 2 sentinel entries) void* m_pEdgesRawPtr[3]; btOverlappingPairCache* m_pairCache; ///btOverlappingPairCallback is an additional optional user callback for adding/removing overlapping pairs, similar interface to btOverlappingPairCache. btOverlappingPairCallback* m_userPairCallback; bool m_ownsPairCache; int m_invalidPair; ///additional dynamic aabb structure, used to accelerate ray cast queries. ///can be disabled using a optional argument in the constructor btDbvtBroadphase* m_raycastAccelerator; btOverlappingPairCache* m_nullPairCache; // allocation/deallocation BP_FP_INT_TYPE allocHandle(); void freeHandle(BP_FP_INT_TYPE handle); bool testOverlap2D(const Handle* pHandleA, const Handle* pHandleB,int axis0,int axis1); #ifdef DEBUG_BROADPHASE void debugPrintAxis(int axis,bool checkCardinality=true); #endif //DEBUG_BROADPHASE //Overlap* AddOverlap(BP_FP_INT_TYPE handleA, BP_FP_INT_TYPE handleB); //void RemoveOverlap(BP_FP_INT_TYPE handleA, BP_FP_INT_TYPE handleB); void sortMinDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); void sortMinUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); void sortMaxDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); void sortMaxUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); public: btAxisSweep3Internal(const btVector3& worldAabbMin,const btVector3& worldAabbMax, BP_FP_INT_TYPE handleMask, BP_FP_INT_TYPE handleSentinel, BP_FP_INT_TYPE maxHandles = 16384, btOverlappingPairCache* pairCache=0,bool disableRaycastAccelerator = false); virtual ~btAxisSweep3Internal(); BP_FP_INT_TYPE getNumHandles() const { return m_numHandles; } virtual void calculateOverlappingPairs(btDispatcher* dispatcher); BP_FP_INT_TYPE addHandle(const btVector3& aabbMin,const btVector3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy); void removeHandle(BP_FP_INT_TYPE handle,btDispatcher* dispatcher); void updateHandle(BP_FP_INT_TYPE handle, const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher); SIMD_FORCE_INLINE Handle* getHandle(BP_FP_INT_TYPE index) const {return m_pHandles + index;} virtual void resetPool(btDispatcher* dispatcher); void processAllOverlappingPairs(btOverlapCallback* callback); //Broadphase Interface virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy); virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher); virtual void getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const; virtual void rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0), const btVector3& aabbMax = btVector3(0,0,0)); virtual void aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback); void quantize(BP_FP_INT_TYPE* out, const btVector3& point, int isMax) const; ///unQuantize should be conservative: aabbMin/aabbMax should be larger then 'getAabb' result void unQuantize(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const; bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); btOverlappingPairCache* getOverlappingPairCache() { return m_pairCache; } const btOverlappingPairCache* getOverlappingPairCache() const { return m_pairCache; } void setOverlappingPairUserCallback(btOverlappingPairCallback* pairCallback) { m_userPairCallback = pairCallback; } const btOverlappingPairCallback* getOverlappingPairUserCallback() const { return m_userPairCallback; } ///getAabb returns the axis aligned bounding box in the 'global' coordinate frame ///will add some transform later virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const { aabbMin = m_worldAabbMin; aabbMax = m_worldAabbMax; } virtual void printStats() { /* printf("btAxisSweep3.h\n"); printf("numHandles = %d, maxHandles = %d\n",m_numHandles,m_maxHandles); printf("aabbMin=%f,%f,%f,aabbMax=%f,%f,%f\n",m_worldAabbMin.getX(),m_worldAabbMin.getY(),m_worldAabbMin.getZ(), m_worldAabbMax.getX(),m_worldAabbMax.getY(),m_worldAabbMax.getZ()); */ } }; //////////////////////////////////////////////////////////////////// #ifdef DEBUG_BROADPHASE #include <stdio.h> template <typename BP_FP_INT_TYPE> void btAxisSweep3<BP_FP_INT_TYPE>::debugPrintAxis(int axis, bool checkCardinality) { int numEdges = m_pHandles[0].m_maxEdges[axis]; printf("SAP Axis %d, numEdges=%d\n",axis,numEdges); int i; for (i=0;i<numEdges+1;i++) { Edge* pEdge = m_pEdges[axis] + i; Handle* pHandlePrev = getHandle(pEdge->m_handle); int handleIndex = pEdge->IsMax()? pHandlePrev->m_maxEdges[axis] : pHandlePrev->m_minEdges[axis]; char beginOrEnd; beginOrEnd=pEdge->IsMax()?'E':'B'; printf(" [%c,h=%d,p=%x,i=%d]\n",beginOrEnd,pEdge->m_handle,pEdge->m_pos,handleIndex); } if (checkCardinality) btAssert(numEdges == m_numHandles*2+1); } #endif //DEBUG_BROADPHASE template <typename BP_FP_INT_TYPE> btBroadphaseProxy* btAxisSweep3Internal<BP_FP_INT_TYPE>::createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy) { (void)shapeType; BP_FP_INT_TYPE handleId = addHandle(aabbMin,aabbMax, userPtr,collisionFilterGroup,collisionFilterMask,dispatcher,multiSapProxy); Handle* handle = getHandle(handleId); if (m_raycastAccelerator) { btBroadphaseProxy* rayProxy = m_raycastAccelerator->createProxy(aabbMin,aabbMax,shapeType,userPtr,collisionFilterGroup,collisionFilterMask,dispatcher,0); handle->m_dbvtProxy = rayProxy; } return handle; } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher) { Handle* handle = static_cast<Handle*>(proxy); if (m_raycastAccelerator) m_raycastAccelerator->destroyProxy(handle->m_dbvtProxy,dispatcher); removeHandle(static_cast<BP_FP_INT_TYPE>(handle->m_uniqueId), dispatcher); } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher) { Handle* handle = static_cast<Handle*>(proxy); handle->m_aabbMin = aabbMin; handle->m_aabbMax = aabbMax; updateHandle(static_cast<BP_FP_INT_TYPE>(handle->m_uniqueId), aabbMin, aabbMax,dispatcher); if (m_raycastAccelerator) m_raycastAccelerator->setAabb(handle->m_dbvtProxy,aabbMin,aabbMax,dispatcher); } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback,const btVector3& aabbMin,const btVector3& aabbMax) { if (m_raycastAccelerator) { m_raycastAccelerator->rayTest(rayFrom,rayTo,rayCallback,aabbMin,aabbMax); } else { //choose axis? BP_FP_INT_TYPE axis = 0; //for each proxy for (BP_FP_INT_TYPE i=1;i<m_numHandles*2+1;i++) { if (m_pEdges[axis][i].IsMax()) { rayCallback.process(getHandle(m_pEdges[axis][i].m_handle)); } } } } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback) { if (m_raycastAccelerator) { m_raycastAccelerator->aabbTest(aabbMin,aabbMax,callback); } else { //choose axis? BP_FP_INT_TYPE axis = 0; //for each proxy for (BP_FP_INT_TYPE i=1;i<m_numHandles*2+1;i++) { if (m_pEdges[axis][i].IsMax()) { Handle* handle = getHandle(m_pEdges[axis][i].m_handle); if (TestAabbAgainstAabb2(aabbMin,aabbMax,handle->m_aabbMin,handle->m_aabbMax)) { callback.process(handle); } } } } } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const { Handle* pHandle = static_cast<Handle*>(proxy); aabbMin = pHandle->m_aabbMin; aabbMax = pHandle->m_aabbMax; } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::unQuantize(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const { Handle* pHandle = static_cast<Handle*>(proxy); unsigned short vecInMin[3]; unsigned short vecInMax[3]; vecInMin[0] = m_pEdges[0][pHandle->m_minEdges[0]].m_pos ; vecInMax[0] = m_pEdges[0][pHandle->m_maxEdges[0]].m_pos +1 ; vecInMin[1] = m_pEdges[1][pHandle->m_minEdges[1]].m_pos ; vecInMax[1] = m_pEdges[1][pHandle->m_maxEdges[1]].m_pos +1 ; vecInMin[2] = m_pEdges[2][pHandle->m_minEdges[2]].m_pos ; vecInMax[2] = m_pEdges[2][pHandle->m_maxEdges[2]].m_pos +1 ; aabbMin.setValue((btScalar)(vecInMin[0]) / (m_quantize.getX()),(btScalar)(vecInMin[1]) / (m_quantize.getY()),(btScalar)(vecInMin[2]) / (m_quantize.getZ())); aabbMin += m_worldAabbMin; aabbMax.setValue((btScalar)(vecInMax[0]) / (m_quantize.getX()),(btScalar)(vecInMax[1]) / (m_quantize.getY()),(btScalar)(vecInMax[2]) / (m_quantize.getZ())); aabbMax += m_worldAabbMin; } template <typename BP_FP_INT_TYPE> btAxisSweep3Internal<BP_FP_INT_TYPE>::btAxisSweep3Internal(const btVector3& worldAabbMin,const btVector3& worldAabbMax, BP_FP_INT_TYPE handleMask, BP_FP_INT_TYPE handleSentinel,BP_FP_INT_TYPE userMaxHandles, btOverlappingPairCache* pairCache , bool disableRaycastAccelerator) :m_bpHandleMask(handleMask), m_handleSentinel(handleSentinel), m_pairCache(pairCache), m_userPairCallback(0), m_ownsPairCache(false), m_invalidPair(0), m_raycastAccelerator(0) { BP_FP_INT_TYPE maxHandles = static_cast<BP_FP_INT_TYPE>(userMaxHandles+1);//need to add one sentinel handle if (!m_pairCache) { void* ptr = btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16); m_pairCache = new(ptr) btHashedOverlappingPairCache(); m_ownsPairCache = true; } if (!disableRaycastAccelerator) { m_nullPairCache = new (btAlignedAlloc(sizeof(btNullPairCache),16)) btNullPairCache(); m_raycastAccelerator = new (btAlignedAlloc(sizeof(btDbvtBroadphase),16)) btDbvtBroadphase(m_nullPairCache);//m_pairCache); m_raycastAccelerator->m_deferedcollide = true;//don't add/remove pairs } //btAssert(bounds.HasVolume()); // init bounds m_worldAabbMin = worldAabbMin; m_worldAabbMax = worldAabbMax; btVector3 aabbSize = m_worldAabbMax - m_worldAabbMin; BP_FP_INT_TYPE maxInt = m_handleSentinel; m_quantize = btVector3(btScalar(maxInt),btScalar(maxInt),btScalar(maxInt)) / aabbSize; // allocate handles buffer, using btAlignedAlloc, and put all handles on free list m_pHandles = new Handle[maxHandles]; m_maxHandles = maxHandles; m_numHandles = 0; // handle 0 is reserved as the null index, and is also used as the sentinel m_firstFreeHandle = 1; { for (BP_FP_INT_TYPE i = m_firstFreeHandle; i < maxHandles; i++) m_pHandles[i].SetNextFree(static_cast<BP_FP_INT_TYPE>(i + 1)); m_pHandles[maxHandles - 1].SetNextFree(0); } { // allocate edge buffers for (int i = 0; i < 3; i++) { m_pEdgesRawPtr[i] = btAlignedAlloc(sizeof(Edge)*maxHandles*2,16); m_pEdges[i] = new(m_pEdgesRawPtr[i]) Edge[maxHandles * 2]; } } //removed overlap management // make boundary sentinels m_pHandles[0].m_clientObject = 0; for (int axis = 0; axis < 3; axis++) { m_pHandles[0].m_minEdges[axis] = 0; m_pHandles[0].m_maxEdges[axis] = 1; m_pEdges[axis][0].m_pos = 0; m_pEdges[axis][0].m_handle = 0; m_pEdges[axis][1].m_pos = m_handleSentinel; m_pEdges[axis][1].m_handle = 0; #ifdef DEBUG_BROADPHASE debugPrintAxis(axis); #endif //DEBUG_BROADPHASE } } template <typename BP_FP_INT_TYPE> btAxisSweep3Internal<BP_FP_INT_TYPE>::~btAxisSweep3Internal() { if (m_raycastAccelerator) { m_nullPairCache->~btOverlappingPairCache(); btAlignedFree(m_nullPairCache); m_raycastAccelerator->~btDbvtBroadphase(); btAlignedFree (m_raycastAccelerator); } for (int i = 2; i >= 0; i--) { btAlignedFree(m_pEdgesRawPtr[i]); } delete [] m_pHandles; if (m_ownsPairCache) { m_pairCache->~btOverlappingPairCache(); btAlignedFree(m_pairCache); } } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::quantize(BP_FP_INT_TYPE* out, const btVector3& point, int isMax) const { #ifdef OLD_CLAMPING_METHOD ///problem with this clamping method is that the floating point during quantization might still go outside the range [(0|isMax) .. (m_handleSentinel&m_bpHandleMask]|isMax] ///see http://code.google.com/p/bullet/issues/detail?id=87 btVector3 clampedPoint(point); clampedPoint.setMax(m_worldAabbMin); clampedPoint.setMin(m_worldAabbMax); btVector3 v = (clampedPoint - m_worldAabbMin) * m_quantize; out[0] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getX() & m_bpHandleMask) | isMax); out[1] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getY() & m_bpHandleMask) | isMax); out[2] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getZ() & m_bpHandleMask) | isMax); #else btVector3 v = (point - m_worldAabbMin) * m_quantize; out[0]=(v[0]<=0)?(BP_FP_INT_TYPE)isMax:(v[0]>=m_handleSentinel)?(BP_FP_INT_TYPE)((m_handleSentinel&m_bpHandleMask)|isMax):(BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v[0]&m_bpHandleMask)|isMax); out[1]=(v[1]<=0)?(BP_FP_INT_TYPE)isMax:(v[1]>=m_handleSentinel)?(BP_FP_INT_TYPE)((m_handleSentinel&m_bpHandleMask)|isMax):(BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v[1]&m_bpHandleMask)|isMax); out[2]=(v[2]<=0)?(BP_FP_INT_TYPE)isMax:(v[2]>=m_handleSentinel)?(BP_FP_INT_TYPE)((m_handleSentinel&m_bpHandleMask)|isMax):(BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v[2]&m_bpHandleMask)|isMax); #endif //OLD_CLAMPING_METHOD } template <typename BP_FP_INT_TYPE> BP_FP_INT_TYPE btAxisSweep3Internal<BP_FP_INT_TYPE>::allocHandle() { btAssert(m_firstFreeHandle); BP_FP_INT_TYPE handle = m_firstFreeHandle; m_firstFreeHandle = getHandle(handle)->GetNextFree(); m_numHandles++; return handle; } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::freeHandle(BP_FP_INT_TYPE handle) { btAssert(handle > 0 && handle < m_maxHandles); getHandle(handle)->SetNextFree(m_firstFreeHandle); m_firstFreeHandle = handle; m_numHandles--; } template <typename BP_FP_INT_TYPE> BP_FP_INT_TYPE btAxisSweep3Internal<BP_FP_INT_TYPE>::addHandle(const btVector3& aabbMin,const btVector3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy) { // quantize the bounds BP_FP_INT_TYPE min[3], max[3]; quantize(min, aabbMin, 0); quantize(max, aabbMax, 1); // allocate a handle BP_FP_INT_TYPE handle = allocHandle(); Handle* pHandle = getHandle(handle); pHandle->m_uniqueId = static_cast<int>(handle); //pHandle->m_pOverlaps = 0; pHandle->m_clientObject = pOwner; pHandle->m_collisionFilterGroup = collisionFilterGroup; pHandle->m_collisionFilterMask = collisionFilterMask; pHandle->m_multiSapParentProxy = multiSapProxy; // compute current limit of edge arrays BP_FP_INT_TYPE limit = static_cast<BP_FP_INT_TYPE>(m_numHandles * 2); // insert new edges just inside the max boundary edge for (BP_FP_INT_TYPE axis = 0; axis < 3; axis++) { m_pHandles[0].m_maxEdges[axis] += 2; m_pEdges[axis][limit + 1] = m_pEdges[axis][limit - 1]; m_pEdges[axis][limit - 1].m_pos = min[axis]; m_pEdges[axis][limit - 1].m_handle = handle; m_pEdges[axis][limit].m_pos = max[axis]; m_pEdges[axis][limit].m_handle = handle; pHandle->m_minEdges[axis] = static_cast<BP_FP_INT_TYPE>(limit - 1); pHandle->m_maxEdges[axis] = limit; } // now sort the new edges to their correct position sortMinDown(0, pHandle->m_minEdges[0], dispatcher,false); sortMaxDown(0, pHandle->m_maxEdges[0], dispatcher,false); sortMinDown(1, pHandle->m_minEdges[1], dispatcher,false); sortMaxDown(1, pHandle->m_maxEdges[1], dispatcher,false); sortMinDown(2, pHandle->m_minEdges[2], dispatcher,true); sortMaxDown(2, pHandle->m_maxEdges[2], dispatcher,true); return handle; } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::removeHandle(BP_FP_INT_TYPE handle,btDispatcher* dispatcher) { Handle* pHandle = getHandle(handle); //explicitly remove the pairs containing the proxy //we could do it also in the sortMinUp (passing true) ///@todo: compare performance if (!m_pairCache->hasDeferredRemoval()) { m_pairCache->removeOverlappingPairsContainingProxy(pHandle,dispatcher); } // compute current limit of edge arrays int limit = static_cast<int>(m_numHandles * 2); int axis; for (axis = 0;axis<3;axis++) { m_pHandles[0].m_maxEdges[axis] -= 2; } // remove the edges by sorting them up to the end of the list for ( axis = 0; axis < 3; axis++) { Edge* pEdges = m_pEdges[axis]; BP_FP_INT_TYPE max = pHandle->m_maxEdges[axis]; pEdges[max].m_pos = m_handleSentinel; sortMaxUp(axis,max,dispatcher,false); BP_FP_INT_TYPE i = pHandle->m_minEdges[axis]; pEdges[i].m_pos = m_handleSentinel; sortMinUp(axis,i,dispatcher,false); pEdges[limit-1].m_handle = 0; pEdges[limit-1].m_pos = m_handleSentinel; #ifdef DEBUG_BROADPHASE debugPrintAxis(axis,false); #endif //DEBUG_BROADPHASE } // free the handle freeHandle(handle); } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::resetPool(btDispatcher* /*dispatcher*/) { if (m_numHandles == 0) { m_firstFreeHandle = 1; { for (BP_FP_INT_TYPE i = m_firstFreeHandle; i < m_maxHandles; i++) m_pHandles[i].SetNextFree(static_cast<BP_FP_INT_TYPE>(i + 1)); m_pHandles[m_maxHandles - 1].SetNextFree(0); } } } extern int gOverlappingPairs; //#include <stdio.h> template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::calculateOverlappingPairs(btDispatcher* dispatcher) { if (m_pairCache->hasDeferredRemoval()) { btBroadphasePairArray& overlappingPairArray = m_pairCache->getOverlappingPairArray(); //perform a sort, to find duplicates and to sort 'invalid' pairs to the end overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); m_invalidPair = 0; int i; btBroadphasePair previousPair; previousPair.m_pProxy0 = 0; previousPair.m_pProxy1 = 0; previousPair.m_algorithm = 0; for (i=0;i<overlappingPairArray.size();i++) { btBroadphasePair& pair = overlappingPairArray[i]; bool isDuplicate = (pair == previousPair); previousPair = pair; bool needsRemoval = false; if (!isDuplicate) { ///important to use an AABB test that is consistent with the broadphase bool hasOverlap = testAabbOverlap(pair.m_pProxy0,pair.m_pProxy1); if (hasOverlap) { needsRemoval = false;//callback->processOverlap(pair); } else { needsRemoval = true; } } else { //remove duplicate needsRemoval = true; //should have no algorithm btAssert(!pair.m_algorithm); } if (needsRemoval) { m_pairCache->cleanOverlappingPair(pair,dispatcher); // m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1); // m_overlappingPairArray.pop_back(); pair.m_pProxy0 = 0; pair.m_pProxy1 = 0; m_invalidPair++; gOverlappingPairs--; } } ///if you don't like to skip the invalid pairs in the array, execute following code: #define CLEAN_INVALID_PAIRS 1 #ifdef CLEAN_INVALID_PAIRS //perform a sort, to sort 'invalid' pairs to the end overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); m_invalidPair = 0; #endif//CLEAN_INVALID_PAIRS //printf("overlappingPairArray.size()=%d\n",overlappingPairArray.size()); } } template <typename BP_FP_INT_TYPE> bool btAxisSweep3Internal<BP_FP_INT_TYPE>::testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) { const Handle* pHandleA = static_cast<Handle*>(proxy0); const Handle* pHandleB = static_cast<Handle*>(proxy1); //optimization 1: check the array index (memory address), instead of the m_pos for (int axis = 0; axis < 3; axis++) { if (pHandleA->m_maxEdges[axis] < pHandleB->m_minEdges[axis] || pHandleB->m_maxEdges[axis] < pHandleA->m_minEdges[axis]) { return false; } } return true; } template <typename BP_FP_INT_TYPE> bool btAxisSweep3Internal<BP_FP_INT_TYPE>::testOverlap2D(const Handle* pHandleA, const Handle* pHandleB,int axis0,int axis1) { //optimization 1: check the array index (memory address), instead of the m_pos if (pHandleA->m_maxEdges[axis0] < pHandleB->m_minEdges[axis0] || pHandleB->m_maxEdges[axis0] < pHandleA->m_minEdges[axis0] || pHandleA->m_maxEdges[axis1] < pHandleB->m_minEdges[axis1] || pHandleB->m_maxEdges[axis1] < pHandleA->m_minEdges[axis1]) { return false; } return true; } template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::updateHandle(BP_FP_INT_TYPE handle, const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher) { // btAssert(bounds.IsFinite()); //btAssert(bounds.HasVolume()); Handle* pHandle = getHandle(handle); // quantize the new bounds BP_FP_INT_TYPE min[3], max[3]; quantize(min, aabbMin, 0); quantize(max, aabbMax, 1); // update changed edges for (int axis = 0; axis < 3; axis++) { BP_FP_INT_TYPE emin = pHandle->m_minEdges[axis]; BP_FP_INT_TYPE emax = pHandle->m_maxEdges[axis]; int dmin = (int)min[axis] - (int)m_pEdges[axis][emin].m_pos; int dmax = (int)max[axis] - (int)m_pEdges[axis][emax].m_pos; m_pEdges[axis][emin].m_pos = min[axis]; m_pEdges[axis][emax].m_pos = max[axis]; // expand (only adds overlaps) if (dmin < 0) sortMinDown(axis, emin,dispatcher,true); if (dmax > 0) sortMaxUp(axis, emax,dispatcher,true); // shrink (only removes overlaps) if (dmin > 0) sortMinUp(axis, emin,dispatcher,true); if (dmax < 0) sortMaxDown(axis, emax,dispatcher,true); #ifdef DEBUG_BROADPHASE debugPrintAxis(axis); #endif //DEBUG_BROADPHASE } } // sorting a min edge downwards can only ever *add* overlaps template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMinDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* /* dispatcher */, bool updateOverlaps) { Edge* pEdge = m_pEdges[axis] + edge; Edge* pPrev = pEdge - 1; Handle* pHandleEdge = getHandle(pEdge->m_handle); while (pEdge->m_pos < pPrev->m_pos) { Handle* pHandlePrev = getHandle(pPrev->m_handle); if (pPrev->IsMax()) { // if previous edge is a maximum check the bounds and add an overlap if necessary const int axis1 = (1 << axis) & 3; const int axis2 = (1 << axis1) & 3; if (updateOverlaps && testOverlap2D(pHandleEdge, pHandlePrev,axis1,axis2)) { m_pairCache->addOverlappingPair(pHandleEdge,pHandlePrev); if (m_userPairCallback) m_userPairCallback->addOverlappingPair(pHandleEdge,pHandlePrev); //AddOverlap(pEdge->m_handle, pPrev->m_handle); } // update edge reference in other handle pHandlePrev->m_maxEdges[axis]++; } else pHandlePrev->m_minEdges[axis]++; pHandleEdge->m_minEdges[axis]--; // swap the edges Edge swap = *pEdge; *pEdge = *pPrev; *pPrev = swap; // decrement pEdge--; pPrev--; } #ifdef DEBUG_BROADPHASE debugPrintAxis(axis); #endif //DEBUG_BROADPHASE } // sorting a min edge upwards can only ever *remove* overlaps template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMinUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps) { Edge* pEdge = m_pEdges[axis] + edge; Edge* pNext = pEdge + 1; Handle* pHandleEdge = getHandle(pEdge->m_handle); while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos)) { Handle* pHandleNext = getHandle(pNext->m_handle); if (pNext->IsMax()) { Handle* handle0 = getHandle(pEdge->m_handle); Handle* handle1 = getHandle(pNext->m_handle); const int axis1 = (1 << axis) & 3; const int axis2 = (1 << axis1) & 3; // if next edge is maximum remove any overlap between the two handles if (updateOverlaps #ifdef USE_OVERLAP_TEST_ON_REMOVES && testOverlap2D(handle0,handle1,axis1,axis2) #endif //USE_OVERLAP_TEST_ON_REMOVES ) { m_pairCache->removeOverlappingPair(handle0,handle1,dispatcher); if (m_userPairCallback) m_userPairCallback->removeOverlappingPair(handle0,handle1,dispatcher); } // update edge reference in other handle pHandleNext->m_maxEdges[axis]--; } else pHandleNext->m_minEdges[axis]--; pHandleEdge->m_minEdges[axis]++; // swap the edges Edge swap = *pEdge; *pEdge = *pNext; *pNext = swap; // increment pEdge++; pNext++; } } // sorting a max edge downwards can only ever *remove* overlaps template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMaxDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps) { Edge* pEdge = m_pEdges[axis] + edge; Edge* pPrev = pEdge - 1; Handle* pHandleEdge = getHandle(pEdge->m_handle); while (pEdge->m_pos < pPrev->m_pos) { Handle* pHandlePrev = getHandle(pPrev->m_handle); if (!pPrev->IsMax()) { // if previous edge was a minimum remove any overlap between the two handles Handle* handle0 = getHandle(pEdge->m_handle); Handle* handle1 = getHandle(pPrev->m_handle); const int axis1 = (1 << axis) & 3; const int axis2 = (1 << axis1) & 3; if (updateOverlaps #ifdef USE_OVERLAP_TEST_ON_REMOVES && testOverlap2D(handle0,handle1,axis1,axis2) #endif //USE_OVERLAP_TEST_ON_REMOVES ) { //this is done during the overlappingpairarray iteration/narrowphase collision m_pairCache->removeOverlappingPair(handle0,handle1,dispatcher); if (m_userPairCallback) m_userPairCallback->removeOverlappingPair(handle0,handle1,dispatcher); } // update edge reference in other handle pHandlePrev->m_minEdges[axis]++;; } else pHandlePrev->m_maxEdges[axis]++; pHandleEdge->m_maxEdges[axis]--; // swap the edges Edge swap = *pEdge; *pEdge = *pPrev; *pPrev = swap; // decrement pEdge--; pPrev--; } #ifdef DEBUG_BROADPHASE debugPrintAxis(axis); #endif //DEBUG_BROADPHASE } // sorting a max edge upwards can only ever *add* overlaps template <typename BP_FP_INT_TYPE> void btAxisSweep3Internal<BP_FP_INT_TYPE>::sortMaxUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* /* dispatcher */, bool updateOverlaps) { Edge* pEdge = m_pEdges[axis] + edge; Edge* pNext = pEdge + 1; Handle* pHandleEdge = getHandle(pEdge->m_handle); while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos)) { Handle* pHandleNext = getHandle(pNext->m_handle); const int axis1 = (1 << axis) & 3; const int axis2 = (1 << axis1) & 3; if (!pNext->IsMax()) { // if next edge is a minimum check the bounds and add an overlap if necessary if (updateOverlaps && testOverlap2D(pHandleEdge, pHandleNext,axis1,axis2)) { Handle* handle0 = getHandle(pEdge->m_handle); Handle* handle1 = getHandle(pNext->m_handle); m_pairCache->addOverlappingPair(handle0,handle1); if (m_userPairCallback) m_userPairCallback->addOverlappingPair(handle0,handle1); } // update edge reference in other handle pHandleNext->m_minEdges[axis]--; } else pHandleNext->m_maxEdges[axis]--; pHandleEdge->m_maxEdges[axis]++; // swap the edges Edge swap = *pEdge; *pEdge = *pNext; *pNext = swap; // increment pEdge++; pNext++; } } //////////////////////////////////////////////////////////////////// /// The btAxisSweep3 is an efficient implementation of the 3d axis sweep and prune broadphase. /// It uses arrays rather then lists for storage of the 3 axis. Also it operates using 16 bit integer coordinates instead of floats. /// For large worlds and many objects, use bt32BitAxisSweep3 or btDbvtBroadphase instead. bt32BitAxisSweep3 has higher precision and allows more then 16384 objects at the cost of more memory and bit of performance. class btAxisSweep3 : public btAxisSweep3Internal<unsigned short int> { public: btAxisSweep3(const btVector3& worldAabbMin,const btVector3& worldAabbMax, unsigned short int maxHandles = 16384, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false); }; /// The bt32BitAxisSweep3 allows higher precision quantization and more objects compared to the btAxisSweep3 sweep and prune. /// This comes at the cost of more memory per handle, and a bit slower performance. /// It uses arrays rather then lists for storage of the 3 axis. class bt32BitAxisSweep3 : public btAxisSweep3Internal<unsigned int> { public: bt32BitAxisSweep3(const btVector3& worldAabbMin,const btVector3& worldAabbMax, unsigned int maxHandles = 1500000, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false); }; #endif
0
0.957922
1
0.957922
game-dev
MEDIA
0.943008
game-dev
0.967051
1
0.967051
Stabyourself/mari0
5,880
goomba.lua
goomba = class:new() function goomba:init(x, y, t) --PHYSICS STUFF self.x = x-6/16 self.y = y-11/16 self.speedy = 0 self.speedx = -goombaspeed self.width = 12/16 self.height = 12/16 self.static = false self.active = true self.category = 4 self.mask = { true, false, false, false, false, true, false, true, false, true, false, false, false, true, false, false, true, true, false, false, false, false, true, true, false, false, true, false, true, true, true} self.emancipatecheck = true self.autodelete = true --IMAGE STUFF self.drawable = true self.graphic = goombaimage self.quad = goombaquad[spriteset][1] self.offsetX = 6 self.offsetY = 3 self.quadcenterX = 8 self.quadcenterY = 8 self.rotation = 0 --for portals self.direction = "left" self.animationtimer = 0 self.t = t or "goomba" if self.t == "spikeyair" then self.air = true self.t = "spikey" end if self.t == "goomba" then self.animationdirection = "left" elseif self.t == "spikey" or self.t == "spikeyfall" then self.graphic = spikeyimg self.fall = true if self.t == "spikey" then self.quadi = 1 else self.mask[21] = true self.starty = self.y self.gravity = 30 self.speedy = -10 self.quadi = 3 self.speedx = 0 end self.quad = spikeyquad[self.quadi] end self.falling = false self.dead = false self.deathtimer = 0 self.shot = false end function goomba:update(dt) --rotate back to 0 (portals) if self.t == "spikeyfall" then self.rotation = 0 else self.rotation = math.fmod(self.rotation, math.pi*2) if self.rotation > 0 then self.rotation = self.rotation - portalrotationalignmentspeed*dt if self.rotation < 0 then self.rotation = 0 end elseif self.rotation < 0 then self.rotation = self.rotation + portalrotationalignmentspeed*dt if self.rotation > 0 then self.rotation = 0 end end end if self.dead then self.deathtimer = self.deathtimer + dt if self.deathtimer > goombadeathtime then return true else return false end elseif self.shot then self.speedy = self.speedy + shotgravity*dt self.x = self.x+self.speedx*dt self.y = self.y+self.speedy*dt return false else self.animationtimer = self.animationtimer + dt while self.animationtimer > goombaanimationspeed do self.animationtimer = self.animationtimer - goombaanimationspeed if self.t == "goomba" then if self.animationdirection == "left" then self.animationdirection = "right" else self.animationdirection = "left" end elseif self.t == "spikey" then if self.quadi == 1 then self.quadi = 2 else self.quadi = 1 end self.quad = spikeyquad[self.quadi] elseif self.t == "spikeyfall" then if self.quadi == 3 then self.quadi = 4 else self.quadi = 3 end self.quad = spikeyquad[self.quadi] if self.mask[21] and self.y > self.starty+2 then self.mask[21] = false end end end if self.t ~= "spikeyfall" then if self.speedx > 0 then if self.speedx > goombaspeed then self.speedx = self.speedx - friction*dt*2 if self.speedx < goombaspeed then self.speedx = goombaspeed end elseif self.speedx < goombaspeed then self.speedx = self.speedx + friction*dt*2 if self.speedx > goombaspeed then self.speedx = goombaspeed end end else if self.speedx < -goombaspeed then self.speedx = self.speedx + friction*dt*2 if self.speedx > -goombaspeed then self.speedx = -goombaspeed end elseif self.speedx > -goombaspeed then self.speedx = self.speedx - friction*dt*2 if self.speedx < -goombaspeed then self.speedx = -goombaspeed end end end end --check if goomba offscreen return false end end function goomba:stomp()--hehe goomba stomp self.dead = true self.active = false self.quad = goombaquad[spriteset][2] end function goomba:shotted(dir) --fireball, star, turtle playsound(shotsound) self.shot = true self.speedy = -shotjumpforce self.direction = dir or "right" self.active = false self.gravity = shotgravity if self.direction == "left" then self.speedx = -shotspeedx else self.speedx = shotspeedx end end function goomba:leftcollide(a, b) if self:globalcollide(a, b) then return false end self.speedx = goombaspeed if self.t == "spikey" then self.animationdirection = "left" end return false end function goomba:rightcollide(a, b) if self:globalcollide(a, b) then return false end self.speedx = -goombaspeed if self.t == "spikey" then self.animationdirection = "right" end return false end function goomba:ceilcollide(a, b) if self:globalcollide(a, b) then return false end end function goomba:globalcollide(a, b) if a == "bulletbill" then if b.killstuff ~= false then return true end end if a == "fireball" or a == "player" then return true end if self.t == "spikeyfall" and a == "lakito" then return true end end function goomba:startfall() end function goomba:floorcollide(a, b) if self:globalcollide(a, b) then return false end if self.t == "spikeyfall" then self.t = "spikey" self.fall = false self.quadi = 1 self.quad = spikeyquad[self.quadi] self.gravity = nil local nearestplayer = 1 local nearestplayerx = objects["player"][1].x for i = 2, players do local v = objects["player"][i] if math.abs(self.x - v.x) < nearestplayerx then nearestplayer = i nearestplayerx = v.x end end if self.x >= nearestplayerx then self.speedx = -goombaspeed else self.speedx = goombaspeed self.animationdirection = "left" end end end function goomba:passivecollide(a, b) self:leftcollide(a, b) return false end function goomba:emancipate(a) self:shotted() end function goomba:laser() self:shotted() end
0
0.726896
1
0.726896
game-dev
MEDIA
0.956025
game-dev
0.913286
1
0.913286
ProjectIgnis/CardScripts
2,344
unofficial/c511000803.lua
--Rampaging Binary Stars Level 2 local s,id=GetID() function s.initial_effect(c) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_BATTLE_DESTROYED) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) end function s.condition(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(Card.IsType,1,nil,TYPE_SYNCHRO) and Duel.GetAttacker():IsType(TYPE_SYNCHRO) and Duel.GetAttackTarget():IsType(TYPE_SYNCHRO) end function s.filter(c,e,tp) return c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:GetLevel()==2 end function s.spfilter(c,e,tp,code) return c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:GetLevel()==2 and c:IsCode(code) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function s.operation(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp) local tc=g:GetFirst() if tc then if ft>1 and Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp,tc:GetCode()) then ft=ft-1 Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local spg=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_HAND,0,ft,ft,tc,e,tp,tc:GetCode()) g:Merge(spg) end Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_ATTACK) local tg=g:GetFirst() while tg do tg:RegisterFlagEffect(id,RESET_PHASE|PHASE_END,0,1) tg=g:GetNext() end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetOperation(s.desop) Duel.RegisterEffect(e1,tp) end end function s.desfilter(c) return c:IsLocation(LOCATION_MZONE) and c:IsDestructable() and c:GetFlagEffect(id)~=0 end function s.desop(e,tp,eg,ep,ev,re,r,rp) local sg=Duel.GetMatchingGroup(s.desfilter,tp,LOCATION_MZONE,0,nil) if Duel.Destroy(sg,REASON_EFFECT)~=0 then local sum=sg:GetSum(Card.GetAttack) Duel.Damage(1-tp,sum,REASON_EFFECT) end end
0
0.93479
1
0.93479
game-dev
MEDIA
0.979908
game-dev
0.97682
1
0.97682
MACURD/Hearthbuddy8.7.6
1,038
Routines/DefaultRoutine/Silverfish/cards/0025-龙争虎斗加基森/Sim_CFM_754.cs
using System; using System.Collections.Generic; using System.Text; namespace HREngine.Bots { class Sim_CFM_754 : SimTemplate //* 污手玩具商 Grimy Gadgeteer //At the end of your turn, give a random minion in your hand +2/+2. //在你的回合结束时,随机使你手牌中的一张随从牌获得+2/+2。 { public override void onTurnEndsTrigger(Playfield p, Minion triggerEffectMinion, bool turnEndOfOwner) { if (turnEndOfOwner == triggerEffectMinion.own) { if (triggerEffectMinion.own) { Handmanager.Handcard hc = p.searchRandomMinionInHand(p.owncards, searchmode.searchLowestCost, GAME_TAGs.Mob); if (hc != null) { hc.addattack += 2; hc.addHp += 2; p.anzOwnExtraAngrHp += 4; } } else { if (p.enemyAnzCards > 0) p.anzEnemyExtraAngrHp += 4; } } } } }
0
0.960216
1
0.960216
game-dev
MEDIA
0.969617
game-dev
0.991272
1
0.991272
shedaniel/RoughlyEnoughItems
7,578
runtime/src/main/java/me/shedaniel/rei/impl/client/gui/credits/CreditsEntryListWidget.java
/* * This file is licensed under the MIT License, part of Roughly Enough Items. * Copyright (c) 2018, 2019, 2020, 2021, 2022, 2023 shedaniel * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.shedaniel.rei.impl.client.gui.credits; import me.shedaniel.rei.impl.client.gui.text.TextTransformations; import me.shedaniel.rei.impl.client.gui.widget.UpdatedListWidget; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.narration.NarratableEntry; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvents; import net.minecraft.util.FormattedCharSequence; import org.jetbrains.annotations.ApiStatus; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; @ApiStatus.Internal public class CreditsEntryListWidget extends UpdatedListWidget<CreditsEntryListWidget.CreditsItem> { private boolean inFocus; public CreditsEntryListWidget(Minecraft client, int width, int height, int startY, int endY) { super(client, width, height, startY, endY); } public void creditsClearEntries() { clearItems(); } private CreditsItem rei_getEntry(int index) { return this.children().get(index); } public void creditsAddEntry(CreditsItem entry) { addItem(entry); } @Override public int getItemWidth() { return width - 80; } @Override protected int getScrollbarPosition() { return width - 40; } public static abstract class CreditsItem extends UpdatedListWidget.Entry<CreditsItem> { @Override public List<? extends NarratableEntry> narratables() { return Collections.emptyList(); } @Override public void setFocused(boolean bl) { } @Override public boolean isFocused() { return false; } } public static class TextCreditsItem extends CreditsItem { private Component text; public TextCreditsItem(Component text) { this.text = text; } @Override public void render(GuiGraphics graphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean isSelected, float delta) { graphics.drawString(Minecraft.getInstance().font, text.getVisualOrderText(), x + 5, y + 5, -1); } @Override public int getItemHeight() { return 12; } } public static class TranslationCreditsItem extends CreditsItem { private Component language; private List<FormattedCharSequence> translators; private int maxWidth; public TranslationCreditsItem(Component language, Component translators, int width, int maxWidth) { this.language = language; this.translators = Minecraft.getInstance().font.split(translators, width); this.maxWidth = maxWidth; } @Override public void render(GuiGraphics graphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean isSelected, float delta) { graphics.drawString(Minecraft.getInstance().font, language.getVisualOrderText(), x + 5, y + 5, -1); int yy = y + 5; for (FormattedCharSequence translator : translators) { graphics.drawString(Minecraft.getInstance().font, translator, x + 5 + maxWidth, yy, -1); yy += 12; } } @Override public int getItemHeight() { return 12 * translators.size(); } } public static class LinkItem extends CreditsItem { private Component text; private List<FormattedCharSequence> textSplit; private String link; private boolean contains; private boolean rainbow; public LinkItem(Component text, String link, int width, boolean rainbow) { this.text = text; this.textSplit = Minecraft.getInstance().font.split(text, width); this.link = link; this.rainbow = rainbow; } @Override public void render(GuiGraphics graphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean isSelected, float delta) { contains = mouseX >= x && mouseX <= x + entryWidth && mouseY >= y && mouseY <= y + entryHeight; if (contains) { graphics.renderTooltip(Minecraft.getInstance().font, Component.literal("Click to open link."), mouseX, mouseY); int yy = y; for (FormattedCharSequence textSp : textSplit) { FormattedCharSequence underlined = characterVisitor -> { return textSp.accept((charIndex, style, codePoint) -> characterVisitor.accept(charIndex, style.applyFormat(ChatFormatting.UNDERLINE), codePoint)); }; if (rainbow) underlined = TextTransformations.applyRainbow(underlined, x + 5, yy); graphics.drawString(Minecraft.getInstance().font, underlined, x + 5, yy, 0xff1fc3ff); yy += 12; } } else { int yy = y; for (FormattedCharSequence textSp : textSplit) { if (rainbow) textSp = TextTransformations.applyRainbow(textSp, x + 5, yy); graphics.drawString(Minecraft.getInstance().font, textSp, x + 5, yy, 0xff1fc3ff); yy += 12; } } } @Override public int getItemHeight() { return 12 * textSplit.size(); } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (contains && button == 0) { Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); try { Util.getPlatform().openUri(new URI(link)); return true; } catch (URISyntaxException e) { e.printStackTrace(); } } return false; } } }
0
0.753512
1
0.753512
game-dev
MEDIA
0.872893
game-dev
0.882963
1
0.882963
sudo-owen/chomp
1,106
src/mons/gorillax/Blow.sol
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.0; import "../../Constants.sol"; import "../../Enums.sol"; import {IEngine} from "../../IEngine.sol"; import {IEffect} from "../../effects/IEffect.sol"; import {StandardAttack} from "../../moves/StandardAttack.sol"; import {ATTACK_PARAMS} from "../../moves/StandardAttackStructs.sol"; import {ITypeCalculator} from "../../types/ITypeCalculator.sol"; contract Blow is StandardAttack { constructor(IEngine _ENGINE, ITypeCalculator _TYPE_CALCULATOR) StandardAttack( address(msg.sender), _ENGINE, _TYPE_CALCULATOR, ATTACK_PARAMS({ NAME: "Blow", BASE_POWER: 70, STAMINA_COST: 2, MOVE_TYPE: Type.Air, MOVE_CLASS: MoveClass.Physical, PRIORITY: DEFAULT_PRIORITY, CRIT_RATE: DEFAULT_CRIT_RATE, VOLATILITY: DEFAULT_VOL, ACCURACY: 100, EFFECT_ACCURACY: 0, EFFECT: IEffect(address(0)) }) ) {} }
0
0.767653
1
0.767653
game-dev
MEDIA
0.163964
game-dev
0.742106
1
0.742106
DanceManiac/Advanced-X-Ray-Public
1,923
SourcesAXR/xrGameCS/group_hierarchy_holder_inline.h
//////////////////////////////////////////////////////////////////////////// // Module : group_hierarchy_holder_inline.h // Created : 12.11.2001 // Modified : 03.09.2004 // Author : Dmitriy Iassenev, Oles Shishkovtsov, Aleksandr Maksimchuk // Description : Group hierarchy holder inline functions //////////////////////////////////////////////////////////////////////////// #pragma once IC CGroupHierarchyHolder::CGroupHierarchyHolder (CSquadHierarchyHolder *squad) { VERIFY (squad); m_squad = squad; #ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER m_leader = 0; #endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER m_visible_objects = 0; m_sound_objects = 0; m_hit_objects = 0; m_agent_manager = 0; m_dwLastActionTime = 0; m_dwLastAction = 0; m_dwActiveCount = 0; m_dwAliveCount = 0; m_dwStandingCount = 0; } IC CAgentManager &CGroupHierarchyHolder::agent_manager () const { VERIFY (m_agent_manager); return (*m_agent_manager); } IC CAgentManager *CGroupHierarchyHolder::get_agent_manager () const { return (m_agent_manager); } IC const GroupHierarchyHolder::MEMBER_REGISTRY &CGroupHierarchyHolder::members () const { return (m_members); } IC CSquadHierarchyHolder &CGroupHierarchyHolder::squad () const { VERIFY (m_squad); return (*m_squad); } #ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER IC CEntity *CGroupHierarchyHolder::leader () const { return (m_leader); } #endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER IC GroupHierarchyHolder::VISIBLE_OBJECTS &CGroupHierarchyHolder::visible_objects () const { VERIFY (m_visible_objects); return (*m_visible_objects); } IC GroupHierarchyHolder::SOUND_OBJECTS &CGroupHierarchyHolder::sound_objects () const { VERIFY (m_sound_objects); return (*m_sound_objects); } IC GroupHierarchyHolder::HIT_OBJECTS &CGroupHierarchyHolder::hit_objects () const { VERIFY (m_hit_objects); return (*m_hit_objects); }
0
0.78857
1
0.78857
game-dev
MEDIA
0.927538
game-dev
0.547706
1
0.547706
TeamPneumatic/pnc-repressurized
3,274
src/main/java/me/desht/pneumaticcraft/common/block/GasLiftBlock.java
/* * This file is part of pnc-repressurized. * * pnc-repressurized 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. * * pnc-repressurized 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 pnc-repressurized. If not, see <https://www.gnu.org/licenses/>. */ package me.desht.pneumaticcraft.common.block; import me.desht.pneumaticcraft.common.block.entity.utility.GasLiftBlockEntity; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import java.util.stream.Stream; public class GasLiftBlock extends AbstractPneumaticCraftBlock implements PneumaticCraftEntityBlock { private static final VoxelShape SHAPE = Stream.of( Block.box(0, 0, 0, 16, 2, 16), Block.box(0, 4, 0, 5, 14, 5), Block.box(0, 4, 11, 5, 14, 16), Block.box(11, 4, 11, 16, 14, 16), Block.box(11, 4, 0, 16, 14, 5), Block.box(2, 14, 2, 14, 15, 14), Block.box(2, 2, 2, 14, 4, 14), Block.box(11, 4, 5, 16, 14, 11), Block.box(0, 4, 5, 5, 14, 11), Block.box(5, 4, 0, 11, 14, 16), Block.box(0, 14, 0, 16, 16, 2), Block.box(0, 14, 14, 16, 16, 16), Block.box(0, 14, 2, 2, 16, 14), Block.box(14, 14, 2, 16, 16, 14) ).reduce((v1, v2) -> Shapes.join(v1, v2, BooleanOp.OR)).get(); public GasLiftBlock(Properties props) { super(props); registerDefaultState(defaultBlockState() .setValue(UP, false) .setValue(NORTH, false) .setValue(SOUTH, false) .setValue(WEST, false) .setValue(EAST, false) ); } @Override protected boolean isWaterloggable() { return true; } @Override public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext selectionContext) { return SHAPE; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { super.createBlockStateDefinition(builder); builder.add(UP, NORTH, SOUTH, WEST, EAST); } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) { return new GasLiftBlockEntity(pPos, pState); } }
0
0.737654
1
0.737654
game-dev
MEDIA
0.99271
game-dev
0.739787
1
0.739787
jswigart/omni-bot
27,752
GameInterfaces/D3/src/game/Game_local.h
// Copyright (C) 2004 Id Software, Inc. // #ifndef __GAME_LOCAL_H__ #define __GAME_LOCAL_H__ /* =============================================================================== Local implementation of the public game interface. =============================================================================== */ #define LAGO_IMG_WIDTH 64 #define LAGO_IMG_HEIGHT 64 #define LAGO_WIDTH 64 #define LAGO_HEIGHT 44 #define LAGO_MATERIAL "textures/sfx/lagometer" #define LAGO_IMAGE "textures/sfx/lagometer.tga" // if set to 1 the server sends the client PVS with snapshots and the client compares against what it sees #ifndef ASYNC_WRITE_PVS #define ASYNC_WRITE_PVS 0 #endif #ifdef ID_DEBUG_UNINITIALIZED_MEMORY // This is real evil but allows the code to inspect arbitrary class variables. #define private public #define protected public #endif extern idRenderWorld * gameRenderWorld; extern idSoundWorld * gameSoundWorld; // the "gameversion" client command will print this plus compile date // Omni-bot - Changed version #define GAME_VERSION "Omni-bot 0.65 beta" // classes used by idGameLocal class idEntity; class idActor; class idPlayer; class idCamera; class idWorldspawn; class idTestModel; class idAAS; class idAI; class idSmokeParticles; class idEntityFx; class idTypeInfo; class idProgram; class idThread; class idEditEntities; class idLocationEntity; #define MAX_CLIENTS 32 #define GENTITYNUM_BITS 12 #define MAX_GENTITIES (1<<GENTITYNUM_BITS) #define ENTITYNUM_NONE (MAX_GENTITIES-1) #define ENTITYNUM_WORLD (MAX_GENTITIES-2) #define ENTITYNUM_MAX_NORMAL (MAX_GENTITIES-2) //============================================================================ int checkFreeSlot(bool isBot, int num); //============================================================================ void gameError( const char *fmt, ... ); #include "gamesys/Event.h" #include "gamesys/Class.h" #include "gamesys/SysCvar.h" #include "gamesys/SysCmds.h" #include "gamesys/SaveGame.h" #include "gamesys/DebugGraph.h" #include "script/Script_Program.h" #include "anim/Anim.h" #include "ai/AAS.h" #include "physics/Clip.h" #include "physics/Push.h" #include "Pvs.h" #include "MultiplayerGame.h" //============================================================================ const int MAX_GAME_MESSAGE_SIZE = 8192; const int MAX_ENTITY_STATE_SIZE = 512; const int ENTITY_PVS_SIZE = ((MAX_GENTITIES+31)>>5); const int NUM_RENDER_PORTAL_BITS = idMath::BitsForInteger( PS_BLOCK_ALL ); typedef struct entityState_s { int entityNumber; idBitMsg state; byte stateBuf[MAX_ENTITY_STATE_SIZE]; struct entityState_s * next; } entityState_t; typedef struct snapshot_s { int sequence; entityState_t * firstEntityState; int pvs[ENTITY_PVS_SIZE]; struct snapshot_s * next; } snapshot_t; const int MAX_EVENT_PARAM_SIZE = 128; typedef struct entityNetEvent_s { int spawnId; int event; int time; int paramsSize; byte paramsBuf[MAX_EVENT_PARAM_SIZE]; struct entityNetEvent_s *next; struct entityNetEvent_s *prev; } entityNetEvent_t; enum { GAME_RELIABLE_MESSAGE_INIT_DECL_REMAP, GAME_RELIABLE_MESSAGE_REMAP_DECL, GAME_RELIABLE_MESSAGE_SPAWN_PLAYER, GAME_RELIABLE_MESSAGE_DELETE_ENT, GAME_RELIABLE_MESSAGE_CHAT, GAME_RELIABLE_MESSAGE_TCHAT, GAME_RELIABLE_MESSAGE_SOUND_EVENT, GAME_RELIABLE_MESSAGE_SOUND_INDEX, GAME_RELIABLE_MESSAGE_DB, GAME_RELIABLE_MESSAGE_KILL, GAME_RELIABLE_MESSAGE_DROPWEAPON, GAME_RELIABLE_MESSAGE_RESTART, GAME_RELIABLE_MESSAGE_SERVERINFO, GAME_RELIABLE_MESSAGE_TOURNEYLINE, GAME_RELIABLE_MESSAGE_CALLVOTE, GAME_RELIABLE_MESSAGE_CASTVOTE, GAME_RELIABLE_MESSAGE_STARTVOTE, GAME_RELIABLE_MESSAGE_UPDATEVOTE, GAME_RELIABLE_MESSAGE_PORTALSTATES, GAME_RELIABLE_MESSAGE_PORTAL, GAME_RELIABLE_MESSAGE_VCHAT, GAME_RELIABLE_MESSAGE_STARTSTATE, GAME_RELIABLE_MESSAGE_MENU, GAME_RELIABLE_MESSAGE_WARMUPTIME, GAME_RELIABLE_MESSAGE_EVENT }; typedef enum { GAMESTATE_UNINITIALIZED, // prior to Init being called GAMESTATE_NOMAP, // no map loaded GAMESTATE_STARTUP, // inside InitFromNewMap(). spawning map entities. GAMESTATE_ACTIVE, // normal gameplay GAMESTATE_SHUTDOWN // inside MapShutdown(). clearing memory. } gameState_t; typedef struct { idEntity *ent; int dist; } spawnSpot_t; //============================================================================ class idEventQueue { public: typedef enum { OUTOFORDER_IGNORE, OUTOFORDER_DROP, OUTOFORDER_SORT } outOfOrderBehaviour_t; idEventQueue() : start( NULL ), end( NULL ) {} entityNetEvent_t * Alloc(); void Free( entityNetEvent_t *event ); void Shutdown(); void Init(); void Enqueue( entityNetEvent_t* event, outOfOrderBehaviour_t oooBehaviour ); entityNetEvent_t * Dequeue( void ); entityNetEvent_t * RemoveLast( void ); entityNetEvent_t * Start( void ) { return start; } private: entityNetEvent_t * start; entityNetEvent_t * end; idBlockAlloc<entityNetEvent_t,32> eventAllocator; }; //============================================================================ template< class type > class idEntityPtr { public: idEntityPtr(); // save games void Save( idSaveGame *savefile ) const; // archives object for save game file void Restore( idRestoreGame *savefile ); // unarchives object from save game file idEntityPtr<type> & operator=( type *ent ); // synchronize entity pointers over the network int GetSpawnId( void ) const { return spawnId; } bool SetSpawnId( int id ); bool UpdateSpawnId( void ); bool IsValid( void ) const; type * GetEntity( void ) const; int GetEntityNum( void ) const; private: int spawnId; }; //============================================================================ class idGameLocal : public idGame { public: idDict serverInfo; // all the tunable parameters, like numclients, etc int numClients; // pulled from serverInfo and verified idDict userInfo[MAX_CLIENTS]; // client specific settings usercmd_t usercmds[MAX_CLIENTS]; // client input commands idDict persistentPlayerInfo[MAX_CLIENTS]; idEntity * entities[MAX_GENTITIES];// index to entities int spawnIds[MAX_GENTITIES];// for use in idEntityPtr int firstFreeIndex; // first free index in the entities array int num_entities; // current number <= MAX_GENTITIES idHashIndex entityHash; // hash table to quickly find entities by name idWorldspawn * world; // world entity idLinkList<idEntity> spawnedEntities; // all spawned entities idLinkList<idEntity> activeEntities; // all thinking entities (idEntity::thinkFlags != 0) int numEntitiesToDeactivate;// number of entities that became inactive in current frame bool sortPushers; // true if active lists needs to be reordered to place pushers at the front bool sortTeamMasters; // true if active lists needs to be reordered to place physics team masters before their slaves idDict persistentLevelInfo; // contains args that are kept around between levels // can be used to automatically effect every material in the world that references globalParms float globalShaderParms[ MAX_GLOBAL_SHADER_PARMS ]; idRandom random; // random number generator used throughout the game idProgram program; // currently loaded script and data space idThread * frameCommandThread; idClip clip; // collision detection idPush push; // geometric pushing idPVS pvs; // potential visible set idTestModel * testmodel; // for development testing of models idEntityFx * testFx; // for development testing of fx idStr sessionCommand; // a target_sessionCommand can set this to return something to the session idMultiplayerGame mpGame; // handles rules for standard dm idSmokeParticles * smokeParticles; // global smoke trails idEditEntities * editEntities; // in game editing int cinematicSkipTime; // don't allow skipping cinemetics until this time has passed so player doesn't skip out accidently from a firefight int cinematicStopTime; // cinematics have several camera changes, so keep track of when we stop them so that we don't reset cinematicSkipTime unnecessarily int cinematicMaxSkipTime; // time to end cinematic when skipping. there's a possibility of an infinite loop if the map isn't set up right. bool inCinematic; // game is playing cinematic (player controls frozen) bool skipCinematic; // are kept up to date with changes to serverInfo int framenum; int previousTime; // time in msec of last frame int time; // in msec static const int msec = USERCMD_MSEC; // time since last update in milliseconds int vacuumAreaNum; // -1 if level doesn't have any outside areas gameType_t gameType; bool isMultiplayer; // set if the game is run in multiplayer mode bool isServer; // set if the game is run for a dedicated or listen server bool isClient; // set if the game is run for a client // discriminates between the RunFrame path and the ClientPrediction path // NOTE: on a listen server, isClient is false int localClientNum; // number of the local client. MP: -1 on a dedicated idLinkList<idEntity> snapshotEntities; // entities from the last snapshot int realClientTime; // real client time bool isNewFrame; // true if this is a new game frame, not a rerun due to prediction float clientSmoothing; // smoothing of other clients in the view int entityDefBits; // bits required to store an entity def number static const char * sufaceTypeNames[ MAX_SURFACE_TYPES ]; // text names for surface types idEntityPtr<idEntity> lastGUIEnt; // last entity with a GUI, used by Cmd_NextGUI_f int lastGUI; // last GUI on the lastGUIEnt // ---------------------- Public idGame Interface ------------------- idGameLocal(); virtual void Init( void ); virtual void Shutdown( void ); virtual void SetLocalClient( int clientNum ); virtual void ThrottleUserInfo( void ); virtual const idDict * SetUserInfo( int clientNum, const idDict &userInfo, bool isClient, bool canModify ); virtual const idDict * GetUserInfo( int clientNum ); virtual void SetServerInfo( const idDict &serverInfo ); virtual const idDict & GetPersistentPlayerInfo( int clientNum ); virtual void SetPersistentPlayerInfo( int clientNum, const idDict &playerInfo ); virtual void InitFromNewMap( const char *mapName, idRenderWorld *renderWorld, idSoundWorld *soundWorld, bool isServer, bool isClient, int randSeed ); virtual bool InitFromSaveGame( const char *mapName, idRenderWorld *renderWorld, idSoundWorld *soundWorld, idFile *saveGameFile ); virtual void SaveGame( idFile *saveGameFile ); virtual void MapShutdown( void ); virtual void CacheDictionaryMedia( const idDict *dict ); virtual void SpawnPlayer( int clientNum ); virtual gameReturn_t RunFrame( const usercmd_t *clientCmds ); virtual bool Draw( int clientNum ); virtual escReply_t HandleESC( idUserInterface **gui ); virtual idUserInterface *StartMenu( void ); virtual const char * HandleGuiCommands( const char *menuCommand ); virtual void HandleMainMenuCommands( const char *menuCommand, idUserInterface *gui ); virtual allowReply_t ServerAllowClient( int numClients, const char *IP, const char *guid, const char *password, char reason[MAX_STRING_CHARS] ); virtual void ServerClientConnect( int clientNum, const char *guid ); virtual void ServerClientBegin( int clientNum ); virtual void ServerClientDisconnect( int clientNum ); virtual void ServerWriteInitialReliableMessages( int clientNum ); virtual void ServerWriteSnapshot( int clientNum, int sequence, idBitMsg &msg, byte *clientInPVS, int numPVSClients ); virtual bool ServerApplySnapshot( int clientNum, int sequence ); virtual void ServerProcessReliableMessage( int clientNum, const idBitMsg &msg ); virtual void ClientReadSnapshot( int clientNum, int sequence, const int gameFrame, const int gameTime, const int dupeUsercmds, const int aheadOfServer, const idBitMsg &msg ); virtual bool ClientApplySnapshot( int clientNum, int sequence ); virtual void ClientProcessReliableMessage( int clientNum, const idBitMsg &msg ); virtual gameReturn_t ClientPrediction( int clientNum, const usercmd_t *clientCmds, bool lastPredictFrame ); virtual void GetClientStats( int clientNum, char *data, const int len ); virtual void SwitchTeam( int clientNum, int team ); virtual bool DownloadRequest( const char *IP, const char *guid, const char *paks, char urls[ MAX_STRING_CHARS ] ); // Omni-bot - Added GetPlayerName and GetBotInput virtual void GetPlayerName( int clientNum, char* name ); // ---------------------- Public idGameLocal Interface ------------------- void Printf( const char *fmt, ... ) const id_attribute((format(printf,2,3))); void DPrintf( const char *fmt, ... ) const id_attribute((format(printf,2,3))); void Warning( const char *fmt, ... ) const id_attribute((format(printf,2,3))); void DWarning( const char *fmt, ... ) const id_attribute((format(printf,2,3))); void Error( const char *fmt, ... ) const id_attribute((format(printf,2,3))); // Initializes all map variables common to both save games and spawned games void LoadMap( const char *mapName, int randseed ); void LocalMapRestart( void ); void MapRestart( void ); static void MapRestart_f( const idCmdArgs &args ); bool NextMap( void ); // returns wether serverinfo settings have been modified static void NextMap_f( const idCmdArgs &args ); idMapFile * GetLevelMap( void ); const char * GetMapName( void ) const; int NumAAS( void ) const; idAAS * GetAAS( int num ) const; idAAS * GetAAS( const char *name ) const; void SetAASAreaState( const idBounds &bounds, const int areaContents, bool closed ); aasHandle_t AddAASObstacle( const idBounds &bounds ); void RemoveAASObstacle( const aasHandle_t handle ); void RemoveAllAASObstacles( void ); bool CheatsOk( bool requirePlayer = true ); void SetSkill( int value ); gameState_t GameState( void ) const; idEntity * SpawnEntityType( const idTypeInfo &classdef, const idDict *args = NULL, bool bIsClientReadSnapshot = false ); bool SpawnEntityDef( const idDict &args, idEntity **ent = NULL, bool setDefaults = true ); int GetSpawnId( const idEntity *ent ) const; const idDeclEntityDef * FindEntityDef( const char *name, bool makeDefault = true ) const; const idDict * FindEntityDefDict( const char *name, bool makeDefault = true ) const; void RegisterEntity( idEntity *ent ); void UnregisterEntity( idEntity *ent ); bool RequirementMet( idEntity *activator, const idStr &requires, int removeItem ); void AlertAI( idEntity *ent ); idActor * GetAlertEntity( void ); bool InPlayerPVS( idEntity *ent ) const; bool InPlayerConnectedArea( idEntity *ent ) const; void SetCamera( idCamera *cam ); idCamera * GetCamera( void ) const; bool SkipCinematic( void ); void CalcFov( float base_fov, float &fov_x, float &fov_y ) const; void AddEntityToHash( const char *name, idEntity *ent ); bool RemoveEntityFromHash( const char *name, idEntity *ent ); int GetTargets( const idDict &args, idList< idEntityPtr<idEntity> > &list, const char *ref ) const; // returns the master entity of a trace. for example, if the trace entity is the player's head, it will return the player. idEntity * GetTraceEntity( const trace_t &trace ) const; static void ArgCompletion_EntityName( const idCmdArgs &args, void(*callback)( const char *s ) ); idEntity * FindTraceEntity( idVec3 start, idVec3 end, const idTypeInfo &c, const idEntity *skip ) const; idEntity * FindEntity( const char *name ) const; // Omni-bot - Added FindEntity idEntity * FindEntity( int entityNumber ) { return ((entityNumber >= 0 && entityNumber < MAX_GENTITIES) ? entities[entityNumber] : NULL); } idEntity * FindEntityUsingDef( idEntity *from, const char *match ) const; int EntitiesWithinRadius( const idVec3 org, float radius, idEntity **entityList, int maxCount ) const; void KillBox( idEntity *ent, bool catch_teleport = false ); void RadiusDamage( const idVec3 &origin, idEntity *inflictor, idEntity *attacker, idEntity *ignoreDamage, idEntity *ignorePush, const char *damageDefName, float dmgPower = 1.0f ); void RadiusPush( const idVec3 &origin, const float radius, const float push, const idEntity *inflictor, const idEntity *ignore, float inflictorScale, const bool quake ); void RadiusPushClipModel( const idVec3 &origin, const float push, const idClipModel *clipModel ); void ProjectDecal( const idVec3 &origin, const idVec3 &dir, float depth, bool parallel, float size, const char *material, float angle = 0 ); void BloodSplat( const idVec3 &origin, const idVec3 &dir, float size, const char *material ); void CallFrameCommand( idEntity *ent, const function_t *frameCommand ); void CallObjectFrameCommand( idEntity *ent, const char *frameCommand ); const idVec3 & GetGravity( void ) const; // added the following to assist licensees with merge issues int GetFrameNum() const { return framenum; }; int GetTime() const { return time; }; int GetMSec() const { return msec; }; int GetNextClientNum( int current ) const; idPlayer * GetClientByNum( int current ) const; idPlayer * GetClientByName( const char *name ) const; idPlayer * GetClientByCmdArgs( const idCmdArgs &args ) const; idPlayer * GetLocalPlayer() const; void SpreadLocations(); idLocationEntity * LocationForPoint( const idVec3 &point ); // May return NULL idEntity * SelectInitialSpawnPoint( idPlayer *player ); void SetPortalState( qhandle_t portal, int blockingBits ); void SaveEntityNetworkEvent( const idEntity *ent, int event, const idBitMsg *msg ); void ServerSendChatMessage( int to, const char *name, const char *text ); int ServerRemapDecl( int clientNum, declType_t type, int index ); int ClientRemapDecl( declType_t type, int index ); void SetGlobalMaterial( const idMaterial *mat ); const idMaterial * GetGlobalMaterial(); void SetGibTime( int _time ) { nextGibTime = _time; }; int GetGibTime() { return nextGibTime; }; bool NeedRestart(); // Omni-bot - Added IsTeamGame bool IsTeamGame ( void ) const; private: const static int INITIAL_SPAWN_COUNT = 1; idStr mapFileName; // name of the map, empty string if no map loaded idMapFile * mapFile; // will be NULL during the game unless in-game editing is used bool mapCycleLoaded; int spawnCount; int mapSpawnCount; // it's handy to know which entities are part of the map idLocationEntity ** locationEntities; // for location names, etc idCamera * camera; const idMaterial * globalMaterial; // for overriding everything idList<idAAS *> aasList; // area system idStrList aasNames; idEntityPtr<idActor> lastAIAlertEntity; int lastAIAlertTime; idDict spawnArgs; // spawn args used during entity spawning FIXME: shouldn't be necessary anymore pvsHandle_t playerPVS; // merged pvs of all players pvsHandle_t playerConnectedAreas; // all areas connected to any player area idVec3 gravity; // global gravity vector gameState_t gamestate; // keeps track of whether we're spawning, shutting down, or normal gameplay bool influenceActive; // true when a phantasm is happening int nextGibTime; idList<int> clientDeclRemap[MAX_CLIENTS][DECL_MAX_TYPES]; entityState_t * clientEntityStates[MAX_CLIENTS][MAX_GENTITIES]; int clientPVS[MAX_CLIENTS][ENTITY_PVS_SIZE]; snapshot_t * clientSnapshots[MAX_CLIENTS]; idBlockAlloc<entityState_t,256>entityStateAllocator; idBlockAlloc<snapshot_t,64>snapshotAllocator; idEventQueue eventQueue; idEventQueue savedEventQueue; idStaticList<spawnSpot_t, MAX_GENTITIES> spawnSpots; idStaticList<idEntity *, MAX_GENTITIES> initialSpots; int currentInitialSpot; idDict newInfo; idStrList shakeSounds; byte lagometer[ LAGO_IMG_HEIGHT ][ LAGO_IMG_WIDTH ][ 4 ]; void Clear( void ); // returns true if the entity shouldn't be spawned at all in this game type or difficulty level bool InhibitEntitySpawn( idDict &spawnArgs ); // spawn entities from the map file void SpawnMapEntities( void ); // commons used by init, shutdown, and restart void MapPopulate( void ); void MapClear( bool clearClients ); pvsHandle_t GetClientPVS( idPlayer *player, pvsType_t type ); void SetupPlayerPVS( void ); void FreePlayerPVS( void ); void UpdateGravity( void ); void SortActiveEntityList( void ); void ShowTargets( void ); void RunDebugInfo( void ); void InitScriptForMap( void ); void InitConsoleCommands( void ); void ShutdownConsoleCommands( void ); void InitAsyncNetwork( void ); void ShutdownAsyncNetwork( void ); void InitLocalClient( int clientNum ); void InitClientDeclRemap( int clientNum ); void ServerSendDeclRemapToClient( int clientNum, declType_t type, int index ); void FreeSnapshotsOlderThanSequence( int clientNum, int sequence ); bool ApplySnapshot( int clientNum, int sequence ); void WriteGameStateToSnapshot( idBitMsgDelta &msg ) const; void ReadGameStateFromSnapshot( const idBitMsgDelta &msg ); void NetworkEventWarning( const entityNetEvent_t *event, const char *fmt, ... ) id_attribute((format(printf,3,4))); void ServerProcessEntityNetworkEventQueue( void ); void ClientProcessEntityNetworkEventQueue( void ); void ClientShowSnapshot( int clientNum ) const; // call after any change to serverInfo. Will update various quick-access flags void UpdateServerInfoFlags( void ); void RandomizeInitialSpawns( void ); static int sortSpawnPoints( const void *ptr1, const void *ptr2 ); void DumpOggSounds( void ); void GetShakeSounds( const idDict *dict ); void SelectTimeGroup( int timeGroup ); int GetTimeGroupTime( int timeGroup ); void GetBestGameType( const char* map, const char* gametype, char buf[ MAX_STRING_CHARS ] ); void Tokenize( idStrList &out, const char *in ); void UpdateLagometer( int aheadOfServer, int dupeUsercmds ); void GetMapLoadingGUI( char gui[ MAX_STRING_CHARS ] ); }; //============================================================================ extern idGameLocal gameLocal; extern idAnimManager animationLib; //============================================================================ template< class type > ID_INLINE idEntityPtr<type>::idEntityPtr() { spawnId = 0; } template< class type > ID_INLINE void idEntityPtr<type>::Save( idSaveGame *savefile ) const { savefile->WriteInt( spawnId ); } template< class type > ID_INLINE void idEntityPtr<type>::Restore( idRestoreGame *savefile ) { savefile->ReadInt( spawnId ); } template< class type > ID_INLINE idEntityPtr<type> &idEntityPtr<type>::operator=( type *ent ) { if ( ent == NULL ) { spawnId = 0; } else { spawnId = ( gameLocal.spawnIds[ent->entityNumber] << GENTITYNUM_BITS ) | ent->entityNumber; } return *this; } template< class type > ID_INLINE bool idEntityPtr<type>::SetSpawnId( int id ) { // the reason for this first check is unclear: // the function returning false may mean the spawnId is already set right, or the entity is missing if ( id == spawnId ) { return false; } if ( ( id >> GENTITYNUM_BITS ) == gameLocal.spawnIds[ id & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] ) { spawnId = id; return true; } return false; } template< class type > ID_INLINE bool idEntityPtr<type>::IsValid( void ) const { return ( gameLocal.spawnIds[ spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] == ( spawnId >> GENTITYNUM_BITS ) ); } template< class type > ID_INLINE type *idEntityPtr<type>::GetEntity( void ) const { int entityNum = spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ); if ( ( gameLocal.spawnIds[ entityNum ] == ( spawnId >> GENTITYNUM_BITS ) ) ) { return static_cast<type *>( gameLocal.entities[ entityNum ] ); } return NULL; } template< class type > ID_INLINE int idEntityPtr<type>::GetEntityNum( void ) const { return ( spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ); } //============================================================================ class idGameError : public idException { public: idGameError( const char *text ) : idException( text ) {} }; //============================================================================ // // these defines work for all startsounds from all entity types // make sure to change script/doom_defs.script if you add any channels, or change their order // typedef enum { SND_CHANNEL_ANY = SCHANNEL_ANY, SND_CHANNEL_VOICE = SCHANNEL_ONE, SND_CHANNEL_VOICE2, SND_CHANNEL_BODY, SND_CHANNEL_BODY2, SND_CHANNEL_BODY3, SND_CHANNEL_WEAPON, SND_CHANNEL_ITEM, SND_CHANNEL_HEART, SND_CHANNEL_PDA, SND_CHANNEL_DEMONIC, SND_CHANNEL_RADIO, // internal use only. not exposed to script or framecommands. SND_CHANNEL_AMBIENT, SND_CHANNEL_DAMAGE } gameSoundChannel_t; // content masks #define MASK_ALL (-1) #define MASK_SOLID (CONTENTS_SOLID) #define MASK_MONSTERSOLID (CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BODY) #define MASK_PLAYERSOLID (CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY) #define MASK_DEADSOLID (CONTENTS_SOLID|CONTENTS_PLAYERCLIP) #define MASK_WATER (CONTENTS_WATER) #define MASK_OPAQUE (CONTENTS_OPAQUE) #define MASK_SHOT_RENDERMODEL (CONTENTS_SOLID|CONTENTS_RENDERMODEL) #define MASK_SHOT_BOUNDINGBOX (CONTENTS_SOLID|CONTENTS_BODY) const float DEFAULT_GRAVITY = 1066.0f; #define DEFAULT_GRAVITY_STRING "1066" const idVec3 DEFAULT_GRAVITY_VEC3( 0, 0, -DEFAULT_GRAVITY ); const int CINEMATIC_SKIP_DELAY = SEC2MS( 2.0f ); //============================================================================ #include "physics/Force.h" #include "physics/Force_Constant.h" #include "physics/Force_Drag.h" #include "physics/Force_Field.h" #include "physics/Force_Spring.h" #include "physics/Physics.h" #include "physics/Physics_Static.h" #include "physics/Physics_StaticMulti.h" #include "physics/Physics_Base.h" #include "physics/Physics_Actor.h" #include "physics/Physics_Monster.h" #include "physics/Physics_Player.h" #include "physics/Physics_Parametric.h" #include "physics/Physics_RigidBody.h" #include "physics/Physics_AF.h" #include "SmokeParticles.h" #include "Entity.h" #include "GameEdit.h" #include "AF.h" #include "IK.h" #include "AFEntity.h" #include "Misc.h" #include "Actor.h" #include "Projectile.h" #include "Weapon.h" #include "Light.h" #include "WorldSpawn.h" #include "Item.h" #include "PlayerView.h" #include "PlayerIcon.h" #include "Player.h" #include "Mover.h" #include "Camera.h" #include "Moveable.h" #include "Target.h" #include "Trigger.h" #include "Sound.h" #include "Fx.h" #include "SecurityCamera.h" #include "BrittleFracture.h" #include "ai/AI.h" #include "anim/Anim_Testmodel.h" #include "script/Script_Compiler.h" #include "script/Script_Interpreter.h" #include "script/Script_Thread.h" // Omni-bot - Added omnibot include #include "omnibot/omnibot_interface.h" // Omni-bot - Added IsTeamGame ID_INLINE bool idGameLocal::IsTeamGame( void ) const { return ( isMultiplayer && ( gameType == GAME_TDM ) ); } #endif /* !__GAME_LOCAL_H__ */
0
0.78345
1
0.78345
game-dev
MEDIA
0.924125
game-dev
0.68511
1
0.68511
openpilot/OpenPilot
3,066
ground/openpilotgcs/src/plugins/uavobjects/uavobjectmanager.h
/** ****************************************************************************** * * @file uavobjectmanager.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @see The GNU Public License (GPL) Version 3 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVObjectsPlugin UAVObjects Plugin * @{ * @brief The UAVUObjects GCS plugin *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef UAVOBJECTMANAGER_H #define UAVOBJECTMANAGER_H #include "uavobjects_global.h" #include "uavobject.h" #include "uavdataobject.h" #include "uavmetaobject.h" #include <QList> #include <QMutex> #include <QMutexLocker> #include <QJsonObject> class UAVOBJECTS_EXPORT UAVObjectManager : public QObject { Q_OBJECT public: enum JSON_EXPORT_OPTION { JSON_EXPORT_ALL, JSON_EXPORT_METADATA, JSON_EXPORT_SETTINGS, JSON_EXPORT_DATA }; UAVObjectManager(); ~UAVObjectManager(); bool registerObject(UAVDataObject *obj); QList< QList<UAVObject *> > getObjects(); QList< QList<UAVDataObject *> > getDataObjects(); QList< QList<UAVMetaObject *> > getMetaObjects(); UAVObject *getObject(const QString & name, quint32 instId = 0); UAVObject *getObject(quint32 objId, quint32 instId = 0); QList<UAVObject *> getObjectInstances(const QString & name); QList<UAVObject *> getObjectInstances(quint32 objId); qint32 getNumInstances(const QString & name); qint32 getNumInstances(quint32 objId); void toJson(QJsonObject &jsonObject, JSON_EXPORT_OPTION what = JSON_EXPORT_ALL); void toJson(QJsonObject &jsonObject, const QList<QString> &objectsToExport); void toJson(QJsonObject &jsonObject, const QList<UAVObject *> &objectsToExport); void fromJson(const QJsonObject &jsonObject, QList<UAVObject *> *updatedObjects = NULL); signals: void newObject(UAVObject *obj); void newInstance(UAVObject *obj); private: static const quint32 MAX_INSTANCES = 1000; QList< QList<UAVObject *> > objects; QMutex *mutex; void addObject(UAVObject *obj); UAVObject *getObject(const QString *name, quint32 objId, quint32 instId); QList<UAVObject *> getObjectInstances(const QString *name, quint32 objId); qint32 getNumInstances(const QString *name, quint32 objId); }; #endif // UAVOBJECTMANAGER_H
0
0.822125
1
0.822125
game-dev
MEDIA
0.186482
game-dev
0.597702
1
0.597702
ModificationStation/StationAPI
3,003
station-registry-api-v0/src/main/java/net/modificationstation/stationapi/api/registry/sync/trackers/BooleanArrayTracker.java
package net.modificationstation.stationapi.api.registry.sync.trackers; import it.unimi.dsi.fastutil.ints.Int2IntMap; import net.mine_diver.unsafeevents.listener.EventListener; import net.mine_diver.unsafeevents.listener.Listener; import net.modificationstation.stationapi.api.StationAPI; import net.modificationstation.stationapi.api.event.registry.RegistryEntryAddedEvent; import net.modificationstation.stationapi.api.event.registry.RegistryIdRemapEvent; import net.modificationstation.stationapi.api.mod.entrypoint.EntrypointManager; import net.modificationstation.stationapi.api.registry.ListenableRegistry; import net.modificationstation.stationapi.api.registry.Registry; import net.modificationstation.stationapi.api.util.math.MathHelper; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.function.Consumer; import java.util.function.Supplier; @EventListener(phase = StationAPI.INTERNAL_PHASE) public class BooleanArrayTracker<T> { static { EntrypointManager.registerLookup(MethodHandles.lookup()); } private final Supplier<boolean[]> arrayGetter; private final Consumer<boolean[]> arraySetter; public static <T, R extends Registry<T> & ListenableRegistry> void register( R registry, Supplier<boolean[]> arrayGetter, Consumer<boolean[]> arraySetter ) { BooleanArrayTracker<T> tracker = new BooleanArrayTracker<>(arrayGetter, arraySetter); registry.getEventBus().register(Listener.object() .listener(tracker) .build()); } private BooleanArrayTracker( Supplier<boolean[]> arrayGetter, Consumer<boolean[]> arraySetter ) { this.arrayGetter = arrayGetter; this.arraySetter = arraySetter; } public static boolean shouldGrow(boolean[] array, int highestExpectedRawId) { return array.length <= highestExpectedRawId; } public static boolean[] grow(boolean[] array, int highestExpectedRawId) { return Arrays.copyOf(array, MathHelper.smallestEncompassingPowerOfTwo(highestExpectedRawId + 1)); } @EventListener private void onEntryAdded(RegistryEntryAddedEvent<T> event) { boolean[] array = arrayGetter.get(); if (shouldGrow(array, event.rawId)) arraySetter.accept(grow(array, event.rawId)); } @EventListener private void onRemap(RegistryIdRemapEvent<T> event) { boolean[] array = arrayGetter.get(); boolean[] prevArray = array.clone(); Arrays.fill(array, false); Int2IntMap remap = event.state.getRawIdChangeMap(); for (int i = 0; i < prevArray.length; i++) { if (!prevArray[i]) continue; int newId = remap.getOrDefault(i, i); if (shouldGrow(array, newId)) array = grow(array, newId); array[newId] = true; } if (prevArray.length != array.length) arraySetter.accept(array); } }
0
0.815081
1
0.815081
game-dev
MEDIA
0.368297
game-dev
0.769447
1
0.769447
matt77hias/RasterTek
1,788
Tutorial 16_Frustum Culling/Engine/positionclass.cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: positionclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "positionclass.h" PositionClass::PositionClass() { m_frameTime = 0.0f; m_rotationY = 0.0f; m_leftTurnSpeed = 0.0f; m_rightTurnSpeed = 0.0f; } PositionClass::PositionClass(const PositionClass& other) { } PositionClass::~PositionClass() { } void PositionClass::SetFrameTime(float time) { m_frameTime = time; return; } void PositionClass::GetRotation(float& y) { y = m_rotationY; return; } void PositionClass::TurnLeft(bool keydown) { // If the key is pressed increase the speed at which the camera turns left. If not slow down the turn speed. if(keydown) { m_leftTurnSpeed += m_frameTime * 0.01f; if(m_leftTurnSpeed > (m_frameTime * 0.15f)) { m_leftTurnSpeed = m_frameTime * 0.15f; } } else { m_leftTurnSpeed -= m_frameTime* 0.005f; if(m_leftTurnSpeed < 0.0f) { m_leftTurnSpeed = 0.0f; } } // Update the rotation using the turning speed. m_rotationY -= m_leftTurnSpeed; if(m_rotationY < 0.0f) { m_rotationY += 360.0f; } return; } void PositionClass::TurnRight(bool keydown) { // If the key is pressed increase the speed at which the camera turns right. If not slow down the turn speed. if(keydown) { m_rightTurnSpeed += m_frameTime * 0.01f; if(m_rightTurnSpeed > (m_frameTime * 0.15f)) { m_rightTurnSpeed = m_frameTime * 0.15f; } } else { m_rightTurnSpeed -= m_frameTime* 0.005f; if(m_rightTurnSpeed < 0.0f) { m_rightTurnSpeed = 0.0f; } } // Update the rotation using the turning speed. m_rotationY += m_rightTurnSpeed; if(m_rotationY > 360.0f) { m_rotationY -= 360.0f; } return; }
0
0.851769
1
0.851769
game-dev
MEDIA
0.723923
game-dev
0.588027
1
0.588027
deepwzh/sdust-examination-materials
1,603
编译原理/CompileExperiment/Cpp/Source/yyacpcre.cpp
/************************************************************ yyacpcre.cpp This file can be freely modified for the generation of custom code. [MBCS] Copyright (c) 1999-2003 Bumble-Bee Software Ltd. ************************************************************/ #include "yydefs.h" #if !(defined(YYDEBUG) && defined(YYSTDCPPLIB)) || defined(YYGROUP) #ifdef YYSTDCPPLIB #include <cstdlib> #else #include <stdlib.h> #endif #include "yycpars.h" #ifdef YYSTDCPPLIB using namespace std; #endif _YL_BEGIN yybool yyparser::yycreate(yylexer YYFAR* lexerptr) { yylexerptr = lexerptr; // stack yystack_t YYFAR* sstackptr; void YYFAR* sattributestackptr; if (yysstack_size != 0) { sstackptr = new YYFAR yystack_t[yysstack_size]; if (sstackptr == NULL) { return yyfalse; } sattributestackptr = yynewattribute(yysstack_size); if (sattributestackptr == NULL) { delete[] sstackptr; return yyfalse; } } else { sstackptr = NULL; sattributestackptr = NULL; } // yylval void YYFAR* lvalptr = yynewattribute(1); if (lvalptr == NULL) { delete[] sstackptr; yydeleteattribute(sattributestackptr); return yyfalse; } // yyval ($$) void YYFAR* valptr = yynewattribute(1); if (valptr == NULL) { delete[] sstackptr; yydeleteattribute(sattributestackptr); yydeleteattribute(lvalptr); return yyfalse; } // assign yysstackptr = sstackptr; yysattributestackptr = sattributestackptr; yylvalptr = lvalptr; yyvalptr = valptr; yystackptr = yysstackptr; yyattributestackptr = yysattributestackptr; yystack_size = yysstack_size; return yytrue; } _YL_END #endif
0
0.531937
1
0.531937
game-dev
MEDIA
0.15099
game-dev
0.592566
1
0.592566
MergHQ/CRYENGINE
5,677
Code/CryEngine/CryEntitySystem/FlowGraphProxy.cpp
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. // ------------------------------------------------------------------------- // File name: FlowGraphProxy.h // Version: v1.00 // Created: 6/6/2005 by Timur. // Compilers: Visual Studio.NET 2003 // Description: // ------------------------------------------------------------------------- // History: // //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FlowGraphProxy.h" #include "Entity.h" #include <CryFlowGraph/IFlowSystem.h> #include <CryNetwork/ISerialize.h> ////////////////////////////////////////////////////////////////////////// CFlowGraphProxy::CFlowGraphProxy() { m_pEntity = NULL; m_pFlowGraph = 0; } ////////////////////////////////////////////////////////////////////////// CFlowGraphProxy::~CFlowGraphProxy() { } ////////////////////////////////////////////////////////////////////////// void CFlowGraphProxy::Initialize(const SComponentInitializer& init) { m_pEntity = (CEntity*)init.m_pEntity; } ////////////////////////////////////////////////////////////////////////// void CFlowGraphProxy::Done() { if (m_pFlowGraph) m_pFlowGraph->Release(); m_pFlowGraph = 0; }; ////////////////////////////////////////////////////////////////////////// void CFlowGraphProxy::SetFlowGraph(IFlowGraph* pFlowGraph) { if (m_pFlowGraph) m_pFlowGraph->Release(); m_pFlowGraph = pFlowGraph; if (m_pFlowGraph) m_pFlowGraph->AddRef(); } ////////////////////////////////////////////////////////////////////////// IFlowGraph* CFlowGraphProxy::GetFlowGraph() { return m_pFlowGraph; } ////////////////////////////////////////////////////////////////////////// void CFlowGraphProxy::ProcessEvent(SEntityEvent& event) { // Assumes only 1 current listener can be deleted as a result of the event. Listeners::iterator next; Listeners::iterator it = m_listeners.begin(); while (it != m_listeners.end()) { next = it; ++next; (*it)->OnEntityEvent(m_pEntity, event); it = next; } // respond to entity activation/deactivation. enable/disable flowgraph switch (event.event) { case ENTITY_EVENT_INIT: case ENTITY_EVENT_DONE: { if (m_pFlowGraph) { const bool bActive = (event.event == ENTITY_EVENT_INIT) ? true : false; const bool bIsActive = m_pFlowGraph->IsActive(); if (bActive != bIsActive) m_pFlowGraph->SetActive(bActive); } } break; case ENTITY_EVENT_POST_SERIALIZE: if (m_pFlowGraph) m_pFlowGraph->PostSerialize(); break; } } ////////////////////////////////////////////////////////////////////////// void CFlowGraphProxy::AddEventListener(IEntityEventListener* pListener) { // Does not check uniquiness due to performance reasons. m_listeners.push_back(pListener); } void CFlowGraphProxy::RemoveEventListener(IEntityEventListener* pListener) { stl::find_and_erase(m_listeners, pListener); } void CFlowGraphProxy::Update(SEntityUpdateContext& ctx) { // if (m_pFlowGraph) // m_pFlowGraph->Update(); } void CFlowGraphProxy::Reload(IEntity* pEntity, SEntitySpawnParams& params) { m_pEntity = (CEntity*)pEntity; SAFE_RELEASE(m_pFlowGraph); m_listeners.clear(); } void CFlowGraphProxy::SerializeXML(XmlNodeRef& entityNode, bool bLoading) { // don't serialize flowgraphs from the editor // (editor needs more information, so it saves them specially) if (gEnv->IsEditor() && !bLoading) return; XmlNodeRef flowGraphNode; if (bLoading) { flowGraphNode = entityNode->findChild("FlowGraph"); if (!flowGraphNode) return; // prevents loading of disabled flowgraphs for optimization // only in game mode, of course #if 1 bool bEnabled = true; if (flowGraphNode->getAttr("enabled", bEnabled) && bEnabled == false) { EntityWarning("[FlowGraphProxy] Skipped loading of FG for Entity %d '%s'. FG was disabled on export.", m_pEntity->GetId(), m_pEntity->GetName()); return; } #endif enum EMultiPlayerType { eMPT_ServerOnly = 0, eMPT_ClientOnly, eMPT_ClientServer }; EMultiPlayerType mpType = eMPT_ServerOnly; const char* mpTypeAttr = flowGraphNode->getAttr("MultiPlayer"); if (mpTypeAttr) { if (strcmp("ClientOnly", mpTypeAttr) == 0) mpType = eMPT_ClientOnly; else if (strcmp("ClientServer", mpTypeAttr) == 0) mpType = eMPT_ClientServer; } const bool bIsServer = gEnv->bServer; const bool bIsClient = gEnv->IsClient(); if (mpType == eMPT_ServerOnly && !bIsServer) return; else if (mpType == eMPT_ClientOnly && !bIsClient) return; if (gEnv->pFlowSystem) { SetFlowGraph(gEnv->pFlowSystem->CreateFlowGraph()); } } else { flowGraphNode = entityNode->createNode("FlowGraph"); entityNode->addChild(flowGraphNode); } assert(!!flowGraphNode); if (m_pFlowGraph) { m_pFlowGraph->SetGraphEntity(m_pEntity->GetId()); m_pFlowGraph->SerializeXML(flowGraphNode, bLoading); } } ////////////////////////////////////////////////////////////////////////// bool CFlowGraphProxy::NeedSerialize() { return m_pFlowGraph != 0; }; ////////////////////////////////////////////////////////////////////////// bool CFlowGraphProxy::GetSignature(TSerialize signature) { signature.BeginGroup("FlowGraphProxy"); signature.EndGroup(); return true; } ////////////////////////////////////////////////////////////////////////// void CFlowGraphProxy::Serialize(TSerialize ser) { bool hasFlowGraph = m_pFlowGraph != 0; if (ser.BeginOptionalGroup("FlowGraph", hasFlowGraph)) { if (ser.IsReading() && m_pFlowGraph == 0) { EntityWarning("Unable to reload flowgraph here"); return; } if (m_pFlowGraph) m_pFlowGraph->Serialize(ser); ser.EndGroup(); } }
0
0.966305
1
0.966305
game-dev
MEDIA
0.406024
game-dev
0.92677
1
0.92677
pen-lang/pen
1,466
examples/snake/entity/snake.pen
import Core'Number import 'direction { Direction } import 'field { Field } import 'position { Position } type Snake { head Position positions [Position] length number direction Direction | none } New = \(p Position) Snake { Snake{ head: p, positions: [Position], length: 0, direction: none, } } Head = \(s Snake) Position { s.head } Move = \(s Snake, d Direction | none) Snake { Snake{...s, direction: if d = d as none { s.direction } else { d }} } Tick = \(s Snake) Snake { if d = s.direction as none { s } else { p = position'Move(s.head, d) Snake{ ...s, head: p, # TODO Use a generalized if-list expression to trim a tail. positions: [Position s.head, ...s.positions], } } } Grow = \(s Snake) Snake { Snake{...s, length: s.length + 1} } Positions = \(s Snake) [Position] { [Position s.head, ...positions(s.positions, s.length)] } positions = \(ps [Position], l number) [Position] { # TODO Use indexed list comprehension. if l == 0 { [Position] } else { if [p, ...ps] = ps { [Position p(), ...positions(ps, l - 1)] } else { [Position] } } } IsCrashed = \(s Snake, f Field) boolean { !field'IsInside(f, s.head) | isCrashed(s.head, s.positions, s.length) } isCrashed = \(head Position, ps [Position], l number) boolean { l > 0 & if [p, ...ps] = ps { p() == head | isCrashed(head, ps, l - 1) } else { false } }
0
0.559041
1
0.559041
game-dev
MEDIA
0.61017
game-dev
0.773347
1
0.773347
Creators-of-Create/Create
4,330
src/main/java/com/simibubi/create/content/logistics/packagerLink/LogisticallyLinkedBlockItem.java
package com.simibubi.create.content.logistics.packagerLink; import java.util.List; import java.util.UUID; import javax.annotation.Nullable; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import com.simibubi.create.foundation.utility.CreateLang; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; public class LogisticallyLinkedBlockItem extends BlockItem { public LogisticallyLinkedBlockItem(Block pBlock, Properties pProperties) { super(pBlock, pProperties); } @Override public boolean isFoil(ItemStack pStack) { return isTuned(pStack); } public static boolean isTuned(ItemStack pStack) { return pStack.hasTag() && pStack.getTag() .contains(BLOCK_ENTITY_TAG); } @Nullable public static UUID networkFromStack(ItemStack pStack) { if (!isTuned(pStack)) return null; CompoundTag tag = pStack.getTag() .getCompound(BLOCK_ENTITY_TAG); if (!tag.hasUUID("Freq")) return null; return tag.getUUID("Freq"); } @Override public void appendHoverText(ItemStack pStack, Level pLevel, List<Component> pTooltip, TooltipFlag pFlag) { super.appendHoverText(pStack, pLevel, pTooltip, pFlag); if (!isTuned(pStack)) return; CompoundTag tag = pStack.getTag() .getCompound(BLOCK_ENTITY_TAG); if (!tag.hasUUID("Freq")) return; CreateLang.translate("logistically_linked.tooltip") .style(ChatFormatting.GOLD) .addTo(pTooltip); CreateLang.translate("logistically_linked.tooltip_clear") .style(ChatFormatting.GRAY) .addTo(pTooltip); } @Override public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand usedHand) { ItemStack stack = player.getItemInHand(usedHand); if (isTuned(stack)) { if (level.isClientSide) { level.playSound(player, player.blockPosition(), SoundEvents.ITEM_FRAME_REMOVE_ITEM, SoundSource.BLOCKS, 0.75f, 1.0f); } else { player.displayClientMessage(CreateLang.translateDirect("logistically_linked.cleared"), true); stack.getTag().remove(BLOCK_ENTITY_TAG); } return InteractionResultHolder.sidedSuccess(stack, level.isClientSide); } else { return super.use(level, player, usedHand); } } @Override public InteractionResult useOn(UseOnContext pContext) { ItemStack stack = pContext.getItemInHand(); BlockPos pos = pContext.getClickedPos(); Level level = pContext.getLevel(); Player player = pContext.getPlayer(); InteractionHand hand = pContext.getHand(); if (player == null) return InteractionResult.FAIL; if (player.isShiftKeyDown()) return super.useOn(pContext); LogisticallyLinkedBehaviour link = BlockEntityBehaviour.get(level, pos, LogisticallyLinkedBehaviour.TYPE); boolean tuned = isTuned(stack); if (link != null) { if (level.isClientSide) return InteractionResult.SUCCESS; if (!link.mayInteractMessage(player)) return InteractionResult.SUCCESS; assignFrequency(stack, player, link.freqId); return InteractionResult.SUCCESS; } InteractionResult useOn = super.useOn(pContext); if (level.isClientSide || useOn == InteractionResult.FAIL) return useOn; player.displayClientMessage(tuned ? CreateLang.translateDirect("logistically_linked.connected") : CreateLang.translateDirect("logistically_linked.new_network_started"), true); return useOn; } public static void assignFrequency(ItemStack stack, Player player, UUID frequency) { CompoundTag stackTag = stack.getOrCreateTag(); CompoundTag teTag = new CompoundTag(); teTag.putUUID("Freq", frequency); stackTag.put(BLOCK_ENTITY_TAG, teTag); player.displayClientMessage(CreateLang.translateDirect("logistically_linked.tuned"), true); stack.setTag(stackTag); } }
0
0.83239
1
0.83239
game-dev
MEDIA
0.998384
game-dev
0.937736
1
0.937736
mingsongli/acycle
76,304
code/guicode/DYNOS.m
function varargout = DYNOS(varargin) % DYNOS MATLAB code for DYNOS.fig % DYNOS, by itself, creates a new DYNOS or raises the existing % singleton*. % % H = DYNOS returns the handle to a new DYNOS or the handle to % the existing singleton*. % % DYNOS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in DYNOS.M with the given input arguments. % % DYNOS('Property','Value',...) creates a new DYNOS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before DYNOS_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to DYNOS_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help DYNOS % Last Modified by GUIDE v2.5 04-May-2017 22:34:18 % The original script is by Mingsong Li, Jan 2015, China Univ. Geoscience; George Mason Univ % The GUI is by Mingsong Li, Dec 2016, China Univ. Geoscience; George Mason Univ % The GUI is updated by Mingsong Li, May 2017, Penn State Univ % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @DYNOS_OpeningFcn, ... 'gui_OutputFcn', @DYNOS_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before DYNOS is made visible. function DYNOS_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to DYNOS (see VARARGIN) handles.MonZoom = varargin{1}.MonZoom; handles.sortdata = varargin{1}.sortdata; handles.val1 = varargin{1}.val1; set(0,'Units','normalized') % set units as normalized set(gcf,'units','norm') % set location h=get(gcf,'Children'); % get all content h1=findobj(h,'FontUnits','norm'); % find all font units as points if ismac fontsize = 12; elseif ispc fontsize = 11; end set(h1,'FontUnits','points','FontSize',fontsize); % set as norm h2=findobj(h,'FontUnits','points'); % find all font units as points set(h2,'FontUnits','points','FontSize',fontsize); % set as norm % language lang_choice = varargin{1}.lang_choice; handles.lang_choice = lang_choice; lang_id = varargin{1}.lang_id; lang_var = varargin{1}.lang_var; handles.lang_id = lang_id; handles.lang_var = lang_var; handles.main_unit_selection = varargin{1}.main_unit_selection; if handles.lang_choice == 0 set(gcf,'Name','Acycle: Sedimentary Noise Model - DYNOT') else [~, dynot24] = ismember('dynot24',lang_id); set(gcf,'Name',['Acycle: ',lang_var{dynot24}]) end % Choose default command line output for DYNOS set(gcf,'position',[0.05,0.05,0.85,0.85] * handles.MonZoom) % set position % language if handles.lang_choice > 0 [~, dynot01] = ismember('dynot01',handles.lang_id); [~, dynot02] = ismember('dynot02',handles.lang_id); [~, dynot03] = ismember('dynot03',handles.lang_id); [~, dynot04] = ismember('dynot04',handles.lang_id); [~, dynot05] = ismember('dynot05',handles.lang_id); [~, dynot06] = ismember('dynot06',handles.lang_id); [~, dynot07] = ismember('dynot07',handles.lang_id); [~, dynot08] = ismember('dynot08',handles.lang_id); [~, dynot09] = ismember('dynot09',handles.lang_id); [~, dynot10] = ismember('dynot10',handles.lang_id); [~, dynot11] = ismember('dynot11',handles.lang_id); [~, dynot12] = ismember('dynot12',handles.lang_id); [~, dynot13] = ismember('dynot13',handles.lang_id); [~, dynot14] = ismember('dynot14',handles.lang_id); [~, dynot15] = ismember('dynot15',handles.lang_id); [~, dynot16] = ismember('dynot16',handles.lang_id); [~, dynot17] = ismember('dynot17',handles.lang_id); [~, dynot18] = ismember('dynot18',handles.lang_id); [~, dynot19] = ismember('dynot19',handles.lang_id); [~, dynot20] = ismember('dynot20',handles.lang_id); [~, dynot21] = ismember('dynot21',handles.lang_id); [~, dynot22] = ismember('dynot22',handles.lang_id); [~, dynot23] = ismember('dynot23',handles.lang_id); [~, main02] = ismember('main02',handles.lang_id); [~, menu71] = ismember('menu71',handles.lang_id); [~, menu03] = ismember('menu03',handles.lang_id); [~, dynot25] = ismember('dynot25',handles.lang_id); % from [~, dynot26] = ismember('dynot26',handles.lang_id); % to [~, main41] = ismember('main41',handles.lang_id); % window [~, MainUnit13] = ismember('MainUnit13',handles.lang_id); % ka [~, a218] = ismember('a218',handles.lang_id); % nw [~, main32] = ismember('main32',handles.lang_id); % step [~, main14] = ismember('main14',handles.lang_id); % freq [~, ec20] = ismember('ec20',handles.lang_id); % middle age of the data [~, main40] = ismember('main40',handles.lang_id); % median set(handles.uipanel6,'Title',lang_var{main02}) % data set(handles.uipanel2,'Title',lang_var{main02}) % data set(handles.uipanel8,'Title',lang_var{menu71}) set(handles.uipanel9,'Title',lang_var{dynot05}) set(handles.uipanel10,'Title',lang_var{main14}) set(handles.uipanel11,'Title',lang_var{menu03}) set(handles.uipanel12,'Title',lang_var{dynot16}) set(handles.pushbutton4,'String',[lang_var{main02},lang_var{dynot01}]) set(handles.pushbutton5,'String',lang_var{dynot02}) set(handles.text45,'String',[lang_var{dynot03},lang_var{main02}]) set(handles.text44,'String',lang_var{dynot26}) % to set(handles.text10,'String',lang_var{dynot26}) % to set(handles.text13,'String',lang_var{dynot26}) set(handles.text17,'String',lang_var{dynot26}) set(handles.text25,'String',lang_var{dynot26}) set(handles.text28,'String',lang_var{dynot26}) set(handles.pushbutton_cut,'String',lang_var{dynot03}) % cut set(handles.text8,'String',lang_var{dynot04}) set(handles.text18,'String',lang_var{dynot06}) set(handles.text40,'String',lang_var{dynot07}) % Number of Monte Carlo Simulations set(handles.radiobutton2,'String',lang_var{dynot08}) set(handles.text23,'String',lang_var{dynot09}) set(handles.text26,'String',lang_var{dynot10}) set(handles.text27,'String',lang_var{dynot11}) set(handles.text47,'String',lang_var{dynot12}) set(handles.text30,'String',lang_var{dynot13}) set(handles.text29,'String',lang_var{dynot14}) set(handles.text36,'String',lang_var{dynot15}) set(handles.text48,'String',lang_var{dynot17}) set(handles.text37,'String',lang_var{dynot18}) set(handles.text50,'String',lang_var{dynot19}) set(handles.text41,'String',lang_var{dynot20}) %set(handles.text42,'String',lang_var{dynot21}) set(handles.text2,'String',lang_var{dynot22}) set(handles.text46,'String',lang_var{MainUnit13}) set(handles.text14,'String',lang_var{MainUnit13}) set(handles.text43,'String',lang_var{MainUnit13}) set(handles.text11,'String',[lang_var{main41},' ',lang_var{dynot25}]) set(handles.text15,'String',lang_var{a218}) set(handles.text16,'String',lang_var{main32}) set(handles.radiobutton1,'String',lang_var{ec20}) set(handles.text16,'String',lang_var{main32}) set(handles.checkbox1median,'String',lang_var{main40}) % menu [~, menu01] = ismember('menu01',handles.lang_id); % File set(handles.menu_file,'Text',lang_var{menu01}) % File set(handles.file_import,'Text',lang_var{dynot23}) [~, dynot40] = ismember('dynot40',handles.lang_id); [~, menu07] = ismember('menu07',handles.lang_id); [~, dynot41] = ismember('dynot41',handles.lang_id); set(handles.menu_help,'Text',lang_var{menu07}) set(handles.menu_about,'Text',lang_var{dynot40}) set(handles.menu_website,'Text',lang_var{dynot41}) end % uipanels set(handles.uipanel6,'position', [0.015,0.9,0.124,0.076]) set(handles.uipanel7,'position', [0.14,0.9,0.167,0.076]) set(handles.uipanel8,'position', [0.015,0.776,0.291,0.12]) set(handles.uipanel9,'position', [0.015,0.592,0.291,0.18]) set(handles.uipanel10,'position', [0.015,0.344,0.291,0.245]) set(handles.uipanel11,'position', [0.015,0.179,0.291,0.145]) set(handles.uipanel12,'position', [0.014,0.005,0.291,0.175]) % plot area set(handles.text2,'position', [0.36,0.914,0.588,0.052],'FontSize',16) set(handles.edit30,'position', [0.36,0.902,0.588,0.025],'FontSize',12) set(handles.uipanel2,'position', [0.321,0.47,0.669,0.43]) set(handles.uipanel3,'position', [0.321,0.012,0.669,0.43]) set(handles.axes1,'position', [0.1,0.159,0.94,0.8]) set(handles.axes2,'position', [0.1,0.159,0.94,0.8]) % data/dynot set(handles.pushbutton4,'position', [0.2,0.15,0.65,0.7]) set(handles.pushbutton5,'position', [0.15,0.15,0.7,0.7]) % interpolation set(handles.text45,'position', [0.035,0.627,0.249,0.237]) set(handles.text8,'position', [0.035,0.22,0.249,0.237]) set(handles.text44,'position', [0.455,0.627,0.078,0.237]) set(handles.text10,'position', [0.455,0.22,0.078,0.237]) set(handles.text46,'position', [0.716,0.22,0.08,0.237]) set(handles.edit26,'position', [0.28,0.559,0.156,0.288]) set(handles.edit25,'position', [0.529,0.559,0.156,0.288]) set(handles.edit_sampa,'position', [0.28,0.153,0.156,0.288]) set(handles.edit_sampb,'position', [0.529,0.153,0.156,0.288]) set(handles.pushbutton_cut,'position', [0.712,0.559,0.233,0.288]) % MC set(handles.text11,'position', [0.035,0.747,0.265,0.179]) set(handles.edit6,'position', [0.366,0.747,0.163,0.179]) set(handles.text13,'position', [0.545,0.747,0.062,0.179]) set(handles.edit7,'position', [0.615,0.747,0.2,0.179]) set(handles.text14,'position', [0.852,0.747,0.09,0.179]) set(handles.text15,'position', [0.035,0.526,0.521,0.179]) set(handles.edit8,'position', [0.568,0.526,0.117,0.179]) set(handles.text17,'position', [0.7,0.526,0.062,0.179]) set(handles.edit9,'position', [0.774,0.526,0.117,0.179]) set(handles.text18,'position', [0.035,0.3,0.253,0.179]) set(handles.edit10,'position', [0.323,0.3,0.163,0.179]) set(handles.text16,'position', [0.615,0.3,0.148,0.179]) set(handles.edit21,'position', [0.735,0.3,0.117,0.179]) set(handles.text43,'position', [0.868,0.3,0.09,0.179]) set(handles.text40,'position', [0.035,0.08,0.665,0.179]) set(handles.edit24,'position', [0.712,0.08,0.253,0.179]) % frequency set(handles.radiobutton1,'position', [0.03,0.774,0.541,0.14]) set(handles.edit29,'position', [0.584,0.774,0.187,0.14]) set(handles.text49,'position', [0.848,0.774,0.089,0.14]) set(handles.radiobutton2,'position', [0.03,0.594,0.934,0.128]) set(handles.edit11,'position', [0.1,0.444,0.85,0.128]) set(handles.text23,'position', [0.03,0.241,0.436,0.128]) set(handles.edit13,'position', [0.45,0.241,0.109,0.128]) set(handles.text25,'position', [0.584,0.241,0.062,0.128]) set(handles.edit14,'position', [0.642,0.241,0.109,0.128]) set(handles.text27,'position', [0.76,0.241,0.226,0.128]) set(handles.text26,'position', [0.03,0.07,0.374,0.128]) set(handles.edit15,'position', [0.393,0.07,0.14,0.128]) set(handles.text28,'position', [0.549,0.07,0.062,0.128]) set(handles.edit12,'position', [0.619,0.07,0.14,0.128]) set(handles.text47,'position', [0.755,0.07,0.226,0.128]) %Plot set(handles.text30,'position', [0.03,0.77,0.43,0.176]) set(handles.checkbox1median,'position', [0.521,0.73,0.268,0.25]) set(handles.checkbox50,'position', [0.755,0.73,0.214,0.25]) set(handles.checkbox68,'position', [0.07,0.473,0.214,0.25]) set(handles.checkbox80,'position', [0.296,0.473,0.214,0.25]) set(handles.checkbox90,'position', [0.521,0.473,0.214,0.25]) set(handles.checkbox95,'position', [0.755,0.473,0.214,0.25]) set(handles.text29,'position', [0.03,0.12,0.42,0.25]) set(handles.edit22,'position', [0.428,0.12,0.163,0.25]) set(handles.text36,'position', [0.607,0.12,0.268,0.25]) set(handles.edit23,'position', [0.875,0.12,0.11,0.25]) % process set(handles.text48,'position', [0.03,0.75,0.659,0.185]) set(handles.edit27,'position', [0.717,0.75,0.163,0.185]) set(handles.text37,'position', [0.03,0.511,0.953,0.185]) set(handles.edit28,'position', [0.202,0.511,0.128,0.185]) set(handles.text50,'position', [0.337,0.511,0.636,0.185]) set(handles.text41,'position', [0.03,0.03,0.926,0.446],'FontSize',fontsize-1) handles.output = hObject; % contact with acycle main window handles.acfigmain = varargin{1}.acfigmain; handles.listbox_acmain = varargin{1}.listbox_acmain; handles.edit_acfigmain_dir = varargin{1}.edit_acfigmain_dir; % data_s = varargin{1}.current_data; handles.data = data_s; assignin('base','data',data_s) handles.filename = varargin{1}.data_name; handles.dat_name = varargin{1}.dat_name; handles.unit = varargin{1}.unit; handles.path_temp = varargin{1}.path_temp; handles.slash_v = varargin{1}.slash_v; % Update handles structure guidata(hObject, handles); % UIWAIT makes DYNOS wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = DYNOS_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function edit2_Callback(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit2 as text % str2double(get(hObject,'String')) returns contents of edit2 as a double % --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit3_Callback(hObject, eventdata, handles) % hObject handle to edit3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit3 as text % str2double(get(hObject,'String')) returns contents of edit3 as a double % --- Executes during object creation, after setting all properties. function edit3_CreateFcn(hObject, eventdata, handles) % hObject handle to edit3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton5. function pushbutton5_Callback(hObject, eventdata, handles) % hObject handle to pushbutton5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) numcore = handles.numcore; % language lang_var = handles.lang_var; lang_choice = handles.lang_choice; lang_id = handles.lang_id; % numcorereal = feature('numCores'); numcore(numcore>numcorereal) = numcorereal; useparpool = handles.useparpool; itinerary = handles.itinerary; data = handles.data; sampa = handles.sampa; sampb = handles.sampb; parmhat = handles.parmhat; unit = handles.unit; window1 = handles.window1; window2 = handles.window2; nw1 = handles.nw1; nw2 = handles.nw2; pad = handles.pad; step = handles.step; nout = handles.nout; shiftwin = handles.shiftwin; f = handles.f; fza = handles.fza; fzb = handles.fzb; ftmin = handles.ftmin; ftmax = handles.ftmax; nmc = handles.nmc; checkbox1median= handles.checkbox1median_v; checkbox50 = handles.checkbox50_v; checkbox68 = handles.checkbox68_v; checkbox80 = handles.checkbox80_v; checkbox90 = handles.checkbox90_v; checkbox95 = handles.checkbox95_v; percent = [checkbox1median, checkbox50, checkbox68, ... checkbox80,checkbox90, checkbox95]; % npercentage percent = sort(unique(percent)); percent = percent(percent~=0); if isempty(percent) percent = 50; end % %% Set random parameters if nw2==nw1 randnw = 0*rand(nmc,1); else randnw = randi(2*(nw2-nw1),[nmc 1]); end % samplez = wblrnd(parmhat(1),parmhat(2),[nmc 1]); samplez(samplez<sampa) = sampa+(sampb-sampa)*rand(1); samplez(samplez>sampb) = sampa+(sampb-sampa)*rand(1); randwindow=rand(nmc,1); windowz = window1+(window2-window1)*randwindow; % windowz range from window1 to window2 nwz = nw1 + randnw/2; % nw range from nw1 to nw2 bw = nwz./windowz; ncol = length(f); f3m =[]; for i=1:ncol fz = fza+(fzb-fza)*rand(nmc,1); f3m(:,2*i-1) = f(i)-fz.*bw; fz = fza+(fzb-fza)*rand(nmc,1); f3m(:,2*i) = f(i)+fz.*bw; end f3m(f3m < ftmin) = ftmin; f3m(f3m > ftmax) = ftmax; %% Set plot y axis grid and a empty powy y_grid = linspace(data(1,1),data(length(data(:,1)),1),nout); y_grid = y_grid'; powy = zeros(nout,nmc); % for interpolated series powmean = zeros(1,nmc); %% Main function. Very heavy loads tic; dispstat('','init'); % One time only initialization if lang_choice == 0 dispstat(sprintf(' Begin the process ...'),'keepthis','timestamp'); hwaitbarText = 'canceling'; else [~, dynot28] = ismember('dynot28',lang_id); dispstat(sprintf([lang_var{dynot28},' ...']),'keepthis','timestamp'); [~, dynot31] = ismember('dynot31',lang_id); hwaitbarText = lang_var{dynot31}; end %% if shiftwin == 1 shiftwin1 = 0; else shiftwin1 = shiftwin; end % Waitbar if handles.lang_choice == 0 hwaitbar = waitbar(0,'Very heavy loads, may take several hours ...',... 'WindowStyle','modal'); else [~, dynot27] = ismember('dynot27',lang_id); hwaitbar = waitbar(0,lang_var{dynot27},... 'WindowStyle','modal'); end hwaitbar_find = findobj(hwaitbar,'Type','Patch'); set(hwaitbar_find,'EdgeColor',[0 0.9 0],'FaceColor',[0 0.9 0]) % changes the color to blue if handles.lang_choice == 0 setappdata(hwaitbar,'canceling',0) else setappdata(hwaitbar,'canceling',0) end steps = 100; % step estimation for waitbar nmc_n = round(nmc/steps); waitbarstep = 1; waitbar(waitbarstep / steps) if nmc > 199 % Check for clicked Cancel button if numcore == 1 % can not use parpool or matlabpool for i=1:nmc if getappdata(hwaitbar,'canceling') break end dat = []; dat(:,1) = data(1,1):samplez(i):data(length(data(:,1)),1); dat(:,2) = interp1(data(:,1),data(:,2),dat(:,1),'pchip'); f3=f3m(i,:); window = windowz(i); y_grid_rand=randi([-1*shiftwin1,shiftwin1])*window/2; % shift y_grid1 nw = nwz(i); [power]=pdan(dat,f3,window,nw,ftmin,ftmax,step,pad); % power ratio of data series powy(:,i)=interp1((power(:,1)+y_grid_rand/shiftwin),power(:,2),y_grid); power2=power(:,2); % powmean(1,i)=mean(power2(~isnan(power2))); % mean power of each calculation time = toc; t_rem = (time*nmc/i)-time; hh = fix(t_rem/3600); mm = fix((t_rem-hh*3600)/60); sec = t_rem-hh*3600-mm*60; if handles.lang_choice == 0 dispstat(sprintf(' Progress %.1f%%. Remain %d:%d:%.0f',100*i/nmc,hh,mm,sec),'timestamp') else [~, dynot29] = ismember('dynot29',lang_id); [~, dynot30] = ismember('dynot30',lang_id); dispstat(lang_var{dynot29},sprintf(' %.1f%%. ',100*i/nmc),lang_var{dynot30},sprintf(' %d:%d:%.0f',hh,mm,sec),'timestamp') end % waitbar if rem(i,nmc_n) == 0 waitbarstep = waitbarstep+1; if waitbarstep > steps; waitbarstep = steps; end pause(0.001);% waitbar(waitbarstep / steps) end end if ishandle(hwaitbar); close(hwaitbar); end else % ready to use parpool or matlabpool % run first 50 times to estimate total computation time for i=1:itinerary if getappdata(hwaitbar,'canceling') break end dat = []; dat(:,1) = data(1,1):samplez(i):data(length(data(:,1)),1); dat(:,2) = interp1(data(:,1),data(:,2),dat(:,1),'pchip'); f3=f3m(i,:); window = windowz(i); y_grid_rand=randi([-1*shiftwin1,shiftwin1])*window/2; % shift y_grid1 nw = nwz(i); [power]=pdan(dat,f3,window,nw,ftmin,ftmax,step,pad); % power ratio of data series powy(:,i)=interp1((power(:,1)+y_grid_rand/shiftwin),power(:,2),y_grid); power2=power(:,2); % powmean(1,i)=mean(power2(~isnan(power2))); % mean power of each calculation time = toc; t_rem = (time*nmc/i)-time; hh = fix(t_rem/3600); mm = fix((t_rem-hh*3600)/60); sec = t_rem-hh*3600-mm*60; if handles.lang_choice == 0 dispstat(sprintf(' Progress %.2f%%. Remain %d:%d:%.0f',100*i/nmc,hh,mm,sec),'timestamp') else [~, dynot29] = ismember('dynot29',lang_id); [~, dynot30] = ismember('dynot30',lang_id); dispstat([lang_var{dynot29},sprintf(' %.2f%%. ',100*i/nmc),lang_var{dynot30},sprintf(' %d:%d:%.0f',hh,mm,sec)],'timestamp') end % waitbar if rem(i,nmc_n) == 0 waitbarstep = waitbarstep+1; if waitbarstep > steps; waitbarstep = steps; end pause(0.001);% waitbar(waitbarstep / steps) end end t_rem = t_rem/numcore; hh = fix(t_rem/3600); mm = fix((t_rem-hh*3600)/60); sec = round(t_rem-hh*3600-mm*60); if handles.lang_choice == 0 dispstat(sprintf(' First %d iterations suggest: remain >= %dh:%dm:%dsec',itinerary,hh,mm,sec),'timestamp') else [~, dynot18] = ismember('dynot18',lang_id); [~, dynot32] = ismember('dynot32',lang_id); dispstat([lang_var{dynot18},sprintf(' %d ',itinerary),lang_var{dynot32},':',lang_var{dynot30},sprintf(' >= %dh:%dm:%ds',hh,mm,sec)],'timestamp') end %end if ishandle(hwaitbar) close(hwaitbar); end if handles.lang_choice == 0 msgbox_v = {'Remaining time is likely:';... [num2str(hh),' hr ',num2str(mm),' min ', num2str(sec), ' sec'];... ['Come back at ~ ',datestr(now + t_rem/86400,'dd-mm-yyyy HH:MM:SS FFF')]}; msgbox1 = msgbox(msgbox_v,'Wait ...'); else [~, dynot33] = ismember('dynot33',lang_id); [~, dynot34] = ismember('dynot34',lang_id); [~, dynot35] = ismember('dynot35',lang_id); [~, dynot36] = ismember('dynot36',lang_id); [~, dynot37] = ismember('dynot37',lang_id); [~, dynot38] = ismember('dynot38',lang_id); msgbox_v = {lang_var{dynot33};... [num2str(hh),lang_var{dynot34},num2str(mm),lang_var{dynot35}, num2str(sec), lang_var{dynot36}];... [lang_var{dynot37},datestr(now + t_rem/86400,'dd-mm-yyyy HH:MM:SS FFF')]}; msgbox1 = msgbox(msgbox_v,lang_var{dynot38}); end % use parpool when version of matlab is higher than 8.2, else use matlabpool if useparpool poolobj = parpool('local',numcore); else if matlabpool('size')<=0 matlabpool('open','local',numcore); else end end % Parallel computing parfor i = itinerary+1:nmc tic; dat = []; dat(:,1) = data(1,1):samplez(i):data(length(data(:,1)),1); dat(:,2) = interp1(data(:,1),data(:,2),dat(:,1),'pchip'); f3=f3m(i,:); window = windowz(i); y_grid_rand=randi([-1*shiftwin1,shiftwin1])*window/2; % shift y_grid1 nw = nwz(i); [power]=pdan(dat,f3,window,nw,ftmin,ftmax,step,pad); % power ratio of data series powy(:,i)=interp1((power(:,1)+y_grid_rand/shiftwin),power(:,2),y_grid); power2=power(:,2); % powmean(1,i)=mean(power2(~isnan(power2))); % mean power of each calculation if lang_choice == 0 dispstat(sprintf(' Current iteration takes %.2f seconds',toc),'timestamp') else [~, dynot39] = ismember('dynot39',lang_id); dispstat(sprintf(lang_var{dynot39},toc),'timestamp') end % end if useparpool delete(poolobj); else matlabpool close end if ishandle(hwaitbar); close(hwaitbar);end if ishandle(msgbox1); close(msgbox1);end end else %figdat = msgbox('Heavy loads, please wait','Wait ...'); for i=1:nmc if getappdata(hwaitbar,hwaitbarText) break end dat = []; dat(:,1) = data(1,1):samplez(i):data(length(data(:,1)),1); dat(:,2) = interp1(data(:,1),data(:,2),dat(:,1),'pchip'); f3=f3m(i,:); window = windowz(i); y_grid_rand=randi([-1*shiftwin1,shiftwin1])*window/2; % shift y_grid1 nw = nwz(i); [power]=pdan(dat,f3,window,nw,ftmin,ftmax,step,pad); % power ratio of data series powy(:,i)=interp1((power(:,1)+y_grid_rand/shiftwin),power(:,2),y_grid); power2=power(:,2); % powmean(1,i)=mean(power2(~isnan(power2))); % mean power of each calculation time = toc; t_rem = (time*nmc/i)-time; hh = fix(t_rem/3600); mm = fix((t_rem-hh*3600)/60); sec = t_rem-hh*3600-mm*60; %dispstat(sprintf(' Progress %.1f%%. Remain %d:%d:%.0f',100*i/nmc,hh,mm,sec),'timestamp') if handles.lang_choice == 0 dispstat(sprintf(' Progress %.1f%%. Remain %d:%d:%.0f',100*i/nmc,hh,mm,sec),'timestamp') else [~, dynot29] = ismember('dynot29',lang_id); [~, dynot30] = ismember('dynot30',lang_id); dispstat([lang_var{dynot29},sprintf(' %.1f%%. ',100*i/nmc),lang_var{dynot30},sprintf(' %d:%d:%.0f',hh,mm,sec)],'timestamp') end % % if rem(i,nmc_n) == 0 waitbarstep = waitbarstep+1; if waitbarstep > steps; waitbarstep = steps; end pause(0.001);% waitbar(waitbarstep / steps) end end if ishandle(hwaitbar); close(hwaitbar);end end %% Adjust each power ratio to a unique ratio powmean_mean = mean(powmean); % mean power ratio of each calculation powmeanadjust = []; % Make sure each running of this script don't be affected by previous running powmeanadjust = powmean_mean./powmean; powmeanadjust = repmat(powmeanadjust,nout,1); powyadjust = powmeanadjust.*powy; % Dec 10, 2016 Add by Mingsong Li. To avoid a problem that total power > 1 maxp = max(max(powyadjust)); if maxp > 1 powyadjust=powyadjust/maxp; end % No adjust?? %powyadjust= powy; % if handles.lang_choice == 0 dispstat('>> Done.','keepprev'); % done else [~, main45] = ismember('main45',lang_id); dispstat(['>> ',lang_var{main45},'.'],'keepprev'); % done end %% npercent = length(percent); npercent2 = (length(percent)-1)/2; powyp = prctile(powy, percent,2); powyadjustp=prctile(powyadjust, percent,2); powyad_p_nan =[]; y_grid_nan=[]; % Remove NaN within powyadjustp for i = 1: npercent powyadjustp1=powyadjustp(:,i); powyad_p_nan(:,i) = powyadjustp1(~isnan(powyadjustp1)); end y_grid_nan = y_grid(~isnan(powyadjustp(:,1))); powyad_p_nan = 1 - powyad_p_nan; powyadjust = 1- powyadjust; powyadjustp = 1 - powyadjustp; %% Plot DYNOS axes(handles.axes2) cla reset hold all % for i = 1: nmc % plot(y_grid,powyadjust(:,i),'color',[0,0,0]+0.8); % end % colorcode = [221/255,234/255,224/255; ... 201/255,227/255,209/255; ... 176/255,219/255,188/255;... 126/255,201/255,146/255;... 67/255,180/255,100/255]; for i = 1:npercent2 fill([y_grid_nan; (fliplr(y_grid_nan'))'],[powyad_p_nan(:,npercent+1-i);... (fliplr(powyad_p_nan(:,i)'))'],colorcode(i,:),'LineStyle','none'); end plot(y_grid_nan,powyad_p_nan(:,npercent2+1),'Color',[0,120/255,0],'LineWidth',1.5,'LineStyle','--') axis([data(1,1) data(length(data(:,1)),1) min(powyad_p_nan(:,npercent)) max(powyad_p_nan(:,1))]) set(handles.axes2,'Ydir','reverse') set(gca,'XMinorTick','on','YMinorTick','on') hold off set(handles.uipushtool4, 'Enable', 'On'); set(handles.uipushtool5, 'Enable', 'On'); set(handles.uipushtool6, 'Enable', 'On'); set(handles.uipushtool7, 'Enable', 'On'); %% save data in workspace assignin('base','freqz',f3m) assignin('base','nwz',nwz) assignin('base','windowz',windowz) assignin('base','samplez',samplez) assignin('base','powy_grid',y_grid) assignin('base','powy',powyadjust) assignin('base','powyp',powyadjustp) assignin('base','powyad_p_grid',y_grid_nan) assignin('base','powyad_p',powyad_p_nan) handles.f3m = f3m; handles.nwz = nwz; handles.windowz = windowz; handles.samplez = samplez; handles.npercent = npercent; handles.npercent2 = npercent2; handles.y_grid = y_grid; handles.powyadjust = powyadjust; handles.powyadjustp = powyadjustp; handles.y_grid_nan = y_grid_nan; handles.powyad_p_nan = powyad_p_nan; handles.colorcode = colorcode; % save data data1 = [y_grid_nan,powyad_p_nan(:,npercent2+1)]; name1 = [handles.dat_name,'-DYNOT-median.txt']; data2 = [y_grid_nan,powyad_p_nan]; name2 = [handles.dat_name,'-DYNOT-prctile.txt']; CDac_pwd if exist([pwd,handles.slash_v,name1]) || exist([pwd,handles.slash_v,name2]) for i = 1:100 name1 = [handles.dat_name,'-DYNOT-median-',num2str(i),'.txt']; name2 = [handles.dat_name,'-DYNOT-prctile-',num2str(i),'.txt']; if exist([pwd,handles.slash_v,name1]) || exist([pwd,handles.slash_v,name2]) else break end end end if handles.lang_choice == 0 disp(['>> Save DYNOT median : ',name1]) disp(['>> Save DYNOT percentile: ',name2]) else [~, main52] = ismember('main52',lang_id); % save [~, main40] = ismember('main40',lang_id); % median [~, main56] = ismember('main56',lang_id); % percentile disp(['>> ',lang_var{main52},' DYNOT ',lang_var{main40},' : ',name1]) disp(['>> ',lang_var{main52},' DYNOT ',lang_var{main56},' : ',name2]) end dlmwrite(name1, data1, 'delimiter', ' ', 'precision', 9); dlmwrite(name2, data2, 'delimiter', ' ', 'precision', 9); cd(pre_dirML); % return to matlab view folder % % refresh AC main window figure(handles.acfigmain); CDac_pwd; % cd working dir refreshcolor; cd(pre_dirML); % return view dir guidata(hObject, handles); % --- Executes on button press in pushbutton4. function pushbutton4_Callback(hObject, eventdata, handles) % hObject handle to pushbutton4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % plot data in axis 1 % estimate matlab version to decide use matlabpool or parpool script % use parpool when matlab version is higher than 8.2,else use % matlabpool matlabversion = version; matversion = str2num(matlabversion(1:3)); if matversion >= 8.2 useparpool = 1; delete(gcp('nocreate')); % clear pool else useparpool = 0; end handles.useparpool = useparpool; existdata = evalin('base','who'); if ismember('data',existdata) handles.data = evalin('base','data'); data = handles.data; if data(2,1)<= data(1,1) data = flipud(data); end xmin = min(data(:,1)); xmax = max(data(:,1)); ymin = min(data(:,2)); ymax = max(data(:,2)); samplerate = diff(data(:,1)); parmhat = wblfit(samplerate); % estimate weibull a and b % plot plot(handles.axes1,data(:,1),data(:,2)); axis(handles.axes1,[xmin xmax ymin ymax]) set(gca,'XMinorTick','on','YMinorTick','on') % plot axes(handles.axes2) histfit(samplerate,40,'kernel'); title(handles.axes2,'Sample rates'); % set default parameters cover 90% sample ranges samplerange = prctile(samplerate, [5 95]); % numcore = feature('numCores'); % set handles handles.numcore = numcore; handles.itinerary = 50; handles.sampa = samplerange(1); handles.sampb = samplerange(2); handles.parmhat = parmhat; handles.unit = 'ka'; handles.window1 = 300; handles.window2 = 500; handles.nw1 = 2; handles.nw2 = 2; handles.pad = 1000; handles.step = 5; handles.nout = 1000; handles.shiftwin = 15; handles.fza = 0.9; handles.fzb = 1.2; handles.ftmin = 0.001; handles.ftmax = 1; handles.nmc = 1000; handles.age = 0; handles.cut1 = data(1,1); handles.cut2 = data(length(data(:,1)),1); handles.checkbox1median_v = 50; handles.checkbox50_v = [25 75]; handles.checkbox68_v = [15.865 84.135]; handles.checkbox80_v = [10 90]; handles.checkbox90_v = [5 95]; handles.checkbox95_v = [2.5 97.5]; % set settings in the app set(handles.edit6, 'String', num2str(handles.window1)); set(handles.edit7, 'String', num2str(handles.window2)); set(handles.edit8, 'String', num2str(handles.nw1)); set(handles.edit9, 'String', num2str(handles.nw2)); set(handles.edit10, 'String', num2str(handles.pad)); c = [405 125 95 40.9 23.6 22.3 19.1]; set(handles.edit11, 'String', num2str(c,'%1.1f ')); set(handles.edit13, 'String', num2str(handles.fza)); set(handles.edit14, 'String', num2str(handles.fzb)); set(handles.edit15, 'String', num2str(handles.ftmin)); set(handles.edit12, 'String', num2str(handles.ftmax)); set(handles.edit21, 'String', num2str(handles.step)); set(handles.edit22, 'String', num2str(handles.nout)); set(handles.edit23, 'String', num2str(handles.shiftwin)); set(handles.edit_sampa, 'String', num2str(samplerange(1))); set(handles.edit_sampb, 'String', num2str(samplerange(2))); set(handles.edit24, 'String', num2str(handles.nmc)); set(handles.edit26, 'String', num2str(data(1,1))); set(handles.edit25, 'String', num2str(data(length(data(:,1)),1))); set(handles.edit27, 'Enable', 'On'); set(handles.edit27, 'String', num2str(numcore)); set(handles.edit28, 'String', num2str(handles.itinerary)); set(handles.pushbutton_cut, 'Enable', 'On'); set(handles.pushbutton5, 'Enable', 'On'); set(handles.edit29, 'Enable', 'On'); set(handles.edit11, 'Enable', 'Off'); set(handles.radiobutton1, 'Value', 1); set(handles.radiobutton2, 'Value', 0); guidata(hObject, handles); else % cd doc data_type % cd .. end function edit6_Callback(hObject, eventdata, handles) % hObject handle to edit6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit6 as text % str2double(get(hObject,'String')) returns contents of edit6 as a double window1 = str2double(get(hObject,'String')); handles.window1 = window1; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit6_CreateFcn(hObject, eventdata, handles) % hObject handle to edit6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit7_Callback(hObject, eventdata, handles) % hObject handle to edit7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit7 as text % str2double(get(hObject,'String')) returns contents of edit7 as a double window2 = str2double(get(hObject,'String')); handles.window2 = window2; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit7_CreateFcn(hObject, eventdata, handles) % hObject handle to edit7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_sampa_Callback(hObject, eventdata, handles) % hObject handle to edit_sampa (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_sampa as text % str2double(get(hObject,'String')) returns contents of edit_sampa as a double sampa = str2double(get(hObject,'String')); handles.sampa = sampa; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit_sampa_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_sampa (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_sampb_Callback(hObject, eventdata, handles) % hObject handle to edit_sampb (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_sampb as text % str2double(get(hObject,'String')) returns contents of edit_sampb as a double sampb = str2double(get(hObject,'String')); handles.sampb = sampb; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit_sampb_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_sampb (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit8_Callback(hObject, eventdata, handles) % hObject handle to edit8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit8 as text % str2double(get(hObject,'String')) returns contents of edit8 as a double nw1 = str2double(get(hObject,'String')); handles.nw1 = nw1; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit8_CreateFcn(hObject, eventdata, handles) % hObject handle to edit8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit9_Callback(hObject, eventdata, handles) % hObject handle to edit9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit9 as text % str2double(get(hObject,'String')) returns contents of edit9 as a double nw2 = str2double(get(hObject,'String')); handles.nw2 = nw2; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit9_CreateFcn(hObject, eventdata, handles) % hObject handle to edit9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit10_Callback(hObject, eventdata, handles) % hObject handle to edit10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit10 as text % str2double(get(hObject,'String')) returns contents of edit10 as a double pad = str2double(get(hObject,'String')); handles.pad = pad; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit10_CreateFcn(hObject, eventdata, handles) % hObject handle to edit10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit11_Callback(hObject, eventdata, handles) % hObject handle to edit11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit11 as text % str2double(get(hObject,'String')) returns contents of edit11 as a double c = strread(get(hObject,'String')); f = 1./c; handles.f = f; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit11_CreateFcn(hObject, eventdata, handles) % hObject handle to edit11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end c = strread(get(hObject,'String')); f = 1./c; handles.f = f; guidata(hObject, handles); function edit12_Callback(hObject, eventdata, handles) % hObject handle to edit12 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit12 as text % str2double(get(hObject,'String')) returns contents of edit12 as a double ftmax = str2double(get(hObject,'String')); handles.ftmax = ftmax; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit12_CreateFcn(hObject, eventdata, handles) % hObject handle to edit12 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit13_Callback(hObject, eventdata, handles) % hObject handle to edit13 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit13 as text % str2double(get(hObject,'String')) returns contents of edit13 as a double fza = str2double(get(hObject,'String')); handles.fza = fza; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit13_CreateFcn(hObject, eventdata, handles) % hObject handle to edit13 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit14_Callback(hObject, eventdata, handles) % hObject handle to edit14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit14 as text % str2double(get(hObject,'String')) returns contents of edit14 as a double fzb = str2double(get(hObject,'String')); handles.fzb = fzb; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit14_CreateFcn(hObject, eventdata, handles) % hObject handle to edit14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit15_Callback(hObject, eventdata, handles) % hObject handle to edit15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit15 as text % str2double(get(hObject,'String')) returns contents of edit15 as a double ftmin = str2double(get(hObject,'String')); handles.ftmin = ftmin; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit15_CreateFcn(hObject, eventdata, handles) % hObject handle to edit15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit16_Callback(hObject, eventdata, handles) % hObject handle to edit16 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit16 as text % str2double(get(hObject,'String')) returns contents of edit16 as a double % --- Executes during object creation, after setting all properties. function edit16_CreateFcn(hObject, eventdata, handles) % hObject handle to edit16 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit17_Callback(hObject, eventdata, handles) % hObject handle to edit17 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit17 as text % str2double(get(hObject,'String')) returns contents of edit17 as a double % --- Executes during object creation, after setting all properties. function edit17_CreateFcn(hObject, eventdata, handles) % hObject handle to edit17 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit18_Callback(hObject, eventdata, handles) % hObject handle to edit18 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit18 as text % str2double(get(hObject,'String')) returns contents of edit18 as a double % --- Executes during object creation, after setting all properties. function edit18_CreateFcn(hObject, eventdata, handles) % hObject handle to edit18 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit19_Callback(hObject, eventdata, handles) % hObject handle to edit19 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit19 as text % str2double(get(hObject,'String')) returns contents of edit19 as a double % --- Executes during object creation, after setting all properties. function edit19_CreateFcn(hObject, eventdata, handles) % hObject handle to edit19 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit20_Callback(hObject, eventdata, handles) % hObject handle to edit20 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit20 as text % str2double(get(hObject,'String')) returns contents of edit20 as a double % --- Executes during object creation, after setting all properties. function edit20_CreateFcn(hObject, eventdata, handles) % hObject handle to edit20 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit21_Callback(hObject, eventdata, handles) % hObject handle to edit21 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit21 as text % str2double(get(hObject,'String')) returns contents of edit21 as a double step = str2double(get(hObject,'String')); handles.step = step; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit21_CreateFcn(hObject, eventdata, handles) % hObject handle to edit21 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popupmenu2. function popupmenu2_Callback(hObject, eventdata, handles) % hObject handle to popupmenu2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array % contents{get(hObject,'Value')} returns selected item from popupmenu2 % Determine the selected data set. str = get(hObject, 'String'); val = get(hObject,'Value'); % Set current data to the selected data set. switch str{val}; case 'ka' % User selects unit. handles.unit = 'ka'; case 'ma' % User selects m. handles.unit = 'ma'; case 'a' % User selects dm. handles.unit = 'a'; end % Save the handles structure. guidata(hObject,handles) % --- Executes during object creation, after setting all properties. function popupmenu2_CreateFcn(hObject, eventdata, handles) % hObject handle to popupmenu2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit22_Callback(hObject, eventdata, handles) % hObject handle to edit22 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit22 as text % str2double(get(hObject,'String')) returns contents of edit22 as a double nout = str2double(get(hObject,'String')); handles.nout = nout; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit22_CreateFcn(hObject, eventdata, handles) % hObject handle to edit22 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit23_Callback(hObject, eventdata, handles) % hObject handle to edit23 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit23 as text % str2double(get(hObject,'String')) returns contents of edit23 as a double shiftwin = str2double(get(hObject,'String')); handles.shiftwin = shiftwin; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit23_CreateFcn(hObject, eventdata, handles) % hObject handle to edit23 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in checkbox1median. function checkbox1median_Callback(hObject, eventdata, handles) % hObject handle to checkbox1median (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox1median % checkbox1median_v = get(handles.checkbox1median,'string'); % handles.checkbox1median_v = checkbox1median_v; checkbox1median = get(handles.checkbox1median,'Value'); if checkbox1median == 1 handles.checkbox1median_v = 50; else handles.checkbox1median_v = 0; end guidata(hObject, handles); % --- Executes on button press in checkbox50. function checkbox50_Callback(hObject, eventdata, handles) % hObject handle to checkbox50 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox50 checkbox50 = get(handles.checkbox50,'Value'); if checkbox50 == 1 handles.checkbox50_v = [25 75]; else handles.checkbox50_v = [0 0]; end guidata(hObject, handles); % --- Executes on button press in checkbox68. function checkbox68_Callback(hObject, eventdata, handles) % hObject handle to checkbox68 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox68 checkbox68 = get(handles.checkbox68,'Value'); if checkbox68 == 1 % set(handles.checkbox68,'Enable','on') handles.checkbox68_v = [15.865 84.135]; else handles.checkbox68_v = [0 0]; end guidata(hObject, handles); % --- Executes on button press in checkbox80. function checkbox80_Callback(hObject, eventdata, handles) % hObject handle to checkbox80 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox80 checkbox80 = get(handles.checkbox80,'Value'); if checkbox80 == 1 % set(handles.checkbox80,'Enable','on') handles.checkbox80_v = [10 90]; else % set(handles.checkbox80,'Enable','on') handles.checkbox80_v = [0 0]; end guidata(hObject, handles); % --- Executes on button press in checkbox90. function checkbox90_Callback(hObject, eventdata, handles) % hObject handle to checkbox90 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox90 checkbox90 = get(handles.checkbox90,'Value'); if checkbox90 == 1 % set(handles.checkbox90,'Enable','on') handles.checkbox90_v = [5 95]; else % set(handles.checkbox90,'Enable','on') handles.checkbox90_v = [0 0]; end guidata(hObject, handles); % --- Executes on button press in checkbox95. function checkbox95_Callback(hObject, eventdata, handles) % hObject handle to checkbox95 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox95 checkbox95 = get(handles.checkbox95,'Value'); if checkbox95 == 1 % set(handles.checkbox95,'Enable','on') handles.checkbox95_v = [2.5 97.5]; else % set(handles.checkbox95,'Enable','on') handles.checkbox95_v = [0 0]; end guidata(hObject, handles); function edit24_Callback(hObject, eventdata, handles) % hObject handle to edit24 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit24 as text % str2double(get(hObject,'String')) returns contents of edit24 as a double nmc = str2double(get(hObject,'String')); handles.nmc = nmc; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit24_CreateFcn(hObject, eventdata, handles) % hObject handle to edit24 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % -------------------------------------------------------------------- function uipushtool1_ClickedCallback(hObject, eventdata, handles) % hObject handle to uipushtool1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) h_old = gcf; close(h_old) run DYNOS function edit25_Callback(hObject, eventdata, handles) % hObject handle to edit25 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit25 as text % str2double(get(hObject,'String')) returns contents of edit25 as a double cut2 = str2double(get(hObject,'String')); handles.cut2 = cut2; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit25_CreateFcn(hObject, eventdata, handles) % hObject handle to edit25 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit26_Callback(hObject, eventdata, handles) % hObject handle to edit26 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit26 as text % str2double(get(hObject,'String')) returns contents of edit26 as a double cut1 = str2double(get(hObject,'String')); handles.cut1 = cut1; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit26_CreateFcn(hObject, eventdata, handles) % hObject handle to edit26 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton_cut. function pushbutton_cut_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_cut (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) cut1 = handles.cut1; cut2 = handles.cut2; cut1 = min(cut1, cut2); cut2 = max(cut1, cut2); data = handles.data; datx = find(data(:,1) >= cut1 & data(:,1)<= cut2); data = data(datx,1:2); samplerate = diff(data(:,1)); % parmhat = wblfit(samplerate); % estimate weibull a and b % plot axes(handles.axes1) cla reset plot(data(:,1),data(:,2)); axis([data(1,1) data(length(data(:,1)),1) min(data(:,2)) max(data(:,2))]) % plot axes(handles.axes2) cla reset histfit(samplerate,40,'kernel'); title(handles.axes2,'Sample rates'); % set default parameters cover 90% sample ranges samplerange = prctile(samplerate, [5 95]); % set handles handles.sampa = samplerange(1); handles.sampb = samplerange(2); handles.parmhat = parmhat; % handles.data = data; set(handles.edit_sampa, 'String', num2str(samplerange(1))); set(handles.edit_sampb, 'String', num2str(samplerange(2))); guidata(hObject, handles); % -------------------------------------------------------------------- function uipushtool4_ClickedCallback(hObject, eventdata, handles) % hObject handle to uipushtool4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) figurename=['plots_','.fig']; saveas(gcf,figurename) % -------------------------------------------------------------------- function uipushtool5_ClickedCallback(hObject, eventdata, handles) % hObject handle to uipushtool5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) data = handles.data; nmc = handles.nmc; y_grid = handles.y_grid; powyadjust = handles.powyadjust; y_grid_nan = handles.y_grid_nan; powyad_p_nan = handles.powyad_p_nan; npercent = handles.npercent; npercent2 = handles.npercent2; powyadjustp = handles.powyadjustp; colorcode = handles.colorcode; figure; hold all for i = 1:npercent2 fill([y_grid_nan; (fliplr(y_grid_nan'))'],[powyad_p_nan(:,i);... (fliplr(powyad_p_nan(:,npercent+1-i)'))'],colorcode(i,:),'LineStyle','none'); end plot(y_grid_nan,powyad_p_nan(:,npercent2+1),'Color',[0,120/255,0],'LineWidth',1.5,'LineStyle','--') axis([data(1,1) data(length(data(:,1)),1) min(powyad_p_nan(:,npercent)) max(powyad_p_nan(:,1))]) set(gca,'Ydir','reverse') hold off % -------------------------------------------------------------------- function uipushtool6_ClickedCallback(hObject, eventdata, handles) % hObject handle to uipushtool6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) figurename=['plots_','.pdf']; saveas(gcf,figurename) % -------------------------------------------------------------------- function uipushtool7_ClickedCallback(hObject, eventdata, handles) % hObject handle to uipushtool7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % use the following script to save workspace % save ('result_workspace.mat') save result_handles.mat function edit27_Callback(hObject, eventdata, handles) % hObject handle to edit27 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit27 as text % str2double(get(hObject,'String')) returns contents of edit27 as a double numcore = str2double(get(hObject,'String')); handles.numcore = numcore; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit27_CreateFcn(hObject, eventdata, handles) % hObject handle to edit27 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit28_Callback(hObject, eventdata, handles) % hObject handle to edit28 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit28 as text % str2double(get(hObject,'String')) returns contents of edit28 as a double itinerary = str2double(get(hObject,'String')); handles.itinerary = itinerary; guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit28_CreateFcn(hObject, eventdata, handles) % hObject handle to edit28 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes when uipanel2 is resized. function uipanel2_SizeChangedFcn(hObject, eventdata, handles) % hObject handle to uipanel2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function menu_file_Callback(hObject, eventdata, handles) % hObject handle to menu_file (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function menu_help_Callback(hObject, eventdata, handles) % hObject handle to menu_help (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function menu_about_Callback(hObject, eventdata, handles) % hObject handle to menu_about (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % cd doc About % cd .. % -------------------------------------------------------------------- function menu_tour_Callback(hObject, eventdata, handles) % hObject handle to menu_tour (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % cd doc open('Tour.pdf') % cd .. % -------------------------------------------------------------------- function menu_website_Callback(hObject, eventdata, handles) % hObject handle to menu_website (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) url = 'https://mingsongli.wixsite.com/home'; web(url,'-browser') % --- Executes on button press in radiobutton1. function radiobutton1_Callback(hObject, eventdata, handles) % hObject handle to radiobutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton1 set(handles.edit11, 'Enable', 'Off'); set(handles.radiobutton2, 'Value', 0); set(handles.edit29, 'Enable', 'On'); function edit29_Callback(hObject, eventdata, handles) % hObject handle to edit29 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit29 as text % str2double(get(hObject,'String')) returns contents of edit29 as a double age = str2double(get(hObject,'String')); handles.age = age; age_obl = 41 - 0.0332*age; age_p1 = 22.43 - 0.0108*age; age_p2 = 23.75 - 0.0121*age; age_p3 = 19.18 - 0.0079*age; c = [405 125 95 age_obl age_p2 age_p1 age_p3]; f = 1./c; handles.f = f; set(handles.edit11, 'String',num2str(c,'%1.1f ')); guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit29_CreateFcn(hObject, eventdata, handles) % hObject handle to edit29 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in radiobutton2. function radiobutton2_Callback(hObject, eventdata, handles) % hObject handle to radiobutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton2 set(handles.edit29, 'Enable', 'Off'); set(handles.radiobutton1, 'Value', 0); set(handles.edit11, 'Enable', 'On'); % --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over radiobutton2. function radiobutton2_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to radiobutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.edit29, 'Enable', 'Off'); set(handles.radiobutton1, 'Value', 0); set(handles.edit11, 'Enable', 'On'); % --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over radiobutton1. function radiobutton1_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to radiobutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.edit11, 'Enable', 'Off'); set(handles.radiobutton2, 'Value', 0); set(handles.edit29, 'Enable', 'On'); % -------------------------------------------------------------------- function file_loadmat_Callback(hObject, eventdata, handles) % hObject handle to file_loadmat (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [filename, ~] = uigetfile({'*.mat','MatLab MAT-file (*.mat)'},'Load data (*.mat)'); if filename == 0 else data=load(filename); assignin('base','data',data) end % -------------------------------------------------------------------- function file_import_Callback(hObject, eventdata, handles) % hObject handle to file_import (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [filename, pathname] = uigetfile({'*.txt;*.csv','Files (*.txt;*.csv)'},... 'Import data (*.csv,*.txt)'); if filename == 0 else aaa = [pathname,filename]; data = load(aaa); assignin('base','data',data) % guidata(hObject, handles); end % --- Executes when figure1 is resized. function figure1_SizeChangedFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
0
0.895902
1
0.895902
game-dev
MEDIA
0.237759
game-dev
0.741802
1
0.741802
hornyyy/Osu-Toy
3,915
osu.Game/Overlays/Comments/CommentsHeader.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics; using osu.Framework.Bindables; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Framework.Graphics.Sprites; using osuTK; using osu.Framework.Input.Events; using osu.Game.Graphics.Sprites; namespace osu.Game.Overlays.Comments { public class CommentsHeader : CompositeDrawable { public readonly Bindable<CommentsSortCriteria> Sort = new Bindable<CommentsSortCriteria>(); public readonly BindableBool ShowDeleted = new BindableBool(); private readonly Box background; public CommentsHeader() { RelativeSizeAxes = Axes.X; Height = 40; AddRangeInternal(new Drawable[] { background = new Box { RelativeSizeAxes = Axes.Both, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Horizontal = 50 }, Children = new Drawable[] { new OverlaySortTabControl<CommentsSortCriteria> { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Current = Sort }, new ShowDeletedButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Checked = { BindTarget = ShowDeleted } } } } }); } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { background.Colour = colourProvider.Background4; } private class ShowDeletedButton : HeaderButton { public readonly BindableBool Checked = new BindableBool(); private readonly SpriteIcon checkboxIcon; public ShowDeletedButton() { Add(new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(5, 0), Children = new Drawable[] { checkboxIcon = new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Size = new Vector2(10), }, new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold), Text = @"Show deleted" } }, }); } protected override void LoadComplete() { Checked.BindValueChanged(isChecked => checkboxIcon.Icon = isChecked.NewValue ? FontAwesome.Solid.CheckSquare : FontAwesome.Regular.Square, true); base.LoadComplete(); } protected override bool OnClick(ClickEvent e) { Checked.Value = !Checked.Value; return true; } } } public enum CommentsSortCriteria { [System.ComponentModel.Description(@"Recent")] New, Old, Top } }
0
0.851007
1
0.851007
game-dev
MEDIA
0.759106
game-dev,desktop-app
0.889243
1
0.889243
RedstoneTools/redstonetools-mod
2,358
src/client/java/tools/redstone/redstonetools/mixin/features/AirPlaceClientMixin.java
package tools.redstone.redstonetools.mixin.features; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.network.ClientPlayerInteractionManager; import net.minecraft.util.hit.HitResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; 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; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import tools.redstone.redstonetools.features.toggleable.AirPlaceFeature; @Mixin(MinecraftClient.class) public class AirPlaceClientMixin { @Shadow public HitResult crosshairTarget; @Inject(method = "doItemUse", at = @At(value = "HEAD")) public void doItemUse(CallbackInfo callbackInfo) { if (!isAirPlaceAllowed()) { return; } crosshairTarget = AirPlaceFeature.findAirPlaceBlockHit(getPlayer()); } @Inject(method = "doAttack", at = @At(value = "HEAD")) public void doAttack(CallbackInfoReturnable<Boolean> cir) { if (!isAirPlaceAllowed()) { return; } // Call interactionManager directly because the block is air, with which the player cannot interact var hit = AirPlaceFeature.findAirPlaceBlockHit(getPlayer()); getInteractionManager().attackBlock(hit.getBlockPos(), hit.getSide()); } @Unique private boolean isAirPlaceAllowed() { // If air place is disabled if (!AirPlaceFeature.INSTANCE.isEnabled()) { return false; } // If the hit result is already set if (crosshairTarget != null && crosshairTarget.getType() != HitResult.Type.MISS) { return false; } // If the player or interactionManager not initialized if (getPlayer() == null || getInteractionManager() == null) { return false; } // If air place isn't possible with the current // player equipment and state return AirPlaceFeature.canAirPlace(getPlayer()); } @Unique private MinecraftClient getMinecraftClient() { return (MinecraftClient) (Object) this; } @Unique private ClientPlayerEntity getPlayer() { return getMinecraftClient().player; } @Unique private ClientPlayerInteractionManager getInteractionManager() { return getMinecraftClient().interactionManager; } }
0
0.899478
1
0.899478
game-dev
MEDIA
0.941959
game-dev
0.865882
1
0.865882
Admer456/halflife-adm
125,825
src/game/server/entities/player.cpp
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /** * @file * functions dealing with the player */ #include <limits> #include <EASTL/fixed_string.h> #include "cbase.h" #include "CCorpse.h" #include "AmmoTypeSystem.h" #include "player.h" #include "trains.h" #include "nodes.h" #include "talkmonster.h" #include "squadmonster.h" #include "items/CWeaponBox.h" #include "military/COFSquadTalkMonster.h" #include "shake.h" #include "spawnpoints.h" #include "CHalfLifeCTFplay.h" #include "ctf/CHUDIconTrigger.h" #include "pm_shared.h" #include "hltv.h" #include "UserMessages.h" #include "client.h" #include "ServerLibrary.h" #include "ctf/ctf_goals.h" #include "rope/CRope.h" // #define DUCKFIX #define TRAIN_ACTIVE 0x80 #define TRAIN_NEW 0xc0 #define TRAIN_OFF 0x00 #define TRAIN_NEUTRAL 0x01 #define TRAIN_SLOW 0x02 #define TRAIN_MEDIUM 0x03 #define TRAIN_FAST 0x04 #define TRAIN_BACK 0x05 #define FLASH_DRAIN_TIME 1.2 // 100 units/3 minutes #define FLASH_CHARGE_TIME 0.2 // 100 units/20 seconds (seconds per unit) BEGIN_DATAMAP(CBasePlayer) DEFINE_FIELD(m_SuitLightType, FIELD_INTEGER), DEFINE_FIELD(m_flFlashLightTime, FIELD_TIME), DEFINE_FIELD(m_iFlashBattery, FIELD_INTEGER), DEFINE_FIELD(m_afButtonLast, FIELD_INTEGER), DEFINE_FIELD(m_afButtonPressed, FIELD_INTEGER), DEFINE_FIELD(m_afButtonReleased, FIELD_INTEGER), DEFINE_ARRAY(m_rgItems, FIELD_INTEGER, MAX_ITEMS), DEFINE_FIELD(m_afPhysicsFlags, FIELD_INTEGER), DEFINE_FIELD(m_flTimeStepSound, FIELD_TIME), DEFINE_FIELD(m_flTimeWeaponIdle, FIELD_TIME), DEFINE_FIELD(m_flSwimTime, FIELD_TIME), DEFINE_FIELD(m_flDuckTime, FIELD_TIME), DEFINE_FIELD(m_flWallJumpTime, FIELD_TIME), DEFINE_FIELD(m_flSuitUpdate, FIELD_TIME), DEFINE_ARRAY(m_rgSuitPlayList, FIELD_STRING, CSUITPLAYLIST), DEFINE_FIELD(m_iSuitPlayNext, FIELD_INTEGER), DEFINE_ARRAY(m_rgiSuitNoRepeat, FIELD_STRING, CSUITNOREPEAT), DEFINE_ARRAY(m_rgflSuitNoRepeatTime, FIELD_TIME, CSUITNOREPEAT), DEFINE_FIELD(m_lastDamageAmount, FIELD_INTEGER), DEFINE_ARRAY(m_rgpPlayerWeapons, FIELD_CLASSPTR, MAX_WEAPON_SLOTS), DEFINE_FIELD(m_pActiveWeapon, FIELD_CLASSPTR), DEFINE_FIELD(m_pLastWeapon, FIELD_CLASSPTR), DEFINE_FIELD(m_WeaponBits, FIELD_INT64), DEFINE_FIELD(m_HudFlags, FIELD_INTEGER), DEFINE_ARRAY(m_rgAmmo, FIELD_INTEGER, MAX_AMMO_TYPES), DEFINE_FIELD(m_idrowndmg, FIELD_INTEGER), DEFINE_FIELD(m_idrownrestored, FIELD_INTEGER), DEFINE_FIELD(m_iTrain, FIELD_INTEGER), DEFINE_FIELD(m_bitsHUDDamage, FIELD_INTEGER), DEFINE_FIELD(m_flFallVelocity, FIELD_FLOAT), DEFINE_FIELD(m_iTargetVolume, FIELD_INTEGER), DEFINE_FIELD(m_iWeaponVolume, FIELD_INTEGER), DEFINE_FIELD(m_iExtraSoundTypes, FIELD_INTEGER), DEFINE_FIELD(m_iWeaponFlash, FIELD_INTEGER), DEFINE_FIELD(m_fLongJump, FIELD_BOOLEAN), DEFINE_FIELD(m_JetpackEnabled, FIELD_BOOLEAN), DEFINE_FIELD(m_fInitHUD, FIELD_BOOLEAN), DEFINE_FIELD(m_tbdPrev, FIELD_TIME), DEFINE_FIELD(m_pTank, FIELD_EHANDLE), DEFINE_FIELD(m_hViewEntity, FIELD_EHANDLE), DEFINE_FIELD(m_iHideHUD, FIELD_INTEGER), DEFINE_FIELD(m_iFOV, FIELD_INTEGER), DEFINE_FIELD(m_SndRoomtype, FIELD_INTEGER), // Don't save these. Let the game recalculate the closest env_sound, and continue to use the last room type like it always has. // DEFINE_FIELD(m_SndLast, FIELD_EHANDLE), // DEFINE_FIELD(m_flSndRange, FIELD_FLOAT), DEFINE_FIELD(m_pRope, FIELD_CLASSPTR), DEFINE_FIELD(m_flLastClimbTime, FIELD_TIME), DEFINE_FIELD(m_bIsClimbing, FIELD_BOOLEAN), // Vanilla Op4 doesn't restore this. Not a big deal but it can cause you to teleport to the wrong area after a restore DEFINE_FIELD(m_DisplacerReturn, FIELD_POSITION_VECTOR), DEFINE_FIELD(m_DisplacerSndRoomtype, FIELD_INTEGER), DEFINE_FIELD(m_HudColor, FIELD_INTEGER), DEFINE_FIELD(m_bInfiniteAir, FIELD_BOOLEAN), DEFINE_FIELD(m_bInfiniteArmor, FIELD_BOOLEAN), // Save this in the unlikely case where the player spawns and saves and loads // in the split second between spawning and the first update. DEFINE_FIELD(m_FireSpawnTarget, FIELD_BOOLEAN), DEFINE_FUNCTION(PlayerDeathThink), // DEFINE_FIELD(m_fDeadTime, FIELD_FLOAT), // only used in multiplayer games // DEFINE_FIELD(m_fGameHUDInitialized, FIELD_INTEGER), // only used in multiplayer games // DEFINE_FIELD(m_flStopExtraSoundTime, FIELD_TIME), // DEFINE_FIELD(m_iPlayerSound, FIELD_INTEGER), // Don't restore, set in Precache() // DEFINE_FIELD(m_flgeigerRange, FIELD_FLOAT), // Don't restore, reset in Precache() // DEFINE_FIELD(m_flgeigerDelay, FIELD_FLOAT), // Don't restore, reset in Precache() // DEFINE_FIELD(m_igeigerRangePrev, FIELD_FLOAT), // Don't restore, reset in Precache() // DEFINE_FIELD(m_iStepLeft, FIELD_INTEGER), // Don't need to restore // DEFINE_ARRAY(m_szTextureName, FIELD_CHARACTER, TextureNameMax), // Don't need to restore // DEFINE_FIELD(m_chTextureType, FIELD_CHARACTER), // Don't need to restore // DEFINE_FIELD(m_fNoPlayerSound, FIELD_BOOLEAN), // Don't need to restore, debug // DEFINE_FIELD(m_iUpdateTime, FIELD_INTEGER), // Don't need to restore // DEFINE_FIELD(m_iClientHealth, FIELD_INTEGER), // Don't restore, client needs reset // DEFINE_FIELD(m_iClientBattery, FIELD_INTEGER), // Don't restore, client needs reset // DEFINE_FIELD(m_iClientHideHUD, FIELD_INTEGER), // Don't restore, client needs reset // DEFINE_FIELD(m_fWeapon, FIELD_BOOLEAN), // Don't restore, client needs reset // DEFINE_FIELD(m_nCustomSprayFrames, FIELD_INTEGER), // Don't restore, depends on server message after spawning and only matters in multiplayer // DEFINE_FIELD(m_vecAutoAim, FIELD_VECTOR), // Don't save/restore - this is recomputed // DEFINE_ARRAY(m_rgAmmoLast, FIELD_INTEGER, MAX_AMMO_TYPES), // Don't need to restore // DEFINE_FIELD(m_fOnTarget, FIELD_BOOLEAN), // Don't need to restore // DEFINE_FIELD(m_nCustomSprayFrames, FIELD_INTEGER), // Don't need to restore END_DATAMAP(); void CBasePlayer::Pain() { float flRndSound; // sound randomizer flRndSound = RANDOM_FLOAT(0, 1); if (flRndSound <= 0.33) EmitSound(CHAN_VOICE, "player/pl_pain5.wav", 1, ATTN_NORM); else if (flRndSound <= 0.66) EmitSound(CHAN_VOICE, "player/pl_pain6.wav", 1, ATTN_NORM); else EmitSound(CHAN_VOICE, "player/pl_pain7.wav", 1, ATTN_NORM); } Vector VecVelocityForDamage(float flDamage) { Vector vec(RANDOM_FLOAT(-100, 100), RANDOM_FLOAT(-100, 100), RANDOM_FLOAT(200, 300)); if (flDamage > -50) vec = vec * 0.7; else if (flDamage > -200) vec = vec * 2; else vec = vec * 10; return vec; } int TrainSpeed(int iSpeed, int iMax) { float fSpeed, fMax; int iRet = 0; fMax = (float)iMax; fSpeed = iSpeed; fSpeed = fSpeed / fMax; if (iSpeed < 0) iRet = TRAIN_BACK; else if (iSpeed == 0) iRet = TRAIN_NEUTRAL; else if (fSpeed < 0.33) iRet = TRAIN_SLOW; else if (fSpeed < 0.66) iRet = TRAIN_MEDIUM; else iRet = TRAIN_FAST; return iRet; } void CBasePlayer::DeathSound() { // water death sounds /* if (pev->waterlevel == 3) { EmitSound(CHAN_VOICE, "player/h2odeath.wav", 1, ATTN_NONE); return; } */ // temporarily using pain sounds for death sounds switch (RANDOM_LONG(1, 5)) { case 1: EmitSound(CHAN_VOICE, "player/pl_pain5.wav", 1, ATTN_NORM); break; case 2: EmitSound(CHAN_VOICE, "player/pl_pain6.wav", 1, ATTN_NORM); break; case 3: EmitSound(CHAN_VOICE, "player/pl_pain7.wav", 1, ATTN_NORM); break; } // play one of the suit death alarms EMIT_GROUPNAME_SUIT(this, "HEV_DEAD"); } bool CBasePlayer::GiveHealth(float flHealth, int bitsDamageType) { return CBaseMonster::GiveHealth(flHealth, bitsDamageType); } Vector CBasePlayer::GetGunPosition() { // UTIL_MakeVectors(pev->v_angle); // m_HackedGunPos = pev->view_ofs; Vector origin; origin = pev->origin + pev->view_ofs; return origin; } void CBasePlayer::TraceAttack(CBaseEntity* attacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType) { if (0 != pev->takedamage) { m_LastHitGroup = ptr->iHitgroup; switch (ptr->iHitgroup) { case HITGROUP_GENERIC: break; case HITGROUP_HEAD: flDamage *= GetSkillFloat("player_head"sv); break; case HITGROUP_CHEST: flDamage *= GetSkillFloat("player_chest"sv); break; case HITGROUP_STOMACH: flDamage *= GetSkillFloat("player_stomach"sv); break; case HITGROUP_LEFTARM: case HITGROUP_RIGHTARM: flDamage *= GetSkillFloat("player_arm"sv); break; case HITGROUP_LEFTLEG: case HITGROUP_RIGHTLEG: flDamage *= GetSkillFloat("player_leg"sv); break; default: break; } SpawnBlood(ptr->vecEndPos, BloodColor(), flDamage); // a little surface blood. TraceBleed(flDamage, vecDir, ptr, bitsDamageType); AddMultiDamage(attacker, this, flDamage, bitsDamageType); } } #define ARMOR_RATIO 0.2 // Armor Takes 80% of the damage #define ARMOR_BONUS 0.5 // Each Point of Armor is work 1/x points of health static const char* m_szSquadClasses[] = { "monster_human_grunt_ally", "monster_human_medic_ally", "monster_human_torch_ally"}; bool CBasePlayer::TakeDamage(CBaseEntity* inflictor, CBaseEntity* attacker, float flDamage, int bitsDamageType) { // have suit diagnose the problem - ie: report damage type int bitsDamage = bitsDamageType; bool ffound = true; bool fmajor; bool fcritical; bool fTookDamage; bool ftrivial; float flRatio; float flBonus; float flHealthPrev = pev->health; flBonus = ARMOR_BONUS; flRatio = ARMOR_RATIO; if ((bitsDamageType & DMG_BLAST) != 0 && g_pGameRules->IsMultiplayer()) { // blasts damage armor more. flBonus *= 2; } // Already dead if (!IsAlive()) return false; // go take the damage first CBaseEntity* pAttacker = CBaseEntity::Instance(attacker); if (auto attackerPlayer = ToBasePlayer(pAttacker); attackerPlayer) { // TODO: this is a pretty bad way to handle damage increase if ((attackerPlayer->m_iItems & CTFItem::Acceleration) != 0) { flDamage *= 1.6; EmitSound(CHAN_STATIC, "turret/tu_ping.wav", VOL_NORM, ATTN_NORM); } if (m_pFlag) { m_nLastShotBy = attackerPlayer->entindex(); m_flLastShotTime = gpGlobals->time; } } if (!g_pGameRules->FPlayerCanTakeDamage(this, pAttacker)) { // Refuse the damage return false; } // keep track of amount of damage last sustained m_lastDamageAmount = flDamage; // Armor. if (0 != pev->armorvalue && (bitsDamageType & (DMG_FALL | DMG_DROWN)) == 0) // armor doesn't protect against fall or drown damage! { float flNew = flDamage * flRatio; float flArmor; flArmor = (flDamage - flNew) * flBonus; // Does this use more armor than we have? if (flArmor > pev->armorvalue) { flArmor = pev->armorvalue; flArmor *= (1 / flBonus); flNew = flDamage - flArmor; if (!m_bInfiniteArmor) pev->armorvalue = 0; } else if (!m_bInfiniteArmor) pev->armorvalue -= flArmor; flDamage = flNew; } // this cast to INT is critical!!! If a player ends up with 0.5 health, the engine will get that // as an int (zero) and think the player is dead! (this will incite a clientside screentilt, etc) fTookDamage = CBaseMonster::TakeDamage(inflictor, attacker, (int)flDamage, bitsDamageType); // reset damage time countdown for each type of time based damage player just sustained { for (int i = 0; i < CDMG_TIMEBASED; i++) if ((bitsDamageType & (DMG_PARALYZE << i)) != 0) m_rgbTimeBasedDamage[i] = 0; } // tell director about it MESSAGE_BEGIN(MSG_SPEC, SVC_DIRECTOR); WRITE_BYTE(9); // command length in bytes WRITE_BYTE(DRC_CMD_EVENT); // take damage event WRITE_SHORT(entindex()); // index number of primary entity WRITE_SHORT(inflictor->entindex()); // index number of secondary entity WRITE_LONG(5); // eventflags (priority and flags) MESSAGE_END(); // how bad is it, doc? ftrivial = (pev->health > 75 || m_lastDamageAmount < 5); fmajor = (m_lastDamageAmount > 25); fcritical = (pev->health < 30); // handle all bits set in this damage message, // let the suit give player the diagnosis // UNDONE: add sounds for types of damage sustained (ie: burn, shock, slash ) // UNDONE: still need to record damage and heal messages for the following types // DMG_BURN // DMG_FREEZE // DMG_BLAST // DMG_SHOCK m_bitsDamageType |= bitsDamage; // Save this so we can report it to the client m_bitsHUDDamage = -1; // make sure the damage bits get resent while (fTookDamage && (!ftrivial || (bitsDamage & DMG_TIMEBASED) != 0) && ffound && 0 != bitsDamage) { ffound = false; if ((bitsDamage & DMG_CLUB) != 0) { if (fmajor) SetSuitUpdate("!HEV_DMG4", SUIT_NEXT_IN_30SEC); // minor fracture bitsDamage &= ~DMG_CLUB; ffound = true; } if ((bitsDamage & (DMG_FALL | DMG_CRUSH)) != 0) { if (fmajor) SetSuitUpdate("!HEV_DMG5", SUIT_NEXT_IN_30SEC); // major fracture else SetSuitUpdate("!HEV_DMG4", SUIT_NEXT_IN_30SEC); // minor fracture bitsDamage &= ~(DMG_FALL | DMG_CRUSH); ffound = true; } if ((bitsDamage & DMG_BULLET) != 0) { if (m_lastDamageAmount > 5) SetSuitUpdate("!HEV_DMG6", SUIT_NEXT_IN_30SEC); // blood loss detected // else // SetSuitUpdate("!HEV_DMG0", SUIT_NEXT_IN_30SEC); // minor laceration bitsDamage &= ~DMG_BULLET; ffound = true; } if ((bitsDamage & DMG_SLASH) != 0) { if (fmajor) SetSuitUpdate("!HEV_DMG1", SUIT_NEXT_IN_30SEC); // major laceration else SetSuitUpdate("!HEV_DMG0", SUIT_NEXT_IN_30SEC); // minor laceration bitsDamage &= ~DMG_SLASH; ffound = true; } if ((bitsDamage & DMG_SONIC) != 0) { if (fmajor) SetSuitUpdate("!HEV_DMG2", SUIT_NEXT_IN_1MIN); // internal bleeding bitsDamage &= ~DMG_SONIC; ffound = true; } if ((bitsDamage & (DMG_POISON | DMG_PARALYZE)) != 0) { SetSuitUpdate("!HEV_DMG3", SUIT_NEXT_IN_1MIN); // blood toxins detected bitsDamage &= ~(DMG_POISON | DMG_PARALYZE); ffound = true; } if ((bitsDamage & DMG_ACID) != 0) { SetSuitUpdate("!HEV_DET1", SUIT_NEXT_IN_1MIN); // hazardous chemicals detected bitsDamage &= ~DMG_ACID; ffound = true; } if ((bitsDamage & DMG_NERVEGAS) != 0) { SetSuitUpdate("!HEV_DET0", SUIT_NEXT_IN_1MIN); // biohazard detected bitsDamage &= ~DMG_NERVEGAS; ffound = true; } if ((bitsDamage & DMG_RADIATION) != 0) { SetSuitUpdate("!HEV_DET2", SUIT_NEXT_IN_1MIN); // radiation detected bitsDamage &= ~DMG_RADIATION; ffound = true; } if ((bitsDamage & DMG_SHOCK) != 0) { bitsDamage &= ~DMG_SHOCK; ffound = true; } } pev->punchangle.x = -2; if (fTookDamage && !ftrivial && fmajor && flHealthPrev >= 75) { // first time we take major damage... // turn automedic on if not on SetSuitUpdate("!HEV_MED1", SUIT_NEXT_IN_30MIN); // automedic on // give morphine shot if not given recently SetSuitUpdate("!HEV_HEAL7", SUIT_NEXT_IN_30MIN); // morphine shot } if (fTookDamage && !ftrivial && fcritical && flHealthPrev < 75) { // already took major damage, now it's critical... if (pev->health < 6) SetSuitUpdate("!HEV_HLTH3", SUIT_NEXT_IN_10MIN); // near death else if (pev->health < 20) SetSuitUpdate("!HEV_HLTH2", SUIT_NEXT_IN_10MIN); // health critical // give critical health warnings if (!RANDOM_LONG(0, 3) && flHealthPrev < 50) SetSuitUpdate("!HEV_DMG7", SUIT_NEXT_IN_5MIN); // seek medical attention } // if we're taking time based damage, warn about its continuing effects if (fTookDamage && (bitsDamageType & DMG_TIMEBASED) != 0 && flHealthPrev < 75) { if (flHealthPrev < 50) { if (!RANDOM_LONG(0, 3)) SetSuitUpdate("!HEV_DMG7", SUIT_NEXT_IN_5MIN); // seek medical attention } else SetSuitUpdate("!HEV_HLTH1", SUIT_NEXT_IN_10MIN); // health dropping } // Make all grunts following me attack the NPC that attacked me if (pAttacker) { auto enemy = pAttacker->MyMonsterPointer(); if (!enemy || enemy->IRelationship(this) == Relationship::Ally) { return fTookDamage; } for (std::size_t i = 0; i < std::size(m_szSquadClasses); ++i) { for (auto ally : UTIL_FindEntitiesByClassname<CBaseEntity>(m_szSquadClasses[i])) { auto squadAlly = ally->MySquadTalkMonsterPointer(); if (squadAlly && squadAlly->m_hTargetEnt && squadAlly->m_hTargetEnt->IsPlayer()) { squadAlly->SquadMakeEnemy(enemy); } } } } return fTookDamage; } void CBasePlayer::PackDeadPlayerItems() { int iWeaponRules; int iAmmoRules; int i; CBasePlayerWeapon* rgpPackWeapons[MAX_WEAPONS]; int iPackAmmo[MAX_AMMO_TYPES + 1]; int iPW = 0; // index into packweapons array int iPA = 0; // index into packammo array memset(rgpPackWeapons, 0, sizeof(rgpPackWeapons)); memset(iPackAmmo, -1, sizeof(iPackAmmo)); // get the game rules iWeaponRules = g_pGameRules->DeadPlayerWeapons(this); iAmmoRules = g_pGameRules->DeadPlayerAmmo(this); if (iWeaponRules == GR_PLR_DROP_GUN_NO && iAmmoRules == GR_PLR_DROP_AMMO_NO) { // nothing to pack. Remove the weapons and return. Don't call create on the box! RemoveAllItems(true); return; } // go through all of the weapons and make a list of the ones to pack for (i = 0; i < MAX_WEAPON_SLOTS; i++) { if (m_rgpPlayerWeapons[i]) { // there's a weapon here. Should I pack it? CBasePlayerWeapon* weapon = m_rgpPlayerWeapons[i]; while (weapon) { switch (iWeaponRules) { case GR_PLR_DROP_GUN_ACTIVE: if (m_pActiveWeapon && weapon == m_pActiveWeapon) { // this is the active item. Pack it. rgpPackWeapons[iPW++] = weapon; } break; case GR_PLR_DROP_GUN_ALL: rgpPackWeapons[iPW++] = weapon; break; default: break; } weapon = weapon->m_pNext; } } } // now go through ammo and make a list of which types to pack. if (iAmmoRules != GR_PLR_DROP_AMMO_NO) { for (i = 0; i < MAX_AMMO_TYPES; i++) { if (m_rgAmmo[i] > 0) { // player has some ammo of this type. switch (iAmmoRules) { case GR_PLR_DROP_AMMO_ALL: iPackAmmo[iPA++] = i; break; case GR_PLR_DROP_AMMO_ACTIVE: if (m_pActiveWeapon && i == m_pActiveWeapon->PrimaryAmmoIndex()) { // this is the primary ammo type for the active weapon iPackAmmo[iPA++] = i; } else if (m_pActiveWeapon && i == m_pActiveWeapon->SecondaryAmmoIndex()) { // this is the secondary ammo type for the active weapon iPackAmmo[iPA++] = i; } break; default: break; } } } } // create a box to pack the stuff into. CWeaponBox* pWeaponBox = (CWeaponBox*)CBaseEntity::Create("weaponbox", pev->origin, pev->angles, this); pWeaponBox->pev->angles.x = 0; // don't let weaponbox tilt. pWeaponBox->pev->angles.z = 0; pWeaponBox->SetThink(&CWeaponBox::Kill); pWeaponBox->pev->nextthink = gpGlobals->time + 120; // back these two lists up to their first elements iPA = 0; iPW = 0; // pack the ammo while (iPackAmmo[iPA] != -1) { pWeaponBox->PackAmmo(MAKE_STRING(g_AmmoTypes.GetByIndex(iPackAmmo[iPA])->Name.c_str()), m_rgAmmo[iPackAmmo[iPA]]); iPA++; } // now pack all of the items in the lists while (rgpPackWeapons[iPW]) { // weapon unhooked from the player. Pack it into der box. pWeaponBox->PackWeapon(rgpPackWeapons[iPW]); iPW++; } pWeaponBox->pev->velocity = pev->velocity * 1.2; // weaponbox has player's velocity, then some. RemoveAllItems(true); // now strip off everything that wasn't handled by the code above. } void CBasePlayer::RemoveAllItems(bool removeSuit) { if (m_pActiveWeapon) { ResetAutoaim(); m_pActiveWeapon->Holster(); m_pActiveWeapon = nullptr; } m_pLastWeapon = nullptr; if (m_pTank != nullptr) { m_pTank->Use(this, this, USE_OFF, 0); m_pTank = nullptr; } int i; CBasePlayerWeapon* pendingWeapon; for (i = 0; i < MAX_WEAPON_SLOTS; i++) { m_pActiveWeapon = m_rgpPlayerWeapons[i]; while (m_pActiveWeapon) { pendingWeapon = m_pActiveWeapon->m_pNext; m_pActiveWeapon->Kill(); m_pActiveWeapon = pendingWeapon; } m_rgpPlayerWeapons[i] = nullptr; } m_pActiveWeapon = nullptr; pev->viewmodel = string_t::Null; pev->weaponmodel = string_t::Null; m_WeaponBits = 0ULL; // Re-add suit bit if needed. SetHasSuit(!removeSuit); for (i = 0; i < MAX_AMMO_TYPES; i++) m_rgAmmo[i] = 0; UpdateClientData(); } void CBasePlayer::Killed(CBaseEntity* attacker, int iGib) { CSound* pSound; // Holster weapon immediately, to allow it to cleanup if (m_pActiveWeapon) m_pActiveWeapon->Holster(); g_pGameRules->PlayerKilled(this, attacker, g_pevLastInflictor); if (m_pTank != nullptr) { m_pTank->Use(this, this, USE_OFF, 0); m_pTank = nullptr; } // this client isn't going to be thinking for a while, so reset the sound until they respawn pSound = CSoundEnt::SoundPointerForIndex(CSoundEnt::ClientSoundIndex(edict())); { if (pSound) { pSound->Reset(); } } SetAnimation(PLAYER_DIE); m_iRespawnFrames = 0; pev->deadflag = DEAD_DYING; pev->movetype = MOVETYPE_TOSS; ClearBits(pev->flags, FL_ONGROUND); if (pev->velocity.z < 10) pev->velocity.z += RANDOM_FLOAT(0, 300); // clear out the suit message cache so we don't keep chattering SetSuitUpdate(nullptr, 0); // send "health" update message to zero m_iClientHealth = 0; MESSAGE_BEGIN(MSG_ONE, gmsgHealth, nullptr, this); WRITE_SHORT(m_iClientHealth); MESSAGE_END(); // Tell Ammo Hud that the player is dead MESSAGE_BEGIN(MSG_ONE, gmsgCurWeapon, nullptr, this); WRITE_BYTE(0); WRITE_BYTE(0XFF); WRITE_BYTE(0xFF); MESSAGE_END(); // reset FOV m_iFOV = m_iClientFOV = 0; MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, nullptr, this); WRITE_BYTE(0); MESSAGE_END(); // UNDONE: Put this in, but add FFADE_PERMANENT and make fade time 8.8 instead of 4.12 // UTIL_ScreenFade( edict(), Vector(128,0,0), 6, 15, 255, FFADE_OUT | FFADE_MODULATE ); if ((pev->health < -40 && iGib != GIB_NEVER) || iGib == GIB_ALWAYS) { pev->solid = SOLID_NOT; GibMonster(); // This clears pev->model pev->effects |= EF_NODRAW; return; } DeathSound(); pev->angles.x = 0; pev->angles.z = 0; SetThink(&CBasePlayer::PlayerDeathThink); pev->nextthink = gpGlobals->time + 0.1; } void CBasePlayer::SetAnimation(PLAYER_ANIM playerAnim) { int animDesired; float speed; char szAnim[64]; speed = pev->velocity.Length2D(); if ((pev->flags & FL_FROZEN) != 0) { speed = 0; playerAnim = PLAYER_IDLE; } switch (playerAnim) { case PLAYER_JUMP: m_IdealActivity = ACT_HOP; break; case PLAYER_SUPERJUMP: m_IdealActivity = ACT_LEAP; break; case PLAYER_DIE: m_IdealActivity = ACT_DIESIMPLE; m_IdealActivity = GetDeathActivity(); break; case PLAYER_ATTACK1: switch (m_Activity) { case ACT_HOVER: case ACT_SWIM: case ACT_HOP: case ACT_LEAP: case ACT_DIESIMPLE: m_IdealActivity = m_Activity; break; default: m_IdealActivity = ACT_RANGE_ATTACK1; break; } break; case PLAYER_IDLE: case PLAYER_WALK: if (!FBitSet(pev->flags, FL_ONGROUND) && (m_Activity == ACT_HOP || m_Activity == ACT_LEAP)) // Still jumping { m_IdealActivity = m_Activity; } else if (pev->waterlevel > WaterLevel::Feet) { if (speed == 0) m_IdealActivity = ACT_HOVER; else m_IdealActivity = ACT_SWIM; } else { m_IdealActivity = ACT_WALK; } break; case PLAYER_GRAPPLE: { if (FBitSet(pev->flags, FL_ONGROUND)) { if (pev->waterlevel > WaterLevel::Feet) { if (speed == 0) m_IdealActivity = ACT_HOVER; else m_IdealActivity = ACT_SWIM; } else { m_IdealActivity = ACT_WALK; } } else if (speed == 0) { m_IdealActivity = ACT_HOVER; } else { m_IdealActivity = ACT_SWIM; } } break; } switch (m_IdealActivity) { case ACT_HOVER: case ACT_LEAP: case ACT_SWIM: case ACT_HOP: case ACT_DIESIMPLE: default: if (m_Activity == m_IdealActivity) return; m_Activity = m_IdealActivity; animDesired = LookupActivity(m_Activity); // Already using the desired animation? if (pev->sequence == animDesired) return; pev->gaitsequence = 0; pev->sequence = animDesired; pev->frame = 0; ResetSequenceInfo(); return; case ACT_RANGE_ATTACK1: if (FBitSet(pev->flags, FL_DUCKING)) // crouching strcpy(szAnim, "crouch_shoot_"); else strcpy(szAnim, "ref_shoot_"); strcat(szAnim, m_szAnimExtention); animDesired = LookupSequence(szAnim); if (animDesired == -1) animDesired = 0; if (pev->sequence != animDesired || !m_fSequenceLoops) { pev->frame = 0; } if (!m_fSequenceLoops) { pev->effects |= EF_NOINTERP; } m_Activity = m_IdealActivity; pev->sequence = animDesired; ResetSequenceInfo(); break; case ACT_WALK: if (m_Activity != ACT_RANGE_ATTACK1 || m_fSequenceFinished) { if (FBitSet(pev->flags, FL_DUCKING)) // crouching strcpy(szAnim, "crouch_aim_"); else strcpy(szAnim, "ref_aim_"); strcat(szAnim, m_szAnimExtention); animDesired = LookupSequence(szAnim); if (animDesired == -1) animDesired = 0; m_Activity = ACT_WALK; } else { animDesired = pev->sequence; } } if (FBitSet(pev->flags, FL_DUCKING)) { if (speed == 0) { pev->gaitsequence = LookupActivity(ACT_CROUCHIDLE); // pev->gaitsequence = LookupActivity( ACT_CROUCH ); } else { pev->gaitsequence = LookupActivity(ACT_CROUCH); } } else if (speed > 220) { pev->gaitsequence = LookupActivity(ACT_RUN); } else if (speed > 0) { pev->gaitsequence = LookupActivity(ACT_WALK); } else { // pev->gaitsequence = LookupActivity( ACT_WALK ); pev->gaitsequence = LookupSequence("deep_idle"); } // Already using the desired animation? if (pev->sequence == animDesired) return; // Logger->debug("Set animation to {}", animDesired); // Reset to first frame of desired animation pev->sequence = animDesired; pev->frame = 0; ResetSequenceInfo(); } #define AIRTIME 12 // lung full of air lasts this many seconds void CBasePlayer::WaterMove() { int air; if (pev->movetype == MOVETYPE_NOCLIP) return; if (pev->health < 0) return; // waterlevel 0 - not in water // waterlevel 1 - feet in water // waterlevel 2 - waist in water // waterlevel 3 - head in water if (pev->waterlevel != WaterLevel::Head) { // not underwater // play 'up for air' sound if (pev->air_finished < gpGlobals->time) EmitSound(CHAN_VOICE, "player/pl_wade1.wav", 1, ATTN_NORM); else if (pev->air_finished < gpGlobals->time + 9) EmitSound(CHAN_VOICE, "player/pl_wade2.wav", 1, ATTN_NORM); pev->air_finished = gpGlobals->time + AIRTIME; pev->dmg = 2; // if we took drowning damage, give it back slowly if (m_idrowndmg > m_idrownrestored) { // set drowning damage bit. hack - dmg_drownrecover actually // makes the time based damage code 'give back' health over time. // make sure counter is cleared so we start count correctly. // NOTE: this actually causes the count to continue restarting // until all drowning damage is healed. m_bitsDamageType |= DMG_DROWNRECOVER; m_bitsDamageType &= ~DMG_DROWN; m_rgbTimeBasedDamage[itbd_DrownRecover] = 0; } } else { // fully under water // stop restoring damage while underwater m_bitsDamageType &= ~DMG_DROWNRECOVER; m_rgbTimeBasedDamage[itbd_DrownRecover] = 0; if (!m_bInfiniteAir && pev->air_finished < gpGlobals->time) // drown! { if (pev->pain_finished < gpGlobals->time) { // take drowning damage pev->dmg += 1; if (pev->dmg > 5) pev->dmg = 5; TakeDamage(World, World, pev->dmg, DMG_DROWN); pev->pain_finished = gpGlobals->time + 1; // track drowning damage, give it back when // player finally takes a breath m_idrowndmg += pev->dmg; } } else { m_bitsDamageType &= ~DMG_DROWN; } } if (WaterLevel::Dry == pev->waterlevel) { if (FBitSet(pev->flags, FL_INWATER)) { ClearBits(pev->flags, FL_INWATER); } return; } // make bubbles if (pev->waterlevel == WaterLevel::Head) { air = (int)(pev->air_finished - gpGlobals->time); if (!RANDOM_LONG(0, 0x1f) && RANDOM_LONG(0, AIRTIME - 1) >= air) { switch (RANDOM_LONG(0, 3)) { case 0: EmitSound(CHAN_BODY, "player/pl_swim1.wav", 0.8, ATTN_NORM); break; case 1: EmitSound(CHAN_BODY, "player/pl_swim2.wav", 0.8, ATTN_NORM); break; case 2: EmitSound(CHAN_BODY, "player/pl_swim3.wav", 0.8, ATTN_NORM); break; case 3: EmitSound(CHAN_BODY, "player/pl_swim4.wav", 0.8, ATTN_NORM); break; } } } if (pev->watertype == CONTENTS_LAVA) // do damage { if (pev->dmgtime < gpGlobals->time) TakeDamage(World, World, 10 * static_cast<int>(pev->waterlevel), DMG_BURN); } else if (pev->watertype == CONTENTS_SLIME) // do damage { pev->dmgtime = gpGlobals->time + 1; TakeDamage(World, World, 4 * static_cast<int>(pev->waterlevel), DMG_ACID); } if (!FBitSet(pev->flags, FL_INWATER)) { SetBits(pev->flags, FL_INWATER); pev->dmgtime = 0; } } bool CBasePlayer::IsOnLadder() { return (pev->movetype == MOVETYPE_FLY); } void CBasePlayer::PlayerDeathThink() { float flForward; if (FBitSet(pev->flags, FL_ONGROUND)) { flForward = pev->velocity.Length() - 20; if (flForward <= 0) pev->velocity = g_vecZero; else pev->velocity = flForward * pev->velocity.Normalize(); } if (HasWeapons()) { // we drop the guns here because weapons that have an area effect and can kill their user // will sometimes crash coming back from CBasePlayer::Killed() if they kill their owner because the // player class sometimes is freed. It's safer to manipulate the weapons once we know // we aren't calling into any of their code anymore through the player pointer. PackDeadPlayerItems(); } if (0 != pev->modelindex && (!m_fSequenceFinished) && (pev->deadflag == DEAD_DYING)) { StudioFrameAdvance(); m_iRespawnFrames++; // Note, these aren't necessarily real "frames", so behavior is dependent on # of client movement commands if (m_iRespawnFrames < 120) // Animations should be no longer than this return; } // once we're done animating our death and we're on the ground, we want to set movetype to None so our dead body won't do collisions and stuff anymore // this prevents a bug where the dead body would go to a player's head if he walked over it while the dead player was clicking their button to respawn if (pev->movetype != MOVETYPE_NONE && FBitSet(pev->flags, FL_ONGROUND)) pev->movetype = MOVETYPE_NONE; if (pev->deadflag == DEAD_DYING) pev->deadflag = DEAD_DEAD; StopAnimation(); pev->effects |= EF_NOINTERP; pev->framerate = 0.0; bool fAnyButtonDown = (pev->button & ~IN_SCORE) != 0; // wait for all buttons released if (pev->deadflag == DEAD_DEAD) { if (fAnyButtonDown) return; if (g_pGameRules->FPlayerCanRespawn(this)) { m_fDeadTime = gpGlobals->time; pev->deadflag = DEAD_RESPAWNABLE; } return; } // if the player has been dead for one second longer than allowed by forcerespawn, // forcerespawn isn't on. Send the player off to an intermission camera until they // choose to respawn. if (g_pGameRules->IsMultiplayer() && (gpGlobals->time > (m_fDeadTime + 6)) && (m_afPhysicsFlags & PFLAG_OBSERVER) == 0) { // go to dead camera. StartDeathCam(); } if (0 != pev->iuser1) // player is in spectator mode return; // wait for any button down, or mp_forcerespawn is set and the respawn time is up if (!fAnyButtonDown && !(g_pGameRules->IsMultiplayer() && forcerespawn.value > 0 && (gpGlobals->time > (m_fDeadTime + 5)))) return; pev->button = 0; m_iRespawnFrames = 0; // Logger->debug("Respawn"); respawn(this, (m_afPhysicsFlags & PFLAG_OBSERVER) == 0); // don't copy a corpse if we're in deathcam. pev->nextthink = -1; } void CBasePlayer::StartDeathCam() { if (pev->view_ofs == g_vecZero) { // don't accept subsequent attempts to StartDeathCam() return; } auto pSpot = UTIL_FindEntityByClassname(nullptr, "info_intermission"); if (!FNullEnt(pSpot)) { // at least one intermission spot in the world. int iRand = RANDOM_LONG(0, 3); CBaseEntity* pNewSpot; while (iRand > 0) { pNewSpot = UTIL_FindEntityByClassname(pSpot, "info_intermission"); if (pNewSpot) { pSpot = pNewSpot; } iRand--; } CopyToBodyQue(this); SetOrigin(pSpot->pev->origin); pev->angles = pev->v_angle = pSpot->pev->v_angle; } else { // no intermission spot. Push them up in the air, looking down at their corpse TraceResult tr; CopyToBodyQue(this); UTIL_TraceLine(pev->origin, pev->origin + Vector(0, 0, 128), ignore_monsters, edict(), &tr); SetOrigin(tr.vecEndPos); pev->angles = pev->v_angle = UTIL_VecToAngles(tr.vecEndPos - pev->origin); } // start death cam m_afPhysicsFlags |= PFLAG_OBSERVER; pev->view_ofs = g_vecZero; pev->fixangle = FIXANGLE_ABSOLUTE; pev->solid = SOLID_NOT; pev->takedamage = DAMAGE_NO; pev->movetype = MOVETYPE_NONE; pev->modelindex = 0; } void CBasePlayer::StartObserver(Vector vecPosition, Vector vecViewAngle) { // clear any clientside entities attached to this player MESSAGE_BEGIN(MSG_PAS, SVC_TEMPENTITY, pev->origin); WRITE_BYTE(TE_KILLPLAYERATTACHMENTS); WRITE_BYTE((byte)entindex()); MESSAGE_END(); // Holster weapon immediately, to allow it to cleanup if (m_pActiveWeapon) m_pActiveWeapon->Holster(); if (m_pTank != nullptr) { m_pTank->Use(this, this, USE_OFF, 0); m_pTank = nullptr; } // clear out the suit message cache so we don't keep chattering SetSuitUpdate(nullptr, 0); // Tell Ammo Hud that the player is dead MESSAGE_BEGIN(MSG_ONE, gmsgCurWeapon, nullptr, this); WRITE_BYTE(0); WRITE_BYTE(0XFF); WRITE_BYTE(0xFF); MESSAGE_END(); // reset FOV m_iFOV = m_iClientFOV = 0; MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, nullptr, this); WRITE_BYTE(0); MESSAGE_END(); // Setup flags m_iHideHUD = (HIDEHUD_HEALTH | HIDEHUD_WEAPONS); m_afPhysicsFlags |= PFLAG_OBSERVER; pev->effects = EF_NODRAW; pev->view_ofs = g_vecZero; pev->angles = pev->v_angle = vecViewAngle; pev->fixangle = FIXANGLE_ABSOLUTE; pev->solid = SOLID_NOT; pev->takedamage = DAMAGE_NO; pev->movetype = MOVETYPE_NONE; ClearBits(m_afPhysicsFlags, PFLAG_DUCKING); ClearBits(pev->flags, FL_DUCKING); pev->deadflag = DEAD_RESPAWNABLE; pev->health = 1; // Clear out the status bar m_fInitHUD = true; pev->team = string_t::Null; MESSAGE_BEGIN(MSG_ALL, gmsgTeamInfo); WRITE_BYTE(entindex()); WRITE_STRING(""); MESSAGE_END(); // Remove all the player's stuff RemoveAllItems(false); // Move them to the new position SetOrigin(vecPosition); // Find a player to watch m_flNextObserverInput = 0; Observer_SetMode(m_iObserverLastMode); } #define PLAYER_SEARCH_RADIUS (float)64 void CBasePlayer::PlayerUse() { if (IsObserver()) return; // Was use pressed or released? if (((pev->button | m_afButtonPressed | m_afButtonReleased) & IN_USE) == 0) return; // Hit Use on a train? if ((m_afButtonPressed & IN_USE) != 0) { if (m_pTank != nullptr) { // Stop controlling the tank // TODO: Send HUD Update m_pTank->Use(this, this, USE_OFF, 0); m_pTank = nullptr; return; } else { if ((m_afPhysicsFlags & PFLAG_ONTRAIN) != 0) { m_afPhysicsFlags &= ~PFLAG_ONTRAIN; m_iTrain = TRAIN_NEW | TRAIN_OFF; return; } else { // Start controlling the train! CBaseEntity* pTrain = CBaseEntity::Instance(pev->groundentity); if (pTrain && (pev->button & IN_JUMP) == 0 && FBitSet(pev->flags, FL_ONGROUND) && (pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) != 0 && pTrain->OnControls(this)) { m_afPhysicsFlags |= PFLAG_ONTRAIN; m_iTrain = TrainSpeed(pTrain->pev->speed, pTrain->pev->impulse); m_iTrain |= TRAIN_NEW; EmitSound(CHAN_ITEM, "plats/train_use1.wav", 0.8, ATTN_NORM); return; } } } } CBaseEntity* pObject = nullptr; CBaseEntity* pClosest = nullptr; Vector vecLOS; float flMaxDot = VIEW_FIELD_NARROW; float flDot; UTIL_MakeVectors(pev->v_angle); // so we know which way we are facing while ((pObject = UTIL_FindEntityInSphere(pObject, pev->origin, PLAYER_SEARCH_RADIUS)) != nullptr) { // Special behavior for ropes: check if the player is close enough to the rope segment origin if (pObject->ClassnameIs("rope_segment")) { if ((pev->origin - pObject->pev->origin).Length() > PLAYER_SEARCH_RADIUS) { continue; } } if ((pObject->ObjectCaps() & (FCAP_IMPULSE_USE | FCAP_CONTINUOUS_USE | FCAP_ONOFF_USE)) != 0) { // !!!PERFORMANCE- should this check be done on a per case basis AFTER we've determined that // this object is actually usable? This dot is being done for every object within PLAYER_SEARCH_RADIUS // when player hits the use key. How many objects can be in that area, anyway? (sjb) vecLOS = (VecBModelOrigin(pObject) - (pev->origin + pev->view_ofs)); // This essentially moves the origin of the target to the corner nearest the player to test to see // if it's "hull" is in the view cone vecLOS = UTIL_ClampVectorToBox(vecLOS, pObject->pev->size * 0.5); flDot = DotProduct(vecLOS, gpGlobals->v_forward); if (flDot > flMaxDot) { // only if the item is in front of the user pClosest = pObject; flMaxDot = flDot; // Logger->debug("{} : {}", STRING(pObject->pev->classname), flDot); } // Logger->debug("{} : {}", STRING(pObject->pev->classname), flDot); } } pObject = pClosest; // Found an object if (pObject) { //!!!UNDONE: traceline here to prevent USEing buttons through walls int caps = pObject->ObjectCaps(); if ((m_afButtonPressed & IN_USE) != 0) EmitSound(CHAN_ITEM, "common/wpn_select.wav", 0.4, ATTN_NORM); if (((pev->button & IN_USE) != 0 && (caps & FCAP_CONTINUOUS_USE) != 0) || ((m_afButtonPressed & IN_USE) != 0 && (caps & (FCAP_IMPULSE_USE | FCAP_ONOFF_USE)) != 0)) { if ((caps & FCAP_CONTINUOUS_USE) != 0) m_afPhysicsFlags |= PFLAG_USING; pObject->Use(this, this, USE_SET, 1); } // UNDONE: Send different USE codes for ON/OFF. Cache last ONOFF_USE object to send 'off' if you turn away else if ((m_afButtonReleased & IN_USE) != 0 && (pObject->ObjectCaps() & FCAP_ONOFF_USE) != 0) // BUGBUG This is an "off" use { pObject->Use(this, this, USE_SET, 0); } } else { if ((m_afButtonPressed & IN_USE) != 0) EmitSound(CHAN_ITEM, "common/wpn_denyselect.wav", 0.4, ATTN_NORM); } } void CBasePlayer::Jump() { if (FBitSet(pev->flags, FL_WATERJUMP)) return; if (pev->waterlevel >= WaterLevel::Waist) { return; } // jump velocity is sqrt( height * gravity * 2) // If this isn't the first frame pressing the jump button, break out. if (!FBitSet(m_afButtonPressed, IN_JUMP)) return; // don't pogo stick if ((pev->flags & FL_ONGROUND) == 0 || !pev->groundentity) { return; } // many features in this function use v_forward, so makevectors now. UTIL_MakeVectors(pev->angles); // ClearBits(pev->flags, FL_ONGROUND); // don't stairwalk SetAnimation(PLAYER_JUMP); if (m_fLongJump && (pev->button & IN_DUCK) != 0 && (pev->flDuckTime > 0) && pev->velocity.Length() > 50) { SetAnimation(PLAYER_SUPERJUMP); } // If you're standing on a conveyor, add it's velocity to yours (for momentum) CBaseEntity* ground = GetGroundEntity(); if (ground && (ground->pev->flags & FL_CONVEYOR) != 0) { pev->velocity = pev->velocity + pev->basevelocity; } } // This is a glorious hack to find free space when you've crouched into some solid space // Our crouching collisions do not work correctly for some reason and this is easier // than fixing the problem :( void FixPlayerCrouchStuck(CBaseEntity* pPlayer) { TraceResult trace; // Move up as many as 18 pixels if the player is stuck. for (int i = 0; i < 18; i++) { UTIL_TraceHull(pPlayer->pev->origin, pPlayer->pev->origin, dont_ignore_monsters, head_hull, pPlayer->edict(), &trace); if (0 != trace.fStartSolid) pPlayer->pev->origin.z++; else break; } } void CBasePlayer::Duck() { if ((pev->button & IN_DUCK) != 0) { if (m_IdealActivity != ACT_LEAP) { SetAnimation(PLAYER_WALK); } } } void CBasePlayer::AddPoints(int score, bool bAllowNegativeScore) { // Positive score always adds if (score < 0) { if (!bAllowNegativeScore) { if (pev->frags < 0) // Can't go more negative return; if (-score > pev->frags) // Will this go negative? { score = -pev->frags; // Sum will be 0 } } } pev->frags += score; SendScoreInfoAll(); } void CBasePlayer::AddPointsToTeam(int score, bool bAllowNegativeScore) { int index = entindex(); for (int i = 1; i <= gpGlobals->maxClients; i++) { auto pPlayer = UTIL_PlayerByIndex(i); if (pPlayer && i != index) { if (g_pGameRules->PlayerRelationship(this, pPlayer) == GR_TEAMMATE) { pPlayer->AddPoints(score, bAllowNegativeScore); } } } } void CBasePlayer::InitStatusBar() { m_flStatusBarDisappearDelay = 0; m_SbarString1[0] = m_SbarString0[0] = 0; } void CBasePlayer::UpdateStatusBar() { int newSBarState[SBAR_END]; char sbuf0[SBAR_STRING_SIZE]; char sbuf1[SBAR_STRING_SIZE]; memset(newSBarState, 0, sizeof(newSBarState)); strcpy(sbuf0, m_SbarString0); strcpy(sbuf1, m_SbarString1); // Find an ID Target TraceResult tr; UTIL_MakeVectors(pev->v_angle + pev->punchangle); Vector vecSrc = EyePosition(); Vector vecEnd = vecSrc + (gpGlobals->v_forward * MAX_ID_RANGE); UTIL_TraceLine(vecSrc, vecEnd, dont_ignore_monsters, edict(), &tr); if (tr.flFraction != 1.0) { if (!FNullEnt(tr.pHit)) { CBaseEntity* pEntity = CBaseEntity::Instance(tr.pHit); if (pEntity->IsPlayer()) { newSBarState[SBAR_ID_TARGETNAME] = pEntity->entindex(); strcpy(sbuf1, "1 %p1\n2 Health: %i2%%\n3 Armor: %i3%%"); // allies and medics get to see the targets health if (g_pGameRules->PlayerRelationship(this, pEntity) == GR_TEAMMATE) { newSBarState[SBAR_ID_TARGETHEALTH] = 100 * (pEntity->pev->health / pEntity->pev->max_health); newSBarState[SBAR_ID_TARGETARMOR] = pEntity->pev->armorvalue; // No need to get it % based since 100 it's the max. } m_flStatusBarDisappearDelay = gpGlobals->time + 1.0; } } else if (m_flStatusBarDisappearDelay > gpGlobals->time) { // hold the values for a short amount of time after viewing the object newSBarState[SBAR_ID_TARGETNAME] = m_izSBarState[SBAR_ID_TARGETNAME]; newSBarState[SBAR_ID_TARGETHEALTH] = m_izSBarState[SBAR_ID_TARGETHEALTH]; newSBarState[SBAR_ID_TARGETARMOR] = m_izSBarState[SBAR_ID_TARGETARMOR]; } } bool bForceResend = false; if (0 != strcmp(sbuf0, m_SbarString0)) { MESSAGE_BEGIN(MSG_ONE, gmsgStatusText, nullptr, this); WRITE_BYTE(0); WRITE_STRING(sbuf0); MESSAGE_END(); strcpy(m_SbarString0, sbuf0); // make sure everything's resent bForceResend = true; } if (0 != strcmp(sbuf1, m_SbarString1)) { MESSAGE_BEGIN(MSG_ONE, gmsgStatusText, nullptr, this); WRITE_BYTE(1); WRITE_STRING(sbuf1); MESSAGE_END(); strcpy(m_SbarString1, sbuf1); // make sure everything's resent bForceResend = true; } // Check values and send if they don't match for (int i = 1; i < SBAR_END; i++) { if (newSBarState[i] != m_izSBarState[i] || bForceResend) { MESSAGE_BEGIN(MSG_ONE, gmsgStatusValue, nullptr, this); WRITE_BYTE(i); WRITE_SHORT(newSBarState[i]); MESSAGE_END(); m_izSBarState[i] = newSBarState[i]; } } } static void ClearEntityInfo(CBasePlayer* player) { MESSAGE_BEGIN(MSG_ONE, gmsgEntityInfo, nullptr, player); WRITE_STRING(""); MESSAGE_END(); } void CBasePlayer::UpdateEntityInfo() { const bool isEnabled = sv_entityinfo_enabled.value != 0; if (m_EntityInfoEnabled != isEnabled) { // Clear out any info that may be drawn. if (m_EntityInfoEnabled) { ClearEntityInfo(this); } m_EntityInfoEnabled = isEnabled; } if (!isEnabled) { return; } if (m_NextEntityInfoUpdateTime > gpGlobals->time) { return; } m_NextEntityInfoUpdateTime = gpGlobals->time + EntityInfoUpdateInterval; const auto entity = UTIL_FindEntityForward(this); if (entity) { // Pick a color based on entity type. RGB24 color{RGB_WHITE}; // Not all NPCs set the FL_MONSTER flag (e.g. Barnacle). const auto monster = entity->MyMonsterPointer(); if (monster) { const auto classification = monster->Classify(); if (classification != ENTCLASS_NONE) { color = [](Relationship relationship) { // Make sure these are colorblind-friendly. switch (relationship) { case Relationship::Ally: return RGB_BLUEISH; case Relationship::Dislike: [[fallthrough]]; case Relationship::Hate: [[fallthrough]]; case Relationship::Nemesis: return RGB_REDISH; default: return RGB_WHITE; } }(monster->IRelationship(this)); } } // Clamp to one removed from the bounds for a 32 bit integer to avoid overflowing due to rounding errors. // Must be doubles because floats are too inaccurate to clamp large values. const double clampedHealth = std::clamp( static_cast<double>(entity->pev->health), static_cast<double>(std::numeric_limits<int>::lowest() + 1), static_cast<double>(std::numeric_limits<int>::max() - 1)); const int roundedHealth = static_cast<int>(clampedHealth); MESSAGE_BEGIN(MSG_ONE, gmsgEntityInfo, nullptr, this); WRITE_STRING(STRING(entity->pev->classname)); WRITE_LONG(roundedHealth); WRITE_RGB24(color); MESSAGE_END(); } // Clear out the previous entity's info if requested. Otherwise the client will clear it after the draw time has passed. else if (sv_entityinfo_eager.value != 0) { ClearEntityInfo(this); } } #define CLIMB_SHAKE_FREQUENCY 22 // how many frames in between screen shakes when climbing #define MAX_CLIMB_SPEED 200 // fastest vertical climbing speed possible #define CLIMB_SPEED_DEC 15 // climbing deceleration rate #define CLIMB_PUNCH_X -7 // how far to 'punch' client X axis when climbing #define CLIMB_PUNCH_Z 7 // how far to 'punch' client Z axis when climbing void CBasePlayer::PreThink() { int buttonsChanged = (m_afButtonLast ^ pev->button); // These buttons have changed this frame // Debounced button codes for pressed/released // UNDONE: Do we need auto-repeat? m_afButtonPressed = buttonsChanged & pev->button; // The changed ones still down are "pressed" m_afButtonReleased = buttonsChanged & (~pev->button); // The ones not down are "released" g_pGameRules->PlayerThink(this); if (g_fGameOver) return; // intermission or finale UpdateShockEffect(); UTIL_MakeVectors(pev->v_angle); // is this still used? ItemPreFrame(); WaterMove(); if (g_pGameRules && g_pGameRules->FAllowFlashlight()) m_iHideHUD &= ~HIDEHUD_FLASHLIGHT; else m_iHideHUD |= HIDEHUD_FLASHLIGHT; if (m_bResetViewEntity) { m_bResetViewEntity = false; CBaseEntity* viewEntity = m_hViewEntity; if (viewEntity) { SET_VIEW(edict(), viewEntity->edict()); } } // in the event that the player JUST spawned, and the level node graph // was loaded, fix all of the node graph pointers before the game starts. // !!!BUGBUG - now that we have multiplayer, this needs to be moved! if (0 != WorldGraph.m_fGraphPresent && 0 == WorldGraph.m_fGraphPointersSet) { if (!WorldGraph.FSetGraphPointers()) { CGraph::Logger->debug("**Graph pointers were not set!"); } else { CGraph::Logger->debug("**Graph Pointers Set!"); } } // JOHN: checks if new client data (for HUD and view control) needs to be sent to the client UpdateClientData(); CheckTimeBasedDamage(); CheckSuitUpdate(); // Observer Button Handling if (IsObserver()) { Observer_HandleButtons(); Observer_CheckTarget(); Observer_CheckProperties(); pev->impulse = 0; return; } if (pev->deadflag >= DEAD_DYING) { PlayerDeathThink(); return; } // So the correct flags get sent to client asap. // if ((m_afPhysicsFlags & PFLAG_ONTRAIN) != 0) pev->flags |= FL_ONTRAIN; else pev->flags &= ~FL_ONTRAIN; // We're on a rope. if ((m_afPhysicsFlags & PFLAG_ONROPE) != 0 && m_pRope) { pev->velocity = g_vecZero; const Vector vecAttachPos = m_pRope->GetAttachedObjectsPosition(); pev->origin = vecAttachPos; Vector vecForce; if ((pev->button & IN_MOVERIGHT) != 0) { vecForce.x = gpGlobals->v_right.x; vecForce.y = gpGlobals->v_right.y; vecForce.z = 0; m_pRope->ApplyForceFromPlayer(vecForce); } if ((pev->button & IN_MOVELEFT) != 0) { vecForce.x = -gpGlobals->v_right.x; vecForce.y = -gpGlobals->v_right.y; vecForce.z = 0; m_pRope->ApplyForceFromPlayer(vecForce); } // Determine if any force should be applied to the rope, or if we should move around. if ((pev->button & (IN_BACK | IN_FORWARD)) != 0) { if ((gpGlobals->v_forward.x * gpGlobals->v_forward.x + gpGlobals->v_forward.y * gpGlobals->v_forward.y - gpGlobals->v_forward.z * gpGlobals->v_forward.z) <= 0) { if (m_bIsClimbing) { const float flDelta = gpGlobals->time - m_flLastClimbTime; m_flLastClimbTime = gpGlobals->time; if ((pev->button & IN_FORWARD) != 0) { if (gpGlobals->v_forward.z < 0.0) { if (!m_pRope->MoveDown(flDelta)) { // Let go of the rope, detach. pev->movetype = MOVETYPE_WALK; pev->solid = SOLID_SLIDEBOX; m_afPhysicsFlags &= ~PFLAG_ONROPE; m_pRope->DetachObject(); m_pRope = nullptr; m_bIsClimbing = false; } } else { m_pRope->MoveUp(flDelta); } } if ((pev->button & IN_BACK) != 0) { if (gpGlobals->v_forward.z < 0.0) { m_pRope->MoveUp(flDelta); } else if (!m_pRope->MoveDown(flDelta)) { // Let go of the rope, detach. pev->movetype = MOVETYPE_WALK; pev->solid = SOLID_SLIDEBOX; m_afPhysicsFlags &= ~PFLAG_ONROPE; m_pRope->DetachObject(); m_pRope = nullptr; m_bIsClimbing = false; } } } else { m_bIsClimbing = true; m_flLastClimbTime = gpGlobals->time; } } else { vecForce.x = gpGlobals->v_forward.x; vecForce.y = gpGlobals->v_forward.y; vecForce.z = 0.0; if ((pev->button & IN_BACK) != 0) { vecForce.x = -gpGlobals->v_forward.x; vecForce.y = -gpGlobals->v_forward.y; vecForce.z = 0; } m_pRope->ApplyForceFromPlayer(vecForce); m_bIsClimbing = false; } } else { m_bIsClimbing = false; } if ((m_afButtonPressed & IN_JUMP) != 0) { // We've jumped off the rope, give us some momentum pev->movetype = MOVETYPE_WALK; pev->solid = SOLID_SLIDEBOX; m_afPhysicsFlags &= ~PFLAG_ONROPE; Vector vecDir = gpGlobals->v_up * 165.0 + gpGlobals->v_forward * 150.0; Vector vecVelocity = m_pRope->GetAttachedObjectsVelocity() * 2; vecVelocity = vecVelocity.Normalize(); vecVelocity = vecVelocity * 200; pev->velocity = vecVelocity + vecDir; m_pRope->DetachObject(); m_pRope = nullptr; m_bIsClimbing = false; } return; } // Train speed control if ((m_afPhysicsFlags & PFLAG_ONTRAIN) != 0) { CBaseEntity* pTrain = CBaseEntity::Instance(pev->groundentity); float vel; if (!pTrain) { TraceResult trainTrace; // Maybe this is on the other side of a level transition UTIL_TraceLine(pev->origin, pev->origin + Vector(0, 0, -38), ignore_monsters, edict(), &trainTrace); // HACKHACK - Just look for the func_tracktrain classname if (trainTrace.flFraction != 1.0 && trainTrace.pHit) pTrain = CBaseEntity::Instance(trainTrace.pHit); if (!pTrain || (pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) == 0 || !pTrain->OnControls(this)) { // Logger->error("In train mode with no train!"); m_afPhysicsFlags &= ~PFLAG_ONTRAIN; m_iTrain = TRAIN_NEW | TRAIN_OFF; return; } } else if (!FBitSet(pev->flags, FL_ONGROUND) || FBitSet(pTrain->pev->spawnflags, SF_TRACKTRAIN_NOCONTROL) || (pev->button & (IN_MOVELEFT | IN_MOVERIGHT)) != 0) { // Turn off the train if you jump, strafe, or the train controls go dead m_afPhysicsFlags &= ~PFLAG_ONTRAIN; m_iTrain = TRAIN_NEW | TRAIN_OFF; return; } pev->velocity = g_vecZero; vel = 0; if ((m_afButtonPressed & IN_FORWARD) != 0) { vel = 1; pTrain->Use(this, this, USE_SET, vel); } else if ((m_afButtonPressed & IN_BACK) != 0) { vel = -1; pTrain->Use(this, this, USE_SET, vel); } if (0 != vel) { m_iTrain = TrainSpeed(pTrain->pev->speed, pTrain->pev->impulse); m_iTrain |= TRAIN_ACTIVE | TRAIN_NEW; } } else if ((m_iTrain & TRAIN_ACTIVE) != 0) m_iTrain = TRAIN_NEW; // turn off train if ((pev->button & IN_JUMP) != 0) { // If on a ladder, jump off the ladder // else Jump Jump(); } // If trying to duck, already ducked, or in the process of ducking if ((pev->button & IN_DUCK) != 0 || FBitSet(pev->flags, FL_DUCKING) || (m_afPhysicsFlags & PFLAG_DUCKING) != 0) Duck(); if (!FBitSet(pev->flags, FL_ONGROUND)) { m_flFallVelocity = -pev->velocity.z; } // StudioFrameAdvance( );//!!!HACKHACK!!! Can't be hit by traceline when not animating? // Clear out ladder pointer m_hEnemy = nullptr; if ((m_afPhysicsFlags & PFLAG_ONBARNACLE) != 0) { pev->velocity = g_vecZero; } } // TODO: move this documentation out of the source code and make sure it's correct. /* Time based Damage works as follows: 1) There are several types of timebased damage 2) A new hit inflicting tbd restarts the tbd counter - each monster has an 8bit counter, per damage type. The counter is decremented every second, so the maximum time an effect will last is 255/60 = 4.25 minutes. Of course, staying within the radius of a damaging effect like fire, nervegas, radiation will continually reset the counter to max. 3) Every second that a tbd counter is running, the player takes damage. The damage is determined by the type of tdb. 4) Certain actions or countermeasures counteract the damaging effects of tbds: Armor/Heater/Cooler - Chemical(acid),burn, freeze all do damage to armor power, then to body - recharged by suit recharger Air In Lungs - drowning damage is done to air in lungs first, then to body - recharged by poking head out of water - 10 seconds if swiming fast Air In SCUBA - drowning damage is done to air in tanks first, then to body - 2 minutes in tanks. Need new tank once empty. Radiation Syringe - Each syringe full provides protection vs one radiation dosage Antitoxin Syringe - Each syringe full provides protection vs one poisoning (nervegas or poison). Health kit - Immediate stop to acid/chemical, fire or freeze damage. Radiation Shower - Immediate stop to radiation damage, acid/chemical or fire damage. */ // If player is taking time based damage, continue doing damage to player - // this simulates the effect of being poisoned, gassed, dosed with radiation etc - // anything that continues to do damage even after the initial contact stops. // Update all time based damage counters, and shut off any that are done. // The m_bitsDamageType bit MUST be set if any damage is to be taken. // This routine will detect the initial on value of the m_bitsDamageType // and init the appropriate counter. Only processes damage every second. void CBasePlayer::CheckTimeBasedDamage() { int i; byte bDuration = 0; if ((m_bitsDamageType & DMG_TIMEBASED) == 0) return; // only check for time based damage approx. every 2 seconds if (fabs(gpGlobals->time - m_tbdPrev) < 2.0) return; m_tbdPrev = gpGlobals->time; for (i = 0; i < CDMG_TIMEBASED; i++) { // make sure bit is set for damage type if ((m_bitsDamageType & (DMG_PARALYZE << i)) != 0) { switch (i) { case itbd_Paralyze: // UNDONE - flag movement as half-speed bDuration = PARALYZE_DURATION; break; case itbd_NerveGas: // TakeDamage(this, this, NERVEGAS_DAMAGE, DMG_GENERIC); bDuration = NERVEGAS_DURATION; break; case itbd_Poison: TakeDamage(this, this, POISON_DAMAGE, DMG_GENERIC); bDuration = POISON_DURATION; break; case itbd_Radiation: // TakeDamage(this, this, RADIATION_DAMAGE, DMG_GENERIC); bDuration = RADIATION_DURATION; break; case itbd_DrownRecover: // NOTE: this hack is actually used to RESTORE health // after the player has been drowning and finally takes a breath if (m_idrowndmg > m_idrownrestored) { int idif = std::min(m_idrowndmg - m_idrownrestored, 10); GiveHealth(idif, DMG_GENERIC); m_idrownrestored += idif; } bDuration = 4; // get up to 5*10 = 50 points back break; case itbd_Acid: // TakeDamage(this, this, ACID_DAMAGE, DMG_GENERIC); bDuration = ACID_DURATION; break; case itbd_SlowBurn: // TakeDamage(this, this, SLOWBURN_DAMAGE, DMG_GENERIC); bDuration = SLOWBURN_DURATION; break; case itbd_SlowFreeze: // TakeDamage(this, this, SLOWFREEZE_DAMAGE, DMG_GENERIC); bDuration = SLOWFREEZE_DURATION; break; default: bDuration = 0; } if (0 != m_rgbTimeBasedDamage[i]) { // use up an antitoxin on poison or nervegas after a few seconds of damage if (((i == itbd_NerveGas) && (m_rgbTimeBasedDamage[i] < NERVEGAS_DURATION)) || ((i == itbd_Poison) && (m_rgbTimeBasedDamage[i] < POISON_DURATION))) { if (0 != m_rgItems[ITEM_ANTIDOTE]) { m_rgbTimeBasedDamage[i] = 0; m_rgItems[ITEM_ANTIDOTE]--; SetSuitUpdate("!HEV_HEAL4", SUIT_REPEAT_OK); } } // decrement damage duration, detect when done. if (0 == m_rgbTimeBasedDamage[i] || --m_rgbTimeBasedDamage[i] == 0) { m_rgbTimeBasedDamage[i] = 0; // if we're done, clear damage bits m_bitsDamageType &= ~(DMG_PARALYZE << i); } } else // first time taking this damage type - init damage duration m_rgbTimeBasedDamage[i] = bDuration; } } } /* THE POWER SUIT The Suit provides 3 main functions: Protection, Notification and Augmentation. Some functions are automatic, some require power. The player gets the suit shortly after getting off the train in C1A0 and it stays with him for the entire game. Protection Heat/Cold When the player enters a hot/cold area, the heating/cooling indicator on the suit will come on and the battery will drain while the player stays in the area. After the battery is dead, the player starts to take damage. This feature is built into the suit and is automatically engaged. Radiation Syringe This will cause the player to be immune from the effects of radiation for N seconds. Single use item. Anti-Toxin Syringe This will cure the player from being poisoned. Single use item. Health Small (1st aid kits, food, etc.) Large (boxes on walls) Armor The armor works using energy to create a protective field that deflects a percentage of damage projectile and explosive attacks. After the armor has been deployed, it will attempt to recharge itself to full capacity with the energy reserves from the battery. It takes the armor N seconds to fully charge. Notification (via the HUD) x Health x Ammo x Automatic Health Care Notifies the player when automatic healing has been engaged. x Geiger counter Classic Geiger counter sound and status bar at top of HUD alerts player to dangerous levels of radiation. This is not visible when radiation levels are normal. x Poison Armor Displays the current level of armor. Augmentation Long Jump Used by hitting the ??? key(s). Caused the player to further than normal. SCUBA Used automatically after picked up and after player enters the water. Works for N seconds. Single use. Things powered by the battery Armor Uses N watts for every M units of damage. */ // if in range of radiation source, ping geiger counter #define GEIGERDELAY 0.25 void CBasePlayer::UpdateGeigerCounter() { byte range; // delay per update ie: don't flood net with these msgs if (gpGlobals->time < m_flgeigerDelay) return; m_flgeigerDelay = gpGlobals->time + GEIGERDELAY; // send range to radition source to client range = (byte)(m_flgeigerRange / 4); if (range != m_igeigerRangePrev) { m_igeigerRangePrev = range; MESSAGE_BEGIN(MSG_ONE, gmsgGeigerRange, nullptr, this); WRITE_BYTE(range); MESSAGE_END(); } // reset counter and semaphore if (!RANDOM_LONG(0, 3)) m_flgeigerRange = 1000; } #define SUITUPDATETIME 3.5 #define SUITFIRSTUPDATETIME 0.1 void CBasePlayer::CheckSuitUpdate() { // Ignore suit updates if no suit if (!HasSuit()) return; // if in range of radiation source, ping geiger counter UpdateGeigerCounter(); if (g_pGameRules->IsMultiplayer()) { // don't bother updating HEV voice in multiplayer. return; } if (gpGlobals->time >= m_flSuitUpdate && m_flSuitUpdate > 0) { // play a sentence off of the end of the queue int isearch = m_iSuitPlayNext; string_t sentence = string_t::Null; for (int i = 0; i < CSUITPLAYLIST; i++) { sentence = m_rgSuitPlayList[isearch]; if (!FStringNull(sentence)) break; if (++isearch == CSUITPLAYLIST) isearch = 0; } if (!FStringNull(sentence)) { m_rgSuitPlayList[isearch] = string_t::Null; const char* sentenceOrGroup = STRING(sentence); if (sentenceOrGroup[0] == '!') { // play sentence number EMIT_SOUND_SUIT(this, sentenceOrGroup); } else { // play sentence group EMIT_GROUPNAME_SUIT(this, sentenceOrGroup); } m_flSuitUpdate = gpGlobals->time + SUITUPDATETIME; } else // queue is empty, don't check m_flSuitUpdate = 0; } } void CBasePlayer::SetSuitUpdate(const char* name, int iNoRepeatTime) { // Ignore suit updates if no suit if (!HasSuit()) return; if (g_pGameRules->IsMultiplayer()) { // due to static channel design, etc. We don't play HEV sounds in multiplayer right now. return; } // if name == nullptr, then clear out the queue if (!name) { for (int i = 0; i < CSUITPLAYLIST; i++) m_rgSuitPlayList[i] = string_t::Null; return; } // check norepeat list - this list lets us cancel // the playback of words or sentences that have already // been played within a certain time. int iempty = -1; for (int i = 0; i < CSUITNOREPEAT; i++) { if (0 == strcmp(name, STRING(m_rgiSuitNoRepeat[i]))) { // this sentence or group is already in // the norepeat list if (m_rgflSuitNoRepeatTime[i] < gpGlobals->time) { // norepeat time has expired, clear it out m_rgiSuitNoRepeat[i] = string_t::Null; m_rgflSuitNoRepeatTime[i] = 0.0; iempty = i; break; } else { // don't play, still marked as norepeat return; } } // keep track of empty slot if (FStringNull(m_rgiSuitNoRepeat[i])) iempty = i; } // sentence is not in norepeat list, save if norepeat time was given const string_t isentence = ALLOC_STRING(name); if (0 != iNoRepeatTime) { if (iempty < 0) iempty = RANDOM_LONG(0, CSUITNOREPEAT - 1); // pick random slot to take over m_rgiSuitNoRepeat[iempty] = isentence; m_rgflSuitNoRepeatTime[iempty] = iNoRepeatTime + gpGlobals->time; } // find empty spot in queue, or overwrite last spot m_rgSuitPlayList[m_iSuitPlayNext++] = isentence; if (m_iSuitPlayNext == CSUITPLAYLIST) m_iSuitPlayNext = 0; if (m_flSuitUpdate <= gpGlobals->time) { if (m_flSuitUpdate == 0) // play queue is empty, don't delay too long before playback m_flSuitUpdate = gpGlobals->time + SUITFIRSTUPDATETIME; else m_flSuitUpdate = gpGlobals->time + SUITUPDATETIME; } } void CBasePlayer::UpdatePlayerSound() { int iBodyVolume; int iVolume; CSound* pSound; pSound = CSoundEnt::SoundPointerForIndex(CSoundEnt::ClientSoundIndex(edict())); if (!pSound) { Logger->debug("Client lost reserved sound!"); return; } pSound->m_iType = bits_SOUND_NONE; // now calculate the best target volume for the sound. If the player's weapon // is louder than his body/movement, use the weapon volume, else, use the body volume. if (FBitSet(pev->flags, FL_ONGROUND)) { iBodyVolume = pev->velocity.Length(); // clamp the noise that can be made by the body, in case a push trigger, // weapon recoil, or anything shoves the player abnormally fast. if (iBodyVolume > 512) { iBodyVolume = 512; } } else { iBodyVolume = 0; } if ((pev->button & IN_JUMP) != 0) { iBodyVolume += 100; } // convert player move speed and actions into sound audible by monsters. if (m_iWeaponVolume > iBodyVolume) { m_iTargetVolume = m_iWeaponVolume; // OR in the bits for COMBAT sound if the weapon is being louder than the player. pSound->m_iType |= bits_SOUND_COMBAT; } else { m_iTargetVolume = iBodyVolume; } // decay weapon volume over time so bits_SOUND_COMBAT stays set for a while m_iWeaponVolume -= 250 * gpGlobals->frametime; if (m_iWeaponVolume < 0) { iVolume = 0; } // if target volume is greater than the player sound's current volume, we paste the new volume in // immediately. If target is less than the current volume, current volume is not set immediately to the // lower volume, rather works itself towards target volume over time. This gives monsters a much better chance // to hear a sound, especially if they don't listen every frame. iVolume = pSound->m_iVolume; if (m_iTargetVolume > iVolume) { iVolume = m_iTargetVolume; } else if (iVolume > m_iTargetVolume) { iVolume -= 250 * gpGlobals->frametime; if (iVolume < m_iTargetVolume) { iVolume = 0; } } if (m_fNoPlayerSound) { // debugging flag, lets players move around and shoot without monsters hearing. iVolume = 0; } if (gpGlobals->time > m_flStopExtraSoundTime) { // since the extra sound that a weapon emits only lasts for one client frame, we keep that sound around for a server frame or two // after actual emission to make sure it gets heard. m_iExtraSoundTypes = 0; } if (pSound) { pSound->m_vecOrigin = pev->origin; pSound->m_iType |= (bits_SOUND_PLAYER | m_iExtraSoundTypes); pSound->m_iVolume = iVolume; } // keep track of virtual muzzle flash m_iWeaponFlash -= 256 * gpGlobals->frametime; if (m_iWeaponFlash < 0) m_iWeaponFlash = 0; // UTIL_MakeVectors ( pev->angles ); // gpGlobals->v_forward.z = 0; // Below are a couple of useful little bits that make it easier to determine just how much noise the // player is making. // UTIL_ParticleEffect ( pev->origin + gpGlobals->v_forward * iVolume, g_vecZero, 255, 25 ); // Logger->debug("{}/{}", iVolume, m_iTargetVolume); } void CBasePlayer::PostThink() { if (g_fGameOver) goto pt_end; // intermission or finale if (!IsAlive()) goto pt_end; // Handle Tank controlling if (m_pTank != nullptr) { // if they've moved too far from the gun, or selected a weapon, unuse the gun if (m_pTank->OnControls(this) && FStringNull(pev->weaponmodel)) { m_pTank->Use(this, this, USE_SET, 2); // try fire the gun } else { // they've moved off the platform m_pTank->Use(this, this, USE_OFF, 0); m_pTank = nullptr; } } // do weapon stuff ItemPostFrame(); // check to see if player landed hard enough to make a sound // falling farther than half of the maximum safe distance, but not as far a max safe distance will // play a bootscrape sound, and no damage will be inflicted. Fallling a distance shorter than half // of maximum safe distance will make no sound. Falling farther than max safe distance will play a // fallpain sound, and damage will be inflicted based on how far the player fell if ((FBitSet(pev->flags, FL_ONGROUND)) && (pev->health > 0) && m_flFallVelocity >= PLAYER_FALL_PUNCH_THRESHHOLD) { // Logger->debug("{}", m_flFallVelocity); if (pev->watertype == CONTENTS_WATER) { // Did he hit the world or a non-moving entity? // BUG - this happens all the time in water, especially when // BUG - water has current force // if (auto groundEntity = GetGroundEntity(); !groundEntity || groundEntity->pev->velocity.z == 0) // EmitSound(CHAN_BODY, "player/pl_wade1.wav", 1, ATTN_NORM); } else if (m_flFallVelocity > PLAYER_MAX_SAFE_FALL_SPEED) { // after this point, we start doing damage float flFallDamage = g_pGameRules->FlPlayerFallDamage(this); if (flFallDamage > pev->health) { // splat // note: play on item channel because we play footstep landing on body channel EmitSound(CHAN_ITEM, "common/bodysplat.wav", 1, ATTN_NORM); } if (flFallDamage > 0) { TakeDamage(World, World, flFallDamage, DMG_FALL); pev->punchangle.x = 0; } } if (IsAlive()) { SetAnimation(PLAYER_WALK); } } if (FBitSet(pev->flags, FL_ONGROUND)) { if (m_flFallVelocity > 64 && !g_pGameRules->IsMultiplayer()) { CSoundEnt::InsertSound(bits_SOUND_PLAYER, pev->origin, m_flFallVelocity, 0.2); // Logger->debug("fall {}", m_flFallVelocity); } m_flFallVelocity = 0; } // select the proper animation for the player character if (IsAlive()) { if (0 == pev->velocity.x && 0 == pev->velocity.y) SetAnimation(PLAYER_IDLE); else if ((0 != pev->velocity.x || 0 != pev->velocity.y) && (FBitSet(pev->flags, FL_ONGROUND))) SetAnimation(PLAYER_WALK); else if (pev->waterlevel > WaterLevel::Feet) SetAnimation(PLAYER_WALK); } StudioFrameAdvance(); UpdatePlayerSound(); pt_end: #if defined(CLIENT_WEAPONS) // Decay timers on weapons // go through all of the weapons and make a list of the ones to pack for (int i = 0; i < MAX_WEAPON_SLOTS; i++) { if (m_rgpPlayerWeapons[i]) { CBasePlayerWeapon* gun = m_rgpPlayerWeapons[i]; while (gun) { if (gun->UseDecrement()) { gun->m_flNextPrimaryAttack = std::max(gun->m_flNextPrimaryAttack - gpGlobals->frametime, -1.1f); gun->m_flNextSecondaryAttack = std::max(gun->m_flNextSecondaryAttack - gpGlobals->frametime, -0.001f); if (gun->m_flTimeWeaponIdle != 1000) { gun->m_flTimeWeaponIdle = std::max(gun->m_flTimeWeaponIdle - gpGlobals->frametime, -0.001f); } if (gun->pev->fuser1 != 1000) { gun->pev->fuser1 = std::max(gun->pev->fuser1 - gpGlobals->frametime, -0.001f); } gun->DecrementTimers(); // Only decrement if not flagged as NO_DECREMENT // if (gun->m_flPumpTime != 1000) // { // gun->m_flPumpTime = std::max(gun->m_flPumpTime - gpGlobals->frametime, -0.001f); // } } gun = gun->m_pNext; } } } m_flNextAttack -= gpGlobals->frametime; if (m_flNextAttack < -0.001) m_flNextAttack = -0.001; if (m_flNextAmmoBurn != 1000) { m_flNextAmmoBurn -= gpGlobals->frametime; if (m_flNextAmmoBurn < -0.001) m_flNextAmmoBurn = -0.001; } if (m_flAmmoStartCharge != 1000) { m_flAmmoStartCharge -= gpGlobals->frametime; if (m_flAmmoStartCharge < -0.001) m_flAmmoStartCharge = -0.001; } #endif // Track button info so we can detect 'pressed' and 'released' buttons next frame m_afButtonLast = pev->button; } void CBasePlayer::Spawn() { m_bIsSpawning = true; // Make sure this gets reset even if somebody adds an early return or throws an exception. const CallOnDestroy resetIsSpawning{[this]() { // Done spawning; reset. m_bIsSpawning = false; }}; pev->health = 100; pev->armorvalue = 0; pev->takedamage = DAMAGE_AIM; pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_WALK; pev->max_health = pev->health; pev->flags &= FL_PROXY | FL_FAKECLIENT; // keep proxy and fakeclient flags set by engine pev->flags |= FL_CLIENT; pev->air_finished = gpGlobals->time + 12; pev->dmg = 2; // initial water damage pev->effects = 0; pev->deadflag = DEAD_NO; pev->dmg_take = 0; pev->dmg_save = 0; pev->friction = 1.0; pev->gravity = 1.0; m_bitsHUDDamage = -1; m_bitsDamageType = 0; m_afPhysicsFlags = 0; SetHasLongJump(false); // no longjump module. SetHasJetpack(false); g_engfuncs.pfnSetPhysicsKeyValue(edict(), "hl", "1"); g_engfuncs.pfnSetPhysicsKeyValue(edict(), "jpj", "0"); m_iFOV = 0; // init field of view. m_iClientFOV = -1; // make sure fov reset is sent m_ClientSndRoomtype = -1; m_flNextDecalTime = 0; // let this player decal as soon as he spawns. m_DisplacerReturn = g_vecZero; m_flgeigerDelay = gpGlobals->time + 2.0; // wait a few seconds until user-defined message registrations // are recieved by all clients m_flTimeStepSound = 0; m_iStepLeft = 0; m_flFieldOfView = 0.5; // some monsters use this to determine whether or not the player is looking at them. m_bloodColor = BLOOD_COLOR_RED; m_flNextAttack = UTIL_WeaponTimeBase(); m_iFlashBattery = 99; m_flFlashLightTime = 1; // force first message // dont let uninitialized value here hurt the player m_flFallVelocity = 0; if (!g_pGameRules->IsCTF()) g_pGameRules->SetDefaultPlayerTeam(this); if (g_pGameRules->IsCTF() && m_iTeamNum == CTFTeam::None) { pev->iuser1 = OBS_ROAMING; } g_pGameRules->GetPlayerSpawnSpot(this); SetModel("models/player.mdl"); pev->sequence = LookupActivity(ACT_IDLE); if (FBitSet(pev->flags, FL_DUCKING)) SetSize(VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX); else SetSize(VEC_HULL_MIN, VEC_HULL_MAX); pev->view_ofs = VEC_VIEW; Precache(); m_HackedGunPos = Vector(0, 32, 0); if (m_iPlayerSound == SOUNDLIST_EMPTY) { Logger->debug("Couldn't alloc player sound slot!"); } m_fNoPlayerSound = false; // normal sound behavior. m_pLastWeapon = nullptr; m_fInitHUD = true; m_iClientHideHUD = -1; // force this to be recalculated m_fWeapon = false; m_pClientActiveWeapon = nullptr; m_iClientBattery = -1; // reset all ammo values to 0 for (int i = 0; i < MAX_AMMO_TYPES; i++) { m_rgAmmo[i] = 0; m_rgAmmoLast[i] = 0; // client ammo values also have to be reset (the death hud clear messages does on the client side) } m_lastx = m_lasty = 0; m_iLastDamage = 0; m_bIsClimbing = false; m_flLastDamageTime = 0; m_flNextChatTime = gpGlobals->time; g_pGameRules->PlayerSpawn(this); if (g_pGameRules->IsCTF() && m_iTeamNum == CTFTeam::None) { pev->effects |= EF_NODRAW; pev->iuser1 = OBS_ROAMING; pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NOCLIP; pev->takedamage = DAMAGE_NO; m_iHideHUD = HIDEHUD_WEAPONS | HIDEHUD_HEALTH; m_afPhysicsFlags |= PFLAG_OBSERVER; pev->flags |= FL_SPECTATOR; MESSAGE_BEGIN(MSG_ALL, gmsgSpectator); WRITE_BYTE(entindex()); WRITE_BYTE(1); MESSAGE_END(); MESSAGE_BEGIN(MSG_ONE, gmsgTeamFull, nullptr, this); WRITE_BYTE(0); MESSAGE_END(); m_pGoalEnt = nullptr; m_iCurrentMenu = m_iNewTeamNum > CTFTeam::None ? MENU_DEFAULT : MENU_CLASS; if (g_pGameRules->IsCTF()) Player_Menu(); } } void CBasePlayer::Precache() { // SOUNDS / MODELS ARE PRECACHED in ClientPrecache() (game specific) // because they need to precache before any clients have connected // init geiger counter vars during spawn and each time // we cross a level transition m_flgeigerRange = 1000; m_igeigerRangePrev = 1000; m_bitsDamageType = 0; m_bitsHUDDamage = -1; m_iClientBattery = -1; m_iTrain |= TRAIN_NEW; m_iUpdateTime = 5; // won't update for 1/2 a second if (gInitHUD) m_fInitHUD = true; } void CBasePlayer::RenewItems() { } void CBasePlayer::PostRestore() { BaseClass::PostRestore(); m_Connected = true; m_ConnectTime = gpGlobals->time; SAVERESTOREDATA* pSaveData = (SAVERESTOREDATA*)gpGlobals->pSaveData; // landmark isn't present. if (0 == pSaveData->fUseLandmark) { Logger->debug("No Landmark:{}", pSaveData->szLandmarkName); // default to normal spawn CBaseEntity* pSpawnSpot = EntSelectSpawnPoint(this); pev->origin = pSpawnSpot->pev->origin + Vector(0, 0, 1); pev->angles = pSpawnSpot->pev->angles; } pev->v_angle.z = 0; // Clear out roll pev->angles = pev->v_angle; pev->fixangle = FIXANGLE_ABSOLUTE; // turn this way immediately m_iClientFOV = -1; // Make sure the client gets the right FOV value. m_ClientSndRoomtype = -1; // Reset room type on level change. if (!FStrEq(pSaveData->szCurrentMapName, STRING(gpGlobals->mapname))) { m_SndRoomtype = 0; } // Copied from spawn() for now m_bloodColor = BLOOD_COLOR_RED; if (FBitSet(pev->flags, FL_DUCKING)) { // Use the crouch HACK // FixPlayerCrouchStuck(this); // Don't need to do this with new player prediction code. SetSize(VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX); } else { SetSize(VEC_HULL_MIN, VEC_HULL_MAX); } g_engfuncs.pfnSetPhysicsKeyValue(edict(), "hl", "1"); SetHasLongJump(m_fLongJump); SetHasJetpack(m_JetpackEnabled); RenewItems(); #if defined(CLIENT_WEAPONS) // HACK: This variable is saved/restored in CBaseMonster as a time variable, but we're using it // as just a counter. Ideally, this needs its own variable that's saved as a plain float. // Barring that, we clear it out here instead of using the incorrect restored time value. m_flNextAttack = UTIL_WeaponTimeBase(); #endif // If we have an active item and it has valid model strings, reset the models now. // Otherwise the weapon will do this itself. if (m_pActiveWeapon) { if (!FStringNull(m_pActiveWeapon->m_ViewModel) && !FStringNull(m_pActiveWeapon->m_PlayerModel)) { m_pActiveWeapon->SetWeaponModels(STRING(m_pActiveWeapon->m_ViewModel), STRING(m_pActiveWeapon->m_PlayerModel)); } } m_bResetViewEntity = true; m_bRestored = true; } void CBasePlayer::SelectNextItem(int iItem) { CBasePlayerWeapon* weapon = m_rgpPlayerWeapons[iItem]; if (!weapon) return; if (weapon == m_pActiveWeapon) { // select the next one in the chain weapon = m_pActiveWeapon->m_pNext; if (!weapon) { return; } CBasePlayerWeapon* pLast; pLast = weapon; while (pLast->m_pNext) pLast = pLast->m_pNext; // relink chain pLast->m_pNext = m_pActiveWeapon; m_pActiveWeapon->m_pNext = nullptr; m_rgpPlayerWeapons[iItem] = weapon; } ResetAutoaim(); // FIX, this needs to queue them up and delay if (m_pActiveWeapon) { m_pActiveWeapon->Holster(); } m_pActiveWeapon = weapon; if (m_pActiveWeapon) { m_pActiveWeapon->Deploy(); m_pActiveWeapon->UpdateItemInfo(); } } bool CBasePlayer::HasWeapons() { int i; for (i = 0; i < MAX_WEAPON_SLOTS; i++) { if (m_rgpPlayerWeapons[i]) { return true; } } return false; } void CBasePlayer::SelectPrevItem(int iItem) { } const char* CBasePlayer::TeamID() { if (pev == nullptr) // Not fully connected yet return ""; // return their team name return m_szTeamName; } /** * @brief !!!UNDONE:ultra temporary SprayCan entity to apply decal frame at a time. For PreAlpha CD */ class CSprayCan : public CBaseEntity { public: void Spawn(CBaseEntity* owner); void Think() override; int ObjectCaps() override { return FCAP_DONT_SAVE; } }; LINK_ENTITY_TO_CLASS(spraycan, CSprayCan); void CSprayCan::Spawn(CBaseEntity* owner) { pev->origin = owner->pev->origin + Vector(0, 0, 32); pev->angles = owner->pev->v_angle; pev->owner = owner->edict(); pev->frame = 0; pev->nextthink = gpGlobals->time + 0.1; EmitSound(CHAN_VOICE, "player/sprayer.wav", 1, ATTN_NORM); } void CSprayCan::Think() { TraceResult tr; CBasePlayer* pPlayer = ToBasePlayer(pev->owner); const int nFrames = pPlayer ? pPlayer->GetCustomDecalFrames() : -1; const int playernum = ENTINDEX(pev->owner); // Logger->debug("Spray by player {}, {} of {}", playernum, (int)(pev->frame + 1), nFrames); UTIL_MakeVectors(pev->angles); UTIL_TraceLine(pev->origin, pev->origin + gpGlobals->v_forward * 128, ignore_monsters, pev->owner, &tr); // No customization present. if (nFrames == -1) { UTIL_DecalTrace(&tr, DECAL_LAMBDA6); UTIL_Remove(this); } else { UTIL_PlayerDecalTrace(&tr, playernum, pev->frame, true); // Just painted last custom frame. if (pev->frame++ >= (nFrames - 1)) UTIL_Remove(this); } pev->nextthink = gpGlobals->time + 0.1; } class CBloodSplat : public CBaseEntity { public: void Spawn(CBaseEntity* owner); void Spray(); }; LINK_ENTITY_TO_CLASS(blood_splat, CBloodSplat); void CBloodSplat::Spawn(CBaseEntity* owner) { pev->origin = owner->pev->origin + Vector(0, 0, 32); pev->angles = owner->pev->v_angle; pev->owner = owner->edict(); SetThink(&CBloodSplat::Spray); pev->nextthink = gpGlobals->time + 0.1; } void CBloodSplat::Spray() { TraceResult tr; if (g_Language != LANGUAGE_GERMAN) { UTIL_MakeVectors(pev->angles); UTIL_TraceLine(pev->origin, pev->origin + gpGlobals->v_forward * 128, ignore_monsters, pev->owner, &tr); UTIL_BloodDecalTrace(&tr, BLOOD_COLOR_RED); } SetThink(&CBloodSplat::SUB_Remove); pev->nextthink = gpGlobals->time + 0.1; } CBaseItem* CBasePlayer::GiveNamedItem(std::string_view className, std::optional<int> defaultAmmo) { // Only give items to player. auto entity = g_ItemDictionary->Create(className); if (FNullEnt(entity)) { CBaseEntity::Logger->debug("nullptr Ent in GiveNamedItem!"); return nullptr; } entity->pev->origin = pev->origin; entity->m_RespawnDelay = ITEM_NEVER_RESPAWN_DELAY; DispatchSpawn(entity->edict()); if (defaultAmmo) { if (auto weapon = dynamic_cast<CBasePlayerWeapon*>(entity); weapon) { weapon->m_iDefaultAmmo = *defaultAmmo; } } if (entity->AddToPlayer(this) != ItemAddResult::Added) { g_engfuncs.pfnRemoveEntity(entity->edict()); return nullptr; } return entity; } int CBasePlayer::GetFlashlightFlag() const { switch (m_SuitLightType) { default: case SuitLightType::Flashlight: return EF_DIMLIGHT; case SuitLightType::Nightvision: return EF_BRIGHTLIGHT; } } bool CBasePlayer::FlashlightIsOn() { return FBitSet(pev->effects, GetFlashlightFlag()); } static void UpdateFlashlight(CBasePlayer* player, bool isOn) { MESSAGE_BEGIN(MSG_ONE, gmsgFlashlight, nullptr, player); WRITE_BYTE(static_cast<int>(player->m_SuitLightType)); WRITE_BYTE(isOn ? 1 : 0); WRITE_BYTE(player->m_iFlashBattery); MESSAGE_END(); } void CBasePlayer::FlashlightTurnOn() { if (!g_pGameRules->FAllowFlashlight()) { return; } if (HasSuit()) { auto onSound = [this]() { switch (m_SuitLightType) { default: case SuitLightType::Flashlight: return SOUND_FLASHLIGHT_ON; case SuitLightType::Nightvision: return SOUND_NIGHTVISION_ON; } }(); EmitSound(CHAN_WEAPON, onSound, 1.0, ATTN_NORM); SetBits(pev->effects, GetFlashlightFlag()); UpdateFlashlight(this, true); m_flFlashLightTime = FLASH_DRAIN_TIME + gpGlobals->time; } } void CBasePlayer::FlashlightTurnOff() { auto offSound = [this]() { switch (m_SuitLightType) { default: case SuitLightType::Flashlight: return SOUND_FLASHLIGHT_OFF; case SuitLightType::Nightvision: return SOUND_NIGHTVISION_OFF; } }(); EmitSound(CHAN_WEAPON, offSound, 1.0, ATTN_NORM); ClearBits(pev->effects, GetFlashlightFlag()); UpdateFlashlight(this, false); m_flFlashLightTime = FLASH_CHARGE_TIME + gpGlobals->time; } void CBasePlayer::SetSuitLightType(SuitLightType type) { if (m_SuitLightType == type) { return; } const bool isOn = FlashlightIsOn(); ClearBits(pev->effects, GetFlashlightFlag()); m_SuitLightType = type; if (isOn) { SetBits(pev->effects, GetFlashlightFlag()); } UpdateFlashlight(this, isOn); } void CBasePlayer::ForceClientDllUpdate() { m_iClientHealth = -1; m_iClientBattery = -1; m_iClientHideHUD = -1; m_iClientFOV = -1; m_ClientWeaponBits = 0; m_ClientSndRoomtype = -1; for (int i = 0; i < MAX_AMMO_TYPES; ++i) { m_rgAmmoLast[i] = 0; } m_iTrain |= TRAIN_NEW; // Force new train message. m_fWeapon = false; // Force weapon send m_fInitHUD = true; // Force HUD gmsgResetHUD message // Now force all the necessary messages // to be sent. UpdateClientData(); } void CBasePlayer::ImpulseCommands() { TraceResult tr; // UNDONE: kill me! This is temporary for PreAlpha CDs int iImpulse = pev->impulse; switch (iImpulse) { case 99: { bool iOn; if (0 == gmsgLogo) { iOn = true; gmsgLogo = REG_USER_MSG("Logo", 1); } else { iOn = false; } ASSERT(gmsgLogo > 0); // send "health" update message MESSAGE_BEGIN(MSG_ONE, gmsgLogo, nullptr, this); WRITE_BYTE(static_cast<int>(iOn)); MESSAGE_END(); if (!iOn) gmsgLogo = 0; break; } case 100: // temporary flashlight for level designers if (FlashlightIsOn()) { FlashlightTurnOff(); } else { FlashlightTurnOn(); } break; case 201: // paint decal if (gpGlobals->time < m_flNextDecalTime) { // too early! break; } UTIL_MakeVectors(pev->v_angle); UTIL_TraceLine(pev->origin + pev->view_ofs, pev->origin + pev->view_ofs + gpGlobals->v_forward * 128, ignore_monsters, edict(), &tr); if (tr.flFraction != 1.0) { // line hit something, so paint a decal m_flNextDecalTime = gpGlobals->time + decalfrequency.value; CSprayCan* pCan = g_EntityDictionary->Create<CSprayCan>("spraycan"); pCan->Spawn(this); } break; case 205: { DropPlayerCTFPowerup(this); break; } default: // check all of the cheat impulse commands now CheatImpulseCommands(iImpulse); break; } pev->impulse = 0; } void CBasePlayer::CheatImpulseCommands(int iImpulse) { if (0 == g_psv_cheats->value) { return; } switch (iImpulse) { case 76: { if (!giPrecacheGrunt) { giPrecacheGrunt = true; Con_DPrintf("You must now restart to use Grunt-o-matic.\n"); } else { UTIL_MakeVectors(Vector(0, pev->v_angle.y, 0)); Create("monster_human_grunt", pev->origin + gpGlobals->v_forward * 128, pev->angles); } break; } case 101: { const bool hasActiveWeapon = m_pActiveWeapon != nullptr; const WeaponSwitchMode savedWepSwitch = m_AutoWepSwitch; m_AutoWepSwitch = WeaponSwitchMode::Never; SetHasSuit(true); pev->armorvalue = MAX_NORMAL_BATTERY; for (auto weapon : g_WeaponDictionary->GetClassNames()) { GiveNamedItem(weapon, -1); } for (int i = 0; i < g_AmmoTypes.GetCount(); ++i) { auto ammoType = g_AmmoTypes.GetByIndex(i + 1); SetAmmoCount(ammoType->Name.c_str(), ammoType->MaximumCapacity); } // Default to the MP5. if (!hasActiveWeapon) { SelectItem("weapon_9mmar"); } m_AutoWepSwitch = savedWepSwitch; break; } case 102: // Gibbage!!! //CGib::SpawnRandomGibs(this, 1, true); CGib::SpawnClientGibs(this, GibType::Human, 1, false, false); break; case 103: { // What the hell are you doing? CBaseEntity* pEntity = UTIL_FindEntityForward(this); if (pEntity) { CBaseMonster* pMonster = pEntity->MyMonsterPointer(); if (pMonster) pMonster->ReportAIState(); } break; } case 104: // Dump all of the global state varaibles (and global entity names) gGlobalState.DumpGlobals(); break; case 105: // player makes no sound for monsters to hear. { if (m_fNoPlayerSound) { Con_DPrintf("Player is audible\n"); m_fNoPlayerSound = false; } else { Con_DPrintf("Player is silent\n"); m_fNoPlayerSound = true; } break; } case 106: { // Give me the classname and targetname of this entity. CBaseEntity* pEntity = UTIL_FindEntityForward(this); if (pEntity) { Con_DPrintf("Classname: %s", pEntity->GetClassname()); if (!FStringNull(pEntity->pev->targetname)) { Con_DPrintf(" - Targetname: %s\n", pEntity->GetTargetname()); } else { Con_DPrintf(" - TargetName: No Targetname\n"); } Con_DPrintf("Model: %s\n", pEntity->GetModelName()); if (!FStringNull(pEntity->pev->globalname)) Con_DPrintf("Globalname: %s\n", pEntity->GetGlobalname()); } break; } case 107: { TraceResult tr; edict_t* pWorld = CBaseEntity::World->edict(); Vector start = pev->origin + pev->view_ofs; Vector end = start + gpGlobals->v_forward * 1024; UTIL_TraceLine(start, end, ignore_monsters, edict(), &tr); if (tr.pHit) pWorld = tr.pHit; const char* pTextureName = TRACE_TEXTURE(pWorld, start, end); if (pTextureName) Con_DPrintf("Texture: %s (%c)\n", pTextureName, g_MaterialSystem.FindTextureType(pTextureName)); } break; case 195: // show shortest paths for entire level to nearest node { Create("node_viewer_fly", pev->origin, pev->angles); } break; case 196: // show shortest paths for entire level to nearest node { Create("node_viewer_large", pev->origin, pev->angles); } break; case 197: // show shortest paths for entire level to nearest node { Create("node_viewer_human", pev->origin, pev->angles); } break; case 199: // show nearest node and all connections { Con_DPrintf("%d\n", WorldGraph.FindNearestNode(pev->origin, bits_NODE_GROUP_REALM)); WorldGraph.ShowNodeConnections(WorldGraph.FindNearestNode(pev->origin, bits_NODE_GROUP_REALM)); } break; case 202: // Random blood splatter { UTIL_MakeVectors(pev->v_angle); TraceResult tr; UTIL_TraceLine(pev->origin + pev->view_ofs, pev->origin + pev->view_ofs + gpGlobals->v_forward * 128, ignore_monsters, edict(), &tr); if (tr.flFraction != 1.0) { // line hit something, so paint a decal CBloodSplat* pBlood = g_EntityDictionary->Create<CBloodSplat>("blood_splat"); pBlood->Spawn(this); } break; } case 203: // remove creature. { CBaseEntity* pEntity = UTIL_FindEntityForward(this); if (pEntity) { if (0 != pEntity->pev->takedamage) pEntity->SetThink(&CBaseEntity::SUB_Remove); } break; } } } ItemAddResult CBasePlayer::AddPlayerWeapon(CBasePlayerWeapon* weapon) { CBasePlayerWeapon* pInsert = m_rgpPlayerWeapons[weapon->iItemSlot()]; while (pInsert) { if (pInsert->ClassnameIs(STRING(weapon->pev->classname))) { if (weapon->AddDuplicate(pInsert)) { // ugly hack to update clip w/o an update clip message pInsert->UpdateItemInfo(); if (m_pActiveWeapon) m_pActiveWeapon->UpdateItemInfo(); weapon->Kill(); return ItemAddResult::AddedAsDuplicate; } return ItemAddResult::NotAdded; } pInsert = pInsert->m_pNext; } if (weapon->CanAddToPlayer(this)) { weapon->AddToPlayer(this); // Add to the list before extracting ammo so weapon ownership checks work properly. weapon->m_pNext = m_rgpPlayerWeapons[weapon->iItemSlot()]; m_rgpPlayerWeapons[weapon->iItemSlot()] = weapon; weapon->ExtractAmmo(weapon); // Immediately update the ammo HUD so weapon pickup isn't sometimes red because the HUD doesn't know about regenerating/free ammo yet. if (-1 != weapon->m_iPrimaryAmmoType) { SendSingleAmmoUpdate(CBasePlayer::GetAmmoIndex(weapon->pszAmmo1()), false); } if (-1 != weapon->m_iSecondaryAmmoType) { SendSingleAmmoUpdate(CBasePlayer::GetAmmoIndex(weapon->pszAmmo2()), false); } // Don't show weapon pickup if we're spawning or if it's an exhaustible weapon (will show ammo pickup instead). if (!m_bIsSpawning && (weapon->iFlags() & ITEM_FLAG_EXHAUSTIBLE) == 0) { MESSAGE_BEGIN(MSG_ONE, gmsgWeapPickup, NULL, this); WRITE_BYTE(weapon->m_iId); MESSAGE_END(); } // should we switch to this item? if (g_pGameRules->FShouldSwitchWeapon(this, weapon)) { SwitchWeapon(weapon); } return ItemAddResult::Added; } return ItemAddResult::NotAdded; } bool CBasePlayer::RemovePlayerWeapon(CBasePlayerWeapon* weapon) { if (m_pActiveWeapon == weapon) { ResetAutoaim(); weapon->Holster(); weapon->pev->nextthink = 0; // crowbar may be trying to swing again, etc. weapon->SetThink(nullptr); m_pActiveWeapon = nullptr; pev->viewmodel = string_t::Null; pev->weaponmodel = string_t::Null; } if (m_pLastWeapon == weapon) m_pLastWeapon = nullptr; CBasePlayerWeapon* pPrev = m_rgpPlayerWeapons[weapon->iItemSlot()]; if (pPrev == weapon) { m_rgpPlayerWeapons[weapon->iItemSlot()] = weapon->m_pNext; return true; } else { while (pPrev && pPrev->m_pNext != weapon) { pPrev = pPrev->m_pNext; } if (pPrev) { pPrev->m_pNext = weapon->m_pNext; return true; } } return false; } int CBasePlayer::GiveAmmo(int iCount, const char* szName) { if (!szName) { // no ammo. return -1; } const auto type = g_AmmoTypes.GetByName(szName); if (!type) { // Ammo type not registered. return -1; } if (iCount == RefillAllAmmoAmount) { iCount = type->MaximumCapacity; } if (!g_pGameRules->CanHaveAmmo(this, szName)) { // game rules say I can't have any more of this ammo type. return -1; } const int iAdd = std::min(iCount, type->MaximumCapacity - m_rgAmmo[type->Id]); // If we couldn't give any more ammo then just bow out. (Should already be handled by gamerules above). if (iAdd <= 0) return -1; // If this is an exhaustible weapon make sure the player has it. if (!type->WeaponName.empty()) { if (!HasNamedPlayerWeapon(type->WeaponName.c_str())) { GiveNamedItem(type->WeaponName.c_str(), 0); } } m_rgAmmo[type->Id] += iAdd; // Send the message that ammo has been picked up MESSAGE_BEGIN(MSG_ONE, gmsgAmmoPickup, nullptr, this); WRITE_BYTE(GetAmmoIndex(szName)); // ammo ID WRITE_BYTE(iAdd); // amount MESSAGE_END(); return type->Id; } int CBasePlayer::GiveMagazine(CBasePlayerWeapon* weapon, int attackMode) { if (!weapon) { return -1; } assert(attackMode >= 0 && attackMode < MAX_WEAPON_ATTACK_MODES); const auto& attackModeInfo = weapon->m_WeaponInfo->AttackModeInfo[attackMode]; if (attackModeInfo.AmmoType.empty()) { return -1; } int magazineSize = attackModeInfo.MagazineSize; // If the weapon does not use magazines, just give one unit of ammo instead. if (magazineSize == WEAPON_NOCLIP) { magazineSize = 1; } return GiveAmmo(magazineSize, attackModeInfo.AmmoType.c_str()); } void CBasePlayer::ItemPreFrame() { if (m_flNextAttack > UTIL_WeaponTimeBase()) { return; } if (!m_pActiveWeapon) return; m_pActiveWeapon->ItemPreFrame(); } void CBasePlayer::ItemPostFrame() { // check if the player is using a tank if (m_pTank != nullptr) return; const bool canUseItem = m_flNextAttack <= UTIL_WeaponTimeBase(); if (canUseItem || GetSkillFloat("allow_use_while_busy") != 0) { // Handle use events PlayerUse(); } if (!canUseItem) { return; } ImpulseCommands(); // check again if the player is using a tank if they started using it in PlayerUse if (m_pTank != nullptr) return; if (!m_pActiveWeapon) return; m_pActiveWeapon->ItemPostFrame(); } void CBasePlayer::SendAmmoUpdate() { for (int i = 0; i < MAX_AMMO_TYPES; i++) { InternalSendSingleAmmoUpdate(i, true); } } bool CBasePlayer::HasLongJump() const { return m_fLongJump; } void CBasePlayer::SetHasLongJump(bool hasLongJump) { m_fLongJump = hasLongJump; g_engfuncs.pfnSetPhysicsKeyValue(edict(), "slj", hasLongJump ? "1" : "0"); // TODO: CTF long jump integration } void CBasePlayer::SetHasJetpack(bool state) { m_JetpackEnabled = state; g_engfuncs.pfnSetPhysicsKeyValue(edict(), "cjp", state ? "1" : "0"); } void CBasePlayer::SendSingleAmmoUpdate(int ammoIndex, bool clearLastState) { if (ammoIndex < 0 || ammoIndex >= MAX_AMMO_TYPES) { return; } InternalSendSingleAmmoUpdate(ammoIndex, clearLastState); } void CBasePlayer::InternalSendSingleAmmoUpdate(int ammoIndex, bool clearLastState) { // This can be called before the client has finished connecting, so ignore the request. if (!IsConnected()) { return; } if (m_rgAmmo[ammoIndex] != m_rgAmmoLast[ammoIndex]) { if (clearLastState) { m_rgAmmoLast[ammoIndex] = m_rgAmmo[ammoIndex]; } ASSERT(m_rgAmmo[ammoIndex] >= 0); ASSERT(m_rgAmmo[ammoIndex] < 255); // send "Ammo" update message MESSAGE_BEGIN(MSG_ONE, gmsgAmmoX, NULL, this); WRITE_BYTE(ammoIndex); WRITE_BYTE(std::clamp(m_rgAmmo[ammoIndex], 0, 254)); // clamp the value to one byte MESSAGE_END(); } } void CBasePlayer::UpdateClientData() { const bool fullHUDInitRequired = m_fInitHUD != false; if (!m_HasActivated) { m_HasActivated = true; g_Server.PlayerActivating(this); FireTargets("game_playeractivate", this, this, USE_TOGGLE, 0); } if (m_fInitHUD) { m_fInitHUD = false; gInitHUD = false; MESSAGE_BEGIN(MSG_ONE, gmsgResetHUD, nullptr, this); WRITE_BYTE(0); MESSAGE_END(); if (!m_fGameHUDInitialized) { MESSAGE_BEGIN(MSG_ONE, gmsgInitHUD, nullptr, this); MESSAGE_END(); g_pGameRules->InitHUD(this); m_fGameHUDInitialized = true; m_iObserverLastMode = OBS_ROAMING; if (g_pGameRules->IsMultiplayer()) { FireTargets("game_playerjoin", this, this, USE_TOGGLE, 0); } } if (g_pGameRules->IsMultiplayer()) { RefreshCustomHUD(this); } InitStatusBar(); } if (m_FireSpawnTarget) { m_FireSpawnTarget = false; // In case a game_player_equip is triggered, this ensures the player equips the last weapon given. const WeaponSwitchMode savedAutoWepSwitch = m_AutoWepSwitch; m_AutoWepSwitch = WeaponSwitchMode::IfBetter; // This counts as spawning, it suppresses weapon pickup notifications. m_bIsSpawning = true; FireTargets("game_playerspawn", this, this, USE_TOGGLE, 0); m_bIsSpawning = false; m_AutoWepSwitch = savedAutoWepSwitch; } if (m_iHideHUD != m_iClientHideHUD) { MESSAGE_BEGIN(MSG_ONE, gmsgHideWeapon, nullptr, this); WRITE_BYTE(m_iHideHUD); MESSAGE_END(); m_iClientHideHUD = m_iHideHUD; } if (m_iFOV != m_iClientFOV) { MESSAGE_BEGIN(MSG_ONE, gmsgSetFOV, nullptr, this); WRITE_BYTE(m_iFOV); MESSAGE_END(); // cache FOV change at end of function, so weapon updates can see that FOV has changed } // HACKHACK -- send the message to display the game title // TODO: will not work properly in multiplayer if (!g_DisplayTitleName.empty()) { MESSAGE_BEGIN(MSG_ONE, gmsgShowGameTitle, nullptr, this); WRITE_STRING(g_DisplayTitleName.c_str()); MESSAGE_END(); g_DisplayTitleName.clear(); } if (pev->health != m_iClientHealth) { // make sure that no negative health values are sent int iHealth = std::clamp(pev->health, 0.f, static_cast<float>(std::numeric_limits<short>::max())); if (pev->health > 0.0f && pev->health <= 1.0f) iHealth = 1; // send "health" update message MESSAGE_BEGIN(MSG_ONE, gmsgHealth, nullptr, this); WRITE_SHORT(iHealth); MESSAGE_END(); m_iClientHealth = pev->health; } if (pev->armorvalue != m_iClientBattery) { m_iClientBattery = pev->armorvalue; ASSERT(gmsgBattery > 0); // send "health" update message MESSAGE_BEGIN(MSG_ONE, gmsgBattery, nullptr, this); WRITE_SHORT((int)pev->armorvalue); MESSAGE_END(); } if (m_WeaponBits != m_ClientWeaponBits) { m_ClientWeaponBits = m_WeaponBits; const int lowerBits = m_WeaponBits & 0xFFFFFFFF; const int upperBits = (m_WeaponBits >> 32) & 0xFFFFFFFF; MESSAGE_BEGIN(MSG_ONE, gmsgWeapons, nullptr, this); WRITE_LONG(lowerBits); WRITE_LONG(upperBits); MESSAGE_END(); } if (0 != pev->dmg_take || 0 != pev->dmg_save || m_bitsHUDDamage != m_bitsDamageType) { // Comes from inside me if not set Vector damageOrigin = pev->origin; // send "damage" message // causes screen to flash, and pain compass to show direction of damage edict_t* other = pev->dmg_inflictor; if (other) { CBaseEntity* pEntity = CBaseEntity::Instance(other); if (pEntity) damageOrigin = pEntity->Center(); } // only send down damage type that have hud art int visibleDamageBits = m_bitsDamageType & DMG_SHOWNHUD; MESSAGE_BEGIN(MSG_ONE, gmsgDamage, nullptr, this); WRITE_BYTE(pev->dmg_save); WRITE_BYTE(pev->dmg_take); WRITE_LONG(visibleDamageBits); WRITE_COORD(damageOrigin.x); WRITE_COORD(damageOrigin.y); WRITE_COORD(damageOrigin.z); MESSAGE_END(); pev->dmg_take = 0; pev->dmg_save = 0; m_bitsHUDDamage = m_bitsDamageType; // Clear off non-time-based damage indicators m_bitsDamageType &= DMG_TIMEBASED; } if (fullHUDInitRequired || m_bRestored) { // Always tell client about battery state MESSAGE_BEGIN(MSG_ONE, gmsgFlashBattery, nullptr, this); WRITE_BYTE(m_iFlashBattery); MESSAGE_END(); // Sync up client flashlight state. UpdateFlashlight(this, FlashlightIsOn()); } if (m_bRestored) { // Reinitialize hud color to saved off value. SetHudColor(RGB24::FromInteger(m_HudColor)); } // Update Flashlight if ((0 != m_flFlashLightTime) && (m_flFlashLightTime <= gpGlobals->time)) { if (FlashlightIsOn()) { if (0 != m_iFlashBattery) { m_flFlashLightTime = FLASH_DRAIN_TIME + gpGlobals->time; m_iFlashBattery--; if (0 == m_iFlashBattery) FlashlightTurnOff(); } } else { if (m_iFlashBattery < 100) { m_flFlashLightTime = FLASH_CHARGE_TIME + gpGlobals->time; m_iFlashBattery++; } else m_flFlashLightTime = 0; } MESSAGE_BEGIN(MSG_ONE, gmsgFlashBattery, nullptr, this); WRITE_BYTE(m_iFlashBattery); MESSAGE_END(); } if ((m_iTrain & TRAIN_NEW) != 0) { ASSERT(gmsgTrain > 0); // send "health" update message MESSAGE_BEGIN(MSG_ONE, gmsgTrain, nullptr, this); WRITE_BYTE(m_iTrain & 0xF); MESSAGE_END(); m_iTrain &= ~TRAIN_NEW; } SendAmmoUpdate(); // Update all the items for (int i = 0; i < MAX_WEAPON_SLOTS; i++) { if (m_rgpPlayerWeapons[i]) // each item updates it's successors m_rgpPlayerWeapons[i]->UpdateClientData(this); } // Active item is becoming null, or we're sending all HUD state to client // Only if we're not in Observer mode, which uses the target player's weapon if (pev->iuser1 == OBS_NONE && !m_pActiveWeapon && ((m_pClientActiveWeapon != m_pActiveWeapon) || fullHUDInitRequired)) { // Tell ammo hud that we have no weapon selected MESSAGE_BEGIN(MSG_ONE, gmsgCurWeapon, nullptr, this); WRITE_BYTE(0); WRITE_BYTE(0); WRITE_BYTE(0); MESSAGE_END(); } // Cache and client weapon change m_pClientActiveWeapon = m_pActiveWeapon; m_iClientFOV = m_iFOV; UpdateCTFHud(); // Update Status Bar if (m_flNextSBarUpdateTime < gpGlobals->time) { UpdateStatusBar(); m_flNextSBarUpdateTime = gpGlobals->time + 0.2; } UpdateEntityInfo(); // Send new room type to client. if (m_ClientSndRoomtype != m_SndRoomtype) { m_ClientSndRoomtype = m_SndRoomtype; MESSAGE_BEGIN(MSG_ONE, SVC_ROOMTYPE, nullptr, this); WRITE_SHORT((short)m_SndRoomtype); // sequence number MESSAGE_END(); } if (fullHUDInitRequired || m_bRestored) { g_Skill.SendAllNetworkedSkillVars(this); } // Handled anything that needs resetting m_bRestored = false; } void CBasePlayer::UpdateCTFHud() { if (0 != gmsgPlayerIcon && 0 != gmsgStatusIcon) { if (m_iItems != m_iClientItems) { const unsigned int itemsChanged = m_iItems ^ m_iClientItems; const unsigned int removedItems = m_iClientItems & itemsChanged; const unsigned int addedItems = m_iItems & itemsChanged; m_iClientItems = m_iItems; // Update flag item info for (int id = CTFItem::BlackMesaFlag; id <= CTFItem::OpposingForceFlag; id <<= 1) { bool state; if ((addedItems & id) != 0) { state = true; } else if ((removedItems & id) != 0) { state = false; } else { // Unchanged continue; } MESSAGE_BEGIN(MSG_ALL, gmsgPlayerIcon); g_engfuncs.pfnWriteByte(entindex()); g_engfuncs.pfnWriteByte(static_cast<int>(state)); g_engfuncs.pfnWriteByte(1); g_engfuncs.pfnWriteByte(id); g_engfuncs.pfnMessageEnd(); } // Ugly hack struct ItemData { const char* ClassName; int R, G, B; }; static const ItemData CTFItemData[] = { {"item_ctfljump", 255, 160, 0}, {"item_ctfphev", 128, 160, 255}, {"item_ctfbpack", 255, 255, 0}, {"item_ctfaccel", 255, 0, 0}, {"Unknown", 0, 0, 0}, // Not actually used, but needed to match the index {"item_ctfregen", 0, 255, 0}, }; for (int id = CTFItem::LongJump, i = 0; id <= CTFItem::Regeneration; id <<= 1, ++i) { bool state; if ((addedItems & id) != 0) { state = true; } else if ((removedItems & id) != 0) { state = false; } else { // Unchanged continue; } const auto& itemData{CTFItemData[i]}; MESSAGE_BEGIN(MSG_ONE, gmsgStatusIcon, nullptr, this); g_engfuncs.pfnWriteByte(static_cast<int>(state)); g_engfuncs.pfnWriteString(itemData.ClassName); if (state) { g_engfuncs.pfnWriteByte(itemData.R); g_engfuncs.pfnWriteByte(itemData.G); g_engfuncs.pfnWriteByte(itemData.B); } g_engfuncs.pfnMessageEnd(); MESSAGE_BEGIN(MSG_ALL, gmsgPlayerIcon); g_engfuncs.pfnWriteByte(entindex()); g_engfuncs.pfnWriteByte(static_cast<int>(state)); g_engfuncs.pfnWriteByte(0); g_engfuncs.pfnWriteByte(id); g_engfuncs.pfnMessageEnd(); } } } } bool CBasePlayer::FBecomeProne() { m_afPhysicsFlags |= PFLAG_ONBARNACLE; return true; } void CBasePlayer::BarnacleVictimBitten(CBaseEntity* pevBarnacle) { TakeDamage(pevBarnacle, pevBarnacle, pev->health + pev->armorvalue, DMG_SLASH | DMG_ALWAYSGIB); } void CBasePlayer::BarnacleVictimReleased() { m_afPhysicsFlags &= ~PFLAG_ONBARNACLE; } int CBasePlayer::Illumination() { int iIllum = CBaseEntity::Illumination(); iIllum += m_iWeaponFlash; if (iIllum > 255) return 255; return iIllum; } void CBasePlayer::EnableControl(bool fControl) { if (!fControl) pev->flags |= FL_FROZEN; else pev->flags &= ~FL_FROZEN; } // TODO: move #define DOT_1DEGREE 0.9998476951564 #define DOT_2DEGREE 0.9993908270191 #define DOT_3DEGREE 0.9986295347546 #define DOT_4DEGREE 0.9975640502598 #define DOT_5DEGREE 0.9961946980917 #define DOT_6DEGREE 0.9945218953683 #define DOT_7DEGREE 0.9925461516413 #define DOT_8DEGREE 0.9902680687416 #define DOT_9DEGREE 0.9876883405951 #define DOT_10DEGREE 0.9848077530122 #define DOT_15DEGREE 0.9659258262891 #define DOT_20DEGREE 0.9396926207859 #define DOT_25DEGREE 0.9063077870367 Vector CBasePlayer::GetAutoaimVector(float flDelta) { return GetAutoaimVectorFromPoint(GetGunPosition(), flDelta); } Vector CBasePlayer::GetAutoaimVectorFromPoint(const Vector& vecSrc, float flDelta) { if (g_Skill.GetSkillLevel() == SkillLevel::Hard) { UTIL_MakeVectors(pev->v_angle + pev->punchangle); return gpGlobals->v_forward; } float flDist = 8192; // always use non-sticky autoaim // UNDONE: use sever variable to chose! if (true /*|| g_Skill.GetSkillLevel() == SkillLevel::Medium*/) { m_vecAutoAim = Vector(0, 0, 0); // flDelta *= 0.5; } bool m_fOldTargeting = m_fOnTarget; Vector angles = AutoaimDeflection(vecSrc, flDist, flDelta); // update ontarget if changed if (!g_pGameRules->AllowAutoTargetCrosshair()) m_fOnTarget = false; else if (m_fOldTargeting != m_fOnTarget) { m_pActiveWeapon->UpdateItemInfo(); } if (angles.x > 180) angles.x -= 360; if (angles.x < -180) angles.x += 360; if (angles.y > 180) angles.y -= 360; if (angles.y < -180) angles.y += 360; if (angles.x > 25) angles.x = 25; if (angles.x < -25) angles.x = -25; if (angles.y > 12) angles.y = 12; if (angles.y < -12) angles.y = -12; // always use non-sticky autoaim // UNDONE: use sever variable to chose! if (false || g_Skill.GetSkillLevel() == SkillLevel::Easy) { m_vecAutoAim = m_vecAutoAim * 0.67 + angles * 0.33; } else { m_vecAutoAim = angles * 0.9; } // m_vecAutoAim = m_vecAutoAim * 0.99; // Don't send across network if sv_aim is 0 if (g_psv_aim->value != 0) { if (m_vecAutoAim.x != m_lastx || m_vecAutoAim.y != m_lasty) { SET_CROSSHAIRANGLE(edict(), -m_vecAutoAim.x, m_vecAutoAim.y); m_lastx = m_vecAutoAim.x; m_lasty = m_vecAutoAim.y; } } else { ResetAutoaim(); } // Logger->debug("{} {}", angles.x, angles.y); UTIL_MakeVectors(pev->v_angle + pev->punchangle + m_vecAutoAim); return gpGlobals->v_forward; } Vector CBasePlayer::AutoaimDeflection(const Vector& vecSrc, float flDist, float flDelta) { edict_t* pEdict = UTIL_GetEntityList() + 1; CBaseEntity* pEntity; float bestdot; Vector bestdir; edict_t* bestent; TraceResult tr; if (g_psv_aim->value == 0) { m_fOnTarget = false; return g_vecZero; } UTIL_MakeVectors(pev->v_angle + pev->punchangle + m_vecAutoAim); // try all possible entities bestdir = gpGlobals->v_forward; bestdot = flDelta; // +- 10 degrees bestent = nullptr; m_fOnTarget = false; UTIL_TraceLine(vecSrc, vecSrc + bestdir * flDist, dont_ignore_monsters, edict(), &tr); if (tr.pHit && tr.pHit->v.takedamage != DAMAGE_NO) { // don't look through water if (!((pev->waterlevel != WaterLevel::Head && tr.pHit->v.waterlevel == WaterLevel::Head) || (pev->waterlevel == WaterLevel::Head && tr.pHit->v.waterlevel == WaterLevel::Dry))) { if (tr.pHit->v.takedamage == DAMAGE_AIM) m_fOnTarget = true; return m_vecAutoAim; } } for (int i = 1; i < gpGlobals->maxEntities; i++, pEdict++) { Vector center; Vector dir; float dot; if (0 != pEdict->free) // Not in use continue; if (pEdict->v.takedamage != DAMAGE_AIM) continue; if (pEdict == edict()) continue; pEntity = Instance(pEdict); if (pEntity == nullptr) continue; // if (pev->team > 0 && pEdict->v.team == pev->team) // continue; // don't aim at teammate if (!g_pGameRules->ShouldAutoAim(this, pEntity)) continue; if (!pEntity->IsAlive()) continue; // don't look through water if ((pev->waterlevel != WaterLevel::Head && pEntity->pev->waterlevel == WaterLevel::Head) || (pev->waterlevel == WaterLevel::Head && pEntity->pev->waterlevel == WaterLevel::Dry)) continue; center = pEntity->BodyTarget(vecSrc); dir = (center - vecSrc).Normalize(); // make sure it's in front of the player if (DotProduct(dir, gpGlobals->v_forward) < 0) continue; dot = fabs(DotProduct(dir, gpGlobals->v_right)) + fabs(DotProduct(dir, gpGlobals->v_up)) * 0.5; // tweek for distance dot *= 1.0 + 0.2 * ((center - vecSrc).Length() / flDist); if (dot > bestdot) continue; // to far to turn UTIL_TraceLine(vecSrc, center, dont_ignore_monsters, edict(), &tr); if (tr.flFraction != 1.0 && tr.pHit != pEdict) { // Logger->debug("hit {}, can't see {}", STRING(tr.pHit->v.classname), STRING(pEdict->v.classname)); continue; } // don't shoot at friends if (IRelationship(pEntity) < Relationship::None) { if (!pEntity->IsPlayer() && !g_pGameRules->IsMultiplayer()) // Logger->debug("friend"); continue; } // can shoot at this one bestdot = dot; bestent = pEdict; bestdir = dir; } if (bestent) { bestdir = UTIL_VecToAngles(bestdir); bestdir.x = -bestdir.x; bestdir = bestdir - pev->v_angle - pev->punchangle; if (bestent->v.takedamage == DAMAGE_AIM) m_fOnTarget = true; return bestdir; } return Vector(0, 0, 0); } void CBasePlayer::ResetAutoaim() { if (m_vecAutoAim.x != 0 || m_vecAutoAim.y != 0) { m_vecAutoAim = Vector(0, 0, 0); SET_CROSSHAIRANGLE(edict(), 0, 0); } m_fOnTarget = false; } void CBasePlayer::SetCustomDecalFrames(int nFrames) { if (nFrames > 0 && nFrames < 8) m_nCustomSprayFrames = nFrames; else m_nCustomSprayFrames = -1; } int CBasePlayer::GetCustomDecalFrames() { return m_nCustomSprayFrames; } void CBasePlayer::DropPlayerWeapon(const char* pszItemName) { if (g_Skill.GetValue("allow_player_weapon_dropping", 0) == 0) { return; } if (0 == strlen(pszItemName)) { // if this string has no length, the client didn't type a name! // assume player wants to drop the active item. // make the string null to make future operations in this function easier pszItemName = nullptr; } CBasePlayerWeapon* weapon; int i; for (i = 0; i < MAX_WEAPON_SLOTS; i++) { weapon = m_rgpPlayerWeapons[i]; while (weapon) { if (pszItemName) { // try to match by name. if (0 == strcmp(pszItemName, STRING(weapon->pev->classname))) { // match! break; } } else { // trying to drop active item if (weapon == m_pActiveWeapon) { // active item! break; } } weapon = weapon->m_pNext; } // if we land here with a valid pWeapon pointer, that's because we found the // item we want to drop and hit a BREAK; pWeapon is the item. if (weapon) { if (!g_pGameRules->GetNextBestWeapon(this, weapon)) return; // can't drop the item they asked for, may be our last item or something we can't holster UTIL_MakeVectors(pev->angles); ClearWeaponBit(weapon->m_iId); // take item off hud CWeaponBox* pWeaponBox = (CWeaponBox*)CBaseEntity::Create("weaponbox", pev->origin + gpGlobals->v_forward * 10, pev->angles, this); pWeaponBox->pev->angles.x = 0; pWeaponBox->pev->angles.z = 0; pWeaponBox->PackWeapon(weapon); pWeaponBox->pev->velocity = gpGlobals->v_forward * 300 + gpGlobals->v_forward * 100; // drop half of the ammo for this weapon. int iAmmoIndex; iAmmoIndex = GetAmmoIndex(weapon->pszAmmo1()); // ??? if (iAmmoIndex != -1) { // this weapon weapon uses ammo, so pack an appropriate amount. if ((weapon->iFlags() & ITEM_FLAG_EXHAUSTIBLE) != 0) { // pack up all the ammo, this weapon is its own ammo type pWeaponBox->PackAmmo(MAKE_STRING(weapon->pszAmmo1()), m_rgAmmo[iAmmoIndex]); m_rgAmmo[iAmmoIndex] = 0; } else { // pack half of the ammo pWeaponBox->PackAmmo(MAKE_STRING(weapon->pszAmmo1()), m_rgAmmo[iAmmoIndex] / 2); m_rgAmmo[iAmmoIndex] /= 2; } } return; // we're done, so stop searching with the FOR loop. } } } bool CBasePlayer::HasPlayerWeapon(CBasePlayerWeapon* checkWeapon) { CBasePlayerWeapon* pItem = m_rgpPlayerWeapons[checkWeapon->iItemSlot()]; while (pItem) { if (pItem->ClassnameIs(STRING(checkWeapon->pev->classname))) { return true; } pItem = pItem->m_pNext; } return false; } bool CBasePlayer::HasNamedPlayerWeapon(const char* pszItemName) { CBasePlayerWeapon* weapon; int i; for (i = 0; i < MAX_WEAPON_SLOTS; i++) { weapon = m_rgpPlayerWeapons[i]; while (weapon) { if (0 == strcmp(pszItemName, STRING(weapon->pev->classname))) { return true; } weapon = weapon->m_pNext; } } return false; } bool CBasePlayer::SwitchWeapon(CBasePlayerWeapon* weapon) { if (weapon && !weapon->CanDeploy()) { return false; } ResetAutoaim(); if (m_pActiveWeapon) { m_pActiveWeapon->Holster(); } m_pActiveWeapon = weapon; if (weapon) { weapon->m_ForceSendAnimations = true; weapon->Deploy(); weapon->m_ForceSendAnimations = false; } return true; } void CBasePlayer::Player_Menu() { if (g_pGameRules->IsCTF()) { if (m_iCurrentMenu == MENU_TEAM) { MESSAGE_BEGIN(MSG_ONE, gmsgAllowSpec, nullptr, this); WRITE_BYTE(1); MESSAGE_END(); MESSAGE_BEGIN(MSG_ONE, gmsgTeamNames, nullptr, this); g_engfuncs.pfnWriteByte(2); WRITE_STRING("#CTFTeam_BM"); WRITE_STRING("#CTFTeam_OF"); MESSAGE_END(); MESSAGE_BEGIN(MSG_ONE, gmsgVGUIMenu, nullptr, this); WRITE_BYTE(MENU_TEAM); MESSAGE_END(); } else if (m_iCurrentMenu == MENU_CLASS) { MESSAGE_BEGIN(MSG_ONE, gmsgSetMenuTeam, nullptr, this); WRITE_BYTE(static_cast<int>(m_iNewTeamNum == CTFTeam::None ? m_iTeamNum : m_iNewTeamNum)); MESSAGE_END(); MESSAGE_BEGIN(MSG_ONE, gmsgVGUIMenu, nullptr, this); WRITE_BYTE(MENU_CLASS); MESSAGE_END(); } } } void CBasePlayer::ResetMenu() { if (0 != gmsgShowMenu) { MESSAGE_BEGIN(MSG_ONE, gmsgShowMenu, nullptr, this); WRITE_SHORT(0); WRITE_CHAR(0); WRITE_BYTE(0); WRITE_STRING(""); MESSAGE_END(); } switch (m_iCurrentMenu) { case MENU_DEFAULT: m_iCurrentMenu = MENU_TEAM; break; case MENU_TEAM: m_iCurrentMenu = MENU_CLASS; break; default: m_iCurrentMenu = MENU_NONE; return; } if (g_pGameRules->IsCTF()) Player_Menu(); } bool CBasePlayer::Menu_Team_Input(int inp) { m_iNewTeamNum = CTFTeam::None; if (inp == -1) { g_pGameRules->ChangePlayerTeam(this, nullptr, false, false); MESSAGE_BEGIN(MSG_ONE, gmsgTeamFull, nullptr, this); WRITE_BYTE(0); MESSAGE_END(); return true; } else if (inp == 3) { if (g_pGameRules->TeamsBalanced()) { if (m_iTeamNum == CTFTeam::None) { m_iNewTeamNum = static_cast<CTFTeam>(RANDOM_LONG(0, 1) + 1); if (m_iNewTeamNum <= CTFTeam::None) { m_iNewTeamNum = CTFTeam::BlackMesa; } else if (m_iNewTeamNum > CTFTeam::OpposingForce) { m_iNewTeamNum = CTFTeam::OpposingForce; } } else { m_iNewTeamNum = m_iTeamNum; } } else { m_iNewTeamNum = static_cast<CTFTeam>(g_pGameRules->GetTeamIndex(g_pGameRules->TeamWithFewestPlayers()) + 1); } MESSAGE_BEGIN(MSG_ONE, gmsgTeamFull, nullptr, this); WRITE_BYTE(0); MESSAGE_END(); ResetMenu(); pev->impulse = 0; return true; } else if (inp <= g_pGameRules->GetNumTeams() && inp > 0) { auto unbalanced = false; if (ctf_autoteam.value == 1) { if (m_iTeamNum != static_cast<CTFTeam>(inp)) { if (!g_pGameRules->TeamsBalanced() && inp != g_pGameRules->GetTeamIndex(g_pGameRules->TeamWithFewestPlayers()) + 1) { ClientPrint(this, HUD_PRINTCONSOLE, "Team balancing enabled.\nThis team is full.\n"); MESSAGE_BEGIN(MSG_ONE, gmsgTeamFull, nullptr, this); WRITE_BYTE(1); MESSAGE_END(); unbalanced = true; } else { m_iNewTeamNum = static_cast<CTFTeam>(inp); } } else { m_iNewTeamNum = m_iTeamNum; } } else { m_iNewTeamNum = static_cast<CTFTeam>(inp); } if (!unbalanced) { MESSAGE_BEGIN(MSG_ONE, gmsgTeamFull, nullptr, this); WRITE_BYTE(0); MESSAGE_END(); ResetMenu(); pev->impulse = 0; return true; } } else if (inp == 6 && m_iTeamNum > CTFTeam::None) { m_iCurrentMenu = MENU_NONE; return true; } m_iCurrentMenu = MENU_TEAM; if (g_pGameRules->IsCTF()) Player_Menu(); return false; } bool CBasePlayer::Menu_Char_Input(int inp) { if (m_iNewTeamNum == CTFTeam::None) { ClientPrint(this, HUD_PRINTCONSOLE, "Can't change character; not in a team.\n"); return false; } const char* pszCharacterType; if (inp == 7) { pszCharacterType = g_pGameRules->GetCharacterType(static_cast<int>(m_iNewTeamNum) - 1, RANDOM_LONG(0, 5)); } else { const auto characterIndex = inp - 1; if (characterIndex < 0 || characterIndex > 5) return false; pszCharacterType = g_pGameRules->GetCharacterType(static_cast<int>(m_iNewTeamNum) - 1, characterIndex); } // Kill and gib the player if they're changing teams const auto killAndGib = 0 == pev->iuser1 && m_iTeamNum != m_iNewTeamNum; g_pGameRules->ChangePlayerTeam(this, pszCharacterType, killAndGib, killAndGib); ResetMenu(); pev->impulse = 0; if (0 != pev->iuser1) { m_bIsSpawning = true; pev->effects &= ~EF_NODRAW; pev->flags &= FL_FAKECLIENT; pev->flags |= FL_CLIENT; pev->takedamage = DAMAGE_YES; m_iHideHUD &= ~(HIDEHUD_HEALTH | HIDEHUD_WEAPONS); m_afPhysicsFlags &= PFLAG_OBSERVER; pev->flags &= ~FL_SPECTATOR; MESSAGE_BEGIN(MSG_ALL, gmsgSpectator); WRITE_BYTE(entindex()); WRITE_BYTE(0); MESSAGE_END(); pev->iuser1 = 0; pev->deadflag = 0; pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_WALK; g_pGameRules->GetPlayerSpawnSpot(this); g_pGameRules->PlayerSpawn(this); m_bIsSpawning = false; } return true; } void CBasePlayer::EquipWeapon() { if (m_pActiveWeapon) { if ((!FStringNull(pev->viewmodel) || !FStringNull(pev->weaponmodel))) { // Already have a weapon equipped and deployed. return; } // Have a weapon equipped, but not deployed. if (m_pActiveWeapon->CanDeploy()) { m_pActiveWeapon->m_ForceSendAnimations = true; const bool result = m_pActiveWeapon->Deploy(); m_pActiveWeapon->m_ForceSendAnimations = false; if (result) { return; } } } // No weapon equipped or couldn't deploy it, find a suitable alternative. g_pGameRules->GetNextBestWeapon(this, m_pActiveWeapon, true); } void CBasePlayer::SetPrefsFromUserinfo(char* infobuffer) { const char* value = g_engfuncs.pfnInfoKeyValue(infobuffer, "cl_autowepswitch"); if (g_pGameRules->IsMultiplayer() && '\0' != *value) { m_AutoWepSwitch = std::clamp(static_cast<WeaponSwitchMode>(atoi(value)), WeaponSwitchMode::Never, WeaponSwitchMode::IfBetterAndNotAttacking); } else { m_AutoWepSwitch = WeaponSwitchMode::IfBetter; } } void CBasePlayer::SetHudColor(RGB24 color) { m_HudColor = color.ToInteger(); MESSAGE_BEGIN(MSG_ONE, gmsgHudColor, nullptr, this); g_engfuncs.pfnWriteByte(color.Red); g_engfuncs.pfnWriteByte(color.Green); g_engfuncs.pfnWriteByte(color.Blue); g_engfuncs.pfnMessageEnd(); } static void SendScoreInfoMessage(CBasePlayer* owner) { WRITE_BYTE(owner->entindex()); WRITE_SHORT(owner->pev->frags); WRITE_SHORT(owner->m_iDeaths); // To properly emulate Opposing Force's behavior we need to write -1 for these 2 in CTF. if (g_pGameRules->IsCTF()) { WRITE_SHORT(-1); WRITE_SHORT(-1); } else { WRITE_SHORT(0); WRITE_SHORT(g_pGameRules->GetTeamIndex(owner->m_szTeamName) + 1); } MESSAGE_END(); } void CBasePlayer::SendScoreInfo(CBasePlayer* destination) { MESSAGE_BEGIN(MSG_ONE, gmsgScoreInfo, nullptr, destination); SendScoreInfoMessage(this); } void CBasePlayer::SendScoreInfoAll() { MESSAGE_BEGIN(MSG_ALL, gmsgScoreInfo); SendScoreInfoMessage(this); } static edict_t* SV_TestEntityPosition(CBaseEntity* ent) { // Need to use this trace function so the engine checks the hull during collision tests. TraceResult tr; TRACE_MONSTER_HULL(ent->edict(), ent->pev->origin, ent->pev->origin, dont_ignore_monsters, nullptr, &tr); if (tr.fStartSolid != 0) { return tr.pHit; } return nullptr; } static bool FindPassableSpace(CBaseEntity* ent, const Vector& direction, float step) { for (int i = 100; i > 0; --i) { ent->pev->origin = ent->pev->origin + step * direction; if (!SV_TestEntityPosition(ent)) { ent->pev->oldorigin = ent->pev->origin; return true; } } return false; } static void Noclip_Toggle(CBasePlayer* player) { if (player->pev->movetype == MOVETYPE_NOCLIP) { player->pev->movetype = MOVETYPE_WALK; player->pev->oldorigin = player->pev->origin; if (SV_TestEntityPosition(player)) { Vector forward, right, up; AngleVectors(player->pev->v_angle, forward, right, up); // Try to find a valid position near the player. if (!FindPassableSpace(player, forward, 1) && !FindPassableSpace(player, right, 1) && !FindPassableSpace(player, right, -1) && !FindPassableSpace(player, up, 1) && !FindPassableSpace(player, up, -1) && !FindPassableSpace(player, forward, -1)) { Con_DPrintf("Can't find the world\n"); } player->pev->origin = player->pev->oldorigin; } } else { player->pev->movetype = MOVETYPE_NOCLIP; } } void CBasePlayer::ToggleCheat(Cheat cheat) { switch (cheat) { case Cheat::Godmode: pev->flags ^= FL_GODMODE; UTIL_ConsolePrint(this, "godmode {}\n", (pev->flags & FL_GODMODE) != 0 ? "ON" : "OFF"); break; case Cheat::Unkillable: m_IsUnkillable = !m_IsUnkillable; UTIL_ConsolePrint(this, "Unkillable: {}\n", m_IsUnkillable ? "ON" : "OFF"); break; case Cheat::Notarget: pev->flags ^= FL_NOTARGET; UTIL_ConsolePrint(this, "notarget {}\n", (pev->flags & FL_NOTARGET) != 0 ? "ON" : "OFF"); break; case Cheat::Noclip: Noclip_Toggle(this); UTIL_ConsolePrint(this, "noclip {}\n", pev->movetype == MOVETYPE_NOCLIP ? "ON" : "OFF"); break; case Cheat::InfiniteAir: m_bInfiniteAir = !m_bInfiniteAir; UTIL_ConsolePrint(this, "Infinite air: {}\n", m_bInfiniteAir ? "ON" : "OFF"); break; case Cheat::InfiniteArmor: m_bInfiniteArmor = !m_bInfiniteArmor; UTIL_ConsolePrint(this, "Infinite armor: {}\n", m_bInfiniteArmor ? "ON" : "OFF"); break; case Cheat::Jetpack: SetHasJetpack(!m_JetpackEnabled); UTIL_ConsolePrint(this, "Jetpack: {}\n", m_JetpackEnabled ? "ON" : "OFF"); break; default: UTIL_ConsolePrint(this, "Bogus cheat value!\n"); } } CBasePlayer* FindPlayerByName(const char* name) { for (int i = 1; i <= gpGlobals->maxClients; i++) { CBasePlayer* pEnt = UTIL_PlayerByIndex(i); if (pEnt) { const char* pNetName = STRING(pEnt->pev->netname); if (stricmp(pNetName, name) == 0) { return pEnt; } } } return nullptr; } class CDeadHEV : public CBaseMonster { public: void OnCreate() override; void Spawn() override; bool HasHumanGibs() override { return true; } bool KeyValue(KeyValueData* pkvd) override; int m_iPose; // which sequence to display -- temporary, don't need to save static const char* m_szPoses[4]; }; const char* CDeadHEV::m_szPoses[] = {"deadback", "deadsitting", "deadstomach", "deadtable"}; void CDeadHEV::OnCreate() { CBaseMonster::OnCreate(); // Corpses have less health pev->health = 8; pev->model = MAKE_STRING("models/deadhaz.mdl"); SetClassification("human_military"); } bool CDeadHEV::KeyValue(KeyValueData* pkvd) { if (FStrEq(pkvd->szKeyName, "pose")) { m_iPose = atoi(pkvd->szValue); return true; } return CBaseMonster::KeyValue(pkvd); } LINK_ENTITY_TO_CLASS(monster_hevsuit_dead, CDeadHEV); void CDeadHEV::Spawn() { PrecacheModel(STRING(pev->model)); SetModel(STRING(pev->model)); pev->effects = 0; pev->yaw_speed = 8; pev->sequence = 0; pev->body = 1; m_bloodColor = BLOOD_COLOR_RED; pev->sequence = LookupSequence(m_szPoses[m_iPose]); if (pev->sequence == -1) { Logger->debug("Dead hevsuit with bad pose"); pev->sequence = 0; pev->effects = EF_BRIGHTFIELD; } MonsterInitDead(); } /** * @brief Multiplayer intermission spots. */ class CInfoIntermission : public CPointEntity { void Spawn() override; void Think() override; }; void CInfoIntermission::Spawn() { SetOrigin(pev->origin); pev->solid = SOLID_NOT; pev->effects = EF_NODRAW; pev->v_angle = g_vecZero; pev->nextthink = gpGlobals->time + 2; // let targets spawn! } void CInfoIntermission::Think() { // find my target auto pTarget = UTIL_FindEntityByTargetname(nullptr, STRING(pev->target)); if (!FNullEnt(pTarget)) { pev->v_angle = UTIL_VecToAngles((pTarget->pev->origin - pev->origin).Normalize()); pev->v_angle.x = -pev->v_angle.x; } } LINK_ENTITY_TO_CLASS(info_intermission, CInfoIntermission);
0
0.98131
1
0.98131
game-dev
MEDIA
0.97931
game-dev
0.870052
1
0.870052
klikli-dev/occultism
7,125
src/main/java/com/klikli_dev/occultism/common/entity/possessed/horde/PossessedWeakBreezeEntity.java
/* * MIT License * * Copyright 2020 klikli-dev * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package com.klikli_dev.occultism.common.entity.possessed.horde; import com.klikli_dev.occultism.common.entity.possessed.PossessedMob; import com.klikli_dev.occultism.registry.OccultismEntities; import com.klikli_dev.occultism.registry.OccultismTags; import com.klikli_dev.occultism.util.TextUtil; import net.minecraft.network.chat.Component; import net.minecraft.tags.TagKey; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.SpawnGroupData; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.monster.breeze.Breeze; import net.minecraft.world.level.Level; import net.minecraft.world.level.ServerLevelAccessor; import net.neoforged.neoforge.event.EventHooks; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; public class PossessedWeakBreezeEntity extends Breeze implements PossessedMob { List<WildZombieEntity> minionsA = new ArrayList<>(); List<WildSkeletonEntity> minionsB = new ArrayList<>(); List<WildSilverfishEntity> minionsC = new ArrayList<>(); public PossessedWeakBreezeEntity(EntityType<? extends Breeze> type, Level worldIn) { super(type, worldIn); } //region Static Methods public static AttributeSupplier.Builder createAttributes() { return Breeze.createAttributes(); } @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor level, DifficultyInstance difficultyIn, MobSpawnType reason, @Nullable SpawnGroupData spawnDataIn) { for (int i = 0; i < 3; i++) { WildZombieEntity entity = OccultismEntities.WILD_ZOMBIE.get().create(this.level()); EventHooks.finalizeMobSpawn(entity, level, difficultyIn, reason, spawnDataIn); double offsetX = level.getRandom().nextGaussian() * (1 + level.getRandom().nextInt(4)); double offsetZ = level.getRandom().nextGaussian() * (1 + level.getRandom().nextInt(4)); entity.absMoveTo(this.getBlockX() + offsetX, this.getBlockY() + 1.5, this.getBlockZ() + offsetZ, level.getRandom().nextInt(360), 0); entity.setCustomName(Component.literal(TextUtil.generateName())); level.addFreshEntity(entity); entity.setMaster(this); this.minionsA.add(entity); } for (int i = 0; i < 3; i++) { WildSkeletonEntity entity = OccultismEntities.WILD_SKELETON.get().create(this.level()); EventHooks.finalizeMobSpawn(entity, level, difficultyIn, reason, spawnDataIn); double offsetX = level.getRandom().nextGaussian() * (1 + level.getRandom().nextInt(4)); double offsetZ = level.getRandom().nextGaussian() * (1 + level.getRandom().nextInt(4)); entity.absMoveTo(this.getBlockX() + offsetX, this.getBlockY() + 1.5, this.getBlockZ() + offsetZ, level.getRandom().nextInt(360), 0); entity.setCustomName(Component.literal(TextUtil.generateName())); level.addFreshEntity(entity); entity.setMaster(this); this.minionsB.add(entity); } for (int i = 0; i < 3; i++) { WildSilverfishEntity entity = OccultismEntities.WILD_SILVERFISH.get().create(this.level()); EventHooks.finalizeMobSpawn(entity, level, difficultyIn, reason, spawnDataIn); double offsetX = level.getRandom().nextGaussian() * (1 + level.getRandom().nextInt(4)); double offsetZ = level.getRandom().nextGaussian() * (1 + level.getRandom().nextInt(4)); entity.absMoveTo(this.getBlockX() + offsetX, this.getBlockY() + 1.5, this.getBlockZ() + offsetZ, level.getRandom().nextInt(360), 0); entity.setCustomName(Component.literal(TextUtil.generateName())); level.addFreshEntity(entity); entity.setMaster(this); this.minionsC.add(entity); } return super.finalizeSpawn(level, difficultyIn, reason, spawnDataIn); } @Override public boolean isInvulnerableTo(DamageSource source) { if (isInvulnerable()) { minionsA.forEach(e -> e.addEffect(new MobEffectInstance(MobEffects.GLOWING, 100, 0, false, false))); minionsB.forEach(e -> e.addEffect(new MobEffectInstance(MobEffects.GLOWING, 100, 0, false, false))); minionsC.forEach(e -> e.addEffect(new MobEffectInstance(MobEffects.GLOWING, 100, 0, false, false))); return true; } TagKey<EntityType<?>> wildTrialTag = OccultismTags.Entities.WILD_TRIAL; Entity trueSource = source.getEntity(); if (trueSource != null && trueSource.getType().is(wildTrialTag)) return true; Entity immediateSource = source.getDirectEntity(); if (immediateSource != null && immediateSource.getType().is(wildTrialTag)) return true; return super.isInvulnerableTo(source); } @Override protected boolean shouldDespawnInPeaceful() { return false; } @Override public boolean isInvulnerable() { return !this.minionsA.isEmpty() || !this.minionsB.isEmpty() || !this.minionsC.isEmpty() || super.isInvulnerable(); } public void notifyMinionDeath(WildZombieEntity minion) { this.minionsA.remove(minion); } public void notifyMinionDeath(WildSkeletonEntity minion) { this.minionsB.remove(minion); } public void notifyMinionDeath(WildSilverfishEntity minion) { this.minionsC.remove(minion); } @Override public EntityType basedMob(){ return EntityType.BREEZE; } }
0
0.864058
1
0.864058
game-dev
MEDIA
0.988927
game-dev
0.957625
1
0.957625
jordoncodes/swift-disguise
4,306
api/src/main/java/me/onlyjordon/swiftdisguise/api/SwiftDisguiseLoader.java
package me.onlyjordon.swiftdisguise.api; import me.onlyjordon.swiftdisguise.utils.Util; import org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; @ApiStatus.Internal public class SwiftDisguiseLoader { private static SwiftDisguiseConfig config; private static YamlConfiguration yamlConfig; private static File configFile; public static File getConfigFile() { return configFile; } public static SwiftDisguiseConfig getConfig() { return config; } public static YamlConfiguration getYamlConfig() { return yamlConfig; } @ApiStatus.Internal public static void load() { configFile = new File(Util.getDataFolder().getAbsolutePath() + File.separator + "config.yml"); if (!configFile.exists()) { if (!configFile.getParentFile().exists()) { configFile.getParentFile().mkdirs(); } try { configFile.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } yamlConfig = YamlConfiguration.loadConfiguration(configFile); loadDefaultConfigValues(); SwiftDisguiseConfig.UUIDHidingMode hidingMode = getEnum(yamlConfig, "settings.uuid-hiding-mode", SwiftDisguiseConfig.UUIDHidingMode.class, SwiftDisguiseConfig.UUIDHidingMode.RANDOM); SwiftDisguiseConfig.NameMode nameMode = getEnum(yamlConfig, "settings.name-mode", SwiftDisguiseConfig.NameMode.class, SwiftDisguiseConfig.NameMode.WEAK); config = SwiftDisguiseConfig.create(hidingMode, nameMode); } private static <E extends Enum<E>> E getEnum(YamlConfiguration configuration, String path, Class<E> enumClass, E defaultValue) { String value = configuration.getString(path); E enumValue = null; try { enumValue = Enum.valueOf(enumClass, configuration.getString(path, defaultValue.toString())); } catch (IllegalArgumentException ignored) {} if (value == null) { System.err.println("Invalid enum value at (" + path + "), using default value: " + defaultValue.toString()); } return Optional.ofNullable(enumValue).orElse(defaultValue); } private static void setDefaultValue(String path, Object value) { if (!yamlConfig.contains(path)) { yamlConfig.set(path, value); } } private static void loadDefaultConfigValues() { setDefaultValue("settings.uuid-hiding-mode",SwiftDisguiseConfig.UUIDHidingMode.RANDOM.toString()); setDefaultValue("settings.name-mode",SwiftDisguiseConfig.NameMode.WEAK.toString()); yamlConfig.setComments("settings", Collections.singletonList("The settings for SwiftDisguise")); yamlConfig.setComments("settings.uuid-hiding-mode", getUUIDHidingModeComments()); yamlConfig.setComments("settings.name-mode", getNameModeComments()); saveConfig(); } private static void saveConfig() { try { yamlConfig.save(configFile); } catch (Exception e) { e.printStackTrace(); } } private static List<String> getUUIDHidingModeComments() { List<String> uuidHidingComments = new ArrayList<>(); uuidHidingComments.add("The mode to use for hiding UUIDs"); uuidHidingComments.add("NONE - No UUID hiding will be done"); uuidHidingComments.add("RANDOM - Random UUIDs for each player"); return uuidHidingComments; } @NotNull private static List<String> getNameModeComments() { List<String> nameModeComments = new ArrayList<>(); nameModeComments.add("The mode to use for player names"); nameModeComments.add("WEAK - The server will think the player's name is their real name - commands will be the same as if they weren't nicked"); nameModeComments.add("STRONG - less compatibility, can have issues as the server thinks your name is the nickname, tab completion + commands show nickname (commands sometimes work with nicknames)"); return nameModeComments; } }
0
0.896231
1
0.896231
game-dev
MEDIA
0.590281
game-dev
0.860348
1
0.860348
edge-classic/EDGE-classic
28,219
libraries/sdl2/msvc/include/SDL2/SDL_rwops.h
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* WIKI CATEGORY: RWOPS */ /** * # CategoryRWOPS * * This file provides a general interface for SDL to read and write data * streams. It can easily be extended to files, memory, etc. */ #ifndef SDL_rwops_h_ #define SDL_rwops_h_ #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* RWops Types */ #define SDL_RWOPS_UNKNOWN 0U /**< Unknown stream type */ #define SDL_RWOPS_WINFILE 1U /**< Win32 file */ #define SDL_RWOPS_STDFILE 2U /**< Stdio file */ #define SDL_RWOPS_JNIFILE 3U /**< Android asset */ #define SDL_RWOPS_MEMORY 4U /**< Memory stream */ #define SDL_RWOPS_MEMORY_RO 5U /**< Read-Only memory stream */ /** * This is the read/write operation structure -- very basic. */ typedef struct SDL_RWops { /** * Return the size of the file in this rwops, or -1 if unknown */ Sint64 (SDLCALL * size) (struct SDL_RWops * context); /** * Seek to `offset` relative to `whence`, one of stdio's whence values: * RW_SEEK_SET, RW_SEEK_CUR, RW_SEEK_END * * \return the final offset in the data stream, or -1 on error. */ Sint64 (SDLCALL * seek) (struct SDL_RWops * context, Sint64 offset, int whence); /** * Read up to `maxnum` objects each of size `size` from the data * stream to the area pointed at by `ptr`. * * \return the number of objects read, or 0 at error or end of file. */ size_t (SDLCALL * read) (struct SDL_RWops * context, void *ptr, size_t size, size_t maxnum); /** * Write exactly `num` objects each of size `size` from the area * pointed at by `ptr` to data stream. * * \return the number of objects written, or 0 at error or end of file. */ size_t (SDLCALL * write) (struct SDL_RWops * context, const void *ptr, size_t size, size_t num); /** * Close and free an allocated SDL_RWops structure. * * \return 0 if successful or -1 on write error when flushing data. */ int (SDLCALL * close) (struct SDL_RWops * context); Uint32 type; union { #if defined(__ANDROID__) struct { void *asset; } androidio; #elif defined(__WIN32__) || defined(__GDK__) struct { SDL_bool append; void *h; struct { void *data; size_t size; size_t left; } buffer; } windowsio; #endif #ifdef HAVE_STDIO_H struct { SDL_bool autoclose; FILE *fp; } stdio; #endif struct { Uint8 *base; Uint8 *here; Uint8 *stop; } mem; struct { void *data1; void *data2; } unknown; } hidden; } SDL_RWops; /** * \name RWFrom functions * * Functions to create SDL_RWops structures from various data streams. */ /* @{ */ /** * Use this function to create a new SDL_RWops structure for reading from * and/or writing to a named file. * * The `mode` string is treated roughly the same as in a call to the C * library's fopen(), even if SDL doesn't happen to use fopen() behind the * scenes. * * Available `mode` strings: * * - "r": Open a file for reading. The file must exist. * - "w": Create an empty file for writing. If a file with the same name * already exists its content is erased and the file is treated as a new * empty file. * - "a": Append to a file. Writing operations append data at the end of the * file. The file is created if it does not exist. * - "r+": Open a file for update both reading and writing. The file must * exist. * - "w+": Create an empty file for both reading and writing. If a file with * the same name already exists its content is erased and the file is * treated as a new empty file. * - "a+": Open a file for reading and appending. All writing operations are * performed at the end of the file, protecting the previous content to be * overwritten. You can reposition (fseek, rewind) the internal pointer to * anywhere in the file for reading, but writing operations will move it * back to the end of file. The file is created if it does not exist. * * **NOTE**: In order to open a file as a binary file, a "b" character has to * be included in the `mode` string. This additional "b" character can either * be appended at the end of the string (thus making the following compound * modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the * letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+"). * Additional characters may follow the sequence, although they should have no * effect. For example, "t" is sometimes appended to make explicit the file is * a text file. * * This function supports Unicode filenames, but they must be encoded in UTF-8 * format, regardless of the underlying operating system. * * As a fallback, SDL_RWFromFile() will transparently open a matching filename * in an Android app's `assets`. * * Closing the SDL_RWops will close the file handle SDL is holding internally. * * \param file a UTF-8 string representing the filename to open. * \param mode an ASCII string representing the mode to be used for opening * the file. * \returns a pointer to the SDL_RWops structure that is created, or NULL on * failure; call SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWseek * \sa SDL_RWtell * \sa SDL_RWwrite */ extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFile(const char *file, const char *mode); #ifdef HAVE_STDIO_H extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(FILE * fp, SDL_bool autoclose); #else /** * Use this function to create an SDL_RWops structure from a standard I/O file * pointer (stdio.h's `FILE*`). * * This function is not available on Windows, since files opened in an * application on that platform cannot be used by a dynamically linked * library. * * On some platforms, the first parameter is a `void*`, on others, it's a * `FILE*`, depending on what system headers are available to SDL. It is * always intended to be the `FILE*` type from the C runtime's stdio.h. * * \param fp the `FILE*` that feeds the SDL_RWops stream. * \param autoclose SDL_TRUE to close the `FILE*` when closing the SDL_RWops, * SDL_FALSE to leave the `FILE*` open when the RWops is * closed. * \returns a pointer to the SDL_RWops structure that is created, or NULL on * failure; call SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWseek * \sa SDL_RWtell * \sa SDL_RWwrite */ extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(void * fp, SDL_bool autoclose); #endif /** * Use this function to prepare a read-write memory buffer for use with * SDL_RWops. * * This function sets up an SDL_RWops struct based on a memory area of a * certain size, for both read and write access. * * This memory buffer is not copied by the RWops; the pointer you provide must * remain valid until you close the stream. Closing the stream will not free * the original buffer. * * If you need to make sure the RWops never writes to the memory buffer, you * should use SDL_RWFromConstMem() with a read-only buffer of memory instead. * * \param mem a pointer to a buffer to feed an SDL_RWops stream. * \param size the buffer size, in bytes. * \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWseek * \sa SDL_RWtell * \sa SDL_RWwrite */ extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromMem(void *mem, int size); /** * Use this function to prepare a read-only memory buffer for use with RWops. * * This function sets up an SDL_RWops struct based on a memory area of a * certain size. It assumes the memory area is not writable. * * Attempting to write to this RWops stream will report an error without * writing to the memory buffer. * * This memory buffer is not copied by the RWops; the pointer you provide must * remain valid until you close the stream. Closing the stream will not free * the original buffer. * * If you need to write to a memory buffer, you should use SDL_RWFromMem() * with a writable buffer of memory instead. * * \param mem a pointer to a read-only buffer to feed an SDL_RWops stream. * \param size the buffer size, in bytes. * \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWseek * \sa SDL_RWtell */ extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromConstMem(const void *mem, int size); /* @} *//* RWFrom functions */ /** * Use this function to allocate an empty, unpopulated SDL_RWops structure. * * Applications do not need to use this function unless they are providing * their own SDL_RWops implementation. If you just need a SDL_RWops to * read/write a common data source, you should use the built-in * implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc. * * You must free the returned pointer with SDL_FreeRW(). Depending on your * operating system and compiler, there may be a difference between the * malloc() and free() your program uses and the versions SDL calls * internally. Trying to mix the two can cause crashing such as segmentation * faults. Since all SDL_RWops must free themselves when their **close** * method is called, all SDL_RWops must be allocated through this function, so * they can all be freed correctly with SDL_FreeRW(). * * \returns a pointer to the allocated memory on success, or NULL on failure; * call SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_FreeRW */ extern DECLSPEC SDL_RWops *SDLCALL SDL_AllocRW(void); /** * Use this function to free an SDL_RWops structure allocated by * SDL_AllocRW(). * * Applications do not need to use this function unless they are providing * their own SDL_RWops implementation. If you just need a SDL_RWops to * read/write a common data source, you should use the built-in * implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc, and * call the **close** method on those SDL_RWops pointers when you are done * with them. * * Only use SDL_FreeRW() on pointers returned by SDL_AllocRW(). The pointer is * invalid as soon as this function returns. Any extra memory allocated during * creation of the SDL_RWops is not freed by SDL_FreeRW(); the programmer must * be responsible for managing that memory in their **close** method. * * \param area the SDL_RWops structure to be freed. * * \since This function is available since SDL 2.0.0. * * \sa SDL_AllocRW */ extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops * area); /* Possible `whence` values for SDL_RWops seeking... */ #define RW_SEEK_SET 0 /**< Seek from the beginning of data */ #define RW_SEEK_CUR 1 /**< Seek relative to current read point */ #define RW_SEEK_END 2 /**< Seek relative to the end of data */ /** * Use this function to get the size of the data stream in an SDL_RWops. * * Prior to SDL 2.0.10, this function was a macro. * * \param context the SDL_RWops to get the size of the data stream from. * \returns the size of the data stream in the SDL_RWops on success, -1 if * unknown or a negative error code on failure; call SDL_GetError() * for more information. * * \since This function is available since SDL 2.0.10. */ extern DECLSPEC Sint64 SDLCALL SDL_RWsize(SDL_RWops *context); /** * Seek within an SDL_RWops data stream. * * This function seeks to byte `offset`, relative to `whence`. * * `whence` may be any of the following values: * * - `RW_SEEK_SET`: seek from the beginning of data * - `RW_SEEK_CUR`: seek relative to current read point * - `RW_SEEK_END`: seek relative to the end of data * * If this stream can not seek, it will return -1. * * SDL_RWseek() is actually a wrapper function that calls the SDL_RWops's * `seek` method appropriately, to simplify application development. * * Prior to SDL 2.0.10, this function was a macro. * * \param context a pointer to an SDL_RWops structure. * \param offset an offset in bytes, relative to **whence** location; can be * negative. * \param whence any of `RW_SEEK_SET`, `RW_SEEK_CUR`, `RW_SEEK_END`. * \returns the final offset in the data stream after the seek or -1 on error. * * \since This function is available since SDL 2.0.10. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWtell * \sa SDL_RWwrite */ extern DECLSPEC Sint64 SDLCALL SDL_RWseek(SDL_RWops *context, Sint64 offset, int whence); /** * Determine the current read/write offset in an SDL_RWops data stream. * * SDL_RWtell is actually a wrapper function that calls the SDL_RWops's `seek` * method, with an offset of 0 bytes from `RW_SEEK_CUR`, to simplify * application development. * * Prior to SDL 2.0.10, this function was a macro. * * \param context a SDL_RWops data stream object from which to get the current * offset. * \returns the current offset in the stream, or -1 if the information can not * be determined. * * \since This function is available since SDL 2.0.10. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWseek * \sa SDL_RWwrite */ extern DECLSPEC Sint64 SDLCALL SDL_RWtell(SDL_RWops *context); /** * Read from a data source. * * This function reads up to `maxnum` objects each of size `size` from the * data source to the area pointed at by `ptr`. This function may read less * objects than requested. It will return zero when there has been an error or * the data stream is completely read. * * SDL_RWread() is actually a function wrapper that calls the SDL_RWops's * `read` method appropriately, to simplify application development. * * Prior to SDL 2.0.10, this function was a macro. * * \param context a pointer to an SDL_RWops structure. * \param ptr a pointer to a buffer to read data into. * \param size the size of each object to read, in bytes. * \param maxnum the maximum number of objects to be read. * \returns the number of objects read, or 0 at error or end of file; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.10. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWseek * \sa SDL_RWwrite */ extern DECLSPEC size_t SDLCALL SDL_RWread(SDL_RWops *context, void *ptr, size_t size, size_t maxnum); /** * Write to an SDL_RWops data stream. * * This function writes exactly `num` objects each of size `size` from the * area pointed at by `ptr` to the stream. If this fails for any reason, it'll * return less than `num` to demonstrate how far the write progressed. On * success, it returns `num`. * * SDL_RWwrite is actually a function wrapper that calls the SDL_RWops's * `write` method appropriately, to simplify application development. * * Prior to SDL 2.0.10, this function was a macro. * * \param context a pointer to an SDL_RWops structure. * \param ptr a pointer to a buffer containing data to write. * \param size the size of an object to write, in bytes. * \param num the number of objects to write. * \returns the number of objects written, which will be less than **num** on * error; call SDL_GetError() for more information. * * \since This function is available since SDL 2.0.10. * * \sa SDL_RWclose * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWseek */ extern DECLSPEC size_t SDLCALL SDL_RWwrite(SDL_RWops *context, const void *ptr, size_t size, size_t num); /** * Close and free an allocated SDL_RWops structure. * * SDL_RWclose() closes and cleans up the SDL_RWops stream. It releases any * resources used by the stream and frees the SDL_RWops itself with * SDL_FreeRW(). This returns 0 on success, or -1 if the stream failed to * flush to its output (e.g. to disk). * * Note that if this fails to flush the stream to disk, this function reports * an error, but the SDL_RWops is still invalid once this function returns. * * Prior to SDL 2.0.10, this function was a macro. * * \param context SDL_RWops structure to close. * \returns 0 on success or a negative error code on failure; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.10. * * \sa SDL_RWFromConstMem * \sa SDL_RWFromFile * \sa SDL_RWFromFP * \sa SDL_RWFromMem * \sa SDL_RWread * \sa SDL_RWseek * \sa SDL_RWwrite */ extern DECLSPEC int SDLCALL SDL_RWclose(SDL_RWops *context); /** * Load all the data from an SDL data stream. * * The data is allocated with a zero byte at the end (null terminated) for * convenience. This extra byte is not included in the value reported via * `datasize`. * * The data should be freed with SDL_free(). * * \param src the SDL_RWops to read all available data from. * \param datasize if not NULL, will store the number of bytes read. * \param freesrc if non-zero, calls SDL_RWclose() on `src` before returning. * \returns the data, or NULL if there was an error. * * \since This function is available since SDL 2.0.6. */ extern DECLSPEC void *SDLCALL SDL_LoadFile_RW(SDL_RWops *src, size_t *datasize, int freesrc); /** * Load all the data from a file path. * * The data is allocated with a zero byte at the end (null terminated) for * convenience. This extra byte is not included in the value reported via * `datasize`. * * The data should be freed with SDL_free(). * * Prior to SDL 2.0.10, this function was a macro wrapping around * SDL_LoadFile_RW. * * \param file the path to read all available data from. * \param datasize if not NULL, will store the number of bytes read. * \returns the data, or NULL if there was an error. * * \since This function is available since SDL 2.0.10. */ extern DECLSPEC void *SDLCALL SDL_LoadFile(const char *file, size_t *datasize); /** * \name Read endian functions * * Read an item of the specified endianness and return in native format. */ /* @{ */ /** * Use this function to read a byte from an SDL_RWops. * * \param src the SDL_RWops to read from. * \returns the read byte on success or 0 on failure; call SDL_GetError() for * more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_WriteU8 */ extern DECLSPEC Uint8 SDLCALL SDL_ReadU8(SDL_RWops * src); /** * Use this function to read 16 bits of little-endian data from an SDL_RWops * and return in native format. * * SDL byteswaps the data only if necessary, so the data returned will be in * the native byte order. * * \param src the stream from which to read data. * \returns 16 bits of data in the native byte order of the platform. * * \since This function is available since SDL 2.0.0. * * \sa SDL_ReadBE16 */ extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops * src); /** * Use this function to read 16 bits of big-endian data from an SDL_RWops and * return in native format. * * SDL byteswaps the data only if necessary, so the data returned will be in * the native byte order. * * \param src the stream from which to read data. * \returns 16 bits of data in the native byte order of the platform. * * \since This function is available since SDL 2.0.0. * * \sa SDL_ReadLE16 */ extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops * src); /** * Use this function to read 32 bits of little-endian data from an SDL_RWops * and return in native format. * * SDL byteswaps the data only if necessary, so the data returned will be in * the native byte order. * * \param src the stream from which to read data. * \returns 32 bits of data in the native byte order of the platform. * * \since This function is available since SDL 2.0.0. * * \sa SDL_ReadBE32 */ extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops * src); /** * Use this function to read 32 bits of big-endian data from an SDL_RWops and * return in native format. * * SDL byteswaps the data only if necessary, so the data returned will be in * the native byte order. * * \param src the stream from which to read data. * \returns 32 bits of data in the native byte order of the platform. * * \since This function is available since SDL 2.0.0. * * \sa SDL_ReadLE32 */ extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops * src); /** * Use this function to read 64 bits of little-endian data from an SDL_RWops * and return in native format. * * SDL byteswaps the data only if necessary, so the data returned will be in * the native byte order. * * \param src the stream from which to read data. * \returns 64 bits of data in the native byte order of the platform. * * \since This function is available since SDL 2.0.0. * * \sa SDL_ReadBE64 */ extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops * src); /** * Use this function to read 64 bits of big-endian data from an SDL_RWops and * return in native format. * * SDL byteswaps the data only if necessary, so the data returned will be in * the native byte order. * * \param src the stream from which to read data. * \returns 64 bits of data in the native byte order of the platform. * * \since This function is available since SDL 2.0.0. * * \sa SDL_ReadLE64 */ extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops * src); /* @} *//* Read endian functions */ /** * \name Write endian functions * * Write an item of native format to the specified endianness. */ /* @{ */ /** * Use this function to write a byte to an SDL_RWops. * * \param dst the SDL_RWops to write to. * \param value the byte value to write. * \returns 1 on success or 0 on failure; call SDL_GetError() for more * information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_ReadU8 */ extern DECLSPEC size_t SDLCALL SDL_WriteU8(SDL_RWops * dst, Uint8 value); /** * Use this function to write 16 bits in native format to a SDL_RWops as * little-endian data. * * SDL byteswaps the data only if necessary, so the application always * specifies native format, and the data written will be in little-endian * format. * * \param dst the stream to which data will be written. * \param value the data to be written, in native format. * \returns 1 on successful write, 0 on error. * * \since This function is available since SDL 2.0.0. * * \sa SDL_WriteBE16 */ extern DECLSPEC size_t SDLCALL SDL_WriteLE16(SDL_RWops * dst, Uint16 value); /** * Use this function to write 16 bits in native format to a SDL_RWops as * big-endian data. * * SDL byteswaps the data only if necessary, so the application always * specifies native format, and the data written will be in big-endian format. * * \param dst the stream to which data will be written. * \param value the data to be written, in native format. * \returns 1 on successful write, 0 on error. * * \since This function is available since SDL 2.0.0. * * \sa SDL_WriteLE16 */ extern DECLSPEC size_t SDLCALL SDL_WriteBE16(SDL_RWops * dst, Uint16 value); /** * Use this function to write 32 bits in native format to a SDL_RWops as * little-endian data. * * SDL byteswaps the data only if necessary, so the application always * specifies native format, and the data written will be in little-endian * format. * * \param dst the stream to which data will be written. * \param value the data to be written, in native format. * \returns 1 on successful write, 0 on error. * * \since This function is available since SDL 2.0.0. * * \sa SDL_WriteBE32 */ extern DECLSPEC size_t SDLCALL SDL_WriteLE32(SDL_RWops * dst, Uint32 value); /** * Use this function to write 32 bits in native format to a SDL_RWops as * big-endian data. * * SDL byteswaps the data only if necessary, so the application always * specifies native format, and the data written will be in big-endian format. * * \param dst the stream to which data will be written. * \param value the data to be written, in native format. * \returns 1 on successful write, 0 on error. * * \since This function is available since SDL 2.0.0. * * \sa SDL_WriteLE32 */ extern DECLSPEC size_t SDLCALL SDL_WriteBE32(SDL_RWops * dst, Uint32 value); /** * Use this function to write 64 bits in native format to a SDL_RWops as * little-endian data. * * SDL byteswaps the data only if necessary, so the application always * specifies native format, and the data written will be in little-endian * format. * * \param dst the stream to which data will be written. * \param value the data to be written, in native format. * \returns 1 on successful write, 0 on error. * * \since This function is available since SDL 2.0.0. * * \sa SDL_WriteBE64 */ extern DECLSPEC size_t SDLCALL SDL_WriteLE64(SDL_RWops * dst, Uint64 value); /** * Use this function to write 64 bits in native format to a SDL_RWops as * big-endian data. * * SDL byteswaps the data only if necessary, so the application always * specifies native format, and the data written will be in big-endian format. * * \param dst the stream to which data will be written. * \param value the data to be written, in native format. * \returns 1 on successful write, 0 on error. * * \since This function is available since SDL 2.0.0. * * \sa SDL_WriteLE64 */ extern DECLSPEC size_t SDLCALL SDL_WriteBE64(SDL_RWops * dst, Uint64 value); /* @} *//* Write endian functions */ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_rwops_h_ */ /* vi: set ts=4 sw=4 expandtab: */
0
0.946142
1
0.946142
game-dev
MEDIA
0.33435
game-dev
0.750604
1
0.750604
Greavesy1899/MafiaToolkit
1,491
Mafia2Libs/ResourceTypes/FileTypes/Prefab/CrashObject/S_InitActionPointData.cs
using BitStreams; using System.Diagnostics; using Utils.Logging; namespace ResourceTypes.Prefab.CrashObject { public class S_InitActionPointData { public byte Unk0 { get; set; } public string Unk1 { get; set; } public byte Unk2 { get; set; } public string Unk3 { get; set; } // 100% not a hash public float[] Unk4 { get; set; } // Could be two C_Vector3s. A box? public S_InitActionPointData() { Unk1 = string.Empty; Unk3 = string.Empty; Unk4 = new float[6]; } public void Load(BitStream MemStream) { Unk0 = MemStream.ReadBit(); ToolkitAssert.Ensure(Unk0 == 1, "Extra data detected"); Unk1 = MemStream.ReadString32(); Unk2 = MemStream.ReadBit(); ToolkitAssert.Ensure(Unk2 == 1, "Extra data detected"); Unk3 = MemStream.ReadString32(); Unk4 = new float[6]; for (int i = 0; i < Unk4.Length; i++) { Unk4[i] = MemStream.ReadSingle(); } } public void Save(BitStream MemStream) { MemStream.WriteBit(Unk0); MemStream.WriteString32(Unk1); MemStream.WriteBit(Unk2); MemStream.WriteString32(Unk3); // Write floats for(int i = 0; i < 6; i++) { MemStream.WriteSingle(Unk4[i]); } } } }
0
0.527485
1
0.527485
game-dev
MEDIA
0.911125
game-dev
0.685758
1
0.685758
TaiyitistMC/Taiyitist
1,812
nms-patches/net/minecraft/commands/arguments/selector/ArgumentParserSelector.patch
--- a/net/minecraft/commands/arguments/selector/ArgumentParserSelector.java +++ b/net/minecraft/commands/arguments/selector/ArgumentParserSelector.java @@ -158,7 +158,7 @@ axisalignedbb = this.createAabb(this.deltaX == null ? 0.0D : this.deltaX, this.deltaY == null ? 0.0D : this.deltaY, this.deltaZ == null ? 0.0D : this.deltaZ); } - Function function; + Function<Vec3D, Vec3D> function; // CraftBukkit - decompile error if (this.x == null && this.y == null && this.z == null) { function = (vec3d) -> { @@ -215,8 +215,10 @@ }; } - protected void parseSelector() throws CommandSyntaxException { - this.usesSelectors = true; + // CraftBukkit start + protected void parseSelector(boolean overridePermissions) throws CommandSyntaxException { + this.usesSelectors = !overridePermissions; + // CraftBukkit end this.suggestions = this::suggestSelector; if (!this.reader.canRead()) { throw ArgumentParserSelector.ERROR_MISSING_SELECTOR_TYPE.createWithContext(this.reader); @@ -505,6 +507,12 @@ } public EntitySelector parse() throws CommandSyntaxException { + // CraftBukkit start + return parse(false); + } + + public EntitySelector parse(boolean overridePermissions) throws CommandSyntaxException { + // CraftBukkit end this.startPosition = this.reader.getCursor(); this.suggestions = this::suggestNameOrSelector; if (this.reader.canRead() && this.reader.peek() == '@') { @@ -513,7 +521,7 @@ } this.reader.skip(); - this.parseSelector(); + this.parseSelector(overridePermissions); // CraftBukkit } else { this.parseNameOrUUID(); }
0
0.883652
1
0.883652
game-dev
MEDIA
0.929624
game-dev
0.911934
1
0.911934
jesses/wck
7,787
Box2DAS/Dynamics/Contacts/b2Contact.as
package Box2DAS.Dynamics.Contacts { import Box2DAS.*; import Box2DAS.Collision.*; import Box2DAS.Collision.Shapes.*; import Box2DAS.Common.*; import Box2DAS.Dynamics.*; import Box2DAS.Dynamics.Contacts.*; import Box2DAS.Dynamics.Joints.*; import cmodule.Box2D.*; /// The class manages contact between two shapes. A contact exists for each overlapping /// AABB in the broad-phase (except if filtered). Therefore a contact object may exist /// that has no contact points. public class b2Contact extends b2Base { public function b2Contact(p:int, fA:b2Fixture = null, fB:b2Fixture = null) { _ptr = p; m_manifold = new b2Manifold(_ptr + 64); /// Address of b2Fixture + userData offset -> deref to AS3 = AS3 b2Fixture. m_fixtureA = fA ? fA : deref(mem._mr32(mem._mr32(_ptr + 48) + 44)) as b2Fixture; m_fixtureB = fB ? fB : deref(mem._mr32(mem._mr32(_ptr + 52) + 44)) as b2Fixture; } // Used when crawling contact graph when forming islands. public static var e_islandFlag:int = 0x0001; // Set when the shapes are touching. public static var e_touchingFlag:int = 0x0002; // This contact can be disabled (by user) public static var e_enabledFlag:int = 0x0004; // This contact needs filtering because a fixture filter was changed. public static var e_filterFlag:int = 0x0008; // This bullet contact had a TOI event public static var e_bulletHitFlag:int = 0x0010; // This contact has a valid TOI in m_toi public static var e_toiFlag:int = 0x0020; /* /// This contact should not participate in Solve /// The contact equivalent of sensors public static var e_sensorFlag:int = 0x0001; /// Generate TOI events public static var e_continuousFlag:int = 0x0002; /// Used when crawling contact graph when forming islands. public static var e_islandFlag:int = 0x0004; /// Used in SolveTOI to indicate the cached toi value is still valid. public static var e_toiFlag:int = 0x0008; /// Set when the shapes are touching. public static var e_touchingFlag:int = 0x0010; /// Disabled (by user) public static var e_enabledFlag:int = 0x0020; /// This contact needs filtering because a fixture filter was changed. public static var e_filterFlag:int = 0x0040; */ /// Get the contact manifold. Do not set the point count to zero. Instead /// call Disable. /// b2Manifold* GetManifold(); public function GetManifold():b2Manifold { return m_manifold; } /// Get the world manifold. /// void GetWorldManifold(b2WorldManifold* worldManifold) const; public function GetWorldManifold(worldManifold:b2WorldManifold):void { var bodyA:b2Body = m_fixtureA.GetBody(); var bodyB:b2Body= m_fixtureB.GetBody(); var shapeA:b2Shape = m_fixtureA.GetShape(); var shapeB:b2Shape = m_fixtureB.GetShape(); worldManifold.Initialize(m_manifold, bodyA.GetTransform(), shapeA.m_radius, bodyB.GetTransform(), shapeB.m_radius); } /// Is this contact solid? Returns false if the shapes are separate, /// sensors, or the contact has been disabled. /// @return true if this contact should generate a response. /// bool IsSolid() const; public function IsSolid():Boolean { return IsTouching() //&& !IsSensor(); } /// Is this contact touching. /// bool IsTouching() const; public function IsTouching():Boolean { return (m_flags & e_touchingFlag) != 0; } /// Does this contact generate TOI events for continuous simulation? /// bool IsContinuous() const; /* public function IsContinuous():Boolean { return (m_flags & e_continuousFlag) != 0; }*/ /// Is this contact a sensor? /// bool IsSensor() const; /*public function IsSensor():Boolean { return (m_flags & e_sensorFlag) == e_sensorFlag; }*/ /// Change this to be a sensor or non-sensor contact. /// void SetAsSensor(bool sensor); /// AS3 ONLY: the value passed to here is cached, so it can be easily determined later /// if the contact was explicitly disabled via this method. /*public function SetSensor(sensor:Boolean):void { _setSensor = sensor; if(sensor) { m_flags |= e_sensorFlag; } else { m_flags &= ~e_sensorFlag; } } public var _setSensor:Boolean = false;*/ /// Disable this contact. This can be used inside the pre-solve /// contact listener. The contact is only disabled for the current /// time step (or sub-step in continuous collisions). /// void Disable(); public function Disable():void { m_flags &= ~e_enabledFlag; } /// Enable/disable this contact. This can be used inside the pre-solve /// contact listener. The contact is only disabled for the current /// time step (or sub-step in continuous collisions). /// void SetEnabled(bool flag); public function SetEnabled(flag:Boolean):void { if(flag) { m_flags |= e_enabledFlag; } else { m_flags &= ~e_enabledFlag; } } /// Has this contact been disabled? /// bool IsEnabled() const; public function IsEnabled():Boolean { return (m_flags & e_enabledFlag) == e_enabledFlag; } /// Get the next contact in the world's contact list. /// b2Contact* GetNext(); public function GetNext():b2Contact { return m_next ? new b2Contact(m_next) : null; } /// Get the first fixture in this contact. /// b2Fixture* GetFixtureA(); public function GetFixtureA():b2Fixture { return m_fixtureA; } /// Get the second fixture in this contact. /// b2Fixture* GetFixtureB(); public function GetFixtureB():b2Fixture { return m_fixtureB; } /// Flag this contact for filtering. Filtering will occur the next time step. /// void FlagForFiltering(); public function FlagForFiltering():void { m_flags |= e_filterFlag; } public function Update():void { lib.b2Contact_Update(_ptr); } public function Evaluate():void { lib.b2Contact_Evaluate(_ptr); } public var m_fixtureA:b2Fixture; public var m_fixtureB:b2Fixture; public var m_manifold:b2Manifold; public function get m_flags():int { return mem._mr32(_ptr + 4); } public function set m_flags(v:int):void { mem._mw32(_ptr + 4, v); } /*public function get m_toiCount():Number { return mem._mrf(_ptr + 120); } public function set m_toiCount(v:Number):void { mem._mwf(_ptr + 120, v); } public function get frictionDisabled():Boolean { return mem._mru8(_ptr + 124) == 1; } public function set frictionDisabled(v:Boolean):void { mem._mw8(_ptr + 124, v ? 1 : 0); } public function get m_next():int { return mem._mr32(_ptr + 12); } public function set m_next(v:int):void { mem._mw32(_ptr + 12, v); } public function get m_prev():int { return mem._mr32(_ptr + 8); } public function set m_prev(v:int):void { mem._mw32(_ptr + 8, v); }*/ public function get m_indexA():int { return mem._mr32(_ptr + 56); } public function set m_indexA(v:int):void { mem._mw32(_ptr + 56, v); } public function get m_indexB():int { return mem._mr32(_ptr + 60); } public function set m_indexB(v:int):void { mem._mw32(_ptr + 60, v); } public function get m_toiCount():int { return mem._mr32(_ptr + 136); } public function set m_toiCount(v:int):void { mem._mw32(_ptr + 136, v); } public function get m_toi():Number { return mem._mrf(_ptr + 140); } public function set m_toi(v:Number):void { mem._mwf(_ptr + 140, v); } public function get frictionDisabled():Boolean { return mem._mru8(_ptr + 144) == 1; } public function set frictionDisabled(v:Boolean):void { mem._mw8(_ptr + 144, v ? 1 : 0); } public function get m_next():int { return mem._mr32(_ptr + 12); } public function set m_next(v:int):void { mem._mw32(_ptr + 12, v); } public function get m_prev():int { return mem._mr32(_ptr + 8); } public function set m_prev(v:int):void { mem._mw32(_ptr + 8, v); } } }
0
0.712681
1
0.712681
game-dev
MEDIA
0.729256
game-dev
0.771094
1
0.771094
RobinSchmidt/RS-MET
13,041
Libraries/JUCE/modules/juce_box2d/box2d/Dynamics/Joints/b2RevoluteJoint.cpp
/* * Copyright (c) 2006-2011 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 "b2RevoluteJoint.h" #include "../b2Body.h" #include "../b2TimeStep.h" // Point-to-point constraint // C = p2 - p1 // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Motor constraint // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) { bodyA = bA; bodyB = bB; localAnchorA = bodyA->GetLocalPoint(anchor); localAnchorB = bodyB->GetLocalPoint(anchor); referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); } b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) : b2Joint(def) { m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_referenceAngle = def->referenceAngle; m_impulse.SetZero(); m_motorImpulse = 0.0f; m_lowerAngle = def->lowerAngle; m_upperAngle = def->upperAngle; m_maxMotorTorque = def->maxMotorTorque; m_motorSpeed = def->motorSpeed; m_enableLimit = def->enableLimit; m_enableMotor = def->enableMotor; m_limitState = e_inactiveLimit; } void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; m_mass.ex.y = m_mass.ey.x; m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; m_mass.ex.z = m_mass.ez.x; m_mass.ey.z = m_mass.ez.y; m_mass.ez.z = iA + iB; m_motorMass = iA + iB; if (m_motorMass > 0.0f) { m_motorMass = 1.0f / m_motorMass; } if (m_enableMotor == false || fixedRotation) { m_motorImpulse = 0.0f; } if (m_enableLimit && fixedRotation == false) { float32 jointAngle = aB - aA - m_referenceAngle; if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) { m_limitState = e_equalLimits; } else if (jointAngle <= m_lowerAngle) { if (m_limitState != e_atLowerLimit) { m_impulse.z = 0.0f; } m_limitState = e_atLowerLimit; } else if (jointAngle >= m_upperAngle) { if (m_limitState != e_atUpperLimit) { m_impulse.z = 0.0f; } m_limitState = e_atUpperLimit; } else { m_limitState = e_inactiveLimit; m_impulse.z = 0.0f; } } else { m_limitState = e_inactiveLimit; } if (data.step.warmStarting) { // Scale impulses to support a variable time step. m_impulse *= data.step.dtRatio; m_motorImpulse *= data.step.dtRatio; b2Vec2 P(m_impulse.x, m_impulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); } else { m_impulse.SetZero(); m_motorImpulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) { b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); // Solve motor constraint. if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) { float32 Cdot = wB - wA - m_motorSpeed; float32 impulse = -m_motorMass * Cdot; float32 oldImpulse = m_motorImpulse; float32 maxImpulse = data.step.dt * m_maxMotorTorque; m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); float32 Cdot2 = wB - wA; b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); b2Vec3 impulse = -m_mass.Solve33(Cdot); if (m_limitState == e_equalLimits) { m_impulse += impulse; } else if (m_limitState == e_atLowerLimit) { float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse < 0.0f) { b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; m_impulse.x += reduced.x; m_impulse.y += reduced.y; m_impulse.z = 0.0f; } else { m_impulse += impulse; } } else if (m_limitState == e_atUpperLimit) { float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse > 0.0f) { b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; m_impulse.x += reduced.x; m_impulse.y += reduced.y; m_impulse.z = 0.0f; } else { m_impulse += impulse; } } b2Vec2 P(impulse.x, impulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + impulse.z); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + impulse.z); } else { // Solve point-to-point constraint b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); b2Vec2 impulse = m_mass.Solve22(-Cdot); m_impulse.x += impulse.x; m_impulse.y += impulse.y; vA -= mA * impulse; wA -= iA * b2Cross(m_rA, impulse); vB += mB * impulse; wB += iB * b2Cross(m_rB, impulse); } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) { b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Rot qA(aA), qB(aB); float32 angularError = 0.0f; float32 positionError = 0.0f; bool fixedRotation = (m_invIA + m_invIB == 0.0f); // Solve angular limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { float32 angle = aB - aA - m_referenceAngle; float32 limitImpulse = 0.0f; if (m_limitState == e_equalLimits) { // Prevent large angular corrections float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); limitImpulse = -m_motorMass * C; angularError = b2Abs(C); } else if (m_limitState == e_atLowerLimit) { float32 C = angle - m_lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); limitImpulse = -m_motorMass * C; } else if (m_limitState == e_atUpperLimit) { float32 C = angle - m_upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); limitImpulse = -m_motorMass * C; } aA -= m_invIA * limitImpulse; aB += m_invIB * limitImpulse; } // Solve point-to-point constraint. { qA.Set(aA); qB.Set(aB); b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2 C = cB + rB - cA - rA; positionError = C.Length(); float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; b2Mat22 K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; b2Vec2 impulse = -K.Solve(C); cA -= mA * impulse; aA -= iA * b2Cross(rA, impulse); cB += mB * impulse; aB += iB * b2Cross(rB, impulse); } data.positions[m_indexA].c = cA; data.positions[m_indexA].a = aA; data.positions[m_indexB].c = cB; data.positions[m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2RevoluteJoint::GetAnchorA() const { return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2RevoluteJoint::GetAnchorB() const { return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const { b2Vec2 P(m_impulse.x, m_impulse.y); return inv_dt * P; } float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const { return inv_dt * m_impulse.z; } float32 b2RevoluteJoint::GetJointAngle() const { b2Body* bA = m_bodyA; b2Body* bB = m_bodyB; return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; } float32 b2RevoluteJoint::GetJointSpeed() const { b2Body* bA = m_bodyA; b2Body* bB = m_bodyB; return bB->m_angularVelocity - bA->m_angularVelocity; } bool b2RevoluteJoint::IsMotorEnabled() const { return m_enableMotor; } void b2RevoluteJoint::EnableMotor(bool flag) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_enableMotor = flag; } float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const { return inv_dt * m_motorImpulse; } void b2RevoluteJoint::SetMotorSpeed(float32 speed) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_motorSpeed = speed; } void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_maxMotorTorque = torque; } bool b2RevoluteJoint::IsLimitEnabled() const { return m_enableLimit; } void b2RevoluteJoint::EnableLimit(bool flag) { if (flag != m_enableLimit) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_enableLimit = flag; m_impulse.z = 0.0f; } } float32 b2RevoluteJoint::GetLowerLimit() const { return m_lowerAngle; } float32 b2RevoluteJoint::GetUpperLimit() const { return m_upperAngle; } void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) { b2Assert(lower <= upper); if (lower != m_lowerAngle || upper != m_upperAngle) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_impulse.z = 0.0f; m_lowerAngle = lower; m_upperAngle = upper; } } void b2RevoluteJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2RevoluteJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); }
0
0.973218
1
0.973218
game-dev
MEDIA
0.9253
game-dev
0.989853
1
0.989853
pixel-boy/NinjaAdventure
1,551
system/character/character.gd
@icon("../character/icon_character.png") extends CharacterBody2D class_name Character enum State{IDLE} signal teleported @export_category("physics") @export var speed = 100.0 @export var acceleration = 1000.0 @export var deceleration = 800.0 @export var actor_scene:PackedScene: set(v): actor_scene = v if !is_inside_tree(): await ready if actor: actor.queue_free() actor = actor_scene.instantiate() @export var team:ResourceDamageTeam: set(v): team = v var actor:ActorSprite var move_vector := Vector2.ZERO: set(v): move_vector = v if move_vector.length(): sprite.direction = move_vector.normalized() var state:State var just_teleport := false @onready var sprite: SpriteCharacter = $Sprite func _physics_process(delta: float) -> void: if Engine.is_editor_hint(): return match state: State.IDLE: if move_vector.length(): sprite.anim = SpriteCharacter.Anim.MOVING velocity = velocity.move_toward(move_vector*speed,acceleration*delta) else: sprite.anim = SpriteCharacter.Anim.IDLE velocity = velocity.move_toward(Vector2.ZERO,deceleration*delta) move_and_slide() func teleport(target_teleporter:Teleporter,offset_position:Vector2): if just_teleport: return global_position = target_teleporter.global_position+offset_position+(target_teleporter.direction*Vector2(25,25)) just_teleport = true for camera in get_tree().get_nodes_in_group("camera"): camera.teleport_to(global_position) await get_tree().create_timer(0.1,false).timeout just_teleport = false teleported.emit()
0
0.598008
1
0.598008
game-dev
MEDIA
0.981056
game-dev
0.942638
1
0.942638
Monkestation/Monkestation2.0
7,455
monkestation/code/modules/martial_arts/tribal_claw.dm
//ported directly from Bee, cleaned up and updated to function with TG. thanks bee! #define TAIL_SWEEP_COMBO "DH" #define FACE_SCRATCH_COMBO "HH" #define JUGULAR_CUT_COMBO "HD" #define TAIL_GRAB_COMBO "DDG" /datum/martial_art/tribal_claw name = "Tribal Claw" id = MARTIALART_TRIBALCLAW allow_temp_override = FALSE help_verb = /mob/living/carbon/human/proc/tribal_claw_help var/list/tribal_traits = list(TRAIT_HARDLY_WOUNDED, TRAIT_HARD_SOLES) smashes_tables = TRUE //:3 ///you can use throw mode to block melee attacks... sometimes block_chance = 60 //originally wanted to do inverse correlation but it donbt work :pensive: /datum/armor/scales melee = 40 bullet = 40 laser = 40 wound = 50 /datum/martial_art/tribal_claw/teach(mob/living/carbon/human/target, make_temporary = FALSE) . = ..() if(!.) return target.add_traits(tribal_traits) target.set_armor(target.get_armor().add_other_armor(/datum/armor/scales)) /datum/martial_art/tribal_claw/on_remove(mob/living/carbon/human/target) target.set_armor(target.get_armor().subtract_other_armor(/datum/armor/scales)) REMOVE_TRAITS_IN(target, tribal_traits) . = ..() /datum/martial_art/tribal_claw/proc/check_streak(mob/living/carbon/human/attacker, mob/living/carbon/human/defender) if(findtext(streak,TAIL_SWEEP_COMBO)) streak = "" tailSweep(attacker,defender) return TRUE if(findtext(streak,FACE_SCRATCH_COMBO)) streak = "" faceScratch(attacker,defender) return TRUE if(findtext(streak,JUGULAR_CUT_COMBO)) streak = "" jugularCut(attacker,defender) return TRUE if(findtext(streak,TAIL_GRAB_COMBO)) streak = "" tailGrab(attacker,defender) return TRUE return FALSE //Tail Sweep, triggers an effect similar to Alien Queen's tail sweep but only affects stuff 1 tile next to you, basically 3x3. /datum/martial_art/tribal_claw/proc/tailSweep(mob/living/carbon/human/attacker, mob/living/carbon/human/defender) if(attacker == current_target) return log_combat(attacker, defender, "tail sweeped(Tribal Claw)", name) defender.visible_message(span_warning("[attacker] sweeps [defender] off their legs with their tail!"), \ span_userdanger("[attacker] sweeps you off your legs with their tail!")) var/static/datum/action/cooldown/spell/aoe/repulse/martial/lizard/tail_sweep = new tail_sweep.cast(attacker) //Face Scratch, deals 30 brute to head(reduced by armor), blurs the defender's vision and gives them the confused effect for a short time. /datum/martial_art/tribal_claw/proc/faceScratch(mob/living/carbon/human/attacker, mob/living/carbon/human/defender) var/def_check = defender.getarmor(BODY_ZONE_HEAD, MELEE) log_combat(attacker, defender, "face scratched (Tribal Claw)", name) defender.visible_message(span_warning("[attacker] scratches [defender]'s face with their claws!"), \ span_userdanger("[attacker] scratches your face with their claws!")) defender.apply_damage(30, BRUTE, BODY_ZONE_HEAD, def_check) defender.adjust_confusion(5 SECONDS) defender.adjust_eye_blur(5 SECONDS) attacker.do_attack_animation(defender, ATTACK_EFFECT_CLAW) playsound(get_turf(defender), 'sound/weapons/slash.ogg', 50, 1, -1) /* Jugular Cut Deals 15 damage to the target plus 10 seconds of oxygen loss and 10 oxyloss, with an open laceration If the target is T3 grabbed or sleeping, instead deal 60 damage with a weeping avulsion alongside the previous. */ /datum/martial_art/tribal_claw/proc/jugularCut(mob/living/carbon/attacker, mob/living/carbon/defender) var/def_check = defender.getarmor(BODY_ZONE_HEAD, MELEE) var/obj/item/bodypart/head = defender.get_bodypart(BODY_ZONE_HEAD) var/wound_type = /datum/wound/slash/flesh/severe var/critical_wound_type = /datum/wound/slash/flesh/critical var/datum/wound/slash/flesh/laceration = new wound_type() var/datum/wound/slash/flesh/jugcut = new critical_wound_type() var/is_jugcut = FALSE log_combat(attacker, defender, "jugular cut (Tribal Claw)", name) //balance feature, prevents damage bonus if(LAZYLEN(head?.wounds) > 0) for(var/wound in head.wounds) if (istype(wound, critical_wound_type)) is_jugcut = TRUE break if((defender.health <= defender.crit_threshold || (attacker.pulling == defender && attacker.grab_state >= GRAB_NECK) || defender.IsSleeping()) && !is_jugcut) { log_combat(attacker, defender, "strong jugular cut (Tribal Claw)", name) defender.apply_damage(60, BRUTE, BODY_ZONE_HEAD, def_check) defender.visible_message(span_warning("[attacker] tears out [defender]'s throat with their tail!"), \ span_userdanger("[attacker] tears out your throat with their tail!")) jugcut.apply_wound(head) playsound(get_turf(defender), 'sound/effects/wounds/splatter.ogg') } else { defender.apply_damage(15, BRUTE, BODY_ZONE_HEAD, def_check) defender.visible_message(span_warning("[attacker] cuts [defender]'s jugular vein with their claws!"), \ span_userdanger("[attacker] cuts your jugular vein!")) laceration.apply_wound(head) } //aditional effects //this should improve lethality if(defender.losebreath <= 50) defender.losebreath = clamp(defender.losebreath + 10, 0, 50) defender.adjustOxyLoss(10) attacker.do_attack_animation(defender, ATTACK_EFFECT_CLAW) playsound(get_turf(defender), 'sound/weapons/slash.ogg', 50, 1, -1) //Tail Grab, instantly puts your defender in a T3 grab and makes them unable to talk for a short time. /datum/martial_art/tribal_claw/proc/tailGrab(mob/living/carbon/human/attacker, mob/living/carbon/human/defender) log_combat(attacker, defender, "tail grabbed (Tribal Claw)", name) defender.visible_message(span_warning("[attacker] grabs [defender] with their tail!"), \ span_userdanger("[attacker] grabs you with their tail!6</span>")) defender.grabbedby(attacker, 1) defender.Knockdown(5) //Without knockdown defender still stands up while T3 grabbed. attacker.setGrabState(GRAB_NECK) defender.adjust_silence_up_to(10 SECONDS, 10 SECONDS) defender.adjust_emote_mute_up_to(10 SECONDS, 10 SECONDS) /datum/martial_art/tribal_claw/harm_act(mob/living/carbon/human/attacker, mob/living/carbon/human/defender) add_to_streak("H",defender) if(check_streak(attacker,defender)) return TRUE return FALSE /datum/martial_art/tribal_claw/disarm_act(mob/living/carbon/human/attacker, mob/living/carbon/human/defender) add_to_streak("D",defender) if(check_streak(attacker,defender)) return TRUE return FALSE /datum/martial_art/tribal_claw/grab_act(mob/living/carbon/human/attacker, mob/living/carbon/human/defender) add_to_streak("G",defender) if(check_streak(attacker,defender)) return TRUE return FALSE /mob/living/carbon/human/proc/tribal_claw_help() set name = "Recall Teachings" set desc = "Remember the martial techniques of the Tribal Claw" set category = "Tribal Claw" to_chat(usr, "<b><i>You retreat inward and recall the teachings of the Tribal Claw...</i></b>") to_chat(usr, span_notice("Tail Sweep</span>: Disarm Harm. Pushes everyone around you away and knocks them down.")) to_chat(usr, span_notice("Face Scratch</span>: Harm Harm. Damages your target's head and confuses them for a short time.")) to_chat(usr, span_notice("Jugular Cut</span>: Harm Disarm. Causes your target to rapidly lose blood, works only if you grab your target by their neck, if they are sleeping, or in critical condition.")) to_chat(usr, span_notice("Tail Grab</span>: Disarm Disarm Grab. Grabs your target by their neck and makes them unable to talk for a short time."))
0
0.842986
1
0.842986
game-dev
MEDIA
0.996708
game-dev
0.851317
1
0.851317
lua9520/source-engine-2018-cstrike15_src
9,867
game/shared/precache_register.cpp
//===== Copyright 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // // $NoKeywords: $ //===========================================================================// #include "cbase.h" #include "precache_register.h" #include "tier0/platform.h" #include "tier1/keyvalues.h" #include "tier2/tier2.h" #include "datacache/iresourceaccesscontrol.h" #include "filesystem.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" static const char *s_pPrecacheResourceTypeName[] = { "vgui_resource", "material", "model", "scriptsound", // NOTE: This is named this way for backward compat in reading from kv files "particle_system", "entity", "decal", "pmaterial", "dependency_file", "game_material_decals", "physics_gamesounds", "shared", }; //----------------------------------------------------------------------------- // Provides callback to do actual precaching of resources //----------------------------------------------------------------------------- class CPrecacheHandler : public IPrecacheHandler { public: void CacheResource( PrecacheResourceType_t nType, const char *pName, bool bPrecache, ResourceList_t hResourceList, int *pIndex = NULL ); private: void CacheResourceFile( const char *pFilename, bool bPrecache, ResourceList_t hResourceList ); void PrecacheGameMaterialDecals( bool bPrecache, ResourceList_t hResourceList ); void PrecachePhysicsSounds( const char *pName, bool bPrecache, ResourceList_t hResourceList ); }; //----------------------------------------------------------------------------- // Singletons //----------------------------------------------------------------------------- static CPrecacheRegister s_PrecacheRegister; CPrecacheRegister *g_pPrecacheRegister = &s_PrecacheRegister; static CPrecacheHandler s_PrecacheHandler; IPrecacheHandler *g_pPrecacheHandler = &s_PrecacheHandler; bool CPrecacheRegister::Init() { return true; } //----------------------------------------------------------------------------- // Level startup, shutdown //----------------------------------------------------------------------------- void CPrecacheRegister::LevelInitPreEntity() { COM_TimestampedLog( "LevelInitPreEntity - PreCache - Start" ); g_pPrecacheSystem->Cache( g_pPrecacheHandler, GLOBAL, NULL, true, RESOURCE_LIST_INVALID, false ); COM_TimestampedLog( "LevelInitPreEntity - PreCache - Finish" ); #ifdef CLIENT_DLL //FIXME: Double check this //Finally, force the cache of these materials COM_TimestampedLog( "LevelInitPreEntity - CacheUsedMaterials - Start" ); materials->CacheUsedMaterials(); COM_TimestampedLog( "LevelInitPreEntity - CacheUsedMaterials - Finish" ); #endif } void CPrecacheRegister::LevelShutdownPostEntity() { // FIXME: How to uncache all resources cached during the course of the level? g_pPrecacheSystem->UncacheAll( g_pPrecacheHandler ); if ( g_pResourceAccessControl ) { g_pResourceAccessControl->DestroyAllResourceLists(); } } //----------------------------------------------------------------------------- // Purpose: Precache game-specific models & sounds //----------------------------------------------------------------------------- void CPrecacheHandler::CacheResourceFile( const char *pFilename, bool bPrecache, ResourceList_t hResourceList ) { COMPILE_TIME_ASSERT( ARRAYSIZE(s_pPrecacheResourceTypeName) == PRECACHE_RESOURCE_TYPE_COUNT ); KeyValues *pValues = new KeyValues( "ResourceFile" ); if ( !pValues->LoadFromFile( g_pFullFileSystem, pFilename, "GAME" ) ) { Warning( "Can't open %s for client precache info.", pFilename ); pValues->deleteThis(); return; } for ( KeyValues *pData = pValues->GetFirstSubKey(); pData != NULL; pData = pData->GetNextKey() ) { const char *pszType = pData->GetName(); const char *pszFile = pData->GetString(); if ( Q_strlen( pszType ) == 0 || Q_strlen( pszFile ) == 0 ) continue; bool bFoundMatch = false; for ( int i = 0; i < PRECACHE_RESOURCE_TYPE_COUNT; ++i ) { if ( !Q_stricmp( pData->GetName(), s_pPrecacheResourceTypeName[i] ) ) { CacheResource( (PrecacheResourceType_t)i, pszFile, bPrecache, hResourceList ); bFoundMatch = true; break; } } if ( !bFoundMatch ) { Warning( "Error in precache file \"%s\":\n", pFilename ); Warning( "\tUnknown resource type specified \"%s\", value \"%s\"\n", pszType, pszFile ); } } pValues->deleteThis(); } //----------------------------------------------------------------------------- // Precaches game material decals //----------------------------------------------------------------------------- void CPrecacheHandler::PrecacheGameMaterialDecals( bool bPrecache, ResourceList_t hResourceList ) { } void CPrecacheHandler::PrecachePhysicsSounds( const char *pName, bool bPrecache, ResourceList_t hResourceList ) { if ( !bPrecache ) return; // precache the surface prop sounds bool bBulletSounds = !Q_stricmp( pName, "BulletSounds" ); bool bStepSounds = !Q_stricmp( pName, "StepSounds" ); bool bPhysicsImpactSounds = !Q_stricmp( pName, "PhysicsImpactSounds" ); for ( int i = 0; i < physprops->SurfacePropCount(); i++ ) { surfacedata_t *pprop = physprops->GetSurfaceData( i ); Assert( pprop ); if ( bBulletSounds ) { const char *pSoundName = physprops->GetString( pprop->sounds.bulletImpact ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); } if ( bStepSounds ) { const char *pSoundName = physprops->GetString( pprop->sounds.walkStepLeft ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.walkStepRight ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.runStepLeft ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.runStepRight ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); } if ( bPhysicsImpactSounds ) { const char *pSoundName = physprops->GetString( pprop->sounds.impactSoft ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.impactHard ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.scrapeSmooth ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.scrapeRough ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.rolling ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.breakSound ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); pSoundName = physprops->GetString( pprop->sounds.strainSound ); CacheResource( GAMESOUND, pSoundName, bPrecache, hResourceList, NULL ); } } } //----------------------------------------------------------------------------- // Caches/uncaches resources //----------------------------------------------------------------------------- void CPrecacheHandler::CacheResource( PrecacheResourceType_t nType, const char *pName, bool bPrecache, ResourceList_t hResourceList, int *pIndex ) { if ( bPrecache ) { if ( pIndex ) { *pIndex = 0; } switch( nType ) { case VGUI_RESOURCE: break; case MATERIAL: PrecacheMaterial( pName ); if ( pIndex ) { *pIndex = GetMaterialIndex( pName ); } if ( hResourceList != RESOURCE_LIST_INVALID ) { g_pResourceAccessControl->AddResource( hResourceList, RESOURCE_MATERIAL, pName ); } break; case PARTICLE_MATERIAL: { #ifdef CLIENT_DLL void* nIndex = ParticleMgr()->GetPMaterial( pName ); #else void* nIndex = 0; #endif if ( pIndex ) { void** pIndexMaterial = (void**)pIndex; *pIndexMaterial = nIndex; } } break; case GAME_MATERIAL_DECALS: PrecacheGameMaterialDecals( bPrecache, hResourceList ); break; case PHYSICS_GAMESOUNDS: PrecachePhysicsSounds( pName, bPrecache, hResourceList ); break; case DECAL: { int nIndex = UTIL_PrecacheDecal( pName, true ); if ( pIndex ) { *pIndex = nIndex; } } break; case MODEL: { int nIndex = CBaseEntity::PrecacheModel( pName ); if ( pIndex ) { *pIndex = nIndex; } if ( hResourceList != RESOURCE_LIST_INVALID ) { g_pResourceAccessControl->AddResource( hResourceList, RESOURCE_MODEL, pName ); } } break; case GAMESOUND: { int nIndex = CBaseEntity::PrecacheScriptSound( pName ); if ( pIndex ) { *pIndex = nIndex; } if ( hResourceList != RESOURCE_LIST_INVALID ) { g_pResourceAccessControl->AddResource( hResourceList, RESOURCE_GAMESOUND, pName ); } } break; case PARTICLE_SYSTEM: PrecacheParticleSystem( pName ); if ( pIndex ) { *pIndex = GetParticleSystemIndex( pName ); } if ( hResourceList != RESOURCE_LIST_INVALID ) { g_pResourceAccessControl->AddResource( hResourceList, RESOURCE_PARTICLE_SYSTEM, pName ); } break; case ENTITY: UTIL_PrecacheOther( pName ); break; case SHARED: g_pPrecacheSystem->Cache( this, SHARED_SYSTEM, pName, bPrecache, hResourceList, false ); break; case KV_DEP_FILE: CacheResourceFile( pName, bPrecache, hResourceList ); break; } return; } // Blat out value if ( pIndex ) { *pIndex = 0; } switch( nType ) { case VGUI_RESOURCE: break; case MATERIAL: break; case MODEL: break; case GAMESOUND: break; case PARTICLE_SYSTEM: break; case ENTITY: break; case DECAL: break; case KV_DEP_FILE: break; } }
0
0.986845
1
0.986845
game-dev
MEDIA
0.91437
game-dev
0.967749
1
0.967749
bdsim-collaboration/bdsim
16,803
include/BDSMagnetOuterFactoryPolesBase.hh
/* Beam Delivery Simulation (BDSIM) Copyright (C) Royal Holloway, University of London 2001 - 2024. This file is part of BDSIM. BDSIM 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 version 3 of the License. BDSIM 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 BDSIM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BDSMAGNETOUTERFACTORYPOLESBASE_H #define BDSMAGNETOUTERFACTORYPOLESBASE_H #include "BDSMagnetOuter.hh" #include "BDSMagnetOuterFactoryBase.hh" #include "globals.hh" // geant4 globals / types #include "G4TwoVector.hh" #include <vector> class BDSBeamPipe; class BDSMagnetOuterInfo; class G4Material; class G4VSolid; /** * @brief Factory class for outer volume of magnets. Produces magnets * with 2N-poles around the beampipe with a yoke of various shapes. * * Most magnets are 2N poles, but sector and r-bends as well as * muon spoilers, and h/v kickers are unique. * * NOTE this is a base class in that there are derived classes * with different outer shapes - all have poles, but the return * yoke can for example, circular, square or faceted (with 4N facets) * * @author Laurie Nevay */ class BDSMagnetOuterFactoryPolesBase: public BDSMagnetOuterFactoryBase { public: BDSMagnetOuterFactoryPolesBase(); explicit BDSMagnetOuterFactoryPolesBase(G4double poleStopFactorIn); virtual ~BDSMagnetOuterFactoryPolesBase(); /// sector bend outer volume virtual BDSMagnetOuter* CreateSectorBend(G4String name, // name G4double length, // full length [mm] const BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // recipe for geometry /// rectangular bend outer volume virtual BDSMagnetOuter* CreateRectangularBend(G4String name, // name G4double length, // full length [mm] const BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // recipe for geometry /// quadrupole outer volume virtual BDSMagnetOuter* CreateQuadrupole(G4String name, // name G4double length, // length [mm] BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// sextupole outer volume virtual BDSMagnetOuter* CreateSextupole(G4String name, // name G4double length, // length [mm] BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// octupole outer volume virtual BDSMagnetOuter* CreateOctupole(G4String name, // name G4double length, // length [mm] BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// decapole outer volume virtual BDSMagnetOuter* CreateDecapole(G4String name, // name G4double length, // length BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// solenoid outer volume virtual BDSMagnetOuter* CreateSolenoid(G4String name, // name G4double length, // length BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// general multipole outer volume - could be any 2N order multipole virtual BDSMagnetOuter* CreateMultipole(G4String name, // name G4double length, // length BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// RF cavity outer volume virtual BDSMagnetOuter* CreateRfCavity(G4String name, // name G4double length, // length BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// muon spoiler outer volume virtual BDSMagnetOuter* CreateMuonSpoiler(G4String name, // name G4double length, // length BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe); // geometry recipe /// horizontal and vertical kicker outer volume virtual BDSMagnetOuter* CreateKicker(G4String name, // name G4double length, // length const BDSBeamPipe* beamPipe, // beampipe G4double containerLength, // full length to make AccComp container const BDSMagnetOuterInfo* recipe, // geometry recipe G4bool vertical); // is it a vertical kicker? protected: // geometry parameters /// The fraction of the distance from the beam pipe to the horizontalWidth/2 that each pole /// will take - always < 1 const G4double poleFraction; /// Fraction of 2pi/Npoles that the pole will occupy - always < 1 const G4double poleAngularFraction; /// Fraction of length from pole tip to horizontalWidth that pole tip ellisoid will /// take up const G4double poleTipFraction; /// Fraction of length from pole tip to outerDiamter that the expanding section of /// the pole will take up. There's the tip, this bit, then a straight bit. const G4double poleAnnulusFraction; /// Bends are often wider in the bending plane. As we only have one parameter to pass /// which is outerDimaeter, make the non bending dimension a fixed (< 1) fraction of /// the outerDimaeter. const G4double bendHeightFraction; /// Factor by which the pole length is multiplied for the raw pole length before it's /// intersected with the inside of the yoke. Where the pole would normally stop at /// yokeStartRadius - lengthSaftey, it runs to yokeStartRadius x poleStopFactor. const G4double poleStopFactor; G4double yokeStartRadius; ///< Start radius of yoke geometry from magnet cetnre. G4double yokeFinishRadius; ///< Finish radius of yoke geometry from magnet centre - less than horizontalWidth. G4double magnetContainerRadius; ///< Radius of the container solid for the outer geometry. G4bool buildPole; ///< Whether or not to build poles (and therefore coils). G4double poleStartRadius; ///< Start radius of the pole from magnet centre. G4double poleFinishRadius; ///< Finish radius of the pole from magnet centre. G4double poleSquareWidth; ///< Full width of pole in constant width section. G4double poleSquareStartRadius; ///< Radius from magnet centre that constant width section starts. G4double segmentAngle; ///< 2PI / # of poles - angle per segment allocated for each pole. G4double poleAngle; ///< The angle allowed for the pole to occupy - less than segmentAngle. G4ThreeVector poleTranslation; ///< Offste of pole for placement from magnet centre. G4double coilHeight; ///< Height along y for coil for coil beside 1 upgright pole aligned with y axis. G4double coilCentreRadius; ///< Radius from magnet centre that the centre of the coils exist at. G4double endPieceLength; ///< Length of the coil end piece along what will be curvilinear S. G4double endPieceInnerR; ///< Inner radius for end piece container. G4double endPieceOuterR; ///< Outer radius for end piece container. G4VSolid* poleIntersectionSolid; ///< Solid used to chop off pole G4VSolid* coilLeftSolid; ///< Left coil solid for one pole built upright along y axis. G4VSolid* coilRightSolid; ///< Right coil solid. G4VSolid* endPieceContainerSolid;///< End piece container solid. G4LogicalVolume* coilLeftLV; ///< Logical volume for left coil. G4LogicalVolume* coilRightLV; ///< Logical volume for right coil. G4LogicalVolume* endPieceCoilLV; ///< Logical volume for end piece single coil piece. G4LogicalVolume* endPieceContainerLV; ///< Logical volume for end piece container. BDSSimpleComponent* endPiece; ///< Fully constructed end piece. std::vector<G4TwoVector> leftPoints; ///< Vector of 2D points for left coil. std::vector<G4TwoVector> rightPoints; ///< Vector of 2D points for right coil. std::vector<G4TwoVector> endPiecePoints;///< Vector of 2D points for end piece looking from above down z. /// Empty containers for next use - this class is never deleted so can't rely on scope virtual void CleanUp(); /// Non-virtual clean up to be used in constructor. void CleanUpPolesBase(); /// Common construction tasks to all methods - assemble yoke and poles in container virtual BDSMagnetOuter* CommonConstructor(const G4String& name, G4double length, BDSBeamPipe* beamPipe, G4int order, G4double magnetContainerLength, const BDSMagnetOuterInfo* recipe); /// Calculate the length of the pole and yoke radii based on the design. This is only /// responsible for calculating the gross proportions of the yoke and pole, not all the /// geometrical parameters that may be required for the final geometry. virtual void CalculatePoleAndYoke(G4double horizontalWidth, BDSBeamPipe* beamPipe, G4int order); /// Create pole for magnet of order N where npoles = Nx2. This contains some calcultion /// of geometrical parameters pertinent to the exact geometry being required. /// NOTE the poles are not joined (boolean union) to the outer yoke - there is a /// gap of length safety. This won't affect physics results and speeds up tracking /// as the solid is not a boolean of order Npoles + 1. virtual void CreatePoleSolid(const G4String& name, // name G4double length, // length [mm] G4int order); // Nx2 poles /// Create the coil solids corresponding to the pole solid. virtual void CreateCoilSolids(const G4String& name, G4double length); /// Create all the points that make up the extruded solid of the pole. virtual void CreateCoilPoints(); /// Create yoke that connects poles and container to put them in. Also create the /// poleIntersectionSolid that will be used to chop the extended pole in /// IntersectPoleWithYoke(). virtual void CreateYokeAndContainerSolid(const G4String& name, G4double length, G4int order, G4double magnetContainerLength, G4double magnetContainerRadiusIn); // so as not to clash with member name /// Chop off the top of the pole to match the appropriate yoke geometry. virtual void IntersectPoleWithYoke(const G4String& name, G4double length, G4int order); virtual void CreateLogicalVolumes(const G4String& name, G4Colour* colour, G4Material* outerMaterial); /// Discretise the coil logical volumes as even though derived factories from this one /// may complete override CreateLogicalVolumes as the poles can be individually unique, /// the coils will be the same and this allows reuse of code and lack of duplication. virtual void CreateLogicalVolumesCoil(const G4String& name); /// Create the solids, logical volumes for the end piece - everything /// but the placement. Also, create the geometry component now. virtual void CreateEndPiece(const G4String& name); /// Place the poles and yoke in the container volume. virtual void PlaceComponents(const G4String& name, G4int order); /// If we're building coils, place two coils for each pole. virtual void PlaceComponentsCoils(const G4String& name, G4int order); /// Ensure the coil fractions lie with [0.05, 0.98] and if they're negative set them to /// a provided default. -ve is assumed to require the default parameter and allows different /// usages of the function (in C and H dipoles) to control the defaults. void TestCoilFractions(G4double& coilWidthFraction, G4double& coilHeightFraction); /// Common task to both dipole construction routines. Clean up, test inputs and check /// if faces will intersect and warn user. Note reference to material pointer so it can /// be fixed if needs be to the default. void DipoleCommonPreConstruction(const G4String& name, G4double angleIn, G4double angleOut, G4double length, G4double& horizontalWidth, G4Material*& material, G4double& vhRatio); /// Common calculations to both dipole construction routines in one place. Pass by reference /// to modify variables declared in each function. void DipoleCalculations(G4bool hStyle, G4bool buildVertically, const BDSBeamPipe* beamPipe, G4double length, G4double horizontalWidth, G4double angleIn, G4double angleOut, G4double yokeThicknessFraction, G4double vhRatio, G4double coilWidthFraction, G4double coilHeightFraction, G4double& cShapeOuterEdge, G4double& poleHalfGap, G4double& poleWidth, G4double& poleHeight, G4double& yokeWidth, G4double& yokeHalfHeight, G4double& yokeThickness, G4double& yokeOverHang, G4double& coilWidth, G4double& coilHeightIn, // to avoid shadowing member variable G4double& coilToYokeGap, G4double& coilToPoleGap, G4double& sLength, G4double& containerSLength, G4double& intersectionRadius); /// Calculate the placement offsets for each of the four coil placements. Common to both dipole /// construction routines. std::vector<G4ThreeVector> CalculateCoilDisplacements(G4double poleHalfWidthIn, G4double poleHalfGapIn, G4double coilWidthIn, G4double coilHeightIn, G4double cDY, G4double& coilDY); /// Routine to construct a C shaped dipole magnet with the yoke either to the left or right /// and can optionally be built vertically. BDSMagnetOuter* CreateDipoleC(const G4String& name, G4double length, const BDSBeamPipe* beamPipe, G4double containerLength, const BDSMagnetOuterInfo* recipe, G4bool buildVertically); /// Routine to construct an H shaped dipole magnet and can optionally be built vertically. BDSMagnetOuter* CreateDipoleH(const G4String& name, G4double length, const BDSBeamPipe* beamPipe, G4double containerLength, const BDSMagnetOuterInfo* recipe, G4bool buildVertically); BDSMagnetOuter* DipoleCommonConstruction(const G4String& name, G4double horizontalWidth, G4bool buildEndPiece, G4double coilWidth, G4double length, G4double containerLength, G4double sLength, G4double angleIn, G4double angleOut, G4Colour* colour, G4Material* material, std::vector<G4ThreeVector>& coilDisps, G4bool buildVertically, BDSExtent& ext, G4double poleHalfWidth, G4double poleHalfGap, G4double cDY, G4double coilDY, G4double intersectionRadius); BDSMagnetOuterFactoryBase* cylindrical; ///< Default factory to fall back to. }; #endif
0
0.817966
1
0.817966
game-dev
MEDIA
0.590645
game-dev
0.874323
1
0.874323
arcana-engine/arcana
25,510
engine/src/control.rs
use std::{ collections::hash_map::{Entry, HashMap}, fmt::Debug, hash::Hash, ops::Neg, }; use edict::{ prelude::{Component, EntityId, World}, world::NoSuchEntity, }; use winit::event::VirtualKeyCode; use crate::{ command::CommandQueue, event::{ AxisId, ButtonId, DeviceEvent, DeviceId, ElementState, Event, KeyboardInput, MouseButton, MouseScrollDelta, WindowEvent, }, funnel::Funnel, }; #[derive(Clone, Copy, Debug)] pub enum InputEvent { Focused(bool), CursorMoved { position: (f64, f64), }, CursorEntered, CursorLeft, MouseMotion { delta: (f64, f64), }, MouseWheel { delta: MouseScrollDelta, }, MouseInput { state: ElementState, button: MouseButton, }, KeyboardInput(KeyboardInput), Motion { axis: AxisId, value: f64, }, Button { button: ButtonId, state: ElementState, }, } /// Device is already associated with a controller. #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] #[error("Device ({device_id:?}) is already associated with a controller")] pub struct DeviceUsed { device_id: DeviceId, } /// Result of `InputController::control` method pub enum ControlResult { /// Event was consumed by the controller. /// It should not be propagated further. Consumed, /// Event ignored. /// It should be propagated further. Ignored, /// Controller detached and should be removed. /// Event should be propagated further. ControlLost, } /// An input controller. /// Receives device events from `Control` hub. pub trait InputController: Send + 'static { /// Translates device event into controls. fn control(&mut self, event: InputEvent, world: &World) -> ControlResult; } impl<F> InputController for F where F: FnMut(InputEvent, &World) -> ControlResult + Send + 'static, { fn control(&mut self, event: InputEvent, world: &World) -> ControlResult { (*self)(event, world) } } /// Collection of controllers. #[derive(Default)] pub struct Control { /// Controllers bound to specific devices. devices: HashMap<DeviceId, Box<dyn InputController>>, /// Global controller that receives all events unhandled by device specific controllers. global: slab::Slab<Box<dyn InputController>>, } /// Identifier of the controller set in global slot. /// See [`Control::add_global_controller`]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(transparent)] pub struct GlobalControllerId { idx: usize, } impl Control { /// Returns empty collection of controllers pub fn new() -> Control { Control::default() } /// Assign global controller. pub fn add_global_controller( &mut self, controller: impl InputController, ) -> GlobalControllerId { let idx = self.global.insert(Box::new(controller)); GlobalControllerId { idx } } /// Assign global controller to specific device. pub fn set_device_control( &mut self, device_id: DeviceId, controller: impl InputController, ) -> Result<(), DeviceUsed> { match self.devices.entry(device_id) { Entry::Occupied(_) => Err(DeviceUsed { device_id }), Entry::Vacant(entry) => { entry.insert(Box::new(controller)); Ok(()) } } } } pub struct ControlFunnel; impl Funnel<Event> for ControlFunnel { fn filter(&mut self, world: &mut World, event: Event) -> Option<Event> { let mut control = world.expect_resource_mut::<Control>(); let (input_event, device_id) = match event { Event::DeviceEvent { device_id, event: ref device_event, } => { let input_event = match *device_event { DeviceEvent::Motion { axis, value } => InputEvent::Motion { axis, value }, DeviceEvent::MouseMotion { delta } => InputEvent::MouseMotion { delta }, DeviceEvent::MouseWheel { delta } => InputEvent::MouseWheel { delta }, DeviceEvent::Button { button, state } => InputEvent::Button { button, state }, _ => return Some(event), }; (input_event, device_id) } Event::WindowEvent { event: ref window_event, .. } => match *window_event { WindowEvent::MouseInput { device_id, button, state, .. } => (InputEvent::MouseInput { state, button }, device_id), WindowEvent::KeyboardInput { device_id, input, .. } => (InputEvent::KeyboardInput(input), device_id), WindowEvent::CursorMoved { device_id, position, .. } => ( InputEvent::CursorMoved { position: (position.x, position.y), }, device_id, ), WindowEvent::Focused(v) => { // This event is always broadcast to every controller. let mut device_id_control_lost = Vec::new(); for (device_id, controller) in &mut control.devices { if let ControlResult::ControlLost = controller.control(InputEvent::Focused(v), world) { device_id_control_lost.push(*device_id); } } for device_id in device_id_control_lost { control.devices.remove(&device_id); } let mut global_control_lost = Vec::new(); for (idx, controller) in control.global.iter_mut() { if let ControlResult::ControlLost = controller.control(InputEvent::Focused(v), world) { global_control_lost.push(idx); } } for idx in global_control_lost { control.global.remove(idx); } return Some(event); } _ => return Some(event), }, _ => return Some(event), }; let mut consumed = match control.devices.get_mut(&device_id) { Some(controller) => match controller.control(input_event, world) { ControlResult::ControlLost => { control.devices.remove(&device_id); false } ControlResult::Consumed => true, ControlResult::Ignored => false, }, None => false, }; for idx in 0..control.global.len() { if !consumed { if let Some(controller) = control.global.get_mut(idx) { match controller.control(input_event, world) { ControlResult::ControlLost => { control.global.remove(idx); } ControlResult::Consumed => consumed = true, ControlResult::Ignored => {} } } } else { break; } } if !consumed { Some(event) } else { None } } } /// Translates device events into commands and pub trait EventTranslator { type Command; fn translate(&mut self, event: InputEvent) -> Option<Self::Command>; } /// Error that can occur when assuming control over an entity. #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] pub enum AssumeControlError { /// Failed to assume control of non-existing entity. #[error("Failed to assume control of non-existing entity ({entity:?})")] NoSuchEntity { entity: EntityId }, /// EntityId is already controlled #[error("EntityId ({entity:?}) is already controlled")] AlreadyControlled { entity: EntityId }, } /// Marker component. Marks that entity is being controlled. #[derive(Component)] pub struct Controlled { // Forbid construction outside of this module. __: (), } const CONTROLLED: Controlled = Controlled { __: () }; /// A kind of [`InputController`]s that yield commands and sends them to a command queue of an entity. pub struct EntityController<T> { commander: T, entity: EntityId, } impl<T> EntityController<T> where T: EventTranslator, T::Command: Send + Sync + 'static, { pub fn assume_control( commander: T, entity: EntityId, world: &mut World, ) -> Result<Self, AssumeControlError> { match world.query_one::<&Controlled>(entity).is_ok() { true => Err(AssumeControlError::AlreadyControlled { entity }), false => { world .insert_bundle(entity, (CONTROLLED, CommandQueue::<T::Command>::new())) .map_err(|NoSuchEntity| AssumeControlError::NoSuchEntity { entity })?; Ok(EntityController { commander, entity }) } } } } impl<T> InputController for EntityController<T> where T: EventTranslator + Send + 'static, T::Command: Send + Sync + 'static, { fn control(&mut self, event: InputEvent, world: &World) -> ControlResult { let result = world.for_one::<&mut CommandQueue<T::Command>, _, _>(self.entity, |queue| { match self.commander.translate(event) { None => ControlResult::Ignored, Some(command) => { queue.add(command); ControlResult::Consumed } } }); match result { Ok(result) => result, Err(_err) => ControlResult::ControlLost, } } } /// Basic configurable system to consume recognized key input into events. /// /// Keys can be configured to produce events of signals. /// When configured to produce events pressing the key would cause event to be emitted. /// When configured to produce signal pressing the key switches state to signalling and event is emitted repeatedly until key is unpressed. /// /// Only keys with key code can be configured. #[derive(Clone, Debug, Default)] pub struct SimpleKeyBinder<T> { bindings: HashMap<VirtualKeyCode, SimpleKeyBinding<T>>, } #[derive(Clone, Debug, Default)] struct SimpleKeyBinding<T> { pressed: bool, action: SimpleKeyEventAction<T>, } #[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct SimpleKeyEventAction<T> { #[serde(default = "none", skip_serializing_if = "Option::is_none")] on_press: Option<T>, #[serde(default = "none", skip_serializing_if = "Option::is_none")] on_release: Option<T>, #[serde(default = "none", skip_serializing_if = "Option::is_none")] on_hold: Option<T>, } fn none<T>() -> Option<T> { None } impl<T> SimpleKeyEventAction<T> { pub fn is_empty(&self) -> bool { self.on_press.is_none() && self.on_release.is_none() && self.on_hold.is_none() } } impl<T> Default for SimpleKeyEventAction<T> { fn default() -> Self { SimpleKeyEventAction { on_press: None, on_release: None, on_hold: None, } } } /// Deserialized from key mapping, impl<'de, T> serde::Deserialize<'de> for SimpleKeyBinder<T> where T: serde::Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let builder = SimpleKeyBuilder::<T>::deserialize(deserializer)?; Ok(SimpleKeyBinder::from_builder(builder)) } } impl<T> SimpleKeyBinder<T> { /// Returns new builder for the key binder. pub fn builder() -> SimpleKeyBuilder<T> { SimpleKeyBuilder::new() } /// Returns new binder configured from binder builder. /// /// Action kind is fetched from action itself. pub fn from_builder(builder: SimpleKeyBuilder<T>) -> Self { SimpleKeyBinder { bindings: builder .bindings .into_iter() .map(|(key, action)| { let binding = SimpleKeyBinding { action, pressed: false, }; (key, binding) }) .collect(), } } /// Returns new binder configured from binder builder. /// /// Action kind is fetched from action itself. /// /// Does not consume builder object. pub fn from_borrowed_builder(builder: &SimpleKeyBuilder<T>) -> Self where T: Clone, { SimpleKeyBinder { bindings: builder .bindings .iter() .map(|(key, action)| { let binding = SimpleKeyBinding { action: action.clone(), pressed: false, }; (*key, binding) }) .collect(), } } /// Returns binder builder matching current binder configuration. pub fn to_builder(&self) -> SimpleKeyBuilder<T> where T: Clone, { SimpleKeyBuilder { bindings: self .bindings .iter() .map(|(key, binding)| (*key, binding.action.clone())) .collect(), } } /// Handle input key event. pub fn handle_input(&mut self, input: &KeyboardInput) -> Option<&T> { let binding = self.bindings.get_mut(input.virtual_keycode.as_ref()?)?; match input.state { ElementState::Pressed => { if binding.pressed { None } else { binding.pressed = true; binding.action.on_press.as_ref() } } ElementState::Released => { if binding.pressed { binding.pressed = false; binding.action.on_release.as_ref() } else { None } } } } /// Returns an iterator over current `on_hold` actions. pub fn iter_holds(&self) -> impl Iterator<Item = &T> + '_ { self.bindings.values().filter_map(|binding| { if binding.pressed { binding.action.on_hold.as_ref() } else { None } }) } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(transparent)] pub struct SimpleKeyBuilder<T> { bindings: HashMap<VirtualKeyCode, SimpleKeyEventAction<T>>, } impl<T> Default for SimpleKeyBuilder<T> { fn default() -> Self { SimpleKeyBuilder { bindings: HashMap::default(), } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct KeyAlreadyBound { key: VirtualKeyCode, } impl<T> SimpleKeyBuilder<T> { /// Returns new empty mapping. pub fn new() -> Self { SimpleKeyBuilder { bindings: HashMap::new(), } } /// Binds action to a key press. /// /// Panics if key press is already bound. pub fn on_press<A>(mut self, key: VirtualKeyCode, action: A) -> Self where A: Into<T>, { self.try_on_press(key, action).unwrap(); self } /// Binds action to a key release. /// /// Panics if key release is already bound. pub fn on_release<A>(mut self, key: VirtualKeyCode, action: A) -> Self where A: Into<T>, { self.try_on_release(key, action).unwrap(); self } /// Binds action to a key press and release. /// /// Panics if key press or release is already bound. pub fn on_switch<P, R>(mut self, key: VirtualKeyCode, press: P, release: R) -> Self where P: Into<T>, R: Into<T>, { self.try_on_switch(key, press, release).unwrap(); self } /// Binds action to a key press and release. /// /// Panics if key press or release is already bound. pub fn on_switch_with<F, V, A>( mut self, key: VirtualKeyCode, f: F, press: V, release: V, ) -> Self where F: FnMut(V) -> A, A: Into<T>, { self.try_on_switch_with(key, f, press, release).unwrap(); self } /// Binds action to a key press and release. /// /// Panics if key press or release is already bound. pub fn on_switch_inverse<F, V, A>(mut self, key: VirtualKeyCode, f: F, action: V) -> Self where F: FnMut(V) -> A, V: Copy + Neg<Output = V>, A: Into<T>, { self.try_on_switch_with(key, f, action, -action).unwrap(); self } /// Binds action to a pair of keys with press and release actions inverted. /// /// Panics if any of the two keys press or release is already bound. pub fn on_key_axis<F, V, A>( mut self, forward: VirtualKeyCode, backward: VirtualKeyCode, f: F, action: V, ) -> Self where F: FnMut(V) -> A, V: Copy + Neg<Output = V>, A: Into<T>, { self.try_on_key_axis(forward, backward, f, action).unwrap(); self } /// Binds action to a key hold. /// /// Panics if key hold is already bound. pub fn on_hold<A>(mut self, key: VirtualKeyCode, action: A) -> Self where A: Into<T>, { self.try_on_hold(key, action) .map_err(|_| "Duplicate key hold") .unwrap(); self } /// Binds action to a key press. /// /// Fails if key press is already bound. pub fn try_on_press<A>(&mut self, key: VirtualKeyCode, action: A) -> Result<(), KeyAlreadyBound> where A: Into<T>, { let bind = self.bindings.entry(key).or_default(); match &mut bind.on_press { Some(_) => Err(KeyAlreadyBound { key }), slot => { *slot = Some(action.into()); Ok(()) } } } /// Clears on press action for the key if there any. /// /// Returns some action if it was bound. /// Returns none if there were none. pub fn clear_on_press(&mut self, key: VirtualKeyCode) -> Option<T> { match self.bindings.entry(key) { Entry::Vacant(_) => None, Entry::Occupied(mut entry) => { let binding = entry.get_mut(); let action = binding.on_press.take(); if binding.on_release.is_none() && binding.on_hold.is_none() { entry.remove(); } action } } } /// Binds action to a key press and release events. /// /// Fails if key press or released is already bound. pub fn try_on_switch<P, R>( &mut self, key: VirtualKeyCode, press: P, release: R, ) -> Result<(), KeyAlreadyBound> where P: Into<T>, R: Into<T>, { let bind = self.bindings.entry(key).or_default(); match (&mut bind.on_press, &mut bind.on_release) { (Some(_), _) | (_, Some(_)) => Err(KeyAlreadyBound { key }), (on_press, on_release) => { *on_press = Some(press.into()); *on_release = Some(release.into()); Ok(()) } } } /// Binds action to a key press and release events. /// /// Fails if key press or released is already bound. pub fn try_on_switch_with<F, V, A>( &mut self, key: VirtualKeyCode, mut f: F, press: V, release: V, ) -> Result<(), KeyAlreadyBound> where F: FnMut(V) -> A, A: Into<T>, { let bind = self.bindings.entry(key).or_default(); match (&mut bind.on_press, &mut bind.on_release) { (Some(_), _) | (_, Some(_)) => Err(KeyAlreadyBound { key }), (on_press, on_release) => { *on_press = Some(f(press).into()); *on_release = Some(f(release).into()); Ok(()) } } } /// Binds action to a key press and release events. /// /// Fails if key press or released is already bound. pub fn try_on_switch_inverse<F, V, A>( &mut self, key: VirtualKeyCode, mut f: F, action: V, ) -> Result<(), KeyAlreadyBound> where F: FnMut(V) -> A, V: Copy + Neg<Output = V>, A: Into<T>, { let bind = self.bindings.entry(key).or_default(); match (&mut bind.on_press, &mut bind.on_release) { (Some(_), _) | (_, Some(_)) => Err(KeyAlreadyBound { key }), (on_press, on_release) => { *on_press = Some(f(action).into()); *on_release = Some(f(-action).into()); Ok(()) } } } /// Binds action to a key press and release events. /// /// Fails if key press or released is already bound. pub fn try_on_key_axis<F, V, A>( &mut self, forward: VirtualKeyCode, backward: VirtualKeyCode, mut f: F, action: V, ) -> Result<(), KeyAlreadyBound> where F: FnMut(V) -> A, V: Copy + Neg<Output = V>, A: Into<T>, { let forward_bind = self.bindings.entry(forward).or_default(); match (&mut forward_bind.on_press, &mut forward_bind.on_release) { (Some(_), _) | (_, Some(_)) => return Err(KeyAlreadyBound { key: forward }), _ => {} } let backward_bind = self.bindings.entry(backward).or_default(); match (&mut backward_bind.on_press, &mut backward_bind.on_release) { (Some(_), _) | (_, Some(_)) => return Err(KeyAlreadyBound { key: backward }), _ => {} } let forward_bind = self.bindings.entry(forward).or_default(); forward_bind.on_press = Some(f(action).into()); forward_bind.on_release = Some(f(-action).into()); let backward_bind = self.bindings.entry(backward).or_default(); backward_bind.on_press = Some(f(-action).into()); backward_bind.on_release = Some(f(action).into()); Ok(()) } /// Binds action to a key release. /// /// Fails if key release is already bound. pub fn try_on_release<A>( &mut self, key: VirtualKeyCode, action: A, ) -> Result<(), KeyAlreadyBound> where A: Into<T>, { let bind = self.bindings.entry(key).or_default(); match &mut bind.on_release { Some(_) => Err(KeyAlreadyBound { key }), slot => { *slot = Some(action.into()); Ok(()) } } } /// Clears on release action for the key if there any. /// /// Returns some action if it was bound. /// Returns none if there were none. pub fn clear_on_release(&mut self, key: VirtualKeyCode) -> Option<T> { match self.bindings.entry(key) { Entry::Vacant(_) => None, Entry::Occupied(mut entry) => { let binding = entry.get_mut(); let action = binding.on_release.take(); if binding.on_press.is_none() && binding.on_hold.is_none() { entry.remove(); } action } } } /// Binds action to a key hold. /// /// Fails if key hold is already bound. pub fn try_on_hold<A>(&mut self, key: VirtualKeyCode, action: A) -> Result<(), KeyAlreadyBound> where A: Into<T>, { let bind = self.bindings.entry(key).or_default(); match &mut bind.on_hold { Some(_) => Err(KeyAlreadyBound { key }), slot => { *slot = Some(action.into()); Ok(()) } } } /// Clears on hold action for the key if there any. /// /// Returns some action if it was bound. /// Returns none if there were none. pub fn clear_on_hold(&mut self, key: VirtualKeyCode) -> Option<T> { match self.bindings.entry(key) { Entry::Vacant(_) => None, Entry::Occupied(mut entry) => { let binding = entry.get_mut(); let action = binding.on_hold.take(); if binding.on_press.is_none() && binding.on_release.is_none() { entry.remove(); } action } } } /// Converts builder into binder. pub fn build(self) -> SimpleKeyBinder<T> { SimpleKeyBinder::from_builder(self) } /// Converts builder into binder. /// /// Does not consume builder object. pub fn clone_build(&self) -> SimpleKeyBinder<T> where T: Clone, { SimpleKeyBinder::from_borrowed_builder(self) } }
0
0.931547
1
0.931547
game-dev
MEDIA
0.733254
game-dev
0.874789
1
0.874789
bozimmerman/CoffeeMud
24,509
com/planet_ink/coffee_mud/Abilities/Properties/Prop_RoomForSale.java
package com.planet_ink.coffee_mud.Abilities.Properties; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Move; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.DatabaseEngine.PlayerData; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2025 Bo Zimmerman 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. */ public class Prop_RoomForSale extends Property implements LandTitle { @Override public String ID() { return "Prop_RoomForSale"; } @Override public String name() { return "Putting a room up for sale"; } protected static String INDOORSTR = null; protected static String OUTDOORSTR = null; protected static String SALESTR = null; protected static String RENTSTR = null; protected int lastItemNums = -1; protected int lastDayDone = -1; protected int daysWithNoChange= 0; protected boolean scheduleReset = false; @Override protected int canAffectCode() { return Ability.CAN_ROOMS; } @Override public String accountForYourself() { return "For Sale"; } @Override public boolean allowsExpansionConstruction() { return false; } @Override public void setMiscText(final String newMiscText) { super.setMiscText(newMiscText); } @Override public int getPrice() { if(text().length()==0) return 100000; final String s=text(); int index=s.length(); while((--index)>=0) { if((!Character.isDigit(s.charAt(index))) &&(!Character.isWhitespace(s.charAt(index)))) break; } int price=CMath.s_int(s.substring(index+1).trim()); if(price<=0) price=100000; return price; } @Override public Room getAConnectedPropertyRoom() { if(affected instanceof Room) return (Room)affected; return CMLib.map().getRoom(landPropertyID()); } @Override public int getNumConnectedPropertyRooms() { return (getAConnectedPropertyRoom()!=null)?1:0; } @Override public void initializeClass() { if(INDOORSTR == null) { final String[] markers = CMProps.getListFileStringList(CMProps.ListFile.REALESTATE_MARKERS); INDOORSTR=" "+((markers.length>0)?markers[0].trim():""); OUTDOORSTR=" "+((markers.length>1)?markers[1].trim():""); SALESTR=" "+((markers.length>2)?markers[2].trim():""); RENTSTR=" "+((markers.length>3)?markers[3].trim():""); } } protected void saveData(final String owner, final int price, final boolean rental, final int backTaxes, final boolean grid, final boolean allowTheft) { setMiscText(owner+"/" +(rental?"RENTAL ":"") +(grid?"GRID ":"") +(allowTheft?"ALLOWTHEFT ":"") +((backTaxes>0)?"TAX"+backTaxes+"X ":"") +price); } @Override public void setPrice(final int price) { saveData(getOwnerName(), price, rentalProperty(), backTaxes(), gridLayout(), allowTheft()); } @Override public String getOwnerName() { final int dex=text().indexOf('/'); if(dex<0) return ""; return text().substring(0,dex); } @Override public boolean isProperlyOwned() { final String owner=getOwnerName(); if(owner.length()==0) return false; final Clan C=CMLib.clans().fetchClanAnyHost(owner); if(C!=null) return true; return CMLib.players().playerExistsAllHosts(owner); } @Override public void setOwnerName(final String owner) { if((owner.length()==0)&&(getOwnerName().length()>0)) scheduleReset=true; saveData(owner, getPrice(), rentalProperty(), backTaxes(), gridLayout(), allowTheft()); } @Override public int backTaxes() { final int dex=text().indexOf('/'); if(dex<0) return 0; final int x=text().indexOf("TAX",dex); if(x<0) return 0; final String s=CMParms.parse(text().substring(x+3)).firstElement(); return CMath.s_int(s.substring(0,s.length()-1)); // last char always X, so eat it } @Override public void setBackTaxes(final int tax) { saveData(getOwnerName(), getPrice(), rentalProperty(), tax, gridLayout(), allowTheft()); } @Override public boolean rentalProperty() { final String upperText=text().toUpperCase(); final int dex=upperText.indexOf('/'); if(dex<0) return upperText.indexOf("RENTAL")>=0; return upperText.indexOf("RENTAL",dex)>0; } @Override public void setRentalProperty(final boolean truefalse) { saveData(getOwnerName(), getPrice(), truefalse, backTaxes(), gridLayout(), allowTheft()); } @Override public boolean gridLayout() { final String upperText=text().toUpperCase(); final int dex=upperText.indexOf('/'); if(dex<0) return upperText.indexOf("GRID")>=0; return upperText.indexOf("GRID",dex)>0; } @Override public void setGridLayout(final boolean layout) { saveData(getOwnerName(), getPrice(), rentalProperty(), backTaxes(), layout, allowTheft()); } @Override public boolean allowTheft() { final String upperText=text().toUpperCase(); final int dex=upperText.indexOf('/'); if(dex<0) return upperText.indexOf("ALLOWTHEFT")>=0; return upperText.indexOf("ALLOWTHEFT",dex)>=0; } @Override public void setAllowTheft(final boolean allow) { saveData(getOwnerName(), getPrice(), rentalProperty(), backTaxes(), gridLayout(), allow); } // update title, since it may affect clusters, worries about ALL involved @Override public void updateTitle() { if(affected instanceof Room) CMLib.database().DBUpdateRoom((Room)affected); else { final Room R=CMLib.map().getRoom(landPropertyID()); if(R!=null) CMLib.database().DBUpdateRoom(R); } } @Override public String getTitleID() { if(affected instanceof Room) return "LAND_TITLE_FOR#"+CMLib.map().getExtendedRoomID((Room)affected); else { final Room R=CMLib.map().getRoom(landPropertyID()); if(R!=null) return "LAND_TITLE_FOR#"+CMLib.map().getExtendedRoomID(R); } return ""; } @Override public String getUniqueLotID() { return "ROOM_PROPERTY_" + landPropertyID(); } @Override public String landPropertyID() { if((affected instanceof Room)) return CMLib.map().getExtendedRoomID(((Room)affected)); return ""; } @Override public void setLandPropertyID(final String landID) { } @Override public LandTitle generateNextRoomTitle() { final LandTitle newTitle=(LandTitle)this.copyOf(); newTitle.setOwnerName(""); newTitle.setBackTaxes(0); return newTitle; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); if(((msg.sourceMinor()==CMMsg.TYP_SHUTDOWN) ||((msg.targetMinor()==CMMsg.TYP_EXPIRE) &&(msg.target()==affected)) ||(msg.sourceMinor()==CMMsg.TYP_ROOMRESET)) &&(affected instanceof Room)) { updateLot(null); final List<MOB> mobs=new ArrayList<MOB>(); Room R=(Room)affected; if(R!=null) { synchronized(CMClass.getSync("SYNC"+R.roomID())) { R=CMLib.map().getRoom(R); for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if((M!=null) &&(M.isSavable()) &&(M.getStartRoom()==R) &&((M.basePhyStats().rejuv()==0)||(M.basePhyStats().rejuv()==PhyStats.NO_REJUV))) { CMLib.catalog().updateCatalogIntegrity(M); mobs.add(M); } } if(!CMSecurity.isSaveFlag(CMSecurity.SaveFlag.NOPROPERTYMOBS)) CMLib.database().DBUpdateTheseMOBs(R,mobs); } } } } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!super.okMessage(myHost,msg)) return false; if(!CMLib.law().robberyCheck(this,msg, false)) return false; return true; } @Override public Room getATitledRoom() { if(affected instanceof Room) return (Room)affected; else return CMLib.map().getRoom(landPropertyID()); } protected void fillCluster(final Room startR, final List<Room> roomList, final String owner, final boolean forceCache) { roomList.add(startR); int start =0; final Area baseA =startR.getArea(); boolean foundEntrance=false; final boolean dontCache = CMath.bset(baseA.flags(), Area.FLAG_THIN) && (!CMath.bset(baseA.flags(), Area.FLAG_INSTANCE_CHILD)); final Set<String> roomIDs = new TreeSet<String>(); roomIDs.add(startR.roomID()); final DatabaseEngine db = CMLib.database(); Exit openE = null; while(start < roomList.size()) { final Room dR = roomList.get(start++); for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room nR=(dontCache?dR.rawDoors()[d]:dR.getRoomInDir(d)); if((nR!=null) &&(nR.roomID().length()>0) &&(!roomIDs.contains(nR.roomID()))) { roomIDs.add(nR.roomID()); final Area nRarea=nR.getArea(); Ability lotA=null; if(nR.ID().equals("ThinRoom") &&(nRarea == baseA)) { if(!forceCache) continue; final Room nAR=db.DBReadRoomObject(nR.roomID(), true, false); // wont have an area! if(nAR==null) continue; lotA=nAR.fetchEffect(ID()); final Pair<String,String>[] exits = db.DBReadRoomExitIDs(nR.roomID()); for(int nd=0;nd<exits.length;nd++) { final Pair<String,String> p = exits[nd]; if(p != null) { final String exitId = p.second; if((p.first!=null) &&(p.first.length()>0)) { if(openE == null) openE = CMClass.getExit("Open"); nR.setRawExit(nd, openE); // this makes the thin room modifiable } else nR.setRawExit(nd, null); // this makes the thin room modifiable final Room nnR = CMLib.map().getCachedRoom(exitId); if(nnR != null) nR.rawDoors()[nd]=nnR; else { final Area A = CMLib.map().findRoomIDArea(exitId); final Room tR = CMClass.getLocale("ThinRoom"); tR.setRoomID(exitId); tR.setArea(A); nR.rawDoors()[nd]=tR; } } } } else lotA=nR.fetchEffect(ID()); if(((nRarea==baseA) &&(lotA!=null) &&((owner==null)||((LandTitle)lotA).getOwnerName().equals(owner)))) roomList.add(nR); // this will keep the list growing, as well as grow the list else if(!foundEntrance) { foundEntrance=true; roomList.remove(dR);// purpose here is to put the "front" door up front. roomList.add(0,dR);// purpose here is to put the "front" door up front. } } } } } @Override public List<Room> getTitledRooms() { final Room R = getATitledRoom(); if(R!=null) return new XVector<Room>(R); return new Vector<Room>(1); } @Override public int getNumTitledRooms() { return getATitledRoom() != null ? 1 : 0; } protected static PairList<Physical, Room> gatherGridItems(final Room R) { final PairList<Physical, Room> gridItems = new PairArrayList<Physical, Room>(); if (R instanceof GridLocale) { for (final Room sR : ((GridLocale) R).getAllRooms()) { for (final Enumeration<Item> i = sR.items(); i.hasMoreElements();) { final Item I = i.nextElement(); if ((I != null) && (I.isSavable()) &&(sR.isContent(I)) && (I.container()==null)) { gridItems.add(new Pair<Physical, Room>(I, sR)); R.moveItemTo(I,Expire.Never,Move.Followers); } } for (final Enumeration<MOB> m = sR.inhabitants(); m.hasMoreElements();) { final MOB M = m.nextElement(); if ((M != null) && (M.isMonster()) && (M.isSavable())) { gridItems.add(new Pair<Physical, Room>(M, sR)); R.bringMobHere(M, true); } } } } return gridItems; } protected static void restoreGridItems(final PairList<Physical, Room> gridItems) { for(final Pair<Physical, Room> thing : gridItems) { if(thing.first instanceof Item) { final Item I=(Item)thing.first; final Room R=thing.second; if((I!=null)&&(R!=null)) R.moveItemTo(I,Expire.Player_Drop,Move.Followers); } else if (thing.first instanceof MOB) { final MOB M = (MOB) thing.first; final Room R = thing.second; if ((M != null) && (R != null)) R.bringMobHere(M, true); } } } /** * Updates a room with the provided land title and various options. This method handles updating items, exits, * and the room itself based on the given parameters. * * @param R The room to be updated. * @param T The land title associated with the room. * @param resetRoomName Whether to reset the room's name. * @param clearAllItems Whether to clear all items from the room. * @param optPlayerList A set of optional player names for additional checks or updates. * @param lastNumItems The number of items in the room before updates were made. * @param daysSinceItemsSaved The number of days since the items were last saved. * @return An array containing two integers: * - The first integer is a status code. If it's -1, it indicates an error or failure occurred. * - The second integer represents the number of updates made to the room. */ public static int[] updateLotWithThisData(Room R, final LandTitle T, final boolean resetRoomName, final boolean clearAllItems, final Set<String> optPlayerList, final int lastNumItems, int daysSinceItemsSaved) { boolean updateItems=false; boolean updateExits=false; boolean updateRoom=false; synchronized(CMClass.getSync("SYNC"+R.roomID())) { R=CMLib.map().getRoom(R); if(R==null) return new int[] {-1,0}; final PairList<Physical,Room> gridItems = gatherGridItems(R); if(T.getOwnerName().length()==0) { Item I=null; for(int i=R.numItems()-1;i>=0;i--) { I=R.getItem(i); if((I==null) ||(I.Name().equalsIgnoreCase("id"))) continue; CMLib.catalog().updateCatalogIntegrity(I); if(clearAllItems) { I.destroy(); updateItems=true; } else { if(I.expirationDate()==0) { long now=System.currentTimeMillis(); now+=(TimeManager.MILI_MINUTE*CMProps.getIntVar(CMProps.Int.EXPIRE_PLAYER_DROP)); I.setExpirationDate(now); } if((I.phyStats().rejuv()!=PhyStats.NO_REJUV) &&(I.phyStats().rejuv()!=0)) { I.basePhyStats().setRejuv(PhyStats.NO_REJUV); I.recoverPhyStats(); } } } Ability A=null; if(clearAllItems) { for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();) { A=a.nextElement(); if(((A!=null) &&((A.classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_PROPERTY))) { A.unInvoke(); R.delEffect(A); updateRoom=true; } } } for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room R2=R.rawDoors()[d]; Exit E=R.getRawExit(d); if((E!=null) &&(E.hasALock()) &&(E.isGeneric())) { E.setKeyName(""); E.setDoorsNLocks(E.hasADoor(),E.isOpen(),E.defaultsClosed(),false,false,false); updateExits=true; if(R2!=null) { E=R2.getRawExit(Directions.getOpDirectionCode(d)); if((E!=null) &&(E.hasALock()) &&(E.isGeneric())) { E.setKeyName(""); E.setDoorsNLocks(E.hasADoor(),E.isOpen(),E.defaultsClosed(),false,false,false); CMLib.database().DBUpdateExits(R2); R2.getArea().fillInAreaRoom(R2); } } } } if(updateExits) { CMLib.database().DBUpdateExits(R); R.getArea().fillInAreaRoom(R); } if(updateItems) CMLib.database().DBUpdateItems(R); if(updateRoom) CMLib.database().DBUpdateRoom(R); CMLib.law().colorRoomForSale(R,T,resetRoomName); restoreGridItems(gridItems); return new int[] {-1, 0}; } if((T.getOwnerName().length()>0) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.PROPERTYOWNERCHECKS))) { boolean playerExists = false; if(optPlayerList != null) playerExists=optPlayerList.contains(T.getOwnerName()); if(!playerExists) { playerExists=(CMLib.players().playerExistsAllHosts(T.getOwnerName())); if(!playerExists) playerExists=(CMLib.clans().getClanAnyHost(T.getOwnerName())!=null); if(playerExists && (optPlayerList != null)) optPlayerList.add(T.getOwnerName()); // dynamic updating, whee! } if(!playerExists) { String id=T.getTitleID(); if((id==null)||(id.equalsIgnoreCase("null"))) id=CMLib.map().getExtendedRoomID(R); Log.warnOut("Property owned by non-existant player "+T.getOwnerName()+" is now lost: "+id); T.setOwnerName(""); T.updateLot(null); CMLib.database().DBUpdateRoom(R); restoreGridItems(gridItems); return new int[] {-1, 0}; } } int x=R.description().indexOf(SALESTR); if(x>=0) { R.setDescription(R.description().substring(0,x)); CMLib.database().DBUpdateRoom(R); } x=R.description().indexOf(RENTSTR); if(x>=0) { R.setDescription(R.description().substring(0,x)); CMLib.database().DBUpdateRoom(R); } // this works on the principle that // 1. if an item has ONLY been removed, the lastNumItems will be != current # items // 2. if an item has ONLY been added, the dispossessiontime will be != null // 3. if an item has been added AND removed, the dispossession time will be != null on the added if((lastNumItems>=0) &&(R.numItems()!=lastNumItems)) updateItems=true; for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if(I!=null) { if((I.expirationDate()!=0) &&((I.isSavable())||(I.Name().equalsIgnoreCase("id"))) &&((!(I instanceof DeadBody))||(((DeadBody)I).isPlayerCorpse()))) { I.setExpirationDate(0); updateItems=true; } if((I.phyStats().rejuv()!=PhyStats.NO_REJUV) &&(I.phyStats().rejuv()!=0)) { I.basePhyStats().setRejuv(PhyStats.NO_REJUV); I.recoverPhyStats(); updateItems=true; } } } if(!updateItems) { if(daysSinceItemsSaved>1) { final TimeClock C=R.getArea().getTimeObj(); if(C!=null) { final long t0 = C.getMonthsInYear() * C.getDaysInMonth() * C.getHoursInDay(); final long t = t0 * CMProps.getMillisPerMudHour() / MudHost.TIME_SAVETHREAD_SLEEP; final CMFlagLibrary flags=CMLib.flags(); if(daysSinceItemsSaved > t) { daysSinceItemsSaved=-1; if(!CMLib.flags().isWateryRoom(R)) { for(final Enumeration<Item> i=R.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I!=null) &&(I.container()==null) &&(flags.isGettable(I)) &&(flags.isSavable(I))) { if((I.numEffects()==0)||(I.fetchEffect("Dusty")==null)) { final Ability A=CMClass.getAbility("Dusty"); if(A!=null) { A.setMiscText("LEVEL=0 INTERVAL="+t0); I.addNonUninvokableEffect(A); updateItems=true; } } } } } } } } } if((!CMSecurity.isSaveFlag(CMSecurity.SaveFlag.NOPROPERTYITEMS)) &&(updateItems)) CMLib.database().DBUpdateItems(R); restoreGridItems(gridItems); } return new int[] {R.numItems(), updateItems?0:(daysSinceItemsSaved+1)}; } @SuppressWarnings("unchecked") public static boolean doRentalProperty(final Area A, final String ID, final String owner, final int rent) { if(!CMProps.isState(CMProps.HostState.RUNNING)) return false; final int month=A.getTimeObj().getMonth(); final int day=A.getTimeObj().getDayOfMonth(); final int year=A.getTimeObj().getYear(); final Object O=Resources.getResource("RENTAL INFO/"+owner); List<PlayerData> pDataV=null; if(O instanceof List) pDataV=(List<PlayerData>)O; else pDataV=CMLib.database().DBReadPlayerData(owner,"RENTAL INFO"); if(pDataV==null) pDataV=new Vector<PlayerData>(); DatabaseEngine.PlayerData pData = null; if(pDataV.size()==0) { final String section="RENTAL INFO"; final String key="RENTAL INFO/"+owner; final String xml=ID+"|~>|"+day+" "+month+" "+year+"|~;|"; pData = CMLib.database().DBCreatePlayerData(owner,section,key,xml); pDataV.add(pData); Resources.submitResource("RENTAL INFO/"+owner,pDataV); return false; } else if(pDataV.get(0) != null) { pData=pDataV.get(0); String parse=pData.xml(); int x=parse.indexOf("|~;|"); final StringBuffer reparse=new StringBuffer(""); boolean changesMade=false; boolean needsToPay=false; while(x>=0) { String thisOne=parse.substring(0,x); if(thisOne.startsWith(ID+"|~>|")) { thisOne=thisOne.substring((ID+"|~>|").length()); final Vector<String> dateV=CMParms.parse(thisOne); if(dateV.size()==3) { int lastYear=CMath.s_int(dateV.lastElement()); int lastMonth=CMath.s_int(dateV.elementAt(1)); final int lastDay=CMath.s_int(dateV.firstElement()); while(!needsToPay) { if(lastYear<year) needsToPay=true; else if((lastYear==year)&&(lastMonth<month)&&(day>=lastDay)) needsToPay=true; if(needsToPay) { if(CMLib.beanCounter().modifyLocalBankGold(A, owner, CMLib.utensils().getFormattedDate(A)+":Withdrawal of "+rent+": Rent for "+ID, (-rent))) { lastMonth++; if(lastMonth>A.getTimeObj().getMonthsInYear()) { lastMonth=1; lastYear++; } changesMade=true; needsToPay=false; } } else break; } if(changesMade) reparse.append(ID+"|~>|"+lastDay+" "+lastMonth+" "+lastYear+"|~;|"); if(needsToPay&&(!changesMade)) return true; } } else reparse.append(thisOne+"|~;|"); parse=parse.substring(x+4); x=parse.indexOf("|~;|"); } if(changesMade) { pData = CMLib.database().DBReCreatePlayerData(owner,"RENTAL INFO","RENTAL INFO/"+owner,reparse.toString()); Resources.removeResource("RENTAL INFO/"+owner); if(pData != null) { pDataV.set(0,pData); Resources.submitResource("RENTAL INFO/"+owner,pDataV); } } return needsToPay; } return false; } // update lot, since its called by the savethread, ONLY worries about itself @Override public void updateLot(final Set<String> optPlayerList) { if(affected instanceof Room) { Room R=(Room)affected; synchronized(CMClass.getSync("SYNC"+R.roomID())) { R=CMLib.map().getRoom(R); int[] data=updateLotWithThisData(R,this,false,scheduleReset,optPlayerList,lastItemNums,daysWithNoChange); lastItemNums=data[0]; daysWithNoChange=data[1]; // rentals are below if((lastDayDone!=R.getArea().getTimeObj().getDayOfMonth()) &&(CMProps.isState(CMProps.HostState.RUNNING))) { lastDayDone=R.getArea().getTimeObj().getDayOfMonth(); if((getOwnerName().length()>0) &&rentalProperty() &&(R.roomID().length()>0)) { if(doRentalProperty(R.getArea(),R.roomID(),getOwnerName(),getPrice())) { setOwnerName(""); CMLib.database().DBUpdateRoom(R); data=updateLotWithThisData(R,this,false,scheduleReset,optPlayerList,lastItemNums,daysWithNoChange); lastItemNums=data[0]; daysWithNoChange=data[1]; } } } scheduleReset=false; } } } }
0
0.969685
1
0.969685
game-dev
MEDIA
0.737366
game-dev
0.940309
1
0.940309
ufrshubham/dino_run
2,805
lib/game/enemy_manager.dart
import 'dart:math'; import 'package:flame/components.dart'; import '/game/enemy.dart'; import '/game/dino_run.dart'; import '/models/enemy_data.dart'; // This class is responsible for spawning random enemies at certain // interval of time depending upon players current score. class EnemyManager extends Component with HasGameReference<DinoRun> { // A list to hold data for all the enemies. final List<EnemyData> _data = []; // Random generator required for randomly selecting enemy type. final Random _random = Random(); // Timer to decide when to spawn next enemy. final Timer _timer = Timer(2, repeat: true); EnemyManager() { _timer.onTick = spawnRandomEnemy; } // This method is responsible for spawning a random enemy. void spawnRandomEnemy() { /// Generate a random index within [_data] and get an [EnemyData]. final randomIndex = _random.nextInt(_data.length); final enemyData = _data.elementAt(randomIndex); final enemy = Enemy(enemyData); // Help in setting all enemies on ground. enemy.anchor = Anchor.bottomLeft; enemy.position = Vector2(game.virtualSize.x + 32, game.virtualSize.y - 24); // If this enemy can fly, set its y position randomly. if (enemyData.canFly) { final newHeight = _random.nextDouble() * 2 * enemyData.textureSize.y; enemy.position.y -= newHeight; } // Due to the size of our viewport, we can // use textureSize as size for the components. enemy.size = enemyData.textureSize; game.world.add(enemy); } @override void onMount() { if (isMounted) { removeFromParent(); } // Don't fill list again and again on every mount. if (_data.isEmpty) { // As soon as this component is mounted, initilize all the data. _data.addAll([ EnemyData( image: game.images.fromCache('AngryPig/Walk (36x30).png'), nFrames: 16, stepTime: 0.1, textureSize: Vector2(36, 30), speedX: 80, canFly: false, ), EnemyData( image: game.images.fromCache('Bat/Flying (46x30).png'), nFrames: 7, stepTime: 0.1, textureSize: Vector2(46, 30), speedX: 100, canFly: true, ), EnemyData( image: game.images.fromCache('Rino/Run (52x34).png'), nFrames: 6, stepTime: 0.09, textureSize: Vector2(52, 34), speedX: 150, canFly: false, ), ]); } _timer.start(); super.onMount(); } @override void update(double dt) { _timer.update(dt); super.update(dt); } void removeAllEnemies() { final enemies = game.world.children.whereType<Enemy>(); for (var enemy in enemies) { enemy.removeFromParent(); } } }
0
0.759218
1
0.759218
game-dev
MEDIA
0.768806
game-dev
0.814895
1
0.814895
decentraland/unity-renderer
4,710
unity-renderer/Assets/Scripts/MainScripts/DCL/Components/LoadableShapes/NFTShape/NFTShape.cs
using DCL.Helpers; using DCL.Models; using UnityEngine; using Decentraland.Sdk.Ecs6; using MainScripts.DCL.Components; namespace DCL.Components { public class NFTShape : LoadableShape<LoadWrapper_NFT, NFTShape.Model> { [System.Serializable] public new class Model : LoadableShape.Model { public Color color = new (0.6404918f, 0.611472f, 0.8584906f); // "light purple" default, same as in explorer public int style; public override BaseModel GetDataFromJSON(string json) => Utils.SafeFromJson<Model>(json); public override BaseModel GetDataFromPb(ComponentBodyPayload pbModel) { if (pbModel.PayloadCase != ComponentBodyPayload.PayloadOneofCase.NftShape) return Utils.SafeUnimplemented<NFTShape, Model>(expected: ComponentBodyPayload.PayloadOneofCase.NftShape, actual: pbModel.PayloadCase); var pb = new Model(); if (pbModel.NftShape.Color != null) pb.color = pbModel.NftShape.Color.AsUnityColor(); if (pbModel.NftShape.HasStyle) pb.style = (int)pbModel.NftShape.Style; if (pbModel.NftShape.HasSrc) pb.src = pbModel.NftShape.Src; if (pbModel.NftShape.HasVisible) pb.visible = pbModel.NftShape.Visible; if (pbModel.NftShape.HasWithCollisions) pb.withCollisions = pbModel.NftShape.WithCollisions; if (pbModel.NftShape.HasIsPointerBlocker) pb.isPointerBlocker = pbModel.NftShape.IsPointerBlocker; return pb; } } public override string componentName => "NFT Shape"; private INFTInfoRetriever infoRetriever; private INFTAssetRetriever assetRetriever; public NFTShape(INFTInfoRetriever infoRetriever, INFTAssetRetriever assetRetriever) { model = new Model(); this.infoRetriever = infoRetriever; this.assetRetriever = assetRetriever; } public override int GetClassId() { return (int) CLASS_ID.NFT_SHAPE; } protected override void AttachShape(IDCLEntity entity) { if (string.IsNullOrEmpty(model.src)) { #if UNITY_EDITOR Debug.LogError($"NFT SHAPE with url '{model.src}' couldn't be loaded."); #endif return; } entity.meshesInfo.meshRootGameObject = NFTShapeFactory.InstantiateLoaderController(model.style); entity.meshesInfo.currentShape = this; entity.meshRootGameObject.name = componentName + " mesh"; entity.meshRootGameObject.transform.SetParent(entity.gameObject.transform); entity.meshRootGameObject.transform.ResetLocalTRS(); var loaderController = entity.meshRootGameObject.GetComponent<NFTShapeLoaderController>(); if (loaderController) loaderController.Initialize(infoRetriever, assetRetriever); entity.OnShapeUpdated += UpdateBackgroundColor; var loadableShape = Environment.i.world.state.GetOrAddLoaderForEntity<LoadWrapper_NFT>(entity); loadableShape.entity = entity; bool initialVisibility = model.visible; if (!DataStore.i.debugConfig.isDebugMode.Get()) initialVisibility &= entity.isInsideSceneBoundaries; loadableShape.initialVisibility = initialVisibility; loadableShape.withCollisions = model.withCollisions && entity.isInsideSceneBoundaries; loadableShape.backgroundColor = model.color; loadableShape.Load(model.src, OnLoadCompleted, OnLoadFailed); } protected override void DetachShape(IDCLEntity entity) { if (entity == null || entity.meshRootGameObject == null) return; entity.OnShapeUpdated -= UpdateBackgroundColor; base.DetachShape(entity); } protected override void ConfigureColliders(IDCLEntity entity) { CollidersManager.i.ConfigureColliders(entity.meshRootGameObject, model.withCollisions, false, entity); } void UpdateBackgroundColor(IDCLEntity entity) { if (previousModel is NFTShape.Model && model.color == previousModel.color) return; var loadableShape = Environment.i.world.state.GetLoaderForEntity(entity) as LoadWrapper_NFT; loadableShape?.loaderController.UpdateBackgroundColor(model.color); } public override string ToString() { if (model == null) return base.ToString(); return $"{componentName} (src = {model.src})"; } } }
0
0.864885
1
0.864885
game-dev
MEDIA
0.8004
game-dev,graphics-rendering
0.926506
1
0.926506
manuel-serrano/bigloo
74,992
api/phidget/src/Clib/bglphidget.c
/*=====================================================================*/ /* .../prgm/project/bigloo/api/phidget/src/Clib/bglphidget.c */ /* ------------------------------------------------------------- */ /* Author : Manuel Serrano */ /* Creation : Tue Sep 21 12:08:37 2010 */ /* Last change : Thu Nov 15 12:41:52 2012 (serrano) */ /* Copyright : 2010-12 Manuel Serrano */ /* ------------------------------------------------------------- */ /* Bigloo wrapper for the widget library */ /*=====================================================================*/ #include "bglphidget_config.h" #include "bglphidget.h" #include <string.h> #include <bigloo.h> /*---------------------------------------------------------------------*/ /* CHECK_PROCEDURE */ /*---------------------------------------------------------------------*/ #define CHECK_PROCEDURE( proc, arity ) \ if( !PROCEDURE_CORRECT_ARITYP( proc, arity ) ) { \ char buf[ 80 ]; \ sprintf( buf, "wrong number of arguments for callback (%d expected)", arity ); \ C_SYSTEM_FAILURE( BGL_ERROR, "phidget-add-event-listener", buf, proc ); \ } /*---------------------------------------------------------------------*/ /* struct handler */ /* ------------------------------------------------------------- */ /* handler is a local data type used to bind bigloo objects and */ /* bigloo procedures so that phidget events can retreive the */ /* owner of the handler. In addition, the handlers global variable */ /* plays the role of a ROOT for the GC. */ /*---------------------------------------------------------------------*/ struct handler { int evtype; obj_t obj; obj_t proc; }; #define EVENT_ERROR 1 #define EVENT_ATTACH 2 #define EVENT_DETACH 3 #define EVENT_INPUTCHANGE 4 #define EVENT_OUTPUTCHANGE 5 #define EVENT_SENSORCHANGE 6 #define EVENT_SERVERCONNECT 7 #define EVENT_SERVERDISCONNECT 8 #define EVENT_SPATIALDATA 9 #define EVENT_SERVOPOSITION 10 #define EVENT_SERVOVELOCITY 11 #define EVENT_SERVOCURRENT 12 #define EVENT_STEPPERINPUT 13 #define EVENT_STEPPERVELOCITY 14 #define EVENT_STEPPERPOSITION 15 #define EVENT_STEPPERCURRENT 16 #define EVENT_MOTORCONTROLVELOCITY 17 #define EVENT_MOTORCONTROLCURRENT 18 #define EVENT_ENCODERINPUT 19 #define EVENT_ENCODERPOSITION 20 #define EVENT_ENCODERINDEX 21 #define INITIAL_MAX_HANDLER 40 static struct handler *handlers; static int handler_length = INITIAL_MAX_HANDLER; static int handler_index = 0; /*---------------------------------------------------------------------*/ /* struct callback */ /* ------------------------------------------------------------- */ /* The callback machinery is used for one purpose. Phidget */ /* threads cannot invoke Bigloo code because the GC gets */ /* confused when alloc and collection functions are called from */ /* non-Bigloo thread. The callback is used to register the */ /* callbacks that are invoked by a dedicated Bigloo thread. */ /*---------------------------------------------------------------------*/ struct callback { struct handler *handler; union { struct { int code; char *msg; } error; struct { CPhidgetHandle id; } phidget; struct { int index; int istate; } change; struct { int seconds; int microseconds; double acceleration[ 3 ]; double angularRate[ 3 ]; double magneticField[ 3 ]; } spatial; struct { int index; double position; } servoposition; struct { int index; double velocity; } servovelocity; struct { int index; double current; } servocurrent; struct { int index; BGL_LONGLONG_T position; } stepperposition; struct { int index; double velocity; } motorcontrolvelocity; struct { int index; double current; } motorcontrolcurrent; struct { int index; int state; } encoderinput; struct { int index; int time; int position; } encoderposition; struct { int index; int position; } encoderindex; } event; }; #define INITIAL_MAX_CALLBACK 40 static struct callback *callbacks; static int callback_length = INITIAL_MAX_CALLBACK; static int callback_index = 0; /*---------------------------------------------------------------------*/ /* void */ /* bgl_phidget_init ... */ /*---------------------------------------------------------------------*/ void bgl_phidget_init() { /* allocated the callbacks array */ callbacks = calloc( sizeof( struct callback ), callback_length ); /* allocated the handlers array */ handlers = (void *)GC_MALLOC( sizeof( struct handler ) * handler_length ); } /*---------------------------------------------------------------------*/ /* ENLARGE_ARRAY ... */ /*---------------------------------------------------------------------*/ #define ENLARGE_ARRAY( type ) { \ struct type *n##type##s; \ int osize = type##_length * sizeof( struct type ); \ \ type##_length *= 2; \ n##type##s = malloc( osize * 2 ); \ memcpy( n##type##s, type##s, osize ); \ \ free( type##s ); \ type##s = n##type##s; \ } /*---------------------------------------------------------------------*/ /* static void */ /* enlarge_callback_array ... */ /*---------------------------------------------------------------------*/ static void enlarge_callback_array() { ENLARGE_ARRAY( callback ); } /*---------------------------------------------------------------------*/ /* static void */ /* enlarge_handler_array ... */ /*---------------------------------------------------------------------*/ static void enlarge_handler_array() { ENLARGE_ARRAY( handler ); } /*---------------------------------------------------------------------*/ /* void */ /* bgl_phidget_invoke_callbacks ... */ /* ------------------------------------------------------------- */ /* This function is invoked by a Scheme code when it has been */ /* signaled that a phidget event has been fired. */ /*---------------------------------------------------------------------*/ void bgl_phidget_invoke_callbacks() { while( callback_index > 0 ) { struct callback *cb = &callbacks[ --callback_index ]; struct handler *hdl = cb->handler; obj_t event; switch( hdl->evtype ) { case EVENT_ERROR: event = bgl_phidget_event_error_new( hdl->obj, cb->event.error.code, cb->event.error.msg ); break; case EVENT_ATTACH: event = bgl_phidget_event_attach_new( hdl->obj, cb->event.phidget.id ); break; case EVENT_DETACH: event = bgl_phidget_event_detach_new( hdl->obj, cb->event.phidget.id ); break; case EVENT_INPUTCHANGE: event = bgl_phidget_event_inputchange_new( hdl->obj, cb->event.change.index, cb->event.change.istate == PTRUE ); break; case EVENT_OUTPUTCHANGE: event = bgl_phidget_event_outputchange_new( hdl->obj, cb->event.change.index, cb->event.change.istate == PTRUE ); break; case EVENT_SENSORCHANGE: event = bgl_phidget_event_sensorchange_new( hdl->obj, cb->event.change.index, cb->event.change.istate ); break; case EVENT_SERVERCONNECT: event = bgl_phidget_event_serverconnect_new( hdl->obj, cb->event.phidget.id ); break; case EVENT_SERVERDISCONNECT: event = bgl_phidget_event_serverdisconnect_new( hdl->obj, cb->event.phidget.id ); break; case EVENT_SPATIALDATA: { event = bgl_phidget_event_spatialdata_new( hdl->obj, cb->event.spatial.seconds, cb->event.spatial.microseconds, cb->event.spatial.acceleration[ 0 ], cb->event.spatial.acceleration[ 1 ], cb->event.spatial.acceleration[ 2 ], cb->event.spatial.angularRate[ 0 ], cb->event.spatial.angularRate[ 1 ], cb->event.spatial.angularRate[ 2 ], cb->event.spatial.magneticField[ 0 ], cb->event.spatial.magneticField[ 1 ], cb->event.spatial.magneticField[ 2 ] ); break; } case EVENT_SERVOPOSITION: { event = bgl_phidget_event_servoposition_new( hdl->obj, cb->event.servoposition.index, cb->event.servoposition.position ); break; } case EVENT_SERVOVELOCITY: { event = bgl_phidget_event_servovelocity_new( hdl->obj, cb->event.servovelocity.index, cb->event.servovelocity.velocity ); break; } case EVENT_SERVOCURRENT: { event = bgl_phidget_event_servocurrent_new( hdl->obj, cb->event.servocurrent.index, cb->event.servocurrent.current ); break; } case EVENT_STEPPERINPUT: { event = bgl_phidget_event_stepperinput_new( hdl->obj, cb->event.change.index, cb->event.change.istate == PTRUE ); break; } case EVENT_STEPPERVELOCITY: { event = bgl_phidget_event_steppervelocity_new( hdl->obj, cb->event.servovelocity.index, cb->event.servovelocity.velocity ); break; } case EVENT_STEPPERPOSITION: { event = bgl_phidget_event_stepperposition_new( hdl->obj, cb->event.stepperposition.index, cb->event.stepperposition.position ); break; } case EVENT_STEPPERCURRENT: { event = bgl_phidget_event_steppercurrent_new( hdl->obj, cb->event.servocurrent.index, cb->event.servocurrent.current ); break; } case EVENT_MOTORCONTROLVELOCITY: { event = bgl_phidget_event_motorcontrolvelocity_new( hdl->obj, cb->event.motorcontrolvelocity.index, cb->event.motorcontrolvelocity.velocity ); break; } case EVENT_MOTORCONTROLCURRENT: { event = bgl_phidget_event_motorcontrolcurrent_new( hdl->obj, cb->event.motorcontrolcurrent.index, cb->event.motorcontrolcurrent.current ); break; } case EVENT_ENCODERINPUT: { event = bgl_phidget_event_encoderinput_new( hdl->obj, cb->event.encoderinput.index, cb->event.encoderinput.state ); break; } case EVENT_ENCODERINDEX: { event = bgl_phidget_event_encoderindex_new( hdl->obj, cb->event.encoderindex.index, cb->event.encoderindex.position ); break; } case EVENT_ENCODERPOSITION: { event = bgl_phidget_event_encoderposition_new( hdl->obj, cb->event.encoderposition.index, cb->event.encoderposition.time, cb->event.encoderposition.position ); break; } default: event = BUNSPEC; C_SYSTEM_FAILURE( BGL_ERROR, "phidget", "Unknown event", BINT( hdl->evtype ) ); } PROCEDURE_ENTRY( hdl->proc )( hdl->proc, event, BEOA ); } } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_add_handler ... */ /*---------------------------------------------------------------------*/ static struct handler *bgl_add_handler( obj_t obj, obj_t proc, int evtype ) { struct handler *hdl; CHECK_PROCEDURE( proc, 1 ); bgl_phidget_lock(); if( handler_index == handler_length ) enlarge_handler_array(); handlers[ handler_index ].evtype = evtype; handlers[ handler_index ].proc = proc; handlers[ handler_index ].obj = obj; hdl = &handlers[ handler_index++ ]; bgl_phidget_unlock(); return hdl; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_phidget_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_phidget_handler( CPhidgetHandle phid, void *ptr ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.phidget.id = phid; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_change_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_change_handler( CPhidgetInterfaceKitHandle id, void *ptr, int index, int istate ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.change.index = index; callbacks[ callback_index ].event.change.istate = istate; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_spatial_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_spatial_handler( CPhidgetSpatialHandle id, void *ptr, CPhidgetSpatial_SpatialEventDataHandle *data, int count ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.spatial.seconds = data[ 0 ]->timestamp.seconds; callbacks[ callback_index ].event.spatial.microseconds = data[ 0 ]->timestamp.microseconds; callbacks[ callback_index ].event.spatial.acceleration[ 0 ] = data[ 0 ]->acceleration[ 0 ]; callbacks[ callback_index ].event.spatial.acceleration[ 1 ] = data[ 0 ]->acceleration[ 1 ]; callbacks[ callback_index ].event.spatial.acceleration[ 2 ] = data[ 0 ]->acceleration[ 2 ]; callbacks[ callback_index ].event.spatial.angularRate[ 0 ] = data[ 0 ]->angularRate[ 0 ]; callbacks[ callback_index ].event.spatial.angularRate[ 1 ] = data[ 0 ]->angularRate[ 1 ]; callbacks[ callback_index ].event.spatial.angularRate[ 2 ] = data[ 0 ]->angularRate[ 2 ]; callbacks[ callback_index ].event.spatial.magneticField[ 0 ] = data[ 0 ]->magneticField[ 0 ]; callbacks[ callback_index ].event.spatial.magneticField[ 1 ] = data[ 0 ]->magneticField[ 1 ]; callbacks[ callback_index ].event.spatial.magneticField[ 2 ] = data[ 0 ]->magneticField[ 2 ]; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_servoposition_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_servoposition_handler( CPhidgetServoHandle id, void *ptr, int index, double position ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servoposition.index = index; callbacks[ callback_index ].event.servoposition.position = position; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_advanced_servoposition_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_advanced_servoposition_handler( CPhidgetAdvancedServoHandle id, void *ptr, int index, double position ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servoposition.index = index; callbacks[ callback_index ].event.servoposition.position = position; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_advanced_servovelocity_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_advanced_servovelocity_handler( CPhidgetAdvancedServoHandle id, void *ptr, int index, double velocity ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servovelocity.index = index; callbacks[ callback_index ].event.servovelocity.velocity = velocity; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_advanced_servocurrent_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_advanced_servocurrent_handler( CPhidgetAdvancedServoHandle id, void *ptr, int index, double current ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servocurrent.index = index; callbacks[ callback_index ].event.servocurrent.current = current; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_stepperinput_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_stepperinput_handler( CPhidgetStepperHandle id, void *ptr, int index, int istate ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.change.index = index; callbacks[ callback_index ].event.change.istate = istate; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_steppervelocity_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_steppervelocity_handler( CPhidgetStepperHandle id, void *ptr, int index, double velocity ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servovelocity.index = index; callbacks[ callback_index ].event.servovelocity.velocity = velocity; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_stepperposition_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_stepperposition_handler( CPhidgetStepperHandle id, void *ptr, int index, BGL_LONGLONG_T position ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.stepperposition.index = index; callbacks[ callback_index ].event.stepperposition.position = position; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_steppercurrent_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_steppercurrent_handler( CPhidgetStepperHandle id, void *ptr, int index, double current ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servocurrent.index = index; callbacks[ callback_index ].event.servocurrent.current = current; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_error_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_error_handler( void *id, void *ptr, int ecode, const char *emsg ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.error.code = ecode; callbacks[ callback_index ].event.error.msg = strdup( emsg ); callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_phidget_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_phidget_add_event_listener( CPhidgetHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "attach" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_ATTACH ); return CPhidget_set_OnAttach_Handler( id, &bgl_phidget_handler, hdl ); } else if( !strcmp( event, "detach" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_DETACH ); return CPhidget_set_OnDetach_Handler( id, &bgl_phidget_handler, hdl ); } else if( !strcmp( event, "error" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_ERROR ); return CPhidget_set_OnError_Handler( id, (int(*)(CPhidgetHandle, void *, int, const char *))&bgl_error_handler, hdl ); } else if( !strcmp( event, "serverconnect" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SERVERCONNECT ); return CPhidget_set_OnServerConnect_Handler( id, &bgl_phidget_handler, hdl ); } else if( !strcmp( event, "serverdisconnect" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SERVERDISCONNECT ); return CPhidget_set_OnServerDisconnect_Handler( id, &bgl_phidget_handler, hdl ); } return EPHIDGET_INVALIDARG; } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_manager_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_manager_add_event_listener( CPhidgetManagerHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "attach" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_ATTACH ); return CPhidgetManager_set_OnAttach_Handler( id, (int (*)())(&bgl_phidget_handler), hdl ); } else if( !strcmp( event, "detach" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_DETACH ); return CPhidgetManager_set_OnDetach_Handler( id, (int (*)())&bgl_phidget_handler, hdl ); } else if( !strcmp( event, "error" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_ERROR ); return CPhidgetManager_set_OnError_Handler( id, (int(*)(CPhidgetManagerHandle, void *, int, const char *))&bgl_error_handler, hdl ); } else { return bgl_phidget_phidget_add_event_listener( (CPhidgetHandle)id, event, obj, proc ); } } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_ifkit_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_ifkit_add_event_listener( CPhidgetInterfaceKitHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "inputchange" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_INPUTCHANGE ); return CPhidgetInterfaceKit_set_OnInputChange_Handler( id, &bgl_change_handler, hdl ); } else if( !strcmp( event, "outputchange" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_OUTPUTCHANGE ); return CPhidgetInterfaceKit_set_OnOutputChange_Handler( id, &bgl_change_handler, hdl ); } else if( !strcmp( event, "sensorchange" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SENSORCHANGE ); return CPhidgetInterfaceKit_set_OnSensorChange_Handler( id, &bgl_change_handler, hdl ); } else { return bgl_phidget_phidget_add_event_listener( (CPhidgetHandle)id, event, obj, proc ); } } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_spatial_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_spatial_add_event_listener( CPhidgetSpatialHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "spatialdata" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SPATIALDATA ); return CPhidgetSpatial_set_OnSpatialData_Handler( id, &bgl_spatial_handler, hdl ); } else { return bgl_phidget_phidget_add_event_listener( (CPhidgetHandle)id, event, obj, proc ); } } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_servo_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_servo_add_event_listener( CPhidgetServoHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "position" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SERVOPOSITION ); return CPhidgetServo_set_OnPositionChange_Handler( id, &bgl_servoposition_handler, hdl ); } else { return bgl_phidget_phidget_add_event_listener( (CPhidgetHandle)id, event, obj, proc ); } } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_advanced_servo_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_advanced_servo_add_event_listener( CPhidgetAdvancedServoHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "position" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SERVOPOSITION ); return CPhidgetAdvancedServo_set_OnPositionChange_Handler( id, &bgl_advanced_servoposition_handler, hdl ); } if( !strcmp( event, "velocity" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SERVOVELOCITY ); return CPhidgetAdvancedServo_set_OnVelocityChange_Handler( id, &bgl_advanced_servovelocity_handler, hdl ); } if( !strcmp( event, "current" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_SERVOCURRENT ); return CPhidgetAdvancedServo_set_OnCurrentChange_Handler( id, &bgl_advanced_servocurrent_handler, hdl ); } else { return bgl_phidget_phidget_add_event_listener( (CPhidgetHandle)id, event, obj, proc ); } } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_stepper_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_stepper_add_event_listener( CPhidgetStepperHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "input" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_STEPPERINPUT ); return CPhidgetStepper_set_OnInputChange_Handler( id, &bgl_stepperinput_handler, hdl ); } if( !strcmp( event, "velocity" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_STEPPERVELOCITY ); return CPhidgetStepper_set_OnVelocityChange_Handler( id, &bgl_steppervelocity_handler, hdl ); } if( !strcmp( event, "position" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_STEPPERPOSITION ); return CPhidgetStepper_set_OnPositionChange_Handler( id, &bgl_stepperposition_handler, hdl ); } if( !strcmp( event, "current" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_STEPPERCURRENT ); return CPhidgetStepper_set_OnCurrentChange_Handler( id, &bgl_steppercurrent_handler, hdl ); } else { return bgl_phidget_phidget_add_event_listener( (CPhidgetHandle)id, event, obj, proc ); } } /*---------------------------------------------------------------------*/ /* FIELD_GET_STRING ... */ /*---------------------------------------------------------------------*/ #define FIELD_GET_STRING( phid, field ) { \ char *name; \ int i = CPhidget_get##field( phid, (const char **)&name ); \ \ return i ? BUNSPEC : string_to_bstring( name ); \ } /*---------------------------------------------------------------------*/ /* FIELD_GET_INT ... */ /*---------------------------------------------------------------------*/ #define FIELD_GET_INT( phid, field ) { \ int i; \ int r = CPhidget_get##field( phid, &i ); \ \ return r ? -1 : i; \ } /*---------------------------------------------------------------------*/ /* FIELD_GET */ /*---------------------------------------------------------------------*/ #define FIELD_GET( _phid, _field, _atype, _rtype, _o ) { \ _rtype _v; \ int _r = _atype##_get##_field( _phid, &_v ); \ return _r == EPHIDGET_OK ? \ _v : (bgl_phidget_error( "" # _field "", _r, _o ), _v); \ } /*---------------------------------------------------------------------*/ /* FIELD_INDEXED_GET */ /*---------------------------------------------------------------------*/ #define FIELD_INDEXED_GET( _phid, _field, _atype, _rtype, _i, _o ) { \ _rtype _v; \ int _r = _atype##_get##_field( _phid, _i, &_v ); \ return _r == EPHIDGET_OK ? \ _v : (bgl_phidget_error( "" # _field "", _r, _o ), _v); \ } /*---------------------------------------------------------------------*/ /* obj_t */ /* bgl_phidget_get_device_name ... */ /*---------------------------------------------------------------------*/ obj_t bgl_phidget_get_device_name( CPhidgetHandle phid ) { FIELD_GET_STRING( phid, DeviceName ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_get_serial_number ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_get_serial_number( CPhidgetHandle phid ) { FIELD_GET_INT( phid, SerialNumber ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_get_device_version ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_get_device_version( CPhidgetHandle phid ) { FIELD_GET_INT( phid, DeviceVersion ); } /*---------------------------------------------------------------------*/ /* obj_t */ /* bgl_phidget_get_device_type ... */ /*---------------------------------------------------------------------*/ obj_t bgl_phidget_get_device_type( CPhidgetHandle phid ) { FIELD_GET_STRING( phid, DeviceType ); } /*---------------------------------------------------------------------*/ /* obj_t */ /* bgl_phidget_get_device_id ... */ /*---------------------------------------------------------------------*/ obj_t bgl_phidget_get_device_id( CPhidgetHandle phid ) { CPhidget_DeviceID id; int i = CPhidget_getDeviceID( phid, &id ); if( i ) { return BUNSPEC; } else { switch( i ) { case PHIDID_ACCELEROMETER_3AXIS: return string_to_bstring( "Phidget 3-axis Accelerometer (1059)" ); case PHIDID_ADVANCEDSERVO_1MOTOR: return string_to_bstring( "Phidget 1 Motor Advanced Servo (1066)" ); case PHIDID_ADVANCEDSERVO_8MOTOR: return string_to_bstring( "Phidget 8 Motor Advanced Servo (1061)" ); case PHIDID_BIPOLAR_STEPPER_1MOTOR: return string_to_bstring( "Phidget 1 Motor Bipolar Stepper Controller with 4 Digital Inputs (1063)" ); case PHIDID_ENCODER_1ENCODER_1INPUT: return string_to_bstring( "Phidget Encoder - Mechanical (1052)" ); case PHIDID_ENCODER_HS_1ENCODER: return string_to_bstring( "Phidget High Speed Encoder (1057)" ); case PHIDID_ENCODER_HS_4ENCODER_4INPUT: return string_to_bstring( "Phidget High Speed Encoder - 4 Encoder (1047)" ); case PHIDID_INTERFACEKIT_0_0_4: return string_to_bstring( "Phidget Interface Kit 0/0/4 (1014)" ); case PHIDID_INTERFACEKIT_0_0_8: return string_to_bstring( "Phidget Interface Kit 0/0/8 (1017)" ); case PHIDID_INTERFACEKIT_0_16_16: return string_to_bstring( "Phidget Interface Kit 0/16/16 (1012)" ); case PHIDID_INTERFACEKIT_8_8_8: return string_to_bstring( "Phidget Interface Kit 8/8/8 (1013, 1018, 1019)" ); case PHIDID_INTERFACEKIT_8_8_8_w_LCD: return string_to_bstring( "Phidget Interface Kit 8/8/8 with TextLCD (1201, 1202, 1203)" ); case PHIDID_IR: return string_to_bstring( "Phidget IR Receiver Transmitter (1055)" ); case PHIDID_LED_64: return string_to_bstring( "Phidget LED 64 (1030)" ); case PHIDID_LED_64_ADV: return string_to_bstring( "Phidget LED 64 Advanced (1031)" ); case PHIDID_LINEAR_TOUCH: return string_to_bstring( "Phidget Linear Touch (1015)" ); case PHIDID_MOTORCONTROL_HC_2MOTOR: return string_to_bstring( "Phidget 2 Motor High Current Motor Controller (1064)" ); case PHIDID_MOTORCONTROL_LV_2MOTOR_4INPUT: return string_to_bstring( "Phidget 2 Motor Low Voltage Motor Controller with 4 Digital Inputs (1060)" ); case PHIDID_PHSENSOR: return string_to_bstring( "Phidget PH Sensor (1058)" ); case PHIDID_RFID_2OUTPUT: return string_to_bstring( "Phidget RFID with Digital Outputs and Onboard LED (1023)" ); case PHIDID_ROTARY_TOUCH: return string_to_bstring( "Phidget Rotary Touch (1016)" ); case PHIDID_SERVO_1MOTOR: return string_to_bstring( "Phidget 1 Motor Servo Controller (1000)" ); case PHIDID_SPATIAL_ACCEL_3AXIS: return string_to_bstring( "Phidget Spatial 3-axis accel (1049)" ); case PHIDID_SPATIAL_ACCEL_GYRO_COMPASS: return string_to_bstring( "Phidget Spatial 3/3/3 (1056)" ); case PHIDID_TEMPERATURESENSOR: return string_to_bstring( "Phidget Temperature Sensor (1051)" ); case PHIDID_TEMPERATURESENSOR_4: return string_to_bstring( "Phidget Temperature Sensor 4-input (1048)" ); case PHIDID_TEXTLCD_2x20_w_8_8_8: return string_to_bstring( "Phidget TextLCD with Interface Kit 8/8/8 (1201, 1202, 1203)" ); case PHIDID_UNIPOLAR_STEPPER_4MOTOR: return string_to_bstring( "Phidget 4 Motor Unipolar Stepper Controller (1062)" ); case PHIDID_ACCELEROMETER_2AXIS: return string_to_bstring( "Phidget 2-axis Accelerometer (1053, 1054)" ); case PHIDID_INTERFACEKIT_0_8_8_w_LCD: return string_to_bstring( "Phidget Interface Kit 0/8/8 with TextLCD (1219, 1220, 1221)" ); case PHIDID_INTERFACEKIT_4_8_8: return string_to_bstring( "Phidget Interface Kit 4/8/8" ); case PHIDID_RFID: return string_to_bstring( "Phidget RFID without Digital Outputs" ); case PHIDID_SERVO_1MOTOR_OLD: return string_to_bstring( "Phidget 1 Motor Servo Controller - Old Version" ); case PHIDID_SERVO_4MOTOR: return string_to_bstring( "Phidget 4 Motor Servo Controller (1001)" ); case PHIDID_SERVO_4MOTOR_OLD: return string_to_bstring( "Phidget 4 Motor Servo Controller - Old Version" ); case PHIDID_TEXTLCD_2x20: return string_to_bstring( "Phidget TextLCD without Interface Kit (1210)" ); case PHIDID_TEXTLCD_2x20_w_0_8_8: return string_to_bstring( "Phidget TextLCD with Interface Kit 0/8/8 (1219, 1220, 1221)" ); case PHIDID_TEXTLED_1x8: return string_to_bstring( "Phidget TextLED 1x8" ); case PHIDID_TEXTLED_4x8: return string_to_bstring( "Phidget TextLED 4x8 (1040)" ); case PHIDID_WEIGHTSENSOR: return string_to_bstring( "Phidget Weight Sensor (1050) " ); default: return BUNSPEC; } } } /*---------------------------------------------------------------------*/ /* obj_t */ /* bgl_phidget_get_server_id ... */ /*---------------------------------------------------------------------*/ obj_t bgl_phidget_get_server_id( CPhidgetHandle phid ) { FIELD_GET_STRING( phid, ServerID ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_spatial_get_datarate ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_spatial_get_datarate( CPhidgetSpatialHandle phid, obj_t o ) { FIELD_GET( phid, DataRate, CPhidgetSpatial, int, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_spatial_get_datarate_min ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_spatial_get_datarate_min( CPhidgetSpatialHandle phid, obj_t o ) { FIELD_GET( phid, DataRateMin, CPhidgetSpatial, int, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_spatial_get_datarate_max ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_spatial_get_datarate_max( CPhidgetSpatialHandle phid, obj_t o ) { FIELD_GET( phid, DataRateMax, CPhidgetSpatial, int, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_servo_get_motor_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_servo_get_motor_count( CPhidgetServoHandle phid , obj_t o ) { FIELD_GET( phid, MotorCount, CPhidgetServo, int, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_servo_get_position ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_servo_get_position( CPhidgetServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Position, CPhidgetServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_servo_get_position_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_servo_get_position_max( CPhidgetServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, PositionMax, CPhidgetServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_servo_get_position_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_servo_get_position_min( CPhidgetServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, PositionMin, CPhidgetServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_servo_get_engaged ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_servo_get_engaged( CPhidgetServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Engaged, CPhidgetServo, int, i, o ); } /*---------------------------------------------------------------------*/ /* CPhidget_ServoType */ /* bgl_phidget_servo_get_servo_type ... */ /*---------------------------------------------------------------------*/ CPhidget_ServoType bgl_phidget_servo_get_servo_type( CPhidgetServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, ServoType, CPhidgetServo, CPhidget_ServoType, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_advanced_servo_get_motor_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_advanced_servo_get_motor_count( CPhidgetAdvancedServoHandle phid, obj_t o ) { FIELD_GET( phid, MotorCount, CPhidgetAdvancedServo, int, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_acceleration ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_acceleration( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Acceleration, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_acceleration_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_acceleration_max( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, AccelerationMax, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_acceleration_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_acceleration_min( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, AccelerationMin, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_velocity_limit ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_velocity_limit( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, VelocityLimit, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_velocity ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_velocity( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Velocity, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_velocity_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_velocity_max( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, VelocityMax, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_velocity_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_velocity_min( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, VelocityMin, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_position ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_position( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Position, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_position_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_position_max( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, PositionMax, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_position_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_position_min( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, PositionMin, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_advanced_servo_get_current ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_advanced_servo_get_current( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Current, CPhidgetAdvancedServo, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_advanced_servo_get_engaged ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_advanced_servo_get_engaged( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Engaged, CPhidgetAdvancedServo, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_advanced_servo_get_stopped ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_advanced_servo_get_stopped( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Stopped, CPhidgetAdvancedServo, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_advanced_servo_get_speed_ramping_on ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_advanced_servo_get_speed_ramping_on( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, SpeedRampingOn, CPhidgetAdvancedServo, int, i, o ); } /*---------------------------------------------------------------------*/ /* CPhidget_ServoType */ /* bgl_phidget_advanced_servo_get_servo_type ... */ /*---------------------------------------------------------------------*/ CPhidget_ServoType bgl_phidget_advanced_servo_get_servo_type( CPhidgetAdvancedServoHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, ServoType, CPhidgetAdvancedServo, CPhidget_ServoType, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_stepper_get_input_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_stepper_get_input_count( CPhidgetStepperHandle phid, obj_t o ) { FIELD_GET( phid, InputCount, CPhidgetStepper, int, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_stepper_get_input_state ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_stepper_get_input_state( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, InputState, CPhidgetStepper, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_stepper_get_motor_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_stepper_get_motor_count( CPhidgetStepperHandle phid, obj_t o ) { FIELD_GET( phid, MotorCount, CPhidgetStepper, int, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_acceleration ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_acceleration( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Acceleration, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_acceleration_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_acceleration_max( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, AccelerationMax, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_acceleration_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_acceleration_min( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, AccelerationMin, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_velocity_limit ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_velocity_limit( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, VelocityLimit, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_velocity ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_velocity( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Velocity, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_velocity_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_velocity_max( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, VelocityMax, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_velocity_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_velocity_min( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, VelocityMin, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* BGL_LONGLONG_T */ /* bgl_phidget_stepper_get_target_position ... */ /*---------------------------------------------------------------------*/ BGL_LONGLONG_T bgl_phidget_stepper_get_target_position( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, TargetPosition, CPhidgetStepper, BGL_LONGLONG_T, i, o ); } /*---------------------------------------------------------------------*/ /* BGL_LONGLONG_T */ /* bgl_phidget_stepper_get_current_position ... */ /*---------------------------------------------------------------------*/ BGL_LONGLONG_T bgl_phidget_stepper_get_current_position( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, CurrentPosition, CPhidgetStepper, BGL_LONGLONG_T, i, o ); } /*---------------------------------------------------------------------*/ /* BGL_LONGLONG_T */ /* bgl_phidget_stepper_get_position_max ... */ /*---------------------------------------------------------------------*/ BGL_LONGLONG_T bgl_phidget_stepper_get_position_max( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, PositionMax, CPhidgetStepper, BGL_LONGLONG_T, i, o ); } /*---------------------------------------------------------------------*/ /* BGL_LONGLONG_T */ /* bgl_phidget_stepper_get_position_min ... */ /*---------------------------------------------------------------------*/ BGL_LONGLONG_T bgl_phidget_stepper_get_position_min( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, PositionMin, CPhidgetStepper, BGL_LONGLONG_T, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_current_limit ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_current_limit( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, CurrentLimit, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_current ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_current( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Current, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_current_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_current_max( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, CurrentMax, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* double */ /* bgl_phidget_stepper_get_current_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_stepper_get_current_min( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, CurrentMin, CPhidgetStepper, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_stepper_get_engaged ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_stepper_get_engaged( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Engaged, CPhidgetStepper, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_stepper_get_stopped ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_stepper_get_stopped( CPhidgetStepperHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Stopped, CPhidgetStepper, int, i, o ); } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_motor_controlvelocity_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_motor_controlvelocity_handler( CPhidgetMotorControlHandle id, void *ptr, int index, double velocity ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servovelocity.index = index; callbacks[ callback_index ].event.servovelocity.velocity = velocity; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_motor_controlcurrent_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_motor_controlcurrent_handler( CPhidgetMotorControlHandle id, void *ptr, int index, double current ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.servocurrent.index = index; callbacks[ callback_index ].event.servocurrent.current = current; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_motor_control_add_event_listener( CPhidgetMotorControlHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "velocity" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_MOTORCONTROLVELOCITY ); return CPhidgetMotorControl_set_OnVelocityChange_Handler( id, &bgl_motor_controlvelocity_handler, hdl ); } if( !strcmp( event, "current" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_MOTORCONTROLCURRENT ); return CPhidgetMotorControl_set_OnCurrentChange_Handler( id, &bgl_motor_controlcurrent_handler, hdl ); } else { return bgl_phidget_phidget_add_event_listener( (CPhidgetHandle)id, event, obj, proc ); } } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_motor_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_motor_control_get_motor_count( CPhidgetMotorControlHandle phid, obj_t o ) { int err, count; err = CPhidgetMotorControl_getMotorCount( phid, &count ); return err == EPHIDGET_OK ? count : (bgl_phidget_error( "MotorCount", err, o ), count); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_encoder_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_motor_control_get_encoder_count( CPhidgetMotorControlHandle phid, obj_t o ) { int err, count; err = CPhidgetMotorControl_getEncoderCount( phid, &count ); return err == EPHIDGET_OK ? count : (bgl_phidget_error( "EncoderCount", err, o ), count); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_acceleration ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_motor_control_get_acceleration( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Acceleration, CPhidgetMotorControl, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_velocity ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_motor_control_get_velocity( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Velocity, CPhidgetMotorControl, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_acceleration_min ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_motor_control_get_acceleration_min( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, AccelerationMin, CPhidgetMotorControl, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_acceleration_max ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_motor_control_get_acceleration_max( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, AccelerationMax, CPhidgetMotorControl, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_encoder_position ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_motor_control_get_encoder_position( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, EncoderPosition, CPhidgetMotorControl, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_braking ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_motor_control_get_braking( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Braking, CPhidgetMotorControl, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_set_braking ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_motor_control_set_braking( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Braking, CPhidgetMotorControl, double, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_motor_control_get_current ... */ /*---------------------------------------------------------------------*/ double bgl_phidget_motor_control_get_current( CPhidgetMotorControlHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Current, CPhidgetMotorControl, double, i, o ); } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_encoderinput_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_encoderinput_handler( CPhidgetEncoderHandle id, void *ptr, int index, int state ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.encoderinput.index = index; callbacks[ callback_index ].event.encoderinput.state = state; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_encoderposition_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_encoderposition_handler( CPhidgetEncoderHandle id, void *ptr, int index, int time, int pos ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.encoderposition.index = index; callbacks[ callback_index ].event.encoderposition.time = time; callbacks[ callback_index ].event.encoderposition.position = pos; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* static int */ /* bgl_encoderindex_handler ... */ /*---------------------------------------------------------------------*/ static int bgl_encoderindex_handler( CPhidgetEncoderHandle id, void *ptr, int index, int position ) { bgl_phidget_lock(); if( callback_index == callback_length ) enlarge_callback_array(); callbacks[ callback_index ].event.encoderindex.index = index; callbacks[ callback_index ].event.encoderindex.position = position; callbacks[ callback_index++ ].handler = (struct handler *)ptr; bgl_phidget_signal(); bgl_phidget_unlock(); return 0; } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_add_event_listener ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_encoder_add_event_listener( CPhidgetEncoderHandle id, char *event, obj_t obj, obj_t proc ) { if( !strcmp( event, "input" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_ENCODERINPUT ); return CPhidgetEncoder_set_OnInputChange_Handler( id, &bgl_encoderinput_handler, hdl ); } else if( !strcmp( event, "position" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_ENCODERPOSITION ); return CPhidgetEncoder_set_OnPositionChange_Handler( id, &bgl_encoderposition_handler, hdl ); } else if( !strcmp( event, "index" ) ) { struct handler *hdl = bgl_add_handler( obj, proc, EVENT_ENCODERINDEX ); return CPhidgetEncoder_set_OnIndex_Handler( id, &bgl_encoderindex_handler, hdl ); } return -1; } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_get_input_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_encoder_get_input_count( CPhidgetEncoderHandle phid, obj_t o ) { int err, count; err = CPhidgetEncoder_getInputCount( phid, &count); return err == EPHIDGET_OK ? count : (bgl_phidget_error( "EncoderCount", err, o ), count); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_get_encoder_count ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_encoder_get_encoder_count( CPhidgetEncoderHandle phid, obj_t o ) { int err, count; err = CPhidgetEncoder_getEncoderCount( phid, &count); return err == EPHIDGET_OK ? count : (bgl_phidget_error( "EncoderCount", err, o ), count); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_get_input_enabled ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_encoder_get_input_enabled( CPhidgetEncoderHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, InputState, CPhidgetEncoder, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_get_position ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_encoder_get_position( CPhidgetEncoderHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Position, CPhidgetEncoder, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_get_index_position ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_encoder_get_index_position( CPhidgetEncoderHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, IndexPosition, CPhidgetEncoder, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_get_enabled ... */ /*---------------------------------------------------------------------*/ int bgl_phidget_encoder_get_enabled( CPhidgetEncoderHandle phid, int i, obj_t o ) { FIELD_INDEXED_GET( phid, Enabled, CPhidgetEncoder, int, i, o ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_enable ... */ /*---------------------------------------------------------------------*/ void bgl_phidget_encoder_enable( CPhidgetEncoderHandle phid, int i ) { CPhidgetEncoder_setEnabled( phid, i, PTRUE ); } /*---------------------------------------------------------------------*/ /* int */ /* bgl_phidget_encoder_disable ... */ /*---------------------------------------------------------------------*/ void bgl_phidget_encoder_disable( CPhidgetEncoderHandle phid, int i ) { CPhidgetEncoder_setEnabled( phid, i, PFALSE ); }
0
0.884629
1
0.884629
game-dev
MEDIA
0.188058
game-dev
0.807788
1
0.807788
Octal450/MD-11
48,935
Nasal/Displays/EAD.nas
# McDonnell Douglas MD-11 EAD # Copyright (c) 2025 Josh Davidson (Octal450) var display = nil; var geDials = nil; var geTapes = nil; var pwDials = nil; var pwTapes = nil; var xx = nil; var Value = { barRest: 293, egtScale: 1000, engType: "GE", eprLimit: 0, Fadec: { activeMode: "T/O", auto: 0, egt: [0, 0, 0], epr: [0, 0, 0], eprLimit: 0, minN: 1.8, n1: [0, 0, 0], n1Limit: 0, n2: [0, 0, 0], powered: [0, 0, 0], rating: "62K", revState: [0, 0, 0], }, Ignition: { starter: [0, 0, 0], }, Misc: { annunTestWow: 0, checklist: 0, checklistItems: ["", "LANDING GEAR", "STAB TRIM", "SLAT", "FLAP", "BRAKES", "SPOILERS"], wow: 0, }, n1Limit: 0, needleRest: -44 * D2R, tat: 0, }; var canvasBase = { init: func(canvasGroup, file) { var font_mapper = func(family, weight) { return "MD11DU.ttf"; }; canvas.parsesvg(canvasGroup, file, {"font-mapper": font_mapper}); var svgKeys = me.getKeys(); foreach(var key; svgKeys) { me[key] = canvasGroup.getElementById(key); var clip_el = canvasGroup.getElementById(key ~ "_clip"); if (clip_el != nil) { clip_el.setVisible(0); var tranRect = clip_el.getTransformedBounds(); var clip_rect = sprintf("rect(%d, %d, %d, %d)", tranRect[1], # 0 ys tranRect[2], # 1 xe tranRect[3], # 2 ye tranRect[0] # 3 xs ); # Coordinates are top, right, bottom, left (ys, xe, ye, xs) ref: l621 of simgear/canvas/CanvasElement.cxx me[key].set("clip", clip_rect); me[key].set("clip-frame", canvas.Element.PARENT); } } me.page = canvasGroup; return me; }, getKeys: func() { return []; }, setup: func() { # Hide the pages by default geDials.page.hide(); geDials.setup(); geTapes.page.hide(); geTapes.setup(); pwDials.page.hide(); pwDials.setup(); pwTapes.page.hide(); pwTapes.setup(); xx.page.hide(); Value.engType = pts.Options.eng.getValue(); }, update: func() { if (systems.DUController.updateEad) { if (systems.DUController.eadType == "PW-Tapes") { pwTapes.update(); } else if (systems.DUController.eadType == "GE-Tapes") { geTapes.update(); } else if (systems.DUController.eadType == "PW-Dials") { pwDials.update(); } else { geDials.update(); } } }, updateBase: func() { if (Value.engType == "PW") { Value.Fadec.minN = 6.3; } else { Value.Fadec.minN = 1.8; } Value.Ignition.starter[0] = systems.IGNITION.starter1.getBoolValue(); Value.Ignition.starter[1] = systems.IGNITION.starter2.getBoolValue(); Value.Ignition.starter[2] = systems.IGNITION.starter3.getBoolValue(); if (systems.DUController.eadType == "GE-Tapes" or systems.DUController.eadType == "PW-Tapes") { me.updateBaseTapes(); } else { me.updateBaseDials(); } # FF me["FF1"].setText(sprintf("%d", math.round(systems.ENGINES.ff[0].getValue(), 10))); me["FF2"].setText(sprintf("%d", math.round(systems.ENGINES.ff[1].getValue(), 10))); me["FF3"].setText(sprintf("%d", math.round(systems.ENGINES.ff[2].getValue(), 10))); if (systems.ENGINES.Controls.cutoff[0].getBoolValue()) { me["FF1"].hide(); me["FFOff1"].show(); } else { me["FFOff1"].hide(); me["FF1"].show(); } if (systems.ENGINES.Controls.cutoff[1].getBoolValue()) { me["FF2"].hide(); me["FFOff2"].show(); } else { me["FFOff2"].hide(); me["FF2"].show(); } if (systems.ENGINES.Controls.cutoff[2].getBoolValue()) { me["FF3"].hide(); me["FFOff3"].show(); } else { me["FFOff3"].hide(); me["FF3"].show(); } # TAT Indication Value.tat = math.round(pts.Fdm.JSBSim.Propulsion.tatC.getValue()); if (Value.tat < 0) { me["TAT"].setText(sprintf("%2.0f", Value.tat) ~ "gC"); } else { me["TAT"].setText("+" ~ sprintf("%2.0f", Value.tat) ~ "gC"); } # Reversers if (Value.Fadec.revState[0] != 0 and Value.Fadec.powered[0]) { me["REV1"].show(); } else { me["REV1"].hide(); } if (Value.Fadec.revState[0] == 2) { me["REV1"].setText("REV"); if (!Value.Misc.wow) { me["REV1"].setColor(1, 0, 0); } else { me["REV1"].setColor(0, 1, 0); } } else { me["REV1"].setText("U/L"); if (!Value.Misc.wow) { me["REV1"].setColor(1, 0, 0); } else { me["REV1"].setColor(0.9412, 0.7255, 0); } } if (Value.Fadec.revState[1] != 0 and Value.Fadec.powered[1]) { me["REV2"].show(); } else { me["REV2"].hide(); } if (Value.Fadec.revState[1] == 2) { me["REV2"].setText("REV"); if (!Value.Misc.wow) { me["REV2"].setColor(1, 0, 0); } else { me["REV2"].setColor(0, 1, 0); } } else { me["REV2"].setText("U/L"); if (!Value.Misc.wow) { me["REV2"].setColor(1, 0, 0); } else { me["REV2"].setColor(0.9412, 0.7255, 0); } } if (Value.Fadec.revState[2] != 0 and Value.Fadec.powered[2]) { me["REV3"].show(); } else { me["REV3"].hide(); } if (Value.Fadec.revState[2] == 2) { me["REV3"].setText("REV"); if (!Value.Misc.wow) { me["REV3"].setColor(1, 0, 0); } else { me["REV3"].setColor(0, 1, 0); } } else { me["REV3"].setText("U/L"); if (!Value.Misc.wow) { me["REV3"].setColor(1, 0, 0); } else { me["REV3"].setColor(0.9412, 0.7255, 0); } } # Checklist Value.Misc.checklist = pts.Instrumentation.Ead.checklist.getValue(); if (Value.Misc.checklist == -1) { me["Checklist"].hide(); me["Checklist_box"].hide(); } else if (Value.Misc.checklist == 0) { me["Checklist"].hide(); me["Checklist_box"].setColor(0, 1, 0); me["Checklist_box"].show(); } else { if (pts.Instrumentation.Ead.checklistRed.getBoolValue()) { me["Checklist"].setColor(1, 0, 0); me["Checklist_box"].setColor(1, 0, 0); } else { me["Checklist"].setColor(1, 1, 1); me["Checklist_box"].setColor(1, 1, 1); } me["Checklist"].setText(Value.Misc.checklistItems[Value.Misc.checklist]); me["Checklist"].show(); me["Checklist_box"].show(); } }, updateBaseDials: func() { # EGT if (Value.Fadec.powered[0]) { me["EGT1"].setText(sprintf("%d", math.round(systems.ENGINES.egt[0].getValue()))); me["EGT1_needle"].setRotation(pts.Instrumentation.Ead.egt[0].getValue() * D2R); if (systems.IGNITION.ign1.getBoolValue()) { me["EGT1_ignition"].show(); } else { me["EGT1_ignition"].hide(); } if (Value.Ignition.starter[0] or systems.ENGINES.state[0].getValue() == 2) { me["EGT1_redstart"].show(); } else { me["EGT1_redstart"].hide(); } me["EGT1"].show(); me["EGT1_needle"].show(); } else { me["EGT1"].hide(); me["EGT1_ignition"].hide(); me["EGT1_needle"].hide(); me["EGT1_redstart"].hide(); } if (Value.Fadec.powered[1]) { me["EGT2"].setText(sprintf("%d", math.round(systems.ENGINES.egt[1].getValue()))); me["EGT2_needle"].setRotation(pts.Instrumentation.Ead.egt[1].getValue() * D2R); if (systems.IGNITION.ign2.getBoolValue()) { me["EGT2_ignition"].show(); } else { me["EGT2_ignition"].hide(); } if (Value.Ignition.starter[1] or systems.ENGINES.state[1].getValue() == 2) { me["EGT2_redstart"].show(); } else { me["EGT2_redstart"].hide(); } me["EGT2"].show(); me["EGT2_needle"].show(); } else { me["EGT2"].hide(); me["EGT2_ignition"].hide(); me["EGT2_needle"].hide(); me["EGT2_redstart"].hide(); } if (Value.Fadec.powered[2]) { me["EGT3"].setText(sprintf("%d", math.round(systems.ENGINES.egt[2].getValue()))); me["EGT3_needle"].setRotation(pts.Instrumentation.Ead.egt[2].getValue() * D2R); if (systems.IGNITION.ign3.getBoolValue()) { me["EGT3_ignition"].show(); } else { me["EGT3_ignition"].hide(); } if (Value.Ignition.starter[2] or systems.ENGINES.state[2].getValue() == 2) { me["EGT3_redstart"].show(); } else { me["EGT3_redstart"].hide(); } me["EGT3"].show(); me["EGT3_needle"].show(); } else { me["EGT3"].hide(); me["EGT3_ignition"].hide(); me["EGT3_needle"].hide(); me["EGT3_redstart"].hide(); } # N2 if (Value.Fadec.powered[0]) { Value.Fadec.n2[0] = systems.ENGINES.n2[0].getValue(); if (Value.Fadec.n2[0] < Value.Fadec.minN) { Value.Fadec.n2[0] = 0; me["N21_needle"].setRotation(Value.needleRest); } else { me["N21_needle"].setRotation(pts.Instrumentation.Ead.n2[0].getValue() * D2R); } me["N21"].setText(sprintf("%5.1f", math.round(Value.Fadec.n2[0], 0.1))); if (Value.Ignition.starter[0] and systems.IGNITION.cutoff1.getBoolValue()) { me["N21_cline"].show(); } else { me["N21_cline"].hide(); } me["N21"].show(); me["N21_needle"].show(); } else { me["N21"].hide(); me["N21_cline"].hide(); me["N21_needle"].hide(); } if (Value.Fadec.powered[1]) { Value.Fadec.n2[1] = systems.ENGINES.n2[1].getValue(); if (Value.Fadec.n2[1] < Value.Fadec.minN) { Value.Fadec.n2[1] = 0; me["N22_needle"].setRotation(Value.needleRest); } else { me["N22_needle"].setRotation(pts.Instrumentation.Ead.n2[1].getValue() * D2R); } me["N22"].setText(sprintf("%5.1f", math.round(Value.Fadec.n2[1], 0.1))); if (Value.Ignition.starter[1] and systems.IGNITION.cutoff2.getBoolValue()) { me["N22_cline"].show(); } else { me["N22_cline"].hide(); } me["N22"].show(); me["N22_needle"].show(); } else { me["N22"].hide(); me["N22_cline"].hide(); me["N22_needle"].hide(); } if (Value.Fadec.powered[2]) { Value.Fadec.n2[2] = systems.ENGINES.n2[2].getValue(); if (Value.Fadec.n2[2] < Value.Fadec.minN) { Value.Fadec.n2[2] = 0; me["N23_needle"].setRotation(Value.needleRest); } else { me["N23_needle"].setRotation(pts.Instrumentation.Ead.n2[2].getValue() * D2R); } me["N23"].setText(sprintf("%5.1f", math.round(Value.Fadec.n2[2], 0.1))); if (Value.Ignition.starter[2] and systems.IGNITION.cutoff3.getBoolValue()) { me["N23_cline"].show(); } else { me["N23_cline"].hide(); } me["N23"].show(); me["N23_needle"].show(); } else { me["N23"].hide(); me["N23_cline"].hide(); me["N23_needle"].hide(); } }, updateBaseTapes: func() { if (Value.engType == "PW") { Value.egtScale = 700; } else { Value.egtScale = 1000; } # EGT if (Value.Fadec.powered[0]) { Value.Fadec.egt[0] = systems.ENGINES.egt[0].getValue(); me["EGT1"].setText(sprintf("%d", math.round(Value.Fadec.egt[0]))); me["EGT1_bar"].setTranslation(0, Value.Fadec.egt[0] / Value.egtScale * -293); if (systems.IGNITION.ign1.getBoolValue()) { me["EGT1_ignition"].show(); } else { me["EGT1_ignition"].hide(); } if (Value.Ignition.starter[0] or systems.ENGINES.state[0].getValue() == 2) { me["EGT1_redstart"].show(); } else { me["EGT1_redstart"].hide(); } me["EGT1"].show(); me["EGT1_bar"].show(); } else { me["EGT1"].hide(); me["EGT1_bar"].hide(); me["EGT1_ignition"].hide(); me["EGT1_redstart"].hide(); } if (Value.Fadec.powered[1]) { Value.Fadec.egt[1] = systems.ENGINES.egt[1].getValue(); me["EGT2"].setText(sprintf("%d", math.round(Value.Fadec.egt[1]))); me["EGT2_bar"].setTranslation(0, Value.Fadec.egt[1] / Value.egtScale * -293); if (systems.IGNITION.ign2.getBoolValue()) { me["EGT2_ignition"].show(); } else { me["EGT2_ignition"].hide(); } if (Value.Ignition.starter[1] or systems.ENGINES.state[1].getValue() == 2) { me["EGT2_redstart"].show(); } else { me["EGT2_redstart"].hide(); } me["EGT2"].show(); me["EGT2_bar"].show(); } else { me["EGT2"].hide(); me["EGT2_bar"].hide(); me["EGT2_ignition"].hide(); me["EGT2_redstart"].hide(); } if (Value.Fadec.powered[2]) { Value.Fadec.egt[2] = systems.ENGINES.egt[2].getValue(); me["EGT3"].setText(sprintf("%d", math.round(Value.Fadec.egt[2]))); me["EGT3_bar"].setTranslation(0, Value.Fadec.egt[2] / Value.egtScale * -293); if (systems.IGNITION.ign3.getBoolValue()) { me["EGT3_ignition"].show(); } else { me["EGT3_ignition"].hide(); } if (Value.Ignition.starter[2] or systems.ENGINES.state[2].getValue() == 2) { me["EGT3_redstart"].show(); } else { me["EGT3_redstart"].hide(); } me["EGT3"].show(); me["EGT3_bar"].show(); } else { me["EGT3"].hide(); me["EGT3_bar"].hide(); me["EGT3_ignition"].hide(); me["EGT3_redstart"].hide(); } # N2 if (Value.Fadec.powered[0]) { Value.Fadec.n2[0] = systems.ENGINES.n2[0].getValue(); if (Value.Fadec.n2[0] < Value.Fadec.minN) { Value.Fadec.n2[0] = 0; me["N21_bar"].setTranslation(0, Value.barRest); } else { me["N21_bar"].setTranslation(0, Value.Fadec.n2[0] / 120 * -209); } if (Value.Ignition.starter[0] and systems.IGNITION.cutoff1.getBoolValue()) { me["N21_cline"].show(); } else { me["N21_cline"].hide(); } me["N21"].setText(sprintf("%5.1f", math.round(Value.Fadec.n2[0], 0.1))); me["N21"].show(); me["N21_bar"].show(); } else { me["N21"].hide(); me["N21_bar"].hide(); me["N21_cline"].hide(); } if (Value.Fadec.powered[1]) { Value.Fadec.n2[1] = systems.ENGINES.n2[1].getValue(); if (Value.Fadec.n2[1] < Value.Fadec.minN) { Value.Fadec.n2[1] = 0; me["N22_bar"].setTranslation(0, Value.barRest); } else { me["N22_bar"].setTranslation(0, Value.Fadec.n2[1] / 120 * -209); } if (Value.Ignition.starter[1] and systems.IGNITION.cutoff2.getBoolValue()) { me["N22_cline"].show(); } else { me["N22_cline"].hide(); } me["N22"].setText(sprintf("%5.1f", math.round(Value.Fadec.n2[1], 0.1))); me["N22"].show(); me["N22_bar"].show(); } else { me["N22"].hide(); me["N22_bar"].hide(); me["N22_cline"].hide(); } if (Value.Fadec.powered[2]) { Value.Fadec.n2[2] = systems.ENGINES.n2[2].getValue(); if (Value.Fadec.n2[2] < Value.Fadec.minN) { Value.Fadec.n2[2] = 0; me["N23_bar"].setTranslation(0, Value.barRest); } else { me["N23_bar"].setTranslation(0, Value.Fadec.n2[2] / 120 * -209); } if (Value.Ignition.starter[2] and systems.IGNITION.cutoff3.getBoolValue()) { me["N23_cline"].show(); } else { me["N23_cline"].hide(); } me["N23"].setText(sprintf("%5.1f", math.round(Value.Fadec.n2[2], 0.1))); me["N23"].show(); me["N23_bar"].show(); } else { me["N23"].hide(); me["N23_bar"].hide(); me["N23_cline"].hide(); } }, }; var canvasGeDials = { new: func(canvasGroup, file) { var m = {parents: [canvasGeDials, canvasBase]}; m.init(canvasGroup, file); return m; }, getKeys: func() { return ["Alert_error", "Checklist", "Checklist_box", "Config", "EGT1", "EGT1_error", "EGT1_ignition", "EGT1_needle", "EGT1_redstart", "EGT2", "EGT2_error", "EGT2_ignition", "EGT2_needle", "EGT2_redstart", "EGT3", "EGT3_error", "EGT3_ignition", "EGT3_needle", "EGT3_redstart", "FF1", "FF1_error", "FF2", "FF2_error", "FF3", "FF3_error", "FFOff1", "FFOff2", "FFOff3", "N11_box", "N11_decimal", "N11_decpnt", "N11_error", "N11_hundreds", "N11_lim", "N11_needle", "N11_ones", "N11_tens", "N11_tens_zero", "N11_thr", "N12_box", "N12_decimal", "N12_decpnt", "N12_error", "N12_hundreds", "N12_lim", "N12_needle", "N12_ones", "N12_tens", "N12_tens_zero", "N12_thr", "N13_box", "N13_decimal", "N13_decpnt", "N13_error", "N13_hundreds", "N13_lim", "N13_needle", "N13_ones", "N13_tens", "N13_tens_zero", "N13_thr", "N1Lim", "N1Lim_error", "N1LimBox", "N1LimFlexBox", "N1LimMode", "N21", "N21_cline", "N21_error", "N21_needle", "N22", "N22_cline", "N22_error", "N22_needle", "N23", "N23_cline", "N23_error", "N23_needle", "REV1", "REV2", "REV3", "TAT", "TAT_error"]; }, setup: func() { # Hide unimplemented objects me["Config"].hide(); }, update: func() { # Provide the value to here and the base Value.Fadec.powered[0] = systems.FADEC.powered[0].getBoolValue(); Value.Fadec.powered[1] = systems.FADEC.powered[1].getBoolValue(); Value.Fadec.powered[2] = systems.FADEC.powered[2].getBoolValue(); Value.Fadec.revState[0] = systems.FADEC.revState[0].getValue(); Value.Fadec.revState[1] = systems.FADEC.revState[1].getValue(); Value.Fadec.revState[2] = systems.FADEC.revState[2].getValue(); Value.Misc.wow = pts.Position.wow.getBoolValue(); Value.Misc.annunTestWow = pts.Controls.Switches.annunTest.getBoolValue() and Value.Misc.wow; # Errors, these don't have separate logic yet. if (Value.Misc.annunTestWow) { me["Alert_error"].show(); me["EGT1_error"].show(); me["EGT2_error"].show(); me["EGT3_error"].show(); me["FF1_error"].show(); me["FF2_error"].show(); me["FF3_error"].show(); me["N11_error"].show(); me["N12_error"].show(); me["N13_error"].show(); me["N1Lim_error"].show(); me["N21_error"].show(); me["N22_error"].show(); me["N23_error"].show(); me["TAT_error"].show(); } else { me["Alert_error"].hide(); me["EGT1_error"].hide(); me["EGT2_error"].hide(); me["EGT3_error"].hide(); me["FF1_error"].hide(); me["FF2_error"].hide(); me["FF3_error"].hide(); me["N11_error"].hide(); me["N12_error"].hide(); me["N13_error"].hide(); me["N1Lim_error"].hide(); me["N21_error"].hide(); me["N22_error"].hide(); me["N23_error"].hide(); me["TAT_error"].hide(); } # N1 Limit Value.Fadec.activeMode = systems.FADEC.Limit.activeMode.getValue(); Value.Fadec.auto = systems.FADEC.Limit.auto.getBoolValue(); Value.Fadec.n1Limit = systems.FADEC.Limit.active.getValue(); if (Value.Fadec.activeMode == "T/O" and fms.flightData.flexActive) { me["N1LimBox"].hide(); me["N1LimMode"].setText("T/O FLEX ( " ~ sprintf("%d", fms.flightData.flexTemp) ~ "gC)"); if (!Value.Fadec.auto) { me["N1LimFlexBox"].show(); me["N1LimMode"].setColor(1, 1, 1); } else { me["N1LimFlexBox"].hide(); me["N1LimMode"].setColor(0.9608, 0, 0.7765); } } else { me["N1LimFlexBox"].hide(); me["N1LimMode"].setText(Value.Fadec.activeMode ~ " LIM"); if (!Value.Fadec.auto) { me["N1LimBox"].show(); me["N1LimMode"].setColor(1, 1, 1); } else { me["N1LimBox"].hide(); me["N1LimMode"].setColor(0.9608, 0, 0.7765); } } me["N1Lim"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1Limit, 0.1))); Value.n1Limit = pts.Instrumentation.Ead.n1Limit.getValue(); me["N11_lim"].setRotation(Value.n1Limit * D2R); me["N12_lim"].setRotation(Value.n1Limit * D2R); me["N13_lim"].setRotation(Value.n1Limit * D2R); # N1 if (Value.Fadec.powered[0]) { Value.Fadec.n1[0] = systems.ENGINES.n1[0].getValue(); if (Value.Fadec.n1[0] < Value.Fadec.minN) { Value.Fadec.n1[0] = 0; me["N11_needle"].setRotation(Value.needleRest); } else { me["N11_needle"].setRotation(pts.Instrumentation.Ead.n1[0].getValue() * D2R); } if (Value.Fadec.n1[0] < 99) { # Prepare to show the zero at 100 me["N11_tens_zero"].hide(); } else { me["N11_tens_zero"].show(); } me["N11_hundreds"].setTranslation(0, genevaN1Hundreds(num(right(sprintf("%07.3f", Value.Fadec.n1[0]), 7))) * 34); me["N11_tens"].setTranslation(0, genevaN1Tens(num(right(sprintf("%06.3f", Value.Fadec.n1[0]), 6))) * 34); me["N11_ones"].setTranslation(0, genevaN1Ones(num(right(sprintf("%05.3f", Value.Fadec.n1[0]), 5))) * 34); me["N11_decimal"].setTranslation(0, (10 * math.round(math.mod(Value.Fadec.n1[0], 1), 0.001) * 34)); me["N11_thr"].setRotation(pts.Instrumentation.Ead.n1Thr[0].getValue() * D2R); me["N11_box"].show(); me["N11_decimal"].show(); me["N11_decpnt"].show(); me["N11_hundreds"].show(); me["N11_needle"].show(); me["N11_ones"].show(); me["N11_tens"].show(); me["N11_thr"].show(); } else { me["N11_box"].hide(); me["N11_decimal"].hide(); me["N11_decpnt"].hide(); me["N11_hundreds"].hide(); me["N11_needle"].hide(); me["N11_ones"].hide(); me["N11_tens"].hide(); me["N11_thr"].hide(); } if (Value.Fadec.powered[1]) { Value.Fadec.n1[1] = systems.ENGINES.n1[1].getValue(); if (Value.Fadec.n1[1] < Value.Fadec.minN) { Value.Fadec.n1[1] = 0; me["N12_needle"].setRotation(Value.needleRest); } else { me["N12_needle"].setRotation(pts.Instrumentation.Ead.n1[1].getValue() * D2R); } if (Value.Fadec.n1[1] < 99) { # Prepare to show the zero at 100 me["N12_tens_zero"].hide(); } else { me["N12_tens_zero"].show(); } me["N12_hundreds"].setTranslation(0, genevaN1Hundreds(num(right(sprintf("%07.3f", Value.Fadec.n1[1]), 7))) * 34); me["N12_tens"].setTranslation(0, genevaN1Tens(num(right(sprintf("%06.3f", Value.Fadec.n1[1]), 6))) * 34); me["N12_ones"].setTranslation(0, genevaN1Ones(num(right(sprintf("%05.3f", Value.Fadec.n1[1]), 5))) * 34); me["N12_decimal"].setTranslation(0, (10 * math.round(math.mod(Value.Fadec.n1[1], 1), 0.001) * 34)); me["N12_thr"].setRotation(pts.Instrumentation.Ead.n1Thr[1].getValue() * D2R); me["N12_box"].show(); me["N12_decimal"].show(); me["N12_decpnt"].show(); me["N12_hundreds"].show(); me["N12_needle"].show(); me["N12_ones"].show(); me["N12_tens"].show(); me["N12_thr"].show(); } else { me["N12_box"].hide(); me["N12_decimal"].hide(); me["N12_decpnt"].hide(); me["N12_hundreds"].hide(); me["N12_needle"].hide(); me["N12_ones"].hide(); me["N12_tens"].hide(); me["N12_thr"].hide(); } if (Value.Fadec.powered[2]) { Value.Fadec.n1[2] = systems.ENGINES.n1[2].getValue(); if (Value.Fadec.n1[2] < Value.Fadec.minN) { Value.Fadec.n1[2] = 0; me["N13_needle"].setRotation(Value.needleRest); } else { me["N13_needle"].setRotation(pts.Instrumentation.Ead.n1[2].getValue() * D2R); } if (Value.Fadec.n1[2] < 99) { # Prepare to show the zero at 100 me["N13_tens_zero"].hide(); } else { me["N13_tens_zero"].show(); } me["N13_hundreds"].setTranslation(0, genevaN1Hundreds(num(right(sprintf("%07.3f", Value.Fadec.n1[2]), 7))) * 34); me["N13_tens"].setTranslation(0, genevaN1Tens(num(right(sprintf("%06.3f", Value.Fadec.n1[2]), 6))) * 34); me["N13_ones"].setTranslation(0, genevaN1Ones(num(right(sprintf("%05.3f", Value.Fadec.n1[2]), 5))) * 34); me["N13_decimal"].setTranslation(0, (10 * math.round(math.mod(Value.Fadec.n1[2], 1), 0.001) * 34)); me["N13_thr"].setRotation(pts.Instrumentation.Ead.n1Thr[2].getValue() * D2R); me["N13_box"].show(); me["N13_decimal"].show(); me["N13_decpnt"].show(); me["N13_hundreds"].show(); me["N13_needle"].show(); me["N13_ones"].show(); me["N13_tens"].show(); me["N13_thr"].show(); } else { me["N13_box"].hide(); me["N13_decimal"].hide(); me["N13_decpnt"].hide(); me["N13_hundreds"].hide(); me["N13_needle"].hide(); me["N13_ones"].hide(); me["N13_tens"].hide(); me["N13_thr"].hide(); } me.updateBase(); }, }; var canvasGeTapes = { new: func(canvasGroup, file) { var m = {parents: [canvasGeTapes, canvasBase]}; m.init(canvasGroup, file); return m; }, getKeys: func() { return ["Alert_error", "Checklist", "Checklist_box", "Config", "EGT_bars", "EGT1", "EGT1_bar", "EGT1_error", "EGT1_ignition", "EGT1_redstart", "EGT2", "EGT2_bar", "EGT2_error", "EGT2_ignition", "EGT2_redstart", "EGT3", "EGT3_bar", "EGT3_error", "EGT3_ignition", "EGT3_redstart", "FF1", "FF1_error", "FF2", "FF2_error", "FF3", "FF3_error", "FFOff1", "FFOff2", "FFOff3", "N1_bars", "N11", "N11_bar", "N11_error", "N11_lim", "N11_thr", "N12", "N12_bar", "N12_error", "N12_lim", "N12_thr", "N13", "N13_bar", "N13_error", "N13_lim", "N13_thr", "N1Lim", "N1Lim_error", "N1LimBox", "N1LimFlexBox", "N1LimMode", "N2_bars", "N21", "N21_bar", "N21_cline", "N21_error", "N22", "N22_bar", "N22_cline", "N22_error", "N23", "N23_bar", "N23_cline", "N23_error", "REV1", "REV2", "REV3", "TAT", "TAT_error"]; }, setup: func() { # Hide unimplemented objects me["Config"].hide(); }, update: func() { # Provide the value to here and the base Value.Fadec.powered[0] = systems.FADEC.powered[0].getBoolValue(); Value.Fadec.powered[1] = systems.FADEC.powered[1].getBoolValue(); Value.Fadec.powered[2] = systems.FADEC.powered[2].getBoolValue(); Value.Fadec.revState[0] = systems.FADEC.revState[0].getValue(); Value.Fadec.revState[1] = systems.FADEC.revState[1].getValue(); Value.Fadec.revState[2] = systems.FADEC.revState[2].getValue(); Value.Misc.wow = pts.Position.wow.getBoolValue(); Value.Misc.annunTestWow = pts.Controls.Switches.annunTest.getBoolValue() and Value.Misc.wow; # Errors, these don't have separate logic yet. if (Value.Misc.annunTestWow) { me["Alert_error"].show(); me["EGT1_error"].show(); me["EGT2_error"].show(); me["EGT3_error"].show(); me["FF1_error"].show(); me["FF2_error"].show(); me["FF3_error"].show(); me["N11_error"].show(); me["N12_error"].show(); me["N13_error"].show(); me["N1Lim_error"].show(); me["N21_error"].show(); me["N22_error"].show(); me["N23_error"].show(); me["TAT_error"].show(); } else { me["Alert_error"].hide(); me["EGT1_error"].hide(); me["EGT2_error"].hide(); me["EGT3_error"].hide(); me["FF1_error"].hide(); me["FF2_error"].hide(); me["FF3_error"].hide(); me["N11_error"].hide(); me["N12_error"].hide(); me["N13_error"].hide(); me["N1Lim_error"].hide(); me["N21_error"].hide(); me["N22_error"].hide(); me["N23_error"].hide(); me["TAT_error"].hide(); } # N1 Limit Value.Fadec.activeMode = systems.FADEC.Limit.activeMode.getValue(); Value.Fadec.auto = systems.FADEC.Limit.auto.getBoolValue(); Value.Fadec.n1Limit = systems.FADEC.Limit.active.getValue(); if (Value.Fadec.activeMode == "T/O" and fms.flightData.flexActive) { me["N1LimBox"].hide(); me["N1LimMode"].setText("T/O FLEX ( " ~ sprintf("%d", fms.flightData.flexTemp) ~ "gC)"); if (!Value.Fadec.auto) { me["N1LimFlexBox"].show(); me["N1LimMode"].setColor(1, 1, 1); } else { me["N1LimFlexBox"].hide(); me["N1LimMode"].setColor(0.9608, 0, 0.7765); } } else { me["N1LimFlexBox"].hide(); me["N1LimMode"].setText(Value.Fadec.activeMode ~ " LIM"); if (!Value.Fadec.auto) { me["N1LimBox"].show(); me["N1LimMode"].setColor(1, 1, 1); } else { me["N1LimBox"].hide(); me["N1LimMode"].setColor(0.9608, 0, 0.7765); } } me["N1Lim"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1Limit, 0.1))); me["N11_lim"].setTranslation(0, Value.Fadec.n1Limit / 120 * -293); me["N12_lim"].setTranslation(0, Value.Fadec.n1Limit / 120 * -293); me["N13_lim"].setTranslation(0, Value.Fadec.n1Limit / 120 * -293); # N1 if (Value.Fadec.powered[0]) { Value.Fadec.n1[0] = systems.ENGINES.n1[0].getValue(); if (Value.Fadec.n1[0] < Value.Fadec.minN) { Value.Fadec.n1[0] = 0; me["N11_bar"].setTranslation(0, Value.barRest); } else { me["N11_bar"].setTranslation(0, Value.Fadec.n1[0] / 120 * -293); } me["N11_thr"].setTranslation(0, systems.FADEC.throttleN1[0].getValue() / 120 * -293); if (Value.Fadec.revState[0] != 0) { me["N11"].hide(); } else { me["N11"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[0], 0.1))); me["N11"].show(); } me["N11_bar"].show(); me["N11_thr"].show(); } else { me["N11"].hide(); me["N11_bar"].hide(); me["N11_thr"].hide(); } if (Value.Fadec.powered[1]) { Value.Fadec.n1[1] = systems.ENGINES.n1[1].getValue(); if (Value.Fadec.n1[1] < Value.Fadec.minN) { Value.Fadec.n1[1] = 0; me["N12_bar"].setTranslation(0, Value.barRest); } else { me["N12_bar"].setTranslation(0, Value.Fadec.n1[1] / 120 * -293); } me["N12_thr"].setTranslation(0, systems.FADEC.throttleN1[1].getValue() / 120 * -293); if (Value.Fadec.revState[1] != 0) { me["N12"].hide(); } else { me["N12"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[1], 0.1))); me["N12"].show(); } me["N12_bar"].show(); me["N12_thr"].show(); } else { me["N12"].hide(); me["N12_bar"].hide(); me["N12_thr"].hide(); } if (Value.Fadec.powered[2]) { Value.Fadec.n1[2] = systems.ENGINES.n1[2].getValue(); if (Value.Fadec.n1[2] < Value.Fadec.minN) { Value.Fadec.n1[2] = 0; me["N13_bar"].setTranslation(0, Value.barRest); } else { me["N13_bar"].setTranslation(0, Value.Fadec.n1[2] / 120 * -293); } me["N13_thr"].setTranslation(0, systems.FADEC.throttleN1[2].getValue() / 120 * -293); if (Value.Fadec.revState[2] != 0) { me["N13"].hide(); } else { me["N13"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[2], 0.1))); me["N13"].show(); } me["N13_bar"].show(); me["N13_thr"].show(); } else { me["N13"].hide(); me["N13_bar"].hide(); me["N13_thr"].hide(); } me.updateBase(); }, }; var canvasPwDials = { new: func(canvasGroup, file) { var m = {parents: [canvasPwDials, canvasBase]}; m.init(canvasGroup, file); return m; }, getKeys: func() { return ["Alert_error", "Checklist", "Checklist_box", "Config", "EGT1", "EGT1_error", "EGT1_ignition", "EGT1_needle", "EGT1_redstart", "EGT2", "EGT2_error", "EGT2_ignition", "EGT2_needle", "EGT2_redstart", "EGT3", "EGT3_error", "EGT3_ignition", "EGT3_needle", "EGT3_redstart", "EGT_group", "EPR1_box", "EPR1_decpnt", "EPR1_error", "EPR1_hundreths", "EPR1_lim", "EPR1_needle", "EPR1_ones", "EPR1_tenths", "EPR1_thr", "EPR2_box", "EPR2_decpnt", "EPR2_error", "EPR2_hundreths", "EPR2_lim", "EPR2_needle", "EPR2_ones", "EPR2_tenths", "EPR2_thr", "EPR3_box", "EPR3_decpnt", "EPR3_error", "EPR3_hundreths", "EPR3_lim", "EPR3_needle", "EPR3_ones", "EPR3_tenths", "EPR3_thr", "EPRLim", "EPRLim_error", "EPRLimBox", "EPRLimFlexBox", "EPRLimMode", "EPRLimToBox", "FF1", "FF1_error", "FF2", "FF2_error", "FF3", "FF3_error", "FFOff1", "FFOff2", "FFOff3", "N11", "N11_error", "N11_needle", "N12", "N12_error", "N12_needle", "N13", "N13_error", "N13_needle", "N1_group", "N21", "N21_cline", "N21_error", "N21_needle", "N22", "N22_cline", "N22_error", "N22_needle", "N23", "N23_cline", "N23_error", "N23_needle", "REV1", "REV2", "REV3", "TAT", "TAT_error"]; }, setup: func() { # Hide unimplemented objects me["Config"].hide(); }, setDials: func() { if (pts.Systems.Acconfig.Options.n1BelowEpr.getBoolValue()) { me["EGT_group"].setTranslation(0, 153.127); me["N1_group"].setTranslation(0, -153.127); } else { me["EGT_group"].setTranslation(0, 0); me["N1_group"].setTranslation(0, 0); } }, update: func() { # Provide the value to here and the base Value.Fadec.powered[0] = systems.FADEC.powered[0].getBoolValue(); Value.Fadec.powered[1] = systems.FADEC.powered[1].getBoolValue(); Value.Fadec.powered[2] = systems.FADEC.powered[2].getBoolValue(); Value.Fadec.revState[0] = systems.FADEC.revState[0].getValue(); Value.Fadec.revState[1] = systems.FADEC.revState[1].getValue(); Value.Fadec.revState[2] = systems.FADEC.revState[2].getValue(); Value.Misc.wow = pts.Position.wow.getBoolValue(); Value.Misc.annunTestWow = pts.Controls.Switches.annunTest.getBoolValue() and Value.Misc.wow; # Errors, these don't have separate logic yet. if (Value.Misc.annunTestWow) { me["Alert_error"].show(); me["EGT1_error"].show(); me["EGT2_error"].show(); me["EGT3_error"].show(); me["EPR1_error"].show(); me["EPR2_error"].show(); me["EPR3_error"].show(); me["EPRLim_error"].show(); me["FF1_error"].show(); me["FF2_error"].show(); me["FF3_error"].show(); me["N11_error"].show(); me["N12_error"].show(); me["N13_error"].show(); me["N21_error"].show(); me["N22_error"].show(); me["N23_error"].show(); me["TAT_error"].show(); } else { me["Alert_error"].hide(); me["EGT1_error"].hide(); me["EGT2_error"].hide(); me["EGT3_error"].hide(); me["EPR1_error"].hide(); me["EPR2_error"].hide(); me["EPR3_error"].hide(); me["EPRLim_error"].hide(); me["FF1_error"].hide(); me["FF2_error"].hide(); me["FF3_error"].hide(); me["N11_error"].hide(); me["N12_error"].hide(); me["N13_error"].hide(); me["N21_error"].hide(); me["N22_error"].hide(); me["N23_error"].hide(); me["TAT_error"].hide(); } # EPR Limit Value.Fadec.activeMode = systems.FADEC.Limit.activeMode.getValue(); Value.Fadec.auto = systems.FADEC.Limit.auto.getBoolValue(); Value.Fadec.eprLimit = systems.FADEC.Limit.active.getValue(); if (Value.Fadec.activeMode == "T/O" or Value.Fadec.activeMode == "G/A") { if (systems.FADEC.Limit.pwDerate.getBoolValue()) { Value.Fadec.rating = "60K"; } else { Value.Fadec.rating = "62K"; } if (Value.Fadec.activeMode == "T/O" and fms.flightData.flexActive) { me["EPRLimBox"].hide(); me["EPRLimToBox"].hide(); me["EPRLimMode"].setText(Value.Fadec.rating ~ " T/O FLEX ( " ~ sprintf("%d", fms.flightData.flexTemp) ~ "gC)"); if (!Value.Fadec.auto) { me["EPRLimFlexBox"].show(); me["EPRLimMode"].setColor(1, 1, 1); } else { me["EPRLimFlexBox"].hide(); me["EPRLimMode"].setColor(0.9608, 0, 0.7765); } } else { me["EPRLimBox"].hide(); me["EPRLimFlexBox"].hide(); me["EPRLimMode"].setText(Value.Fadec.rating ~ " " ~ Value.Fadec.activeMode ~ " LIM"); if (!Value.Fadec.auto) { me["EPRLimMode"].setColor(1, 1, 1); me["EPRLimToBox"].show(); } else { me["EPRLimMode"].setColor(0.9608, 0, 0.7765); me["EPRLimToBox"].hide(); } } } else { me["EPRLimFlexBox"].hide(); me["EPRLimToBox"].hide(); me["EPRLimMode"].setText(Value.Fadec.activeMode ~ " LIM"); if (!Value.Fadec.auto) { me["EPRLimBox"].show(); me["EPRLimMode"].setColor(1, 1, 1); } else { me["EPRLimBox"].hide(); me["EPRLimMode"].setColor(0.9608, 0, 0.7765); } } me["EPRLim"].setText(sprintf("%4.2f", math.round(Value.Fadec.eprLimit, 0.01))); Value.eprLimit = pts.Instrumentation.Ead.eprLimit.getValue(); me["EPR1_lim"].setRotation(Value.eprLimit * D2R); me["EPR2_lim"].setRotation(Value.eprLimit * D2R); me["EPR3_lim"].setRotation(Value.eprLimit * D2R); # EPR if (Value.Fadec.powered[0]) { Value.Fadec.epr[0] = systems.ENGINES.epr[0].getValue(); me["EPR1_ones"].setTranslation(0, genevaEprOnes(num(right(sprintf("%06.3f", Value.Fadec.epr[0] * 10), 6))) * 34); me["EPR1_tenths"].setTranslation(0, genevaEprTenths(num(right(sprintf("%05.3f", Value.Fadec.epr[0] * 10), 5))) * 34); me["EPR1_hundreths"].setTranslation(0, 10 * (math.round(math.mod(Value.Fadec.epr[0] * 10, 1), 0.0001) * 34)); me["EPR1_needle"].setRotation(pts.Instrumentation.Ead.epr[0].getValue() * D2R); if (!systems.FADEC.n1Mode[0].getValue()) { me["EPR1_thr"].setRotation(pts.Instrumentation.Ead.eprThr[0].getValue() * D2R); me["EPR1_thr"].show(); } else { me["EPR1_thr"].hide(); } me["EPR1_box"].show(); me["EPR1_decpnt"].show(); me["EPR1_hundreths"].show(); me["EPR1_needle"].show(); me["EPR1_ones"].show(); me["EPR1_tenths"].show(); } else { me["EPR1_box"].hide(); me["EPR1_decpnt"].hide(); me["EPR1_hundreths"].hide(); me["EPR1_needle"].hide(); me["EPR1_ones"].hide(); me["EPR1_tenths"].hide(); me["EPR1_thr"].hide(); } if (Value.Fadec.powered[1]) { Value.Fadec.epr[1] = systems.ENGINES.epr[1].getValue(); me["EPR2_ones"].setTranslation(0, genevaEprOnes(num(right(sprintf("%06.3f", Value.Fadec.epr[1] * 10), 6))) * 34); me["EPR2_tenths"].setTranslation(0, genevaEprTenths(num(right(sprintf("%05.3f", Value.Fadec.epr[1] * 10), 5))) * 34); me["EPR2_hundreths"].setTranslation(0, 10 * (math.round(math.mod(Value.Fadec.epr[1] * 10, 1), 0.0001) * 34)); me["EPR2_needle"].setRotation(pts.Instrumentation.Ead.epr[1].getValue() * D2R); if (!systems.FADEC.n1Mode[1].getValue()) { me["EPR2_thr"].setRotation(pts.Instrumentation.Ead.eprThr[1].getValue() * D2R); me["EPR2_thr"].show(); } else { me["EPR2_thr"].hide(); } me["EPR2_box"].show(); me["EPR2_decpnt"].show(); me["EPR2_hundreths"].show(); me["EPR2_needle"].show(); me["EPR2_ones"].show(); me["EPR2_tenths"].show(); } else { me["EPR2_box"].hide(); me["EPR2_decpnt"].hide(); me["EPR2_hundreths"].hide(); me["EPR2_needle"].hide(); me["EPR2_ones"].hide(); me["EPR2_tenths"].hide(); me["EPR2_thr"].hide(); } if (Value.Fadec.powered[2]) { Value.Fadec.epr[2] = systems.ENGINES.epr[2].getValue(); me["EPR3_ones"].setTranslation(0, genevaEprOnes(num(right(sprintf("%06.3f", Value.Fadec.epr[2] * 10), 6))) * 34); me["EPR3_tenths"].setTranslation(0, genevaEprTenths(num(right(sprintf("%05.3f", Value.Fadec.epr[2] * 10), 5))) * 34); me["EPR3_hundreths"].setTranslation(0, 10 * (math.round(math.mod(Value.Fadec.epr[2] * 10, 1), 0.0001) * 34)); me["EPR3_needle"].setRotation(pts.Instrumentation.Ead.epr[2].getValue() * D2R); if (!systems.FADEC.n1Mode[2].getValue()) { me["EPR3_thr"].setRotation(pts.Instrumentation.Ead.eprThr[2].getValue() * D2R); me["EPR3_thr"].show(); } else { me["EPR3_thr"].hide(); } me["EPR3_box"].show(); me["EPR3_decpnt"].show(); me["EPR3_hundreths"].show(); me["EPR3_needle"].show(); me["EPR3_ones"].show(); me["EPR3_tenths"].show(); } else { me["EPR3_box"].hide(); me["EPR3_decpnt"].hide(); me["EPR3_hundreths"].hide(); me["EPR3_needle"].hide(); me["EPR3_ones"].hide(); me["EPR3_tenths"].hide(); me["EPR3_thr"].hide(); } # N1 Value.Fadec.n1[0] = systems.ENGINES.n1[0].getValue(); Value.Fadec.n1[1] = systems.ENGINES.n1[1].getValue(); Value.Fadec.n1[2] = systems.ENGINES.n1[2].getValue(); if (Value.Fadec.powered[0] and Value.Fadec.n1[0] >= Value.Fadec.minN) { me["N11_needle"].setRotation(pts.Instrumentation.Ead.n1[0].getValue() * D2R); me["N11"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[0], 0.1))); me["N11"].show(); me["N11_needle"].show(); } else { me["N11"].hide(); me["N11_needle"].hide(); } if (Value.Fadec.powered[1] and Value.Fadec.n1[1] >= Value.Fadec.minN) { me["N12_needle"].setRotation(pts.Instrumentation.Ead.n1[1].getValue() * D2R); me["N12"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[1], 0.1))); me["N12"].show(); me["N12_needle"].show(); } else { me["N12"].hide(); me["N12_needle"].hide(); } if (Value.Fadec.powered[2] and Value.Fadec.n1[2] >= Value.Fadec.minN) { me["N13_needle"].setRotation(pts.Instrumentation.Ead.n1[2].getValue() * D2R); me["N13"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[2], 0.1))); me["N13"].show(); me["N13_needle"].show(); } else { me["N13"].hide(); me["N13_needle"].hide(); } me.updateBase(); }, }; var canvasPwTapes = { new: func(canvasGroup, file) { var m = {parents: [canvasPwTapes, canvasBase]}; m.init(canvasGroup, file); return m; }, getKeys: func() { return ["Alert_error", "Checklist", "Checklist_box", "Config", "EGT_bars", "EGT1", "EGT1_bar", "EGT1_error", "EGT1_ignition", "EGT1_redstart", "EGT2", "EGT2_bar", "EGT2_error", "EGT2_ignition", "EGT2_redstart", "EGT3", "EGT3_bar", "EGT3_error", "EGT3_ignition", "EGT3_redstart", "EPR_bars", "EPR1", "EPR1_bar", "EPR1_error", "EPR1_lim", "EPR1_thr", "EPR2", "EPR2_bar", "EPR2_error", "EPR2_lim", "EPR2_thr", "EPR3", "EPR3_bar", "EPR3_error", "EPR3_lim", "EPR3_thr", "EPRLim", "EPRLim_error", "EPRLimBox", "EPRLimFlexBox", "EPRLimMode", "EPRLimToBox", "FF1", "FF1_error", "FF2", "FF2_error", "FF3", "FF3_error", "FFOff1", "FFOff2", "FFOff3", "N11", "N11_error", "N12", "N12_error", "N13", "N13_error", "N2_bars", "N21", "N21_bar", "N21_cline", "N21_error", "N22", "N22_bar", "N22_cline", "N22_error", "N23", "N23_bar", "N23_cline", "N23_error", "REV1", "REV2", "REV3", "TAT", "TAT_error"]; }, setup: func() { # Hide unimplemented objects me["Config"].hide(); }, update: func() { # Provide the value to here and the base Value.Fadec.powered[0] = systems.FADEC.powered[0].getBoolValue(); Value.Fadec.powered[1] = systems.FADEC.powered[1].getBoolValue(); Value.Fadec.powered[2] = systems.FADEC.powered[2].getBoolValue(); Value.Fadec.revState[0] = systems.FADEC.revState[0].getValue(); Value.Fadec.revState[1] = systems.FADEC.revState[1].getValue(); Value.Fadec.revState[2] = systems.FADEC.revState[2].getValue(); Value.Misc.wow = pts.Position.wow.getBoolValue(); Value.Misc.annunTestWow = pts.Controls.Switches.annunTest.getBoolValue() and Value.Misc.wow; # Errors, these don't have separate logic yet. if (Value.Misc.annunTestWow) { me["Alert_error"].show(); me["EGT1_error"].show(); me["EGT2_error"].show(); me["EGT3_error"].show(); me["EPR1_error"].show(); me["EPR2_error"].show(); me["EPR3_error"].show(); me["EPRLim_error"].show(); me["FF1_error"].show(); me["FF2_error"].show(); me["FF3_error"].show(); me["N11_error"].show(); me["N12_error"].show(); me["N13_error"].show(); me["N21_error"].show(); me["N22_error"].show(); me["N23_error"].show(); me["TAT_error"].show(); } else { me["Alert_error"].hide(); me["EGT1_error"].hide(); me["EGT2_error"].hide(); me["EGT3_error"].hide(); me["EPR1_error"].hide(); me["EPR2_error"].hide(); me["EPR3_error"].hide(); me["EPRLim_error"].hide(); me["FF1_error"].hide(); me["FF2_error"].hide(); me["FF3_error"].hide(); me["N11_error"].hide(); me["N12_error"].hide(); me["N13_error"].hide(); me["N21_error"].hide(); me["N22_error"].hide(); me["N23_error"].hide(); me["TAT_error"].hide(); } # EPR Limit Value.Fadec.activeMode = systems.FADEC.Limit.activeMode.getValue(); Value.Fadec.auto = systems.FADEC.Limit.auto.getBoolValue(); Value.Fadec.eprLimit = systems.FADEC.Limit.active.getValue(); if (Value.Fadec.activeMode == "T/O" or Value.Fadec.activeMode == "G/A") { if (systems.FADEC.Limit.pwDerate.getBoolValue()) { Value.Fadec.rating = "60K"; } else { Value.Fadec.rating = "62K"; } if (Value.Fadec.activeMode == "T/O" and fms.flightData.flexActive) { me["EPRLimBox"].hide(); me["EPRLimToBox"].hide(); me["EPRLimMode"].setText(Value.Fadec.rating ~ " T/O FLEX ( " ~ sprintf("%d", fms.flightData.flexTemp) ~ "gC)"); if (!Value.Fadec.auto) { me["EPRLimFlexBox"].show(); me["EPRLimMode"].setColor(1, 1, 1); } else { me["EPRLimFlexBox"].hide(); me["EPRLimMode"].setColor(0.9608, 0, 0.7765); } } else { me["EPRLimBox"].hide(); me["EPRLimFlexBox"].hide(); me["EPRLimMode"].setText(Value.Fadec.rating ~ " " ~ Value.Fadec.activeMode ~ " LIM"); if (!Value.Fadec.auto) { me["EPRLimMode"].setColor(1, 1, 1); me["EPRLimToBox"].show(); } else { me["EPRLimMode"].setColor(0.9608, 0, 0.7765); me["EPRLimToBox"].hide(); } } } else { me["EPRLimFlexBox"].hide(); me["EPRLimToBox"].hide(); me["EPRLimMode"].setText(Value.Fadec.activeMode ~ " LIM"); if (!Value.Fadec.auto) { me["EPRLimBox"].show(); me["EPRLimMode"].setColor(1, 1, 1); } else { me["EPRLimBox"].hide(); me["EPRLimMode"].setColor(0.9608, 0, 0.7765); } } me["EPRLim"].setText(sprintf("%4.2f", math.round(Value.Fadec.eprLimit, 0.01))); me["EPR1_lim"].setTranslation(0, (Value.Fadec.eprLimit - 0.4) / 1.6 * -293); me["EPR2_lim"].setTranslation(0, (Value.Fadec.eprLimit - 0.4) / 1.6 * -293); me["EPR3_lim"].setTranslation(0, (Value.Fadec.eprLimit - 0.4) / 1.6 * -293); # EPR if (Value.Fadec.powered[0]) { Value.Fadec.epr[0] = systems.ENGINES.epr[0].getValue(); if (Value.Fadec.revState[0] != 0) { me["EPR1"].hide(); } else { me["EPR1"].setText(sprintf("%4.2f", math.round(Value.Fadec.epr[0], 0.01))); me["EPR1"].show(); } me["EPR1_bar"].setTranslation(0, (Value.Fadec.epr[0] - 0.4) / 1.6 * -293); if (!systems.FADEC.n1Mode[0].getValue()) { me["EPR1_thr"].setTranslation(0, (systems.FADEC.throttleEpr[0].getValue() - 0.4) / 1.6 * -293); me["EPR1_thr"].show(); } else { me["EPR1_thr"].hide(); } me["EPR1_bar"].show(); } else { me["EPR1"].hide(); me["EPR1_bar"].hide(); me["EPR1_thr"].hide(); } if (Value.Fadec.powered[1]) { Value.Fadec.epr[1] = systems.ENGINES.epr[1].getValue(); if (Value.Fadec.revState[1] != 0) { me["EPR2"].hide(); } else { me["EPR2"].setText(sprintf("%4.2f", math.round(Value.Fadec.epr[1], 0.01))); me["EPR2"].show(); } me["EPR2_bar"].setTranslation(0, (Value.Fadec.epr[1] - 0.4) / 1.6 * -293); if (!systems.FADEC.n1Mode[1].getValue()) { me["EPR2_thr"].setTranslation(0, (systems.FADEC.throttleEpr[1].getValue() - 0.4) / 1.6 * -293); me["EPR2_thr"].show(); } else { me["EPR2_thr"].hide(); } me["EPR2_bar"].show(); } else { me["EPR2"].hide(); me["EPR2_bar"].hide(); me["EPR2_thr"].hide(); } if (Value.Fadec.powered[2]) { Value.Fadec.epr[2] = systems.ENGINES.epr[2].getValue(); if (Value.Fadec.revState[2] != 0) { me["EPR3"].hide(); } else { me["EPR3"].setText(sprintf("%4.2f", math.round(Value.Fadec.epr[2], 0.01))); me["EPR3"].show(); } me["EPR3_bar"].setTranslation(0, (Value.Fadec.epr[2] - 0.4) / 1.6 * -293); if (!systems.FADEC.n1Mode[2].getValue()) { me["EPR3_thr"].setTranslation(0, (systems.FADEC.throttleEpr[2].getValue() - 0.4) / 1.6 * -293); me["EPR3_thr"].show(); } else { me["EPR3_thr"].hide(); } me["EPR3_bar"].show(); } else { me["EPR3"].hide(); me["EPR3_bar"].hide(); me["EPR3_thr"].hide(); } # N1 Value.Fadec.n1[0] = systems.ENGINES.n1[0].getValue(); Value.Fadec.n1[1] = systems.ENGINES.n1[1].getValue(); Value.Fadec.n1[2] = systems.ENGINES.n1[2].getValue(); if (Value.Fadec.powered[0] and Value.Fadec.n1[0] >= Value.Fadec.minN) { me["N11"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[0], 0.1))); me["N11"].show(); } else { me["N11"].hide(); } if (Value.Fadec.powered[1] and Value.Fadec.n1[1] >= Value.Fadec.minN) { me["N12"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[1], 0.1))); me["N12"].show(); } else { me["N12"].hide(); } if (Value.Fadec.powered[2] and Value.Fadec.n1[2] >= Value.Fadec.minN) { me["N13"].setText(sprintf("%5.1f", math.round(Value.Fadec.n1[2], 0.1))); me["N13"].show(); } else { me["N13"].hide(); } me.updateBase(); }, }; var canvasXx = { new: func(canvasGroup, file) { var m = {parents: [canvasXx]}; canvas.parsesvg(canvasGroup, file); m.page = canvasGroup; return m; }, }; var setup = func() { display = canvas.new({ "name": "EAD", "size": [1024, 1024], "view": [1024, 1024], "mipmapping": 1 }); display.addPlacement({"node": "ead.screen"}); var geDialsGroup = display.createGroup(); var geTapesGroup = display.createGroup(); var pwDialsGroup = display.createGroup(); var pwTapesGroup = display.createGroup(); var xxGroup = display.createGroup(); geDials = canvasGeDials.new(geDialsGroup, "Aircraft/MD-11/Nasal/Displays/res/EAD-GE-Dials.svg"); geTapes = canvasGeTapes.new(geTapesGroup, "Aircraft/MD-11/Nasal/Displays/res/EAD-GE-Tapes.svg"); pwDials = canvasPwDials.new(pwDialsGroup, "Aircraft/MD-11/Nasal/Displays/res/EAD-PW-Dials.svg"); pwTapes = canvasPwTapes.new(pwTapesGroup, "Aircraft/MD-11/Nasal/Displays/res/EAD-PW-Tapes.svg"); xx = canvasXx.new(xxGroup, "Aircraft/MD-11/Nasal/Displays/res/XX.svg"); canvasBase.setup(); update.start(); if (pts.Systems.Acconfig.Options.Du.eadFps.getValue() != 20) { rateApply(); } } var rateApply = func() { update.restart(1 / pts.Systems.Acconfig.Options.Du.eadFps.getValue()); } var update = maketimer(0.05, func() { # 20FPS canvasBase.update(); }); var showEad = func() { var dlg = canvas.Window.new([512, 512], "dialog", nil, 0).set("resize", 1); dlg.setCanvas(display); dlg.set("title", "Engine and Alert Display"); } var m = 0; var s = 0; var genevaN1Hundreds = func(input) { m = math.floor(input / 100); s = math.max(0, (math.mod(input, 1) - 0.9) * 10); if (math.mod(input / 10, 1) < 0.9 or math.mod(input / 100, 1) < 0.9) s = 0; return m + s; } var genevaN1Tens = func(input) { m = math.floor(input / 10); s = math.max(0, (math.mod(input, 1) - 0.9) * 10); if (math.mod(input / 10, 1) < 0.9) s = 0; return m + s; } var genevaN1Ones = func(input) { m = math.floor(input); s = math.max(0, (math.mod(input, 1) - 0.9) * 10); return m + s; } var genevaEprOnes = func(input) { m = math.floor(input / 10); s = math.max(0, (math.mod(input, 1) - 0.9) * 10); if (math.mod(input / 10, 1) < 0.9) s = 0; return m + s; } var genevaEprTenths = func(input) { m = math.floor(input); s = math.max(0, (math.mod(input, 1) - 0.9) * 10); return m + s; }
0
0.74783
1
0.74783
game-dev
MEDIA
0.636729
game-dev
0.855026
1
0.855026
deathlyrage/breakingpointmod
4,516
ModSource/breakingpoint_map_objects/data/particleeffects/scripts/destruction/airdestruction.sqf
_v=_this select 0; _int = (fuel _v)*(8+random 2); _t=time; _fl = "#particlesource" createVehicleLocal getpos _v; _fl attachto [_v,[0,0,0],"destructionEffect2"]; _fl setParticleRandom [0.3, [1, 1, 0], [0, 0, 0], 0, 0.3, [0, 0, 0, 0], 0, 0]; _fl setParticleParams [["\Ca\Data\ParticleEffects\Universal\Universal", 16, 10, 32], "", "Billboard", 1, 2, "destructionEffect2", [0, 0, 5], 0, 10, 7.9, 0.075, [4,7,9,10], [[1, 1, 1, -1], [1, 1, 1, -1], [1, 1, 1, -1], [1, 1, 1, -0.5], [1, 1, 1, -0]], [1,0.5], 1, 0, "", "", _v]; _fl setDropInterval 1; _sm = "#particlesource" createVehicleLocal getpos _v; _sm attachto [_v,[0,0,0],"destructionEffect1"]; _sm setParticleRandom [2, [2, 2, 0], [0, 0, 0], 0, 0.3, [0, 0, 0, 0.1], 0, 0]; _sm setParticleParams [["\Ca\Data\ParticleEffects\Universal\Universal", 16, 7, 48], "", "Billboard", 1, 5, "destructionEffect1", [0, 0, 5], 0, 10, 7.9, 0.075, [4,8,12,14], [[0.3, 0.3, 0.3, 1], [0.45, 0.45, 0.45, 1],[0.6, 0.6, 0.6, 0.6], [0.7, 0.7, 0.7, 0.25], [1, 1, 1, 0]], [0.8,0.3,0.25], 1, 0, "", "", _v]; _sm setDropInterval 1; _i=0; _dr=0.2; _tv=11; //Remove weapons/ammo to prevent explosion. Script will create its own explosions (doesnt work?) removeallweapons _v; if (local _v) then {_expl="HelicopterExploSmall" createvehicle (getpos _v);}; while {_i <1200 && ((velocity _v select 2)<-20 || (getpos _v select 2)>8) && !(alive _v) && !(isnull _v) && (getpos _v select 2)>1} do { _tv=abs(velocity _v select 0)+abs(velocity _v select 1)+abs(velocity _v select 2); if (_tv>2) then {_dr=1/_tv} else {_dr=1}; _fl setDropInterval _dr; _sm setDropInterval _dr; _i=_i+1; sleep 0.2; }; _pos=getpos _v; clearVehicleInit _v; deletevehicle _fl;deletevehicle _sm; if (surfaceiswater(_pos) && (_pos select 2)<9 ) then { _wave = "#particlesource" createVehicleLocal getpos _v; _wave attachto [_v,[0,0,0],"destructionEffect1"]; _wave setParticleRandom [0.3, [1, 1, 0], [0.5, 0.5, 0], 0, 0.3, [0, 0, 0, 0], 0, 0]; _wave setParticleParams [["\Ca\Data\ParticleEffects\Universal\Universal", 16, 12, 13,0], "", "Billboard", 1, 1.6, "destructionEffect1", [0, 0, 0], 0, 10, 7.9, 0.075, [3,8], [[0.7,0.8,1,0.6],[0.85,0.9,1,0.0]], [1000], 1, 0, "", "", _v]; _wave setparticlecircle [2,[0,16,0]]; _wave setDropInterval 0.0015; _splash = "#particlesource" createVehicleLocal getpos _v; _splash attachto [_v,[0,0,0],"destructionEffect1"]; _splash setParticleRandom [2, [2, 2, 0], [2, 2, 7], 0, 0.5, [0, 0, 0, 0], 0, 0]; _splash setParticleParams [["\Ca\Data\ParticleEffects\Universal\Universal", 16, 13, 6, 0], "", "Billboard", 1, 4, "destructionEffect1", [0, 0, 0], 0, 30, 7.9, 0.075, [8,15], [[0.7,0.7,0.7,1],[1,1,1,0]], [1000], 1, 0, "", "", _v]; _splash setparticlecircle [2,[0,3,15]]; _splash setDropInterval 0.002; sleep 0.2; deletevehicle _wave;deletevehicle _splash; /* if (local _v) then { _wreck=GetText (configFile >> "CfgVehicles" >> (typeof _v) >> "wreck"); if (_wreck!="") then { _pos = getpos _v; _dir = vectordir _v; _vecUp = vectorup _v; _vel = velocity _v; clearvehicleinit _v; _crw= crew _v; clearvehicleinit _v; deleteVehicle _v; _v =(_wreck) createvehicle _pos; {_x moveincargo _v} foreach _crw; _v setVectorDirAndUp [_dir,_vecUp]; _v setFuel 0; _v setdamage 0; _v setvelocity _vel; //Send to garbage collecter so wreck can be deleted later [_v] call BIS_GC_trashItFunc; }; }; */ } else { if (local _v) then { //_velx = velocity _v select 0; _velx = _velx / 4; //_vely = velocity _v select 1; _vely = _vely / 4; _velz=velocity _v select 2; if (_velz>1) then (_v setvelocity [velocity _v select 0,velocity _v select 1,0]); _expl="HelicopterExploBig" createvehicle [_pos select 0,_pos select 1,(_pos select 2) + 1]; sleep 0.05; /* _wreck=GetText (configFile >> "CfgVehicles" >> (typeof _v) >> "wreck"); if (_wreck!="") then { _pos = getpos _v; _dir = vectordir _v; _vecUp = vectorup _v; _vel = velocity _v; _crw= crew _v; clearvehicleinit _v; deleteVehicle _v; _v =(_wreck) createvehicle _pos; {_x moveincargo _v} foreach _crw; //sleep 0.05; _v setvelocity _vel; //_v setPos _pos; _v setvectordir (_dir); _v setvectorup _vecUp; _v setFuel 0; _v setdamage 0; }; */ _v setVehicleInit format ["[this, %1, %2]spawn BIS_Effects_AirDestructionStage2",_int, _t]; processInitCommands; //ClearvehicleInit done at end of burn script }; };
0
0.743034
1
0.743034
game-dev
MEDIA
0.957075
game-dev
0.787908
1
0.787908
kornelski/7z
2,635
CPP/Windows/Clipboard.cpp
// Windows/Clipboard.cpp #include "StdAfx.h" #ifdef UNDER_CE #include <winuserm.h> #endif #include "../Common/StringConvert.h" #include "Clipboard.h" #include "Defs.h" #include "MemoryGlobal.h" #include "Shell.h" namespace NWindows { bool CClipboard::Open(HWND wndNewOwner) throw() { m_Open = BOOLToBool(::OpenClipboard(wndNewOwner)); return m_Open; } bool CClipboard::Close() throw() { if (!m_Open) return true; m_Open = !BOOLToBool(CloseClipboard()); return !m_Open; } bool ClipboardIsFormatAvailableHDROP() { return BOOLToBool(IsClipboardFormatAvailable(CF_HDROP)); } /* bool ClipboardGetTextString(AString &s) { s.Empty(); if (!IsClipboardFormatAvailable(CF_TEXT)) return false; CClipboard clipboard; if (!clipboard.Open(NULL)) return false; HGLOBAL h = ::GetClipboardData(CF_TEXT); if (h != NULL) { NMemory::CGlobalLock globalLock(h); const char *p = (const char *)globalLock.GetPointer(); if (p != NULL) { s = p; return true; } } return false; } */ /* bool ClipboardGetFileNames(UStringVector &names) { names.Clear(); if (!IsClipboardFormatAvailable(CF_HDROP)) return false; CClipboard clipboard; if (!clipboard.Open(NULL)) return false; HGLOBAL h = ::GetClipboardData(CF_HDROP); if (h != NULL) { NMemory::CGlobalLock globalLock(h); void *p = (void *)globalLock.GetPointer(); if (p != NULL) { NShell::CDrop drop(false); drop.Attach((HDROP)p); drop.QueryFileNames(names); return true; } } return false; } */ static bool ClipboardSetData(UINT uFormat, const void *data, size_t size) throw() { NMemory::CGlobal global; if (!global.Alloc(GMEM_DDESHARE | GMEM_MOVEABLE, size)) return false; { NMemory::CGlobalLock globalLock(global); LPVOID p = globalLock.GetPointer(); if (!p) return false; memcpy(p, data, size); } if (::SetClipboardData(uFormat, global) == NULL) return false; global.Detach(); return true; } bool ClipboardSetText(HWND owner, const UString &s) { CClipboard clipboard; if (!clipboard.Open(owner)) return false; if (!::EmptyClipboard()) return false; bool res; res = ClipboardSetData(CF_UNICODETEXT, (const wchar_t *)s, (s.Len() + 1) * sizeof(wchar_t)); #ifndef _UNICODE AString a (UnicodeStringToMultiByte(s, CP_ACP)); if (ClipboardSetData(CF_TEXT, (const char *)a, (a.Len() + 1) * sizeof(char))) res = true; a = UnicodeStringToMultiByte(s, CP_OEMCP); if (ClipboardSetData(CF_OEMTEXT, (const char *)a, (a.Len() + 1) * sizeof(char))) res = true; #endif return res; } }
0
0.843742
1
0.843742
game-dev
MEDIA
0.370656
game-dev
0.784339
1
0.784339
swiftlang/swift
35,085
lib/SILGen/SILGenConcurrency.cpp
//===--- SILGenConcurrency.cpp - Concurrency-specific SILGen --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "ArgumentSource.h" #include "ExecutorBreadcrumb.h" #include "RValue.h" #include "Scope.h" #include "swift/AST/ASTContext.h" #include "swift/AST/AvailabilityContext.h" #include "swift/AST/ConformanceLookup.h" #include "swift/AST/DistributedDecl.h" #include "swift/AST/ProtocolConformance.h" #include "swift/Basic/Assertions.h" #include "swift/Basic/Range.h" using namespace swift; using namespace Lowering; static void setExpectedExecutorForGeneric(SILGenFunction &SGF) { auto loc = RegularLocation::getAutoGeneratedLocation(SGF.F.getLocation()); SGF.ExpectedExecutor.set(SGF.emitGenericExecutor(loc)); } static void setExpectedExecutorForGlobalActor(SILGenFunction &SGF, Type globalActor) { SGF.ExpectedExecutor.set(SGF.emitLoadGlobalActorExecutor(globalActor)); } static void setExpectedExecutorForLocalVar(SILGenFunction &SGF, VarDecl *var) { auto loc = RegularLocation::getAutoGeneratedLocation(SGF.F.getLocation()); Type actorType = var->getTypeInContext(); RValue actorInstanceRV = SGF.emitRValueForDecl( loc, var, actorType, AccessSemantics::Ordinary); ManagedValue actorInstance = std::move(actorInstanceRV).getScalarValue(); SGF.ExpectedExecutor.set(SGF.emitLoadActorExecutor(loc, actorInstance)); } static void setExpectedExecutorForParameterIsolation(SILGenFunction &SGF, ActorIsolation actorIsolation) { auto loc = RegularLocation::getAutoGeneratedLocation(SGF.F.getLocation()); if (actorIsolation.isActorInstanceIsolated()) { if (actorIsolation.isActorInstanceForSelfParameter()) { ManagedValue selfMV; auto selfArg = SGF.F.getSelfArgument(); if (selfArg->getOwnershipKind() == OwnershipKind::Guaranteed) { selfMV = ManagedValue::forBorrowedRValue(selfArg); } else { selfMV = ManagedValue::forUnmanagedOwnedValue(selfArg); } SGF.ExpectedExecutor.set(SGF.emitLoadActorExecutor(loc, selfMV)); return; } // See if our actorIsolation actually has an actor instance associated with // it. if (auto param = actorIsolation.getActorInstance()) { return setExpectedExecutorForLocalVar(SGF, param); } } // If we have caller isolation inheriting... just grab from our isolated // argument. if (actorIsolation.getKind() == ActorIsolation::CallerIsolationInheriting) { auto *isolatedArg = SGF.F.maybeGetIsolatedArgument(); ASSERT(isolatedArg && "Caller Isolation Inheriting without isolated parameter"); ManagedValue isolatedMV; if (isolatedArg->getOwnershipKind() == OwnershipKind::Guaranteed) { isolatedMV = ManagedValue::forBorrowedRValue(isolatedArg); } else { isolatedMV = ManagedValue::forUnmanagedOwnedValue(isolatedArg); } SGF.ExpectedExecutor.set(SGF.emitLoadActorExecutor(loc, isolatedMV)); return; } llvm_unreachable("Unhandled case?!"); } void SILGenFunction::emitExpectedExecutorProlog() { // Whether the given declaration context is nested within an actor's // destructor. auto isInActorDestructor = [](DeclContext *dc) { while (!dc->isModuleScopeContext() && !dc->isTypeContext()) { if (auto destructor = dyn_cast<DestructorDecl>(dc)) { switch (getActorIsolation(destructor)) { case ActorIsolation::ActorInstance: return true; case ActorIsolation::GlobalActor: // Global-actor-isolated types should likely have deinits that // are not themselves actor-isolated, yet still have access to // the instance properties of the class. return false; case ActorIsolation::Nonisolated: case ActorIsolation::NonisolatedUnsafe: case ActorIsolation::Unspecified: case ActorIsolation::CallerIsolationInheriting: return false; case ActorIsolation::Erased: llvm_unreachable("deinit cannot have erased isolation"); } } dc = dc->getParent(); } return false; }; // Initialize ExpectedExecutor if: // - this function is async or // - this function is sync and isolated to an actor, and we want to // dynamically check that we're on the right executor. // // Actor destructors are isolated in the sense that we now have a // unique reference to the actor, but we probably aren't running on // the actor's executor, so we cannot safely do this check. // // Defer bodies are always called synchronously within their enclosing // function, so the check is unnecessary; in addition, we cannot // necessarily perform the check because the defer may not have // captured the isolated parameter of the enclosing function, and // forcing a capture would cause DI problems in actor initializers. bool wantDataRaceChecks = [&] { if (F.isAsync() || F.isDefer()) return false; if (getOptions().EnableActorDataRaceChecks && !isInActorDestructor(FunctionDC)) return true; if (getASTContext().LangOpts.isDynamicActorIsolationCheckingEnabled()) { if (auto closure = dyn_cast<ClosureExpr>(FunctionDC)) if (closure->requiresDynamicIsolationChecking()) return true; } return false; }(); // FIXME: Avoid loading and checking the expected executor if concurrency is // unavailable. This is specifically relevant for MainActor-isolated contexts, // which are allowed to be available on OSes where concurrency is not // available. rdar://106827064 if (auto *funcDecl = dyn_cast_or_null<AbstractFunctionDecl>(FunctionDC->getAsDecl())) { auto actorIsolation = getActorIsolation(funcDecl); switch (actorIsolation.getKind()) { case ActorIsolation::Unspecified: case ActorIsolation::Nonisolated: case ActorIsolation::NonisolatedUnsafe: break; case ActorIsolation::Erased: llvm_unreachable("method cannot have erased isolation"); case ActorIsolation::ActorInstance: { // Only produce an executor for actor-isolated functions that are async // or are local functions. The former require a hop, while the latter // are prone to dynamic data races in code that does not enforce Sendable // completely. if (F.isAsync() || (wantDataRaceChecks && funcDecl->isLocalCapture())) { auto loweredCaptures = SGM.Types.getLoweredLocalCaptures(SILDeclRef(funcDecl)); if (auto isolatedParam = loweredCaptures.getIsolatedParamCapture()) { setExpectedExecutorForLocalVar(*this, isolatedParam); } else { setExpectedExecutorForParameterIsolation(*this, actorIsolation); } } break; } case ActorIsolation::CallerIsolationInheriting: assert(F.isAsync() || F.isDefer()); setExpectedExecutorForParameterIsolation(*this, actorIsolation); break; case ActorIsolation::GlobalActor: if (F.isAsync() || wantDataRaceChecks) { auto globalActorType = F.mapTypeIntoContext(actorIsolation.getGlobalActor()); setExpectedExecutorForGlobalActor(*this, globalActorType); } break; } } else if (auto *closureExpr = dyn_cast<AbstractClosureExpr>(FunctionDC)) { bool wantExecutor = F.isAsync() || wantDataRaceChecks; auto actorIsolation = closureExpr->getActorIsolation(); switch (actorIsolation.getKind()) { case ActorIsolation::Unspecified: case ActorIsolation::Nonisolated: case ActorIsolation::NonisolatedUnsafe: break; case ActorIsolation::CallerIsolationInheriting: assert(F.isAsync()); setExpectedExecutorForParameterIsolation(*this, actorIsolation); break; case ActorIsolation::Erased: llvm_unreachable("closure cannot have erased isolation"); case ActorIsolation::ActorInstance: { if (wantExecutor) { setExpectedExecutorForLocalVar(*this, actorIsolation.getActorInstance()); } break; } case ActorIsolation::GlobalActor: if (wantExecutor) { auto globalActorType = F.mapTypeIntoContext(actorIsolation.getGlobalActor()); setExpectedExecutorForGlobalActor(*this, globalActorType); break; } } } // In async functions, the generic executor is our expected executor // if we don't have any sort of isolation. if (!ExpectedExecutor.isValid()) { if (F.isAsync() && !unsafelyInheritsExecutor()) { setExpectedExecutorForGeneric(*this); } else { ExpectedExecutor.setUnnecessary(); } } assert(ExpectedExecutor.isValid()); // Jump to the expected executor. if (ExpectedExecutor.isNecessary()) { auto executor = ExpectedExecutor.getEager(); // never lazy if (F.isAsync()) { // For an async function, hop to the executor. B.createHopToExecutor( RegularLocation::getDebugOnlyLocation(F.getLocation(), getModule()), executor, /*mandatory*/ false); } else if (wantDataRaceChecks) { // For a synchronous function, check that we're on the same executor. // Note: if we "know" that the code is completely Sendable-safe, this // is unnecessary. The type checker will need to make this determination. emitPreconditionCheckExpectedExecutor( RegularLocation::getAutoGeneratedLocation(F.getLocation()), executor); } } } void SILGenFunction::emitConstructorExpectedExecutorProlog() { auto ctor = cast<ConstructorDecl>(F.getDeclRef().getDecl()); // In async actor initializers that are isolated to self, we need // to emit the ExpectedExecutor reference lazily. if (ctor->hasAsync()) { auto isolation = getActorIsolation(ctor); auto selfDecl = ctor->getImplicitSelfDecl(); if (isolation.getKind() == ActorIsolation::ActorInstance && isolation.getActorInstance() == selfDecl) { assert(isCtorWithHopsInjectedByDefiniteInit()); ExpectedExecutor.setLazy(); auto loc = SILLocation(selfDecl); loc.markAsPrologue(); loc = loc.asAutoGenerated(); auto initialExecutor = emitGenericExecutor(loc); B.createHopToExecutor(loc, initialExecutor, /*mandatory*/ false); return; } } // Otherwise, emit the normal expected executor prolog. emitExpectedExecutorProlog(); } void SILGenFunction::emitPrologGlobalActorHop(SILLocation loc, Type globalActor) { auto executor = emitLoadGlobalActorExecutor(globalActor); ExpectedExecutor.set(executor); B.createHopToExecutor(RegularLocation::getDebugOnlyLocation(loc, getModule()), executor, /*mandatory*/ false); } SILValue SILGenFunction::emitMainExecutor(SILLocation loc) { auto &ctx = getASTContext(); auto builtinName = ctx.getIdentifier( getBuiltinName(BuiltinValueKind::BuildMainActorExecutorRef)); auto resultType = SILType::getPrimitiveObjectType(ctx.TheExecutorType); return B.createBuiltin(loc, builtinName, resultType, {}, {}); } SILValue SILGenFunction::emitGenericExecutor(SILLocation loc) { // The generic executor is encoded as the nil value of // std::optional<Builtin.SerialExecutor>. auto ty = SILType::getOptionalType( SILType::getPrimitiveObjectType( getASTContext().TheExecutorType)); return B.createOptionalNone(loc, ty); } ManagedValue SILGenFunction::emitNonIsolatedIsolation(SILLocation loc) { return B.createManagedOptionalNone(loc, SILType::getOpaqueIsolationType(getASTContext())); } SILValue SILGenFunction::emitLoadGlobalActorExecutor(Type globalActor) { auto loc = RegularLocation::getAutoGeneratedLocation(F.getLocation()); auto actorAndFormalType = emitLoadOfGlobalActorShared(loc, globalActor->getCanonicalType()); return emitLoadActorExecutor(loc, actorAndFormalType.first); } std::pair<ManagedValue, CanType> SILGenFunction::emitLoadOfGlobalActorShared(SILLocation loc, CanType actorType) { NominalTypeDecl *nominal = actorType->getNominalOrBoundGenericNominal(); VarDecl *sharedInstanceDecl = nominal->getGlobalActorInstance(); assert(sharedInstanceDecl && "no shared actor field in global actor"); SubstitutionMap subs = actorType->getContextSubstitutionMap(); Type instanceType = actorType->getTypeOfMember(sharedInstanceDecl); auto metaRepr = nominal->isResilient(SGM.SwiftModule, F.getResilienceExpansion()) ? MetatypeRepresentation::Thick : MetatypeRepresentation::Thin; CanType actorMetaType = CanMetatypeType::get(actorType, metaRepr); ManagedValue actorMetaTypeValue = ManagedValue::forObjectRValueWithoutOwnership(B.createMetatype( loc, SILType::getPrimitiveObjectType(actorMetaType))); RValue actorInstanceRV = emitRValueForStorageLoad(loc, actorMetaTypeValue, actorMetaType, /*isSuper*/ false, sharedInstanceDecl, PreparedArguments(), subs, AccessSemantics::Ordinary, instanceType, SGFContext()); ManagedValue actorInstance = std::move(actorInstanceRV).getScalarValue(); return {actorInstance, instanceType->getCanonicalType()}; } ManagedValue SILGenFunction::emitGlobalActorIsolation(SILLocation loc, CanType globalActorType) { // Load the .shared property. Note that this isn't necessarily a value // of the global actor type. auto actorAndFormalType = emitLoadOfGlobalActorShared(loc, globalActorType); // Since it's just a normal actor instance, we can use the normal path. return emitActorInstanceIsolation(loc, actorAndFormalType.first, actorAndFormalType.second); } static ProtocolConformanceRef getActorConformance(SILGenFunction &SGF, CanType actorType) { auto &ctx = SGF.getASTContext(); auto proto = ctx.getProtocol(KnownProtocolKind::Actor); return lookupConformance(actorType, proto); } static ProtocolConformanceRef getDistributedActorConformance(SILGenFunction &SGF, CanType actorType) { auto &ctx = SGF.getASTContext(); auto proto = ctx.getProtocol(KnownProtocolKind::DistributedActor); return lookupConformance(actorType, proto); } /// Given a value of some non-optional distributed actor type, convert it /// to the non-optional `any Actor` type. static ManagedValue emitDistributedActorIsolation(SILGenFunction &SGF, SILLocation loc, ManagedValue actor, CanType actorType) { // First, open the actor type if it's an existential type. if (actorType->isExistentialType()) { CanType openedType = ExistentialArchetypeType::getAny(actorType) ->getCanonicalType(); SILType loweredOpenedType = SGF.getLoweredType(openedType); actor = SGF.emitOpenExistential(loc, actor, loweredOpenedType, AccessKind::Read); actorType = openedType; } // Build <T: DistributedActor> and its substitutions for actorType. // Doing this manually is ill-advised in general, but this is such a // simple case that it's okay. auto distributedActorConf = getDistributedActorConformance(SGF, actorType); auto sig = distributedActorConf.getProtocol()->getGenericSignature(); auto distributedActorSubs = SubstitutionMap::get(sig, {actorType}, {distributedActorConf}); // Use that to build the magical conformance to Actor for the distributed // actor type. return SGF.emitDistributedActorAsAnyActor(loc, distributedActorSubs, actor); } /// Given a value of some non-optional actor type, convert it to /// non-optional `any Actor` type. static ManagedValue emitNonOptionalActorInstanceIsolation(SILGenFunction &SGF, SILLocation loc, ManagedValue actor, CanType actorType, SILType anyActorTy) { // If we have an `any Actor` already, we're done. if (actor.getType() == anyActorTy) return actor; CanType anyActorType = anyActorTy.getASTType(); // If the actor is a distributed actor, (1) it had better be local // and (2) we need to use the special conformance. if (actorType->isDistributedActor()) { return emitDistributedActorIsolation(SGF, loc, actor, actorType); } return SGF.emitTransformExistential(loc, actor, actorType, anyActorType); } ManagedValue SILGenFunction::emitActorInstanceIsolation(SILLocation loc, ManagedValue actor, CanType actorType) { // $Optional<any Actor> auto optionalAnyActorTy = SILType::getOpaqueIsolationType(getASTContext()); // Optional<any Actor> as a formal type (it's invariant to lowering) auto optionalAnyActorType = optionalAnyActorTy.getASTType(); // If we started with an Optional<any Actor>, we're done. if (actorType == optionalAnyActorType) { return actor; } // Otherwise, if we have an optional value, we need to transform the payload. auto actorObjectType = actorType.getOptionalObjectType(); if (actorObjectType) { return emitOptionalToOptional(loc, actor, optionalAnyActorTy, [&](SILGenFunction &SGF, SILLocation loc, ManagedValue actorObject, SILType anyActorTy, SGFContext C) { return emitNonOptionalActorInstanceIsolation(*this, loc, actorObject, actorObjectType, anyActorTy); }); } // Otherwise, transform the non-optional value we have, then inject that // into Optional. SILType anyActorTy = optionalAnyActorTy.getOptionalObjectType(); ManagedValue anyActor = emitNonOptionalActorInstanceIsolation(*this, loc, actor, actorType, anyActorTy); // Inject into `Optional`. auto result = B.createOptionalSome(loc, anyActor); return result; } SILValue SILGenFunction::emitLoadActorExecutor(SILLocation loc, ManagedValue actor) { // FIXME: Checking for whether we're in a formal evaluation scope // like this doesn't seem like a good pattern. SILValue actorV; if (isInFormalEvaluationScope()) actorV = actor.formalAccessBorrow(*this, loc).getValue(); else actorV = actor.borrow(*this, loc).getValue(); // For now, we just want to emit a hop_to_executor directly to the // actor; LowerHopToActor will add the emission logic necessary later. return actorV; } /// If we are in an actor initializer that is isolated to self, the /// current isolation is flow-sensitive: it will be nil before self is /// initialized, and afterwards it will be the value of self. /// Call a builtin that the definite initialization pass will rewrite. ManagedValue SILGenFunction::emitFlowSensitiveSelfIsolation(SILLocation loc, ActorIsolation isolation) { auto isolatedVar = isolation.getActorInstance(); #ifndef NDEBUG { auto ctor = cast<ConstructorDecl>(F.getDeclRef().getDecl()); assert(isolatedVar == ctor->getImplicitSelfDecl()); } #endif CanType actorType = isolatedVar->getTypeInContext()->getCanonicalType(); assert(actorType->isAnyActorType()); ASTContext &ctx = getASTContext(); Identifier builtinName; ProtocolConformanceRef conformance; if (isolation.isDistributedActor()) { // Create a reference to the asLocalActor getter. We don't call this // immediately, but we need to make sure it's available later when the // mandatory passes clean this up. auto asLocalActorDecl = getDistributedActorAsLocalActorComputedProperty( F.getDeclContext()->getParentModule()); auto asLocalActorGetter = asLocalActorDecl->getAccessor(AccessorKind::Get); SILDeclRef asLocalActorRef = SILDeclRef( asLocalActorGetter, SILDeclRef::Kind::Func); (void) emitGlobalFunctionRef(loc, asLocalActorRef); builtinName = ctx.getIdentifier( getBuiltinName(BuiltinValueKind::FlowSensitiveDistributedSelfIsolation)); conformance = getDistributedActorConformance(*this, actorType); } else { builtinName = ctx.getIdentifier( getBuiltinName(BuiltinValueKind::FlowSensitiveSelfIsolation)); conformance = getActorConformance(*this, actorType); } SGM.useConformance(conformance); SubstitutionMap subs = SubstitutionMap::getProtocolSubstitutions( conformance.getProtocol(), actorType, conformance); auto origActor = maybeEmitValueOfLocalVarDecl(isolatedVar, AccessKind::Read).getValue(); SILType resultTy = SILType::getOpaqueIsolationType(ctx); auto call = B.createBuiltin(loc, builtinName, resultTy, subs, origActor); return ManagedValue::forForwardedRValue(*this, call); } SILValue SILGenFunction::emitLoadErasedExecutor(SILLocation loc, ManagedValue fn) { // As with emitLoadActorExecutor, we just emit the actor reference // for now and let LowerHopToActor deal with the executor projection. return emitLoadErasedIsolation(loc, fn).getUnmanagedValue(); } ManagedValue SILGenFunction::emitLoadErasedIsolation(SILLocation loc, ManagedValue fn) { fn = fn.borrow(*this, loc); // This expects a borrowed function and returns a borrowed (any Actor)?. auto actor = B.createFunctionExtractIsolation(loc, fn.getValue()); return ManagedValue::forBorrowedObjectRValue(actor); } ManagedValue SILGenFunction::emitFunctionTypeIsolation(SILLocation loc, FunctionTypeIsolation isolation, ManagedValue fn) { switch (isolation.getKind()) { // Parameter-isolated functions don't have a specific actor they're isolated // to; they're essentially polymorphic over isolation. case FunctionTypeIsolation::Kind::Parameter: llvm_unreachable("cannot load isolation from parameter-isoaltion function " "reference"); // Emit nonisolated by simply emitting Optional.none in the result type. case FunctionTypeIsolation::Kind::NonIsolated: case FunctionTypeIsolation::Kind::NonIsolatedNonsending: return emitNonIsolatedIsolation(loc); // Emit global actor isolation by loading .shared from the global actor, // erasing it into `any Actor`, and injecting that into Optional. case FunctionTypeIsolation::Kind::GlobalActor: { return emitGlobalActorIsolation(loc, isolation.getGlobalActorType()->getCanonicalType()); } // Emit @isolated(any) isolation by loading the actor reference from the // function. case FunctionTypeIsolation::Kind::Erased: { Scope scope(*this, CleanupLocation(loc)); auto value = emitLoadErasedIsolation(loc, fn).copy(*this, loc); return scope.popPreservingValue(value); } } llvm_unreachable("bad kind"); } static ActorIsolation getClosureIsolationInfo(SILDeclRef constant) { if (auto closure = constant.getAbstractClosureExpr()) { return closure->getActorIsolation(); } auto func = constant.getAbstractFunctionDecl(); assert(func && "unexpected closure constant"); return getActorIsolation(func); } static ManagedValue emitLoadOfCaptureIsolation(SILGenFunction &SGF, SILLocation loc, VarDecl *isolatedCapture, SILDeclRef constant, ArrayRef<ManagedValue> captureArgs) { auto &TC = SGF.SGM.Types; auto captureInfo = TC.getLoweredLocalCaptures(constant); auto isolatedVarType = isolatedCapture->getTypeInContext()->getCanonicalType(); // Capture arguments are 1-1 with the lowered capture info. auto captures = captureInfo.getCaptures(); for (auto i : indices(captures)) { const auto &capture = captures[i]; if (capture.isDynamicSelfMetadata()) continue; auto capturedVar = capture.getDecl(); if (capturedVar != isolatedCapture) continue; // Captured actor references should always be captured as constants. assert(TC.getDeclCaptureKind(capture, TC.getCaptureTypeExpansionContext(constant)) == CaptureKind::Constant); auto value = captureArgs[i].copy(SGF, loc); return SGF.emitActorInstanceIsolation(loc, value, isolatedVarType); } // The capture not being a lowered capture can happen in global code. auto value = SGF.emitRValueForDecl(loc, isolatedCapture, isolatedVarType, AccessSemantics::Ordinary) .getAsSingleValue(SGF, loc); return SGF.emitActorInstanceIsolation(loc, value, isolatedVarType); } ManagedValue SILGenFunction::emitClosureIsolation(SILLocation loc, SILDeclRef constant, ArrayRef<ManagedValue> captures) { auto isolation = getClosureIsolationInfo(constant); switch (isolation) { case ActorIsolation::Unspecified: case ActorIsolation::Nonisolated: case ActorIsolation::CallerIsolationInheriting: case ActorIsolation::NonisolatedUnsafe: return emitNonIsolatedIsolation(loc); case ActorIsolation::Erased: llvm_unreachable("closures cannot directly have erased isolation"); case ActorIsolation::GlobalActor: { auto globalActorType = F.mapTypeIntoContext(isolation.getGlobalActor()) ->getCanonicalType(); return emitGlobalActorIsolation(loc, globalActorType); } case ActorIsolation::ActorInstance: { assert(isolation.isActorInstanceForCapture()); auto capture = isolation.getActorInstance(); assert(capture); return emitLoadOfCaptureIsolation(*this, loc, capture, constant, captures); } } llvm_unreachable("bad kind"); } ExecutorBreadcrumb SILGenFunction::emitHopToTargetActor(SILLocation loc, std::optional<ActorIsolation> maybeIso, std::optional<ManagedValue> maybeSelf) { if (!maybeIso) return ExecutorBreadcrumb(); if (auto executor = emitExecutor(loc, *maybeIso, maybeSelf)) { return emitHopToTargetExecutor(loc, *executor); } else { return ExecutorBreadcrumb(); } } namespace { class HopToActorCleanup : public Cleanup { SILValue value; public: HopToActorCleanup(SILValue value) : value(value) {} void emit(SILGenFunction &SGF, CleanupLocation l, ForUnwind_t forUnwind) override { SGF.B.createHopToExecutor(l, value, false /*mandatory*/); } void dump(SILGenFunction &) const override { #ifndef NDEBUG llvm::errs() << "HopToExecutorCleanup\n" << "State:" << getState() << "\n" << "Value:" << value << "\n"; #endif } }; } // end anonymous namespace CleanupHandle SILGenFunction::emitScopedHopToTargetActor(SILLocation loc, SILValue actor) { Cleanups.pushCleanup<HopToActorCleanup>(actor); return Cleanups.getTopCleanup(); } ExecutorBreadcrumb SILGenFunction::emitHopToTargetExecutor( SILLocation loc, SILValue executor) { // Record that we need to hop back to the current executor. auto breadcrumb = ExecutorBreadcrumb(true); B.createHopToExecutor(RegularLocation::getDebugOnlyLocation(loc, getModule()), executor, /*mandatory*/ false); return breadcrumb; } std::optional<SILValue> SILGenFunction::emitExecutor(SILLocation loc, ActorIsolation isolation, std::optional<ManagedValue> maybeSelf) { switch (isolation.getKind()) { case ActorIsolation::Unspecified: case ActorIsolation::Nonisolated: case ActorIsolation::CallerIsolationInheriting: case ActorIsolation::NonisolatedUnsafe: return std::nullopt; case ActorIsolation::Erased: llvm_unreachable("executor emission for erased isolation is unimplemented"); case ActorIsolation::ActorInstance: { // "self" here means the actor instance's "self" value. assert(maybeSelf.has_value() && "actor-instance but no self provided?"); auto self = maybeSelf.value(); return emitLoadActorExecutor(loc, self); } case ActorIsolation::GlobalActor: { auto globalActorType = F.mapTypeIntoContext(isolation.getGlobalActor()); return emitLoadGlobalActorExecutor(globalActorType); } } llvm_unreachable("covered switch"); } void SILGenFunction::emitHopToActorValue(SILLocation loc, ManagedValue actor) { // TODO: can the type system enforce this async requirement? if (!F.isAsync()) { llvm::report_fatal_error("Builtin.hopToActor must be in an async function"); } auto isolation = getActorIsolationOfContext(FunctionDC, [](AbstractClosureExpr *CE) { return CE->getActorIsolation(); }); if (isolation != ActorIsolation::Nonisolated && isolation != ActorIsolation::NonisolatedUnsafe && isolation != ActorIsolation::Unspecified) { // TODO: Explicit hop with no hop-back should only be allowed in nonisolated // async functions. But it needs work for any closure passed to // Task.detached, which currently has unspecified isolation. llvm::report_fatal_error( "Builtin.hopToActor must be in an actor-independent function"); } SILValue executor = emitLoadActorExecutor(loc, actor); B.createHopToExecutor(RegularLocation::getDebugOnlyLocation(loc, getModule()), executor, /*mandatory*/ true); } static bool isCheckExpectedExecutorIntrinsicAvailable(SILGenModule &SGM) { auto checkExecutor = SGM.getCheckExpectedExecutor(); if (!checkExecutor) return false; // Forego a check if instrinsic is unavailable, this could happen // in main-actor context. auto &C = checkExecutor->getASTContext(); if (!C.LangOpts.DisableAvailabilityChecking) { auto deploymentAvailability = AvailabilityContext::forDeploymentTarget(C); auto declAvailability = AvailabilityContext::forDeclSignature(checkExecutor); return deploymentAvailability.isContainedIn(declAvailability); } return true; } void SILGenFunction::emitPreconditionCheckExpectedExecutor( SILLocation loc, ActorIsolation isolation, std::optional<ManagedValue> actorSelf) { if (!isCheckExpectedExecutorIntrinsicAvailable(SGM)) return; auto executor = emitExecutor(loc, isolation, actorSelf); assert(executor); emitPreconditionCheckExpectedExecutor(loc, *executor); } void SILGenFunction::emitPreconditionCheckExpectedExecutor( SILLocation loc, SILValue executorOrActor) { if (!isCheckExpectedExecutorIntrinsicAvailable(SGM)) return; // We don't want the debugger to step into these. loc.markAutoGenerated(); // If the function is isolated to an optional actor reference, // check dynamically whether it's non-null. We don't need to // do an assertion if the expected expected is nil. SILBasicBlock *noneBB = nullptr; bool isOptional = (bool) executorOrActor->getType().getOptionalObjectType(); if (isOptional) { // Start by emiting the .some path. noneBB = createBasicBlock(); auto someBB = createBasicBlockBefore(noneBB); executorOrActor = B.createSwitchOptional(loc, executorOrActor, someBB, noneBB, executorOrActor->getOwnershipKind()); B.emitBlock(someBB); } // Get the executor. SILValue executor = B.createExtractExecutor(loc, executorOrActor); // Call the library function that performs the checking. auto args = emitSourceLocationArgs(loc.getSourceLoc(), loc); emitApplyOfLibraryIntrinsic( loc, SGM.getCheckExpectedExecutor(), SubstitutionMap(), {args.filenameStartPointer, args.filenameLength, args.filenameIsAscii, args.line, ManagedValue::forObjectRValueWithoutOwnership(executor)}, SGFContext()); // Complete the optional control flow if we had an optional value. if (isOptional) { assert(noneBB); // Finish the .some path by branching to the continuation block. auto contBB = createBasicBlockAfter(noneBB); B.createBranch(loc, contBB); // The .none path is trivial. B.emitBlock(noneBB); B.createBranch(loc, contBB); B.emitBlock(contBB); } } bool SILGenFunction::unsafelyInheritsExecutor() { if (auto fn = dyn_cast<AbstractFunctionDecl>(FunctionDC)) return fn->getAttrs().hasAttribute<UnsafeInheritExecutorAttr>(); return false; } void ExecutorBreadcrumb::emit(SILGenFunction &SGF, SILLocation loc) { if (mustReturnToExecutor) { assert(SGF.ExpectedExecutor.isValid()); if (SGF.ExpectedExecutor.isNecessary()) { FullExpr scope(SGF.Cleanups, CleanupLocation(loc)); auto executor = SGF.emitExpectedExecutor(loc); SGF.B.createHopToExecutor( RegularLocation::getDebugOnlyLocation(loc, SGF.getModule()), executor.getValue(), /*mandatory*/ false); } } } ManagedValue SILGenFunction::emitExpectedExecutor(SILLocation loc) { assert(ExpectedExecutor.isNecessary() && "prolog failed to set up expected executor?"); // Fast (common) path: we have an eagerly-set expected executor. if (ExpectedExecutor.isEager()) { return ManagedValue::forBorrowedObjectRValue(ExpectedExecutor.getEager()); } // Otherwise, the current function must have lazy, flow-sensitive isolation. auto ctor = cast<ConstructorDecl>(F.getDeclRef().getDecl()); auto isolation = getActorIsolation(ctor); return emitFlowSensitiveSelfIsolation(loc, isolation); } ManagedValue SILGenFunction::emitDistributedActorAsAnyActor(SILLocation loc, SubstitutionMap distributedActorSubs, ManagedValue actorValue) { auto &ctx = SGM.getASTContext(); auto distributedActorAsActorConformance = getDistributedActorAsActorConformance(ctx); auto actorProto = ctx.getProtocol(KnownProtocolKind::Actor); auto distributedActorType = distributedActorSubs.getReplacementTypes()[0]; auto ref = ProtocolConformanceRef(ctx.getSpecializedConformance( distributedActorType, distributedActorAsActorConformance, distributedActorSubs)); ProtocolConformanceRef conformances[1] = {ref}; // Erase the distributed actor instance into an `any Actor` existential with // the special conformance. CanType distributedActorCanType = distributedActorType->getCanonicalType(); auto &distributedActorTL = getTypeLowering(distributedActorCanType); auto &anyActorTL = getTypeLowering(actorProto->getDeclaredExistentialType()); return emitExistentialErasure( loc, distributedActorCanType, distributedActorTL, anyActorTL, ctx.AllocateCopy(conformances), SGFContext(), [actorValue](SGFContext) { return actorValue; }); }
0
0.866833
1
0.866833
game-dev
MEDIA
0.79431
game-dev
0.860588
1
0.860588
Sduibek/fixtsrc
4,334
SCRIPTS/VPLSTRAP.SSL
// // ---TRAP SCRIPT--- Sduibek // procedure start; // VATS, Plasma Trap procedure boom; variable CritFailDmg := 0; variable Traps_roll := 0; variable XP := 0; // local_var(0) == Detected? // local_var(1) == Disarmed (1) or Triggered (2) // local_var(2) == #ofTimes // SCRIPT 509 (TRAPFLOR) <-- msgs are from this procedure start begin if (script_action == 2) then begin// spatial_p_proc - Player is on or near hex of the location or object this script is using if global_var(146) then begin// VATS ON ALERT if (source_obj == dude_obj) or party_member_obj(obj_pid(source_obj)) then begin// new check (party member) set_local_var(2, local_var(2) + 1); XP := 0; CritFailDmg := 0; Traps_roll := roll_vs_skill(dude_obj, 11, 0); if not(is_success(Traps_roll)) and is_critical(Traps_roll) then begin CritFailDmg := 10; end else begin if not(local_var(0)) then begin if is_success(Traps_roll) then begin set_local_var(0, 1); if is_critical(Traps_roll) then begin XP := XP + 50; end else begin XP := XP + 25; end reg_anim_func(2, dude_obj); if source_obj != dude_obj then begin reg_anim_func(2, source_obj); end display_msg(message_str(509, 101)); anim(dude_obj, 11, 0); Traps_roll := roll_vs_skill(dude_obj, 11, 0); if not(is_success(Traps_roll)) and is_critical(Traps_roll) then begin CritFailDmg := 10; call boom; end else begin if is_success(Traps_roll) then begin set_local_var(1, 1); if is_critical(Traps_roll) then begin XP := XP + 100; end else begin XP := XP + 50; end display_msg(message_str(509, 107)); end else begin display_msg(message_str(509, 111)); end end if XP then begin display_msg(message_str(509, 104) + XP + message_str(509, 105)); give_exp_points(XP); end end else begin call boom; end end else begin if not(local_var(1)) then begin if local_var(2) <= 3 then begin Traps_roll := roll_vs_skill(dude_obj, 11, 0); reg_anim_func(2, dude_obj); if source_obj != dude_obj then begin reg_anim_func(2, source_obj); end anim(dude_obj, 11, 0); if not(is_success(Traps_roll)) and is_critical(Traps_roll) then begin CritFailDmg := 10; call boom; end else begin if is_success(Traps_roll) then begin set_local_var(1, 1); if is_critical(Traps_roll) then begin XP := XP + 100; end else begin XP := XP + 50; end display_msg(message_str(509, 107)); if XP then begin display_msg(message_str(509, 104) + XP + message_str(509, 105)); give_exp_points(XP); end end else begin if local_var(2) < 3 then begin display_msg(message_str(509, 111)); end else begin call boom; end end end end else begin call boom; end end end end if local_var(1) then begin destroy_object(self_obj); end end end end end procedure boom begin if local_var(2) <= 1 then begin if source_obj == dude_obj then begin display_msg(message_str(509, 109)); end else begin display_msg(proto_data(obj_pid(source_obj), 1) + message_str(509, 108)); end end else begin if source_obj == dude_obj then begin display_msg(message_str(509, 114)); end else begin display_msg(proto_data(obj_pid(source_obj), 1) + message_str(509, 113)); end end set_local_var(1, 2); if source_obj == dude_obj then begin critter_dmg(dude_obj, random(20 + (difficulty_level * 5), 40 + (difficulty_level * 10)) + ), 3); end else begin critter_dmg(source_obj, random(20 + (difficulty_level * 5), 40 + (difficulty_level * 10)) + ), 3); critter_dmg(dude_obj, random(20 + (difficulty_level * 5), 40 + (difficulty_level * 10)) + ), 3); end end // #define DMG_normal_dam 0 // #define DMG_laser 1 // #define DMG_plasma 3 // #define DMG_electrical 4 // #define DMG_emp 5
0
0.831559
1
0.831559
game-dev
MEDIA
0.918879
game-dev
0.989166
1
0.989166
cnthigu/Conquer-Online-Server-Source
1,087
GameServer/Database/HouseTable.cs
namespace COServer.Database { public class HouseTable { //3990 or 3995 house level 6 internal static int CountFurnitures(byte Level) { switch (Level) { case 2: return 8; case 3: return 9; case 4: return 10; case 5: return 12; case 6: return 20; } return 0; } internal static bool InHouse(uint MapID) { return MapID == 1098 || MapID == 1099 || MapID == 2080 || MapID == 601 || MapID == 3024 || MapID == 3995; } internal static ushort GetHouseId(byte level) { if (level == 1) return 1098; else if (level == 2) return 1099; else if (level == 3) return 2080; else if (level == 4) return 601; else if (level == 5) return 3024; else if (level == 6) return 3995; return 0; } } }
0
0.638724
1
0.638724
game-dev
MEDIA
0.807661
game-dev
0.726861
1
0.726861
CaptGreg/SenecaOOP345-attic
70,313
opencl/time_opencl_kernel.i.bcpp.cl
typedef ulong uint64_t; typedef uint uint32_t; typedef uchar uint8_t; inline int haveAESNI() { return 0; } struct r123array1x32{ uint32_t v[1]; }; struct r123array2x32{ uint32_t v[2]; }; struct r123array4x32{ uint32_t v[4]; }; struct r123array8x32{ uint32_t v[8]; }; struct r123array1x64{ uint64_t v[1]; }; struct r123array2x64{ uint64_t v[2]; }; struct r123array4x64{ uint64_t v[4]; }; struct r123array16x8{ uint8_t v[16]; }; inline uint32_t mulhilo32(uint32_t a, uint32_t b, uint32_t* hip){ uint64_t product = ((uint64_t)a)*((uint64_t)b); *hip = product>>32; return (uint32_t)product; } inline uint64_t mulhilo64(uint64_t a, uint64_t b, uint64_t* hip){ *hip = mul_hi(a, b); return a*b; } inline struct r123array1x32 _philox2x32bumpkey( struct r123array1x32 key) { key.v[0] += ((uint32_t)0x9E3779B9); return key; } inline struct r123array2x32 _philox4x32bumpkey( struct r123array2x32 key) { key.v[0] += ((uint32_t)0x9E3779B9); key.v[1] += ((uint32_t)0xBB67AE85); return key; } inline struct r123array2x32 _philox2x32round(struct r123array2x32 ctr, struct r123array1x32 key) __attribute__((always_inline)); inline struct r123array2x32 _philox2x32round(struct r123array2x32 ctr, struct r123array1x32 key) { uint32_t hi; uint32_t lo = mulhilo32(((uint32_t)0xd256d193), ctr.v[0], &hi); struct r123array2x32 out = { { hi^key.v[0]^ctr.v[1], lo } }; return out; } inline struct r123array4x32 _philox4x32round(struct r123array4x32 ctr, struct r123array2x32 key) __attribute__((always_inline)); inline struct r123array4x32 _philox4x32round(struct r123array4x32 ctr, struct r123array2x32 key) { uint32_t hi0; uint32_t hi1; uint32_t lo0 = mulhilo32(((uint32_t)0xD2511F53), ctr.v[0], &hi0); uint32_t lo1 = mulhilo32(((uint32_t)0xCD9E8D57), ctr.v[2], &hi1); struct r123array4x32 out = { { hi1^ctr.v[1]^key.v[0], lo1, hi0^ctr.v[3]^key.v[1], lo0 } }; return out; } enum { philox2x32_rounds = 10 }; typedef struct r123array2x32 philox2x32_ctr_t; typedef struct r123array1x32 philox2x32_key_t; typedef struct r123array1x32 philox2x32_ukey_t; inline philox2x32_key_t philox2x32keyinit(philox2x32_ukey_t uk) { return uk; } inline philox2x32_ctr_t philox2x32_R(unsigned int R, philox2x32_ctr_t ctr, philox2x32_key_t key) __attribute__((always_inline)); inline philox2x32_ctr_t philox2x32_R(unsigned int R, philox2x32_ctr_t ctr, philox2x32_key_t key) { ; if(R>0) { ctr = _philox2x32round(ctr, key); } if(R>1) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>2) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>3) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>4) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>5) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>6) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>7) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>8) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>9) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>10) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>11) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>12) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>13) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>14) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } if(R>15) { key = _philox2x32bumpkey(key); ctr = _philox2x32round(ctr, key); } return ctr; } enum { philox4x32_rounds = 10 }; typedef struct r123array4x32 philox4x32_ctr_t; typedef struct r123array2x32 philox4x32_key_t; typedef struct r123array2x32 philox4x32_ukey_t; inline philox4x32_key_t philox4x32keyinit(philox4x32_ukey_t uk) { return uk; } inline philox4x32_ctr_t philox4x32_R(unsigned int R, philox4x32_ctr_t ctr, philox4x32_key_t key) __attribute__((always_inline)); inline philox4x32_ctr_t philox4x32_R(unsigned int R, philox4x32_ctr_t ctr, philox4x32_key_t key) { ; if(R>0) { ctr = _philox4x32round(ctr, key); } if(R>1) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>2) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>3) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>4) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>5) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>6) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>7) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>8) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>9) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>10) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>11) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>12) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>13) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>14) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } if(R>15) { key = _philox4x32bumpkey(key); ctr = _philox4x32round(ctr, key); } return ctr; } inline struct r123array1x64 _philox2x64bumpkey( struct r123array1x64 key) { key.v[0] += ((ulong)(0x9E3779B97F4A7C15UL)); return key; } inline struct r123array2x64 _philox4x64bumpkey( struct r123array2x64 key) { key.v[0] += ((ulong)(0x9E3779B97F4A7C15UL)); key.v[1] += ((ulong)(0xBB67AE8584CAA73BUL)); return key; } inline struct r123array2x64 _philox2x64round(struct r123array2x64 ctr, struct r123array1x64 key) __attribute__((always_inline)); inline struct r123array2x64 _philox2x64round(struct r123array2x64 ctr, struct r123array1x64 key) { uint64_t hi; uint64_t lo = mulhilo64(((ulong)(0xD2B74407B1CE6E93UL)), ctr.v[0], &hi); struct r123array2x64 out = { { hi^key.v[0]^ctr.v[1], lo } }; return out; } inline struct r123array4x64 _philox4x64round(struct r123array4x64 ctr, struct r123array2x64 key) __attribute__((always_inline)); inline struct r123array4x64 _philox4x64round(struct r123array4x64 ctr, struct r123array2x64 key) { uint64_t hi0; uint64_t hi1; uint64_t lo0 = mulhilo64(((ulong)(0xD2E7470EE14C6C93UL)), ctr.v[0], &hi0); uint64_t lo1 = mulhilo64(((ulong)(0xCA5A826395121157UL)), ctr.v[2], &hi1); struct r123array4x64 out = { { hi1^ctr.v[1]^key.v[0], lo1, hi0^ctr.v[3]^key.v[1], lo0 } }; return out; } enum { philox2x64_rounds = 10 }; typedef struct r123array2x64 philox2x64_ctr_t; typedef struct r123array1x64 philox2x64_key_t; typedef struct r123array1x64 philox2x64_ukey_t; inline philox2x64_key_t philox2x64keyinit(philox2x64_ukey_t uk) { return uk; } inline philox2x64_ctr_t philox2x64_R(unsigned int R, philox2x64_ctr_t ctr, philox2x64_key_t key) __attribute__((always_inline)); inline philox2x64_ctr_t philox2x64_R(unsigned int R, philox2x64_ctr_t ctr, philox2x64_key_t key) { ; if(R>0) { ctr = _philox2x64round(ctr, key); } if(R>1) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>2) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>3) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>4) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>5) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>6) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>7) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>8) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>9) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>10) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>11) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>12) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>13) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>14) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } if(R>15) { key = _philox2x64bumpkey(key); ctr = _philox2x64round(ctr, key); } return ctr; } enum { philox4x64_rounds = 10 }; typedef struct r123array4x64 philox4x64_ctr_t; typedef struct r123array2x64 philox4x64_key_t; typedef struct r123array2x64 philox4x64_ukey_t; inline philox4x64_key_t philox4x64keyinit(philox4x64_ukey_t uk) { return uk; } inline philox4x64_ctr_t philox4x64_R(unsigned int R, philox4x64_ctr_t ctr, philox4x64_key_t key) __attribute__((always_inline)); inline philox4x64_ctr_t philox4x64_R(unsigned int R, philox4x64_ctr_t ctr, philox4x64_key_t key) { ; if(R>0) { ctr = _philox4x64round(ctr, key); } if(R>1) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>2) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>3) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>4) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>5) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>6) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>7) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>8) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>9) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>10) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>11) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>12) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>13) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>14) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } if(R>15) { key = _philox4x64bumpkey(key); ctr = _philox4x64round(ctr, key); } return ctr; } enum { R_64x4_0_0=14, R_64x4_0_1=16, R_64x4_1_0=52, R_64x4_1_1=57, R_64x4_2_0=23, R_64x4_2_1=40, R_64x4_3_0= 5, R_64x4_3_1=37, R_64x4_4_0=25, R_64x4_4_1=33, R_64x4_5_0=46, R_64x4_5_1=12, R_64x4_6_0=58, R_64x4_6_1=22, R_64x4_7_0=32, R_64x4_7_1=32 }; enum { R_64x2_0_0=16, R_64x2_1_0=42, R_64x2_2_0=12, R_64x2_3_0=31, R_64x2_4_0=16, R_64x2_5_0=32, R_64x2_6_0=24, R_64x2_7_0=21 }; enum { R_32x4_0_0=10, R_32x4_0_1=26, R_32x4_1_0=11, R_32x4_1_1=21, R_32x4_2_0=13, R_32x4_2_1=27, R_32x4_3_0=23, R_32x4_3_1= 5, R_32x4_4_0= 6, R_32x4_4_1=20, R_32x4_5_0=17, R_32x4_5_1=11, R_32x4_6_0=25, R_32x4_6_1=10, R_32x4_7_0=18, R_32x4_7_1=20 }; enum { R_32x2_0_0=13, R_32x2_1_0=15, R_32x2_2_0=26, R_32x2_3_0= 6, R_32x2_4_0=17, R_32x2_5_0=29, R_32x2_6_0=16, R_32x2_7_0=24 }; enum { WCNT2=2, WCNT4=4 }; inline uint64_t RotL_64(uint64_t x, unsigned int N) __attribute__((always_inline)); inline uint64_t RotL_64(uint64_t x, unsigned int N) { return (x << (N & 63)) | (x >> ((64-N) & 63)); } inline uint32_t RotL_32(uint32_t x, unsigned int N) __attribute__((always_inline)); inline uint32_t RotL_32(uint32_t x, unsigned int N) { return (x << (N & 31)) | (x >> ((32-N) & 31)); } typedef struct r123array2x64 threefry2x64_ctr_t; typedef struct r123array2x64 threefry2x64_key_t; typedef struct r123array2x64 threefry2x64_ukey_t; inline threefry2x64_key_t threefry2x64keyinit(threefry2x64_ukey_t uk) { return uk; } inline threefry2x64_ctr_t threefry2x64_R(unsigned int Nrounds, threefry2x64_ctr_t in, threefry2x64_key_t k) __attribute__((always_inline)); inline threefry2x64_ctr_t threefry2x64_R(unsigned int Nrounds, threefry2x64_ctr_t in, threefry2x64_key_t k) { threefry2x64_ctr_t X; uint64_t ks[WCNT2+1]; int i; ; ks[WCNT2] = ((0xA9FC1A22) + (((uint64_t) (0x1BD11BDA)) << 32)); for (i=0;i < WCNT2; i++) { ks[i] = k.v[i]; X.v[i] = in.v[i]; ks[WCNT2] ^= k.v[i]; } X.v[0] += ks[0]; X.v[1] += ks[1]; if(Nrounds>0) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>1) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>2) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>3) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>3) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[1] += 1; } if(Nrounds>4) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_4_0); X.v[1] ^= X.v[0]; } if(Nrounds>5) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_5_0); X.v[1] ^= X.v[0]; } if(Nrounds>6) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_6_0); X.v[1] ^= X.v[0]; } if(Nrounds>7) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_7_0); X.v[1] ^= X.v[0]; } if(Nrounds>7) { X.v[0] += ks[2]; X.v[1] += ks[0]; X.v[1] += 2; } if(Nrounds>8) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>9) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>10) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>11) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>11) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[1] += 3; } if(Nrounds>12) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_4_0); X.v[1] ^= X.v[0]; } if(Nrounds>13) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_5_0); X.v[1] ^= X.v[0]; } if(Nrounds>14) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_6_0); X.v[1] ^= X.v[0]; } if(Nrounds>15) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_7_0); X.v[1] ^= X.v[0]; } if(Nrounds>15) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[1] += 4; } if(Nrounds>16) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>17) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>18) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>19) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>19) { X.v[0] += ks[2]; X.v[1] += ks[0]; X.v[1] += 5; } if(Nrounds>20) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>21) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>22) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>23) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>23) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[1] += 6; } if(Nrounds>24) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_4_0); X.v[1] ^= X.v[0]; } if(Nrounds>25) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_5_0); X.v[1] ^= X.v[0]; } if(Nrounds>26) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_6_0); X.v[1] ^= X.v[0]; } if(Nrounds>27) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_7_0); X.v[1] ^= X.v[0]; } if(Nrounds>27) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[1] += 7; } if(Nrounds>28) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>29) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>30) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>31) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>31) { X.v[0] += ks[2]; X.v[1] += ks[0]; X.v[1] += 8; } return X; } enum { threefry2x64_rounds = 20 }; inline threefry2x64_ctr_t threefry2x64(threefry2x64_ctr_t in, threefry2x64_key_t k) __attribute__((always_inline)); inline threefry2x64_ctr_t threefry2x64(threefry2x64_ctr_t in, threefry2x64_key_t k) { return threefry2x64_R(threefry2x64_rounds, in, k); } typedef struct r123array2x32 threefry2x32_ctr_t; typedef struct r123array2x32 threefry2x32_key_t; typedef struct r123array2x32 threefry2x32_ukey_t; inline threefry2x32_key_t threefry2x32keyinit(threefry2x32_ukey_t uk) { return uk; } inline threefry2x32_ctr_t threefry2x32_R(unsigned int Nrounds, threefry2x32_ctr_t in, threefry2x32_key_t k) __attribute__((always_inline)); inline threefry2x32_ctr_t threefry2x32_R(unsigned int Nrounds, threefry2x32_ctr_t in, threefry2x32_key_t k) { threefry2x32_ctr_t X; uint32_t ks[WCNT2+1]; int i; ; ks[WCNT2] = 0x1BD11BDA; for (i=0;i < WCNT2; i++) { ks[i] = k.v[i]; X.v[i] = in.v[i]; ks[WCNT2] ^= k.v[i]; } X.v[0] += ks[0]; X.v[1] += ks[1]; if(Nrounds>0) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>1) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>2) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>3) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>3) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[1] += 1; } if(Nrounds>4) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_4_0); X.v[1] ^= X.v[0]; } if(Nrounds>5) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_5_0); X.v[1] ^= X.v[0]; } if(Nrounds>6) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_6_0); X.v[1] ^= X.v[0]; } if(Nrounds>7) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_7_0); X.v[1] ^= X.v[0]; } if(Nrounds>7) { X.v[0] += ks[2]; X.v[1] += ks[0]; X.v[1] += 2; } if(Nrounds>8) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>9) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>10) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>11) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>11) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[1] += 3; } if(Nrounds>12) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_4_0); X.v[1] ^= X.v[0]; } if(Nrounds>13) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_5_0); X.v[1] ^= X.v[0]; } if(Nrounds>14) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_6_0); X.v[1] ^= X.v[0]; } if(Nrounds>15) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_7_0); X.v[1] ^= X.v[0]; } if(Nrounds>15) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[1] += 4; } if(Nrounds>16) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>17) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>18) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>19) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>19) { X.v[0] += ks[2]; X.v[1] += ks[0]; X.v[1] += 5; } if(Nrounds>20) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>21) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>22) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>23) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>23) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[1] += 6; } if(Nrounds>24) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_4_0); X.v[1] ^= X.v[0]; } if(Nrounds>25) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_5_0); X.v[1] ^= X.v[0]; } if(Nrounds>26) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_6_0); X.v[1] ^= X.v[0]; } if(Nrounds>27) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_7_0); X.v[1] ^= X.v[0]; } if(Nrounds>27) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[1] += 7; } if(Nrounds>28) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; } if(Nrounds>29) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; } if(Nrounds>30) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; } if(Nrounds>31) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; } if(Nrounds>31) { X.v[0] += ks[2]; X.v[1] += ks[0]; X.v[1] += 8; } return X; } enum { threefry2x32_rounds = 20 }; inline threefry2x32_ctr_t threefry2x32(threefry2x32_ctr_t in, threefry2x32_key_t k) __attribute__((always_inline)); inline threefry2x32_ctr_t threefry2x32(threefry2x32_ctr_t in, threefry2x32_key_t k) { return threefry2x32_R(threefry2x32_rounds, in, k); } typedef struct r123array4x64 threefry4x64_ctr_t; typedef struct r123array4x64 threefry4x64_key_t; typedef struct r123array4x64 threefry4x64_ukey_t; inline threefry4x64_key_t threefry4x64keyinit(threefry4x64_ukey_t uk) { return uk; } inline threefry4x64_ctr_t threefry4x64_R(unsigned int Nrounds, threefry4x64_ctr_t in, threefry4x64_key_t k) __attribute__((always_inline)); inline threefry4x64_ctr_t threefry4x64_R(unsigned int Nrounds, threefry4x64_ctr_t in, threefry4x64_key_t k) { threefry4x64_ctr_t X; uint64_t ks[WCNT4+1]; int i; ; ks[WCNT4] = ((0xA9FC1A22) + (((uint64_t) (0x1BD11BDA)) << 32)); for (i=0;i < WCNT4; i++) { ks[i] = k.v[i]; X.v[i] = in.v[i]; ks[WCNT4] ^= k.v[i]; } X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; if(Nrounds>0) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>1) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>2) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>3) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>3) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 1; } if(Nrounds>4) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>5) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>6) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>7) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>7) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 2; } if(Nrounds>8) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>9) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>10) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>11) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>11) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 3; } if(Nrounds>12) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>13) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>14) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>15) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>15) { X.v[0] += ks[4]; X.v[1] += ks[0]; X.v[2] += ks[1]; X.v[3] += ks[2]; X.v[WCNT4-1] += 4; } if(Nrounds>16) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>17) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>18) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>19) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>19) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; X.v[WCNT4-1] += 5; } if(Nrounds>20) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>21) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>22) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>23) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>23) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 6; } if(Nrounds>24) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>25) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>26) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>27) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>27) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 7; } if(Nrounds>28) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>29) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>30) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>31) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>31) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 8; } if(Nrounds>32) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>33) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>34) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>35) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>35) { X.v[0] += ks[4]; X.v[1] += ks[0]; X.v[2] += ks[1]; X.v[3] += ks[2]; X.v[WCNT4-1] += 9; } if(Nrounds>36) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>37) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>38) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>39) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>39) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; X.v[WCNT4-1] += 10; } if(Nrounds>40) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>41) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>42) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>43) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>43) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 11; } if(Nrounds>44) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>45) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>46) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>47) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>47) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 12; } if(Nrounds>48) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>49) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>50) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>51) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>51) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 13; } if(Nrounds>52) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>53) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>54) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>55) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>55) { X.v[0] += ks[4]; X.v[1] += ks[0]; X.v[2] += ks[1]; X.v[3] += ks[2]; X.v[WCNT4-1] += 14; } if(Nrounds>56) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>57) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>58) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>59) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>59) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; X.v[WCNT4-1] += 15; } if(Nrounds>60) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>61) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>62) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>63) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>63) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 16; } if(Nrounds>64) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>65) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>66) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>67) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>67) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 17; } if(Nrounds>68) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>69) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>70) { X.v[0] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>71) { X.v[0] += X.v[3]; X.v[3] = RotL_64(X.v[3],R_64x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_64(X.v[1],R_64x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>71) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 18; } return X; } enum { threefry4x64_rounds = 20 }; inline threefry4x64_ctr_t threefry4x64(threefry4x64_ctr_t in, threefry4x64_key_t k) __attribute__((always_inline)); inline threefry4x64_ctr_t threefry4x64(threefry4x64_ctr_t in, threefry4x64_key_t k) { return threefry4x64_R(threefry4x64_rounds, in, k); } typedef struct r123array4x32 threefry4x32_ctr_t; typedef struct r123array4x32 threefry4x32_key_t; typedef struct r123array4x32 threefry4x32_ukey_t; inline threefry4x32_key_t threefry4x32keyinit(threefry4x32_ukey_t uk) { return uk; } inline threefry4x32_ctr_t threefry4x32_R(unsigned int Nrounds, threefry4x32_ctr_t in, threefry4x32_key_t k) __attribute__((always_inline)); inline threefry4x32_ctr_t threefry4x32_R(unsigned int Nrounds, threefry4x32_ctr_t in, threefry4x32_key_t k) { threefry4x32_ctr_t X; uint32_t ks[WCNT4+1]; int i; ; ks[WCNT4] = 0x1BD11BDA; for (i=0;i < WCNT4; i++) { ks[i] = k.v[i]; X.v[i] = in.v[i]; ks[WCNT4] ^= k.v[i]; } X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; if(Nrounds>0) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>1) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>2) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>3) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>3) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 1; } if(Nrounds>4) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>5) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>6) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>7) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>7) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 2; } if(Nrounds>8) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>9) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>10) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>11) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>11) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 3; } if(Nrounds>12) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>13) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>14) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>15) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>15) { X.v[0] += ks[4]; X.v[1] += ks[0]; X.v[2] += ks[1]; X.v[3] += ks[2]; X.v[WCNT4-1] += 4; } if(Nrounds>16) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>17) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>18) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>19) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>19) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; X.v[WCNT4-1] += 5; } if(Nrounds>20) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>21) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>22) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>23) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>23) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 6; } if(Nrounds>24) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>25) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>26) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>27) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>27) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 7; } if(Nrounds>28) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>29) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>30) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>31) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>31) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 8; } if(Nrounds>32) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>33) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>34) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>35) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>35) { X.v[0] += ks[4]; X.v[1] += ks[0]; X.v[2] += ks[1]; X.v[3] += ks[2]; X.v[WCNT4-1] += 9; } if(Nrounds>36) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>37) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>38) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>39) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>39) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; X.v[WCNT4-1] += 10; } if(Nrounds>40) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>41) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>42) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>43) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>43) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 11; } if(Nrounds>44) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>45) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>46) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>47) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>47) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 12; } if(Nrounds>48) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>49) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>50) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>51) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>51) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 13; } if(Nrounds>52) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>53) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>54) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>55) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>55) { X.v[0] += ks[4]; X.v[1] += ks[0]; X.v[2] += ks[1]; X.v[3] += ks[2]; X.v[WCNT4-1] += 14; } if(Nrounds>56) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>57) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>58) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>59) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>59) { X.v[0] += ks[0]; X.v[1] += ks[1]; X.v[2] += ks[2]; X.v[3] += ks[3]; X.v[WCNT4-1] += 15; } if(Nrounds>60) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>61) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>62) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>63) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>63) { X.v[0] += ks[1]; X.v[1] += ks[2]; X.v[2] += ks[3]; X.v[3] += ks[4]; X.v[WCNT4-1] += 16; } if(Nrounds>64) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_0_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_0_1); X.v[3] ^= X.v[2]; } if(Nrounds>65) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_1_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_1_1); X.v[1] ^= X.v[2]; } if(Nrounds>66) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_2_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_2_1); X.v[3] ^= X.v[2]; } if(Nrounds>67) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_3_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_3_1); X.v[1] ^= X.v[2]; } if(Nrounds>67) { X.v[0] += ks[2]; X.v[1] += ks[3]; X.v[2] += ks[4]; X.v[3] += ks[0]; X.v[WCNT4-1] += 17; } if(Nrounds>68) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_4_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_4_1); X.v[3] ^= X.v[2]; } if(Nrounds>69) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_5_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_5_1); X.v[1] ^= X.v[2]; } if(Nrounds>70) { X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_6_0); X.v[1] ^= X.v[0]; X.v[2] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_6_1); X.v[3] ^= X.v[2]; } if(Nrounds>71) { X.v[0] += X.v[3]; X.v[3] = RotL_32(X.v[3],R_32x4_7_0); X.v[3] ^= X.v[0]; X.v[2] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x4_7_1); X.v[1] ^= X.v[2]; } if(Nrounds>71) { X.v[0] += ks[3]; X.v[1] += ks[4]; X.v[2] += ks[0]; X.v[3] += ks[1]; X.v[WCNT4-1] += 18; } return X; } enum { threefry4x32_rounds = 20 }; inline threefry4x32_ctr_t threefry4x32(threefry4x32_ctr_t in, threefry4x32_key_t k) __attribute__((always_inline)); inline threefry4x32_ctr_t threefry4x32(threefry4x32_ctr_t in, threefry4x32_key_t k) { return threefry4x32_R(threefry4x32_rounds, in, k); } __kernel void test_philox4x32_7(uint64_t n64, philox4x32_ukey_t uk, philox4x32_ctr_t ctrinit, __global philox4x32_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; philox4x32_ctr_t c, v= { { 0 } }; philox4x32_key_t k=philox4x32keyinit(uk); c = ctrinit; if( 7 == philox4x32_rounds ) { for (i = 0; i < n; ++i) { v = philox4x32_R(philox4x32_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = philox4x32_R(7, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_philox4x32_10(uint64_t n64, philox4x32_ukey_t uk, philox4x32_ctr_t ctrinit, __global philox4x32_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; philox4x32_ctr_t c, v= { { 0 } }; philox4x32_key_t k=philox4x32keyinit(uk); c = ctrinit; if( 10 == philox4x32_rounds ) { for (i = 0; i < n; ++i) { v = philox4x32_R(philox4x32_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = philox4x32_R(10, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_philox2x64_6(uint64_t n64, philox2x64_ukey_t uk, philox2x64_ctr_t ctrinit, __global philox2x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; philox2x64_ctr_t c, v= { { 0 } }; philox2x64_key_t k=philox2x64keyinit(uk); c = ctrinit; if( 6 == philox2x64_rounds ) { for (i = 0; i < n; ++i) { v = philox2x64_R(philox2x64_rounds, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = philox2x64_R(6, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_philox2x64_10(uint64_t n64, philox2x64_ukey_t uk, philox2x64_ctr_t ctrinit, __global philox2x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; philox2x64_ctr_t c, v= { { 0 } }; philox2x64_key_t k=philox2x64keyinit(uk); c = ctrinit; if( 10 == philox2x64_rounds ) { for (i = 0; i < n; ++i) { v = philox2x64_R(philox2x64_rounds, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = philox2x64_R(10, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_philox4x64_7(uint64_t n64, philox4x64_ukey_t uk, philox4x64_ctr_t ctrinit, __global philox4x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; philox4x64_ctr_t c, v= { { 0 } }; philox4x64_key_t k=philox4x64keyinit(uk); c = ctrinit; if( 7 == philox4x64_rounds ) { for (i = 0; i < n; ++i) { v = philox4x64_R(philox4x64_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = philox4x64_R(7, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_philox4x64_10(uint64_t n64, philox4x64_ukey_t uk, philox4x64_ctr_t ctrinit, __global philox4x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; philox4x64_ctr_t c, v= { { 0 } }; philox4x64_key_t k=philox4x64keyinit(uk); c = ctrinit; if( 10 == philox4x64_rounds ) { for (i = 0; i < n; ++i) { v = philox4x64_R(philox4x64_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = philox4x64_R(10, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_threefry2x64_13(uint64_t n64, threefry2x64_ukey_t uk, threefry2x64_ctr_t ctrinit, __global threefry2x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; threefry2x64_ctr_t c, v= { { 0 } }; threefry2x64_key_t k=threefry2x64keyinit(uk); c = ctrinit; if( 13 == threefry2x64_rounds ) { for (i = 0; i < n; ++i) { v = threefry2x64_R(threefry2x64_rounds, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = threefry2x64_R(13, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_threefry2x64_20(uint64_t n64, threefry2x64_ukey_t uk, threefry2x64_ctr_t ctrinit, __global threefry2x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; threefry2x64_ctr_t c, v= { { 0 } }; threefry2x64_key_t k=threefry2x64keyinit(uk); c = ctrinit; if( 20 == threefry2x64_rounds ) { for (i = 0; i < n; ++i) { v = threefry2x64_R(threefry2x64_rounds, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = threefry2x64_R(20, c, k); do { if (2==4) if(!(v.v[2>2?3:0]^v.v[2>2?2:0]^v.v[2>1?1:0]^v.v[0])) ++i; if (2==2) if(!(v.v[2>1?1:0]^v.v[0])) ++i; if (2==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_threefry4x64_12(uint64_t n64, threefry4x64_ukey_t uk, threefry4x64_ctr_t ctrinit, __global threefry4x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; threefry4x64_ctr_t c, v= { { 0 } }; threefry4x64_key_t k=threefry4x64keyinit(uk); c = ctrinit; if( 12 == threefry4x64_rounds ) { for (i = 0; i < n; ++i) { v = threefry4x64_R(threefry4x64_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = threefry4x64_R(12, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_threefry4x64_20(uint64_t n64, threefry4x64_ukey_t uk, threefry4x64_ctr_t ctrinit, __global threefry4x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; threefry4x64_ctr_t c, v= { { 0 } }; threefry4x64_key_t k=threefry4x64keyinit(uk); c = ctrinit; if( 20 == threefry4x64_rounds ) { for (i = 0; i < n; ++i) { v = threefry4x64_R(threefry4x64_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = threefry4x64_R(20, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_threefry4x32_12(uint64_t n64, threefry4x32_ukey_t uk, threefry4x32_ctr_t ctrinit, __global threefry4x32_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; threefry4x32_ctr_t c, v= { { 0 } }; threefry4x32_key_t k=threefry4x32keyinit(uk); c = ctrinit; if( 12 == threefry4x32_rounds ) { for (i = 0; i < n; ++i) { v = threefry4x32_R(threefry4x32_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = threefry4x32_R(12, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_threefry4x32_20(uint64_t n64, threefry4x32_ukey_t uk, threefry4x32_ctr_t ctrinit, __global threefry4x32_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; threefry4x32_ctr_t c, v= { { 0 } }; threefry4x32_key_t k=threefry4x32keyinit(uk); c = ctrinit; if( 20 == threefry4x32_rounds ) { for (i = 0; i < n; ++i) { v = threefry4x32_R(threefry4x32_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = threefry4x32_R(20, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; } __kernel void test_threefry4x64_72(uint64_t n64, threefry4x64_ukey_t uk, threefry4x64_ctr_t ctrinit, __global threefry4x64_ctr_t *ctr) { uint n = (uint)n64; unsigned tid = get_global_id(0); uint i; threefry4x64_ctr_t c, v= { { 0 } }; threefry4x64_key_t k=threefry4x64keyinit(uk); c = ctrinit; if( 72 == threefry4x64_rounds ) { for (i = 0; i < n; ++i) { v = threefry4x64_R(threefry4x64_rounds, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } else { for (i = 0; i < n; ++i) { v = threefry4x64_R(72, c, k); do { if (4==4) if(!(v.v[4>2?3:0]^v.v[4>2?2:0]^v.v[4>1?1:0]^v.v[0])) ++i; if (4==2) if(!(v.v[4>1?1:0]^v.v[0])) ++i; if (4==1) if(!(v.v[0])) ++i; } while(0); c.v[0]++; } } ctr[tid] = v; }
0
0.745269
1
0.745269
game-dev
MEDIA
0.454386
game-dev
0.78156
1
0.78156
TurtleZhong/PoseGraph-Ceres
3,774
src/VISO++/Thirdparty/DBoW2/DUtils/Random.h
/* * File: Random.h * Project: DUtils library * Author: Dorian Galvez-Lopez * Date: April 2010, November 2011 * Description: manages pseudo-random numbers * License: see the LICENSE.txt file * */ #pragma once #ifndef __D_RANDOM__ #define __D_RANDOM__ #include <cstdlib> #include <vector> namespace DUtils { /// Functions to generate pseudo-random numbers class Random { public: class UnrepeatedRandomizer; public: /** * Sets the random number seed to the current time */ static void SeedRand(); /** * Sets the random number seed to the current time only the first * time this function is called */ static void SeedRandOnce(); /** * Sets the given random number seed * @param seed */ static void SeedRand(int seed); /** * Sets the given random number seed only the first time this function * is called * @param seed */ static void SeedRandOnce(int seed); /** * Returns a random number in the range [0..1] * @return random T number in [0..1] */ template <class T> static T RandomValue(){ return (T)rand()/(T)RAND_MAX; } /** * Returns a random number in the range [min..max] * @param min * @param max * @return random T number in [min..max] */ template <class T> static T RandomValue(T min, T max){ return Random::RandomValue<T>() * (max - min) + min; } /** * Returns a random int in the range [min..max] * @param min * @param max * @return random int in [min..max] */ static int RandomInt(int min, int max); /** * Returns a random number from a gaussian distribution * @param mean * @param sigma standard deviation */ template <class T> static T RandomGaussianValue(T mean, T sigma) { // Box-Muller transformation T x1, x2, w, y1; do { x1 = (T)2. * RandomValue<T>() - (T)1.; x2 = (T)2. * RandomValue<T>() - (T)1.; w = x1 * x1 + x2 * x2; } while ( w >= (T)1. || w == (T)0. ); w = sqrt( ((T)-2.0 * log( w ) ) / w ); y1 = x1 * w; return( mean + y1 * sigma ); } private: /// If SeedRandOnce() or SeedRandOnce(int) have already been called static bool m_already_seeded; }; // --------------------------------------------------------------------------- /// Provides pseudo-random numbers with no repetitions class Random::UnrepeatedRandomizer { public: /** * Creates a randomizer that returns numbers in the range [min, max] * @param min * @param max */ UnrepeatedRandomizer(int min, int max); ~UnrepeatedRandomizer(){} /** * Copies a randomizer * @param rnd */ UnrepeatedRandomizer(const UnrepeatedRandomizer& rnd); /** * Copies a randomizer * @param rnd */ UnrepeatedRandomizer& operator=(const UnrepeatedRandomizer& rnd); /** * Returns a random number not given before. If all the possible values * were already given, the process starts again * @return unrepeated random number */ int get(); /** * Returns whether all the possible values between min and max were * already given. If get() is called when empty() is true, the behaviour * is the same than after creating the randomizer * @return true iff all the values were returned */ inline bool empty() const { return m_values.empty(); } /** * Returns the number of values still to be returned * @return amount of values to return */ inline unsigned int left() const { return m_values.size(); } /** * Resets the randomizer as it were just created */ void reset(); protected: /** * Creates the vector with available values */ void createValues(); protected: /// Min of range of values int m_min; /// Max of range of values int m_max; /// Available values std::vector<int> m_values; }; } #endif
0
0.830946
1
0.830946
game-dev
MEDIA
0.255076
game-dev
0.887297
1
0.887297
emileb/OpenGames
13,860
opengames/src/main/jni/Quake/fteqw/ctf/g_trigger.c
/* Copyright (C) 1997-2001 Id Software, Inc. 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "g_local.h" void InitTrigger (edict_t *self) { if (!VectorCompare (self->s.angles, vec3_origin)) G_SetMovedir (self->s.angles, self->movedir); self->solid = SOLID_TRIGGER; self->movetype = MOVETYPE_NONE; gi.setmodel (self, self->model); self->svflags = SVF_NOCLIENT; } // the wait time has passed, so set back up for another activation void multi_wait (edict_t *ent) { ent->nextthink = 0; } // the trigger was just activated // ent->activator should be set to the activator so it can be held through a delay // so wait for the delay time before firing void multi_trigger (edict_t *ent) { if (ent->nextthink) return; // already been triggered G_UseTargets (ent, ent->activator); if (ent->wait > 0) { ent->think = multi_wait; ent->nextthink = level.time + ent->wait; } else { // we can't just remove (self) here, because this is a touch function // called while looping through area links... ent->touch = NULL; ent->nextthink = level.time + FRAMETIME; ent->think = G_FreeEdict; } } void Use_Multi (edict_t *ent, edict_t *other, edict_t *activator) { ent->activator = activator; multi_trigger (ent); } void Touch_Multi (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { if(other->client) { if (self->spawnflags & 2) return; } else if (other->svflags & SVF_MONSTER) { if (!(self->spawnflags & 1)) return; } else return; if (!VectorCompare(self->movedir, vec3_origin)) { vec3_t forward; AngleVectors(other->s.angles, forward, NULL, NULL); if (_DotProduct(forward, self->movedir) < 0) return; } self->activator = other; multi_trigger (self); } /*QUAKED trigger_multiple (.5 .5 .5) ? MONSTER NOT_PLAYER TRIGGERED Variable sized repeatable trigger. Must be targeted at one or more entities. If "delay" is set, the trigger waits some time after activating before firing. "wait" : Seconds between triggerings. (.2 default) sounds 1) secret 2) beep beep 3) large switch 4) set "message" to text string */ void trigger_enable (edict_t *self, edict_t *other, edict_t *activator) { self->solid = SOLID_TRIGGER; self->use = Use_Multi; gi.linkentity (self); } void SP_trigger_multiple (edict_t *ent) { if (ent->sounds == 1) ent->noise_index = gi.soundindex ("misc/secret.wav"); else if (ent->sounds == 2) ent->noise_index = gi.soundindex ("misc/talk.wav"); else if (ent->sounds == 3) ent->noise_index = gi.soundindex ("misc/trigger1.wav"); if (!ent->wait) ent->wait = 0.2; ent->touch = Touch_Multi; ent->movetype = MOVETYPE_NONE; ent->svflags |= SVF_NOCLIENT; if (ent->spawnflags & 4) { ent->solid = SOLID_NOT; ent->use = trigger_enable; } else { ent->solid = SOLID_TRIGGER; ent->use = Use_Multi; } if (!VectorCompare(ent->s.angles, vec3_origin)) G_SetMovedir (ent->s.angles, ent->movedir); gi.setmodel (ent, ent->model); gi.linkentity (ent); } /*QUAKED trigger_once (.5 .5 .5) ? x x TRIGGERED Triggers once, then removes itself. You must set the key "target" to the name of another object in the level that has a matching "targetname". If TRIGGERED, this trigger must be triggered before it is live. sounds 1) secret 2) beep beep 3) large switch 4) "message" string to be displayed when triggered */ void SP_trigger_once(edict_t *ent) { // make old maps work because I messed up on flag assignments here // triggered was on bit 1 when it should have been on bit 4 if (ent->spawnflags & 1) { vec3_t v; VectorMA (ent->mins, 0.5, ent->size, v); ent->spawnflags &= ~1; ent->spawnflags |= 4; gi.dprintf("fixed TRIGGERED flag on %s at %s\n", ent->classname, vtos(v)); } ent->wait = -1; SP_trigger_multiple (ent); } /*QUAKED trigger_relay (.5 .5 .5) (-8 -8 -8) (8 8 8) This fixed size trigger cannot be touched, it can only be fired by other events. */ void trigger_relay_use (edict_t *self, edict_t *other, edict_t *activator) { G_UseTargets (self, activator); } void SP_trigger_relay (edict_t *self) { self->use = trigger_relay_use; } /* ============================================================================== trigger_key ============================================================================== */ /*QUAKED trigger_key (.5 .5 .5) (-8 -8 -8) (8 8 8) A relay trigger that only fires it's targets if player has the proper key. Use "item" to specify the required key, for example "key_data_cd" */ void trigger_key_use (edict_t *self, edict_t *other, edict_t *activator) { int index; if (!self->item) return; if (!activator->client) return; index = ITEM_INDEX(self->item); if (!activator->client->pers.inventory[index]) { if (level.time < self->touch_debounce_time) return; self->touch_debounce_time = level.time + 5.0; gi.centerprintf (activator, "You need the %s", self->item->pickup_name); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/keytry.wav"), 1, ATTN_NORM, 0); return; } gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/keyuse.wav"), 1, ATTN_NORM, 0); if (coop->value) { int player; edict_t *ent; if (strcmp(self->item->classname, "key_power_cube") == 0) { int cube; for (cube = 0; cube < 8; cube++) if (activator->client->pers.power_cubes & (1 << cube)) break; for (player = 1; player <= game.maxclients; player++) { ent = &g_edicts[player]; if (!ent->inuse) continue; if (!ent->client) continue; if (ent->client->pers.power_cubes & (1 << cube)) { ent->client->pers.inventory[index]--; ent->client->pers.power_cubes &= ~(1 << cube); } } } else { for (player = 1; player <= game.maxclients; player++) { ent = &g_edicts[player]; if (!ent->inuse) continue; if (!ent->client) continue; ent->client->pers.inventory[index] = 0; } } } else { activator->client->pers.inventory[index]--; } G_UseTargets (self, activator); self->use = NULL; } void SP_trigger_key (edict_t *self) { if (!st.item) { gi.dprintf("no key item for trigger_key at %s\n", vtos(self->s.origin)); return; } self->item = FindItemByClassname (st.item); if (!self->item) { gi.dprintf("item %s not found for trigger_key at %s\n", st.item, vtos(self->s.origin)); return; } if (!self->target) { gi.dprintf("%s at %s has no target\n", self->classname, vtos(self->s.origin)); return; } gi.soundindex ("misc/keytry.wav"); gi.soundindex ("misc/keyuse.wav"); self->use = trigger_key_use; } /* ============================================================================== trigger_counter ============================================================================== */ /*QUAKED trigger_counter (.5 .5 .5) ? nomessage Acts as an intermediary for an action that takes multiple inputs. If nomessage is not set, t will print "1 more.. " etc when triggered and "sequence complete" when finished. After the counter has been triggered "count" times (default 2), it will fire all of it's targets and remove itself. */ void trigger_counter_use(edict_t *self, edict_t *other, edict_t *activator) { if (self->count == 0) return; self->count--; if (self->count) { if (! (self->spawnflags & 1)) { gi.centerprintf(activator, "%i more to go...", self->count); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } return; } if (! (self->spawnflags & 1)) { gi.centerprintf(activator, "Sequence completed!"); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } self->activator = activator; multi_trigger (self); } void SP_trigger_counter (edict_t *self) { self->wait = -1; if (!self->count) self->count = 2; self->use = trigger_counter_use; } /* ============================================================================== trigger_always ============================================================================== */ /*QUAKED trigger_always (.5 .5 .5) (-8 -8 -8) (8 8 8) This trigger will always fire. It is activated by the world. */ void SP_trigger_always (edict_t *ent) { // we must have some delay to make sure our use targets are present if (ent->delay < 0.2) ent->delay = 0.2; G_UseTargets(ent, ent); } /* ============================================================================== trigger_push ============================================================================== */ #define PUSH_ONCE 1 static int windsound; void trigger_push_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { if (strcmp(other->classname, "grenade") == 0) { VectorScale (self->movedir, self->speed * 10, other->velocity); } else if (other->health > 0) { VectorScale (self->movedir, self->speed * 10, other->velocity); if (other->client) { // don't take falling damage immediately from this VectorCopy (other->velocity, other->client->oldvelocity); if (other->fly_sound_debounce_time < level.time) { other->fly_sound_debounce_time = level.time + 1.5; gi.sound (other, CHAN_AUTO, windsound, 1, ATTN_NORM, 0); } } } if (self->spawnflags & PUSH_ONCE) G_FreeEdict (self); } /*QUAKED trigger_push (.5 .5 .5) ? PUSH_ONCE Pushes the player "speed" defaults to 1000 */ void SP_trigger_push (edict_t *self) { InitTrigger (self); windsound = gi.soundindex ("misc/windfly.wav"); self->touch = trigger_push_touch; if (!self->speed) self->speed = 1000; gi.linkentity (self); } /* ============================================================================== trigger_hurt ============================================================================== */ /*QUAKED trigger_hurt (.5 .5 .5) ? START_OFF TOGGLE SILENT NO_PROTECTION SLOW Any entity that touches this will be hurt. It does dmg points of damage each server frame SILENT supresses playing the sound SLOW changes the damage rate to once per second NO_PROTECTION *nothing* stops the damage "dmg" default 5 (whole numbers only) */ void hurt_use (edict_t *self, edict_t *other, edict_t *activator) { if (self->solid == SOLID_NOT) self->solid = SOLID_TRIGGER; else self->solid = SOLID_NOT; gi.linkentity (self); if (!(self->spawnflags & 2)) self->use = NULL; } void hurt_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { int dflags; if (!other->takedamage) return; if (self->timestamp > level.time) return; if (self->spawnflags & 16) self->timestamp = level.time + 1; else self->timestamp = level.time + FRAMETIME; if (!(self->spawnflags & 4)) { if ((level.framenum % 10) == 0) gi.sound (other, CHAN_AUTO, self->noise_index, 1, ATTN_NORM, 0); } if (self->spawnflags & 8) dflags = DAMAGE_NO_PROTECTION; else dflags = 0; T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, self->dmg, dflags, MOD_TRIGGER_HURT); } void SP_trigger_hurt (edict_t *self) { InitTrigger (self); self->noise_index = gi.soundindex ("world/electro.wav"); self->touch = hurt_touch; if (!self->dmg) self->dmg = 5; if (self->spawnflags & 1) self->solid = SOLID_NOT; else self->solid = SOLID_TRIGGER; if (self->spawnflags & 2) self->use = hurt_use; gi.linkentity (self); } /* ============================================================================== trigger_gravity ============================================================================== */ /*QUAKED trigger_gravity (.5 .5 .5) ? Changes the touching entites gravity to the value of "gravity". 1.0 is standard gravity for the level. */ void trigger_gravity_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { other->gravity = self->gravity; } void SP_trigger_gravity (edict_t *self) { if (st.gravity == 0) { gi.dprintf("trigger_gravity without gravity set at %s\n", vtos(self->s.origin)); G_FreeEdict (self); return; } InitTrigger (self); self->gravity = atoi(st.gravity); self->touch = trigger_gravity_touch; } /* ============================================================================== trigger_monsterjump ============================================================================== */ /*QUAKED trigger_monsterjump (.5 .5 .5) ? Walking monsters that touch this will jump in the direction of the trigger's angle "speed" default to 200, the speed thrown forward "height" default to 200, the speed thrown upwards */ void trigger_monsterjump_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { if (other->flags & (FL_FLY | FL_SWIM) ) return; if (other->svflags & SVF_DEADMONSTER) return; if ( !(other->svflags & SVF_MONSTER)) return; // set XY even if not on ground, so the jump will clear lips other->velocity[0] = self->movedir[0] * self->speed; other->velocity[1] = self->movedir[1] * self->speed; if (!other->groundentity) return; other->groundentity = NULL; other->velocity[2] = self->movedir[2]; } void SP_trigger_monsterjump (edict_t *self) { if (!self->speed) self->speed = 200; if (!st.height) st.height = 200; if (self->s.angles[YAW] == 0) self->s.angles[YAW] = 360; InitTrigger (self); self->touch = trigger_monsterjump_touch; self->movedir[2] = st.height; }
0
0.899538
1
0.899538
game-dev
MEDIA
0.965166
game-dev
0.994238
1
0.994238
WowLegacyCore/HermesProxy
7,173
Framework/IO/StringArguments.cs
/* * Copyright (C) 2012-2020 CypherCore <http://github.com/CypherCore> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Text.RegularExpressions; namespace Framework.IO { public sealed class StringArguments { public StringArguments(string args) { if (!args.IsEmpty()) activestring = args.TrimStart(' '); activeposition = -1; } public bool Empty() { return activestring.IsEmpty(); } public void MoveToNextChar(char c) { for (var i = activeposition; i < activestring.Length; ++i) if (activestring[i] == c) break; } public string NextString(string delimiters = " ") { if (!MoveNext(delimiters)) return ""; return Current; } public bool NextBoolean(string delimiters = " ") { if (!MoveNext(delimiters)) return false; bool value; if (bool.TryParse(Current, out value)) return value; return false; } public char NextChar(string delimiters = " ") { if (!MoveNext(delimiters)) return default; char value; if (char.TryParse(Current, out value)) return value; return default; } public byte NextByte(string delimiters = " ") { if (!MoveNext(delimiters)) return default; byte value; if (byte.TryParse(Current, out value)) return value; return default; } public sbyte NextSByte(string delimiters = " ") { if (!MoveNext(delimiters)) return default; sbyte value; if (sbyte.TryParse(Current, out value)) return value; return default; } public ushort NextUInt16(string delimiters = " ") { if (!MoveNext(delimiters)) return default; ushort value; if (ushort.TryParse(Current, out value)) return value; return default; } public short NextInt16(string delimiters = " ") { if (!MoveNext(delimiters)) return default; short value; if (short.TryParse(Current, out value)) return value; return default; } public uint NextUInt32(string delimiters = " ") { if (!MoveNext(delimiters)) return default; uint value; if (uint.TryParse(Current, out value)) return value; return default; } public int NextInt32(string delimiters = " ") { if (!MoveNext(delimiters)) return default; int value; if (int.TryParse(Current, out value)) return value; return default; } public ulong NextUInt64(string delimiters = " ") { if (!MoveNext(delimiters)) return default; ulong value; if (ulong.TryParse(Current, out value)) return value; return default; } public long NextInt64(string delimiters = " ") { if (!MoveNext(delimiters)) return default; long value; if (long.TryParse(Current, out value)) return value; return default; } public float NextSingle(string delimiters = " ") { if (!MoveNext(delimiters)) return default; float value; if (float.TryParse(Current, out value)) return value; return default; } public double NextDouble(string delimiters = " ") { if (!MoveNext(delimiters)) return default; double value; if (double.TryParse(Current, out value)) return value; return default; } public decimal NextDecimal(string delimiters = " ") { if (!MoveNext(delimiters)) return default; decimal value; if (decimal.TryParse(Current, out value)) return value; return default; } public void AlignToNextChar() { while (activeposition < activestring.Length && activestring[activeposition] != ' ') activeposition++; } public char this[int index] { get { return activestring[index]; } } public string GetString() { return activestring; } public void Reset() { activeposition = -1; Current = null; } bool MoveNext(string delimiters) { //the stringtotokenize was never set: if (activestring == null) return false; //all tokens have already been extracted: if (activeposition == activestring.Length) return false; //bypass delimiters: activeposition++; while (activeposition < activestring.Length && delimiters.IndexOf(activestring[activeposition]) > -1) { activeposition++; } //only delimiters were left, so return null: if (activeposition == activestring.Length) return false; //get starting position of string to return: int startingposition = activeposition; //read until next delimiter: do { activeposition++; } while (activeposition < activestring.Length && delimiters.IndexOf(activestring[activeposition]) == -1); Current = activestring.Substring(startingposition, activeposition - startingposition); return true; } bool Match(string pattern, out Match m) { Regex r = new Regex(pattern); m = r.Match(activestring); return m.Success; } private string activestring; private int activeposition; private string Current; } }
0
0.920712
1
0.920712
game-dev
MEDIA
0.708994
game-dev
0.943372
1
0.943372
EpicSentry/P2ASW
5,606
src/game/server/hl2/extinguisherjet.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "extinguisherjet.h" #include "engine/IEngineSound.h" #include "fire.h" #include "ndebugoverlay.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern ConVar fire_extinguisher_debug; //Networking IMPLEMENT_SERVERCLASS_ST( CExtinguisherJet, DT_ExtinguisherJet ) SendPropInt(SENDINFO(m_bEmit), 1, SPROP_UNSIGNED), SendPropInt(SENDINFO(m_bUseMuzzlePoint), 1, SPROP_UNSIGNED), SendPropInt(SENDINFO(m_nLength), 32, SPROP_UNSIGNED), SendPropInt(SENDINFO(m_nSize), 32, SPROP_UNSIGNED), END_SEND_TABLE() //Save/restore BEGIN_DATADESC( CExtinguisherJet ) //Regular fields DEFINE_FIELD( m_bEmit, FIELD_BOOLEAN ), DEFINE_KEYFIELD( m_bEnabled, FIELD_BOOLEAN, "enabled" ), DEFINE_KEYFIELD( m_nLength, FIELD_INTEGER, "length" ), DEFINE_KEYFIELD( m_nSize, FIELD_INTEGER, "size" ), DEFINE_KEYFIELD( m_nRadius, FIELD_INTEGER, "radius" ), DEFINE_KEYFIELD( m_flStrength,FIELD_FLOAT, "strength" ), DEFINE_FIELD( m_bAutoExtinguish, FIELD_BOOLEAN ), DEFINE_FIELD( m_bUseMuzzlePoint, FIELD_BOOLEAN ), DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ), DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ), DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ), DEFINE_FUNCTION( ExtinguishThink ), END_DATADESC() LINK_ENTITY_TO_CLASS( env_extinguisherjet, CExtinguisherJet ); //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CExtinguisherJet::CExtinguisherJet( void ) { m_bEmit = false; m_bEnabled = false; m_bAutoExtinguish = true; m_nLength = 128; m_nSize = 8; m_flStrength = 0.97f; //FIXME: Stub numbers m_nRadius = 32; // Send to the client even though we don't have a model AddEFlags( EFL_FORCE_CHECK_TRANSMIT ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CExtinguisherJet::Spawn( void ) { Precache(); if ( m_bEnabled ) { TurnOn(); } } void CExtinguisherJet::Precache() { BaseClass::Precache(); PrecacheScriptSound( "ExtinguisherJet.TurnOn" ); PrecacheScriptSound( "ExtinguisherJet.TurnOff" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CExtinguisherJet::TurnOn( void ) { //Turn on sound if ( m_bEmit == false ) { EmitSound( "ExtinguisherJet.TurnOn" ); m_bEnabled = m_bEmit = true; } SetThink( ExtinguishThink ); SetNextThink( gpGlobals->curtime + 0.1f ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CExtinguisherJet::TurnOff( void ) { //Turn off sound if ( m_bEmit ) { EmitSound( "ExtinguisherJet.TurnOff" ); m_bEnabled = m_bEmit = false; } SetThink( NULL ); } //----------------------------------------------------------------------------- // Purpose: // Input : &inputdata - //----------------------------------------------------------------------------- void CExtinguisherJet::InputEnable( inputdata_t &inputdata ) { TurnOn(); } //----------------------------------------------------------------------------- // Purpose: // Input : &inputdata - //----------------------------------------------------------------------------- void CExtinguisherJet::InputDisable( inputdata_t &inputdata ) { TurnOff(); } //----------------------------------------------------------------------------- // Purpose: // Input : &inputdata - //----------------------------------------------------------------------------- void CExtinguisherJet::InputToggle( inputdata_t &inputdata ) { if ( m_bEnabled ) { TurnOff(); } else { TurnOn(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CExtinguisherJet::Think( void ) { CBaseEntity::Think(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CExtinguisherJet::ExtinguishThink( void ) { SetNextThink( gpGlobals->curtime + 0.1f ); if ( m_bEnabled == false ) return; if ( m_bAutoExtinguish == false ) return; Vector vTestPos; Vector vForward, vRight, vUp; AngleVectors( GetAbsAngles(), &vForward ); vTestPos = GetAbsOrigin() + ( vForward * m_nLength ); trace_t tr; UTIL_TraceLine( GetAbsOrigin(), vTestPos, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); //Extinguish the fire where we hit FireSystem_ExtinguishInRadius( tr.endpos, m_nRadius, m_flStrength ); //Debug visualization if ( fire_extinguisher_debug.GetInt() ) { int radius = m_nRadius; NDebugOverlay::Line( GetAbsOrigin(), tr.endpos, 0, 0, 128, false, 0.1f ); NDebugOverlay::Box( GetAbsOrigin(), Vector(-1, -1, -1), Vector(1, 1, 1), 0, 0, 128, false, 0.1f ); NDebugOverlay::Box( tr.endpos, Vector(-2, -2, -2), Vector(2, 2, 2), 0, 0, 128, false, 0.1f ); NDebugOverlay::Box( tr.endpos, Vector(-radius, -radius, -radius), Vector(radius, radius, radius), 0, 0, 255, false, 0.1f ); } }
0
0.913327
1
0.913327
game-dev
MEDIA
0.968611
game-dev
0.865117
1
0.865117
Jondolf/avian
1,135
benches/src/dim3/large_pyramid.rs
use avian3d::{math::Scalar, prelude::*}; use bevy::prelude::*; use super::Benchmark3dPlugins; pub fn create_bench(base_count: usize) -> App { let mut app = App::new(); app.add_plugins((Benchmark3dPlugins, PhysicsPlugins::default())); app.add_systems(Startup, move |commands: Commands| { setup(commands, base_count) }); app } fn setup(mut commands: Commands, base_count: usize) { // Ground commands.spawn(( RigidBody::Static, Collider::cuboid(800.0, 40.0, 800.0), Transform::from_xyz(0.0, -20.0, 0.0), )); let h = 0.5; let box_size = 2.0 * h; let collider = Collider::cuboid(box_size as Scalar, box_size as Scalar, box_size as Scalar); let shift = h; for i in 0..base_count { let y = (2.0 * i as f32 + 1.0) * shift * 0.99; for j in i..base_count { let x = (i as f32 + 1.0) * shift + 2.0 * (j - i) as f32 * shift - h * base_count as f32; commands.spawn(( RigidBody::Dynamic, collider.clone(), Transform::from_xyz(x, y, 0.0), )); } } }
0
0.69143
1
0.69143
game-dev
MEDIA
0.239788
game-dev
0.882519
1
0.882519
mizchi/vibe-hack-and-slash
9,910
rust/src/types.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; use uuid::Uuid; // ブランド型マクロ macro_rules! branded_type { ($name:ident, $inner:ty) => { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct $name($inner); impl $name { pub fn new(value: $inner) -> Self { Self(value) } pub fn value(&self) -> $inner { self.0 } } }; } // ID型の定義 branded_type!(PlayerId, Uuid); branded_type!(ItemId, Uuid); branded_type!(SkillId, Uuid); branded_type!(MonsterId, Uuid); branded_type!(SessionId, Uuid); // 数値型の定義 branded_type!(Level, u32); branded_type!(Health, i32); branded_type!(Damage, i32); branded_type!(Mana, i32); branded_type!(Gold, u64); branded_type!(Experience, u64); // 基本ステータス #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct BaseStats { pub strength: i32, pub intelligence: i32, pub dexterity: i32, pub vitality: i32, } // 要素タイプ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ElementType { Physical, Arcane, Fire, Lightning, Holy, } // 要素耐性 #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct ElementResistance { pub physical: f64, pub arcane: f64, pub fire: f64, pub lightning: f64, pub holy: f64, } impl Default for ElementResistance { fn default() -> Self { Self { physical: 0.0, arcane: 0.0, fire: 0.0, lightning: 0.0, holy: 0.0, } } } // 要素倍率 #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct ElementModifier { pub physical: f64, pub arcane: f64, pub fire: f64, pub lightning: f64, pub holy: f64, } impl Default for ElementModifier { fn default() -> Self { Self { physical: 1.0, arcane: 0.0, fire: 0.0, lightning: 0.0, holy: 0.0, } } } // アイテムレアリティ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ItemRarity { Common, Magic, Rare, Legendary, } // モディファイアタイプ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum ModifierType { IncreaseHealth(i32), LifeSteal(f64), CriticalChance(f64), CriticalDamage(f64), IncreaseMana(i32), ManaRegen(i32), SkillPower(f64), IncreaseStrength(i32), IncreaseIntelligence(i32), IncreaseDexterity(i32), IncreaseVitality(i32), ElementResistance { element: ElementType, value: f64 }, ElementModifier { element: ElementType, multiplier: f64 }, } // アイテムタイプ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ItemType { Weapon, Armor, Accessory, } // 武器タイプ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum WeaponType { Sword, Axe, Staff, Bow, Dagger, } // アイテムタグ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ItemTag { Sword, Axe, Staff, Bow, Dagger, Helm, Gloves, Boots, Belt, Armor, Ring, Amulet, Shield, } // 装備スロット #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum EquipmentSlot { MainHand, OffHand, Helm, Armor, Gloves, Boots, Belt, Ring1, Ring2, Amulet, } // プレイヤークラス #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum PlayerClass { Warrior, Mage, Rogue, Paladin, } // 武器スケーリング #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct WeaponScaling { pub strength: f64, pub intelligence: f64, pub dexterity: f64, } // ベースアイテム #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct BaseItem { pub id: ItemId, pub name: String, pub item_type: ItemType, pub tags: Vec<ItemTag>, pub required_level: Level, pub required_class: Option<Vec<PlayerClass>>, pub base_modifiers: Vec<ModifierType>, pub weapon_type: Option<WeaponType>, pub weapon_unique_skills: Vec<SkillId>, pub weapon_scaling: Option<WeaponScaling>, } // アイテムプレフィックス #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ItemPrefix { pub name: String, pub modifiers: Vec<ModifierType>, } // アイテムサフィックス #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ItemSuffix { pub name: String, pub modifiers: Vec<ModifierType>, } // アイテム #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Item { pub id: ItemId, pub base_item: BaseItem, pub rarity: ItemRarity, pub prefix: Option<ItemPrefix>, pub suffix: Option<ItemSuffix>, pub level: Level, } // キャラクターステータス #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct CharacterStats { pub max_health: Health, pub base_damage: Damage, pub critical_chance: f64, pub critical_damage: f64, pub life_steal: f64, pub mp_regen: Mana, pub element_modifier: ElementModifier, } // バフタイプ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum BuffType { IncreaseStats(BaseStats), IncreaseHealth(Health), IncreaseMana(Mana), IncreaseDamage(f64), IncreaseDefense(f64), IncreaseCritical(f64), IncreaseLifeSteal(f64), ElementResistance { element: ElementType, value: f64 }, } // バフ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Buff { pub id: String, pub name: String, pub buff_type: BuffType, pub duration: i32, pub remaining_turns: i32, } // スキルターゲット #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum SkillTarget { #[serde(rename = "Self")] SelfTarget, Enemy, AllEnemies, } // スキルタイプ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum SkillType { Active, Passive, Aura, } // スキル効果 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum SkillEffect { Damage { base_damage: Damage, scaling: f64, element: ElementType, }, Heal { base_heal: Health, scaling: f64, }, Buff { buff_type: BuffType, duration: i32, }, Debuff { debuff_type: BuffType, duration: i32, }, Summon { monster_id: MonsterId, duration: i32, }, } // スキルトリガー条件 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum SkillTriggerCondition { Always, OnCritical, OnKill, OnLowHealth(f64), OnHighHealth(f64), EveryNTurns(i32), OnBattleStart, OnBattleEnd, } // スキル #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Skill { pub id: SkillId, pub name: String, pub description: String, pub skill_type: SkillType, pub mana_cost: Mana, pub cooldown: i32, pub target_type: SkillTarget, pub effects: Vec<SkillEffect>, pub trigger_conditions: Vec<SkillTriggerCondition>, pub required_level: Level, pub weapon_type: Option<WeaponType>, } // プレイヤー #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Player { pub id: PlayerId, pub name: String, pub class: PlayerClass, pub level: Level, pub current_health: Health, pub current_mana: Mana, pub experience: Experience, pub base_stats: CharacterStats, pub base_attributes: BaseStats, pub equipment: HashMap<EquipmentSlot, Item>, pub inventory: Vec<Item>, pub skills: Vec<Skill>, pub skill_cooldowns: HashMap<SkillId, i32>, pub skill_timers: HashMap<SkillId, i32>, pub active_buffs: Vec<Buff>, pub element_resistance: ElementResistance, pub gold: Gold, } // モンスターティア #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum MonsterTier { Common, Elite, Rare, Boss, Legendary, } // レアリティウェイト #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct RarityWeights { pub common: f64, pub magic: f64, pub rare: f64, pub legendary: f64, } // ルートエントリー #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct LootEntry { pub base_item_id: ItemId, pub drop_chance: f64, pub rarity_weights: RarityWeights, } // モンスター #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Monster { pub id: MonsterId, pub name: String, pub tier: MonsterTier, pub level: Level, pub current_health: Health, pub stats: CharacterStats, pub element_resistance: ElementResistance, pub loot_table: Vec<LootEntry>, } // セッション状態 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum SessionState { InProgress, Paused, Completed, } // セッション #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Session { pub id: SessionId, pub player: Player, pub current_monster: Option<Monster>, pub defeated_count: u32, pub wave: u32, pub state: SessionState, pub started_at: String, // TODO: chrono::DateTime } // バトルイベント #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum BattleEvent { PlayerAttack { damage: Damage, is_critical: bool }, MonsterAttack { damage: Damage }, PlayerHeal { amount: Health }, MonsterDefeated { experience: Experience }, ItemDropped { item: Item }, PlayerLevelUp { new_level: Level }, PlayerDefeated, SkillUsed { skill_name: String }, SkillDamage { skill_name: String, damage: Damage, target_id: MonsterId, target_name: String, }, SkillHeal { skill_name: String, amount: Health, }, ManaRegenerated { amount: Mana }, NotEnoughMana, }
0
0.828682
1
0.828682
game-dev
MEDIA
0.606748
game-dev
0.86571
1
0.86571
Sterberino/open-behavior-trees
1,266
Runtime/Base Node Types/RepeaterNode.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace OpenBehaviorTrees { public class RepeaterNode : DecoratorNode { [Tooltip("If set to true, the repeater will repeat indefinitely.")] public bool repeatForever; [Tooltip("The number of times the repeater node should repeat.")] [DrawIf("repeatForever", true)] public int repeatCount; private int timesRepeated = 0; [Tooltip("The result that is returned when the node has repeated [repeatCount] times.")] public BehaviorTreeNodeResult resultOnComplete = BehaviorTreeNodeResult.success; protected override BehaviorTreeNodeResult Evaluate(BehaviorTree behaviorTree) { if(repeatForever) { child.Tick(behaviorTree); return BehaviorTreeNodeResult.running; } if(timesRepeated < repeatCount) { timesRepeated++; child.Tick(behaviorTree); return BehaviorTreeNodeResult.running; } else { timesRepeated = 0; return resultOnComplete; } } } }
0
0.787135
1
0.787135
game-dev
MEDIA
0.684622
game-dev
0.745081
1
0.745081
Apress/pro-c-sharp-10
1,174
Chapter_05/SimpleClassExample/Car.cs
namespace SimpleClassExample; class Car { // The 'state' of the Car. public string petName; public int currSpeed; // A custom default constructor. public Car() { petName = "Chuck"; currSpeed = 10; } // In this constructor, currSpeed will receive the // default value of an int (zero). //public Car(string pn) //{ // petName = pn; //} //Previous Constructor as expression bodied member public Car(string pn) => petName = pn; // Let caller set the full state of the Car. public Car(string pn, int cs) { petName = pn; currSpeed = cs; } public Car(string pn, int cs, out bool inDanger) { petName = pn; currSpeed = cs; if (cs > 100) { inDanger = true; } else { inDanger = false; } } // The functionality of the Car. // Using the expression-bodied member syntax introduced in C# 6 public void PrintState() => Console.WriteLine("{0} is going {1} MPH.", petName, currSpeed); public void SpeedUp(int delta) => currSpeed += delta; }
0
0.590429
1
0.590429
game-dev
MEDIA
0.358583
game-dev
0.584359
1
0.584359
misyltoad/VPhysics-Jolt
3,208
vphysics_jolt/vjolt_objectpairhash.cpp
#include "cbase.h" #include "vjolt_objectpairhash.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //------------------------------------------------------------------------------------------------- static std::pair< void *, void * > CreateSortedPair( void *pObject0, void *pObject1 ) { return std::make_pair( pObject0 <= pObject1 ? pObject0 : pObject1, pObject0 <= pObject1 ? pObject1 : pObject0 ); } //------------------------------------------------------------------------------------------------- JoltPhysicsObjectPairHash::JoltPhysicsObjectPairHash() { } //------------------------------------------------------------------------------------------------- void JoltPhysicsObjectPairHash::AddObjectPair( void *pObject0, void *pObject1 ) { auto pair = CreateSortedPair( pObject0, pObject1 ); if ( IsObjectPairInHash( pObject0, pObject1 ) ) return; m_PairHashes[ GetHashArrayIndex( PointerHasher{}( pair ) ) ].emplace( pair ); m_ObjectHashes[ GetHashArrayIndex( std::hash< void* >()( pObject0 ) ) ].emplace( pair ); m_ObjectHashes[ GetHashArrayIndex( std::hash< void* >()( pObject1 ) ) ].emplace( pair ); m_Objects.emplace( pObject0 ); m_Objects.emplace( pObject1 ); } void JoltPhysicsObjectPairHash::RemoveObjectPair( void *pObject0, void *pObject1 ) { auto pair = CreateSortedPair( pObject0, pObject1 ); if ( !IsObjectPairInHash( pObject0, pObject1 ) ) return; m_PairHashes[ GetHashArrayIndex( PointerHasher{}( pair ) ) ].erase( pair ); m_ObjectHashes[ GetHashArrayIndex( std::hash< void* >()( pObject0 ) ) ].erase( pair ); m_ObjectHashes[ GetHashArrayIndex( std::hash< void* >()( pObject1 ) ) ].erase( pair ); m_Objects.erase( pObject0 ); m_Objects.erase( pObject1 ); } bool JoltPhysicsObjectPairHash::IsObjectPairInHash( void *pObject0, void *pObject1 ) { auto pair = CreateSortedPair( pObject0, pObject1 ); return Contains( m_PairHashes[GetHashArrayIndex( PointerHasher{}( pair ) )], pair ); } void JoltPhysicsObjectPairHash::RemoveAllPairsForObject( void *pObject0 ) { auto &objectHashes = m_ObjectHashes[ GetHashArrayIndex( std::hash< void* >()( pObject0 ) ) ]; for ( auto it = objectHashes.begin(); it != objectHashes.end(); ) { auto pair = *it++; RemoveObjectPair( pair.first, pair.second ); } } bool JoltPhysicsObjectPairHash::IsObjectInHash( void *pObject0 ) { return Contains( m_Objects, pObject0 ); } //------------------------------------------------------------------------------------------------- int JoltPhysicsObjectPairHash::GetPairCountForObject( void *pObject0 ) { return int( m_Objects.count( pObject0 ) ); } int JoltPhysicsObjectPairHash::GetPairListForObject( void *pObject0, int nMaxCount, void **ppObjectList ) { auto& objectHashes = m_ObjectHashes[GetHashArrayIndex( std::hash< void* >()( pObject0 ) )]; int nCount = 0; for ( auto it = objectHashes.begin(); it != objectHashes.end() && nCount < nMaxCount; ++it, ++nCount ) { auto pair = *it; ppObjectList[ nCount ] = pair.second != pObject0 ? pair.second : pair.first; } return nCount; }
0
0.850132
1
0.850132
game-dev
MEDIA
0.401249
game-dev
0.745234
1
0.745234
abomb4/super-cheat
3,601
scripts/super-cheat/lib.js
exports.loadSound = function (name, setter) { const params = new Packages.arc.assets.loaders.SoundLoader.SoundParameter(); params.loadedCallback = new Packages.arc.assets.AssetLoaderParameters.LoadedCallback({ finishedLoading(asset, str, cls) { // print('1 load sound ' + name + ' from arc'); setter(asset.get(str, cls)); } }); Core.assets.load("sounds/" + name, Packages.arc.audio.Sound, params).loaded = new Cons({ get(a) { // print('2 load sound ' + name + ' from arc'); setter(a); } }); } exports.modName = "invincible-cheat-mod-v8"; exports.newEffect = (lifetime, renderer) => new Effect(lifetime, cons(renderer)); exports.cons2 = (func) => new Cons2({ get: (v1, v2) => func(v1, v2) }); exports.floatc2 = (func) => new Floatc2({ get: (v1, v2) => func(v1, v2) }); exports.boolf2 = (func) => new Boolf2({ get: (v1, v2) => func(v1, v2) }); exports.func = (getter) => new Func({ get: getter }); exports.raycaster = (func) => new Geometry.Raycaster({ accept: func }); exports.intc = (func) => new Intc({ get: func }); exports.intc2 = (func) => new Intc2({ get: func }); exports.floatf = (func) => new Floatf({ get: func }); exports.loadRegion = (name) => { if (Vars.headless === true) { return null } return Core.atlas.find(exports.modName + '-' + name, "error") }; /** * @param {Block} blockType The block type * @param {(block: Block) => Building} buildingCreator * A function receives block type, return Building instance; * don't use prov (this function will use prov once) */ exports.setBuilding = function(blockType, buildingCreator) { blockType.buildType = prov(() => buildingCreator(blockType)); } /** * @param {Block} blockType The block type * @param {Class<Building>} buildingType The building type * @param {Object} overrides Object that as second parameter of extend() */ exports.setBuildingSimple = function(blockType, buildingType, overrides) { blockType.buildType = prov(() => new JavaAdapter(buildingType, overrides, blockType)); } /** * Get message from bundle. * @param {string} type the prefix such as block, unit, mech * @param */ exports.getMessage = function(type, key) { return Core.bundle.get(type + "." + exports.modName + "." + key); } exports.int = (v) => new java.lang.Integer(v); exports.createProbabilitySelector = function() { const objects = []; const probabilities = []; var maxProbabilitySum = 0; return { showProbabilities() { const p = []; var previous = 0; for (var i = 0; i < probabilities.length; i++) { var current = probabilities[i]; p.push(parseFloat(((current - previous) / maxProbabilitySum).toFixed(5))) previous = current; } return p; }, add(obj, probability) { if (!Number.isInteger(probability)) { throw "'probability' must integer." } maxProbabilitySum += probability; objects.push(obj); probabilities.push(maxProbabilitySum); }, random: function() { const random = Math.floor(Math.random() * maxProbabilitySum); // Can use binary search for (var i = 0; i < probabilities.length; i++) { var max = probabilities[i]; if (random < max) { return objects[i]; } } throw "IMPOSSIBLE!!! THIS IS A BUG" } } }
0
0.62651
1
0.62651
game-dev
MEDIA
0.4923
game-dev
0.594428
1
0.594428
Dimbreath/AzurLaneData
4,193
en-US/view/activity/panels/ptawardwindow.lua
slot0 = class("PtAwardWindow") function slot0.Ctor(slot0, slot1, slot2) slot0._tf = slot1 slot0.binder = slot2 slot0.UIlist = UIItemList.New(slot0._tf:Find("window/panel/list"), slot0._tf:Find("window/panel/list/item")) slot0.ptTF = slot0._tf:Find("window/pt") slot0.totalTxt = slot0._tf:Find("window/pt/Text"):GetComponent(typeof(Text)) slot0.totalTitleTxt = slot0._tf:Find("window/pt/title"):GetComponent(typeof(Text)) slot0.totalTitleIcon = slot0._tf:Find("window/pt/icon/image"):GetComponent(typeof(Image)) slot0.closeBtn = slot0._tf:Find("window/top/btnBack") slot0.ptIcon = slot0._tf:Find("window/pt/icon") onButton(slot0.binder, slot0._tf, function () uv0:Hide() end, SFX_PANEL) onButton(slot0.binder, slot0.closeBtn, function () uv0:Hide() end, SFX_PANEL) end function slot0.UpdateList(slot0, slot1, slot2, slot3) slot0.UIlist:make(function (slot0, slot1, slot2) if slot0 == UIItemList.EventUpdate then slot3 = uv0[slot1 + 1] slot4 = uv1[slot1 + 1] if PLATFORM_CODE == PLATFORM_JP then if GetPerceptualSize(uv2.resTitle) > 15 then GetComponent(slot2:Find("target/Text"), typeof(Text)).fontSize = 26 GetComponent(slot2:Find("target/title"), typeof(Text)).fontSize = 26 elseif slot5 > 12 then GetComponent(slot2:Find("target/Text"), typeof(Text)).fontSize = 28 GetComponent(slot2:Find("target/title"), typeof(Text)).fontSize = 28 elseif slot5 > 10 then GetComponent(slot2:Find("target/Text"), typeof(Text)).fontSize = 30 GetComponent(slot2:Find("target/title"), typeof(Text)).fontSize = 30 else GetComponent(slot2:Find("target/Text"), typeof(Text)).fontSize = 32 GetComponent(slot2:Find("target/title"), typeof(Text)).fontSize = 32 end end setText(slot2:Find("title/Text"), "PHASE " .. slot1 + 1) setText(slot2:Find("target/Text"), slot4) if slot2:Find("target/icon") and uv2.resIcon and uv2.resIcon ~= "" then setActive(slot2:Find("target/icon"), true) LoadImageSpriteAsync(uv2.resIcon, slot2:Find("target/icon/image"), false) else setActive(slot2:Find("target/icon"), false) end setText(slot2:Find("target/title"), HXSet.hxLan(uv2.resTitle)) updateDrop(slot2:Find("award"), { type = slot3[1], id = slot3[2], count = slot3[3] }, { hideName = true }) onButton(uv2.binder, slot2:Find("award"), function () uv0.binder:emit(BaseUI.ON_DROP, uv1) end, SFX_PANEL) setActive(slot2:Find("award/mask"), slot1 + 1 <= uv3) end end) slot0.UIlist:align(#slot1) end function slot0.Show(slot0, slot1) slot2 = slot1.dropList slot3 = slot1.targets slot4 = slot1.level slot5 = slot1.count slot6 = slot1.resId slot8 = "" slot0.resIcon = nil if slot1.type == 2 then slot0.cntTitle = i18n("pt_total_count", i18n("pt_cosume", slot8)) slot0.resTitle = i18n("pt_cosume", slot8) slot0.cntTitle = string.gsub(slot0.cntTitle, ":", "") elseif slot7 == 3 then slot0.cntTitle = i18n("pt_ship_now") slot0.resTitle = i18n("pt_ship_goal") elseif slot7 == 4 then slot0.cntTitle = i18n("cumulative_victory_now_tip") slot0.resTitle = i18n("cumulative_victory_target_tip") else slot0.cntTitle = i18n("pt_total_count", slot8) slot0.resTitle = i18n("target_get_tip") slot0.cntTitle = string.gsub(slot0.cntTitle, ":", "") end slot0:updateResIcon(slot1.resId, slot1.resIcon, slot1.type) slot0:UpdateList(slot2, slot3, slot4) slot0.totalTxt.text = slot5 slot0.totalTitleTxt.text = HXSet.hxLan(slot0.cntTitle) Canvas.ForceUpdateCanvases() setActive(slot0._tf, true) end function slot0.updateResIcon(slot0, slot1, slot2, slot3) if slot3 == 2 or slot3 ~= 3 and slot3 ~= 4 then if slot1 then slot0.resIcon = pg.item_data_statistics[id2ItemId(slot1)].icon elseif slot2 then slot0.resIcon = slot2 end if slot0.ptIcon and slot0.resIcon and slot0.resIcon ~= "" then setActive(slot0.ptIcon, true) LoadImageSpriteAsync(slot0.resIcon, slot0.totalTitleIcon, false) else setActive(slot0.ptIcon, false) end end end function slot0.Hide(slot0) setActive(slot0._tf, false) end function slot0.Dispose(slot0) slot0:Hide() removeOnButton(slot0._tf) removeOnButton(slot0.closeBtn) end return slot0
0
0.709082
1
0.709082
game-dev
MEDIA
0.951451
game-dev
0.85372
1
0.85372
microsoft/ZappysPlayground
7,685
Assets/MSPlayground/Core/UI/TooltipStandalone.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using Microsoft.MixedReality.Toolkit; using UnityEngine; using UnityEngine.UI; using UnityEngine.XR.Interaction.Toolkit; namespace MSPlayground.Core.UI { /// <summary> /// Handles the animation states of standalone tooltips. /// Unlike the base tooltip, standalone tips only trigger the animator to fade in when /// the entire rect is in full view for the first time. /// </summary> public class TooltipStandalone : TooltipBase { private enum AnimateInCondition { /// <summary> /// When rect transform is in full view for the first time /// </summary> InFullView = 0, /// <summary> /// XR event trigger on firstSelectEntered /// </summary> OnSelectEnter, /// <summary> /// When the referenced stateful interactable has been clicked /// </summary> OnClick } /// <summary> /// Condition to destroy the gameobject /// </summary> private enum DestroyCondition { /// <summary> /// On animate out (fade) /// </summary> OnAnimateOut = 0, /// <summary> /// On animate out after the first time user expands the tooltip /// </summary> OnAnimateOutAfterExpand, /// <summary> /// Allow gameobject to be active, but still alpha 0 /// </summary> DontDestroy } private const string ANIM_TRIGGER_CAN_ANIMATE_IN = "CanAnimateIn"; private const string ANIM_STATE_HIDDEN = "HideUntilInView"; [Header("Animate In")] [Tooltip("Conditions to animate the tooltip in")] [SerializeField] private AnimateInCondition _animateInCondition = 0; [Tooltip("Wait until this rect transform is in full view of the camera before animating in")] [SerializeField] private RectTransform _rectTransform = null; [Tooltip("Stateful interactable to keep track of for animating in conditions")] [SerializeField] private StatefulInteractable _statefulInteractable = null; [Tooltip("Audio source to play on animate in")] [SerializeField] private AudioSource _audioSource = null; [Header("Destroy Condition")] [Tooltip("Condition to destroy the tooltip")] [SerializeField] private DestroyCondition _destroyCondition = 0; [Header("UI")] [SerializeField] private Image _onGazeSlicedImage = null; /// <summary> /// Has the tooltip animated in at least one time /// </summary> private bool _hasAnimatedInOnce = false; public void Start() { #if VRBUILD if (_skipOnVR) { gameObject.SetActive(false); return; } #endif // Add persistent listeners for animate in condition switch (_animateInCondition) { case AnimateInCondition.OnSelectEnter: if (_statefulInteractable) { _statefulInteractable.firstSelectEntered.AddListener(OnSelectEnter); } break; case AnimateInCondition.OnClick: if (_statefulInteractable) { _statefulInteractable.OnClicked.AddListener(OnStatefulGeneralInteract); } break; } } public void OnEnable() { // Wait for animate in condition switch (_animateInCondition) { case AnimateInCondition.InFullView: if (_rectTransform) { StartCoroutine(WaitUntilInFullView()); } break; } } /// Will happen externally or if parent objects are disabled /// Destroy tooltip as necessary in this case public void OnDisable() { if (_destroyCondition == DestroyCondition.OnAnimateOutAfterExpand && _hasExpanded) { Destroy(gameObject); } else { ResetAnimationState(); } } public override void Reset() { base.Reset(); if (!_rectTransform) { _rectTransform = GetComponent<RectTransform>(); } } private void OnDestroy() { RemoveStatefulEventListener(); } #region Animation Events /// <summary> /// Invoked on fade out animation complete /// </summary> public void OnAnimateOutComplete() { switch (_destroyCondition) { case DestroyCondition.OnAnimateOut: Destroy(gameObject); break; case DestroyCondition.OnAnimateOutAfterExpand: if (_hasExpanded) { Destroy(gameObject); } break; } } /// <summary> /// Invoked on animate in /// </summary> public void OnAnimateIn() { // Only play the animate in SFX the first time to avoid being spammy if (_audioSource && !_hasAnimatedInOnce) { _audioSource.Play(); _hasAnimatedInOnce = true; } } #endregion #region Event Listeners private void OnSelectEnter(SelectEnterEventArgs args) { OnStatefulGeneralInteract(); } private void OnStatefulGeneralInteract() { _animator.SetTrigger(ANIM_TRIGGER_CAN_ANIMATE_IN); RemoveStatefulEventListener(); } #endregion /// <summary> /// Only animate in when the entire rect is in full view within the viewframe /// </summary> private IEnumerator WaitUntilInFullView() { if (!_rectTransform) { yield break; } _animator.Play(ANIM_STATE_HIDDEN); // Force reset animation to hidden state while (!_rectTransform.IsFullyVisibleFrom(Camera.main)) { yield return null; } _animator.SetTrigger(ANIM_TRIGGER_CAN_ANIMATE_IN); } private void RemoveStatefulEventListener() { if (_statefulInteractable) { switch (_animateInCondition) { case AnimateInCondition.OnClick: _statefulInteractable.OnClicked.RemoveListener(OnStatefulGeneralInteract); break; case AnimateInCondition.OnSelectEnter: _statefulInteractable.firstSelectEntered.RemoveListener(OnSelectEnter); break; } } } /// <summary> /// Reset animation state of the tooltip /// </summary> private void ResetAnimationState() { _animator.ResetTrigger(ANIM_TRIGGER_CAN_ANIMATE_IN); base.StopGaze(); _onGazeSlicedImage.fillAmount = 0; } } }
0
0.972059
1
0.972059
game-dev
MEDIA
0.975967
game-dev
0.983169
1
0.983169
TouchController/TouchController
4,358
mod/1.20.6/common-1.20.6/src/mixin/java/top/fifthlight/touchcontroller/mixin/InGameHudMixin.java
package top.fifthlight.touchcontroller.mixin; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.AttackIndicatorStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import org.koin.java.KoinJavaComponent; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import top.fifthlight.touchcontroller.common.event.RenderEvents; import top.fifthlight.touchcontroller.common.model.ControllerHudModel; @Mixin(Gui.class) public abstract class InGameHudMixin { @Shadow @Final private static ResourceLocation CROSSHAIR_ATTACK_INDICATOR_FULL_SPRITE; @Shadow @Final private static ResourceLocation CROSSHAIR_ATTACK_INDICATOR_BACKGROUND_SPRITE; @Shadow @Final private static ResourceLocation CROSSHAIR_ATTACK_INDICATOR_PROGRESS_SPRITE; @Shadow @Final private Minecraft minecraft; @Inject( method = "renderCrosshair", at = @At( value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiGraphics;blitSprite(Lnet/minecraft/resources/ResourceLocation;IIII)V", ordinal = 0 ), cancellable = true ) private void renderCrosshair(GuiGraphics context, float partialTick, CallbackInfo callbackInfo) { boolean shouldRender = RenderEvents.INSTANCE.shouldRenderCrosshair(); if (!shouldRender) { if (this.minecraft.options.attackIndicator().get() == AttackIndicatorStatus.CROSSHAIR) { float attackCooldownProgress = this.minecraft.player.getAttackStrengthScale(0.0f); boolean renderFullTexture = false; if (this.minecraft.crosshairPickEntity != null && this.minecraft.crosshairPickEntity instanceof LivingEntity && attackCooldownProgress >= 1.0f) { renderFullTexture = this.minecraft.player.getCurrentItemAttackStrengthDelay() > 5.0f && this.minecraft.crosshairPickEntity.isAlive(); } int x = context.guiWidth() / 2; int y = context.guiHeight() / 2; if (renderFullTexture) { context.blitSprite(CROSSHAIR_ATTACK_INDICATOR_FULL_SPRITE, x - 8, y - 8, 16, 16); } else if (attackCooldownProgress < 1.0f) { int progress = (int) (attackCooldownProgress * 17.0f); context.blitSprite(CROSSHAIR_ATTACK_INDICATOR_BACKGROUND_SPRITE, x - 8, y - 2, 16, 4); context.blitSprite(CROSSHAIR_ATTACK_INDICATOR_PROGRESS_SPRITE, 16, 4, 0, 0, x - 8, y - 2, progress, 4); } } RenderSystem.defaultBlendFunc(); RenderSystem.disableBlend(); callbackInfo.cancel(); } } @Inject( method = "renderItemHotbar", at = @At( value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;popPose()V", ordinal = 0 ) ) private void renderHotbar(GuiGraphics context, float partialTick, CallbackInfo ci) { var player = minecraft.player; if (player != null) { var controllerHudModel = (ControllerHudModel) KoinJavaComponent.get(ControllerHudModel.class); var inventory = controllerHudModel.getResult().getInventory(); var slots = inventory.getSlots(); var x = (context.guiWidth() - 182) / 2 + 1; var y = context.guiHeight() - 22 + 1; for (int i = 0; i < 9; i++) { var stack = player.getInventory().getItem(i); if (stack.isEmpty()) { continue; } var slot = slots[i]; var progress = slot.getProgress(); var height = (int) (16 * progress); context.fill(x + 20 * i + 2, y + 18 - height, x + 20 * i + 18, y + 18, 0xFF00BB00); } } } }
0
0.864658
1
0.864658
game-dev
MEDIA
0.961551
game-dev
0.975332
1
0.975332
demoth/jake2
16,527
game/src/main/kotlin/jake2/game/miscEntities.kt
package jake2.game import jake2.game.adapters.SuperAdapter.Companion.registerDie import jake2.game.adapters.SuperAdapter.Companion.registerThink import jake2.game.adapters.SuperAdapter.Companion.registerTouch import jake2.game.adapters.SuperAdapter.Companion.registerUse import jake2.game.components.MoveInfo import jake2.game.components.addComponent import jake2.game.components.getComponent import jake2.qcommon.Defines import jake2.qcommon.math.Vector3f import jake2.qcommon.util.Lib import jake2.qcommon.util.Math3D /* * QUAKED misc_explobox (0 .5 .8) (-16 -16 0) (16 16 40) * Large exploding barrel. You can override its mass (400), health (10), and dmg (150). */ fun miscExplobox(self: GameEntity, game: GameExportsImpl) { if (game.skipForDeathmatch(self)) return game.gameImports.modelindex("models/objects/debris1/tris.md2") game.gameImports.modelindex("models/objects/debris2/tris.md2") game.gameImports.modelindex("models/objects/debris3/tris.md2") self.solid = Defines.SOLID_BBOX self.movetype = GameDefines.MOVETYPE_STEP self.model = "models/objects/barrels/tris.md2" self.s.modelindex = game.gameImports.modelindex(self.model) Math3D.VectorSet(self.mins, -16f, -16f, 0f) Math3D.VectorSet(self.maxs, 16f, 16f, 40f) if (self.mass == 0) self.mass = 400 if (self.health == 0) self.health = 10 if (self.dmg == 0) self.dmg = 150 self.die = miscExploboxDelayedExplode self.takedamage = Defines.DAMAGE_YES self.monsterinfo.aiflags = GameDefines.AI_NOSTEP self.touch = miscExploboxPush self.think.action = M.M_droptofloor self.think.nextTime = game.level.time + 2 * Defines.FRAMETIME game.gameImports.linkentity(self) } private val miscExploboxDelayedExplode = registerDie("barrel_delay") { self, _, attacker, _, _, game -> self.takedamage = Defines.DAMAGE_NO self.think.nextTime = game.level.time + 2 * Defines.FRAMETIME self.think.action = miscExploboxExplode self.activator = attacker } // pushes the barrel forward private val miscExploboxPush = registerTouch("barrel_touch") { self, other, _, _, game -> if (other.groundentity == null || other.groundentity === self) return@registerTouch val ratio = other.mass.toFloat() / self.mass.toFloat() val v = floatArrayOf(0f, 0f, 0f) Math3D.VectorSubtract(self.s.origin, other.s.origin, v) M.M_walkmove(self, Math3D.vectoyaw(v), 20 * ratio * Defines.FRAMETIME, game) } private val miscExploboxExplode = registerThink("barrel_explode") { self, game -> val oldOrigin = floatArrayOf(0f, 0f, 0f) GameCombat.T_RadiusDamage(self, self.activator, self.dmg.toFloat(), null, (self.dmg + 40).toFloat(), GameDefines.MOD_BARREL, game) Math3D.VectorCopy(self.s.origin, oldOrigin) Math3D.VectorMA(self.absmin, 0.5f, self.size, self.s.origin) // a few big chunks var speed = 1.5f * self.dmg.toFloat() / 200.0f val origin = floatArrayOf(0f, 0f, 0f) repeat(2) { origin[0] = self.s.origin[0] + Lib.crandom() * self.size[0] origin[1] = self.s.origin[1] + Lib.crandom() * self.size[1] origin[2] = self.s.origin[2] + Lib.crandom() * self.size[2] GameMisc.ThrowDebris(self, "models/objects/debris1/tris.md2", speed, origin, game) } // bottom corners speed = 1.75f * self.dmg.toFloat() / 200.0f Math3D.VectorCopy(self.absmin, origin) GameMisc.ThrowDebris(self, "models/objects/debris3/tris.md2", speed, origin, game) Math3D.VectorCopy(self.absmin, origin) origin[0] += self.size[0] GameMisc.ThrowDebris(self, "models/objects/debris3/tris.md2", speed, origin, game) Math3D.VectorCopy(self.absmin, origin) origin[1] += self.size[1] GameMisc.ThrowDebris(self, "models/objects/debris3/tris.md2", speed, origin, game) Math3D.VectorCopy(self.absmin, origin) origin[0] += self.size[0] origin[1] += self.size[1] GameMisc.ThrowDebris(self, "models/objects/debris3/tris.md2", speed, origin, game) // a bunch of little chunks speed = 2 * self.dmg.toFloat() / 200.0f repeat(8) { origin[0] = self.s.origin[0] + Lib.crandom() * self.size[0] origin[1] = self.s.origin[1] + Lib.crandom() * self.size[1] origin[2] = self.s.origin[2] + Lib.crandom() * self.size[2] GameMisc.ThrowDebris(self, "models/objects/debris2/tris.md2", speed, origin, game) } Math3D.VectorCopy(oldOrigin, self.s.origin) if (self.groundentity != null) GameMisc.BecomeExplosion2(self, game) else GameMisc.BecomeExplosion1(self, game) true } /* * QUAKED misc_blackhole (1 .5 0) (-8 -8 -8) (8 8 8) * * Disappears when used. */ fun miscBlackhole(self: GameEntity, game: GameExportsImpl) { self.movetype = GameDefines.MOVETYPE_NONE self.solid = Defines.SOLID_NOT Math3D.VectorSet(self.mins, -64f, -64f, 0f) Math3D.VectorSet(self.maxs, 64f, 64f, 8f) self.s.modelindex = game.gameImports.modelindex("models/objects/black/tris.md2") self.s.renderfx = Defines.RF_TRANSLUCENT self.use = miscBlackholeDisappear self.think.action = miscBlackholeThink self.think.nextTime = game.level.time + 2 * Defines.FRAMETIME game.gameImports.linkentity(self) } private val miscBlackholeThink = registerThink("misc_blackhole_think") { self, game -> if (++self.s.frame >= 19) { self.s.frame = 0 } self.think.nextTime = game.level.time + Defines.FRAMETIME true } private val miscBlackholeDisappear = registerUse("misc_blackhole_use") { self, _, _, game -> game.freeEntity(self) } /* * QUAKED misc_banner (1 .5 0) (-4 -4 -4) (4 4 4) * The origin is the bottom of the banner. * The banner is 128 tall. */ fun miscBanner(self: GameEntity, game: GameExportsImpl) { self.movetype = GameDefines.MOVETYPE_NONE self.solid = Defines.SOLID_NOT self.s.modelindex = game.gameImports.modelindex("models/objects/banner/tris.md2") self.s.frame = Lib.rand() % 16 game.gameImports.linkentity(self) self.think.action = bannerThink self.think.nextTime = game.level.time + Defines.FRAMETIME } private val bannerThink = registerThink("misc_banner_think") { self, game -> self.s.frame = (self.s.frame + 1) % 16 self.think.nextTime = game.level.time + Defines.FRAMETIME true } /* * QUAKED misc_gib_arm (1 0 0) (-8 -8 -8) (8 8 8) * Intended for use with the target_spawner */ fun miscGibArm(self: GameEntity, game: GameExportsImpl) { initGib(self, game, "arm") } /* * QUAKED misc_gib_leg (1 0 0) (-8 -8 -8) (8 8 8) * Intended for use with the target_spawner */ fun miscGibLeg(self: GameEntity, game: GameExportsImpl) { initGib(self, game, "leg") } /* * QUAKED misc_gib_head (1 0 0) (-8 -8 -8) (8 8 8) * Intended for use with the target_spawner */ fun miscGibHead(self: GameEntity, game: GameExportsImpl) { initGib(self, game, "head") } private fun initGib(ent: GameEntity, game: GameExportsImpl, model: String) { game.gameImports.setmodel(ent, "models/objects/gibs/$model/tris.md2") ent.solid = Defines.SOLID_NOT ent.s.effects = ent.s.effects or Defines.EF_GIB ent.takedamage = Defines.DAMAGE_YES ent.die = dieFreeEntity ent.movetype = GameDefines.MOVETYPE_TOSS ent.svflags = ent.svflags or Defines.SVF_MONSTER ent.deadflag = GameDefines.DEAD_DEAD ent.avelocity[0] = Lib.random() * 200 ent.avelocity[1] = Lib.random() * 200 ent.avelocity[2] = Lib.random() * 200 ent.think.action = GameUtil.G_FreeEdictA ent.think.nextTime = game.level.time + 30 game.gameImports.linkentity(ent) } private val dieFreeEntity = registerDie("die-free-entity") { self, _, _, _, _, game -> game.freeEntity(self) } /* * QUAKED misc_satellite_dish (1 .5 0) (-64 -64 0) (64 64 128) */ fun miscSatelliteDish(self: GameEntity, game: GameExportsImpl) { self.movetype = GameDefines.MOVETYPE_NONE self.solid = Defines.SOLID_BBOX Math3D.VectorSet(self.mins, -64f, -64f, 0f) Math3D.VectorSet(self.maxs, 64f, 64f, 128f) self.s.modelindex = game.gameImports.modelindex("models/objects/satellite/tris.md2") self.use = miscSatelliteDishUse game.gameImports.linkentity(self) } private val miscSatelliteDishUse = registerUse("misc_satellite_dish_use") { self, other, activator, game -> self.s.frame = 0 self.think.action = miscDishRotate self.think.nextTime = game.level.time + Defines.FRAMETIME } private val miscDishRotate = registerThink("misc_satellite_dish_think") { self, game -> self.s.frame++ if (self.s.frame < 38) self.think.nextTime = game.level.time + Defines.FRAMETIME true } /* * QUAKED misc_deadsoldier (1 .5 0) (-16 -16 0) (16 16 16) * ON_BACK * ON_STOMACH * BACK_DECAP * FETAL_POS * SIT_DECAP * IMPALED * This is the dead player model. * Comes in 6 exciting different poses! */ // todo: extract spawnflags fun miscDeadSoldier(self: GameEntity, game: GameExportsImpl) { if (game.gameCvars.deathmatch.value != 0f) { // auto-remove for deathmatch game.freeEntity(self) return } self.movetype = GameDefines.MOVETYPE_NONE self.solid = Defines.SOLID_BBOX self.s.modelindex = game.gameImports.modelindex("models/deadbods/dude/tris.md2") // Defaults to frame 0 self.s.frame = if (self.spawnflags and 2 != 0) 1 else if (self.spawnflags and 4 != 0) 2 else if (self.spawnflags and 8 != 0) 3 else if (self.spawnflags and 16 != 0) 4 else if (self.spawnflags and 32 != 0) 5 else 0 Math3D.VectorSet(self.mins, -16f, -16f, 0f) Math3D.VectorSet(self.maxs, 16f, 16f, 16f) self.deadflag = GameDefines.DEAD_DEAD self.takedamage = Defines.DAMAGE_YES self.svflags = self.svflags or (Defines.SVF_MONSTER or Defines.SVF_DEADMONSTER) self.die = miscDeadSoldierDieAdapter self.monsterinfo.aiflags = self.monsterinfo.aiflags or GameDefines.AI_GOOD_GUY game.gameImports.linkentity(self) } private val miscDeadSoldierDieAdapter = registerDie("misc_deadsoldier_die") { self, inflictor, attacker, damage, point, game -> if (self.health > -80) return@registerDie game.gameImports.sound(self, Defines.CHAN_BODY, game.gameImports.soundindex("misc/udeath.wav"), 1f, Defines.ATTN_NORM.toFloat(), 0f) repeat(3) { GameMisc.ThrowGib(self, "models/objects/gibs/sm_meat/tris.md2", damage, GameDefines.GIB_ORGANIC, game) } GameMisc.ThrowHead(self, "models/objects/gibs/head2/tris.md2", damage, GameDefines.GIB_ORGANIC, game) } /* * QUAKED misc_viper_bomb (1 0 0) (-8 -8 -8) (8 8 8) "dmg" how much boom * should the bomb make? */ fun miscViperBomb(self: GameEntity, game: GameExportsImpl) { self.movetype = GameDefines.MOVETYPE_NONE self.solid = Defines.SOLID_NOT Math3D.VectorSet(self.mins, -8f, -8f, -8f) Math3D.VectorSet(self.maxs, 8f, 8f, 8f) self.s.modelindex = game.gameImports.modelindex("models/objects/bomb/tris.md2") if (self.dmg == 0) self.dmg = 1000 self.use = miscViperBombUse self.svflags = self.svflags or Defines.SVF_NOCLIENT self.addComponent(MoveInfo()) game.gameImports.linkentity(self) } private val miscViperBombUse = registerUse("misc_viper_bomb_use") { self, other, activator, game -> self.solid = Defines.SOLID_BBOX self.svflags = self.svflags and Defines.SVF_NOCLIENT.inv() self.s.effects = self.s.effects or Defines.EF_ROCKET self.use = null self.movetype = GameDefines.MOVETYPE_TOSS self.think.prethink = miscViperBombPrethink self.touch = miscViperBombTouch self.activator = activator // get the ship reference (so it sticks to the first found ship?) val es = GameBase.G_Find(null, GameBase.findByClassName, "misc_viper", game) var viper: GameEntity? = null if (es != null) viper = es.o // the bomb goes same direction as the viper ship val viperMove: MoveInfo = viper!!.getComponent()!! self.velocity = (viperMove.dir * viperMove.speed).toArray() self.getComponent<MoveInfo>()!!.dir = viperMove.dir.copy() self.timestamp = game.level.time } /** * Rotates the bomb to imitate the drag of the tail * todo: why it's prethink? */ private val miscViperBombPrethink = registerThink("misc_viper_bomb_prethink") { self, game -> self.groundentity = null var diff: Float = self.timestamp - game.level.time if (diff < -1.0) diff = -1.0f val result = self.getComponent<MoveInfo>()!!.dir * (1.0f + diff) val v = Vector3f(result.x, result.y, diff) diff = self.s.angles[2] self.s.angles = v.toAngles() self.s.angles[2] = diff + 10 true } private val miscViperBombTouch = registerTouch("misc_viper_bomb_touch") { self, other, plane, surf, game -> GameUtil.G_UseTargets(self, self.activator, game) self.s.origin[2] = self.absmin[2] + 1 GameCombat.T_RadiusDamage(self, self, self.dmg.toFloat(), null, (self.dmg + 40).toFloat(), GameDefines.MOD_BOMB, game) GameMisc.BecomeExplosion2(self, game) } /* * QUAKED misc_bigviper (1 .5 0) (-176 -120 -24) (176 120 72) * This is a large stationary viper as seen in Paul's intro */ fun miscBigViper(self: GameEntity, game: GameExportsImpl) { self.movetype = GameDefines.MOVETYPE_NONE self.solid = Defines.SOLID_BBOX Math3D.VectorSet(self.mins, -176f, -120f, -24f) Math3D.VectorSet(self.maxs, 176f, 120f, 72f) self.s.modelindex = game.gameImports.modelindex("models/ships/bigviper/tris.md2") game.gameImports.linkentity(self) } /** * QUAKED misc_teleporter (1 0 0) (-32 -32 -24) (32 32 -16) * Stepping onto this disc will teleport player to the targeted misc_teleporter_dest object. */ fun miscTeleporter(self: GameEntity, game: GameExportsImpl) { if (self.target == null) { game.gameImports.dprintf("teleporter without a target.\n") game.freeEntity(self) return } game.gameImports.setmodel(self, "models/objects/dmspot/tris.md2") self.s.skinnum = 1 self.s.effects = Defines.EF_TELEPORTER self.s.sound = game.gameImports.soundindex("world/amb10.wav") self.solid = Defines.SOLID_BBOX Math3D.VectorSet(self.mins, -32f, -32f, -24f) Math3D.VectorSet(self.maxs, 32f, 32f, -16f) game.gameImports.linkentity(self) val trigger = game.G_Spawn() trigger.touch = teleporterTriggerTouch trigger.solid = Defines.SOLID_TRIGGER trigger.target = self.target trigger.owner = self Math3D.VectorCopy(self.s.origin, trigger.s.origin) Math3D.VectorSet(trigger.mins, -8f, -8f, 8f) Math3D.VectorSet(trigger.maxs, 8f, 8f, 24f) game.gameImports.linkentity(trigger) } private val teleporterTriggerTouch = registerTouch("teleporter_touch") { self, other, plane, surf, game -> val client = other.client ?: return@registerTouch val dest = GameBase.G_Find(null, GameBase.findByTargetName, self.target, game)?.o if (dest == null) { game.gameImports.dprintf("Couldn't find destination\n") return@registerTouch } // unlink to make sure it can't possibly interfere with KillBox game.gameImports.unlinkentity(other) Math3D.VectorCopy(dest.s.origin, other.s.origin) Math3D.VectorCopy(dest.s.origin, other.s.old_origin) other.s.origin[2] += 10f // clear the velocity and hold them in place briefly Math3D.VectorClear(other.velocity) client.playerState.pmove.pm_time = (160 shr 3).toByte() // hold time client.playerState.pmove.pm_flags = (client.playerState.pmove.pm_flags.toInt() or Defines.PMF_TIME_TELEPORT).toByte() // draw the teleport splash at source and on the player self.owner.s.event = Defines.EV_PLAYER_TELEPORT other.s.event = Defines.EV_PLAYER_TELEPORT // set angles for (i in 0..2) { client.playerState.pmove.delta_angles[i] = Math3D.ANGLE2SHORT(dest.s.angles[i]- client.resp.cmd_angles[i]).toShort() } Math3D.VectorClear(other.s.angles) Math3D.VectorClear(client.playerState.viewangles) Math3D.VectorClear(client.v_angle) // kill anything at the destination GameUtil.KillBox(other, game) game.gameImports.linkentity(other) } /* * QUAKED misc_teleporter_dest (1 0 0) (-32 -32 -24) (32 32 -16) * Point teleporters at these. */ fun miscTeleporterDest(self: GameEntity, game: GameExportsImpl) { game.gameImports.setmodel(self, "models/objects/dmspot/tris.md2") self.s.skinnum = 0 self.solid = Defines.SOLID_BBOX Math3D.VectorSet(self.mins, -32f, -32f, -24f) Math3D.VectorSet(self.maxs, 32f, 32f, -16f) game.gameImports.linkentity(self) }
0
0.771442
1
0.771442
game-dev
MEDIA
0.752127
game-dev
0.978291
1
0.978291
generatives/Wrecker
5,138
ClunkerGO/Toolbar/VoxelAddingTool.cs
using System; using System.Collections.Generic; using System.Numerics; using System.Text; using Clunker.Graphics; using Clunker.Geometry; using Clunker.SceneGraph; using Clunker.SceneGraph.ComponentInterfaces; using Clunker.SceneGraph.Core; using Clunker.Voxels; using ImGuiNET; namespace Clunker.Tooling { public abstract class VoxelAddingTool : VoxelEditingTool, IComponentEventListener { private VoxelGrid _displayGrid; private static MaterialInstance _materialInstance; private VoxelTypes _types; protected VoxelSide Orientation { get; private set; } protected ushort VoxelType { get; private set; } public VoxelAddingTool(ushort voxelType, VoxelTypes types, MaterialInstance materialInstance) { VoxelType = voxelType; _types = types; _materialInstance = materialInstance; } public void ComponentStarted() { if(_displayGrid == null) { _displayGrid = new VoxelGrid(new VoxelGridData(1, 1, 1, 1), new Dictionary<Vector3i, GameObject>()); var gameObject = new GameObject($"{Name} Display Object"); gameObject.Transform.InheiritParentTransform = false; gameObject.AddComponent(_displayGrid); gameObject.AddComponent(new VoxelMeshRenderable(_types, _materialInstance)); GameObject.AddChild(_displayGrid.GameObject); } _displayGrid.GameObject.IsActive = true; } public void ComponentStopped() { _displayGrid.GameObject.IsActive = false; } protected override void DoVoxelAction(VoxelSpace space, Vector3 hitLocation, Vector3i index) { var addIndex = CalculateAddIndex(space, hitLocation, index); if(addIndex.HasValue) { AddVoxel(space, addIndex.Value); } } protected override void DrawVoxelChange(VoxelSpace space, Vector3 hitLocation, Vector3i index) { if(space == null) { _displayGrid.GameObject.IsActive = false; } else { _displayGrid.GameObject.IsActive = true; var displayVoxel = _displayGrid.GetVoxel(new Vector3i(0, 0, 0)); var newVoxel = new Voxel() { Exists = true, BlockType = VoxelType, Orientation = Orientation }; if (displayVoxel != newVoxel) { _displayGrid.SetVoxel(new Vector3i(0, 0, 0), newVoxel); } var addIndex = CalculateAddIndex(space, hitLocation, index); if (addIndex.HasValue) { var localPosition = addIndex.Value * space.VoxelSize; var worldPosition = space.GameObject.Transform.GetWorld(localPosition); _displayGrid.GameObject.Transform.Position = worldPosition; _displayGrid.GameObject.Transform.Orientation = space.GameObject.Transform.WorldOrientation; } } } private Vector3i? CalculateAddIndex(VoxelSpace space, Vector3 hitLocation, Vector3i index) { var size = space.VoxelSize; var voxelLocation = index * size; var relativeLocation = space.GameObject.Transform.GetLocal(hitLocation); if (NearlyEqual(relativeLocation.X, voxelLocation.X)) { return new Vector3i(index.X - 1, index.Y, index.Z); } else if (NearlyEqual(relativeLocation.X, voxelLocation.X + size)) { return new Vector3i(index.X + 1, index.Y, index.Z); } else if (NearlyEqual(relativeLocation.Y, voxelLocation.Y)) { return new Vector3i(index.X, index.Y - 1, index.Z); } else if (NearlyEqual(relativeLocation.Y, voxelLocation.Y + size)) { return new Vector3i(index.X, index.Y + 1, index.Z); } else if (NearlyEqual(relativeLocation.Z, voxelLocation.Z)) { return new Vector3i(index.X, index.Y, index.Z - 1); } else if (NearlyEqual(relativeLocation.Z, voxelLocation.Z + size)) { return new Vector3i(index.X, index.Y, index.Z + 1); } else { return null; } } public override void BuildMenu() { var sides = Enum.GetNames(typeof(VoxelSide)); var selectedOrientation = (int)Orientation; ImGui.Combo("Orientation", ref selectedOrientation, sides, sides.Length); Orientation = (VoxelSide)selectedOrientation; } public abstract void AddVoxel(VoxelSpace space, Vector3i index); public static bool NearlyEqual(float f1, float f2) => System.Math.Abs(f1 - f2) < 0.01; } }
0
0.838816
1
0.838816
game-dev
MEDIA
0.874057
game-dev
0.870779
1
0.870779
PacktPublishing/Mastering-Cpp-Game-Animation-Programming
9,630
chapter08/01_opengl_collisions/quadtree/Quadtree.cpp
#include <algorithm> #include "Quadtree.h" #include "Logger.h" QuadTree::QuadTree(std::shared_ptr<BoundingBox2D> rootBox, int threshold, int maxDepth) : mRootBoundingBox(*rootBox), mThreshold(threshold), mMaxDepth(maxDepth) { mRootNode = std::make_shared<QuadTreeNode>(); } bool QuadTree::isLeaf(const std::shared_ptr<QuadTreeNode> node) { return node && !node->childs[0]; } BoundingBox2D QuadTree::getChildQuadrant(BoundingBox2D parentBox, int quadrantId) { glm::vec2 origin = parentBox.getTopLeft(); glm::vec2 childSize = parentBox.getSize() / 2.0f; /* Quadrants: * +---+---+ +----+----+ * | 0 | 1 | | NW | NE | * +---+---+ +----+----+ * | 2 | 3 | | SW | SE | * +---+---+ +----+----+ */ switch(quadrantId) { case 0: return BoundingBox2D(origin, childSize); break; case 1: return BoundingBox2D(glm::vec2(origin.x + childSize.x, origin.y), childSize); break; case 2: return BoundingBox2D(glm::vec2(origin.x, origin.y + childSize.y), childSize); break; case 3: return BoundingBox2D(origin + childSize, childSize); break; default: Logger::log(1, "%s error: invalid quadrant id %i\n", __FUNCTION__, quadrantId); return BoundingBox2D(); } } int QuadTree::getQuadrantId(BoundingBox2D nodeBox, BoundingBox2D valueBox) { glm::vec2 center = nodeBox.getCenter(); /* West */ if (valueBox.getRight() < center.x) { if (valueBox.getBottom() < center.y) { /* NW */ return 0; } else if (valueBox.getTopLeft().y >= center.y) { /* SW */ return 2; } else { /* not found */ return -1; } /* East */ } else if (valueBox.getTopLeft().x >= center.x) { if (valueBox.getBottom() < center.y) { /* NE */ return 1; } else if ( valueBox.getTopLeft().y >= center.y) { /* SE */ return 3; } else { /* not found */ return -1; } } else { /* not found */ return -1; } } void QuadTree::add(int instanceId) { /* do not add instance when outside of quadtree */ if (!mRootBoundingBox.intersects(mInstanceGetBoundingBox2DCallbackFunction(instanceId))) { return; } add(mRootNode, 0, mRootBoundingBox, instanceId); } void QuadTree::add(std::shared_ptr<QuadTreeNode> node, int depth, BoundingBox2D box, int instanceId) { if (!box.intersects(mInstanceGetBoundingBox2DCallbackFunction(instanceId))) { Logger::log(1, "%s error: current quadtree node bounding box does not contain the bounding box of instance %i \n", __FUNCTION__, instanceId); return; } if (isLeaf(node)) { /* insert into node if possible */ if (depth >= mMaxDepth || node->instancIds.size() < mThreshold) { node->instancIds.emplace_back(instanceId); } else { split(node, box); add(node, depth, box, instanceId); } } else { int i = getQuadrantId(box, mInstanceGetBoundingBox2DCallbackFunction(instanceId)); if (i != -1) { add(node->childs.at(i), depth + 1, getChildQuadrant(box, i), instanceId); } else { node->instancIds.emplace_back(instanceId); } } } void QuadTree::split(std::shared_ptr<QuadTreeNode> node, BoundingBox2D box) { if (!isLeaf(node)) { Logger::log(1, "%s error: only leafs can be splitted\n", __FUNCTION__); return; } for (auto& child : node->childs) { child = std::make_shared<QuadTreeNode>(); } std::vector<int> newInstanceIds{}; for (const auto& instanceId : node->instancIds) { int i = getQuadrantId(box, mInstanceGetBoundingBox2DCallbackFunction(instanceId)); if (i != -1) { /* found child, store in child ids */ node->childs[i]->instancIds.emplace_back(instanceId); } else { /* not found, store in parent */ newInstanceIds.emplace_back(instanceId); } } node->instancIds = std::move(newInstanceIds); } void QuadTree::remove(int instanceId) { remove(mRootNode, mRootBoundingBox, instanceId); } bool QuadTree::remove(std::shared_ptr<QuadTreeNode> node, BoundingBox2D box, int instanceId) { if (!box.intersects(mInstanceGetBoundingBox2DCallbackFunction(instanceId))) { Logger::log(1, "%s error: current quadtree node bounding box does not contain the bounding box of instance %i \n", __FUNCTION__, instanceId); return false; } if (isLeaf(node)) { removeInstance(node, instanceId); return true; } else { int i = getQuadrantId(box, mInstanceGetBoundingBox2DCallbackFunction(instanceId)); if (i != -1) { if (remove(node->childs[i], getChildQuadrant(box, i), instanceId)) { return tryMerge(node); } } else { removeInstance(node, instanceId); } return false; } } void QuadTree::removeInstance(std::shared_ptr<QuadTreeNode> node, int instanceId) { auto it = std::find_if(std::begin(node->instancIds), std::end(node->instancIds), [&instanceId](const auto& rhs) { return instanceId == rhs; }); if (it == std::end(node->instancIds)) { Logger::log(1, "%s error: could not remove not existing instance with id %i\n", __FUNCTION__, instanceId); return; } // Swap with the last element and pop back *it = std::move(node->instancIds.back()); node->instancIds.pop_back(); } bool QuadTree::tryMerge(std::shared_ptr<QuadTreeNode> node) { int numInstanceIds = node->instancIds.size(); for (const auto& child : node->childs) { if (!isLeaf(child)) { return false; } numInstanceIds += child->instancIds.size(); } if (numInstanceIds <= mThreshold) { for (const auto& child : node->childs) { node->instancIds.insert(node->instancIds.end(), child->instancIds.begin(), child->instancIds.end()); } /* remove the childs */ for (auto& child : node->childs) { child.reset(); } return true; } else { return false; } } void QuadTree::update(int instanceId) { remove(instanceId); add(instanceId); } std::vector<int> QuadTree::query(BoundingBox2D box) { std::vector<int> values; values = query(mRootNode, mRootBoundingBox, box); return values; } std::vector<int> QuadTree::query(std::shared_ptr<QuadTreeNode> node, BoundingBox2D box, BoundingBox2D queryBox) { std::vector<int> values; for (const auto& instanceId : node->instancIds) { if (queryBox.intersects(mInstanceGetBoundingBox2DCallbackFunction(instanceId))) { values.emplace_back(instanceId); } } if (!isLeaf(node)) { for (int i = 0; i < node->childs.size(); ++i) { BoundingBox2D childBox = getChildQuadrant(box, i); if (queryBox.intersects(childBox)) { std::vector<int> childValues = query(node->childs.at(i), childBox, queryBox); values.insert(values.end(), childValues.begin(), childValues.end()); } } } return values; } void QuadTree::clear() { mRootNode.reset(); mRootNode = std::make_shared<QuadTreeNode>(); } std::set<std::pair<int, int>> QuadTree::findAllIntersections() { std::set<std::pair<int, int>> values; values = findAllIntersections(mRootNode); for (auto it = values.begin(); it != values.end(); ) { auto reversePair = std::make_pair((*it).second, (*it).first); if (values.count(reversePair) > 0) { values.erase(it++); } else { ++it; } } return values; } std::set<std::pair<int, int>> QuadTree::findAllIntersections(std::shared_ptr<QuadTreeNode> node) { std::set<std::pair<int, int>> values; for (int i = 0; i < node->instancIds.size(); ++i) { for (int j = 0; j < i; ++j) { if (mInstanceGetBoundingBox2DCallbackFunction(node->instancIds.at(i)).intersects(mInstanceGetBoundingBox2DCallbackFunction(node->instancIds.at(j)))) { values.insert({node->instancIds[i], node->instancIds[j]}); } } } if (!isLeaf(node)) { for (const auto& child : node->childs) { for (const auto& value : node->instancIds) { std::set<std::pair<int, int>> childValues; childValues = findIntersectionsInDescendants(child, value); values.insert(childValues.begin(), childValues.end()); } } for (const auto& child : node->childs) { std::set<std::pair<int, int>> childValues; childValues = findAllIntersections(child); values.insert(childValues.begin(), childValues.end()); } } return values; } std::set<std::pair<int, int>> QuadTree::findIntersectionsInDescendants(std::shared_ptr<QuadTreeNode> node, int instanceId) { std::set<std::pair<int, int>> values; for (const auto& other : node->instancIds) { if (mInstanceGetBoundingBox2DCallbackFunction(instanceId).intersects(mInstanceGetBoundingBox2DCallbackFunction(other))) { values.insert({instanceId, other}); } } if (!isLeaf(node)) { for (const auto& child : node->childs) { std::set<std::pair<int, int>> childValues; childValues = findIntersectionsInDescendants(child, instanceId); values.insert(childValues.begin(), childValues.end()); } } return values; } std::vector<BoundingBox2D> QuadTree::getTreeBoxes() { std::vector<BoundingBox2D> values; values = getTreeBoxes(mRootNode, mRootBoundingBox); return values; } std::vector<BoundingBox2D> QuadTree::getTreeBoxes(std::shared_ptr<QuadTreeNode> node, BoundingBox2D box) { std::vector<BoundingBox2D> values; if (isLeaf(node)) { values.emplace_back(box); } else { for (int i = 0; i < node->childs.size(); ++i) { BoundingBox2D childBox = getChildQuadrant(box, i); std::vector<BoundingBox2D> childValues = getTreeBoxes(node->childs.at(i), childBox); values.insert(values.end(), childValues.begin(), childValues.end()); } } return values; }
0
0.954609
1
0.954609
game-dev
MEDIA
0.460138
game-dev
0.889306
1
0.889306
lufylegend/lufylegend.js
21,170
project/assets/plugin/lufylegend/lib/LTransitionManager.js
import LGlobal from '../utils/LGlobal'; import LGraphics from '../display/LGraphics'; import LTweenLite from '../transitions/LTweenLite'; class LTransition { constructor(displayObject, transObj) { this.child = displayObject; this.trans = transObj; } startTransition() { let self = this; switch (self.trans.type) { case LTransition.Blinds: self.blinds(); break; case LTransition.Fade: self.fade(); break; case LTransition.Fly: self.fly(); break; case LTransition.Iris: self.iris(); break; case LTransition.Squeeze: self.squeeze(); break; case LTransition.Wipe: self.wipe(); break; case LTransition.Zoom: self.zoom(); break; case LTransition.PixelDissolve: self.pixelDissolve(); break; case LTransition.Curtain: self.curtain(); break; default: throw ('the type is not exists.'); } } blindsComplete(self) { if (self.trans.direction === LTransition.OUT) { self.child.mask.clear(); } else { self.blindsUpdateRun(); } self.child.mask = null; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } blindsUpdateRun() { let self = this, g = self.child.mask, c = LGlobal.canvas; g.clear(); if (self.trans.dimension) { g.add(function() { c.save(); for (let i = 0; i < self.trans.numStrips; i++) { c.rect(i * self.maxSize, 0, self.blindsSize, self.child.getHeight()); } c.restore(); }); } else { g.add(function() { c.save(); for (let i = 0; i < self.trans.numStrips; i++) { c.rect(0, 0 + i * self.maxSize, self.child.getWidth(), self.blindsSize); } c.restore(); }); } } blindsUpdate(self) { self.blindsUpdateRun(); if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } blinds() { let self = this; if (!self.trans.numStrips) self.trans.numStrips = 1; self.blindsSize = 0; if (self.trans.dimension) { self.maxSize = self.child.getWidth() / self.trans.numStrips >> 0; } else { self.maxSize = self.child.getHeight() / self.trans.numStrips >> 0; } let g = new LGraphics(); self.child.mask = g; let toSize = self.maxSize; if (self.trans.direction === LTransition.OUT) { self.blindsSize = self.maxSize; toSize = 0; } LTweenLite.to(self, self.trans.duration, { blindsSize: toSize, onComplete: self.blindsComplete, onUpdate: self.blindsUpdate, ease: self.trans.easing }); } fadeComplete(self) { self.child.alpha = self.alpha; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } fadeUpdate(self) { self.child.alpha = self.alpha; if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } fade() { let self = this; let toAlpha = 1; self.alpha = 0; if (self.trans.direction === LTransition.OUT) { self.alpha = 1; toAlpha = 0; } self.child.alpha = self.alpha; LTweenLite.to(self, self.trans.duration, { alpha: toAlpha, onComplete: self.fadeComplete, onUpdate: self.fadeUpdate, ease: self.trans.easing }); } flyComplete(self) { self.child.x = self.x; self.child.y = self.y; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } flyUpdate(self) { self.child.x = self.x; self.child.y = self.y; if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } fly() { let self = this; let toX = self.child.x; let toY = self.child.y; switch (self.trans.startPoint) { case 1: self.x = -self.child.getWidth(); self.y = -self.child.getHeight(); break; case 2: self.x = (LGlobal.width - self.child.getWidth()) * 0.5; self.y = -self.child.getHeight(); break; case 3: self.x = LGlobal.width; self.y = -self.child.getHeight(); break; case 4: self.x = -self.child.getWidth(); self.y = (LGlobal.height - self.child.getHeight()) * 0.5; break; case 6: self.x = LGlobal.width; self.y = (LGlobal.height - self.child.getHeight()) * 0.5; break; case 7: self.x = -self.child.getWidth(); self.y = LGlobal.height; break; case 8: self.x = (LGlobal.width - self.child.getWidth()) * 0.5; self.y = LGlobal.height; break; case 9: self.x = LGlobal.width; self.y = LGlobal.height; break; case 5: default: self.x = (LGlobal.width - self.child.getWidth()) * 0.5; self.y = (LGlobal.height - self.child.getHeight()) * 0.5; } if (self.trans.direction === LTransition.OUT) { toX = self.x; toY = self.y; self.x = self.child.x; self.y = self.child.y; } else { self.child.x = self.x; self.child.y = self.y; } LTweenLite.to(self, self.trans.duration, { x: toX, y: toY, onComplete: self.flyComplete, onUpdate: self.flyUpdate, ease: self.trans.easing }); } irisComplete(self) { if (self.trans.direction === LTransition.OUT) { self.child.mask.clear(); } else { self.irisUpdateRun(); } self.child.mask = null; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } irisUpdateRun() { let self = this, g = self.child.mask; g.clear(); if (self.trans.shape === LIris.CIRCLE) { g.drawArc(0, '#000000', [self.x, self.y, self.r, 0, Math.PI * 2]); } else { g.drawRect(0, '#000000', [self.x + self.sLeft, self.y + self.sTop, self.width, self.height]); } } irisUpdate(self) { self.irisUpdateRun(); if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } iris() { let self = this; self.sLeft = 0; self.sTop = 0; self.width = 0; self.height = 0; self.x = 0; self.y = 0; self.r = 0; self.eWidth = self.child.getWidth(); self.eHeight = self.child.getHeight(); switch (self.trans.startPoint) { case 1: self.eR = Math.sqrt(self.eWidth * self.eWidth + self.eHeight * self.eHeight); break; case 2: self.eR = Math.sqrt((self.eWidth * 0.5) * (self.eWidth * 0.5) + self.eHeight * self.eHeight); self.x = self.child.getWidth() * 0.5; break; case 3: self.eR = Math.sqrt(self.eWidth * self.eWidth + self.eHeight * self.eHeight); self.x = self.child.getWidth(); break; case 4: self.eR = Math.sqrt(self.eWidth * self.eWidth + (self.eHeight * 0.5) * (self.eHeight * 0.5)); self.y = self.child.getHeight() * 0.5; break; case 6: self.eR = Math.sqrt(self.eWidth * self.eWidth + (self.eHeight * 0.5) * (self.eHeight * 0.5)); self.x = self.child.getWidth(); self.y = self.child.getHeight() * 0.5; break; case 7: self.eR = Math.sqrt(self.eWidth * self.eWidth + self.eHeight * self.eHeight); self.y = self.child.getHeight(); break; case 8: self.eR = Math.sqrt((self.eWidth * 0.5) * (self.eWidth * 0.5) + self.eHeight * self.eHeight); self.x = self.child.getWidth() * 0.5; self.y = self.child.getHeight(); break; case 9: self.eR = Math.sqrt(self.eWidth * self.eWidth + self.eHeight * self.eHeight); self.x = self.child.getWidth(); self.y = self.child.getHeight(); break; case 5: default: self.eR = Math.sqrt((self.eWidth * 0.5) * (self.eWidth * 0.5) + (self.eHeight * 0.5) * (self.eHeight * 0.5)); self.x = self.child.getWidth() * 0.5; self.y = self.child.getHeight() * 0.5; } self.eLeft = -self.x; self.eTop = -self.y; let g = new LGraphics(); self.child.mask = g; if (self.trans.direction === LTransition.OUT) { self.sLeft = self.eLeft; self.sTop = self.eTop; self.eLeft = 0; self.eTop = 0; self.width = self.eWidth; self.height = self.eHeight; self.eWidth = 0; self.eHeight = 0; self.r = self.eR; self.eR = 0; } LTweenLite.to(self, self.trans.duration, { width: self.eWidth, height: self.eHeight, sLeft: self.eLeft, sTop: self.eTop, r: self.eR, onComplete: self.irisComplete, onUpdate: self.irisUpdate, ease: self.trans.easing }); } curtainComplete(self) { if (self.trans.direction === LTransition.OUT) { self.child.mask.clear(); } else { self.curtainUpdateRun(); } self.child.mask = null; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } curtainUpdateRun() { let self = this, g = self.child.mask, c = LGlobal.canvas; g.clear(); if (self.trans.dimension) { g.add(function() { c.beginPath(); c.save(); c.rect(0, 0, self.width, self.child.getHeight()); c.rect(self.child.getWidth() - self.width, 0, self.width, self.child.getHeight()); c.restore(); }); } else { g.add(function() { c.beginPath(); c.save(); c.rect(0, 0, self.child.getWidth(), self.height); c.rect(0, self.child.getHeight() - self.height, self.child.getWidth(), self.height); c.restore(); }); } } curtainUpdate(self) { self.curtainUpdateRun(); if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } curtain() { let self = this; let eW = self.child.getWidth() * 0.5; let eH = self.child.getHeight() * 0.5; if (self.trans.dimension) { eH = 0; } else { eW = 0; } self.width = 0; self.height = 0; let g = new LGraphics(); self.child.mask = g; if (self.trans.direction === LTransition.OUT) { self.width = eW; self.height = eH; eW = 0; eH = 0; } LTweenLite.to(self, self.trans.duration, { width: eW, height: eH, onComplete: self.curtainComplete, onUpdate: self.curtainUpdate, ease: self.trans.easing }); } squeezeComplete(self) { self.child.scaleX = self.scaleX; self.child.scaleY = self.scaleY; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } squeezeUpdate(self) { self.child.scaleX = self.scaleX; self.child.scaleY = self.scaleY; if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } squeeze() { let self = this; let toScaleX = 1, toScaleY = 1; self.scaleX = 0, self.scaleY = 0; if (self.trans.dimension) { self.scaleX = 1; } else { self.scaleY = 1; } if (self.trans.direction === LTransition.OUT) { toScaleX = self.scaleX, toScaleY = self.scaleY; self.scaleX = 1, self.scaleY = 1; } self.child.scaleX = self.scaleX; self.child.scaleY = self.scaleY; LTweenLite.to(self, self.trans.duration, { scaleX: toScaleX, scaleY: toScaleY, onComplete: self.squeezeComplete, onUpdate: self.squeezeUpdate, ease: self.trans.easing }); } zoomComplete(self) { self.child.scaleX = self.scaleX; self.child.scaleY = self.scaleY; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } zoomUpdate(self) { self.child.scaleX = self.scaleX; self.child.scaleY = self.scaleY; if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } zoom() { let self = this; let toScaleX = 1, toScaleY = 1; self.scaleX = 0, self.scaleY = 0; if (self.trans.direction === LTransition.OUT) { toScaleX = 0, toScaleY = 0; self.scaleX = 1, self.scaleY = 1; } self.child.scaleX = self.scaleX; self.child.scaleY = self.scaleY; LTweenLite.to(self, self.trans.duration, { scaleX: toScaleX, scaleY: toScaleY, onComplete: self.zoomComplete, onUpdate: self.zoomUpdate, ease: self.trans.easing }); } wipeComplete(self) { if (self.trans.direction === LTransition.OUT) { self.child.mask.clear(); } else { self.wipeUpdateRun(); } self.child.mask = null; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } wipeUpdateRun() { let self = this, g = self.child.mask; g.clear(); g.drawVertices(0, '#000000', [[self.leftTopX, self.leftTopY], [self.leftBottomX, self.leftBottomY], [self.rightBottomX, self.rightBottomY], [self.rightTopX, self.rightTopY]]); } wipeUpdate(self) { self.wipeUpdateRun(); if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } wipe() { let self = this, w = self.child.getWidth(), h = self.child.getHeight(), ltX = self.leftTopX = 0, ltY = self.leftTopY = 0, lbX = self.leftBottomX = 0, lbY = self.leftBottomY = h, rtX = self.rightTopX = w, rtY = self.rightTopY = 0, rbX = self.rightBottomX = w, rbY = self.rightBottomY = h; switch (self.trans.startPoint) { case 1: ltX = self.leftTopX = -w; lbX = self.leftBottomX = -w * 2; self.rightTopX = 0; rtX = w * 2; self.rightBottomX = -w; rbX = w; break; case 2: ltY = self.leftTopY = -h; self.leftBottomY = 0; lbY = h; rtY = self.rightTopY = -h; self.rightBottomY = 0; rbY = h; break; case 3: self.leftTopX = w; ltX = -w; self.leftBottomX = w * 2; lbX = 0; rtX = self.rightTopX = w * 2; rbX = self.rightBottomX = w * 3; break; case 4: self.rightTopX = 0; rtX = w; self.rightBottomX = 0; rbX = w; break; case 6: self.leftTopX = w; ltX = 0; self.leftBottomX = w; lbX = 0; break; case 7: lbX = self.leftBottomX = -w; ltX = self.leftTopX = -w * 2; self.rightBottomX = 0; rbX = w * 2; self.rightTopX = -w; rtX = w; break; case 8: lbY = self.leftBottomY = h; self.leftTopY = h; ltY = 0; rbY = self.rightBottomY = h; self.rightTopY = h; rtY = 0; break; case 9: self.leftBottomX = w; lbX = -w; self.leftTopX = w * 2; ltX = 0; rbX = self.rightBottomX = w * 2; rtX = self.rightTopX = w * 3; break; case 5: default: self.leftTopX = w * 0.5; self.leftTopY = h * 0.5; self.rightTopX = w * 0.5; self.rightTopY = h * 0.5; self.leftBottomX = w * 0.5; self.leftBottomY = h * 0.5; self.rightBottomX = w * 0.5; self.rightBottomY = h * 0.5; ltX = 0, ltY = 0; lbX = 0, lbY = h; rtX = w, rtY = 0; rbX = w, rbY = h; } let g = new LGraphics(); self.child.mask = g; if (self.trans.direction === LTransition.OUT) { let oltX = ltX, oltY = ltY, olbX = lbX, olbY = lbY, ortX = rtX, ortY = rtY, orbX = rbX, orbY = rbY; ltX = self.leftTopX, ltY = self.leftTopY, lbX = self.leftBottomX, lbY = self.leftBottomY, rtX = self.rightTopX, rtY = self.rightTopY, rbX = self.rightBottomX, rbY = self.rightBottomY; self.leftTopX = oltX, self.leftTopY = oltY, self.leftBottomX = olbX, self.leftBottomY = olbY, self.rightTopX = ortX, self.rightTopY = ortY, self.rightBottomX = orbX, self.rightBottomY = orbY; } LTweenLite.to(self, self.trans.duration, { leftTopX: ltX, leftTopY: ltY, leftBottomX: lbX, leftBottomY: lbY, rightTopX: rtX, rightTopY: rtY, rightBottomX: rbX, rightBottomY: rbY, onComplete: self.wipeComplete, onUpdate: self.wipeUpdate, ease: self.trans.easing }); } pixelDissolveComplete(self) { if (self.trans.direction === LTransition.OUT) { self.child.mask.clear(); } else { self.pixelDissolveUpdateRun(); } self.child.mask = null; if (self.trans.onComplete) { self.trans.onComplete(self.child); } } pixelDissolveUpdateRun() { let self = this, g = self.child.mask, c = LGlobal.canvas, list; g.clear(); g.add(function() { c.beginPath(); c.save(); for (let i = 0; i < self.index; i++) { list = self.list[i]; c.rect(list[0] * self.w, list[1] * self.h, self.w, self.h); } c.restore(); }); } pixelDissolveUpdate(self) { self.pixelDissolveUpdateRun(); if (self.trans.onUpdate) { self.trans.onUpdate(self.child); } } pixelDissolve() { let self = this; let g = new LGraphics(); self.child.mask = g; LGlobal.mg = g; self.w = self.child.getWidth() / self.trans.xSections, self.h = self.child.getHeight() / self.trans.ySections; self.list = []; for (let i = 0; i < self.trans.xSections; i++) { for (let j = 0; j < self.trans.ySections; j++) { self.list.push([i, j]); } } self.index = 0; let to = self.trans.xSections * self.trans.ySections; if (self.trans.direction === LTransition.OUT) { self.index = to; to = 0; } self.list = self.list.sort(function(a, b) { return Math.random() > 0.5; }); self.pixelDissolveUpdateRun(); LTweenLite.to(self, self.trans.duration, { index: to, onComplete: self.pixelDissolveComplete, onUpdate: self.pixelDissolveUpdate, ease: self.trans.easing }); } } LTransition.IN = 'in'; LTransition.OUT = 'out'; LTransition.Blinds = 1; LTransition.Fade = 2; LTransition.Fly = 3; LTransition.Iris = 4; LTransition.Curtain = 5; LTransition.PixelDissolve = 6; LTransition.Squeeze = 7; LTransition.Wipe = 8; LTransition.Zoom = 9; const LIris = { SQUARE: 0, CIRCLE: 1 }; class LTransitionManager { constructor(displayObject) { this.child = displayObject; } startTransition(transParams) { return LTransitionManager.start(this.child, transParams); } } LTransitionManager.start = function(displayObject, transParams) { let trans = new LTransition(displayObject, transParams); trans.startTransition(); return trans; }; export default { LTransition: LTransition, LIris: LIris, LTransitionManager: LTransitionManager };
0
0.757906
1
0.757906
game-dev
MEDIA
0.53235
game-dev,graphics-rendering
0.757221
1
0.757221
Droivox/Godot-Engine-FPS
1,237
Project/data/scripts/character/hud.gd
extends CanvasLayer export(NodePath) var weapon; export(NodePath) var weapon_hud; export(NodePath) var crosshair; func _ready(): weapon = get_node(weapon); weapon_hud = get_node(weapon_hud); crosshair = get_node(crosshair); func _process(_delta) -> void: _weapon_hud() _crosshair() func _weapon_hud() -> void: var off = Vector2(180, 80); weapon_hud.position = get_viewport().size - off; weapon_hud.get_node("name").text = str(weapon.arsenal.values()[weapon.current].name); weapon_hud.get_node("bullets").text = str(weapon.arsenal.values()[weapon.current].bullets); weapon_hud.get_node("ammo").text = str(weapon.arsenal.values()[weapon.current].ammo); # Color if weapon.arsenal.values()[weapon.current].bullets < (weapon.arsenal.values()[weapon.current].max_bullets/4): weapon_hud.get_node("bullets").add_color_override("font_color", Color("#ff0000")); elif weapon.arsenal.values()[weapon.current].bullets < (weapon.arsenal.values()[weapon.current].max_bullets/2): weapon_hud.get_node("bullets").add_color_override("font_color", Color("#dd761b")); else: weapon_hud.get_node("bullets").add_color_override("font_color", Color("#ffffff")); func _crosshair() -> void: crosshair.position = get_viewport().size/2;
0
0.790626
1
0.790626
game-dev
MEDIA
0.982381
game-dev
0.554284
1
0.554284
RCInet/LastEpoch_Mods
1,610
AssetBundleExport/Library/PackageCache/com.unity.timeline@c58b4ee65782/Editor/Actions/TimelineAction.cs
namespace UnityEditor.Timeline.Actions { /// <summary> /// Base class for a timeline action. /// Inherit from this class to make an action on a timeline after a menu click and/or a key shortcut. /// </summary> /// <remarks> /// To add an action as a menu item in the Timeline context menu, add <see cref="MenuEntryAttribute"/> on the action class. /// To make an action to react to a shortcut, use the Shortcut Manager API with <see cref="TimelineShortcutAttribute"/>. /// <seealso cref="UnityEditor.ShortcutManagement.ShortcutAttribute"/> /// <seealso cref="ActiveInModeAttribute"/> /// </remarks> /// <example> /// Simple Timeline Action example (with context menu and shortcut support). /// <code source="../../DocCodeExamples/ActionExamples.cs" region="declare-sampleTimelineAction" title="SampleTimelineAction"/> /// </example> [ActiveInMode(TimelineModes.Default)] public abstract class TimelineAction : IAction { /// <summary> /// Execute the action. /// </summary> /// <param name="context">Context for the action.</param> /// <returns>true if the action has been executed. false otherwise</returns> public abstract bool Execute(ActionContext context); /// <summary> /// Defines the validity of an Action based on the context. /// </summary> /// <param name="context">Context for the action.</param> /// <returns>Visual state of the menu for the action.</returns> public abstract ActionValidity Validate(ActionContext context); } }
0
0.773264
1
0.773264
game-dev
MEDIA
0.566365
game-dev
0.732563
1
0.732563
Albeoris/Memoria
2,397
Memoria.Patcher/StreamingAssets/Data/SpecialEffects/ef287/PlayerSequence.seq
// Player sequence of SFX Dark_Matter WaitAnimation: Char=Caster StartThread: Condition=CasterRow == 0 && AreCasterAndSelectedTargetsEnemies ; Sync=True MoveToPosition: Char=Caster ; RelativePosition=(0, 0, 400) ; Anim=MP_STEP_FORWARD WaitMove: Char=Caster EndThread StartThread: Condition=IsSingleSelectedTarget Turn: Char=Caster ; BaseAngle=AllTargets ; Time=5 EndThread Message: Text=[CastName] ; Priority=1 ; Title=True ; Reflect=True SetupReflect: Delay=SFXLoaded StartThread: Condition=IsSingleTarget ; Sync=True LoadSFX: SFX=Dark_Matter ; Reflect=True StartThread: Condition=ItemUseId == 255 ; Sync=True PlayAnimation: Char=Caster ; Anim=MP_IDLE_TO_CHANT WaitAnimation: Char=Caster PlayAnimation: Char=Caster ; Anim=MP_CHANT ; Loop=True Channel WaitSFXLoaded: SFX=Dark_Matter ; Reflect=True WaitAnimation: Char=Caster StopChannel PlayAnimation: Char=Caster ; Anim=MP_MAGIC WaitAnimation: Char=Caster EndThread StartThread: Condition=ItemUseId != 255 ; Sync=True PlayAnimation: Char=Caster ; Anim=MP_ITEM1 WaitAnimation: Char=Caster WaitSFXLoaded: SFX=Dark_Matter ; Reflect=True EndThread PlaySFX: SFX=Dark_Matter ; Reflect=True WaitSFXDone: SFX=Dark_Matter ; Reflect=True EndThread StartThread: Condition=!IsSingleTarget ; Sync=True StartThread: Condition=ItemUseId == 255 ; Sync=True PlayAnimation: Char=Caster ; Anim=MP_IDLE_TO_CHANT WaitAnimation: Char=Caster PlayAnimation: Char=Caster ; Anim=MP_CHANT ; Loop=True Channel WaitAnimation: Char=Caster WaitAnimation: Char=Caster StopChannel PlayAnimation: Char=Caster ; Anim=MP_MAGIC WaitAnimation: Char=Caster EndThread StartThread: Condition=ItemUseId != 255 ; Sync=True PlayAnimation: Char=Caster ; Anim=MP_ITEM1 WaitAnimation: Char=Caster EndThread StartThread: TargetLoop=True ; Chain=True ; Sync=True LoadSFX: SFX=Dark_Matter ; Reflect=True ; UseCamera=False WaitSFXLoaded: SFX=Dark_Matter ; Reflect=True PlaySFX: SFX=Dark_Matter ; Reflect=True Wait: Time=10 EndThread WaitSFXDone: SFX=Dark_Matter ; Reflect=True EndThread ActivateReflect WaitReflect StartThread: Condition=CasterRow == 0 && AreCasterAndSelectedTargetsEnemies ; Sync=True MoveToPosition: Char=Caster ; RelativePosition=(0, 0, -400) ; Anim=MP_STEP_BACK WaitMove: Char=Caster EndThread PlayAnimation: Char=Caster ; Anim=Idle Turn: Char=Caster ; BaseAngle=Default ; Time=5 WaitTurn: Char=Caster
0
0.768815
1
0.768815
game-dev
MEDIA
0.760593
game-dev
0.85873
1
0.85873
RiddleTime/Race-Element
1,084
Race_Element.HUD.ACC/Overlays/Driving/LapDeltaTrace/LapDeltaDataCollector.cs
using System.Collections.Generic; namespace RaceElement.HUD.ACC.Overlays.Driving.OverlayLapDeltaTrace; internal class LapDeltaDataCollector { private readonly int TraceCount = 300; public float MaxDelta { get; set; } public LinkedList<float> PositiveDeltaData = new(); public LinkedList<float> NegativeDeltaData = new(); public LapDeltaDataCollector(int traceCount) { TraceCount = traceCount; for (int i = 0; i < TraceCount; i++) { PositiveDeltaData.AddLast(0); NegativeDeltaData.AddLast(0); } } public void Collect(float delta) { if (delta < 0) { NegativeDeltaData.AddFirst(-delta); PositiveDeltaData.AddFirst(0); } else { PositiveDeltaData.AddFirst(delta); NegativeDeltaData.AddFirst(0); } if (PositiveDeltaData.Count > TraceCount) PositiveDeltaData.RemoveLast(); if (NegativeDeltaData.Count > TraceCount) NegativeDeltaData.RemoveLast(); } }
0
0.53107
1
0.53107
game-dev
MEDIA
0.524173
game-dev,desktop-app
0.765659
1
0.765659
boozook/playdate
1,926
api/lua/examples/add-function-get-arg-string.rs
#![no_std] extern crate alloc; #[macro_use] extern crate sys; extern crate playdate_lua as lua; use core::ffi::c_int; use core::ptr::NonNull; use lua::Lua; use sys::EventLoopCtrl; use sys::ffi::*; use system::System; use system::event::SystemEventExt as _; use system::update::UpdateCtrl; /// Entry point, event handler #[no_mangle] fn event_handler(_api: NonNull<PlaydateAPI>, event: PDSystemEvent, _: u32) -> EventLoopCtrl { // We need to set our update callback in the InitLua handler instead of Init. // https://devforum.play.date/t/lua-c-minimal-example/4354/5 // // Just for this example, ignore all other events. if event != PDSystemEvent::InitLua { return EventLoopCtrl::Continue; } // Set update callback System::Default().set_update_callback_static(Some(on_update), ()); // Add a function that we depend on and call in main.lua Lua::Default().add_function(Some(log_to_console_from_main_dot_lua), "example.logToConsole") .expect("add_function 'log_to_console_from_main_dot_lua' should succeed"); // Continue event loop EventLoopCtrl::Continue } /// Update handler fn on_update(_: &mut ()) -> UpdateCtrl { // Continue updates UpdateCtrl::Continue } // The function we add to the Lua runtime and call from main.lua pub unsafe extern "C" fn log_to_console_from_main_dot_lua(_lua_state: *mut lua_State) -> c_int { // We know that our function takes a single argument which is a string. let arg_string = Lua::Default().get_arg_string(1) .expect("get_arg_string should succeed"); // Avoid going from CString to str and back with playdate::sys::log::println let f = (*(*sys::API).system).logToConsole .expect("get logToConsole to succeed"); f(arg_string.as_ptr()); // A `lua_CFunction` should return the number of return values it has pushed // onto the stack. 0 } // Needed for debug build ll_symbols!();
0
0.878327
1
0.878327
game-dev
MEDIA
0.514088
game-dev
0.89643
1
0.89643
cookgreen/Yuris-Revenge
22,784
OpenRA.Mods.YR/UtilityCommands/ImportTranslationStringCommand.cs
using OpenRA.FileSystem; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenRA.Mods.YR.UtilityCommands { public class ImportTranslationStringCommand : IUtilityCommand { public string Name { get { return "--import-translation-string"; } } public bool ValidateArguments(string[] args) { return args.Length >= 3; } [Desc("LOCALIZATIONNAME NEWMODID [FONTSETTINGYAMLFILE]", "")] public void Run(Utility utility, string[] args) { Console.WriteLine("Starting importing the translated strings"); //Get translated strings from LOCALIZATIONNAME.yaml string customFontPath = null; if (args.Length == 4) { customFontPath = args[3]; } string localizationName = args[1]; var modData = utility.ModData; string localizationFile = string.Format("languages\\{0}.yaml", localizationName); var stream = modData.ModFiles.Open(localizationFile); var nodes = MiniYaml.FromStream(stream); if (nodes[0].Value.Nodes[0].Key != localizationName) { Console.WriteLine("Invalid localization file!"); return; } var rulesLocalizationNode = nodes[0].Value.Nodes[0].Value.Nodes.Where(o => o.Key == "Rules").FirstOrDefault(); var chromeLayoutsLocalizationNode = nodes[0].Value.Nodes[0].Value.Nodes.Where(o => o.Key == "ChromeLayouts").FirstOrDefault(); var worldRulesLocalizationNode = nodes[0].Value.Nodes[0].Value.Nodes.Where(o => o.Key == "World").FirstOrDefault(); var modContentLocalizationNode = nodes[0].Value.Nodes[0].Value.Nodes.Where(o => o.Key == "ModContent").FirstOrDefault(); //Get the original mod install dir string modID = modData.Manifest.Id; string modFolder = null; if (stream is FileStream) { var fs = stream as FileStream; if (fs.Name.Contains(localizationFile)) { int idx = fs.Name.IndexOf(localizationFile); modFolder = fs.Name.Substring(0, idx); } } //Copy all the original mod files to the new mod which id is defined by NEWMODID parameter string newModID = args[2]; if (!string.IsNullOrEmpty(modFolder)) { DirectoryInfo di = new DirectoryInfo(modFolder); DirectoryInfo modRootDir = di.Parent; string newModFullPath = Path.Combine(modRootDir.FullName, newModID); if (Directory.Exists(newModFullPath)) { Directory.Delete(newModFullPath, true); } Directory.CreateDirectory(newModFullPath); foreach (var fileSystemInfo in di.EnumerateFileSystemInfos()) { if (fileSystemInfo.Attributes == FileAttributes.Directory) { DirectoryCopy(fileSystemInfo.FullName, Path.Combine(newModFullPath, fileSystemInfo.Name), true); } else { File.Copy(fileSystemInfo.FullName, Path.Combine(newModFullPath, fileSystemInfo.Name)); } } string lightFont = null; string normalFont = null; string boldFont = null; if (!string.IsNullOrEmpty(customFontPath)) { string currentDir = Environment.CurrentDirectory; DirectoryInfo d = new DirectoryInfo(currentDir); string fontSettingFilePath = Path.Combine(d.Parent.FullName, customFontPath); Console.WriteLine(fontSettingFilePath); if (File.Exists(fontSettingFilePath)) { var fontSettingFile = MiniYaml.FromFile(fontSettingFilePath); if (fontSettingFile[0].Value.Nodes.Count == 2) { normalFont = Path.Combine(Path.GetDirectoryName(fontSettingFilePath), fontSettingFile[0].Value.Nodes[0].Value.Value); boldFont = Path.Combine(Path.GetDirectoryName(fontSettingFilePath), fontSettingFile[0].Value.Nodes[1].Value.Value); } else { Console.WriteLine("Error: Invalid font setting file!"); } } else { Console.WriteLine("Error: Specific font path can't be found!"); } } //------------------------------------------------------ // Modify all the yaml files using the original mod id //------------------------------------------------------ List<string> mapFolders = new List<string>(); List<string> ruleFilePathes = new List<string>(); List<string> chromeLayoutFilePathes = new List<string>(); Dictionary<string, string> externalMods = new Dictionary<string, string>(); //Modify mod.yaml file string newModYaml = Path.Combine(newModFullPath, "mod.yaml"); var modYamlNodes = MiniYaml.FromFile(newModYaml); foreach (var modYamlNode in modYamlNodes) { if (modYamlNode.Key == "Metadata") { var modYamlMetadataTitleNode = modYamlNode.Value.Nodes.Where(o => o.Key == "Title").FirstOrDefault(); if (modYamlMetadataTitleNode != null) { localizationName = localizationName.Replace(localizationName.Substring(0, 1), localizationName.Substring(0, 1).ToUpper()); modYamlMetadataTitleNode.Value.Value += string.Format(" ({0} Version)", localizationName); } } else if (modYamlNode.Key == "Packages") { foreach (var subYamlNode in modYamlNode.Value.Nodes) { if (subYamlNode.Key == string.Format("${0}", modID)) { subYamlNode.Key = string.Format("${0}", newModID); subYamlNode.Value.Value = newModID; } else if (subYamlNode.Key.StartsWith(string.Format("{0}|", modID))) { string oldKey = string.Format("{0}|", modID); subYamlNode.Key = subYamlNode.Key.Replace( oldKey, string.Format("{0}|", newModID) ); } else if (subYamlNode.Key.StartsWith("~")) { if (subYamlNode.Key.Substring(1).StartsWith("^")) { subYamlNode.Key = "~^" + ReplacePathWithNewModID(subYamlNode.Key.Substring(2), modID, newModID); } } else if (!subYamlNode.Key.StartsWith("~") && !string.IsNullOrEmpty(subYamlNode.Value.Value)) { //This is an external mod Console.WriteLine(Platform.ResolvePath(subYamlNode.Key)); externalMods.Add(subYamlNode.Value.Value, Platform.ResolvePath(subYamlNode.Key)); } } } else if (modYamlNode.Key == "Rules" || modYamlNode.Key == "Sequences" || modYamlNode.Key == "ModelSequences" || modYamlNode.Key == "Cursors" || modYamlNode.Key == "Chrome" || modYamlNode.Key == "Assemblies" || modYamlNode.Key == "ChromeLayout" || modYamlNode.Key == "Hotkeys" || modYamlNode.Key == "Weapons" || modYamlNode.Key == "Voices" || modYamlNode.Key == "Notifications" || modYamlNode.Key == "TileSets" || modYamlNode.Key == "Music" || modYamlNode.Key == "Translations" || modYamlNode.Key == "ChromeMetrics" || modYamlNode.Key == "Missions") { foreach (var subYamlNode in modYamlNode.Value.Nodes) { if (subYamlNode.Key.StartsWith(string.Format("{0}|", modID))) { string oldKey = string.Format("{0}|", modID); subYamlNode.Key = subYamlNode.Key.Replace( oldKey, string.Format("{0}|", newModID) ); if (modYamlNode.Key == "Rules") { ruleFilePathes.Add(Path.Combine(newModFullPath, subYamlNode.Key.Split('|')[1])); } else if (modYamlNode.Key == "ChromeLayout") { chromeLayoutFilePathes.Add(Path.Combine(newModFullPath, subYamlNode.Key.Split('|')[1])); } } else { string[] tokens = subYamlNode.Key.Split('|'); if (tokens.Length == 2) { if (externalMods.ContainsKey(tokens[0]) && (modYamlNode.Key == "Rules" || modYamlNode.Key == "ChromeLayout")) { //Copy the external mod files string filePath = Path.Combine(externalMods[tokens[0]], tokens[1]); string newFilePath = Path.Combine(newModFullPath, tokens[0], tokens[1]); string newFileDir = Path.GetDirectoryName(newFilePath); if (!Directory.Exists(newFileDir)) { Directory.CreateDirectory(newFileDir); } if (!File.Exists(newFilePath)) { File.Copy(filePath, newFilePath); } string relativePath = ConvertToRelativeCurrentPath(newFilePath, newModFullPath); subYamlNode.Key = string.Format("{0}|{1}", newModID, relativePath); if (modYamlNode.Key == "Rules") { ruleFilePathes.Add(newFilePath); } else if (modYamlNode.Key == "ChromeLayout") { chromeLayoutFilePathes.Add(newFilePath); } } } } } } else if (modYamlNode.Key == "MapFolders") { foreach (var subYamlNode in modYamlNode.Value.Nodes) { if (subYamlNode.Key.StartsWith(string.Format("{0}|", modID))) { string oldKey = string.Format("{0}|", modID); subYamlNode.Key = subYamlNode.Key.Replace( oldKey, string.Format("{0}|", newModID) ); string[] tokens = subYamlNode.Key.Split('|');//Relative map folder mapFolders.Add(Path.Combine(newModFullPath, tokens[1])); } else if (subYamlNode.Key.StartsWith("~"))//optional map folder { string temp = subYamlNode.Key.Substring(1); if (temp.StartsWith("^")) { string[] pathBlocks = temp.Substring(1).Split('/'); int idx = 0; string pathAfterModified = string.Empty; foreach (var pathBlock in pathBlocks) { if (pathBlock == modID) { pathBlocks[idx] = newModID; } pathAfterModified = Path.Combine(pathAfterModified, pathBlocks[idx]); idx++; } temp = "^" + pathAfterModified.Replace("\\", "/"); string fullPath = Platform.ResolvePath(temp); mapFolders.Add(fullPath); subYamlNode.Key = "~" + temp; } } } } else if (modYamlNode.Key == "LoadScreen") { foreach (var subYamlNode in modYamlNode.Value.Nodes) { if (subYamlNode.Value.Value.StartsWith(string.Format("{0}|", modID))) { string oldKey = string.Format("{0}|", modID); subYamlNode.Value.Value = subYamlNode.Value.Value.Replace( oldKey, string.Format("{0}|", newModID) ); } } } else if (modYamlNode.Key == "Fonts") { foreach (var subYamlNode in modYamlNode.Value.Nodes) { foreach (var sNode in subYamlNode.Value.Nodes) { if (sNode.Key == "Font") { if (sNode.Value.Value.StartsWith(string.Format("{0}|", modID))) { string oldKey = string.Format("{0}|", modID); sNode.Value.Value = sNode.Value.Value.Replace( oldKey, string.Format("{0}|", newModID) ); } if ((subYamlNode.Key == "Tiny" || subYamlNode.Key == "Small" || subYamlNode.Key == "Regular" || subYamlNode.Key == "Title")) { string targetNormalFontFile = Path.Combine(newModFullPath, Path.GetFileName(normalFont)); if (File.Exists(normalFont) && !File.Exists(targetNormalFontFile)) { File.Copy(normalFont, targetNormalFontFile); } sNode.Value.Value = string.Format("{0}|{1}", newModID, Path.GetFileName(normalFont)); } else if (subYamlNode.Key == "TinyBold" || subYamlNode.Key == "Bold" || subYamlNode.Key == "MediumBold" || subYamlNode.Key == "BigBold") { string targetBoldFontFile = Path.Combine(newModFullPath, Path.GetFileName(boldFont)); if (File.Exists(boldFont) && !File.Exists(targetBoldFontFile)) { File.Copy(boldFont, targetBoldFontFile); } sNode.Value.Value = string.Format("{0}|{1}", newModID, Path.GetFileName(boldFont)); } } } } } else if (modYamlNode.Key == "ModContent") { foreach (var subYamlNode in modYamlNode.Value.Nodes) { if (subYamlNode.Key == "InstallPromptMessage") { //Translate if (modContentLocalizationNode != null) { var installPromptLocalization = modContentLocalizationNode.Value.Nodes.Where(o => o.Key == "InstallPromptMessage").FirstOrDefault(); if (installPromptLocalization != null) { subYamlNode.Value.Value = installPromptLocalization.Value.Value; } } } else if (subYamlNode.Key == "HeaderMessage") { //Translate if (modContentLocalizationNode != null) { var headerMessageLocalization = modContentLocalizationNode.Value.Nodes.Where(o => o.Key == "HeaderMessage").FirstOrDefault(); if (headerMessageLocalization != null) { subYamlNode.Value.Value = headerMessageLocalization.Value.Value; } } } else if (subYamlNode.Key == "Packages") { foreach (var sNode in subYamlNode.Value.Nodes) { //Translate if (modContentLocalizationNode != null) { var packageLocalization = modContentLocalizationNode.Value.Nodes.Where(o => o.Key == "Packages").FirstOrDefault(); if (packageLocalization != null) { var subPackageLocalizationNode = packageLocalization.Value.Nodes.Where(o => o.Key == sNode.Key).FirstOrDefault(); if (subPackageLocalizationNode != null) { sNode.Value.Value = subPackageLocalizationNode.Value.Value; } } } foreach (var sn in sNode.Value.Nodes) { if (sn.Key == "TestFiles") { string[] contentFilePathes = sn.Value.Value.Split(','); int idx = 0; StringBuilder builder = new StringBuilder(); foreach (var contentFilePath in contentFilePathes) { string path = null; var contentFilePathTemp = contentFilePath.Trim(); if (contentFilePathTemp.StartsWith("^")) { path = contentFilePathTemp.Substring(1); } else { path = contentFilePathTemp; } contentFilePathes[idx] = "^" + ReplacePathWithNewModID(path, modID, newModID); builder.Append(contentFilePathes[idx] + ","); idx++; } sn.Value.Value = builder.ToString(); } } } } else if (subYamlNode.Key == "Sources") { foreach (var sNode in subYamlNode.Value.Nodes) { if (sNode.Key.StartsWith(string.Format("{0}|", modID))) { string oldKey = string.Format("{0}|", modID); sNode.Key = sNode.Key.Replace( oldKey, string.Format("{0}|", newModID) ); } } } } } } modYamlNodes.WriteToFile(newModYaml); //Modify all maps foreach (var mapFolder in mapFolders) { DirectoryInfo mapDir = new DirectoryInfo(mapFolder); if (!mapDir.Exists) { continue; } foreach (var directory in mapDir.EnumerateDirectories()) { if (File.Exists(Path.Combine(directory.FullName, "map.bin")) && File.Exists(Path.Combine(directory.FullName, "map.yaml")) && File.Exists(Path.Combine(directory.FullName, "map.png"))) { string mapYamlPath = Path.Combine(directory.FullName, "map.yaml"); var mapYamlFile = MiniYaml.FromFile(mapYamlPath); foreach (var node in mapYamlFile) { if (node.Key == "RequiresMod") { node.Value.Value = newModID; break; } } mapYamlFile.WriteToFile(mapYamlPath); } } } //Translate Rules file foreach (var ruleFilePath in ruleFilePathes) { var ruleYamlFile = MiniYaml.FromFile(ruleFilePath); foreach (var node in ruleYamlFile) { if (rulesLocalizationNode != null && node.Key != "^BaseWorld") { var actorLocalizationNode = rulesLocalizationNode.Value.Nodes.Where(o => o.Key == node.Key).FirstOrDefault(); var toolTipTraitNode = node.Value.Nodes.Where(o => o.Key == "Tooltip").FirstOrDefault(); if (toolTipTraitNode != null && actorLocalizationNode != null) { toolTipTraitNode.Value.Nodes[0].Value.Value = actorLocalizationNode.Value.Value; } } else if (node.Key == "^BaseWorld")//Translate Factions { if (worldRulesLocalizationNode != null) { foreach (var worldChildNode in node.Value.Nodes) { var factionLocalizationNode = worldRulesLocalizationNode.Value.Nodes.Where(o => o.Key == worldChildNode.Key).FirstOrDefault(); if (factionLocalizationNode != null) { foreach (var valueNode in worldChildNode.Value.Nodes) { var valueLocalizationNode = factionLocalizationNode.Value.Nodes.Where(o => o.Key == valueNode.Key).FirstOrDefault(); if (valueLocalizationNode != null) { valueNode.Value.Value = valueLocalizationNode.Value.Value; } } } } } } } ruleYamlFile.WriteToFile(ruleFilePath); } //Translate Chrome Layouts foreach (var chromeLayoutFilePath in chromeLayoutFilePathes) { var chromeLayoutFile = MiniYaml.FromFile(chromeLayoutFilePath); foreach (var chromeNode in chromeLayoutFile) { var chromeLocalizationNode = chromeLayoutsLocalizationNode.Value.Nodes.Where(o => o.Key == chromeNode.Key).FirstOrDefault(); if (chromeLocalizationNode != null) { translateChrome(chromeNode, chromeLocalizationNode); } } chromeLayoutFile.WriteToFile(chromeLayoutFilePath); } } Console.WriteLine("Import task has already finished!"); } private string ConvertToRelativeCurrentPath(string fullPath, string relativeTo) { fullPath = fullPath.Replace("\\", "/"); relativeTo = relativeTo.Replace("\\", "/"); int index = 0; for (int i = 0; i < fullPath.Length; i++) { if ((fullPath[i] != relativeTo[i]) || i == relativeTo.Length - 1) { index = i; break; } } string relativePath = fullPath.Substring(index + 2); Console.WriteLine(relativePath); return relativePath; } private void translateChrome(MiniYamlNode chromeNode, MiniYamlNode chromeLocalizationNode) { foreach(var subNode in chromeNode.Value.Nodes) { var subChromeLocalizationNode = chromeLocalizationNode.Value.Nodes.Where(o => o.Key == subNode.Key).FirstOrDefault(); if (subChromeLocalizationNode != null) { if (!string.IsNullOrEmpty(subNode.Value.Value)) { subNode.Value.Value = subChromeLocalizationNode.Value.Value; } translateChrome(subNode, subChromeLocalizationNode); } } } private string ReplacePathWithNewModID(string path, string oldModID, string newModID) { string[] pathBlocks = path.Split('/'); int idx = 0; string pathAfterModified = string.Empty; foreach (var pathBlock in pathBlocks) { if (pathBlock == oldModID) { pathBlocks[idx] = newModID; } pathAfterModified = Path.Combine(pathAfterModified, pathBlocks[idx]); idx++; } return pathAfterModified.Replace("\\", "/"); } private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } DirectoryInfo[] dirs = dir.GetDirectories(); // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } } }
0
0.931579
1
0.931579
game-dev
MEDIA
0.610412
game-dev
0.939833
1
0.939833
cmangos/mangos-wotlk
26,790
src/game/AI/ScriptDevAI/scripts/eastern_kingdoms/sunwell_plateau/boss_kalecgos.cpp
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Kalecgos SD%Complete: 70 SDComment: Timers; SDCategory: Sunwell Plateau EndScriptData */ #include "AI/ScriptDevAI/include/sc_common.h" #include "sunwell_plateau.h" #include "AI/ScriptDevAI/base/CombatAI.h" #include "Spells/Scripts/SpellScript.h" #include "Tools/Language.h" enum { // kalecgos dragon form SAY_EVIL_AGGRO = -1580000, SAY_EVIL_SPELL_1 = -1580001, SAY_EVIL_SPELL_2 = -1580002, SAY_EVIL_SLAY_1 = 25499, SAY_EVIL_SLAY_2 = 25500, SAY_EVIL_ENRAGE = -1580005, SAY_EVIL_WIPE = -1580114, // kalecgos humanoid form SAY_GOOD_75 = -1580006, SAY_GOOD_50 = -1580007, SAY_GOOD_25 = -1580008, SAY_GOOD_PLRWIN = -1580009, SAY_GOOD_PLRWIN_2 = -1580108, // unused atm SAY_GOOD_PLRWIN_3 = -1580115, SAY_SATH_AGGRO = -1580010, SAY_SATH_DEATH = -1580011, SAY_SATH_SPELL_1 = -1580012, SAY_SATH_SPELL_2 = -1580013, SAY_SATH_SLAY_1 = 25508, SAY_SATH_SLAY_2 = 25509, SAY_SATH_ENRAGE = -1580016, // Kalecgos SPELL_SPECTRAL_BLAST = 44869, SPELL_SPECTRAL_REALM_NOTIFY = 44845, // cast by the players on teleport to notify boss SPELL_ARCANE_BUFFET = 45018, SPELL_FROST_BREATH = 44799, SPELL_TAIL_LASH = 45122, SPELL_CRAZED_RAGE = 44807, SPELL_CRAZED_RAGE_BUFF = 44806, SPELL_SPECTRAL_REALM = 44811, SPELL_SPECTRAL_REALM_FORCE_F = 44852, // SPELL_SPECTRAL_REALM_AURA = 46021, SPELL_TELEPORT_SPECTRAL_REALM = 46019, SPELL_SPECTRAL_BLAST_IMPACT = 44866, SPELL_SPECTRAL_BLAST_VISUAL = 46648, // SPELL_SPECTRAL_EXHAUSTION = 44867, SPELL_CURSE_OF_BOUNDLESS_AGONY_REMOVAL = 45050, // Kalecgos human SPELL_HEROIC_STRIKE = 45026, SPELL_REVITALIZE = 45027, // Sathrovarr SPELL_SPECTRAL_INVISIBILITY = 44801, SPELL_CORRUPTING_STRIKE = 45029, SPELL_CURSE_OF_BOUNDLESS_AGONY = 45032, SPELL_SHADOW_BOLT_VOLLEY = 45031, // SPELL_TELEPORT_NORMAL_REALM = 46020, // Misc SPELL_BANISH = 44836, SPELL_INSTAKILL_SELF = 29878, }; static const uint32 aWildMagicSpells[6] = {44978, 45001, 45002, 45004, 45006, 45010}; static const float aKalecHumanLoc[4] = {1709.094f, 927.5035f, -74.28364f, 2.932153f}; /*###### ## boss_kalecgos ######*/ enum KalecgosActions { KALECGOS_ENRAGE, KALECGOS_ARCANE_BUFFET, KALECGOS_FROST_BREATH, KALECGOS_WILD_MAGIC, KALECGOS_SPECTRAL_BLAST, KALECGOS_TAIL_LASH, KALECGOS_ACTION_MAX, KALECGOS_EXIT_TIMER, }; struct boss_kalecgosAI : public CombatAI { boss_kalecgosAI(Creature* creature) : CombatAI(creature, KALECGOS_ACTION_MAX), m_instance(static_cast<instance_sunwell_plateau*>(creature->GetInstanceData())) { AddTimerlessCombatAction(KALECGOS_ENRAGE, true); AddCombatAction(KALECGOS_ARCANE_BUFFET, 8000u); AddCombatAction(KALECGOS_FROST_BREATH, 24000u); AddCombatAction(KALECGOS_WILD_MAGIC, 6000u); AddCombatAction(KALECGOS_SPECTRAL_BLAST, 15000, 18000); AddCombatAction(KALECGOS_TAIL_LASH, 5000u); AddCustomAction(KALECGOS_EXIT_TIMER, true, [&]() { HandleExit(); }); AddOnKillText(SAY_EVIL_SLAY_1, SAY_EVIL_SLAY_2); m_creature->GetCombatManager().SetLeashingCheck([](Unit* /*unit*/, float /*x*/, float y, float /*z*/) { return y < 762 || y > 1076; }); } instance_sunwell_plateau* m_instance; bool m_isCorrupted; uint32 m_exitStage; void Reset() override { CombatAI::Reset(); SetDeathPrevention(true); m_isCorrupted = true; m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE); } void Aggro(Unit* /*who*/) override { DoScriptText(SAY_EVIL_AGGRO, m_creature); if (m_instance) m_instance->SetData(TYPE_KALECGOS, IN_PROGRESS); if (Creature* sathrovarr = m_instance->GetSingleCreatureFromStorage(NPC_SATHROVARR)) m_creature->AI()->SendAIEvent(AI_EVENT_CUSTOM_B, m_creature, sathrovarr); } void JustPreventedDeath(Unit* /*attacker*/) override { // If Sathrovarr is not banished yet, then banish the boss if (m_isCorrupted) { DoCastSpellIfCan(nullptr, SPELL_BANISH, CAST_TRIGGERED); m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE); m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE_BUFF); } else DoStartOutro(); } void EnterEvadeMode() override { if (m_instance && m_instance->GetData(TYPE_KALECGOS) != DONE) { m_instance->DoEjectSpectralPlayers(); m_instance->SetData(TYPE_KALECGOS, FAIL); } else CombatAI::EnterEvadeMode(); } void DoStartOutro() { if (!m_instance) return; // Bring Sathrovarr in the normal realm and kill him if (Creature* sathrovarr = m_instance->GetSingleCreatureFromStorage(NPC_SATHROVARR)) { // The teleport spell doesn't work right for this, so we need to teleport him manually sathrovarr->CastSpell(nullptr, SPELL_TELEPORT_NORMAL_REALM, TRIGGERED_OLD_TRIGGERED); sathrovarr->CastSpell(nullptr, SPELL_CURSE_OF_BOUNDLESS_AGONY_REMOVAL, TRIGGERED_OLD_TRIGGERED); sathrovarr->SetInCombatWithZone(false); // for loot table sathrovarr->CastSpell(nullptr, SPELL_INSTAKILL_SELF, TRIGGERED_OLD_TRIGGERED); } m_instance->DoEjectSpectralPlayers(); if (Creature* kalec = m_instance->GetSingleCreatureFromStorage(NPC_KALECGOS_HUMAN)) kalec->ForcedDespawn(); if (m_instance) m_instance->SetData(TYPE_KALECGOS, DONE); m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE); m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE_BUFF); EnterEvadeMode(); m_exitStage = 0; m_creature->SetFactionTemporary(35, TEMPFACTION_RESTORE_RESPAWN); m_creature->GetMotionMaster()->MoveIdle(); ResetTimer(KALECGOS_EXIT_TIMER, 10000); } void MovementInform(uint32 motionType, uint32 pointId) override { if (motionType != POINT_MOTION_TYPE) return; if (pointId) m_creature->ForcedDespawn(1000); } void ReceiveAIEvent(AIEventType eventType, Unit* /*pSender*/, Unit* pInvoker, uint32 /*uiMiscValue*/) override { if (eventType == AI_EVENT_CUSTOM_A && m_instance) m_instance->AddToSpectralRealm(pInvoker->GetObjectGuid()); else if (eventType == AI_EVENT_CUSTOM_B) { if (m_creature->HasAura(SPELL_BANISH)) DoStartOutro(); else m_isCorrupted = false; } else if (eventType == AI_EVENT_CUSTOM_C) EnterEvadeMode(); else if (eventType == AI_EVENT_CUSTOM_E) { m_creature->CastSpell(nullptr, SPELL_CURSE_OF_BOUNDLESS_AGONY_REMOVAL, TRIGGERED_OLD_TRIGGERED); if (Creature* sathrovarr = m_instance->GetSingleCreatureFromStorage(NPC_SATHROVARR)) sathrovarr->CastSpell(nullptr, SPELL_CURSE_OF_BOUNDLESS_AGONY_REMOVAL, TRIGGERED_OLD_TRIGGERED); DoScriptText(SAY_EVIL_WIPE, m_creature); } } void HandleExit() { switch (m_exitStage) { case 0: { m_creature->HandleEmote(EMOTE_ONESHOT_LIFTOFF); m_creature->SetByteValue(UNIT_FIELD_BYTES_1, UNIT_BYTES_1_OFFSET_MISC_FLAGS, UNIT_BYTE1_FLAG_FLY_ANIM | UNIT_BYTE1_FLAG_ALWAYS_STAND); m_creature->SetLevitate(true); m_creature->SetHover(true); ResetTimer(KALECGOS_EXIT_TIMER, 4000); break; } case 1: { DoScriptText(SAY_GOOD_PLRWIN, m_creature); ResetTimer(KALECGOS_EXIT_TIMER, 10000); break; } case 2: { DoScriptText(SAY_GOOD_PLRWIN_3, m_creature); m_creature->GetMotionMaster()->MovePoint(1, 1614.355f, 846.9694f, 119.0971f); break; } } ++m_exitStage; } void ExecuteAction(uint32 action) override { switch (action) { case KALECGOS_ENRAGE: if (m_creature->GetHealthPercent() < 10.0f) if (DoCastSpellIfCan(m_creature, SPELL_CRAZED_RAGE) == CAST_OK) SetActionReadyStatus(action, false); break; case KALECGOS_ARCANE_BUFFET: if (DoCastSpellIfCan(m_creature->GetVictim(), SPELL_ARCANE_BUFFET) == CAST_OK) { if (!urand(0, 4)) DoScriptText(SAY_EVIL_SPELL_1, m_creature); ResetCombatAction(action, 10000); } break; case KALECGOS_FROST_BREATH: if (DoCastSpellIfCan(m_creature->GetVictim(), SPELL_FROST_BREATH, CAST_AURA_NOT_PRESENT) == CAST_OK) { if (!urand(0, 4)) DoScriptText(SAY_EVIL_SPELL_2, m_creature); ResetCombatAction(action, urand(10000, 25000)); } break; case KALECGOS_WILD_MAGIC: if (DoCastSpellIfCan(nullptr, aWildMagicSpells[urand(0, 5)]) == CAST_OK) ResetCombatAction(action, 6000); break; case KALECGOS_SPECTRAL_BLAST: if (!m_isCorrupted) return; if (DoCastSpellIfCan(nullptr, SPELL_SPECTRAL_BLAST) == CAST_OK) ResetCombatAction(action, urand(21000, 26000)); break; case KALECGOS_TAIL_LASH: if (DoCastSpellIfCan(nullptr, SPELL_TAIL_LASH) == CAST_OK) ResetCombatAction(action, urand(10000, 20000)); break; } } }; /*###### ## boss_sathrovarr ######*/ enum SathrovarrActions { SATHROVARR_ENRAGE, SATHROVARR_CURSE_OF_BOUNDLESS_AGONY, SATHROVARR_SHADOW_BOLT_VOLLEY, SATHROVARR_CORRUPTING_STRIKE, SATHROVARR_ACTION_MAX, }; struct boss_sathrovarrAI : public CombatAI { boss_sathrovarrAI(Creature* creature) : CombatAI(creature, SATHROVARR_ACTION_MAX), m_instance(static_cast<instance_sunwell_plateau*>(creature->GetInstanceData())) { AddTimerlessCombatAction(SATHROVARR_ENRAGE, true); AddCombatAction(SATHROVARR_CURSE_OF_BOUNDLESS_AGONY, 40000u); AddCombatAction(SATHROVARR_SHADOW_BOLT_VOLLEY, 10000u); AddCombatAction(SATHROVARR_CORRUPTING_STRIKE, 5000u); AddOnKillText(SAY_SATH_SLAY_1, SAY_SATH_SLAY_2); if (m_instance) { m_creature->GetCombatManager().SetLeashingCheck([](Unit* unit, float /*x*/, float /*y*/, float /*z*/) { return static_cast<ScriptedInstance*>(unit->GetInstanceData())->GetPlayerInMap(true, false) == nullptr; }); } } instance_sunwell_plateau* m_instance; bool m_firstShadow; void Reset() override { CombatAI::Reset(); DoCastSpellIfCan(m_creature, SPELL_SPECTRAL_INVISIBILITY); m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE); m_firstShadow = true; SetDeathPrevention(true); } void EnterEvadeMode() override { CombatAI::EnterEvadeMode(); if (Creature* kalecgos = m_instance->GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON)) SendAIEvent(AI_EVENT_CUSTOM_C, m_creature, kalecgos); } void ReceiveAIEvent(AIEventType eventType, Unit* /*sender*/, Unit* invoker, uint32 /*miscValue*/) override { if (eventType == AI_EVENT_CUSTOM_A && m_instance) m_instance->AddToSpectralRealm(invoker->GetObjectGuid()); // spawn human Kalec; he starts to attack else if (eventType == AI_EVENT_CUSTOM_B) m_creature->SummonCreature(NPC_KALECGOS_HUMAN, aKalecHumanLoc[0], aKalecHumanLoc[1], aKalecHumanLoc[2], aKalecHumanLoc[3], TEMPSPAWN_CORPSE_DESPAWN, 0, true); else if (eventType == AI_EVENT_CUSTOM_C) { if (!m_firstShadow) return; m_firstShadow = false; DoScriptText(SAY_SATH_AGGRO, m_creature); } } void JustPreventedDeath(Unit* /*attacker*/) override { // banish Sathrovarr and eject the players if (DoCastSpellIfCan(nullptr, SPELL_BANISH, CAST_TRIGGERED) != CAST_OK) { SetDeathPrevention(true); return; } m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE); m_creature->RemoveAurasDueToSpell(SPELL_CRAZED_RAGE_BUFF); if (!m_instance) return; if (Creature* kalecgos = m_instance->GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON)) SendAIEvent(AI_EVENT_CUSTOM_B, m_creature, kalecgos); } void JustDied(Unit* /*killer*/) override { DoScriptText(SAY_SATH_DEATH, m_creature); } void JustSummoned(Creature* summoned) override { if (summoned->GetEntry() == NPC_KALECGOS_HUMAN) summoned->AI()->AttackStart(m_creature); } void ExecuteAction(uint32 action) override { switch (action) { case SATHROVARR_ENRAGE: if (m_creature->GetHealthPercent() < 10.0f) if (DoCastSpellIfCan(m_creature, SPELL_CRAZED_RAGE) == CAST_OK) SetActionReadyStatus(action, false); break; case SATHROVARR_CURSE_OF_BOUNDLESS_AGONY: if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER)) if (DoCastSpellIfCan(target, SPELL_CURSE_OF_BOUNDLESS_AGONY) == CAST_OK) ResetCombatAction(action, 40000); break; case SATHROVARR_SHADOW_BOLT_VOLLEY: if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER | SELECT_FLAG_SKIP_TANK)) { if (DoCastSpellIfCan(target, SPELL_SHADOW_BOLT_VOLLEY) == CAST_OK) { if (!urand(0, 4)) DoScriptText(SAY_SATH_SPELL_1, m_creature); ResetCombatAction(action, 15000); } } break; case SATHROVARR_CORRUPTING_STRIKE: if (DoCastSpellIfCan(m_creature->GetVictim(), SPELL_CORRUPTING_STRIKE) == CAST_OK) { if (!urand(0, 4)) DoScriptText(SAY_SATH_SPELL_2, m_creature); ResetCombatAction(action, 13000); } break; } } }; /*###### ## boss_kalecgos_humanoid ######*/ enum KalecgosHumanActions { KALEC_YELL_75, KALEC_YELL_50, KALEC_YELL_25, KALEC_REVITALIZE, KALEC_HEROIC_STRIKE, KALEC_HUMAN_ACTION_MAX, KALEC_FORCEFIELD }; struct boss_kalecgos_humanoidAI : public CombatAI { boss_kalecgos_humanoidAI(Creature* creature) : CombatAI(creature, KALEC_HUMAN_ACTION_MAX), m_instance(static_cast<instance_sunwell_plateau*>(creature->GetInstanceData())) { AddTimerlessCombatAction(KALEC_YELL_75, true); AddTimerlessCombatAction(KALEC_YELL_50, true); AddTimerlessCombatAction(KALEC_YELL_25, true); AddCombatAction(KALEC_REVITALIZE, 30000u); AddCombatAction(KALEC_HEROIC_STRIKE, 8000u); AddCustomAction(KALEC_FORCEFIELD, true, [&]() { if (!m_creature->IsInCombat() || m_creature->GetCombatManager().IsEvadingHome()) return; // combat doors m_instance->DoUseDoorOrButton(GO_FORCEFIELD); m_instance->DoUseDoorOrButton(GO_BOSS_COLLISION_1); m_instance->DoUseDoorOrButton(GO_BOSS_COLLISION_2); }); } instance_sunwell_plateau* m_instance; void Reset() override { CombatAI::Reset(); DoCastSpellIfCan(nullptr, SPELL_SPECTRAL_INVISIBILITY); } void Aggro(Unit* /*who*/) override { ResetTimer(KALEC_FORCEFIELD, 3000); } void JustDied(Unit* /*killer*/) override { if (m_instance) { m_instance->DoEjectSpectralPlayers(); m_instance->SetData(TYPE_KALECGOS, FAIL); } } void EnterEvadeMode() override { m_creature->ForcedDespawn(); } void ExecuteAction(uint32 action) override { switch (action) { case KALEC_YELL_75: if (m_creature->GetHealthPercent() < 75.0f) { DoScriptText(SAY_GOOD_75, m_creature); SetActionReadyStatus(action, false); } break; case KALEC_YELL_50: if (m_creature->GetHealthPercent() < 50.0f) { DoScriptText(SAY_GOOD_50, m_creature); SetActionReadyStatus(action, false); } break; case KALEC_YELL_25: if (m_creature->GetHealthPercent() < 25.0f) { DoScriptText(SAY_GOOD_25, m_creature); SetActionReadyStatus(action, false); } break; case KALEC_REVITALIZE: if (DoCastSpellIfCan(nullptr, SPELL_REVITALIZE) == CAST_OK) ResetCombatAction(action, 30000); break; case KALEC_HEROIC_STRIKE: if (DoCastSpellIfCan(m_creature->GetVictim(), SPELL_HEROIC_STRIKE) == CAST_OK) ResetCombatAction(action, 30000); break; } } }; struct SpectralBlast : public SpellScript { bool OnCheckTarget(const Spell* spell, Unit* target, SpellEffectIndex /*eff*/) const override { if (spell->GetCaster()->getThreatManager().getThreatList().size() > 1 && spell->GetCaster()->GetVictim() == target) return false; if (target->HasAura(SPELL_SPECTRAL_EXHAUSTION) || target->HasAura(SPELL_SPECTRAL_REALM_AURA)) return false; return true; } void OnEffectExecute(Spell* spell, SpellEffectIndex /*effIdx*/) const override { Unit* unitTarget = spell->GetUnitTarget(); if (!unitTarget) return; spell->GetCaster()->getThreatManager().modifyThreatPercent(unitTarget, -100); // Cast the spectral realm effect spell, visual spell and spectral blast rift summoning unitTarget->CastSpell(nullptr, SPELL_SPECTRAL_BLAST_IMPACT, TRIGGERED_OLD_TRIGGERED); spell->GetCaster()->CastSpell(unitTarget, SPELL_SPECTRAL_BLAST_VISUAL, TRIGGERED_OLD_TRIGGERED); spell->GetCaster()->AI()->DoCastSpellIfCan(unitTarget, SPELL_SPECTRAL_REALM, CAST_INTERRUPT_PREVIOUS); } }; struct SpectralRealm : public SpellScript { void OnEffectExecute(Spell* spell, SpellEffectIndex /*effIdx*/) const override { Unit* unitTarget = spell->GetUnitTarget(); if (!unitTarget) return; // If the player can't be teleported, send him a notification if (unitTarget->HasAura(SPELL_SPECTRAL_EXHAUSTION) && unitTarget->IsPlayer()) { static_cast<Player*>(unitTarget)->GetSession()->SendNotification(LANG_FAIL_ENTER_SPECTRAL_REALM); return; } if (InstanceData* data = unitTarget->GetInstanceData()) if (data->GetData(TYPE_KALECGOS) == DONE) return; // Teleport target to the spectral realm, add debuff and force faction unitTarget->CastSpell(nullptr, SPELL_TELEPORT_SPECTRAL_REALM, TRIGGERED_OLD_TRIGGERED); unitTarget->CastSpell(nullptr, SPELL_SPECTRAL_REALM_AURA, TRIGGERED_OLD_TRIGGERED); unitTarget->CastSpell(nullptr, SPELL_SPECTRAL_REALM_NOTIFY, TRIGGERED_OLD_TRIGGERED); unitTarget->CastSpell(nullptr, SPELL_SPECTRAL_REALM_FORCE_F, TRIGGERED_OLD_TRIGGERED); if (auto instance = dynamic_cast<instance_sunwell_plateau*>(unitTarget->GetInstanceData())) if (Creature* sathrovarr = instance->GetSingleCreatureFromStorage(NPC_SATHROVARR)) sathrovarr->AI()->SendAIEvent(AI_EVENT_CUSTOM_C, sathrovarr, sathrovarr); } }; struct SpectralRealmNotify : public SpellScript { void OnEffectExecute(Spell* spell, SpellEffectIndex effIdx) const override { if (effIdx == EFFECT_INDEX_0 && spell->GetUnitTarget()) if (spell->GetCaster()->GetTypeId() == TYPEID_PLAYER) spell->GetUnitTarget()->AI()->SendAIEvent(AI_EVENT_CUSTOM_A, spell->GetCaster(), spell->GetUnitTarget()); } }; struct SpectralRealmAura : public AuraScript { void OnApply(Aura* aura, bool apply) const override { if (!apply && aura->GetEffIndex() == EFFECT_INDEX_0) { Unit* target = aura->GetTarget(); target->RemoveAurasDueToSpell(SPELL_SPECTRAL_REALM_FORCE_F); SpellCastResult result = target->CastSpell(nullptr, SPELL_TELEPORT_NORMAL_REALM, TRIGGERED_OLD_TRIGGERED); target->CastSpell(nullptr, SPELL_SPECTRAL_EXHAUSTION, TRIGGERED_OLD_TRIGGERED); if (auto instance = dynamic_cast<instance_sunwell_plateau*>(target->GetInstanceData())) instance->RemoveFromSpectralRealm(target->GetObjectGuid()); } } }; enum { SPELL_CURSE_OF_BOUNDLESS_AGONY_FRIENDLY = 45034, SPELL_COBA_ANIM_1 = 45083, SPELL_COBA_ANIM_2 = 45084, SPELL_COBA_ANIM_3 = 45085, }; struct CurseOfBoundlessAgony : public SpellScript, public AuraScript { bool OnCheckTarget(const Spell* spell, Unit* target, SpellEffectIndex eff) const override { if (target->IsImmuneToSpell(spell->m_spellInfo, false, (1 << eff), spell->GetCaster()) || target->IsImmuneToSpellEffect(spell->m_spellInfo, eff, false)) return false; if (target->HasAura(SPELL_CURSE_OF_BOUNDLESS_AGONY) || target->HasAura(SPELL_CURSE_OF_BOUNDLESS_AGONY_FRIENDLY)) return false; return true; } void OnApply(Aura* aura, bool apply) const override { if (!apply && aura->GetRemoveMode() != AURA_REMOVE_BY_CANCEL && aura->GetTarget()->GetMapId() == 580) // jump only in SWP { aura->GetTarget()->CastSpell(nullptr, SPELL_CURSE_OF_BOUNDLESS_AGONY_FRIENDLY, TRIGGERED_OLD_TRIGGERED); } } void OnPeriodicCalculateAmount(Aura* aura, uint32& amount) const override { uint32 multiples = (aura->GetAuraTicks() - 1) / 5; for (uint32 i = 0; i < multiples; ++i) amount *= 2; } void OnPeriodicTickEnd(Aura* aura) const override { uint32 spellId = 0; switch (aura->GetAuraTicks()) { case 0: spellId = SPELL_COBA_ANIM_1; break; case 1: spellId = SPELL_COBA_ANIM_2; break; default: spellId = SPELL_COBA_ANIM_3; break; } aura->GetTarget()->CastSpell(nullptr, spellId, TRIGGERED_OLD_TRIGGERED); } }; struct CurseOfBoundlessAgonyRemoval : public SpellScript, public AuraScript { void Remove(Unit* target) const { target->RemoveAurasDueToSpell(SPELL_CURSE_OF_BOUNDLESS_AGONY, nullptr, AURA_REMOVE_BY_CANCEL); target->RemoveAurasDueToSpell(SPELL_CURSE_OF_BOUNDLESS_AGONY_FRIENDLY, nullptr, AURA_REMOVE_BY_CANCEL); } void OnEffectExecute(Spell* spell, SpellEffectIndex effIdx) const override { if (effIdx == EFFECT_INDEX_1 && spell->GetUnitTarget()) Remove(spell->GetUnitTarget()); } void OnApply(Aura* aura, bool /*apply*/) const override { Remove(aura->GetTarget()); } void OnPeriodicTickEnd(Aura* aura) const override { Remove(aura->GetTarget()); } }; struct CrazedRage : public SpellScript { bool OnCheckTarget(const Spell* /*spell*/, Unit* target, SpellEffectIndex /*eff*/) const override { if (target->IsPlayer() || (target->GetEntry() != NPC_KALECGOS_DRAGON && target->GetEntry() != NPC_SATHROVARR) || target->HasAura(SPELL_BANISH)) return false; return true; } }; void AddSC_boss_kalecgos() { Script* pNewScript = new Script; pNewScript->Name = "boss_kalecgos"; pNewScript->GetAI = &GetNewAIInstance<boss_kalecgosAI>; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "boss_sathrovarr"; pNewScript->GetAI = &GetNewAIInstance<boss_sathrovarrAI>; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "boss_kalecgos_humanoid"; pNewScript->GetAI = &GetNewAIInstance<boss_kalecgos_humanoidAI>; pNewScript->RegisterSelf(); RegisterSpellScript<SpectralBlast>("spell_spectral_blast"); RegisterSpellScript<SpectralRealm>("spell_spectral_realm"); RegisterSpellScript<SpectralRealmNotify>("spell_spectral_realm_notify"); RegisterSpellScript<SpectralRealmAura>("spell_spectral_realm_aura"); RegisterSpellScript<CurseOfBoundlessAgony>("spell_curse_of_boundless_agony"); RegisterSpellScript<CurseOfBoundlessAgonyRemoval>("spell_curse_of_boundless_agony_removal"); RegisterSpellScript<CrazedRage>("spell_crazed_rage"); }
0
0.90249
1
0.90249
game-dev
MEDIA
0.991499
game-dev
0.978939
1
0.978939
Frontiers-PackForge/CosmicFrontiers
9,460
overrides/kubejs/server_scripts/Recipes/Chains/NuclearRecipes.js
const $ChanceLogic = Java.loadClass('com.gregtechceu.gtceu.api.recipe.chance.logic.ChanceLogic') ServerEvents.recipes(event => { event.recipes.gtceu.mixer(`flinak`) .itemInputs('gtceu:lithium_dust') .inputFluids('gtceu:fluorine 1000') .inputFluids('gtceu:sodium_potassium 1000') .outputFluids('gtceu:flinak 3000') .duration(80) .EUt(GTValues.VA[GTValues.HV]); event.recipes.gtceu.centrifuge(`uranium_waste_reproc_tier_1`) .inputFluids(`gtceu:waste_uranium_fuel_salt 1000`) .outputFluids(`gtceu:fluorine 6000`) .outputFluids(`gtceu:flinak 1000`) .itemOutputs('gtceu:plutonium_dust') .chancedOutput(`gtceu:uranium_dust`, 500, 500) .itemOutputsRanged('gtceu:neptunium_dust', 2, 4) .itemOutputsRanged('gtceu:plutonium_dust', 1, 2) .itemOutputsRanged('gtceu:americium_dust', 1, 2) .chancedOutput(`gtceu:americium_dust`, 3500, 1500) .duration(120) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.centrifuge(`americium_waste_reproc_tier_1`) .inputFluids(`gtceu:waste_americium_fuel_salt 1000`) .outputFluids(`gtceu:fluorine 6000`) .outputFluids(`gtceu:flinak 1000`) .itemOutputs('gtceu:curium_dust') .chancedOutput(`gtceu:americium_dust`, 500, 500) .itemOutputsRanged('gtceu:berkelium_dust', 1, 2) .itemOutputsRanged('gtceu:californium_dust', 1, 2) .chancedOutput('gtceu:californium_dust', 3500, 1500) .duration(120) .EUt(GTValues.VA[GTValues.IV]); // event.recipes.gtceu.chemical_reactor("test_xor") // .itemInputs('1x minecraft:stone') // .chancedFluidOutputLogic($ChanceLogic.XOR) // .chancedFluidOutput('gtceu:oxygen 500', 5000, 0) // .chancedFluidOutput('gtceu:fluorine 500', 2500, 0) // .duration(400) // .EUt(25) let saltFuelt1 = [ 'uranium', ] let saltFuelt2 = [ 'americium', ] let saltFuelt3 = [ 'californium', ] let saltFuelt4 = [ 'medelevium', ] let saltFuelt5 = [ 'lawrencium', ] let coilTier = [ 'cupronickel', 'kanthal', 'nichrome', 'tungstensteel', 'hssg', 'naquadah', 'trinium', 'tritanium' ] saltFuelt1.forEach((tier) => { event.recipes.gtceu.centrifuge(`${tier}_fluoride_centri`) .inputFluids(`gtceu:${tier}_hexafluoride 1000`) .outputFluids(`gtceu:depleted_${tier}_hexafluoride 900`) .outputFluids(`gtceu:enriched_${tier}_hexafluoride 100`) .duration(100) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.chemical_reactor(`${tier}_salt_fuel`) .inputFluids(`gtceu:depleted_${tier}_hexafluoride 9000`) .inputFluids(`gtceu:enriched_${tier}_hexafluoride 1000`) .inputFluids(`gtceu:flinak 10000`) .outputFluids(`gtceu:${tier}_fuel_salt 10000`) .duration(200) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.molten_salt_reactor(`${tier}_salt_reaction_equal`) .inputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids(`gtceu:superheated_${tier}_fuel_salt 500`) .outputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 500`) .circuit(1) .duration(120) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.molten_salt_reactor(`${tier}_salt_reaction_breeder`) .inputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids([`gtceu:superheated_${tier}_fuel_salt 250`, `gtceu:superheated_waste_${tier}_fuel_salt 750`]) .circuit(2) .duration(120) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.molten_salt_reactor(`${tier}_salt_reaction_power`) .inputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids(`gtceu:superheated_${tier}_fuel_salt 750`) .outputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 250`) .circuit(3) .duration(120) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam(`${tier}_salt_waste_freezing_steamy`) .inputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:waste_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:super_critical_steam 32000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam_vent(`${tier}_salt_waste_freezing_steamy_lossy`) .inputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:waste_${tier}_fuel_salt 1000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam(`${tier}_salt_freezing_steamy`) .inputFluids(`gtceu:superheated_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids(`gtceu:super_critical_steam 32000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam_vent(`${tier}_salt_freezing_steamy_lossy`) .inputFluids(`gtceu:superheated_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:${tier}_fuel_salt 1000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); }) event.recipes.gtceu.chemical_reactor(`americium_oxide`) .itemInputs('gtceu:americium_dust') .inputFluids('gtceu:oxygen 2000') .itemOutputs(`3x gtceu:americium_oxide_dust`) .duration(80) .EUt(GTValues.VA[GTValues.LV]); event.recipes.gtceu.chemical_reactor(`americium_hexa`) .itemInputs('3x gtceu:americium_oxide_dust') .inputFluids('gtceu:hydrofluoric_acid 4000') .inputFluids('gtceu:fluorine 2000') .outputFluids('gtceu:americium_hexafluoride 1000') .outputFluids('minecraft:water 1000') .duration(80) .EUt(GTValues.VA[GTValues.LV]); saltFuelt2.forEach((tier) => { event.recipes.gtceu.centrifuge(`${tier}_fluoride_centri`) .inputFluids(`gtceu:${tier}_hexafluoride 1000`) .outputFluids(`gtceu:depleted_${tier}_hexafluoride 900`) .outputFluids(`gtceu:enriched_${tier}_hexafluoride 100`) .duration(100) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.chemical_reactor(`${tier}_salt_fuel`) .inputFluids(`gtceu:depleted_${tier}_hexafluoride 9000`) .inputFluids(`gtceu:enriched_${tier}_hexafluoride 1000`) .inputFluids(`gtceu:flinak 10000`) .outputFluids(`gtceu:${tier}_fuel_salt 10000`) .duration(200) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.molten_salt_reactor(`${tier}_salt_reaction_equal`) .inputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids(`gtceu:superheated_${tier}_fuel_salt 500`) .outputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 500`) .circuit(1) .duration(120) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.molten_salt_reactor(`${tier}_salt_reaction_breeder`) .inputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids(`gtceu:superheated_${tier}_fuel_salt 250`) .outputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 750`) .circuit(2) .duration(120) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.molten_salt_reactor(`${tier}_salt_reaction_power`) .inputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids(`gtceu:superheated_${tier}_fuel_salt 750`) .outputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 250`) .circuit(3) .duration(120) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam(`${tier}_salt_waste_freezing_steamy`) .inputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:waste_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:super_critical_steam 32000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam_vent(`${tier}_salt_waste_freezing_steamy_lossy`) .inputFluids(`gtceu:superheated_waste_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:waste_${tier}_fuel_salt 1000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam(`${tier}_salt_freezing_steamy`) .inputFluids(`gtceu:superheated_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:${tier}_fuel_salt 1000`) .outputFluids(`gtceu:super_critical_steam 32000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); event.recipes.gtceu.pulse_exchange_steam_vent(`${tier}_salt_freezing_steamy_lossy`) .inputFluids(`gtceu:superheated_${tier}_fuel_salt 1000`) .outputFluids(`gtceu:${tier}_fuel_salt 1000`) .duration(240) .EUt(GTValues.VA[GTValues.EV]); }) saltFuelt3.forEach((tier) => { }) saltFuelt4.forEach((tier) => { }) saltFuelt5.forEach((tier) => { }) })
0
0.824911
1
0.824911
game-dev
MEDIA
0.907122
game-dev
0.868606
1
0.868606
LordOfDragons/dragengine
4,766
src/deigde/editors/rigeditor/src/rig/shape/reSelectionShapes.cpp
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "reSelectionShapes.h" #include "reRigShape.h" #include "reRigShapeList.h" #include "../reRig.h" #include "dragengine/common/exceptions.h" // Class reSelectionShapes //////////////////////////// // Constructor, destructor //////////////////////////// reSelectionShapes::reSelectionShapes( reRig *rig ){ if( ! rig ) DETHROW( deeInvalidParam ); pRig = rig; pShapes = NULL; pShapeCount = 0; pShapeSize = 0; pActiveShape = NULL; } reSelectionShapes::~reSelectionShapes(){ Reset(); if( pShapes ) delete [] pShapes; } // Management /////////////// reRigShape *reSelectionShapes::GetShapeAt( int index ) const{ if( index < 0 || index >= pShapeCount ) DETHROW( deeOutOfBoundary ); return pShapes[ index ]; } bool reSelectionShapes::HasShape( reRigShape *shape ) const{ if( ! shape ) DETHROW( deeInvalidParam ); int i; for( i=0; i<pShapeCount; i++ ){ if( shape == pShapes[ i ] ){ return true; } } return false; } int reSelectionShapes::IndexOfShape( reRigShape *shape ) const{ if( ! shape ) DETHROW( deeInvalidParam ); int i; for( i=0; i<pShapeCount; i++ ){ if( shape == pShapes[ i ] ){ return i; } } return -1; } int reSelectionShapes::IndexOfShapeWith( deColliderVolume *collider ) const{ if( ! collider ) DETHROW( deeInvalidParam ); int i; for( i=0; i<pShapeCount; i++ ){ if( collider == pShapes[ i ]->GetCollider() ){ return i; } } return -1; } void reSelectionShapes::AddShape( reRigShape *shape ){ if( HasShape( shape ) ) DETHROW( deeInvalidParam ); if( pShapeCount == pShapeSize ){ int newSize = pShapeSize * 3 / 2 + 1; reRigShape **newArray = new reRigShape*[ newSize ]; if( ! newArray ) DETHROW( deeOutOfMemory ); if( pShapes ){ memcpy( newArray, pShapes, sizeof( reRigShape* ) * pShapeSize ); delete [] pShapes; } pShapes = newArray; pShapeSize = newSize; } pShapes[ pShapeCount ] = shape; pShapeCount++; shape->AddReference(); shape->SetSelected( true ); pRig->NotifyShapeSelectedChanged( shape ); if( pActiveShape == NULL ){ SetActiveShape( shape ); } } void reSelectionShapes::RemoveShape( reRigShape *shape ){ int i, index = IndexOfShape( shape ); if( index == -1 ) DETHROW( deeInvalidParam ); for( i=index+1; i<pShapeCount; i++ ){ pShapes[ i - 1 ] = pShapes[ i ]; } pShapes[ pShapeCount - 1 ] = NULL; pShapeCount--; shape->SetSelected( false ); if( shape == pActiveShape ){ if( pShapeCount > 0 ){ SetActiveShape( pShapes[ 0 ] ); }else{ SetActiveShape( NULL ); } } pRig->NotifyShapeSelectedChanged( shape ); shape->FreeReference(); } void reSelectionShapes::RemoveAllShapes(){ SetActiveShape( NULL ); pRig->NotifyAllShapesDeselected(); while( pShapeCount > 0 ){ pShapeCount--; pShapes[ pShapeCount ]->SetSelected( false ); pShapes[ pShapeCount ]->FreeReference(); } } bool reSelectionShapes::HasActiveShape() const{ return pActiveShape != NULL; } void reSelectionShapes::SetActiveShape( reRigShape *shape ){ if( shape != pActiveShape ){ if( shape && ! HasShape( shape ) ) DETHROW( deeInvalidParam ); if( pActiveShape ){ pActiveShape->SetActive( false ); } pActiveShape = shape; if( shape ){ shape->SetActive( true ); } pRig->NotifyActiveShapeChanged(); } } void reSelectionShapes::Reset(){ RemoveAllShapes(); } void reSelectionShapes::AddVisibleShapesTo( reRigShapeList &list ) const{ int s; for( s=0; s<pShapeCount; s++ ){ if( pShapes[ s ]->IsVisible() ){ list.AddShape( pShapes[ s ] ); } } }
0
0.992348
1
0.992348
game-dev
MEDIA
0.621621
game-dev
0.949526
1
0.949526
BuildCraft/BuildCraft
2,622
src_old_license/buildcraft/energy/gui/ContainerEngine.java
/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com * <p/> * BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents * of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */ package buildcraft.energy.gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import buildcraft.core.lib.engines.TileEngineWithInventory; import buildcraft.core.lib.gui.BuildCraftContainer; import buildcraft.core.lib.gui.widgets.FluidTankWidget; import buildcraft.energy.TileEngineIron; import buildcraft.energy.TileEngineStone; import buildcraft.lib.gui.ContainerBC_Neptune; public class ContainerEngine extends ContainerBC_Neptune { protected TileEngineWithInventory engine; public ContainerEngine(EntityPlayer player, TileEngineWithInventory tileEngine) { super(player, tileEngine.getSizeInventory()); engine = tileEngine; int yOffset = 0; if (tileEngine instanceof TileEngineStone) { addSlotToContainer(new Slot(tileEngine, 0, 80, 41)); } else {// Assume TileEngineIron TileEngineIron combustionEngine = (TileEngineIron) tileEngine; FluidTankWidget fuelWidget = new FluidTankWidget(combustionEngine.tankFuel, 26, 19, 16, 58).withOverlay(176, 0); addWidget(fuelWidget); addWidget(fuelWidget.copyMoved(combustionEngine.tankCoolant, 80, 19)); addWidget(fuelWidget.copyMoved(combustionEngine.tankResidue, 134, 19)); yOffset = 11; } for (int i = 0; i < 3; i++) { for (int k = 0; k < 9; k++) { addSlotToContainer(new Slot(player.inventory, k + i * 9 + 9, 8 + k * 18, 84 + i * 18 + yOffset)); } } for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(player.inventory, j, 8 + j * 18, 142 + yOffset)); } } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); for (Object crafter : crafters) { engine.sendGUINetworkData(this, (ICrafting) crafter); } } @Override public void updateProgressBar(int i, int j) { engine.getGUINetworkData(i, j); } public boolean isUsableByPlayer(EntityPlayer entityplayer) { return engine.isUseableByPlayer(entityplayer); } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return engine.isUseableByPlayer(entityplayer); } }
0
0.841748
1
0.841748
game-dev
MEDIA
0.992464
game-dev
0.872839
1
0.872839
EphemeralSpace/ephemeral-space
3,309
Content.Shared/Containers/SlotBasedConnectedContainerSystem.cs
using System.Diagnostics.CodeAnalysis; using Content.Shared.Chemistry.Components; using Content.Shared.Inventory; using Content.Shared.Whitelist; using Robust.Shared.Containers; namespace Content.Shared.Containers; /// <summary> /// System for getting container that is linked to subject entity. Container is supposed to be present in certain character slot. /// Can be used for linking ammo feeder, solution source for spray nozzle, etc. /// </summary> public sealed class SlotBasedConnectedContainerSystem : EntitySystem { [Dependency] private readonly SharedContainerSystem _containers = default!; [Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!; [Dependency] private readonly InventorySystem _inventory = default!; /// <inheritdoc /> public override void Initialize() { SubscribeLocalEvent<SlotBasedConnectedContainerComponent, GetConnectedContainerEvent>(OnGettingConnectedContainer); } /// <summary> /// Try get connected container entity in character slots for <see cref="uid"/>. /// </summary> /// <param name="uid"> /// Entity for which connected container is required. If <see cref="SlotBasedConnectedContainerComponent"/> /// is used - tries to find container in slot, returns false and null <see cref="slotEntity"/> otherwise. /// </param> /// <param name="slotEntity">Found connected container entity or null.</param> /// <returns>True if connected container was found, false otherwise.</returns> public bool TryGetConnectedContainer(EntityUid uid, [NotNullWhen(true)] out EntityUid? slotEntity) { if (!TryComp<SlotBasedConnectedContainerComponent>(uid, out var component)) { slotEntity = null; return false; } return TryGetConnectedContainer(uid, component.TargetSlot, component.ContainerWhitelist, out slotEntity); } private void OnGettingConnectedContainer(Entity<SlotBasedConnectedContainerComponent> ent, ref GetConnectedContainerEvent args) { if (TryGetConnectedContainer(ent, ent.Comp.TargetSlot, ent.Comp.ContainerWhitelist, out var val)) args.ContainerEntity = val; } private bool TryGetConnectedContainer(EntityUid uid, SlotFlags slotFlag, EntityWhitelist? providerWhitelist, [NotNullWhen(true)] out EntityUid? slotEntity) { slotEntity = null; if (!_containers.TryGetContainingContainer((uid, null, null), out var container)) return false; var user = container.Owner; if (!_inventory.TryGetContainerSlotEnumerator(user, out var enumerator, slotFlag)) return false; while (enumerator.NextItem(out var item)) { if (_whitelistSystem.IsWhitelistFailOrNull(providerWhitelist, item)) continue; slotEntity = item; return true; } return false; } } /// <summary> /// Event for an attempt of getting container, connected to entity on which event was raised. /// Fills <see cref="ContainerEntity"/> if connected container exists. /// </summary> [ByRefEvent] public struct GetConnectedContainerEvent { /// <summary> /// Container entity, if it exists, or null. /// </summary> public EntityUid? ContainerEntity; }
0
0.904301
1
0.904301
game-dev
MEDIA
0.551931
game-dev
0.941548
1
0.941548
fredsa/gritsgame
3,303
src/shared/weaponinstances/BounceBallBullet.js
/*Copyright 2012 Google Inc. All Rights Reserved. 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.*/ BounceBallBulletClass = WeaponInstanceClass.extend({ rotAngle: 0, lifetime: 0, physBody: null, init: function (x, y, settings) { this.parent(x, y, settings); var owningPlayer = gGameEngine.namedEntities[settings.owner]; var startPos = settings.pos; var dir = settings.dir; //this.parent(owningPlayer); this.lifetime = 101; //DETERMINE WHAT OUR ROTATION ANGLE IS rotAngle = 0; var guid = newGuid_short(); //create our physics body; var entityDef = { id: "MachineBullet" + guid, x: startPos.x, y: startPos.y, halfHeight: 5 * 0.5, halfWidth: 11 * 0.5, damping: 0, angle: rotAngle, useBouncyFixture: true, categories: ['projectile', owningPlayer.team == 0 ? 'team0' : 'team1'], collidesWith: ['mapobject', owningPlayer.team == 0 ? 'team1' : 'team0'], userData: { "id": "wpnMachineBullet" + guid, "ent": this } }; this.physBody = gPhysicsEngine.addBody(entityDef); this.physBody.SetLinearVelocity(new Vec2(dir.x * 800, dir.y * 800)); }, kill: function () { //remove my physics body gPhysicsEngine.removeBodyAsObj(this.physBody); this.physBody = null; //destroy me as an ent. gGameEngine.removeEntity(this); }, update: function () { this.lifetime--; if (this.lifetime <= 0) { this.kill(); return; } if (this.physBody != null) { this.autoAdjustVelocity(); var pPos = this.physBody.GetPosition(); this.pos.x = pPos.x; this.pos.y = pPos.y; } this.parent(); }, sendUpdates: function () { this.sendPhysicsUpdates(); }, onTouch: function (otherBody, point, impulse) { if (!this.physBody) { // The object has already been killed, ignore return false; } if (otherBody ==null || !otherBody.GetUserData()) { Logger.log("Invalid collision object"); return false; //invalid object?? } var physOwner = otherBody.GetUserData().ent; if (physOwner != null) { if (physOwner._killed) return false; //spawn impact visual if (!IS_SERVER) { var pPos = this.physBody.GetPosition(); var ent = gGameEngine.spawnEntity("BounceBallImpact", pPos.x, pPos.y, null); // TODO: pass in settings ent.onInit(pPos); } else { gGameEngine.dealDmg(this,physOwner,parseInt(5 * this.damageMultiplier)); } this.markForDeath = true; } else { // The bullet should bounce off walls and other things using box2d } return true; //return false if we don't validate the collision }, }); Factory.nameClassMap['BounceBallBullet'] = BounceBallBulletClass;
0
0.801951
1
0.801951
game-dev
MEDIA
0.854376
game-dev
0.609662
1
0.609662
SimpleSSD/SimpleSSD-FullSystem
7,845
ext/dsent/libutil/String.h
/* Copyright (c) 2012 Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef __STRING_H__ #define __STRING_H__ #include <string> #include <cstdarg> #include <vector> #include <sstream> #include <bitset> namespace LibUtil { using std::string; using std::vector; class String : public string { public: static String format(const String& format_, ...); static String format(const String& format_, va_list args_); template<class T> static String toString(const T& value_); static String toBitString(unsigned int value_, unsigned int num_bits_); template<class T> static T fromString(const String& str_); private: static const unsigned int msBufferSize; public: String(); String(const string& str_); String(const char* str_, size_t n); String(const char* str_); String(size_t n, char c); String(int value_); String(unsigned int value_); String(long value_); String(unsigned long value_); String(float value_); String(double value_); String(bool value_); ~String(); public: // Remove leading and trailing whitespace String& trim(); // Substitute str1 with str2 String& substitute(const String& str1_, const String& str2_); // Split the String into vector of Strings separated by delimiters_ vector<String> split(const char* delimiters_) const; vector<String> split(const String* delimiters_, unsigned int num_delimiters_ = 1) const; vector<String> splitByString(const String& delimiters_) const; // Check if contains str bool contain(const String& str_) const; public: // Convertions const char* toCString() const; int toInt() const; unsigned int toUInt() const; long toLong() const; unsigned long toULong() const; float toFloat() const; double toDouble() const; bool toBool() const; operator const char*() const; operator int() const; operator unsigned int() const; operator long() const; operator unsigned long() const; operator float() const; operator double() const; operator bool() const; String& operator=(char c_); }; template<class T> String String::toString(const T& value_) { std::ostringstream ost; ost << value_; return ost.str(); } template<> inline String String::toString<bool>(const bool& value_) { if(value_ == true) { return "TRUE"; } else { return "FALSE"; } } inline String String::toBitString(unsigned int value_, unsigned int num_bits_) { std::bitset<sizeof(unsigned int)*8> bitSet(value_); String ret = String(bitSet.to_string()); ret = ret.substr(ret.length()-num_bits_); return ret; } template<class T> T String::fromString(const String& str_) { T ret; std::istringstream ist(str_); ist >> ret; return ret; } template<> inline String String::fromString<String>(const String& str_) { return str_; } template<> inline bool String::fromString<bool>(const String& str_) { bool ret; if((str_ == String("TRUE")) || (str_ == String("true"))) { ret = true; } else if((str_ == string("FALSE")) || (str_ == String("false"))) { ret = false; } else { //std::cerr << "Invalid bool value: " << str_ << std::endl; throw ("Invalid bool value: " + str_); } return ret; } template<class T> String arrayToString( const T* array_, unsigned int start_index_, unsigned int end_index_, const String& delimiters_ ) { // Ensure end_index_ >= start_index_ + 1 if(end_index_ <= start_index_) { throw("Invalid index range: start_index = " + (String)start_index_ + ", end_index = " + (String)end_index_); } String ret = "["; for(unsigned int i = start_index_; i < (end_index_-1); ++i) { ret += (String)array_[i] + delimiters_; } ret += (String)array_[end_index_-1] + "]"; return ret; } template<class T> String arrayToString(const T* array_, unsigned int num_elements_) { return arrayToString(array_, 0, num_elements_, ", "); } template<class T> String arrayToString(const T* array_, unsigned int start_index_, unsigned int end_index_) { return arrayToString(array_, start_index_, end_index_); } template<class T> String vectorToString( const vector<T>& vector_, unsigned int start_index_, unsigned int end_index_, const String& delimiters_ ) { // Ensure end_index_ >= start_index_ + 1, or if the vector is empty if((end_index_ <= start_index_) || (end_index_ > vector_.size())) { // If the vector is empty, return empty array if (vector_.size() == 0) return "[]"; throw("Invalid index range: start_index = " + (String)start_index_ + ", end_index = " + (String)end_index_); } String ret = "["; for(unsigned int i = start_index_; i < (end_index_-1); ++i) { ret += (String)vector_[i] + delimiters_; } ret += (String)vector_[end_index_-1] + "]"; return ret; } template<class T> String vectorToString(const vector<T>& vector_) { return vectorToString(vector_, 0, vector_.size(), ", "); } template<class T> String vectorToString(const vector<T>& vector_, unsigned int num_elements_) { return vectorToString(vector_, 0, num_elements_, ", "); } template<class T> String vectorToString(const vector<T>& vector_, unsigned int start_index_, unsigned int end_index_) { return vectorToString(vector_, start_index_, end_index_); } template<class T> vector<T> castStringVector(const vector<String>& vector_) { vector<T> ret_vector; for(unsigned int i = 0; i < vector_.size(); ++i) { ret_vector.push_back((T)vector_[i]); } return ret_vector; } std::istream& safeGetline(std::istream& is_, String& str_); } // namespace LibUtil #endif // __STRING_H__
0
0.788956
1
0.788956
game-dev
MEDIA
0.233746
game-dev
0.77018
1
0.77018
Nero-TheThrill/JinEngine
7,319
Project/SNAKE_Engine/Private/Collider.cpp
#include "Engine.h" #define GLM_ENABLE_EXPERIMENTAL #include <unordered_set> #include "gtx/norm.hpp" constexpr int LARGE_OBJECT_THRESHOLD = 128; float CircleCollider::GetRadius() const { return useTransformScale ? baseRadius * std::max(glm::abs(owner->GetWorldScale().x), glm::abs(owner->GetWorldScale().y)): scaledRadius; } float CircleCollider::GetSize() const { return GetRadius() * 2.f; } void CircleCollider::SetRadius(float r) { baseRadius = r; if (!useTransformScale) scaledRadius = r; } float CircleCollider::GetBoundingRadius() const { return GetRadius(); } bool CircleCollider::CheckCollision(const Collider* other) const { return other->DispatchAgainst(*this); } bool CircleCollider::DispatchAgainst(const CircleCollider& other) const { glm::vec2 a = owner->GetWorldPosition()+ GetOffset(); glm::vec2 b = other.GetOwner()->GetWorldPosition() + other.GetOwner()->GetCollider()->GetOffset(); float distSqr = glm::length2(a - b); float rSum = GetRadius() + other.GetRadius(); return distSqr <= rSum * rSum; } bool CircleCollider::DispatchAgainst(const AABBCollider& other) const { return other.DispatchAgainst(*this); } void CircleCollider::SyncWithTransformScale() { if (!useTransformScale) return; float scale = std::max(glm::abs(owner->GetWorldScale().x),glm::abs(owner->GetWorldScale().y)); scaledRadius = baseRadius * scale; } bool CircleCollider::CheckPointCollision(const glm::vec2& point) const { glm::vec2 center = owner->GetWorldPosition() + GetOffset(); float distSqr = glm::dot(center - point, center - point); return distSqr <= GetRadius() * GetRadius(); } void CircleCollider::DrawDebug(RenderManager* rm, Camera2D* cam, const glm::vec4& color) const { glm::vec2 center = owner->GetWorldPosition() + GetOffset(); float r = GetRadius(); const int segments = 20; const float angleStep = glm::two_pi<float>() / segments; for (int i = 0; i < segments; ++i) { float angleA = i * angleStep; float angleB = (i + 1) * angleStep; glm::vec2 a = center + r * glm::vec2(std::cos(angleA), std::sin(angleA)); glm::vec2 b = center + r * glm::vec2(std::cos(angleB), std::sin(angleB)); rm->DrawDebugLine(a, b, cam, color); } } glm::vec2 AABBCollider::GetHalfSize() const { return useTransformScale ? baseHalfSize * glm::abs(owner->GetWorldScale()) : scaledHalfSize; } glm::vec2 AABBCollider::GetSize() const { return GetHalfSize() * glm::vec2(2); } void AABBCollider::SetSize(const glm::vec2& size) { baseHalfSize = size/glm::vec2(2); if (!useTransformScale) scaledHalfSize = size / glm::vec2(2); } float AABBCollider::GetBoundingRadius() const { glm::vec2 half = GetHalfSize(); return glm::length(half); } bool AABBCollider::CheckCollision(const Collider* other) const { return other->DispatchAgainst(*this); } bool AABBCollider::CheckPointCollision(const glm::vec2& point) const { glm::vec2 center = owner->GetWorldPosition() + GetOffset(); glm::vec2 half = GetHalfSize(); glm::vec2 min = center - half; glm::vec2 max = center + half; return point.x >= min.x && point.x <= max.x && point.y >= min.y && point.y <= max.y; } bool AABBCollider::DispatchAgainst(const AABBCollider& other) const { glm::vec2 aPos = owner->GetWorldPosition() + GetOffset(); glm::vec2 bPos = other.GetOwner()->GetWorldPosition()+other.GetOwner()->GetCollider()->GetOffset(); glm::vec2 aHalf = GetHalfSize(); glm::vec2 bHalf = other.GetHalfSize(); return std::abs(aPos.x - bPos.x) <= (aHalf.x + bHalf.x) && std::abs(aPos.y - bPos.y) <= (aHalf.y + bHalf.y); } void AABBCollider::SyncWithTransformScale() { if (useTransformScale) scaledHalfSize = baseHalfSize * glm::abs(owner->GetWorldScale()); } void AABBCollider::DrawDebug(RenderManager* rm, Camera2D* cam, const glm::vec4& color) const { glm::vec2 center = owner->GetWorldPosition()+GetOffset(); glm::vec2 half = GetHalfSize(); glm::vec2 min = center - half; glm::vec2 max = center + half; rm->DrawDebugLine({ min.x, min.y }, { max.x, min.y }, cam, color); rm->DrawDebugLine({ max.x, min.y }, { max.x, max.y }, cam, color); rm->DrawDebugLine({ max.x, max.y }, { min.x, max.y }, cam, color); rm->DrawDebugLine({ min.x, max.y }, { min.x, min.y }, cam, color); } bool AABBCollider::DispatchAgainst(const CircleCollider& other) const { glm::vec2 aPos = owner->GetWorldPosition() + GetOffset(); glm::vec2 half = GetHalfSize(); glm::vec2 circlePos = other.GetOwner()->GetWorldPosition() + other.GetOwner()->GetCollider()->GetOffset(); float radius = other.GetRadius(); glm::vec2 closest = glm::clamp(circlePos, aPos - half, aPos + half); float distSqr = glm::length2(circlePos - closest); return distSqr <= radius * radius; } void SpatialHashGrid::Clear() { grid.clear(); objects.clear(); largeObjects.clear(); } void SpatialHashGrid::Insert(Object* obj) { if (!obj->IsAlive() || !obj->GetCollider()) return; objects.push_back(obj); Collider* collider = obj->GetCollider(); glm::vec2 offset = collider? collider->GetOffset(): glm::vec2(0); glm::vec2 pos = obj->GetWorldPosition()+ offset; float radius = obj->GetCollider()->GetBoundingRadius(); glm::ivec2 minCell = GetCell(pos - glm::vec2(radius)); glm::ivec2 maxCell = GetCell(pos + glm::vec2(radius)); int coveredCells = (maxCell.x - minCell.x + 1) * (maxCell.y - minCell.y + 1); if (coveredCells > LARGE_OBJECT_THRESHOLD) { largeObjects.push_back(obj); return; } for (int y = minCell.y; y <= maxCell.y; ++y) { for (int x = minCell.x; x <= maxCell.x; ++x) { InsertToCell(obj, { x, y }); } } } void SpatialHashGrid::ComputeCollisions(std::function<void(Object*, Object*)> onCollision) { for (auto obj : largeObjects) { for (auto* other : objects) { if (obj != other) onCollision(obj, other); } } for (auto& [cell, list] : grid) { const size_t count = list.size(); for (size_t i = 0; i < count; ++i) { for (size_t j = i + 1; j < count; ++j) { onCollision(list[i], list[j]); } } } } glm::ivec2 SpatialHashGrid::GetCell(const glm::vec2& pos) const { return glm::ivec2( static_cast<int>(std::floor(pos.x / cellSize)), static_cast<int>(std::floor(pos.y / cellSize)) ); } void SpatialHashGrid::InsertToCell(Object* obj, const glm::ivec2& cell) { grid[cell].push_back(obj); } uint32_t CollisionGroupRegistry::GetGroupBit(const std::string& tag) { auto it = tagToBit.find(tag); if (it != tagToBit.end()) return it->second; if (currentBit >= 32) { SNAKE_ERR("Exceeded maximum number of collision groups"); return UINT32_MAX; } uint32_t bit = (1 << currentBit); tagToBit[tag] = bit; bitToTag[bit] = tag; ++currentBit; return bit; } std::string CollisionGroupRegistry::GetGroupTag(uint32_t bit) const { auto it = bitToTag.find(bit); if (it != bitToTag.end()) return it->second; return "unknown"; }
0
0.881594
1
0.881594
game-dev
MEDIA
0.542756
game-dev,graphics-rendering
0.939321
1
0.939321
spartanoah/acrimony-client
18,496
net/minecraft/client/multiplayer/PlayerControllerMP.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package net.minecraft.client.multiplayer; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.entity.Entity; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.network.play.client.C02PacketUseEntity; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.network.play.client.C09PacketHeldItemChange; import net.minecraft.network.play.client.C0EPacketClickWindow; import net.minecraft.network.play.client.C10PacketCreativeInventoryAction; import net.minecraft.network.play.client.C11PacketEnchantItem; import net.minecraft.stats.StatFileWriter; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldSettings; public class PlayerControllerMP { private final Minecraft mc; private final NetHandlerPlayClient netClientHandler; private BlockPos currentBlock = new BlockPos(-1, -1, -1); private ItemStack currentItemHittingBlock; private float curBlockDamageMP; private float stepSoundTickCounter; public int blockHitDelay; private boolean isHittingBlock; private WorldSettings.GameType currentGameType = WorldSettings.GameType.SURVIVAL; public int currentPlayerItem; public PlayerControllerMP(Minecraft mcIn, NetHandlerPlayClient p_i45062_2_) { this.mc = mcIn; this.netClientHandler = p_i45062_2_; } public static void clickBlockCreative(Minecraft mcIn, PlayerControllerMP p_178891_1_, BlockPos p_178891_2_, EnumFacing p_178891_3_) { if (!mcIn.theWorld.extinguishFire(mcIn.thePlayer, p_178891_2_, p_178891_3_)) { p_178891_1_.onPlayerDestroyBlock(p_178891_2_, p_178891_3_); } } public void setPlayerCapabilities(EntityPlayer p_78748_1_) { this.currentGameType.configurePlayerCapabilities(p_78748_1_.capabilities); } public boolean isSpectator() { return this.currentGameType == WorldSettings.GameType.SPECTATOR; } public void setGameType(WorldSettings.GameType p_78746_1_) { this.currentGameType = p_78746_1_; this.currentGameType.configurePlayerCapabilities(this.mc.thePlayer.capabilities); } public void flipPlayer(EntityPlayer playerIn) { playerIn.rotationYaw = -180.0f; } public boolean shouldDrawHUD() { return this.currentGameType.isSurvivalOrAdventure(); } public boolean onPlayerDestroyBlock(BlockPos pos, EnumFacing side) { ItemStack itemstack1; if (this.currentGameType.isAdventure()) { if (this.currentGameType == WorldSettings.GameType.SPECTATOR) { return false; } if (!this.mc.thePlayer.isAllowEdit()) { Block block = this.mc.theWorld.getBlockState(pos).getBlock(); ItemStack itemstack = this.mc.thePlayer.getCurrentEquippedItem(); if (itemstack == null) { return false; } if (!itemstack.canDestroy(block)) { return false; } } } if (this.currentGameType.isCreative() && this.mc.thePlayer.getHeldItem() != null && this.mc.thePlayer.getHeldItem().getItem() instanceof ItemSword) { return false; } WorldClient world = this.mc.theWorld; IBlockState iblockstate = world.getBlockState(pos); Block block1 = iblockstate.getBlock(); if (block1.getMaterial() == Material.air) { return false; } world.playAuxSFX(2001, pos, Block.getStateId(iblockstate)); boolean flag = world.setBlockToAir(pos); if (flag) { block1.onBlockDestroyedByPlayer(world, pos, iblockstate); } this.currentBlock = new BlockPos(this.currentBlock.getX(), -1, this.currentBlock.getZ()); if (!this.currentGameType.isCreative() && (itemstack1 = this.mc.thePlayer.getCurrentEquippedItem()) != null) { itemstack1.onBlockDestroyed(world, block1, pos, this.mc.thePlayer); if (itemstack1.stackSize == 0) { this.mc.thePlayer.destroyCurrentEquippedItem(); } } return flag; } public boolean clickBlock(BlockPos loc, EnumFacing face) { if (this.currentGameType.isAdventure()) { if (this.currentGameType == WorldSettings.GameType.SPECTATOR) { return false; } if (!this.mc.thePlayer.isAllowEdit()) { Block block = this.mc.theWorld.getBlockState(loc).getBlock(); ItemStack itemstack = this.mc.thePlayer.getCurrentEquippedItem(); if (itemstack == null) { return false; } if (!itemstack.canDestroy(block)) { return false; } } } if (!this.mc.theWorld.getWorldBorder().contains(loc)) { return false; } if (this.currentGameType.isCreative()) { this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, loc, face)); PlayerControllerMP.clickBlockCreative(this.mc, this, loc, face); this.blockHitDelay = 5; } else if (!this.isHittingBlock || !this.isHittingPosition(loc)) { boolean flag; if (this.isHittingBlock) { this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, face)); } this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, loc, face)); Block block1 = this.mc.theWorld.getBlockState(loc).getBlock(); boolean bl = flag = block1.getMaterial() != Material.air; if (flag && this.curBlockDamageMP == 0.0f) { block1.onBlockClicked(this.mc.theWorld, loc, this.mc.thePlayer); } if (flag && block1.getPlayerRelativeBlockHardness(this.mc.thePlayer, this.mc.thePlayer.worldObj, loc) >= 1.0f) { this.onPlayerDestroyBlock(loc, face); } else { this.isHittingBlock = true; this.currentBlock = loc; this.currentItemHittingBlock = this.mc.thePlayer.getHeldItem(); this.curBlockDamageMP = 0.0f; this.stepSoundTickCounter = 0.0f; this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0f) - 1); } } return true; } public void resetBlockRemoving() { if (this.isHittingBlock) { this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, EnumFacing.DOWN)); this.isHittingBlock = false; this.curBlockDamageMP = 0.0f; this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, -1); } } public boolean onPlayerDamageBlock(BlockPos posBlock, EnumFacing directionFacing) { this.syncCurrentPlayItem(); if (this.blockHitDelay > 0) { --this.blockHitDelay; return true; } if (this.currentGameType.isCreative() && this.mc.theWorld.getWorldBorder().contains(posBlock)) { this.blockHitDelay = 5; this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, posBlock, directionFacing)); PlayerControllerMP.clickBlockCreative(this.mc, this, posBlock, directionFacing); return true; } if (this.isHittingPosition(posBlock)) { Block block = this.mc.theWorld.getBlockState(posBlock).getBlock(); if (block.getMaterial() == Material.air) { this.isHittingBlock = false; return false; } this.curBlockDamageMP += block.getPlayerRelativeBlockHardness(this.mc.thePlayer, this.mc.thePlayer.worldObj, posBlock); if (this.stepSoundTickCounter % 4.0f == 0.0f) { this.mc.getSoundHandler().playSound(new PositionedSoundRecord(new ResourceLocation(block.stepSound.getStepSound()), (block.stepSound.getVolume() + 1.0f) / 8.0f, block.stepSound.getFrequency() * 0.5f, (float)posBlock.getX() + 0.5f, (float)posBlock.getY() + 0.5f, (float)posBlock.getZ() + 0.5f)); } this.stepSoundTickCounter += 1.0f; if (this.curBlockDamageMP >= 1.0f) { this.isHittingBlock = false; this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.STOP_DESTROY_BLOCK, posBlock, directionFacing)); this.onPlayerDestroyBlock(posBlock, directionFacing); this.curBlockDamageMP = 0.0f; this.stepSoundTickCounter = 0.0f; this.blockHitDelay = 5; } this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0f) - 1); return true; } return this.clickBlock(posBlock, directionFacing); } public float getBlockReachDistance() { return this.currentGameType.isCreative() ? 5.0f : 4.5f; } public void updateController() { this.syncCurrentPlayItem(); if (this.netClientHandler.getNetworkManager().isChannelOpen()) { this.netClientHandler.getNetworkManager().processReceivedPackets(); } else { this.netClientHandler.getNetworkManager().checkDisconnected(); } } private boolean isHittingPosition(BlockPos pos) { boolean flag; ItemStack itemstack = this.mc.thePlayer.getHeldItem(); boolean bl = flag = this.currentItemHittingBlock == null && itemstack == null; if (this.currentItemHittingBlock != null && itemstack != null) { flag = itemstack.getItem() == this.currentItemHittingBlock.getItem() && ItemStack.areItemStackTagsEqual(itemstack, this.currentItemHittingBlock) && (itemstack.isItemStackDamageable() || itemstack.getMetadata() == this.currentItemHittingBlock.getMetadata()); } return pos.equals(this.currentBlock) && flag; } public void syncCurrentPlayItem() { int i = this.mc.thePlayer.inventory.currentItem; if (i != this.currentPlayerItem) { this.currentPlayerItem = i; this.netClientHandler.addToSendQueue(new C09PacketHeldItemChange(this.currentPlayerItem)); } } public boolean onPlayerRightClick(EntityPlayerSP player, WorldClient worldIn, ItemStack heldStack, BlockPos hitPos, EnumFacing side, Vec3 hitVec) { this.syncCurrentPlayItem(); float f = (float)(hitVec.xCoord - (double)hitPos.getX()); float f1 = (float)(hitVec.yCoord - (double)hitPos.getY()); float f2 = (float)(hitVec.zCoord - (double)hitPos.getZ()); boolean flag = false; if (!this.mc.theWorld.getWorldBorder().contains(hitPos)) { return false; } if (this.currentGameType != WorldSettings.GameType.SPECTATOR) { ItemBlock itemblock; IBlockState iblockstate = worldIn.getBlockState(hitPos); if ((!player.isSneaking() || player.getHeldItem() == null) && iblockstate.getBlock().onBlockActivated(worldIn, hitPos, iblockstate, player, side, f, f1, f2)) { flag = true; } if (!flag && heldStack != null && heldStack.getItem() instanceof ItemBlock && !(itemblock = (ItemBlock)heldStack.getItem()).canPlaceBlockOnSide(worldIn, hitPos, side, player, heldStack)) { return false; } } this.netClientHandler.addToSendQueue(new C08PacketPlayerBlockPlacement(hitPos, side.getIndex(), player.inventory.getCurrentItem(), f, f1, f2)); if (!flag && this.currentGameType != WorldSettings.GameType.SPECTATOR) { if (heldStack == null) { return false; } if (this.currentGameType.isCreative()) { int i = heldStack.getMetadata(); int j = heldStack.stackSize; boolean flag1 = heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2); heldStack.setItemDamage(i); heldStack.stackSize = j; return flag1; } return heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2); } return true; } public boolean sendUseItem(EntityPlayer playerIn, World worldIn, ItemStack itemStackIn) { if (this.currentGameType == WorldSettings.GameType.SPECTATOR) { return false; } this.syncCurrentPlayItem(); this.netClientHandler.addToSendQueue(new C08PacketPlayerBlockPlacement(playerIn.inventory.getCurrentItem())); int i = itemStackIn.stackSize; ItemStack itemstack = itemStackIn.useItemRightClick(worldIn, playerIn); if (itemstack != itemStackIn || itemstack != null && itemstack.stackSize != i) { playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = itemstack; if (itemstack.stackSize == 0) { playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = null; } return true; } return false; } public EntityPlayerSP func_178892_a(World worldIn, StatFileWriter p_178892_2_) { return new EntityPlayerSP(this.mc, worldIn, this.netClientHandler, p_178892_2_); } public void attackEntity(EntityPlayer playerIn, Entity targetEntity) { this.syncCurrentPlayItem(); this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.ATTACK)); if (this.currentGameType != WorldSettings.GameType.SPECTATOR) { playerIn.attackTargetEntityWithCurrentItem(targetEntity); } } public void attackEntityNoSlowdown(EntityPlayer playerIn, Entity targetEntity) { this.syncCurrentPlayItem(); this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.ATTACK)); if (this.currentGameType != WorldSettings.GameType.SPECTATOR) { playerIn.attackEntityNoSlowdown(targetEntity); } } public boolean interactWithEntitySendPacket(EntityPlayer playerIn, Entity targetEntity) { this.syncCurrentPlayItem(); this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.INTERACT)); return this.currentGameType != WorldSettings.GameType.SPECTATOR && playerIn.interactWith(targetEntity); } public boolean func_178894_a(EntityPlayer p_178894_1_, Entity p_178894_2_, MovingObjectPosition p_178894_3_) { this.syncCurrentPlayItem(); Vec3 vec3 = new Vec3(p_178894_3_.hitVec.xCoord - p_178894_2_.posX, p_178894_3_.hitVec.yCoord - p_178894_2_.posY, p_178894_3_.hitVec.zCoord - p_178894_2_.posZ); this.netClientHandler.addToSendQueue(new C02PacketUseEntity(p_178894_2_, vec3)); return this.currentGameType != WorldSettings.GameType.SPECTATOR && p_178894_2_.interactAt(p_178894_1_, vec3); } public ItemStack windowClick(int windowId, int slotId, int mouseButtonClicked, int mode, EntityPlayer playerIn) { short short1 = playerIn.openContainer.getNextTransactionID(playerIn.inventory); ItemStack itemstack = playerIn.openContainer.slotClick(slotId, mouseButtonClicked, mode, playerIn); this.netClientHandler.addToSendQueue(new C0EPacketClickWindow(windowId, slotId, mouseButtonClicked, mode, itemstack, short1)); return itemstack; } public void sendEnchantPacket(int p_78756_1_, int p_78756_2_) { this.netClientHandler.addToSendQueue(new C11PacketEnchantItem(p_78756_1_, p_78756_2_)); } public void sendSlotPacket(ItemStack itemStackIn, int slotId) { if (this.currentGameType.isCreative()) { this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(slotId, itemStackIn)); } } public void sendPacketDropItem(ItemStack itemStackIn) { if (this.currentGameType.isCreative() && itemStackIn != null) { this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(-1, itemStackIn)); } } public void onStoppedUsingItem(EntityPlayer playerIn) { this.syncCurrentPlayItem(); this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN)); playerIn.stopUsingItem(); } public boolean gameIsSurvivalOrAdventure() { return this.currentGameType.isSurvivalOrAdventure(); } public boolean isNotCreative() { return !this.currentGameType.isCreative(); } public boolean isInCreativeMode() { return this.currentGameType.isCreative(); } public boolean extendedReach() { return this.currentGameType.isCreative(); } public boolean isRidingHorse() { return this.mc.thePlayer.isRiding() && this.mc.thePlayer.ridingEntity instanceof EntityHorse; } public boolean isSpectatorMode() { return this.currentGameType == WorldSettings.GameType.SPECTATOR; } public WorldSettings.GameType getCurrentGameType() { return this.currentGameType; } public boolean func_181040_m() { return this.isHittingBlock; } }
0
0.948883
1
0.948883
game-dev
MEDIA
0.985118
game-dev
0.94107
1
0.94107
rockbite/talos
3,592
editor/src/com/talosvfx/talos/editor/widgets/ui/timeline/TimelineListener.java
package com.talosvfx.talos.editor.widgets.ui.timeline; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.scenes.scene2d.EventListener; /** Listener for {@link TimelineEvent}. * @author Avetis Zakharyan */ public class TimelineListener implements EventListener { public boolean handle (Event event) { if (event instanceof TimelineEvent) { TimelineEvent timelineEvent = (TimelineEvent) event; switch (timelineEvent.getType()) { case itemSelected: onItemSelect(timelineEvent.getTargetIdentifier()); break; case visibilityChanged: onItemVisibilityChange(timelineEvent.getTargetIdentifier(), (Boolean) timelineEvent.payload); break; case selectorUpdated: onSelectorUpdate(); break; case play: onPlayClicked(); break; case rewind: onRewindClicked(); break; case skipToStart: onSkipToStartClicked(); break; case skipToEnd: onSkipToEndClicked(); break; case newItem: onNewClicked(); break; case deleteSelection: onDeleteClicked(); break; case toggleLoop: onToggleLoop((Boolean) timelineEvent.payload); break; case rename: onItemRename(timelineEvent.getTargetIdentifier(), (String) timelineEvent.payload); break; case up: onUp(); break; case down: onDown(); break; } } return false; } static public class TimelineEvent extends Event { private Type type; private Object target; private Object payload; public Type getType() { return type; } public TimelineEvent as(Type type) { this.type = type; return this; } public TimelineEvent payload(Object payload) { this.payload = payload; return this; } public TimelineEvent target(ListItem target) { this.target = target.getIdentifier(); return this; } public Object getTargetIdentifier () { return target; } } protected void onItemSelect(Object identifier) { } protected void onItemVisibilityChange(Object identifier, boolean isVisible) {} protected void onSelectorUpdate() {} protected void onPlayClicked() {} protected void onRewindClicked() {} protected void onSkipToStartClicked() {} protected void onSkipToEndClicked() {} protected void onNewClicked() {} protected void onDeleteClicked() {} protected void onToggleLoop(boolean loopEnabled) {} protected void onDown () {} protected void onUp () {} protected void onItemRename(Object identifier, String newName) {} static public enum Type { itemSelected, visibilityChanged, selectorUpdated, skipToStart, skipToEnd, play, rewind, newItem, deleteSelection, toggleLoop, rename, up, down } }
0
0.907002
1
0.907002
game-dev
MEDIA
0.78145
game-dev
0.976688
1
0.976688
games50/pong
3,066
pong-10/class.lua
--[[ Copyright (c) 2010-2013 Matthias Richter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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. ]]-- local function include_helper(to, from, seen) if from == nil then return to elseif type(from) ~= 'table' then return from elseif seen[from] then return seen[from] end seen[from] = to for k,v in pairs(from) do k = include_helper({}, k, seen) -- keys might also be tables if to[k] == nil then to[k] = include_helper({}, v, seen) end end return to end -- deeply copies `other' into `class'. keys in `other' that are already -- defined in `class' are omitted local function include(class, other) return include_helper(class, other, {}) end -- returns a deep copy of `other' local function clone(other) return setmetatable(include({}, other), getmetatable(other)) end local function new(class) -- mixins class = class or {} -- class can be nil local inc = class.__includes or {} if getmetatable(inc) then inc = {inc} end for _, other in ipairs(inc) do if type(other) == "string" then other = _G[other] end include(class, other) end -- class implementation class.__index = class class.init = class.init or class[1] or function() end class.include = class.include or include class.clone = class.clone or clone -- constructor call return setmetatable(class, {__call = function(c, ...) local o = setmetatable({}, c) o:init(...) return o end}) end -- interface for cross class-system compatibility (see https://github.com/bartbes/Class-Commons). if class_commons ~= false and not common then common = {} function common.class(name, prototype, parent) return new{__includes = {prototype, parent}} end function common.instance(class, ...) return class(...) end end -- the module return setmetatable({new = new, include = include, clone = clone}, {__call = function(_,...) return new(...) end})
0
0.840598
1
0.840598
game-dev
MEDIA
0.210187
game-dev
0.778516
1
0.778516
gokhanmoral/siyahkernel3
19,700
drivers/video/samsung/mdnie_table_gc1.h
#ifndef __MDNIE_TABLE_H__ #define __MDNIE_TABLE_H__ #include "mdnie.h" static const unsigned short tune_dynamic_gallery[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00ac, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0090, 0x0080, /*DE egth*/ 0x0092, 0x0030, /*DE pe*/ 0x0093, 0x0080, /*DE pf*/ 0x0094, 0x0080, /*DE pb*/ 0x0095, 0x0080, /*DE ne*/ 0x0096, 0x0080, /*DE nf*/ 0x0097, 0x0080, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0100, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1a04, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0080, /*CC chsel strength*/ 0x0020, 0x0000, /*CC lut r 0*/ 0x0021, 0x0a94, /*CC lut r 16 144*/ 0x0022, 0x18a6, /*CC lut r 32 160*/ 0x0023, 0x28b8, /*CC lut r 48 176*/ 0x0024, 0x3ac9, /*CC lut r 64 192*/ 0x0025, 0x4cd9, /*CC lut r 80 208*/ 0x0026, 0x5ee7, /*CC lut r 96 224*/ 0x0027, 0x70f4, /*CC lut r 112 240*/ 0x0028, 0x82ff, /*CC lut r 128 255*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_dynamic_ui[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00ac, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0092, 0x0020, /*DE pe*/ 0x0093, 0x0020, /*DE pf*/ 0x0094, 0x0020, /*DE pb*/ 0x0095, 0x0020, /*DE ne*/ 0x0096, 0x0020, /*DE nf*/ 0x0097, 0x0020, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0100, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1a04, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0080, /*CC chsel strength*/ 0x0020, 0x0000, /*CC lut r 0*/ 0x0021, 0x0a94, /*CC lut r 16 144*/ 0x0022, 0x18a6, /*CC lut r 32 160*/ 0x0023, 0x28b8, /*CC lut r 48 176*/ 0x0024, 0x3ac9, /*CC lut r 64 192*/ 0x0025, 0x4cd9, /*CC lut r 80 208*/ 0x0026, 0x5ee7, /*CC lut r 96 224*/ 0x0027, 0x70f4, /*CC lut r 112 240*/ 0x0028, 0x82ff, /*CC lut r 128 255*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_dynamic_video[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00ac, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0092, 0x0080, /*DE pe*/ 0x0093, 0x0080, /*DE pf*/ 0x0094, 0x0080, /*DE pb*/ 0x0095, 0x0080, /*DE ne*/ 0x0096, 0x0080, /*DE nf*/ 0x0097, 0x0080, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0100, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1a04, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0080, /*CC chsel strength*/ 0x0020, 0x0000, /*CC lut r 0*/ 0x0021, 0x0a94, /*CC lut r 16 144*/ 0x0022, 0x18a6, /*CC lut r 32 160*/ 0x0023, 0x28b8, /*CC lut r 48 176*/ 0x0024, 0x3ac9, /*CC lut r 64 192*/ 0x0025, 0x4cd9, /*CC lut r 80 208*/ 0x0026, 0x5ee7, /*CC lut r 96 224*/ 0x0027, 0x70f4, /*CC lut r 112 240*/ 0x0028, 0x82ff, /*CC lut r 128 255*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_dynamic_vt[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00ae, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0005, /*FA cs1 | de8 dnr4 hdr2 fa1*/ 0x0039, 0x0080, /*FA dnrWeight*/ 0x0080, 0x0fff, /*DNR dirTh*/ 0x0081, 0x19ff, /*DNR dirnumTh decon7Th*/ 0x0082, 0xff16, /*DNR decon5Th maskTh*/ 0x0083, 0x0000, /*DNR blTh*/ 0x0092, 0x00e0, /*DE pe*/ 0x0093, 0x00e0, /*DE pf*/ 0x0094, 0x00e0, /*DE pb*/ 0x0095, 0x00e0, /*DE ne*/ 0x0096, 0x00e0, /*DE nf*/ 0x0097, 0x00e0, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0010, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1a04, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0080, /*CC chsel strength*/ 0x0020, 0x0000, /*CC lut r 0*/ 0x0021, 0x0a94, /*CC lut r 16 144*/ 0x0022, 0x18a6, /*CC lut r 32 160*/ 0x0023, 0x28b8, /*CC lut r 48 176*/ 0x0024, 0x3ac9, /*CC lut r 64 192*/ 0x0025, 0x4cd9, /*CC lut r 80 208*/ 0x0026, 0x5ee7, /*CC lut r 96 224*/ 0x0027, 0x70f4, /*CC lut r 112 240*/ 0x0028, 0x82ff, /*CC lut r 128 255*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_movie_gallery[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x0020, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00f0, /*SCR KgWg*/ 0x00ec, 0x00e6, /*SCR KbWb*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_movie_ui[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x0020, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00f0, /*SCR KgWg*/ 0x00ec, 0x00e6, /*SCR KbWb*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_movie_video[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x0020, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0092, 0x0000, /*DE pe*/ 0x0093, 0x0000, /*DE pf*/ 0x0094, 0x0000, /*DE pb*/ 0x0095, 0x0000, /*DE ne*/ 0x0096, 0x0000, /*DE nf*/ 0x0097, 0x0000, /*DE nb*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1004, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00f0, /*SCR KgWg*/ 0x00ec, 0x00e6, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0000, /*CC chsel strength*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_movie_vt[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x002e, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0005, /*FA cs1 | de8 dnr4 hdr2 fa1*/ 0x0039, 0x0080, /*FA dnrWeight*/ 0x0080, 0x0fff, /*DNR dirTh*/ 0x0081, 0x19ff, /*DNR dirnumTh decon7Th*/ 0x0082, 0xff16, /*DNR decon5Th maskTh*/ 0x0083, 0x0000, /*DNR blTh*/ 0x0092, 0x0040, /*DE pe*/ 0x0093, 0x0040, /*DE pf*/ 0x0094, 0x0040, /*DE pb*/ 0x0095, 0x0040, /*DE ne*/ 0x0096, 0x0040, /*DE nf*/ 0x0097, 0x0040, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0010, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1204, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00f0, /*SCR KgWg*/ 0x00ec, 0x00e6, /*SCR KbWb*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_standard_gallery[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00ac, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0090, 0x0080, /*DE egth*/ 0x0092, 0x0000, /*DE pe*/ 0x0093, 0x0080, /*DE pf*/ 0x0094, 0x0080, /*DE pb*/ 0x0095, 0x0080, /*DE ne*/ 0x0096, 0x0080, /*DE nf*/ 0x0097, 0x0080, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0100, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1404, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0080, /*CC chsel strength*/ 0x0020, 0x0000, /*CC lut r 0*/ 0x0021, 0x179b, /*CC lut r 16 144*/ 0x0022, 0x29aa, /*CC lut r 32 160*/ 0x0023, 0x3bb9, /*CC lut r 48 176*/ 0x0024, 0x4cc8, /*CC lut r 64 192*/ 0x0025, 0x5cd6, /*CC lut r 80 208*/ 0x0026, 0x6ce4, /*CC lut r 96 224*/ 0x0027, 0x7cf2, /*CC lut r 112 240*/ 0x0028, 0x8cff, /*CC lut r 128 255*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_standard_ui[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x0028, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1804, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_standard_video[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x002c, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0092, 0x0060, /*DE pe*/ 0x0093, 0x0060, /*DE pf*/ 0x0094, 0x0060, /*DE pb*/ 0x0095, 0x0060, /*DE ne*/ 0x0096, 0x0060, /*DE nf*/ 0x0097, 0x0060, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0100, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1804, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0000, /*CC chsel strength*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_standard_vt[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x002e, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0005, /*FA cs1 | de8 dnr4 hdr2 fa1*/ 0x0039, 0x0080, /*FA dnrWeight*/ 0x0080, 0x0fff, /*DNR dirTh*/ 0x0081, 0x19ff, /*DNR dirnumTh decon7Th*/ 0x0082, 0xff16, /*DNR decon5Th maskTh*/ 0x0083, 0x0000, /*DNR blTh*/ 0x0092, 0x00c0, /*DE pe*/ 0x0093, 0x00c0, /*DE pf*/ 0x0094, 0x00c0, /*DE pb*/ 0x0095, 0x00c0, /*DE ne*/ 0x0096, 0x00c0, /*DE nf*/ 0x0097, 0x00c0, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0010, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1804, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_camera[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00a8, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0090, 0x0080, /*DE egth*/ 0x0092, 0x0000, /*DE pe*/ 0x0093, 0x0080, /*DE pf*/ 0x0094, 0x0080, /*DE pb*/ 0x0095, 0x0080, /*DE ne*/ 0x0096, 0x0080, /*DE nf*/ 0x0097, 0x0080, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0100, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg ry*/ 0x00b1, 0x1010, /*CS hg gc*/ 0x00b2, 0x1010, /*CS hg bm*/ 0x00b3, 0x1404, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0080, /*CC chsel strength*/ 0x0020, 0x0000, /*CC lut r 0*/ 0x0021, 0x179b, /*CC lut r 16 144*/ 0x0022, 0x29aa, /*CC lut r 32 160*/ 0x0023, 0x3bb9, /*CC lut r 48 176*/ 0x0024, 0x4cc8, /*CC lut r 64 192*/ 0x0025, 0x5cd6, /*CC lut r 80 208*/ 0x0026, 0x6ce4, /*CC lut r 96 224*/ 0x0027, 0x7cf2, /*CC lut r 112 240*/ 0x0028, 0x8cff, /*CC lut r 128 255*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_camera_outdoor[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x04a8, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0030, 0x0000, /*FA cs1 de8 hdr2 fa1*/ 0x0090, 0x0080, /*DE egth*/ 0x0092, 0x0000, /*DE pe*/ 0x0093, 0x0060, /*DE pf*/ 0x0094, 0x0060, /*DE pb*/ 0x0095, 0x0060, /*DE ne*/ 0x0096, 0x0060, /*DE nf*/ 0x0097, 0x0060, /*DE nb*/ 0x0098, 0x1000, /*DE max ratio*/ 0x0099, 0x0100, /*DE min ratio*/ 0x00b0, 0x1010, /*CS hg RY*/ 0x00b1, 0x1010, /*CS hg GC*/ 0x00b2, 0x1010, /*CS hg BM*/ 0x00b3, 0x1404, /*CS weight grayTH*/ 0x00e1, 0xff00, /*SCR RrCr*/ 0x00e2, 0x00ff, /*SCR RgCg*/ 0x00e3, 0x00ff, /*SCR RbCb*/ 0x00e4, 0x00ff, /*SCR GrMr*/ 0x00e5, 0xff00, /*SCR GgMg*/ 0x00e6, 0x00ff, /*SCR GbMb*/ 0x00e7, 0x00ff, /*SCR BrYr*/ 0x00e8, 0x00e4, /*SCR BgYg*/ 0x00e9, 0xff00, /*SCR BbYb*/ 0x00ea, 0x00ff, /*SCR KrWr*/ 0x00eb, 0x00ff, /*SCR KgWg*/ 0x00ec, 0x00ff, /*SCR KbWb*/ 0x0000, 0x0001, /*BANK 1*/ 0x001f, 0x0080, /*CC chsel strength*/ 0x0020, 0x0000, /*CC lut r 0*/ 0x0021, 0x169a, /*CC lut r 16 144*/ 0x0022, 0x29a9, /*CC lut r 32 160*/ 0x0023, 0x3ab8, /*CC lut r 48 176*/ 0x0024, 0x4bc7, /*CC lut r 64 192*/ 0x0025, 0x5bd5, /*CC lut r 80 208*/ 0x0026, 0x6be3, /*CC lut r 96 224*/ 0x0027, 0x7bf2, /*CC lut r 112 240*/ 0x0028, 0x8bff, /*CC lut r 128 255*/ 0x00d0, 0x01c0, /*UC y*/ 0x00d1, 0x01ff, /*UC cs*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_cold[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00ec, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0000, 0x0001, /*BANK 1*/ 0x0001, 0x0064, /*MCM 10000K*/ 0x0009, 0xa08e, /*MCM 5cb 1cr W*/ 0x000b, 0x7979, /*MCM 4cr 5cr W*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_cold_outdoor[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x04ec, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0000, 0x0001, /*BANK 1*/ 0x0001, 0x0064, /*MCM 10000K*/ 0x0009, 0xa08e, /*MCM 5cb 1cr W*/ 0x000b, 0x7979, /*MCM 4cr 5cr W*/ 0x00d0, 0x01c0, /*UC y*/ 0x00d1, 0x01ff, /*UC cs*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_normal_outdoor[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x04ac, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0000, 0x0001, /*BANK 1*/ 0x00d0, 0x01c0, /*UC y*/ 0x00d1, 0x01ff, /*UC cs*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_warm[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x00ec, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0000, 0x0001, /*BANK 1*/ 0x0001, 0x0028, /*MCM 4000K*/ 0x0007, 0x7575, /*MCM 1cb 2cb W*/ 0x0009, 0xa08e, /*MCM 5cb 1cr W*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; static const unsigned short tune_warm_outdoor[] = { 0x0000, 0x0000, /*BANK 0*/ 0x0008, 0x04ec, /*Dither8 UC4 ABC2 CP1 | CC8 MCM4 SCR2 SCC1 | CS8 DE4 DNR2 HDR1*/ 0x0000, 0x0001, /*BANK 1*/ 0x0001, 0x0028, /*MCM 4000K*/ 0x0007, 0x7575, /*MCM 1cb 2cb W*/ 0x0009, 0xa08e, /*MCM 5cb 1cr W*/ 0x00d0, 0x01c0, /*UC y*/ 0x00d1, 0x01ff, /*UC cs*/ 0x00ff, 0x0000, /*Mask Release*/ END_SEQ, 0x0000, }; struct mdnie_tunning_info etc_table[CABC_MAX][OUTDOOR_MAX][TONE_MAX] = { { { {"NORMAL", NULL}, {"WARM", tune_warm}, {"COLD", tune_cold}, }, { {"NORMAL_OUTDOOR", tune_normal_outdoor}, {"WARM_OUTDOOR", tune_warm_outdoor}, {"COLD_OUTDOOR", tune_cold_outdoor}, }, } }; struct mdnie_tunning_info tunning_table[CABC_MAX][MODE_MAX][SCENARIO_MAX] = { { { {"DYNAMIC_UI", tune_dynamic_ui}, {"DYNAMIC_VIDEO", tune_dynamic_video}, {"DYNAMIC_VIDEO", tune_dynamic_video}, {"DYNAMIC_VIDEO", tune_dynamic_video}, {"CAMERA", NULL}, {"DYNAMIC_UI", tune_dynamic_ui}, {"DYNAMIC_GALLERY", tune_dynamic_gallery}, {"DYNAMIC_VT", tune_dynamic_vt}, }, { {"STANDARD_UI", tune_standard_ui}, {"STANDARD_VIDEO", tune_standard_video}, {"STANDARD_VIDEO", tune_standard_video}, {"STANDARD_VIDEO", tune_standard_video}, {"CAMERA", NULL}, {"STANDARD_UI", tune_standard_ui}, {"STANDARD_GALLERY", tune_standard_gallery}, {"STANDARD_VT", tune_standard_vt}, }, { {"MOVIE_UI", tune_movie_ui}, {"MOVIE_VIDEO", tune_movie_video}, {"MOVIE_VIDEO", tune_movie_video}, {"MOVIE_VIDEO", tune_movie_video}, {"CAMERA", NULL}, {"MOVIE_UI", tune_movie_ui}, {"MOVIE_GALLERY", tune_movie_gallery}, {"MOVIE_VT", tune_movie_vt}, }, } }; struct mdnie_tunning_info camera_table[OUTDOOR_MAX] = { {"CAMERA", tune_camera}, {"CAMERA_OUTDOOR", tune_camera_outdoor}, }; #endif /* __MDNIE_TABLE_H__ */
0
0.733828
1
0.733828
game-dev
MEDIA
0.199598
game-dev
0.684269
1
0.684269
Interactml/iml-unity
2,317
Assets/InteractML/Scripts/IML Nodes/Movement Features Nodes/Editor/RotationQuaternionNodeEditor.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; using XNodeEditor; #endif namespace InteractML.GameObjectMovementFeatures { [CustomNodeEditor(typeof(RotationQuaternionNode))] public class ExtractRotationQuaternionNodeEditor : IMLNodeEditor { /// <summary> /// Reference to the node itself /// </summary> private RotationQuaternionNode m_ExtractRotationQuaternion; /// <summary> /// Initialise node specific interface labels and parameters /// </summary> public override void OnCreate() { // Get reference to the current node m_ExtractRotationQuaternion = (target as RotationQuaternionNode); // Initialise node name NodeName = "ROTATION"; NodeSubtitle = "Quaternion"; // Initialise node height m_BodyRect.height = 180; nodeSpace = 180; // Initialise input port labels InputPortsNamesOverride = new Dictionary<string, string>(); base.InputPortsNamesOverride.Add("GameObjectDataIn", "Game Object\nData In"); // Initialise output port labels OutputPortsNamesOverride = new Dictionary<string, string>(); base.OutputPortsNamesOverride.Add("LiveDataOut", "Rotation\nData Out"); // Initialise node tooltips base.nodeTips = m_ExtractRotationQuaternion.tooltips; // Initialise axis labels feature_labels = new string[4] { "x: ", "y: ", "z: ", "w: " }; } protected override void ShowBodyFields() { GUILayout.Space(60); // set body space based on node editors rects GUILayout.BeginArea(m_BodyRect); GUILayout.Space(20); //draws node data fields MovementFeatureEditorMethods.DrawFeatureValueToggleAndLabel(this, m_ExtractRotationQuaternion); GUILayout.Space(10); //draw toggle to select whether to use localspace m_ExtractRotationQuaternion.LocalSpace = MovementFeatureEditorMethods.DrawLocalSpaceToggle(this, m_ExtractRotationQuaternion.LocalSpace); GUILayout.EndArea(); } } }
0
0.908939
1
0.908939
game-dev
MEDIA
0.784826
game-dev
0.787736
1
0.787736
osgcc/ryzom
5,247
ryzom/client/src/interfaces_manager/progress_bar.cpp
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "stdpch.h" ////////////// // Includes // ////////////// // Misc. #include "nel/misc/time_nl.h" // 3D Interface. #include "nel/3d/u_driver.h" #include "nel/3d/u_text_context.h" // Client #include "progress_bar.h" #include "interfaces_manager.h" /////////// // Using // /////////// using namespace std; using namespace NL3D; using namespace NLMISC; ///////////// // Externs // ///////////// extern UDriver *Driver; extern UTextContext *TextContext; //----------------------------------------------- // CProgressBar : // Constructor. //----------------------------------------------- CProgressBar::CProgressBar(uint id, float x, float y, float x_pixel, float y_pixel, float w, float h, float w_pixel, float h_pixel, uint range) :CControl(id, x, y, x_pixel, y_pixel, w, h, w_pixel, h_pixel) { init(range); }// CControl // //----------------------------------------------- // init : //----------------------------------------------- void CProgressBar::init( uint32 range) { _Range = range; _CurrentPos = 0 ; _TempPos = 0 ; _StepInc = 1; _Smooth = false; _SmoothFillRate = 50; // 1 unit / 50ms _LastUpdateSmooth = ryzomGetLocalTime (); } // init // //----------------------------------------------- // setRange : //----------------------------------------------- uint32 CProgressBar::setRange( uint32 range) { uint32 old = _Range; _Range = range; if (_CurrentPos > _Range) { _CurrentPos = _Range; _TempPos = _Range; } return old; } // setRange // //----------------------------------------------- // setStep : //----------------------------------------------- uint32 CProgressBar::setStep( uint32 step) { uint32 old = _StepInc; _StepInc = step; return old; }// setStep // //----------------------------------------------- // setPos : //----------------------------------------------- uint32 CProgressBar::setPos( uint32 pos) { uint32 old = _CurrentPos; _CurrentPos = pos; if (_CurrentPos > _Range) { _CurrentPos = _Range; } if (!_Smooth) { _TempPos = _CurrentPos; } return old; }// setPos // //----------------------------------------------- // display : //----------------------------------------------- void CProgressBar::display() { // compute the temp pos if in smooth mode if (_Smooth) { uint32 nbUnit = (uint32)(ryzomGetLocalTime () - _LastUpdateSmooth) / _SmoothFillRate; if (nbUnit > 0) { _LastUpdateSmooth = ryzomGetLocalTime (); uint32 diff = abs( _TempPos - _CurrentPos ); if (diff < nbUnit) nbUnit = diff; if ( _TempPos < _CurrentPos ) _TempPos += nbUnit; else _TempPos -= nbUnit; } } else { nlassert( _TempPos == _CurrentPos ); } // If the control is hide -> return if(!_Show) return; // draw background UTextureFile *utexture = CInterfMngr::getTexture( _BackgroundTexture ); if(utexture) { Driver->drawBitmap(_X_Display, _Y_Display, _W_Display, _H_Display, *utexture, true, _BackgroundColor); } // calculate _W_Display of the progress bar const float wBar = _W_Display * ( static_cast<float>(_TempPos) / static_cast<float>(_Range) ); // Backup scissor and create the new scissor to clip the bar correctly. CScissor oldScissor = Driver->getScissor(); CScissor scissor; float scisX, scisY, scisWidth, scisHeight; scisX = oldScissor.X; scisY = oldScissor.Y; scisWidth = oldScissor.Width; scisHeight = oldScissor.Height; float xtmp = _X_Display + wBar; float ytmp = _Y_Display + _H_Display; float xscistmp = scisX + scisWidth; float yscistmp = scisY + scisHeight; if( _X_Display > scisX ) scisX = _X_Display; if( _Y_Display > scisY ) scisY = _Y_Display; if( xtmp < xscistmp ) scisWidth = xtmp - scisX; else scisWidth = xscistmp - scisX; if( ytmp < yscistmp ) scisHeight = ytmp - scisY; else scisHeight = yscistmp - scisY; scissor.init(scisX, scisY, scisWidth, scisHeight); Driver->setScissor(scissor); // display progress bar utexture = CInterfMngr::getTexture( _ProgressBarTexture ); Driver->drawBitmap(_X_Display, _Y_Display, _W_Display, _H_Display, *utexture, true, _ProgressBarColor); // restore old scissor Driver->setScissor(oldScissor); // display text if ( ! _Text.empty() ) { TextContext->setShaded(_Shadow); TextContext->setHotSpot(NL3D::UTextContext::THotSpot::MiddleMiddle); TextContext->setColor(_Color); TextContext->setFontSize(_FontSize); TextContext->printAt(_X_Display + _W_Display/2, _Y_Display + _H_Display/2, _Text); } // }// display //
0
0.892331
1
0.892331
game-dev
MEDIA
0.622137
game-dev,graphics-rendering
0.869439
1
0.869439
Official3DRealms/wrath-darkplaces
84,939
cl_main.c
/* Copyright (C) 1996-1997 Id Software, Inc. 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // cl_main.c -- client main loop #include "quakedef.h" #include "cl_collision.h" #include "cl_video.h" #include "image.h" #include "csprogs.h" #include "r_shadow.h" #include "libcurl.h" #include "snd_main.h" #include "cl_steam.h" // we need to declare some mouse variables here, because the menu system // references them even when on a unix system. cvar_t csqc_progname = {0, "csqc_progname","csprogs.dat","name of csprogs.dat file to load"}; cvar_t csqc_progcrc = {CVAR_READONLY, "csqc_progcrc","-1","CRC of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"}; cvar_t csqc_progsize = {CVAR_READONLY, "csqc_progsize","-1","file size of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"}; cvar_t csqc_usedemoprogs = {0, "csqc_usedemoprogs","1","use csprogs stored in demos"}; cvar_t cl_shownet = {0, "cl_shownet","0","1 = print packet size, 2 = print packet message list"}; cvar_t cl_nolerp = {0, "cl_nolerp", "0","network update smoothing"}; cvar_t cl_lerpexcess = {0, "cl_lerpexcess", "0","maximum allowed lerp excess (hides, not fixes, some packet loss)"}; cvar_t cl_lerpanim_maxdelta_server = {0, "cl_lerpanim_maxdelta_server", "0.1","maximum frame delta for smoothing between server-controlled animation frames (when 0, one network frame)"}; cvar_t cl_lerpanim_maxdelta_framegroups = {0, "cl_lerpanim_maxdelta_framegroups", "0.1","maximum frame delta for smoothing between framegroups (when 0, one network frame)"}; cvar_t cl_itembobheight = {0, "cl_itembobheight", "0","how much items bob up and down (try 8)"}; cvar_t cl_itembobspeed = {0, "cl_itembobspeed", "0.5","how frequently items bob up and down"}; cvar_t lookspring = {CVAR_SAVE, "lookspring","0","returns pitch to level with the floor when no longer holding a pitch key"}; cvar_t lookstrafe = {CVAR_SAVE, "lookstrafe","0","move instead of turning"}; cvar_t sensitivity = {CVAR_SAVE, "sensitivity","3","mouse speed multiplier"}; cvar_t m_pitch = {CVAR_SAVE, "m_pitch","0.022","mouse pitch speed multiplier"}; cvar_t m_yaw = {CVAR_SAVE, "m_yaw","0.022","mouse yaw speed multiplier"}; cvar_t m_forward = {CVAR_SAVE, "m_forward","1","mouse forward speed multiplier"}; cvar_t m_side = {CVAR_SAVE, "m_side","0.8","mouse side speed multiplier"}; cvar_t freelook = {CVAR_SAVE, "freelook", "1","mouse controls pitch instead of forward/back"}; cvar_t cl_autodemo = {CVAR_SAVE, "cl_autodemo", "0", "records every game played, using the date/time and map name to name the demo file" }; cvar_t cl_autodemo_nameformat = {CVAR_SAVE, "cl_autodemo_nameformat", "autodemos/%Y-%m-%d_%H-%M", "The format of the cl_autodemo filename, followed by the map name (the date is encoded using strftime escapes)" }; cvar_t cl_autodemo_delete = {0, "cl_autodemo_delete", "0", "Delete demos after recording. This is a bitmask, bit 1 gives the default, bit 0 the value for the current demo. Thus, the values are: 0 = disabled; 1 = delete current demo only; 2 = delete all demos except the current demo; 3 = delete all demos from now on" }; cvar_t r_draweffects = {0, "r_draweffects", "1","renders temporary sprite effects"}; cvar_t cl_explosions_alpha_start = {CVAR_SAVE, "cl_explosions_alpha_start", "1.5","starting alpha of an explosion shell"}; cvar_t cl_explosions_alpha_end = {CVAR_SAVE, "cl_explosions_alpha_end", "0","end alpha of an explosion shell (just before it disappears)"}; cvar_t cl_explosions_size_start = {CVAR_SAVE, "cl_explosions_size_start", "16","starting size of an explosion shell"}; cvar_t cl_explosions_size_end = {CVAR_SAVE, "cl_explosions_size_end", "128","ending alpha of an explosion shell (just before it disappears)"}; cvar_t cl_explosions_lifetime = {CVAR_SAVE, "cl_explosions_lifetime", "0.5","how long an explosion shell lasts"}; cvar_t cl_stainmaps = {CVAR_SAVE, "cl_stainmaps", "0","stains lightmaps, much faster than decals but blurred"}; cvar_t cl_stainmaps_clearonload = {CVAR_SAVE, "cl_stainmaps_clearonload", "1","clear stainmaps on map restart"}; cvar_t cl_beams_polygons = {CVAR_SAVE, "cl_beams_polygons", "1","use beam polygons instead of models"}; cvar_t cl_beams_quakepositionhack = {CVAR_SAVE, "cl_beams_quakepositionhack", "1", "makes your lightning gun appear to fire from your waist (as in Quake and QuakeWorld)"}; cvar_t cl_beams_instantaimhack = {CVAR_SAVE, "cl_beams_instantaimhack", "0", "makes your lightning gun aiming update instantly"}; cvar_t cl_beams_lightatend = {CVAR_SAVE, "cl_beams_lightatend", "0", "make a light at the end of the beam"}; cvar_t cl_deathfade = {CVAR_SAVE, "cl_deathfade", "0", "fade screen to dark red when dead, value represents how fast the fade is (higher is faster)"}; cvar_t cl_noplayershadow = {CVAR_SAVE, "cl_noplayershadow", "0","hide player shadow"}; cvar_t cl_dlights_decayradius = {CVAR_SAVE, "cl_dlights_decayradius", "1", "reduces size of light flashes over time"}; cvar_t cl_dlights_decaybrightness = {CVAR_SAVE, "cl_dlights_decaybrightness", "1", "reduces brightness of light flashes over time"}; cvar_t qport = {0, "qport", "0", "identification key for playing on qw servers (allows you to maintain a connection to a quakeworld server even if your port changes)"}; cvar_t cl_prydoncursor = {0, "cl_prydoncursor", "0", "enables a mouse pointer which is able to click on entities in the world, useful for point and click mods, see PRYDON_CLIENTCURSOR extension in dpextensions.qc"}; cvar_t cl_prydoncursor_notrace = {0, "cl_prydoncursor_notrace", "0", "disables traceline used in prydon cursor reporting to the game, saving some cpu time"}; cvar_t cl_deathnoviewmodel = {0, "cl_deathnoviewmodel", "1", "hides gun model when dead"}; cvar_t cl_locs_enable = {CVAR_SAVE, "locs_enable", "1", "enables replacement of certain % codes in chat messages: %l (location), %d (last death location), %h (health), %a (armor), %x (rockets), %c (cells), %r (rocket launcher status), %p (powerup status), %w (weapon status), %t (current time in level)"}; cvar_t cl_locs_show = {0, "locs_show", "0", "shows defined locations for editing purposes"}; extern cvar_t r_equalize_entities_fullbright; client_static_t cls; client_state_t cl; /* ===================== CL_ClearState ===================== */ void CL_ClearState(void) { int i; entity_t *ent; CL_VM_ShutDown(); // wipe the entire cl structure Mem_EmptyPool(cls.levelmempool); memset (&cl, 0, sizeof(cl)); S_StopAllSounds(); // reset the view zoom interpolation cl.mviewzoom[0] = cl.mviewzoom[1] = 1; cl.sensitivityscale = 1.0f; // enable rendering of the world and such cl.csqc_vidvars.drawworld = r_drawworld.integer != 0; cl.csqc_vidvars.drawenginesbar = true; cl.csqc_vidvars.drawcrosshair = true; // set up the float version of the stats array for easier access to float stats cl.statsf = (float *)cl.stats; cl.num_entities = 0; cl.num_static_entities = 0; cl.num_brushmodel_entities = 0; // tweak these if the game runs out cl.max_csqcrenderentities = 0; cl.max_entities = MAX_ENITIES_INITIAL; cl.max_static_entities = MAX_STATICENTITIES; cl.max_effects = MAX_EFFECTS; cl.max_beams = MAX_BEAMS; cl.max_dlights = MAX_DLIGHTS; cl.max_lightstyle = MAX_LIGHTSTYLES; cl.max_brushmodel_entities = MAX_EDICTS; cl.max_particles = MAX_PARTICLES_INITIAL; // grows dynamically cl.max_decals = MAX_DECALS_INITIAL; // grows dynamically cl.max_showlmps = 0; cl.num_dlights = 0; cl.num_effects = 0; cl.num_beams = 0; cl.csqcrenderentities = NULL; cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t)); cl.entities_active = (unsigned char *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(unsigned char)); cl.static_entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_static_entities * sizeof(entity_t)); cl.effects = (cl_effect_t *)Mem_Alloc(cls.levelmempool, cl.max_effects * sizeof(cl_effect_t)); cl.beams = (beam_t *)Mem_Alloc(cls.levelmempool, cl.max_beams * sizeof(beam_t)); cl.dlights = (dlight_t *)Mem_Alloc(cls.levelmempool, cl.max_dlights * sizeof(dlight_t)); cl.lightstyle = (lightstyle_t *)Mem_Alloc(cls.levelmempool, cl.max_lightstyle * sizeof(lightstyle_t)); cl.brushmodel_entities = (int *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(int)); cl.particles = (particle_t *) Mem_Alloc(cls.levelmempool, cl.max_particles * sizeof(particle_t)); cl.decals = (decal_t *) Mem_Alloc(cls.levelmempool, cl.max_decals * sizeof(decal_t)); cl.showlmps = NULL; // LordHavoc: have to set up the baseline info for alpha and other stuff for (i = 0;i < cl.max_entities;i++) { cl.entities[i].state_baseline = defaultstate; cl.entities[i].state_previous = defaultstate; cl.entities[i].state_current = defaultstate; } if (IS_NEXUIZ_DERIVED(gamemode)) { VectorSet(cl.playerstandmins, -16, -16, -24); VectorSet(cl.playerstandmaxs, 16, 16, 45); VectorSet(cl.playercrouchmins, -16, -16, -24); VectorSet(cl.playercrouchmaxs, 16, 16, 25); } else { VectorSet(cl.playerstandmins, -16, -16, -24); VectorSet(cl.playerstandmaxs, 16, 16, 24); VectorSet(cl.playercrouchmins, -16, -16, -24); VectorSet(cl.playercrouchmaxs, 16, 16, 24); } // disable until we get textures for it R_ResetSkyBox(); ent = &cl.entities[0]; // entire entity array was cleared, so just fill in a few fields ent->state_current.active = true; ent->render.model = cl.worldmodel = NULL; // no world model yet ent->render.alpha = 1; ent->render.flags = RENDER_SHADOW | RENDER_LIGHT; Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, 0, 0, 0, 0, 0, 0, 1); ent->render.allowdecals = true; CL_UpdateRenderEntity(&ent->render); // noclip is turned off at start noclip_anglehack = false; // mark all frames invalid for delta memset(cl.qw_deltasequence, -1, sizeof(cl.qw_deltasequence)); // set bestweapon data back to Quake data IN_BestWeapon_ResetData(); CL_Screen_NewMap(); } void CL_SetInfo(const char *key, const char *value, qboolean send, qboolean allowstarkey, qboolean allowmodel, qboolean quiet) { int i; qboolean fail = false; char vabuf[1024]; if (!allowstarkey && key[0] == '*') fail = true; if (!allowmodel && (!strcasecmp(key, "pmodel") || !strcasecmp(key, "emodel"))) fail = true; for (i = 0;key[i];i++) if (ISWHITESPACE(key[i]) || key[i] == '\"') fail = true; for (i = 0;value[i];i++) if (value[i] == '\r' || value[i] == '\n' || value[i] == '\"') fail = true; if (fail) { if (!quiet) Con_Printf("Can't setinfo \"%s\" \"%s\"\n", key, value); return; } InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), key, value); if (cls.state == ca_connected && cls.netcon) { if (cls.protocol == PROTOCOL_QUAKEWORLD) { MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd); MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "setinfo \"%s\" \"%s\"", key, value)); } else if (!strcasecmp(key, "name")) { MSG_WriteByte(&cls.netcon->message, clc_stringcmd); MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "name \"%s\"", value)); } else if (!strcasecmp(key, "playermodel")) { MSG_WriteByte(&cls.netcon->message, clc_stringcmd); MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "playermodel \"%s\"", value)); } else if (!strcasecmp(key, "playerskin")) { MSG_WriteByte(&cls.netcon->message, clc_stringcmd); MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "playerskin \"%s\"", value)); } else if (!strcasecmp(key, "topcolor")) { // don't send anything, the combined color code will be updated manually } else if (!strcasecmp(key, "bottomcolor")) { // don't send anything, the combined color code will be updated manually } else if (!strcasecmp(key, "rate")) { MSG_WriteByte(&cls.netcon->message, clc_stringcmd); MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "rate \"%s\"", value)); } else if (!strcasecmp(key, "rate_burstsize")) { MSG_WriteByte(&cls.netcon->message, clc_stringcmd); MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "rate_burstsize \"%s\"", value)); } } } void CL_ExpandEntities(int num) { int i, oldmaxentities; entity_t *oldentities; if (num >= cl.max_entities) { if (!cl.entities) Sys_Error("CL_ExpandEntities: cl.entities not initialized"); if (num >= MAX_EDICTS) Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS); oldmaxentities = cl.max_entities; oldentities = cl.entities; cl.max_entities = (num & ~255) + 256; cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t)); memcpy(cl.entities, oldentities, oldmaxentities * sizeof(entity_t)); Mem_Free(oldentities); for (i = oldmaxentities;i < cl.max_entities;i++) { cl.entities[i].state_baseline = defaultstate; cl.entities[i].state_previous = defaultstate; cl.entities[i].state_current = defaultstate; } } } void CL_ExpandCSQCRenderEntities(int num) { int i; int oldmaxcsqcrenderentities; entity_render_t *oldcsqcrenderentities; if (num >= cl.max_csqcrenderentities) { if (num >= MAX_EDICTS) Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS); oldmaxcsqcrenderentities = cl.max_csqcrenderentities; oldcsqcrenderentities = cl.csqcrenderentities; cl.max_csqcrenderentities = (num & ~255) + 256; cl.csqcrenderentities = (entity_render_t *)Mem_Alloc(cls.levelmempool, cl.max_csqcrenderentities * sizeof(entity_render_t)); if (oldcsqcrenderentities) { memcpy(cl.csqcrenderentities, oldcsqcrenderentities, oldmaxcsqcrenderentities * sizeof(entity_render_t)); for (i = 0;i < r_refdef.scene.numentities;i++) if(r_refdef.scene.entities[i] >= oldcsqcrenderentities && r_refdef.scene.entities[i] < (oldcsqcrenderentities + oldmaxcsqcrenderentities)) r_refdef.scene.entities[i] = cl.csqcrenderentities + (r_refdef.scene.entities[i] - oldcsqcrenderentities); Mem_Free(oldcsqcrenderentities); } } } /* ===================== CL_Disconnect Sends a disconnect message to the server This is also called on Host_Error, so it shouldn't cause any errors ===================== */ void CL_Disconnect(void) { if (cls.state == ca_dedicated) return; if (COM_CheckParm("-profilegameonly")) Sys_AllowProfiling(false); Curl_Clear_forthismap(); Con_DPrintf("CL_Disconnect\n"); Cvar_SetValueQuick(&csqc_progcrc, -1); Cvar_SetValueQuick(&csqc_progsize, -1); CL_VM_ShutDown(); // stop sounds (especially looping!) S_StopAllSounds (); cl.parsingtextexpectingpingforscores = 0; // just in case no reply has come yet // clear contents blends cl.cshifts[0].percent = 0; cl.cshifts[1].percent = 0; cl.cshifts[2].percent = 0; cl.cshifts[3].percent = 0; cl.worldmodel = NULL; CL_Parse_ErrorCleanUp(); if (cls.demoplayback) CL_StopPlayback(); else if (cls.netcon) { sizebuf_t buf; unsigned char bufdata[8]; if (cls.demorecording) CL_Stop_f(); // send disconnect message 3 times to improve chances of server // receiving it (but it still fails sometimes) memset(&buf, 0, sizeof(buf)); buf.data = bufdata; buf.maxsize = sizeof(bufdata); if (cls.protocol == PROTOCOL_QUAKEWORLD) { Con_DPrint("Sending drop command\n"); MSG_WriteByte(&buf, qw_clc_stringcmd); MSG_WriteString(&buf, "drop"); } else { Con_DPrint("Sending clc_disconnect\n"); MSG_WriteByte(&buf, clc_disconnect); } NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, 0, false); NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, 0, false); NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, 0, false); NetConn_Close(cls.netcon); cls.netcon = NULL; } cls.state = ca_disconnected; cl.islocalgame = false; cls.demoplayback = cls.timedemo = false; cls.signon = 0; } void CL_Disconnect_f(void) { CL_Disconnect (); if (sv.active) Host_ShutdownServer (); } /* ===================== CL_EstablishConnection Host should be either "local" or a net address ===================== */ void CL_EstablishConnection(const char *host, int firstarg) { if (cls.state == ca_dedicated) return; // don't connect to a server if we're benchmarking a demo if (COM_CheckParm("-benchmark")) return; // clear menu's connect error message #ifdef CONFIG_MENU M_Update_Return_Reason(""); #endif cls.demonum = -1; // stop demo loop in case this fails if (cls.demoplayback) CL_StopPlayback(); // if downloads are running, cancel their finishing action Curl_Clear_forthismap(); // make sure the client ports are open before attempting to connect NetConn_UpdateSockets(); if (LHNETADDRESS_FromString(&cls.connect_address, host, 26000) && (cls.connect_mysocket = NetConn_ChooseClientSocketForAddress(&cls.connect_address))) { cls.connect_trying = true; cls.connect_remainingtries = 3; cls.connect_nextsendtime = 0; // only NOW, set connect_userinfo if(firstarg >= 0) { int i; *cls.connect_userinfo = 0; for(i = firstarg; i+2 <= Cmd_Argc(); i += 2) InfoString_SetValue(cls.connect_userinfo, sizeof(cls.connect_userinfo), Cmd_Argv(i), Cmd_Argv(i+1)); } else if(firstarg < -1) { // -1: keep as is (reconnect) // -2: clear *cls.connect_userinfo = 0; } #ifdef CONFIG_MENU M_Update_Return_Reason("Trying to connect..."); #endif } else { Con_Print("Unable to find a suitable network socket to connect to server.\n"); #ifdef CONFIG_MENU M_Update_Return_Reason("No network"); #endif } } /* ============== CL_PrintEntities_f ============== */ static void CL_PrintEntities_f(void) { entity_t *ent; int i; for (i = 0, ent = cl.entities;i < cl.num_entities;i++, ent++) { const char* modelname; if (!ent->state_current.active) continue; if (ent->render.model) modelname = ent->render.model->name; else modelname = "--no model--"; Con_Printf("%3i: %-25s:%4i (%5i %5i %5i) [%3i %3i %3i] %4.2f %5.3f\n", i, modelname, ent->render.framegroupblend[0].frame, (int) ent->state_current.origin[0], (int) ent->state_current.origin[1], (int) ent->state_current.origin[2], (int) ent->state_current.angles[0] % 360, (int) ent->state_current.angles[1] % 360, (int) ent->state_current.angles[2] % 360, ent->render.scale, ent->render.alpha); } } /* =============== CL_ModelIndexList_f List information on all models in the client modelindex =============== */ static void CL_ModelIndexList_f(void) { int i; dp_model_t *model; // Print Header Con_Printf("%3s: %-30s %-8s %-8s\n", "ID", "Name", "Type", "Triangles"); for (i = -MAX_MODELS;i < MAX_MODELS;i++) { model = CL_GetModelByIndex(i); if (!model) continue; if(model->loaded || i == 1) Con_Printf("%3i: %-30s %-8s %-10i\n", i, model->name, model->modeldatatypestring, model->surfmesh.num_triangles); else Con_Printf("%3i: %-30s %-30s\n", i, model->name, "--no local model found--"); i++; } } /* =============== CL_SoundIndexList_f List all sounds in the client soundindex =============== */ static void CL_SoundIndexList_f(void) { int i = 1; while(cl.sound_precache[i] && i != MAX_SOUNDS) { // Valid Sound Con_Printf("%i : %s\n", i, cl.sound_precache[i]->name); i++; } } /* =============== CL_UpdateRenderEntity Updates inversematrix, animation interpolation factors, scale, and mins/maxs =============== */ void CL_UpdateRenderEntity(entity_render_t *ent) { vec3_t org; vec_t scale; dp_model_t *model = ent->model; // update the inverse matrix for the renderer Matrix4x4_Invert_Simple(&ent->inversematrix, &ent->matrix); // update the animation blend state VM_FrameBlendFromFrameGroupBlend(ent->frameblend, ent->framegroupblend, ent->model, cl.time); // we need the matrix origin to center the box Matrix4x4_OriginFromMatrix(&ent->matrix, org); // update entity->render.scale because the renderer needs it ent->scale = scale = Matrix4x4_ScaleFromMatrix(&ent->matrix); if (model) { // NOTE: this directly extracts vector components from the matrix, which relies on the matrix orientation! #ifdef MATRIX4x4_OPENGLORIENTATION if (ent->matrix.m[0][2] != 0 || ent->matrix.m[1][2] != 0) #else if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0) #endif { // pitch or roll VectorMA(org, scale, model->rotatedmins, ent->mins); VectorMA(org, scale, model->rotatedmaxs, ent->maxs); } #ifdef MATRIX4x4_OPENGLORIENTATION else if (ent->matrix.m[1][0] != 0 || ent->matrix.m[0][1] != 0) #else else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0) #endif { // yaw VectorMA(org, scale, model->yawmins, ent->mins); VectorMA(org, scale, model->yawmaxs, ent->maxs); } else { VectorMA(org, scale, model->normalmins, ent->mins); VectorMA(org, scale, model->normalmaxs, ent->maxs); } } else { ent->mins[0] = org[0] - 16; ent->mins[1] = org[1] - 16; ent->mins[2] = org[2] - 16; ent->maxs[0] = org[0] + 16; ent->maxs[1] = org[1] + 16; ent->maxs[2] = org[2] + 16; } } /* =============== CL_LerpPoint Determines the fraction between the last two messages that the objects should be put at. =============== */ static float CL_LerpPoint(void) { float f; if (cl_nettimesyncboundmode.integer == 1) cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]); // LordHavoc: lerp in listen games as the server is being capped below the client (usually) if (cl.mtime[0] <= cl.mtime[1]) { cl.time = cl.mtime[0]; return 1; } f = (cl.time - cl.mtime[1]) / (cl.mtime[0] - cl.mtime[1]); return bound(0, f, 1 + cl_lerpexcess.value); } void CL_ClearTempEntities (void) { r_refdef.scene.numtempentities = 0; // grow tempentities buffer on request if (r_refdef.scene.expandtempentities) { Con_Printf("CL_NewTempEntity: grow maxtempentities from %i to %i\n", r_refdef.scene.maxtempentities, r_refdef.scene.maxtempentities * 2); r_refdef.scene.maxtempentities *= 2; r_refdef.scene.tempentities = (entity_render_t *)Mem_Realloc(cls.permanentmempool, r_refdef.scene.tempentities, sizeof(entity_render_t) * r_refdef.scene.maxtempentities); r_refdef.scene.expandtempentities = false; } } entity_render_t *CL_NewTempEntity(double shadertime) { entity_render_t *render; if (r_refdef.scene.numentities >= r_refdef.scene.maxentities) return NULL; if (r_refdef.scene.numtempentities >= r_refdef.scene.maxtempentities) { r_refdef.scene.expandtempentities = true; // will be reallocated next frame since current frame may have pointers set already return NULL; } render = &r_refdef.scene.tempentities[r_refdef.scene.numtempentities++]; memset (render, 0, sizeof(*render)); r_refdef.scene.entities[r_refdef.scene.numentities++] = render; render->shadertime = shadertime; render->alpha = 1; VectorSet(render->colormod, 1, 1, 1); VectorSet(render->glowmod, 1, 1, 1); return render; } void CL_Effect(vec3_t org, int modelindex, int startframe, int framecount, float framerate) { int i; cl_effect_t *e; if (!modelindex) // sanity check return; if (framerate < 1) { Con_Printf("CL_Effect: framerate %f is < 1\n", framerate); return; } if (framecount < 1) { Con_Printf("CL_Effect: framecount %i is < 1\n", framecount); return; } for (i = 0, e = cl.effects;i < cl.max_effects;i++, e++) { if (e->active) continue; e->active = true; VectorCopy(org, e->origin); e->modelindex = modelindex; e->starttime = cl.time; e->startframe = startframe; e->endframe = startframe + framecount; e->framerate = framerate; e->frame = 0; e->frame1time = cl.time; e->frame2time = cl.time; cl.num_effects = max(cl.num_effects, i + 1); break; } } void CL_AllocLightFlash(entity_render_t *ent, matrix4x4_t *matrix, float radius, float red, float green, float blue, float decay, float lifetime, char *cubemapname, int style, int shadowenable, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags) { int i; dlight_t *dl; // then look for anything else dl = cl.dlights; for (i = 0;i < cl.max_dlights;i++, dl++) if (!dl->radius) break; // unable to find one if (i == cl.max_dlights) return; //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius); memset (dl, 0, sizeof(*dl)); cl.num_dlights = max(cl.num_dlights, i + 1); Matrix4x4_Normalize(&dl->matrix, matrix); dl->ent = ent; Matrix4x4_OriginFromMatrix(&dl->matrix, dl->origin); CL_FindNonSolidLocation(dl->origin, dl->origin, 6); Matrix4x4_SetOrigin(&dl->matrix, dl->origin[0], dl->origin[1], dl->origin[2]); dl->radius = radius; dl->color[0] = red; dl->color[1] = green; dl->color[2] = blue; dl->initialradius = radius; dl->initialcolor[0] = red; dl->initialcolor[1] = green; dl->initialcolor[2] = blue; dl->decay = decay / radius; // changed decay to be a percentage decrease dl->intensity = 1; // this is what gets decayed if (lifetime) dl->die = cl.time + lifetime; else dl->die = 0; dl->cubemapname[0] = 0; if (cubemapname && cubemapname[0]) strlcpy(dl->cubemapname, cubemapname, sizeof(dl->cubemapname)); dl->style = style; dl->shadow = shadowenable; dl->corona = corona; dl->flags = flags; dl->coronasizescale = coronasizescale; dl->ambientscale = ambientscale; dl->diffusescale = diffusescale; dl->specularscale = specularscale; } static void CL_DecayLightFlashes(void) { int i, oldmax; dlight_t *dl; float time; time = bound(0, cl.time - cl.oldtime, 0.1); oldmax = cl.num_dlights; cl.num_dlights = 0; for (i = 0, dl = cl.dlights;i < oldmax;i++, dl++) { if (dl->radius) { dl->intensity -= time * dl->decay; if (cl.time < dl->die && dl->intensity > 0) { if (cl_dlights_decayradius.integer) dl->radius = dl->initialradius * dl->intensity; else dl->radius = dl->initialradius; if (cl_dlights_decaybrightness.integer) VectorScale(dl->initialcolor, dl->intensity, dl->color); else VectorCopy(dl->initialcolor, dl->color); cl.num_dlights = i + 1; } else dl->radius = 0; } } } // called before entity relinking void CL_RelinkLightFlashes(void) { int i, j, k, l; dlight_t *dl; float frac, f; matrix4x4_t tempmatrix; if (r_dynamic.integer) { for (i = 0, dl = cl.dlights;i < cl.num_dlights && r_refdef.scene.numlights < MAX_DLIGHTS;i++, dl++) { if (dl->radius) { tempmatrix = dl->matrix; Matrix4x4_Scale(&tempmatrix, dl->radius, 1); // we need the corona fading to be persistent R_RTLight_Update(&dl->rtlight, false, &tempmatrix, dl->color, dl->style, dl->cubemapname, dl->shadow, dl->corona, dl->coronasizescale, dl->ambientscale, dl->diffusescale, dl->specularscale, dl->flags); r_refdef.scene.lights[r_refdef.scene.numlights++] = &dl->rtlight; } } } if (!cl.lightstyle) { for (j = 0;j < cl.max_lightstyle;j++) { r_refdef.scene.rtlightstylevalue[j] = 1; r_refdef.scene.lightstylevalue[j] = 256; } return; } // light animations // 'm' is normal light, 'a' is no light, 'z' is double bright f = cl.time * 10; i = (int)floor(f); frac = f - i; for (j = 0;j < cl.max_lightstyle;j++) { if (!cl.lightstyle[j].length) { r_refdef.scene.rtlightstylevalue[j] = 1; r_refdef.scene.lightstylevalue[j] = 256; continue; } // static lightstyle "=value" if (cl.lightstyle[j].map[0] == '=') { r_refdef.scene.rtlightstylevalue[j] = atof(cl.lightstyle[j].map + 1); if ( r_lerplightstyles.integer || ((int)f - f) < 0.01) r_refdef.scene.lightstylevalue[j] = r_refdef.scene.rtlightstylevalue[j]; continue; } k = i % cl.lightstyle[j].length; l = (i-1) % cl.lightstyle[j].length; k = cl.lightstyle[j].map[k] - 'a'; l = cl.lightstyle[j].map[l] - 'a'; // rtlightstylevalue is always interpolated because it has no bad // consequences for performance // lightstylevalue is subject to a cvar for performance reasons; // skipping lightmap updates on most rendered frames substantially // improves framerates (but makes light fades look bad) r_refdef.scene.rtlightstylevalue[j] = ((k*frac)+(l*(1-frac)))*(22/256.0f); r_refdef.scene.lightstylevalue[j] = r_lerplightstyles.integer ? (unsigned short)(((k*frac)+(l*(1-frac)))*22) : k*22; } } static void CL_AddQWCTFFlagModel(entity_t *player, int skin) { int frame = player->render.framegroupblend[0].frame; float f; entity_render_t *flagrender; matrix4x4_t flagmatrix; // this code taken from QuakeWorld f = 14; if (frame >= 29 && frame <= 40) { if (frame >= 29 && frame <= 34) { //axpain if (frame == 29) f = f + 2; else if (frame == 30) f = f + 8; else if (frame == 31) f = f + 12; else if (frame == 32) f = f + 11; else if (frame == 33) f = f + 10; else if (frame == 34) f = f + 4; } else if (frame >= 35 && frame <= 40) { // pain if (frame == 35) f = f + 2; else if (frame == 36) f = f + 10; else if (frame == 37) f = f + 10; else if (frame == 38) f = f + 8; else if (frame == 39) f = f + 4; else if (frame == 40) f = f + 2; } } else if (frame >= 103 && frame <= 118) { if (frame >= 103 && frame <= 104) f = f + 6; //nailattack else if (frame >= 105 && frame <= 106) f = f + 6; //light else if (frame >= 107 && frame <= 112) f = f + 7; //rocketattack else if (frame >= 112 && frame <= 118) f = f + 7; //shotattack } // end of code taken from QuakeWorld flagrender = CL_NewTempEntity(player->render.shadertime); if (!flagrender) return; flagrender->model = CL_GetModelByIndex(cl.qw_modelindex_flag); flagrender->skinnum = skin; flagrender->alpha = 1; VectorSet(flagrender->colormod, 1, 1, 1); VectorSet(flagrender->glowmod, 1, 1, 1); // attach the flag to the player matrix Matrix4x4_CreateFromQuakeEntity(&flagmatrix, -f, -22, 0, 0, 0, -45, 1); Matrix4x4_Concat(&flagrender->matrix, &player->render.matrix, &flagmatrix); CL_UpdateRenderEntity(flagrender); } matrix4x4_t viewmodelmatrix_withbob; matrix4x4_t viewmodelmatrix_nobob; static const vec3_t muzzleflashorigin = {18, 0, 0}; void CL_SetEntityColormapColors(entity_render_t *ent, int colormap) { const unsigned char *cbcolor; if (colormap >= 0) { cbcolor = palette_rgb_pantscolormap[colormap & 0xF]; VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_pantscolor); cbcolor = palette_rgb_shirtcolormap[(colormap & 0xF0) >> 4]; VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_shirtcolor); } else { VectorClear(ent->colormap_pantscolor); VectorClear(ent->colormap_shirtcolor); } } // note this is a recursive function, recursionlimit should be 32 or so on the initial call static void CL_UpdateNetworkEntity(entity_t *e, int recursionlimit, qboolean interpolate) { const matrix4x4_t *matrix; matrix4x4_t blendmatrix, tempmatrix, matrix2; int frame; vec_t origin[3], angles[3], lerp; entity_t *t; entity_render_t *r; //entity_persistent_t *p = &e->persistent; //entity_render_t *r = &e->render; // skip inactive entities and world if (!e->state_current.active || e == cl.entities) return; if (recursionlimit < 1) return; e->render.alpha = e->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate? e->render.scale = e->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate? e->render.flags = e->state_current.flags; e->render.effects = e->state_current.effects; VectorScale(e->state_current.colormod, (1.0f / 32.0f), e->render.colormod); VectorScale(e->state_current.glowmod, (1.0f / 32.0f), e->render.glowmod); if(e >= cl.entities && e < cl.entities + cl.num_entities) e->render.entitynumber = e - cl.entities; else e->render.entitynumber = 0; if (e->state_current.flags & RENDER_COLORMAPPED) CL_SetEntityColormapColors(&e->render, e->state_current.colormap); else if (e->state_current.colormap > 0 && e->state_current.colormap <= cl.maxclients && cl.scores != NULL) CL_SetEntityColormapColors(&e->render, cl.scores[e->state_current.colormap-1].colors); else CL_SetEntityColormapColors(&e->render, -1); e->render.skinnum = e->state_current.skin; if (e->state_current.tagentity) { // attached entity (gun held in player model's hand, etc) // if the tag entity is currently impossible, skip it if (e->state_current.tagentity >= cl.num_entities) return; t = cl.entities + e->state_current.tagentity; // if the tag entity is inactive, skip it if (t->state_current.active) { // update the parent first CL_UpdateNetworkEntity(t, recursionlimit - 1, interpolate); r = &t->render; } else { // it may still be a CSQC entity... trying to use its // info from last render frame (better than nothing) if(!cl.csqc_server2csqcentitynumber[e->state_current.tagentity]) return; r = cl.csqcrenderentities + cl.csqc_server2csqcentitynumber[e->state_current.tagentity]; if(!r->entitynumber) return; // neither CSQC nor legacy entity... can't attach } // make relative to the entity matrix = &r->matrix; // some properties of the tag entity carry over e->render.flags |= r->flags & (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL); // if a valid tagindex is used, make it relative to that tag instead if (e->state_current.tagentity && e->state_current.tagindex >= 1 && r->model) { if(!Mod_Alias_GetTagMatrix(r->model, r->frameblend, r->skeleton, e->state_current.tagindex - 1, &blendmatrix)) // i.e. no error { // concat the tag matrices onto the entity matrix Matrix4x4_Concat(&tempmatrix, &r->matrix, &blendmatrix); // use the constructed tag matrix matrix = &tempmatrix; } } } else if (e->render.flags & RENDER_VIEWMODEL) { // view-relative entity (guns and such) if (e->render.effects & EF_NOGUNBOB) matrix = &viewmodelmatrix_nobob; // really attached to view else matrix = &viewmodelmatrix_withbob; // attached to gun bob matrix } else { // world-relative entity (the normal kind) matrix = &identitymatrix; } // movement lerp // if it's the predicted player entity, update according to client movement // but don't lerp if going through a teleporter as it causes a bad lerp // also don't use the predicted location if fixangle was set on both of // the most recent server messages, as that cause means you are spectating // someone or watching a cutscene of some sort if (cl_nolerp.integer || cls.timedemo) interpolate = false; if (e == cl.entities + cl.playerentity && cl.movement_predicted && (!cl.fixangle[1] || !cl.fixangle[0])) { VectorCopy(cl.movement_origin, origin); VectorSet(angles, 0, cl.viewangles[1], 0); } else if (interpolate && e->persistent.lerpdeltatime > 0 && (lerp = (cl.time - e->persistent.lerpstarttime) / e->persistent.lerpdeltatime) < 1 + cl_lerpexcess.value) { // interpolate the origin and angles lerp = max(0, lerp); VectorLerp(e->persistent.oldorigin, lerp, e->persistent.neworigin, origin); #if 0 // this fails at the singularity of euler angles VectorSubtract(e->persistent.newangles, e->persistent.oldangles, delta); if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360; if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360; if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360; VectorMA(e->persistent.oldangles, lerp, delta, angles); #else { vec3_t f0, u0, f1, u1; AngleVectors(e->persistent.oldangles, f0, NULL, u0); AngleVectors(e->persistent.newangles, f1, NULL, u1); VectorMAM(1-lerp, f0, lerp, f1, f0); VectorMAM(1-lerp, u0, lerp, u1, u0); AnglesFromVectors(angles, f0, u0, false); } #endif } else { // no interpolation VectorCopy(e->persistent.neworigin, origin); VectorCopy(e->persistent.newangles, angles); } // model setup and some modelflags frame = e->state_current.frame; e->render.model = CL_GetModelByIndex(e->state_current.modelindex); if (e->render.model) { if (e->render.skinnum >= e->render.model->numskins) e->render.skinnum = 0; if (frame >= e->render.model->numframes) frame = 0; // models can set flags such as EF_ROCKET // this 0xFF800000 mask is EF_NOMODELFLAGS plus all the higher EF_ flags such as EF_ROCKET if (!(e->render.effects & 0xFF800000)) e->render.effects |= e->render.model->effects; // if model is alias or this is a tenebrae-like dlight, reverse pitch direction if (e->render.model->type == mod_alias) angles[0] = -angles[0]; if ((e->render.effects & EF_SELECTABLE) && cl.cmd.cursor_entitynumber == e->state_current.number) { VectorScale(e->render.colormod, 2, e->render.colormod); VectorScale(e->render.glowmod, 2, e->render.glowmod); } } // if model is alias or this is a tenebrae-like dlight, reverse pitch direction else if (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC) angles[0] = -angles[0]; // NOTE: this must be synced to SV_GetPitchSign! if ((e->render.effects & EF_ROTATE) && !(e->render.flags & RENDER_VIEWMODEL)) { angles[1] = ANGLEMOD(100*cl.time); if (cl_itembobheight.value) origin[2] += (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value; } // animation lerp e->render.skeleton = NULL; if (e->render.flags & RENDER_COMPLEXANIMATION) { e->render.framegroupblend[0] = e->state_current.framegroupblend[0]; e->render.framegroupblend[1] = e->state_current.framegroupblend[1]; e->render.framegroupblend[2] = e->state_current.framegroupblend[2]; e->render.framegroupblend[3] = e->state_current.framegroupblend[3]; if (e->state_current.skeletonobject.model && e->state_current.skeletonobject.relativetransforms) e->render.skeleton = &e->state_current.skeletonobject; } else if (e->render.framegroupblend[0].frame == frame) { // update frame lerp fraction e->render.framegroupblend[0].lerp = 1; e->render.framegroupblend[1].lerp = 0; if (e->render.framegroupblend[0].start > e->render.framegroupblend[1].start) { // make sure frame lerp won't last longer than 100ms // (this mainly helps with models that use framegroups and // switch between them infrequently) float maxdelta = cl_lerpanim_maxdelta_server.value; if(e->render.model) if(e->render.model->animscenes) if(e->render.model->animscenes[e->render.framegroupblend[0].frame].framecount > 1 || e->render.model->animscenes[e->render.framegroupblend[1].frame].framecount > 1) maxdelta = cl_lerpanim_maxdelta_framegroups.value; maxdelta = max(maxdelta, cl.mtime[0] - cl.mtime[1]); e->render.framegroupblend[0].lerp = (cl.time - e->render.framegroupblend[0].start) / min(e->render.framegroupblend[0].start - e->render.framegroupblend[1].start, maxdelta); e->render.framegroupblend[0].lerp = bound(0, e->render.framegroupblend[0].lerp, 1); e->render.framegroupblend[1].lerp = 1 - e->render.framegroupblend[0].lerp; } } else { // begin a new frame lerp e->render.framegroupblend[1] = e->render.framegroupblend[0]; e->render.framegroupblend[1].lerp = 1; e->render.framegroupblend[0].frame = frame; e->render.framegroupblend[0].start = cl.time; e->render.framegroupblend[0].lerp = 0; } // set up the render matrix if (matrix) { // attached entity, this requires a matrix multiply (concat) // FIXME: e->render.scale should go away Matrix4x4_CreateFromQuakeEntity(&matrix2, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale); // concat the matrices to make the entity relative to its tag Matrix4x4_Concat(&e->render.matrix, matrix, &matrix2); // get the origin from the new matrix Matrix4x4_OriginFromMatrix(&e->render.matrix, origin); } else { // unattached entities are faster to process Matrix4x4_CreateFromQuakeEntity(&e->render.matrix, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale); } // tenebrae's sprites are all additive mode (weird) if (gamemode == GAME_TENEBRAE && e->render.model && e->render.model->type == mod_sprite) e->render.flags |= RENDER_ADDITIVE; // player model is only shown with chase_active on if (e->state_current.number == cl.viewentity) e->render.flags |= RENDER_EXTERIORMODEL; // either fullbright or lit if(!r_fullbright.integer) { if (!(e->render.effects & EF_FULLBRIGHT)) e->render.flags |= RENDER_LIGHT; else if(r_equalize_entities_fullbright.integer) e->render.flags |= RENDER_LIGHT | RENDER_EQUALIZE; } // hide player shadow during intermission or nehahra movie if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST)) && (e->render.alpha >= 1) && !(e->render.flags & RENDER_VIEWMODEL) && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer))) e->render.flags |= RENDER_SHADOW; if (e->render.flags & RENDER_VIEWMODEL) e->render.flags |= RENDER_NOSELFSHADOW; if (e->render.effects & EF_NOSELFSHADOW) e->render.flags |= RENDER_NOSELFSHADOW; if (e->render.effects & EF_NODEPTHTEST) e->render.flags |= RENDER_NODEPTHTEST; if (e->render.effects & EF_ADDITIVE) e->render.flags |= RENDER_ADDITIVE; if (e->render.effects & EF_DOUBLESIDED) e->render.flags |= RENDER_DOUBLESIDED; if (e->render.effects & EF_DYNAMICMODELLIGHT) e->render.flags |= RENDER_DYNAMICMODELLIGHT; // make the other useful stuff e->render.allowdecals = true; CL_UpdateRenderEntity(&e->render); } // creates light and trails from an entity static void CL_UpdateNetworkEntityTrail(entity_t *e) { effectnameindex_t trailtype; vec3_t origin; // bmodels are treated specially since their origin is usually '0 0 0' and // their actual geometry is far from '0 0 0' if (e->render.model && e->render.model->soundfromcenter) { vec3_t o; VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o); Matrix4x4_Transform(&e->render.matrix, o, origin); } else Matrix4x4_OriginFromMatrix(&e->render.matrix, origin); // handle particle trails and such effects now that we know where this // entity is in the world... trailtype = EFFECT_NONE; // LordHavoc: if the entity has no effects, don't check each if (e->render.effects & (EF_BRIGHTFIELD | EF_FLAME | EF_STARDUST)) { if (e->render.effects & EF_BRIGHTFIELD) { if (IS_NEXUIZ_DERIVED(gamemode)) trailtype = EFFECT_TR_NEXUIZPLASMA; else CL_EntityParticles(e); } if (e->render.effects & EF_FLAME) CL_ParticleTrail(EFFECT_EF_FLAME, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true, NULL, NULL, 1); if (e->render.effects & EF_STARDUST) CL_ParticleTrail(EFFECT_EF_STARDUST, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true, NULL, NULL, 1); } if (e->render.internaleffects & (INTEF_FLAG1QW | INTEF_FLAG2QW)) { // these are only set on player entities CL_AddQWCTFFlagModel(e, (e->render.internaleffects & INTEF_FLAG2QW) != 0); } // muzzleflash fades over time if (e->persistent.muzzleflash > 0) e->persistent.muzzleflash -= bound(0, cl.time - cl.oldtime, 0.1) * 20; // LordHavoc: if the entity has no effects, don't check each if (e->render.effects && !(e->render.flags & RENDER_VIEWMODEL)) { if (e->render.effects & EF_GIB) trailtype = EFFECT_TR_BLOOD; else if (e->render.effects & EF_ZOMGIB) trailtype = EFFECT_TR_SLIGHTBLOOD; else if (e->render.effects & EF_TRACER) trailtype = EFFECT_TR_WIZSPIKE; else if (e->render.effects & EF_TRACER2) trailtype = EFFECT_TR_KNIGHTSPIKE; else if (e->render.effects & EF_ROCKET) trailtype = EFFECT_TR_ROCKET; else if (e->render.effects & EF_GRENADE) { // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke) trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE; } else if (e->render.effects & EF_TRACER3) trailtype = EFFECT_TR_VORESPIKE; } // do trails if (e->render.flags & RENDER_GLOWTRAIL) trailtype = EFFECT_TR_GLOWTRAIL; if (e->state_current.traileffectnum) trailtype = (effectnameindex_t)e->state_current.traileffectnum; // check if a trail is allowed (it is not after a teleport for example) if (trailtype && e->persistent.trail_allowed) { float len; vec3_t vel; VectorSubtract(e->state_current.origin, e->state_previous.origin, vel); len = e->state_current.time - e->state_previous.time; if (len > 0) len = 1.0f / len; VectorScale(vel, len, vel); // pass time as count so that trails that are time based (such as an emitter) will emit properly as long as they don't use trailspacing CL_ParticleTrail(trailtype, bound(0, cl.time - cl.oldtime, 0.1), e->persistent.trail_origin, origin, vel, vel, e, e->state_current.glowcolor, false, true, NULL, NULL, 1); } // now that the entity has survived one trail update it is allowed to // leave a real trail on later frames e->persistent.trail_allowed = true; VectorCopy(origin, e->persistent.trail_origin); } /* =============== CL_UpdateViewEntities =============== */ void CL_UpdateViewEntities(void) { int i; // update any RENDER_VIEWMODEL entities to use the new view matrix for (i = 1;i < cl.num_entities;i++) { if (cl.entities_active[i]) { entity_t *ent = cl.entities + i; if ((ent->render.flags & RENDER_VIEWMODEL) || ent->state_current.tagentity) CL_UpdateNetworkEntity(ent, 32, true); } } // and of course the engine viewmodel needs updating as well CL_UpdateNetworkEntity(&cl.viewent, 32, true); } /* =============== CL_UpdateNetworkCollisionEntities =============== */ static void CL_UpdateNetworkCollisionEntities(void) { entity_t *ent; int i; // start on the entity after the world cl.num_brushmodel_entities = 0; for (i = cl.maxclients + 1;i < cl.num_entities;i++) { if (cl.entities_active[i]) { ent = cl.entities + i; if (ent->state_current.active && ent->render.model && ent->render.model->name[0] == '*' && ent->render.model->TraceBox) { // do not interpolate the bmodels for this CL_UpdateNetworkEntity(ent, 32, false); cl.brushmodel_entities[cl.num_brushmodel_entities++] = i; } } } } /* =============== CL_UpdateNetworkEntities =============== */ static void CL_UpdateNetworkEntities(void) { entity_t *ent; int i; // start on the entity after the world for (i = 1;i < cl.num_entities;i++) { if (cl.entities_active[i]) { ent = cl.entities + i; if (ent->state_current.active) { CL_UpdateNetworkEntity(ent, 32, true); // view models should never create light/trails if (!(ent->render.flags & RENDER_VIEWMODEL)) CL_UpdateNetworkEntityTrail(ent); } else { R_DecalSystem_Reset(&ent->render.decalsystem); cl.entities_active[i] = false; } } } } static void CL_UpdateViewModel(void) { entity_t *ent; ent = &cl.viewent; ent->state_previous = ent->state_current; ent->state_current = defaultstate; ent->state_current.time = cl.time; ent->state_current.number = (unsigned short)-1; ent->state_current.active = true; ent->state_current.modelindex = cl.stats[STAT_WEAPON]; ent->state_current.frame = cl.stats[STAT_WEAPONFRAME]; ent->state_current.flags = RENDER_VIEWMODEL; if ((cl.stats[STAT_HEALTH] <= 0 && cl_deathnoviewmodel.integer) || cl.intermission) ent->state_current.modelindex = 0; else if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY) { if (gamemode == GAME_TRANSFUSION) ent->state_current.alpha = 128; else ent->state_current.modelindex = 0; } ent->state_current.alpha = cl.entities[cl.viewentity].state_current.alpha; ent->state_current.effects = EF_NOSHADOW | (cl.entities[cl.viewentity].state_current.effects & (EF_ADDITIVE | EF_FULLBRIGHT | EF_NODEPTHTEST | EF_NOGUNBOB)); // reset animation interpolation on weaponmodel if model changed if (ent->state_previous.modelindex != ent->state_current.modelindex) { ent->render.framegroupblend[0].frame = ent->render.framegroupblend[1].frame = ent->state_current.frame; ent->render.framegroupblend[0].start = ent->render.framegroupblend[1].start = cl.time; ent->render.framegroupblend[0].lerp = 1;ent->render.framegroupblend[1].lerp = 0; } CL_UpdateNetworkEntity(ent, 32, true); } // note this is a recursive function, but it can never get in a runaway loop (because of the delayedlink flags) static void CL_LinkNetworkEntity(entity_t *e) { effectnameindex_t trailtype; vec3_t origin; vec3_t dlightcolor; vec_t dlightradius; char vabuf[1024]; // skip inactive entities and world if (!e->state_current.active || e == cl.entities) return; if (e->state_current.tagentity) { // if the tag entity is currently impossible, skip it if (e->state_current.tagentity >= cl.num_entities) return; // if the tag entity is inactive, skip it if (!cl.entities[e->state_current.tagentity].state_current.active) { if(!cl.csqc_server2csqcentitynumber[e->state_current.tagentity]) return; if(!cl.csqcrenderentities[cl.csqc_server2csqcentitynumber[e->state_current.tagentity]].entitynumber) return; // if we get here, it's properly csqc networked and attached } } // create entity dlights associated with this entity if (e->render.model && e->render.model->soundfromcenter) { // bmodels are treated specially since their origin is usually '0 0 0' vec3_t o; VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o); Matrix4x4_Transform(&e->render.matrix, o, origin); } else Matrix4x4_OriginFromMatrix(&e->render.matrix, origin); trailtype = EFFECT_NONE; dlightradius = 0; dlightcolor[0] = 0; dlightcolor[1] = 0; dlightcolor[2] = 0; // LordHavoc: if the entity has no effects, don't check each if (e->render.effects & (EF_BRIGHTFIELD | EF_DIMLIGHT | EF_BRIGHTLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST)) { if (e->render.effects & EF_BRIGHTFIELD) { if (IS_NEXUIZ_DERIVED(gamemode)) trailtype = EFFECT_TR_NEXUIZPLASMA; } if (e->render.effects & EF_DIMLIGHT) { dlightradius = max(dlightradius, 200); dlightcolor[0] += 1.50f; dlightcolor[1] += 1.50f; dlightcolor[2] += 1.50f; } if (e->render.effects & EF_BRIGHTLIGHT) { dlightradius = max(dlightradius, 400); dlightcolor[0] += 3.00f; dlightcolor[1] += 3.00f; dlightcolor[2] += 3.00f; } // LordHavoc: more effects if (e->render.effects & EF_RED) // red { dlightradius = max(dlightradius, 200); dlightcolor[0] += 1.50f; dlightcolor[1] += 0.15f; dlightcolor[2] += 0.15f; } if (e->render.effects & EF_BLUE) // blue { dlightradius = max(dlightradius, 200); dlightcolor[0] += 0.15f; dlightcolor[1] += 0.15f; dlightcolor[2] += 1.50f; } if (e->render.effects & EF_FLAME) CL_ParticleTrail(EFFECT_EF_FLAME, 1, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false, NULL, NULL, 1); if (e->render.effects & EF_STARDUST) CL_ParticleTrail(EFFECT_EF_STARDUST, 1, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false, NULL, NULL, 1); } // muzzleflash fades over time, and is offset a bit if (e->persistent.muzzleflash > 0 && r_refdef.scene.numlights < MAX_DLIGHTS) { vec3_t v2; vec3_t color; trace_t trace; matrix4x4_t tempmatrix; Matrix4x4_Transform(&e->render.matrix, muzzleflashorigin, v2); trace = CL_TraceLine(origin, v2, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID | SUPERCONTENTS_SKY, collision_extendmovelength.value, true, false, NULL, false, false); Matrix4x4_Normalize(&tempmatrix, &e->render.matrix); Matrix4x4_SetOrigin(&tempmatrix, trace.endpos[0], trace.endpos[1], trace.endpos[2]); Matrix4x4_Scale(&tempmatrix, 150, 1); VectorSet(color, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f); R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &tempmatrix, color, -1, NULL, true, 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE); r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights];r_refdef.scene.numlights++; } // LordHavoc: if the model has no flags, don't check each if (e->render.model && e->render.effects && !(e->render.flags & RENDER_VIEWMODEL)) { if (e->render.effects & EF_GIB) trailtype = EFFECT_TR_BLOOD; else if (e->render.effects & EF_ZOMGIB) trailtype = EFFECT_TR_SLIGHTBLOOD; else if (e->render.effects & EF_TRACER) trailtype = EFFECT_TR_WIZSPIKE; else if (e->render.effects & EF_TRACER2) trailtype = EFFECT_TR_KNIGHTSPIKE; else if (e->render.effects & EF_ROCKET) trailtype = EFFECT_TR_ROCKET; else if (e->render.effects & EF_GRENADE) { // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke) trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE; } else if (e->render.effects & EF_TRACER3) trailtype = EFFECT_TR_VORESPIKE; } // LordHavoc: customizable glow if (e->state_current.glowsize) { // * 4 for the expansion from 0-255 to 0-1023 range, // / 255 to scale down byte colors dlightradius = max(dlightradius, e->state_current.glowsize * 4); VectorMA(dlightcolor, (1.0f / 255.0f), palette_rgb[e->state_current.glowcolor], dlightcolor); } // custom rtlight if ((e->state_current.lightpflags & PFLAGS_FULLDYNAMIC) && r_refdef.scene.numlights < MAX_DLIGHTS) { matrix4x4_t dlightmatrix; vec4_t light; VectorScale(e->state_current.light, (1.0f / 256.0f), light); light[3] = e->state_current.light[3]; if (light[0] == 0 && light[1] == 0 && light[2] == 0) VectorSet(light, 1, 1, 1); if (light[3] == 0) light[3] = 350; // FIXME: add ambient/diffuse/specular scales as an extension ontop of TENEBRAE_GFX_DLIGHTS? Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix); Matrix4x4_Scale(&dlightmatrix, light[3], 1); R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &dlightmatrix, light, e->state_current.lightstyle, e->state_current.skin > 0 ? va(vabuf, sizeof(vabuf), "cubemaps/%i", e->state_current.skin) : NULL, !(e->state_current.lightpflags & PFLAGS_NOSHADOW), (e->state_current.lightpflags & PFLAGS_CORONA) != 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE | (e->state_current.lightpflags & PFLAGS_LODFADE ? LIGHTFLAG_DISTANCEFADE : 0)); r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights]; r_refdef.scene.numlights++; } // make the glow dlight else if (dlightradius > 0 && (dlightcolor[0] || dlightcolor[1] || dlightcolor[2]) && !(e->render.flags & RENDER_VIEWMODEL) && r_refdef.scene.numlights < MAX_DLIGHTS) { matrix4x4_t dlightmatrix; Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix); // hack to make glowing player light shine on their gun //if (e->state_current.number == cl.viewentity/* && !chase_active.integer*/) // Matrix4x4_AdjustOrigin(&dlightmatrix, 0, 0, 30); Matrix4x4_Scale(&dlightmatrix, dlightradius, 1); R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &dlightmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE); r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights];r_refdef.scene.numlights++; } // do trail light if (e->render.flags & RENDER_GLOWTRAIL) trailtype = EFFECT_TR_GLOWTRAIL; if (e->state_current.traileffectnum) trailtype = (effectnameindex_t)e->state_current.traileffectnum; if (trailtype) CL_ParticleTrail(trailtype, 1, origin, origin, vec3_origin, vec3_origin, NULL, e->state_current.glowcolor, true, false, NULL, NULL, 1); // don't show entities with no modelindex (note: this still shows // entities which have a modelindex that resolved to a NULL model) if (e->render.model && !(e->render.effects & EF_NODRAW) && r_refdef.scene.numentities < r_refdef.scene.maxentities) r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render; //if (cl.viewentity && e->state_current.number == cl.viewentity) // Matrix4x4_Print(&e->render.matrix); } static void CL_RelinkWorld(void) { entity_t *ent = &cl.entities[0]; // FIXME: this should be done at load ent->render.matrix = identitymatrix; ent->render.flags = RENDER_SHADOW; if (!r_fullbright.integer) ent->render.flags |= RENDER_LIGHT; VectorSet(ent->render.colormod, 1, 1, 1); VectorSet(ent->render.glowmod, 1, 1, 1); ent->render.allowdecals = true; CL_UpdateRenderEntity(&ent->render); r_refdef.scene.worldentity = &ent->render; r_refdef.scene.worldmodel = cl.worldmodel; } static void CL_RelinkStaticEntities(void) { int i; entity_t *e; for (i = 0, e = cl.static_entities;i < cl.num_static_entities && r_refdef.scene.numentities < r_refdef.scene.maxentities;i++, e++) { e->render.flags = 0; // if the model was not loaded when the static entity was created we // need to re-fetch the model pointer e->render.model = CL_GetModelByIndex(e->state_baseline.modelindex); // either fullbright or lit if(!r_fullbright.integer) { if (!(e->render.effects & EF_FULLBRIGHT)) e->render.flags |= RENDER_LIGHT; else if(r_equalize_entities_fullbright.integer) e->render.flags |= RENDER_LIGHT | RENDER_EQUALIZE; } // hide player shadow during intermission or nehahra movie if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST)) && (e->render.alpha >= 1)) e->render.flags |= RENDER_SHADOW; VectorSet(e->render.colormod, 1, 1, 1); VectorSet(e->render.glowmod, 1, 1, 1); VM_FrameBlendFromFrameGroupBlend(e->render.frameblend, e->render.framegroupblend, e->render.model, cl.time); e->render.allowdecals = true; CL_UpdateRenderEntity(&e->render); r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render; } } /* =============== CL_RelinkEntities =============== */ static void CL_RelinkNetworkEntities(void) { entity_t *ent; int i; // start on the entity after the world for (i = 1;i < cl.num_entities;i++) { if (cl.entities_active[i]) { ent = cl.entities + i; if (ent->state_current.active) CL_LinkNetworkEntity(ent); else cl.entities_active[i] = false; } } } static void CL_RelinkEffects(void) { int i, intframe; cl_effect_t *e; entity_render_t *entrender; float frame; for (i = 0, e = cl.effects;i < cl.num_effects;i++, e++) { if (e->active) { frame = (cl.time - e->starttime) * e->framerate + e->startframe; intframe = (int)frame; if (intframe < 0 || intframe >= e->endframe) { memset(e, 0, sizeof(*e)); while (cl.num_effects > 0 && !cl.effects[cl.num_effects - 1].active) cl.num_effects--; continue; } if (intframe != e->frame) { e->frame = intframe; e->frame1time = e->frame2time; e->frame2time = cl.time; } // if we're drawing effects, get a new temp entity // (NewTempEntity adds it to the render entities list for us) if (r_draweffects.integer && (entrender = CL_NewTempEntity(e->starttime))) { // interpolation stuff entrender->framegroupblend[0].frame = intframe; entrender->framegroupblend[0].lerp = 1 - frame - intframe; entrender->framegroupblend[0].start = e->frame1time; if (intframe + 1 >= e->endframe) { entrender->framegroupblend[1].frame = 0; // disappear entrender->framegroupblend[1].lerp = 0; entrender->framegroupblend[1].start = 0; } else { entrender->framegroupblend[1].frame = intframe + 1; entrender->framegroupblend[1].lerp = frame - intframe; entrender->framegroupblend[1].start = e->frame2time; } // normal stuff entrender->model = CL_GetModelByIndex(e->modelindex); entrender->alpha = 1; VectorSet(entrender->colormod, 1, 1, 1); VectorSet(entrender->glowmod, 1, 1, 1); Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1); CL_UpdateRenderEntity(entrender); } } } } void CL_Beam_CalculatePositions(const beam_t *b, vec3_t start, vec3_t end) { VectorCopy(b->start, start); VectorCopy(b->end, end); // if coming from the player, update the start position if (b->entity == cl.viewentity) { if (cl_beams_quakepositionhack.integer && !chase_active.integer) { // LordHavoc: this is a stupid hack from Quake that makes your // lightning appear to come from your waist and cover less of your // view // in Quake this hack was applied to all players (causing the // infamous crotch-lightning), but in darkplaces and QuakeWorld it // only applies to your own lightning, and only in first person Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, start); } if (cl_beams_instantaimhack.integer) { vec3_t dir, localend; vec_t len; // LordHavoc: this updates the beam direction to match your // viewangles VectorSubtract(end, start, dir); len = VectorLength(dir); VectorNormalize(dir); VectorSet(localend, len, 0, 0); Matrix4x4_Transform(&r_refdef.view.matrix, localend, end); } } } void CL_RelinkBeams(void) { int i; beam_t *b; vec3_t dist, org, start, end; float d; entity_render_t *entrender; double yaw, pitch; float forward; matrix4x4_t tempmatrix; for (i = 0, b = cl.beams;i < cl.num_beams;i++, b++) { if (!b->model) continue; if (b->endtime < cl.time) { b->model = NULL; continue; } CL_Beam_CalculatePositions(b, start, end); if (b->lightning) { if (cl_beams_lightatend.integer && r_refdef.scene.numlights < MAX_DLIGHTS) { // FIXME: create a matrix from the beam start/end orientation vec3_t dlightcolor; VectorSet(dlightcolor, 0.3, 0.7, 1); Matrix4x4_CreateFromQuakeEntity(&tempmatrix, end[0], end[1], end[2], 0, 0, 0, 200); R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &tempmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 1, 0, 0, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE); r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights];r_refdef.scene.numlights++; } if (cl_beams_polygons.integer) continue; } // calculate pitch and yaw // (this is similar to the QuakeC builtin function vectoangles) VectorSubtract(end, start, dist); if (dist[1] == 0 && dist[0] == 0) { yaw = 0; if (dist[2] > 0) pitch = 90; else pitch = 270; } else { yaw = atan2(dist[1], dist[0]) * 180 / M_PI; if (yaw < 0) yaw += 360; forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]); pitch = atan2(dist[2], forward) * 180 / M_PI; if (pitch < 0) pitch += 360; } // add new entities for the lightning VectorCopy (start, org); d = VectorNormalizeLength(dist); while (d > 0) { entrender = CL_NewTempEntity (0); if (!entrender) return; //VectorCopy (org, ent->render.origin); entrender->model = b->model; //ent->render.effects = EF_FULLBRIGHT; //ent->render.angles[0] = pitch; //ent->render.angles[1] = yaw; //ent->render.angles[2] = rand()%360; Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1); CL_UpdateRenderEntity(entrender); VectorMA(org, 30, dist, org); d -= 30; } } while (cl.num_beams > 0 && !cl.beams[cl.num_beams - 1].model) cl.num_beams--; } static void CL_RelinkQWNails(void) { int i; vec_t *v; entity_render_t *entrender; for (i = 0;i < cl.qw_num_nails;i++) { v = cl.qw_nails[i]; // if we're drawing effects, get a new temp entity // (NewTempEntity adds it to the render entities list for us) if (!(entrender = CL_NewTempEntity(0))) continue; // normal stuff entrender->model = CL_GetModelByIndex(cl.qw_modelindex_spike); entrender->alpha = 1; VectorSet(entrender->colormod, 1, 1, 1); VectorSet(entrender->glowmod, 1, 1, 1); Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, v[0], v[1], v[2], v[3], v[4], v[5], 1); CL_UpdateRenderEntity(entrender); } } static void CL_LerpPlayer(float frac) { int i; cl.viewzoom = cl.mviewzoom[1] + frac * (cl.mviewzoom[0] - cl.mviewzoom[1]); for (i = 0;i < 3;i++) { cl.punchangle[i] = cl.mpunchangle[1][i] + frac * (cl.mpunchangle[0][i] - cl.mpunchangle[1][i]); cl.punchvector[i] = cl.mpunchvector[1][i] + frac * (cl.mpunchvector[0][i] - cl.mpunchvector[1][i]); cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]); } // interpolate the angles if playing a demo or spectating someone if (cls.demoplayback || cl.fixangle[0]) { for (i = 0;i < 3;i++) { float d = cl.mviewangles[0][i] - cl.mviewangles[1][i]; if (d > 180) d -= 360; else if (d < -180) d += 360; cl.viewangles[i] = cl.mviewangles[1][i] + frac * d; } } } void CSQC_RelinkAllEntities (int drawmask) { // link stuff CL_RelinkWorld(); CL_RelinkStaticEntities(); CL_RelinkBeams(); CL_RelinkEffects(); // link stuff if (drawmask & ENTMASK_ENGINE) { CL_RelinkNetworkEntities(); if (drawmask & ENTMASK_ENGINEVIEWMODELS) CL_LinkNetworkEntity(&cl.viewent); // link gun model CL_RelinkQWNails(); } // update view blend V_CalcViewBlend(); } /* =============== CL_UpdateWorld Update client game world for a new frame =============== */ void CL_UpdateWorld(void) { r_refdef.scene.extraupdate = !r_speeds.integer; r_refdef.scene.numentities = 0; r_refdef.scene.numlights = 0; r_refdef.view.matrix = identitymatrix; r_refdef.view.quality = 1; cl.num_brushmodel_entities = 0; if (cls.state == ca_connected && cls.signon == SIGNONS) { // prepare for a new frame CL_LerpPlayer(CL_LerpPoint()); CL_DecayLightFlashes(); CL_ClearTempEntities(); V_DriftPitch(); V_FadeViewFlashs(); // if prediction is enabled we have to update all the collidable // network entities before the prediction code can be run CL_UpdateNetworkCollisionEntities(); // now update the player prediction CL_ClientMovement_Replay(); // update the player entity (which may be predicted) CL_UpdateNetworkEntity(cl.entities + cl.viewentity, 32, true); // now update the view (which depends on that player entity) V_CalcRefdef(); // now update all the network entities and create particle trails // (some entities may depend on the view) CL_UpdateNetworkEntities(); // update the engine-based viewmodel CL_UpdateViewModel(); CL_RelinkLightFlashes(); CSQC_RelinkAllEntities(ENTMASK_ENGINE | ENTMASK_ENGINEVIEWMODELS); // decals, particles, and explosions will be updated during rneder } // Reki (May 4 2023): Run steam tick every render frame Steam_Tick(); r_refdef.scene.time = cl.time; } // LordHavoc: pausedemo command static void CL_PauseDemo_f (void) { cls.demopaused = !cls.demopaused; if (cls.demopaused) Con_Print("Demo paused\n"); else Con_Print("Demo unpaused\n"); } /* ====================== CL_Fog_f ====================== */ static void CL_Fog_f (void) { if (Cmd_Argc () == 1) { Con_Printf("\"fog\" is \"%f %f %f %f %f %f %f %f %f\"\n", r_refdef.fog_density, r_refdef.fog_red, r_refdef.fog_green, r_refdef.fog_blue, r_refdef.fog_alpha, r_refdef.fog_start, r_refdef.fog_end, r_refdef.fog_height, r_refdef.fog_fadedepth); return; } FOG_clear(); // so missing values get good defaults if(Cmd_Argc() > 1) r_refdef.fog_density = atof(Cmd_Argv(1)); if(Cmd_Argc() > 2) r_refdef.fog_red = atof(Cmd_Argv(2)); if(Cmd_Argc() > 3) r_refdef.fog_green = atof(Cmd_Argv(3)); if(Cmd_Argc() > 4) r_refdef.fog_blue = atof(Cmd_Argv(4)); if(Cmd_Argc() > 5) r_refdef.fog_alpha = atof(Cmd_Argv(5)); if(Cmd_Argc() > 6) r_refdef.fog_start = atof(Cmd_Argv(6)); if(Cmd_Argc() > 7) r_refdef.fog_end = atof(Cmd_Argv(7)); if(Cmd_Argc() > 8) r_refdef.fog_height = atof(Cmd_Argv(8)); if(Cmd_Argc() > 9) r_refdef.fog_fadedepth = atof(Cmd_Argv(9)); } /* ====================== CL_FogHeightTexture_f ====================== */ static void CL_Fog_HeightTexture_f (void) { if (Cmd_Argc () < 11) { Con_Printf("\"fog_heighttexture\" is \"%f %f %f %f %f %f %f %f %f %s\"\n", r_refdef.fog_density, r_refdef.fog_red, r_refdef.fog_green, r_refdef.fog_blue, r_refdef.fog_alpha, r_refdef.fog_start, r_refdef.fog_end, r_refdef.fog_height, r_refdef.fog_fadedepth, r_refdef.fog_height_texturename); return; } FOG_clear(); // so missing values get good defaults r_refdef.fog_density = atof(Cmd_Argv(1)); r_refdef.fog_red = atof(Cmd_Argv(2)); r_refdef.fog_green = atof(Cmd_Argv(3)); r_refdef.fog_blue = atof(Cmd_Argv(4)); r_refdef.fog_alpha = atof(Cmd_Argv(5)); r_refdef.fog_start = atof(Cmd_Argv(6)); r_refdef.fog_end = atof(Cmd_Argv(7)); r_refdef.fog_height = atof(Cmd_Argv(8)); r_refdef.fog_fadedepth = atof(Cmd_Argv(9)); strlcpy(r_refdef.fog_height_texturename, Cmd_Argv(10), sizeof(r_refdef.fog_height_texturename)); } /* ==================== CL_TimeRefresh_f For program optimization ==================== */ static void CL_TimeRefresh_f (void) { int i; double timestart, timedelta; r_refdef.scene.extraupdate = false; timestart = Sys_DirtyTime(); for (i = 0;i < 128;i++) { Matrix4x4_CreateFromQuakeEntity(&r_refdef.view.matrix, r_refdef.view.origin[0], r_refdef.view.origin[1], r_refdef.view.origin[2], 0, i / 128.0 * 360.0, 0, 1); r_refdef.view.quality = 1; CL_UpdateScreen(); } timedelta = Sys_DirtyTime() - timestart; Con_Printf("%f seconds (%f fps)\n", timedelta, 128/timedelta); } static void CL_AreaStats_f(void) { World_PrintAreaStats(&cl.world, "client"); } cl_locnode_t *CL_Locs_FindNearest(const vec3_t point) { int i; cl_locnode_t *loc; cl_locnode_t *best; vec3_t nearestpoint; vec_t dist, bestdist; best = NULL; bestdist = 0; for (loc = cl.locnodes;loc;loc = loc->next) { for (i = 0;i < 3;i++) nearestpoint[i] = bound(loc->mins[i], point[i], loc->maxs[i]); dist = VectorDistance2(nearestpoint, point); if (bestdist > dist || !best) { bestdist = dist; best = loc; if (bestdist < 1) break; } } return best; } void CL_Locs_FindLocationName(char *buffer, size_t buffersize, vec3_t point) { cl_locnode_t *loc; loc = CL_Locs_FindNearest(point); if (loc) strlcpy(buffer, loc->name, buffersize); else dpsnprintf(buffer, buffersize, "LOC=%.0f:%.0f:%.0f", point[0], point[1], point[2]); } static void CL_Locs_FreeNode(cl_locnode_t *node) { cl_locnode_t **pointer, **next; for (pointer = &cl.locnodes;*pointer;pointer = next) { next = &(*pointer)->next; if (*pointer == node) { *pointer = node->next; Mem_Free(node); return; } } Con_Printf("CL_Locs_FreeNode: no such node! (%p)\n", (void *)node); } static void CL_Locs_AddNode(vec3_t mins, vec3_t maxs, const char *name) { cl_locnode_t *node, **pointer; int namelen; if (!name) name = ""; namelen = strlen(name); node = (cl_locnode_t *) Mem_Alloc(cls.levelmempool, sizeof(cl_locnode_t) + namelen + 1); VectorSet(node->mins, min(mins[0], maxs[0]), min(mins[1], maxs[1]), min(mins[2], maxs[2])); VectorSet(node->maxs, max(mins[0], maxs[0]), max(mins[1], maxs[1]), max(mins[2], maxs[2])); node->name = (char *)(node + 1); memcpy(node->name, name, namelen); node->name[namelen] = 0; // link it into the tail of the list to preserve the order for (pointer = &cl.locnodes;*pointer;pointer = &(*pointer)->next) ; *pointer = node; } static void CL_Locs_Add_f(void) { vec3_t mins, maxs; if (Cmd_Argc() != 5 && Cmd_Argc() != 8) { Con_Printf("usage: %s x y z[ x y z] name\n", Cmd_Argv(0)); return; } mins[0] = atof(Cmd_Argv(1)); mins[1] = atof(Cmd_Argv(2)); mins[2] = atof(Cmd_Argv(3)); if (Cmd_Argc() == 8) { maxs[0] = atof(Cmd_Argv(4)); maxs[1] = atof(Cmd_Argv(5)); maxs[2] = atof(Cmd_Argv(6)); CL_Locs_AddNode(mins, maxs, Cmd_Argv(7)); } else CL_Locs_AddNode(mins, mins, Cmd_Argv(4)); } static void CL_Locs_RemoveNearest_f(void) { cl_locnode_t *loc; loc = CL_Locs_FindNearest(r_refdef.view.origin); if (loc) CL_Locs_FreeNode(loc); else Con_Printf("no loc point or box found for your location\n"); } static void CL_Locs_Clear_f(void) { while (cl.locnodes) CL_Locs_FreeNode(cl.locnodes); } static void CL_Locs_Save_f(void) { cl_locnode_t *loc; qfile_t *outfile; char locfilename[MAX_QPATH]; if (!cl.locnodes) { Con_Printf("No loc points/boxes exist!\n"); return; } if (cls.state != ca_connected || !cl.worldmodel) { Con_Printf("No level loaded!\n"); return; } dpsnprintf(locfilename, sizeof(locfilename), "%s.loc", cl.worldnamenoextension); outfile = FS_OpenRealFile(locfilename, "w", false); if (!outfile) return; // if any boxes are used then this is a proquake-format loc file, which // allows comments, so add some relevant information at the start for (loc = cl.locnodes;loc;loc = loc->next) if (!VectorCompare(loc->mins, loc->maxs)) break; if (loc) { FS_Printf(outfile, "// %s %s saved by %s\n// x,y,z,x,y,z,\"name\"\n\n", locfilename, Sys_TimeString("%Y-%m-%d"), engineversion); for (loc = cl.locnodes;loc;loc = loc->next) if (VectorCompare(loc->mins, loc->maxs)) break; if (loc) Con_Printf("Warning: writing loc file containing a mixture of qizmo-style points and proquake-style boxes may not work in qizmo or proquake!\n"); } for (loc = cl.locnodes;loc;loc = loc->next) { if (VectorCompare(loc->mins, loc->maxs)) { int len; const char *s; const char *in = loc->name; char name[MAX_INPUTLINE]; for (len = 0;len < (int)sizeof(name) - 1 && *in;) { if (*in == ' ') {s = "$loc_name_separator";in++;} else if (!strncmp(in, "SSG", 3)) {s = "$loc_name_ssg";in += 3;} else if (!strncmp(in, "NG", 2)) {s = "$loc_name_ng";in += 2;} else if (!strncmp(in, "SNG", 3)) {s = "$loc_name_sng";in += 3;} else if (!strncmp(in, "GL", 2)) {s = "$loc_name_gl";in += 2;} else if (!strncmp(in, "RL", 2)) {s = "$loc_name_rl";in += 2;} else if (!strncmp(in, "LG", 2)) {s = "$loc_name_lg";in += 2;} else if (!strncmp(in, "GA", 2)) {s = "$loc_name_ga";in += 2;} else if (!strncmp(in, "YA", 2)) {s = "$loc_name_ya";in += 2;} else if (!strncmp(in, "RA", 2)) {s = "$loc_name_ra";in += 2;} else if (!strncmp(in, "MEGA", 4)) {s = "$loc_name_mh";in += 4;} else s = NULL; if (s) { while (len < (int)sizeof(name) - 1 && *s) name[len++] = *s++; continue; } name[len++] = *in++; } name[len] = 0; FS_Printf(outfile, "%.0f %.0f %.0f %s\n", loc->mins[0]*8, loc->mins[1]*8, loc->mins[2]*8, name); } else FS_Printf(outfile, "%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,\"%s\"\n", loc->mins[0], loc->mins[1], loc->mins[2], loc->maxs[0], loc->maxs[1], loc->maxs[2], loc->name); } FS_Close(outfile); } void CL_Locs_Reload_f(void) { int i, linenumber, limit, len; const char *s; char *filedata, *text, *textend, *linestart, *linetext, *lineend; fs_offset_t filesize; vec3_t mins, maxs; char locfilename[MAX_QPATH]; char name[MAX_INPUTLINE]; if (cls.state != ca_connected || !cl.worldmodel) { Con_Printf("No level loaded!\n"); return; } CL_Locs_Clear_f(); // try maps/something.loc first (LordHavoc: where I think they should be) dpsnprintf(locfilename, sizeof(locfilename), "%s.loc", cl.worldnamenoextension); filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize); if (!filedata) { // try proquake name as well (LordHavoc: I hate path mangling) dpsnprintf(locfilename, sizeof(locfilename), "locs/%s.loc", cl.worldbasename); filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize); if (!filedata) return; } text = filedata; textend = filedata + filesize; for (linenumber = 1;text < textend;linenumber++) { linestart = text; for (;text < textend && *text != '\r' && *text != '\n';text++) ; lineend = text; if (text + 1 < textend && *text == '\r' && text[1] == '\n') text++; if (text < textend) text++; // trim trailing whitespace while (lineend > linestart && ISWHITESPACE(lineend[-1])) lineend--; // trim leading whitespace while (linestart < lineend && ISWHITESPACE(*linestart)) linestart++; // check if this is a comment if (linestart + 2 <= lineend && !strncmp(linestart, "//", 2)) continue; linetext = linestart; limit = 3; for (i = 0;i < limit;i++) { if (linetext >= lineend) break; // note: a missing number is interpreted as 0 if (i < 3) mins[i] = atof(linetext); else maxs[i - 3] = atof(linetext); // now advance past the number while (linetext < lineend && !ISWHITESPACE(*linetext) && *linetext != ',') linetext++; // advance through whitespace if (linetext < lineend) { if (*linetext == ',') { linetext++; limit = 6; // note: comma can be followed by whitespace } if (ISWHITESPACE(*linetext)) { // skip whitespace while (linetext < lineend && ISWHITESPACE(*linetext)) linetext++; } } } // if this is a quoted name, remove the quotes if (i == 6) { if (linetext >= lineend || *linetext != '"') continue; // proquake location names are always quoted lineend--; linetext++; len = min(lineend - linetext, (int)sizeof(name) - 1); memcpy(name, linetext, len); name[len] = 0; // add the box to the list CL_Locs_AddNode(mins, maxs, name); } // if a point was parsed, it needs to be scaled down by 8 (since // point-based loc files were invented by a proxy which dealt // directly with quake protocol coordinates, which are *8), turn // it into a box else if (i == 3) { // interpret silly fuhquake macros for (len = 0;len < (int)sizeof(name) - 1 && linetext < lineend;) { if (*linetext == '$') { if (linetext + 18 <= lineend && !strncmp(linetext, "$loc_name_separator", 19)) {s = " ";linetext += 19;} else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_ssg", 13)) {s = "SSG";linetext += 13;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ng", 12)) {s = "NG";linetext += 12;} else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_sng", 13)) {s = "SNG";linetext += 13;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_gl", 12)) {s = "GL";linetext += 12;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_rl", 12)) {s = "RL";linetext += 12;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_lg", 12)) {s = "LG";linetext += 12;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ga", 12)) {s = "GA";linetext += 12;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ya", 12)) {s = "YA";linetext += 12;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ra", 12)) {s = "RA";linetext += 12;} else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_mh", 12)) {s = "MEGA";linetext += 12;} else s = NULL; if (s) { while (len < (int)sizeof(name) - 1 && *s) name[len++] = *s++; continue; } } name[len++] = *linetext++; } name[len] = 0; // add the point to the list VectorScale(mins, (1.0 / 8.0), mins); CL_Locs_AddNode(mins, mins, name); } else continue; } } /* =========== CL_Shutdown =========== */ void CL_Shutdown (void) { CL_Screen_Shutdown(); CL_Particles_Shutdown(); CL_Parse_Shutdown(); Mem_FreePool (&cls.permanentmempool); Mem_FreePool (&cls.levelmempool); } /* ================= CL_Init ================= */ void CL_Init (void) { cls.levelmempool = Mem_AllocPool("client (per-level memory)", 0, NULL); cls.permanentmempool = Mem_AllocPool("client (long term memory)", 0, NULL); memset(&r_refdef, 0, sizeof(r_refdef)); // max entities sent to renderer per frame r_refdef.scene.maxentities = MAX_EDICTS + 256 + 512; r_refdef.scene.entities = (entity_render_t **)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t *) * r_refdef.scene.maxentities); // max temp entities r_refdef.scene.maxtempentities = MAX_TEMPENTITIES; r_refdef.scene.tempentities = (entity_render_t *)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t) * r_refdef.scene.maxtempentities); CL_InitInput (); // // register our commands // Cvar_RegisterVariable (&cl_upspeed); Cvar_RegisterVariable (&cl_forwardspeed); Cvar_RegisterVariable (&cl_backspeed); Cvar_RegisterVariable (&cl_sidespeed); Cvar_RegisterVariable (&cl_movespeedkey); Cvar_RegisterVariable (&cl_yawspeed); Cvar_RegisterVariable (&cl_pitchspeed); Cvar_RegisterVariable (&cl_anglespeedkey); Cvar_RegisterVariable (&cl_shownet); Cvar_RegisterVariable (&cl_nolerp); Cvar_RegisterVariable (&cl_lerpexcess); Cvar_RegisterVariable (&cl_lerpanim_maxdelta_server); Cvar_RegisterVariable (&cl_lerpanim_maxdelta_framegroups); Cvar_RegisterVariable (&cl_deathfade); Cvar_RegisterVariable (&lookspring); Cvar_RegisterVariable (&lookstrafe); Cvar_RegisterVariable (&sensitivity); Cvar_RegisterVariable (&freelook); Cvar_RegisterVariable (&m_pitch); Cvar_RegisterVariable (&m_yaw); Cvar_RegisterVariable (&m_forward); Cvar_RegisterVariable (&m_side); Cvar_RegisterVariable (&cl_itembobspeed); Cvar_RegisterVariable (&cl_itembobheight); Cmd_AddCommand ("entities", CL_PrintEntities_f, "print information on network entities known to client"); Cmd_AddCommand ("disconnect", CL_Disconnect_f, "disconnect from server (or disconnect all clients if running a server)"); Cmd_AddCommand ("record", CL_Record_f, "record a demo"); Cmd_AddCommand ("stop", CL_Stop_f, "stop recording or playing a demo"); Cmd_AddCommand ("playdemo", CL_PlayDemo_f, "watch a demo file"); Cmd_AddCommand ("timedemo", CL_TimeDemo_f, "play back a demo as fast as possible and save statistics to benchmark.log"); // Support Client-side Model Index List Cmd_AddCommand ("cl_modelindexlist", CL_ModelIndexList_f, "list information on all models in the client modelindex"); // Support Client-side Sound Index List Cmd_AddCommand ("cl_soundindexlist", CL_SoundIndexList_f, "list all sounds in the client soundindex"); Cvar_RegisterVariable (&cl_autodemo); Cvar_RegisterVariable (&cl_autodemo_nameformat); Cvar_RegisterVariable (&cl_autodemo_delete); Cmd_AddCommand ("fog", CL_Fog_f, "set global fog parameters (density red green blue [alpha [mindist [maxdist [top [fadedepth]]]]])"); Cmd_AddCommand ("fog_heighttexture", CL_Fog_HeightTexture_f, "set global fog parameters (density red green blue alpha mindist maxdist top depth textures/mapname/fogheight.tga)"); // LordHavoc: added pausedemo Cmd_AddCommand ("pausedemo", CL_PauseDemo_f, "pause demo playback (can also safely pause demo recording if using QUAKE, QUAKEDP or NEHAHRAMOVIE protocol, useful for making movies)"); Cmd_AddCommand ("cl_areastats", CL_AreaStats_f, "prints statistics on entity culling during collision traces"); Cvar_RegisterVariable(&r_draweffects); Cvar_RegisterVariable(&cl_explosions_alpha_start); Cvar_RegisterVariable(&cl_explosions_alpha_end); Cvar_RegisterVariable(&cl_explosions_size_start); Cvar_RegisterVariable(&cl_explosions_size_end); Cvar_RegisterVariable(&cl_explosions_lifetime); Cvar_RegisterVariable(&cl_stainmaps); Cvar_RegisterVariable(&cl_stainmaps_clearonload); Cvar_RegisterVariable(&cl_beams_polygons); Cvar_RegisterVariable(&cl_beams_quakepositionhack); Cvar_RegisterVariable(&cl_beams_instantaimhack); Cvar_RegisterVariable(&cl_beams_lightatend); Cvar_RegisterVariable(&cl_noplayershadow); Cvar_RegisterVariable(&cl_dlights_decayradius); Cvar_RegisterVariable(&cl_dlights_decaybrightness); Cvar_RegisterVariable(&cl_prydoncursor); Cvar_RegisterVariable(&cl_prydoncursor_notrace); Cvar_RegisterVariable(&cl_deathnoviewmodel); // for QW connections Cvar_RegisterVariable(&qport); Cvar_SetValueQuick(&qport, (rand() * RAND_MAX + rand()) & 0xffff); Cmd_AddCommand("timerefresh", CL_TimeRefresh_f, "turn quickly and print rendering statistcs"); Cvar_RegisterVariable(&cl_locs_enable); Cvar_RegisterVariable(&cl_locs_show); Cmd_AddCommand("locs_add", CL_Locs_Add_f, "add a point or box location (usage: x y z[ x y z] \"name\", if two sets of xyz are supplied it is a box, otherwise point)"); Cmd_AddCommand("locs_removenearest", CL_Locs_RemoveNearest_f, "remove the nearest point or box (note: you need to be very near a box to remove it)"); Cmd_AddCommand("locs_clear", CL_Locs_Clear_f, "remove all loc points/boxes"); Cmd_AddCommand("locs_reload", CL_Locs_Reload_f, "reload .loc file for this map"); Cmd_AddCommand("locs_save", CL_Locs_Save_f, "save .loc file for this map containing currently defined points and boxes"); CL_Parse_Init(); CL_Particles_Init(); CL_Screen_Init(); CL_Video_Init(); Steam_Startup(); }
0
0.908515
1
0.908515
game-dev
MEDIA
0.523872
game-dev,graphics-rendering
0.861507
1
0.861507
Sparker95/Vindicta
1,349
src/GameMode/LocationGameModeData.sqf
#include "common.hpp" /* Class: GameMode.LocationGameModeData Base class of objects assigned as Location.gameModeData */ #define OOP_CLASS_NAME LocationGameModeData CLASS("LocationGameModeData", "MessageReceiverEx") VARIABLE_ATTR("location", [ATTR_SAVE]); METHOD(new) params [P_THISOBJECT, P_OOP_OBJECT("_location")]; T_SETV_PUBLIC("location", _location); ENDMETHOD; // Meant to do processing and enable/disable respawn at this place based on different rules public virtual METHOD(updatePlayerRespawn) params [P_THISOBJECT]; ENDMETHOD; public override METHOD(getMessageLoop) gMessageLoopGameMode ENDMETHOD; public virtual METHOD(getRecruitCount) // For common interface params [P_THISOBJECT, P_ARRAY("_cities")]; 0 ENDMETHOD; // Returns intel entries for display on the client map UI public virtual METHOD(getMapInfoEntries) params [P_THISOBJECT]; [] ENDMETHOD; // Overrides the location name public virtual METHOD(getDisplayName) params [P_THISOBJECT]; private _loc = T_GETV("location"); CALLM0(_loc, "getName") ENDMETHOD; // STORAGE public override METHOD(postDeserialize) params [P_THISOBJECT, P_OOP_OBJECT("_storage")]; // Call method of all base classes CALLCM("MessageReceiverEx", _thisObject, "postDeserialize", [_storage]); T_PUBLIC_VAR("location"); true ENDMETHOD; ENDCLASS;
0
0.720463
1
0.720463
game-dev
MEDIA
0.753139
game-dev
0.535349
1
0.535349
fuyouawa/MMORPG
5,880
MMORPG/Assets/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 using System; using System.Reflection; using UnityEngine; using DG.Tweening.Core; using DG.Tweening.Plugins.Core.PathCore; using DG.Tweening.Plugins.Options; #pragma warning disable 1591 namespace DG.Tweening { /// <summary> /// Utility functions that deal with available Modules. /// Modules defines: /// - DOTAUDIO /// - DOTPHYSICS /// - DOTPHYSICS2D /// - DOTSPRITE /// - DOTUI /// Extra defines set and used for implementation of external assets: /// - DOTWEEN_TMP ► TextMesh Pro /// - DOTWEEN_TK2D ► 2D Toolkit /// </summary> public static class DOTweenModuleUtils { static bool _initialized; #region Reflection /// <summary> /// Called via Reflection by DOTweenComponent on Awake /// </summary> #if UNITY_2018_1_OR_NEWER [UnityEngine.Scripting.Preserve] #endif public static void Init() { if (_initialized) return; _initialized = true; DOTweenExternalCommand.SetOrientationOnPath += Physics.SetOrientationOnPath; #if UNITY_EDITOR #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1 UnityEditor.EditorApplication.playmodeStateChanged += PlaymodeStateChanged; #else UnityEditor.EditorApplication.playModeStateChanged += PlaymodeStateChanged; #endif #endif } #if UNITY_2018_1_OR_NEWER #pragma warning disable [UnityEngine.Scripting.Preserve] // Just used to preserve methods when building, never called static void Preserver() { Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); MethodInfo mi = typeof(MonoBehaviour).GetMethod("Stub"); } #pragma warning restore #endif #endregion #if UNITY_EDITOR // Fires OnApplicationPause in DOTweenComponent even when Editor is paused (otherwise it's only fired at runtime) #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1 static void PlaymodeStateChanged() #else static void PlaymodeStateChanged(UnityEditor.PlayModeStateChange state) #endif { if (DOTween.instance == null) return; DOTween.instance.OnApplicationPause(UnityEditor.EditorApplication.isPaused); } #endif // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ public static class Physics { // Called via DOTweenExternalCommand callback public static void SetOrientationOnPath(PathOptions options, Tween t, Quaternion newRot, Transform trans) { #if true // PHYSICS_MARKER if (options.isRigidbody) ((Rigidbody)t.target).rotation = newRot; else trans.rotation = newRot; #else trans.rotation = newRot; #endif } // Returns FALSE if the DOTween's Physics2D Module is disabled, or if there's no Rigidbody2D attached public static bool HasRigidbody2D(Component target) { #if true // PHYSICS2D_MARKER return target.GetComponent<Rigidbody2D>() != null; #else return false; #endif } #region Called via Reflection // Called via Reflection by DOTweenPathInspector // Returns FALSE if the DOTween's Physics Module is disabled, or if there's no rigidbody attached #if UNITY_2018_1_OR_NEWER [UnityEngine.Scripting.Preserve] #endif public static bool HasRigidbody(Component target) { #if true // PHYSICS_MARKER return target.GetComponent<Rigidbody>() != null; #else return false; #endif } // Called via Reflection by DOTweenPath #if UNITY_2018_1_OR_NEWER [UnityEngine.Scripting.Preserve] #endif public static TweenerCore<Vector3, Path, PathOptions> CreateDOTweenPathTween( MonoBehaviour target, bool tweenRigidbody, bool isLocal, Path path, float duration, PathMode pathMode ){ TweenerCore<Vector3, Path, PathOptions> t = null; bool rBodyFoundAndTweened = false; #if true // PHYSICS_MARKER if (tweenRigidbody) { Rigidbody rBody = target.GetComponent<Rigidbody>(); if (rBody != null) { rBodyFoundAndTweened = true; t = isLocal ? rBody.DOLocalPath(path, duration, pathMode) : rBody.DOPath(path, duration, pathMode); } } #endif #if true // PHYSICS2D_MARKER if (!rBodyFoundAndTweened && tweenRigidbody) { Rigidbody2D rBody2D = target.GetComponent<Rigidbody2D>(); if (rBody2D != null) { rBodyFoundAndTweened = true; t = isLocal ? rBody2D.DOLocalPath(path, duration, pathMode) : rBody2D.DOPath(path, duration, pathMode); } } #endif if (!rBodyFoundAndTweened) { t = isLocal ? target.transform.DOLocalPath(path, duration, pathMode) : target.transform.DOPath(path, duration, pathMode); } return t; } #endregion } } }
0
0.85663
1
0.85663
game-dev
MEDIA
0.969353
game-dev
0.932024
1
0.932024
theCapypara/GMnet-ENGINE
1,163
GMnetENGINE.gmx/scripts/htme_doMapsAndLists.gml
///htme_doGlobalSync(); /* ** Description: ** PRIVATE "METHOD" OF obj_htme! That means this script MUST be called with obj_htme! ** ** Draw debug information about lists and maps: ** * Currently displays number of all lists and maps. ** ** Usage: ** <See above> ** ** Arguments: ** <None> ** ** Returns: ** <Nothing> ** */ htme_doMain(); draw_set_halign(fa_left); //HEADER var headstr = "MAPS AND LISTS#High numbers indicate memory leaks.#========#"; var offs = self.dbg_top+20+string_height(headstr)+10; var countlist=0; var countmap=0; for (var i=0; i<5000; i+=1) { if (ds_exists(i,ds_type_list)) { countlist+=1; } if (ds_exists(i,ds_type_map)) { countmap+=1; } } var str = "Current list count: " + string(countlist) + "#--------#" + "Current map count: " + string(countmap); draw_text(self.dbg_left+20,offs,str); offs = offs + string_height(str); draw_rectangle_colour(self.dbg_left,self.dbg_top,self.dbg_left+20+string_width(headstr)+20,self.dbg_top+20+string_height(headstr)+5,c_black,c_black,c_black,c_black,false); draw_text(self.dbg_left+20,self.dbg_top+20,headstr);
0
0.653794
1
0.653794
game-dev
MEDIA
0.606313
game-dev
0.911538
1
0.911538
alliedmodders/hl2sdk
36,859
utils/vbsp/portals.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "vbsp.h" #include "utlvector.h" #include "mathlib/vmatrix.h" #include "iscratchpad3d.h" #include "csg.h" #include "fmtstr.h" int c_active_portals; int c_peak_portals; int c_boundary; int c_boundary_sides; /* =========== AllocPortal =========== */ portal_t *AllocPortal (void) { static int s_PortalCount = 0; portal_t *p; if (numthreads == 1) c_active_portals++; if (c_active_portals > c_peak_portals) c_peak_portals = c_active_portals; p = (portal_t*)malloc (sizeof(portal_t)); memset (p, 0, sizeof(portal_t)); p->id = s_PortalCount; ++s_PortalCount; return p; } void FreePortal (portal_t *p) { if (p->winding) FreeWinding (p->winding); if (numthreads == 1) c_active_portals--; free (p); } //============================================================== /* ============== VisibleContents Returns the single content bit of the strongest visible content present ============== */ int VisibleContents (int contents) { int i; for (i=1 ; i<=LAST_VISIBLE_CONTENTS ; i<<=1) { if (contents & i ) { return i; } } return 0; } /* =============== ClusterContents =============== */ int ClusterContents (node_t *node) { int c1, c2, c; if (node->planenum == PLANENUM_LEAF) return node->contents; c1 = ClusterContents(node->children[0]); c2 = ClusterContents(node->children[1]); c = c1|c2; // a cluster may include some solid detail areas, but // still be seen into if ( ! (c1&CONTENTS_SOLID) || ! (c2&CONTENTS_SOLID) ) c &= ~CONTENTS_SOLID; return c; } /* ============= Portal_VisFlood Returns true if the portal is empty or translucent, allowing the PVS calculation to see through it. The nodes on either side of the portal may actually be clusters, not leafs, so all contents should be ored together ============= */ qboolean Portal_VisFlood (portal_t *p) { int c1, c2; if (!p->onnode) return false; // to global outsideleaf c1 = ClusterContents(p->nodes[0]); c2 = ClusterContents(p->nodes[1]); if (!VisibleContents (c1^c2)) return true; if (c1 & (CONTENTS_TRANSLUCENT|CONTENTS_DETAIL)) c1 = 0; if (c2 & (CONTENTS_TRANSLUCENT|CONTENTS_DETAIL)) c2 = 0; if ( (c1|c2) & CONTENTS_SOLID ) return false; // can't see through solid if (! (c1 ^ c2)) return true; // identical on both sides if (!VisibleContents (c1^c2)) return true; return false; } /* =============== Portal_EntityFlood The entity flood determines which areas are "outside" on the map, which are then filled in. Flowing from side s to side !s =============== */ qboolean Portal_EntityFlood (portal_t *p, int s) { if (p->nodes[0]->planenum != PLANENUM_LEAF || p->nodes[1]->planenum != PLANENUM_LEAF) Error ("Portal_EntityFlood: not a leaf"); // can never cross to a solid if ( (p->nodes[0]->contents & CONTENTS_SOLID) || (p->nodes[1]->contents & CONTENTS_SOLID) ) return false; // can flood through everything else return true; } qboolean Portal_AreaLeakFlood (portal_t *p, int s) { if ( !Portal_EntityFlood( p, s ) ) return false; // can never cross through areaportal if ( (p->nodes[0]->contents & CONTENTS_AREAPORTAL) || (p->nodes[1]->contents & CONTENTS_AREAPORTAL) ) return false; // can flood through everything else return true; } //============================================================================= int c_tinyportals; /* ============= AddPortalToNodes ============= */ void AddPortalToNodes (portal_t *p, node_t *front, node_t *back) { if (p->nodes[0] || p->nodes[1]) Error ("AddPortalToNode: allready included"); p->nodes[0] = front; p->next[0] = front->portals; front->portals = p; p->nodes[1] = back; p->next[1] = back->portals; back->portals = p; } /* ============= RemovePortalFromNode ============= */ void RemovePortalFromNode (portal_t *portal, node_t *l) { portal_t **pp, *t; // remove reference to the current portal pp = &l->portals; while (1) { t = *pp; if (!t) Error ("RemovePortalFromNode: portal not in leaf"); if ( t == portal ) break; if (t->nodes[0] == l) pp = &t->next[0]; else if (t->nodes[1] == l) pp = &t->next[1]; else Error ("RemovePortalFromNode: portal not bounding leaf"); } if (portal->nodes[0] == l) { *pp = portal->next[0]; portal->nodes[0] = NULL; } else if (portal->nodes[1] == l) { *pp = portal->next[1]; portal->nodes[1] = NULL; } } //============================================================================ void PrintPortal (portal_t *p) { int i; winding_t *w; w = p->winding; for (i=0 ; i<w->numpoints ; i++) Msg ("(%5.0f,%5.0f,%5.0f)\n",w->p[i][0] , w->p[i][1], w->p[i][2]); } // because of water areaportals support, the areaportal may not be the only brush on this node bspbrush_t *AreaportalBrushForNode( node_t *node ) { bspbrush_t *b = node->brushlist; while ( b && !(b->original->contents & CONTENTS_AREAPORTAL) ) { b = b->next; } Assert( b->original->entitynum != 0 ); return b; } /* ================ MakeHeadnodePortals The created portals will face the global outside_node ================ */ // buffer space around sides of nodes #define SIDESPACE 8 void MakeHeadnodePortals (tree_t *tree) { Vector bounds[2]; int i, j, n; portal_t *p, *portals[6]; plane_t bplanes[6], *pl; node_t *node; node = tree->headnode; // pad with some space so there will never be null volume leafs for (i=0 ; i<3 ; i++) { bounds[0][i] = tree->mins[i] - SIDESPACE; bounds[1][i] = tree->maxs[i] + SIDESPACE; } tree->outside_node.planenum = PLANENUM_LEAF; tree->outside_node.brushlist = NULL; tree->outside_node.portals = NULL; tree->outside_node.contents = 0; for (i=0 ; i<3 ; i++) for (j=0 ; j<2 ; j++) { n = j*3 + i; p = AllocPortal (); portals[n] = p; pl = &bplanes[n]; memset (pl, 0, sizeof(*pl)); if (j) { pl->normal[i] = -1; pl->dist = -bounds[j][i]; } else { pl->normal[i] = 1; pl->dist = bounds[j][i]; } p->plane = *pl; p->winding = BaseWindingForPlane (pl->normal, pl->dist); AddPortalToNodes (p, node, &tree->outside_node); } // clip the basewindings by all the other planes for (i=0 ; i<6 ; i++) { for (j=0 ; j<6 ; j++) { if (j == i) continue; ChopWindingInPlace (&portals[i]->winding, bplanes[j].normal, bplanes[j].dist, ON_EPSILON); } } } //=================================================== /* ================ BaseWindingForNode ================ */ #define BASE_WINDING_EPSILON 0.001 #define SPLIT_WINDING_EPSILON 0.001 winding_t *BaseWindingForNode (node_t *node) { winding_t *w; node_t *n; plane_t *plane; Vector normal; vec_t dist; w = BaseWindingForPlane (g_MainMap->mapplanes[node->planenum].normal, g_MainMap->mapplanes[node->planenum].dist); // clip by all the parents for (n=node->parent ; n && w ; ) { plane = &g_MainMap->mapplanes[n->planenum]; if (n->children[0] == node) { // take front ChopWindingInPlace (&w, plane->normal, plane->dist, BASE_WINDING_EPSILON); } else { // take back VectorSubtract (vec3_origin, plane->normal, normal); dist = -plane->dist; ChopWindingInPlace (&w, normal, dist, BASE_WINDING_EPSILON); } node = n; n = n->parent; } return w; } //============================================================ /* ================== MakeNodePortal create the new portal by taking the full plane winding for the cutting plane and clipping it by all of parents of this node ================== */ void MakeNodePortal (node_t *node) { portal_t *new_portal, *p; winding_t *w; Vector normal; float dist = 0.0f; int side = 0; w = BaseWindingForNode (node); // clip the portal by all the other portals in the node for (p = node->portals ; p && w; p = p->next[side]) { if (p->nodes[0] == node) { side = 0; VectorCopy (p->plane.normal, normal); dist = p->plane.dist; } else if (p->nodes[1] == node) { side = 1; VectorSubtract (vec3_origin, p->plane.normal, normal); dist = -p->plane.dist; } else { Error ("CutNodePortals_r: mislinked portal"); } ChopWindingInPlace (&w, normal, dist, 0.1); } if (!w) { return; } if (WindingIsTiny (w)) { c_tinyportals++; FreeWinding (w); return; } new_portal = AllocPortal (); new_portal->plane = g_MainMap->mapplanes[node->planenum]; new_portal->onnode = node; new_portal->winding = w; AddPortalToNodes (new_portal, node->children[0], node->children[1]); } /* ============== SplitNodePortals Move or split the portals that bound node so that the node's children have portals instead of node. ============== */ void SplitNodePortals (node_t *node) { portal_t *p, *next_portal, *new_portal; node_t *f, *b, *other_node; int side = 0; plane_t *plane; winding_t *frontwinding, *backwinding; plane = &g_MainMap->mapplanes[node->planenum]; f = node->children[0]; b = node->children[1]; for (p = node->portals ; p ; p = next_portal) { if (p->nodes[0] == node) side = 0; else if (p->nodes[1] == node) side = 1; else Error ("CutNodePortals_r: mislinked portal"); next_portal = p->next[side]; other_node = p->nodes[!side]; RemovePortalFromNode (p, p->nodes[0]); RemovePortalFromNode (p, p->nodes[1]); // // cut the portal into two portals, one on each side of the cut plane // ClipWindingEpsilon (p->winding, plane->normal, plane->dist, SPLIT_WINDING_EPSILON, &frontwinding, &backwinding); if (frontwinding && WindingIsTiny(frontwinding)) { FreeWinding (frontwinding); frontwinding = NULL; c_tinyportals++; } if (backwinding && WindingIsTiny(backwinding)) { FreeWinding (backwinding); backwinding = NULL; c_tinyportals++; } if (!frontwinding && !backwinding) { // tiny windings on both sides continue; } if (!frontwinding) { FreeWinding (backwinding); if (side == 0) AddPortalToNodes (p, b, other_node); else AddPortalToNodes (p, other_node, b); continue; } if (!backwinding) { FreeWinding (frontwinding); if (side == 0) AddPortalToNodes (p, f, other_node); else AddPortalToNodes (p, other_node, f); continue; } // the winding is split new_portal = AllocPortal (); *new_portal = *p; new_portal->winding = backwinding; FreeWinding (p->winding); p->winding = frontwinding; if (side == 0) { AddPortalToNodes (p, f, other_node); AddPortalToNodes (new_portal, b, other_node); } else { AddPortalToNodes (p, other_node, f); AddPortalToNodes (new_portal, other_node, b); } } node->portals = NULL; } /* ================ CalcNodeBounds ================ */ void CalcNodeBounds (node_t *node) { portal_t *p; int s; int i; // calc mins/maxs for both leafs and nodes ClearBounds (node->mins, node->maxs); for (p = node->portals ; p ; p = p->next[s]) { s = (p->nodes[1] == node); for (i=0 ; i<p->winding->numpoints ; i++) AddPointToBounds (p->winding->p[i], node->mins, node->maxs); } } /* ================== MakeTreePortals_r ================== */ void MakeTreePortals_r (node_t *node) { int i; CalcNodeBounds (node); if (node->mins[0] >= node->maxs[0]) { Warning("WARNING: node without a volume\n"); } for (i=0 ; i<3 ; i++) { if (node->mins[i] < (MIN_COORD_INTEGER-SIDESPACE) || node->maxs[i] > (MAX_COORD_INTEGER+SIDESPACE)) { const char *pMatName = "<NO BRUSH>"; // split by brush side if ( node->side ) { texinfo_t *pTexInfo = &texinfo[node->side->texinfo]; dtexdata_t *pTexData = GetTexData( pTexInfo->texdata ); pMatName = TexDataStringTable_GetString( pTexData->nameStringTableID ); } Vector point = node->portals->winding->p[0]; Warning("WARNING: BSP node with unbounded volume (material: %s, near %s)\n", pMatName, VecToString(point) ); break; } } if (node->planenum == PLANENUM_LEAF) return; MakeNodePortal (node); SplitNodePortals (node); MakeTreePortals_r (node->children[0]); MakeTreePortals_r (node->children[1]); } /* ================== MakeTreePortals ================== */ void MakeTreePortals (tree_t *tree) { MakeHeadnodePortals (tree); MakeTreePortals_r (tree->headnode); } /* ========================================================= FLOOD ENTITIES ========================================================= */ //----------------------------------------------------------------------------- // Purpose: Floods outward from the given node, marking visited nodes with // the number of hops from a node with an entity. If we ever mark // the outside_node for this tree, we've leaked. // Input : node - // dist - //----------------------------------------------------------------------------- void FloodPortals_r (node_t *node, int dist) { portal_t *p; int s; node->occupied = dist; for (p=node->portals ; p ; p = p->next[s]) { s = (p->nodes[1] == node); // Skip nodes that have already been marked. if (p->nodes[!s]->occupied) continue; // Skip portals that lead to or from nodes with solid contents. if (!Portal_EntityFlood (p, s)) continue; FloodPortals_r (p->nodes[!s], dist+1); } } void FloodAreaLeak_r( node_t *node, int dist ) { portal_t *p; int s; node->occupied = dist; for (p=node->portals ; p ; p = p->next[s]) { s = (p->nodes[1] == node); if (p->nodes[!s]->occupied) continue; if (!Portal_AreaLeakFlood (p, s)) continue; FloodAreaLeak_r( p->nodes[!s], dist+1 ); } } void ClearOccupied_r( node_t *headnode ) { if ( !headnode ) return; headnode->occupied = 0; ClearOccupied_r( headnode->children[0] ); ClearOccupied_r( headnode->children[1] ); } void FloodAreaLeak( node_t *headnode, node_t *pFirstSide ) { ClearOccupied_r( headnode ); FloodAreaLeak_r( pFirstSide, 2 ); } //----------------------------------------------------------------------------- // Purpose: For the given entity at the given origin, finds the leaf node in the // BSP tree that the entity occupies. // // We then flood outward from that leaf to see if the entity leaks. // Input : headnode - // origin - // occupant - // Output : Returns false if the entity is in solid, true if it is not. //----------------------------------------------------------------------------- qboolean PlaceOccupant (node_t *headnode, Vector& origin, entity_t *occupant) { node_t *node; vec_t d; plane_t *plane; // find the leaf to start in node = headnode; while (node->planenum != PLANENUM_LEAF) { plane = &g_MainMap->mapplanes[node->planenum]; d = DotProduct (origin, plane->normal) - plane->dist; if (d >= 0) node = node->children[0]; else node = node->children[1]; } if (node->contents == CONTENTS_SOLID) return false; node->occupant = occupant; // Flood outward from here to see if this entity leaks. FloodPortals_r (node, 1); return true; } /* ============= FloodEntities Marks all nodes that can be reached by entites ============= */ qboolean FloodEntities (tree_t *tree) { int i; Vector origin; char *cl; qboolean inside; node_t *headnode; headnode = tree->headnode; qprintf ("--- FloodEntities ---\n"); inside = false; tree->outside_node.occupied = 0; for (i=1 ; i<num_entities ; i++) { GetVectorForKey (&entities[i], "origin", origin); if (VectorCompare(origin, vec3_origin)) continue; cl = ValueForKey (&entities[i], "classname"); origin[2] += 1; // so objects on floor are ok // nudge playerstart around if needed so clipping hulls allways // have a valid point if (!strcmp (cl, "info_player_start")) { int x, y; for (x=-16 ; x<=16 ; x += 16) { for (y=-16 ; y<=16 ; y += 16) { origin[0] += x; origin[1] += y; if (PlaceOccupant (headnode, origin, &entities[i])) { inside = true; goto gotit; } origin[0] -= x; origin[1] -= y; } } gotit: ; } else { if (PlaceOccupant (headnode, origin, &entities[i])) inside = true; } } if (!inside) { qprintf ("no entities in open -- no filling\n"); } if (tree->outside_node.occupied) { qprintf ("entity reached from outside -- no filling\n" ); } return (qboolean)(inside && !tree->outside_node.occupied); } /* ========================================================= FLOOD AREAS ========================================================= */ int c_areas; bool IsAreaportalNode( node_t *node ) { return ( node->contents & CONTENTS_AREAPORTAL ) ? true : false; } /* ============= FloodAreas_r ============= */ void FloodAreas_r (node_t *node, portal_t *pSeeThrough) { portal_t *p; int s; bspbrush_t *b; entity_t *e; if ( IsAreaportalNode(node) ) { // this node is part of an area portal b = AreaportalBrushForNode( node ); e = &entities[b->original->entitynum]; // if the current area has allready touched this // portal, we are done if (e->portalareas[0] == c_areas || e->portalareas[1] == c_areas) return; // note the current area as bounding the portal if (e->portalareas[1]) { Warning("WARNING: areaportal entity %i (brush %i) touches > 2 areas\n", b->original->entitynum, b->original->id ); return; } if (e->portalareas[0]) { e->portalareas[1] = c_areas; e->m_pPortalsLeadingIntoAreas[1] = pSeeThrough; } else { e->portalareas[0] = c_areas; e->m_pPortalsLeadingIntoAreas[0] = pSeeThrough; } return; } if (node->area) return; // allready got it node->area = c_areas; for (p=node->portals ; p ; p = p->next[s]) { s = (p->nodes[1] == node); #if 0 if (p->nodes[!s]->occupied) continue; #endif if (!Portal_EntityFlood (p, s)) continue; FloodAreas_r (p->nodes[!s], p); } } /* ============= FindAreas_r Just decend the tree, and for each node that hasn't had an area set, flood fill out from there ============= */ void FindAreas_r (node_t *node) { if (node->planenum != PLANENUM_LEAF) { FindAreas_r (node->children[0]); FindAreas_r (node->children[1]); return; } if (node->area) return; // allready got it if (node->contents & CONTENTS_SOLID) return; if (!node->occupied) return; // not reachable by entities // area portals are allways only flooded into, never // out of if (IsAreaportalNode(node)) return; c_areas++; FloodAreas_r (node, NULL); } void ReportAreaportalLeak( tree_t *tree, node_t *node ) { portal_t *p, *pStart = NULL; int s; // Find a portal out of this areaportal into empty space for (p=node->portals ; p ; p = p->next[s]) { s = (p->nodes[1] == node); if ( !Portal_EntityFlood( p, !s ) ) continue; if ( p->nodes[!s]->contents & CONTENTS_AREAPORTAL ) continue; pStart = p; break; } if ( pStart ) { s = pStart->nodes[0] == node; Assert(!(pStart->nodes[s]->contents & CONTENTS_AREAPORTAL) ); // flood fill the area outside this areaportal brush FloodAreaLeak( tree->headnode, pStart->nodes[s] ); // find the portal into the longest path around the portal portal_t *pBest = NULL; int bestDist = 0; for (p=node->portals ; p ; p = p->next[s]) { if ( p == pStart ) continue; s = (p->nodes[1] == node); if ( p->nodes[!s]->occupied > bestDist ) { pBest = p; bestDist = p->nodes[!s]->occupied; } } if ( pBest ) { s = (pBest->nodes[0] == node); // write the linefile that goes from pBest to pStart AreaportalLeakFile( tree, pStart, pBest, pBest->nodes[s] ); } } } /* ============= SetAreaPortalAreas_r Just decend the tree, and for each node that hasn't had an area set, flood fill out from there ============= */ void SetAreaPortalAreas_r (tree_t *tree, node_t *node) { bspbrush_t *b; entity_t *e; if (node->planenum != PLANENUM_LEAF) { SetAreaPortalAreas_r (tree, node->children[0]); SetAreaPortalAreas_r (tree, node->children[1]); return; } if (IsAreaportalNode(node)) { if (node->area) return; // already set b = AreaportalBrushForNode( node ); e = &entities[b->original->entitynum]; node->area = e->portalareas[0]; if (!e->portalareas[1]) { ReportAreaportalLeak( tree, node ); Warning("\nBrush %i: areaportal brush doesn't touch two areas\n", b->original->id); return; } } } // Return a positive value between 0 and 2*PI telling the angle distance // from flBaseAngle to flTestAngle. float AngleOffset( float flBaseAngle, float flTestAngle ) { while( flTestAngle > flBaseAngle ) flTestAngle -= 2 * M_PI; return fmod( flBaseAngle - flTestAngle, (float) (2 * M_PI) ); } int FindUniquePoints( const Vector2D *pPoints, int nPoints, int *indexMap, int nMaxIndexMapPoints, float flTolerance ) { float flToleranceSqr = flTolerance * flTolerance; // This could be slightly more efficient. int nUniquePoints = 0; for ( int i=0; i < nPoints; i++ ) { int j; for ( j=0; j < nUniquePoints; j++ ) { if ( pPoints[i].DistToSqr( pPoints[indexMap[j]] ) < flToleranceSqr ) break; } if ( j == nUniquePoints ) { if ( nUniquePoints >= nMaxIndexMapPoints ) Error( "FindUniquePoints: overflowed unique point list (size %d).", nMaxIndexMapPoints ); indexMap[nUniquePoints++] = i; } } return nUniquePoints; } // Build a 2D convex hull of the set of points. // This essentially giftwraps the points as it walks around the perimeter. int Convex2D( Vector2D const *pPoints, int nPoints, int *indices, int nMaxIndices ) { int nIndices = 0; bool touched[512]; int indexMap[512]; if( nPoints == 0 ) return 0; // If we don't collapse the points into a unique set, we can loop around forever // and max out nMaxIndices. nPoints = FindUniquePoints( pPoints, nPoints, indexMap, ARRAYSIZE( indexMap ), 0.1f ); memset( touched, 0, nPoints*sizeof(touched[0]) ); // Find the (lower) left side. int i; int iBest = 0; for( i=1; i < nPoints; i++ ) { if( pPoints[indexMap[i]].x < pPoints[indexMap[iBest]].x || (pPoints[indexMap[i]].x == pPoints[indexMap[iBest]].x && pPoints[indexMap[i]].y < pPoints[indexMap[iBest]].y) ) { iBest = i; } } touched[iBest] = true; indices[0] = indexMap[iBest]; nIndices = 1; Vector2D curEdge( 0, 1 ); // Wind around clockwise. while( 1 ) { Vector2D const *pStartPoint = &pPoints[ indices[nIndices-1] ]; float flEdgeAngle = atan2( curEdge.y, curEdge.x ); int iMinAngle = -1; float flMinAngle = 5000; for( i=0; i < nPoints; i++ ) { Vector2D vTo = pPoints[indexMap[i]] - *pStartPoint; float flDistToSqr = vTo.LengthSqr(); if ( flDistToSqr <= 0.1f ) continue; // Get the angle from the edge to this point. float flAngle = atan2( vTo.y, vTo.x ); flAngle = AngleOffset( flEdgeAngle, flAngle ); if( fabs( flAngle - flMinAngle ) < 0.00001f ) { float flDistToTestSqr = pStartPoint->DistToSqr( pPoints[iMinAngle] ); // If the angle is the same, pick the point farthest away. // unless the current one is closing the face loop if ( iMinAngle != indices[0] && flDistToSqr > flDistToTestSqr ) { flMinAngle = flAngle; iMinAngle = indexMap[i]; } } else if( flAngle < flMinAngle ) { flMinAngle = flAngle; iMinAngle = indexMap[i]; } } if( iMinAngle == -1 ) { // Couldn't find a point? Assert( false ); break; } else if( iMinAngle == indices[0] ) { // Finished. break; } else { // Add this point. if( nIndices >= nMaxIndices ) break; for ( int jj = 0; jj < nIndices; jj++ ) { // if this assert hits, this routine is broken and is generating a spiral // rather than a closed polygon - basically an edge overlap of some kind Assert(indices[jj] != iMinAngle ); } indices[nIndices] = iMinAngle; ++nIndices; } curEdge = pPoints[indices[nIndices-1]] - pPoints[indices[nIndices-2]]; } return nIndices; } void FindPortalsLeadingToArea_R( node_t *pHeadNode, int iSrcArea, int iDestArea, plane_t *pPlane, CUtlVector<portal_t*> &portals ) { if (pHeadNode->planenum != PLANENUM_LEAF) { FindPortalsLeadingToArea_R( pHeadNode->children[0], iSrcArea, iDestArea, pPlane, portals ); FindPortalsLeadingToArea_R( pHeadNode->children[1], iSrcArea, iDestArea, pPlane, portals ); return; } // Ok.. this is a leaf, check its portals. int s; for( portal_t *p = pHeadNode->portals; p ;p = p->next[!s] ) { s = (p->nodes[0] == pHeadNode); if( !p->nodes[0]->occupied || !p->nodes[1]->occupied ) continue; if( p->nodes[1]->area == iDestArea && p->nodes[0]->area == iSrcArea || p->nodes[0]->area == iDestArea && p->nodes[1]->area == iSrcArea ) { // Make sure the plane normals point the same way. plane_t *pMapPlane = &g_MainMap->mapplanes[p->onnode->planenum]; float flDot = fabs( pMapPlane->normal.Dot( pPlane->normal ) ); if( fabs( 1 - flDot ) < 0.01f ) { Vector vPlanePt1 = pPlane->normal * pPlane->dist; Vector vPlanePt2 = pMapPlane->normal * pMapPlane->dist; if( vPlanePt1.DistToSqr( vPlanePt2 ) < 0.01f ) { portals.AddToTail( p ); } } } } } void EmitClipPortalGeometry( node_t *pHeadNode, portal_t *pPortal, int iSrcArea, dareaportal_t *dp ) { // Build a list of all the points in portals from the same original face. CUtlVector<portal_t*> portals; FindPortalsLeadingToArea_R( pHeadNode, iSrcArea, dp->otherarea, &pPortal->plane, portals ); CUtlVector<Vector> points; for( int iPortal=0; iPortal < portals.Size(); iPortal++ ) { portal_t *pPointPortal = portals[iPortal]; winding_t *pWinding = pPointPortal->winding; for( int i=0; i < pWinding->numpoints; i++ ) { points.AddToTail( pWinding->p[i] ); } } // Get the 2D convex hull. //// First transform them into a plane. QAngle vAngles; Vector vecs[3]; VectorAngles( pPortal->plane.normal, vAngles ); AngleVectors( vAngles, &vecs[0], &vecs[1], &vecs[2] ); VMatrix mTransform; mTransform.Identity(); mTransform.SetBasisVectors( vecs[0], vecs[1], vecs[2] ); VMatrix mInvTransform = mTransform.Transpose(); int i; CUtlVector<Vector2D> points2D; for( i=0; i < points.Size(); i++ ) { Vector vTest = mTransform * points[i]; points2D.AddToTail( Vector2D( vTest.y, vTest.z ) ); } // Build the hull. int indices[512]; int nIndices = Convex2D( points2D.Base(), points2D.Size(), indices, 512 ); // Output the hull. dp->m_FirstClipPortalVert = g_nClipPortalVerts; dp->m_nClipPortalVerts = nIndices; if ( nIndices >= 32 ) { Warning( "Warning: area portal has %d verts. Could be a vbsp bug.\n", nIndices ); } if( dp->m_FirstClipPortalVert + dp->m_nClipPortalVerts >= MAX_MAP_PORTALVERTS ) { Vector *p = pPortal->winding->p; Error( "MAX_MAP_PORTALVERTS (probably a broken areaportal near %.1f %.1f %.1f ", p->x, p->y, p->z ); } for( i=0; i < nIndices; i++ ) { g_ClipPortalVerts[g_nClipPortalVerts] = points[ indices[i] ]; ++g_nClipPortalVerts; } } // Sets node_t::area for non-leaf nodes (this allows an optimization in the renderer). void SetNodeAreaIndices_R( node_t *node ) { // All leaf area indices should already be set. if( node->planenum == PLANENUM_LEAF ) return; // Have the children set their area indices. SetNodeAreaIndices_R( node->children[0] ); SetNodeAreaIndices_R( node->children[1] ); // If all children (leaves or nodes) are in the same area, then set our area // to this area as well. Otherwise, set it to -1. if( node->children[0]->area == node->children[1]->area ) node->area = node->children[0]->area; else node->area = -1; } /* ============= EmitAreaPortals ============= */ void EmitAreaPortals (node_t *headnode) { entity_t *e; dareaportal_t *dp; if (c_areas > MAX_MAP_AREAS) Error ("Map is split into too many unique areas (max = %d)\nProbably too many areaportals", MAX_MAP_AREAS); numareas = c_areas+1; numareaportals = 1; // leave 0 as an error // Reset the clip portal vert info. g_nClipPortalVerts = 0; for (int iSrcArea=1 ; iSrcArea<=c_areas ; iSrcArea++) { dareas[iSrcArea].firstareaportal = numareaportals; for (int j=0 ; j<num_entities ; j++) { e = &entities[j]; if (!e->areaportalnum) continue; if (e->portalareas[0] == iSrcArea || e->portalareas[1] == iSrcArea) { int iSide = (e->portalareas[0] == iSrcArea); // We're only interested in the portal that divides the two areas. // One of the portals that leads into the CONTENTS_AREAPORTAL just bounds // the same two areas but the other bounds two different ones. portal_t *pLeadingPortal = e->m_pPortalsLeadingIntoAreas[0]; if( pLeadingPortal->nodes[0]->area == pLeadingPortal->nodes[1]->area ) pLeadingPortal = e->m_pPortalsLeadingIntoAreas[1]; if( pLeadingPortal ) { Assert( pLeadingPortal->nodes[0]->area != pLeadingPortal->nodes[1]->area ); dp = &dareaportals[numareaportals]; numareaportals++; dp->m_PortalKey = e->areaportalnum; dp->otherarea = e->portalareas[iSide]; dp->planenum = pLeadingPortal->onnode->planenum; Assert( pLeadingPortal->nodes[0]->planenum == PLANENUM_LEAF ); Assert( pLeadingPortal->nodes[1]->planenum == PLANENUM_LEAF ); if( pLeadingPortal->nodes[0]->area == dp->otherarea ) { // Use the flipped version of the plane. dp->planenum = (dp->planenum & ~1) | (~dp->planenum & 1); } EmitClipPortalGeometry( headnode, pLeadingPortal, iSrcArea, dp ); } } } dareas[iSrcArea].numareaportals = numareaportals - dareas[iSrcArea].firstareaportal; } SetNodeAreaIndices_R( headnode ); qprintf ("%5i numareas\n", numareas); qprintf ("%5i numareaportals\n", numareaportals); } /* ============= FloodAreas Mark each leaf with an area, bounded by CONTENTS_AREAPORTAL ============= */ void FloodAreas (tree_t *tree) { int start = Plat_FloatTime(); qprintf ("--- FloodAreas ---\n"); Msg("Processing areas..."); FindAreas_r (tree->headnode); SetAreaPortalAreas_r (tree, tree->headnode); qprintf ("%5i areas\n", c_areas); Msg("done (%d)\n", (int)(Plat_FloatTime() - start) ); } //====================================================== int c_outside; int c_inside; int c_solid; void FillOutside_r (node_t *node) { if (node->planenum != PLANENUM_LEAF) { FillOutside_r (node->children[0]); FillOutside_r (node->children[1]); return; } // anything not reachable by an entity // can be filled away if (!node->occupied) { if (node->contents != CONTENTS_SOLID) { c_outside++; node->contents = CONTENTS_SOLID; } else c_solid++; } else c_inside++; } /* ============= FillOutside Fill all nodes that can't be reached by entities ============= */ void FillOutside (node_t *headnode) { c_outside = 0; c_inside = 0; c_solid = 0; qprintf ("--- FillOutside ---\n"); FillOutside_r (headnode); qprintf ("%5i solid leafs\n", c_solid); qprintf ("%5i leafs filled\n", c_outside); qprintf ("%5i inside leafs\n", c_inside); } static float ComputeDistFromPlane( winding_t *pWinding, plane_t *pPlane, float maxdist ) { float totaldist = 0.0f; for (int i = 0; i < pWinding->numpoints; ++i) { totaldist += fabs(DotProduct( pPlane->normal, pWinding->p[i] ) - pPlane->dist); if (totaldist > maxdist) return totaldist; } return totaldist; } //----------------------------------------------------------------------------- // Display portal error //----------------------------------------------------------------------------- static void DisplayPortalError( portal_t *p, int viscontents ) { char contents[3][1024]; PrintBrushContentsToString( p->nodes[0]->contents, contents[0], sizeof( contents[0] ) ); PrintBrushContentsToString( p->nodes[1]->contents, contents[1], sizeof( contents[1] ) ); PrintBrushContentsToString( viscontents, contents[2], sizeof( contents[2] ) ); Vector center; WindingCenter( p->winding, center ); Warning( "\nFindPortalSide: Couldn't find a good match for which brush to assign to a portal near (%.1f %.1f %.1f)\n", center.x, center.y, center.z); Warning( "Leaf 0 contents: %s\n", contents[0] ); Warning( "Leaf 1 contents: %s\n", contents[1] ); Warning( "viscontents (node 0 contents ^ node 1 contents): %s\n", contents[2] ); Warning( "This means that none of the brushes in leaf 0 or 1 that touches the portal has %s\n", contents[2] ); Warning( "Check for a huge brush enclosing the coordinates above that has contents %s\n", contents[2] ); Warning( "Candidate brush IDs: " ); CUtlVector<int> listed; for (int j=0 ; j<2 ; j++) { node_t *n = p->nodes[j]; for (bspbrush_t *bb=n->brushlist ; bb ; bb=bb->next) { mapbrush_t *brush = bb->original; if ( brush->contents & viscontents ) { if ( listed.Find( brush->brushnum ) == -1 ) { listed.AddToTail( brush->brushnum ); Warning( "Brush %d: ", brush->id ); } } } } Warning( "\n\n" ); } //============================================================== /* ============ FindPortalSide Finds a brush side to use for texturing the given portal ============ */ void FindPortalSide (portal_t *p) { int viscontents; bspbrush_t *bb; mapbrush_t *brush; node_t *n; int i,j; int planenum; side_t *side, *bestside; float bestdist; plane_t *p1, *p2; // decide which content change is strongest // solid > lava > water, etc viscontents = VisibleContents (p->nodes[0]->contents ^ p->nodes[1]->contents); if (!viscontents) { return; } planenum = p->onnode->planenum; bestside = NULL; bestdist = 1000000; for (j=0 ; j<2 ; j++) { n = p->nodes[j]; p1 = &g_MainMap->mapplanes[p->onnode->planenum]; for (bb=n->brushlist ; bb ; bb=bb->next) { brush = bb->original; if ( !(brush->contents & viscontents) ) continue; for (i=0 ; i<brush->numsides ; i++) { side = &brush->original_sides[i]; if (side->bevel) continue; if (side->texinfo == TEXINFO_NODE) continue; // non-visible if ((side->planenum&~1) == planenum) { // exact match bestside = &brush->original_sides[i]; bestdist = 0.0f; goto gotit; } p2 = &g_MainMap->mapplanes[side->planenum&~1]; float dist = ComputeDistFromPlane( p->winding, p2, bestdist ); if (dist < bestdist) { bestside = side; bestdist = dist; } } } } gotit: if (!bestside) qprintf ("WARNING: side not found for portal\n"); // Compute average dist, check for problems... if ((bestdist / p->winding->numpoints) > 2) { static int nWarnCount = 0; if ( nWarnCount < 8 ) { DisplayPortalError( p, viscontents ); if ( ++nWarnCount == 8 ) { Warning("*** Suppressing further FindPortalSide errors.... ***\n" ); } } } p->sidefound = true; p->side = bestside; } /* =============== MarkVisibleSides_r =============== */ void MarkVisibleSides_r (node_t *node) { portal_t *p; int s; if (node->planenum != PLANENUM_LEAF) { MarkVisibleSides_r (node->children[0]); MarkVisibleSides_r (node->children[1]); return; } // empty leafs are never boundary leafs if (!node->contents) return; // see if there is a visible face for (p=node->portals ; p ; p = p->next[!s]) { s = (p->nodes[0] == node); if (!p->onnode) continue; // edge of world if (!p->sidefound) FindPortalSide (p); if (p->side) p->side->visible = true; } } /* ============= MarkVisibleSides ============= */ // UNDONE: Put detail brushes in a separate list (not mapbrushes) ? void MarkVisibleSides (tree_t *tree, int startbrush, int endbrush, int detailScreen) { int i, j; mapbrush_t *mb; int numsides; qboolean detail; qprintf ("--- MarkVisibleSides ---\n"); // clear all the visible flags for (i=startbrush ; i<endbrush ; i++) { mb = &g_MainMap->mapbrushes[i]; if ( detailScreen != FULL_DETAIL ) { qboolean onlyDetail = (detailScreen==ONLY_DETAIL)?true:false; // true for detail brushes detail = (mb->contents & CONTENTS_DETAIL) ? true : false; if ( onlyDetail ^ detail ) { // both of these must have the same value or we're not interested in this brush continue; } } numsides = mb->numsides; for (j=0 ; j<numsides ; j++) mb->original_sides[j].visible = false; } // set visible flags on the sides that are used by portals MarkVisibleSides_r (tree->headnode); } //----------------------------------------------------------------------------- // Used to determine which sides are visible //----------------------------------------------------------------------------- void MarkVisibleSides (tree_t *tree, mapbrush_t **ppBrushes, int nCount ) { qprintf ("--- MarkVisibleSides ---\n"); // clear all the visible flags int i, j; for ( i=0; i < nCount; ++i ) { mapbrush_t *mb = ppBrushes[i]; int numsides = mb->numsides; for (j=0 ; j<numsides ; j++) { mb->original_sides[j].visible = false; } } // set visible flags on the sides that are used by portals MarkVisibleSides_r( tree->headnode ); }
0
0.957596
1
0.957596
game-dev
MEDIA
0.491996
game-dev
0.980066
1
0.980066
wangtaoking1/texaspoker
23,091
branches/mlearning/run_area/works/source/AdvancedAI/MoreAI.java
package AdvancedAI; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import utils.BetState; import utils.CardGroup; import utils.Color; import utils.Constants; import utils.MaxCardComputer; import utils.Poker; import utils.SuperAI; /** * 人数多于4人的时候使用该AI * * @author wenzhu * */ public class MoreAI extends SuperAI { private int foldCounter = 0; // 用来计算fold的局数 public MoreAI(String playerID) { super(playerID); } private int getIndex(Color color) { switch (color) { case SPADES: return 0; case HEARTS: return 1; case CLUBS: return 2; case DIAMONDS: return 3; default: break; } return 0; } private String fold(ArrayList<BetState> betStates) { // String colors[] = { "SPADES", // 黑桃 // "HEARTS", // 红桃 // "CLUBS", // 梅花 // "DIAMONDS" // 方片 // }; // String logName = "/home/wenzhu/area/fold_log.txt"; // try { // FileWriter writer = new FileWriter(logName, true); // foldCounter++; // writer.write("MoreAI" + "\n"); // writer.write("Playerid:" + this.getPlayerID() + "\n"); // writer.write("fold " + Integer.toString(foldCounter) + "\n"); // writer.write("Current Hand Number: " // + Integer.toString(this.getHandNum()) + "\n"); // writer.write("Hold pokers:\n"); // ArrayList<Poker> hp = this.getHoldPokers(); // for (int i = 0; i < hp.size(); i++) // writer.write(colors[getIndex(hp.get(i).getColor())] + " " // + hp.get(i).getValue() + "\n"); // // writer.write("Public pokers:\n"); // ArrayList<Poker> pp = this.getPublicPokers(); // for (int i = 0; i < pp.size(); i++) // writer.write(colors[getIndex(pp.get(i).getColor())] + " " // + pp.get(i).getValue() + "\n"); // // int maxBet = this.getMaxBet(betStates); // int selfBet = this.getSelfBet(betStates); // int diff = maxBet - selfBet; // writer.write("MaxBet: " + Integer.toString(maxBet) + "\n"); // writer.write("SelfBet " + Integer.toString(selfBet) + "\n"); // writer.write("Diff: " + Integer.toString(diff) + "\n"); // writer.write("Rest Jetton: " // + Integer.toString(this.getTotalJetton()) + "\n"); // writer.write("Rest Money: " // + Integer.toString(this.getTotalMoney()) + "\n"); // writer.write("Money and Jetton: " // + Integer.toString(this.getTotalMoneyAndJetton()) + "\n"); // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // } return "fold"; } @Override public String thinkAfterHold(ArrayList<BetState> betStates) { ArrayList<Poker> hp = this.getHoldPokers(); // 计算自己与最大押注的差距,得出需要押注的大小 int maxBet = this.getMaxBet(betStates); int selfBet = this.getSelfBet(betStates); int diff = (maxBet - selfBet); int maxBlindBet = Constants.MORE_HIGH_BET_MULTIPLE * this.getBlind(); // 可接受(跟注)最大下注筹码 int midBlindBet = Constants.MORE_MIDDLE_BET_MULTIPLE * this.getBlind(); // 可接受(跟注)中等下注筹码 int lowBlindBet = Constants.MORE_LOW_BET_MULTIPLE * this.getBlind(); // 如果手牌是大对:AA, KK, QQ, JJ, 1010等 if (this.isHoldBigPair(hp)) { // 加注至 MIDDLE_RAISE_MULTIPLE * blind return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); } // 手牌是小对:2~9中的一对 else if (this.isHoldSmallPair(hp)) { // 如果需要下注小于可接受最大下注金额,则跟注 if (diff <= maxBlindBet) return callByDiff(diff); } // 手牌不相等且都大于GAP_VALUE else if (this.isHoldBig(hp)) { // 如果需要下注小于可接受最大下注金额,则跟注 if (diff <= maxBlindBet) return callByDiff(diff); } // 手牌其中有一个大于GAP_VALUE else if (hp.get(0).getValue() >= Constants.GAP_VALUE || hp.get(0).getValue() >= Constants.GAP_VALUE) { // 如果需要下注小于可接受中等下注金额且(手牌同花色(有可能组成同花)或者相差小于4(有可能组成顺子)) if (diff <= midBlindBet) { if (this.isHoldSameColor(hp) || this.isHoldLessThanFour(hp) || (hp.get(0).getValue() >= 11 || hp.get(1).getValue() >= 11)) return callByDiff(diff); } } // 手牌都小于10 else { // 手牌同花色或者相差小于4 if (this.isHoldSameColor(hp) || this.isHoldLessThanFour(hp)) { if (diff <= midBlindBet) return callByDiff(diff); } // 其它牌型,50%概率跟注 else if ((int) Math.random() * 100 <= Constants.MORE_CALL_PERCENTAGE) { if (diff <= lowBlindBet) return callByDiff(diff); } } return fold(betStates); } /** * 判断手牌是否相差小于等于4(有可能组成顺子) * * @param hp * @return */ private boolean isHoldLessThanFour(ArrayList<Poker> hp) { // 其中有一张为A if (hp.get(0).getValue() == 14 || hp.get(1).getValue() == 14) return Math.abs(hp.get(0).getValue() - hp.get(1).getValue()) % 13 <= 4 ? true : false; else if (Math.abs(hp.get(0).getValue() - hp.get(1).getValue()) <= 4) return true; return false; } /** * 手牌都大于或等于10 * * @param hp * @return */ private boolean isHoldBig(ArrayList<Poker> hp) { if (hp.get(0).getValue() >= Constants.GAP_VALUE && hp.get(1).getValue() >= Constants.GAP_VALUE) return true; return false; } private boolean isHoldSmall(ArrayList<Poker> hp) { if (hp.get(0).getValue() < Constants.GAP_VALUE && hp.get(1).getValue() < Constants.GAP_VALUE) return true; return false; } /** * 判断手牌是否同花色 * * @param hp * @return */ private boolean isHoldSameColor(ArrayList<Poker> hp) { if (hp.get(0).getColor() == hp.get(1).getColor()) return true; return false; } /** * 跟注 * * @param diff * @return */ private String callByDiff(int diff) { // 不需要跟注的时候,则让牌(check) if (diff == 0) return "check"; // 剩余筹码足够,则跟注 else if (diff < this.getTotalJetton()) return "call"; // 剩余筹码不够,则全押 else return "all_in"; } /** * 获取本手牌已下注的玩家下的最大注 * * @param betStates * @return */ private int getMaxBet(ArrayList<BetState> betStates) { int maxBet = 0; for (int i = 0; i < betStates.size(); i++) { if (betStates.get(i).getBet() > maxBet) maxBet = betStates.get(i).getBet(); } return maxBet; } /** * 获取本手牌自己已下注的筹码 * * @param betStates * @return */ private int getSelfBet(ArrayList<BetState> betStates) { for (int i = 0; i < betStates.size(); i++) { if (betStates.get(i).getPlayerID().equals(this.getPlayerID())) return betStates.get(i).getBet(); } return 0; } /** * 发出三张公共牌之后思考策略 * * @param betStates * 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ @Override public String thinkAfterFlop(ArrayList<BetState> betStates) { ArrayList<Poker> hp = this.getHoldPokers(); ArrayList<Poker> pp = this.getPublicPokers(); CardGroup maxGroup = (new MaxCardComputer(hp, pp)).getMaxCardGroup(); int maxBet = this.getMaxBet(betStates); int selfBet = this.getSelfBet(betStates); int diff = (maxBet - selfBet); long power = maxGroup.getPower(); // 一对 if (power > (long) 2 * Math.pow(10, 10) && power < (long) 3 * Math.pow(10, 10)) { // 手牌是大对,加中倍注 if (isHoldBigPair(hp)) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 手牌是小对,加低倍注 else if (isHoldSmallPair(hp)) { return raiseByDiff(diff, Constants.MORE_LOW_RAISE_MULTIPLE); } else { ArrayList<Integer> pubPair = this.getPubPairValue(pp); // 获取公共牌中的对子的值 // 公共牌中有一对,说明手牌没有和公共牌中的某一张组成对子 ,这种情况跟高牌差不多 if (pubPair.size() == 1) { // 手牌中有一个大牌 if (hp.get(0).getValue() >= Constants.GAP_VALUE || hp.get(1).getValue() >= Constants.GAP_VALUE) { if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } } // 说明手牌中的一张牌与公共牌中的一张牌组成对子 else if (pubPair.size() == 0) { ArrayList<Integer> pairValues = this.getHoldPubPairValue( hp, pp); // 在这里,pairValues中有且只有一个值 // 大对,加中倍注 if (pairValues.get(0) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 小对,加低倍注 else return raiseByDiff(diff, Constants.MORE_LOW_RAISE_MULTIPLE); } } } // 两对 else if (power > (long) 3 * Math.pow(10, 10) && power < (long) 4 * Math.pow(10, 10)) { ArrayList<Integer> holdPairValues = this .getHoldPubPairValue(hp, pp); // 获取手牌与公共牌组成对子的value // 手牌中只有一张与公共牌组成对子,说明另一对是在公共牌里的 if (holdPairValues.size() == 1) { return callByDiff(diff); } // 手牌中的两张分别与公共牌中的一张组成对子 else if (holdPairValues.size() == 2) { // 两对都是大对,加高倍注 if (holdPairValues.get(0) >= Constants.GAP_VALUE && holdPairValues.get(1) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 其中一个为大对,加中倍注 else if (holdPairValues.get(0) >= Constants.GAP_VALUE || holdPairValues.get(1) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 两对都是小对,加低倍注 else return raiseByDiff(diff, Constants.MORE_LOW_RAISE_MULTIPLE); } } // 三条 else if (power > (long) 4 * Math.pow(10, 10) && power < (long) 5 * Math.pow(10, 10)) { // 手牌相等 if (hp.get(0).getValue() == hp.get(1).getValue()) { return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 加高倍注 } // 手牌不相等 else { ArrayList<Integer> pairValues = this.getPubPairValue(pp); // 公共牌中有一对,说明三条中有两个是在公共牌里的 if (pairValues.size() == 1) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 说明三条是出现在公共牌里 else if (pairValues.size() == 0) { // 手牌都是大牌 if (hp.get(0).getValue() >= Constants.GAP_VALUE && hp.get(0).getValue() >= Constants.GAP_VALUE) { if (diff <= Constants.MORE_MIDDLE_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } else if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } } } // 顺子及以上 else if (power > (long) 5 * Math.pow(10, 10)) { return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 加高倍注 } // 在当前剩余金币与筹码总和下,下注太多,弃牌 if (diff * Constants.MAX_TOTAL_MULTIPLE > this.getTotalMoneyAndJetton()) return fold(betStates); // 同花或顺子差一张 else if (this.computeFlush(hp, pp) <= 1 || this.computeStraight(hp, pp) <= 1) { if (diff <= Constants.MORE_MIDDLE_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } // 高牌 else if (this.isHoldBig(hp)) { if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } // 手牌中有一张是大牌 else if (hp.get(0).getValue() >= Constants.GAP_VALUE || hp.get(1).getValue() >= Constants.GAP_VALUE) { if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind() && (int) (Math.random() * 100) <= Constants.MORE_CALL_PERCENTAGE) // 按照一定的概率跟注 return callByDiff(diff); } else if (diff == 0) return "check"; return fold(betStates); } private boolean isHoldPair(ArrayList<Poker> hp) { if (hp.get(0).getValue() == hp.get(1).getValue()) return true; return false; } /** * 加注:加注金额为mutiple * blind * * @param diff * 根据前面玩家下注,需要跟注的最小数量 * @param multiple * @return */ private String raiseByDiff(int diff, int multiple) { // 本环节已经加过注,则选择跟注 if (this.getHasRaised()) return "call"; if (diff < multiple * this.getBlind()) { this.setHasRaised(true); return "raise " + Integer.toString(multiple * this.getBlind() - diff); } else return "call"; } /** * 获取公共牌与手牌组成的对子的value * * @param hp * @param pp * @return */ private ArrayList<Integer> getHoldPubPairValue(ArrayList<Poker> hp, ArrayList<Poker> pp) { ArrayList<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < hp.size(); i++) { for (int j = 0; j < pp.size(); j++) { if (hp.get(i).getValue() == pp.get(j).getValue()) { res.add(hp.get(i).getValue()); break; } } } return res; } /** * 获取公共牌中组成对子的值,返回的ArrayList包含的是这些对子的value * * @param pp * @return */ private ArrayList<Integer> getPubPairValue(ArrayList<Poker> pp) { int counter[] = new int[15]; for (int i = 0; i < pp.size(); i++) { counter[pp.get(i).getValue()]++; } ArrayList<Integer> res = new ArrayList<Integer>(); for (int i = 2; i <= 14; i++) { if (counter[i] == 2) res.add(i); } return res; } /** * 获取手牌与公共牌组成对子的值 * * @param hp * @param pp * @return */ private int getPairValue(ArrayList<Poker> hp, ArrayList<Poker> pp) { for (int i = 0; i < hp.size(); i++) { for (int j = 0; j < pp.size(); j++) { if (hp.get(i).getValue() == pp.get(j).getValue()) return hp.get(i).getValue(); } } return -1; } /** * 发出一张转牌之后思考策略 * * @param betStates * 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ @Override public String thinkAfterTurn(ArrayList<BetState> betStates) { ArrayList<Poker> hp = this.getHoldPokers(); ArrayList<Poker> pp = this.getPublicPokers(); CardGroup maxGroup = (new MaxCardComputer(hp, pp)).getMaxCardGroup(); int maxBet = this.getMaxBet(betStates); int selfBet = this.getSelfBet(betStates); int diff = (maxBet - selfBet); long power = maxGroup.getPower(); // 一对 if (power > (long) 2 * Math.pow(10, 10) && power < (long) 3 * Math.pow(10, 10)) { // 手牌是一对,跟注 if (isHoldPair(hp) && diff <= Constants.MORE_HIGH_BET_MULTIPLE * this.getBlind()) { return callByDiff(diff); } else { ArrayList<Integer> pubPair = this.getPubPairValue(pp); // 获取公共牌中的对子的值 // 公共牌中有一对,说明手牌没有和公共牌中的某一张组成对子 ,这种情况跟高牌差不多 if (pubPair.size() == 1) { // 手牌都是大牌 if (this.isHoldBig(hp) && diff <= Constants.MORE_HIGH_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } // 说明手牌中的一张牌与公共牌中的一张牌组成对子 else if (pubPair.size() == 0) { ArrayList<Integer> pairValues = this.getHoldPubPairValue( hp, pp); // 在这里,pairValues中有且只有一个值 // 大对,加中倍注 if (pairValues.get(0) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 小对,跟注 else if (diff <= Constants.MORE_HIGH_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } } } // 两对 else if (power > (long) 3 * Math.pow(10, 10) && power < (long) 4 * Math.pow(10, 10)) { ArrayList<Integer> holdPairValues = this .getHoldPubPairValue(hp, pp); // 获取手牌与公共牌组成对子的value // 手牌中只有一张与公共牌组成对子,说明另一对是在公共牌里的 if (holdPairValues.size() == 1) { // 大对 if (holdPairValues.get(0) >= Constants.GAP_VALUE) { return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); } // 小对 else { return callByDiff(diff); // TODO 加注还是跟注好? } } // 手牌中的两张分别与公共牌中的一张组成对子 else if (holdPairValues.size() == 2) { // 两对都是大对,加高倍注 if (holdPairValues.get(0) >= Constants.GAP_VALUE && holdPairValues.get(1) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 其中一个为大对,加中倍注 else if (holdPairValues.get(0) >= Constants.GAP_VALUE || holdPairValues.get(1) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 两对都是小对,加低倍注 else return raiseByDiff(diff, Constants.MORE_LOW_RAISE_MULTIPLE); } } // 三条 else if (power > (long) 4 * Math.pow(10, 10) && power < (long) 5 * Math.pow(10, 10)) { // 手牌相等 if (hp.get(0).getValue() == hp.get(1).getValue()) { return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 加高倍注 } // 手牌不相等 else { ArrayList<Integer> pairValues = this.getPubPairValue(pp); // 公共牌中有一对,说明三条中有两个是在公共牌里的 if (pairValues.size() == 1) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 说明三条是出现在公共牌里 else if (pairValues.size() == 0) { // 手牌都是大牌 if (hp.get(0).getValue() >= Constants.GAP_VALUE && hp.get(0).getValue() >= Constants.GAP_VALUE) { if (diff <= Constants.MORE_MIDDLE_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } else if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } } } // 顺子及以上 else if (power > (long) 5 * Math.pow(10, 10)) { return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 加高倍注 } // 在当前剩余金币与筹码总和下,下注太多,弃牌 if (diff * Constants.MAX_TOTAL_MULTIPLE > this.getTotalMoneyAndJetton()) return fold(betStates); // 同花或顺子差一张 else if (this.computeFlush(hp, pp) <= 1 || this.computeStraight(hp, pp) <= 1) { if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } // 高牌,按照一定的概率跟注定 else { if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind() && (int) (Math.random() * 100) <= Constants.MORE_CALL_PERCENTAGE) // 按照一定的概率跟注 return callByDiff(diff); } return fold(betStates); } /** * 发出一张河牌之后思考策略 * * @param betStates * 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ @Override public String thinkAfterRiver(ArrayList<BetState> betStates) { ArrayList<Poker> hp = this.getHoldPokers(); ArrayList<Poker> pp = this.getPublicPokers(); CardGroup maxGroup = (new MaxCardComputer(hp, pp)).getMaxCardGroup(); int maxBet = this.getMaxBet(betStates); int selfBet = this.getSelfBet(betStates); int diff = (maxBet - selfBet); long power = maxGroup.getPower(); // 一对 if (power > (long) 2 * Math.pow(10, 10) && power < (long) 3 * Math.pow(10, 10)) { // 手牌是大对,加低倍注 if (isHoldBigPair(hp)) return raiseByDiff(diff, Constants.MORE_LOW_RAISE_MULTIPLE); // 手牌是小对,跟注 else if (isHoldSmallPair(hp) && diff <= Constants.MORE_HIGH_BET_MULTIPLE * this.getBlind()) { return callByDiff(diff); } else { ArrayList<Integer> pubPair = this.getPubPairValue(pp); // 获取公共牌中的对子的值 // 公共牌中有一对,说明手牌没有和公共牌中的某一张组成对子 ,这种情况跟高牌差不多 if (pubPair.size() == 1) { // 手牌都是大牌 if (this.isHoldBig(hp) && diff <= Constants.MORE_HIGH_BET_MULTIPLE * this.getBlind() && (int) (Math.random() * 100) <= Constants.MORE_CALL_PERCENTAGE) return callByDiff(diff); } // 说明手牌中的一张牌与公共牌中的一张牌组成对子 else if (pubPair.size() == 0) { ArrayList<Integer> pairValues = this.getHoldPubPairValue( hp, pp); // 在这里,pairValues中有且只有一个值 // 大对,加低倍注 if (pairValues.get(0) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_LOW_RAISE_MULTIPLE); // 小对,跟注 else if (diff <= Constants.MORE_MIDDLE_RAISE_MULTIPLE * this.getBlind()) return callByDiff(diff); } } } // 两对 else if (power > (long) 3 * Math.pow(10, 10) && power < (long) 4 * Math.pow(10, 10)) { ArrayList<Integer> holdPairValues = this .getHoldPubPairValue(hp, pp); // 获取手牌与公共牌组成对子的value // 手牌中只有一张与公共牌组成对子,说明另一对是在公共牌里的 if (holdPairValues.size() == 1) { // 大对 if (holdPairValues.get(0) >= Constants.GAP_VALUE) { return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); } // 小对 else { return callByDiff(diff); // TODO 加注还是跟注好? } } // 手牌中的两张分别与公共牌中的一张组成对子 else if (holdPairValues.size() == 2) { // 两对都是大对,加高倍注 if (holdPairValues.get(0) >= Constants.GAP_VALUE && holdPairValues.get(1) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 其中一个为大对,加中倍注 else if (holdPairValues.get(0) >= Constants.GAP_VALUE || holdPairValues.get(1) >= Constants.GAP_VALUE) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 两对都是小对,跟注 else return callByDiff(diff); } } // 三条 else if (power > (long) 4 * Math.pow(10, 10) && power < (long) 5 * Math.pow(10, 10)) { // 手牌相等 if (hp.get(0).getValue() == hp.get(1).getValue()) { return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 加高倍注 } // 手牌不相等 else { ArrayList<Integer> pairValues = this.getPubPairValue(pp); // 公共牌中有一对,说明三条中有两个是在公共牌里的 if (pairValues.size() == 1) return raiseByDiff(diff, Constants.MORE_MIDDLE_RAISE_MULTIPLE); // 说明三条是出现在公共牌里 else if (pairValues.size() == 0) { // 手牌都是大牌 if (this.isHoldBig(hp)) { if (diff <= Constants.MORE_MIDDLE_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } else if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); } } } // 顺子及以上 else if (power > (long) 5 * Math.pow(10, 10)) { return raiseByDiff(diff, Constants.MORE_HIGH_RAISE_MULTIPLE); // 加高倍注 } // 在当前剩余金币与筹码总和下,下注太多,弃牌 if (diff * Constants.MAX_TOTAL_MULTIPLE > this.getTotalMoneyAndJetton()) return fold(betStates); // 高牌,按照一定的概率跟注 else { if (diff <= Constants.MORE_LOW_BET_MULTIPLE * this.getBlind() && (int) (Math.random() * 100) <= Constants.MORE_CALL_PERCENTAGE) // 按照一定的概率跟注 return callByDiff(diff); } return fold(betStates); } /** * 判断手牌是否是大对:AA, KK, QQ, JJ, 1010等 * * @param hp * 手牌 * @return 大对返回true, 否则返回false */ private boolean isHoldBigPair(ArrayList<Poker> hp) { // 避免出错 if (hp == null || hp.size() < 2) return false; // 手牌是大对:AA, KK, QQ, JJ, 1010等 else if (hp.get(0).getValue() == hp.get(1).getValue() && hp.get(0).getValue() >= 10) return true; return false; } /** * 判断手牌是否是小对:2~9中的一对 * * @param hp * 手牌 * @return 小对返回true,否则返回false */ private boolean isHoldSmallPair(ArrayList<Poker> hp) { // 避免出错 if (hp == null || hp.size() < 2) return false; // 手牌是大对:AA, KK, QQ, JJ, 1010等 else if (hp.get(0).getValue() == hp.get(1).getValue() && hp.get(0).getValue() < 10) return true; return false; } /** * 计算当前牌组成同花最少还差多少张 * * @param backPokers * @param publicPokers * @return */ private int computeFlush(ArrayList<Poker> holdPokers, ArrayList<Poker> publicPokers) { int count[] = new int[4]; for (Poker p : holdPokers) { switch (p.getColor()) { case SPADES: count[0]++; break; case HEARTS: count[1]++; break; case CLUBS: count[2]++; break; case DIAMONDS: count[3]++; break; } } for (Poker p : publicPokers) { switch (p.getColor()) { case SPADES: count[0]++; break; case HEARTS: count[1]++; break; case CLUBS: count[2]++; break; case DIAMONDS: count[3]++; break; } } int maxCount = 0; for (int i = 0; i < count.length; i++) if (count[i] > maxCount) maxCount = count[i]; return 5 - maxCount; } /** * 计算当前牌组成顺子最少需要多少张牌 * * @param holdPokers * @param publicPokers * @return */ private int computeStraight(ArrayList<Poker> holdPokers, ArrayList<Poker> publicPokers) { boolean visited[] = new boolean[15]; for (int i = 0; i < visited.length; i++) visited[i] = false; // 将所有出现的牌值标记 for (Poker poker : holdPokers) { if (poker.getValue() == 14) { visited[1] = visited[14] = true; } else { visited[poker.getValue()] = true; } } for (Poker poker : publicPokers) { if (poker.getValue() == 14) { visited[1] = visited[14] = true; } else { visited[poker.getValue()] = true; } } int maxCount = 0; for (int i = 1; i <= 10; i++) { int count = 0; for (int j = 0; j < 5; j++) { if (visited[i + j]) { count++; } } if (count > maxCount) { maxCount = count; } } return 5 - maxCount; } }
0
0.893348
1
0.893348
game-dev
MEDIA
0.792911
game-dev
0.92808
1
0.92808
Cycling74/gen-plugin-export
40,347
misc/JUCE/modules/juce_audio_processors/format_types/VST3_SDK/base/source/fstring.h
//------------------------------------------------------------------------ // Project : SDK Base // Version : 1.0 // // Category : Helpers // Filename : base/source/fstring.h // Created by : Steinberg, 2008 // Description : String class // //----------------------------------------------------------------------------- // LICENSE // (c) 2019, Steinberg Media Technologies GmbH, All Rights Reserved //----------------------------------------------------------------------------- // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the Steinberg Media Technologies nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #pragma once #include "pluginterfaces/base/ftypes.h" #include "pluginterfaces/base/fstrdefs.h" #include "pluginterfaces/base/istringresult.h" #include "pluginterfaces/base/ipersistent.h" #include "base/source/fobject.h" #include <stdarg.h> namespace Steinberg { class FVariant; class String; #ifdef UNICODE static const bool kWideStringDefault = true; #else static const bool kWideStringDefault = false; #endif static const uint16 kBomUtf16 = 0xFEFF; ///< UTF16 Byte Order Mark static const char8* const kBomUtf8 = "\xEF\xBB\xBF"; ///< UTF8 Byte Order Mark static const int32 kBomUtf8Length = 3; enum MBCodePage { kCP_ANSI = 0, ///< Default ANSI codepage. kCP_MAC_ROMAN = 2, ///< Default Mac codepage. kCP_ANSI_WEL = 1252, ///< West European Latin Encoding. kCP_MAC_CEE = 10029, ///< Mac Central European Encoding. kCP_Utf8 = 65001, ///< UTF8 Encoding. kCP_ShiftJIS = 932, ///< Shifted Japan Industrial Standard Encoding. kCP_US_ASCII = 20127, ///< US-ASCII (7-bit). kCP_Default = kCP_ANSI ///< Default ANSI codepage. }; enum UnicodeNormalization { kUnicodeNormC, ///< Unicode normalization Form C, canonical composition. kUnicodeNormD, ///< Unicode normalization Form D, canonical decomposition. kUnicodeNormKC, ///< Unicode normalization form KC, compatibility composition. kUnicodeNormKD ///< Unicode normalization form KD, compatibility decomposition. }; //------------------------------------------------------------------------ // Helper functions to create hash codes from string data. //------------------------------------------------------------------------ extern uint32 hashString8 (const char8* s, uint32 m); extern uint32 hashString16 (const char16* s, uint32 m); inline uint32 hashString (const tchar* s, uint32 m) { #ifdef UNICODE return hashString16 (s, m); #else return hashString8 (s, m); #endif } //----------------------------------------------------------------------------- /** Invariant String. @ingroup adt A base class which provides methods to work with its member string. Neither of the operations allows modifying the member string and that is why all operation are declared as const. There are operations for access, comparison, find, numbers and conversion. Almost all operations exist in three versions for char8, char16 and the polymorphic type tchar. The type tchar can either be char8 or char16 depending on whether UNICODE is activated or not.*/ //----------------------------------------------------------------------------- class ConstString { public: //----------------------------------------------------------------------------- ConstString (const char8* str, int32 length = -1); ///< Assign from string of type char8 (length=-1: all) ConstString (const char16* str, int32 length = -1); ///< Assign from string of type char16 (length=-1: all) ConstString (const ConstString& str, int32 offset = 0, int32 length = -1); ///< Copy constructor (length=-1: all). ConstString (const FVariant& var); ///< Assign a string from FVariant ConstString (); virtual ~ConstString () {} ///< Destructor. // access ----------------------------------------------------------------- virtual int32 length () const {return static_cast<int32> (len);} ///< Return length of string inline bool isEmpty () const {return buffer == 0 || len == 0;} ///< Return true if string is empty operator const char8* () const {return text8 ();} ///< Returns pointer to string of type char8 (no modification allowed) operator const char16* () const {return text16 ();} ///< Returns pointer to string of type char16(no modification allowed) inline tchar operator[] (short idx) const {return getChar (static_cast<uint32> (idx));} ///< Returns character at 'idx' inline tchar operator[] (long idx) const {return getChar (static_cast<uint32> (idx));} inline tchar operator[] (int idx) const {return getChar (static_cast<uint32> (idx));} inline tchar operator[] (unsigned short idx) const {return getChar (idx);} inline tchar operator[] (unsigned long idx) const {return getChar (static_cast<uint32> (idx));} inline tchar operator[] (unsigned int idx) const {return getChar (idx);} inline virtual const char8* text8 () const; ///< Returns pointer to string of type char8 inline virtual const char16* text16 () const; ///< Returns pointer to string of type char16 inline virtual const tchar* text () const; ///< Returns pointer to string of type tchar inline virtual const void* ptr () const {return buffer;} ///< Returns pointer to string of type void inline virtual char8 getChar8 (uint32 index) const; ///< Returns character of type char16 at 'index' inline virtual char16 getChar16 (uint32 index) const; ///< Returns character of type char8 at 'index' inline tchar getChar (uint32 index) const; ///< Returns character of type tchar at 'index' inline tchar getCharAt (uint32 index) const; ///< Returns character of type tchar at 'index', no conversion! bool testChar8 (uint32 index, char8 c) const; ///< Returns true if character is equal at position 'index' bool testChar16 (uint32 index, char16 c) const; inline bool testChar (uint32 index, char8 c) const {return testChar8 (index, c);} inline bool testChar (uint32 index, char16 c) const {return testChar16 (index, c);} bool extract (String& result, uint32 idx, int32 n = -1) const; ///< Get n characters long substring starting at index (n=-1: until end) int32 copyTo8 (char8* str, uint32 idx = 0, int32 n = -1) const; int32 copyTo16 (char16* str, uint32 idx = 0, int32 n = -1) const; int32 copyTo (tchar* str, uint32 idx = 0, int32 n = -1) const; void copyTo (IStringResult* result) const; ///< Copies whole member string void copyTo (IString& string) const; ///< Copies whole member string inline uint32 hash (uint32 tsize) const { return isWide ? hashString16 (buffer16, tsize) : hashString8 (buffer8, tsize) ; } //------------------------------------------------------------------------- // compare ---------------------------------------------------------------- enum CompareMode { kCaseSensitive, ///< Comparison is done with regard to character's case kCaseInsensitive ///< Comparison is done without regard to character's case }; int32 compareAt (uint32 index, const ConstString& str, int32 n = -1, CompareMode m = kCaseSensitive) const; ///< Compare n characters of str with n characters of this starting at index (return: see above) int32 compare (const ConstString& str, int32 n, CompareMode m = kCaseSensitive) const; ///< Compare n characters of str with n characters of this (return: see above) int32 compare (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Compare all characters of str with this (return: see above) int32 naturalCompare (const ConstString& str, CompareMode mode = kCaseSensitive) const; bool startsWith (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Check if this starts with str bool endsWith (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Check if this ends with str bool contains (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Check if this contains str // static methods static bool isCharSpace (char8 character); ///< Returns true if character is a space static bool isCharSpace (char16 character); ///< @copydoc isCharSpace(const char8) static bool isCharAlpha (char8 character); ///< Returns true if character is an alphabetic character static bool isCharAlpha (char16 character); ///< @copydoc isCharAlpha(const char8) static bool isCharAlphaNum (char8 character); ///< Returns true if character is an alphanumeric character static bool isCharAlphaNum (char16 character); ///< @copydoc isCharAlphaNum(const char8) static bool isCharDigit (char8 character); ///< Returns true if character is a number static bool isCharDigit (char16 character); ///< @copydoc isCharDigit(const char8) static bool isCharAscii (char8 character); ///< Returns true if character is in ASCII range static bool isCharAscii (char16 character); ///< Returns true if character is in ASCII range static bool isCharUpper (char8 character); static bool isCharUpper (char16 character); static bool isCharLower (char8 character); static bool isCharLower (char16 character); //------------------------------------------------------------------------- /** @name Find first occurrence of n characters of str in this (n=-1: all) ending at endIndex (endIndex = -1: all)*/ ///@{ inline int32 findFirst (const ConstString& str, int32 n = -1, CompareMode m = kCaseSensitive, int32 endIndex = -1) const {return findNext (0, str, n, m, endIndex);} inline int32 findFirst (char8 c, CompareMode m = kCaseSensitive, int32 endIndex = -1) const {return findNext (0, c, m, endIndex);} inline int32 findFirst (char16 c, CompareMode m = kCaseSensitive, int32 endIndex = -1) const {return findNext (0, c, m, endIndex);} ///@} /** @name Find next occurrence of n characters of str starting at startIndex in this (n=-1: all) ending at endIndex (endIndex = -1: all)*/ ///@{ int32 findNext (int32 startIndex, const ConstString& str, int32 n = -1, CompareMode = kCaseSensitive, int32 endIndex = -1) const; int32 findNext (int32 startIndex, char8 c, CompareMode = kCaseSensitive, int32 endIndex = -1) const; int32 findNext (int32 startIndex, char16 c, CompareMode = kCaseSensitive, int32 endIndex = -1) const; ///@} /** @name Find previous occurrence of n characters of str starting at startIndex in this (n=-1: all) */ ///@{ int32 findPrev (int32 startIndex, const ConstString& str, int32 n = -1, CompareMode = kCaseSensitive) const; int32 findPrev (int32 startIndex, char8 c, CompareMode = kCaseSensitive) const; int32 findPrev (int32 startIndex, char16 c, CompareMode = kCaseSensitive) const; ///@} inline int32 findLast (const ConstString& str, int32 n = -1, CompareMode m = kCaseSensitive) const {return findPrev (-1, str, n, m);} ///< Find last occurrence of n characters of str in this (n=-1: all) inline int32 findLast (char8 c, CompareMode m = kCaseSensitive) const {return findPrev (-1, c, m);} inline int32 findLast (char16 c, CompareMode m = kCaseSensitive) const {return findPrev (-1, c, m);} int32 countOccurences (char8 c, uint32 startIndex, CompareMode = kCaseSensitive) const; ///< Counts occurences of c within this starting at index int32 countOccurences (char16 c, uint32 startIndex, CompareMode = kCaseSensitive) const; int32 getFirstDifferent (const ConstString& str, CompareMode = kCaseSensitive) const; ///< Returns position of first different character //------------------------------------------------------------------------- // numbers ---------------------------------------------------------------- bool isDigit (uint32 index) const; ///< Returns true if character at position is a digit bool scanFloat (double& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to double value starting at offset bool scanInt64 (int64& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to int64 value starting at offset bool scanUInt64 (uint64& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to uint64 value starting at offset bool scanInt32 (int32& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to int32 value starting at offset bool scanUInt32 (uint32& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to uint32 value starting at offset bool scanHex (uint8& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to hex/uint8 value starting at offset int32 getTrailingNumberIndex (uint32 width = 0) const; ///< Returns start index of trailing number int64 getTrailingNumber (int64 fallback = 0) const; ///< Returns result of scanInt64 or the fallback int64 getNumber () const; ///< Returns result of scanInt64 // static methods static bool scanInt64_8 (const char8* text, int64& value, bool scanToEnd = true); ///< Converts string of type char8 to int64 value static bool scanInt64_16 (const char16* text, int64& value, bool scanToEnd = true); ///< Converts string of type char16 to int64 value static bool scanInt64 (const tchar* text, int64& value, bool scanToEnd = true); ///< Converts string of type tchar to int64 value static bool scanUInt64_8 (const char8* text, uint64& value, bool scanToEnd = true); ///< Converts string of type char8 to uint64 value static bool scanUInt64_16 (const char16* text, uint64& value, bool scanToEnd = true); ///< Converts string of type char16 to uint64 value static bool scanUInt64 (const tchar* text, uint64& value, bool scanToEnd = true); ///< Converts string of type tchar to uint64 value static bool scanInt32_8 (const char8* text, int32& value, bool scanToEnd = true); ///< Converts string of type char8 to int32 value static bool scanInt32_16 (const char16* text, int32& value, bool scanToEnd = true); ///< Converts string of type char16 to int32 value static bool scanInt32 (const tchar* text, int32& value, bool scanToEnd = true); ///< Converts string of type tchar to int32 value static bool scanUInt32_8 (const char8* text, uint32& value, bool scanToEnd = true); ///< Converts string of type char8 to int32 value static bool scanUInt32_16 (const char16* text, uint32& value, bool scanToEnd = true); ///< Converts string of type char16 to int32 value static bool scanUInt32 (const tchar* text, uint32& value, bool scanToEnd = true); ///< Converts string of type tchar to int32 value static bool scanHex_8 (const char8* text, uint8& value, bool scanToEnd = true); ///< Converts string of type char8 to hex/unit8 value static bool scanHex_16 (const char16* text, uint8& value, bool scanToEnd = true); ///< Converts string of type char16 to hex/unit8 value static bool scanHex (const tchar* text, uint8& value, bool scanToEnd = true); ///< Converts string of type tchar to hex/unit8 value //------------------------------------------------------------------------- // conversion ------------------------------------------------------------- void toVariant (FVariant& var) const; static char8 toLower (char8 c); ///< Converts to lower case static char8 toUpper (char8 c); ///< Converts to upper case static char16 toLower (char16 c); static char16 toUpper (char16 c); static int32 multiByteToWideString (char16* dest, const char8* source, int32 wcharCount, uint32 sourceCodePage = kCP_Default); ///< If dest is zero, this returns the maximum number of bytes needed to convert source static int32 wideStringToMultiByte (char8* dest, const char16* source, int32 char8Count, uint32 destCodePage = kCP_Default); ///< If dest is zero, this returns the maximum number of bytes needed to convert source bool isWideString () const {return isWide != 0;} ///< Returns true if string is wide bool isAsciiString () const; ///< Checks if all characters in string are in ascii range bool isNormalized (UnicodeNormalization = kUnicodeNormC); ///< On PC only kUnicodeNormC is working #if SMTG_OS_MACOS virtual void* toCFStringRef (uint32 encoding = 0xFFFF, bool mutableCFString = false) const; ///< CFString conversion #endif //------------------------------------------------------------------------- //----------------------------------------------------------------------------- protected: union { void* buffer; char8* buffer8; char16* buffer16; }; uint32 len : 30; uint32 isWide : 1; }; //----------------------------------------------------------------------------- /** String. @ingroup adt Extends class ConstString by operations which allow modifications. \see ConstString */ //----------------------------------------------------------------------------- class String : public ConstString { public: //----------------------------------------------------------------------------- String (); String (const char8* str, MBCodePage codepage, int32 n = -1, bool isTerminated = true); ///< assign n characters of str and convert to wide string by using the specified codepage String (const char8* str, int32 n = -1, bool isTerminated = true); ///< assign n characters of str (-1: all) String (const char16* str, int32 n = -1, bool isTerminated = true); ///< assign n characters of str (-1: all) String (const String& str, int32 n = -1); ///< assign n characters of str (-1: all) String (const ConstString& str, int32 n = -1); ///< assign n characters of str (-1: all) String (const FVariant& var); ///< assign from FVariant String (IString* str); ///< assign from IString ~String (); #if SMTG_CPP11_STDLIBSUPPORT String (String&& str); String& operator= (String&& str); #endif // access------------------------------------------------------------------ void updateLength (); ///< Call this when the string is truncated outside (not recommended though) virtual const char8* text8 () const SMTG_OVERRIDE; virtual const char16* text16 () const SMTG_OVERRIDE; virtual char8 getChar8 (uint32 index) const SMTG_OVERRIDE; virtual char16 getChar16 (uint32 index) const SMTG_OVERRIDE; bool setChar8 (uint32 index, char8 c); bool setChar16 (uint32 index, char16 c); inline bool setChar (uint32 index, char8 c) {return setChar8 (index, c);} inline bool setChar (uint32 index, char16 c) {return setChar16 (index, c);} //------------------------------------------------------------------------- // assignment-------------------------------------------------------------- String& operator= (const char8* str) {return assign (str);} ///< Assign from a string of type char8 String& operator= (const char16* str) {return assign (str);} String& operator= (const ConstString& str) {return assign (str);} String& operator= (const String& str) {return assign (str);} String& operator= (char8 c) {return assign (c);} String& operator= (char16 c) {return assign (c);} String& assign (const ConstString& str, int32 n = -1); ///< Assign n characters of str (-1: all) String& assign (const char8* str, int32 n = -1, bool isTerminated = true); ///< Assign n characters of str (-1: all) String& assign (const char16* str, int32 n = -1, bool isTerminated = true); ///< Assign n characters of str (-1: all) String& assign (char8 c, int32 n = 1); String& assign (char16 c, int32 n = 1); //------------------------------------------------------------------------- // concat------------------------------------------------------------------ String& append (const ConstString& str, int32 n = -1); ///< Append n characters of str to this (n=-1: all) String& append (const char8* str, int32 n = -1); ///< Append n characters of str to this (n=-1: all) String& append (const char16* str, int32 n = -1); ///< Append n characters of str to this (n=-1: all) String& append (const char8 c, int32 n = 1); ///< Append char c n times String& append (const char16 c, int32 n = 1); ///< Append char c n times String& insertAt (uint32 idx, const ConstString& str, int32 n = -1); ///< Insert n characters of str at position idx (n=-1: all) String& insertAt (uint32 idx, const char8* str, int32 n = -1); ///< Insert n characters of str at position idx (n=-1: all) String& insertAt (uint32 idx, const char16* str, int32 n = -1); ///< Insert n characters of str at position idx (n=-1: all) String& insertAt (uint32 idx, char8 c) {char8 str[] = {c, 0}; return insertAt (idx, str, 1);} String& insertAt (uint32 idx, char16 c) {char16 str[] = {c, 0}; return insertAt (idx, str, 1);} String& operator+= (const String& str) {return append (str);} String& operator+= (const ConstString& str) {return append (str);} String& operator+= (const char8* str) {return append (str);} String& operator+= (const char16* str) {return append (str);} String& operator+= (const char8 c) {return append (c);} String& operator+= (const char16 c) {return append (c);} //------------------------------------------------------------------------- // replace----------------------------------------------------------------- String& replace (uint32 idx, int32 n1, const ConstString& str, int32 n2 = -1); ///< Replace n1 characters of this (starting at idx) with n2 characters of str (n1,n2=-1: until end) String& replace (uint32 idx, int32 n1, const char8* str, int32 n2 = -1); ///< Replace n1 characters of this (starting at idx) with n2 characters of str (n1,n2=-1: until end) String& replace (uint32 idx, int32 n1, const char16* str, int32 n2 = -1); ///< Replace n1 characters of this (starting at idx) with n2 characters of str (n1,n2=-1: until end) int32 replace (const char8* toReplace, const char8* toReplaceWith, bool all = false, CompareMode m = kCaseSensitive); ///< Replace find string with replace string - returns number of replacements int32 replace (const char16* toReplace, const char16* toReplaceWith, bool all = false, CompareMode m = kCaseSensitive); ///< Replace find string with replace string - returns number of replacements bool replaceChars8 (const char8* toReplace, char8 toReplaceBy); ///< Returns true when any replacement was done bool replaceChars16 (const char16* toReplace, char16 toReplaceBy); inline bool replaceChars8 (char8 toReplace, char8 toReplaceBy) {char8 str[] = {toReplace, 0}; return replaceChars8 (str, toReplaceBy);} inline bool replaceChars16 (char16 toReplace, char16 toReplaceBy) {char16 str[] = {toReplace, 0}; return replaceChars16 (str, toReplaceBy);} inline bool replaceChars (char8 toReplace, char8 toReplaceBy) {return replaceChars8 (toReplace, toReplaceBy);} inline bool replaceChars (char16 toReplace, char16 toReplaceBy) {return replaceChars16 (toReplace, toReplaceBy);} inline bool replaceChars (const char8* toReplace, char8 toReplaceBy) {return replaceChars8 (toReplace, toReplaceBy);} inline bool replaceChars (const char16* toReplace, char16 toReplaceBy) {return replaceChars16 (toReplace, toReplaceBy);} //------------------------------------------------------------------------- // remove------------------------------------------------------------------ String& remove (uint32 index = 0, int32 n = -1); ///< Remove n characters from string starting at index (n=-1: until end) enum CharGroup {kSpace, kNotAlphaNum, kNotAlpha}; bool trim (CharGroup mode = kSpace); ///< Trim lead/trail. void removeChars (CharGroup mode = kSpace); ///< Removes all of group. bool removeChars8 (const char8* which); ///< Remove all occurrences of each char in 'which' bool removeChars16 (const char16* which); ///< Remove all occurrences of each char in 'which' inline bool removeChars8 (const char8 which) {char8 str[] = {which, 0}; return removeChars8 (str); } inline bool removeChars16 (const char16 which) {char16 str[] = {which, 0}; return removeChars16 (str); } inline bool removeChars (const char8* which) {return removeChars8 (which);} inline bool removeChars (const char16* which) {return removeChars16 (which);} inline bool removeChars (const char8 which) {return removeChars8 (which);} inline bool removeChars (const char16 which) {return removeChars16 (which);} bool removeSubString (const ConstString& subString, bool allOccurences = true); //------------------------------------------------------------------------- // print------------------------------------------------------------------- String& printf (const char8* format, ...); ///< Print formatted data into string String& printf (const char16* format, ...); ///< Print formatted data into string String& vprintf (const char8* format, va_list args); String& vprintf (const char16* format, va_list args); //------------------------------------------------------------------------- // numbers----------------------------------------------------------------- String& printInt64 (int64 value); String& printFloat (double value); /** Increment the trailing number if present else start with minNumber, width specifies the string width format (width 2 for number 3 is 03), applyOnlyFormat set to true will only format the string to the given width without incrementing the founded trailing number */ bool incrementTrailingNumber (uint32 width = 2, tchar separator = STR (' '), uint32 minNumber = 1, bool applyOnlyFormat = false); //------------------------------------------------------------------------- // conversion-------------------------------------------------------------- bool fromVariant (const FVariant& var); ///< Assigns string from FVariant void toVariant (FVariant& var) const; bool fromAttributes (IAttributes* a, IAttrID attrID); ///< Assigns string from FAttributes bool toAttributes (IAttributes* a, IAttrID attrID); void swapContent (String& s); ///< Swaps ownership of the strings pointed to void take (String& str); ///< Take ownership of the string of 'str' void take (void* _buffer, bool wide); ///< Take ownership of buffer void* pass (); void passToVariant (FVariant& var); ///< Pass ownership of buffer to Variant - sets Variant ownership void toLower (uint32 index); ///< Lower case the character. void toLower (); ///< Lower case the string. void toUpper (uint32 index); ///< Upper case the character. void toUpper (); ///< Upper case the string. unsigned char* toPascalString (unsigned char* buf); ///< Pascal string conversion const String& fromPascalString (const unsigned char* buf); ///< Pascal string conversion bool toWideString (uint32 sourceCodePage = kCP_Default); ///< Converts to wide string according to sourceCodePage bool toMultiByte (uint32 destCodePage = kCP_Default); void fromUTF8 (const char8* utf8String); ///< Assigns from UTF8 string bool normalize (UnicodeNormalization = kUnicodeNormC); ///< On PC only kUnicodeNormC is working #if SMTG_OS_MACOS virtual bool fromCFStringRef (const void*, uint32 encoding = 0xFFFF); ///< CFString conversion #endif //------------------------------------------------------------------------- //----------------------------------------------------------------------------- protected: bool resize (uint32 newSize, bool wide, bool fill = false); private: void tryFreeBuffer (); bool checkToMultiByte (uint32 destCodePage = kCP_Default) const; // to remove debug code from inline - const_cast inside!!! }; // String concatenation functions. inline String operator+ (const ConstString& s1, const ConstString& s2) {return String (s1).append (s2);} inline String operator+ (const ConstString& s1, const char8* s2) {return String (s1).append (s2);} inline String operator+ (const ConstString& s1, const char16* s2) {return String (s1).append (s2);} inline String operator+ (const char8* s1, const ConstString& s2) {return String (s1).append (s2);} inline String operator+ (const char16* s1, const ConstString& s2) {return String (s1).append (s2);} inline String operator+ (const ConstString& s1, const String& s2) {return String (s1).append (s2);} inline String operator+ (const String& s1, const ConstString& s2) {return String (s1).append (s2);} inline String operator+ (const String& s1, const String& s2) {return String (s1).append (s2);} inline String operator+ (const String& s1, const char8* s2) {return String (s1).append (s2);} inline String operator+ (const String& s1, const char16* s2) {return String (s1).append (s2);} inline String operator+ (const char8* s1, const String& s2) {return String (s1).append (s2);} inline String operator+ (const char16* s1, const String& s2) {return String (s1).append (s2);} //----------------------------------------------------------------------------- // ConstString //----------------------------------------------------------------------------- inline const tchar* ConstString::text () const { #ifdef UNICODE return text16 (); #else return text8 (); #endif } //----------------------------------------------------------------------------- inline const char8* ConstString::text8 () const { return (!isWide && buffer8) ? buffer8: kEmptyString8; } //----------------------------------------------------------------------------- inline const char16* ConstString::text16 () const { return (isWide && buffer16) ? buffer16 : kEmptyString16; } //----------------------------------------------------------------------------- inline char8 ConstString::getChar8 (uint32 index) const { if (index < len && buffer8 && !isWide) return buffer8[index]; return 0; } //----------------------------------------------------------------------------- inline char16 ConstString::getChar16 (uint32 index) const { if (index < len && buffer16 && isWide) return buffer16[index]; return 0; } //----------------------------------------------------------------------------- inline tchar ConstString::getChar (uint32 index) const { #ifdef UNICODE return getChar16 (index); #else return getChar8 (index); #endif } //----------------------------------------------------------------------------- inline tchar ConstString::getCharAt (uint32 index) const { #ifdef UNICODE if (isWide) return getChar16 (index); #endif return static_cast<tchar> (getChar8 (index)); } //----------------------------------------------------------------------------- inline int64 ConstString::getNumber () const { int64 tmp = 0; scanInt64 (tmp); return tmp; } //----------------------------------------------------------------------------- inline bool ConstString::scanInt32_8 (const char8* text, int32& value, bool scanToEnd) { int64 tmp; if (scanInt64_8 (text, tmp, scanToEnd)) { value = (int32)tmp; return true; } return false; } //----------------------------------------------------------------------------- inline bool ConstString::scanInt32_16 (const char16* text, int32& value, bool scanToEnd) { int64 tmp; if (scanInt64_16 (text, tmp, scanToEnd)) { value = (int32)tmp; return true; } return false; } //----------------------------------------------------------------------------- inline bool ConstString::scanInt32 (const tchar* text, int32& value, bool scanToEnd) { int64 tmp; if (scanInt64 (text, tmp, scanToEnd)) { value = (int32)tmp; return true; } return false; } //----------------------------------------------------------------------------- inline bool ConstString::scanUInt32_8 (const char8* text, uint32& value, bool scanToEnd) { uint64 tmp; if (scanUInt64_8 (text, tmp, scanToEnd)) { value = (uint32)tmp; return true; } return false; } //----------------------------------------------------------------------------- inline bool ConstString::scanUInt32_16 (const char16* text, uint32& value, bool scanToEnd) { uint64 tmp; if (scanUInt64_16 (text, tmp, scanToEnd)) { value = (uint32)tmp; return true; } return false; } //----------------------------------------------------------------------------- inline bool ConstString::scanUInt32 (const tchar* text, uint32& value, bool scanToEnd) { uint64 tmp; if (scanUInt64 (text, tmp, scanToEnd)) { value = (uint32)tmp; return true; } return false; } //----------------------------------------------------------------------------- inline const char8* String::text8 () const { if (isWide && !isEmpty ()) checkToMultiByte (); // this should be avoided, since it can lead to information loss return ConstString::text8 (); } //----------------------------------------------------------------------------- inline const char16* String::text16 () const { if (!isWide && !isEmpty ()) { const_cast<String&> (*this).toWideString (); } return ConstString::text16 (); } //----------------------------------------------------------------------------- inline char8 String::getChar8 (uint32 index) const { if (isWide && !isEmpty ()) checkToMultiByte (); // this should be avoided, since it can lead to information loss return ConstString::getChar8 (index); } //----------------------------------------------------------------------------- inline char16 String::getChar16 (uint32 index) const { if (!isWide && !isEmpty ()) { const_cast<String&> (*this).toWideString (); } return ConstString::getChar16 (index); } //----------------------------------------------------------------------------- inline bool operator< (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) < 0) ? true : false;} inline bool operator<= (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) <= 0) ? true : false;} inline bool operator> (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) > 0) ? true : false;} inline bool operator>= (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) >= 0) ? true : false;} inline bool operator== (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) == 0) ? true : false;} inline bool operator!= (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) != 0) ? true : false;} inline bool operator< (const ConstString& s1, const char8* s2) {return (s1.compare (s2) < 0) ? true : false;} inline bool operator<= (const ConstString& s1, const char8* s2) {return (s1.compare (s2) <= 0) ? true : false;} inline bool operator> (const ConstString& s1, const char8* s2) {return (s1.compare (s2) > 0) ? true : false;} inline bool operator>= (const ConstString& s1, const char8* s2) {return (s1.compare (s2) >= 0) ? true : false;} inline bool operator== (const ConstString& s1, const char8* s2) {return (s1.compare (s2) == 0) ? true : false;} inline bool operator!= (const ConstString& s1, const char8* s2) {return (s1.compare (s2) != 0) ? true : false;} inline bool operator< (const char8* s1, const ConstString& s2) {return (s2.compare (s1) > 0) ? true : false;} inline bool operator<= (const char8* s1, const ConstString& s2) {return (s2.compare (s1) >= 0) ? true : false;} inline bool operator> (const char8* s1, const ConstString& s2) {return (s2.compare (s1) < 0) ? true : false;} inline bool operator>= (const char8* s1, const ConstString& s2) {return (s2.compare (s1) <= 0) ? true : false;} inline bool operator== (const char8* s1, const ConstString& s2) {return (s2.compare (s1) == 0) ? true : false;} inline bool operator!= (const char8* s1, const ConstString& s2) {return (s2.compare (s1) != 0) ? true : false;} inline bool operator< (const ConstString& s1, const char16* s2) {return (s1.compare (s2) < 0) ? true : false;} inline bool operator<= (const ConstString& s1, const char16* s2) {return (s1.compare (s2) <= 0) ? true : false;} inline bool operator> (const ConstString& s1, const char16* s2) {return (s1.compare (s2) > 0) ? true : false;} inline bool operator>= (const ConstString& s1, const char16* s2) {return (s1.compare (s2) >= 0) ? true : false;} inline bool operator== (const ConstString& s1, const char16* s2) {return (s1.compare (s2) == 0) ? true : false;} inline bool operator!= (const ConstString& s1, const char16* s2) {return (s1.compare (s2) != 0) ? true : false;} inline bool operator< (const char16* s1, const ConstString& s2) {return (s2.compare (s1) > 0) ? true : false;} inline bool operator<= (const char16* s1, const ConstString& s2) {return (s2.compare (s1) >= 0) ? true : false;} inline bool operator> (const char16* s1, const ConstString& s2) {return (s2.compare (s1) < 0) ? true : false;} inline bool operator>= (const char16* s1, const ConstString& s2) {return (s2.compare (s1) <= 0) ? true : false;} inline bool operator== (const char16* s1, const ConstString& s2) {return (s2.compare (s1) == 0) ? true : false;} inline bool operator!= (const char16* s1, const ConstString& s2) {return (s2.compare (s1) != 0) ? true : false;} // The following functions will only work with European Numbers! // (e.g. Arabic, Tibetan, and Khmer digits are not supported) extern int32 strnatcmp8 (const char8* s1, const char8* s2, bool caseSensitive = true); extern int32 strnatcmp16 (const char16* s1, const char16* s2, bool caseSensitive = true); inline int32 strnatcmp (const tchar* s1, const tchar* s2, bool caseSensitive = true) { #ifdef UNICODE return strnatcmp16 (s1, s2, caseSensitive); #else return strnatcmp8 (s1, s2, caseSensitive); #endif } //----------------------------------------------------------------------------- /** StringObject implements IStringResult and IString methods. It can therefore be exchanged with other Steinberg objects using one or both of these interfaces. \see String, ConstString */ //----------------------------------------------------------------------------- class StringObject : public FObject, public String, public IStringResult, public IString { public: //----------------------------------------------------------------------------- StringObject () {} StringObject (const char16* str, int32 n = -1, bool isTerminated = true) : String (str, n, isTerminated) {} StringObject (const char8* str, int32 n = -1, bool isTerminated = true) : String (str, n, isTerminated) {} StringObject (const StringObject& str, int32 n = -1) : String (str, n) {} StringObject (const String& str, int32 n = -1) : String (str, n) {} StringObject (const FVariant& var) : String (var) {} using String::operator=; // IStringResult ---------------------------------------------------------- virtual void PLUGIN_API setText (const char8* text) SMTG_OVERRIDE; //------------------------------------------------------------------------- // IString----------------------------------------------------------------- virtual void PLUGIN_API setText8 (const char8* text) SMTG_OVERRIDE; virtual void PLUGIN_API setText16 (const char16* text) SMTG_OVERRIDE; virtual const char8* PLUGIN_API getText8 () SMTG_OVERRIDE; virtual const char16* PLUGIN_API getText16 () SMTG_OVERRIDE; virtual void PLUGIN_API take (void* s, bool _isWide) SMTG_OVERRIDE; virtual bool PLUGIN_API isWideString () const SMTG_OVERRIDE; //------------------------------------------------------------------------- OBJ_METHODS (StringObject, FObject) FUNKNOWN_METHODS2 (IStringResult, IString, FObject) }; //------------------------------------------------------------------------ } // namespace Steinberg
0
0.979524
1
0.979524
game-dev
MEDIA
0.197847
game-dev
0.741988
1
0.741988
Mat0u5/LifeSeries
2,637
src/main/java/net/mat0u5/lifeseries/config/ConfigFileEntry.java
package net.mat0u5.lifeseries.config; import net.mat0u5.lifeseries.Main; import net.mat0u5.lifeseries.utils.enums.ConfigTypes; import net.mat0u5.lifeseries.utils.other.TextUtils; import java.util.List; public class ConfigFileEntry<T> { public final String key; public T defaultValue; public final ConfigTypes type; public final String displayName; public final String description; public final String groupInfo; public final List<String> args; public ConfigFileEntry(String key, T defaultValue, String groupInfo, String displayName, String description) { this(key, defaultValue, getTypeFromValue(defaultValue), groupInfo, displayName, description); } public ConfigFileEntry(String key, T defaultValue, ConfigTypes type, String groupInfo, String displayName, String description) { this(key, defaultValue, type, groupInfo, displayName, description, null); } public ConfigFileEntry(String key, T defaultValue, ConfigTypes type, String groupInfo, String displayName, String description, List<String> args) { this.key = key; this.defaultValue = defaultValue; this.type = type; this.displayName = displayName; this.description = description; this.groupInfo = groupInfo; this.args = args; } public static ConfigTypes getTypeFromValue(Object defaultValue) { if (defaultValue instanceof Integer) { return ConfigTypes.INTEGER; } else if (defaultValue instanceof Boolean) { return ConfigTypes.BOOLEAN; } else if (defaultValue instanceof Double) { return ConfigTypes.DOUBLE; } else if (defaultValue instanceof String) { return ConfigTypes.STRING; } return ConfigTypes.NULL; } @SuppressWarnings("unchecked") public T get(ConfigManager config) { try { if (defaultValue instanceof Integer i) { return (T) Integer.valueOf(config.getOrCreateInt(key, i)); } else if (defaultValue instanceof Boolean b) { return (T) Boolean.valueOf(config.getOrCreateBoolean(key, b)); } else if (defaultValue instanceof Double d) { return (T) Double.valueOf(config.getOrCreateDouble(key, d)); } else if (defaultValue instanceof String s) { return (T) config.getOrCreateProperty(key, s); } }catch(Exception e) {} Main.LOGGER.error(TextUtils.formatString("Config value {} was null, returning default value - {}", key, defaultValue)); return defaultValue; } }
0
0.979611
1
0.979611
game-dev
MEDIA
0.41909
game-dev
0.936617
1
0.936617
wheelos/apollo-lite
13,436
third_party/tf2/include/tf2/LinearMath/Scalar.h
/* Copyright (c) 2003-2009 Erwin Coumans http://bullet.googlecode.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TF2_SCALAR_H #define TF2_SCALAR_H #ifdef TF2_MANAGED_CODE //Aligned data types not supported in managed code #pragma unmanaged #endif #include <math.h> #include <stdlib.h>//size_t for MSVC 6.0 #include <cstdlib> #include <cfloat> #include <float.h> #if defined(DEBUG) || defined (_DEBUG) #define TF2_DEBUG #endif #ifdef _WIN32 #if defined(__MINGW32__) || defined(__CYGWIN__) || (defined (_MSC_VER) && _MSC_VER < 1300) #define TF2SIMD_FORCE_INLINE inline #define ATTRIBUTE_ALIGNED16(a) a #define ATTRIBUTE_ALIGNED64(a) a #define ATTRIBUTE_ALIGNED128(a) a #else //#define TF2_HAS_ALIGNED_ALLOCATOR #pragma warning(disable : 4324) // disable padding warning // #pragma warning(disable:4530) // Disable the exception disable but used in MSCV Stl warning. // #pragma warning(disable:4996) //Turn off warnings about deprecated C routines // #pragma warning(disable:4786) // Disable the "debug name too long" warning #define TF2SIMD_FORCE_INLINE __forceinline #define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a #define ATTRIBUTE_ALIGNED64(a) __declspec(align(64)) a #define ATTRIBUTE_ALIGNED128(a) __declspec (align(128)) a #ifdef _XBOX #define TF2_USE_VMX128 #include <ppcintrinsics.h> #define TF2_HAVE_NATIVE_FSEL #define tf2Fsel(a,b,c) __fsel((a),(b),(c)) #else #endif//_XBOX #endif //__MINGW32__ #include <assert.h> #ifdef TF2_DEBUG #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) _c #define tf2Unlikely(_c) _c #else #if defined (__CELLOS_LV2__) #define TF2SIMD_FORCE_INLINE inline #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) #define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64))) #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) #ifndef assert #include <assert.h> #endif #ifdef TF2_DEBUG #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) _c #define tf2Unlikely(_c) _c #else #ifdef USE_LIBSPE2 #define TF2SIMD_FORCE_INLINE __inline #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) #define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64))) #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) #ifndef assert #include <assert.h> #endif #ifdef TF2_DEBUG #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) __builtin_expect((_c), 1) #define tf2Unlikely(_c) __builtin_expect((_c), 0) #else //non-windows systems #define TF2SIMD_FORCE_INLINE inline ///@todo: check out alignment methods for other platforms/compilers ///#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) ///#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64))) ///#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) #define ATTRIBUTE_ALIGNED16(a) a #define ATTRIBUTE_ALIGNED64(a) a #define ATTRIBUTE_ALIGNED128(a) a #ifndef assert #include <assert.h> #endif #if defined(DEBUG) || defined (_DEBUG) #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) _c #define tf2Unlikely(_c) _c #endif // LIBSPE2 #endif //__CELLOS_LV2__ #endif ///The tf2Scalar type abstracts floating point numbers, to easily switch between double and single floating point precision. typedef double tf2Scalar; //this number could be bigger in double precision #define TF2_LARGE_FLOAT 1e30 #define TF2_DECLARE_ALIGNED_ALLOCATOR() \ TF2SIMD_FORCE_INLINE void* operator new(size_t sizeInBytes) { return tf2AlignedAlloc(sizeInBytes,16); } \ TF2SIMD_FORCE_INLINE void operator delete(void* ptr) { tf2AlignedFree(ptr); } \ TF2SIMD_FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \ TF2SIMD_FORCE_INLINE void operator delete(void*, void*) { } \ TF2SIMD_FORCE_INLINE void* operator new[](size_t sizeInBytes) { return tf2AlignedAlloc(sizeInBytes,16); } \ TF2SIMD_FORCE_INLINE void operator delete[](void* ptr) { tf2AlignedFree(ptr); } \ TF2SIMD_FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \ TF2SIMD_FORCE_INLINE void operator delete[](void*, void*) { } \ TF2SIMD_FORCE_INLINE tf2Scalar tf2Sqrt(tf2Scalar x) { return sqrt(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Fabs(tf2Scalar x) { return fabs(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Cos(tf2Scalar x) { return cos(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Sin(tf2Scalar x) { return sin(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Tan(tf2Scalar x) { return tan(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Acos(tf2Scalar x) { if (x<tf2Scalar(-1)) x=tf2Scalar(-1); if (x>tf2Scalar(1)) x=tf2Scalar(1); return acos(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Asin(tf2Scalar x) { if (x<tf2Scalar(-1)) x=tf2Scalar(-1); if (x>tf2Scalar(1)) x=tf2Scalar(1); return asin(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Atan(tf2Scalar x) { return atan(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Atan2(tf2Scalar x, tf2Scalar y) { return atan2(x, y); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Exp(tf2Scalar x) { return exp(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Log(tf2Scalar x) { return log(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Pow(tf2Scalar x,tf2Scalar y) { return pow(x,y); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Fmod(tf2Scalar x,tf2Scalar y) { return fmod(x,y); } #define TF2SIMD_2_PI tf2Scalar(6.283185307179586232) #define TF2SIMD_PI (TF2SIMD_2_PI * tf2Scalar(0.5)) #define TF2SIMD_HALF_PI (TF2SIMD_2_PI * tf2Scalar(0.25)) #define TF2SIMD_RADS_PER_DEG (TF2SIMD_2_PI / tf2Scalar(360.0)) #define TF2SIMD_DEGS_PER_RAD (tf2Scalar(360.0) / TF2SIMD_2_PI) #define TF2SIMDSQRT12 tf2Scalar(0.7071067811865475244008443621048490) #define tf2RecipSqrt(x) ((tf2Scalar)(tf2Scalar(1.0)/tf2Sqrt(tf2Scalar(x)))) /* reciprocal square root */ #define TF2SIMD_EPSILON DBL_EPSILON #define TF2SIMD_INFINITY DBL_MAX TF2SIMD_FORCE_INLINE tf2Scalar tf2Atan2Fast(tf2Scalar y, tf2Scalar x) { tf2Scalar coeff_1 = TF2SIMD_PI / 4.0f; tf2Scalar coeff_2 = 3.0f * coeff_1; tf2Scalar abs_y = tf2Fabs(y); tf2Scalar angle; if (x >= 0.0f) { tf2Scalar r = (x - abs_y) / (x + abs_y); angle = coeff_1 - coeff_1 * r; } else { tf2Scalar r = (x + abs_y) / (abs_y - x); angle = coeff_2 - coeff_1 * r; } return (y < 0.0f) ? -angle : angle; } TF2SIMD_FORCE_INLINE bool tf2FuzzyZero(tf2Scalar x) { return tf2Fabs(x) < TF2SIMD_EPSILON; } TF2SIMD_FORCE_INLINE bool tf2Equal(tf2Scalar a, tf2Scalar eps) { return (((a) <= eps) && !((a) < -eps)); } TF2SIMD_FORCE_INLINE bool tf2GreaterEqual (tf2Scalar a, tf2Scalar eps) { return (!((a) <= eps)); } TF2SIMD_FORCE_INLINE int tf2IsNegative(tf2Scalar x) { return x < tf2Scalar(0.0) ? 1 : 0; } TF2SIMD_FORCE_INLINE tf2Scalar tf2Radians(tf2Scalar x) { return x * TF2SIMD_RADS_PER_DEG; } TF2SIMD_FORCE_INLINE tf2Scalar tf2Degrees(tf2Scalar x) { return x * TF2SIMD_DEGS_PER_RAD; } #define TF2_DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name #ifndef tf2Fsel TF2SIMD_FORCE_INLINE tf2Scalar tf2Fsel(tf2Scalar a, tf2Scalar b, tf2Scalar c) { return a >= 0 ? b : c; } #endif #define tf2Fsels(a,b,c) (tf2Scalar)tf2Fsel(a,b,c) TF2SIMD_FORCE_INLINE bool tf2MachineIsLittleEndian() { long int i = 1; const char *p = (const char *) &i; if (p[0] == 1) // Lowest address contains the least significant byte return true; else return false; } ///tf2Select avoids branches, which makes performance much better for consoles like Playstation 3 and XBox 360 ///Thanks Phil Knight. See also http://www.cellperformance.com/articles/2006/04/more_techniques_for_eliminatin_1.html TF2SIMD_FORCE_INLINE unsigned tf2Select(unsigned condition, unsigned valueIfConditionNonZero, unsigned valueIfConditionZero) { // Set testNz to 0xFFFFFFFF if condition is nonzero, 0x00000000 if condition is zero // Rely on positive value or'ed with its negative having sign bit on // and zero value or'ed with its negative (which is still zero) having sign bit off // Use arithmetic shift right, shifting the sign bit through all 32 bits unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31); unsigned testEqz = ~testNz; return ((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz)); } TF2SIMD_FORCE_INLINE int tf2Select(unsigned condition, int valueIfConditionNonZero, int valueIfConditionZero) { unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31); unsigned testEqz = ~testNz; return static_cast<int>((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz)); } TF2SIMD_FORCE_INLINE float tf2Select(unsigned condition, float valueIfConditionNonZero, float valueIfConditionZero) { #ifdef TF2_HAVE_NATIVE_FSEL return (float)tf2Fsel((tf2Scalar)condition - tf2Scalar(1.0f), valueIfConditionNonZero, valueIfConditionZero); #else return (condition != 0) ? valueIfConditionNonZero : valueIfConditionZero; #endif } template<typename T> TF2SIMD_FORCE_INLINE void tf2Swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } //PCK: endian swapping functions TF2SIMD_FORCE_INLINE unsigned tf2SwapEndian(unsigned val) { return (((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24)); } TF2SIMD_FORCE_INLINE unsigned short tf2SwapEndian(unsigned short val) { return static_cast<unsigned short>(((val & 0xff00) >> 8) | ((val & 0x00ff) << 8)); } TF2SIMD_FORCE_INLINE unsigned tf2SwapEndian(int val) { return tf2SwapEndian((unsigned)val); } TF2SIMD_FORCE_INLINE unsigned short tf2SwapEndian(short val) { return tf2SwapEndian((unsigned short) val); } ///tf2SwapFloat uses using char pointers to swap the endianness ////tf2SwapFloat/tf2SwapDouble will NOT return a float, because the machine might 'correct' invalid floating point values ///Not all values of sign/exponent/mantissa are valid floating point numbers according to IEEE 754. ///When a floating point unit is faced with an invalid value, it may actually change the value, or worse, throw an exception. ///In most systems, running user mode code, you wouldn't get an exception, but instead the hardware/os/runtime will 'fix' the number for you. ///so instead of returning a float/double, we return integer/long long integer TF2SIMD_FORCE_INLINE unsigned int tf2SwapEndianFloat(float d) { unsigned int a = 0; unsigned char *dst = (unsigned char *)&a; unsigned char *src = (unsigned char *)&d; dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; return a; } // unswap using char pointers TF2SIMD_FORCE_INLINE float tf2UnswapEndianFloat(unsigned int a) { float d = 0.0f; unsigned char *src = (unsigned char *)&a; unsigned char *dst = (unsigned char *)&d; dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; return d; } // swap using char pointers TF2SIMD_FORCE_INLINE void tf2SwapEndianDouble(double d, unsigned char* dst) { unsigned char *src = (unsigned char *)&d; dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; } // unswap using char pointers TF2SIMD_FORCE_INLINE double tf2UnswapEndianDouble(const unsigned char *src) { double d = 0.0; unsigned char *dst = (unsigned char *)&d; dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; return d; } // returns normalized value in range [-TF2SIMD_PI, TF2SIMD_PI] TF2SIMD_FORCE_INLINE tf2Scalar tf2NormalizeAngle(tf2Scalar angleInRadians) { angleInRadians = tf2Fmod(angleInRadians, TF2SIMD_2_PI); if(angleInRadians < -TF2SIMD_PI) { return angleInRadians + TF2SIMD_2_PI; } else if(angleInRadians > TF2SIMD_PI) { return angleInRadians - TF2SIMD_2_PI; } else { return angleInRadians; } } ///rudimentary class to provide type info struct tf2TypedObject { tf2TypedObject(int objectType) :m_objectType(objectType) { } int m_objectType; inline int getObjectType() const { return m_objectType; } }; #endif //TF2SIMD___SCALAR_H
0
0.78631
1
0.78631
game-dev
MEDIA
0.897412
game-dev
0.592823
1
0.592823
utkabobr/SliceBeam
6,129
app/src/main/jni/libslic3r/BuildVolume.hpp
///|/ Copyright (c) Prusa Research 2021 - 2022 Enrico Turri @enricoturri1966, Vojtěch Bubník @bubnikv, Lukáš Matěna @lukasmatena, Filip Sykala @Jony01 ///|/ ///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher ///|/ #ifndef slic3r_BuildVolume_hpp_ #define slic3r_BuildVolume_hpp_ #include "Point.hpp" #include "Geometry/Circle.hpp" #include "Polygon.hpp" #include "BoundingBox.hpp" #include <admesh/stl.h> #include <string_view> namespace Slic3r { struct GCodeProcessorResult; // For collision detection of objects and G-code (extrusion paths) against the build volume. class BuildVolume { public: enum class Type : unsigned char { // Not set yet or undefined. Invalid, // Rectangular print bed. Most common, cheap to work with. Rectangle, // Circular print bed. Common on detals, cheap to work with. Circle, // Convex print bed. Complex to process. Convex, // Some non convex shape. Custom }; // Initialized to empty, all zeros, Invalid. BuildVolume() {} // Initialize from PrintConfig::bed_shape and PrintConfig::max_print_height BuildVolume(const std::vector<Vec2d> &bed_shape, const double max_print_height); // Source data, unscaled coordinates. const std::vector<Vec2d>& bed_shape() const { return m_bed_shape; } double max_print_height() const { return m_max_print_height; } // Derived data Type type() const { return m_type; } // Format the type for console output. static std::string_view type_name(Type type); std::string_view type_name() const { return type_name(m_type); } bool valid() const { return m_type != Type::Invalid; } // Same as bed_shape(), but scaled coordinates. const Polygon& polygon() const { return m_polygon; } // Bounding box of polygon(), scaled. const BoundingBox& bounding_box() const { return m_bbox; } // Bounding volume of bed_shape(), max_print_height(), unscaled. const BoundingBoxf3& bounding_volume() const { return m_bboxf; } BoundingBoxf bounding_volume2d() const { return { to_2d(m_bboxf.min), to_2d(m_bboxf.max) }; } // Center of the print bed, unscaled. Vec2d bed_center() const { return to_2d(m_bboxf.center()); } // Convex hull of polygon(), scaled. const Polygon& convex_hull() const { return m_convex_hull; } // Smallest enclosing circle of polygon(), scaled. const Geometry::Circled& circle() const { return m_circle; } enum class ObjectState : unsigned char { // Inside the build volume, thus printable. Inside, // Colliding with the build volume boundary, thus not printable and error is shown. Colliding, // Outside of the build volume means the object is ignored: Not printed and no error is shown. Outside, // Completely below the print bed. The same as Outside, but an object with one printable part below the print bed // and at least one part above the print bed is still printable. Below, }; // 1) Tests called on the plater. // Using SceneEpsilon for all tests. static constexpr const double SceneEpsilon = EPSILON; // Called by Plater to update Inside / Colliding / Outside state of ModelObjects before slicing. // Called from Model::update_print_volume_state() -> ModelObject::update_instances_print_volume_state() // Using SceneEpsilon ObjectState object_state(const indexed_triangle_set &its, const Transform3f &trafo, bool may_be_below_bed, bool ignore_bottom = true) const; // Called by GLVolumeCollection::check_outside_state() after an object is manipulated with gizmos for example. // Called for a rectangular bed: ObjectState volume_state_bbox(const BoundingBoxf3& volume_bbox, bool ignore_bottom = true) const; // 2) Test called on G-code paths. // Using BedEpsilon for all tests. static constexpr const double BedEpsilon = 3. * EPSILON; // Called on final G-code paths. //FIXME The test does not take the thickness of the extrudates into account! bool all_paths_inside(const GCodeProcessorResult& paths, const BoundingBoxf3& paths_bbox, bool ignore_bottom = true) const; const std::pair<std::vector<Vec2d>, std::vector<Vec2d>>& top_bottom_convex_hull_decomposition_scene() const { return m_top_bottom_convex_hull_decomposition_scene; } const std::pair<std::vector<Vec2d>, std::vector<Vec2d>>& top_bottom_convex_hull_decomposition_bed() const { return m_top_bottom_convex_hull_decomposition_bed; } private: // Source definition of the print bed geometry (PrintConfig::bed_shape) std::vector<Vec2d> m_bed_shape; // Source definition of the print volume height (PrintConfig::max_print_height) double m_max_print_height; // Derived values. Type m_type { Type::Invalid }; // Geometry of the print bed, scaled copy of m_bed_shape. Polygon m_polygon; // Scaled snug bounding box around m_polygon. BoundingBox m_bbox; // 3D bounding box around m_shape, m_max_print_height. BoundingBoxf3 m_bboxf; // Area of m_polygon, scaled. double m_area { 0. }; // Convex hull of m_polygon, scaled. Polygon m_convex_hull; // For collision detection against a convex build volume. Only filled in for m_type == Convex or Custom. // Variant with SceneEpsilon applied. std::pair<std::vector<Vec2d>, std::vector<Vec2d>> m_top_bottom_convex_hull_decomposition_scene; // Variant with BedEpsilon applied. std::pair<std::vector<Vec2d>, std::vector<Vec2d>> m_top_bottom_convex_hull_decomposition_bed; // Smallest enclosing circle of m_polygon, scaled. Geometry::Circled m_circle { Vec2d::Zero(), 0 }; }; } // namespace Slic3r #endif // slic3r_BuildVolume_hpp_
0
0.976513
1
0.976513
game-dev
MEDIA
0.529833
game-dev
0.968498
1
0.968498
llde/xOBSE
5,710
obse/obse/Commands_Faction.cpp
#include "Commands_Faction.h" #include "ParamInfos.h" #include "Script.h" #if OBLIVION #include "GameObjects.h" #include "GameExtraData.h" #include "GameAPI.h" #include "GameForms.h" #include "GameProcess.h" static bool Cmd_IsFactionEvil_Execute(COMMAND_ARGS) { TESFaction* fact = NULL; *result = 0; if (ExtractArgs(PASS_EXTRACT_ARGS, &fact)) { if (fact && fact->IsEvil()) *result = 1; } return true; } static bool Cmd_IsFactionHidden_Execute(COMMAND_ARGS) { TESFaction* fact = NULL; *result = 0; if (ExtractArgs(PASS_EXTRACT_ARGS, &fact)) { if (fact && fact->IsHidden()) *result = 1; } return true; } static bool Cmd_FactionHasSpecialCombat_Execute(COMMAND_ARGS) { TESFaction* fact = NULL; *result = 0; if (ExtractArgs(PASS_EXTRACT_ARGS, &fact)) { if (fact && fact->HasSpecialCombat()) *result = 1; } return true; } static bool Cmd_SetFactionEvil_Execute(COMMAND_ARGS) { TESFaction* fact = NULL; UInt32 bMod = 0; if (ExtractArgs(PASS_EXTRACT_ARGS, &fact, &bMod)) { if (fact) fact->SetEvil(bMod ? true : false); } return true; } static bool Cmd_SetFactionHidden_Execute(COMMAND_ARGS) { TESFaction* fact = NULL; UInt32 bMod = 0; if (ExtractArgs(PASS_EXTRACT_ARGS, &fact, &bMod)) { if (fact) fact->SetHidden(bMod ? true : false); } return true; } static bool Cmd_SetFactionSpecialCombat_Execute(COMMAND_ARGS) { TESFaction* fact = NULL; UInt32 bMod = 0; if (ExtractArgs(PASS_EXTRACT_ARGS, &fact, &bMod)) { if (fact) fact->SetSpecialCombat(bMod ? true : false); } return true; } static TESActorBase* ExtractActorBase(COMMAND_ARGS) { TESActorBase* actorBase = NULL; TESForm* actorForm = NULL; ExtractArgs(PASS_EXTRACT_ARGS, &actorForm); if (!actorForm) if (thisObj) actorForm = thisObj->baseForm; if (actorForm) { actorBase = (TESActorBase*)Oblivion_DynamicCast(actorForm, 0, RTTI_TESForm, RTTI_TESActorBase, 0); } return actorBase; } static TESActorBase* ExtractSetActorBase(COMMAND_ARGS, UInt32* bMod) { TESActorBase* actorBase = NULL; TESForm* actorForm = NULL; *bMod = 0; ExtractArgs(PASS_EXTRACT_ARGS, bMod, &actorForm); if (!actorForm) if (thisObj) actorForm = thisObj->baseForm; if (actorForm) { actorBase = (TESActorBase*)Oblivion_DynamicCast(actorForm, 0, RTTI_TESForm, RTTI_TESActorBase, 0); } return actorBase; } static bool Cmd_GetNumFactions_Execute(COMMAND_ARGS) { *result = 0; TESActorBase* actorBase = ExtractActorBase(PASS_COMMAND_ARGS); if (actorBase) { *result = FactionListVisitor(&(actorBase->actorBaseData.factionList)).Count(); } return true; } static bool Cmd_GetNthFaction_Execute(COMMAND_ARGS) { UInt32 factionIdx = 0; UInt32* refResult = (UInt32*)result; *refResult = 0; TESActorBase* actorBase = ExtractSetActorBase(PASS_COMMAND_ARGS, &factionIdx); if (actorBase) { TESActorBaseData::FactionListData* data = FactionListVisitor(&(actorBase->actorBaseData.factionList)).GetNthInfo(factionIdx); if (data) *refResult = data->faction->refID; } return true; } static bool Cmd_GetNumRanks_Execute(COMMAND_ARGS) { TESFaction* fact = NULL; *result = 0; if (ExtractArgs(PASS_EXTRACT_ARGS, &fact)) *result = FactionRankVisitor(&(fact->ranks)).Count(); return true; } #endif static ParamInfo kParams_OneIntOneOptionalActorBase[2] = { { "bool", kParamType_Integer, 0 }, { "base actor", kParamType_ActorBase, 1 }, }; CommandInfo kCommandInfo_GetNumFactions = { "GetNumFactions", "", 0, "returns the number of factions to which an actor belongs", 0, 1, kParams_OneOptionalActorBase, HANDLER(Cmd_GetNumFactions_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetNthFaction = { "GetNthFaction", "", 0, "returns the nth faction to which an actor belongs", 0, 2, kParams_OneIntOneOptionalActorBase, HANDLER(Cmd_GetNthFaction_Execute), Cmd_Default_Parse, NULL, 0 }; static ParamInfo kParams_OneFaction[1] = { { "faction", kParamType_Faction, 0 }, }; CommandInfo kCommandInfo_IsFactionEvil = { "IsFactionEvil", "", 0, "returns true if the faction is marked as evil", 0, 1, kParams_OneFaction, HANDLER(Cmd_IsFactionEvil_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsFactionHidden = { "IsFactionHidden", "", 0, "returns true if the faction is marked as hidden", 0, 1, kParams_OneFaction, HANDLER(Cmd_IsFactionHidden_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_FactionHasSpecialCombat = { "FactionHasSpecialCombat", "", 0, "returns true if the faction has special combat", 0, 1, kParams_OneFaction, HANDLER(Cmd_FactionHasSpecialCombat_Execute), Cmd_Default_Parse, NULL, 0 }; static ParamInfo kParams_SetFactionFlag[2] = { { "faction", kParamType_Faction, 0 }, { "bool", kParamType_Integer, 0 }, }; CommandInfo kCommandInfo_SetFactionEvil = { "SetFactionEvil", "", 0, "changes the evil flag on the faction", 0, 2, kParams_SetFactionFlag, HANDLER(Cmd_SetFactionEvil_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetFactionHidden = { "SetFactionHidden", "", 0, "changes the hidden flag on the faction", 0, 2, kParams_SetFactionFlag, HANDLER(Cmd_SetFactionHidden_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetFactionSpecialCombat = { "SetFactionSpecialCombat", "", 0, "changes the special combat flag on the faction", 0, 2, kParams_SetFactionFlag, HANDLER(Cmd_SetFactionSpecialCombat_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetNumRanks = { "GetNumRanks", "GetNumFactionRanks", 0, "returns the number of ranks in the faction", 0, 1, kParams_OneFaction, HANDLER(Cmd_GetNumRanks_Execute), Cmd_Default_Parse, NULL, 0 };
0
0.73113
1
0.73113
game-dev
MEDIA
0.934515
game-dev
0.780069
1
0.780069
evaera/matter
1,041
example/src/shared/setupTags.lua
local CollectionService = game:GetService("CollectionService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Components = require(ReplicatedStorage.Shared.components) local boundTags = { Spinner = Components.Spinner, } local function setupTags(world) local function spawnBound(instance, component) local id = world:spawn( component(), Components.Model({ model = instance, }), Components.Transform({ cframe = instance.PrimaryPart.CFrame, }) ) instance:SetAttribute("serverEntityId", id) end for tagName, component in pairs(boundTags) do for _, instance in ipairs(CollectionService:GetTagged(tagName)) do spawnBound(instance, component) end CollectionService:GetInstanceAddedSignal(tagName):Connect(function(instance) spawnBound(instance, component) end) CollectionService:GetInstanceRemovedSignal(tagName):Connect(function(instance) local id = instance:GetAttribute("serverEntityId") if id then world:despawn(id) end end) end end return setupTags
0
0.915732
1
0.915732
game-dev
MEDIA
0.950456
game-dev
0.930504
1
0.930504
pmq20/node-packer
9,668
lts/deps/v8/src/heap/scavenger.h
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_HEAP_SCAVENGER_H_ #define V8_HEAP_SCAVENGER_H_ #include "src/base/platform/condition-variable.h" #include "src/heap/local-allocator.h" #include "src/heap/objects-visiting.h" #include "src/heap/slot-set.h" #include "src/heap/worklist.h" namespace v8 { namespace internal { class OneshotBarrier; enum class CopyAndForwardResult { SUCCESS_YOUNG_GENERATION, SUCCESS_OLD_GENERATION, FAILURE }; using ObjectAndSize = std::pair<HeapObject, int>; using SurvivingNewLargeObjectsMap = std::unordered_map<HeapObject, Map, Object::Hasher>; using SurvivingNewLargeObjectMapEntry = std::pair<HeapObject, Map>; constexpr int kEphemeronTableListSegmentSize = 128; using EphemeronTableList = Worklist<EphemeronHashTable, kEphemeronTableListSegmentSize>; class ScavengerCollector { public: static const int kMaxScavengerTasks = 8; static const int kMaxWaitTimeMs = 2; explicit ScavengerCollector(Heap* heap); void CollectGarbage(); private: void MergeSurvivingNewLargeObjects( const SurvivingNewLargeObjectsMap& objects); int NumberOfScavengeTasks(); void ProcessWeakReferences(EphemeronTableList* ephemeron_table_list); void ClearYoungEphemerons(EphemeronTableList* ephemeron_table_list); void ClearOldEphemerons(); void HandleSurvivingNewLargeObjects(); Isolate* const isolate_; Heap* const heap_; base::Semaphore parallel_scavenge_semaphore_; SurvivingNewLargeObjectsMap surviving_new_large_objects_; friend class Scavenger; }; class Scavenger { public: struct PromotionListEntry { HeapObject heap_object; Map map; int size; }; class PromotionList { public: class View { public: View(PromotionList* promotion_list, int task_id) : promotion_list_(promotion_list), task_id_(task_id) {} inline void PushRegularObject(HeapObject object, int size); inline void PushLargeObject(HeapObject object, Map map, int size); inline bool IsEmpty(); inline size_t LocalPushSegmentSize(); inline bool Pop(struct PromotionListEntry* entry); inline bool IsGlobalPoolEmpty(); inline bool ShouldEagerlyProcessPromotionList(); private: PromotionList* promotion_list_; int task_id_; }; explicit PromotionList(int num_tasks) : regular_object_promotion_list_(num_tasks), large_object_promotion_list_(num_tasks) {} inline void PushRegularObject(int task_id, HeapObject object, int size); inline void PushLargeObject(int task_id, HeapObject object, Map map, int size); inline bool IsEmpty(); inline size_t LocalPushSegmentSize(int task_id); inline bool Pop(int task_id, struct PromotionListEntry* entry); inline bool IsGlobalPoolEmpty(); inline bool ShouldEagerlyProcessPromotionList(int task_id); private: static const int kRegularObjectPromotionListSegmentSize = 256; static const int kLargeObjectPromotionListSegmentSize = 4; using RegularObjectPromotionList = Worklist<ObjectAndSize, kRegularObjectPromotionListSegmentSize>; using LargeObjectPromotionList = Worklist<PromotionListEntry, kLargeObjectPromotionListSegmentSize>; RegularObjectPromotionList regular_object_promotion_list_; LargeObjectPromotionList large_object_promotion_list_; }; static const int kCopiedListSegmentSize = 256; using CopiedList = Worklist<ObjectAndSize, kCopiedListSegmentSize>; Scavenger(ScavengerCollector* collector, Heap* heap, bool is_logging, CopiedList* copied_list, PromotionList* promotion_list, EphemeronTableList* ephemeron_table_list, int task_id); // Entry point for scavenging an old generation page. For scavenging single // objects see RootScavengingVisitor and ScavengeVisitor below. void ScavengePage(MemoryChunk* page); // Processes remaining work (=objects) after single objects have been // manually scavenged using ScavengeObject or CheckAndScavengeObject. void Process(OneshotBarrier* barrier = nullptr); // Finalize the Scavenger. Needs to be called from the main thread. void Finalize(); void AddEphemeronHashTable(EphemeronHashTable table); size_t bytes_copied() const { return copied_size_; } size_t bytes_promoted() const { return promoted_size_; } private: // Number of objects to process before interrupting for potentially waking // up other tasks. static const int kInterruptThreshold = 128; static const int kInitialLocalPretenuringFeedbackCapacity = 256; inline Heap* heap() { return heap_; } inline void PageMemoryFence(MaybeObject object); void AddPageToSweeperIfNecessary(MemoryChunk* page); // Potentially scavenges an object referenced from |slot| if it is // indeed a HeapObject and resides in from space. template <typename TSlot> inline SlotCallbackResult CheckAndScavengeObject(Heap* heap, TSlot slot); // Scavenges an object |object| referenced from slot |p|. |object| is required // to be in from space. template <typename THeapObjectSlot> inline SlotCallbackResult ScavengeObject(THeapObjectSlot p, HeapObject object); // Copies |source| to |target| and sets the forwarding pointer in |source|. V8_INLINE bool MigrateObject(Map map, HeapObject source, HeapObject target, int size); V8_INLINE SlotCallbackResult RememberedSetEntryNeeded(CopyAndForwardResult result); template <typename THeapObjectSlot> V8_INLINE CopyAndForwardResult SemiSpaceCopyObject(Map map, THeapObjectSlot slot, HeapObject object, int object_size, ObjectFields object_fields); template <typename THeapObjectSlot> V8_INLINE CopyAndForwardResult PromoteObject(Map map, THeapObjectSlot slot, HeapObject object, int object_size, ObjectFields object_fields); template <typename THeapObjectSlot> V8_INLINE SlotCallbackResult EvacuateObject(THeapObjectSlot slot, Map map, HeapObject source); V8_INLINE bool HandleLargeObject(Map map, HeapObject object, int object_size, ObjectFields object_fields); // Different cases for object evacuation. template <typename THeapObjectSlot> V8_INLINE SlotCallbackResult EvacuateObjectDefault(Map map, THeapObjectSlot slot, HeapObject object, int object_size, ObjectFields object_fields); template <typename THeapObjectSlot> inline SlotCallbackResult EvacuateThinString(Map map, THeapObjectSlot slot, ThinString object, int object_size); template <typename THeapObjectSlot> inline SlotCallbackResult EvacuateShortcutCandidate(Map map, THeapObjectSlot slot, ConsString object, int object_size); void IterateAndScavengePromotedObject(HeapObject target, Map map, int size); void RememberPromotedEphemeron(EphemeronHashTable table, int index); ScavengerCollector* const collector_; Heap* const heap_; PromotionList::View promotion_list_; CopiedList::View copied_list_; EphemeronTableList::View ephemeron_table_list_; Heap::PretenuringFeedbackMap local_pretenuring_feedback_; size_t copied_size_; size_t promoted_size_; LocalAllocator allocator_; SurvivingNewLargeObjectsMap surviving_new_large_objects_; EphemeronRememberedSet ephemeron_remembered_set_; const bool is_logging_; const bool is_incremental_marking_; const bool is_compacting_; friend class IterateAndScavengePromotedObjectsVisitor; friend class RootScavengeVisitor; friend class ScavengeVisitor; }; // Helper class for turning the scavenger into an object visitor that is also // filtering out non-HeapObjects and objects which do not reside in new space. class RootScavengeVisitor final : public RootVisitor { public: explicit RootScavengeVisitor(Scavenger* scavenger); void VisitRootPointer(Root root, const char* description, FullObjectSlot p) final; void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) final; private: void ScavengePointer(FullObjectSlot p); Scavenger* const scavenger_; }; class ScavengeVisitor final : public NewSpaceVisitor<ScavengeVisitor> { public: explicit ScavengeVisitor(Scavenger* scavenger); V8_INLINE void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) final; V8_INLINE void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) final; V8_INLINE void VisitCodeTarget(Code host, RelocInfo* rinfo) final; V8_INLINE void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) final; V8_INLINE int VisitEphemeronHashTable(Map map, EphemeronHashTable object); private: template <typename TSlot> V8_INLINE void VisitHeapObjectImpl(TSlot slot, HeapObject heap_object); template <typename TSlot> V8_INLINE void VisitPointersImpl(HeapObject host, TSlot start, TSlot end); Scavenger* const scavenger_; }; } // namespace internal } // namespace v8 #endif // V8_HEAP_SCAVENGER_H_
0
0.980391
1
0.980391
game-dev
MEDIA
0.298658
game-dev
0.966744
1
0.966744
lf201014/STS_ThMod_MRS
2,550
src/main/java/ThMod/action/DiscToHandATKOnly.java
package ThMod.action; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.CardGroup; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.UIStrings; public class DiscToHandATKOnly extends AbstractGameAction{ private static final UIStrings uiStrings = CardCrawlGame.languagePack.getUIString("AttackFromDeckToHandAction"); public static final String[] TEXT = uiStrings.TEXT; private AbstractPlayer p; public DiscToHandATKOnly(int amount){ this.p = AbstractDungeon.player; setValues(this.p, AbstractDungeon.player, amount); this.actionType = AbstractGameAction.ActionType.CARD_MANIPULATION; this.duration = Settings.ACTION_DUR_MED; } public void update(){ CardGroup tmp; if (this.duration == Settings.ACTION_DUR_MED){ tmp = new CardGroup(CardGroup.CardGroupType.UNSPECIFIED); for (AbstractCard c : this.p.discardPile.group) { if (c.type == AbstractCard.CardType.ATTACK) { tmp.addToRandomSpot(c); } } if (tmp.size() == 0){ this.isDone = true; return; } if (tmp.size() == 1){ AbstractCard card = tmp.getTopCard(); if (this.p.hand.size() == 10){ this.p.createHandIsFullDialog(); } else{ card.unhover(); card.lighten(true); card.setAngle(0.0F); card.drawScale = 0.12F; card.targetDrawScale = 0.75F; card.current_x = CardGroup.DRAW_PILE_X; card.current_y = CardGroup.DRAW_PILE_Y; this.p.discardPile.removeCard(card); AbstractDungeon.player.hand.addToTop(card); AbstractDungeon.player.hand.refreshHandLayout(); AbstractDungeon.player.hand.applyPowers(); } this.isDone = true; return; } AbstractDungeon.gridSelectScreen.open(tmp, this.amount, TEXT[0], false); tickDuration(); return; } if (AbstractDungeon.gridSelectScreen.selectedCards.size() != 0){ for (AbstractCard c : AbstractDungeon.gridSelectScreen.selectedCards){ c.unhover(); if (this.p.hand.size() == 10){ this.p.createHandIsFullDialog(); } else{ this.p.discardPile.removeCard(c); this.p.hand.addToTop(c); } this.p.hand.refreshHandLayout(); this.p.hand.applyPowers(); } AbstractDungeon.gridSelectScreen.selectedCards.clear(); this.p.hand.refreshHandLayout(); } tickDuration(); } }
0
0.920634
1
0.920634
game-dev
MEDIA
0.900618
game-dev
0.981637
1
0.981637
PacktPublishing/Mastering-Cpp-Game-Animation-Programming
11,185
chapter13/01_opengl_navigation/octree/Octree.cpp
#include <algorithm> #include "Octree.h" #include "Logger.h" Octree::Octree(std::shared_ptr<BoundingBox3D> rootBox, int threshold, int maxDepth) : mRootBoundingBox(*rootBox), mThreshold(threshold), mMaxDepth(maxDepth) { mRootNode = std::make_shared<OctreeNode>(); } bool Octree::isLeaf(const std::shared_ptr<OctreeNode> node) { return node && !node->childs[0]; } BoundingBox3D Octree::getChildOctant(BoundingBox3D parentBox, int octantId) { glm::vec3 origin = parentBox.getFrontTopLeft(); glm::vec3 childSize = parentBox.getSize() / 2.0f; /* Octants: * * +---+---+ +-----+-----+ * / 4 / 5 /| / BNW / BNE /|-- back * +---+---+ + +-----+-----+ + * / 0 / 1 /|/| / FNW / FNE /|/|-- front * +---+---+ + + +-----+-----+ + + * | 0 | 1 |/|/ | FNW | FNE |/|/ * +---+---+ + +-----+-----+ + * | 2 | 3 |/ | FSW | FSE |/ * +---+---+ +-----+-----+ * * Back octant ID is front octant ID plus 4 * */ switch(octantId) { case 0: return BoundingBox3D(origin, childSize); break; case 1: return BoundingBox3D(glm::vec3(origin.x + childSize.x, origin.y, origin.z), childSize); break; case 2: return BoundingBox3D(glm::vec3(origin.x, origin.y + childSize.y, origin.z), childSize); break; case 3: return BoundingBox3D(glm::vec3(origin.x + childSize.x, origin.y + childSize.y, origin.z), childSize); break; case 4: return BoundingBox3D(glm::vec3(origin.x, origin.y, origin.z + childSize.z), childSize); break; case 5: return BoundingBox3D(glm::vec3(origin.x + childSize.x, origin.y, origin.z + childSize.z), childSize); break; case 6: return BoundingBox3D(glm::vec3(origin.x, origin.y + childSize.y, origin.z + childSize.z), childSize); break; case 7: return BoundingBox3D(origin + childSize, childSize); break; default: Logger::log(1, "%s error: invalid octant id %i\n", __FUNCTION__, octantId); return BoundingBox3D(); } } int Octree::getOctantId(BoundingBox3D nodeBox, BoundingBox3D valueBox) { glm::vec3 center = nodeBox.getCenter(); /* Front */ if (valueBox.getBack() < center.z) { /* West */ if (valueBox.getRight() < center.x) { if (valueBox.getBottom() < center.y) { /* FNW */ return 0; } else if (valueBox.getFrontTopLeft().y >= center.y) { /* FSW */ return 2; } else { /* not found */ return -1; } /* East */ } else if (valueBox.getFrontTopLeft().x >= center.x) { if (valueBox.getBottom() < center.y) { /* FNE */ return 1; } else if ( valueBox.getFrontTopLeft().y >= center.y) { /* FSE */ return 3; } else { /* not found */ return -1; } } else { /* not found */ return -1; } /* Back */ } else { /* West */ if (valueBox.getRight() < center.x) { if (valueBox.getBottom() < center.y) { /* BNW */ return 4; } else if (valueBox.getFrontTopLeft().y >= center.y) { /* BSW */ return 6; } else { /* not found */ return -1; } /* East */ } else if (valueBox.getFrontTopLeft().x >= center.x) { if (valueBox.getBottom() < center.y) { /* BNE */ return 5; } else if ( valueBox.getFrontTopLeft().y >= center.y) { /* BSE */ return 7; } else { /* not found */ return -1; } } else { /* not found */ return -1; } } } void Octree::add(int instanceId) { /* do not add instance when outside of octree */ if (!mRootBoundingBox.intersects(mInstanceGetBoundingBoxCallbackFunction(instanceId))) { return; } add(mRootNode, 0, mRootBoundingBox, instanceId); } void Octree::add(std::shared_ptr<OctreeNode> node, int depth, BoundingBox3D box, int instanceId) { if (!box.intersects(mInstanceGetBoundingBoxCallbackFunction(instanceId))) { Logger::log(1, "%s error: current octree node bounding box does not contain the bounding box of instance %i \n", __FUNCTION__, instanceId); return; } if (isLeaf(node)) { /* insert into node if possible */ if (depth >= mMaxDepth || node->instancIds.size() < mThreshold) { node->instancIds.emplace_back(instanceId); } else { split(node, box); add(node, depth, box, instanceId); } } else { int i = getOctantId(box, mInstanceGetBoundingBoxCallbackFunction(instanceId)); if (i != -1) { add(node->childs.at(i), depth + 1, getChildOctant(box, i), instanceId); } else { node->instancIds.emplace_back(instanceId); } } } void Octree::split(std::shared_ptr<OctreeNode> node, BoundingBox3D box) { if (!isLeaf(node)) { Logger::log(1, "%s error: only leafs can be splitted\n", __FUNCTION__); return; } for (auto& child : node->childs) { child = std::make_shared<OctreeNode>(); } std::vector<int> newInstanceIds{}; for (const auto& instanceId : node->instancIds) { int i = getOctantId(box, mInstanceGetBoundingBoxCallbackFunction(instanceId)); if (i != -1) { /* found child, store in child ids */ node->childs[i]->instancIds.emplace_back(instanceId); } else { /* not found, store in parent */ newInstanceIds.emplace_back(instanceId); } } node->instancIds = std::move(newInstanceIds); } void Octree::remove(int instanceId) { remove(mRootNode, mRootBoundingBox, instanceId); } bool Octree::remove(std::shared_ptr<OctreeNode> node, BoundingBox3D box, int instanceId) { if (!box.intersects(mInstanceGetBoundingBoxCallbackFunction(instanceId))) { Logger::log(1, "%s error: current octree node bounding box does not contain the bounding box of instance %i \n", __FUNCTION__, instanceId); return false; } if (isLeaf(node)) { removeInstance(node, instanceId); return true; } else { int i = getOctantId(box, mInstanceGetBoundingBoxCallbackFunction(instanceId)); if (i != -1) { if (remove(node->childs[i], getChildOctant(box, i), instanceId)) { return tryMerge(node); } } else { removeInstance(node, instanceId); } return false; } } void Octree::removeInstance(std::shared_ptr<OctreeNode> node, int instanceId) { auto it = std::find_if(std::begin(node->instancIds), std::end(node->instancIds), [&instanceId](const auto& rhs) { return instanceId == rhs; }); if (it == std::end(node->instancIds)) { Logger::log(1, "%s error: could not remove not existing instance with id %i\n", __FUNCTION__, instanceId); return; } // Swap with the last element and pop back *it = std::move(node->instancIds.back()); node->instancIds.pop_back(); } bool Octree::tryMerge(std::shared_ptr<OctreeNode> node) { int numInstanceIds = node->instancIds.size(); for (const auto& child : node->childs) { if (!isLeaf(child)) { return false; } numInstanceIds += child->instancIds.size(); } if (numInstanceIds <= mThreshold) { for (const auto& child : node->childs) { node->instancIds.insert(node->instancIds.end(), child->instancIds.begin(), child->instancIds.end()); } /* remove the childs */ for (auto& child : node->childs) { child.reset(); } return true; } else { return false; } } void Octree::update(int instanceId) { remove(instanceId); add(instanceId); } std::set<int> Octree::query(BoundingBox3D box) { std::vector<int> values; values = query(mRootNode, mRootBoundingBox, box); return std::set<int>(values.begin(), values.end()); } std::vector<int> Octree::query(std::shared_ptr<OctreeNode> node, BoundingBox3D box, BoundingBox3D queryBox) { std::vector<int> values; for (const auto& instanceId : node->instancIds) { if (queryBox.intersects(mInstanceGetBoundingBoxCallbackFunction(instanceId))) { values.emplace_back(instanceId); } } if (!isLeaf(node)) { for (int i = 0; i < node->childs.size(); ++i) { BoundingBox3D childBox = getChildOctant(box, i); if (queryBox.intersects(childBox)) { std::vector<int> childValues = query(node->childs.at(i), childBox, queryBox); values.insert(values.end(), childValues.begin(), childValues.end()); } } } return values; } void Octree::clear() { mRootNode.reset(); mRootNode = std::make_shared<OctreeNode>(); } std::set<std::pair<int, int>> Octree::findAllIntersections() { std::set<std::pair<int, int>> values; values = findAllIntersections(mRootNode); for (auto it = values.begin(); it != values.end(); ) { auto reversePair = std::make_pair((*it).second, (*it).first); if (values.count(reversePair) > 0) { values.erase(it++); } else { ++it; } } return values; } std::set<std::pair<int, int>> Octree::findAllIntersections(std::shared_ptr<OctreeNode> node) { std::set<std::pair<int, int>> values; for (int i = 0; i < node->instancIds.size(); ++i) { for (int j = 0; j < i; ++j) { if (mInstanceGetBoundingBoxCallbackFunction(node->instancIds.at(i)).intersects(mInstanceGetBoundingBoxCallbackFunction(node->instancIds.at(j)))) { values.insert({node->instancIds[i], node->instancIds[j]}); } } } if (!isLeaf(node)) { for (const auto& child : node->childs) { for (const auto& value : node->instancIds) { std::set<std::pair<int, int>> childValues; childValues = findIntersectionsInDescendants(child, value); values.insert(childValues.begin(), childValues.end()); } } for (const auto& child : node->childs) { std::set<std::pair<int, int>> childValues; childValues = findAllIntersections(child); values.insert(childValues.begin(), childValues.end()); } } return values; } std::set<std::pair<int, int>> Octree::findIntersectionsInDescendants(std::shared_ptr<OctreeNode> node, int instanceId) { std::set<std::pair<int, int>> values; for (const auto& other : node->instancIds) { if (mInstanceGetBoundingBoxCallbackFunction(instanceId).intersects(mInstanceGetBoundingBoxCallbackFunction(other))) { values.insert({instanceId, other}); } } if (!isLeaf(node)) { for (const auto& child : node->childs) { std::set<std::pair<int, int>> childValues; childValues = findIntersectionsInDescendants(child, instanceId); values.insert(childValues.begin(), childValues.end()); } } return values; } std::vector<BoundingBox3D> Octree::getTreeBoxes() { std::vector<BoundingBox3D> values; values = getTreeBoxes(mRootNode, mRootBoundingBox); return values; } std::vector<BoundingBox3D> Octree::getTreeBoxes(std::shared_ptr<OctreeNode> node, BoundingBox3D box) { std::vector<BoundingBox3D> values; if (isLeaf(node)) { values.emplace_back(box); } else { for (int i = 0; i < node->childs.size(); ++i) { BoundingBox3D childBox = getChildOctant(box, i); std::vector<BoundingBox3D> childValues = getTreeBoxes(node->childs.at(i), childBox); values.insert(values.end(), childValues.begin(), childValues.end()); } } return values; }
0
0.929353
1
0.929353
game-dev
MEDIA
0.476559
game-dev,graphics-rendering
0.922738
1
0.922738
Farama-Foundation/MicroRTS
34,369
src/rts/GameState.java
package rts; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import rts.units.Unit; import rts.units.UnitType; import rts.units.UnitTypeTable; import util.Pair; import util.XMLWriter; /** * A fully-observable game state * @author santi */ public class GameState { public static final boolean REPORT_ILLEGAL_ACTIONS = false; static Random r = new Random(); // only used if the action conflict resolution strategy is set to random protected int unitCancelationCounter = 0; // only used if the action conflict resolution strategy is set to alternating protected int time = 0; protected PhysicalGameState pgs; protected HashMap<Unit,UnitActionAssignment> unitActions = new LinkedHashMap<>(); protected UnitTypeTable utt; // [player][feature map][Y][X] --> Note: feature maps not yet binarised here! protected int [][][][] vectorObservation; // Feature maps: // 1: hit points // 2: resources // 3: player // 4: unit type // 5: current unit action // 6: wall private static final int NUM_VECTOR_OBSERVATION_FEATURE_MAPS = 6; /** * Initializes the GameState with a PhysicalGameState and a UnitTypeTable * @param a_pgs * @param a_utt */ public GameState(PhysicalGameState a_pgs, UnitTypeTable a_utt) { pgs = a_pgs; utt = a_utt; } /** * Current game timestep (frames since beginning) * @return */ public int getTime() { return time; } /** * Removes a unit from the game * @param u */ public void removeUnit(Unit u) { pgs.removeUnit(u); unitActions.remove(u); } /** * @see PhysicalGameState#getPlayer(int) * @param ID * @return */ public Player getPlayer(int ID) { return pgs.getPlayer(ID); } /** * @see PhysicalGameState#getUnit(long) * @param ID * @return */ public Unit getUnit(long ID) { return pgs.getUnit(ID); } /** * @see PhysicalGameState#getUnits() * @return */ public List<Unit> getUnits() { return pgs.getUnits(); } /** * Returns a map with the units and the actions assigned to them * @return */ public HashMap<Unit,UnitActionAssignment> getUnitActions() { return unitActions; } public UnitTypeTable getUnitTypeTable() { return utt; } /** * Returns the action of a unit * @param u * @return */ public UnitAction getUnitAction(Unit u) { UnitActionAssignment uaa = unitActions.get(u); if (uaa==null) return null; return uaa.action; } /** * Returns the action assigned to a unit * @param u * @return */ public UnitActionAssignment getActionAssignment(Unit u) { return unitActions.get(u); } /** * Indicates whether all units owned by the players have a valid action or not * @return */ public boolean isComplete() { for(Unit u : pgs.units) { if (u.getPlayer() != -1) { UnitActionAssignment uaa = unitActions.get(u); if (uaa == null) return false; if (uaa.action == null) return false; } } return true; } /** * @see PhysicalGameState#winner() * @return */ public int winner() { return pgs.winner(); } /** * @see PhysicalGameState#gameover() * @return */ public boolean gameover() { return pgs.gameover(); } /** * Returns the {@link PhysicalGameState} associated with this state * @return */ public PhysicalGameState getPhysicalGameState() { return pgs; } /** * Returns true if there is no unit in the specified position and no unit is executing * an action that will use that position * @param x coordinate of the position * @param y coordinate of the position * @return */ public boolean free(int x, int y) { if (pgs.getTerrain(x, y)!=PhysicalGameState.TERRAIN_NONE) return false; for(Unit u:pgs.units) { if (u.getX()==x && u.getY()==y) return false; } for(UnitActionAssignment ua:unitActions.values()) { if (ua.action.type==UnitAction.TYPE_MOVE || ua.action.type==UnitAction.TYPE_PRODUCE) { Unit u = ua.unit; if (ua.action.getDirection()==UnitAction.DIRECTION_UP && u.getX()==x && u.getY()==y+1) return false; if (ua.action.getDirection()==UnitAction.DIRECTION_RIGHT && u.getX()==x-1 && u.getY()==y) return false; if (ua.action.getDirection()==UnitAction.DIRECTION_DOWN && u.getX()==x && u.getY()==y-1) return false; if (ua.action.getDirection()==UnitAction.DIRECTION_LEFT && u.getX()==x+1 && u.getY()==y) return false; } } return true; } /** * Returns a boolean array with true if there is no unit in * the specified position and no unit is executing an action that will use that position * @return */ public boolean[][] getAllFree() { boolean free[][]=pgs.getAllFree(); for(UnitActionAssignment ua:unitActions.values()) { if (ua.action.type==UnitAction.TYPE_MOVE || ua.action.type==UnitAction.TYPE_PRODUCE) { Unit u = ua.unit; if (ua.action.getDirection()==UnitAction.DIRECTION_UP ) free[u.getX()][u.getY()-1]=false; if (ua.action.getDirection()==UnitAction.DIRECTION_RIGHT) free[u.getX()+1][u.getY()]=false; if (ua.action.getDirection()==UnitAction.DIRECTION_DOWN ) free[u.getX()][u.getY()+1]=false; if (ua.action.getDirection()==UnitAction.DIRECTION_LEFT) free[u.getX()-1][u.getY()]=false; } } return free; } /** * Returns whether the cell is observable. * For fully observable game states, all the cells are observable. * @param x * @param y * @return */ public boolean observable(int x, int y) { return true; } /** * Issues a player action * @param pa * @return "true" is any action different from NONE was issued */ public boolean issue(PlayerAction pa) { boolean returnValue = false; for(Pair<Unit,UnitAction> p:pa.actions) { // if (p.m_a==null) { // System.err.println("Issuing an action to a null unit!!!"); // System.exit(1); // } // if (unitActions.get(p.m_a)!=null) { // System.err.println("Issuing an action to a unit with another action!"); // } else // { // check for conflicts: ResourceUsage ru = p.m_b.resourceUsage(p.m_a, pgs); for(UnitActionAssignment uaa:unitActions.values()) { if (!uaa.action.resourceUsage(uaa.unit, pgs).consistentWith(ru, this)) { // conflicting actions: if (uaa.time==time) { // The actions were issued in the same game cycle, so it's normal boolean cancel_old = false; boolean cancel_new = false; switch(utt.getMoveConflictResolutionStrategy()) { default: System.err.println("Unknown move conflict resolution strategy in the UnitTypeTable!: " + utt.getMoveConflictResolutionStrategy()); System.err.println("Defaulting to MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH"); //$FALL-THROUGH$ case UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_BOTH: cancel_old = cancel_new = true; break; case UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_RANDOM: if (r.nextInt(2)==0) cancel_new = true; else cancel_old = true; break; case UnitTypeTable.MOVE_CONFLICT_RESOLUTION_CANCEL_ALTERNATING: if ((unitCancelationCounter%2)==0) cancel_new = true; else cancel_old = true; unitCancelationCounter++; break; } int duration1 = uaa.action.ETA(uaa.unit); int duration2 = p.m_b.ETA(p.m_a); if (cancel_old) { // System.out.println("Old action canceled: " + uaa.unit.getID() + ", " + uaa.action); uaa.action = new UnitAction(UnitAction.TYPE_NONE,Math.min(duration1,duration2)); } if (cancel_new) { // System.out.println("New action canceled: " + p.m_a.getID() + ", " + p.m_b); p = new Pair<>(p.m_a, new UnitAction(UnitAction.TYPE_NONE,Math.min(duration1,duration2))); } } else { // This is more a problem, since it means there is a bug somewhere... // (probably in one of the AIs) System.err.println("Inconsistent actions were executed!"); System.err.println(uaa); System.err.println(" Resources: " + uaa.action.resourceUsage(uaa.unit, pgs)); System.err.println(p.m_a + " assigned action " + p.m_b + " at time " + time); System.err.println(" Resources: " + ru); System.err.println("Player resources: " + pgs.getPlayer(0).getResources() + ", " + pgs.getPlayer(1).getResources()); System.err.println("Resource Consistency: " + uaa.action.resourceUsage(uaa.unit, pgs).consistentWith(ru, this)); try { throw new Exception("dummy"); // just to be able to print the stack trace }catch(Exception e) { e.printStackTrace(); } // only the newly issued action is cancelled, since it's the problematic one... p.m_b = new UnitAction(UnitAction.TYPE_NONE); } } } UnitActionAssignment uaa = new UnitActionAssignment(p.m_a, p.m_b, time); unitActions.put(p.m_a,uaa); if (p.m_b.type!=UnitAction.TYPE_NONE) returnValue = true; // System.out.println("Issuing action " + p.m_b + " to " + p.m_a); // } } return returnValue; } /** * Issues a player action, with additional checks for validity. This function is slower * than "issue", and should not be used internally by any AI. It is used externally in the main loop * to verify that the actions proposed by an AI are valid, before sending them to the game. * @param pa * @return "true" is any action different from NONE was issued */ public boolean issueSafe(PlayerAction pa) { if (!pa.integrityCheck()) throw new Error("PlayerAction inconsistent before 'issueSafe'"); if (!integrityCheck()) throw new Error("GameState inconsistent before 'issueSafe'"); for(Pair<Unit,UnitAction> p:pa.actions) { if (p.m_a==null) { System.err.println("Issuing an action to a null unit!!!"); System.exit(1); } if (!p.m_a.canExecuteAction(p.m_b, this)) { if (REPORT_ILLEGAL_ACTIONS) { System.err.println("Issuing a non legal action to unit " + p.m_a + "!! Ignoring it..."); } // replace the action by a NONE action of the same duration: int l = p.m_b.ETA(p.m_a); p.m_b = new UnitAction(UnitAction.TYPE_NONE, l); } // get the unit that corresponds to that action (since the state might have been cloned): boolean foundRealUnit = false; Unit substituteUnit = null; for (final Unit u : pgs.units) { if (u.equals(p.m_a)) { foundRealUnit = true; break; } if (substituteUnit == null) { // TODO should we also compare u.getType() to p.m_a.getType()? if (u.getX() == p.m_a.getX() && u.getY() == p.m_a.getY()) { substituteUnit = u; } } } if (!foundRealUnit) { if (substituteUnit == null) { System.err.println("Inconsistent order: " + pa); System.err.println(this); System.err.println("The problem was with unit " + p.m_a); } else { p.m_a = substituteUnit; } } { // check to see if the action is legal! ResourceUsage r = p.m_b.resourceUsage(p.m_a, pgs); for(int position:r.getPositionsUsed()) { int y = position/pgs.getWidth(); int x = position%pgs.getWidth(); if (pgs.getTerrain(x, y) != PhysicalGameState.TERRAIN_NONE || pgs.getUnitAt(x, y) != null) { UnitAction new_ua = new UnitAction(UnitAction.TYPE_NONE, p.m_b.ETA(p.m_a)); System.err.println("Player " + p.m_a.getPlayer() + " issued an illegal move action (to "+x+","+y+") to unit "+p.m_a.getID()+" at time "+getTime()+", cancelling and replacing by " + new_ua); System.err.println(" Action: " + p.m_b); System.err.println(" Resources used by the action: " + r); System.err.println(" Unit at that coordinate " + pgs.getUnitAt(x, y)); p.m_b = new_ua; } } } } boolean returnValue = issue(pa); if (!integrityCheck()) throw new Error("GameState inconsistent after 'issueSafe': " + pa); return returnValue; } /** * Indicates whether a player can issue an action in this state * @param pID the player ID * @return true if the player can execute any action */ public boolean canExecuteAnyAction(int pID) { for(Unit u : pgs.getUnits()) { if (u.getPlayer() == pID) { if (unitActions.get(u) == null) return true; } } return false; } /** * This function checks whether the intended unit action has any conflicts with some * other action. It assumes that the UnitAction ua is valid (i.e. one of the * actions that the unit can potentially execute) * @param u * @param ua * @return */ public boolean isUnitActionAllowed(Unit u, UnitAction ua) { PlayerAction empty = new PlayerAction(); if (ua.getType()==UnitAction.TYPE_MOVE) { int x2 = u.getX() + UnitAction.DIRECTION_OFFSET_X[ua.getDirection()]; int y2 = u.getY() + UnitAction.DIRECTION_OFFSET_Y[ua.getDirection()]; if (x2<0 || y2<0 || x2>=getPhysicalGameState().getWidth() || y2>=getPhysicalGameState().getHeight() || getPhysicalGameState().getTerrain(x2, y2) == PhysicalGameState.TERRAIN_WALL || getPhysicalGameState().getUnitAt(x2, y2) != null) return false; } // Generate the reserved resources: for(Unit u2:pgs.getUnits()) { UnitActionAssignment uaa = unitActions.get(u2); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u2, pgs); empty.r.merge(ru); } } return ua.resourceUsage(u, pgs).consistentWith(empty.getResourceUsage(), this); } /** * * @param unit * @return */ public List<PlayerAction> getPlayerActionsSingleUnit(Unit unit) { List<PlayerAction> l = new LinkedList<>(); PlayerAction empty = new PlayerAction(); l.add(empty); // Generate the reserved resources: for(Unit u:pgs.getUnits()) { UnitActionAssignment uaa = unitActions.get(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); empty.r.merge(ru); } } if (unitActions.get(unit)==null) { l = empty.cartesianProduct(unit.getUnitActions(this), unit, this); } return l; } /** * Returns the list of {@link PlayerAction} for a given player * @param playerID the player ID * @return */ public List<PlayerAction> getPlayerActions(int playerID) { List<PlayerAction> l = new LinkedList<>(); PlayerAction empty = new PlayerAction(); l.add(empty); // Generate the reserved resources: for(Unit u:pgs.getUnits()) { // if (u.getPlayer()==pID) { UnitActionAssignment uaa = unitActions.get(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); empty.r.merge(ru); } // } } for(Unit u:pgs.getUnits()) { if (u.getPlayer()==playerID) { if (unitActions.get(u)==null) { List<PlayerAction> l2 = new LinkedList<>(); for(PlayerAction pa:l) { l2.addAll(pa.cartesianProduct(u.getUnitActions(this), u, this)); } l = l2; } } } return l; } /** * Returns the time the next unit action will complete, or current time * if a player can act * @return */ public int getNextChangeTime() { int nextChangeTime = -1; for(Player player:pgs.players) { if (canExecuteAnyAction(player.ID)) return time; } for(UnitActionAssignment uaa:unitActions.values()) { int t = uaa.time + uaa.action.ETA(uaa.unit); if (nextChangeTime == -1 || t < nextChangeTime) nextChangeTime = t; } if (nextChangeTime == -1) return time; return nextChangeTime; } /** * Runs a game cycle, execution all assigned actions * @return whether the game was over */ public boolean cycle() { time++; List<UnitActionAssignment> readyToExecute = new LinkedList<>(); for(UnitActionAssignment uaa:unitActions.values()) { if (uaa.action.ETA(uaa.unit)+uaa.time<=time) readyToExecute.add(uaa); } // execute the actions: for(UnitActionAssignment uaa:readyToExecute) { unitActions.remove(uaa.unit); // System.out.println("Executing action for " + u + " issued at time " + uaa.time + " with duration " + uaa.action.ETA(uaa.unit)); uaa.action.execute(uaa.unit,this); } return gameover(); } /** * Forces the execution of all assigned actions */ public void forceExecuteAllActions() { List<UnitActionAssignment> readyToExecute = new LinkedList<>(unitActions.values()); // execute all the actions: for(UnitActionAssignment uaa:readyToExecute) { unitActions.remove(uaa.unit); uaa.action.execute(uaa.unit,this); } } /* * @see java.lang.Object#clone() */ @Override public GameState clone() { GameState gs = new GameState(pgs.clone(), utt); gs.time = time; gs.unitCancelationCounter = unitCancelationCounter; for(UnitActionAssignment uaa:unitActions.values()) { Unit u = uaa.unit; int idx = pgs.getUnits().indexOf(u); if (idx==-1) { System.out.println("Problematic game state:"); System.out.println(this); System.out.println("Problematic action:"); System.out.println(uaa); throw new Error("Inconsistent game state during cloning..."); } else { Unit u2 = gs.pgs.getUnits().get(idx); gs.unitActions.put(u2,new UnitActionAssignment(u2, uaa.action, uaa.time)); } } return gs; } /** * This method does a quick clone, that shares the same PGS, but different unit assignments * @param pa * @return */ public GameState cloneIssue(PlayerAction pa) { GameState gs = new GameState(pgs, utt); gs.time = time; gs.unitCancelationCounter = unitCancelationCounter; gs.unitActions.putAll(unitActions); gs.issue(pa); return gs; } /** * Clone this game state, replacing the active {@link UnitTypeTable} * @param new_utt * @return the new GameState */ public GameState cloneChangingUTT(UnitTypeTable new_utt) { GameState gs = clone(); gs.utt = new_utt; for(Unit u:gs.getUnits()) { UnitType new_type = new_utt.getUnitType(u.getType().name); if (new_type == null) return null; if (u.getHitPoints() == u.getType().hp) u.setHitPoints(new_type.hp); u.setType(new_type); } return gs; } /** * Returns the resources being used for all actions issued * in current cycle * @return */ public ResourceUsage getResourceUsage() { ResourceUsage base_ru = new ResourceUsage(); for(Unit u : pgs.getUnits()) { UnitActionAssignment uaa = unitActions.get(u); if (uaa!=null) { ResourceUsage ru = uaa.action.resourceUsage(u, pgs); base_ru.merge(ru); } } return base_ru; } /* * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (!(o instanceof GameState)) return false; GameState s2 = (GameState)o; if(this.getTime() != s2.getTime()) return false; if (!pgs.equivalents(s2.pgs)) return false; // compare actions: int n = pgs.units.size(); for(int i = 0;i<n;i++) { UnitActionAssignment uaa = unitActions.get(pgs.units.get(i)); UnitActionAssignment uaa2 = s2.unitActions.get(s2.pgs.units.get(i)); if (uaa==null) { if (uaa2!=null) return false; } else { if (uaa2==null) return false; if (uaa.time!=uaa2.time) return false; if (!uaa.action.equals(uaa2.action)) return false; } } return true; } /** * Verifies integrity: if an action was assigned to non-existing unit * or two actions were assigned to the same unit, integrity is violated * @return */ public boolean integrityCheck() { List<Unit> alreadyUsed = new LinkedList<>(); for(UnitActionAssignment uaa:unitActions.values()) { Unit u = uaa.unit; int idx = pgs.getUnits().indexOf(u); if (idx==-1) { System.err.println("integrityCheck: unit does not exist!"); return false; } if (alreadyUsed.contains(u)) { System.err.println("integrityCheck: two actions to the same unit!"); return false; } alreadyUsed.add(u); } return true; } /** * Shows {@link UnitActionAssignment}s on the terminal */ public void dumpActionAssignments() { for(Unit u:pgs.getUnits()) { if (u.getPlayer()>=0) { UnitActionAssignment uaa = unitActions.get(u); if (uaa==null) { System.out.println(u + " : -"); } else { System.out.println(u + " : " + uaa.action + " at " + uaa.time); } } } } /* * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder tmp = new StringBuilder("ObservableGameState: " + time + "\n"); for(Player p:pgs.getPlayers()) tmp.append("player ").append(p.ID).append(": ").append(p.getResources()).append("\n"); for(Unit u:unitActions.keySet()) { UnitActionAssignment ua = unitActions.get(u); if (ua==null) { tmp.append(" ").append(u).append(" -> null (ERROR!)\n"); } else { tmp.append(" ").append(u).append(" -> ").append(ua.time).append(" ").append(ua.action).append("\n"); } } tmp.append(pgs); return tmp.toString(); } /** * Writes a XML representation of this state into a XMLWriter * * @param w */ public void toxml(XMLWriter w) { toxml(w, true, false); } /** * Writes a XML representation of this state into a XMLWriter * * @param w */ public void toxml(XMLWriter w, boolean includeConstants, boolean compressTerrain) { w.tagWithAttributes(this.getClass().getName(), "time=\"" + time + "\""); pgs.toxml(w, includeConstants, compressTerrain); w.tag("actions"); for (Unit u : unitActions.keySet()) { UnitActionAssignment uaa = unitActions.get(u); w.tagWithAttributes("unitAction", "ID=\"" + uaa.unit.getID() + "\" time=\"" + uaa.time + "\""); uaa.action.toxml(w); w.tag("/unitAction"); } w.tag("/actions"); w.tag("/" + this.getClass().getName()); } /** * Dumps this state to a XML file. * It can be reconstructed later (e.g. with {@link #fromXML(String, UnitTypeTable)} * @param path */ public void toxml(String path) { try { XMLWriter dumper = new XMLWriter(new FileWriter(path)); this.toxml(dumper); dumper.close(); } catch (IOException e) { System.err.println("Error while writing state to: " + path); e.printStackTrace(); } } /** * Writes a JSON representation of this state * * @param w * @throws Exception */ public void toJSON(Writer w) throws Exception { toJSON(w, true, false); } /** * Writes a JSON representation of this state * * @param w * @throws Exception */ public void toJSON(Writer w, boolean includeConstants, boolean compressTerrain) throws Exception { w.write("{"); w.write("\"time\":" + time + ",\"pgs\":"); pgs.toJSON(w, includeConstants, compressTerrain); w.write(",\"actions\":["); boolean first = true; for (Unit u : unitActions.keySet()) { if (!first) { w.write(","); } first = false; UnitActionAssignment uaa = unitActions.get(u); w.write("{\"ID\":" + uaa.unit.getID() + ", \"time\":" + uaa.time + ", \"action\":"); uaa.action.toJSON(w); w.write("}"); } w.write("]"); w.write("}"); } /** * Constructs a GameState from a XML Element * @param e * @param utt * @return */ public static GameState fromXML(Element e, UnitTypeTable utt) throws Exception { PhysicalGameState pgs = PhysicalGameState.fromXML(e.getChild(PhysicalGameState.class.getName()), utt); GameState gs = new GameState(pgs, utt); gs.time = Integer.parseInt(e.getAttributeValue("time")); Element actions_e = e.getChild("actions"); for(Object o:actions_e.getChildren()) { Element action_e = (Element)o; long ID = Long.parseLong(action_e.getAttributeValue("ID")); Unit u = gs.getUnit(ID); int time = Integer.parseInt(action_e.getAttributeValue("time")); UnitAction ua = UnitAction.fromXML(action_e.getChild("UnitAction"), utt); UnitActionAssignment uaa = new UnitActionAssignment(u, ua, time); gs.unitActions.put(u, uaa); } return gs; } /** * Returns the GameState previously dumped (e.g. with {@link #toxml(String)} from the specified file. * @param utt * @param path * @return */ public static GameState fromXML(String path, UnitTypeTable utt) { SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(path); Document document = null; GameState reconstructed = null; try { document = (Document) builder.build(xmlFile); } catch (JDOMException | IOException e) { System.err.println("Error while opening file: '" + path + "'. Returning null."); e.printStackTrace(); } try { reconstructed = GameState.fromXML(document.getRootElement(), utt); } catch (Exception e) { System.err.println("ERror while reconstructing the state from the XML element. Returning null."); e.printStackTrace(); } return reconstructed; } /** * Constructs a GameState from JSON * @param JSON * @param utt * @return */ public static GameState fromJSON(String JSON, UnitTypeTable utt) { JsonObject o = Json.parse(JSON).asObject(); PhysicalGameState pgs = PhysicalGameState.fromJSON(o.get("pgs").asObject(), utt); GameState gs = new GameState(pgs, utt); gs.time = o.getInt("time", 0); JsonArray actions_a = o.get("actions").asArray(); for(JsonValue v:actions_a.values()) { JsonObject uaa_o = v.asObject(); long ID = uaa_o.getLong("ID", -1); Unit u = gs.getUnit(ID); int time = uaa_o.getInt("time", 0); UnitAction ua = UnitAction.fromJSON(uaa_o.get("action").asObject(), utt); UnitActionAssignment uaa = new UnitActionAssignment(u, ua, time); gs.unitActions.put(u, uaa); } return gs; } /** * Constructs a vector observation for a player * @param player * @return a vector observation for the specified player */ public int [][][] getVectorObservation(final int player){ if (vectorObservation == null) { vectorObservation = new int[2][NUM_VECTOR_OBSERVATION_FEATURE_MAPS][pgs.height][pgs.width]; } // hitpointsMatrix is vectorObservation[player][0] // resourcesMatrix is vectorObservation[player][1] // playersMatrix is vectorObservation[player][2] // unitTypesMatrix is vectorObservation[player][3] // unitActionMatrix is vectorObservation[player][4] // wallMatrix is vectorObservation[player][5] for (int i=0; i<vectorObservation[player][0].length; i++) { Arrays.fill(vectorObservation[player][0][i], 0); Arrays.fill(vectorObservation[player][1][i], 0); Arrays.fill(vectorObservation[player][2][i], 0); Arrays.fill(vectorObservation[player][3][i], 0); Arrays.fill(vectorObservation[player][4][i], 0); Arrays.fill(vectorObservation[player][5][i], 0); } for (final Unit u : pgs.units) { UnitActionAssignment uaa = unitActions.get(u); vectorObservation[player][0][u.getY()][u.getX()] = u.getHitPoints(); vectorObservation[player][1][u.getY()][u.getX()] = u.getResources(); final int owner = u.getPlayer(); if (owner >= 0) // Owned by a player, not neutral vectorObservation[player][2][u.getY()][u.getX()] = ((u.getPlayer() + player) % 2) + 1; vectorObservation[player][3][u.getY()][u.getX()] = u.getType().ID + 1; if (uaa != null) { vectorObservation[player][4][u.getY()][u.getX()] = uaa.action.type; } else { // Commented line of code is unnecessary: already initialised to 0 //vectorObservation[player][4][u.getY()][u.getX()] = UnitAction.TYPE_NONE; } } // Encode the presence of walls final int[] terrain = pgs.terrain; for (int y = 0; y < pgs.height; ++y) { System.arraycopy(terrain, y * pgs.width, vectorObservation[player][5][y], 0, pgs.width); } return vectorObservation[player]; } }
0
0.882619
1
0.882619
game-dev
MEDIA
0.843573
game-dev
0.907212
1
0.907212
GregTechCEu/GregTech
5,008
src/main/java/gregtech/integration/forestry/bees/BeeRemovals.java
package gregtech.integration.forestry.bees; import gregtech.api.util.Mods; import gregtech.integration.IntegrationModule; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; public class BeeRemovals { private static final List<String> MB_REMOVALS = new ArrayList<>(); private static final List<String> EB_REMOVALS = new ArrayList<>(); public static void init() { if (Mods.MagicBees.isModLoaded()) { removeMagicBees(); } if (Mods.ExtraBees.isModLoaded()) { removeExtraBees(); } } // No breed tree issues with these removals private static void removeMagicBees() { MB_REMOVALS.add("FLUIX"); MB_REMOVALS.add("CERTUS"); MB_REMOVALS.add("SILICON"); MB_REMOVALS.add("APATITE"); MB_REMOVALS.add("EMERALD"); MB_REMOVALS.add("DIAMOND"); MB_REMOVALS.add("BRONZE"); MB_REMOVALS.add("INVAR"); MB_REMOVALS.add("NICKEL"); MB_REMOVALS.add("PLATINUM"); MB_REMOVALS.add("ELECTRUM"); MB_REMOVALS.add("OSMIUM"); MB_REMOVALS.add("ALUMINIUM"); MB_REMOVALS.add("LEAD"); MB_REMOVALS.add("SILVER"); MB_REMOVALS.add("TIN"); MB_REMOVALS.add("COPPER"); MB_REMOVALS.add("GOLD"); MB_REMOVALS.add("IRON"); try { Class<?> mbBeeDefinition = Class.forName("magicbees.bees.EnumBeeSpecies"); Field enabledField = mbBeeDefinition.getDeclaredField("enabledOverride"); enabledField.setAccessible(true); for (var o : mbBeeDefinition.getEnumConstants()) { if (o instanceof Enum<?>bee) { String name = bee.name(); if (MB_REMOVALS.contains(name)) { try { enabledField.set(bee, false); } catch (IllegalAccessException e) { IntegrationModule.logger.error("Failed to disable bee {}! Skipping...", name); } } } } } catch (ClassNotFoundException e) { IntegrationModule.logger.error("Could not find MagicBees EnumBeeSpecies! Skipping..."); } catch (NoSuchFieldException e) { IntegrationModule.logger.error("Could not find MagicBees \"enabledOverride\" field! Skipping..."); } } private static void removeExtraBees() { EB_REMOVALS.add("COPPER"); EB_REMOVALS.add("TIN"); EB_REMOVALS.add("IRON"); EB_REMOVALS.add("LEAD"); EB_REMOVALS.add("ZINC"); EB_REMOVALS.add("TITANIUM"); EB_REMOVALS.add("TUNGSTATE"); EB_REMOVALS.add("NICKEL"); EB_REMOVALS.add("GOLD"); EB_REMOVALS.add("SILVER"); EB_REMOVALS.add("PLATINUM"); EB_REMOVALS.add("LAPIS"); EB_REMOVALS.add("SODALITE"); EB_REMOVALS.add("PYRITE"); EB_REMOVALS.add("BAUXITE"); EB_REMOVALS.add("CINNABAR"); EB_REMOVALS.add("SPHALERITE"); EB_REMOVALS.add("EMERALD"); EB_REMOVALS.add("RUBY"); EB_REMOVALS.add("SAPPHIRE"); EB_REMOVALS.add("DIAMOND"); EB_REMOVALS.add("NUCLEAR"); EB_REMOVALS.add("RADIOACTIVE"); EB_REMOVALS.add("YELLORIUM"); EB_REMOVALS.add("CYANITE"); EB_REMOVALS.add("BLUTONIUM"); try { Class<?> ebBeeDefinition = Class.forName("binnie.extrabees.genetics.ExtraBeeDefinition"); Field branchField = ebBeeDefinition.getDeclaredField("branch"); Field speciesBuilderField = ebBeeDefinition.getDeclaredField("speciesBuilder"); branchField.setAccessible(true); speciesBuilderField.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(branchField, branchField.getModifiers() & ~Modifier.FINAL); modifiersField.setInt(speciesBuilderField, speciesBuilderField.getModifiers() & ~Modifier.FINAL); for (var o : ebBeeDefinition.getEnumConstants()) { if (o instanceof Enum<?>bee) { String name = bee.name(); if (EB_REMOVALS.contains(name)) { branchField.set(bee, null); speciesBuilderField.set(bee, null); } } } } catch (ClassNotFoundException e) { IntegrationModule.logger.error("Could not find ExtraBees ExtraBeeDefinition! Skipping..."); } catch (NoSuchFieldException e) { IntegrationModule.logger.error("Could not find ExtraBees \"branch\" field! Skipping..."); } catch (IllegalAccessException e) { IntegrationModule.logger.error("Could not properly set ExtraBees \"branch\" field! Skipping..."); } } }
0
0.840084
1
0.840084
game-dev
MEDIA
0.500545
game-dev
0.920125
1
0.920125
age-series/ElectricalAge
7,631
src/main/java/mods/eln/sixnode/hub/HubElement.java
package mods.eln.sixnode.hub; import mods.eln.Eln; import mods.eln.misc.Direction; import mods.eln.misc.LRDU; import mods.eln.misc.Utils; import mods.eln.node.NodeBase; import mods.eln.node.six.SixNode; import mods.eln.node.six.SixNodeDescriptor; import mods.eln.node.six.SixNodeElement; import mods.eln.node.six.SixNodeElementInventory; import mods.eln.sim.ElectricalLoad; import mods.eln.sim.ThermalLoad; import mods.eln.sim.mna.component.Component; import mods.eln.sim.mna.component.Resistor; import mods.eln.sim.nbt.NbtElectricalLoad; import mods.eln.sim.process.destruct.VoltageStateWatchDog; import mods.eln.sim.process.destruct.WorldExplosion; import mods.eln.sixnode.electricalcable.ElectricalCableDescriptor; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public class HubElement extends SixNodeElement { NbtElectricalLoad[] electricalLoad = new NbtElectricalLoad[4]; boolean[] connectionGrid = new boolean[]{false, false, false, false, true, true}; SixNodeElementInventory inventory = new SixNodeElementInventory(4, 64, this); public static final byte clientConnectionGridToggle = 1; public HubElement(SixNode sixNode, Direction side, SixNodeDescriptor descriptor) { super(sixNode, side, descriptor); for (int idx = 0; idx < 4; idx++) { electricalLoad[idx] = new NbtElectricalLoad("electricalLoad" + idx); electricalLoadList.add(electricalLoad[idx]); } } @Override public void readFromNBT(@NotNull NBTTagCompound nbt) { super.readFromNBT(nbt); for (int idx = 0; idx < 6; idx++) { connectionGrid[idx] = nbt.getBoolean("connectionGrid" + idx); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); for (int idx = 0; idx < 6; idx++) { nbt.setBoolean("connectionGrid" + idx, connectionGrid[idx]); } } @Override public IInventory getInventory() { return inventory; } @Override public ElectricalLoad getElectricalLoad(LRDU lrdu, int mask) { if (inventory.getStackInSlot(HubContainer.cableSlotId + lrdu.toInt()) != null) return electricalLoad[lrdu.toInt()]; return null; } @Nullable @Override public ThermalLoad getThermalLoad(@NotNull LRDU lrdu, int mask) { return null; } @Override public int getConnectionMask(LRDU lrdu) { if (getElectricalLoad(lrdu, 0) != null) return NodeBase.maskElectricalAll; return 0; } @NotNull @Override public String multiMeterString() { return ""; } @NotNull @Override public String thermoMeterString() { return ""; } @Override public void networkSerialize(DataOutputStream stream) { super.networkSerialize(stream); try { for (int idx = 0; idx < 4; idx++) { Utils.serialiseItemStack(stream, inventory.getStackInSlot(HubContainer.cableSlotId + idx)); } for (int idx = 0; idx < 6; idx++) { stream.writeBoolean(connectionGrid[idx]); } } catch (IOException e) { e.printStackTrace(); } } @Override public void initialize() { setup(); for (int idx = 0; idx < 4; idx++) { Eln.applySmallRs(electricalLoad[idx]); } } @Override public void inventoryChanged() { super.inventoryChanged(); sixNode.disconnect(); setup(); sixNode.connect(); } void setup() { slowProcessList.clear(); WorldExplosion exp = new WorldExplosion(this); exp.cableExplosion(); for (Component c : electricalComponentList) { Resistor r = (Resistor) c; r.breakConnection(); } electricalComponentList.clear(); for (LRDU lrdu : LRDU.values()) { ElectricalCableDescriptor d = getCableDescriptorFromLrdu(lrdu); if (d == null) continue; VoltageStateWatchDog watchdog = new VoltageStateWatchDog(electricalLoad[lrdu.toInt()]); slowProcessList.add(watchdog); watchdog .setNominalVoltage(d.electricalNominalVoltage) .setDestroys(exp); } for (int idx = 0; idx < 6; idx++) { if (connectionGrid[idx]) { LRDU[] lrdu = connectionIdToSide(idx); if (inventory.getStackInSlot(HubContainer.cableSlotId + lrdu[0].toInt()) != null && inventory.getStackInSlot(HubContainer.cableSlotId + lrdu[1].toInt()) != null) { Resistor r = new Resistor(electricalLoad[lrdu[0].toInt()], electricalLoad[lrdu[1].toInt()]); r.setResistance(getCableDescriptorFromLrdu(lrdu[0]).electricalRs + getCableDescriptorFromLrdu(lrdu[1]).electricalRs); electricalComponentList.add(r); //ResistorCurrentWatchdog watchdog = new ResistorCurrentWatchdog(); //slowProcessList.add(watchdog); /*watchdog .set(r) .setIAbsMax(Math.min(getCableDescriptorFromLrdu(lrdu[0]).electricalMaximalCurrent, getCableDescriptorFromLrdu(lrdu[1]).electricalMaximalCurrent)) .set(exp);*/ } } } } ElectricalCableDescriptor getCableDescriptorFromLrdu(LRDU lrdu) { ElectricalCableDescriptor cableDescriptor; ItemStack cable; cable = inventory.getStackInSlot(HubContainer.cableSlotId + lrdu.toInt()); cableDescriptor = (ElectricalCableDescriptor) Eln.sixNodeItem.getDescriptor(cable); return cableDescriptor; } static LRDU[] connectionIdToSide(int id) { switch (id) { case 0: return new LRDU[]{LRDU.Left, LRDU.Down}; case 1: return new LRDU[]{LRDU.Right, LRDU.Up}; case 2: return new LRDU[]{LRDU.Down, LRDU.Right}; case 3: return new LRDU[]{LRDU.Up, LRDU.Left}; case 4: return new LRDU[]{LRDU.Left, LRDU.Right}; case 5: return new LRDU[]{LRDU.Down, LRDU.Up}; } return null; } @Override public boolean hasGui() { return true; } @Nullable @Override public Container newContainer(@NotNull Direction side, @NotNull EntityPlayer player) { return new HubContainer(player, inventory); } @Override public boolean onBlockActivated(EntityPlayer entityPlayer, Direction side, float vx, float vy, float vz) { return false; } @Override public void networkUnserialize(DataInputStream stream) { super.networkUnserialize(stream); try { switch (stream.readByte()) { case clientConnectionGridToggle: int id = stream.readByte(); connectionGrid[id] = !connectionGrid[id]; sixNode.disconnect(); setup(); sixNode.connect(); needPublish(); break; } } catch (IOException e) { e.printStackTrace(); } } }
0
0.966574
1
0.966574
game-dev
MEDIA
0.808015
game-dev
0.991451
1
0.991451