diff --git a/scripts/$PBOPREFIX$.txt b/scripts/$PBOPREFIX$.txt new file mode 100644 index 0000000000000000000000000000000000000000..11b1a611c15e47e4817eec58039e34b684dba6f7 --- /dev/null +++ b/scripts/$PBOPREFIX$.txt @@ -0,0 +1,6 @@ +//<'scripts.pbo' properties via Mikero's dos tools, dll version 9.36> +product=dayz; +prefix=scripts; +version=105080; +//PboType=Arma Addon; +// diff --git a/scripts/1_Core/DayZ/constants.c b/scripts/1_Core/DayZ/constants.c new file mode 100644 index 0000000000000000000000000000000000000000..1f21a24b511614a80354af2228f8662be510c9f8 --- /dev/null +++ b/scripts/1_Core/DayZ/constants.c @@ -0,0 +1,106 @@ +/** + * \defgroup Constants Constants + * \desc static script constants + * @{ + */ + + +/** + * \defgroup InputDevice InputDevice + * \desc constants for input device - inputInterfaceDef.h + * @{ + */ +const int INPUT_MODULE_TYPE_MASK = 0x00700000; +const int INPUT_KEY_MASK = 0x000000ff; +const int INPUT_ACTION_TYPE_MASK = 0x00000f00; +const int INPUT_AXIS = 0x00010000; +const int INPUT_POV = 0x00020000; +const int INPUT_COMBO_MASK = 0xff000000; +const int INPUT_COMBO_AXIS = 0x00800000; +const int INPUT_COMBO_AXIS_OFFSET = 0x00000080; +const int INPUT_COMBO_KEY_OFFSET = 0x01000000; + +const int INPUT_DEVICE_KEYBOARD = 0x00000000; +const int INPUT_DEVICE_MOUSE = 0x00100000; // mouse button +const int INPUT_DEVICE_STICK = 0x00200000; +const int INPUT_DEVICE_XINPUT = 0x00300000; // XInput device +const int INPUT_DEVICE_TRACKIR = 0x00400000; +const int INPUT_DEVICE_GAMEPAD = 0x00500000; +const int INPUT_DEVICE_CHEAT = 0x00600000; + +const int INPUT_ACTION_TYPE_NONE = 0x00000000; +const int INPUT_ACTION_TYPE_STATE = 0x00000100; +const int INPUT_ACTION_TYPE_DOWN_EVENT = 0x00000200; +const int INPUT_ACTION_TYPE_UP_EVENT = 0x00000300; +const int INPUT_ACTION_TYPE_SHORTCLICK_EVENT= 0x00000400; +const int INPUT_ACTION_TYPE_HOLD_EVENT = 0x00000500; + +const int INPUT_ACTION_TYPE_COMBO = 0x00002000; +const int INPUT_ACTION_TYPE_SPECIALCOMBO = 0x00004000; +const int INPUT_ACTION_TYPE_DOUBLETAP = 0x00008000; + +const int INPUT_DEVICE_MOUSE_AXIS = (INPUT_DEVICE_MOUSE | INPUT_AXIS); +const int INPUT_DEVICE_STICK_AXIS = (INPUT_DEVICE_STICK | INPUT_AXIS); +const int INPUT_DEVICE_STICK_POV = (INPUT_DEVICE_STICK | INPUT_POV); +const int INPUT_DEVICE_GAMEPAD_AXIS = (INPUT_DEVICE_GAMEPAD | INPUT_AXIS); + +/** @}*/ + +/** + * \defgroup StringConstants String constants + * \desc String constants + * @{ + */ +const string STRING_EMPTY = ""; +/** @}*/ + + +/** + + * \defgroup Colors Colors + * @{ + */ +const int COLOR_WHITE = 0xFFFFFFFF; +const int COLOR_RED = 0xFFF22613; +const int COLOR_GREEN = 0xFF2ECC71; +const int COLOR_BLUE = 0xFF4B77BE; +const int COLOR_YELLOW = 0xFFF7CA18; + +const int COLOR_RED_A = 0x1fF22613; +const int COLOR_GREEN_A = 0x1f2ECC71; +const int COLOR_BLUE_A = 0x1f4B77BE; +const int COLOR_YELLOW_A = 0x1fF7CA18; + +/** @}*/ + +/** + + * \defgroup Materials Materials + * @{ + */ + +/**************************************************************************** + * MATERIALS LIST + * + * Note: If you add new materials here, don't forget to add physics + * parameters to them in physics/materials.xml + ***************************************************************************/ +const int MATERIAL_DEFAULT = 0; +const int MATERIAL_METAL = 1; //full steel +const int MATERIAL_IRON = 2; //iron +const int MATERIAL_GLASS = 3; //glass pane +const int MATERIAL_PLASTIC = 4; //plastic object +const int MATERIAL_LIQUID = 5; //liquids, water +const int MATERIAL_SLIME = 6; //slime, oil etc +const int MATERIAL_BETON = 7; //concrete +const int MATERIAL_RUBBER = 8; //rubber, linoeum +const int MATERIAL_FLESH = 9; //flesh, humanoids +const int MATERIAL_GRASS = 10; //grass +const int MATERIAL_WOOD = 11; //wood +const int MATERIAL_SNOW = 12; //snow +const int MATERIAL_SAND = 13; //soft sand +const int MATERIAL_DIRT = 14; //super-soft dirt +const int MATERIAL_GRAVEL = 15; //gravel +const int MATERIAL_STONE = 16; //rocks, cliffs + +/** @}*/ \ No newline at end of file diff --git a/scripts/1_Core/DayZ/defines.c b/scripts/1_Core/DayZ/defines.c new file mode 100644 index 0000000000000000000000000000000000000000..3a6edaaa874ac3796c4234f9f63ef878fc99d2e1 --- /dev/null +++ b/scripts/1_Core/DayZ/defines.c @@ -0,0 +1,139 @@ +// All defines in this file are added from C++ side +// It simply exists for documentation purposes +#ifdef DOXYGEN + +/** + * \defgroup Defines Defines + * \desc static defines + * @{ + */ + +/*! + \brief Define filled in with the current Major and Minor version (e.g. DAYZ_1_16) +*/ +#define DAYZ_X_XX + +/*! + \brief Enabled when game is in Buldozer mode +*/ +#define BULDOZER + +/*! + \brief Enabled when script is compiled for Workbench +*/ +#define WORKBENCH + +/*! + \note Present for server builds +*/ +#define NO_GUI + +/*! + \note Present for server builds +*/ +#define NO_GUI_INGAME + +/*! + \note Work in progress feature flag to prevent cursor from being hijacked by the game. Original intention was only DEVELOPER_DIAG but the fix later introduced problems in retail. +*/ +#define FEATURE_CURSOR + + + +/** + * \defgroup BuildDefines Build defines + * \desc Defines for different builds + * @{ + */ + + /*! + \brief Define present in Diag builds + */ + #define DIAG + + /*! + \note A build is always either DEVELOPER or RELEASE, one is always active + */ + #define DEVELOPER + + /*! + \note includes Diag + */ + #define RELEASE + + /*! + \brief DIAG || DEVELOPER + */ + #define DIAG_DEVELOPER + + /*! + \brief Define present in Experimental builds + */ + #define BUILD_EXPERIMENTAL + +/** @}*/ + + + +/** + * \defgroup ServerDefines Server defines + * \desc Defines for dedicated server code + * \note Only defined when CGame.IsDedicatedServer equals true + * \note The platforms mentioned are the client platform, for game platform use PLATFORM defines + * @{ + */ + + /*! + \brief Define always present on dedicated servers + \note Should be preferred over using CGame.IsDedicatedServer when possible + */ + #define SERVER + + /*! + \warning This is defined for Linux servers as well, as it targets Windows clients + \note A server is always either FOR_WINDOWS, FOR_X1 or FOR_PS4 + */ + #define SERVER_FOR_WINDOWS + + /*! + \note A server is always either FOR_WINDOWS, FOR_X1 or FOR_PS4 + */ + #define SERVER_FOR_X1 + + /*! + \note A server is always either FOR_WINDOWS, FOR_X1 or FOR_PS4 + */ + #define SERVER_FOR_PS4 + + /*! + \brief SERVER_FOR_X1 || SERVER_FOR_PS4 + */ + #define SERVER_FOR_CONSOLE + +/** @}*/ + + + +/** + * \defgroup PlatformDefines Platform defines + * \desc Defines for platform the build is built for + * @{ + */ + + #define PLATFORM_LINUX + + #define PLATFORM_WINDOWS + + #define PLATFORM_XBOX + + #define PLATFORM_PS4 + + /*! + \brief PLATFORM_XBOX || PLATFORM_PS4 + */ + #define PLATFORM_CONSOLE + +/** @}*/ + +/** @}*/ +#endif \ No newline at end of file diff --git a/scripts/1_Core/DayZ/param.c b/scripts/1_Core/DayZ/param.c new file mode 100644 index 0000000000000000000000000000000000000000..72bd6a47f33204ef1b7f91bf1a7bf267af78b1a5 --- /dev/null +++ b/scripts/1_Core/DayZ/param.c @@ -0,0 +1,357 @@ +/** + * \defgroup Tools Tools + * \desc Helpful functions & classes + * @{ + */ + +//----------------------------------------------------------------------------- +/** +\brief Base Param Class with no parameters. Used as general purpose parameter overloaded with Param1 to Param4 templates + */ +class Param: Managed +{ + bool Serialize(Serializer ctx) + { + return false; + } + + bool Deserializer(Serializer ctx) + { + return false; + } +}; + +/** + \brief Param Class Template with one parameter. + \n usage: + @code + Param paramA = new Param1(55); + Param paramB = new Param1("Hello"); + @endcode + */ +class Param1 extends Param +{ + T1 param1; + + void Param1(T1 p1) + { + param1 = p1; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1); + } +}; + +/** + \brief Param Class Template with two parameters. + \n usage: + @code + Param param = new Param2(3.14, "Pi"); + @endcode + */ +class Param2 extends Param +{ + T1 param1; + T2 param2; + + void Param2(T1 p1, T2 p2) + { + param1 = p1; + param2 = p2; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2); + } +}; + +/** + \brief Param Class Template with three parameters. + \n usage: + @code + Param param = new Param3(2.89, "Lala", true); + @endcode + */ +class Param3 extends Param +{ + T1 param1; + T2 param2; + T3 param3; + + void Param3(T1 p1, T2 p2, T3 p3) + { + param1 = p1; + param2 = p2; + param3 = p3; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3); + } +}; + +/** + \brief Param Class Template with four parameters. + \n usage: + @code + Param param = new Param4(100, false, 79.9, "Test"); + @endcode + */ +class Param4 extends Param +{ + T1 param1; + T2 param2; + T3 param3; + T4 param4; + + void Param4(T1 p1, T2 p2, T3 p3, T4 p4) + { + param1 = p1; + param2 = p2; + param3 = p3; + param4 = p4; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3) && ctx.Write(param4); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3) && ctx.Read(param4); + } +}; + +/** + \brief Param Class Template with five parameters. + */ +class Param5 extends Param +{ + T1 param1; + T2 param2; + T3 param3; + T4 param4; + T5 param5; + + void Param5(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5) + { + param1 = p1; + param2 = p2; + param3 = p3; + param4 = p4; + param5 = p5; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3) && ctx.Write(param4) && ctx.Write(param5); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3) && ctx.Read(param4) && ctx.Read(param5); + } +}; + +/** + \brief Param Class Template with six parameters. + */ +class Param6 extends Param +{ + T1 param1; + T2 param2; + T3 param3; + T4 param4; + T5 param5; + T6 param6; + + void Param6(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6) + { + param1 = p1; + param2 = p2; + param3 = p3; + param4 = p4; + param5 = p5; + param6 = p6; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3) && ctx.Write(param4) && ctx.Write(param5) && ctx.Write(param6); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3) && ctx.Read(param4) && ctx.Read(param5) && ctx.Read(param6); + } +}; + +/** + \brief Param Class Template with seven parameters. + */ +class Param7: Param +{ + T1 param1; + T2 param2; + T3 param3; + T4 param4; + T5 param5; + T6 param6; + T7 param7; + + void Param7(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7) + { + param1 = p1; + param2 = p2; + param3 = p3; + param4 = p4; + param5 = p5; + param6 = p6; + param7 = p7; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3) && ctx.Write(param4) && ctx.Write(param5) && ctx.Write(param6) && ctx.Write(param7); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3) && ctx.Read(param4) && ctx.Read(param5) && ctx.Read(param6) && ctx.Read(param7); + } +}; +/** + \brief Param Class Template with eight parameters. + */ +class Param8: Param +{ + T1 param1; + T2 param2; + T3 param3; + T4 param4; + T5 param5; + T6 param6; + T7 param7; + T8 param8; + + void Param8(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7, T8 p8) + { + param1 = p1; + param2 = p2; + param3 = p3; + param4 = p4; + param5 = p5; + param6 = p6; + param7 = p7; + param8 = p8; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3) && ctx.Write(param4) && ctx.Write(param5) && ctx.Write(param6) && ctx.Write(param7) && ctx.Write(param8); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3) && ctx.Read(param4) && ctx.Read(param5) && ctx.Read(param6) && ctx.Read(param7) && ctx.Read(param8); + } +}; +/** + \brief Param Class Template with nine parameters. + */ +class Param9: Param +{ + T1 param1; + T2 param2; + T3 param3; + T4 param4; + T5 param5; + T6 param6; + T7 param7; + T8 param8; + T9 param9; + + void Param9(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7, T8 p8, T9 p9) + { + param1 = p1; + param2 = p2; + param3 = p3; + param4 = p4; + param5 = p5; + param6 = p6; + param7 = p7; + param8 = p8; + param9 = p9; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3) && ctx.Write(param4) && ctx.Write(param5) && ctx.Write(param6) && ctx.Write(param7) && ctx.Write(param8) && ctx.Write(param9); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3) && ctx.Read(param4) && ctx.Read(param5) && ctx.Read(param6) && ctx.Read(param7) && ctx.Read(param8) && ctx.Read(param9); + } +}; +/** + \brief Param Class Template with ten parameters. + */ +class Param10: Param +{ + T1 param1; + T2 param2; + T3 param3; + T4 param4; + T5 param5; + T6 param6; + T7 param7; + T8 param8; + T9 param9; + T10 param10; + + void Param10(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7, T8 p8, T9 p9, T10 p10) + { + param1 = p1; + param2 = p2; + param3 = p3; + param4 = p4; + param5 = p5; + param6 = p6; + param7 = p7; + param8 = p8; + param9 = p9; + param10 = p10; + } + + override bool Serialize(Serializer ctx) + { + return ctx.Write(param1) && ctx.Write(param2) && ctx.Write(param3) && ctx.Write(param4) && ctx.Write(param5) && ctx.Write(param6) && ctx.Write(param7) && ctx.Write(param8) && ctx.Write(param9) && ctx.Write(param10); + } + + override bool Deserializer(Serializer ctx) + { + return ctx.Read(param1) && ctx.Read(param2) && ctx.Read(param3) && ctx.Read(param4) && ctx.Read(param5) && ctx.Read(param6) && ctx.Read(param7) && ctx.Read(param8) && ctx.Read(param9) && ctx.Read(param10); + } +}; +/** @}*/ \ No newline at end of file diff --git a/scripts/1_Core/DayZ/proto/DbgUI.c b/scripts/1_Core/DayZ/proto/DbgUI.c new file mode 100644 index 0000000000000000000000000000000000000000..2f67707a02d8ddb30ff65ab45a6bf107ac9fb03c --- /dev/null +++ b/scripts/1_Core/DayZ/proto/DbgUI.c @@ -0,0 +1,94 @@ +/** @addtogroup Debug +@{*/ + +/** + * \defgroup DebugUI Debug UI API + \brief Immediate mode debug UI API + * @{ + Per frame usage example: + @code + bool m_ShowDbgUI = false; + int m_DbgListSelection = 0; + float m_DbgSliderValue = 0.0; + autoptr array m_DbgOptions = {"jedna", "dva", "tri"}; + + void OnUpdate(float timeslice) + { + DbgUI.Begin("Test"); + DbgUI.Check("Show DbgUI", m_ShowDbgUI); + if (m_ShowDbgUI) + { + DbgUI.Text("DbgUI Test"); + + string name = ""; + DbgUI.InputText("name", name); + + if (DbgUI.Button("Print name")) + { + Print(name); + } + + DbgUI.List("test list", m_DbgListSelection, m_DbgOptions); + + DbgUI.Text("Choice = " + m_DbgListSelection.ToString()); + + DbgUI.Spacer(10); + DbgUI.SliderFloat("slider", m_DbgSliderValue, 0, 100); + DbgUI.Text("Slider value = " + ftoa(m_DbgSliderValue)); + } + DbgUI.End(); + } + @endcode + + For non-per frame usage example: + @code + int m_DbgEventCount = 0; + void OnEvent(EventType eventTypeId, Param params) + { + m_DbgEventCount++; + + DbgUI.BeginCleanupScope(); + DbgUI.Begin("events", 300, 0); + DbgUI.Text("Events count = " + m_DbgEventCount.ToString()); + DbgUI.End(); + DbgUI.EndCleanupScope(); + } + @endcode +*/ + +class DbgUI +{ + private void DbgUI() {} + private void ~DbgUI() {} + + static proto native void DoUnitTest(); ///< Creates all possible DbgUI widgets. Just for the testing purposes. + static proto native void Text(string label); + static proto native void ColoredText(int color, string label); + static proto void Check(string label, out bool checked); + static proto void Combo(string label, out int selection, TStringArray elems); + static proto void List(string label, out int selection, TStringArray elems); + static proto void SliderFloat(string label, out float value, float min, float max, int pxWidth = 150); + static proto native void Spacer(int height); + static proto native void Panel(string label, int width, int height, int color = 0xaa555555); + static proto native bool Button(string txt, int minWidth = 0); + static proto void InputText(string txt, out string value, int pxWidth = 150); + static proto void InputInt(string txt, out int value, int pxWidth = 150); + static proto void InputFloat(string txt, out float value, int pxWidth = 150); + + static proto native void PlotLive(string label, int sizeX, int sizeY, float val, int timeStep = 100, int historySize = 30, int color = 0xFFFFFFFF); + + static proto native void SameLine(); + static proto native void SameSpot(); + + static proto native void PushID_Int(int int_id); + static proto native void PushID_Str(string str_id); + static proto native void PopID(); + + static proto void BeginCleanupScope(); + static proto native void EndCleanupScope(); + + static proto native void Begin(string windowTitle, float x = 0, float y = 0); + static proto native void End(); +}; +//@} +//@} diff --git a/scripts/1_Core/DayZ/proto/EnAudio.c b/scripts/1_Core/DayZ/proto/EnAudio.c new file mode 100644 index 0000000000000000000000000000000000000000..b02040989325976607d04331bdf502244e45b39a --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnAudio.c @@ -0,0 +1,9 @@ +typedef int[] AudioHandle; + +class AudioSystem +{ + proto native static AudioHandle BankLoad(string path); + proto native static AudioHandle ShaderLoad(string path); + proto native static AudioHandle SoundPlay(AudioHandle bank, AudioHandle shader); + proto native static void SoundDestroy(AudioHandle handle); +}; diff --git a/scripts/1_Core/DayZ/proto/EnConvert.c b/scripts/1_Core/DayZ/proto/EnConvert.c new file mode 100644 index 0000000000000000000000000000000000000000..80b231f3dd29f04a99eacee410d863a1ede0e2a5 --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnConvert.c @@ -0,0 +1,653 @@ +class bool +{ + string ToString() + { + if (value) return "true"; + else return "false"; + } +}; + +class func +{ + //! For internal usage of VM + private proto void SetInstance(Class inst); +}; + +enum EBool +{ + NO = 0, + YES = 1 +} + +class int +{ + protected const int ZERO_PAD_SIZE = 8; + protected static string m_ZeroPad[ZERO_PAD_SIZE] = {"", "0", "00", "000", "0000", "00000", "000000", "0000000"}; + + const int MAX = 2147483647; + const int MIN = -2147483648; + + proto string ToString(); + + /** + \brief Converts ASCII code to string + \param ascii ASCII code for convert to \p string. + \return \p string - Converted \p int. + @code + int ascii_code = 77; + string str = ascii_code.AsciiToString(); + Print(str); + + >> str = 'M' + @endcode + */ + proto string AsciiToString(); + + /** + \brief Integer to string with fixed length, padded with zeroes + \param num \p int integer to convert + \param len \p int fixed length + \return \p vector Converted s as vector + @code + int num = 123; + string s = num.ToStringLen(5); + Print(s); + + >> s = '00123' + @endcode + */ + string ToStringLen(int len) + { + string str = value.ToString(); + + int l = len - str.Length(); + + if (l > 0 && l < ZERO_PAD_SIZE ) + return m_ZeroPad[l] + str; + + return str; + } + + /** + \brief Check whether integer falls into an inclusive range + \param min \p int low end of range + \param max \p int high end of range + \return \p bool True if this value is withing the set range + @code + int num = 123; + bool test = num.InRange( 100, 150 ); + Print(test); + + >> s = true + @endcode + */ + bool InRange( int min, int max, bool inclusive_min = true, bool inclusive_max = true ) + { + if( ( !inclusive_min && value <= min ) || value < min ) + return false; + + if( ( !inclusive_max && value >= max ) || value > max ) + return false; + + return true; + } +}; + +class float +{ + const float MIN = FLT_MIN; + const float MAX = FLT_MAX; + const float LOWEST = -FLT_MAX; + + proto string ToString(); +}; + +class vector +{ + static const vector Up = "0 1 0"; + static const vector Aside = "1 0 0"; + static const vector Forward = "0 0 1"; + static const vector Zero = "0 0 0"; + + /** + \brief Vector to string + \param beautify If true verbose vector in more human readable form "<1, 1, 1>" instead of simple form "1 1 1" + \return \p string Converted vector as parsed string + @code + vector v = "1 0 1"; + Print( v.ToString() ); + Print( v.ToString(false) ); + + >> '<1, 0, 1>' + >> '1 0 1' + @endcode + */ + proto string ToString(bool beautify = true); + + /** + \brief Normalizes vector. Returns length + \return \p float Length of origin vector + @code + vector vec = "1 0 1"; + float length = vec.Normalize(); + Print( vec ); + Print( length ); + + >> vec = <0.707107,0,0.707107> + >> length = 1.41421 + @endcode + */ + proto float Normalize(); + + //! return normalized vector (keeps orginal vector untouched) + proto vector Normalized(); + + /** + \brief Returns length of vector (magnitude) + \return \p float Length of vector + @code + vector vec = "1 0 1"; + float length = vec.Length(); + Print( length ); + + >> length = 1.41421 + @endcode + */ + proto native float Length(); + + /** + \brief Returns squared length (magnitudeSqr) + \return \p float Length of vector + @code + vector vec = "1 1 0"; + float length = vec.LengthSq(); + Print( length ); + + >> length = 2 + @endcode + */ + proto native float LengthSq(); + + /** + \brief Returns the distance between tips of two 3D vectors. + \param v1 \p vector 3D Vector 1 + \param v2 \p vector 3D Vector 2 + \return \p float Distance + @code + float dist = vector.Distance( "1 2 3", "4 5 6" ); + Print( dist ); + + >> dist = 5.19615 + @endcode + */ + proto static native float Distance(vector v1, vector v2); + + /** + \brief Returns the square distance between tips of two 3D vectors. + \param v1 \p vector 3D Vector 1 + \param v2 \p vector 3D Vector 2 + \return \p float Squere distance + @code + float dist = vector.DistanceSq( "0 0 0", "0 5 0" ); + Print( dist ); + + >> dist = 25 + @endcode + */ + proto static native float DistanceSq(vector v1, vector v2); + + /** + \brief Returns perpendicular vector. Perpendicular vector is computed as cross product between input vector and up vector (0, 1, 0). + \return \p vector perpendicular vector + @code + vector vec = "1 0 0"; + Print( vec.Perpend() ); + + >> <0,0,1> + @endcode + */ + vector Perpend() + { + return value * vector.Up; + } + + /** + \brief Returns direction vector from point p1 to point p2 + \param p1 \p vector point from + \param p2 \p vector point to + \return \p vector direction vector + */ + static vector Direction(vector p1, vector p2) + { + vector dir_vec; + + dir_vec[0] = p2[0] - p1[0]; + dir_vec[1] = p2[1] - p1[1]; + dir_vec[2] = p2[2] - p1[2]; + + return dir_vec; + } + + /** + \brief Returns randomly generated unit vector + \return \p randomly generated unit vector + @code + vector vec = vector.RandomDir(); + Print(vec); + Print(vec.Length()); + + >> <-0.179424,0.966825,0.181816> + >> 1 + @endcode + */ + static vector RandomDir() + { + return Vector(Math.RandomFloatInclusive(-1,1),Math.RandomFloatInclusive(-1,1),Math.RandomFloatInclusive(-1,1)).Normalized(); + } + + /** + \brief Returns randomly generated XZ unit vector with the Y(up) axis set to 0 + \return \p randomly generated XZ unit vector + @code + vector vec = vector.RandomDir(); + Print(vec); + Print(vec.Length()); + + >> <0.631697,0,0.775216> + >> 1 + @endcode + */ + static vector RandomDir2D() + { + return Vector(Math.RandomFloatInclusive(-1,1),0,Math.RandomFloatInclusive(-1,1)).Normalized(); + } + + /** + \brief Returns Dot product of vector v1 and vector v2 + \param v1 \p vector input vector + \param v2 \p vector input vector + \return \p vector direction vector + */ + static float Dot(vector v1, vector v2) + { + return ((v1[0] * v2[0]) + (v1[1] * v2[1]) + (v1[2] * v2[2])); + } + + /** + \brief Returns relative angles between -180 and 180, not 0 to 360 + \return \p float Relative angles + @code + vector angles = "-45 190 160"; + Print( angles.GetRelAngles() ); + + >> <-45,-170,160> + @endcode + */ + vector GetRelAngles() + { + for(int i = 0; i < 3; i++) { + if(value[i] > 180) + value[i] = value[i] - 360; + if(value[i] < -180) + value[i] = value[i] + 360; + } + return value; + } + + /** + \brief Returns yaw of vector + \param vec \p vector Vector to convert yaw + \return \p float Yaw of vector + @code + vector v1 = "0 1 0"; + vector v2 = "0.7 0.7 0"; + Print( v1.ToYaw() ); + Print( v2.ToYaw() ); + + >> 90 + >> 45 + @endcode + */ + proto float VectorToYaw(); + + /** + \brief Returns vector of yaw + \param yaw \p float Value of yaw + \return \p vector Yaw converted in vector + @code + Print( vector.Yaw2Vector(90) ); + Print( vector.Yaw2Vector(45) ); + + >> <0,1,0> + >> <0.707107,0.707107,0> + @endcode + */ + proto native static vector YawToVector(float yaw); + + /** + \brief Converts vector to spherical coordinates with radius = 1 + \return \p vector spherical coordinates (yaw, pitch, roll in degrees) + @code + vector v1 = "1 0 1"; + vector v2 = "1 1 1"; + Print( v1.VectorToAngles() ); + Print( v2.VectorToAngles() ); + + >> <45,-0,0> + >> <45,35.2644,0> + @endcode + */ + proto vector VectorToAngles(); + + /** + \brief Converts spherical coordinates (yaw, pitch, roll in degrees) to unit length vector + \return \p normalized direction vector + @code + vector v1 = "45 0 0"; + vector v2 = "15 60 0"; + Print( v1.AnglesToVector() ); + Print( v2.AnglesToVector() ); + + >> <0.707107,0,0.707107> + >> <0.12941,0.866025,0.482963> + @endcode + */ + proto vector AnglesToVector(); + + /** + \brief Creates rotation matrix from angles + \param ang \p vector which contains angles + \param[out] mat \p vector created rotation matrix + @code + vector mat[3]; + vector ang = "70 15 45"; + ang.RotationMatrixFromAngles( mat ); + Print( mat ); + + >> <0.330366,0.0885213,-0.939693>,<0.458809,0.854988,0.241845>,<0.824835,-0.511037,0.241845> + @endcode + */ + proto void RotationMatrixFromAngles(out vector mat[3]); + + /** + \brief Transforms position + \param mat \p vector[4] transformation matrix + \param vec \p vector position to transform + \return \p vector transformed position + @code + vector mat[4] = { "1 0 0 0", "0 1 0 0", "0 0 1 1", "3 1 2 1" }; // translation matrix + vector pos = "1 1 1"; + Print( pos.Multiply4(mat) ); + + >> <4,2,3> + @endcode + */ + proto vector Multiply4(vector mat[4]); + + /** + \brief Transforms vector + \param mat \p vector[3] transformation matrix + \param vec \p vector vector to transform + \return \p vector transformed vector + @code + vector mat[3] = { "2 0 0", "0 3 0", "0 0 1" }; // scale matrix + vector vec = "1 1 1"; + Print( vec.Multiply3(mat) ); + + >> <2,3,1> + @endcode + */ + proto vector Multiply3(vector mat[3]); + + /** + \brief Invert-transforms position + \param mat \p vector[4] transformation matrix + \param vec \p vector position to transform + \return \p vector transformed position + @code + vector mat[4] = { "1 0 0 0", "0 1 0 0", "0 0 1 1", "3 1 2 1" }; // translation matrix + vector pos = "1 1 1"; + Print( pos.InvMultiply4(mat) ); + + >> <-2,0,-1> + @endcode + */ + proto vector InvMultiply4(vector mat[4]); + + /** + \brief Invert-transforms vector + \param mat \p vector[3] transformation matrix + \param vec \p vector vector to transform + \return \p vector transformed vector + @code + vector mat[3] = { "1.5 2.5 0", "0.1 1.3 0", "0 0 1" }; // rotation matrix + vector vec = "1 1 1"; + Print( vec.InvMultiply3(mat) ); + + >> <4,1.4,1> + @endcode + */ + proto vector InvMultiply3(vector mat[3]); + + /** + \brief Lerp between two vectors + @code + vector v1 = Vector(0,0,0); + vector v2 = Vector(5,6,1); + Print( vector.Lerp(v1, v2, 0.5) ); + @endcode + */ + proto static native vector Lerp(vector v1, vector v2, float t); + + /** + \brief Rotate a vector around 0,0,0 by an angle in degrees + \param vec \p vector to rotate + \param axis \p axis to rotate around + \param cosAngle \p angle in degrees + \return \p vector transformed vector + */ + + static vector RotateAroundZeroDeg(vector vec, vector axis, float angle) + { + return (vec * Math.Cos(angle * Math.DEG2RAD)) + ((axis * vec) * Math.Sin(angle * Math.DEG2RAD)) + (axis * vector.Dot(axis, vec)) * (1 - Math.Cos(angle * Math.DEG2RAD)); + } + + /** + \brief Rotate a vector around 0,0,0 by an angle in radians + \param vec \p vector to rotate + \param axis \p axis to rotate around + \param cosAngle \p angle in radians + \return \p vector transformed vector + */ + + static vector RotateAroundZeroRad(vector vec, vector axis, float angle) + { + return (vec * Math.Cos(angle)) + ((axis * vec) * Math.Sin(angle)) + (axis * vector.Dot(axis, vec)) * (1 - Math.Cos(angle)); + } + + /** + \brief Rotate a vector around 0,0,0 + \param pos \p vector to rotate + \param axis \p axis to rotate around + \param cosAngle \p cos of angle + \param sinAngle \p sin of angle + \return \p vector transformed vector + */ + + static vector RotateAroundZero(vector pos, vector axis, float cosAngle, float sinAngle) + { + return (pos * cosAngle) + ((axis * pos) * sinAngle) + (axis * vector.Dot(axis, pos)) * (1 - cosAngle); + } + + /** + \brief Rotate a vector around point + \param point \p point to rotate around + \param pos \p vector to rotate + \param axis \p axis to rotate around + \param cosAngle \p cos of angle + \param sinAngle \p sin of angle + \return \p vector transformed vector + */ + static vector RotateAroundPoint(vector point, vector pos, vector axis, float cosAngle, float sinAngle) + { + vector offsetPos = pos - point; + return RotateAroundZero(offsetPos, axis, cosAngle, sinAngle) + point; + } + + /** + \brief Convert static array of floats into a vector + \param arr \p vector in array format + \return \p vector resulting vector + */ + static vector ArrayToVec(float arr[]) + { + return Vector(arr[0], arr[1], arr[2]); + } +}; + +class typename +{ + /** + \brief Dynamic variant to 'new' keyword. It creates new instance of class + \returns \p volatile instance of class + @code + ??? + @endcode + */ + proto volatile Class Spawn(); + + /** + \brief Get the name of the module the typename belongs to + \returns \p string Name of parent module (1_Core) + */ + proto owned string GetModule(); + + //!Returns type name of variable as string + proto native owned string ToString(); + + /** + \brief Returns true when type is the same as 'baseType', or inherited one. + \param baseType typename + \returns \p bool true when type is the same as 'baseType', or inherited one. + @code + ??? + @endcode + */ + proto native bool IsInherited(typename baseType); + + proto native int GetVariableCount(); + proto native owned string GetVariableName(int vIdx); + proto native typename GetVariableType(int vIdx); + proto bool GetVariableValue(Class var, int vIdx, out void val); + + /** + \brief Return string name of enum value + @code + DialogPriority prio = DialogPriority.WARNING; + Print( typename.EnumToString(DialogPriority, prio) ); + @endcode + */ + static string EnumToString(typename e, int enumValue) + { + int cnt = e.GetVariableCount(); + int val; + + for (int i = 0; i < cnt; i++) + { + if (e.GetVariableType(i) == int && e.GetVariableValue(null, i, val) && val == enumValue) + { + return e.GetVariableName(i); + } + } + + return "unknown"; + } + + /** + \brief Return enum value from string name + @code + Print( typename.StringToEnum(DialogPriority, "WARNING") ); + @endcode + */ + static int StringToEnum(typename e, string enumName) + { + int count = e.GetVariableCount(); + int value; + + for (int i = 0; i < count; i++) + { + if (e.GetVariableType(i) == int && e.GetVariableValue(null, i, value) && e.GetVariableName(i) == enumName) + { + return value; + } + } + + return -1; + } +}; + +class EnumTools +{ + private void EnumTools(); + private void ~EnumTools(); + + /** + \brief Return string name of enum value + @code + DialogPriority prio = DialogPriority.WARNING; + Print( EnumTools.EnumToString(DialogPriority, prio) ); + @endcode + */ + static string EnumToString(typename e, int enumValue) + { + return typename.EnumToString(e, enumValue); + } + + /** + \brief Return enum value from string name + @code + Print( EnumTools.StringToEnum(DialogPriority, "WARNING") ); + @endcode + */ + static int StringToEnum(typename e, string enumName) + { + return typename.StringToEnum(e, enumName); + } + + /** + \brief Return amount of values in enum + @code + Print( EnumTools.GetEnumSize(DialogPriority) ); + @endcode + */ + static int GetEnumSize(typename e) + { + return e.GetVariableCount(); + } + + /** + \brief Return the nth value in the enum + @code + Print( EnumTools.GetEnumValue(DialogPriority, 1) ); + @endcode + */ + static int GetEnumValue(typename e, int idx) + { + int value; + e.GetVariableValue(null, idx, value); + return value; + } + + /** + \brief Return amount of values in enum + @code + Print( EnumTools.GetLastEnumValue(DialogPriority) ); + @endcode + */ + static int GetLastEnumValue(typename e) + { + int lastValue; + e.GetVariableValue(null, e.GetVariableCount() - 1, lastValue); + return lastValue; + } +} \ No newline at end of file diff --git a/scripts/1_Core/DayZ/proto/EnDebug.c b/scripts/1_Core/DayZ/proto/EnDebug.c new file mode 100644 index 0000000000000000000000000000000000000000..debda50039877a33472eb327e33b55e14a5c3e9f --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnDebug.c @@ -0,0 +1,341 @@ +/** + * \defgroup Debug Debug utilities + * @{ + */ + +/** +\brief Prints current call stack (stack trace) + \return \p void + @code + DumpStack(); + + @endcode + + \verbatim + Output: + -- Stack trace -- + SaveFile() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler.c : 51 + SaveConfigToFile() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile.c : 114 + SaveParameterArray() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile.c : 133 + SetParameterArray() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile.c : 231 + PresetAdd() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile\ModuleLocalProfileUI.h : 46 + OnKeyPress() Scripts/mission/missionGameplay.c : 215 + OnKeyPress() Scripts/DayZGame.c : 334 + ----------------- + \endverbatim +*/ +proto void DumpStack(); + +/** +\brief Prints current call stack (stack trace) to given output + \return \p void + @code + string tmp; + DumpStackString(tmp); + Print(tmp); + + @endcode + + \verbatim + Output: + SaveFile() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler.c : 51 + SaveConfigToFile() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile.c : 114 + SaveParameterArray() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile.c : 133 + SetParameterArray() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile.c : 231 + PresetAdd() Scripts\Entities\Modules\ModuleBase\ModuleFileHandler\ModuleLocalProfile\ModuleLocalProfileUI.h : 46 + OnKeyPress() Scripts/mission/missionGameplay.c : 215 + OnKeyPress() Scripts/DayZGame.c : 334 + \endverbatim +*/ +proto void DumpStackString(out string stack); + +//! Triggers breakpoint in C++ in run time(when app is running in debug enviroment) +proto void DebugBreak(bool condition = true, void param1 = NULL, void param2 = NULL, void param3 = NULL, void param4 = NULL, void param5 = NULL, void param6 = NULL, void param7 = NULL, void param8 = NULL, void param9 = NULL); + +//! Triggers breakpoint in C++ in compile time(when app is running in debug enviroment) +void CompileBreak(); + +//! Prints content of variable to console/log. Should be used for critical messages so it will appear in debug log +proto void DPrint(string var); + +enum ErrorExSeverity +{ + INFO, + WARNING, + ERROR, +} + +/** +\brief Error message, prefixed by method name, above 'INFO' will show a messagebox + \note Format: [%className%::%methodName%] :: [%severity%] :: %errString% + \param \p string Error message to use + @code + class ErrorExTest + { + void ThrowWarning() + { + // [ErrorExTest::ThrowWarning] :: [WARNING] :: This is a warning. + ErrorEx("This is a warning.", ErrorExSeverity.WARNING); + } + } + @endcode +*/ +proto void ErrorEx(string err, ErrorExSeverity severity = ErrorExSeverity.ERROR); +proto void ErrorExString(string err, out string str, ErrorExSeverity severity = ErrorExSeverity.ERROR); + +//! Messagebox with error message +proto native void Error2(string title, string err); + +//! Messagebox with error message +void Error(string err) +{ + Error2("", err); +} + +//!Prints content of variable to console/log +proto void Print(void var); + +//!Prints content of variable to RPT file (performance warning - each write means fflush! use with care) +proto void PrintToRPT(void var); + +/** +\brief Prints formated text to console/log + @code + string c = "Peter"; + PrintFormat("Hello %1, how are you?", c); // prints "Hello 'Peter', how are you?" + @endcode +*/ +proto void PrintFormat(string fmt, void param1 = NULL, void param2 = NULL, void param3 = NULL, void param4 = NULL, void param5 = NULL, void param6 = NULL, void param7 = NULL, void param8 = NULL, void param9 = NULL); + + //------------------------------------------ +/** + * \defgroup DebugShape Debug Shape API definition + * @{ + */ +enum ShapeType +{ + BBOX, //< Just box + LINE, //< One or more lines + SPHERE, //< Sphere represented by triangle mesh + CYLINDER, //< Cylinder represented by triangle mesh + DIAMOND, //< Eight faced pyramid. Defined by bound-box, where middle part is equal to horizontal extents of box and top/bottom apogees lies on top/bottom side of box. + PYRAMID //< Four sided pyramid. Defined by bound-box, where base is equal to bottom side of box. +}; + +enum ShapeFlags +{ + NOZBUFFER, //< Do not compare z-buffer when render + NOZWRITE, //< Do not update z-buffer when render + WIREFRAME, //< Render just wire-frame outline. No solid faces + TRANSP, //< Is translucent + DOUBLESIDE, //< Double-sided (do not cull back-faces) + ONCE, //< Rendered just once and then it's automatically destroyed. Do not keep pointer to these!! + NOOUTLINE, //< Render just solid faces. No wire-frame outline. + BACKFACE, //< Render just back faces + NOCULL, //< Do not cull shapes by view frustum + VISIBLE, //< Make it visible. Set by default + ADDITIVE //< Additive blending (works with ShapeFlags.TRANSP) +}; + +enum CollisionFlags +{ + FIRSTCONTACT, //> <0.989879,-0,0.141916>,<0,1,0>,<-0.141916,0,0.989879>,<2545.08,15.6754,2867.49> + @endcode + */ + proto external void GetTransform(out vector mat[]); + + /** + \brief Returns render transformation of Entity. Must pass in vector array size of 4 + \param mat \p vector[4] matrix to be get + @code + Man player = g_Game.GetPlayer(); + + vector mat[4]; + player.GetRenderTransform(mat); + Print( mat ); + + >> <0.989879,-0,0.141916>,<0,1,0>,<-0.141916,0,0.989879>,<2545.08,15.6754,2867.49> + @endcode + */ + proto external void GetRenderTransform(out vector mat[]); + + /** + \brief Returns local transformation of Entity. It returns only so much vectors as array is big + \param mat \p vector[1...4] matrix to be get + @code + Man player = g_Game.GetPlayer(); + + vector mat[4]; + player.GetTransform(mat); + Print( mat ); + + >> <0.989879,-0,0.141916>,<0,1,0>,<-0.141916,0,0.989879>,<2545.08,15.6754,2867.49> + @endcode + */ + proto external void GetLocalTransform(out vector mat[]); + + /** + \brief Returns one row of Entity transformation matrix + \param axis \p int matrix axis. Can be 0..3 + \return \p vector axis row of Entity matrix + @code + Man player = g_Game.GetPlayer(); + Print( player.GetTransformAxis(0) ); + Print( player.GetTransformAxis(1) ); + Print( player.GetTransformAxis(2) ); + Print( player.GetTransformAxis(3) ); + + >> <-0.386781,0,0.922171> + >> <0,1,0> + >> <-0.922171,0,-0.386782> + >> <2551.34,15.6439,2856.72> + @endcode + */ + proto native external vector GetTransformAxis(int axis); + + /** + \brief Sets entity transformation + \param mat \p vector[4] matrix to be set + @code + vector mat[4]; + Math3D.MatrixIdentity( mat ) + + Man player = g_Game.GetPlayer(); + player.SetTransform( mat ); + + vector outmat[4]; + player.GetTransform(outmat ); + Print( outmat ); + + >> <1,0,0>,<0,1,0>,<0,0,1>,<0,0,0> + @endcode + */ + proto native external void SetTransform(vector mat[4]); + + /** + \brief Returns origin of Entity + \return \p vector entity origin + @code + Man player = g_Game.GetPlayer(); + Print( player.GetOrigin() ); + + >> <2577.02,15.6837,2924.27> + @endcode + */ + proto native external vector GetOrigin(); + + /** + \brief Returns local position of Entity + \return \p vector entity local position + @code + Man player = g_Game.GetPlayer(); + Print( player.GetOrigin() ); + + >> <2577.02,15.6837,2924.27> + @endcode + */ + proto external vector GetLocalPosition(); + + /** + \brief Returns orientation of Entity in world space (Yaw, Pitch, Roll) + \return \p vector entity orientation + @code + Man player = g_Game.GetPlayer(); + Print( player.GetYawPitchRoll() ); + + >> <180,-76.5987,180> + @endcode + */ + proto native external vector GetYawPitchRoll(); + + /** + \brief Same as GetYawPitchRoll, but returns rotation vector around X, Y and Z axis. + */ + proto native external vector GetAngles(); + + /** + \brief Returns local orientation when it's in hierarchy (Yaw, Pitch, Roll) + \return \p vector local orientation + @code + Man player = g_Game.GetPlayer(); + Print( player.GetLocalYawPitchRoll() ); + + >> <180,-57.2585,180> + @endcode + */ + proto native external vector GetLocalYawPitchRoll(); + + /** + \brief Same as GetLocalYawPitchRoll, but returns rotation vector around X, Y and Z axis. + */ + proto native external vector GetLocalAngles(); + + /** + \brief Sets angles for entity (Yaw, Pitch, Roll) + \param angles \p vector angles to be set + @code + Man player = g_Game.GetPlayer(); + player.SetYawPitchRoll("180 50 180" ); + Print( player.GetYawPitchRoll() ); + + >> <-180,50,-180> + @endcode + */ + proto native external void SetYawPitchRoll(vector angles); + + /** + \brief Same as SetYawPitchRoll, but sets rotation around X, Y and Z axis. + */ + proto native external void SetAngles(vector angles); + + /** + \brief Sets origin for entity + \param orig \p vector origin to be set + @code + Man player = g_Game.GetPlayer(); + player.SetOrigin("2550 10 2900" ); + Print( player.GetOrigin() ); + + >> <2550,10,2900> + @endcode + */ + proto native external void SetOrigin(vector orig); + + proto native external float GetScale(); + proto native external void SetScale(float scale); + /** + \brief Transforms local vector to world space + \param vec \p vector local space vector to transform + \return \p vector world space vector + @code + Man player = g_Game.GetPlayer(); + Print( player.VectorToParent("1 2 3") ); + + >> <2.89791,2,1.26575> + @endcode + */ + proto native external vector VectorToParent(vector vec); + + /** + \brief Transforms local position to world space + \param coord \p vector local position to transform + \return \p vector position in world space + @code + Man player = g_Game.GetPlayer(); + Print( player.CoordToParent("1 2 3") ); + + >> <2549,17.6478,2857> + @endcode + */ + proto native external vector CoordToParent(vector coord); + + /** + \brief Transforms world space vector to local space + \param vec \p vector world space vector to transform + \return \p vector local space vector + @code + Man player = g_Game.GetPlayer(); + Print( player.VectorToLocal("2 1 5") ); + + >> <-0.166849,1,5.38258> + @endcode + */ + proto native external vector VectorToLocal(vector vec); + + /** + \brief Transforms world space position to local space + \param coord \p vector world space position to transform + \return \p vector position in local space + @code + Man player = g_Game.GetPlayer(); + Print( player.CoordToLocal("500 10 155") ); + + >> <15254,-54.2004,8745.53> + @endcode + */ + proto native external vector CoordToLocal(vector coord); + + //@} + + + /** \name Name/ID methods + */ + //@{ + + /** + \brief Return unique entity ID + \return \p int unique entity ID + @code + ItemBase apple = g_Game.CreateObject( "FruitApple", String2Vector("0 10 0"), false ); + Print( apple.GetID() ); + + >> 0 + @endcode + */ + proto native int GetID(); + + /** + \brief Set unique entity ID + \param id \p int unique entity ID to be set + @code + ItemBase apple = g_Game.CreateObject( "Fruit_Apple", String2Vector("0 10 0"), false ); + apple.SetID(101); + Print( apple.GetID() ); + + >> 101 + @endcode + */ + proto native void SetID(int id); + + proto native void SetName(string name); + proto native external owned string GetName(); + //@} + + + /** \name Hierarchy methods + Scene hierarchy management + */ + //@{ + + /** + \brief Adds child entity to this entity. + \note Make sure the parent is not ToDelete + \param child \p IEntity Pointer to entity which become our child + \param pivot \p int Pivot is pivot index, or -1 for center of parent. + \param positionOnly \p bool When set to true, the orientation will still be in WS. + \return \p bool True when entity has been attached. False otherwise. + */ + proto native external bool AddChild(notnull IEntity child, int pivot, bool positionOnly = false); + + /** + \brief Removes child entity from hierarchy. + \note Make sure the child is not ToDelete + \param child \p IEntity Pointer to child entity we want to remove. + \param keepTransform \p bool When set to true, Entity is kept on her world position. Otherwise it's local transform is used as world-space one. + \return \p bool True if it was removed, false when this entity is not our child. + */ + proto native external bool RemoveChild(notnull IEntity child, bool keepTransform = false); + + //! Returns if the hierarchy component was created with positionOnly + proto native bool IsHierarchyPositionOnly(); + + //! Returns the hierarchy component pivot + proto native int GetHierarchyPivot(); + + //! Returns pointer to parent Entity in hierarchy + proto native IEntity GetParent(); + //! Returns pointer to first child Entity in hierarchy + proto native IEntity GetChildren(); + //! Returns pointer to next child Entity on the same hierarchy + proto native IEntity GetSibling(); + //@} + + /** + \brief Returns local bounding box of model on Entity + \param[out] mins \p vector minimum point of bounding box + \param[out] maxs \p vector maximum point of bounding box + @code + Man player = g_Game.GetPlayer(); + + vector mins, maxs; + player.GetBounds(mins, maxs ); + + Print( mins ); + Print( maxs ); + + >> <0,0,0> + >> <0,0,0> + @endcode + */ + proto external void GetBounds(out vector mins, out vector maxs); + + /** + \brief Returns quantized world-bound-box of Entity + \param[out] mins \p vector minimum point of bounding box + \param[out] maxs \p vector maximum point of bounding box + @code + Man player = g_Game.GetPlayer(); + + vector mins, maxs; + player.GetWorldBounds( mins, maxs ); + + Print( mins ); + Print( maxs ); + + >> <2547.2,15.5478,2852.85> + >> <2548.8,17.5478,2855.05> + @endcode + */ + proto external void GetWorldBounds(out vector mins, out vector maxs); + + /** \name Simulation/handling properties + Flags that affects simulation and entity handling behavior + */ + //@{ + /** + \brief Returns Entity flags + \return \p EntityFlags entity flags + @code + Man player = g_Game.GetPlayer(); + Print( player.GetFlags() ); + + >> 1610612745 + @endcode + */ + proto native external EntityFlags GetFlags(); + + /** + \brief Test if one or more of specified flags are set + \return \p bool True if is set, false otherwise. + @code + Man player = g_Game.GetPlayer(); + player.SetFlags(EntityFlags.VISIBLE); + Print( player.IsFlagSet(EntityFlags.VISIBLE) ); + + >> true + @endcode + */ + proto native external bool IsFlagSet(EntityFlags flags); + + /** + \brief Sets Entity flags. It's OR operation, not rewrite. Returns previous flags + \param flags \p int flags to be set + \param recursively flags will be recursively applied to children of hierarchy too + \return \p int previous flags + @code + Man player = g_Game.GetPlayer(); + player.SetFlags(EntityFlags.VISIBLE|EntityFlags.SOLID ); + Print( player.GetFlags() ); + + >> 1610612747 + @endcode + */ + proto native external EntityFlags SetFlags(EntityFlags flags, bool recursively); + + /** + \brief Clear Entity flags. Returns cleared flags + \param flags \p int flags to be set + \param recursively flags will be recursively applied to children of hierarchy too + \return \p int cleared flags + @code + Man player = g_Game.GetPlayer(); + player.ClearFlags(EntityFlags.VISIBLE|EntityFlags.SOLID ); + Print( player.GetFlags() ); + + >> 1610612744 + @endcode + */ + proto native external EntityFlags ClearFlags(EntityFlags flags, bool recursively); + + + /** + \brief Returns current event mask + \return \p int current event mask + @code + Man player = g_Game.GetPlayer(); + Print( player.GetEventMask() ); + + >> 0 + @endcode + */ + proto native external EntityEvent GetEventMask(); + + /** + \brief Sets event mask + \param e combined mask of one or more members of EntityEvent enum + @code + Man player = g_Game.GetPlayer(); + Print( player.GetEventMask() ); + player.SetEventMask( EntityEvent.VISIBLE ); + Print( player.GetEventMask() ); + + >> 0 + >> 128 + @endcode + */ + proto native external EntityEvent SetEventMask(EntityEvent e ); + + /** + \brief Clears event mask + \param e \p int event mask + \return \p int event mask + @code + Man player = g_Game.GetPlayer(); + player.SetEventMask(EntityEvent.VISIBLE ); + Print( player.GetEventMask() ); + player.ClearEventMask(EntityEvent.ALL ); + Print( player.GetEventMask() ); + + >> 128 + >> 0 + @endcode + */ + proto native external EntityEvent ClearEventMask(EntityEvent e); + + //!Dynamic event invokation. Parameters are the same as in IEntity::EOnXXXX() methods + proto external volatile void SendEvent(notnull IEntity actor, EntityEvent e, void extra); + +//@} + +/** \name Visual component methods + Manipulation with visual component - model, particle effect etc +*/ +//@{ + + /** + \brief Sets the visual object to this entity. Reference is added and released upon entity destruction + \param object handle to object got by GetObject() + \param options String, dependant on object type. + //Only supported one for XOB objects: + //$remap 'original material name' 'new material'; [$remap 'another original material name' 'anothernew material'] + */ + proto native external void SetObject(vobject object, string options); + + /** + \brief Returns visual object set to this Entity. No reference is added + */ + proto native vobject GetVObject(); + + //!Updates animation (either xob, or particle, whatever) + proto native external int Animate(float speed, int loop); + //!Updates animation (either xob, or particle, whatever) + proto native external int AnimateEx(float speed, int loop, out vector lin, out vector ang); + + //!Sets visibility mask for cameras, where Entity will be rendered + proto native external int SetCameraMask(int mask); +//@} + + /** + \brief When called, the Entity is excluded from consequent TraceMove/TraceLine + */ + proto native external void FilterNextTrace(); + + /*! + Updates entity state/position. Should be called when you want to manually commit position changes etc + before trace methods etc. Entity is updated automatically at the end and the beginning of simulation step, + when it has EntityFlags.TFL_ACTIVE flag set. + \returns mask with flags + // EntityFlags.UPDATE - hierarchy has been updated + // EntityFlags.UPDATE_MDL - model hierarchy has been updated + */ + proto native external int Update(); + +#ifdef COMPONENT_SYSTEM + //! Constructor + protected void IEntity(IEntitySource src, IEntity parent); +#endif +}; + +#ifdef ENF_DONE +// Set fixed LOD. -1 for non-fixed LOD +proto native void SetFixedLOD(IEntity ent, int lod); +//Sets the texture that can be referenced from material as $renderview +//and connects it with camera cam_index. Size iz recommended size of +//rendertarget (0 is default) +proto native void SetRenderView(IEntity ent, int cam_index, int width, int height); +proto void GetRenderView(IEntity ent, out int cam_index, out int width, out int height); +#endif + + +/** + * \defgroup EntityAttributes Entity editor attribute system + * @{ + */ + +class ParamEnum: Managed +{ + string m_Key; + string m_Value; + string m_Desc; + + void ParamEnum(string key, string value, string desc = "") + { + m_Key = key; + m_Value = value; + m_Desc = desc; + } +} + +class ParamEnumArray: array +{ + static ParamEnumArray FromEnum(typename e) + { + ParamEnumArray params = new ParamEnumArray(); + int cnt = e.GetVariableCount(); + int val; + + for (int i = 0; i < cnt; i++) + { + if (e.GetVariableType(i) == int && e.GetVariableValue(NULL, i, val)) + { + params.Insert(new ParamEnum(e.GetVariableName(i), val.ToString())); + } + } + + return params; + } +} + +// ------------------------------------------------------------------------- +class Attribute +{ + string m_DefValue; + string m_UiWidget; ///< can be "editbox", "combobox", "spinbox", "slider", "font", "fileeditbox", "colorPicker", "flags", "resourceNamePicker" + string m_RangeScale; ///< defined as "MIN_VALUE MAX_VALUE STEP" eg. "1 100 0.5" + string m_Desc; + ref ParamEnumArray m_Enums; ///< Only ints and floats are currently supported. Array can be defined this way: { ParamEnum("Choice 1", "1"), ParamEnum("Choicen 2", "2") } + + void Attribute(string defvalue, string uiwidget, string desc = "", string rangescale = "", ParamEnumArray enums = NULL) + { + m_DefValue = defvalue; + m_UiWidget = uiwidget; + m_RangeScale = rangescale; + m_Desc = desc; + m_Enums = enums; + } +} + +class EditorAttribute +{ + string m_Style; ///< can be "box", "sphere", "cylinder", "pyramid", "diamond" or custom style name + string m_Category; ///< folder structure eg. StaticEntities/Walls + string m_Description; ///< class purpose description + vector m_SizeMin; ///< min vector of a bounding box + vector m_SizeMax; ///< max vector of a bounding box + string m_Color; + string m_Color2; + bool m_Visible; + bool m_Insertable; + bool m_DynamicBox; + + void EditorAttribute(string style, string category, string description, vector sizeMin, vector sizeMax, string color, string color2 = "0 0 0 0", bool visible = true, bool insertable = true, bool dynamicBox = false) + { + m_Style = style; + m_Category = category; + m_Description = description; + m_SizeMin = sizeMin; + m_SizeMax = sizeMax; + m_Color = color; + m_Color2 = color2; + m_Visible = visible; + m_Insertable = insertable; + m_DynamicBox = dynamicBox; + } +} +//@} + +//@} diff --git a/scripts/1_Core/DayZ/proto/EnMath.c b/scripts/1_Core/DayZ/proto/EnMath.c new file mode 100644 index 0000000000000000000000000000000000000000..6f048ef75e6e5b07a97deccff7d99fcc215300a6 --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnMath.c @@ -0,0 +1,704 @@ +/** + * \defgroup Math Math library + * @{ + */ + +class Math +{ + private void Math() {} + private void ~Math() {} + + static const float EULER = 2.7182818284590452353; + static const float PI = 3.14159265358979; + static const float PI2 = 6.28318530717958; + static const float PI_HALF = 1.570796326794; + + static const float RAD2DEG = 57.2957795130823208768; + static const float DEG2RAD = 0.01745329251994329577; + + //! returns the number of bits set in a bitmask i + proto static int GetNumberOfSetBits(int i); + + //! returns the the index of n-th bit set in a bit mask counting from the right, for instance, in a mask ..0110 1000 , the 0th set bit(right-most bit set to 1) is at 3th position(starting at 0), 1st bit is at 5th position, 2nd bit is at 6th position etc.. + proto static int GetNthBitSet(int value, int n); + + /** + \brief Returns a random \p int number between and min [inclusive] and max [exclusive]. + \param min \p int Range starts [inclusive] + \param max \p int Range ends [exclusive] + \return \p int - Random number in range + @code + Print( Math.RandomInt(0, 1) ); // only 0 + Print( Math.RandomInt(0, 2) ); // 0 or 1 + + >> 0 + >> 1 + @endcode + */ + proto static int RandomInt(int min, int max); + + /** + \brief Returns a random \p int number between and min [inclusive] and max [inclusive]. + \param min \p int Range starts [inclusive] + \param max \p int Range ends [inclusive] + \return \p int - Random number in range + @code + Print( Math.RandomIntInclusive(0, 1) ); // 0 or 1 + Print( Math.RandomIntInclusive(0, 2) ); // 0, 1, 2 + + >> 1 + >> 2 + @endcode + */ + + static int RandomIntInclusive(int min, int max) + { + return Math.RandomInt(min, max+1); + } + + /** + \brief Returns a random \p bool . + \return \p bool - Random bool either 0 or 1 + @code + Print( Math.RandomBool() ); + Print( Math.RandomBool() ); + Print( Math.RandomBool() ); + + >> true + >> true + >> false + @endcode + */ + + static bool RandomBool() + { + return RandomIntInclusive(0,1); + } + + /** + \brief Returns a random \p float number between and min[inclusive] and max[exclusive]. + \param min \p float Range starts [inclusive] + \param max \p float Range ends [exclusive] + \return \p float - Random number in range + @code + Print( Math.RandomFloat(0,1) ); + Print( Math.RandomFloat(0,2) ); + + >> 0.597561 + >> 1.936456 + @endcode + */ + proto static float RandomFloat(float min, float max); + + /** + \brief Returns a random \p float number between and min [inclusive] and max [inclusive]. + \param min \p float Range starts [inclusive] + \param max \p float Range ends [inclusive] + \return \p float - Random number in range + @code + Print( Math.RandomFloatInclusive(0, 1) ); // 0.0 .. 1.0 + Print( Math.RandomFloatInclusive(1, 2) ); // 1.0 .. 2.0 + + >> 0.3 + >> 2.0 + @endcode + */ + static float RandomFloatInclusive(float min, float max) + { + int max_range = Math.Pow(2, 30); //max range + int random_int = Math.RandomInt(0, max_range); + float rand_float = (float)random_int / (float)max_range; + float range = max - min; + + return min + (rand_float * range); //rand float + } + + /** + \brief Returns a random \p float number between and min [inclusive] and max [inclusive]. + \return \p float - Random number in range 0.0 .. 1.0 + @code + Print( Math.RandomFloat01() ); // 0.0 .. 1.0 + + >> 0.3 + >> 1.0 + @endcode + */ + static float RandomFloat01() + { + return RandomFloatInclusive(0, 1); + } + + /** + \brief Sets the seed for the random number generator. + \param seed \p int New seed for the random number generator, -1 will use time + \return \p int - Returns new seed + @code + Print( Math.Randomize(5) ); + + >> 5 + @endcode + */ + proto static int Randomize(int seed); + + /** + \brief Normalizes the angle (0...360) + \param ang \p float Angle for normalizing + \return \p float - Normalized angle + @code + Print( Math.NormalizeAngle(390) ); + Print( Math.NormalizeAngle(-90) ); + + >> 30 + >> 270 + @endcode + */ + proto static float NormalizeAngle(float ang); + + /** + \brief Return relative difference between angles + \param angle1 \p float + \param angle2 \p float + \return \p float Difference between angles (angle1 - angle2) + @code + Print( Math.DiffAngle(-45, 45) ); + Print( Math.DiffAngle(90, 80) ); + + >> -90 + >> 10 + @endcode + */ + proto static float DiffAngle(float angle1, float angle2); + + /** + \brief Return power of v ^ power + \param v \p float Value + \param power \p float Power + \return \p float - The result of raising v to the given power + @code + Print( Math.Pow(2, 4) ); // (2*2*2*2)=16 + + >> 16 + @endcode + */ + proto static float Pow(float v, float power); + + /** + \brief Returns the floating-point remainder of x/y rounded towards zero + \param x \p float Value of the quotient numerator + \param y \p float Value of the quotient denominator + \return \p float - The remainder of dividing the arguments + @code + Print( Math.ModFloat(5.3, 2) ); + Print( Math.ModFloat(18.5, 4.2) ); + + >> 1.3 + >> 1.7 + @endcode + */ + proto static float ModFloat(float x, float y); + + /** + \brief Returns the floating-point remainder of x/y rounded to nearest + \param x \p float Value of the quotient numerator + \param y \p float Value of the quotient denominator + \return \p float - The remainder of dividing the arguments + @code + Print( Math.RemainderFloat(5.3, 2) ); + Print( Math.RemainderFloat(18.5, 4.2) ); + + >> -0.7 + >> 1.7 + @endcode + */ + proto static float RemainderFloat(float x, float y); + + /** + \brief Returns absolute value + \param f \p float Value + \return \p float - Absolute value + @code + Print( Math.AbsFloat(-12.5) ); + + >> 12.5 + @endcode + */ + proto static float AbsFloat(float f); + + /** + \brief Returns absolute value + \param i \p int Value + \return \p int - Absolute value + @code + Print( Math.AbsInt(-12) ); + + >> 12 + @endcode + */ + proto static int AbsInt(int i); + + /** + \brief Returns sign of given value + \param f \p float Value + \return \p float - Sign of given value + @code + Print( Math.SignFloat(-12.0) ); + Print( Math.SignFloat(0.0) ); + Print( Math.SignFloat(12.0) ); + + >> -1.0 + >> 0 + >> 1.0 + @endcode + */ + proto static float SignFloat(float f); + + /** + \brief Returns sign of given value + \param i \p int Value + \return \p int - Sign of given value + @code + Print( Math.SignFloat(-12) ); + Print( Math.SignFloat(0) ); + Print( Math.SignFloat(12) ); + + >> -1 + >> 0 + >> 1 + @endcode + */ + proto static int SignInt(int i); + + /** + \brief Returns squared value + \param f \p float Value + \return \p float - Squared value + @code + Print( Math.SqrFloat(12.5) ); + + >> 156.25 + @endcode + */ + proto static float SqrFloat(float f); + + /** + \brief Returns squared value + \param i \p int Value + \return \p int - Squared value + @code + Print( Math.SqrInt(12) ); + + >> 144 + @endcode + */ + proto static int SqrInt(int i); + + /** + \brief Returns square root + \param val \p float Value + \return \p float - Square of value + @code + Print( Math.Sqrt(25)); + + >> 5 + @endcode + */ + proto static float Sqrt(float val); + + /** + \brief Returns the binary (base-2) logarithm of x. + \param x \p float Value whose logarithm is calculated. + \return \p float The binary logarithm of x: log2x. + \n If x is negative, it causes a domain error: + \n If x is zero, it may cause a pole error (depending on the library implementation). + @code + Print( Math.Log2(1.0) ); + + >> 0.0 + @endcode + */ + proto static float Log2(float x); + + /** + \brief Returns sinus of angle in radians + \param angle \p float Angle in radians + \return \p float - Sinus of angle + @code + Print( Math.Sin(0.785398) ); // (45) + + >> 0.707107 + @endcode + */ + proto static float Sin(float angle); + + /** + \brief Returns cosinus of angle in radians + \param angle \p float Angle in radians + \return \p float - Cosinus of angle + @code + Print( Math.Cos(0.785398) ); // (45) + + >> 0.707107 + @endcode + */ + proto static float Cos(float angle); + + /** + \brief Returns tangent of angle in radians + \param angle \p float Angle in radians + \return \p float - Tangens of angle + @code + Print( Math.Tan(0.785398) ); // (45) + + >> 1 + @endcode + */ + proto static float Tan(float angle); + + /** + \brief Returns angle in radians from sinus + \param s \p float Sinus + \return \p float - Angle in radians + @code + Print( Math.Asin(0.707107) ); // (sinus 45) + + >> 0.785398 + @endcode + */ + proto static float Asin(float s); + + /** + \brief Returns angle in radians from cosinus + \param c \p float Cosinus + \return \p float - Angle in radians + @code + Print( Math.Acos(0.707107) ); // (cosinus 45) + + >> 0.785398 + @endcode + */ + proto static float Acos(float c); + + /** + \brief Returns angle in radians from tangent + \param x \p float Tangent + \return \p float - Angle in radians + */ + proto static float Atan(float x); + + /** + \brief Returns angle in radians from tangent + \param y \p float Tangent + \param x \p float Tangent + \return \p float - Angle in radians + @code + Print ( Math.Atan2(1, 1) ); + + >> 0.785398 + @endcode + */ + proto static float Atan2(float y, float x); + + /** + \brief Returns mathematical round of value + \param f \p float Value + \return \p float - closest whole number to 'f' + @code + Print( Math.Round(5.3) ); + Print( Math.Round(5.8) ); + + >> 5 + >> 6 + @endcode + */ + proto static float Round(float f); + + /** + \brief Returns floor of value + \param f \p float Value + \return \p float - Floor of value + @code + Print( Math.Floor(5.3) ); + Print( Math.Floor(5.8) ); + + >> 5 + >> 5 + @endcode + */ + proto static float Floor(float f); + + /** + \brief Returns ceil of value + \param f \p float Value + \return \p float - Ceil of value + @code + Print( Math.Ceil(5.3) ); + Print( Math.Ceil(5.8) ); + + >> 6 + >> 6 + @endcode + */ + proto static float Ceil(float f); + + /** + \brief Returns wrap number to specified interval [min, max[ + \param f \p float Value + \param min \p float Minimum + \param max \p float Maximum + \return \p float - number in specified interval [min, max[ + @code + Print( Math.WrapFloat(9.0, 1.0, 9.0) ); + + >> 1.0 + @endcode + */ + proto static float WrapFloat(float f, float min, float max); + + /** + \brief Returns wrap number to specified interval [min, max] + \param f \p float Value + \param min \p float Minimum + \param max \p float Maximum + \return \p float - number in specified interval [min, max] + @code + Print( Math.WrapFloatInclusive(9.0, 1.0, 9.0) ); + + >> 9.0 + @endcode + */ + proto static float WrapFloatInclusive(float f, float min, float max); + + /** + \brief Returns wrap number to specified interval [0, max[ + \param f \p float Value + \param max \p float Maximum + \return \p float - number in specified interval [0, max[ + @code + Print( Math.WrapFloat0X(9.0, 9.0) ); + + >> 0.0 + @endcode + */ + proto static float WrapFloat0X(float f, float max); + + /** + \brief Returns wrap number to specified interval [0, max] + \param f \p float Value + \param max \p float Maximum + \return \p float - number in specified interval [0, max] + @code + Print( Math.WrapFloat0X(9.0, 9.0) ); + + >> 9.0 + @endcode + */ + proto static float WrapFloat0XInclusive(float f, float max); + + /** + \brief Returns wrap number to specified interval [min, max[ + \param i \p int Value + \param min \p float Minimum + \param max \p int Maximum + \return \p int - number in specified interval [min, max[ + @code + Print( Math.WrapInt(9, 1, 9) ); + + >> 1 + @endcode + */ + proto static int WrapInt(int i, int min, int max); + + /** + \brief Returns wrap number to specified interval [0, max[ + \param i \p int Value + \param max \p int Maximum + \return \p int - number in specified interval [0, max[ + @code + Print( Math.WrapInt0X(9, 9) ); + + >> 0 + @endcode + */ + proto static int WrapInt0X(int i, int max); + + /** + \brief Clamps 'value' to 'min' if it is lower than 'min', or to 'max' if it is higher than 'max' + \param value \p float Value + \param min \p float Minimum value + \param max \p float Maximum value + \return \p float - Clamped value + @code + Print( Math.Clamp(-0.1, 0, 1) ); + Print( Math.Clamp(2, 0, 1) ); + Print( Math.Clamp(0.5, 0, 1) ); + + >> 0 + >> 1 + >> 0.5 + @endcode + */ + proto static float Clamp(float value, float min, float max); + + /** + \brief Returns smaller of two given values + \param x \p float Value + \param y \p float Value + \return \p float - min value + @code + Print( Math.Min(5.3, 2.8) ); + + >> 2.8 + @endcode + */ + proto static float Min(float x, float y); + + /** + \brief Returns bigger of two given values + \param x \p float Value + \param y \p float Value + \return \p float - max value + @code + Print( Math.Max(5.3, 2.8) ); + + >> 5.3 + @endcode + */ + proto static float Max(float x, float y); + + /** + \brief Returns if value is between min and max (inclusive) + \param v \p float Value + \param min \p float Minimum value + \param max \p float Maximum value + \return \p bool - if value is within range [min,max] + @code + Print( Math.IsInRange(6.9, 3.6, 9.3) ); + + >> true + @endcode + */ + proto static bool IsInRange(float v, float min, float max); + + /** + \brief Returns if value is between min and max (inclusive) + \param v \p int Value + \param min \p int Minimum value + \param max \p int Maximum value + \return \p bool - if value is within range [min,max] + @code + Print( Math.IsInRangeInt(6, 3, 9) ); + + >> true + @endcode + */ + proto static bool IsInRangeInt(int v, int min, int max); + + /** + \brief Linearly interpolates between 'a' and 'b' given 'time'. + \param a \p float Start + \param b \p float End + \param time \p float Time [value needs to be between 0..1 for correct results, no auto clamp applied] + \return \p float - The interpolated result between the two float values. + @code + Print( Math.Lerp(3, 7, 0.5) ); + + >> 5 + @endcode + */ + proto static float Lerp(float a, float b, float time); + + /** + \brief Calculates the linear value that produces the interpolant value within the range [a, b], it's an inverse of Lerp. + \param a \p float Start + \param b \p float End + \param value \p float value + \return \p float - the time given the position between 'a' and 'b' given 'value', there is no clamp on 'value', to stay between [0..1] use 'value' between 'a' and 'b' + @code + Print( Math.InverseLerp(3, 7, 5) ); + + >> 0.5 + @endcode + */ + proto static float InverseLerp(float a, float b, float value); + + /** + \brief Returns area of a right triangle + \param s \p float Length of adjacent leg + \param a \p float Angle of corner bordering adjacent which is not the right corner (in radians) + \return \p float - Area + */ + proto static float AreaOfRightTriangle(float s, float a); + + /** + \brief Returns hypotenus of a right triangle + \param s \p float Length of adjacent leg + \param a \p float Angle of corner bordering adjacent which is not the right corner (in radians) + \return \p float - hypotenus + */ + proto static float HypotenuseOfRightTriangle(float s, float a); + + /** + \brief Returns if point is inside circle + \param c \p vector Center of circle ([0] and [2] will be used, as a circle is 2D) + \param r \p float Radius of circle + \param p \p vector Point ([0] and [2] will be used, as a circle is 2D) + \return \p bool - True when point is in circle + */ + proto static bool IsPointInCircle(vector c, float r, vector p); + + /** + \brief Returns if point is inside rectangle + \param mi \p vector Minimums of rectangle ([0] and [2] will be used, as a rectangle is 2D) + \param ma \p vector Maximums of rectangle ([0] and [2] will be used, as a rectangle is 2D) + \param p \p vector Point ([0] and [2] will be used, as a rectangle is 2D) + \return \p bool - True when point is in rectangle + */ + proto static bool IsPointInRectangle(vector mi, vector ma, vector p); + + //-------------------------------------------------------------------------- + //-------------------------------- filters --------------------------------- + //-------------------------------------------------------------------------- + + /** + \brief Does the CD smoothing function - easy in | easy out / S shaped smoothing + \param val \p actual value + \param target \p value we are reaching for -> Target + \param velocity \p float[1] - array of ONE member - some kind of memory and actual accel/decel rate, need to be zeroed when filter is about to be reset + \param smoothTime \p smoothing parameter, 0.1 .. 0.4 are resonable values, 0.1 is sharp, 0.4 is very smooth + \param maxVelocity \p maximal value change when multiplied by dt + \param dt \p delta time + + \return \p float smoothed/filtered value + + @code + val = EnfMath.SmoothCD(val, varTarget, valVelocity, 0.3, 1000, dt); + @endcode + */ + + proto static float SmoothCD(float val, float target, inout float velocity[], float smoothTime, float maxVelocity, float dt); + + //! occurences values above '12' will cause Factorial to overflow int. + static float Poisson(float mean, int occurences) + { + return Pow(mean, occurences) * Pow(EULER,-mean) / Factorial(occurences); + } + + //! values above '12' will cause int overflow + static int Factorial(int val) + { + if (val > 12) + { + ErrorEx("Values above '12' cause int overflow! Returning '1'"); + return 1; + } + + int res = 1; + while (val > 1) + { + res *= val--; + } + return res; + } +}; + +//@} \ No newline at end of file diff --git a/scripts/1_Core/DayZ/proto/EnMath3D.c b/scripts/1_Core/DayZ/proto/EnMath3D.c new file mode 100644 index 0000000000000000000000000000000000000000..61ece3c65c9360ed8bf2ad67065621dbbe1fea65 --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnMath3D.c @@ -0,0 +1,474 @@ +/** + * \defgroup Math3DAPI Math3D library + * @{ + */ + +/** +\brief Vector constructor from components + \param x \p float x component + \param y \p float y component + \param z \p float z component + \return \p vector resulting vector + @code + Print( Vector(1, 2, 3) ); + + >> <1,2,3> + @endcode +*/ +proto native vector Vector(float x, float y, float z); + +enum ECurveType +{ + CatmullRom, + NaturalCubic, + UniformCubic +}; + +class Math3D +{ + private void Math3D() {} + private void ~Math3D() {} + + //----------------------------------------------------------------- + proto static vector ClipLine(vector start, vector end, vector norm, float d); + + /** + \brief Tests whether ray is intersecting sphere. + \param raybase \p vector Start of ray + \param raycos \p vector End of ray + \param center \p vector Center of sphere + \param radius \p float Radius of sphere + \return \p float -1 when not intersecting, else the fraction of ray + */ + proto static float IntersectRaySphere(vector raybase, vector raycos, vector center, float radius); + + /** + \brief Tests whether ray is intersecting axis aligned box. + \param start \p vector Start of ray + \param end \p vector End of ray + \param mins \p vector Minimums of bound box + \param maxs \p vector Maximums of bound box + \return \p float -1 when not intersecting, else the fraction of ray + */ + proto static float IntersectRayBox(vector start, vector end, vector mins, vector maxs); + + /** + \brief Tests whether sphere is intersecting axis aligned box. + \param origin \p vector Origin of sphere + \param radius \p float Radius of sphere + \param mins \p vector Minimums of bound box + \param maxs \p vector Maximums of bound box + \return \p bool True when intersects + */ + proto static bool IntersectSphereBox(vector origin, float radius, vector mins, vector maxs); + + /** + \brief Tests whether sphere is intersecting cone. + \param origin \p vector Origin of sphere + \param radius \p float Radius of sphere + \param conepos \p vector Position of top of cone + \param axis \p vector Orientation of cone in direction from top to bottom + \param angle \p float Angle of cone in radians + \return \p bool True when sphere is intersecting cone + */ + proto static bool IntersectSphereCone(vector origin, float radius, vector conepos, vector axis, float angle); + + /** + \brief Tests whether sphere is fully inside cone. + \param origin \p vector Origin of sphere + \param radius \p float Radius of sphere + \param conepos \p vector Position of top of cone + \param axis \p vector Orientation of cone in direction from top to bottom + \param angle \p float Angle of cone in radians + \return \p bool True when sphere is fully inside cone + */ + proto static bool IntersectWholeSphereCone(vector origin, float radius, vector conepos, vector axis, float angle); + + /** + \brief Tests whether cylinder is intersecting oriented box. + \param mins \p vector Minimums of bound box + \param maxs \p vector Maximums of bound box + \param obbMat \p vector Transform of box + \param cylMat \p vector Transform of cylinder + \param cylinderRadius \p float Radius of cylinder + \param cylinderHeight \p float Height of cylinder + \return \p bool True when cylinder is intersecting oriented box + */ + proto static bool IntersectCylinderOBB(vector mins, vector maxs, vector obbMat[4], vector cylMat[4], float cylinderRadius, float cylinderHeight); + + /** + \brief Tests whether ray is intersecting cylinder. + \param rayStart \p vector Start of ray + \param rayEnd \p vector End of ray + \param center \p vector Center of cylinder + \param radius \p float Radius of cylinder + \param height \p float Height of cylinder + \return \p bool True when ray is intersecting cylinder + */ + proto static bool IntersectRayCylinder(vector rayStart, vector rayEnd, vector center, float radius, float height); + + /** + \brief Creates rotation matrix from angles + \param ang \p vector which contains angles + \param[out] mat \p vector created rotation matrix + @code + vector mat[3]; + YawPitchRollMatrix( "70 15 45", mat ); + Print( mat ); + + >> <0.330366,0.0885213,-0.939693>,<0.458809,0.854988,0.241845>,<0.824835,-0.511037,0.241845> + @endcode + */ + proto static void YawPitchRollMatrix(vector ang, out vector mat[3]); + + /** + \brief Creates rotation matrix from direction and up vector + \param dir \p vector direction vector + \param up \p vector up vector + \param[out] mat \p vector[4] created rotation matrix + @code + vector mat[4]; + vector dir = "1 0 1"; + vector up = "0 1 0"; + DirectionAndUpMatrix( dir, up, mat ); + Print( mat ); + + >> <0.707107,0,-0.707107>,<0,1,0>,<0.707107,0,0.707107>,<0,0,0> + @endcode + */ + proto static void DirectionAndUpMatrix(vector dir, vector up, out vector mat[4]); + + /** + \brief Transforms matrix + \param mat0 \p vector[4] first matrix + \param mat1 \p vector[4] second matrix + \param[out] res \p vector[4] result of first and second matrix multiplication + @code + vector mat0[4] = { "2 0 0 0", "0 3 0 0", "0 1 0 0", "0 0 0 1" }; // scale matrix + vector mat1[4] = { "1 0 0 0", "0 1 0 0", "0 1 0 0", "2 4 1 3" }; // translation matrix + vector res[4]; + Math3D.MatrixMultiply4(mat0, mat1, res) + Print( res ); + + >> <2,0,0>,<0,3,0>,<0,3,0>,<4,13,0> + @endcode + */ + proto static void MatrixMultiply4(vector mat0[4], vector mat1[4], out vector res[4]); + + /** + \brief Transforms rotation matrix + \param mat0 \p vector[3] first matrix + \param mat1 \p vector[3] second matrix + \param[out] res \p vector[3] result of first and second matrix multiplication + @code + vector mat0[3] = { "1.5 2.5 0", "0.1 1.3 0", "0 0 1" }; // rotation matrix + vector mat1[3] = { "1 0.4 0", "0 1 0", "0 1.3 2.7" }; // rotation matrix + vector res[3]; + Math3D.MatrixMultiply3(mat0, mat1, res) + Print( res ); + + >> <1.54,3.02,0>,<0.1,1.3,0>,<0.13,1.69,2.7> + @endcode + */ + proto static void MatrixMultiply3(vector mat0[3], vector mat1[3], out vector res[3]); + + /** + \brief Invert-transforms matrix + \param mat0 \p vector[4] first matrix + \param mat1 \p vector[4] second matrix + \param[out] res \p vector[4] inverse result of first and second matrix multiplication + @code + vector mat0[4] = { "2 0 0", "0 3 0", "0 0 1", "0 0 0" }; // scale matrix + vector mat1[4] = { "1 0 0", "0 1 0", "0 0 1", "2 4 1" }; // translation matrix + vector res[4]; + Math3D.MatrixInvMultiply4(mat0, mat1, res) + Print( res ); + + >> <2,0,0>,<0,3,1>,<0,3,1>,<4,12,4> + @endcode + */ + proto static void MatrixInvMultiply4(vector mat0[4], vector mat1[4], out vector res[4]); + + /** + \brief Invert-transforms rotation matrix + \param mat0 \p vector[3] first matrix + \param mat1 \p vector[3] second matrix + \param[out] res \p vector[3] result of first and second matrix multiplication + @code + vector mat0[3] = { "1.5 2.5 0", "0.1 1.3 0", "0 0 1" }; // rotation matrix + vector mat1[3] = { "1 0.4 0", "0 1 0", "0 1.3 2.7" }; // rotation matrix + vector res[3]; + Math3D.MatrixInvMultiply3(mat0, mat1, res) + Print( res ); + + >> <2.5,0.62,0>,<2.5,1.3,0>,<3.25,1.69,2.7> + @endcode + */ + proto static void MatrixInvMultiply3(vector mat0[3], vector mat1[3], out vector res[3]); + + /** + \brief Orthogonalizes matrix + \param[it] mat \p matrix which should be orthogonalized + */ + proto static void MatrixOrthogonalize4(vector mat[4]); + + /** + \brief Orthogonalizes matrix + \param[it] mat \p matrix which should be orthogonalized + */ + proto static void MatrixOrthogonalize3(vector mat[3]); + + /** + \brief Creates identity matrix + \param[out] mat \p created identity matrix + @code + vector mat[4]; + Math3D.MatrixIdentity4( mat ); + Print( mat ); + + >> <1,0,0>,<0,1,0>,<0,0,1>,<0,0,0> + @endcode + */ + + static void MatrixIdentity4(out vector mat[4]) + { + mat[0] = "1 0 0"; + mat[1] = "0 1 0"; + mat[2] = "0 0 1"; + mat[3] = vector.Zero; + } + + /** + \brief Creates identity matrix + \param[out] mat \p created identity matrix + @code + vector mat[3]; + Math3D.MatrixIdentity3( mat ); + Print( mat ); + + >> <1,0,0>,<0,1,0>,<0,0,1> + @endcode + */ + static void MatrixIdentity3(out vector mat[3]) + { + mat[0] = "1 0 0"; + mat[1] = "0 1 0"; + mat[2] = "0 0 1"; + } + + /** + \brief Creates scale matrix + \param scale \p scale coeficient + \param[out] mat \p created scale matrix + @code + vector mat[3]; + Math3D.ScaleMatrix( 2.5, mat ); + Print( mat ); + + >> <2.5,0,0>,<0,2.5,0>,<0,0,2.5> + @endcode + */ + static void ScaleMatrix(float scale, out vector mat[3]) + { + vector v0, v1, v2; + v0[0] = scale; + v1[1] = scale; + v2[2] = scale; + mat[0] = v0; + mat[1] = v1; + mat[2] = v2; + } + + /** + \brief Creates identity quaternion + \param[out] q \p float[4] created identity quaternion + @code + float q[4]; + Math3D.QuatIdentity( q ); + Print( q ); + + >> {0,0,0,1} + @endcode + */ + static void QuatIdentity(out float q[4]) + { + q[0] = 0; + q[1] = 0; + q[2] = 0; + q[3] = 1; + } + + /** + \brief Copies quaternion + \param s \p float[4] quaternion to copy + \param[out] d \p float[4] created quaternion copy + @code + float s[4] = { 2, 3, 4, 1 }; + float d[4]; + Math3D.QuatCopy( s, d ); + Print( d ); + + >> {2,3,4,1} + @endcode + */ + static void QuatCopy(float s[4], out float d[4]) + { + d[0] = s[0]; + d[1] = s[1]; + d[2] = s[2]; + d[3] = s[3]; + } + + /** + \brief Converts rotation matrix to quaternion + \param mat \p vector[3] rotation matrix + \param[out] d \p float[4] created quaternion copy + @code + vector mat[3]; + vector rot = "70 15 45"; + rot.RotationMatrixFromAngles( mat ); + float d[4]; + Math3D.MatrixToQuat( mat, d ); + Print( d ); + + >> {0.241626,0.566299,-0.118838,0.778973} + @endcode + */ + proto static void MatrixToQuat(vector mat[3], out float d[4]); + + + //! Converts quaternion to rotation matrix + proto static void QuatToMatrix(float q[4], out vector mat[3]); + + /** + \brief Returns angles of rotation matrix + \param mat \p vector[3] rotation matrix + \return \p vector roll, pitch, yaw angles + @code + vector mat[3]; + Math3D.RollPitchYawMatrix( "70 15 45", mat ); + vector ang = Math3D.MatrixToAngles( mat ); + Print( ang ); + + >> <70,15,-45> + @endcode + */ + proto static vector MatrixToAngles(vector mat[3]); + + /** + \brief Linear interpolation between q1 and q2 with weight 'frac' (0...1) + \param[out] qout \p float[4] result quaternion + \param q1 \p float[4] first quaternion + \param q2 \p float[4] second quaternion + \param frac \p float interpolation weight + @code + float q1[4] = { 1, 1, 1, 1 }; + float q2[4] = { 2, 2, 2, 1 }; + float qout[4]; + Math3D.QuatLerp( qout, q1, q2, 0.5 ); + Print( qout ); + + >> {1.5,1.5,1.5,1} + @endcode + */ + proto static void QuatLerp(out float qout[4], float q1[4], float q2[4], float frac); + + /** + \brief Multiplies quaternions + \param[out] qout \p float[4] result quaternion + \param q1 \p float[4] first quaternion + \param q2 \p float[4] second quaternion + @code + float q1[4] = { 1, 2, 3, 1 }; + float q2[4] = { 2, 2, 2, 1 }; + float qout[4]; + Math3D.QuatMultiply( qout, q1, q2 ); + Print( qout ); + + >> {2,4,6,1} + @endcode + */ + proto static void QuatMultiply(out float qout[4], float q1[4], float q2[4]); + + //! Returns Angles vector from quaternion + proto static vector QuatToAngles(float q[4]); + + /** + \brief Returns 1, when bounding boxes intersects + \param mins1 \p vector minimum point of first bounding box + \param maxs1 \p vector maximum point of first bounding box + \param mins2 \p vector minimum point of second bounding box + \param maxs2 \p vector maximum point of second bounding box + \return \p int 1 if boundig boxes intersects, otherwise 0 + @code + vector mins1 = "1 1 1"; + vector maxs1 = "3 3 3"; + vector mins2 = "2 2 2"; + vector maxs2 = "4 4 4"; + Print( Math3D.CheckBoundBox(mins1, maxs1, mins2, maxs2) ); + + >> 1 + @endcode + */ + proto static int CheckBoundBox(vector mins1, vector maxs1, vector mins2, vector maxs2); + + /** + \brief Returns randon normalized direction + \return \p vector + @code + Print( Math3D.GetRandomDir() ); + + >>vector ret = 0x0000000007c1a1c0 {<0.422565,0,-0.906333>} + @endcode + */ + static vector GetRandomDir() + { + float x = Math.RandomFloatInclusive(-1, 1); + float y = Math.RandomFloatInclusive(-1, 1); + float z = Math.RandomFloatInclusive(-1, 1); + + return Vector(x, y, z).Normalized(); + } + + + /** + \brief Computes curve + \return \p vector + @code + auto points = new array(); + points.Insert( Vector( 0, 0, 0) ); + points.Insert( Vector( 5, 0, 0) ); + points.Insert( Vector( 8, 3, 0) ); + points.Insert( Vector( 6, 1, 0) ); + + float t = 0.5; + vector result = Math3D.Curve(ECurveType.CatmullRom, t, points); + @endcode + */ + proto static native vector Curve(ECurveType type, float param, notnull array points); + + + /** + \brief Point on line beg .. end nearest to pos + \return \p vector + */ + proto static vector NearestPoint(vector beg, vector end, vector pos); + + /** + \brief Angle that a target is from the direction of an origin + \return \p float Angle in radians + */ + proto static float AngleFromPosition(vector origin, vector originDir, vector target); + + /** + \brief Calculates the points of a right 2D cone in 3D space + \param origin \p vector Origin of cone + \param length \p float Length of the cone + \param halfAngle \p float Half of the angle of the cone in radians + \param angleOffset \p float Angle offset of the cone in radians (handy for rotating it along with something in the world) + \param[out] leftPoint \p vector Left point of the cone + \param[out] rightPoint \p vector Right point of the cone + */ + proto static void ConePoints(vector origin, float length, float halfAngle, float angleOffset, out vector leftPoint, out vector rightPoint); +}; +//@} \ No newline at end of file diff --git a/scripts/1_Core/DayZ/proto/EnPhysics.c b/scripts/1_Core/DayZ/proto/EnPhysics.c new file mode 100644 index 0000000000000000000000000000000000000000..9368a4f8f44802c83ec209aa283f4e2cbf50b532 --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnPhysics.c @@ -0,0 +1,327 @@ +/** + * \defgroup Physics Physics system + * @{ + */ + +typedef int[] dGeom; +typedef int[] dJoint; +typedef int[] dBlock; + +proto native int dGetNumDynamicBodies(notnull IEntity worldEnt); +proto native IEntity dGetDynamicBody(notnull IEntity worldEnt, int index); +proto native void dSetInteractionLayer(notnull IEntity worldEntity, int mask1, int mask2, bool enable); +proto native bool dGetInteractionLayer(notnull IEntity worldEntity, int mask1, int mask2); + +//!Gets global gravity +proto native vector dGetGravity(notnull IEntity worldEntity); +//!Changes global gravity +proto native void dSetGravity(notnull IEntity worldEntity, vector g); +//!Changes fixed time-slice. Default is 1/40, thus simulation runs on 40fps. With smaller values, there is more precise simulation +proto native void dSetTimeSlice(notnull IEntity worldEntity, float timeSlice); + +/** + * \defgroup RigidBody RigidBody API + * @{ + */ + +//proto native int dMaterialClone(string target, string source, int material_index) +//proto native int dMaterialGetType(string source) +//proto native int dMaterialSetType(string source, int material_index) + +class PhysicsGeomDef: Managed +{ + string Name; + dGeom Geometry; + vector Frame[4] = {Vector(1, 0, 0), Vector(0, 1, 0), Vector(0, 0, 1), Vector(0, 0, 0)}; + int ParentNode = -1; + string MaterialName; + int LayerMask; //=0 then the continuous collision detection is enabled. +If you want to disable it, use -1 +\param maxMotion max motion threshold when sphere-cast is performed, to find time of impact. It should be +little bit less than size of the geometry to catch the situation when tunelling can happen +\param sphereCastRadius The radius of the largest possible sphere, that is completelly inside the body geometry. +*/ +proto native void dBodyEnableCCD(notnull IEntity body, float maxMotion, float sphereCastRadius); +/*! +Sets scale factor for all impulses/velocities/forces. Default is <1,1,1>. Zero any axis if you want to do 2D physics +*/ +proto native void dBodySetLinearFactor(notnull IEntity body, vector linearFactor); + +//!returns center of mass offset +proto native vector dBodyGetCenterOfMass(notnull IEntity body); + +/** +\brief Returns linear velocity + \param ent \p IEntity entity which origin will be set + \param mat \p vector[4] matrix to be set + \return \p vector linear velocity + @code + Man player = g_Game.GetPlayer(); + Print( GetVelocity(player) ); + + >> <0,0,0> + @endcode +*/ +proto native vector GetVelocity(notnull IEntity ent); + +/** +\brief Sets linear velocity (for Rigid bodies) + \param ent \p entity which velocity will be set + \param vel \p velocity vector to be set +*/ +proto native void SetVelocity(notnull IEntity ent, vector vel); + +/** +\brief Disables collisions between two entities +*/ +proto native dBlock dBodyCollisionBlock(notnull IEntity ent1, notnull IEntity ent2); +proto native void dBodyRemoveBlock(notnull IEntity worldEntity, dBlock block); + +proto native void dBodySetInertiaTensorV(notnull IEntity body, vector v); +proto native void dBodySetInertiaTensorM(notnull IEntity body, vector m[3]); + +proto native float dBodyGetMass(notnull IEntity ent); +proto native void dBodySetMass(notnull IEntity body, float mass); + +proto native void dBodyApplyTorqueImpulse(notnull IEntity ent, vector torqueImpulse); +proto native vector dBodyGetInvInertiaDiagLocal(notnull IEntity ent); +proto native float dBodyComputeImpulseDenominator(notnull IEntity ent, vector position, vector normal); +proto native float dBodyComputeAngularImpulseDenominator(notnull IEntity ent, vector axis); +proto native vector dBodyGetLocalInertia(notnull IEntity ent); + +proto void dBodyGetInvInertiaTensorWorld(notnull IEntity body, out vector inertiaTensorWS[3]); + +/** +\brief Applies impuls on a pos position in world coordinates +*/ +proto void dBodyApplyImpulseAt(notnull IEntity body, vector impulse, vector pos); + +/** +\brief Applies impuls on a rigidbody (origin) +*/ +proto void dBodyApplyImpulse(notnull IEntity body, vector impulse); + +/** +\brief Applies constant force on a rigidbody (origin) +*/ +proto void dBodyApplyForce(notnull IEntity body, vector force); + +/** +\brief Applies constant force on a position +*/ +proto void dBodyApplyForceAt(notnull IEntity body, vector pos, vector force); + +proto native void dBodyApplyTorque(notnull IEntity body, vector torque); + +/** +\brief Gets angular velocity for a rigidbody +*/ +proto vector dBodyGetAngularVelocity(notnull IEntity body); + +/** +\brief Changed an angular velocity + \param body \p Rigid body + \param angvel \p Angular velocity, rotation around x, y and z axis (not yaw/pitch/roll) +*/ +proto void dBodySetAngularVelocity(notnull IEntity body, vector angvel); + +/** +\brief Sets target transformation. If timeslice == dt (simulation step delta time), it will happen in next step, otherwise in time = timeslice +*/ +proto native void dBodySetTargetMatrix(notnull IEntity body, vector matrix[4], float timeslice); +proto native float dBodyGetKineticEnergy(notnull IEntity body); + +proto native vector dBodyGetVelocityAt(notnull IEntity body, vector globalpos); +//@} + +/** + * \defgroup Geometry Geometry API definition + * @{ + */ + +//! Creates box geometry +proto native dGeom dGeomCreateBox(vector size); + +//! Creates sphere geometry +proto native dGeom dGeomCreateSphere(float radius); + +//! Creates capsule geometry +proto native dGeom dGeomCreateCapsule(float radius, vector extent); + +//! Creates cylinder geometry +proto native dGeom dGeomCreateCylinder(float radius, vector extent); + +//! Destroys geometry +proto native void dGeomDestroy(dGeom geom); + +//proto native int dBodyAddGeom(notnull IEntity body, dGeom geom, vector frame[4], string material, int interactionLayer); +// find a geometry by its name and returns its index or -1 if the geometry wasn't found +proto native int dBodyGetGeom(notnull IEntity ent, string name); +// returns number of geometries of the entity +proto native int dBodyGetNumGeoms(notnull IEntity ent); +//@} + +/** + * \defgroup Constraints Constraints API definition + * @{ + */ + +proto native dJoint dJointCreateHinge(notnull IEntity ent1, notnull IEntity ent2, vector point1, vector axis1, vector point2, vector axis2, bool block, float breakThreshold); +proto native dJoint dJointCreateHinge2(notnull IEntity ent1, notnull IEntity ent2, vector matrix1[4], vector matrix2[4], bool block, float breakThreshold); +proto native dJoint dJointCreateSlider(notnull IEntity ent1, notnull IEntity ent2, vector matrix1[4], vector matrix2[4], bool block, float breakThreshold); +proto native dJoint dJointCreateBallSocket(notnull IEntity ent1, notnull IEntity ent2, vector point1, vector point2, bool block, float breakThreshold); +proto native dJoint dJointCreateFixed(notnull IEntity ent1, notnull IEntity ent2, vector point1, vector point2, bool block, float breakThreshold); +proto native dJoint dJointCreateConeTwist(notnull IEntity ent1, notnull IEntity ent2, vector matrix1[4], vector matrix2[4], bool block, float breakThreshold); +proto native dJoint dJointCreate6DOF(notnull IEntity ent1, notnull IEntity ent2, vector matrix1[4], vector matrix2[4], bool block, float breakThreshold); +proto native dJoint dJointCreate6DOFSpring(notnull IEntity ent1, notnull IEntity ent2, vector matrix1[4], vector matrix2[4], bool block, float breakThreshold); +proto native void dJointDestroy(dJoint joint); + +//only hinge joint +proto native void dJointHingeSetLimits(dJoint joint, float low, float high, float softness, float biasFactor, float relaxationFactor); +proto native void dJointHingeSetAxis(dJoint joint, vector axis); +proto native void dJointHingeSetMotorTargetAngle(dJoint joint, float angle, float dt, float maxImpulse); + +//only cone-twist joint +proto native void dJointConeTwistSetAngularOnly(dJoint joint, bool angularOnly); +// setLimit(), a few notes: +// _softness: +// 0->1, recommend ~0.8->1. +// describes % of limits where movement is free. +// beyond this softness %, the limit is gradually enforced until the "hard" (1.0) limit is reached. +// _biasFactor: +// 0->1?, recommend 0.3 +/-0.3 or so. +// strength with which constraint resists zeroth order (angular, not angular velocity) limit violation. +// __relaxationFactor: +// 0->1, recommend to stay near 1. +// the lower the value, the less the constraint will fight velocities which violate the angular limits. +proto native void dJointConeTwistSetLimit(dJoint joint, int limitIndex, float limitValue); +proto native void dJointConeTwistSetLimits(dJoint joint, float _swingSpan1, float _swingSpan2, float _twistSpan, float _softness, float _biasFactor, float _relaxationFactor); + +//only 6DOF & 6DOFSpring. +/*! + - free means upper < lower, + - locked means upper == lower + - limited means upper > lower + - axis: first 3 are linear, next 3 are angular +*/ +proto native void dJoint6DOFSetLinearLimits(dJoint joint, vector linearLower, vector linearUpper); +proto native void dJoint6DOFSetAngularLimits(dJoint joint, vector angularLower, vector angularUpper); +proto native void dJoint6DOFSetLimit(dJoint joint, int axis, float lo, float hi); + +//when stiffness == -1 && damping == -1, spring is disabled +proto native void dJoint6DOFSpringSetSpring(dJoint joint, int axis, float stiffness, float damping); + +//only slider joint +proto native void dJointSliderSetLinearLimits(dJoint joint, float lowerLimit, float upperLimit); +proto native void dJointSliderSetAngularLimits(dJoint joint, float lowerLimit, float upperLimit); +proto native void dJointSliderSetDirLinear(dJoint joint, float softness, float restitution, float damping); +proto native void dJointSliderSetDirAngular(dJoint joint, float softness, float restitution, float damping); +proto native void dJointSliderSetLimLinear(dJoint joint, float softness, float restitution, float damping); +proto native void dJointSliderSetLimAngular(dJoint joint, float softness, float restitution, float damping); +proto native void dJointSliderSetOrthoLinear(dJoint joint, float softness, float restitution, float damping); +proto native void dJointSliderSetOrthoAngular(dJoint joint, float softness, float restitution, float damping); +//if force == 0, motor is off +proto native void dJointSliderSetLinearMotor(dJoint joint, float velocity, float force); +proto native void dJointSliderSetAngularMotor(dJoint joint, float velocity, float force); +proto native float dJointSliderGetLinearPos(dJoint joint); +proto native float dJointSliderGetAngularPos(dJoint joint); +//@} + +//----------------------------------------------------------------- +typedef int[] dMaterial; + +class Contact +{ + private void Contact() {} + private void ~Contact() {} + + dMaterial Material1; + dMaterial Material2; + int MaterialIndex1; + int MaterialIndex2; + int Index1; + int Index2; + + float PenetrationDepth; + + float Impulse; + float RelativeNormalVelocityBefore; + float RelativeNormalVelocityAfter; + + vector Normal; + vector Position; + vector RelativeVelocityBefore; + vector RelativeVelocityAfter; + + proto native vector GetNormalImpulse(); + proto native float GetRelativeVelocityBefore(vector vel); + proto native float GetRelativeVelocityAfter(vector vel); +}; +//@} diff --git a/scripts/1_Core/DayZ/proto/EnProfiler.c b/scripts/1_Core/DayZ/proto/EnProfiler.c new file mode 100644 index 0000000000000000000000000000000000000000..ac4b778733601e56d9c36609eed0d210b553da4e --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnProfiler.c @@ -0,0 +1,762 @@ +/** + * \defgroup Profiler Enforce Script profiling API + * \warning Only available on developer and diag builds + * @{ + */ + +//! Flags that influences the behaviour of the EnProfiler API, applied through ...Flags functions +enum EnProfilerFlags +{ + //! No flags + NONE, + //! When present, will reset [PD] on sorting, otherwise will accumulate on top of it + RESET, + //! Whether to profile child modules + RECURSIVE, + //! All flags enabled + ALL +}; + +//! Current base scripted modules +enum EnProfilerModule +{ + //! 1_Core + CORE, + //! 2_GameLib + GAMELIB, + //! 3_Game + GAME, + //! 4_World + WORLD, + //! 5_Mission + MISSION, + //! init.c + MISSION_CUSTOM, + //! Can be returned from some methods + ERROR, +}; + +/** +*\brief There are 3 states which can be toggled that governs whether script profiling is enabled or not +* \note The reason for this is because when it is enabled in debug menu, or through this API without 'immediate', it will only be enabled the next frame +*/ +enum EnProfilerEnabledFlags +{ + //! No flags, has value 0, so will count as false in conditions + NONE, + //! Script profiling UI is enabled in WIN+ALT debug menu, when this is true, it will override SCRP + DIAG, + //! It has been set to being always enabled through EnProfiler (SCRipt Profiler) + SCRP, + //! Whether profiling is currently truly happening (SCRipt Context) + SCRC, +}; + +typedef Param2 EnProfilerTimeClassPair; +typedef Param2 EnProfilerCountClassPair; + +typedef Param2 EnProfilerTimeFuncPair; +typedef Param2 EnProfilerCountFuncPair; + +/** +*\brief Set of methods for accessing script profiling data +* \note To enable profiling on game launch, use parameter "-profile" +* \note Any mention of "[DM]" in this context will mean the WIN+ALT debug menu +* \note Any mention of "[CI]" in this context will mean Class Instances count +* \note Any mention of "[SR]" in this context will mean a Session Reset (See ResetSession for more information) +* \note Any mention of "[SD]" in this context will mean a Sorted Data, which is the data which supplies Get...Per... functions (the ones that give an array) +* \note Any mention of "[PD]" in this context will mean a Profiling Data, which is the time, count and allocation information which is stored on the class/func itself +* \warning [PD] is only calculated AFTER a function call is finished, there is no continuous timer running +* \note 'proto' methods are not tracked, but will contribute to a script methods total time +*/ +class EnProfiler +{ + /** + \brief Enable the gathering of script profiling data + \note DEFAULT: disabled (unless launched with "-profile", then it is default enabled) + \note This is separate from the one in [DM], so toggling it in [DM] will not affect this, and toggling it here will not affect [DM] + \note It will ignore the call if trying to set the current state, except when "immediate" is used + \param enable \p bool Whether to enable or disable, if it was previously not enabled, it will cause [SR] + \note Disabling does not cause [SR], so all data will stay intact + \param immediate \p bool When true will instantly start/stop profiling, otherwise it will apply it at the end of the frame (to have one stable point in time) + \warning Keep in mind that when using immediate, it will not be the data of the entire frame, which can skew data if not kept in mind + \param sessionReset \p bool When set to false, no [SR] will trigger, regardless of situation + + @code + // Simple enable, will start profiling the next frame + // Will cause [SR] if !IsEnabledP() before this call + EnProfiler.Enable(true); + + // Immediate enable, will start profiling immediately + // Will cause [SR] if !IsEnabledP() before this call + EnProfiler.Enable(true, true); + + // Immediate disable, will stop profiling immediately + // Disabling will never cause [SR], preserving data + EnProfiler.Enable(false, true); + + // Simple disable, will not profile the next frame (but still finish profiling the current one) + // Disabling will never cause [SR], preserving data + EnProfiler.Enable(false); + @endcode + */ + static proto void Enable(bool enable, bool immediate = false, bool sessionReset = true); + + /** + \brief Return if script profiling is enabled + \note Helper methods below + \return \p int Flags regarding the current state + + @code + int isScriptProfilingEnabled = EnProfiler.IsEnabled(); + @endcode + */ + static proto int IsEnabled(); + + /** + \brief Return if script profiling is enabled through [DM] + \return \p bool Whether script profiling is enabled through [DM] + + @code + bool isScriptProfilingDiagEnabled = EnProfiler.IsEnabledD(); + @endcode + */ + static bool IsEnabledD() + { + return (IsEnabled() & EnProfilerEnabledFlags.DIAG); + } + + /** + \brief Return if script profiling is enabled through EnProfiler + \note When using "-profile" launch parameter, it will enable it through EnProfiler, so this will return true + \return \p bool Whether script profiling is enabled through script profiler + + @code + bool isScriptProfilingToggleEnabled = EnProfiler.IsEnabledP(); + @endcode + */ + static bool IsEnabledP() + { + return (IsEnabled() & EnProfilerEnabledFlags.SCRP); + } + + /** + \brief Return if script profiling is actually turned on inside of the script context + \note When using "-profile" launch parameter, it will enable it through EnProfiler, so this will return true + \return \p bool Whether script is being profiled as of this moment + + @code + bool isScriptProfilingEnabled = EnProfiler.IsEnabledC(); + @endcode + */ + static bool IsEnabledC() + { + return (IsEnabled() & EnProfilerEnabledFlags.SCRC); + } + + /** + \brief The internal sorting that happens at the end of the frame (so it is NOT necessary to call this manually) to supply Get...Per... functions + \note This will clear the previous [SD] and sort the [PD] currently available at this moment + \note Flags apply to this + \warning Keep in mind that EnProfilerFlags.RESET will clear all [PD] after this is called + + @code + // Sorting all the currently available [PD], populating [SD] + EnProfiler.SortData(); + + // If flag EnProfilerFlags.RESET is enabled, then this will return 0 now even if it has been called, as [PD] has been cleared + // This goes for any Get...Of... function (Except for [CI], the counter persists) + EnProfiler.GetTimeOfFunc("Sleep", EnProfilerTests, true); + @endcode + */ + static proto void SortData(); + + /** + \brief Perform [SR], clearing SessionFrame, ProfiledSessionFrames, [SD] and [PD] (except for [CI]) + \note Can also be triggered by a variety of other functions in this API + \note When triggered by the other functions, it will call with fullReset = false + \param fullReset \p bool Whether to clear [PD] of all modules, when false it will only clear the [PD] according to current settings + + @code + // Considering the settings: SetFlags(EnProfilerFlags.NONE) and SetModule(EnProfilerModule.GAME) + // The following call will only clear [PD] of 3_Game + EnProfiler.ResetSession(); + + // Considering the settings: SetFlags(EnProfilerFlags.RECURSIVE) and SetModule(EnProfilerModule.WORLD) + // The following call will clear [PD] of 3_Game, 4_World, 5_Mission and their children + EnProfiler.ResetSession(); + + // The following call resets [PD] across all modules + EnProfiler.ResetSession(true); + @endcode + */ + static proto void ResetSession(bool fullReset = false); + + + + /** \name EnProfilerFlags + Set of functions to configure the currently active EnProfilerFlags + */ + //@{ + + /** + \brief Override the currently used set of EnProfilerFlags across the API + \note DEFAULT: EnProfilerFlags.ALL + \param flags \p int The combination of desired EnProfilerFlags to override the currently used set + \param sessionReset \p bool When set to false, no [SR] will trigger, regardless of situation + \return \p int The currently used set of EnProfilerFlags after the function call + + @code + // No RESET flag, [PD] will be accumulated across frames + // No RECURSIVE flag, only the curently profiled module will be sorted + EnProfiler.SetFlags(EnProfilerFlags.NONE); + + // RESET flag, [PD] will be reset after sorting + // No RECURSIVE flag, only the curently profiled module will be sorted + EnProfiler.SetFlags(EnProfilerFlags.RESET); + + // RESET flag, [PD] will be reset after sorting + // RECURSIVE flag, all modules will be sorted + EnProfiler.SetFlags(EnProfilerFlags.ALL); + @endcode + */ + static proto int SetFlags(int flags, bool sessionReset = true); + + /** + \brief Get the currently used flags across the API + \return \p int The currently used set of EnProfilerFlags + + @code + int flags = EnProfiler.GetFlags(); + + if (flags & EnProfilerFlags.RECURSIVE) + { + Print("Currently profiling all modules."); + } + @endcode + */ + static proto int GetFlags(); + + /** + \brief Check if the flags are set + \note Is effectively the same as the code displayed in GetFlags example, but without the bitwise operation + \param flags \p int The combination of EnProfilerFlags to check if present + \return \p bool If the flags are set + + @code + if (EnProfiler.IsFlagsSet(EnProfilerFlags.ALL)) + { + Print("Currently all flags are enabled."); + } + + if (EnProfiler.IsFlagsSet(EnProfilerFlags.RECURSIVE)) + { + Print("Currently profiling all modules."); + } + @endcode + */ + static proto bool IsFlagsSet(int flags); + + /** + \brief Add flags to the currently used set of EnProfilerFlags across the API + \note Simply a helper method to quickly add EnProfilerFlags + \param flags \p int The combination of desired EnProfilerFlags to be added to the currently used set + \param sessionReset \p bool When set to false, no [SR] will trigger, regardless of situation + \return \p int The currently used set of EnProfilerFlags after the function call + + @code + // In the case where the current set of EnProfilerFlags is EnProfilerFlags.RESET + EnProfiler.AddFlags(EnProfilerFlags.RECURSIVE); + // The resulting set of flags now will be EnProfilerFlags.RESET | EnProfilerFlags.RECURSIVE + // As the above is pretty much the same as the following + // EnProfiler.SetFlags(EnProfiler.GetFlags() | EnProfilerFlags.RECURSIVE); + // But a much cleaner and faster alternative (bitwise operations in script is ~10x slower than C++) + @endcode + */ + static proto int AddFlags(int flags, bool sessionReset = true); + + /** + \brief Remove flags from the currently used set of EnProfilerFlags across the API + \note Simply a helper method to quickly remove EnProfilerFlags + \param flags \p int The combination of desired EnProfilerFlags to be added to the currently used set + \param sessionReset \p bool When set to false, no [SR] will trigger, regardless of situation + \return \p int The currently used set of EnProfilerFlags after the function call + + @code + // In the case where the current set of EnProfilerFlags is EnProfilerFlags.RESET + EnProfiler.RemoveFlags(EnProfilerFlags.RESET); + // The resulting set of flags now will be EnProfilerFlags.NONE + // As the above is pretty much the same as the following + // EnProfiler.SetFlags(EnProfiler.GetFlags() & ~EnProfilerFlags.RECURSIVE); + // But a much cleaner and faster alternative (bitwise operations in script is ~10x slower than C++) + @endcode + */ + static proto int RemoveFlags(int flags, bool sessionReset = true); + + /** + \brief Remove all flags from the currently used set of EnProfilerFlags across the API + \note Simply a helper method to quickly remove all EnProfilerFlags + \param sessionReset \p bool When set to false, no [SR] will trigger, regardless of situation + \return \p int The currently used set of EnProfilerFlags after the function call + + @code + // In the case where the current set of EnProfilerFlags is EnProfilerFlags.RESET + EnProfiler.ClearFlags(); + // The resulting set of flags now will be EnProfilerFlags.NONE + // As the above is pretty much the same as the following + // EnProfiler.SetFlags(EnProfilerFlags.NONE); + // But a much cleaner and implicit alternative + @endcode + */ + static proto int ClearFlags(bool sessionReset = true); + + //@} + + + + /** \name EnProfilerModule + Set of functions to configure the currently profiled EnProfilerModule + */ + //@{ + + /** + \brief Set the module to be profiled + \note DEFAULT: EnProfilerModule.CORE + \note When session reset is enabled, it will only reset the module which it is currently being set to, previous module data will be untouched + \param module \p EnProfilerModule The module to profile + \param sessionReset \p bool When set to false, no [SR] will trigger, regardless of situation + + @code + EnProfiler.SetModule(EnProfilerModule.WORLD); + @endcode + */ + static proto void SetModule(EnProfilerModule module, bool sessionReset = true); + + /** + \brief Get the currently profiled module + \return \p EnProfilerModule The currently profiled module + + @code + EnProfilerModule module = EnProfiler.GetModule(); + @endcode + */ + static proto EnProfilerModule GetModule(); + + /** + \brief Helper to convert EnProfilerModule to string + \param module \p EnProfilerModule The module to get the name of + \return \p string The name of the module + + @code + string moduleName = EnProfiler.ModuleToName(EnProfilerModule.GAME); + @endcode + */ + static proto owned string ModuleToName(EnProfilerModule module); + + /** + \brief Convert string to EnProfilerModule + \param moduleName \p string The name of the module + \param module \p EnProfilerModule The enum value of the module or EnProfilerModule.ERROR if not found + \return \p bool Whether the module was found + + @code + // Get the name of the module of the current class + string nameOfCurrentModule = Type().GetModule(); + EnProfilerModule module; + + // Convert it to the enum value + if (EnProfiler.NameToModule(nameOfCurrentModule, module)) + { + EnProfiler.SetModule(module); + } + else + { + ErrorEx(string.Format("Could not find EnProfilerModule: %1", nameOfCurrentModule)); + } + @endcode + */ + static proto bool NameToModule(string moduleName, out EnProfilerModule module); + + //@} + + + + /** + \brief Set the interval for the [SD] to update + \note DEFAULT: 0 + \note [DM] has the following values: {0, 5, 10, 20, 30, 50, 60, 120, 144}; When an interval not part of this list is set, [DM] will be set to "CUSTOM_INTERVAL" + \note Does not affect the gathering of [PD], this will happen continuously as the profiling is enabled + \note This also delays the [SR] caused by EnProfilerFlags.RESET + \param interval \p int Amount of frames to wait before [SD] is updated + \param sessionReset \p bool When set to false, no [SR] will trigger, regardless of situation + + @code + // This will make it so that [SD] is updated every 60 frames + EnProfiler.SetInterval(60); + @endcode + */ + static proto void SetInterval(int interval, bool sessionReset = true); + + /** + \brief Get the currently set interval + \return \p int The currently set interval + + @code + int currentInterval = EnProfiler.GetInterval(); + @endcode + */ + static proto int GetInterval(); + + + + /** + \brief Set the resolution of the fetched Time data + \note DEFAULT: 100000 + \note [DM] has the following values: {100000, 1000000, 1, 10, 100, 1000, 10000}; These are the only values available, otherwise it will round up to one in the list + \note Does not affect any data itself, only the fetching and displaying of it (therefore, no [SR] is ever triggered by this method) + \param resolution \p int The nth resolution of a second + + @code + // Have all time being reported in 1 second + EnProfiler.SetTimeResolution(1); + + // Have all time being reported in 1000th of a second (ms) + EnProfiler.SetTimeResolution(1000); + @endcode + */ + static proto void SetTimeResolution(int resolution); + + /** + \brief Get the currently set time resolution + \return \p int The currently set resolution + + @code + int currentTimeResolution = EnProfiler.GetTimeResolution(); + @endcode + */ + static proto int GetTimeResolution(); + + + + /** + \brief Enable/disable returning calculated averages + \note DEFAULT: false + \note When EnProfilerFlags.RESET flag is not present, it will divide by the session frame + \note When an interval is set, it will divide by the interval + \note Does not affect any data itself, only the fetching and displaying of it (therefore, no [SR] is ever triggered by this method) + \note [CI] will never be an average, it will always be the current count of the instance (allocations will be the value of how many times an instance is created) + \param enable \p bool Whether to enable or disable + + @code + // For example, take the situation where we only reset every 60 frames + EnProfiler.AddFlags(EnProfilerFlags.RESET); + EnProfiler.SetInterval(60); + EnProfiler.EnableAverage(true); + + // And a method is called once per frame, gathering the count of that function will be 1 + // Or if a method is called twice per frame, gathering the count of that function will be 2 + // Or if a method is 3 times every 3 frames, gathering the count of that function will be 1 + // ... + // So you get the average amount of times the method is called per frame, out of the sample of 60 frames + @endcode + */ + static proto void EnableAverage(bool enable); + + /** + \brief Check if returning of average data is enabled + \return \p bool Whether returning of average data is enabled + + @code + bool isDataAverage = EnProfiler.IsAverage(); + @endcode + */ + static proto bool IsAverage(); + + + + /** + \brief Print out [SD] to script log + + @code + EnProfiler.Dump(); + @endcode + */ + static proto void Dump(); + + + + /** \name Frame data + Set of functions to obtain information about frame counts + */ + //@{ + + /** + \brief Get the total amount of frames passed + \return \p int The total amount of frames passed + + @code + int gameFrame = EnProfiler.GetGameFrame(); + @endcode + */ + static proto int GetGameFrame(); + + /** + \brief Get the total amount of frames in this profiling session + \note This will only differ from GetProfiledSessionFrames when there is an Interval set + \return \p int The total amount of frames in this profiling session + + @code + int sessionFrame = EnProfiler.GetSessionFrame(); + @endcode + */ + static proto int GetSessionFrame(); + + /** + \brief Get the total amount of frames across all profiling session + \note This will only differ from GetProfiledFrames when there was an Interval set at some point + \return \p int The total amount of frames across all profiling session + + @code + int totalFrames = EnProfiler.GetTotalFrames(); + @endcode + */ + static proto int GetTotalFrames(); + + /** + \brief Get the total amount of frames profiled in this profiling session + \note This will only differ from GetSessionFrame when there is an Interval set + \return \p int The total amount of frames profiled in this profiling session + + @code + int profiledSessionFrames = EnProfiler.GetProfiledSessionFrames(); + @endcode + */ + static proto int GetProfiledSessionFrames(); + + /** + \brief Get the total amount of frames profiled across all profiling session + \note This will only differ from GetTotalFrames when there was an Interval set at some point + \return \p int The total amount of frames profiled across all profiling session + + @code + int totalProfiledFrames = EnProfiler.GetProfiledFrames(); + @endcode + */ + static proto int GetProfiledFrames(); + + //@} + + + + /** \name Sorted data + Set of functions to obtain [SD] + \warning Data is appended to the array, it will not clear any previous data already existing in the array + \note Read SortData as well for more information regarding [SD] + */ + //@{ + + /** + \brief Obtain [SD] for Time Per Class + \param outArr \p array Array sorted by time consumed by a class + \param count \p int The maximum amount of entries wanted + + @code + // In this example the array will be filled with the 20 most time intensive classes + // If there are less than 20 classes which consumed time, it will output that number of classes instead + array timePerClass = {}; + EnProfiler.GetTimePerClass(timePerClass, 20); + + // In this example the array will be filled with all classes sorted by time + array timePerClass2 = {}; + EnProfiler.GetTimePerClass(timePerClass2); + @endcode + */ + static proto void GetTimePerClass(notnull out array outArr, int count = int.MAX); + + /** + \brief Obtain [SD] for Allocations Per Class + \param outArr \p array Array sorted by number of allocations of a class + \param count \p int The maximum amount of entries wanted + + @code + array allocPerClass = {}; + EnProfiler.GetAllocationsPerClass(allocPerClass, 20); + @endcode + */ + static proto void GetAllocationsPerClass(notnull out array outArr, int count = int.MAX); + + /** + \brief Obtain [SD] for Instances Per Class + \param outArr \p array Array sorted by number of instances of a class + \param count \p int The maximum amount of entries wanted + + @code + array instancesPerClass = {}; + EnProfiler.GetInstancesPerClass(instancesPerClass, 20); + @endcode + */ + static proto void GetInstancesPerClass(notnull out array outArr, int count = int.MAX); + + /** + \brief Obtain [SD] for Time Per Function + \param outArr \p array Array sorted by time consumed by a function + \param count \p int The maximum amount of entries wanted + + @code + array timePerFunc = {}; + EnProfiler.GetTimePerFunc(timePerFunc, 20); + @endcode + */ + static proto void GetTimePerFunc(notnull out array outArr, int count = int.MAX); + + /** + \brief Obtain [SD] for Count Per Function + \param outArr \p array Array sorted by amount of times a function was called + \param count \p int The maximum amount of entries wanted + + @code + array countPerFunc = {}; + EnProfiler.GetCountPerFunc(countPerFunc, 20); + @endcode + */ + static proto void GetCountPerFunc(notnull out array outArr, int count = int.MAX); + + //@} + + + + /** \name Specific data + Set of functions to obtain specific data + */ + //@{ + + /** + \brief Obtain [SD] or [PD] regarding the time a specific class consumed + \param clss \p typename Typename of desired class + \param immediate \p bool When true, it will pull from [SD], when false it will pull from [PD] + \return \p float Time consumed by the specified class + + @code + // Consider the class + EPTHelperClass clss = new EPTHelperClass(); + + // Some functions being called here... + + // Gathering of data can be done through + float timeOfClass = EnProfiler.GetTimeOfClass(clss.Type(), true); + + // Or when you have no variable/reference + float timeOfClass2 = EnProfiler.GetTimeOfClass(StaticGetType(EPTHelperClass), true); + @endcode + */ + static proto float GetTimeOfClass(typename clss, bool immediate = false); + + /** + \brief Obtain [SD] or [PD] regarding the allocations of a specific class + \param clss \p typename Typename of desired class + \param immediate \p bool When true, it will pull from [SD], when false it will pull from [PD] + \return \p int Allocations of the specified class + + @code + int allocationsOfClass = EnProfiler.GetAllocationsOfClass(StaticGetType(EPTHelperClass), true); + @endcode + */ + static proto int GetAllocationsOfClass(typename clss, bool immediate = false); + + /** + \brief Obtain [SD] or [PD] regarding the [CI] of a specific class + \param clss \p typename Typename of desired class + \param immediate \p bool When true, it will pull from [SD], when false it will pull from [PD] + \return \p int [CI] of the specified class + + @code + int instancesOfClass = EnProfiler.GetInstancesOfClass(StaticGetType(EPTHelperClass), true); + @endcode + */ + static proto int GetInstancesOfClass(typename clss, bool immediate = false); + + /** + \brief Obtain [SD] or [PD] regarding the time consumed by a specific function + \param funct \p string Function name + \param clss \p typename Typename of class the function belongs to + \param immediate \p bool When true, it will pull from [SD], when false it will pull from [PD] + \return \p float Time consumed by the specified function or -1 when function was not found + + @code + float timeOfFunc = EnProfiler.GetTimeOfFunc("StringFormat", StaticGetType(EnProfilerTests), true); + @endcode + */ + static proto float GetTimeOfFunc(string funct, typename clss, bool immediate = false); + + /** + \brief Obtain [SD] or [PD] regarding the time consumed by a specific global function + \param funct \p string Function name + \param immediate \p bool When true, it will pull from [SD], when false it will pull from [PD] + \return \p float Time consumed by the specified function or -1 when function was not found + + @code + float timeOfFunc = EnProfiler.GetTimeOfFuncG("ErrorEx", true); + @endcode + */ + static proto float GetTimeOfFuncG(string funct, bool immediate, bool immediate = false); + + /** + \brief Obtain [SD] or [PD] regarding the amount of times a specific function was called + \param funct \p string Function name + \param clss \p typename Typename of class the function belongs to + \param immediate \p bool When true, it will pull from [SD], when false it will pull from [PD] + \return \p int Amount of calls to the specified function or -1 when function was not found + + @code + int callCountOfFunc = EnProfiler.GetCountOfFunc("StringFormat", StaticGetType(EnProfilerTests), true); + @endcode + */ + static proto int GetCountOfFunc(string funct, typename clss, bool immediate = false); + + /** + \brief Obtain [SD] or [PD] regarding the amount of times a specific function was called + \param funct \p string Function name + \param immediate \p bool When true, it will pull from [SD], when false it will pull from [PD] + \return \p int Amount of calls to the specified function or -1 when function was not found + + @code + int callCountOfFunc = EnProfiler.GetCountOfFuncG("ErrorEx", true); + @endcode + */ + static proto int GetCountOfFuncG(string funct, bool immediate = false); + + //@} + + + + /** \name Misc + Set of helper functions + */ + //@{ + + /** + \brief Helper method to ascertain the profiler will record [PD] right after this call + \return \p bool Whether it was enabled before or not + + @code + bool wasEnabled = EnProfiler.RequestImmediateData(); + @endcode + */ + static bool RequestImmediateData() + { + // I only care if it is actually profiling right now, so C + bool wasEnabled = IsEnabledC(); + + if (!wasEnabled) + { + // I want the data, and I want it now, so immediate + Enable(true, true); + } + + return wasEnabled; + } + + //@} +}; + + //@} diff --git a/scripts/1_Core/DayZ/proto/EnScript.c b/scripts/1_Core/DayZ/proto/EnScript.c new file mode 100644 index 0000000000000000000000000000000000000000..048072e56db390d9103575b2f5fec4923d6d7f6a --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnScript.c @@ -0,0 +1,1003 @@ +/** + * \defgroup Enforce Enforce script essentials + * \note \p float ftime; The deltaTime since last frame + * \note \p float FLT_MAX; The maximum value for float + * \note \p float FLT_MIN; The minimum value for float + * @{ + */ + + //! Super root of all classes in Enforce script +class Class +{ + /** + \brief Returns true when instance is of the type, or inherited one. + \param type Class type + \returns \p bool true when 'clType' is the same as 'type', or inherited one. + @code + if (inst && inst.IsInherited(Widget)) + { + Print("inst is inherited from Widget class!"); + } + @endcode + */ + proto native external bool IsInherited(typename type); + + /** + \brief Returns name of class-type + \param inst Class + \returns \p string class-type + @code + Man player = g_Game.GetPlayer(); + string className = player.ClassName(); + Print(className); + + >> className = 'Man' + @endcode + */ + proto native owned external string ClassName(); + + string GetDebugName() { return ClassName(); } + + /** + \brief Returns typename of object's class + \returns \p typename class-type + @code + Man player = g_Game.GetPlayer(); + typename type = player.Type(); + Print(type.ToString()); + + >> 'Man' + @endcode + */ + proto native external typename Type(); + + /** + \brief Returns typename of object's reference + \returns \p typename class-type + @code + EntityAI e; + Print(e.StaticType()); + + >> 'EntityAI' + @endcode + */ + proto external static typename StaticType(); + + /** + \brief Returns typename of class even without a variable or instance + \returns \p typename class-type + @code + typename eAITypename = StaticGetType(EntityAI); + @endcode + */ + static typename StaticGetType(typename t) + { + return t; + } + + proto external string ToString(); + + /** + \brief Try to safely down-cast base class to child class. + \returns down-casted 'from' pointer when cast is successfull (classes are related), or null if casting is invalid + @code + // assume that Man inheites from Object + Object obj = g_Game.GetPlayer(); + Man player = Man.Cast(obj); + + if (player) + { + // horay! + } + @endcode + */ + proto static Class Cast(Class from); + + /** + \brief Try to safely down-cast base class to child class. + \returns \p bool true when 'from' is not null and cast successfull, false when casting is not valid or 'from' is null + @code + // assume that Man inheites from Object + Object obj = g_Game.GetPlayer(); + Man player; + + if (Class.CastTo(player, obj)) + { + // horay! + } + @endcode + */ + proto static bool CastTo(out Class to, Class from); + + //! This function is for internal script usage + private proto static bool SafeCastType(Class type, out Class to, Class from); +}; + + //! TODO doc +class Managed +{ +}; + +//! TODO doc +class NonSerialized +{ +}; + +//! script representation for C++ RTTI types +typedef int[] TypeID; + +//! Module containing compiled scripts. +class ScriptModule +{ + private void ~ScriptModule(); + + /*!dynamic call of function + when inst == NULL, it's global function call, otherwise it's method of class + returns true, when success + The call creates new thread, so it's legal to use sleep/wait + */ + proto volatile int Call(Class inst, string function, void parm); + + /*!dynamic call of function + when inst == NULL, it's global function call, otherwise it's method of class + returns true, when success + The call do not create new thread!!!! + */ + proto volatile int CallFunction(Class inst, string function, out void returnVal, void parm); + proto volatile int CallFunctionParams(Class inst, string function, out void returnVal, Class parms); + proto native void Release(); + + /** + \brief Do load script and create ScriptModule for it + \param parentModule Module + \param scriptFile Script path + \param listing ?? + \returns \p ScriptModule Loaded scripted module + @code + ??? + @endcode + */ + static proto native ScriptModule LoadScript(ScriptModule parentModule, string scriptFile, bool listing); +}; + +//main script module (contains script.c and this file) +//ScriptModule g_Script; + +class EnScript +{ + private void EnScript() {} + private void ~EnScript() {} + + /** + \brief Dynamic read of variable value by its name + \param inst When inst == NULL, it's for global variable, otherwise it's class member + \param index Is index when variable is array + \param[out] result Variable must be of the same type! + \returns \p int true when success + @code + float count = 0; + + bool success = EnScript.GetClassVar(myClass, "m_Counter", 0, count); + Print(count); + Print(success); + + >> count = 5 + >> success = 1 + @endcode + */ + static proto int GetClassVar(Class inst, string varname,int index, out void result); + + /** + \brief Dynamic write to variable by its name + \param inst when inst == NULL, it's for global variable, otherwise it's class member + \param varname + \param index Is index when variable is array + \param input Input variable must be of the same type! + \returns \p int Returns true(1) when success + @code + Print(myClass.m_Counter); + + >> m_Counter = 0 + + bool success = EnScript.SetClassVar(myClass, "m_Counter", 0, 5.0); + + Print(myClass.m_Counter); + Print(success); + + >> m_Counter = 5 + >> success = 1 + @endcode + */ + static proto int SetClassVar(Class inst, string varname, int index, void input); + + /** + \brief Sets variable value by value in string + \param[out] var + \param value + \returns int + @code + ??? + @endcode + */ + static proto int SetVar(out void var, string value); + + /** + \brief Debug tool for watching certain variable. Invokes debugger whenever is variable used + \param var Certain variable for watching + \param flags = 1 means it will break even when not modified + \return \p void + */ + static proto void Watch(void var, int flags); +}; + + + +/** +\brief Sorts static array of integers(ascendically) / floats(ascendically) / strings(alphabetically) + \param param_array \p array Array to sort + \param num \p int How many items will be sorted in array + \return \p void + @code + string arrStr[3] = {"Dog", "Car", "Apple"}; + Sort(arrStr, 2) + for ( int x = 0; x < 3; x++ ) + { + Print( arrStr[x] ); + } + + >> 'Car' + >> 'Dog' + >> 'Apple' + @endcode +*/ +proto void Sort(void param_array[], int num); +proto void reversearray(void param_array); +proto void copyarray(void destArray, void srcArray); + +/** +\brief Parses one token from input string. Result is put into token string, and type of token is returned. Input string is left-truncated by the resulting token length. + \param[in,out] input \p string String for parse\ Output is without founded token + \param[out] token \p string Founded string token + \return \p int Type of token + \verbatim +Token types: + 0 - error, no token + 1 - defined token (special characters etc. . / * ) + 2 - quoted string. Quotes are removed -> TODO + 3 - alphabetic string + 4 - number + 5 - end of line -> TODO + \endverbatim + @code + string input = "Hello*World"; + string token1; + string token2; + + int result1 = ParseStringEx(input, token1); + int result2 = ParseStringEx(input, token2); + + Print( String( "Token1 = '" + token1 + "' Type = " + result1.ToString() ) ); + Print( String( "Token2 = '" + token2 + "' Type = " + result2.ToString() ) ); + Print( input ); + + >> 'Toke1 = 'Hello' Type = 3' + >> 'Toke1 = '*' Type = 1' + @endcode +*/ +proto int ParseStringEx(inout string input, string token); + +/** +\brief Parses string into array of tokens returns number of tokens + \param input \p string String for parse + \param[out] tokens \p array[] Parsed string in array + \return \p int Number of tokens + @code + string token[2]; + int result = ParseString("Hello World", token); + + for( int i = 0; i < 2; i++ ) + { + Print(token[i]); + } + + >> 'Hello' + >> 'World' + @endcode +*/ +proto int ParseString(string input, out string tokens[]); + +/** +\brief Kills thread. + \param owner Can be NULL for global threads. + \param name Name of the first function on stack + \return \p int ??? + @code + ??? + @endcode +*/ +proto native int KillThread(Class owner, string name); + +/** +Yiels execution to other threads and then it continues. Obsolete... +*/ +proto volatile void Idle(); + +/** +\brief Debug function. Returns current function on stack of the thread + \param owner Can be NULL for global threads + \param name Name of the first function on stack + \param backtrace ??? + \param linenumber ??? + \return \p string ??? + @code + ??? + @endcode +*/ +proto owned string ThreadFunction(Class owner, string name, int backtrace, out int linenumber); + +//!Helper for passing string expression to functions with void parameter. Example: Print(String("Hello " + var)); +string String(string s) +{ + return s; +} + +//!Helper for printing out string expression. Example: PrintString("Hello " + var); +void PrintString(string s) +{ + Print(s); +} + +class array +{ + /*! + O(1) complexity. + \return Number of elements of the array + */ + proto native int Count(); + /*! + Destroyes all elements of the array and sets the Count to 0. + The underlying memory of the array is not freed. + */ + proto native void Clear(); + /*! + Sets n-th element to given value. + */ + proto void Set(int n, T value); + /*! + Tries to find the first occurance of given value in the array. + \return Index of the first occurance of `value` if found, -1 otherwise + */ + proto int Find(T value); + /*! + \return Element at the index `n` + */ + + proto T Get(int n); + /*! + Inserts element at the end of array. + \param value + Element to be inserted + \return + Position at which element is inserted + */ + proto int Insert(T value); + /*! + Inserts element at certain position and moves all elements behind + this position by one. + \param value + Element to be inserted + \param index + Position at which element is inserted. Must be less than Array::GetCardinality() + \return + Number of elements after insertion + */ + proto int InsertAt(T value, int index); + /** + \brief Inserts all elements from array + \param from \p array array from which all elements will be added + @code + TStringArray arr1 = new TStringArray; + arr1.Insert( "Dave" ); + arr1.Insert( "Mark" ); + arr1.Insert( "John" ); + + TStringArray arr2 = new TStringArray; + arr2.Insert( "Sarah" ); + arr2.Insert( "Cate" ); + + arr1.InsertAll(arr2); + + for ( int i = 0; i < arr1.Count(); i++ ) + { + Print( arr1.Get(i) ); + } + + delete arr2; + delete arr1; + + >> "Dave" + >> "Mark" + >> "John" + >> "Sarah" + >> "Cate" + @endcode + */ + void InsertAll(notnull array from) + { + for ( int i = 0; i < from.Count(); i++ ) + { + Insert( from.Get(i) ); + } + } + /*! + Removes element from array. The empty position is replaced by + last element, so removal is quite fast but do not retain order. + \param index + Index of element to be removed + */ + proto native void Remove(int index); + /*! + Removes element from array, but retain all elements ordered. It's + slower than Remove + \param index + Index of element to be removed + */ + proto native void RemoveOrdered(int index); + /*! + Resizes the array to given size. + If the `newSize` is lower than current Count overflowing objects are destroyed. + If the `newSize` is higher than current Count missing elements are initialized to zero (null). + */ + proto native void Resize(int newSize); + + /*! + Resizes the array to given size internally. + Is used for optimization purposes when the approx. size is known beforehand + */ + proto native void Reserve(int newSize); + + /*! + Swaps the contents of this and `other` arrays. + Does not involve copying of the elements. + */ + proto native void Swap(notnull array other); + + /*! + Sorts elements of array, depends on underlaying type. + */ + proto native void Sort(bool reverse = false); + /*! + Copes contents of `from` array to this array. + \return How many elements were copied + */ + + proto int Copy(notnull array from); + proto int Init(T init[]); + + void RemoveItem(T value) + { + int remove_index = Find(value); + + if ( remove_index >= 0 ) + { + RemoveOrdered(remove_index); + } + } + + void RemoveItemUnOrdered(T value) + { + int remove_index = Find(value); + + if ( remove_index >= 0 ) + { + Remove(remove_index); + } + } + + bool IsValidIndex( int index ) + { + return ( index > -1 && index < Count() ); + } + + /* + T GetChecked( int index ) + { + if( IsValidIndex( index ) ) + return Get( index ); + else + return null; + } + */ + + /** + \brief Print all elements in array + \return \p void + @code + my_array.Debug(); + + >> "One" + >> "Two" + >> "Three" + @endcode + */ + void Debug() + { + Print(string.Format("Array count: %1", Count())); + for (int i = 0; i < Count(); i++) + { + T item = Get(i); + Print(string.Format("[%1] => %2", i, item)); + } + } + + /** + \brief Returns a random index of array. If Count is 0, return index is -1 . + \return \p int Random index of array + @code + Print( my_array.GetRandomIndex() ); + + >> 2 + @endcode + */ + int GetRandomIndex() + { + if ( Count() > 0 ) + { + return Math.RandomInt(0, Count()); + } + + return -1; + } + + /** + \brief Returns a random element of array + \return \p int Random element of array + @code + Print( my_array.GetRandomElement() ); + + >> "Three" + @endcode + */ + T GetRandomElement() + { + return Get(GetRandomIndex()); + } + + void SwapItems(int item1_index, int item2_index) + { + T item1 = Get(item1_index); + Set(item1_index, Get(item2_index)); + Set(item2_index, item1); + } + + void InsertArray(array other) + { + for (int i = 0; i < other.Count(); i++) + { + T item = other.Get(i); + Insert(item); + } + } + + void Invert() + { + int left = 0; + int right = Count() - 1; + if (right > 0) + { + while (left < right) + { + T temp = Get(left); + Set(left++, Get(right)); + Set(right--, temp); + } + } + } + + /** + \brief Returns a index in array moved by specific number + \return \p int Moved index in this array + @code + Print( "Count: "+ my_array.Count() ); + Print( "Moved 1:"+ my_array.MoveIndex(2, 1) ); + Print( "Moved 3:"+ my_array.MoveIndex(2, 2) ); + + >> "Count: 4" + >> "Moved index 2 by 1: 3"; + >> "Moved index 2 by 2: 0"; + @endcode + */ + int MoveIndex(int curr_index, int move_number) + { + int count = Count(); + int new_index = curr_index; + + if ( move_number > 0 ) + { + new_index = curr_index + move_number; + } + + if ( move_number < 0 ) + { + new_index = curr_index - move_number; + + if ( new_index < 0 ) + { + if ( new_index <= -count ) + { + new_index = (new_index % count); + } + + new_index = new_index + count; + } + } + + if ( new_index >= count ) + { + new_index = (new_index % count); + } + + // move_number is 0 + return new_index; + } + + void ShuffleArray() + { + for (int i = 0; i < Count(); i++) + { + SwapItems(i,GetRandomIndex()); + } + } + + /** + \brief Returns an index where 2 arrays start to differ from each other + \return \p int Index from where arrays differ + @code + array arr1 = {0,1,2,3}; + array arr2 = {0,1,3,2}; + int differsAt = arr1.DifferentAtPosition(arr2); + Print(differsAt); + + >> 2 + @endcode + */ + int DifferentAtPosition(array pOtherArray) + { + if (Count() != pOtherArray.Count()) + { + ErrorEx("arrays are not the same size"); + return -1; + } + + for (int i = 0; i < pOtherArray.Count(); ++i) + { + if (Get(i) != pOtherArray.Get(i)) + { + return i; + } + } + + return -1; + } +}; + +//force these to compile so we can link C++ methods to them +typedef array TStringArray; +typedef array TFloatArray; +typedef array TIntArray; +typedef array TBoolArray; +typedef array TClassArray; +typedef array TManagedArray; +typedef array TManagedRefArray; +typedef array TVectorArray; +typedef array TTypenameArray; + +class set +{ + proto native int Count(); + proto native void Clear(); + /*! + Tries to find the first occurance of given value in the set. + \return Index of the first occurance of `value` if found, -1 otherwise + */ + proto int Find(T value); + proto T Get(int n); + /*! + Inserts element at the end of array. + \param value + Element to be inserted + \return + Position at which element is inserted + */ + proto int Insert(T value); + /*! + Inserts element at certain position and moves all elements behind + this position by one. + \param value + Element to be inserted + \param index + Position at which element is inserted. Must be less than Array::GetCardinality() + \return + Number of elements after insertion + */ + proto int InsertAt(T value, int index); + /*! + Removes element from array, but retain all elements ordered. + \param index + Index of element to be removed + */ + proto native void Remove(int index); + proto int Copy(set from); + proto native void Swap(set other); + proto int Init(T init[]); + + void InsertSet(set other) + { + int count = other.Count(); + for (int i = 0; i < count; i++) + { + T item = other[i]; + Insert(item); + } + } + + void RemoveItem(T value) + { + int remove_index = Find(value); + if (remove_index >= 0) + { + Remove(remove_index); + } + } + + void RemoveItems(set other) + { + int count = other.Count(); + for (int i = 0; i < count; i++) + { + T item = other[i]; + RemoveItem(item); + } + } + + void Debug() + { + Print(string.Format("Set count: %1", Count())); + for (int i = 0; i < Count(); i++) + { + T item = Get(i); + Print(string.Format("[%1] => %2", i, item)); + } + } +}; + +//force these to compile so we can link C++ methods to them +typedef set TStringSet; +typedef set TFloatSet; +typedef set TIntSet; +typedef set TClassSet; +typedef set TManagedSet; +typedef set TManagedRefSet; +typedef set TTypenameSet; + +typedef int MapIterator; +/** + \brief Associative array template + \n usage: + @code + autoptr map prg_count = new map; + + // fill + project_locations.Insert("dayz", 10); + project_locations.Insert("arma", 20); + project_locations.Insert("tkom", 1); + + Print(project_locations.Get("arma")); // prints '20' + + @endcode + + */ +class map +{ + /*! + \return + The number of elements in the hashmap. + */ + proto native int Count(); + + /*! + Clears the hash map. + */ + proto native void Clear(); + /*! + Search for an element with the given key. + + \param key + The key of the element to find + \return + Pointer to element data if found, NULL otherwise. + */ + proto TValue Get(TKey key); + /*! + Search for an element with the given key. + + \param key + The key of the element to find + \param val + result is stored to val + \return + returns True if given key exist. + */ + proto bool Find(TKey key, out TValue val); + /*! + Return the i:th element in the map. + Note: This operation is O(n) complexity. Use with care! + + \param index + The position of the element in the map + \return + The element on the i:th position + */ + proto TValue GetElement(int index); + /*! + Return the i:th element key in the map. + Note: This operation is O(n) complexity. Use with care! + + \param i + The position of the element key in the map + \return + Return key of i-th element + */ + proto TKey GetKey(int i); + /*! + Sets value of element with given key. If element with key not exists, it is created. + Note: creating new elements is faster using Insert function. + */ + proto void Set(TKey key, TValue value); + /*! + Removes element with given key. + */ + proto void Remove(TKey key); + /*! + Removes i:th element with given key. + Note: This operation is O(n) complexity. Use with care! + \param i + The position of the element key in the map + */ + proto void RemoveElement(int i); + /*! + Returns if map contains element with given key. + */ + proto bool Contains(TKey key); + /*! + Insert new element into hash map. + + \param key + Key of element to be inserted. + \param value + Data of element to be inserted. + */ + proto bool Insert(TKey key, TValue value); + proto int Copy(map from); + + array GetKeyArray() + { + array keys = new array; + for (int i = 0; i < Count(); i++) + { + keys.Insert( GetKey( i ) ); + } + return keys; + } + + array GetValueArray() + { + array elements = new array; + for (int i = 0; i < Count(); i++) + { + elements.Insert( GetElement( i ) ); + } + return elements; + } + + bool ReplaceKey(TKey old_key, TKey new_key) + { + if (Contains(old_key)) + { + Set(new_key, Get(old_key)); + Remove(old_key); + return true; + } + return false; + } + + TKey GetKeyByValue(TValue value) + { + TKey ret; + for (int i = 0; i < Count(); i++) + { + if (GetElement(i) == value) + { + ret = GetKey(i); + break; + } + } + + return ret; + } + + bool GetKeyByValueChecked(TValue value, out TKey key) + { + for (int i = 0; i < Count(); i++) + { + if (GetElement(i) == value) + { + key = GetKey(i); + return true; + } + } + return false; + } + + proto native MapIterator Begin(); + proto native MapIterator End(); + proto native MapIterator Next(MapIterator it); + proto TKey GetIteratorKey(MapIterator it); + proto TValue GetIteratorElement(MapIterator it); +}; + +typedef map TIntFloatMap; +typedef map TIntIntMap; +typedef map TIntStringMap; +typedef map TIntClassMap; +typedef map TIntManagedMap; +typedef map TIntManagedRefMap; +typedef map TIntTypenameMap; +typedef map TIntVectorMap; + +typedef map TStringFloatMap; +typedef map TStringIntMap; +typedef map TStringStringMap; +typedef map TStringClassMap; +typedef map TStringManagedMap; +typedef map TStringManagedRefMap; +typedef map TStringTypenameMap; +typedef map TStringVectorMap; + +typedef map TClassFloatMap; +typedef map TClassIntMap; +typedef map TClassStringMap; +typedef map TClassClassMap; +typedef map TClassManagedMap; +typedef map TClassManagedRefMap; +typedef map TClassTypenameMap; +typedef map TClassVectorMap; + +typedef map TTypeNameFloatMap; +typedef map TTypeNameIntMap; +typedef map TTypeNameStringMap; +typedef map TTypeNameClassMap; +typedef map TTypeNameManagedMap; +typedef map TTypeNameManagedRefMap; +typedef map TTypeNameTypenameMap; +typedef map TTypeNameVectorMap; + +typedef map TManagedFloatMap; +typedef map TManagedIntMap; +typedef map TManagedStringMap; +typedef map TManagedClassMap; +typedef map TManagedManagedMap; +typedef map TManagedManagedRefMap; +typedef map TManagedTypenameMap; +typedef map TManagedVectorMap; + +typedef map TManagedRefFloatMap; +typedef map TManagedRefIntMap; +typedef map TManagedRefStringMap; +typedef map TManagedRefClassMap; +typedef map TManagedRefManagedMap; +typedef map TManagedRefManagedRefMap; +typedef map TManagedRefTypenameMap; +typedef map TManagedRefVectorMap; + + //@} diff --git a/scripts/1_Core/DayZ/proto/EnString.c b/scripts/1_Core/DayZ/proto/EnString.c new file mode 100644 index 0000000000000000000000000000000000000000..b7ef3b7ce58cd697c1aff5cde3076ef226c36b45 --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnString.c @@ -0,0 +1,529 @@ +/** + * \defgroup Strings Strings + * @{ + */ +class string +{ + static const string Empty; + + /** + \brief Converts string to integer + \return \p int - Converted \p string. + @code + string str = "56"; + int i = str.ToInt(); + Print(i); + + >> i = 56 + @endcode + */ + proto native int ToInt(); + + /** + \brief Converts string to integer + \return \p int - Converted \p string. + @code + string str = "0xFF"; + int i = str.HexToInt(); + Print(i); + + >> i = 255 + @endcode + */ + proto native int HexToInt(); + + /** + \brief Converts string to float + \return \p float - Converted \p string \p in float. + @code + string str = "56.6"; + float f = str.ToFloat(); + Print(f); + + >> f = 56.6 + @endcode + */ + proto native float ToFloat(); + + /** + \brief Returns a vector from a string + \return \p vector Converted s as vector + @code + string str = "1 0 1"; + vector v = str.ToVector(); + Print(v); + + >> v = <1,0,1> + @endcode + */ + proto vector ToVector(); + + + /** + \brief Convert beautified string into a vector + \param vec \p beautified string + \return \p vector resulting vector + */ + vector BeautifiedToVector() + { + string copy = value; + copy.Replace("<", ""); + copy.Replace(">", ""); + copy.Replace(",", " "); + return copy.ToVector(); + } + /** + \brief Converts string's first character to ASCII code + \param str String for convert to ASCII code + \return \p ascii code \p int. + @code + int ascii = "M".ToAscii(); + Print(ascii); + + >> ascii = 77 + @endcode + */ + proto native int ToAscii(); + + /** + \brief Returns internal type representation. Can be used in runtime, or cached in variables and used for faster inheritance checking + \returns \p typename Type of class + @code + ??? + @endcode + */ + proto native typename ToType(); + + //! Return string representation of variable + static proto string ToString(void var, bool type = false, bool name = false, bool quotes = true); + + /** + \brief Substring of 'str' from 'start' position 'len' number of characters + \param start Position in \p str + \param len Count of characters + \return \p string - Substring of \p str + @code + string str = "Hello World"; + string strSub = str.Substring(2, 5); + Print(strSub); + + >> strSub = llo W + @endcode + */ + proto string Substring(int start, int len); + + //! Inverted SubString. This deletes everything in between position_start and position_end. + string SubstringInverted( string string_to_split, int position_start, int position_end ) + { + string first_half = string_to_split.Substring(0, position_start); + string second_half = string_to_split.Substring( position_end, string_to_split.Length() - position_end ); + string result = first_half + second_half; + return result; + } + + /** + \brief Substring of 'str' from 'startChar' position 'len' number of characters for UTF8 strings with multibyte chars + \param startChar Position in \p str. + \param len Count of characters + \return \p string - Substring of \p str with \p startChar character and \p len characters + @code + string str = "こんにちは世界"; + string strSub = str.SubstringUtf8(2, 4); + Print(strSub); + + >> strSub = にちは世 + @endcode + */ + proto string SubstringUtf8(int startChar, int len); + + /** + \brief Replace all occurrances of 'sample' in 'str' by 'replace' + \param sample string to search in \p str + \param replace string which replace \p sample in \p str + \return \p int - number of occurrances of 'sample' in 'str' + @code + string test = "If the length of the C string in source is less than num, only the content up to the terminating null-character is copied."; + Print(test); + int count = test.Replace("the", "*"); + Print(count); + Print(test); + + >> string test = 'If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.'; + >> int count = 4 + >> string test = 'If * length of * C string in source is less than num, only * content up to * terminating null-character is copied.' + @endcode + */ + proto int Replace(string sample, string replace); + + /** + \brief Changes string to lowercase. Returns length + \return \p int - Length of changed string + @code + string str = "Hello World"; + int i = str.ToLower(); + Print(str); + Print(i); + + >> str = hello world + >> i = 11 + @endcode + */ + proto int ToLower(); + + /** + \brief Changes string to uppercase. Returns length + \return \p int - Length of changed string + @code + string str = "Hello World"; + int i = str.ToUpper(); + Print(str); + Print(i); + + >> str = HELLO WORLD + >> i = 11 + @endcode + */ + proto int ToUpper(); + + /** + \brief Returns length of string + \return \p int - Length of string + @code + string str = "Hello World"; + int i = str.Length(); + Print(i); + + >> i = 11 + @endcode + */ + proto native int Length(); + + /** + \brief Returns number of characters in UTF8 string + \return \p int - Number of characters in UTF8 string + @code + string str = "こんにちは世界"; + int i = str.LengthUtf8(); + Print(i); + + >> i = 7 + @endcode + */ + proto native int LengthUtf8(); + + /** + \brief Returns hash of string + \return \p int - Hash of string + @code + string str = "Hello World"; + int hash = str.Hash(); + Print(hash); + @endcode + */ + proto native int Hash(); + + /** + \brief Finds 'sample' in 'str'. Returns -1 when not found + \param sample \p string Finding string + \return \p int - Returns position where \p sample starts, or -1 when \p sample not found + @code + string str = "Hello World"; + Print( str.IndexOf( "H" ) ); + Print( str.IndexOf( "W" ) ); + Print( str.IndexOf( "Q" ) ); + + >> 0 + >> 6 + >> -1 + @endcode + */ + proto native int IndexOf(string sample); + + /** + \brief Finds last 'sample' in 'str'. Returns -1 when not found + \param sample \p string Finding string + \return \p int - Returns position where \p sample starts, or -1 when \p sample not found + @code + string str = "Hello World"; + Print( str.IndexOf( "l" ) ); + + >> 9 + @endcode + */ + proto native int LastIndexOf(string sample); + + /** + \brief Finds 'sample' in 'str' from 'start' position. Returns -1 when not found + \param start \p int Start from position + \param sample \p string Finding string expression + \return \p int - Length of string \p s + @code + string str = "Hello World"; + Print( str.IndexOfFrom( 3, "H" ) ); + Print( str.IndexOfFrom( 3, "W" ) ); + Print( str.IndexOfFrom( 3, "Q" ) ); + + >> -1 + >> 6 + >> -1 + @endcode + */ + proto native int IndexOfFrom(int start, string sample); + + /** + \brief Returns true if sample is substring of string + \param sample \p string Finding string expression + \return \p bool true if sample is substring of string + @code + string str = "Hello World"; + Print( str.IndexOfFrom( 3, "Hello" ) ); + Print( str.IndexOfFrom( 3, "Mexico" ) ); + + >> true + >> false + @endcode + */ + bool Contains(string sample) + { + return value.IndexOf(sample) != -1; + } + + /** + \brief Returns trimmed string with removed leading and trailing whitespaces + \return \p string - Trimmed string + @code + string str = " Hello World " + Print( str ); + Print( str.Trim() ); + + >> ' Hello World ' + >> 'Hello World' + @endcode + + */ + proto string Trim(); + + /** + \brief Removes leading and trailing whitespaces in string. Returns length + \return \p int - Count of chars + @code + string str = " Hello World "; + int i = str.TrimInPlace(); + Print(str); + Print(i); + + >> str = 'Hello World' + >> i = 11 + @endcode + */ + proto int TrimInPlace(); + + /** + \brief Parses one token from input string. Result is put into token string, and type of token is returned. Input string is left-truncated by the resulting token length. + \param[out] token \p string Founded string token + \return \p int Type of token + \verbatim + Token types: + 0 - error, no token + 1 - defined token (special characters etc. . / * ) + 2 - quoted string. Quotes are removed -> TODO + 3 - alphabetic string + 4 - number + 5 - end of line -> TODO + \endverbatim + @code + string input = "Hello*World"; + string token1; + string token2; + + int result1 = input.ParseStringEx(token1); + int result2 = input.ParseStringEx(token2); + + Print( "Token1 = '" + token1 + "' Type = " + result1.ToString() ) ); + Print( "Token2 = '" + token2 + "' Type = " + result2.ToString() ) ); + + >> 'Toke1 = 'Hello' Type = 3' + >> 'Toke1 = '*' Type = 1' + @endcode + */ + proto int ParseStringEx(out string token); + + /** + \brief Parses string into array of tokens returns number of tokens + \param[out] tokens \p array[] Parsed string in array + \return \p int Number of tokens + @code + string token[2]; + string str = "Hello World"; + int result = str.ParseString(token); + + for (int i = 0; i < 2; i++) + { + Print(token[i]); + } + + >> 'Hello' + >> 'World' + @endcode + */ + proto int ParseString(out string tokens[]); + + /** + \brief Splits string into array of strings separated by 'sample' + \param sample \p string Strings separator + \return \p TStringArray Array with strings + @code + string example = "The quick brown fox jumps over the lazy dog"; + TStringArray strs = new TStringArray; + example.Split(" ", strs); + + for (int i = 0; i < strs.Count(); i++) + { + Print(strs.Get(i)); + } + + >> 'The' + >> 'quick' + >> 'brown' + >> 'fox' + >> 'jumps' + >> 'over' + >> 'the' + >> 'lazy' + >> 'dog' + @endcode + */ + void Split(string sample, out array output) + { + int txt_len = 0; + int sep_pos = -1; + int nxt_sep_pos = 0; + string text = ""; + + bool line_end = false; + while (line_end == false) + { + sep_pos = sep_pos + txt_len + 1; + nxt_sep_pos = value.IndexOfFrom(sep_pos, sample); + if ( nxt_sep_pos == -1 ) + { + nxt_sep_pos = value.Length(); + line_end = true; + } + + txt_len = nxt_sep_pos - sep_pos; + if ( txt_len > 0 ) + { + text = value.Substring(sep_pos, txt_len); + output.Insert(text); + } + } + } + + // !Joins array of strings into a single string, separated by 'separator'. Inverse of Split + static string Join(string separator, notnull TStringArray tokens) + { + string output; + foreach (int i, string s: tokens) + { + if (i != 0) + output += separator; + output += s; + } + return output; + } + + /** + \brief Gets n-th character from string + \param index character index + \return \p string character on index-th position in string + \warning VME When index less than 0 or greater than string length + @code + string str = "Hello World"; + Print( str[4] ); // Print( str.Get(4) ); + + >> 'o' + @endcode + */ + proto string Get(int index); + + /** + \brief Sets the n-th character in string with the input, replacing previous value + \param index index to be replaced + \param input single non-terminated character value to replace with + \warning VME When index less than 0 or greater than string length + \warning (Diag) VME When string is empty or greater than length of 1 + (Retail) Calls 'string.Insert' except it replaces only the initial character + @code + string str = "Hello World"; + str[4] = "O"; + Print( str ); + + >> 'HellO World' + @endcode + + @code + string str = "Hello World"; + str[6] = "Test "; + Print( str ); + + >> 'Hello Test orld' + @endcode + */ + proto void Set(int index, string input); + +#ifdef DIAG_DEVELOPER + /** + \brief Do not use. Re-implemented for verification of new function due to design of previous function allowing for unexpected behavior that modders may depend on. + \see string.Set warnings for handling existing mods in Retail + @code + string str = "Hello World"; + str.OldSet(6, "Test "); + Print( str ); + + >> 'Hello Test orld' + @endcode + */ + void OldSet(int n, string _value) + { + string pre = value.Substring(0, n); + n += 1; + int length = value.Length() - n; + string post = value.Substring(n, length); + value = pre + _value + post; + } +#endif + + /** + \brief Inserts a string into the n-th index, increasing the string length by the size of the input + \param index index to insert at + \param input string value to insert with + \warning VME When index less than 0 or greater than string length + \warning VME When string is empty + @code + string str = "Hello World"; + str.Insert(6, "Test "); + Print( str ); + + >> 'Hello Test World' + @endcode + */ + proto void Insert(int index, string input); + + /** + \brief Gets n-th character from string + \param index character index + \return \p string character on index-th position in string + @code + int a = 5; + float b = 5.99; + string c = "beta"; + string test = string.Format("Ahoj %1 = %3 , %2", a, b, c); + Print(test); + >> 'Ahoj 5 = 'beta' , 5.99' + @endcode + */ + static proto string Format(string fmt, void param1 = NULL, void param2 = NULL, void param3 = NULL, void param4 = NULL, void param5 = NULL, void param6 = NULL, void param7 = NULL, void param8 = NULL, void param9 = NULL); +}; + +//@} \ No newline at end of file diff --git a/scripts/1_Core/DayZ/proto/EnSystem.c b/scripts/1_Core/DayZ/proto/EnSystem.c new file mode 100644 index 0000000000000000000000000000000000000000..f8b04473d45c1bc4e5e1250bbb0f5b031227eec8 --- /dev/null +++ b/scripts/1_Core/DayZ/proto/EnSystem.c @@ -0,0 +1,534 @@ +/** + * \defgroup System System + * @{ + */ + +/** +\brief Returns world time + \param[out] hour \p int Hour + \param[out] minute \p int Minute + \param[out] second \p int Second + \return \p void + @code + int hour = 0; + int minute = 0; + int second = 0; + + GetHourMinuteSecondUTC(hour, minute, second); + + Print(hour); + Print(minute); + Print(second); + + >> hour = 16 + >> minute = 38 + >> second = 7 + @endcode +*/ +proto void GetHourMinuteSecond(out int hour, out int minute, out int second); + +/** +\brief Returns world date + \param[out] year \p int Year + \param[out] month \p int Month + \param[out] day \p int Day + \return \p void + @code + int year = 0; + int month = 0; + int day = 0; + + GetYearMonthDay(year, month, day); + + Print(year); + Print(month); + Print(day); + + >> year = 2015 + >> month = 3 + >> day = 24 + @endcode +*/ +proto void GetYearMonthDay(out int year, out int month, out int day); + +/** +\brief Returns UTC world time + \param[out] hour \p int Hour + \param[out] minute \p int Minute + \param[out] second \p int Second + \return \p void + @code + int hour = 0; + int minute = 0; + int second = 0; + + GetHourMinuteSecondUTC(hour, minute, second); + + Print(hour); + Print(minute); + Print(second); + + >> hour = 15 + >> minute = 38 + >> second = 7 + @endcode +*/ +proto void GetHourMinuteSecondUTC(out int hour, out int minute, out int second); + +/** +\brief Returns UTC world date + \param[out] year \p int Year + \param[out] month \p int Month + \param[out] day \p int Day + \return \p void + @code + int year = 0; + int month = 0; + int day = 0; + + GetYearMonthDayUTC(year, month, day); + + Print(year); + Print(month); + Print(day); + + >> year = 2015 + >> month = 3 + >> day = 24 + @endcode +*/ +proto void GetYearMonthDayUTC(out int year, out int month, out int day); + +proto string GetProfileName(); +proto string GetMachineName(); + +//! performance counter. Returns number of CPU ticks between 'prev' and 'now' +proto native int TickCount(int prev); + +/** +\brief Switches memory validation (huge slowdown! Use with care only for certain section of code!) + \param enable \p bool Enable + \return \p void + @code + ??? + @endcode +*/ +proto native void MemoryValidation(bool enable); + +/** +\brief Returns command line argument + \param name of a command line argument + \param val \p string value of the param or empty string if the param hasn't been found + \return True if param is present, False if hasn't been found + @code + string param; + GetCLIParam("world", param); // return a value when program executed with param -world something + @endcode +*/ +proto bool GetCLIParam(string param, out string val); + +/** +\brief Returns if command line argument is present + \param name of a command line argument + \return True if param is present, False if hasn't been found + @code + if (IsCLIParam("verbose")) // Prints "something" when program executed with param -verbose + { + Print("something"); + } + @endcode +*/ +proto native bool IsCLIParam(string param); + +#ifdef ENF_DONE + +//! developer tool - start video grabber +proto native void StartVideo(string name); +//! developer tool - stop video grabber +proto native void StopVideo(); +#endif + + +/** + * \defgroup Keyboard Keyboard input API + * @{ + */ +enum KeyCode +{ + KC_ESCAPE, + KC_1, + KC_2, + KC_3, + KC_4, + KC_5, + KC_6, + KC_7, + KC_8, + KC_9, + KC_0, + KC_MINUS, ///< - on main keyboard + KC_EQUALS, + KC_BACK, ///< backspace + KC_TAB, + KC_Q, + KC_W, + KC_E, + KC_R, + KC_T, + KC_Y, + KC_U, + KC_I, + KC_O, + KC_P, + KC_LBRACKET, + KC_RBRACKET, + KC_RETURN, ///< Enter on main keyboard + KC_LCONTROL, + KC_A, + KC_S, + KC_D, + KC_F, + KC_G, + KC_H, + KC_J, + KC_K, + KC_L, + KC_SEMICOLON, + KC_APOSTROPHE, + KC_GRAVE, ///< accent grave + KC_LSHIFT, + KC_BACKSLASH, + KC_Z, + KC_X, + KC_C, + KC_V, + KC_B, + KC_N, + KC_M, + KC_COMMA, + KC_PERIOD, ///< . on main keyboard + KC_SLASH, ///< / on main keyboard + KC_RSHIFT, + KC_MULTIPLY, ///< * on numeric keypad + KC_LMENU, ///< left Alt + KC_SPACE, + KC_CAPITAL, + KC_F1, + KC_F2, + KC_F3, + KC_F4, + KC_F5, + KC_F6, + KC_F7, + KC_F8, + KC_F9, + KC_F10, + KC_NUMLOCK, + KC_SCROLL, ///< Scroll Lock + KC_NUMPAD7, + KC_NUMPAD8, + KC_NUMPAD9, + KC_SUBTRACT, ///< - on numeric keypad + KC_NUMPAD4, + KC_NUMPAD5, + KC_NUMPAD6, + KC_ADD, ///< + on numeric keypad + KC_NUMPAD1, + KC_NUMPAD2, + KC_NUMPAD3, + KC_NUMPAD0, + KC_DECIMAL, ///< . on numeric keypad + KC_OEM_102, ///< < > | on UK/Germany keyboards + KC_F11, + KC_F12, + KC_NUMPADEQUALS, ///< = on numeric keypad (NEC PC98) + KC_PREVTRACK, ///< Previous Track (DIKC_CIRCUMFLEX on Japanese keyboard) + KC_AT, ///< (NEC PC98) + KC_COLON, ///< (NEC PC98) + KC_UNDERLINE, ///< (NEC PC98) + KC_STOP, ///< (NEC PC98) + KC_AX, ///< (Japan AX) + KC_UNLABELED, ///< (J3100) + KC_NEXTTRACK, ///< Next Track + KC_NUMPADENTER, ///< Enter on numeric keypad + KC_RCONTROL, + KC_MUTE, ///< Mute + KC_CALCULATOR, ///< Calculator + KC_PLAYPAUSE, ///< Play / Pause + KC_MEDIASTOP, ///< Media Stop + KC_VOLUMEDOWN, ///< Volume - + KC_VOLUMEUP, ///< Volume + + KC_WEBHOME, ///< Web home + KC_NUMPADCOMMA, ///< , on numeric keypad (NEC PC98) + KC_DIVIDE, ///< / on numeric keypad + KC_SYSRQ, + KC_RMENU, ///< right Alt + KC_PAUSE, ///< Pause + KC_HOME, ///< Home on arrow keypad + KC_UP, ///< UpArrow on arrow keypad + KC_PRIOR, ///< PgUp on arrow keypad + KC_LEFT, ///< LeftArrow on arrow keypad + KC_RIGHT, ///< RightArrow on arrow keypad + KC_END, ///< End on arrow keypad + KC_DOWN, ///< DownArrow on arrow keypad + KC_NEXT, ///< PgDn on arrow keypad + KC_INSERT, ///< Insert on arrow keypad + KC_DELETE, ///< Delete on arrow keypad + KC_LWIN, ///< Left Windows key + KC_RWIN, ///< Right Windows key + KC_APPS, ///< AppMenu key + KC_POWER, ///< System Power + KC_SLEEP, ///< System Sleep + KC_WAKE, ///< System Wake + KC_MEDIASELECT ///< Media Select +}; + +/*! +Gets key state +\param key Key code +\returns 0 when not pressed, 15. bit set when pressed, 0.-14. bit pressed count +*/ +proto native int KeyState(KeyCode key); + +/*! +Clears the key state. +Call this function if you want to overcome autorepeating in reporting key state. If called, the KeyState returns pressed only after the key is released and pressed again. +*/ +proto native void ClearKey(KeyCode key); +/** @}*/ + +//! returns index of defined key in InputDevice by its name +//proto native int GetDefKey(string name); +//proto native int DefKeyState(int defkey, bool clear); + + +/** + * \defgroup Mouse Mouse API + * @{ + */ + +enum MouseState +{ + LEFT, + RIGHT, + MIDDLE, + X, + Y, + WHEEL +}; +//const int MB_PRESSED_MASK + +/*! +Returns state of mouse button. It's combination of number of release/pressed edges and mask MB_PRESSED_MASK +that is set when button is pressed. +If you want just to check if button is pressed, use this: if(GetMouseState(MouseState.LEFT) & MB_PRESSED_MASK)) Print("left button pressed"); +*/ +proto native int GetMouseState(MouseState index); + +// Gets current mouse position +proto void GetMousePos(out int x, out int y); +// Gets current screen size (resolution) +proto void GetScreenSize(out int x, out int y); + +/** @}*/ + +/** + * \defgroup Gamepad API + * @{ + */ + +enum GamepadButton +{ + BUTTON_NONE, + MENU, + VIEW, + A, + B, + X, + Y, + PAD_UP, + PAD_DOWN, + PAD_LEFT, + PAD_RIGHT, + SHOULDER_LEFT, + SHOULDER_RIGHT, + THUMB_LEFT, + THUMB_RIGHT +}; + +enum GamepadAxis +{ + LEFT_THUMB_HORIZONTAL, + LEFT_THUMB_VERTICAL, + RIGHT_THUMB_HORIZONTAL, + RIGHT_THUMB_VERTICAL, + LEFT_TRIGGER, + RIGHT_TRIGGER, +}; + +//! return if the button is pressed or not +proto native int GetGamepadButton(GamepadButton button); +//! return value in gamepad axis <-1000; 1000> +proto native float GetGamepadAxis(GamepadAxis axis); + +/** @}*/ + +//---------------------------------------------- +/** + * \defgroup File FileIO API + * @{ + */ + +enum FileMode +{ + READ, + WRITE, + APPEND +}; + +typedef int[] ParseHandle; +typedef int[] FileHandle; + +proto native ParseHandle BeginParse(string filename); +proto int ParseLine(ParseHandle tp, int num, string tokens[]); +proto native void EndParse(ParseHandle file); + +//!Check existence of file +proto bool FileExist(string name); + +/** +\brief Opens File + @param name of a file to open, (you can use filesystem prefixes ('$profile','$saves','$mission'). For accessing profile dir use '$profile', e.g. '$profile:myfilename.txt') + @param mode constants FileMode.WRITE, FileMode.READ or FileMode.APPEND flag can be used + \return file handle ID or 0 if fails + \n usage : + @code + FileHandle file = OpenFile("$profile:testiik.txt", FileMode.WRITE); + //FileHandle file = OpenFile("$profile:testiik.txt", FileMode.APPEND); + if (file != 0) + { + FPrintln(file, "line1"); + FPrintln(file, "line2"); + FPrintln(file, "line3"); + CloseFile(file); + } + @endcode +*/ +proto FileHandle OpenFile(string name, FileMode mode); + +/** +Reads raw data from file. +\param param_array Receiving array for the data. Valid types are int[] or string +\param length Length of data +\returns number of read bytes +*/ +proto int ReadFile(FileHandle file, void param_array, int length); + +/** +\brief Close the File + @param file File handle ID of a opened file + \return void + \n usage : + @code + FileHandle file = OpenFile("$profile:testiik.txt", FileMode.WRITE); + if (file != 0) + { + FPrintln(file, "line1"); + FPrintln(file, "line2"); + FPrintln(file, "line3"); + CloseFile(file); + } + @endcode +*/ +proto void CloseFile(FileHandle file); + +/** +\brief Write to file + @param file File handle ID of a opened file + @param var Value to write + \return void + \n usage : + @code + FileHandle file = OpenFile("$profile:testiik.txt", FileMode.WRITE); + if (file != 0) + { + FPrint(file, "A"); + FPrint(file, "B"); + FPrint(file, "C"); + CloseFile(file); + } + @endcode +*/ +proto void FPrint(FileHandle file, void var); + +/** +\brief Write to file and add new line + @param file File handle ID of a opened file + @param var Value to write + \return void + \n usage : + @code + FileHandle file = OpenFile("$profile:testiik.txt", FileMode.WRITE); + if (file != 0) + { + FPrintln(file, "line1"); + FPrintln(file, "line2"); + FPrintln(file, "line3"); + CloseFile(file); + } + @endcode +*/ +proto void FPrintln(FileHandle file, void var); + +/** +\brief Get line from file, every next call of this function returns next line + @param file File handle ID of a opened file + @param var Value to write + \return int Count of chars or -1 if is not any for read (end of file is EMPTY line) + \n usage : + @code + FileHandle file_handle = OpenFile("$profile:testiik.txt", FileMode.READ); + string line_content; + + while ( FGets( file_handle, line_content ) > 0 ) + { + Print(line_content); + } + + CloseFile(file_handle); + @endcode +*/ +proto int FGets(FileHandle file, string var); + +typedef int[] FindFileHandle; + +enum FileAttr +{ + DIRECTORY, ///