repo_id
stringlengths
4
98
size
int64
611
5.02M
file_path
stringlengths
1
276
content
stringlengths
611
5.02M
shard_id
int64
0
109
quality_score
float32
0.5
1
quality_prediction
int8
1
1
quality_confidence
float32
0.5
1
topic_primary
stringclasses
1 value
topic_group
stringclasses
1 value
topic_score
float32
0.05
1
topic_all
stringclasses
96 values
quality2_score
float32
0.5
1
quality2_prediction
int8
1
1
quality2_confidence
float32
0.5
1
AppliedEnergistics/Applied-Energistics-2
2,497
guidebook/example-setups/charger-automation.md
--- navigation: parent: example-setups/example-setups-index.md title: Charger Automation icon: charger --- # Charger Automation Note that since this uses a <ItemLink id="pattern_provider" />, it is meant to integrate into your [autocrafting](../ae2-mechanics/autocrafting.md) setup. If you just want to automate a <ItemLink id="charger" /> standalone, use hoppers and chests and stuff. Automation of a <ItemLink id="charger" /> is fairly simple. A <ItemLink id="pattern_provider" /> pushes the ingredient into the charger, then a [pipe subnet](pipe-subnet.md) or other item pipe pushes the result back into the provider. <GameScene zoom="6" interactive={true}> <ImportStructure src="../assets/assemblies/charger_automation.snbt" /> <BoxAnnotation color="#dddddd" min="1 0 0" max="2 1 1"> (1) Pattern Provider: In its default configuration, with the relevant processing patterns. Also provides the charger with power. ![Charger Pattern](../assets/diagrams/charger_pattern_small.png) </BoxAnnotation> <BoxAnnotation color="#dddddd" min="0 1 0" max="1 1.3 1"> (2) Import Bus: In its default configuration. </BoxAnnotation> <BoxAnnotation color="#dddddd" min="1 1 0" max="2 1.3 1"> (3) Storage Bus: In its default configuration. </BoxAnnotation> <DiamondAnnotation pos="4 0.5 0.5" color="#00ff00"> To Main Network </DiamondAnnotation> <IsometricCamera yaw="195" pitch="30" /> </GameScene> ## Configurations * The <ItemLink id="pattern_provider" /> (1) is in its default configuration, with the relevant <ItemLink id="processing_pattern" />s. It also provides the <ItemLink id="charger" /> with [energy](../ae2-mechanics/energy.md) because it acts like a [cable](../items-blocks-machines/cables.md). ![Charger Pattern](../assets/diagrams/charger_pattern.png) * The <ItemLink id="import_bus" /> (2) is in its default configuration. * The <ItemLink id="storage_bus" /> (3) is in its default configuration. ## How It Works 1. The <ItemLink id="pattern_provider" /> pushes the ingredients into the <ItemLink id="charger" />. 2. The charger does its charging thing. 3. The <ItemLink id="import_bus" /> on the green subnet pulls the result out of the charger and attempts to store it in [network storage](../ae2-mechanics/import-export-storage.md). 4. The only storage on the green subnet is the <ItemLink id="storage_bus" />, which stores the resulting items in the pattern provider, returning them to the main network.
0
0.980155
1
0.980155
game-dev
MEDIA
0.813103
game-dev
0.620846
1
0.620846
DescentDevelopers/Descent3
7,609
netgames/dmfc/encryption.cpp
/* * Descent 3 * Copyright (C) 2024 Parallax Software * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. --- HISTORICAL COMMENTS FOLLOW --- * $Logfile: /DescentIII/Main/dmfc/encryption.cpp $ * $Revision: 1.1.1.1 $ * $Date: 2003/08/26 03:57:21 $ * $Author: kevinb $ * * header file for ICE encryption class * * $Log: encryption.cpp,v $ * Revision 1.1.1.1 2003/08/26 03:57:21 kevinb * initial 1.5 import * * * 2 7/08/99 2:37a Jeff * created encryption class based off of ICE encryption * * $NoKeywords: $ */ #include "encryption.h" class IceSubkey { public: uint32_t val[3]; }; // the S-boxes static uint32_t ice_sbox[4][1024]; static int ice_sboxes_initialised = 0; // modulo values for the S-boxes static const int ice_smod[4][4] = { {333, 313, 505, 369}, {379, 375, 319, 391}, {361, 445, 451, 397}, {397, 425, 395, 505}}; // XOR values for the S-boxes static const int ice_sxor[4][4] = { {0x83, 0x85, 0x9b, 0xcd}, {0xcc, 0xa7, 0xad, 0x41}, {0x4b, 0x2e, 0xd4, 0x33}, {0xea, 0xcb, 0x2e, 0x04}}; // Permutation values for the P-box static const uint32_t ice_pbox[32] = { 0x00000001, 0x00000080, 0x00000400, 0x00002000, 0x00080000, 0x00200000, 0x01000000, 0x40000000, 0x00000008, 0x00000020, 0x00000100, 0x00004000, 0x00010000, 0x00800000, 0x04000000, 0x20000000, 0x00000004, 0x00000010, 0x00000200, 0x00008000, 0x00020000, 0x00400000, 0x08000000, 0x10000000, 0x00000002, 0x00000040, 0x00000800, 0x00001000, 0x00040000, 0x00100000, 0x02000000, 0x80000000}; // key rotation schedule static const int ice_keyrot[16] = {0, 1, 2, 3, 2, 1, 3, 0, 1, 3, 2, 0, 3, 1, 0, 2}; // // 8-bit Galois Field multiplication of a by b, modulo m. // Just like arithmetic multiplication, except that additions and // subtractions are replaced by XOR. // static uint32_t gf_mult(uint32_t a, uint32_t b, uint32_t m) { uint32_t res = 0; while (b) { if (b & 1) res ^= a; a <<= 1; b >>= 1; if (a >= 256) a ^= m; } return (res); } // // Galois Field exponentiation. // Raise the base to the power of 7, modulo m. // static uint32_t gf_exp7(uint32_t b, uint32_t m) { uint32_t x; if (b == 0) return 0; x = gf_mult(b, b, m); x = gf_mult(b, x, m); x = gf_mult(x, x, m); return (gf_mult(b, x, m)); } // // Carry out the ICE 32-bit P-box permutation. // static uint32_t ice_perm32(uint32_t x) { uint32_t res = 0; const uint32_t *pbox = ice_pbox; while (x) { if (x & 1) res |= *pbox; pbox++; x >>= 1; } return (res); } // // Initialise the ICE S-boxes. // This only has to be done once. // static void ice_sboxes_init(void) { int i; for (i = 0; i < 1024; i++) { int col = (i >> 1) & 0xff; int row = (i & 0x1) | ((i & 0x200) >> 8); uint32_t x; x = gf_exp7(col ^ ice_sxor[0][row], ice_smod[0][row]) << 24; ice_sbox[0][i] = ice_perm32(x); x = gf_exp7(col ^ ice_sxor[1][row], ice_smod[1][row]) << 16; ice_sbox[1][i] = ice_perm32(x); x = gf_exp7(col ^ ice_sxor[2][row], ice_smod[2][row]) << 8; ice_sbox[2][i] = ice_perm32(x); x = gf_exp7(col ^ ice_sxor[3][row], ice_smod[3][row]); ice_sbox[3][i] = ice_perm32(x); } } // // Create a new ICE key. // IceKey::IceKey(int n) { if (!ice_sboxes_initialised) { ice_sboxes_init(); ice_sboxes_initialised = 1; } if (n < 1) { _size = 1; _rounds = 8; } else { _size = n; _rounds = n * 16; } _keysched = new IceSubkey[_rounds]; } // // Destroy an ICE key. // IceKey::~IceKey() { int i, j; for (i = 0; i < _rounds; i++) { for (j = 0; j < 3; j++) { _keysched[i].val[j] = 0; } } _rounds = _size = 0; delete[] _keysched; } // // The single round ICE f function. // static uint32_t ice_f(uint32_t p, const IceSubkey *sk) { uint32_t tl, tr; /* Expanded 40-bit values */ uint32_t al, ar; /* Salted expanded 40-bit values */ // Left half expansion tl = ((p >> 16) & 0x3ff) | (((p >> 14) | (p << 18)) & 0xffc00); // Right half expansion tr = (p & 0x3ff) | ((p << 2) & 0xffc00); // Perform the salt permutation al = sk->val[2] & (tl ^ tr); ar = al ^ tr; al ^= tl; al ^= sk->val[0]; // XOR with the subkey ar ^= sk->val[1]; // S-box lookup and permutation return (ice_sbox[0][al >> 10] | ice_sbox[1][al & 0x3ff] | ice_sbox[2][ar >> 10] | ice_sbox[3][ar & 0x3ff]); } // // Encrypt a block of 8 bytes of data with the given ICE key. // void IceKey::encrypt(const uint8_t *ptext, uint8_t *ctext) const { int i; uint32_t l, r; l = (((uint32_t)ptext[0]) << 24) | (((uint32_t)ptext[1]) << 16) | (((uint32_t)ptext[2]) << 8) | ptext[3]; r = (((uint32_t)ptext[4]) << 24) | (((uint32_t)ptext[5]) << 16) | (((uint32_t)ptext[6]) << 8) | ptext[7]; for (i = 0; i < _rounds; i += 2) { l ^= ice_f(r, &_keysched[i]); r ^= ice_f(l, &_keysched[i + 1]); } for (i = 0; i < 4; i++) { ctext[3 - i] = (uint8_t)r & 0xff; ctext[7 - i] = (uint8_t)l & 0xff; r >>= 8; l >>= 8; } } // // Decrypt a block of 8 bytes of data with the given ICE key. // void IceKey::decrypt(const uint8_t *ctext, uint8_t *ptext) const { int i; uint32_t l, r; l = (((uint32_t)ctext[0]) << 24) | (((uint32_t)ctext[1]) << 16) | (((uint32_t)ctext[2]) << 8) | ctext[3]; r = (((uint32_t)ctext[4]) << 24) | (((uint32_t)ctext[5]) << 16) | (((uint32_t)ctext[6]) << 8) | ctext[7]; for (i = _rounds - 1; i > 0; i -= 2) { l ^= ice_f(r, &_keysched[i]); r ^= ice_f(l, &_keysched[i - 1]); } for (i = 0; i < 4; i++) { ptext[3 - i] = (uint8_t)r & 0xff; ptext[7 - i] = (uint8_t)l & 0xff; r >>= 8; l >>= 8; } } // // Set 8 rounds [n, n+7] of the key schedule of an ICE key. // void IceKey::scheduleBuild(uint16_t *kb, int n, const int *keyrot) { int i; for (i = 0; i < 8; i++) { int j; int kr = keyrot[i]; IceSubkey *isk = &_keysched[n + i]; for (j = 0; j < 3; j++) isk->val[j] = 0; for (j = 0; j < 15; j++) { int k; uint32_t *curr_sk = &isk->val[j % 3]; for (k = 0; k < 4; k++) { uint16_t *curr_kb = &kb[(kr + k) & 3]; int bit = *curr_kb & 1; *curr_sk = (*curr_sk << 1) | bit; *curr_kb = (*curr_kb >> 1) | ((bit ^ 1) << 15); } } } } // // Set the key schedule of an ICE key. // void IceKey::set(const uint8_t *key) { int i; if (_rounds == 8) { uint16_t kb[4]; for (i = 0; i < 4; i++) { kb[3 - i] = (key[i * 2] << 8) | key[i * 2 + 1]; } scheduleBuild(kb, 0, ice_keyrot); return; } for (i = 0; i < _size; i++) { int j; uint16_t kb[4]; for (j = 0; j < 4; j++) { kb[3 - j] = (key[i * 8 + j * 2] << 8) | key[i * 8 + j * 2 + 1]; scheduleBuild(kb, i * 8, ice_keyrot); scheduleBuild(kb, _rounds - 8 - i * 8, &ice_keyrot[8]); } } } // // Return the key size, in bytes. // int IceKey::keySize(void) const { return (_size * 8); } // // Return the block size, in bytes. // int IceKey::blockSize(void) const { return 8; }
0
0.956833
1
0.956833
game-dev
MEDIA
0.163887
game-dev
0.961936
1
0.961936
VilleKrumlinde/zgameeditor
104,528
ZExpressions.pas
{Copyright (c) 2020 Ville Krumlinde Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.} unit ZExpressions; { Expressions. Use global proc RunCode(...) to execute code. Runtime Virtual Machine } {$include zzdc_globalopt.inc} interface uses ZClasses; type TExpBase = class; //Expression execution context PExecutionEnvironment = ^TExecutionEnvironment; TExecutionEnvironment = record const ZcStackSize=16384; type TStackElement = NativeUInt; PStackElement = ^TStackElement; PExpBase = ^TExpBase; private gCurrentPc : PExpBase; gCurrentBP : integer; var ZcStack : array[0..ZcStackSize div SizeOf(TStackElement)] of TStackElement; ZcStackPtr : PStackElement; strict private {$ifdef CALLSTACK} procedure LogCallstack; {$endif} private function StackGetDepth : integer; inline; procedure StackPopTo(var X); {$IFDEF RELEASE}inline;{$ENDIF} procedure StackPopToPointer(var X); {$IFDEF RELEASE}inline;{$ENDIF} function StackPopFloat : single; {$ifndef minimal} procedure ScriptError(const S : string); {$endif} {$ifdef CALLSTACK} procedure CheckNilDeref(P : pointer); {$endif} {$if defined(cpux64) or defined(cpuaarch64)} function StackPopAndGetPtr(const Count : integer) : PStackElement; inline; {$endif} public function StackGetPtrToItem(const Index : integer) : PStackElement; inline; procedure StackPush(const X); {$IFDEF RELEASE}inline;{$ENDIF} procedure StackPushPointer(const X); {$IFDEF RELEASE}inline;{$ENDIF} procedure Init; end; //Klass med en expression-prop TZExpression = class(TCommand) protected procedure DefineProperties(List: TZPropertyList); override; public Expression : TZExpressionPropValue; procedure Execute; override; end; //User-defined functions TZLibrary = class(TZComponent) strict private Lock : pointer; HasExecutedInitializer : boolean; procedure InitGlobalArea; procedure RemoveManagedTargets; private procedure AquireLock; procedure ReleaseLock; protected procedure DefineProperties(List: TZPropertyList); override; procedure InitAfterPropsAreSet; override; public UseThreadLock : boolean; Source : TZExpressionPropValue; HasInitializer : boolean; GlobalArea : pointer; //Storage for non-managed global variables GlobalAreaSize : integer; ManagedVariables : TZBinaryPropValue; procedure Update; override; destructor Destroy; override; {$ifndef minimal} procedure DesignerReset; override; procedure AddGlobalVar(const Typ : TZcDataType); {$endif} end; PExternalFunctionEntry = ^TExternalFunctionEntry; TExternalFunctionEntry = record Name: PAnsiChar; NameLength: Integer; Proc: Pointer; Trampoline: Pointer; end; //Import of external library (dll) TZExternalLibrary = class(TZComponent) strict private Entries: TZArrayList; ModuleHandle : NativeUInt; procedure ClearEntries; private function GetEntry(P : PAnsiChar) : PExternalFunctionEntry; protected procedure DefineProperties(List: TZPropertyList); override; public ModuleName : TPropString; CallingConvention : (ccStdCall,ccCdecl); Source : TZExpressionPropValue; BeforeInitExp : TZExpressionPropValue; {$ifndef minimal} DefinitionsFile : TPropString; function GetDisplayName: ansistring; override; procedure DesignerReset; override; {$endif} constructor Create(OwnerList: TZComponentList); override; destructor Destroy; override; end; TDefineVariableBase = class(TZComponent) protected procedure DefineProperties(List: TZPropertyList); override; public _Type : TZcDataType; {$ifndef minimal} function GetDisplayName: ansistring; override; {$endif} end; //Define a global variable that can be used in expressions TDefineVariable = class(TDefineVariableBase) strict private procedure InitManaged; protected procedure DefineProperties(List: TZPropertyList); override; procedure InitAfterPropsAreSet; override; public Value : single; IntValue : integer; ModelValue : TZComponent; ByteValue : byte; StringValue : TPropString; PointerValue : pointer; {$ifndef minimal} procedure DesignerReset; override; {$endif} end; //Define a global constant that can be used in expressions //Value is copied into code TDefineConstant = class(TDefineVariableBase) protected procedure DefineProperties(List: TZPropertyList); override; public Value : single; IntValue : integer; StringValue : TPropString; ByteValue : byte; {$ifndef minimal}function GetDisplayName: ansistring; override;{$endif} end; //Holds a stringconstant used in expressions //It is automatically inserted in App.ConstantPool TExpStringConstant = class(TZComponent) protected procedure DefineProperties(List: TZPropertyList); override; public Value : TPropString; end; TArrayDimensions = (dadOne,dadTwo,dadThree); TDefineArray = class(TDefineVariableBase) strict private Data : PFloatArray; Limit : integer; AllocItemCount : integer; AllocType : TZcDataTypeKind; AllocPtr : PPointer; IsExternal : boolean; procedure CleanUpManagedValues(TheType : TZcDataTypeKind; Count : integer; P : PPointer); procedure AllocData; private function PopAndGetElement(Env : PExecutionEnvironment) : PFloat; protected procedure DefineProperties(List: TZPropertyList); override; public Dimensions : TArrayDimensions; SizeDim1,SizeDim2,SizeDim3 : integer; Persistent : boolean; Values : TZBinaryPropValue; destructor Destroy; override; function GetData : PFloat; function CalcLimit : integer; function GetElementSize : integer; function SetExternalData(P: pointer) : PPointer; end; //Virtual machine instruction baseclass TExpBase = class(TZComponent) protected procedure Execute(Env : PExecutionEnvironment); virtual; abstract; {$ifndef minimal}public function ExpAsText : string; virtual;{$endif} end; TExpConstantFloat = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Constant : single; {$ifndef minimal} function GetDisplayName: ansistring; override; {$endif} end; TExpConstantInt = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Constant : integer; {$ifndef minimal} function GetDisplayName: ansistring; override; {$endif} end; TExpOpBinaryKind = (vbkPlus,vbkMinus,vbkMul,vbkDiv,vbkBinaryOr,vbkBinaryAnd, vbkBinaryShiftLeft,vbkBinaryShiftRight,vbkBinaryXor,vbkMod); TExpOpBinaryBase = class(TExpBase) protected procedure DefineProperties(List: TZPropertyList); override; public Kind : TExpOpBinaryKind; {$ifndef minimal} constructor Create(OwnerList: TZComponentList; Kind : TExpOpBinaryKind); reintroduce; function ExpAsText : string; override; {$endif} end; TExpOpBinaryFloat = class(TExpOpBinaryBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; TExpOpBinaryInt = class(TExpOpBinaryBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; TExpOpJumpKind = (jsJumpAlways,jsJumpLT,jsJumpGT,jsJumpLE,jsJumpGE,jsJumpNE,jsJumpEQ); TExpJump = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Kind : TExpOpJumpKind; Destination : integer; _Type : (jutFloat,jutInt,jutString,jutPointer); {$ifndef minimal} function ExpAsText : string; override; {$endif} end; TExpFuncCallKind = (fcSin,fcSqrt,fcCos,fcAbs,fcRnd,fcFrac,fcExp, fcTan,fcCeil,fcFloor,fcAcos,fcAsin,fcLog2,fcRound, fcRandom,fcAtan2,fcNoise2,fcNoise3,fcClamp,fcPow,fcCenterMouse, fcSetRandomSeed,fcQuit, fcJoyGetAxis,fcJoyGetButton,fcJoyGetPOV,fcSystemTime, fcStringLength,fcStringIndexOf,fcStrToInt,fcOrd, fcIntToStr,fcSubStr,fcChr,fcCreateModel,fcTrace, fcTouchGetCount,fcTouchGetX,fcTouchGetY,fcTouchGetID, fcGetBinaryProp,fcSetBinaryProp,fcGetModels,fcSleep,fcStartThread, //Mat4 fcMatMultiply,fcMatTransformPoint,fcGetMatrix,fcSetMatrix, fcVec2,fcVec3,fcVec4 {$ifndef minimal} ,fcGenLValue, //IDE fcFindComponent,fcCreateComponent,fcSetNumericProperty,fcSetStringProperty, fcSetObjectProperty,fcSaveComponentToTextFile, fcGetStringProperty {$endif} ); TExpFuncCallBase = class(TExpBase) protected procedure DefineProperties(List: TZPropertyList); override; public Kind : TExpFuncCallKind; {$ifndef minimal} function ExpAsText : string; override; {$endif} end; //Built-in function call TExpFuncCall = class(TExpFuncCallBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; //Built-in functions that return pointer TExpPointerFuncCall = class(TExpFuncCallBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; //Matrix functions TExpMat4FuncCall = class(TExpFuncCallBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; {$ifndef minimal} //IDE/Visualizer "meta" functions TExpIDEFuncCall = class(TExpFuncCallBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; {$endif} //Push ptr to element in array on stack, used with assign TExpArrayGetElement = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; //Setup local stack frame TExpStackFrame = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Size : integer; end; //Load/store local value TExpAccessLocal = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Kind : (loLoad,loStore,loGetAddress); Index : integer; {$ifndef minimal} function ExpAsText : string; override; {$endif} end; //Load/store global (non-managed) value TExpAccessGlobal = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Kind : (glLoad,glStore,glGetAddress); Offset : integer; Lib : TZLibrary; {$ifndef minimal} function ExpAsText : string; override; {$endif} end; //Return from function TExpReturn = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Lib : TZLibrary; HasFrame : boolean; HasReturnValue : boolean; Arguments : integer; {$ifdef CALLSTACK} FunctionName : string; {$endif} end; TExpMiscKind = (emPop,emDup,emLoadCurrentModel,emPtrDeref4,emPtrDeref1, emPtrDerefPointer, emNotifyPropChanged, emLoadNull, emNop, emBinaryNot, emNot,emGetUserClass,emGetGlobalDataProp); TExpMisc = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Kind : TExpMiscKind; {$ifndef minimal} constructor Create(OwnerList: TZComponentList; Kind : TExpMiscKind); reintroduce; public function ExpAsText : string; override; {$endif} end; TExpUserFuncCall = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Lib : TZLibrary; Index : integer; {$ifndef minimal} Ref : TObject; //points to TZcOpFunctionUserDefined, used in RetroCoding {$endif} end; TExpExternalFuncCall = class(TExpBase) strict private Entry: PExternalFunctionEntry; protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Lib : TZExternalLibrary; FuncName : TPropString; ArgCount : integer; ReturnType : TZcDataType; ArgTypes : TPropString; {$ifndef minimal} procedure DesignerReset; override; {$endif} end; TExpConvertKind = (eckFloatToInt,eckIntToFloat,eckArrayToXptr,eckBinaryToXptr, eckPropToVec3,eckPropToVec4); TExpConvert = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Kind : TExpConvertKind; end; //Assign ptr to 4-byte value, both on stack TExpAssign4 = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; //Assign ptr to 1-byte value, both on stack TExpAssign1 = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; //Assign ptr to Pointersize value, both on stack TExpAssignPointer = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; //Join two strings TExpStringConCat = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; TExpLoadComponent = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Component : TZComponent; end; TExpLoadPropOffset = class(TExpBase) strict private IsInit : boolean; Offset : integer; protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public PropId : integer; end; TExpLoadModelDefined = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public DefinedIndex : integer; {$ifndef minimal} DefinedName : TPropString; ComponentRef : TZComponent; {$endif} end; TExpAddToPointer = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; end; TExpInvokeComponent = class(TExpBase) strict private InvokeC : TZComponent; protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public InvokedItemList : TZComponentList; InvokeClassId : integer; InvokeArgCount : integer; IsValue : boolean; end; TExpInitArray = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Dimensions : TArrayDimensions; _Type : TZcDataTypeKind; Size1,Size2,Size3 : integer; end; TExpGetRawMemElement = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public _Type : TZcDataTypeKind; end; TExpArrayUtil = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public Kind : (auArrayToRawMem, auRawMemToArray, auArrayToArray); _Type : TZcDataTypeKind; end; TExpSwitchTable = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public LowBound,HighBound : integer; DefaultOrExit : integer; Jumps : TZBinaryPropValue; end; TCodeReturnValue = record case boolean of True : (PointerValue : pointer); False : (SingleValue : single); end; TUserClass = class(TZComponent) protected procedure DefineProperties(List: TZPropertyList); override; public SizeInBytes : integer; ManagedFields : TZBinaryPropValue; BaseClass : TUserClass; Vmt : TZBinaryPropValue; DefinedInLib : TZLibrary; InitializerIndex : integer; end; TUserClassInstance = class strict private ManagedCount : integer; ManagedCleanup : PPointer; public InstanceData : pointer; TheClass : TUserClass; constructor Create(TheClass : TUserClass); destructor Destroy; override; end; TExpNewClassInstance = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public TheClass : TUserClass; end; TExpVirtualFuncCall = class(TExpBase) protected procedure Execute(Env : PExecutionEnvironment); override; procedure DefineProperties(List: TZPropertyList); override; public VmtIndex : integer; end; //Run a compiled expression //Uses global vars for state. function RunCode(Code : TZComponentList; Env : PExecutionEnvironment=nil) : TCodeReturnValue; function ExpGetValue(Code : TZComponentList) : single; function ExpGetPointer(Code : TZComponentList) : PFloat; implementation uses ZMath, ZPlatform, ZApplication, ZLog, Meshes, AudioComponents, AudioPlayer {$ifndef MSWINDOWS} {$ifdef fpc}, BaseUnix{$endif} {$endif} {$if (not defined(minimal))}, SysUtils, Math, TypInfo, Classes{$endif} {$if defined(cpux64) and defined(mswindows)}, Windows{$endif} ; {$POINTERMATH ON} function ExpGetValue(Code : TZComponentList) : single; begin Result := RunCode(Code).SingleValue; end; function ExpGetPointer(Code : TZComponentList) : ZClasses.PFloat; begin Result := RunCode(Code).PointerValue; end; procedure TExecutionEnvironment.Init; begin ZcStackPtr := @ZcStack; gCurrentBP := 0; end; {$if defined(cpux64) or defined(cpuaarch64)} function TExecutionEnvironment.StackPopAndGetPtr(const Count: integer): PStackElement; begin Dec(ZcStackPtr,Count); Result := ZcStackPtr; end; {$endif} function TExecutionEnvironment.StackGetDepth : integer; begin //Returns the number of stack elements from start of stack Result := (ZcStackPtr - PStackElement(@ZcStack)); end; //Push 32-bit value procedure TExecutionEnvironment.StackPush(const X); begin {$ifdef debug} if StackGetDepth>=High(ZcStack) then ScriptError('Zc Stack Overflow (infinite recursion?)'); {$endif} PInteger(ZcStackPtr)^ := PInteger(@X)^; Inc(ZcStackPtr); end; //Push 32 or 64-bit value depending on architechture procedure TExecutionEnvironment.StackPushPointer(const X); begin {$ifdef debug} if StackGetDepth>=High(ZcStack) then ScriptError('Zc Stack Overflow (infinite recursion?)'); {$endif} ZcStackPtr^ := TStackElement( PPointer(@X)^ ); Inc(ZcStackPtr); end; //Pop 32-bit value procedure TExecutionEnvironment.StackPopTo(var X); begin {$ifdef debug} if StackGetDepth=0 then ScriptError('Zc Stack Underflow'); {$endif} Dec(ZcStackPtr); PInteger(@X)^ := PInteger(ZcStackPtr)^; end; //Pop 32 or 64-bit value depending on architechture procedure TExecutionEnvironment.StackPopToPointer(var X); begin {$ifdef debug} if StackGetDepth=0 then ScriptError('Zc Stack Underflow'); {$endif} Dec(ZcStackPtr); PPointer(@X)^ := pointer(ZcStackPtr^); end; function TExecutionEnvironment.StackPopFloat : single; begin StackPopTo(Result); end; function TExecutionEnvironment.StackGetPtrToItem(const Index : integer) : PStackElement; begin Result := @ZcStack; Inc(Result,Index); end; {$ifdef CALLSTACK} procedure TExecutionEnvironment.LogCallstack; var Log : TLog; procedure DoOne(P : PExpBase); begin while (P<>nil) and (P^<>nil) do begin if (P^ is TExpReturn) then begin Log.Error(TExpReturn(P^).FunctionName); TExpReturn(P^).Execute(@Self); P := Self.gCurrentPc; Continue; end; Inc(P); end; end; begin Log := ZLog.GetLog('Zc'); Log.Error('Callstack:'); DoOne(Self.gCurrentPc); end; procedure TExecutionEnvironment.CheckNilDeref(P : pointer); begin if NativeUInt(P)<=1024 then Self.ScriptError('Null pointer referenced in expression'); end; {$endif} {$ifndef minimal} procedure TExecutionEnvironment.ScriptError(const S : string); begin {$ifdef CALLSTACK} LogCallstack; {$endif} ZHalt(S); end; {$endif} function RunCode(Code : TZComponentList; Env : PExecutionEnvironment=nil) : TCodeReturnValue; {$IFDEF ZDESIGNER} {$DEFINE GUARD_LIMIT} {$ENDIF} const NilP : pointer = nil; var {$ifdef GUARD_LIMIT} GuardLimit,GuardAllocLimit : integer; {$endif} LocalEnv : TExecutionEnvironment; begin //Pc can be modified in jump-code if Code.Count=0 then Exit; if Env=nil then begin Env := @LocalEnv; Env.Init; end; Env.gCurrentPc := Code.GetPtrToItem(0); Env.StackPushPointer(NilP); //Push return adress nil {$ifdef GUARD_LIMIT} GuardLimit := Round(1E8); GuardAllocLimit := ManagedHeap_GetAllocCount + 1000000*10; {$endif} while True do begin TExpBase(Env.gCurrentPc^).Execute(Env); if Env.gCurrentPc=nil then Break; Inc(Env.gCurrentPc); {$ifdef GUARD_LIMIT} Dec(GuardLimit); if (GuardLimit=0) and (TThread.CurrentThread.ThreadID=MainThreadID) then Env.ScriptError('Infinite loop?'); if ManagedHeap_GetAllocCount>GuardAllocLimit then Env.ScriptError('Ten million strings allocated. Infinite loop?'); {$endif} end; if Env.StackGetDepth=1 then Env.StackPopToPointer(Result.PointerValue); {$ifdef ZDESIGNER} if (Env=@LocalEnv) and (Env.StackGetDepth>0) then ZLog.GetLog('Zc').Warning('Stack not empty on script completion'); {$endif} end; function CreateManagedValue(const Typ : TZcDataTypeKind) : pointer; var A : TDefineArray; begin Result := nil; case Typ of zctMat4: begin A := TDefineArray.Create(nil); A.Dimensions := dadTwo; A.SizeDim1 := 4; A.SizeDim2 := 4; A._Type.Kind := zctFloat; Result := A; end; zctVec2, zctVec3, zctVec4 : begin A := TDefineArray.Create(nil); A.Dimensions := dadOne; A.SizeDim1 := 2 + Ord(Typ)-Ord(zctVec2); A._Type.Kind := zctFloat; Result := A; end; end; ManagedHeap_AddValueObject(Result); end; { TZExpression } procedure TZExpression.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Expression',{$ENDIF}(@Expression), zptExpression); end; procedure TZExpression.Execute; begin ZExpressions.RunCode(Expression.Code); end; { TExpConstantFloat } procedure TExpConstantFloat.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Constant',{$ENDIF}(@Constant), zptFloat); end; procedure TExpConstantFloat.Execute(Env : PExecutionEnvironment); begin Env.StackPush( Constant ); end; {$ifndef minimal} function TExpConstantFloat.GetDisplayName: AnsiString; begin Result := inherited GetDisplayName + ' ' + AnsiString(FloatToStr(Constant)); end; {$endif} { TExpConstantInt } procedure TExpConstantInt.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Constant',{$ENDIF}(@Constant), zptInteger); end; procedure TExpConstantInt.Execute(Env : PExecutionEnvironment); begin Env.StackPush( Constant ); end; {$ifndef minimal} function TExpConstantInt.GetDisplayName: AnsiString; begin Result := inherited GetDisplayName + ' ' + AnsiString(IntToStr(Constant)); end; {$endif} { TExpOpBinary } procedure TExpOpBinaryBase.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}(@Kind), zptByte); end; {$ifndef minimal} constructor TExpOpBinaryBase.Create(OwnerList: TZComponentList; Kind : TExpOpBinaryKind); begin inherited Create(OwnerList); Self.Kind := Kind; end; {$endif} {$ifndef minimal} function TExpOpBinaryBase.ExpAsText : string; begin Result := Copy(GetEnumName(TypeInfo(TExpOpBinaryKind),Ord(Self.Kind)),4,100) + ' (' + Copy(ComponentManager.GetInfo(Self).ZClassName,4,255) + ')'; end; {$endif} {$ifdef minimal} {$WARNINGS OFF} {$endif} procedure TExpOpBinaryFloat.Execute(Env : PExecutionEnvironment); var A1,A2,V : single; begin Env.StackPopTo(A1); Env.StackPopTo(A2); case Kind of vbkPlus : V := A1 + A2; vbkMinus : V := A2 - A1; vbkMul : V := A2 * A1; vbkDiv : V := A2 / A1; {$ifndef minimal}else Env.ScriptError('Invalid binary op'); {$endif} end; Env.StackPush(V); end; {$ifdef minimal} {$WARNINGS ON} {$endif} {$ifdef minimal} {$WARNINGS OFF} {$endif} procedure TExpOpBinaryInt.Execute(Env : PExecutionEnvironment); var A1,A2,V : integer; begin Env.StackPopTo(A1); Env.StackPopTo(A2); case Kind of vbkPlus : V := A1 + A2; vbkMinus : V := A2 - A1; vbkMul : V := A2 * A1; vbkDiv : V := A2 div A1; vbkBinaryOr : V := A2 or A1; vbkBinaryAnd : V := A2 and A1; vbkBinaryXor : V := A2 xor A1; vbkBinaryShiftLeft : V := A2 shl A1; vbkBinaryShiftRight : V := A2 shr A1; vbkMod : if A1<>0 then V := A2 mod A1 else V := 0; //avoid runtime div by zero error {$ifndef minimal}else Env.ScriptError('Invalid binary op'); {$endif} end; Env.StackPush(V); end; {$ifdef minimal} {$WARNINGS ON} {$endif} { TExpJump } procedure TExpJump.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}(@Kind), zptByte); List.AddProperty({$IFNDEF MINIMAL}'Destination',{$ENDIF}(@Destination), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'Type',{$ENDIF}(@_Type), zptByte); end; procedure TExpJump.Execute(Env : PExecutionEnvironment); var L,R : single; Li,Ri : integer; Lp,Rp : pointer; Jump : boolean; begin Jump := True; case Kind of jsJumpAlways : ; else begin case _Type of jutFloat: begin Env.StackPopTo(R); Env.StackPopTo(L); case Kind of jsJumpLT : Jump := L<R; jsJumpGT : Jump := L>R; jsJumpLE : Jump := L<=R; jsJumpGE : Jump := L>=R; jsJumpNE : Jump := L<>R; jsJumpEQ : Jump := L=R; {$ifndef minimal}else Env.ScriptError('Invalid jump op');{$endif} end; end; jutInt: begin Env.StackPopTo(Ri); Env.StackPopTo(Li); case Kind of jsJumpLT : Jump := Li<Ri; jsJumpGT : Jump := Li>Ri; jsJumpLE : Jump := Li<=Ri; jsJumpGE : Jump := Li>=Ri; jsJumpNE : Jump := Li<>Ri; jsJumpEQ : Jump := Li=Ri; {$ifndef minimal}else Env.ScriptError('Invalid jump op');{$endif} end; end; jutString: begin Env.StackPopToPointer(Rp); Env.StackPopToPointer(Lp); Jump := ZStrCompare(PAnsiChar(Lp),PAnsiChar(Rp)); if Kind=jsJumpNE then Jump := not Jump; end; jutPointer: begin Env.StackPopToPointer(Rp); Env.StackPopToPointer(Lp); Jump := Rp=Lp; if Kind=jsJumpNE then Jump := not Jump; end; end; end; end; if Jump then Inc(Env.gCurrentPc,Destination); end; {$ifndef minimal} function TExpJump.ExpAsText : string; begin Result := inherited ExpAsText + ' ' + Copy(GetEnumName(TypeInfo(TExpOpJumpKind),Ord(Kind)),7,100); end; {$endif} { TDefineVariable } procedure TDefineVariable.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Value',{$ENDIF}(@Value), zptFloat); //Variabler är ingen ide att spara, de måste sättas ifrån kod List.GetLast.NeverPersist := True; List.AddProperty({$IFNDEF MINIMAL}'IntValue',{$ENDIF}(@IntValue), zptInteger); List.GetLast.NeverPersist := True; List.AddProperty({$IFNDEF MINIMAL}'StringValue',{$ENDIF}(@StringValue), zptString); List.GetLast.NeverPersist := True; List.GetLast.IsManagedTarget := True; List.AddProperty({$IFNDEF MINIMAL}'ModelValue',{$ENDIF}(@ModelValue), zptComponentRef); List.GetLast.NeverPersist := True; {$ifndef minimal}List.GetLast.SetChildClasses([TModel]);{$endif} List.AddProperty({$IFNDEF MINIMAL}'ByteValue',{$ENDIF}(@ByteValue), zptByte); List.GetLast.NeverPersist := True; List.AddProperty({$IFNDEF MINIMAL}'PointerValue',{$ENDIF}(@PointerValue), zptPointer); List.GetLast.NeverPersist := True; List.GetLast.IsManagedTarget := True; {$ifdef zgeviz} //In zgeviz whole apps are cloned and then copy pointervalue is not correct behavior List.GetLast.DontClone := True; {$endif} {$ifndef minimal}List.GetLast.HideInGui := True;{$endif} end; {$ifndef minimal} procedure TDefineVariable.DesignerReset; begin inherited; InitManaged; end; {$endif} procedure TDefineVariable.InitManaged; begin if (Self._Type.Kind in [zctMat4,zctVec2,zctVec3,zctVec4]) and (Self.PointerValue=nil) then //Create default empty value Self.PointerValue := CreateManagedValue(Self._Type.Kind); end; procedure TDefineVariable.InitAfterPropsAreSet; begin inherited; InitManaged; end; { TExpFuncCallBase } procedure TExpFuncCallBase.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}(@Kind), zptByte); end; {$ifndef minimal} function TExpFuncCallBase.ExpAsText : string; begin Result := 'Call ' + Copy(GetEnumName(TypeInfo(TExpFuncCallKind),Ord(Kind)),3,100); end; {$endif} { TExpFuncCall } {$ifdef minimal} {$WARNINGS OFF} {$endif} procedure TExpFuncCall.Execute(Env : PExecutionEnvironment); var V,A1,A2,A3 : single; I1,I2 : integer; P1,P2 : pointer; Bp : PZBinaryPropValue; A : TDefineArray; L : TZArrayList; HasReturnValue : boolean; I,J : integer; begin HasReturnValue := True; case Kind of fcSin : V := Sin(Env.StackPopFloat); fcSqrt : V := Sqrt(Env.StackPopFloat); fcCos : V := Cos(Env.StackPopFloat); fcAbs : V := Abs(Env.StackPopFloat); fcRnd : V := System.Random; fcFrac : V := Frac(Env.StackPopFloat); fcExp : V := Exp(Env.StackPopFloat); fcTan : V := Tan(Env.StackPopFloat); fcCeil : V := Ceil(Env.StackPopFloat); fcFloor : V := Floor(Env.StackPopFloat); fcAcos : V := ArcCos(Env.StackPopFloat); fcAsin : V := ArcSin(Env.StackPopFloat); fcLog2 : V := Log2(Env.StackPopFloat); fcRound : PInteger(@V)^ := Round(Env.StackPopFloat); fcRandom : begin Env.StackPopTo(A2); //Variance Env.StackPopTo(A1); //Base V := A1 + ((2*System.Random-1.0) * A2); end; fcAtan2 : begin Env.StackPopTo(A2); Env.StackPopTo(A1); V := ArcTan2(A1,A2); end; fcNoise2 : begin Env.StackPopTo(A2); Env.StackPopTo(A1); V := PerlinNoise2(A1,A2); end; fcNoise3 : begin Env.StackPopTo(A3); Env.StackPopTo(A2); Env.StackPopTo(A1); V := PerlinNoise3(A1,A2,A3); end; fcClamp : begin Env.StackPopTo(A3); Env.StackPopTo(A2); Env.StackPopTo(A1); V := Clamp(A1,A2,A3); end; fcPow : begin Env.StackPopTo(A2); Env.StackPopTo(A1); V := ZMath.Power(A1,A2); end; fcCenterMouse : begin HasReturnValue := False; ZApp.CenterMouse; end; fcSetRandomSeed : begin V := System.RandSeed; //int to float System.RandSeed := Round(Env.StackPopFloat); //float to int end; fcQuit : begin {$ifndef minimal} Env.ScriptError('Quit called'); {$else} HasReturnValue := False; ZApp.Terminating := True; {$endif} end; fcJoyGetAxis : begin Env.StackPopTo(I2); Env.StackPopTo(I1); V := Platform_GetJoystickAxis(I1,I2); end; fcJoyGetButton : begin Env.StackPopTo(I2); Env.StackPopTo(I1); PInteger(@V)^ := Ord(Platform_GetJoystickButton(I1,I2)) and 1; end; fcJoyGetPOV : begin Env.StackPopTo(I1); V := Platform_GetJoystickPOV(I1); end; fcSystemTime : begin PInteger(@V)^ := Platform_GetSystemTime; end; fcStringLength : begin Env.StackPopToPointer(P1); PInteger(@V)^ := ZStrLength(PAnsiChar(P1)); end; fcStringIndexOf : begin //x=indexOf("lo","hello",2) Env.StackPopTo(I1); Env.StackPopToPointer(P1); Env.StackPopToPointer(P2); PInteger(@V)^ := ZStrPos(PAnsiChar(P2),PAnsiChar(P1),I1); end; fcStrToInt : begin Env.StackPopToPointer(P1); PInteger(@V)^ := ZStrToInt(PAnsiChar(P1)); end; fcOrd : begin //i=ord("A") Env.StackPopToPointer(P1); PInteger(@V)^ := PByte(P1)^; end; fcTrace : begin HasReturnValue := False; Env.StackPopToPointer(P1); {$ifndef minimal} ZLog.GetLog('Zc').Write(String(PAnsiChar(P1)),lleUserTrace); {$endif} {$ifdef android} AndroidLog(PAnsiChar(P1)); {$endif} {$ifdef linux} writeln(PAnsiChar(P1)); {$endif} end; fcTouchGetCount : begin PInteger(@V)^ := Platform_TouchGetCount; end; fcTouchGetX : begin Env.StackPopTo(I1); V := ZApp.NormalizeToScreen( Platform_TouchGetPos(I1) )[0]; end; fcTouchGetY : begin Env.StackPopTo(I1); V := ZApp.NormalizeToScreen( Platform_TouchGetPos(I1) )[1]; end; fcTouchGetID : begin Env.StackPopTo(I1); PInteger(@V)^ := Platform_TouchGetID(I1); end; fcGetBinaryProp : begin Env.StackPopToPointer(A); Env.StackPopToPointer(Bp); if A.GetElementSize*A.CalcLimit<>Bp^.Size then //Only resize if needed A.SizeDim1 := Bp.Size div A.GetElementSize; Move(Bp^.Data^, A.GetData^, Bp^.Size); HasReturnValue := False; end; fcSetBinaryProp : begin Env.StackPopToPointer(A); Env.StackPopToPointer(Bp); Bp^.Size := A.CalcLimit * A.GetElementSize; ReallocMem(Bp^.Data,Bp^.Size); Move(A.GetData^ , Bp^.Data^, Bp^.Size); HasReturnValue := False; end; fcGetModels : begin Env.StackPopTo(I1); Env.StackPopToPointer(A); L := ZApp.Models.Get(I1); A.SizeDim1 := L.Count; P1 := A.GetData; J := 0; for I := 0 to L.Count-1 do begin if TModel(L[I]).Active then begin //Only copy non-removed models PPointer(P1)^ := L[I]; Inc(PPointer(P1)); Inc(J); end; end; A.SizeDim1 := J; //Set to actual models copied over HasReturnValue := False; end; fcSleep : begin Env.StackPopTo(I1); Platform_Sleep(I1); HasReturnValue := False; end; fcStartThread : begin Env.StackPopTo(I1); Env.StackPopToPointer(P1); TZThreadComponent(P1).Start(I1); HasReturnValue := False; end; {$ifndef minimal}else Env.ScriptError('Invalid func op'); {$endif} end; if HasReturnValue then Env.StackPush(V); end; {$ifdef minimal} {$WARNINGS ON} {$endif} { TDefineConstant } procedure TDefineConstant.DefineProperties(List: TZPropertyList); begin inherited; //Defineconstant class or properties are never stored in binary List.AddProperty({$IFNDEF MINIMAL}'Value',{$ENDIF}(@Value), zptFloat); {$ifndef minimal}List.GetLast.IsReadOnly := True;{$endif} {$ifndef minimal}List.GetLast.NeedRefreshNodeName := True; {$endif} {$ifndef minimal}List.GetLast.ExcludeFromBinary := True; {$endif} List.AddProperty({$IFNDEF MINIMAL}'IntValue',{$ENDIF}(@IntValue), zptInteger); {$ifndef minimal}List.GetLast.IsReadOnly := True;{$endif} {$ifndef minimal}List.GetLast.NeedRefreshNodeName := True; {$endif} {$ifndef minimal}List.GetLast.ExcludeFromBinary := True; {$endif} List.AddProperty({$IFNDEF MINIMAL}'StringValue',{$ENDIF}(@StringValue), zptString); {$ifndef minimal}List.GetLast.IsReadOnly := True;{$endif} {$ifndef minimal}List.GetLast.NeedRefreshNodeName := True; {$endif} {$ifndef minimal}List.GetLast.ExcludeFromBinary := True; {$endif} List.AddProperty({$IFNDEF MINIMAL}'ByteValue',{$ENDIF}(@ByteValue), zptByte); {$ifndef minimal}List.GetLast.IsReadOnly := True;{$endif} {$ifndef minimal}List.GetLast.NeedRefreshNodeName := True; {$endif} {$ifndef minimal}List.GetLast.ExcludeFromBinary := True; {$endif} end; {$ifndef minimal} function TDefineConstant.GetDisplayName: AnsiString; begin Result := inherited GetDisplayName + ' '; case _Type.Kind of zctFloat: Result := Result + AnsiString(FormatFloat('###0.#',Value)); zctInt: Result := Result + AnsiString(IntToStr(IntValue)); zctString: Result := Result + '"' + StringValue + '"'; zctByte: Result := Result + AnsiString(IntToStr(ByteValue)); end; end; {$endif} { TDefineArray } procedure TDefineArray.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Dimensions',{$ENDIF}(@Dimensions), zptByte); {$ifndef minimal}List.GetLast.SetOptions(['One','Two','Three']);{$endif} List.AddProperty({$IFNDEF MINIMAL}'SizeDim1',{$ENDIF}(@SizeDim1), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'SizeDim2',{$ENDIF}(@SizeDim2), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'SizeDim3',{$ENDIF}(@SizeDim3), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'Persistent',{$ENDIF}(@Persistent), zptBoolean); List.AddProperty({$IFNDEF MINIMAL}'Values',{$ENDIF}(@Values), zptBinary); end; destructor TDefineArray.Destroy; begin CleanUpManagedValues(_Type.Kind,Limit,AllocPtr); if (Data<>nil) and (not IsExternal) then FreeMem(Data); inherited; end; function TDefineArray.GetData: ZClasses.PFloat; begin //Check if Array size has changed if (Limit<>CalcLimit) then AllocData; {$ifndef minimal} ZAssert(not (Persistent and (_Type.Kind in [zctString,zctModel,zctMat4,zctVec3,zctVec2,zctVec4])),'Persistent arrays of this datatype not supported'); {$endif} if Persistent then begin if Values.Data=nil then AllocData; Result := ZClasses.PFloat(Values.Data) end else begin if Data=nil then AllocData; Result := ZClasses.PFloat(Data); end; end; function TDefineArray.GetElementSize: integer; begin Result := GetZcTypeSize(Self._Type.Kind); end; function TDefineArray.CalcLimit: integer; begin Result := SizeDim1; if SizeDim2>0 then Result := Result * SizeDim2; if SizeDim3>0 then Result := Result * SizeDim3; end; procedure TDefineArray.AllocData; var ByteSize: Integer; P : PPointer; I : integer; WasNil : boolean; begin CleanUpManagedValues(AllocType,AllocItemCount,AllocPtr); Self.Limit := CalcLimit; if IsExternal then Exit; ByteSize := Limit * GetElementSize; if Persistent then begin Self.Values.Size := ByteSize; P := @Self.Values.Data end else P := @Self.Data; WasNil := P^ = nil; ReallocMem(P^, ByteSize); if WasNil then FillChar(P^^, ByteSize, 0); Self.AllocPtr := P^; Self.AllocItemCount := Self.Limit; Self.AllocType := Self._Type.Kind; if Self._Type.Kind in [zctString,zctClass] then begin P := P^; for I := 0 to Self.Limit - 1 do begin ManagedHeap_AddTarget(P); Inc(P); end; end; end; procedure TDefineArray.CleanUpManagedValues(TheType : TZcDataTypeKind; Count : integer; P : PPointer); var I : integer; begin if (not (TheType in [zctString,zctClass])) or (Count=0) then Exit; for I := 0 to Count - 1 do begin ManagedHeap_RemoveTarget(P); Inc(P); end; end; function TDefineArray.PopAndGetElement(Env : PExecutionEnvironment) : ZClasses.PFloat; var Index,I1,I2,I3 : integer; P : PBytes; begin Env.StackPopTo(I3); if Self.Dimensions>=dadTwo then Env.StackPopTo(I2) else I2 := 0; if Self.Dimensions=dadThree then Env.StackPopTo(I1) else I1 := 0; case Self.Dimensions of dadOne: Index := I3; dadTwo: Index := (I2*SizeDim2) + I3; else Index := (I1*SizeDim2*SizeDim3) + (I2*SizeDim3) + I3; end; P := PBytes(GetData); {$ifndef minimal} if ((Index<0) or (Index>=Limit)) or ((I1<0) or (I2<0) or (I3<0)) or ((Dimensions=dadOne) and (I3>=SizeDim1)) or ((Dimensions=dadTwo) and ((I2>=SizeDim1) or (I3>=SizeDim2))) or ((Dimensions=dadThree) and ((I1>=SizeDim1) or (I2>=SizeDim2) or (I3>=SizeDim3))) then begin Env.ScriptError('Array access outside range: ' + String(Self.Name) + ' ' + IntToStr(I1) + ' ' + IntToStr(I2) + ' ' + IntToStr(I3)); Result := nil; Exit; end; {$endif} Result := @P^[Index * Self.GetElementSize]; end; function TDefineArray.SetExternalData(P: pointer) : PPointer; begin Self.Data := P; Self.IsExternal := True; Result := @Self.Data; end; { TExpArrayWrite } procedure TExpArrayGetElement.Execute(Env : PExecutionEnvironment); var P : Pointer; A : TDefineArray; begin Env.StackPopToPointer(A); P := A.PopAndGetElement(Env); Env.StackPushPointer(P); end; { TExpStackFrame } procedure TExpStackFrame.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Size',{$ENDIF}(@Size), zptInteger); end; procedure TExpStackFrame.Execute(Env : PExecutionEnvironment); //http://en.wikipedia.org/wiki/Function_prologue begin Env.StackPush(Env.gCurrentBP); Env.gCurrentBP := Env.StackGetDepth; //Null-initialize stack frame FillChar(Env.ZcStackPtr^,Self.Size * SizeOf(Env.ZcStackPtr^),0); //Add frame to stack Inc(Env.ZcStackPtr,Self.Size); end; { TExpAccessLocal } procedure TExpAccessLocal.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}(@Kind), zptByte); List.AddProperty({$IFNDEF MINIMAL}'Index',{$ENDIF}(@Index), zptInteger); end; procedure TExpAccessLocal.Execute(Env : PExecutionEnvironment); var P : TExecutionEnvironment.PStackElement; begin //Use pointer size to get all bits in 64-bit mode P := Env.StackGetPtrToItem( Env.gCurrentBP + Self.Index ); case Kind of loLoad: Env.StackPushPointer(P^); loStore: Env.StackPopToPointer(P^); loGetAddress: Env.StackPushPointer(P); end; end; {$ifndef minimal} function TExpAccessLocal.ExpAsText : string; begin if Kind=loLoad then Result := 'Load' else if Kind=loStore then Result := 'Store' else Result := 'GetAddress'; Result := Result + ' ' + IntToStr(Self.Index) + ' (local)'; end; {$endif} { TExpAccessGlobal } procedure TExpAccessGlobal.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}@Kind, zptByte); List.AddProperty({$IFNDEF MINIMAL}'Offset',{$ENDIF}@Offset, zptInteger); List.AddProperty({$IFNDEF MINIMAL}'Lib',{$ENDIF}@Lib, zptComponentRef); end; procedure TExpAccessGlobal.Execute(Env : PExecutionEnvironment); var P : TExecutionEnvironment.PStackElement; begin //Use pointer size to get all bits in 64-bit mode P := TExecutionEnvironment.PStackElement(NativeUInt(Lib.GlobalArea)+Cardinal(Self.Offset)); case Kind of glLoad: Env.StackPushPointer(P^); glStore: Env.StackPopToPointer(P^); glGetAddress: Env.StackPushPointer(P); end; end; {$ifndef minimal} function TExpAccessGlobal.ExpAsText : string; begin if Kind=glLoad then Result := 'Load' else if Kind=glStore then Result := 'Store' else Result := 'GetAddress'; Result := Result + ' ' + IntToStr(Self.Offset) + ' (global)'; end; {$endif} { TExpReturn } procedure TExpReturn.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'HasFrame',{$ENDIF}(@HasFrame), zptBoolean); List.AddProperty({$IFNDEF MINIMAL}'HasReturnValue',{$ENDIF}(@HasReturnValue), zptBoolean); List.AddProperty({$IFNDEF MINIMAL}'Arguments',{$ENDIF}(@Arguments), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'Lib',{$ENDIF}(@Lib), zptComponentRef); end; {$warnings off} procedure TExpReturn.Execute(Env : PExecutionEnvironment); var RetVal : pointer; begin if HasReturnValue then begin //Local0 holds returnvalue //Treat return value as pointer to get all bits in 64-bit mode RetVal := PPointer( Env.StackGetPtrToItem( Env.gCurrentBP ) )^; end; if HasFrame then begin Dec(Env.ZcStackPtr,Env.StackGetDepth-Env.gCurrentBP); Env.StackPopTo(Env.gCurrentBP); end; //Get return adress Env.StackPopToPointer(Env.gCurrentPc); //Clean stack of function arguments Dec(Env.ZcStackPtr,Arguments); if HasReturnValue then begin Env.StackPushPointer(RetVal); end; if (Lib<>nil) and Lib.UseThreadLock then Lib.ReleaseLock end; {$warnings on} { TExpBase } {$ifndef minimal} function TExpBase.ExpAsText: string; var PropList : TZPropertyList; Prop : TZProperty; Value : TZPropertyValue; I : integer; S : string; begin Result := Copy(ComponentManager.GetInfo(Self).ZClassName,4,255); PropList := Self.GetProperties; for I := 4 to PropList.Count-1 do begin Prop := TZProperty(PropList[I]); Value := Self.GetProperty(Prop); case Prop.PropertyType of zptFloat,zptScalar : S := FloatToStr( RoundTo( Value.FloatValue ,-FloatTextDecimals) ); zptInteger : S := IntToStr(Value.IntegerValue); zptComponentRef : begin if Value.ComponentValue=nil then S := '*null*' else begin S := String(Value.ComponentValue.Name); if S='' then S := Value.ComponentValue.ClassName; end; end; zptByte : S := IntToStr(Value.ByteValue); zptBoolean : S := IntToStr( byte(Value.BooleanValue) ); else S := ''; end; Result:=Result + ' ' + S; end; end; {$endif} { TExpMisc } procedure TExpMisc.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}(@Kind), zptByte); end; procedure TExpMisc.Execute(Env : PExecutionEnvironment); var V : integer; P,ValueP : pointer; begin case Kind of emPop: Env.StackPopFloat; //Pop, discard value from top of stack emDup : begin Env.StackPopTo(V); Env.StackPush(V); Env.StackPush(V); end; emLoadCurrentModel : Env.StackPushPointer( Meshes.CurrentModel ); emPtrDeref4 : begin Env.StackPopToPointer(P); {$ifdef CALLSTACK} Env.CheckNilDeref(P); {$endif} V := PInteger(P)^; Env.StackPush(V); end; emPtrDeref1 : begin Env.StackPopToPointer(P); {$ifdef CALLSTACK} Env.CheckNilDeref(P); {$endif} V := PByte(P)^; Env.StackPush(V); end; emPtrDerefPointer : begin Env.StackPopToPointer(P); {$ifdef CALLSTACK} Env.CheckNilDeref(P); {$endif} Env.StackPushPointer(P^); end; emNotifyPropChanged : begin Env.StackPopTo(V); Env.StackPopToPointer(P); Env.StackPopToPointer(ValueP); TZComponent(P).GetProperties.GetById(V).NotifyWhenChanged(P,V,ValueP); end; emLoadNull : begin P := nil; Env.StackPushPointer(P); end; emNop : ; emBinaryNot : begin Env.StackPopTo(V); V := not V; Env.StackPush(V); end; emNot : begin Env.StackPopTo(V); if V=0 then V := 1 else V := 0; Env.StackPush(V); end; emGetUserClass : begin //Convert TUserClassInstance to the instancedata for field access Env.StackPopToPointer(P); {$ifdef CALLSTACK} Env.CheckNilDeref(P); {$endif} Env.StackPushPointer( TUserClassInstance(P).InstanceData ); end; emGetGlobalDataProp : begin Env.StackPopTo(V); Env.StackPopToPointer(P); P := TZComponent(P).GetPropertyPtr(TZComponent(P).GetProperties.GetById(V),0); Env.StackPushPointer(P); end; end; end; {$ifndef minimal} constructor TExpMisc.Create(OwnerList: TZComponentList; Kind: TExpMiscKind); begin inherited Create(OwnerList); Self.Kind := Kind; end; function TExpMisc.ExpAsText : string; begin Result := Copy(GetEnumName(TypeInfo(TExpMiscKind),Ord(Kind)),3,100) + ' (misc)'; end; {$endif} { TZLibrary } procedure TZLibrary.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Source',{$ENDIF}@Source, zptExpression); {$ifndef minimal}List.GetLast.ExpressionKind := ekiLibrary;{$endif} List.AddProperty({$IFNDEF MINIMAL}'UseThreadLock',{$ENDIF}@UseThreadLock, zptBoolean); List.AddProperty({$IFNDEF MINIMAL}'HasInitializer',{$ENDIF}@HasInitializer, zptBoolean); {$ifndef minimal}List.GetLast.HideInGui := True;{$endif} List.AddProperty({$IFNDEF MINIMAL}'GlobalAreaSize',{$ENDIF}@GlobalAreaSize, zptInteger); {$ifndef minimal}List.GetLast.HideInGui := True;{$endif} {$ifndef minimal}List.GetLast.ExcludeFromXml := True;{$endif} List.AddProperty({$IFNDEF MINIMAL}'ManagedVariables',{$ENDIF}@ManagedVariables, zptBinary); {$ifndef minimal}List.GetLast.HideInGui := True;{$endif} {$ifndef minimal}List.GetLast.ExcludeFromXml := True;{$endif} end; procedure TZLibrary.AquireLock; begin if Self.Lock=nil then Lock := Platform_CreateMutex; Platform_EnterMutex(Lock); end; procedure TZLibrary.ReleaseLock; begin Platform_LeaveMutex(Lock); end; procedure TZLibrary.Update; begin inherited; if Self.HasInitializer and (not Self.HasExecutedInitializer) then begin ZExpressions.RunCode(Source.Code); Self.HasExecutedInitializer := True; end; end; procedure TZLibrary.InitAfterPropsAreSet; begin inherited; InitGlobalArea; end; procedure TZLibrary.RemoveManagedTargets; var Offsets : PInteger; I,ManagedCount : integer; P : pointer; begin if (Self.ManagedVariables.Size>0) and (GlobalArea<>nil) then begin //Remove targets for managed variables ManagedCount := Self.ManagedVariables.Size div 4; Offsets := PInteger(ManagedVariables.Data); for I := 0 to ManagedCount-1 do begin P := Pointer(IntPtr(Self.GlobalArea) + Offsets^); ManagedHeap_RemoveTarget( P ); Inc(Offsets); end; end; end; procedure TZLibrary.InitGlobalArea; var Offsets : PInteger; I,ManagedCount : integer; P : pointer; begin if (Self.GlobalAreaSize>0) then begin ReAllocMem(Self.GlobalArea,Self.GlobalAreaSize); FillChar(Self.GlobalArea^,Self.GlobalAreaSize,0); if Self.ManagedVariables.Size>0 then begin //Add targets for managed fields ManagedCount := Self.ManagedVariables.Size div 4; Offsets := PInteger(ManagedVariables.Data); for I := 0 to ManagedCount-1 do begin P := Pointer(IntPtr(Self.GlobalArea) + Offsets^); ManagedHeap_AddTarget( P ); Inc(Offsets); end; end; end; end; destructor TZLibrary.Destroy; begin {$ifndef minimal} if Lock<>nil then Platform_FreeMutex(Lock); {$endif} RemoveManagedTargets; FreeMem(GlobalArea); inherited; end; {$ifndef minimal} procedure TZLibrary.DesignerReset; begin Self.HasExecutedInitializer := False; RemoveManagedTargets; InitGlobalArea; inherited; end; procedure TZLibrary.AddGlobalVar(const Typ: TZcDataType); begin //Need to always increase 8 here instead of sizeof(pointer) to //allow generated binary to be compatible with both 32 and 64 bit runtime. if Typ.Kind in ManagedTypes then begin Inc(ManagedVariables.Size,4); ReallocMem(ManagedVariables.Data,ManagedVariables.Size); PInteger( pointer(IntPtr(ManagedVariables.Data)+ManagedVariables.Size-4) )^ := Self.GlobalAreaSize; end; Inc(Self.GlobalAreaSize,8); end; {$endif} { TExpUserFuncCall } procedure TExpUserFuncCall.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Lib',{$ENDIF}(@Lib), zptComponentRef); List.AddProperty({$IFNDEF MINIMAL}'Index',{$ENDIF}(@Index), zptInteger); end; procedure TExpUserFuncCall.Execute(Env : PExecutionEnvironment); begin if Lib.UseThreadLock then Lib.AquireLock; Env.StackPushPointer(Env.gCurrentPC); Env.gCurrentPC := Lib.Source.Code.GetPtrToItem(Index); Dec(Env.gCurrentPc); end; { TExpConvert } procedure TExpConvert.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}(@Kind), zptByte); end; procedure TExpConvert.Execute(Env : PExecutionEnvironment); var V : single; I : integer; D : TDefineArray; P : pointer; Bp : PZBinaryPropValue; begin case Kind of eckFloatToInt: begin I := Trunc(Env.StackPopFloat); Env.StackPush(I); end; eckIntToFloat : begin Env.StackPopTo(I); V := I; Env.StackPush(V); end; eckArrayToXptr : begin Env.StackPopToPointer(D); P := D.GetData; Env.StackPushPointer(P); end; eckBinaryToXptr : begin Env.StackPopToPointer(Bp); P := Bp.Data; Env.StackPushPointer(P); end; eckPropToVec3,eckPropToVec4 : begin Env.StackPopToPointer(P); D := TDefineArray(CreateManagedValue(TZcDataTypeKind(Ord(zctVec3)+Ord(Kind)-Ord(eckPropToVec3)))); D.SetExternalData(P); Env.StackPushPointer(D); end; end; end; { TExpAssign4 } procedure TExpAssign4.Execute(Env : PExecutionEnvironment); var I : integer; P : pointer; begin Env.StackPopTo(I); Env.StackPopToPointer(P); PInteger(P)^ := I; end; { TExpAssign1 } procedure TExpAssign1.Execute(Env : PExecutionEnvironment); var V : integer; B : byte; P : pointer; begin //Cast integer to byte before assigning Env.StackPopTo(V); Env.StackPopToPointer(P); B := V; PByte(P)^ := B; end; { TExpAssignPointer } procedure TExpAssignPointer.Execute(Env : PExecutionEnvironment); var V,P : pointer; begin Env.StackPopToPointer(V); Env.StackPopToPointer(P); PPointer(P)^ := V; end; { TDefineVariableBase } procedure TDefineVariableBase.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Type',{$ENDIF}@_Type.Kind, zptByte); {$ifndef minimal}List.GetLast.SetOptions(['float','int','string','model','byte','mat4','vec2','vec3','vec4','xptr']);{$endif} {$ifndef minimal}List.GetLast.NeedRefreshNodeName:=True;{$endif} end; {$ifndef minimal} function TDefineVariableBase.GetDisplayName: AnsiString; var I : integer; P : TZProperty; begin I := Ord(Self._Type.Kind); P := Self.GetProperties.GetByName('Type'); if I<Length(P.Options) then Result := inherited GetDisplayName + ' <' + AnsiString(P.Options[ I ]) + '>' else Result := inherited GetDisplayName + ' <error>'; end; {$endif} { TExpStringConstant } procedure TExpStringConstant.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$ifndef minimal}'Value',{$ENDIF}(@Value), zptString); end; { TExpStringConCat } procedure TExpStringConCat.Execute(Env : PExecutionEnvironment); var P1,P2,Dest : PAnsiChar; I : integer; begin Env.StackPopToPointer(P2); Env.StackPopToPointer(P1); I := ZStrLength(P1) + ZStrLength(P2); //Add to gc Dest := ManagedHeap_Alloc(I+1); ZStrCopy(Dest,P1); ZStrCat(Dest,P2); Env.StackPushPointer(Dest); end; { TExpPointerFuncCall } procedure TExpPointerFuncCall.Execute(Env : PExecutionEnvironment); var I1,I2 : integer; Buf : array[0..15] of ansichar; P1,Dest : PAnsiChar; M : TModel; begin case Kind of fcIntToStr: begin Env.StackPopTo(I1); ZStrConvertInt(I1,PAnsiChar(@Buf)); Dest := ManagedHeap_Alloc(ZStrLength(@Buf)+1); ZStrCopy(Dest,@Buf); end; fcSubStr : begin //s=subStr("hello",0,2) Env.StackPopTo(I1); Env.StackPopTo(I2); Env.StackPopToPointer(P1); Dest := ManagedHeap_Alloc(I1+1); ZStrSubString(P1,Dest,I2,I1); end; fcChr : begin //s=chr(65); Env.StackPopTo(I1); Dest := ManagedHeap_Alloc(2); Dest^ := PAnsiChar(@I1)^; PBytes(Dest)^[1] := 0; end; fcCreateModel : begin Env.StackPopToPointer(M); //AddToScene will call m.OnSpawn which in turn can run expressions M := TModel(M.CloneModel); M.AddToScene(ZApp); Dest := pointer(M); end; end; Env.StackPushPointer(Dest); end; { TExternalLibrary } procedure TZExternalLibrary.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'ModuleName',{$ENDIF}(@ModuleName), zptString); {$ifndef minimal}List.GetLast.NeedRefreshNodeName := True;{$endif} List.GetLast.IsManagedTarget := True; List.AddProperty({$IFNDEF MINIMAL}'CallingConvention',{$ENDIF}(@CallingConvention), zptByte); {$ifndef minimal}List.GetLast.SetOptions(['Stdcall','Cdecl']);{$endif} List.AddProperty({$IFNDEF MINIMAL}'BeforeInitExp',{$ENDIF}(@BeforeInitExp), zptExpression); List.AddProperty({$IFNDEF MINIMAL}'Source',{$ENDIF}(@Source), zptExpression); {$ifndef minimal} List.GetLast.DefaultValue.ExpressionValue.Source := '//Import a DLL-library by setting ModuleName to name of the DLL'#13#10 + '//and then declaring the function headers here. For example:'#13#10 + '//'#13#10 + '// int SetWindowLongA(int hWnd, int nIndex, int dwNewLong) { } '#13#10 + '// int SetWindowTextA(int hWnd,string lpString) { }'; List.GetLast.ExcludeFromBinary := True; List.GetLast.ExpressionKind := ekiLibrary; {$endif} {$ifndef minimal} List.AddProperty({$IFNDEF MINIMAL}'DefinitionsFile',{$ENDIF}(@DefinitionsFile), zptString); List.SetDesignerProperty; {$endif} end; procedure TZExternalLibrary.ClearEntries; var entry: PExternalFunctionEntry; i: Integer; begin for i := 0 to Entries.Count - 1 do begin entry := PExternalFunctionEntry(Entries[i]); {$if defined(cpuaarch64)} // ARM64 fpmunmap(entry.Trampoline, 512); {$endif} {$if defined(MSWINDOWS) and defined(CPUX64)} FreeMem(entry.Trampoline); {$endif} FreeMem(entry.Name); Dispose(entry); end; Entries.Clear; end; function TZExternalLibrary.GetEntry(P: PAnsiChar): PExternalFunctionEntry; var i, nameLength: Integer; entry: PExternalFunctionEntry; proc: Pointer; begin if ModuleHandle=0 then begin ZExpressions.RunCode(BeforeInitExp.Code); ModuleHandle := Platform_LoadModule(Self.ModuleName); if ModuleHandle=0 then {$ifndef minimal} ZHalt(Self.ModuleName + ' not found'); {$else} ZHalt(Self.ModuleName); {$endif} end; nameLength := ZStrLength(P); for i := 0 to Entries.Count - 1 do begin entry := PExternalFunctionEntry(Entries[i]); if (entry.NameLength = nameLength) and ZStrCompare(P, entry.Name) then Exit(entry); // return existing entry end; proc := Platform_GetModuleProc(ModuleHandle,P); if proc=nil then //OpenGL functions needs to be handled differently (at least on Win32) proc := Platform_GLLoadProc(P); if proc=nil then begin {$ifndef minimal} ZHalt(P + ' not found'); {$else} ZHalt(P); {$endif} Exit(nil); end; // add new entry New(Result); Result.Proc := proc; Result.NameLength := nameLength; GetMem(Result.Name, nameLength + 1); ZStrCopy(Result.Name, P); Result.Trampoline := nil; Entries.Add(TObject(Result)); end; constructor TZExternalLibrary.Create(OwnerList: TZComponentList); begin inherited Create(OwnerList); Entries := TZArrayList.CreateReferenced; end; destructor TZExternalLibrary.Destroy; begin {$ifndef minimal} if Self.ModuleHandle<>0 then Platform_FreeModule(Self.ModuleHandle); {$endif} inherited; ClearEntries; Entries.Free; end; {$ifndef minimal} procedure TZExternalLibrary.DesignerReset; begin inherited; if Self.ModuleHandle<>0 then begin {$ifdef MSWINDOWS} Platform_FreeModule(Self.ModuleHandle); Self.ModuleHandle := 0; {$endif} end; ClearEntries; end; function TZExternalLibrary.GetDisplayName: AnsiString; begin Result := inherited GetDisplayName + ' ' + Self.ModuleName; end; {$endif} { TExpExternalFuncCall } procedure TExpExternalFuncCall.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Lib',{$ENDIF}(@Lib), zptComponentRef); List.AddProperty({$IFNDEF MINIMAL}'FuncName',{$ENDIF}(@FuncName), zptString); List.AddProperty({$IFNDEF MINIMAL}'ArgCount',{$ENDIF}(@ArgCount), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'ReturnType',{$ENDIF}(@ReturnType), zptByte); List.AddProperty({$IFNDEF MINIMAL}'ArgTypes',{$ENDIF}(@ArgTypes), zptString); end; {$ifndef minimal} procedure TExpExternalFuncCall.DesignerReset; begin inherited; Self.Entry := nil; end; {$endif} {$if defined(android) and defined(cpu32)} // 32-bit Android procedure TExpExternalFuncCall.Execute(Env : PExecutionEnvironment); const MaxArgs = 16; type TArgArray = array[0..MaxArgs-1] of integer; TFunc = procedure(); PFunc = ^TFunc; TDummyFunc = procedure(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16 : integer); PDummyFunc = ^TDummyFunc; var Arg1,I,RetVal,Tmp : integer; P : pointer; TheFunc : PFunc; Args : TArgArray; begin if Self.Entry=nil then begin Self.Entry := Lib.GetEntry(Self.FuncName); //Make sure android generates enough stack space for calling a func with maxargs params if ArgCount<0 then PDummyFunc(Self.Entry.Proc)^(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1); //Should never execute end; TheFunc := Self.Entry.Proc; if ArgCount>MaxArgs then begin Platform_Error('Too many arguments to external function call'); Exit; end; //Transfer arguments from Zc-stack to hardware stack for I := 0 to ArgCount-1 do Env.StackPopTo(Args[ArgCount-I-1]); //http://en.wikipedia.org/wiki/Calling_convention#ARM //First params in r-registers //Then on stack if ArgCount>4 then begin P := @Args+16; Tmp := ArgCount-4; asm ldr r0, Tmp ldr r1, P mov r3, #0 .Lmyloop: ldr r2, [r1, r3] str r2, [r13, r3] add r3,r3,#4 sub r0,r0,#1 cmp r0,#0 bgt .Lmyloop end; end; asm ldr r0, Args ldr r1, Args+4 ldr r2, Args+8 ldr r3, Args+12 ldr r4,TheFunc blx r4 str r0,RetVal end; // ldr r4, Args+16 // str r4,[r13] // ldr r4, Args+20 // str r4,[r13, #4] // ldr r4, Args+24 // str r4,[r13, #8] // ldr r4, Args+28 // str r4,[r13, #12] if Self.ReturnType.Kind<>zctVoid then Env.StackPush(RetVal); end; {$elseif defined(cpux64)} // 64-bit Intel Mac and Windows procedure DummyProc(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12 : NativeInt); begin end; {$ifndef MSWINDOWS} function mprotect(__addr:pointer;__len:cardinal;__prot:longint):longint; cdecl; external 'libc' name 'mprotect'; {$endif} function GenerateTrampoline(const ArgCount : integer; ArgTypes : PAnsiChar; Proc : pointer) : pointer; const {$ifdef MSWINDOWS} IntRegCount = 4; FloatRegCount = 4; Int64Regs : array[0..IntRegCount-1] of array[0..3] of byte = ( ($49,$8B,$4A,0), //mov rcx,[r10+x] ($49,$8B,$52,0), ($4d,$8B,$42,0), ($4d,$8B,$4A,0) ); Int32Regs : array[0..IntRegCount-1] of array[0..3] of byte = ( ($41,$8B,$4A,0), //mov ecx,[r10+x] ($41,$8B,$52,0), ($45,$8B,$42,0), ($45,$8B,$4A,0) ); Float32Regs : array[0..FloatRegCount-1] of array[0..5] of byte = ( ($66,$41,$0F,$6E,$42,0), //movd xmm0,[r10+x] ($66,$41,$0F,$6E,$4A,0), ($66,$41,$0F,$6E,$52,0), ($66,$41,$0F,$6E,$5A,0) ); {$ELSE} //Non MS-abi: https://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_calling_conventions IntRegCount = 6; FloatRegCount = 8; Int64Regs : array[0..IntRegCount-1] of array[0..3] of byte = ( ($49,$8B,$7A,0), //mov rdi,[r10+x] ($49,$8B,$72,0), ($49,$8B,$52,0), ($49,$8B,$4A,0), ($4D,$8B,$42,0), ($4D,$8B,$4A,0) ); Int32Regs : array[0..IntRegCount-1] of array[0..3] of byte = ( ($41,$8B,$7A,0), //mov edi,[r10+x] ($41,$8B,$72,0), ($41,$8B,$52,0), ($41,$8B,$4A,0), ($45,$8B,$42,0), ($45,$8B,$4A,0) ); Float32Regs : array[0..FloatRegCount-1] of array[0..5] of byte = ( ($66,$41,$0F,$6E,$42,0), //movd xmm0,[r10+x] ($66,$41,$0F,$6E,$4A,0), ($66,$41,$0F,$6E,$52,0), ($66,$41,$0F,$6E,$5A,0), ($66,$41,$0F,$6E,$62,0), ($66,$41,$0F,$6E,$6A,0), ($66,$41,$0F,$6E,$72,0), ($66,$41,$0F,$6E,$7A,0) ); {$ENDIF} Int32Stack1 : array[0..3] of byte = ($41,$8B,$42,0); //mov eax,[r10+$10] Int32Stack2 : array[0..3] of byte = ($89,$44,$24,0); //mov [rsp+$10],eax Int64Stack1 : array[0..3] of byte = ($49,$8B,$42,0); //mov rax,[r10+$10] Int64Stack2 : array[0..4] of byte = ($48,$89,$44,$24,0); //mov [rsp+$10],rax var P : PByte; procedure W(const code : array of byte); var I : integer; begin for I := 0 to High(Code) do begin P^ := Code[I]; Inc(P); end; end; var I,FloatI,IntI,Offs : integer; OldProtect : dword; CodeSize : integer; StackOffs : integer; UseStack : boolean; begin {$ifdef MSWINDOWS} CodeSize := 64 + (6 * ArgCount); GetMem(Result,CodeSize); {$else} CodeSize := 512; //Use fixed size so we don't have to save the size for unmap call Result := fpmmap(nil,CodeSize,PROT_READ or PROT_WRITE or PROT_EXEC,MAP_PRIVATE or MAP_ANONYMOUS,-1,0); {$endif} P := Result; if ArgCount>0 then //Copy Args-ptr to R10 {$ifdef MSWINDOWS} W([$49,$89,$ca]); //mov r10,rcx {$else} W([$49,$89,$fa]); //mov r10,rdi {$endif} Offs := 0; //Offset in Args {$ifdef MSWINDOWS} StackOffs := $28; {$else} StackOffs := 8; {$endif} {$ifndef MSWINDOWS} FloatI := 0; IntI := 0; {$endif} for I := 0 to ArgCount-1 do begin UseStack := False; {$ifdef MSWINDOWS} //MS-calling convention uses registers for 4 first parameters only, regardless of float or int. //Rest of the world uses 6 int + 8 float registers depending on argument types. FloatI := I; IntI := I; {$endif} case TZcDataTypeKind(Ord(ArgTypes[I])-65) of zctInt : begin if IntI<IntRegCount then begin W(Int32Regs[IntI]); P[-1] := Offs; {$ifndef MSWINDOWS} Inc(IntI); {$endif} end else UseStack := True; end; zctString,zctModel,zctXptr,zctMat4,zctVec2,zctVec3,zctVec4,zctArray : begin if IntI<IntRegCount then begin W(Int64Regs[IntI]); P[-1] := Offs; {$ifndef MSWINDOWS} Inc(IntI); {$endif} end else UseStack := True; end; zctFloat : begin if FloatI<FloatRegCount then begin W(Float32Regs[FloatI]); P[-1] := Offs; {$ifndef MSWINDOWS} Inc(FloatI); {$endif} end else UseStack := True; end; else Assert(False,'This argument type not yet supported on 64-bit:'); end; if UseStack then begin //push on stack case GetZcTypeSize(TZcDataTypeKind(Ord(ArgTypes[I])-65)) of 4 : begin W(Int32Stack1); P[-1] := Offs; W(Int32Stack2); P[-1] := StackOffs; end; 8 : begin W(Int64Stack1); P[-1] := Offs; W(Int64Stack2); P[-1] := StackOffs; end; else Assert(False,'This argument type not yet supported on 64-bit'); end; Inc(StackOffs, 8); end; Inc(Offs, SizeOf(TExecutionEnvironment.TStackElement) ); end; W([$49,$bb]); //mov r11,x PPointer(P)^ := Proc; Inc(P,8); //x W([$49,$ff,$e3]); //jmp r11 {$ifdef mswindows} Windows.VirtualProtect(Result,CodeSize,PAGE_EXECUTE_READWRITE,@OldProtect); {$else} mprotect(Result,CodeSize,PROT_READ or PROT_WRITE or PROT_EXEC); {$endif} end; procedure TExpExternalFuncCall.Execute(Env : PExecutionEnvironment); type TFunc = function(Args : pointer) : NativeUInt; TFloatFunc = function(Args : pointer) : single; var RetVal : NativeUInt; begin if Self.Entry=nil then begin Self.Entry := Lib.GetEntry(Self.FuncName); //Make sure there is enough stack space for calling a func with 8 params DummyProc(1,2,3,4,5,6,7,8,9,10,11,12); if Self.Entry.Trampoline = nil then Self.Entry.Trampoline := GenerateTrampoline(ArgCount, Self.ArgTypes, Self.Entry.Proc); {$ifndef minimal} Assert(Length(Self.ArgTypes)=ArgCount); {$endif} end; if Self.ReturnType.Kind=zctFloat then begin //Float returns in xmm0 PSingle(@RetVal)^ := TFloatFunc(Self.Entry.Trampoline)( Env.StackPopAndGetPtr(ArgCount) ); end else //other return types return in rax Retval := TFunc(Self.Entry.Trampoline)( Env.StackPopAndGetPtr(ArgCount) ); if Self.ReturnType.Kind<>zctVoid then begin if GetZcTypeSize(Self.ReturnType.Kind)=SizeOf(Pointer) then Env.StackPushPointer(RetVal) else Env.StackPush(RetVal); end; end; {$elseif defined(cpux86) or defined(CPU32)} //CPU32 is for Freepascal // 32-bit Intel procedure TExpExternalFuncCall.Execute(Env : PExecutionEnvironment); {.$define darwin} type TFunc = procedure(); PFunc = ^TFunc; var Arg1,I,RetVal : integer; TheFunc : PFunc; Args : array[0..31] of integer; RetValFloat : single; {$ifndef minimal} BeforeSP,AfterSP : integer; {$endif} {$ifdef darwin} OsxExtra : integer; {$endif} begin {$ifndef minimal} Assert(ArgCount<High(Args),'Too many arguments to external function'); {$endif} if Self.Entry=nil then Self.Entry := Lib.GetEntry(Self.FuncName); TheFunc := Self.Entry.Proc; //Transfer arguments from Zc-stack to hardware stack for I := 0 to ArgCount-1 do Env.StackPopTo(Args[I]); {$ifndef minimal} asm mov BeforeSP,esp end; {$endif} {$ifdef darwin} //http://blogs.embarcadero.com/eboling/2009/05/20/5607 //http://blogs.embarcadero.com/abauer/2010/01/14/38904 I := ArgCount * 4 + 4; while (I and 15)<>0 do Inc(I,4); OsxExtra := (I-4) - (ArgCount*4); if OsxExtra>0 then asm sub esp,OsxExtra end; {$endif} for I := 0 to ArgCount-1 do begin Arg1 := Args[I]; asm push Arg1 end; end; {$ifdef darwin} asm mov eax,esp and eax,8 mov I,eax end; if I<>0 then ZHalt('Zzdc Stack error'); {$endif} asm //Make the call call TheFunc //Non-float results are returned in eax mov RetVal,eax end; //Cdecl requires caller to clean up stack if Lib.CallingConvention=ccCdecl then begin I := ArgCount * 4; asm add esp,I end; end; {$ifdef darwin} if OsxExtra>0 then asm add esp,OsxExtra end; {$endif} if Self.ReturnType.Kind=zctFloat then begin //Float-values results returned on float-stack asm fstp RetValFloat wait end; RetVal := PInteger(@RetValFloat)^; end; {$ifndef minimal} //Check hw-stack consistency asm mov AfterSP,esp end; if AfterSP<>BeforeSP then begin asm mov esp,BeforeSP end; ZHalt('Hardware stack error after call to ' + Self.FuncName + '. Check argument count and sizes, and calling convention.'); end; {$endif} if Self.ReturnType.Kind<>zctVoid then Env.StackPush(RetVal); end; {$endif} {$if defined(cpuaarch64)} // ARM64 Android and Mac procedure DummyProc(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12 : NativeInt); begin end; function mprotect(__addr:pointer;__len:cardinal;__prot:longint):longint; cdecl; external 'libc' name 'mprotect'; {$IFDEF MACOS} procedure pthread_jit_write_protect_np(enabled : integer); cdecl; external 'pthread' name 'pthread_jit_write_protect_np'; procedure sys_icache_invalidate(start : pointer; len : nativeuint); cdecl; external 'libc' name 'sys_icache_invalidate'; {$ENDIF} function GenerateTrampoline(const ArgCount : integer; ArgTypes : PAnsiChar; Proc : pointer) : pointer; { https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=msvc-160 http://shell-storm.org/online/Online-Assembler-and-Disassembler/ https://godbolt.org/ https://developer.apple.com/documentation/apple_silicon/porting_just-in-time_compilers_to_apple_silicon?language=objc } const IntRegCount = 8; FloatRegCount = 8; PtrRegs : array[0..IntRegCount-1] of array[0..3] of byte = ( ($00,$01,$40,$f9), //ldr x0,[x8] ($01,$01,$40,$f9), //ldr x1,[x8] ($02,$01,$40,$f9), //ldr x2,[x8] ($03,$01,$40,$f9), //ldr x3,[x8] ($04,$01,$40,$f9), //ldr x4,[x8] ($05,$01,$40,$f9), //ldr x5,[x8] ($06,$01,$40,$f9), //ldr x6,[x8] ($07,$01,$40,$f9) //ldr x7,[x8] ); Int32Regs : array[0..IntRegCount-1] of array[0..3] of byte = ( ($00,$01,$40,$b9), //ldr w0,[x8] ($01,$01,$40,$b9), //ldr w1,[x8] ($02,$01,$40,$b9), //ldr w2,[x8] ($03,$01,$40,$b9), //ldr w3,[x8] ($04,$01,$40,$b9), //ldr w4,[x8] ($05,$01,$40,$b9), //ldr w5,[x8] ($06,$01,$40,$b9), //ldr w6,[x8] ($07,$01,$40,$b9) //ldr w7,[x8] ); Float32Regs : array[0..FloatRegCount-1] of array[0..3] of byte = ( ($00,$01,$40,$bd), //ldr s0,[x8] ($01,$01,$40,$bd), //ldr s1,[x8] ($02,$01,$40,$bd), //ldr s2,[x8] ($03,$01,$40,$bd), //ldr s3,[x8] ($04,$01,$40,$bd), //ldr s4,[x8] ($05,$01,$40,$bd), //ldr s5,[x8] ($06,$01,$40,$bd), //ldr s6,[x8] ($07,$01,$40,$bd) //ldr s7,[x8] ); Int32Stack : array[0..4-1] of array[0..7] of byte = ( ($09,$01,$40,$b9,$e9,$03,$00,$b9), //ldr w9,[x8] str w9,[sp] ($09,$01,$40,$b9,$e9,$0b,$00,$b9), //ldr w9,[x8] str w9,[sp,#8] ($09,$01,$40,$b9,$e9,$13,$00,$b9), //ldr w9,[x8] str w9,[sp,#16] ($09,$01,$40,$b9,$e9,$1b,$00,$b9) //ldr w9,[x8] str w9,[sp,#24] ); PtrStack : array[0..4-1] of array[0..7] of byte = ( ($09,$01,$40,$f9,$e9,$03,$00,$f9), //ldr x9,[x8] str x9,[sp] ($09,$01,$40,$f9,$e9,$07,$00,$f9), //ldr x9,[x8] str x9,[sp,#8] ($09,$01,$40,$f9,$e9,$0b,$00,$f9), //ldr x9,[x8] str x9,[sp,#16] ($09,$01,$40,$f9,$e9,$0f,$00,$f9) //ldr x9,[x8] str x9,[sp,#24] ); var P : PByte; procedure W(const code : array of byte); var I : integer; begin for I := 0 to High(Code) do begin P^ := Code[I]; Inc(P); end; end; var I,FloatI,IntI,StackI,Offs : integer; OldProtect : dword; CodeSize : integer; UseStack : boolean; const MAP_JIT = $0800; begin CodeSize := 512; //Use fixed size so we don't have to save the size for unmap call Result := fpmmap(nil,CodeSize,PROT_READ or PROT_WRITE or PROT_EXEC,MAP_PRIVATE or MAP_ANONYMOUS{$IFDEF MACOS}or MAP_JIT{$ENDIF},-1,0); {$IFDEF MACOS} pthread_jit_write_protect_np(0); {$ENDIF} P := Result; if ArgCount>0 then //Copy Args-ptr to x8 W([$e8,$03,$00,$aa]); //mov x8,x0 Offs := 0; //Offset in Args FloatI := 0; IntI := 0; StackI := 0; for I := 0 to ArgCount-1 do begin UseStack := False; case TZcDataTypeKind(Ord(ArgTypes[I])-65) of zctInt : begin if IntI<IntRegCount then begin W(Int32Regs[IntI]); // modify the offset so it becomes "ldr w0, [x8,#offset]" P[-3] := P[-3] or Offs; Inc(IntI); end else UseStack := True; end; zctString,zctModel,zctXptr,zctMat4,zctVec2,zctVec3,zctVec4,zctArray : begin if IntI<IntRegCount then begin W(PtrRegs[IntI]); P[-3] := P[-3] or (Offs shr 1); Inc(IntI); end else UseStack := True; end; zctFloat : begin if FloatI<FloatRegCount then begin W(Float32Regs[FloatI]); P[-3] := P[-3] or Offs; Inc(FloatI); end else UseStack := True; end; else Assert(False,'This argument type not yet supported on 64-bit:'); end; if UseStack then begin //push on stack case GetZcTypeSize(TZcDataTypeKind(Ord(ArgTypes[I])-65)) of 4 : begin Assert(StackI<High(Int32Stack)); W(Int32Stack[StackI]); P[-7] := P[-7] or Offs; end; 8 : begin Assert(StackI<High(PtrStack)); W(PtrStack[StackI]); P[-7] := P[-7] or (Offs shr 1); end; else Assert(False,'This argument type not yet supported on 64-bit'); end; Inc(StackI); end; Inc(Offs, SizeOf(TExecutionEnvironment.TStackElement) ); end; W([$68,$00,$00,$10]); //adr x8,12 (PC relative offset to function pointer. 12 is the number of bytes in these three lines.) W([$08,$01,$40,$F9]); //ldr x8,[x8] W([$00,$01,$1f,$d6]); //br x8 // Store function pointer PPointer(P)^ := Proc; Inc(P,8); {$IFDEF MACOS} pthread_jit_write_protect_np(1); sys_icache_invalidate(Result,CodeSize); {$ENDIF} mprotect(Result,CodeSize,PROT_READ or PROT_WRITE or PROT_EXEC); end; procedure TExpExternalFuncCall.Execute(Env : PExecutionEnvironment); type TFunc = function(Args : pointer) : NativeUInt; TFloatFunc = function(Args : pointer) : single; var RetVal : NativeUInt; begin if Self.Entry=nil then begin Self.Entry := Lib.GetEntry(Self.FuncName); //Make sure there is enough stack space for calling a func with many params DummyProc(1,2,3,4,5,6,7,8,9,10,11,12); if Self.Entry.Trampoline = nil then Self.Entry.Trampoline := GenerateTrampoline(ArgCount,Self.ArgTypes,Self.Entry.Proc) {$ifndef minimal} Assert(Length(Self.ArgTypes)=ArgCount); {$endif} end; if Self.ReturnType.Kind=zctFloat then begin //Float returns in different register than other types PSingle(@RetVal)^ := TFloatFunc(Self.Entry.Trampoline)( Env.StackPopAndGetPtr(ArgCount) ); end else Retval := TFunc(Self.Entry.Trampoline)( Env.StackPopAndGetPtr(ArgCount) ); if Self.ReturnType.Kind<>zctVoid then begin if GetZcTypeSize(Self.ReturnType.Kind)=SizeOf(Pointer) then Env.StackPushPointer(RetVal) else Env.StackPush(RetVal); end; end; {$endif} { TExpLoadComponent } procedure TExpLoadComponent.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Component',{$ENDIF}(@Component), zptComponentRef); end; procedure TExpLoadComponent.Execute(Env : PExecutionEnvironment); begin Env.StackPushPointer(Self.Component); end; { TExpLoadPropOffset } procedure TExpLoadPropOffset.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'PropId',{$ENDIF}(@PropId), zptInteger); end; procedure TExpLoadPropOffset.Execute(Env : PExecutionEnvironment); var C : TZComponent; begin if not IsInit then begin Env.StackPopToPointer(C); {$ifdef CALLSTACK} Env.CheckNilDeref(C); {$endif} Self.Offset := C.GetProperties.GetById(Self.PropId).Offset; Env.StackPushPointer(C); IsInit := True; end; Env.StackPush(Self.Offset); end; { TExpLoadModelDefined } procedure TExpLoadModelDefined.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'DefinedIndex',{$ENDIF}(@DefinedIndex), zptInteger); {$ifndef minimal} List.AddProperty({$IFNDEF MINIMAL}'DefinedName',{$ENDIF}(@DefinedName), zptString); List.SetDesignerProperty; List.AddProperty({$IFNDEF MINIMAL}'ComponentRef',{$ENDIF}@ComponentRef, zptComponentRef); List.SetDesignerProperty; {$endif} end; procedure TExpLoadModelDefined.Execute(Env : PExecutionEnvironment); var M : TModel; C : TZComponent; begin Env.StackPopToPointer(M); {$ifndef minimal} if (Self.DefinedIndex>=M.Definitions.Count) or (not SameText(String(TZComponent(M.Definitions[Self.DefinedIndex]).Name),String(DefinedName))) then begin raise TModelDefinedException.Create('Defined var mismatch "' + DefinedName + '" in model "' + String(M.Name) + '" must be at position ' + IntToStr(Self.DefinedIndex) + ' in Definitions-list.'); end; {$endif} C := TZComponent(M.Definitions[Self.DefinedIndex]); Env.StackPushPointer( C ); end; { TExpAddToPointer } procedure TExpAddToPointer.Execute(Env : PExecutionEnvironment); //Add 32-bit value to pointer and store the result as pointer var V : integer; P : pbyte; begin Env.StackPopTo(V); Env.StackPopToPointer(P); Inc(P,V); Env.StackPushPointer(P); end; { TExpInvokeComponent } procedure TExpInvokeComponent.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'InvokeClassId',{$ENDIF}(@InvokeClassId), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'InvokeArgCount',{$ENDIF}(@InvokeArgCount), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'InvokedItemList',{$ENDIF}(@InvokedItemList), zptComponentList); List.GetLast.NeverPersist := True; List.AddProperty({$IFNDEF MINIMAL}'IsValue',{$ENDIF}(@IsValue), zptBoolean); end; procedure TExpInvokeComponent.Execute(Env : PExecutionEnvironment); var Ci : TZComponentInfo; I,PropId : integer; RawValue : nativeint; Prop : TZProperty; V : TZPropertyValue; begin if InvokeC=nil then begin Ci := ComponentManager.GetInfoFromId(TZClassIds(Self.InvokeClassId)); Self.InvokeC := Ci.ZClass.Create(Self.InvokedItemList); Self.InvokeC._ZApp := Self.ZApp; end; for I := 0 to InvokeArgCount-1 do begin Env.StackPopTo(PropId); {$if defined(CPUX64) or defined(cpuaarch64)} Env.StackPopToPointer(RawValue); {$else} Env.StackPopTo(RawValue); {$endif} Prop := InvokeC.GetProperties.GetById(PropId); case Prop.PropertyType of zptFloat: V.FloatValue := PFloat(@RawValue)^; zptInteger: V.IntegerValue := RawValue; zptByte: V.ByteValue := RawValue; zptBoolean: V.BooleanValue := ByteBool(RawValue); zptComponentRef : V.ComponentValue := TZComponent(RawValue); zptString : V.StringValue := PAnsiChar(RawValue); {$ifndef minimal} else Env.ScriptError(ClassName + ' invalid datatype for argument'); {$endif} end; Self.InvokeC.SetProperty(Prop,V); end; if IsValue then begin Env.StackPushPointer(Self.InvokeC); end else begin TCommand(InvokeC).Execute; end; end; { TExpInitArray } procedure TExpInitArray.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Dimensions',{$ENDIF}(@Dimensions), zptByte); List.AddProperty({$IFNDEF MINIMAL}'Type',{$ENDIF}(@_Type), zptByte); List.AddProperty({$IFNDEF MINIMAL}'Size1',{$ENDIF}(@Size1), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'Size2',{$ENDIF}(@Size2), zptInteger); List.AddProperty({$IFNDEF MINIMAL}'Size3',{$ENDIF}(@Size3), zptInteger); end; procedure TExpInitArray.Execute(Env : PExecutionEnvironment); var A : TDefineArray; begin //Use pointer size to get all bits in 64-bit mode A := TDefineArray.Create(nil); ManagedHeap_AddValueObject(A); A.Dimensions := Self.Dimensions; A._Type.Kind := Self._Type; A.SizeDim1 := Self.Size1; A.SizeDim2 := Self.Size2; A.SizeDim3 := Self.Size3; Env.StackPushPointer(A); end; { TExpMat4 } procedure TExpMat4FuncCall.Execute(Env : PExecutionEnvironment); var M1,M2 : PZMatrix4f; V1 : PZVector3f; I : integer; A : TDefineArray; X,Y,Z,W : single; begin case Kind of fcMatMultiply: begin Env.StackPopToPointer(M1); Env.StackPopToPointer(M2); A := TDefineArray(CreateManagedValue(zctMat4)); M1 := PZMatrix4f(TDefineArray(M1).GetData); M2 := PZMatrix4f(TDefineArray(M2).GetData); PZMatrix4f(A.GetData)^ := MatrixMultiply(M1^,M2^); Env.StackPushPointer(A); end; fcMatTransformPoint : begin Env.StackPopToPointer(V1); Env.StackPopToPointer(M1); A := TDefineArray(CreateManagedValue(zctVec3)); V1 := PZVector3f(TDefineArray(V1).GetData); M1 := PZMatrix4f(TDefineArray(M1).GetData); VectorTransform(V1^,M1^,PZVector3f(A.GetData)^); Env.StackPushPointer(A); end; fcGetMatrix : begin Env.StackPopToPointer(A); Env.StackPopTo(I); Self.ZApp.Driver.GetMatrix(I, PZMatrix4f(A.GetData)); end; fcSetMatrix : begin Env.StackPopToPointer(A); Env.StackPopTo(I); Self.ZApp.Driver.SetMatrix(I, PZMatrix4f(A.GetData)^); end; fcVec2 : begin Env.StackPopTo(Y); Env.StackPopTo(X); A := TDefineArray(CreateManagedValue(zctVec2)); PZVector2f(A.GetData)^ := Vector2f(X,Y); Env.StackPushPointer(A); end; fcVec3 : begin Env.StackPopTo(Z); Env.StackPopTo(Y); Env.StackPopTo(X); A := TDefineArray(CreateManagedValue(zctVec3)); PZVector3f(A.GetData)^ := Vector3f(X,Y,Z); Env.StackPushPointer(A); end; fcVec4 : begin Env.StackPopTo(W); Env.StackPopTo(Z); Env.StackPopTo(Y); Env.StackPopTo(X); A := TDefineArray(CreateManagedValue(zctVec4)); PColorf(A.GetData)^ := MakeColorf(X,Y,Z,W); Env.StackPushPointer(A); end; end; end; { TExpIDEFuncCall } {$ifndef minimal} procedure TExpIDEFuncCall.Execute(Env : PExecutionEnvironment); var P1,P2,P3 : pointer; C : TZComponent; Ci : TZComponentInfo; Prop : TZProperty; Value : TZPropertyValue; V : single; I : integer; Stream : TMemoryStream; TmpS : ansistring; Dest : PAnsiChar; begin case Kind of fcFindComponent : begin Env.StackPopToPointer(P1); P2 := ZApp.Symtab.Lookup(String(PAnsiChar(P1))); Env.StackPushPointer(P2); end; fcCreateComponent : begin Env.StackPopToPointer(P1); //compname Env.StackPopToPointer(P2); //proplistname Env.StackPopToPointer(P3); //owner Ci := ZClasses.ComponentManager.GetInfoFromName(String(PAnsiChar(P1))); if (P2=nil) or (P3=nil) then begin C := Ci.ZClass.Create( nil ); //No owner, add to GC ZClasses.ManagedHeap_AddValueObject(C); end else begin Prop := TZComponent(P3).GetProperties.GetByName( String(PAnsiChar(P2)) ); if (Prop=nil) or (Prop.PropertyType<>zptComponentList) then Env.ScriptError('CreateComponent called with invalid proplistname: ' + String(PAnsiChar(P2))); C := Ci.ZClass.Create( TZComponent(P3).GetProperty(Prop).ComponentListValue ); C.ZApp.HasScriptCreatedComponents := True; end; Env.StackPushPointer(C); ZLog.GetLog('Zc').Write('Creating component: ' + Ci.ZClassName,lleNormal); end; fcSetNumericProperty : begin //XSIF V := Env.StackPopFloat; //value Env.StackPopTo(I); //index Env.StackPopToPointer(P2); //propname Env.StackPopToPointer(P1); //comp Prop := TZComponent(P1).GetProperties.GetByName( String(PAnsiChar(P2)) ); if Prop=nil then Env.ScriptError('SetNumericProperty called with invalid propname: ' + String(PAnsiChar(P2))); Value := TZComponent(P1).GetProperty(Prop); //Must read prop first, when modifying rects case Prop.PropertyType of zptFloat,zptScalar: Value.FloatValue := V; zptRectf: Value.RectfValue.Area[I] := V; zptColorf: Value.ColorfValue.V[I] := V; zptInteger: Value.IntegerValue := Round(V); zptVector3f: Value.Vector3fValue[I] := V; zptByte: Value.ByteValue := Round(V); zptBoolean: Value.BooleanValue := ByteBool(Round(V)); else Env.ScriptError('SetNumericProperty called with prop of unsupported type: ' + String(PAnsiChar(P2))); end; TZComponent(P1).SetProperty(Prop,Value); end; fcSetStringProperty : begin //XSS Env.StackPopToPointer(P3); //value Env.StackPopToPointer(P2); //propname Env.StackPopToPointer(P1); //comp Prop := TZComponent(P1).GetProperties.GetByName( String(PAnsiChar(P2)) ); if Prop=nil then Env.ScriptError('SetStringProperty called with invalid propname: ' + String(PAnsiChar(P2))); case Prop.PropertyType of zptString : Value.StringValue := AnsiString(PAnsiChar(P3)); zptExpression : Value.ExpressionValue.Source := String(PAnsiChar(P3)); else Env.ScriptError('SetStringProperty called with prop of unsupported type: ' + String(PAnsiChar(P2))); end; if (Prop.Name='Name') then begin if Assigned(ZApp.SymTab.Lookup(String(PAnsiChar(P3)))) then Env.ScriptError('SetStringProperty tried to set duplicate name: ' + String(PAnsiChar(P3))); ZApp.SymTab.Add(String(PAnsiChar(P3)),TZComponent(P1)); end; TZComponent(P1).SetProperty(Prop,Value); //If we set an expression, then compile this now so it will execute in same run. if Prop.PropertyType=zptExpression then Self.ZApp.CompileProperty(TZComponent(P1),TZComponent(P1).GetProperty(Prop),Prop); end; fcSetObjectProperty : begin Env.StackPopToPointer(P3); //value Env.StackPopToPointer(P2); //propname Env.StackPopToPointer(P1); //comp Prop := TZComponent(P1).GetProperties.GetByName( String(PAnsiChar(P2)) ); if Prop=nil then Env.ScriptError('SetObjectProperty called with invalid propname: ' + String(PAnsiChar(P2))); case Prop.PropertyType of zptComponentRef : Value.ComponentValue := P3; else Env.ScriptError('SetObjectProperty called with prop of unsupported type: ' + String(PAnsiChar(P2))); end; TZComponent(P1).SetProperty(Prop,Value); end; fcSaveComponentToTextFile: begin Env.StackPopToPointer(P2); //filename Env.StackPopToPointer(P1); //comp Stream := ComponentManager.SaveXmlToStream(TZComponent(P1)) as TMemoryStream; Stream.SaveToFile( String(PAnsiChar(P2)) ); Stream.Free; end; fcGetStringProperty : begin Env.StackPopToPointer(P2); //propname Env.StackPopToPointer(P1); //comp Prop := TZComponent(P1).GetProperties.GetByName( String(PAnsiChar(P2)) ); if Prop=nil then Env.ScriptError('GetStringProperty called with invalid propname: ' + String(PAnsiChar(P2))); Value := TZComponent(P1).GetProperty(Prop); case Prop.PropertyType of zptString : TmpS := Value.StringValue; zptExpression : TmpS := AnsiString(Value.ExpressionValue.Source); else Env.ScriptError('GetStringProperty called with prop of unsupported type: ' + String(PAnsiChar(P2))); end; Dest := ManagedHeap_Alloc(Length(TmpS)+1); ZStrCopy(Dest,PAnsiChar(TmpS)); Env.StackPushPointer(Dest); end; end; end; {$endif} { TExpGetRawMemElement } procedure TExpGetRawMemElement.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Type',{$ENDIF}(@_Type), zptByte); end; procedure TExpGetRawMemElement.Execute(Env : PExecutionEnvironment); var I3,I2,Index : integer; P : PBytes; begin Env.StackPopToPointer(P); case Self._Type of zctMat4: begin Env.StackPopTo(I3); Env.StackPopTo(I2); Index := (I2*4) + I3; end; zctVec2..zctVec4: begin Env.StackPopTo(I3); Index := I3; end; else Index := 0; end; P := @P^[Index * 4]; Env.StackPushPointer(P); end; { TExpArrayUtil } procedure TExpArrayUtil.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'Kind',{$ENDIF}(@Kind), zptByte); List.AddProperty({$IFNDEF MINIMAL}'Type',{$ENDIF}(@_Type), zptByte); end; procedure TExpArrayUtil.Execute(Env : PExecutionEnvironment); var A,A2 : TDefineArray; P : pointer; begin case Kind of auArrayToRawMem: begin Env.StackPopToPointer(A); Env.StackPopToPointer(P); Move(A.GetData^, P^, A.GetElementSize * A.CalcLimit); end; auRawMemToArray: begin Env.StackPopToPointer(P); A := TDefineArray(CreateManagedValue(Self._Type)); Move(P^, A.GetData^, A.GetElementSize * A.CalcLimit); Env.StackPushPointer(A); end; auArrayToArray: //Copy from one array into the memory of another begin Env.StackPopToPointer(A); Env.StackPopToPointer(A2); Move(A2.GetData^, A.GetData^, A.GetElementSize * A.CalcLimit); end; end; end; { TExpSwitchTable } procedure TExpSwitchTable.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'LowBound',{$ENDIF}@LowBound, zptInteger); List.AddProperty({$IFNDEF MINIMAL}'HighBound',{$ENDIF}@HighBound, zptInteger); List.AddProperty({$IFNDEF MINIMAL}'DefaultOrExit',{$ENDIF}@DefaultOrExit, zptInteger); List.AddProperty({$IFNDEF MINIMAL}'Jumps',{$ENDIF}@Jumps, zptBinary); end; procedure TExpSwitchTable.Execute(Env: PExecutionEnvironment); var V,Destination : integer; begin Env.StackPopTo(V); if (V<LowBound) or (V>HighBound) then Destination := Self.DefaultOrExit else begin Dec(V,LowBound); Destination := PIntegerArray(Self.Jumps.Data)^[V]; end; Inc(Env.gCurrentPc,Destination); end; { TExpNewClassInstance } procedure TExpNewClassInstance.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'TheClass',{$ENDIF}@TheClass, zptComponentRef); end; procedure TExpNewClassInstance.Execute(Env: PExecutionEnvironment); var P : TUserClassInstance; Cls : TUserClass; begin Cls := Self.TheClass; P := TUserClassInstance.Create(Cls); ManagedHeap_AddValueObject(P); Env.StackPushPointer(P); //todo: call initializer not here but generate code in constructor instead if Cls.InitializerIndex<>-1 then begin //Call initializer Env.StackPushPointer(P); //push "this" as argument to initializer Env.StackPushPointer(Env.gCurrentPC); Env.gCurrentPC := Cls.DefinedInLib.Source.Code.GetPtrToItem(Cls.InitializerIndex); Dec(Env.gCurrentPc); end; end; { TUserClassInstance } constructor TUserClassInstance.Create(TheClass: TUserClass); var I : integer; P : pointer; Offsets : PInteger; Mp : PPointer; begin Self.TheClass := TheClass; GetMem(Self.InstanceData,TheClass.SizeInBytes); FillChar(Self.InstanceData^,TheClass.SizeInBytes,0); ManagedCount := (TheClass.ManagedFields.Size div 4); if ManagedCount>0 then begin //Copy pointers to owned memory to avoid dangling pointer to UserClass GetMem(ManagedCleanup,ManagedCount*SizeOf(Pointer)); //Add targets for managed fields Offsets := PInteger(TheClass.ManagedFields.Data); Mp := ManagedCleanup; for I := 0 to ManagedCount-1 do begin P := Pointer(IntPtr(Self.InstanceData) + Offsets^); ManagedHeap_AddTarget( P ); Mp^ := P; Inc(Mp); Inc(Offsets); end; end; end; destructor TUserClassInstance.Destroy; var I : integer; Mp : PPointer; begin //Remove targets for managed fields if Self.ManagedCount>0 then begin Mp := ManagedCleanup; for I := 0 to Self.ManagedCount-1 do begin ManagedHeap_RemoveTarget( Mp^ ); Inc(Mp); end; FreeMem(ManagedCleanup); end; FreeMem(InstanceData); inherited; end; { TUserClass } procedure TUserClass.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'SizeInBytes',{$ENDIF}@SizeInBytes, zptInteger); List.AddProperty({$IFNDEF MINIMAL}'ManagedFields',{$ENDIF}@ManagedFields, zptBinary); List.AddProperty({$IFNDEF MINIMAL}'BaseClass',{$ENDIF}@BaseClass, zptComponentRef); List.AddProperty({$IFNDEF MINIMAL}'Vmt',{$ENDIF}@Vmt, zptBinary); List.AddProperty({$IFNDEF MINIMAL}'DefinedInLib',{$ENDIF}@DefinedInLib, zptComponentRef); List.AddProperty({$IFNDEF MINIMAL}'InitializerIndex',{$ENDIF}@InitializerIndex, zptInteger); end; { TExpVirtualFuncCall } procedure TExpVirtualFuncCall.DefineProperties(List: TZPropertyList); begin inherited; List.AddProperty({$IFNDEF MINIMAL}'VmtIndex',{$ENDIF}@VmtIndex, zptInteger); end; procedure TExpVirtualFuncCall.Execute(Env: PExecutionEnvironment); procedure InCheck(C : TUserClass); var Pc : integer; begin Pc := PIntegerArray(C.Vmt.Data)^[ Self.VmtIndex ]; if Pc<>-1 then begin Env.gCurrentPC := C.DefinedInLib.Source.Code.GetPtrToItem(Pc-1); Exit; end; {$ifdef debug} Assert(Assigned(C.BaseClass),'virtual method error'); {$endif} InCheck(C.BaseClass); end; var P : TUserClassInstance; begin Env.StackPopToPointer(P); Env.StackPushPointer(Env.gCurrentPC); InCheck(P.TheClass); end; initialization ZClasses.Register(TZExpression,ZExpressionClassId); {$ifndef minimal}ComponentManager.LastAdded.ImageIndex:=2;{$endif} ZClasses.Register(TZLibrary,ZLibraryClassId); {$ifndef minimal}ComponentManager.LastAdded.ImageIndex:=36;{$endif} ZClasses.Register(TDefineVariable,DefineVariableClassId); {$ifndef minimal}ComponentManager.LastAdded.ImageIndex:=8;{$endif} {$ifndef minimal}ComponentManager.LastAdded.ZClassName := 'Variable';{$endif} {$ifndef minimal}ComponentManager.LastAdded.AutoName := True;{$endif} ZClasses.Register(TDefineConstant,DefineConstantClassId); {$ifndef minimal}ComponentManager.LastAdded.ImageIndex:=29;{$endif} {$ifndef minimal}ComponentManager.LastAdded.ZClassName := 'Constant';{$endif} ZClasses.Register(TDefineArray,DefineArrayClassId); {$ifndef minimal}ComponentManager.LastAdded.ImageIndex:=22;{$endif} {$ifndef minimal}ComponentManager.LastAdded.ZClassName := 'Array';{$endif} {$ifndef minimal}ComponentManager.LastAdded.AutoName := True;{$endif} ZClasses.Register(TZExternalLibrary,ExternalLibraryClassId); {$ifndef minimal}ComponentManager.LastAdded.ImageIndex:=35;{$endif} ZClasses.Register(TExpConstantFloat,ExpConstantFloatClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpConstantInt,ExpConstantIntClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpOpBinaryFloat,ExpOpBinaryFloatClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpOpBinaryInt,ExpOpBinaryIntClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpJump,ExpJumpClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpFuncCall,ExpFuncCallClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpExternalFuncCall,ExpExternalFuncCallClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpArrayGetElement,ExpArrayWriteClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpStackFrame,ExpStackFrameClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpAccessLocal,ExpAccessLocalClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpReturn,ExpReturnClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpMisc,ExpMiscClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpUserFuncCall,ExpUserFuncCallClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpConvert,ExpConvertClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpAssign4,ExpAssign4ClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpAssign1,ExpAssign1ClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpAssignPointer,ExpAssignPointerClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpStringConstant,ExpStringConstantClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpStringConCat,ExpStringConCatClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpPointerFuncCall,ExpPointerFuncCallClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpLoadComponent,ExpLoadComponentClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpLoadPropOffset,ExpLoadPropOffsetClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpLoadModelDefined,ExpLoadModelDefinedClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpAddToPointer,ExpAddToPointerClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpInvokeComponent,ExpInvokeComponentClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpInitArray,ExpInitLocalArrayClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpMat4FuncCall,ExpMat4FuncCallClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpGetRawMemElement,ExpGetRawMemElementClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpArrayUtil,ExpArrayUtilClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpSwitchTable,ExpSwitchTableClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpAccessGlobal,ExpAccessGlobalClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TUserClass,UserClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpNewClassInstance,ExpNewClassInstanceId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} ZClasses.Register(TExpVirtualFuncCall,ExpVirtualFuncCallClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} {$ifndef minimal} ZClasses.Register(TExpIDEFuncCall,ExpIDEFuncCallClassId); {$ifndef minimal}ComponentManager.LastAdded.NoUserCreate:=True;{$endif} {$endif} end.
0
0.945433
1
0.945433
game-dev
MEDIA
0.305576
game-dev
0.92101
1
0.92101
StranikS-Scan/WorldOfTanks-Decompiled
2,550
source/res/battle_modifiers/scripts/common/battle_modifiers_ext/remappings_cache.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: battle_modifiers/scripts/common/battle_modifiers_ext/remappings_cache.py from typing import Any, Dict, TYPE_CHECKING, Optional from battle_modifiers_ext.constants_ext import REMAPPING_XML_PATH, RemappingNames from remapping.remapping_readers import ERR_TEMPLATE, readComposers, readConditions from extension_utils import ResMgr from ResMgr import DataSection from soft_exception import SoftException _ERR_TEMPLATE = "[Remapping] {} for remapping '{}'" if TYPE_CHECKING: from battle_modifiers_common import ModifiersContext from battle_modifiers_ext.remapping.remapping_composers import IComposer g_cache = None class RemappingCache(object): __slots__ = ('__remapping',) def __init__(self): self.__readConfig() def __repr__(self): return 'RemappingCache({})'.format(self.__remapping) def getValue(self, modifierName, remappingName, oldValue, ctx): composer = self.__remapping.get(remappingName, {}).get(modifierName) return composer.getValue(ctx, oldValue) if composer is not None else None def getValues(self, modifierName, remappingName, oldValue): composer = self.__remapping.get(remappingName, {}).get(modifierName) return composer.getValues(oldValue) if composer is not None else None def __readConfig(self): config = ResMgr.openSection(REMAPPING_XML_PATH) if config is None: raise SoftException("[Remapping] Cannot open or read '{}'".format(REMAPPING_XML_PATH)) self.__remapping = {} for remappingName, remappingSection in config.items(): if remappingName == 'xmlns:xmlref': continue if remappingName not in RemappingNames.ALL: raise SoftException("[Remapping] Invalid remapping name '{}'".format(remappingName)) self.__remapping[remappingName] = self.__readRemappingSection(remappingSection) return def __readRemappingSection(self, config): remappingName = config.name if not config.has_key('conditions'): raise SoftException(ERR_TEMPLATE.format('Missing conditions', remappingName)) conditions = readConditions(config['conditions'], remappingName) if not config.has_key('composers'): raise SoftException(ERR_TEMPLATE.format('Missing composers', remappingName)) return readComposers(config['composers'], remappingName, conditions) def init(): global g_cache g_cache = RemappingCache()
0
0.863436
1
0.863436
game-dev
MEDIA
0.357303
game-dev
0.800323
1
0.800323
ProjectIgnis/CardScripts
1,457
official/c78636495.lua
--ニュート --Slate Warrior local s,id=GetID() function s.initial_effect(c) --flip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP) e1:SetOperation(s.operation) c:RegisterEffect(e1) --destroyed local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_BATTLE_DESTROYED) e2:SetOperation(s.desop) c:RegisterEffect(e2) end function s.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT|RESETS_STANDARD) e1:SetValue(500) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENSE) c:RegisterEffect(e2) end function s.desop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetAttacker() if c==tc then tc=Duel.GetAttackTarget() end if not tc:IsRelateToBattle() then return end local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT|RESETS_STANDARD) e1:SetValue(-500) tc:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENSE) tc:RegisterEffect(e2) end
0
0.876402
1
0.876402
game-dev
MEDIA
0.967143
game-dev
0.79671
1
0.79671
LibraStack/Match3-SDK
2,006
src/Match3.Infrastructure/SequenceDetectors/LineDetector.cs
using System.Collections.Generic; using Match3.App; using Match3.App.Interfaces; using Match3.Core.Interfaces; using Match3.Core.Structs; namespace Match3.Infrastructure.SequenceDetectors { public abstract class LineDetector<TGridSlot> : ISequenceDetector<TGridSlot> where TGridSlot : IGridSlot { public abstract ItemSequence<TGridSlot> GetSequence(IGameBoard<TGridSlot> gameBoard, GridPosition gridPosition); protected ItemSequence<TGridSlot> GetSequenceByDirection(IGameBoard<TGridSlot> gameBoard, GridPosition gridPosition, IEnumerable<GridPosition> directions) { var gridSlot = gameBoard[gridPosition]; var gridSlots = new List<TGridSlot>(); foreach (var direction in directions) { gridSlots.AddRange(GetSequenceOfGridSlots(gameBoard, gridSlot, gridPosition, direction)); } if (gridSlots.Count < 2) { return null; } gridSlots.Add(gridSlot); return new ItemSequence<TGridSlot>(GetType(), gridSlots); } private IEnumerable<TGridSlot> GetSequenceOfGridSlots(IGameBoard<TGridSlot> gameBoard, TGridSlot gridSlot, GridPosition gridPosition, GridPosition direction) { var newPosition = gridPosition + direction; var slotsSequence = new List<TGridSlot>(); while (gameBoard.IsPositionOnBoard(newPosition)) { var currentSlot = gameBoard[newPosition]; if (currentSlot.HasItem == false) { break; } if (currentSlot.ItemId == gridSlot.ItemId) { newPosition += direction; slotsSequence.Add(currentSlot); } else { break; } } return slotsSequence; } } }
0
0.777104
1
0.777104
game-dev
MEDIA
0.812181
game-dev
0.685861
1
0.685861
ProjectIgnis/CardScripts
1,646
rush/c160012052.lua
--蒼救の祈り --Skysavior Prayer --scripted by YoshiDuels local s,id=GetID() function s.initial_effect(c) --Special Summon 1 LIGHT/DARK Celestial Warrior monster from the GY local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,e:GetHandler()) end end function s.filter(c,e,tp) return c:IsRace(RACE_CELESTIALWARRIOR) and c:IsAttribute(ATTRIBUTE_LIGHT|ATTRIBUTE_DARK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE) end function s.activate(e,tp,eg,ep,ev,re,r,rp) --Requirement Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,1,e:GetHandler()) --Effect if Duel.SendtoGrave(g,REASON_COST)>0 then if Duel.GetLocationCount(tp,LOCATION_MZONE)==0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tc=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(s.filter),tp,LOCATION_GRAVE,0,1,1,nil,e,tp):GetFirst() if tc then Duel.HintSelection(tc,true) Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end end
0
0.952177
1
0.952177
game-dev
MEDIA
0.992557
game-dev
0.942208
1
0.942208
BigheadSMZ/Zelda-LA-DX-HD-Updated
3,445
ladxhd_game_source_code/InGame/GameObjects/Things/ObjLeverStone.cs
using System.Collections.Generic; using Microsoft.Xna.Framework; using ProjectZ.InGame.GameObjects.Base; using ProjectZ.InGame.GameObjects.Base.CObjects; using ProjectZ.InGame.GameObjects.Base.Components; using ProjectZ.InGame.GameObjects.Base.Systems; using ProjectZ.InGame.Things; namespace ProjectZ.InGame.GameObjects.Things { internal class ObjLeverStone : GameObject { private readonly List<GameObject> _collidingObjects = new List<GameObject>(); private readonly CBox _box; private readonly Vector2 _startPosition; private readonly Vector2 _endPosition; private readonly int _direction; public ObjLeverStone() : base("movestone_0") { } public ObjLeverStone(Map.Map map, int posX, int posY, int direction) : base(map) { EntityPosition = new CPosition(posX, posY, 0); EntitySize = new Rectangle(0, 0, 16, 16); _direction = direction; _startPosition = new Vector2(posX, posY); _endPosition = new Vector2(posX, posY) + AnimationHelper.DirectionOffset[direction] * 16; _box = new CBox(EntityPosition, 0, 0, 0, 16, 16, 8); // does not deal damage in the real game var damageBox = new CBox(EntityPosition, 1, 1, 0, 14, 14, 8); AddComponent(DamageFieldComponent.Index, new DamageFieldComponent(damageBox, HitType.Object, 2)); AddComponent(CollisionComponent.Index, new BoxCollisionComponent(_box, Values.CollisionTypes.Normal)); AddComponent(UpdateComponent.Index, new UpdateComponent(Update)); AddComponent(DrawComponent.Index, new DrawSpriteComponent("movestone_0", EntityPosition, Vector2.Zero, Values.LayerBottom)); } private void Update() { UpdatePosition(ObjPullLever.LeverState); } private void UpdatePosition(float amount) { var lastBox = _box.Box; EntityPosition.Set(Vector2.Lerp(_startPosition, _endPosition, amount)); // @HACK: this kind of stuff should be inside the movement system // check for colliding bodies and push them forward _collidingObjects.Clear(); Map.Objects.GetComponentList(_collidingObjects, (int)EntityPosition.Position.X - 1, (int)EntityPosition.Position.Y - 1, 18, 18, BodyComponent.Mask); foreach (var collidingObject in _collidingObjects) { var body = (BodyComponent)collidingObject.Components[BodyComponent.Index]; if (body.BodyBox.Box.Intersects(_box.Box) && !body.BodyBox.Box.Intersects(lastBox)) { var offset = Vector2.Zero; if (_direction == 2) offset.X = _box.Box.Left - body.BodyBox.Box.Right - 0.05f; else if (_direction == 0) offset.X = _box.Box.Right - body.BodyBox.Box.Left + 0.05f; else if (_direction == 3) offset.Y = _box.Box.Back - body.BodyBox.Box.Front - 0.05f; else if (_direction == 1) offset.Y = _box.Box.Front - body.BodyBox.Box.Back + 0.05f; SystemBody.MoveBody(body, offset, body.CollisionTypes, false, false, false); body.Position.NotifyListeners(); } } } } }
0
0.794819
1
0.794819
game-dev
MEDIA
0.864521
game-dev
0.956053
1
0.956053
blendogames/SkinDeep
10,171
d3xp/bc_vrvisor.cpp
#include "sys/platform.h" #include "gamesys/SysCvar.h" #include "Entity.h" #include "Light.h" #include "Player.h" #include "Fx.h" #include "ai/AI.h" #include "bc_vrvisor.h" CLASS_DECLARATION(idMoveableItem, idVRVisor) END_CLASS #define VISOR_MOVETIME 600 #define VISOR_MOVEPAUSETIME 150 #define VISOR_MOVINGTOEYES_TIME 300 #define VISOR_RETURNTIME 500 #define VISOR_FORWARDDIST 8 idVRVisor::idVRVisor(void) { state = VRV_IDLE; stateTimer = 0; visorStartPosition = vec3_zero; visorStartAngle = idAngles(0, 0, 0); visorFinalPosition = vec3_zero; visorFinalAngle = idAngles(0, 0, 0); playerStartPosition = vec3_zero; playerStartAngle = 0; arrowProp = NULL; } idVRVisor::~idVRVisor(void) { } void idVRVisor::Save(idSaveGame* savefile) const { savefile->WriteInt( state ); // int state savefile->WriteInt( stateTimer ); // int stateTimer savefile->WriteVec3( visorStartPosition ); // idVec3 visorStartPosition savefile->WriteAngles( visorStartAngle ); // idAngles visorStartAngle savefile->WriteVec3( visorFinalPosition ); // idVec3 visorFinalPosition savefile->WriteAngles( visorFinalAngle ); // idAngles visorFinalAngle savefile->WriteVec3( playerStartPosition ); // idVec3 playerStartPosition savefile->WriteFloat( playerStartAngle ); // float playerStartAngle savefile->WriteObject( arrowProp ); // idEntity* arrowProp } void idVRVisor::Restore(idRestoreGame* savefile) { savefile->ReadInt( state ); // int state savefile->ReadInt( stateTimer ); // int stateTimer savefile->ReadVec3( visorStartPosition ); // idVec3 visorStartPosition savefile->ReadAngles( visorStartAngle ); // idAngles visorStartAngle savefile->ReadVec3( visorFinalPosition ); // idVec3 visorFinalPosition savefile->ReadAngles( visorFinalAngle ); // idAngles visorFinalAngle savefile->ReadVec3( playerStartPosition ); // idVec3 playerStartPosition savefile->ReadFloat( playerStartAngle ); // float playerStartAngle savefile->ReadObject( arrowProp ); // idEntity* arrowProp } void idVRVisor::Spawn(void) { isFrobbable = true; BecomeActive(TH_THINK); fl.takedamage = false; if (spawnArgs.GetBool("showarrow", "1")) { idDict args; args.Set("classname", "func_static"); args.Set("model", spawnArgs.GetString("model_arrow")); args.SetBool("spin", true); args.Set("bind", GetName()); args.SetVector("origin", GetPhysics()->GetOrigin() + idVec3(0,0,3)); args.SetBool("solid", false); gameLocal.SpawnEntityDef(args, &arrowProp); } PostEventMS(&EV_PostSpawn, 0); } void idVRVisor::Event_PostSpawn(void) { //This does not work for some reason?????? //if (targets.Num() <= 0) //{ // int zz = targets.Num(); // gameLocal.Error("visor '%s' has no targets.", GetName(), zz); //} } void idVRVisor::Think(void) { if (state == VRV_IDLE) { idMoveableItem::Think(); } else if (state == VRV_MOVINGTOPLAYER) { Present(); //Get visor final position. idAngles playerViewAngle = gameLocal.GetLocalPlayer()->viewAngles; playerViewAngle.pitch = 0; playerViewAngle.roll = 0; idVec3 playerEyePos = gameLocal.GetLocalPlayer()->firstPersonViewOrigin; visorFinalPosition = playerEyePos + playerViewAngle.ToForward() * VISOR_FORWARDDIST; visorFinalPosition.z += .1f; //Get visor final angle. visorFinalAngle = idAngles(0, gameLocal.GetLocalPlayer()->viewAngles.yaw, 0);; visorFinalAngle.pitch = 0; visorFinalAngle.yaw += 180; visorFinalAngle.roll = 0; visorFinalAngle.Normalize180(); float lerp = (gameLocal.time - stateTimer) / (float)VISOR_MOVETIME; lerp = idMath::ClampFloat(0, 1, lerp); lerp = idMath::CubicEaseOut(lerp); //Lerp visor position. idVec3 visorLerpedPosition; visorLerpedPosition.Lerp(visorStartPosition, visorFinalPosition, lerp); SetOrigin(visorLerpedPosition); //Lerp visor angle. idAngles visorLerpedAngle; visorLerpedAngle.pitch = idMath::Lerp(visorStartAngle.pitch, visorFinalAngle.pitch, lerp); visorLerpedAngle.yaw = idMath::Lerp(visorStartAngle.yaw, visorFinalAngle.yaw, lerp); visorLerpedAngle.roll = idMath::Lerp(visorStartAngle.roll, visorFinalAngle.roll, lerp); SetAxis(visorLerpedAngle.ToMat3()); if (gameLocal.time > stateTimer + VISOR_MOVETIME) { state = VRV_MOVEPAUSE; stateTimer = gameLocal.time; } } else if (state == VRV_MOVEPAUSE) { if (gameLocal.time > stateTimer + VISOR_MOVEPAUSETIME) { state = VRV_MOVINGTOEYES; stateTimer = gameLocal.time; gameLocal.GetLocalPlayer()->Event_SetFOVLerp(-80, VISOR_MOVINGTOEYES_TIME); StartSound("snd_enter", SND_CHANNEL_ANY); } } else if (state == VRV_MOVINGTOEYES) { if (gameLocal.time > stateTimer + VISOR_MOVINGTOEYES_TIME) { state = VRV_ATTACHEDTOPLAYER; gameLocal.GetLocalPlayer()->Event_setPlayerFrozen(0); if (targets.Num() > 0) { gameLocal.GetLocalPlayer()->FlashScreenCustom(idVec4(0, .6f, .8f, 1), 600); gameLocal.GetLocalPlayer()->Event_SetFOVLerp(40, 0); gameLocal.GetLocalPlayer()->Event_SetFOVLerp(0, 500); gameLocal.GetLocalPlayer()->Event_TeleportToEnt(targets[0].GetEntity()); //Call the script to start the sequence. idStr startScript = spawnArgs.GetString("call_start"); if (startScript.Length() > 0) { if (!gameLocal.RunMapScriptArgs(startScript.c_str(), this, this)) { gameLocal.Warning("visor '%s' failed to run script '%s'", GetName(), startScript.c_str()); } } } else { gameLocal.Error("visor '%s' has no targets.", GetName()); } } } else if (state == VRV_RETURNINGTOSTARTPOSITION) { Present(); float lerp = (gameLocal.time - stateTimer) / (float)VISOR_RETURNTIME; lerp = idMath::ClampFloat(0, 1, lerp); //Lerp visor position. idVec3 visorLerpedPosition; visorLerpedPosition.Lerp(visorFinalPosition, visorStartPosition, lerp); SetOrigin(visorLerpedPosition); //Lerp visor angle. idAngles visorLerpedAngle; visorLerpedAngle.pitch = idMath::Lerp( visorFinalAngle.pitch, visorStartAngle.pitch, lerp); visorLerpedAngle.yaw = idMath::Lerp( visorFinalAngle.yaw, visorStartAngle.yaw, lerp); visorLerpedAngle.roll = idMath::Lerp(visorFinalAngle.roll, visorStartAngle.roll, lerp); SetAxis(visorLerpedAngle.ToMat3()); if (gameLocal.time > stateTimer + VISOR_RETURNTIME) { state = VRV_IDLE; //isFrobbable = true; //bc 11-12-2024 just make the vr visor be a one-use only item. } } } bool idVRVisor::DoFrob(int index, idEntity * frobber) { //idMoveableItem::DoFrob(index, frobber); if (frobber == NULL) return false; if (frobber != gameLocal.GetLocalPlayer()) return false; if (state == VRV_IDLE) { if (arrowProp != nullptr) { arrowProp->Hide(); } gameLocal.GetLocalPlayer()->Event_setPlayerFrozen(1); gameLocal.GetLocalPlayer()->SetViewPitchLerp(0, VISOR_MOVETIME+ VISOR_MOVINGTOEYES_TIME + VISOR_MOVEPAUSETIME); gameLocal.GetLocalPlayer()->SetViewYawLerp(gameLocal.GetLocalPlayer()->viewAngles.yaw, VISOR_MOVETIME + VISOR_MOVINGTOEYES_TIME + VISOR_MOVEPAUSETIME); state = VRV_MOVINGTOPLAYER; stateTimer = gameLocal.time; visorStartPosition = GetPhysics()->GetOrigin(); visorStartAngle = GetPhysics()->GetAxis().ToAngles(); isFrobbable = false; //BC 6-11-2025: fix issue where player can go out of bounds by exiting a clambered/crouch space while interacting with vr visor (sd-654) playerStartPosition = GetSafeStartPosition(); playerStartAngle = gameLocal.GetLocalPlayer()->viewAngles.yaw; //Get visor final position. idAngles playerViewAngle = gameLocal.GetLocalPlayer()->viewAngles; playerViewAngle.pitch = 0; playerViewAngle.roll = 0; idVec3 playerEyePos = gameLocal.GetLocalPlayer()->firstPersonViewOrigin; visorFinalPosition = playerEyePos + playerViewAngle.ToForward() * VISOR_FORWARDDIST; visorFinalPosition.z += .1f; //Get visor final angle. visorFinalAngle = idAngles(0, gameLocal.GetLocalPlayer()->viewAngles.yaw, 0);; visorFinalAngle.pitch = 0; visorFinalAngle.yaw += 180; visorFinalAngle.roll = 0; visorFinalAngle.Normalize180(); StartSound("snd_grab", SND_CHANNEL_ANY); } return true; } //BC 6-11-2025: fix issue where player can go out of bounds by exiting a clambered/crouch space while interacting with vr visor (sd-654) idVec3 idVRVisor::GetSafeStartPosition() { //See if player is already standing on solid ground. idVec3 candidateStartPosition = gameLocal.GetLocalPlayer()->GetPhysics()->GetOrigin(); trace_t tr; gameLocal.clip.TracePoint(tr, candidateStartPosition + idVec3(0, 0, 1), candidateStartPosition + idVec3(0, 0, -16), MASK_SOLID, NULL); if (tr.fraction < 1) { return candidateStartPosition; //player is on ground. } //Player is NOT on ground. Find the ground. gameLocal.clip.TracePoint(tr, candidateStartPosition + idVec3(0, 0, 1), candidateStartPosition + idVec3(0, 0, -128), MASK_SOLID, NULL); candidateStartPosition = tr.endpos + idVec3(0, 0, .1f); //Get player standing bounding box idBounds playerbounds = gameLocal.GetLocalPlayer()->GetPhysics()->GetBounds(); playerbounds[1].z = pm_normalheight.GetFloat(); //Get standing height. #define CANDIDATEOFFSETCOUNT 9 idVec3 candidateOffsets[] = { idVec3(0, 0, 0), idVec3(0, -16, 0), idVec3(0, -32, 0), idVec3(-16, 0, 0), idVec3(-32, 0, 0), idVec3(0, 16, 0), idVec3(0, 32, 0), idVec3(16, 0, 0), idVec3(32, 0, 0), }; //do bounds check. for (int i = 0; i < CANDIDATEOFFSETCOUNT; i++) { trace_t standingTr; idVec3 adjustedPos = candidateStartPosition + candidateOffsets[i]; gameLocal.clip.TraceBounds(standingTr, adjustedPos, adjustedPos, playerbounds, MASK_SOLID, NULL); if (standingTr.fraction >= 1) { return adjustedPos; } } //Couldn't find a clear spot, so just return the original position on the ground. return candidateStartPosition; } //If this visor is active, then deactivate it and return player to the hub. bool idVRVisor::SetExitVisor() { if (state != VRV_ATTACHEDTOPLAYER) return false; state = VRV_RETURNINGTOSTARTPOSITION; stateTimer = gameLocal.time; gameLocal.GetLocalPlayer()->FlashScreenCustom(idVec4(0, 0, 0, 1), 200); gameLocal.GetLocalPlayer()->Teleport(playerStartPosition, idAngles(0, playerStartAngle,0), NULL); return true; }
0
0.961451
1
0.961451
game-dev
MEDIA
0.97512
game-dev
0.997417
1
0.997417
4azuo/GuiGuBaHuang-ModLib
2,108
3161035078/ModProject/ModCode/ModMain/Mod/SMLocalConfigsEvent.cs
using MOD_nE7UL2.Const; using ModLib.Mod; using UnityEngine; namespace MOD_nE7UL2.Mod { [Cache(ModConst.SM_LOCAL_CONFIGS_EVENT)] public class SMLocalConfigsEvent : ModEvent { public static SMLocalConfigsEvent Instance { get; set; } public SMGlobalConfigsEvent Configs { get; set; } public override void OnLoadClass(bool isNew, string modId, CacheAttribute attr) { base.OnLoadClass(isNew, modId, attr); if (isNew) Configs = CacheHelper.ReadGlobalCacheFile<SMGlobalConfigsEvent>(modId, ModConst.SM_GLOBAL_CONFIGS_EVENT) ?? new SMGlobalConfigsEvent(); } public override void OnLoadGame() { base.OnLoadGame(); //exp foreach (var item in g.conf.roleGrade._allConfList) { item.exp = Calculate(item.exp, Configs.AddLevelupExpRate).Parse<int>(); } //item value foreach (var props in g.conf.itemProps._allConfList) { if (props.type == (int)PropsType.Money) continue; props.sale = Calculate(props.sale, Configs.AddItemValueRate).Parse<int>(); props.worth = Calculate(props.worth, Configs.AddItemValueRate).Parse<int>(); } foreach (var item in g.conf.itemSkill._allConfList) { item.price = Calculate(item.price, Configs.AddItemValueRate).Parse<int>(); item.cost = Calculate(item.cost, Configs.AddItemValueRate).Parse<int>(); item.sale = Calculate(item.sale, Configs.AddItemValueRate).Parse<int>(); item.worth = Calculate(item.worth, Configs.AddItemValueRate).Parse<int>(); } foreach (var refine in g.conf.townRefine._allConfList) { refine.moneyCost = Calculate(refine.moneyCost, Configs.AddItemValueRate).Parse<int>(); } } public double Calculate(double bas, double addRate) { return bas + (bas * addRate); } } }
0
0.887416
1
0.887416
game-dev
MEDIA
0.946951
game-dev
0.740581
1
0.740581
rdaum/moor
13,423
book/src/the-moo-programming-language/lambda-functions.md
# Functions and Lambdas mooR lets you create small functions inside your verbs, similar to how you might define functions in other programming languages. These functions help you organize your code better and avoid repeating yourself. There are two main types: - **Named functions** - functions with names that help organize your code - **Anonymous functions** (also called "lambdas") - unnamed functions that are useful for short, simple operations > **Fun Fact**: Despite its name suggesting otherwise, the original LambdaMOO never actually had lambda functions! mooR > brings this useful programming tool to MOO as part of our mission of dragging the future into the past. ## Syntax Forms Functions in mooR support three different syntax forms, each suited to different use cases: ### Arrow Syntax (Lambdas) Perfect for simple, one-line anonymous functions: ```moo {x, y} => x + y // Addition function {name} => "Hello, " + name // String formatting {} => random(100) // No parameters, returns random number {x} => x * x // Square function ``` ### Function Syntax For more complex logic with multiple statements. These can be anonymous or named: ```moo // Anonymous function fn(x, y) if (x > y) return x; else return y; endif endfn // Named function for code organization fn calculate_damage(attacker, defender) let base_damage = attacker.strength * 2; let defense = defender.armor; let final_damage = max(1, base_damage - defense); return final_damage; endfn ``` ### Named Functions for Code Structure Named functions work much like `def` in Python or `function` in JavaScript - they help organize code within verbs: ```moo // In a combat verb: fn calculate_hit_chance(attacker, target) let base_chance = 0.5; let skill_bonus = attacker.skill / 100.0; let dodge_penalty = target.agility / 200.0; return base_chance + skill_bonus - dodge_penalty; endfn fn apply_damage(target, damage) target.health = target.health - damage; if (target.health <= 0) this:handle_death(target); endif endfn // Main combat logic becomes much cleaner: if (random() < calculate_hit_chance(attacker, defender)) let damage = calculate_damage(attacker, defender); apply_damage(defender, damage); notify(attacker, "You hit for " + damage + " damage!"); else notify(attacker, "You miss!"); endif ``` ### Named Recursive Functions For functions that need to call themselves: ```moo fn factorial(n) if (n <= 1) return 1; else return n * factorial(n - 1); endif endfn fn fibonacci(n) if (n <= 1) return n; else return fibonacci(n - 1) + fibonacci(n - 2); endif endfn ``` ## Parameter Patterns Functions support all the same parameter patterns as regular MOO scatter assignments: ### Required Parameters ```moo {x, y} => x + y // Both x and y must be provided {name, age} => name + " is " + age // String concatenation ``` ### Optional Parameters Optional parameters default to `0` (false) if not provided: ```moo {x, ?y} => x + (y || 10) // y defaults to 0, but we use 10 if not provided {message, ?urgent} => urgent && ("URGENT: " + message) || message ``` ### Rest Parameters Collect extra arguments into a list: ```moo {first, @rest} => {first, length(rest)} {@all} => length(all) // Count total arguments ``` ### Mixed Parameters You can combine all parameter types: ```moo {required, ?optional, @rest} => [ "required" -> required, "optional" -> optional || "default", "rest" -> rest ] ``` ## Remembering Variables (Closures) One of the most useful features of functions in mooR is that they can "remember" variables from where they were created. This is called "capturing" variables, and when a function does this, programmers call it a "closure" - but don't worry about the fancy name, it's simpler than it sounds! ### Basic Example ```moo let multiplier = 5; let multiply_by_five = {x} => x * multiplier; // The function "remembers" multiplier return multiply_by_five(10); // Returns 50 ``` Even though `multiplier` was created outside the function, the function can still use it! ### Remembering Multiple Things Functions can remember more than one variable at a time: ```moo fn create_calculator(operation, initial_value) return {x} => { if (operation == "add") return initial_value + x; elseif (operation == "multiply") return initial_value * x; else return x; endif }; endfn let add_ten = create_calculator("add", 10); let multiply_by_three = create_calculator("multiply", 3); add_ten(5); // Returns 15 multiply_by_three(4); // Returns 12 ``` ## Functions Are Like Other Values In mooR, functions work just like other values (numbers, strings, lists) - you can store them in variables, put them in properties, and pass them to other functions. This might seem strange at first, but it's actually very useful! ### Storing Functions in Variables ```moo let add = {x, y} => x + y; let max_func = fn(x, y) return x > y && x || y; endfn; result = add(5, 3); // Returns 8 result = max_func(10, 7); // Returns 10 ``` ### Storing Functions in Properties Functions can be stored in object properties and called later: ```moo this.validator = {input} => length(input) >= 3; this.formatter = fn(text) return uppercase(text[1]) + lowercase(text[2..$]); endfn; // Later in another verb: if (this.validator(user_input)) return this.formatter(user_input); endif ``` **Important caveat:** Storing functions in properties is rarely what you actually want to do. When you call a function stored in a property, it doesn't get the `this`, `player`, `caller`, etc. values you'd expect from the object the property is on - instead it inherits those values from the calling verb. This can lead to confusing behavior. In most cases, you'll want to use regular verbs instead. Function properties might occasionally be useful for things like configuration callbacks or data transformation functions, but consider carefully whether a verb wouldn't be clearer. ### Passing Functions as Arguments Like Python or JavaScript, you can pass functions to other functions: ```moo fn process_list(items, transform_func) let result = {}; for item in (items) result = {@result, transform_func(item)}; endfor return result; endfn let numbers = {1, 2, 3, 4}; let doubled = process_list(numbers, {x} => x * 2); let strings = process_list(numbers, {x} => "Item: " + tostr(x)); ``` ### Immediate Invocation You can call a function immediately after creating it: ```moo result = ({x} => x * 2)(5); // Returns 10 // Useful for creating isolated scopes: let config = (fn() let base_url = "https://api.example.com"; let api_key = "secret123"; return ["url" -> base_url, "key" -> api_key]; endfn)(); ``` ## Functions That Use Other Functions One really useful thing you can do is write functions that take other functions as input. This might sound complicated, but it's actually quite handy for common tasks like transforming lists of data: ### Map Function Transform all elements in a list: ```moo fn map(func, list) let result = {}; for item in (list) result = {@result, func(item)}; endfor return result; endfn let numbers = {1, 2, 3, 4}; let doubled = map({x} => x * 2, numbers); // {2, 4, 6, 8} let squared = map({x} => x * x, numbers); // {1, 4, 9, 16} let strings = map({x} => tostr(x), numbers); // {"1", "2", "3", "4"} ``` ### Filter Function Select elements that match a condition: ```moo fn filter(pred, list) let result = {}; for item in (list) if (pred(item)) result = {@result, item}; endif endfor return result; endfn let numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; let evens = filter({x} => x % 2 == 0, numbers); // {2, 4, 6, 8, 10} let big_numbers = filter({x} => x > 5, numbers); // {6, 7, 8, 9, 10} ``` ### Reduce Function Combine all elements into a single value: ```moo fn reduce(func, list, initial) let accumulator = initial; for item in (list) accumulator = func(accumulator, item); endfor return accumulator; endfn let numbers = {1, 2, 3, 4, 5}; let sum = reduce({acc, x} => acc + x, numbers, 0); // 15 let product = reduce({acc, x} => acc * x, numbers, 1); // 120 let max = reduce({acc, x} => x > acc && x || acc, numbers, 0); // 5 ``` ## Event Handling and Callbacks Lambda functions are perfect for event handling: ```moo fn on_player_connect(player, callback) // Store the callback for later use this.connect_callbacks = {@(this.connect_callbacks || {}), callback}; endfn // Register event handlers on_player_connect(player, {p} => notify(p, "Welcome to the server!")); on_player_connect(player, {p} => this:log_connection(p)); ``` ## Practical Examples ### Data Processing Pipeline ```moo let data = {" Alice ", " BOB ", " charlie "}; // Clean, normalize, and format names let clean_names = map({name} => { let trimmed = strsub(strsub(name, "^\\s+", ""), "\\s+$", ""); let lower = lowercase(trimmed); return uppercase(lower[1]) + lower[2..$]; }, data); // Result: {"Alice", "Bob", "Charlie"} ``` ### Template Functions ```moo fn create_template_renderer(template, defaults) return {values} => { let merged = defaults; for key in (keys(values)) merged[key] = values[key]; endfor let result = template; for key in (keys(merged)) result = strsub(result, "{" + key + "}", tostr(merged[key])); endfor return result; }; endfn let email_template = create_template_renderer( "Hello {name}, your order #{order_id} is ready!", ["name" -> "Customer", "order_id" -> "0000"] ); email_template(["name" -> "Alice", "order_id" -> "1234"]); // Returns: "Hello Alice, your order #1234 is ready!" ``` ### Validation Functions ```moo fn create_validator(rules) return {data} => { let errors = {}; for rule in (rules) let field = rule["field"]; let check = rule["check"]; let message = rule["message"]; if (!check(data[field])) errors = {@errors, message}; endif endfor return errors; }; endfn let user_validator = create_validator({ ["field" -> "name", "check" -> {x} => length(x) > 0, "message" -> "Name required"], ["field" -> "email", "check" -> {x} => "@" in x, "message" -> "Invalid email"] }); user_validator(["name" -> "Alice", "email" -> "alice@example.com"]); // Returns: {} (no errors) ``` ## Best Practices ### When to Use Functions vs Verbs **Great for named functions within verbs:** - Breaking down complex verb logic into smaller, manageable pieces - Avoiding code duplication within a single verb - Mathematical calculations or data processing - Input validation and formatting - Any logic that would benefit from a descriptive function name **Great for lambdas (anonymous functions):** - Short, focused operations - Event handlers and callbacks - Data transformation and filtering (map, filter, etc.) - Function factories and builders - Functional programming patterns - One-off operations that don't need names **Better to use regular verbs for:** - Functions that need to be called from multiple other verbs - Complex business logic that forms the core of your application - Functions that need comprehensive documentation and help - Code that should be accessible to other objects via inheritance - Functions that need persistent storage or caching ### Performance Considerations - Lambda creation is fast, but not free - avoid creating them in tight loops - Variable capture is done by value, so large data structures are copied - Recursive lambdas can still hit stack limits like regular MOO recursion (fancy functional languages like Scheme or Lisp sometimes offer what's called tail-call elimination, but mooR doesn't) ### Debugging Tips Stack traces show lambda calls clearly: - Anonymous lambdas appear as `verb.<fn>` - Named lambdas appear as `verb.function_name` - Line numbers point to where the function was declared, not where it was invoked (to find the invocation site, look one level up in the traceback) ## Technical Details ### Variable Capture Semantics - Variables are captured by **value**, not by reference - Captured variables are immutable from the lambda's perspective - Each lambda invocation gets its own copy of captured variables ### Memory Management - Lambdas are garbage collected when no longer referenced - Captured variables are freed when the lambda is freed - Circular references between lambdas are not possible due to pass-by-value capture ### Compatibility - Lambda functions are a mooR extension and won't work on LambdaMOO - They can be stored in the database like any other value - They survive server restarts when stored in properties - They work seamlessly with existing MOO functions and operators Lambda functions represent a significant enhancement to MOO's programming capabilities, enabling more expressive and functional programming patterns while maintaining full compatibility with existing MOO code.
0
0.88628
1
0.88628
game-dev
MEDIA
0.139172
game-dev
0.871399
1
0.871399
Stephane-D/SGDK
1,346
sample/game/platformer/src/levelgenerator.c
#include "levelgenerator.h" #include "resources.h" #include "global.h" #include "map.h" //Dynamic 2D array where we store the collision map data //We could read that directly from ROM but in the long term it's cleaner and/or more performant u8** currentMap; //Downlscaled size of the map in order to match the collision map size Vect2D_u16 roomTileSize; void freeCollisionMap() { //We have to free the collision map data in this way in order to avoid memory leaks for (u16 i = 0; i < roomTileSize.y; i++) { MEM_free(currentMap[i]); } MEM_free(currentMap); } void generateCollisionMap(const u8 map[][48]) { roomSize = newAABB(0, 768, 0, 768); //Each tile is 16x16px so we divide 768(size of the room in pixels) / 16, we use bitshifts because it is more performant than divisions roomTileSize = newVector2D_u16(768 >> 4, 768 >> 4); //To store a 2D array with pointers we have to do it in that way currentMap = (u8**)MEM_alloc(roomTileSize.y * sizeof(u8*)); for (u16 i = 0; i < roomTileSize.y; i++) { currentMap[i] = (u8*)MEM_alloc(roomTileSize.x); memcpy(currentMap[i], map[i], roomTileSize.x); } } u16 getTileValue(s16 x, s16 y) { if (x >= roomTileSize.x || x < 0 || y < 0 || y >= roomTileSize.y) return 0; //If the position is inside the collision map return the value of the tile from it return currentMap[y][x]; }
0
0.855318
1
0.855318
game-dev
MEDIA
0.641226
game-dev
0.962639
1
0.962639
source-academy/frontend
7,055
src/features/game/scenes/chapterSelect/ChapterSelect.ts
import { screenCenter, screenSize } from 'src/features/game/commons/CommonConstants'; import { mandatory, toS3Path } from 'src/features/game/utils/GameUtils'; import ImageAssets from '../../assets/ImageAssets'; import CommonBackButton from '../../commons/CommonBackButton'; import { addLoadingScreen } from '../../effects/LoadingScreen'; import GameLayerManager from '../../layer/GameLayerManager'; import { Layer } from '../../layer/GameLayerTypes'; import SourceAcademyGame from '../../SourceAcademyGame'; import { createButton } from '../../utils/ButtonUtils'; import { loadImage } from '../../utils/LoaderUtils'; import { createBitmapText } from '../../utils/TextUtils'; import chapConstants, { pageNumberStyle } from './ChapterSelectConstants'; import { createChapter } from './ChapterSelectHelper'; /** * The Chapter Select scene. * Player is able to choose which chapter to play from here. */ class ChapterSelect extends Phaser.Scene { public layerManager?: GameLayerManager; private chaptersContainer: Phaser.GameObjects.Container | undefined; private backButtonContainer: Phaser.GameObjects.Container | undefined; private pageNumberText: Phaser.GameObjects.BitmapText | undefined; private targetPage: number; constructor() { super('ChapterSelect'); this.chaptersContainer = undefined; this.backButtonContainer = undefined; this.pageNumberText = undefined; this.targetPage = 0; // First page is page 0 (but is displayed as page 1) } public preload() { addLoadingScreen(this); } public async create() { SourceAcademyGame.getInstance().setCurrentSceneRef(this); this.layerManager = new GameLayerManager(this); await this.preloadChapterAssets(); this.renderBackground(); this.renderChapters(); } public update() { if (!this.chaptersContainer) return; const targetX = -this.targetPage * screenSize.x; if (this.chaptersContainer.x > targetX) { // Scroll right const newXPos = this.chaptersContainer.x - chapConstants.scrollSpeed; this.chaptersContainer.x = Math.max(newXPos, targetX); } else if (targetX > this.chaptersContainer.x) { // Scroll left const newXPos = this.chaptersContainer.x + chapConstants.scrollSpeed; this.chaptersContainer.x = Math.min(newXPos, targetX); } } /** * Clean up of related managers. */ public cleanUp() { this.getLayerManager().clearAllLayers(); } /** * Load the chapter previews assets to be shown. */ private async preloadChapterAssets() { await Promise.all( this.getGameChapters().map( async chapterDetail => await loadImage(this, chapterDetail.imageUrl, toS3Path(chapterDetail.imageUrl, true)) ) ); } /** * Render the background of this scene. */ private renderBackground() { const background = new Phaser.GameObjects.Image( this, screenCenter.x, screenCenter.y, ImageAssets.spaceshipBg.key ); const blackOverlay = new Phaser.GameObjects.Rectangle( this, screenCenter.x, screenCenter.y, screenSize.x, screenSize.y, 0 ).setAlpha(0.3); this.getLayerManager().addToLayer(Layer.Background, background); this.getLayerManager().addToLayer(Layer.Background, blackOverlay); } /** * Render all the chapter selections and UI elements * (the gray frame, the left and right arrow, back button, page number) */ private renderChapters() { this.backButtonContainer = new CommonBackButton(this, () => { this.cleanUp(); this.scene.start('MainMenu'); }); this.chaptersContainer = this.createChaptersContainer(); this.pageNumberText = createBitmapText( this, `1 / ${this.numPages()}`, chapConstants.pageNumberTextConfig, pageNumberStyle ); // Prepare to autoscroll to smallest incomplete chapter const latestChapter = Math.min( SourceAcademyGame.getInstance().getSaveManager().getLargestCompletedChapterNum() + 1, this.getGameChapters().length - 1 ); this.targetPage = Math.floor(latestChapter / chapConstants.grid.chapPerPage); if (this.targetPage < 0) { // Only happens when this.getGameChapters().length === 0 this.targetPage = 0; } this.pageNumberText.setText(`${this.targetPage + 1} / ${this.numPages()}`); const border = new Phaser.GameObjects.Image( this, screenCenter.x, screenCenter.y, ImageAssets.chapterSelectBorder.key ); const leftArrow = createButton(this, { assetKey: ImageAssets.chapterSelectArrow.key, onUp: () => this.scrollPrevPage() }).setPosition(screenCenter.x - chapConstants.arrow.xOffset, screenCenter.y); const rightArrow = createButton(this, { assetKey: ImageAssets.chapterSelectArrow.key, onUp: () => this.scrollNextPage() }) .setPosition(screenCenter.x + chapConstants.arrow.xOffset, screenCenter.y) .setScale(-1, 1); this.getLayerManager().addToLayer(Layer.UI, this.chaptersContainer); this.getLayerManager().addToLayer(Layer.UI, this.backButtonContainer); this.getLayerManager().addToLayer(Layer.UI, this.pageNumberText); this.getLayerManager().addToLayer(Layer.UI, border); this.getLayerManager().addToLayer(Layer.UI, leftArrow); this.getLayerManager().addToLayer(Layer.UI, rightArrow); } /** * Create a chapter selection based on its detail; as well as * attach it with the necessary information (user progress). * * The information will be used/mutated depending on whether * the user decides to continue or reset the progress. */ private createChaptersContainer() { const chaptersContainer = new Phaser.GameObjects.Container(this, 0, 0); chaptersContainer .add( this.getGameChapters().map((chapterDetail, chapterIndex) => { return createChapter(this, chapterDetail, chapterIndex); }) ) .sort('depth') .reverse(); // Ensures hover text correctly render over other objects in container return chaptersContainer; } private getGameChapters = () => SourceAcademyGame.getInstance().getGameChapters(); /** * Returns the number of pages of chapters */ private numPages() { const pages = Math.ceil(this.getGameChapters().length / chapConstants.grid.chapPerPage); return Math.max(pages, 1); // Always have at least 1 page, even when 0 chapters } /** * Scroll the screen to the previous page of chapters */ private scrollPrevPage() { this.targetPage = Math.max(this.targetPage - 1, 0); this.pageNumberText?.setText(`${this.targetPage + 1} / ${this.numPages()}`); } /** * Scroll the screen to the next page of chapters */ private scrollNextPage() { const numPages = this.numPages(); this.targetPage = Math.min(this.targetPage + 1, numPages - 1); this.pageNumberText?.setText(`${this.targetPage + 1} / ${numPages}`); } public getLayerManager = () => mandatory(this.layerManager); } export default ChapterSelect;
0
0.838238
1
0.838238
game-dev
MEDIA
0.877312
game-dev
0.98248
1
0.98248
dcs-retribution/dcs-retribution
13,976
qt_ui/windows/mission/flight/settings/QFlightSlotEditor.py
import logging from typing import Optional, Callable from PySide6.QtCore import Signal, QModelIndex from PySide6.QtWidgets import ( QLabel, QGroupBox, QSpinBox, QGridLayout, QComboBox, QHBoxLayout, QCheckBox, QVBoxLayout, QPushButton, QDialog, QWidget, QSizePolicy, ) from game import Game from game.ato.closestairfields import ClosestAirfields from game.ato.flight import Flight from game.ato.flightroster import FlightRoster from game.ato.iflightroster import IFlightRoster from game.dcs.aircrafttype import AircraftType from game.squadrons import Squadron from game.squadrons.pilot import Pilot from game.theater import ControlPoint, OffMapSpawn from game.utils import nautical_miles from qt_ui.models import PackageModel class PilotSelector(QComboBox): available_pilots_changed = Signal() def __init__( self, squadron: Optional[Squadron], roster: Optional[IFlightRoster], idx: int ) -> None: super().__init__() self.squadron = squadron self.roster = roster self.pilot_index = idx self.rebuild() @staticmethod def text_for(pilot: Pilot) -> str: return pilot.name def _do_rebuild(self) -> None: self.clear() if self.roster is None or self.pilot_index >= self.roster.max_size: self.addItem("No aircraft", None) self.setDisabled(True) return if self.squadron is None: raise RuntimeError("squadron cannot be None if roster is set") self.setEnabled(True) self.addItem("Unassigned", None) choices = list(self.squadron.available_pilots) current_pilot = self.roster.pilot_at(self.pilot_index) if current_pilot is not None: choices.append(current_pilot) # Put players first, otherwise alphabetically. for pilot in sorted(choices, key=lambda p: (not p.player, p.name)): self.addItem(self.text_for(pilot), pilot) if current_pilot is None: self.setCurrentText("Unassigned") else: self.setCurrentText(self.text_for(current_pilot)) self.currentIndexChanged.connect(self.replace_pilot) def rebuild(self) -> None: # The contents of the selector depend on the selection of the other selectors # for the flight, so changing the selection of one causes each selector to # rebuild. A rebuild causes a selection change, so if we don't block signals # during a rebuild we'll never stop rebuilding. self.blockSignals(True) try: self._do_rebuild() finally: self.blockSignals(False) def replace_pilot(self, index: QModelIndex) -> None: if self.itemText(index) == "No aircraft": # The roster resize is handled separately, so we have no pilots to remove. return pilot = self.itemData(index) if pilot == self.roster.pilot_at(self.pilot_index): return self.roster.set_pilot(self.pilot_index, pilot) self.available_pilots_changed.emit() def replace( self, squadron: Optional[Squadron], new_roster: Optional[FlightRoster] ) -> None: self.squadron = squadron self.roster = new_roster self.rebuild() class PilotControls(QHBoxLayout): player_toggled = Signal() def __init__( self, squadron: Optional[Squadron], roster: Optional[FlightRoster], idx: int, pilots_changed: Signal, ) -> None: super().__init__() self.roster = roster self.pilot_index = idx self.pilots_changed = pilots_changed self.selector = PilotSelector(squadron, roster, idx) self.selector.setSizePolicy( QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed ) self.selector.currentIndexChanged.connect(self.on_pilot_changed) self.addWidget(self.selector) self.player_checkbox = QCheckBox(text="Player") self.player_checkbox.setToolTip("Checked if this pilot is a player.") self.on_pilot_changed(self.selector.currentIndex()) enabled = False if self.roster is not None and squadron is not None: enabled = squadron.aircraft.flyable self.player_checkbox.setEnabled(enabled) self.addWidget(self.player_checkbox) self.player_checkbox.toggled.connect(self.on_player_toggled) @property def pilot(self) -> Optional[Pilot]: if self.roster is None or self.pilot_index >= self.roster.max_size: return None return self.roster.pilot_at(self.pilot_index) def on_player_toggled(self, checked: bool) -> None: pilot = self.pilot if pilot is None: logging.error("Cannot toggle state of a pilot when none is selected") return pilot.player = checked self.player_toggled.emit() self.pilots_changed.emit() def on_pilot_changed(self, index: int) -> None: pilot = self.selector.itemData(index) self.player_checkbox.blockSignals(True) try: if self.roster and self.roster.squadron.aircraft.flyable: self.player_checkbox.setChecked(pilot is not None and pilot.player) else: self.player_checkbox.setChecked(False) finally: if self.roster is not None: self.player_checkbox.setEnabled(self.roster.squadron.aircraft.flyable) self.player_checkbox.blockSignals(False) # on_pilot_changed should emit pilots_changed in its finally block, # otherwise the start-type isn't updated if you have a single client # pilot which you switch to a non-client pilot self.pilots_changed.emit() def update_available_pilots(self) -> None: self.selector.rebuild() def enable_and_reset(self) -> None: self.selector.rebuild() self.player_checkbox.setEnabled(True) self.on_pilot_changed(self.selector.currentIndex()) def disable_and_clear(self) -> None: self.selector.rebuild() self.player_checkbox.blockSignals(True) try: self.player_checkbox.setEnabled(False) self.player_checkbox.setChecked(False) finally: self.player_checkbox.blockSignals(False) def replace( self, squadron: Optional[Squadron], new_roster: Optional[FlightRoster] ) -> None: self.roster = new_roster if self.roster is None or self.pilot_index >= self.roster.max_size: self.disable_and_clear() else: self.enable_and_reset() self.selector.replace(squadron, new_roster) class FlightRosterEditor(QVBoxLayout): MAX_PILOTS = 4 pilots_changed = Signal() def __init__( self, squadron: Optional[Squadron], roster: Optional[IFlightRoster], ) -> None: super().__init__() self.roster = roster self.pilot_controls = [] for pilot_idx in range(self.MAX_PILOTS): def make_reset_callback(source_idx: int) -> Callable[[int], None]: def callback() -> None: self.update_available_pilots(source_idx) return callback controls = PilotControls(squadron, roster, pilot_idx, self.pilots_changed) controls.selector.available_pilots_changed.connect( make_reset_callback(pilot_idx) ) self.pilot_controls.append(controls) self.addLayout(controls) def update_available_pilots(self, source_idx: int) -> None: for idx, controls in enumerate(self.pilot_controls): # No need to reset the source of the reset, it was just manually selected. if idx != source_idx: controls.update_available_pilots() def resize(self, new_size: int) -> None: if new_size > self.MAX_PILOTS: raise ValueError("A flight may not have more than four pilots.") if self.roster is not None: self.roster.resize(new_size) for controls in self.pilot_controls[:new_size]: controls.enable_and_reset() for controls in self.pilot_controls[new_size:]: controls.disable_and_clear() def replace( self, squadron: Optional[Squadron], new_roster: Optional[FlightRoster] ) -> None: if self.roster is not None: self.roster.clear() self.roster = new_roster for controls in self.pilot_controls: controls.replace(squadron, new_roster) class QSquadronSelector(QDialog): def __init__(self, flight: Flight, parent: Optional[QWidget] = None): super().__init__(parent) self.flight = flight self.parent = parent self.init() def init(self): vbox = QVBoxLayout() self.setLayout(vbox) self.selector = QComboBox() air_wing = self.flight.coalition.air_wing for squadron in air_wing.best_squadrons_for( self.flight.package.target, self.flight.flight_type, self.flight.roster.max_size, self.flight.is_helo, True, ignore_range=True, ): if squadron is self.flight.squadron: continue self.selector.addItem( f"{squadron.name} - {squadron.aircraft.variant_id}", squadron ) vbox.addWidget(self.selector) hbox = QHBoxLayout() accept = QPushButton("Accept") accept.clicked.connect(self.accept) hbox.addWidget(accept) cancel = QPushButton("Cancel") cancel.clicked.connect(self.reject) hbox.addWidget(cancel) vbox.addLayout(hbox) class QFlightSlotEditor(QGroupBox): flight_resized = Signal(int) squadron_changed = Signal(Flight) def __init__( self, package_model: PackageModel, flight: Flight, game: Game, ): super().__init__("Slots") self.package_model = package_model self.flight = flight self.game = game self.closest_airfields = ClosestAirfields( flight.package.target, list(game.theater.control_points_for(self.flight.coalition.player)), ) available = self.flight.squadron.untasked_aircraft max_count = self.flight.count + available if max_count > 4: max_count = 4 layout = QGridLayout() self.aircraft_count = QLabel("Aircraft count:") self.aircraft_count_spinner = QSpinBox() self.aircraft_count_spinner.setMinimum(1) self.aircraft_count_spinner.setMaximum(max_count) self.aircraft_count_spinner.setValue(flight.count) self.aircraft_count_spinner.valueChanged.connect(self._changed_aircraft_count) layout.addWidget(self.aircraft_count, 0, 0) layout.addWidget(self.aircraft_count_spinner, 0, 1) layout.addWidget(QLabel("Squadron:"), 1, 0) hbox = QHBoxLayout() hbox.addWidget(QLabel(str(self.flight.squadron))) squadron_btn = QPushButton("Change Squadron") squadron_btn.clicked.connect(self._change_squadron) hbox.addWidget(squadron_btn) layout.addLayout(hbox, 1, 1) layout.addWidget(QLabel("Assigned pilots:"), 2, 0) self.roster_editor = FlightRosterEditor(flight.squadron, flight.roster) layout.addLayout(self.roster_editor, 2, 1) self.setLayout(layout) def _change_squadron(self): dialog = QSquadronSelector(self.flight) if dialog.exec(): squadron: Optional[Squadron] = dialog.selector.currentData() if not squadron: return flight = Flight( self.package_model.package, squadron, self.flight.count, self.flight.flight_type, self.flight.start_type, self._find_divert_field(squadron.aircraft, squadron.location), frequency=self.flight.frequency, cargo=self.flight.cargo, channel=self.flight.tacan, callsign_tcn=self.flight.tcn_name, ) self.package_model.add_flight(flight) self.package_model.delete_flight(self.flight) self.squadron_changed.emit(flight) def _find_divert_field( self, aircraft: AircraftType, arrival: ControlPoint ) -> Optional[ControlPoint]: divert_limit = nautical_miles(150) for airfield in self.closest_airfields.operational_airfields_within( divert_limit ): if airfield.captured != self.flight.coalition.player: continue if airfield == arrival: continue if not airfield.can_operate(aircraft): continue if isinstance(airfield, OffMapSpawn): continue return airfield return None def _changed_aircraft_count(self): old_count = self.flight.count new_count = int(self.aircraft_count_spinner.value()) try: self.flight.resize(new_count) except ValueError: # The UI should have prevented this, but if we ran out of aircraft # then roll back the inventory change. difference = new_count - self.flight.count available = self.flight.squadron.untasked_aircraft logging.error( f"Could not add {difference} additional aircraft to " f"{self.flight} because {self.flight.departure} has only " f"{available} {self.flight.unit_type} remaining" ) self.flight.resize(old_count) return self.roster_editor.resize(new_count) self.flight_resized.emit(new_count)
0
0.804226
1
0.804226
game-dev
MEDIA
0.303585
game-dev
0.951178
1
0.951178
Retera/WarsmashModEngine
1,347
core/src/com/etheller/warsmash/viewer5/handlers/w3x/simulation/abilitybuilder/behavior/action/timer/ABActionUpdateTimerTimeout.java
package com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.behavior.action.timer; import java.util.Map; import com.etheller.warsmash.parsers.jass.JassTextGenerator; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CSimulation; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CUnit; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.behavior.callback.floatcallbacks.ABFloatCallback; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.behavior.callback.timercallbacks.ABTimerCallback; import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.core.ABSingleAction; public class ABActionUpdateTimerTimeout implements ABSingleAction { private ABTimerCallback timer; private ABFloatCallback timeout; @Override public void runAction(final CSimulation game, final CUnit caster, final Map<String, Object> localStore, final int castId) { this.timer.callback(game, caster, localStore, castId) .setTimeoutTime(this.timeout.callback(game, caster, localStore, castId)); } @Override public String generateJassEquivalent(JassTextGenerator jassTextGenerator) { return "ABTimerSetTimeoutTime(" + this.timer.generateJassEquivalent(jassTextGenerator) + ", " + this.timeout.generateJassEquivalent(jassTextGenerator) + ")"; } }
0
0.783756
1
0.783756
game-dev
MEDIA
0.932524
game-dev
0.903821
1
0.903821
Subject9x/battleMETAL
7,901
dp/subs.qc
/* Quake 1 author: iD Software */ void() SUB_Null = {}; void(entity attacker) SUB_Null_pain = {}; void() SUB_Remove = {remove(self);}; /* QuakeEd only writes a single float for angles (bad idea), so up and down are just constant angles. Lord Havoc note: I added direct interpretation of movedir, and you could already use direct vector angles. */ void() SetMovedir = { if (self.movedir != '0 0 0') self.movedir = normalize(self.movedir); else { if (self.angles == '0 -1 0') self.movedir = '0 0 1'; else if (self.angles == '0 -2 0') self.movedir = '0 0 -1'; else { makevectors (self.angles); self.movedir = v_forward; } } self.angles = '0 0 0'; }; /* ================ InitTrigger ================ */ void() InitTrigger = { // trigger angles are used for one-way touches. An angle of 0 is assumed // to mean no restrictions, so use a yaw of 360 instead. if (self.movedir == '0 0 0') if (self.angles != '0 0 0') SetMovedir (); self.solid = SOLID_TRIGGER; setmodel (self, self.model); // set size and link into world self.movetype = MOVETYPE_NONE; self.modelindex = 0; self.model = ""; }; void() InitSolidBSPTrigger = { // trigger angles are used for one-way touches. An angle of 0 is assumed // to mean no restrictions, so use a yaw of 360 instead. if (self.movedir == '0 0 0') if (self.angles != '0 0 0') SetMovedir (); self.solid = SOLID_BSP; setmodel (self, self.model); // set size and link into world self.movetype = MOVETYPE_PUSH; // self.modelindex = 0; self.model = ""; }; /* ============= SUB_CalcMove calculate self.velocity and self.nextthink to reach dest from self.origin traveling at speed =============== */ void(entity ent, vector tdest, float tspeed, void() func) SUB_CalcMoveEnt = { stemp = self; self = ent; SUB_CalcMove (tdest, tspeed, func); self = stemp; }; void(vector tdest, float tspeed, void() func) SUB_CalcMove = { local vector vdestdelta; local float len, traveltime; if (!tspeed) objerror("No speed is defined!"); self.think1 = func; self.dest3 = tdest; self.think = SUB_CalcMoveDone; if (tdest == self.origin) { self.velocity = '0 0 0'; self.nextthink = self.ltime + 0.1; return; } // set destdelta to the vector needed to move vdestdelta = tdest - self.origin; // calculate length of vector len = vlen (vdestdelta); // divide by speed to get time to reach dest traveltime = len / tspeed; if (traveltime < 0.1) { self.velocity = '0 0 0'; self.nextthink = self.ltime + 0.1; return; } // set nextthink to trigger a think when dest is reached self.nextthink = self.ltime + traveltime; // scale the destdelta vector by the time spent traveling to get velocity self.velocity = vdestdelta * (1/traveltime); // qcc won't take vec/float // LordHavoc - why does MOVETYPE_NOCLIP use per frame deltas??? if (self.movetype == MOVETYPE_NOCLIP) self.velocity = self.velocity * 0.1; }; /* ============ After moving, set origin to exact final destination ============ */ void() SUB_CalcMoveDone = { setorigin(self, self.dest3); self.velocity = '0 0 0'; self.nextthink = -1; if (self.think1) self.think1(); }; /* ============= SUB_CalcAngleMove calculate self.avelocity and self.nextthink to reach destangle from self.angles rotating The calling function should make sure self.think is valid =============== */ void(entity ent, vector destangle, float tspeed, void() func) SUB_CalcAngleMoveEnt = { stemp = self; self = ent; SUB_CalcAngleMove (destangle, tspeed, func); self = stemp; }; void(vector destangle, float tspeed, void() func) SUB_CalcAngleMove = { local vector destdelta; local float len, traveltime; if (!tspeed) objerror("No speed is defined!"); // set destdelta to the vector needed to move destdelta = destangle - self.angles; // calculate length of vector len = vlen (destdelta); // divide by speed to get time to reach dest traveltime = len / tspeed; // set nextthink to trigger a think when dest is reached self.nextthink = self.ltime + traveltime; // scale the destdelta vector by the time spent traveling to get velocity self.avelocity = destdelta * (1 / traveltime); self.think1 = func; self.dest4 = destangle; self.think = SUB_CalcAngleMoveDone; }; /* ============ After rotating, set angle to exact final angle ============ */ void() SUB_CalcAngleMoveDone = { self.angles = self.dest4; self.avelocity = '0 0 0'; self.nextthink = -1; if (self.think1) self.think1(); }; //============================================================================= void() DelayThink = { activator = self.enemy; SUB_UseTargets (); remove(self); }; /* ============================== SUB_UseTargets the global "activator" should be set to the entity that initiated the firing. If self.delay is set, a DelayedUse entity will be created that will actually do the SUB_UseTargets after that many seconds have passed. Centerprints any self.message to the activator. Removes all entities with a targetname that match self.killtarget, and removes them, so some events can remove other triggers. Search for (string)targetname in all entities that match (string)self.target and call their .use function ============================== */ void() SUB_UseTargets = { local entity t, act; local entity tempSelf, tempOther; // // check for a delay // if (self.delay){ // create a temp object to fire at a later time t = spawn(); t.classname = "DelayedUse"; t.nextthink = time + self.delay; t.think = DelayThink; t.enemy = activator; t.message = self.message; t.killtarget = self.killtarget; t.target = self.target; return; } // // print the message // if (activator.classname == "player" && self.message != "") { if (activator.flags & FL_CLIENT){ centerprint (activator, self.message); } if (!self.noise){ precache_sound ("misc/talk.wav"); sound (activator, CHAN_VOICE, "misc/talk.wav", 1, ATTN_NORM); } } // // kill the killtagets // if (self.killtarget){ for( t = nextent(world); t != world; t = nextent(t) ){ if( t.targetname != self.killtarget ){ continue; } if( t.data_type && t.th_die){ t.think = t.th_die; t.nextthink = time + 0.1; } else{ remove (t); } } } // // fire targets // /*if (self.target){ act = activator; t = world; do{ t = find(t, targetname, self.target); if (!t) return; tempSelf = self; tempOther = other; self = t; other = tempSelf; if (self.use) self.use (); self = tempSelf; other = tempOther; activator = act; } while ( 1 ); }*/ // guess this needed updating too. if( self.target ){ act = activator; for(t = nextent(world); t != world; t = nextent(t) ){ if( t.targetname != self.target ){ continue; } if(!t.use){ continue; } tempSelf = self; tempOther = other; self = t; other = tempSelf; self.use(); self = tempSelf; other = tempOther; } activator = act; } }; /* in nightmare mode, all attack_finished times become 0 some monsters refire twice automatically */ void(float normal) SUB_AttackFinished = { self.cnt = 0; // refire count for nightmare if (skill < 3) self.attack_finished = time + normal; }; void (void() thinkst) SUB_CheckRefire = { if (skill < 3) return; if (self.cnt == 1) return; //if (!visible (self.enemy)) //return; self.cnt = 1; self.think = thinkst; }; //========================= // SUB_NormalizeAngles //========================= vector (vector ang) SUB_NormalizeAngles = { while(ang_x > 360) ang_x = ang_x - 360; while(ang_x < 0) ang_x = ang_x + 360; while(ang_y > 360) ang_y = ang_y - 360; while(ang_y < 0) ang_y = ang_y + 360; while(ang_z > 360) ang_z = ang_z - 360; while(ang_z < 0) ang_z = ang_z + 360; return ang; };
0
0.796235
1
0.796235
game-dev
MEDIA
0.951323
game-dev
0.980021
1
0.980021
ComfyFactory/ComfyFactorio
12,108
maps/journey/main.lua
--[[ Journey, launch a rocket in increasingly harder getting worlds. - MewMew ]]-- if script.active_mods['space-age'] then error('Journey Scenario is not compatible with the Space Age mod. Please disable the mod and try again', 2) end local Server = require 'utils.server' local Constants = require 'maps.journey.constants' local Functions = require 'maps.journey.functions' local Unique_modifiers = require 'maps.journey.unique_modifiers' local Map = require 'modules.map_info' local Global = require 'utils.global' local Token = require 'utils.token' local Event = require 'utils.event' local Vacants = require 'modules.clear_vacant_players' local Robolimits = require 'modules.robot_limits' local journey = { announce_capsules = true } local events = { import = Event.generate_event_name('import'), check_import = Event.generate_event_name('check_import'), } Global.register( journey, function(tbl) journey = tbl end ) journey.import = Token.register( function(data) if not data then return end script.raise_event(events.import, data) end ) journey.check_import = Token.register( function(data) if not data then return end script.raise_event(events.check_import, data) end ) local function on_chunk_generated(event) local surface = event.surface if surface.index == 1 then Functions.place_mixed_ore(event, journey) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_chunk_generated then unique_modifier.on_chunk_generated(event, journey) end return end if surface.name ~= 'mothership' then return end Functions.on_mothership_chunk_generated(event) end local function on_console_chat(event) if not event.player_index then return end local message = event.message message = string.lower(message) local a = string.find(message, '?', 1, true) if not a then return end local b = string.find(message, 'mother', 1, true) if not b then return end local answer = Constants.mothership_messages.answers[math.random(1, #Constants.mothership_messages.answers)] if math.random(1, 4) == 1 then for _ = 1, math.random(2, 5), 1 do table.insert(journey.mothership_messages, '') end table.insert(journey.mothership_messages, '...') end for _ = 1, math.random(15, 30), 1 do table.insert(journey.mothership_messages, '') end table.insert(journey.mothership_messages, answer) end local function on_player_joined_game(event) local player = game.players[event.player_index] Functions.draw_gui(journey) Functions.set_minimum_to_vote(journey) if player.surface.name == 'mothership' then journey.characters_in_mothership = journey.characters_in_mothership + 1 end if player.force.name == 'enemy' then Functions.clear_player(player) player.force = game.forces.player local position = game.surfaces.nauvis.find_non_colliding_position('character', {0,0}, 32, 0.5) if position then player.teleport(position, game.surfaces.nauvis) else player.teleport({0,0}, game.surfaces.nauvis) end end end local function on_player_left_game(event) local player = game.players[event.player_index] Functions.draw_gui(journey) if player.surface.name == 'mothership' then journey.characters_in_mothership = journey.characters_in_mothership - 1 player.clear_items_inside() end end local function on_player_changed_position(event) local player = game.players[event.player_index] Functions.teleporters(journey, player) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_player_changed_position then unique_modifier.on_player_changed_position(event) end end local function on_built_entity(event) Functions.deny_building(event) Functions.register_built_silo(event, journey) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_built_entity then unique_modifier.on_built_entity(event, journey) end end local function on_robot_built_entity(event) Functions.deny_building(event) Functions.register_built_silo(event, journey) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_robot_built_entity then unique_modifier.on_robot_built_entity(event, journey) end end local function on_player_mined_entity(event) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_player_mined_entity then unique_modifier.on_player_mined_entity(event, journey) end end local function on_robot_mined_entity(event) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_robot_mined_entity then unique_modifier.on_robot_mined_entity(event, journey) end end local function on_research_finished(event) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_research_finished then unique_modifier.on_research_finished(event, journey) Functions.update_tooltips(journey) Functions.draw_gui(journey) end end local function on_entity_damaged(event) local entity = event.entity if not entity or not entity.valid then return end if entity ~= journey.beacon_objective then return end if event.force and event.force.name == 'enemy' then Functions.deal_damage_to_beacon(journey, event.final_damage_amount) end entity.health = 1000 end local function on_entity_died(event) local unique_modifier = Unique_modifiers[journey.world_trait] if unique_modifier.on_entity_died then unique_modifier.on_entity_died(event, journey) end end local function on_rocket_launched(event) local rocket_inventory = event.rocket.cargo_pod.get_inventory(defines.inventory.cargo_unit) local slot = rocket_inventory[1] if slot and slot.valid and slot.valid_for_read then if journey.mothership_cargo[slot.name] then journey.mothership_cargo[slot.name] = journey.mothership_cargo[slot.name] + slot.count else journey.mothership_cargo[slot.name] = slot.count end if journey.mothership_cargo_space[slot.name] then if journey.mothership_cargo[slot.name] > journey.mothership_cargo_space[slot.name] then journey.mothership_cargo[slot.name] = journey.mothership_cargo_space[slot.name] end if slot.name == 'uranium-fuel-cell' or slot.name == 'nuclear-reactor' then Server.to_discord_embed('Refueling progress: ' .. slot.name .. ': ' .. journey.mothership_cargo[slot.name] .. '/' .. journey.mothership_cargo_space[slot.name]) elseif journey.speedrun.enabled and slot.name == journey.speedrun.item then Server.to_discord_embed('Orbital Station delivery: ' .. slot.name .. ': ' .. journey.mothership_cargo[slot.name] .. '/' .. journey.mothership_cargo_space[slot.name]) end end end rocket_inventory.clear() rocket_inventory.insert({name = 'space-science-pack', count = 200}) local force = event.rocket.force if force.technologies['space-science-pack'].researched == false then force.technologies['space-science-pack'].researched = true force.print('[technology=space-science-pack] researched.') force.play_sound({path = 'utility/research_completed'}) table.insert(journey.goods_to_dispatch, { 'loader', 3 }) table.insert(journey.mothership_messages, 'I am sending you some loaders. Use them to load the rocket silos with all needed items.') journey.game_state = 'dispatch_goods' end Functions.draw_gui(journey) end local function make_import(data) if not data then return end if data.key ~= 'journey_data' then return end local old_selectors = journey.world_selectors for key, value in pairs(data.value) do journey[key] = value end for k, selector in pairs(old_selectors) do journey.world_selectors[k].border = selector.border journey.world_selectors[k].texts = selector.texts journey.world_selectors[k].rectangles = selector.rectangles end journey.importing = true game.print('Journey data imported.') journey.game_state = 'importing_world' end local function check_import(data) if not data then return end if data.key ~= 'journey_updating' then return end journey.import_checked = true local importing = data.value if importing then Functions.import_journey(journey) end end local function on_nth_tick() Functions[journey.game_state](journey) Functions.mothership_message_queue(journey) local tick = game.tick if tick % 3600 == 0 then Functions.lure_far_biters(journey) elseif tick % 600 == 0 then Functions.lure_biters(journey) end end local function on_init() local T = Map.Pop_info() T.localised_category = 'journey' T.main_caption_color = {r = 100, g = 20, b = 255} T.sub_caption_color = {r = 100, g = 100, b = 100} game.permissions.get_group('Default').set_allows_action(defines.input_action.set_rocket_silo_send_to_orbit_automated_mode, false) Vacants.init(1, true) Robolimits.set_construction_robot_limit(1000) Robolimits.set_logistic_robot_limit(1000) Robolimits.set_roboport_limit(100) Functions.hard_reset(journey) end local function cmd_handler() local player = game.player local p if not (player and player.valid) then p = log else p = player.print end if player and not player.admin then p('You are not an admin!') return false, nil, p end return true, player or {name = 'Server'}, p end commands.add_command( 'journey-reset', 'Fully resets the journey map.', function() local s, player = cmd_handler() if s then Functions.hard_reset(journey) game.print((player and player.name or 'Server') .. ' has reset the map.') end end ) commands.add_command( 'journey-skip-world', 'Instantly wins and skips the current world.', function() local s, _, p = cmd_handler() if s then if journey.game_state ~= 'dispatch_goods' and journey.game_state ~= 'world' then return end journey.game_state = 'set_world_selectors' p('The current world was skipped...') end end ) commands.add_command( 'journey-update', 'Restarts the server with newest version of Journey scenario code during next map reset', function() local s, _, p = cmd_handler() if s then journey.restart_from_scenario = not journey.restart_from_scenario p('Journey marking for full restart with updates on next reset was switched to ' .. tostring(journey.restart_from_scenario)) end end ) commands.add_command( 'journey-update-now', 'Restarts the server with newest version of Journey scenario code right now. Only doable during map selection.', function() local s, _, p = cmd_handler() if s then Functions.restart_server(journey) p('Journey is restarting to apply changes...') end end ) commands.add_command( 'journey-import', 'Sets the journey gamestate to the last exported one.', function() local s, _, p = cmd_handler() if s then Functions.import_journey(journey) p('Journey world settings importing...') end end ) commands.add_command( 'journey-export', 'Exports the journey gamestate to the server', function() local s, _, p = cmd_handler() if s then Functions.export_journey(journey, journey.restart_from_scenario) p('Journey world settings exporting...') end end ) Event.on_init(on_init) Event.on_nth_tick(10, on_nth_tick) Event.add(defines.events.on_chunk_generated, on_chunk_generated) Event.add(defines.events.on_player_joined_game, on_player_joined_game) Event.add(defines.events.on_player_left_game, on_player_left_game) Event.add(defines.events.on_player_changed_position, on_player_changed_position) Event.add(defines.events.on_rocket_launch_ordered, on_rocket_launched) Event.add(defines.events.on_robot_built_entity, on_robot_built_entity) Event.add(defines.events.on_built_entity, on_built_entity) Event.add(defines.events.on_robot_mined_entity, on_robot_mined_entity) Event.add(defines.events.on_player_mined_entity, on_player_mined_entity) Event.add(defines.events.on_entity_died, on_entity_died) Event.add(defines.events.on_entity_damaged, on_entity_damaged) Event.add(defines.events.on_console_chat, on_console_chat) Event.add(defines.events.on_research_finished, on_research_finished) Event.add(events['import'], make_import) Event.add(events['check_import'], check_import)
0
0.948699
1
0.948699
game-dev
MEDIA
0.938033
game-dev
0.972771
1
0.972771
ScutGame/Scut-samples
3,510
Koudai/Server/release/Script/CsScript/GM/GeneralCommand.cs
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using ZyGames.Framework.Cache.Generic; using ZyGames.Framework.Common; using ZyGames.Tianjiexing.Model; using ZyGames.Framework.Game.Runtime; using ZyGames.Tianjiexing.Model.Enum; namespace ZyGames.Tianjiexing.BLL.GM { public class GeneralCommand : TjBaseCommand { protected override void ProcessCmd(string[] args) { int generalID = args.Length > 0 ? args[0].Trim().ToInt() : 1; Process(UserID, generalID); } private void Process(string userID, int generalID) { GeneralInfo generalInfo = new ShareCacheStruct<GeneralInfo>().FindKey(generalID); if (generalInfo != null) { var cacheSet = new PersonalCacheStruct<UserGeneral>(); var usergeneral = cacheSet.FindKey(userID, generalID); if (usergeneral == null) { usergeneral = new UserGeneral() { UserID = userID, GeneralID = generalID, GeneralName = generalInfo.GeneralName, HeadID = generalInfo.HeadID, PicturesID = generalInfo.PicturesID, GeneralLv = generalInfo.GeneralLv, LifeNum = generalInfo.LifeNum, GeneralType = GeneralType.YongBing, CareerID = generalInfo.CareerID, PowerNum = generalInfo.PowerNum, SoulNum = generalInfo.SoulNum, IntellectNum = generalInfo.IntellectNum, TrainingPower = 0, TrainingSoul = 0, TrainingIntellect = 0, AbilityID = generalInfo.AbilityID, Momentum = 25, HitProbability = 85, GeneralStatus = GeneralStatus.DuiWuZhong, Experience1 = 0, Experience2 = 0, CurrExperience = 0, Description = string.Empty, }; cacheSet.Add(usergeneral); } } } } }
0
0.678661
1
0.678661
game-dev
MEDIA
0.57903
game-dev,web-backend
0.654208
1
0.654208
NeotokyoRebuild/neo
2,697
src/game/server/hl2/ai_behavior_functank.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef AI_BEHAVIOR_FUNCTANK_H #define AI_BEHAVIOR_FUNCTANK_H #ifdef _WIN32 #pragma once #endif #include "simtimer.h" #include "ai_behavior.h" #include "func_tank.h" #define AI_FUNCTANK_BEHAVIOR_BUSYTIME 10.0f enum { FUNCTANK_SENTENCE_MOVE_TO_MOUNT = SENTENCE_BASE_BEHAVIOR_INDEX, FUNCTANK_SENTENCE_JUST_MOUNTED, FUNCTANK_SENTENCE_SCAN_FOR_ENEMIES, FUNCTANK_SENTENCE_DISMOUNTING, }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CAI_FuncTankBehavior : public CAI_SimpleBehavior { DECLARE_CLASS( CAI_FuncTankBehavior, CAI_SimpleBehavior ); DEFINE_CUSTOM_SCHEDULE_PROVIDER; DECLARE_DATADESC(); public: // Contructor/Deconstructor CAI_FuncTankBehavior(); ~CAI_FuncTankBehavior(); void UpdateOnRemove(); // Identifier const char *GetName() { return "FuncTank"; } // Schedule bool CanSelectSchedule(); void BeginScheduleSelection(); void EndScheduleSelection(); void PrescheduleThink(); Activity NPC_TranslateActivity( Activity activity ); // Conditions: virtual void GatherConditions(); enum { SCHED_MOVE_TO_FUNCTANK = BaseClass::NEXT_SCHEDULE, SCHED_FIRE_FUNCTANK, SCHED_SCAN_WITH_FUNCTANK, SCHED_FAIL_MOVE_TO_FUNCTANK, }; // Tasks void StartTask( const Task_t *pTask ); void RunTask( const Task_t *pTask ); enum { TASK_GET_PATH_TO_FUNCTANK = BaseClass::NEXT_TASK, TASK_FACE_FUNCTANK, TASK_HOLSTER_WEAPON, TASK_FIRE_FUNCTANK, TASK_SCAN_LEFT_FUNCTANK, TASK_SCAN_RIGHT_FUNCTANK, TASK_FORGET_ABOUT_FUNCTANK, TASK_FUNCTANK_ANNOUNCE_SCAN, }; enum { COND_FUNCTANK_DISMOUNT = BaseClass::NEXT_CONDITION, NEXT_CONDITION, }; // Combat. CBaseEntity *BestEnemy( void ); void Event_Killed( const CTakeDamageInfo &info ); bool HasFuncTank( void ) { return ( m_hFuncTank != NULL ); } void SetFuncTank( CHandle<CFuncTank> hFuncTank ); CFuncTank *GetFuncTank() { return m_hFuncTank; } void AimGun( void ); void Dismount( void ); int OnTakeDamage_Alive( const CTakeDamageInfo &info ); // Time. void SetBusy( float flTime ) { m_flBusyTime = flTime; } bool IsBusy( void ) { return ( gpGlobals->curtime < m_flBusyTime ); } bool IsMounted( void ) { return m_bMounted; } private: // Schedule int SelectSchedule(); private: CHandle<CFuncTank> m_hFuncTank; bool m_bMounted; float m_flBusyTime; bool m_bSpottedPlayerOutOfCover; }; #endif // AI_BEHAVIOR_FUNCTANK_H
0
0.947692
1
0.947692
game-dev
MEDIA
0.89364
game-dev
0.825834
1
0.825834
SlashGames/slash-framework
1,946
Source/Slash.Unity.Common/Source/GUI/ValueEditors/ValueEditorContext.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ValueEditorContext.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Slash.Unity.Common.GUI.ValueEditors { /// <summary> /// Implements the basic methods. /// </summary> public abstract class ValueEditorContext { #region Public Methods and Operators /// <summary> /// Takes the value, tries to cast it to the specified type and returns it. /// </summary> /// <typeparam name="T"> Expected type of value. </typeparam> /// <returns> Value casted to specified type. </returns> /// <exception type="InvalidCastException">Thrown if value isn't of expected type.</exception> public static T GetValue<T>(object objectValue) { return (T)objectValue; } /// <summary> /// Tries to take the value, cast it to the specified type and return it. If value isn't of expected type, false is returned. /// </summary> /// <typeparam name="T"> Expected type of value. </typeparam> /// <param name="objectValue"> Object value. </param> /// <param name="value"> Contains the value if it was casted successful; otherwise the default value of the specified type. </param> /// <returns> True if the value could be successful casted; otherwise, false. </returns> public static bool TryGetValue<T>(object objectValue, out T value) { if (!(objectValue is T)) { value = default(T); return false; } value = (T)objectValue; return true; } #endregion } }
0
0.857305
1
0.857305
game-dev
MEDIA
0.559077
game-dev
0.727902
1
0.727902
oot-pc-port/oot-pc-port
2,218
asm/non_matchings/code/z_bgcheck/func_8003C55C.s
glabel func_8003C55C /* AB36FC 8003C55C 3C014248 */ li $at, 0x42480000 # 0.000000 /* AB3700 8003C560 44811000 */ mtc1 $at, $f2 /* AB3704 8003C564 C4840004 */ lwc1 $f4, 4($a0) /* AB3708 8003C568 C4A00000 */ lwc1 $f0, ($a1) /* AB370C 8003C56C 46022181 */ sub.s $f6, $f4, $f2 /* AB3710 8003C570 4606003C */ c.lt.s $f0, $f6 /* AB3714 8003C574 00000000 */ nop /* AB3718 8003C578 45010022 */ bc1t .L8003C604 /* AB371C 8003C57C 00000000 */ nop /* AB3720 8003C580 C4880010 */ lwc1 $f8, 0x10($a0) /* AB3724 8003C584 46024280 */ add.s $f10, $f8, $f2 /* AB3728 8003C588 4600503C */ c.lt.s $f10, $f0 /* AB372C 8003C58C 00000000 */ nop /* AB3730 8003C590 4501001C */ bc1t .L8003C604 /* AB3734 8003C594 00000000 */ nop /* AB3738 8003C598 C4900008 */ lwc1 $f16, 8($a0) /* AB373C 8003C59C C4A00004 */ lwc1 $f0, 4($a1) /* AB3740 8003C5A0 46028481 */ sub.s $f18, $f16, $f2 /* AB3744 8003C5A4 4612003C */ c.lt.s $f0, $f18 /* AB3748 8003C5A8 00000000 */ nop /* AB374C 8003C5AC 45010015 */ bc1t .L8003C604 /* AB3750 8003C5B0 00000000 */ nop /* AB3754 8003C5B4 C4840014 */ lwc1 $f4, 0x14($a0) /* AB3758 8003C5B8 46022180 */ add.s $f6, $f4, $f2 /* AB375C 8003C5BC 4600303C */ c.lt.s $f6, $f0 /* AB3760 8003C5C0 00000000 */ nop /* AB3764 8003C5C4 4501000F */ bc1t .L8003C604 /* AB3768 8003C5C8 00000000 */ nop /* AB376C 8003C5CC C488000C */ lwc1 $f8, 0xc($a0) /* AB3770 8003C5D0 C4A00008 */ lwc1 $f0, 8($a1) /* AB3774 8003C5D4 46024281 */ sub.s $f10, $f8, $f2 /* AB3778 8003C5D8 460A003C */ c.lt.s $f0, $f10 /* AB377C 8003C5DC 00000000 */ nop /* AB3780 8003C5E0 45010008 */ bc1t .L8003C604 /* AB3784 8003C5E4 00000000 */ nop /* AB3788 8003C5E8 C4900018 */ lwc1 $f16, 0x18($a0) /* AB378C 8003C5EC 24020001 */ li $v0, 1 /* AB3790 8003C5F0 46028480 */ add.s $f18, $f16, $f2 /* AB3794 8003C5F4 4600903C */ c.lt.s $f18, $f0 /* AB3798 8003C5F8 00000000 */ nop /* AB379C 8003C5FC 45000003 */ bc1f .L8003C60C /* AB37A0 8003C600 00000000 */ nop .L8003C604: /* AB37A4 8003C604 03E00008 */ jr $ra /* AB37A8 8003C608 00001025 */ move $v0, $zero .L8003C60C: /* AB37AC 8003C60C 03E00008 */ jr $ra /* AB37B0 8003C610 00000000 */ nop
0
0.622148
1
0.622148
game-dev
MEDIA
0.68258
game-dev,embedded-firmware
0.810292
1
0.810292
mdparker/Derelict3
35,599
import/derelict/sdl2/sdl.d
/* Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module derelict.sdl2.sdl; public { import derelict.sdl2.types; import derelict.sdl2.functions; } private { import derelict.util.loader; import derelict.util.system; static if(Derelict_OS_Windows) enum libNames = "SDL2.dll"; else static if(Derelict_OS_Mac) enum libNames = "/usr/local/lib/libSDL2.dylib, ../Frameworks/SDL2.framework/SDL2, /Library/Frameworks/SDL2.framework/SDL2, /System/Library/Frameworks/SDL2.framework/SDL2"; else static if(Derelict_OS_Posix) enum libNames = "libSDL2.so, libSDL2-2.0.so, libSDL2-2.0.so.0, /usr/local/lib/libSDL2.so, /usr/local/lib/libSDL2-2.0.so, /usr/local/lib/libSDL2-2.0.so.0"; else static assert(0, "Need to implement SDL2 libNames for this operating system."); } /* This function is not part of the public interface, but SDL expects it to be called before any subsystems have been intiailized. Normally, this happens via linking with libSDLmain, but since that doesn't happen when using Derelict, then the loader must load this function and call it before the load method returns. Otherwise, bad things can happen. */ private extern(C) alias nothrow void function() da_SDL_SetMainReady; class DerelictSDL2Loader : SharedLibLoader { protected { override void loadSymbols() { bindFunc(cast(void**)&SDL_Init, "SDL_Init"); bindFunc(cast(void**)&SDL_InitSubSystem, "SDL_InitSubSystem"); bindFunc(cast(void**)&SDL_QuitSubSystem, "SDL_QuitSubSystem"); bindFunc(cast(void**)&SDL_WasInit, "SDL_WasInit"); bindFunc(cast(void**)&SDL_Quit, "SDL_Quit"); bindFunc(cast(void**)&SDL_GetNumAudioDrivers, "SDL_GetNumAudioDrivers"); bindFunc(cast(void**)&SDL_GetAudioDriver, "SDL_GetAudioDriver"); bindFunc(cast(void**)&SDL_AudioInit, "SDL_AudioInit"); bindFunc(cast(void**)&SDL_AudioQuit, "SDL_AudioQuit"); bindFunc(cast(void**)&SDL_GetCurrentAudioDriver, "SDL_GetCurrentAudioDriver"); bindFunc(cast(void**)&SDL_OpenAudio, "SDL_OpenAudio"); bindFunc(cast(void**)&SDL_GetNumAudioDevices, "SDL_GetNumAudioDevices"); bindFunc(cast(void**)&SDL_GetAudioDeviceName, "SDL_GetAudioDeviceName"); bindFunc(cast(void**)&SDL_OpenAudioDevice, "SDL_OpenAudioDevice"); bindFunc(cast(void**)&SDL_GetAudioStatus, "SDL_GetAudioStatus"); bindFunc(cast(void**)&SDL_GetAudioDeviceStatus, "SDL_GetAudioDeviceStatus"); bindFunc(cast(void**)&SDL_PauseAudio, "SDL_PauseAudio"); bindFunc(cast(void**)&SDL_PauseAudioDevice, "SDL_PauseAudioDevice"); bindFunc(cast(void**)&SDL_LoadWAV_RW, "SDL_LoadWAV_RW"); bindFunc(cast(void**)&SDL_FreeWAV, "SDL_FreeWAV"); bindFunc(cast(void**)&SDL_BuildAudioCVT, "SDL_BuildAudioCVT"); bindFunc(cast(void**)&SDL_ConvertAudio, "SDL_ConvertAudio"); bindFunc(cast(void**)&SDL_MixAudio, "SDL_MixAudio"); bindFunc(cast(void**)&SDL_MixAudioFormat, "SDL_MixAudioFormat"); bindFunc(cast(void**)&SDL_LockAudio, "SDL_LockAudio"); bindFunc(cast(void**)&SDL_LockAudioDevice, "SDL_LockAudioDevice"); bindFunc(cast(void**)&SDL_UnlockAudio, "SDL_UnlockAudio"); bindFunc(cast(void**)&SDL_UnlockAudioDevice, "SDL_UnlockAudioDevice"); bindFunc(cast(void**)&SDL_CloseAudio, "SDL_CloseAudio"); bindFunc(cast(void**)&SDL_CloseAudioDevice, "SDL_CloseAudioDevice"); // bindFunc(cast(void**)&SDL_AudioDeviceConnected, "SDL_AudioDeviceConnected"); bindFunc(cast(void**)&SDL_SetClipboardText, "SDL_SetClipboardText"); bindFunc(cast(void**)&SDL_GetClipboardText, "SDL_GetClipboardText"); bindFunc(cast(void**)&SDL_HasClipboardText, "SDL_HasClipboardText"); bindFunc(cast(void**)&SDL_GetCPUCount, "SDL_GetCPUCount"); bindFunc(cast(void**)&SDL_GetCPUCacheLineSize, "SDL_GetCPUCacheLineSize"); bindFunc(cast(void**)&SDL_HasRDTSC, "SDL_HasRDTSC"); bindFunc(cast(void**)&SDL_HasAltiVec, "SDL_HasAltiVec"); bindFunc(cast(void**)&SDL_HasMMX, "SDL_HasMMX"); bindFunc(cast(void**)&SDL_Has3DNow, "SDL_Has3DNow"); bindFunc(cast(void**)&SDL_HasSSE, "SDL_HasSSE"); bindFunc(cast(void**)&SDL_HasSSE2, "SDL_HasSSE2"); bindFunc(cast(void**)&SDL_HasSSE3, "SDL_HasSSE3"); bindFunc(cast(void**)&SDL_HasSSE41, "SDL_HasSSE41"); bindFunc(cast(void**)&SDL_HasSSE42, "SDL_HasSSE42"); bindFunc(cast(void**)&SDL_GetSystemRAM, "SDL_GetSystemRAM"); bindFunc(cast(void**)&SDL_SetError, "SDL_SetError"); bindFunc(cast(void**)&SDL_GetError, "SDL_GetError"); bindFunc(cast(void**)&SDL_ClearError, "SDL_ClearError"); bindFunc(cast(void**)&SDL_PumpEvents, "SDL_PumpEvents"); bindFunc(cast(void**)&SDL_PeepEvents, "SDL_PeepEvents"); bindFunc(cast(void**)&SDL_HasEvent, "SDL_HasEvent"); bindFunc(cast(void**)&SDL_HasEvents, "SDL_HasEvents"); bindFunc(cast(void**)&SDL_FlushEvent, "SDL_FlushEvent"); bindFunc(cast(void**)&SDL_FlushEvents, "SDL_FlushEvents"); bindFunc(cast(void**)&SDL_PollEvent, "SDL_PollEvent"); bindFunc(cast(void**)&SDL_WaitEvent, "SDL_WaitEvent"); bindFunc(cast(void**)&SDL_WaitEventTimeout, "SDL_WaitEventTimeout"); bindFunc(cast(void**)&SDL_PushEvent, "SDL_PushEvent"); bindFunc(cast(void**)&SDL_SetEventFilter, "SDL_SetEventFilter"); bindFunc(cast(void**)&SDL_GetEventFilter, "SDL_GetEventFilter"); bindFunc(cast(void**)&SDL_AddEventWatch, "SDL_AddEventWatch"); bindFunc(cast(void**)&SDL_DelEventWatch, "SDL_DelEventWatch"); bindFunc(cast(void**)&SDL_FilterEvents, "SDL_FilterEvents"); bindFunc(cast(void**)&SDL_EventState, "SDL_EventState"); bindFunc(cast(void**)&SDL_RegisterEvents, "SDL_RegisterEvents"); bindFunc(cast(void**)&SDL_GameControllerAddMapping, "SDL_GameControllerAddMapping"); bindFunc(cast(void**)&SDL_GameControllerMappingForGUID, "SDL_GameControllerMappingForGUID"); bindFunc(cast(void**)&SDL_GameControllerMapping, "SDL_GameControllerMapping"); bindFunc(cast(void**)&SDL_IsGameController, "SDL_IsGameController"); bindFunc(cast(void**)&SDL_GameControllerNameForIndex, "SDL_GameControllerNameForIndex"); bindFunc(cast(void**)&SDL_GameControllerOpen, "SDL_GameControllerOpen"); bindFunc(cast(void**)&SDL_GameControllerName, "SDL_GameControllerName"); bindFunc(cast(void**)&SDL_GameControllerGetAttached, "SDL_GameControllerGetAttached"); bindFunc(cast(void**)&SDL_GameControllerGetJoystick, "SDL_GameControllerGetJoystick"); bindFunc(cast(void**)&SDL_GameControllerEventState, "SDL_GameControllerEventState"); bindFunc(cast(void**)&SDL_GameControllerUpdate, "SDL_GameControllerUpdate"); bindFunc(cast(void**)&SDL_GameControllerGetAxisFromString, "SDL_GameControllerGetAxisFromString"); bindFunc(cast(void**)&SDL_GameControllerGetStringForAxis, "SDL_GameControllerGetStringForAxis"); bindFunc(cast(void**)&SDL_GameControllerGetBindForAxis, "SDL_GameControllerGetBindForAxis"); bindFunc(cast(void**)&SDL_GameControllerGetAxis, "SDL_GameControllerGetAxis"); bindFunc(cast(void**)&SDL_GameControllerGetButtonFromString, "SDL_GameControllerGetButtonFromString"); bindFunc(cast(void**)&SDL_GameControllerGetStringForButton, "SDL_GameControllerGetStringForButton"); bindFunc(cast(void**)&SDL_GameControllerGetBindForButton, "SDL_GameControllerGetBindForButton"); bindFunc(cast(void**)&SDL_GameControllerGetButton, "SDL_GameControllerGetButton"); bindFunc(cast(void**)&SDL_GameControllerClose, "SDL_GameControllerClose"); bindFunc(cast(void**)&SDL_RecordGesture, "SDL_RecordGesture"); bindFunc(cast(void**)&SDL_SaveAllDollarTemplates, "SDL_SaveAllDollarTemplates"); bindFunc(cast(void**)&SDL_SaveDollarTemplate, "SDL_SaveDollarTemplate"); bindFunc(cast(void**)&SDL_LoadDollarTemplates, "SDL_LoadDollarTemplates"); bindFunc(cast(void**)&SDL_NumHaptics, "SDL_NumHaptics"); bindFunc(cast(void**)&SDL_HapticName, "SDL_HapticName"); bindFunc(cast(void**)&SDL_HapticOpen, "SDL_HapticOpen"); bindFunc(cast(void**)&SDL_HapticOpened, "SDL_HapticOpened"); bindFunc(cast(void**)&SDL_HapticIndex, "SDL_HapticIndex"); bindFunc(cast(void**)&SDL_MouseIsHaptic, "SDL_MouseIsHaptic"); bindFunc(cast(void**)&SDL_HapticOpenFromMouse, "SDL_HapticOpenFromMouse"); bindFunc(cast(void**)&SDL_JoystickIsHaptic, "SDL_JoystickIsHaptic"); bindFunc(cast(void**)&SDL_HapticOpenFromJoystick, "SDL_HapticOpenFromJoystick"); bindFunc(cast(void**)&SDL_HapticClose, "SDL_HapticClose"); bindFunc(cast(void**)&SDL_HapticNumEffects, "SDL_HapticNumEffects"); bindFunc(cast(void**)&SDL_HapticNumEffectsPlaying, "SDL_HapticNumEffectsPlaying"); bindFunc(cast(void**)&SDL_HapticQuery, "SDL_HapticQuery"); bindFunc(cast(void**)&SDL_HapticNumAxes, "SDL_HapticNumAxes"); bindFunc(cast(void**)&SDL_HapticEffectSupported, "SDL_HapticEffectSupported"); bindFunc(cast(void**)&SDL_HapticNewEffect, "SDL_HapticNewEffect"); bindFunc(cast(void**)&SDL_HapticUpdateEffect, "SDL_HapticUpdateEffect"); bindFunc(cast(void**)&SDL_HapticRunEffect, "SDL_HapticRunEffect"); bindFunc(cast(void**)&SDL_HapticStopEffect, "SDL_HapticStopEffect"); bindFunc(cast(void**)&SDL_HapticDestroyEffect, "SDL_HapticDestroyEffect"); bindFunc(cast(void**)&SDL_HapticGetEffectStatus, "SDL_HapticGetEffectStatus"); bindFunc(cast(void**)&SDL_HapticSetGain, "SDL_HapticSetGain"); bindFunc(cast(void**)&SDL_HapticSetAutocenter, "SDL_HapticSetAutocenter"); bindFunc(cast(void**)&SDL_HapticPause, "SDL_HapticPause"); bindFunc(cast(void**)&SDL_HapticUnpause, "SDL_HapticUnpause"); bindFunc(cast(void**)&SDL_HapticStopAll, "SDL_HapticStopAll"); bindFunc(cast(void**)&SDL_HapticRumbleSupported, "SDL_HapticRumbleSupported"); bindFunc(cast(void**)&SDL_HapticRumbleInit, "SDL_HapticRumbleInit"); bindFunc(cast(void**)&SDL_HapticRumblePlay, "SDL_HapticRumblePlay"); bindFunc(cast(void**)&SDL_HapticRumbleStop, "SDL_HapticRumbleStop"); bindFunc(cast(void**)&SDL_SetHintWithPriority, "SDL_SetHintWithPriority"); bindFunc(cast(void**)&SDL_SetHint, "SDL_SetHint"); bindFunc(cast(void**)&SDL_GetHint, "SDL_GetHint"); bindFunc(cast(void**)&SDL_AddHintCallback, "SDL_AddHintCallback"); bindFunc(cast(void**)&SDL_DelHintCallback, "SDL_DelHintCallback"); bindFunc(cast(void**)&SDL_ClearHints, "SDL_ClearHints"); // bindFunc(cast(void**)&SDL_RedetectInputDevices, "SDL_RedetectInputDevices"); // bindFunc(cast(void**)&SDL_GetNumInputDevices, "SDL_GetNumInputDevices"); // bindFunc(cast(void**)&SDL_GetInputDeviceName, "SDL_GetInputDeviceName"); // bindFunc(cast(void**)&SDL_IsDeviceDisconnected, "SDL_IsDeviceDisconnected"); bindFunc(cast(void**)&SDL_NumJoysticks, "SDL_NumJoysticks"); bindFunc(cast(void**)&SDL_JoystickNameForIndex, "SDL_JoystickNameForIndex"); bindFunc(cast(void**)&SDL_JoystickOpen, "SDL_JoystickOpen"); bindFunc(cast(void**)&SDL_JoystickName, "SDL_JoystickName"); bindFunc(cast(void**)&SDL_JoystickGetDeviceGUID, "SDL_JoystickGetDeviceGUID"); bindFunc(cast(void**)&SDL_JoystickGetGUID, "SDL_JoystickGetGUID"); bindFunc(cast(void**)&SDL_JoystickGetGUIDString, "SDL_JoystickGetGUIDString"); bindFunc(cast(void**)&SDL_JoystickGetGUIDFromString, "SDL_JoystickGetGUIDFromString"); bindFunc(cast(void**)&SDL_JoystickGetAttached, "SDL_JoystickGetAttached"); bindFunc(cast(void**)&SDL_JoystickInstanceID, "SDL_JoystickInstanceID"); bindFunc(cast(void**)&SDL_JoystickNumAxes, "SDL_JoystickNumAxes"); bindFunc(cast(void**)&SDL_JoystickNumBalls, "SDL_JoystickNumBalls"); bindFunc(cast(void**)&SDL_JoystickNumHats, "SDL_JoystickNumHats"); bindFunc(cast(void**)&SDL_JoystickNumButtons, "SDL_JoystickNumButtons"); bindFunc(cast(void**)&SDL_JoystickUpdate, "SDL_JoystickUpdate"); bindFunc(cast(void**)&SDL_JoystickEventState, "SDL_JoystickEventState"); bindFunc(cast(void**)&SDL_JoystickGetAxis, "SDL_JoystickGetAxis"); bindFunc(cast(void**)&SDL_JoystickGetHat, "SDL_JoystickGetHat"); bindFunc(cast(void**)&SDL_JoystickGetBall, "SDL_JoystickGetBall"); bindFunc(cast(void**)&SDL_JoystickGetButton, "SDL_JoystickGetButton"); bindFunc(cast(void**)&SDL_JoystickClose, "SDL_JoystickClose"); bindFunc(cast(void**)&SDL_GetKeyboardFocus, "SDL_GetKeyboardFocus"); bindFunc(cast(void**)&SDL_GetKeyboardState, "SDL_GetKeyboardState"); bindFunc(cast(void**)&SDL_GetModState, "SDL_GetModState"); bindFunc(cast(void**)&SDL_SetModState, "SDL_SetModState"); bindFunc(cast(void**)&SDL_GetKeyFromScancode, "SDL_GetKeyFromScancode"); bindFunc(cast(void**)&SDL_GetScancodeFromKey, "SDL_GetScancodeFromKey"); bindFunc(cast(void**)&SDL_GetScancodeName, "SDL_GetScancodeName"); bindFunc(cast(void**)&SDL_GetScancodeFromName, "SDL_GetScancodeFromName"); bindFunc(cast(void**)&SDL_GetKeyName, "SDL_GetKeyName"); bindFunc(cast(void**)&SDL_GetKeyFromName, "SDL_GetKeyFromName"); bindFunc(cast(void**)&SDL_StartTextInput, "SDL_StartTextInput"); bindFunc(cast(void**)&SDL_IsTextInputActive, "SDL_IsTextInputActive"); bindFunc(cast(void**)&SDL_StopTextInput, "SDL_StopTextInput"); bindFunc(cast(void**)&SDL_SetTextInputRect, "SDL_SetTextInputRect"); bindFunc(cast(void**)&SDL_HasScreenKeyboardSupport, "SDL_HasScreenKeyboardSupport"); bindFunc(cast(void**)&SDL_IsScreenKeyboardShown, "SDL_IsScreenKeyboardShown"); bindFunc(cast(void**)&SDL_LoadObject, "SDL_LoadObject"); bindFunc(cast(void**)&SDL_LoadFunction, "SDL_LoadFunction"); bindFunc(cast(void**)&SDL_UnloadObject, "SDL_UnloadObject"); bindFunc(cast(void**)&SDL_LogSetAllPriority, "SDL_LogSetAllPriority"); bindFunc(cast(void**)&SDL_LogSetPriority, "SDL_LogSetPriority"); bindFunc(cast(void**)&SDL_LogGetPriority, "SDL_LogGetPriority"); bindFunc(cast(void**)&SDL_LogResetPriorities, "SDL_LogResetPriorities"); bindFunc(cast(void**)&SDL_Log, "SDL_Log"); bindFunc(cast(void**)&SDL_LogVerbose, "SDL_LogVerbose"); bindFunc(cast(void**)&SDL_LogDebug, "SDL_LogDebug"); bindFunc(cast(void**)&SDL_LogInfo, "SDL_LogInfo"); bindFunc(cast(void**)&SDL_LogWarn, "SDL_LogWarn"); bindFunc(cast(void**)&SDL_LogError, "SDL_LogError"); bindFunc(cast(void**)&SDL_LogCritical, "SDL_LogCritical"); bindFunc(cast(void**)&SDL_LogMessage, "SDL_LogMessage"); bindFunc(cast(void**)&SDL_LogMessageV, "SDL_LogMessageV"); bindFunc(cast(void**)&SDL_LogGetOutputFunction, "SDL_LogGetOutputFunction"); bindFunc(cast(void**)&SDL_LogSetOutputFunction, "SDL_LogSetOutputFunction"); bindFunc(cast(void**)&SDL_ShowMessageBox, "SDL_ShowMessageBox"); bindFunc(cast(void**)&SDL_ShowSimpleMessageBox, "SDL_ShowSimpleMessageBox"); bindFunc(cast(void**)&SDL_GetMouseFocus, "SDL_GetMouseFocus"); bindFunc(cast(void**)&SDL_GetMouseState, "SDL_GetMouseState"); bindFunc(cast(void**)&SDL_GetRelativeMouseState, "SDL_GetRelativeMouseState"); bindFunc(cast(void**)&SDL_WarpMouseInWindow, "SDL_WarpMouseInWindow"); bindFunc(cast(void**)&SDL_SetRelativeMouseMode, "SDL_SetRelativeMouseMode"); bindFunc(cast(void**)&SDL_GetRelativeMouseMode, "SDL_GetRelativeMouseMode"); bindFunc(cast(void**)&SDL_CreateCursor, "SDL_CreateCursor"); bindFunc(cast(void**)&SDL_CreateColorCursor, "SDL_CreateColorCursor"); bindFunc(cast(void**)&SDL_CreateSystemCursor, "SDL_CreateSystemCursor"); bindFunc(cast(void**)&SDL_SetCursor, "SDL_SetCursor"); bindFunc(cast(void**)&SDL_GetCursor, "SDL_GetCursor"); bindFunc(cast(void**)&SDL_FreeCursor, "SDL_FreeCursor"); bindFunc(cast(void**)&SDL_ShowCursor, "SDL_ShowCursor"); bindFunc(cast(void**)&SDL_GetPixelFormatName, "SDL_GetPixelFormatName"); bindFunc(cast(void**)&SDL_PixelFormatEnumToMasks, "SDL_PixelFormatEnumToMasks"); bindFunc(cast(void**)&SDL_MasksToPixelFormatEnum, "SDL_MasksToPixelFormatEnum"); bindFunc(cast(void**)&SDL_AllocFormat, "SDL_AllocFormat"); bindFunc(cast(void**)&SDL_FreeFormat, "SDL_FreeFormat"); bindFunc(cast(void**)&SDL_AllocPalette, "SDL_AllocPalette"); bindFunc(cast(void**)&SDL_SetPixelFormatPalette, "SDL_SetPixelFormatPalette"); bindFunc(cast(void**)&SDL_SetPaletteColors, "SDL_SetPaletteColors"); bindFunc(cast(void**)&SDL_FreePalette, "SDL_FreePalette"); bindFunc(cast(void**)&SDL_MapRGB, "SDL_MapRGB"); bindFunc(cast(void**)&SDL_MapRGBA, "SDL_MapRGBA"); bindFunc(cast(void**)&SDL_GetRGB, "SDL_GetRGB"); bindFunc(cast(void**)&SDL_GetRGBA, "SDL_GetRGBA"); bindFunc(cast(void**)&SDL_CalculateGammaRamp, "SDL_CalculateGammaRamp"); bindFunc(cast(void**)&SDL_GetPlatform, "SDL_GetPlatform"); bindFunc(cast(void**)&SDL_GetPowerInfo, "SDL_GetPowerInfo"); bindFunc(cast(void**)&SDL_HasIntersection, "SDL_HasIntersection"); bindFunc(cast(void**)&SDL_IntersectRect, "SDL_IntersectRect"); bindFunc(cast(void**)&SDL_UnionRect, "SDL_UnionRect"); bindFunc(cast(void**)&SDL_EnclosePoints, "SDL_EnclosePoints"); bindFunc(cast(void**)&SDL_IntersectRectAndLine, "SDL_IntersectRectAndLine"); bindFunc(cast(void**)&SDL_GetNumRenderDrivers, "SDL_GetNumRenderDrivers"); bindFunc(cast(void**)&SDL_GetRenderDriverInfo, "SDL_GetRenderDriverInfo"); bindFunc(cast(void**)&SDL_CreateWindowAndRenderer, "SDL_CreateWindowAndRenderer"); bindFunc(cast(void**)&SDL_CreateRenderer, "SDL_CreateRenderer"); bindFunc(cast(void**)&SDL_CreateSoftwareRenderer, "SDL_CreateSoftwareRenderer"); bindFunc(cast(void**)&SDL_GetRendererInfo, "SDL_GetRendererInfo"); bindFunc(cast(void**)&SDL_CreateTexture, "SDL_CreateTexture"); bindFunc(cast(void**)&SDL_CreateTextureFromSurface, "SDL_CreateTextureFromSurface"); bindFunc(cast(void**)&SDL_QueryTexture, "SDL_QueryTexture"); bindFunc(cast(void**)&SDL_SetTextureColorMod, "SDL_SetTextureColorMod"); bindFunc(cast(void**)&SDL_GetTextureColorMod, "SDL_GetTextureColorMod"); bindFunc(cast(void**)&SDL_SetTextureAlphaMod, "SDL_SetTextureAlphaMod"); bindFunc(cast(void**)&SDL_GetTextureAlphaMod, "SDL_GetTextureAlphaMod"); bindFunc(cast(void**)&SDL_SetTextureBlendMode, "SDL_SetTextureBlendMode"); bindFunc(cast(void**)&SDL_GetTextureBlendMode, "SDL_GetTextureBlendMode"); bindFunc(cast(void**)&SDL_UpdateTexture, "SDL_UpdateTexture"); bindFunc(cast(void**)&SDL_UpdateYUVTexture, "SDL_UpdateYUVTexture"); bindFunc(cast(void**)&SDL_LockTexture, "SDL_LockTexture"); bindFunc(cast(void**)&SDL_UnlockTexture, "SDL_UnlockTexture"); bindFunc(cast(void**)&SDL_RenderTargetSupported, "SDL_RenderTargetSupported"); bindFunc(cast(void**)&SDL_SetRenderTarget, "SDL_SetRenderTarget"); bindFunc(cast(void**)&SDL_GetRenderTarget, "SDL_GetRenderTarget"); bindFunc(cast(void**)&SDL_RenderSetLogicalSize, "SDL_RenderSetLogicalSize"); bindFunc(cast(void**)&SDL_RenderGetLogicalSize, "SDL_RenderGetLogicalSize"); bindFunc(cast(void**)&SDL_RenderSetViewport, "SDL_RenderSetViewport"); bindFunc(cast(void**)&SDL_RenderGetViewport, "SDL_RenderGetViewport"); bindFunc(cast(void**)&SDL_RenderSetScale, "SDL_RenderSetScale"); bindFunc(cast(void**)&SDL_RenderGetScale, "SDL_RenderGetScale"); bindFunc(cast(void**)&SDL_SetRenderDrawColor, "SDL_SetRenderDrawColor"); bindFunc(cast(void**)&SDL_GetRenderDrawColor, "SDL_GetRenderDrawColor"); bindFunc(cast(void**)&SDL_SetRenderDrawBlendMode, "SDL_SetRenderDrawBlendMode"); bindFunc(cast(void**)&SDL_GetRenderDrawBlendMode, "SDL_GetRenderDrawBlendMode"); bindFunc(cast(void**)&SDL_RenderClear, "SDL_RenderClear"); bindFunc(cast(void**)&SDL_RenderDrawPoint, "SDL_RenderDrawPoint"); bindFunc(cast(void**)&SDL_RenderDrawPoints, "SDL_RenderDrawPoints"); bindFunc(cast(void**)&SDL_RenderDrawLine, "SDL_RenderDrawLine"); bindFunc(cast(void**)&SDL_RenderDrawLines, "SDL_RenderDrawLines"); bindFunc(cast(void**)&SDL_RenderDrawRect, "SDL_RenderDrawRect"); bindFunc(cast(void**)&SDL_RenderDrawRects, "SDL_RenderDrawRects"); bindFunc(cast(void**)&SDL_RenderFillRect, "SDL_RenderFillRect"); bindFunc(cast(void**)&SDL_RenderFillRects, "SDL_RenderFillRects"); bindFunc(cast(void**)&SDL_RenderCopy, "SDL_RenderCopy"); bindFunc(cast(void**)&SDL_RenderCopyEx, "SDL_RenderCopyEx"); bindFunc(cast(void**)&SDL_RenderReadPixels, "SDL_RenderReadPixels"); bindFunc(cast(void**)&SDL_RenderPresent, "SDL_RenderPresent"); bindFunc(cast(void**)&SDL_DestroyTexture, "SDL_DestroyTexture"); bindFunc(cast(void**)&SDL_DestroyRenderer, "SDL_DestroyRenderer"); bindFunc(cast(void**)&SDL_GL_BindTexture, "SDL_GL_BindTexture"); bindFunc(cast(void**)&SDL_GL_UnbindTexture, "SDL_GL_UnbindTexture"); bindFunc(cast(void**)&SDL_RWFromFile, "SDL_RWFromFile"); bindFunc(cast(void**)&SDL_RWFromFP, "SDL_RWFromFP"); bindFunc(cast(void**)&SDL_RWFromMem, "SDL_RWFromMem"); bindFunc(cast(void**)&SDL_RWFromConstMem, "SDL_RWFromConstMem"); bindFunc(cast(void**)&SDL_AllocRW, "SDL_AllocRW"); bindFunc(cast(void**)&SDL_FreeRW, "SDL_FreeRW"); bindFunc(cast(void**)&SDL_ReadU8, "SDL_ReadU8"); bindFunc(cast(void**)&SDL_ReadLE16, "SDL_ReadLE16"); bindFunc(cast(void**)&SDL_ReadBE16, "SDL_ReadBE16"); bindFunc(cast(void**)&SDL_ReadLE32, "SDL_ReadLE32"); bindFunc(cast(void**)&SDL_ReadBE32, "SDL_ReadBE32"); bindFunc(cast(void**)&SDL_ReadLE64, "SDL_ReadLE64"); bindFunc(cast(void**)&SDL_ReadBE64, "SDL_ReadBE64"); bindFunc(cast(void**)&SDL_WriteU8, "SDL_WriteU8"); bindFunc(cast(void**)&SDL_WriteLE16, "SDL_WriteLE16"); bindFunc(cast(void**)&SDL_WriteBE16, "SDL_WriteBE16"); bindFunc(cast(void**)&SDL_WriteLE32, "SDL_WriteLE32"); bindFunc(cast(void**)&SDL_WriteBE32, "SDL_WriteBE32"); bindFunc(cast(void**)&SDL_WriteLE64, "SDL_WriteLE64"); bindFunc(cast(void**)&SDL_WriteBE64, "SDL_WriteBE64"); bindFunc(cast(void**)&SDL_CreateShapedWindow, "SDL_CreateShapedWindow"); bindFunc(cast(void**)&SDL_IsShapedWindow, "SDL_IsShapedWindow"); bindFunc(cast(void**)&SDL_SetWindowShape, "SDL_SetWindowShape"); bindFunc(cast(void**)&SDL_GetShapedWindowMode, "SDL_GetShapedWindowMode"); bindFunc(cast(void**)&SDL_CreateRGBSurface, "SDL_CreateRGBSurface"); bindFunc(cast(void**)&SDL_CreateRGBSurfaceFrom, "SDL_CreateRGBSurfaceFrom"); bindFunc(cast(void**)&SDL_FreeSurface, "SDL_FreeSurface"); bindFunc(cast(void**)&SDL_SetSurfacePalette, "SDL_SetSurfacePalette"); bindFunc(cast(void**)&SDL_LockSurface, "SDL_LockSurface"); bindFunc(cast(void**)&SDL_UnlockSurface, "SDL_UnlockSurface"); bindFunc(cast(void**)&SDL_LoadBMP_RW, "SDL_LoadBMP_RW"); bindFunc(cast(void**)&SDL_SaveBMP_RW, "SDL_SaveBMP_RW"); bindFunc(cast(void**)&SDL_SetSurfaceRLE, "SDL_SetSurfaceRLE"); bindFunc(cast(void**)&SDL_SetColorKey, "SDL_SetColorKey"); bindFunc(cast(void**)&SDL_GetColorKey, "SDL_GetColorKey"); bindFunc(cast(void**)&SDL_SetSurfaceColorMod, "SDL_SetSurfaceColorMod"); bindFunc(cast(void**)&SDL_GetSurfaceColorMod, "SDL_GetSurfaceColorMod"); bindFunc(cast(void**)&SDL_SetSurfaceAlphaMod, "SDL_SetSurfaceAlphaMod"); bindFunc(cast(void**)&SDL_GetSurfaceAlphaMod, "SDL_GetSurfaceAlphaMod"); bindFunc(cast(void**)&SDL_SetSurfaceBlendMode, "SDL_SetSurfaceBlendMode"); bindFunc(cast(void**)&SDL_GetSurfaceBlendMode, "SDL_GetSurfaceBlendMode"); bindFunc(cast(void**)&SDL_SetClipRect, "SDL_SetClipRect"); bindFunc(cast(void**)&SDL_GetClipRect, "SDL_GetClipRect"); bindFunc(cast(void**)&SDL_ConvertSurface, "SDL_ConvertSurface"); bindFunc(cast(void**)&SDL_ConvertSurfaceFormat, "SDL_ConvertSurfaceFormat"); bindFunc(cast(void**)&SDL_ConvertPixels, "SDL_ConvertPixels"); bindFunc(cast(void**)&SDL_FillRect, "SDL_FillRect"); bindFunc(cast(void**)&SDL_FillRects, "SDL_FillRects"); bindFunc(cast(void**)&SDL_UpperBlit, "SDL_UpperBlit"); bindFunc(cast(void**)&SDL_LowerBlit, "SDL_LowerBlit"); bindFunc(cast(void**)&SDL_SoftStretch, "SDL_SoftStretch"); bindFunc(cast(void**)&SDL_UpperBlitScaled, "SDL_UpperBlitScaled"); bindFunc(cast(void**)&SDL_LowerBlitScaled, "SDL_LowerBlitScaled"); bindFunc(cast(void**)&SDL_GetTicks, "SDL_GetTicks"); bindFunc(cast(void**)&SDL_GetPerformanceCounter, "SDL_GetPerformanceCounter"); bindFunc(cast(void**)&SDL_GetPerformanceFrequency, "SDL_GetPerformanceFrequency"); bindFunc(cast(void**)&SDL_Delay, "SDL_Delay"); bindFunc(cast(void**)&SDL_AddTimer, "SDL_AddTimer"); bindFunc(cast(void**)&SDL_GetNumTouchDevices, "SDL_GetNumTouchDevices"); bindFunc(cast(void**)&SDL_GetTouchDevice, "SDL_GetTouchDevice"); bindFunc(cast(void**)&SDL_GetNumTouchFingers, "SDL_GetNumTouchFingers"); bindFunc(cast(void**)&SDL_GetTouchFinger, "SDL_GetTouchFinger"); bindFunc(cast(void**)&SDL_GetVersion, "SDL_GetVersion"); bindFunc(cast(void**)&SDL_GetRevision, "SDL_GetRevision"); bindFunc(cast(void**)&SDL_GetRevisionNumber, "SDL_GetRevisionNumber"); bindFunc(cast(void**)&SDL_GetNumVideoDrivers, "SDL_GetNumVideoDrivers"); bindFunc(cast(void**)&SDL_GetVideoDriver, "SDL_GetVideoDriver"); bindFunc(cast(void**)&SDL_VideoInit, "SDL_VideoInit"); bindFunc(cast(void**)&SDL_VideoQuit, "SDL_VideoQuit"); bindFunc(cast(void**)&SDL_GetCurrentVideoDriver, "SDL_GetCurrentVideoDriver"); bindFunc(cast(void**)&SDL_GetNumVideoDisplays, "SDL_GetNumVideoDisplays"); bindFunc(cast(void**)&SDL_GetDisplayName, "SDL_GetDisplayName"); bindFunc(cast(void**)&SDL_GetDisplayBounds, "SDL_GetDisplayBounds"); bindFunc(cast(void**)&SDL_GetNumDisplayModes, "SDL_GetNumDisplayModes"); bindFunc(cast(void**)&SDL_GetDisplayMode, "SDL_GetDisplayMode"); bindFunc(cast(void**)&SDL_GetDesktopDisplayMode, "SDL_GetDesktopDisplayMode"); bindFunc(cast(void**)&SDL_GetCurrentDisplayMode, "SDL_GetCurrentDisplayMode"); bindFunc(cast(void**)&SDL_GetClosestDisplayMode, "SDL_GetClosestDisplayMode"); bindFunc(cast(void**)&SDL_GetWindowDisplayIndex, "SDL_GetWindowDisplayIndex"); bindFunc(cast(void**)&SDL_SetWindowDisplayMode, "SDL_SetWindowDisplayMode"); bindFunc(cast(void**)&SDL_GetWindowDisplayMode, "SDL_GetWindowDisplayMode"); bindFunc(cast(void**)&SDL_GetWindowPixelFormat, "SDL_GetWindowPixelFormat"); bindFunc(cast(void**)&SDL_CreateWindow, "SDL_CreateWindow"); bindFunc(cast(void**)&SDL_CreateWindowFrom, "SDL_CreateWindowFrom"); bindFunc(cast(void**)&SDL_GetWindowID, "SDL_GetWindowID"); bindFunc(cast(void**)&SDL_GetWindowFromID, "SDL_GetWindowFromID"); bindFunc(cast(void**)&SDL_GetWindowFlags, "SDL_GetWindowFlags"); bindFunc(cast(void**)&SDL_SetWindowTitle, "SDL_SetWindowTitle"); bindFunc(cast(void**)&SDL_GetWindowTitle, "SDL_GetWindowTitle"); bindFunc(cast(void**)&SDL_SetWindowIcon, "SDL_SetWindowIcon"); bindFunc(cast(void**)&SDL_SetWindowData, "SDL_SetWindowData"); bindFunc(cast(void**)&SDL_GetWindowData, "SDL_GetWindowData"); bindFunc(cast(void**)&SDL_SetWindowPosition, "SDL_SetWindowPosition"); bindFunc(cast(void**)&SDL_GetWindowPosition, "SDL_GetWindowPosition"); bindFunc(cast(void**)&SDL_SetWindowSize, "SDL_SetWindowSize"); bindFunc(cast(void**)&SDL_GetWindowSize, "SDL_GetWindowSize"); bindFunc(cast(void**)&SDL_SetWindowMinimumSize, "SDL_SetWindowMinimumSize"); bindFunc(cast(void**)&SDL_GetWindowMinimumSize, "SDL_GetWindowMinimumSize"); bindFunc(cast(void**)&SDL_SetWindowMaximumSize, "SDL_SetWindowMaximumSize"); bindFunc(cast(void**)&SDL_GetWindowMaximumSize, "SDL_GetWindowMaximumSize"); bindFunc(cast(void**)&SDL_SetWindowBordered, "SDL_SetWindowBordered"); bindFunc(cast(void**)&SDL_ShowWindow, "SDL_ShowWindow"); bindFunc(cast(void**)&SDL_HideWindow, "SDL_HideWindow"); bindFunc(cast(void**)&SDL_RaiseWindow, "SDL_RaiseWindow"); bindFunc(cast(void**)&SDL_MaximizeWindow, "SDL_MaximizeWindow"); bindFunc(cast(void**)&SDL_MinimizeWindow, "SDL_MinimizeWindow"); bindFunc(cast(void**)&SDL_RestoreWindow, "SDL_RestoreWindow"); bindFunc(cast(void**)&SDL_SetWindowFullscreen, "SDL_SetWindowFullscreen"); bindFunc(cast(void**)&SDL_GetWindowSurface, "SDL_GetWindowSurface"); bindFunc(cast(void**)&SDL_UpdateWindowSurface, "SDL_UpdateWindowSurface"); bindFunc(cast(void**)&SDL_UpdateWindowSurfaceRects, "SDL_UpdateWindowSurfaceRects"); bindFunc(cast(void**)&SDL_SetWindowGrab, "SDL_SetWindowGrab"); bindFunc(cast(void**)&SDL_GetWindowGrab, "SDL_GetWindowGrab"); bindFunc(cast(void**)&SDL_SetWindowBrightness, "SDL_SetWindowBrightness"); bindFunc(cast(void**)&SDL_GetWindowBrightness, "SDL_GetWindowBrightness"); bindFunc(cast(void**)&SDL_SetWindowGammaRamp, "SDL_SetWindowGammaRamp"); bindFunc(cast(void**)&SDL_GetWindowGammaRamp, "SDL_GetWindowGammaRamp"); bindFunc(cast(void**)&SDL_DestroyWindow, "SDL_DestroyWindow"); bindFunc(cast(void**)&SDL_IsScreenSaverEnabled, "SDL_IsScreenSaverEnabled"); bindFunc(cast(void**)&SDL_EnableScreenSaver, "SDL_EnableScreenSaver"); bindFunc(cast(void**)&SDL_DisableScreenSaver, "SDL_DisableScreenSaver"); bindFunc(cast(void**)&SDL_GL_LoadLibrary, "SDL_GL_LoadLibrary"); bindFunc(cast(void**)&SDL_GL_GetProcAddress, "SDL_GL_GetProcAddress"); bindFunc(cast(void**)&SDL_GL_UnloadLibrary, "SDL_GL_UnloadLibrary"); bindFunc(cast(void**)&SDL_GL_ExtensionSupported, "SDL_GL_ExtensionSupported"); bindFunc(cast(void**)&SDL_GL_SetAttribute, "SDL_GL_SetAttribute"); bindFunc(cast(void**)&SDL_GL_GetAttribute, "SDL_GL_GetAttribute"); bindFunc(cast(void**)&SDL_GL_CreateContext, "SDL_GL_CreateContext"); bindFunc(cast(void**)&SDL_GL_MakeCurrent, "SDL_GL_MakeCurrent"); bindFunc(cast(void**)&SDL_GL_GetCurrentWindow, "SDL_GL_GetCurrentWindow"); bindFunc(cast(void**)&SDL_GL_GetCurrentContext, "SDL_GL_GetCurrentContext"); bindFunc(cast(void**)&SDL_GL_SetSwapInterval, "SDL_GL_SetSwapInterval"); bindFunc(cast(void**)&SDL_GL_GetSwapInterval, "SDL_GL_GetSwapInterval"); bindFunc(cast(void**)&SDL_GL_SwapWindow, "SDL_GL_SwapWindow"); bindFunc(cast(void**)&SDL_GL_DeleteContext, "SDL_GL_DeleteContext"); // SDL_init will fail if SDL_SetMainReady has not been called. // Since there's no SDL_main on the D side, it needs to be handled // manually. My understanding that this is fine on the platforms // that D is currently available on. If we ever get on to Android // or iPhone, though, this will need to be versioned. // I've wrapped it in a try/catch because it seem the function is // not always exported on Linux. See issue #153 // https://github.com/aldacron/Derelict3/issues/153 import derelict.util.exception; try { da_SDL_SetMainReady setReady; bindFunc(cast(void**)&setReady, "SDL_SetMainReady"); setReady(); } catch( DerelictException de ) {} } } public { this() { super(libNames); } } } __gshared DerelictSDL2Loader DerelictSDL2; shared static this() { DerelictSDL2 = new DerelictSDL2Loader(); } shared static ~this() { DerelictSDL2.unload(); }
0
0.811528
1
0.811528
game-dev
MEDIA
0.881332
game-dev
0.509214
1
0.509214
Sandrem/FlyCasual
4,473
Assets/Scripts/Model/Content/SecondEdition/Standard/Pilots/Republic/BTLBYWing/Goji.cs
using BoardTools; using Bombs; using Content; using Ship; using System; using System.Collections.Generic; using System.Linq; using Upgrade; namespace Ship { namespace SecondEdition.BTLBYWing { public class Goji : BTLBYWing { public Goji() : base() { PilotInfo = new PilotCardInfo25 ( "\"Goji\"", "Payload Specialist", Faction.Republic, 2, 4, 12, isLimited: true, abilityType: typeof(Abilities.SecondEdition.GojiAbility), extraUpgradeIcons: new List<UpgradeType> { UpgradeType.Talent, UpgradeType.Turret, UpgradeType.Gunner, UpgradeType.Astromech, UpgradeType.Device, UpgradeType.Device, UpgradeType.Device, UpgradeType.Modification }, tags: new List<Tags> { Tags.Clone, Tags.YWing } ); ImageUrl = "https://images-cdn.fantasyflightgames.com/filer_public/71/ca/71ca5555-2cf9-4d11-8163-c443669897bd/swz48_pilot-goji.png"; } } } } namespace Abilities.SecondEdition { public class GojiAbility : GenericAbility { private int BombsAndMinesInRangeCount; public override void ActivateAbility() { GenericShip.OnAttackStartAsDefenderGlobal += CheckAbility; } public override void DeactivateAbility() { GenericShip.OnAttackStartAsDefenderGlobal -= CheckAbility; } private void CheckAbility() { if (Combat.Defender.Owner.PlayerNo != HostShip.Owner.PlayerNo) return; DistanceInfo distInfo = new DistanceInfo(HostShip, Combat.Defender); if (distInfo.Range > 3) return; BombsAndMinesInRangeCount = 0; foreach (var bombHolder in BombsManager.GetBombsOnBoard().Where(n => n.Value.HostShip.Owner.PlayerNo == HostShip.Owner.PlayerNo)) { //January 2020 errata: This ability now only works with bombs if (bombHolder.Value.UpgradeInfo.SubType != UpgradeSubType.Bomb) break; if (BombsManager.IsShipInRange(Combat.Defender, bombHolder.Key, 1)) { BombsAndMinesInRangeCount++; break; } } if (BombsAndMinesInRangeCount > 0) RegisterAbilityTrigger(TriggerTypes.OnDefenseStart, AskToAddExtraDice); } private void AskToAddExtraDice(object sender, EventArgs e) { if (!alwaysUseAbility) { AskToUseAbility( HostShip.PilotInfo.PilotName, AlwaysUseByDefault, ChooseToAddExtraDice, showAlwaysUseOption: true, descriptionLong: "Do you want to roll 1 additional defense dice for each friendly bomb or mine in range?", imageHolder: HostShip, requiredPlayer: HostShip.Owner.PlayerNo ); } else { PlanToAddExtraDice(); } } private void ChooseToAddExtraDice(object sender, EventArgs e) { SubPhases.DecisionSubPhase.ConfirmDecisionNoCallback(); PlanToAddExtraDice(); } private void PlanToAddExtraDice() { Combat.Defender.AfterGotNumberOfDefenceDice += AddExtraDice; Triggers.FinishTrigger(); } private void AddExtraDice(ref int count) { Combat.Defender.OnAttackFinishAsDefender += PlanToDisableAbility; Messages.ShowInfo(HostShip.PilotInfo.PilotName + ": Exra dice are added"); count += BombsAndMinesInRangeCount; } private void PlanToDisableAbility(GenericShip ship) { Combat.Defender.OnAttackFinishAsDefender -= PlanToDisableAbility; Combat.Defender.AfterGotNumberOfDefenceDice -= AddExtraDice; } } }
0
0.83569
1
0.83569
game-dev
MEDIA
0.943504
game-dev
0.920226
1
0.920226
semontesdeoca/MNPR
1,583
plugins/mnpr_present.h
#pragma once /////////////////////////////////////////////////////////////////////////////////// // _ _ _ // _ __ _ __ ___ ___ ___ _ __ | |_ ___ _ __ ___ _ __ __ _| |_(_) ___ _ __ // | '_ \| '__/ _ \/ __|/ _ \ '_ \| __| / _ \| '_ \ / _ \ '__/ _` | __| |/ _ \| '_ \ // | |_) | | | __/\__ \ __/ | | | |_ | (_) | |_) | __/ | | (_| | |_| | (_) | | | | // | .__/|_| \___||___/\___|_| |_|\__| \___/| .__/ \___|_| \__,_|\__|_|\___/|_| |_| // |_| |_| // // \brief Present operation // Contains the MPresentTarget that will display the active render target in the viewport /////////////////////////////////////////////////////////////////////////////////// #include "MRenderTargetList.h" class PresentTarget : public MHWRender::MPresentTarget { public: PresentTarget(const MString &t_name, MRenderTargetList* t_targetList) : MPresentTarget(t_name) { mTargets[0] = t_targetList->target(t_targetList->length() - 1); mTargets[1] = t_targetList->target(1); // depth } ~PresentTarget() {} /// target override list MHWRender::MRenderTarget* const* targetOverrideList(unsigned int &listSize) { if (mTargets) { listSize = 2; return mTargets; } listSize = 0; return nullptr; } protected: MHWRender::MRenderTarget* mTargets[2]; ///< target list that is presented on the viewport };
0
0.674971
1
0.674971
game-dev
MEDIA
0.200291
game-dev
0.736985
1
0.736985
spacechase0/StardewValleyMods
4,626
framework/JsonAssets/Data/BigCraftableRecipe.cs
using System.Collections.Generic; using System.Runtime.Serialization; using JsonAssets.Framework; using SpaceShared; using StardewValley; namespace JsonAssets.Data { public class BigCraftableRecipe { /********* ** Accessors *********/ public string SkillUnlockName { get; set; } = null; public int SkillUnlockLevel { get; set; } = -1; public int ResultCount { get; set; } = 1; public IList<BigCraftableIngredient> Ingredients { get; set; } = new List<BigCraftableIngredient>(); public bool IsDefault { get; set; } = false; public bool CanPurchase { get; set; } = false; public int PurchasePrice { get; set; } public string PurchaseFrom { get; set; } = "Gus"; public IList<string> PurchaseRequirements { get; set; } = new List<string>(); public IList<PurchaseData> AdditionalPurchaseData { get; set; } = new List<PurchaseData>(); /********* ** Public methods *********/ internal string GetRecipeString(BigCraftableData parent) { string str = ""; foreach (var ingredient in this.Ingredients) { string ingredientName = ingredient.Object.ToString(); // If the original object name is an integer, it's a category or an original ID if (int.TryParse(ingredientName, out int ingredIndex)) { ingredientName = ingredIndex.ToString(); // Check if it's valid item or category, if it's not then skip adding the item if (ItemRegistry.GetDataOrErrorItem(ingredientName).IsErrorItem && StardewValley.Object.GetCategoryDisplayName(ingredIndex) == "") { Log.Warn($"Invalid recipe ingredient:{ingredient.Object.ToString()}"); continue; } } // If the object is a JA object, then just use that else if (ingredient.Object.ToString().FixIdJA("O") != null) { ingredientName = ingredient.Object.ToString().FixIdJA("O"); } // If the object isn't an integer, or a JA object, or an existing item, check if it's close to the name of any existing item and use that if so else if (ItemRegistry.GetDataOrErrorItem(ingredientName).IsErrorItem) { Item tryGetItem = Utility.fuzzyItemSearch(ingredientName); if (tryGetItem != null) { ingredientName = tryGetItem.ItemId; } // Don't add the ingredient if it's not a valid item else { Log.Warn($"Invalid recipe ingredient:{ingredient.Object.ToString()}"); continue; } } // Finally, add the ingredient name if it now matches an existing item str += ingredientName + " " + ingredient.Count + " "; } // If no ingredients were added, add the torch recipe ingredients if (str == "") { Log.Warn($"Recipe with no valid ingredients:{parent.Name}"); str += "388 1 92 2 "; } str = str.Substring(0, str.Length - 1); str += $"/what is this for?/{parent.Name.FixIdJA("BC")} {this.ResultCount}/true/"; if (this.SkillUnlockName?.Length > 0 && this.SkillUnlockLevel > 0) str += this.SkillUnlockName + " " + this.SkillUnlockLevel; else str += "null"; //if (LocalizedContentManager.CurrentLanguageCode != LocalizedContentManager.LanguageCode.en) str += "/" + parent.LocalizedName(); return str; } /********* ** Private methods *********/ /// <summary>Normalize the model after it's deserialized.</summary> /// <param name="context">The deserialization context.</param> [OnDeserialized] private void OnDeserialized(StreamingContext context) { this.Ingredients ??= new List<BigCraftableIngredient>(); this.PurchaseRequirements ??= new List<string>(); this.AdditionalPurchaseData ??= new List<PurchaseData>(); this.Ingredients.FilterNulls(); this.PurchaseRequirements.FilterNulls(); this.AdditionalPurchaseData.FilterNulls(); } } }
0
0.799629
1
0.799629
game-dev
MEDIA
0.832857
game-dev
0.941965
1
0.941965
ProjectIgnis/CardScripts
3,890
official/c41371602.lua
--スタンドアップ・センチュリオン! --Stand Up Centur-Ion! --Scripted by Eerie Code local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(s.reg) c:RegisterEffect(e1) --Cannot be destroyed by your opponent's effects while you control a "Centurion" Monster Card local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e2:SetRange(LOCATION_FZONE) e2:SetCondition(s.indcon) e2:SetValue(aux.indoval) c:RegisterEffect(e2) --Place 1 "Centurion" monster from your Deck in your Spell & Trap Zone as a Continuous Trap local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,0)) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_FZONE) e3:SetCountLimit(1,{id,0}) e3:SetCondition(function(e) return e:GetHandler():HasFlagEffect(id) end) e3:SetCost(s.tfcost) e3:SetTarget(s.tftg) e3:SetOperation(s.tfop) c:RegisterEffect(e3) --Synchro Summon using at least 1 "Centurion" monster as material local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(id,1)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e4:SetProperty(EFFECT_FLAG_DELAY) e4:SetCode(EVENT_SPSUMMON_SUCCESS) e4:SetRange(LOCATION_FZONE) e4:SetCountLimit(1,{id,1}) e4:SetTarget(s.syntg) e4:SetOperation(s.synop) c:RegisterEffect(e4) end s.listed_series={SET_CENTURION} function s.reg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end e:GetHandler():RegisterFlagEffect(id,RESETS_STANDARD_PHASE_END,EFFECT_FLAG_OATH,1) end function s.indfilter(c) return c:IsFaceup() and c:IsOriginalType(TYPE_MONSTER) and c:IsSetCard(SET_CENTURION) end function s.indcon(e) return Duel.IsExistingMatchingCard(s.indfilter,e:GetHandlerPlayer(),LOCATION_ONFIELD,0,1,nil) end function s.tfcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,1,nil) Duel.SendtoGrave(g,REASON_COST) end function s.plfilter(c) return c:IsSetCard(SET_CENTURION) and c:IsMonster() and not c:IsForbidden() end function s.tftg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingMatchingCard(s.plfilter,tp,LOCATION_DECK,0,1,nil) end end function s.tfop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD) local tc=Duel.SelectMatchingCard(tp,s.plfilter,tp,LOCATION_DECK,0,1,1,nil):GetFirst() if tc and Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEUP,true) then --Treat it as a Continuous Trap local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EFFECT_CHANGE_TYPE) e1:SetValue(TYPE_TRAP|TYPE_CONTINUOUS) e1:SetReset((RESET_EVENT|RESETS_STANDARD)&~RESET_TURN_SET) tc:RegisterEffect(e1) end end function s.syncheck(tp,sg,sc) return sg:IsExists(Card.IsSetCard,1,nil,SET_CENTURION) end function s.syntg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then Synchro.CheckAdditional=s.syncheck local res=Duel.IsExistingMatchingCard(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,1,nil) Synchro.CheckAdditional=nil return res end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function s.synop(e,tp,eg,ep,ev,re,r,rp) Synchro.CheckAdditional=s.syncheck local g=Duel.GetMatchingGroup(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,nil) if #g>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:Select(tp,1,1,nil) Duel.SynchroSummon(tp,sg:GetFirst()) else Synchro.CheckAdditional=nil end end
0
0.884881
1
0.884881
game-dev
MEDIA
0.987943
game-dev
0.972547
1
0.972547
darkstornmetu/JellyLink
1,840
Assets/02_Scripts/InjectionSystem/GameInitializer.cs
using System; using System.Collections.Generic; using UnityEngine; public class GameInitializer : MonoBehaviour { [Header("Inject Scene References")] [SerializeField] private GridManager _gridManager; [SerializeField] private SelectionManager _selectionManager; [SerializeField] private LinkFactory _linkFactory; [SerializeField] private JellyFactory _jellyFactory; [SerializeField] private Camera _mainCamera; [Header("Inject Data References")] [SerializeField] private LevelProperties _levelProperties; [SerializeField] private AnimationProperties _animationProperties; private void Awake() { ServiceContainer.Register<ICollectableFactory>(_jellyFactory); ServiceContainer.Register<IJellyFactory>(_jellyFactory); ServiceContainer.Register<ILinkFactory>(_linkFactory); ServiceContainer.Register(_gridManager); ServiceContainer.Register(_selectionManager); ServiceContainer.Register(_mainCamera); ServiceContainer.Register(_levelProperties); ServiceContainer.Register(_animationProperties); InjectDependenciesInScene(); } private void InjectDependenciesInScene() { var injectables = InjectableMonoBehaviours(); foreach (var injectable in injectables) ServiceContainer.InjectDependencies(injectable); } private IEnumerable<MonoBehaviour> InjectableMonoBehaviours() { var allMonoBehaviours = FindObjectsByType<MonoBehaviour>(FindObjectsSortMode.None); foreach (var monoBehaviour in allMonoBehaviours) { var type = monoBehaviour.GetType(); if (Attribute.IsDefined(type, typeof(InjectableAttribute))) { yield return monoBehaviour; } } } }
0
0.847549
1
0.847549
game-dev
MEDIA
0.795861
game-dev
0.8267
1
0.8267
CrypticMonkey33/ArchipelagoExplorersOfSky
2,531
worlds/stardew_valley/mods/logic/sve_logic.py
from ...logic.base_logic import BaseLogicMixin, BaseLogic from ...strings.ap_names.mods.mod_items import SVELocation, SVERunes, SVEQuestItem from ...strings.quest_names import Quest, ModQuest from ...strings.region_names import Region, SVERegion from ...strings.tool_names import Tool, ToolMaterial from ...strings.wallet_item_names import Wallet class SVELogicMixin(BaseLogicMixin): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sve = SVELogic(*args, **kwargs) class SVELogic(BaseLogic): def initialize_rules(self): self.registry.sve_location_rules.update({ SVELocation.tempered_galaxy_sword: self.logic.money.can_spend_at(SVERegion.alesia_shop, 350000), SVELocation.tempered_galaxy_dagger: self.logic.money.can_spend_at(SVERegion.isaac_shop, 600000), SVELocation.tempered_galaxy_hammer: self.logic.money.can_spend_at(SVERegion.isaac_shop, 400000), }) def has_any_rune(self): rune_list = SVERunes.nexus_items return self.logic.or_(*(self.logic.received(rune) for rune in rune_list)) def has_iridium_bomb(self): if self.options.quest_locations.has_story_quests(): return self.logic.received(SVEQuestItem.iridium_bomb) return self.logic.quest.can_complete_quest(ModQuest.RailroadBoulder) def has_marlon_boat(self): if self.options.quest_locations.has_story_quests(): return self.logic.received(SVEQuestItem.marlon_boat_paddle) return self.logic.quest.can_complete_quest(ModQuest.MarlonsBoat) def has_grandpa_shed_repaired(self): if self.options.quest_locations.has_story_quests(): return self.logic.received(SVEQuestItem.grandpa_shed) return self.logic.quest.can_complete_quest(ModQuest.GrandpasShed) def has_bear_knowledge(self): if self.options.quest_locations.has_story_quests(): return self.logic.received(Wallet.bears_knowledge) return self.logic.quest.can_complete_quest(Quest.strange_note) def can_buy_bear_recipe(self): access_rule = (self.logic.quest.can_complete_quest(Quest.strange_note) & self.logic.tool.has_tool(Tool.axe, ToolMaterial.basic) & self.logic.tool.has_tool(Tool.pickaxe, ToolMaterial.basic)) forage_rule = self.logic.region.can_reach_any((Region.forest, Region.backwoods, Region.mountain)) knowledge_rule = self.has_bear_knowledge() return access_rule & forage_rule & knowledge_rule
0
0.833938
1
0.833938
game-dev
MEDIA
0.888312
game-dev
0.860939
1
0.860939
CalamityTeam/CalamityModPublic
1,483
Projectiles/Magic/BrimstoneHomer.cs
using CalamityMod.Buffs.DamageOverTime; using CalamityMod.Dusts; using Microsoft.Xna.Framework; using Terraria; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Magic { public class BrimstoneHomer : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Magic"; public override void SetDefaults() { Projectile.width = 8; Projectile.height = 8; Projectile.friendly = true; Projectile.DamageType = DamageClass.Magic; Projectile.ignoreWater = true; Projectile.penetrate = 1; Projectile.extraUpdates = 1; Projectile.timeLeft = 180; } public override bool? CanHitNPC(NPC target) => Projectile.timeLeft < 150 && target.CanBeChasedBy(Projectile); public override void AI() { Projectile.rotation += 0.7f * Projectile.direction; int brimstone = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, (int)CalamityDusts.Brimstone, 0f, 0f, 100, default, 1f); Main.dust[brimstone].noGravity = true; if (Projectile.timeLeft < 150) CalamityUtils.HomeInOnNPC(Projectile, !Projectile.tileCollide, 200f, 8f, 20f); } public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { target.AddBuff(ModContent.BuffType<BrimstoneFlames>(), 120); } } }
0
0.892429
1
0.892429
game-dev
MEDIA
0.995508
game-dev
0.941539
1
0.941539
OpenXRay/xray-15
2,807
cs/engine/xrGame/ui/UIOutfitSlot.cpp
#include "stdafx.h" #include "UIOutfitSlot.h" #include "UIStatic.h" #include "UICellItem.h" #include "CustomOutfit.h" #include "Actor.h" #include "UIInventoryUtilities.h" CUIOutfitDragDropList::CUIOutfitDragDropList() { m_background = new CUIStatic(); m_background->SetAutoDelete (true); AttachChild (m_background); m_default_outfit = "npc_icon_without_outfit"; } CUIOutfitDragDropList::~CUIOutfitDragDropList() { } #include "Level.h" #include "game_base_space.h" void CUIOutfitDragDropList::SetOutfit(CUICellItem* itm) { m_background->SetWndPos (Fvector2().set(0,0)); m_background->SetWndSize (Fvector2().set(GetWidth(), GetHeight())); m_background->SetStretchTexture (true); if ((!IsGameTypeSingle()) && !itm) { CObject *pActor = NULL; pActor = smart_cast<CActor*>(Level().CurrentEntity()); xr_string a; if (pActor) a = *pActor->cNameVisual(); else a = *m_default_outfit; xr_string::iterator it = std::find(a.rbegin(), a.rend(), '\\').base(); // Cut leading full path if (it != a.begin()) a.erase(a.begin(), it); // Cut trailing ".ogf" R_ASSERT(xr_strlen(a.c_str()) > 4); if ('.' == a[a.size() - 4]) a.erase(a.size() - 4); m_background->InitTexture(a.c_str()); } else { if(itm) { PIItem _iitem = (PIItem)itm->m_pData; CCustomOutfit* pOutfit = smart_cast<CCustomOutfit*>(_iitem); VERIFY(pOutfit); /* r.lt = pOutfit->GetIconPos(); r.x1 *= ICON_GRID_WIDTH; r.y1 *= ICON_GRID_HEIGHT; */ m_background->InitTexture (pOutfit->GetFullIconName().c_str()); }else { m_background->InitTexture ("npc_icon_without_outfit"); } /* r.x2 = r.x1+CHAR_ICON_FULL_WIDTH*ICON_GRID_WIDTH; r.y2 = r.y1+CHAR_ICON_FULL_HEIGHT*ICON_GRID_HEIGHT; m_background->SetShader (InventoryUtilities::GetCharIconsShader()); m_background->SetOriginalRect (r); */ } m_background->TextureOn (); // m_background->RescaleRelative2Rect (r); } void CUIOutfitDragDropList::SetDefaultOutfit(LPCSTR default_outfit){ m_default_outfit = default_outfit; } void CUIOutfitDragDropList::SetItem(CUICellItem* itm) { if(itm) inherited::SetItem (itm); SetOutfit (itm); } void CUIOutfitDragDropList::SetItem(CUICellItem* itm, Fvector2 abs_pos) { if(itm) inherited::SetItem (itm, abs_pos); SetOutfit (itm); } void CUIOutfitDragDropList::SetItem(CUICellItem* itm, Ivector2 cell_pos) { if(itm) inherited::SetItem (itm, cell_pos); SetOutfit (itm); } CUICellItem* CUIOutfitDragDropList::RemoveItem(CUICellItem* itm, bool force_root) { VERIFY (!force_root); CUICellItem* ci = inherited::RemoveItem(itm, force_root); SetOutfit (NULL); return ci; } void CUIOutfitDragDropList::Draw() { m_background->Draw (); //. inherited::Draw (); }
0
0.944948
1
0.944948
game-dev
MEDIA
0.835801
game-dev
0.930245
1
0.930245
glKarin/com.n0n3m4.diii4a
3,275
Q3E/src/main/jni/openmohaa/code/botlib/be_aas_bsp.h
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ /***************************************************************************** * name: be_aas_bsp.h * * desc: AAS * * $Archive: /source/code/botlib/be_aas_bsp.h $ * *****************************************************************************/ #ifdef AASINTERN //loads the given BSP file int AAS_LoadBSPFile(void); //dump the loaded BSP data void AAS_DumpBSPData(void); //unlink the given entity from the bsp tree leaves void AAS_UnlinkFromBSPLeaves(bsp_link_t *leaves); //link the given entity to the bsp tree leaves of the given model bsp_link_t *AAS_BSPLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum, int modelnum); //calculates collision with given entity qboolean AAS_EntityCollision(int entnum, vec3_t start, vec3_t boxmins, vec3_t boxmaxs, vec3_t end, int contentmask, bsp_trace_t *trace); //for debugging void AAS_PrintFreeBSPLinks(char *str); // #endif //AASINTERN #define MAX_EPAIRKEY 128 //trace through the world bsp_trace_t AAS_Trace( vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask); //returns the contents at the given point int AAS_PointContents(vec3_t point); //returns true when p2 is in the PVS of p1 qboolean AAS_inPVS(vec3_t p1, vec3_t p2); //returns true when p2 is in the PHS of p1 qboolean AAS_inPHS(vec3_t p1, vec3_t p2); //returns true if the given areas are connected qboolean AAS_AreasConnected(int area1, int area2); //creates a list with entities totally or partly within the given box int AAS_BoxEntities(vec3_t absmins, vec3_t absmaxs, int *list, int maxcount); //gets the mins, maxs and origin of a BSP model void AAS_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin); //handle to the next bsp entity int AAS_NextBSPEntity(int ent); //return the value of the BSP epair key int AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size); //get a vector for the BSP epair key int AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v); //get a float for the BSP epair key int AAS_FloatForBSPEpairKey(int ent, char *key, float *value); //get an integer for the BSP epair key int AAS_IntForBSPEpairKey(int ent, char *key, int *value);
0
0.847596
1
0.847596
game-dev
MEDIA
0.845642
game-dev
0.836185
1
0.836185
ether/pad
22,134
infrastructure/rhino1_7R1/src/org/mozilla/javascript/optimizer/Block.java
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Roger Lawrence * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.optimizer; import org.mozilla.javascript.*; import java.util.Hashtable; import java.io.PrintWriter; import java.io.StringWriter; class Block { private static class FatBlock { private static Block[] reduceToArray(ObjToIntMap map) { Block[] result = null; if (!map.isEmpty()) { result = new Block[map.size()]; int i = 0; ObjToIntMap.Iterator iter = map.newIterator(); for (iter.start(); !iter.done(); iter.next()) { FatBlock fb = (FatBlock)(iter.getKey()); result[i++] = fb.realBlock; } } return result; } void addSuccessor(FatBlock b) { successors.put(b, 0); } void addPredecessor(FatBlock b) { predecessors.put(b, 0); } Block[] getSuccessors() { return reduceToArray(successors); } Block[] getPredecessors() { return reduceToArray(predecessors); } // all the Blocks that come immediately after this private ObjToIntMap successors = new ObjToIntMap(); // all the Blocks that come immediately before this private ObjToIntMap predecessors = new ObjToIntMap(); Block realBlock; } Block(int startNodeIndex, int endNodeIndex) { itsStartNodeIndex = startNodeIndex; itsEndNodeIndex = endNodeIndex; } static void runFlowAnalyzes(OptFunctionNode fn, Node[] statementNodes) { int paramCount = fn.fnode.getParamCount(); int varCount = fn.fnode.getParamAndVarCount(); int[] varTypes = new int[varCount]; // If the variable is a parameter, it could have any type. for (int i = 0; i != paramCount; ++i) { varTypes[i] = Optimizer.AnyType; } // If the variable is from a "var" statement, its typeEvent will be set // when we see the setVar node. for (int i = paramCount; i != varCount; ++i) { varTypes[i] = Optimizer.NoType; } Block[] theBlocks = buildBlocks(statementNodes); if (DEBUG) { ++debug_blockCount; System.out.println("-------------------"+fn.fnode.getFunctionName()+" "+debug_blockCount+"--------"); System.out.println(toString(theBlocks, statementNodes)); } reachingDefDataFlow(fn, statementNodes, theBlocks, varTypes); typeFlow(fn, statementNodes, theBlocks, varTypes); if (DEBUG) { for (int i = 0; i < theBlocks.length; i++) { System.out.println("For block " + theBlocks[i].itsBlockID); theBlocks[i].printLiveOnEntrySet(fn); } System.out.println("Variable Table, size = " + varCount); for (int i = 0; i != varCount; i++) { System.out.println("["+i+"] type: "+varTypes[i]); } } for (int i = paramCount; i != varCount; i++) { if (varTypes[i] == Optimizer.NumberType) { fn.setIsNumberVar(i); } } } private static Block[] buildBlocks(Node[] statementNodes) { // a mapping from each target node to the block it begins Hashtable theTargetBlocks = new Hashtable(); ObjArray theBlocks = new ObjArray(); // there's a block that starts at index 0 int beginNodeIndex = 0; for (int i = 0; i < statementNodes.length; i++) { switch (statementNodes[i].getType()) { case Token.TARGET : { if (i != beginNodeIndex) { FatBlock fb = newFatBlock(beginNodeIndex, i - 1); if (statementNodes[beginNodeIndex].getType() == Token.TARGET) theTargetBlocks.put(statementNodes[beginNodeIndex], fb); theBlocks.add(fb); // start the next block at this node beginNodeIndex = i; } } break; case Token.IFNE : case Token.IFEQ : case Token.GOTO : { FatBlock fb = newFatBlock(beginNodeIndex, i); if (statementNodes[beginNodeIndex].getType() == Token.TARGET) theTargetBlocks.put(statementNodes[beginNodeIndex], fb); theBlocks.add(fb); // start the next block at the next node beginNodeIndex = i + 1; } break; } } if (beginNodeIndex != statementNodes.length) { FatBlock fb = newFatBlock(beginNodeIndex, statementNodes.length - 1); if (statementNodes[beginNodeIndex].getType() == Token.TARGET) theTargetBlocks.put(statementNodes[beginNodeIndex], fb); theBlocks.add(fb); } // build successor and predecessor links for (int i = 0; i < theBlocks.size(); i++) { FatBlock fb = (FatBlock)(theBlocks.get(i)); Node blockEndNode = statementNodes[fb.realBlock.itsEndNodeIndex]; int blockEndNodeType = blockEndNode.getType(); if ((blockEndNodeType != Token.GOTO) && (i < (theBlocks.size() - 1))) { FatBlock fallThruTarget = (FatBlock)(theBlocks.get(i + 1)); fb.addSuccessor(fallThruTarget); fallThruTarget.addPredecessor(fb); } if ( (blockEndNodeType == Token.IFNE) || (blockEndNodeType == Token.IFEQ) || (blockEndNodeType == Token.GOTO) ) { Node target = ((Node.Jump)blockEndNode).target; FatBlock branchTargetBlock = (FatBlock)(theTargetBlocks.get(target)); target.putProp(Node.TARGETBLOCK_PROP, branchTargetBlock.realBlock); fb.addSuccessor(branchTargetBlock); branchTargetBlock.addPredecessor(fb); } } Block[] result = new Block[theBlocks.size()]; for (int i = 0; i < theBlocks.size(); i++) { FatBlock fb = (FatBlock)(theBlocks.get(i)); Block b = fb.realBlock; b.itsSuccessors = fb.getSuccessors(); b.itsPredecessors = fb.getPredecessors(); b.itsBlockID = i; result[i] = b; } return result; } private static FatBlock newFatBlock(int startNodeIndex, int endNodeIndex) { FatBlock fb = new FatBlock(); fb.realBlock = new Block(startNodeIndex, endNodeIndex); return fb; } private static String toString(Block[] blockList, Node[] statementNodes) { if (!DEBUG) return null; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(blockList.length + " Blocks"); for (int i = 0; i < blockList.length; i++) { Block b = blockList[i]; pw.println("#" + b.itsBlockID); pw.println("from " + b.itsStartNodeIndex + " " + statementNodes[b.itsStartNodeIndex].toString()); pw.println("thru " + b.itsEndNodeIndex + " " + statementNodes[b.itsEndNodeIndex].toString()); pw.print("Predecessors "); if (b.itsPredecessors != null) { for (int j = 0; j < b.itsPredecessors.length; j++) pw.print(b.itsPredecessors[j].itsBlockID + " "); pw.println(); } else pw.println("none"); pw.print("Successors "); if (b.itsSuccessors != null) { for (int j = 0; j < b.itsSuccessors.length; j++) pw.print(b.itsSuccessors[j].itsBlockID + " "); pw.println(); } else pw.println("none"); } return sw.toString(); } private static void reachingDefDataFlow(OptFunctionNode fn, Node[] statementNodes, Block theBlocks[], int[] varTypes) { /* initialize the liveOnEntry and liveOnExit sets, then discover the variables that are def'd by each function, and those that are used before being def'd (hence liveOnEntry) */ for (int i = 0; i < theBlocks.length; i++) { theBlocks[i].initLiveOnEntrySets(fn, statementNodes); } /* this visits every block starting at the last, re-adding the predecessors of any block whose inputs change as a result of the dataflow. REMIND, better would be to visit in CFG postorder */ boolean visit[] = new boolean[theBlocks.length]; boolean doneOnce[] = new boolean[theBlocks.length]; int vIndex = theBlocks.length - 1; boolean needRescan = false; visit[vIndex] = true; while (true) { if (visit[vIndex] || !doneOnce[vIndex]) { doneOnce[vIndex] = true; visit[vIndex] = false; if (theBlocks[vIndex].doReachedUseDataFlow()) { Block pred[] = theBlocks[vIndex].itsPredecessors; if (pred != null) { for (int i = 0; i < pred.length; i++) { int index = pred[i].itsBlockID; visit[index] = true; needRescan |= (index > vIndex); } } } } if (vIndex == 0) { if (needRescan) { vIndex = theBlocks.length - 1; needRescan = false; } else break; } else vIndex--; } /* if any variable is live on entry to block 0, we have to mark it as not jRegable - since it means that someone is trying to access the 'undefined'-ness of that variable. */ theBlocks[0].markAnyTypeVariables(varTypes); } private static void typeFlow(OptFunctionNode fn, Node[] statementNodes, Block theBlocks[], int[] varTypes) { boolean visit[] = new boolean[theBlocks.length]; boolean doneOnce[] = new boolean[theBlocks.length]; int vIndex = 0; boolean needRescan = false; visit[vIndex] = true; while (true) { if (visit[vIndex] || !doneOnce[vIndex]) { doneOnce[vIndex] = true; visit[vIndex] = false; if (theBlocks[vIndex].doTypeFlow(fn, statementNodes, varTypes)) { Block succ[] = theBlocks[vIndex].itsSuccessors; if (succ != null) { for (int i = 0; i < succ.length; i++) { int index = succ[i].itsBlockID; visit[index] = true; needRescan |= (index < vIndex); } } } } if (vIndex == (theBlocks.length - 1)) { if (needRescan) { vIndex = 0; needRescan = false; } else break; } else vIndex++; } } private static boolean assignType(int[] varTypes, int index, int type) { return type != (varTypes[index] |= type); } private void markAnyTypeVariables(int[] varTypes) { for (int i = 0; i != varTypes.length; i++) { if (itsLiveOnEntrySet.test(i)) { assignType(varTypes, i, Optimizer.AnyType); } } } /* We're tracking uses and defs - in order to build the def set and to identify the last use nodes. The itsNotDefSet is built reversed then flipped later. */ private void lookForVariableAccess(OptFunctionNode fn, Node n) { switch (n.getType()) { case Token.DEC : case Token.INC : { Node child = n.getFirstChild(); if (child.getType() == Token.GETVAR) { int varIndex = fn.getVarIndex(child); if (!itsNotDefSet.test(varIndex)) itsUseBeforeDefSet.set(varIndex); itsNotDefSet.set(varIndex); } } break; case Token.SETVAR : { Node lhs = n.getFirstChild(); Node rhs = lhs.getNext(); lookForVariableAccess(fn, rhs); itsNotDefSet.set(fn.getVarIndex(n)); } break; case Token.GETVAR : { int varIndex = fn.getVarIndex(n); if (!itsNotDefSet.test(varIndex)) itsUseBeforeDefSet.set(varIndex); } break; default : Node child = n.getFirstChild(); while (child != null) { lookForVariableAccess(fn, child); child = child.getNext(); } break; } } /* build the live on entry/exit sets. Then walk the trees looking for defs/uses of variables and build the def and useBeforeDef sets. */ private void initLiveOnEntrySets(OptFunctionNode fn, Node[] statementNodes) { int listLength = fn.getVarCount(); itsUseBeforeDefSet = new DataFlowBitSet(listLength); itsNotDefSet = new DataFlowBitSet(listLength); itsLiveOnEntrySet = new DataFlowBitSet(listLength); itsLiveOnExitSet = new DataFlowBitSet(listLength); for (int i = itsStartNodeIndex; i <= itsEndNodeIndex; i++) { Node n = statementNodes[i]; lookForVariableAccess(fn, n); } itsNotDefSet.not(); // truth in advertising } /* the liveOnEntry of each successor is the liveOnExit for this block. The liveOnEntry for this block is - liveOnEntry = liveOnExit - defsInThisBlock + useBeforeDefsInThisBlock */ private boolean doReachedUseDataFlow() { itsLiveOnExitSet.clear(); if (itsSuccessors != null) for (int i = 0; i < itsSuccessors.length; i++) itsLiveOnExitSet.or(itsSuccessors[i].itsLiveOnEntrySet); return itsLiveOnEntrySet.df2(itsLiveOnExitSet, itsUseBeforeDefSet, itsNotDefSet); } /* the type of an expression is relatively unknown. Cases we can be sure about are - Literals, Arithmetic operations - always return a Number */ private static int findExpressionType(OptFunctionNode fn, Node n, int[] varTypes) { switch (n.getType()) { case Token.NUMBER : return Optimizer.NumberType; case Token.CALL : case Token.NEW : case Token.REF_CALL : return Optimizer.AnyType; case Token.GETELEM : return Optimizer.AnyType; case Token.GETVAR : return varTypes[fn.getVarIndex(n)]; case Token.INC : case Token.DEC : case Token.DIV: case Token.MOD: case Token.BITOR: case Token.BITXOR: case Token.BITAND: case Token.LSH: case Token.RSH: case Token.URSH: case Token.SUB : return Optimizer.NumberType; case Token.ARRAYLIT: case Token.OBJECTLIT: return Optimizer.AnyType; // XXX: actually, we know it's not // number, but no type yet for that case Token.ADD : { // if the lhs & rhs are known to be numbers, we can be sure that's // the result, otherwise it could be a string. Node child = n.getFirstChild(); int lType = findExpressionType(fn, child, varTypes); int rType = findExpressionType(fn, child.getNext(), varTypes); return lType | rType; // we're not distinguishing strings yet } } Node child = n.getFirstChild(); if (child == null) { return Optimizer.AnyType; } else { int result = Optimizer.NoType; while (child != null) { result |= findExpressionType(fn, child, varTypes); child = child.getNext(); } return result; } } private static boolean findDefPoints(OptFunctionNode fn, Node n, int[] varTypes) { boolean result = false; Node child = n.getFirstChild(); switch (n.getType()) { default : while (child != null) { result |= findDefPoints(fn, child, varTypes); child = child.getNext(); } break; case Token.DEC : case Token.INC : if (child.getType() == Token.GETVAR) { // theVar is a Number now int i = fn.getVarIndex(child); result |= assignType(varTypes, i, Optimizer.NumberType); } break; case Token.SETPROP : case Token.SETPROP_OP : if (child.getType() == Token.GETVAR) { int i = fn.getVarIndex(child); assignType(varTypes, i, Optimizer.AnyType); } while (child != null) { result |= findDefPoints(fn, child, varTypes); child = child.getNext(); } break; case Token.SETVAR : { Node rValue = child.getNext(); int theType = findExpressionType(fn, rValue, varTypes); int i = fn.getVarIndex(n); result |= assignType(varTypes, i, theType); break; } } return result; } private boolean doTypeFlow(OptFunctionNode fn, Node[] statementNodes, int[] varTypes) { boolean changed = false; for (int i = itsStartNodeIndex; i <= itsEndNodeIndex; i++) { Node n = statementNodes[i]; if (n != null) changed |= findDefPoints(fn, n, varTypes); } return changed; } private void printLiveOnEntrySet(OptFunctionNode fn) { if (DEBUG) { for (int i = 0; i < fn.getVarCount(); i++) { String name = fn.fnode.getParamOrVarName(i); if (itsUseBeforeDefSet.test(i)) System.out.println(name + " is used before def'd"); if (itsNotDefSet.test(i)) System.out.println(name + " is not def'd"); if (itsLiveOnEntrySet.test(i)) System.out.println(name + " is live on entry"); if (itsLiveOnExitSet.test(i)) System.out.println(name + " is live on exit"); } } } // all the Blocks that come immediately after this private Block[] itsSuccessors; // all the Blocks that come immediately before this private Block[] itsPredecessors; private int itsStartNodeIndex; // the Node at the start of the block private int itsEndNodeIndex; // the Node at the end of the block private int itsBlockID; // a unique index for each block // reaching def bit sets - private DataFlowBitSet itsLiveOnEntrySet; private DataFlowBitSet itsLiveOnExitSet; private DataFlowBitSet itsUseBeforeDefSet; private DataFlowBitSet itsNotDefSet; static final boolean DEBUG = false; private static int debug_blockCount; }
0
0.946204
1
0.946204
game-dev
MEDIA
0.585197
game-dev
0.967804
1
0.967804
orchain/go-ethereum
24,883
tests/testdata/src/GeneralStateTestsFiller/stBadOpcode/opcCFDiffPlacesFiller.yml
# Created by tests/src/Templates/DiffPlaces/templateGen.js # # With the template code: # // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then # // kill the goat if we don't revert. # # # verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) # # // If we get here, kill the goat so we'll get an error # mstore(0, hex"DEAD60A7") # # # Expected result: 0x60A7 # opcCFDiffPlaces: _info: comment: Ori Pomerantz qbzzt1@gmail.com env: currentCoinbase: 2adc25665018aa1fe0e6bc666dac8fc2697ff9ba currentDifficulty: 0x20000 currentNumber: 1 currentTimestamp: 1000 currentGasLimit: 0x10000000000000 previousHash: 5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6 currentBaseFee: 10 pre: # It is not trivial to use the Yul compiler to get the # binary code for the code we're checking, so we'll use EXTCODECOPY # from this contract 000000000000000000000000000000000000C0DE: balance: 1000000000000000000 code: | :yul { // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") // Here the result is is mload(0). We want to run it, but // prefix it with a zero so we'll be safe from being considered // an invalid program. // // If we use this as a contructor the result will be // the code of the created contract, but we can live // with that. We won't call it. mstore(0x40, mload(0x00)) return(0x3F, 0x21) } nonce: 1 storage: {} # When we create a contract and then call it, we don't want the # zero prefix in the return value 000000000000000000000000000000000020C0DE: balance: 1000000000000000000 code: | :yul { // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") // Here the result is is mload(0). return(0x00, 0x20) } nonce: 1 storage: {} # Code for a construct to create a contract with the template code 00000000000000000000000000000000C0DEC0DE: balance: 1000000000000000000 code: | :yul { let addr := 0x20C0DE let length := extcodesize(addr) // Read the code from 0x20C0DE extcodecopy(addr, 0, 0, length) // Return this memory as the code for the contract return(0, length) } nonce: 1 storage: {} # Perform the action (directly or indirectly). Either way, # store the result in sload(0). cccccccccccccccccccccccccccccccccccccccc: balance: 1000000000000000000 code: | :yul { let action := calldataload(4) let res := 1 // If the result of a call is revert, revert here too let addr := 1 // If the result of CREATE[2] is zero, it reverted // For when we need code in our memory let codeBuffer := 0x20 // When running the template in the constructor let codeLength := extcodesize(0xC0DE) // When running the template in the created code let codeLength2 := extcodesize(0xC0DEC0DE) // Goat should be overwritten mstore(0, 0x60A7) switch action case 0 { // run the code snippet as normal code // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") } // One level of call stack case 0xF1 { // call a contract to run this code res := call(gas(), 0xca11, 0, 0, 0, 0, 0x20) // call template code } case 0xF2 { // callcode a contract to run this code res := callcode(gas(), 0xca11, 0, 0, 0, 0, 0x20) } case 0xF4 { // delegate call a contract to run this code res := delegatecall(gas(), 0xca11, 0, 0, 0, 0x20) } case 0xFA { // static call a contract to run this code res := staticcall(gas(), 0xca11, 0, 0, 0, 0x20) } // Two levels of call stack case 0xF1F1 { // call, call res := call(gas(), 0xca1100f1, 0, 0, 0, 0, 0x20) } case 0xF2F1 { // callcode, call res := callcode(gas(), 0xca1100f1, 0, 0, 0, 0, 0x20) } case 0xF4F1 { // delegatecall, call res := delegatecall(gas(), 0xca1100f1, 0, 0, 0, 0x20) } case 0xFAF1 { // staticcall, call res := staticcall(gas(), 0xca1100f1, 0, 0, 0, 0x20) } case 0xF1F2 { // call, callcode res := call(gas(), 0xca1100f2, 0, 0, 0, 0, 0x20) } case 0xF2F2 { // callcode, callcode res := callcode(gas(), 0xca1100f2, 0, 0, 0, 0, 0x20) } case 0xF4F2 { // delegatecall, callcode res := delegatecall(gas(), 0xca1100f2, 0, 0, 0, 0x20) } case 0xFAF2 { // staticcall, callcode res := staticcall(gas(), 0xca1100f2, 0, 0, 0, 0x20) } case 0xF1F4 { // call, delegatecall res := call(gas(), 0xca1100f4, 0, 0, 0, 0, 0x20) } case 0xF2F4 { // callcode, delegatecall res := callcode(gas(), 0xca1100f4, 0, 0, 0, 0, 0x20) } case 0xF4F4 { // delegatecall, delegatecall res := delegatecall(gas(), 0xca1100f4, 0, 0, 0, 0x20) } case 0xFAF4 { // staticcall, delegatecall res := staticcall(gas(), 0xca1100f4, 0, 0, 0, 0x20) } case 0xF1FA { // call, staticcall res := call(gas(), 0xca1100fa, 0, 0, 0, 0, 0x20) } case 0xF2FA { // callcode, staticcall res := callcode(gas(), 0xca1100fa, 0, 0, 0, 0, 0x20) } case 0xF4FA { // delegatecall, staticcall res := delegatecall(gas(), 0xca1100fa, 0, 0, 0, 0x20) } case 0xFAFA { // staticcall, staticcall res := staticcall(gas(), 0xca1100fa, 0, 0, 0, 0x20) } case 0xFD { // Rerun the code after a REVERT // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") sstore(0, mload(0)) pop(call(gas(), 0x60BACC, 0, 0, 0, 0, 0)) // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") // The two results should be equal if iszero(eq(sload(0), mload(0))) {mstore(0, 0xBADBADBAD)} } case 0xFE { // Rerun the code after an out of gas // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") sstore(0, mload(0)) pop(call(25000, 0x60006, 0, 0, 0, 0, 0)) // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") // The two results should be equal if iszero(eq(sload(0), mload(0))) {mstore(0, 0xBADBADBAD)} } case 0xFF { // Rerun the code after a SELFDESTRUCT // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") sstore(0, mload(0)) pop(call(gas(), 0xDEADDEAD, 0, 0, 0, 0, 0)) // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") // The two results should be equal if iszero(eq(sload(0), mload(0))) {mstore(0, 0xBADBADBAD)} } case 0xF0 { // CREATE, run the code in the constructor // Read the code from 0xC0DE and create a contract based on it extcodecopy(0xC0DE, codeBuffer, 0, codeLength) addr := create(1000000000000000000, codeBuffer, codeLength) // Read the created contract, that is the result // We start it from the second byte so the first byte of // code will be STOP (0x00). Otherwise we might run into // invalid program issues (because the result isn't a valid // program extcodecopy(addr, 0, 1, 0x20) } case 0xF5 { // CREATE2, run the code in the constructor // Read the code from 0xC0DE and create a contract based on it extcodecopy(0xC0DE, codeBuffer, 0, codeLength) addr := create2(1000000000000000000, codeBuffer, codeLength, 0x5a17) // Read the created contract, that is the result // We start it from the second byte so the first byte of // code will be STOP (0x00). Otherwise we might run into // invalid program issues (because the result isn't a valid // program extcodecopy(addr, 0, 1, 0x20) } case 0xF0F1 { // CREATE, then CALL the created code for the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) addr := create(1000000000000000000, codeBuffer, codeLength2) // Call the contract res := call(gas(), addr, 0, 0, 0, 0, 0x20) } case 0xF5F1 { // CREATE2, then CALL the created code for the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) addr := create2(1000000000000000000, codeBuffer, codeLength2, 0x5a17) // Call the contract res := call(gas(), addr, 0, 0, 0, 0, 0x20) } case 0xF0F2 { // CREATE, then CALLCODE the created code // for the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) // Here we don't transfer cc..cc's ETH to the new contract // because if we run SELFBALANCE it will run in the context // of CC....CC and therefore return 0 addr := create(0, codeBuffer, codeLength2) // Call the contract res := callcode(gas(), addr, 0, 0, 0, 0, 0x20) } case 0xF5F2 { // CREATE2, then CALLCODE the created code for // the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) // Here we don't transfer cc..cc's ETH to the new contract // because if we run SELFBALANCE it will run in the context // of CC....CC and therefore return 0 addr := create2(0, codeBuffer, codeLength2, 0x5a17) // Call the contract res := callcode(gas(), addr, 0, 0, 0, 0, 0x20) } case 0xF0F4 { // CREATE, then DELEGATECALL the created code // for the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) // Here we don't transfer cc..cc's ETH to the new contract // because if we run SELFBALANCE it will run in the context // of CC....CC and therefore return 0 addr := create(0, codeBuffer, codeLength2) // Call the contract res := delegatecall(gas(), addr, 0, 0, 0, 0x20) } case 0xF5F4 { // CREATE2, then DELEGATECALL the created code // for the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) // Here we don't transfer cc..cc's ETH to the new contract // because if we run SELFBALANCE it will run in the context // of CC....CC and therefore return 0 addr := create2(0, codeBuffer, codeLength2, 0x5a17) // Call the contract res := delegatecall(gas(), addr, 0, 0, 0, 0x20) } case 0xF0FA { // CREATE, then CALLSTATIC the created code // for the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) addr := create(1000000000000000000, codeBuffer, codeLength2) // Call the contract res := staticcall(gas(), addr, 0, 0, 0, 0x20) } case 0xF5FA { // CREATE2, then STATICCALL the created code // for the result // Read the code from 0xC0DEC0DE and create a // contract based on it extcodecopy(0xC0DEC0DE, codeBuffer, 0, codeLength2) addr := create2(1000000000000000000, codeBuffer, codeLength2, 0x5a17) // Call the contract res := staticcall(gas(), addr, 0, 0, 0, 0x20) } // Recurse (= run backwards) case 0x60BACCFA57 { mstore(0, 1023) res := call(gas(), 0x60BACCFA57, 0, 0, 0x20, 0, 0x20) } default { // Fail, we should never get here mstore(0, 0xBAD0BAD0BAD0) } // If res is zero, that means a call failed, so fail too if iszero(res) { revert(0,0x20) } // If addr is zero, that means a create failed, so fail too if iszero(addr) { revert(0,0x20) } // Here the result is is mload(0), store it so // the test can check it sstore(0, mload(0)) } nonce: 1 storage: 0: 0x60A7 # To be overwritten by the code snippet # Called to perform the code snippet and return the result 000000000000000000000000000000000000ca11: balance: '1000000000000000000' code: | :yul { // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") return(0, 0x20) // return the result as our return value } nonce: 1 storage: {} # Called to CALL the code (two level call stack) 00000000000000000000000000000000ca1100f1: balance: '1000000000000000000' code: | :yul { if iszero(call(gas(), 0xca11, 0, 0, 0, 0, 0x20)) { revert(0,0x20) } return(0, 0x20) // return the result as our return value } nonce: 1 storage: {} # Called to CALLCODE the code (two level call stack) 00000000000000000000000000000000ca1100f2: balance: '1000000000000000000' code: | :yul { if iszero(callcode(gas(), 0xca11, 0, 0, 0, 0, 0x20)) { revert(0,0x20) } return(0, 0x20) // return the result as our return value } nonce: 1 storage: {} # Called to DELEGATECALL the code (two level call stack) 00000000000000000000000000000000ca1100f4: balance: '1000000000000000000' code: | :yul { if iszero(delegatecall(gas(), 0xca11, 0, 0, 0, 0x20)) { revert(0,0x20) } return(0, 0x20) // return the result as our return value } nonce: 1 storage: {} # Called to STATICCALL the code (two level call stack) 00000000000000000000000000000000ca1100fa: balance: '1000000000000000000' code: | :yul { if iszero(staticcall(gas(), 0xca11, 0, 0, 0, 0x20)) { revert(0,0x20) } return(0, 0x20) // return the result as our return value } nonce: 1 storage: {} # Failures (to run the code after a failure, see it works) # Out of gas 0000000000000000000000000000000000060006: balance: '1000000000000000000' code: | :yul { // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") sstore(0,mload(0)) invalid() } nonce: 1 storage: 0: 0x60A7 # If it changes, we have a problem # REVERT 000000000000000000000000000000000060BACC: balance: '1000000000000000000' code: | :yul { // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") sstore(0,mload(0)) revert(0,0x20) } nonce: 1 storage: 0: 0x60A7 # If it changes, we have a problem # SELFDESTRUCT 00000000000000000000000000000000DEADDEAD: balance: '1000000000000000000' code: | :yul { selfdestruct(0) } nonce: 1 storage: {} # Recursively call until reaching the stack depth, then run the template 00000000000000000000000000000060BACCFA57: balance: 1000000000000000000 code: | :yul { let depth := calldataload(0) if eq(depth,0) { // Run an invalid opcode (make sure it doesn't fail due to a stack underflow) and then // kill the goat if we don't revert. verbatim_9i_0o(hex"CF", 1, 2, 3, 4, 5, 6, 7, 8, 9) // If we get here, kill the goat so we'll get an error mstore(0, hex"DEAD60A7") return(0, 0x20) } // Dig deeper mstore(0, sub(depth,1)) // Call yourself with depth-1 if iszero(call(gas(), 0x60BACCFA57, 0, 0, 0x20, 0, 0x20)) { // Propagate failure if we failed revert(0, 0x20) } // Propagate success return (0, 0x20) } nonce: 1 storage: {} a94f5374fce5edbc8e2a8697c15331677e6ebf0b: balance: 1000000000000000000000 code: '0x' nonce: 1 storage: {} transaction: data: # Run the code snippet normally - :label normal :abi f(uint) 0x00 # Single level call stack # CALL - :label normal :abi f(uint) 0xf1 # CALLCODE - :label normal :abi f(uint) 0xf2 # DELEGATECALL - :abi f(uint) 0xf4 # STATICCALL - :abi f(uint) 0xfa # Two level call stack # CALL CALL - :abi f(uint) 0xf1f1 # CALLCODE CALL - :abi f(uint) 0xf2f1 # DELEGATECALL CALL - :abi f(uint) 0xf4f1 # STATICCALL CALL - :abi f(uint) 0xfaf1 # CALL CALLCODE - :abi f(uint) 0xf1f2 # CALLCODE CALLCODE - :abi f(uint) 0xf2f2 # DELEGATECALL CALLCODE - :abi f(uint) 0xf4f2 # STATICCALL CALLCODE - :abi f(uint) 0xfaf2 # CALL DELEGATECALL - :abi f(uint) 0xf1f4 # CALLCODE DELEGATECALL - :abi f(uint) 0xf2f4 # DELEGATECALL DELEGATECALL - :abi f(uint) 0xf4f4 # STATICCALL DELEGATECALL - :abi f(uint) 0xfaf4 # CALL STATICCALL - :abi f(uint) 0xf1fa # CALLCODE STATICCALL - :abi f(uint) 0xf2fa # DELEGATECALL STATICCALL - :abi f(uint) 0xf4fa # STATICCALL STATICCALL - :abi f(uint) 0xfafa # Call after something fails # REVERT - :abi f(uint) 0xfd # Out of gas - :abi f(uint) 0xfe # SELFDESTRUCT - :abi f(uint) 0xff # Combined with creation of contracts # CREATE (run code in the constructor) - :abi f(uint) 0xf0 # CREATE2 (run code in the constructor) - :abi f(uint) 0xf5 # CREATE and then CALL - :abi f(uint) 0xf0f1 # CREATE2 and then CALL - :abi f(uint) 0xf5f1 # CREATE and then CALLCODE - :abi f(uint) 0xf0f2 # CREATE2 and then CALLCODE - :abi f(uint) 0xf5f2 # CREATE and then DELEGATECALL - :abi f(uint) 0xf0f4 # CREATE2 and then DELEGATECALL - :abi f(uint) 0xf5f4 # CREATE and then STATICCALL - :abi f(uint) 0xf0fa # CREATE2 and then STATICCALL - :abi f(uint) 0xf5fa # Recurse almost until the limit - :abi f(uint) 0x60BACCFA57 gasLimit: - 0x10000000000000 nonce: 1 to: cccccccccccccccccccccccccccccccccccccccc value: - 0 secretKey: "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8" gasPrice: 2000 expect: - indexes: data: !!int -1 gas: !!int -1 value: !!int -1 network: - '>=London' result: cccccccccccccccccccccccccccccccccccccccc: storage: # The result we expect 0x00: 0x60A7 000000000000000000000000000000000060BACC: storage: 0x00: 0x60A7 # Anything that happens should be reverted out of 0000000000000000000000000000000000060006: storage: 0x00: 0x60A7 # Anything that happens should be reverted out of
0
0.779719
1
0.779719
game-dev
MEDIA
0.777649
game-dev
0.752632
1
0.752632
RestedXP/RXPGuides
3,805
libs/AceGUI-3.0/widgets/AceGUIWidget-Icon.lua
--[[----------------------------------------------------------------------------- Icon Widget -------------------------------------------------------------------------------]] local Type, Version = "Icon", 21 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local select, pairs, print = select, pairs, print -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Button_OnClick(frame, button) frame.obj:Fire("OnClick", button) AceGUI:ClearFocus() end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetHeight(110) self:SetWidth(110) self:SetLabel() self:SetImage(nil) self:SetImageSize(64, 64) self:SetDisabled(false) end, -- ["OnRelease"] = nil, ["SetLabel"] = function(self, text) if text and text ~= "" then self.label:Show() self.label:SetText(text) self:SetHeight(self.image:GetHeight() + 25) else self.label:Hide() self:SetHeight(self.image:GetHeight() + 10) end end, ["SetImage"] = function(self, path, ...) local image = self.image image:SetTexture(path) if image:GetTexture() then local n = select("#", ...) if n == 4 or n == 8 then image:SetTexCoord(...) else image:SetTexCoord(0, 1, 0, 1) end end end, ["SetImageSize"] = function(self, width, height) self.image:SetWidth(width) self.image:SetHeight(height) --self.frame:SetWidth(width + 30) if self.label:IsShown() then self:SetHeight(height + 25) else self:SetHeight(height + 10) end end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.frame:Disable() self.label:SetTextColor(0.5, 0.5, 0.5) self.image:SetVertexColor(0.5, 0.5, 0.5, 0.5) else self.frame:Enable() self.label:SetTextColor(1, 1, 1) self.image:SetVertexColor(1, 1, 1, 1) end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Button", nil, UIParent) frame:Hide() frame:EnableMouse(true) frame:SetScript("OnEnter", Control_OnEnter) frame:SetScript("OnLeave", Control_OnLeave) frame:SetScript("OnClick", Button_OnClick) local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlight") label:SetPoint("BOTTOMLEFT") label:SetPoint("BOTTOMRIGHT") label:SetJustifyH("CENTER") label:SetJustifyV("TOP") label:SetHeight(18) local image = frame:CreateTexture(nil, "BACKGROUND") image:SetWidth(64) image:SetHeight(64) image:SetPoint("TOP", 0, -5) local highlight = frame:CreateTexture(nil, "HIGHLIGHT") highlight:SetAllPoints(image) highlight:SetTexture(136580) -- Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight highlight:SetTexCoord(0, 1, 0.23, 0.77) highlight:SetBlendMode("ADD") local widget = { label = label, image = image, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end widget.SetText = function(self, ...) print("AceGUI-3.0-Icon: SetText is deprecated! Use SetLabel instead!"); self:SetLabel(...) end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
0
0.869413
1
0.869413
game-dev
MEDIA
0.659066
game-dev
0.539792
1
0.539792
H4PM/Elywing
2,220
src/pocketmine/block/SignPost.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\block; use pocketmine\item\Item; use pocketmine\item\Tool; use pocketmine\level\Level; use pocketmine\Player; use pocketmine\math\Vector3; class SignPost extends Transparent{ protected $id = self::SIGN_POST; public function __construct($meta = 0){ $this->meta = $meta; } public function getHardness(){ return 1; } public function isSolid(){ return false; } public function getName(){ return "Sign Post"; } public function getBoundingBox(){ return null; } public function place(Item $item, Block $block, Block $target, $face, $fx, $fy, $fz, Player $player = null){ if($face !== 0){ $faces = [ 2 => 2, 3 => 3, 4 => 4, 5 => 5, ]; if(!isset($faces[$face])){ $this->meta = floor((($player->yaw + 180) * 16 / 360) + 0.5) & 0x0F; $this->getLevel()->setBlock($block, Block::get(Item::SIGN_POST, $this->meta), true); return true; }else{ $this->meta = $faces[$face]; $this->getLevel()->setBlock($block, Block::get(Item::WALL_SIGN, $this->meta), true); return true; } } return false; } public function onUpdate($type){ if($type === Level::BLOCK_UPDATE_NORMAL){ if($this->getSide(Vector3::SIDE_DOWN)->getId() === Block::AIR){ $this->getLevel()->useBreakOn($this); return Level::BLOCK_UPDATE_NORMAL; } } return false; } public function getDrops(Item $item) : array{ return [ [Item::SIGN, 0, 1], ]; } public function getToolType(){ return Tool::TYPE_AXE; } }
0
0.984031
1
0.984031
game-dev
MEDIA
0.959636
game-dev
0.987598
1
0.987598
advent-of-craft/2024
2,487
exercise/C#/day16/TaskAssignmentSystem/TaskAssignment.cs
namespace TaskAssignmentSystem { public class TaskAssignment(IEnumerable<Elf> elves) { public bool ReportTaskCompletion(int elfId) { var elf = elves.FirstOrDefault(e => e.Id == elfId); if (elf != null) { TotalTasksCompleted++; return true; } return false; } public int TotalTasksCompleted { get; private set; } public Elf ElfWithHighestSkill() => elves.Aggregate((prev, current) => prev.SkillLevel > current.SkillLevel ? prev : current); public Elf AssignTask(int taskSkillRequired) => elves.FirstOrDefault(elf => elf.SkillLevel >= taskSkillRequired + 1); public void IncreaseSkillLevel(int elfId, int increment) { var elf = elves.FirstOrDefault(e => e.Id == elfId); if (elf != null) { elf.SkillLevel += increment; } } public void DecreaseSkillLevel(int elfId, int decrement) { var elf = elves.FirstOrDefault(e => e.Id == elfId); if (elf != null && elf.SkillLevel - decrement > 0) { elf.SkillLevel -= decrement; } } // Ignore this function and use AssignTask instead public Elf AssignTaskBasedOnAvailability(int taskSkillRequired) { var availableElves = elves.Where(elf => elf.SkillLevel >= taskSkillRequired).ToList(); if (availableElves.Any()) { var random = new Random(); return availableElves[random.Next(availableElves.Count)]; } return null; } public bool ReassignTask(int fromElfId, int toElfId) { var fromElf = elves.FirstOrDefault(e => e.Id == fromElfId); var toElf = elves.FirstOrDefault(e => e.Id == toElfId); if (fromElf != null && toElf != null && fromElf.SkillLevel > toElf.SkillLevel) { toElf.SkillLevel = fromElf.SkillLevel; return true; } return false; } public List<Elf> ElvesBySkillDescending() => elves.OrderByDescending(e => e.SkillLevel).ToList(); public void ResetAllSkillsToBaseline(int baseline) { foreach (var elf in elves) { elf.SkillLevel = baseline; } } } }
0
0.799517
1
0.799517
game-dev
MEDIA
0.707133
game-dev
0.85745
1
0.85745
DigitalRune/DigitalRune
2,345
Samples/Samples/Shared GameObjects/GroundObject.cs
using DigitalRune.Game; using DigitalRune.Geometry.Shapes; using DigitalRune.Graphics.SceneGraph; using DigitalRune.Mathematics.Algebra; using DigitalRune.Physics; using Microsoft.Practices.ServiceLocation; using Microsoft.Xna.Framework.Content; namespace Samples { // Loads a ground plane model and creates a static rigid body for the ground plane. public class GroundObject : GameObject { private readonly IServiceLocator _services; private ModelNode _modelNode; private RigidBody _rigidBody; public GroundObject(IServiceLocator services) { _services = services; Name = "Ground"; } // OnLoad() is called when the GameObject is added to the IGameObjectService. protected override void OnLoad() { // Load model. var contentManager = _services.GetInstance<ContentManager>(); _modelNode = contentManager.Load<ModelNode>("Ground/Ground").Clone(); _modelNode.ScaleLocal = new Vector3F(0.5f); foreach (var node in _modelNode.GetSubtree()) { // Disable the CastsShadows flag for ground meshes. No need to render // this model into the shadow map. (This also avoids any shadow acne on // the ground model.) node.CastsShadows = false; // If models will never move, set the IsStatic flag. This gives the engine // more room for optimizations. Additionally, some effects, like certain // decals, may only affect static geometry. node.IsStatic = true; } // Add model node to scene graph. var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode); // Create rigid body. _rigidBody = new RigidBody(new PlaneShape(Vector3F.UnitY, 0)) { MotionType = MotionType.Static, }; // Add rigid body to the physics simulation. var simulation = _services.GetInstance<Simulation>(); simulation.RigidBodies.Add(_rigidBody); } // OnUnload() is called when the GameObject is removed from the IGameObjectService. protected override void OnUnload() { // Remove model and rigid body. _modelNode.Parent.Children.Remove(_modelNode); _modelNode.Dispose(false); _modelNode = null; _rigidBody.Simulation.RigidBodies.Remove(_rigidBody); _rigidBody = null; } } }
0
0.503323
1
0.503323
game-dev
MEDIA
0.920034
game-dev
0.802385
1
0.802385
oot-pc-port/oot-pc-port
1,164
asm/non_matchings/overlays/actors/ovl_En_Xc/func_80B3ED88.s
glabel func_80B3ED88 /* 02BA8 80B3ED88 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8 /* 02BAC 80B3ED8C AFBF0014 */ sw $ra, 0x0014($sp) /* 02BB0 80B3ED90 AFA40018 */ sw $a0, 0x0018($sp) /* 02BB4 80B3ED94 0C2CF12C */ jal func_80B3C4B0 /* 02BB8 80B3ED98 AFA5001C */ sw $a1, 0x001C($sp) /* 02BBC 80B3ED9C 8FA40018 */ lw $a0, 0x0018($sp) /* 02BC0 80B3EDA0 0C2CF11A */ jal func_80B3C468 /* 02BC4 80B3EDA4 8FA5001C */ lw $a1, 0x001C($sp) /* 02BC8 80B3EDA8 0C2CF0C7 */ jal func_80B3C31C /* 02BCC 80B3EDAC 8FA40018 */ lw $a0, 0x0018($sp) /* 02BD0 80B3EDB0 8FA40018 */ lw $a0, 0x0018($sp) /* 02BD4 80B3EDB4 0C2CFB24 */ jal func_80B3EC90 /* 02BD8 80B3EDB8 8FA5001C */ lw $a1, 0x001C($sp) /* 02BDC 80B3EDBC 8FBF0014 */ lw $ra, 0x0014($sp) /* 02BE0 80B3EDC0 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000 /* 02BE4 80B3EDC4 03E00008 */ jr $ra /* 02BE8 80B3EDC8 00000000 */ nop
0
0.639323
1
0.639323
game-dev
MEDIA
0.937677
game-dev
0.674241
1
0.674241
SpongePowered/SpongeForge
9,367
src/main/java/org/spongepowered/mod/mixin/core/world/WorldMixin_Forge.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.core.world; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.profiler.Profiler; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldServer; import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.MapStorage; import net.minecraft.world.storage.WorldInfo; import net.minecraftforge.common.DimensionManager; import org.spongepowered.asm.mixin.Dynamic; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Group; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.Slice; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.SpongeImplHooks; import org.spongepowered.common.bridge.world.WorldBridge; import org.spongepowered.mod.bridge.world.WorldBridge_Forge; import org.spongepowered.mod.event.CapturedSnapshotWrapperList; import javax.annotation.Nullable; // Use lower priority so it is applied before the changes in SpongeCommon @Mixin(value = World.class, priority = 999) public abstract class WorldMixin_Forge implements WorldBridge_Forge { private WorldInfo forgeImpl$redirectWorldInfo; @Shadow(remap = false) public java.util.ArrayList<net.minecraftforge.common.util.BlockSnapshot> capturedBlockSnapshots; @Shadow @Final public WorldProvider provider; @Shadow @Final public boolean isRemote; @Shadow protected MapStorage mapStorage; @Shadow public abstract boolean canSeeSky(BlockPos pos); @Shadow public abstract IBlockState getBlockState(BlockPos pos); @Shadow public abstract int getLightFor(EnumSkyBlock type, BlockPos pos); @Shadow public abstract void updateComparatorOutputLevel(BlockPos pos, Block blockIn); @Shadow public boolean isBlockModifiable(final EntityPlayer player, final BlockPos pos) { return false; } // Shadow @Shadow protected WorldInfo worldInfo; @Shadow public abstract long getTotalWorldTime(); /** * @author gabizou - July 25th, 2016 * @reason Optimizes several blockstate lookups for getting raw light. * * @param pos The position to get the light for * @param lightType The light type * @return The raw light */ @Overwrite private int getRawLight(final BlockPos pos, final EnumSkyBlock lightType) { if (lightType == EnumSkyBlock.SKY && this.canSeeSky(pos)) { return 15; } else { // Sponge Start - Optimize block light checks final IBlockState blockState = this.getBlockState(pos); final int blockLight = SpongeImplHooks.getChunkPosLight(blockState, (net.minecraft.world.World) (Object) this, pos); int i = lightType == EnumSkyBlock.SKY ? 0 : blockLight; // Changed by forge to use the local variable int j = SpongeImplHooks.getBlockLightOpacity(blockState, (net.minecraft.world.World) (Object) this, pos); // Sponge End if (j >= 15 && blockLight > 0) { j = 1; } if (j < 1) { j = 1; } if (j >= 15) { return 0; } else if (i >= 14) { return i; } else { for (final EnumFacing enumfacing : EnumFacing.values()) { final BlockPos blockpos = pos.offset(enumfacing); final int k = this.getLightFor(lightType, blockpos) - j; if (k > i) { i = k; } if (i >= 14) { return i; } } return i; } } } @Redirect(method = "updateEntities", at = @At( value = "INVOKE", // Forge adds the method change from isBlockLoaded(BlockPos) to isBlockLoaded(BlockPos,boolean).... target = "Lnet/minecraft/world/World;isBlockLoaded(Lnet/minecraft/util/math/BlockPos;Z)Z"), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/tileentity/TileEntity;isInvalid()Z", ordinal = 0), to = @At(value = "INVOKE", target = "Lnet/minecraft/world/border/WorldBorder;contains(Lnet/minecraft/util/math/BlockPos;)Z") ) ) private boolean forgeImpl$useTileActiveChunk(final World world, final BlockPos pos, final boolean allowEmpty) { return true; // If we got to here, we already have the method `bridge$shouldTick()` passing } /** * @author gabizou - March 1st, 2019 - 1.12.2 * @reason Forge adds the comparator output update to notify neighboring * blocks, and when Sponge is performing block restores, this needs to be * ignored when Sponge performs the restore. To be overridden in the mod * equivalent to MixinWorldServer. * * @param world This world * @param pos The position of the tile being removed * @param blockIn The block type of the tile entity being removed */ @Redirect(method = "removeTileEntity", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;updateComparatorOutputLevel(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/Block;)V")) protected void forgeImpl$UseComparatorOutputLevel(final World world, final BlockPos pos, final Block blockIn, final BlockPos samePos) { this.updateComparatorOutputLevel(pos, blockIn); } @Inject(method = "getWorldInfo", at = @At("HEAD"), cancellable = true) private void forgeImpl$getRedirectedWorldInfoIfAvailable(final CallbackInfoReturnable<WorldInfo> cir) { if (this.provider.getDimension() != 0 && this.forgeImpl$redirectWorldInfo != null) { cir.setReturnValue(this.forgeImpl$redirectWorldInfo); } } @Inject(method = "getMapStorage", at = @At("HEAD"), cancellable = true) private void forgeImpl$getOverworldMapStorageInsteadOfMultiDimension(final CallbackInfoReturnable<MapStorage> cir) { // Forge only uses a single save handler so we need to always pass overworld's mapstorage here if (!this.isRemote && (this.mapStorage == null || this.provider.getDimension() != 0)) { final WorldServer overworld = DimensionManager.getWorld(0); if (overworld != null) { cir.setReturnValue(overworld.getMapStorage()); } } } @Override public void forgeBridge$setRedirectedWorldInfo(@Nullable final WorldInfo info) { this.forgeImpl$redirectWorldInfo = info; } @Inject(method = "<init>", at = @At("RETURN")) private void onIniitToSetForgeList(final ISaveHandler saveHandlerIn, final WorldInfo info, final WorldProvider providerIn, final Profiler profilerIn, final boolean client, final CallbackInfo ci) { if (!((WorldBridge) this).bridge$isFake()) { this.capturedBlockSnapshots = new CapturedSnapshotWrapperList((World) (Object) this); } } @ModifyArg(method = "updateWeatherBody", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setRainTime(I)V")) int vanillaImpl$updateRainTimeStart(final int newRainTime) { return newRainTime; } @ModifyArg(method = "updateWeatherBody", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setThunderTime(I)V")) int vanillaImpl$updateThunderTimeStart(final int newThunderTime) { return newThunderTime; } }
0
0.93566
1
0.93566
game-dev
MEDIA
0.998172
game-dev
0.979742
1
0.979742
Hiro420/GI_CBT1_Data
2,524
resources/lua/actor/quest/MQ382.lua
require('Actor/ActorCommon') local questActorProxy = require('Actor/Quest/QuestActorProxy') local Quest382 = class("Quest382", questActorProxy) Quest382.defaultAlias = "Quest382" local q382Cfg = require('Quest/Client/Q382ClientConfig') local subIDs = q382Cfg.SubIDs -- Generated function Quest382:OnSubStartHandlerBuild() self.subStartHandlers = {} self.subStartHandlers["38201"] = self.OnSubStart38201 self.subStartHandlers["38202"] = self.OnSubStart38202 self.subStartHandlers["38203"] = self.OnSubStart38203 end function Quest382:OnSubFinishHandlerBuild() self.subFinishHandlers = {} self.subFinishHandlers["38201"] = self.OnSubFinish38201 self.subFinishHandlers["38202"] = self.OnSubFinish38202 self.subFinishHandlers["38203"] = self.OnSubFinish38203 end -- local param begin -- local param end -- local method begin --@region sub start handlers function Quest382:OnSubStart38201(quest) print("38201 start:...") -- local quest = actorMgr:GetActor(q382Cfg.ActorAlias) -- if quest ~= nil then -- quest:FinishQuest(false, nil) -- end actorMgr:CreateActorWithPos("Q382Trigger", "Actor/Gadget/Q382Trigger", 70900002, 0, sceneData:GetDummyPoint(3,"Q382DragonTill").pos, sceneData:GetDummyPoint(3,"Q382DragonTill").rot, true, false) end function Quest382:OnSubStart38202(quest) print("38202 start:...") self:CallDelay(20,self.DestroyMark) end function Quest382:OnSubStart38203(quest) print("38203 start:...") -- TODO: Do sth on sub quest 38202 start local quest = actorMgr:GetActor(q382Cfg.ActorAlias) if quest ~= nil then quest:FinishQuest(false, nil) end end --@endregion --@region sub finish handlers function Quest382:OnSubFinish38201(quest) print("OnFinished 38201") self:NarratorOnlyTask(q382Cfg.PaimonNarrator, nil, "Story") self:EnterSceneLookCamera(sceneData:GetDummyPoint(3,"Q382DragonTillChest").pos, 4.5, 3, true) -- globalActor:SpawnGadget(70900201, sceneData:GetDummyPoint(3,"Q382DragonTillChest").pos, sceneData:GetDummyPoint(3,"Q382DragonTillChest").rot, "Tearchest", 3) end function Quest382:OnSubFinish38202(quest) print("OnFinished 38202") self:UnSpawn("Tearchest") -- self:NarratorOnlyTask(q382Cfg.StoryNarrator, nil, "Story") end function Quest382:DestroyMark() self:UnSpawn("Tearchest") end function Quest382:OnSubFinish38203(quest) print("OnFinished 38202") end --@endregion function Quest382:Start() end function Quest382:OnDestroy() end return Quest382
0
0.745767
1
0.745767
game-dev
MEDIA
0.933198
game-dev
0.653868
1
0.653868
kwsch/pkNX
7,371
pkNX.WinForms/Subforms/PaldeaMap.cs
using System; using System.Collections.Generic; using pkNX.Game; using pkNX.Structures; using pkNX.Structures.FlatBuffers; using pkNX.Structures.FlatBuffers.SV; using pkNX.Structures.FlatBuffers.SV.Trinity; namespace pkNX.WinForms.Subforms; public class PaldeaMap { public readonly List<string>[] AreaNames = [[], [], []]; private readonly Dictionary<string, AreaDef9>[] Areas = [[], [], []]; public readonly Dictionary<string, HavokCollision.AABBTree>[] AreaCollisionTrees = [[], [], []]; public readonly Dictionary<string, BoxCollision9>[] AreaCollisionBoxes = [[], [], []]; private readonly IList<FieldMainArea>[] MainAreas = new IList<FieldMainArea>[3]; private readonly IList<FieldSubArea>[] SubAreas = new IList<FieldSubArea>[3]; private readonly IList<FieldInsideArea>[] InsideAreas = new IList<FieldInsideArea>[3]; private readonly IList<FieldDungeonArea>[] DungeonAreas = new IList<FieldDungeonArea>[3]; private readonly IList<FieldLocation>[] FieldLocations = new IList<FieldLocation>[3]; public PaldeaMap(GameManagerSV ROM) { MainAreas[0] = FlatBufferConverter.DeserializeFrom<FieldMainAreaArray>(ROM.GetPackedFile("world/data/field/area/field_main_area/field_main_area_array.bin")).Table; SubAreas[0] = FlatBufferConverter.DeserializeFrom<FieldSubAreaArray>(ROM.GetPackedFile("world/data/field/area/field_sub_area/field_sub_area_array.bin")).Table; InsideAreas[0] = FlatBufferConverter.DeserializeFrom<FieldInsideAreaArray>(ROM.GetPackedFile("world/data/field/area/field_inside_area/field_inside_area_array.bin")).Table; DungeonAreas[0] = FlatBufferConverter.DeserializeFrom<FieldDungeonAreaArray>(ROM.GetPackedFile("world/data/field/area/field_dungeon_area/field_dungeon_area_array.bin")).Table; FieldLocations[0] = FlatBufferConverter.DeserializeFrom<FieldLocationArray>(ROM.GetPackedFile("world/data/field/area/field_location/field_location_array.bin")).Table; MainAreas[1] = FlatBufferConverter.DeserializeFrom<FieldMainAreaArray>(ROM.GetPackedFile("world/data/field/area_su1/field_main_area_su1/field_main_area_su1_array.bin")).Table; SubAreas[1] = FlatBufferConverter.DeserializeFrom<FieldSubAreaArray>(ROM.GetPackedFile("world/data/field/area_su1/field_sub_area_su1/field_sub_area_su1_array.bin")).Table; InsideAreas[1] = FlatBufferConverter.DeserializeFrom<FieldInsideAreaArray>(ROM.GetPackedFile("world/data/field/area_su1/field_inside_area_su1/field_inside_area_su1_array.bin")).Table; DungeonAreas[1] = FlatBufferConverter.DeserializeFrom<FieldDungeonAreaArray>(ROM.GetPackedFile("world/data/field/area_su1/field_dungeon_area_su1/field_dungeon_area_su1_array.bin")).Table; FieldLocations[1] = FlatBufferConverter.DeserializeFrom<FieldLocationArray>(ROM.GetPackedFile("world/data/field/area_su1/field_location_su1/field_location_su1_array.bin")).Table; MainAreas[2] = FlatBufferConverter.DeserializeFrom<FieldMainAreaArray>(ROM.GetPackedFile("world/data/field/area_su2/field_main_area_su2/field_main_area_su2_array.bin")).Table; SubAreas[2] = FlatBufferConverter.DeserializeFrom<FieldSubAreaArray>(ROM.GetPackedFile("world/data/field/area_su2/field_sub_area_su2/field_sub_area_su2_array.bin")).Table; InsideAreas[2] = FlatBufferConverter.DeserializeFrom<FieldInsideAreaArray>(ROM.GetPackedFile("world/data/field/area_su2/field_inside_area_su2/field_inside_area_su2_array.bin")).Table; DungeonAreas[2] = FlatBufferConverter.DeserializeFrom<FieldDungeonAreaArray>(ROM.GetPackedFile("world/data/field/area_su2/field_dungeon_area_su2/field_dungeon_area_su2_array.bin")).Table; FieldLocations[2] = []; // FlatBufferConverter.DeserializeFrom<FieldLocationArray>(ROM.GetPackedFile("world/data/field/area_su2/field_location_su2/field_location_su2_array.bin")).Table; LoadScenes(ROM); } private void LoadScenes(GameManagerSV ROM) { // Load default scenes LoadScene(ROM, ROM.GetPackedFile("world/scene/parts/field/resident_event/resident_area_collision_/resident_area_collision_0.trscn"), 0); // Load default scenes LoadScene(ROM, ROM.GetPackedFile("world/scene/parts/field/main/field_1/field_main/resident_event/resident_area_collision_/resident_area_collision_0.trscn"), 1); // Load default scenes LoadScene(ROM, ROM.GetPackedFile("world/scene/parts/field/main/field_2/field_main/resident_event/resident_area_collision_/resident_area_collision_0.trscn"), 2); } private void LoadScene(GameManagerSV ROM, byte[] collisionFile, int index) { var area_collision = FlatBufferConverter.DeserializeFrom<TrinitySceneObjectTemplate>(collisionFile); foreach (var obj in area_collision.Objects) { if (obj is not { Type: "trinity_SceneObject", SubObjects.Count: > 0 }) continue; if (obj.SubObjects[0].Type != "trinity_CollisionComponent") continue; var sceneObject = FlatBufferConverter.DeserializeFrom<TrinitySceneObject>(obj.Data); var trcData = obj.SubObjects[0].Data; var trc = FlatBufferConverter.DeserializeFrom<TrinityComponent>(trcData); var collisionComponent = trc.Component.CollisionComponent; AreaNames[index].Add(sceneObject.ObjectName); var areaInfo = FindAreaInfo(index, sceneObject.ObjectName); var shape = collisionComponent.Shape; if (shape.TryGet(out Box? box)) { // Box collision, obj.ObjectPosition.Field_02 is pos, box.Field_01 is size of box AreaCollisionBoxes[index][sceneObject.ObjectName] = new BoxCollision9 { Position = sceneObject.ObjectPosition.Field02, Size = box!.Field01, }; } if (shape.TryGet(out Havok? havok)) { var havokData = ROM.GetPackedFile(havok!.TrcolFilePath); AreaCollisionTrees[index][sceneObject.ObjectName] = HavokCollision.ParseAABBTree(havokData); } Areas[index][sceneObject.ObjectName] = new AreaDef9 { SceneObject = sceneObject, CollisionComponent = collisionComponent, Info = areaInfo, }; } } public AreaInfo FindAreaInfo(int index, string name) { foreach (var area in MainAreas[index]) { if (area.Name == name) return area.Info; } foreach (var area in SubAreas[index]) { if (area.Name == name) return area.Info; } foreach (var area in InsideAreas[index]) { if (area.Name == name) return area.Info; } foreach (var area in DungeonAreas[index]) { if (area.Name == name) return area.Info; } foreach (var area in FieldLocations[index]) { if (area.Name == name) return area.Info; } throw new ArgumentException($"Unknown area {name}"); } } public class AreaDef9 { public required TrinitySceneObject SceneObject; public required CollisionComponent CollisionComponent; public required AreaInfo Info; }
0
0.88635
1
0.88635
game-dev
MEDIA
0.872163
game-dev
0.984331
1
0.984331
M-Studio-M/2D-Controller
21,512
Library/PackageCache/com.unity.cinemachine@2.4.0/Editor/Utility/SaveDuringPlay.cs
using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; namespace SaveDuringPlay { /// <summary>A collection of tools for finding objects</summary> internal static class ObjectTreeUtil { /// <summary> /// Get the full name of an object, travelling up the transform parents to the root. /// </summary> public static string GetFullName(GameObject current) { if (current == null) return ""; if (current.transform.parent == null) return "/" + current.name; return GetFullName(current.transform.parent.gameObject) + "/" + current.name; } /// <summary> /// Will find the named object, active or inactive, from the full path. /// </summary> public static GameObject FindObjectFromFullName(string fullName, GameObject[] roots) { if (fullName == null || fullName.Length == 0 || roots == null) return null; string[] path = fullName.Split('/'); if (path.Length < 2) // skip leading '/' return null; Transform root = null; for (int i = 0; root == null && i < roots.Length; ++i) if (roots[i].name == path[1]) root = roots[i].transform; if (root == null) return null; for (int i = 2; i < path.Length; ++i) // skip root { bool found = false; for (int c = 0; c < root.childCount; ++c) { Transform child = root.GetChild(c); if (child.name == path[i]) { found = true; root = child; break; } } if (!found) return null; } return root.gameObject; } /// <summary>Finds all the root objects in a scene, active or not</summary> public static GameObject[] FindAllRootObjectsInScene() { return UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); } /// <summary> /// This finds all the behaviours in scene, active or inactive, excluding prefabs /// </summary> public static T[] FindAllBehavioursInScene<T>() where T : MonoBehaviour { List<T> objectsInScene = new List<T>(); foreach (T b in Resources.FindObjectsOfTypeAll<T>()) { GameObject go = b.gameObject; if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave) continue; if (EditorUtility.IsPersistent(go.transform.root.gameObject)) continue; objectsInScene.Add(b); } return objectsInScene.ToArray(); } } class GameObjectFieldScanner { /// <summary> /// Called for each leaf field. Return value should be true if action was taken. /// It will be propagated back to the caller. /// </summary> public OnLeafFieldDelegate OnLeafField; public delegate bool OnLeafFieldDelegate(string fullName, Type type, ref object value); /// <summary> /// Called for each field node, if and only if OnLeafField() for it or one /// of its leaves returned true. /// </summary> public OnFieldValueChangedDelegate OnFieldValueChanged; public delegate bool OnFieldValueChangedDelegate( string fullName, FieldInfo fieldInfo, object fieldOwner, object value); /// <summary> /// Called for each field, to test whether to proceed with scanning it. Return true to scan. /// </summary> public FilterFieldDelegate FilterField; public delegate bool FilterFieldDelegate(string fullName, FieldInfo fieldInfo); /// <summary> /// Which fields will be scanned /// </summary> public BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance; bool ScanFields(string fullName, Type type, ref object obj) { bool doneSomething = false; // Check if it's a complex type bool isLeaf = true; if (obj != null && !typeof(Component).IsAssignableFrom(type) && !typeof(ScriptableObject).IsAssignableFrom(type) && !typeof(GameObject).IsAssignableFrom(type)) { // Is it an array? if (type.IsArray) { isLeaf = false; Array array = obj as Array; object arrayLength = array.Length; if (OnLeafField != null && OnLeafField( fullName + ".Length", arrayLength.GetType(), ref arrayLength)) { Array newArray = Array.CreateInstance( array.GetType().GetElementType(), Convert.ToInt32(arrayLength)); Array.Copy(array, 0, newArray, 0, Math.Min(array.Length, newArray.Length)); array = newArray; doneSomething = true; } for (int i = 0; i < array.Length; ++i) { object element = array.GetValue(i); if (ScanFields(fullName + "[" + i + "]", array.GetType().GetElementType(), ref element)) { array.SetValue(element, i); doneSomething = true; } } if (doneSomething) obj = array; } else { // Check if it's a complex type FieldInfo[] fields = obj.GetType().GetFields(bindingFlags); if (fields.Length > 0) { isLeaf = false; for (int i = 0; i < fields.Length; ++i) { string name = fullName + "." + fields[i].Name; if (FilterField == null || FilterField(name, fields[i])) { object fieldValue = fields[i].GetValue(obj); if (ScanFields(name, fields[i].FieldType, ref fieldValue)) { doneSomething = true; if (OnFieldValueChanged != null) OnFieldValueChanged(name, fields[i], obj, fieldValue); } } } } } } // If it's a leaf field then call the leaf handler if (isLeaf && OnLeafField != null) if (OnLeafField(fullName, type, ref obj)) doneSomething = true; return doneSomething; } public bool ScanFields(string fullName, MonoBehaviour b) { bool doneSomething = false; FieldInfo[] fields = b.GetType().GetFields(bindingFlags); if (fields.Length > 0) { for (int i = 0; i < fields.Length; ++i) { string name = fullName + "." + fields[i].Name; if (FilterField == null || FilterField(name, fields[i])) { object fieldValue = fields[i].GetValue(b); if (ScanFields(name, fields[i].FieldType, ref fieldValue)) doneSomething = true; // If leaf action was taken, propagate it up to the parent node if (doneSomething && OnFieldValueChanged != null) OnFieldValueChanged(fullName, fields[i], b, fieldValue); } } } return doneSomething; } /// <summary> /// Recursively scan the MonoBehaviours of a GameObject and its children. /// For each leaf field found, call the OnFieldValue delegate. /// </summary> public bool ScanFields(GameObject go, string prefix = null) { bool doneSomething = false; if (prefix == null) prefix = ""; else if (prefix.Length > 0) prefix += "."; MonoBehaviour[] components = go.GetComponents<MonoBehaviour>(); for (int i = 0; i < components.Length; ++i) { MonoBehaviour c = components[i]; if (c != null && ScanFields(prefix + c.GetType().FullName + i, c)) doneSomething = true; } return doneSomething; } }; /// <summary> /// Using reflection, this class scans a GameObject (and optionally its children) /// and records all the field settings. This only works for "nice" field settings /// within MonoBehaviours. Changes to the behaviour stack made between saving /// and restoring will fool this class. /// </summary> class ObjectStateSaver { string mObjectFullPath; Dictionary<string, string> mValues = new Dictionary<string, string>(); /// <summary> /// Recursively collect all the field values in the MonoBehaviours /// owned by this object and its descendants. The values are stored /// in an internal dictionary. /// </summary> public void CollectFieldValues(GameObject go) { mObjectFullPath = ObjectTreeUtil.GetFullName(go); GameObjectFieldScanner scanner = new GameObjectFieldScanner(); scanner.FilterField = FilterField; scanner.OnLeafField = (string fullName, Type type, ref object value) => { // Save the value in the dictionary mValues[fullName] = StringFromLeafObject(value); //Debug.Log(mObjectFullPath + "." + fullName + " = " + mValues[fullName]); return false; }; scanner.ScanFields(go); } public GameObject FindSavedGameObject(GameObject[] roots) { return ObjectTreeUtil.FindObjectFromFullName(mObjectFullPath, roots); } public string ObjetFullPath { get { return mObjectFullPath; } } /// <summary> /// Recursively scan the MonoBehaviours of a GameObject and its children. /// For each field found, look up its value in the internal dictionary. /// If it's present and its value in the dictionary differs from the actual /// value in the game object, Set the GameObject's value using the value /// recorded in the dictionary. /// </summary> public bool PutFieldValues(GameObject go, GameObject[] roots) { GameObjectFieldScanner scanner = new GameObjectFieldScanner(); scanner.FilterField = FilterField; scanner.OnLeafField = (string fullName, Type type, ref object value) => { // Lookup the value in the dictionary string savedValue; if (mValues.TryGetValue(fullName, out savedValue) && StringFromLeafObject(value) != savedValue) { //Debug.Log("Put " + mObjectFullPath + "." + fullName + " = " + mValues[fullName]); value = LeafObjectFromString(type, mValues[fullName].Trim(), roots); return true; // changed } return false; }; scanner.OnFieldValueChanged = (fullName, fieldInfo, fieldOwner, value) => { fieldInfo.SetValue(fieldOwner, value); return true; }; return scanner.ScanFields(go); } /// Ignore fields marked with the [NoSaveDuringPlay] attribute bool FilterField(string fullName, FieldInfo fieldInfo) { var attrs = fieldInfo.GetCustomAttributes(false); foreach (var attr in attrs) if (attr.GetType().Name.Contains("NoSaveDuringPlay")) return false; return true; } /// <summary> /// Parse a string to generate an object. /// Only very limited primitive object types are supported. /// Enums, Vectors and most other structures are automatically supported, /// because the reflection system breaks them down into their primitive components. /// You can add more support here, as needed. /// </summary> static object LeafObjectFromString(Type type, string value, GameObject[] roots) { if (type == typeof(Single)) return float.Parse(value); if (type == typeof(Double)) return double.Parse(value); if (type == typeof(Boolean)) return Boolean.Parse(value); if (type == typeof(string)) return value; if (type == typeof(Int32)) return Int32.Parse(value); if (type == typeof(UInt32)) return UInt32.Parse(value); if (typeof(Component).IsAssignableFrom(type)) { // Try to find the named game object GameObject go = ObjectTreeUtil.FindObjectFromFullName(value, roots); return (go != null) ? go.GetComponent(type) : null; } if (typeof(GameObject).IsAssignableFrom(type)) { // Try to find the named game object return GameObject.Find(value); } if (typeof(ScriptableObject).IsAssignableFrom(type)) { return AssetDatabase.LoadAssetAtPath(value, type); } return null; } static string StringFromLeafObject(object obj) { if (obj == null) return string.Empty; if (typeof(Component).IsAssignableFrom(obj.GetType())) { Component c = (Component)obj; if (c == null) // Component overrides the == operator, so we have to check return string.Empty; return ObjectTreeUtil.GetFullName(c.gameObject); } if (typeof(GameObject).IsAssignableFrom(obj.GetType())) { GameObject go = (GameObject)obj; if (go == null) // GameObject overrides the == operator, so we have to check return string.Empty; return ObjectTreeUtil.GetFullName(go); } if (typeof(ScriptableObject).IsAssignableFrom(obj.GetType())) { return AssetDatabase.GetAssetPath(obj as ScriptableObject); } return obj.ToString(); } }; /// <summary> /// For all registered object types, record their state when exiting Play Mode, /// and restore that state to the objects in the scene. This is a very limited /// implementation which has not been rigorously tested with many objects types. /// It's quite possible that not everything will be saved. /// /// This class is expected to become obsolete when Unity implements this functionality /// in a more general way. /// /// To use this class, /// drop this script into your project, and add the [SaveDuringPlay] attribute to your class. /// /// Note: if you want some specific field in your class NOT to be saved during play, /// add a property attribute whose class name contains the string "NoSaveDuringPlay" /// and the field will not be saved. /// </summary> [InitializeOnLoad] public class SaveDuringPlay { public static string kEnabledKey = "SaveDuringPlay_Enabled"; public static bool Enabled { get { return EditorPrefs.GetBool(kEnabledKey, false); } set { if (value != Enabled) { EditorPrefs.SetBool(kEnabledKey, value); } } } static SaveDuringPlay() { // Install our callbacks #if UNITY_2017_2_OR_NEWER EditorApplication.playModeStateChanged += OnPlayStateChanged; #else EditorApplication.update += OnEditorUpdate; EditorApplication.playmodeStateChanged += OnPlayStateChanged; #endif } #if UNITY_2017_2_OR_NEWER static void OnPlayStateChanged(PlayModeStateChange pmsc) { if (Enabled) { // If exiting playmode, collect the state of all interesting objects if (pmsc == PlayModeStateChange.ExitingPlayMode) SaveAllInterestingStates(); else if (pmsc == PlayModeStateChange.EnteredEditMode && sSavedStates != null) RestoreAllInterestingStates(); } } #else static void OnPlayStateChanged() { // If exiting playmode, collect the state of all interesting objects if (Enabled) { if (!EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying) SaveAllInterestingStates(); } } static float sWaitStartTime = 0; static void OnEditorUpdate() { if (Enabled && sSavedStates != null && !Application.isPlaying) { // Wait a bit for things to settle before applying the saved state const float WaitTime = 1f; // GML todo: is there a better way to do this? float time = Time.realtimeSinceStartup; if (sWaitStartTime == 0) sWaitStartTime = time; else if (time - sWaitStartTime > WaitTime) { RestoreAllInterestingStates(); sWaitStartTime = 0; } } } #endif /// <summary> /// If you need to get notified before state is collected for hotsave, this is the place /// </summary> public static OnHotSaveDelegate OnHotSave; public delegate void OnHotSaveDelegate(); /// Collect all relevant objects, active or not static Transform[] FindInterestingObjects() { List<Transform> objects = new List<Transform>(); MonoBehaviour[] everything = ObjectTreeUtil.FindAllBehavioursInScene<MonoBehaviour>(); foreach (var b in everything) { var attrs = b.GetType().GetCustomAttributes(true); foreach (var attr in attrs) { if (attr.GetType().Name.Contains("SaveDuringPlay")) { //Debug.Log("Found " + ObjectTreeUtil.GetFullName(b.gameObject) + " for hot-save"); objects.Add(b.transform); break; } } } return objects.ToArray(); } static List<ObjectStateSaver> sSavedStates = null; static GameObject sSaveStatesGameObject; static void SaveAllInterestingStates() { //Debug.Log("Exiting play mode: Saving state for all interesting objects"); if (OnHotSave != null) OnHotSave(); sSavedStates = new List<ObjectStateSaver>(); Transform[] objects = FindInterestingObjects(); foreach (Transform obj in objects) { ObjectStateSaver saver = new ObjectStateSaver(); saver.CollectFieldValues(obj.gameObject); sSavedStates.Add(saver); } if (sSavedStates.Count == 0) sSavedStates = null; } static void RestoreAllInterestingStates() { //Debug.Log("Updating state for all interesting objects"); bool dirty = false; GameObject[] roots = ObjectTreeUtil.FindAllRootObjectsInScene(); foreach (ObjectStateSaver saver in sSavedStates) { GameObject go = saver.FindSavedGameObject(roots); if (go != null) { Undo.RegisterFullObjectHierarchyUndo(go, "SaveDuringPlay"); if (saver.PutFieldValues(go, roots)) { //Debug.Log("SaveDuringPlay: updated settings of " + saver.ObjetFullPath); EditorUtility.SetDirty(go); dirty = true; } } } if (dirty) UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); sSavedStates = null; } } }
0
0.914921
1
0.914921
game-dev
MEDIA
0.743855
game-dev
0.984626
1
0.984626
DecentSoftware-eu/DecentHolograms
2,570
nms/nms-paper_v1_21_R6/src/main/java/eu/decentsoftware/holograms/nms/paper_v1_21_R6/HeadHologramRenderer.java
package eu.decentsoftware.holograms.nms.paper_v1_21_R6; import eu.decentsoftware.holograms.nms.api.NmsHologramPartData; import eu.decentsoftware.holograms.nms.api.renderer.NmsHeadHologramRenderer; import eu.decentsoftware.holograms.shared.DecentPosition; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; class HeadHologramRenderer implements NmsHeadHologramRenderer { private final int entityId; private final boolean small; HeadHologramRenderer(EntityIdGenerator entityIdGenerator) { this(entityIdGenerator, false); } protected HeadHologramRenderer(EntityIdGenerator entityIdGenerator, boolean small) { this.entityId = entityIdGenerator.getFreeEntityId(); this.small = small; } @Override public void display(Player player, NmsHologramPartData<ItemStack> data) { DecentPosition position = data.getPosition(); ItemStack content = data.getContent(); DecentPosition offsetPosition = offsetPosition(position); EntityPacketsBuilder.create() .withSpawnEntity(entityId, EntityType.ARMOR_STAND, offsetPosition) .withEntityMetadata(entityId, EntityMetadataBuilder.create() .withInvisible() .withNoGravity() .withArmorStandProperties(small, true) .toWatchableObjects()) .withHelmet(entityId, content) .sendTo(player); } @Override public void updateContent(Player player, NmsHologramPartData<ItemStack> data) { EntityPacketsBuilder.create() .withHelmet(entityId, data.getContent()) .sendTo(player); } @Override public void move(Player player, NmsHologramPartData<ItemStack> data) { EntityPacketsBuilder.create() .withTeleportEntity(entityId, offsetPosition(data.getPosition())) .sendTo(player); } @Override public void hide(Player player) { EntityPacketsBuilder.create() .withRemoveEntity(entityId) .sendTo(player); } @Override public double getHeight(NmsHologramPartData<ItemStack> data) { return small ? 0.5d : 0.7d; } @Override public int[] getEntityIds() { return new int[]{entityId}; } private DecentPosition offsetPosition(DecentPosition position) { double offsetY = small ? 1.1875d : 2.0d; return position.subtractY(offsetY); } }
0
0.813535
1
0.813535
game-dev
MEDIA
0.764523
game-dev
0.95095
1
0.95095
kisence-mian/UnityLockStepDemo
3,651
LockStepDemo/Client/Assets/Script/SyncFrameWork/ECS/ECSEvent.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public delegate void ECSEventHandle(EntityBase entity,params object[] objs); public class ECSEvent { WorldBase m_world; private Dictionary<string, ECSEventHandle> m_EventDict = new Dictionary<string, ECSEventHandle>(); //只在重计算和本地计算调用 private Dictionary<string, ECSEventHandle> m_certaintyEventDict = new Dictionary<string, ECSEventHandle>(); List<EventCache> m_eventCache = new List<EventCache>(); public ECSEvent(WorldBase world) { m_world = world; } public void AddListener(string key, ECSEventHandle handle,bool certainty = false) { if (!certainty) { if (m_EventDict.ContainsKey(key)) { m_EventDict[key] += handle; } else { m_EventDict.Add(key, handle); } } else { if (m_certaintyEventDict.ContainsKey(key)) { m_certaintyEventDict[key] += handle; } else { m_certaintyEventDict.Add(key, handle); } } } public void RemoveListener(string key, ECSEventHandle handle, bool certainty = false) { if (!certainty) { if (m_EventDict.ContainsKey(key)) { m_EventDict[key] -= handle; } } else { if (m_certaintyEventDict.ContainsKey(key)) { m_certaintyEventDict[key] -= handle; } } } public void DispatchEvent(string key, EntityBase entity, params object[] objs) { if (m_EventDict.ContainsKey(key)) { try { m_EventDict[key](entity, objs); } catch(Exception e) { Debug.LogError("DispatchECSEvent " + e.ToString()); } } if (m_world.m_isCertainty) { if (m_certaintyEventDict.ContainsKey(key)) { try { m_certaintyEventDict[key](entity, objs); } catch (Exception e) { Debug.LogError("DispatchECSEvent isCertainty " + e.ToString()); } } } else { EventCache e = new EventCache(); e.frame = m_world.FrameCount; e.eventKey = key; e.entity = entity; e.objs = objs; m_eventCache.Add(e); } } //这一帧之前的计算认为全部有效 public void DispatchCertainty(int frame) { for (int i = 0; i < m_eventCache.Count; i++) { EventCache e = m_eventCache[i]; if (e.frame <= frame) { if (m_certaintyEventDict.ContainsKey(e.eventKey)) { m_certaintyEventDict[e.eventKey](e.entity, e.objs); } m_eventCache.RemoveAt(i); i--; } } } //推倒重新计算 public void ClearCache(int frame) { for (int i = 0; i < m_eventCache.Count; i++) { EventCache e = m_eventCache[i]; if (e.frame <= frame) { m_eventCache.RemoveAt(i); i--; } } } public struct EventCache { public int frame; public string eventKey; public EntityBase entity; public object[] objs; } }
0
0.722314
1
0.722314
game-dev
MEDIA
0.591127
game-dev
0.850641
1
0.850641
localcc/PalworldModdingKit
2,117
Source/Pal/Public/PalMapObjectMasterData.h
#pragma once #include "CoreMinimal.h" #include "Engine/DataTable.h" #include "EPalMapObjectMaterialSubType.h" #include "EPalMapObjectMaterialType.h" #include "PalMapObjectMasterData.generated.h" class APalMapObject; USTRUCT(BlueprintType) struct PAL_API FPalMapObjectMasterData : public FTableRowBase { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FName OverrideNameMsgID; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FName BlueprintClassName; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TSoftClassPtr<APalMapObject> BlueprintClassSoft; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) EPalMapObjectMaterialType MaterialType; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) EPalMapObjectMaterialSubType MaterialSubType; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bCollectionObject; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 Hp; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 Defense; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bBelongToBaseCamp; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 DistributeExpAroundPlayer; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float DeteriorationDamage; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float ExtinguishBurnWorkAmount; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bShowHPGauge; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool bInDevelop; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 Editor_RowNameHash; FPalMapObjectMasterData(); };
0
0.916153
1
0.916153
game-dev
MEDIA
0.896728
game-dev
0.539255
1
0.539255
Phobos-developers/Phobos
5,392
src/Ext/Bullet/Trajectories/ParabolaTrajectory.h
#pragma once #include "PhobosTrajectory.h" enum class ParabolaFireMode { Speed = 0, Height = 1, Angle = 2, SpeedAndHeight = 3, HeightAndAngle = 4, SpeedAndAngle = 5, }; class ParabolaTrajectoryType final : public PhobosTrajectoryType { public: ParabolaTrajectoryType() : PhobosTrajectoryType() , DetonationDistance { Leptons(102) } , TargetSnapDistance { Leptons(128) } , OpenFireMode { ParabolaFireMode::Speed } , ThrowHeight { 600 } , LaunchAngle { 30.0 } , LeadTimeCalculate { false } , DetonationAngle { -90.0 } , DetonationHeight { -1 } , BounceTimes { 0 } , BounceOnWater { false } , BounceDetonate { false } , BounceAttenuation { 0.8 } , BounceCoefficient { 0.8 } , OffsetCoord { { 0, 0, 0 } } , RotateCoord { 0 } , MirrorCoord { true } , UseDisperseBurst { false } , AxisOfRotation { { 0, 0, 1 } } { } virtual bool Load(PhobosStreamReader& Stm, bool RegisterForChange) override; virtual bool Save(PhobosStreamWriter& Stm) const override; virtual std::unique_ptr<PhobosTrajectory> CreateInstance() const override; virtual void Read(CCINIClass* const pINI, const char* pSection) override; virtual TrajectoryFlag Flag() const override { return TrajectoryFlag::Parabola; } Valueable<Leptons> DetonationDistance; Valueable<Leptons> TargetSnapDistance; Valueable<ParabolaFireMode> OpenFireMode; Valueable<int> ThrowHeight; Valueable<double> LaunchAngle; Valueable<bool> LeadTimeCalculate; Valueable<double> DetonationAngle; Valueable<int> DetonationHeight; Valueable<int> BounceTimes; Valueable<bool> BounceOnWater; Valueable<bool> BounceDetonate; Valueable<double> BounceAttenuation; Valueable<double> BounceCoefficient; Valueable<CoordStruct> OffsetCoord; Valueable<double> RotateCoord; Valueable<bool> MirrorCoord; Valueable<bool> UseDisperseBurst; Valueable<CoordStruct> AxisOfRotation; private: template <typename T> void Serialize(T& Stm); }; class ParabolaTrajectory final : public PhobosTrajectory { public: ParabolaTrajectory(noinit_t) { } ParabolaTrajectory(ParabolaTrajectoryType const* trajType) : Type { trajType } , ThrowHeight { trajType->ThrowHeight > 0 ? trajType->ThrowHeight : 600 } , BounceTimes { trajType->BounceTimes } , OffsetCoord { trajType->OffsetCoord.Get() } , UseDisperseBurst { trajType->UseDisperseBurst } , ShouldDetonate { false } , ShouldBounce { false } , NeedExtraCheck { false } , LastTargetCoord {} , CurrentBurst { 0 } , CountOfBurst { 0 } , WaitOneFrame { 0 } , LastVelocity {} { } virtual bool Load(PhobosStreamReader& Stm, bool RegisterForChange) override; virtual bool Save(PhobosStreamWriter& Stm) const override; virtual TrajectoryFlag Flag() const override { return TrajectoryFlag::Parabola; } virtual void OnUnlimbo(BulletClass* pBullet, CoordStruct* pCoord, BulletVelocity* pVelocity) override; virtual bool OnAI(BulletClass* pBullet) override; virtual void OnAIPreDetonate(BulletClass* pBullet) override; virtual void OnAIVelocity(BulletClass* pBullet, BulletVelocity* pSpeed, BulletVelocity* pPosition) override; virtual TrajectoryCheckReturnType OnAITargetCoordCheck(BulletClass* pBullet) override; virtual TrajectoryCheckReturnType OnAITechnoCheck(BulletClass* pBullet, TechnoClass* pTechno) override; const ParabolaTrajectoryType* Type; int ThrowHeight; int BounceTimes; CoordStruct OffsetCoord; bool UseDisperseBurst; bool ShouldDetonate; bool ShouldBounce; bool NeedExtraCheck; CoordStruct LastTargetCoord; int CurrentBurst; int CountOfBurst; int WaitOneFrame; BulletVelocity LastVelocity; private: template <typename T> void Serialize(T& Stm); void PrepareForOpenFire(BulletClass* pBullet); bool BulletPrepareCheck(BulletClass* pBullet); void CalculateBulletVelocityRightNow(BulletClass* pBullet, CoordStruct* pSourceCoords, double gravity); void CalculateBulletVelocityLeadTime(BulletClass* pBullet, CoordStruct* pSourceCoords, double gravity); void CheckIfNeedExtraCheck(BulletClass* pBullet); double SearchVelocity(double horizontalDistance, int distanceCoordsZ, double radian, double gravity); double CheckVelocityEquation(double horizontalDistance, int distanceCoordsZ, double velocity, double radian, double gravity); double SolveFixedSpeedMeetTime(CoordStruct* pSourceCrd, CoordStruct* pTargetCrd, CoordStruct* pOffsetCrd, double horizontalSpeed); double SearchFixedHeightMeetTime(CoordStruct* pSourceCrd, CoordStruct* pTargetCrd, CoordStruct* pOffsetCrd, double gravity); double CheckFixedHeightEquation(CoordStruct* pSourceCrd, CoordStruct* pTargetCrd, CoordStruct* pOffsetCrd, double meetTime, double gravity); double SearchFixedAngleMeetTime(CoordStruct* pSourceCrd, CoordStruct* pTargetCrd, CoordStruct* pOffsetCrd, double radian, double gravity); double CheckFixedAngleEquation(CoordStruct* pSourceCrd, CoordStruct* pTargetCrd, CoordStruct* pOffsetCrd, double meetTime, double radian, double gravity); bool CalculateBulletVelocityAfterBounce(BulletClass* pBullet, CellClass* pCell); BulletVelocity GetGroundNormalVector(BulletClass* pBullet, CellClass* pCell); bool CheckBulletHitCliff(short X, short Y, int bulletHeight, int lastCellHeight); bool BulletDetonatePreCheck(BulletClass* pBullet); bool BulletDetonateLastCheck(BulletClass* pBullet, CellClass* pCell, double gravity, bool bounce); void BulletDetonateEffectuate(BulletClass* pBullet, double velocityMult); };
0
0.803614
1
0.803614
game-dev
MEDIA
0.936813
game-dev
0.682812
1
0.682812
acidburn974/CorthezzWoWBot
31,878
BotTemplate/Helper/Ingame.cs
using System; using BotTemplate.Interact; using System.Windows.Forms; using BotTemplate.Constants; using BotTemplate.Engines; using System.Collections.Generic; using System.Text; using System.Threading; using BotTemplate.Helper.SpellSystem; namespace BotTemplate.Helper { internal static class Ingame { #region BG functions internal static bool IsInQ() { string LuaStatement = "test12 = GetBattlefieldTimeWaited(1)"; return (Calls.GetText(LuaStatement, "test12", 10) != "0"); } internal static bool IsBgEnd() { string LuaStatement = "test123 = GetBattlefieldWinner()"; return (Calls.GetText(LuaStatement, "test123", 10) == ""); } internal static bool CanJoinBg() { string LuaStatement = "test123 = GetBattlefieldPortExpiration(1)"; return (Calls.GetText(LuaStatement, "test123", 10) != "0"); } internal static string ZoneText() { string LuaStatement = "tesko1 = GetRealZoneText()"; return Calls.GetText(LuaStatement, "tesko1", 30); } internal static void SignUp() { Calls.DoString("SelectGossipOption(1) JoinBattlefield(0)"); } internal static bool IsBgFrameOpen() { string LuaStatement = "function IsOpen() if BattlefieldFrame:IsVisible() then return 'true' else return 'false' end end " + "tesko1 = IsOpen();"; return (Calls.GetText(LuaStatement, "tesko1", 5).Trim() == "true"); } internal static void CloseBgFrame() { Calls.DoString("BattlefieldFrame:Hide()"); } internal static void AcceptPort() { Calls.DoString("AcceptBattlefieldPort(1, true)"); } internal static void LeaveBg() { Calls.DoString("LeaveBattlefield()"); } #endregion #region misc internal static void Follow(string name) { Calls.DoString("FollowByName('" + name + "');"); } internal static void BackToLogin() { Calls.DoString("if GlueDialog:IsVisible() then GlueDialog:Hide(); end if RealmList:IsVisible() then RealmListCancelButton:Click(); end CharacterSelect_Exit();"); } internal static bool IsDc() { try { if (ObjectManager.playerPtr == 0) { string LuaStatement = "test123 = 0 if AccountLogin ~= nil or CharacterSelect ~= nil then test123 = 1 end"; return (Calls.GetText(LuaStatement, "test123", 10) != "0"); } return false; } catch { return false; } } internal static int GetLatency() { string LuaStatement = "_,_,drei = GetNetStats()"; return Int32.Parse(Calls.GetText(LuaStatement, "drei", 2)); } #endregion #region enchants internal static bool IsMainHandEnchantApplied { get { string LuaStatement = "mainhand1 = GetWeaponEnchantInfo()"; return (Calls.GetText(LuaStatement, "mainhand1", 5) == "1"); } } internal static bool IsOffHandEnchantApplied { get { string LuaStatement = "_, _, _, offhand1 = GetWeaponEnchantInfo()"; return (Calls.GetText(LuaStatement, "offhand1", 5) == "1"); } } internal static void EnchantMainHand(string name) { if (!Ingame.IsMainHandEnchantApplied) { Ingame.UseItem(name); Calls.DoString("PickupInventoryItem(16)"); } } internal static void EnchantOffHand(string name) { if (!Ingame.IsOffHandEnchantApplied) { Ingame.UseItem(name); Calls.DoString("PickupInventoryItem(17)"); } } #endregion #region Item Management private static void SkipGossip() { string Statement = "arg = { GetGossipOptions() }; count = 1; typ = 2; while true do if arg[typ] ~= nil then if arg[typ] == 'vendor' then SelectGossipOption(count); break; else count = count + 1; typ = typ + 2; end else break end end"; Calls.DoString(Statement); } internal static bool IsVendorFrameOpen() { string LuaStatement = "troll1 = IsVendorOpen();"; return (Calls.GetText(LuaStatement, "troll1", 10).Trim() == "true"); } internal static bool PopupVisible() { string LuaStatement = "troll1 = 'false' if StaticPopup1:IsVisible() then troll1 = 'true'; else troll1 = 'false' end"; return (Calls.GetText(LuaStatement, "troll1", 10).Trim() == "true"); } internal static void SellAll() { Calls.DoString("for bag = 0,4,1 do for slot = 1, GetContainerNumSlots(bag), 1 do local name = GetContainerItemLink(bag,slot); if name then UseContainerItem(bag,slot) end end end"); } internal static void SellAllButGlobal() { string part1 = "if MerchantRepairAllButton:IsVisible() then MerchantRepairAllButton:Click() end " + "for bag = 0,4,1 do " + "for slot = 1, GetContainerNumSlots(bag), 1 do " + "link = GetContainerItemLink(bag,slot) " + "if link then " + "name = gsub(link,'^.*%[(.*)%].*$','%1') " + "if '1' == '1' "; string part2 = ""; part2 += " and string.find(name, 'Dragon Finger') == nil"; part2 += " and string.find(name, 'Glowstar') == nil"; string part3 = " then " + "UseContainerItem(bag,slot) " + "end " + "end " + "end " + "end "; string execute = part1 + part2 + part3; Calls.DoString(execute); } internal static void SellAllBut(string[] items) { string part1 = "if MerchantRepairAllButton:IsVisible() then MerchantRepairAllButton:Click() end " + "for bag = 0,4,1 do " + "for slot = 1, GetContainerNumSlots(bag), 1 do " + "link = GetContainerItemLink(bag,slot) " + "if link then " + "name = gsub(link,'^.*%[(.*)%].*$','%1') " + "if '1' == '1' "; if (Data.keepGreen) { part1 = part1 + "and string.find(link, '1eff00') == nil "; } if (Data.keepBlue) { part1 = part1 + "and string.find(link, '0070dd') == nil "; } if (Data.keepPurple) { part1 = part1 + "and string.find(link, 'a335ee') == nil "; } string part2 = ""; foreach (string x in items) { part2 += " and string.find(name, '" + x.Trim() + "') == nil"; } part2 += " and string.find(name, 'Dragon Finger') == nil"; part2 += " and string.find(name, 'Glowstar') == nil"; string part3 = " then " + "UseContainerItem(bag,slot) " + "end " + "end " + "end " + "end "; string execute = part1 + part2 + part3; Calls.DoString(execute); } private static int QueryBag(int bagnumber, string item) { int totalSlots = 0; switch (bagnumber) { case 0: totalSlots = 16; break; case 1: totalSlots = ObjectManager.Bag1.TotalSlots; break; case 2: totalSlots = ObjectManager.Bag2.TotalSlots; break; case 3: totalSlots = ObjectManager.Bag3.TotalSlots; break; case 4: totalSlots = ObjectManager.Bag4.TotalSlots; break; default: totalSlots = 0; break; } string LuaStatement = "itemcount1 = getItemsInBag(" + totalSlots + "," + bagnumber + ",'" + item + "');"; int tmpInt; Int32.TryParse(Calls.GetText(LuaStatement, "itemcount1", 10), out tmpInt); return tmpInt; } private static bool UseQueryBag(int bagnumber, string item) { int totalSlots = 0; switch (bagnumber) { case 0: totalSlots = 16; break; case 1: totalSlots = ObjectManager.Bag1.TotalSlots; break; case 2: totalSlots = ObjectManager.Bag2.TotalSlots; break; case 3: totalSlots = ObjectManager.Bag3.TotalSlots; break; case 4: totalSlots = ObjectManager.Bag4.TotalSlots; break; default: totalSlots = 0; break; } string LuaStatement = "tryhard = useItemInBag(" + totalSlots + "," + bagnumber + ",'" + item + "');"; return (Calls.GetText(LuaStatement, "tryhard", 5) == "1"); } internal static void UseDrink() { if (!IsDrinking()) UseItem(Data.drinkName); } internal static void UseFood() { if (!IsEating()) UseItem(Data.foodName); } internal static void UseItem(string name) { for (int i = 0; i <= ObjectManager.TotalBags; i = i + 1) { bool con = UseQueryBag(i, name); if (con == true) { break; } } } internal static int ItemCount(string name) { int itemCount = 0; for (int i = 0; i <= ObjectManager.TotalBags; i = i + 1) { itemCount = itemCount + QueryBag(i, name); } return itemCount; } #endregion #region tele private static readonly object tele_Lock = new object(); internal static void TeleOverTarget() { lock (tele_Lock) { float x = ObjectManager.TargetObject.Pos.x; float y = ObjectManager.TargetObject.Pos.y; float z = ObjectManager.TargetObject.Pos.z + 100; if (x != 0 && y != 0 && z != 0) { Tele(new Objects.Location(x, y, z), 60, false); } } } internal static void KillPlayer() { lock (tele_Lock) { Ingame.Tele(new Objects.Location(ObjectManager.PlayerObject.Pos.x, ObjectManager.PlayerObject.Pos.y, -10000f), 60, false); } } internal static void hotKeyTele(Objects.Location TargetPos, float parSeconds) { lock (tele_Lock) { if (parSeconds > 0.25f) parSeconds = 0.25f; Calls.StepTelePreview(TargetPos.x, TargetPos.y, TargetPos.z, parSeconds); } } internal static void setCoords(Objects.Location TargetPos) { uint ptr = ObjectManager.playerPtr + 0x9B8; BmWrapper.memory.WriteFloat(ptr, TargetPos.x); BmWrapper.memory.WriteFloat(ptr + 4, TargetPos.y); BmWrapper.memory.WriteFloat(ptr + 8, TargetPos.z); } internal static void TeleHb(Objects.Location TargetPos, float seconds, bool Preview) { lock (tele_Lock) { if (seconds > 0.25f) seconds = 0.25f; uint ptr = ObjectManager.playerPtr; if (ptr != 0) { float diff = ObjectManager.PlayerObject.Pos.differenceTo(TargetPos); bool success = true; if (diff > 2) { // 7 meter alle 1000 ms float startX = ObjectManager.PlayerObject.Pos.x; float startY = ObjectManager.PlayerObject.Pos.y; float steps = (float)diff / (7f * seconds); float stepRangeX = (TargetPos.x - startX) / steps; float StepRangeY = (TargetPos.y - startY) / steps; Calls.SetTeleStart(startX, startY, ObjectManager.PlayerObject.Pos.z); Calls.StopRunning(); Calls.SetMovementFlags(0); Thread.CurrentThread.Join(50); for (int i = 0; i < steps - 1; i++) { startX = startX + stepRangeX; startY = startY + StepRangeY; if (Preview) { success = Calls.StepTelePreview(startX, startY, 10000, seconds); } else { success = Calls.StepTele(startX, startY, 10000, seconds, 0); } if (!success) { break; } } } if (success) { if (Preview) { success = Calls.StepTelePreview(TargetPos.x, TargetPos.y, TargetPos.z, seconds); } else { success = Calls.StepTele(TargetPos.x, TargetPos.y, TargetPos.z, seconds, 1); } } } } } internal static void Tele(Objects.Location TargetPos, float seconds, bool Preview) { lock (tele_Lock) { //uint xAddr = ObjectManager.playerPtr + 0x9B8; //uint yAddr = ObjectManager.playerPtr + 0x9B8 + 0x4; //uint zAddr = ObjectManager.playerPtr + 0x9B8 + 0x8; //BmWrapper.memory.WriteFloat(xAddr, TargetPos.x); //BmWrapper.memory.WriteFloat(yAddr, TargetPos.y); //BmWrapper.memory.WriteFloat(zAddr, TargetPos.z); if (seconds > 0.35f) seconds = 0.35f; uint ptr = ObjectManager.playerPtr; if (ptr != 0) { float diff = ObjectManager.PlayerObject.Pos.differenceTo(TargetPos); bool success = true; if (diff > 2) { // 7 meter alle 1000 ms float startX = ObjectManager.PlayerObject.Pos.x; float startY = ObjectManager.PlayerObject.Pos.y; float steps = (float)diff / (7f * seconds); float stepRangeX = (TargetPos.x - startX) / steps; float StepRangeY = (TargetPos.y - startY) / steps; Calls.SetTeleStart(startX, startY, ObjectManager.PlayerObject.Pos.z); Calls.StopRunning(); Calls.SetMovementFlags(0); Thread.CurrentThread.Join(50); for (int i = 0; i < steps - 1; i++) { startX = startX + stepRangeX; startY = startY + StepRangeY; if (Preview) { success = Calls.StepTelePreview(startX, startY, 10000, seconds); } else { success = Calls.StepTele(startX, startY, 10000, seconds, 0); } if (!success) { break; } } } if (success) { if (Preview) { success = Calls.StepTelePreview(TargetPos.x, TargetPos.y, TargetPos.z, seconds); } else { success = Calls.StepTele(TargetPos.x, TargetPos.y, TargetPos.z, seconds, 1); } } } } } internal static void TeleNoZFake(Objects.Location TargetPos, float seconds, bool Preview) { lock (tele_Lock) { if (seconds > 0.25f) seconds = 0.25f; uint ptr = ObjectManager.playerPtr; if (ptr != 0) { float diff = ObjectManager.PlayerObject.Pos.differenceTo(TargetPos); bool success = true; if (diff > 2) { // 7 meter alle 1000 ms float startX = ObjectManager.PlayerObject.Pos.x; float startY = ObjectManager.PlayerObject.Pos.y; float z = ObjectManager.PlayerObject.Pos.z; float steps = (float)diff / (7f * seconds); float stepRangeX = (TargetPos.x - startX) / steps; float StepRangeY = (TargetPos.y - startY) / steps; Calls.SetTeleStart(startX, startY, ObjectManager.PlayerObject.Pos.z); Calls.StopRunning(); Calls.SetMovementFlags(0); Thread.CurrentThread.Join(50); for (int i = 0; i < steps - 1; i++) { startX = startX + stepRangeX; startY = startY + StepRangeY; if (Preview) { success = Calls.StepTelePreview(startX, startY, z, seconds); } else { success = Calls.StepTele(startX, startY, 10000, z, 0); } if (!success) { break; } } } if (success) { if (Preview) { success = Calls.StepTelePreview(TargetPos.x, TargetPos.y, TargetPos.z, seconds); } else { success = Calls.StepTele(TargetPos.x, TargetPos.y, TargetPos.z, seconds, 1); } } } } } #endregion #region Movement internal static void moveForward() { if (!Calls.MovementContainsFlag((uint)Offsets.movementFlags.Forward)) { Calls.SetControlBit((uint)Offsets.controlBits.Back, 0); Calls.SetControlBit((uint)Offsets.controlBits.Front, 1); } } internal static void moveBackwards() { if (!Calls.MovementContainsFlag((uint)Offsets.movementFlags.Back)) { Calls.SetControlBit((uint)Offsets.controlBits.Front, 0); Calls.SetControlBit((uint)Offsets.controlBits.Back, 1); } } internal static void Jump() { Calls.DoString("Jump();"); } #endregion #region Spells internal static bool druidIsBear() { return GotBuff("Dire Bear Form") || GotBuff("Bear Form"); } internal static bool druidIsCat() { return GotBuff("Cat Form"); } private static StringBuilder writeToChain = new StringBuilder(castChain); private static string castChain = ""; private static StringBuilder writeToPetChain = new StringBuilder(petCastChain); private static string petCastChain = ""; internal static void Cast(string name, bool gotCastTime) { if (gotCastTime) { if (Calls.MovementIsOnly(0) || Calls.MovementIsOnly((uint)Offsets.movementFlags.Swimming)) { if (IsSpellReady(name)) { //Calls.DoString("CastSpellByName('" + name + "');"); writeToChain.Append("CastSpellByName('" + name + "');"); } } } else { if (IsSpellReady(name)) { //Calls.DoString("CastSpellByName('" + name + "');"); writeToChain.Append("CastSpellByName('" + name + "');"); } } } internal static void CastWait(string name, int ms, bool gotCastTime) { if (!SpellManager.SpellContains(name)) { if (gotCastTime) { if (Calls.MovementIsOnly(0) || Calls.MovementIsOnly((uint)Offsets.movementFlags.Swimming)) { if (IsSpellReady(name)) { Cast(name, gotCastTime); SpellManager.Add(new Spell(name, ms)); } } } else { if (IsSpellReady(name)) { Cast(name, gotCastTime); SpellManager.Add(new Spell(name, ms)); } } } } internal static void Stand() { Calls.DoString("DoEmote('stand')"); } internal static void SwitchToStance(string name) { Calls.DoString("CastShapeshiftForm(returnStanceIndex('" + name + "'));"); } internal static bool IsInStance(string name) { string LuaStatement = "_, _, active, _ = GetShapeshiftFormInfo(returnStanceIndex('" + name + "'))"; return (Calls.GetText(LuaStatement, "active", 1) == "1"); } internal static string getSpellId(string name) { string LuaStatement = "finalresult = getSpellId('" + name + "');"; return Calls.GetText(LuaStatement, "finalresult", 6); } internal static void CastFinal() { if (!IsGCD()) { if (ObjectManager.PlayerObject.isChanneling == 0 && !ObjectManager.IsCasting) { if (writeToChain.Length != 0) { Calls.DoString(writeToChain.ToString()); } } } if (ObjectManager.playerClass == (uint)Offsets.classIds.Hunter || ObjectManager.playerClass == (uint)Offsets.classIds.Warlock) { if (!IsPetGCD()) { if (writeToPetChain.Length != 0) { Calls.DoString(writeToPetChain.ToString()); } } } writeToChain.Length = 0; writeToPetChain.Length = 0; } internal static bool IsGCD() { return CooldownManager.Contains("GCD"); } internal static bool IsPetGCD() { return PetCooldownManager.Contains("GCD"); } internal static bool GotBuff(string name) { if (!BuffManager.Contains(name)) { string LuaStatement = "finalresult = hasBuff('" + name + "');"; if (Calls.GetText(LuaStatement, "finalresult", 5).Trim() == "true") { BuffManager.Add(name); return true; } else { return false; } } return true; } internal static bool GotDebuff(string name, string unit) { string LuaStatement = "finalresult = hasDebuff('" + name + "','" + unit + "');"; return (Calls.GetText(LuaStatement, "finalresult", 5).Trim() == "true"); } internal static void PlaceAutoAttackAndShoot() { string LuaStatement = "abc12 = getSpellId('Shoot') " + "if abc12 ~= nil then " + "PickupSpell(abc12, 'BOOKTYPE_SPELL') PlaceAction(23) ClearCursor() end"; Calls.DoString(LuaStatement); } internal static void Shoot() { string LuaStatement = "shoot()"; Calls.DoString(LuaStatement); } internal static void StopShoot() { string LuaStatement = "stopShoot()"; Calls.DoString(LuaStatement); } internal static int GetComboPoints() { return Convert.ToInt32(Calls.GetText("points = GetComboPoints('target')", "points", 1)); } internal static void Attack() { if (!IsGCD()) { Calls.OnRightClickUnit(ObjectManager.TargetObject.baseAdd, 0); } } internal static bool IsTargetInCombat() { return (Calls.GetText("abc = UnitAffectingCombat('target')", "abc", 1) == "1"); } internal static bool IsSpellReady(string name) { name = name.Replace("()", ""); if (!CooldownManager.Contains("GCD") && !CooldownManager.Contains(name)) { string LuaStatement = "eins, zwei, drei = isSpellReady('" + name + "')"; string[] result = Calls.GetText(LuaStatement, new string[] { "eins", "zwei", "drei" }, 20); if (result[0].Trim() == "0") { return true; } else { if (result[0] != "" && result[1] != "") { double timeStamp = Convert.ToDouble(result[0].Replace(".", "")); double secCd = TimeSpan.FromSeconds(Convert.ToDouble(result[1].Replace(".", ","))).TotalMilliseconds; if (result[2] == "1") { if (secCd == 1500) { CooldownManager.Add("GCD", timeStamp + secCd); } CooldownManager.Add(name, timeStamp + secCd); } } } } return false; } internal static bool GotTextureAsBuff(string tex) { string LuaStatement = "finalresult = hasBuffWithTexture('" + tex + "', 'player');"; return (Calls.GetText(LuaStatement, "finalresult", 5).Trim() == "true"); } internal static bool GotTextureAsDebuff(string tex) { string LuaStatement = "finalresult = hasDebuffWithTexture('" + tex + "', 'player');"; return (Calls.GetText(LuaStatement, "finalresult", 5).Trim() == "true"); } internal static bool IsEating() { string eat = @"Interface\\Icons\\INV_Misc_Fork&Knife"; return GotTextureAsBuff(eat); } internal static bool IsPartyEatingOrDrinking() { try { return Convert.ToBoolean(Calls.GetText("maxo = isGroupResting()", "maxo", 5)); } catch { return false; } } internal static bool IsDrinking() { string drink = @"Interface\\Icons\\INV_Drink_07"; return GotTextureAsBuff(drink); } #endregion #region Pet stuff internal static void PetFollow() { Calls.DoString("PetFollow()"); } internal static bool PetGotTextureAsDebuff(string tex) { string LuaStatement = "finalresult = hasDebuffWithTexture('" + tex + "', 'pet');"; return (Calls.GetText(LuaStatement, "finalresult", 5).Trim() == "true"); } internal static bool PetGotTextureAsBuff(string tex) { string LuaStatement = "finalresult = hasBuffWithTexture('" + tex + "', 'pet');"; return (Calls.GetText(LuaStatement, "finalresult", 5).Trim() == "true"); } internal static void CastPetSpell(string name) { if (PetIsSpellReady(name)) { writeToPetChain.Append("castPetSpell('" + name + "');"); } } internal static void DismissPet() { Calls.DoString("PetDismiss()"); } internal static bool GotPet() { return (ObjectManager.PetObject.guid != 0); } internal static void PetAttack() { writeToChain.Append("PetAttack()"); } internal static bool PetIsSpellReady(string name) { name = name.Replace("()", ""); if (!PetCooldownManager.Contains("GCD") && !PetCooldownManager.Contains(name)) { string LuaStatement = "eins, zwei = gotPetSpellCd('" + name + "')"; string[] result = Calls.GetText(LuaStatement, new string[] { "eins", "zwei" }, 20); if (result[0].Trim() == "0") { return true; } else { if (result[0] != "" && result[1] != "") { double timeStamp = Convert.ToDouble(result[0].Replace(".", "")); double secCd = TimeSpan.FromSeconds(Convert.ToDouble(result[1].Replace(".", ","))).TotalMilliseconds; if (secCd == 1500) { PetCooldownManager.Add("GCD", timeStamp + secCd); } PetCooldownManager.Add(name, timeStamp + secCd); } } } return false; } #endregion } }
0
0.904768
1
0.904768
game-dev
MEDIA
0.8912
game-dev
0.954509
1
0.954509
CloudburstMC/Cloudburst
3,841
server/src/main/java/org/cloudburstmc/server/blockentity/LecternBlockEntity.java
package org.cloudburstmc.server.blockentity; import org.checkerframework.checker.nullness.qual.Nullable; import org.cloudburstmc.api.block.BlockTypes; import org.cloudburstmc.api.blockentity.BlockEntityType; import org.cloudburstmc.api.blockentity.Lectern; import org.cloudburstmc.api.item.ItemKeys; import org.cloudburstmc.api.item.ItemStack; import org.cloudburstmc.api.item.ItemTypes; import org.cloudburstmc.api.level.chunk.Chunk; import org.cloudburstmc.math.GenericMath; import org.cloudburstmc.math.vector.Vector3i; import org.cloudburstmc.nbt.NbtMap; import org.cloudburstmc.nbt.NbtMapBuilder; import org.cloudburstmc.server.item.ItemUtils; import javax.annotation.Nonnegative; public class LecternBlockEntity extends BaseBlockEntity implements Lectern { private static final String TAG_HAS_BOOK = "hasBook"; private static final String TAG_BOOK = "book"; private static final String TAG_PAGE = "page"; private static final String TAG_TOTAL_PAGES = "totalPages"; private ItemStack book; private int page; private int totalPages; public LecternBlockEntity(BlockEntityType<?> type, Chunk chunk, Vector3i position) { super(type, chunk, position); } @Override public boolean isValid() { return getBlockState().getType() == BlockTypes.LECTERN; } @Override protected void init() { updateTotalPages(false); } @Override public void loadAdditionalData(NbtMap tag) { super.loadAdditionalData(tag); if (tag.getBoolean(TAG_HAS_BOOK)) { this.book = ItemUtils.deserializeItem(tag.getCompound(TAG_BOOK)); this.page = tag.getInt(TAG_PAGE); this.totalPages = tag.getInt(TAG_TOTAL_PAGES); } } @Override public void saveAdditionalData(NbtMapBuilder tag) { super.saveAdditionalData(tag); if (this.book != null) { tag.putBoolean(TAG_HAS_BOOK, true); tag.putCompound(TAG_BOOK, ItemUtils.serializeItem(this.book)); tag.putInt(TAG_PAGE, this.page); tag.putInt(TAG_TOTAL_PAGES, this.totalPages); } } @Override public void onBreak() { if (this.book != null) { this.getLevel().dropItem(this.getPosition(), book); } } public boolean hasBook() { return this.book != null; } @Nullable public ItemStack getBook() { return book; } public void setBook(ItemStack item) { if (item != null && (item.getType() == ItemTypes.WRITTEN_BOOK || item.getType() == ItemTypes.WRITABLE_BOOK)) { this.book = item; } else { this.book = null; } updateTotalPages(true); } public int getLeftPage() { return (getPage() * 2) + 1; } public void setLeftPage(int newLeftPage) { setPage((newLeftPage - 1) / 2); } public int getRightPage() { return getLeftPage() + 1; } public void setRightPage(int newRightPage) { setLeftPage(newRightPage - 1); } @Override public int getPage() { return this.page; } @Override public void setPage(@Nonnegative int page) { this.page = GenericMath.clamp(page, 0, this.totalPages); this.getLevel().updateAround(this.getPosition()); } @Override public int getTotalPages() { return totalPages; } private void updateTotalPages(boolean updateRedstone) { if (hasBook()) { this.totalPages = this.book.get(ItemKeys.BOOK_DATA).getPages().size(); } else { this.totalPages = 0; } if (updateRedstone) { this.getLevel().updateAroundRedstone(this.getPosition(), null); } } @Override public boolean isSpawnable() { return true; } }
0
0.83995
1
0.83995
game-dev
MEDIA
0.625215
game-dev
0.819249
1
0.819249
CardboardPowered/cardboard
25,870
src/main/java/org/cardboardpowered/mixin/MixinPlayerManager.java
/** * CardboardPowered - Bukkit/Spigot for Fabric * Copyright (C) CardboardPowered.org and contributors * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.cardboardpowered.mixin; //<<<<<<< HEAD import com.google.common.collect.Lists; import org.bukkit.craftbukkit.event.CraftEventFactory; import org.cardboardpowered.interfaces.IMixinPlayNetworkHandler; import org.cardboardpowered.interfaces.IMixinPlayerManager; import org.cardboardpowered.interfaces.IMixinServerEntityPlayer; import org.cardboardpowered.interfaces.IMixinServerLoginNetworkHandler; import org.cardboardpowered.interfaces.IMixinWorld; import com.mojang.authlib.GameProfile; import me.isaiah.common.ICommonMod; import me.isaiah.common.cmixin.IMixinMinecraftServer; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.network.ClientConnection; import net.minecraft.network.encryption.PlayerPublicKey; import net.minecraft.network.packet.c2s.common.SyncedClientOptions; import net.minecraft.registry.tag.BlockTags; import net.minecraft.scoreboard.ServerScoreboard; import net.minecraft.server.BannedIpEntry; import net.minecraft.server.PlayerManager; import net.minecraft.server.network.ConnectedClientData; import net.minecraft.server.network.ServerLoginNetworkHandler; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity.RespawnPos; import net.minecraft.server.world.ServerWorld; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; import net.minecraft.world.World; //======= import java.net.SocketAddress; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import org.bukkit.Bukkit; //>>>>>>> upstream/ver/1.20 import org.bukkit.Location; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.craftbukkit.util.CraftLocation; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerRespawnEvent.RespawnFlag; import org.cardboardpowered.impl.entity.CraftPlayer; import org.cardboardpowered.impl.world.CraftWorld; import org.jetbrains.annotations.NotNull; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.function.Function; import net.minecraft.entity.Entity; import net.minecraft.entity.Entity.RemovalReason; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.server.MinecraftServer; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.world.WorldProperties; import net.minecraft.network.packet.s2c.play.*; //>>>>>>> upstream/ver/1.20 @Mixin(PlayerManager.class) public abstract class MixinPlayerManager implements IMixinPlayerManager { @Shadow public List<ServerPlayerEntity> players; @Shadow private MinecraftServer server; @Shadow public void sendCommandTree(ServerPlayerEntity player) {} @Shadow public void sendWorldInfo(ServerPlayerEntity player, ServerWorld world) {} @Shadow public void savePlayerData(ServerPlayerEntity player) {} @Shadow public void sendPlayerStatus(ServerPlayerEntity player) {} @Shadow public Map<UUID, ServerPlayerEntity> playerMap; @Override public ServerPlayerEntity moveToWorld(ServerPlayerEntity player, ServerWorld worldserver, boolean flag, Location location, boolean avoidSuffocation) { boolean flag2 = false; BlockPos blockposition = player.getSpawnPointPosition(); float f = player.getSpawnAngle(); boolean flag1 = player.isSpawnForced(); if (location == null) { boolean isBedSpawn = false; ServerWorld worldserver1 = CraftServer.server.getWorld(player.getSpawnPointDimension()); if (worldserver1 != null) { Optional<?> optional; if (blockposition != null) optional = ServerPlayerEntity.findRespawnPosition(worldserver1, blockposition, f, flag1, flag).map(RespawnPos::pos); else optional = Optional.empty(); if (optional.isPresent()) { BlockState iblockdata = worldserver1.getBlockState(blockposition); boolean flag3 = iblockdata.isOf(Blocks.RESPAWN_ANCHOR); Vec3d vec3d = (Vec3d) optional.get(); float f1; if (!iblockdata.isIn(BlockTags.BEDS) && !flag3) { f1 = f; } else { Vec3d vec3d1 = Vec3d.ofBottomCenter((Vec3i) blockposition).subtract(vec3d).normalize(); f1 = (float) MathHelper.wrapDegrees(MathHelper.atan2(vec3d1.z, vec3d1.x) * 57.2957763671875D - 90.0D); } player.refreshPositionAndAngles(vec3d.x, vec3d.y, vec3d.z, f1, 0.0F); player.setSpawnPoint(worldserver1.getRegistryKey(), blockposition, f, flag1, false); flag2 = !flag && flag3; isBedSpawn = true; location = new Location(((IMixinWorld)worldserver1).getCraftWorld(), vec3d.x, vec3d.y, vec3d.z); } else if (blockposition != null) player.networkHandler.sendPacket(new GameStateChangeS2CPacket(GameStateChangeS2CPacket.NO_RESPAWN_BLOCK, 0.0F)); } if (location == null) { worldserver1 = CraftServer.server.getWorld(World.OVERWORLD); blockposition = player.getSpawnPointPosition(); location = new Location(((IMixinWorld)worldserver1).getCraftWorld(), (double) ((float) blockposition.getX() + 0.5F), (double) ((float) blockposition.getY() + 0.1F), (double) ((float) blockposition.getZ() + 0.5F)); } Player respawnPlayer = CraftServer.INSTANCE.getPlayer(player); PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(respawnPlayer, location, isBedSpawn && !flag2, flag2); CraftServer.INSTANCE.getPluginManager().callEvent(respawnEvent); if (player.isDisconnected()) return player; location = respawnEvent.getRespawnLocation(); } else location.setWorld(((IMixinWorld)worldserver).getCraftWorld()); ServerWorld worldserver1 = ((CraftWorld) location.getWorld()).getHandle(); World fromWorld = player.getWorld(); // TODO: 1.21.4: Check this player.teleport(worldserver1, location.getX(), location.getY(), location.getZ(), null, 0, 0, false); if (fromWorld != ((CraftWorld) location.getWorld()).getHandle()) { PlayerChangedWorldEvent event = new PlayerChangedWorldEvent((Player) ((IMixinServerEntityPlayer)player).getBukkitEntity(), ((IMixinWorld)fromWorld).getCraftWorld()); CraftServer.INSTANCE.getPluginManager().callEvent(event); } return player; } @Unique private CraftPlayer plr; @Inject(method = "onPlayerConnect", at = @At("HEAD")) public void onConnect(ClientConnection connection, ServerPlayerEntity player, ConnectedClientData clientData, CallbackInfo ci) { this.plr = (CraftPlayer) CraftServer.INSTANCE.getPlayer(player); } @Redirect(method = "onPlayerConnect", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/PlayerManager;broadcast(Lnet/minecraft/text/Text;Z)V")) public void firePlayerJoinEvent(PlayerManager instance, Text message, boolean overlay) { CraftPlayer plr; if(this.plr == null) { instance.broadcast(message, overlay); return; } else { plr = this.plr; this.plr = null; } String key = "multiplayer.player.joined"; Text name = plr.nms.getDisplayName(); String joinMessage = Formatting.YELLOW + Text.translatable(key, name).getString(); PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(plr, joinMessage); CraftEventFactory.callEvent(playerJoinEvent); IMixinPlayNetworkHandler ims = (IMixinPlayNetworkHandler)plr.nms.networkHandler; if (!ims.cb_get_connection().isOpen()) { return; } joinMessage = playerJoinEvent.getJoinMessage(); if (joinMessage != null && !joinMessage.isEmpty()) { for (Text line : CraftChatMessage.fromString(joinMessage)) { broadcast(line, entityplayer -> line, false); } } } @Inject(at = @At("HEAD"), method = "remove") public void firePlayerQuitEvent(ServerPlayerEntity player, CallbackInfo ci) { player.closeHandledScreen(); PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(CraftServer.INSTANCE.getPlayer(player), "\u00A7e" + player.getDisplayName().getString() + " left the game"); CraftServer.INSTANCE.getPluginManager().callEvent(playerQuitEvent); player.playerTick(); } @Override public ServerPlayerEntity attemptLogin(ServerLoginNetworkHandler nethand, GameProfile profile, PlayerPublicKey key, String hostname) { MutableText chatmessage; // Moved from processLogin // 1.18: UUID uuid = PlayerEntity.getUuidFromProfile(profile); UUID uuid = ICommonMod.getIServer().get_uuid_from_profile(profile); // UUID uuid = DynamicSerializableUuid.getUuidFromProfile(profile); List<ServerPlayerEntity> list = Lists.newArrayList(); ServerPlayerEntity entityplayer; for (int i = 0; i < this.players.size(); ++i) { entityplayer = (ServerPlayerEntity) this.players.get(i); if (entityplayer.getUuid().equals(uuid)) list.add(entityplayer); } Iterator<ServerPlayerEntity> iterator = list.iterator(); while (iterator.hasNext()) { entityplayer = (ServerPlayerEntity) iterator.next(); savePlayerData(entityplayer); // Force the player's inventory to be saved entityplayer.networkHandler.disconnect(Text.of("multiplayer.disconnect.duplicate_login")); } IMixinServerLoginNetworkHandler ims = (IMixinServerLoginNetworkHandler)nethand; SocketAddress address = ims.cb_get_connection().getAddress(); me.isaiah.common.cmixin.IMixinPlayerManager imixin = (me.isaiah.common.cmixin.IMixinPlayerManager) (Object)this; // ServerPlayerEntity entity = imixin.InewPlayer(CraftServer.server, CraftServer.server.getWorld(World.OVERWORLD), profile); ServerPlayerEntity entity = new ServerPlayerEntity(CraftServer.server, CraftServer.server.getWorld(World.OVERWORLD), profile, SyncedClientOptions.createDefault()); Player player = (Player) ((IMixinServerEntityPlayer)entity).getBukkitEntity(); PlayerLoginEvent event = new PlayerLoginEvent(player, hostname, ((java.net.InetSocketAddress) address).getAddress(), ((java.net.InetSocketAddress) ims.cb_get_connection().channel.remoteAddress()).getAddress()); if (((PlayerManager)(Object)this).getUserBanList().contains(profile) /*&& !((PlayerManager)(Object)this).getUserBanList().get(gameprofile).isInvalid()*/) { chatmessage = Text.translatable("multiplayer.disconnect.banned.reason", new Object[]{"TODO REASON!"}); //chatmessage.append(new TranslatableTextContent("multiplayer.disconnect.banned.expiration", new Object[] {"TODO EXPIRE!"})); event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); } else if (!((PlayerManager)(Object)this).isWhitelisted(profile)) { chatmessage = Text.translatable("multiplayer.disconnect.not_whitelisted"); event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, "Server whitelisted!"); } else if (((PlayerManager)(Object)this).getIpBanList().isBanned(address) /*&& !((PlayerManager)(Object)this).getIpBanList().get(socketaddress).isInvalid()*/) { BannedIpEntry ipbanentry = ((PlayerManager)(Object)this).getIpBanList().get(address); chatmessage = Text.translatable("multiplayer.disconnect.banned_ip.reason", new Object[]{ipbanentry.getReason()}); //if (ipbanentry.getExpiryDate() != null) // chatmessage.append(new TranslatableTextContent("multiplayer.disconnect.banned_ip.expiration", new Object[]{ipbanentry.getExpiryDate()})); event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); } else { if (this.players.size() >= ((PlayerManager)(Object)this).getMaxPlayerCount() && !((PlayerManager)(Object)this).canBypassPlayerLimit(profile)) event.disallow(PlayerLoginEvent.Result.KICK_FULL, "Server is full"); } CraftEventFactory.callEvent(event); if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) { nethand.disconnect(Text.of(event.getKickMessage())); return null; } return entity; } @Shadow public void sendScoreboard(ServerScoreboard scoreboardserver, ServerPlayerEntity entityplayer) { } @Shadow public abstract void broadcast(Text message, Function<ServerPlayerEntity, Text> playerMessageFactory, boolean overlay); @Override public void sendScoreboardBF(ServerScoreboard newboard, ServerPlayerEntity handle) { sendScoreboard(newboard, handle); } /*@Redirect(at = @At(value = "INVOKE", target = "class=net/minecraft/server/network/ServerPlayerEntity;"), method = "acceptPlayer") public ServerPlayerEntity acceptPlayer_createPlayer(PlayerManager man, GameProfile a, PlayerPublicKey key) { return cardboard_player; }*/ /** * @author wdog5 * @reason bukkit */ @Overwrite public ServerPlayerEntity respawnPlayer(ServerPlayerEntity playerIn, boolean conqueredEnd, RemovalReason removalReason) { playerIn.stopRiding(); // CraftBukkit this.players.remove(playerIn); playerIn.getServerWorld().removePlayer(playerIn, Entity.RemovalReason.DISCARDED); BlockPos blockposition = playerIn.getSpawnPointPosition(); float f = playerIn.getSpawnAngle(); boolean flag1 = playerIn.isSpawnForced(); // CraftBukkit start // Banner start - remain original field to compat with carpet ServerWorld worldserver_vanilla = this.server.getWorld(playerIn.getSpawnPointDimension()); Optional<Vec3d> optional_vanilla; if (worldserver_vanilla != null && blockposition != null) { optional_vanilla = ServerPlayerEntity.findRespawnPosition(worldserver_vanilla, blockposition, f, flag1, conqueredEnd).map(RespawnPos::pos); } else { optional_vanilla = Optional.empty(); } ServerWorld worldserver_vanilla_1 = worldserver_vanilla != null && optional_vanilla.isPresent() ? worldserver_vanilla : this.server.getOverworld(); entityplayer_vanilla = new ServerPlayerEntity(this.server, worldserver_vanilla_1, playerIn.getGameProfile(), SyncedClientOptions.createDefault()); // Banner end ServerPlayerEntity entityplayer1 = playerIn; fromWorld = ((IMixinServerEntityPlayer)playerIn).getBukkitEntity().getWorld(); playerIn.notInAnyWorld = false; // CraftBukkit end if (null != playerIn.networkHandler) { //entityplayer1.networkHandler = playerIn.networkHandler; } ((IMixinServerEntityPlayer)entityplayer1).copyFrom_unused(playerIn, conqueredEnd); entityplayer1.setId(playerIn.getId()); entityplayer1.setMainArm(playerIn.getMainArm()); // for (String s : playerIn.getCommandTags()) { // entityplayer1.addCommandTag(s); // } boolean flag2 = false; // CraftBukkit start - fire PlayerRespawnEvent if (banner$loc == null) { boolean isBedSpawn = false; ServerWorld worldserver1 = this.server.getWorld(playerIn.getSpawnPointDimension()); if (worldserver1 != null) { if (optional_vanilla.isPresent()) { BlockState iblockdata = worldserver1.getBlockState(blockposition); boolean flag3 = iblockdata.isOf(Blocks.RESPAWN_ANCHOR); Vec3d vec3d = (Vec3d) optional_vanilla.get(); float f1; if (!iblockdata.isIn(BlockTags.BEDS) && !flag3) { f1 = f; } else { Vec3d vec3d1 = Vec3d.ofBottomCenter(blockposition).subtract(vec3d).normalize(); f1 = (float) MathHelper.wrapDegrees(MathHelper.atan2(vec3d1.z, vec3d1.x) * 57.2957763671875D - 90.0D); } // Banner end flag2 = !conqueredEnd && flag3; isBedSpawn = true; banner$loc = CraftLocation.toBukkit(vec3d, ((IMixinWorld)worldserver1).getCraftWorld(), f1, 0.0F); } else if (blockposition != null) { entityplayer1.networkHandler.sendPacket(new GameStateChangeS2CPacket(GameStateChangeS2CPacket.NO_RESPAWN_BLOCK, 0.0F)); // entityplayer1.pushChangeSpawnCause(PlayerSpawnChangeEvent.Cause.RESET); entityplayer1.setSpawnPoint(null, null, 0f, false, false); } } if (banner$loc == null) { worldserver1 = this.server.getWorld(World.OVERWORLD); // blockposition = entityplayer1.getSpawnPoint(worldserver1); blockposition = entityplayer1.getSpawnPointPosition(); if (null == blockposition) { blockposition = worldserver1.getSpawnPos(); } banner$loc = CraftLocation.toBukkit(blockposition, ((IMixinWorld)worldserver1).getCraftWorld()).add(0.5F, 0.1F, 0.5F); } Player respawnPlayer = (Player) ((IMixinServerEntityPlayer)entityplayer1).getBukkitEntity(); respawnEvent = new PlayerRespawnEvent(respawnPlayer, banner$loc, isBedSpawn && !flag2, flag2); CraftServer.INSTANCE.getPluginManager().callEvent(respawnEvent); // Spigot Start // if (playerIn.networkHandler.isDisconnected()) { if (playerIn.isDisconnected()) { System.out.println("PLAYER DISCONNECT"); return playerIn; } // Spigot End banner$loc = respawnEvent.getRespawnLocation(); if (!conqueredEnd) { // keep inventory here since inventory dropped at ServerPlayerEntity#onDeath ((IMixinServerEntityPlayer)playerIn).reset(); // SPIGOT-4785 } } else { if (banner$worldserver == null) banner$worldserver = this.server.getWorld(playerIn.getSpawnPointDimension()); banner$loc.setWorld(((IMixinWorld)banner$worldserver).getCraftWorld()); } worldserver1 = ((CraftWorld) banner$loc.getWorld()).getHandle(); entityplayer1.setPos(banner$loc.getX(), banner$loc.getY(), banner$loc.getZ()); entityplayer1.setRotation(banner$loc.getYaw(), banner$loc.getPitch()); //entityplayer1.forceSetPositionRotation(banner$loc.getX(), banner$loc.getY(), banner$loc.getZ(), banner$loc.getYaw(), banner$loc.getPitch()); // CraftBukkit end while (avoidSuffocation.getAndSet(true) && !worldserver1.isSpaceEmpty(entityplayer1) && entityplayer1.getY() < (double) worldserver1.getTopYInclusive()) { entityplayer1.setPosition(entityplayer1.getX(), entityplayer1.getY() + 1.0D, entityplayer1.getZ()); } // CraftBukkit start worlddata = worldserver1.getLevelProperties(); int sim = CraftServer.INSTANCE.getSimulationDistance(); int vd = CraftServer.INSTANCE.getViewDistance(); entityplayer1.networkHandler.sendPacket(new PlayerRespawnS2CPacket(entityplayer1.createCommonPlayerSpawnInfo(entityplayer1.getServerWorld()), (byte) (conqueredEnd ? 1 : 0))); //entityplayer1.networkHandler.sendPacket(new PlayerRespawnS2CPacket(worldserver1.getDimensionKey(), worldserver1.getRegistryKey(), // BiomeAccess.hashSeed(worldserver1.getSeed()), entityplayer1.interactionManager.getGameMode(), entityplayer1.interactionManager.getPreviousGameMode(), // worldserver1.isDebugWorld(), worldserver1.isFlat(), (byte) (conqueredEnd ? 1 : 0), entityplayer1.getLastDeathPos(), entityplayer1.getPortalCooldown())); entityplayer1.networkHandler.sendPacket(new ChunkLoadDistanceS2CPacket((vd))); entityplayer1.networkHandler.sendPacket(new SimulationDistanceS2CPacket(sim)); ((IMixinServerEntityPlayer)entityplayer1).spawnIn(worldserver1); entityplayer1.unsetRemoved(); ((IMixinPlayNetworkHandler)entityplayer1.networkHandler).teleport(CraftLocation.toBukkit(entityplayer1.getPos(), ((IMixinWorld)worldserver1).getCraftWorld(), entityplayer1.getYaw(), entityplayer1.getPitch())); entityplayer1.setSneaking(false); entityplayer1.networkHandler.sendPacket(new PlayerSpawnPositionS2CPacket(worldserver1.getSpawnPos(), worldserver1.getSpawnAngle())); entityplayer1.networkHandler.sendPacket(new DifficultyS2CPacket(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); entityplayer1.networkHandler.sendPacket(new ExperienceBarUpdateS2CPacket(entityplayer1.experienceProgress, entityplayer1.totalExperience, entityplayer1.experienceLevel)); this.sendWorldInfo(entityplayer1, worldserver1); this.sendCommandTree(entityplayer1); if (!playerIn.isDisconnected()) { worldserver1.onPlayerRespawned(entityplayer1); this.players.add(entityplayer1); this.playerMap.put(entityplayer1.getUuid(), entityplayer1); } // Banner start - add for carpet compat if (entityplayer_vanilla == null) { entityplayer1.onSpawn(); } // Banner end entityplayer1.setHealth(entityplayer1.getHealth()); if (flag2) { entityplayer1.networkHandler.sendPacket(new PlaySoundS2CPacket(SoundEvents.BLOCK_RESPAWN_ANCHOR_DEPLETE, SoundCategory.BLOCKS, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), 1.0F, 1.0F, worldserver1.getRandom().nextLong())); } // Added from changeDimension this.sendPlayerStatus(playerIn); // Update health, etc... playerIn.sendAbilitiesUpdate(); for (StatusEffectInstance mobEffect : playerIn.getStatusEffects()) { EntityStatusEffectS2CPacket pk = ((IMixinMinecraftServer)ICommonMod.getIServer().getMinecraft()).new_status_effect_packet(playerIn.getId(), mobEffect, false); playerIn.networkHandler.sendPacket(pk); } // Fire advancement trigger playerIn.worldChanged(((CraftWorld) fromWorld).getHandle()); // Don't fire on respawn if (fromWorld != banner$loc.getWorld()) { PlayerChangedWorldEvent event = new PlayerChangedWorldEvent( (@NotNull Player) ((IMixinServerEntityPlayer)playerIn).getBukkitEntity(), fromWorld); Bukkit.getPluginManager().callEvent(event); } // Save player file again if they were disconnected // if (playerIn.networkHandler.isDisconnected()) { if (playerIn.isDisconnected()) { this.savePlayerData(playerIn); } // CraftBukkit end banner$loc = null; banner$respawnReason = null; banner$worldserver = null; entityplayer1.setHealth(entityplayer1.getMaxHealth()); return entityplayer1; } private Location banner$loc = null; private transient RespawnFlag banner$respawnReason; public ServerWorld banner$worldserver = null; public AtomicBoolean avoidSuffocation = new AtomicBoolean(true); // Banner start - Fix mixin by apoli public org.bukkit.World fromWorld; public PlayerRespawnEvent respawnEvent; public ServerWorld worldserver1; public WorldProperties worlddata; public ServerPlayerEntity entityplayer_vanilla; // Banner end }
0
0.973403
1
0.973403
game-dev
MEDIA
0.973974
game-dev
0.958117
1
0.958117
DavidPeicho/ecstra
6,784
src/decorators.ts
import { ComponentData } from './component.js'; import { ArrayProp, BooleanProp, CopyableProp, CopyClonableOptions, CopyClonableType, NumberProp, Property, RefProp, StringProp } from './property.js'; import { QueryComponents } from './query.js'; import { DataComponentClass, Nullable, PropertyClass, SystemClass, SystemGroupClass } from './types.js'; /** Properties. */ /** * Assigns the given Fecs property to a decorated class property * * @param property - Fecs property object to assign to the decorated class * property * @return A generic property decorator * * @hidden */ function setupProperty(property: Property<unknown>) { return function (target: ComponentData, key: string) { const constructor = target.constructor as DataComponentClass; if (!constructor.Properties) { constructor.Properties = {}; } constructor.Properties[key] = property; }; } /** * Builds a Fecs property and assign it to a decorated class property. * * **Notes**: This function is just a healper to construct class with a generic * object * * @param {(PropertyClass | PropertyDecoratorOptions<T>)} options - Option * object to use to setup the property * @return A generic property decorator */ export function property<T>( options: PropertyClass | PropertyDecoratorOptions<T> ) { return function (_: ComponentData, key: string) { if (typeof options === 'function') { setupProperty(new (options as PropertyClass)()); } else { const Class = options.type; setupProperty(new Class(options)); } }; } /** * Decorator for a boolean component property * * ```ts * class MyComponent extends ComponentData { * boolean(true) * myBoolean!: boolean; * } * ``` * * @param defaultValue - Default value of the property, used when * the component is initialized * @return Decorator for a property storing a boolean value */ export function boolean(defaultValue?: boolean) { return setupProperty(BooleanProp(defaultValue)); } /** * Decorator for a numeric component property * * ## Examples * * ```ts * class MyComponent extends ComponentData { * number(100) * myNumber!: boolean; * } * ``` * * @param defaultValue - Default value of the property, used when * the component is initialized * @return Decorator for a property storing a number value */ export function number(defaultValue?: number) { return setupProperty(NumberProp(defaultValue)); } /** * Decorator for a string component property * * ```ts * class MyComponent extends ComponentData { * string('This is the default value!') * myString!: boolean; * } * ``` * * @param defaultValue - Default value of the property, used when * the component is initialized * @return Decorator for a property storing a string value */ export function string(defaultValue?: string) { return setupProperty(StringProp(defaultValue)); } /** * Decorator for an array component property * * ```ts * class MyComponent extends ComponentData { * array([ 'This', 'is', 'the', 'default', 'value']) * myArray!: string[]; * } * ``` * * @param defaultValue - Default value of the property, used when * the component is initialized * @return Decorator for a property storing an array value */ export function array<T>(defaultValue?: T[]) { return setupProperty(ArrayProp(defaultValue)); } /** * Decorator for a reference component property * * ```ts * class MyComponent extends ComponentData { * ref(null) * myRef!: Vector2 | null; * } * ``` * * @param defaultValue - Default value of the property, used when * the component is initialized * @return Decorator for a property storing a reference value */ export function ref<T>(defaultValue?: Nullable<T>) { return setupProperty(RefProp(defaultValue)); } /** * Decorator for a reference component property * * ## Examples * * ```ts * class Vector2() { * static Zero = new Vector2(0, 0); * constructor(x: number, y: number) { * this.x = x; * this.y = y; * } * copy(source: this): this { * this.x = source.x; * this.y = source.y; * return this; * } * clone(): Vector2 { * return new (this.constructor)().copy(this); * } * } * * class MyComponent extends ComponentData { * copyable({ type: Vector2, default: new Vector2(0, 0) }) * myCopyable!: Vector2; * } * ``` * * @param defaultValue - Default value of the property, used when * the component is initialized * @return Decorator for a property storing a 'copyable' value */ export function copyable<T extends CopyClonableType>( opts: CopyClonableOptions<T> ) { return setupProperty(CopyableProp(opts)); } export interface PropertyDecoratorOptions<T> { type: PropertyClass; default?: T; } /** Systems. */ /** * Decorator to specifiy system classes that should be executed **after** * a system * * ## Examples * * @before([ SystemThatRunsAfter, ... ]) * class MySystem extends System {} * * @param Classes - List of classes that should be executed * **after** * @return Decorator for a system class declaration */ export function before(Classes: SystemClass[]) { return function (constructor: SystemClass) { constructor.UpdateBefore = Classes; }; } /** * Decorator to specifiy system classes that should be executed **before** * a system * * ## Examples * * @after([ SystemThatRunsBefore, ... ]) * class MySystem extends System {} * * @param Classes - List of classes that should be executed * **before** * @return Decorator for a system class declaration */ export function after(Classes: SystemClass[]) { // @todo: merge with existing hierarchy. return function (constructor: SystemClass) { constructor.UpdateAfter = Classes; }; } /** * Decorator to specifiy the group a system should belong to * * ## Examples * * class MyGroup extends SystemGroup {} * * @group(MyGroup) * class MySystem extends System {} * * @param Class - Group class in which this system should be added * @return Decorator for a system class declaration */ export function group(Class: SystemGroupClass) { // @todo: merge with existing hierarchy. return function (constructor: SystemClass) { constructor.Group = Class; }; } /** * Decorator to specifiy the static queries of a system. * * * ## Examples * * class MyGroup extends SystemGroup {} * * @queries({ * queryA: [ ComponentX, ... ] * }) * class MySystem extends System {} * * @param Class - Group class in which this system should be added * @return Decorator for a system class declaration */ export function queries(QueriesDesc: { [key: string]: QueryComponents }) { return function (constructor: SystemClass) { constructor.Queries = QueriesDesc; }; }
0
0.924464
1
0.924464
game-dev
MEDIA
0.178905
game-dev
0.875141
1
0.875141
MotorolaMobilityLLC/system-core
4,726
libpixelflinger/codeflinger/tinyutils/smartpointer.h
/* * Copyright 2005 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ANDROID_PIXELFLINGER_SMART_POINTER_H #define ANDROID_PIXELFLINGER_SMART_POINTER_H #include <stdint.h> #include <sys/types.h> #include <stdlib.h> // --------------------------------------------------------------------------- namespace android { namespace tinyutils { // --------------------------------------------------------------------------- #define COMPARE(_op_) \ inline bool operator _op_ (const sp<T>& o) const { \ return m_ptr _op_ o.m_ptr; \ } \ inline bool operator _op_ (const T* o) const { \ return m_ptr _op_ o; \ } \ template<typename U> \ inline bool operator _op_ (const sp<U>& o) const { \ return m_ptr _op_ o.m_ptr; \ } \ template<typename U> \ inline bool operator _op_ (const U* o) const { \ return m_ptr _op_ o; \ } // --------------------------------------------------------------------------- template <typename T> class sp { public: inline sp() : m_ptr(0) { } sp(T* other); sp(const sp<T>& other); template<typename U> sp(U* other); template<typename U> sp(const sp<U>& other); ~sp(); // Assignment sp& operator = (T* other); sp& operator = (const sp<T>& other); template<typename U> sp& operator = (const sp<U>& other); template<typename U> sp& operator = (U* other); // Reset void clear(); // Accessors inline T& operator* () const { return *m_ptr; } inline T* operator-> () const { return m_ptr; } inline T* get() const { return m_ptr; } // Operators COMPARE(==) COMPARE(!=) COMPARE(>) COMPARE(<) COMPARE(<=) COMPARE(>=) private: template<typename Y> friend class sp; T* m_ptr; }; // --------------------------------------------------------------------------- // No user serviceable parts below here. template<typename T> sp<T>::sp(T* other) : m_ptr(other) { if (other) other->incStrong(this); } template<typename T> sp<T>::sp(const sp<T>& other) : m_ptr(other.m_ptr) { if (m_ptr) m_ptr->incStrong(this); } template<typename T> template<typename U> sp<T>::sp(U* other) : m_ptr(other) { if (other) other->incStrong(this); } template<typename T> template<typename U> sp<T>::sp(const sp<U>& other) : m_ptr(other.m_ptr) { if (m_ptr) m_ptr->incStrong(this); } template<typename T> sp<T>::~sp() { if (m_ptr) m_ptr->decStrong(this); } template<typename T> sp<T>& sp<T>::operator = (const sp<T>& other) { if (other.m_ptr) other.m_ptr->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other.m_ptr; return *this; } template<typename T> sp<T>& sp<T>::operator = (T* other) { if (other) other->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other; return *this; } template<typename T> template<typename U> sp<T>& sp<T>::operator = (const sp<U>& other) { if (other.m_ptr) other.m_ptr->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other.m_ptr; return *this; } template<typename T> template<typename U> sp<T>& sp<T>::operator = (U* other) { if (other) other->incStrong(this); if (m_ptr) m_ptr->decStrong(this); m_ptr = other; return *this; } template<typename T> void sp<T>::clear() { if (m_ptr) { m_ptr->decStrong(this); m_ptr = 0; } } // --------------------------------------------------------------------------- } // namespace tinyutils } // namespace android // --------------------------------------------------------------------------- #endif // ANDROID_PIXELFLINGER_SMART_POINTER_H
0
0.976919
1
0.976919
game-dev
MEDIA
0.101823
game-dev
0.975149
1
0.975149
mridgers/clink
2,875
clink/lib/src/matches_impl.h
// Copyright (c) Martin Ridgers // License: http://opensource.org/licenses/MIT #pragma once #include "matches.h" #include <vector> //------------------------------------------------------------------------------ struct MatchInfo { uint16 store_id; uint16 displayable_store_id; uint16 aux_store_id; uint8 cell_count; uint8 suffix : 7; // TODO: suffix can be in Store instead of info. uint8 select : 1; }; //------------------------------------------------------------------------------ class MatchStore { public: const char* get(uint32 id) const; protected: static const int32 alignment_bits = 1; static const int32 alignment = 1 << alignment_bits; char* _ptr; uint32 _size; }; //------------------------------------------------------------------------------ class MatchesImpl : public Matches { public: MatchesImpl(uint32 store_size=0x10000); virtual uint32 get_match_count() const override; virtual const char* get_match(uint32 index) const override; virtual const char* get_displayable(uint32 index) const override; virtual const char* get_aux(uint32 index) const override; virtual char get_suffix(uint32 index) const override; virtual uint32 get_cell_count(uint32 index) const override; virtual bool has_aux() const override; bool is_prefix_included() const; virtual void get_match_lcd(StrBase& out) const override; private: friend class MatchPipeline; friend class MatchBuilder; void set_prefix_included(bool included); bool add_match(const MatchDesc& desc); uint32 get_info_count() const; MatchInfo* get_infos(); const MatchStore& get_store() const; void reset(); void coalesce(uint32 count_hint); private: class StoreImpl : public MatchStore { public: StoreImpl(uint32 size); ~StoreImpl(); void reset(); int32 store_front(const char* str); int32 store_back(const char* str); private: uint32 get_size(const char* str) const; uint32 _front; uint32 _back; }; typedef std::vector<MatchInfo> Infos; StoreImpl _store; Infos _infos; uint16 _count = 0; bool _coalesced = false; bool _has_aux = false; bool _prefix_included = false; };
0
0.885502
1
0.885502
game-dev
MEDIA
0.236991
game-dev
0.647268
1
0.647268
thomhurst/ModularPipelines
1,189
src/ModularPipelines.Azure/Services/AzCosmosdbCassandraTableThroughput.cs
using System.Diagnostics.CodeAnalysis; using ModularPipelines.Attributes; using ModularPipelines.Azure.Options; using ModularPipelines.Context; using ModularPipelines.Models; namespace ModularPipelines.Azure.Services; [ExcludeFromCodeCoverage] [CommandPrecedingArguments("cosmosdb", "cassandra", "table")] public class AzCosmosdbCassandraTableThroughput { public AzCosmosdbCassandraTableThroughput( ICommand internalCommand ) { _command = internalCommand; } private readonly ICommand _command; public async Task<CommandResult> Migrate(AzCosmosdbCassandraTableThroughputMigrateOptions options, CancellationToken token = default) { return await _command.ExecuteCommandLineTool(options, token); } public async Task<CommandResult> Show(AzCosmosdbCassandraTableThroughputShowOptions options, CancellationToken token = default) { return await _command.ExecuteCommandLineTool(options, token); } public async Task<CommandResult> Update(AzCosmosdbCassandraTableThroughputUpdateOptions options, CancellationToken token = default) { return await _command.ExecuteCommandLineTool(options, token); } }
0
0.817693
1
0.817693
game-dev
MEDIA
0.258035
game-dev
0.515476
1
0.515476
RomkoSI/G3D
22,293
GLG3D.lib/source/GConsole.cpp
/** @file GConsole.cpp Copyright 2000-2015, Morgan McGuire. All rights reserved. */ #include "G3D/stringutils.h" #include "G3D/fileutils.h" #include "G3D/debugPrintf.h" #include "G3D/TextInput.h" #include "G3D/FileSystem.h" #include "GLG3D/GConsole.h" #include "GLG3D/RenderDevice.h" #include "GLG3D/Draw.h" #include "GLG3D/SlowMesh.h" namespace G3D { static weak_ptr<GConsole> lastGConsole; static void gconsolePrintHook(const String& s) { GConsoleRef last = lastGConsole.lock(); if (last) { last->print(s); } } GConsole::Settings::Settings() : blinkRate(3), keyRepeatRate(18), lineHeight(13), numVisibleLines(15), maxBufferLength(2000), keyRepeatDelay(0.25f), commandEcho(true), performFilenameCompletion(true), performCommandCompletion(true), maxCompletionHistorySize(3000), defaultCommandColor(Color3::white()), defaultPrintColor(0.8f, 1.0f, 0.8f), backgroundColor(0, 0, 0, 0.3f) { } GConsoleRef GConsole::create(const shared_ptr<GFont>& f, const Settings& s, Callback callback, void* data) { GConsoleRef c(new GConsole(f, s, callback, data)); lastGConsole = c; if (consolePrintHook() == NULL) { setConsolePrintHook(gconsolePrintHook); } return c; } GConsole::GConsole(const shared_ptr<GFont>& f, const Settings& s, Callback callback, void* data) : m_settings(s), m_callback(callback), m_callbackData(data), m_font(f), m_resetHistoryIndexOnEnter(true), m_rect(Rect2D::xywh(-finf(), -(float)inf(), (float)inf(), (float)inf())), m_bufferShift(0), m_active(false), m_inCompletion(false), m_cursorPos(0) { debugAssert(m_font); unsetRepeatKeysym(); m_keyDownTime = System::time(); setActive(true); m_historyIndex = m_history.size() - 1; } GConsole::~GConsole() { // Intentionally empty } void GConsole::setCallback(Callback callback, void* callbackData) { m_callback = callback; m_callbackData = callbackData; } void GConsole::setActive(bool a) { if (m_active != a) { unsetRepeatKeysym(); m_active = a; if (m_manager != NULL) { if (m_active) { m_manager->setFocusedWidget(dynamic_pointer_cast<Widget>(shared_from_this())); // Conservative; these bounds will be refined in render m_rect = Rect2D::xywh(-(float)inf(), -(float)inf(), (float)inf(), (float)inf()); } else { m_manager->defocusWidget(dynamic_pointer_cast<Widget>(shared_from_this())); m_rect = Rect2D::xywh(0,0,0,0); } } } } void GConsole::onPose(Array<shared_ptr<Surface> >& posedArray, Array<shared_ptr<Surface2D> >& posed2DArray) { if (m_active) { posed2DArray.append(dynamic_pointer_cast<Surface2D>(shared_from_this())); } } void GConsole::issueCommand() { string oldCommandLine = m_currentLine; m_currentLine = string(); m_cursorPos = 0; // Jump back to the end m_bufferShift = 0; if (m_settings.commandEcho) { print(oldCommandLine, m_settings.defaultCommandColor); } else { addToCompletionHistory(oldCommandLine); } m_history.push(oldCommandLine); if (m_resetHistoryIndexOnEnter) { // Note that we need to go one past the end of the list so that // the first up arrow allows us to hit the last element. m_historyIndex = m_history.size(); m_resetHistoryIndexOnEnter = true; } onCommand(oldCommandLine); } void GConsole::onCommand(const string& cmd) { if (m_callback) { m_callback(cmd, m_callbackData); } } void GConsole::clearBuffer() { m_buffer.clear(); m_bufferShift = 0; } void GConsole::clearHistory() { m_history.clear(); } void GConsole::paste(const string& s) { if (s.empty()) { // Nothing to do return; } size_t i = 0; // Separate the string by newlines and paste each individually do { size_t j = s.find('\n', i); bool issue = true; if (j == string::npos) { j = s.size(); issue = false; } string insert = s.substr(i, j - i + 1); if (! insert.empty()) { if (insert[0] == '\r') { // On Win32, we can conceivably get carriage returns next to newlines in a paste insert = insert.substr(1, insert.size() - 1); } if (! insert.empty() && (insert[insert.size() - 1] == '\r')) { insert = insert.substr(0, insert.size() - 1); } if (! insert.empty()) { string begin = m_currentLine.substr(0, max(0, m_cursorPos - 1)); string end = m_currentLine.substr(m_cursorPos, m_currentLine.size() - m_cursorPos + 1); m_currentLine = begin + insert + end; m_cursorPos += (int)insert.size(); } } if (issue) { issueCommand(); } i = j + 1; } while (i < s.size()); } void __cdecl GConsole::printf(const char* fmt, ...) { va_list arg_list; va_start(arg_list, fmt); vprintf(fmt, arg_list); va_end(arg_list); } void __cdecl GConsole::vprintf(const char* fmt, va_list argPtr) { print(vformat(fmt, argPtr), m_settings.defaultPrintColor); } void GConsole::print(const string& s) { print(s, m_settings.defaultPrintColor); } void GConsole::print(const string& s, const Color4& c) { // Break by newlines size_t firstNewline = (int)s.find('\n'); if ((firstNewline != String::npos) && (firstNewline != s.size() - 1)) { // There are newlines in the middle of this string Array<String> lines = stringSplit(s, '\n'); for (int i = 0; i < lines.size() - 1; ++i) { print(lines[i] + "\n", c); } if (lines.last() != "") { print(lines.last() + "\n", c); } return; } addToCompletionHistory(s); // If the buffer is too long, pop one from the front if (m_buffer.size() >= m_settings.maxBufferLength) { m_buffer.popFront(); } m_buffer.pushBack(Text(s, c)); } static void parseForCompletion( const GConsole::string& source, const int x, GConsole::string& beginStr, GConsole::string& matchStr, GConsole::string& endStr) { // Search backwards for a non-identifier character (start one before cursor) int i = x - 1; while ((i >= 0) && (isDigit(source[i]) || isLetter(source[i]))) { --i; } beginStr = source.substr(0, i + 1); matchStr = source.substr(i + 1, x - i - 1); endStr = source.substr(x, source.size() - x + 1); } /*inline static bool isQuote(char c) { return (c == '\'') || (c == '\"'); } */ void GConsole::generateFilenameCompletions(Array<string>& files) { if (m_cursorPos == 0) { // Nothing to do return; } // Walk backwards, looking for a slash space or a quote that breaks the filename) int i = m_cursorPos - 1; while ((i > 0) && ! isWhitespace(m_currentLine[i - 1]) && ! isQuote(m_currentLine[i - 1])) { --i; } const String& filespec = m_currentLine.substr(i, m_cursorPos - i + 1) + "*"; FileSystem::list(filespec, files); } void GConsole::beginCompletion() { m_completionArray.fastClear(); // Separate the current line into two pieces; before and after the current word. // A word follows normal C++ identifier rules. string matchStr; parseForCompletion(m_currentLine, m_cursorPos, m_completionBeginStr, matchStr, m_completionEndStr); // Push the current command on so that we can TAB back to it m_completionArray.push(matchStr); m_completionArrayIndex = 0; // Don't insert the same completion more than once static Set<string> alreadySeen; if (m_settings.performFilenameCompletion) { static Array<string> fcomplete; generateFilenameCompletions(fcomplete); for (int i = 0; i < fcomplete.size(); ++i) { const string& s = fcomplete[i]; if (! alreadySeen.contains(s)) { m_completionArray.push(s); } } fcomplete.fastClear(); } if (m_settings.performCommandCompletion && ! matchStr.empty()) { // Generate command completions against completionHistory for (int i = 0; i < m_completionHistory.size(); ++i) { const string& s = m_completionHistory[i]; if (beginsWith(s, matchStr) && ! alreadySeen.contains(s)) { m_completionArray.push(s); } } // Generate command completions against seed array for (int i = 0; i < m_settings.commandCompletionSeed.size(); ++i) { const string& s = m_settings.commandCompletionSeed[i]; if (beginsWith(s, matchStr) && ! alreadySeen.contains(s)) { m_completionArray.push(s); } } } if (m_completionArray.size() > 1) { // We found at least one new alternative to the current string m_inCompletion = true; } alreadySeen.clear(); } void GConsole::endCompletion() { // Cancel the current completion m_inCompletion = false; } void GConsole::addTokenToCompletionHistory(const string& s) { // See if already present if (m_completionHistorySet.contains(s)) { return; } // See if we need to remove a queue element if (m_completionHistory.size() > m_settings.maxCompletionHistorySize) { m_completionHistorySet.remove(m_completionHistory.popFront()); } m_completionHistory.pushBack(s); m_completionHistorySet.insert(s); } void GConsole::addToCompletionHistory(const string& s) { // Parse tokens. // This algorithm treats a token as a legal C++ identifier, number, or string. // A better algorithm might follow the one from emacs, which considers pathnames // and operator-separated tokens to also be tokens when combined. static bool initialized = false; static TextInput::Settings settings; if (! initialized) { settings.cppBlockComments = false; settings.cppLineComments = false; settings.msvcFloatSpecials = false; initialized = true; } try { TextInput t(TextInput::FROM_STRING, s, settings); while (t.hasMore()) { Token x = t.read(); // No point in considering one-character completions if (x.string().size() > 1) { if (x.type() == Token::STRING) { // Recurse into the string to grab its tokens addToCompletionHistory(x.string()); } else { // Add the raw unparsed string contents addTokenToCompletionHistory(x.string()); } // if string } // if } // while } catch (...) { // In the event of a parse exception we just give up on this string; // the worst that will happen is that we'll miss the opportunity to // add some tokens. } } void GConsole::completeCommand(int direction) { if (! m_inCompletion) { beginCompletion(); if (! m_inCompletion) { // No identifier under cursor return; } } // Compose new command line m_completionArrayIndex = (m_completionArrayIndex + m_completionArray.size() + direction) % m_completionArray.size(); const string& str = m_completionArray[m_completionArrayIndex]; m_currentLine = m_completionBeginStr + str + m_completionEndStr; m_cursorPos = (int)(m_completionBeginStr.size() + str.size()); m_resetHistoryIndexOnEnter = true; } void GConsole::processRepeatKeysym() { if ((m_repeatKeysym.sym != GKey::TAB) && m_inCompletion) { endCompletion(); } switch (m_repeatKeysym.sym) { case GKey::UNKNOWN: // No key break; case GKey::RIGHT: if (m_cursorPos < (int)m_currentLine.size()) { ++m_cursorPos; } break; case GKey::LEFT: if (m_cursorPos > 0) { --m_cursorPos; } break; case GKey::HOME: m_cursorPos = 0; break; case GKey::END: m_cursorPos = (int)m_currentLine.size(); break; case GKey::DELETE: if (m_cursorPos < (int)m_currentLine.size()) { m_currentLine = m_currentLine.substr(0, m_cursorPos) + m_currentLine.substr(m_cursorPos + 1, string::npos); m_resetHistoryIndexOnEnter = true; } break; case GKey::BACKSPACE: if (m_cursorPos > 0) { m_currentLine = m_currentLine.substr(0, m_cursorPos - 1) + ((m_cursorPos < (int)m_currentLine.size()) ? m_currentLine.substr(m_cursorPos, string::npos) : string()); m_resetHistoryIndexOnEnter = true; --m_cursorPos; } break; case GKey::UP: if (m_historyIndex > 0) { historySelect(-1); } break; case GKey::DOWN: if (m_historyIndex < m_history.size() - 1) { historySelect(+1); } break; case GKey::TAB: // Command completion if ((m_repeatKeysym.mod & GKeyMod::SHIFT) != 0) { completeCommand(-1); } else { completeCommand(1); } break; case GKey::PAGEUP: if (m_bufferShift < m_buffer.length() - m_settings.numVisibleLines + 1) { ++m_bufferShift; } break; case GKey::PAGEDOWN: if (m_bufferShift > 0) { --m_bufferShift; } break; case GKey::RETURN: issueCommand(); break; default: // This key wasn't processed by the console debugAssertM(false, "Unexpected repeat key"); } } void GConsole::historySelect(int direction) { m_historyIndex += direction; m_currentLine = m_history[m_historyIndex]; m_cursorPos = (int)m_currentLine.size(); m_resetHistoryIndexOnEnter = false; } void GConsole::setRepeatKeysym(GKeySym key) { m_keyDownTime = System::time(); m_keyRepeatTime = m_keyDownTime + m_settings.keyRepeatDelay; m_repeatKeysym = key; } void GConsole::unsetRepeatKeysym() { m_repeatKeysym.sym = GKey::UNKNOWN; } bool GConsole::onEvent(const GEvent& event) { if (! m_active) { if ((event.type == GEventType::CHAR_INPUT) && ((event.character.unicode & 0xFF) == '~')) { // '~': Open console setActive(true); return true; } else { // Console is closed, ignore key return false; } } switch (event.type) { case GEventType::KEY_DOWN: switch (event.key.keysym.sym) { case GKey::ESCAPE: // Close the console setActive(false); return true; case GKey::RIGHT: case GKey::LEFT: case GKey::DELETE: case GKey::BACKSPACE: case GKey::UP: case GKey::DOWN: case GKey::PAGEUP: case GKey::PAGEDOWN: case GKey::RETURN: case GKey::HOME: case GKey::END: setRepeatKeysym(event.key.keysym); processRepeatKeysym(); return true; break; case GKey::TAB: setRepeatKeysym(event.key.keysym); processRepeatKeysym(); // Tab is used for command completion and shouldn't repeat unsetRepeatKeysym(); return true; break; default: if ((((event.key.keysym.mod & GKeyMod::CTRL) != 0) && ((event.key.keysym.sym == 'v') || (event.key.keysym.sym == 'y'))) || (((event.key.keysym.mod & GKeyMod::SHIFT) != 0) && (event.key.keysym.sym == GKey::INSERT))) { // Paste (not autorepeatable) paste(OSWindow::clipboardText()); return true; } else if (((event.key.keysym.mod & GKeyMod::CTRL) != 0) && (event.key.keysym.sym == 'k')) { // Cut (not autorepeatable) string cut = m_currentLine.substr(m_cursorPos); m_currentLine = m_currentLine.substr(0, m_cursorPos); OSWindow::setClipboardText(cut); return true; } else if ((event.key.keysym.sym >= GKey::SPACE) && (event.key.keysym.sym <= 'z')) { // Suppress this event. Actually handle the key press on the CHAR_INPUT event return true; } else { // Text input is done through CHAR_INPUT events instead // This key wasn't processed by the console return false; } } break; case GEventType::KEY_UP: if (event.key.keysym.sym == m_repeatKeysym.sym) { unsetRepeatKeysym(); return true; } break; case GEventType::CHAR_INPUT: // Insert character char c = event.character.unicode & 0xFF; m_currentLine = m_currentLine.substr(0, m_cursorPos) + c + ((m_cursorPos < (int)m_currentLine.size()) ? m_currentLine.substr(m_cursorPos, string::npos) : string()); ++m_cursorPos; m_resetHistoryIndexOnEnter = true; break; } return false; } void GConsole::render(RenderDevice* rd) const { if (! m_active) { return; } static const float pad = 2; const float fontSize = m_settings.lineHeight - 3; Rect2D rect; static RealTime then = System::time(); RealTime now = System::time(); bool hasKeyDown = (m_repeatKeysym.sym != GKey::UNKNOWN); // Amount of time that the last simulation step took. // This is used to limit the key repeat rate // so that it is not faster than the frame rate. RealTime frameTime = then - now; // If a key is being pressed, process it on a steady repeat schedule. if (hasKeyDown && (now > m_keyRepeatTime)) { const_cast<GConsole*>(this)->processRepeatKeysym(); m_keyRepeatTime = max(now + frameTime * 1.1, now + 1.0 / m_settings.keyRepeatRate); } then = now; // Only blink the cursor when keys are not being pressed or // have not recently been pressed. bool solidCursor = hasKeyDown || (now - m_keyRepeatTime < 1.0 / m_settings.blinkRate); if (! solidCursor) { static const RealTime zero = System::time(); solidCursor = isOdd((int)((now - zero) * m_settings.blinkRate)); } { float w = (float)rd->width(); float h = (float)rd->height(); float myHeight = m_settings.lineHeight * m_settings.numVisibleLines + pad * 2; rect = m_rect = Rect2D::xywh(pad, h - myHeight - pad, w - pad * 2, myHeight); } rd->push2D(); rd->setBlendFunc(RenderDevice::BLEND_SRC_ALPHA, RenderDevice::BLEND_ONE_MINUS_SRC_ALPHA); if (m_settings.backgroundColor.a > 0) { Draw::rect2D(rect, rd, m_settings.backgroundColor); } if (m_bufferShift > 0) { // Draw a line indicating that we aren't looking at the bottom of the buffer SlowMesh mesh(PrimitiveType::LINES); mesh.setColor(Color3::white()); const Vector2 v(rect.x0() - 0.3f, rect.y1() - m_settings.lineHeight + 1 - 0.3f); mesh.makeVertex(v); mesh.makeVertex(v + Vector2(rect.width(), 0)); mesh.render(rd); } static Array<GFont::CPUCharVertex> charVertexArray; static Array<int> indexArray; charVertexArray.fastClear(); indexArray.fastClear(); // Show PGUP/PGDN commands if (m_buffer.size() >= m_settings.numVisibleLines) { m_font->appendToCharVertexArray(charVertexArray, indexArray, rd, "pgup ^", rect.x1y0() - Vector2(2, 0), fontSize * 0.75f, Color4(1,1,1,0.7f), Color4::clear(), GFont::XALIGN_RIGHT, GFont::YALIGN_TOP); m_font->appendToCharVertexArray(charVertexArray, indexArray, rd, "pgdn v", rect.x1y1() - Vector2(2, 0), fontSize * 0.75f, Color4(1,1,1,0.7f), Color4::clear(), GFont::XALIGN_RIGHT, GFont::YALIGN_BOTTOM); } rect = Rect2D::xyxy(rect.x0y0() + Vector2(2,1), rect.x1y1() - Vector2(2, 1)); // Print history for (int count = 0; count < m_settings.numVisibleLines - 1; ++count) { int q = m_buffer.size() - count - 1 - m_bufferShift; if (q >= 0) { m_font->appendToCharVertexArray(charVertexArray, indexArray, rd, m_buffer[q].value, rect.x0y1() - Vector2(0, m_settings.lineHeight * (count + 2)), fontSize, m_buffer[q].color); } } m_font->appendToCharVertexArray(charVertexArray, indexArray, rd, m_currentLine, rect.x0y1() - Vector2(0, m_settings.lineHeight), fontSize, m_settings.defaultCommandColor); // Draw cursor if (solidCursor) { // Put cursor under a specific character. We need to check bounds to do this because we might not // have a fixed width font. Vector2 bounds; if (m_cursorPos > 0) { bounds = m_font->bounds(m_currentLine.substr(0, m_cursorPos), fontSize); } m_font->appendToCharVertexArray(charVertexArray, indexArray, rd, "_", rect.x0y1() + Vector2(bounds.x, -m_settings.lineHeight), fontSize, m_settings.defaultCommandColor); } m_font->renderCharVertexArray(rd, charVertexArray, indexArray); rd->pop2D(); } void GConsole::onNetwork() { } void GConsole::onAI() { } void GConsole::onUserInput(UserInput* ui) { if (m_active && (m_manager->focusedWidget().get() != this)) { // Something else has stolen the focus; turn off the console. setActive(false); } } void GConsole::onSimulation(RealTime rdt, SimTime sdt, SimTime idt) { } } // G3D
0
0.974642
1
0.974642
game-dev
MEDIA
0.344794
game-dev
0.959396
1
0.959396
nbusseneau/hephaistos
1,248
hephaistos-data/lua/GUIComponents/UpgradeChoice.lua
local filterHooks = { OpenUpgradeChoiceMenu = { SetScale = { -- boon / hammer choice menu overlay UpgradeChoiceMenuOverlay = { Filter = function(params) return Hephaistos.MatchAll(params, { Id = ScreenAnchors.ChoiceScreen.Components.ShopBackgroundDim.Id, Fraction = 4 }) end, Callback = Hephaistos.Rescale, }, }, CreateScreenComponent = { -- top left icon on boon / hammer choice menu UpgradeChoiceMenuTopLeftIcon = { Filter = function(params) return Hephaistos.MatchAll(params, { Name = "rectangle01", Group = "Combat_Menu", X = 182, Y = 160 }) end, Callback = Hephaistos.Recenter, }, }, }, CreateBoonLootButtons = { CreateScreenComponent = { -- the boons themselves UpgradeChoiceMenuBoons = { Filter = function(params) return Hephaistos.MatchAll(params, { Group = "Combat_Menu" }, { Group = "Combat_Menu_Overlay_Backing" }) and params.X and params.Y end, Callback = function(params) params.Y = Hephaistos.RecomputeFixedYFromCenter(params.Y) end, }, }, }, } Hephaistos.CopyFilterHooks(filterHooks, Hephaistos.FilterHooks)
0
0.868009
1
0.868009
game-dev
MEDIA
0.88553
game-dev
0.882274
1
0.882274
ronbrogan/OpenH2
2,627
src/OpenH2.Engine/Systems/Physics/DefaultFilterShader.cs
using PhysX; namespace OpenH2.Engine.Systems.Physics { public enum OpenH2FilterData : uint { PlayerCharacter = 1 << 0, AiActor = 1 << 1, TriggerVolume = 1 << 2, NoClip = 1 << 3, TriggerSubject = PlayerCharacter | AiActor } public class DefaultFilterShader : SimulationFilterShader { private static FilterResult DefaultResult = new FilterResult() { PairFlags = PairFlag.ContactDefault, FilterFlag = FilterFlag.Default }; private static FilterResult PlayerCharacterResult = new FilterResult() { PairFlags = PairFlag.ModifyContacts | PairFlag.ContactDefault, FilterFlag = FilterFlag.Default }; private static FilterResult TriggerVolumeResult = new FilterResult() { PairFlags = PairFlag.TriggerDefault, FilterFlag = FilterFlag.Default }; public override FilterResult Filter(int attributes0, FilterData filterData0, int attributes1, FilterData filterData1) { if(filterData0.Word0 == 0 && filterData1.Word0 == 0) { return DefaultResult; } var result = DefaultResult; result.FilterFlag = FilterFlag.Default; if(IsPlayerCharacter(filterData0) || IsPlayerCharacter(filterData1)) { result.PairFlags |= PlayerCharacterResult.PairFlags; } if ((IsTriggerSubject(filterData0) || IsTriggerSubject(filterData1)) && (IsTriggerVolume(filterData0) || IsTriggerVolume(filterData1))) { result.PairFlags |= TriggerVolumeResult.PairFlags; } if(IsNoClip(filterData0) || IsNoClip(filterData1)) { // TODO: surface PairFlag.SolveContact in package result.PairFlags = (result.PairFlags) & (PairFlag)(~1); } return result; } private bool IsPlayerCharacter(FilterData fd) => (((OpenH2FilterData)fd.Word0) & OpenH2FilterData.PlayerCharacter) == OpenH2FilterData.PlayerCharacter; private bool IsNoClip(FilterData fd) => (((OpenH2FilterData)fd.Word0) & OpenH2FilterData.NoClip) == OpenH2FilterData.NoClip; private bool IsTriggerVolume(FilterData fd) => (((OpenH2FilterData)fd.Word0) & OpenH2FilterData.TriggerVolume) == OpenH2FilterData.TriggerVolume; private bool IsTriggerSubject(FilterData fd) => (((OpenH2FilterData)fd.Word0) & OpenH2FilterData.TriggerSubject) != 0; } }
0
0.78776
1
0.78776
game-dev
MEDIA
0.494601
game-dev
0.754063
1
0.754063
ezEngine/ezEngine
30,185
Code/ThirdParty/RmlUi/Dependencies/lunasvg/source/svgparser.cpp
#include "lunasvg.h" #include "svgelement.h" #include "svgparserutils.h" #include <cassert> namespace lunasvg { struct SimpleSelector; using Selector = std::vector<SimpleSelector>; using SelectorList = std::vector<Selector>; struct AttributeSelector { enum class MatchType { None, Equals, Contains, Includes, StartsWith, EndsWith, DashEquals }; MatchType matchType{MatchType::None}; PropertyID id{PropertyID::Unknown}; std::string value; }; struct PseudoClassSelector { enum class Type { Unknown, Empty, Root, Is, Not, FirstChild, LastChild, OnlyChild, FirstOfType, LastOfType, OnlyOfType }; Type type{Type::Unknown}; SelectorList subSelectors; }; struct SimpleSelector { enum class Combinator { None, Descendant, Child, DirectAdjacent, InDirectAdjacent }; explicit SimpleSelector(Combinator combinator) : combinator(combinator) {} Combinator combinator{Combinator::Descendant}; ElementID id{ElementID::Star}; std::vector<AttributeSelector> attributeSelectors; std::vector<PseudoClassSelector> pseudoClassSelectors; }; struct Declaration { int specificity; PropertyID id; std::string value; }; using DeclarationList = std::vector<Declaration>; struct Rule { SelectorList selectors; DeclarationList declarations; }; class RuleData { public: RuleData(const Selector& selector, const DeclarationList& declarations, size_t specificity, size_t position) : m_selector(selector), m_declarations(declarations), m_specificity(specificity), m_position(position) {} bool isLessThan(const RuleData& rule) const { return std::tie(m_specificity, m_position) < std::tie(rule.m_specificity, rule.m_position); } const Selector& selector() const { return m_selector; } const DeclarationList& declarations() const { return m_declarations; } size_t specificity() const { return m_specificity; } size_t position() const { return m_position; } bool match(const SVGElement* element) const; private: Selector m_selector; DeclarationList m_declarations; size_t m_specificity; size_t m_position; }; inline bool operator<(const RuleData& a, const RuleData& b) { return a.isLessThan(b); } using RuleDataList = std::vector<RuleData>; constexpr bool equals(const std::string_view& value, const std::string_view& subvalue) { return value.compare(subvalue) == 0; } constexpr bool contains(const std::string_view& value, const std::string_view& subvalue) { return value.find(subvalue) != std::string_view::npos; } constexpr bool includes(const std::string_view& value, const std::string_view& subvalue) { if(subvalue.empty() || subvalue.length() > value.length()) return false; std::string_view input(value); while(!input.empty()) { skipOptionalSpaces(input); std::string_view start(input); while(!input.empty() && !IS_WS(input.front())) input.remove_prefix(1); if(subvalue == start.substr(0, start.length() - input.length())) { return true; } } return false; } constexpr bool startswith(const std::string_view& value, const std::string_view& subvalue) { if(subvalue.empty() || subvalue.length() > value.length()) return false; return subvalue == value.substr(0, subvalue.size()); } constexpr bool endswith(const std::string_view& value, const std::string_view& subvalue) { if(subvalue.empty() || subvalue.length() > value.length()) return false; return subvalue == value.substr(value.size() - subvalue.size(), subvalue.size()); } constexpr bool dashequals(const std::string_view& value, const std::string_view& subvalue) { if(startswith(value, subvalue)) return (value.length() == subvalue.length() || value.at(subvalue.length()) == '-'); return false; } static bool matchAttributeSelector(const AttributeSelector& selector, const SVGElement* element) { const auto& value = element->getAttribute(selector.id); if(selector.matchType == AttributeSelector::MatchType::None) return !value.empty(); if(selector.matchType == AttributeSelector::MatchType::Equals) return equals(value, selector.value); if(selector.matchType == AttributeSelector::MatchType::Contains) return contains(value, selector.value); if(selector.matchType == AttributeSelector::MatchType::Includes) return includes(value, selector.value); if(selector.matchType == AttributeSelector::MatchType::StartsWith) return startswith(value, selector.value); if(selector.matchType == AttributeSelector::MatchType::EndsWith) return endswith(value, selector.value); if(selector.matchType == AttributeSelector::MatchType::DashEquals) return dashequals(value, selector.value); return false; } static bool matchSimpleSelector(const SimpleSelector& selector, const SVGElement* element); static bool matchPseudoClassSelector(const PseudoClassSelector& selector, const SVGElement* element) { if(selector.type == PseudoClassSelector::Type::Empty) return element->children().empty(); if(selector.type == PseudoClassSelector::Type::Root) return element->isRootElement(); if(selector.type == PseudoClassSelector::Type::Is) { for(const auto& subSelector : selector.subSelectors) { for(const auto& simpleSelector : subSelector) { if(!matchSimpleSelector(simpleSelector, element)) { return false; } } } return true; } if(selector.type == PseudoClassSelector::Type::Not) { for(const auto& subSelector : selector.subSelectors) { for(const auto& simpleSelector : subSelector) { if(matchSimpleSelector(simpleSelector, element)) { return false; } } } return true; } if(selector.type == PseudoClassSelector::Type::FirstChild) return !element->previousElement(); if(selector.type == PseudoClassSelector::Type::LastChild) return !element->nextElement(); if(selector.type == PseudoClassSelector::Type::OnlyChild) return !(element->previousElement() || element->nextElement()); if(selector.type == PseudoClassSelector::Type::FirstOfType) { auto sibling = element->previousElement(); while(sibling) { if(sibling->id() == element->id()) return false; sibling = element->previousElement(); } return true; } if(selector.type == PseudoClassSelector::Type::LastOfType) { auto sibling = element->nextElement(); while(sibling) { if(sibling->id() == element->id()) return false; sibling = element->nextElement(); } return true; } return false; } static bool matchSimpleSelector(const SimpleSelector& selector, const SVGElement* element) { if(selector.id != ElementID::Star && selector.id != element->id()) return false; for(const auto& sel : selector.attributeSelectors) { if(!matchAttributeSelector(sel, element)) { return false; } } for(const auto& sel : selector.pseudoClassSelectors) { if(!matchPseudoClassSelector(sel, element)) { return false; } } return true; } static bool matchSelector(const Selector& selector, const SVGElement* element) { if(selector.empty()) return false; auto it = selector.rbegin(); auto end = selector.rend(); if(!matchSimpleSelector(*it, element)) { return false; } auto combinator = it->combinator; ++it; while(it != end) { switch(combinator) { case SimpleSelector::Combinator::Child: case SimpleSelector::Combinator::Descendant: element = element->parentElement(); break; case SimpleSelector::Combinator::DirectAdjacent: case SimpleSelector::Combinator::InDirectAdjacent: element = element->previousElement(); break; case SimpleSelector::Combinator::None: assert(false); } if(element == nullptr) return false; if(matchSimpleSelector(*it, element)) { combinator = it->combinator; ++it; } else if(combinator != SimpleSelector::Combinator::Descendant && combinator != SimpleSelector::Combinator::InDirectAdjacent) { return false; } } return true; } bool RuleData::match(const SVGElement* element) const { return matchSelector(m_selector, element); } constexpr bool IS_CSS_STARTNAMECHAR(int c) { return IS_ALPHA(c) || c == '_' || c == '-'; } constexpr bool IS_CSS_NAMECHAR(int c) { return IS_CSS_STARTNAMECHAR(c) || IS_NUM(c); } inline bool readCSSIdentifier(std::string_view& input, std::string& output) { if(input.empty() || !IS_CSS_STARTNAMECHAR(input.front())) return false; output.clear(); do { output.push_back(input.front()); input.remove_prefix(1); } while(!input.empty() && IS_CSS_NAMECHAR(input.front())); return true; } static bool parseTagSelector(std::string_view& input, SimpleSelector& simpleSelector) { std::string name; if(skipDelimiter(input, '*')) simpleSelector.id = ElementID::Star; else if(readCSSIdentifier(input, name)) simpleSelector.id = elementid(name); else return false; return true; } static bool parseIdSelector(std::string_view& input, SimpleSelector& simpleSelector) { AttributeSelector a; a.id = PropertyID::Id; a.matchType = AttributeSelector::MatchType::Equals; if(!readCSSIdentifier(input, a.value)) return false; simpleSelector.attributeSelectors.push_back(std::move(a)); return true; } static bool parseClassSelector(std::string_view& input, SimpleSelector& simpleSelector) { AttributeSelector a; a.id = PropertyID::Class; a.matchType = AttributeSelector::MatchType::Includes; if(!readCSSIdentifier(input, a.value)) return false; simpleSelector.attributeSelectors.push_back(std::move(a)); return true; } static bool parseAttributeSelector(std::string_view& input, SimpleSelector& simpleSelector) { std::string name; skipOptionalSpaces(input); if(!readCSSIdentifier(input, name)) return false; AttributeSelector a; a.id = propertyid(name); a.matchType = AttributeSelector::MatchType::None; if(skipDelimiter(input, '=')) a.matchType = AttributeSelector::MatchType::Equals; else if(skipString(input, "*=")) a.matchType = AttributeSelector::MatchType::Contains; else if(skipString(input, "~=")) a.matchType = AttributeSelector::MatchType::Includes; else if(skipString(input, "^=")) a.matchType = AttributeSelector::MatchType::StartsWith; else if(skipString(input, "$=")) a.matchType = AttributeSelector::MatchType::EndsWith; else if(skipString(input, "|=")) a.matchType = AttributeSelector::MatchType::DashEquals; if(a.matchType != AttributeSelector::MatchType::None) { skipOptionalSpaces(input); if(!readCSSIdentifier(input, a.value)) { if(input.empty() || !(input.front() == '\"' || input.front() == '\'')) return false; auto quote = input.front(); input.remove_prefix(1); auto n = input.find(quote); if(n == std::string_view::npos) return false; a.value.assign(input.substr(0, n)); input.remove_prefix(n + 1); } } skipOptionalSpaces(input); if(!skipDelimiter(input, ']')) return false; simpleSelector.attributeSelectors.push_back(std::move(a)); return true; } static bool parseSelectors(std::string_view& input, SelectorList& selectors); static bool parsePseudoClassSelector(std::string_view& input, SimpleSelector& simpleSelector) { std::string name; if(!readCSSIdentifier(input, name)) return false; PseudoClassSelector selector; if(name.compare("empty") == 0) selector.type = PseudoClassSelector::Type::Empty; else if(name.compare("root") == 0) selector.type = PseudoClassSelector::Type::Root; else if(name.compare("not") == 0) selector.type = PseudoClassSelector::Type::Not; else if(name.compare("first-child") == 0) selector.type = PseudoClassSelector::Type::FirstChild; else if(name.compare("last-child") == 0) selector.type = PseudoClassSelector::Type::LastChild; else if(name.compare("only-child") == 0) selector.type = PseudoClassSelector::Type::OnlyChild; else if(name.compare("first-of-type") == 0) selector.type = PseudoClassSelector::Type::FirstOfType; else if(name.compare("last-of-type") == 0) selector.type = PseudoClassSelector::Type::LastOfType; else if(name.compare("only-of-type") == 0) selector.type = PseudoClassSelector::Type::OnlyOfType; if(selector.type == PseudoClassSelector::Type::Is || selector.type == PseudoClassSelector::Type::Not) { skipOptionalSpaces(input); if(!skipDelimiter(input, '(')) return false; skipOptionalSpaces(input); if(!parseSelectors(input, selector.subSelectors)) return false; skipOptionalSpaces(input); if(!skipDelimiter(input, ')')) { return false; } } simpleSelector.pseudoClassSelectors.push_back(std::move(selector)); return true; } static bool parseSimpleSelector(std::string_view& input, SimpleSelector& simpleSelector, bool& failed) { auto consumed = parseTagSelector(input, simpleSelector); do { if(skipDelimiter(input, '#')) failed = !parseIdSelector(input, simpleSelector); else if(skipDelimiter(input, '.')) failed = !parseClassSelector(input, simpleSelector); else if(skipDelimiter(input, '[')) failed = !parseAttributeSelector(input, simpleSelector); else if(skipDelimiter(input, ':')) failed = !parsePseudoClassSelector(input, simpleSelector); else break; consumed = true; } while(!failed); return consumed && !failed; } static bool parseCombinator(std::string_view& input, SimpleSelector::Combinator& combinator) { combinator = SimpleSelector::Combinator::None; while(!input.empty() && IS_WS(input.front())) { combinator = SimpleSelector::Combinator::Descendant; input.remove_prefix(1); } if(skipDelimiterAndOptionalSpaces(input, '>')) combinator = SimpleSelector::Combinator::Child; else if(skipDelimiterAndOptionalSpaces(input, '+')) combinator = SimpleSelector::Combinator::DirectAdjacent; else if(skipDelimiterAndOptionalSpaces(input, '~')) combinator = SimpleSelector::Combinator::InDirectAdjacent; return combinator != SimpleSelector::Combinator::None; } static bool parseSelector(std::string_view& input, Selector& selector) { auto combinator = SimpleSelector::Combinator::None; do { bool failed = false; SimpleSelector simpleSelector(combinator); if(!parseSimpleSelector(input, simpleSelector, failed)) return !failed && (combinator == SimpleSelector::Combinator::Descendant); selector.push_back(std::move(simpleSelector)); } while(parseCombinator(input, combinator)); return true; } static bool parseSelectors(std::string_view& input, SelectorList& selectors) { do { Selector selector; if(!parseSelector(input, selector)) return false; selectors.push_back(std::move(selector)); } while(skipDelimiterAndOptionalSpaces(input, ',')); return true; } static bool parseDeclarations(std::string_view& input, DeclarationList& declarations) { if(!skipDelimiter(input, '{')) return false; skipOptionalSpaces(input); do { std::string name; if(!readCSSIdentifier(input, name)) return false; skipOptionalSpaces(input); if(!skipDelimiter(input, ':')) return false; skipOptionalSpaces(input); std::string_view value(input); while(!input.empty() && !(input.front() == '!' || input.front() == ';' || input.front() == '}')) input.remove_prefix(1); value.remove_suffix(input.length()); stripTrailingSpaces(value); Declaration declaration; declaration.specificity = 0x10; declaration.id = csspropertyid(name); declaration.value.assign(value); if(skipDelimiter(input, '!')) { skipOptionalSpaces(input); if(!skipString(input, "important")) return false; declaration.specificity = 0x1000; } if(declaration.id != PropertyID::Unknown) declarations.push_back(std::move(declaration)); skipOptionalSpacesOrDelimiter(input, ';'); } while(!input.empty() && input.front() != '}'); return skipDelimiter(input, '}'); } static bool parseRule(std::string_view& input, Rule& rule) { if(!parseSelectors(input, rule.selectors)) return false; return parseDeclarations(input, rule.declarations); } static RuleDataList parseStyleSheet(std::string_view input) { RuleDataList rules; while(!input.empty()) { skipOptionalSpaces(input); if(skipDelimiter(input, '@')) { int depth = 0; while(!input.empty()) { auto ch = input.front(); input.remove_prefix(1); if(ch == ';' && depth == 0) break; if(ch == '{') ++depth; else if(ch == '}' && depth > 0) { if(depth == 1) break; --depth; } } continue; } Rule rule; if(!parseRule(input, rule)) break; for(const auto& selector : rule.selectors) { size_t specificity = 0; for(const auto& simpleSelector : selector) { specificity += (simpleSelector.id == ElementID::Star) ? 0x0 : 0x1; for(const auto& attributeSelector : simpleSelector.attributeSelectors) { specificity += (attributeSelector.id == PropertyID::Id) ? 0x10000 : 0x100; } } rules.emplace_back(selector, rule.declarations, specificity, rules.size()); } } return rules; } static SelectorList parseQuerySelectors(std::string_view input) { SelectorList selectors; stripLeadingAndTrailingSpaces(input); if(!parseSelectors(input, selectors) || !input.empty()) { return SelectorList(); } return selectors; } inline void parseInlineStyle(std::string_view input, SVGElement* element) { std::string name; skipOptionalSpaces(input); while(readCSSIdentifier(input, name)) { skipOptionalSpaces(input); if(!skipDelimiter(input, ':')) return; std::string value; while(!input.empty() && input.front() != ';') { value.push_back(input.front()); input.remove_prefix(1); } auto id = csspropertyid(name); if(id != PropertyID::Unknown) element->setAttribute(0x100, id, value); skipOptionalSpacesOrDelimiter(input, ';'); } } inline void removeStyleComments(std::string& value) { auto start = value.find("/*"); while(start != std::string::npos) { auto end = value.find("*/", start + 2); value.erase(start, end - start + 2); start = value.find("/*"); } } inline bool decodeText(std::string_view input, std::string& output) { output.clear(); while(!input.empty()) { auto ch = input.front(); input.remove_prefix(1); if(ch != '&') { output.push_back(ch); continue; } if(skipDelimiter(input, '#')) { int base = 10; if(skipDelimiter(input, 'x')) base = 16; unsigned int cp; if(!parseInteger(input, cp, base)) return false; char c[5] = {0, 0, 0, 0, 0}; if(cp < 0x80) { c[1] = 0; c[0] = char(cp); } else if(cp < 0x800) { c[2] = 0; c[1] = char((cp & 0x3F) | 0x80); cp >>= 6; c[0] = char(cp | 0xC0); } else if(cp < 0x10000) { c[3] = 0; c[2] = char((cp & 0x3F) | 0x80); cp >>= 6; c[1] = char((cp & 0x3F) | 0x80); cp >>= 6; c[0] = char(cp | 0xE0); } else if(cp < 0x200000) { c[4] = 0; c[3] = char((cp & 0x3F) | 0x80); cp >>= 6; c[2] = char((cp & 0x3F) | 0x80); cp >>= 6; c[1] = char((cp & 0x3F) | 0x80); cp >>= 6; c[0] = char(cp | 0xF0); } output.append(c); } else { if(skipString(input, "amp")) { output.push_back('&'); } else if(skipString(input, "lt")) { output.push_back('<'); } else if(skipString(input, "gt")) { output.push_back('>'); } else if(skipString(input, "quot")) { output.push_back('\"'); } else if(skipString(input, "apos")) { output.push_back('\''); } else { return false; } } if(!skipDelimiter(input, ';')) { return false; } } return true; } constexpr bool IS_STARTNAMECHAR(int c) { return IS_ALPHA(c) || c == '_' || c == ':'; } constexpr bool IS_NAMECHAR(int c) { return IS_STARTNAMECHAR(c) || IS_NUM(c) || c == '-' || c == '.'; } inline bool readIdentifier(std::string_view& input, std::string& output) { if(input.empty() || !IS_STARTNAMECHAR(input.front())) return false; output.clear(); do { output.push_back(input.front()); input.remove_prefix(1); } while(!input.empty() && IS_NAMECHAR(input.front())); return true; } bool Document::parse(const char* data, size_t length) { std::string buffer; std::string styleSheet; SVGElement* currentElement = nullptr; int ignoring = 0; auto handleText = [&](const std::string_view& text, bool in_cdata) { if(text.empty() || currentElement == nullptr || ignoring > 0) return; if(currentElement->id() != ElementID::Text && currentElement->id() != ElementID::Tspan && currentElement->id() != ElementID::Style) { return; } if(in_cdata) { buffer.assign(text); } else { decodeText(text, buffer); } if(currentElement->id() == ElementID::Style) { removeStyleComments(buffer); styleSheet.append(buffer); } else { auto node = std::make_unique<SVGTextNode>(this); node->setData(buffer); currentElement->addChild(std::move(node)); } }; std::string_view input(data, length); while(!input.empty()) { if(currentElement) { auto text = input.substr(0, input.find('<')); handleText(text, false); input.remove_prefix(text.length()); } else { if(!skipOptionalSpaces(input)) { break; } } if(!skipDelimiter(input, '<')) return false; if(skipDelimiter(input, '?')) { if(!readIdentifier(input, buffer)) return false; auto n = input.find("?>"); if(n == std::string_view::npos) return false; input.remove_prefix(n + 2); continue; } if(skipDelimiter(input, '!')) { if(skipString(input, "--")) { auto n = input.find("-->"); if(n == std::string_view::npos) return false; handleText(input.substr(0, n), false); input.remove_prefix(n + 3); continue; } if(skipString(input, "[CDATA[")) { auto n = input.find("]]>"); if(n == std::string_view::npos) return false; handleText(input.substr(0, n), true); input.remove_prefix(n + 3); continue; } if(skipString(input, "DOCTYPE")) { while(!input.empty() && input.front() != '>') { if(input.front() == '[') { int depth = 1; input.remove_prefix(1); while(!input.empty() && depth > 0) { if(input.front() == '[') ++depth; else if(input.front() == ']') --depth; input.remove_prefix(1); } } else { input.remove_prefix(1); } } if(!skipDelimiter(input, '>')) return false; continue; } return false; } if(skipDelimiter(input, '/')) { if(currentElement == nullptr && ignoring == 0) return false; if(!readIdentifier(input, buffer)) return false; if(ignoring == 0) { auto id = elementid(buffer); if(id != currentElement->id()) return false; currentElement = currentElement->parentElement(); } else { --ignoring; } skipOptionalSpaces(input); if(!skipDelimiter(input, '>')) return false; continue; } if(!readIdentifier(input, buffer)) return false; SVGElement* element = nullptr; if(ignoring > 0) { ++ignoring; } else { auto id = elementid(buffer); if(id == ElementID::Unknown) { ignoring = 1; } else { if(m_rootElement && currentElement == nullptr) return false; if(m_rootElement == nullptr) { if(id != ElementID::Svg) return false; m_rootElement = std::make_unique<SVGRootElement>(this); element = m_rootElement.get(); } else { auto child = SVGElement::create(this, id); element = child.get(); currentElement->addChild(std::move(child)); } } } skipOptionalSpaces(input); while(readIdentifier(input, buffer)) { skipOptionalSpaces(input); if(!skipDelimiter(input, '=')) return false; skipOptionalSpaces(input); if(input.empty() || !(input.front() == '\"' || input.front() == '\'')) return false; auto quote = input.front(); input.remove_prefix(1); auto n = input.find(quote); if(n == std::string_view::npos) return false; auto id = PropertyID::Unknown; if(element != nullptr) id = propertyid(buffer); if(id != PropertyID::Unknown) { decodeText(input.substr(0, n), buffer); if(id == PropertyID::Style) { removeStyleComments(buffer); parseInlineStyle(buffer, element); } else { if(id == PropertyID::Id) m_rootElement->addElementById(buffer, element); element->setAttribute(0x1, id, buffer); } } input.remove_prefix(n + 1); skipOptionalSpaces(input); } if(skipDelimiter(input, '>')) { if(element != nullptr) currentElement = element; continue; } if(skipDelimiter(input, '/')) { if(!skipDelimiter(input, '>')) return false; if(ignoring > 0) --ignoring; continue; } return false; } if(m_rootElement == nullptr || ignoring > 0 || !input.empty()) return false; applyStyleSheet(styleSheet); m_rootElement->build(); return true; } void Document::applyStyleSheet(const std::string& content) { auto rules = parseStyleSheet(content); if(!rules.empty()) { std::sort(rules.begin(), rules.end()); m_rootElement->transverse([&rules](SVGElement* element) { for(const auto& rule : rules) { if(rule.match(element)) { for(const auto& declaration : rule.declarations()) { element->setAttribute(declaration.specificity, declaration.id, declaration.value); } } } }); } } ElementList Document::querySelectorAll(const std::string& content) const { auto selectors = parseQuerySelectors(content); if(selectors.empty()) return ElementList(); ElementList elements; m_rootElement->transverse([&](SVGElement* element) { for(const auto& selector : selectors) { if(matchSelector(selector, element)) { elements.push_back(element); break; } } }); return elements; } } // namespace lunasvg
0
0.97678
1
0.97678
game-dev
MEDIA
0.203718
game-dev
0.97693
1
0.97693
Coderx-Gamer/ui-utils
26,094
src/main/java/com/ui_utils/MainClient.java
package com.ui_utils; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.mojang.serialization.JsonOps; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.metadata.ModMetadata; import net.minecraft.client.MinecraftClient; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.c2s.play.ButtonClickC2SPacket; import net.minecraft.network.packet.c2s.play.ClickSlotC2SPacket; import net.minecraft.network.packet.c2s.play.CloseHandledScreenC2SPacket; import net.minecraft.screen.slot.SlotActionType; import net.minecraft.screen.sync.ItemStackHash; import net.minecraft.text.Text; import net.minecraft.text.TextCodecs; import org.jetbrains.annotations.NotNull; import org.lwjgl.glfw.GLFW; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ui_utils.mixin.accessor.ClientConnectionAccessor; import javax.swing.*; import java.awt.*; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; public class MainClient implements ClientModInitializer { public static Font monospace; public static Color darkWhite; public static KeyBinding restoreScreenKey; public static Logger LOGGER = LoggerFactory.getLogger("ui-utils"); public static MinecraftClient mc = MinecraftClient.getInstance(); @Override public void onInitializeClient() { UpdateUtils.checkForUpdates(); // register "restore screen" key restoreScreenKey = KeyBindingHelper.registerKeyBinding(new KeyBinding("Restore Screen", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "UI Utils")); // register event for END_CLIENT_TICK ClientTickEvents.END_CLIENT_TICK.register((client) -> { // detect if the "restore screen" keybinding is pressed while (restoreScreenKey.wasPressed()) { if (SharedVariables.storedScreen != null && SharedVariables.storedScreenHandler != null && client.player != null) { client.setScreen(SharedVariables.storedScreen); client.player.currentScreenHandler = SharedVariables.storedScreenHandler; } } }); // set java.awt.headless to false if os is not mac (allows for JFrame guis to be used) if (!MinecraftClient.IS_SYSTEM_MAC) { System.setProperty("java.awt.headless", "false"); monospace = new Font(Font.MONOSPACED, Font.PLAIN, 10); darkWhite = new Color(220, 220, 220); } } @SuppressWarnings("all") public static void createText(MinecraftClient mc, DrawContext context, TextRenderer textRenderer) { // display the current gui's sync id, revision context.drawText(textRenderer, "Sync Id: " + mc.player.currentScreenHandler.syncId, 200, 5, Color.WHITE.getRGB(), false); context.drawText(textRenderer, "Revision: " + mc.player.currentScreenHandler.getRevision(), 200, 35, Color.WHITE.getRGB(), false); } // bro are you ever going to clean this up? // this code is very messy, ill clean it up if you dont // -- MrBreakNFix public static void createWidgets(MinecraftClient mc, Screen screen) { // register "close without packet" button in all HandledScreens screen.addDrawableChild(ButtonWidget.builder(Text.of("Close without packet"), (button) -> { // closes the current gui without sending a packet to the current server mc.setScreen(null); }).width(115).position(5, 5).build()); // register "de-sync" button in all HandledScreens screen.addDrawableChild(ButtonWidget.builder(Text.of("De-sync"), (button) -> { // keeps the current gui open client-side and closed server-side if (mc.getNetworkHandler() != null && mc.player != null) { mc.getNetworkHandler().sendPacket(new CloseHandledScreenC2SPacket(mc.player.currentScreenHandler.syncId)); } else { LOGGER.warn("Minecraft network handler or player was null while using 'De-sync' in UI Utils."); } }).width(115).position(5, 35).build()); // register "send packets" button in all HandledScreens screen.addDrawableChild(ButtonWidget.builder(Text.of("Send packets: " + SharedVariables.sendUIPackets), (button) -> { // tells the client if it should send any gui related packets SharedVariables.sendUIPackets = !SharedVariables.sendUIPackets; button.setMessage(Text.of("Send packets: " + SharedVariables.sendUIPackets)); }).width(115).position(5, 65).build()); // register "delay packets" button in all HandledScreens screen.addDrawableChild(ButtonWidget.builder(Text.of("Delay packets: " + SharedVariables.delayUIPackets), (button) -> { // toggles a setting to delay all gui related packets to be used later when turning this setting off SharedVariables.delayUIPackets = !SharedVariables.delayUIPackets; button.setMessage(Text.of("Delay packets: " + SharedVariables.delayUIPackets)); if (!SharedVariables.delayUIPackets && !SharedVariables.delayedUIPackets.isEmpty() && mc.getNetworkHandler() != null) { for (Packet<?> packet : SharedVariables.delayedUIPackets) { mc.getNetworkHandler().sendPacket(packet); } if (mc.player != null) { mc.player.sendMessage(Text.of("Sent " + SharedVariables.delayedUIPackets.size() + " packets."), false); } SharedVariables.delayedUIPackets.clear(); } }).width(115).position(5, 95).build()); // register "save gui" button in all HandledScreens screen.addDrawableChild(ButtonWidget.builder(Text.of("Save GUI"), (button) -> { // saves the current gui to a variable to be accessed later if (mc.player != null) { SharedVariables.storedScreen = mc.currentScreen; SharedVariables.storedScreenHandler = mc.player.currentScreenHandler; } }).width(115).position(5, 125).build()); // register "disconnect and send packets" button in all HandledScreens screen.addDrawableChild(ButtonWidget.builder(Text.of("Disconnect and send packets"), (button) -> { // sends all "delayed" gui related packets before disconnecting, use: potential race conditions on non-vanilla servers SharedVariables.delayUIPackets = false; if (mc.getNetworkHandler() != null) { for (Packet<?> packet : SharedVariables.delayedUIPackets) { mc.getNetworkHandler().sendPacket(packet); } mc.getNetworkHandler().getConnection().disconnect(Text.of("Disconnecting (UI-UTILS)")); } else { LOGGER.warn("Minecraft network handler (mc.getNetworkHandler()) is null while client is disconnecting."); } SharedVariables.delayedUIPackets.clear(); }).width(160).position(5, 155).build()); // register "fabricate packet" button in all HandledScreens ButtonWidget fabricatePacketButton = ButtonWidget.builder(Text.of("Fabricate packet"), (button) -> { // creates a gui allowing you to fabricate packets JFrame frame = new JFrame("Choose Packet"); frame.setBounds(0, 0, 450, 100); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setLayout(null); JButton clickSlotButton = getPacketOptionButton("Click Slot"); clickSlotButton.setBounds(100, 25, 110, 20); clickSlotButton.addActionListener((event) -> { // im too lazy to comment everything here just read the code yourself frame.setVisible(false); JFrame clickSlotFrame = new JFrame("Click Slot Packet"); clickSlotFrame.setBounds(0, 0, 450, 300); clickSlotFrame.setResizable(false); clickSlotFrame.setLocationRelativeTo(null); clickSlotFrame.setLayout(null); JLabel syncIdLabel = new JLabel("Sync Id:"); syncIdLabel.setFocusable(false); syncIdLabel.setFont(monospace); syncIdLabel.setBounds(25, 25, 100, 20); JLabel revisionLabel = new JLabel("Revision:"); revisionLabel.setFocusable(false); revisionLabel.setFont(monospace); revisionLabel.setBounds(25, 50, 100, 20); JLabel slotLabel = new JLabel("Slot:"); slotLabel.setFocusable(false); slotLabel.setFont(monospace); slotLabel.setBounds(25, 75, 100, 20); JLabel buttonLabel = new JLabel("Button:"); buttonLabel.setFocusable(false); buttonLabel.setFont(monospace); buttonLabel.setBounds(25, 100, 100, 20); JLabel actionLabel = new JLabel("Action:"); actionLabel.setFocusable(false); actionLabel.setFont(monospace); actionLabel.setBounds(25, 125, 100, 20); JLabel timesToSendLabel = new JLabel("Times to send:"); timesToSendLabel.setFocusable(false); timesToSendLabel.setFont(monospace); timesToSendLabel.setBounds(25, 190, 100, 20); JTextField syncIdField = new JTextField(1); syncIdField.setFont(monospace); syncIdField.setBounds(125, 25, 100, 20); JTextField revisionField = new JTextField(1); revisionField.setFont(monospace); revisionField.setBounds(125, 50, 100, 20); JTextField slotField = new JTextField(1); slotField.setFont(monospace); slotField.setBounds(125, 75, 100, 20); JTextField buttonField = new JTextField(1); buttonField.setFont(monospace); buttonField.setBounds(125, 100, 100, 20); JComboBox<String> actionField = new JComboBox<>(new Vector<>(ImmutableList.of( "PICKUP", "QUICK_MOVE", "SWAP", "CLONE", "THROW", "QUICK_CRAFT", "PICKUP_ALL" ))); actionField.setFocusable(false); actionField.setEditable(false); actionField.setBorder(BorderFactory.createEmptyBorder()); actionField.setBackground(darkWhite); actionField.setFont(monospace); actionField.setBounds(125, 125, 100, 20); JLabel statusLabel = new JLabel(); statusLabel.setVisible(false); statusLabel.setFocusable(false); statusLabel.setFont(monospace); statusLabel.setBounds(210, 150, 190, 20); JCheckBox delayBox = new JCheckBox("Delay"); delayBox.setBounds(115, 150, 85, 20); delayBox.setSelected(false); delayBox.setFont(monospace); delayBox.setFocusable(false); JTextField timesToSendField = new JTextField("1"); timesToSendField.setFont(monospace); timesToSendField.setBounds(125, 190, 100, 20); JButton sendButton = new JButton("Send"); sendButton.setFocusable(false); sendButton.setBounds(25, 150, 75, 20); sendButton.setBorder(BorderFactory.createEtchedBorder()); sendButton.setBackground(darkWhite); sendButton.setFont(monospace); sendButton.addActionListener((event0) -> { if ( MainClient.isInteger(syncIdField.getText()) && MainClient.isInteger(revisionField.getText()) && MainClient.isInteger(slotField.getText()) && MainClient.isInteger(buttonField.getText()) && MainClient.isInteger(timesToSendField.getText()) && actionField.getSelectedItem() != null) { int syncId = Integer.parseInt(syncIdField.getText()); int revision = Integer.parseInt(revisionField.getText()); short slot = Short.parseShort(slotField.getText()); byte button0 = Byte.parseByte(buttonField.getText()); SlotActionType action = MainClient.stringToSlotActionType(actionField.getSelectedItem().toString()); int timesToSend = Integer.parseInt(timesToSendField.getText()); if (action != null) { ClickSlotC2SPacket packet = new ClickSlotC2SPacket(syncId, revision, slot, button0, action, new Int2ObjectArrayMap<>(), ItemStackHash.EMPTY); try { Runnable toRun = getFabricatePacketRunnable(mc, delayBox.isSelected(), packet); for (int i = 0; i < timesToSend; i++) { toRun.run(); } } catch (Exception e) { statusLabel.setForeground(Color.RED.darker()); statusLabel.setText("You must be connected to a server!"); MainClient.queueTask(() -> { statusLabel.setVisible(false); statusLabel.setText(""); }, 1500L); return; } statusLabel.setVisible(true); statusLabel.setForeground(Color.GREEN.darker()); statusLabel.setText("Sent successfully!"); MainClient.queueTask(() -> { statusLabel.setVisible(false); statusLabel.setText(""); }, 1500L); } else { statusLabel.setVisible(true); statusLabel.setForeground(Color.RED.darker()); statusLabel.setText("Invalid arguments!"); MainClient.queueTask(() -> { statusLabel.setVisible(false); statusLabel.setText(""); }, 1500L); } } else { statusLabel.setVisible(true); statusLabel.setForeground(Color.RED.darker()); statusLabel.setText("Invalid arguments!"); MainClient.queueTask(() -> { statusLabel.setVisible(false); statusLabel.setText(""); }, 1500L); } }); clickSlotFrame.add(syncIdLabel); clickSlotFrame.add(revisionLabel); clickSlotFrame.add(slotLabel); clickSlotFrame.add(buttonLabel); clickSlotFrame.add(actionLabel); clickSlotFrame.add(timesToSendLabel); clickSlotFrame.add(syncIdField); clickSlotFrame.add(revisionField); clickSlotFrame.add(slotField); clickSlotFrame.add(buttonField); clickSlotFrame.add(actionField); clickSlotFrame.add(sendButton); clickSlotFrame.add(statusLabel); clickSlotFrame.add(delayBox); clickSlotFrame.add(timesToSendField); clickSlotFrame.setVisible(true); }); JButton buttonClickButton = getPacketOptionButton("Button Click"); buttonClickButton.setBounds(250, 25, 110, 20); buttonClickButton.addActionListener((event) -> { frame.setVisible(false); JFrame buttonClickFrame = new JFrame("Button Click Packet"); buttonClickFrame.setBounds(0, 0, 450, 250); buttonClickFrame.setResizable(false); buttonClickFrame.setLocationRelativeTo(null); buttonClickFrame.setLayout(null); JLabel syncIdLabel = new JLabel("Sync Id:"); syncIdLabel.setFocusable(false); syncIdLabel.setFont(monospace); syncIdLabel.setBounds(25, 25, 100, 20); JLabel buttonIdLabel = new JLabel("Button Id:"); buttonIdLabel.setFocusable(false); buttonIdLabel.setFont(monospace); buttonIdLabel.setBounds(25, 50, 100, 20); JTextField syncIdField = new JTextField(1); syncIdField.setFont(monospace); syncIdField.setBounds(125, 25, 100, 20); JTextField buttonIdField = new JTextField(1); buttonIdField.setFont(monospace); buttonIdField.setBounds(125, 50, 100, 20); JLabel statusLabel = new JLabel(); statusLabel.setVisible(false); statusLabel.setFocusable(false); statusLabel.setFont(monospace); statusLabel.setBounds(210, 95, 190, 20); JCheckBox delayBox = new JCheckBox("Delay"); delayBox.setBounds(115, 95, 85, 20); delayBox.setSelected(false); delayBox.setFont(monospace); delayBox.setFocusable(false); JLabel timesToSendLabel = new JLabel("Times to send:"); timesToSendLabel.setFocusable(false); timesToSendLabel.setFont(monospace); timesToSendLabel.setBounds(25, 130, 100, 20); JTextField timesToSendField = new JTextField("1"); timesToSendField.setFont(monospace); timesToSendField.setBounds(125, 130, 100, 20); JButton sendButton = new JButton("Send"); sendButton.setFocusable(false); sendButton.setBounds(25, 95, 75, 20); sendButton.setBorder(BorderFactory.createEtchedBorder()); sendButton.setBackground(darkWhite); sendButton.setFont(monospace); sendButton.addActionListener((event0) -> { if ( MainClient.isInteger(syncIdField.getText()) && MainClient.isInteger(buttonIdField.getText()) && MainClient.isInteger(timesToSendField.getText())) { int syncId = Integer.parseInt(syncIdField.getText()); int buttonId = Integer.parseInt(buttonIdField.getText()); int timesToSend = Integer.parseInt(timesToSendField.getText()); ButtonClickC2SPacket packet = new ButtonClickC2SPacket(syncId, buttonId); try { Runnable toRun = getFabricatePacketRunnable(mc, delayBox.isSelected(), packet); for (int i = 0; i < timesToSend; i++) { toRun.run(); } } catch (Exception e) { statusLabel.setVisible(true); statusLabel.setForeground(Color.RED.darker()); statusLabel.setText("You must be connected to a server!"); MainClient.queueTask(() -> { statusLabel.setVisible(false); statusLabel.setText(""); }, 1500L); return; } statusLabel.setVisible(true); statusLabel.setForeground(Color.GREEN.darker()); statusLabel.setText("Sent successfully!"); MainClient.queueTask(() -> { statusLabel.setVisible(false); statusLabel.setText(""); }, 1500L); } else { statusLabel.setVisible(true); statusLabel.setForeground(Color.RED.darker()); statusLabel.setText("Invalid arguments!"); MainClient.queueTask(() -> { statusLabel.setVisible(false); statusLabel.setText(""); }, 1500L); } }); buttonClickFrame.add(syncIdLabel); buttonClickFrame.add(buttonIdLabel); buttonClickFrame.add(syncIdField); buttonClickFrame.add(timesToSendLabel); buttonClickFrame.add(buttonIdField); buttonClickFrame.add(sendButton); buttonClickFrame.add(statusLabel); buttonClickFrame.add(delayBox); buttonClickFrame.add(timesToSendField); buttonClickFrame.setVisible(true); }); frame.add(clickSlotButton); frame.add(buttonClickButton); frame.setVisible(true); }).width(115).position(5, 185).build(); fabricatePacketButton.active = !MinecraftClient.IS_SYSTEM_MAC; screen.addDrawableChild(fabricatePacketButton); screen.addDrawableChild(ButtonWidget.builder(Text.of("Copy GUI Title JSON"), (button) -> { try { if (mc.currentScreen == null) { throw new IllegalStateException("The current minecraft screen (mc.currentScreen) is null"); } // fixes #137 // From fabric wiki https://docs.fabricmc.net/develop/text-and-translations#serializing-text mc.keyboard.setClipboard(new Gson().toJson(TextCodecs.CODEC.encodeStart(JsonOps.INSTANCE, mc.currentScreen.getTitle()).getOrThrow())); } catch (IllegalStateException e) { LOGGER.error("Error while copying title JSON to clipboard", e); } }).width(115).position(5, 215).build()); } @NotNull private static JButton getPacketOptionButton(String label) { JButton button = new JButton(label); button.setFocusable(false); button.setBorder(BorderFactory.createEtchedBorder()); button.setBackground(darkWhite); button.setFont(monospace); return button; } @NotNull private static Runnable getFabricatePacketRunnable(MinecraftClient mc, boolean delay, Packet<?> packet) { Runnable toRun; if (delay) { toRun = () -> { if (mc.getNetworkHandler() != null) { mc.getNetworkHandler().sendPacket(packet); } else { LOGGER.warn("Minecraft network handler (mc.getNetworkHandler()) is null while sending fabricated packets."); } }; } else { toRun = () -> { if (mc.getNetworkHandler() != null) { mc.getNetworkHandler().sendPacket(packet); } else { LOGGER.warn("Minecraft network handler (mc.getNetworkHandler()) is null while sending fabricated packets."); } ((ClientConnectionAccessor) mc.getNetworkHandler().getConnection()).getChannel().writeAndFlush(packet); }; } return toRun; } public static boolean isInteger(String string) { try { Integer.parseInt(string); return true; } catch (Exception e) { return false; } } public static SlotActionType stringToSlotActionType(String string) { // converts a string to SlotActionType return switch (string) { case "PICKUP" -> SlotActionType.PICKUP; case "QUICK_MOVE" -> SlotActionType.QUICK_MOVE; case "SWAP" -> SlotActionType.SWAP; case "CLONE" -> SlotActionType.CLONE; case "THROW" -> SlotActionType.THROW; case "QUICK_CRAFT" -> SlotActionType.QUICK_CRAFT; case "PICKUP_ALL" -> SlotActionType.PICKUP_ALL; default -> null; }; } public static void queueTask(Runnable runnable, long delayMs) { // queues a task for minecraft to run Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { MinecraftClient.getInstance().send(runnable); } }; timer.schedule(task, delayMs); } public static String getModVersion(String modId) { ModMetadata modMetadata = FabricLoader.getInstance().getModContainer(modId).isPresent() ? FabricLoader.getInstance().getModContainer(modId).get().getMetadata() : null; return modMetadata != null ? modMetadata.getVersion().getFriendlyString() : "null"; } }
0
0.926182
1
0.926182
game-dev
MEDIA
0.951725
game-dev
0.9489
1
0.9489
deeeity/mercury-lib
2,368
use-this-to-test.lua
local Library = loadstring(game:HttpGet("https://raw.githubusercontent.com/deeeity/mercury-lib/master/src.lua"))() local gui = Library:create{ Theme = Library.Themes.Serika } local tab = gui:tab{ Icon = "rbxassetid://6034996695", Name = "Aimbot" } tab:button({ Name = "show prompt", Callback = function() tab:prompt{ Title = "baby", Text = "shark doo doo doo doo im blank lmao", Buttons = { Ok = function() tab:prompt{ Followup = true, Title = "really?", Text = "you sure?=", Buttons = { Yes = function() tab:prompt{ Followup = true, Title = "xd", Text = "sus", Buttons = { balls = function() gui:set_status("github") end, anal = function() gui:set_Status("money") end } } end, } } end, } } end, }) tab:keybind({Callback = function() gui:prompt() end,}) tab:dropdown({ Name = "Dropdown", Description = "yeeeeeeeeeeeeeeeeeeeboi", StartingText = "Bodypart", Items = { "Head", "Torso", "Random" } }) tab:dropdown({ Name = "yes", StartingText = "Number", Items = { {"One", 1}, {"Two", 2}, {"Three", 3} }, Description = "amongu s", Callback = function(v) print(v, "clicked") end, }) local cum = tab:slider({Callback = function(v) gui:set_status(v) end}) tab:textbox({Callback = function(v) gui:prompt{Text = v} end,}) tab:color_picker({ Name = "your mom's color", Style = Library.ColorPickerStyles.Legacy, Description = "Click to adjust color...", Callback = function(color) print(color) end, })
0
0.606731
1
0.606731
game-dev
MEDIA
0.722946
game-dev
0.842011
1
0.842011
526077247/TaoTie
3,803
Modules/com.tuyoogame.yooasset/Samples~/UniTask Sample/UniTask/Runtime/Linq/All.cs
using Cysharp.Threading.Tasks.Internal; using System; using System.Threading; namespace Cysharp.Threading.Tasks.Linq { public static partial class UniTaskAsyncEnumerable { public static UniTask<Boolean> AllAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, Boolean> predicate, CancellationToken cancellationToken = default) { Error.ThrowArgumentNullException(source, nameof(source)); Error.ThrowArgumentNullException(predicate, nameof(predicate)); return All.AllAsync(source, predicate, cancellationToken); } public static UniTask<Boolean> AllAwaitAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<Boolean>> predicate, CancellationToken cancellationToken = default) { Error.ThrowArgumentNullException(source, nameof(source)); Error.ThrowArgumentNullException(predicate, nameof(predicate)); return All.AllAwaitAsync(source, predicate, cancellationToken); } public static UniTask<Boolean> AllAwaitWithCancellationAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<Boolean>> predicate, CancellationToken cancellationToken = default) { Error.ThrowArgumentNullException(source, nameof(source)); Error.ThrowArgumentNullException(predicate, nameof(predicate)); return All.AllAwaitWithCancellationAsync(source, predicate, cancellationToken); } } internal static class All { internal static async UniTask<bool> AllAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, Boolean> predicate, CancellationToken cancellationToken) { var e = source.GetAsyncEnumerator(cancellationToken); try { while (await e.MoveNextAsync()) { if (!predicate(e.Current)) { return false; } } return true; } finally { if (e != null) { await e.DisposeAsync(); } } } internal static async UniTask<bool> AllAwaitAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, UniTask<Boolean>> predicate, CancellationToken cancellationToken) { var e = source.GetAsyncEnumerator(cancellationToken); try { while (await e.MoveNextAsync()) { if (!await predicate(e.Current)) { return false; } } return true; } finally { if (e != null) { await e.DisposeAsync(); } } } internal static async UniTask<bool> AllAwaitWithCancellationAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, UniTask<Boolean>> predicate, CancellationToken cancellationToken) { var e = source.GetAsyncEnumerator(cancellationToken); try { while (await e.MoveNextAsync()) { if (!await predicate(e.Current, cancellationToken)) { return false; } } return true; } finally { if (e != null) { await e.DisposeAsync(); } } } } }
0
0.86485
1
0.86485
game-dev
MEDIA
0.802858
game-dev
0.524058
1
0.524058
SteamDatabase/GameTracking-Dota2
3,926
game/dota_addons/npx_2019/scripts/vscripts/ai/lockdown_single_target/bane.lua
local BANE_BOT_STATE_IDLE = 0 local BANE_BOT_STATE_AGGRO = 1 local BANE_BOT_STATE_REMOVAL = 2 -------------------------------------------------------------------------------- if CLockdownScenarioBaneBot == nil then CLockdownScenarioBaneBot = class({}) end -------------------------------------------------------------------------------- function CLockdownScenarioBaneBot:constructor( me ) self.me = me self.nBotState = BANE_BOT_STATE_IDLE self.hBrainSapAbility = self.me:FindAbilityByName( "bane_brain_sap" ) self.hFiendsGripAbility = self.me:FindAbilityByName( "bane_fiends_grip" ) self.hEscapeLoc = Entities:FindByName( nil, "escape_location" ) ScriptAssert( self.hEscapeLoc ~= nil, "self.hEscapeLoc is nil!" ) end -------------------------------------------------------------------------------- function CLockdownScenarioBaneBot:ChangeBotState( nNewState ) self.nBotState = nNewState end -------------------------------------------------------------------------------- function CLockdownScenarioBaneBot:BotThink() if not IsServer() then return end if self.bWasKilled then return -1 end if ( not self.me:IsAlive() ) then self.bWasKilled = true return -1 end if GameRules:IsGamePaused() == true then return 0.5 end if self.me:IsChanneling() then printf( "Bane is busy channeling, return to think shortly" ) return 0.25 end if self.nBotState == BANE_BOT_STATE_IDLE then local nSearchRange = 700 local Heroes = FindUnitsInRadius( DOTA_TEAM_BADGUYS, self.me:GetOrigin(), self.me, nSearchRange, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS + DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE, 0, false ) if #Heroes > 0 then self:ChangeBotState( BANE_BOT_STATE_AGGRO ) end elseif self.nBotState == BANE_BOT_STATE_AGGRO then if GameRules.DotaNPX:IsTaskComplete( "protect_lina" ) then self.nBotState = BANE_BOT_STATE_REMOVAL return 1.0 end local nSearchRange = 1000 local Heroes = FindUnitsInRadius( DOTA_TEAM_BADGUYS, self.me:GetOrigin(), self.me, nSearchRange, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS + DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE, 0, false ) if #Heroes > 0 then -- Find lowest health enemy local hLowestHealthEnemy = nil for _, hHero in pairs( Heroes ) do if hLowestHealthEnemy == nil or hHero:GetHealthPercent() < hLowestHealthEnemy:GetHealthPercent() then hLowestHealthEnemy = hHero end end if self.hFiendsGripAbility and self.hFiendsGripAbility:IsFullyCastable() then self.me:CastAbilityOnTarget( hLowestHealthEnemy, self.hFiendsGripAbility, -1 ) return self.hFiendsGripAbility:GetCastPoint() + 0.3 elseif self.hBrainSapAbility and self.hBrainSapAbility:IsFullyCastable() then self.me:CastAbilityOnTarget( hLowestHealthEnemy, self.hBrainSapAbility, -1 ) return self.hBrainSapAbility:GetCastPoint() + 0.2 end end elseif self.nBotState == BANE_BOT_STATE_REMOVAL then UTIL_Remove( self.me ) return nil --[[ ExecuteOrderFromTable({ UnitIndex = self.me:entindex(), OrderType = DOTA_UNIT_ORDER_STOP }) ExecuteOrderFromTable( { UnitIndex = self.me:entindex(), OrderType = DOTA_UNIT_ORDER_MOVE_TO_POSITION, Position = self.hEscapeLoc:GetAbsOrigin(), Queue = true, } ) ]] end return 0.5 end -------------------------------------------------------------------------------- function Spawn( entityKeyValues ) if IsServer() then thisEntity:SetContextThink( "LockdownScenarioBaneThink", LockdownScenarioBaneThink, 0.25 ) thisEntity.Bot = CLockdownScenarioBaneBot( thisEntity ) end end -------------------------------------------------------------------------------- function LockdownScenarioBaneThink() if IsServer() == false then return -1 end return thisEntity.Bot:BotThink() end --------------------------------------------------------------------------------
0
0.936766
1
0.936766
game-dev
MEDIA
0.972384
game-dev
0.984031
1
0.984031
NebulaSS13/Nebula
1,479
code/modules/crafting/forging/bellows.dm
/obj/structure/working/bellows name = "bellows" desc = "An air pump used to improve the heat of a furnace." icon = 'icons/obj/structures/forging/bellows.dmi' obj_flags = OBJ_FLAG_ANCHORABLE | OBJ_FLAG_ROTATABLE work_skill = SKILL_HAULING var/decl/material/bellows_material = /decl/material/solid/organic/leather /obj/structure/working/bellows/Initialize() bellows_material = GET_DECL(bellows_material) . = ..() /obj/structure/working/bellows/on_update_icon() . = ..() underlays = list(overlay_image(icon, "[icon_state]-bellows", bellows_material.color, RESET_COLOR)) /obj/structure/working/bellows/try_start_working(mob/user) var/obj/structure/fire_source/stoking = locate() in get_step(loc, EAST) if(!istype(stoking) || !stoking.lit) to_chat(user, SPAN_WARNING("\The [src] must face east towards a lit fire source; it would be pointless to work them currently.")) return TRUE to_chat(user, SPAN_NOTICE("You begin working \the [src], stoking \the [stoking] to a hotter flame.")) start_working() while(user.do_skilled(3 SECONDS, work_skill, src)) if(QDELETED(src) || QDELETED(user) || user.get_stamina() < 25 || !user.get_empty_hand_slot()) break stoking = locate() in get_step(loc, EAST) if(!istype(stoking) || !stoking.lit) break user.adjust_stamina(-25) stoking.bellows_oxygenation = max(50, stoking.bellows_oxygenation+3) if(!QDELETED(user)) to_chat(user, SPAN_NOTICE("You stop working \the [src].")) stop_working() return TRUE
0
0.987007
1
0.987007
game-dev
MEDIA
0.483207
game-dev
0.844936
1
0.844936
eliemichel/OpenMfxForBlender
9,492
extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btSimpleBroadphase.h" #include "BulletCollision/BroadphaseCollision/btDispatcher.h" #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "LinearMath/btVector3.h" #include "LinearMath/btTransform.h" #include "LinearMath/btMatrix3x3.h" #include "LinearMath/btAabbUtil2.h" #include <new> void btSimpleBroadphase::validate() { for (int i = 0; i < m_numHandles; i++) { for (int j = i + 1; j < m_numHandles; j++) { btAssert(&m_pHandles[i] != &m_pHandles[j]); } } } btSimpleBroadphase::btSimpleBroadphase(int maxProxies, btOverlappingPairCache* overlappingPairCache) : m_pairCache(overlappingPairCache), m_ownsPairCache(false), m_invalidPair(0) { if (!overlappingPairCache) { void* mem = btAlignedAlloc(sizeof(btHashedOverlappingPairCache), 16); m_pairCache = new (mem) btHashedOverlappingPairCache(); m_ownsPairCache = true; } // allocate handles buffer and put all handles on free list m_pHandlesRawPtr = btAlignedAlloc(sizeof(btSimpleBroadphaseProxy) * maxProxies, 16); m_pHandles = new (m_pHandlesRawPtr) btSimpleBroadphaseProxy[maxProxies]; m_maxHandles = maxProxies; m_numHandles = 0; m_firstFreeHandle = 0; m_LastHandleIndex = -1; { for (int i = m_firstFreeHandle; i < maxProxies; i++) { m_pHandles[i].SetNextFree(i + 1); m_pHandles[i].m_uniqueId = i + 2; //any UID will do, we just avoid too trivial values (0,1) for debugging purposes } m_pHandles[maxProxies - 1].SetNextFree(0); } } btSimpleBroadphase::~btSimpleBroadphase() { btAlignedFree(m_pHandlesRawPtr); if (m_ownsPairCache) { m_pairCache->~btOverlappingPairCache(); btAlignedFree(m_pairCache); } } btBroadphaseProxy* btSimpleBroadphase::createProxy(const btVector3& aabbMin, const btVector3& aabbMax, int shapeType, void* userPtr, int collisionFilterGroup, int collisionFilterMask, btDispatcher* /*dispatcher*/) { if (m_numHandles >= m_maxHandles) { btAssert(0); return 0; //should never happen, but don't let the game crash ;-) } btAssert(aabbMin[0] <= aabbMax[0] && aabbMin[1] <= aabbMax[1] && aabbMin[2] <= aabbMax[2]); int newHandleIndex = allocHandle(); btSimpleBroadphaseProxy* proxy = new (&m_pHandles[newHandleIndex]) btSimpleBroadphaseProxy(aabbMin, aabbMax, shapeType, userPtr, collisionFilterGroup, collisionFilterMask); return proxy; } class RemovingOverlapCallback : public btOverlapCallback { protected: virtual bool processOverlap(btBroadphasePair& pair) { (void)pair; btAssert(0); return false; } }; class RemovePairContainingProxy { btBroadphaseProxy* m_targetProxy; public: virtual ~RemovePairContainingProxy() { } protected: virtual bool processOverlap(btBroadphasePair& pair) { btSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy0); btSimpleBroadphaseProxy* proxy1 = static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy1); return ((m_targetProxy == proxy0 || m_targetProxy == proxy1)); }; }; void btSimpleBroadphase::destroyProxy(btBroadphaseProxy* proxyOrg, btDispatcher* dispatcher) { m_pairCache->removeOverlappingPairsContainingProxy(proxyOrg, dispatcher); btSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(proxyOrg); freeHandle(proxy0); //validate(); } void btSimpleBroadphase::getAabb(btBroadphaseProxy* proxy, btVector3& aabbMin, btVector3& aabbMax) const { const btSimpleBroadphaseProxy* sbp = getSimpleProxyFromProxy(proxy); aabbMin = sbp->m_aabbMin; aabbMax = sbp->m_aabbMax; } void btSimpleBroadphase::setAabb(btBroadphaseProxy* proxy, const btVector3& aabbMin, const btVector3& aabbMax, btDispatcher* /*dispatcher*/) { btSimpleBroadphaseProxy* sbp = getSimpleProxyFromProxy(proxy); sbp->m_aabbMin = aabbMin; sbp->m_aabbMax = aabbMax; } void btSimpleBroadphase::rayTest(const btVector3& rayFrom, const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin, const btVector3& aabbMax) { for (int i = 0; i <= m_LastHandleIndex; i++) { btSimpleBroadphaseProxy* proxy = &m_pHandles[i]; if (!proxy->m_clientObject) { continue; } rayCallback.process(proxy); } } void btSimpleBroadphase::aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback) { for (int i = 0; i <= m_LastHandleIndex; i++) { btSimpleBroadphaseProxy* proxy = &m_pHandles[i]; if (!proxy->m_clientObject) { continue; } if (TestAabbAgainstAabb2(aabbMin, aabbMax, proxy->m_aabbMin, proxy->m_aabbMax)) { callback.process(proxy); } } } bool btSimpleBroadphase::aabbOverlap(btSimpleBroadphaseProxy* proxy0, btSimpleBroadphaseProxy* proxy1) { return proxy0->m_aabbMin[0] <= proxy1->m_aabbMax[0] && proxy1->m_aabbMin[0] <= proxy0->m_aabbMax[0] && proxy0->m_aabbMin[1] <= proxy1->m_aabbMax[1] && proxy1->m_aabbMin[1] <= proxy0->m_aabbMax[1] && proxy0->m_aabbMin[2] <= proxy1->m_aabbMax[2] && proxy1->m_aabbMin[2] <= proxy0->m_aabbMax[2]; } //then remove non-overlapping ones class CheckOverlapCallback : public btOverlapCallback { public: virtual bool processOverlap(btBroadphasePair& pair) { return (!btSimpleBroadphase::aabbOverlap(static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy0), static_cast<btSimpleBroadphaseProxy*>(pair.m_pProxy1))); } }; void btSimpleBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher) { //first check for new overlapping pairs int i, j; if (m_numHandles >= 0) { int new_largest_index = -1; for (i = 0; i <= m_LastHandleIndex; i++) { btSimpleBroadphaseProxy* proxy0 = &m_pHandles[i]; if (!proxy0->m_clientObject) { continue; } new_largest_index = i; for (j = i + 1; j <= m_LastHandleIndex; j++) { btSimpleBroadphaseProxy* proxy1 = &m_pHandles[j]; btAssert(proxy0 != proxy1); if (!proxy1->m_clientObject) { continue; } btSimpleBroadphaseProxy* p0 = getSimpleProxyFromProxy(proxy0); btSimpleBroadphaseProxy* p1 = getSimpleProxyFromProxy(proxy1); if (aabbOverlap(p0, p1)) { if (!m_pairCache->findPair(proxy0, proxy1)) { m_pairCache->addOverlappingPair(proxy0, proxy1); } } else { if (!m_pairCache->hasDeferredRemoval()) { if (m_pairCache->findPair(proxy0, proxy1)) { m_pairCache->removeOverlappingPair(proxy0, proxy1, dispatcher); } } } } } m_LastHandleIndex = new_largest_index; if (m_ownsPairCache && m_pairCache->hasDeferredRemoval()) { btBroadphasePairArray& overlappingPairArray = m_pairCache->getOverlappingPairArray(); //perform a sort, to find duplicates and to sort 'invalid' pairs to the end overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); m_invalidPair = 0; btBroadphasePair previousPair; previousPair.m_pProxy0 = 0; previousPair.m_pProxy1 = 0; previousPair.m_algorithm = 0; for (i = 0; i < overlappingPairArray.size(); i++) { btBroadphasePair& pair = overlappingPairArray[i]; bool isDuplicate = (pair == previousPair); previousPair = pair; bool needsRemoval = false; if (!isDuplicate) { bool hasOverlap = testAabbOverlap(pair.m_pProxy0, pair.m_pProxy1); if (hasOverlap) { needsRemoval = false; //callback->processOverlap(pair); } else { needsRemoval = true; } } else { //remove duplicate needsRemoval = true; //should have no algorithm btAssert(!pair.m_algorithm); } if (needsRemoval) { m_pairCache->cleanOverlappingPair(pair, dispatcher); // m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1); // m_overlappingPairArray.pop_back(); pair.m_pProxy0 = 0; pair.m_pProxy1 = 0; m_invalidPair++; } } ///if you don't like to skip the invalid pairs in the array, execute following code: #define CLEAN_INVALID_PAIRS 1 #ifdef CLEAN_INVALID_PAIRS //perform a sort, to sort 'invalid' pairs to the end overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); m_invalidPair = 0; #endif //CLEAN_INVALID_PAIRS } } } bool btSimpleBroadphase::testAabbOverlap(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) { btSimpleBroadphaseProxy* p0 = getSimpleProxyFromProxy(proxy0); btSimpleBroadphaseProxy* p1 = getSimpleProxyFromProxy(proxy1); return aabbOverlap(p0, p1); } void btSimpleBroadphase::resetPool(btDispatcher* dispatcher) { //not yet }
0
0.949225
1
0.949225
game-dev
MEDIA
0.562116
game-dev
0.984954
1
0.984954
mekanism/Mekanism
16,507
src/main/java/mekanism/common/tile/machine/TileEntityRotaryCondensentrator.java
package mekanism.common.tile.machine; import java.util.List; import java.util.function.BooleanSupplier; import mekanism.api.AutomationType; import mekanism.api.IContentsListener; import mekanism.api.RelativeSide; import mekanism.api.SerializationConstants; import mekanism.api.Upgrade; import mekanism.api.chemical.BasicChemicalTank; import mekanism.api.chemical.ChemicalStack; import mekanism.api.chemical.IChemicalTank; import mekanism.api.chemical.attribute.ChemicalAttributeValidator; import mekanism.api.recipes.RotaryRecipe; import mekanism.api.recipes.cache.CachedRecipe; import mekanism.api.recipes.cache.CachedRecipe.OperationTracker.RecipeError; import mekanism.api.recipes.cache.RotaryCachedRecipe; import mekanism.api.recipes.inputs.IInputHandler; import mekanism.api.recipes.inputs.InputHelper; import mekanism.api.recipes.outputs.IOutputHandler; import mekanism.api.recipes.outputs.OutputHelper; import mekanism.api.recipes.vanilla_input.RotaryRecipeInput; import mekanism.common.attachments.containers.ContainerType; import mekanism.common.capabilities.energy.MachineEnergyContainer; import mekanism.common.capabilities.fluid.BasicFluidTank; import mekanism.common.capabilities.holder.chemical.ChemicalTankHelper; import mekanism.common.capabilities.holder.chemical.IChemicalTankHolder; import mekanism.common.capabilities.holder.energy.EnergyContainerHelper; import mekanism.common.capabilities.holder.energy.IEnergyContainerHolder; import mekanism.common.capabilities.holder.fluid.FluidTankHelper; import mekanism.common.capabilities.holder.fluid.IFluidTankHolder; import mekanism.common.capabilities.holder.slot.IInventorySlotHolder; import mekanism.common.capabilities.holder.slot.InventorySlotHelper; import mekanism.common.integration.computer.ComputerException; import mekanism.common.integration.computer.SpecialComputerMethodWrapper.ComputerChemicalTankWrapper; import mekanism.common.integration.computer.SpecialComputerMethodWrapper.ComputerFluidTankWrapper; import mekanism.common.integration.computer.SpecialComputerMethodWrapper.ComputerIInventorySlotWrapper; import mekanism.common.integration.computer.annotation.ComputerMethod; import mekanism.common.integration.computer.annotation.WrappingComputerMethod; import mekanism.common.integration.computer.computercraft.ComputerConstants; import mekanism.common.inventory.container.MekanismContainer; import mekanism.common.inventory.container.slot.ContainerSlotType; import mekanism.common.inventory.container.slot.SlotOverlay; import mekanism.common.inventory.container.sync.SyncableBoolean; import mekanism.common.inventory.container.sync.SyncableLong; import mekanism.common.inventory.slot.EnergyInventorySlot; import mekanism.common.inventory.slot.FluidInventorySlot; import mekanism.common.inventory.slot.OutputInventorySlot; import mekanism.common.inventory.slot.chemical.ChemicalInventorySlot; import mekanism.common.lib.transmitter.TransmissionType; import mekanism.common.recipe.IMekanismRecipeTypeProvider; import mekanism.common.recipe.MekanismRecipeType; import mekanism.common.recipe.lookup.cache.RotaryInputRecipeCache; import mekanism.common.registries.MekanismBlocks; import mekanism.common.registries.MekanismDataComponents; import mekanism.common.tile.component.TileComponentEjector; import mekanism.common.tile.interfaces.IHasMode; import mekanism.common.tile.prefab.TileEntityRecipeMachine; import mekanism.common.util.MekanismUtils; import mekanism.common.util.NBTUtils; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; import net.minecraft.core.component.DataComponentMap; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.neoforged.neoforge.fluids.FluidStack; import net.neoforged.neoforge.fluids.FluidType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class TileEntityRotaryCondensentrator extends TileEntityRecipeMachine<RotaryRecipe> implements IHasMode { public static final RecipeError NOT_ENOUGH_FLUID_INPUT_ERROR = RecipeError.create(); public static final RecipeError NOT_ENOUGH_GAS_INPUT_ERROR = RecipeError.create(); public static final RecipeError NOT_ENOUGH_SPACE_GAS_OUTPUT_ERROR = RecipeError.create(); public static final RecipeError NOT_ENOUGH_SPACE_FLUID_OUTPUT_ERROR = RecipeError.create(); private static final List<RecipeError> TRACKED_ERROR_TYPES = List.of( RecipeError.NOT_ENOUGH_ENERGY, RecipeError.NOT_ENOUGH_ENERGY_REDUCED_RATE, NOT_ENOUGH_FLUID_INPUT_ERROR, NOT_ENOUGH_GAS_INPUT_ERROR, NOT_ENOUGH_SPACE_GAS_OUTPUT_ERROR, NOT_ENOUGH_SPACE_FLUID_OUTPUT_ERROR, RecipeError.INPUT_DOESNT_PRODUCE_OUTPUT ); public static final int CAPACITY = 10 * FluidType.BUCKET_VOLUME; @WrappingComputerMethod(wrapper = ComputerChemicalTankWrapper.class, methodNames = {"getGas", "getGasCapacity", "getGasNeeded", "getGasFilledPercentage"}, docPlaceholder = "gas tank") public IChemicalTank gasTank; @WrappingComputerMethod(wrapper = ComputerFluidTankWrapper.class, methodNames = {"getFluid", "getFluidCapacity", "getFluidNeeded", "getFluidFilledPercentage"}, docPlaceholder = "fluid tank") public BasicFluidTank fluidTank; /** * True: fluid -> chemical * <p> * False: chemical -> fluid */ private boolean mode; private final IOutputHandler<@NotNull ChemicalStack> gasOutputHandler; private final IOutputHandler<@NotNull FluidStack> fluidOutputHandler; private final IInputHandler<@NotNull FluidStack> fluidInputHandler; private final IInputHandler<@NotNull ChemicalStack> gasInputHandler; private long clientEnergyUsed = 0; private int baselineMaxOperations = 1; private MachineEnergyContainer<TileEntityRotaryCondensentrator> energyContainer; @WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getGasItemInput", docPlaceholder = "gas item input slot") ChemicalInventorySlot gasInputSlot; @WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getGasItemOutput", docPlaceholder = "gas item output slot") ChemicalInventorySlot gasOutputSlot; @WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getFluidItemInput", docPlaceholder = "fluid item input slot") FluidInventorySlot fluidInputSlot; @WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getFluidItemOutput", docPlaceholder = "fluid item ouput slot") OutputInventorySlot fluidOutputSlot; @WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getEnergyItem", docPlaceholder = "energy slot") EnergyInventorySlot energySlot; public TileEntityRotaryCondensentrator(BlockPos pos, BlockState state) { super(MekanismBlocks.ROTARY_CONDENSENTRATOR, pos, state, TRACKED_ERROR_TYPES); configComponent.setupItemIOConfig(List.of(gasInputSlot, fluidInputSlot), List.of(gasOutputSlot, fluidOutputSlot), energySlot, true); configComponent.setupIOConfig(TransmissionType.CHEMICAL, gasTank, RelativeSide.LEFT, true); configComponent.setupIOConfig(TransmissionType.FLUID, fluidTank, RelativeSide.RIGHT, true); configComponent.setupInputConfig(TransmissionType.ENERGY, energyContainer); ejectorComponent = new TileComponentEjector(this); ejectorComponent.setOutputData(configComponent, TransmissionType.ITEM, TransmissionType.CHEMICAL, TransmissionType.FLUID) .setCanEject(transmissionType -> { if (transmissionType == TransmissionType.CHEMICAL) { return mode; } else if (transmissionType == TransmissionType.FLUID) { return !mode; } return true; }); gasInputHandler = InputHelper.getInputHandler(gasTank, NOT_ENOUGH_GAS_INPUT_ERROR); fluidInputHandler = InputHelper.getInputHandler(fluidTank, NOT_ENOUGH_FLUID_INPUT_ERROR); gasOutputHandler = OutputHelper.getOutputHandler(gasTank, NOT_ENOUGH_SPACE_GAS_OUTPUT_ERROR); fluidOutputHandler = OutputHelper.getOutputHandler(fluidTank, NOT_ENOUGH_SPACE_FLUID_OUTPUT_ERROR); } @NotNull @Override public IChemicalTankHolder getInitialChemicalTanks(IContentsListener listener, IContentsListener recipeCacheListener, IContentsListener recipeCacheUnpauseListener) { ChemicalTankHelper builder = ChemicalTankHelper.forSideWithConfig(this); //Only allow extraction builder.addTank(gasTank = BasicChemicalTank.createModern(CAPACITY, (gas, automationType) -> automationType == AutomationType.MANUAL || mode, (gas, automationType) -> automationType == AutomationType.INTERNAL || !mode, this::isValidGas, ChemicalAttributeValidator.ALWAYS_ALLOW, recipeCacheListener)); return builder.build(); } private boolean isValidGas(@NotNull ChemicalStack chemical) { return getRecipeType().getInputCache().containsInput(level, chemical); } @NotNull @Override protected IFluidTankHolder getInitialFluidTanks(IContentsListener listener, IContentsListener recipeCacheListener, IContentsListener recipeCacheUnpauseListener) { FluidTankHelper builder = FluidTankHelper.forSideWithConfig(this); builder.addTank(fluidTank = BasicFluidTank.create(CAPACITY, (fluid, automationType) -> automationType == AutomationType.MANUAL || !mode, (fluid, automationType) -> automationType == AutomationType.INTERNAL || mode, this::isValidFluid, recipeCacheListener)); return builder.build(); } private boolean isValidFluid(@NotNull FluidStack fluidStack) { return getRecipeType().getInputCache().containsInput(level, fluidStack); } @NotNull @Override protected IEnergyContainerHolder getInitialEnergyContainers(IContentsListener listener, IContentsListener recipeCacheListener, IContentsListener recipeCacheUnpauseListener) { EnergyContainerHelper builder = EnergyContainerHelper.forSideWithConfig(this); builder.addContainer(energyContainer = MachineEnergyContainer.input(this, recipeCacheUnpauseListener)); return builder.build(); } @NotNull @Override protected IInventorySlotHolder getInitialInventory(IContentsListener listener, IContentsListener recipeCacheListener, IContentsListener recipeCacheUnpauseListener) { InventorySlotHelper builder = InventorySlotHelper.forSideWithConfig(this); BooleanSupplier modeSupplier = this::getMode; builder.addSlot(gasInputSlot = ChemicalInventorySlot.rotaryDrain(gasTank, modeSupplier, listener, 5, 25)); builder.addSlot(gasOutputSlot = ChemicalInventorySlot.rotaryFill(gasTank, modeSupplier, listener, 5, 56)); builder.addSlot(fluidInputSlot = FluidInventorySlot.rotary(fluidTank, modeSupplier, listener, 155, 25)); builder.addSlot(fluidOutputSlot = OutputInventorySlot.at(listener, 155, 56)); builder.addSlot(energySlot = EnergyInventorySlot.fillOrConvert(energyContainer, this::getLevel, listener, 155, 5)); gasInputSlot.setSlotType(ContainerSlotType.INPUT); gasInputSlot.setSlotOverlay(SlotOverlay.PLUS); gasOutputSlot.setSlotType(ContainerSlotType.OUTPUT); gasOutputSlot.setSlotOverlay(SlotOverlay.MINUS); fluidInputSlot.setSlotType(ContainerSlotType.INPUT); return builder.build(); } @Override protected boolean onUpdateServer() { boolean sendUpdatePacket = super.onUpdateServer(); energySlot.fillContainerOrConvert(); if (mode) {//Fluid to Gas fluidInputSlot.fillTank(fluidOutputSlot); gasInputSlot.drainTank(); } else {//Gas to Fluid gasOutputSlot.fillTank(); fluidInputSlot.drainTank(fluidOutputSlot); } clientEnergyUsed = recipeCacheLookupMonitor.updateAndProcess(energyContainer); return sendUpdatePacket; } public boolean getMode() { return mode; } @Override public void nextMode() { mode = !mode; setChanged(); } @Override public void previousMode() { //We only have two modes just flip it nextMode(); } @ComputerMethod(nameOverride = "getEnergyUsage", methodDescription = ComputerConstants.DESCRIPTION_GET_ENERGY_USAGE) public long getEnergyUsed() { return clientEnergyUsed; } @Override public void readSustainedData(HolderLookup.Provider provider, @NotNull CompoundTag data) { super.readSustainedData(provider, data); NBTUtils.setBooleanIfPresent(data, SerializationConstants.MODE, value -> mode = value); } @Override public void writeSustainedData(HolderLookup.Provider provider, CompoundTag data) { super.writeSustainedData(provider, data); data.putBoolean(SerializationConstants.MODE, mode); } @Override protected void applyImplicitComponents(@NotNull BlockEntity.DataComponentInput input) { super.applyImplicitComponents(input); mode = input.getOrDefault(MekanismDataComponents.ROTARY_MODE, mode); } @Override protected void collectImplicitComponents(@NotNull DataComponentMap.Builder builder) { super.collectImplicitComponents(builder); builder.set(MekanismDataComponents.ROTARY_MODE, mode); } @Override public int getRedstoneLevel() { if (mode) { return MekanismUtils.redstoneLevelFromContents(fluidTank.getFluidAmount(), fluidTank.getCapacity()); } return MekanismUtils.redstoneLevelFromContents(gasTank.getStored(), gasTank.getCapacity()); } @Override protected boolean makesComparatorDirty(ContainerType<?, ?, ?> type) { return type == ContainerType.FLUID || type == ContainerType.CHEMICAL; } @NotNull @Override public IMekanismRecipeTypeProvider<RotaryRecipeInput, RotaryRecipe, RotaryInputRecipeCache> getRecipeType() { return MekanismRecipeType.ROTARY; } @Nullable @Override public RotaryRecipe getRecipe(int cacheIndex) { RotaryInputRecipeCache inputCache = getRecipeType().getInputCache(); return mode ? inputCache.findFirstRecipe(level, fluidInputHandler.getInput()) : inputCache.findFirstRecipe(level, gasInputHandler.getInput()); } public MachineEnergyContainer<TileEntityRotaryCondensentrator> getEnergyContainer() { return energyContainer; } @NotNull @Override public CachedRecipe<RotaryRecipe> createNewCachedRecipe(@NotNull RotaryRecipe recipe, int cacheIndex) { return new RotaryCachedRecipe(recipe, recheckAllRecipeErrors, fluidInputHandler, gasInputHandler, gasOutputHandler, fluidOutputHandler, this::getMode) .setErrorsChanged(this::onErrorsChanged) .setCanHolderFunction(this::canFunction) .setActive(this::setActive) .setEnergyRequirements(energyContainer::getEnergyPerTick, energyContainer) .setBaselineMaxOperations(() -> baselineMaxOperations) .setOnFinish(this::markForSave); } @Override public void recalculateUpgrades(Upgrade upgrade) { super.recalculateUpgrades(upgrade); if (upgrade == Upgrade.SPEED) { baselineMaxOperations = (int) Math.pow(2, upgradeComponent.getUpgrades(Upgrade.SPEED)); } } @Override public void addContainerTrackers(MekanismContainer container) { super.addContainerTrackers(container); container.track(SyncableBoolean.create(this::getMode, value -> mode = value)); container.track(SyncableLong.create(this::getEnergyUsed, value -> clientEnergyUsed = value)); } //Methods relating to IComputerTile @ComputerMethod boolean isCondensentrating() { return !mode; } @ComputerMethod(requiresPublicSecurity = true) void setCondensentrating(boolean value) throws ComputerException { validateSecurityIsPublic(); if (mode != value) { mode = value; setChanged(); } } //End methods IComputerTile }
0
0.896893
1
0.896893
game-dev
MEDIA
0.954538
game-dev
0.893149
1
0.893149
Return-To-The-Roots/s25client
1,588
libs/s25main/mapGenerator/Harbors.h
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org) // // SPDX-License-Identifier: GPL-2.0-or-later #pragma once #include "mapGenerator/Map.h" #include "mapGenerator/Rivers.h" namespace rttr::mapGenerator { /** * Places a harbor position on the map. * @param map reference to the map to place the harbor position on * @param position position for the harbor */ void PlaceHarborPosition(Map& map, const MapPoint& position); /** * Finds all connected nodes which are part of a coastline. A coast node must fulfill following three criteria: * 1) a coast node is surrounded by at least one land & one water texture * 2) a coast node is at least 5 edges away from the next river * 3) a coast node has a neighbor node which is fully surrounded by water * * @param map reference to the map to look up coastlines for * @param rivers all rivers already placed on the map */ std::vector<std::vector<MapPoint>> FindCoastlines(const Map& map, const std::vector<River>& rivers); /** * Places harbors on the specified map in suitable positions based on the given parameters. * * @param map reference to the map to add harbors positions to * @param rivers all rivers already placed on the map to avoid harbor positions for tiny rivers * @param coastSize minimum number of nodes a coastline requires to be considered for harbor positions * @param nodesPerHarbor number of coast nodes required per harbor position */ void PlaceHarbors(Map& map, const std::vector<River>& rivers, int coastSize = 32, int nodesPerHarbor = 64); } // namespace rttr::mapGenerator
0
0.855774
1
0.855774
game-dev
MEDIA
0.49181
game-dev
0.506389
1
0.506389
Razcoina/Bully-SE-scripts
54,923
scripts/secnd/4_G4.lua
ImportScript("Library/LibTagging.lua") ImportScript("Library/LibTable.lua") ImportScript("Library/LibObjective.lua") ImportScript("Library/LibPed.lua") local gBusTagCount = 0 local gSchoolTagCount = 0 local gTotalTags = 0 local gMissionTime = 300 local gBonusTime = 300 local missionPassed = false local tblSchoolTags = {} local tblBusinessTags = {} local tblAlgieTags = {} local tblPerverts = {} local idValidTagType, algie, mandy local bReachedPathEnd = false local currentTrig = 1 local bYelled = false local gPostersChanged = false local algieScrubbing = false local nMissionPhase = 0 local bCharactersCreated = false local gMandyBlip local gAlgieCutscenePlayed = false local gTblComicBookTag = {} local bDisabledSigns = false local timerStart, timerCurrent local timerElapsed = 0 local timerMax = 5000 local gStageUpdateFunction local gMissionStage = "running" local bCheckFailing = false local bTetherJimmyToTown = false local gMandyNode = 0 local pedModels = { { id = 14, maxNum = 0 }, { id = 85, maxNum = 0 }, { id = 99, maxNum = 0 }, { id = 146, maxNum = 0 }, { id = 76, maxNum = 0 }, { id = 144, maxNum = 0 }, { id = 18, maxNum = 0 }, { id = 15, maxNum = 0 }, { id = 20, maxNum = 0 }, { id = 13, maxNum = 0 }, { id = 149, maxNum = 0 }, { id = 4, maxNum = 0 }, { id = 7, maxNum = 0 }, { id = 11, maxNum = 0 } } local bPlayerGreetedMandy = false local bPlayerShotMandy = false local bVandalizingTutorial = true local gJocks = {} local bJocksFought = false local gNerds = {} local bNerdsFought = false local bInNIS = false local gLastPersonTalked local bNeedSpray = false local gSprayBlip local bMandyAttacked = false function F_SetupStage1() if PedGetAmmoCount(gPlayer, 321) < 3 then GiveWeaponToPlayer(321, false) GiveAmmoToPlayer(321, 3, false) end nMissionPhase = 1 MissionTimerStart(gMissionTime) F_StartCounter() F_CreateThreads() CameraFade(500, 1) Wait(500) F_AddMissionObjective("4_G4_OBJ1", true) Wait(4500) gStageUpdateFunction = F_Stage1 end function F_Stage1() while not AreaGetVisible() == 0 do Wait(0) end F_DisableBusinessPosters() F_CheckNerds() F_CheckSpray() end local bSaidSpeech = false local bWalkingAway = false local bNerdSpeaking = 0 function F_CheckNerds() if not bNerdsFought then if table.getn(gNerds) == 0 then if PlayerIsInTrigger(TRIGGER._4_G4_LIBNERDS) then table.insert(gNerds, PedCreatePoint(4, POINTLIST._4G4_NERDLIBRARY, 1)) table.insert(gNerds, PedCreatePoint(11, POINTLIST._4G4_NERDLIBRARY, 2)) PedSetFlag(gNerds[1], 122, true) PedSetFlag(gNerds[2], 122, true) end else if not PlayerIsInTrigger(TRIGGER._4_G4_LIBNERDS) then if gNerds[1] and PedIsValid(gNerds[1]) then PedDelete(gNerds[1]) end if gNerds[2] and PedIsValid(gNerds[2]) then PedDelete(gNerds[2]) end gNerds = {} elseif PedIsHit(gNerds[1], 2, 1000) and PedGetWhoHitMeLast(gNerds[1]) or PedIsHit(gNerds[2], 2, 1000) and PedGetWhoHitMeLast(gNerds[2]) then bNerdsFought = true PedClearObjectives(gNerds[1]) PedClearObjectives(gNerds[2]) PedAttack(gNerds[1], gPlayer, 1) PedAttack(gNerds[2], gPlayer, 1) PedMakeAmbient(gNerds[1]) PedMakeAmbient(gNerds[2]) if PedIsValid(gNerds[1]) and not PedIsDead(gNerds[1]) then SoundPlayScriptedSpeechEvent(gNerds[1], "FIGHTING", 0, "large") elseif PedIsValid(gNerds[2]) and not PedIsDead(gNerds[2]) then SoundPlayScriptedSpeechEvent(gNerds[2], "FIGHTING", 0, "large") end elseif not bSaidSpeech and PlayerIsInAreaObject(gNerds[1], 2, 3.5, 0) then bSaidSpeech = true SoundPlayScriptedSpeechEvent(gNerds[1], "M_4_G4", 199, "large") bNerdSpeaking = 1 end if PedIsValid(gNerds[2]) and PAnimIsPlaying(TRIGGER._4_G4_SCHOOLTAG2, "/Global/TagSmall/NotUseable/Tagged/VandalTag", false) and PedIsPlaying(gPlayer, "/Global/TagSmall/PedPropsActions/IsPlayer/DrawVandalTag/ParametricTagging/Finished", false) then SoundPlayScriptedSpeechEvent(gNerds[2], "SEE_VANDALISM", 0, "large") bNerdsFought = true bNerdSpeaking = 2 end end elseif not bWalkingAway then if bNerdSpeaking == 1 then if not SoundSpeechPlaying(gNerds[1]) and not bWalkingAway then bWalkingAway = true PedClearObjectives(gNerds[1]) PedClearObjectives(gNerds[2]) PedWander(gNerds[1], 0) PedWander(gNerds[2], 0) PedMakeAmbient(gNerds[1]) PedMakeAmbient(gNerds[2]) end elseif bNerdSpeaking == 2 and not SoundSpeechPlaying(gNerds[2]) and not bWalkingAway then bWalkingAway = true PedClearObjectives(gNerds[1]) PedClearObjectives(gNerds[2]) PedWander(gNerds[1], 0) PedWander(gNerds[2], 0) PedMakeAmbient(gNerds[1]) PedMakeAmbient(gNerds[2]) end end end function F_VandalismTutorial() --print("THIS IS EXECUTING!!") if bVandalizingTutorial then return 1 end return 0 end function F_SetupStage2() bMandyHold = true if mandy ~= nil and PedIsValid(mandy) then PedDelete(mandy) end local timeLeft = MissionTimerGetTimeRemaining() MissionTimerStart(timeLeft + gBonusTime) F_CompleteMissionObjective("4_G4_OBJ1") F_AddMissionObjective("4_G4_19", true) F_CreateBusinessPosters() --print("==== Finished Business Poster Create ====") L_TagLoad("4G4_BusTags", tblBusinessTags) --print("==== Finished 4G4_BusTags Poster Create ====") L_TagExec("4G4_BusTags", F_SetupTag, "element") --print("==== Finished F_SetupTag Poster Create ====") --print("==== Start gTblComicBookTag ====", i) --print("==== Done gTblComicBookTag ====", i) gStageUpdateFunction = F_Stage2 end function F_CheckSpray() if not bInNIS then if not bNeedSpray then if ItemGetCurrentNum(321) == 0 then if PlayerGetMoney() < 100 and not shared.playerShopping then gMissionStage = "OutOfMoney" else bNeedSpray = true if gStageUpdateFunction == F_Stage2 or gStageUpdateFunction == F_Stage3 then F_RemoveMissionObjective("4_G4_19") F_AddMissionObjective("4_G4_SPRAYBUY", true) gSprayBlip = BlipAddPoint(POINTLIST._4G4_YUMYUM, 0, 1, 1) elseif gStageUpdateFunction == F_Stage1 then F_RemoveMissionObjective("4_G4_OBJ1") F_AddMissionObjective("4_G4_SPRAYBUY", true) gSprayBlip = BlipAddPoint(POINTLIST._4G4_YUMYUM, 0, 1, 1) end if gAlgieCutscenePlayed then --print("Do business comics") L_TagExec("4G4_BusComicTags", F_CleanBlip, "element") end if gStageUpdateFunction == F_Stage2 or gStageUpdateFunction == F_Stage3 then --print("Do business tags comics") L_TagExec("4G4_BusTags", F_CleanBlip, "element") --print("Do school tags!") L_TagExec("4G4SchoolTags", F_CleanBlip, "element") elseif gStageUpdateFunction == F_Stage1 then --print("DO SCHOOL TAAGS!!") L_TagExec("4G4SchoolTags", F_CleanBlip, "element") end end end elseif bNeedSpray then if ItemGetCurrentNum(321) > 0 then bNeedSpray = false if gSprayBlip then BlipRemove(gSprayBlip) gSprayBlip = nil end if gStageUpdateFunction == F_Stage2 or gStageUpdateFunction == F_Stage3 then F_RemoveMissionObjective("4_G4_SPRAYBUY") F_AddMissionObjective("4_G4_19", false) elseif gStageUpdateFunction == F_Stage1 then F_RemoveMissionObjective("4_G4_SPRAYBUY") F_AddMissionObjective("4_G4_OBJ1", false) end if gAlgieCutscenePlayed then L_TagExec("4G4_BusComicTags", F_SetupTag, "element") end if gStageUpdateFunction == F_Stage2 or gStageUpdateFunction == F_Stage3 then L_TagExec("4G4_BusTags", F_SetupTag, "element") elseif gStageUpdateFunction == F_Stage1 then L_TagExec("4G4SchoolTags", F_SetupTag, "element") end while AreaGetVisible() ~= 0 do Wait(0) end if gStageUpdateFunction == F_Stage2 or gStageUpdateFunction == F_Stage3 then TextPrint("4_G4_19", 4, 1) elseif gStageUpdateFunction == F_Stage1 then TextPrint("4_G4_OBJ1", 4, 1) end elseif PlayerGetMoney() < 100 and not shared.playerShopping then gMissionStage = "OutOfMoney" end end end end function F_Stage2() F_DisableBusinessPosters() F_CheckSpray() F_CheckNerds() F_MonitorJimmy() if PlayerIsInTrigger(TRIGGER._AMB_BUSINESS_AREA) then gStageUpdateFunction = F_SetupStage3 end end function F_SetupStage3() gStageUpdateFunction = F_Stage3 end local bPissedOffJocks = false function F_Stage3() F_CheckSpray() F_MonitorJimmy() if CounterGetCurrent() == CounterGetMax() then F_CompleteMissionObjective("4_G4_19") gStageUpdateFunction = F_SetupStage4 end if not bPissedOffJocks and PedIsPlaying(gPlayer, "/Global/TagSmall/PedPropsActions/IsPlayer", true) and PlayerIsInTrigger(TRIGGER._4_G4_NERDCOMICS) then for i, ped in tblPerverts do if (ped.model == 18 or ped.model == 13) and ped.id and PedIsValid(ped.id) and not PedIsDead(ped.id) then if ped.model == 18 then SoundPlayScriptedSpeechEvent(ped.id, "FIGHTING", 0, "large") end PedSetActionNode(ped.id, "/Global/4_G4/ShortIdle", "Act/Conv/4_G4.act") PedAttack(ped.id, gPlayer, 1) end end bPissedOffJocks = true end end function F_SetupStage4() nMissionPhase = 3 bEndAlgieThread = true Wait(0) L_StopMonitoringTags() MissionTimerStop() ToggleHUDComponentVisibility(3, false) bTetherJimmyToTown = false F_CompleteMissionObjective("4_G4_19") F_AddMissionObjective("4_G4_OBJ2", true) gMandyBlip = BlipAddPoint(POINTLIST._4G4_MANDYEND, 0, 4) Wait(4000) CounterClearIcon() CounterMakeHUDVisible(false, false) gStageUpdateFunction = F_SetupStage5 end function F_SetupStage5() bMandyHold = false gStageUpdateFunction = F_Stage5 end function CB_MandyAttacked() if mandy and PedIsValid(mandy) then PedSetInvulnerable(mandy, false) PedSetFlag(mandy, 113, false) PedSetStationary(mandy, false) PedIgnoreStimuli(mandy, false) PedMakeAmbient(mandy) end bMandyAttacked = true gMissionStage = "failed" end function F_Stage5() if mandy == nil then if gMandyBlip then BlipRemove(gMandyBlip) end mandy = PedCreatePoint(14, POINTLIST._4G4_MANDYEND) PedSetMissionCritical(mandy, true, CB_MandyAttacked, true) PedSetFlag(mandy, 113, true) PedSetStationary(mandy, true) PedIgnoreStimuli(mandy, true) PedSetPedToTypeAttitude(mandy, 13, 3) gMandyBlip = AddBlipForChar(mandy, 2, 17, 4, 0) PedSetActionNode(mandy, "/Global/4_G4/4_G4_Where", "Act/Conv/4_G4.act") PedStop(mandy) PedClearObjectives(mandy) end if PedIsInAreaObject(gPlayer, mandy, 2, 3, 0) then PedSetInvulnerable(mandy, true) PlayerSetInvulnerable(true) PedSetActionNode(mandy, "/Global/4_G4/ShortIdle", "Act/Conv/4_G4.act") PlayerSetControl(0) CameraSetWidescreen(true) SoundDisableSpeech_ActionTree() F_MakePlayerSafeForNIS(true) F_PlayerDismountBike() PedSetInvulnerable(mandy, false) PedSetFlag(mandy, 113, false) PedSetStationary(mandy, false) PedIgnoreStimuli(mandy, false) PedSetEmotionTowardsPed(mandy, gPlayer, 8, true) PedSetPedToTypeAttitude(mandy, gPlayer, 4) PedSetFlag(mandy, 84, true) PedFaceObject(mandy, gPlayer, 3, 1) PedFaceObject(gPlayer, mandy, 2, 1) PedLockTarget(gPlayer, mandy, 3) PedMoveToObject(mandy, gPlayer, 2, 0) while not PlayerIsInAreaObject(mandy, 2, 0.8, 0) do Wait(0) end PedStop(mandy) PedClearObjectives(mandy) PedFaceObject(gPlayer, mandy, 2, 0) PedFaceObject(mandy, gPlayer, 3, 0, false) PedLockTarget(gPlayer, mandy, 3) PedSetActionNode(mandy, "/Global/4_G4/4_G4_Hello", "Act/Conv/4_G4.act") SoundPlayScriptedSpeechEvent(mandy, "M_4_G4", 27, "large") Wait(100) F_PedSetCameraOffsetXYZ(gPlayer, 1, -1, 1.4, 0.5, -0.5, 1.4, mandy) while SoundSpeechPlaying(mandy) do Wait(0) end PedLockTarget(mandy, gPlayer) PedLockTarget(gPlayer, mandy) PedSetActionNode(gPlayer, "/Global/Player/Social_Actions/MakeOut/Makeout/GrappleAttempt", "Act/Player.act") CameraSetWidescreen(true) Wait(6000) SoundStopInteractiveStream() PedIgnoreStimuli(mandy, true) MinigameSetCompletion("M_PASS", true, 0, "4_G4_RESPECT") MinigameAddCompletionMsg("MRESPECT_NM5", 1) SoundPlayMissionEndMusic(true, 4) while PedIsPlaying(gPlayer, "/Global/Player/Social_Actions/MakeOut/Makeout/GrappleAttempt/Kisses", true) or PedIsPlaying(mandy, "/Global/Player/Social_Actions/MakeOut/Makeout/GrappleAttempt/Kisses", true) do Wait(0) end while MinigameIsShowingCompletion() do Wait(0) end CameraFade(500, 0) Wait(501) CameraReset() CameraReturnToPlayer() PedSetPedToTypeAttitude(mandy, 13, 4) PedSetEmotionTowardsPed(mandy, gPlayer, 8, true) PedLockTarget(gPlayer, -1) PedLockTarget(mandy, -1) PedStop(mandy) BlipRemove(gMandyBlip) PedMakeAmbient(mandy) gMissionStage = "passed" end end function F_PlayerGreetedMandy() bPlayerGreetedMandy = true end function CleanupFailed() for i, tag in tblSchoolTags do if tag.poster then PAnimDelete(tag.poster) --print("CleanupFailed Poster deleted!", tag.tagName) end if tag.id then PAnimDelete(tag.id) end end for i, tag in tblBusinessTags do if tag.poster then PAnimDelete(tag.poster) end if tag.id then PAnimDelete(tag.id) end end end function F_CreateSchoolPosters() for i, tag in tblSchoolTags do --print("==== F_CreateSchoolPosters ====", i) if tag.id then PAnimCreate(tag.id, false) end if tag.poster then PAnimCreate(tag.poster, false) else --print(">>>[RUI]", "BAD School Poster Trigger") end end --print(">>>[RUI]", "++SchoolPosters") --print(">>>[RUI]", "++F_CreateSchoolPosters") end function F_CreateBusinessPosters() --print("Size of tblBusinessTags: ", table.getn(tblBusinessTags)) for i, tag in tblBusinessTags do --print("==== F_CreateBusinessPosters ====", i, "tag name: ", tag.tagName) if tag.id then PAnimCreate(tag.id, false) end if tag.poster and tag.bCheckTag then --print("Creating poster!") PAnimCreate(tag.poster, false) elseif not tag.bCheckTag and PAnimExists(tag.poster) then PAnimDelete(tag.poster) --print("Do not create poster!!") --print("F_CreateBusinessPosters Poster deleted!", tag.tagName) end end --print(">>>[RUI]", "++BusinessPosters") --print(">>>[RUI]", "++F_CreateBusinessPosters") end function T_MonitorAttackedPervs() while gMissionStage == "running" do for i, perv in tblPerverts do if perv.id and not PedIsDead(perv.id) and perv.bAttacked == false and PedGetWhoHitMeLast(perv.id) == gPlayer then PedAttack(perv.id, gPlayer, 3) perv.bAttacked = true if perv.buddy then for j, buddyPerv in tblPerverts do if buddyPerv.tagName == perv.buddy and buddyPerv.id then PedSetActionNode(buddyPerv.id, "/Global/Ambient/MissionSpec/PlayerIdle/IdleOneFrame", "/Act/Anim/Ambient.act") Wait(1) PedAttack(buddyPerv.id, gPlayer, 3) buddyPerv.bAttacked = true if buddyPerv.buddy ~= perv.tagName then for l, buddyPervbuddy in tblPerverts do if buddyPervbuddy.tagName == buddyPerv.buddy and buddyPervbuddy.id then PedAttack(buddyPervbuddy.id, gPlayer, 3) buddyPervbuddy.bAttacked = true break end Wait(1) end end break end Wait(1) end end break end Wait(1) end Wait(1) end end function F_DisableBusinessPosters() if shared.gAreaDATFileLoaded[0] == true and bDisabledSigns == false then bDisabledSigns = true for i, tag in tblBusinessTags do if tag.id then --print("========>>> disable tag.") PAnimSetActionNode(tag.id, "/Global/TagSmall/NotUseable", "Act/Props/TagSmall.act") end end for i, tag in gTblComicBookTag do if tag.id and PAnimExists(tag.id) then PAnimDelete(tag.id) PAnimDelete(tag.poster) --print("F_DisableBusinessPosters Poster deleted!", tag.tagName) end end elseif not shared.gAreaDATFileLoaded[0] and bDisabledSigns then bDisabledSigns = false end end function PervertsAttack(taggedPoint) bYelled = false for i, perv in tblPerverts do if perv.id and not PedIsDead(perv.id) and perv.id and taggedPoint == perv.trigger and PedIsInAreaObject(perv.id, gPlayer, 3, 6, 0) and not PedIsDead(perv.id) then PedSetActionNode(perv.id, "/Global/Ambient/MissionSpec/PlayerIdle/IdleOneFrame", "Act/Anim/Ambient.act") Wait(10) perv.bAttacked = true if perv.reaction then perv.reaction(perv.id, perv.yell) else FightPlayer(perv.id, perv.yell) end PedMakeAmbient(perv.id) end end end function PervertsLeave(pervId, yell) if yell == "4_G4_13" then QueueSoundSpeech(pervId, "WTF_TV", 0, nil, "large") QueueTextString("", 0.1, 2, false, CB_BulliesLeave) elseif yell == "4_G4_A2" then SoundPlayScriptedSpeechEvent(pervId, "M_4_G4", 15, "large") elseif yell == "4_G4_A1" then SoundPlayScriptedSpeechEvent(pervId, "M_4_G4", 14, "large") end if not gAlgieCutscenePlayed then gLastPersonTalked = pervId SoundDisableSpeech_ActionTree() end PedMakeAmbient(pervId) PedWander(pervId, 0) end function CB_BulliesLeave() if tblPerverts[1].id and PedIsValid(tblPerverts[1].id) then PedWander(tblPerverts[1].id, 0) end if tblPerverts[2].id and PedIsValid(tblPerverts[3].id) then PedWander(tblPerverts[2].id, 0) end if tblPerverts[3].id and PedIsValid(tblPerverts[3].id) then PedWander(tblPerverts[3].id, 0) end end function BleacherPervAttack(ped) end function AlgieCreate() algie = PedCreatePoint(7, POINTLIST._4_G4_PEDALGIESTART) end function PervertsCreate() local theAction, theModel for i, entry in tblPerverts do if entry.phase == nMissionPhase and entry.bAlive and entry.id == nil and not entry.bAttacked then theModel = entry.model --print("MODEL ENUM: ", theModel) entry.id = PedCreatePoint(theModel, entry.point, entry.element) theAction = entry.action or "/Global/4_G4/Animations/GenStandTalking/TalkingLoops" PedSetActionNode(entry.id, theAction, "Act/Conv/4_G4.act") PedSetFlag(entry.id, 122, true) if entry.threadInit then entry.threadInit(entry.id) else end end end end function PervertsDelete() for i, entry in tblPerverts do if entry.phase == nMissionPhase and entry.id and PedIsValid(entry.id) and not entry.bAttacked then if PedIsDead(entry.id) or PedGetHealth(entry.id) <= 0 then entry.bAlive = false end PedMakeAmbient(entry.id) entry.id = nil end end end function MonitorPerverts() local previousPhase = 0 bCharactersCreated = true while gMissionStage == "running" do if nMissionPhase ~= 0 then if previousPhase ~= nMissionPhase then PervertsDelete() bCharactersCreated = false end previousPhase = nMissionPhase if bCharactersCreated == false and AreaGetVisible() == 0 then PervertsCreate() bCharactersCreated = true elseif bCharactersCreated == true and AreaGetVisible() ~= 0 then PervertsDelete() bCharactersCreated = false end end Wait(0) end end function F_CreateThreads() CreateThread("L_MonitorTags") --print(">>>[RUI]", "++L_MonitorTags") CreateThread("T_MandyMonitor") --print(">>>[RUI]", "++T_MandyMonitor") CreateThread("MonitorPerverts") --print(">>>[RUI]", "++MonitorPerverts") CreateThread("T_MonitorTimer") --print(">>>[RUI]", "++T_MonitorTimer") CreateThread("T_MonitorAttackedPervs") --print(">>>[RUI]", "++T_MonitorAttackedPervs") end function CB_MandyPath(pedId, pathId, nodeId) gMandyNode = nodeId end function F_OnClean() end function FightPlayer(ped, yell) if not bYelled then if yell == "4_G4_10" then SoundPlayScriptedSpeechEvent(ped, "M_4_G4", 5, "large") end bYelled = true end if ped and not PedIsDead(ped) then PedAttackPlayer(ped) PedMakeAmbient(ped) --print(">>>[RUI]", "!!FightPlayer") end end function FleePlayer(ped) if ped and not PedIsDead(ped) then PedFlee(ped, gPlayer) PedMakeAmbient(ped) --print(">>>[RUI]", "!!FleePlayer") end end function F_PopulateTables() tblSchoolTags = { { id = TRIGGER._4_G4_SCHOOLTAG2, poster = TRIGGER._4_G4_SCHOOLPOSTER02, idBlip = nil, completed = false, bCheckTag = true, count = 30, OnTagDone = F_OnTagDone, OnSetup = nil, tagType = 5, tagName = "SchoolTagEntranceA", startNode = "/Global/TagSmall/Useable", startFile = "/Act/Props/TagSmall.act" }, { id = TRIGGER._4_G4_SCHOOLTAG3, poster = TRIGGER._4_G4_SCHOOLPOSTER03, idBlip = nil, completed = false, bCheckTag = true, count = 30, OnTagDone = F_OnTagDone, OnSetup = nil, tagType = 5, tagName = "SchoolTagMain", startNode = "/Global/TagSmall/Useable", startFile = "/Act/Props/TagSmall.act" }, { id = TRIGGER._4_G4_TILTTAG1, poster = TRIGGER._4_G4_TILTPOST1, idBlip = nil, completed = false, bCheckTag = true, count = 30, OnTag = nil, OnClean = nil, OnSetup = nil, bIsTagged = true, bIsTagDone = true, tagType = 5, tagName = "BusinessTaggedComics", startNode = "/Global/TagSmall/NotUseable/Tagged/Executes/SetTagDone", startFile = "/Act/Props/TagSmall.act" } } gSchoolTagCount = table.getn(tblSchoolTags) - 1 tblBusinessTags = { { id = TRIGGER._4_G4_BUSTAG2, poster = TRIGGER._4_G4_BUSPOSTER02, idBlip = nil, completed = false, bCheckTag = true, count = 30, OnTagDone = F_OnTagDone, OnClean = F_OnClean, OnSetup = nil, tagType = 5, tagName = "BusinessTagCinema", startNode = "/Global/TagSmall/Useable", startFile = "/Act/Props/TagSmall.act" }, { id = TRIGGER._4_G4_BUSTAG8, poster = TRIGGER._4_G4_BUSPOSTER08, idBlip = nil, completed = false, bCheckTag = true, count = 30, OnTagDone = F_OnTagDone, OnClean = F_OnClean, OnSetup = nil, tagType = 5, tagName = "BusinessTagStatue", startNode = "/Global/TagSmall/Useable", startFile = "/Act/Props/TagSmall.act" } } --print("Size of business tags: ", table.getn(tblBusinessTags)) gBusTagCount = table.getn(tblBusinessTags) gTblComicBookTag = { { id = TRIGGER._4_G4_SCHOOLTAG4, poster = TRIGGER._4_G4_SCHOOLPOSTER04, idBlip = nil, completed = false, bCheckTag = true, count = 30, OnTagDone = F_OnTagDone, OnClean = F_OnClean, OnSetup = nil, bIsTagged = false, bIsTagDone = false, bIsTagDone = true, tagType = 5, tagName = "BusinessTagComics", startNode = "/Global/TagSmall/Useable", startFile = "/Act/Props/TagSmall.act" } } gTotalTags = gSchoolTagCount tblPerverts = { { id = nil, trigger = TRIGGER._4_G4_SCHOOLTAG3, point = POINTLIST._4_G4_SCHOOLTAG3A, action = "/Global/4_G4/Animations/GenReactions/ReactionLoops", element = 1, phase = 1, reaction = PervertsLeave, blipid = nil, tagName = "SchoolPervTag3a", buddy = "SchoolPervTag3b", bAlive = true, bAttacked = false, model = 85, yell = "4_G4_15" }, { id = nil, trigger = TRIGGER._4_G4_SCHOOLTAG3, point = POINTLIST._4_G4_SCHOOLTAG3A, action = nil, element = 2, phase = 1, reaction = PervertsLeave, blipid = nil, tagName = "SchoolPervTag3b", buddy = "SchoolPervTag3c", bAlive = true, bAttacked = false, model = 99, yell = "4_G4_14" }, { id = nil, trigger = TRIGGER._4_G4_SCHOOLTAG3, point = POINTLIST._4_G4_SCHOOLTAG3A, action = "/Global/4_G4/Animations/GenReactions/ReactionLoops", element = 3, phase = 1, reaction = PervertsLeave, blipid = nil, tagName = "SchoolPervTag3c", buddy = "SchoolPervTag3a", bAlive = true, bAttacked = false, model = 146, yell = "4_G4_13" }, { id = nil, trigger = TRIGGER._4_G4_BUSTAG2, point = POINTLIST._4_G4_BUSTAG2A, action = nil, element = 1, phase = 2, reaction = PervertsLeave, blipid = nil, tagName = "BusPervCinema1", buddy = "BusPervCinema2", bAlive = true, bAttacked = false, model = 76, yell = "4_G4_A0" }, { id = nil, trigger = TRIGGER._4_G4_BUSTAG2, point = POINTLIST._4_G4_BUSTAG2A, action = nil, element = 3, phase = 2, reaction = PervertsLeave, blipid = nil, tagName = "BusPervCinema2", buddy = "BusPervCinema1", bAlive = true, bAttacked = false, model = 144, yell = "4_G4_A1" }, { id = nil, trigger = TRIGGER._4_G4_BUSTAG4, point = POINTLIST._4_G4_BUSTAG4A, action = nil, element = 1, phase = 2, reaction = FightPlayer, blipid = nil, tagName = "BusPervComic1", buddy = "BusPervComic2", bAlive = false, bAttacked = false, model = 18, yell = "4_G4_14" }, { id = nil, trigger = TRIGGER._4_G4_BUSTAG4, point = POINTLIST._4_G4_BUSTAG4A, action = nil, element = 2, phase = 2, reaction = FightPlayer, blipid = nil, tagName = "BusPervComic2", buddy = "BusPervComic1", bAlive = false, bAttacked = false, model = 13, yell = "4_G4_10" }, { id = nil, trigger = TRIGGER._4_G4_BUSTAG8, point = POINTLIST._4_G4_BUSTAG8A, action = "/Global/4_G4/Animations/GenReactions/ReactionLoops", element = 1, phase = 2, reaction = PervertsLeave, blipid = nil, tagName = "BusPervStatue", bAlive = true, bAttacked = false, model = 149, yell = "4_G4_A2" } } bleacherPervIdx = 3 tblAlgieTags = { { poster = TRIGGER._4_G4_BUSPOSTER08, id = TRIGGER._4_G4_BUSTAG8, path = PATH._4G4_COMICTOBACKALLEY, idBlip = nil, bCurrentFollowing = false, tagName = "BusinessTagStatue", bCheckTag = true }, { poster = TRIGGER._4_G4_BUSPOSTER02, id = TRIGGER._4_G4_BUSTAG2, path = PATH._4G4_PITTOALLEY, idBlip = nil, bCurrentFollowing = false, tagName = "BusinessTagCinema", bCheckTag = true }, { poster = TRIGGER._4_G4_BUSPOSTER04, id = TRIGGER._4_G4_BUSTAG4, path = PATH._4G4_CINEMATOMEX, idBlip = nil, bCurrentFollowing = false, tagName = "BusinessTagComics", bCheckTag = true } } gMaxNerdTrigs = table.getn(tblAlgieTags) end function F_StartCounter() CounterSetCurrent(0) CounterSetMax(2) CounterSetIcon("MandPost", "MandPost_x") CounterMakeHUDVisible(true, true) end function F_OnTagDone(tblTag) --print(">>>[RUI]", "++F_OnTag: ") if L_TagIsFaction(tblTag.id, tblTag.tagType) then --print(">>>[RUI]", "Tag Good") bVandalizingTutorial = false CounterIncrementCurrent(1) if tblTag.idBlip ~= nil then BlipRemove(tblTag.idBlip) tblTag.idBlip = nil end PervertsAttack(tblTag.id) else L_ClearTag(tblTag.id, 210) --print(">>>[RUI]", "Tag Bad") end --print("Number of posters tagged: ", CounterGetCurrent()) if not gAlgieCutscenePlayed and nMissionPhase == 2 then if SoundSpeechPlaying(gLastPersonTalked) then PlayerSetControl(0) while SoundSpeechPlaying(gLastPersonTalked) do Wait(0) --print("IN HERE!") end SoundEnableSpeech_ActionTree() end F_DoAlgieCutscene() elseif nMissionPhase == 1 and CounterGetCurrent() == gSchoolTagCount then CounterSetCurrent(2) CounterSetMax(4) nMissionPhase = 2 gStageUpdateFunction = F_SetupStage2 end end function F_SetupTag(tag) local idBlip --print("Tag name: ", tag.tagName) --print("Tag check tag?: ", tostring(tag.bCheckTag)) --print("Tag is tagged?: ", tostring(tag.bIsTagged)) --print("Tag is done?: ", tostring(tag.bIsTagDone)) if tag.id and tag.bCheckTag and not tag.bIsTagDone then --print(">>>[RUI]", "F_SetupTag add blip") local x, y, z = GetAnchorPosition(tag.id) idBlip = BlipAddXYZ(x, y, z, 0) tag.idBlip = idBlip end end function F_CleanBlip(tag) if tag.idBlip then BlipRemove(tag.idBlip) tag.idBlip = nil end end function F_SetValidTags(intFaction) if intFaction == 1 then idValidTagType = 1 elseif intFaction == 2 then idValidTagType = 2 elseif intFaction == 3 then idValidTagType = 3 elseif intFaction == 4 then idValidTagType = 4 elseif intFaction == 5 then idValidTagType = 5 end end function T_AlgieTagCleanup() local nextTrig = 1 local bAlgieSprinting = false local bAlgieCleanupTags = true local bAlgieWasAttacked = false local bAlgieWasAttackedAgain = false local nTimeAlgieWasAttacked = 0 while 0 < PedGetHealth(algie) do if not bInNIS then if not bAlgieWasAttacked then if PedIsHit(algie, 2, 1000) and PedGetWhoHitMeLast(algie) == gPlayer and 0 < PedGetHealth(algie) then SoundStopCurrentSpeechEvent(algie) PedClearObjectives(algie) SoundPlayScriptedSpeechEvent(algie, "VICTIMIZED", 0, "large") if not PedMePlaying(algie, "Grapples", true) then PedSetActionNode(algie, "/Global/4_G4/Cower", "Act/Conv/4_G4.act") while PedIsPlaying(algie, "/Global/4_G4/Cower", false) do Wait(0) end end PedIgnoreStimuli(algie, true) PedAddPedToIgnoreList(algie, gPlayer) PedClearObjectives(algie) PedStop(algie) PedMoveToPoint(algie, 3, POINTLIST._4G4_THADRUN, 1) nTimeAlgieWasAttacked = GetTimer() bAlgieCleanupTags = false tblAlgieTags[currentTrig].bCurrentFollowing = false bAlgieWasAttacked = true end elseif bAlgieWasAttacked then if not bAlgieCleanupTags and (GetTimer() - nTimeAlgieWasAttacked > 30000 or not PlayerIsInAreaObject(algie, 2, 40, 0)) then PedClearObjectives(algie) PedIgnoreStimuli(algie, false) bAlgieCleanupTags = true end if not bAlgieWasAttackedAgain and bAlgieCleanupTags and (PedCanSeeObject(gPlayer, algie, 2) and PlayerIsInAreaObject(algie, 2, 10, 0) or PedIsHit(algie, 2, 1000) and PedGetWhoHitMeLast(algie) == gPlayer) and 0 < PedGetHealth(algie) then F_DoAlgieRunNIS() bAlgieWasAttackedAgain = true PedMakeAmbient(algie) bAlgieCleanupTags = false break end end if bAlgieCleanupTags then if tblAlgieTags[currentTrig].path and tblAlgieTags[currentTrig].bCurrentFollowing == false then PedFollowPath(algie, tblAlgieTags[currentTrig].path, 0, 1, F_ReachedPathEnd) tblAlgieTags[currentTrig].bCurrentFollowing = true end if bReachedPathEnd then tblAlgieTags[currentTrig].bCurrentFollowing = false AlgieCleansTag(tblAlgieTags[currentTrig]) currentTrig = F_CycleTriggers(currentTrig) bReachedPathEnd = false end end end Wait(1) end end function F_DoAlgieRunNIS() PlayerSetControl(0) F_MakePlayerSafeForNIS(true) CameraSetWidescreen(true) PedSetInvulnerable(algie, true) PedClearObjectives(algie) PedStop(algie) PedSetStationary(algie, true) PedFaceObjectNow(algie, gPlayer, 2) Wait(500) F_PedSetCameraOffsetXYZ(algie, 0.1, 1.3, 1.4, 0, 0, 1.4) Wait(500) PedSetStationary(algie, false) PedSetActionNode(algie, "/Global/4_G4/Scream", "Act/Conv/4_G4.act") SoundPlayScriptedSpeechEvent(algie, "TAUNT_RESPONSE_CRY", 0, "large") Wait(1500) PedMoveToPoint(algie, 3, POINTLIST._4G4_THADRUN, 1) CameraLookAtObject(algie, 2, true, 1.4) Wait(4000) PedSetInvulnerable(algie, false) CameraSetWidescreen(false) PlayerSetControl(1) CameraReset() CameraReturnToPlayer() CameraFollowPed(gPlayer) F_MakePlayerSafeForNIS(false) end function F_ReachedPathEnd(pedid, pathid, nodeid) if nodeid == PathGetLastNode(pathid) then bReachedPathEnd = true end end function AlgieCleansTag(tag) if not bEndAlgieThread then local Dachoice = math.random(1, 3) local DaScaredChoice = math.random(4, 6) local bFoundTag = false local bPlayerAlreadyTaggingIt = false --print("tag.tagName: ", tostring(tag.tagName)) --print("tag.bCheckTag: ", tostring(tag.bCheckTag)) --print("tag.id: ", tostring(tag.id)) tag = GetRelativeTag(tag.tagName) if AreaGetVisible() == 0 and tag.bCheckTag and (not tag.id or not PAnimIsPlaying(tag.id, "/Global/TagSmall/NotUseable/Tagged/VandalTag", false)) then --print(">>>[RUI]", "!!AlgieCleansTag INVALID TAG") return end PedStop(algie) bReachedPathEnd = false timerElapsed = 0 timerStart = GetTimer() if PAnimIsPlaying(tag.id, "/Global/TagSmall/NotUseable/Tagged/VandalTag", false) then bFoundTag = true end if not tag.bCheckTag then bFoundTag = true end algieScrubbing = false if PlayerIsInAreaObject(algie, 2, 4, 0) and PedIsPlaying(gPlayer, "/Global/TagSmall/PedPropsActions/IsPlayer", true) then bPlayerAlreadyTaggingIt = true end if bFoundTag and not bPlayerAlreadyTaggingIt then local x, y, z = GetAnchorPosition(tag.id) PedFaceXYZ(algie, x, y, z, 0) Wait(40) TextPrint("4_G4_ALGIECLEAN", 4, 1) PedSetActionNode(algie, "/Global/4_G4/Animations/SetupPoster/PlaceIt", "Act/Conv/4_G4.act") while PedIsPlaying(algie, "/Global/4_G4/Animations/SetupPoster/PlaceIt", false) do Wait(0) end tag.bCurrentFollowing = false if not tag.bCheckTag then PAnimCreate(tag.poster, false) CounterSetMax(CounterGetMax() + 1) else CounterIncrementCurrent(-1) end tag.bIsTagged = false tag.bIsTagDone = false tag.bCheckTag = true if not bNeedSpray then tag.idBlip = BlipAddXYZ(x, y, z, 0) else tag.idBlip = nil end PAnimSetActionNode(tag.id, "/Global/TagSmall/Useable", "/Act/Props/TagSmall.act") end end end function F_CycleTriggers(triggerNumber) triggerNumber = triggerNumber + 1 if triggerNumber > gMaxNerdTrigs then triggerNumber = 1 end return triggerNumber end function GetRelativeTag(name) for i, tag in tblBusinessTags do if tag.tagName == name then return tag end end for i, tag in gTblComicBookTag do if tag.tagName == name then return tag end end return nil end function PlayerHasHitPed(ped) return PedGetWhoHitMeLast(ped) == gPlayer end function T_MandyMonitor() while gMissionStage == "running" do if mandy and (PlayerHasHitPed(mandy) or PedIsDead(mandy)) and gMissionStage ~= "passed" then if PlayerHasHitPed(mandy) then elseif PedIsDead(mandy) then end bMandySlapped = true break end if AreaGetVisible() == 13 and mandy == nil then if gStageUpdateFunction == F_Stage5 and mandy and PedIsValid(mandy) then PedSetMissionCritical(mandy, false) PedDelete(mandy) end elseif AreaGetVisible() == 0 and gStageUpdateFunction == F_Stage5 and mandy == nil then mandy = PedCreatePoint(14, POINTLIST._4G4_MANDYEND) PedSetMissionCritical(mandy, true, CB_MandyAttacked, true) PedSetPedToTypeAttitude(mandy, 13, 3) PedSetActionNode(mandy, "/Global/4_G4/4_G4_Where", "Act/Conv/4_G4.act") gMandyBlip = BlipAddPoint(POINTLIST._4G4_MANDYEND, 0, 4) end Wait(100) end if gMissionStage ~= "passed" and bMandySlapped and not bMandyHold then gMissionStage = "failed" if not PedIsDead(mandy) then PedFlee(mandy, gPlayer) end Wait(4000) end end function T_MonitorTimer() while gMissionStage == "running" do if MissionTimerHasFinished() then bTimesUp = true break end Wait(100) end if bTimesUp and nMissionPhase < 3 then gMissionStage = "failed" end collectgarbage() end function F_SetPlayerLoc(point, area) local areaID = area or 0 AreaTransitionPoint(areaID, point) end function F_CleanupTags(tag) --print("tag.id = ", tostring(tag.id)) --print("tag.poster = ", tostring(tag.poster)) if tag.id then PAnimDelete(tag.id) end if tag.poster then PAnimDelete(tag.poster) --print("F_CleanupTags Poster deleted!", tag.tagName) end if tag.idBlip then BlipRemove(tag.idBlip) tag.idBlip = nil end end function CB_PedArrivedAtNode(pedId, pathId, nodeId) if nodeId == PathGetLastNode(pathId) and pedId == perv1 then PedSetActionNode(perv1, "/Global/4_G4/Animations/GenStandTalking/TalkingLoops", "Act/Conv/4_G4.act") end if nodeId == PathGetLastNode(pathId) and pedId == perv2 then PedSetActionNode(perv2, "/Global/4_G4/Animations/GenStandTalking/TalkingLoops", "Act/Conv/4_G4.act") end end function F_DoAlgieCutscene() local perv1, perv2, x, y, z, heading x2, y2, z2 = PlayerGetPosXYZ() gAlgieCutscenePlayed = true CameraFade(500, 0) Wait(500) TextPrintString("", 1, 2) TextPrintString("", 1, 1) bInNIS = true PlayerUnequip() while WeaponEquipped() do Wait(0) end PlayerSetPosXYZ(516.14, -70.544, 4.64) PlayerSetControl(0) F_MakePlayerSafeForNIS(true) CameraSetWidescreen(true) AlgieCreate() for i, perv in tblPerverts do if perv.tagName == "BusPervComic1" or perv.tagName == "BusPervComic2" then perv.bAlive = true end end PervertsCreate() for i, perv in tblPerverts do if perv.tagName == "BusPervComic1" then perv1 = perv.id PedSetActionNode(perv1, "/Global/Ambient/MissionSpec/PlayerIdle/IdleOneFrame", "Act/Anim/Ambient.act") elseif perv.tagName == "BusPervComic2" then perv2 = perv.id PedSetActionNode(perv2, "/Global/Ambient/MissionSpec/PlayerIdle/IdleOneFrame", "Act/Anim/Ambient.act") end end PAnimSetActionNode(TRIGGER._4_G4_TILTTAG1, "/Global/TagSmall/NotUseable/Tagged/Executes/SetTagDone", "Act/Props/TagSmall.act") PedSetPosPoint(perv1, POINTLIST._4_G4_ALGIECUT, 2) PedSetPosPoint(perv2, POINTLIST._4_G4_ALGIECUT, 1) PedSetPosPoint(algie, POINTLIST._4_G4_ALGIECUT, 3) PedClearAllWeapons(algie) CameraSetFOV(70) CameraSetXYZ(512.32794, -64.18165, 6.174207, 513.1554, -63.620415, 6.186368) CameraFade(500, 1) Wait(500) PedFollowPath(algie, PATH._4G4_ALGIEPATH, 0, 1) SoundPlayScriptedSpeechEvent(algie, "M_4_G4", 22, "large") Wait(3000) PedStop(algie) while SoundSpeechPlaying(algie) do Wait(0) end PedSetActionNode(algie, "/Global/4_G4/Animations/SetupPoster/PlaceIt", "Act/Conv/4_G4.act") while PedIsPlaying(algie, "/Global/4_G4/Animations/SetupPoster/PlaceIt", false) do Wait(0) end for i, tag in gTblComicBookTag do PAnimCreate(tag.id) PAnimCreate(tag.poster) end --print("Load tag during the NIS!") L_TagLoad("4G4_BusComicTags", gTblComicBookTag) for i, tag in gTblComicBookTag do if tag.id then tag.bIsTagged = false tag.bIsTagDone = false tag.bCheckTag = true tag.bIsTagDone = false PAnimSetActionNode(tag.id, "/Global/TagSmall/Useable", "/Act/Props/TagSmall.act") end end if not bNeedSpray then --print("Setup the business comic tags") L_TagExec("4G4_BusComicTags", F_SetupTag, "element") end PedFollowPath(algie, tblAlgieTags[currentTrig].path, 0, 1, F_ReachedPathEnd) CreateThread("T_AlgieTagCleanup") Wait(1000) PedFollowPath(perv1, PATH._4G4_PERV1, 0, 0, CB_PedArrivedAtNode) PedFollowPath(perv2, PATH._4G4_PERV1, 0, 0, CB_PedArrivedAtNode) CameraFade(500, 0) Wait(500) CameraDefaultFOV() CameraReset() CameraReturnToPlayer() CameraSetWidescreen(false) PlayerSetPosXYZ(x2, y2, z2) PlayerFaceHeading(180, 0) TextPrintString("", 1, 2) CounterSetIcon("MandPost", "MandPost_x") CounterMakeHUDVisible(true, true) CounterSetMax(5) bTetherJimmyToTown = true bInNIS = false F_MakePlayerSafeForNIS(false) Wait(300) CameraFade(500, 1) Wait(500) PlayerSetControl(1) if bNeedSpray then TextPrint("4_G4_SPRAYBUY", 4, 1) end end function F_MonitorJimmy() if bTetherJimmyToTown and not AreaIsLoading() and AreaGetVisible() == 0 then if bCheckFailing then if not PlayerIsInTrigger(TRIGGER._4_G4_LEFTTOWN) then gMissionStage = "LeftTown" elseif PlayerIsInTrigger(TRIGGER._AMB_BUSINESS_AREA) then bCheckFailing = false TextPrintString("", 1, 1) end elseif not PlayerIsInTrigger(TRIGGER._AMB_BUSINESS_AREA) then TextPrint("4_G4_SEARCH", 4000000, 1) bCheckFailing = true end end end function InitialSetup() WeaponRequestModel(321) LoadAnimationGroup("MINIGraf") LoadAnimationGroup("Hang_Jock") LoadAnimationGroup("Hang_Talking") LoadAnimationGroup("NPC_Love") LoadAnimationGroup("NPC_NeedsResolving") LoadAnimationGroup("POI_Smoking") LoadAnimationGroup("GEN_Socia") LoadAnimationGroup("IDLE_SEXY_C") LoadAnimationGroup("SGIRL_F") LoadPAnims({ TRIGGER._4_G4_SCHOOLPOSTER02, TRIGGER._4_G4_SCHOOLPOSTER03, TRIGGER._4_G4_SCHOOLPOSTER04, TRIGGER._4_G4_BUSPOSTER02, TRIGGER._4_G4_BUSPOSTER03, TRIGGER._4_G4_BUSPOSTER04, TRIGGER._4_G4_BUSPOSTER06A, TRIGGER._4_G4_BUSPOSTER08 }) for i, ped in pedModels do ped.maxNum = PedGetUniqueModelStatus(ped.id) PedSetUniqueModelStatus(ped.id, -1) end LoadPedModels({ 85, 99, 146, 76, 144, 18, 15, 20, 13, 149, 14, 4, 7, 11 }) LoadActionTree("Act/Conv/4_G4.act") F_PopulateTables() F_SetValidTags(5) F_CreateSchoolPosters() L_TagLoad("4G4SchoolTags", tblSchoolTags) for i, tag in tblSchoolTags do if tag.id and tag.tagName == "BusinessTaggedComics" then tag.bIsTagged = true tag.bIsTagDone = true tag.bCheckTag = false end end L_TagExec("4G4SchoolTags", F_SetupTag, "element") F_DisableBusinessPosters() AreaTransitionPoint(0, POINTLIST._4_G4_PLAYERSTART) while not shared.gAreaDATFileLoaded[0] == true do Wait(100) end TaggingStartPersistentTag() Wait(100) CameraReset() CameraReturnToPlayer() end function MissionSetup() MissionDontFadeIn() TaggingOnlyShowMissionTags(true) SoundPlayInteractiveStream("MS_SearchingLow.rsm", MUSIC_DEFAULT_VOLUME) SoundSetMidIntensityStream("MS_SearchingMid.rsm", 0.6) SoundSetHighIntensityStream("MS_SearchingHigh.rsm", 0.7) PlayCutsceneWithLoad("4-G4", true, true) DATLoad("4_G4.DAT", 2) DATInit() if PlayerGetMoney() < 100 then PlayerSetMoney(100) end end function main() InitialSetup() CreateThread("T_PedMonitor") gStageUpdateFunction = F_SetupStage1 while not (gMissionStage ~= "running" or bPlayerShotMandy) do UpdateTextQueue() gStageUpdateFunction() Wait(0) end if gMissionStage == "passed" then SoundStopInteractiveStream() SetFactionRespect(1, GetFactionRespect(1) - 5) MissionSucceed(false, false, false) AreaEnsureSpecialEntitiesAreCreatedWithOverride("4_G4", 4) Wait(500) CameraFade(500, 1) Wait(101) else CleanupFailed() if bMandyAttacked then if mandy and PedIsValid(mandy) then PedSetInvulnerable(mandy, false) PedSetFlag(mandy, 113, false) PedSetStationary(mandy, false) PedIgnoreStimuli(mandy, false) PedMakeAmbient(mandy) end SoundPlayMissionEndMusic(false, 4) MissionFail(false, true, "4_G4_MANDHIT") elseif gMissionStage == "OutOfMoney" then CounterClearIcon() CounterMakeHUDVisible(false, false) SoundPlayMissionEndMusic(false, 4) TextPrintString("", 1, 1) MissionFail(false, true, "CMN_STR_06") elseif bTimesUp then CounterClearIcon() CounterMakeHUDVisible(false, false) SoundPlayMissionEndMusic(false, 4) MissionFail(false, true, "4_G4_TIMEUP") elseif gMissionStage == "LeftTown" then CounterClearIcon() CounterMakeHUDVisible(false, false) SoundPlayMissionEndMusic(false, 4) TextPrintString("", 1, 1) MissionFail(false, true, "4_G4_FAILLEFT") else SoundPlayMissionEndMusic(false, 4) MissionFail() end end end function MissionCleanup() PlayerSetControl(1) F_MakePlayerSafeForNIS(false) CameraSetWidescreen(false) CameraReturnToPlayer(true) CameraReset() TaggingStopPersistentTag() TaggingOnlyShowMissionTags(false) SoundStopInteractiveStream() SoundEnableSpeech_ActionTree() if mandy and PedIsValid(mandy) then PedSetInvulnerable(mandy, false) PedSetFlag(mandy, 113, false) PedSetStationary(mandy, false) PedIgnoreStimuli(mandy, false) PedMakeAmbient(mandy) PedWander(mandy, 0) end for i, ped in pedModels do PedSetUniqueModelStatus(ped.id, ped.maxNum) end CounterClearIcon() CounterMakeHUDVisible(false, false) --print("SLKDFMSKMFSM!") if 1 <= nMissionPhase and 0 < table.getn(tblSchoolTags) then L_TagExec("4G4SchoolTags", F_CleanupTags, "element") end if 2 <= nMissionPhase then --print("E{LWPREPWLRWLPERWR!") if 0 < table.getn(tblBusinessTags) then L_TagExec("4G4_BusTags", F_CleanupTags, "element") end --print("LNKEWRMKMKKMKLFIOI!") if gAlgieCutscenePlayed and 0 < table.getn(gTblComicBookTag) then L_TagExec("4G4_BusComicTags", F_CleanupTags, "element") end end UnLoadAnimationGroup("MINIGraf") UnLoadAnimationGroup("Hang_Jock") UnLoadAnimationGroup("Hang_Talking") UnLoadAnimationGroup("NPC_Love") UnLoadAnimationGroup("NPC_NeedsResolving") UnLoadAnimationGroup("POI_Smoking") UnLoadAnimationGroup("GEN_Socia") UnLoadAnimationGroup("IDLE_SEXY_C") UnLoadAnimationGroup("SGIRL_F") DATUnload(2) end function F_PlayerShotMandy() --print("PWNED!") bPlayerShotMandy = true end local tObjectiveTable = {} function F_ObjectiveAlreadyGiven(reference) for i, objective in tObjectiveTable do if objective.ref == reference then return true end end return false end function F_ObjectiveAlreadyComplete(reference) for i, objective in tObjectiveTable do if objective.ref == reference then return objective.bComplete end end return false end function F_RemoveMissionObjective(reference) for i, objective in tObjectiveTable do if objective.ref == reference then MissionObjectiveRemove(objective.id) table.remove(tObjectiveTable, i) end end end function F_CompleteMissionObjective(reference) for i, objective in tObjectiveTable do if objective.ref == reference then MissionObjectiveComplete(objective.id) objective.bComplete = true end end end function F_AddMissionObjective(reference, bPrint) if F_ObjectiveAlreadyGiven(reference) then for i, objective in tObjectiveTable do if objective.ref == reference then return objective.id end end end if bPrint then TextPrint(reference, 3, 1) end local objId = MissionObjectiveAdd(reference) table.insert(tObjectiveTable, { id = objId, ref = reference, bComplete = false }) return objId end
0
0.815567
1
0.815567
game-dev
MEDIA
0.769614
game-dev,testing-qa
0.940367
1
0.940367
SceneView/sceneview-android
4,570
sceneview/src/main/java/io/github/sceneview/node/VideoNode.kt
package io.github.sceneview.node // TODO: To finish //open class VideoNode private constructor( // engine: Engine, // val materialLoader: MaterialLoader, // entity: Entity = EntityManager.get().create(), // parent: Node? = null, // mediaPlayer: MediaPlayer, // val texture: Texture, // /** // * `null` to adjust size on the normalized image size // */ // val size: Size? = null, // center: Position = Plane.DEFAULT_CENTER, // normal: Direction = Plane.DEFAULT_NORMAL, // builder: RenderableManager.Builder.() -> Unit = {} //) : PlaneNode( // engine, entity, parent, // size ?: normalize(Size(mediaPlayer.videoWidth.toFloat(), mediaPlayer.videoHeight.toFloat())), // center, normal, // materialLoader.createVideoInstance(texture), // builder //) { // var mediaPlayer = mediaPlayer // set(value) { // field = value // texture.setExternalStream()setBitmap(engine, value) // if (size == null) { // updateGeometry( // size = normalize(Size(value.videoWidth.toFloat(), value.videoHeight.toFloat())) // ) // } // } // // init { // if (size == null) { // mediaPlayer.doOnVideoSized { player, width, height -> // if (player == this.player) { // updateGeometry(size = normalize(Size(width.toFloat(), height.toFloat()))) // } // } // } // } //} // //open class VideoNode( // videoMaterial: VideoMaterial, // val player: MediaPlayer, // size: Size = Plane.DEFAULT_SIZE, // center: Position = Plane.DEFAULT_CENTER, // normal: Direction = Plane.DEFAULT_NORMAL, // scaleToVideoRatio: Boolean = true, // /** // * Keep the video aspect ratio. // * - `true` to fit within max width or height // * - `false` the video will be stretched to the node scale // */ // keepAspectRatio: Boolean = true, // /** // * The parent node. // * // * If set to null, this node will not be attached. // * // * The local position, rotation, and scale of this node will remain the same. // * Therefore, the world position, rotation, and scale of this node may be different after the // * parent changes. // */ // parent: Node? = null, // renderableApply: RenderableManager.Builder.() -> Unit = {} //) : PlaneNode( // engine = videoMaterial.engine, // size = size, // center = center, // normal = normal, // materialInstance = videoMaterial.instance, // parent = parent, // renderableApply = renderableApply //) { // // // constructor( // materialLoader: MaterialLoader, // player: MediaPlayer, // chromaKeyColor: Int? = null, // scaleToVideoRatio: Boolean = true, // /** // * Keep the video aspect ratio. // * - `true` to fit within max width or height // * - `false` the video will be stretched to the node scale // */ // keepAspectRatio: Boolean = true, // size: Size = Plane.DEFAULT_SIZE, // center: Position = Plane.DEFAULT_CENTER, // normal: Direction = Plane.DEFAULT_NORMAL, // /** // * The parent node. // * // * If set to null, this node will not be attached. // * // * The local position, rotation, and scale of this node will remain the same. // * Therefore, the world position, rotation, and scale of this node may be different after the // * parent changes. // */ // parent: Node? = null, // renderableApply: RenderableManager.Builder.() -> Unit = {} // ) : this( // videoMaterial = materialLoader.createVideoInstance(player, chromaKeyColor), // player = player, // scaleToVideoRatio = scaleToVideoRatio, // keepAspectRatio = keepAspectRatio, // size = size, // center = center, // normal = normal, // parent = parent, // renderableApply = renderableApply // ) // // override fun destroy() { // super.destroy() // // player.stop() // } //} // // //fun MediaPlayer.doOnVideoSized(block: (player: MediaPlayer, videoWidth: Int, videoHeight: Int) -> Unit) { // if (videoWidth > 0 && videoHeight > 0) { // block(this, videoWidth, videoHeight) // } else { // setOnVideoSizeChangedListener { _, width: Int, height: Int -> // if (width > 0 && height > 0) { // block(this, width, height) // } // } // } //}
0
0.911746
1
0.911746
game-dev
MEDIA
0.70046
game-dev
0.776437
1
0.776437
PentestSS13/Pentest
12,321
code/modules/power/singularity/field_generator.dm
/* field_generator power level display The icon used for the field_generator need to have 'num_power_levels' number of icon states named 'Field_Gen +p[num]' where 'num' ranges from 1 to 'num_power_levels' The power level is displayed using overlays. The current displayed power level is stored in 'powerlevel'. The overlay in use and the powerlevel variable must be kept in sync. A powerlevel equal to 0 means that no power level overlay is currently in the overlays list. -Aygar */ #define field_generator_max_power 250 #define FG_OFFLINE 0 #define FG_CHARGING 1 #define FG_ONLINE 2 //field generator construction defines #define FG_UNSECURED 0 #define FG_SECURED 1 #define FG_WELDED 2 /obj/machinery/field/generator name = "field generator" desc = "A large thermal battery that projects a high amount of energy when powered." icon = 'icons/obj/machines/field_generator.dmi' icon_state = "Field_Gen" anchored = FALSE density = TRUE use_power = NO_POWER_USE max_integrity = 500 CanAtmosPass = ATMOS_PASS_YES //100% immune to lasers and energy projectiles since it absorbs their energy. armor = list("melee" = 25, "bullet" = 10, "laser" = 100, "energy" = 100, "bomb" = 0, "bio" = 0, "rad" = 0, "fire" = 50, "acid" = 70) var/const/num_power_levels = 6 // Total number of power level icon has var/power_level = 0 var/active = FG_OFFLINE var/power = 20 // Current amount of power var/state = FG_UNSECURED var/warming_up = 0 var/list/obj/machinery/field/containment/fields var/list/obj/machinery/field/generator/connected_gens var/clean_up = 0 /obj/machinery/field/generator/update_overlays() . = ..() if(warming_up) . += "+a[warming_up]" if(LAZYLEN(fields)) . += "+on" if(power_level) . += "+p[power_level]" /obj/machinery/field/generator/Initialize() . = ..() fields = list() connected_gens = list() /obj/machinery/field/generator/anchored/Initialize() . = ..() set_anchored(TRUE) /obj/machinery/field/generator/ComponentInitialize() . = ..() AddComponent(/datum/component/empprotection, EMP_PROTECT_SELF | EMP_PROTECT_WIRES) /obj/machinery/field/generator/process(seconds_per_tick) if(active == FG_ONLINE) calc_power() /obj/machinery/field/generator/interact(mob/user) if(state == FG_WELDED) if(get_dist(src, user) <= 1)//Need to actually touch the thing to turn it on if(active >= FG_CHARGING) to_chat(user, span_warning("You are unable to turn off [src] once it is online!")) return 1 else user.visible_message(span_notice("[user] turns on [src]."), \ span_notice("You turn on [src]."), \ span_hear("You hear heavy droning.")) turn_on() investigate_log("<font color='green'>activated</font> by [key_name(user)].", INVESTIGATE_SINGULO) add_fingerprint(user) else to_chat(user, span_warning("[src] needs to be firmly secured to the floor first!")) /obj/machinery/field/generator/set_anchored(anchorvalue) . = ..() if(isnull(.)) return if(active) turn_off() state = anchorvalue ? FG_SECURED : FG_UNSECURED /obj/machinery/field/generator/can_be_unfasten_wrench(mob/user, silent) if(active) if(!silent) to_chat(user, span_warning("Turn \the [src] off first!")) return FAILED_UNFASTEN else if(state == FG_WELDED) if(!silent) to_chat(user, span_warning("[src] is welded to the floor!")) return FAILED_UNFASTEN return ..() /obj/machinery/field/generator/default_unfasten_wrench(mob/user, obj/item/I, time = 20) . = ..() if(. == SUCCESSFUL_UNFASTEN) if(anchored) state = FG_SECURED else state = FG_UNSECURED /obj/machinery/field/generator/wrench_act(mob/living/user, obj/item/I) ..() default_unfasten_wrench(user, I) return TRUE /obj/machinery/field/generator/welder_act(mob/living/user, obj/item/I) . = ..() if(active) to_chat(user, span_warning("[src] needs to be off!")) return TRUE switch(state) if(FG_UNSECURED) to_chat(user, span_warning("[src] needs to be wrenched to the floor!")) if(FG_SECURED) if(!I.tool_start_check(user, src, amount=0)) return TRUE user.visible_message(span_notice("[user] starts to weld [src] to the floor."), \ span_notice("You start to weld \the [src] to the floor..."), \ span_hear("You hear welding.")) if(I.use_tool(src, user, 20, volume=50) && state == FG_SECURED) state = FG_WELDED to_chat(user, span_notice("You weld the field generator to the floor.")) if(FG_WELDED) if(!I.tool_start_check(user, src, amount=0)) return TRUE user.visible_message(span_notice("[user] starts to cut [src] free from the floor."), \ span_notice("You start to cut \the [src] free from the floor..."), \ span_hear("You hear welding.")) if(I.use_tool(src, user, 20, volume=50) && state == FG_WELDED) state = FG_SECURED to_chat(user, span_notice("You cut \the [src] free from the floor.")) return TRUE /obj/machinery/field/generator/attack_animal(mob/living/simple_animal/M) if(M.environment_smash & ENVIRONMENT_SMASH_RWALLS && active == FG_OFFLINE && state != FG_UNSECURED) set_anchored(FALSE) M.visible_message(span_warning("[M] rips [src] free from its moorings!")) else ..() if(!anchored) step(src, get_dir(M, src)) /obj/machinery/field/generator/bullet_act(obj/projectile/Proj) if(Proj.flag != "bullet") power = min(power + Proj.damage, field_generator_max_power) check_power_level() . = ..() /obj/machinery/field/generator/Destroy() cleanup() return ..() /obj/machinery/field/generator/proc/check_power_level() var/new_level = round(num_power_levels * power / field_generator_max_power) if(new_level != power_level) power_level = new_level update_appearance() /obj/machinery/field/generator/proc/turn_off() active = FG_OFFLINE CanAtmosPass = ATMOS_PASS_YES air_update_turf(TRUE) INVOKE_ASYNC(src, PROC_REF(cleanup)) addtimer(CALLBACK(src, PROC_REF(cool_down)), 50) /obj/machinery/field/generator/proc/cool_down() if(active || warming_up <= 0) return warming_up-- update_appearance() if(warming_up > 0) addtimer(CALLBACK(src, PROC_REF(cool_down)), 50) /obj/machinery/field/generator/proc/turn_on() active = FG_CHARGING addtimer(CALLBACK(src, PROC_REF(warm_up)), 50) /obj/machinery/field/generator/proc/warm_up() if(!active) return warming_up++ update_appearance() if(warming_up >= 3) start_fields() else addtimer(CALLBACK(src, PROC_REF(warm_up)), 50) /obj/machinery/field/generator/proc/calc_power(set_power_draw) var/power_draw = 2 + fields.len if(set_power_draw) power_draw = set_power_draw if(draw_power(round(power_draw/2,1))) check_power_level() return 1 else visible_message(span_danger("The [name] shuts down!"), span_hear("You hear something shutting down.")) turn_off() investigate_log("ran out of power and <font color='red'>deactivated</font>", INVESTIGATE_SINGULO) power = 0 check_power_level() return 0 //This could likely be better, it tends to start loopin if you have a complex generator loop setup. Still works well enough to run the engine fields will likely recode the field gens and fields sometime -Mport /obj/machinery/field/generator/proc/draw_power(draw = 0, failsafe = FALSE, obj/machinery/field/generator/G = null, obj/machinery/field/generator/last = null) if((G && (G == src)) || (failsafe >= 8))//Loopin, set fail return 0 else failsafe++ if(power >= draw)//We have enough power power -= draw return 1 else//Need more power draw -= power power = 0 for(var/CG in connected_gens) var/obj/machinery/field/generator/FG = CG if(FG == last)//We just asked you continue if(G)//Another gen is askin for power and we dont have it if(FG.draw_power(draw,failsafe,G,src))//Can you take the load return 1 else return 0 else//We are askin another for power if(FG.draw_power(draw,failsafe,src,src)) return 1 else return 0 /obj/machinery/field/generator/proc/start_fields() if(state != FG_WELDED || !anchored) turn_off() return move_resist = INFINITY CanAtmosPass = ATMOS_PASS_NO air_update_turf(TRUE) addtimer(CALLBACK(src, PROC_REF(setup_field), 1), 1) addtimer(CALLBACK(src, PROC_REF(setup_field), 2), 2) addtimer(CALLBACK(src, PROC_REF(setup_field), 4), 3) addtimer(CALLBACK(src, PROC_REF(setup_field), 8), 4) addtimer(VARSET_CALLBACK(src, active, FG_ONLINE), 5) /obj/machinery/field/generator/proc/setup_field(NSEW) var/turf/T = loc if(!istype(T)) return 0 var/obj/machinery/field/generator/G = null var/steps = 0 if(!NSEW)//Make sure its ran right return 0 for(var/dist in 0 to 7) // checks out to 8 tiles away for another generator T = get_step(T, NSEW) if(T.density)//We cant shoot a field though this return 0 G = locate(/obj/machinery/field/generator) in T if(G) steps -= 1 if(!G.active) return 0 break for(var/TC in T.contents) var/atom/A = TC if(ismob(A)) continue if(A.density) return 0 steps++ if(!G) return 0 T = loc for(var/dist in 0 to steps) // creates each field tile var/field_dir = get_dir(T,get_step(G.loc, NSEW)) T = get_step(T, NSEW) if(!locate(/obj/machinery/field/containment) in T) var/obj/machinery/field/containment/CF = new(T) CF.set_master(src,G) CF.setDir(field_dir) fields += CF G.fields += CF for(var/mob/living/L in T) CF.on_entered(src, L) connected_gens |= G G.connected_gens |= src shield_floor(TRUE) update_appearance() /obj/machinery/field/generator/proc/cleanup() clean_up = 1 for (var/F in fields) qdel(F) shield_floor(FALSE) for(var/CG in connected_gens) var/obj/machinery/field/generator/FG = CG FG.connected_gens -= src if(!FG.clean_up)//Makes the other gens clean up as well FG.cleanup() connected_gens -= FG clean_up = 0 update_appearance() //This is here to help fight the "release singulo cos nobody will notice before the //singulo eats the evidence". It's not fool-proof but better than nothing. //I want to avoid using global variables. INVOKE_ASYNC(src, PROC_REF(notify_admins)) move_resist = initial(move_resist) /obj/machinery/field/generator/proc/shield_floor(create) if(connected_gens.len < 2) return var/CGcounter for(CGcounter = 1; CGcounter < connected_gens.len, CGcounter++) var/list/CGList = ((connected_gens[CGcounter].connected_gens & connected_gens[CGcounter+1].connected_gens)^src) if(!CGList.len) return var/obj/machinery/field/generator/CG = CGList[1] var/x_step var/y_step if(CG.x > x && CG.y > y) for(x_step=x; x_step <= CG.x; x_step++) for(y_step=y; y_step <= CG.y; y_step++) place_floor(locate(x_step,y_step,z),create) else if(CG.x > x && CG.y < y) for(x_step=x; x_step <= CG.x; x_step++) for(y_step=y; y_step >= CG.y; y_step--) place_floor(locate(x_step,y_step,z),create) else if(CG.x < x && CG.y > y) for(x_step=x; x_step >= CG.x; x_step--) for(y_step=y; y_step <= CG.y; y_step++) place_floor(locate(x_step,y_step,z),create) else for(x_step=x; x_step >= CG.x; x_step--) for(y_step=y; y_step >= CG.y; y_step--) place_floor(locate(x_step,y_step,z),create) /obj/machinery/field/generator/proc/place_floor(Location,create) if(create && !locate(/obj/effect/shield) in Location) new/obj/effect/shield(Location) else if(!create) var/obj/effect/shield/S=locate(/obj/effect/shield) in Location if(S) qdel(S) /obj/machinery/field/generator/proc/notify_admins() var/temp = TRUE //stops spam for(var/obj/singularity/O in GLOB.singularities) if(O.last_warning && temp) if((world.time - O.last_warning) > 50) //to stop message-spam temp = FALSE var/turf/T = get_turf(src) message_admins("A singulo exists and a containment field has failed at [ADMIN_VERBOSEJMP(T)].") investigate_log("has <font color='red'>failed</font> whilst a singulo exists at [AREACOORD(T)].", INVESTIGATE_SINGULO) notify_ghosts("IT'S LOOSE", source = src, action = NOTIFY_ORBIT, flashwindow = FALSE, ghost_sound = 'sound/machines/warning-buzzer.ogg', header = "IT'S LOOSE", notify_volume = 75) O.last_warning = world.time /obj/machinery/field/generator/shock(mob/living/user) if(fields.len) ..() /obj/machinery/field/generator/bump_field(atom/movable/AM as mob|obj) if(fields.len) ..() #undef FG_UNSECURED #undef FG_SECURED #undef FG_WELDED #undef FG_OFFLINE #undef FG_CHARGING #undef FG_ONLINE
0
0.967303
1
0.967303
game-dev
MEDIA
0.716988
game-dev
0.851756
1
0.851756
unresolved3169/Altay-Old
1,107
src/pocketmine/metadata/LevelMetadataStore.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\metadata; use pocketmine\level\Level; class LevelMetadataStore extends MetadataStore{ public function disambiguate(Metadatable $level, string $metadataKey) : string{ if(!($level instanceof Level)){ throw new \InvalidArgumentException("Argument must be a Level instance"); } return strtolower($level->getName()) . ":" . $metadataKey; } }
0
0.6807
1
0.6807
game-dev
MEDIA
0.646544
game-dev
0.606196
1
0.606196
i-Jiro/Unity3D-Turn_Based_RPG
1,247
Assets/Scripts/Battle/Abilities/Ability.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class Ability { public string Name; public float Multiplier { get; } public float ManaCost { get; } public GameObject Source { get; } protected readonly AbilityData abilityData; protected readonly List<StatusEffectData> statusEffectsDataList; protected readonly List<StatusEffect> statusEffects; public Ability(AbilityData data, GameObject source, List<StatusEffectData> statusEffectDataList) { abilityData = data; ManaCost = data.ManaCost; Name = data.AbilityName; Multiplier = data.Multiplier; statusEffectsDataList = statusEffectDataList; statusEffects = new List<StatusEffect>(); Source = source; InitializeStatusEffect(); } public Ability(AbilityData data, GameObject source) : this( data, source, null) {} protected void InitializeStatusEffect() { if(statusEffectsDataList != null) { foreach(StatusEffectData data in statusEffectsDataList) { StatusEffect statusEffect = data.Initialize(); statusEffects.Add(statusEffect); } } } }
0
0.580373
1
0.580373
game-dev
MEDIA
0.876442
game-dev
0.913451
1
0.913451
thomasxm/BOAZ_beta
24,589
Include/10.0.22621.0/um/10.0.22621.0/cppwinrt/winrt/impl/windows.gaming.preview.gamesenumeration.0.h
// C++/WinRT v2.0.220110.5 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #ifndef WINRT_Windows_Gaming_Preview_GamesEnumeration_0_H #define WINRT_Windows_Gaming_Preview_GamesEnumeration_0_H WINRT_EXPORT namespace winrt::Windows::ApplicationModel { struct AppDisplayInfo; } WINRT_EXPORT namespace winrt::Windows::Foundation { struct EventRegistrationToken; struct IAsyncAction; template <typename TResult> struct __declspec(empty_bases) IAsyncOperation; template <typename T> struct __declspec(empty_bases) IReference; } WINRT_EXPORT namespace winrt::Windows::Foundation::Collections { template <typename K, typename V> struct __declspec(empty_bases) IMapView; template <typename T> struct __declspec(empty_bases) IVectorView; template <typename T> struct __declspec(empty_bases) IVector; } WINRT_EXPORT namespace winrt::Windows::Storage { struct IStorageFile; } WINRT_EXPORT namespace winrt::Windows::Gaming::Preview::GamesEnumeration { enum class GameListCategory : int32_t { Candidate = 0, ConfirmedBySystem = 1, ConfirmedByUser = 2, }; enum class GameListEntryLaunchableState : int32_t { NotLaunchable = 0, ByLastRunningFullPath = 1, ByUserProvidedPath = 2, ByTile = 3, }; struct IGameListEntry; struct IGameListEntry2; struct IGameListStatics; struct IGameListStatics2; struct IGameModeConfiguration; struct IGameModeUserConfiguration; struct IGameModeUserConfigurationStatics; struct GameList; struct GameListEntry; struct GameModeConfiguration; struct GameModeUserConfiguration; struct GameListChangedEventHandler; struct GameListRemovedEventHandler; } namespace winrt::impl { template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry>{ using type = interface_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry2>{ using type = interface_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics>{ using type = interface_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics2>{ using type = interface_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeConfiguration>{ using type = interface_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfiguration>{ using type = interface_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfigurationStatics>{ using type = interface_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameList>{ using type = class_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry>{ using type = class_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeConfiguration>{ using type = class_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeUserConfiguration>{ using type = class_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListCategory>{ using type = enum_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntryLaunchableState>{ using type = enum_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler>{ using type = delegate_category; }; template <> struct category<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListRemovedEventHandler>{ using type = delegate_category; }; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameList> = L"Windows.Gaming.Preview.GamesEnumeration.GameList"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry> = L"Windows.Gaming.Preview.GamesEnumeration.GameListEntry"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeConfiguration> = L"Windows.Gaming.Preview.GamesEnumeration.GameModeConfiguration"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeUserConfiguration> = L"Windows.Gaming.Preview.GamesEnumeration.GameModeUserConfiguration"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListCategory> = L"Windows.Gaming.Preview.GamesEnumeration.GameListCategory"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntryLaunchableState> = L"Windows.Gaming.Preview.GamesEnumeration.GameListEntryLaunchableState"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry> = L"Windows.Gaming.Preview.GamesEnumeration.IGameListEntry"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry2> = L"Windows.Gaming.Preview.GamesEnumeration.IGameListEntry2"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics> = L"Windows.Gaming.Preview.GamesEnumeration.IGameListStatics"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics2> = L"Windows.Gaming.Preview.GamesEnumeration.IGameListStatics2"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeConfiguration> = L"Windows.Gaming.Preview.GamesEnumeration.IGameModeConfiguration"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfiguration> = L"Windows.Gaming.Preview.GamesEnumeration.IGameModeUserConfiguration"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfigurationStatics> = L"Windows.Gaming.Preview.GamesEnumeration.IGameModeUserConfigurationStatics"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler> = L"Windows.Gaming.Preview.GamesEnumeration.GameListChangedEventHandler"; template <> inline constexpr auto& name_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListRemovedEventHandler> = L"Windows.Gaming.Preview.GamesEnumeration.GameListRemovedEventHandler"; template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry>{ 0x735924D3,0x811F,0x4494,{ 0xB6,0x9C,0xC6,0x41,0xA0,0xC6,0x15,0x43 } }; // 735924D3-811F-4494-B69C-C641A0C61543 template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry2>{ 0xD84A8F8B,0x8749,0x4A25,{ 0x90,0xD3,0xF6,0xC5,0xA4,0x27,0x88,0x6D } }; // D84A8F8B-8749-4A25-90D3-F6C5A427886D template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics>{ 0x2DDD0F6F,0x9C66,0x4B05,{ 0x94,0x5C,0xD6,0xED,0x78,0x49,0x1B,0x8C } }; // 2DDD0F6F-9C66-4B05-945C-D6ED78491B8C template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics2>{ 0x395F2098,0xEA1A,0x45AA,{ 0x92,0x68,0xA8,0x39,0x05,0x68,0x6F,0x27 } }; // 395F2098-EA1A-45AA-9268-A83905686F27 template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeConfiguration>{ 0x78E591AF,0xB142,0x4EF0,{ 0x88,0x30,0x55,0xBC,0x2B,0xE4,0xF5,0xEA } }; // 78E591AF-B142-4EF0-8830-55BC2BE4F5EA template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfiguration>{ 0x72D34AF4,0x756B,0x470F,{ 0xA0,0xC2,0xBA,0x62,0xA9,0x07,0x95,0xDB } }; // 72D34AF4-756B-470F-A0C2-BA62A90795DB template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfigurationStatics>{ 0x6E50D97C,0x66EA,0x478E,{ 0xA4,0xA1,0xF5,0x7C,0x0E,0x8D,0x00,0xE7 } }; // 6E50D97C-66EA-478E-A4A1-F57C0E8D00E7 template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler>{ 0x25F6A421,0xD8F5,0x4D91,{ 0xB4,0x0E,0x53,0xD5,0xE8,0x6F,0xDE,0x64 } }; // 25F6A421-D8F5-4D91-B40E-53D5E86FDE64 template <> inline constexpr guid guid_v<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListRemovedEventHandler>{ 0x10C5648F,0x6C8F,0x4712,{ 0x9B,0x38,0x47,0x4B,0xC2,0x2E,0x76,0xD8 } }; // 10C5648F-6C8F-4712-9B38-474BC22E76D8 template <> struct default_interface<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry>{ using type = winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry; }; template <> struct default_interface<winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeConfiguration>{ using type = winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeConfiguration; }; template <> struct default_interface<winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeUserConfiguration>{ using type = winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfiguration; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_DisplayInfo(void**) noexcept = 0; virtual int32_t __stdcall LaunchAsync(void**) noexcept = 0; virtual int32_t __stdcall get_Category(int32_t*) noexcept = 0; virtual int32_t __stdcall get_Properties(void**) noexcept = 0; virtual int32_t __stdcall SetCategoryAsync(int32_t, void**) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry2> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_LaunchableState(int32_t*) noexcept = 0; virtual int32_t __stdcall get_LauncherExecutable(void**) noexcept = 0; virtual int32_t __stdcall get_LaunchParameters(void**) noexcept = 0; virtual int32_t __stdcall SetLauncherExecutableFileAsync(void*, void**) noexcept = 0; virtual int32_t __stdcall SetLauncherExecutableFileWithParamsAsync(void*, void*, void**) noexcept = 0; virtual int32_t __stdcall get_TitleId(void**) noexcept = 0; virtual int32_t __stdcall SetTitleIdAsync(void*, void**) noexcept = 0; virtual int32_t __stdcall get_GameModeConfiguration(void**) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall FindAllAsync(void**) noexcept = 0; virtual int32_t __stdcall FindAllAsyncPackageFamilyName(void*, void**) noexcept = 0; virtual int32_t __stdcall add_GameAdded(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_GameAdded(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_GameRemoved(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_GameRemoved(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_GameUpdated(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_GameUpdated(winrt::event_token) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics2> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall MergeEntriesAsync(void*, void*, void**) noexcept = 0; virtual int32_t __stdcall UnmergeEntryAsync(void*, void**) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeConfiguration> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_IsEnabled(bool*) noexcept = 0; virtual int32_t __stdcall put_IsEnabled(bool) noexcept = 0; virtual int32_t __stdcall get_RelatedProcessNames(void**) noexcept = 0; virtual int32_t __stdcall get_PercentGpuTimeAllocatedToGame(void**) noexcept = 0; virtual int32_t __stdcall put_PercentGpuTimeAllocatedToGame(void*) noexcept = 0; virtual int32_t __stdcall get_PercentGpuMemoryAllocatedToGame(void**) noexcept = 0; virtual int32_t __stdcall put_PercentGpuMemoryAllocatedToGame(void*) noexcept = 0; virtual int32_t __stdcall get_PercentGpuMemoryAllocatedToSystemCompositor(void**) noexcept = 0; virtual int32_t __stdcall put_PercentGpuMemoryAllocatedToSystemCompositor(void*) noexcept = 0; virtual int32_t __stdcall get_MaxCpuCount(void**) noexcept = 0; virtual int32_t __stdcall put_MaxCpuCount(void*) noexcept = 0; virtual int32_t __stdcall get_CpuExclusivityMaskLow(void**) noexcept = 0; virtual int32_t __stdcall put_CpuExclusivityMaskLow(void*) noexcept = 0; virtual int32_t __stdcall get_CpuExclusivityMaskHigh(void**) noexcept = 0; virtual int32_t __stdcall put_CpuExclusivityMaskHigh(void*) noexcept = 0; virtual int32_t __stdcall get_AffinitizeToExclusiveCpus(bool*) noexcept = 0; virtual int32_t __stdcall put_AffinitizeToExclusiveCpus(bool) noexcept = 0; virtual int32_t __stdcall SaveAsync(void**) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfiguration> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_GamingRelatedProcessNames(void**) noexcept = 0; virtual int32_t __stdcall SaveAsync(void**) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfigurationStatics> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall GetDefault(void**) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*) noexcept = 0; }; }; template <> struct abi<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListRemovedEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*) noexcept = 0; }; }; template <typename D> struct consume_Windows_Gaming_Preview_GamesEnumeration_IGameListEntry { [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::AppDisplayInfo) DisplayInfo() const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<bool>) LaunchAsync() const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListCategory) Category() const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IMapView<hstring, winrt::Windows::Foundation::IInspectable>) Properties() const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SetCategoryAsync(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListCategory const& value) const; }; template <> struct consume<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry> { template <typename D> using type = consume_Windows_Gaming_Preview_GamesEnumeration_IGameListEntry<D>; }; template <typename D> struct consume_Windows_Gaming_Preview_GamesEnumeration_IGameListEntry2 { [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntryLaunchableState) LaunchableState() const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Storage::IStorageFile) LauncherExecutable() const; [[nodiscard]] WINRT_IMPL_AUTO(hstring) LaunchParameters() const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SetLauncherExecutableFileAsync(winrt::Windows::Storage::IStorageFile const& executableFile) const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SetLauncherExecutableFileAsync(winrt::Windows::Storage::IStorageFile const& executableFile, param::hstring const& launchParams) const; [[nodiscard]] WINRT_IMPL_AUTO(hstring) TitleId() const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SetTitleIdAsync(param::hstring const& id) const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeConfiguration) GameModeConfiguration() const; }; template <> struct consume<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListEntry2> { template <typename D> using type = consume_Windows_Gaming_Preview_GamesEnumeration_IGameListEntry2<D>; }; template <typename D> struct consume_Windows_Gaming_Preview_GamesEnumeration_IGameListStatics { WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry>>) FindAllAsync() const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry>>) FindAllAsync(param::hstring const& packageFamilyName) const; WINRT_IMPL_AUTO(winrt::event_token) GameAdded(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler const& handler) const; using GameAdded_revoker = impl::event_revoker<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics, &impl::abi_t<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics>::remove_GameAdded>; [[nodiscard]] GameAdded_revoker GameAdded(auto_revoke_t, winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler const& handler) const; WINRT_IMPL_AUTO(void) GameAdded(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) GameRemoved(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListRemovedEventHandler const& handler) const; using GameRemoved_revoker = impl::event_revoker<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics, &impl::abi_t<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics>::remove_GameRemoved>; [[nodiscard]] GameRemoved_revoker GameRemoved(auto_revoke_t, winrt::Windows::Gaming::Preview::GamesEnumeration::GameListRemovedEventHandler const& handler) const; WINRT_IMPL_AUTO(void) GameRemoved(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) GameUpdated(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler const& handler) const; using GameUpdated_revoker = impl::event_revoker<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics, &impl::abi_t<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics>::remove_GameUpdated>; [[nodiscard]] GameUpdated_revoker GameUpdated(auto_revoke_t, winrt::Windows::Gaming::Preview::GamesEnumeration::GameListChangedEventHandler const& handler) const; WINRT_IMPL_AUTO(void) GameUpdated(winrt::event_token const& token) const noexcept; }; template <> struct consume<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics> { template <typename D> using type = consume_Windows_Gaming_Preview_GamesEnumeration_IGameListStatics<D>; }; template <typename D> struct consume_Windows_Gaming_Preview_GamesEnumeration_IGameListStatics2 { WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry>) MergeEntriesAsync(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry const& left, winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry const& right) const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry>>) UnmergeEntryAsync(winrt::Windows::Gaming::Preview::GamesEnumeration::GameListEntry const& mergedEntry) const; }; template <> struct consume<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameListStatics2> { template <typename D> using type = consume_Windows_Gaming_Preview_GamesEnumeration_IGameListStatics2<D>; }; template <typename D> struct consume_Windows_Gaming_Preview_GamesEnumeration_IGameModeConfiguration { [[nodiscard]] WINRT_IMPL_AUTO(bool) IsEnabled() const; WINRT_IMPL_AUTO(void) IsEnabled(bool value) const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVector<hstring>) RelatedProcessNames() const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::IReference<int32_t>) PercentGpuTimeAllocatedToGame() const; WINRT_IMPL_AUTO(void) PercentGpuTimeAllocatedToGame(winrt::Windows::Foundation::IReference<int32_t> const& value) const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::IReference<int32_t>) PercentGpuMemoryAllocatedToGame() const; WINRT_IMPL_AUTO(void) PercentGpuMemoryAllocatedToGame(winrt::Windows::Foundation::IReference<int32_t> const& value) const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::IReference<int32_t>) PercentGpuMemoryAllocatedToSystemCompositor() const; WINRT_IMPL_AUTO(void) PercentGpuMemoryAllocatedToSystemCompositor(winrt::Windows::Foundation::IReference<int32_t> const& value) const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::IReference<int32_t>) MaxCpuCount() const; WINRT_IMPL_AUTO(void) MaxCpuCount(winrt::Windows::Foundation::IReference<int32_t> const& value) const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::IReference<int32_t>) CpuExclusivityMaskLow() const; WINRT_IMPL_AUTO(void) CpuExclusivityMaskLow(winrt::Windows::Foundation::IReference<int32_t> const& value) const; [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::IReference<int32_t>) CpuExclusivityMaskHigh() const; WINRT_IMPL_AUTO(void) CpuExclusivityMaskHigh(winrt::Windows::Foundation::IReference<int32_t> const& value) const; [[nodiscard]] WINRT_IMPL_AUTO(bool) AffinitizeToExclusiveCpus() const; WINRT_IMPL_AUTO(void) AffinitizeToExclusiveCpus(bool value) const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SaveAsync() const; }; template <> struct consume<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeConfiguration> { template <typename D> using type = consume_Windows_Gaming_Preview_GamesEnumeration_IGameModeConfiguration<D>; }; template <typename D> struct consume_Windows_Gaming_Preview_GamesEnumeration_IGameModeUserConfiguration { [[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVector<hstring>) GamingRelatedProcessNames() const; WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SaveAsync() const; }; template <> struct consume<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfiguration> { template <typename D> using type = consume_Windows_Gaming_Preview_GamesEnumeration_IGameModeUserConfiguration<D>; }; template <typename D> struct consume_Windows_Gaming_Preview_GamesEnumeration_IGameModeUserConfigurationStatics { WINRT_IMPL_AUTO(winrt::Windows::Gaming::Preview::GamesEnumeration::GameModeUserConfiguration) GetDefault() const; }; template <> struct consume<winrt::Windows::Gaming::Preview::GamesEnumeration::IGameModeUserConfigurationStatics> { template <typename D> using type = consume_Windows_Gaming_Preview_GamesEnumeration_IGameModeUserConfigurationStatics<D>; }; } #endif
0
0.710144
1
0.710144
game-dev
MEDIA
0.793419
game-dev
0.634357
1
0.634357
libgdx/gdx-ai
4,339
gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/MatchVelocity.java
/******************************************************************************* * Copyright 2014 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.ai.steer.behaviors; import com.badlogic.gdx.ai.steer.Limiter; import com.badlogic.gdx.ai.steer.Steerable; import com.badlogic.gdx.ai.steer.SteeringAcceleration; import com.badlogic.gdx.ai.steer.SteeringBehavior; import com.badlogic.gdx.math.Vector; /** This steering behavior produces a linear acceleration trying to match target's velocity. It does not produce any angular * acceleration. * * @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface * * @author davebaol */ public class MatchVelocity<T extends Vector<T>> extends SteeringBehavior<T> { /** The target of this behavior */ protected Steerable<T> target; /** The time over which to achieve target speed */ protected float timeToTarget; /** Creates a {@code MatchVelocity} behavior for the given owner. No target is set. The maxLinearAcceleration is set to 100. The * timeToTarget is set to 0.1 seconds. * @param owner the owner of this behavior. */ public MatchVelocity (Steerable<T> owner) { this(owner, null); } /** Creates a {@code MatchVelocity} behavior for the given owner and target. The timeToTarget is set to 0.1 seconds. * @param owner the owner of this behavior * @param target the target of this behavior. */ public MatchVelocity (Steerable<T> owner, Steerable<T> target) { this(owner, target, 0.1f); } /** Creates a {@code MatchVelocity} behavior for the given owner, target and timeToTarget. * @param owner the owner of this behavior * @param target the target of this behavior * @param timeToTarget the time over which to achieve target speed. */ public MatchVelocity (Steerable<T> owner, Steerable<T> target, float timeToTarget) { super(owner); this.target = target; this.timeToTarget = timeToTarget; } @Override protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) { // Acceleration tries to get to the target velocity without exceeding max acceleration steering.linear.set(target.getLinearVelocity()).sub(owner.getLinearVelocity()).scl(1f / timeToTarget) .limit(getActualLimiter().getMaxLinearAcceleration()); // No angular acceleration steering.angular = 0; // Output steering acceleration return steering; } /** Returns the target whose velocity should be matched. */ public Steerable<T> getTarget () { return target; } /** Sets the target whose velocity should be matched. * @param target the target to set * @return this behavior for chaining. */ public MatchVelocity<T> setTarget (Steerable<T> target) { this.target = target; return this; } /** Returns the time over which to achieve target speed. */ public float getTimeToTarget () { return timeToTarget; } /** Sets the time over which to achieve target speed. * @param timeToTarget the time to set * @return this behavior for chaining. */ public MatchVelocity<T> setTimeToTarget (float timeToTarget) { this.timeToTarget = timeToTarget; return this; } // // Setters overridden in order to fix the correct return type for chaining // @Override public MatchVelocity<T> setOwner (Steerable<T> owner) { this.owner = owner; return this; } @Override public MatchVelocity<T> setEnabled (boolean enabled) { this.enabled = enabled; return this; } /** Sets the limiter of this steering behavior. The given limiter must at least take care of the maximum linear acceleration. * @return this behavior for chaining. */ @Override public MatchVelocity<T> setLimiter (Limiter limiter) { this.limiter = limiter; return this; } }
0
0.916468
1
0.916468
game-dev
MEDIA
0.813667
game-dev
0.919936
1
0.919936
Nebukam/PCGExtendedToolkit
1,382
Source/PCGExtendedToolkit/Private/Debug/PCGExFlushDebug.cpp
// Copyright 2025 Timothé Lapetite and contributors // Released under the MIT license https://opensource.org/license/MIT/ #include "Debug/PCGExFlushDebug.h" #include "PCGPin.h" #include "PCGGraph.h" #include "DrawDebugHelpers.h" #define LOCTEXT_NAMESPACE "PCGExGraphSettings" #define PCGEX_NAMESPACE Debug #pragma region UPCGSettings interface TArray<FPCGPinProperties> UPCGExDebugSettings::InputPinProperties() const { TArray<FPCGPinProperties> PinProperties; PCGEX_PIN_ANY(PCGPinConstants::DefaultInputLabel, "In.", Required) return PinProperties; } TArray<FPCGPinProperties> UPCGExDebugSettings::OutputPinProperties() const { TArray<FPCGPinProperties> PinProperties; PCGEX_PIN_ANY(PCGPinConstants::DefaultInputLabel, "Out.", Required) return PinProperties; } FPCGElementPtr UPCGExDebugSettings::CreateElement() const { return MakeShared<FPCGExDebugElement>(); } #pragma endregion bool FPCGExDebugElement::ExecuteInternal(FPCGContext* InContext) const { PCGEX_CONTEXT_AND_SETTINGS(Debug) #if WITH_EDITOR if (!Settings->bPCGExDebug) { DisabledPassThroughData(Context); return true; } if (Context->bWait) { Context->bWait = false; return false; } FlushPersistentDebugLines(Context->GetWorld()); FlushDebugStrings(Context->GetWorld()); #endif DisabledPassThroughData(Context); return true; } #undef LOCTEXT_NAMESPACE #undef PCGEX_NAMESPACE
0
0.689298
1
0.689298
game-dev
MEDIA
0.454553
game-dev
0.761915
1
0.761915
SethRobinson/proton
25,418
shared/Irrlicht/source/Irrlicht/libpng/powerpc/filter_vsx_intrinsics.c
/* filter_vsx_intrinsics.c - PowerPC optimised filter functions * * Copyright (c) 2018 Cosmin Truta * Copyright (c) 2017 Glenn Randers-Pehrson * Written by Vadim Barkov, 2017. * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h */ #include <stdio.h> #include <stdint.h> #include "../pngpriv.h" #ifdef PNG_READ_SUPPORTED /* This code requires -maltivec and -mvsx on the command line: */ #if PNG_POWERPC_VSX_IMPLEMENTATION == 1 /* intrinsics code from pngpriv.h */ #include <altivec.h> #if PNG_POWERPC_VSX_OPT > 0 #ifndef __VSX__ # error "This code requires VSX support (POWER7 and later). Please provide -mvsx compiler flag." #endif #define vec_ld_unaligned(vec,data) vec = vec_vsx_ld(0,data) #define vec_st_unaligned(vec,data) vec_vsx_st(vec,0,data) /* Functions in this file look at most 3 pixels (a,b,c) to predict the 4th (d). * They're positioned like this: * prev: c b * row: a d * The Sub filter predicts d=a, Avg d=(a+b)/2, and Paeth predicts d to be * whichever of a, b, or c is closest to p=a+b-c. * ( this is taken from ../intel/filter_sse2_intrinsics.c ) */ #define vsx_declare_common_vars(row_info,row,prev_row,offset) \ png_byte i;\ png_bytep rp = row + offset;\ png_const_bytep pp = prev_row;\ size_t unaligned_top = 16 - (((size_t)rp % 16));\ size_t istop;\ if(unaligned_top == 16)\ unaligned_top = 0;\ istop = row_info->rowbytes;\ if((unaligned_top < istop))\ istop -= unaligned_top;\ else{\ unaligned_top = istop;\ istop = 0;\ } void png_read_filter_row_up_vsx(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { vector unsigned char rp_vec; vector unsigned char pp_vec; vsx_declare_common_vars(row_info,row,prev_row,0) /* Altivec operations require 16-byte aligned data * but input can be unaligned. So we calculate * unaligned part as usual. */ for (i = 0; i < unaligned_top; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); rp++; } /* Using SIMD while we can */ while( istop >= 16 ) { rp_vec = vec_ld(0,rp); vec_ld_unaligned(pp_vec,pp); rp_vec = vec_add(rp_vec,pp_vec); vec_st(rp_vec,0,rp); pp += 16; rp += 16; istop -= 16; } if(istop > 0) { /* If byte count of row is not divisible by 16 * we will process remaining part as usual */ for (i = 0; i < istop; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); rp++; } } } static const vector unsigned char VSX_LEFTSHIFTED1_4 = {16,16,16,16, 0, 1, 2, 3,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_LEFTSHIFTED2_4 = {16,16,16,16,16,16,16,16, 4, 5, 6, 7,16,16,16,16}; static const vector unsigned char VSX_LEFTSHIFTED3_4 = {16,16,16,16,16,16,16,16,16,16,16,16, 8, 9,10,11}; static const vector unsigned char VSX_LEFTSHIFTED1_3 = {16,16,16, 0, 1, 2,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_LEFTSHIFTED2_3 = {16,16,16,16,16,16, 3, 4, 5,16,16,16,16,16,16,16}; static const vector unsigned char VSX_LEFTSHIFTED3_3 = {16,16,16,16,16,16,16,16,16, 6, 7, 8,16,16,16,16}; static const vector unsigned char VSX_LEFTSHIFTED4_3 = {16,16,16,16,16,16,16,16,16,16,16,16, 9,10,11,16}; static const vector unsigned char VSX_NOT_SHIFTED1_4 = {16,16,16,16, 4, 5, 6, 7,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_NOT_SHIFTED2_4 = {16,16,16,16,16,16,16,16, 8, 9,10,11,16,16,16,16}; static const vector unsigned char VSX_NOT_SHIFTED3_4 = {16,16,16,16,16,16,16,16,16,16,16,16,12,13,14,15}; static const vector unsigned char VSX_NOT_SHIFTED1_3 = {16,16,16, 3, 4, 5,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_NOT_SHIFTED2_3 = {16,16,16,16,16,16, 6, 7, 8,16,16,16,16,16,16,16}; static const vector unsigned char VSX_NOT_SHIFTED3_3 = {16,16,16,16,16,16,16,16,16, 9,10,11,16,16,16,16}; static const vector unsigned char VSX_NOT_SHIFTED4_3 = {16,16,16,16,16,16,16,16,16,16,16,16,12,13,14,16}; static const vector unsigned char VSX_CHAR_ZERO = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; #ifdef __LITTLE_ENDIAN__ static const vector unsigned char VSX_CHAR_TO_SHORT1_4 = { 4,16, 5,16, 6,16, 7,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT2_4 = { 8,16, 9,16,10,16,11,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT3_4 = {12,16,13,16,14,16,15,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR1_4 = {16,16,16,16, 0, 2, 4, 6,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR2_4 = {16,16,16,16,16,16,16,16, 0, 2, 4, 6,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR3_4 = {16,16,16,16,16,16,16,16,16,16,16,16, 0, 2, 4, 6}; static const vector unsigned char VSX_CHAR_TO_SHORT1_3 = { 3,16, 4,16, 5,16,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT2_3 = { 6,16, 7,16, 8,16,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT3_3 = { 9,16,10,16,11,16,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT4_3 = {12,16,13,16,14,16,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR1_3 = {16,16,16, 0, 2, 4,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR2_3 = {16,16,16,16,16,16, 0, 2, 4,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR3_3 = {16,16,16,16,16,16,16,16,16, 0, 2, 4,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR4_3 = {16,16,16,16,16,16,16,16,16,16,16,16, 0, 2, 4,16}; #elif defined(__BIG_ENDIAN__) static const vector unsigned char VSX_CHAR_TO_SHORT1_4 = {16, 4,16, 5,16, 6,16, 7,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT2_4 = {16, 8,16, 9,16,10,16,11,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT3_4 = {16,12,16,13,16,14,16,15,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR1_4 = {16,16,16,16, 1, 3, 5, 7,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR2_4 = {16,16,16,16,16,16,16,16, 1, 3, 5, 7,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR3_4 = {16,16,16,16,16,16,16,16,16,16,16,16, 1, 3, 5, 7}; static const vector unsigned char VSX_CHAR_TO_SHORT1_3 = {16, 3,16, 4,16, 5,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT2_3 = {16, 6,16, 7,16, 8,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT3_3 = {16, 9,16,10,16,11,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_CHAR_TO_SHORT4_3 = {16,12,16,13,16,14,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR1_3 = {16,16,16, 1, 3, 5,16,16,16,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR2_3 = {16,16,16,16,16,16, 1, 3, 5,16,16,16,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR3_3 = {16,16,16,16,16,16,16,16,16, 1, 3, 5,16,16,16,16}; static const vector unsigned char VSX_SHORT_TO_CHAR4_3 = {16,16,16,16,16,16,16,16,16,16,16,16, 1, 3, 5,16}; #endif #define vsx_char_to_short(vec,offset,bpp) (vector unsigned short)vec_perm((vec),VSX_CHAR_ZERO,VSX_CHAR_TO_SHORT##offset##_##bpp) #define vsx_short_to_char(vec,offset,bpp) vec_perm(((vector unsigned char)(vec)),VSX_CHAR_ZERO,VSX_SHORT_TO_CHAR##offset##_##bpp) #ifdef PNG_USE_ABS # define vsx_abs(number) abs(number) #else # define vsx_abs(number) (number > 0) ? (number) : -(number) #endif void png_read_filter_row_sub4_vsx(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_byte bpp = 4; vector unsigned char rp_vec; vector unsigned char part_vec; vsx_declare_common_vars(row_info,row,prev_row,bpp) PNG_UNUSED(pp) /* Altivec operations require 16-byte aligned data * but input can be unaligned. So we calculate * unaligned part as usual. */ for (i = 0; i < unaligned_top; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } /* Using SIMD while we can */ while( istop >= 16 ) { for(i=0;i < bpp ; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } rp -= bpp; rp_vec = vec_ld(0,rp); part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED1_4); rp_vec = vec_add(rp_vec,part_vec); part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED2_4); rp_vec = vec_add(rp_vec,part_vec); part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED3_4); rp_vec = vec_add(rp_vec,part_vec); vec_st(rp_vec,0,rp); rp += 16; istop -= 16; } if(istop > 0) for (i = 0; i < istop % 16; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp - bpp))) & 0xff); rp++; } } void png_read_filter_row_sub3_vsx(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_byte bpp = 3; vector unsigned char rp_vec; vector unsigned char part_vec; vsx_declare_common_vars(row_info,row,prev_row,bpp) PNG_UNUSED(pp) /* Altivec operations require 16-byte aligned data * but input can be unaligned. So we calculate * unaligned part as usual. */ for (i = 0; i < unaligned_top; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } /* Using SIMD while we can */ while( istop >= 16 ) { for(i=0;i < bpp ; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } rp -= bpp; rp_vec = vec_ld(0,rp); part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED1_3); rp_vec = vec_add(rp_vec,part_vec); part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED2_3); rp_vec = vec_add(rp_vec,part_vec); part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED3_3); rp_vec = vec_add(rp_vec,part_vec); part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED4_3); rp_vec = vec_add(rp_vec,part_vec); vec_st(rp_vec,0,rp); rp += 15; istop -= 16; /* Since 16 % bpp = 16 % 3 = 1, last element of array must * be proceeded manually */ *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } if(istop > 0) for (i = 0; i < istop % 16; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } } void png_read_filter_row_avg4_vsx(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_byte bpp = 4; vector unsigned char rp_vec; vector unsigned char pp_vec; vector unsigned char pp_part_vec; vector unsigned char rp_part_vec; vector unsigned char avg_vec; vsx_declare_common_vars(row_info,row,prev_row,bpp) rp -= bpp; if(istop >= bpp) istop -= bpp; for (i = 0; i < bpp; i++) { *rp = (png_byte)(((int)(*rp) + ((int)(*pp++) / 2 )) & 0xff); rp++; } /* Altivec operations require 16-byte aligned data * but input can be unaligned. So we calculate * unaligned part as usual. */ for (i = 0; i < unaligned_top; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } /* Using SIMD while we can */ while( istop >= 16 ) { for(i=0;i < bpp ; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } rp -= bpp; pp -= bpp; vec_ld_unaligned(pp_vec,pp); rp_vec = vec_ld(0,rp); rp_part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED1_4); pp_part_vec = vec_perm(pp_vec,VSX_CHAR_ZERO,VSX_NOT_SHIFTED1_4); avg_vec = vec_avg(rp_part_vec,pp_part_vec); avg_vec = vec_sub(avg_vec, vec_and(vec_xor(rp_part_vec,pp_part_vec),vec_splat_u8(1))); rp_vec = vec_add(rp_vec,avg_vec); rp_part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED2_4); pp_part_vec = vec_perm(pp_vec,VSX_CHAR_ZERO,VSX_NOT_SHIFTED2_4); avg_vec = vec_avg(rp_part_vec,pp_part_vec); avg_vec = vec_sub(avg_vec, vec_and(vec_xor(rp_part_vec,pp_part_vec),vec_splat_u8(1))); rp_vec = vec_add(rp_vec,avg_vec); rp_part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED3_4); pp_part_vec = vec_perm(pp_vec,VSX_CHAR_ZERO,VSX_NOT_SHIFTED3_4); avg_vec = vec_avg(rp_part_vec,pp_part_vec); avg_vec = vec_sub(avg_vec, vec_and(vec_xor(rp_part_vec,pp_part_vec),vec_splat_u8(1))); rp_vec = vec_add(rp_vec,avg_vec); vec_st(rp_vec,0,rp); rp += 16; pp += 16; istop -= 16; } if(istop > 0) for (i = 0; i < istop % 16; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } } void png_read_filter_row_avg3_vsx(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_byte bpp = 3; vector unsigned char rp_vec; vector unsigned char pp_vec; vector unsigned char pp_part_vec; vector unsigned char rp_part_vec; vector unsigned char avg_vec; vsx_declare_common_vars(row_info,row,prev_row,bpp) rp -= bpp; if(istop >= bpp) istop -= bpp; for (i = 0; i < bpp; i++) { *rp = (png_byte)(((int)(*rp) + ((int)(*pp++) / 2 )) & 0xff); rp++; } /* Altivec operations require 16-byte aligned data * but input can be unaligned. So we calculate * unaligned part as usual. */ for (i = 0; i < unaligned_top; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } /* Using SIMD while we can */ while( istop >= 16 ) { for(i=0;i < bpp ; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } rp -= bpp; pp -= bpp; vec_ld_unaligned(pp_vec,pp); rp_vec = vec_ld(0,rp); rp_part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED1_3); pp_part_vec = vec_perm(pp_vec,VSX_CHAR_ZERO,VSX_NOT_SHIFTED1_3); avg_vec = vec_avg(rp_part_vec,pp_part_vec); avg_vec = vec_sub(avg_vec, vec_and(vec_xor(rp_part_vec,pp_part_vec),vec_splat_u8(1))); rp_vec = vec_add(rp_vec,avg_vec); rp_part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED2_3); pp_part_vec = vec_perm(pp_vec,VSX_CHAR_ZERO,VSX_NOT_SHIFTED2_3); avg_vec = vec_avg(rp_part_vec,pp_part_vec); avg_vec = vec_sub(avg_vec, vec_and(vec_xor(rp_part_vec,pp_part_vec),vec_splat_u8(1))); rp_vec = vec_add(rp_vec,avg_vec); rp_part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED3_3); pp_part_vec = vec_perm(pp_vec,VSX_CHAR_ZERO,VSX_NOT_SHIFTED3_3); avg_vec = vec_avg(rp_part_vec,pp_part_vec); avg_vec = vec_sub(avg_vec, vec_and(vec_xor(rp_part_vec,pp_part_vec),vec_splat_u8(1))); rp_vec = vec_add(rp_vec,avg_vec); rp_part_vec = vec_perm(rp_vec,VSX_CHAR_ZERO,VSX_LEFTSHIFTED4_3); pp_part_vec = vec_perm(pp_vec,VSX_CHAR_ZERO,VSX_NOT_SHIFTED4_3); avg_vec = vec_avg(rp_part_vec,pp_part_vec); avg_vec = vec_sub(avg_vec, vec_and(vec_xor(rp_part_vec,pp_part_vec),vec_splat_u8(1))); rp_vec = vec_add(rp_vec,avg_vec); vec_st(rp_vec,0,rp); rp += 15; pp += 15; istop -= 16; /* Since 16 % bpp = 16 % 3 = 1, last element of array must * be proceeded manually */ *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } if(istop > 0) for (i = 0; i < istop % 16; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } } /* Bytewise c ? t : e. */ #define if_then_else(c,t,e) vec_sel(e,t,c) #define vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) {\ c = *(pp - bpp);\ a = *(rp - bpp);\ b = *pp++;\ p = b - c;\ pc = a - c;\ pa = vsx_abs(p);\ pb = vsx_abs(pc);\ pc = vsx_abs(p + pc);\ if (pb < pa) pa = pb, a = b;\ if (pc < pa) a = c;\ a += *rp;\ *rp++ = (png_byte)a;\ } void png_read_filter_row_paeth4_vsx(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_byte bpp = 4; int a, b, c, pa, pb, pc, p; vector unsigned char rp_vec; vector unsigned char pp_vec; vector unsigned short a_vec,b_vec,c_vec,nearest_vec; vector signed short pa_vec,pb_vec,pc_vec,smallest_vec; vsx_declare_common_vars(row_info,row,prev_row,bpp) rp -= bpp; if(istop >= bpp) istop -= bpp; /* Process the first pixel in the row completely (this is the same as 'up' * because there is only one candidate predictor for the first row). */ for(i = 0; i < bpp ; i++) { *rp = (png_byte)( *rp + *pp); rp++; pp++; } for(i = 0; i < unaligned_top ; i++) { vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) } while( istop >= 16) { for(i = 0; i < bpp ; i++) { vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) } rp -= bpp; pp -= bpp; rp_vec = vec_ld(0,rp); vec_ld_unaligned(pp_vec,pp); a_vec = vsx_char_to_short(vec_perm(rp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED1_4),1,4); b_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_NOT_SHIFTED1_4),1,4); c_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED1_4),1,4); pa_vec = (vector signed short) vec_sub(b_vec,c_vec); pb_vec = (vector signed short) vec_sub(a_vec , c_vec); pc_vec = vec_add(pa_vec,pb_vec); pa_vec = vec_abs(pa_vec); pb_vec = vec_abs(pb_vec); pc_vec = vec_abs(pc_vec); smallest_vec = vec_min(pc_vec, vec_min(pa_vec,pb_vec)); nearest_vec = if_then_else( vec_cmpeq(pa_vec,smallest_vec), a_vec, if_then_else( vec_cmpeq(pb_vec,smallest_vec), b_vec, c_vec ) ); rp_vec = vec_add(rp_vec,(vsx_short_to_char(nearest_vec,1,4))); a_vec = vsx_char_to_short(vec_perm(rp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED2_4),2,4); b_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_NOT_SHIFTED2_4),2,4); c_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED2_4),2,4); pa_vec = (vector signed short) vec_sub(b_vec,c_vec); pb_vec = (vector signed short) vec_sub(a_vec , c_vec); pc_vec = vec_add(pa_vec,pb_vec); pa_vec = vec_abs(pa_vec); pb_vec = vec_abs(pb_vec); pc_vec = vec_abs(pc_vec); smallest_vec = vec_min(pc_vec, vec_min(pa_vec,pb_vec)); nearest_vec = if_then_else( vec_cmpeq(pa_vec,smallest_vec), a_vec, if_then_else( vec_cmpeq(pb_vec,smallest_vec), b_vec, c_vec ) ); rp_vec = vec_add(rp_vec,(vsx_short_to_char(nearest_vec,2,4))); a_vec = vsx_char_to_short(vec_perm(rp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED3_4),3,4); b_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_NOT_SHIFTED3_4),3,4); c_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED3_4),3,4); pa_vec = (vector signed short) vec_sub(b_vec,c_vec); pb_vec = (vector signed short) vec_sub(a_vec , c_vec); pc_vec = vec_add(pa_vec,pb_vec); pa_vec = vec_abs(pa_vec); pb_vec = vec_abs(pb_vec); pc_vec = vec_abs(pc_vec); smallest_vec = vec_min(pc_vec, vec_min(pa_vec,pb_vec)); nearest_vec = if_then_else( vec_cmpeq(pa_vec,smallest_vec), a_vec, if_then_else( vec_cmpeq(pb_vec,smallest_vec), b_vec, c_vec ) ); rp_vec = vec_add(rp_vec,(vsx_short_to_char(nearest_vec,3,4))); vec_st(rp_vec,0,rp); rp += 16; pp += 16; istop -= 16; } if(istop > 0) for (i = 0; i < istop % 16; i++) { vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) } } void png_read_filter_row_paeth3_vsx(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_byte bpp = 3; int a, b, c, pa, pb, pc, p; vector unsigned char rp_vec; vector unsigned char pp_vec; vector unsigned short a_vec,b_vec,c_vec,nearest_vec; vector signed short pa_vec,pb_vec,pc_vec,smallest_vec; vsx_declare_common_vars(row_info,row,prev_row,bpp) rp -= bpp; if(istop >= bpp) istop -= bpp; /* Process the first pixel in the row completely (this is the same as 'up' * because there is only one candidate predictor for the first row). */ for(i = 0; i < bpp ; i++) { *rp = (png_byte)( *rp + *pp); rp++; pp++; } for(i = 0; i < unaligned_top ; i++) { vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) } while( istop >= 16) { for(i = 0; i < bpp ; i++) { vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) } rp -= bpp; pp -= bpp; rp_vec = vec_ld(0,rp); vec_ld_unaligned(pp_vec,pp); a_vec = vsx_char_to_short(vec_perm(rp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED1_3),1,3); b_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_NOT_SHIFTED1_3),1,3); c_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED1_3),1,3); pa_vec = (vector signed short) vec_sub(b_vec,c_vec); pb_vec = (vector signed short) vec_sub(a_vec , c_vec); pc_vec = vec_add(pa_vec,pb_vec); pa_vec = vec_abs(pa_vec); pb_vec = vec_abs(pb_vec); pc_vec = vec_abs(pc_vec); smallest_vec = vec_min(pc_vec, vec_min(pa_vec,pb_vec)); nearest_vec = if_then_else( vec_cmpeq(pa_vec,smallest_vec), a_vec, if_then_else( vec_cmpeq(pb_vec,smallest_vec), b_vec, c_vec ) ); rp_vec = vec_add(rp_vec,(vsx_short_to_char(nearest_vec,1,3))); a_vec = vsx_char_to_short(vec_perm(rp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED2_3),2,3); b_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_NOT_SHIFTED2_3),2,3); c_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED2_3),2,3); pa_vec = (vector signed short) vec_sub(b_vec,c_vec); pb_vec = (vector signed short) vec_sub(a_vec , c_vec); pc_vec = vec_add(pa_vec,pb_vec); pa_vec = vec_abs(pa_vec); pb_vec = vec_abs(pb_vec); pc_vec = vec_abs(pc_vec); smallest_vec = vec_min(pc_vec, vec_min(pa_vec,pb_vec)); nearest_vec = if_then_else( vec_cmpeq(pa_vec,smallest_vec), a_vec, if_then_else( vec_cmpeq(pb_vec,smallest_vec), b_vec, c_vec ) ); rp_vec = vec_add(rp_vec,(vsx_short_to_char(nearest_vec,2,3))); a_vec = vsx_char_to_short(vec_perm(rp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED3_3),3,3); b_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_NOT_SHIFTED3_3),3,3); c_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED3_3),3,3); pa_vec = (vector signed short) vec_sub(b_vec,c_vec); pb_vec = (vector signed short) vec_sub(a_vec , c_vec); pc_vec = vec_add(pa_vec,pb_vec); pa_vec = vec_abs(pa_vec); pb_vec = vec_abs(pb_vec); pc_vec = vec_abs(pc_vec); smallest_vec = vec_min(pc_vec, vec_min(pa_vec,pb_vec)); nearest_vec = if_then_else( vec_cmpeq(pa_vec,smallest_vec), a_vec, if_then_else( vec_cmpeq(pb_vec,smallest_vec), b_vec, c_vec ) ); rp_vec = vec_add(rp_vec,(vsx_short_to_char(nearest_vec,3,3))); a_vec = vsx_char_to_short(vec_perm(rp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED4_3),4,3); b_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_NOT_SHIFTED4_3),4,3); c_vec = vsx_char_to_short(vec_perm(pp_vec , VSX_CHAR_ZERO , VSX_LEFTSHIFTED4_3),4,3); pa_vec = (vector signed short) vec_sub(b_vec,c_vec); pb_vec = (vector signed short) vec_sub(a_vec , c_vec); pc_vec = vec_add(pa_vec,pb_vec); pa_vec = vec_abs(pa_vec); pb_vec = vec_abs(pb_vec); pc_vec = vec_abs(pc_vec); smallest_vec = vec_min(pc_vec, vec_min(pa_vec,pb_vec)); nearest_vec = if_then_else( vec_cmpeq(pa_vec,smallest_vec), a_vec, if_then_else( vec_cmpeq(pb_vec,smallest_vec), b_vec, c_vec ) ); rp_vec = vec_add(rp_vec,(vsx_short_to_char(nearest_vec,4,3))); vec_st(rp_vec,0,rp); rp += 15; pp += 15; istop -= 16; /* Since 16 % bpp = 16 % 3 = 1, last element of array must * be proceeded manually */ vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) } if(istop > 0) for (i = 0; i < istop % 16; i++) { vsx_paeth_process(rp,pp,a,b,c,pa,pb,pc,bpp) } } #endif /* PNG_POWERPC_VSX_OPT > 0 */ #endif /* PNG_POWERPC_VSX_IMPLEMENTATION == 1 (intrinsics) */ #endif /* READ */
0
0.72976
1
0.72976
game-dev
MEDIA
0.382128
game-dev
0.611212
1
0.611212
discordia-space/CEV-Eris
8,494
code/modules/mob/living/carbon/human/human_organs.dm
/mob/living/carbon/human/proc/update_eyes() var/obj/item/organ/internal/eyes/eyes = random_organ_by_process(OP_EYES) if(eyes) eyes.update_colour() regenerate_icons() /mob/living/carbon/var/list/internal_organs = list() /mob/living/carbon/human/var/list/organs = list() /mob/living/carbon/human/var/list/organs_by_name = list() // map organ names to organs /mob/living/carbon/human/var/list/internal_organs_by_efficiency = list() // Takes care of organ related updates, such as broken and missing limbs /mob/living/carbon/human/proc/handle_organs() var/force_process = 0 var/damage_this_tick = getBruteLoss() + getFireLoss() if(damage_this_tick > last_dam) force_process = 1 last_dam = damage_this_tick if(force_process) bad_external_organs.Cut() for(var/obj/item/organ/external/Ex in organs) bad_external_organs |= Ex //processing internal organs is pretty cheap, do that first. for(var/obj/item/organ/I in internal_organs) I.Process() if(I.damage > 0) force_process = TRUE // Let's us know that we have internal damage to process handle_stance() handle_grasp() if(!force_process && !bad_external_organs.len) return for(var/obj/item/organ/external/E in organs) E.handle_bones() // If there is a flag from an internal injury, queue it for processing if(E.status & ORGAN_MUTATED|ORGAN_INFECTED|ORGAN_WOUNDED) bad_external_organs |= E for(var/obj/item/organ/external/E in bad_external_organs) if(!E) continue if(!E.need_process()) bad_external_organs -= E continue else E.Process() if(!lying && !buckled && world.time - l_move_time < 15) //Moving around with fractured ribs won't do you any good if(E.is_broken() && E.internal_organs && E.internal_organs.len && prob(15)) var/obj/item/organ/internal/I = pick(E.internal_organs) custom_pain("You feel broken bones moving in your [E.name]!", 1) I.take_damage(3, BRUTE, E.max_damage, 5.8, TRUE, TRUE) // Internal damage is taken at 80% health /mob/living/carbon/human/proc/handle_stance() // Don't need to process any of this if they aren't standing anyways // unless their stance is damaged, and we want to check if they should stay down if (!stance_damage && (lying || resting) && (life_tick % 4) == 0) return stance_damage = 0 // Buckled to a bed/chair. Stance damage is forced to 0 since they're sitting on something solid if (istype(buckled, /obj/structure/bed)) return // Calculate limb effect on stance for(var/limb_tag in BP_LEGS) var/obj/item/organ/external/E = organs_by_name[limb_tag] // A missing limb causes high stance damage if(!E) stance_damage += 4 else stance_damage += E.get_tally() // Canes and crutches help you stand (if the latter is ever added) // One cane fully mitigates a broken leg. // Two canes are needed for a lost leg. If you are missing both legs, canes aren't gonna help you. if(stance_damage > 0 && stance_damage < 8) if (l_hand && istype(l_hand, /obj/item/tool/cane)) stance_damage -= 3 if (r_hand && istype(r_hand, /obj/item/tool/cane)) stance_damage -= 3 stance_damage = max(stance_damage, 0) // standing is poor if(stance_damage >= 8 || (stance_damage >= 4 && prob(5))) if(!(lying || resting)) if(species && !(species.flags & NO_PAIN)) emote("scream") custom_emote(1, "collapses!") Weaken(5) //can't emote while weakened, apparently. /mob/living/carbon/human/proc/handle_grasp() if(!l_hand && !r_hand) return // You should not be able to pick anything up, but stranger things have happened. if(l_hand) for(var/limb_tag in list(BP_L_ARM)) var/obj/item/organ/external/E = get_organ(limb_tag) if(!E) visible_message(SPAN_DANGER("Lacking a functioning left hand, \the [src] drops \the [l_hand].")) drop_from_inventory(l_hand) break if(r_hand) for(var/limb_tag in list(BP_R_ARM)) var/obj/item/organ/external/E = get_organ(limb_tag) if(!E) visible_message(SPAN_DANGER("Lacking a functioning right hand, \the [src] drops \the [r_hand].")) drop_from_inventory(r_hand) break // Check again... if(!l_hand && !r_hand) return for (var/obj/item/organ/external/E in organs) if(!E || !(E.functions & BODYPART_GRASP) || (E.status & ORGAN_SPLINTED)) continue if(E.mob_can_unequip(src)) if(E.is_broken() || E.limb_efficiency <= 50) drop_from_inventory(E) if(E.limb_efficiency <= 50) emote("me", 1, "drops what they were holding in their [E.name], [pick("unable to grasp it", "unable to feel it", "too weak to hold it")]!") else emote("me", 1, "[(species.flags & NO_PAIN) ? "" : pick("screams in pain and ", "lets out a sharp cry and ", "cries out and ")]drops what they were holding in their [E.name]!") else if(E.is_malfunctioning()) drop_from_inventory(E) emote("pain", 1, "drops what they were holding, their [E.name] malfunctioning!") var/datum/effect/effect/system/spark_spread/spark_system = new /datum/effect/effect/system/spark_spread() spark_system.set_up(5, 0, src) spark_system.attach(src) spark_system.start() QDEL_IN(spark_system, 1 SECOND) //Handles chem traces /mob/living/carbon/human/proc/handle_trace_chems() //New are added for reagents to random organs. for(var/datum/reagent/A in reagents.reagent_list) var/obj/item/organ/O = pick(organs) O.trace_chemicals[A.name] = 100 /mob/living/carbon/human/proc/sync_organ_dna() var/list/all_bits = internal_organs|organs for(var/obj/item/organ/O in all_bits) O.set_dna(src) /mob/living/carbon/human/is_asystole() if(should_have_process(OP_HEART)) var/obj/item/organ/internal/vital/heart/heart = random_organ_by_process(OP_HEART) if(!istype(heart) || !heart.is_working()) return TRUE return FALSE /mob/living/carbon/human/proc/organ_list_by_process(organ_process) RETURN_TYPE(/list) . = list() for(var/organ in internal_organs_by_efficiency[organ_process]) . += organ /mob/living/carbon/human/proc/random_organ_by_process(organ_process) if(organ_list_by_process(organ_process).len) return pick(organ_list_by_process(organ_process)) return FALSE // basically has_limb() /mob/living/carbon/human/has_appendage(var/appendage_check) //returns TRUE if found, type of organ modification if limb is robotic, FALSE if not found if (appendage_check == BP_CHEST) return TRUE var/obj/item/organ/external/appendage appendage = organs_by_name[appendage_check] if(appendage && !appendage.is_stump()) if(BP_IS_ROBOTIC(appendage)) return appendage.nature else return TRUE return FALSE /mob/living/carbon/human/proc/restore_organ(organ_type, var/show_message = FALSE, var/heal = FALSE,) var/obj/item/organ/E = organs_by_name[organ_type] if(E && E.organ_tag != BP_HEAD && !E.vital && !E.is_usable()) //Skips heads and vital bits... QDEL_NULL(E) //...because no one wants their head to explode to make way for a new one. if(!E) if(organ_type in BP_ALL_LIMBS) var/datum/organ_description/organ_data = species.has_limbs[organ_type] var/obj/item/organ/external/O = organ_data.create_organ(src) var/datum/reagent/organic/blood/B = locate(/datum/reagent/organic/blood) in vessel.reagent_list blood_splatter(src,B,1) O.set_dna(src) update_body() if (show_message) to_chat(src, SPAN_DANGER("With a shower of fresh blood, a new [O.name] forms.")) visible_message(SPAN_DANGER("With a shower of fresh blood, a length of biomass shoots from [src]'s [O.amputation_point], forming a new [O.name]!")) return TRUE else var/list/organ_data = species.has_process[organ_type] var/organ_path = organ_data["path"] var/obj/item/organ/internal/O = new organ_path(src) organ_data["descriptor"] = O.name O.set_dna(src) update_body() if(is_carrion(src) && O.organ_tag == BP_BRAIN) O.vital = 0 return TRUE else if(organ_type in BP_ALL_LIMBS) var/obj/item/organ/external/O = E if (heal && (O.damage > 0 || O.status & (ORGAN_BROKEN))) O.status &= ~ORGAN_BROKEN for(var/datum/wound/W in O.wounds) if(W.internal) O.wounds.Remove(W) qdel(W) O.update_wounds() for(var/datum/wound/W in O.wounds) if(W.wound_damage() == 0 && prob(50)) O.wounds -= W return TRUE else if (heal && (E.damage > 0 || E.status & (ORGAN_BROKEN))) E.status &= ~ORGAN_BROKEN return TRUE return FALSE /mob/living/carbon/human/get_limb_efficiency(bodypartdefine) var/obj/item/organ/external/E = get_organ(bodypartdefine) if(E) return E.limb_efficiency return 0
0
0.912857
1
0.912857
game-dev
MEDIA
0.956301
game-dev
0.90343
1
0.90343
willpirkleaudio/ASPiK
7,845
vstgui4/vstgui/lib/platform/mac/cocoa/objcclassbuilder.h
// This file is part of VSTGUI. It is subject to the license terms // in the LICENSE file found in the top-level directory of this // distribution and at http://github.com/steinbergmedia/vstgui/LICENSE #pragma once #include <objc/runtime.h> #include <objc/message.h> #include <tuple> #include <string> #include <optional> #include <cmath> #include <cassert> //------------------------------------------------------------------------------------ namespace VSTGUI { //------------------------------------------------------------------------------------ template<typename T> struct ObjCVariable { ObjCVariable (__unsafe_unretained id obj, Ivar ivar) : obj (obj), ivar (ivar) {} ObjCVariable (ObjCVariable&& o) { *this = std::move (o); } ObjCVariable& operator= (ObjCVariable&& o) { obj = o.obj; ivar = o.ivar; o.obj = nullptr; o.ivar = nullptr; return *this; } T get () const { auto offset = ivar_getOffset (ivar); return *reinterpret_cast<T*> (((__bridge uintptr_t)obj) + offset); } void set (const T& value) { auto offset = ivar_getOffset (ivar); auto storage = reinterpret_cast<T*> (((__bridge uintptr_t)obj) + offset); *storage = value; } private: __unsafe_unretained id obj; Ivar ivar {nullptr}; }; //------------------------------------------------------------------------------------ struct ObjCInstance { ObjCInstance (__unsafe_unretained id obj, Class superClass = nullptr) : obj (obj) { os.super_class = superClass; } template<typename T> std::optional<ObjCVariable<T>> getVariable (const char* name) const { if (__strong auto ivar = class_getInstanceVariable (object_getClass (obj), name)) { return {ObjCVariable<T> (obj, ivar)}; } return {}; } template<typename Func, typename... T> void callSuper (SEL selector, T... args) const { void (*f) (__unsafe_unretained id, SEL, T...) = (void (*) (__unsafe_unretained id, SEL, T...))objc_msgSendSuper; f (getSuper (), selector, args...); } template<typename Func, typename R, typename... T> R callSuper (SEL selector, T... args) const { R (*f) (__unsafe_unretained id, SEL, T...) = (R (*) (__unsafe_unretained id, SEL, T...))objc_msgSendSuper; return f (getSuper (), selector, args...); } private: id getSuper () const { if (os.receiver == nullptr) { os.receiver = obj; } if (os.super_class == nullptr) { os.super_class = class_getSuperclass (object_getClass (obj)); } return (__bridge id) (&os); } __unsafe_unretained id obj; mutable objc_super os {}; }; //------------------------------------------------------------------------ template<typename T> struct RuntimeObjCClass { using Base = RuntimeObjCClass<T>; static id alloc () { static auto allocSel = sel_registerName ("alloc"); if (auto method = class_getClassMethod (instance ().cl, allocSel)) { if (auto methodImpl = method_getImplementation (method)) { using fn2 = id (*) (id, SEL); auto alloc = (fn2)methodImpl; return alloc (instance ().cl, allocSel); } } return nil; } RuntimeObjCClass () { cl = T::CreateClass (); superClass = class_getSuperclass (cl); } virtual ~RuntimeObjCClass () noexcept { if (cl) objc_disposeClassPair (cl); } static ObjCInstance makeInstance (__unsafe_unretained id obj) { return ObjCInstance (obj, instance ().superClass); } protected: static T& instance () { static T gInstance; return gInstance; } Class getClass () const { return cl; } Class getSuperClass () const { return superClass; } private: Class cl {nullptr}; Class superClass {nullptr}; }; //------------------------------------------------------------------------------------ struct ObjCClassBuilder { ObjCClassBuilder& init (const char* name, Class baseClass); template<typename Func> ObjCClassBuilder& addMethod (SEL selector, Func imp); template<typename T> ObjCClassBuilder& addIvar (const char* name); ObjCClassBuilder& addProtocol (const char* name); ObjCClassBuilder& addProtocol (Protocol* proto); Class finalize (); private: static Class generateUniqueClass (const std::string& inClassName, Class baseClass); template<typename Func> ObjCClassBuilder& addMethod (SEL selector, Func imp, const char* types); ObjCClassBuilder& addIvar (const char* name, size_t size, uint8_t alignment, const char* types); template<typename R, typename... T> static constexpr std::tuple<R, T...> functionArgs (R (*) (T...)) { return std::tuple<R, T...> (); } template<typename... T> static constexpr std::tuple<T...> functionArgs (void (*) (T...)) { return std::tuple<T...> (); } template<typename R, typename... T> static constexpr bool isVoidReturnType (R (*) (T...)) { return false; } template<typename... T> static constexpr bool isVoidReturnType (void (*) (T...)) { return true; } template<typename Proc> static std::string encodeFunction (Proc proc) { std::string result; if (isVoidReturnType (proc)) result = "v"; std::apply ([&] (auto&&... args) { ((result += @encode (decltype (args))), ...); }, functionArgs (proc)); return result; } Class cl {nullptr}; Class baseClass {nullptr}; }; //------------------------------------------------------------------------ inline ObjCClassBuilder& ObjCClassBuilder::init (const char* name, Class bc) { baseClass = bc; cl = generateUniqueClass (name, baseClass); return *this; } //------------------------------------------------------------------------------------ inline Class ObjCClassBuilder::generateUniqueClass (const std::string& inClassName, Class baseClass) { std::string className (inClassName); int32_t iteration = 0; while (objc_lookUpClass (className.data ()) != nil) { iteration++; className = inClassName + "_" + std::to_string (iteration); } Class resClass = objc_allocateClassPair (baseClass, className.data (), 0); return resClass; } //----------------------------------------------------------------------------- inline Class ObjCClassBuilder::finalize () { objc_registerClassPair (cl); auto res = cl; baseClass = cl = nullptr; return res; } //----------------------------------------------------------------------------- template<typename Func> inline ObjCClassBuilder& ObjCClassBuilder::addMethod (SEL selector, Func imp, const char* types) { auto res = class_addMethod (cl, selector, IMP (imp), types); assert (res == true); (void)res; return *this; } //----------------------------------------------------------------------------- template<typename Func> ObjCClassBuilder& ObjCClassBuilder::addMethod (SEL selector, Func imp) { return addMethod (selector, imp, encodeFunction (imp).data ()); } //------------------------------------------------------------------------ template<typename T> inline ObjCClassBuilder& ObjCClassBuilder::addIvar (const char* name) { return addIvar (name, sizeof (T), static_cast<uint8_t> (std::log2 (sizeof (T))), @encode (T)); } //----------------------------------------------------------------------------- inline ObjCClassBuilder& ObjCClassBuilder::addIvar (const char* name, size_t size, uint8_t alignment, const char* types) { auto res = class_addIvar (cl, name, size, alignment, types); assert (res == true); (void)res; return *this; } //----------------------------------------------------------------------------- inline ObjCClassBuilder& ObjCClassBuilder::addProtocol (const char* name) { if (auto protocol = objc_getProtocol (name)) return addProtocol (protocol); return *this; } //----------------------------------------------------------------------------- inline ObjCClassBuilder& ObjCClassBuilder::addProtocol (Protocol* proto) { auto res = class_addProtocol (cl, proto); assert (res == true); (void)res; return *this; } //------------------------------------------------------------------------------------ } // VSTGUI
0
0.88531
1
0.88531
game-dev
MEDIA
0.18915
game-dev
0.961922
1
0.961922
Ormael13/CoCX
15,551
classes/classes/Items/Consumables/EmberTF.as
/** * Ormael - 28.07.2017 */ package classes.Items.Consumables { import classes.BaseContent; import classes.BodyParts.Arms; import classes.BodyParts.Ears; import classes.BodyParts.Eyes; import classes.BodyParts.Face; import classes.BodyParts.Horns; import classes.BodyParts.LowerBody; import classes.BodyParts.Skin; import classes.BodyParts.Tail; import classes.BodyParts.Tongue; import classes.BodyParts.Wings; import classes.CoC; import classes.CockTypesEnum; import classes.GlobalFlags.kFLAGS; import classes.PerkLib; import classes.Races; import classes.Races.DragonRace; import classes.Scenes.SceneLib; public class EmberTF extends BaseContent { public function EmberTF() { super(); } public function dragonTFeffects(drakesHeart:Boolean = false):void { var changes:int = 0; var changeLimit:int = 2 + player.additionalTransformationChances; //Temporary storage var temp:Number = 0; if (player.blockingBodyTransformations()) changeLimit = 0; //Gain Dragon Dick if (changes < changeLimit && player.dragonCocks() < player.cockTotal() && rand(3) == 0) { var choices:Array = []; var select:int; temp = player.cockTotal(); //Build an array of all the locations for TF'able cocks. while (temp > 0) { temp--; if (player.cocks[temp].cockType != CockTypesEnum.DRAGON) choices[choices.length] = temp; } //Randomly choose one of those locations select = choices[rand(choices.length)]; transformations.CockDragon(select).applyEffect(); //lose lust if sens>=50, gain lust if else dynStats("lus", 10) player.addCurse("sen", 10, 1); changes++; } //-Existing horns become draconic, max of 4, max length of 1' if (player.horns.type != Horns.DRACONIC_X4_12_INCH_LONG && changes < changeLimit && rand(5) == 0) { //No dragon horns yet. if (player.horns.type != Horns.DRACONIC_X2 && player.horns.type != Horns.DRACONIC_X4_12_INCH_LONG && player.horns.type != Horns.ORCHID) { //Already have horns if (player.horns.count > 0) { //High quantity demon horns if (player.horns.type == Horns.DEMON && player.horns.count > 4) { CoC.instance.transformations.HornsDraconicQuadruple.applyEffect(); } else { CoC.instance.transformations.HornsDraconicDual.applyEffect(); } changes++; } //No horns else { //-If no horns, grow a pair CoC.instance.transformations.HornsDraconicDual.applyEffect(); changes++; } } //ALREADY DRAGON else { if (player.horns.type == Horns.DRACONIC_X2) { if (player.horns.count < 12) { if (rand(2) == 0) { outputText("\n\nYou get a headache as an inch of fresh horns escapes from your pounding skull."); player.horns.count += 1; } else { outputText("\n\nYour head aches as your horns grow a few inches longer. They get even thicker about the base, giving you a menacing appearance."); player.horns.count += 2 + rand(4); } if (player.horns.count >= 12) outputText(" <b>Your horns settle down quickly, as if they're reached their full size.</b>"); changes++; } //maxxed out, new row else { //--Next horns growth adds second row and brings length up to 12\" CoC.instance.transformations.HornsDraconicQuadruple.applyEffect(); changes++; } } } } //Gain Dragon Ears if (changes < changeLimit && rand(3) == 0 && player.ears.type != Ears.DRAGON) { outputText("\n\n"); CoC.instance.transformations.EarsDraconic.applyEffect(); changes++; } //Gain Dragon Eyes if (player.ears.type == Ears.DRAGON && player.eyes.type != Eyes.DRACONIC && rand(3) == 0 && changes < changeLimit) { outputText("\n\n"); CoC.instance.transformations.EyesDraconic.applyEffect(); changes++; } //Gain Dragon Tongue if (changes < changeLimit && rand(3) == 0 && player.tongue.type != Tongue.DRACONIC) { outputText("\n\n"); CoC.instance.transformations.TongueDraconic.applyEffect(); changes++; //Note: This type of tongue should be eligible for all things you can do with demon tongue... Dunno if it's best attaching a boolean just to change the description or creating a whole new tongue type. } //(Pending Tongue Masturbation Variants; if we ever get around to doing that.) //Gain Dragon Head OR Dragon Fangs if (changes < changeLimit && rand(3) == 0 && player.tongue.type == Tongue.DRACONIC && (player.faceType != Face.DRAGON && player.faceType != Face.DRAGON_FANGS)) { outputText("\n\n"); CoC.instance.transformations.FaceDragonFangs.applyEffect(); changes++; } else if (changes < changeLimit && rand(3) == 0 && player.tongue.type == Tongue.DRACONIC && player.faceType == Face.DRAGON_FANGS) { outputText("\n\n"); CoC.instance.transformations.FaceDragon.applyEffect(); changes++; } //Gain Dragon Scales if (player.hasPartialCoat(Skin.DRAGON_SCALES) && changes < changeLimit && rand(3) == 0) { outputText("\n\n"); CoC.instance.transformations.SkinDragonScales(Skin.COVERAGE_COMPLETE, { colors: DragonRace.DragonScaleColors }).applyEffect(); changes++; } if (!player.isDagonScaleCovered() && changes < changeLimit && rand(3) == 0) { var color:String; if (rand(10) == 0) { color = randomChoice("purple","silver"); } else { color = randomChoice("red","green","white","blue","black"); } //layer.scaleColor = color; outputText("\n\n"); CoC.instance.transformations.SkinDragonScales(Skin.COVERAGE_LOW, { color: color }).applyEffect(); changes++; } //Gain Dragon Legs if (player.lowerBody != LowerBody.DRAGON && changes < changeLimit && rand(3) == 0) { outputText("\n\n"); transformations.LowerBodyDraconic(2).applyEffect(); changes++; } //Arms if (player.arms.type != Arms.DRACONIC && player.lowerBody == LowerBody.DRAGON && changes < changeLimit && rand(3) == 0) { outputText("\n\n"); CoC.instance.transformations.ArmsDraconic.applyEffect(); changes++; } //Gain Dragon Tail if (player.tailType != Tail.DRACONIC && changes < changeLimit && rand(3) == 0) { outputText("\n\n"); CoC.instance.transformations.TailDraconic.applyEffect(); changes++ } /* //9999 - prolly not gonna do this! Tail Slam Attack Effects: Deals ⅓ normal damage, but pierces 30 defense (stacks with perks) and has a (strength / 2) chance of stunning the opponent that turn. Note: Dunno how much defense critters usually have, but this is meant as a surprise attack of sorts, so it pierces a good amount of it. Tail Slam Attack Description: You spin around quickly, whipping your tail spikes at [enemy]. Hit: Your tail slams against it/" + emberMF("him","her") + " with brutal force, the spikes on the tip extending to puncture flesh. Miss: Unfortunately, you lose your sense of depth as you whirl, and the tip swings harmlessly through the air in front of your target. */ //Grow Dragon Wings if (player.wings.type != Wings.DRACONIC_HUGE && changes < changeLimit && rand(3) == 0) { if (player.wings.type == Wings.NONE) { outputText("\n\n"); CoC.instance.transformations.WingsDraconicSmall.applyEffect(); } //(If Small Dragon Wings Present) else if (player.wings.type == Wings.DRACONIC_SMALL) { outputText("\n\n"); CoC.instance.transformations.WingsDraconicLarge.applyEffect(); } //even larger dragon wings ^^ else if (player.wings.type == Wings.DRACONIC_LARGE) { outputText("\n\n"); CoC.instance.transformations.WingsDraconicHuge.applyEffect(); } //(If other wings present) else { outputText("\n\n"); CoC.instance.transformations.WingsDraconicSmall.applyEffect(); } changes++; } //Get Dragon Breath (Tainted version) //Can only be obtained if you are considered a dragon-morph, once you do get it though, it won't just go away even if you aren't a dragon-morph anymore. if (player.racialScore(Races.DRAGON, false) >= 4) { if (changes < changeLimit && !player.hasPerk(PerkLib.DragonFireBreath)) { outputText("\n\nYou feel something awakening within you... then a sudden sensation of choking grabs hold of your throat, sending you to your knees as you clutch and gasp for breath. It feels like there's something trapped inside your windpipe, clawing and crawling its way up. You retch and splutter and then, with a feeling of almost painful relief, you expel a bellowing roar from deep inside of yourself... with enough force that clods of dirt and shattered gravel are sent flying all around. You look at the small crater you have literally blasted into the landscape with a mixture of awe and surprise."); outputText("\n\nIt seems " + (drakesHeart ? "the flower" : "Ember's dragon blood") + " has awaked some kind of power within you... your throat and chest feel very sore, however; you doubt you can force out more than one such blast before resting. (<b>Gained Perk: Dragon fire breath!</b>)"); player.createPerk(PerkLib.DragonFireBreath, 0, 0, 0, 0); if (SceneLib.emberScene.emberAffection() >= 75 && !drakesHeart) outputText("\n\nEmber immediately dives back in to soothe your battered throat and mouth with another kiss."); changes++; } if (changes < changeLimit && !player.hasPerk(PerkLib.DragonIceBreath)) { outputText("\n\nYou feel something awakening within you... then a sudden sensation of choking grabs hold of your throat, sending you to your knees as you clutch and gasp for breath. It feels like there's something trapped inside your windpipe, clawing and crawling its way up. You retch and splutter and then, with a feeling of almost painful relief, you expel a bellowing roar from deep inside of yourself... with enough force that clods of dirt and shattered gravel are sent flying all around. You look at the small crater you have literally blasted into the landscape with a mixture of awe and surprise."); outputText("\n\nIt seems " + (drakesHeart ? "the flower" : "Ember's dragon blood") + " has awaked some kind of power within you... your throat and chest feel very cold, however; you doubt you can force out more than one such blast before resting. (<b>Gained Perk: Dragon ice breath!</b>)"); player.createPerk(PerkLib.DragonIceBreath, 0, 0, 0, 0); if (SceneLib.emberScene.emberAffection() >= 75 && !drakesHeart) outputText("\n\nEmber immediately dives back in to soothe your battered throat and mouth with another kiss."); changes++; } if (changes < changeLimit && !player.hasPerk(PerkLib.DragonLightningBreath)) { outputText("\n\nYou feel something awakening within you... then a sudden sensation of choking grabs hold of your throat, sending you to your knees as you clutch and gasp for breath. It feels like there's something trapped inside your windpipe, clawing and crawling its way up. You retch and splutter and then, with a feeling of almost painful relief, you expel a bellowing roar from deep inside of yourself... with enough force that clods of dirt and shattered gravel are sent flying all around. You look at the small crater you have literally blasted into the landscape with a mixture of awe and surprise."); outputText("\n\nIt seems " + (drakesHeart ? "the flower" : "Ember's dragon blood") + " has awaked some kind of power within you... your throat and chest feel like it was electrocuted, however; you doubt you can force out more than one such blast before resting. (<b>Gained Perk: Dragon lightning breath!</b>)"); player.createPerk(PerkLib.DragonLightningBreath, 0, 0, 0, 0); if (SceneLib.emberScene.emberAffection() >= 75 && !drakesHeart) outputText("\n\nEmber immediately dives back in to soothe your battered throat and mouth with another kiss."); changes++; } if (changes < changeLimit && !player.hasPerk(PerkLib.DragonDarknessBreath)) { outputText("\n\nYou feel something awakening within you... then a sudden sensation of choking grabs hold of your throat, sending you to your knees as you clutch and gasp for breath. It feels like there's something trapped inside your windpipe, clawing and crawling its way up. You retch and splutter and then, with a feeling of almost painful relief, you expel a bellowing roar from deep inside of yourself... with enough force that clods of dirt and shattered gravel are sent flying all around. You look at the small crater you have literally blasted into the landscape with a mixture of awe and surprise."); outputText("\n\nIt seems " + (drakesHeart ? "the flower" : "Ember's dragon blood") + " has awaked some kind of power within you... your throat and chest feel very... strange and you can't put a finger what this feeling exactly is, however; you doubt you can force out more than one such blast before resting. (<b>Gained Perk: Dragon darkness breath!</b>)"); player.createPerk(PerkLib.DragonDarknessBreath, 0, 0, 0, 0); if (SceneLib.emberScene.emberAffection() >= 75 && !drakesHeart) outputText("\n\nEmber immediately dives back in to soothe your battered throat and mouth with another kiss."); changes++; } } //grow up to 11 feet tall if (changes < changeLimit && rand(2) == 0 && player.basetallness < 132) { temp = rand(5) + 3; //Slow rate of growth after some tresholds if (player.basetallness >= 120) temp = Math.floor(temp / 3.5); if (player.basetallness >= 96 && player.basetallness < 120) temp = Math.floor(temp / 2); //Never 0 if (temp == 0) temp = 1; if (temp < 5) outputText("\n\nYou shift uncomfortably as you realize you feel off balance. Gazing down, you realize you have grown SLIGHTLY taller."); if (temp >= 5 && temp < 7) outputText("\n\nYou feel dizzy and slightly off, but quickly realize it's due to a sudden increase in height."); if (temp == 7) outputText("\n\nStaggering forwards, you clutch at your head dizzily. You spend a moment getting your balance, and stand up, feeling noticeably taller."); player.tallness += temp; changes++; } var canReactMale:Boolean = player.hasCock() && (drakesHeart || SceneLib.emberScene.hasVagina()); var canReactFemale:Boolean = player.hasVagina() && (drakesHeart || SceneLib.emberScene.hasCock()); if (player.racialScore(Races.DRAGON, false) >= 4 && rand(3) == 0 && (canReactMale || canReactFemale)) { outputText("\n\nA sudden swell of lust races through your "); if (canReactMale) { outputText(cockDescript(0)); if (canReactFemale) outputText(" and "); } if (canReactFemale) outputText(vaginaDescript()); outputText(", making you wish " + (drakesHeart ? "you had a dragon to go with." : "you could have sex with Ember right here and now") + ". All you can think about now is fucking " + (drakesHeart ? "a dragon-morph" : SceneLib.emberScene.emberMF("him", "her")) + "; "); if (canReactMale) { if (drakesHeart) outputText("filling a womb with your seed and fertilizing those eggs"); else { outputText("filling her womb with your seed and fertilizing her eggs"); if (canReactFemale) outputText(" even while "); } } if (canReactFemale) { outputText("taking that hard, spurting cock inside your own [vagina]"); } outputText("... too late, you realize that <b>" + (drakesHeart ? "the flower" : "Ember's blood") + " has sent your draconic body into "); if (canReactMale && (rand(2) == 0 || !canReactFemale)) { //If hermaphrodite, the chance is 50/50. outputText("rut"); player.goIntoRut(false); changes++; } else { outputText("heat"); player.goIntoHeat(false); changes++; } outputText("</b>."); } if (changes == 0) outputText("\n\nRemarkably, " + (drakesHeart ? "the flower" : "Ember's blood") + " has no effect. Maybe next time?"); flags[kFLAGS.TIMES_TRANSFORMED] += changes; } } }
0
0.878227
1
0.878227
game-dev
MEDIA
0.987938
game-dev
0.957974
1
0.957974
oot-pc-port/oot-pc-port
1,481
asm/non_matchings/overlays/actors/ovl_En_Ssh/func_80B028CC.s
glabel func_80B028CC /* 0065C 80B028CC 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8 /* 00660 80B028D0 AFBF0014 */ sw $ra, 0x0014($sp) /* 00664 80B028D4 848E0528 */ lh $t6, 0x0528($a0) ## 00000528 /* 00668 80B028D8 24050004 */ addiu $a1, $zero, 0x0004 ## $a1 = 00000004 /* 0066C 80B028DC 55C00009 */ bnel $t6, $zero, .L80B02904 /* 00670 80B028E0 3C01C120 */ lui $at, 0xC120 ## $at = C1200000 /* 00674 80B028E4 0C2C09C0 */ jal func_80B02700 /* 00678 80B028E8 AFA40018 */ sw $a0, 0x0018($sp) /* 0067C 80B028EC 4600010D */ trunc.w.s $f4, $f0 /* 00680 80B028F0 8FA40018 */ lw $a0, 0x0018($sp) /* 00684 80B028F4 44182000 */ mfc1 $t8, $f4 /* 00688 80B028F8 00000000 */ nop /* 0068C 80B028FC A4980534 */ sh $t8, 0x0534($a0) ## 00000534 /* 00690 80B02900 3C01C120 */ lui $at, 0xC120 ## $at = C1200000 .L80B02904: /* 00694 80B02904 44813000 */ mtc1 $at, $f6 ## $f6 = -10.00 /* 00698 80B02908 00000000 */ nop /* 0069C 80B0290C E4860060 */ swc1 $f6, 0x0060($a0) ## 00000060 /* 006A0 80B02910 8FBF0014 */ lw $ra, 0x0014($sp) /* 006A4 80B02914 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000 /* 006A8 80B02918 03E00008 */ jr $ra /* 006AC 80B0291C 00000000 */ nop
0
0.701424
1
0.701424
game-dev
MEDIA
0.989729
game-dev
0.658483
1
0.658483
spartanoah/acrimony-client
5,471
net/minecraft/entity/item/EntityMinecartFurnace.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package net.minecraft.entity.item; import net.minecraft.block.BlockFurnace; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityMinecart; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.BlockPos; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; public class EntityMinecartFurnace extends EntityMinecart { private int fuel; public double pushX; public double pushZ; public EntityMinecartFurnace(World worldIn) { super(worldIn); } public EntityMinecartFurnace(World worldIn, double p_i1719_2_, double p_i1719_4_, double p_i1719_6_) { super(worldIn, p_i1719_2_, p_i1719_4_, p_i1719_6_); } @Override public EntityMinecart.EnumMinecartType getMinecartType() { return EntityMinecart.EnumMinecartType.FURNACE; } @Override protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(16, new Byte(0)); } @Override public void onUpdate() { super.onUpdate(); if (this.fuel > 0) { --this.fuel; } if (this.fuel <= 0) { this.pushZ = 0.0; this.pushX = 0.0; } this.setMinecartPowered(this.fuel > 0); if (this.isMinecartPowered() && this.rand.nextInt(4) == 0) { this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_LARGE, this.posX, this.posY + 0.8, this.posZ, 0.0, 0.0, 0.0, new int[0]); } } @Override protected double getMaximumSpeed() { return 0.2; } @Override public void killMinecart(DamageSource p_94095_1_) { super.killMinecart(p_94095_1_); if (!p_94095_1_.isExplosion() && this.worldObj.getGameRules().getGameRuleBooleanValue("doEntityDrops")) { this.entityDropItem(new ItemStack(Blocks.furnace, 1), 0.0f); } } @Override protected void func_180460_a(BlockPos p_180460_1_, IBlockState p_180460_2_) { super.func_180460_a(p_180460_1_, p_180460_2_); double d0 = this.pushX * this.pushX + this.pushZ * this.pushZ; if (d0 > 1.0E-4 && this.motionX * this.motionX + this.motionZ * this.motionZ > 0.001) { d0 = MathHelper.sqrt_double(d0); this.pushX /= d0; this.pushZ /= d0; if (this.pushX * this.motionX + this.pushZ * this.motionZ < 0.0) { this.pushX = 0.0; this.pushZ = 0.0; } else { double d1 = d0 / this.getMaximumSpeed(); this.pushX *= d1; this.pushZ *= d1; } } } @Override protected void applyDrag() { double d0 = this.pushX * this.pushX + this.pushZ * this.pushZ; if (d0 > 1.0E-4) { d0 = MathHelper.sqrt_double(d0); this.pushX /= d0; this.pushZ /= d0; double d1 = 1.0; this.motionX *= (double)0.8f; this.motionY *= 0.0; this.motionZ *= (double)0.8f; this.motionX += this.pushX * d1; this.motionZ += this.pushZ * d1; } else { this.motionX *= (double)0.98f; this.motionY *= 0.0; this.motionZ *= (double)0.98f; } super.applyDrag(); } @Override public boolean interactFirst(EntityPlayer playerIn) { ItemStack itemstack = playerIn.inventory.getCurrentItem(); if (itemstack != null && itemstack.getItem() == Items.coal) { if (!playerIn.capabilities.isCreativeMode && --itemstack.stackSize == 0) { playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, null); } this.fuel += 3600; } this.pushX = this.posX - playerIn.posX; this.pushZ = this.posZ - playerIn.posZ; return true; } @Override protected void writeEntityToNBT(NBTTagCompound tagCompound) { super.writeEntityToNBT(tagCompound); tagCompound.setDouble("PushX", this.pushX); tagCompound.setDouble("PushZ", this.pushZ); tagCompound.setShort("Fuel", (short)this.fuel); } @Override protected void readEntityFromNBT(NBTTagCompound tagCompund) { super.readEntityFromNBT(tagCompund); this.pushX = tagCompund.getDouble("PushX"); this.pushZ = tagCompund.getDouble("PushZ"); this.fuel = tagCompund.getShort("Fuel"); } protected boolean isMinecartPowered() { return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; } protected void setMinecartPowered(boolean p_94107_1_) { if (p_94107_1_) { this.dataWatcher.updateObject(16, (byte)(this.dataWatcher.getWatchableObjectByte(16) | 1)); } else { this.dataWatcher.updateObject(16, (byte)(this.dataWatcher.getWatchableObjectByte(16) & 0xFFFFFFFE)); } } @Override public IBlockState getDefaultDisplayTile() { return (this.isMinecartPowered() ? Blocks.lit_furnace : Blocks.furnace).getDefaultState().withProperty(BlockFurnace.FACING, EnumFacing.NORTH); } }
0
0.875756
1
0.875756
game-dev
MEDIA
0.99133
game-dev
0.93532
1
0.93532
Eusth/VRGIN
6,208
VRGIN/U46/OSP/OSPReflectionZone.cs
/************************************************************************************ Filename : OSPReflectionZone.cs Content : Add reflection zone volumes to set reflection parameters. Created : August 10, 2015 Authors : Peter Giokaris opyright : Copyright 2015 Oculus VR, Inc. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.1 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using UnityEngine; using System.Collections; using System.Collections.Generic; public class OSPReflectionZone : MonoBehaviour { [SerializeField] private Vector3 dimensions = new Vector3 (0.0f, 0.0f, 0.0f); public Vector3 Dimensions { get{return dimensions; } set{dimensions = value; dimensions.x = Mathf.Clamp (dimensions.x, 1.0f, 200.0f); dimensions.y = Mathf.Clamp (dimensions.y, 1.0f, 200.0f); dimensions.z = Mathf.Clamp (dimensions.z, 1.0f, 200.0f);} } [SerializeField] private Vector2 rK01 = new Vector2(0.0f, 0.0f); public Vector2 RK01 { get{return rK01; } set{rK01 = value; rK01.x = Mathf.Clamp (rK01.x, 0.0f, 0.97f); rK01.y = Mathf.Clamp (rK01.y, 0.0f, 0.97f);} } [SerializeField] private Vector2 rK23 = new Vector2(0.0f, 0.0f); public Vector2 RK23 { get{return rK23; } set{rK23 = value; rK23.x = Mathf.Clamp (rK23.x, 0.0f, 0.95f); rK23.y = Mathf.Clamp (rK23.y, 0.0f, 0.95f);} } [SerializeField] private Vector2 rK45 = new Vector2(0.0f, 0.0f); public Vector2 RK45 { get{return rK45; } set{rK45 = value; rK45.x = Mathf.Clamp (rK45.x, 0.0f, 0.95f); rK45.y = Mathf.Clamp (rK45.y, 0.0f, 0.95f);} } // Push/pop list private static Stack<OSPManager.RoomModel> reflectionList = new Stack<OSPManager.RoomModel>(); /// <summary> /// Start this instance. /// </summary> void Start () { } /// <summary> /// Update this instance. /// </summary> void Update () { } /// <summary> /// Raises the trigger enter event. /// </summary> /// <param name="other">Other.</param> void OnTriggerEnter(Collider other) { if(CheckForAudioListener(other.gameObject) == true) { PushCurrentReflectionValues(); } } /// <summary> /// Raises the trigger exit event. /// </summary> /// <param name="other">Other.</param> void OnTriggerExit(Collider other) { if(CheckForAudioListener(other.gameObject) == true) { PopCurrentReflectionValues(); } } // * * * * * * * * * * * * * // Private functions /// <summary> /// Checks for audio listener. /// </summary> /// <returns><c>true</c>, if for audio listener was checked, <c>false</c> otherwise.</returns> /// <param name="gameObject">Game object.</param> bool CheckForAudioListener(GameObject gameObject) { AudioListener al = gameObject.GetComponentInChildren<AudioListener>(); if(al != null) return true; return false; } /// <summary> /// Pushs the current reflection values onto reflectionsList stack. /// </summary> void PushCurrentReflectionValues() { if(OSPManager.sInstance == null) { Debug.LogWarning (System.String.Format ("OSPReflectionZone-PushCurrentReflectionValues: OSPManager does not exist in scene.")); return; } OSPManager.RoomModel rm = new OSPManager.RoomModel(); rm.DimensionX = OSPManager.sInstance.Dimensions.x; rm.DimensionY = OSPManager.sInstance.Dimensions.y; rm.DimensionZ = OSPManager.sInstance.Dimensions.z; rm.Reflection_K0 = OSPManager.sInstance.RK01.x; rm.Reflection_K1 = OSPManager.sInstance.RK01.y; rm.Reflection_K2 = OSPManager.sInstance.RK23.x; rm.Reflection_K3 = OSPManager.sInstance.RK23.y; rm.Reflection_K4 = OSPManager.sInstance.RK45.x; rm.Reflection_K5 = OSPManager.sInstance.RK45.y; reflectionList.Push(rm); // Set the zone reflection values // NOTE: There will be conditions that might need resolution when dealing with volumes that // overlap. Best practice is to never have volumes half-way inside other volumes; larger // volumes should completely contain smaller volumes SetReflectionValues(); } /// <summary> /// Pops the current reflection values from reflectionsList stack. /// </summary> void PopCurrentReflectionValues() { if(OSPManager.sInstance == null) { Debug.LogWarning (System.String.Format ("OSPReflectionZone-PopCurrentReflectionValues: OSPManager does not exist in scene.")); return; } if(reflectionList.Count == 0) { Debug.LogWarning (System.String.Format ("OSPReflectionZone-PopCurrentReflectionValues: reflectionList is empty.")); return; } OSPManager.RoomModel rm = reflectionList.Pop(); // Set the popped reflection values SetReflectionValues(ref rm); } /// <summary> /// Sets the reflection values. This is done when entering a zone (use zone values). /// </summary> void SetReflectionValues() { OSPManager.sInstance.Dimensions = Dimensions; OSPManager.sInstance.RK01 = RK01; OSPManager.sInstance.RK23 = RK23; OSPManager.sInstance.RK45 = RK45; } /// <summary> /// Sets the reflection values. This is done when exiting a zone (use popped values). /// </summary> /// <param name="rm">Rm.</param> void SetReflectionValues(ref OSPManager.RoomModel rm) { OSPManager.sInstance.Dimensions = new Vector3(rm.DimensionX, rm.DimensionY, rm.DimensionZ); OSPManager.sInstance.RK01 = new Vector3(rm.Reflection_K0, rm.Reflection_K1); OSPManager.sInstance.RK23 = new Vector3(rm.Reflection_K2, rm.Reflection_K3); OSPManager.sInstance.RK45 = new Vector3(rm.Reflection_K4, rm.Reflection_K5); } }
0
0.773646
1
0.773646
game-dev
MEDIA
0.667462
game-dev
0.755681
1
0.755681
mchekin/rpg
4,829
app/Modules/Equipment/Domain/Inventory.php
<?php namespace App\Modules\Equipment\Domain; use App\Modules\Character\Domain\CharacterId; use App\Modules\Generic\Domain\Container\ContainerIsFullException; use App\Modules\Generic\Domain\Container\ItemNotInContainer; use App\Modules\Generic\Domain\Container\NotEnoughSpaceInContainerException; use Illuminate\Support\Collection; use InvalidArgumentException; class Inventory { public const NUMBER_OF_SLOTS = 24; /** * @var InventoryId */ private $id; /** * @var CharacterId */ private $characterId; /** * @var Collection */ private $items; /** * @var Money */ private $money; public function __construct(InventoryId $id, CharacterId $characterId, Collection $items, Money $money) { if ($items->count() > self::NUMBER_OF_SLOTS) { throw new NotEnoughSpaceInContainerException( "Not enough space in the Inventory for {$items->count()} new items" ); } $items->each(static function ($item) { if (!($item instanceof InventoryItem)) { throw new InvalidArgumentException('Trying to populate inventory with non inventory item'); } }); $this->id = $id; $this->characterId = $characterId; $this->items = $items; $this->money = $money; } public function getId(): InventoryId { return $this->id; } public function add(Item $item): void { $item = new InventoryItem($item, ItemStatus::inBackpack()); $slot = $this->findFreeSlot(); $this->items->put($slot, $item); } public function getEquippedItemsEffect(string $itemEffectType): int { return (int)$this->getEquippedItems()->reduce(static function ($carry, InventoryItem $item) use ($itemEffectType) { $itemEffect = $item->getItemEffect($itemEffectType); return $carry + $itemEffect; }); } public function unEquipItem(ItemId $itemId): void { $equippedItem = $this->findEquippedItem($itemId); if ($equippedItem) { $equippedItem->unEquip(); } } public function equip(ItemId $itemId): void { $item = $this->findItem($itemId); if (!$item) { throw new ItemNotInContainer('Cannot equip item that is not in the inventory'); } if ($equippedItem = $this->findEquippedItemOfType($item->getType())) { $equippedItem->unEquip(); } $item->equip(); } public function getCharacterId(): CharacterId { return $this->characterId; } public function getItems(): Collection { return $this->items; } public function takeOut(ItemId $itemId): Item { $slot = $this->items->search(static function (InventoryItem $item) use ($itemId) { return $item->getId()->equals($itemId); }); if ($slot === false) { throw new ItemNotInContainer('Cannot take out item from empty slot'); } /** @var InventoryItem $item */ $item = $this->items->get($slot); $this->items->forget($slot); return $item->toBaseItem(); } public function putMoneyIn(Money $money): void { $this->money = $this->money->combine($money); } public function takeMoneyOut(Money $money): Money { $this->money = $this->money->remove($money); return $money; } public function getMoney(): Money { return $this->money; } public function findItem(ItemId $itemId):? InventoryItem { return $this->items->first(static function (InventoryItem $item) use ($itemId) { return $item->getId()->equals($itemId); }); } private function findFreeSlot(): int { for ($slot = 0; $slot < self::NUMBER_OF_SLOTS; $slot++) { if (!$this->items->has($slot)) { return $slot; } } throw new ContainerIsFullException('Cannot add to full inventory'); } private function findEquippedItem(ItemId $itemId):? InventoryItem { return $this->items->first(static function (InventoryItem $item) use ($itemId) { return $item->getId()->equals($itemId) && $item->isEquipped(); }); } private function findEquippedItemOfType(ItemType $type):? InventoryItem { return $this->items->first(static function (InventoryItem $item) use ($type) { return $item->isOfType($type) && $item->isEquipped(); }); } private function getEquippedItems(): Collection { return $this->items->filter(static function (InventoryItem $item) { return $item->isEquipped(); }); } }
0
0.895473
1
0.895473
game-dev
MEDIA
0.973463
game-dev,web-backend
0.881984
1
0.881984
eduard-permyakov/permafrost-engine
14,967
deps/SDL2/src/events/SDL_touch.c
/* Simple DirectMedia Layer Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* General touch handling code for SDL */ #include "SDL_events.h" #include "SDL_events_c.h" #include "../video/SDL_sysvideo.h" static int SDL_num_touch = 0; static SDL_Touch **SDL_touchDevices = NULL; /* for mapping touch events to mice */ #define SYNTHESIZE_TOUCH_TO_MOUSE 1 #if SYNTHESIZE_TOUCH_TO_MOUSE static SDL_bool finger_touching = SDL_FALSE; static SDL_FingerID track_fingerid; static SDL_TouchID track_touchid; #endif /* Public functions */ int SDL_TouchInit(void) { return 0; } int SDL_GetNumTouchDevices(void) { return SDL_num_touch; } SDL_TouchID SDL_GetTouchDevice(int index) { if (index < 0 || index >= SDL_num_touch) { SDL_SetError("Unknown touch device index %d", index); return 0; } return SDL_touchDevices[index]->id; } const char *SDL_GetTouchName(int index) { if (index < 0 || index >= SDL_num_touch) { SDL_SetError("Unknown touch device"); return NULL; } return SDL_touchDevices[index]->name; } static int SDL_GetTouchIndex(SDL_TouchID id) { int index; SDL_Touch *touch; for (index = 0; index < SDL_num_touch; ++index) { touch = SDL_touchDevices[index]; if (touch->id == id) { return index; } } return -1; } SDL_Touch *SDL_GetTouch(SDL_TouchID id) { int index = SDL_GetTouchIndex(id); if (index < 0 || index >= SDL_num_touch) { if (SDL_GetVideoDevice()->ResetTouch != NULL) { SDL_SetError("Unknown touch id %d, resetting", (int)id); (SDL_GetVideoDevice()->ResetTouch)(SDL_GetVideoDevice()); } else { SDL_SetError("Unknown touch device id %d, cannot reset", (int)id); } return NULL; } return SDL_touchDevices[index]; } SDL_TouchDeviceType SDL_GetTouchDeviceType(SDL_TouchID id) { SDL_Touch *touch = SDL_GetTouch(id); if (touch) { return touch->type; } return SDL_TOUCH_DEVICE_INVALID; } static int SDL_GetFingerIndex(const SDL_Touch *touch, SDL_FingerID fingerid) { int index; for (index = 0; index < touch->num_fingers; ++index) { if (touch->fingers[index]->id == fingerid) { return index; } } return -1; } static SDL_Finger *SDL_GetFinger(const SDL_Touch *touch, SDL_FingerID id) { int index = SDL_GetFingerIndex(touch, id); if (index < 0 || index >= touch->num_fingers) { return NULL; } return touch->fingers[index]; } int SDL_GetNumTouchFingers(SDL_TouchID touchID) { SDL_Touch *touch = SDL_GetTouch(touchID); if (touch) { return touch->num_fingers; } return 0; } SDL_Finger *SDL_GetTouchFinger(SDL_TouchID touchID, int index) { SDL_Touch *touch = SDL_GetTouch(touchID); if (!touch) { return NULL; } if (index < 0 || index >= touch->num_fingers) { SDL_SetError("Unknown touch finger"); return NULL; } return touch->fingers[index]; } int SDL_AddTouch(SDL_TouchID touchID, SDL_TouchDeviceType type, const char *name) { SDL_Touch **touchDevices; int index; index = SDL_GetTouchIndex(touchID); if (index >= 0) { return index; } /* Add the touch to the list of touch */ touchDevices = (SDL_Touch **)SDL_realloc(SDL_touchDevices, (SDL_num_touch + 1) * sizeof(*touchDevices)); if (!touchDevices) { return SDL_OutOfMemory(); } SDL_touchDevices = touchDevices; index = SDL_num_touch; SDL_touchDevices[index] = (SDL_Touch *)SDL_malloc(sizeof(*SDL_touchDevices[index])); if (!SDL_touchDevices[index]) { return SDL_OutOfMemory(); } /* Added touch to list */ ++SDL_num_touch; /* we're setting the touch properties */ SDL_touchDevices[index]->id = touchID; SDL_touchDevices[index]->type = type; SDL_touchDevices[index]->num_fingers = 0; SDL_touchDevices[index]->max_fingers = 0; SDL_touchDevices[index]->fingers = NULL; SDL_touchDevices[index]->name = SDL_strdup(name ? name : ""); /* Record this touch device for gestures */ /* We could do this on the fly in the gesture code if we wanted */ SDL_GestureAddTouch(touchID); return index; } static int SDL_AddFinger(SDL_Touch *touch, SDL_FingerID fingerid, float x, float y, float pressure) { SDL_Finger *finger; if (touch->num_fingers == touch->max_fingers) { SDL_Finger **new_fingers; new_fingers = (SDL_Finger **)SDL_realloc(touch->fingers, (touch->max_fingers + 1) * sizeof(*touch->fingers)); if (!new_fingers) { return SDL_OutOfMemory(); } touch->fingers = new_fingers; touch->fingers[touch->max_fingers] = (SDL_Finger *)SDL_malloc(sizeof(*finger)); if (!touch->fingers[touch->max_fingers]) { return SDL_OutOfMemory(); } touch->max_fingers++; } finger = touch->fingers[touch->num_fingers++]; finger->id = fingerid; finger->x = x; finger->y = y; finger->pressure = pressure; return 0; } static int SDL_DelFinger(SDL_Touch *touch, SDL_FingerID fingerid) { SDL_Finger *temp; int index = SDL_GetFingerIndex(touch, fingerid); if (index < 0) { return -1; } touch->num_fingers--; temp = touch->fingers[index]; touch->fingers[index] = touch->fingers[touch->num_fingers]; touch->fingers[touch->num_fingers] = temp; return 0; } int SDL_SendTouch(SDL_TouchID id, SDL_FingerID fingerid, SDL_Window *window, SDL_bool down, float x, float y, float pressure) { int posted; SDL_Finger *finger; SDL_Mouse *mouse; SDL_Touch *touch = SDL_GetTouch(id); if (!touch) { return -1; } mouse = SDL_GetMouse(); #if SYNTHESIZE_TOUCH_TO_MOUSE /* SDL_HINT_TOUCH_MOUSE_EVENTS: controlling whether touch events should generate synthetic mouse events */ /* SDL_HINT_VITA_TOUCH_MOUSE_DEVICE: controlling which touchpad should generate synthetic mouse events, PSVita-only */ { #if defined(__vita__) if (mouse->touch_mouse_events && ((mouse->vita_touch_mouse_device == id) || (mouse->vita_touch_mouse_device == 2))) { #else if (mouse->touch_mouse_events) { #endif /* FIXME: maybe we should only restrict to a few SDL_TouchDeviceType */ if (id != SDL_MOUSE_TOUCHID) { if (window) { if (down) { if (finger_touching == SDL_FALSE) { int pos_x = (int)(x * (float)window->w); int pos_y = (int)(y * (float)window->h); if (pos_x < 0) { pos_x = 0; } if (pos_x > window->w - 1) { pos_x = window->w - 1; } if (pos_y < 0) { pos_y = 0; } if (pos_y > window->h - 1) { pos_y = window->h - 1; } SDL_SendMouseMotion(window, SDL_TOUCH_MOUSEID, 0, pos_x, pos_y); SDL_SendMouseButton(window, SDL_TOUCH_MOUSEID, SDL_PRESSED, SDL_BUTTON_LEFT); } } else { if (finger_touching == SDL_TRUE && track_touchid == id && track_fingerid == fingerid) { SDL_SendMouseButton(window, SDL_TOUCH_MOUSEID, SDL_RELEASED, SDL_BUTTON_LEFT); } } } if (down) { if (finger_touching == SDL_FALSE) { finger_touching = SDL_TRUE; track_touchid = id; track_fingerid = fingerid; } } else { if (finger_touching == SDL_TRUE && track_touchid == id && track_fingerid == fingerid) { finger_touching = SDL_FALSE; } } } } } #endif /* SDL_HINT_MOUSE_TOUCH_EVENTS: if not set, discard synthetic touch events coming from platform layer */ if (mouse->mouse_touch_events == 0) { if (id == SDL_MOUSE_TOUCHID) { return 0; } } finger = SDL_GetFinger(touch, fingerid); if (down) { if (finger) { /* This finger is already down. Assume the finger-up for the previous touch was lost, and send it. */ SDL_SendTouch(id, fingerid, window, SDL_FALSE, x, y, pressure); } if (SDL_AddFinger(touch, fingerid, x, y, pressure) < 0) { return 0; } posted = 0; if (SDL_GetEventState(SDL_FINGERDOWN) == SDL_ENABLE) { SDL_Event event; event.tfinger.type = SDL_FINGERDOWN; event.tfinger.touchId = id; event.tfinger.fingerId = fingerid; event.tfinger.x = x; event.tfinger.y = y; event.tfinger.dx = 0; event.tfinger.dy = 0; event.tfinger.pressure = pressure; event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0; posted = (SDL_PushEvent(&event) > 0); } } else { if (!finger) { /* This finger is already up */ return 0; } posted = 0; if (SDL_GetEventState(SDL_FINGERUP) == SDL_ENABLE) { SDL_Event event; event.tfinger.type = SDL_FINGERUP; event.tfinger.touchId = id; event.tfinger.fingerId = fingerid; /* I don't trust the coordinates passed on fingerUp */ event.tfinger.x = finger->x; event.tfinger.y = finger->y; event.tfinger.dx = 0; event.tfinger.dy = 0; event.tfinger.pressure = pressure; event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0; posted = (SDL_PushEvent(&event) > 0); } SDL_DelFinger(touch, fingerid); } return posted; } int SDL_SendTouchMotion(SDL_TouchID id, SDL_FingerID fingerid, SDL_Window *window, float x, float y, float pressure) { SDL_Touch *touch; SDL_Finger *finger; SDL_Mouse *mouse; int posted; float xrel, yrel, prel; touch = SDL_GetTouch(id); if (!touch) { return -1; } mouse = SDL_GetMouse(); #if SYNTHESIZE_TOUCH_TO_MOUSE /* SDL_HINT_TOUCH_MOUSE_EVENTS: controlling whether touch events should generate synthetic mouse events */ { if (mouse->touch_mouse_events) { if (id != SDL_MOUSE_TOUCHID) { if (window) { if (finger_touching == SDL_TRUE && track_touchid == id && track_fingerid == fingerid) { int pos_x = (int)(x * (float)window->w); int pos_y = (int)(y * (float)window->h); if (pos_x < 0) { pos_x = 0; } if (pos_x > window->w - 1) { pos_x = window->w - 1; } if (pos_y < 0) { pos_y = 0; } if (pos_y > window->h - 1) { pos_y = window->h - 1; } SDL_SendMouseMotion(window, SDL_TOUCH_MOUSEID, 0, pos_x, pos_y); } } } } } #endif /* SDL_HINT_MOUSE_TOUCH_EVENTS: if not set, discard synthetic touch events coming from platform layer */ if (mouse->mouse_touch_events == 0) { if (id == SDL_MOUSE_TOUCHID) { return 0; } } finger = SDL_GetFinger(touch, fingerid); if (!finger) { return SDL_SendTouch(id, fingerid, window, SDL_TRUE, x, y, pressure); } xrel = x - finger->x; yrel = y - finger->y; prel = pressure - finger->pressure; /* Drop events that don't change state */ if (xrel == 0.0f && yrel == 0.0f && prel == 0.0f) { #if 0 printf("Touch event didn't change state - dropped!\n"); #endif return 0; } /* Update internal touch coordinates */ finger->x = x; finger->y = y; finger->pressure = pressure; /* Post the event, if desired */ posted = 0; if (SDL_GetEventState(SDL_FINGERMOTION) == SDL_ENABLE) { SDL_Event event; event.tfinger.type = SDL_FINGERMOTION; event.tfinger.touchId = id; event.tfinger.fingerId = fingerid; event.tfinger.x = x; event.tfinger.y = y; event.tfinger.dx = xrel; event.tfinger.dy = yrel; event.tfinger.pressure = pressure; event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0; posted = (SDL_PushEvent(&event) > 0); } return posted; } void SDL_DelTouch(SDL_TouchID id) { int i, index; SDL_Touch *touch; if (SDL_num_touch == 0) { /* We've already cleaned up, we won't find this device */ return; } index = SDL_GetTouchIndex(id); touch = SDL_GetTouch(id); if (!touch) { return; } for (i = 0; i < touch->max_fingers; ++i) { SDL_free(touch->fingers[i]); } SDL_free(touch->fingers); SDL_free(touch->name); SDL_free(touch); SDL_num_touch--; SDL_touchDevices[index] = SDL_touchDevices[SDL_num_touch]; /* Delete this touch device for gestures */ SDL_GestureDelTouch(id); } void SDL_TouchQuit(void) { int i; for (i = SDL_num_touch; i--;) { SDL_DelTouch(SDL_touchDevices[i]->id); } SDL_assert(SDL_num_touch == 0); SDL_free(SDL_touchDevices); SDL_touchDevices = NULL; SDL_GestureQuit(); } /* vi: set ts=4 sw=4 expandtab: */
0
0.711646
1
0.711646
game-dev
MEDIA
0.840643
game-dev
0.682522
1
0.682522
tcmxx/UnityTensorflowKeras
2,149
Assets/UnityTensorflow/Examples/IntelligentPool/Scripts/BilliardSimple.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BilliardSimple : MonoBehaviour, IESOptimizable { protected BilliardGameSystem gameSystem; public ESOptimizer optimizer; private void Start() { gameSystem = FindObjectOfType(typeof(BilliardGameSystem)) as BilliardGameSystem; Debug.Assert(gameSystem != null, "Did not find BilliardGameSystem in the scene"); } private void Update() { if (optimizer.IsOptimizing) { gameSystem.EvaluateShot(ParamsToForceVector(optimizer.BestParams), Color.green); } } public List<float> Evaluate(List<double[]> action) { List<Vector3> forces = new List<Vector3>(); for (int i = 0; i < action.Count; ++i) { forces.Add(ParamsToForceVector(action[i])); } var values = gameSystem.EvaluateShotBatch(forces, Color.gray); return values; } public void OnReady(double[] vectorAction) { gameSystem.Shoot(ParamsToForceVector(vectorAction)); Physics.autoSimulation = true; } public Vector3 ParamsToForceVector(double[] x) { Vector3 force = (new Vector3((float)x[0], 0, (float)x[1])); //if (force.magnitude > maxForce) //force = maxForce * force.normalized; return force; } public Vector3 SamplePointToForceVectorRA(float x, float y) { x = Mathf.Clamp01(x); y = Mathf.Clamp01(y); float angle = x * Mathf.PI * 2; float force = y; double[] param = new double[2]; param[0] = Mathf.Sin(angle) * force; param[1] = Mathf.Cos(angle) * force; return ParamsToForceVector(param); } public Vector3 SamplePointToForceVectorXY(float x, float y) { x = Mathf.Clamp01(x); y = Mathf.Clamp01(y); float fx = x - 0.5f; float fy = y - 0.5f; double[] param = new double[2]; param[0] = fx * 2; param[1] = fy * 2; return ParamsToForceVector(param); } public int GetParamDimension() { return 2; } }
0
0.887565
1
0.887565
game-dev
MEDIA
0.983435
game-dev
0.996054
1
0.996054
mindreframer/love2d-games
4,996
1gam-jan2013/zoetrope/core/mouse.lua
-- Class: Mouse -- This tracks the state of the mouse, i.e. its coordinates onscreen -- and if a button was just pressed or released this frame. -- -- See http://love2d.org/wiki/MouseConstant for a list of mouse button names. -- -- Extends: -- <Sprite> Mouse = Sprite:extend{ visible = false, -- private property: _thisFrame -- what buttons are pressed this frame -- if you are interested in this, use allPressed() instead _thisFrame = {}, -- private property: lastFrame -- what mouse buttons were pressed last frame _lastFrame = {}, new = function (self, obj) obj = self:extend(obj) the.mouse = obj love.mousepressed = function (x, y, button) obj:mousePressed(button) end love.mousereleased = function (x, y, button) obj:mouseReleased(button) end if obj.onNew then obj:onNew() end return obj end, -- Method: pressed -- Are *any* of the buttons passed held down this frame? -- -- Arguments: -- string button descriptions passed as individual arguments; -- if none are passed, the left mouse button is assumed -- -- Returns: -- boolean pressed = function (self, ...) local buttons = {...} if #buttons == 0 then buttons[1] = 'l' end for _, value in pairs(buttons) do if STRICT then assert(type(value) == 'string', 'all mouse buttons are strings; asked to check a ' .. type(value)) end if self._thisFrame[value] then return true end end return false end, -- Method: justPressed -- Are *any* of the buttons passed pressed for the first time this frame? -- -- Arguments: -- string button descriptions passed as individual arguments; -- if none are passed, the left mouse button is assumed -- -- Returns: -- boolean justPressed = function (self, ...) local buttons = {...} if #buttons == 0 then buttons[1] = 'l' end for _, value in pairs(buttons) do if STRICT then assert(type(value) == 'string', 'all mouse buttons are strings; asked to check a ' .. type(value)) end if self._thisFrame[value] and not self._lastFrame[value] then return true end end return false end, -- Method: released -- Are *all* of the buttons passed not held down this frame? -- -- Arguments: -- string button descriptions passed as individual arguments; -- if none are passed, the left mouse button is assumed -- -- Returns: -- boolean released = function (self, ...) local buttons = {...} if #buttons == 0 then buttons[1] = 'l' end for _, value in pairs(buttons) do if STRICT then assert(type(value) == 'string', 'all mouse buttons are strings; asked to check a ' .. type(value)) end if self._thisFrame[value] then return false end end return true end, -- Method: justReleased -- Are *any* of the buttons passed released after being held last frame? -- -- Arguments: -- string button descriptions passed as individual arguments; -- if none are passed, the left mouse button is assumed -- -- Returns: -- boolean justReleased = function (self, ...) local buttons = {...} if #buttons == 0 then buttons[1] = 'l' end for _, value in pairs(buttons) do if STRICT then assert(type(value) == 'string', 'all mouse buttons are strings; asked to check a ' .. type(value)) end if self._lastFrame[value] and not self._thisFrame[value] then return true end end return false end, -- Method: allPressed -- Returns all buttons currently pressed this frame. -- -- Arguments: -- none -- -- Returns: -- string button descriptions; if nothing is pressed, nil allPressed = function (self) local result = {} for key, value in pairs(self._thisFrame) do if value then table.insert(result, key) end end return unpack(result) end, -- Method: allJustPressed -- Returns all buttons just pressed this frame. -- -- Arguments: -- none -- -- Returns: -- string button descriptions; if nothing is just pressed, nil allJustPressed = function (self) local result = {} for key, value in pairs(self._thisFrame) do if value and not self._lastFrame[key] then table.insert(result, key) end end return unpack(result) end, -- Method: allJustReleased -- Returns all buttons just released this frame. -- -- Arguments: -- none -- -- Returns: -- string buttons descriptions; if nothing is just pressed, nil allJustPressed = function (self) local result = {} for key, value in pairs(self._thisFrame) do if not value and self._lastFrame[key] then table.insert(result, key) end end return unpack(result) end, mousePressed = function (self, button) self._thisFrame[button] = true end, mouseReleased = function (self, button) self._thisFrame[button] = false end, endFrame = function (self, elapsed) for key, value in pairs(self._thisFrame) do self._lastFrame[key] = value end self.x = love.mouse.getX() - the.app.inset.x self.y = love.mouse.getY() - the.app.inset.y Sprite.endFrame(self) end, update = function() end }
0
0.743514
1
0.743514
game-dev
MEDIA
0.714894
game-dev
0.826843
1
0.826843
IAFEnvoy/IceAndFire-CE
3,388
common/src/main/java/com/iafenvoy/iceandfire/item/block/entity/DreadSpawnerBlockEntity.java
package com.iafenvoy.iceandfire.item.block.entity; import com.iafenvoy.iceandfire.entity.util.DreadSpawnerBaseLogic; import com.iafenvoy.iceandfire.registry.IafBlockEntities; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.Spawner; import net.minecraft.block.spawner.MobSpawnerEntry; import net.minecraft.block.spawner.MobSpawnerLogic; import net.minecraft.entity.EntityType; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket; import net.minecraft.registry.RegistryWrapper; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.random.Random; import net.minecraft.world.World; public class DreadSpawnerBlockEntity extends BlockEntity implements Spawner { private final DreadSpawnerBaseLogic spawner = new DreadSpawnerBaseLogic() { @Override public void sendStatus(World world, BlockPos pos, int status) { world.addSyncedBlockEvent(pos, Blocks.SPAWNER, status, 0); } @Override public void setSpawnEntry(World world, BlockPos pos, MobSpawnerEntry spawnEntry) { super.setSpawnEntry(world, pos, spawnEntry); if (world != null) { BlockState blockstate = world.getBlockState(pos); world.updateListeners(pos, blockstate, blockstate, 4); } } }; public DreadSpawnerBlockEntity(BlockPos pos, BlockState state) { super(IafBlockEntities.DREAD_SPAWNER.get(), pos, state); } @Override public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { super.readNbt(nbt, registryLookup); this.spawner.readNbt(this.world, this.pos, nbt); } public NbtCompound save(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { super.writeNbt(nbt, registryLookup); this.spawner.writeNbt(nbt); return nbt; } @Override public BlockEntityUpdateS2CPacket toUpdatePacket() { return BlockEntityUpdateS2CPacket.create(this); } @Override public NbtCompound toInitialChunkDataNbt(RegistryWrapper.WrapperLookup registryLookup) { NbtCompound compoundtag = this.save(new NbtCompound(), registryLookup); compoundtag.remove("SpawnPotentials"); return compoundtag; } @Override public boolean onSyncedBlockEvent(int p_59797_, int p_59798_) { return this.spawner.handleStatus(this.world, p_59797_) || super.onSyncedBlockEvent(p_59797_, p_59798_); } @Override public boolean copyItemDataRequiresOperator() { return true; } public MobSpawnerLogic getLogic() { return this.spawner; } public static void clientTick(World world, BlockPos pos, BlockState state, DreadSpawnerBlockEntity blockEntity) { blockEntity.spawner.clientTick(world, pos); } public static void serverTick(World world, BlockPos pos, BlockState state, DreadSpawnerBlockEntity blockEntity) { blockEntity.spawner.serverTick((ServerWorld) world, pos); } @Override public void setEntityType(EntityType<?> type, Random random) { this.spawner.setEntityId(type, this.world, random, this.pos); this.markDirty(); } }
0
0.863081
1
0.863081
game-dev
MEDIA
0.99728
game-dev
0.822734
1
0.822734
KAMKEEL/CustomNPC-Plus
1,345
src/main/java/noppes/npcs/items/ItemScripted.java
package noppes.npcs.items; import kamkeel.npcs.network.packets.data.ChatAlertPacket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import noppes.npcs.CustomItems; import noppes.npcs.CustomNpcs; import noppes.npcs.CustomNpcsPermissions; import noppes.npcs.NoppesUtilServer; import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumGuiType; public class ItemScripted extends ItemCustomizable { public ItemScripted() { maxStackSize = 1; setCreativeTab(CustomItems.tab); CustomNpcs.proxy.registerItem(this); setHasSubtypes(true); } public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { if (!world.isRemote) { if (player.isSneaking() && player.capabilities.isCreativeMode) { if (!ConfigScript.canScript(player, CustomNpcsPermissions.TOOL_SCRIPTED_ITEM)) { ChatAlertPacket.sendChatAlert((EntityPlayerMP) player, "availability.permission"); } else { NoppesUtilServer.sendOpenGui(player, EnumGuiType.ScriptItem, null, 0, 0, 0); } } } return super.onItemRightClick(stack, world, player); } }
0
0.864138
1
0.864138
game-dev
MEDIA
0.980227
game-dev
0.772175
1
0.772175
runuo/runuo
993
Scripts/Items/Skill Items/Magical/NecromancerSpellbook.cs
using System; using Server.Network; using Server.Spells; namespace Server.Items { public class NecromancerSpellbook : Spellbook { public override SpellbookType SpellbookType{ get{ return SpellbookType.Necromancer; } } public override int BookOffset{ get{ return 100; } } public override int BookCount{ get{ return ((Core.SE) ? 17 : 16); } } [Constructable] public NecromancerSpellbook() : this( (ulong)0 ) { } [Constructable] public NecromancerSpellbook( ulong content ) : base( content, 0x2253 ) { Layer = (Core.ML ? Layer.OneHanded : Layer.Invalid); } public NecromancerSpellbook( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)1 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); if( version == 0 && Core.ML ) Layer = Layer.OneHanded; } } }
0
0.758238
1
0.758238
game-dev
MEDIA
0.736126
game-dev
0.873029
1
0.873029
DignitySAMP/SP-RP
7,503
gamemodes/jobs/trucker/data/wholesaler.pwn
enum { E_WS_CONST_EASTBOARD_FARM, E_WS_CONST_FLINT_FARM, E_WS_CONST_STEVENS_FARM, E_WS_CONST_SOLARIN, E_WS_CONST_PINE_JEANS, E_WS_CONST_FALLEN_TREE, E_WS_CONST_APW, E_WS_CONST_GOODWEEK, E_WS_CONST_HQUARRY, E_WS_CONST_APJ, E_WS_CONST_AVERY_CON, E_WS_CONST_HILLTOP, E_WS_CONST_BIOENGI, E_WS_CONST_WSTONE_FARM, E_WS_CONST_LEAFY, E_WS_CONST_PANOP, E_WS_CONST_GP_OIL, E_WS_CONST_PLAINE } enum E_WHOLE_SALERS_DATA { E_WHOLESALERS_CONST, E_WHOLESALERS_DESC[32], E_WHOLESALERS_ICON, E_WHOLESALERS_MODEL, Float:E_WHOLESALERS_POS_X, Float:E_WHOLESALERS_POS_Y, Float:E_WHOLESALERS_POS_Z, E_WHOLESALERS_INVENTORY[5] } new Wholesalers[][E_WHOLE_SALERS_DATA] = { { E_WS_CONST_EASTBOARD_FARM, "EasterBoard Farm", 51, 19626, -86.0049, 2.6024, 3.1172, {ITEM_MEAT, ITEM_CHICKEN, ITEM_MILK, ITEM_EGG, ITEM_WHEAT} }, { E_WS_CONST_FLINT_FARM, "Flint Farm", 51, 19626, -1060.5466, -1205.4701, 129.2188, {ITEM_CORN, ITEM_POTATO, ITEM_LEMON, ITEM_APPLE, ITEM_FIG} }, { E_WS_CONST_STEVENS_FARM, "Stevens Farm", 51, 19626, -382.2487, -1438.9296, 25.7266, {ITEM_COTTON, ITEM_SILK, ITEM_SALT, ITEM_SUGAR, ITEM_WATER} }, { E_WS_CONST_SOLARIN, "Solarin Industries", 51, 1558, 790.2123, -605.0410, 16.0768, {ITEM_SOAP, ITEM_PAINT, ITEM_FRYING_OIL} }, { E_WS_CONST_PINE_JEANS, "Pine Jeans Wholesale", 51, 2384, -2109.1245, -2281.1162, 30.6319, {ITEM_COTTON, ITEM_SILK}, }, { E_WS_CONST_FALLEN_TREE, "Fallen Tree Co.", 51, 2060, -516.1326, -539.9604, 25.5234, {ITEM_IRON, ITEM_ROCK, ITEM_PLASTIC, ITEM_SAND, ITEM_CONCRETE} }, { E_WS_CONST_APW, "Angel Pine Sawmill", 51, 19793, -1971.7515, -2431.1162, 30.6250, {ITEM_SAPLING, ITEM_LOG, ITEM_PAPER} }, { E_WS_CONST_GOODWEEK, "Goodweek Auto Tech.", 51, 1096, 2836.3967, 954.0068, 10.7500, {ITEM_CAR_ENGINE, ITEM_MOTOR_OIL, ITEM_TYRE} }, { E_WS_CONST_HQUARRY, "Hunter Quarry", 11, 337, 819.8788, 857.7254, 12.0469, {ITEM_COAL, ITEM_ROCK, ITEM_SAND, ITEM_CONCRETE} }, { E_WS_CONST_APJ, "Angel Pine Junkyard", 51, 1327, -1896.4722, -1676.7620, 23.0156, {ITEM_IRON, ITEM_PLASTIC}, }, { E_WS_CONST_AVERY_CON, "Avery Construction", 51, 19904, 303.7226, -242.6337, 1.5781, {ITEM_IRON, ITEM_ROCK, ITEM_PLASTIC, ITEM_SAND, ITEM_CONCRETE} }, { E_WS_CONST_HILLTOP, "Hilltop Farm", 51, 19626, 1059.6060, -345.4454, 73.9922, {ITEM_COCAO, ITEM_CARROT}, }, { E_WS_CONST_BIOENGI, "Bio Engineering", 51, 1241, 1351.4584, 348.6518, 20.4107, {ITEM_ACETONE, ITEM_ETHANOL} }, { E_WS_CONST_WSTONE_FARM, "Whetstone Farm", 51, 19626, -1448.0990, -1522.8875, 101.7578, {ITEM_CORN, ITEM_WHEAT, ITEM_POTATO, ITEM_CARROT} }, { E_WS_CONST_LEAFY, "Leafy Strings", 51, 1271, -1095.7229, -1627.3754, 76.3672, {ITEM_STRING, ITEM_SILK}, }, { E_WS_CONST_PANOP, "The Panopticon", 51, 19793, -546.1591, -192.9910, 78.4063, {ITEM_SAPLING, ITEM_LOG, ITEM_PAPER} }, { E_WS_CONST_GP_OIL, "Green Palms Oil", 51, 1650, 262.5852, 1459.9071, 10.5859, {ITEM_GAS, ITEM_MOTOR_OIL}, }, { E_WS_CONST_PLAINE, "Plaine Food Co.", 51, 2803, 967.1489, 2159.9172, 10.8203, {ITEM_MEAT, ITEM_PORK, ITEM_CHICKEN, ITEM_TURKEY} } }; Trucker_LoadEntities_Wholesaler() { new text_long [ 512 ] ; for(new w, j = sizeof ( Wholesalers ); w < j; w++) { format(text_long, sizeof(text_long), "[%d] [%s]\n{DEDEDE}Available Commands: /crate [pickup/putdown]\n\n[Offers the following]:\n%s", w, Wholesalers[w][E_WHOLESALERS_DESC], Wholesaler_GetItems(w, .formatted=true)); CreateDynamicMapIcon(Wholesalers[w][E_WHOLESALERS_POS_X], Wholesalers[w][E_WHOLESALERS_POS_Y], Wholesalers[w][E_WHOLESALERS_POS_Z], Wholesalers[w][E_WHOLESALERS_ICON], 0); CreateDynamicPickup(Wholesalers[w][E_WHOLESALERS_MODEL], 1, Wholesalers[w][E_WHOLESALERS_POS_X], Wholesalers[w][E_WHOLESALERS_POS_Y], Wholesalers[w][E_WHOLESALERS_POS_Z]); CreateDynamic3DTextLabel(text_long, 0xDE921FFF, Wholesalers[w][E_WHOLESALERS_POS_X], Wholesalers[w][E_WHOLESALERS_POS_Y], Wholesalers[w][E_WHOLESALERS_POS_Z], 10.0); } } Wholesaler_GetClosestPoint(playerid) { for(new w, j = sizeof ( Wholesalers ); w < j; w++) { if ( IsPlayerInRangeOfPoint(playerid, 3.5, Wholesalers[w][E_WHOLESALERS_POS_X], Wholesalers[w][E_WHOLESALERS_POS_Y], Wholesalers[w][E_WHOLESALERS_POS_Z] ) ) { return w ; } else continue ; } return -1 ; } Wholesaler_GetItems(index, formatted=false) { new string[512], item_index, item_name [ 64 ] ; for(new i = 0; i < 5; i++) { if(Wholesalers[index][E_WHOLESALERS_INVENTORY][i] > 0) { item_index = Wholesalers[index][E_WHOLESALERS_INVENTORY][i] ; TruckerItem_GetName ( item_index, item_name, sizeof ( item_name ) ) ; if ( formatted ) { format(item_name, sizeof(item_name), "{97D270}%s{DEDEDE} [$%s]\n", item_name, IntegerWithDelimiter ( TruckerItem_GetPrice(item_index) )); } else format(item_name, sizeof(item_name), "[%s: $%s]", item_name, IntegerWithDelimiter ( TruckerItem_GetPrice(item_index) )); strcat(string, item_name); item_name[0] = EOS; // Clearing after storing so we don't overlap the old data. } } return string; } GetGoodsFromWholesaler(id) { new string[128], part[16], bool:do_no_harm = false; for(new p = 0; p < 5; p++) { if(Wholesalers[id][E_WHOLESALERS_INVENTORY][p] > 0) { format(part, sizeof(part), "%s, ", TruckerItem[Wholesalers[id][E_WHOLESALERS_INVENTORY][p]][E_WHOLESALER_ITEM_NAME]); strcat(string, part); if(p == 4) { strdel(string, strlen(string)-2, strlen(string)); } } else if(do_no_harm == false) { do_no_harm = true; strdel(string, strlen(string)-2, strlen(string)); } } return string; } CMD:gotowholesaler(playerid, params[]) { if ( GetPlayerAdminLevel ( playerid ) < ADMIN_LVL_ADVANCED ) { return SendServerMessage ( playerid, COLOR_ERROR, "Access Denied", "A3A3A3", "You don't have access to this command.") ; } new index, string [ 128 ]; if ( sscanf ( params, "i", index ) ) { return SendServerMessage(playerid, COLOR_JOB, "Trucker", "DEDEDE", "/gotowholesaler [index]" ) ; } if ( index < 0 || index >= sizeof ( Wholesalers ) ) { format ( string, sizeof ( string ), "Index can't be less than 0 or more than %d.", sizeof ( Wholesalers ) - 1 ) ; return SendServerMessage(playerid, COLOR_JOB, "Trucker", "DEDEDE", string ) ; } format ( string, sizeof ( string ), "You've teleported to \"%s\". It sells the following items:", Wholesalers [ index ] [ E_WHOLESALERS_DESC ] ) ; SendServerMessage(playerid, COLOR_JOB, "Trucker", "DEDEDE", string ) ; SendClientMessage ( playerid, 0xDEDEDEFF, Wholesaler_GetItems(index, .formatted=false) ) ; PauseAC(playerid, 3); SetPlayerPos(playerid, Wholesalers[index][E_WHOLESALERS_POS_X], Wholesalers[index][E_WHOLESALERS_POS_Y], Wholesalers[index][E_WHOLESALERS_POS_Z]); return true ; } IsWholesalerAcceptingGood(wholesalerid, goodid) { new bool:response = false; for(new inv = 0; inv < 5; inv++) { if(Wholesalers[wholesalerid][E_WHOLESALERS_INVENTORY][inv] == goodid) { response = true; break; } } return response; } GetNearestWholesalerID(playerid) { new ID = -1; for(new w = 0; w < sizeof(Wholesalers); w++) { if(IsPlayerInRangeOfPoint(playerid, 2.5, Wholesalers[w][E_WHOLESALERS_POS_X], Wholesalers[w][E_WHOLESALERS_POS_Y], Wholesalers[w][E_WHOLESALERS_POS_Z])) { ID = w; break; } } return ID; }
0
0.926318
1
0.926318
game-dev
MEDIA
0.82859
game-dev
0.816459
1
0.816459
bokuweb/flownes
1,235
src/parser/index.js
/* @flow */ import log from '../helper/log'; const NES_HEADER_SIZE = 0x0010; const PROGRAM_ROM_SIZE = 0x4000; const CHARACTER_ROM_SIZE = 0x2000; export type NesROM = { isHorizontalMirror: boolean; characterROM: Uint8Array; programROM: Uint8Array; }; export const parse = (nesBuffer: ArrayBuffer): NesROM => { const nes = new Uint8Array(nesBuffer); if ([].slice.call(nes, 0, 3).map(v => String.fromCharCode(v)).join('') !== 'NES') { throw new Error('This file is not NES format.'); } const programROMPages = nes[4]; log.info('prom pages =', programROMPages); const characterROMPages = nes[5]; log.info('crom pages =', characterROMPages); const isHorizontalMirror = !(nes[6] & 0x01); const mapper = (((nes[6] & 0xF0) >> 4) | nes[7] & 0xF0); log.info('mapper', mapper); const characterROMStart = NES_HEADER_SIZE + programROMPages * PROGRAM_ROM_SIZE; const characterROMEnd = characterROMStart + characterROMPages * CHARACTER_ROM_SIZE; // console.log('prom pages = ', programROMPages); const nesROM: NesROM = { isHorizontalMirror, programROM: nes.slice(NES_HEADER_SIZE, characterROMStart - 1), characterROM: nes.slice(characterROMStart, characterROMEnd - 1), }; return nesROM; };
0
0.779276
1
0.779276
game-dev
MEDIA
0.726523
game-dev
0.761871
1
0.761871
VideogameSources/gta3-decomp-alt
259,061
src/peds/Ped.cpp
#include "common.h" #include "main.h" #include "Pools.h" #include "Particle.h" #include "RpAnimBlend.h" #include "Bones.h" #include "Ped.h" #include "AnimBlendAssociation.h" #include "Fire.h" #include "DMAudio.h" #include "General.h" #include "VisibilityPlugins.h" #include "HandlingMgr.h" #include "Replay.h" #include "Radar.h" #include "PedPlacement.h" #include "Shadows.h" #include "Weather.h" #include "ZoneCull.h" #include "Population.h" #include "Pad.h" #include "Phones.h" #include "TrafficLights.h" #include "CopPed.h" #include "Script.h" #include "CarCtrl.h" #include "Garages.h" #include "WaterLevel.h" #include "Timecycle.h" #include "ParticleObject.h" #include "Floater.h" #include "Range2D.h" CPed *gapTempPedList[50]; uint16 gnNumTempPedList; static CColPoint aTempPedColPts[MAX_COLLISION_POINTS]; uint16 CPed::nThreatReactionRangeMultiplier = 1; uint16 CPed::nEnterCarRangeMultiplier = 1; bool CPed::bNastyLimbsCheat; bool CPed::bPedCheat2; bool CPed::bPedCheat3; CVector2D CPed::ms_vec2DFleePosition; void *CPed::operator new(size_t sz) { return CPools::GetPedPool()->New(); } void *CPed::operator new(size_t sz, int handle) { return CPools::GetPedPool()->New(handle); } void CPed::operator delete(void *p, size_t sz) { CPools::GetPedPool()->Delete((CPed*)p); } void CPed::operator delete(void *p, int handle) { CPools::GetPedPool()->Delete((CPed*)p); } #ifdef DEBUGMENU bool CPed::bPopHeadsOnHeadshot = false; #endif CPed::CPed(uint32 pedType) : m_pedIK(this) { m_type = ENTITY_TYPE_PED; bPedPhysics = true; bUseCollisionRecords = true; m_vecAnimMoveDelta.x = 0.0f; m_vecAnimMoveDelta.y = 0.0f; m_fHealth = 100.0f; m_fArmour = 0.0f; m_nPedType = pedType; m_lastSoundStart = 0; m_soundStart = 0; m_lastQueuedSound = SOUND_NO_SOUND; m_queuedSound = SOUND_NO_SOUND; m_objective = OBJECTIVE_NONE; m_prevObjective = OBJECTIVE_NONE; #ifdef FIX_BUGS m_objectiveTimer = 0; #endif CharCreatedBy = RANDOM_CHAR; m_leader = nil; m_pedInObjective = nil; m_carInObjective = nil; bInVehicle = false; m_pMyVehicle = nil; m_pVehicleAnim = nil; m_vecOffsetSeek.x = 0.0f; m_vecOffsetSeek.y = 0.0f; m_vecOffsetSeek.z = 0.0f; m_pedFormation = FORMATION_UNDEFINED; m_collidingThingTimer = 0; m_nPedStateTimer = 0; m_actionX = 0.0f; m_actionY = 0.0f; m_phoneTalkTimer = 0; m_stateUnused = 0; m_leaveCarTimer = 0; m_getUpTimer = 0; m_attackTimer = 0; m_timerUnused = 0; m_lookTimer = 0; m_standardTimer = 0; m_shootTimer = 0; m_hitRecoverTimer = 0; m_duckAndCoverTimer = 0; m_moved = CVector2D(0.0f, 0.0f); m_fRotationCur = 0.0f; m_headingRate = 15.0f; m_fRotationDest = 0.0f; m_vehEnterType = CAR_DOOR_LF; m_walkAroundType = 0; m_pCurrentPhysSurface = nil; m_vecOffsetFromPhysSurface = CVector(0.0f, 0.0f, 0.0f); m_pSeekTarget = nil; m_vecSeekPos = CVector(0.0f, 0.0f, 0.0f); m_wepSkills = 0; m_distanceToCountSeekDone = 1.0f; bRunningToPhone = false; m_phoneId = -1; m_lastAccident = 0; m_fleeFrom = nil; m_fleeFromPosX = 0; m_fleeFromPosY = 0; m_fleeTimer = 0; m_vecSeekPosEx = CVector(0.0f, 0.0f, 0.0f); m_distanceToCountSeekDoneEx = 0.0f; m_nWaitState = WAITSTATE_FALSE; m_nWaitTimer = 0; m_pCollidingEntity = nil; m_nPedState = PED_IDLE; m_nLastPedState = PED_NONE; m_nMoveState = PEDMOVE_STILL; #ifdef FIX_BUGS m_nPrevMoveState = PEDMOVE_NONE; #endif m_nStoredMoveState = PEDMOVE_NONE; m_pFire = nil; m_pPointGunAt = nil; m_pLookTarget = nil; m_fLookDirection = 0.0f; m_pCurSurface = nil; m_wanderRangeBounds = nil; m_nPathNodes = 0; m_nCurPathNode = 0; m_nPathDir = 0; m_pLastPathNode = nil; m_pNextPathNode = nil; m_routeLastPoint = -1; m_routeStartPoint = 0; m_routePointsPassed = 0; m_routeType = 0; m_bodyPartBleeding = -1; m_fMass = 70.0f; m_fTurnMass = 100.0f; m_fAirResistance = 0.4f / m_fMass; m_fElasticity = 0.05f; bIsStanding = false; bWasStanding = false; bIsAttacking = false; bIsPointingGunAt = false; bIsLooking = false; bKeepTryingToLook = false; bIsRestoringLook = false; bIsAimingGun = false; bIsRestoringGun = false; bCanPointGunAtTarget = false; bIsTalking = false; bIsInTheAir = false; bIsLanding = false; bIsRunning = false; bHitSomethingLastFrame = false; bVehEnterDoorIsBlocked = false; bCanPedEnterSeekedCar = false; bRespondsToThreats = true; bRenderPedInCar = true; bChangedSeat = false; bUpdateAnimHeading = false; bBodyPartJustCameOff = false; bIsShooting = false; bFindNewNodeAfterStateRestore = false; bGonnaInvestigateEvent = false; bPedIsBleeding = false; bStopAndShoot = false; bIsPedDieAnimPlaying = false; bUsePedNodeSeek = false; bObjectiveCompleted = false; bScriptObjectiveCompleted = false; bKindaStayInSamePlace = false; bBeingChasedByPolice = false; bNotAllowedToDuck = false; bCrouchWhenShooting = false; bIsDucking = false; bGetUpAnimStarted = false; bDoBloodyFootprints = false; bFleeAfterExitingCar = false; bWanderPathAfterExitingCar = false; bIsLeader = false; bDontDragMeOutCar = false; m_ped_flagF8 = false; bWillBeQuickJacked = false; bCancelEnteringCar = false; bObstacleShowedUpDuringKillObjective = false; bDuckAndCover = false; bStillOnValidPoly = false; bAllowMedicsToReviveMe = true; bResetWalkAnims = false; bStartWanderPathOnFoot = false; bOnBoat = false; bBusJacked = false; bGonnaKillTheCarJacker = false; bFadeOut = false; bKnockedUpIntoAir = false; bHitSteepSlope = false; bCullExtraFarAway = false; bClearObjective = false; bTryingToReachDryLand = false; bCollidedWithMyVehicle = false; bRichFromMugging = false; bChrisCriminal = false; bShakeFist = false; bNoCriticalHits = false; bVehExitWillBeInstant = false; bHasAlreadyBeenRecorded = false; bFallenDown = false; #ifdef KANGAROO_CHEAT m_ped_flagI80 = false; #endif #ifdef VC_PED_PORTS bSomeVCflag1 = false; #endif if (CGeneral::GetRandomNumber() & 3) bHasACamera = false; else bHasACamera = true; m_audioEntityId = DMAudio.CreateEntity(AUDIOTYPE_PHYSICAL, this); DMAudio.SetEntityStatus(m_audioEntityId, 1); m_fearFlags = CPedType::GetThreats(m_nPedType); m_threatEntity = nil; m_eventOrThreat = CVector2D(0.0f, 0.0f); m_pEventEntity = nil; m_fAngleToEvent = 0.0f; m_numNearPeds = 0; for (int i = 0; i < ARRAY_SIZE(m_nearPeds); i++) { m_nearPeds[i] = nil; if (i < ARRAY_SIZE(m_pPathNodesStates)) { m_pPathNodesStates[i] = nil; } } m_maxWeaponTypeAllowed = WEAPONTYPE_UNARMED; m_currentWeapon = WEAPONTYPE_UNARMED; m_storedWeapon = WEAPONTYPE_UNIDENTIFIED; for(int i = 0; i < WEAPONTYPE_TOTAL_INVENTORY_WEAPONS; i++) { CWeapon &weapon = GetWeapon(i); weapon.m_eWeaponType = WEAPONTYPE_UNARMED; weapon.m_eWeaponState = WEAPONSTATE_READY; weapon.m_nAmmoInClip = 0; weapon.m_nAmmoTotal = 0; weapon.m_nTimer = 0; } m_curFightMove = FIGHTMOVE_NULL; GiveWeapon(WEAPONTYPE_UNARMED, 0); m_wepAccuracy = 60; m_lastWepDam = -1; m_collPoly.valid = false; m_fCollisionSpeed = 0.0f; m_wepModelID = -1; #ifdef PED_SKIN m_pWeaponModel = nil; #endif CPopulation::UpdatePedCount((ePedType)m_nPedType, false); } CPed::~CPed(void) { CWorld::Remove(this); CRadar::ClearBlipForEntity(BLIP_CHAR, CPools::GetPedPool()->GetIndex(this)); if (InVehicle()){ uint8 door_flag = GetCarDoorFlag(m_vehEnterType); if (m_pMyVehicle->pDriver == this) m_pMyVehicle->pDriver = nil; else { // FIX: Passenger counter now decreasing after removing ourself from vehicle. m_pMyVehicle->RemovePassenger(this); } if (m_nPedState == PED_EXIT_CAR || m_nPedState == PED_DRAG_FROM_CAR) m_pMyVehicle->m_nGettingOutFlags &= ~door_flag; bInVehicle = false; m_pMyVehicle = nil; } else if (EnteringCar()) { QuitEnteringCar(); } if (m_pFire) m_pFire->Extinguish(); CPopulation::UpdatePedCount((ePedType)m_nPedType, true); DMAudio.DestroyEntity(m_audioEntityId); } void CPed::Initialise(void) { debug("Initialising CPed...\n"); CPedType::Initialise(); LoadFightData(); SetAnimOffsetForEnterOrExitVehicle(); debug("CPed ready\n"); } void CPed::SetModelIndex(uint32 mi) { CEntity::SetModelIndex(mi); RpAnimBlendClumpInit(GetClump()); RpAnimBlendClumpFillFrameArray(GetClump(), m_pFrames); CPedModelInfo *modelInfo = (CPedModelInfo *)CModelInfo::GetModelInfo(GetModelIndex()); SetPedStats(modelInfo->m_pedStatType); m_headingRate = m_pedStats->m_headingChangeRate; m_animGroup = (AssocGroupId) modelInfo->m_animGroup; CAnimManager::AddAnimation(GetClump(), m_animGroup, ANIM_IDLE_STANCE); // This is a mistake by R*, velocity is CVector, whereas m_vecAnimMoveDelta is CVector2D. (*RPANIMBLENDCLUMPDATA(m_rwObject))->velocity = (CVector*) &m_vecAnimMoveDelta; #ifdef PED_SKIN if(modelInfo->GetHitColModel() == nil) modelInfo->CreateHitColModelSkinned(GetClump()); #endif } void CPed::SetPedStats(ePedStats pedStat) { m_pedStats = CPedStats::ms_apPedStats[pedStat]; } void CPed::BuildPedLists(void) { if (((CTimer::GetFrameCounter() + m_randomSeed) % 16) == 0) { CVector centre = CEntity::GetBoundCentre(); CRect rect(centre.x - 20.0f, centre.y - 20.0f, centre.x + 20.0f, centre.y + 20.0f); int xstart = CWorld::GetSectorIndexX(rect.left); int ystart = CWorld::GetSectorIndexY(rect.top); int xend = CWorld::GetSectorIndexX(rect.right); int yend = CWorld::GetSectorIndexY(rect.bottom); gnNumTempPedList = 0; for(int y = ystart; y <= yend; y++) { for(int x = xstart; x <= xend; x++) { for (CPtrNode *pedPtrNode = CWorld::GetSector(x,y)->m_lists[ENTITYLIST_PEDS].first; pedPtrNode; pedPtrNode = pedPtrNode->next) { CPed *ped = (CPed*)pedPtrNode->item; if (ped != this && !ped->bInVehicle) { float dist = (ped->GetPosition() - GetPosition()).Magnitude2D(); if (nThreatReactionRangeMultiplier * 30.0f > dist) { gapTempPedList[gnNumTempPedList] = ped; gnNumTempPedList++; assert(gnNumTempPedList < ARRAY_SIZE(gapTempPedList)); } } } } } gapTempPedList[gnNumTempPedList] = nil; SortPeds(gapTempPedList, 0, gnNumTempPedList - 1); for (m_numNearPeds = 0; m_numNearPeds < ARRAY_SIZE(m_nearPeds); m_numNearPeds++) { CPed *ped = gapTempPedList[m_numNearPeds]; if (!ped) break; m_nearPeds[m_numNearPeds] = ped; } for (int pedToClear = m_numNearPeds; pedToClear < ARRAY_SIZE(m_nearPeds); pedToClear++) m_nearPeds[pedToClear] = nil; } else { for(int i = 0; i < ARRAY_SIZE(m_nearPeds); ) { bool removePed = false; if (m_nearPeds[i]) { if (m_nearPeds[i]->IsPointerValid()) { float distSqr = (GetPosition() - m_nearPeds[i]->GetPosition()).MagnitudeSqr2D(); if (distSqr > 900.0f) removePed = true; } else removePed = true; } if (removePed) { // If we arrive here, the ped we're checking isn't "near", so we should remove it. for (int j = i; j < ARRAY_SIZE(m_nearPeds) - 1; j++) { m_nearPeds[j] = m_nearPeds[j + 1]; m_nearPeds[j + 1] = nil; } // Above loop won't work on last slot, so we need to empty it. m_nearPeds[ARRAY_SIZE(m_nearPeds) - 1] = nil; m_numNearPeds--; } else i++; } } } bool CPed::OurPedCanSeeThisOne(CEntity *target) { CColPoint colpoint; CEntity *ent; CVector2D dist = CVector2D(target->GetPosition()) - CVector2D(GetPosition()); // Check if target is behind ped if (DotProduct2D(dist, CVector2D(GetForward())) < 0.0f) return false; // Check if target is too far away if (dist.Magnitude() >= 40.0f) return false; // Check line of sight from head CVector headPos = this->GetPosition(); headPos.z += 1.0f; return !CWorld::ProcessLineOfSight(headPos, target->GetPosition(), colpoint, ent, true, false, false, false, false, false); } // Some kind of binary sort void CPed::SortPeds(CPed **list, int min, int max) { if (min >= max) return; CVector leftDiff, rightDiff; CVector middleDiff = GetPosition() - list[(max + min) / 2]->GetPosition(); float middleDist = middleDiff.Magnitude(); int left = max; int right = min; while(right <= left){ float rightDist, leftDist; do { rightDiff = GetPosition() - list[right]->GetPosition(); rightDist = rightDiff.Magnitude(); } while (middleDist > rightDist && ++right); do { leftDiff = GetPosition() - list[left]->GetPosition(); leftDist = leftDiff.Magnitude(); } while (middleDist < leftDist && left--); if (right <= left) { CPed *ped = list[right]; list[right] = list[left]; list[left] = ped; right++; left--; } } SortPeds(list, min, left); SortPeds(list, right, max); } void CPed::SetMoveState(eMoveState state) { m_nMoveState = state; } void CPed::SetMoveAnim(void) { if (m_nStoredMoveState == m_nMoveState || !IsPedInControl()) return; if (m_nMoveState == PEDMOVE_NONE) { m_nStoredMoveState = PEDMOVE_NONE; return; } AssocGroupId animGroupToUse; if (m_leader && m_leader->IsPlayer()) animGroupToUse = ASSOCGRP_PLAYER; else animGroupToUse = m_animGroup; CAnimBlendAssociation *animAssoc = RpAnimBlendClumpGetFirstAssociation(GetClump(), ASSOC_BLOCK); if (!animAssoc) { CAnimBlendAssociation *fightIdleAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FIGHT_IDLE); animAssoc = fightIdleAssoc; if (fightIdleAssoc && m_nPedState == PED_FIGHT) return; if (fightIdleAssoc) { CAnimBlendAssociation *idleAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_STANCE); if (!idleAssoc || idleAssoc->blendDelta <= 0.0f) { animAssoc->flags |= ASSOC_DELETEFADEDOUT; animAssoc = CAnimManager::BlendAnimation(GetClump(), animGroupToUse, ANIM_IDLE_STANCE, 8.0f); } } } if (!animAssoc) { animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_TIRED); if (animAssoc) if (m_nWaitState == WAITSTATE_STUCK || m_nWaitState == WAITSTATE_FINISH_FLEE) return; if (animAssoc) { CAnimBlendAssociation *idleAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_STANCE); if (!idleAssoc || idleAssoc->blendDelta <= 0.0f) { animAssoc->flags |= ASSOC_DELETEFADEDOUT; animAssoc = CAnimManager::BlendAnimation(GetClump(), animGroupToUse, ANIM_IDLE_STANCE, 4.0f); } } } if (!animAssoc) { m_nStoredMoveState = m_nMoveState; if (m_nMoveState == PEDMOVE_WALK || m_nMoveState == PEDMOVE_RUN || m_nMoveState == PEDMOVE_SPRINT) { for (CAnimBlendAssociation *assoc = RpAnimBlendClumpGetFirstAssociation(GetClump(), ASSOC_PARTIAL); assoc; assoc = RpAnimBlendGetNextAssociation(assoc, ASSOC_PARTIAL)) { if (!(assoc->flags & ASSOC_FADEOUTWHENDONE)) { assoc->blendDelta = -2.0f; assoc->flags |= ASSOC_DELETEFADEDOUT; } } ClearAimFlag(); ClearLookFlag(); } switch (m_nMoveState) { case PEDMOVE_STILL: animAssoc = CAnimManager::BlendAnimation(GetClump(), animGroupToUse, ANIM_IDLE_STANCE, 4.0f); break; case PEDMOVE_WALK: animAssoc = CAnimManager::BlendAnimation(GetClump(), animGroupToUse, ANIM_WALK, 1.0f); break; case PEDMOVE_RUN: if (m_nPedState == PED_FLEE_ENTITY) { animAssoc = CAnimManager::BlendAnimation(GetClump(), animGroupToUse, ANIM_RUN, 3.0f); } else { animAssoc = CAnimManager::BlendAnimation(GetClump(), animGroupToUse, ANIM_RUN, 1.0f); } break; case PEDMOVE_SPRINT: animAssoc = CAnimManager::BlendAnimation(GetClump(), animGroupToUse, ANIM_SPRINT, 1.0f); break; default: break; } if (animAssoc) { if (m_leader) { CAnimBlendAssociation *walkAssoc = RpAnimBlendClumpGetAssociation(m_leader->GetClump(), ANIM_WALK); if (!walkAssoc) walkAssoc = RpAnimBlendClumpGetAssociation(m_leader->GetClump(), ANIM_RUN); if (!walkAssoc) walkAssoc = RpAnimBlendClumpGetAssociation(m_leader->GetClump(), ANIM_SPRINT); if (walkAssoc) { animAssoc->speed = walkAssoc->speed; } else { if (CharCreatedBy == MISSION_CHAR) animAssoc->speed = 1.0f; else animAssoc->speed = 1.2f - m_randomSeed * 0.4f / MYRAND_MAX; } } else { if (CharCreatedBy == MISSION_CHAR) animAssoc->speed = 1.0f; else animAssoc->speed = 1.2f - m_randomSeed * 0.4f / MYRAND_MAX; } } } } void CPed::StopNonPartialAnims(void) { CAnimBlendAssociation *assoc; for (assoc = RpAnimBlendClumpGetFirstAssociation(GetClump()); assoc; assoc = RpAnimBlendGetNextAssociation(assoc)) { if (!assoc->IsPartial()) assoc->flags &= ~ASSOC_RUNNING; } } void CPed::RestartNonPartialAnims(void) { CAnimBlendAssociation *assoc; for (assoc = RpAnimBlendClumpGetFirstAssociation(GetClump()); assoc; assoc = RpAnimBlendGetNextAssociation(assoc)) { if (!assoc->IsPartial()) assoc->SetRun(); } } void CPed::SetStoredState(void) { if (m_nLastPedState != PED_NONE || !CanPedReturnToState()) return; if (m_nPedState == PED_WANDER_PATH) { bFindNewNodeAfterStateRestore = true; if (m_nMoveState == PEDMOVE_NONE || m_nMoveState == PEDMOVE_STILL) m_nMoveState = PEDMOVE_WALK; } #ifdef VC_PED_PORTS if (m_nPedState != PED_IDLE) #endif { m_nLastPedState = m_nPedState; if (m_nMoveState >= m_nPrevMoveState) m_nPrevMoveState = m_nMoveState; } } void CPed::RestorePreviousState(void) { if(!CanSetPedState() || m_nPedState == PED_FALL) return; if (m_nPedState == PED_GETUP && !bGetUpAnimStarted) return; if (InVehicle()) { m_nPedState = PED_DRIVING; m_nLastPedState = PED_NONE; } else { if (m_nLastPedState == PED_NONE) { if (!IsPlayer() && CharCreatedBy != MISSION_CHAR && m_objective == OBJECTIVE_NONE) { if (SetWanderPath(CGeneral::GetRandomNumber() & 7) != 0) return; } SetIdle(); return; } switch (m_nLastPedState) { case PED_IDLE: SetIdle(); break; case PED_WANDER_PATH: m_nPedState = PED_WANDER_PATH; bIsRunning = false; if (bFindNewNodeAfterStateRestore) { if (m_pNextPathNode) { CVector diff = m_pNextPathNode->GetPosition() - GetPosition(); if (diff.MagnitudeSqr() < sq(7.0f)) { SetMoveState(PEDMOVE_WALK); break; } } } SetWanderPath(CGeneral::GetRandomNumber() & 7); break; default: m_nPedState = m_nLastPedState; SetMoveState((eMoveState) m_nPrevMoveState); break; } m_nLastPedState = PED_NONE; } } uint32 CPed::ScanForThreats(void) { int fearFlags = m_fearFlags; CVector ourPos = GetPosition(); float closestPedDist = 60.0f; CVector2D explosionPos = GetPosition(); if (fearFlags & PED_FLAG_EXPLOSION && CheckForExplosions(explosionPos)) { m_eventOrThreat = explosionPos; return PED_FLAG_EXPLOSION; } CPed *shooter = nil; if ((fearFlags & PED_FLAG_GUN) && (shooter = CheckForGunShots()) && (m_nPedType != shooter->m_nPedType || m_nPedType == PEDTYPE_CIVMALE || m_nPedType == PEDTYPE_CIVFEMALE)) { if (!IsGangMember()) { m_threatEntity = shooter; m_threatEntity->RegisterReference((CEntity **) &m_threatEntity); return PED_FLAG_GUN; } if (CPedType::GetFlag(shooter->m_nPedType) & fearFlags) { m_threatEntity = shooter; m_threatEntity->RegisterReference((CEntity **) &m_threatEntity); return CPedType::GetFlag(shooter->m_nPedType); } } CPed *deadPed = nil; if (fearFlags & PED_FLAG_DEADPEDS && CharCreatedBy != MISSION_CHAR && (deadPed = CheckForDeadPeds()) != nil && (deadPed->GetPosition() - ourPos).MagnitudeSqr() < sq(20.0f)) { m_pEventEntity = deadPed; m_pEventEntity->RegisterReference((CEntity **) &m_pEventEntity); return PED_FLAG_DEADPEDS; } else { uint32 flagsOfSomePed = 0; CPed *pedToFearFrom = nil; #ifndef VC_PED_PORTS for (int i = 0; i < m_numNearPeds; i++) { if (CharCreatedBy != RANDOM_CHAR || m_nearPeds[i]->CharCreatedBy != MISSION_CHAR || m_nearPeds[i]->IsPlayer()) { CPed *nearPed = m_nearPeds[i]; // BUG: WTF Rockstar?! Putting this here will result in returning the flags of farthest ped to us, since m_nearPeds is sorted by distance. // Fixed at the bottom of the function. flagsOfSomePed = CPedType::GetFlag(nearPed->m_nPedType); if (CPedType::GetFlag(nearPed->m_nPedType) & fearFlags) { if (nearPed->m_fHealth > 0.0f && OurPedCanSeeThisOne(m_nearPeds[i])) { // FIX: Taken from VC #ifdef FIX_BUGS float nearPedDistSqr = (nearPed->GetPosition() - ourPos).MagnitudeSqr2D(); #else float nearPedDistSqr = (CVector2D(ourPos) - explosionPos).MagnitudeSqr(); #endif if (sq(closestPedDist) > nearPedDistSqr) { closestPedDist = Sqrt(nearPedDistSqr); pedToFearFrom = m_nearPeds[i]; } } } } } #else bool weSawOurEnemy = false; bool weMaySeeOurEnemy = false; float closestEnemyDist = 60.0f; if ((CTimer::GetFrameCounter() + (uint8)m_randomSeed + 16) & 4) { for (int i = 0; i < m_numNearPeds; ++i) { if (CharCreatedBy == RANDOM_CHAR && m_nearPeds[i]->CharCreatedBy == MISSION_CHAR && !m_nearPeds[i]->IsPlayer()) { continue; } // BUG: Explained at the same occurence of this bug above. Fixed at the bottom of the function. flagsOfSomePed = CPedType::GetFlag(m_nearPeds[i]->m_nPedType); if (flagsOfSomePed & fearFlags) { if (m_nearPeds[i]->m_fHealth > 0.0f) { // VC also has ability to include objects to line of sight check here (via last bit of flagsL) if (OurPedCanSeeThisOne(m_nearPeds[i])) { if (m_nearPeds[i]->m_nPedState == PED_ATTACK) { if (m_nearPeds[i]->m_pedInObjective == this) { float enemyDistSqr = (m_nearPeds[i]->GetPosition() - ourPos).MagnitudeSqr2D(); if (sq(closestEnemyDist) > enemyDistSqr) { float enemyDist = Sqrt(enemyDistSqr); weSawOurEnemy = true; closestPedDist = enemyDist; closestEnemyDist = enemyDist; pedToFearFrom = m_nearPeds[i]; } } } else { float nearPedDistSqr = (m_nearPeds[i]->GetPosition() - ourPos).MagnitudeSqr2D(); if (sq(closestPedDist) > nearPedDistSqr && !weSawOurEnemy) { closestPedDist = Sqrt(nearPedDistSqr); pedToFearFrom = m_nearPeds[i]; } } } else if (!weSawOurEnemy) { CPed *nearPed = m_nearPeds[i]; if (nearPed->m_nPedState == PED_ATTACK) { CColPoint foundCol; CEntity *foundEnt; // We don't see him yet but he's behind a ped, vehicle or object // VC also has ability to include objects to line of sight check here (via last bit of flagsL) if (!CWorld::ProcessLineOfSight(ourPos, nearPed->GetPosition(), foundCol, foundEnt, true, false, false, false, false, false, false)) { if (nearPed->m_pedInObjective == this) { float enemyDistSqr = (m_nearPeds[i]->GetPosition() - ourPos).MagnitudeSqr2D(); if (sq(closestEnemyDist) > enemyDistSqr) { float enemyDist = Sqrt(enemyDistSqr); weMaySeeOurEnemy = true; closestPedDist = enemyDist; closestEnemyDist = enemyDist; pedToFearFrom = m_nearPeds[i]; } } else if (!nearPed->GetWeapon()->IsTypeMelee() && !weMaySeeOurEnemy) { float nearPedDistSqr = (m_nearPeds[i]->GetPosition() - ourPos).MagnitudeSqr2D(); if (sq(closestPedDist) > nearPedDistSqr) { weMaySeeOurEnemy = true; closestPedDist = Sqrt(nearPedDistSqr); pedToFearFrom = m_nearPeds[i]; } } } } } } } } } #endif int16 lastVehicle; CEntity* vehicles[8]; CWorld::FindObjectsInRange(ourPos, 20.0f, true, &lastVehicle, 6, vehicles, false, true, false, false, false); CVehicle* foundVeh = nil; for (int i = 0; i < lastVehicle; i++) { CVehicle* nearVeh = (CVehicle*)vehicles[i]; CPed *driver = nearVeh->pDriver; if (driver) { // BUG: Same bug as above. Fixed at the bottom of function. flagsOfSomePed = CPedType::GetFlag(driver->m_nPedType); if (CPedType::GetFlag(driver->m_nPedType) & fearFlags) { if (driver->m_fHealth > 0.0f && OurPedCanSeeThisOne(nearVeh->pDriver)) { // FIX: Taken from VC #ifdef FIX_BUGS float driverDistSqr = (driver->GetPosition() - ourPos).MagnitudeSqr2D(); #else float driverDistSqr = (CVector2D(ourPos) - explosionPos).MagnitudeSqr(); #endif if (sq(closestPedDist) > driverDistSqr) { closestPedDist = Sqrt(driverDistSqr); pedToFearFrom = nearVeh->pDriver; } } } } } m_threatEntity = pedToFearFrom; if (m_threatEntity) m_threatEntity->RegisterReference((CEntity **) &m_threatEntity); #ifdef FIX_BUGS if (pedToFearFrom) flagsOfSomePed = CPedType::GetFlag(((CPed*)m_threatEntity)->m_nPedType); else flagsOfSomePed = 0; #endif return flagsOfSomePed; } } void CPed::SetLookFlag(float direction, bool keepTryingToLook) { if (m_lookTimer < CTimer::GetTimeInMilliseconds()) { bIsLooking = true; bIsRestoringLook = false; m_pLookTarget = nil; m_fLookDirection = direction; m_lookTimer = 0; bKeepTryingToLook = keepTryingToLook; if (m_nPedState != PED_DRIVING) { m_pedIK.m_flags &= ~CPedIK::LOOKAROUND_HEAD_ONLY; } } } void CPed::SetLookFlag(CEntity *target, bool keepTryingToLook) { if (m_lookTimer < CTimer::GetTimeInMilliseconds()) { bIsLooking = true; bIsRestoringLook = false; m_pLookTarget = target; m_pLookTarget->RegisterReference((CEntity**)&m_pLookTarget); m_fLookDirection = 999999.0f; m_lookTimer = 0; bKeepTryingToLook = keepTryingToLook; if (m_nPedState != PED_DRIVING) { m_pedIK.m_flags &= ~CPedIK::LOOKAROUND_HEAD_ONLY; } } } void CPed::ClearLookFlag(void) { if (bIsLooking) { bIsLooking = false; bIsRestoringLook = true; bShakeFist = false; m_pedIK.m_flags &= ~CPedIK::LOOKAROUND_HEAD_ONLY; if (IsPlayer()) m_lookTimer = CTimer::GetTimeInMilliseconds() + 2000; else m_lookTimer = CTimer::GetTimeInMilliseconds() + 4000; if (m_nPedState == PED_LOOK_HEADING || m_nPedState == PED_LOOK_ENTITY) { ClearLook(); } } } void FinishFuckUCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; if (animAssoc->animId == ANIM_FUCKU && ped->GetWeapon()->m_eWeaponType == WEAPONTYPE_UNARMED) ped->RemoveWeaponModel(0); } void CPed::MoveHeadToLook(void) { CVector lookPos; if (m_lookTimer && CTimer::GetTimeInMilliseconds() > m_lookTimer) { ClearLookFlag(); } else if (m_nPedState == PED_DRIVING) { m_pedIK.m_flags |= CPedIK::LOOKAROUND_HEAD_ONLY; } if (m_pLookTarget) { if (!bShakeFist && GetWeapon()->m_eWeaponType == WEAPONTYPE_UNARMED) { CAnimBlendAssociation *fuckUAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FUCKU); if (fuckUAssoc) { float animTime = fuckUAssoc->currentTime; if (animTime > 4.0f / 30.0f && animTime - fuckUAssoc->timeStep > 4.0f / 30.0f) { bool lookingToCop = false; if (m_pLookTarget->GetModelIndex() == MI_POLICE || m_pLookTarget->IsPed() && ((CPed*)m_pLookTarget)->m_nPedType == PEDTYPE_COP) { lookingToCop = true; } if (IsPlayer() && (m_pedStats->m_temper >= 52 || lookingToCop)) { AddWeaponModel(MI_FINGERS); ((CPlayerPed*)this)->AnnoyPlayerPed(true); } else if ((CGeneral::GetRandomNumber() & 3) == 0) { AddWeaponModel(MI_FINGERS); } } } } if (m_pLookTarget->IsPed()) { ((CPed*)m_pLookTarget)->m_pedIK.GetComponentPosition((RwV3d*) &lookPos, PED_MID); } else { lookPos = m_pLookTarget->GetPosition(); } if (!m_pedIK.LookAtPosition(lookPos)) { if (!bKeepTryingToLook) { ClearLookFlag(); } return; } if (!bShakeFist || bIsAimingGun || bIsRestoringGun) return; if (m_lookTimer - CTimer::GetTimeInMilliseconds() >= 1000) return; bool notRocketLauncher = false; bool notTwoHanded = false; AnimationId animToPlay = NUM_ANIMS; if (!GetWeapon()->IsType2Handed()) notTwoHanded = true; if (notTwoHanded && GetWeapon()->m_eWeaponType != WEAPONTYPE_ROCKETLAUNCHER) notRocketLauncher = true; if (IsPlayer() && notRocketLauncher) { if (m_pLookTarget->IsPed()) { if (m_pedStats->m_temper >= 49 && ((CPed*)m_pLookTarget)->m_nPedType != PEDTYPE_COP) { // FIX: Unreachable and meaningless condition #ifndef FIX_BUGS if (m_pedStats->m_temper < 47) #endif animToPlay = ANIM_FIGHT_PPUNCH; } else { animToPlay = ANIM_FUCKU; } } else if (m_pedStats->m_temper > 49 || m_pLookTarget->GetModelIndex() == MI_POLICE) { animToPlay = ANIM_FUCKU; } } else if (notRocketLauncher && (CGeneral::GetRandomNumber() & 1)) { animToPlay = ANIM_FUCKU; } if (animToPlay != NUM_ANIMS) { CAnimBlendAssociation *newAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, animToPlay, 4.0f); if (newAssoc) { newAssoc->flags |= ASSOC_FADEOUTWHENDONE; newAssoc->flags |= ASSOC_DELETEFADEDOUT; if (newAssoc->animId == ANIM_FUCKU) newAssoc->SetDeleteCallback(FinishFuckUCB, this); } } bShakeFist = false; return; } else if (999999.0f == m_fLookDirection) { ClearLookFlag(); } else if (!m_pedIK.LookInDirection(m_fLookDirection, 0.0f)) { if (!bKeepTryingToLook) ClearLookFlag(); } } void CPed::RestoreHeadPosition(void) { if (m_pedIK.RestoreLookAt()) { bIsRestoringLook = false; } } void CPed::SetAimFlag(float angle) { bIsAimingGun = true; bIsRestoringGun = false; m_fLookDirection = angle; m_lookTimer = 0; m_pLookTarget = nil; m_pSeekTarget = nil; if (CWeaponInfo::GetWeaponInfo(GetWeapon()->m_eWeaponType)->m_bCanAimWithArm) m_pedIK.m_flags |= CPedIK::AIMS_WITH_ARM; else m_pedIK.m_flags &= ~CPedIK::AIMS_WITH_ARM; } void CPed::SetAimFlag(CEntity *to) { bIsAimingGun = true; bIsRestoringGun = false; m_pLookTarget = to; m_pLookTarget->RegisterReference((CEntity **) &m_pLookTarget); m_pSeekTarget = to; m_pSeekTarget->RegisterReference((CEntity **) &m_pSeekTarget); m_lookTimer = 0; } void CPed::ClearAimFlag(void) { if (bIsAimingGun) { bIsAimingGun = false; bIsRestoringGun = true; m_pedIK.m_flags &= ~CPedIK::AIMS_WITH_ARM; #if defined VC_PED_PORTS || defined FIX_BUGS m_lookTimer = 0; #endif } if (IsPlayer()) ((CPlayerPed*)this)->m_fFPSMoveHeading = 0.0f; } void CPed::AimGun(void) { CVector vector; if (m_pSeekTarget) { if (m_pSeekTarget->IsPed()) { ((CPed*)m_pSeekTarget)->m_pedIK.GetComponentPosition(vector, PED_MID); } else { vector = m_pSeekTarget->GetPosition(); } Say(SOUND_PED_ATTACK); bCanPointGunAtTarget = m_pedIK.PointGunAtPosition(vector); if (m_pLookTarget != m_pSeekTarget) { SetLookFlag(m_pSeekTarget, true); } } else { if (IsPlayer()) { bCanPointGunAtTarget = m_pedIK.PointGunInDirection(m_fLookDirection, ((CPlayerPed*)this)->m_fFPSMoveHeading); } else { bCanPointGunAtTarget = m_pedIK.PointGunInDirection(m_fLookDirection, 0.0f); } } } void CPed::RestoreGunPosition(void) { if (bIsLooking) { m_pedIK.m_flags &= ~CPedIK::LOOKAROUND_HEAD_ONLY; bIsRestoringGun = false; } else if (m_pedIK.RestoreGunPosn()) { bIsRestoringGun = false; } else { if (IsPlayer()) ((CPlayerPed*)this)->m_fFPSMoveHeading = 0.0f; } } void CPed::ScanForInterestingStuff(void) { if (!IsPedInControl()) return; if (m_objective != OBJECTIVE_NONE) return; if (CharCreatedBy == MISSION_CHAR) return; LookForSexyPeds(); LookForSexyCars(); if (LookForInterestingNodes()) return; if (m_nPedType == PEDTYPE_CRIMINAL && m_hitRecoverTimer < CTimer::GetTimeInMilliseconds()) { if (CGeneral::GetRandomNumber() % 100 < 10) { int mostExpensiveVehAround = -1; int bestMonetaryValue = 0; CVector pos = GetPosition(); int16 lastVehicle; CEntity *vehicles[8]; CWorld::FindObjectsInRange(pos, 10.0f, true, &lastVehicle, 6, vehicles, false, true, false, false, false); for (int i = 0; i < lastVehicle; i++) { CVehicle* veh = (CVehicle*)vehicles[i]; if (veh->VehicleCreatedBy != MISSION_VEHICLE) { if (veh->m_vecMoveSpeed.Magnitude() <= 0.1f && veh->IsVehicleNormal() && veh->IsCar() && bestMonetaryValue < veh->pHandling->nMonetaryValue) { mostExpensiveVehAround = i; bestMonetaryValue = veh->pHandling->nMonetaryValue; } } } if (bestMonetaryValue > 2000 && mostExpensiveVehAround != -1 && vehicles[mostExpensiveVehAround]) { SetObjective(OBJECTIVE_ENTER_CAR_AS_DRIVER, vehicles[mostExpensiveVehAround]); m_hitRecoverTimer = CTimer::GetTimeInMilliseconds() + 5000; return; } m_hitRecoverTimer = CTimer::GetTimeInMilliseconds() + 5000; } else if (m_objective != OBJECTIVE_MUG_CHAR && !(CGeneral::GetRandomNumber() & 7)) { CPed *charToMug = nil; for (int i = 0; i < m_numNearPeds; ++i) { CPed *nearPed = m_nearPeds[i]; if ((nearPed->GetPosition() - GetPosition()).MagnitudeSqr() > sq(7.0f)) break; if ((nearPed->m_nPedType == PEDTYPE_CIVFEMALE || nearPed->m_nPedType == PEDTYPE_CIVMALE || nearPed->m_nPedType == PEDTYPE_CRIMINAL || nearPed->m_nPedType == PEDTYPE_UNUSED1 || nearPed->m_nPedType == PEDTYPE_PROSTITUTE) && nearPed->CharCreatedBy != MISSION_CHAR && nearPed->IsPedShootable() && nearPed->m_objective != OBJECTIVE_MUG_CHAR) { charToMug = nearPed; break; } } if (charToMug) SetObjective(OBJECTIVE_MUG_CHAR, charToMug); m_hitRecoverTimer = CTimer::GetTimeInMilliseconds() + 5000; } } if (m_nPedState == PED_WANDER_PATH) { #ifndef VC_PED_PORTS if (CTimer::GetTimeInMilliseconds() > m_standardTimer) { // += 2 is weird for (int i = 0; i < m_numNearPeds; i += 2) { if (m_nearPeds[i]->m_nPedState == PED_WANDER_PATH && WillChat(m_nearPeds[i])) { if (CGeneral::GetRandomNumberInRange(0, 100) >= 100) m_standardTimer = CTimer::GetTimeInMilliseconds() + 30000; else { if ((GetPosition() - m_nearPeds[i]->GetPosition()).Magnitude() >= 1.8f) { m_standardTimer = CTimer::GetTimeInMilliseconds() + 30000; } else if (CanSeeEntity(m_nearPeds[i])) { int time = CGeneral::GetRandomNumber() % 4000 + 10000; SetChat(m_nearPeds[i], time); m_nearPeds[i]->SetChat(this, time); return; } } } } } #else if (CGeneral::GetRandomNumberInRange(0.0f, 1.0f) < 0.5f) { if (CTimer::GetTimeInMilliseconds() > m_standardTimer) { for (int i = 0; i < m_numNearPeds; i ++) { if (m_nearPeds[i] && m_nearPeds[i]->m_nPedState == PED_WANDER_PATH) { if ((GetPosition() - m_nearPeds[i]->GetPosition()).Magnitude() < 1.8f && CanSeeEntity(m_nearPeds[i]) && m_nearPeds[i]->CanSeeEntity(this) && WillChat(m_nearPeds[i])) { int time = CGeneral::GetRandomNumber() % 4000 + 10000; SetChat(m_nearPeds[i], time); m_nearPeds[i]->SetChat(this, time); return; } } } } } else { m_standardTimer = CTimer::GetTimeInMilliseconds() + 200; } #endif } // Parts below aren't there in VC, they're in somewhere else. if (!CGame::noProstitutes && m_nPedType == PEDTYPE_PROSTITUTE && CharCreatedBy != MISSION_CHAR && m_objectiveTimer < CTimer::GetTimeInMilliseconds() && !CTheScripts::IsPlayerOnAMission()) { CVector pos = GetPosition(); int16 lastVehicle; CEntity* vehicles[8]; CWorld::FindObjectsInRange(pos, CHECK_NEARBY_THINGS_MAX_DIST, true, &lastVehicle, 6, vehicles, false, true, false, false, false); for (int i = 0; i < lastVehicle; i++) { CVehicle* veh = (CVehicle*)vehicles[i]; if (veh->IsVehicleNormal()) { if (veh->IsCar()) { if ((GetPosition() - veh->GetPosition()).Magnitude() < 5.0f && veh->IsRoomForPedToLeaveCar(CAR_DOOR_LF, nil)) { SetObjective(OBJECTIVE_SOLICIT_VEHICLE, veh); Say(SOUND_PED_SOLICIT); return; } } } } } if (m_nPedType == PEDTYPE_CIVMALE || m_nPedType == PEDTYPE_CIVFEMALE) { CVector pos = GetPosition(); int16 lastVehicle; CEntity* vehicles[8]; CWorld::FindObjectsInRange(pos, CHECK_NEARBY_THINGS_MAX_DIST, true, &lastVehicle, 6, vehicles, false, true, false, false, false); for (int i = 0; i < lastVehicle; i++) { CVehicle* veh = (CVehicle*)vehicles[i]; if (veh->GetModelIndex() == MI_MRWHOOP) { if (veh->GetStatus() != STATUS_ABANDONED && veh->GetStatus() != STATUS_WRECKED) { if ((GetPosition() - veh->GetPosition()).Magnitude() < 5.0f) { SetObjective(OBJECTIVE_BUY_ICE_CREAM, veh); return; } } } } } } bool CPed::WillChat(CPed *stranger) { if (m_pNextPathNode && m_pLastPathNode) { if (m_pNextPathNode != m_pLastPathNode && ThePaths.TestCrossesRoad(m_pNextPathNode, m_pLastPathNode)) { return false; } } if (m_nSurfaceTouched == SURFACE_TARMAC) return false; if (stranger == this) return false; if (m_nPedType == stranger->m_nPedType) return true; if (m_nPedType == PEDTYPE_CRIMINAL) return false; if ((IsGangMember() || stranger->IsGangMember()) && m_nPedType != stranger->m_nPedType) return false; return true; } void CPed::CalculateNewVelocity(void) { if (IsPedInControl()) { float headAmount = DEGTORAD(m_headingRate) * CTimer::GetTimeStep(); m_fRotationCur = CGeneral::LimitRadianAngle(m_fRotationCur); float limitedRotDest = CGeneral::LimitRadianAngle(m_fRotationDest); if (m_fRotationCur - PI > limitedRotDest) { limitedRotDest += 2 * PI; } else if(PI + m_fRotationCur < limitedRotDest) { limitedRotDest -= 2 * PI; } if (IsPlayer() && m_nPedState == PED_ATTACK) headAmount /= 4.0f; float neededTurn = limitedRotDest - m_fRotationCur; if (neededTurn <= headAmount) { if (neededTurn > (-headAmount)) m_fRotationCur += neededTurn; else m_fRotationCur -= headAmount; } else { m_fRotationCur += headAmount; } } CVector2D forward(Sin(m_fRotationCur), Cos(m_fRotationCur)); m_moved.x = CrossProduct2D(m_vecAnimMoveDelta, forward); // (m_vecAnimMoveDelta.x * Cos(m_fRotationCur)) + -Sin(m_fRotationCur) * m_vecAnimMoveDelta.y; m_moved.y = DotProduct2D(m_vecAnimMoveDelta, forward); // m_vecAnimMoveDelta.y* Cos(m_fRotationCur) + (m_vecAnimMoveDelta.x * Sin(m_fRotationCur)); if (CTimer::GetTimeStep() >= 0.01f) { m_moved = m_moved * (1 / CTimer::GetTimeStep()); } else { m_moved = m_moved * (1 / 100.0f); } if ((!TheCamera.Cams[TheCamera.ActiveCam].GetWeaponFirstPersonOn() && !TheCamera.Cams[0].Using3rdPersonMouseCam()) || FindPlayerPed() != this || !CanStrafeOrMouseControl()) return; float walkAngle = WorkOutHeadingForMovingFirstPerson(m_fRotationCur); float pedSpeed = m_moved.Magnitude(); float localWalkAngle = CGeneral::LimitRadianAngle(walkAngle - m_fRotationCur); if (localWalkAngle < -0.5f * PI) { localWalkAngle += PI; } else if (localWalkAngle > 0.5f * PI) { localWalkAngle -= PI; } // Interestingly this part is responsible for diagonal walking. if (localWalkAngle > -DEGTORAD(50.0f) && localWalkAngle < DEGTORAD(50.0f)) { TheCamera.Cams[TheCamera.ActiveCam].m_fPlayerVelocity = pedSpeed; m_moved = CVector2D(-Sin(walkAngle), Cos(walkAngle)) * pedSpeed; } CAnimBlendAssociation *idleAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_STANCE); CAnimBlendAssociation *fightAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FIGHT_IDLE); #ifdef VC_PED_PORTS if ((!idleAssoc || idleAssoc->blendAmount < 0.5f) && !fightAssoc && !bIsDucking) { #else if ((!idleAssoc || idleAssoc->blendAmount < 0.5f) && !fightAssoc) { #endif LimbOrientation newUpperLegs; newUpperLegs.yaw = localWalkAngle; if (newUpperLegs.yaw < -DEGTORAD(100.0f)) { newUpperLegs.yaw += PI; } else if (newUpperLegs.yaw > DEGTORAD(100.0f)) { newUpperLegs.yaw -= PI; } if (newUpperLegs.yaw > -DEGTORAD(50.0f) && newUpperLegs.yaw < DEGTORAD(50.0f)) { #ifdef PED_SKIN if(IsClumpSkinned(GetClump())){ /* // this looks shit newUpperLegs.pitch = 0.0f; RwV3d axis = { -1.0f, 0.0f, 0.0f }; RtQuatRotate(&m_pFrames[PED_UPPERLEGL]->hanimFrame->q, &axis, RADTODEG(newUpperLegs.yaw), rwCOMBINEPRECONCAT); RtQuatRotate(&m_pFrames[PED_UPPERLEGR]->hanimFrame->q, &axis, RADTODEG(newUpperLegs.yaw), rwCOMBINEPRECONCAT); */ newUpperLegs.pitch = 0.1f; RwV3d Xaxis = { 1.0f, 0.0f, 0.0f }; RwV3d Zaxis = { 0.0f, 0.0f, 1.0f }; RtQuatRotate(&m_pFrames[PED_UPPERLEGL]->hanimFrame->q, &Zaxis, RADTODEG(newUpperLegs.pitch), rwCOMBINEPOSTCONCAT); RtQuatRotate(&m_pFrames[PED_UPPERLEGL]->hanimFrame->q, &Xaxis, RADTODEG(newUpperLegs.yaw), rwCOMBINEPOSTCONCAT); RtQuatRotate(&m_pFrames[PED_UPPERLEGR]->hanimFrame->q, &Zaxis, RADTODEG(newUpperLegs.pitch), rwCOMBINEPOSTCONCAT); RtQuatRotate(&m_pFrames[PED_UPPERLEGR]->hanimFrame->q, &Xaxis, RADTODEG(newUpperLegs.yaw), rwCOMBINEPOSTCONCAT); bDontAcceptIKLookAts = true; }else #endif { newUpperLegs.pitch = 0.0f; m_pedIK.RotateTorso(m_pFrames[PED_UPPERLEGL], &newUpperLegs, false); m_pedIK.RotateTorso(m_pFrames[PED_UPPERLEGR], &newUpperLegs, false); } } } } float CPed::WorkOutHeadingForMovingFirstPerson(float offset) { if (!IsPlayer()) return 0.0f; CPad *pad0 = CPad::GetPad(0); float leftRight = pad0->GetPedWalkLeftRight(); float upDown = pad0->GetPedWalkUpDown(); float &angle = ((CPlayerPed*)this)->m_fWalkAngle; if (upDown != 0.0f) { angle = CGeneral::GetRadianAngleBetweenPoints(0.0f, 0.0f, -leftRight, upDown); } else { if (leftRight < 0.0f) angle = 0.5f * PI; else if (leftRight > 0.0f) angle = -0.5f * PI; } return CGeneral::LimitRadianAngle(offset + angle); } void CPed::UpdatePosition(void) { if (CReplay::IsPlayingBack() || !bIsStanding) return; CVector2D velocityChange; SetHeading(m_fRotationCur); if (m_pCurrentPhysSurface) { CVector2D velocityOfSurface; if (!IsPlayer() && m_pCurrentPhysSurface->IsVehicle() && ((CVehicle*)m_pCurrentPhysSurface)->IsBoat()) { // It seems R* didn't like m_vecOffsetFromPhysSurface for boats CVector offsetToSurface = GetPosition() - m_pCurrentPhysSurface->GetPosition(); offsetToSurface.z -= FEET_OFFSET; CVector surfaceMoveVelocity = m_pCurrentPhysSurface->m_vecMoveSpeed; CVector surfaceTurnVelocity = CrossProduct(m_pCurrentPhysSurface->m_vecTurnSpeed, offsetToSurface); // Also we use that weird formula instead of friction if it's boat float slideMult = -m_pCurrentPhysSurface->m_vecTurnSpeed.MagnitudeSqr(); velocityOfSurface = slideMult * offsetToSurface * CTimer::GetTimeStep() + (surfaceTurnVelocity + surfaceMoveVelocity); m_vecMoveSpeed.z = slideMult * offsetToSurface.z * CTimer::GetTimeStep() + (surfaceTurnVelocity.z + surfaceMoveVelocity.z); } else { velocityOfSurface = m_pCurrentPhysSurface->GetSpeed(m_vecOffsetFromPhysSurface); } // Reminder: m_moved is displacement from walking/running. velocityChange = m_moved + velocityOfSurface - m_vecMoveSpeed; m_fRotationCur += m_pCurrentPhysSurface->m_vecTurnSpeed.z * CTimer::GetTimeStep(); m_fRotationDest += m_pCurrentPhysSurface->m_vecTurnSpeed.z * CTimer::GetTimeStep(); } else if (m_nSurfaceTouched == SURFACE_STEEP_CLIFF && (m_vecDamageNormal.x != 0.0f || m_vecDamageNormal.y != 0.0f)) { // Ped got damaged by steep slope m_vecMoveSpeed = CVector(0.0f, 0.0f, -0.001f); // some kind of CVector2D reactionForce = m_vecDamageNormal; reactionForce.Normalise(); velocityChange = 0.02f * reactionForce + m_moved; float reactionAndVelocityDotProd = DotProduct2D(reactionForce, velocityChange); // they're in same direction if (reactionAndVelocityDotProd < 0.0f) { velocityChange -= reactionAndVelocityDotProd * reactionForce; } } else { velocityChange = m_moved - m_vecMoveSpeed; } // Take time step into account if (m_pCurrentPhysSurface) { float speedChange = velocityChange.Magnitude(); float changeMult = speedChange; if (m_nPedState == PED_DIE && m_pCurrentPhysSurface->IsVehicle()) { changeMult = 0.002f * CTimer::GetTimeStep(); } else if (!(m_pCurrentPhysSurface->IsVehicle() && ((CVehicle*)m_pCurrentPhysSurface)->IsBoat())) { changeMult = 0.01f * CTimer::GetTimeStep(); } if (speedChange > changeMult) { velocityChange = velocityChange * (changeMult / speedChange); } } m_vecMoveSpeed.x += velocityChange.x; m_vecMoveSpeed.y += velocityChange.y; } void CPed::CalculateNewOrientation(void) { if (CReplay::IsPlayingBack() || !IsPedInControl()) return; SetHeading(m_fRotationCur); } void CPed::ClearAll(void) { if (!IsPedInControl() && m_nPedState != PED_DEAD) return; m_nPedState = PED_NONE; m_nMoveState = PEDMOVE_NONE; m_pSeekTarget = nil; m_vecSeekPos = CVector(0.0f, 0.0f, 0.0f); m_fleeFromPosX = 0.0f; m_fleeFromPosY = 0.0f; m_fleeFrom = nil; m_fleeTimer = 0; bUsesCollision = true; #ifdef VC_PED_PORTS ClearPointGunAt(); #else ClearAimFlag(); ClearLookFlag(); #endif bIsPointingGunAt = false; bRenderPedInCar = true; bKnockedUpIntoAir = false; m_pCollidingEntity = nil; } void CPed::ProcessBuoyancy(void) { static uint32 nGenerateRaindrops = 0; static uint32 nGenerateWaterCircles = 0; CRGBA color(((0.5f * CTimeCycle::GetDirectionalRed() + CTimeCycle::GetAmbientRed()) * 127.5f), ((0.5f * CTimeCycle::GetDirectionalBlue() + CTimeCycle::GetAmbientBlue()) * 127.5f), ((0.5f * CTimeCycle::GetDirectionalGreen() + CTimeCycle::GetAmbientGreen()) * 127.5f), (CGeneral::GetRandomNumber() % 256 * 48.0f) + 48); if (bInVehicle) return; CVector buoyancyPoint; CVector buoyancyImpulse; #ifndef VC_PED_PORTS float buoyancyLevel = (m_nPedState == PED_DEAD ? 1.5f : 1.3f); #else float buoyancyLevel = (m_nPedState == PED_DEAD ? 1.8f : 1.1f); #endif if (mod_Buoyancy.ProcessBuoyancy(this, GRAVITY * m_fMass * buoyancyLevel, &buoyancyPoint, &buoyancyImpulse)) { bTouchingWater = true; CEntity *entity; CColPoint point; if (CWorld::ProcessVerticalLine(GetPosition(), GetPosition().z - 3.0f, point, entity, false, true, false, false, false, false, nil) && entity->IsVehicle() && ((CVehicle*)entity)->IsBoat()) { bIsInWater = false; return; } bIsInWater = true; ApplyMoveForce(buoyancyImpulse); if (!DyingOrDead()) { if (bTryingToReachDryLand) { if (buoyancyImpulse.z / m_fMass > GRAVITY * 0.4f * CTimer::GetTimeStep()) { bTryingToReachDryLand = false; CVector pos = GetPosition(); if (PlacePedOnDryLand()) { if (m_fHealth > 20.0f) InflictDamage(nil, WEAPONTYPE_DROWNING, 15.0f, PEDPIECE_TORSO, false); if (bIsInTheAir) { RpAnimBlendClumpSetBlendDeltas(GetClump(), ASSOC_PARTIAL, -1000.0f); bIsInTheAir = false; } pos.z = pos.z - 0.8f; #ifdef PC_PARTICLE CParticleObject::AddObject(POBJECT_PED_WATER_SPLASH, pos, CVector(0.0f, 0.0f, 0.0f), 0.0f, 50, color, true); #else CParticleObject::AddObject(POBJECT_PED_WATER_SPLASH, pos, CVector(0.0f, 0.0f, 0.0f), 0.0f, 50, CRGBA(0, 0, 0, 0), true); #endif m_vecMoveSpeed = CVector(0.0f, 0.0f, 0.0f); m_nPedState = PED_IDLE; return; } } } float speedMult = 0.0f; if (buoyancyImpulse.z / m_fMass > GRAVITY * 0.75f * CTimer::GetTimeStep() || mod_Buoyancy.m_waterlevel > GetPosition().z) { speedMult = pow(0.9f, CTimer::GetTimeStep()); m_vecMoveSpeed.x *= speedMult; m_vecMoveSpeed.y *= speedMult; m_vecMoveSpeed.z *= speedMult; bIsStanding = false; InflictDamage(nil, WEAPONTYPE_DROWNING, 3.0f * CTimer::GetTimeStep(), PEDPIECE_TORSO, 0); } if (buoyancyImpulse.z / m_fMass > GRAVITY * 0.25f * CTimer::GetTimeStep()) { if (speedMult == 0.0f) { speedMult = pow(0.9f, CTimer::GetTimeStep()); } m_vecMoveSpeed.x *= speedMult; m_vecMoveSpeed.y *= speedMult; if (m_vecMoveSpeed.z >= -0.1f) { if (m_vecMoveSpeed.z < -0.04f) m_vecMoveSpeed.z = -0.02f; } else { m_vecMoveSpeed.z = -0.01f; DMAudio.PlayOneShot(m_audioEntityId, SOUND_SPLASH, 0.0f); #ifdef PC_PARTICLE CVector aBitForward = 2.2f * m_vecMoveSpeed + GetPosition(); float level = 0.0f; if (CWaterLevel::GetWaterLevel(aBitForward, &level, false)) aBitForward.z = level; CParticleObject::AddObject(POBJECT_PED_WATER_SPLASH, aBitForward, CVector(0.0f, 0.0f, 0.1f), 0.0f, 200, color, true); nGenerateRaindrops = CTimer::GetTimeInMilliseconds() + 80; nGenerateWaterCircles = CTimer::GetTimeInMilliseconds() + 100; #else CVector aBitForward = 1.6f * m_vecMoveSpeed + GetPosition(); float level = 0.0f; if (CWaterLevel::GetWaterLevel(aBitForward, &level, false)) aBitForward.z = level + 0.5f; CVector vel = m_vecMoveSpeed * 0.1f; vel.z = 0.18f; CParticleObject::AddObject(POBJECT_PED_WATER_SPLASH, aBitForward, vel, 0.0f, 350, CRGBA(0, 0, 0, 0), true); nGenerateRaindrops = CTimer::GetTimeInMilliseconds() + 300; nGenerateWaterCircles = CTimer::GetTimeInMilliseconds() + 60; #endif } } } else return; } else bTouchingWater = false; if (nGenerateWaterCircles && CTimer::GetTimeInMilliseconds() >= nGenerateWaterCircles) { CVector pos = GetPosition(); float level = 0.0f; if (CWaterLevel::GetWaterLevel(pos, &level, false)) pos.z = level; if (pos.z != 0.0f) { nGenerateWaterCircles = 0; for(int i = 0; i < 4; i++) { #ifdef PC_PARTICLE pos.x += CGeneral::GetRandomNumberInRange(-0.75f, 0.75f); pos.y += CGeneral::GetRandomNumberInRange(-0.75f, 0.75f); CParticle::AddParticle(PARTICLE_RAIN_SPLASH_BIGGROW, pos, CVector(0.0f, 0.0f, 0.0f), nil, 0.0f, color, 0, 0, 0, 0); #else pos.x += CGeneral::GetRandomNumberInRange(-2.5f, 2.5f); pos.y += CGeneral::GetRandomNumberInRange(-2.5f, 2.5f); CParticle::AddParticle(PARTICLE_RAIN_SPLASH_BIGGROW, pos+CVector(0.0f, 0.0f, 1.0f), CVector(0.0f, 0.0f, 0.0f)); #endif } } } if (nGenerateRaindrops && CTimer::GetTimeInMilliseconds() >= nGenerateRaindrops) { CVector pos = GetPosition(); float level = 0.0f; if (CWaterLevel::GetWaterLevel(pos, &level, false)) pos.z = level; if (pos.z >= 0.0f) { #ifdef PC_PARTICLE pos.z += 0.25f; #else pos.z += 0.5f; #endif nGenerateRaindrops = 0; #ifdef PC_PARTICLE CParticleObject::AddObject(POBJECT_SPLASHES_AROUND, pos, CVector(0.0f, 0.0f, 0.0f), 4.5f, 1500, CRGBA(0,0,0,0), true); #else CParticleObject::AddObject(POBJECT_SPLASHES_AROUND, pos, CVector(0.0f, 0.0f, 0.0f), 4.5f, 2500, CRGBA(0,0,0,0), true); #endif } } } void CPed::ProcessControl(void) { CColPoint foundCol; CEntity *foundEnt = nil; if (m_nZoneLevel > LEVEL_GENERIC && m_nZoneLevel != CCollision::ms_collisionInMemory) return; int alpha = CVisibilityPlugins::GetClumpAlpha(GetClump()); if (!bFadeOut) { if (alpha < 255) { alpha += 16; if (alpha > 255) alpha = 255; } } else { alpha -= 8; if (alpha < 0) alpha = 0; } CVisibilityPlugins::SetClumpAlpha(GetClump(), alpha); bIsShooting = false; BuildPedLists(); bIsInWater = false; ProcessBuoyancy(); if (m_nPedState != PED_ARRESTED) { if (m_nPedState == PED_DEAD) { DeadPedMakesTyresBloody(); #ifndef VC_PED_PORTS if (CGame::nastyGame) { #else if (CGame::nastyGame && !bIsInWater) { #endif uint32 remainingBloodyFpTime = CTimer::GetTimeInMilliseconds() - m_bloodyFootprintCountOrDeathTime; float timeDependentDist; if (remainingBloodyFpTime >= 2000) { if (remainingBloodyFpTime <= 7000) timeDependentDist = (remainingBloodyFpTime - 2000) / 5000.0f * 0.75f; else timeDependentDist = 0.75f; } else { timeDependentDist = 0.0f; } for (int i = 0; i < m_numNearPeds; ++i) { CPed *nearPed = m_nearPeds[i]; if (!nearPed->DyingOrDead()) { CVector dist = nearPed->GetPosition() - GetPosition(); if (dist.MagnitudeSqr() < sq(timeDependentDist)) { nearPed->m_bloodyFootprintCountOrDeathTime = 200; nearPed->bDoBloodyFootprints = true; if (nearPed->IsPlayer()) { if (!nearPed->bIsLooking && nearPed->m_nPedState != PED_ATTACK) { int16 camMode = TheCamera.Cams[TheCamera.ActiveCam].Mode; if (camMode != CCam::MODE_SNIPER && camMode != CCam::MODE_ROCKETLAUNCHER && camMode != CCam::MODE_M16_1STPERSON && camMode != CCam::MODE_1STPERSON && camMode != CCam::MODE_HELICANNON_1STPERSON && !TheCamera.Cams[TheCamera.ActiveCam].GetWeaponFirstPersonOn()) { nearPed->SetLookFlag(this, true); nearPed->SetLookTimer(500); } } } } } } if (remainingBloodyFpTime > 2000) { CVector bloodPos = GetPosition(); if (remainingBloodyFpTime - 2000 >= 5000) { if (!m_deadBleeding) { CShadows::AddPermanentShadow(SHADOWTYPE_DARK, gpBloodPoolTex, &bloodPos, 0.75f, 0.0f, 0.0f, -0.75f, 255, 255, 0, 0, 4.0f, 40000, 1.0f); m_deadBleeding = true; } } else { CShadows::StoreStaticShadow( (uintptr)this + 17, SHADOWTYPE_DARK, gpBloodPoolTex, &bloodPos, (remainingBloodyFpTime - 2000) / 5000.0f * 0.75f, 0.0f, 0.0f, (remainingBloodyFpTime - 2000) / 5000.0f * -0.75f, 255, 255, 0, 0, 4.0f, 1.0f, 40.0f, false, 0.0f); } } } if (ServiceTalkingWhenDead()) ServiceTalking(); #ifdef VC_PED_PORTS if (bIsInWater) { bIsStanding = false; bWasStanding = false; CPhysical::ProcessControl(); } #endif return; } bWasStanding = false; if (bIsStanding) { if (!CWorld::bForceProcessControl) { if (m_pCurrentPhysSurface && m_pCurrentPhysSurface->bIsInSafePosition) { bWasPostponed = true; return; } } } if (!IsPedInControl() || m_nWaitState != WAITSTATE_FALSE || 0.01f * CTimer::GetTimeStep() <= m_fDistanceTravelled || (m_nStoredMoveState != PEDMOVE_WALK && m_nStoredMoveState != PEDMOVE_RUN && m_nStoredMoveState != PEDMOVE_SPRINT)) m_panicCounter = 0; else if (m_panicCounter < 50) ++m_panicCounter; if (m_fHealth <= 1.0f && m_nPedState <= PED_STATES_NO_AI && !bIsInTheAir && !bIsLanding) SetDie(ANIM_KO_SHOT_FRONT1, 4.0f, 0.0f); bCollidedWithMyVehicle = false; CEntity *collidingEnt = m_pDamageEntity; #ifndef VC_PED_PORTS if (!bUsesCollision || m_fDamageImpulse <= 0.0f || m_nPedState == PED_DIE || !collidingEnt) { #else if (!bUsesCollision || ((!collidingEnt || m_fDamageImpulse <= 0.0f) && (!IsPlayer() || !bIsStuck)) || m_nPedState == PED_DIE) { #endif bHitSomethingLastFrame = false; if (m_nPedStateTimer <= 500 && bIsInTheAir) { if (m_nPedStateTimer) m_nPedStateTimer--; } else if (m_nPedStateTimer < 1001) { m_nPedStateTimer = 0; } } else { if (m_panicCounter == 50 && IsPedInControl()) { SetWaitState(WAITSTATE_STUCK, nil); // Leftover /* if (m_nPedType < PEDTYPE_COP) { } else { } */ #ifndef VC_PED_PORTS } else { #else } else if (collidingEnt) { #endif switch (collidingEnt->GetType()) { case ENTITY_TYPE_BUILDING: case ENTITY_TYPE_OBJECT: { CBaseModelInfo *collidingModel = CModelInfo::GetModelInfo(collidingEnt->GetModelIndex()); CColModel *collidingCol = collidingModel->GetColModel(); if (collidingEnt->IsObject() && ((CObject*)collidingEnt)->m_nSpecialCollisionResponseCases != COLLRESPONSE_FENCEPART || collidingCol->boundingBox.max.x < 3.0f && collidingCol->boundingBox.max.y < 3.0f) { if (!IsPlayer()) { SetDirectionToWalkAroundObject(collidingEnt); break; } } if (IsPlayer()) { bHitSomethingLastFrame = true; break; } float angleToFaceWhenHit = CGeneral::GetRadianAngleBetweenPoints( GetPosition().x, GetPosition().y, m_vecDamageNormal.x + GetPosition().x, m_vecDamageNormal.y + GetPosition().y); float neededTurn = Abs(m_fRotationCur - angleToFaceWhenHit); if (neededTurn > PI) neededTurn = TWOPI - neededTurn; float oldDestRot = CGeneral::LimitRadianAngle(m_fRotationDest); if (m_pedInObjective && (m_objective == OBJECTIVE_GOTO_CHAR_ON_FOOT || m_objective == OBJECTIVE_KILL_CHAR_ON_FOOT)) { if (m_pedInObjective->IsPlayer() && (neededTurn < DEGTORAD(20.0f) || m_panicCounter > 10)) { if (CanPedJumpThis(collidingEnt)) { SetJump(); } else if (m_objective == OBJECTIVE_KILL_CHAR_ON_FOOT) { SetWaitState(WAITSTATE_LOOK_ABOUT, nil); } else { SetWaitState(WAITSTATE_PLAYANIM_TAXI, nil); m_headingRate = 0.0f; SetLookFlag(m_pedInObjective, true); SetLookTimer(3000); Say(SOUND_PED_TAXI_CALL); } } else { m_pLookTarget = m_pedInObjective; m_pLookTarget->RegisterReference((CEntity **) &m_pLookTarget); TurnBody(); } } else { if (m_nPedType != PEDTYPE_COP && neededTurn < DEGTORAD(15.0f) && m_nWaitState == WAITSTATE_FALSE) { if ((m_nStoredMoveState == PEDMOVE_RUN || m_nStoredMoveState == PEDMOVE_SPRINT) && m_vecDamageNormal.z < 0.3f) { CAnimBlendAssociation *runAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_RUN); if (!runAssoc) runAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_SPRINT); if (runAssoc && runAssoc->blendAmount > 0.9f && runAssoc->IsRunning()) { SetWaitState(WAITSTATE_HITWALL, nil); } } } if (m_nPedState == PED_FLEE_POS) { CVector2D fleePos = collidingEnt->GetPosition(); uint32 oldFleeTimer = m_fleeTimer; SetFlee(fleePos, 5000); if (oldFleeTimer != m_fleeTimer) m_nPedStateTimer = CTimer::GetTimeInMilliseconds() + 500; } else { if (m_nPedState == PED_FLEE_ENTITY && (neededTurn < DEGTORAD(25.0f) || m_panicCounter > 10)) { m_collidingThingTimer = CTimer::GetTimeInMilliseconds() + 2500; m_collidingEntityWhileFleeing = collidingEnt; m_collidingEntityWhileFleeing->RegisterReference((CEntity **) &m_collidingEntityWhileFleeing); uint8 currentDir = Floor((PI + m_fRotationCur) / DEGTORAD(45.0f)); uint8 nextDir; ThePaths.FindNextNodeWandering(PATH_PED, GetPosition(), &m_pLastPathNode, &m_pNextPathNode, currentDir, &nextDir); } else { if (neededTurn < DEGTORAD(60.0f)) { CVector posToHead = m_vecDamageNormal * 4.0f; posToHead.z = 0.0f; posToHead += GetPosition(); int closestNodeId = ThePaths.FindNodeClosestToCoors(posToHead, PATH_PED, 999999.9f, false, false); float angleToFace; if (m_objective != OBJECTIVE_KILL_CHAR_ON_FOOT && m_objective != OBJECTIVE_KILL_CHAR_ANY_MEANS) { if (m_nPedState != PED_SEEK_POS && m_nPedState != PED_SEEK_CAR) { if (m_nPedState == PED_WANDER_PATH) { m_pNextPathNode = &ThePaths.m_pathNodes[closestNodeId]; angleToFace = CGeneral::GetRadianAngleBetweenPoints( m_pNextPathNode->GetX(), m_pNextPathNode->GetY(), GetPosition().x, GetPosition().y); } else { if (ThePaths.m_pathNodes[closestNodeId].GetX() == 0.0f || ThePaths.m_pathNodes[closestNodeId].GetY() == 0.0f) { posToHead = (3.0f * m_vecDamageNormal) + GetPosition(); posToHead.x += (CGeneral::GetRandomNumber() % 512) / 250.0f - 1.0f; posToHead.y += (CGeneral::GetRandomNumber() % 512) / 250.0f - 1.0f; } else { posToHead.x = ThePaths.m_pathNodes[closestNodeId].GetX(); posToHead.y = ThePaths.m_pathNodes[closestNodeId].GetY(); } angleToFace = CGeneral::GetRadianAngleBetweenPoints( posToHead.x, posToHead.y, GetPosition().x, GetPosition().y); if (m_nPedState != PED_FOLLOW_PATH) m_nPedStateTimer = CTimer::GetTimeInMilliseconds() + 500; } } else { angleToFace = CGeneral::GetRadianAngleBetweenPoints( ThePaths.m_pathNodes[closestNodeId].GetX(), ThePaths.m_pathNodes[closestNodeId].GetY(), GetPosition().x, GetPosition().y); CVector2D distToNode = ThePaths.m_pathNodes[closestNodeId].GetPosition() - GetPosition(); CVector2D distToSeekPos = m_vecSeekPos - GetPosition(); if (DotProduct2D(distToNode, distToSeekPos) < 0.0f) { m_fRotationCur = m_fRotationDest; break; } } } else { float angleToFaceAwayDamage = CGeneral::GetRadianAngleBetweenPoints( m_vecDamageNormal.x, m_vecDamageNormal.y, 0.0f, 0.0f); if (angleToFaceAwayDamage < m_fRotationCur) angleToFaceAwayDamage += TWOPI; float neededTurn = angleToFaceAwayDamage - m_fRotationCur; if (neededTurn <= PI) { angleToFace = 0.5f * neededTurn + m_fRotationCur; m_fRotationCur += DEGTORAD(m_pedStats->m_headingChangeRate) * 2.0f; } else { angleToFace = m_fRotationCur - (TWOPI - neededTurn) * 0.5f; m_fRotationCur -= DEGTORAD(m_pedStats->m_headingChangeRate) * 2.0f; } m_nPedStateTimer = CTimer::GetTimeInMilliseconds() + 200; if (m_nPedType == PEDTYPE_COP) { if (m_pedInObjective) { float angleToLookCriminal = CGeneral::GetRadianAngleBetweenPoints( m_pedInObjective->GetPosition().x, m_pedInObjective->GetPosition().y, GetPosition().x, GetPosition().y); angleToLookCriminal = CGeneral::LimitRadianAngle(angleToLookCriminal); angleToFace = CGeneral::LimitRadianAngle(angleToFace); if (angleToLookCriminal < angleToFace) angleToLookCriminal += TWOPI; float neededTurnToCriminal = angleToLookCriminal - angleToFace; if (neededTurnToCriminal > DEGTORAD(150.0f) && neededTurnToCriminal < DEGTORAD(210.0f)) { ((CCopPed*)this)->m_bStopAndShootDisabledZone = true; } } } } m_fRotationDest = CGeneral::LimitRadianAngle(angleToFace); if (m_fRotationCur - PI > m_fRotationDest) { m_fRotationDest += TWOPI; } else if (PI + m_fRotationCur < m_fRotationDest) { m_fRotationDest -= TWOPI; } if (oldDestRot == m_fRotationDest && CTimer::GetTimeInMilliseconds() > m_nPedStateTimer) { m_nPedStateTimer = CTimer::GetTimeInMilliseconds() + 200; m_fRotationDest += HALFPI; } } } } } if (m_nPedState != PED_WANDER_PATH && m_nPedState != PED_FLEE_ENTITY) m_pNextPathNode = nil; bHitSomethingLastFrame = true; break; } case ENTITY_TYPE_VEHICLE: { CVehicle* collidingVeh = ((CVehicle*)collidingEnt); float collidingVehSpeedSqr = collidingVeh->m_vecMoveSpeed.MagnitudeSqr(); if (collidingVeh == m_pMyVehicle) bCollidedWithMyVehicle = true; #ifdef VC_PED_PORTS float oldHealth = m_fHealth; bool playerSufferSound = false; if (collidingVehSpeedSqr <= 1.0f / 400.0f) { if (IsPedInControl() && (!IsPlayer() || m_objective == OBJECTIVE_GOTO_AREA_ON_FOOT || m_objective == OBJECTIVE_RUN_TO_AREA || m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER)) { if (collidingVeh != m_pCurrentPhysSurface || IsPlayer()) { if (!bVehEnterDoorIsBlocked) { if (collidingVeh->GetStatus() != STATUS_PLAYER || CharCreatedBy == MISSION_CHAR) { // VC calls SetDirectionToWalkAroundVehicle instead if ped is in PED_SEEK_CAR. SetDirectionToWalkAroundObject(collidingVeh); CWorld::Players[CWorld::PlayerInFocus].m_nLastBumpPlayerCarTimer = m_nPedStateTimer; } else { if (CTimer::GetTimeInMilliseconds() >= CWorld::Players[CWorld::PlayerInFocus].m_nLastBumpPlayerCarTimer || m_nPedStateTimer >= CTimer::GetTimeInMilliseconds()) { // VC calls SetDirectionToWalkAroundVehicle instead if ped is in PED_SEEK_CAR. SetDirectionToWalkAroundObject(collidingVeh); CWorld::Players[CWorld::PlayerInFocus].m_nLastBumpPlayerCarTimer = m_nPedStateTimer; } else if (m_fleeFrom != collidingVeh) { SetFlee(collidingVeh, 4000); bUsePedNodeSeek = false; SetMoveState(PEDMOVE_WALK); } } } } else { float angleLeftToCompleteTurn = Abs(m_fRotationCur - m_fRotationDest); if (angleLeftToCompleteTurn < 0.01f && CanPedJumpThis(collidingVeh)) { SetJump(); } } } else if (IsPlayer() && !bIsInTheAir) { if (IsPedInControl() && ((CPlayerPed*)this)->m_fMoveSpeed == 0.0f && !bIsLooking && CTimer::GetTimeInMilliseconds() > m_lookTimer && collidingVeh->pDriver) { ((CPlayerPed*)this)->AnnoyPlayerPed(false); SetLookFlag(collidingVeh, true); SetLookTimer(1300); eWeaponType weaponType = GetWeapon()->m_eWeaponType; if (weaponType == WEAPONTYPE_UNARMED || weaponType == WEAPONTYPE_BASEBALLBAT || weaponType == WEAPONTYPE_COLT45 || weaponType == WEAPONTYPE_UZI) { bShakeFist = true; } } else { SetLookFlag(collidingVeh, true); SetLookTimer(500); } } } else { float adjustedImpulse = m_fDamageImpulse; if (IsPlayer()) { if (bIsStanding) { float forwardVecAndDamageDirDotProd = DotProduct(m_vecAnimMoveDelta.y * GetForward(), m_vecDamageNormal); if (forwardVecAndDamageDirDotProd < 0.0f) { adjustedImpulse = forwardVecAndDamageDirDotProd * m_fMass + m_fDamageImpulse; if (adjustedImpulse < 0.0f) adjustedImpulse = 0.0f; } } } if (m_fMass / 20.0f < adjustedImpulse) DMAudio.PlayOneShot(collidingVeh->m_audioEntityId, SOUND_CAR_PED_COLLISION, adjustedImpulse); if (IsPlayer()) { if (adjustedImpulse > 20.0f) adjustedImpulse = 20.0f; if (adjustedImpulse > 5.0f) { if (adjustedImpulse <= 13.0f) playerSufferSound = true; else Say(SOUND_PED_DAMAGE); } CColModel* collidingCol = CModelInfo::GetModelInfo(collidingVeh->m_modelIndex)->GetColModel(); CVector colMinVec = collidingCol->boundingBox.min; CVector colMaxVec = collidingCol->boundingBox.max; CVector vehColCenterDist = collidingVeh->GetMatrix() * ((colMinVec + colMaxVec) * 0.5f) - GetPosition(); // TLVC = To look vehicle center float angleToVehFront = collidingVeh->GetForward().Heading(); float angleDiffFromLookingFrontTLVC = angleToVehFront - vehColCenterDist.Heading(); angleDiffFromLookingFrontTLVC = CGeneral::LimitRadianAngle(angleDiffFromLookingFrontTLVC); // I don't know why do we use that float vehTopRightHeading = Atan2(colMaxVec.x - colMinVec.x, colMaxVec.y - colMinVec.y); CVector vehDist = GetPosition() - collidingVeh->GetPosition(); vehDist.Normalise(); float vehRightVecAndSpeedDotProd; if (Abs(angleDiffFromLookingFrontTLVC) >= vehTopRightHeading && Abs(angleDiffFromLookingFrontTLVC) < PI - vehTopRightHeading) { if (angleDiffFromLookingFrontTLVC <= 0.0f) { vehRightVecAndSpeedDotProd = DotProduct(collidingVeh->GetRight(), collidingVeh->m_vecMoveSpeed); // vehRightVecAndSpeedDotProd < 0.1f = Vehicle being overturned or spinning to it's right? if (collidingVehSpeedSqr > 1.0f / 100.0f && vehRightVecAndSpeedDotProd < 0.1f) { // Car's right faces towards us and isn't coming directly to us if (DotProduct(collidingVeh->GetRight(), GetForward()) < 0.0f && DotProduct(vehDist, collidingVeh->m_vecMoveSpeed) > 0.0f) { SetEvasiveStep(collidingVeh, 1); } } } else { vehRightVecAndSpeedDotProd = DotProduct(-1.0f * collidingVeh->GetRight(), collidingVeh->m_vecMoveSpeed); if (collidingVehSpeedSqr > 1.0f / 100.0f && vehRightVecAndSpeedDotProd < 0.1f) { if (DotProduct(collidingVeh->GetRight(), GetForward()) > 0.0f && DotProduct(vehDist, collidingVeh->m_vecMoveSpeed) > 0.0f) { SetEvasiveStep(collidingVeh, 1); } } } } else { vehRightVecAndSpeedDotProd = DotProduct(vehDist, collidingVeh->m_vecMoveSpeed); } if (vehRightVecAndSpeedDotProd <= 0.1f) { if (m_nPedState != PED_FIGHT) { SetLookFlag(collidingVeh, true); SetLookTimer(700); } } else { bIsStanding = false; CVector2D collidingEntMoveDir = -collidingVeh->m_vecMoveSpeed; int dir = GetLocalDirection(collidingEntMoveDir); SetFall(1000, (AnimationId)(dir + ANIM_KO_SKID_FRONT), false); float damage; if (collidingVeh->m_modelIndex == MI_TRAIN) { damage = 50.0f; } else { damage = 20.0f; } InflictDamage(collidingVeh, WEAPONTYPE_RAMMEDBYCAR, damage, PEDPIECE_TORSO, dir); Say(SOUND_PED_DAMAGE); } } else { KillPedWithCar(collidingVeh, m_fDamageImpulse); } /* VC specific if (m_pCollidingEntity != collidingEnt) bPushedAlongByCar = true; */ } if (m_fHealth < oldHealth && playerSufferSound) Say(SOUND_PED_HIT); #else if (collidingVehSpeedSqr <= 1.0f / 400.0f) { if (!IsPedInControl() || IsPlayer() && m_objective != OBJECTIVE_GOTO_AREA_ON_FOOT && m_objective != OBJECTIVE_ENTER_CAR_AS_DRIVER && m_objective != OBJECTIVE_RUN_TO_AREA) { if (IsPlayer() && !bIsInTheAir) { if (IsPedInControl() && ((CPlayerPed*)this)->m_fMoveSpeed == 0.0f && !bIsLooking && CTimer::GetTimeInMilliseconds() > m_lookTimer && collidingVeh->pDriver) { ((CPlayerPed*)this)->AnnoyPlayerPed(false); SetLookFlag(collidingVeh, true); SetLookTimer(1300); eWeaponType weaponType = GetWeapon()->m_eWeaponType; if (weaponType == WEAPONTYPE_UNARMED || weaponType == WEAPONTYPE_BASEBALLBAT || weaponType == WEAPONTYPE_COLT45 || weaponType == WEAPONTYPE_UZI) { bShakeFist = true; } } else { SetLookFlag(collidingVeh, true); SetLookTimer(500); } } } else if (!bVehEnterDoorIsBlocked) { if (collidingVeh->GetStatus() != STATUS_PLAYER || CharCreatedBy == MISSION_CHAR) { SetDirectionToWalkAroundObject(collidingVeh); } else if (CTimer::GetTimeInMilliseconds() >= CWorld::Players[CWorld::PlayerInFocus].m_nLastBumpPlayerCarTimer || m_nPedStateTimer >= CTimer::GetTimeInMilliseconds()) { SetDirectionToWalkAroundObject(collidingVeh); CWorld::Players[CWorld::PlayerInFocus].m_nLastBumpPlayerCarTimer = m_nPedStateTimer; } else if (m_fleeFrom != collidingVeh) { SetFlee(collidingVeh, 4000); bUsePedNodeSeek = false; SetMoveState(PEDMOVE_WALK); } } } else { DMAudio.PlayOneShot(collidingVeh->m_audioEntityId, SOUND_CAR_PED_COLLISION, m_fDamageImpulse); if (IsPlayer()) { CColModel *collidingCol = CModelInfo::GetModelInfo(collidingVeh->GetModelIndex())->GetColModel(); CVector colMinVec = collidingCol->boundingBox.min; CVector colMaxVec = collidingCol->boundingBox.max; CVector vehColCenterDist = collidingVeh->GetMatrix() * ((colMinVec + colMaxVec) * 0.5f) - GetPosition(); // TLVC = To look vehicle center float angleToVehFront = collidingVeh->GetForward().Heading(); float angleDiffFromLookingFrontTLVC = angleToVehFront - vehColCenterDist.Heading(); angleDiffFromLookingFrontTLVC = CGeneral::LimitRadianAngle(angleDiffFromLookingFrontTLVC); // I don't know why do we use that float vehTopRightHeading = Atan2(colMaxVec.x - colMinVec.x, colMaxVec.y - colMinVec.y); CVector vehDist = GetPosition() - collidingVeh->GetPosition(); vehDist.Normalise(); float vehRightVecAndSpeedDotProd; if (Abs(angleDiffFromLookingFrontTLVC) >= vehTopRightHeading && Abs(angleDiffFromLookingFrontTLVC) < PI - vehTopRightHeading) { if (angleDiffFromLookingFrontTLVC <= 0.0f) { vehRightVecAndSpeedDotProd = DotProduct(collidingVeh->GetRight(), collidingVeh->m_vecMoveSpeed); // vehRightVecAndSpeedDotProd < 0.1f = Vehicle being overturned or spinning to it's right? if (collidingVehSpeedSqr > 1.0f / 100.0f && vehRightVecAndSpeedDotProd < 0.1f) { // Car's right faces towards us and isn't coming directly to us if (DotProduct(collidingVeh->GetRight(), GetForward()) < 0.0f && DotProduct(vehDist, collidingVeh->m_vecMoveSpeed) > 0.0f) { SetEvasiveStep(collidingVeh, 1); } } } else { vehRightVecAndSpeedDotProd = DotProduct(-1.0f * collidingVeh->GetRight(), collidingVeh->m_vecMoveSpeed); if (collidingVehSpeedSqr > 1.0f / 100.0f && vehRightVecAndSpeedDotProd < 0.1f) { if (DotProduct(collidingVeh->GetRight(), GetForward()) > 0.0f && DotProduct(vehDist, collidingVeh->m_vecMoveSpeed) > 0.0f) { SetEvasiveStep(collidingVeh, 1); } } } } else { vehRightVecAndSpeedDotProd = DotProduct(vehDist, collidingVeh->m_vecMoveSpeed); } if (vehRightVecAndSpeedDotProd <= 0.1f) { if (m_nPedState != PED_FIGHT) { SetLookFlag(collidingVeh, true); SetLookTimer(700); } } else { bIsStanding = false; CVector2D collidingEntMoveDir = -collidingVeh->m_vecMoveSpeed; int dir = GetLocalDirection(collidingEntMoveDir); SetFall(1000, (AnimationId)(dir + ANIM_KO_SKID_FRONT), false); CPed *driver = collidingVeh->pDriver; float damage; if (driver && driver->IsPlayer()) { damage = vehRightVecAndSpeedDotProd * 1000.0f; } else if (collidingVeh->GetModelIndex() == MI_TRAIN) { damage = 50.0f; } else { damage = 20.0f; } InflictDamage(collidingVeh, WEAPONTYPE_RAMMEDBYCAR, damage, PEDPIECE_TORSO, dir); Say(SOUND_PED_DAMAGE); } } else { KillPedWithCar(collidingVeh, m_fDamageImpulse); } } #endif break; } case ENTITY_TYPE_PED: { CollideWithPed((CPed*)collidingEnt); if (((CPed*)collidingEnt)->IsPlayer()) { CPlayerPed *player = ((CPlayerPed*)collidingEnt); Say(SOUND_PED_CHAT); if (m_nMoveState > PEDMOVE_STILL && player->IsPedInControl()) { if (player->m_fMoveSpeed < 1.0f) { if (!player->bIsLooking) { if (CTimer::GetTimeInMilliseconds() > player->m_lookTimer) { player->AnnoyPlayerPed(false); player->SetLookFlag(this, true); player->SetLookTimer(1300); eWeaponType weapon = player->GetWeapon()->m_eWeaponType; if (weapon == WEAPONTYPE_UNARMED || weapon == WEAPONTYPE_BASEBALLBAT || weapon == WEAPONTYPE_COLT45 || weapon == WEAPONTYPE_UZI) { player->bShakeFist = true; } } } } } } break; } default: break; } } CVector forceDir; if (!bIsInTheAir && m_nPedState != PED_JUMP #ifdef VC_PED_PORTS && m_fDamageImpulse > 0.0f #endif ) { forceDir = m_vecDamageNormal; forceDir.z = 0.0f; if (!bIsStanding) { forceDir *= 4.0f; } else { forceDir *= 0.5f; } ApplyMoveForce(forceDir); } if ((bIsInTheAir && !DyingOrDead()) #ifdef VC_PED_PORTS || (!bIsStanding && !bWasStanding && m_nPedState == PED_FALL) #endif ) { if (m_nPedStateTimer > 0 && m_nPedStateTimer <= 1000) { forceDir = GetPosition() - m_vecHitLastPos; } else { m_nPedStateTimer = 0; m_vecHitLastPos = GetPosition(); forceDir = CVector(0.0f, 0.0f, 0.0f); } CVector offsetToCheck; m_nPedStateTimer++; float adjustedTs = Max(CTimer::GetTimeStep(), 0.01f); CPad *pad0 = CPad::GetPad(0); if ((m_nPedStateTimer <= 50.0f / (4.0f * adjustedTs) || m_nPedStateTimer * 0.01f <= forceDir.MagnitudeSqr()) && (m_nCollisionRecords <= 1 || m_nPedStateTimer <= 50.0f / (2.0f * adjustedTs) || m_nPedStateTimer * 1.0f / 250.0f <= Abs(forceDir.z))) { if (m_nCollisionRecords == 1 && m_aCollisionRecords[0] != nil && m_aCollisionRecords[0]->IsBuilding() && m_nPedStateTimer > 50.0f / (2.0f * adjustedTs) && m_nPedStateTimer * 1.0f / 250.0f > Abs(forceDir.z)) { offsetToCheck.x = -forceDir.y; #ifdef VC_PED_PORTS offsetToCheck.z = 1.0f; #else offsetToCheck.z = 0.0f; #endif offsetToCheck.y = forceDir.x; offsetToCheck.Normalise(); CVector posToCheck = GetPosition() + offsetToCheck; // These are either obstacle or ground to land, I don't know which one. float obstacleForFlyingZ, obstacleForFlyingOtherDirZ; CColPoint obstacleForFlying, obstacleForFlyingOtherDir; // Check is there any room for being knocked up in reverse direction of force if (CWorld::ProcessVerticalLine(posToCheck, -20.0f, obstacleForFlying, foundEnt, true, false, false, false, false, false, nil)) { obstacleForFlyingZ = obstacleForFlying.point.z; } else { obstacleForFlyingZ = 500.0f; } posToCheck = GetPosition() - offsetToCheck; // Now check for direction of force this time if (CWorld::ProcessVerticalLine(posToCheck, -20.0f, obstacleForFlyingOtherDir, foundEnt, true, false, false, false, false, false, nil)) { obstacleForFlyingOtherDirZ = obstacleForFlyingOtherDir.point.z; } else { obstacleForFlyingOtherDirZ = 501.0f; } #ifdef VC_PED_PORTS uint8 flyDir = 0; float feetZ = GetPosition().z - FEET_OFFSET; if ((obstacleForFlyingZ <= feetZ || obstacleForFlyingOtherDirZ >= 500.0f) && (obstacleForFlyingZ <= feetZ || obstacleForFlyingOtherDirZ <= feetZ)) { if (obstacleForFlyingOtherDirZ > feetZ && obstacleForFlyingZ < 499.0f) flyDir = 2; } else { flyDir = 1; } if (flyDir != 0 && !bSomeVCflag1) { SetPosition((flyDir == 2 ? obstacleForFlyingOtherDir.point : obstacleForFlying.point)); GetMatrix().GetPosition().z += FEET_OFFSET; GetMatrix().UpdateRW(); SetLanding(); bIsStanding = true; } #endif if (obstacleForFlyingZ < obstacleForFlyingOtherDirZ) { offsetToCheck *= -1.0f; } offsetToCheck.z = 1.0f; forceDir = 4.0f * offsetToCheck; forceDir.z = 4.0f; ApplyMoveForce(forceDir); GetMatrix().GetPosition() += 0.25f * offsetToCheck; m_fRotationCur = CGeneral::GetRadianAngleBetweenPoints(offsetToCheck.x, offsetToCheck.y, 0.0f, 0.0f); m_fRotationCur = CGeneral::LimitRadianAngle(m_fRotationCur); m_fRotationDest = m_fRotationCur; SetHeading(m_fRotationCur); if (m_nPedState != PED_FALL && !bIsPedDieAnimPlaying) { SetFall(1000, ANIM_KO_SKID_BACK, true); } bIsInTheAir = false; } else if (m_vecDamageNormal.z > 0.4f) { #ifndef VC_PED_PORTS forceDir = m_vecDamageNormal; forceDir.z = 0.0f; forceDir.Normalise(); ApplyMoveForce(2.0f * forceDir); #else if (m_nPedState == PED_JUMP) { if (m_nWaitTimer <= 2000) { if (m_nWaitTimer < 1000) m_nWaitTimer += CTimer::GetTimeStep() * 0.02f * 1000.0f; } else { m_nWaitTimer = 0; } } forceDir = m_vecDamageNormal; forceDir.z = 0.0f; forceDir.Normalise(); if (m_nPedState != PED_JUMP || m_nWaitTimer >= 300) { ApplyMoveForce(2.0f * forceDir); } else { ApplyMoveForce(-4.0f * forceDir); } #endif } } else if ((CTimer::GetFrameCounter() + m_randomSeed % 256 + 3) & 7) { if (IsPlayer() && m_nPedState != PED_JUMP && pad0->JumpJustDown()) { int16 padWalkX = pad0->GetPedWalkLeftRight(); int16 padWalkY = pad0->GetPedWalkUpDown(); if (Abs(padWalkX) > 0.0f || Abs(padWalkY) > 0.0f) { m_fRotationDest = CGeneral::GetRadianAngleBetweenPoints(0.0f, 0.0f, -padWalkX, padWalkY); m_fRotationDest -= TheCamera.Orientation; m_fRotationDest = CGeneral::LimitRadianAngle(m_fRotationDest); m_fRotationCur = m_fRotationDest; SetHeading(m_fRotationCur); } SetJump(); m_nPedStateTimer = 0; m_vecHitLastPos = GetPosition(); // Why? forceDir is unused after this point. forceDir = CVector(0.0f, 0.0f, 0.0f); } else if (IsPlayer()) { int16 padWalkX = pad0->GetPedWalkLeftRight(); int16 padWalkY = pad0->GetPedWalkUpDown(); if (Abs(padWalkX) > 0.0f || Abs(padWalkY) > 0.0f) { m_fRotationDest = CGeneral::GetRadianAngleBetweenPoints(0.0f, 0.0f, -padWalkX, padWalkY); m_fRotationDest -= TheCamera.Orientation; m_fRotationDest = CGeneral::LimitRadianAngle(m_fRotationDest); m_fRotationCur = m_fRotationDest; SetHeading(m_fRotationCur); } CAnimBlendAssociation *jumpAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_JUMP_GLIDE); if (!jumpAssoc) jumpAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FALL_GLIDE); if (jumpAssoc) { jumpAssoc->blendDelta = -3.0f; jumpAssoc->flags |= ASSOC_DELETEFADEDOUT; } if (m_nPedState == PED_JUMP) m_nPedState = PED_IDLE; } else { CAnimBlendAssociation *jumpAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_JUMP_GLIDE); if (!jumpAssoc) jumpAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FALL_GLIDE); if (jumpAssoc) { jumpAssoc->blendDelta = -3.0f; jumpAssoc->flags |= ASSOC_DELETEFADEDOUT; } } } else { offsetToCheck = GetPosition(); offsetToCheck.z += 0.5f; if (CWorld::ProcessVerticalLine(offsetToCheck, GetPosition().z - FEET_OFFSET, foundCol, foundEnt, true, true, false, true, false, false, nil)) { #ifdef VC_PED_PORTS if (!bSomeVCflag1 || FEET_OFFSET + foundCol.point.z < GetPosition().z) { GetMatrix().GetPosition().z = FEET_OFFSET + foundCol.point.z; GetMatrix().UpdateRW(); if (bSomeVCflag1) bSomeVCflag1 = false; } #else GetMatrix().GetPosition().z = FEET_OFFSET + foundCol.point.z; GetMatrix().UpdateRW(); #endif SetLanding(); bIsStanding = true; } } } else if (m_nPedStateTimer < 1001) { m_nPedStateTimer = 0; } } if (bIsDucking) Duck(); if (bStartWanderPathOnFoot) { if (IsPedInControl()) { ClearAll(); SetWanderPath(m_nPathDir); bStartWanderPathOnFoot = false; } else if (m_nPedState == PED_DRIVING) { bWanderPathAfterExitingCar = true; SetObjective(OBJECTIVE_LEAVE_CAR, m_pMyVehicle); } } if (!bIsStanding && m_vecMoveSpeed.z > 0.25f) { float airResistance = Pow(0.95f, CTimer::GetTimeStep()); m_vecMoveSpeed *= airResistance; } #ifdef VC_PED_PORTS if (IsPlayer() || !bIsStanding || m_vecMoveSpeed.x != 0.0f || m_vecMoveSpeed.y != 0.0f || m_vecMoveSpeed.z != 0.0f || (m_nMoveState != PEDMOVE_NONE && m_nMoveState != PEDMOVE_STILL) || m_vecAnimMoveDelta.x != 0.0f || m_vecAnimMoveDelta.y != 0.0f || m_nPedState == PED_JUMP || bIsInTheAir || m_pCurrentPhysSurface) { CPhysical::ProcessControl(); } else { bHasContacted = false; bIsInSafePosition = false; bWasPostponed = false; bHasHitWall = false; m_nCollisionRecords = 0; bHasCollided = false; m_nDamagePieceType = 0; m_fDamageImpulse = 0.0f; m_pDamageEntity = nil; m_vecTurnFriction = CVector(0.0f, 0.0f, 0.0f); m_vecMoveFriction = CVector(0.0f, 0.0f, 0.0f); } #else CPhysical::ProcessControl(); #endif if (m_nPedState != PED_DIE || bIsPedDieAnimPlaying) { if (m_nPedState != PED_DEAD) { CalculateNewVelocity(); CalculateNewOrientation(); } UpdatePosition(); PlayFootSteps(); if (IsPedInControl() && !bIsStanding && !m_pDamageEntity && CheckIfInTheAir()) { SetInTheAir(); #ifdef VC_PED_PORTS bSomeVCflag1 = false; #endif } #ifdef VC_PED_PORTS if (bSomeVCflag1) { CVector posToCheck = GetPosition(); posToCheck.z += 0.9f; if (!CWorld::TestSphereAgainstWorld(posToCheck, 0.2f, this, true, true, false, true, false, false)) bSomeVCflag1 = false; } #endif ProcessObjective(); if (!bIsAimingGun) { if (bIsRestoringGun) RestoreGunPosition(); } else { AimGun(); } if (bIsLooking) { MoveHeadToLook(); } else if (bIsRestoringLook) { RestoreHeadPosition(); } if (bIsInTheAir) InTheAir(); if (bUpdateAnimHeading) { if (m_nPedState != PED_GETUP && m_nPedState != PED_FALL) { m_fRotationCur -= HALFPI; m_fRotationDest = m_fRotationCur; bUpdateAnimHeading = false; } } if (m_nWaitState != WAITSTATE_FALSE) Wait(); if (m_nPedState != PED_IDLE) { CAnimBlendAssociation *idleAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_ARMED); if(idleAssoc) { idleAssoc->blendDelta = -8.0f; idleAssoc->flags |= ASSOC_DELETEFADEDOUT; } } switch (m_nPedState) { case PED_IDLE: Idle(); break; case PED_LOOK_ENTITY: case PED_LOOK_HEADING: Look(); break; case PED_WANDER_RANGE: WanderRange(); CheckAroundForPossibleCollisions(); break; case PED_WANDER_PATH: WanderPath(); break; case PED_SEEK_POS: case PED_SEEK_ENTITY: case PED_PURSUE: case PED_SNIPER_MODE: case PED_ROCKET_MODE: case PED_DUMMY: case PED_FACE_PHONE: case PED_MAKE_CALL: case PED_MUG: case PED_AI_CONTROL: case PED_FOLLOW_ROUTE: case PED_CPR: case PED_SOLICIT: case PED_BUY_ICECREAM: case PED_STEP_AWAY: case PED_UNKNOWN: case PED_STATES_NO_AI: case PED_JUMP: case PED_STAGGER: case PED_DIVE_AWAY: case PED_STATES_NO_ST: case PED_ARREST_PLAYER: case PED_PASSENGER: case PED_TAXI_PASSENGER: case PED_OPEN_DOOR: case PED_DEAD: case PED_DRAG_FROM_CAR: case PED_EXIT_CAR: case PED_STEAL_CAR: break; case PED_ENTER_CAR: case PED_CARJACK: { #ifdef CANCELLABLE_CAR_ENTER if (!IsPlayer() || !m_pVehicleAnim) break; CPad *pad = CPad::GetPad(0); if (pad->ArePlayerControlsDisabled()) break; int vehAnim = m_pVehicleAnim->animId; static bool cancelJack = false; int16 padWalkX = pad->GetPedWalkLeftRight(); int16 padWalkY = pad->GetPedWalkUpDown(); if (Abs(padWalkX) > 0.0f || Abs(padWalkY) > 0.0f) { if (vehAnim == ANIM_CAR_OPEN_LHS || vehAnim == ANIM_CAR_OPEN_RHS || vehAnim == ANIM_COACH_OPEN_L || vehAnim == ANIM_COACH_OPEN_R || vehAnim == ANIM_VAN_OPEN_L || vehAnim == ANIM_VAN_OPEN) { if (!m_pMyVehicle->pDriver) { cancelJack = false; bCancelEnteringCar = true; } else cancelJack = true; } else if (vehAnim == ANIM_CAR_QJACK && m_pVehicleAnim->GetTimeLeft() > 0.75f) { cancelJack = true; } else if (vehAnim == ANIM_CAR_PULLOUT_LHS || vehAnim == ANIM_CAR_PULLOUT_LOW_LHS || vehAnim == ANIM_CAR_PULLOUT_LOW_RHS || vehAnim == ANIM_CAR_PULLOUT_RHS) { bCancelEnteringCar = true; cancelJack = false; } } if (cancelJack && vehAnim == ANIM_CAR_QJACK && m_pVehicleAnim->GetTimeLeft() > 0.75f && m_pVehicleAnim->GetTimeLeft() < 0.78f) { cancelJack = false; QuitEnteringCar(); RestorePreviousObjective(); } if (cancelJack && (vehAnim == ANIM_CAR_PULLOUT_LHS || vehAnim == ANIM_CAR_PULLOUT_LOW_LHS || vehAnim == ANIM_CAR_PULLOUT_LOW_RHS || vehAnim == ANIM_CAR_PULLOUT_RHS)) { cancelJack = false; bCancelEnteringCar = true; } #endif break; } case PED_FLEE_POS: ms_vec2DFleePosition.x = m_fleeFromPosX; ms_vec2DFleePosition.y = m_fleeFromPosY; Flee(); break; case PED_FLEE_ENTITY: if (!m_fleeFrom) { SetIdle(); break; } if (CTimer::GetTimeInMilliseconds() <= m_nPedStateTimer) break; ms_vec2DFleePosition = m_fleeFrom->GetPosition(); Flee(); break; case PED_FOLLOW_PATH: FollowPath(); break; case PED_PAUSE: Pause(); break; case PED_ATTACK: Attack(); break; case PED_FIGHT: Fight(); break; case PED_CHAT: Chat(); break; case PED_AIM_GUN: if (m_pPointGunAt && m_pPointGunAt->IsPed() #ifdef FIX_BUGS && !GetWeapon()->IsTypeMelee() #endif && ((CPed*)m_pPointGunAt)->CanSeeEntity(this, CAN_SEE_ENTITY_ANGLE_THRESHOLD * 2)) { ((CPed*)m_pPointGunAt)->ReactToPointGun(this); } PointGunAt(); break; case PED_SEEK_CAR: SeekCar(); break; case PED_SEEK_IN_BOAT: SeekBoatPosition(); break; case PED_INVESTIGATE: InvestigateEvent(); break; case PED_ON_FIRE: if (IsPlayer()) break; if (CTimer::GetTimeInMilliseconds() <= m_fleeTimer) { if (m_fleeFrom) { ms_vec2DFleePosition = m_fleeFrom->GetPosition(); } else { ms_vec2DFleePosition.x = m_fleeFromPosX; ms_vec2DFleePosition.y = m_fleeFromPosY; } Flee(); } else { if (m_pFire) m_pFire->Extinguish(); } break; case PED_FALL: Fall(); break; case PED_GETUP: SetGetUp(); break; case PED_ENTER_TRAIN: EnterTrain(); break; case PED_EXIT_TRAIN: ExitTrain(); break; case PED_DRIVING: { if (!m_pMyVehicle) { bInVehicle = false; FlagToDestroyWhenNextProcessed(); return; } if (m_pMyVehicle->pDriver != this || m_pMyVehicle->IsBoat()) { LookForSexyPeds(); LookForSexyCars(); break; } if (m_pMyVehicle->m_vehType == VEHICLE_TYPE_BIKE || !m_pMyVehicle->pDriver->IsPlayer()) { break; } CPad* pad = CPad::GetPad(0); #ifdef CAR_AIRBREAK if (!pad->ArePlayerControlsDisabled()) { if (pad->GetHorn()) { float c = Cos(m_fRotationCur); float s = Sin(m_fRotationCur); m_pMyVehicle->GetRight() = CVector(1.0f, 0.0f, 0.0f); m_pMyVehicle->GetForward() = CVector(0.0f, 1.0f, 0.0f); m_pMyVehicle->GetUp() = CVector(0.0f, 0.0f, 1.0f); if (pad->GetAccelerate()) { m_pMyVehicle->ApplyMoveForce(GetForward() * 30.0f); } else if (pad->GetBrake()) { m_pMyVehicle->ApplyMoveForce(-GetForward() * 30.0f); } else { int16 lr = pad->GetSteeringLeftRight(); if (lr < 0) { //m_pMyVehicle->ApplyTurnForce(20.0f * -GetRight(), GetForward()); m_pMyVehicle->ApplyMoveForce(-GetRight() * 30.0f); } else if (lr > 0) { m_pMyVehicle->ApplyMoveForce(GetRight() * 30.0f); } else { m_pMyVehicle->ApplyMoveForce(0.0f, 0.0f, 50.0f); } } } } #endif float steerAngle = m_pMyVehicle->m_fSteerAngle; CAnimBlendAssociation *lDriveAssoc; CAnimBlendAssociation *rDriveAssoc; CAnimBlendAssociation *lbAssoc; CAnimBlendAssociation *sitAssoc; if (m_pMyVehicle->bLowVehicle) { sitAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_LSIT); if (!sitAssoc || sitAssoc->blendAmount < 1.0f) { break; } lDriveAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_DRIVE_LOW_L); lbAssoc = nil; rDriveAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_DRIVE_LOW_R); } else { sitAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_SIT); if (!sitAssoc || sitAssoc->blendAmount < 1.0f) { break; } lDriveAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_DRIVE_L); rDriveAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_DRIVE_R); lbAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_LB); if (lbAssoc && TheCamera.Cams[TheCamera.ActiveCam].Mode == CCam::MODE_1STPERSON && TheCamera.Cams[TheCamera.ActiveCam].DirectionWasLooking == LOOKING_LEFT) { lbAssoc->blendDelta = -1000.0f; } } CAnimBlendAssociation *driveByAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_DRIVEBY_L); if (!driveByAssoc) driveByAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_DRIVEBY_R); if (m_pMyVehicle->bLowVehicle || m_pMyVehicle->m_fGasPedal >= 0.0f || driveByAssoc) { if (steerAngle == 0.0f || driveByAssoc) { if (lDriveAssoc) lDriveAssoc->blendAmount = 0.0f; if (rDriveAssoc) rDriveAssoc->blendAmount = 0.0f; } else if (steerAngle <= 0.0f) { if (lDriveAssoc) lDriveAssoc->blendAmount = 0.0f; if (rDriveAssoc) rDriveAssoc->blendAmount = clamp(steerAngle * -100.0f / 61.0f, 0.0f, 1.0f); else if (m_pMyVehicle->bLowVehicle) CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_DRIVE_LOW_R); else CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_DRIVE_R); } else { if (rDriveAssoc) rDriveAssoc->blendAmount = 0.0f; if (lDriveAssoc) lDriveAssoc->blendAmount = clamp(steerAngle * 100.0f / 61.0f, 0.0f, 1.0f); else if (m_pMyVehicle->bLowVehicle) CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_DRIVE_LOW_L); else CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_DRIVE_L); } if (lbAssoc) lbAssoc->blendDelta = -4.0f; } else { if ((TheCamera.Cams[TheCamera.ActiveCam].Mode != CCam::MODE_1STPERSON || TheCamera.Cams[TheCamera.ActiveCam].DirectionWasLooking != LOOKING_LEFT) && (!lbAssoc || lbAssoc->blendAmount < 1.0f)) { CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_CAR_LB, 4.0f); } } break; } case PED_DIE: Die(); break; case PED_HANDS_UP: if (m_pedStats->m_temper <= 50) { if (!RpAnimBlendClumpGetAssociation(GetClump(), ANIM_HANDSCOWER)) { CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_HANDSCOWER); Say(SOUND_PED_HANDS_COWER); } } else if (!RpAnimBlendClumpGetAssociation(GetClump(), ANIM_HANDSUP)) { CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_HANDSUP); Say(SOUND_PED_HANDS_UP); } break; default: break; } SetMoveAnim(); if (bPedIsBleeding) { if (CGame::nastyGame) { if (!(CTimer::GetFrameCounter() & 3)) { CVector cameraDist = GetPosition() - TheCamera.GetPosition(); if (cameraDist.MagnitudeSqr() < sq(50.0f)) { float length = (CGeneral::GetRandomNumber() & 127) * 0.0015f + 0.15f; CVector bloodPos( ((CGeneral::GetRandomNumber() & 127) - 64) * 0.007f, ((CGeneral::GetRandomNumber() & 127) - 64) * 0.007f, 1.0f); bloodPos += GetPosition(); CShadows::AddPermanentShadow(SHADOWTYPE_DARK, gpBloodPoolTex, &bloodPos, length, 0.0f, 0.0f, -length, 255, 255, 0, 0, 4.0f, (CGeneral::GetRandomNumber() & 4095) + 2000, 1.0f); } } } } ServiceTalking(); if (bInVehicle && !m_pMyVehicle) bInVehicle = false; #ifndef VC_PED_PORTS m_pCurrentPhysSurface = nil; #endif } else { if (bIsStanding && (!m_pCurrentPhysSurface || IsPlayer()) || bIsInWater || !bUsesCollision) { SetDead(); } m_pCurrentPhysSurface = nil; } } } int32 CPed::ProcessEntityCollision(CEntity *collidingEnt, CColPoint *collidingPoints) { bool collidedWithBoat = false; bool belowTorsoCollided = false; float gravityEffect = -0.15f * CTimer::GetTimeStep(); CColPoint intersectionPoint; CColLine ourLine; CColModel *ourCol = CModelInfo::GetModelInfo(GetModelIndex())->GetColModel(); CColModel *hisCol = CModelInfo::GetModelInfo(collidingEnt->GetModelIndex())->GetColModel(); if (!bUsesCollision) return false; if (collidingEnt->IsVehicle() && ((CVehicle*)collidingEnt)->IsBoat()) collidedWithBoat = true; // ofc we're not vehicle if (!m_bIsVehicleBeingShifted && !bSkipLineCol #ifdef VC_PED_PORTS && !collidingEnt->IsPed() #endif ) { if (!bCollisionProcessed) { #ifdef VC_PED_PORTS m_pCurrentPhysSurface = nil; #endif if (bIsStanding) { bIsStanding = false; bWasStanding = true; } bCollisionProcessed = true; m_fCollisionSpeed += m_vecMoveSpeed.Magnitude2D() * CTimer::GetTimeStep(); bStillOnValidPoly = false; if (IsPlayer() || m_fCollisionSpeed >= 1.0f && (m_fCollisionSpeed >= 2.0f || m_nPedState != PED_WANDER_PATH)) { m_collPoly.valid = false; m_fCollisionSpeed = 0.0f; bHitSteepSlope = false; } else { CVector pos = GetPosition(); float potentialGroundZ = GetPosition().z - FEET_OFFSET; if (bWasStanding) { pos.z += -0.25f; potentialGroundZ += gravityEffect; } if (CCollision::IsStoredPolyStillValidVerticalLine(pos, potentialGroundZ, intersectionPoint, &m_collPoly)) { bStillOnValidPoly = true; #ifdef VC_PED_PORTS if(!bSomeVCflag1 || FEET_OFFSET + intersectionPoint.point.z < GetPosition().z) { GetMatrix().GetPosition().z = FEET_OFFSET + intersectionPoint.point.z; if (bSomeVCflag1) bSomeVCflag1 = false; } #else GetMatrix().GetPosition().z = FEET_OFFSET + intersectionPoint.point.z; #endif m_vecMoveSpeed.z = 0.0f; bIsStanding = true; } else { m_collPoly.valid = false; m_fCollisionSpeed = 0.0f; bHitSteepSlope = false; } } } if (!bStillOnValidPoly) { CVector potentialCenter = GetPosition(); potentialCenter.z = GetPosition().z - 0.52f; // 0.52f should be a ped's approx. radius float totalRadiusWhenCollided = collidingEnt->GetBoundRadius() + 0.52f - gravityEffect; if (bWasStanding) { if (collidedWithBoat) { potentialCenter.z += 2.0f * gravityEffect; totalRadiusWhenCollided += Abs(gravityEffect); } else { potentialCenter.z += gravityEffect; } } if (sq(totalRadiusWhenCollided) > (potentialCenter - collidingEnt->GetBoundCentre()).MagnitudeSqr()) { ourLine.p0 = GetPosition(); ourLine.p1 = GetPosition(); ourLine.p1.z = GetPosition().z - FEET_OFFSET; if (bWasStanding) { ourLine.p1.z = ourLine.p1.z + gravityEffect; ourLine.p0.z = ourLine.p0.z + -0.25f; } float minDist = 1.0f; belowTorsoCollided = CCollision::ProcessVerticalLine(ourLine, collidingEnt->GetMatrix(), *hisCol, intersectionPoint, minDist, false, &m_collPoly); if (collidedWithBoat && bWasStanding && !belowTorsoCollided) { ourLine.p0.z = ourLine.p1.z; ourLine.p1.z = ourLine.p1.z + gravityEffect; belowTorsoCollided = CCollision::ProcessVerticalLine(ourLine, collidingEnt->GetMatrix(), *hisCol, intersectionPoint, minDist, false, &m_collPoly); } if (belowTorsoCollided) { #ifndef VC_PED_PORTS if (!collidingEnt->IsPed()) { #endif if (!bIsStanding || FEET_OFFSET + intersectionPoint.point.z > GetPosition().z || collidedWithBoat && 3.12f + intersectionPoint.point.z > GetPosition().z) { if (!collidingEnt->IsVehicle() && !collidingEnt->IsObject()) { m_pCurSurface = collidingEnt; collidingEnt->RegisterReference((CEntity**)&m_pCurSurface); bTryingToReachDryLand = false; bOnBoat = false; } else { m_pCurrentPhysSurface = (CPhysical*)collidingEnt; collidingEnt->RegisterReference((CEntity**)&m_pCurrentPhysSurface); m_vecOffsetFromPhysSurface = intersectionPoint.point - collidingEnt->GetPosition(); m_pCurSurface = collidingEnt; collidingEnt->RegisterReference((CEntity**)&m_pCurSurface); m_collPoly.valid = false; if (collidingEnt->IsVehicle() && ((CVehicle*)collidingEnt)->IsBoat()) { bOnBoat = true; } else { bOnBoat = false; } } #ifdef VC_PED_PORTS if (!bSomeVCflag1 || FEET_OFFSET + intersectionPoint.point.z < GetPosition().z) { GetMatrix().GetPosition().z = FEET_OFFSET + intersectionPoint.point.z; if (bSomeVCflag1) bSomeVCflag1 = false; } #else GetMatrix().GetPosition().z = FEET_OFFSET + intersectionPoint.point.z; #endif m_nSurfaceTouched = intersectionPoint.surfaceB; if (m_nSurfaceTouched == SURFACE_STEEP_CLIFF) { bHitSteepSlope = true; m_vecDamageNormal = intersectionPoint.normal; } } #ifdef VC_PED_PORTS float upperSpeedLimit = 0.33f; float lowerSpeedLimit = -0.25f; float speed = m_vecMoveSpeed.Magnitude2D(); if (m_nPedState == PED_IDLE) { upperSpeedLimit *= 2.0f; lowerSpeedLimit *= 1.5f; } CAnimBlendAssociation *fallAnim = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FALL_FALL); if (!bWasStanding && speed > upperSpeedLimit && (/*!bPushedAlongByCar ||*/ m_vecMoveSpeed.z < lowerSpeedLimit) && m_pCollidingEntity != collidingEnt) { float damage = 100.0f * Max(speed - 0.25f, 0.0f); float damage2 = damage; if (m_vecMoveSpeed.z < -0.25f) damage += (-0.25f - m_vecMoveSpeed.z) * 150.0f; uint8 dir = 2; // from backward if (m_vecMoveSpeed.x > 0.01f || m_vecMoveSpeed.x < -0.01f || m_vecMoveSpeed.y > 0.01f || m_vecMoveSpeed.y < -0.01f) { CVector2D offset = -m_vecMoveSpeed; dir = GetLocalDirection(offset); } InflictDamage(collidingEnt, WEAPONTYPE_FALL, damage, PEDPIECE_TORSO, dir); if (IsPlayer() && damage2 > 5.0f) Say(SOUND_PED_LAND); } else if (!bWasStanding && fallAnim && -0.016f * CTimer::GetTimeStep() > m_vecMoveSpeed.z) { InflictDamage(collidingEnt, WEAPONTYPE_FALL, 15.0f, PEDPIECE_TORSO, 2); } #else float speedSqr = 0.0f; CAnimBlendAssociation *fallAnim = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FALL_FALL); if (!bWasStanding && (m_vecMoveSpeed.z < -0.25f || (speedSqr = m_vecMoveSpeed.MagnitudeSqr()) > sq(0.5f))) { if (speedSqr == 0.0f) speedSqr = sq(m_vecMoveSpeed.z); uint8 dir = 2; // from backward if (m_vecMoveSpeed.x > 0.01f || m_vecMoveSpeed.x < -0.01f || m_vecMoveSpeed.y > 0.01f || m_vecMoveSpeed.y < -0.01f) { CVector2D offset = -m_vecMoveSpeed; dir = GetLocalDirection(offset); } InflictDamage(collidingEnt, WEAPONTYPE_FALL, 350.0f * sq(speedSqr), PEDPIECE_TORSO, dir); } else if (!bWasStanding && fallAnim && -0.016f * CTimer::GetTimeStep() > m_vecMoveSpeed.z) { InflictDamage(collidingEnt, WEAPONTYPE_FALL, 15.0f, PEDPIECE_TORSO, 2); } #endif m_vecMoveSpeed.z = 0.0f; bIsStanding = true; #ifndef VC_PED_PORTS } else { bOnBoat = false; } #endif } else { bOnBoat = false; } } } } int ourCollidedSpheres = CCollision::ProcessColModels(GetMatrix(), *ourCol, collidingEnt->GetMatrix(), *hisCol, collidingPoints, nil, nil); if (ourCollidedSpheres > 0 || belowTorsoCollided) { AddCollisionRecord(collidingEnt); if (!collidingEnt->IsBuilding()) ((CPhysical*)collidingEnt)->AddCollisionRecord(this); if (ourCollidedSpheres > 0 && (collidingEnt->IsBuilding() || collidingEnt->GetIsStatic())) { bHasHitWall = true; } } if (collidingEnt->IsBuilding() || collidingEnt->GetIsStatic()) { if (bWasStanding) { CVector sphereNormal; float normalLength; for(int sphere = 0; sphere < ourCollidedSpheres; sphere++) { sphereNormal = collidingPoints[sphere].normal; #ifdef VC_PED_PORTS if (sphereNormal.z >= -1.0f || !IsPlayer()) { #endif normalLength = sphereNormal.Magnitude2D(); if (normalLength != 0.0f) { sphereNormal.x = sphereNormal.x / normalLength; sphereNormal.y = sphereNormal.y / normalLength; } #ifdef VC_PED_PORTS } else { float speed = m_vecMoveSpeed.Magnitude2D(); sphereNormal.x = -m_vecMoveSpeed.x / Max(0.001f, speed); sphereNormal.y = -m_vecMoveSpeed.y / Max(0.001f, speed); GetMatrix().GetPosition().z -= 0.05f; bSomeVCflag1 = true; } #endif sphereNormal.Normalise(); collidingPoints[sphere].normal = sphereNormal; if (collidingPoints[sphere].surfaceB == SURFACE_STEEP_CLIFF) bHitSteepSlope = true; } } } return ourCollidedSpheres; } static void particleProduceFootSplash(CPed *ped, CVector const &pos, float size, int times) { #ifdef PC_PARTICLE for (int i = 0; i < times; i++) { CVector adjustedPos = pos; adjustedPos.x += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f); adjustedPos.y += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f); CVector direction = ped->GetForward() * -0.05f; CParticle::AddParticle(PARTICLE_RAIN_SPLASHUP, adjustedPos, direction, nil, size, CRGBA(32, 32, 32, 32), 0, 0, CGeneral::GetRandomNumber() & 1, 200); } #else for ( int32 i = 0; i < times; i++ ) { CVector adjustedPos = pos; adjustedPos.x += CGeneral::GetRandomNumberInRange(-0.2f, 0.2f); adjustedPos.y += CGeneral::GetRandomNumberInRange(-0.2f, 0.2f); CParticle::AddParticle(PARTICLE_RAIN_SPLASHUP, adjustedPos, CVector(0.0f, 0.0f, 0.0f), nil, size, CRGBA(0, 0, 0, 0), 0, 0, CGeneral::GetRandomNumber() & 1, 200); } #endif } static void particleProduceFootDust(CPed *ped, CVector const &pos, float size, int times) { switch (ped->m_nSurfaceTouched) { case SURFACE_TARMAC: case SURFACE_GRAVEL: case SURFACE_PAVEMENT: case SURFACE_SAND: for (int i = 0; i < times; ++i) { CVector adjustedPos = pos; adjustedPos.x += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f); adjustedPos.y += CGeneral::GetRandomNumberInRange(-0.1f, 0.1f); CParticle::AddParticle(PARTICLE_PEDFOOT_DUST, adjustedPos, CVector(0.0f, 0.0f, 0.0f), nil, size, CRGBA(0, 0, 0, 0), 0, 0, 0, 0); } break; default: break; } } void CPed::PlayFootSteps(void) { if (bDoBloodyFootprints) { if (m_bloodyFootprintCountOrDeathTime > 0 && m_bloodyFootprintCountOrDeathTime < 300) { m_bloodyFootprintCountOrDeathTime--; if (m_bloodyFootprintCountOrDeathTime == 0) bDoBloodyFootprints = false; } } if (!bIsStanding) return; CAnimBlendAssociation *assoc = RpAnimBlendClumpGetFirstAssociation(GetClump()); CAnimBlendAssociation *walkRunAssoc = nil; float walkRunAssocBlend = 0.0f, idleAssocBlend = 0.0f; for (; assoc; assoc = RpAnimBlendGetNextAssociation(assoc)) { if (assoc->flags & ASSOC_WALK) { walkRunAssoc = assoc; walkRunAssocBlend += assoc->blendAmount; } else if ((assoc->flags & ASSOC_NOWALK) == 0) { idleAssocBlend += assoc->blendAmount; } } #ifdef GTA_PS2_STUFF CAnimBlendAssociation *runStopAsoc = NULL; if ( IsPlayer() ) { runStopAsoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_RUN_STOP); if ( runStopAsoc == NULL ) runStopAsoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_RUN_STOP_R); } if ( runStopAsoc != NULL && runStopAsoc->blendAmount > 0.1f ) { { CVector pos(0.0f, 0.0f, 0.0f); TransformToNode(pos, PED_FOOTL); pos.z -= 0.1f; pos += GetForward()*0.2f; particleProduceFootDust(this, pos, 0.02f, 1); } { CVector pos(0.0f, 0.0f, 0.0f); TransformToNode(pos, PED_FOOTR); pos.z -= 0.1f; pos += GetForward()*0.2f; particleProduceFootDust(this, pos, 0.02f, 1); } } #endif if (walkRunAssoc && walkRunAssocBlend > 0.5f && idleAssocBlend < 1.0f) { float stepStart = 1 / 15.0f; float stepEnd = walkRunAssoc->hierarchy->totalLength / 2.0f + stepStart; float currentTime = walkRunAssoc->currentTime; int stepPart = 0; if (currentTime >= stepStart && currentTime - walkRunAssoc->timeStep < stepStart) stepPart = 1; else if (currentTime >= stepEnd && currentTime - walkRunAssoc->timeStep < stepEnd) stepPart = 2; if (stepPart != 0) { DMAudio.PlayOneShot(m_audioEntityId, stepPart == 1 ? SOUND_STEP_START : SOUND_STEP_END, 1.0f); CVector footPos(0.0f, 0.0f, 0.0f); TransformToNode(footPos, stepPart == 1 ? PED_FOOTL : PED_FOOTR); CVector forward = GetForward(); footPos.z -= 0.1f; footPos += 0.2f * forward; if (bDoBloodyFootprints) { CVector2D top(forward * 0.26f); CVector2D right(GetRight() * 0.14f); CShadows::AddPermanentShadow(SHADOWTYPE_DARK, gpBloodPoolTex, &footPos, top.x, top.y, right.x, right.y, 255, 255, 0, 0, 4.0f, 3000.0f, 1.0f); if (m_bloodyFootprintCountOrDeathTime <= 20) { m_bloodyFootprintCountOrDeathTime = 0; bDoBloodyFootprints = false; } else { m_bloodyFootprintCountOrDeathTime -= 20; } } if (CWeather::Rain <= 0.1f || CCullZones::CamNoRain() || CCullZones::PlayerNoRain()) { if(IsPlayer()) particleProduceFootDust(this, footPos, 0.0f, 4); } #ifdef PC_PARTICLE else if(stepPart == 2) #else else #endif { particleProduceFootSplash(this, footPos, 0.15f, 4); } } } if (m_nSurfaceTouched == SURFACE_WATER) { float pedSpeed = CVector2D(m_vecMoveSpeed).Magnitude(); if (pedSpeed > 0.03f && CTimer::GetFrameCounter() % 2 == 0 && pedSpeed > 0.13f) { #ifdef PC_PARTICLE float particleSize = pedSpeed * 2.0f; if (particleSize < 0.25f) particleSize = 0.25f; if (particleSize > 0.75f) particleSize = 0.75f; CVector particlePos = GetPosition() + GetForward() * 0.3f; particlePos.z -= 1.2f; CVector particleDir = m_vecMoveSpeed * -0.75f; particleDir.z = CGeneral::GetRandomNumberInRange(0.01f, 0.03f); CParticle::AddParticle(PARTICLE_PED_SPLASH, particlePos, particleDir, nil, 0.8f * particleSize, CRGBA(155,155,185,128), 0, 0, 0, 0); particleDir.z = CGeneral::GetRandomNumberInRange(0.03f, 0.05f); CParticle::AddParticle(PARTICLE_RUBBER_SMOKE, particlePos, particleDir, nil, particleSize, CRGBA(255,255,255,255), 0, 0, 0, 0); #else CVector particlePos = (GetPosition() - 0.3f * GetUp()) + GetForward()*0.3f; CVector particleDir = m_vecMoveSpeed * 0.45f; particleDir.z = CGeneral::GetRandomNumberInRange(0.03f, 0.05f); CParticle::AddParticle(PARTICLE_PED_SPLASH, particlePos-CVector(0.0f, 0.0f, 1.2f), particleDir, nil, 0.0f, CRGBA(155, 185, 155, 255)); #endif } } } // Actually GetLocalDirectionTo(Turn/Look) int CPed::GetLocalDirection(const CVector2D &posOffset) { int direction; float angle; for (angle = posOffset.Heading() - m_fRotationCur + DEGTORAD(45.0f); angle < 0.0f; angle += TWOPI); for (direction = RADTODEG(angle)/90.0f; direction > 3; direction -= 4); // 0-forward, 1-left, 2-backward, 3-right. return direction; } #ifdef NEW_WALK_AROUND_ALGORITHM CVector LocalPosForWalkAround(CVector2D colMin, CVector2D colMax, int walkAround, uint32 enterDoorNode, bool itsVan) { switch (walkAround) { case 0: if (enterDoorNode == CAR_DOOR_LF) return CVector(colMin.x, colMax.y - 1.0f, 0.0f); case 1: return CVector(colMin.x, colMax.y, 0.0f); case 2: case 3: if (walkAround == 3 && enterDoorNode == CAR_DOOR_RF) return CVector(colMax.x, colMax.y - 1.0f, 0.0f); return CVector(colMax.x, colMax.y, 0.0f); case 4: if (enterDoorNode == CAR_DOOR_RR && !itsVan) return CVector(colMax.x, colMin.y + 1.0f, 0.0f); case 5: return CVector(colMax.x, colMin.y, 0.0f); case 6: case 7: if (walkAround == 7 && enterDoorNode == CAR_DOOR_LR && !itsVan) return CVector(colMin.x, colMin.y + 1.0f, 0.0f); return CVector(colMin.x, colMin.y, 0.0f); default: return CVector(0.0f, 0.0f, 0.0f); } } bool CanWeSeeTheCorner(CVector2D dist, CVector2D fwdOffset) { // because fov isn't important if dist is more then 5 unit, we want shortest way if (dist.Magnitude() > 5.0f) return true; if (DotProduct2D(dist, fwdOffset) < 0.0f) return false; return true; } #endif // This function looks completely same on VC. void CPed::SetDirectionToWalkAroundObject(CEntity *obj) { float distLimitForTimer = 8.0f; CColModel *objCol = CModelInfo::GetModelInfo(obj->GetModelIndex())->GetColModel(); CVector objColMin = objCol->boundingBox.min; CVector objColMax = objCol->boundingBox.max; CVector objColCenter = (objColMin + objColMax) / 2.0f; CMatrix objMat(obj->GetMatrix()); float dirToSet = obj->GetForward().Heading(); bool goingToEnterCarAndItsVan = false; bool goingToEnterCar = false; bool objUpsideDown = false; float checkIntervalInDist = (objColMax.y - objColMin.y) * 0.1f; float checkIntervalInTime; if (m_nMoveState == PEDMOVE_NONE || m_nMoveState == PEDMOVE_STILL) return; #ifndef PEDS_REPORT_CRIMES_ON_PHONE if (CharCreatedBy != MISSION_CHAR && obj->GetModelIndex() == MI_PHONEBOOTH1) { bool isRunning = m_nMoveState == PEDMOVE_RUN || m_nMoveState == PEDMOVE_SPRINT; SetFindPathAndFlee(obj, 5000, !isRunning); return; } #endif CVector2D adjustedColMin(objColMin.x - 0.35f, objColMin.y - 0.35f); CVector2D adjustedColMax(objColMax.x + 0.35f, objColMax.y + 0.35f); checkIntervalInDist = Max(checkIntervalInDist, 0.5f); checkIntervalInDist = Min(checkIntervalInDist, (objColMax.z - objColMin.z) / 2.0f); checkIntervalInDist = Min(checkIntervalInDist, (adjustedColMax.x - adjustedColMin.x) / 2.0f); if (objMat.GetUp().z < 0.0f) objUpsideDown = true; if (obj->GetModelIndex() != MI_TRAFFICLIGHTS && obj->GetModelIndex() != MI_SINGLESTREETLIGHTS1 && obj->GetModelIndex() != MI_SINGLESTREETLIGHTS2) { objColCenter = obj->GetMatrix() * objColCenter; } else { checkIntervalInDist = 0.4f; if (objMat.GetUp().z <= 0.57f) { // Specific calculations for traffic lights, didn't get a bit. adjustedColMin.x = 1.2f * (adjustedColMin.x < adjustedColMin.y ? adjustedColMin.x : adjustedColMin.y); adjustedColMax.x = 1.2f * (adjustedColMax.x > adjustedColMax.y ? adjustedColMax.x : adjustedColMax.y); adjustedColMin.y = 1.2f * objColMin.z; adjustedColMax.y = 1.2f * objColMax.z; dirToSet = objMat.GetUp().Heading(); objMat.SetUnity(); objMat.RotateZ(dirToSet); objMat.GetPosition() += obj->GetPosition(); objColCenter = obj->GetPosition(); } else { objColCenter.x = adjustedColMax.x - 0.25f; objColCenter = obj->GetMatrix() * objColCenter; distLimitForTimer = 0.75f; } objUpsideDown = false; } float oldRotDest = m_fRotationDest; #ifndef NEW_WALK_AROUND_ALGORITHM float angleToFaceObjCenter = (objColCenter - GetPosition()).Heading(); float angleDiffBtwObjCenterAndForward = CGeneral::LimitRadianAngle(dirToSet - angleToFaceObjCenter); float objTopRightHeading = Atan2(adjustedColMax.x - adjustedColMin.x, adjustedColMax.y - adjustedColMin.y); #endif if (IsPlayer()) { if (FindPlayerPed()->m_fMoveSpeed <= 0.0f) checkIntervalInTime = 0.0f; else checkIntervalInTime = 2.0f / FindPlayerPed()->m_fMoveSpeed; } else { switch (m_nMoveState) { case PEDMOVE_WALK: checkIntervalInTime = 2.0f; break; case PEDMOVE_RUN: checkIntervalInTime = 0.5f; break; case PEDMOVE_SPRINT: checkIntervalInTime = 0.5f; break; default: checkIntervalInTime = 0.0f; break; } } if (m_pSeekTarget == obj && obj->IsVehicle()) { if (m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER || m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER || m_objective == OBJECTIVE_SOLICIT_VEHICLE) { goingToEnterCar = true; if (IsPlayer()) checkIntervalInTime = 0.0f; if (((CVehicle*)obj)->bIsVan) goingToEnterCarAndItsVan = true; } } int entityOnTopLeftOfObj = 0; int entityOnBottomLeftOfObj = 0; int entityOnTopRightOfObj = 0; int entityOnBottomRightOfObj = 0; if (CTimer::GetTimeInMilliseconds() > m_collidingThingTimer || m_collidingEntityWhileFleeing != obj) { bool collidingThingChanged = true; CEntity *obstacle; #ifndef NEW_WALK_AROUND_ALGORITHM if (!obj->IsVehicle() || objUpsideDown) { collidingThingChanged = false; } else { #else CVector cornerToGo = CVector(10.0f, 10.0f, 10.0f); int dirToGo; m_walkAroundType = 0; int iWouldPreferGoingBack = 0; // 1:left 2:right #endif float adjustedCheckInterval = 0.7f * checkIntervalInDist; CVector posToCheck; // Top left of obj posToCheck.x = adjustedColMin.x + adjustedCheckInterval; posToCheck.y = adjustedColMax.y - adjustedCheckInterval; posToCheck.z = 0.0f; posToCheck = objMat * posToCheck; posToCheck.z += 0.6f; obstacle = CWorld::TestSphereAgainstWorld(posToCheck, checkIntervalInDist, obj, true, true, false, true, false, false); if (obstacle) { if (obstacle->IsBuilding()) { entityOnTopLeftOfObj = 1; } else if (obstacle->IsVehicle()) { entityOnTopLeftOfObj = 2; } else { entityOnTopLeftOfObj = 3; } } #ifdef NEW_WALK_AROUND_ALGORITHM else { CVector tl = obj->GetMatrix() * CVector(adjustedColMin.x, adjustedColMax.y, 0.0f) - GetPosition(); if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_LF || m_vehEnterType == CAR_DOOR_LR)) { cornerToGo = tl; m_walkAroundType = 1; if (m_vehEnterType == CAR_DOOR_LR) iWouldPreferGoingBack = 1; } else if(CanWeSeeTheCorner(tl, GetForward())){ cornerToGo = tl; dirToGo = GetLocalDirection(tl); if (dirToGo == 1) m_walkAroundType = 0; // ALL of the next turns will be right turn else if (dirToGo == 3) m_walkAroundType = 1; // ALL of the next turns will be left turn } } #endif // Top right of obj posToCheck.x = adjustedColMax.x - adjustedCheckInterval; posToCheck.y = adjustedColMax.y - adjustedCheckInterval; posToCheck.z = 0.0f; posToCheck = objMat * posToCheck; posToCheck.z += 0.6f; obstacle = CWorld::TestSphereAgainstWorld(posToCheck, checkIntervalInDist, obj, true, true, false, true, false, false); if (obstacle) { if (obstacle->IsBuilding()) { entityOnTopRightOfObj = 1; } else if (obstacle->IsVehicle()) { entityOnTopRightOfObj = 2; } else { entityOnTopRightOfObj = 3; } } #ifdef NEW_WALK_AROUND_ALGORITHM else { CVector tr = obj->GetMatrix() * CVector(adjustedColMax.x, adjustedColMax.y, 0.0f) - GetPosition(); if (tr.Magnitude2D() < cornerToGo.Magnitude2D()) { if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_RF || m_vehEnterType == CAR_DOOR_RR)) { cornerToGo = tr; m_walkAroundType = 2; if (m_vehEnterType == CAR_DOOR_RR) iWouldPreferGoingBack = 2; } else if (CanWeSeeTheCorner(tr, GetForward())) { cornerToGo = tr; dirToGo = GetLocalDirection(tr); if (dirToGo == 1) m_walkAroundType = 2; // ALL of the next turns will be right turn else if (dirToGo == 3) m_walkAroundType = 3; // ALL of the next turns will be left turn } } } #endif // Bottom right of obj posToCheck.x = adjustedColMax.x - adjustedCheckInterval; posToCheck.y = adjustedColMin.y + adjustedCheckInterval; posToCheck.z = 0.0f; posToCheck = objMat * posToCheck; posToCheck.z += 0.6f; obstacle = CWorld::TestSphereAgainstWorld(posToCheck, checkIntervalInDist, obj, true, true, false, true, false, false); if (obstacle) { if (obstacle->IsBuilding()) { entityOnBottomRightOfObj = 1; } else if (obstacle->IsVehicle()) { entityOnBottomRightOfObj = 2; } else { entityOnBottomRightOfObj = 3; } } #ifdef NEW_WALK_AROUND_ALGORITHM else { CVector br = obj->GetMatrix() * CVector(adjustedColMax.x, adjustedColMin.y, 0.0f) - GetPosition(); if (iWouldPreferGoingBack == 2) m_walkAroundType = 4; else if (br.Magnitude2D() < cornerToGo.Magnitude2D()) { if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_RF || m_vehEnterType == CAR_DOOR_RR)) { cornerToGo = br; m_walkAroundType = 5; } else if (CanWeSeeTheCorner(br, GetForward())) { cornerToGo = br; dirToGo = GetLocalDirection(br); if (dirToGo == 1) m_walkAroundType = 4; // ALL of the next turns will be right turn else if (dirToGo == 3) m_walkAroundType = 5; // ALL of the next turns will be left turn } } } #endif // Bottom left of obj posToCheck.x = adjustedColMin.x + adjustedCheckInterval; posToCheck.y = adjustedColMin.y + adjustedCheckInterval; posToCheck.z = 0.0f; posToCheck = objMat * posToCheck; posToCheck.z += 0.6f; obstacle = CWorld::TestSphereAgainstWorld(posToCheck, checkIntervalInDist, obj, true, true, false, true, false, false); if (obstacle) { if (obstacle->IsBuilding()) { entityOnBottomLeftOfObj = 1; } else if (obstacle->IsVehicle()) { entityOnBottomLeftOfObj = 2; } else { entityOnBottomLeftOfObj = 3; } } #ifdef NEW_WALK_AROUND_ALGORITHM else { CVector bl = obj->GetMatrix() * CVector(adjustedColMin.x, adjustedColMin.y, 0.0f) - GetPosition(); if (iWouldPreferGoingBack == 1) m_walkAroundType = 7; else if (bl.Magnitude2D() < cornerToGo.Magnitude2D()) { if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_LF || m_vehEnterType == CAR_DOOR_LR)) { cornerToGo = bl; m_walkAroundType = 6; } else if (CanWeSeeTheCorner(bl, GetForward())) { cornerToGo = bl; dirToGo = GetLocalDirection(bl); if (dirToGo == 1) m_walkAroundType = 6; // ALL of the next turns will be right turn else if (dirToGo == 3) m_walkAroundType = 7; // ALL of the next turns will be left turn } } } #else } if (entityOnTopLeftOfObj && entityOnTopRightOfObj && entityOnBottomRightOfObj && entityOnBottomLeftOfObj) { collidingThingChanged = false; entityOnTopLeftOfObj = 0; entityOnBottomLeftOfObj = 0; entityOnTopRightOfObj = 0; entityOnBottomRightOfObj = 0; } if (!collidingThingChanged) { m_walkAroundType = 0; } else { if (Abs(angleDiffBtwObjCenterAndForward) >= objTopRightHeading) { if (PI - objTopRightHeading >= Abs(angleDiffBtwObjCenterAndForward)) { if ((angleDiffBtwObjCenterAndForward <= 0.0f || objUpsideDown) && (angleDiffBtwObjCenterAndForward < 0.0f || !objUpsideDown)) { if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_RF || m_vehEnterType == CAR_DOOR_RR)) { m_walkAroundType = 0; } else { if (CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) >= 0.0f) { if (entityOnBottomRightOfObj == 1 || entityOnBottomRightOfObj && !entityOnTopLeftOfObj && !entityOnTopRightOfObj) { m_walkAroundType = 1; } else if (entityOnBottomLeftOfObj == 1 || entityOnBottomLeftOfObj && !entityOnTopLeftOfObj && !entityOnTopRightOfObj) { m_walkAroundType = 1; } } else { if (entityOnTopRightOfObj == 1 || entityOnTopRightOfObj && !entityOnBottomRightOfObj && !entityOnBottomLeftOfObj) { m_walkAroundType = 4; } else if (entityOnTopLeftOfObj == 1 || entityOnTopLeftOfObj && !entityOnBottomRightOfObj && !entityOnBottomLeftOfObj) { m_walkAroundType = 4; } } } } else { if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_LF || m_vehEnterType == CAR_DOOR_LR)) { m_walkAroundType = 0; } else { if (CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) <= 0.0f) { if (entityOnBottomLeftOfObj == 1 || entityOnBottomLeftOfObj && !entityOnTopLeftOfObj && !entityOnTopRightOfObj) { m_walkAroundType = 2; } else if (entityOnBottomRightOfObj == 1 || entityOnBottomRightOfObj && !entityOnTopLeftOfObj && !entityOnTopRightOfObj) { m_walkAroundType = 2; } } else { if (entityOnTopLeftOfObj == 1 || entityOnTopLeftOfObj && !entityOnBottomRightOfObj && !entityOnBottomLeftOfObj) { m_walkAroundType = 3; } else if (entityOnTopRightOfObj == 1 || entityOnTopRightOfObj && !entityOnBottomRightOfObj && !entityOnBottomLeftOfObj) { m_walkAroundType = 3; } } } } } else if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_LF || m_vehEnterType == CAR_DOOR_LR) || CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) < 0.0f) { if (entityOnTopLeftOfObj == 1 || entityOnTopLeftOfObj && !entityOnTopRightOfObj && !entityOnBottomRightOfObj) { m_walkAroundType = 3; } } else if (entityOnTopRightOfObj == 1 || entityOnTopRightOfObj && !entityOnTopLeftOfObj && !entityOnBottomLeftOfObj) { m_walkAroundType = 4; } } else if (goingToEnterCar && (m_vehEnterType == CAR_DOOR_LF || m_vehEnterType == CAR_DOOR_LR) || CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) > 0.0f) { if (entityOnBottomLeftOfObj == 1 || entityOnBottomLeftOfObj && !entityOnTopRightOfObj && !entityOnBottomRightOfObj) { m_walkAroundType = 2; } } else if (entityOnBottomRightOfObj == 1 || entityOnBottomRightOfObj && !entityOnTopLeftOfObj && !entityOnBottomLeftOfObj) { m_walkAroundType = 1; } else { m_walkAroundType = 0; } } #endif } m_collidingEntityWhileFleeing = obj; m_collidingEntityWhileFleeing->RegisterReference((CEntity**) &m_collidingEntityWhileFleeing); // TODO: This random may need to be changed. m_collidingThingTimer = CTimer::GetTimeInMilliseconds() + 512 + CGeneral::GetRandomNumber(); CVector localPosToHead; #ifdef NEW_WALK_AROUND_ALGORITHM int nextWalkAround = m_walkAroundType; if (m_walkAroundType % 2 == 0) { nextWalkAround += 2; if (nextWalkAround > 6) nextWalkAround = 0; } else { nextWalkAround -= 2; if (nextWalkAround < 0) nextWalkAround = 7; } CVector nextPosToHead = objMat * LocalPosForWalkAround(adjustedColMin, adjustedColMax, nextWalkAround, goingToEnterCar ? m_vehEnterType : 0, goingToEnterCarAndItsVan); bool nextRouteIsClear = CWorld::GetIsLineOfSightClear(GetPosition(), nextPosToHead, true, true, true, true, true, true, false); if(nextRouteIsClear) m_walkAroundType = nextWalkAround; else { CVector posToHead = objMat * LocalPosForWalkAround(adjustedColMin, adjustedColMax, m_walkAroundType, goingToEnterCar ? m_vehEnterType : 0, goingToEnterCarAndItsVan); bool currentRouteIsClear = CWorld::GetIsLineOfSightClear(GetPosition(), posToHead, true, true, true, true, true, true, false); /* Either; * - Some obstacle came in and it's impossible to reach current destination * - We reached to the destination, but since next route is not clear, we're turning around us */ if (!currentRouteIsClear || ((posToHead - GetPosition()).Magnitude2D() < 0.8f && !CWorld::GetIsLineOfSightClear(GetPosition() + GetForward(), nextPosToHead, true, true, true, true, true, true, false))) { // Change both target and direction (involves changing even/oddness) if (m_walkAroundType % 2 == 0) { m_walkAroundType -= 2; if (m_walkAroundType < 0) m_walkAroundType = 7; else m_walkAroundType += 1; } else { m_walkAroundType += 2; if (m_walkAroundType > 7) m_walkAroundType = 0; else m_walkAroundType -= 1; } } } localPosToHead = LocalPosForWalkAround(adjustedColMin, adjustedColMax, m_walkAroundType, goingToEnterCar ? m_vehEnterType : 0, goingToEnterCarAndItsVan); #else if (Abs(angleDiffBtwObjCenterAndForward) < objTopRightHeading) { if (goingToEnterCar) { if (goingToEnterCarAndItsVan) { if (m_vehEnterType == CAR_DOOR_LR || m_vehEnterType == CAR_DOOR_RR) return; } if (m_vehEnterType != CAR_DOOR_LF && m_vehEnterType != CAR_DOOR_LR && (!entityOnBottomRightOfObj || entityOnBottomLeftOfObj)) { m_fRotationDest = CGeneral::LimitRadianAngle(dirToSet - HALFPI); localPosToHead.x = adjustedColMax.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } else { m_fRotationDest = CGeneral::LimitRadianAngle(HALFPI + dirToSet); localPosToHead.x = adjustedColMin.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } } else { if (m_walkAroundType != 1 && m_walkAroundType != 4 && (m_walkAroundType || CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) <= 0.0f)) { m_fRotationDest = CGeneral::LimitRadianAngle(dirToSet - HALFPI); localPosToHead.x = adjustedColMax.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } else { m_fRotationDest = CGeneral::LimitRadianAngle(HALFPI + dirToSet); localPosToHead.x = adjustedColMin.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } } } else { if (PI - objTopRightHeading >= Abs(angleDiffBtwObjCenterAndForward)) { if (angleDiffBtwObjCenterAndForward <= 0.0f) { if (!goingToEnterCar || !goingToEnterCarAndItsVan || m_vehEnterType != CAR_DOOR_LR && m_vehEnterType != CAR_DOOR_RR) { if (goingToEnterCar) { if (m_vehEnterType == CAR_DOOR_RF || (m_vehEnterType == CAR_DOOR_RR && !goingToEnterCarAndItsVan)) return; } if (m_walkAroundType == 4 || m_walkAroundType == 3 || !m_walkAroundType && CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) > 0.0f) { m_fRotationDest = CGeneral::LimitRadianAngle(PI + dirToSet); localPosToHead.x = adjustedColMax.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } else { m_fRotationDest = dirToSet; localPosToHead.x = adjustedColMax.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMax.y; } } else { m_fRotationDest = CGeneral::LimitRadianAngle(PI + dirToSet); localPosToHead.x = adjustedColMax.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } } else if (goingToEnterCar && goingToEnterCarAndItsVan && (m_vehEnterType == CAR_DOOR_LR || m_vehEnterType == CAR_DOOR_RR)) { m_fRotationDest = CGeneral::LimitRadianAngle(PI + dirToSet); localPosToHead.x = adjustedColMin.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } else { if (goingToEnterCar) { if (m_vehEnterType == CAR_DOOR_LF || m_vehEnterType == CAR_DOOR_LR && !goingToEnterCarAndItsVan) return; } if (m_walkAroundType == 1 || m_walkAroundType == 2 || !m_walkAroundType && CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) > 0.0f) { m_fRotationDest = dirToSet; localPosToHead.x = adjustedColMin.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMax.y; } else { m_fRotationDest = CGeneral::LimitRadianAngle(PI + dirToSet); localPosToHead.x = adjustedColMin.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMin.y; } } } else { if (goingToEnterCar && (!goingToEnterCarAndItsVan || m_vehEnterType != CAR_DOOR_LR && m_vehEnterType != CAR_DOOR_RR)) { if (m_vehEnterType != CAR_DOOR_LF && m_vehEnterType != CAR_DOOR_LR && (!entityOnTopRightOfObj || entityOnTopLeftOfObj)) { m_fRotationDest = CGeneral::LimitRadianAngle(dirToSet - HALFPI); localPosToHead.x = adjustedColMax.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMax.y; } else { m_fRotationDest = CGeneral::LimitRadianAngle(HALFPI + dirToSet); localPosToHead.x = adjustedColMin.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMax.y; } } else { if (m_walkAroundType == 2 || m_walkAroundType == 3 || !m_walkAroundType && CGeneral::LimitRadianAngle(m_fRotationDest - angleToFaceObjCenter) > 0.0f) { m_fRotationDest = CGeneral::LimitRadianAngle(dirToSet - HALFPI); localPosToHead.x = adjustedColMax.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMax.y; } else { m_fRotationDest = CGeneral::LimitRadianAngle(HALFPI + dirToSet); localPosToHead.x = adjustedColMin.x; localPosToHead.z = 0.0f; localPosToHead.y = adjustedColMax.y; } } } } #endif if (objUpsideDown) localPosToHead.x = localPosToHead.x * -1.0f; localPosToHead = objMat * localPosToHead; m_actionX = localPosToHead.x; m_actionY = localPosToHead.y; localPosToHead -= GetPosition(); m_fRotationDest = CGeneral::LimitRadianAngle(localPosToHead.Heading()); if (m_fRotationDest != m_fRotationCur && bHitSomethingLastFrame) { if (m_fRotationDest == oldRotDest) { m_fRotationDest = oldRotDest; } else { m_fRotationDest = CGeneral::LimitRadianAngle(PI + dirToSet); } } float dist = localPosToHead.Magnitude2D(); if (dist < 0.5f) dist = 0.5f; if (dist > distLimitForTimer) dist = distLimitForTimer; m_nPedStateTimer = CTimer::GetTimeInMilliseconds() + 280.0f * dist * checkIntervalInTime; } bool CPed::IsPedInControl(void) { return m_nPedState <= PED_STATES_NO_AI && !bIsInTheAir && !bIsLanding && m_fHealth > 0.0f; } bool CPed::IsPedShootable(void) { return m_nPedState <= PED_STATES_NO_ST; } bool CPed::UseGroundColModel(void) { return m_nPedState == PED_FALL || m_nPedState == PED_DIVE_AWAY || m_nPedState == PED_DIE || m_nPedState == PED_DEAD; } bool CPed::CanPedReturnToState(void) { return m_nPedState <= PED_STATES_NO_AI && m_nPedState != PED_AIM_GUN && m_nPedState != PED_ATTACK && m_nPedState != PED_FIGHT && m_nPedState != PED_STEP_AWAY && m_nPedState != PED_SNIPER_MODE && m_nPedState != PED_LOOK_ENTITY; } bool CPed::CanSetPedState(void) { return !DyingOrDead() && m_nPedState != PED_ARRESTED && !EnteringCar() && m_nPedState != PED_STEAL_CAR; } bool CPed::CanStrafeOrMouseControl(void) { #ifdef FREE_CAM if (CCamera::bFreeCam) return false; #endif return m_nPedState == PED_NONE || m_nPedState == PED_IDLE || m_nPedState == PED_FLEE_POS || m_nPedState == PED_FLEE_ENTITY || m_nPedState == PED_ATTACK || m_nPedState == PED_FIGHT || m_nPedState == PED_AIM_GUN || m_nPedState == PED_JUMP; } void CPed::PedGetupCB(CAnimBlendAssociation* animAssoc, void* arg) { CPed* ped = (CPed*)arg; if (ped->m_nPedState == PED_GETUP) RpAnimBlendClumpSetBlendDeltas(ped->GetClump(), ASSOC_PARTIAL, -1000.0f); ped->bFallenDown = false; animAssoc->blendDelta = -1000.0f; if (ped->m_nPedState == PED_GETUP) ped->RestorePreviousState(); if (ped->m_nPedState != PED_FLEE_POS && ped->m_nPedState != PED_FLEE_ENTITY) ped->SetMoveState(PEDMOVE_STILL); else ped->SetMoveState(PEDMOVE_RUN); ped->SetMoveAnim(); ped->bGetUpAnimStarted = false; } void CPed::PedLandCB(CAnimBlendAssociation* animAssoc, void* arg) { CPed* ped = (CPed*)arg; animAssoc->blendDelta = -1000.0f; ped->bIsLanding = false; if (ped->m_nPedState == PED_JUMP) ped->RestorePreviousState(); } void CPed::PedStaggerCB(CAnimBlendAssociation* animAssoc, void* arg) { /* CPed *ped = (CPed*)arg; if (ped->m_nPedState == PED_STAGGER) // nothing */ } void CPed::PedSetOutCarCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; CVehicle *veh = ped->m_pMyVehicle; bool startedToRun = false; ped->bUsesCollision = true; ped->m_actionX = 0.0f; ped->m_actionY = 0.0f; ped->bVehExitWillBeInstant = false; if (veh && veh->IsBoat()) ped->ApplyMoveSpeed(); if (ped->m_objective == OBJECTIVE_LEAVE_CAR) ped->RestorePreviousObjective(); #ifdef VC_PED_PORTS else if (ped->m_objective == OBJECTIVE_LEAVE_CAR_AND_DIE) { ped->m_fHealth = 0.0f; ped->SetDie(ANIM_FLOOR_HIT, 4.0f, 0.5f); } #endif ped->bInVehicle = false; if (veh && veh->IsCar() && !veh->IsRoomForPedToLeaveCar(ped->m_vehEnterType, nil)) { ped->PositionPedOutOfCollision(); } if (ped->m_nPedState == PED_EXIT_CAR) { if (ped->m_nPedType == PEDTYPE_COP) ped->SetIdle(); else ped->RestorePreviousState(); veh = ped->m_pMyVehicle; if (ped->bFleeAfterExitingCar && veh) { ped->bFleeAfterExitingCar = false; ped->SetFlee(veh->GetPosition(), 12000); ped->bUsePedNodeSeek = true; ped->m_pNextPathNode = nil; if (CGeneral::GetRandomNumber() & 1 || ped->m_pedStats->m_fear > 70) { ped->SetMoveState(PEDMOVE_SPRINT); ped->Say(SOUND_PED_FLEE_SPRINT); } else { ped->SetMoveState(PEDMOVE_RUN); ped->Say(SOUND_PED_FLEE_RUN); } startedToRun = true; // This is not a good way to do this... ped->m_nLastPedState = PED_WANDER_PATH; } else if (ped->bWanderPathAfterExitingCar) { ped->SetWanderPath(CGeneral::GetRandomNumberInRange(0.0f, 8.0f)); ped->bWanderPathAfterExitingCar = false; if (ped->m_nPedType == PEDTYPE_PROSTITUTE) ped->SetObjectiveTimer(30000); ped->m_nLastPedState = PED_NONE; } else if (ped->bGonnaKillTheCarJacker) { // Kill objective is already given at this point. ped->bGonnaKillTheCarJacker = false; if (ped->m_pedInObjective) { if (!(CGeneral::GetRandomNumber() & 1) && ped->m_nPedType != PEDTYPE_COP && (!ped->m_pedInObjective->IsPlayer() || !CTheScripts::IsPlayerOnAMission())) { ped->ClearObjective(); ped->SetObjective(OBJECTIVE_ENTER_CAR_AS_DRIVER, veh); } ped->m_leaveCarTimer = CTimer::GetTimeInMilliseconds() + 1500; } int waitTime = 1500; ped->SetWaitState(WAITSTATE_PLAYANIM_COWER, &waitTime); ped->SetMoveState(PEDMOVE_RUN); startedToRun = true; } else if (ped->m_objective == OBJECTIVE_NONE && ped->CharCreatedBy != MISSION_CHAR && ped->m_nPedState == PED_IDLE && !ped->IsPlayer()) { ped->SetWanderPath(CGeneral::GetRandomNumberInRange(0.0f, 8.0f)); } } #ifdef VC_PED_PORTS else { ped->m_nPedState = PED_IDLE; } #endif if (animAssoc) animAssoc->blendDelta = -1000.0f; ped->RestartNonPartialAnims(); ped->m_pVehicleAnim = nil; CVector posFromZ = ped->GetPosition(); CPedPlacement::FindZCoorForPed(&posFromZ); ped->m_vecMoveSpeed = CVector(0.0f, 0.0f, 0.0f); ped->SetPosition(posFromZ); veh = ped->m_pMyVehicle; if (veh) { if (ped->m_nPedType == PEDTYPE_PROSTITUTE) { if (veh->pDriver) { if (veh->pDriver->IsPlayer() && ped->CharCreatedBy == RANDOM_CHAR) { CWorld::Players[CWorld::PlayerInFocus].m_nNextSexMoneyUpdateTime = 0; CWorld::Players[CWorld::PlayerInFocus].m_nNextSexFrequencyUpdateTime = 0; CWorld::Players[CWorld::PlayerInFocus].m_pHooker = nil; CWorld::Players[CWorld::PlayerInFocus].m_nMoney -= 100; if (CWorld::Players[CWorld::PlayerInFocus].m_nMoney < 0) CWorld::Players[CWorld::PlayerInFocus].m_nMoney = 0; } } } veh->m_nGettingOutFlags &= ~GetCarDoorFlag(ped->m_vehEnterType); if (veh->pDriver == ped) { veh->RemoveDriver(); veh->SetStatus(STATUS_ABANDONED); if (veh->m_nDoorLock == CARLOCK_LOCKED_INITIALLY) veh->m_nDoorLock = CARLOCK_UNLOCKED; if (ped->m_nPedType == PEDTYPE_COP && veh->IsLawEnforcementVehicle()) veh->ChangeLawEnforcerState(false); } else { veh->RemovePassenger(ped); } if (veh->bIsBus && !veh->IsUpsideDown() && !veh->IsOnItsSide()) { float angleAfterExit; if (ped->m_vehEnterType == CAR_DOOR_LF) { angleAfterExit = HALFPI + veh->GetForward().Heading(); } else { angleAfterExit = veh->GetForward().Heading() - HALFPI; } ped->SetHeading(angleAfterExit); ped->m_fRotationDest = angleAfterExit; ped->m_fRotationCur = angleAfterExit; if (!ped->bBusJacked) ped->SetMoveState(PEDMOVE_WALK); } if (CGarages::IsPointWithinAnyGarage(ped->GetPosition())) veh->bLightsOn = false; } if (ped->IsPlayer()) AudioManager.PlayerJustLeftCar(); ped->ReplaceWeaponWhenExitingVehicle(); ped->bOnBoat = false; if (ped->bBusJacked) { ped->SetFall(1500, ANIM_KO_SKID_BACK, false); ped->bBusJacked = false; } ped->m_nStoredMoveState = PEDMOVE_NONE; if (!ped->IsPlayer()) { // It's a shame... #ifdef FIX_BUGS int createdBy = ped->CharCreatedBy; #else int createdBy = !ped->CharCreatedBy; #endif if (createdBy == MISSION_CHAR && !startedToRun) ped->SetMoveState(PEDMOVE_WALK); } } void CPed::PedSetDraggedOutCarCB(CAnimBlendAssociation *dragAssoc, void *arg) { CAnimBlendAssociation *quickJackedAssoc; CVehicle *vehicle; CPed *ped = (CPed*)arg; quickJackedAssoc = RpAnimBlendClumpGetAssociation(ped->GetClump(), ANIM_CAR_QJACKED); if (ped->m_nPedState != PED_ARRESTED) { ped->m_nLastPedState = PED_NONE; if (dragAssoc) dragAssoc->blendDelta = -1000.0f; } ped->RestartNonPartialAnims(); ped->m_pVehicleAnim = nil; ped->m_pSeekTarget = nil; vehicle = ped->m_pMyVehicle; if (vehicle) { vehicle->m_nGettingOutFlags &= ~GetCarDoorFlag(ped->m_vehEnterType); if (vehicle->pDriver == ped) { vehicle->RemoveDriver(); if (vehicle->m_nDoorLock == CARLOCK_LOCKED_INITIALLY) vehicle->m_nDoorLock = CARLOCK_UNLOCKED; if (ped->m_nPedType == PEDTYPE_COP && vehicle->IsLawEnforcementVehicle()) vehicle->ChangeLawEnforcerState(false); } else { vehicle->RemovePassenger(ped); } } ped->bInVehicle = false; if (ped->IsPlayer()) AudioManager.PlayerJustLeftCar(); #ifdef VC_PED_PORTS if (ped->m_objective == OBJECTIVE_LEAVE_CAR_AND_DIE) { dragAssoc->SetDeleteCallback(PedSetDraggedOutCarPositionCB, ped); ped->m_fHealth = 0.0f; ped->SetDie(ANIM_FLOOR_HIT, 1000.0f, 0.5f); return; } #endif if (quickJackedAssoc) { dragAssoc->SetDeleteCallback(PedSetQuickDraggedOutCarPositionCB, ped); } else { dragAssoc->SetDeleteCallback(PedSetDraggedOutCarPositionCB, ped); if (ped->CanSetPedState()) CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_GETUP1, 1000.0f); } ped->ReplaceWeaponWhenExitingVehicle(); ped->m_nStoredMoveState = PEDMOVE_NONE; ped->bVehExitWillBeInstant = false; } void CPed::PedSetInCarCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; CVehicle *veh = ped->m_pMyVehicle; // Pointless code if (!veh) return; #ifdef VC_PED_PORTS // Situation of entering car as a driver while there is already a driver exiting atm. CPed *driver = veh->pDriver; if (driver && driver->m_nPedState == PED_DRIVING && !veh->bIsBus && driver->m_objective == OBJECTIVE_LEAVE_CAR && (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER || ped->m_nPedState == PED_CARJACK)) { if (!ped->IsPlayer() && (ped->CharCreatedBy != MISSION_CHAR || driver->IsPlayer())) { ped->QuitEnteringCar(); return; } if (driver->CharCreatedBy == MISSION_CHAR) { PedSetOutCarCB(nil, veh->pDriver); if (driver->m_pMyVehicle) { driver->PositionPedOutOfCollision(); } else { driver->m_pMyVehicle = veh; driver->PositionPedOutOfCollision(); driver->m_pMyVehicle = nil; } veh->pDriver = nil; } else { driver->SetDead(); driver->FlagToDestroyWhenNextProcessed(); veh->pDriver = nil; } } #endif if (!ped->IsNotInWreckedVehicle() || ped->DyingOrDead()) return; ped->bInVehicle = true; if (ped->m_nPedType == PEDTYPE_PROSTITUTE) { if (veh->pDriver) { if (veh->pDriver->IsPlayer() && ped->CharCreatedBy == RANDOM_CHAR) { CWorld::Players[CWorld::PlayerInFocus].m_nSexFrequency = 1000; CWorld::Players[CWorld::PlayerInFocus].m_nNextSexMoneyUpdateTime = CTimer::GetTimeInMilliseconds() + 1000; CWorld::Players[CWorld::PlayerInFocus].m_nNextSexFrequencyUpdateTime = CTimer::GetTimeInMilliseconds() + 3000; CWorld::Players[CWorld::PlayerInFocus].m_pHooker = (CCivilianPed*)ped; } } } if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER #if defined VC_PED_PORTS || defined FIX_BUGS || ped->m_nPedState == PED_CARJACK #endif ) veh->bIsBeingCarJacked = false; if (veh->m_nNumGettingIn) --veh->m_nNumGettingIn; if (ped->IsPlayer() && ((CPlayerPed*)ped)->m_bAdrenalineActive) ((CPlayerPed*)ped)->ClearAdrenaline(); if (veh->IsBoat()) { if (ped->IsPlayer()) { #if defined VC_PED_PORTS || defined FIX_BUGS CCarCtrl::RegisterVehicleOfInterest(veh); #endif if (veh->GetStatus() == STATUS_SIMPLE) { veh->m_vecMoveSpeed = CVector(0.0f, 0.0f, -0.00001f); veh->m_vecTurnSpeed = CVector(0.0f, 0.0f, 0.0f); } veh->SetStatus(STATUS_PLAYER); AudioManager.PlayerJustGotInCar(); } veh->SetDriver(ped); if (!veh->bEngineOn) veh->bEngineOn = true; ped->m_nPedState = PED_DRIVING; ped->StopNonPartialAnims(); return; } if (ped->m_pVehicleAnim) ped->m_pVehicleAnim->blendDelta = -1000.0f; ped->bDoBloodyFootprints = false; if (veh->m_nAlarmState == -1) veh->m_nAlarmState = 15000; if (ped->IsPlayer()) { if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER) { if (veh->GetStatus() == STATUS_SIMPLE) { veh->m_vecMoveSpeed = CVector(0.0f, 0.0f, 0.0f); veh->m_vecTurnSpeed = CVector(0.0f, 0.0f, 0.0f); } veh->SetStatus(STATUS_PLAYER); } AudioManager.PlayerJustGotInCar(); } else if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER) { if (veh->GetStatus() == STATUS_SIMPLE) { veh->m_vecMoveSpeed = CVector(0.0f, 0.0f, 0.0f); veh->m_vecTurnSpeed = CVector(0.0f, 0.0f, 0.0f); } veh->SetStatus(STATUS_PHYSICS); } if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER) { for (int i = 0; i < veh->m_nNumMaxPassengers; ++i) { CPed *passenger = veh->pPassengers[i]; if (passenger && passenger->CharCreatedBy == RANDOM_CHAR) { passenger->SetObjective(OBJECTIVE_LEAVE_CAR, veh); #ifdef VC_PED_PORTS passenger->m_leaveCarTimer = CTimer::GetTimeInMilliseconds(); #endif } } } // This shouldn't happen at all. Passengers can't enter with PED_CARJACK. Even though they did, we shouldn't call AddPassenger in here and SetDriver in below. #if !defined VC_PED_PORTS && !defined FIX_BUGS else if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER) { if (ped->m_nPedState == PED_CARJACK) { veh->AddPassenger(ped, 0); ped->m_nPedState = PED_DRIVING; ped->RestorePreviousObjective(); ped->SetObjective(OBJECTIVE_LEAVE_CAR, veh); } else if (veh->pDriver && ped->CharCreatedBy == RANDOM_CHAR) { veh->AutoPilot.m_nCruiseSpeed = 17; } } #endif if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER || ped->m_nPedState == PED_CARJACK) { veh->SetDriver(ped); if (veh->VehicleCreatedBy == PARKED_VEHICLE) { veh->VehicleCreatedBy = RANDOM_VEHICLE; ++CCarCtrl::NumRandomCars; --CCarCtrl::NumParkedCars; } if (veh->bIsAmbulanceOnDuty) { veh->bIsAmbulanceOnDuty = false; --CCarCtrl::NumAmbulancesOnDuty; } if (veh->bIsFireTruckOnDuty) { veh->bIsFireTruckOnDuty = false; --CCarCtrl::NumFiretrucksOnDuty; } if (ped->m_nPedType == PEDTYPE_COP && veh->IsLawEnforcementVehicle()) veh->ChangeLawEnforcerState(true); if (!veh->bEngineOn) { veh->bEngineOn = true; DMAudio.PlayOneShot(ped->m_audioEntityId, SOUND_CAR_ENGINE_START, 1.0f); } if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER && ped->CharCreatedBy == RANDOM_CHAR && ped != FindPlayerPed() && ped->m_nPedType != PEDTYPE_EMERGENCY) { CCarCtrl::JoinCarWithRoadSystem(veh); veh->AutoPilot.m_nCarMission = MISSION_CRUISE; veh->AutoPilot.m_nTempAction = TEMPACT_NONE; veh->AutoPilot.m_nDrivingStyle = DRIVINGSTYLE_AVOID_CARS; veh->AutoPilot.m_nCruiseSpeed = 25; } ped->m_nPedState = PED_DRIVING; if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER) { if (ped->m_prevObjective == OBJECTIVE_RUN_TO_AREA || ped->m_prevObjective == OBJECTIVE_GOTO_CHAR_ON_FOOT || ped->m_prevObjective == OBJECTIVE_KILL_CHAR_ON_FOOT) ped->m_prevObjective = OBJECTIVE_NONE; ped->RestorePreviousObjective(); } } else if (ped->m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER) { if (veh->bIsBus) { veh->AddPassenger(ped); } else { switch (ped->m_vehEnterType) { case CAR_DOOR_RF: veh->AddPassenger(ped, 0); break; case CAR_DOOR_RR: veh->AddPassenger(ped, 2); break; case CAR_DOOR_LR: veh->AddPassenger(ped, 1); break; default: veh->AddPassenger(ped); break; } } ped->m_nPedState = PED_DRIVING; if (ped->m_prevObjective == OBJECTIVE_RUN_TO_AREA || ped->m_prevObjective == OBJECTIVE_GOTO_CHAR_ON_FOOT || ped->m_prevObjective == OBJECTIVE_KILL_CHAR_ON_FOOT) ped->m_prevObjective = OBJECTIVE_NONE; ped->RestorePreviousObjective(); #ifdef VC_PED_PORTS if(veh->pDriver && ped->CharCreatedBy == RANDOM_CHAR) veh->AutoPilot.m_nCruiseSpeed = 17; #endif } veh->m_nGettingInFlags &= ~GetCarDoorFlag(ped->m_vehEnterType); if (veh->bIsBus && !veh->m_nGettingInFlags) ((CAutomobile*)veh)->SetBusDoorTimer(1000, 1); switch (ped->m_objective) { case OBJECTIVE_KILL_CHAR_ON_FOOT: case OBJECTIVE_KILL_CHAR_ANY_MEANS: case OBJECTIVE_LEAVE_CAR: case OBJECTIVE_FOLLOW_CAR_IN_CAR: case OBJECTIVE_GOTO_AREA_ANY_MEANS: case OBJECTIVE_GOTO_AREA_ON_FOOT: case OBJECTIVE_RUN_TO_AREA: break; default: ped->SetObjective(OBJECTIVE_NONE); } if (veh->pDriver == ped) { if (veh->bLowVehicle) { ped->m_pVehicleAnim = CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_CAR_LSIT, 100.0f); } else { ped->m_pVehicleAnim = CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_CAR_SIT, 100.0f); } } else if (veh->bLowVehicle) { ped->m_pVehicleAnim = CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_CAR_SITPLO, 100.0f); } else { ped->m_pVehicleAnim = CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_CAR_SITP, 100.0f); } ped->StopNonPartialAnims(); if (veh->bIsBus) ped->bRenderPedInCar = false; // FIX: RegisterVehicleOfInterest not just registers the vehicle, but also updates register time. So remove the IsThisVehicleInteresting check. #ifndef FIX_BUGS if (ped->IsPlayer() && !CCarCtrl::IsThisVehicleInteresting(veh) && veh->VehicleCreatedBy != MISSION_VEHICLE) { #else if (ped->IsPlayer() && veh->VehicleCreatedBy != MISSION_VEHICLE) { #endif CCarCtrl::RegisterVehicleOfInterest(veh); if (!veh->bHasBeenOwnedByPlayer && veh->VehicleCreatedBy != MISSION_VEHICLE) CEventList::RegisterEvent(EVENT_STEAL_CAR, EVENT_ENTITY_VEHICLE, veh, ped, 1500); veh->bHasBeenOwnedByPlayer = true; } ped->bChangedSeat = true; } bool CPed::CanBeDeleted(void) { if (bInVehicle) return false; switch (CharCreatedBy) { case RANDOM_CHAR: return true; case MISSION_CHAR: return false; default: return true; } } void CPed::AddWeaponModel(int id) { RpAtomic *atm; if (id != -1) { #ifdef PED_SKIN if (IsClumpSkinned(GetClump())) { if (m_pWeaponModel) RemoveWeaponModel(-1); m_pWeaponModel = (RpAtomic*)CModelInfo::GetModelInfo(id)->CreateInstance(); } else #endif { atm = (RpAtomic*)CModelInfo::GetModelInfo(id)->CreateInstance(); RwFrameDestroy(RpAtomicGetFrame(atm)); RpAtomicSetFrame(atm, m_pFrames[PED_HANDR]->frame); RpClumpAddAtomic(GetClump(), atm); } m_wepModelID = id; } } static RwObject* RemoveAllModelCB(RwObject *object, void *data) { RpAtomic *atomic = (RpAtomic*)object; if (CVisibilityPlugins::GetAtomicModelInfo(atomic)) { RpClumpRemoveAtomic(RpAtomicGetClump(atomic), atomic); RpAtomicDestroy(atomic); } return object; } void CPed::RemoveWeaponModel(int modelId) { // modelId is not used!! This function just removes the current weapon. #ifdef PED_SKIN if(IsClumpSkinned(GetClump())){ if(m_pWeaponModel){ RwFrame *frm = RpAtomicGetFrame(m_pWeaponModel); RpAtomicDestroy(m_pWeaponModel); RwFrameDestroy(frm); m_pWeaponModel = nil; } }else #endif RwFrameForAllObjects(m_pFrames[PED_HANDR]->frame,RemoveAllModelCB,nil); m_wepModelID = -1; } uint32 CPed::GiveWeapon(eWeaponType weaponType, uint32 ammo) { CWeapon &weapon = GetWeapon(weaponType); if (HasWeapon(weaponType)) { if (weapon.m_nAmmoTotal + ammo > 99999) weapon.m_nAmmoTotal = 99999; else weapon.m_nAmmoTotal += ammo; weapon.Reload(); } else { weapon.Initialise(weaponType, ammo); // TODO: It seems game uses this as both weapon count and max WeaponType we have, which is ofcourse erroneous. m_maxWeaponTypeAllowed++; } if (weapon.m_eWeaponState == WEAPONSTATE_OUT_OF_AMMO) weapon.m_eWeaponState = WEAPONSTATE_READY; return weaponType; } // Some kind of VC leftover I think int CPed::GetWeaponSlot(eWeaponType weaponType) { if (HasWeapon(weaponType)) return weaponType; else return -1; } void CPed::SetCurrentWeapon(uint32 weaponType) { CWeaponInfo *weaponInfo; if (HasWeapon(weaponType)) { weaponInfo = CWeaponInfo::GetWeaponInfo(GetWeapon()->m_eWeaponType); RemoveWeaponModel(weaponInfo->m_nModelId); m_currentWeapon = weaponType; weaponInfo = CWeaponInfo::GetWeaponInfo(GetWeapon()->m_eWeaponType); AddWeaponModel(weaponInfo->m_nModelId); } } void CPed::GrantAmmo(eWeaponType weaponType, uint32 ammo) { if (HasWeapon(weaponType)) { GetWeapon(weaponType).m_nAmmoTotal += ammo; } else { GetWeapon(weaponType).Initialise(weaponType, ammo); m_maxWeaponTypeAllowed++; } } void CPed::SetAmmo(eWeaponType weaponType, uint32 ammo) { if (HasWeapon(weaponType)) { GetWeapon(weaponType).m_nAmmoTotal = ammo; } else { GetWeapon(weaponType).Initialise(weaponType, ammo); m_maxWeaponTypeAllowed++; } } void CPed::ClearWeapons(void) { CWeaponInfo *currentWeapon = CWeaponInfo::GetWeaponInfo(GetWeapon()->m_eWeaponType); RemoveWeaponModel(currentWeapon->m_nModelId); m_maxWeaponTypeAllowed = WEAPONTYPE_BASEBALLBAT; m_currentWeapon = WEAPONTYPE_UNARMED; currentWeapon = CWeaponInfo::GetWeaponInfo(GetWeapon()->m_eWeaponType); AddWeaponModel(currentWeapon->m_nModelId); for(int i = 0; i < WEAPONTYPE_TOTAL_INVENTORY_WEAPONS; i++) { CWeapon &weapon = GetWeapon(i); weapon.m_eWeaponType = WEAPONTYPE_UNARMED; weapon.m_eWeaponState = WEAPONSTATE_READY; weapon.m_nAmmoInClip = 0; weapon.m_nAmmoTotal = 0; weapon.m_nTimer = 0; } } void CPed::PreRender(void) { CShadows::StoreShadowForPed(this, CTimeCycle::m_fShadowDisplacementX[CTimeCycle::m_CurrentStoredValue], CTimeCycle::m_fShadowDisplacementY[CTimeCycle::m_CurrentStoredValue], CTimeCycle::m_fShadowFrontX[CTimeCycle::m_CurrentStoredValue], CTimeCycle::m_fShadowFrontY[CTimeCycle::m_CurrentStoredValue], CTimeCycle::m_fShadowSideX[CTimeCycle::m_CurrentStoredValue], CTimeCycle::m_fShadowSideY[CTimeCycle::m_CurrentStoredValue]); #ifdef PED_SKIN if(IsClumpSkinned(GetClump())){ UpdateRpHAnim(); if(bBodyPartJustCameOff && m_bodyPartBleeding == PED_HEAD){ // scale head to 0 if shot off RpHAnimHierarchy *hier = GetAnimHierarchyFromSkinClump(GetClump()); int32 idx = RpHAnimIDGetIndex(hier, ConvertPedNode2BoneTag(PED_HEAD)); RwMatrix *head = &RpHAnimHierarchyGetMatrixArray(hier)[idx]; RwV3d zero = { 0.0f, 0.0f, 0.0f }; RwMatrixScale(head, &zero, rwCOMBINEPRECONCAT); } } #endif if (bBodyPartJustCameOff && bIsPedDieAnimPlaying && m_bodyPartBleeding != -1 && (CTimer::GetFrameCounter() & 7) > 3) { CVector bloodDir(0.0f, 0.0f, 0.0f); CVector bloodPos(0.0f, 0.0f, 0.0f); TransformToNode(bloodPos, m_bodyPartBleeding); switch (m_bodyPartBleeding) { case PED_HEAD: bloodDir = 0.1f * GetUp(); break; case PED_UPPERARML: bloodDir = 0.04f * GetUp() - 0.04f * GetRight(); break; case PED_UPPERARMR: bloodDir = 0.04f * GetUp() - 0.04f * GetRight(); break; case PED_UPPERLEGL: bloodDir = 0.04f * GetUp() + 0.05f * GetForward(); break; case PED_UPPERLEGR: bloodDir = 0.04f * GetUp() + 0.05f * GetForward(); break; default: bloodDir = CVector(0.0f, 0.0f, 0.0f); break; } for(int i = 0; i < 4; i++) CParticle::AddParticle(PARTICLE_BLOOD_SPURT, bloodPos, bloodDir, nil, 0.0f, 0, 0, 0, 0); } if (CWeather::Rain > 0.3f && TheCamera.SoundDistUp > 15.0f) { if ((TheCamera.GetPosition() - GetPosition()).Magnitude() < 25.0f) { bool doSplashUp = true; CColModel *ourCol = CModelInfo::GetModelInfo(GetModelIndex())->GetColModel(); CVector speed = FindPlayerSpeed(); if (Abs(speed.x) <= 0.05f && Abs(speed.y) <= 0.05f) { if (!OnGround() && m_nPedState != PED_ATTACK && m_nPedState != PED_FIGHT) { if (!IsPedHeadAbovePos(0.3f) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_TIRED)) { doSplashUp = false; } } else doSplashUp = false; } else doSplashUp = false; if (doSplashUp && ourCol->numSpheres > 0) { for(int i = 0; i < ourCol->numSpheres; i++) { CColSphere *sphere = &ourCol->spheres[i]; CVector splashPos; switch (sphere->piece) { case PEDPIECE_LEFTARM: case PEDPIECE_RIGHTARM: case PEDPIECE_HEAD: splashPos = GetMatrix() * ourCol->spheres[i].center; splashPos.z += 0.7f * sphere->radius; splashPos.x += CGeneral::GetRandomNumberInRange(-0.15f, 0.15f); splashPos.y += CGeneral::GetRandomNumberInRange(-0.15f, 0.15f); CParticle::AddParticle(PARTICLE_RAIN_SPLASHUP, splashPos, CVector(0.0f, 0.0f, 0.0f), nil, 0.0f, 0, 0, CGeneral::GetRandomNumber() & 1, 0); break; default: break; } } } } } } void CPed::Render(void) { if (bInVehicle && m_nPedState != PED_EXIT_CAR && m_nPedState != PED_DRAG_FROM_CAR) { if (!bRenderPedInCar) return; float camDistSq = (TheCamera.GetPosition() - GetPosition()).MagnitudeSqr(); if (camDistSq > SQR(25.0f * TheCamera.LODDistMultiplier)) return; } CEntity::Render(); #ifdef PED_SKIN if(IsClumpSkinned(GetClump())){ renderLimb(PED_HEAD); renderLimb(PED_HANDL); renderLimb(PED_HANDR); } if(m_pWeaponModel && IsClumpSkinned(GetClump())){ RpHAnimHierarchy *hier = GetAnimHierarchyFromSkinClump(GetClump()); int idx = RpHAnimIDGetIndex(hier, m_pFrames[PED_HANDR]->nodeID); RwMatrix *mat = &RpHAnimHierarchyGetMatrixArray(hier)[idx]; RwFrame *frame = RpAtomicGetFrame(m_pWeaponModel); *RwFrameGetMatrix(frame) = *mat; RwFrameUpdateObjects(frame); RpAtomicRender(m_pWeaponModel); } #endif } void CPed::CheckAroundForPossibleCollisions(void) { CVector ourCentre, objCentre; CEntity *objects[8]; int16 maxObject; if (CTimer::GetTimeInMilliseconds() <= m_nPedStateTimer) return; GetBoundCentre(ourCentre); CWorld::FindObjectsInRange(ourCentre, 10.0f, true, &maxObject, 6, objects, false, true, false, true, false); for (int i = 0; i < maxObject; i++) { CEntity *object = objects[i]; if (bRunningToPhone) { if (gPhoneInfo.PhoneAtThisPosition(object->GetPosition())) break; } object->GetBoundCentre(objCentre); float radius = object->GetBoundRadius(); if (radius > 4.5f || radius < 1.0f) radius = 1.0f; // Developers gave up calculating Z diff. later according to asm. float diff = CVector(ourCentre - objCentre).MagnitudeSqr2D(); if (sq(radius + 1.0f) > diff) m_fRotationDest += DEGTORAD(22.5f); } } void CPed::SetIdle(void) { if (m_nPedState != PED_IDLE && m_nPedState != PED_MUG && m_nPedState != PED_FLEE_ENTITY) { #ifdef VC_PED_PORTS if (m_nPedState == PED_AIM_GUN) ClearPointGunAt(); m_nLastPedState = PED_NONE; #endif m_nPedState = PED_IDLE; SetMoveState(PEDMOVE_STILL); } if (m_nWaitState == WAITSTATE_FALSE) { m_nWaitTimer = CTimer::GetTimeInMilliseconds() + CGeneral::GetRandomNumberInRange(2000, 4000); } } void CPed::Idle(void) { CVehicle *veh = m_pMyVehicle; if (veh && veh->m_nGettingOutFlags && m_vehEnterType) { if (veh->m_nGettingOutFlags & GetCarDoorFlag(m_vehEnterType)) { if (m_objective != OBJECTIVE_KILL_CHAR_ON_FOOT) { CVector doorPos = GetPositionToOpenCarDoor(veh, m_vehEnterType); CVector doorDist = GetPosition() - doorPos; if (doorDist.MagnitudeSqr() < sq(0.5f)) { SetMoveState(PEDMOVE_WALK); return; } } } } CAnimBlendAssociation *armedIdleAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_ARMED); CAnimBlendAssociation *unarmedIdleAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_STANCE); int waitTime; if (m_nMoveState == PEDMOVE_STILL) { eWeaponType curWeapon = GetWeapon()->m_eWeaponType; if (!armedIdleAssoc || CTimer::GetTimeInMilliseconds() <= m_nWaitTimer && curWeapon != WEAPONTYPE_UNARMED && curWeapon != WEAPONTYPE_MOLOTOV && curWeapon != WEAPONTYPE_GRENADE) { if ((!GetWeapon()->IsType2Handed() || curWeapon == WEAPONTYPE_SHOTGUN) && curWeapon != WEAPONTYPE_BASEBALLBAT || !unarmedIdleAssoc || unarmedIdleAssoc->blendAmount <= 0.95f || m_nWaitState != WAITSTATE_FALSE || CTimer::GetTimeInMilliseconds() <= m_nWaitTimer) { m_moved = CVector2D(0.0f, 0.0f); return; } CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_IDLE_ARMED, 3.0f); waitTime = CGeneral::GetRandomNumberInRange(4000, 7500); } else { armedIdleAssoc->blendDelta = -2.0f; armedIdleAssoc->flags |= ASSOC_DELETEFADEDOUT; waitTime = CGeneral::GetRandomNumberInRange(3000, 8500); } m_nWaitTimer = CTimer::GetTimeInMilliseconds() + waitTime; } else { if (armedIdleAssoc) { armedIdleAssoc->blendDelta = -8.0f; armedIdleAssoc->flags |= ASSOC_DELETEFADEDOUT; m_nWaitTimer = 0; } if (!IsPlayer()) SetMoveState(PEDMOVE_STILL); } m_moved = CVector2D(0.0f, 0.0f); } void CPed::ClearPause(void) { RestorePreviousState(); } void CPed::Pause(void) { m_moved = CVector2D(0.0f, 0.0f); if (CTimer::GetTimeInMilliseconds() > m_leaveCarTimer) ClearPause(); } void CPed::SetFall(int extraTime, AnimationId animId, uint8 evenIfNotInControl) { if (!IsPedInControl() && (!evenIfNotInControl || DyingOrDead())) return; ClearLookFlag(); ClearAimFlag(); SetStoredState(); m_nPedState = PED_FALL; CAnimBlendAssociation *fallAssoc = RpAnimBlendClumpGetAssociation(GetClump(), animId); if (fallAssoc) { fallAssoc->SetCurrentTime(0.0f); fallAssoc->blendAmount = 0.0f; fallAssoc->blendDelta = 8.0f; fallAssoc->SetRun(); } else { fallAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, animId, 8.0f); } if (extraTime == -1) { m_getUpTimer = UINT32_MAX; } else if (fallAssoc) { if (IsPlayer()) { m_getUpTimer = 1000.0f * fallAssoc->hierarchy->totalLength + CTimer::GetTimeInMilliseconds() + 500.0f; } else { m_getUpTimer = 1000.0f * fallAssoc->hierarchy->totalLength + CTimer::GetTimeInMilliseconds() + extraTime + ((m_randomSeed + CTimer::GetFrameCounter()) % 1000); } } else { m_getUpTimer = extraTime + CTimer::GetTimeInMilliseconds() + 1000 + ((m_randomSeed + CTimer::GetFrameCounter()) % 1000); } bFallenDown = true; } void CPed::ClearFall(void) { SetGetUp(); } void CPed::Fall(void) { if (m_getUpTimer != UINT32_MAX && CTimer::GetTimeInMilliseconds() > m_getUpTimer #ifdef VC_PED_PORTS && bIsStanding #endif ) ClearFall(); // VC plays animations ANIM_STD_FALL_ONBACK and ANIM_STD_FALL_ONFRONT in here, which doesn't exist in III. } bool CPed::CheckIfInTheAir(void) { if (bInVehicle) return false; CVector pos = GetPosition(); CColPoint foundColPoint; CEntity *foundEntity; float startZ = pos.z - 1.54f; bool foundGround = CWorld::ProcessVerticalLine(pos, startZ, foundColPoint, foundEntity, true, true, false, true, false, false, nil); if (!foundGround && m_nPedState != PED_JUMP) { pos.z -= FEET_OFFSET; if (CWorld::TestSphereAgainstWorld(pos, 0.15f, this, true, false, false, false, false, false)) foundGround = true; } return !foundGround; } void CPed::SetInTheAir(void) { if (bIsInTheAir) return; bIsInTheAir = true; CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_FALL_GLIDE, 4.0f); if (m_nPedState == PED_ATTACK) { ClearAttack(); ClearPointGunAt(); } else if (m_nPedState == PED_FIGHT) { EndFight(ENDFIGHT_FAST); } } void CPed::InTheAir(void) { CColPoint foundCol; CEntity *foundEnt; CVector ourPos = GetPosition(); CVector bitBelow = GetPosition(); bitBelow.z -= 4.04f; if (m_vecMoveSpeed.z < 0.0f && !bIsPedDieAnimPlaying) { if (!DyingOrDead()) { if (CWorld::ProcessLineOfSight(ourPos, bitBelow, foundCol, foundEnt, true, true, false, true, false, false, false)) { if (GetPosition().z - foundCol.point.z < 1.3f #ifdef VC_PED_PORTS || bIsStanding #endif ) SetLanding(); } else { if (!RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FALL_FALL)) { if (m_vecMoveSpeed.z < -0.1f) CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_FALL_FALL, 4.0f); } } } } } void CPed::SetLanding(void) { if (DyingOrDead()) return; CAnimBlendAssociation *fallAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_FALL_FALL); CAnimBlendAssociation *landAssoc; RpAnimBlendClumpSetBlendDeltas(GetClump(), ASSOC_PARTIAL, -1000.0f); if (fallAssoc) { landAssoc = CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_FALL_COLLAPSE); DMAudio.PlayOneShot(m_audioEntityId, SOUND_FALL_COLLAPSE, 1.0f); if (IsPlayer()) Say(SOUND_PED_LAND); } else { landAssoc = CAnimManager::AddAnimation(GetClump(), ASSOCGRP_STD, ANIM_FALL_LAND); DMAudio.PlayOneShot(m_audioEntityId, SOUND_FALL_LAND, 1.0f); } landAssoc->SetFinishCallback(PedLandCB, this); bIsInTheAir = false; bIsLanding = true; } void CPed::SetGetUp(void) { if (m_nPedState == PED_GETUP && bGetUpAnimStarted) return; if (!CanSetPedState()) return; if (m_fHealth >= 1.0f || IsPedHeadAbovePos(-0.3f)) { if (bUpdateAnimHeading) { m_fRotationCur = CGeneral::LimitRadianAngle(m_fRotationCur); m_fRotationCur -= HALFPI; bUpdateAnimHeading = false; } if (m_nPedState != PED_GETUP) { SetStoredState(); m_nPedState = PED_GETUP; } CVehicle *collidingVeh = (CVehicle*)m_pCollidingEntity; CVehicle *veh = (CVehicle*)CPedPlacement::IsPositionClearOfCars(&GetPosition()); if (veh && veh->m_vehType != VEHICLE_TYPE_BIKE || collidingVeh && collidingVeh->IsVehicle() && collidingVeh->m_vehType != VEHICLE_TYPE_BIKE && ((uint8)(CTimer::GetFrameCounter() + m_randomSeed + 5) % 8 || CCollision::ProcessColModels(GetMatrix(), *GetColModel(), collidingVeh->GetMatrix(), *collidingVeh->GetColModel(), aTempPedColPts, nil, nil) > 0)) { bGetUpAnimStarted = false; if (IsPlayer()) InflictDamage(nil, WEAPONTYPE_RUNOVERBYCAR, CTimer::GetTimeStep(), PEDPIECE_TORSO, 0); else { if (!CPad::GetPad(0)->ArePlayerControlsDisabled()) return; InflictDamage(nil, WEAPONTYPE_RUNOVERBYCAR, 1000.0f, PEDPIECE_TORSO, 0); } return; } bGetUpAnimStarted = true; m_pCollidingEntity = nil; bKnockedUpIntoAir = false; CAnimBlendAssociation *animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_SPRINT); if (animAssoc) { if (RpAnimBlendClumpGetAssociation(GetClump(), ANIM_RUN)) { CAnimManager::BlendAnimation(GetClump(), m_animGroup, ANIM_RUN, 8.0f); } else { CAnimManager::BlendAnimation(GetClump(), m_animGroup, ANIM_IDLE_STANCE, 8.0f); } animAssoc->flags |= ASSOC_DELETEFADEDOUT; } if (RpAnimBlendClumpGetFirstAssociation(GetClump(), ASSOC_FRONTAL)) animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_GETUP_FRONT, 1000.0f); else animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_GETUP1, 1000.0f); animAssoc->SetFinishCallback(PedGetupCB,this); } else { m_fHealth = 0.0f; SetDie(NUM_ANIMS, 4.0f, 0.0f); } } void CPed::Mug(void) { if (m_pSeekTarget && m_pSeekTarget->IsPed()) { if (CTimer::GetTimeInMilliseconds() <= m_attackTimer - 2000) { if ((m_pSeekTarget->GetPosition() - GetPosition()).Magnitude() > 3.0f) m_wepSkills = 50; Say(SOUND_PED_MUGGING); ((CPed*)m_pSeekTarget)->Say(SOUND_PED_ROBBED); } else { SetWanderPath(CGeneral::GetRandomNumber() & 7); SetFlee(m_pSeekTarget, 20000); } } else { SetIdle(); } } void CPed::SetLookTimer(int time) { if (CTimer::GetTimeInMilliseconds() > m_lookTimer) { m_lookTimer = CTimer::GetTimeInMilliseconds() + time; } } void CPed::SetAttackTimer(uint32 time) { if (CTimer::GetTimeInMilliseconds() > m_attackTimer) m_attackTimer = Max(m_shootTimer, CTimer::GetTimeInMilliseconds()) + time; } void CPed::SetShootTimer(uint32 time) { if (CTimer::GetTimeInMilliseconds() > m_shootTimer) { m_shootTimer = CTimer::GetTimeInMilliseconds() + time; } } void CPed::ClearLook(void) { RestorePreviousState(); ClearLookFlag(); } void CPed::Look(void) { // UNUSED: This is a perfectly empty function. } bool CPed::TurnBody(void) { bool turnDone = true; if (m_pLookTarget) m_fLookDirection = CGeneral::GetRadianAngleBetweenPoints( m_pLookTarget->GetPosition().x, m_pLookTarget->GetPosition().y, GetPosition().x, GetPosition().y); float limitedLookDir = CGeneral::LimitRadianAngle(m_fLookDirection); float currentRot = m_fRotationCur; if (currentRot - PI > limitedLookDir) limitedLookDir += 2 * PI; else if (PI + currentRot < limitedLookDir) limitedLookDir -= 2 * PI; float neededTurn = currentRot - limitedLookDir; m_fRotationDest = limitedLookDir; if (Abs(neededTurn) > 0.05f) { turnDone = false; currentRot -= neededTurn * 0.2f; } m_fRotationCur = currentRot; m_fLookDirection = limitedLookDir; return turnDone; } void CPed::SetSeek(CVector pos, float distanceToCountDone) { if (!IsPedInControl() || (m_nPedState == PED_SEEK_POS && m_vecSeekPos.x == pos.x && m_vecSeekPos.y == pos.y)) return; if (GetWeapon()->m_eWeaponType == WEAPONTYPE_M16 || GetWeapon()->m_eWeaponType == WEAPONTYPE_AK47 || GetWeapon()->m_eWeaponType == WEAPONTYPE_SNIPERRIFLE || GetWeapon()->m_eWeaponType == WEAPONTYPE_ROCKETLAUNCHER || GetWeapon()->m_eWeaponType == WEAPONTYPE_SHOTGUN) { ClearPointGunAt(); } if (m_nPedState != PED_SEEK_POS) SetStoredState(); m_nPedState = PED_SEEK_POS; m_distanceToCountSeekDone = distanceToCountDone; m_vecSeekPos = pos; } void CPed::SetSeek(CEntity *seeking, float distanceToCountDone) { if (!IsPedInControl()) return; if (m_nPedState == PED_SEEK_ENTITY && m_pSeekTarget == seeking) return; if (!seeking) return; if (m_nPedState != PED_SEEK_ENTITY) SetStoredState(); m_nPedState = PED_SEEK_ENTITY; m_distanceToCountSeekDone = distanceToCountDone; m_pSeekTarget = seeking; m_pSeekTarget->RegisterReference((CEntity **) &m_pSeekTarget); SetMoveState(PEDMOVE_STILL); } void CPed::ClearSeek(void) { SetIdle(); bRunningToPhone = false; } bool CPed::Seek(void) { float distanceToCountItDone = m_distanceToCountSeekDone; eMoveState nextMove = PEDMOVE_NONE; if (m_objective != OBJECTIVE_ENTER_CAR_AS_DRIVER) { if (m_nPedState != PED_EXIT_TRAIN && m_nPedState != PED_ENTER_TRAIN && m_nPedState != PED_SEEK_IN_BOAT && m_objective != OBJECTIVE_ENTER_CAR_AS_PASSENGER && m_objective != OBJECTIVE_SOLICIT_VEHICLE && !bDuckAndCover) { if ((!m_pedInObjective || !m_pedInObjective->bInVehicle) && !((CTimer::GetFrameCounter() + (m_randomSeed % 256) + 17) & 7)) { CEntity *obstacle = CWorld::TestSphereAgainstWorld(m_vecSeekPos, 0.4f, nil, false, true, false, false, false, false); if (obstacle) { if (!obstacle->IsVehicle() || ((CVehicle*)obstacle)->m_vehType == VEHICLE_TYPE_CAR) { distanceToCountItDone = 2.5f; } else { CVehicleModelInfo *vehModel = (CVehicleModelInfo *)CModelInfo::GetModelInfo(obstacle->GetModelIndex()); float yLength = vehModel->GetColModel()->boundingBox.max.y - vehModel->GetColModel()->boundingBox.min.y; distanceToCountItDone = yLength * 0.55f; } } } } } if (!m_pSeekTarget && m_nPedState == PED_SEEK_ENTITY) ClearSeek(); float seekPosDist = (m_vecSeekPos - GetPosition()).Magnitude2D(); if (seekPosDist < 2.0f || m_objective == OBJECTIVE_GOTO_AREA_ON_FOOT) { if (m_objective == OBJECTIVE_FOLLOW_CHAR_IN_FORMATION) { if (m_pedInObjective->m_nMoveState != PEDMOVE_STILL) nextMove = m_pedInObjective->m_nMoveState; } else nextMove = PEDMOVE_WALK; } else if (m_objective != OBJECTIVE_FOLLOW_CHAR_IN_FORMATION) { if (m_objective == OBJECTIVE_KILL_CHAR_ON_FOOT || m_objective == OBJECTIVE_KILL_CHAR_ANY_MEANS || m_objective == OBJECTIVE_RUN_TO_AREA || bIsRunning) nextMove = PEDMOVE_RUN; else nextMove = PEDMOVE_WALK; } else if (seekPosDist <= 2.0f) { if (m_pedInObjective->m_nMoveState != PEDMOVE_STILL) nextMove = m_pedInObjective->m_nMoveState; } else { nextMove = PEDMOVE_RUN; } if (m_nPedState == PED_SEEK_ENTITY) { if (m_pSeekTarget->IsPed()) { if (((CPed*)m_pSeekTarget)->bInVehicle) distanceToCountItDone += 2.0f; } } if (seekPosDist >= distanceToCountItDone) { if (bIsRunning) nextMove = PEDMOVE_RUN; if (CTimer::GetTimeInMilliseconds() <= m_nPedStateTimer) { if (m_actionX != 0.0f && m_actionY != 0.0f) { m_fRotationDest = CGeneral::GetRadianAngleBetweenPoints( m_actionX, m_actionY, GetPosition().x, GetPosition().y); float neededTurn = Abs(m_fRotationDest - m_fRotationCur); if (neededTurn > PI) neededTurn = TWOPI - neededTurn; if (neededTurn > HALFPI) { if (seekPosDist >= 1.0f) { if (seekPosDist < 2.0f) { if (bIsRunning) nextMove = PEDMOVE_RUN; else nextMove = PEDMOVE_WALK; } } else { nextMove = PEDMOVE_STILL; } } CVector2D moveDist(GetPosition().x - m_actionX, GetPosition().y - m_actionY); if (moveDist.Magnitude() < 0.5f) { m_nPedStateTimer = 0; m_actionX = 0; m_actionY = 0; } } } else { m_fRotationDest = CGeneral::GetRadianAngleBetweenPoints( m_vecSeekPos.x, m_vecSeekPos.y, GetPosition().x, GetPosition().y); float neededTurn = Abs(m_fRotationDest - m_fRotationCur); if (neededTurn > PI) neededTurn = TWOPI - neededTurn; if (neededTurn > HALFPI) { if (seekPosDist >= 1.0 && neededTurn <= DEGTORAD(135.0f)) { if (seekPosDist < 2.0f) nextMove = PEDMOVE_WALK; } else { nextMove = PEDMOVE_STILL; } } } if (((m_nPedState == PED_FLEE_POS || m_nPedState == PED_FLEE_ENTITY) && m_nMoveState < nextMove) || (m_nPedState != PED_FLEE_POS && m_nPedState != PED_FLEE_ENTITY && m_objective != OBJECTIVE_GOTO_CHAR_ON_FOOT && m_nWaitState == WAITSTATE_FALSE)) { SetMoveState(nextMove); } SetMoveAnim(); return false; } if ((m_objective != OBJECTIVE_FOLLOW_CHAR_IN_FORMATION || m_pedInObjective->m_nMoveState == PEDMOVE_STILL) && m_nMoveState != PEDMOVE_STILL) { m_nPedStateTimer = 0; m_actionX = 0; m_actionY = 0; } if (m_objective == OBJECTIVE_GOTO_AREA_ON_FOOT || m_objective == OBJECTIVE_RUN_TO_AREA || m_objective == OBJECTIVE_GOTO_AREA_ANY_MEANS) { if (m_pNextPathNode) m_pNextPathNode = nil; else bScriptObjectiveCompleted = true; bUsePedNodeSeek = true; } if (SeekFollowingPath(nil)) m_nCurPathNode++; return true; } void CPed::SetFlee(CVector2D const &from, int time) { if (CTimer::GetTimeInMilliseconds() < m_nPedStateTimer || !IsPedInControl() || bKindaStayInSamePlace) return; if (m_nPedState != PED_FLEE_ENTITY) { SetStoredState(); m_nPedState = PED_FLEE_POS; SetMoveState(PEDMOVE_RUN); m_fleeFromPosX = from.x; m_fleeFromPosY = from.y; } bUsePedNodeSeek = true; m_pNextPathNode = nil; m_fleeTimer = CTimer::GetTimeInMilliseconds() + time; float angleToFace = CGeneral::GetRadianAngleBetweenPoints( GetPosition().x, GetPosition().y, from.x, from.y); m_fRotationDest = CGeneral::LimitRadianAngle(angleToFace); if (m_fRotationCur - PI > m_fRotationDest) { m_fRotationDest += 2 * PI; } else if (PI + m_fRotationCur < m_fRotationDest) { m_fRotationDest -= 2 * PI; } } void CPed::SetFlee(CEntity *fleeFrom, int time) { if (!IsPedInControl() || bKindaStayInSamePlace || !fleeFrom) return; SetStoredState(); m_nPedState = PED_FLEE_ENTITY; bUsePedNodeSeek = true; SetMoveState(PEDMOVE_RUN); m_fleeFrom = fleeFrom; m_fleeFrom->RegisterReference((CEntity **) &m_fleeFrom); if (time <= 0) m_fleeTimer = 0; else m_fleeTimer = CTimer::GetTimeInMilliseconds() + time; float angleToFace = CGeneral::GetRadianAngleBetweenPoints( GetPosition().x, GetPosition().y, fleeFrom->GetPosition().x, fleeFrom->GetPosition().y); m_fRotationDest = CGeneral::LimitRadianAngle(angleToFace); if (m_fRotationCur - PI > m_fRotationDest) { m_fRotationDest += 2 * PI; } else if (PI + m_fRotationCur < m_fRotationDest) { m_fRotationDest -= 2 * PI; } } void CPed::ClearFlee(void) { RestorePreviousState(); bUsePedNodeSeek = false; m_standardTimer = 0; m_fleeTimer = 0; } void CPed::Flee(void) { if (CTimer::GetTimeInMilliseconds() > m_fleeTimer && m_fleeTimer) { bool mayFinishFleeing = true; if (m_nPedState == PED_FLEE_ENTITY) { if ((CVector2D(GetPosition()) - ms_vec2DFleePosition).MagnitudeSqr() < sq(30.0f)) mayFinishFleeing = false; } if (mayFinishFleeing) { eMoveState moveState = m_nMoveState; ClearFlee(); if (m_objective == OBJECTIVE_FLEE_CHAR_ON_FOOT_TILL_SAFE || m_objective == OBJECTIVE_FLEE_CHAR_ON_FOOT_ALWAYS) RestorePreviousObjective(); if ((m_nPedState == PED_IDLE || m_nPedState == PED_WANDER_PATH) && CGeneral::GetRandomNumber() & 1) { SetWaitState(moveState <= PEDMOVE_WALK ? WAITSTATE_CROSS_ROAD_LOOK : WAITSTATE_FINISH_FLEE, nil); } return; } m_fleeTimer = CTimer::GetTimeInMilliseconds() + 5000; } if (bUsePedNodeSeek) { CPathNode *realLastNode = nil; uint8 nextDirection = 0; uint8 curDirectionShouldBe = 9; // means not defined yet if (m_nPedStateTimer < CTimer::GetTimeInMilliseconds() && m_collidingThingTimer < CTimer::GetTimeInMilliseconds()) { if (m_pNextPathNode && CTimer::GetTimeInMilliseconds() > m_standardTimer) { curDirectionShouldBe = CGeneral::GetNodeHeadingFromVector(GetPosition().x - ms_vec2DFleePosition.x, GetPosition().y - ms_vec2DFleePosition.y); if (m_nPathDir < curDirectionShouldBe) m_nPathDir += 8; int dirDiff = m_nPathDir - curDirectionShouldBe; if (dirDiff > 2 && dirDiff < 6) { realLastNode = nil; m_pLastPathNode = m_pNextPathNode; m_pNextPathNode = nil; } } if (m_pNextPathNode) { m_vecSeekPos = m_pNextPathNode->GetPosition(); if (m_nMoveState == PEDMOVE_RUN) bIsRunning = true; eMoveState moveState = m_nMoveState; if (Seek()) { realLastNode = m_pLastPathNode; m_pLastPathNode = m_pNextPathNode; m_pNextPathNode = nil; } bIsRunning = false; SetMoveState(moveState); } } if (!m_pNextPathNode) { if (curDirectionShouldBe == 9) { curDirectionShouldBe = CGeneral::GetNodeHeadingFromVector(GetPosition().x - ms_vec2DFleePosition.x, GetPosition().y - ms_vec2DFleePosition.y); } ThePaths.FindNextNodeWandering(PATH_PED, GetPosition(), &m_pLastPathNode, &m_pNextPathNode, curDirectionShouldBe, &nextDirection); if (curDirectionShouldBe < nextDirection) curDirectionShouldBe += 8; if (m_pNextPathNode && m_pNextPathNode != realLastNode && m_pNextPathNode != m_pLastPathNode && curDirectionShouldBe - nextDirection != 4) { m_nPathDir = nextDirection; m_standardTimer = CTimer::GetTimeInMilliseconds() + 2000; } else { bUsePedNodeSeek = false; SetMoveState(PEDMOVE_RUN); Flee(); } } return; } if ((m_nPedState == PED_FLEE_ENTITY || m_nPedState == PED_ON_FIRE) && m_nPedStateTimer < CTimer::GetTimeInMilliseconds()) { float angleToFleeFromPos = CGeneral::GetRadianAngleBetweenPoints( GetPosition().x, GetPosition().y, ms_vec2DFleePosition.x, ms_vec2DFleePosition.y); m_fRotationDest = CGeneral::LimitRadianAngle(angleToFleeFromPos); if (m_fRotationCur - PI > m_fRotationDest) m_fRotationDest += TWOPI; else if (PI + m_fRotationCur < m_fRotationDest) m_fRotationDest -= TWOPI; } if (CTimer::GetTimeInMilliseconds() & 0x20) { //CVector forwardPos = GetPosition(); CMatrix forwardMat(GetMatrix()); forwardMat.GetPosition() += Multiply3x3(forwardMat, CVector(0.0f, 4.0f, 0.0f)); CVector forwardPos = forwardMat.GetPosition(); CEntity *foundEnt; CColPoint foundCol; bool found = CWorld::ProcessVerticalLine(forwardPos, forwardMat.GetPosition().z - 100.0f, foundCol, foundEnt, 1, 0, 0, 0, 1, 0, 0); if (!found || Abs(forwardPos.z - forwardMat.GetPosition().z) > 1.0f) { m_fRotationDest += DEGTORAD(112.5f); m_nPedStateTimer = CTimer::GetTimeInMilliseconds() + 2000; } } if (CTimer::GetTimeInMilliseconds() >= m_collidingThingTimer) return; if (!m_collidingEntityWhileFleeing) return; double collidingThingPriorityMult = (double)(m_collidingThingTimer - CTimer::GetTimeInMilliseconds()) * 2.0 / 2500; if (collidingThingPriorityMult <= 1.5) { double angleToFleeEntity = CGeneral::GetRadianAngleBetweenPoints( GetPosition().x, GetPosition().y, m_collidingEntityWhileFleeing->GetPosition().x, m_collidingEntityWhileFleeing->GetPosition().y); angleToFleeEntity = CGeneral::LimitRadianAngle(angleToFleeEntity); double angleToFleeCollidingThing = CGeneral::GetRadianAngleBetweenPoints( m_vecDamageNormal.x, m_vecDamageNormal.y, 0.0f, 0.0f); angleToFleeCollidingThing = CGeneral::LimitRadianAngle(angleToFleeCollidingThing); if (angleToFleeEntity - PI > angleToFleeCollidingThing) angleToFleeCollidingThing += TWOPI; else if (PI + angleToFleeEntity < angleToFleeCollidingThing) angleToFleeCollidingThing -= TWOPI; if (collidingThingPriorityMult <= 1.0f) { // Range [0.0, 1.0] float angleToFleeBoth = (angleToFleeCollidingThing + angleToFleeEntity) * 0.5f; if (m_fRotationDest - PI > angleToFleeBoth) angleToFleeBoth += TWOPI; else if (PI + m_fRotationDest < angleToFleeBoth) angleToFleeBoth -= TWOPI; m_fRotationDest = (1.0f - collidingThingPriorityMult) * m_fRotationDest + collidingThingPriorityMult * angleToFleeBoth; } else { // Range (1.0, 1.5] double adjustedMult = (collidingThingPriorityMult - 1.0f) * 2.0f; m_fRotationDest = angleToFleeEntity * (1.0 - adjustedMult) + adjustedMult * angleToFleeCollidingThing; } } else { m_fRotationDest = CGeneral::GetRadianAngleBetweenPoints( m_vecDamageNormal.x, m_vecDamageNormal.y, 0.0f, 0.0f); m_fRotationDest = CGeneral::LimitRadianAngle(m_fRotationDest); } m_fRotationCur = CGeneral::LimitRadianAngle(m_fRotationCur); if (m_fRotationCur - PI > m_fRotationDest) m_fRotationDest += TWOPI; else if (PI + m_fRotationCur < m_fRotationDest) m_fRotationDest -= TWOPI; } // "Wander range" state is unused in game, and you can't use it without SetWanderRange anyway void CPed::WanderRange(void) { bool arrived = Seek(); if (arrived) { Idle(); if ((m_randomSeed + 3 * CTimer::GetFrameCounter()) % 1000 > 997) { CVector2D newCoords2D = m_wanderRangeBounds->GetRandomPointInRange(); SetSeek(CVector(newCoords2D.x, newCoords2D.y, GetPosition().z), 2.5f); } } } bool CPed::SetWanderPath(int8 pathStateDest) { uint8 nextPathState; if (IsPedInControl()) { if (bKindaStayInSamePlace) { SetIdle(); return false; } else { m_nPathDir = pathStateDest; if (pathStateDest == 0) pathStateDest = CGeneral::GetRandomNumberInRange(1, 7); ThePaths.FindNextNodeWandering(PATH_PED, GetPosition(), &m_pLastPathNode, &m_pNextPathNode, m_nPathDir, &nextPathState); // Circular loop until we find a node for current m_nPathDir while (!m_pNextPathNode) { m_nPathDir = (m_nPathDir+1) % 8; // We're at where we started and couldn't find any node if (m_nPathDir == pathStateDest) { ClearAll(); SetIdle(); return false; } ThePaths.FindNextNodeWandering(PATH_PED, GetPosition(), &m_pLastPathNode, &m_pNextPathNode, m_nPathDir, &nextPathState); } // We did it, save next path state and return true m_nPathDir = nextPathState; m_nPedState = PED_WANDER_PATH; SetMoveState(PEDMOVE_WALK); bIsRunning = false; return true; } } else { m_nPathDir = pathStateDest; bStartWanderPathOnFoot = true; return false; } } void CPed::WanderPath(void) { if (!m_pNextPathNode) { printf("THIS SHOULDN@T HAPPEN TOO OFTEN\n"); SetIdle(); return; } if (m_nWaitState == WAITSTATE_FALSE) { if (m_nMoveState == PEDMOVE_STILL || m_nMoveState == PEDMOVE_NONE) SetMoveState(PEDMOVE_WALK); } m_vecSeekPos = m_pNextPathNode->GetPosition(); m_vecSeekPos.z += 1.0f; // Only returns true when ped is stuck(not stopped) I think, then we should assign new direction or wait state to him. if (!Seek()) return; CPathNode *previousLastNode = m_pLastPathNode; uint8 randVal = (m_randomSeed + 3 * CTimer::GetFrameCounter()) % 100; // We don't prefer 180-degree turns in normal situations uint8 dirWeWouldntPrefer = m_nPathDir; if (dirWeWouldntPrefer <= 3) dirWeWouldntPrefer += 4; else dirWeWouldntPrefer -= 4; CPathNode *nodeWeWouldntPrefer = nil; uint8 dirToSet = 9; // means undefined uint8 dirWeWouldntPrefer2 = 9; // means undefined if (randVal <= 90) { if (randVal > 80) { m_nPathDir += 2; m_nPathDir %= 8; } } else { m_nPathDir -= 2; if (m_nPathDir < 0) m_nPathDir += 8; } m_pLastPathNode = m_pNextPathNode; ThePaths.FindNextNodeWandering(PATH_PED, GetPosition(), &m_pLastPathNode, &m_pNextPathNode, m_nPathDir, &dirToSet); uint8 tryCount = 0; // NB: SetWanderPath checks for m_nPathDir == dirToStartWith, this one checks for tryCount > 7 while (!m_pNextPathNode) { tryCount++; m_nPathDir = (m_nPathDir + 1) % 8; // We're at where we started and couldn't find any node if (tryCount > 7) { if (!nodeWeWouldntPrefer) { ClearAll(); SetIdle(); // Probably this text carried over here after copy-pasting this loop from early version of SetWanderPath. Error("Can't find valid path node, SetWanderPath, Ped.cpp"); return; } m_pNextPathNode = nodeWeWouldntPrefer; dirToSet = dirWeWouldntPrefer2; } else { ThePaths.FindNextNodeWandering(PATH_PED, GetPosition(), &m_pLastPathNode, &m_pNextPathNode, m_nPathDir, &dirToSet); if (m_pNextPathNode) { if (dirToSet == dirWeWouldntPrefer) { nodeWeWouldntPrefer = m_pNextPathNode; dirWeWouldntPrefer2 = dirToSet; m_pNextPathNode = nil; } } } } m_nPathDir = dirToSet; if (m_pLastPathNode == m_pNextPathNode) { m_pNextPathNode = previousLastNode; SetWaitState(WAITSTATE_DOUBLEBACK, nil); Say(SOUND_PED_WAIT_DOUBLEBACK); } else if (ThePaths.TestForPedTrafficLight(m_pLastPathNode, m_pNextPathNode)) { SetWaitState(WAITSTATE_TRAFFIC_LIGHTS, nil); } else if (ThePaths.TestCrossesRoad(m_pLastPathNode, m_pNextPathNode)) { SetWaitState(WAITSTATE_CROSS_ROAD, nil); } else if (m_pNextPathNode == previousLastNode) { SetWaitState(WAITSTATE_DOUBLEBACK, nil); Say(SOUND_PED_WAIT_DOUBLEBACK); } } void CPed::Avoid(void) { CPed *nearestPed; if(m_pedStats->m_temper > m_pedStats->m_fear && m_pedStats->m_temper > 50) return; if (CTimer::GetTimeInMilliseconds() > m_nPedStateTimer) { if (m_nMoveState != PEDMOVE_NONE && m_nMoveState != PEDMOVE_STILL) { nearestPed = m_nearPeds[0]; if (nearestPed && nearestPed->m_nPedState != PED_DEAD && nearestPed != m_pSeekTarget && nearestPed != m_pedInObjective) { // Check if this ped wants to avoid the nearest one if (CPedType::GetAvoid(m_nPedType) & CPedType::GetFlag(nearestPed->m_nPedType)) { // Further codes checks whether the distance between us and ped will be equal or below 1.0, if we walk up to him by 1.25 meters. // If so, we want to avoid it, so we turn our body 45 degree and look to somewhere else. // Game converts from radians to degress and back again here, doesn't make much sense CVector2D forward(-Sin(m_fRotationCur), Cos(m_fRotationCur)); forward.Normalise(); // this is kinda pointless // Move forward 1.25 meters CVector2D testPosition = CVector2D(GetPosition()) + forward*1.25f; // Get distance to ped we want to avoid CVector2D distToPed = CVector2D(nearestPed->GetPosition()) - testPosition; if (distToPed.Magnitude() <= 1.0f && OurPedCanSeeThisOne((CEntity*)nearestPed)) { m_nPedStateTimer = CTimer::GetTimeInMilliseconds() + 500 + (m_randomSeed + 3 * CTimer::GetFrameCounter()) % 1000 / 5; m_fRotationDest += DEGTORAD(45.0f); if (!bIsLooking) { SetLookFlag(nearestPed, false); SetLookTimer(CGeneral::GetRandomNumberInRange(500, 800)); } } } } } } } bool CPed::SeekFollowingPath(CVector *unused) { return m_nCurPathNode <= m_nPathNodes && m_nPathNodes; } bool CPed::SetFollowPath(CVector dest) { if (m_nPedState == PED_FOLLOW_PATH) return false; if (FindPlayerPed() != this) return false; if ((dest - GetPosition()).Magnitude() <= 2.0f) return false; CVector pointPoses[7]; int16 pointsFound; CPedPath::CalcPedRoute(0, GetPosition(), dest, pointPoses, &pointsFound, 7); for(int i = 0; i < pointsFound; i++) { m_stPathNodeStates[i].x = pointPoses[i].x; m_stPathNodeStates[i].y = pointPoses[i].y; } m_nCurPathNode = 0; m_nPathNodes = pointsFound; if (m_nPathNodes < 1) return false; SetStoredState(); m_nPedState = PED_FOLLOW_PATH; SetMoveState(PEDMOVE_WALK); return true; } void CPed::FollowPath(void) { m_vecSeekPos.x = m_stPathNodeStates[m_nCurPathNode].x; m_vecSeekPos.y = m_stPathNodeStates[m_nCurPathNode].y; m_vecSeekPos.z = GetPosition().z; // Mysterious code /* int v4 = 0; int maxNodeIndex = m_nPathNodes - 1; if (maxNodeIndex > 0) { if (maxNodeIndex > 8) { while (v4 < maxNodeIndex - 8) v4 += 8; } while (v4 < maxNodeIndex) v4++; } */ if (Seek()) { m_nCurPathNode++; if (m_nCurPathNode == m_nPathNodes) RestorePreviousState(); } } void CPed::SetEvasiveStep(CEntity *reason, uint8 animType) { AnimationId stepAnim; if (m_nPedState == PED_STEP_AWAY || !IsPedInControl() || ((IsPlayer() || !bRespondsToThreats) && animType == 0)) return; float angleToFace = CGeneral::GetRadianAngleBetweenPoints( reason->GetPosition().x, reason->GetPosition().y, GetPosition().x, GetPosition().y); angleToFace = CGeneral::LimitRadianAngle(angleToFace); m_fRotationCur = CGeneral::LimitRadianAngle(m_fRotationCur); float neededTurn = Abs(angleToFace - m_fRotationCur); bool vehPressedHorn = false; if (neededTurn > PI) neededTurn = TWOPI - neededTurn; CVehicle *veh = (CVehicle*)reason; if (reason->IsVehicle() && veh->m_vehType == VEHICLE_TYPE_CAR) { if (veh->m_nCarHornTimer != 0) { vehPressedHorn = true; if (!IsPlayer()) animType = 1; } } if (neededTurn <= DEGTORAD(90.0f) || veh->GetModelIndex() == MI_RCBANDIT || vehPressedHorn || animType != 0) { SetLookFlag(veh, true); if ((CGeneral::GetRandomNumber() & 1) && veh->GetModelIndex() != MI_RCBANDIT && animType == 0) { stepAnim = ANIM_IDLE_TAXI; } else { float vehDirection = CGeneral::GetRadianAngleBetweenPoints( veh->m_vecMoveSpeed.x, veh->m_vecMoveSpeed.y, 0.0f, 0.0f); // Let's turn our back to the "reason" angleToFace += PI; if (angleToFace > PI) angleToFace -= TWOPI; // We don't want to run towards car's direction float dangerZone = angleToFace - vehDirection; dangerZone = CGeneral::LimitRadianAngle(dangerZone); // So, add or subtract 90deg (jump to left/right) according to that if (dangerZone > 0.0f) angleToFace = vehDirection - HALFPI; else angleToFace = vehDirection + HALFPI; stepAnim = NUM_ANIMS; if (animType == 0 || animType == 1) stepAnim = ANIM_EV_STEP; else if (animType == 2) stepAnim = ANIM_HANDSCOWER; } if (!RpAnimBlendClumpGetAssociation(GetClump(), stepAnim)) { CAnimBlendAssociation *stepAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, stepAnim, 8.0f); stepAssoc->flags &= ~ASSOC_DELETEFADEDOUT; stepAssoc->SetFinishCallback(PedEvadeCB, this); if (animType == 0) Say(SOUND_PED_EVADE); m_fRotationCur = CGeneral::LimitRadianAngle(angleToFace); ClearAimFlag(); SetStoredState(); m_nPedState = PED_STEP_AWAY; } } } void CPed::SetEvasiveDive(CPhysical *reason, uint8 onlyRandomJump) { if (!IsPedInControl() || !bRespondsToThreats) return; CAnimBlendAssociation *animAssoc; float angleToFace, neededTurn; bool handsUp = false; angleToFace = m_fRotationCur; CVehicle *veh = (CVehicle*) reason; if (reason->IsVehicle() && veh->m_vehType == VEHICLE_TYPE_CAR && veh->m_nCarHornTimer != 0 && !IsPlayer()) { onlyRandomJump = true; } if (onlyRandomJump) { if (reason) { // Simple version of my bug fix below. Doesn't calculate "danger zone", selects jump direction randomly. // Also doesn't include random hands up, sound etc. Only used on player ped and peds running from gun shots. float vehDirection = CGeneral::GetRadianAngleBetweenPoints( veh->m_vecMoveSpeed.x, veh->m_vecMoveSpeed.y, 0.0f, 0.0f); angleToFace = (CGeneral::GetRandomNumber() & 1) * PI + (-0.5f*PI) + vehDirection; angleToFace = CGeneral::LimitRadianAngle(angleToFace); } } else { if (IsPlayer()) { ((CPlayerPed*)this)->m_nEvadeAmount = 5; ((CPlayerPed*)this)->m_pEvadingFrom = reason; reason->RegisterReference((CEntity**) &((CPlayerPed*)this)->m_pEvadingFrom); return; } angleToFace = CGeneral::GetRadianAngleBetweenPoints( reason->GetPosition().x, reason->GetPosition().y, GetPosition().x, GetPosition().y); angleToFace = CGeneral::LimitRadianAngle(angleToFace); m_fRotationCur = CGeneral::LimitRadianAngle(m_fRotationCur); // FIX: Peds no more dive into cars. Taken from SetEvasiveStep, last if statement inverted #ifdef FIX_BUGS float vehDirection = CGeneral::GetRadianAngleBetweenPoints( veh->m_vecMoveSpeed.x, veh->m_vecMoveSpeed.y, 0.0f, 0.0f); // Let's turn our back to the "reason" angleToFace += PI; if (angleToFace > PI) angleToFace -= 2 * PI; // We don't want to dive towards car's direction float dangerZone = angleToFace - vehDirection; dangerZone = CGeneral::LimitRadianAngle(dangerZone); // So, add or subtract 90deg (jump to left/right) according to that if (dangerZone > 0.0f) angleToFace = 0.5f * PI + vehDirection; else angleToFace = vehDirection - 0.5f * PI; #endif neededTurn = Abs(angleToFace - m_fRotationCur); if (neededTurn > PI) neededTurn = 2 * PI - neededTurn; if (neededTurn <= 0.5f*PI) { if (CGeneral::GetRandomNumber() & 1) handsUp = true; } else { if (CGeneral::GetRandomNumber() & 7) return; } Say(SOUND_PED_EVADE); } if (handsUp || !IsPlayer() && m_pedStats->m_flags & STAT_NO_DIVE) { m_fRotationCur = angleToFace; ClearLookFlag(); ClearAimFlag(); SetLookFlag(reason, true); animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_HANDSUP); if (animAssoc) return; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_HANDSUP, 8.0f); animAssoc->flags &= ~ASSOC_DELETEFADEDOUT; animAssoc->SetFinishCallback(PedEvadeCB, this); SetStoredState(); m_nPedState = PED_STEP_AWAY; } else { m_fRotationCur = angleToFace; ClearLookFlag(); ClearAimFlag(); SetStoredState(); m_nPedState = PED_DIVE_AWAY; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_EV_DIVE, 8.0f); animAssoc->SetFinishCallback(PedEvadeCB, this); } if (reason->IsVehicle() && m_nPedType == PEDTYPE_COP) { if (veh->pDriver && veh->pDriver->IsPlayer()) { CWanted *wanted = FindPlayerPed()->m_pWanted; wanted->RegisterCrime_Immediately(CRIME_RECKLESS_DRIVING, GetPosition(), (uintptr)this, false); wanted->RegisterCrime_Immediately(CRIME_SPEEDING, GetPosition(), (uintptr)this, false); } } #ifdef PEDS_REPORT_CRIMES_ON_PHONE else if (reason->IsVehicle()) { if (veh->pDriver && veh->pDriver->IsPlayer()) { CWanted* wanted = FindPlayerPed()->m_pWanted; wanted->RegisterCrime(CRIME_RECKLESS_DRIVING, GetPosition(), (uintptr)this, false); } } #endif } void CPed::PedEvadeCB(CAnimBlendAssociation* animAssoc, void* arg) { CPed* ped = (CPed*)arg; if (!animAssoc) { ped->ClearLookFlag(); if (ped->m_nPedState == PED_DIVE_AWAY || ped->m_nPedState == PED_STEP_AWAY) ped->RestorePreviousState(); } else if (animAssoc->animId == ANIM_EV_DIVE) { ped->bUpdateAnimHeading = true; ped->ClearLookFlag(); if (ped->m_nPedState == PED_DIVE_AWAY) { ped->m_getUpTimer = CTimer::GetTimeInMilliseconds() + 1; ped->m_nPedState = PED_FALL; } animAssoc->flags &= ~ASSOC_FADEOUTWHENDONE; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } else if (animAssoc->flags & ASSOC_FADEOUTWHENDONE) { ped->ClearLookFlag(); if (ped->m_nPedState == PED_DIVE_AWAY || ped->m_nPedState == PED_STEP_AWAY) ped->RestorePreviousState(); } else if (ped->m_nPedState != PED_ARRESTED) { animAssoc->flags |= ASSOC_DELETEFADEDOUT; if (animAssoc->blendDelta >= 0.0f) animAssoc->blendDelta = -4.0f; ped->ClearLookFlag(); if (ped->m_nPedState == PED_DIVE_AWAY || ped->m_nPedState == PED_STEP_AWAY) { ped->RestorePreviousState(); } } } void CPed::SetDie(AnimationId animId, float delta, float speed) { CPlayerPed *player = FindPlayerPed(); if (player == this) { if (!player->m_bCanBeDamaged) return; } m_threatEntity = nil; if (DyingOrDead()) return; if (m_nPedState == PED_FALL || m_nPedState == PED_GETUP) delta *= 0.5f; SetStoredState(); ClearAll(); m_fHealth = 0.0f; if (m_nPedState == PED_DRIVING) { if (!IsPlayer()) FlagToDestroyWhenNextProcessed(); } else if (bInVehicle) { if (m_pVehicleAnim) m_pVehicleAnim->blendDelta = -1000.0f; } else if (EnteringCar()) { QuitEnteringCar(); } m_nPedState = PED_DIE; if (animId == NUM_ANIMS) { bIsPedDieAnimPlaying = false; } else { CAnimBlendAssociation *dieAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, animId, delta); if (speed > 0.0f) dieAssoc->speed = speed; dieAssoc->flags &= ~ASSOC_FADEOUTWHENDONE; if (dieAssoc->IsRunning()) { dieAssoc->SetFinishCallback(FinishDieAnimCB, this); bIsPedDieAnimPlaying = true; } } Say(SOUND_PED_DEATH); if (m_nLastPedState == PED_ENTER_CAR || m_nLastPedState == PED_CARJACK) QuitEnteringCar(); if (!bInVehicle) StopNonPartialAnims(); m_bloodyFootprintCountOrDeathTime = CTimer::GetTimeInMilliseconds(); } void CPed::FinishDieAnimCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; if (ped->bIsPedDieAnimPlaying) ped->bIsPedDieAnimPlaying = false; } void CPed::SetDead(void) { bUsesCollision = false; m_fHealth = 0.0f; if (m_nPedState == PED_DRIVING) bIsVisible = false; m_nPedState = PED_DEAD; m_pVehicleAnim = nil; m_pCollidingEntity = nil; CWeaponInfo *weapon = CWeaponInfo::GetWeaponInfo(GetWeapon()->m_eWeaponType); RemoveWeaponModel(weapon->m_nModelId); m_currentWeapon = WEAPONTYPE_UNARMED; CEventList::RegisterEvent(EVENT_INJURED_PED, EVENT_ENTITY_PED, this, nil, 250); if (this != FindPlayerPed()) { CreateDeadPedWeaponPickups(); CreateDeadPedMoney(); } m_bloodyFootprintCountOrDeathTime = CTimer::GetTimeInMilliseconds(); m_deadBleeding = false; bDoBloodyFootprints = false; bVehExitWillBeInstant = false; CEventList::RegisterEvent(EVENT_DEAD_PED, EVENT_ENTITY_PED, this, nil, 1000); } void CPed::Die(void) { // UNUSED: This is a perfectly empty function. } void CPed::SetChat(CEntity *chatWith, uint32 time) { if(m_nPedState != PED_CHAT) SetStoredState(); m_nPedState = PED_CHAT; SetMoveState(PEDMOVE_STILL); #if defined VC_PED_PORTS || defined FIX_BUGS m_lookTimer = 0; #endif SetLookFlag(chatWith, true); m_standardTimer = CTimer::GetTimeInMilliseconds() + time; m_lookTimer = CTimer::GetTimeInMilliseconds() + 3000; } void CPed::Chat(void) { // We're already looking to our partner if (bIsLooking && TurnBody()) ClearLookFlag(); if (!m_pLookTarget || !m_pLookTarget->IsPed()) { ClearChat(); return; } CPed *partner = (CPed*) m_pLookTarget; if (partner->m_nPedState != PED_CHAT) { ClearChat(); if (partner->m_pedInObjective) { if (partner->m_objective == OBJECTIVE_KILL_CHAR_ON_FOOT || partner->m_objective == OBJECTIVE_FLEE_CHAR_ON_FOOT_TILL_SAFE) ReactToAttack(partner->m_pedInObjective); } return; } if (bIsTalking) { if (CGeneral::GetRandomNumber() < 512) { CAnimBlendAssociation *chatAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_CHAT); if (chatAssoc) { chatAssoc->blendDelta = -4.0f; chatAssoc->flags |= ASSOC_DELETEFADEDOUT; } bIsTalking = false; } else Say(SOUND_PED_CHAT); } else { if (CGeneral::GetRandomNumber() < 20 && !RpAnimBlendClumpGetFirstAssociation(GetClump(), ASSOC_IDLE)) { CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_XPRESS_SCRATCH, 4.0f); } if (!bIsTalking && !RpAnimBlendClumpGetFirstAssociation(GetClump(), ASSOC_IDLE)) { CAnimBlendAssociation *chatAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_IDLE_CHAT, 4.0f); float chatTime = CGeneral::GetRandomNumberInRange(0.0f, 3.0f); chatAssoc->SetCurrentTime(chatTime); bIsTalking = true; Say(SOUND_PED_CHAT); } } if (m_standardTimer && CTimer::GetTimeInMilliseconds() > m_standardTimer) { ClearChat(); m_standardTimer = CTimer::GetTimeInMilliseconds() + 30000; } } void CPed::ClearChat(void) { CAnimBlendAssociation *animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_CHAT); if (animAssoc) { animAssoc->blendDelta = -8.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } bIsTalking = false; ClearLookFlag(); RestorePreviousState(); } #ifdef PEDS_REPORT_CRIMES_ON_PHONE void ReportPhonePickUpCB(CAnimBlendAssociation* assoc, void* arg) { CPed* ped = (CPed*)arg; ped->m_nMoveState = PEDMOVE_STILL; CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_IDLE_STANCE, 8.0f); if (assoc->blendAmount > 0.5f && ped) { CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_PHONE_TALK, 8.0f); } } void ReportPhonePutDownCB(CAnimBlendAssociation* assoc, void* arg) { assoc->flags |= ASSOC_DELETEFADEDOUT; assoc->blendDelta = -1000.0f; CPed* ped = (CPed*)arg; if (ped->m_phoneId != -1 && crimeReporters[ped->m_phoneId] == ped) { crimeReporters[ped->m_phoneId] = nil; gPhoneInfo.m_aPhones[ped->m_phoneId].m_nState = PHONE_STATE_FREE; ped->m_phoneId = -1; } if (assoc->blendAmount > 0.5f) ped->bUpdateAnimHeading = true; ped->SetWanderPath(CGeneral::GetRandomNumber() & 7); } #endif bool CPed::FacePhone(void) { // This function was broken since it's left unused early in development. #ifdef PEDS_REPORT_CRIMES_ON_PHONE float phoneDir = CGeneral::GetRadianAngleBetweenPoints( gPhoneInfo.m_aPhones[m_phoneId].m_vecPos.x, gPhoneInfo.m_aPhones[m_phoneId].m_vecPos.y, GetPosition().x, GetPosition().y); if (m_facePhoneStart) { m_lookTimer = 0; SetLookFlag(phoneDir, true); m_lookTimer = CTimer::GetTimeInMilliseconds() + 3000; m_facePhoneStart = false; } if (bIsLooking && TurnBody()) { ClearLookFlag(); SetIdle(); m_phoneTalkTimer = CTimer::GetTimeInMilliseconds() + 10000; CAnimBlendAssociation* assoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_PHONE_IN, 4.0f); assoc->SetFinishCallback(ReportPhonePickUpCB, this); return true; } return false; #else float currentRot = RADTODEG(m_fRotationCur); float phoneDir = CGeneral::GetRadianAngleBetweenPoints( gPhoneInfo.m_aPhones[m_phoneId].m_vecPos.x, gPhoneInfo.m_aPhones[m_phoneId].m_vecPos.y, GetPosition().x, GetPosition().y); SetLookFlag(phoneDir, false); phoneDir = CGeneral::LimitAngle(phoneDir); m_moved = CVector2D(0.0f, 0.0f); if (currentRot - 180.0f > phoneDir) phoneDir += 2 * 180.0f; else if (180.0f + currentRot < phoneDir) phoneDir -= 2 * 180.0f; float neededTurn = currentRot - phoneDir; if (Abs(neededTurn) <= 0.75f) { SetIdle(); ClearLookFlag(); m_phoneTalkTimer = CTimer::GetTimeInMilliseconds() + 10000; return true; } else { m_fRotationCur = DEGTORAD(currentRot - neededTurn * 0.2f); return false; } #endif } bool CPed::MakePhonecall(void) { #ifdef PEDS_REPORT_CRIMES_ON_PHONE if (!IsPlayer() && CTimer::GetTimeInMilliseconds() > m_phoneTalkTimer - 7000 && bRunningToPhone) { FindPlayerPed()->m_pWanted->RegisterCrime_Immediately(m_crimeToReportOnPhone, GetPosition(), (m_crimeToReportOnPhone == CRIME_POSSESSION_GUN ? (uintptr)m_threatEntity : (uintptr)m_victimOfPlayerCrime), false); if (m_crimeToReportOnPhone != CRIME_POSSESSION_GUN) FindPlayerPed()->m_pWanted->SetWantedLevelNoDrop(1); bRunningToPhone = false; } #endif if (CTimer::GetTimeInMilliseconds() <= m_phoneTalkTimer) return false; #ifdef PEDS_REPORT_CRIMES_ON_PHONE CAnimBlendAssociation* talkAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_PHONE_TALK); if (talkAssoc && talkAssoc->blendAmount > 0.5f) { CAnimBlendAssociation* endAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_PHONE_OUT, 8.0f); endAssoc->flags &= ~ASSOC_DELETEFADEDOUT; endAssoc->SetFinishCallback(ReportPhonePutDownCB, this); } #endif SetIdle(); gPhoneInfo.m_aPhones[m_phoneId].m_nState = PHONE_STATE_FREE; #ifndef PEDS_REPORT_CRIMES_ON_PHONE m_phoneId = -1; #endif // Because SetWanderPath is now done async in ReportPhonePutDownCB #ifdef PEDS_REPORT_CRIMES_ON_PHONE return false; #else return true; #endif } void CPed::Teleport(CVector pos) { CWorld::Remove(this); SetPosition(pos); bIsStanding = false; m_nPedStateTimer = 0; m_actionX = 0.0f; m_actionY = 0.0f; m_pDamageEntity = nil; CWorld::Add(this); } void CPed::SetSeekCar(CVehicle *car, uint32 doorNode) { if (m_nPedState == PED_SEEK_CAR) return; #ifdef VC_PED_PORTS if (!CanSetPedState() || m_nPedState == PED_DRIVING) return; #endif SetStoredState(); m_pSeekTarget = car; m_pSeekTarget->RegisterReference((CEntity**) &m_pSeekTarget); m_carInObjective = car; m_carInObjective->RegisterReference((CEntity**) &m_carInObjective); m_pMyVehicle = car; m_pMyVehicle->RegisterReference((CEntity**) &m_pMyVehicle); // m_pSeekTarget->RegisterReference((CEntity**) &m_pSeekTarget); m_vehEnterType = doorNode; m_distanceToCountSeekDone = 0.5f; m_nPedState = PED_SEEK_CAR; } void CPed::SeekCar(void) { CVehicle *vehToSeek = m_carInObjective; CVector dest(0.0f, 0.0f, 0.0f); if (!vehToSeek) { RestorePreviousState(); return; } if (m_objective != OBJECTIVE_ENTER_CAR_AS_PASSENGER) { if (m_vehEnterType && m_objective != OBJECTIVE_ENTER_CAR_AS_DRIVER) { if (IsRoomToBeCarJacked()) { dest = GetPositionToOpenCarDoor(vehToSeek, m_vehEnterType); } else if (m_nPedType == PEDTYPE_COP) { dest = GetPositionToOpenCarDoor(vehToSeek, CAR_DOOR_RF); } else { SetMoveState(PEDMOVE_STILL); } } else GetNearestDoor(vehToSeek, dest); } else { if (m_hitRecoverTimer > CTimer::GetTimeInMilliseconds()) { SetMoveState(PEDMOVE_STILL); return; } if (vehToSeek->GetModelIndex() == MI_COACH) { GetNearestDoor(vehToSeek, dest); } else { if (vehToSeek->IsTrain()) { if (vehToSeek->GetStatus() != STATUS_TRAIN_NOT_MOVING) { RestorePreviousObjective(); RestorePreviousState(); return; } if (!GetNearestTrainDoor(vehToSeek, dest)) { RestorePreviousObjective(); RestorePreviousState(); return; } } else { if (!GetNearestPassengerDoor(vehToSeek, dest)) { if (vehToSeek->m_nNumPassengers == vehToSeek->m_nNumMaxPassengers) { RestorePreviousObjective(); RestorePreviousState(); } else { SetMoveState(PEDMOVE_STILL); } bVehEnterDoorIsBlocked = true; return; } bVehEnterDoorIsBlocked = false; } } } if (dest.x == 0.0f && dest.y == 0.0f) { #ifdef FIX_BUGS if ((!IsPlayer() && CharCreatedBy != MISSION_CHAR) || vehToSeek->VehicleCreatedBy != MISSION_VEHICLE || vehToSeek->pDriver || !vehToSeek->CanPedOpenLocks(this)) { #else if ((!IsPlayer() && CharCreatedBy != MISSION_CHAR) || vehToSeek->VehicleCreatedBy != MISSION_VEHICLE || vehToSeek->pDriver) { #endif RestorePreviousState(); if (IsPlayer()) { ClearObjective(); } else if (CharCreatedBy == RANDOM_CHAR) { m_hitRecoverTimer = CTimer::GetTimeInMilliseconds() + 30000; } SetMoveState(PEDMOVE_STILL); TheCamera.ClearPlayerWeaponMode(); CCarCtrl::RemoveFromInterestingVehicleList(vehToSeek); return; } dest = vehToSeek->GetPosition(); if (bCollidedWithMyVehicle) { WarpPedIntoCar(m_pMyVehicle); return; } } bool foundBetterPosToSeek = PossiblyFindBetterPosToSeekCar(&dest, vehToSeek); m_vecSeekPos = dest; float distToDestSqr = (m_vecSeekPos - GetPosition()).MagnitudeSqr(); #ifndef VC_PED_PORTS if (bIsRunning) SetMoveState(PEDMOVE_RUN); #else if (bIsRunning || vehToSeek->pDriver && distToDestSqr > sq(2.0f) && (Abs(vehToSeek->m_vecMoveSpeed.x) > 0.01f || Abs(vehToSeek->m_vecMoveSpeed.y) > 0.01f)) SetMoveState(PEDMOVE_RUN); #endif else if (distToDestSqr < sq(2.0f)) SetMoveState(PEDMOVE_WALK); if (distToDestSqr >= 1.0f) bCanPedEnterSeekedCar = false; else if (2.0f * vehToSeek->GetColModel()->boundingBox.max.x > distToDestSqr) bCanPedEnterSeekedCar = true; if (vehToSeek->m_nGettingInFlags & GetCarDoorFlag(m_vehEnterType)) bVehEnterDoorIsBlocked = true; else bVehEnterDoorIsBlocked = false; // Arrived to the car if (Seek()) { if (!foundBetterPosToSeek) { if (1.5f + GetPosition().z > dest.z && GetPosition().z - 0.5f < dest.z) { if (vehToSeek->IsTrain()) { SetEnterTrain(vehToSeek, m_vehEnterType); } else { m_fRotationCur = m_fRotationDest; if (!bVehEnterDoorIsBlocked) { vehToSeek->SetIsStatic(false); if (m_objective == OBJECTIVE_SOLICIT_VEHICLE) { SetSolicit(1000); } else if (m_objective == OBJECTIVE_BUY_ICE_CREAM) { SetBuyIceCream(); } else if (vehToSeek->m_nNumGettingIn < vehToSeek->m_nNumMaxPassengers + 1 && vehToSeek->CanPedEnterCar()) { switch (vehToSeek->GetStatus()) { case STATUS_PLAYER: case STATUS_SIMPLE: case STATUS_PHYSICS: case STATUS_PLAYER_DISABLED: if (!vehToSeek->bIsBus && (!m_leader || m_leader != vehToSeek->pDriver) && (m_vehEnterType == CAR_DOOR_LF && vehToSeek->pDriver || m_vehEnterType == CAR_DOOR_RF && vehToSeek->pPassengers[0] || m_vehEnterType == CAR_DOOR_LR && vehToSeek->pPassengers[1] || m_vehEnterType == CAR_DOOR_RR && vehToSeek->pPassengers[2])) { SetCarJack(vehToSeek); if (m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER && m_vehEnterType != CAR_DOOR_LF) vehToSeek->pDriver->bFleeAfterExitingCar = true; } else { SetEnterCar(vehToSeek, m_vehEnterType); } break; case STATUS_ABANDONED: if (m_vehEnterType == CAR_DOOR_RF && vehToSeek->pPassengers[0]) { if (vehToSeek->pPassengers[0]->bDontDragMeOutCar) { if (IsPlayer()) SetEnterCar(vehToSeek, m_vehEnterType); } else { SetCarJack(vehToSeek); } } else { SetEnterCar(vehToSeek, m_vehEnterType); } break; case STATUS_WRECKED: SetIdle(); break; default: return; } } else { RestorePreviousState(); } } else { SetMoveState(PEDMOVE_STILL); } } } } } } bool CPed::CheckForExplosions(CVector2D &area) { int event = 0; if (CEventList::FindClosestEvent(EVENT_EXPLOSION, GetPosition(), &event)) { area.x = gaEvent[event].posn.x; area.y = gaEvent[event].posn.y; CEntity *actualEntity = nil; switch (gaEvent[event].entityType) { case EVENT_ENTITY_PED: actualEntity = CPools::GetPed(gaEvent[event].entityRef); break; case EVENT_ENTITY_VEHICLE: actualEntity = CPools::GetVehicle(gaEvent[event].entityRef); break; case EVENT_ENTITY_OBJECT: actualEntity = CPools::GetObject(gaEvent[event].entityRef); break; default: break; } if (actualEntity) { m_pEventEntity = actualEntity; m_pEventEntity->RegisterReference((CEntity **) &m_pEventEntity); bGonnaInvestigateEvent = true; } else bGonnaInvestigateEvent = false; CEventList::ClearEvent(event); return true; } else if (CEventList::FindClosestEvent(EVENT_FIRE, GetPosition(), &event)) { area.x = gaEvent[event].posn.x; area.y = gaEvent[event].posn.y; CEventList::ClearEvent(event); bGonnaInvestigateEvent = false; return true; } bGonnaInvestigateEvent = false; return false; } CPed * CPed::CheckForGunShots(void) { int event; if (CEventList::FindClosestEvent(EVENT_GUNSHOT, GetPosition(), &event)) { if (gaEvent[event].entityType == EVENT_ENTITY_PED) { // Probably due to we don't want peds to go gunshot area? (same on VC) bGonnaInvestigateEvent = false; return CPools::GetPed(gaEvent[event].entityRef); } } bGonnaInvestigateEvent = false; return nil; } CPed * CPed::CheckForDeadPeds(void) { int event; if (CEventList::FindClosestEvent(EVENT_DEAD_PED, GetPosition(), &event)) { int pedHandle = gaEvent[event].entityRef; if (pedHandle && gaEvent[event].entityType == EVENT_ENTITY_PED) { bGonnaInvestigateEvent = true; return CPools::GetPed(pedHandle); } } bGonnaInvestigateEvent = false; return nil; } bool CPed::IsPlayer(void) const { return m_nPedType == PEDTYPE_PLAYER1 || m_nPedType == PEDTYPE_PLAYER2 || m_nPedType == PEDTYPE_PLAYER3 || m_nPedType == PEDTYPE_PLAYER4; } bool CPed::IsGangMember(void) const { return m_nPedType >= PEDTYPE_GANG1 && m_nPedType <= PEDTYPE_GANG9; } bool CPed::IsPointerValid(void) { int pedIndex = CPools::GetPedPool()->GetIndex(this) >> 8; if (pedIndex < 0 || pedIndex >= NUMPEDS) return false; if (m_entryInfoList.first || FindPlayerPed() == this) return true; return false; } void CPed::SetPedPositionInCar(void) { if (CReplay::IsPlayingBack()) return; if (bChangedSeat) { bool notYet = false; if (RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_GETIN_LHS) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_GETIN_LOW_LHS) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_CLOSEDOOR_LHS) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_CLOSEDOOR_LOW_LHS) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_SHUFFLE_RHS) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_LSHUFFLE_RHS) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_VAN_CLOSE_L) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_VAN_CLOSE) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_VAN_GETIN_L) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_VAN_GETIN) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_COACH_IN_L) || RpAnimBlendClumpGetAssociation(GetClump(), ANIM_COACH_IN_R)) { notYet = true; } if (notYet) { LineUpPedWithCar(LINE_UP_TO_CAR_START); bChangedSeat = false; return; } } CVehicleModelInfo *vehModel = (CVehicleModelInfo *)CModelInfo::GetModelInfo(m_pMyVehicle->GetModelIndex()); CMatrix newMat(m_pMyVehicle->GetMatrix()); CVector seatPos; if (m_pMyVehicle->pDriver == this) { seatPos = vehModel->GetFrontSeatPosn(); if (!m_pMyVehicle->IsBoat() && m_pMyVehicle->m_vehType != VEHICLE_TYPE_BIKE) seatPos.x = -seatPos.x; } else if (m_pMyVehicle->pPassengers[0] == this) { seatPos = vehModel->GetFrontSeatPosn(); } else if (m_pMyVehicle->pPassengers[1] == this) { seatPos = vehModel->m_positions[CAR_POS_BACKSEAT]; seatPos.x = -seatPos.x; } else { if (m_pMyVehicle->pPassengers[2] == this) { seatPos = vehModel->m_positions[CAR_POS_BACKSEAT]; } else { seatPos = vehModel->GetFrontSeatPosn(); } } newMat.GetPosition() += Multiply3x3(newMat, seatPos); // Already done below (SetTranslate(0.0f, 0.0f, 0.0f)) // tempMat.SetUnity(); // Rear seats on vans don't face to front, so rotate them HALFPI. if (m_pMyVehicle->bIsVan) { CMatrix tempMat; if (m_pMyVehicle->pPassengers[1] == this) { m_fRotationCur = m_pMyVehicle->GetForward().Heading() - HALFPI; tempMat.SetTranslate(0.0f, 0.0f, 0.0f); tempMat.RotateZ(-HALFPI); newMat = newMat * tempMat; } else if (m_pMyVehicle->pPassengers[2] == this) { m_fRotationCur = m_pMyVehicle->GetForward().Heading() + HALFPI; tempMat.SetTranslate(0.0f, 0.0f, 0.0f); tempMat.RotateZ(HALFPI); newMat = newMat * tempMat; } else { m_fRotationCur = m_pMyVehicle->GetForward().Heading(); } } else { m_fRotationCur = m_pMyVehicle->GetForward().Heading(); } GetMatrix() = newMat; } void CPed::LookForSexyPeds(void) { if ((!IsPedInControl() && m_nPedState != PED_DRIVING) || m_lookTimer >= CTimer::GetTimeInMilliseconds() || m_nPedType != PEDTYPE_CIVMALE) return; for (int i = 0; i < m_numNearPeds; i++) { if (CanSeeEntity(m_nearPeds[i])) { if ((GetPosition() - m_nearPeds[i]->GetPosition()).Magnitude() < 10.0f) { CPed *nearPed = m_nearPeds[i]; if ((nearPed->m_pedStats->m_sexiness > m_pedStats->m_sexiness) && nearPed->m_nPedType == PEDTYPE_CIVFEMALE) { SetLookFlag(nearPed, true); m_lookTimer = CTimer::GetTimeInMilliseconds() + 4000; Say(SOUND_PED_CHAT_SEXY); return; } } } } m_lookTimer = CTimer::GetTimeInMilliseconds() + 10000; } void CPed::LookForSexyCars(void) { CEntity *vehicles[8]; CVehicle *veh; int foundVehId = 0; int bestPriceYet = 0; int16 lastVehicle; if (!IsPedInControl() && m_nPedState != PED_DRIVING) return; if (m_lookTimer < CTimer::GetTimeInMilliseconds()) { CWorld::FindObjectsInRange(GetPosition(), 10.0f, true, &lastVehicle, 6, vehicles, false, true, false, false, false); for (int vehId = 0; vehId < lastVehicle; vehId++) { veh = (CVehicle*)vehicles[vehId]; if (veh != m_pMyVehicle && bestPriceYet < veh->pHandling->nMonetaryValue) { foundVehId = vehId; bestPriceYet = veh->pHandling->nMonetaryValue; } } if (lastVehicle > 0 && bestPriceYet > 40000) SetLookFlag(vehicles[foundVehId], false); m_lookTimer = CTimer::GetTimeInMilliseconds() + 10000; } } bool CPed::LookForInterestingNodes(void) { CBaseModelInfo *model; CPtrNode *ptrNode; CVector effectDist; C2dEffect *effect; CMatrix *objMat; if ((CTimer::GetFrameCounter() + (m_randomSeed % 256)) & 7 || CTimer::GetTimeInMilliseconds() <= m_standardTimer) { return false; } bool found = false; uint8 randVal = CGeneral::GetRandomNumber() % 256; int minX = CWorld::GetSectorIndexX(GetPosition().x - CHECK_NEARBY_THINGS_MAX_DIST); if (minX < 0) minX = 0; int minY = CWorld::GetSectorIndexY(GetPosition().y - CHECK_NEARBY_THINGS_MAX_DIST); if (minY < 0) minY = 0; int maxX = CWorld::GetSectorIndexX(GetPosition().x + CHECK_NEARBY_THINGS_MAX_DIST); #ifdef FIX_BUGS if (maxX >= NUMSECTORS_X) maxX = NUMSECTORS_X - 1; #else if (maxX >= NUMSECTORS_X) maxX = NUMSECTORS_X; #endif int maxY = CWorld::GetSectorIndexY(GetPosition().y + CHECK_NEARBY_THINGS_MAX_DIST); #ifdef FIX_BUGS if (maxY >= NUMSECTORS_Y) maxY = NUMSECTORS_Y - 1; #else if (maxY >= NUMSECTORS_Y) maxY = NUMSECTORS_Y; #endif for (int curY = minY; curY <= maxY && !found; curY++) { for (int curX = minX; curX <= maxX && !found; curX++) { CSector *sector = CWorld::GetSector(curX, curY); for (ptrNode = sector->m_lists[ENTITYLIST_VEHICLES].first; ptrNode && !found; ptrNode = ptrNode->next) { CVehicle *veh = (CVehicle*)ptrNode->item; model = veh->GetModelInfo(); if (model->GetNum2dEffects() != 0) { for (int e = 0; e < model->GetNum2dEffects(); e++) { effect = model->Get2dEffect(e); if (effect->type == EFFECT_ATTRACTOR && effect->attractor.probability >= randVal) { objMat = &veh->GetMatrix(); CVector effectPos = veh->GetMatrix() * effect->pos; effectDist = effectPos - GetPosition(); if (effectDist.MagnitudeSqr() < sq(8.0f)) { found = true; break; } } } } } for (ptrNode = sector->m_lists[ENTITYLIST_OBJECTS].first; ptrNode && !found; ptrNode = ptrNode->next) { CObject *obj = (CObject*)ptrNode->item; model = CModelInfo::GetModelInfo(obj->GetModelIndex()); if (model->GetNum2dEffects() != 0) { for (int e = 0; e < model->GetNum2dEffects(); e++) { effect = model->Get2dEffect(e); if (effect->type == EFFECT_ATTRACTOR && effect->attractor.probability >= randVal) { objMat = &obj->GetMatrix(); CVector effectPos = obj->GetMatrix() * effect->pos; effectDist = effectPos - GetPosition(); if (effectDist.MagnitudeSqr() < sq(8.0f)) { found = true; break; } } } } } for (ptrNode = sector->m_lists[ENTITYLIST_BUILDINGS].first; ptrNode && !found; ptrNode = ptrNode->next) { CBuilding *building = (CBuilding*)ptrNode->item; model = CModelInfo::GetModelInfo(building->GetModelIndex()); if (model->GetNum2dEffects() != 0) { for (int e = 0; e < model->GetNum2dEffects(); e++) { effect = model->Get2dEffect(e); if (effect->type == EFFECT_ATTRACTOR && effect->attractor.probability >= randVal) { objMat = &building->GetMatrix(); CVector effectPos = building->GetMatrix() * effect->pos; effectDist = effectPos - GetPosition(); if (effectDist.MagnitudeSqr() < sq(8.0f)) { found = true; break; } } } } } for (ptrNode = sector->m_lists[ENTITYLIST_BUILDINGS_OVERLAP].first; ptrNode && !found; ptrNode = ptrNode->next) { CBuilding *building = (CBuilding*)ptrNode->item; model = CModelInfo::GetModelInfo(building->GetModelIndex()); if (model->GetNum2dEffects() != 0) { for (int e = 0; e < model->GetNum2dEffects(); e++) { effect = model->Get2dEffect(e); if (effect->type == EFFECT_ATTRACTOR && effect->attractor.probability >= randVal) { objMat = &building->GetMatrix(); CVector effectPos = building->GetMatrix() * effect->pos; effectDist = effectPos - GetPosition(); if (effectDist.MagnitudeSqr() < sq(8.0f)) { found = true; break; } } } } } } } if (!found) return false; CVector effectFrontLocal = Multiply3x3(*objMat, effect->attractor.dir); float angleToFace = CGeneral::GetRadianAngleBetweenPoints(effectFrontLocal.x, effectFrontLocal.y, 0.0f, 0.0f); randVal = CGeneral::GetRandomNumber() % 256; if (randVal <= m_randomSeed % 256) { m_standardTimer = CTimer::GetTimeInMilliseconds() + 2000; SetLookFlag(angleToFace, true); SetLookTimer(1000); return false; } CVector2D effectPos = *objMat * effect->pos; switch (effect->attractor.type) { case ATTRACTORTYPE_ICECREAM: SetInvestigateEvent(EVENT_ICECREAM, effectPos, 0.1f, 15000, angleToFace); break; case ATTRACTORTYPE_STARE: SetInvestigateEvent(EVENT_SHOPSTALL, effectPos, 1.0f, CGeneral::GetRandomNumberInRange(8000, 10 * effect->attractor.probability + 8500), angleToFace); break; default: return true; } return true; } void CPed::SetWaitState(eWaitState state, void *time) { AnimationId waitAnim = NUM_ANIMS; CAnimBlendAssociation *animAssoc; if (!IsPedInControl()) return; if (state != m_nWaitState) FinishedWaitCB(nil, this); switch (state) { case WAITSTATE_TRAFFIC_LIGHTS: m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 500; SetMoveState(PEDMOVE_STILL); break; case WAITSTATE_CROSS_ROAD: m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 1000; CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_IDLE_HBHB, 4.0f); break; case WAITSTATE_CROSS_ROAD_LOOK: CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_ROAD_CROSS, 8.0f); if (time) m_nWaitTimer = CTimer::GetTimeInMilliseconds() + *(int*)time; else m_nWaitTimer = CTimer::GetTimeInMilliseconds() + CGeneral::GetRandomNumberInRange(2000,5000); break; case WAITSTATE_LOOK_PED: case WAITSTATE_LOOK_SHOP: case WAITSTATE_LOOK_ACCIDENT: case WAITSTATE_FACEOFF_GANG: break; case WAITSTATE_DOUBLEBACK: m_headingRate = 0.0f; m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 3500; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_IDLE_HBHB, 4.0f); #ifdef FIX_BUGS animAssoc->SetFinishCallback(RestoreHeadingRateCB, this); #endif break; case WAITSTATE_HITWALL: m_headingRate = 2.0f; m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 5000; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_HIT_WALL, 16.0f); animAssoc->flags |= ASSOC_DELETEFADEDOUT; animAssoc->flags |= ASSOC_FADEOUTWHENDONE; animAssoc->SetDeleteCallback(FinishedWaitCB, this); if (m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER && CharCreatedBy == RANDOM_CHAR && m_nPedState == PED_SEEK_CAR) { ClearObjective(); RestorePreviousState(); m_hitRecoverTimer = CTimer::GetTimeInMilliseconds() + 30000; } break; case WAITSTATE_TURN180: m_headingRate = 0.0f; m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 5000; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_TURN_180, 4.0f); animAssoc->SetFinishCallback(FinishedWaitCB, this); animAssoc->SetDeleteCallback(RestoreHeadingRateCB, this); break; case WAITSTATE_SURPRISE: m_headingRate = 0.0f; m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 2000; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_HIT_WALL, 4.0f); animAssoc->SetFinishCallback(FinishedWaitCB, this); break; case WAITSTATE_STUCK: SetMoveState(PEDMOVE_STILL); SetMoveAnim(); m_headingRate = 0.0f; m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 5000; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_IDLE_TIRED, 4.0f); #ifdef FIX_BUGS animAssoc->SetFinishCallback(RestoreHeadingRateCB, this); #endif if (m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER && CharCreatedBy == RANDOM_CHAR && m_nPedState == PED_SEEK_CAR) { ClearObjective(); RestorePreviousState(); m_hitRecoverTimer = CTimer::GetTimeInMilliseconds() + 30000; } break; case WAITSTATE_LOOK_ABOUT: SetMoveState(PEDMOVE_STILL); SetMoveAnim(); m_headingRate = 0.0f; m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 5000; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_IDLE_HBHB, 4.0f); #ifdef FIX_BUGS animAssoc->SetFinishCallback(RestoreHeadingRateCB, this); #endif break; case WAITSTATE_PLAYANIM_COWER: waitAnim = ANIM_HANDSCOWER; case WAITSTATE_PLAYANIM_HANDSUP: if (waitAnim == NUM_ANIMS) waitAnim = ANIM_HANDSUP; case WAITSTATE_PLAYANIM_HANDSCOWER: if (waitAnim == NUM_ANIMS) waitAnim = ANIM_HANDSCOWER; m_headingRate = 0.0f; if (time) m_nWaitTimer = CTimer::GetTimeInMilliseconds() + *(int*)time; else m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 3000; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, waitAnim, 4.0f); animAssoc->SetDeleteCallback(FinishedWaitCB, this); break; case WAITSTATE_PLAYANIM_DUCK: waitAnim = ANIM_DUCK_DOWN; case WAITSTATE_PLAYANIM_TAXI: if (waitAnim == NUM_ANIMS) waitAnim = ANIM_IDLE_TAXI; case WAITSTATE_PLAYANIM_CHAT: if (waitAnim == NUM_ANIMS) waitAnim = ANIM_IDLE_CHAT; if (time) m_nWaitTimer = CTimer::GetTimeInMilliseconds() + *(int*)time; else m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 3000; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, waitAnim, 4.0f); animAssoc->flags &= ~ASSOC_FADEOUTWHENDONE; animAssoc->flags |= ASSOC_DELETEFADEDOUT; animAssoc->SetDeleteCallback(FinishedWaitCB, this); break; case WAITSTATE_FINISH_FLEE: SetMoveState(PEDMOVE_STILL); SetMoveAnim(); m_headingRate = 0.0f; m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 2500; animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_IDLE_TIRED, 4.0f); #ifdef FIX_BUGS animAssoc->SetFinishCallback(RestoreHeadingRateCB, this); #endif break; default: m_nWaitState = WAITSTATE_FALSE; RestoreHeadingRate(); return; } m_nWaitState = state; } void CPed::Wait(void) { AnimationId mustHaveAnim = NUM_ANIMS; CAnimBlendAssociation *animAssoc; CPed *pedWeLook; if (DyingOrDead()) { m_nWaitState = WAITSTATE_FALSE; RestoreHeadingRate(); return; } switch (m_nWaitState) { case WAITSTATE_TRAFFIC_LIGHTS: if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { if (CTrafficLights::LightForPeds() == PED_LIGHTS_WALK) { m_nWaitState = WAITSTATE_FALSE; SetMoveState(PEDMOVE_WALK); } } break; case WAITSTATE_CROSS_ROAD: if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { if (CGeneral::GetRandomNumber() & 1 || !m_nWaitTimer) m_nWaitState = WAITSTATE_FALSE; else SetWaitState(WAITSTATE_CROSS_ROAD_LOOK, nil); animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_HBHB); if (animAssoc) { animAssoc->blendDelta = -8.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } } break; case WAITSTATE_CROSS_ROAD_LOOK: if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { m_nWaitState = WAITSTATE_FALSE; animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_ROAD_CROSS); if (animAssoc) { animAssoc->blendDelta = -8.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } } break; case WAITSTATE_DOUBLEBACK: if (CTimer::GetTimeInMilliseconds() <= m_nWaitTimer) { uint32 timeLeft = m_nWaitTimer - CTimer::GetTimeInMilliseconds(); if (timeLeft < 2500 && timeLeft > 2000) { m_nWaitTimer -= 500; CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_XPRESS_SCRATCH, 4.0f); } } else { m_nWaitState = WAITSTATE_FALSE; SetMoveState(PEDMOVE_WALK); } break; case WAITSTATE_HITWALL: if (CTimer::GetTimeInMilliseconds() <= m_nWaitTimer) { if (m_collidingThingTimer > CTimer::GetTimeInMilliseconds()) { m_collidingThingTimer = CTimer::GetTimeInMilliseconds() + 2500; } } else { m_nWaitState = WAITSTATE_FALSE; } break; case WAITSTATE_TURN180: if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { m_nWaitState = WAITSTATE_FALSE; SetMoveState(PEDMOVE_WALK); m_fRotationCur = m_fRotationCur + PI; if (m_nPedState == PED_INVESTIGATE) ClearInvestigateEvent(); } if (m_collidingThingTimer > CTimer::GetTimeInMilliseconds()) { m_collidingThingTimer = CTimer::GetTimeInMilliseconds() + 2500; } break; case WAITSTATE_SURPRISE: if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { if (RpAnimBlendClumpGetAssociation(GetClump(), ANIM_HIT_WALL)) { animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_XPRESS_SCRATCH, 4.0f); animAssoc->SetFinishCallback(FinishedWaitCB, this); m_nWaitTimer = CTimer::GetTimeInMilliseconds() + 5000; } else { m_nWaitState = WAITSTATE_FALSE; } } break; case WAITSTATE_STUCK: if (CTimer::GetTimeInMilliseconds() <= m_nWaitTimer) break; animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_TIRED); if (!animAssoc) animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_TURN_180); if (!animAssoc) animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_XPRESS_SCRATCH); if (!animAssoc) animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_ROAD_CROSS); if (animAssoc) { if (animAssoc->IsPartial()) { animAssoc->blendDelta = -8.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } else { animAssoc->flags |= ASSOC_DELETEFADEDOUT; CAnimManager::BlendAnimation(GetClump(), m_animGroup, ANIM_IDLE_STANCE, 4.0f); } if (animAssoc->animId == ANIM_TURN_180) { m_fRotationCur = CGeneral::LimitRadianAngle(PI + m_fRotationCur); m_nWaitState = WAITSTATE_FALSE; SetMoveState(PEDMOVE_WALK); m_nStoredMoveState = PEDMOVE_NONE; m_panicCounter = 0; return; } } AnimationId animToPlay; switch (CGeneral::GetRandomNumber() & 3) { case 0: animToPlay = ANIM_ROAD_CROSS; break; case 1: animToPlay = ANIM_IDLE_TIRED; break; case 2: animToPlay = ANIM_XPRESS_SCRATCH; break; case 3: animToPlay = ANIM_TURN_180; break; default: break; } animAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, animToPlay, 4.0f); if (animToPlay == ANIM_TURN_180) animAssoc->SetFinishCallback(FinishedWaitCB, this); m_nWaitTimer = CTimer::GetTimeInMilliseconds() + CGeneral::GetRandomNumberInRange(1500, 5000); break; case WAITSTATE_LOOK_ABOUT: if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { m_nWaitState = WAITSTATE_FALSE; animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_HBHB); if (animAssoc) { animAssoc->blendDelta = -8.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } } break; case WAITSTATE_PLAYANIM_HANDSUP: mustHaveAnim = ANIM_HANDSUP; case WAITSTATE_PLAYANIM_HANDSCOWER: if (mustHaveAnim == NUM_ANIMS) mustHaveAnim = ANIM_HANDSCOWER; animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), mustHaveAnim); pedWeLook = (CPed*) m_pLookTarget; if ((!m_pLookTarget || !m_pLookTarget->IsPed() || pedWeLook->m_pPointGunAt) && m_nPedState != PED_FLEE_ENTITY && m_nPedState != PED_ATTACK && CTimer::GetTimeInMilliseconds() <= m_nWaitTimer && animAssoc) { TurnBody(); } else { m_nWaitState = WAITSTATE_FALSE; m_nWaitTimer = 0; if (m_pLookTarget && m_pLookTarget->IsPed()) { if (m_nPedState != PED_FLEE_ENTITY && m_nPedState != PED_ATTACK) { if (m_pedStats->m_fear <= 100 - pedWeLook->m_pedStats->m_temper) { if (GetWeapon()->IsTypeMelee()) { #ifdef VC_PED_PORTS if(m_pedStats->m_flags & STAT_GUN_PANIC) { #endif SetObjective(OBJECTIVE_FLEE_CHAR_ON_FOOT_TILL_SAFE, m_pLookTarget); if (m_nPedState == PED_FLEE_ENTITY || m_nPedState == PED_FLEE_POS) { bUsePedNodeSeek = true; m_pNextPathNode = nil; } if (m_nMoveState != PEDMOVE_RUN) SetMoveState(PEDMOVE_WALK); if (m_nPedType != PEDTYPE_COP) { ProcessObjective(); SetMoveState(PEDMOVE_WALK); } #ifdef VC_PED_PORTS } else { SetObjective(OBJECTIVE_NONE); SetWanderPath(CGeneral::GetRandomNumberInRange(0.0f, 8.0f)); } #endif } else { SetObjective(OBJECTIVE_KILL_CHAR_ON_FOOT, m_pLookTarget); SetObjectiveTimer(20000); } } else { SetObjective(OBJECTIVE_FLEE_CHAR_ON_FOOT_TILL_SAFE, m_pLookTarget); if (m_nPedState == PED_FLEE_ENTITY || m_nPedState == PED_FLEE_POS) { bUsePedNodeSeek = true; m_pNextPathNode = nil; } SetMoveState(PEDMOVE_RUN); Say(SOUND_PED_FLEE_RUN); } } } animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), mustHaveAnim); if (animAssoc) { animAssoc->blendDelta = -4.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } } break; case WAITSTATE_PLAYANIM_COWER: mustHaveAnim = ANIM_HANDSCOWER; case WAITSTATE_PLAYANIM_DUCK: if (mustHaveAnim == NUM_ANIMS) mustHaveAnim = ANIM_DUCK_DOWN; case WAITSTATE_PLAYANIM_TAXI: if (mustHaveAnim == NUM_ANIMS) mustHaveAnim = ANIM_IDLE_TAXI; case WAITSTATE_PLAYANIM_CHAT: if (mustHaveAnim == NUM_ANIMS) mustHaveAnim = ANIM_IDLE_CHAT; if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), mustHaveAnim); if (animAssoc) { animAssoc->blendDelta = -4.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } m_nWaitState = WAITSTATE_FALSE; } #ifdef VC_PED_PORTS else if (m_nWaitState == WAITSTATE_PLAYANIM_TAXI) { if (m_pedInObjective) { if (m_objective == OBJECTIVE_GOTO_CHAR_ON_FOOT || m_objective == OBJECTIVE_KILL_CHAR_ON_FOOT) { // VC also calls CleanUpOldReference here for old LookTarget. m_pLookTarget = m_pedInObjective; m_pLookTarget->RegisterReference((CEntity **) &m_pLookTarget); TurnBody(); } } } #endif break; case WAITSTATE_FINISH_FLEE: animAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_IDLE_TIRED); if (animAssoc) { if (CTimer::GetTimeInMilliseconds() > m_nWaitTimer) { animAssoc->flags |= ASSOC_DELETEFADEDOUT; CAnimManager::BlendAnimation(GetClump(), m_animGroup, ANIM_IDLE_STANCE, 4.0f); int timer = 2000; m_nWaitState = WAITSTATE_FALSE; SetWaitState(WAITSTATE_CROSS_ROAD_LOOK, &timer); } } else { m_nWaitState = WAITSTATE_FALSE; } break; default: break; } if(!m_nWaitState) RestoreHeadingRate(); } void CPed::FinishedWaitCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; ped->m_nWaitTimer = 0; ped->RestoreHeadingRate(); ped->Wait(); } void CPed::RestoreHeadingRate(void) { m_headingRate = m_pedStats->m_headingChangeRate; } void CPed::RestoreHeadingRateCB(CAnimBlendAssociation *assoc, void *arg) { ((CPed*)arg)->m_headingRate = ((CPed*)arg)->m_pedStats->m_headingChangeRate; } void CPed::FlagToDestroyWhenNextProcessed(void) { bRemoveFromWorld = true; if (!InVehicle()) return; if (m_pMyVehicle->pDriver == this){ m_pMyVehicle->pDriver = nil; if (IsPlayer() && m_pMyVehicle->GetStatus() != STATUS_WRECKED) m_pMyVehicle->SetStatus(STATUS_ABANDONED); }else{ m_pMyVehicle->RemovePassenger(this); } bInVehicle = false; m_pMyVehicle = nil; if (CharCreatedBy == MISSION_CHAR) m_nPedState = PED_DEAD; else m_nPedState = PED_NONE; m_pVehicleAnim = nil; } void CPed::SetSolicit(uint32 time) { if (m_nPedState == PED_SOLICIT || !IsPedInControl() || !m_carInObjective) return; if (CharCreatedBy != MISSION_CHAR && m_carInObjective->m_nNumGettingIn == 0 && CTimer::GetTimeInMilliseconds() < m_objectiveTimer) { if (m_vehEnterType == CAR_DOOR_LF) { m_fRotationDest = m_carInObjective->GetForward().Heading() - HALFPI; } else { m_fRotationDest = m_carInObjective->GetForward().Heading() + HALFPI; } if (Abs(m_fRotationDest - m_fRotationCur) < HALFPI) { m_standardTimer = CTimer::GetTimeInMilliseconds() + time; if(!m_carInObjective->bIsVan && !m_carInObjective->bIsBus) m_pVehicleAnim = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_CAR_HOOKERTALK, 4.0f); m_nPedState = PED_SOLICIT; } } } void CPed::Solicit(void) { if (m_standardTimer >= CTimer::GetTimeInMilliseconds() && m_carInObjective) { CVector doorPos = GetPositionToOpenCarDoor(m_carInObjective, m_vehEnterType, 0.0f); SetMoveState(PEDMOVE_STILL); // Game uses GetAngleBetweenPoints and converts it to radian m_fRotationDest = CGeneral::GetRadianAngleBetweenPoints( doorPos.x, doorPos.y, GetPosition().x, GetPosition().y); if (m_fRotationDest < 0.0f) { m_fRotationDest = m_fRotationDest + TWOPI; } else if (m_fRotationDest > TWOPI) { m_fRotationDest = m_fRotationDest - TWOPI; } if ((GetPosition() - doorPos).MagnitudeSqr() <= 1.0f) return; CAnimBlendAssociation *talkAssoc = RpAnimBlendClumpGetAssociation(GetClump(), ANIM_CAR_HOOKERTALK); if (talkAssoc) { talkAssoc->blendDelta = -1000.0f; talkAssoc->flags |= ASSOC_DELETEFADEDOUT; } RestorePreviousState(); RestorePreviousObjective(); SetObjectiveTimer(10000); } else if (!m_carInObjective) { RestorePreviousState(); RestorePreviousObjective(); SetObjectiveTimer(10000); } else if (CWorld::Players[CWorld::PlayerInFocus].m_nMoney <= 100) { m_carInObjective = nil; } else { m_pVehicleAnim = nil; SetLeader(m_carInObjective->pDriver); } } void CPed::SetBuyIceCream(void) { if (m_nPedState == PED_BUY_ICECREAM || !IsPedInControl()) return; if (!m_carInObjective) return; #ifdef FIX_ICECREAM // Simulating BuyIceCream CPed* driver = m_carInObjective->pDriver; if (driver) { m_nPedState = PED_BUY_ICECREAM; bFindNewNodeAfterStateRestore = true; SetObjectiveTimer(8000); SetChat(driver, 8000); driver->SetChat(this, 8000); return; } #endif // Side of the Ice Cream van m_fRotationDest = m_carInObjective->GetForward().Heading() - HALFPI; if (Abs(m_fRotationDest - m_fRotationCur) < HALFPI) { m_standardTimer = CTimer::GetTimeInMilliseconds() + 3000; m_nPedState = PED_BUY_ICECREAM; } } bool CPed::PossiblyFindBetterPosToSeekCar(CVector *pos, CVehicle *veh) { bool foundIt = false; CVector helperPos = GetPosition(); helperPos.z = pos->z - 0.5f; CVector foundPos = *pos; foundPos.z -= 0.5f; // If there is another car between target car and us. if (CWorld::TestSphereAgainstWorld((foundPos + helperPos) / 2.0f, 0.25f, veh, false, true, false, false, false, false)) { CColModel *vehCol = veh->GetModelInfo()->GetColModel(); CVector *colMin = &vehCol->boundingBox.min; CVector *colMax = &vehCol->boundingBox.max; CVector leftRearPos = CVector(colMin->x - 0.5f, colMin->y - 0.5f, 0.0f); CVector rightRearPos = CVector(0.5f + colMax->x, colMin->y - 0.5f, 0.0f); CVector leftFrontPos = CVector(colMin->x - 0.5f, 0.5f + colMax->y, 0.0f); CVector rightFrontPos = CVector(0.5f + colMax->x, 0.5f + colMax->y, 0.0f); leftRearPos = veh->GetMatrix() * leftRearPos; rightRearPos = veh->GetMatrix() * rightRearPos; leftFrontPos = veh->GetMatrix() * leftFrontPos; rightFrontPos = veh->GetMatrix() * rightFrontPos; // Makes helperPos veh-ped distance vector. helperPos -= veh->GetPosition(); // ?!? I think it's absurd to use this unless another function like SeekCar finds next pos. with it and we're trying to simulate it's behaviour. // On every run it returns another pos. for ped, with same distance to the veh. // Sequence of positions are not guaranteed, it depends on global pos. (So sometimes it returns positions to make ped draw circle, sometimes don't) helperPos = veh->GetMatrix() * helperPos; float vehForwardHeading = veh->GetForward().Heading(); // I'm absolutely not sure about these namings. // NTVF = needed turn if we're looking to vehicle front and wanna look to... float potentialLrHeading = Atan2(leftRearPos.x - helperPos.x, leftRearPos.y - helperPos.y); float NTVF_LR = CGeneral::LimitRadianAngle(potentialLrHeading - vehForwardHeading); float potentialRrHeading = Atan2(rightRearPos.x - helperPos.x, rightRearPos.y - helperPos.y); float NTVF_RR = CGeneral::LimitRadianAngle(potentialRrHeading - vehForwardHeading); float potentialLfHeading = Atan2(leftFrontPos.x - helperPos.x, leftFrontPos.y - helperPos.y); float NTVF_LF = CGeneral::LimitRadianAngle(potentialLfHeading - vehForwardHeading); float potentialRfHeading = Atan2(rightFrontPos.x - helperPos.x, rightFrontPos.y - helperPos.y); float NTVF_RF = CGeneral::LimitRadianAngle(potentialRfHeading - vehForwardHeading); bool canHeadToLr = NTVF_LR <= -PI || NTVF_LR >= -HALFPI; bool canHeadToRr = NTVF_RR <= HALFPI || NTVF_RR >= PI; bool canHeadToLf = NTVF_LF >= 0.0f || NTVF_LF <= -HALFPI; bool canHeadToRf = NTVF_RF <= 0.0f || NTVF_RF >= HALFPI; // Only order of conditions are different among enterTypes. if (m_vehEnterType == CAR_DOOR_RR) { if (canHeadToRr) { foundPos = rightRearPos; foundIt = true; } else if (canHeadToRf) { foundPos = rightFrontPos; foundIt = true; } else if (canHeadToLr) { foundPos = leftRearPos; foundIt = true; } else if (canHeadToLf) { foundPos = leftFrontPos; foundIt = true; } } else if(m_vehEnterType == CAR_DOOR_RF) { if (canHeadToRf) { foundPos = rightFrontPos; foundIt = true; } else if (canHeadToRr) { foundPos = rightRearPos; foundIt = true; } else if (canHeadToLf) { foundPos = leftFrontPos; foundIt = true; } else if (canHeadToLr) { foundPos = leftRearPos; foundIt = true; } } else if (m_vehEnterType == CAR_DOOR_LF) { if (canHeadToLf) { foundPos = leftFrontPos; foundIt = true; } else if (canHeadToLr) { foundPos = leftRearPos; foundIt = true; } else if (canHeadToRf) { foundPos = rightFrontPos; foundIt = true; } else if (canHeadToRr) { foundPos = rightRearPos; foundIt = true; } } else if (m_vehEnterType == CAR_DOOR_LR) { if (canHeadToLr) { foundPos = leftRearPos; foundIt = true; } else if (canHeadToLf) { foundPos = leftFrontPos; foundIt = true; } else if (canHeadToRr) { foundPos = rightRearPos; foundIt = true; } else if (canHeadToRf) { foundPos = rightFrontPos; foundIt = true; } } } if (!foundIt) return false; helperPos = GetPosition() - foundPos; helperPos.z = 0.0f; if (helperPos.MagnitudeSqr() <= sq(0.5f)) return false; pos->x = foundPos.x; pos->y = foundPos.y; return true; } void CPed::SetLeader(CEntity *leader) { m_leader = (CPed*)leader; if(m_leader) m_leader->RegisterReference((CEntity **)&m_leader); } #ifdef VC_PED_PORTS bool CPed::CanPedJumpThis(CEntity *unused, CVector *damageNormal) { if (m_nSurfaceTouched == SURFACE_WATER) return true; CVector pos = GetPosition(); CVector forwardOffset = GetForward(); if (damageNormal && damageNormal->z > 0.17f) { if (damageNormal->z > 0.9f) return false; CColModel *ourCol = CModelInfo::GetModelInfo(m_modelIndex)->GetColModel(); pos.z = ourCol->spheres->center.z - ourCol->spheres->radius * damageNormal->z + pos.z; pos.z = pos.z + 0.05f; float collPower = damageNormal->Magnitude2D(); if (damageNormal->z > 0.5f) { CVector invDamageNormal(-damageNormal->x, -damageNormal->y, 0.0f); invDamageNormal *= 1.0f / collPower; CVector estimatedJumpDist = invDamageNormal + collPower * invDamageNormal * ourCol->spheres->radius; forwardOffset = estimatedJumpDist * Min(2.0f / collPower, 4.0f); } else { forwardOffset += collPower * ourCol->spheres->radius * forwardOffset; } } else { pos.z -= 0.15f; } CVector forwardPos = pos + forwardOffset; return CWorld::GetIsLineOfSightClear(pos, forwardPos, true, false, false, true, false, false, false); } #else bool CPed::CanPedJumpThis(CEntity *unused) { CVector2D forward(-Sin(m_fRotationCur), Cos(m_fRotationCur)); CVector pos = GetPosition(); CVector forwardPos( forward.x + pos.x, forward.y + pos.y, pos.z); return CWorld::GetIsLineOfSightClear(pos, forwardPos, true, false, false, true, false, false, false); } #endif void CPed::SetJump(void) { if (!bInVehicle && #if defined VC_PED_PORTS || defined FIX_BUGS m_nPedState != PED_JUMP && !RpAnimBlendClumpGetAssociation(GetClump(), ANIM_JUMP_LAUNCH) && #endif (m_nSurfaceTouched != SURFACE_STEEP_CLIFF || DotProduct(GetForward(), m_vecDamageNormal) >= 0.0f)) { SetStoredState(); m_nPedState = PED_JUMP; CAnimBlendAssociation *jumpAssoc = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_JUMP_LAUNCH, 8.0f); jumpAssoc->SetFinishCallback(FinishLaunchCB, this); m_fRotationDest = m_fRotationCur; } } void CPed::FinishLaunchCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; if (ped->m_nPedState != PED_JUMP) return; CVector forward(0.15f * ped->GetForward() + ped->GetPosition()); forward.z += CModelInfo::GetModelInfo(ped->GetModelIndex())->GetColModel()->spheres->center.z + 0.25f; CEntity *obstacle = CWorld::TestSphereAgainstWorld(forward, 0.25f, nil, true, true, false, true, false, false); if (!obstacle) { // Forward of forward forward += 0.15f * ped->GetForward(); forward.z += 0.15f; obstacle = CWorld::TestSphereAgainstWorld(forward, 0.25f, nil, true, true, false, true, false, false); } if (obstacle) { animAssoc->flags |= ASSOC_DELETEFADEDOUT; // ANIM_HIT_WALL in VC (which makes more sense) CAnimBlendAssociation *handsCoverAssoc = CAnimManager::BlendAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_HANDSCOWER, 8.0f); handsCoverAssoc->flags &= ~ASSOC_FADEOUTWHENDONE; handsCoverAssoc->SetFinishCallback(FinishHitHeadCB, ped); ped->bIsLanding = true; return; } float velocityFromAnim = 0.1f; CAnimBlendAssociation *sprintAssoc = RpAnimBlendClumpGetAssociation(ped->GetClump(), ANIM_SPRINT); if (sprintAssoc) { velocityFromAnim = 0.05f * sprintAssoc->blendAmount + 0.17f; } else { CAnimBlendAssociation *runAssoc = RpAnimBlendClumpGetAssociation(ped->GetClump(), ANIM_RUN); if (runAssoc) { velocityFromAnim = 0.07f * runAssoc->blendAmount + 0.1f; } } if (ped->IsPlayer() #ifdef VC_PED_PORTS || ped->m_pedInObjective && ped->m_pedInObjective->IsPlayer() #endif ) ped->ApplyMoveForce(0.0f, 0.0f, 8.5f); else ped->ApplyMoveForce(0.0f, 0.0f, 4.5f); if (sq(velocityFromAnim) > ped->m_vecMoveSpeed.MagnitudeSqr2D() #ifdef VC_PED_PORTS || ped->m_pCurrentPhysSurface #endif ) { #ifdef FREE_CAM if (TheCamera.Cams[0].Using3rdPersonMouseCam() && !CCamera::bFreeCam) { #else if (TheCamera.Cams[0].Using3rdPersonMouseCam()) { #endif float fpsAngle = ped->WorkOutHeadingForMovingFirstPerson(ped->m_fRotationCur); ped->m_vecMoveSpeed.x = -velocityFromAnim * Sin(fpsAngle); ped->m_vecMoveSpeed.y = velocityFromAnim * Cos(fpsAngle); } else { ped->m_vecMoveSpeed.x = -velocityFromAnim * Sin(ped->m_fRotationCur); ped->m_vecMoveSpeed.y = velocityFromAnim * Cos(ped->m_fRotationCur); } #ifdef VC_PED_PORTS if (ped->m_pCurrentPhysSurface) { ped->m_vecMoveSpeed.x += ped->m_pCurrentPhysSurface->m_vecMoveSpeed.x; ped->m_vecMoveSpeed.y += ped->m_pCurrentPhysSurface->m_vecMoveSpeed.y; } #endif } ped->bIsStanding = false; ped->bIsInTheAir = true; animAssoc->blendDelta = -1000.0f; CAnimManager::AddAnimation(ped->GetClump(), ASSOCGRP_STD, ANIM_JUMP_GLIDE); if (ped->bDoBloodyFootprints) { CVector bloodPos(0.0f, 0.0f, 0.0f); ped->TransformToNode(bloodPos, PED_FOOTL); bloodPos.z -= 0.1f; bloodPos += 0.2f * ped->GetForward(); CShadows::AddPermanentShadow(SHADOWTYPE_DARK, gpBloodPoolTex, &bloodPos, 0.26f * ped->GetForward().x, 0.26f * ped->GetForward().y, 0.14f * ped->GetRight().x, 0.14f * ped->GetRight().y, 255, 255, 0, 0, 4.0f, 3000, 1.0f); bloodPos = CVector(0.0f, 0.0f, 0.0f); ped->TransformToNode(bloodPos, PED_FOOTR); bloodPos.z -= 0.1f; bloodPos += 0.2f * ped->GetForward(); CShadows::AddPermanentShadow(SHADOWTYPE_DARK, gpBloodPoolTex, &bloodPos, 0.26f * ped->GetForward().x, 0.26f * ped->GetForward().y, 0.14f * ped->GetRight().x, 0.14f * ped->GetRight().y, 255, 255, 0, 0, 4.0f, 3000, 1.0f); if (ped->m_bloodyFootprintCountOrDeathTime <= 40) { ped->m_bloodyFootprintCountOrDeathTime = 0; ped->bDoBloodyFootprints = false; } else { ped->m_bloodyFootprintCountOrDeathTime -= 40; } } } void CPed::FinishJumpCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; ped->bResetWalkAnims = true; ped->bIsLanding = false; animAssoc->blendDelta = -1000.0f; } void CPed::FinishHitHeadCB(CAnimBlendAssociation *animAssoc, void *arg) { CPed *ped = (CPed*)arg; if (animAssoc) { animAssoc->blendDelta = -4.0f; animAssoc->flags |= ASSOC_DELETEFADEDOUT; } if (ped->m_nPedState == PED_JUMP) ped->RestorePreviousState(); ped->bIsLanding = false; } bool CPed::CanPedDriveOff(void) { if (m_nPedState != PED_DRIVING || m_lookTimer > CTimer::GetTimeInMilliseconds()) return false; for (int i = 0; i < m_numNearPeds; i++) { CPed *nearPed = m_nearPeds[i]; if (nearPed->m_nPedType == m_nPedType && nearPed->m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER && nearPed->m_carInObjective == m_carInObjective) { m_lookTimer = CTimer::GetTimeInMilliseconds() + 1000; return false; } } return true; } // These categories are purely random, most of ped models have no correlation. So I don't think making an enum. uint8 CPed::GetPedRadioCategory(uint32 modelIndex) { switch (modelIndex) { case MI_MALE01: case MI_FEMALE03: case MI_PROSTITUTE2: case MI_WORKER1: case MI_MOD_MAN: case MI_MOD_WOM: case MI_ST_WOM: case MI_FAN_WOM: return 3; case MI_TAXI_D: case MI_PIMP: case MI_MALE02: case MI_FEMALE02: case MI_FATFEMALE01: case MI_FATFEMALE02: case MI_DOCKER1: case MI_WORKER2: case MI_FAN_MAN2: return 9; case MI_GANG01: case MI_GANG02: case MI_SCUM_MAN: case MI_SCUM_WOM: case MI_HOS_WOM: case MI_CONST1: return 1; case MI_GANG03: case MI_GANG04: case MI_GANG07: case MI_GANG08: case MI_CT_MAN2: case MI_CT_WOM2: case MI_B_MAN3: case MI_SHOPPER3: return 4; case MI_GANG05: case MI_GANG06: case MI_GANG11: case MI_GANG12: case MI_CRIMINAL02: case MI_B_WOM2: case MI_ST_MAN: case MI_HOS_MAN: return 5; case MI_FATMALE01: case MI_LI_MAN2: case MI_SHOPPER1: case MI_CAS_MAN: return 6; case MI_PROSTITUTE: case MI_P_WOM2: case MI_LI_WOM2: case MI_B_WOM3: case MI_CAS_WOM: return 2; case MI_P_WOM1: case MI_DOCKER2: case MI_STUD_MAN: return 7; case MI_CT_MAN1: case MI_CT_WOM1: case MI_LI_MAN1: case MI_LI_WOM1: case MI_B_MAN1: case MI_B_MAN2: case MI_B_WOM1: case MI_SHOPPER2: case MI_STUD_WOM: return 8; default: return 0; } } void CPed::SetRadioStation(void) { static const uint8 radiosPerRadioCategories[10][4] = { {JAH_RADIO, RISE_FM, GAME_FM, MSX_FM}, {HEAD_RADIO, DOUBLE_CLEF, LIPS_106, FLASHBACK}, {RISE_FM, GAME_FM, MSX_FM, FLASHBACK}, {HEAD_RADIO, RISE_FM, LIPS_106, MSX_FM}, {HEAD_RADIO, RISE_FM, MSX_FM, FLASHBACK}, {JAH_RADIO, RISE_FM, LIPS_106, FLASHBACK}, {HEAD_RADIO, RISE_FM, LIPS_106, FLASHBACK}, {HEAD_RADIO, JAH_RADIO, LIPS_106, FLASHBACK}, {HEAD_RADIO, DOUBLE_CLEF, LIPS_106, FLASHBACK}, {CHATTERBOX, HEAD_RADIO, LIPS_106, GAME_FM} }; uint8 orderInCat = 0; // BUG: this wasn't initialized if (IsPlayer() || !m_pMyVehicle || m_pMyVehicle->pDriver != this) return; uint8 category = GetPedRadioCategory(GetModelIndex()); if (DMAudio.IsMP3RadioChannelAvailable()) { if (CGeneral::GetRandomNumber() & 15) { for (orderInCat = 0; orderInCat < 4; orderInCat++) { if (m_pMyVehicle->m_nRadioStation == radiosPerRadioCategories[category][orderInCat]) break; } } else { m_pMyVehicle->m_nRadioStation = USERTRACK; } } else { for (orderInCat = 0; orderInCat < 4; orderInCat++) { if (m_pMyVehicle->m_nRadioStation == radiosPerRadioCategories[category][orderInCat]) break; } } if (orderInCat == 4) { if (DMAudio.IsMP3RadioChannelAvailable()) { if (CGeneral::GetRandomNumber() & 15) m_pMyVehicle->m_nRadioStation = radiosPerRadioCategories[category][CGeneral::GetRandomNumber() & 3]; else m_pMyVehicle->m_nRadioStation = USERTRACK; } else { m_pMyVehicle->m_nRadioStation = radiosPerRadioCategories[category][CGeneral::GetRandomNumber() & 3]; } } } void CPed::WarpPedIntoCar(CVehicle *car) { bInVehicle = true; m_pMyVehicle = car; m_pMyVehicle->RegisterReference((CEntity **) &m_pMyVehicle); m_carInObjective = car; m_carInObjective->RegisterReference((CEntity **) &m_carInObjective); m_nPedState = PED_DRIVING; bUsesCollision = false; bIsInTheAir = false; bVehExitWillBeInstant = true; if (m_objective == OBJECTIVE_ENTER_CAR_AS_DRIVER) { car->SetDriver(this); car->pDriver->RegisterReference((CEntity **) &car->pDriver); } else if (m_objective == OBJECTIVE_ENTER_CAR_AS_PASSENGER) { for (int i = 0; i < 4; i++) { if (!car->pPassengers[i]) { car->pPassengers[i] = this; car->pPassengers[i]->RegisterReference((CEntity **) &car->pPassengers[i]); break; } } } else return; if (IsPlayer()) { car->SetStatus(STATUS_PLAYER); AudioManager.PlayerJustGotInCar(); CCarCtrl::RegisterVehicleOfInterest(car); } else { car->SetStatus(STATUS_PHYSICS); } CWorld::Remove(this); SetPosition(car->GetPosition()); CWorld::Add(this); if (car->bIsAmbulanceOnDuty) { car->bIsAmbulanceOnDuty = false; --CCarCtrl::NumAmbulancesOnDuty; } if (car->bIsFireTruckOnDuty) { car->bIsFireTruckOnDuty = false; --CCarCtrl::NumFiretrucksOnDuty; } if (!car->bEngineOn) { car->bEngineOn = true; DMAudio.PlayOneShot(car->m_audioEntityId, SOUND_CAR_ENGINE_START, 1.0f); } #ifdef VC_PED_PORTS RpAnimBlendClumpSetBlendDeltas(GetClump(), ASSOC_PARTIAL, -1000.0f); // VC uses AddInCarAnims but we don't have that m_pVehicleAnim = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, car->GetDriverAnim(), 100.0f); RemoveWeaponWhenEnteringVehicle(); #else if (car->IsBoat()) { #ifndef FIX_BUGS m_pVehicleAnim = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_DRIVE_BOAT, 100.0f); #else m_pVehicleAnim = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, car->GetDriverAnim(), 100.0f); #endif CWeaponInfo *ourWeapon = CWeaponInfo::GetWeaponInfo(GetWeapon()->m_eWeaponType); RemoveWeaponModel(ourWeapon->m_nModelId); } else { // Because we can use Uzi for drive by RemoveWeaponWhenEnteringVehicle(); if (car->bLowVehicle) m_pVehicleAnim = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_CAR_LSIT, 100.0f); else m_pVehicleAnim = CAnimManager::BlendAnimation(GetClump(), ASSOCGRP_STD, ANIM_CAR_SIT, 100.0f); } #endif StopNonPartialAnims(); if (car->bIsBus) bRenderPedInCar = false; bChangedSeat = true; } #ifdef PEDS_REPORT_CRIMES_ON_PHONE // returns event id, parameter is optional int32 CPed::CheckForPlayerCrimes(CPed *victim) { int i; float dist; float mindist = 60.0f; CPlayerPed *player = FindPlayerPed(); int32 victimRef = (victim ? CPools::GetPedRef(victim) : 0); int event = -1; for (i = 0; i < NUMEVENTS; i++) { if (gaEvent[i].type == EVENT_NULL || gaEvent[i].type > EVENT_CAR_SET_ON_FIRE) continue; // those are already handled in game, also DEAD_PED isn't registered alone, most of the time there is SHOOT_PED etc. if (gaEvent[i].type == EVENT_DEAD_PED || gaEvent[i].type == EVENT_GUNSHOT || gaEvent[i].type == EVENT_EXPLOSION) continue; if (victim && gaEvent[i].entityRef != victimRef) continue; if (gaEvent[i].criminal != player) continue; dist = (GetPosition() - gaEvent[i].posn).Magnitude(); if (dist < mindist) { mindist = dist; event = i; } } if (event != -1) { if (victim) { m_victimOfPlayerCrime = victim; } else { switch (gaEvent[event].entityType) { case EVENT_ENTITY_PED: m_victimOfPlayerCrime = CPools::GetPed(gaEvent[event].entityRef); break; case EVENT_ENTITY_VEHICLE: m_victimOfPlayerCrime = CPools::GetVehicle(gaEvent[event].entityRef); break; case EVENT_ENTITY_OBJECT: m_victimOfPlayerCrime = CPools::GetObject(gaEvent[event].entityRef); break; default: break; } } } return event; } #endif #ifdef PED_SKIN static RpMaterial* SetLimbAlphaCB(RpMaterial *material, void *data) { ((RwRGBA*)RpMaterialGetColor(material))->alpha = *(uint8*)data; return material; } void CPed::renderLimb(int node) { RpHAnimHierarchy *hier = GetAnimHierarchyFromSkinClump(GetClump()); int idx = RpHAnimIDGetIndex(hier, m_pFrames[node]->nodeID); RwMatrix *mat = &RpHAnimHierarchyGetMatrixArray(hier)[idx]; CPedModelInfo *mi = (CPedModelInfo *)CModelInfo::GetModelInfo(GetModelIndex()); RpAtomic *atomic; switch(node){ case PED_HEAD: atomic = mi->getHead(); break; case PED_HANDL: atomic = mi->getLeftHand(); break; case PED_HANDR: atomic = mi->getRightHand(); break; default: return; } if(atomic == nil) return; RwFrame *frame = RpAtomicGetFrame(atomic); *RwFrameGetMatrix(frame) = *mat; RwFrameUpdateObjects(frame); int alpha = CVisibilityPlugins::GetClumpAlpha(GetClump()); RpGeometryForAllMaterials(RpAtomicGetGeometry(atomic), SetLimbAlphaCB, &alpha); RpAtomicRender(atomic); } #endif #ifdef COMPATIBLE_SAVES #define CopyFromBuf(buf, data) memcpy(&data, buf, sizeof(data)); SkipSaveBuf(buf, sizeof(data)); #define CopyToBuf(buf, data) memcpy(buf, &data, sizeof(data)); SkipSaveBuf(buf, sizeof(data)); void CPed::Save(uint8*& buf) { SkipSaveBuf(buf, 52); CopyToBuf(buf, GetPosition().x); CopyToBuf(buf, GetPosition().y); CopyToBuf(buf, GetPosition().z); SkipSaveBuf(buf, 288); CopyToBuf(buf, CharCreatedBy); SkipSaveBuf(buf, 351); CopyToBuf(buf, m_fHealth); CopyToBuf(buf, m_fArmour); SkipSaveBuf(buf, 148); for (int i = 0; i < 13; i++) // has to be hardcoded m_weapons[i].Save(buf); SkipSaveBuf(buf, 5); CopyToBuf(buf, m_maxWeaponTypeAllowed); SkipSaveBuf(buf, 162); } void CPed::Load(uint8*& buf) { SkipSaveBuf(buf, 52); CopyFromBuf(buf, GetMatrix().GetPosition().x); CopyFromBuf(buf, GetMatrix().GetPosition().y); CopyFromBuf(buf, GetMatrix().GetPosition().z); SkipSaveBuf(buf, 288); CopyFromBuf(buf, CharCreatedBy); SkipSaveBuf(buf, 351); CopyFromBuf(buf, m_fHealth); CopyFromBuf(buf, m_fArmour); SkipSaveBuf(buf, 148); for (int i = 0; i < 13; i++) // has to be hardcoded m_weapons[i].Load(buf); SkipSaveBuf(buf, 5); CopyFromBuf(buf, m_maxWeaponTypeAllowed); SkipSaveBuf(buf, 162); } #undef CopyFromBuf #undef CopyToBuf #endif
0
0.974706
1
0.974706
game-dev
MEDIA
0.977359
game-dev
0.922203
1
0.922203
chachaxw/data-structure-and-algorithm
1,937
ts/game.ts
/** input: - gameBoardWidth: int - gameBoardHeight: int - mPosition: ? - hPosition: ? output: function render(input: ...): string[] [ "XXXXXXXXXXXXX", "X.......H...X", "X...........X", "X.M.........X", "X...........X", "XXXXXXXXXXXXX", ] */ interface Position { x: number; y: number; } class Game { public gameBoardWidth: number; public gameBoardHeight: number; public mPosition: Position; public hPosition: Position; public container: string[] = []; constructor( gameBoardWidth: number, gameBoardHeight: number, mPosition: Position, hPosition: Position ) { this.gameBoardWidth = gameBoardWidth; this.gameBoardHeight = gameBoardHeight; this.mPosition = mPosition; this.hPosition = hPosition; this.render(); } public render() { for (let i = 0; i < this.gameBoardHeight; i++) { let wall: string = "X"; for (let j = 1; j < this.gameBoardWidth; j++) { if (i === 0 || i === this.gameBoardHeight - 1) { wall += "X"; } else { if (j === this.gameBoardWidth - 1) { wall += "X"; } else { if (i === this.mPosition.x && j === this.mPosition.y) { wall += "M"; } else if ( i === this.hPosition.x && j === this.hPosition.y ) { wall += "H"; } else { wall += "."; } } } } this.container.push(wall); } } } const m: Position = { x: 3, y: 2 }; const h: Position = { x: 1, y: 8 }; const game = new Game(13, 6, m, h); console.log(game);
0
0.605068
1
0.605068
game-dev
MEDIA
0.597012
game-dev,web-frontend
0.511957
1
0.511957
wopss/RED4ext.SDK
1,196
include/RED4ext/Scripting/Natives/Generated/quest/CharacterHit_ConditionType.hpp
#pragma once // clang-format off // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/DynArray.hpp> #include <RED4ext/Scripting/Natives/Generated/game/EntityReference.hpp> #include <RED4ext/Scripting/Natives/Generated/quest/CharacterHitEventType.hpp> #include <RED4ext/Scripting/Natives/Generated/quest/ICharacterConditionType.hpp> namespace RED4ext { namespace quest { struct CharacterHit_ConditionType : quest::ICharacterConditionType { static constexpr const char* NAME = "questCharacterHit_ConditionType"; static constexpr const char* ALIAS = NAME; game::EntityReference targetRef; // 78 bool isTargetPlayer; // B0 uint8_t unkB1[0xB8 - 0xB1]; // B1 DynArray<quest::CharacterHitEventType> includeHitTypes; // B8 DynArray<quest::CharacterHitEventType> excludeHitTypes; // C8 DynArray<CName> includeHitShapes; // D8 DynArray<CName> excludeHitShapes; // E8 }; RED4EXT_ASSERT_SIZE(CharacterHit_ConditionType, 0xF8); } // namespace quest using questCharacterHit_ConditionType = quest::CharacterHit_ConditionType; } // namespace RED4ext // clang-format on
0
0.690128
1
0.690128
game-dev
MEDIA
0.908689
game-dev
0.662788
1
0.662788
glKarin/com.n0n3m4.diii4a
306,105
Q3E/src/main/jni/doom3/neo/quake4/MultiplayerGame.cpp
// RAVEN BEGIN // ddynerman: note that this file is no longer merged with Doom3 updates // // MERGE_DATE 09/30/2004 #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" idCVar g_spectatorChat( "g_spectatorChat", "0", CVAR_GAME | CVAR_ARCHIVE | CVAR_BOOL, "let spectators talk to everyone during game" ); const char *idMultiplayerGame::MPGuis[] = { // RAVEN BEGIN // bdube: use regular hud for now "guis/hud.gui", // RAVEN END "guis/mpmain.gui", "guis/mpmsgmode.gui", "guis/netmenu.gui", "guis/mphud.gui", NULL }; const char *idMultiplayerGame::ThrottleVars[] = { "ui_spectate", "ui_ready", "ui_team", NULL }; const char *idMultiplayerGame::ThrottleVarsInEnglish[] = { "#str_106738", "#str_106737", "#str_101991", NULL }; const int idMultiplayerGame::ThrottleDelay[] = { 8, 5, 5 }; const char* idMultiplayerGame::teamNames[ TEAM_MAX ] = { "Marine", "Strogg" }; idCVar gui_ui_name( "gui_ui_name", "", CVAR_GAME | CVAR_NOCHEAT, "copy-over cvar for ui_name" ); /* ================ ComparePlayerByScore ================ */ int ComparePlayersByScore( const void* left, const void* right ) { return ((const rvPair<idPlayer*, int>*)right)->Second() - ((const rvPair<idPlayer*, int>*)left)->Second(); } /* ================ CompareTeamByScore ================ */ int CompareTeamsByScore( const void* left, const void* right ) { return ((const rvPair<int, int>*)right)->Second() - ((const rvPair<int, int>*)left)->Second(); } /* ================ idMultiplayerGame::idMultiplayerGame ================ */ idMultiplayerGame::idMultiplayerGame() { // RITUAL BEGIN // squirrel: Mode-agnostic buymenus buyMenu = NULL; // RITUAL END scoreBoard = NULL; statSummary = NULL; mainGui = NULL; mapList = NULL; msgmodeGui = NULL; defaultWinner = -1; deadZonePowerupCount = -1; marineScoreBarPulseAmount = 0.0f; stroggScoreBarPulseAmount = 0.0f; memset( lights, 0, sizeof( lights ) ); memset( lightHandles, -1, sizeof( lightHandles ) ); Clear(); for( int i = 0; i < TEAM_MAX; i++ ) { teamScore[ i ] = 0; flagEntities[ i ] = NULL; teamDeadZoneScore[i] = 0; } for( int i = 0; i < TEAM_MAX; i++ ) for( int j = 0; j < MAX_TEAM_POWERUPS; j++ ) { teamPowerups[i][j].powerup = 0; teamPowerups[i][j].time = 0; teamPowerups[i][j].endTime = 0; teamPowerups[i][j].update = false; } announcerSoundQueue.Clear(); announcerPlayTime = 0; gameState = NULL; currentSoundOverride = false; rankTextPlayer = NULL; privatePlayers = 0; lastAnnouncerSound = AS_NUM_SOUNDS; } /* ================ idMultiplayerGame::Shutdown ================ */ void idMultiplayerGame::Shutdown( void ) { Clear(); statManager->Shutdown(); if( gameState ) { delete gameState; } gameState = NULL; } /* ================ idMultiplayerGame::Reset ================ */ void idMultiplayerGame::Reset() { Clear(); assert( !scoreBoard && !mainGui && !mapList ); mpBuyingManager.Reset(); // RITUAL BEGIN // squirrel: Mode-agnostic buymenus buyMenu = uiManager->FindGui( "guis/buymenu.gui", true, false, true ); buyMenu->SetStateString( "field_credits", "$0.00"); buyMenu->SetStateBool( "gameDraw", true ); // RITUAL END PACIFIER_UPDATE; scoreBoard = uiManager->FindGui( "guis/scoreboard.gui", true, false, true ); #ifdef _XENON statSummary = scoreBoard; #else statSummary = uiManager->FindGui( "guis/summary.gui", true, false, true ); statSummary->SetStateBool( "gameDraw", true ); #endif PACIFIER_UPDATE; mainGui = uiManager->FindGui( "guis/mpmain.gui", true, false, true ); mapList = uiManager->AllocListGUI( ); mapList->Config( mainGui, "mapList" ); // set this GUI so that our Draw function is still called when it becomes the active/fullscreen GUI mainGui->SetStateBool( "gameDraw", true ); mainGui->SetKeyBindingNames(); mainGui->SetStateInt( "com_machineSpec", cvarSystem->GetCVarInteger( "com_machineSpec" ) ); // SetMenuSkin(); PACIFIER_UPDATE; msgmodeGui = uiManager->FindGui( "guis/mpmsgmode.gui", true, false, true ); msgmodeGui->SetStateBool( "gameDraw", true ); memset ( lights, 0, sizeof( lights ) ); memset ( lightHandles, -1, sizeof( lightHandles ) ); renderLight_t *light; const char *shader; light = &lights[ MPLIGHT_CTF_MARINE ]; shader = "lights/mpCTFLight"; if ( shader && *shader ) { light->axis.Identity(); light->shader = declManager->FindMaterial( shader, false ); light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = 64.0f; light->shaderParms[ SHADERPARM_RED ] = 142.0f / 255.0f; light->shaderParms[ SHADERPARM_GREEN ] = 190.0f / 255.0f; light->shaderParms[ SHADERPARM_BLUE ] = 84.0f / 255.0f; light->shaderParms[ SHADERPARM_ALPHA ] = 1.0f; light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; light->pointLight = true; light->noShadows = true; light->noDynamicShadows = true; light->lightId = -MPLIGHT_CTF_MARINE; light->allowLightInViewID = 0; } light = &lights[ MPLIGHT_CTF_STROGG ]; shader = "lights/mpCTFLight"; if ( shader && *shader ) { light->axis.Identity(); light->shader = declManager->FindMaterial( shader, false ); light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = 64.0f; light->shaderParms[ SHADERPARM_RED ] = 255.0f / 255.0f; light->shaderParms[ SHADERPARM_GREEN ] = 153.0f / 255.0f; light->shaderParms[ SHADERPARM_BLUE ] = 0.0f / 255.0f; light->shaderParms[ SHADERPARM_ALPHA ] = 1.0f; light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; light->pointLight = true; light->noShadows = true; light->noDynamicShadows = true; light->lightId = -MPLIGHT_CTF_STROGG; light->allowLightInViewID = 0; } light = &lights[ MPLIGHT_QUAD ]; shader = "lights/mpCTFLight"; if ( shader && *shader ) { light->axis.Identity(); light->shader = declManager->FindMaterial( shader, false ); light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = 64.0f; light->shaderParms[ SHADERPARM_RED ] = 0.0f; light->shaderParms[ SHADERPARM_GREEN ] = 128.0f / 255.0f; light->shaderParms[ SHADERPARM_BLUE ] = 255.0f / 255.0f; light->shaderParms[ SHADERPARM_ALPHA ] = 1.0f; light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; light->pointLight = true; light->noShadows = true; light->noDynamicShadows = true; light->lightId = -MPLIGHT_CTF_STROGG; light->allowLightInViewID = 0; } light = &lights[ MPLIGHT_HASTE ]; shader = "lights/mpCTFLight"; if ( shader && *shader ) { light->axis.Identity(); light->shader = declManager->FindMaterial( shader, false ); light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = 64.0f; light->shaderParms[ SHADERPARM_RED ] = 225.0f / 255.0f; light->shaderParms[ SHADERPARM_GREEN ] = 255.0f / 255.0f; light->shaderParms[ SHADERPARM_BLUE ] = 0.0f; light->shaderParms[ SHADERPARM_ALPHA ] = 1.0f; light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; light->pointLight = true; light->noShadows = true; light->noDynamicShadows = true; light->lightId = -MPLIGHT_CTF_STROGG; light->allowLightInViewID = 0; } light = &lights[ MPLIGHT_REGEN ]; shader = "lights/mpCTFLight"; if ( shader && *shader ) { light->axis.Identity(); light->shader = declManager->FindMaterial( shader, false ); light->lightRadius[0] = light->lightRadius[1] = light->lightRadius[2] = 64.0f; light->shaderParms[ SHADERPARM_RED ] = 255.0f / 255.0f; light->shaderParms[ SHADERPARM_GREEN ] = 0.0f; light->shaderParms[ SHADERPARM_BLUE ] = 0.0f; light->shaderParms[ SHADERPARM_ALPHA ] = 1.0f; light->detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; light->pointLight = true; light->noShadows = true; light->noDynamicShadows = true; light->lightId = -MPLIGHT_CTF_STROGG; light->allowLightInViewID = 0; } PACIFIER_UPDATE; ClearGuis(); //asalmon: Need to refresh stats periodically if the player is looking at stats currentStatClient = -1; currentStatTeam = 0; iconManager->Shutdown(); // update serverinfo UpdatePrivatePlayerCount(); lastReadyToggleTime = -1; cvarSystem->SetCVarBool( "s_voiceChatTest", false ); } /* ================ idMultiplayerGame::ServerClientConnect ================ */ void idMultiplayerGame::ServerClientConnect( int clientNum ) { memset( &playerState[ clientNum ], 0, sizeof( playerState[ clientNum ] ) ); statManager->ClientConnect( clientNum ); } /* ================ idMultiplayerGame::SpawnPlayer ================ */ void idMultiplayerGame::SpawnPlayer( int clientNum ) { TIME_THIS_SCOPE( __FUNCLINE__); bool ingame = playerState[ clientNum ].ingame; // keep ingame to true if needed, that should only happen for local player memset( &playerState[ clientNum ], 0, sizeof( playerState[ clientNum ] ) ); if ( !gameLocal.isClient ) { idPlayer *p = static_cast< idPlayer * >( gameLocal.entities[ clientNum ] ); p->spawnedTime = gameLocal.time; //if ( gameLocal.IsTeamGame() ) { // SwitchToTeam( clientNum, -1, p->team ); //} playerState[ clientNum ].ingame = ingame; } if ( clientNum == gameLocal.localClientNum ) { tourneyGUI.SetupTourneyGUI( gameLocal.GetLocalPlayer()->mphud, scoreBoard ); } lastVOAnnounce = 0; } /* ================ idMultiplayerGame::Clear ================ */ void idMultiplayerGame::Clear() { int i; pingUpdateTime = 0; vote = VOTE_NONE; voteTimeOut = 0; voteExecTime = 0; matchStartedTime = 0; memset( &playerState, 0 , sizeof( playerState ) ); currentMenu = 0; bCurrentMenuMsg = false; nextMenu = 0; pureReady = false; scoreBoard = NULL; buyMenu = NULL; isBuyingAllowedRightNow = false; statSummary = NULL; mainGui = NULL; msgmodeGui = NULL; if ( mapList ) { uiManager->FreeListGUI( mapList ); mapList = NULL; } memset( &switchThrottle, 0, sizeof( switchThrottle ) ); voiceChatThrottle = 0; voteValue.Clear(); voteString.Clear(); prevAnnouncerSnd = -1; localisedGametype.Clear(); for( i = 0; i < MAX_CLIENTS; i++ ) { kickVoteMapNames[ i ].Clear(); } for ( i = 0; i < MPLIGHT_MAX; i ++ ) { FreeLight( i ); } chatHistory.Clear(); rconHistory.Clear(); memset( rankedTeams, 0, sizeof( rvPair<int, int> ) * TEAM_MAX ); if( gameState ) { gameState->Clear(); } // RAVEN BEGIN // mwhitlock: Dynamic memory consolidation #if defined(_RV_MEM_SYS_SUPPORT) rankedPlayers.SetAllocatorHeap(rvGetSysHeap(RV_HEAP_ID_MULTIPLE_FRAME)); unrankedPlayers.SetAllocatorHeap(rvGetSysHeap(RV_HEAP_ID_MULTIPLE_FRAME)); assaultPoints.SetAllocatorHeap(rvGetSysHeap(RV_HEAP_ID_MULTIPLE_FRAME)); #endif // RAVEN END rankedPlayers.Clear(); unrankedPlayers.Clear(); assaultPoints.Clear(); ClearAnnouncerSounds(); rankTextPlayer = NULL; for ( i = 0; i < TEAM_MAX; i++ ) { flagEntities[ i ] = NULL; } } /* ================ idMultiplayerGame::ClearMap ================ */ void idMultiplayerGame::ClearMap( void ) { assaultPoints.Clear(); ClearAnnouncerSounds(); announcerPlayTime = 0; powerupCount = 0; marineScoreBarPulseAmount = 0.0f; stroggScoreBarPulseAmount = 0.0f; prevAnnouncerSnd = -1; for( int i = 0; i < TEAM_MAX; i++ ) for( int j = 0; j < MAX_TEAM_POWERUPS; j++ ) { teamPowerups[i][j].powerup = 0; teamPowerups[i][j].time = 0; teamPowerups[i][j].endTime = 0; teamPowerups[i][j].update = false; } // Dead Zone uses teamFragCount as the "player score" // so we need to clear it at the beginning of every round. if ( gameLocal.gameType == GAME_DEADZONE ) { for ( int i = 0; i < MAX_CLIENTS; i++ ) { playerState[i].teamFragCount = 0; playerState[i].deadZoneScore = 0; } } } /* ================ idMultiplayerGame::ClearGuis ================ */ void idMultiplayerGame::ClearGuis() { int i; for ( i = 0; i < MAX_CLIENTS; i++ ) { scoreBoard->SetStateString( va( "player%i",i+1 ), "" ); scoreBoard->SetStateString( va( "player%i_score", i+1 ), "" ); scoreBoard->SetStateString( va( "player%i_tdm_tscore", i+1 ), "" ); scoreBoard->SetStateString( va( "player%i_tdm_score", i+1 ), "" ); scoreBoard->SetStateString( va( "player%i_wins", i+1 ), "" ); scoreBoard->SetStateString( va( "player%i_status", i+1 ), "" ); scoreBoard->SetStateInt( va( "rank%i", i+1 ), 0 ); scoreBoard->SetStateInt( "rank_self", 0 ); idPlayer *player = static_cast<idPlayer *>( gameLocal.entities[ i ] ); if ( !player || !player->hud ) { continue; } player->hud->SetStateString( va( "player%i",i+1 ), "" ); player->hud->SetStateString( va( "player%i_score", i+1 ), "" ); player->hud->SetStateString( va( "player%i_ready", i+1 ), "" ); scoreBoard->SetStateInt( va( "rank%i", i+1 ), 0 ); player->hud->SetStateInt( "rank_self", 0 ); player->hud->SetStateInt( "team", TEAM_MARINE ); player->hud->HandleNamedEvent( "flagReturn" ); player->hud->SetStateInt( "team", TEAM_STROGG ); player->hud->HandleNamedEvent( "flagReturn" ); } ClearVote(); } /* ================ idMultiplayerGame::GetPlayerRank Returns the player rank (0 best), returning the best rank in the case of a tie ================ */ int idMultiplayerGame::GetPlayerRank( idPlayer* player, bool& isTied ) { int initialRank = -1; int rank = -1; for( int i = 0; i < rankedPlayers.Num(); i++ ) { if( rankedPlayers[ i ].First() == player ) { rank = i; initialRank = rank; } } if( rank == -1 ) { return rank; } if( rank > 0 ) { if( rankedPlayers[ rank - 1 ].Second() == rankedPlayers[ rank ].Second() ) { rank = rankedPlayers[ rank - 1 ].First()->GetRank(); } else { rank = rankedPlayers[ rank - 1 ].First()->GetRank() + 1; } } // check for tie isTied = false; for( int i = rank - 1; i <= rank + 1; i++ ) { if( i < 0 || i >= rankedPlayers.Num() || rankedPlayers[ i ].First() == player ) { continue; } if( rankedPlayers[ i ].Second() == rankedPlayers[ initialRank ].Second() ) { isTied = true; break; } } return rank; } /* ================ idMultiplayerGame::UpdatePlayerRanks ================ */ void idMultiplayerGame::UpdatePlayerRanks( playerRankMode_t rankMode ) { idEntity* ent = NULL; if( rankMode == PRM_AUTO ) { if( gameLocal.IsTeamGame() ) { rankMode = PRM_TEAM_SCORE_PLUS_SCORE; } else if ( gameLocal.gameType == GAME_TOURNEY ) { rankMode = PRM_WINS; } else { rankMode = PRM_SCORE; } } rankedPlayers.Clear(); unrankedPlayers.Clear(); for ( int i = 0; i < gameLocal.numClients; i++ ) { ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer* player = (idPlayer*)ent; if ( !CanPlay( player ) ) { unrankedPlayers.Append( player ); } else { int rankingValue = 0; switch( rankMode ) { case PRM_SCORE: { rankingValue = GetScore( player ); break; } case PRM_TEAM_SCORE: { rankingValue = GetTeamScore( player ); break; } case PRM_TEAM_SCORE_PLUS_SCORE: { rankingValue = GetScore( player ) + GetTeamScore( player ); break; } case PRM_WINS: { rankingValue = GetWins( player ); break; } default: { gameLocal.Error( "idMultiplayerGame::UpdatePlayerRanks() - Bad ranking mode '%d'\n", rankMode ); } } rankedPlayers.Append( rvPair<idPlayer*, int>(player, rankingValue ) ); } } qsort( rankedPlayers.Ptr(), rankedPlayers.Num(), rankedPlayers.TypeSize(), ComparePlayersByScore ); for( int i = 0; i < rankedPlayers.Num(); i++ ) { bool tied; rankedPlayers[ i ].First()->SetRank( GetPlayerRank( rankedPlayers[ i ].First(), tied ) ); } for( int i = 0; i < unrankedPlayers.Num(); i++ ) { unrankedPlayers[ i ]->SetRank( -1 ); } } /* ================ idMultiplayerGame::UpdateTeamRanks ================ */ void idMultiplayerGame::UpdateTeamRanks( void ) { for ( int i = 0; i < TEAM_MAX; i++ ) { rankedTeams[ i ] = rvPair<int, int>( i, teamScore[ i ] ); } qsort( rankedTeams, TEAM_MAX, sizeof( rvPair<int, int> ), CompareTeamsByScore ); } /* ================ idMultiplayerGame::UpdateRankColor ================ */ void idMultiplayerGame::UpdateRankColor( idUserInterface *gui, const char *mask, int i, const idVec3 &vec ) { for ( int j = 1; j < 4; j++ ) { gui->SetStateFloat( va( mask, i, j ), vec[ j - 1 ] ); } } /* ================ idMultiplayerGame::CanCapture Determines if the given flag can be captured in the given gamestate ================ */ bool idMultiplayerGame::CanCapture( int team ) { // no AP's in one flag if( gameLocal.gameType == GAME_1F_CTF || gameLocal.gameType == GAME_ARENA_1F_CTF ) { return true; } else if( gameLocal.gameType != GAME_CTF && gameLocal.gameType != GAME_ARENA_CTF ) { return false; // no flag caps in none-CTF games } if ( !assaultPoints.Num() ) { return true; } // since other logic ensures AP's are captured in order, we just need to check the last AP before the enemy flag if ( team == TEAM_STROGG ) { // AP 0 is always next to the marine flag return ((rvCTFGameState*)gameState)->GetAPOwner( 0 ) == TEAM_STROGG; } if ( team == TEAM_MARINE ) { // the last AP is always the one next to the strogg flag return ((rvCTFGameState*)gameState)->GetAPOwner( assaultPoints.Num() - 1 ) == TEAM_MARINE; } return false; } void idMultiplayerGame::FlagCaptured( idPlayer *player ) { if( !gameLocal.isClient ) { AddTeamScore( player->team, 1 ); AddPlayerTeamScore( player, 5 ); // RITUAL BEGIN // squirrel: Mode-agnostic buymenus if( gameLocal.mpGame.IsBuyingAllowedInTheCurrentGameMode() ) { float teamCashAward = (float) gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "teamCashAward_flagCapture", 0 ); GiveCashToTeam( player->team, teamCashAward ); float cashAward = (float) gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "playerCashAward_flagCapture", 0 ); player->GiveCash( cashAward ); } // RITUAL END gameLocal.ClearForwardSpawns(); for( int i = 0; i < assaultPoints.Num(); i++ ) { assaultPoints[ i ]->Reset(); ((rvCTFGameState*)gameState)->SetAPOwner( i, AS_NEUTRAL ); } statManager->FlagCaptured( player, OpposingTeam( player->team ) ); player->SetEmote( PE_CHEER ); } } /* ================ idMultiplayerGame::SendDeathMessage ================ */ void idMultiplayerGame::SendDeathMessage( idPlayer* attacker, idPlayer* victim, int methodOfDeath ) { if( !gameLocal.isClient ) { idBitMsg outMsg; byte msgBuf[1024]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_DEATH ); if( attacker ) { outMsg.WriteByte( attacker->entityNumber ); outMsg.WriteBits( idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, playerState[ attacker->entityNumber ].fragCount ), ASYNC_PLAYER_FRAG_BITS ); } else { outMsg.WriteByte( 255 ); } if( victim ) { outMsg.WriteByte( victim->entityNumber ); outMsg.WriteBits( idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, playerState[ victim->entityNumber ].fragCount ), ASYNC_PLAYER_FRAG_BITS ); } else { outMsg.WriteByte( 255 ); } outMsg.WriteByte( methodOfDeath ); gameLocal.ServerSendInstanceReliableMessage( victim, -1, outMsg ); if( gameLocal.isListenServer && gameLocal.GetLocalPlayer() && victim && gameLocal.GetLocalPlayer()->GetInstance() == victim->GetInstance() ) { // This is for listen servers, which won't get to ClientProcessReliableMessage ReceiveDeathMessage( attacker, attacker ? playerState[ attacker->entityNumber ].fragCount : -1, victim, victim ? playerState[ victim->entityNumber ].fragCount : -1, methodOfDeath ); } } } /* ================ idMultiplayerGame::ReceiveDeathMessage ================ */ void idMultiplayerGame::ReceiveDeathMessage( idPlayer *attacker, int attackerScore, idPlayer *victim, int victimScore, int methodOfDeath ) { if( gameLocal.GetLocalPlayer() == NULL ) { return; } // RITUAL BEGIN // squirrel: force buy menu open when you die //if( gameLocal.IsMultiplayer() && gameLocal.mpGame.IsBuyingAllowedInTheCurrentGameMode() && victim == gameLocal.GetLocalPlayer() ) //{ // OpenLocalBuyMenu(); //} // RITUAL END const char* icon = ""; // if methodOfDeath is in range [0, MAX_WEAPONS - 1] it refers to a specific weapon. MAX_WEAPONS refers to // a generic or unknown death (i.e. "Killer killed victim") and values above MAX_WEAPONS + 1 refer // to other non-weapon deaths (i.e. telefrags) // setup to either use weapon icons for a weapon death, or generic death icons if ( methodOfDeath < MAX_WEAPONS ) { icon = va( "w%02d", methodOfDeath ); } else { icon = va( "dm%d", methodOfDeath - MAX_WEAPONS ); } char* message = NULL; if ( gameLocal.IsTeamGame() ) { idStr attackerStr( ( attacker ? gameLocal.userInfo[ attacker->entityNumber ].GetString( "ui_name" ) : "" ) ); idStr victimStr( ( victim ? gameLocal.userInfo[ victim->entityNumber ].GetString( "ui_name" ) : "" ) ); attackerStr.RemoveEscapes(); victimStr.RemoveEscapes(); message = va ( "%s%s ^r^i%s %s%s", (attacker ? (attacker->team ? S_COLOR_STROGG : S_COLOR_MARINE) : ""), attackerStr.c_str(), icon, (victim ? (victim->team ? S_COLOR_STROGG : S_COLOR_MARINE) : ""), victimStr.c_str() ); } else { message = va ( "%s ^r^i%s %s", (attacker ? gameLocal.userInfo[ attacker->entityNumber ].GetString( "ui_name" ) : ""), icon, (victim ? gameLocal.userInfo[ victim->entityNumber ].GetString( "ui_name" ) : "") ); } if( gameLocal.GetLocalPlayer()->hud ) { gameLocal.GetLocalPlayer()->hud->SetStateString ( "deathinfo", message ); gameLocal.GetLocalPlayer()->hud->HandleNamedEvent ( "addDeathLine" ); } // echo to console gameLocal.Printf( gameLocal.GetLocalPlayer()->spawnArgs.GetString( va( "%s_text", icon ), "%s killed %s" ), (victim ? gameLocal.userInfo[ victim->entityNumber ].GetString( "ui_name" ) : "world"), (attacker ? gameLocal.userInfo[ attacker->entityNumber ].GetString( "ui_name" ) : "world") ); gameLocal.Printf( "\n" ); // display message on hud if( attacker && victim && (gameLocal.GetLocalPlayer() == attacker || gameLocal.GetLocalPlayer() == victim) && attacker != victim && methodOfDeath < MAX_WEAPONS ) { if( gameLocal.GetLocalPlayer() == attacker ) { // RAVEN BEGIN // rhummer: Added lang entries for "You fragged %s" and "You were fragged by %s" (gameLocal.GetLocalPlayer())->GUIFragNotice( va( common->GetLocalizedString( "#str_107295" ), gameLocal.userInfo[ victim->entityNumber ].GetString( "ui_name" ) ) ); } else { (gameLocal.GetLocalPlayer())->GUIFragNotice( va( common->GetLocalizedString( "#str_107296" ), gameLocal.userInfo[ attacker->entityNumber ].GetString( "ui_name" ) ) ); // RAVEN END } if( gameLocal.gameType == GAME_DM ) { // print rank text next time after we update scores // stash the scores on the client so we can print accurate rank info if( gameLocal.isClient ) { if( victim ) { playerState[ victim->entityNumber ].fragCount = victimScore; } if( attacker ) { playerState[ attacker->entityNumber ].fragCount = attackerScore; } } if( victim && (gameLocal.GetLocalPlayer() == victim || (gameLocal.GetLocalPlayer()->spectating && gameLocal.GetLocalPlayer()->spectator == victim->entityNumber)) ) { rankTextPlayer = victim; } if( attacker && (gameLocal.GetLocalPlayer() == attacker || (gameLocal.GetLocalPlayer()->spectating && gameLocal.GetLocalPlayer()->spectator == attacker->entityNumber)) ) { rankTextPlayer = attacker; } } } } // ddynerman: Gametype specific scoreboard /* ================ idMultiplayerGame::UpdateScoreboard ================ */ void idMultiplayerGame::UpdateScoreboard( idUserInterface *scoreBoard ) { scoreBoard->SetStateInt( "gametype", gameLocal.gameType ); //statManager->UpdateInGameHud( scoreBoard, true ); if( gameLocal.IsTeamGame() ) { UpdateTeamScoreboard( scoreBoard ); } else { UpdateDMScoreboard( scoreBoard ); } return; } /* ================ idMultiplayerGame::UpdateDMScoreboard ================ */ void idMultiplayerGame::UpdateDMScoreboard( idUserInterface *scoreBoard ) { idPlayer* player = gameLocal.GetLocalPlayer(); int i; // bdube: mechanism for testing the scoreboard (populates it with fake names, pings, etc) if ( g_testScoreboard.GetInteger() > 0 ) { UpdateTestScoreboard ( scoreBoard ); return; } if( !player ) { return; } scoreBoard->SetStateString( "scores_sel_0", "-1" ); scoreBoard->SetStateString( "spectator_scores_sel_0", "-1" ); bool useReady = (gameLocal.serverInfo.GetBool( "si_useReady" ) && gameLocal.mpGame.GetGameState()->GetMPGameState() == WARMUP); if( gameLocal.gameType == GAME_DM ) { for ( i = 0; i < MAX_CLIENTS; i++ ) { if( i < rankedPlayers.Num() ) { // ranked player idPlayer* rankedPlayer = rankedPlayers[ i ].First(); int rankedScore = rankedPlayers[ i ].Second(); if ( rankedPlayer == gameLocal.GetLocalPlayer() ) { // highlight who we are scoreBoard->SetStateInt( "scores_sel_0", i ); } scoreBoard->SetStateString ( va("scores_item_%i", i), va("%s\t%s\t%s\t%s\t%s\t%i\t%i\t%i\t", ( useReady ? (rankedPlayer->IsReady() ? I_READY : I_NOT_READY) : "" ), // ready icon ( player->IsPlayerMuted( rankedPlayer ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( rankedPlayer ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon rankedPlayer->GetUserInfo()->GetString( "ui_name" ), // name rankedPlayer->GetUserInfo()->GetString( "ui_clan" ), // clan rankedScore, // score GetPlayerTime( rankedPlayer ), // time playerState[ rankedPlayer->entityNumber ].ping ) ); // ping } else { scoreBoard->SetStateString ( va("scores_item_%i", i), "" ); scoreBoard->SetStateBool( va( "scores_item_%i_greyed", i ), false ); } if( i < unrankedPlayers.Num() ) { if ( unrankedPlayers[ i ] == gameLocal.GetLocalPlayer() ) { // highlight who we are scoreBoard->SetStateInt( "spectator_scores_sel_0", i ); } scoreBoard->SetStateString ( va("spectator_scores_item_%i", i), va("%s\t%s\t%s\t%s\t%s\t%i\t%i\t", ( player->spectator && player->IsPlayerMuted( unrankedPlayers[ i ] ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( unrankedPlayers[ i ] ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon unrankedPlayers[ i ]->GetUserInfo()->GetString( "ui_name" ), // name unrankedPlayers[ i ]->GetUserInfo()->GetString( "ui_clan" ), // clan "", // score GetPlayerTime( unrankedPlayers[ i ] ), // time playerState[ unrankedPlayers[ i ]->entityNumber ].ping ) ); // ping } else { scoreBoard->SetStateString ( va("spectator_scores_item_%i", i), "" ); scoreBoard->SetStateBool( va( "scores_item_%i_greyed", i ), false ); } } } else if( gameLocal.gameType == GAME_TOURNEY ) { // loop through twice listing players who are playing, then players who have been eliminated int listIndex = 0; for ( i = 0; i < rankedPlayers.Num(); i++ ) { // ranked player idPlayer* rankedPlayer = rankedPlayers[ i ].First(); int rankedScore = rankedPlayers[ i ].Second(); if( rankedPlayer->GetTourneyStatus() == PTS_ELIMINATED ) { continue; } if ( rankedPlayer == gameLocal.GetLocalPlayer() ) { // highlight who we are scoreBoard->SetStateInt( "scores_sel_0", listIndex ); } scoreBoard->SetStateString ( va("scores_item_%i", listIndex), va("%s\t%s\t%s\t%s\t%s\t%i\t%i\t%s\t", ( useReady ? (rankedPlayer->IsReady() ? I_READY : I_NOT_READY) : "" ), // ready icon ( player->IsPlayerMuted( rankedPlayer ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( rankedPlayer ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon rankedPlayer->GetUserInfo()->GetString( "ui_name" ), // name rankedPlayer->GetUserInfo()->GetString( "ui_clan" ), // clan rankedScore, // score playerState[ rankedPlayer->entityNumber ].ping, // ping rankedPlayer->GetTextTourneyStatus() ) ); // tourney status scoreBoard->SetStateBool( va( "scores_item_%i_greyed", listIndex ), false ); listIndex++; } for ( i = 0; i < rankedPlayers.Num(); i++ ) { // ranked player idPlayer* rankedPlayer = rankedPlayers[ i ].First(); int rankedScore = rankedPlayers[ i ].Second(); if( rankedPlayer->GetTourneyStatus() != PTS_ELIMINATED ) { continue; } if ( rankedPlayer == gameLocal.GetLocalPlayer() ) { // highlight who we are scoreBoard->SetStateInt( "scores_sel_0", listIndex ); } scoreBoard->SetStateString ( va("scores_item_%i", listIndex), va("%s\t%s\t%s\t%s\t%s\t%i\t%i\t%s\t", ( useReady ? (rankedPlayer->IsReady() ? I_READY : I_NOT_READY) : "" ), // ready icon ( player->IsPlayerMuted( rankedPlayer ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( rankedPlayer ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon rankedPlayer->GetUserInfo()->GetString( "ui_name" ), // name rankedPlayer->GetUserInfo()->GetString( "ui_clan" ), // clan rankedScore, // score playerState[ rankedPlayer->entityNumber ].ping, // ping rankedPlayer->GetTextTourneyStatus() ) ); // tourney status scoreBoard->SetStateBool( va( "scores_item_%i_greyed", listIndex ), true ); listIndex++; } for( i = 0; i < MAX_CLIENTS; i++ ) { if( i < unrankedPlayers.Num() ) { if ( unrankedPlayers[ i ] == gameLocal.GetLocalPlayer() ) { // highlight who we are scoreBoard->SetStateInt( "spectator_scores_sel_0", i ); } scoreBoard->SetStateString ( va("spectator_scores_item_%i", i), va("%s\t%s\t%s\t%s\t%s\t%i\t%s\t", ( player->spectator && player->IsPlayerMuted( unrankedPlayers[ i ] ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( unrankedPlayers[ i ] ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon unrankedPlayers[ i ]->GetUserInfo()->GetString( "ui_name" ), // name unrankedPlayers[ i ]->GetUserInfo()->GetString( "ui_clan" ), // clan "", // score playerState[ unrankedPlayers[ i ]->entityNumber ].ping, // ping "" ) ); } else { scoreBoard->SetStateString( va( "spectator_scores_item_%i", i ), "" ); } } for( i = listIndex; i < MAX_CLIENTS; i++ ) { scoreBoard->SetStateString( va( "scores_item_%i", i ), "" ); scoreBoard->SetStateBool( va( "scores_item_%i_greyed", i ), false ); } } scoreBoard->SetStateInt ( "num_players", idMath::ClampInt( 0, 16, rankedPlayers.Num() ) ); scoreBoard->SetStateInt ( "num_spec_players", idMath::ClampInt( 0, 16, unrankedPlayers.Num() ) ); scoreBoard->SetStateInt ( "num_total_players", idMath::ClampInt( 0, 16, rankedPlayers.Num() + unrankedPlayers.Num() ) ); idStr serverAddress = networkSystem->GetServerAddress(); scoreBoard->SetStateString( "servername", gameLocal.serverInfo.GetString( "si_name" ) ); scoreBoard->SetStateString( "position_text", GetPlayerRankText( gameLocal.GetLocalPlayer() ) ); // shouchard: added map name // mekberg: localized string const char *mapName = gameLocal.serverInfo.GetString( "si_map" ); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } scoreBoard->SetStateString( "servermap", mapName ); scoreBoard->SetStateString( "serverip", serverAddress.c_str() ); scoreBoard->SetStateString( "servergametype", GetLongGametypeName( gameLocal.serverInfo.GetString( "si_gameType" ) ) ); scoreBoard->SetStateString( "servertimelimit", va( "%s: %d", common->GetLocalizedString( "#str_107659" ), gameLocal.serverInfo.GetInt( "si_timeLimit" ) ) ); scoreBoard->SetStateString( "serverlimit", va( "%s: %d", common->GetLocalizedString( "#str_107660" ), gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) ); int timeLimit = gameLocal.serverInfo.GetInt( "si_timeLimit" ); mpGameState_t state = gameState->GetMPGameState(); bool inNonTimedState = (state == SUDDENDEATH) || (state == WARMUP) || (state == GAMEREVIEW); if( gameLocal.gameType == GAME_TOURNEY ) { if( gameLocal.serverInfo.GetInt( "si_fragLimit" ) == 1 ) { // stupid english plurals scoreBoard->SetStateString( "tourney_frag_count", va( common->GetLocalizedString( "#str_107712" ), gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) ); } else { scoreBoard->SetStateString( "tourney_frag_count", va( common->GetLocalizedString( "#str_107715" ), gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) ); } scoreBoard->SetStateString( "tourney_count", va( common->GetLocalizedString( "#str_107713" ), ((rvTourneyGameState*)gameState)->GetTourneyCount(), gameLocal.serverInfo.GetInt( "si_tourneyLimit" ) ) ); if( gameLocal.GetLocalPlayer() ) { inNonTimedState |= ((rvTourneyGameState*)gameState)->GetArena( gameLocal.GetLocalPlayer()->GetArena() ).GetState() == AS_SUDDEN_DEATH; } } scoreBoard->SetStateString( "timeleft", GameTime() ); scoreBoard->SetStateBool( "infinity", ( !timeLimit && state != COUNTDOWN ) || inNonTimedState ); scoreBoard->StateChanged ( gameLocal.time ); scoreBoard->Redraw( gameLocal.time ); } /* ================ idMultiplayerGame::UpdateTeamScoreboard ================ */ // only output 16 clients onto the scoreboard #define SCOREBOARD_MAX_CLIENTS 16 void idMultiplayerGame::UpdateTeamScoreboard( idUserInterface *scoreBoard ) { idStr gameinfo; int numTeamEntries[ TEAM_MAX ]; idPlayer* player = gameLocal.GetLocalPlayer(); // bdube: mechanism for testing the scoreboard (populates it with fake names, pings, etc) if ( g_testScoreboard.GetInteger() > 0 ) { UpdateTestScoreboard ( scoreBoard ); return; } if( !player ) { return; } SIMDProcessor->Memset( numTeamEntries, 0, sizeof( int ) * TEAM_MAX ); scoreBoard->SetStateString( "team_0_scores_sel_0", "-1" ); scoreBoard->SetStateString( "team_1_scores_sel_0", "-1" ); scoreBoard->SetStateString( "spectator_scores_sel_0", "-1" ); bool useReady = (gameLocal.serverInfo.GetBool( "si_useReady" ) && gameLocal.mpGame.GetGameState()->GetMPGameState() == WARMUP); for ( int i = 0; i < SCOREBOARD_MAX_CLIENTS; i++ ) { if( i < rankedPlayers.Num() ) { // ranked player idPlayer* rankedPlayer = rankedPlayers[ i ].First(); int rankedScore = rankedPlayers[ i ].Second(); if ( rankedPlayer == gameLocal.GetLocalPlayer() ) { // highlight who we are scoreBoard->SetStateInt( va("team_%i_scores_sel_0", rankedPlayer->team ), numTeamEntries[ rankedPlayer->team ] ); } // RAVEN BEGIN // mekberg: redid this if ( gameLocal.gameType == GAME_TDM ) { scoreBoard->SetStateString ( va("team_%i_scores_item_%i", rankedPlayer->team, numTeamEntries[ rankedPlayer->team ]), va("%s\t%s\t%s\t%s\t%s\t%i\t%i\t%i\t", ( useReady ? (rankedPlayer->IsReady() ? I_READY : I_NOT_READY) : "" ), // ready icon ( player->IsPlayerMuted( rankedPlayer ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( rankedPlayer ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon rankedPlayer->GetUserInfo()->GetString( "ui_name" ), // name rankedPlayer->GetUserInfo()->GetString( "ui_clan" ), // clan rankedScore, // score GetPlayerTime( rankedPlayer ), // time playerState[ rankedPlayer->entityNumber ].ping ) ); // ping numTeamEntries[ rankedPlayer->team ]++; } //else if ( gameLocal.gameType == GAME_DEADZONE ) //{ // // mekberg: made this check slightly more sane. // const char* flagString = ""; // if ( rankedPlayer->PowerUpActive( rankedPlayer->team ? POWERUP_CTF_MARINEFLAG : POWERUP_CTF_STROGGFLAG ) ) { // flagString = ( rankedPlayer->team ? I_FLAG_MARINE : I_FLAG_STROGG ); // } else if ( gameLocal.gameType == GAME_ARENA_CTF && gameLocal.GetLocalPlayer() && rankedPlayer->team == gameLocal.GetLocalPlayer()->team ) { // flagString = rankedPlayer->GetArenaPowerupString( ); // } // scoreBoard->SetStateString ( // va("team_%i_scores_item_%i", rankedPlayer->team, numTeamEntries[ rankedPlayer->team ]), // va("%s\t%s\t%s\t%s\t%s\t%s\t%.01f\t%i\t%i\t%i\t", // ( useReady ? (rankedPlayer->IsReady() ? I_READY : I_NOT_READY) : "" ), // ready icon // ( player->IsPlayerMuted( rankedPlayer ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon // ( player->IsFriend( rankedPlayer ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon // flagString, // shouchard: twhitaker: updated steve's original flag system // rankedPlayer->GetUserInfo()->GetString( "ui_name" ), // name // rankedPlayer->GetUserInfo()->GetString( "ui_clan" ), // clan // rankedScore * 0.1f, // score // playerState[ rankedPlayer->entityNumber ].fragCount, // kills // GetPlayerTime( rankedPlayer ), // time // playerState[ rankedPlayer->entityNumber ].ping ) ); // ping // numTeamEntries[ rankedPlayer->team ]++; //} else { // mekberg: made this check slightly more sane. const char* flagString = ""; if ( rankedPlayer->PowerUpActive( rankedPlayer->team ? POWERUP_CTF_MARINEFLAG : POWERUP_CTF_STROGGFLAG ) ) { flagString = ( rankedPlayer->team ? I_FLAG_MARINE : I_FLAG_STROGG ); } else if ( gameLocal.gameType == GAME_ARENA_CTF && gameLocal.GetLocalPlayer() && rankedPlayer->team == gameLocal.GetLocalPlayer()->team ) { flagString = rankedPlayer->GetArenaPowerupString( ); } scoreBoard->SetStateString ( va("team_%i_scores_item_%i", rankedPlayer->team, numTeamEntries[ rankedPlayer->team ]), va("%s\t%s\t%s\t%s\t%s\t%s\t%i\t%i\t%i\t%i\t", ( useReady ? (rankedPlayer->IsReady() ? I_READY : I_NOT_READY) : "" ), // ready icon ( player->IsPlayerMuted( rankedPlayer ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( rankedPlayer ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon flagString, // shouchard: twhitaker: updated steve's original flag system rankedPlayer->GetUserInfo()->GetString( "ui_name" ), // name rankedPlayer->GetUserInfo()->GetString( "ui_clan" ), // clan rankedScore, // score playerState[ rankedPlayer->entityNumber ].fragCount, // kills GetPlayerTime( rankedPlayer ), // time playerState[ rankedPlayer->entityNumber ].ping ) ); // ping numTeamEntries[ rankedPlayer->team ]++; } // RAVEN END } if( i < unrankedPlayers.Num() ) { if ( unrankedPlayers[ i ] == gameLocal.GetLocalPlayer() ) { // highlight who we are scoreBoard->SetStateInt( "spectator_scores_sel_0", i ); } // RAVEN BEGIN // mekberg: redid this scoreBoard->SetStateString ( va("spectator_scores_item_%i", i), va("%s\t%s\t%s\t%s\t%s\t%i\t%i\t", ( player->spectating && player->IsPlayerMuted( unrankedPlayers[ i ] ) ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( player->IsFriend( unrankedPlayers[ i ] ) ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon unrankedPlayers[ i ]->GetUserInfo()->GetString( "ui_name" ), // name unrankedPlayers[ i ]->GetUserInfo()->GetString( "ui_clan" ), // clan "", // score GetPlayerTime( unrankedPlayers[ i ] ), // time playerState[ unrankedPlayers[ i ]->entityNumber ].ping ) ); // ping // ping // RAVEN END } else { scoreBoard->SetStateString ( va("spectator_scores_item_%i", i), "" ); } } // clear unused space for( int k = 0; k < TEAM_MAX; k++ ) { for( int i = numTeamEntries[ k ]; i < MAX_CLIENTS; i++ ) { scoreBoard->SetStateString ( va("team_%i_scores_item_%i", k, i), "" ); } } scoreBoard->SetStateInt ( "playerteam", gameLocal.GetLocalPlayer()->team ); scoreBoard->SetStateInt ( "strogg_score", teamScore[ TEAM_STROGG ] ); scoreBoard->SetStateInt ( "marine_score", teamScore[ TEAM_MARINE ] ); scoreBoard->SetStateInt ( "num_strogg_players", idMath::ClampInt( 0, 16, numTeamEntries[ TEAM_STROGG ] ) ); scoreBoard->SetStateInt ( "num_marine_players", idMath::ClampInt( 0, 16, numTeamEntries[ TEAM_MARINE ] ) ); scoreBoard->SetStateInt ( "num_players", idMath::ClampInt( 0, 16, numTeamEntries[ TEAM_STROGG ] + numTeamEntries[ TEAM_MARINE ] ) ); scoreBoard->SetStateInt ( "num_total_players", idMath::ClampInt( 0, 16, numTeamEntries[ TEAM_STROGG ] + numTeamEntries[ TEAM_MARINE ] + unrankedPlayers.Num() ) ); scoreBoard->SetStateInt ( "num_spec_players", idMath::ClampInt( 0, 16, unrankedPlayers.Num() ) ); idStr serverAddress = networkSystem->GetServerAddress(); scoreBoard->SetStateString( "servername", gameLocal.serverInfo.GetString( "si_name" ) ); // RAVEN BEGIN // shouchard: added map name // mekberg: get localized string. const char *mapName = gameLocal.serverInfo.GetString( "si_map" ); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } scoreBoard->SetStateString( "servermap", mapName ); // RAVEN END scoreBoard->SetStateString( "serverip", serverAddress.c_str() ); scoreBoard->SetStateString( "servergametype", GetLongGametypeName( gameLocal.serverInfo.GetString( "si_gameType" ) ) ); scoreBoard->SetStateString( "servertimelimit", va( "%s: %d", common->GetLocalizedString( "#str_107659" ), gameLocal.serverInfo.GetInt( "si_timeLimit" ) ) ); if ( gameLocal.IsFlagGameType() ) { scoreBoard->SetStateString( "serverlimit", va( "%s: %d", common->GetLocalizedString( "#str_107661" ), gameLocal.serverInfo.GetInt( "si_captureLimit" ) ) ); } else if ( gameLocal.gameType == GAME_DEADZONE ) { scoreBoard->SetStateString( "serverlimit", va( "%s: %d", common->GetLocalizedString( "#str_122008" ), gameLocal.serverInfo.GetInt( "si_controlTime" ) ) ); } else { scoreBoard->SetStateString( "serverlimit", va( "%s: %d", common->GetLocalizedString( "#str_107660" ), gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) ); } scoreBoard->SetStateString( "timeleft", GameTime() ); int timeLimit = gameLocal.serverInfo.GetInt( "si_timeLimit" ); mpGameState_t state = gameState->GetMPGameState(); scoreBoard->SetStateBool( "infinity", ( !timeLimit && state != COUNTDOWN ) || state == WARMUP || state == GAMEREVIEW || state == SUDDENDEATH ); scoreBoard->StateChanged( gameLocal.time ); scoreBoard->Redraw( gameLocal.time ); } /* ================ idMultiplayerGame::BuildSummaryListString Returns a summary string for the specified player ================ */ const char* idMultiplayerGame::BuildSummaryListString( idPlayer* player, int rankedScore ) { // track top 3 accuracies rvPlayerStat* stat = statManager->GetPlayerStat( player->entityNumber ); idList<rvPair<int, float> > bestAccuracies; for( int j = 0; j < MAX_WEAPONS; j++ ) { // only consider weapons we fired more than a few shots if( stat->weaponShots[ j ] <= 10 ) { continue; } float accuracy = (float)stat->weaponHits[ j ] / (float)stat->weaponShots[ j ]; bestAccuracies.Append( rvPair<int, float>( j, accuracy ) ); } bestAccuracies.Sort( rvPair<int, float>::rvPairSecondCompareDirect ); // hold upto 3 top weapons at 5 chars each idStr weaponString; for( int j = 0; j < 3; j++ ) { if( j >= bestAccuracies.Num() ) { continue; } weaponString += va( "^iw%02d", bestAccuracies[ j ].First() ); } return va("%d. %s\t%s\t%d\t%s\t", player->GetRank() + 1, player->GetUserInfo()->GetString( "ui_name" ), // name player->GetUserInfo()->GetString( "ui_clan" ), // clan rankedScore, // score weaponString.c_str() ); } /* ================ idMultiplayerGame::UpdateSummaryBoard Shows top 10 players if local player is in top 10, otherwise shows top 9 and localplayer ================ */ void idMultiplayerGame::UpdateSummaryBoard( idUserInterface *scoreBoard ) { idPlayer* player = gameLocal.GetLocalPlayer(); if( !player ) { return; } int playerIndex = -1; // update our ranks in case we call this the same frame it happens UpdatePlayerRanks(); // highlight top 3 players idVec4 blueHighlight = idStr::ColorForIndex( C_COLOR_BLUE ); idVec4 redHighlight = idStr::ColorForIndex( C_COLOR_RED ); idVec4 yellowHighlight = idStr::ColorForIndex( C_COLOR_YELLOW ); blueHighlight[ 3 ] = 0.15f; redHighlight[ 3 ] = 0.15f; yellowHighlight[ 3 ] = 0.15f; if( gameLocal.IsTeamGame() ) { scoreBoard->HandleNamedEvent( teamScore[ TEAM_MARINE ] > teamScore[ TEAM_STROGG ] ? "marine_wins" : "strogg_wins" ); // summary is top 5 players on each team int lastHighIndices[ TEAM_MAX ]; memset( lastHighIndices, 0, sizeof( int ) * TEAM_MAX ); for( int i = 0; i < 5; i++ ) { scoreBoard->SetStateString ( va( "%s_item_%i", "summary_marine_names", i ), "" ); scoreBoard->SetStateString ( va( "%s_item_%i", "summary_strogg_names", i ), "" ); } for( int i = 0; i < TEAM_MAX; i++ ) { for( int j = 0; j < 5; j++ ) { idPlayer* rankedPlayer = NULL; int rankedScore = 0; int k; for( k = lastHighIndices[ i ]; k < rankedPlayers.Num(); k++ ) { if( rankedPlayers[ k ].First()->team == i ) { rankedPlayer = rankedPlayers[ k ].First(); rankedScore = rankedPlayers[ k ].Second(); break; } } // no more teammates if( k >= rankedPlayers.Num() ) { break; } if( j == 4 && playerIndex == -1 && player->team == i ) { int z; for( z = 0; z < rankedPlayers.Num(); z++ ) { if( rankedPlayers[ z ].First() == player ) { rankedPlayer = player; rankedScore = rankedPlayers[ z ].Second(); break; } } } if ( rankedPlayer == gameLocal.GetLocalPlayer() ) { // highlight who we are playerIndex = j; } scoreBoard->SetStateString ( va( "%s_item_%i", i == TEAM_MARINE ? "summary_marine_names" : "summary_strogg_names", j ), BuildSummaryListString( rankedPlayer, rankedScore ) ); lastHighIndices[ i ] = k + 1; } } if( playerIndex > 0 ) { if( player->team == TEAM_MARINE ) { scoreBoard->SetStateInt( "summary_marine_names_sel_0", playerIndex ); scoreBoard->SetStateInt( "summary_strogg_names_sel_0", -1 ); } else { scoreBoard->SetStateInt( "summary_strogg_names_sel_0", playerIndex ); scoreBoard->SetStateInt( "summary_marine_names_sel_0", -1 ); } } else { scoreBoard->SetStateInt( "summary_marine_names_sel_0", -1 ); scoreBoard->SetStateInt( "summary_strogg_names_sel_0", -1 ); } } else { for ( int i = 0; i < 10; i++ ) { // mekberg: delete old highlights scoreBoard->DeleteStateVar( va( "summary_names_item_%d_highlight", i ) ); if( i < rankedPlayers.Num() ) { // ranked player idPlayer* rankedPlayer = rankedPlayers[ i ].First(); int rankedScore = rankedPlayers[ i ].Second(); if( i == 9 && playerIndex == -1 ) { // if the player is ranked, substitute them in int i; for( i = 0; i < rankedPlayers.Num(); i++ ) { if( rankedPlayers[ i ].First() == player ) { rankedPlayer = player; rankedScore = rankedPlayers[ i ].Second(); break; } } } if ( rankedPlayer == gameLocal.GetLocalPlayer() ) { // highlight who we are playerIndex = i; } scoreBoard->SetStateString ( va( "%s_item_%i", "summary_names", i ), BuildSummaryListString( rankedPlayer, rankedScore ) ); if( rankedPlayer->GetRank() == 0 ) { scoreBoard->SetStateVec4( va( "summary_names_item_%d_highlight", i ), blueHighlight ); } else if( rankedPlayer->GetRank() == 1 ) { scoreBoard->SetStateVec4( va( "summary_names_item_%d_highlight", i ), redHighlight ); } else if( rankedPlayer->GetRank() == 2 ) { scoreBoard->SetStateVec4( va( "summary_names_item_%d_highlight", i ), yellowHighlight ); } } else { scoreBoard->SetStateString ( va("summary_names_item_%i", i), "" ); } } // highlight who we are (only if not ranked in the top 3) if( player->GetRank() >= 0 && player->GetRank() < 3 ) { scoreBoard->SetStateInt( "summary_names_sel_0", -1 ); } else { scoreBoard->SetStateInt( "summary_names_sel_0", playerIndex ); } } scoreBoard->StateChanged ( gameLocal.time ); scoreBoard->Redraw( gameLocal.time ); } /* ================ idMultiplayerGame::UpdateTestScoreboard ================ */ void idMultiplayerGame::UpdateTestScoreboard ( idUserInterface *scoreBoard ) { int i; gameLocal.random.SetSeed ( g_testScoreboard.GetInteger ( ) ); if( gameLocal.IsTeamGame() ) { for ( i = 0; i < MAX_CLIENTS && i < g_testScoreboard.GetInteger ( ); i ++ ) { idStr name = va("Player %d", i + 1 ); name = va("%s\t%i\t%i", name.c_str(), gameLocal.random.RandomInt ( 50 ), gameLocal.random.RandomInt ( 10 )); scoreBoard->SetStateString ( va("team_0_scores_item_%i", i), name ); } while ( i < MAX_CLIENTS ) { scoreBoard->SetStateString ( va("team_0_scores_item_%i", i), "" ); i++; } for ( i = 0; i < MAX_CLIENTS && i < g_testScoreboard.GetInteger ( ); i ++ ) { idStr name = va("Player %d", i + 1 ); name = va("%s\t%i\t%i", name.c_str(), gameLocal.random.RandomInt ( 50 ), gameLocal.random.RandomInt ( 10 )); scoreBoard->SetStateString ( va("team_1_scores_item_%i", i), name ); } while ( i < MAX_CLIENTS ) { scoreBoard->SetStateString ( va("team_1_scores_item_%i", i), "" ); i++; } scoreBoard->SetStateInt ( "strogg_score", gameLocal.random.RandomInt ( 10 ) ); scoreBoard->SetStateInt ( "marine_score", gameLocal.random.RandomInt ( 10 ) ); } else { for ( i = 0; i < MAX_CLIENTS && i < g_testScoreboard.GetInteger ( ); i ++ ) { idStr name = va("Player %d", i + 1 ); scoreBoard->SetStateString ( va("scores_item_%i", i), va("%s\t%s\t%s\t%s\t%s\t%s\t%i\t%i\t%i\t", ( gameLocal.random.RandomInt() % 2 ? I_VOICE_DISABLED : I_VOICE_ENABLED ), // mute icon ( gameLocal.random.RandomInt() % 2 ? I_FRIEND_ENABLED : I_FRIEND_DISABLED ), // friend icon "", // shouchard: flag name.c_str(), // name "Clan", // clan "", // team score (unused in DM) gameLocal.random.RandomInt ( 50 ), // score gameLocal.random.RandomInt ( 10 ), // time gameLocal.random.RandomInt ( 300 ) + 20 ) ); } // clear remaining lines (empty slots) while ( i < MAX_CLIENTS ) { scoreBoard->SetStateString ( va("scores_item_%i", i), "" ); i++; } } scoreBoard->SetStateInt ( "num_marine_players", g_testScoreboard.GetInteger() ); scoreBoard->SetStateInt ( "num_strogg_players", g_testScoreboard.GetInteger() ); scoreBoard->SetStateInt ( "num_players", g_testScoreboard.GetInteger() ); scoreBoard->SetStateInt( "rank_self", 2 ); scoreBoard->SetStateInt ( "playercount", g_testScoreboard.GetInteger ( ) ); scoreBoard->StateChanged ( gameLocal.time ); scoreBoard->SetStateString( "gameinfo", va( "Game Type:%s Frag Limit:%i Time Limit:%i", gameLocal.serverInfo.GetString( "si_gameType" ), gameLocal.serverInfo.GetInt( "si_fragLimit" ), gameLocal.serverInfo.GetInt( "si_timeLimit" ) ) ); scoreBoard->Redraw( gameLocal.time ); } // RAVEN END /* ================ idMultiplayerGame::GameTime ================ */ const char *idMultiplayerGame::GameTime( void ) { static char buff[32]; int m, s, t, ms; bool inCountdown = false; ms = 0; if( gameState->GetMPGameState() == COUNTDOWN ) { inCountdown = true; ms = gameState->GetNextMPGameStateTime() - gameLocal.realClientTime; } else if( gameLocal.GetLocalPlayer() && gameLocal.gameType == GAME_TOURNEY && ((rvTourneyGameState*)gameState)->GetArena( gameLocal.GetLocalPlayer()->GetArena() ).GetState() == AS_WARMUP ) { inCountdown = true; ms = ((rvTourneyGameState*)gameState)->GetArena( gameLocal.GetLocalPlayer()->GetArena() ).GetNextStateTime() - gameLocal.realClientTime; } if ( inCountdown ) { s = ms / 1000 + 1; if ( ms <= 0 ) { // in tourney mode use a different string since warmups happen before each round // (not really before the overall game) idStr::snPrintf( buff, sizeof( buff ), "%s --", ( gameState->GetMPGameState() == COUNTDOWN && gameLocal.gameType == GAME_TOURNEY ) ? common->GetLocalizedString( "#str_107721" ) : common->GetLocalizedString( "#str_107706" ) ); } else { idStr::snPrintf( buff, sizeof( buff ), "%s %i", (gameState->GetMPGameState() == COUNTDOWN && gameLocal.gameType == GAME_TOURNEY) ? common->GetLocalizedString( "#str_107721" ) : common->GetLocalizedString( "#str_107706" ), s ); } } else { int timeLimit = gameLocal.serverInfo.GetInt( "si_timeLimit" ); int startTime = matchStartedTime; if( gameLocal.gameType == GAME_TOURNEY ) { if( gameLocal.GetLocalPlayer() ) { startTime = ((rvTourneyGameState*)gameState)->GetArena( gameLocal.GetLocalPlayer()->GetArena() ).GetMatchStartTime(); } } if ( timeLimit ) { ms = ( timeLimit * 60000 ) - ( gameLocal.time - startTime ); } else { ms = gameLocal.time - startTime; } if ( ms < 0 ) { ms = 0; } s = ms / 1000; m = s / 60; s -= m * 60; t = s / 10; s -= t * 10; sprintf( buff, "%i:%i%i", m, t, s ); } return &buff[0]; } /* ================ idMultiplayerGame::NumActualClients ================ */ int idMultiplayerGame::NumActualClients( bool countSpectators, int *teamcounts ) { idPlayer *p; int c = 0; if ( teamcounts ) { teamcounts[ 0 ] = teamcounts[ 1 ] = 0; } for( int i = 0 ; i < gameLocal.numClients ; i++ ) { idEntity *ent = gameLocal.entities[ i ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END continue; } p = static_cast< idPlayer * >( ent ); if ( countSpectators || CanPlay( p ) ) { c++; } if ( teamcounts && CanPlay( p ) ) { teamcounts[ p->team ]++; } } return c; } /* ================ idMultiplayerGame::EnoughClientsToPlay ================ */ bool idMultiplayerGame::EnoughClientsToPlay() { int team[ 2 ]; int clients = NumActualClients( false, &team[ 0 ] ); if ( gameLocal.IsTeamGame() ) { return clients >= 2 && team[ 0 ] && team[ 1 ]; } else { return clients >= 2; } } /* ================ idMultiplayerGame::AllPlayersReady ================ */ bool idMultiplayerGame::AllPlayersReady( idStr* reason ) { int i, minClients, numClients; idEntity *ent; idPlayer *p; int team[ 2 ]; bool notReady; notReady = false; minClients = Max( 2, gameLocal.serverInfo.GetInt( "si_minPlayers" ) ); numClients = NumActualClients( false, &team[ 0 ] ); if ( numClients < minClients ) { if( reason ) { // stupid english plurals if( minClients == 2 ) { *reason = common->GetLocalizedString( "#str_107674" ); } else { *reason = va( common->GetLocalizedString( "#str_107732" ), minClients - numClients ); } } return false; } if ( gameLocal.IsTeamGame() ) { if ( !team[ 0 ] || !team[ 1 ] ) { if( reason ) { *reason = common->GetLocalizedString( "#str_107675" ); } return false; } } for( i = 0; i < gameLocal.numClients; i++ ) { ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } p = static_cast< idPlayer * >( ent ); if ( CanPlay( p ) && !p->IsReady() ) { notReady = true; } team[ p->team ]++; } if( notReady ) { if( reason ) { if( gameLocal.GetLocalPlayer() && gameLocal.GetLocalPlayer()->IsReady() ) { // Tourney has a different hud layout, so needs a different "you are (not)ready" string if( gameLocal.gameType == GAME_TOURNEY ) { *reason = va( common->GetLocalizedString( "#str_110018" ), common->KeysFromBinding( "_impulse17" ) ); } else { *reason = va( common->GetLocalizedString( "#str_107711" ), common->KeysFromBinding( "_impulse17" ) ); } } else if( gameLocal.GetLocalPlayer() ) { if( gameLocal.gameType == GAME_TOURNEY ) { *reason = va( common->GetLocalizedString( "#str_110017" ), common->KeysFromBinding( "_impulse17" ) ); } else { *reason = va( common->GetLocalizedString( "#str_107710" ), common->KeysFromBinding( "_impulse17" ) ); } } } return false; } return true; } /* ================ idMultiplayerGame::FragLimitHit return the winning player (team player) if there is no FragLeader(), the game is tied and we return NULL ================ */ idPlayer *idMultiplayerGame::FragLimitHit() { int fragLimit = gameLocal.serverInfo.GetInt( "si_fragLimit" ); idPlayer *leader = NULL; if ( fragLimit <= 0 ) { return NULL; // fraglimit disabled } leader = FragLeader(); if ( !leader ) { return NULL; } if ( playerState[ leader->entityNumber ].fragCount >= fragLimit ) { return leader; } return NULL; } /* ================ idMultiplayerGame::TimeLimitHit ================ */ bool idMultiplayerGame::TimeLimitHit( void ) { int timeLimit = gameLocal.serverInfo.GetInt( "si_timeLimit" ); if ( timeLimit ) { if ( gameLocal.time >= matchStartedTime + timeLimit * 60000 ) { return true; } } return false; } /* ================ idMultiplayerGame::FragLeader return the current winner NULL if even relies on UpdatePlayerRanks() being called earlier in frame to sort players ================ */ idPlayer* idMultiplayerGame::FragLeader( void ) { if( rankedPlayers.Num() < 2 ) { return NULL; } // mark leaders int i; int high = GetScore( rankedPlayers[ 0 ].First() ); idPlayer* p; for ( i = 0; i < rankedPlayers.Num(); i++ ) { p = rankedPlayers[ i ].First(); if ( !p ) { continue; } p->SetLeader( false ); if ( !CanPlay( p ) ) { continue; } if ( gameLocal.gameType == GAME_TOURNEY ) { continue; } if ( p->spectating ) { continue; } if ( GetScore( p ) >= high ) { p->SetLeader( true ); } } if( gameLocal.IsTeamGame() ) { // in a team game, find the first player not on the leader's team, and make sure they aren't tied int i = 0; while( i < rankedPlayers.Num() && rankedPlayers[ i ].First()->team == rankedPlayers[ 0 ].First()->team ) { i++; } if( i < rankedPlayers.Num() ) { if( GetScore( rankedPlayers[ i ].First()->entityNumber ) == GetScore( rankedPlayers[ 0 ].First()->entityNumber ) ) { return NULL; } } } else if( GetScore( rankedPlayers[ 0 ].First()->entityNumber ) == GetScore( rankedPlayers[ 1 ].First()->entityNumber ) ) { return NULL; } return rankedPlayers[ 0 ].First(); } /* ================ idMultiplayerGame::PlayerDeath ================ */ void idMultiplayerGame::PlayerDeath( idPlayer *dead, idPlayer *killer, int methodOfDeath ) { // don't do PrintMessageEvent assert( !gameLocal.isClient ); if ( killer ) { if ( gameLocal.IsTeamGame() ) { if ( killer == dead || killer->team == dead->team ) { // suicide or teamkill // in flag games, we subtract suicides from team-score rather than player score, which is the true // kill count if( gameLocal.IsFlagGameType() ) { AddPlayerTeamScore( killer == dead ? dead : killer, -1 ); } else { AddPlayerScore( killer == dead ? dead : killer, -1 ); } } else { // mark a kill AddPlayerScore( killer, 1 ); } // additional CTF points if( gameLocal.IsFlagGameType() ) { if( dead->PowerUpActive( killer->team ? POWERUP_CTF_STROGGFLAG : POWERUP_CTF_MARINEFLAG ) ) { AddPlayerTeamScore( killer, 2 ); } } if( gameLocal.gameType == GAME_TDM ) { if ( killer == dead || killer->team == dead->team ) { // suicide or teamkill AddTeamScore( killer->team, -1 ); } else { AddTeamScore( killer->team, 1 ); } } } else { // in tourney mode, we don't award points while in the waiting arena if( gameLocal.gameType != GAME_TOURNEY || ((rvTourneyGameState*)gameState)->GetArena( killer->GetArena() ).GetState() != AS_WARMUP ) { AddPlayerScore( killer, ( killer == dead ) ? -1 : 1 ); } // in tourney mode, frags track performance over the entire level load, team score keeps track of // individual rounds if( gameLocal.gameType == GAME_TOURNEY ) { AddPlayerTeamScore( killer, ( killer == dead ) ? -1 : 1 ); } } } else { // e.g. an environmental death // flag gametypes subtract points from teamscore, not playerscore if( gameLocal.IsFlagGameType() ) { AddPlayerTeamScore( dead, -1 ); } else { AddPlayerScore( dead, -1 ); } if( gameLocal.gameType == GAME_TOURNEY ) { AddPlayerTeamScore( dead, -1 ); } if( gameLocal.gameType == GAME_TDM ) { AddTeamScore( dead->team, -1 ); } } SendDeathMessage( killer, dead, methodOfDeath ); statManager->Kill( dead, killer, methodOfDeath ); // RAVEN BEGIN // shouchard: hack for CTF drop messages for listen servers if ( dead == gameLocal.GetLocalPlayer() && dead->PowerUpActive( dead->team ? POWERUP_CTF_MARINEFLAG : POWERUP_CTF_STROGGFLAG ) ) { if ( dead->mphud ) { dead->mphud->SetStateString( "main_notice_text", common->GetLocalizedString( "#str_104420" ) ); dead->mphud->HandleNamedEvent( "main_notice" ); } } // RAVEN END } /* ================ idMultiplayerGame::PlayerStats ================ */ void idMultiplayerGame::PlayerStats( int clientNum, char *data, const int len ) { idEntity *ent; int team; *data = 0; // make sure we don't exceed the client list if ( clientNum < 0 || clientNum > gameLocal.numClients ) { return; } // find which team this player is on ent = gameLocal.entities[ clientNum ]; if ( ent && ent->IsType( idPlayer::GetClassType() ) ) { team = static_cast< idPlayer * >(ent)->team; } else { return; } idStr::snPrintf( data, len, "team=%d score=%d tks=%d", team, playerState[ clientNum ].fragCount, playerState[ clientNum ].teamFragCount ); } /* ================ idMultiplayerGame::PlayerVote ================ */ void idMultiplayerGame::PlayerVote( int clientNum, playerVote_t vote ) { playerState[ clientNum ].vote = vote; } /* ================ idMultiplayerGame::ExecuteVote the votes are checked for validity/relevance before they are started we assume that they are still legit when reaching here ================ */ void idMultiplayerGame::ExecuteVote( void ) { bool needRestart; ClearVote(); switch ( vote ) { case VOTE_RESTART: cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "serverMapRestart\n"); break; case VOTE_TIMELIMIT: si_timeLimit.SetInteger( atoi( voteValue ) ); needRestart = gameLocal.NeedRestart(); cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" " " __FILE__ " " __LINESTR__ ); if ( needRestart ) { gameLocal.sessionCommand = "nextMap"; } break; case VOTE_FRAGLIMIT: si_fragLimit.SetInteger( atoi( voteValue ) ); needRestart = gameLocal.NeedRestart(); cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" " " __FILE__ " " __LINESTR__ ); if ( needRestart ) { gameLocal.sessionCommand = "nextMap"; } break; case VOTE_GAMETYPE: cvarSystem->SetCVarString( "si_gametype", voteValue ); cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "serverMapRestart\n"); break; case VOTE_KICK: cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "kick %s", voteValue.c_str() ) ); break; case VOTE_MAP: cvarSystem->SetCVarString( "si_map", voteValue ); cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "serverMapRestart\n"); break; case VOTE_BUYING: if ( gameLocal.GetCurrentDemoProtocol() == 69 ) gameLocal.Error("MIN_PLAYERS vote in a Quake 4 1.2 recorded demo ( protocol 69 ) is not supported."); cvarSystem->SetCVarString( "si_isBuyingEnabled", voteValue ); //cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" " " __FILE__ " " __LINESTR__ ); cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "serverMapRestart\n"); break; // RAVEN BEGIN // shouchard: added capture limit case VOTE_CAPTURELIMIT: si_captureLimit.SetInteger( atoi( voteValue ) ); gameLocal.sessionCommand = "nextMap"; break; // todo: round limit here (if we add it) case VOTE_AUTOBALANCE: si_autobalance.SetInteger( atoi( voteValue ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" " " __FILE__ " " __LINESTR__ ); break; case VOTE_MULTIFIELD: ExecutePackedVote(); break; // RAVEN END case VOTE_CONTROLTIME: si_controlTime.SetInteger( atoi( voteValue ) ); gameLocal.sessionCommand = "nextMap"; break; case VOTE_NEXTMAP: cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "serverNextMap\n" ); break; } } /* ================ idMultiplayerGame::CheckVote ================ */ void idMultiplayerGame::CheckVote( void ) { int numVoters, i; if ( vote == VOTE_NONE ) { return; } if ( voteExecTime ) { if ( gameLocal.time > voteExecTime ) { voteExecTime = 0; ClientUpdateVote( VOTE_RESET, 0, 0, currentVoteData ); ExecuteVote(); vote = VOTE_NONE; } return; } // count voting players numVoters = 0; for ( i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END continue; } if ( playerState[ i ].vote != PLAYER_VOTE_NONE ) { numVoters++; } } if ( !numVoters ) { // abort vote = VOTE_NONE; ClientUpdateVote( VOTE_ABORTED, yesVotes, noVotes, currentVoteData ); return; } if ( float(yesVotes) / numVoters > 0.5f ) { ClientUpdateVote( VOTE_PASSED, yesVotes, noVotes, currentVoteData ); voteExecTime = gameLocal.time + 2000; return; } if ( gameLocal.time > voteTimeOut || float(noVotes) / numVoters >= 0.5f ) { ClientUpdateVote( VOTE_FAILED, yesVotes, noVotes, currentVoteData ); vote = VOTE_NONE; return; } } // RAVEN BEGIN // shouchard: multifield voting here /* ================ idMultiplayerGame::ClientCallPackedVote The assumption is that the zero changes case has been handled above. ================ */ void idMultiplayerGame::ClientCallPackedVote( const voteStruct_t &voteData ) { idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; assert( 0 != voteData.m_fieldFlags ); // send outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_CALLPACKEDVOTE ); outMsg.WriteShort( voteData.m_fieldFlags ); if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_KICK ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_kick ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_MAP ) ) { outMsg.WriteString( voteData.m_map.c_str() ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_GAMETYPE ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_gameType ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TIMELIMIT ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_timeLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TOURNEYLIMIT ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_tourneyLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CAPTURELIMIT ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_captureLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_FRAGLIMIT ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_fragLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_BUYING ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_buying) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TEAMBALANCE ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_teamBalance ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CONTROLTIME ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_controlTime ) ); } networkSystem->ClientSendReliableMessage( outMsg ); } /* ================ idMultiplayerGame::ServerCallPackedVote ================ */ void idMultiplayerGame::ServerCallPackedVote( int clientNum, const idBitMsg &msg ) { voteStruct_t voteData; memset( &voteData, 0, sizeof( voteData ) ); assert( -1 != clientNum ); if( !gameLocal.serverInfo.GetBool( "si_allowVoting" ) ) { return; } // this is set to false if an invalid parameter is asked for-- time limit of -1, or frag limit of "jeff" or whatever. // if it's a multivote, it may still be valid, but this value is only checked if there are no vote parameters changed. bool validVote = true; // sanity checks - setup the vote if ( vote != VOTE_NONE ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104273" ); common->DPrintf( "client %d: called vote while voting already in progress - ignored\n", clientNum ); return; } // flags (short) voteData.m_fieldFlags = msg.ReadShort(); // clear any unallowed votes int disallowedVotes = gameLocal.serverInfo.GetInt( "si_voteFlags" ); for( int i = 0; i < NUM_VOTES; i++ ) { if ( disallowedVotes & (1 << i) ) { voteData.m_fieldFlags &= ~(1 << i); } } // kick if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_KICK ) ) { voteData.m_kick = msg.ReadByte(); if ( voteData.m_kick == gameLocal.localClientNum ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104257" ); common->DPrintf( "client %d: called kick for the server host\n", clientNum ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_KICK ); } } // map (string) if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_MAP ) ) { char buffer[128]; msg.ReadString( buffer, sizeof( buffer ) ); voteData.m_map = buffer; if ( 0 == idStr::Icmp( buffer, si_map.GetString() ) ) { //gameLocal.ServerSendChatMessage( clientNum, "server", "Selected map is the same as current map." ); // mekberg: localized string const char* mapName = si_map.GetString(); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } gameLocal.ServerSendChatMessage( clientNum, "server", va( common->GetLocalizedString( "#str_104295" ), mapName ) ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_MAP ); } // because of addon pk4's clients may submit votes for maps the server doesn't have - audit here const idDeclEntityDef *mapDef = (const idDeclEntityDef*)declManager->FindType( DECL_MAPDEF, voteData.m_map.c_str(), false ); if( !mapDef ) { validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_MAP ); gameLocal.ServerSendChatMessage( clientNum, "server", "Selected map does not exist on the server" ); } } // gametype if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_GAMETYPE ) ) { voteData.m_gameType = msg.ReadByte(); const char *voteString = "DM"; switch ( voteData.m_gameType ) { case VOTE_GAMETYPE_TOURNEY: voteString = "Tourney"; break; case VOTE_GAMETYPE_CTF: voteString = "CTF"; break; case VOTE_GAMETYPE_TDM: voteString = "Team DM"; break; case VOTE_GAMETYPE_ARENA_CTF: voteString = "Arena CTF"; break; case VOTE_GAMETYPE_DEADZONE: voteString = "DeadZone"; break; case VOTE_GAMETYPE_DM: default: voteString = "DM"; break; } if ( !idStr::Icmp( voteString, gameLocal.serverInfo.GetString( "si_gameType" ) ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104259" ); common->DPrintf( "client %d: already at the voted Game Type\n", clientNum ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_GAMETYPE ); } } // timelimit if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TIMELIMIT ) ) { voteData.m_timeLimit = msg.ReadByte(); if ( voteData.m_timeLimit < si_timeLimit.GetMinValue() || voteData.m_timeLimit > si_timeLimit.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104269" ); common->DPrintf( "client %d: timelimit value out of range for vote: %d\n", clientNum, voteData.m_timeLimit ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_TIMELIMIT ); } if ( voteData.m_timeLimit == si_timeLimit.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104270" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_TIMELIMIT ); } } // tourneylimit if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TOURNEYLIMIT ) ) { voteData.m_tourneyLimit = msg.ReadShort(); if ( voteData.m_tourneyLimit < si_tourneyLimit.GetMinValue() || voteData.m_tourneyLimit > si_tourneyLimit.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104261" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_TOURNEYLIMIT ); } if ( voteData.m_tourneyLimit == si_tourneyLimit.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104260" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_TOURNEYLIMIT ); } } // capture limit if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CAPTURELIMIT ) ) { voteData.m_captureLimit = msg.ReadShort(); if ( voteData.m_captureLimit < si_captureLimit.GetMinValue() || voteData.m_captureLimit > si_fragLimit.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104402" ); common->DPrintf( "client %d: caplimit value out of range for vote: %d\n", clientNum, voteData.m_captureLimit ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_CAPTURELIMIT ); } if ( voteData.m_captureLimit == si_captureLimit.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104401" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_CAPTURELIMIT ); } } // fraglimit if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_FRAGLIMIT ) ) { voteData.m_fragLimit = msg.ReadShort(); if ( voteData.m_fragLimit < si_fragLimit.GetMinValue() || voteData.m_fragLimit > si_fragLimit.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104266" ); common->DPrintf( "client %d: fraglimit value out of range for vote: %d\n", clientNum, voteData.m_fragLimit ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_FRAGLIMIT ); } if ( voteData.m_fragLimit == si_fragLimit.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104267" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_FRAGLIMIT ); } } // spectators /* if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_SPECTATORS ) ) { voteData.m_spectators = msg.ReadByte(); if ( voteData.m_spectators == si_spectators.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104421" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_SPECTATORS ); } } */ // buying if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_BUYING ) ) { voteData.m_buying = msg.ReadShort(); if ( voteData.m_buying == si_isBuyingEnabled.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_122013" ); validVote = false; voteData.m_buying &= ( ~VOTEFLAG_BUYING ); } } // autobalance teams if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TEAMBALANCE ) ) { voteData.m_teamBalance = msg.ReadByte(); if ( voteData.m_teamBalance == si_autobalance.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104403" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_TEAMBALANCE ); } } // control time if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CONTROLTIME ) ) { voteData.m_controlTime = msg.ReadShort(); if ( voteData.m_controlTime == si_controlTime.GetInteger() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_122017" ); validVote = false; voteData.m_fieldFlags &= ( ~VOTEFLAG_CONTROLTIME ); } } // check for no changes at all if ( 0 == voteData.m_fieldFlags ) { // If the vote was called empty, announce there were no valid changes. Otherwise, say nothing, there's already been a warning message. if( validVote ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104400" ); } return; } ServerStartPackedVote( clientNum, voteData ); ClientStartPackedVote( clientNum, voteData ); } /* ================ idMultiplayerGame::ClientStartPackedVote ================ */ void idMultiplayerGame::ClientStartPackedVote( int clientNum, const voteStruct_t &voteData ) { assert( 0 != voteData.m_fieldFlags ); if ( !gameLocal.isListenServer && !gameLocal.isClient ) { return; } // "%s has called a vote!" AddChatLine( va( common->GetLocalizedString( "#str_104279" ), gameLocal.userInfo[ clientNum ].GetString( "ui_name" ) ) ); // display the vote called text on the hud and play an announcer sound if ( gameLocal.GetLocalPlayer() && gameLocal.GetLocalPlayer()->mphud ) { gameLocal.GetLocalPlayer()->mphud->SetStateInt( "voteNotice", 1 ); } ScheduleAnnouncerSound( AS_GENERAL_VOTE_NOW, gameLocal.time ); if ( clientNum == gameLocal.localClientNum ) { voted = true; } else { voted = false; } if ( gameLocal.isClient ) { // the the vote value to something so the vote line is displayed vote = VOTE_RESTART; yesVotes = 1; noVotes = 0; } currentVoteData = voteData; idUserInterface * mpHud = gameLocal.GetLocalPlayer()->mphud; // push data to the interface if ( mpHud && mainGui ) { int voteLineCount = 1; int menuVoteLineCount = 0; bool kickActive = false; bool maxWindows = false; idStr yesKey = common->KeysFromBinding("_impulse28"); mainGui->SetStateInt( "vote_going", 1 ); //dynamic vote yes/no box mpHud->SetStateString( "voteNoticeText", va( common->GetLocalizedString( "#str_107242" ), yesKey.c_str(), common->KeysFromBinding("_impulse29") )); // kick should always be the highest one if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_KICK ) ) { // mpGui here, not mpHud //mpHud->SetStateString( "vote_data0", va( common->GetLocalizedString( "#str_104422" ), player->GetName() ); kickActive = true; mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104422" ), gameLocal.userInfo[ currentVoteData.m_kick ].GetString( "ui_name" ) ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104422" ), gameLocal.userInfo[ currentVoteData.m_kick ].GetString( "ui_name" ) ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_RESTART ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), common->GetLocalizedString( "#str_104423" ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), common->GetLocalizedString( "#str_104423" ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_BUYING ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_122011" ), currentVoteData.m_buying ? common->GetLocalizedString( "#str_104341" ) : common->GetLocalizedString( "#str_104342" ) ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_122011" ), currentVoteData.m_buying ? common->GetLocalizedString( "#str_104341" ) : common->GetLocalizedString( "#str_104342" ) ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_TEAMBALANCE ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104427" ), currentVoteData.m_teamBalance ? common->GetLocalizedString( "#str_104341" ) : common->GetLocalizedString( "#str_104342" ) ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104427" ), currentVoteData.m_teamBalance ? common->GetLocalizedString( "#str_104341" ) : common->GetLocalizedString( "#str_104342" ) ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_CONTROLTIME) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_122009" ), currentVoteData.m_controlTime ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_122009" ), currentVoteData.m_controlTime ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_SHUFFLE ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), common->GetLocalizedString( "#str_110010" ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), common->GetLocalizedString( "#str_110010" ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_MAP ) ) { const char *mapName = currentVoteData.m_map.c_str(); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104429" ), mapName ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104429" ), mapName ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_GAMETYPE ) ) { const char *gameTypeString = common->GetLocalizedString( "#str_110011" ); switch( currentVoteData.m_gameType ) { case VOTE_GAMETYPE_TOURNEY: gameTypeString = common->GetLocalizedString( "#str_110012" ); break; case VOTE_GAMETYPE_TDM: gameTypeString = common->GetLocalizedString( "#str_110013" ); break; case VOTE_GAMETYPE_CTF: gameTypeString = common->GetLocalizedString( "#str_110014" ); break; case VOTE_GAMETYPE_ARENA_CTF: gameTypeString = common->GetLocalizedString( "#str_110015" ); break; case VOTE_GAMETYPE_DEADZONE: gameTypeString = "DeadZone"; break; case VOTE_GAMETYPE_DM: default: gameTypeString = common->GetLocalizedString( "#str_110011" ); break; } mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104430" ), gameTypeString ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104430" ), gameTypeString ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_TIMELIMIT ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104431" ), currentVoteData.m_timeLimit ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104431" ), currentVoteData.m_timeLimit ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_TOURNEYLIMIT ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104432" ), currentVoteData.m_tourneyLimit ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104432" ), currentVoteData.m_tourneyLimit ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_CAPTURELIMIT ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104433" ), currentVoteData.m_captureLimit ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104433" ), currentVoteData.m_captureLimit ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_FRAGLIMIT ) ) { mpHud->SetStateString( va( "voteInfo_%d", voteLineCount ), va( common->GetLocalizedString( "#str_104434" ), currentVoteData.m_fragLimit ) ); mainGui->SetStateString( va( "voteData_item_%d", menuVoteLineCount ), va( common->GetLocalizedString( "#str_104434" ), currentVoteData.m_fragLimit ) ); voteLineCount++; menuVoteLineCount++; if( voteLineCount == 7) { voteLineCount = 6; maxWindows = true; } } //jshep: max of 7 windows and the 7th is always "..." if( maxWindows ) { mpHud->SetStateString( "voteInfo_7", "..." ); } mainGui->DeleteStateVar( va( "voteData_item_%d", menuVoteLineCount ) ); mainGui->SetStateInt( "vote_going", 1 ); mainGui->SetStateString( "voteCount", va( common->GetLocalizedString( "#str_104435" ), yesVotes, noVotes ) ); } ClientUpdateVote( VOTE_UPDATE, yesVotes, noVotes, currentVoteData ); } /* ================ idMultiplayerGame::ServerStartPackedVote ================ */ void idMultiplayerGame::ServerStartPackedVote( int clientNum, const voteStruct_t &voteData ) { idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; assert( vote == VOTE_NONE ); if ( !gameLocal.isServer ) { return; } // #13705: clients passing a vote during server restart could abuse the voting system into passing the vote right away after the new map loads if ( !playerState[ clientNum ].ingame ) { common->Printf( "ignore vote called by client %d: not in game\n", clientNum ); return; } // setup yesVotes = 1; noVotes = 0; vote = VOTE_MULTIFIELD; currentVoteData = voteData; voteTimeOut = gameLocal.time + 30000; // 30 seconds? might need to be longer because it requires fiddling with the GUI // mark players allowed to vote - only current ingame players, players joining during vote will be ignored for ( int i = 0; i < gameLocal.numClients; i++ ) { if ( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idPlayer::GetClassType() ) ) { playerState[ i ].vote = ( i == clientNum ) ? PLAYER_VOTE_YES : PLAYER_VOTE_WAIT; } else { playerState[i].vote = PLAYER_VOTE_NONE; } } outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_STARTPACKEDVOTE ); outMsg.WriteByte( clientNum ); outMsg.WriteShort( voteData.m_fieldFlags ); if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_KICK ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_kick ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_MAP ) ) { outMsg.WriteString( voteData.m_map.c_str() ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_GAMETYPE ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_gameType ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TIMELIMIT ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_timeLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_FRAGLIMIT ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_fragLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TOURNEYLIMIT ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_tourneyLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CAPTURELIMIT ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_captureLimit ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_BUYING ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_buying ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TEAMBALANCE ) ) { outMsg.WriteByte( idMath::ClampChar( voteData.m_teamBalance ) ); } if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CONTROLTIME ) ) { outMsg.WriteShort( idMath::ClampShort( voteData.m_controlTime ) ); } networkSystem->ServerSendReliableMessage( -1, outMsg ); } /* ================ idMultiplayerGame::ExecutePackedVote ================ */ void idMultiplayerGame::ExecutePackedVote( void ) { assert( VOTE_MULTIFIELD == vote ); if ( 0 == currentVoteData.m_fieldFlags ) { return; } bool needRestart = false; bool needNextMap = false; bool needRescanSI = false; if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_RESTART ) ) { needRestart = true; } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_BUYING ) ) { si_isBuyingEnabled.SetInteger( currentVoteData.m_buying ); needRescanSI = true; needRestart = true; } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_TEAMBALANCE ) ) { si_autobalance.SetInteger( currentVoteData.m_teamBalance ); needRescanSI = true; } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_CONTROLTIME ) ) { si_controlTime.SetInteger( currentVoteData.m_controlTime ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" ); } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_SHUFFLE ) ) { ShuffleTeams(); } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_KICK ) ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "kick %d", currentVoteData.m_kick ) ); } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_MAP ) ) { si_map.SetString( currentVoteData.m_map.c_str() ); needNextMap = true; } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_GAMETYPE ) ) { const char *gameTypeString = NULL; //jshepard: Currently the DM gametypes can be played on any map. The other gametypes require specially configured maps. //if further gametypes are added that can be played on any map, don't set the "runPickMap" flag. bool runPickMap = false; switch ( currentVoteData.m_gameType ) { case VOTE_GAMETYPE_TOURNEY: gameTypeString = "Tourney"; runPickMap = true; break; case VOTE_GAMETYPE_TDM: gameTypeString = "Team DM"; runPickMap = true; break; case VOTE_GAMETYPE_CTF: gameTypeString = "CTF"; runPickMap = true; break; case VOTE_GAMETYPE_ARENA_CTF: gameTypeString = "Arena CTF"; runPickMap = true; break; case VOTE_GAMETYPE_DEADZONE: gameTypeString = "DeadZone"; runPickMap = true; break; case VOTE_GAMETYPE_DM: default: gameTypeString = "DM"; break; } assert( gameTypeString ); si_gameType.SetString( gameTypeString ); //jshepard: run a pick map here in case the packed vote is trying to pick the wrong map type. //PickMap returns true if the map has changed (requiring a nextMap call) if( runPickMap ) { if( PickMap( gameTypeString ) ) { needNextMap = true; } else { needRestart = true; } } else { needRestart = true; } } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_TIMELIMIT ) ) { si_timeLimit.SetInteger( currentVoteData.m_timeLimit ); needRescanSI = true; } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_TOURNEYLIMIT ) ) { si_tourneyLimit.SetInteger( currentVoteData.m_tourneyLimit ); needRescanSI = true; } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_CAPTURELIMIT ) ) { si_captureLimit.SetInteger( currentVoteData.m_captureLimit ); needRescanSI = true; } if ( 0 != ( currentVoteData.m_fieldFlags & VOTEFLAG_FRAGLIMIT ) ) { si_fragLimit.SetInteger( currentVoteData.m_fragLimit ); needRescanSI = true; } if ( needRescanSI ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" " " __FILE__ " " __LINESTR__ ); } if ( needNextMap ) { gameLocal.sessionCommand = "nextMap"; } else if ( needRestart || gameLocal.NeedRestart() ) { cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "serverMapRestart" ); } } // RAVEN END /* ================ idMultiplayerGame::ClientEndFrame Called once each render frame (client) after all idGameLocal::ClientPredictionThink() calls ================ */ void idMultiplayerGame::ClientEndFrame( void ) { iconManager->UpdateIcons(); } /* ================ idMultiplayerGame::CommonRun Called once each render frame (client)/once each game frame (server) ================ */ void idMultiplayerGame::CommonRun( void ) { idPlayer* player = gameLocal.GetLocalPlayer(); // twhitaker r282 // TTimo: sure is a nasty way to do it if ( gameLocal.isServer && ( gameLocal.serverInfo.GetInt( "net_serverDedicated" ) != cvarSystem->GetCVarInteger( "net_serverDedicated" ) ) ) { cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "spawnServer\n" ); } if ( player && player->mphud ) { // update icons if ( gameLocal.isServer ) { iconManager->UpdateIcons(); } #ifdef _USE_VOICECHAT float micLevel; bool sending, testing; // jscott: enable the voice recording testing = cvarSystem->GetCVarBool( "s_voiceChatTest" ); sending = soundSystem->EnableRecording( !!( player->usercmd.buttons & BUTTON_VOICECHAT ), testing, micLevel ); if( mainGui ) { mainGui->SetStateFloat( "s_micLevel", micLevel ); mainGui->SetStateFloat( "s_micInputLevel", cvarSystem->GetCVarFloat( "s_micInputLevel" ) ); } // RAVEN BEGIN // shouchard: let the UI know about voicechat states if ( !testing && sending ) { player->mphud->HandleNamedEvent( "show_transmit_self" ); } else { player->mphud->HandleNamedEvent( "hide_transmit_self" ); } if( player->GetUserInfo()->GetBool( "s_voiceChatReceive" ) ) { int maxChannels = soundSystem->GetNumVoiceChannels(); int clientNum = -1; for (int channels = 0; channels < maxChannels; channels++ ) { clientNum = soundSystem->GetCommClientNum( channels ); if ( -1 != clientNum ) { break; } } // Sanity check for network errors assert( clientNum > -2 && clientNum < MAX_CLIENTS ); if ( clientNum > -1 && clientNum < MAX_CLIENTS ) { idPlayer *from = ( idPlayer * )gameLocal.entities[clientNum]; if( from ) { player->mphud->SetStateString( "audio_name", from->GetUserInfo()->GetString( "ui_name" ) ); player->mphud->HandleNamedEvent( "show_transmit" ); } } else { player->mphud->HandleNamedEvent( "hide_transmit" ); } } else { player->mphud->HandleNamedEvent( "hide_transmit" ); } #endif // _USE_VOICECHAT // RAVEN END } #ifdef _USE_VOICECHAT // jscott: Send any new voice data XmitVoiceData(); #endif int oldRank = -1; int oldLeadingTeam = -1; bool wasTied = false; int oldHighScore = /*idMath::*/INT_MIN; if( player && rankedPlayers.Num() ) { if( gameLocal.gameType == GAME_DM ) { oldRank = GetPlayerRank( player, wasTied ); oldHighScore = rankedPlayers[ 0 ].Second(); } else if( gameLocal.IsTeamGame() ) { oldLeadingTeam = rankedTeams[ 0 ].First(); wasTied = ( rankedTeams[ 0 ].Second() == rankedTeams[ 1 ].Second() ); oldHighScore = rankedTeams[ 0 ].Second(); } } UpdatePlayerRanks(); if ( gameLocal.IsTeamGame() ) { UpdateTeamRanks(); } if ( player && rankedPlayers.Num() && gameState->GetMPGameState() == GAMEON ) { if ( gameLocal.gameType == GAME_DM ) { // leader message bool isTied = false; int newRank = GetPlayerRank( player, isTied ); if ( newRank == 0 ) { if( ( oldRank != 0 || wasTied ) && !isTied ) { // we've gained first place or the person we were tied with dropped out of first place ScheduleAnnouncerSound( AS_DM_YOU_HAVE_TAKEN_LEAD, gameLocal.time ); } else if( oldRank != 0 || (!wasTied && isTied) ) { // we tied first place or we were in first and someone else tied ScheduleAnnouncerSound( AS_DM_YOU_TIED_LEAD, gameLocal.time ); } } else if ( oldRank == 0 ) { // we lost first place ScheduleAnnouncerSound( AS_DM_YOU_LOST_LEAD, gameLocal.time ); } } else if ( gameLocal.IsTeamGame() ) { int leadingTeam = rankedTeams[ 0 ].First(); bool isTied = ( rankedTeams[ 0 ].Second() == rankedTeams[ 1 ].Second() ); if ( !wasTied && isTied ) { if ( gameLocal.gameType != GAME_DEADZONE ) ScheduleAnnouncerSound( AS_TEAM_TEAMS_TIED, gameLocal.time ); } else if ( (leadingTeam != oldLeadingTeam && !isTied) || ( wasTied && !isTied ) ) { ScheduleAnnouncerSound( leadingTeam ? AS_TEAM_STROGG_LEAD : AS_TEAM_MARINES_LEAD, gameLocal.time ); } if ( gameLocal.gameType == GAME_TDM && oldHighScore != teamScore[ rankedTeams[ 0 ].First() ] && gameLocal.serverInfo.GetInt( "si_fragLimit" ) > 0 ) { if( teamScore[ rankedTeams[ 0 ].First() ] == gameLocal.serverInfo.GetInt( "si_fragLimit" ) - 3 ) { ScheduleAnnouncerSound( AS_GENERAL_THREE_FRAGS, gameLocal.time ); } else if( teamScore[ rankedTeams[ 0 ].First() ] == gameLocal.serverInfo.GetInt( "si_fragLimit" ) - 2 ) { ScheduleAnnouncerSound( AS_GENERAL_TWO_FRAGS, gameLocal.time ); } else if( teamScore[ rankedTeams[ 0 ].First() ] == gameLocal.serverInfo.GetInt( "si_fragLimit" ) - 1 ) { ScheduleAnnouncerSound( AS_GENERAL_ONE_FRAG, gameLocal.time ); } } } if( ( gameLocal.gameType == GAME_DM ) && rankedPlayers[ 0 ].Second() != oldHighScore && gameLocal.serverInfo.GetInt( "si_fragLimit" ) > 0 ) { // fraglimit warning if( rankedPlayers[ 0 ].Second() == gameLocal.serverInfo.GetInt( "si_fragLimit" ) - 3 ) { ScheduleAnnouncerSound( AS_GENERAL_THREE_FRAGS, gameLocal.time ); } else if( rankedPlayers[ 0 ].Second() == gameLocal.serverInfo.GetInt( "si_fragLimit" ) - 2 ) { ScheduleAnnouncerSound( AS_GENERAL_TWO_FRAGS, gameLocal.time ); } else if( rankedPlayers[ 0 ].Second() == gameLocal.serverInfo.GetInt( "si_fragLimit" ) - 1 ) { ScheduleAnnouncerSound( AS_GENERAL_ONE_FRAG, gameLocal.time ); } } } if ( rankTextPlayer ) { bool tied = false; int rank = GetPlayerRank( rankTextPlayer, tied ); (gameLocal.GetLocalPlayer())->GUIMainNotice( GetPlayerRankText( rank, tied, playerState[ rankTextPlayer->entityNumber ].fragCount ) ); rankTextPlayer = NULL; } PlayAnnouncerSounds(); // asalmon: Need to refresh stats periodically if the player is looking at stats if ( currentStatClient != -1 ) { rvPlayerStat* clientStat = statManager->GetPlayerStat( currentStatClient ); if ( ( gameLocal.time - clientStat->lastUpdateTime ) > 5000 ) { statManager->SelectStatWindow(currentStatClient, currentStatTeam); } } bool updateModels = false; if( g_forceModel.IsModified() && !gameLocal.IsTeamGame() ) { updateModels = true; g_forceModel.ClearModified(); } if( g_forceMarineModel.IsModified() && gameLocal.IsTeamGame() ) { updateModels = true; g_forceMarineModel.ClearModified(); } if( g_forceStroggModel.IsModified() && gameLocal.IsTeamGame() ) { updateModels = true; g_forceStroggModel.ClearModified(); } if( updateModels ) { for( int i = 0; i < gameLocal.numClients; i++ ) { idPlayer* player = (idPlayer*)gameLocal.entities[ i ]; if( player ) { player->UpdateModelSetup(); } } } // do this here rather than in idItem::Think() because clients don't run Think on ents outside their snap if( g_simpleItems.IsModified() ) { for( int i = 0; i < MAX_GENTITIES; i++ ) { idEntity* ent = gameLocal.entities[ i ]; if( !ent || !ent->IsType( idItem::GetClassType() ) || ent->IsType( rvItemCTFFlag::GetClassType() ) ) { continue; } idItem* item = (idItem*)ent; item->FreeModelDef(); renderEntity_t* renderEntity = item->GetRenderEntity(); memset( renderEntity, 0, sizeof( renderEntity ) ); item->simpleItem = g_simpleItems.GetBool() && gameLocal.isMultiplayer && !item->IsType( rvItemCTFFlag::GetClassType() ); if( item->simpleItem ) { renderEntity->shaderParms[ SHADERPARM_RED ] = 1.0f; renderEntity->shaderParms[ SHADERPARM_GREEN ] = 1.0f; renderEntity->shaderParms[ SHADERPARM_BLUE ] = 1.0f; renderEntity->shaderParms[ SHADERPARM_ALPHA ] = 1.0f; renderEntity->shaderParms[ SHADERPARM_SPRITE_WIDTH ] = 32.0f; renderEntity->shaderParms[ SHADERPARM_SPRITE_HEIGHT ] = 32.0f; renderEntity->hModel = renderModelManager->FindModel( "_sprite" ); renderEntity->callback = NULL; renderEntity->numJoints = 0; renderEntity->joints = NULL; renderEntity->customSkin = 0; renderEntity->noShadow = true; renderEntity->noSelfShadow = true; renderEntity->customShader = declManager->FindMaterial( item->spawnArgs.GetString( "mtr_simple_icon" ) ); renderEntity->referenceShader = 0; renderEntity->bounds = renderEntity->hModel->Bounds( renderEntity ); renderEntity->axis = mat3_identity; item->StopEffect( "fx_idle", true ); item->effectIdle = NULL; item->SetAxis( mat3_identity ); if( item->pickedUp ) { item->FreeModelDef(); item->UpdateVisuals(); } } else { gameEdit->ParseSpawnArgsToRenderEntity( &item->spawnArgs, renderEntity ); item->SetAxis( renderEntity->axis ); if ( item->spawnArgs.GetString( "fx_idle" ) ) { item->UpdateModelTransform(); item->effectIdle = item->PlayEffect( "fx_idle", renderEntity->origin, renderEntity->axis, true ); } if( item->pickedUp && item->pickupSkin ) { item->SetSkin( item->pickupSkin ); } } if ( !item->spawnArgs.GetBool( "dropped" ) ) { if ( item->spawnArgs.GetBool( "nodrop" ) ) { item->GetPhysics()->PutToRest(); } else { item->Event_DropToFloor(); } } } g_simpleItems.ClearModified(); } } /* ================ idMultiplayerGame::ClientRun Called once each client render frame (before any ClientPrediction frames have been run) ================ */ void idMultiplayerGame::ClientRun( void ) { CommonRun(); } /* ================ idMultiplayerGame::ReportZoneControllingPlayer ================ */ void idMultiplayerGame::ReportZoneControllingPlayer( idPlayer* player ) { if ( !player ) return; playerState[player->entityNumber].deadZoneScore += gameLocal.GetMSec(); playerState[player->entityNumber].teamFragCount = playerState[player->entityNumber].deadZoneScore / 1000; float cashPerSecondForDeadZoneControl = (float) gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "playerCashAward_deadZoneControlPerSecond", 0 ); // player->GiveCash( cashPerSecondForDeadZoneControl * 0.001f * (float) gameLocal.GetMSec() ); player->buyMenuCash += ( cashPerSecondForDeadZoneControl * 0.001f * (float) gameLocal.GetMSec() ); } /* ================ idMultiplayerGame::ReportZoneController ================ */ void idMultiplayerGame::ReportZoneController(int team, int pCount, int situation, idEntity* zoneTrigger) { powerupCount = pCount; idTrigger_Multi* zTrigger = 0; if ( zoneTrigger && zoneTrigger->IsType( idTrigger_Multi::GetClassType() ) ) { zTrigger = static_cast<idTrigger_Multi *>( zoneTrigger ); } if ( gameLocal.mpGame.GetGameState()->GetMPGameState() != GAMEON && gameLocal.mpGame.GetGameState()->GetMPGameState() != SUDDENDEATH ) { // We're not playing right now. However, make sure all the clients are updated to know // that the zone is neutral. ((riDZGameState*)gameState)->SetDZState(TEAM_MARINE, DZ_NONE); ((riDZGameState*)gameState)->SetDZState(TEAM_STROGG, DZ_NONE); if ( zTrigger && zTrigger->spawnArgs.MatchPrefix( "entityAffect" ) ) { idEntity* targetEnt = gameLocal.FindEntity(zTrigger->spawnArgs.GetString("entityAffect", "")); if ( targetEnt ) { ((riDZGameState*)gameState)->dzTriggerEnt = targetEnt->entityNumber; ((riDZGameState*)gameState)->dzShaderParm = 2; targetEnt->SetShaderParm(7, 2.0f); } } return; } if ( IsValidTeam(team) ) { const int t = gameLocal.serverInfo.GetInt( "si_controlTime" ); teamDeadZoneScore[team] += gameLocal.GetMSec() * powerupCount; teamScore[team] = (int)((float)teamDeadZoneScore[team] / 1000.0f); // We have a winner! if ( teamDeadZoneScore[team] > t*1000 ) { // Set the shaders and lights back to neutral. if ( zTrigger->spawnArgs.MatchPrefix( "colorTarget" ) ) { const idKeyValue *arg; int refLength = strlen( "colorTarget" ); int num = zTrigger->spawnArgs.GetNumKeyVals(); for( int i = 0; i < num; i++ ) { arg = zTrigger->spawnArgs.GetKeyVal( i ); if ( arg->GetKey().Icmpn( "colorTarget", refLength ) == 0 ) { idStr targetStr = arg->GetValue(); idEntity* targetEnt = gameLocal.FindEntity(targetStr); if ( targetEnt ) { targetEnt->SetColor(idVec3(0.75f, 0.75f, 0.75f)); } } } } if ( zTrigger && zTrigger->spawnArgs.MatchPrefix( "entityAffect" ) ) { idEntity* targetEnt = gameLocal.FindEntity(zTrigger->spawnArgs.GetString("entityAffect", "")); if ( targetEnt ) { ((riDZGameState*)gameState)->dzTriggerEnt = targetEnt->entityNumber; ((riDZGameState*)gameState)->dzShaderParm = 2; targetEnt->SetShaderParm(7, 2.0f); } } OnDeadZoneTeamVictory( team ); return; } } // Someone took control of a zone, report this to the if ( situation == DZ_MARINES_TAKEN || situation == DZ_STROGG_TAKEN || situation == DZ_MARINE_TO_STROGG || situation == DZ_STROGG_TO_MARINE || situation == DZ_MARINE_REGAIN || situation == DZ_STROGG_REGAIN ) { ((riDZGameState*)gameState)->SetDZState(TEAM_MARINE, DZ_NONE); // Clear hacked deadlock ((riDZGameState*)gameState)->SetDZState(team, DZ_TAKEN); } const int NOCHANGE = -2; const int DEADLOCK = 3; int controlSit = NOCHANGE; switch ( situation ) { case DZ_NONE : controlSit = NOCHANGE; break; case DZ_MARINES_TAKEN : controlSit = TEAM_MARINE; break; case DZ_MARINES_LOST : controlSit = TEAM_NONE; ((riDZGameState*)gameState)->SetDZState(TEAM_MARINE, DZ_LOST); break; case DZ_STROGG_TAKEN : controlSit = TEAM_STROGG; break; case DZ_STROGG_LOST : controlSit = TEAM_NONE; ((riDZGameState*)gameState)->SetDZState(TEAM_STROGG, DZ_LOST); break; case DZ_MARINE_TO_STROGG : controlSit = TEAM_STROGG; break; case DZ_STROGG_TO_MARINE : controlSit = TEAM_MARINE; break; case DZ_MARINE_DEADLOCK : controlSit = DEADLOCK; ((riDZGameState*)gameState)->SetDZState(TEAM_MARINE, DZ_DEADLOCK); break; case DZ_STROGG_DEADLOCK : controlSit = DEADLOCK; ((riDZGameState*)gameState)->SetDZState(TEAM_MARINE, DZ_DEADLOCK); break; case DZ_MARINE_REGAIN : controlSit = TEAM_MARINE; break; case DZ_STROGG_REGAIN : controlSit = TEAM_STROGG; break; } if ( zTrigger && controlSit == NOCHANGE && zTrigger->spawnArgs.MatchPrefix( "entityAffect" ) ) { // There's been no change in status, but keep these variables updated on the client idEntity* targetEnt = gameLocal.FindEntity(zTrigger->spawnArgs.GetString("entityAffect", "")); if ( targetEnt ) { ((riDZGameState*)gameState)->dzTriggerEnt = targetEnt->entityNumber; ((riDZGameState*)gameState)->dzShaderParm = (int)targetEnt->GetRenderEntity()->shaderParms[7]; } } if ( controlSit == NOCHANGE || !zTrigger ) return; // We're done. idVec3 colorVec; int parmNum = 2; if ( controlSit == TEAM_NONE ) { colorVec = idVec3(0.75f, 0.75f, 0.75f); parmNum = 2; } else if ( controlSit == TEAM_MARINE ) { colorVec = idVec3(0.0f, 1.0f, 0.0f); parmNum = 0; } else if ( controlSit == TEAM_STROGG ) { colorVec = idVec3(1.0f, 0.5f, 0.0f); parmNum = 1; } else if ( controlSit == DEADLOCK ) { colorVec = idVec3(1.0f, 0.0f, 0.0f); parmNum = 3; } if ( zTrigger->spawnArgs.MatchPrefix( "colorTarget" ) ) { const idKeyValue *arg; int refLength = strlen( "colorTarget" ); int num = zTrigger->spawnArgs.GetNumKeyVals(); for( int i = 0; i < num; i++ ) { arg = zTrigger->spawnArgs.GetKeyVal( i ); if ( arg->GetKey().Icmpn( "colorTarget", refLength ) == 0 ) { idStr targetStr = arg->GetValue(); idEntity* targetEnt = gameLocal.FindEntity(targetStr); if ( targetEnt ) { targetEnt->SetColor(colorVec); } } } } if ( zTrigger && zTrigger->spawnArgs.MatchPrefix( "entityAffect" ) ) { idEntity* targetEnt = gameLocal.FindEntity(zTrigger->spawnArgs.GetString("entityAffect", "")); if ( targetEnt ) { ((riDZGameState*)gameState)->dzTriggerEnt = targetEnt->entityNumber; ((riDZGameState*)gameState)->dzShaderParm = parmNum; targetEnt->SetShaderParm(7, (float)parmNum); } } } bool idMultiplayerGame::IsValidTeam(int team) { if ( team == TEAM_MARINE || team == TEAM_STROGG ) return true; return false; } void idMultiplayerGame::OnDeadZoneTeamVictory( int winningTeam ) { OnBuyModeTeamVictory( winningTeam ); gameState->NewState( GAMEREVIEW ); } void idMultiplayerGame::OnBuyModeTeamVictory( int winningTeam ) { if( !IsBuyingAllowedInTheCurrentGameMode() ) return; float teamCashForWin = (float) gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "teamCashAward_gameModeWin", 0 ); float teamCashForTie = (float) gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "teamCashAward_gameModeTie", 0 ); float teamCashForLoss = (float) gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "teamCashAward_gameModeLoss", 0 ); if( winningTeam == TEAM_NONE ) { GiveCashToTeam( TEAM_MARINE, teamCashForTie ); GiveCashToTeam( TEAM_STROGG, teamCashForTie ); } else { int losingTeam = 1 - winningTeam; GiveCashToTeam( winningTeam, teamCashForWin ); GiveCashToTeam( losingTeam, teamCashForLoss ); } } /* ================ idMultiplayerGame::Run ================ */ void idMultiplayerGame::Run( void ) { pureReady = true; assert( gameLocal.isMultiplayer && gameLocal.isServer && gameState ); CommonRun(); CheckVote(); CheckRespawns(); CheckSpecialLights( ); //RITUAL BEGIN UpdateTeamPowerups(); //RITUAL END gameState->Run(); gameState->SendState(); // don't update the ping every frame to save bandwidth if ( gameLocal.time > pingUpdateTime ) { for ( int i = 0; i < gameLocal.numClients; i++ ) { playerState[i].ping = networkSystem->ServerGetClientPing( i ); } pingUpdateTime = gameLocal.time + 1000; } } /* ================ idMultiplayerGame::UpdateMainGui ================ */ void idMultiplayerGame::UpdateMainGui( void ) { int i; mainGui->SetStateInt( "readyon", gameState->GetMPGameState() == WARMUP ? 1 : 0 ); mainGui->SetStateInt( "readyoff", gameState->GetMPGameState() != WARMUP ? 1 : 0 ); idStr strReady = cvarSystem->GetCVarString( "ui_ready" ); if ( strReady.Icmp( "ready") == 0 ){ strReady = common->GetLocalizedString( "#str_104248" ); } else { strReady = common->GetLocalizedString( "#str_104247" ); } mainGui->SetStateString( "ui_ready", strReady ); mainGui->SetStateInt( "num_spec_players", unrankedPlayers.Num() ); mainGui->SetStateInt( "gametype", gameLocal.gameType ); mainGui->SetStateBool( "s_useOpenAL", cvarSystem->GetCVarBool( "s_useOpenAL" ) ); mainGui->SetStateBool( "s_loadOpenALFailed", cvarSystem->GetCVarBool( "s_loadOpenALFailed" ) ); idVec4 hitscanTint; idStr hitScanValue = cvarSystem->GetCVarString( "ui_hitscanTint" ); sscanf( hitScanValue.c_str(), "%f %f %f %f", &hitscanTint.x, &hitscanTint.y, &hitscanTint.z, &hitscanTint.w ); mainGui->SetStateFloat( "ui_hitscanTint", hitscanTint.x ); // RAVEN BEGIN // bdube: capture the flag if ( gameLocal.IsTeamGame() ) { idPlayer *p = gameLocal.GetClientByNum( gameLocal.localClientNum ); if ( p ) { mainGui->SetStateInt( "team", p->team ); } mainGui->SetStateInt( "teamon", 1 ); mainGui->SetStateInt( "teamoff", 0 ); } else { mainGui->SetStateInt( "teamon", 0 ); mainGui->SetStateInt( "teamoff", 1 ); } // RAVEN END // RITUAL BEGIN // squirrel: added DeadZone multiplayer mode mainGui->SetStateInt( "teamon", (gameLocal.gameType == GAME_TDM || gameLocal.gameType == GAME_DEADZONE) ? 1 : 0 ); mainGui->SetStateInt( "teamoff", !(gameLocal.gameType == GAME_TDM || gameLocal.gameType == GAME_DEADZONE) ? 1 : 0 ); if ( gameLocal.gameType == GAME_TDM || gameLocal.gameType == GAME_DEADZONE ) { // RITUAL END idPlayer *p = gameLocal.GetClientByNum( gameLocal.localClientNum ); if ( p ) { mainGui->SetStateInt( "team", p->team ); } } // setup vote mainGui->SetStateInt( "voteon", ( vote != VOTE_NONE && !voted ) ? 1 : 0 ); mainGui->SetStateInt( "voteoff", ( vote != VOTE_NONE && !voted ) ? 0 : 1 ); // send the current serverinfo values for ( i = 0; i < gameLocal.serverInfo.GetNumKeyVals(); i++ ) { const idKeyValue *keyval = gameLocal.serverInfo.GetKeyVal( i ); mainGui->SetStateString( keyval->GetKey(), keyval->GetValue() ); } mainGui->StateChanged( gameLocal.time ); #if defined( __linux__ ) // replacing the oh-so-useful s_reverse with sound backend prompt mainGui->SetStateString( "driver_prompt", "1" ); #else mainGui->SetStateString( "driver_prompt", "0" ); #endif //RAVEN BEGIN // cnicholson: Add Custom Crosshair update mainGui->SetStateString( "g_crosshairCustom", cvarSystem->GetCVarBool( "g_crosshairCustom" ) ? "1" : "0" ); //RAVEN END // RAVEN BEGIN // cnicholson: We need to setup the custom crosshair so it shows up the first time the player enters the MP settings menu. // This block checks the current crosshair, and compares it against the list of crosshairs in player.def (mtr_crosshair*) under the // player_marine_mp section. If it finds a match, it assigns the crosshair, otherwise, the first found crosshair is used. #ifndef _XENON const idDeclEntityDef *defCH = static_cast<const idDeclEntityDef*>( declManager->FindType( DECL_ENTITYDEF, "player_marine_mp", false, true ) ); #else bool insideLevelLoad = declManager->GetInsideLoad(); if ( !insideLevelLoad ) { declManager->SetInsideLoad( true ); } const idDeclEntityDef *defCH = static_cast<const idDeclEntityDef*>( declManager->FindType( DECL_ENTITYDEF, "player_marine_mp_ui", false, false ) ); declManager->SetInsideLoad( insideLevelLoad ); #endif #ifndef _XENON idStr currentCrosshair = cvarSystem->GetCVarString("g_crosshairCustomFile"); const idKeyValue* kv = defCH->dict.MatchPrefix("mtr_crosshair", NULL); while ( kv ) { // Loop through all crosshairs listed in the def if ( kv->GetValue() == currentCrosshair.c_str() ) { // Until a match is found break; } kv = defCH->dict.MatchPrefix("mtr_crosshair", kv ); } if ( !kv ){ kv = defCH->dict.MatchPrefix("mtr_crosshair", NULL ); // If no natches are found, use the first one. } idStr newCrosshair(kv->GetValue()); mainGui->SetStateString ( "crossImage", newCrosshair.c_str()); const idMaterial *material = declManager->FindMaterial( newCrosshair.c_str() ); if ( material ) { material->SetSort( SS_GUI ); } cvarSystem->SetCVarString("g_crosshairCustomFile", newCrosshair.c_str()); #endif //asalmon: Set up a state var for match type of Xbox 360 #ifdef _XENON mainGui->SetStateBool("CustomHost", Live()->IsCustomHost()); mainGui->SetStateInt("MatchType", Live()->GetMatchtype()); mainGui->SetStateString("si_gametype", gameLocal.serverInfo.GetString("si_gametype")); const char *damage; if (gameLocal.serverInfo.GetBool("si_teamdamage")){ damage = "Yes" ; } else { damage = "No"; } mainGui->SetStateString("si_teamdamage", damage); const char *shuffle; if (gameLocal.serverInfo.GetBool("si_shuffleMaps")){ shuffle = "Yes" ; } else { shuffle = "No"; } mainGui->SetStateString("si_shuffleMaps", shuffle); mainGui->SetStateString("si_fraglimit", gameLocal.serverInfo.GetString("si_fraglimit")); mainGui->SetStateString("si_capturelimit", gameLocal.serverInfo.GetString("si_capturelimit")); mainGui->SetStateString("si_timelimit", gameLocal.serverInfo.GetString("si_timelimit")); // mekberg: send spectating to the mainGui. if ( gameLocal.GetLocalPlayer( ) ) { mainGui->SetStateBool( "spectating", gameLocal.GetLocalPlayer( )->spectating ); if( gameLocal.gameType == GAME_TOURNEY ) { // additionally in tourney, indicate whether the player is voluntarily spectating mainGui->SetStateBool( "tourneyspectating", !idStr::Icmp( gameLocal.GetLocalPlayer()->GetUserInfo()->GetString( "ui_spectate" ), "Spectate" ) ); } } else { mainGui->SetStateBool( "spectating", false ); } #endif // RAVEN END } /* ================ idMultiplayerGame::SetupBuyMenuItems ================ */ void idMultiplayerGame::SetupBuyMenuItems() { idPlayer* player = gameLocal.GetLocalPlayer(); if ( !player ) return; buyMenu->SetStateInt( "buyStatus_shotgun", player->ItemBuyStatus( "weapon_shotgun" ) ); buyMenu->SetStateInt( "buyStatus_hyperblaster", player->ItemBuyStatus( "weapon_hyperblaster" ) ); buyMenu->SetStateInt( "buyStatus_grenadelauncher", player->ItemBuyStatus( "weapon_grenadelauncher" ) ); buyMenu->SetStateInt( "buyStatus_nailgun", player->ItemBuyStatus( "weapon_nailgun" ) ); buyMenu->SetStateInt( "buyStatus_rocketlauncher", player->ItemBuyStatus( "weapon_rocketlauncher" ) ); buyMenu->SetStateInt( "buyStatus_railgun", player->ItemBuyStatus( "weapon_railgun" ) ); buyMenu->SetStateInt( "buyStatus_lightninggun", player->ItemBuyStatus( "weapon_lightninggun" ) ); // buyMenu->SetStateInt( "buyStatus_dmg", player->ItemBuyStatus( "weapon_dmg" ) ); buyMenu->SetStateInt( "buyStatus_napalmgun", player->ItemBuyStatus( "weapon_napalmgun" ) ); buyMenu->SetStateInt( "buyStatus_lightarmor", player->ItemBuyStatus( "item_armor_small" ) ); buyMenu->SetStateInt( "buyStatus_heavyarmor", player->ItemBuyStatus( "item_armor_large" ) ); buyMenu->SetStateInt( "buyStatus_ammorefill", player->ItemBuyStatus( "ammorefill" ) ); buyMenu->SetStateInt( "buyStatus_special0", player->ItemBuyStatus( "ammo_regen" ) ); buyMenu->SetStateInt( "buyStatus_special1", player->ItemBuyStatus( "health_regen" ) ); buyMenu->SetStateInt( "buyStatus_special2", player->ItemBuyStatus( "damage_boost" ) ); buyMenu->SetStateInt( "playerTeam", player->team ); if ( player->weapon ) buyMenu->SetStateString( "ammoIcon", player->weapon->spawnArgs.GetString ( "inv_icon" ) ); buyMenu->SetStateInt( "player_weapon", player->GetCurrentWeapon() ); } /* ================ idMultiplayerGame::StartMenu ================ */ idUserInterface* idMultiplayerGame::StartMenu( void ) { if ( mainGui == NULL ) { return NULL; } //if we're the server, allow access to the admin tab right away. Otherwise, make sure we don't have it. if( gameLocal.isServer ) { mainGui->SetStateInt( "password_valid", 1 ); } else { mainGui->SetStateInt( "password_valid", 0 ); } int i, j; if ( currentMenu ) { currentMenu = 0; cvarSystem->SetCVarBool( "ui_chat", false ); } else { if ( nextMenu >= 2 ) { currentMenu = nextMenu; } else { // for default and explicit currentMenu = 1; } cvarSystem->SetCVarBool( "ui_chat", true ); } if( gameLocal.GetLocalPlayer() ) { gameLocal.GetLocalPlayer()->disableHud = true; } nextMenu = 0; if ( currentMenu == 1 ) { UpdateMainGui(); // UpdateMainGui sets most things, but it doesn't set these because // it'd be pointless and/or harmful to set them every frame (for various reasons) // Currenty the gui doesn't update properly if they change anyway, so we'll leave it like this. // player kick data for ( i = 0; i < 16; i++ ) { kickVoteMapNames[ i ].Clear(); kickVoteMap[ i ] = -1; } idStr kickList; j = 0; for ( i = 0; i < gameLocal.numClients; i++ ) { // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idPlayer::GetClassType() ) ) { // RAVEN END if ( kickList.Length() ) { kickList += ";"; } kickList += va( "\"%d - %s\"", i, gameLocal.userInfo[ i ].GetString( "ui_name" ) ); kickVoteMap[ j ] = i; // RAVEN BEGIN // shouchard: names for kick vote map kickVoteMapNames[ j ] = gameLocal.userInfo[ i ].GetString( "ui_name" ); // RAVEN END j++; } } mainGui->SetStateString( "kickChoices", kickList ); mainGui->SetStateString( "chattext", "" ); mainGui->Activate( true, gameLocal.time ); idPlayer *localP = gameLocal.GetLocalPlayer(); #ifndef _XENON const idDeclEntityDef *def = gameLocal.FindEntityDef( "player_marine_mp", false ); #else const idDeclEntityDef *def = gameLocal.FindEntityDef( "player_marine_mp_ui", false ); #endif idStr buildValues, buildNames; int numModels = declManager->GetNumDecls( DECL_PLAYER_MODEL ); for( int i = 0; i < numModels; i++ ) { const rvDeclPlayerModel* playerModel = (const rvDeclPlayerModel*)declManager->DeclByIndex( DECL_PLAYER_MODEL, i, false ); if( !playerModel ) { continue; } const char *resultValue = playerModel->GetName(); if ( !resultValue || !resultValue[0] ) { continue; } const char *team = playerModel->team.c_str(); if ( gameLocal.IsTeamGame() ) { if ( team && localP && localP->team >= 0 && localP->team < TEAM_MAX && idStr::Icmp( teamNames[ localP->team ], team ) == 0 ) { } else { // doesn't match, so skip continue; } } if ( i ) { buildValues += ";"; buildNames += ";"; } buildValues += resultValue; const char *resultName = common->GetLocalizedString( playerModel->description.c_str() ); if ( !resultName || !resultName[0] ) { buildNames += resultValue; } else { buildNames += resultName; } } mainGui->SetStateString( "model_values", buildValues.c_str() ); mainGui->SetStateString( "model_names", buildNames.c_str() ); mainGui->SetStateBool( "player_model_updated", true ); const char *model; if ( localP && localP->team >= 0 && localP->team < TEAM_MAX ) { model = cvarSystem->GetCVarString( va( "ui_model_%s", teamNames[ localP->team ] ) ); if( *model == '\0' ) { model = def->dict.GetString( va( "def_default_model_%s", teamNames[ localP->team ] ) ); } } else { model = cvarSystem->GetCVarString( "ui_model" ); if( *model == '\0' ) { model = def->dict.GetString( "def_default_model" ); } } const rvDeclPlayerModel* playerModel = (const rvDeclPlayerModel*)declManager->FindType( DECL_PLAYER_MODEL, model, false ); if ( playerModel ) { mainGui->SetStateString( "player_model_name", playerModel->model.c_str() ); mainGui->SetStateString( "player_head_model_name", playerModel->uiHead.c_str() ); mainGui->SetStateString( "player_skin_name", playerModel->skin.c_str() ); if( playerModel->uiHead.Length() ) { const idDeclEntityDef* head = (const idDeclEntityDef*)declManager->FindType( DECL_ENTITYDEF, playerModel->uiHead.c_str(), false ); if( head && head->dict.GetString( "skin" ) ) { mainGui->SetStateString( "player_head_skin_name", head->dict.GetString( "skin" ) ); } } mainGui->SetStateBool( "need_update", true ); } if( gameLocal.GetLocalPlayer() ) { cvarSystem->SetCVarString( "gui_ui_name", gameLocal.GetLocalPlayer()->GetUserInfo()->GetString( "ui_name" ) ); } return mainGui; } else if ( currentMenu == 2 ) { // the setup is done in MessageMode if( gameLocal.GetLocalPlayer() ) { gameLocal.GetLocalPlayer()->disableHud = false; } msgmodeGui->Activate( true, gameLocal.time ); cvarSystem->SetCVarBool( "ui_chat", true ); return msgmodeGui; } else if ( currentMenu == 3 ) { statSummary->Activate( true, gameLocal.time ); statManager->SetupStatWindow( statSummary ); UpdateScoreboard( statSummary ); UpdateSummaryBoard( statSummary ); statSummary->SetStateFloat( "ready", 0 ); statSummary->StateChanged( gameLocal.time ); // Moved the announcer sound here. This way we can be sure the client has updated team score information by this point. // #13576 #13544 causing double sounds because it's getting triggered twice at endgame ( from GameStateChanged and from ReceiveAllStats ) // the move to here was for fixing some problem when running at the previous location ( GameStateChanged ) // there are too many codepaths leading to various orders of ReceiveAllStats and GameStateChanged // various attempts to flag the right call that should trigger the sound failed, so just using a timeout now if ( gameLocal.time - lastVOAnnounce > 1000 ) { idPlayer* player = gameLocal.GetLocalPlayer(); if ( gameLocal.IsTeamGame() ) { int winningTeam = GetScoreForTeam( TEAM_MARINE ) > GetScoreForTeam( TEAM_STROGG ) ? TEAM_MARINE : TEAM_STROGG; if( player->team == winningTeam ) { ScheduleAnnouncerSound( AS_GENERAL_YOU_WIN, gameLocal.time ); } else { ScheduleAnnouncerSound( AS_GENERAL_YOU_LOSE, gameLocal.time ); } } else if ( gameLocal.gameType != GAME_TOURNEY ) { if( player->GetRank() == 0 ) { ScheduleAnnouncerSound( AS_GENERAL_YOU_WIN, gameLocal.time ); } else { ScheduleAnnouncerSound( AS_GENERAL_YOU_LOSE, gameLocal.time ); } } lastVOAnnounce = gameLocal.time; } return statSummary; // RITUAL BEGIN // squirrel: Mode-agnostic buymenus } else if ( currentMenu == 4 ) { //if( mpClientGameState.gameState.currentState == COUNTDOWN ) { idPlayer* player = gameLocal.GetLocalPlayer(); buyMenu->SetStateString( "field_credits", va("%i", (int)player->buyMenuCash) ); buyMenu->SetStateInt( "price_shotgun", player->GetItemCost("weapon_shotgun") ); buyMenu->SetStateInt( "price_hyperblaster", player->GetItemCost("weapon_hyperblaster") ); buyMenu->SetStateInt( "price_grenadelauncher", player->GetItemCost( "weapon_grenadelauncher" ) ); buyMenu->SetStateInt( "price_nailgun", player->GetItemCost( "weapon_nailgun" ) ); buyMenu->SetStateInt( "price_rocketlauncher", player->GetItemCost( "weapon_rocketlauncher" ) ); buyMenu->SetStateInt( "price_railgun", player->GetItemCost( "weapon_railgun" ) ); buyMenu->SetStateInt( "price_lightninggun", player->GetItemCost( "weapon_lightninggun" ) ); // buyMenu->SetStateInt( "price_dmg", player->GetItemCost( "weapon_dmg" ) ); buyMenu->SetStateInt( "price_napalmgun", player->GetItemCost( "weapon_napalmgun" ) ); buyMenu->SetStateInt( "price_lightarmor", player->GetItemCost( "item_armor_small" ) ); buyMenu->SetStateInt( "price_heavyarmor", player->GetItemCost( "item_armor_large" ) ); buyMenu->SetStateInt( "price_ammorefill", player->GetItemCost( "ammorefill" ) ); buyMenu->SetStateInt( "price_special0", player->GetItemCost( "ammo_regen" ) ); buyMenu->SetStateInt( "price_special1", player->GetItemCost( "health_regen" ) ); buyMenu->SetStateInt( "price_special2", player->GetItemCost( "damage_boost" ) ); SetupBuyMenuItems(); buyMenu->Activate(true, gameLocal.time); return buyMenu; //} // RITUAL END } return NULL; } /* ================ idMultiplayerGame::DisableMenu ================ */ void idMultiplayerGame::DisableMenu( void ) { if ( currentMenu == 1 ) { mainGui->Activate( false, gameLocal.time ); } else if ( currentMenu == 2 ) { msgmodeGui->Activate( false, gameLocal.time ); } else if( currentMenu == 3 ) { statSummary->Activate( false, gameLocal.time ); // RITUAL BEGIN // squirrel: Mode-agnostic buymenus } else if( currentMenu == 4 ) { buyMenu->Activate( false, gameLocal.time ); // RITUAL END } // copy over name from temp cvar if( currentMenu == 1 && idStr::Cmp( cvarSystem->GetCVarString( "gui_ui_name" ), cvarSystem->GetCVarString( "ui_name" ) ) ) { cvarSystem->SetCVarString( "ui_name", cvarSystem->GetCVarString( "gui_ui_name" ) ); } currentMenu = 0; nextMenu = 0; cvarSystem->SetCVarBool( "ui_chat", false ); if( gameLocal.GetLocalPlayer() ) { gameLocal.GetLocalPlayer()->disableHud = false; //RAVEN BEGIN //asalmon: make the scoreboard on Xenon close #ifdef _XENON gameLocal.GetLocalPlayer()->scoreBoardOpen = false; #endif //RAVEN END if( gameLocal.GetLocalPlayer()->mphud) { gameLocal.GetLocalPlayer()->mphud->Activate( true, gameLocal.time ); } } mainGui->DeleteStateVar( va( "sa_playerList_item_%d", 0 ) ); mainGui->SetStateString( "sa_playerList_sel_0", "-1" ); mainGui->DeleteStateVar( va( "sa_banList_item_%d", 0 ) ); mainGui->SetStateString( "sa_banList_sel_0", "-1" ); // asalmon: Need to refresh stats periodically if the player is looking at stats currentStatClient = -1; currentStatTeam = -1; } /* ================ idMultiplayerGame::SetMapShot ================ */ void idMultiplayerGame::SetMapShot( void ) { #ifdef _XENON // Should not be used assert( 0 ); #else char screenshot[ MAX_STRING_CHARS ]; int mapNum = mapList->GetSelection( NULL, 0 ); const idDict *dict = NULL; if ( mapNum >= 0 ) { dict = fileSystem->GetMapDecl( mapNum ); } fileSystem->FindMapScreenshot( dict ? dict->GetString( "path" ) : "", screenshot, MAX_STRING_CHARS ); mainGui->SetStateString( "current_levelshot", screenshot ); // RAVEN BEGIN // cnicholson: Need to sort the material screenshot so it doesn't overlap other things const idMaterial *mat = declManager->FindMaterial( screenshot ); mat->SetSort( SS_GUI ); // RAVEN END #endif } /* ================ LocalServerRedirect Dummy local redirect for gui rcon functionality on a local server ================ */ void LocalServerRedirect( const char* string ) { gameLocal.mpGame.ReceiveRemoteConsoleOutput( string ); } /* ================ idMultiplayerGame::HandleGuiCommands ================ */ const char* idMultiplayerGame::HandleGuiCommands( const char *_menuCommand ) { idUserInterface *currentGui; // RAVEN BEGIN // shouchard: removed the code that deals with these variables //const char *voteValue; //int vote_clientNum; // RAVEN END int icmd; idCmdArgs args; if ( !_menuCommand[ 0 ] ) { common->Printf( "idMultiplayerGame::HandleGuiCommands: empty command\n" ); return "continue"; } #ifdef _XENON if ( currentMenu == 0 && (session->GetActiveGUI() != scoreBoard) ) { #else if ( currentMenu == 0 ) { #endif return NULL; // this will tell session to not send us events/commands anymore } if ( currentMenu == 1 ) { currentGui = mainGui; } #ifdef _XENON else if (session->GetActiveGUI() != scoreBoard) { currentGui = msgmodeGui; } else { currentGui = scoreBoard; } #else else if( currentMenu == 2 ) { currentGui = msgmodeGui; // RITUAL BEGIN // squirrel: Mode-agnostic buymenus } else if ( currentMenu == 4 ) { currentGui = buyMenu; // jmartel: make sure var is initialized (compiler complained) } else if( currentMenu == 3 ) { currentGui = statSummary; } else { gameLocal.Warning( "idMultiplayerGame::HandleGuiCommands() - Unknown current menu '%d'\n", currentMenu ); currentGui = mainGui; } // RITUAL END #endif args.TokenizeString( _menuCommand, false ); for( icmd = 0; icmd < args.Argc(); ) { const char *cmd = args.Argv( icmd++ ); if ( !idStr::Icmp( cmd, ";" ) ) { continue; } else if ( !idStr::Icmp( cmd, "inGameMenu" ) ) { if ( args.Argc() - icmd >= 1 ) { idStr igArg = args.Argv( icmd++ ); if( !igArg.Icmp( "init" ) ) { currentGui->SetStateString( "chat", chatHistory.c_str() ); if( gameLocal.GetLocalPlayer() ) { currentGui->SetStateInt( "player_team", gameLocal.GetLocalPlayer()->team ); } // mekberg: added UpdateMPSettingsModel ( currentGui ); if( gameLocal.gameType == GAME_TOURNEY ) { if( !idStr::Icmp( cvarSystem->GetCVarString( "ui_spectate" ), "Spectate" ) ) { currentGui->SetStateString( "toggleTourneyButton", common->GetLocalizedString( "#str_107699" ) ); } else { currentGui->SetStateString( "toggleTourneyButton", common->GetLocalizedString( "#str_107700" ) ); } } currentGui->SetStateBool( "useReady", gameLocal.serverInfo.GetBool( "si_useReady", "0" ) && gameState->GetMPGameState() == WARMUP ); if( gameLocal.serverInfo.GetBool( "si_useReady" ) && gameLocal.GetLocalPlayer() && gameLocal.GetLocalPlayer()->IsReady() && gameState->GetMPGameState() == WARMUP ) { currentGui->SetStateString( "readyStatus", common->GetLocalizedString( "#str_104247" ) ); } else if( gameLocal.serverInfo.GetBool( "si_useReady" ) && gameLocal.GetLocalPlayer() && !gameLocal.GetLocalPlayer()->IsReady() && gameState->GetMPGameState() == WARMUP ) { currentGui->SetStateString( "readyStatus", common->GetLocalizedString( "#str_104248" ) ); } else { currentGui->SetStateString( "readyStatus", "" ); } currentGui->SetStateBool( "si_allowVoting", gameLocal.serverInfo.GetBool( "si_allowVoting" ) ); currentGui->SetStateBool( "si_allowVoice", gameLocal.serverInfo.GetBool( "si_voiceChat" ) ); int disallowedVotes = gameLocal.serverInfo.GetInt( "si_voteFlags" ); for( int i = 0; i < NUM_VOTES; i++ ) { if( disallowedVotes & (1 << i) ) { currentGui->SetStateBool( va( "allowvote_%d", i + 1 ), false ); } else { currentGui->SetStateBool( va( "allowvote_%d", i + 1 ), true ); } } } } continue; } else if ( !idStr::Icmp( cmd, "video" ) ) { idStr vcmd; if ( args.Argc() - icmd >= 1 ) { vcmd = args.Argv( icmd++ ); } if ( idStr::Icmp( vcmd, "low" ) == 0 ) { cvarSystem->SetCVarInteger( "com_machineSpec", 0 ); } else if ( idStr::Icmp( vcmd, "medium" ) == 0 ) { cvarSystem->SetCVarInteger( "com_machineSpec", 1 ); } else if ( idStr::Icmp( vcmd, "high" ) == 0 ) { cvarSystem->SetCVarInteger( "com_machineSpec", 2 ); } else if ( idStr::Icmp( vcmd, "ultra" ) == 0 ) { cvarSystem->SetCVarInteger( "com_machineSpec", 3 ); } else if ( idStr::Icmp( vcmd, "recommended" ) == 0 ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "setMachineSpec\n" ); } // RAVEN BEGIN // mekberg: set the r_mode. cvarSystem->SetCVarInteger( "r_aspectRatio", 0 ); currentGui->SetStateInt( "r_aspectRatio", 0 ); currentGui->HandleNamedEvent( "forceAspect0" ); currentGui->SetStateInt( "com_machineSpec", cvarSystem->GetCVarInteger( "com_machineSpec" ) ); currentGui->StateChanged( gameLocal.realClientTime ); cvarSystem->SetCVarInteger( "r_mode", common->GetRModeForMachineSpec ( cvarSystem->GetCVarInteger( "com_machineSpec" ) ) ); common->SetDesiredMachineSpec( cvarSystem->GetCVarInteger( "com_machineSpec" ) ); // RAVEN END cmdSystem->BufferCommandText( CMD_EXEC_NOW, "execMachineSpec" ); if ( idStr::Icmp( vcmd, "restart" ) == 0) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "vid_restart\n" ); } continue; } else if ( !idStr::Icmp( cmd, "join" ) ) { if ( args.Argc() - icmd >= 1 ) { JoinTeam( args.Argv( icmd++ ) ); } continue; } else if ( !idStr::Icmp( cmd, "quit" ) ) { cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "quit\n" ); return NULL; } else if ( !idStr::Icmp( cmd, "disconnect" ) ) { cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "disconnect\n" ); return NULL; } else if ( !idStr::Icmp( cmd, "close" ) ) { DisableMenu( ); return NULL; } else if ( !idStr::Icmp( cmd, "spectate" ) ) { ToggleSpectate(); DisableMenu( ); return NULL; } else if ( !idStr::Icmp( cmd, "admin" ) ) { if ( args.Argc() - icmd >= 1 ) { idStr igArg = args.Argv( icmd++ ); idStr input( currentGui->State().GetString( "admin_console_input" ) ); input.StripTrailing( "\n" ); //jshepard: check to see if this is a server before using rcon! if( gameLocal.isServer ) { char redirectBuffer[ RCON_HISTORY_SIZE ]; common->BeginRedirect( (char *)redirectBuffer, sizeof( redirectBuffer ), LocalServerRedirect ); if( !igArg.Icmp( "tab" ) ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "tabComplete \"%s\"\n", input.c_str() ) ); } else if( !igArg.Icmp( "command" ) ) { currentGui->SetStateString( "admin_console_input", "" ); ReceiveRemoteConsoleOutput( input.c_str() ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "%s\n", input.c_str() ) ); } common->EndRedirect(); } else { if( !igArg.Icmp( "tab" ) ) { cmdSystem->BufferCommandText( CMD_EXEC_APPEND, va( "rcon tabComplete \"%s\"\n", input.c_str() ) ); } else if( !igArg.Icmp( "command" ) ) { currentGui->SetStateString( "admin_console_input", "" ); cmdSystem->BufferCommandText( CMD_EXEC_APPEND, va( "rcon \"%s\"\n", input.c_str() ) ); ReceiveRemoteConsoleOutput( input.c_str() ); } } } continue; } else if ( !idStr::Icmp( cmd, "chatmessage" ) ) { int mode = currentGui->State().GetInt( "messagemode" ); // RAVEN BEGIN // bdube: dont send chat message if there was no text specified const char* text; text = currentGui->State().GetString( "chattext" ); if ( *text ) { if ( mode ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "sayTeam \"%s\"", text ) ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "say \"%s\"", text ) ); } } // RAVEN BEGIN currentGui->SetStateString( "chattext", "" ); if ( currentMenu == 1 || currentMenu == 3 ) { return "continue"; } else { DisableMenu(); return NULL; } } else if ( !idStr::Icmp( cmd, "toggleReady" ) ) { ToggleReady( ); DisableMenu( ); return NULL; } else if ( !idStr::Icmp( cmd, "play" ) ) { if ( args.Argc() - icmd >= 1 ) { idStr snd = args.Argv( icmd++ ); int channel = 1; if ( snd.Length() == 1 ) { channel = atoi( snd ); snd = args.Argv( icmd++ ); } soundSystem->PlayShaderDirectly( SOUNDWORLD_GAME, snd, channel ); } continue; } else if ( !idStr::Icmp( cmd, "callVote" ) ) { // RAVEN BEGIN // shouchard: new functionality to match the new interface voteStruct_t voteData; memset( &voteData, 0, sizeof( voteData ) ); // kick int uiKickSelection = mainGui->State().GetInt( "playerList_sel_0" ); if ( -1 != uiKickSelection ) { voteData.m_kick = kickVoteMap[ uiKickSelection ]; voteData.m_fieldFlags |= VOTEFLAG_KICK; } // restart if ( 0 != mainGui->State().GetInt( "vote_val2_sel" ) ) { voteData.m_fieldFlags |= VOTEFLAG_RESTART; } if ( 0 != mainGui->State().GetBool( "si_shuffleteams" ) ) { voteData.m_fieldFlags |= VOTEFLAG_SHUFFLE; } // map int uiMapSelection = mainGui->State().GetInt( "mapList_sel_0" ); if ( -1 != uiMapSelection ) { // rjohnson: code commented out below would get the text friendly name of the map and not the file name int mapNum = mainGui->State().GetInt( va( "mapList_item_%d_id", uiMapSelection ) ); if ( mapNum >= 0 ) { const idDict *dict = fileSystem->GetMapDecl( mapNum ); voteData.m_map = dict->GetString( "path" ); voteData.m_fieldFlags |= VOTEFLAG_MAP; } // const char *mapName = mainGui->State().GetString( va( "mapList_item_%d", uiMapSelection ) ); // if ( NULL != mapName && '\0' != mapName[0] ) { // if ( mapFileName[ 0 ] ) { // voteData.m_map = va( "mp/%s", mapName ); // voteData.m_fieldFlags |= VOTEFLAG_MAP; // } } // gametype // todo: need a function for switching between gametype strings and values int uiGameTypeInt = mainGui->GetStateInt( "currentGametype" ); const char *currentGameTypeString = gameLocal.serverInfo.GetString( "si_gametype" ); int serverGameTypeInt = GameTypeToVote( currentGameTypeString ); if ( uiGameTypeInt != serverGameTypeInt ) { voteData.m_gameType = uiGameTypeInt; voteData.m_fieldFlags |= VOTEFLAG_GAMETYPE; } // time limit int uiTimeLimit = mainGui->GetStateInt( "timeLimit" ); if ( uiTimeLimit != gameLocal.serverInfo.GetInt( "si_timeLimit" ) ) { voteData.m_timeLimit = uiTimeLimit; voteData.m_fieldFlags |= VOTEFLAG_TIMELIMIT; } // autobalance int uiBalanceTeams = mainGui->GetStateInt( "vote_val6_sel" ); if ( uiBalanceTeams != gameLocal.serverInfo.GetInt( "si_autobalance" ) ) { voteData.m_teamBalance = uiBalanceTeams; voteData.m_fieldFlags |= VOTEFLAG_TEAMBALANCE; } // allow spectators /* int uiAllowSpectators = mainGui->GetStateInt( "vote_val7_sel" ); if ( uiAllowSpectators != gameLocal.serverInfo.GetInt( "si_spectators" ) ) { voteData.m_spectators = uiAllowSpectators; voteData.m_fieldFlags |= VOTEFLAG_SPECTATORS; } */ // minimum players int uiBuying = mainGui->GetStateInt( "buying" ); if ( uiBuying != gameLocal.serverInfo.GetInt( "si_isBuyingEnabled" ) ) { voteData.m_buying = uiBuying; voteData.m_fieldFlags |= VOTEFLAG_BUYING; } // roundlimit (tourney only) int uiTourneyLimit = mainGui->GetStateInt( "tourneylimit" ); if ( uiTourneyLimit != gameLocal.serverInfo.GetInt( "si_tourneyLimit" ) ) { voteData.m_tourneyLimit = uiTourneyLimit; voteData.m_fieldFlags |= VOTEFLAG_TOURNEYLIMIT; } // capturelimit (ctf only) int uiCaptureLimit = mainGui->GetStateInt( "capturelimit" ); if ( uiCaptureLimit != gameLocal.serverInfo.GetInt( "si_captureLimit" ) ) { voteData.m_captureLimit = uiCaptureLimit; voteData.m_fieldFlags |= VOTEFLAG_CAPTURELIMIT; } // controltime (deadzone only) int uiControlTime = mainGui->GetStateInt( "controlTime" ); if ( uiControlTime != gameLocal.serverInfo.GetInt( "si_controlTime" ) ) { voteData.m_controlTime = uiControlTime; voteData.m_fieldFlags |= VOTEFLAG_CONTROLTIME; } // fraglimit (DM & TDM only) int uiFragLimit = mainGui->GetStateInt( "fraglimit" ); if ( uiFragLimit != gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) { voteData.m_fragLimit = uiFragLimit; voteData.m_fieldFlags |= VOTEFLAG_FRAGLIMIT; } DisableMenu(); // clear any disallowed votes int disallowedVotes = gameLocal.serverInfo.GetInt( "si_voteFlags" ); for( int i = 0; i < NUM_VOTES; i++ ) { if( disallowedVotes & (1 << i) ) { voteData.m_fieldFlags &= ~(1 << i); } } // this means we haven't changed anything if ( 0 == voteData.m_fieldFlags ) { //AddChatLine( common->GetLocalizedString( "#str_104400" ) ); } else { ClientCallPackedVote( voteData ); } /* // sjh: original doom code here vote_flags_t voteIndex = (vote_flags_t)mainGui->State().GetInt( "voteIndex" ); if ( voteIndex == VOTE_MAP ) { int mapNum = mapList->GetSelection( NULL, 0 ); if ( mapNum >= 0 ) { const idDict *dict = fileSystem->GetMapDecl( mapNum ); if ( dict ) { ClientCallVote( VOTE_MAP, dict->GetString( "path" ) ); } } } else { voteValue = mainGui->State().GetString( "str_voteValue" ); if ( voteIndex == VOTE_KICK ) { vote_clientNum = kickVoteMap[ atoi( voteValue ) ]; ClientCallVote( voteIndex, va( "%d", vote_clientNum ) ); } else { ClientCallVote( voteIndex, voteValue ); } } */ return NULL; } else if ( !idStr::Icmp( cmd, "voteYes" ) ) { gameLocal.mpGame.CastVote( gameLocal.localClientNum, true ); DisableMenu(); return NULL; } else if ( !idStr::Icmp( cmd, "voteNo" ) ) { gameLocal.mpGame.CastVote( gameLocal.localClientNum, false ); DisableMenu(); return NULL; } else if ( !idStr::Icmp( cmd, "click_playerList" ) ) { // push data into the name field int sel = mainGui->GetStateInt( "playerList_sel_0" ); if ( -1 == sel ) { mainGui->SetStateString( "playerKick", "" ); } else { mainGui->SetStateString( "playerKick", kickVoteMapNames[ sel ] ); } continue; } else if ( !idStr::Icmp( cmd, "click_voteMapList" ) ) { int sel = mainGui->GetStateInt( "mapList_sel_0" ); if ( -1 == sel ) { mainGui->SetStateString( "mapName", "" ); } else { mainGui->SetStateString( "mapName", mainGui->GetStateString( va( "mapList_item_%d", sel ) ) ); } continue; } else if ( !idStr::Icmp( cmd, "setVoteMapList" ) ) { #ifdef _XENON // Xenon should not get here assert( 0 ); #else int numMaps = fileSystem->GetNumMaps(); const idDict *dict; int numMapsAdded = 0; int i; int gameTypeInt = mainGui->GetStateInt( "currentGametype" ); const char *gameType = NULL; switch ( gameTypeInt ) { case VOTE_GAMETYPE_DM: gameType = "DM"; break; case VOTE_GAMETYPE_TOURNEY: gameType = "Tourney"; break; case VOTE_GAMETYPE_TDM: gameType = "Team DM"; break; case VOTE_GAMETYPE_CTF: gameType = "CTF"; break; case VOTE_GAMETYPE_ARENA_CTF: gameType = "Arena CTF"; break; case VOTE_GAMETYPE_DEADZONE: gameType = "DeadZone"; break; } if ( NULL == gameType || 0 == *gameType || 0 == idStr::Icmp( gameType, "singleplayer" ) ) { gameType = "DM"; } idStr originalMapName = gameLocal.serverInfo.GetString( "si_map" ); originalMapName.StripFileExtension(); bool foundOriginalMap = false; int originalMapIndex = -1; for ( i = 0; i < numMaps; i++ ) { dict = fileSystem->GetMapDecl( i ); bool mapOk = false; //if the gametype is DM, check for any of these types... if( !(strcmp( gameType, "DM")) || !(strcmp( gameType, "Team DM")) ) { if ( dict && ( dict->GetBool( "DM" ) || dict->GetBool( "Team DM" ) || dict->GetBool( "CTF" ) || dict->GetBool( "Tourney" ) || dict->GetBool( "Arena CTF" )) ) { mapOk = true; } //but if not, match the gametype. } else if ( dict && dict->GetBool( gameType ) ) { mapOk = true; } if( mapOk ) { const char *mapName = dict->GetString( "name" ); if ( '\0' == mapName[ 0 ] ) { mapName = dict->GetString( "path" ); } mapName = common->GetLocalizedString( mapName ); if ( idStr::Icmp(dict->GetString( "path" ), originalMapName) == 0 ) { foundOriginalMap = true; originalMapIndex = numMapsAdded; } mainGui->SetStateString( va( "mapList_item_%d", numMapsAdded), mapName ); mainGui->SetStateInt( va( "mapList_item_%d_id", numMapsAdded), i ); numMapsAdded++; } } mainGui->DeleteStateVar( va( "mapList_item_%d", numMapsAdded ) ); if ( !foundOriginalMap ) { mainGui->SetStateInt( "mapList_sel_0", 0 ); mainGui->SetStateString( "mapName", mainGui->GetStateString( "mapList_item_0" ) ); } else { mainGui->SetStateInt( "mapList_sel_0", originalMapIndex ); mainGui->SetStateString( "mapName", mainGui->GetStateString( va( "mapList_item_%d", originalMapIndex ) ) ); } #endif continue; } else if ( !idStr::Icmp( cmd, "setVoteData" ) ) { #ifdef _XENON // Xenon should not get here assert( 0 ); #else // push data into the vote_ cvars so the UI can start at where we currently are int players; for ( players=0; players<gameLocal.numClients; players++ ) { mainGui->SetStateString( va( "playerList_item_%d", players ), kickVoteMapNames[players] ); } if ( players < MAX_CLIENTS ) { mainGui->DeleteStateVar( va( "playerList_item_%d", players ) ); } mainGui->SetStateString( "playerList_sel_0", "-1" ); mainGui->SetStateString( "playerKick", "" ); mainGui->SetStateInt( "vote_val2_sel", 0 ); // RAVEN BEGIN // mekberg: get localized string. const char *mapName = gameLocal.serverInfo.GetString( "si_map" ); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } mainGui->SetStateString( "mapName", mapName ); // RAVEN END int numMaps = fileSystem->GetNumMaps(); const idDict *dict; int numMapsAdded = 0; int i; const char *gameType = gameLocal.serverInfo.GetString( "si_gametype" ); // this will need to change for multi-votes if ( NULL == gameType || 0 == *gameType || 0 == idStr::Icmp( gameType, "singleplayer" ) ) { gameType = "DM"; } // RAVEN BEGIN // jshepard: if gametype is DM, then we can play on DM, TeamDM, Tourney or CTF maps. So, all of them, basically. for ( i = 0; i < numMaps; i++ ) { dict = fileSystem->GetMapDecl( i ); bool mapOk = false; //if the gametype is DM, check for any of these types... if( !(strcmp( gameType, "DM")) || !(strcmp( gameType, "Team DM")) ) { if ( dict && ( dict->GetBool( "DM" ) || dict->GetBool( "Team DM" ) || dict->GetBool( "CTF" ) || dict->GetBool( "Tourney" ) || dict->GetBool( "Arena CTF" )) ) { mapOk = true; } //but if not, match the gametype. } else if ( dict && dict->GetBool( gameType ) ) { mapOk = true; } if( mapOk ) { const char *mapName = dict->GetString( "name" ); if ( '\0' == mapName[ 0 ] ) { mapName = dict->GetString( "path" ); } mapName = common->GetLocalizedString( mapName ); mainGui->SetStateString( va( "mapList_item_%d", numMapsAdded), mapName ); numMapsAdded++; } } mainGui->DeleteStateVar( va( "mapList_item_%d", numMapsAdded ) ); mainGui->SetStateString( "mapList_sel_0", "-1" ); const char *currentGameTypeString = gameLocal.serverInfo.GetString( "si_gameType" ); int uiGameTypeInt = GameTypeToVote( currentGameTypeString ); mainGui->SetStateInt( "currentGametype", uiGameTypeInt ); mainGui->SetStateInt( "timelimit", gameLocal.serverInfo.GetInt( "si_timeLimit" ) ); mainGui->SetStateInt( "tourneylimit", gameLocal.serverInfo.GetInt( "si_tourneyLimit" ) ); mainGui->SetStateInt( "capturelimit", gameLocal.serverInfo.GetInt( "si_captureLimit" ) ); mainGui->SetStateInt( "controlTime", gameLocal.serverInfo.GetInt( "si_controlTime" ) ); mainGui->SetStateInt( "vote_val6_sel", gameLocal.serverInfo.GetInt( "si_autobalance" ) ); mainGui->SetStateInt( "buying", gameLocal.serverInfo.GetInt( "si_isBuyingEnabled" ) ); mainGui->SetStateInt( "fraglimit", gameLocal.serverInfo.GetInt( "si_fraglimit" ) ); mainGui->SetStateInt( "si_shuffleteams", 0 ); mainGui->StateChanged( gameLocal.time ); mainGui->HandleNamedEvent( "gametypeChange" ); #endif continue; } else if ( !idStr::Icmp( cmd, "populateServerInfo" ) ) { #ifdef _XENON // Xenon should not get here assert( 0 ); #else mainGui->SetStateString( "serverInfoList_item_0", va( "%s:\t%s", common->GetLocalizedString( "#str_107725" ), gameLocal.serverInfo.GetString( "si_name" ) ) ); idStr serverAddress = networkSystem->GetServerAddress( ); mainGui->SetStateString( "serverInfoList_item_1", va( "%s:\t%s", common->GetLocalizedString( "#str_107726" ), serverAddress.c_str() ) ); mainGui->SetStateString( "serverInfoList_item_2", va( "%s:\t%s", common->GetLocalizedString( "#str_107727" ), LocalizeGametype() ) ); const char *mapName = gameLocal.serverInfo.GetString( "si_map" ); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } // rhummer localized "map name" mainGui->SetStateString( "serverInfoList_item_3", va( "%s\t%s", common->GetLocalizedString( "#str_107730" ), mapName ) ); const char *gameType = gameLocal.serverInfo.GetString( "si_gametype" ); if ( 0 == idStr::Icmp( gameType, "CTF" ) ) { mainGui->SetStateString( "serverInfoList_item_4", va( "%s:\t%s", common->GetLocalizedString( "#str_107661" ), gameLocal.serverInfo.GetString( "si_captureLimit" ) ) ); } else if ( 0 == idStr::Icmp( gameType, "DM" ) || 0 == idStr::Icmp( gameType, "Team DM" ) ) { mainGui->SetStateString( "serverInfoList_item_4", va( "%s:\t%s", common->GetLocalizedString( "#str_107660" ), gameLocal.serverInfo.GetString( "si_fragLimit" ) ) ); } mainGui->SetStateString( "serverInfoList_item_5", va( "%s:\t%s", common->GetLocalizedString( "#str_107659" ), gameLocal.serverInfo.GetString( "si_timeLimit" ) ) ); mainGui->SetStateString( "serverInfoList_item_6", va( "%s:\t%s", common->GetLocalizedString( "#str_107662" ), gameLocal.serverInfo.GetString( "si_pure" ) ) ); mainGui->SetStateString( "serverInfoList_item_7", va( "%s:\t%s", common->GetLocalizedString( "#str_107663" ), gameLocal.serverInfo.GetString( "si_maxPlayers" ) ) ); mainGui->SetStateString( "serverInfoList_item_8", va( "%s:\t%s", common->GetLocalizedString( "#str_107664" ), gameLocal.serverInfo.GetString( "si_teamDamage" ) ) ); mainGui->SetStateString( "serverInfoList_item_9", va( "%s:\t%s", common->GetLocalizedString( "#str_104254" ), gameLocal.serverInfo.GetString( "si_spectators" ) ) ); #endif continue; // handler for the server admin tab (normal stuff) } else if ( !idStr::Icmp( cmd, "checkAdminPass" )) { //password has been added, so call the rcon verifypassword command cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rcon verifyRconPass" ); continue; } else if ( !idStr::Icmp( cmd, "initServerAdmin" ) ) { mainGui->SetStateInt( "admin_server_val1_sel", 0 ); // restart defaults to off // maplist handled in initServerAdminMaplist; this needs to be called first // to properly set the gametype since we read it back to show an appropriate list const char *currentGameTypeString = gameLocal.serverInfo.GetString( "si_gameType" ); int uiGameTypeInt = GameTypeToVote( currentGameTypeString ); mainGui->SetStateInt( "admincurrentGametype", uiGameTypeInt ); mainGui->SetStateInt( "sa_timelimit", gameLocal.serverInfo.GetInt( "si_timeLimit" ) ); mainGui->SetStateInt( "sa_tourneylimit", gameLocal.serverInfo.GetInt( "si_tourneyLimit" ) ); mainGui->SetStateInt( "sa_capturelimit", gameLocal.serverInfo.GetInt( "si_captureLimit" ) ); mainGui->SetStateInt( "sa_controlTime", gameLocal.serverInfo.GetInt( "si_controlTime" ) ); mainGui->SetStateInt( "sa_autobalance", gameLocal.serverInfo.GetInt( "si_autobalance" ) ); mainGui->SetStateInt( "sa_buying", gameLocal.serverInfo.GetInt( "si_isBuyingEnabled" ) ); mainGui->SetStateInt( "sa_fraglimit", gameLocal.serverInfo.GetInt( "si_fraglimit" ) ); mainGui->SetStateInt( "sa_shuffleteams", 0 ); // mekberg: get the ban list if not server if ( !gameLocal.isServer ) { idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_GETADMINBANLIST ) ; networkSystem->ClientSendReliableMessage( outMsg ); } mainGui->StateChanged( gameLocal.time ); continue; // handler for populating the map list; called both on open and on change gametype so it'll show the right maps } else if ( !idStr::Icmp( cmd, "initServerAdminMapList" ) ) { #ifdef _XENON // Xenon should not get here assert( 0 ); #else // RAVEN BEGIN // mekberg: get localized string. const char *mapName = gameLocal.serverInfo.GetString( "si_map" ); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } mainGui->SetStateString( "sa_mapName", mapName ); // RAVEN END int numMaps = fileSystem->GetNumMaps(); const idDict *dict; int numMapsAdded = 0; int i; const char *gameType = "DM"; int gameTypeInt = mainGui->GetStateInt( "adminCurrentGametype" ); if ( VOTE_GAMETYPE_TOURNEY == gameTypeInt ) { gameType = "Tourney"; } else if ( VOTE_GAMETYPE_TDM == gameTypeInt ) { gameType = "Team DM"; } else if ( VOTE_GAMETYPE_CTF == gameTypeInt ) { gameType = "CTF"; } else if ( VOTE_GAMETYPE_ARENA_CTF == gameTypeInt ) { gameType = "Arena CTF"; } else if ( VOTE_GAMETYPE_DEADZONE == gameTypeInt ) { gameType = "DeadZone"; } else { gameType = "DM"; } // sanity check if ( NULL == gameType || 0 == *gameType || 0 == idStr::Icmp( gameType, "singleplayer" ) ) { gameType = "DM"; } for ( i = 0; i < numMaps; i++ ) { dict = fileSystem->GetMapDecl( i ); bool mapOk = false; //if the gametype is DM, check for any of these types... if( !(strcmp( gameType, "DM")) || !(strcmp( gameType, "Team DM")) ) { if ( dict && ( dict->GetBool( "DM" ) || dict->GetBool( "Team DM" ) || dict->GetBool( "CTF" ) || dict->GetBool( "Tourney" ) || dict->GetBool( "Arena CTF" )) ) { mapOk = true; } //but if not, match the gametype. } else if ( dict && dict->GetBool( gameType ) ) { mapOk = true; } if ( mapOk ) { const char *mapName = dict->GetString( "name" ); if ( '\0' == mapName[ 0 ] ) { mapName = dict->GetString( "path" ); } mapName = common->GetLocalizedString( mapName ); mainGui->SetStateString( va( "sa_mapList_item_%d", numMapsAdded), mapName ); mainGui->SetStateInt( va( "sa_mapList_item_%d_id", numMapsAdded), i ); numMapsAdded++; } } mainGui->DeleteStateVar( va( "sa_mapList_item_%d", numMapsAdded ) ); mainGui->SetStateString( "sa_mapList_sel_0", "-1" ); #endif continue; // handler for updating the current map in the name } else if ( !idStr::Icmp( cmd, "serverAdminUpdateMap" ) ) { int mapSelection = mainGui->GetStateInt( "sa_mapList_sel_0" ); if ( -1 == mapSelection ) { idDecl *mapDecl = const_cast<idDecl *>(declManager->FindType( DECL_MAPDEF, gameLocal.serverInfo.GetString( "si_map" ), false )); if ( mapDecl ) { idDeclEntityDef *mapDef = static_cast<idDeclEntityDef *>( mapDecl ); mainGui->SetStateString( "sa_mapName", common->GetLocalizedString( mapDef->dict.GetString( "name" )) ); } else { mainGui->SetStateString( "sa_mapName", gameLocal.serverInfo.GetString( "si_map" ) ); } } else { int mapNum = mainGui->State().GetInt( va( "sa_mapList_item_%d_id", mapSelection ) ); if ( mapNum >= 0 ) { const idDict *dict = fileSystem->GetMapDecl( mapNum ); mainGui->SetStateString( "sa_mapName", common->GetLocalizedString( dict->GetString( "name" )) ); } } continue; // handler for initializing the player list on the admin player tab } else if ( !idStr::Icmp( cmd, "initServerAdminPlayer" ) ) { int players; for ( players=0; players<gameLocal.numClients; players++ ) { mainGui->SetStateString( va( "sa_playerList_item_%d", players ), kickVoteMapNames[players] ); } if ( players < MAX_CLIENTS ) { mainGui->DeleteStateVar( va( "sa_playerList_item_%d", players ) ); //common->Printf( "DELETING at slot %d\n", players ); } mainGui->SetStateString( "sa_playerList_sel_0", "-1" ); continue; // handler for actually changing something on the server admin tab } else if ( !idStr::Icmp( cmd, "handleServerAdmin" ) ) { // read in a bunch of data, pack it into the appropriate structure serverAdminData_t data; memset( &data, 0, sizeof( data ) ); data.restartMap = 0 != mainGui->GetStateInt( "admin_server_val1_sel" ); // map list here int uiMapSelection = mainGui->State().GetInt( "sa_mapList_sel_0" ); if (-1 != uiMapSelection ) { int mapNum = mainGui->State().GetInt( va( "sa_mapList_item_%d_id", uiMapSelection ) ); if ( mapNum >= 0 ) { const idDict *dict = fileSystem->GetMapDecl( mapNum ); data.mapName = common->GetLocalizedString( dict->GetString( "path" )); } else { data.mapName = gameLocal.serverInfo.GetString( "si_map" ); } } else { data.mapName = gameLocal.serverInfo.GetString( "si_map" ); } switch ( mainGui->GetStateInt( "admincurrentGametype" ) ) { case VOTE_GAMETYPE_DM: data.gameType = GAME_DM; break; case VOTE_GAMETYPE_TOURNEY: data.gameType = GAME_TOURNEY; break; case VOTE_GAMETYPE_TDM: data.gameType = GAME_TDM; break; case VOTE_GAMETYPE_CTF: data.gameType = GAME_CTF; break; case VOTE_GAMETYPE_ARENA_CTF: data.gameType = GAME_ARENA_CTF; break; case VOTE_GAMETYPE_DEADZONE: data.gameType = GAME_DEADZONE; } data.captureLimit = mainGui->GetStateInt( "sa_captureLimit" ); data.fragLimit = mainGui->GetStateInt( "sa_fragLimit" ); data.tourneyLimit = mainGui->GetStateInt( "sa_tourneylimit" ); data.timeLimit = mainGui->GetStateInt( "sa_timeLimit" ); data.buying = mainGui->GetStateInt( "sa_buying" ); data.autoBalance = 0 != mainGui->GetStateInt( "sa_autobalance" ); data.buying = 0 != mainGui->GetStateInt( "sa_buying" ); data.controlTime = mainGui->GetStateInt( "sa_controlTime" ); data.shuffleTeams = 0 != mainGui->GetStateInt( "sa_shuffleteams" ); // make the call to change the server data if ( gameLocal.mpGame.HandleServerAdminCommands( data ) ) { DisableMenu(); return NULL; } continue; // handler for the kick button on the player tab of the server admin gui } else if ( !idStr::Icmp( cmd, "handleServerAdminKick" ) ) { int uiKickSelection = mainGui->State().GetInt( "sa_playerList_sel_0" ); if ( -1 != uiKickSelection ) { HandleServerAdminKickPlayer( kickVoteMap[ uiKickSelection ] ); DisableMenu(); return NULL; } //common->Printf( "HANDLE SERVER ADMIN KICK!\n" ); continue; // handler for the ban button on the player tab of the server admin gui } else if ( !idStr::Icmp( cmd, "handleServerAdminBan" ) ) { //common->Printf( "HANDLE SERVER ADMIN BAN!\n" ); int uiBanSelection = mainGui->State().GetInt( "sa_playerList_sel_0" ); if ( -1 != uiBanSelection ) { HandleServerAdminBanPlayer( kickVoteMap[ uiBanSelection ] ); DisableMenu(); mainGui->DeleteStateVar( va( "sa_banList_item_%d", 0 ) ); mainGui->SetStateString( "sa_banList_sel_0", "-1" ); return NULL; } continue; // handler for the remove ban button on the player tab of the server admin gui } else if ( !idStr::Icmp( cmd, "handleServerAdminRemoveBan" ) ) { //common->Printf( "HANDLE SERVER ADMIN REMOVE BAN!\n" ); int uiBanSelection = mainGui->State().GetInt( "sa_banList_sel_0" ); if ( -1 != uiBanSelection ) { idStr guid = &mainGui->GetStateString( va( "sa_banList_item_%d", uiBanSelection ) )[ 4 ]; guid = guid.ReplaceChar( '\t', '\0' ); guid = &guid.c_str()[ strlen( guid.c_str() ) + 1 ]; HandleServerAdminRemoveBan( guid.c_str() ); DisableMenu(); return NULL; } continue; // handler for the switch teams button on the player tab of the server admin gui } else if ( !idStr::Icmp( cmd, "handleServerAdminSwitchTeams" ) ) { if ( gameLocal.IsTeamGame() ) { int uiSwitchSelection = mainGui->State().GetInt( "sa_playerList_sel_0" ); if ( -1 != uiSwitchSelection ) { HandleServerAdminForceTeamSwitch( kickVoteMap[ uiSwitchSelection ] ); DisableMenu(); return NULL; } } continue; // handler for the show ban list button of the server admin gui } else if ( !idStr::Icmp( cmd, "populateBanList" ) ) { gameLocal.PopulateBanList( mainGui ); continue; // RAVEN END } else if ( !idStr::Icmp( cmd, "voteyes" ) ) { CastVote( gameLocal.localClientNum, true ); DisableMenu(); return NULL; } else if ( !idStr::Icmp( cmd, "voteno" ) ) { CastVote( gameLocal.localClientNum, false ); DisableMenu(); return NULL; } else if ( !idStr::Icmp( cmd, "bind" ) ) { if ( args.Argc() - icmd >= 2 ) { idStr key = args.Argv( icmd++ ); idStr bind = args.Argv( icmd++ ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "bindunbindtwo \"%s\" \"%s\"", key.c_str(), bind.c_str() ) ); mainGui->SetKeyBindingNames(); } continue; } else if ( !idStr::Icmp( cmd, "clearbind" ) ) { if ( args.Argc() - icmd >= 1 ) { idStr bind = args.Argv( icmd++ ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "unbind \"%s\"", bind.c_str() ) ); mainGui->SetKeyBindingNames(); } continue; } else if ( !idStr::Icmp( cmd, "MAPScan" ) ) { #ifdef _XENON // Xenon should not get here assert( 0 ); #else const char *gametype = gameLocal.serverInfo.GetString( "si_gameType" ); if ( gametype == NULL || *gametype == 0 || idStr::Icmp( gametype, "singleplayer" ) == 0 ) { gametype = "DM"; } int i, num; idStr si_map = gameLocal.serverInfo.GetString("si_map"); const idDict *dict; mapList->Clear(); mapList->SetSelection( -1 ); num = fileSystem->GetNumMaps(); for ( i = 0; i < num; i++ ) { dict = fileSystem->GetMapDecl( i ); if ( dict ) { // any MP gametype supported bool isMP = false; int igt = GAME_SP + 1; while ( si_gameTypeArgs[ igt ] ) { if ( dict->GetBool( si_gameTypeArgs[ igt ] ) ) { isMP = true; break; } igt++; } if ( isMP ) { const char *mapName = dict->GetString( "name" ); if ( mapName[0] == '\0' ) { mapName = dict->GetString( "path" ); } mapName = common->GetLocalizedString( mapName ); mapList->Add( i, mapName ); if ( !si_map.Icmp( dict->GetString( "path" ) ) ) { mapList->SetSelection( mapList->Num() - 1 ); } } } } // set the current level shot SetMapShot( ); #endif return "continue"; } else if ( !idStr::Icmp( cmd, "click_maplist" ) ) { SetMapShot( ); return "continue"; } else if ( !idStr::Icmp( cmd, "sm_select_player" ) ) { idStr vcmd; if ( args.Argc() - icmd >= 1 ) { vcmd = args.Argv( icmd++ ); } int index = atoi( vcmd.c_str() ); if( index > 0 && index < MAX_CLIENTS && statSummary && currentMenu == 3 ) { statManager->UpdateEndGameHud( statSummary, index - 1 ); } return "continue"; } else if ( !idStr::Icmp( cmd, "update_model" ) ) { UpdateMPSettingsModel( currentGui ); continue; } else if( !idStr::Icmp( cmd, "ingameStats" ) ) { if ( args.Argc() - icmd >= 1 ) { idStr igArg = args.Argv( icmd++ ); if( !igArg.Icmp( "init" ) ) { // setup the player list statManager->SetupStatWindow( currentGui ); } else if( !igArg.Icmp( "spectator" ) ) { int currentSel = currentGui->State().GetInt( "spec_names_sel_0", "-1" ); currentGui->SetStateString( "dm_names_sel_0", "-1" ); currentGui->SetStateString( "team_1_names_sel_0", "-1" ); currentGui->SetStateString( "team_2_names_sel_0", "-1" ); statManager->SelectStatWindow( currentSel, TEAM_MAX ); // asalmon: Need to refresh stats periodically if the player is looking at stats currentStatClient = currentSel; currentStatTeam = TEAM_MAX; } else if( !igArg.Icmp( "dm" ) ) { int currentSel = currentGui->State().GetInt( "dm_names_sel_0", "-1" ); currentGui->SetStateString( "spec_names_sel_0", "-1" ); currentGui->SetStateString( "team_1_names_sel_0", "-1" ); currentGui->SetStateString( "team_2_names_sel_0", "-1" ); statManager->SelectStatWindow( currentSel, 0 ); // asalmon: Need to refresh stats periodically if the player is looking at stats currentStatClient = currentSel; currentStatTeam = 0; } else if( !igArg.Icmp( "strogg" ) ) { int currentSel = currentGui->State().GetInt( "team_2_names_sel_0", "-1" ); currentGui->SetStateString( "spec_names_sel_0", "-1" ); currentGui->SetStateString( "team_1_names_sel_0", "-1" ); currentGui->SetStateString( "dm_names_sel_0", "-1" ); statManager->SelectStatWindow( currentSel, TEAM_STROGG ); // asalmon: Need to refresh stats periodically if the player is looking at stats currentStatClient = currentSel; currentStatTeam = TEAM_STROGG; } else if( !igArg.Icmp( "marine" ) ) { int currentSel = currentGui->State().GetInt( "team_1_names_sel_0", "-1" ); currentGui->SetStateString( "spec_names_sel_0", "-1" ); currentGui->SetStateString( "team_2_names_sel_0", "-1" ); currentGui->SetStateString( "dm_names_sel_0", "-1" ); statManager->SelectStatWindow( currentSel, TEAM_MARINE ); // asalmon: Need to refresh stats periodically if the player is looking at stats currentStatClient = currentSel; currentStatTeam = TEAM_MARINE; } } continue; } else if( !idStr::Icmp( cmd, "mainMenu" ) ) { DisableMenu(); static idStr menuCmd; menuCmd.Clear(); // cnicholson: In order to avoid repeated eventnames from screwing up the menu system, clear it. menuCmd.Append( "main" ); const char* eventName = ""; if( args.Argc() - icmd >= 1 ) { eventName = args.Argv( icmd++ ); menuCmd.Append( " " ); menuCmd.Append( eventName ); } return menuCmd.c_str(); } // RAVEN BEGIN // cnicholson: The menu calls this prior to entering multiplayer settings. What it does is to check the current crosshair, and compare it // agasint the list of crosshairs in player.def under the player_marine_mp section. If it finds a match, it assigns the // crosshair to the next one in the list. If there isn't one, or if its the end of the list, the first found crosshair is used. else if ( !idStr::Icmp( cmd, "chooseCrosshair" ) ) { #ifndef _XENON #ifndef _XENON const idDeclEntityDef *def = static_cast<const idDeclEntityDef*>( declManager->FindType( DECL_ENTITYDEF, "player_marine_mp", false, true ) ); #else bool insideLevelLoad = declManager->GetInsideLoad(); if ( !insideLevelLoad ) { declManager->SetInsideLoad( true ); } const idDeclEntityDef *def = static_cast<const idDeclEntityDef*>( declManager->FindType( DECL_ENTITYDEF, "player_marine_mp_ui", false, false ) ); declManager->SetInsideLoad( insideLevelLoad ); #endif idStr currentCrosshair = cvarSystem->GetCVarString("g_crosshairCustomFile"); const idKeyValue* kv = def->dict.MatchPrefix("mtr_crosshair", NULL); while ( kv ) { if ( kv->GetValue() == currentCrosshair.c_str() ) { kv = def->dict.MatchPrefix("mtr_crosshair", kv ); break; } kv = def->dict.MatchPrefix("mtr_crosshair", kv ); } if ( !kv ){ kv = def->dict.MatchPrefix("mtr_crosshair", NULL ); } idStr newCrosshair(kv->GetValue()); mainGui->SetStateString ( "crossImage", newCrosshair.c_str()); const idMaterial *material = declManager->FindMaterial( newCrosshair.c_str() ); if ( material ) { material->SetSort( SS_GUI ); } cvarSystem->SetCVarString("g_crosshairCustomFile", newCrosshair.c_str()); #endif } // RAVEN END else if( !idStr::Icmp( cmd, "friend" ) ) { // we friend/unfriend from the stat window, so use that to get selection info int selectionTeam = -1; int selectionIndex = -1; // get the selected client num, as well as the selectionIndex/Team from the stat window int client = statManager->GetSelectedClientNum( &selectionIndex, &selectionTeam ); if( ( client < 0 || client >= MAX_CLIENTS ) || !gameLocal.GetLocalPlayer() ) { continue; } // un-mark this client as a friend if( gameLocal.GetLocalPlayer()->IsFriend( client ) ) { networkSystem->RemoveFriend( client ); } else { networkSystem->AddFriend( client ); } // refresh with new info statManager->SetupStatWindow( currentGui ); statManager->SelectStatWindow( selectionIndex, selectionTeam ); continue; } else if( !idStr::Icmp( cmd, "mute" ) ) { // we mute/unmute from the stat window, so use that to get selection info int selectionTeam = -1; int selectionIndex = -1; // get the selected client num, as well as the selectionIndex/Team from the stat window int client = statManager->GetSelectedClientNum( &selectionIndex, &selectionTeam ); ClientVoiceMute( client, !gameLocal.GetLocalPlayer()->IsPlayerMuted( client ) ); // refresh with new info statManager->SetupStatWindow( currentGui ); statManager->SelectStatWindow( selectionIndex, selectionTeam ); continue; } //RAVEN BEGIN //asalmon: pass through some commands that need to be handled in the main menu handle function else if(strstr( cmd, "LiveInviteAccept" ) == cmd){ #ifdef _XENON Live()->SetInvite(); #endif } else if ((strstr( cmd, "FilterMPMapList" ) == cmd) || (strstr( cmd, "AddMapLive" ) == cmd) || (strstr( cmd, "RemoveMapLive" ) == cmd) ) { static idStr menuCmd; menuCmd.Clear(); menuCmd.Append( cmd ); return menuCmd.c_str(); } else if( !idStr::Icmp( cmd, "toggleTourney" ) ) { if( gameLocal.gameType == GAME_TOURNEY ) { ToggleSpectate(); DisableMenu( ); return NULL; } continue; } //RAVEN END common->Printf( "idMultiplayerGame::HandleGuiCommands: '%s' unknown\n", cmd ); } return "continue"; } /* =============== idMultiplayerGame::SetShaderParms =============== */ void idMultiplayerGame::SetShaderParms( renderView_t *view ) { if ( gameLocal.IsFlagGameType() ) { view->shaderParms[ 1 ] = ( ((rvCTFGameState*)GetGameState())->GetFlagState( TEAM_MARINE ) != FS_AT_BASE ); view->shaderParms[ 2 ] = ( ((rvCTFGameState*)GetGameState())->GetFlagState( TEAM_STROGG ) != FS_AT_BASE ); } } /* ================ idMultiplayerGame::Draw server demo: clientNum == MAX_CLIENTS ================ */ bool idMultiplayerGame::Draw( int clientNum ) { idPlayer *player, *viewPlayer; idUserInterface *hud = NULL; if ( clientNum == MAX_CLIENTS ) { assert( gameLocal.GetDemoState() == DEMO_PLAYING ); clientNum = gameLocal.GetDemoFollowClient(); hud = gameLocal.GetDemoHud(); if ( clientNum == -1 ) { gameLocal.freeView.Draw(); return true; } } player = viewPlayer = static_cast<idPlayer *>( gameLocal.entities[ clientNum ] ); if ( player == NULL ) { return false; } if ( player->spectating ) { viewPlayer = static_cast<idPlayer *>( gameLocal.entities[ player->spectator ] ); if ( viewPlayer == NULL ) { return false; } } if ( !viewPlayer->GetRenderView() ) { return false; } SetShaderParms( viewPlayer->GetRenderView() ); // use the hud of the local player if ( !hud ) { hud = player->hud; } viewPlayer->playerView.RenderPlayerView( hud ); // allow force scoreboard to overwrite a fullscreen menu if ( currentMenu ) { #if 0 // uncomment this if you want to track when players are in a menu if ( !bCurrentMenuMsg ) { idBitMsg outMsg; byte msgBuf[ 128 ]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_MENU ); outMsg.WriteBits( 1, 1 ); networkSystem->ClientSendReliableMessage( outMsg ); bCurrentMenuMsg = true; } #endif if ( player->wantSpectate ) { mainGui->SetStateString( "spectext", common->GetLocalizedString( "#str_104249" ) ); } else { mainGui->SetStateString( "spectext", common->GetLocalizedString( "#str_104250" ) ); } // if we died, isChatting is cleared, so re-set our chatting cvar if ( gameLocal.GetLocalPlayer() && !gameLocal.GetLocalPlayer()->isChatting && !gameLocal.GetLocalPlayer()->pfl.dead ) { cvarSystem->SetCVarBool( "ui_chat", true ); cvarSystem->SetModifiedFlags( CVAR_USERINFO ); // force update } if ( currentMenu == 1 ) { UpdateMainGui(); mainGui->Redraw( gameLocal.time ); } else if( currentMenu == 2 ) { msgmodeGui->Redraw( gameLocal.time ); } else if( currentMenu == 3 ) { DrawStatSummary(); // RITUAL BEGIN // squirrel: Mode-agnostic buymenus } else if( currentMenu == 4 ) { SetupBuyMenuItems(); player->UpdateHudStats( buyMenu ); buyMenu->HandleNamedEvent( "update_buymenu" ); idPlayer* player = gameLocal.GetLocalPlayer(); buyMenu->SetStateString( "field_credits", va("%i", (int)player->buyMenuCash) ); buyMenu->Redraw(gameLocal.time); // RITUAL END } } else { #if 0 // uncomment this if you want to track when players are in a menu if ( bCurrentMenuMsg ) { idBitMsg outMsg; byte msgBuf[ 128 ]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_MENU ); outMsg.WriteBits( 0, 1 ); networkSystem->ClientSendReliableMessage( outMsg ); bCurrentMenuMsg = false; } #endif DrawScoreBoard( player ); } // RAVEN BEGIN // bdube: debugging HUD gameDebug.DrawHud(); // RAVEN END return true; } /* ================ idMultiplayerGame::UpdateHud ================ */ void idMultiplayerGame::UpdateHud( idUserInterface* _mphud ) { idPlayer *localPlayer; if ( !_mphud ) { return; } // server demos don't have a true local player, but need one for hud updates localPlayer = gameLocal.GetLocalPlayer(); if ( !localPlayer ) { assert( gameLocal.GetDemoState() == DEMO_PLAYING && gameLocal.IsServerDemo() ); assert( gameLocal.GetDemoFollowClient() >= 0 ); assert( gameLocal.entities[ gameLocal.GetDemoFollowClient() ] && gameLocal.entities[ gameLocal.GetDemoFollowClient() ]->IsType( idPlayer::GetClassType() ) ); localPlayer = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.GetDemoFollowClient() ] ); } //RAVEN BEGIN //asalmon: Turn on/off the lag icon so that clients know that they are losing connection if ( networkSystem->ClientGetTimeSinceLastPacket() > 0 && ( networkSystem->ClientGetTimeSinceLastPacket() > cvarSystem->GetCVarInteger("net_clientServerTimeout")*500 ) ) { _mphud->SetStateBool("IsLagged", true); } else{ _mphud->SetStateBool("IsLagged", false); } //RAVEN END _mphud->SetStateInt( "marine_score", teamScore[ TEAM_MARINE ] ); _mphud->SetStateInt( "strogg_score", teamScore[ TEAM_STROGG ] ); int timeLimit = gameLocal.serverInfo.GetInt( "si_timeLimit" ); // Always show GameTime() for WARMUP and COUNTDOWN. mpGameState_t state = gameState->GetMPGameState(); _mphud->SetStateString( "timeleft", GameTime() ); // RITUAL BEGIN // squirrel: Mode-agnostic buymenus /// Set "credits" gui element if( gameLocal.mpGame.IsBuyingAllowedInTheCurrentGameMode() ) { int cash = 0; idPlayer* localPlayer = gameLocal.GetLocalPlayer(); if ( !localPlayer ) { assert( gameLocal.GetDemoState() == DEMO_PLAYING && gameLocal.IsServerDemo() ); assert( gameLocal.GetDemoFollowClient() >= 0 ); assert( gameLocal.entities[ gameLocal.GetDemoFollowClient() ] && gameLocal.entities[ gameLocal.GetDemoFollowClient() ]->IsType( idPlayer::GetClassType() ) ); localPlayer = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.GetDemoFollowClient() ] ); } idPlayer* specPlayer = NULL; if ( localPlayer->spectating ) specPlayer = gameLocal.GetClientByNum( localPlayer->spectator ); if ( specPlayer ) cash = (int)specPlayer->buyMenuCash; else cash = (int)localPlayer->buyMenuCash; if( localPlayer->CanBuy() ) { _mphud->SetStateString("credits", va("%s %d %s", common->GetLocalizedString( "#str_122015" ), cash, common->GetLocalizedString( "#str_122016" ))); } else { _mphud->SetStateString("credits", va("%s %d", common->GetLocalizedString( "#str_122015" ), cash)); } } else { _mphud->SetStateString("credits", ""); } // RITUAL END bool inNonTimedState = (state == SUDDENDEATH) || (state == WARMUP) || (state == GAMEREVIEW); bool inCountdownState = (state == COUNTDOWN); if( gameLocal.gameType == GAME_TOURNEY ) { inNonTimedState |= (((rvTourneyGameState*)gameState)->GetArena( localPlayer->GetArena() ).GetState() == AS_SUDDEN_DEATH); inCountdownState |= (((rvTourneyGameState*)gameState)->GetArena( localPlayer->GetArena() ).GetState() == AS_WARMUP); } _mphud->SetStateBool( "infinity", ( !timeLimit && !inCountdownState ) || inNonTimedState ); if( gameLocal.gameType == GAME_DM ) { if( rankedPlayers.Num() ) { _mphud->SetStateString( "player1_name", rankedPlayers[ 0 ].First()->GetUserInfo()->GetString( "ui_name" ) ); _mphud->SetStateString( "player1_score", va( "%d", GetScore( rankedPlayers[ 0 ].First() ) ) ); _mphud->SetStateString( "player1_rank", "1." ); // if we're in the lead or spectating, show the person in 2nd if( ( (rankedPlayers[ 0 ].First() == localPlayer) || (localPlayer->spectating) ) && rankedPlayers.Num() > 1 ) { _mphud->SetStateString( "player2_name", rankedPlayers[ 1 ].First()->GetUserInfo()->GetString( "ui_name" ) ); _mphud->SetStateString( "player2_score", va( "%d", GetScore( rankedPlayers[ 1 ].First() ) ) ); _mphud->SetStateString( "player2_rank", va( "%d.", rankedPlayers[ 1 ].First()->GetRank() + 1 ) ); } else if( rankedPlayers[ 0 ].First() != localPlayer && !localPlayer->spectating ) { // otherwise, show our score _mphud->SetStateString( "player2_name", localPlayer->GetUserInfo()->GetString( "ui_name" ) ); _mphud->SetStateString( "player2_score", va( "%d", GetScore( localPlayer ) ) ); _mphud->SetStateString( "player2_rank", va( "%d.", localPlayer->GetRank() + 1 ) ); } else { // no person to place in 2nd _mphud->SetStateString( "player2_name", "" ); _mphud->SetStateString( "player2_score", "" ); _mphud->SetStateString( "player2_rank", "" ); } } else { _mphud->SetStateString( "player1_name", "" ); _mphud->SetStateString( "player1_score", "" ); _mphud->SetStateString( "player1_rank", "" ); _mphud->SetStateString( "player2_name", "" ); _mphud->SetStateString( "player2_score", "" ); _mphud->SetStateString( "player2_rank", "" ); } } // RITUAL BEGIN // squirrel: added DeadZone multiplayer mode if( gameLocal.gameType == GAME_DEADZONE ) { static int lastMarineScore = teamScore[ TEAM_MARINE ]; static int lastStroggScore = teamScore[ TEAM_STROGG ]; int marineScore = teamScore[ TEAM_MARINE ]; int stroggScore = teamScore[ TEAM_STROGG ]; const float asymptoticAverageWeight = 0.95f; /// Check if Marines have scored since last frame if( marineScore != lastMarineScore ) { /// Pulse the bar's color marineScoreBarPulseAmount = 1.0f; // Play the pulse sound idStr pulseSnd = "snd_dzpulse_happy"; if ( localPlayer->team != TEAM_MARINE ) pulseSnd = "snd_dzpulse_unhappy"; localPlayer->StartSound( pulseSnd, SND_CHANNEL_ANY, 0, false, NULL ); } else { /// Asymptotic-average back to the normal color marineScoreBarPulseAmount *= asymptoticAverageWeight; } /// Check if Strogg have scored since last frame if( stroggScore != lastStroggScore ) { /// Pulse the bar's color stroggScoreBarPulseAmount = 1.0f; // Play the pulse sound idStr pulseSnd = "snd_dzpulse_happy"; if ( localPlayer->team != TEAM_STROGG ) pulseSnd = "snd_dzpulse_unhappy"; localPlayer->StartSound( pulseSnd, SND_CHANNEL_ANY, 0, false, NULL ); } else { /// Asymptotic-average back to the normal color stroggScoreBarPulseAmount *= asymptoticAverageWeight; } /// Set "gameStatus" gui element _mphud->SetStateString("gameStatus", "" ); _mphud->SetStateFloat( "marine_pulse_amount", marineScoreBarPulseAmount ); _mphud->SetStateFloat( "strogg_pulse_amount", stroggScoreBarPulseAmount ); lastMarineScore = teamScore[ TEAM_MARINE ]; lastStroggScore = teamScore[ TEAM_STROGG ]; } // RITUAL END if( gameLocal.gameType == GAME_TOURNEY && localPlayer->GetArena() == MAX_ARENAS ) { int numWaitingArenaPlayers = 0; for( int i = 0; i < rankedPlayers.Num(); i++ ) { if( rankedPlayers[ i ].First() && rankedPlayers[ i ].First()->GetArena() == MAX_ARENAS ) { _mphud->SetStateString( va( "waitRoom_item_%d", numWaitingArenaPlayers++ ), rankedPlayers[ i ].First()->GetUserInfo()->GetString( "ui_name" ) ); } } _mphud->SetStateString( va( "waitRoom_item_%d", numWaitingArenaPlayers ), "" ); _mphud->SetStateBool( "waitroom", true ); _mphud->SetStateInt( "num_waitroom_players", numWaitingArenaPlayers ); } else { _mphud->SetStateBool( "waitroom", false ); } idStr spectateText0; idStr spectateText1; idStr spectateText2; if( gameLocal.gameType == GAME_TOURNEY ) { // line 1 - why we aren't playing if( localPlayer->wantSpectate ) { if( localPlayer->spectator != localPlayer->entityNumber ) { spectateText0 = va( common->GetLocalizedString( "#str_107672" ), gameLocal.GetClientByNum( localPlayer->spectator )->GetUserInfo()->GetString( "ui_name" ) ); } else if( localPlayer->spectating ) { spectateText0 = common->GetLocalizedString( "#str_107673" ); } } else { rvTourneyArena& currentArena = ((rvTourneyGameState*)gameState)->GetArena( localPlayer->GetArena() ); if( gameState->GetMPGameState() == WARMUP ) { // grab the reason we aren't playing yet AllPlayersReady( &spectateText0 ); } else if( gameState->GetMPGameState() == COUNTDOWN ) { spectateText0 = va( common->GetLocalizedString( "#str_107671" ), Max( ((gameState->GetNextMPGameStateTime() - gameLocal.time) / 1000) + 1, 0 ) ); } else if( gameState->GetMPGameState() != GAMEREVIEW && localPlayer->GetTourneyStatus() == PTS_ELIMINATED ) { spectateText0 = common->GetLocalizedString( "#str_107687" ); } else if( gameState->GetMPGameState() != GAMEREVIEW && localPlayer->GetTourneyStatus() == PTS_ADVANCED ) { spectateText0 = common->GetLocalizedString( "#str_107688" ); } else if( ((rvTourneyGameState*)gameState)->HasBye( localPlayer ) ) { spectateText0 = common->GetLocalizedString( "#str_107709" ); } else if( currentArena.IsPlaying( localPlayer ) ) { spectateText0 = va( "%s %d; %s", common->GetLocalizedString( "#str_107716" ), localPlayer->GetArena() + 1, ((rvTourneyGameState*)gameState)->GetRoundDescription() ); } else if( localPlayer->spectating ) { // this should only happen if the player was spectating at start of round, but then decides // to join the tourney spectateText0 = common->GetLocalizedString( "#str_107684" ); } } // line 2 - will or wont be seeded, how to cycle // line 3 - how to enter waiting room if( gameState->GetMPGameState() == WARMUP || gameState->GetMPGameState() == COUNTDOWN ) { if( localPlayer->wantSpectate ) { spectateText1 = common->GetLocalizedString( "#str_107685" ); spectateText2 = common->GetLocalizedString( "#str_107695" ); } else { spectateText1 = common->GetLocalizedString( "#str_107684" ); spectateText2 = common->GetLocalizedString( "#str_107694" ); } } else if( localPlayer->spectating ) { if( localPlayer->GetArena() == MAX_ARENAS ) { spectateText1 = common->GetLocalizedString( "#str_107686" ); } else { spectateText1 = va( common->GetLocalizedString( "#str_107670" ), common->KeysFromBinding( "_impulse14" ), common->KeysFromBinding( "_impulse15" ) ); } } } else { // non-tourney spectate text if( localPlayer->spectating ) { if( localPlayer->spectator != localPlayer->entityNumber ) { spectateText0 = va( common->GetLocalizedString( "#str_107672" ), gameLocal.GetClientByNum( localPlayer->spectator )->GetUserInfo()->GetString( "ui_name" ) ); } else if( localPlayer->spectating ) { spectateText0 = common->GetLocalizedString( "#str_107673" ); } // spectating instructions if( localPlayer->spectator != localPlayer->entityNumber ) { //cycle & exit follow spectateText1 = va( common->GetLocalizedString( "#str_107698" ), common->KeysFromBinding( "_attack" ), common->KeysFromBinding( "_moveup" ) ); } else { //start follow spectateText1 = va( common->GetLocalizedString( "#str_108024" ), common->KeysFromBinding( "_attack" ) ); } } if( gameState->GetMPGameState() == WARMUP ) { AllPlayersReady( &spectateText1 ); } else if( gameState->GetMPGameState() == COUNTDOWN ) { spectateText1 = va( common->GetLocalizedString( "#str_107671" ), Max( ((gameState->GetNextMPGameStateTime() - gameLocal.time) / 1000) + 1, 0 ) ); } } _mphud->SetStateString( "spectatetext0", spectateText0 ); _mphud->SetStateString( "spectatetext1", spectateText1 ); _mphud->SetStateString( "spectatetext2", spectateText2 ); if( gameLocal.gameType == GAME_TOURNEY ) { gameLocal.mpGame.tourneyGUI.UpdateScores(); } _mphud->StateChanged( gameLocal.time ); statManager->UpdateInGameHud( _mphud, ( localPlayer->usercmd.buttons & BUTTON_INGAMESTATS ) != 0 ); //update awards if ( gameLocal.isClient || gameLocal.isListenServer) { statManager->CheckAwardQueue(); } } /* ================ idMultiplayerGame::DrawScoreBoard ================ */ void idMultiplayerGame::DrawScoreBoard( idPlayer *player ) { if ( player->scoreBoardOpen ) { if ( !playerState[ player->entityNumber ].scoreBoardUp ) { scoreBoard->Activate( true, gameLocal.time ); playerState[ player->entityNumber ].scoreBoardUp = true; player->disableHud = true; } if( gameLocal.gameType == GAME_TOURNEY ) { ((rvTourneyGameState*)gameState)->UpdateTourneyBrackets(); } UpdateScoreboard( scoreBoard ); } else { if ( playerState[ player->entityNumber ].scoreBoardUp ) { scoreBoard->Activate( false, gameLocal.time ); playerState[ player->entityNumber ].scoreBoardUp = false; player->disableHud = false; } } } /* =============== idMultiplayerGame::AddChatLine =============== */ void idMultiplayerGame::AddChatLine( const char *fmt, ... ) { idStr temp; va_list argptr; // mekberg: chat changes. wrapInfo_t wrapInfo; idStr wrap1; idStr wrap2; va_start( argptr, fmt ); vsprintf( temp, fmt, argptr ); va_end( argptr ); temp.StripTrailingOnce("\n"); #ifdef MOD_BOTS // TinMan: process chat if(BOT_ENABLED()) botAi::ProcessCommand( temp ); #endif // this isn't a good way to color informational lines.... if( temp.Find( ":" ) > 0 && temp.Find( ":" ) < temp.Length() - 1 ) { gameLocal.Printf( "%s^0^2%s\n", temp.Left( temp.Find( ":" ) + 1 ).c_str(), temp.Right( temp.Length() - temp.Find( ":" ) - 1).c_str() ); } else { gameLocal.Printf( "%s\n", temp.c_str() ); } // bdube: new chat interraction with hud if ( gameLocal.GetLocalPlayer() != NULL && gameLocal.GetLocalPlayer()->mphud ) { wrap1 = temp; wrap2 = temp; do { memset( &wrapInfo, -1, sizeof ( wrapInfo_t ) ); gameLocal.GetLocalPlayer( )->mphud->GetMaxTextIndex( "history1", wrap1.c_str( ), wrapInfo ); // If we have a whitespace near the end. Otherwise the user could enter a giant word. if ( wrapInfo.lastWhitespace != -1 && float( wrapInfo.lastWhitespace ) / float( wrapInfo.maxIndex ) > .75 ) { wrap2 = wrap1.Left( wrapInfo.lastWhitespace++ ); // Just text wrap, no word wrap. } else if ( wrapInfo.maxIndex != -1 ) { wrap2 = wrap1.Left( wrapInfo.maxIndex ); // We fit in less than a line. } else { wrap2 = wrap1; } // Recalc the base string. wrap1 = wrap1.Right( wrap1.Length( ) - wrap2.Length( ) ); // Push to gui. gameLocal.GetLocalPlayer( )->mphud->SetStateString( "chattext", wrap2.c_str( ) ); gameLocal.GetLocalPlayer( )->mphud->HandleNamedEvent( "addchatline" ); } while ( wrapInfo.maxIndex != -1 ); } if( chatHistory.Length() + temp.Length() > CHAT_HISTORY_SIZE ) { int removeLength = chatHistory.Find( '\n' ); if( removeLength == -1 ) { // nuke the whole string chatHistory.Empty(); } else { while( (chatHistory.Length() - removeLength) + temp.Length() > CHAT_HISTORY_SIZE ) { removeLength = chatHistory.Find( '\n', removeLength + 1 ); if( removeLength == -1 ) { chatHistory.Empty(); break; } } } chatHistory = chatHistory.Right( chatHistory.Length() - removeLength ); } chatHistory.Append( temp ); chatHistory.Append( '\n' ); if( mainGui ) { mainGui->SetStateString( "chat", chatHistory.c_str() ); } if( statSummary ) { statSummary->SetStateString( "chat", chatHistory.c_str() ); } // play chat sound char* chatSound = "snd_chat"; if( gameLocal.GetLocalPlayer() ) { // not a great way to detect teams if( gameLocal.IsTeamGame() ) { int i = temp.Find( gameLocal.GetLocalPlayer()->team ? "Strogg" : "Marine", false ); int firstColon = temp.Find( ":" ); if( firstColon >= 0 && i < firstColon && i >= 1 && temp[ i - 6 ] == '(' ) { chatSound = "snd_teamchat"; } } gameLocal.GetLocalPlayer()->StartSound( chatSound, SND_CHANNEL_ANY, 0, false, NULL ); } } void idMultiplayerGame::DrawStatSummary( void ) { if ( !statSummary->GetStateFloat( "ready" ) ) { statSummary->SetStateFloat( "ready", 1 ); statSummary->HandleNamedEvent( "chatFocus" ); statSummary->StateChanged( gameLocal.time ); } statSummary->Redraw( gameLocal.time ); } void idMultiplayerGame::ShowStatSummary( void ) { if ( !gameLocal.GetLocalPlayer() ) { assert( false ); return; } DisableMenu( ); nextMenu = 3; gameLocal.sessionCommand = "game_startmenu"; gameLocal.GetLocalPlayer()->GUIMainNotice( "" ); gameLocal.GetLocalPlayer()->GUIFragNotice( "" ); } /* ================ idMultiplayerGame::WriteToSnapshot ================ */ void idMultiplayerGame::WriteToSnapshot( idBitMsgDelta &msg ) const { int i; int value; byte ingame[ MAX_CLIENTS / 8 ]; idEntity* ent; assert( MAX_CLIENTS % 8 == 0 ); // RITUAL BEGIN - DeadZone Messages msg.WriteBits(isBuyingAllowedRightNow, 1); msg.WriteShort(powerupCount); msg.WriteFloat( marineScoreBarPulseAmount ); msg.WriteFloat( stroggScoreBarPulseAmount ); // RITUAL END // RAVEN BEGIN // ddynerman: CTF scoring // FIXME - not in the snapshot for( i = 0; i < TEAM_MAX; i++ ) { msg.WriteShort( teamScore[i] ); msg.WriteLong( teamDeadZoneScore[i] ); } // RAVEN END // write ingame bits first, then we only sync down for ingame clients // do a single write, this doesn't change often it's best to deltify in a single shot for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( playerState[i].ingame ) { ingame[ i / 8 ] |= 1 << ( i % 8 ); } else { ingame[ i / 8 ] &= ~( 1 << ( i % 8 ) ); } } msg.WriteData( ingame, MAX_CLIENTS / 8 ); // those rarely change as well and will deltify away nicely for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( playerState[i].ingame ) { ent = gameLocal.entities[ i ]; // clamp all values to min/max possible value that we can send over value = idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, playerState[i].fragCount ); msg.WriteBits( value, ASYNC_PLAYER_FRAG_BITS ); value = idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, playerState[i].teamFragCount ); msg.WriteBits( value, ASYNC_PLAYER_FRAG_BITS ); msg.WriteLong( playerState[i].deadZoneScore ); value = idMath::ClampInt( 0, MP_PLAYER_MAXWINS, playerState[i].wins ); msg.WriteBits( value, ASYNC_PLAYER_WINS_BITS ); // only transmit instance info in tourney if( gameLocal.gameType == GAME_TOURNEY ) { if( !ent ) { msg.WriteBits( 0, 1 ); } else { msg.WriteBits( 1, 1 ); value = idMath::ClampInt( 0, MAX_INSTANCES, ent->GetInstance() ); msg.WriteBits( value, ASYNC_PLAYER_INSTANCE_BITS ); msg.WriteBits( ((idPlayer*)ent)->GetTourneyStatus(), ASYNC_PLAYER_TOURNEY_STATUS_BITS ); } } } } // those change all the time, keep them in a single pack for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( playerState[i].ingame ) { value = idMath::ClampInt( 0, MP_PLAYER_MAXPING, playerState[i].ping ); msg.WriteBits( value, ASYNC_PLAYER_PING_BITS ); } } } /* ================ idMultiplayerGame::ReadFromSnapshot ================ */ void idMultiplayerGame::ReadFromSnapshot( const idBitMsgDelta &msg ) { int i, newInstance; byte ingame[ MAX_CLIENTS / 8 ]; idEntity* ent; bool proto69 = ( gameLocal.GetCurrentDemoProtocol() == 69 ); if ( proto69 ) { isBuyingAllowedRightNow = false; powerupCount = 0; marineScoreBarPulseAmount = 0; stroggScoreBarPulseAmount = 0; } else { // RITUAL BEGIN - DeadZone & buying Messages isBuyingAllowedRightNow = msg.ReadBits(1); powerupCount = msg.ReadShort(); // TTimo: NOTE: sounds excessive to be transmitting floats for that marineScoreBarPulseAmount = msg.ReadFloat(); stroggScoreBarPulseAmount = msg.ReadFloat(); // RITUAL END } // CTF/TDM scoring for( i = 0; i < TEAM_MAX; i++ ) { teamScore[ i ] = msg.ReadShort( ); if ( proto69 ) { teamDeadZoneScore[ i ] = 0; } else { teamDeadZoneScore[ i ] = msg.ReadLong( ); } } msg.ReadData( ingame, MAX_CLIENTS / 8 ); for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( ingame[ i / 8 ] & ( 1 << ( i % 8 ) ) ) { playerState[i].ingame = true; } else { playerState[i].ingame = false; } } for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( playerState[i].ingame ) { ent = gameLocal.entities[ i ]; playerState[ i ].fragCount = msg.ReadBits( ASYNC_PLAYER_FRAG_BITS ); playerState[ i ].teamFragCount = msg.ReadBits( ASYNC_PLAYER_FRAG_BITS ); if ( proto69 ) { playerState[ i ].deadZoneScore = 0; } else { playerState[ i ].deadZoneScore = msg.ReadLong(); } playerState[ i ].wins = msg.ReadBits( ASYNC_PLAYER_WINS_BITS ); if( gameLocal.gameType == GAME_TOURNEY ) { if( msg.ReadBits( 1 ) ) { newInstance = msg.ReadBits( ASYNC_PLAYER_INSTANCE_BITS ); if( newInstance != ent->GetInstance() ) { ent->SetInstance( newInstance ); if( gameLocal.GetLocalPlayer() && i != gameLocal.localClientNum ) { if( ent->GetInstance() == gameLocal.GetLocalPlayer()->GetInstance() ) { ((idPlayer*)ent)->ClientInstanceJoin(); } else { ((idPlayer*)ent)->ClientInstanceLeave(); } } } ((idPlayer*)ent)->SetTourneyStatus( (playerTourneyStatus_t)msg.ReadBits( ASYNC_PLAYER_TOURNEY_STATUS_BITS ) ); } } } } for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( playerState[i].ingame ) { playerState[ i ].ping = msg.ReadBits( ASYNC_PLAYER_PING_BITS ); } } } // RAVEN BEGIN // bdube: global item sounds /* ================ idMultiplayerGame::PlayGlobalItemAcquireSound ================ */ void idMultiplayerGame::PlayGlobalItemAcquireSound( int defIndex ) { const idDeclEntityDef* def; def = static_cast<const idDeclEntityDef*>( declManager->DeclByIndex( DECL_ENTITYDEF, defIndex, false ) ); if ( !def ) { gameLocal.Warning ( "NET: invalid entity def index (%d) for global item acquire sound", defIndex ); return; } if( !gameLocal.GetLocalPlayer() || !gameLocal.currentThinkingEntity || gameLocal.GetLocalPlayer()->GetInstance() == gameLocal.currentThinkingEntity->GetInstance() ) { soundSystem->PlayShaderDirectly ( SOUNDWORLD_GAME, def->dict.GetString ( "snd_acquire" ) ); } if ( gameLocal.isServer ) { idBitMsg outMsg; byte msgBuf[1024]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_ITEMACQUIRESOUND ); outMsg.WriteBits( defIndex, gameLocal.entityDefBits ); gameLocal.ServerSendInstanceReliableMessage( gameLocal.currentThinkingEntity, -1, outMsg ); } } // RAVEN END /* ================ idMultiplayerGame::PrintMessageEvent ================ */ void idMultiplayerGame::PrintMessageEvent( int to, msg_evt_t evt, int parm1, int parm2 ) { idPlayer *p = gameLocal.GetLocalPlayer(); if ( to == -1 || ( p && to == p->entityNumber ) ) { switch ( evt ) { case MSG_SUICIDE: assert( parm1 >= 0 ); AddChatLine( common->GetLocalizedString( "#str_104293" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ) ); break; case MSG_KILLED: assert( parm1 >= 0 && parm2 >= 0 ); AddChatLine( common->GetLocalizedString( "#str_104292" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ), gameLocal.userInfo[ parm2 ].GetString( "ui_name" ) ); break; case MSG_KILLEDTEAM: assert( parm1 >= 0 && parm2 >= 0 ); AddChatLine( common->GetLocalizedString( "#str_104291" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ), gameLocal.userInfo[ parm2 ].GetString( "ui_name" ) ); break; case MSG_TELEFRAGGED: assert( parm1 >= 0 && parm2 >= 0 ); AddChatLine( common->GetLocalizedString( "#str_104290" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ), gameLocal.userInfo[ parm2 ].GetString( "ui_name" ) ); break; case MSG_DIED: assert( parm1 >= 0 ); AddChatLine( common->GetLocalizedString( "#str_104289" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ) ); break; case MSG_VOTE: AddChatLine( common->GetLocalizedString( "#str_104288" ) ); break; case MSG_SUDDENDEATH: AddChatLine( common->GetLocalizedString( "#str_104287" ) ); break; case MSG_FORCEREADY: AddChatLine( common->GetLocalizedString( "#str_104286" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ) ); // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( gameLocal.entities[ parm1 ] && gameLocal.entities[ parm1 ]->IsType( idPlayer::GetClassType() ) ) { // RAVEN END static_cast< idPlayer * >( gameLocal.entities[ parm1 ] )->forcedReady = true; } break; case MSG_JOINEDSPEC: AddChatLine( common->GetLocalizedString( "#str_104285" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ) ); break; case MSG_TIMELIMIT: AddChatLine( common->GetLocalizedString( "#str_104284" ) ); break; case MSG_FRAGLIMIT: // RITUAL BEGIN // squirrel: added DeadZone multiplayer mode if ( gameLocal.gameType == GAME_TDM || gameLocal.gameType == GAME_DEADZONE ) { // RITUAL END // RAVEN BEGIN // rhummer: localized "Strogg" and "Marine" AddChatLine( common->GetLocalizedString( "#str_107665" ), parm1 ? common->GetLocalizedString( "#str_108025" ) : common->GetLocalizedString( "#str_108026" ) ); // RAVEN END } else { AddChatLine( common->GetLocalizedString( "#str_104281" ), gameLocal.userInfo[ parm1 ].GetString( "ui_name" ) ); } break; case MSG_CAPTURELIMIT: // RAVEN BEGIN // rhummer: localized "%s team hit the capture limit." and "Strogg and "Marine" AddChatLine( common->GetLocalizedString( "#str_108027" ), parm1 ? common->GetLocalizedString( "#str_108025" ) : common->GetLocalizedString( "#str_108026" ) ); // RAVEN END break; case MSG_HOLYSHIT: AddChatLine( common->GetLocalizedString( "#str_106732" ) ); break; default: gameLocal.DPrintf( "PrintMessageEvent: unknown message type %d\n", evt ); return; } } if ( !gameLocal.isClient ) { idBitMsg outMsg; byte msgBuf[1024]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_DB ); outMsg.WriteByte( evt ); outMsg.WriteByte( parm1 ); outMsg.WriteByte( parm2 ); networkSystem->ServerSendReliableMessage( to, outMsg ); } } /* ================ idMultiplayerGame::PrintMessage ================ */ void idMultiplayerGame::PrintMessage( int to, const char* msg ) { if( idStr::Length( msg ) >= MAX_PRINT_LEN ) { common->Warning( "idMultiplayerGame::PrintMessage() - Not transmitting message of length %d", idStr::Length( msg ) ); return; } AddChatLine( msg ); if ( !gameLocal.isClient ) { idBitMsg outMsg; byte msgBuf[1024]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_PRINT ); outMsg.WriteString( msg ); networkSystem->ServerSendReliableMessage( to, outMsg ); } } /* ================ idMultiplayerGame::CheckSpawns ================ */ void idMultiplayerGame::CheckRespawns( idPlayer *spectator ) { for( int i = 0 ; i < gameLocal.numClients ; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer *p = static_cast<idPlayer *>(ent); // once we hit sudden death, nobody respawns till game has ended // no respawns in tourney mode, the tourney manager manually handles spawns if ( (WantRespawn( p ) || p == spectator) ) { if ( gameState->GetMPGameState() == SUDDENDEATH && gameLocal.gameType != GAME_TOURNEY ) { // respawn rules while sudden death are different // sudden death may trigger while a player is dead, so there are still cases where we need to respawn // don't do any respawns while we are in end game delay though if ( gameLocal.IsTeamGame() || p->IsLeader() ) { //everyone respawns in team games, only fragleaders respawn in DM p->ServerSpectate( false ); } else {//if ( !p->IsLeader() ) { // sudden death is rolling, this player is not a leader, have him spectate p->ServerSpectate( true ); CheckAbortGame(); } } else { if ( gameState->GetMPGameState() == WARMUP || gameState->GetMPGameState() == COUNTDOWN || gameState->GetMPGameState() == GAMEON ) { if ( gameLocal.gameType != GAME_TOURNEY ) { // wait for team to be set before spawning in if( !gameLocal.IsTeamGame() || p->team != -1 ) { p->ServerSpectate( false ); } } else { if( p->GetArena() >= 0 && p->GetArena() < MAX_ARENAS ) { rvTourneyArena& arena = ((rvTourneyGameState*)gameState)->GetArena( p->GetArena() ); if( ( arena.GetState() != AS_DONE && arena.GetState() != AS_INACTIVE ) && ( p == arena.GetPlayers()[ 0 ] || p == arena.GetPlayers()[ 1 ] ) ) { // only allow respawn if the arena we're in is active // and we're one of the assigned players (we're not just spectating it) p->ServerSpectate( false ); } } else { // always allow respawn in the waiting room assert( p->GetArena() == MAX_ARENAS ); p->ServerSpectate( false ); } } } } } else if ( p->wantSpectate && !p->spectating ) { playerState[ i ].fragCount = 0; // whenever you willingly go spectate during game, your score resets p->ServerSpectate( true ); CheckAbortGame(); } } } void idMultiplayerGame::FreeLight ( int lightID ) { if ( lightHandles[lightID] != -1 && gameRenderWorld ) { gameRenderWorld->FreeLightDef( lightHandles[lightID] ); lightHandles[lightID] = -1; } } void idMultiplayerGame::UpdateLight ( int lightID, idPlayer *player ) { lights[ lightID ].origin = player->GetPhysics()->GetOrigin() + idVec3( 0, 0, 20 ); if ( lightHandles[ lightID ] == -1 ) { lightHandles[ lightID ] = gameRenderWorld->AddLightDef ( &lights[ lightID ] ); } else { gameRenderWorld->UpdateLightDef( lightHandles[ lightID ], &lights[ lightID ] ); } } void idMultiplayerGame::CheckSpecialLights( void ) { if ( !gameLocal.isLastPredictFrame ) { return; } idPlayer *marineFlagCarrier = NULL; idPlayer *stroggFlagCarrier = NULL; idPlayer *quadDamageCarrier = NULL; idPlayer *regenerationCarrier = NULL; idPlayer *hasteCarrier = NULL; for( int i = 0 ; i < gameLocal.numClients ; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer *p = static_cast<idPlayer *>( ent ); if( gameLocal.GetLocalPlayer() && p->GetInstance() != gameLocal.GetLocalPlayer()->GetInstance() ) { continue; } if ( p->PowerUpActive( POWERUP_CTF_MARINEFLAG ) ) { marineFlagCarrier = p; } else if ( p->PowerUpActive( POWERUP_CTF_STROGGFLAG ) ) { stroggFlagCarrier = p; } else if( p->PowerUpActive( POWERUP_QUADDAMAGE ) || p->PowerUpActive( POWERUP_TEAM_DAMAGE_MOD )) { quadDamageCarrier = p; } else if( p->PowerUpActive( POWERUP_REGENERATION ) ) { regenerationCarrier = p; } else if( p->PowerUpActive( POWERUP_HASTE ) ) { hasteCarrier = p; } } if ( marineFlagCarrier ) { UpdateLight( MPLIGHT_CTF_MARINE, marineFlagCarrier ); } else { FreeLight( MPLIGHT_CTF_MARINE ); } if ( stroggFlagCarrier ) { UpdateLight( MPLIGHT_CTF_STROGG, stroggFlagCarrier ); } else { FreeLight( MPLIGHT_CTF_STROGG ); } if ( quadDamageCarrier ) { UpdateLight( MPLIGHT_QUAD, quadDamageCarrier ); } else { FreeLight( MPLIGHT_QUAD ); } if ( regenerationCarrier ) { UpdateLight( MPLIGHT_REGEN, regenerationCarrier ); } else { FreeLight( MPLIGHT_REGEN ); } if ( hasteCarrier ) { UpdateLight( MPLIGHT_HASTE, hasteCarrier ); } else { FreeLight( MPLIGHT_HASTE ); } } /* ================ idMultiplayerGame::ForceReady ================ */ void idMultiplayerGame::ForceReady( ) { for( int i = 0 ; i < gameLocal.numClients ; i++ ) { idEntity *ent = gameLocal.entities[ i ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END continue; } idPlayer *p = static_cast<idPlayer *>( ent ); if ( !p->IsReady() ) { PrintMessageEvent( -1, MSG_FORCEREADY, i ); p->forcedReady = true; } } } /* ================ idMultiplayerGame::ForceReady_f ================ */ void idMultiplayerGame::ForceReady_f( const idCmdArgs &args ) { if ( !gameLocal.isMultiplayer || gameLocal.isClient ) { gameLocal.Printf( "forceReady: multiplayer server only\n" ); return; } gameLocal.mpGame.ForceReady(); } /* ================ idMultiplayerGame::DropWeapon ================ */ void idMultiplayerGame::DropWeapon( int clientNum ) { assert( !gameLocal.isClient ); idEntity *ent = gameLocal.entities[ clientNum ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END return; } // RAVEN BEGIN // bdube: removed parameter static_cast< idPlayer* >( ent )->DropWeapon( ); // RAVEN END } /* ================ idMultiplayerGame::DropWeapon_f ================ */ void idMultiplayerGame::DropWeapon_f( const idCmdArgs &args ) { if ( !gameLocal.isMultiplayer ) { gameLocal.Printf( "clientDropWeapon: only valid in multiplayer\n" ); return; } idBitMsg outMsg; byte msgBuf[128]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_DROPWEAPON ); networkSystem->ClientSendReliableMessage( outMsg ); } /* ================ idMultiplayerGame::MessageMode_f ================ */ void idMultiplayerGame::MessageMode_f( const idCmdArgs &args ) { gameLocal.mpGame.MessageMode( args ); } /* ================ idMultiplayerGame::MessageMode ================ */ void idMultiplayerGame::MessageMode( const idCmdArgs &args ) { const char *mode; int imode; if ( !gameLocal.isMultiplayer ) { common->Printf( "clientMessageMode: only valid in multiplayer\n" ); return; } if ( !mainGui ) { common->Printf( "no local client\n" ); return; } mode = args.Argv( 1 ); if ( !mode[ 0 ] || !gameLocal.IsTeamGame() ) { imode = 0; } else { imode = atoi( mode ); } msgmodeGui->SetStateString( "messagemode", imode ? "1" : "0" ); msgmodeGui->SetStateString( "chattext", "" ); nextMenu = 2; // let the session know that we want our ingame main menu opened gameLocal.sessionCommand = "game_startmenu"; } /* ================ idMultiplayerGame::Vote_f ================ */ void idMultiplayerGame::Vote_f( const idCmdArgs &args ) { // RAVEN BEGIN // shouchard: implemented for testing if ( args.Argc() < 2 ) { common->Printf( common->GetLocalizedString( "#str_104418" ) ); return; } const char *szArg1 = args.Argv(1); bool voteValue = false; if ( 0 == idStr::Icmp( szArg1, "yes" ) ) { voteValue = true; } gameLocal.mpGame.CastVote( gameLocal.localClientNum, voteValue ); // RAVEN END } /* ================ idMultiplayerGame::CallVote_f moved this over the use the packed voting still only does one vote though, can easily be extended to do more ================ */ void idMultiplayerGame::CallVote_f( const idCmdArgs &args ) { const char *szArg1 = args.Argv(1); const char *szArg2 = args.Argv(2); if ( '\0' == *szArg1 ) { common->Printf( common->GetLocalizedString( "#str_104404" ) ); common->Printf( common->GetLocalizedString( "#str_104405" ) ); return; } voteStruct_t voteData; memset( &voteData, 0, sizeof( voteData ) ); if ( 0 == idStr::Icmp( szArg1, "restart" ) ) { voteData.m_fieldFlags |= VOTEFLAG_RESTART; } else if ( 0 == idStr::Icmp( szArg1, "timelimit" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_104406" ) ); return; } voteData.m_fieldFlags |= VOTEFLAG_TIMELIMIT; voteData.m_timeLimit = atoi( szArg2 ); } else if ( 0 == idStr::Icmp( szArg1, "fraglimit" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_104407" ) ); return; } voteData.m_fieldFlags |= VOTEFLAG_FRAGLIMIT; voteData.m_fragLimit = atoi( szArg2 ); } else if ( 0 == idStr::Icmp( szArg1, "gametype" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_104408" ) ); common->Printf( common->GetLocalizedString( "#str_104409" ) ); return; } voteData.m_fieldFlags |= VOTEFLAG_GAMETYPE; voteData.m_gameType = gameLocal.mpGame.GameTypeToVote( szArg2 ); } else if ( 0 == idStr::Icmp( szArg1, "kick" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_104412" ) ); return; } voteData.m_kick = gameLocal.mpGame.GetClientNumFromPlayerName( szArg2 ); if ( voteData.m_kick >= 0 ) { voteData.m_fieldFlags |= VOTEFLAG_KICK; } } else if ( 0 == idStr::Icmp( szArg1, "map" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_104413" ) ); return; } voteData.m_fieldFlags |= VOTEFLAG_MAP; voteData.m_map = szArg2; } else if ( 0 == idStr::Icmp( szArg1, "buying" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_122012" ) ); return; } voteData.m_fieldFlags |= VOTEFLAG_BUYING; voteData.m_buying = atoi( szArg2 ); } else if ( 0 == idStr::Icmp( szArg1, "capturelimit" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_104415" ) ); return; } voteData.m_fieldFlags |= VOTEFLAG_CAPTURELIMIT; voteData.m_captureLimit = atoi( szArg2 ); } else if ( 0 == idStr::Icmp( szArg1, "autobalance" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_104416" ) ); } voteData.m_fieldFlags |= VOTEFLAG_TEAMBALANCE; voteData.m_teamBalance = atoi( szArg2 ); } else if ( 0 == idStr::Icmp( szArg1, "controlTime" ) ) { if ( '\0' == *szArg2 ) { common->Printf( common->GetLocalizedString( "#str_122002" ) ); // Squirrel@Ritual - Localized for 1.2 Patch } voteData.m_fieldFlags |= VOTEFLAG_CONTROLTIME; voteData.m_controlTime = atoi(szArg2 ); } else { common->Printf( common->GetLocalizedString( "#str_104404" ) ); common->Printf( common->GetLocalizedString( "#str_104405" ) ); return; } if ( voteData.m_fieldFlags != 0 ) { gameLocal.mpGame.ClientCallPackedVote( voteData ); } } // RAVEN BEGIN // shouchard: added voice mute and unmute console commands; sans XBOX to not step on their live voice stuff #ifndef _XBOX /* ================ idMultiplayerGame::VoiceMute_f ================ */ void idMultiplayerGame::VoiceMute_f( const idCmdArgs &args ) { if ( args.Argc() < 2 ) { common->Printf( "USAGE: clientvoicemute <player>\n" ); return; } gameLocal.mpGame.ClientVoiceMute( gameLocal.mpGame.GetClientNumFromPlayerName( args.Argv( 1 ) ), true ); } /* ================ idMultiplayerGame::VoiceUnmute_f ================ */ void idMultiplayerGame::VoiceUnmute_f( const idCmdArgs &args ) { if ( args.Argc() < 2 ) { common->Printf( "USAGE: clientvoiceunmute <player>\n" ); return; } gameLocal.mpGame.ClientVoiceMute( gameLocal.mpGame.GetClientNumFromPlayerName( args.Argv( 1 ) ), false ); } // RAVEN END #endif // _XBOX // RAVEN BEGIN /* ================ idMultiplayerGame::ForceTeamChange_f ================ */ void idMultiplayerGame::ForceTeamChange_f( const idCmdArgs &args) { if( !gameLocal.isMultiplayer ) { common->Printf( "[MP ONLY] Forces player to change teams. Usage: ForceTeamChange <client number>\n" ); return; } idStr clientId; int clientNum; clientId = args.Argv( 1 ); if ( !clientId.IsNumeric() ) { common->Printf( "usage: ForceTeamChange <client number>\n" ); return; } clientNum = atoi( clientId ); if ( gameLocal.entities[ clientNum ] && gameLocal.entities[ clientNum ]->IsType( idPlayer::GetClassType() ) ) { idPlayer *player = static_cast< idPlayer *>( gameLocal.entities[ clientNum ] ); player->GetUserInfo()->Set( "ui_team", player->team ? "Marine" : "Strogg" ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "updateUI %d\n", clientNum ) ); } } /* ================ idMultiplayerGame::RemoveClientFromBanList_f ================ */ void idMultiplayerGame::RemoveClientFromBanList_f( const idCmdArgs& args ) { if( !gameLocal.isMultiplayer ) { common->Printf( "[MP ONLY] Remove player from banlist. Usage: RemoveClientFromBanList <client number>\n" ); return; } idStr clientId; clientId = args.Argv( 1 ); int clientNum; if ( !clientId.IsNumeric() ) { common->Printf( "Usage: RemoveClientFromBanList <client number>\n" ); return; } clientNum = atoi( clientId ); const char *clientGuid = networkSystem->GetClientGUID( clientNum ); // gameLocal.GetGuidByClientNum( clientNum ); if ( NULL == clientGuid || !clientGuid[ 0 ]) { common->DPrintf( "idMultiplayerGame::HandleServerAdminRemoveBan: bad guid!\n" ); return; } if ( gameLocal.isServer || gameLocal.isListenServer ) { // remove from the ban list gameLocal.RemoveGuidFromBanList( clientGuid ); } } /* ================ idMultiplayerGame::ProcessRconReturn ================ */ void idMultiplayerGame::ProcessRconReturn( bool success ) { if( success ) { mainGui->HandleNamedEvent("adminPasswordSuccess"); } else { mainGui->HandleNamedEvent("adminPasswordFail"); } } // RAVEN END /* ================ idMultiplayerGame::ServerStartVote ================ */ void idMultiplayerGame::ServerStartVote( int clientNum, vote_flags_t voteIndex, const char *value ) { int i; assert( vote == VOTE_NONE ); // setup yesVotes = 1; noVotes = 0; vote = voteIndex; voteValue = value; voteTimeOut = gameLocal.time + 20000; // mark players allowed to vote - only current ingame players, players joining during vote will be ignored for ( i = 0; i < gameLocal.numClients; i++ ) { // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idPlayer::GetClassType() ) ) { // RAVEN END playerState[ i ].vote = ( i == clientNum ) ? PLAYER_VOTE_YES : PLAYER_VOTE_WAIT; } else { playerState[i].vote = PLAYER_VOTE_NONE; } } } /* ================ idMultiplayerGame::ClientStartVote ================ */ void idMultiplayerGame::ClientStartVote( int clientNum, const char *_voteString ) { idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; if ( !gameLocal.isClient ) { outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_STARTVOTE ); outMsg.WriteByte( clientNum ); outMsg.WriteString( _voteString ); networkSystem->ServerSendReliableMessage( -1, outMsg ); } voteString = _voteString; AddChatLine( va( common->GetLocalizedString( "#str_104279" ), gameLocal.userInfo[ clientNum ].GetString( "ui_name" ) ) ); // RAVEN BEGIN // shouchard: better info when a vote called in the chat buffer AddChatLine( voteString ); // TODO: will push this into a UI field later // shouchard: display the vote called text on the hud if ( gameLocal.GetLocalPlayer() && gameLocal.GetLocalPlayer()->mphud ) { gameLocal.GetLocalPlayer()->mphud->SetStateInt( "voteNotice", 1 ); } // RAVEN END ScheduleAnnouncerSound( AS_GENERAL_VOTE_NOW, gameLocal.time ); if ( clientNum == gameLocal.localClientNum ) { voted = true; } else { voted = false; } if ( gameLocal.isClient ) { // the the vote value to something so the vote line is displayed vote = VOTE_RESTART; yesVotes = 1; noVotes = 0; } ClientUpdateVote( VOTE_UPDATE, yesVotes, noVotes, currentVoteData ); } /* ================ idMultiplayerGame::ClientUpdateVote ================ */ void idMultiplayerGame::ClientUpdateVote( vote_result_t status, int yesCount, int noCount, const voteStruct_t &voteData ) { idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; const char * localizedString = 0; idPlayer* player = gameLocal.GetLocalPlayer( ); if ( !gameLocal.isClient ) { outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_UPDATEVOTE ); outMsg.WriteByte( status ); outMsg.WriteByte( yesCount ); outMsg.WriteByte( noCount ); // RAVEN BEGIN // shouchard: multifield vote support if ( VOTE_MULTIFIELD != vote ) { outMsg.WriteByte( 0 ); } else { outMsg.WriteByte( 1 ); outMsg.WriteShort( voteData.m_fieldFlags ); outMsg.WriteByte( idMath::ClampChar( voteData.m_kick ) ); outMsg.WriteString( voteData.m_map.c_str() ); outMsg.WriteByte( idMath::ClampChar( voteData.m_gameType ) ); outMsg.WriteByte( idMath::ClampChar( voteData.m_timeLimit ) ); outMsg.WriteShort( idMath::ClampShort( voteData.m_fragLimit ) ); outMsg.WriteShort( idMath::ClampShort( voteData.m_tourneyLimit ) ); outMsg.WriteShort( idMath::ClampShort( voteData.m_captureLimit ) ); outMsg.WriteShort( idMath::ClampShort( voteData.m_buying ) ); outMsg.WriteByte( idMath::ClampChar( voteData.m_teamBalance ) ); } networkSystem->ServerSendReliableMessage( -1, outMsg ); } else { currentVoteData = voteData; } // RAVEN END if ( vote == VOTE_NONE ) { // clients coming in late don't get the vote start and are not allowed to vote if ( mainGui ) { mainGui->SetStateInt( "vote_going", 0 ); } return; } switch ( status ) { case VOTE_FAILED: localizedString = common->GetLocalizedString( "#str_104278" ); AddChatLine( localizedString ); ScheduleAnnouncerSound( AS_GENERAL_VOTE_FAILED, gameLocal.time ); if ( gameLocal.isClient ) { vote = VOTE_NONE; } break; case VOTE_PASSED: localizedString = common->GetLocalizedString( "#str_104277" ); AddChatLine( localizedString ); ScheduleAnnouncerSound( AS_GENERAL_VOTE_PASSED, gameLocal.time ); break; case VOTE_RESET: if ( gameLocal.isClient ) { vote = VOTE_NONE; } break; case VOTE_ABORTED: localizedString = common->GetLocalizedString( "#str_104276" ); AddChatLine( localizedString ); if ( gameLocal.isClient ) { vote = VOTE_NONE; } break; case VOTE_UPDATE: if ( player && player->mphud && voted ) { player->mphud->SetStateString( "voteNoticeText", va("^:%s\n%s: %d %s: %d", common->GetLocalizedString( "#str_107724" ), common->GetLocalizedString( "#str_107703" ), yesCount, common->GetLocalizedString( "#str_107704" ), noCount ) ); } if ( mainGui ) { mainGui->SetStateInt( "playerVoted", voted ); } break; default: break; } if ( gameLocal.isClient ) { yesVotes = yesCount; noVotes = noCount; } // RAVEN BEGIN // shouchard: remove vote notification if ( VOTE_FAILED == status || VOTE_PASSED == status || VOTE_RESET == status ) { ClearVote(); } if ( mainGui ) { mainGui->SetStateString( "voteCount", va( common->GetLocalizedString( "#str_104435" ), (int)yesVotes, (int)noVotes ) ); } // RAVEN END } /* ================ idMultiplayerGame::ClientCallVote ================ */ void idMultiplayerGame::ClientCallVote( vote_flags_t voteIndex, const char *voteValue ) { idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; // send outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_CALLVOTE ); outMsg.WriteByte( voteIndex ); outMsg.WriteString( voteValue ); networkSystem->ClientSendReliableMessage( outMsg ); } /* ================ idMultiplayerGame::CastVote ================ */ void idMultiplayerGame::CastVote( int clientNum, bool castVote ) { idBitMsg outMsg; byte msgBuf[ 128 ]; if ( clientNum == gameLocal.localClientNum ) { voted = true; } if ( gameLocal.isClient ) { outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_CASTVOTE ); outMsg.WriteByte( castVote ); networkSystem->ClientSendReliableMessage( outMsg ); return; } // sanity if ( vote == VOTE_NONE ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104275" ); common->DPrintf( "client %d: cast vote while no vote in progress\n", clientNum ); return; } if ( playerState[ clientNum ].vote != PLAYER_VOTE_WAIT ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104274" ); common->DPrintf( "client %d: cast vote - vote %d != PLAYER_VOTE_WAIT\n", clientNum, playerState[ clientNum ].vote ); return; } if ( castVote ) { playerState[ clientNum ].vote = PLAYER_VOTE_YES; yesVotes++; } else { playerState[ clientNum ].vote = PLAYER_VOTE_NO; noVotes++; } ClientUpdateVote( VOTE_UPDATE, yesVotes, noVotes, currentVoteData ); } /* ================ idMultiplayerGame::ServerCallVote ================ */ void idMultiplayerGame::ServerCallVote( int clientNum, const idBitMsg &msg ) { vote_flags_t voteIndex; int vote_timeLimit, vote_fragLimit, vote_clientNum, vote_gameTypeIndex, vote_buying; //, vote_kickIndex; // RAVEN BEGIN // shouchard: added capture limit and autobalance int vote_captureLimit; bool vote_autobalance; // RAVEN END int vote_controlTime; char value[ MAX_STRING_CHARS ]; assert( clientNum != -1 ); assert( !gameLocal.isClient ); if( !gameLocal.serverInfo.GetBool( "si_allowVoting" ) ) { return; } voteIndex = (vote_flags_t)msg.ReadByte( ); msg.ReadString( value, sizeof( value ) ); // sanity checks - setup the vote if ( vote != VOTE_NONE ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104273" ); common->DPrintf( "client %d: called vote while voting already in progress - ignored\n", clientNum ); return; } switch ( voteIndex ) { case VOTE_RESTART: { ServerStartVote( clientNum, voteIndex, "" ); ClientStartVote( clientNum, common->GetLocalizedString( "#str_104271" ) ); break; } case VOTE_NEXTMAP: { ServerStartVote( clientNum, voteIndex, "" ); ClientStartVote( clientNum, common->GetLocalizedString( "#str_104272" ) ); break; } case VOTE_TIMELIMIT: { vote_timeLimit = strtol( value, NULL, 10 ); if ( vote_timeLimit == gameLocal.serverInfo.GetInt( "si_timeLimit" ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104270" ); common->DPrintf( "client %d: already at the voted Time Limit\n", clientNum ); return; } if ( vote_timeLimit < si_timeLimit.GetMinValue() || vote_timeLimit > si_timeLimit.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104269" ); common->DPrintf( "client %d: timelimit value out of range for vote: %s\n", clientNum, value ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, va( common->GetLocalizedString( "#str_104268" ), vote_timeLimit ) ); break; } case VOTE_FRAGLIMIT: { vote_fragLimit = strtol( value, NULL, 10 ); if ( vote_fragLimit == gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104267" ); common->DPrintf( "client %d: already at the voted Frag Limit\n", clientNum ); return; } if ( vote_fragLimit < si_fragLimit.GetMinValue() || vote_fragLimit > si_fragLimit.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104266" ); common->DPrintf( "client %d: fraglimit value out of range for vote: %s\n", clientNum, value ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, va( common->GetLocalizedString( "#str_104303" ), common->GetLocalizedString( "#str_104265" ), vote_fragLimit ) ); break; } case VOTE_GAMETYPE: { // RAVEN BEGIN // shouchard: removed magic numbers & added CTF type vote_gameTypeIndex = strtol( value, NULL, 10 ); assert( vote_gameTypeIndex >= 0 && vote_gameTypeIndex < VOTE_GAMETYPE_COUNT ); switch ( vote_gameTypeIndex ) { case VOTE_GAMETYPE_DM: strcpy( value, "DM" ); break; case VOTE_GAMETYPE_TOURNEY: strcpy( value, "Tourney" ); break; case VOTE_GAMETYPE_TDM: strcpy( value, "Team DM" ); break; case VOTE_GAMETYPE_CTF: strcpy( value, "CTF" ); break; case VOTE_GAMETYPE_ARENA_CTF: strcpy( value, "Arena CTF" ); break; // RAVEN END // RITUAL BEGIN // squirrel: added DeadZone multiplayer mode case VOTE_GAMETYPE_DEADZONE: strcpy( value, "DeadZone" ); break; // RITUAL END } if ( !idStr::Icmp( value, gameLocal.serverInfo.GetString( "si_gameType" ) ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104259" ); common->DPrintf( "client %d: already at the voted Game Type\n", clientNum ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, va( common->GetLocalizedString( "#str_104258" ), value ) ); break; } case VOTE_KICK: { vote_clientNum = strtol( value, NULL, 10 ); if ( vote_clientNum == gameLocal.localClientNum ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104257" ); common->DPrintf( "client %d: called kick for the server host\n", clientNum ); return; } ServerStartVote( clientNum, voteIndex, va( "%d", vote_clientNum ) ); ClientStartVote( clientNum, va( common->GetLocalizedString( "#str_104302" ), vote_clientNum, gameLocal.userInfo[ vote_clientNum ].GetString( "ui_name" ) ) ); break; } case VOTE_MAP: { #ifdef _XENON // Xenon should not get here assert( 0 ); #else if ( idStr::FindText( gameLocal.serverInfo.GetString( "si_map" ), value ) != -1 ) { // mekberg: localized string const char* mapName = si_map.GetString(); const idDeclEntityDef *mapDef = static_cast<const idDeclEntityDef *>(declManager->FindType( DECL_MAPDEF, mapName, false )); if ( mapDef ) { mapName = common->GetLocalizedString( mapDef->dict.GetString( "name", mapName ) ); } gameLocal.ServerSendChatMessage( clientNum, "server", va( common->GetLocalizedString( "#str_104295" ), mapName ) ); common->DPrintf( "client %d: already running the voted map: %s\n", clientNum, value ); return; } int num = fileSystem->GetNumMaps(); int i; const idDict *dict = NULL; bool haveMap = false; for ( i = 0; i < num; i++ ) { dict = fileSystem->GetMapDecl( i ); if( !dict ) { gameLocal.Warning( "idMultiplayerGame::ServerCallVote() - bad map decl index on vote\n" ); break; } if ( dict && !idStr::Icmp( dict->GetString( "path" ), value ) ) { haveMap = true; break; } } if ( !haveMap ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104296", value ); common->Printf( "client %d: map not found: %s\n", clientNum, value ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, va( common->GetLocalizedString( "#str_104256" ), dict ? dict->GetString( "name" ) : value ) ); #endif break; } case VOTE_BUYING: { if ( gameLocal.GetCurrentDemoProtocol() == 69 ) gameLocal.Error("MIN_PLAYERS vote in a pre-1.2 recorded demo is not supported."); vote_buying = strtol( value, NULL, 10 ); if ( vote_buying == gameLocal.serverInfo.GetInt( "si_isBuyingEnabled" ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_122013" ); common->DPrintf( "client %d: already at the voted buying mode\n", clientNum ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, va( common->GetLocalizedString( "#str_122014" ), vote_buying ) ); break; } // RAVEN BEGIN // shouchard: added capture limit, round limit, and autobalance case VOTE_CAPTURELIMIT: { vote_captureLimit = strtol( value, NULL, 10 ); if ( vote_captureLimit == gameLocal.serverInfo.GetInt( "si_captureLimit" ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104401" ); common->DPrintf( "client %d: already at the voted Capture Limit\n", clientNum ); return; } if ( vote_captureLimit < si_captureLimit.GetMinValue() || vote_captureLimit > si_fragLimit.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104402" ); common->DPrintf( "client %d: fraglimit value out of range for vote: %s\n", clientNum, value ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, "si_captureLimit" ); break; } // round limit is for tourneys case VOTE_ROUNDLIMIT: { // need a CVar or something to change here break; } case VOTE_AUTOBALANCE: { vote_autobalance = (0 != strtol( value, NULL, 10 ) ); if ( vote_autobalance == gameLocal.serverInfo.GetBool( "si_autobalance" ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104403" ); common->DPrintf( "client %d: already at the voted balance teams\n", clientNum ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, "si_autobalance" ); break; } // RAVEN END case VOTE_CONTROLTIME: { vote_controlTime = strtol( value, NULL, 10 ); if ( vote_controlTime == gameLocal.serverInfo.GetInt( "si_controlTime" ) ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_122017" ); common->DPrintf( "client %d: already at the voted Control Time\n", clientNum ); return; } if ( vote_controlTime < si_controlTime.GetMinValue() || vote_controlTime > si_controlTime.GetMaxValue() ) { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_122018" ); common->DPrintf( "client %d: controlTime value out of range for vote: %s\n", clientNum, value ); return; } ServerStartVote( clientNum, voteIndex, value ); ClientStartVote( clientNum, "si_controlTime" ); break; } default: { gameLocal.ServerSendChatMessage( clientNum, "server", "#str_104297", va( "%d", ( int )voteIndex ) ); common->DPrintf( "client %d: unknown vote index %d\n", clientNum, voteIndex ); } } } /* ================ idMultiplayerGame::DisconnectClient ================ */ void idMultiplayerGame::DisconnectClient( int clientNum ) { // gameLocal.entities[ clientNum ] could be null if server is shutting down if( gameLocal.entities[ clientNum ] ) { // only kill non-spectators if( !((idPlayer*)gameLocal.entities[ clientNum ])->spectating ) { static_cast<idPlayer *>( gameLocal.entities[ clientNum ] )->Kill( true, true ); } statManager->ClientDisconnect( clientNum ); } delete gameLocal.entities[ clientNum ]; UpdatePlayerRanks(); CheckAbortGame(); privatePlayers &= ~( 1 << clientNum ); // update serverinfo UpdatePrivatePlayerCount(); } /* ================ idMultiplayerGame::CheckAbortGame ================ */ void idMultiplayerGame::CheckAbortGame( void ) { // only checks for aborts -> game review below if ( gameState->GetMPGameState() != COUNTDOWN && gameState->GetMPGameState() != GAMEON && gameState->GetMPGameState() != SUDDENDEATH ) { return; } // in tourney, if we don't have enough clients to play we need to cycle back to // warmup to re-seed if( gameLocal.gameType == GAME_TOURNEY ) { if ( !EnoughClientsToPlay() ) { gameState->NewState( WARMUP ); } } else { if ( !EnoughClientsToPlay() && TimeLimitHit() ) { gameState->NewState( GAMEREVIEW ); } } } /* ================ idMultiplayerGame::WantKilled ================ */ void idMultiplayerGame::WantKilled( int clientNum ) { idEntity *ent = gameLocal.entities[ clientNum ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( ent && ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END static_cast<idPlayer *>( ent )->Kill( false, false ); } } /* ================ idMultiplayerGame::ClearVote ================ */ void idMultiplayerGame::ClearVote( int clientNum ) { int start = 0; int end = MAX_CLIENTS; if( clientNum != -1 ) { start = clientNum; end = clientNum + 1; } for ( int i = start; i < end; i++ ) { idPlayer *player = static_cast<idPlayer *>( gameLocal.entities[ i ] ); if ( !player || !player->mphud ) { continue; } player->mphud->SetStateInt( "voteNotice", 0 ); player->mphud->SetStateString( "voteInfo_1", "" ); player->mphud->SetStateString( "voteInfo_2", "" ); player->mphud->SetStateString( "voteInfo_3", "" ); player->mphud->SetStateString( "voteInfo_4", "" ); player->mphud->SetStateString( "voteInfo_5", "" ); player->mphud->SetStateString( "voteInfo_6", "" ); player->mphud->SetStateString( "voteInfo_7", "" ); player->mphud->StateChanged( gameLocal.time ); } if ( mainGui ) { mainGui->SetStateInt( "vote_going", 0 ); mainGui->StateChanged( gameLocal.time ); } } /* ================ idMultiplayerGame::MapRestart ================ */ void idMultiplayerGame::MapRestart( void ) { int clientNum; // jshepard: clean up votes ClearVote(); ClearAnnouncerSounds(); assert( !gameLocal.isClient ); if ( gameLocal.GameState() != GAMESTATE_SHUTDOWN && gameState->GetMPGameState() != WARMUP ) { gameState->NewState( WARMUP ); // force an immediate state detection/update, otherwise if we update our state this // same frame we'll miss transitions gameState->SendState(); gameState->SetNextMPGameState( INACTIVE ); gameState->SetNextMPGameStateTime( 0 ); } // mekberg: moved this before the updateUI just in case these values weren't reset. for ( int i = 0; i < TEAM_MAX; i++ ) { teamScore[ i ] = 0; teamDeadZoneScore[i] = 0; } // mekberg: Re-wrote this loop to always updateUI. Previously the player would be // on a team but the UI wouldn't know about it // shouchard: balance teams extended to CTF for ( clientNum = 0; clientNum < gameLocal.numClients; clientNum++ ) { // jnewquist: Use accessor for static class type if ( gameLocal.entities[ clientNum ] && gameLocal.entities[ clientNum ]->IsType( idPlayer::GetClassType() ) ) { // mekberg: clear wins only on map restart idPlayer *player = static_cast<idPlayer *>( gameLocal.entities[ clientNum ] ); SetPlayerWin( player, 0 ); /*if( clientNum == gameLocal.localClientNum ) { if ( player->alreadyDidTeamAnnouncerSound ) { player->alreadyDidTeamAnnouncerSound = false; } else { if ( gameLocal.IsTeamGame() ) { player->alreadyDidTeamAnnouncerSound = true; if( player->team == TEAM_STROGG ) { ScheduleAnnouncerSound( AS_TEAM_JOIN_STROGG, gameLocal.time + 500 ); } else if( player->team == TEAM_MARINE ) { ScheduleAnnouncerSound( AS_TEAM_JOIN_MARINE, gameLocal.time + 500 ); } } } }*/ // let the player rejoin the team through normal channels //player->ServerSpectate( true ); //player->team = -1; //player->latchedTeam = -1; // shouchard: BalanceTDM->BalanceTeam //if ( gameLocal.serverInfo.GetBool( "si_autoBalance" ) && gameLocal.IsTeamGame() ) { // player->BalanceTeam(); //} // core is in charge of syncing down userinfo changes // it will also call back game through SetUserInfo with the current info for update /*cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "updateUI %d\n", clientNum ) );*/ } } } /* ================ idMultiplayerGame::SwitchToTeam ================ */ void idMultiplayerGame::SwitchToTeam( int clientNum, int oldteam, int newteam ) { assert( gameLocal.IsTeamGame() ); assert( oldteam != newteam ); assert( !gameLocal.isClient ); if ( !gameLocal.isClient && newteam >= 0 ) { // clients might not have userinfo of joining client at this point, so // send down the player's name idPlayer *p = static_cast<idPlayer *>( gameLocal.entities[ clientNum ] ); if ( !p->wantSpectate ) { PrintMessage( -1, va( common->GetLocalizedString( "#str_104280" ), gameLocal.userInfo[ clientNum ].GetString( "ui_name" ), newteam ? common->GetLocalizedString( "#str_108025" ) : common->GetLocalizedString( "#str_108026" ) ) ); } } if ( oldteam != -1 ) { // kill and respawn idPlayer *p = static_cast<idPlayer *>( gameLocal.entities[ clientNum ] ); if ( p->IsInTeleport() ) { p->ServerSendInstanceEvent( idPlayer::EVENT_ABORT_TELEPORTER, NULL, false, -1 ); p->SetPrivateCameraView( NULL ); } //RITUAL BEGIN p->inventory.carryOverWeapons = 0; p->ResetCash(); //RITUAL END p->Kill( true, true ); CheckAbortGame(); } } /* ================ idMultiplayerGame::JoinTeam ================ */ void idMultiplayerGame::JoinTeam( const char* team ) { if( !idStr::Icmp( team, "auto" ) ) { int teamCount[ TEAM_MAX ]; idEntity *ent; memset( teamCount, 0, sizeof( int ) * TEAM_MAX ); for( int i = 0; i < gameLocal.numClients; i++ ) { ent = gameLocal.entities[ i ]; if ( ent && ent->IsType( idPlayer::GetClassType() ) ) { if ( !static_cast< idPlayer * >( ent )->spectating ) { teamCount[ ((idPlayer*)ent)->team ]++; } } } int minCount = /*idMath::*/INT_MAX; int minCountTeam = -1; for( int i = 0; i < TEAM_MAX; i++ ) { if( teamCount[ i ] < minCount ) { minCount = teamCount[ i ]; minCountTeam = i; } } if( minCountTeam >= 0 && minCountTeam < TEAM_MAX ) { cvarSystem->SetCVarString( "ui_spectate", "Play" ); cvarSystem->SetCVarString( "ui_team", teamNames[ minCountTeam ] ); } else { cvarSystem->SetCVarString( "ui_spectate", "Play" ); cvarSystem->SetCVarString( "ui_team", teamNames[ gameLocal.random.RandomInt( TEAM_MAX - 1 ) ] ); } } else if( !idStr::Icmp( team, "spectator" ) ) { cvarSystem->SetCVarString( "ui_spectate", "Spectate" ); } else { int i; for( i = 0; i < TEAM_MAX; i++ ) { if( !idStr::Icmp( team, teamNames[ i ] ) ) { cvarSystem->SetCVarString( "ui_spectate", "Play" ); cvarSystem->SetCVarString( "ui_team", teamNames[ i ] ); break; } } if( i >= TEAM_MAX ) { gameLocal.Warning( "idMultiplayerGame::JoinTeam() - unknown team '%s'\n", team ); } } } /* ================ idMultiplayerGame::ProcessChatMessage ================ */ void idMultiplayerGame::ProcessChatMessage( int clientNum, bool team, const char *name, const char *text, const char *sound ) { idBitMsg outMsg; byte msgBuf[ 256 ]; const char *suffix = NULL; int send_to; // 0 - all, 1 - specs, 2 - team int i; idEntity *ent; idPlayer *p; idStr suffixed_name; idStr prefixed_text; assert( !gameLocal.isClient ); if ( clientNum >= 0 ) { p = static_cast< idPlayer * >( gameLocal.entities[ clientNum ] ); // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !( p && p->IsType( idPlayer::GetClassType() ) ) ) { // RAVEN END return; } if ( p->spectating && ( p->wantSpectate || gameLocal.gameType == GAME_TOURNEY ) ) { suffix = "spectating"; if ( team || ( !g_spectatorChat.GetBool() && ( gameState->GetMPGameState() == GAMEON || gameState->GetMPGameState() == SUDDENDEATH ) ) ) { // to specs send_to = 1; } else { // to all send_to = 0; } } else if ( team ) { suffix = va( "%s%s", p->team ? S_COLOR_STROGG : S_COLOR_MARINE, p->team ? "Strogg^0" : "Marine^0" ); // to team send_to = 2; } else { if( gameLocal.gameType == GAME_TOURNEY ) { suffix = va( "Arena %d", (p->GetArena() + 1) ); } // to all send_to = 0; } } else { p = NULL; send_to = 0; } // put the message together outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_CHAT ); if ( suffix ) { suffixed_name = va( "^0%s^0 (%s)", name, suffix ); } else { suffixed_name = va( "^0%s^0", name ); } if( p && send_to == 2 ) { prefixed_text = va( "%s%s", p->team ? S_COLOR_STROGG : S_COLOR_MARINE, common->GetLocalizedString( text ) ); } else { prefixed_text = common->GetLocalizedString( text ); } if( suffixed_name.Length() + prefixed_text.Length() >= 240 ) { gameLocal.Warning( "idMultiplayerGame::ProcessChatMessage() - Chat line too long\n" ); return; } outMsg.WriteString( suffixed_name ); outMsg.WriteString( prefixed_text ); outMsg.WriteString( "" ); for ( i = 0; i < gameLocal.numClients; i++ ) { ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idPlayer::GetClassType() ) ) { continue; } idPlayer *to = static_cast< idPlayer * >( ent ); switch( send_to ) { case 0: if ( !p || !to->IsPlayerMuted( p ) ) { if ( i == gameLocal.localClientNum ) { AddChatLine( "%s^0: %s\n", suffixed_name.c_str(), prefixed_text.c_str() ); } else { networkSystem->ServerSendReliableMessage( i, outMsg ); } } break; case 1: if ( !p || ( to->spectating && !to->IsPlayerMuted( p ) ) ) { if ( i == gameLocal.localClientNum ) { AddChatLine( "%s^0: %s\n", suffixed_name.c_str(), prefixed_text.c_str() ); } else { networkSystem->ServerSendReliableMessage( i, outMsg ); } } break; case 2: if ( !p || ( to->team == p->team && !to->IsPlayerMuted( p ) ) ) { if ( !to->spectating ) { if ( i == gameLocal.localClientNum ) { AddChatLine( "%s^0: %s\n", suffixed_name.c_str(), prefixed_text.c_str() ); } else { networkSystem->ServerSendReliableMessage( i, outMsg ); } } } break; } } } /* ================ idMultiplayerGame::Precache ================ */ void idMultiplayerGame::Precache( void ) { int i; if ( !gameLocal.isMultiplayer ) { return; } gameLocal.FindEntityDef( "player_marine", false ); // MP game sounds for ( i = 0; i < AS_NUM_SOUNDS; i++ ) { declManager->FindSound( announcerSoundDefs[ i ], false ); } // MP guis. just make sure we hit all of them i = 0; while ( MPGuis[ i ] ) { uiManager->FindGui( MPGuis[ i ], true ); i++; } } /* ================ idMultiplayerGame::ToggleSpectate ================ */ void idMultiplayerGame::ToggleSpectate( void ) { bool spectating; assert( gameLocal.isClient || gameLocal.localClientNum == 0 ); spectating = ( idStr::Icmp( cvarSystem->GetCVarString( "ui_spectate" ), "Spectate" ) == 0 ); if ( spectating ) { // always allow toggling to play cvarSystem->SetCVarString( "ui_spectate", "Play" ); } else { // only allow toggling to spectate if spectators are enabled. if ( gameLocal.serverInfo.GetBool( "si_spectators" ) ) { cvarSystem->SetCVarString( "ui_spectate", "Spectate" ); } else { gameLocal.mpGame.AddChatLine( common->GetLocalizedString( "#str_106747" ) ); } } } /* ================ idMultiplayerGame::ToggleReady ================ */ void idMultiplayerGame::ToggleReady( void ) { bool ready; assert( gameLocal.isClient || gameLocal.localClientNum == 0 ); if ( lastReadyToggleTime == -1 ) { lastReadyToggleTime = gameLocal.time; } else { int currentTime = gameLocal.time; if ( currentTime - lastReadyToggleTime < 500 ) { return; } else { lastReadyToggleTime = currentTime; } } ready = ( idStr::Icmp( cvarSystem->GetCVarString( "ui_ready" ), "Ready" ) == 0 ); if ( ready ) { cvarSystem->SetCVarString( "ui_ready", "Not Ready" ); } else { cvarSystem->SetCVarString( "ui_ready", "Ready" ); } } /* ================ idMultiplayerGame::ToggleTeam ================ */ void idMultiplayerGame::ToggleTeam( void ) { bool team; assert( gameLocal.isClient || gameLocal.localClientNum == 0 ); // RAVEN BEGIN // ddynerman: new multiplayer teams team = ( idStr::Icmp( cvarSystem->GetCVarString( "ui_team" ), "Marine" ) == 0 ); if ( team ) { cvarSystem->SetCVarString( "ui_team", "Strogg" ); } else { cvarSystem->SetCVarString( "ui_team", "Marine" ); } // RAVEN END } /* ================ idMultiplayerGame::ToggleUserInfo ================ */ void idMultiplayerGame::ThrottleUserInfo( void ) { int i; assert( gameLocal.localClientNum >= 0 ); i = 0; while ( ThrottleVars[ i ] ) { if ( idStr::Icmp( gameLocal.userInfo[ gameLocal.localClientNum ].GetString( ThrottleVars[ i ] ), cvarSystem->GetCVarString( ThrottleVars[ i ] ) ) ) { if ( gameLocal.realClientTime < switchThrottle[ i ] ) { AddChatLine( common->GetLocalizedString( "#str_104299" ), common->GetLocalizedString( ThrottleVarsInEnglish[ i ] ), ( switchThrottle[ i ] - gameLocal.time ) / 1000 + 1 ); cvarSystem->SetCVarString( ThrottleVars[ i ], gameLocal.userInfo[ gameLocal.localClientNum ].GetString( ThrottleVars[ i ] ) ); } else { switchThrottle[ i ] = gameLocal.time + ThrottleDelay[ i ] * 1000; } } i++; } } /* ================ idMultiplayerGame::CanPlay ================ */ bool idMultiplayerGame::CanPlay( idPlayer *p ) { return !p->wantSpectate && playerState[ p->entityNumber ].ingame; } /* ================ idMultiplayerGame::EnterGame ================ */ void idMultiplayerGame::EnterGame( int clientNum ) { assert( !gameLocal.isClient ); if ( !playerState[ clientNum ].ingame ) { playerState[ clientNum ].ingame = true; if ( gameLocal.isMultiplayer ) { // can't use PrintMessageEvent as clients don't know the nickname yet //gameLocal.ServerSendChatMessage( -1, common->GetLocalizedString( "#str_102047" ), va( common->GetLocalizedString( "#str_107177" ), gameLocal.userInfo[ clientNum ].GetString( "ui_name" ) ) ); } // mark them as private and update si_numPrivatePlayers for( int i = 0; i < privateClientIds.Num(); i++ ) { int num = networkSystem->ServerGetClientNum( privateClientIds[ i ] ); // check for timed out clientids if( num < 0 ) { privateClientIds.RemoveIndex( i ); i--; continue; } if( num == clientNum ) { privatePlayers |= (1 << clientNum); } } // update serverinfo UpdatePrivatePlayerCount(); } } /* ================ idMultiplayerGame::WantRespawn ================ */ bool idMultiplayerGame::WantRespawn( idPlayer *p ) { return p->forceRespawn && !p->wantSpectate && playerState[ p->entityNumber ].ingame; } /* ================ idMultiplayerGame::VoiceChat ================ */ void idMultiplayerGame::VoiceChat_f( const idCmdArgs &args ) { gameLocal.mpGame.VoiceChat( args, false ); } /* ================ idMultiplayerGame::UpdateMPSettingsModel ================ */ void idMultiplayerGame::UpdateMPSettingsModel( idUserInterface* currentGui ) { if ( !currentGui ) { return; } const char *model; idPlayer *localP = gameLocal.GetLocalPlayer(); if ( gameLocal.IsTeamGame() && localP && localP->team >= 0 && localP->team < TEAM_MAX ) { model = cvarSystem->GetCVarString( va( "ui_model_%s", teamNames[ localP->team ] ) ); if ( idStr::Cmp( model, "" ) == 0 ) { const idDeclEntityDef *def = static_cast<const idDeclEntityDef*>( declManager->FindType( DECL_ENTITYDEF, "player_marine_mp_ui", false, true ) ); model = def->dict.GetString( va( "def_default_model_%s", teamNames[ localP->team ] ) ); cvarSystem->SetCVarString( va( "ui_model_%s", teamNames[ localP->team ] ), model ); } } else { model = cvarSystem->GetCVarString( "ui_model" ); if ( idStr::Cmp( model, "" ) == 0 ) { const idDeclEntityDef *def = static_cast<const idDeclEntityDef*>( declManager->FindType( DECL_ENTITYDEF, "player_marine_mp_ui", false, true ) ); model = def->dict.GetString( "def_default_model" ); cvarSystem->SetCVarString( "ui_model", model ); } } const rvDeclPlayerModel* playerModel = (const rvDeclPlayerModel*)declManager->FindType( DECL_PLAYER_MODEL, model, false ); if ( playerModel ) { currentGui->SetStateString( "player_model_name", playerModel->model.c_str() ); currentGui->SetStateString( "player_head_model_name", playerModel->uiHead.c_str() ); currentGui->SetStateString( "player_skin_name", playerModel->skin.c_str() ); if( playerModel->uiHead.Length() ) { const idDeclEntityDef* head = (const idDeclEntityDef*)declManager->FindType( DECL_ENTITYDEF, playerModel->uiHead.c_str(), false ); if( head && head->dict.GetString( "skin" ) ) { mainGui->SetStateString( "player_head_skin_name", head->dict.GetString( "skin" ) ); } } currentGui->SetStateBool( "need_update", true ); } } /* ================ idMultiplayerGame::VoiceChatTeam ================ */ void idMultiplayerGame::VoiceChatTeam_f( const idCmdArgs &args ) { gameLocal.mpGame.VoiceChat( args, true ); } /* ================ idMultiplayerGame::VoiceChat ================ */ void idMultiplayerGame::VoiceChat( const idCmdArgs &args, bool team ) { idBitMsg outMsg; byte msgBuf[128]; const char *voc; const idDict *spawnArgs; const idKeyValue *keyval; int index; if ( !gameLocal.isMultiplayer ) { common->Printf( "clientVoiceChat: only valid in multiplayer\n" ); return; } if ( args.Argc() != 2 ) { common->Printf( "clientVoiceChat: bad args\n" ); return; } // throttle if ( gameLocal.realClientTime < voiceChatThrottle ) { return; } voc = args.Argv( 1 ); spawnArgs = gameLocal.FindEntityDefDict( "player_marine", false ); keyval = spawnArgs->MatchPrefix( "snd_voc_", NULL ); index = 0; while ( keyval ) { if ( !keyval->GetValue().Icmp( voc ) ) { break; } keyval = spawnArgs->MatchPrefix( "snd_voc_", keyval ); index++; } if ( !keyval ) { common->Printf( "Voice command not found: %s\n", voc ); return; } voiceChatThrottle = gameLocal.realClientTime + 1000; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_VCHAT ); outMsg.WriteLong( index ); outMsg.WriteBits( team ? 1 : 0, 1 ); networkSystem->ClientSendReliableMessage( outMsg ); } /* ================ idMultiplayerGame::ProcessVoiceChat ================ */ void idMultiplayerGame::ProcessVoiceChat( int clientNum, bool team, int index ) { const idDict *spawnArgs; const idKeyValue *keyval; idStr name; idStr snd_key; idStr text_key; idPlayer *p; p = static_cast< idPlayer * >( gameLocal.entities[ clientNum ] ); // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( !( p && p->IsType( idPlayer::GetClassType() ) ) ) { // RAVEN END return; } if ( p->spectating ) { return; } // lookup the sound def spawnArgs = gameLocal.FindEntityDefDict( "player_marine", false ); keyval = spawnArgs->MatchPrefix( "snd_voc_", NULL ); while ( index > 0 && keyval ) { keyval = spawnArgs->MatchPrefix( "snd_voc_", keyval ); index--; } if ( !keyval ) { common->DPrintf( "ProcessVoiceChat: unknown chat index %d\n", index ); return; } snd_key = keyval->GetKey(); name = gameLocal.userInfo[ clientNum ].GetString( "ui_name" ); sprintf( text_key, "txt_%s", snd_key.Right( snd_key.Length() - 4 ).c_str() ); if ( team || gameState->GetMPGameState() == COUNTDOWN || gameState->GetMPGameState() == GAMEREVIEW ) { ProcessChatMessage( clientNum, team, name, spawnArgs->GetString( text_key ), spawnArgs->GetString( snd_key ) ); } else { p->StartSound( snd_key, SND_CHANNEL_ANY, 0, true, NULL ); ProcessChatMessage( clientNum, team, name, spawnArgs->GetString( text_key ), NULL ); } } // RAVEN BEGIN // shouchard: added commands to mute/unmute voice chat /* ================ idMultiplayerGame::ClientVoiceMute ================ */ void idMultiplayerGame::ClientVoiceMute( int muteClient, bool mute ) { // clients/listen server only assert( gameLocal.isListenServer || gameLocal.isClient ); if ( NULL == gameLocal.GetLocalPlayer() ) { return; } if ( muteClient == -1 || !gameLocal.mpGame.IsInGame( muteClient ) ) { gameLocal.Warning( "idMultiplayerGame::ClientVoiceMute() - Invalid client '%d' specified", muteClient ); return; } // do the mute/unmute gameLocal.GetLocalPlayer()->MutePlayer( muteClient, mute ); // tell the server if( gameLocal.isClient ) { idBitMsg outMsg; byte msgBuf[128]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_VOICECHAT_MUTING ); outMsg.WriteByte( muteClient ); outMsg.WriteByte( mute ? 1 : 0 ); // 1 for mute, 0 for unmute networkSystem->ClientSendReliableMessage( outMsg ); } // display some niceties common->Printf( "Player %s's has been %s.\n", gameLocal.GetUserInfo( muteClient )->GetString( "ui_name" ), mute ? "muted" : "unmuted" ); } /* ================ idMultiplayerGame::GetClientNumFromPlayerName ================ */ int idMultiplayerGame::GetClientNumFromPlayerName( const char *playerName ) { if ( NULL == playerName || '\0' == *playerName ) { return -1; } int clientNum = -1; for ( int i = 0; i < gameLocal.numClients; i++ ) { if ( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idPlayer::GetClassType() ) ) { if ( 0 == idStr::Icmp( gameLocal.userInfo[ i ].GetString( "ui_name" ), playerName ) ) { clientNum = i; break; } } } if ( -1 == clientNum ) { common->Warning( "idMultiplayerGame::GetClientNumFromPlayerName(): unknown player '%s'", playerName ); } return clientNum; } /* ================ idMultiplayerGame::ServerHandleVoiceMuting ================ */ void idMultiplayerGame::ServerHandleVoiceMuting( int clientSrc, int clientDest, bool mute ) { assert( !gameLocal.isClient ); idPlayer *playerSrc = gameLocal.GetClientByNum( clientSrc ); idPlayer *playerDest = gameLocal.GetClientByNum( clientDest ); if ( NULL == playerSrc ) { common->DPrintf( "idMultiplayerGame::ServerHandleVoiceMuting: couldn't map client %d to a player\n", clientSrc ); return; } if ( NULL == playerDest ) { common->DPrintf( "idMultiplayerGame::ServerHandleVoiceMuting: couldn't map client %d to a player\n", clientDest ); return; } if ( mute ) { playerSrc->MutePlayer( playerDest, true ); common->DPrintf( "DEBUG: client %s muted to client %s\n", gameLocal.userInfo[ clientDest ].GetString( "ui_name" ), gameLocal.userInfo[ clientSrc ].GetString( "ui_name" ) ); } else { playerSrc->MutePlayer( playerDest, false ); common->DPrintf( "DEBUG: client %s unmuted to client %s\n", gameLocal.userInfo[ clientDest ].GetString( "ui_name" ), gameLocal.userInfo[ clientSrc ].GetString( "ui_name" ) ); } } /* ================ idMultiplayerGame::ClearAnnouncerSounds This method deletes unplayed announcer sounds at the end of a game round. This fixes a bug where the round time warnings were being played from previous rounds. ================ */ void idMultiplayerGame::ClearAnnouncerSounds( void ) { announcerSoundNode_t* snd = NULL; announcerSoundNode_t* nextSnd = NULL; for ( snd = announcerSoundQueue.Next(); snd != NULL; snd = nextSnd ) { nextSnd = snd->announcerSoundNode.Next(); snd->announcerSoundNode.Remove ( ); delete snd; } announcerPlayTime = 0; } /* ================ idMultiplayerGame::HandleServerAdminBanPlayer ================ */ void idMultiplayerGame::HandleServerAdminBanPlayer( int clientNum ) { if ( clientNum < 0 || clientNum >= gameLocal.numClients ) { common->DPrintf( "idMultiplayerGame::HandleServerAdminBanPlayer: bad client num %d\n", clientNum ); return; } if ( gameLocal.isServer || gameLocal.isListenServer ) { if ( gameLocal.isListenServer && clientNum == gameLocal.localClientNum ) { common->DPrintf( "idMultiplayerGame::HandleServerAdminBanPlayer: Cannot ban the host!\n" ); return; } cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "kick %i ban", clientNum ) ); } else { if ( clientNum == gameLocal.localClientNum ) { common->DPrintf( "idMultiplayerGame::HandleServerAdminBanPlayer: Cannot ban yourserlf!\n" ); return; } cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon kick %i ban", clientNum ) ); } } /* ================ idMultiplayerGame::HandleServerAdminRemoveBan ================ */ void idMultiplayerGame::HandleServerAdminRemoveBan( const char * clientGuid ) { if ( NULL == clientGuid || !clientGuid[ 0 ]) { common->DPrintf( "idMultiplayerGame::HandleServerAdminRemoveBan: bad guid!\n" ); return; } if ( gameLocal.isServer || gameLocal.isListenServer ) { gameLocal.RemoveGuidFromBanList( clientGuid ); } else { int clientNum = gameLocal.GetClientNumByGuid( clientGuid ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon removeClientFromBanList %d", clientNum ) ); } } /* ================ idMultiplayerGame::HandleServerAdminKickPlayer ================ */ void idMultiplayerGame::HandleServerAdminKickPlayer( int clientNum ) { if ( clientNum < 0 || clientNum >= gameLocal.numClients ) { common->DPrintf( "idMultiplayerGame::HandleServerAdminKickPlayer: bad client num %d\n", clientNum ); return; } if ( gameLocal.isServer || gameLocal.isListenServer ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "kick %i", clientNum ) ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon kick %i", clientNum ) ); } } /* ================ idMultiplayerGame::HandleServerAdminForceTeamSwitch ================ */ void idMultiplayerGame::HandleServerAdminForceTeamSwitch( int clientNum ) { if ( !gameLocal.IsTeamGame() ) { return; } if ( clientNum < 0 || clientNum >= gameLocal.numClients ) { common->DPrintf( "idMultiplayerGame::HandleServerAdminForceTeamSwitch: bad client num %d\n", clientNum ); return; } if ( gameLocal.isServer || gameLocal.isListenServer ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "forceTeamChange %d\n", clientNum)); /* if ( gameLocal.entities[ clientNum ] && gameLocal.entities[ clientNum ]->IsType( idPlayer::GetClassType() ) ) { idPlayer *player = static_cast< idPlayer *>( gameLocal.entities[ clientNum ] ); player->GetUserInfo()->Set( "ui_team", player->team ? "Marine" : "Strogg" ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "updateUI %d\n", clientNum ) ); }*/ } else { /* idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_SERVER_ADMIN ); outMsg.WriteByte( SERVER_ADMIN_FORCE_SWITCH ); outMsg.WriteByte( clientNum ); networkSystem->ClientSendReliableMessage( outMsg ); */ //jshepard: need to be able to do this via rcon cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon forceTeamChange %d\n", clientNum)); } } /* ================ idMultiplayerGame::HandleServerAdminCommands ================ */ bool idMultiplayerGame::HandleServerAdminCommands( serverAdminData_t &data ) { bool restartNeeded = false; bool nextMapNeeded = false; bool anyChanges = false; bool runPickMap = false; int nGameType = 0; idStr currentMap = si_map.GetString( ); const char *szGameType = gameLocal.serverInfo.GetString( "si_gametype" ); if ( 0 == idStr::Icmp( szGameType, "DM" ) ) { nGameType = GAME_DM; } else if ( 0 == idStr::Icmp( szGameType, "Team DM" ) ) { nGameType = GAME_TDM; } else if ( 0 == idStr::Icmp( szGameType, "CTF" ) ) { nGameType = GAME_CTF; } else if ( 0 == idStr::Icmp( szGameType, "Tourney" ) ) { nGameType = GAME_TOURNEY; } else if ( 0 == idStr::Icmp( szGameType, "Arena CTF" ) ) { nGameType = GAME_ARENA_CTF; } else if ( 0 == idStr::Icmp( szGameType, "DeadZone" ) ) { nGameType = GAME_DEADZONE; } else { nGameType = GAME_SP; } if ( nGameType != data.gameType ) { switch ( data.gameType ) { case GAME_TDM: szGameType = "Team DM"; runPickMap = true; break; case GAME_TOURNEY: szGameType = "Tourney"; runPickMap = true; break; case GAME_CTF: szGameType = "CTF"; runPickMap = true; break; case GAME_ARENA_CTF: szGameType = "Arena CTF"; runPickMap = true; break; // mekberg: hack, if we had 1f ctf the gui index wouldn't be off =( case GAME_1F_CTF: szGameType = "Arena CTF"; runPickMap = true; break; case GAME_DEADZONE: szGameType = "DeadZone"; runPickMap = true; break; default: case GAME_DM: szGameType = "DM"; break; } //we're going to reset the map here, so make sure to kill the active vote. ClientUpdateVote( VOTE_RESET, 0, 0, currentVoteData ); vote = VOTE_NONE; restartNeeded = true; anyChanges = true; si_gameType.SetString( szGameType ); if( runPickMap && gameLocal.isServer ) { //set the selected map to the admin data value, then make sure it can run the selected gametype. si_map.SetString( data.mapName.c_str() ); if( PickMap( szGameType ) || idStr::Icmp( si_map.GetString( ), currentMap.c_str( ) ) ) { nextMapNeeded = true; restartNeeded = false; data.mapName = idStr( si_map.GetString() ); data.restartMap = true; } } } if ( gameLocal.serverInfo.GetBool( "si_isBuyingEnabled" ) != data.buying ) restartNeeded = true; // Rcon these cvars if this isn't the server. We can trust the input from the gui that the // gametype and map always match. if ( !gameLocal.isServer ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_autoBalance %d", data.autoBalance ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_isBuyingEnabled %d", data.buying ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_captureLimit %d", data.captureLimit ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_controlTime %d", data.controlTime ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_fragLimit %d", data.fragLimit ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_gameType %s", szGameType ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_map %s", data.mapName.c_str() ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_tourneyLimit %d", data.tourneyLimit ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_minPlayers %d", data.minPlayers ) ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon si_timeLimit %d", data.timeLimit ) ); if( runPickMap ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "rcon verifyServerSettings" ) ); } if( data.shuffleTeams ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rcon shuffleTeams" ); } if( restartNeeded ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rcon serverMapRestart" ); } else if( data.restartMap || nextMapNeeded || idStr::Icmp( gameLocal.serverInfo.GetString( "si_map" ), data.mapName.c_str() ) ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rcon serverNextMap" ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rcon rescanSI" ); } return true; } if ( data.restartMap ) { ClientUpdateVote( VOTE_RESET, 0, 0, currentVoteData ); vote = VOTE_NONE; restartNeeded = true; anyChanges = true; } if ( data.shuffleTeams ) { ShuffleTeams(); anyChanges = true; } //this section won't be encountered if the gametype was changed. But that's ok. if ( data.mapName.c_str() && idStr::Icmp( data.mapName.c_str(), si_map.GetString() ) ) { ClientUpdateVote( VOTE_RESET, 0, 0, currentVoteData ); vote = VOTE_NONE; si_map.SetString(data.mapName.c_str()); cvarSystem->SetCVarString( "si_map", data.mapName.c_str() ); nextMapNeeded = true; anyChanges = true; } if ( data.captureLimit != gameLocal.serverInfo.GetInt( "si_captureLimit" ) ) { si_captureLimit.SetInteger( data.captureLimit ); anyChanges = true; } if ( data.fragLimit != gameLocal.serverInfo.GetInt( "si_fragLimit" ) ) { si_fragLimit.SetInteger( data.fragLimit ); anyChanges = true; } if ( data.tourneyLimit != gameLocal.serverInfo.GetInt( "si_tourneyLimit" ) ) { si_tourneyLimit.SetInteger( data.tourneyLimit ); anyChanges = true; } if ( data.timeLimit != gameLocal.serverInfo.GetInt( "si_timeLimit" ) ) { si_timeLimit.SetInteger( data.timeLimit ); anyChanges = true; } if ( data.buying != gameLocal.serverInfo.GetBool( "si_isBuyingEnabled" ) ) { si_isBuyingEnabled.SetInteger( data.buying ); anyChanges = true; restartNeeded = true; } if ( data.autoBalance != gameLocal.serverInfo.GetBool( "si_autobalance" ) ) { si_autobalance.SetBool( data.autoBalance ); anyChanges = true; } if ( data.controlTime != gameLocal.serverInfo.GetInt( "si_controlTime" ) ) { si_controlTime.SetInteger( data.controlTime ); anyChanges = true; } if ( nextMapNeeded ) { ClientUpdateVote( VOTE_RESET, 0, 0, currentVoteData ); vote = VOTE_NONE; gameLocal.sessionCommand = "nextMap"; return anyChanges; } else if ( gameLocal.NeedRestart() || restartNeeded ) { ClientUpdateVote( VOTE_RESET, 0, 0, currentVoteData ); vote = VOTE_NONE; cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "serverMapRestart" ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" " " __FILE__ " " __LINESTR__ ); } return anyChanges; } // RAVEN END /* =============== idMultiplayerGame::WriteStartState =============== */ void idMultiplayerGame::WriteStartState( int clientNum, idBitMsg &msg, bool withLocalClient ) { int i; idEntity *ent; // send the start time msg.WriteLong( matchStartedTime ); // send the powerup states and the spectate states for( i = 0; i < gameLocal.numClients; i++ ) { ent = gameLocal.entities[ i ]; // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( ( withLocalClient || i != clientNum ) && ent && ent->IsType( idPlayer::GetClassType() ) ) { // RAVEN END msg.WriteShort( i ); msg.WriteShort( static_cast< idPlayer * >( ent )->inventory.powerups ); msg.WriteBits( ent->GetInstance(), ASYNC_PLAYER_INSTANCE_BITS ); msg.WriteBits( static_cast< idPlayer * >( ent )->spectating, 1 ); } } msg.WriteShort( MAX_CLIENTS ); } /* ================ idMultiplayerGame::ServerWriteInitialReliableMessages ================ */ void idMultiplayerGame::ServerWriteInitialReliableMessages( int clientNum ) { idBitMsg outMsg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; outMsg.Init( msgBuf, sizeof( msgBuf ) ); outMsg.BeginWriting(); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_STARTSTATE ); WriteStartState( clientNum, outMsg, false ); networkSystem->ServerSendReliableMessage( clientNum, outMsg ); // we send SI in connectResponse messages, but it may have been modified already outMsg.BeginWriting( ); outMsg.WriteByte( GAME_RELIABLE_MESSAGE_SERVERINFO ); outMsg.WriteDeltaDict( gameLocal.serverInfo, NULL ); networkSystem->ServerSendReliableMessage( clientNum, outMsg ); gameState->SendInitialState( clientNum ); } /* ================ idMultiplayerGame::ClientReadStartState ================ */ void idMultiplayerGame::ClientReadStartState( const idBitMsg &msg ) { int i, client, powerup; assert( gameLocal.isClient ); // read the state in preparation for reading snapshot updates matchStartedTime = msg.ReadLong( ); while ( ( client = msg.ReadShort() ) != MAX_CLIENTS ) { // RAVEN BEGIN // jnewquist: Use accessor for static class type assert( gameLocal.entities[ client ] && gameLocal.entities[ client ]->IsType( idPlayer::GetClassType() ) ); // RAVEN END powerup = msg.ReadShort(); int instance = ( msg.ReadBits( ASYNC_PLAYER_INSTANCE_BITS ) ); static_cast< idPlayer * >( gameLocal.entities[ client ] )->SetInstance( instance ); bool spectate = ( msg.ReadBits( 1 ) != 0 ); static_cast< idPlayer * >( gameLocal.entities[ client ] )->Spectate( spectate ); // set powerups after we get instance information for this client for ( i = 0; i < POWERUP_MAX; i++ ) { if ( powerup & ( 1 << i ) ) { static_cast< idPlayer * >( gameLocal.entities[ client ] )->GivePowerUp( i, 0 ); } } } } const char* idMultiplayerGame::announcerSoundDefs[ AS_NUM_SOUNDS ] = { // General announcements "announce_general_one", // AS_GENERAL_ONE "announce_general_two", // AS_GENERAL_TWO "announce_general_three", // AS_GENERAL_THREE "announce_general_you_win", // AS_GENERAL_YOU_WIN "announce_general_you_lose", // AS_GENERAL_YOU_LOSE "announce_general_fight", // AS_GENERAL_FIGHT "announce_general_sudden_death", // AS_GENERAL_SUDDEN_DEATH "announce_general_vote_failed", // AS_GENERAL_VOTE_FAILED "announce_general_vote_passed", // AS_GENERAL_VOTE_PASSED "announce_general_vote_now", // AS_GENERAL_VOTE_NOW "announce_general_one_frag", // AS_GENERAL_ONE_FRAG "announce_general_two_frags", // AS_GENERAL_TWO_FRAGS "announce_general_three_frags", // AS_GENERAL_THREE_FRAGS "announce_general_one_minute", // AS_GENERAL_ONE_MINUTE "announce_general_five_minute", // AS_GENERAL_FIVE_MINUTE "announce_general_prepare_to_fight", // AS_GENERAL_PREPARE_TO_FIGHT "announce_general_quad_damage", // AS_GENERAL_QUAD_DAMAGE "announce_general_regeneration", // AS_GENERAL_REGENERATION "announce_general_haste", // AS_GENERAL_HASTE "announce_general_invisibility", // AS_GENERAL_INVISIBILITY // DM announcements "announce_dm_you_tied_lead", // AS_DM_YOU_TIED_LEAD "announce_dm_you_have_taken_lead", // AS_DM_YOU_HAVE_TAKEN_LEAD "announce_dm_you_lost_lead", // AS_DM_YOU_LOST_LEAD // Team announcements "announce_team_enemy_score", // AS_TEAM_ENEMY_SCORES "announce_team_you_score", // AS_TEAM_YOU_SCORE "announce_team_teams_tied", // AS_TEAM_TEAMS_TIED "announce_team_strogg_lead", // AS_TEAM_STROGG_LEAD "announce_team_marines_lead", // AS_TEAM_MARINES_LEAD "announce_team_join_marine", // AS_TEAM_JOIN_MARINE "announce_team_join_strogg", // AS_TEAM_JOIN_STROGG // CTF announcements "announce_ctf_you_have_flag", // AS_CTF_YOU_HAVE_FLAG "announce_ctf_your_team_has_flag", // AS_CTF_YOUR_TEAM_HAS_FLAG "announce_ctf_enemy_has_flag", // AS_CTF_ENEMY_HAS_FLAG "announce_ctf_your_team_drops_flag", // AS_CTF_YOUR_TEAM_DROPS_FLAG "announce_ctf_enemy_drops_flag", // AS_CTF_ENEMY_DROPS_FLAG "announce_ctf_your_flag_returned", // AS_CTF_YOUR_FLAG_RETURNED "announce_ctf_enemy_returns_flag", // AS_CTF_ENEMY_RETURNS_FLAG // Tourney announcements "announce_tourney_advance", // AS_TOURNEY_ADVANCE "announce_tourney_join_arena_one", // AS_TOURNEY_JOIN_ARENA_ONE "announce_tourney_join_arena_two", // AS_TOURNEY_JOIN_ARENA_TWO "announce_tourney_join_arena_three", // AS_TOURNEY_JOIN_ARENA_THREE "announce_tourney_join_arena_four", // AS_TOURNEY_JOIN_ARENA_FOUR "announce_tourney_join_arena_five", // AS_TOURNEY_JOIN_ARENA_FIVE "announce_tourney_join_arena_six", // AS_TOURNEY_JOIN_ARENA_SIX "announce_tourney_join_arena_seven", // AS_TOURNEY_JOIN_ARENA_SEVEN "announce_tourney_join_arena_eight", // AS_TOURNEY_JOIN_ARENA_EIGHT "announce_tourney_join_arena_waiting", // AS_TOURNEY_JOIN_ARENA_WAITING "announce_tourney_done", // AS_TOURNEY_DONE "announce_tourney_start", // AS_TOURNEY_START "announce_tourney_eliminated", // AS_TOURNEY_ELIMINATED "announce_tourney_won", // AS_TOURNEY_WON "announce_tourney_prelims", // AS_TOURNEY_PRELIMS "announce_tourney_quarter_finals", // AS_TOURNEY_QUARTER_FINALS "announce_tourney_semi_finals", // AS_TOURNEY_SEMI_FINALS "announce_tourney_final_match", // AS_TOURNEY_FINAL_MATCH "sound/vo/mp/9_99_320_10", // AS_GENERAL_TEAM_AMMOREGEN "sound/vo/mp/9_99_360_6" // AS_GENERAL_TEAM_DOUBLER }; void idMultiplayerGame::ScheduleAnnouncerSound( announcerSound_t sound, float time, int instance, bool allowOverride ) { if( !gameLocal.GetLocalPlayer() ) { return; } if ( time < gameLocal.time ) { return; } if ( sound >= AS_NUM_SOUNDS ) { return; } announcerSoundNode_t* newSound = new announcerSoundNode_t; newSound->soundShader = sound; newSound->time = time; newSound->announcerSoundNode.SetOwner( newSound ); newSound->instance = instance; newSound->allowOverride = allowOverride; announcerSoundNode_t* snd = NULL; for ( snd = announcerSoundQueue.Next(); snd != NULL; snd = snd->announcerSoundNode.Next() ) { if ( snd->time > newSound->time ) { newSound->announcerSoundNode.InsertBefore( snd->announcerSoundNode ); break; } } if ( snd == NULL ) { newSound->announcerSoundNode.AddToEnd( announcerSoundQueue ); } } void idMultiplayerGame::RemoveAnnouncerSound( int type ) { // clean out any preexisting announcer sounds announcerSoundNode_t* snd = NULL; announcerSoundNode_t* nextSnd = NULL; for ( snd = announcerSoundQueue.Next(); snd != NULL; snd = nextSnd ) { nextSnd = snd->announcerSoundNode.Next(); if ( snd->soundShader == type ) { snd->announcerSoundNode.Remove( ); delete snd; break; } } // if a sound is currently playing, stop it if( lastAnnouncerSound == type ) { gameLocal.GetLocalPlayer()->StopSound( SND_CHANNEL_MP_ANNOUNCER, false ); lastAnnouncerSound = AS_NUM_SOUNDS; } } void idMultiplayerGame::RemoveAnnouncerSoundRange( int startType, int endType ) { // clean out any preexisting announcer sounds announcerSoundNode_t* snd = NULL; announcerSoundNode_t* nextSnd = NULL; for ( snd = announcerSoundQueue.Next(); snd != NULL; snd = nextSnd ) { nextSnd = snd->announcerSoundNode.Next(); for( int i = startType; i <= endType; i++ ) { if ( snd->soundShader == i ) { snd->announcerSoundNode.Remove( ); delete snd; } } } // if a sound is currently playing, stop it for( int i = startType; i <= endType; i++ ) { if( lastAnnouncerSound == i ) { gameLocal.GetLocalPlayer()->StopSound( SND_CHANNEL_MP_ANNOUNCER, false ); lastAnnouncerSound = AS_NUM_SOUNDS; break; } } } void idMultiplayerGame::ScheduleTimeAnnouncements( void ) { if( !gameLocal.GetLocalPlayer() || !gameState ) { // too early return; } if( gameState->GetMPGameState() != COUNTDOWN && gameState->GetMPGameState() != WARMUP ) { int timeLimit = gameLocal.serverInfo.GetInt( "si_timeLimit" ); int endGameTime = 0; if( gameLocal.gameType == GAME_TOURNEY ) { int arena = gameLocal.GetLocalPlayer()->GetArena(); if( !((rvTourneyGameState*)gameState)->GetArena( arena ).IsPlaying() ) { return; // arena is not active } // per-arena timelimits endGameTime = ((rvTourneyGameState*)gameState)->GetArena( arena ).GetMatchStartTime() + ( timeLimit * 60000 ); } else { endGameTime = matchStartedTime + ( timeLimit * 60000 ); } // clean out any preexisting announcer sounds RemoveAnnouncerSound( AS_GENERAL_ONE_MINUTE ); RemoveAnnouncerSound( AS_GENERAL_FIVE_MINUTE ); if( timeLimit > 5 ) { ScheduleAnnouncerSound( AS_GENERAL_FIVE_MINUTE, endGameTime - (5 * 60000) ); } if( timeLimit > 1 ) { ScheduleAnnouncerSound( AS_GENERAL_ONE_MINUTE, endGameTime - (60000) ); } } } void idMultiplayerGame::PlayAnnouncerSounds( void ) { announcerSoundNode_t* snd = NULL; announcerSoundNode_t* nextSnd = NULL; if( !gameLocal.GetLocalPlayer() ) { return; } // if we're done playing the last sound reset override status if( announcerPlayTime <= gameLocal.time ) { currentSoundOverride = false; } if ( announcerPlayTime > gameLocal.time && !currentSoundOverride ) { return; } // in tourney only play sounds scheduled for your current arena if ( gameLocal.gameType == GAME_TOURNEY ) { // go through and find the first sound to play in our arena, delete any sounds // for other arenas we see along the way. for ( snd = announcerSoundQueue.Next(); snd != NULL; snd = nextSnd ) { nextSnd = snd->announcerSoundNode.Next(); if( snd->time > gameLocal.time ) { return; } if( snd->instance == -1 || snd->soundShader == AS_GENERAL_VOTE_NOW || snd->soundShader == AS_GENERAL_VOTE_PASSED || snd->soundShader == AS_GENERAL_VOTE_FAILED ) { // all-instance sound break; } if( snd->instance == gameLocal.GetLocalPlayer()->GetInstance() ) { if( snd->allowOverride && nextSnd && nextSnd->time <= gameLocal.time ) { // this sound is OK with being over-ridden, // and the next sound is ready to play, so go ahead and look at the next sound snd->announcerSoundNode.Remove ( ); delete snd; continue; } else { break; } } snd->announcerSoundNode.Remove ( ); delete snd; } } else { snd = announcerSoundQueue.Next(); if( snd && snd->time > gameLocal.time ) { return; } } // play the sound locally if ( snd && snd->soundShader < AS_NUM_SOUNDS ) { int length = 0; //don't play timelimit countdown announcements if game is already over mpGameState_t state = gameState->GetMPGameState(); if ( state == GAMEREVIEW //game is over, in scoreboard && ( snd->soundShader == AS_GENERAL_ONE_MINUTE || snd->soundShader == AS_GENERAL_FIVE_MINUTE ) ) { //ignore scheduled time limit warnings that haven't executed yet snd->announcerSoundNode.Remove(); delete snd; } else { snd->announcerSoundNode.Remove(); gameLocal.GetLocalPlayer()->StartSoundShader( declManager->FindSound( announcerSoundDefs[ snd->soundShader ], false ), SND_CHANNEL_MP_ANNOUNCER, 0, false, &length ); currentSoundOverride = snd->allowOverride; lastAnnouncerSound = snd->soundShader; delete snd; } // if sounds remain to be played, check again announcerPlayTime = gameLocal.time + length; } } void idMultiplayerGame::ClearTeamScores ( void ) { for ( int i = 0; i < TEAM_MAX; i++ ) { teamScore[ i ] = 0; teamDeadZoneScore[i] = 0; } } void idMultiplayerGame::AddTeamScore ( int team, int amount ) { if ( team < 0 || team >= TEAM_MAX ) { return; } teamScore[ team ] += amount; } void idMultiplayerGame::AddPlayerScore( idPlayer* player, int amount ) { if( player == NULL ) { gameLocal.Warning( "idMultiplayerGame::AddPlayerScore() - NULL player specified" ); return; } if( player->entityNumber < 0 || player->entityNumber >= MAX_CLIENTS ) { gameLocal.Warning( "idMultiplayerGame::AddPlayerScore() - Bad player entityNumber '%d'\n", player->entityNumber ); return; } playerState[ player->entityNumber ].fragCount += amount; playerState[ player->entityNumber ].fragCount = idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, playerState[ player->entityNumber ].fragCount ); } void idMultiplayerGame::AddPlayerTeamScore( idPlayer* player, int amount ) { if( player == NULL ) { gameLocal.Warning( "idMultiplayerGame::AddPlayerTeamScore() - NULL player specified" ); return; } if( player->entityNumber < 0 || player->entityNumber >= MAX_CLIENTS ) { gameLocal.Warning( "idMultiplayerGame::AddPlayerTeamScore() - Bad player entityNumber '%d'\n", player->entityNumber ); return; } playerState[ player->entityNumber ].teamFragCount += amount; playerState[ player->entityNumber ].teamFragCount = idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, playerState[ player->entityNumber ].teamFragCount ); } void idMultiplayerGame::AddPlayerWin( idPlayer* player, int amount ) { if( player == NULL ) { gameLocal.Warning( "idMultiplayerGame::AddPlayerWin() - NULL player specified" ); return; } if( player->entityNumber < 0 || player->entityNumber >= MAX_CLIENTS ) { gameLocal.Warning( "idMultiplayerGame::AddPlayerWin() - Bad player entityNumber '%d'\n", player->entityNumber ); return; } playerState[ player->entityNumber ].wins += amount; playerState[ player->entityNumber ].wins = idMath::ClampInt( 0, MP_PLAYER_MAXWINS, playerState[ player->entityNumber ].wins ); } void idMultiplayerGame::SetPlayerScore( idPlayer* player, int value ) { if( player == NULL ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerScore() - NULL player specified" ); return; } if( player->entityNumber < 0 || player->entityNumber >= MAX_CLIENTS ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerScore() - Bad player entityNumber '%d'\n", player->entityNumber ); return; } playerState[ player->entityNumber ].fragCount = idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, value ); } void idMultiplayerGame::SetPlayerTeamScore( idPlayer* player, int value ) { if( player == NULL ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerTeamScore() - NULL player specified" ); return; } if( player->entityNumber < 0 || player->entityNumber >= MAX_CLIENTS ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerTeamScore() - Bad player entityNumber '%d'\n", player->entityNumber ); return; } playerState[ player->entityNumber ].teamFragCount = idMath::ClampInt( MP_PLAYER_MINFRAGS, MP_PLAYER_MAXFRAGS, value ); } void idMultiplayerGame::SetPlayerDeadZoneScore( idPlayer* player, float value ) { if( player == NULL ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerDeadZoneScore() - NULL player specified" ); return; } if( player->entityNumber < 0 || player->entityNumber >= MAX_CLIENTS ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerDeadZoneScore() - Bad player entityNumber '%d'\n", player->entityNumber ); return; } playerState[ player->entityNumber ].deadZoneScore = value; } void idMultiplayerGame::SetPlayerWin( idPlayer* player, int value ) { if( player == NULL ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerWin() - NULL player specified" ); return; } if( player->entityNumber < 0 || player->entityNumber >= MAX_CLIENTS ) { gameLocal.Warning( "idMultiplayerGame::SetPlayerWin() - Bad player entityNumber '%d'\n", player->entityNumber ); return; } playerState[ player->entityNumber ].wins = idMath::ClampInt( 0, MP_PLAYER_MAXWINS, value ); } rvCTF_AssaultPoint* idMultiplayerGame::NextAP( int team ) { for( int i = 0; i < assaultPoints.Num(); i++ ) { if( assaultPoints[ (team ? (assaultPoints.Num() - 1 - i) : i) ]->GetOwner() == team ) { continue; } return assaultPoints[ (team ? (assaultPoints.Num() - 1 - i) : i) ]; } return NULL; } void idMultiplayerGame::ClientSetInstance( const idBitMsg& msg ) { assert( gameLocal.GetLocalPlayer() ); idPlayer* player = gameLocal.GetLocalPlayer(); int instance = msg.ReadByte(); gameLocal.GetInstance( 0 )->SetSpawnInstanceID( instance ); // on the client, we delete all entities, // the server will send over new ones gameLocal.InstanceClear(); // set the starting offset for repopulation back to matching what the server will have // this should be covered by setting indexes when populating the instances as well, but it doesn't hurt gameLocal.firstFreeIndex = MAX_CLIENTS; player->SetArena( instance ); player->SetInstance( instance ); // spawn the instance entities gameLocal.GetInstance( 0 )->PopulateFromMessage( msg ); // players in other instances might have been hidden, update them for( int i = 0; i < MAX_CLIENTS; i++ ) { idPlayer* p = (idPlayer*)gameLocal.entities[ i ]; if( p ) { if( p->GetInstance() == instance ) { p->ClientInstanceJoin(); } else { p->ClientInstanceLeave(); } } } } void idMultiplayerGame::ServerSetInstance( int instance ) { for( int i = MAX_CLIENTS; i < MAX_GENTITIES; i++ ) { idEntity* ent = gameLocal.entities[ i ]; if( ent ) { if( ent->GetInstance() != instance ) { ent->InstanceLeave(); } else { ent->InstanceJoin(); } } } } const char* idMultiplayerGame::GetLongGametypeName( const char* gametype ) { if( !idStr::Icmp( gametype, "Tourney" ) ) { return common->GetLocalizedString( "#str_107676" ); } else if( !idStr::Icmp( gametype, "Team DM" ) ) { return common->GetLocalizedString( "#str_107677" ); } else if( !idStr::Icmp( gametype, "CTF" ) ) { return common->GetLocalizedString( "#str_107678" ); } else if( !idStr::Icmp( gametype, "DM" ) ) { return common->GetLocalizedString( "#str_107679" ); } else if( !idStr::Icmp( gametype, "One Flag CTF" ) ) { return common->GetLocalizedString( "#str_107680" ); } else if( !idStr::Icmp( gametype, "Arena CTF" ) ) { return common->GetLocalizedString( "#str_107681" ); } else if( !idStr::Icmp( gametype, "Arena One Flag CTF" ) ) { return common->GetLocalizedString( "#str_107682" ); // RITUAL BEGIN // squirrel: added DeadZone multiplayer mode } else if( !idStr::Icmp( gametype, "DeadZone" ) ) { return common->GetLocalizedString( "#str_122001" ); // Squirrel@Ritual - Localized for 1.2 Patch // RITUAL END } return ""; } int idMultiplayerGame::GameTypeToVote( const char *gameType ) { if ( 0 == idStr::Icmp( gameType, "DM" ) ) { return VOTE_GAMETYPE_DM; } else if ( 0 == idStr::Icmp( gameType, "Tourney" ) ) { return VOTE_GAMETYPE_TOURNEY; } else if ( 0 == idStr::Icmp( gameType, "Team DM" ) ) { return VOTE_GAMETYPE_TDM; } else if ( 0 == idStr::Icmp( gameType, "CTF" ) ) { return VOTE_GAMETYPE_CTF; } else if ( 0 == idStr::Icmp( gameType, "Arena CTF" ) ) { return VOTE_GAMETYPE_ARENA_CTF; } else if ( 0 == idStr::Icmp( gameType, "DeadZone" ) ) { return VOTE_GAMETYPE_DEADZONE; } return VOTE_GAMETYPE_DM; } float idMultiplayerGame::GetPlayerDeadZoneScore( idPlayer* player ) { return playerState[ player->entityNumber ].deadZoneScore; } int idMultiplayerGame::GetPlayerTime( idPlayer* player ) { return ( gameLocal.time - player->GetConnectTime() ) / 60000; } int idMultiplayerGame::GetTeamScore( idPlayer* player ) { return GetTeamScore( player->entityNumber ); } int idMultiplayerGame::GetScore( idPlayer* player ) { return GetScore( player->entityNumber ); } int idMultiplayerGame::GetWins( idPlayer* player ) { return GetWins( player->entityNumber ); } void idMultiplayerGame::EnableDamage( bool enable ) { for( int i = 0; i < gameLocal.numClients; i++ ) { idPlayer* player = (idPlayer*)gameLocal.entities[ i ]; if( player == NULL ) { continue; } player->fl.takedamage = enable; } } void idMultiplayerGame::ReceiveRemoteConsoleOutput( const char* output ) { if( mainGui ) { idStr newOutput( output ); if( rconHistory.Length() + newOutput.Length() > RCON_HISTORY_SIZE ) { int removeLength = rconHistory.Find( '\n' ); if( removeLength == -1 ) { // nuke the whole string rconHistory.Empty(); } else { while( (rconHistory.Length() - removeLength) + newOutput.Length() > RCON_HISTORY_SIZE ) { removeLength = rconHistory.Find( '\n', removeLength + 1 ); if( removeLength == -1 ) { rconHistory.Empty(); break; } } } rconHistory = rconHistory.Right( rconHistory.Length() - removeLength ); } int consoleInputStart = newOutput.Find( "Console Input: " ); if( consoleInputStart != -1 ) { idStr consoleInput = newOutput.Right( newOutput.Length() - consoleInputStart - 15 ); newOutput = newOutput.Left( consoleInputStart ); newOutput.StripTrailing( "\n" ); consoleInput.StripTrailing( "\n" ); mainGui->SetStateString( "admin_console_input", consoleInput.c_str() ); } if( newOutput.Length() ) { rconHistory.Append( newOutput ); rconHistory.Append( '\n' ); } mainGui->SetStateString( "admin_console_history", rconHistory.c_str() ); } } /* =============== idMultiplayerGame::ShuffleTeams =============== */ void idMultiplayerGame::ShuffleTeams( void ) { // turn off autobalance if its on bool autoBalance = gameLocal.serverInfo.GetBool( "si_autoBalance" ); if( autoBalance ) { gameLocal.serverInfo.SetBool( "si_autoBalance", false ); } int loosingTeam = teamScore[ TEAM_MARINE ] < teamScore[ TEAM_STROGG ] ? TEAM_MARINE : TEAM_STROGG; int winningTeam = loosingTeam == TEAM_MARINE ? TEAM_STROGG : TEAM_MARINE; for( int i = 0; i < rankedPlayers.Num(); i++ ) { if( !(i % 2) ) { // switch even players to losing team if( rankedPlayers[ i ].First()->team != loosingTeam ) { rankedPlayers[ i ].First()->GetUserInfo()->Set( "ui_team", teamNames[ loosingTeam ] ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "updateUI %d\n", rankedPlayers[ i ].First()->entityNumber ) ); } } else { if( rankedPlayers[ i ].First()->team != winningTeam ) { rankedPlayers[ i ].First()->GetUserInfo()->Set( "ui_team", teamNames[ winningTeam ] ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "updateUI %d\n", rankedPlayers[ i ].First()->entityNumber ) ); } } } if( autoBalance ) { gameLocal.serverInfo.SetBool( "si_autoBalance", true ); } } rvGameState* idMultiplayerGame::GetGameState( void ) { return gameState; } void idMultiplayerGame::SetGameType( void ) { if( gameState ) { delete gameState; } gameState = NULL; if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "DM" ) == 0 ) ) { gameLocal.gameType = GAME_DM; gameState = new rvDMGameState(); } else if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "Tourney" ) == 0 ) ) { gameLocal.gameType = GAME_TOURNEY; gameState = new rvTourneyGameState(); } else if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "Team DM" ) == 0 ) ) { gameLocal.gameType = GAME_TDM; gameState = new rvTeamDMGameState(); } else if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "CTF" ) == 0 ) ) { gameLocal.gameType = GAME_CTF; gameState = new rvCTFGameState(); } else if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "One Flag CTF" ) == 0 ) ) { gameLocal.gameType = GAME_1F_CTF; gameState = new rvCTFGameState(); } else if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "Arena CTF" ) == 0 ) ) { gameLocal.gameType = GAME_ARENA_CTF; gameState = new rvCTFGameState(); } else if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "Arena One Flag CTF" ) == 0 ) ) { gameLocal.gameType = GAME_ARENA_1F_CTF; gameState = new rvCTFGameState(); } else if ( ( idStr::Icmp( gameLocal.serverInfo.GetString( "si_gameType" ), "DeadZone" ) == 0 ) ) { gameLocal.gameType = GAME_DEADZONE; gameState = new riDZGameState; } else { gameLocal.Error( "idMultiplayerGame::SetGameType() - Unknown gametype '%s'\n", gameLocal.serverInfo.GetString( "si_gameType" ) ); } // force entity filter to gametype name in multiplayer if( gameLocal.gameType != GAME_SP ) { gameLocal.serverInfo.Set( "si_entityFilter", gameLocal.serverInfo.GetString( "si_gameType" ) ); // also set as a CVar for when serverinfo is rescanned cvarSystem->SetCVarString( "si_entityFilter", gameLocal.serverInfo.GetString( "si_gameType" ) ); } } //asalmon: need to access total frags for a team and total score for a team int idMultiplayerGame::GetTeamsTotalFrags( int i ) { if( i < 0 || i > TEAM_MAX ) { return 0; } int total = 0; for(int j=0; j < GetNumRankedPlayers(); j++) { if(rankedPlayers[ j ].First()->team == i) { total += GetScore(rankedPlayers[ j ].First()->entityNumber); } } return total; } int idMultiplayerGame::GetTeamsTotalScore( int i ) { if( i < 0 || i > TEAM_MAX ) { return 0; } int total = 0; for(int j=0; j < GetNumRankedPlayers(); j++) { idPlayer foo; if(rankedPlayers[ j ].First()->team == i) { total += GetTeamScore(rankedPlayers[ j ].First()->entityNumber); } } return total; } /* =============== idMultiplayerGame::PickMap =============== */ bool idMultiplayerGame::PickMap( idStr gameType, bool checkOnly ) { idStrList maps; int miss = 0; const idDecl *mapDecl; const idDeclEntityDef *mapDef; int index = 0; int btype; const char* mapName; mapName = si_map.GetString(); // if we didn't set up a gametype, grab the current game type. if ( gameType.IsEmpty() ) { gameType = si_gameType.GetString(); } // if we're playing a map of this gametype, don't change. mapDecl = declManager->FindType( DECL_MAPDEF, mapName, false ); mapDef = static_cast<const idDeclEntityDef *>( mapDecl ); if ( mapDef ) { btype = mapDef->dict.GetInt( gameType ); if ( btype ) { // ( not sure what the gloubi boulga is about re-setting si_map two ways after reading it at the start of the function already ) cvarSystem->SetCVarString( "si_map", mapName ); si_map.SetString( mapName ); return false; } } if ( checkOnly ) { // always allow switching to DM mode, whatever the settings on the map ( DM should always be possible ) if ( !idStr::Icmp( si_gameType.GetString(), "DM" ) ) { return false; } // don't actually change anything, indicate we would return true; } int i; idFileList *files; idStrList fileList; int count = 0; files = fileSystem->ListFiles( "maps/mp", ".map" ); for ( i = 0; i < files->GetList().Num(); i++, count++ ) { fileList.AddUnique( va( "mp/%s", files->GetList()[i].c_str() ) ); } fileSystem->FreeFileList( files ); files = fileSystem->ListFiles( "maps/mp", ".mapc" ); for ( i = 0; i < files->GetList().Num(); i++, count++ ) { idStr fixedExtension(files->GetList()[i]); fixedExtension.SetFileExtension("map"); fileList.AddUnique( va( "mp/%s", fixedExtension.c_str() ) ); } fileList.Sort(); idStr name; idStr cycle; //Populate the map list for ( i = 0; i < fileList.Num(); i++) { //Add only MP maps. if(!idStr::FindText(fileList[i].c_str(), "mp/")) { maps.AddUnique(fileList[i].c_str()); } } maps.Sort(); if(maps.Num() > 0) { while(miss < 100) { index = gameLocal.random.RandomInt( maps.Num() ); mapName = maps[index].c_str(); mapDecl = declManager->FindType( DECL_MAPDEF, mapName, false ); mapDef = static_cast<const idDeclEntityDef *>( mapDecl ); if ( mapDef ) { btype = mapDef->dict.GetInt( gameType ); if(btype) { cvarSystem->SetCVarString("si_map",mapName); si_map.SetString( mapName ); return true; } } miss++; } } //something is wrong and there are no maps for this game type. This should never happen. gameLocal.Error( "No maps found for game type: %s.\n", gameType.c_str() ); return false; } /* =============== idMultiplayerGame::GetPlayerRankText =============== */ char* idMultiplayerGame::GetPlayerRankText( int rank, bool tied, int score ) { char* placeString; if( rank == 0 ) { //"1st^0 place with" placeString = va( "%s%s %d", S_COLOR_BLUE, common->GetLocalizedString( "#str_107689" ), score ); } else if( rank == 1 ) { //"2nd^0 place with" placeString = va( "%s%s %d", S_COLOR_RED, common->GetLocalizedString( "#str_107690" ), score ); } else if( rank == 2 ) { //"3rd^0 place with" placeString = va( "%s%s %d", S_COLOR_YELLOW, common->GetLocalizedString( "#str_107691" ), score ); } else { //"th^0 place with" placeString = va( "%d%s %d", rank + 1, common->GetLocalizedString( "#str_107692" ), score ); } if( tied ) { //Tied for return va( "%s %s", common->GetLocalizedString( "#str_107693" ), placeString ); } else { return placeString; } } /* =============== idMultiplayerGame::GetPlayerRankText =============== */ char* idMultiplayerGame::GetPlayerRankText( idPlayer* player ) { if( player == NULL ) { return ""; } bool tied = false; int rank = GetPlayerRank( player, tied ); return GetPlayerRankText( rank, tied, GetScore( player ) ); } /* =============== idMultiplayerGame::WriteNetworkInfo =============== */ void idMultiplayerGame::WriteNetworkInfo( idFile *file, int clientNum ) { idBitMsg msg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; msg.Init( msgBuf, sizeof( msgBuf ) ); msg.BeginWriting(); WriteStartState( clientNum, msg, true ); file->WriteInt( msg.GetSize() ); file->Write( msg.GetData(), msg.GetSize() ); gameState->WriteNetworkInfo( file, clientNum ); } /* =============== idMultiplayerGame::ReadNetworkInfo =============== */ void idMultiplayerGame::ReadNetworkInfo( idFile* file, int clientNum ) { idBitMsg msg; byte msgBuf[ MAX_GAME_MESSAGE_SIZE ]; int size; file->ReadInt( size ); msg.Init( msgBuf, sizeof( msgBuf ) ); msg.SetSize( size ); file->Read( msg.GetData(), size ); ClientReadStartState( msg ); gameState->ReadNetworkInfo( file, clientNum ); } void idMultiplayerGame::AddPrivatePlayer( int clientId ) { privateClientIds.Append( clientId ); } void idMultiplayerGame::RemovePrivatePlayer( int clientId ) { for( int i = 0; i < privateClientIds.Num(); i++ ) { if( clientId == privateClientIds[ i ] ) { privateClientIds.RemoveIndex( i ); i--; } } } void idMultiplayerGame::UpdatePrivatePlayerCount( void ) { if ( !gameLocal.isServer ) { return; } int numPrivatePlayers = 0; for( int i = 0; i < MAX_CLIENTS; i++ ) { if( privatePlayers & (1 << i) ) { if( gameLocal.entities[ i ] ) { numPrivatePlayers++; } else { privatePlayers &= ~( 1 << i ); } } } cvarSystem->SetCVarInteger( "si_numPrivatePlayers", numPrivatePlayers ); cmdSystem->BufferCommandText( CMD_EXEC_NOW, "rescanSI" " " __FILE__ " " __LINESTR__ ); } void idMultiplayerGame::SetFlagEntity( idEntity* ent, int team ) { assert( ( team == TEAM_STROGG || team == TEAM_MARINE ) ); flagEntities[ team ] = ent; } idEntity* idMultiplayerGame::GetFlagEntity( int team ) { assert( team >= 0 && team < TEAM_MAX ); return flagEntities[ team ]; } // <team to switch to> <named event for yes> <named event for no> <named event for same team> void idMultiplayerGame::CheckTeamBalance_f( const idCmdArgs &args ) { if ( args.Argc() < 5 ) { return; } idPlayer *localPlayer = gameLocal.GetClientByNum( gameLocal.localClientNum ); const char *team = args.Argv(1); const char *yesEvent = args.Argv(2); const char *noEvent = args.Argv(3); const char *sameTeamEvent = args.Argv(4); if ( !gameLocal.serverInfo.GetBool( "si_autoBalance" ) || !gameLocal.IsTeamGame() ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("GuiEvent %s", yesEvent) ); return; } int teamCount[2]; teamCount[0] = teamCount[1] = 0; for ( int i = 0; i < gameLocal.numClients; ++i ) { idEntity *ent = gameLocal.entities[i]; if ( ent && ent->IsType( idPlayer::GetClassType() ) && gameLocal.mpGame.IsInGame( i ) ) { if ( !static_cast< idPlayer * >( ent )->spectating && ent != localPlayer ) { teamCount[ static_cast< idPlayer * >( ent )->team ]++; } } } if ( idStr::Icmp( team, "marine" ) == 0 ) { if ( localPlayer->team == TEAM_MARINE && !localPlayer->spectating ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("GuiEvent %s", sameTeamEvent) ); } else { if ( teamCount[TEAM_MARINE] > teamCount[TEAM_STROGG] ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("GuiEvent %s", noEvent) ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("GuiEvent %s", yesEvent) ); } } } else { if ( localPlayer->team == TEAM_STROGG && !localPlayer->spectating ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("GuiEvent %s", sameTeamEvent) ); } else { if ( teamCount[TEAM_STROGG] > teamCount[TEAM_MARINE] ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("GuiEvent %s", noEvent) ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("GuiEvent %s", yesEvent) ); } } } } /* ================ idMultiplayerGame::LocalizeGametype dupe of rvServerScanGUI::LocalizeGametype ================ */ const char *idMultiplayerGame::LocalizeGametype( void ) { const char *gameType; gameType = gameLocal.serverInfo.GetString( "si_gametype" ); localisedGametype = gameType; if( !idStr::Icmp( gameType, "DM" ) ) { localisedGametype = common->GetLocalizedString( "#str_110011" ); } if( !idStr::Icmp( gameType, "Tourney" ) ) { localisedGametype = common->GetLocalizedString( "#str_110012" ); } if( !idStr::Icmp( gameType, "Team DM" ) ) { localisedGametype = common->GetLocalizedString( "#str_110013" ); } if( !idStr::Icmp( gameType, "CTF" ) ) { localisedGametype = common->GetLocalizedString( "#str_110014" ); } if( !idStr::Icmp( gameType, "Arena CTF" ) ) { localisedGametype = common->GetLocalizedString( "#str_110015" ); } if( !idStr::Icmp( gameType, "DeadZone" ) ) { localisedGametype = common->GetLocalizedString( "#str_122001" ); // Squirrel@Ritual - Localized for 1.2 Patch } return( localisedGametype.c_str() ); } int idMultiplayerGame::VerifyTeamSwitch( int wantTeam, idPlayer *player ) { idEntity* ent; int teamCount[ TEAM_MAX ]; int balanceTeam = -1; if( !gameLocal.serverInfo.GetBool( "si_autoBalance" ) ) { return wantTeam; } teamCount[ TEAM_MARINE ] = teamCount[ TEAM_STROGG ] = 0; for( int i = 0; i < gameLocal.numClients; i++ ) { ent = gameLocal.entities[ i ]; if ( ent && ent->IsType( idPlayer::GetClassType() ) && gameLocal.mpGame.IsInGame( i ) ) { if ( !static_cast< idPlayer * >( ent )->spectating && ent != player ) { teamCount[ static_cast< idPlayer * >( ent )->team ]++; } } } balanceTeam = -1; if ( teamCount[ TEAM_MARINE ] > teamCount[ TEAM_STROGG ] ) { balanceTeam = TEAM_STROGG; } else if ( teamCount[ TEAM_STROGG ] > teamCount[ TEAM_MARINE ] ) { balanceTeam = TEAM_MARINE; } return (balanceTeam == -1) ? wantTeam : balanceTeam; } // RITUAL BEGIN // squirrel: added DeadZone multiplayer mode /* ================ idMultiplayerGame::NumberOfPlayersOnTeam ================ */ int idMultiplayerGame::NumberOfPlayersOnTeam( int team ) { int teamPlayerCount = 0; for ( int i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( ent && ent->IsType( idPlayer::GetClassType() ) ) { idPlayer* entPlayer = static_cast< idPlayer * >( ent ); if( entPlayer->team == team ) { teamPlayerCount ++; } } } return teamPlayerCount; } /* ================ idMultiplayerGame::NumberOfAlivePlayersOnTeam ================ */ int idMultiplayerGame::NumberOfAlivePlayersOnTeam( int team ) { int teamAlivePlayerCount = 0; for ( int i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( ent && ent->IsType( idPlayer::GetClassType() ) ) { idPlayer* entPlayer = static_cast< idPlayer * >( ent ); if( entPlayer->team == team && entPlayer->allowedToRespawn ) { teamAlivePlayerCount ++; } } } return teamAlivePlayerCount; } // RITUAL END // RITUAL BEGIN // squirrel: Mode-agnostic buymenus /* ================ idMultiplayerGame::OpenLocalBuyMenu ================ */ void idMultiplayerGame::OpenLocalBuyMenu( void ) { // Buy menu work in progress //if ( gameLocal.mpGame.GetCurrentMenu() == 4 ) //{ // return; //} if ( currentMenu == 4 ) return; // Already open gameLocal.sessionCommand = "game_startmenu"; gameLocal.mpGame.nextMenu = 4; } /* ================ idMultiplayerGame::RedrawLocalBuyMenu ================ */ void idMultiplayerGame::RedrawLocalBuyMenu( void ) { if ( !buyMenu ) return; SetupBuyMenuItems(); buyMenu->HandleNamedEvent( "update_buymenu" ); } /* ================ idMultiplayerGame::GiveCashToTeam ================ */ void idMultiplayerGame::GiveCashToTeam( int team, float cashAmount ) { for ( int i = 0; i < gameLocal.numClients; i++ ) { idEntity *ent = gameLocal.entities[ i ]; if ( ent && ent->IsType( idPlayer::GetClassType() ) ) { idPlayer* entPlayer = static_cast< idPlayer * >( ent ); if( entPlayer->team == team ) { entPlayer->GiveCash( cashAmount ); } } } } /* ================ idMultiplayerGame::IsBuyingAllowedInTheCurrentGameMode ================ */ bool idMultiplayerGame::IsBuyingAllowedInTheCurrentGameMode( void ) { if ( !gameLocal.isMultiplayer ) { return false; } if ( gameLocal.gameType != GAME_TOURNEY ) { return gameLocal.serverInfo.GetBool( "si_isBuyingEnabled" ); } return false; } /* ================ idMultiplayerGame::IsBuyingAllowedRightNow ================ */ bool idMultiplayerGame::IsBuyingAllowedRightNow( void ) { return ( IsBuyingAllowedInTheCurrentGameMode() && isBuyingAllowedRightNow ); } void idMultiplayerGame::AddTeamPowerup(int powerup, int time, int team) { int i; for ( i=0; i<MAX_TEAM_POWERUPS; i++ ) { if ( teamPowerups[team][i].powerup == powerup ) { //teamPowerups[team][i].time = teamPowerups[team][i].endTime - gameLocal.time + time; //teamPowerups[team][i].endTime += time; // Just reset the time to it's maximum. This effectively caps the time // from accumulating infinitely if the players are very wealthy. teamPowerups[team][i].endTime = gameLocal.time + time; teamPowerups[team][i].time = time; teamPowerups[team][i].update = true; return; } } // If we get here, the powerup wasn't previously active, so find the first // empty slot available and activate the powerup for ( i=0; i<MAX_TEAM_POWERUPS; i++ ) { if ( teamPowerups[team][i].powerup == 0 ) { teamPowerups[team][i].powerup = powerup; teamPowerups[team][i].endTime = gameLocal.time + time; teamPowerups[team][i].time = time; teamPowerups[team][i].update = true; return; } } } void idMultiplayerGame::UpdateTeamPowerups( void ) { int i,j; for ( i=0; i<TEAM_MAX; i++ ) for ( j=0; j<MAX_TEAM_POWERUPS; j++ ) { if ( teamPowerups[i][j].powerup == 0 ) continue; if ( teamPowerups[i][j].endTime < gameLocal.time ) { // Expired teamPowerups[i][j].powerup = 0; teamPowerups[i][j].time = 0; teamPowerups[i][j].endTime = 0; teamPowerups[i][j].update = false; } else { teamPowerups[i][j].time = teamPowerups[i][j].endTime - gameLocal.time; } } } void idMultiplayerGame::SetUpdateForTeamPowerups(int team) { int i; for ( i=0; i<MAX_TEAM_POWERUPS; i++ ) { if ( teamPowerups[team][i].powerup != 0 ) teamPowerups[team][i].update = true; } } // RITUAL END
0
0.944916
1
0.944916
game-dev
MEDIA
0.665311
game-dev
0.991077
1
0.991077
electronicarts/CnC_Generals_Zero_Hour
11,453
GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp
/* ** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*********************************************************************************************** *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** *********************************************************************************************** * * * Project Name : WW3D * * * * $Archive:: /Commando/Code/ww3d2/hmdldef.cpp $* * * * Author:: Greg_h * * * * $Modtime:: 1/08/01 10:04a $* * * * $Revision:: 1 $* * * *---------------------------------------------------------------------------------------------* * Functions: * * HModelDefClass::HModelDefClass -- Constructor * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #include "hmdldef.h" #include <assert.h> #include <string.h> #include "w3d_file.h" #include "chunkio.h" #include "snappts.h" /*********************************************************************************************** * HModelDefClass::HModelDefClass -- Constructor * * * * INPUT: * * * * OUTPUT: * * * * WARNINGS: * * * * HISTORY: * * 12/15/97 GTH : Created. * *=============================================================================================*/ HModelDefClass::HModelDefClass(void) : SubObjectCount(0), SubObjects(NULL), SnapPoints(NULL) { } /*********************************************************************************************** * HModelDefClass::~HModelDefClass -- destructor * * * * INPUT: * * * * OUTPUT: * * * * WARNINGS: * * * * HISTORY: * * 08/11/1997 GH : Created. * *=============================================================================================*/ HModelDefClass::~HModelDefClass(void) { Free(); } /*********************************************************************************************** * HModelDefClass::Free -- de-allocate all memory in use * * * * INPUT: * * * * OUTPUT: * * * * WARNINGS: * * * * HISTORY: * * 08/11/1997 GH : Created. * *=============================================================================================*/ void HModelDefClass::Free(void) { if (SubObjects != NULL) { delete[] SubObjects; SubObjects = NULL; } SubObjectCount = 0; if (SnapPoints != NULL) { SnapPoints->Release_Ref(); SnapPoints = NULL; } } /*********************************************************************************************** * HModelDefClass::Load -- load a set of mesh connections from a file * * * * INPUT: * * * * OUTPUT: * * * * WARNINGS: * * * * HISTORY: * * 08/11/1997 GH : Created. * *=============================================================================================*/ int HModelDefClass::Load_W3D(ChunkLoadClass & cload) { bool pre30 = false; int subobjcounter = 0; Free(); /* ** Read the first chunk, it should be the header */ if (!cload.Open_Chunk()) { return false; } if (cload.Cur_Chunk_ID() != W3D_CHUNK_HMODEL_HEADER) { goto Error; } /* ** read in the header */ W3dHModelHeaderStruct header; if (cload.Read(&header,sizeof(W3dHModelHeaderStruct)) != sizeof(W3dHModelHeaderStruct)) { goto Error; } cload.Close_Chunk(); /* ** process the header info */ strncpy(ModelName,header.Name,W3D_NAME_LEN); ModelName[W3D_NAME_LEN - 1] = 0; strncpy(BasePoseName,header.HierarchyName,W3D_NAME_LEN); BasePoseName[W3D_NAME_LEN-1] = 0; strcpy(Name,ModelName); /* ** Just allocate a node for the number of sub objects we're expecting */ SubObjectCount = header.NumConnections; SubObjects = W3DNEWARRAY HmdlNodeDefStruct[SubObjectCount]; if (SubObjects == NULL) { goto Error; } /* ** If this is pre-3.0 set a flag so that each render object's ** bone id will be incremented by one to account for the new ** root node added with version3.0 of the file format. Basically, ** I'm making all of the code assume that node 0 is the root and ** therefore, pre-3.0 files have to have it added and all of ** the indices adjusted */ if (header.Version < W3D_MAKE_VERSION(3,0)) { pre30 = true; } /* ** Process the rest of the chunks */ subobjcounter = 0; while (cload.Open_Chunk()) { switch (cload.Cur_Chunk_ID()) { case W3D_CHUNK_NODE: case W3D_CHUNK_COLLISION_NODE: case W3D_CHUNK_SKIN_NODE: if (!read_connection(cload,&(SubObjects[subobjcounter]),pre30)) { goto Error; } subobjcounter++; break; case W3D_CHUNK_POINTS: SnapPoints = W3DNEW SnapPointsClass; SnapPoints->Load_W3D(cload); break; default: break; } cload.Close_Chunk(); } return OK; Error: return LOAD_ERROR; } /*********************************************************************************************** * HModelDefClass::read_connection -- read a single connection from the file * * * * INPUT: * * * * OUTPUT: * * * * WARNINGS: * * * * HISTORY: * * 08/11/1997 GH : Created. * * 10/22/97 GH : Check for mesh connections with PivotID=-1 * *=============================================================================================*/ bool HModelDefClass::read_connection(ChunkLoadClass & cload,HmdlNodeDefStruct * node,bool pre30) { W3dHModelNodeStruct con; if (cload.Read(&con,sizeof(W3dHModelNodeStruct)) != sizeof(W3dHModelNodeStruct)) { return false; } strcpy(node->RenderObjName,ModelName); strcat(node->RenderObjName,"."); strcat(node->RenderObjName,con.RenderObjName); if (pre30) { if (con.PivotIdx == 65535) { node->PivotID = 0; } else { node->PivotID = con.PivotIdx + 1; } } else { assert(con.PivotIdx != 65535); node->PivotID = con.PivotIdx; } return true; }
0
0.904508
1
0.904508
game-dev
MEDIA
0.682488
game-dev
0.92921
1
0.92921
SourceEngine-CommunityEdition/source
2,542
game/client/c_te_beaments.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "c_te_basebeam.h" #include "iviewrender_beams.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: BeamEnts TE //----------------------------------------------------------------------------- class C_TEBeamEnts : public C_TEBaseBeam { public: DECLARE_CLASS( C_TEBeamEnts, C_TEBaseBeam ); DECLARE_CLIENTCLASS(); C_TEBeamEnts( void ); virtual ~C_TEBeamEnts( void ); virtual void PostDataUpdate( DataUpdateType_t updateType ); public: int m_nStartEntity; int m_nEndEntity; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_TEBeamEnts::C_TEBeamEnts( void ) { m_nStartEntity = 0; m_nEndEntity = 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_TEBeamEnts::~C_TEBeamEnts( void ) { } void TE_BeamEnts( IRecipientFilter& filter, float delay, int start, int end, int modelindex, int haloindex, int startframe, int framerate, float life, float width, float endWidth, int fadeLength, float amplitude, int r, int g, int b, int a, int speed ) { beams->CreateBeamEnts( start, end, modelindex, haloindex, 0.0f, life, width, endWidth, fadeLength, amplitude, a, 0.1 * (float)speed, startframe, 0.1 * (float)framerate, r, g, b ); } //----------------------------------------------------------------------------- // Purpose: // Input : bool - //----------------------------------------------------------------------------- void C_TEBeamEnts::PostDataUpdate( DataUpdateType_t updateType ) { beams->CreateBeamEnts( m_nStartEntity, m_nEndEntity, m_nModelIndex, m_nHaloIndex, 0.0f, m_fLife, m_fWidth, m_fEndWidth, m_nFadeLength, m_fAmplitude, a, 0.1 * m_nSpeed, m_nStartFrame, 0.1 * m_nFrameRate, r, g, b ); } // Expose the TE to the engine. IMPLEMENT_CLIENTCLASS_EVENT( C_TEBeamEnts, DT_TEBeamEnts, CTEBeamEnts ); BEGIN_RECV_TABLE(C_TEBeamEnts, DT_TEBeamEnts) RecvPropInt( RECVINFO(m_nStartEntity)), RecvPropInt( RECVINFO(m_nEndEntity)), END_RECV_TABLE()
0
0.744066
1
0.744066
game-dev
MEDIA
0.548277
game-dev,graphics-rendering
0.624594
1
0.624594
PhoenixBladez/SpiritMod
2,692
Items/Accessory/OpalFrog/OpalFrogGlobals.cs
using System; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace SpiritMod.Items.Accessory.OpalFrog { public class OpalFrogProjectile : GlobalProjectile { private Player GetPlayer(Projectile projectile) => Main.player[projectile.owner]; private OpalFrogPlayer GetOpalFrogPlayer(Projectile projectile) => GetPlayer(projectile).GetModPlayer<OpalFrogPlayer>(); //Increase pull speed based on hook stats public override void GrapplePullSpeed(Projectile projectile, Player player, ref float speed) { speed *= GetOpalFrogPlayer(projectile).HookStat; //Bat hook in 1.3 in particular is way too strong of a synergy, so temporary hardcoded nerf until 1.4 if (projectile.type == ProjectileID.BatHook && GetOpalFrogPlayer(projectile).AutoUnhook) speed *= 0.8f; } public override void GrappleRetreatSpeed(Projectile projectile, Player player, ref float speed) => speed *= GetOpalFrogPlayer(projectile).HookStat; public override bool PreAI(Projectile projectile) { var hitBox = projectile.Hitbox; hitBox.Inflate(hitBox.Width / 2, hitBox.Height / 2); //enlarge hitbox, as otherwise no intersection would happen when hooked into a tile //If the projectile has the hook aistyle, and intersects the owner's hitbox, and has the ai[0] value corresponding to being stuck in place, kill before stopping the player if(projectile.aiStyle == 7 && projectile.ai[0] == 2 && hitBox.Intersects(GetPlayer(projectile).Hitbox) && GetOpalFrogPlayer(projectile).AutoUnhook) { projectile.Kill(); return false; } return true; } } public class OpalFrogGItem : GlobalItem { //Simplest way I could find to increase hook shootspeed based on player hookstat, overriding shoot doesn't seem to work (hooks don't use shoot hook in the first place?) public override void UpdateInventory(Item item, Player player) => UpdateItem(item, player); public static void UpdateItem(Item item, Player player) { OpalFrogPlayer modPlayer = player.GetModPlayer<OpalFrogPlayer>(); //Create an instance of the projectile to check its aistyle Projectile shootInstance = new Projectile(); shootInstance.SetDefaults(item.shoot); //Create an instance of the item to find the base shootspeed Item baseItemInstance = new Item(); baseItemInstance.SetDefaults(item.type); //If the instance of the item's shoot projectile has hook aistyle, increase shootspeed if (shootInstance.aiStyle == 7) { //Due to update order, checks the last tick's hook stat value if the current hook stat value is the default item.shootSpeed = baseItemInstance.shootSpeed * Math.Max(modPlayer.HookStat, modPlayer.LastHookStat); } } } }
0
0.876413
1
0.876413
game-dev
MEDIA
0.982371
game-dev
0.959935
1
0.959935
FireEmblemUniverse/fireemblem8u
24,590
src/banim-efxmagic-demonsurge.c
#include "global.h" #include "anime.h" #include "ekrbattle.h" #include "efxbattle.h" #include "efxmagic.h" #include "hardware.h" #include "bmlib.h" #include "ekrdragon.h" // clang-format off struct ProcCmd CONST_DATA ProcScr_efxGorgon[] = { PROC_NAME("efxGorgon"), PROC_REPEAT(efxGorgon_Loop_Main), PROC_END, }; // clang-format on //! FE8U = 0x0806B4F8 void StartSpellAnimDemonSurge(struct Anim * anim) { struct ProcEfx * proc; SpellFx_Begin(); NewEfxSpellCast(); SpellFx_ClearBG1Position(); proc = Proc_Start(ProcScr_efxGorgon, PROC_TREE_3); proc->anim = anim; proc->timer = 0; proc->hitted = CheckRoundMiss(GetAnimRoundTypeAnotherSide(anim)); return; } //! FE8U = 0x0806B534 void efxGorgon_Loop_Main(struct ProcEfx * proc) { struct Anim * anim = GetAnimAnotherSide(proc->anim); int duration = EfxGetCamMovDuration(); proc->timer++; if (proc->timer == 1) { NewEfxFarAttackWithDistance(proc->anim, -1); } else if (proc->timer == duration + 11) { StartSubSpell_efxGorgon_806B680(anim); PlaySFX(0x3B6, 0x100, 192, 1); } else if (proc->timer == duration + 37) { StartSubSpell_efxGorgonBGDirt(anim); } else if (proc->timer == duration + 84) { sub_806BBDC(); } else if (proc->timer == duration + 96) { StartSubSpell_efxSuperdruidOBJ2(anim); } else if (proc->timer == duration + 111) { StartSpellThing_MagicQuake(proc->anim, 12, 4); StartSubSpell_efxGorgonBGTwister(anim); } else if (proc->timer == duration + 112) { StartSubSpell_efxGorgonOBJTwister(anim); } else if (proc->timer == duration + 122) { sub_806C464(); } else if (proc->timer == duration + 123) { StartSubSpell_efxGorgonBGFinish(anim); StartSpellThing_MagicQuake(proc->anim, 26, 2); } else if (proc->timer == duration + 149) { anim->state3 |= 9; StartBattleAnimHitEffectsDefault(anim, proc->hitted); if (!proc->hitted) { EfxPlayHittedSFX(anim); } } else if (proc->timer == duration + 169) { SpellFx_Finish(); RegisterEfxSpellCastEnd(); Proc_Break(proc); } return; } //! FE8U = 0x0806B64C void sub_806B64C(struct ProcEfxOBJ * proc) { AnimDelete(proc->anim2); gEfxBgSemaphore--; return; } //! FE8U = 0x0806B664 void sub_806B664(struct ProcEfxOBJ * proc) { struct Anim * anim = proc->anim2; anim->pScrStart = AnimScr_086EAE14; anim->pScrCurrent = AnimScr_086EAE14; anim->timer = 0; Proc_Break(proc); return; } // clang-format off struct ProcCmd CONST_DATA ProcScr_085D8B24[] = { PROC_SET_END_CB(sub_806B64C), PROC_SLEEP(25), PROC_REPEAT(sub_806B664), PROC_SLEEP(54), PROC_END, }; // clang-format on //! FE8U = 0x0806B680 void StartSubSpell_efxGorgon_806B680(struct Anim * anim) { struct ProcEfxOBJ * proc; struct Anim * frontAnim; u32 * scr; gEfxBgSemaphore++; proc = Proc_Start(ProcScr_085D8B24, PROC_TREE_3); proc->anim = anim; scr = AnimScr_086EAE24; frontAnim = EfxCreateFrontAnim(anim, scr, scr, scr, scr); proc->anim2 = frontAnim; if (GetAnimPosition(proc->anim) == 0) { frontAnim->xPosition = 88; } else { frontAnim->xPosition = 152; } frontAnim->yPosition = 84; if (gEkrDistanceType == 1) { if (GetAnimPosition(proc->anim) == 0) { frontAnim->xPosition -= 24; } else { frontAnim->xPosition += 24; } } if ((GetBanimDragonStatusType() == 1) || (GetBanimDragonStatusType() == 2)) { frontAnim->oam2Base |= 0xc00; } frontAnim->drawLayerPriority = 20; AnimSort(); SpellFx_RegisterObjGfx(Img_086E9D40, 32 * 4 * CHR_SIZE); SpellFx_RegisterObjPal(Pal_086EA3EC, PLTT_SIZE_4BPP); return; } //! FE8U = 0x0806B73C void efxGorgonBGDirt_Loop(struct ProcEfxBG * proc) { s16 ret = EfxAdvanceFrameLut((s16 *)&proc->timer, (s16 *)&proc->frame, proc->frame_config); if (ret >= 0) { u16 ** tsa = proc->tsal; u16 ** img = proc->img; u16 ** pal = proc->pal; SpellFx_RegisterBgGfx(*(img + ret), 32 * 8 * CHR_SIZE); SpellFx_RegisterBgPal(*(pal + ret), PLTT_SIZE_4BPP); SpellFx_WriteBgMap(proc->anim, *(tsa + ret), *(tsa + ret)); } else { if (ret == -1) { SpellFx_ClearBG1(); gEfxBgSemaphore--; SetDefaultColorEffects_(); Proc_Break(proc); } } return; } // clang-format off u16 * CONST_DATA TsaArray_efxGorgonBGDirt[] = { Tsa_086F0344, Tsa_086F03EC, Tsa_086F04B8, Tsa_086F05A0, Tsa_086F069C, Tsa_086F079C, Tsa_086F08B8, Tsa_086F09E0, Tsa_086F0B2C, Tsa_086F0C88, Tsa_086F0DF8, }; u16 * CONST_DATA ImgArray_efxGorgonBGDirt[] = { Img_086EB8B4, Img_086EBD44, Img_086EC264, Img_086EC7D4, Img_086ECDD8, Img_086ED424, Img_086EDAF8, Img_086EE25C, Img_086EE9F8, Img_086EF1DC, Img_086EF9C8, }; u16 * CONST_DATA PalArray_efxGorgonBGDirt[] = { Pal_086F01E4, Pal_086F0204, Pal_086F0224, Pal_086F0244, Pal_086F0264, Pal_086F0284, Pal_086F02A4, Pal_086F02C4, Pal_086F02E4, Pal_086F0304, Pal_086F0324, }; const u16 gFrameConfig_efxGorgonBGDirt[] = { 0, 5, 1, 5, 2, 5, 3, 5, 4, 5, 5, 5, 6, 5, 7, 5, 8, 5, 9, 5, 10, 5, -1, }; struct ProcCmd CONST_DATA ProcScr_efxGorgonBGDirt[] = { PROC_NAME("efxGorgonBGDirt"), PROC_REPEAT(efxGorgonBGDirt_Loop), PROC_END, }; // clang-format on //! FE8U = 0x0806B7A8 void StartSubSpell_efxGorgonBGDirt(struct Anim * anim) { struct ProcEfxBG * proc; gEfxBgSemaphore++; proc = Proc_Start(ProcScr_efxGorgonBGDirt, PROC_TREE_3); proc->anim = anim; proc->timer = 0; proc->frame = 0; proc->frame_config = gFrameConfig_efxGorgonBGDirt; proc->tsal = TsaArray_efxGorgonBGDirt; proc->img = ImgArray_efxGorgonBGDirt; proc->pal = PalArray_efxGorgonBGDirt; if (gEkrDistanceType == 1) { if (GetAnimPosition(anim) == 0) { BG_SetPosition(BG_1, 24, 0); } else { BG_SetPosition(BG_1, -24, 0); } } else { BG_SetPosition(BG_1, 0, 0); } SpellFx_SetSomeColorEffect(); return; } //! FE8U = 0x0806B830 void efxGorgonBGTwister_Loop(struct ProcEfxBG * proc) { int ret = EfxAdvanceFrameLut((s16 *)&proc->timer, (s16 *)&proc->frame, proc->frame_config); if (ret >= 0) { u16 ** tsa = proc->tsal; u16 ** img = proc->img; u16 ** pal = proc->pal; SpellFx_RegisterBgGfx(*(img + ret), 32 * 8 * CHR_SIZE); SpellFx_RegisterBgPal(*(pal + ret), PLTT_SIZE_4BPP); SpellFx_WriteBgMapExt(proc->anim, *(tsa + ret), 32, 20); } else { if (ret == -1) { SpellFx_ClearBG1(); gEfxBgSemaphore--; Proc_Break(proc); } } return; } // clang-format off u16 * CONST_DATA TsaArray_efxGorgonBGTwister[] = { Tsa_086F4A98, Tsa_086F4CCC, Tsa_086F4ED8, }; u16 * CONST_DATA ImgArray_efxGorgonBGTwister[] = { Img_086F0F6C, Img_086F24C8, Img_086F3830, }; u16 * CONST_DATA PalArray_efxGorgonBGTwister[] = { Pal_086F4A38, Pal_086F4A58, Pal_086F4A78, }; const u16 gFrameConfig_efxGorgonBGTwister[] = { 0, 2, 1, 2, 2, 2, 0, 2, 1, 2, 2, 2, -1, }; struct ProcCmd CONST_DATA ProcScr_efxGorgonBGTwister[] = { PROC_NAME("efxGorgonBGTwister"), PROC_REPEAT(efxGorgonBGTwister_Loop), PROC_END, }; // clang-format on //! FE8U = 0x0806B89C void StartSubSpell_efxGorgonBGTwister(struct Anim * anim) { struct ProcEfxBG * proc; gEfxBgSemaphore++; proc = Proc_Start(ProcScr_efxGorgonBGTwister, PROC_TREE_3); proc->anim = anim; proc->timer = 0; proc->frame = 0; proc->frame_config = gFrameConfig_efxGorgonBGTwister; proc->tsal = TsaArray_efxGorgonBGTwister; proc->img = ImgArray_efxGorgonBGTwister; proc->pal = PalArray_efxGorgonBGTwister; if (gEkrDistanceType == 1) { if (GetAnimPosition(anim) == 0) { BG_SetPosition(BG_1, 40, 0); } else { BG_SetPosition(BG_1, -24, 0); } } else { if (GetAnimPosition(anim) == 0) { BG_SetPosition(BG_1, 16, 0); } else { BG_SetPosition(BG_1, 0, 0); } } SpellFx_SetSomeColorEffect(); return; } struct Proc085D8C24 { /* 00 */ PROC_HEADER; /* 29 */ STRUCT_PAD(0x29, 0x4C); /* 4C */ s16 unk4C; }; //! FE8U = 0x0806B938 void sub_806B938(struct Proc085D8C24 * proc) { proc->unk4C = 0; return; } #define RGB_(r, g, b) (((b) << 10) | ((g) << 5) | (r)) //! FE8U = 0x0806B940 void sub_806B940(struct Proc085D8C24 * proc) { int sl; u16 * r6; u16 * r7; int sp_08; int ip; r7 = gPaletteBuffer; r6 = gEfxPal; sl = Interpolate(0, 0, 0x10, proc->unk4C, 12); *r6 = *r7; for (sp_08 = 0; sp_08 < 0x20; sp_08++) { switch (sp_08) { case 2: case 3: case 16: case 21: case 22: case 27: case 28: case 29: case 30: CpuFastCopy(r7, r6, 0x20); r7 += 0x10; r6 += 0x10; continue; default: break; } r7++; r6++; for (ip = 0; ip < 0xF; ip++) { u8 r = ((*r7 & 0x1f) * (0x10 - sl)) >> 4; u8 g = (((*r7 >> 5) & 0x1f) * (0x10 - sl)) >> 4; u8 b = (((*r7 >> 10) & 0x1f) * (0x10 - sl)) >> 4; *r6 = RGB_(r & 0x1f, g & 0x1f, b & 0x1f); r7++; r6++; } } CpuFastCopy(gEfxPal, (void *)PLTT, 0x400); DisablePaletteSync(); if (proc->unk4C == 12) { proc->unk4C = 0; Proc_Break(proc); } else { proc->unk4C++; } return; } //! FE8U = 0x0806BACC void sub_806BACC(struct Proc085D8C24 * proc) { int sl; u16 * r6; u16 * r7; int sp_08; int ip; r7 = gPaletteBuffer; r6 = gEfxPal; *r6 = *r7; for (sp_08 = 0; sp_08 < 0x20; sp_08++) { switch (sp_08) { case 2: case 3: case 16: case 18: case 21: case 22: case 27: case 28: case 29: case 30: CpuFastCopy(r7, r6, 0x20); r7 += 0x10; r6 += 0x10; continue; default: break; } r7++; r6++; for (ip = 0; ip < 0xF; ip++) { *r6 = 0; r7++; r6++; } } CpuFastCopy(gEfxPal, (void *)PLTT, 0x400); DisablePaletteSync(); if (proc->unk4C == 16) { Proc_Break(proc); } proc->unk4C++; return; } #undef RGB_ // clang-format off struct ProcCmd CONST_DATA ProcScr_085D8C24[] = { PROC_CALL(sub_806B938), PROC_REPEAT(sub_806B940), PROC_REPEAT(sub_806BACC), PROC_CALL(EnablePaletteSync), PROC_END, }; // clang-format on //! FE8U = 0x0806BBDC void sub_806BBDC(void) { Proc_Start(ProcScr_085D8C24, PROC_TREE_VSYNC); return; } //! FE8U = 0x0806BBF0 void efxGorgonOBJTwisterPiece_Loop(struct ProcEfxOBJ * proc) { switch (proc->unk44) { case 0: proc->anim2->xPosition -= 2; break; case 1: proc->anim2->xPosition -= 3; break; case 2: proc->anim2->xPosition -= 4; break; case 3: proc->anim2->xPosition += 2; break; case 4: proc->anim2->xPosition += 3; break; case 5: proc->anim2->xPosition += 4; break; } proc->anim2->yPosition -= 6; proc->timer++; if ((proc->timer == proc->terminator) || (proc->anim2->xPosition < -16)) { gEfxBgSemaphore--; AnimDelete(proc->anim2); Proc_Break(proc); } return; } // clang-format off struct ProcCmd CONST_DATA ProcScr_efxGorgonOBJTwisterPiece[] = { PROC_NAME("efxGorgonOBJTwisterPiece"), PROC_REPEAT(efxGorgonOBJTwisterPiece_Loop), PROC_END, }; // clang-format on //! FE8U = 0x0806BC98 void StartSubSpell_efxGorgonOBJTwisterPiece(struct Anim * anim, int flag, int c, int terminator) { struct ProcEfxOBJ * proc; struct Anim * frontAnim; u32 * scr; gEfxBgSemaphore++; proc = Proc_Start(ProcScr_efxGorgonOBJTwisterPiece, PROC_TREE_3); proc->anim = anim; proc->timer = 0; proc->terminator = terminator; proc->unk44 = c; scr = AnimScr_EfxCrimsonEyeOBJ; frontAnim = EfxCreateFrontAnim(anim, scr, scr, scr, scr); proc->anim2 = frontAnim; if (GetAnimPosition(proc->anim) == 0) { frontAnim->xPosition = 88; } else { frontAnim->xPosition = 152; } frontAnim->yPosition = 88; if (gEkrDistanceType == 1) { if (GetAnimPosition(proc->anim) == 0) { frontAnim->xPosition -= 0x18; } else { frontAnim->xPosition += 0x18; } } switch (proc->unk44) { case 0: frontAnim->xPosition -= 12; break; case 1: frontAnim->xPosition -= 24; break; case 2: frontAnim->xPosition -= 36; break; case 3: frontAnim->xPosition += 12; break; case 4: frontAnim->xPosition += 24; break; case 5: frontAnim->xPosition += 36; break; } if (flag == 0) { frontAnim->oamBase = 0x3E000100; } else { frontAnim->oamBase = 0x3C000100; } return; } //! FE8U = 0x0806BD94 void efxGorgonOBJTwister_Loop(struct ProcEfxOBJ * proc) { switch (proc->timer & 0x1f) { case 0: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 0, 0, 12 - proc->timer); break; case 4: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 1, 5, 12 - proc->timer); break; case 8: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 0, 6, 12 - proc->timer); break; case 12: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 1, 4, 12 - proc->timer); break; case 16: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 0, 2, 12 - proc->timer); break; case 20: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 1, 1, 12 - proc->timer); break; case 24: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 0, 3, 12 - proc->timer); break; case 28: StartSubSpell_efxGorgonOBJTwisterPiece(proc->anim, 1, 7, 12 - proc->timer); break; } proc->timer++; if (proc->timer == 0xc) { gEfxBgSemaphore--; Proc_Break(proc); } return; } // clang-format off struct ProcCmd CONST_DATA ProcScr_efxGorgonOBJTwister[] = { PROC_NAME("efxGorgonOBJTwister"), PROC_REPEAT(efxGorgonOBJTwister_Loop), PROC_END, }; // clang-format on //! FE8U = 0x0806BEEC void StartSubSpell_efxGorgonOBJTwister(struct Anim * anim) { struct ProcEfxOBJ * proc; gEfxBgSemaphore++; proc = Proc_Start(ProcScr_efxGorgonOBJTwister, PROC_TREE_3); proc->anim = anim; proc->timer = 0; if (GetAnimPosition(anim) == 0) { proc->unk32 = 88; } else { proc->unk32 = 152; } proc->unk3A = 72; if (gEkrDistanceType == 1) { if (GetAnimPosition(proc->anim) == 0) { proc->unk32 -= 24; } else { proc->unk32 += 24; } } // clang-format off SetObjAffine( 31, Div(+COS(0) * 16, 128), Div(-SIN(0) * 16, 128), Div(+SIN(0) * 16, 128), Div(+COS(0) * 16, 128) ); SetObjAffine( 30, Div(+COS(0) * 16, 256), Div(-SIN(0) * 16, 256), Div(+SIN(0) * 16, 256), Div(+COS(0) * 16, 256) ); // clang-format on SpellFx_RegisterObjPal(Pal_CrimsonEyeSprites, PLTT_SIZE_4BPP); SpellFx_RegisterObjGfx(Img_CrimsonEyeSprites, 32 * 4 * CHR_SIZE); return; } //! FE8U = 0x0806C050 void efxGorgonBGFinish_Loop(struct ProcEfxBG * proc) { s16 ret = EfxAdvanceFrameLut((s16 *)&proc->timer, (s16 *)&proc->frame, proc->frame_config); if (ret >= 0) { u16 ** tsa = proc->tsal; u16 ** img = proc->img; SpellFx_RegisterBgGfx(*(img + ret), 32 * 8 * CHR_SIZE); sub_8068AFC(GetAnimAnotherSide(proc->anim), *(tsa + ret), *(tsa + ret), 1); } else { if (ret == -1) { SpellFx_ClearBG1(); gEfxBgSemaphore--; SetDefaultColorEffects_(); Proc_Break(proc); } } return; } // clang-format off u16 * CONST_DATA TsaArray_efxGorgonBGFinish[] = { Tsa_086FDA64, Tsa_086FDB08, Tsa_086FDCE0, Tsa_086FDEC4, Tsa_086FE0D4, Tsa_086FE320, Tsa_086FE4E0, Tsa_086FE680, Tsa_086FE81C, }; u16 * CONST_DATA ImgArray_efxGorgonBGFinish[] = { Img_086F50D4, Img_086F6264, Img_086F7150, Img_086F80B8, Img_086F915C, Img_086FA350, Img_086FB07C, Img_086FBCE8, Img_086FCD58, }; const u16 gFrameConfig_efxGorgonBGFinish[] = { 0, 10, 1, 2, 2, 2, 3, 2, 4, 2, 5, 2, 6, 2, 7, 2, 8, 2, -1, }; struct ProcCmd CONST_DATA ProcScr_efxGorgonBGFinish[] = { PROC_NAME("efxGorgonBGFinish"), PROC_REPEAT(efxGorgonBGFinish_Loop), PROC_REPEAT(efxDarkLongMonsBG01_Loop_B), PROC_END, }; // clang-format on //! FE8U = 0x0806C0B8 void StartSubSpell_efxGorgonBGFinish(struct Anim * anim) { struct ProcEfxBG * proc; gEfxBgSemaphore++; proc = Proc_Start(ProcScr_efxGorgonBGFinish, PROC_TREE_3); proc->anim = anim; proc->timer = 0; proc->frame = 0; proc->frame_config = gFrameConfig_efxGorgonBGFinish; proc->tsal = TsaArray_efxGorgonBGFinish; proc->img = ImgArray_efxGorgonBGFinish; if (gEkrDistanceType == 1) { if (GetAnimPosition(anim) == 0) { BG_SetPosition(BG_1, 24, 0); } else { BG_SetPosition(BG_1, -24, 0); } } else { BG_SetPosition(BG_1, 0, 0); } SpellFx_RegisterBgPal(Pal_086FDA44, PLTT_SIZE_4BPP); SetPrimaryHBlankHandler(OnHBlank_806B088); return; } struct Proc085D8CE4 { /* 00 */ PROC_HEADER; /* 29 */ STRUCT_PAD(0x29, 0x4C); /* 4C */ s16 unk4C; }; //! FE8U = 0x0806C14C void sub_806C14C(struct Proc085D8CE4 * proc) { proc->unk4C = 0; return; } //! FE8U = 0x0806C154 void sub_806C154(struct Proc085D8CE4 * proc) { u16 * src; int i; int j; u16 * src_ = gEfxPal; for (i = 0, src = gEfxPal; i < 0x20; i++) { src_++; for (j = 0; j < 0xf; j++) { *src_ = 0x00007FFF; src_++; } } CpuFastCopy(src, (void *)PLTT, 0x400); DisablePaletteSync(); if (proc->unk4C == 8) { proc->unk4C = 0; Proc_Break(proc); } else { proc->unk4C++; } return; } #define RGB_(r, g, b) (((b) << 10) | ((g) << 5) | (r)) //! FE8U = 0x0806C1B8 void sub_806C1B8(struct Proc085D8CE4 * proc) { int sl; u16 * r6; u16 * r7; int sp_08; int ip; r7 = gPaletteBuffer; r6 = gEfxPal; *r6 = *r7; for (sp_08 = 0; sp_08 < 0x20; sp_08++) { switch (sp_08) { case 1: case 2: case 3: case 16: case 21: case 22: case 27: case 28: case 29: case 30: CpuFastCopy(r7, r6, 0x20); r7 += 0x10; r6 += 0x10; continue; default: break; } r7++; r6++; for (ip = 0; ip < 0xF; ip++) { *r6 = 0; r7++; r6++; } } CpuFastCopy(gEfxPal, (void *)PLTT, 0x400); DisablePaletteSync(); if (proc->unk4C == 18) { proc->unk4C = 0; Proc_Break(proc); } else { proc->unk4C++; } return; } //! FE8U = 0x0806C2D4 void sub_806C2D4(struct Proc085D8CE4 * proc) { int sl; u16 * r6; u16 * r7; int sp_08; int ip; r7 = gPaletteBuffer; r6 = gEfxPal; sl = Interpolate(0, 16, 0, proc->unk4C, 18); *r6 = *r7; for (sp_08 = 0; sp_08 < 0x20; sp_08++) { switch (sp_08) { case 1: case 2: case 3: case 16: case 21: case 22: case 27: case 28: case 29: case 30: CpuFastCopy(r7, r6, 0x20); r7 += 0x10; r6 += 0x10; continue; default: break; } r7++; r6++; for (ip = 0; ip < 0xF; ip++) { u8 r = ((*r7 & 0x1f) * (0x10 - sl)) >> 4; u8 g = (((*r7 >> 5) & 0x1f) * (0x10 - sl)) >> 4; u8 b = (((*r7 >> 10) & 0x1f) * (0x10 - sl)) >> 4; *r6 = RGB_(r & 0x1f, g & 0x1f, b & 0x1f); r7++; r6++; } } CpuFastCopy(gEfxPal, (void *)PLTT, 0x400); DisablePaletteSync(); if (proc->unk4C == 18) { proc->unk4C = 0; Proc_Break(proc); } else { proc->unk4C++; } return; } #undef RGB_ // clang-format off struct ProcCmd CONST_DATA ProcScr_085D8CE4[] = { PROC_CALL(sub_806C14C), PROC_REPEAT(sub_806C154), PROC_REPEAT(sub_806C1B8), PROC_REPEAT(sub_806C2D4), PROC_CALL(EnablePaletteSync), PROC_END, }; // clang-format on //! FE8U = 0x0806C464 void sub_806C464(void) { Proc_Start(ProcScr_085D8CE4, PROC_TREE_VSYNC); return; } struct Proc085D8D14 { /* 00 */ PROC_HEADER; /* 29 */ STRUCT_PAD(0x29, 0x4C); /* 4C */ s16 unk4C; }; #define RGB_(r, g, b) (((b) << 10) | ((g) << 5) | (r)) //! FE8U = 0x0806C478 void sub_806C478(struct Proc085D8D14 * proc) { int sl; u16 * r6; u16 * r7; int sp_08; int ip; r7 = gPaletteBuffer; r6 = gEfxPal; sl = Interpolate(0, 0, 0x10, proc->unk4C, 8); *r6 = *r7; for (sp_08 = 0; sp_08 < 0x20; sp_08++) { switch (sp_08) { case 1: case 2: case 3: case 16: case 21: case 22: case 27: case 28: case 29: case 30: CpuFastCopy(r7, r6, 0x20); r7 += 0x10; r6 += 0x10; continue; default: break; } r7++; r6++; for (ip = 0; ip < 0xF; ip++) { u8 r = ((*r7 & 0x1f) * (0x10 - sl)) >> 4; u8 g = (((*r7 >> 5) & 0x1f) * (0x10 - sl)) >> 4; u8 b = (((*r7 >> 10) & 0x1f) * (0x10 - sl)) >> 4; *r6 = RGB_(r & 0x1f, g & 0x1f, b & 0x1f); r7++; r6++; } } CpuFastCopy(gEfxPal, (void *)PLTT, 0x400); DisablePaletteSync(); if (proc->unk4C == 8) { proc->unk4C = 0; Proc_Break(proc); } else { proc->unk4C++; } return; } #undef RGB_ // clang-format off struct ProcCmd CONST_DATA ProcScr_085D8D14[] = { PROC_CALL(sub_806C14C), PROC_REPEAT(sub_806C478), PROC_REPEAT(sub_806C1B8), PROC_REPEAT(sub_806C2D4), PROC_CALL(EnablePaletteSync), PROC_END, }; // clang-format on //! FE8U = 0x0806C608 void sub_806C608(void) { Proc_Start(ProcScr_085D8D14, PROC_TREE_VSYNC); return; }
0
0.817382
1
0.817382
game-dev
MEDIA
0.388322
game-dev
0.959798
1
0.959798
RCInet/LastEpoch_Mods
11,169
AssetBundleExport/LibraryBack/PackageCache/com.unity.textmeshpro@2.1.6/Scripts/Editor/TMP_SpriteCharacterPropertyDrawer.cs
using UnityEngine; using UnityEngine.TextCore; using UnityEditor; using System.Collections; namespace TMPro.EditorUtilities { [CustomPropertyDrawer(typeof(TMP_SpriteCharacter))] public class TMP_SpriteCharacterPropertyDrawer : PropertyDrawer { int m_GlyphSelectedForEditing = -1; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty prop_SpriteName = property.FindPropertyRelative("m_Name"); SerializedProperty prop_SpriteNameHashCode = property.FindPropertyRelative("m_HashCode"); SerializedProperty prop_SpriteUnicode = property.FindPropertyRelative("m_Unicode"); SerializedProperty prop_SpriteGlyphIndex = property.FindPropertyRelative("m_GlyphIndex"); SerializedProperty prop_SpriteScale = property.FindPropertyRelative("m_Scale"); GUIStyle style = new GUIStyle(EditorStyles.label); style.richText = true; EditorGUIUtility.labelWidth = 40f; EditorGUIUtility.fieldWidth = 50; Rect rect = new Rect(position.x + 60, position.y, position.width, 49); // Display non-editable fields if (GUI.enabled == false) { // Sprite Character Index int spriteCharacterIndex; int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex); EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style); EditorGUI.LabelField(new Rect(rect.x + 75f, rect.y, 120f, 18), new GUIContent("Unicode: <color=#FFFF80>0x" + prop_SpriteUnicode.intValue.ToString("X") + "</color>"), style); EditorGUI.LabelField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), new GUIContent("Name: <color=#FFFF80>" + prop_SpriteName.stringValue + "</color>"), style); EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: <color=#FFFF80>" + prop_SpriteGlyphIndex.intValue + "</color>"), style); // Draw Sprite Glyph (if exists) DrawSpriteGlyph(position, property); EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: <color=#FFFF80>" + prop_SpriteScale.floatValue + "</color>"), style); } else // Display editable fields { // Get a reference to the underlying Sprite Asset TMP_SpriteAsset spriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset; // Sprite Character Index int spriteCharacterIndex; int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex); EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style); EditorGUIUtility.labelWidth = 55f; GUI.SetNextControlName("Unicode Input"); EditorGUI.BeginChangeCheck(); string unicode = EditorGUI.DelayedTextField(new Rect(rect.x + 75f, rect.y, 120, 18), "Unicode:", prop_SpriteUnicode.intValue.ToString("X")); if (GUI.GetNameOfFocusedControl() == "Unicode Input") { //Filter out unwanted characters. char chr = Event.current.character; if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F')) { Event.current.character = '\0'; } } if (EditorGUI.EndChangeCheck()) { // Update Unicode value prop_SpriteUnicode.intValue = TMP_TextUtilities.StringHexToInt(unicode); spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; } EditorGUIUtility.labelWidth = 41f; EditorGUI.BeginChangeCheck(); EditorGUI.DelayedTextField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), prop_SpriteName, new GUIContent("Name:")); if (EditorGUI.EndChangeCheck()) { // Recompute hashCode for new name prop_SpriteNameHashCode.intValue = TMP_TextUtilities.GetSimpleHashCode(prop_SpriteName.stringValue); spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; } EditorGUIUtility.labelWidth = 59f; EditorGUI.BeginChangeCheck(); EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_SpriteGlyphIndex, new GUIContent("Glyph ID:")); if (EditorGUI.EndChangeCheck()) { spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; } // Draw Sprite Glyph (if exists) DrawSpriteGlyph(position, property); int glyphIndex = prop_SpriteGlyphIndex.intValue; // Reset glyph selection if new character has been selected. if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex) m_GlyphSelectedForEditing = -1; // Display button to edit the glyph data. if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph"))) { if (m_GlyphSelectedForEditing == -1) m_GlyphSelectedForEditing = glyphIndex; else m_GlyphSelectedForEditing = -1; // Button clicks should not result in potential change. GUI.changed = false; } // Show the glyph property drawer if selected if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled) { if (spriteAsset != null) { // Lookup glyph and draw glyph (if available) int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex); if (elementIndex != -1) { // Get a reference to the Sprite Glyph Table SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable"); SerializedProperty prop_SpriteGlyph = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex); SerializedProperty prop_GlyphMetrics = prop_SpriteGlyph.FindPropertyRelative("m_Metrics"); SerializedProperty prop_GlyphRect = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect"); Rect newRect = EditorGUILayout.GetControlRect(false, 115); EditorGUI.DrawRect(new Rect(newRect.x + 62, newRect.y - 20, newRect.width - 62, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f)); EditorGUI.DrawRect(new Rect(newRect.x + 63, newRect.y - 19, newRect.width - 64, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f)); // Display GlyphRect newRect.x += 65; newRect.y -= 18; newRect.width += 5; EditorGUI.PropertyField(newRect, prop_GlyphRect); // Display GlyphMetrics newRect.y += 45; EditorGUI.PropertyField(newRect, prop_GlyphMetrics); rect.y += 120; } } } EditorGUIUtility.labelWidth = 39f; EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_SpriteScale, new GUIContent("Scale:")); } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 58; } void DrawSpriteGlyph(Rect position, SerializedProperty property) { // Get a reference to the sprite glyph table TMP_SpriteAsset spriteAsset = property.serializedObject.targetObject as TMP_SpriteAsset; if (spriteAsset == null) return; int glyphIndex = property.FindPropertyRelative("m_GlyphIndex").intValue; // Lookup glyph and draw glyph (if available) int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex); if (elementIndex != -1) { // Get a reference to the Sprite Glyph Table SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable"); SerializedProperty prop_SpriteGlyph = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex); SerializedProperty prop_GlyphRect = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect"); // Get a reference to the sprite texture Texture tex = spriteAsset.spriteSheet; // Return if we don't have a texture assigned to the sprite asset. if (tex == null) { Debug.LogWarning("Please assign a valid Sprite Atlas texture to the [" + spriteAsset.name + "] Sprite Asset.", spriteAsset); return; } Vector2 spriteTexPosition = new Vector2(position.x, position.y); Vector2 spriteSize = new Vector2(48, 48); Vector2 alignmentOffset = new Vector2((58 - spriteSize.x) / 2, (58 - spriteSize.y) / 2); float x = prop_GlyphRect.FindPropertyRelative("m_X").intValue; float y = prop_GlyphRect.FindPropertyRelative("m_Y").intValue; float spriteWidth = prop_GlyphRect.FindPropertyRelative("m_Width").intValue; float spriteHeight = prop_GlyphRect.FindPropertyRelative("m_Height").intValue; if (spriteWidth >= spriteHeight) { spriteSize.y = spriteHeight * spriteSize.x / spriteWidth; spriteTexPosition.y += (spriteSize.x - spriteSize.y) / 2; } else { spriteSize.x = spriteWidth * spriteSize.y / spriteHeight; spriteTexPosition.x += (spriteSize.y - spriteSize.x) / 2; } // Compute the normalized texture coordinates Rect texCoords = new Rect(x / tex.width, y / tex.height, spriteWidth / tex.width, spriteHeight / tex.height); GUI.DrawTextureWithTexCoords(new Rect(spriteTexPosition.x + alignmentOffset.x, spriteTexPosition.y + alignmentOffset.y, spriteSize.x, spriteSize.y), tex, texCoords, true); } } } }
0
0.792515
1
0.792515
game-dev
MEDIA
0.94721
game-dev
0.853675
1
0.853675
MaximumADHD/Roblox-Client-Tracker
2,635
LuaPackages/Packages/_Index/Foundation/Foundation/Components/Slider/useSliderVariants.lua
local Foundation = script:FindFirstAncestor("Foundation") local InputSize = require(Foundation.Enums.InputSize) type InputSize = InputSize.InputSize local SliderVariant = require(Foundation.Enums.SliderVariant) type SliderVariant = SliderVariant.SliderVariant local composeStyleVariant = require(Foundation.Utility.composeStyleVariant) type VariantProps = composeStyleVariant.VariantProps local Tokens = require(Foundation.Providers.Style.Tokens) type Tokens = Tokens.Tokens local VariantsContext = require(Foundation.Providers.Style.VariantsContext) local Types = require(Foundation.Components.Types) type ColorStyleValue = Types.ColorStyleValue type SliderVariantProps = { bar: { tag: string, }, fill: { tag: string, }, hitbox: { height: number, }, knob: { style: ColorStyleValue, dragStyle: ColorStyleValue?, stroke: Types.Stroke?, hasShadow: boolean?, }, } local function variantsFactory(tokens: Tokens) local common = { bar = { tag = "anchor-center-center position-center-center size-full-100 radius-small" }, fill = { tag = "radius-small" }, } local variants: { [SliderVariant]: VariantProps } = { [SliderVariant.Emphasis] = { bar = { tag = "bg-shift-400" }, fill = { tag = "bg-emphasis" }, knob = { style = tokens.Color.Extended.White.White_100, dragStyle = tokens.Color.ActionEmphasis.Background, hasShadow = true, }, }, [SliderVariant.Standard] = { bar = { tag = "bg-shift-400" }, fill = { tag = "bg-system-contrast" }, knob = { style = tokens.Color.System.Contrast, dragStyle = tokens.Color.System.Contrast, hasShadow = false, }, }, [SliderVariant.Utility] = { knob = { style = tokens.Color.None, dragStyle = tokens.Color.None, stroke = { Color = tokens.Color.System.Contrast.Color3, Transparency = tokens.Color.System.Contrast.Transparency, Thickness = tokens.Stroke.Thicker, }, hasShadow = true, }, }, } local sizes: { [InputSize]: VariantProps } = { [InputSize.XSmall] = { hitbox = { height = tokens.Size.Size_300 } }, [InputSize.Small] = { hitbox = { height = tokens.Size.Size_400 } }, [InputSize.Medium] = { hitbox = { height = tokens.Size.Size_500 } }, [InputSize.Large] = { hitbox = { height = tokens.Size.Size_700, }, }, } return { common = common, variants = variants, sizes = sizes } end return function(tokens: Tokens, size: InputSize, variant: SliderVariant): SliderVariantProps local props = VariantsContext.useVariants("Slider", variantsFactory, tokens) return composeStyleVariant(props.common, props.variants[variant], props.sizes[size]) end
0
0.877728
1
0.877728
game-dev
MEDIA
0.315162
game-dev
0.984245
1
0.984245
DrChat/Gmod-vphysics
3,951
bullet/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btConvexInternalShape.h" btConvexInternalShape::btConvexInternalShape() : m_localScaling(btScalar(1.), btScalar(1.), btScalar(1.)), m_collisionMargin(CONVEX_DISTANCE_MARGIN) { } void btConvexInternalShape::setLocalScaling(const btVector3& scaling) { m_localScaling = scaling.absolute(); } void btConvexInternalShape::getAabbSlow(const btTransform& trans, btVector3&minAabb, btVector3&maxAabb) const { #ifndef __SPU__ //use localGetSupportingVertexWithoutMargin? btScalar margin = getMargin(); for (int i=0;i<3;i++) { btVector3 vec(btScalar(0.), btScalar(0.), btScalar(0.)); vec[i] = btScalar(1.); btVector3 sv = localGetSupportingVertex(vec*trans.getBasis()); btVector3 tmp = trans(sv); maxAabb[i] = tmp[i]+margin; vec[i] = btScalar(-1.); tmp = trans(localGetSupportingVertex(vec*trans.getBasis())); minAabb[i] = tmp[i]-margin; } #endif } btVector3 btConvexInternalShape::localGetSupportingVertex(const btVector3& vec)const { #ifndef __SPU__ btVector3 supVertex = localGetSupportingVertexWithoutMargin(vec); if ( getMargin()!=btScalar(0.) ) { btVector3 vecnorm = vec; if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON)) { vecnorm.setValue(btScalar(-1.), btScalar(-1.), btScalar(-1.)); } vecnorm.normalize(); supVertex+= getMargin() * vecnorm; } return supVertex; #else btAssert(0); return btVector3(0,0,0); #endif //__SPU__ } btConvexInternalAabbCachingShape::btConvexInternalAabbCachingShape() : btConvexInternalShape(), m_localAabbMin(1,1,1), m_localAabbMax(-1,-1,-1), m_isLocalAabbValid(false) { } void btConvexInternalAabbCachingShape::getAabb(const btTransform& trans, btVector3& aabbMin, btVector3& aabbMax) const { getNonvirtualAabb(trans, aabbMin, aabbMax, getMargin()); } void btConvexInternalAabbCachingShape::setLocalScaling(const btVector3& scaling) { btConvexInternalShape::setLocalScaling(scaling); recalcLocalAabb(); } void btConvexInternalAabbCachingShape::recalcLocalAabb() { m_isLocalAabbValid = true; #if 1 static const btVector3 _directions[] = { btVector3( 1., 0., 0.), btVector3( 0., 1., 0.), btVector3( 0., 0., 1.), btVector3( -1., 0., 0.), btVector3( 0., -1., 0.), btVector3( 0., 0., -1.) }; btVector3 _supporting[] = { btVector3( 0., 0., 0.), btVector3( 0., 0., 0.), btVector3( 0., 0., 0.), btVector3( 0., 0., 0.), btVector3( 0., 0., 0.), btVector3( 0., 0., 0.) }; batchedUnitVectorGetSupportingVertexWithoutMargin(_directions, _supporting, 6); for ( int i = 0; i < 3; ++i ) { m_localAabbMax[i] = _supporting[i][i] + m_collisionMargin; m_localAabbMin[i] = _supporting[i + 3][i] - m_collisionMargin; } #else for (int i=0;i<3;i++) { btVector3 vec(btScalar(0.), btScalar(0.), btScalar(0.)); vec[i] = btScalar(1.); btVector3 tmp = localGetSupportingVertex(vec); m_localAabbMax[i] = tmp[i]+m_collisionMargin; vec[i] = btScalar(-1.); tmp = localGetSupportingVertex(vec); m_localAabbMin[i] = tmp[i]-m_collisionMargin; } #endif }
0
0.891874
1
0.891874
game-dev
MEDIA
0.978414
game-dev
0.985458
1
0.985458