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
skyrim-multiplayer/skymp
1,654
unit/AnimationSystemTest.cpp
#include "TestUtils.hpp" #include <catch2/catch_all.hpp> #include "ActionListener.h" PartOne& GetPartOne(); TEST_CASE("Animations system processes animation events correctly", "[AnimationSystem]") { PartOne& p = GetPartOne(); p.animationSystem.Init(&p.worldState); DoConnect(p, 0); p.CreateActor(0xff000000, { 0, 0, 0 }, 0, 0x3c); p.SetUserActor(0, 0xff000000); auto& actor = p.worldState.GetFormAt<MpActor>(0xff000000); AnimationData data; // Normally, stamina is not consumed when playing animations data.animEventName = "attackStart"; REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 1.f); p.animationSystem.Process(&actor, data); REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 1.f); data.animEventName = "JumpStandingStart"; REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 1.f); p.animationSystem.Process(&actor, data); REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 1.f); // Sweetpie p.worldState.espmFiles.push_back("SweetPie.esp"); p.animationSystem.Init(&p.worldState); data.animEventName = "attackStart"; REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 1.f); p.animationSystem.Process(&actor, data); // attackStart consumes 7 points of stamina REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 0.93f); data.animEventName = "JumpStandingStart"; REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 0.93f); p.animationSystem.Process(&actor, data); // JumpStandingStart consumes 10 points of stamina REQUIRE(actor.GetChangeForm().actorValues.staminaPercentage == 0.83f); }
412
0.711688
1
0.711688
game-dev
MEDIA
0.932507
game-dev
0.678124
1
0.678124
next-hack/MG24Quake
12,215
QuakeMG24/Quake/sv_move.c
/* Quake port to Silicon Labs EFR32MG24 and MGM240x by Nicola Wrachien (next-hack in the comments) Original Quake code has been deeply changed to run in only 276 kB RAM, and 32 MB external flash, while maintaining all the game and 3D engine features (except music and multiplayer). Copyright (C) 1996-1997 Id Software, Inc. Copyright (C) 2023-2024 Nicola Wrachien (next-hack in the comments) on EFR32MG24 and MGM240 port. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sv_move.c -- monster movement #include "quakedef.h" #if RETAIL_QUAKE_PAK_SUPPORT #pragma GCC optimize("Os") // #endif #define STEPSIZE 18 /* ============= SV_CheckBottom Returns false if any part of the bottom of the entity is off an edge that is not a staircase. ============= */ int c_yes, c_no; qboolean SV_CheckBottom(edict_t *ent) { vec3_t mins, maxs, start, stop; trace_t trace; int x, y; float mid, bottom; VectorAdd(VEC(get_qcc_origin(ent)), VEC(get_qcc_mins(ent)), mins); VectorAdd(VEC(get_qcc_origin(ent)), VEC(get_qcc_maxs(ent)), maxs); // if all of the points under the corners are solid world, don't bother // with the tougher checks // the corners must be within 16 of the midpoint start[2] = mins[2] - 1; for (x = 0; x <= 1; x++) for (y = 0; y <= 1; y++) { start[0] = x ? maxs[0] : mins[0]; start[1] = y ? maxs[1] : mins[1]; if (SV_PointContents(start) != CONTENTS_SOLID) goto realcheck; } c_yes++; return true; // we got out easy realcheck: c_no++; // // check it for real... // start[2] = mins[2]; // the midpoint must be within 16 of the bottom start[0] = stop[0] = (mins[0] + maxs[0]) * 0.5; start[1] = stop[1] = (mins[1] + maxs[1]) * 0.5; stop[2] = start[2] - 2 * STEPSIZE; trace = SV_Move(start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction == 1.0) return false; mid = bottom = trace.endpos[2]; // the corners must be within 16 of the midpoint for (x = 0; x <= 1; x++) for (y = 0; y <= 1; y++) { start[0] = stop[0] = x ? maxs[0] : mins[0]; start[1] = stop[1] = y ? maxs[1] : mins[1]; trace = SV_Move(start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction != 1.0 && trace.endpos[2] > bottom) bottom = trace.endpos[2]; if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) return false; } c_yes++; return true; } /* ============= SV_movestep Called by monster program code. The move will be adjusted for slopes and stairs, but if the move isn't possible, no move is done, false is returned, and pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ qboolean SV_movestep(edict_t *ent, vec3_t move, qboolean relink) { float dz; vec3_t oldorg, neworg, end; trace_t trace; int i; edict_t *enemy; // try the move VectorCopy(VEC(get_qcc_origin(ent)), oldorg); VectorAdd(VEC(get_qcc_origin(ent)), move, neworg); // flying monsters don't step up if ((int) get_qcc_flags(ent) & (FL_SWIM | FL_FLY)) { // try one move with vertical motion, then one without for (i = 0; i < 2; i++) { VectorAdd(VEC(get_qcc_origin(ent)), move, neworg); enemy = PROG_TO_EDICT(get_qcc_enemy(ent)); if (i == 0 && enemy != sv.edicts) { dz = VEC(get_qcc_origin(ent))[2] - VEC(get_qcc_origin(PROG_TO_EDICT(get_qcc_enemy(ent))))[2]; if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; } trace = SV_Move(VEC(get_qcc_origin(ent)), VEC(get_qcc_mins(ent)), VEC(get_qcc_maxs(ent)), neworg, false, ent); if (trace.fraction == 1) { if (((int) get_qcc_flags(ent) & FL_SWIM) && SV_PointContents(trace.endpos) == CONTENTS_EMPTY) return false; // swim monster left water set_qcc_origin(ent, vectorize(trace.endpos)); if (relink) SV_LinkEdict(ent, true); return true; } if (enemy == sv.edicts) break; } return false; } // push down from a step height above the wished position neworg[2] += STEPSIZE; VectorCopy(neworg, end); end[2] -= STEPSIZE * 2; trace = SV_Move(neworg, VEC(get_qcc_mins(ent)), VEC(get_qcc_maxs(ent)), end, false, ent); if (trace.allsolid) return false; if (trace.startsolid) { neworg[2] -= STEPSIZE; trace = SV_Move(neworg, VEC(get_qcc_mins(ent)), VEC(get_qcc_maxs(ent)), end, false, ent); if (trace.allsolid || trace.startsolid) return false; } if (trace.fraction == 1) { // if monster had the ground pulled out, go ahead and fall if ((int) get_qcc_flags(ent) & FL_PARTIALGROUND) { vec3_t temp; VectorAdd(VEC(get_qcc_origin(ent)), move, temp); set_qcc_origin(ent, vectorize(temp)); if (relink) SV_LinkEdict(ent, true); set_qcc_flags(ent, (int) get_qcc_flags(ent) & ~FL_ONGROUND); // Con_Printf ("fall down\n"); return true; } return false; // walked off an edge } // check point traces down for dangling corners set_qcc_origin(ent, vectorize(trace.endpos)); if (!SV_CheckBottom(ent)) { if ((int) get_qcc_flags(ent) & FL_PARTIALGROUND) { // entity had floor mostly pulled out from underneath it // and is trying to correct if (relink) SV_LinkEdict(ent, true); return true; } set_qcc_origin(ent, vectorize(oldorg)); return false; } if ((int) get_qcc_flags(ent) & FL_PARTIALGROUND) { // Con_Printf ("back on ground\n"); set_qcc_flags(ent, (int) get_qcc_flags(ent) & ~FL_PARTIALGROUND); } set_qcc_groundentity(ent, EDICT_TO_PROG(trace.ent)); // the move is ok if (relink) SV_LinkEdict(ent, true); return true; } //============================================================================ /* ====================== SV_StepDirection Turns to the movement direction, and walks the current distance if facing it. ====================== */ qboolean SV_StepDirection(edict_t *ent, float yaw, float dist) { vec3_t move, oldorigin; float delta; set_qcc_ideal_yaw(ent, yaw); #if USE_PROGSDAT PF_changeyaw(); #else qcc_ChangeYaw(); #endif yaw = yaw * M_PI * 2 / 360; move[0] = cos_t(yaw) * dist; move[1] = sin_t(yaw) * dist; move[2] = 0; VectorCopy(VEC(get_qcc_origin(ent)), oldorigin); if (SV_movestep(ent, move, false)) { delta = VEC(get_qcc_angles(ent))[YAW] - get_qcc_ideal_yaw(ent); if (delta > 45 && delta < 315) { // not turned far enough, so don't take the step set_qcc_origin(ent, vectorize(oldorigin)); } SV_LinkEdict(ent, true); return true; } SV_LinkEdict(ent, true); return false; } /* ====================== SV_FixCheckBottom ====================== */ void SV_FixCheckBottom(edict_t *ent) { // Con_Printf ("SV_FixCheckBottom\n"); set_qcc_flags(ent, (int) get_qcc_flags(ent) | FL_PARTIALGROUND); } /* ================ SV_NewChaseDir ================ */ #define DI_NODIR -1 void SV_NewChaseDir(edict_t *actor, edict_t *enemy, float dist) { float deltax, deltay; float d[3]; float tdir, olddir, turnaround; olddir = anglemod((int) (get_qcc_ideal_yaw(actor) / 45) * 45); turnaround = anglemod(olddir - 180); deltax = VEC(get_qcc_origin(enemy))[0] - VEC(get_qcc_origin(actor))[0]; deltay = VEC(get_qcc_origin(enemy))[1] - VEC(get_qcc_origin(actor))[1]; if (deltax > 10) d[1] = 0; else if (deltax < -10) d[1] = 180; else d[1] = DI_NODIR; if (deltay < -10) d[2] = 270; else if (deltay > 10) d[2] = 90; else d[2] = DI_NODIR; // try direct route if (d[1] != DI_NODIR && d[2] != DI_NODIR) { if (d[1] == 0) tdir = d[2] == 90 ? 45 : 315; else tdir = d[2] == 90 ? 135 : 215; if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) return; } // try other directions if (((rand() & 3) & 1) || abs(deltay) > abs(deltax)) { tdir = d[1]; d[1] = d[2]; d[2] = tdir; } if (d[1] != DI_NODIR && d[1] != turnaround && SV_StepDirection(actor, d[1], dist)) return; if (d[2] != DI_NODIR && d[2] != turnaround && SV_StepDirection(actor, d[2], dist)) return; /* there is no direct path to the player, so pick another direction */ if (olddir != DI_NODIR && SV_StepDirection(actor, olddir, dist)) return; if (rand() & 1) /*randomly determine direction of search*/ { for (tdir = 0; tdir <= 315; tdir += 45) if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) return; } else { for (tdir = 315; tdir >= 0; tdir -= 45) if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) return; } if (turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist)) return; set_qcc_ideal_yaw(actor, olddir); // can't move // if a bridge was pulled out from underneath a monster, it may not have // a valid standing position at all if (!SV_CheckBottom(actor)) SV_FixCheckBottom(actor); } /* ====================== SV_CloseEnough ====================== */ qboolean SV_CloseEnough(edict_t *ent, edict_t *goal, float dist) { #if USE_OLD_ABS_CALLS // tbd if is faster int i; for (i=0 ; i<3 ; i++) { if (VEC(get_qcc_absmin(goal))[i] > VEC(get_qcc_absmax(ent))[i] + dist) return false; if (VEC(get_qcc_absmax(goal))[i] < VEC(get_qcc_absmin(ent))[i] - dist) return false; } #else vector absminGoal = get_qcc_absmin(goal); vector absmaxEnt = get_qcc_absmax(ent); if (absminGoal.v[0] > absmaxEnt.v[0] + dist) return false; if (absminGoal.v[1] > absmaxEnt.v[1] + dist) return false; if (absminGoal.v[2] > absmaxEnt.v[2] + dist) return false; vector absmaxGoal = get_qcc_absmax(goal); vector absminEnt = get_qcc_absmin(ent); if (absmaxGoal.v[0] < absminEnt.v[0] - dist) return false; if (absmaxGoal.v[1] < absminEnt.v[1] - dist) return false; if (absmaxGoal.v[2] < absminEnt.v[2] - dist) return false; #endif return true; } /* ====================== SV_MoveToGoal ====================== */ void qcc_movetogoal(float dist) { edict_t *ent, *goal; //float dist; ent = PROG_TO_EDICT(progs.qcc_self); goal = PROG_TO_EDICT(get_qcc_goalentity(ent)); // dist = G_FLOAT(OFS_PARM0); if (!((int) get_qcc_flags(ent) & (FL_ONGROUND | FL_FLY | FL_SWIM))) { // ??? G_FLOAT(OFS_RETURN) = 0; return; } // if the next step hits the enemy, return immediately if (PROG_TO_EDICT(get_qcc_enemy(ent)) != sv.edicts && SV_CloseEnough(ent, goal, dist)) return; // bump around... if ((rand() & 3) == 1 || !SV_StepDirection(ent, get_qcc_ideal_yaw(ent), dist)) { SV_NewChaseDir(ent, goal, dist); } return; }
412
0.944476
1
0.944476
game-dev
MEDIA
0.562349
game-dev,audio-video-media
0.99755
1
0.99755
CWBudde/DWScript
31,145
Source/jitter/dwsJIT.pas
{**************************************************************************} { } { This Source Code Form is subject to the terms of the Mozilla Public } { License, v. 2.0. If a copy of the MPL was not distributed with this } { file, You can obtain one at http://mozilla.org/MPL/2.0/. } { } { 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. } { } { Copyright Eric Grange / Creative IT } { } {**************************************************************************} unit dwsJIT; {$I ../dws.inc} interface uses Classes, SysUtils, dwsExprs, dwsExprList, dwsSymbols, dwsErrors, dwsUtils, dwsCoreExprs, dwsXPlatform, dwsRelExprs, dwsMagicExprs, dwsJITFixups, dwsScriptSource, dwsJITx86Intrinsics; type DWORD = Cardinal; TdwsJIT = class; TdwsJITOption = (jitoDoStep, jitoRangeCheck, jitoNoBranchAlignment); TdwsJITOptions = set of TdwsJITOption; TdwsJITter = class (TRefCountedObject) private Fjit : TdwsJIT; protected property jit : TdwsJIT read Fjit; public constructor Create(aJIT : TdwsJIT); function IncRefCount : TdwsJITter; inline; procedure CompileStatement(expr : TExprBase); virtual; function CompileFloat(expr : TTypedExpr) : Integer; virtual; function CompileInteger(expr : TTypedExpr) : Integer; virtual; function CompileBooleanValue(expr : TTypedExpr) : Integer; virtual; procedure CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); virtual; function CompileScriptObj(expr : TTypedExpr) : Integer; virtual; procedure CompileAssignFloat(expr : TTypedExpr; source : Integer); virtual; procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); virtual; procedure CompileAssignBoolean(expr : TTypedExpr; source : Integer); virtual; end; TdwsRegisteredJITter = class (TRefCountedObject) public Expr : TClass; JIT : TdwsJITter; destructor Destroy; override; end; TdwsRegisteredJITterList = class(TSortedList<TdwsRegisteredJITter>) protected function Compare(const item1, item2 : TdwsRegisteredJITter) : Integer; override; end; IdwsJITCodeSubAllocator = interface ['{62180935-76A0-496A-A392-3BED1CAD193E}'] function Allocate(aSize : Integer) : Pointer; procedure Protect; procedure Reset; function GetNext : IdwsJITCodeSubAllocator; procedure SetNext(const aNext : IdwsJITCodeSubAllocator); property Next : IdwsJITCodeSubAllocator read GetNext write SetNext; function BlockSize : Integer; procedure RegisterFunctionTable(rtFn : Pointer); procedure DeregisterFunctionTable(rtFn : Pointer); end; TdwsJITCodeBlockFlag = ( cbfSteppable ); TdwsJITCodeBlockFlags = set of TdwsJITCodeBlockFlag; TdwsJITCodeBlock = class private FCodePtr : Pointer; FSubAllocator : IdwsJITCodeSubAllocator; FFlags : TdwsJITCodeBlockFlags; protected function GetSteppable : Boolean; inline; procedure SetSteppable(const val : Boolean); public constructor Create(const aCodePtr : Pointer; const aSubAllocator : IdwsJITCodeSubAllocator); virtual; destructor Destroy; override; function CodePtr : Pointer; inline; property SubAllocator : IdwsJITCodeSubAllocator read FSubAllocator; property Flags : TdwsJITCodeBlockFlags read FFlags; property Steppable : Boolean read GetSteppable write SetSteppable; end; TdwsJITCodeBlockClass = class of TdwsJITCodeBlock; TJITTedProgramExpr = class (TNoResultExpr) protected FCodePtr : Pointer; private FOriginal : TProgramExpr; FCodeBlock : TdwsJITCodeBlock; protected function GetSubExpr(i : Integer) : TExprBase; override; function GetSubExprCount : Integer; override; public constructor Create(original : TProgramExpr; const aCodeBlock : TdwsJITCodeBlock); virtual; destructor Destroy; override; procedure EvalNoResult(exec : TdwsExecution); override; property Original : TProgramExpr read FOriginal write FOriginal; end; TJITTedProgramExprClass = class of TJITTedProgramExpr; TJITTedTypedExpr = class (TTypedExpr) protected FCodePtr : Pointer; private FOriginal : TTypedExpr; FCodeBlock : TdwsJITCodeBlock; protected function GetSubExpr(i : Integer) : TExprBase; override; function GetSubExprCount : Integer; override; public constructor Create(original : TTypedExpr; const aCodeBlock : TdwsJITCodeBlock); virtual; destructor Destroy; override; function ScriptPos : TScriptPos; override; property Original : TTypedExpr read FOriginal write FOriginal; end; TJITTedFloatExpr = class (TJITTedTypedExpr) public procedure EvalAsVariant(exec : TdwsExecution; var Result : Variant); override; end; TJITTedFloatExprClass = class of TJITTedFloatExpr; TJITTedIntegerExpr = class (TJITTedTypedExpr) public procedure EvalAsVariant(exec : TdwsExecution; var Result : Variant); override; end; TJITTedIntegerExprClass = class of TJITTedIntegerExpr; TJITTedBooleanExpr = class (TJITTedTypedExpr) public procedure EvalAsVariant(exec : TdwsExecution; var Result : Variant); override; end; TJITTedBooleanExprClass = class of TJITTedBooleanExpr; TQueuedJITGreed = class public Next : TQueuedJITGreed; Expr : TExprBase; Prog : TdwsProgram; end; TJITLoopContext = class public TargetContinue : TFixup; TargetExit : TFixup; Exited : Boolean; Prev : TJITLoopContext; end; TdwsJIT = class private FRegistered : TdwsRegisteredJITterList; FTempReg : TdwsRegisteredJITter; FOutput : Tx86BaseWriteOnlyStream; FOutputFailedOn : TExprBase; FSeenByGreedy : TSimpleObjectHash<TSymbol>; FQueuedGreed : TQueuedJITGreed; FFixups : TFixupLogic; FLoopContext : TJITLoopContext; FExitTarget : TFixupTarget; FJITTedProgramExprClass : TJITTedProgramExprClass; FJITTedFloatExprClass : TJITTedFloatExprClass; FJITTedIntegerExprClass : TJITTedIntegerExprClass; FJITTedBooleanExprClass : TJITTedBooleanExprClass; FOptions : TdwsJITOptions; protected function CreateOutput : Tx86BaseWriteOnlyStream; virtual; function CreateFixupLogic : TFixupLogic; virtual; procedure SetOutputFailedOn(e : TExprBase); procedure StartJIT(expr : TExprBase; exitable : Boolean); virtual; procedure EndJIT; virtual; procedure EndFloatJIT(resultHandle : Integer); virtual; procedure EndIntegerJIT(resultHandle : Integer); virtual; function GetLocation : Integer; property JITTedProgramExprClass : TJITTedProgramExprClass read FJITTedProgramExprClass write FJITTedProgramExprClass; property JITTedFloatExprClass : TJITTedFloatExprClass read FJITTedFloatExprClass write FJITTedFloatExprClass; property JITTedIntegerExprClass : TJITTedIntegerExprClass read FJITTedIntegerExprClass write FJITTedIntegerExprClass; property JITTedBooleanExprClass : TJITTedBooleanExprClass read FJITTedBooleanExprClass write FJITTedBooleanExprClass; public constructor Create; virtual; destructor Destroy; override; procedure RegisterJITter(exprClass : TClass; jitter : TdwsJITter); function FindJITter(exprClass : TClass) : TdwsJITter; overload; function FindJITter(expr : TExprBase) : TdwsJITter; overload; function JITStatement(expr : TProgramExpr; exitable : Boolean) : TJITTedProgramExpr; function JITFloat(expr : TTypedExpr) : TJITTedFloatExpr; function JITInteger(expr : TTypedExpr) : TJITTedIntegerExpr; function JITBoolean(expr : TTypedExpr) : TJITTedBooleanExpr; procedure CompileStatement(expr : TExprBase); function CompileFloat(expr : TTypedExpr) : Integer; function CompileInteger(expr : TTypedExpr) : Integer; function CompileBooleanValue(expr : TTypedExpr) : Integer; procedure CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); function CompileScriptObj(expr : TTypedExpr) : Integer; function CompileScriptDynArray(expr : TTypedExpr) : Integer; procedure CompileAssignFloat(expr : TTypedExpr; source : Integer); procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); procedure CompileAssignBoolean(expr : TTypedExpr; source : Integer); function IsFloat(expr : TTypedExpr) : Boolean; overload; inline; function IsFloat(typ : TTypeSymbol) : Boolean; overload; function IsInteger(expr : TTypedExpr) : Boolean; overload; function IsInteger(typ : TTypeSymbol) : Boolean; overload; function IsBoolean(expr : TTypedExpr) : Boolean; overload; function IsDynamicArray(expr : TTypedExpr) : Boolean; overload; function IsInterface(expr : TTypedExpr) : Boolean; overload; property LoopContext : TJITLoopContext read FLoopContext; property ExitTarget : TFixupTarget read FExitTarget; procedure EnterLoop(targetContinue, targetExit : TFixup); procedure LeaveLoop; property Fixups : TFixupLogic read FFixups; property Options : TdwsJITOptions read FOptions write FOptions; function CompiledOutput : TdwsJITCodeBlock; virtual; abstract; procedure Clear; procedure GreedyJIT(expr : TExprBase); overload; procedure GreedyJIT(prog : TdwsProgram); overload; procedure GreedyJITParameters(funcExpr : TFuncExprBase); procedure DeQueueGreed; procedure QueueGreed(expr : TExprBase); overload; procedure QueueGreed(prog : TdwsProgram); overload; property Output : Tx86BaseWriteOnlyStream read FOutput; property OutputFailedOn : TExprBase read FOutputFailedOn write SetOutputFailedOn; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------ // ------------------ TdwsJITter ------------------ // ------------------ // Create // constructor TdwsJITter.Create(aJIT : TdwsJIT); begin Fjit:=aJIT; end; // IncRefCount // function TdwsJITter.IncRefCount : TdwsJITter; begin inherited IncRefCount; Result:=Self; end; // CompileFloat // function TdwsJITter.CompileFloat(expr : TTypedExpr) : Integer; begin jit.OutputFailedOn:=expr; Result:=0; end; // CompileInteger // function TdwsJITter.CompileInteger(expr : TTypedExpr) : Integer; begin jit.OutputFailedOn:=expr; Result:=0; end; // CompileBooleanValue // function TdwsJITter.CompileBooleanValue(expr : TTypedExpr) : Integer; begin jit.OutputFailedOn:=expr; Result:=0; end; // CompileBoolean // procedure TdwsJITter.CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); begin jit.OutputFailedOn:=expr; end; // CompileScriptObj // function TdwsJITter.CompileScriptObj(expr : TTypedExpr) : Integer; begin jit.OutputFailedOn:=expr; Result:=0; end; // CompileAssignFloat // procedure TdwsJITter.CompileAssignFloat(expr : TTypedExpr; source : Integer); begin jit.OutputFailedOn:=expr; end; // CompileAssignInteger // procedure TdwsJITter.CompileAssignInteger(expr : TTypedExpr; source : Integer); begin jit.OutputFailedOn:=expr; end; // CompileAssignBoolean // procedure TdwsJITter.CompileAssignBoolean(expr : TTypedExpr; source : Integer); begin jit.OutputFailedOn:=expr; end; // CompileStatement // procedure TdwsJITter.CompileStatement(expr : TExprBase); begin jit.OutputFailedOn:=expr; end; // ------------------ // ------------------ TdwsRegisteredJITter ------------------ // ------------------ // Destroy // destructor TdwsRegisteredJITter.Destroy; begin inherited; JIT.Free; end; // ------------------ // ------------------ TdwsRegisteredJITterList ------------------ // ------------------ // Compare // function TdwsRegisteredJITterList.Compare(const item1, item2 : TdwsRegisteredJITter) : Integer; var i1, i2 : Integer; begin i1:=NativeInt(item1.Expr); i2:=NativeInt(item2.Expr); if i1<i2 then Result:=-1 else if i1=i2 then Result:=0 else Result:=1; end; // ------------------ // ------------------ TdwsJITCodeBlock ------------------ // ------------------ // Create // constructor TdwsJITCodeBlock.Create(const aCodePtr : Pointer; const aSubAllocator : IdwsJITCodeSubAllocator); begin inherited Create; FCodePtr := aCodePtr; FSubAllocator := aSubAllocator; end; // Free // destructor TdwsJITCodeBlock.Destroy; begin FCodePtr := nil; FSubAllocator := nil; inherited; end; // CodePtr // function TdwsJITCodeBlock.CodePtr : Pointer; begin Result := FCodePtr; end; // GetSteppable // function TdwsJITCodeBlock.GetSteppable : Boolean; begin Result := cbfSteppable in FFlags; end; // SetSteppable // procedure TdwsJITCodeBlock.SetSteppable(const val : Boolean); begin Include(FFlags, cbfSteppable); end; // ------------------ // ------------------ TdwsJITter ------------------ // ------------------ // Create // constructor TdwsJIT.Create; begin inherited; FRegistered:=TdwsRegisteredJITterList.Create; FTempReg:=TdwsRegisteredJITter.Create; FOutput:=CreateOutput; FSeenByGreedy:=TSimpleObjectHash<TSymbol>.Create; FFixups:=CreateFixupLogic; FFixups.OnNeedLocation:=GetLocation; end; // Destroy // destructor TdwsJIT.Destroy; begin inherited; FFixups.Free; FRegistered.Clean; FRegistered.Free; FTempReg.Free; FOutput.Free; FSeenByGreedy.Free; end; // CreateOutput // function TdwsJIT.CreateOutput : Tx86BaseWriteOnlyStream; begin Result:=Tx86_Platform_WriteOnlyStream.Create; end; // CreateFixupLogic // function TdwsJIT.CreateFixupLogic : TFixupLogic; begin Result:=TFixupLogic.Create; end; // SetOutputFailedOn // procedure TdwsJIT.SetOutputFailedOn(e : TExprBase); begin FOutputFailedOn := e; if e <> nil then OutputDebugString(e.ClassName) else OutputDebugString('nil'); end; // RegisterJITter // procedure TdwsJIT.RegisterJITter(exprClass : TClass; jitter : TdwsJITter); var reg : TdwsRegisteredJITter; begin reg:=TdwsRegisteredJITter.Create; reg.Expr:=exprClass; reg.JIT:=jitter; FRegistered.Add(reg); end; // FindJITter // function TdwsJIT.FindJITter(exprClass : TClass) : TdwsJITter; var i : Integer; begin if exprClass.InheritsFrom(TJITTedProgramExpr) then FTempReg.Expr:=exprClass; FTempReg.Expr:=exprClass; if FRegistered.Find(FTempReg, i) then Result:=FRegistered.Items[i].JIT else Result := nil; end; // FindJITter // function TdwsJIT.FindJITter(expr : TExprBase) : TdwsJITter; begin Result:=FindJITter(expr.ClassType); end; // JITStatement // function TdwsJIT.JITStatement(expr : TProgramExpr; exitable : Boolean) : TJITTedProgramExpr; var jit : TdwsJITter; begin Result:=nil; jit:=FindJITter(expr); if jit=nil then begin OutputDebugString(expr.ClassName); Exit; end; StartJIT(expr, exitable); jit.CompileStatement(expr); EndJIT; if OutputFailedOn=nil then Result := JITTedProgramExprClass.Create(expr, CompiledOutput) else begin OutputDebugString(OutputFailedOn.ClassName); GreedyJIT(expr); end; end; // JITFloat // function TdwsJIT.JITFloat(expr : TTypedExpr) : TJITTedFloatExpr; var outcome : Integer; begin Result:=nil; StartJIT(expr, False); outcome:=CompileFloat(expr); EndFloatJIT(outcome); if (OutputFailedOn=nil) then Result:=JITTedFloatExprClass.Create(expr, CompiledOutput) else OutputDebugString(OutputFailedOn.ClassName); end; // JITInteger // function TdwsJIT.JITInteger(expr : TTypedExpr) : TJITTedIntegerExpr; var outcome : Integer; begin Result:=nil; StartJIT(expr, False); outcome:=CompileInteger(expr); EndIntegerJIT(outcome); if (OutputFailedOn=nil) then Result:=JITTedIntegerExprClass.Create(expr, CompiledOutput) else OutputDebugString(OutputFailedOn.ClassName); end; // JITBoolean // function TdwsJIT.JITBoolean(expr : TTypedExpr) : TJITTedBooleanExpr; var outcome : Integer; begin Result := nil; StartJIT(expr, False); outcome := CompileBooleanValue(expr); EndIntegerJIT(outcome); if OutputFailedOn = nil then Result := JITTedBooleanExprClass.Create(expr, CompiledOutput) else OutputDebugString(OutputFailedOn.ClassName); end; // CompileStatement // procedure TdwsJIT.CompileStatement(expr : TExprBase); var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit<>nil then jit.CompileStatement(expr) else OutputFailedOn:=expr; end; // CompileFloat // function TdwsJIT.CompileFloat(expr : TTypedExpr) : Integer; var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then begin OutputFailedOn:=expr; Result:=0; end else begin Result:=jit.CompileFloat(expr); end; end; // CompileInteger // function TdwsJIT.CompileInteger(expr : TTypedExpr) : Integer; var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then begin OutputFailedOn:=expr; Result:=0; end else begin Result:=jit.CompileInteger(expr); end; end; // CompileBooleanValue // function TdwsJIT.CompileBooleanValue(expr : TTypedExpr) : Integer; var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then begin OutputFailedOn:=expr; Result:=0; end else Result:=jit.CompileBooleanValue(expr); end; // CompileBoolean // procedure TdwsJIT.CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then OutputFailedOn:=expr else jit.CompileBoolean(expr, targetTrue, targetFalse); end; // CompileScriptObj // function TdwsJIT.CompileScriptObj(expr : TTypedExpr) : Integer; var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then begin OutputFailedOn:=expr; Result:=0; end else Result:=jit.CompileScriptObj(expr); end; // CompileScriptDynArray // function TdwsJIT.CompileScriptDynArray(expr : TTypedExpr) : Integer; var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then begin OutputFailedOn:=expr; Result:=0; end else Result:=jit.CompileScriptObj(expr); end; // CompileAssignFloat // procedure TdwsJIT.CompileAssignFloat(expr : TTypedExpr; source : Integer); var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then OutputFailedOn:=expr else jit.CompileAssignFloat(expr, source); end; // CompileAssignInteger // procedure TdwsJIT.CompileAssignInteger(expr : TTypedExpr; source : Integer); var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then OutputFailedOn:=expr else jit.CompileAssignInteger(expr, source); end; // CompileAssignBoolean // procedure TdwsJIT.CompileAssignBoolean(expr : TTypedExpr; source : Integer); var jit : TdwsJITter; begin jit:=FindJITter(expr); if jit=nil then OutputFailedOn:=expr else jit.CompileAssignBoolean(expr, source); end; // IsFloat // function TdwsJIT.IsFloat(expr : TTypedExpr) : Boolean; begin Result:=IsFloat(expr.Typ); end; // IsFloat // function TdwsJIT.IsFloat(typ : TTypeSymbol) : Boolean; begin Result:=(typ.UnAliasedType.ClassType=TBaseFloatSymbol); end; // IsInteger // function TdwsJIT.IsInteger(expr : TTypedExpr) : Boolean; begin Result:=(expr.Typ.UnAliasedType.ClassType=TBaseIntegerSymbol); end; // IsInteger // function TdwsJIT.IsInteger(typ : TTypeSymbol) : Boolean; begin Result:=(typ.UnAliasedType.ClassType=TBaseIntegerSymbol); end; // IsBoolean // function TdwsJIT.IsBoolean(expr : TTypedExpr) : Boolean; begin Result:=(expr.Typ.UnAliasedType.ClassType=TBaseBooleanSymbol); end; // IsDynamicArray // function TdwsJIT.IsDynamicArray(expr : TTypedExpr) : Boolean; var ct : TClass; begin ct := expr.Typ.UnAliasedType.ClassType; Result := (ct = TDynamicArraySymbol); end; // IsInterface // function TdwsJIT.IsInterface(expr : TTypedExpr) : Boolean; var ct : TClass; begin ct := expr.Typ.UnAliasedType.ClassType; Result := (ct = TClassSymbol) or (ct = TDynamicArraySymbol) or (ct = TInterfaceSymbol); end; // EnterLoop // procedure TdwsJIT.EnterLoop(targetContinue, targetExit : TFixup); var context : TJITLoopContext; begin context:=TJITLoopContext.Create; context.TargetContinue:=targetContinue; context.TargetExit:=targetExit; context.Prev:=FLoopContext; FLoopContext:=context; end; // LeaveLoop // procedure TdwsJIT.LeaveLoop; var context : TJITLoopContext; begin context:=FLoopContext; FLoopContext:=context.Prev; context.Free; end; // StartJIT // procedure TdwsJIT.StartJIT(expr : TExprBase; exitable : Boolean); begin FOutput.Clear; FOutputFailedOn:=nil; if exitable then FExitTarget:=Fixups.NewHangingTarget(False); end; // EndJIT // procedure TdwsJIT.EndJIT; begin if FExitTarget<>nil then begin Fixups.AddFixup(FExitTarget); FExitTarget:=nil; end; // nothing end; // EndFloatJIT // procedure TdwsJIT.EndFloatJIT(resultHandle : Integer); begin EndJIT; end; // EndIntegerJIT // procedure TdwsJIT.EndIntegerJIT(resultHandle : Integer); begin EndJIT; end; // GetLocation // function TdwsJIT.GetLocation : Integer; begin Result:=Output.Position; end; // Clear // procedure TdwsJIT.Clear; begin FSeenByGreedy.Clear; end; // GreedyJIT // procedure TdwsJIT.GreedyJIT(expr : TExprBase); var i : Integer; block : TBlockExprBase; subExpr : TExprBase; statementJIT : TJITTedProgramExpr; floatJIT : TJITTedFloatExpr; funcSym : TFuncSymbol; funcExpr : TFuncExprBase; executable : IExecutable; execObject : TObject; assignExpr : TAssignExpr; composite : TCompositeTypeSymbol; begin if expr is TBlockExprBase then begin block:=TBlockExprBase(expr); for i:=0 to block.SubExprCount-1 do begin subExpr:=block.SubExpr[i]; if subExpr is TFuncExprBase then GreedyJIT(subExpr) else if subExpr is TProgramExpr then begin statementJIT:=JITStatement(TProgramExpr(subExpr), False); if statementJIT<>nil then begin block.ReplaceStatement(i, statementJIT); continue; end; GreedyJIT(subExpr); end; end; end else if expr.ClassType=TAssignExpr then begin assignExpr:=TAssignExpr(expr); if assignExpr.Left.Typ.UnAliasedType.ClassType=TBaseFloatSymbol then begin floatJIT:=JITFloat(assignExpr.Right); if floatJIT<>nil then begin assignExpr.Right.Free; assignExpr.Right:=floatJIT; end; end; end else if expr is TFuncExprBase then begin funcExpr:=TFuncExprBase(expr); funcSym:=funcExpr.FuncSym; if (funcSym is TSourceFuncSymbol) and not FSeenByGreedy.Contains(funcSym) then begin FSeenByGreedy.Add(funcSym); executable:=funcSym.Executable; if executable<>nil then begin execObject:=executable.GetSelf; if execObject is TdwsProgram then QueueGreed(TdwsProgram(execObject)); end; end else if funcSym is TSourceMethodSymbol then begin composite:=TSourceMethodSymbol(funcSym).StructSymbol; while (composite<>nil) and not FSeenByGreedy.Contains(composite) do begin FSeenByGreedy.Add(composite); for i:=0 to composite.Members.Count-1 do begin if composite.Members[i] is TSourceMethodSymbol then begin funcSym:=TSourceMethodSymbol(composite.Members[i]); executable:=funcSym.Executable; if executable<>nil then begin execObject:=executable.GetSelf; if execObject is TdwsProgram then QueueGreed(TdwsProgram(execObject)); end; end; end; composite:=composite.Parent; end; end; GreedyJITParameters(funcExpr); end else begin for i:=0 to expr.SubExprCount-1 do begin subExpr:=expr.SubExpr[i]; if subExpr<>nil then GreedyJIT(subExpr); end; end; end; // GreedyJITParameters // procedure TdwsJIT.GreedyJITParameters(funcExpr : TFuncExprBase); var i : Integer; jitted : TJITTedTypedExpr; funcSym : TFuncSymbol; p : TParamSymbol; paramTyp : TTypeSymbol; argExpr : TExprBase; begin funcSym := funcExpr.FuncSym; if funcSym = nil then Exit; if funcExpr is TMagicFuncExpr then begin for i := 0 to funcExpr.Args.Count-1 do begin p:=funcSym.Params[i]; if p.ClassType<>TParamSymbol then continue; argExpr:=funcExpr.Args[i]; if not (argExpr is TJITTedTypedExpr) then begin paramTyp := p.Typ.UnAliasedType; if paramTyp is TBaseIntegerSymbol then jitted := JITInteger(argExpr as TTypedExpr) else if paramTyp is TBaseFloatSymbol then jitted := JITFloat(argExpr as TTypedExpr) else if paramTyp is TBaseBooleanSymbol then jitted := JITBoolean(argExpr as TTypedExpr) else jitted := nil; if jitted <> nil then begin funcExpr.Args[i].Free; funcExpr.Args[i] := jitted; end else GreedyJIT(argExpr); end; end; end else begin for i := 0 to funcExpr.SubExprCount-1 do begin argExpr := funcExpr.SubExpr[i]; if argExpr is TFuncExprBase then QueueGreed(argExpr); end; end; end; // DeQueueGreed // procedure TdwsJIT.DeQueueGreed; var greed : TQueuedJITGreed; begin while FQueuedGreed<>nil do begin greed:=FQueuedGreed; FQueuedGreed:=greed.Next; try if greed.Expr<>nil then GreedyJIT(greed.Expr) else GreedyJIT(greed.Prog); finally greed.Free; end; end; end; // QueueGreed // procedure TdwsJIT.QueueGreed(expr : TExprBase); var greed : TQueuedJITGreed; begin greed:=TQueuedJITGreed.Create; greed.Expr:=expr; greed.Next:=FQueuedGreed; FQueuedGreed:=greed; end; // QueueGreed // procedure TdwsJIT.QueueGreed(prog : TdwsProgram); var greed : TQueuedJITGreed; begin greed:=TQueuedJITGreed.Create; greed.Prog:=prog; greed.Next:=FQueuedGreed; FQueuedGreed:=greed; end; // GreedyJIT // procedure TdwsJIT.GreedyJIT(prog : TdwsProgram); var i : Integer; initStatement : TExprBase; statementJIT : TJITTedProgramExpr; begin for i := 0 to prog.InitExpr.StatementCount-1 do begin initStatement := prog.InitExpr.SubExpr[i]; if initStatement is TBlockExpr then begin statementJIT := JITStatement(TBlockExpr(initStatement), True); if statementJIT <> nil then prog.InitExpr.ReplaceStatement(i, statementJIT); end; end; if prog.Expr is TProgramExpr then begin statementJIT := JITStatement(TProgramExpr(prog.Expr), True); if statementJIT <> nil then begin prog.Expr.Free; prog.Expr:=statementJIT; end; end; DeQueueGreed; end; // ------------------ // ------------------ TJITTedProgramExpr ------------------ // ------------------ // Create // constructor TJITTedProgramExpr.Create(original : TProgramExpr; const aCodeBlock : TdwsJITCodeBlock); begin inherited Create(original.ScriptPos); FCodeBlock := aCodeBlock; FCodePtr := aCodeBlock.CodePtr; FOriginal := original; FOriginal.IncRefCount; end; // Destroy // destructor TJITTedProgramExpr.Destroy; begin inherited; FOriginal.Free; FCodeBlock.Free; end; // EvalNoResult // procedure TJITTedProgramExpr.EvalNoResult(exec : TdwsExecution); begin FOriginal.EvalNoResult(exec); end; // GetSubExpr // function TJITTedProgramExpr.GetSubExpr(i : Integer) : TExprBase; begin Result:=FOriginal.SubExpr[i]; end; // GetSubExprCount // function TJITTedProgramExpr.GetSubExprCount : Integer; begin if FCodeBlock.Steppable then Result:=FOriginal.SubExprCount else Result:=0; end; // ------------------ // ------------------ TJITTedTypedExpr ------------------ // ------------------ // Create // constructor TJITTedTypedExpr.Create(original : TTypedExpr; const aCodeBlock : TdwsJITCodeBlock); begin inherited Create; FCodeBlock := aCodeBlock; FCodePtr := aCodeBlock.CodePtr; FOriginal:=original; FOriginal.IncRefCount; end; // Destroy // destructor TJITTedTypedExpr.Destroy; begin inherited; FOriginal.Free; FCodeBlock.Free; end; // ScriptPos // function TJITTedTypedExpr.ScriptPos : TScriptPos; begin Result:=Original.ScriptPos; end; // GetSubExpr // function TJITTedTypedExpr.GetSubExpr(i : Integer) : TExprBase; begin Result:=FOriginal.SubExpr[i]; end; // GetSubExprCount // function TJITTedTypedExpr.GetSubExprCount : Integer; begin if FCodeBlock.Steppable then Result:=FOriginal.SubExprCount else Result:=0; end; // ------------------ // ------------------ TJITTedFloatExpr ------------------ // ------------------ // EvalAsVariant // procedure TJITTedFloatExpr.EvalAsVariant(exec : TdwsExecution; var Result : Variant); begin result:=EvalAsFloat(exec); end; // ------------------ // ------------------ TJITTedIntegerExpr ------------------ // ------------------ // EvalAsVariant // procedure TJITTedIntegerExpr.EvalAsVariant(exec : TdwsExecution; var Result : Variant); begin Result:=EvalAsInteger(exec); end; // ------------------ // ------------------ TJITTedBooleanExpr ------------------ // ------------------ // EvalAsVariant // procedure TJITTedBooleanExpr.EvalAsVariant(exec : TdwsExecution; var Result : Variant); begin Result := EvalAsBoolean(exec); end; end.
412
0.799349
1
0.799349
game-dev
MEDIA
0.28196
game-dev
0.821231
1
0.821231
MohistMC/Youer
3,516
src/main/java/io/papermc/paper/configuration/mapping/InnerClassInstanceSupplier.java
package io.papermc.paper.configuration.mapping; import com.mohistmc.org.spongepowered.configurate.serialize.SerializationException; import com.mohistmc.org.spongepowered.configurate.util.CheckedFunction; import com.mohistmc.org.spongepowered.configurate.util.CheckedSupplier; import io.papermc.paper.configuration.ConfigurationPart; import java.lang.reflect.AnnotatedType; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.Nullable; import static com.mohistmc.io.leangen.geantyref.GenericTypeReflector.erase; /** * This instance factory handles creating non-static inner classes by tracking all instances of objects that extend * {@link ConfigurationPart}. Only 1 instance of each {@link ConfigurationPart} should be present for each instance * of the field discoverer this is used in. */ final class InnerClassInstanceSupplier implements CheckedFunction<AnnotatedType, @Nullable Supplier<Object>, SerializationException> { private final Map<Class<?>, Object> instanceMap = new HashMap<>(); private final Map<Class<?>, Object> initialOverrides; /** * @param initialOverrides map of types to objects to preload the config objects with. */ InnerClassInstanceSupplier(final Map<Class<?>, Object> initialOverrides) { this.initialOverrides = initialOverrides; } @Override public Supplier<Object> apply(final AnnotatedType target) throws SerializationException { final Class<?> type = erase(target.getType()); if (this.initialOverrides.containsKey(type)) { this.instanceMap.put(type, this.initialOverrides.get(type)); return () -> this.initialOverrides.get(type); } if (ConfigurationPart.class.isAssignableFrom(type) && !this.instanceMap.containsKey(type)) { try { final Constructor<?> constructor; final CheckedSupplier<Object, ReflectiveOperationException> instanceSupplier; if (type.getEnclosingClass() != null && !Modifier.isStatic(type.getModifiers())) { final @Nullable Object instance = this.instanceMap.get(type.getEnclosingClass()); if (instance == null) { throw new SerializationException("Cannot create a new instance of an inner class " + type.getName() + " without an instance of its enclosing class " + type.getEnclosingClass().getName()); } constructor = type.getDeclaredConstructor(type.getEnclosingClass()); instanceSupplier = () -> constructor.newInstance(instance); } else { constructor = type.getDeclaredConstructor(); instanceSupplier = constructor::newInstance; } constructor.setAccessible(true); final Object instance = instanceSupplier.get(); this.instanceMap.put(type, instance); return () -> instance; } catch (ReflectiveOperationException e) { throw new SerializationException(ConfigurationPart.class, target + " must be a valid ConfigurationPart", e); } } else { throw new SerializationException(target + " must be a valid ConfigurationPart"); } } Map<Class<?>, Object> instanceMap() { return this.instanceMap; } }
412
0.90022
1
0.90022
game-dev
MEDIA
0.302154
game-dev
0.968904
1
0.968904
GrognardsFromHell/TemplePlus
2,607
tpdatasrc/co8fixes/scr/py00070furnok.py
from toee import * from utilities import * from combat_standard_routines import * def san_dialog( attachee, triggerer ): if (game.leader.reputation_has(32) == 1 or game.leader.reputation_has(30) == 1 or game.leader.reputation_has(29) == 1): attachee.float_line(11004,triggerer) elif (game.global_flags[61] == 1): triggerer.begin_dialog( attachee, 500 ) elif (attachee.leader_get() != OBJ_HANDLE_NULL): triggerer.begin_dialog( attachee, 300 ) elif (game.global_flags[51] == 1): if (game.quests[18].state == qs_completed): triggerer.begin_dialog( attachee, 220 ) else: triggerer.begin_dialog( attachee, 210 ) else: triggerer.begin_dialog( attachee, 1 ) return SKIP_DEFAULT def san_first_heartbeat( attachee, triggerer ): if (attachee.leader_get() == OBJ_HANDLE_NULL): if (game.global_vars[501] == 4 or game.global_vars[501] == 5 or game.global_vars[501] == 6 or game.global_vars[510] == 2): attachee.object_flag_set(OF_OFF) else: attachee.object_flag_unset(OF_OFF) return RUN_DEFAULT def san_dying( attachee, triggerer ): if should_modify_CR( attachee ): modify_CR( attachee, get_av_level() ) game.global_flags[58] = 1 attachee.float_line(12014,triggerer) if (game.global_flags[235] == 0): game.global_vars[23] = game.global_vars[23] + 1 if (game.global_vars[23] >= 2): game.party[0].reputation_add( 92 ) else: game.global_vars[29] = game.global_vars[29] + 1 return RUN_DEFAULT def san_resurrect( attachee, triggerer ): game.global_flags[58] = 0 return RUN_DEFAULT def san_join( attachee, triggerer ): game.global_flags[235] = 1 ring = attachee.item_find( 6088 ) if (ring != OBJ_HANDLE_NULL): ring.item_flag_set(OIF_NO_TRANSFER) dagger = attachee.item_find( 4058 ) if (dagger != OBJ_HANDLE_NULL): dagger.item_flag_set(OIF_NO_TRANSFER) return RUN_DEFAULT def san_disband( attachee, triggerer ): game.global_flags[235] = 0 ring = attachee.item_find( 6088 ) if (ring != OBJ_HANDLE_NULL): ring.item_flag_unset(OIF_NO_TRANSFER) dagger = attachee.item_find( 4058 ) if (dagger != OBJ_HANDLE_NULL): dagger.item_flag_unset(OIF_NO_TRANSFER) for pc in game.party: attachee.ai_shitlist_remove( pc ) attachee.reaction_set( pc, 50 ) return RUN_DEFAULT def san_new_map( attachee, triggerer ): if ((attachee.area == 2) or (attachee.area == 4)): game.global_flags[60] = 1 elif ((attachee.area == 1) and (game.global_flags[60] == 1)): game.global_flags[60] = 0 if (attachee.money_get() >= 200000): leader = attachee.leader_get() if (leader != OBJ_HANDLE_NULL): leader.begin_dialog(attachee, 400) return RUN_DEFAULT
412
0.796187
1
0.796187
game-dev
MEDIA
0.964747
game-dev
0.876686
1
0.876686
sk7725/BetaMindy
1,876
src/betamindy/world/blocks/defense/StatusWall.java
package betamindy.world.blocks.defense; import arc.*; import arc.util.*; import betamindy.content.*; import mindustry.entities.*; import mindustry.entities.bullet.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.blocks.defense.*; import mindustry.world.meta.*; import static mindustry.Vars.tilesize; public class StatusWall extends Wall { public StatusEffect status = MindyStatusEffects.icy; public float statusDuration = 600f; public Effect shotEffect = MindyFx.spike; public BulletType puddle = MindyBullets.icyZone; public StatusWall(String name){ super(name); } @Override public void setStats(){ super.setStats(); stats.add(Stat.abilities, table -> { table.image(status.uiIcon).size(18f); table.add(" [accent]" + status.localizedName + "[] " + (int)(statusDuration / 60) + " " + Core.bundle.get("unit.seconds")); }); } public class StatusWallBuild extends WallBuild { public void reactTo(Unit unit){ unit.apply(status, statusDuration); float angle = angleTo(unit); Tmp.v1.trns(angle, size * tilesize / 2f).add(this); shotEffect.at(Tmp.v1.x, Tmp.v1.y, angle, status.color); } @Override public void onDestroyed(){ if(destroyEffect != null) destroyEffect.at(this); puddle.create(this, x, y, 0f); super.onDestroyed(); } @Override public boolean collision(Bullet bullet){ if(bullet.team != team && (bullet.owner instanceof Unit)) reactTo((Unit)bullet.owner); return super.collision(bullet); } @Override public void drawLight(){ super.drawLight(); Drawf.light(x, y, 16f * size, status.color, 0.2f); } } }
412
0.856271
1
0.856271
game-dev
MEDIA
0.867396
game-dev
0.93817
1
0.93817
SMGCommunity/Petari
3,829
src/Game/Boss/TripodBossKillerGeneraterCircle.cpp
#include "Game/Boss/TripodBossKillerGeneraterCircle.hpp" #include "Game/Boss/TripodBossKillerGenerator.hpp" #include "JSystem/JGeometry/TMatrix.hpp" struct GeneratorCircleData { const char* mName; // 0x00 const f32* mAngleTable; // 0x04 s32 mNumAngles; // 0x08 f32 _C; f32 _10; f32 _14; f32 _18; u32 mActiveLabel; // 0x1C bool mHasCollision; // 0x20 }; namespace { static f32 sUpperHorizonAngleTable[7] = { 42.0f, 96.0f, 140.0f, 180.0f, -140.0f, -96.0f, -42.0f }; static f32 sUnderHorizonAngleTable[6] = { 78.0f, 120.0f, 160.0f, -160.0f, -120.0f, -78.0f }; static f32 sBottomHorizonAngleTable[3] = { 0.0f, 120.0f, 240.0f }; static const GeneratorCircleData sSetUpDataTable[3] = { { "TripodBossUpperKillerCannon", sUpperHorizonAngleTable, 7, 2150.0f, 49.0f, -29.0f, 975.0f, 1, 0x1000000 }, { "TripodBossUnderKillerCannon", sUnderHorizonAngleTable, 6, 2150.0f,5.8000002f, 39.200001f, 975.0f, 0, 0x1000000 }, { "TripodBossBottomKillerCannon", sBottomHorizonAngleTable, 3, 500.0f, -50.0f, -30.0f, -1300.0f, 0, 0 } }; const GeneratorCircleData* getCirlceData(const char *pName) { for (u32 i = 0; i < 3; i++) { if (MR::isEqualString(pName, sSetUpDataTable[i].mName)) { return &sSetUpDataTable[i]; } } return nullptr; } }; TripodBossKillerGeneraterCircle::~TripodBossKillerGeneraterCircle() { } TripodBossKillerGeneraterCircle::TripodBossKillerGeneraterCircle(const char *pName) : NameObj(pName) { mGenerators = nullptr; mPosition.x = 0.0f; mPosition.y = 0.0f; mPosition.z = 0.0f; mAngleTable = nullptr; mNumAngles = 0; _30 = 0.0f; _34 = 0.0f; _38 = 0.0f; _3C = 0.0f; _40 = 0; } void TripodBossKillerGeneraterCircle::init(const JMapInfoIter &rIter) { const char* objName; MR::getObjectName(&objName, rIter); const GeneratorCircleData* dataPtr = getCirlceData(objName); MR::getJMapInfoTrans(rIter, &mPosition); MR::getJMapInfoRotate(rIter, &mRotation); mAngleTable = dataPtr->mAngleTable; mNumAngles = dataPtr->mNumAngles; _34 = dataPtr->_C; _38 = dataPtr->_10; _3C = dataPtr->_14; _30 = dataPtr->_18; mGenerators = new TripodBossKillerGenerater[mNumAngles]; for (s32 i = 0; i < mNumAngles; i++) { mGenerators[i].setActiveLebel(dataPtr->mActiveLabel); mGenerators[i].setHasCollision(dataPtr->mHasCollision); mGenerators[i].init(rIter); } placementGenerater(); } // https://decomp.me/scratch/kbnGV void TripodBossKillerGeneraterCircle::placementGenerater() { for (s32 i = 0; i < mNumAngles; i++) { TPos3f mtx; mtx.identity(); f32 v5 = -(0.017453292f * _3C); f32 v6 = sin(v5); f32 v7 = cos(v5); mtx.mMtx[0][0] = 1.0f; mtx.mMtx[2][1] = v6; mtx.mMtx[1][1] = v7; mtx.mMtx[1][2] = -v6; mtx.mMtx[2][2] = v7; mtx.mMtx[2][0] = 0.0f; mtx.mMtx[0][2] = 0.0f; mtx.mMtx[1][0] = 0.0f; mtx.mMtx[0][1] = 0.0f; // might be a fake temp, as it causes regswaps, but is the only way i found to get // the load in the correct position f32 temp = _34; mtx.mMtx[0][3] = 0.0f; mtx.mMtx[1][3] = 0.0f; mtx.mMtx[2][3] = temp; TPos3f mtx2; mtx2.identity(); mtx2.someInlineMatrixFunction(mAngleTable[i], _38); mtx2.concat(mtx2, mtx); TVec3f v18(0.0f, _30, 0.0f); MR::addTransMtx(mtx2, v18); TPos3f trMtx; MR::makeMtxTR(trMtx, mPosition, mRotation); mtx2.concat(trMtx, mtx2); mGenerators[i].setLocalMatrix(mtx2); } }
412
0.861165
1
0.861165
game-dev
MEDIA
0.484403
game-dev,scientific-computing
0.951319
1
0.951319
facebookresearch/habitat-sim
1,860
src/esp/physics/bullet/BulletArticulatedLink.h
// Copyright (c) Meta Platforms, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #ifndef ESP_PHYSICS_BULLET_BULLETARTICULATEDLINK_H_ #define ESP_PHYSICS_BULLET_BULLETARTICULATEDLINK_H_ #include "../ArticulatedLink.h" #include "BulletBase.h" #include "objectWrappers/ManagedBulletArticulatedObject.h" namespace esp { namespace physics { class ManagedBulletArticulatedObject; //////////////////////////////////// // Link //////////////////////////////////// class BulletArticulatedLink : public ArticulatedLink, public BulletBase { public: BulletArticulatedLink(scene::SceneNode* bodyNode, const assets::ResourceManager& resMgr, std::shared_ptr<btMultiBodyDynamicsWorld> bWorld, int index, std::shared_ptr<std::map<const btCollisionObject*, int>> collisionObjToObjIds) : ArticulatedLink(bodyNode, index, resMgr), BulletBase(std::move(bWorld), std::move(collisionObjToObjIds)) {} Magnum::Range3D getCollisionShapeAabb() const override { // TODO: collision object should be linked here ESP_WARNING() << "Not implemented."; return Magnum::Range3D(); } //! link can't do this. void setMotionType(CORRADE_UNUSED MotionType mt) override { ESP_WARNING() << "Cannot set MotionType individually for links."; } std::shared_ptr<ManagedBulletArticulatedObject> getOwningManagedBulletAO() const { return ArticulatedLink::getOwningManagedAOInternal< ManagedBulletArticulatedObject>(); } protected: int mbIndex_; private: ESP_SMART_POINTERS(BulletArticulatedLink) }; } // namespace physics } // namespace esp #endif // ESP_PHYSICS_BULLET_BULLETARTICULATEDLINK_H_
412
0.89842
1
0.89842
game-dev
MEDIA
0.971954
game-dev
0.546615
1
0.546615
erwincoumans/experiments
4,072
bullet2/BulletCollision/CollisionShapes/btCapsuleShape.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 "btCapsuleShape.h" #include "BulletCollision/CollisionShapes/btCollisionMargin.h" #include "LinearMath/btQuaternion.h" btCapsuleShape::btCapsuleShape(btScalar radius, btScalar height) : btConvexInternalShape () { m_shapeType = CAPSULE_SHAPE_PROXYTYPE; m_upAxis = 1; m_implicitShapeDimensions.setValue(radius,0.5f*height,radius); } btVector3 btCapsuleShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const { btVector3 supVec(0,0,0); btScalar maxDot(btScalar(-BT_LARGE_FLOAT)); btVector3 vec = vec0; btScalar lenSqr = vec.length2(); if (lenSqr < btScalar(0.0001)) { vec.setValue(1,0,0); } else { btScalar rlen = btScalar(1.) / btSqrt(lenSqr ); vec *= rlen; } btVector3 vtx; btScalar newDot; btScalar radius = getRadius(); { btVector3 pos(0,0,0); pos[getUpAxis()] = getHalfHeight(); vtx = pos +vec*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) { maxDot = newDot; supVec = vtx; } } { btVector3 pos(0,0,0); pos[getUpAxis()] = -getHalfHeight(); vtx = pos +vec*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) { maxDot = newDot; supVec = vtx; } } return supVec; } void btCapsuleShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { btScalar radius = getRadius(); for (int j=0;j<numVectors;j++) { btScalar maxDot(btScalar(-BT_LARGE_FLOAT)); const btVector3& vec = vectors[j]; btVector3 vtx; btScalar newDot; { btVector3 pos(0,0,0); pos[getUpAxis()] = getHalfHeight(); vtx = pos +vec*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) { maxDot = newDot; supportVerticesOut[j] = vtx; } } { btVector3 pos(0,0,0); pos[getUpAxis()] = -getHalfHeight(); vtx = pos +vec*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) { maxDot = newDot; supportVerticesOut[j] = vtx; } } } } void btCapsuleShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const { //as an approximation, take the inertia of the box that bounds the spheres btTransform ident; ident.setIdentity(); btScalar radius = getRadius(); btVector3 halfExtents(radius,radius,radius); halfExtents[getUpAxis()]+=getHalfHeight(); btScalar margin = CONVEX_DISTANCE_MARGIN; btScalar lx=btScalar(2.)*(halfExtents[0]+margin); btScalar ly=btScalar(2.)*(halfExtents[1]+margin); btScalar lz=btScalar(2.)*(halfExtents[2]+margin); const btScalar x2 = lx*lx; const btScalar y2 = ly*ly; const btScalar z2 = lz*lz; const btScalar scaledmass = mass * btScalar(.08333333); inertia[0] = scaledmass * (y2+z2); inertia[1] = scaledmass * (x2+z2); inertia[2] = scaledmass * (x2+y2); } btCapsuleShapeX::btCapsuleShapeX(btScalar radius,btScalar height) { m_upAxis = 0; m_implicitShapeDimensions.setValue(0.5f*height, radius,radius); } btCapsuleShapeZ::btCapsuleShapeZ(btScalar radius,btScalar height) { m_upAxis = 2; m_implicitShapeDimensions.setValue(radius,radius,0.5f*height); }
412
0.95063
1
0.95063
game-dev
MEDIA
0.955814
game-dev
0.967815
1
0.967815
phaserjs/phaser
1,399
src/display/align/in/BottomRight.js
/** * @author Richard Davey <rich@phaser.io> * @copyright 2013-2025 Phaser Studio Inc. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var GetBottom = require('../../bounds/GetBottom'); var GetRight = require('../../bounds/GetRight'); var SetBottom = require('../../bounds/SetBottom'); var SetRight = require('../../bounds/SetRight'); /** * Takes given Game Object and aligns it so that it is positioned in the bottom right of the other. * * @function Phaser.Display.Align.In.BottomRight * @since 3.0.0 * * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] * * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be positioned. * @param {Phaser.GameObjects.GameObject} alignIn - The Game Object to base the alignment position on. * @param {number} [offsetX=0] - Optional horizontal offset from the position. * @param {number} [offsetY=0] - Optional vertical offset from the position. * * @return {Phaser.GameObjects.GameObject} The Game Object that was aligned. */ var BottomRight = function (gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } SetRight(gameObject, GetRight(alignIn) + offsetX); SetBottom(gameObject, GetBottom(alignIn) + offsetY); return gameObject; }; module.exports = BottomRight;
412
0.847164
1
0.847164
game-dev
MEDIA
0.987131
game-dev
0.727285
1
0.727285
MinecraftForge/MinecraftForge
9,780
javafmllanguage/src/main/java/net/minecraftforge/fml/javafmlmod/FMLModContainer.java
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.minecraftforge.fml.javafmlmod; import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.ModLoadingException; import net.minecraftforge.fml.ModLoadingStage; import net.minecraftforge.fml.config.IConfigEvent; import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.forgespi.language.IModInfo; import net.minecraftforge.forgespi.language.ModFileScanData; import net.minecraftforge.unsafe.UnsafeHacks; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import cpw.mods.jarhandling.SecureJar; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; import java.util.jar.Attributes; public class FMLModContainer extends ModContainer { private static final Logger LOGGER = LogManager.getLogger(); private static final Marker LOADING = MarkerManager.getMarker("LOADING"); private final ModFileScanData scanResults; private final BusGroup eventBusGroup; private Object modInstance; private final Class<?> modClass; private final FMLJavaModLoadingContext context = new FMLJavaModLoadingContext(this); public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer) { super(info); LOGGER.debug(LOADING,"Creating FMLModContainer instance for {}", className); this.scanResults = modFileScanResults; activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod); this.eventBusGroup = BusGroup.create("modBusFor" + info.getModId(), IModBusEvent.class); this.contextExtension = () -> context; try { var moduleName = info.getOwningFile().moduleName(); var module = gameLayer.findModule(moduleName) .orElseThrow(() -> new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer)); openModules(gameLayer, module, info.getOwningFile().getFile().getSecureJar()); modClass = Class.forName(module, className); LOGGER.debug(LOADING,"Loaded modclass {}/{} with {}", modClass.getModule().getName(), modClass.getName(), modClass.getClassLoader()); } catch (Throwable e) { LOGGER.error(LOADING, "Failed to load class {}", className, e); throw new ModLoadingException(info, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmodclass", e); } } /** * <pre> * Reads the Add-Exports and Add-Opens attributes (see note) from a mod file and * attempts to apply them. This differers from the JEP in two significant ways: * 1) Instead of opening things to ALL-UNNAMED it instead only opens to the * mod's module itself. Because I don't want other mods accidently relying * on transitive behavior * 2) It is read from all mods not just the executable jars. * * From <a href = "https://openjdk.org/jeps/261">JEP 261: Module System</a> * * Two new JDK-specific JAR-file manifest attributes are defined to correspond * to the --add-exports and --add-opens command-line options: * Add-Exports: &lt;module&gt;/&lt;package&gt;( &lt;module&gt;/&lt;package&gt;)* * Add-Opens: &lt;module&gt;/&lt;package&gt;( &lt;module&gt;/&lt;package&gt;)* * * The value of each attribute is a space-separated list of slash-separated * module-name/package-name pairs. A &gt;module&lt;/&gt;package&lt; pair in * the value of an Add-Exports attribute has the same meaning as the * command-line option --add-exports &gt;module&lt;/&gt;package&lt;=ALL-UNNAMED. * * A &gt;module&lt;/&gt;package&lt; pair in the value of an Add-Opens attribute has the * same meaning as the command-line option --add-opens &gt;module&lt;/&gt;package&lt;=ALL-UNNAMED. * * Each attribute can occur at most once, in the main section of a MANIFEST.MF file. * A particular pair can be listed more than once. If a specified module was not * resolved, or if a specified package does not exist, then the corresponding pair * is ignored. */ private static void openModules(ModuleLayer layer, Module self, SecureJar jar) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException { var manifest = jar.moduleDataProvider().getManifest().getMainAttributes(); addOpenOrExports(layer, self, true, manifest); addOpenOrExports(layer, self, false, manifest); } private static void addOpenOrExports(ModuleLayer layer, Module self, boolean open, Attributes attrs) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException { var key = open ? "Add-Opens" : "Add-Exports"; var entry = attrs.getValue(key); if (entry == null) return; for (var pair : entry.split(" ")) { var pts = pair.trim().split("/"); if (pts.length == 2) { var target = layer.findModule(pts[0]).orElse(null); if (target == null || !target.getDescriptor().packages().contains(pts[1])) continue; addOpenOrExport(target, pts[1], self, open); } else { LOGGER.warn(LOADING, "Invalid {} entry in {}: {}", key, self.getName(), pair); } } } private static Method implAddExportsOrOpens; private static void addOpenOrExport(Module target, String pkg, Module reader, boolean open) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException { if (implAddExportsOrOpens == null) { implAddExportsOrOpens = Module.class.getDeclaredMethod("implAddExportsOrOpens", String.class, Module.class, boolean.class, boolean.class); UnsafeHacks.setAccessible(implAddExportsOrOpens); } LOGGER.info(LOADING, "{} {}/{} to {}", open ? "Opening" : "Exporting", target.getName(), pkg, reader.getName()); implAddExportsOrOpens.invoke(target, pkg, reader, open, /*syncVM*/true); } private void constructMod() { try { LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName()); Constructor<?> constructor; try { constructor = modClass.getDeclaredConstructor(context.getClass()); } catch (NoSuchMethodException | SecurityException exception) { constructor = modClass.getDeclaredConstructor(); } this.modInstance = constructor.getParameterCount() == 0 ? constructor.newInstance() : constructor.newInstance(context); LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName()); } catch (Throwable e) { // When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the // actual exception from the mod loading error screen. if (e instanceof InvocationTargetException wrapped) e = Objects.requireNonNullElse(wrapped.getCause(), e); // unwrap the exception LOGGER.error(LOADING, "Failed to create mod instance. ModID: {}, class {}", getModId(), modClass.getName(), e); throw new ModLoadingException(modInfo, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmod", e, modClass); } try { LOGGER.trace(LOADING, "Injecting Automatic event subscribers for {}", getModId()); AutomaticEventSubscriber.inject(this, this.scanResults, this.modClass.getClassLoader()); LOGGER.trace(LOADING, "Completed Automatic event subscribers for {}", getModId()); } catch (Throwable e) { LOGGER.error(LOADING, "Failed to register automatic subscribers. ModID: {}, class {}", getModId(), modClass.getName(), e); throw new ModLoadingException(modInfo, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmod", e, modClass); } } @Override public boolean matches(Object mod) { return mod == modInstance; } @Override public Object getMod() { return modInstance; } public BusGroup getModBusGroup() { return this.eventBusGroup; } @Override protected <T extends IModBusEvent> void acceptEvent(final T e) { try { LOGGER.trace(LOADING, "Firing event for modid {} : {}", this.getModId(), e); @SuppressWarnings("unchecked") var eventBus = (EventBus<T>) IModBusEvent.getBus(eventBusGroup, e.getClass()); eventBus.post(e); LOGGER.trace(LOADING, "Fired event for modid {} : {}", this.getModId(), e); } catch (Throwable t) { LOGGER.error(LOADING,"Caught exception during event {} dispatch for modid {}", e, this.getModId(), t); throw new ModLoadingException(modInfo, modLoadingStage, "fml.modloading.errorduringevent", t); } } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void dispatchConfigEvent(IConfigEvent event) { var eventBus = (EventBus) EventBus.create(eventBusGroup, event.self().getClass()); eventBus.post(event.self()); } @Override public String toString() { return "FMLModContainer[" + this.getModInfo().getModId() + ", " + this.getClass().getName() + ']'; } }
412
0.961361
1
0.961361
game-dev
MEDIA
0.914539
game-dev
0.964649
1
0.964649
fetus-hina/stat.ink
1,302
views/entire/v3/splatfest3/weapons/table/columns/special.php
<?php /** * @copyright Copyright (C) 2024-2025 AIZAWA Hina * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT * @author AIZAWA Hina <hina@fetus.jp> */ declare(strict_types=1); use app\components\widgets\BattleSummaryItemWidget; use app\models\Splatfest3StatsWeapon; use yii\base\Model; use yii\grid\GridView; use yii\helpers\Html; return [ 'contentOptions' => fn (Splatfest3StatsWeapon $model): array => [ 'class' => 'text-right', 'data-sort-value' => $model->avg_special, ], 'format' => 'raw', 'headerOptions' => [ 'data-sort' => 'float', 'data-sort-default' => 'desc', ], 'label' => Yii::t('app', 'Avg Specials'), 'value' => fn (Splatfest3StatsWeapon $model): string => BattleSummaryItemWidget::widget([ 'battles' => $model->battles, 'max' => $model->max_special, 'median' => $model->p50_special, 'min' => $model->min_special, 'pct5' => $model->p05_special, 'pct95' => $model->p95_special, 'q1' => $model->p25_special, 'q3' => $model->p75_special, 'stddev' => $model->sd_special, 'summary' => vsprintf('%s - %s', [ Yii::t('app-weapon3', $model->weapon->name), Yii::t('app', 'Avg Specials'), ]), 'tooltipText' => '', 'total' => $model->battles * $model->avg_special, ]), ];
412
0.902089
1
0.902089
game-dev
MEDIA
0.287023
game-dev
0.771733
1
0.771733
lunar-sway/minestuck
12,995
src/main/java/com/mraof/minestuck/blockentity/machine/TotemLatheBlockEntity.java
package com.mraof.minestuck.blockentity.machine; import com.mraof.minestuck.api.alchemy.recipe.combination.CombinationInput; import com.mraof.minestuck.api.alchemy.recipe.combination.CombinationMode; import com.mraof.minestuck.api.alchemy.recipe.combination.CombinationRecipe; import com.mraof.minestuck.block.EnumDowelType; import com.mraof.minestuck.block.MSBlocks; import com.mraof.minestuck.block.machine.TotemLatheBlock; import com.mraof.minestuck.blockentity.ItemStackBlockEntity; import com.mraof.minestuck.blockentity.MSBlockEntityTypes; import com.mraof.minestuck.item.MSItems; import com.mraof.minestuck.item.components.EncodedItemComponent; import com.mraof.minestuck.item.components.MSItemComponents; import com.mraof.minestuck.util.MSSoundEvents; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.sounds.SoundSource; import net.minecraft.world.Containers; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.LevelEvent; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import java.util.Objects; /** * Stores 1-2 punched captcha cards. Handles the triggering and logic of && combination recipes using those punched cards, the result of which is applied to a cruxite dowel. * {@link TotemLatheDowelBlockEntity} handles the storage of the dowel that will be lathed. The Totem Lathe is a core Editmode deployable */ @ParametersAreNonnullByDefault public class TotemLatheBlockEntity extends BlockEntity { private static final Logger LOGGER = LogManager.getLogger(); private boolean isProcessing; private int animationticks; private boolean broken = false; //two cards so that we can preform the && alchemy operation private ItemStack card1 = ItemStack.EMPTY; private ItemStack card2 = ItemStack.EMPTY; public TotemLatheBlockEntity(BlockPos pos, BlockState state) { super(MSBlockEntityTypes.TOTEM_LATHE.get(), pos, state); } private boolean tryAddCard(ItemStack stack) { if(!isBroken() && stack.is(MSItems.CAPTCHA_CARD.get())) { if(card1.isEmpty()) card1 = stack; else if(card2.isEmpty()) card2 = stack; else return false; updateState(); return true; } return false; } private ItemStack tryTakeCard() { ItemStack card = ItemStack.EMPTY; if(!card2.isEmpty()) { card = card2; card2 = ItemStack.EMPTY; } else if(!card1.isEmpty()) { card = card1; card1 = ItemStack.EMPTY; } if(!card.isEmpty()) updateState(); return card; } private void updateState() { int worldCount = getBlockState().getValue(TotemLatheBlock.Slot.COUNT); int actualCount = getActualCardCount(); if(worldCount != actualCount) { level.setBlockAndUpdate(worldPosition, getBlockState().setValue(TotemLatheBlock.Slot.COUNT, actualCount)); } } private int getActualCardCount() { if(!card2.isEmpty()) return 2; else if(!card1.isEmpty()) return 1; else return 0; } @Nonnull public ItemStack getCard1() { return card1; } public ItemStack getCard2() { return card2; } public boolean isBroken() { return broken; } public void setBroken() { broken = true; } public void dropItems() { Objects.requireNonNull(this.level); BlockPos pos = this.getBlockPos(); if(!this.card1.isEmpty()) { Containers.dropItemStack(level, pos.getX(), pos.getY(), pos.getZ(), this.card1); this.card1 = ItemStack.EMPTY; } if(!this.card2.isEmpty()) { Containers.dropItemStack(level, pos.getX(), pos.getY(), pos.getZ(), this.card2); this.card2 = ItemStack.EMPTY; } } public boolean setDowel(ItemStack dowelStack) { Objects.requireNonNull(this.level); if(!(dowelStack.is(MSItems.CRUXITE_DOWEL.get()) || dowelStack.isEmpty())) return false; Direction facing = getFacing(); BlockPos dowelPos = MSBlocks.TOTEM_LATHE.getDowelPos(getBlockPos(), getBlockState()); BlockState oldState = level.getBlockState(dowelPos); BlockState newState = MSBlocks.TOTEM_LATHE.DOWEL_ROD.get() .defaultBlockState().setValue(TotemLatheBlock.FACING, facing) .setValue(TotemLatheBlock.DowelRod.DOWEL, EnumDowelType.getForDowel(dowelStack)); if(isValidDowelRod(oldState, facing)) { BlockEntity be = level.getBlockEntity(dowelPos); if(!(be instanceof TotemLatheDowelBlockEntity)) { be = new TotemLatheDowelBlockEntity(dowelPos, newState); level.setBlockEntity(be); } TotemLatheDowelBlockEntity beItem = (TotemLatheDowelBlockEntity) be; beItem.setStack(dowelStack); //updating the dowel block entity if(!oldState.equals(newState)) level.setBlockAndUpdate(dowelPos, newState); else level.sendBlockUpdated(dowelPos, oldState, oldState, Block.UPDATE_ALL); //updating the machine's block entity isProcessing = false; level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); return true; } return false; } private void setCarvedItem(ItemStack output) { Objects.requireNonNull(this.level); Direction facing = getFacing(); BlockPos pos = MSBlocks.TOTEM_LATHE.getDowelPos(getBlockPos(), getBlockState()); BlockState oldState = level.getBlockState(pos); if(!isValidDowelRod(oldState, facing)) return; // This is not our dowel rod block! BlockEntity be = level.getBlockEntity(pos); if(!(be instanceof ItemStackBlockEntity beItem)) return; ItemStack oldDowel = beItem.getStack(); ItemStack newDowel = EncodedItemComponent.setEncodedUnlessBlank(oldDowel.copy().split(1), output.getItem()); beItem.setStack(newDowel); BlockState newState = MSBlocks.TOTEM_LATHE.DOWEL_ROD.get() .defaultBlockState().setValue(TotemLatheBlock.FACING, facing) .setValue(TotemLatheBlock.DowelRod.DOWEL, EnumDowelType.getForDowel(newDowel)); if(!oldState.equals(newState)) level.setBlockAndUpdate(pos, newState); else level.sendBlockUpdated(pos, oldState, newState, 2); // Make sure the new dowel item is synced to client } public ItemStack getDowel() { BlockPos pos = MSBlocks.TOTEM_LATHE.getDowelPos(getBlockPos(), getBlockState()); if(isValidDowelRod(level.getBlockState(pos), getFacing())) { if(level.getBlockEntity(pos) instanceof TotemLatheDowelBlockEntity blockEntity) return blockEntity.getStack(); } return ItemStack.EMPTY; } private boolean isValidDowelRod(BlockState state, Direction facing) { return state.is(MSBlocks.TOTEM_LATHE.DOWEL_ROD.get()) && state.getValue(TotemLatheBlock.FACING) == facing; } public Direction getFacing() { return getBlockState().getValue(TotemLatheBlock.FACING); } public void onRightClick(Player player, BlockState clickedState) { boolean working = isUseable(clickedState); //if they have clicked on the part that holds the captcha cards if(clickedState.getBlock() instanceof TotemLatheBlock.Slot) handleSlotClick(player, working); //if they have clicked the dowel block if(clickedState.is(MSBlocks.TOTEM_LATHE.DOWEL_ROD.get())) handleDowelClick(player, working); //if they have clicked on the lever if(clickedState.is(MSBlocks.TOTEM_LATHE.TOP.get()) && level != null) { boolean startingCarving = false; //carve the dowel. if(working && !getDowel().isEmpty() && !getDowel().has(MSItemComponents.ENCODED_ITEM) && (!card1.isEmpty() || !card2.isEmpty())) { this.level.playSound(null, this.getBlockPos(), MSSoundEvents.TOTEM_LATHE_LATHE.get(), SoundSource.BLOCKS, 1F, 1F); startingCarving = true; isProcessing = true; animationticks = 25; level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); } level.levelEvent(startingCarving ? LevelEvent.SOUND_DISPENSER_DISPENSE : LevelEvent.SOUND_DISPENSER_FAIL, getBlockPos(), 0); } } private void handleSlotClick(Player player, boolean isWorking) { ItemStack heldStack = player.getMainHandItem(); ItemStack card = heldStack.copy().split(1); if(tryAddCard(card)) { heldStack.shrink(1); } else { card = tryTakeCard(); if(!card.isEmpty()) { if(player.getMainHandItem().isEmpty()) player.setItemInHand(InteractionHand.MAIN_HAND, card); else if(!player.getInventory().add(card)) dropItem(false, getBlockPos(), card); else player.inventoryMenu.broadcastChanges(); } } } private void handleDowelClick(Player player, boolean isWorking) { ItemStack heldStack = player.getMainHandItem(); ItemStack dowel = getDowel(); if (dowel.isEmpty()) { if(isWorking && heldStack.is(MSItems.CRUXITE_DOWEL.get())) { ItemStack copy = heldStack.copy(); copy.setCount(1); if(setDowel(copy)) { heldStack.shrink(1); } } } else { if(player.getMainHandItem().isEmpty()) player.setItemInHand(InteractionHand.MAIN_HAND, dowel); else if(!player.getInventory().add(dowel)) dropItem(true, getBlockPos().above().relative(getFacing().getCounterClockWise(), 2), dowel); else player.inventoryMenu.broadcastChanges(); setDowel(ItemStack.EMPTY); } } private boolean isUseable(BlockState state) { BlockState currentState = getLevel().getBlockState(getBlockPos()); if(!isBroken()) { checkStates(); if(isBroken()) LOGGER.warn("Failed to notice a block being broken or misplaced at the totem lathe at {}", getBlockPos()); } if(!state.getValue(TotemLatheBlock.FACING).equals(currentState.getValue(TotemLatheBlock.FACING))) return false; return !isBroken(); } public void checkStates() { if(isBroken()) return; if(MSBlocks.TOTEM_LATHE.isInvalidFromSlot(level, getBlockPos())) setBroken(); } private void dropItem(boolean inBlock, BlockPos pos, ItemStack stack) { Direction direction = getFacing(); BlockPos dropPos; if(inBlock) dropPos = pos; else if(!Block.canSupportCenter(level, pos.relative(direction), direction.getOpposite())) dropPos = pos.relative(direction); else dropPos = pos; Containers.dropItemStack(level, dropPos.getX(), dropPos.getY(), dropPos.getZ(), stack); } @Override protected void loadAdditional(CompoundTag nbt, HolderLookup.Provider pRegistries) { super.loadAdditional(nbt, pRegistries); broken = nbt.getBoolean("broken"); card1 = ItemStack.parseOptional(pRegistries, nbt.getCompound("card1")); card2 = ItemStack.parseOptional(pRegistries, nbt.getCompound("card2")); isProcessing = nbt.getBoolean("isProcessing"); if(card1.isEmpty() && !card2.isEmpty()) { card1 = card2; card2 = ItemStack.EMPTY; } } @Override public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) { super.saveAdditional(compound, provider); compound.putBoolean("broken",broken); compound.put("card1", card1.saveOptional(provider)); compound.put("card2", card2.saveOptional(provider)); compound.putBoolean("isProcessing", isProcessing); } private void processContents(Level level) { ItemStack dowel = getDowel(); ItemStack output; if(!dowel.isEmpty() && !dowel.has(MSItemComponents.ENCODED_ITEM) && (!card1.isEmpty() || !card2.isEmpty())) { if(!card1.isEmpty() && !card2.isEmpty()) { ItemStack input1 = EncodedItemComponent.getEncodedOrBlank(card1), input2 = EncodedItemComponent.getEncodedOrBlank(card2); if(input1.is(MSItems.GENERIC_OBJECT.get()) || input2.is(MSItems.GENERIC_OBJECT.get())) output = new ItemStack(MSItems.GENERIC_OBJECT.get()); else output = CombinationRecipe.findResult(new CombinationInput(input1, input2, CombinationMode.AND), level); } else { ItemStack input = card1.isEmpty() ? card2 : card1; output = EncodedItemComponent.getEncodedOrBlank(input); } if(!output.isEmpty()) setCarvedItem(output); } } public static void tick(Level level, BlockPos pos, BlockState state, TotemLatheBlockEntity blockEntity) { if(blockEntity.animationticks > 0) { blockEntity.animationticks--; if(blockEntity.animationticks <= 0) { blockEntity.processContents(level); } } } @Override public CompoundTag getUpdateTag(HolderLookup.Provider provider) { return this.saveWithoutMetadata(provider); } @Override public Packet<ClientGamePacketListener> getUpdatePacket() { return ClientboundBlockEntityDataPacket.create(this); } public boolean isProcessing() { return isProcessing; } }
412
0.980949
1
0.980949
game-dev
MEDIA
0.987079
game-dev
0.990704
1
0.990704
MrBElga/java-games
1,201
tetris/src/mino/Mino_Bar.java
package mino; import java.awt.*; public class Mino_Bar extends Mino{ public Mino_Bar(){ create(Color.CYAN); } public void setXY(int x, int y) { b[0].x = x; b[0].y = y; b[1].x = b[0].x - Block.SIZE; b[1].y = b[0].y; b[2].x = b[0].x + Block.SIZE; b[2].y = b[0].y; b[3].x = b[0].x + Block.SIZE*2; b[3].y = b[0].y; } public void getDirection1(){ tempB[0].x = b[0].x; tempB[0].y = b[0].y; tempB[1].x = b[0].x - Block.SIZE; tempB[1].y = b[0].y; tempB[2].x = b[0].x + Block.SIZE; tempB[2].y = b[0].y; tempB[3].x = b[0].x + Block.SIZE*2; tempB[3].y = b[0].y; updateXY(1); } public void getDirection2(){ tempB[0].x = b[0].x; tempB[0].y = b[0].y; tempB[1].x = b[0].x; tempB[1].y = b[0].y - Block.SIZE; tempB[2].x = b[0].x; tempB[2].y = b[0].y + Block.SIZE; tempB[3].x = b[0].x; tempB[3].y = b[0].y + Block.SIZE*2; updateXY(2); } public void getDirection3(){ getDirection1(); } public void getDirection4(){ getDirection2(); } }
412
0.735249
1
0.735249
game-dev
MEDIA
0.511884
game-dev
0.591135
1
0.591135
ppy/osu
2,213
osu.Game/Rulesets/Difficulty/Skills/StrainDecaySkill.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Difficulty.Skills { /// <summary> /// Used to processes strain values of <see cref="DifficultyHitObject"/>s, keep track of strain levels caused by the processed objects /// and to calculate a final difficulty value representing the difficulty of hitting all the processed objects. /// </summary> public abstract class StrainDecaySkill : StrainSkill { /// <summary> /// Strain values are multiplied by this number for the given skill. Used to balance the value of different skills between each other. /// </summary> protected abstract double SkillMultiplier { get; } /// <summary> /// Determines how quickly strain decays for the given skill. /// For example a value of 0.15 indicates that strain decays to 15% of its original value in one second. /// </summary> protected abstract double StrainDecayBase { get; } /// <summary> /// The current strain level. /// </summary> protected double CurrentStrain { get; private set; } protected StrainDecaySkill(Mod[] mods) : base(mods) { } protected override double CalculateInitialStrain(double time, DifficultyHitObject current) => CurrentStrain * strainDecay(time - current.Previous(0).StartTime); protected override double StrainValueAt(DifficultyHitObject current) { CurrentStrain *= strainDecay(current.DeltaTime); CurrentStrain += StrainValueOf(current) * SkillMultiplier; return CurrentStrain; } /// <summary> /// Calculates the strain value of a <see cref="DifficultyHitObject"/>. This value is affected by previously processed objects. /// </summary> protected abstract double StrainValueOf(DifficultyHitObject current); private double strainDecay(double ms) => Math.Pow(StrainDecayBase, ms / 1000); } }
412
0.941083
1
0.941083
game-dev
MEDIA
0.836666
game-dev
0.910897
1
0.910897
chocoteam/choco-solver
1,318
solver/src/main/java/org/chocosolver/solver/variables/events/SetEventType.java
/* * This file is part of choco-solver, http://choco-solver.org/ * * Copyright (c) 2025, IMT Atlantique. All rights reserved. * * Licensed under the BSD 4-clause license. * * See LICENSE file in the project root for full license information. */ package org.chocosolver.solver.variables.events; /** * An enum defining the set variable event types: * <ul> * <li><code>ADD_TO_KER</code>: value enforcing event,</li> * <li><code>REMOVE_FROM_ENVELOPE</code>: value removal event,</li> * </ul> * <p/> * * @author Charles Prud'homme, Jean-Guillaume Fages */ public enum SetEventType implements IEventType { VOID(0), ADD_TO_KER(1), REMOVE_FROM_ENVELOPE(2); private final int mask; SetEventType(int mask) { this.mask = mask; } @Override public int getMask() { return mask; } //****************************************************************************************************************** //****************************************************************************************************************** public static int all() { return ADD_TO_KER.mask+REMOVE_FROM_ENVELOPE.mask; } public static boolean isKerAddition(int mask) { return (mask & ADD_TO_KER.mask) != 0; } public static boolean isEnvRemoval(int mask) { return (mask & REMOVE_FROM_ENVELOPE.mask) != 0; } }
412
0.939227
1
0.939227
game-dev
MEDIA
0.273454
game-dev
0.683603
1
0.683603
PacktPublishing/Mastering-Cpp-Game-Development
3,425
Chapter04/Include/bullet/BulletDynamics/Vehicle/btWheelInfo.h
/* * Copyright (c) 2005 Erwin Coumans http://continuousphysics.com/Bullet/ * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies. * Erwin Coumans makes no representations about the suitability * of this software for any purpose. * It is provided "as is" without express or implied warranty. */ #ifndef BT_WHEEL_INFO_H #define BT_WHEEL_INFO_H #include "LinearMath/btVector3.h" #include "LinearMath/btTransform.h" class btRigidBody; struct btWheelInfoConstructionInfo { btVector3 m_chassisConnectionCS; btVector3 m_wheelDirectionCS; btVector3 m_wheelAxleCS; btScalar m_suspensionRestLength; btScalar m_maxSuspensionTravelCm; btScalar m_wheelRadius; btScalar m_suspensionStiffness; btScalar m_wheelsDampingCompression; btScalar m_wheelsDampingRelaxation; btScalar m_frictionSlip; btScalar m_maxSuspensionForce; bool m_bIsFrontWheel; }; /// btWheelInfo contains information per wheel about friction and suspension. struct btWheelInfo { struct RaycastInfo { //set by raycaster btVector3 m_contactNormalWS;//contactnormal btVector3 m_contactPointWS;//raycast hitpoint btScalar m_suspensionLength; btVector3 m_hardPointWS;//raycast starting point btVector3 m_wheelDirectionWS; //direction in worldspace btVector3 m_wheelAxleWS; // axle in worldspace bool m_isInContact; void* m_groundObject; //could be general void* ptr }; RaycastInfo m_raycastInfo; btTransform m_worldTransform; btVector3 m_chassisConnectionPointCS; //const btVector3 m_wheelDirectionCS;//const btVector3 m_wheelAxleCS; // const or modified by steering btScalar m_suspensionRestLength1;//const btScalar m_maxSuspensionTravelCm; btScalar getSuspensionRestLength() const; btScalar m_wheelsRadius;//const btScalar m_suspensionStiffness;//const btScalar m_wheelsDampingCompression;//const btScalar m_wheelsDampingRelaxation;//const btScalar m_frictionSlip; btScalar m_steering; btScalar m_rotation; btScalar m_deltaRotation; btScalar m_rollInfluence; btScalar m_maxSuspensionForce; btScalar m_engineForce; btScalar m_brake; bool m_bIsFrontWheel; void* m_clientInfo;//can be used to store pointer to sync transforms... btWheelInfo(btWheelInfoConstructionInfo& ci) { m_suspensionRestLength1 = ci.m_suspensionRestLength; m_maxSuspensionTravelCm = ci.m_maxSuspensionTravelCm; m_wheelsRadius = ci.m_wheelRadius; m_suspensionStiffness = ci.m_suspensionStiffness; m_wheelsDampingCompression = ci.m_wheelsDampingCompression; m_wheelsDampingRelaxation = ci.m_wheelsDampingRelaxation; m_chassisConnectionPointCS = ci.m_chassisConnectionCS; m_wheelDirectionCS = ci.m_wheelDirectionCS; m_wheelAxleCS = ci.m_wheelAxleCS; m_frictionSlip = ci.m_frictionSlip; m_steering = btScalar(0.); m_engineForce = btScalar(0.); m_rotation = btScalar(0.); m_deltaRotation = btScalar(0.); m_brake = btScalar(0.); m_rollInfluence = btScalar(0.1); m_bIsFrontWheel = ci.m_bIsFrontWheel; m_maxSuspensionForce = ci.m_maxSuspensionForce; } void updateWheel(const btRigidBody& chassis,RaycastInfo& raycastInfo); btScalar m_clippedInvContactDotSuspension; btScalar m_suspensionRelativeVelocity; //calculated by suspension btScalar m_wheelsSuspensionForce; btScalar m_skidInfo; }; #endif //BT_WHEEL_INFO_H
412
0.92988
1
0.92988
game-dev
MEDIA
0.986047
game-dev
0.935196
1
0.935196
SonicTHI/SaveOurShip2Experimental
13,425
Source/1.5/Building/Building_ShipAirlock.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Verse; using Verse.AI; using Verse.AI.Group; using Verse.Sound; using HarmonyLib; using RimWorld; using UnityEngine; using Vehicles; namespace SaveOurShip2 { public class Building_ShipAirlock : Building_Door { List<Building> extenders = new List<Building>(); public ShipMapComp mapComp; public CompUnfold unfoldComp; public bool hacked = false; public bool failed = false; public bool docked = false; public Building dockedTo; public Building First; public Building Second; public int firstRot = -1; //doors dont have normal rot so this is used for extender gfx int dist = 0; int startTick = 0; public override IEnumerable<FloatMenuOption> GetFloatMenuOptions(Pawn pawn) { List<FloatMenuOption> options = new List<FloatMenuOption>(); foreach (FloatMenuOption op in base.GetFloatMenuOptions(pawn)) options.Add(op); if (Map != null && Map.Parent != null && Map.Parent.def == ResourceBank.WorldObjectDefOf.SiteSpace) //To prevent cheesing the starship bow quest return options; if (Faction != Faction.OfPlayer) { if (!hacked && !failed && !pawn.skills.GetSkill(SkillDefOf.Intellectual).TotallyDisabled && pawn.health.capacities.GetLevel(PawnCapacityDefOf.Manipulation) > 0) { options.Add(new FloatMenuOption("Hack", delegate { Job hackAirlock = new Job(ResourceBank.JobDefOf.HackAirlock, this); pawn.jobs.TryTakeOrderedJob(hackAirlock); })); } if (!hacked && !pawn.skills.GetSkill(SkillDefOf.Construction).TotallyDisabled && pawn.health.capacities.GetLevel(PawnCapacityDefOf.Manipulation) > 0) { options.Add(new FloatMenuOption("Breach", delegate { Job breachAirlock = new Job(ResourceBank.JobDefOf.BreachAirlock, this); pawn.jobs.TryTakeOrderedJob(breachAirlock); })); } } return options; } //hacked - chance to open and set to neutral public void HackMe(Pawn pawn) { if (Rand.Chance(0.045f * pawn.skills.GetSkill(SkillDefOf.Intellectual).levelInt + 0.05f)) { hacked = true; pawn.skills.GetSkill(SkillDefOf.Intellectual).Learn(200); SetFaction(Faction.OfAncients); DoorOpen(); def.building.soundDoorOpenManual.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); if (pawn.Faction == Faction.OfPlayer) Messages.Message(TranslatorFormattedStringExtensions.Translate("SoS.AirlockHacked"), this, MessageTypeDefOf.PositiveEvent); } else { failed = true; pawn.skills.GetSkill(SkillDefOf.Intellectual).Learn(100); if (pawn.Faction == Faction.OfPlayer) Messages.Message(TranslatorFormattedStringExtensions.Translate("SoS.AirlockHackFailed"), this, MessageTypeDefOf.NegativeEvent); } } //breached - will open and stay open public void BreachMe(Pawn pawn) { hacked = true; if (!pawn.RaceProps.IsMechanoid) pawn.skills.GetSkill(SkillDefOf.Construction).Learn(200); DoorOpen(); Traverse.Create(this).Field("holdOpenInt").SetValue(true); def.building.soundDoorOpenManual.PlayOneShot(new TargetInfo(base.Position, base.Map, false)); if (pawn.Faction == Faction.OfPlayer) Messages.Message(TranslatorFormattedStringExtensions.Translate("SoS.AirlockBreached"), this, MessageTypeDefOf.PositiveEvent); TakeDamage(new DamageInfo(DamageDefOf.Cut, 200)); } public override bool PawnCanOpen(Pawn p) { if (p.RaceProps.FenceBlocked && p.RaceProps.Roamer && p.CurJobDef != JobDefOf.FollowRoper) return false; //enemy pawns can pass through their doors if outside or with EVA when player is present if (p.Map.IsSpace() && p.Faction != Faction.OfPlayer && Outerdoor()) { if (!(ShipInteriorMod2.ExposedToOutside(p.GetRoom()) || (p.CanSurviveVacuum() && (mapComp.ShipMapState != ShipMapState.inCombat || p.Map.mapPawns.AnyColonistSpawned)) || p.CurJobDef == ResourceBank.JobDefOf.FleeVacuum)) return false; } Lord lord = p.GetLord(); return base.PawnCanOpen(p) && ((lord != null && lord.LordJob != null && lord.LordJob.CanOpenAnyDoor(p)) || WildManUtility.WildManShouldReachOutsideNow(p) || base.Faction == null || (p.guest != null && p.guest.Released) || GenAI.MachinesLike(base.Faction, p)); } public bool Outerdoor() { foreach (IntVec3 pos in GenAdj.CellsAdjacentCardinal(this)) { Room room = pos.GetRoom(Map); if (room != null && (room.OpenRoofCount > 0 || room.TouchesMapEdge)) { return true; } } return false; } public IntVec3 VacuumSafeSpot() { foreach (IntVec3 pos in GenAdj.CellsAdjacentCardinal(this)) { Room room = pos.GetRoom(Map); if (room != null && !(room.OpenRoofCount > 0 || room.TouchesMapEdge)) { return pos; } } return IntVec3.Invalid; } public override string GetInspectString() { StringBuilder stringBuilder = new StringBuilder(base.GetInspectString()); if (Prefs.DevMode) { if (this.Outerdoor()) { stringBuilder.AppendLine("outerdoor"); } else { stringBuilder.AppendLine("innerdoor"); } } return stringBuilder.ToString().TrimEndNewlines(); } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look<bool>(ref hacked, "hacked", false); Scribe_Values.Look<bool>(ref failed, "failed", false); Scribe_Values.Look<bool>(ref docked, "docked", false); Scribe_References.Look<Building>(ref dockedTo, "dockedTo"); Scribe_Values.Look<int>(ref dist, "dist", 0); Scribe_Values.Look<int>(ref startTick, "startTick", 0); Scribe_Values.Look<int>(ref firstRot, "firstRot", -1); Scribe_Collections.Look<Building>(ref extenders, "extenders", LookMode.Reference); } public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); mapComp = this.Map.GetComponent<ShipMapComp>(); unfoldComp = this.TryGetComp<CompUnfold>(); } //docking - doors dont have proper rot public override void Destroy(DestroyMode mode = DestroyMode.Vanish) { base.Destroy(mode); } public override void DeSpawn(DestroyMode mode = DestroyMode.Vanish) { if (docked) { DeSpawnDock(); } mapComp.Docked.Remove(this); dockedTo = null; base.DeSpawn(mode); } public override void Tick() { base.Tick(); int ticks = Find.TickManager.TicksGame; //create area after animation if (startTick > 0 && ticks > startTick) { startTick = 0; if (mapComp.ShipMapState != ShipMapState.inCombat && CanDock()) { SpawnDock(); } } //Glow when opened if (OpenPct > 0 && ticks % 16 == 0 && Outerdoor()) Map.flecks.CreateFleck(FleckMaker.GetDataStatic(DrawPos, Map, FleckDefOf.LightningGlow, 3)); } public override IEnumerable<Gizmo> GetGizmos() { foreach (Gizmo g in base.GetGizmos()) { yield return g; } if (Faction == Faction.OfPlayer && (Outerdoor() || docked) && HasDocking()) { bool canDock = CanDock(); Command_Toggle toggleDock = new Command_Toggle { toggleAction = delegate { if (!docked && canDock) { float d = (dist - 1) * 0.3334f; startTick = Find.TickManager.TicksGame + (int)(200 * d); unfoldComp.Target = d; } else { DeSpawnDock(); } }, defaultLabel = TranslatorFormattedStringExtensions.Translate("SoS.ToggleDock"), defaultDesc = TranslatorFormattedStringExtensions.Translate("SoS.ToggleDockDesc"), isActive = () => docked }; if (docked) toggleDock.icon = ContentFinder<Texture2D>.Get("UI/DockingOn"); else toggleDock.icon = ContentFinder<Texture2D>.Get("UI/DockingOff"); if (startTick > 0 || !powerComp.PowerOn || !canDock) { toggleDock.Disable(); } yield return toggleDock; } } public bool HasDocking() //check if airlock has docking beams { for (int i = 0; i < 2; i++) //find first extender, check opposite for other, same rot, not facing airlock { IntVec3 v = Position + GenAdj.CardinalDirections[i]; Thing first = v.GetFirstThingWithComp<CompDockExtender>(Map); if (first == null) continue; var firstComp = first.TryGetComp<CompDockExtender>(); if (firstComp.Props.extender) { if (i == first.Rotation.AsByte || i == first.Rotation.AsByte + 2) //cant face same or opp cardinal break; Thing second = (Position + GenAdj.CardinalDirections[i + 2]).GetFirstThingWithComp<CompDockExtender>(Map); if (second != null) { var secondComp = second.TryGetComp<CompDockExtender>(); if (secondComp.Props.extender && first.Rotation == second.Rotation) { First = first as Building; firstRot = first.Rotation.AsInt; Second = second as Building; firstComp.dockParent = this; secondComp.dockParent = this; return true; } } break; } } First = null; Second = null; firstRot = -1; return false; } public bool CanDock() //check if all clear, set dist { if (docked) return true; if (First == null || First.Destroyed || Second == null || Second.Destroyed) { unfoldComp.Target = 0.0f; ResetDock(); return false; } dist = 0; for (int i = 1; i < 4; i++) { IntVec3 offset = GenAdj.CardinalDirections[First.Rotation.AsByte] * -i; IntVec3 center = Position + offset; IntVec3 first = First.Position + offset; IntVec3 second = Second.Position + offset; var grid = Map.thingGrid; if (grid.ThingsAt(first).Any() || grid.ThingsAt(center).Any() || grid.ThingsAt(second).Any()) { if (i == 1) return false; dist = i; return true; } } dist = 4; return true; } public void SpawnDock() { IntVec3 rot = GenAdj.CardinalDirections[First.Rotation.AsByte]; //place fake walls, floor, extend for (int i = 1; i < dist + 1; i++) { IntVec3 offset = rot * -i; if (i == dist) //register dock - ship part or extender at dist LR { foreach (Thing t in (First.Position + offset).GetThingList(Map)) { if (t.TryGetComp<CompShipCachePart>() != null) //connect to ship part //td check if edifice? { foreach (Thing t2 in (Second.Position + offset).GetThingList(Map)) { if (t2.TryGetComp<CompShipCachePart>() != null) { dockedTo = t as Building; mapComp.Docked.Add(this); break; } } break; } else if (t.TryGetComp<CompDockExtender>() != null) //to extender //td check for cheese { foreach (Thing t2 in (Second.Position + offset).GetThingList(Map)) { var c2 = t2.TryGetComp<CompDockExtender>(); if (c2 != null) { dockedTo = c2.dockParent; mapComp.Docked.Add(this); break; } } break; } } break; } Thing thing; if (dockedTo != null && (dockedTo?.Faction.HostileTo(Faction) ?? false)) thing = ThingMaker.MakeThing(ResourceBank.ThingDefOf.ShipAirlockBeamWallInert); else thing = ThingMaker.MakeThing(ResourceBank.ThingDefOf.ShipAirlockBeamWall); GenSpawn.Spawn(thing, First.Position + offset, Map); thing.TryGetComp<CompDockExtender>().dockParent = this; extenders.Add(thing as Building); thing = ThingMaker.MakeThing(ResourceBank.ThingDefOf.ShipAirlockBeamTile); GenSpawn.Spawn(thing, Position + offset, Map); thing.TryGetComp<CompDockExtender>().dockParent = this; extenders.Add(thing as Building); if (dockedTo != null && (dockedTo?.Faction.HostileTo(Faction) ?? false)) thing = ThingMaker.MakeThing(ResourceBank.ThingDefOf.ShipAirlockBeamWallInert); else thing = ThingMaker.MakeThing(ResourceBank.ThingDefOf.ShipAirlockBeamWall); GenSpawn.Spawn(thing, Second.Position + offset, Map); thing.TryGetComp<CompDockExtender>().dockParent = this; extenders.Add(thing as Building); } //set temp Room room = (Position - rot).GetRoom(Map); if (room != null && !room.UsesOutdoorTemperature) room.Temperature = (Position + rot).GetRoom(Map).Temperature; docked = true; } public void DeSpawnDock(bool force = false) { unfoldComp.Target = 0.0f; if (mapComp.Docked.Contains(this)) //was docked to ship { dockedTo = null; mapComp.Docked.Remove(this); if (!mapComp.AnyShipCanMove()) //if any ship got stuck and stop move { mapComp.MapFullStop(); } } if (extenders.Any()) { if (extenders.Count > 3) { FleckMaker.ThrowDustPuff(extenders[extenders.Count - 1].Position, Map, 1f); FleckMaker.ThrowDustPuff(extenders[extenders.Count - 3].Position, Map, 1f); } List<Building> toDestroy = new List<Building>(); foreach (Building building in extenders.Where(b => !b.Destroyed)) { if (!force) { var comp = building.TryGetComp<CompDockExtender>(); if (comp != null) comp.removedByDock = true; } toDestroy.Add(building); } foreach (Building building in toDestroy) { if (!building.Destroyed) building.Destroy(); } extenders.Clear(); } docked = false; } public void ResetDock() { First = null; Second = null; firstRot = -1; unfoldComp.extension = 0.0f; } protected override void DrawAt(Vector3 drawLoc, bool flip = false) { base.DrawAt(drawLoc, flip); Comps_PostDraw(); } } }
412
0.973129
1
0.973129
game-dev
MEDIA
0.982266
game-dev
0.962403
1
0.962403
OpenRCT2/OpenRCT2
23,371
src/openrct2/Game.cpp
/***************************************************************************** * Copyright (c) 2014-2025 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 * * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ #include "Game.h" #include "Cheats.h" #include "Context.h" #include "Diagnostic.h" #include "Editor.h" #include "FileClassifier.h" #include "GameState.h" #include "GameStateSnapshots.h" #include "Input.h" #include "OpenRCT2.h" #include "ParkImporter.h" #include "PlatformEnvironment.h" #include "ReplayManager.h" #include "actions/GameSetSpeedAction.h" #include "actions/LoadOrQuitAction.h" #include "audio/Audio.h" #include "config/Config.h" #include "core/Console.hpp" #include "core/File.h" #include "core/FileScanner.h" #include "core/Money.hpp" #include "core/Path.hpp" #include "core/String.hpp" #include "entity/EntityList.h" #include "entity/EntityRegistry.h" #include "entity/PatrolArea.h" #include "entity/Peep.h" #include "entity/Staff.h" #include "interface/Colour.h" #include "interface/Screenshot.h" #include "interface/Viewport.h" #include "interface/Window.h" #include "management/Finance.h" #include "management/Marketing.h" #include "management/Research.h" #include "network/Network.h" #include "object/Object.h" #include "object/ObjectEntryManager.h" #include "object/ObjectList.h" #include "object/WaterEntry.h" #include "platform/Platform.h" #include "rct12/CSStringConverter.h" #include "ride/Ride.h" #include "ride/RideRatings.h" #include "ride/Station.h" #include "ride/Track.h" #include "ride/TrackDesign.h" #include "ride/Vehicle.h" #include "sawyer_coding/SawyerCoding.h" #include "scenario/Scenario.h" #include "scenes/title/TitleScene.h" #include "scripting/ScriptEngine.h" #include "ui/UiContext.h" #include "ui/WindowManager.h" #include "windows/Intent.h" #include "world/Banner.h" #include "world/Climate.h" #include "world/Entrance.h" #include "world/Footpath.h" #include "world/Map.h" #include "world/MapAnimation.h" #include "world/Park.h" #include "world/Scenery.h" #include "world/tile_element/SurfaceElement.h" #include <cstdio> #include <iterator> #include <memory> #ifdef __EMSCRIPTEN__ extern "C" { extern void EmscriptenSaveGame(bool isTrackDesign, bool isAutosave, LoadSaveType type); extern void EmscriptenResetAutosave(); } #endif using namespace OpenRCT2; uint16_t gCurrentDeltaTime; uint8_t gGamePaused = 0; uint8_t gGameSpeed = 1; bool gDoSingleUpdate = false; float gDayNightCycle = 0; bool gInUpdateCode = false; bool gInMapInitCode = false; std::string gCurrentLoadedPath; bool gIsAutosave = false; bool gIsAutosaveLoaded = false; bool gLoadKeepWindowsOpen = false; uint32_t gCurrentRealTimeTicks; #ifdef ENABLE_SCRIPTING static bool _mapChangedExpected; #endif using namespace OpenRCT2; void GameResetSpeed() { auto setSpeedAction = GameActions::GameSetSpeedAction(1); GameActions::Execute(&setSpeedAction, getGameState()); } void GameIncreaseGameSpeed() { auto newSpeed = std::min(Config::Get().general.debuggingTools ? 5 : 4, gGameSpeed + 1); if (newSpeed == 5) newSpeed = 8; auto setSpeedAction = GameActions::GameSetSpeedAction(newSpeed); GameActions::Execute(&setSpeedAction, getGameState()); } void GameReduceGameSpeed() { auto newSpeed = std::max(1, gGameSpeed - 1); if (newSpeed == 7) newSpeed = 4; auto setSpeedAction = GameActions::GameSetSpeedAction(newSpeed); GameActions::Execute(&setSpeedAction, getGameState()); } /** * * rct2: 0x0066B5C0 (part of 0x0066B3E8) */ void GameCreateWindows() { ContextOpenWindow(WindowClass::mainWindow); ContextOpenWindow(WindowClass::topToolbar); ContextOpenWindow(WindowClass::bottomToolbar); WindowResizeGui(ContextGetWidth(), ContextGetHeight()); } void PauseToggle() { gGamePaused ^= GAME_PAUSED_NORMAL; auto* windowMgr = Ui::GetWindowManager(); windowMgr->InvalidateByClass(WindowClass::topToolbar); if (gGamePaused & GAME_PAUSED_NORMAL) { OpenRCT2::Audio::StopAll(); } } bool GameIsPaused() { return gGamePaused != 0; } bool GameIsNotPaused() { return gGamePaused == 0; } /** * * rct2: 0x0066DC0F */ static void LoadLandscape() { auto intent = Intent(WindowClass::loadsave); intent.PutEnumExtra<LoadSaveAction>(INTENT_EXTRA_LOADSAVE_ACTION, LoadSaveAction::load); intent.PutEnumExtra<LoadSaveType>(INTENT_EXTRA_LOADSAVE_TYPE, LoadSaveType::landscape); ContextOpenIntent(&intent); } void RCT2StringToUTF8Self(char* buffer, size_t length) { if (length > 0) { auto temp = RCT2StringToUTF8(buffer, RCT2LanguageId::englishUK); String::safeUtf8Copy(buffer, temp.data(), length); } } static void FixGuestsHeadingToParkCount() { uint32_t guestsHeadingToPark = 0; for (auto* peep : EntityList<Guest>()) { if (peep->OutsideOfPark && peep->State != PeepState::leavingPark) { guestsHeadingToPark++; } } auto& park = getGameState().park; if (park.numGuestsHeadingForPark != guestsHeadingToPark) { LOG_VERBOSE( "Corrected bad amount of guests heading to park: %u -> %u", park.numGuestsHeadingForPark, guestsHeadingToPark); } park.numGuestsHeadingForPark = guestsHeadingToPark; } static void FixGuestCount() { // Recalculates peep count after loading a save to fix corrupted files uint32_t guestCount = 0; for (auto guest : EntityList<Guest>()) { if (!guest->OutsideOfPark) { guestCount++; } } auto& park = getGameState().park; if (park.numGuestsInPark != guestCount) { LOG_VERBOSE("Corrected bad amount of guests in park: %u -> %u", park.numGuestsInPark, guestCount); } park.numGuestsInPark = guestCount; } static void FixPeepsWithInvalidRideReference() { // Peeps to remove have to be cached here, as removing them from within the loop breaks iteration std::vector<Peep*> peepsToRemove; // Fix possibly invalid field values for (auto peep : EntityList<Guest>()) { if (peep->CurrentRideStation.ToUnderlying() >= OpenRCT2::Limits::kMaxStationsPerRide) { const auto srcStation = peep->CurrentRideStation; const auto rideIdx = peep->CurrentRide; if (rideIdx.IsNull()) { continue; } Ride* ride = GetRide(rideIdx); if (ride == nullptr) { LOG_WARNING("Couldn't find ride %u, resetting ride on peep %u", rideIdx, peep->Id); peep->CurrentRide = RideId::GetNull(); continue; } auto curName = peep->GetName(); LOG_WARNING( "Peep %u (%s) has invalid ride station = %u for ride %u.", peep->Id, curName.c_str(), srcStation.ToUnderlying(), rideIdx); auto station = RideGetFirstValidStationExit(*ride); if (station.IsNull()) { LOG_WARNING("Couldn't find station, removing peep %u", peep->Id); peepsToRemove.push_back(peep); } else { LOG_WARNING("Amending ride station to %u.", station); peep->CurrentRideStation = station; } } } if (!peepsToRemove.empty()) { // Some broken saves have broken spatial indexes getGameState().entities.ResetEntitySpatialIndices(); } for (auto ptr : peepsToRemove) { ptr->Remove(); } } static void FixInvalidSurfaces() { // Fixes broken saves where a surface element could be null // and broken saves with incorrect invisible map border tiles for (int32_t y = 0; y < kMaximumMapSizeTechnical; y++) { for (int32_t x = 0; x < kMaximumMapSizeTechnical; x++) { auto* surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y }); if (surfaceElement == nullptr) { LOG_ERROR("Null map element at x = %d and y = %d. Fixing...", x, y); surfaceElement = TileElementInsert<SurfaceElement>(TileCoordsXYZ{ x, y, 14 }.ToCoordsXYZ(), 0b0000); if (surfaceElement == nullptr) { LOG_ERROR("Unable to fix: Map element limit reached."); return; } } // Fix the invisible border tiles. // At this point, we can be sure that surfaceElement is not NULL. auto& gameState = getGameState(); if (x == 0 || x == gameState.mapSize.x - 1 || y == 0 || y == gameState.mapSize.y - 1) { surfaceElement->SetBaseZ(kMinimumLandZ); surfaceElement->SetClearanceZ(kMinimumLandZ); surfaceElement->SetSlope(0); surfaceElement->SetWaterHeight(0); } } } } // OpenRCT2 workaround to recalculate some values which are saved redundantly in the save to fix corrupted files. // For example recalculate guest count by looking at all the guests instead of trusting the value in the file. void GameFixSaveVars() { FixGuestsHeadingToParkCount(); FixGuestCount(); FixPeepsWithInvalidRideReference(); FixInvalidSurfaces(); ResearchFix(); // Fix banners which share their index BannerApplyFixes(); // Fix invalid vehicle sprite sizes, thus preventing visual corruption of sprites FixInvalidVehicleSpriteSizes(); // Fix gParkEntrance locations for which the tile_element no longer exists ParkEntranceFixLocations(); UpdateConsolidatedPatrolAreas(); MapCountRemainingLandRights(); // Update sprite bounds, rather than relying on stored data PeepUpdateAllBoundingBoxes(); } void GameLoadInit() { auto* context = GetContext(); IGameStateSnapshots* snapshots = context->GetGameStateSnapshots(); snapshots->Reset(); context->SetActiveScene(context->GetGameScene()); if (!gLoadKeepWindowsOpen) { ViewportInitAll(); GameCreateWindows(); } else { auto* mainWindow = WindowGetMain(); WindowUnfollowSprite(*mainWindow); } auto windowManager = context->GetUiContext().GetWindowManager(); auto& gameState = getGameState(); windowManager->SetMainView(gameState.savedView, gameState.savedViewZoom, gameState.savedViewRotation); if (Network::GetMode() != Network::Mode::client) { GameActions::ClearQueue(); } getGameState().entities.ResetEntitySpatialIndices(); ResetAllSpriteQuadrantPlacements(); gWindowUpdateTicks = 0; gCurrentRealTimeTicks = 0; LoadPalette(); if (!gOpenRCT2Headless) { windowManager->BroadcastIntent(Intent(INTENT_ACTION_SET_DEFAULT_SCENERY_CONFIG)); windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_NEW_RIDES)); windowManager->BroadcastIntent(Intent(INTENT_ACTION_CLEAR_TILE_INSPECTOR_CLIPBOARD)); } gGameSpeed = 1; } void GameLoadScripts() { #ifdef ENABLE_SCRIPTING GetContext()->GetScriptEngine().LoadTransientPlugins(); #endif } void GameUnloadScripts() { #ifdef ENABLE_SCRIPTING GetContext()->GetScriptEngine().UnloadTransientPlugins(); #endif } void GameNotifyMapChange() { #ifdef ENABLE_SCRIPTING // Ensure we don't get a two lots of change events if (_mapChangedExpected) return; using namespace OpenRCT2::Scripting; auto& scriptEngine = GetContext()->GetScriptEngine(); auto& hookEngine = scriptEngine.GetHookEngine(); hookEngine.Call(HookType::mapChange, false); _mapChangedExpected = true; #endif } void GameNotifyMapChanged() { #ifdef ENABLE_SCRIPTING using namespace OpenRCT2::Scripting; auto& scriptEngine = GetContext()->GetScriptEngine(); auto& hookEngine = scriptEngine.GetHookEngine(); hookEngine.Call(HookType::mapChanged, false); _mapChangedExpected = false; #endif } /** * * rct2: 0x0069E9A7 * Call after a rotation or loading of a save to reset sprite quadrants */ void ResetAllSpriteQuadrantPlacements() { for (EntityId::UnderlyingType i = 0; i < kMaxEntities; i++) { auto* spr = getGameState().entities.GetEntity(EntityId::FromUnderlying(i)); if (spr != nullptr && spr->Type != EntityType::null) { spr->MoveTo(spr->GetLocation()); } } } void SaveGame() { if (!gFirstTimeSaving && !gIsAutosaveLoaded) { #ifndef __EMSCRIPTEN__ const auto savePath = Path::WithExtension(gScenarioSavePath, ".park"); SaveGameWithName(savePath); #else const auto savePath = Path::WithExtension("save", ".park"); SaveGameWithName(savePath); EmscriptenSaveGame(false, false, LoadSaveType::park); #endif } else { SaveGameAs(); } } void SaveGameCmd(u8string_view name /* = {} */) { if (name.empty()) { const auto savePath = Path::WithExtension(gScenarioSavePath, ".park"); SaveGameWithName(savePath); } else { auto& env = GetContext()->GetPlatformEnvironment(); auto savePath = Path::Combine(env.GetDirectoryPath(DirBase::user, DirId::saves), u8string(name) + u8".park"); SaveGameWithName(savePath); } } void SaveGameWithName(u8string_view name) { LOG_VERBOSE("Saving to %s", u8string(name).c_str()); auto& gameState = getGameState(); if (ScenarioSave(gameState, name, Config::Get().general.savePluginData ? 1 : 0)) { LOG_VERBOSE("Saved to %s", u8string(name).c_str()); gCurrentLoadedPath = name; gIsAutosaveLoaded = false; gScreenAge = 0; } } std::unique_ptr<Intent> CreateSaveGameAsIntent() { auto name = Path::GetFileNameWithoutExtension(gScenarioSavePath); auto intent = std::make_unique<Intent>(WindowClass::loadsave); intent->PutEnumExtra<LoadSaveAction>(INTENT_EXTRA_LOADSAVE_ACTION, LoadSaveAction::save); intent->PutEnumExtra<LoadSaveType>(INTENT_EXTRA_LOADSAVE_TYPE, LoadSaveType::park); intent->PutExtra(INTENT_EXTRA_PATH, name); return intent; } void SaveGameAs() { #ifdef __EMSCRIPTEN__ EmscriptenResetAutosave(); #endif auto intent = CreateSaveGameAsIntent(); ContextOpenIntent(intent.get()); } #ifndef __EMSCRIPTEN__ static void LimitAutosaveCount(const size_t numberOfFilesToKeep, bool processLandscapeFolder) { size_t autosavesCount = 0; size_t numAutosavesToDelete = 0; auto& environment = GetContext()->GetPlatformEnvironment(); auto folderDirectory = environment.GetDirectoryPath(DirBase::user, DirId::saves); char const* fileFilter = "autosave_*.park"; if (processLandscapeFolder) { folderDirectory = environment.GetDirectoryPath(DirBase::user, DirId::landscapes); fileFilter = "autosave_*.park"; } const u8string filter = Path::Combine(folderDirectory, "autosave", fileFilter); // At first, count how many autosaves there are { auto scanner = Path::ScanDirectory(filter, false); while (scanner->Next()) { autosavesCount++; } } // If there are fewer autosaves than the number of files to keep we don't need to delete anything if (autosavesCount <= numberOfFilesToKeep) { return; } std::vector<u8string> autosaveFiles; { auto scanner = Path::ScanDirectory(filter, false); for (size_t i = 0; i < autosavesCount; i++) { if (scanner->Next()) { autosaveFiles.emplace_back(Path::Combine(folderDirectory, "autosave", scanner->GetPathRelative())); } } } std::sort(autosaveFiles.begin(), autosaveFiles.end(), [](const auto& saveFile0, const auto& saveFile1) { return saveFile0.compare(saveFile1) < 0; }); // Calculate how many saves we need to delete. numAutosavesToDelete = autosaveFiles.size() - numberOfFilesToKeep; for (size_t i = 0; numAutosavesToDelete > 0; i++, numAutosavesToDelete--) { if (!File::Delete(autosaveFiles[i])) { LOG_WARNING("Failed to delete autosave file: %s", autosaveFiles[i].data()); } } } void GameAutosave() { auto subDirectory = DirId::saves; const char* fileExtension = ".park"; uint32_t saveFlags = 0x80000000; if (isInEditorMode()) { subDirectory = DirId::landscapes; fileExtension = ".park"; saveFlags |= 2; } // Retrieve current time auto currentDate = Platform::GetDateLocal(); auto currentTime = Platform::GetTimeLocal(); utf8 timeName[44]; snprintf( timeName, sizeof(timeName), "autosave_%04u-%02u-%02u_%02u-%02u-%02u%s", currentDate.year, currentDate.month, currentDate.day, currentTime.hour, currentTime.minute, currentTime.second, fileExtension); int32_t autosavesToKeep = Config::Get().general.autosaveAmount; LimitAutosaveCount(autosavesToKeep - 1, isInEditorMode()); auto& env = GetContext()->GetPlatformEnvironment(); auto autosaveDir = Path::Combine(env.GetDirectoryPath(DirBase::user, subDirectory), u8"autosave"); Path::CreateDirectory(autosaveDir); auto path = Path::Combine(autosaveDir, timeName); auto backupFileName = u8string(u8"autosave") + fileExtension + u8".bak"; auto backupPath = Path::Combine(autosaveDir, backupFileName); if (File::Exists(path)) { File::Copy(path, backupPath, true); } auto& gameState = getGameState(); if (!ScenarioSave(gameState, path, saveFlags)) Console::Error::WriteLine("Could not autosave the scenario. Is the save folder writeable?"); } #else void GameAutosave() { const auto savePath = Path::WithExtension("save", ".park"); SaveGameWithName(savePath); EmscriptenSaveGame(false, true, LoadSaveType::park); } #endif // __EMSCRIPTEN__ static void GameLoadOrQuitNoSavePromptCallback(ModalResult result, const utf8* path) { if (result == ModalResult::ok) { GameNotifyMapChange(); GameUnloadScripts(); auto* windowMgr = Ui::GetWindowManager(); windowMgr->CloseByClass(WindowClass::editorObjectSelection); GameLoadScripts(); GameNotifyMapChanged(); gIsAutosaveLoaded = gIsAutosave; gFirstTimeSaving = false; } } static void NewGameWindowCallback(const utf8* path) { // Closing this will cause a Ride window to pop up, so we have to do this to ensure that // no windows are open (besides the toolbars and LoadSave window). auto* windowMgr = Ui::GetWindowManager(); windowMgr->CloseByClass(WindowClass::rideConstruction); windowMgr->CloseAllExceptClass(WindowClass::loadsave); GameNotifyMapChange(); GetContext()->LoadParkFromFile(path, false, true); GameLoadScripts(); GameNotifyMapChanged(); #ifdef __EMSCRIPTEN__ EmscriptenResetAutosave(); #endif } /** * * rct2: 0x0066DB79 */ void GameLoadOrQuitNoSavePrompt() { auto& gameState = getGameState(); switch (gSavePromptMode) { case PromptMode::saveBeforeLoad: { auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::CloseSavePrompt); GameActions::Execute(&loadOrQuitAction, gameState); ToolCancel(); if (gLegacyScene == LegacyScene::scenarioEditor) { LoadLandscape(); } else { auto intent = Intent(WindowClass::loadsave); intent.PutEnumExtra<LoadSaveAction>(INTENT_EXTRA_LOADSAVE_ACTION, LoadSaveAction::load); intent.PutEnumExtra<LoadSaveType>(INTENT_EXTRA_LOADSAVE_TYPE, LoadSaveType::park); intent.PutExtra(INTENT_EXTRA_CALLBACK, reinterpret_cast<CloseCallback>(GameLoadOrQuitNoSavePromptCallback)); ContextOpenIntent(&intent); } break; } case PromptMode::saveBeforeQuit: { auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::CloseSavePrompt); GameActions::Execute(&loadOrQuitAction, gameState); ToolCancel(); if (gInputFlags.has(InputFlag::rightMousePressed)) { gInputFlags.unset(InputFlag::rightMousePressed); } GameResetSpeed(); gFirstTimeSaving = true; GameNotifyMapChange(); GameUnloadScripts(); #ifdef __EMSCRIPTEN__ EmscriptenResetAutosave(); #endif auto* context = OpenRCT2::GetContext(); context->SetActiveScene(context->GetTitleScene()); break; } case PromptMode::saveBeforeNewGame: { auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::CloseSavePrompt); GameActions::Execute(&loadOrQuitAction, gameState); ToolCancel(); auto intent = Intent(WindowClass::scenarioSelect); intent.PutExtra(INTENT_EXTRA_CALLBACK, reinterpret_cast<CloseCallback>(NewGameWindowCallback)); ContextOpenIntent(&intent); break; } default: GameUnloadScripts(); getGameState().entities.ResetAllEntities(); GetContext()->Finish(); break; } } void StartSilentRecord() { std::string name = Path::Combine( OpenRCT2::GetContext()->GetPlatformEnvironment().GetDirectoryPath(OpenRCT2::DirBase::user), u8"debug_replay.parkrep"); auto* replayManager = OpenRCT2::GetContext()->GetReplayManager(); if (replayManager->StartRecording(name, OpenRCT2::k_MaxReplayTicks, OpenRCT2::IReplayManager::RecordType::SILENT)) { OpenRCT2::ReplayRecordInfo info; replayManager->GetCurrentReplayInfo(info); gSilentRecordingName = info.FilePath; const char* logFmt = "Silent replay recording started: (%s) %s\n"; Console::WriteLine(logFmt, info.Name.c_str(), info.FilePath.c_str()); } } bool StopSilentRecord() { auto* replayManager = OpenRCT2::GetContext()->GetReplayManager(); if (!replayManager->IsRecording() && !replayManager->IsNormalising()) { return false; } OpenRCT2::ReplayRecordInfo info; replayManager->GetCurrentReplayInfo(info); if (replayManager->StopRecording()) { const char* logFmt = "Replay recording stopped: (%s) %s\n" " Ticks: %u\n" " Commands: %u\n" " Checksums: %u"; Console::WriteLine(logFmt, info.Name.c_str(), info.FilePath.c_str(), info.Ticks, info.NumCommands, info.NumChecksums); return true; } return false; } void PrepareMapForSave() { ViewportSetSavedView(); #ifdef ENABLE_SCRIPTING auto& scriptEngine = GetContext()->GetScriptEngine(); auto& hookEngine = scriptEngine.GetHookEngine(); if (hookEngine.HasSubscriptions(OpenRCT2::Scripting::HookType::mapSave)) { hookEngine.Call(OpenRCT2::Scripting::HookType::mapSave, false); } #endif }
412
0.980283
1
0.980283
game-dev
MEDIA
0.966588
game-dev
0.754775
1
0.754775
tamtaasatiani/pong-plusplus
7,290
pong/lib/SDL2-2.30.5/include/SDL_timer.h
/* 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. */ #ifndef SDL_timer_h_ #define SDL_timer_h_ /** * \file SDL_timer.h * * Header for the SDL time management routines. */ #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * Get the number of milliseconds since SDL library initialization. * * This value wraps if the program runs for more than ~49 days. * * This function is not recommended as of SDL 2.0.18; use SDL_GetTicks64() * instead, where the value doesn't wrap every ~49 days. There are places in * SDL where we provide a 32-bit timestamp that can not change without * breaking binary compatibility, though, so this function isn't officially * deprecated. * * \returns an unsigned 32-bit value representing the number of milliseconds * since the SDL library initialized. * * \since This function is available since SDL 2.0.0. * * \sa SDL_TICKS_PASSED */ extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void); /** * Get the number of milliseconds since SDL library initialization. * * Note that you should not use the SDL_TICKS_PASSED macro with values * returned by this function, as that macro does clever math to compensate for * the 32-bit overflow every ~49 days that SDL_GetTicks() suffers from. 64-bit * values from this function can be safely compared directly. * * For example, if you want to wait 100 ms, you could do this: * * ```c * const Uint64 timeout = SDL_GetTicks64() + 100; * while (SDL_GetTicks64() < timeout) { * // ... do work until timeout has elapsed * } * ``` * * \returns an unsigned 64-bit value representing the number of milliseconds * since the SDL library initialized. * * \since This function is available since SDL 2.0.18. */ extern DECLSPEC Uint64 SDLCALL SDL_GetTicks64(void); /** * Compare 32-bit SDL ticks values, and return true if `A` has passed `B`. * * This should be used with results from SDL_GetTicks(), as this macro * attempts to deal with the 32-bit counter wrapping back to zero every ~49 * days, but should _not_ be used with SDL_GetTicks64(), which does not have * that problem. * * For example, with SDL_GetTicks(), if you want to wait 100 ms, you could * do this: * * ```c * const Uint32 timeout = SDL_GetTicks() + 100; * while (!SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) { * // ... do work until timeout has elapsed * } * ``` * * Note that this does not handle tick differences greater * than 2^31 so take care when using the above kind of code * with large timeout delays (tens of days). */ #define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0) /** * Get the current value of the high resolution counter. * * This function is typically used for profiling. * * The counter values are only meaningful relative to each other. Differences * between values can be converted to times by using * SDL_GetPerformanceFrequency(). * * \returns the current counter value. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GetPerformanceFrequency */ extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceCounter(void); /** * Get the count per second of the high resolution counter. * * \returns a platform-specific count per second. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GetPerformanceCounter */ extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceFrequency(void); /** * Wait a specified number of milliseconds before returning. * * This function waits a specified number of milliseconds before returning. It * waits at least the specified time, but possibly longer due to OS * scheduling. * * \param ms the number of milliseconds to delay * * \since This function is available since SDL 2.0.0. */ extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms); /** * Function prototype for the timer callback function. * * The callback function is passed the current timer interval and returns * the next timer interval. If the returned value is the same as the one * passed in, the periodic alarm continues, otherwise a new alarm is * scheduled. If the callback returns 0, the periodic alarm is cancelled. */ typedef Uint32 (SDLCALL * SDL_TimerCallback) (Uint32 interval, void *param); /** * Definition of the timer ID type. */ typedef int SDL_TimerID; /** * Call a callback function at a future time. * * If you use this function, you must pass `SDL_INIT_TIMER` to SDL_Init(). * * The callback function is passed the current timer interval and the user * supplied parameter from the SDL_AddTimer() call and should return the next * timer interval. If the value returned from the callback is 0, the timer is * canceled. * * The callback is run on a separate thread. * * Timers take into account the amount of time it took to execute the * callback. For example, if the callback took 250 ms to execute and returned * 1000 (ms), the timer would only wait another 750 ms before its next * iteration. * * Timing may be inexact due to OS scheduling. Be sure to note the current * time with SDL_GetTicks() or SDL_GetPerformanceCounter() in case your * callback needs to adjust for variances. * * \param interval the timer delay, in milliseconds, passed to `callback` * \param callback the SDL_TimerCallback function to call when the specified * `interval` elapses * \param param a pointer that is passed to `callback` * \returns a timer ID or 0 if an error occurs; call SDL_GetError() for more * information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_RemoveTimer */ extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param); /** * Remove a timer created with SDL_AddTimer(). * * \param id the ID of the timer to remove * \returns SDL_TRUE if the timer is removed or SDL_FALSE if the timer wasn't * found. * * \since This function is available since SDL 2.0.0. * * \sa SDL_AddTimer */ extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID id); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_timer_h_ */ /* vi: set ts=4 sw=4 expandtab: */
412
0.769209
1
0.769209
game-dev
MEDIA
0.405209
game-dev
0.691662
1
0.691662
db0/hypnagonia
3,530
src/dreamscape/CombatElements/CombatSignifier.gd
class_name CombatSignifier extends Control enum SIGNIFIER_TYPES { NONE COMBAT_EFFECT INTENT ARTIFACT MEMORY } export(StreamTexture) var icon_container_texture :StreamTexture export(StreamTexture) var icon_extra_container_texture :StreamTexture export(SIGNIFIER_TYPES) var signifier_type: int var amount : int setget update_amount onready var signifier_label := $Signifier/Label onready var signifier_icon := $Signifier/Icon onready var signifier_icon_container := $Signifier/IconContainer onready var signifier_extra_container := $Signifier/ExtraContainer onready var signifier_amount := $MC/Amount onready var decription_popup := $Description onready var decription_label := $Description/VBC/Label onready var focus_info := $Description/VBC/DetailPanels onready var anims = $AnimationPlayer var canonical_name: String func _ready() -> void: if icon_container_texture: signifier_icon_container.texture = CFUtils.convert_texture_to_image( icon_container_texture, true) if icon_extra_container_texture: signifier_extra_container.texture = CFUtils.convert_texture_to_image( icon_extra_container_texture, true) func setup(signifier_details: Dictionary, signifier_name: String) -> void: # print_debug("Setting up intent: " + intent_name) canonical_name = signifier_name if signifier_details.has("icon") and signifier_details.icon: signifier_icon.texture = CFUtils.convert_texture_to_image(signifier_details.icon, true) signifier_label.visible = false else: signifier_icon.visible = false signifier_label.text = signifier_name[0] if signifier_details.has("amount") and not signifier_details.get("hide_amount_in_intent"): update_amount(signifier_details.amount) elif signifier_details.has("modification") and signifier_details.get("show_modification_in_intent"): update_amount(signifier_details.modification) else: signifier_amount.visible = false if signifier_details.has("description"): decription_label.bbcode_text = signifier_details.description.format(Terms.get_bbcode_formats(18)) else: decription_label.text = signifier_name anims.play("Spawned") func _on_CombatSingifier_mouse_entered() -> void: decription_popup.visible = true decription_popup.rect_global_position = rect_global_position + Vector2(20,-decription_popup.rect_size.y) if decription_popup.rect_global_position.x + decription_popup.rect_size.x > get_viewport().size.x: decription_popup.rect_global_position.x = get_viewport().size.x - decription_popup.rect_size.x - 10 func _on_CombatSingifier_mouse_exited() -> void: decription_popup.visible = false func update_amount(value) -> void: # If the value we're trying to assign is a string # It's propable a per definition, so we don't show it # We'll wait for the proper integer from the recalculations instead. if typeof(value) == TYPE_STRING: return amount = value signifier_amount.text = str(value) func update_amount_animated(value, increase := true) -> void: if typeof(value) == TYPE_STRING: return var animation = "Increased" if not increase: animation = "Decreased" amount = value if anims.current_animation == "Spawned": return anims.play(animation) func set_amount_from_int() -> void: signifier_amount.text = str(amount) func queue_free() -> void: if signifier_type == SIGNIFIER_TYPES.INTENT: .queue_free() return # First thing we do, is we remove all further scripting while the animations are playing var anim_player = anims anim_player.play("Despawned") yield(anim_player,"animation_finished") .queue_free()
412
0.79221
1
0.79221
game-dev
MEDIA
0.575067
game-dev,desktop-app
0.872749
1
0.872749
salutesh/DayZ-Expansion-Scripts
21,916
DayZExpansion/AI/Scripts/4_World/DayZExpansion_AI/Classes/Patrols/eAIDynamicPatrol.c
class eAIDynamicPatrol : eAIPatrol { static ExpansionAIPatrolSettings s_AIPatrolSettings; private static int s_PatrolCount; static ref map<string, ref ExpansionAIPatrolLoadBalancing> s_LoadBalancing = new map<string, ref ExpansionAIPatrolLoadBalancing>; static ref ExpansionAIPatrolLoadBalancing s_LoadBalancingGlobal; static bool s_LoadBalancing_IsScheduled; ref ExpansionAIDynamicSpawnBase m_Config; ref ExpansionAIPatrolLoadBalancing m_LoadBalancing; ref ExpansionAIPatrolLoadBalancingTracker m_PatrolCountTracker; vector m_Position; autoptr array<vector> m_Waypoints; eAIWaypointBehavior m_WaypointBehaviour; int m_WaypointIdx; float m_MinimumRadius; float m_MaximumRadius; float m_DespawnRadius; float m_MovementSpeedLimit; float m_MovementThreatSpeedLimit; ref ExpansionArray<string> m_Units; int m_NumberOfAI; int m_RespawnTime; // negative respawn time = patrol won't respawn int m_DespawnTime; // if all players outside despawn radius, ticks up time. When despawn time reached, patrol is deleted ref eAIFaction m_Faction; ref eAIFormation m_Formation; float m_FormationScale; float m_AccuracyMin; // zero or negative = use general setting float m_AccuracyMax; // zero or negative = use general setting float m_ThreatDistanceLimit; // zero or negative = use general setting float m_NoiseInvestigationDistanceLimit; // zero or negative = use general setting float m_DamageMultiplier; // zero or negative = use general setting float m_DamageReceivedMultiplier; // zero or negative = use general setting eAIGroup m_Group; float m_TimeSinceLastSpawn; bool m_CanSpawn; private bool m_IsSpawned; private bool m_WasGroupDestroyed; private eAIDynamicPatrolSphereTrigger m_Trigger; private string m_NameForLog; void ~eAIDynamicPatrol() { if (GetGame() && m_Trigger) GetGame().ObjectDelete(m_Trigger); } /** * @brief Creates a dynamic patrol which spawns a patrol under the right conditions. * * @param config * @param startpos the position that the trigger distance is calculated from. If zero vector, waypoint from config is used * @param autoStart * * @return the patrol instance */ static eAIDynamicPatrol CreateEx(ExpansionAIDynamicSpawnBase config, vector startpos, bool autoStart = true) { return eAIDynamicPatrolT<eAIDynamicPatrol>.CreateEx(config, startpos, autoStart); } bool Setup(ExpansionAIDynamicSpawnBase config, vector startpos, bool autoStart = true) { InitSettings(); m_Config = config; if (!m_Config.LoadBalancingCategory) { if (m_Config.ObjectClassName) { m_Config.LoadBalancingCategory = "ObjectPatrol"; } else { switch (m_Config.ClassName()) { case "ExpansionQuestAISpawn": m_Config.LoadBalancingCategory = "Quest"; break; default: m_Config.LoadBalancingCategory = "Patrol"; break; } } } if (!s_AIPatrolSettings.LoadBalancingCategories[m_Config.LoadBalancingCategory]) m_Config.LoadBalancingCategory = "Global"; LoadBalancing_Update(); if (config.NumberOfAI == 0) { EXError.Error(null, "NumberOfAI shouldn't be set to 0", {}); return false; } m_Waypoints = config.GetWaypoints(startpos); if (config.Persist && config.m_BaseName) { string fileName = eAIGroup.GetStorageDirectory(config.m_BaseName) + eAIGroup.BASENAME; if (FileExist(fileName)) { eAIGroup.ReadPosition(fileName, startpos); if (config.GetBehaviour() != eAIWaypointBehavior.ROAMING) { //! Since this patrol is using waypoints, find the closest one float minDistSq = float.MAX; foreach (int idx, vector waypoint: m_Waypoints) { float distSq = vector.DistanceSq(startpos, waypoint); if (distSq < minDistSq) { minDistSq = distSq; m_WaypointIdx = idx; } } } } else { startpos = GetInitialSpawnPosition(); } } else { startpos = GetInitialSpawnPosition(); } if (startpos == vector.Zero) { EXError.Error(null, "Invalid spawn position - waypoint is set to zero vector <0 0 0>", {}); return false; } m_Position = startpos; if (config.FormationScale <= 0) m_FormationScale = s_AIPatrolSettings.FormationScale; else m_FormationScale = config.FormationScale; if (config.RespawnTime == -2) m_RespawnTime = s_AIPatrolSettings.RespawnTime; else m_RespawnTime = config.RespawnTime; if (config.DespawnTime < 0) m_DespawnTime = s_AIPatrolSettings.DespawnTime; else m_DespawnTime = config.DespawnTime; if (config.MinDistRadius <= 0) m_MinimumRadius = s_AIPatrolSettings.MinDistRadius; else m_MinimumRadius = config.MinDistRadius; if (config.MaxDistRadius <= 0) m_MaximumRadius = s_AIPatrolSettings.MaxDistRadius; else m_MaximumRadius = config.MaxDistRadius; if (config.DespawnRadius <= 0) m_DespawnRadius = s_AIPatrolSettings.DespawnRadius; else m_DespawnRadius = config.DespawnRadius; if (m_MinimumRadius > m_MaximumRadius) { EXError.Error(null, "MinDistRadius (" + m_MinimumRadius + ") should be smaller than MaxDistRadius (" + m_MaximumRadius + ")", {}); float actualMax = m_MinimumRadius; m_MinimumRadius = m_MaximumRadius; m_MaximumRadius = actualMax; } float accuracyMin; if (config.AccuracyMin <= 0) accuracyMin = s_AIPatrolSettings.AccuracyMin; else accuracyMin = config.AccuracyMin; float accuracyMax; if (config.AccuracyMin <= 0) accuracyMax = s_AIPatrolSettings.AccuracyMax; else accuracyMax = config.AccuracyMax; float threatDistanceLimit; if (config.ThreatDistanceLimit <= 0) threatDistanceLimit = s_AIPatrolSettings.ThreatDistanceLimit; else threatDistanceLimit = config.ThreatDistanceLimit; float noiseDistanceLimit; if (config.NoiseInvestigationDistanceLimit <= 0) noiseDistanceLimit = s_AIPatrolSettings.NoiseInvestigationDistanceLimit; else noiseDistanceLimit = config.NoiseInvestigationDistanceLimit; float damageMultiplier; if (config.DamageMultiplier <= 0) damageMultiplier = s_AIPatrolSettings.DamageMultiplier; else damageMultiplier = config.DamageMultiplier; float damageReceivedMultiplier; if ( config.DamageReceivedMultiplier <= 0 ) damageReceivedMultiplier = s_AIPatrolSettings.DamageReceivedMultiplier; else damageReceivedMultiplier = config.DamageReceivedMultiplier; SetAccuracy(accuracyMin, accuracyMax); SetThreatDistanceLimit(threatDistanceLimit); SetNoiseInvestigationDistanceLimit(noiseDistanceLimit); SetDamageMultiplier(damageMultiplier); SetDamageReceivedMultiplier(damageReceivedMultiplier); if (config.Units && config.Units.Count()) SetUnits(config.Units); m_CanSpawn = true; if (autoStart) Start(); return true; } vector GetInitialSpawnPosition() { int startPosIndex; //! For object patrols, we always use random waypoint as startpoint, for patrols with fixed waypoints, only if random is set if (m_Config.ObjectClassName || m_Config.UseRandomWaypointAsStartPoint) startPosIndex = Math.RandomInt(0, m_Waypoints.Count()); return m_Waypoints[startPosIndex]; } static bool InitSettings() { if ( !s_AIPatrolSettings ) { s_AIPatrolSettings = GetExpansionSettings().GetAIPatrol(); LoadBalancing_Setup(); } return s_AIPatrolSettings.Enabled; } void SetAccuracy(float accuracyMin, float accuracyMax) { m_AccuracyMin = accuracyMin; m_AccuracyMax = accuracyMax; } void SetThreatDistanceLimit(float distance) { m_ThreatDistanceLimit = distance; } void SetNoiseInvestigationDistanceLimit(float distance) { m_NoiseInvestigationDistanceLimit = distance; } void SetDamageMultiplier(float multiplier) { m_DamageMultiplier = multiplier; } void SetDamageReceivedMultiplier(float multiplier) { m_DamageReceivedMultiplier = multiplier; } void SetUnits(TStringArray units) { if (m_Units) m_Units.Clear(); else m_Units = new ExpansionArray<string>; m_Units.InsertAll(units); } private eAIBase CreateAI(vector pos) { #ifdef EXTRACE_DIAG auto trace = EXTrace.Start(EXTrace.AI, this); #endif string unit; if (m_Units) unit = m_Units.GetQuasiRandomElementAvoidRepetition(); else unit = eAISurvivor.GetQuasiRandom(); return eAIBase.Cast(GetGame().CreateObject(unit, pos)); } private eAIBase SpawnAI(vector pos) { #ifdef EXTRACE_DIAG auto trace = EXTrace.Start(EXTrace.AI, this); #endif pos = ExpansionAIPatrol.GetPlacementPosition(pos); eAIBase ai = CreateAI(pos); if (!ai) return null; ai.SetPosition(pos); ExpansionHumanLoadout.Apply(ai, m_Config.Loadout, false); SetupAI(ai); return ai; } void SetupAI(eAIBase ai) { ai.SetMovementSpeedLimits(m_MovementSpeedLimit, m_MovementThreatSpeedLimit); ai.Expansion_SetCanBeLooted(m_Config.CanBeLooted); ai.eAI_SetUnlimitedReload(m_Config.UnlimitedReload); ai.eAI_SetAccuracy(m_AccuracyMin, m_AccuracyMax); ai.eAI_SetThreatDistanceLimit(m_ThreatDistanceLimit); ai.eAI_SetNoiseInvestigationDistanceLimit(m_NoiseInvestigationDistanceLimit); ai.eAI_SetDamageMultiplier(m_DamageMultiplier); ai.eAI_SetDamageReceivedMultiplier(m_DamageReceivedMultiplier); ai.eAI_SetSniperProneDistanceThreshold(m_Config.SniperProneDistanceThreshold); ai.eAI_SetLootingBehavior(m_Config.GetLootingBehaviour()); } bool WasGroupDestroyed() { if (!m_Group) return false; if (m_WasGroupDestroyed) return true; if (m_Group.Count()) return false; m_WasGroupDestroyed = true; Log(m_NameForLog + " bots were wiped out (spawn position " + m_Position + ", " + (m_NumberOfAI - m_Group.Count()) + "/" + m_NumberOfAI + " deceased)"); m_Position = GetInitialSpawnPosition(); //! Reset spawn position for next spawn if (s_PatrolCount) UpdatePatrolCount(-1); return true; } bool CanSpawn() { if (m_Group) return false; if (!m_CanSpawn) return false; return CanStay(1); } bool CanStay(int delta) { #ifdef SERVER if (m_LoadBalancing && m_LoadBalancing != s_LoadBalancingGlobal) { if (m_LoadBalancing.MaxPatrols > -1 && m_PatrolCountTracker.m_PatrolCount + delta > m_LoadBalancing.MaxPatrols) return false; } if (s_LoadBalancingGlobal && s_LoadBalancingGlobal.MaxPatrols > -1 && s_PatrolCount + delta > s_LoadBalancingGlobal.MaxPatrols) return false; #endif return true; } override void LoadBalancing_Update() { m_LoadBalancing = s_LoadBalancing[m_Config.LoadBalancingCategory]; if (m_LoadBalancing) m_PatrolCountTracker = m_LoadBalancing.m_PatrolCountTracker; if (m_Group) m_Group.m_Leave = !CanStay(0); #ifdef DIAG_DEVELOPER EXTrace.Print(EXTrace.AI, this, m_Config.Name + " LoadBalancing_Update category " + m_Config.LoadBalancingCategory + " " + m_LoadBalancing); #endif } static void LoadBalancing_Setup() { int playerCount = PlayerBase.Expansion_GetOnlinePlayersCount(); s_LoadBalancingGlobal = null; foreach (string name, auto categories: s_AIPatrolSettings.LoadBalancingCategories) { s_LoadBalancing[name] = null; foreach (auto loadBalancing: categories) { if (playerCount < loadBalancing.MinPlayers || (loadBalancing.MaxPlayers > 0 && playerCount > loadBalancing.MaxPlayers)) continue; #ifdef DIAG_DEVELOPER EXTrace.Print(EXTrace.AI, eAIDynamicPatrol, "LoadBalancing_Setup category " + name + " " + loadBalancing + " minPlayers " + loadBalancing.MinPlayers + " maxPlayers " + loadBalancing.MaxPlayers + " maxPatrols " + loadBalancing.MaxPatrols); #endif s_LoadBalancing[name] = loadBalancing; if (name == "Global") s_LoadBalancingGlobal = loadBalancing; break; } } } static void LoadBalancing_UpdateAll() { LoadBalancing_Setup(); foreach (auto patrol: s_AllPatrols) { patrol.LoadBalancing_Update(); } s_LoadBalancing_IsScheduled = false; } //! @note called everytime a player connects/disconnects static void LoadBalancing_Schedule() { if (s_LoadBalancing_IsScheduled) return; s_LoadBalancing_IsScheduled = true; GetGame().GetCallQueue(CALL_CATEGORY_SYSTEM).CallLater(LoadBalancing_UpdateAll, 10000, false); } void Spawn() { #ifdef EXTRACE_DIAG auto trace = EXTrace.Start(EXTrace.AI, this); #endif if (m_Group) return; m_TimeSinceLastSpawn = 0; m_CanSpawn = false; bool loaded; if (!m_WasGroupDestroyed && m_Config.Persist && m_Config.m_BaseName) { string fileName = eAIGroup.GetStorageDirectory(m_Config.m_BaseName) + eAIGroup.BASENAME; if (FileExist(fileName)) loaded = eAIGroup.Load(fileName, m_Group); } if (loaded) { m_NumberOfAI = m_Group.Count(); m_Faction = m_Group.GetFaction(); m_Group.m_CurrentWaypointIndex = m_WaypointIdx; SetNameForLog(); Log("Loaded " + m_NumberOfAI + " persistent " + m_NameForLog + " bots at " + m_Position); } else { if (m_Config.NumberOfAI < 0) { m_NumberOfAI = Math.RandomIntInclusive(1, -m_Config.NumberOfAI); } else { m_NumberOfAI = m_Config.NumberOfAI; } m_Faction = eAIFaction.Create(m_Config.Faction); if (m_Faction == null) m_Faction = new eAIFactionCivilian(); if (m_Config.Loadout == "") m_Config.Loadout = m_Faction.GetDefaultLoadout(); SetNameForLog(); Log("Spawning " + m_NumberOfAI + " " + m_NameForLog + " bots at " + m_Position); } m_WasGroupDestroyed = false; m_MovementSpeedLimit = m_Config.GetSpeed(); m_MovementThreatSpeedLimit = m_Config.GetThreatSpeed(); eAIBase ai; if (!loaded) { ai = SpawnAI(m_Position); m_Group = ai.GetGroup(); ai.m_eAI_GroupMemberID = m_Group.m_NextGroupMemberID++; } else { for (int i = 0; i < m_Group.Count(); i++) { if (Class.CastTo(ai, m_Group.GetMember(i))) { SetupAI(ai); } } } m_Group.m_Persist = m_Config.Persist; m_Group.m_BaseName = m_Config.m_BaseName; if (m_Group.m_Persist && m_Group.m_BaseName) eAIGroup.s_PersistentGroups.Insert(m_Group); m_Group.SetName(m_Config.Name); if (!loaded) m_Group.SetFaction(m_Faction); m_Formation = eAIFormation.Create(m_Config.Formation); if (m_Formation == null) m_Formation = new eAIFormationVee(); m_Formation.SetScale(m_FormationScale); m_Formation.SetLooseness(m_Config.FormationLooseness); m_Group.SetFormation(m_Formation); m_WaypointBehaviour = m_Config.GetBehaviour(); if (!loaded && m_NumberOfAI > 1) m_Group.SetWaypointBehaviour(eAIWaypointBehavior.HALT); //! Only start moving after all AI spawned else m_Group.SetWaypointBehaviour(m_WaypointBehaviour); foreach (int idx, vector waypoint: m_Waypoints) { m_Group.AddWaypoint(waypoint); if (waypoint == m_Position) { m_Group.m_CurrentWaypointIndex = idx; m_Group.m_CurrentWaypoint = waypoint; if (idx != 0 && Math.RandomIntInclusive(0, 1)) m_Group.m_BackTracking = true; } } if (!loaded && m_NumberOfAI > 1) GetGame().GetCallQueue(CALL_CATEGORY_SYSTEM).Call(SpawnAI_Deferred, 1); m_IsSpawned = true; UpdatePatrolCount(1); } void SpawnAI_Deferred(int i) { #ifdef EXTRACE_DIAG auto trace = EXTrace.Start(EXTrace.AI, this); #endif if (m_Group) { eAIBase ai = SpawnAI(m_Formation.ToWorld(m_Formation.GetPosition(i))); ai.SetGroup(m_Group); if (++i < m_NumberOfAI) GetGame().GetCallQueue(CALL_CATEGORY_SYSTEM).Call(SpawnAI_Deferred, i); else m_Group.SetWaypointBehaviour(m_WaypointBehaviour); //! Only start moving after all AI spawned } } void Despawn(bool deferDespawnUntilLoosingAggro = false) { #ifdef EXTRACE_DIAG auto trace = EXTrace.Start(EXTrace.AI, this); #endif if (!m_IsSpawned) return; m_IsSpawned = false; m_TimeSinceLastSpawn = 0; if (m_Group) { Log("Despawning " + m_Group.Count() + " " + m_NameForLog + " bots (spawn position " + m_Position + ", " + (m_NumberOfAI - m_Group.Count()) + "/" + m_NumberOfAI + " deceased)"); if (m_Group.m_Persist && m_Group.Count() && m_Group.m_BaseName) { m_Group.Save(true); m_TimeSinceLastSpawn = m_RespawnTime; //! Allow "respawn" instantly if persistent group wasn't killed m_Position = m_Group.GetFormationLeader().GetPosition(); //! Update spawn position for next spawn } m_Group.ClearAI(true, deferDespawnUntilLoosingAggro); m_Group = null; } else { Log("Despawning " + m_NameForLog + " patrol (spawn position " + m_Position + ")"); } if (!m_WasGroupDestroyed && s_PatrolCount) UpdatePatrolCount(-1); } override void OnUpdate() { #ifdef EAI_TRACE auto trace = CF_Trace_0(this, "OnUpdate"); #endif if ( WasGroupDestroyed() && m_RespawnTime < 0 ) { return; } if (!m_Group || m_WasGroupDestroyed) { if (m_IsSpawned && !m_WasGroupDestroyed) //! Group is NULL but not killed so was deleted behind our back, need to do cleanup Despawn(); m_TimeSinceLastSpawn += eAIPatrol.UPDATE_RATE_IN_SECONDS; //! https://feedback.bistudio.com/T173348 if (!m_CanSpawn && m_RespawnTime > -1 && m_TimeSinceLastSpawn >= m_RespawnTime) m_CanSpawn = true; } if (!m_Group) { if (!m_Trigger && CanSpawn()) { m_Trigger = eAIDynamicPatrolSphereTrigger.Cast(GetGame().CreateObjectEx("eAIDynamicPatrolSphereTrigger", m_Position, ECE_LOCAL)); m_Trigger.eAI_SetParams(this, m_MaximumRadius, m_MinimumRadius); } } else { vector patrolPos = m_Position; DayZPlayerImplement leader = m_Group.GetFormationLeader(); if (leader) patrolPos = leader.GetPosition(); if ((m_WasGroupDestroyed && m_Group.DeceasedCount() == 0) || AvoidPlayer(patrolPos, m_DespawnRadius) || m_Group.m_ForcePatrolDespawn) { if (!m_WasGroupDestroyed) m_TimeSinceLastSpawn += eAIPatrol.UPDATE_RATE_IN_SECONDS; if (m_TimeSinceLastSpawn >= m_DespawnTime || m_Group.m_ForcePatrolDespawn) Despawn(); } } } bool CanBeTriggeredBy(PlayerBase player) { if (!player.IsAlive()) return false; //! Actual players can always trigger if (player.GetIdentity()) return true; if (!m_Config.CanBeTriggeredByAI) return false; //! Determine if AI can trigger eAIGroup group = player.GetGroup(); if (!group) return false; //! Can't trigger ourself or prevent from despawn if (group == m_Group) return false; eAIFaction faction = group.GetFaction(); if (faction.IsInvincible()) return false; if (faction.IsObserver()) return false; if (faction.IsPassive()) return false; return true; } bool AvoidPlayer(vector patrolPos, float radius) { if (m_Config.CanBeTriggeredByAI || !GetCEApi()) { set<PlayerBase> players = PlayerBase.Expansion_GetInCircle(patrolPos, radius); foreach (auto player: players) { if (CanBeTriggeredBy(player)) return false; } return true; } return GetCEApi().AvoidPlayer(patrolPos, radius); } private void UpdatePatrolCount(int delta) { s_PatrolCount += delta; Log("Global patrol count: " + s_PatrolCount); if (m_PatrolCountTracker && (!s_LoadBalancingGlobal || m_PatrolCountTracker != s_LoadBalancingGlobal.m_PatrolCountTracker)) { m_PatrolCountTracker.m_PatrolCount += delta; Log(m_Config.LoadBalancingCategory + " category patrol count: " + m_PatrolCountTracker.m_PatrolCount); } if (s_LoadBalancingGlobal) { s_LoadBalancingGlobal.m_PatrolCountTracker.m_PatrolCount += delta; int patrolCount = s_LoadBalancingGlobal.m_PatrolCountTracker.m_PatrolCount; if (patrolCount != s_PatrolCount) CF.FormatError("Global category patrol count %1 doesn't match internal global patrol count %2", patrolCount.ToString(), s_PatrolCount.ToString()); } } static void OnDebugAll() { Print(s_LoadBalancingGlobal); if (s_LoadBalancingGlobal) { Print(s_LoadBalancingGlobal.MinPlayers); Print(s_LoadBalancingGlobal.MaxPlayers); Print(s_LoadBalancingGlobal.MaxPatrols); Print(s_LoadBalancingGlobal.m_PatrolCountTracker.m_PatrolCount); } } override void Debug() { super.Debug(); Print(m_Config.Name); Print(m_NameForLog); Print(m_Trigger); Print(m_Position); Print(m_MinimumRadius); Print(m_MaximumRadius); Print(m_DespawnRadius); Print(m_Group); if (m_Group) { bool canStay = CanStay(0); Print(canStay); Print(m_Group.m_Leave); } Print(m_TimeSinceLastSpawn); bool canSpawn = CanSpawn(); Print(canSpawn); Print(m_CanSpawn); Print(m_IsSpawned); Print(m_Config.NumberOfAI); Print(m_NumberOfAI); Print(m_RespawnTime); Print(m_DespawnTime); Print(m_WasGroupDestroyed); Print(m_Config.LoadBalancingCategory); Print(m_LoadBalancing); if (m_LoadBalancing) { Print(m_LoadBalancing.MinPlayers); Print(m_LoadBalancing.MaxPlayers); Print(m_LoadBalancing.MaxPatrols); Print(m_LoadBalancing.m_PatrolCountTracker.m_PatrolCount); } } private void SetNameForLog() { m_NameForLog = m_Config.Name; if (m_NameForLog == string.Empty) m_NameForLog = m_Faction.GetName(); else m_NameForLog = string.Format("%1 (%2)", m_NameForLog, m_Faction.GetName()); } string GetNameForLog() { return m_NameForLog; } static void Log(ExpansionAIDynamicSpawnBase config, string msg) { Error("DEPRECATED, use ExpansionAISpawnBase::Log"); if (config) { config.Log(msg); } else { auto settings = GetExpansionSettings().GetLog(); if (settings.AIPatrol) settings.PrintLog("[AI Patrol] %1", msg); } } void Log(string msg) { auto settings = GetExpansionSettings().GetLog(); if (m_Config && m_Config.ObjectClassName) { if (settings.AIObjectPatrol) settings.PrintLog("[AI Object Patrol %1] %2", m_ID.ToStringLen(5), msg); } else if (settings.AIPatrol) { settings.PrintLog("[AI Patrol %1] %2", m_ID.ToStringLen(5), msg); } } }; class eAIDynamicPatrolT<Class T> { static T CreateEx(ExpansionAIDynamicSpawnBase config, vector startpos, bool autoStart = true) { T patrol; Class.CastTo(patrol, ((typename)T).Spawn()); if (patrol.Setup(config, startpos, autoStart)) return patrol; return null; } }
412
0.875504
1
0.875504
game-dev
MEDIA
0.990731
game-dev
0.958262
1
0.958262
chai3d/chai3d
4,923
modules/Bullet/externals/bullet/test/Bullet2/Source/Tests/Test_3x3setRot.cpp
// // Test_3x3setRot.cpp // BulletTest // // Copyright (c) 2011 Apple Inc. // #include "LinearMath/btScalar.h" #if defined (BT_USE_SSE_IN_API) || defined (BT_USE_NEON) #include "Test_3x3setRot.h" #include "vector.h" #include "Utils.h" #include "main.h" #include <math.h> #include <string.h> #include <LinearMath/btMatrix3x3.h> #define LOOPCOUNT 1000 #define ARRAY_SIZE 128 static inline btSimdFloat4 rand_f4(void) { return btAssign128( RANDF_01, RANDF_01, RANDF_01, BT_NAN ); // w channel NaN } static inline btSimdFloat4 qtrand_f4(void) { return btAssign128( RANDF_01, RANDF_01, RANDF_01, RANDF_01 ); } static btMatrix3x3 M3x3setRot_ref( btMatrix3x3 &m, const btQuaternion &q ) { btScalar d = q.length2(); btScalar s = btScalar(2.0) / d; btScalar xs = q.x() * s, ys = q.y() * s, zs = q.z() * s; btScalar wx = q.w() * xs, wy = q.w() * ys, wz = q.w() * zs; btScalar xx = q.x() * xs, xy = q.x() * ys, xz = q.x() * zs; btScalar yy = q.y() * ys, yz = q.y() * zs, zz = q.z() * zs; m.setValue( btScalar(1.0) - (yy + zz), xy - wz, xz + wy, xy + wz, btScalar(1.0) - (xx + zz), yz - wx, xz - wy, yz + wx, btScalar(1.0) - (xx + yy)); return m; } static int operator!= ( const btMatrix3x3 &a, const btMatrix3x3 &b ) { int i; btVector3 av3, bv3; for(i=0; i<3; i++) { av3 = a.getRow(i); bv3 = b.getRow(i); if( fabs(av3.m_floats[0] - bv3.m_floats[0]) + fabs(av3.m_floats[1] - bv3.m_floats[1]) + fabs(av3.m_floats[2] - bv3.m_floats[2]) > FLT_EPSILON * 4) return 1; } return 0; } int Test_3x3setRot(void) { // Init an array flanked by guard pages btMatrix3x3 in1[ARRAY_SIZE]; btQuaternion in2[ARRAY_SIZE]; btMatrix3x3 in3[ARRAY_SIZE]; btMatrix3x3 out[ARRAY_SIZE]; btMatrix3x3 out2[ARRAY_SIZE]; // Init the data size_t i, j; for( i = 0; i < ARRAY_SIZE; i++ ) { in1[i] = btMatrix3x3(rand_f4(), rand_f4(), rand_f4() ); in2[i] = btQuaternion(qtrand_f4()); in3[i] = in1[i]; out[i] = M3x3setRot_ref(in1[i], in2[i]); in3[i].setRotation(in2[i]); out2[i] = in3[i]; if( out[i] != out2[i] ) { vlog( "Error - M3x3setRot result error! "); vlog( "failure @ %ld\n", i); btVector3 m0, m1, m2; m0 = out[i].getRow(0); m1 = out[i].getRow(1); m2 = out[i].getRow(2); vlog( "\ncorrect = (%10.7f, %10.7f, %10.7f, %10.7f) " "\n (%10.7f, %10.7f, %10.7f, %10.7f) " "\n (%10.7f, %10.7f, %10.7f, %10.7f) \n", m0.m_floats[0], m0.m_floats[1], m0.m_floats[2], m0.m_floats[3], m1.m_floats[0], m1.m_floats[1], m1.m_floats[2], m1.m_floats[3], m2.m_floats[0], m2.m_floats[1], m2.m_floats[2], m2.m_floats[3]); m0 = out2[i].getRow(0); m1 = out2[i].getRow(1); m2 = out2[i].getRow(2); vlog( "\ntested = (%10.7f, %10.7f, %10.7f, %10.7f) " "\n (%10.7f, %10.7f, %10.7f, %10.7f) " "\n (%10.7f, %10.7f, %10.7f, %10.7f) \n", m0.m_floats[0], m0.m_floats[1], m0.m_floats[2], m0.m_floats[3], m1.m_floats[0], m1.m_floats[1], m1.m_floats[2], m1.m_floats[3], m2.m_floats[0], m2.m_floats[1], m2.m_floats[2], m2.m_floats[3]); return -1; } } uint64_t scalarTime, vectorTime; uint64_t startTime, bestTime, currentTime; bestTime = -1LL; scalarTime = 0; for (j = 0; j < LOOPCOUNT; j++) { startTime = ReadTicks(); for( i = 0; i < ARRAY_SIZE; i++ ) out[i] = M3x3setRot_ref(in1[i], in2[i]); currentTime = ReadTicks() - startTime; scalarTime += currentTime; if( currentTime < bestTime ) bestTime = currentTime; } if( 0 == gReportAverageTimes ) scalarTime = bestTime; else scalarTime /= LOOPCOUNT; bestTime = -1LL; vectorTime = 0; for (j = 0; j < LOOPCOUNT; j++) { startTime = ReadTicks(); for( i = 0; i < ARRAY_SIZE; i++ ) { in3[i].setRotation(in2[i]); out2[i] = in3[i]; } currentTime = ReadTicks() - startTime; vectorTime += currentTime; if( currentTime < bestTime ) bestTime = currentTime; } if( 0 == gReportAverageTimes ) vectorTime = bestTime; else vectorTime /= LOOPCOUNT; vlog( "Timing:\n" ); vlog( "\t scalar\t vector\n" ); vlog( "\t%10.2f\t%10.2f\n", TicksToCycles( scalarTime ) / ARRAY_SIZE, TicksToCycles( vectorTime ) / ARRAY_SIZE ); return 0; } #endif //BT_USE_SSE
412
0.682826
1
0.682826
game-dev
MEDIA
0.279646
game-dev
0.973599
1
0.973599
GregTechCEu/GregTech-Modern
1,772
src/main/java/com/gregtechceu/gtceu/api/gui/editor/UIMainPanel.java
package com.gregtechceu.gtceu.api.gui.editor; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.lowdragmc.lowdraglib.gui.editor.ui.Editor; import com.lowdragmc.lowdraglib.gui.editor.ui.MainPanel; import com.lowdragmc.lowdraglib.gui.texture.IGuiTexture; import com.lowdragmc.lowdraglib.gui.texture.TextTexture; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import net.minecraft.client.gui.GuiGraphics; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public class UIMainPanel extends MainPanel { final String description; public UIMainPanel(Editor editor, WidgetGroup root, String description) { super(editor, root); this.setBackground(new IGuiTexture() { @Override @OnlyIn(Dist.CLIENT) public void draw(GuiGraphics graphics, int mouseX, int mouseY, float x, float y, int width, int height) { if (description != null) { new TextTexture(description).scale(2.0f).draw(graphics, mouseX, mouseY, x, y, width - editor.getConfigPanel().getSize().getWidth(), height); } var border = 4; var background = GuiTextures.BACKGROUND; var position = root.getPosition(); var size = root.getSize(); var w = Math.max(size.width + border * 2, 172); var h = Math.max(size.height + border * 2, 86); background.draw(graphics, mouseX, mouseY, position.x - (w - size.width) / 2f, position.y - (h - size.height) / 2f, w, h); } }); this.description = description; } }
412
0.745885
1
0.745885
game-dev
MEDIA
0.720665
game-dev
0.899989
1
0.899989
CalamityTeam/CalamityModPublic
1,568
Particles/FireParticle.cs
using Microsoft.Xna.Framework; using Terraria; namespace CalamityMod.Particles { public class FireParticle : Particle { public float RelativePower; public override bool SetLifetime => true; public override int FrameVariants => 3; public Color BrightColor; public Color DarkColor; public override string Texture => "CalamityMod/Particles/Fire"; public FireParticle(Vector2 relativePosition, int lifetime, float scale, float relativePower, Color brightColor, Color darkColor) { RelativeOffset = relativePosition; Velocity = Vector2.Zero; Scale = scale; Variant = Main.rand.Next(3); Lifetime = lifetime; RelativePower = relativePower; BrightColor = brightColor; DarkColor = darkColor; } public override void Update() { Scale += RelativePower * 0.01f; RelativeOffset.Y -= RelativePower * 3f; Color = Color.Lerp(BrightColor, DarkColor, LifetimeCompletion); Color = Color.Lerp(Color, Color.SaddleBrown, Utils.GetLerpValue(0.95f, 0.7f, LifetimeCompletion, true)); Color = Color.Lerp(Color, Color.White, Utils.GetLerpValue(0.1f, 0.25f, LifetimeCompletion, true) * Utils.GetLerpValue(0.4f, 0.25f, LifetimeCompletion, true) * 0.7f); Color *= Utils.GetLerpValue(0f, 0.15f, LifetimeCompletion, true) * Utils.GetLerpValue(1f, 0.8f, LifetimeCompletion, true) * 0.6f; Color.A = 50; } } }
412
0.765037
1
0.765037
game-dev
MEDIA
0.563331
game-dev
0.877056
1
0.877056
LordOfDragons/dragengine
2,328
src/deigde/editors/animator/src/undosys/rule/animdiff/aeUSetRuleAniDLeadMoveTime.cpp
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "aeUSetRuleAniDLeadMoveTime.h" #include "../../../animator/rule/aeRuleAnimationDifference.h" #include <dragengine/common/exceptions.h> // Class aeUSetRuleAniDLeadMoveTime ///////////////////////////////////// // Constructor, destructor //////////////////////////// aeUSetRuleAniDLeadMoveTime::aeUSetRuleAniDLeadMoveTime( aeRuleAnimationDifference *rule, float newTime ){ if( ! rule ) DETHROW( deeInvalidParam ); pRule = NULL; try{ pRule = rule; pRule->AddReference(); pOldTime = rule->GetLeadingMoveTime(); pNewTime = newTime; SetShortInfo( "Set animation difference rule leading move time" ); }catch( const deException & ){ pCleanUp(); throw; } } aeUSetRuleAniDLeadMoveTime::~aeUSetRuleAniDLeadMoveTime(){ pCleanUp(); } // Management /////////////// void aeUSetRuleAniDLeadMoveTime::Undo(){ pRule->SetLeadingMoveTime( pOldTime ); } void aeUSetRuleAniDLeadMoveTime::Redo(){ pRule->SetLeadingMoveTime( pNewTime ); } // Private Functions ////////////////////// void aeUSetRuleAniDLeadMoveTime::pCleanUp(){ if( pRule ) pRule->FreeReference(); }
412
0.689898
1
0.689898
game-dev
MEDIA
0.479146
game-dev,desktop-app
0.634332
1
0.634332
emocat/VioHawk
13,055
utils/able/src/bridge/PythonAPImaster/lgsvl/agent.py
# # Copyright (c) 2019-2020 LG Electronics, Inc. # # This software contains code licensed as described in LICENSE. # from .geometry import Vector, BoundingBox from .sensor import Sensor from .utils import accepts, ObjectState as AgentState from enum import Enum from collections.abc import Iterable, Callable import json class DriveWaypoint: def __init__( self, position, speed, angle=Vector(0, 0, 0), idle=0, deactivate=False, trigger_distance=0, timestamp=-1, trigger=None, ): self.position = position self.speed = speed self.angle = angle self.idle = idle self.deactivate = deactivate self.trigger_distance = trigger_distance self.timestamp = timestamp self.trigger = trigger class WalkWaypoint: def __init__(self, position, idle, trigger_distance=0, speed=1, trigger=None): self.position = position self.speed = speed self.idle = idle self.trigger_distance = trigger_distance self.trigger = trigger class WaypointTrigger: def __init__(self, effectors): self.effectors = effectors @staticmethod def from_json(j): return WaypointTrigger(json.loads(j["effectors"])) def to_json(self): effectors_json = [] for effector in self.effectors: effectors_json.append(effector.to_json()) return {"effectors": effectors_json} class TriggerEffector: def __init__(self, type_name, parameters): self.type_name = type_name self.parameters = parameters @staticmethod def from_json(j): return TriggerEffector(j["type_name"], j["parameters"]) def to_json(self): return {"type_name": self.type_name, "parameters": self.parameters} class AgentType(Enum): EGO = 1 NPC = 2 PEDESTRIAN = 3 class VehicleControl: def __init__(self): self.steering = 0.0 # [-1..+1] self.throttle = 0.0 # [0..1] self.braking = 0.0 # [0..1] self.reverse = False self.handbrake = False # optional self.headlights = None # int, 0=off, 1=low, 2=high beams self.windshield_wipers = None # int, 0=off, 1-3=on self.turn_signal_left = None # bool self.turn_signal_right = None # bool class NPCControl: def __init__(self): self.headlights = None # int, 0=off, 1=low, 2=high self.hazards = None # bool self.e_stop = None # bool self.turn_signal_left = None # bool self.turn_signal_right = None # bool class Agent: def __init__(self, uid, simulator): self.uid = uid self.remote = simulator.remote self.simulator = simulator @property def state(self): j = self.remote.command("agent/state/get", {"uid": self.uid}) return AgentState.from_json(j) @state.setter @accepts(AgentState) def state(self, state): self.remote.command( "agent/state/set", {"uid": self.uid, "state": state.to_json()} ) @property def transform(self): return self.state.transform @property def bounding_box(self): j = self.remote.command("agent/bounding_box/get", {"uid": self.uid}) return BoundingBox.from_json(j) def __eq__(self, other): return self.uid == other.uid def __hash__(self): return hash(self.uid) @accepts(Callable) def on_collision(self, fn): self.remote.command("agent/on_collision", {"uid": self.uid}) self.simulator._add_callback(self, "collision", fn) @staticmethod def create(simulator, uid, agent_type): if agent_type == AgentType.EGO: return EgoVehicle(uid, simulator) elif agent_type == AgentType.NPC: return NpcVehicle(uid, simulator) elif agent_type == AgentType.PEDESTRIAN: return Pedestrian(uid, simulator) else: raise ValueError("unsupported agent type") class Vehicle(Agent): def __init__(self, uid, simulator): super().__init__(uid, simulator) class EgoVehicle(Vehicle): def __init__(self, uid, simulator): super().__init__(uid, simulator) @property def bridge_connected(self): return self.remote.command("vehicle/bridge/connected", {"uid": self.uid}) @accepts(str, int) def connect_bridge(self, address, port): if port <= 0 or port > 65535: raise ValueError("port value is out of range") self.remote.command( "vehicle/bridge/connect", {"uid": self.uid, "address": address, "port": port}, ) def get_sensors(self): j = self.remote.command("vehicle/sensors/get", {"uid": self.uid}) return [Sensor.create(self.remote, sensor) for sensor in j] @accepts(bool, float) def set_fixed_speed(self, isCruise, speed=None): self.remote.command( "vehicle/set_fixed_speed", {"uid": self.uid, "isCruise": isCruise, "speed": speed}, ) @accepts(VehicleControl, bool) def apply_control(self, control, sticky=False): args = { "uid": self.uid, "sticky": sticky, "control": { "steering": control.steering, "throttle": control.throttle, "braking": control.braking, "reverse": control.reverse, "handbrake": control.handbrake, }, } if control.headlights is not None: args["control"]["headlights"] = control.headlights if control.windshield_wipers is not None: args["control"]["windshield_wipers"] = control.windshield_wipers if control.turn_signal_left is not None: args["control"]["turn_signal_left"] = control.turn_signal_left if control.turn_signal_right is not None: args["control"]["turn_signal_right"] = control.turn_signal_right self.remote.command("vehicle/apply_control", args) def on_custom(self, fn): self.simulator._add_callback(self, "custom", fn) class NpcVehicle(Vehicle): def __init__(self, uid, simulator): super().__init__(uid, simulator) @accepts(Iterable, bool) def follow(self, waypoints, loop=False): """Tells the NPC to follow the waypoints When an NPC reaches a waypoint, it will: 1. Wait for an EGO vehicle to approach to within the trigger_distance [meters] (ignored if 0) 2. Wait the idle time (ignored if 0) 3. Drive to the next waypoint (if any) Parameters ---------- waypoints : list of DriveWaypoints DriveWaypoint : Class (position, speed, angle, idle, trigger_distance) position : lgsvl.Vector() Unity coordinates of waypoint speed : float how fast the NPC should drive to the waypoint angle : lgsvl.Vector() Unity rotation of the NPC at the waypoint idle : float time for the NPC to wait at the waypoint deactivate : bool whether the NPC is to deactivate while waiting at this waypoint trigger_distance : float how close an EGO must approach for the NPC to continue trigger : Class (list of Effectors) trigger data with effectors applied on this waypoint effectors : Class (type, value) typeName : string effector type name parameters : dictionary parameters of the effector (for example "value", "max_distance", "radius") loop : bool whether the NPC should loop through the waypoints after reaching the final one """ self.remote.command( "vehicle/follow_waypoints", { "uid": self.uid, "waypoints": [ { "position": wp.position.to_json(), "speed": wp.speed, "angle": wp.angle.to_json(), "idle": wp.idle, "deactivate": wp.deactivate, "trigger_distance": wp.trigger_distance, "timestamp": wp.timestamp, "trigger": ( None if wp.trigger is None else wp.trigger.to_json() ), } for wp in waypoints ], "loop": loop, }, ) def follow_closest_lane(self, follow, max_speed, isLaneChange=True): self.remote.command( "vehicle/follow_closest_lane", { "uid": self.uid, "follow": follow, "max_speed": max_speed, "isLaneChange": isLaneChange, }, ) def set_behaviour(self, behaviour): self.remote.command( "vehicle/behaviour", {"uid": self.uid, "behaviour": behaviour} ) @accepts(bool) def change_lane(self, isLeftChange): self.remote.command( "vehicle/change_lane", {"uid": self.uid, "isLeftChange": isLeftChange} ) @accepts(NPCControl) def apply_control(self, control): args = {"uid": self.uid, "control": {}} if control.headlights is not None: if control.headlights not in [0, 1, 2]: raise ValueError("unsupported intensity value") args["control"]["headlights"] = control.headlights if control.hazards is not None: args["control"]["hazards"] = control.hazards if control.e_stop is not None: args["control"]["e_stop"] = control.e_stop if ( control.turn_signal_left is not None or control.turn_signal_right is not None ): args["control"]["isLeftTurnSignal"] = control.turn_signal_left args["control"]["isRightTurnSignal"] = control.turn_signal_right self.remote.command("vehicle/apply_npc_control", args) def on_waypoint_reached(self, fn): self.remote.command("agent/on_waypoint_reached", {"uid": self.uid}) self.simulator._add_callback(self, "waypoint_reached", fn) def on_stop_line(self, fn): self.remote.command("agent/on_stop_line", {"uid": self.uid}) self.simulator._add_callback(self, "stop_line", fn) def on_lane_change(self, fn): self.remote.command("agent/on_lane_change", {"uid": self.uid}) self.simulator._add_callback(self, "lane_change", fn) class Pedestrian(Agent): def __init__(self, uid, simulator): super().__init__(uid, simulator) @accepts(bool) def walk_randomly(self, enable): self.remote.command( "pedestrian/walk_randomly", {"uid": self.uid, "enable": enable} ) @accepts(Iterable, bool) def follow(self, waypoints, loop=False): """Tells the Pedestrian to follow the waypoints When a pedestrian reaches a waypoint, it will: 1. Wait for an EGO vehicle to approach to within the trigger_distance [meters] (ignored if 0) 2. Wait the idle time (ignored if 0) 3. Walk to the next waypoint (if any) Parameters ---------- waypoints : list of WalkWaypoints WalkWaypoint : Class (position, idle, trigger_distance, speed) position : lgsvl.Vector() Unity coordinates of waypoint idle : float time for the pedestrian to wait at the waypoint trigger_distance : float how close an EGO must approach for the pedestrian to continue speed : float how fast the pedestrian should drive to the waypoint (default value 1) loop : bool whether the pedestrian should loop through the waypoints after reaching the final one """ self.remote.command( "pedestrian/follow_waypoints", { "uid": self.uid, "waypoints": [ { "position": wp.position.to_json(), "idle": wp.idle, "trigger_distance": wp.trigger_distance, "speed": wp.speed, "trigger": ( None if wp.trigger is None else wp.trigger.to_json() ), } for wp in waypoints ], "loop": loop, }, ) @accepts(float) def set_speed(self, speed): self.remote.command("pedestrian/set_speed", {"uid": self.uid, "speed": speed}) @accepts(Callable) def on_waypoint_reached(self, fn): self.remote.command("agent/on_waypoint_reached", {"uid": self.uid}) self.simulator._add_callback(self, "waypoint_reached", fn)
412
0.779553
1
0.779553
game-dev
MEDIA
0.843876
game-dev
0.963233
1
0.963233
dotnet/iot
1,828
tools/ArduinoCsCompiler/Runtime/MiniGen2GcCallback.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArduinoCsCompiler.Runtime { /// <summary> /// This is a very strange class. It internally creates a reference that is immediately garbage, expecting a callback /// on it by the finalizer thread. /// Since we do not currently run any finalizers, we can as well also just forget about registration /// </summary> [ArduinoReplacement("System.Gen2GcCallback", null, true, typeof(System.GC), IncludingPrivates = true)] internal class MiniGen2GcCallback { /// <summary> /// Schedule 'callback' to be called in the next GC. If the callback returns true it is /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. /// </summary> public static void Register(Func<bool> callback) { // Create a unreachable object that remembers the callback function and target object. // new Gen2GcCallback(callback); } /// <summary> /// Schedule 'callback' to be called in the next GC. If the callback returns true it is /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. /// /// NOTE: This callback will be kept alive until either the callback function returns false, /// or the target object dies. /// </summary> public static void Register(Func<object, bool> callback, object targetObj) { // Create a unreachable object that remembers the callback function and target object. // new Gen2GcCallback(callback, targetObj); } } }
412
0.891966
1
0.891966
game-dev
MEDIA
0.241873
game-dev
0.683438
1
0.683438
pjasicek/OpenClaw
6,048
OpenClaw/Engine/UserInterface/ScoreScreen/ScoreScreenProcesses.h
#ifndef __SCORE_SCREEN_PROCESSES_H__ #define __SCORE_SCREEN_PROCESSES_H__ #include "ScoreScreenCommon.h" //================================================================================================= // Processes //================================================================================================= //================================================================================================= // DelayedProcess // // Purpose: Delay execution of another process by a given amount of time (in miliseconds) //================================================================================================= class DelayedProcess : public Process { public: DelayedProcess(int delay); virtual void VOnUpdate(uint32 msDiff) override; private: int m_Delay; }; //================================================================================================= // ImageSpawnProcess // // Purpose: Spawn a static image in specified position //================================================================================================= class ImageSpawnProcess : public Process { public: ImageSpawnProcess(const std::string& imagePath, const Point& position, const AnimationDef& aniDef); virtual void VOnUpdate(uint32 msDiff) override; private: const std::string m_ImagePath; const Point m_Position; const AnimationDef m_AniDef; }; //================================================================================================= // PlaySoundProcess // // Purpose: Plays a sound //================================================================================================= class PlaySoundProcess : public Process { public: PlaySoundProcess(const SoundInfo& sound); virtual void VOnUpdate(uint32 msDiff) override; private: const SoundInfo m_Sound; }; //================================================================================================= // FireEventProcess // // Purpose: Triggers or queues specified event //================================================================================================= class FireEventProcess : public Process { public: FireEventProcess(IEventDataPtr pEvent, bool isTriggered); virtual void VOnUpdate(uint32 msDiff) override; private: IEventDataPtr m_pEvent; bool m_bIsTriggered; }; //================================================================================================= // SpawnScoreRowProcess implementation // // Purpose: Spawns a single score row in level finished screen. // Sequence is as follows: // // 1) Spawn specified item defining this row outside the screen (Jewelled skull, Coin, Scepter...) // 2) Move initial score item to its destination // 3) Spawn whole row with all numbers (How many items of this kind were collected, // maximum collectible number of these items in finished level, score points worth, // score gained from collecting these items) and symbols (=, X, OF) // 4) Spawn from the upper left corner number of collected items of this kind and // forward them to the item's default location (defined in step (1) ) // 5) Add sparkle animation to the item and fire EventData_ScoreScreen_Finished_Loading_ScoreRow event // 6) Wait for further request (dissolving or destroying this row) //================================================================================================= enum ScoreRowState { ScoreRowState_None, ScoreRowState_SpawnInitialScoreItem, // 1) ScoreRowState_MoveInitialScoreItem, // 2) ScoreRowState_SpawnScoreRowImages, // 3) ScoreRowState_SpawnCollectedItems, // 4) ScoreRowState_FinalizeScoreRowLoading, // 5) ScoreRowState_FinishedLoading // 6) }; enum ScoreRowActorType { ScoreRowActorType_None, ScoreRowActorType_Numbers_ItemsPickedUp, ScoreRowActorType_Numbers_ScorePointsFromThisRow, ScoreRowActorType_MovingScoreItems }; typedef std::map<ScoreRowActorType, ActorList> ScoreRowActorListMap; class SpawnScoreRowProcess : public Process { public: SpawnScoreRowProcess(const ScoreRowDef& scoreRowDef); virtual ~SpawnScoreRowProcess(); virtual void VOnInit() override; virtual void VOnUpdate(uint32 msDiff) override; void ForceSpawnImmediately(); private: Point CalculateUpdatedPosition(uint32 msDiff, const Point& speed, const Point& currentPosition); Point CalculateSpawnedScoreItemSpeed(); int CalculateScoreItemSpawnInterval(); void UpdateSpawnedScoreItemPositions(uint32 msDiff, const Point& speed); void AddNumberImageActors(int numberToDisplay, int futureMaximumNumber, Point position, ScoreRowActorType numberType); void AddScore(int addedScore); void SetScore(int newScore); void IncrementCollectedSpawnedScoreItems(); void SetCollectedSpawnedScoreItems(int newCount); ScoreRowDef m_ScoreRowDef; ScoreRowState m_State; // Contains all actors spawned by this score row ActorList m_ChildrenActorList; // Contains actor groups belonging to defined category - e.g. actors I need to // access and modify later for whatever reason, e.g. spawned items, updating score, etc. ScoreRowActorListMap m_ActorCategoryToActorListMap; // Initial score item Actor* m_pInitialScoreItemActor; // Initial and spawned score items X speed in pixels / s (y speed is calculated) double m_ScoreItemDefaultSpeed; // How long has it been since we spawned one collected item int m_TimeSinceLastSpawnedItem; // How many collected items we spawned so far (not all of them had to arrive to its destination yet) int m_CountOfSpawnedScoreItems; // How many collected items ARRIVED at their destination so far int m_CountOfCollectedSpawnedScoreItems; // Current score of the row calculated from the count of colleted spawned score items and score items score points int m_CurrentScore; }; #endif
412
0.869809
1
0.869809
game-dev
MEDIA
0.976563
game-dev
0.885872
1
0.885872
b3dgs/lionheart-remake
8,133
lionheart-game/src/main/java/com/b3dgs/lionheart/intro/Part4.java
/* * Copyright (C) 2013-2024 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.lionheart.intro; import com.b3dgs.lionengine.Context; import com.b3dgs.lionengine.Engine; import com.b3dgs.lionengine.Media; import com.b3dgs.lionengine.Medias; import com.b3dgs.lionengine.Updatable; import com.b3dgs.lionengine.UpdatableVoid; import com.b3dgs.lionengine.audio.Audio; import com.b3dgs.lionengine.game.feature.Services; import com.b3dgs.lionengine.graphic.ColorRgba; import com.b3dgs.lionengine.graphic.Graphic; import com.b3dgs.lionengine.graphic.Renderable; import com.b3dgs.lionengine.graphic.RenderableVoid; import com.b3dgs.lionengine.graphic.engine.Sequence; import com.b3dgs.lionengine.graphic.engine.SourceResolutionDelegate; import com.b3dgs.lionengine.helper.DeviceControllerConfig; import com.b3dgs.lionengine.io.DeviceController; import com.b3dgs.lionheart.AppInfo; import com.b3dgs.lionheart.Constant; import com.b3dgs.lionheart.DeviceMapping; import com.b3dgs.lionheart.GameConfig; import com.b3dgs.lionheart.Time; import com.b3dgs.lionheart.Util; import com.b3dgs.lionheart.menu.Menu; /** * Intro part 4 implementation. */ public class Part4 extends Sequence { private static final int FADE_SPEED = 6; private static final int STORY0_INDEX = 0; private static final int STORY1_INDEX = 1; private static final int STORY2_INDEX = 2; private static final int STORY3_INDEX = 3; private static final int TIME_START_MS = 114_200; private static final int TIME_STORY1_MS = 130_000; private static final int TIME_STORY2_MS = 155_300; private static final int TIME_STORY3_MS = 180_600; private static final int TIME_END_MS = 200_200; /** Device controller reference. */ final DeviceController device; /** Alpha speed. */ int alphaSpeed = FADE_SPEED; private final Stories stories = new Stories(getWidth(), getHeight()); private final GameConfig config; private final AppInfo info; private final Time time; private final Audio audio; private final DeviceController deviceCursor; private Updatable updater = this::updateInit; private Renderable rendererFade = this::renderFade; private double alpha = 255.0; /** * Constructor. * * @param context The context reference. * @param config The config reference (must not be <code>null</code>). * @param time The time reference. * @param audio The audio reference. */ public Part4(Context context, GameConfig config, Time time, Audio audio) { super(context, Util.getResolution(Constant.RESOLUTION, context), Util.getLoop(context.getConfig().getOutput())); this.config = config; this.time = time; this.audio = audio; final Services services = new Services(); services.add(context); services.add(new SourceResolutionDelegate(this::getWidth, this::getHeight, this::getRate)); device = services.add(DeviceControllerConfig.create(services, Medias.create(Constant.INPUT_FILE_DEFAULT))); final Media mediaCursor = Medias.create(Constant.INPUT_FILE_CURSOR); deviceCursor = DeviceControllerConfig.create(services, mediaCursor); info = new AppInfo(this::getFps, services); setSystemCursorVisible(false); Util.setFilter(this, context, Util.getResolution(Constant.RESOLUTION, context), 2); } /** * Update init until time start. * * @param extrp The extrapolation value. */ private void updateInit(double extrp) { if (time.isAfter(TIME_START_MS)) { stories.setStory(STORY0_INDEX); updater = this::updateFadeIn; rendererFade = this::renderFade; } } /** * Update fade in process. * * @param extrp The extrapolation value. */ private void updateFadeIn(double extrp) { alpha -= alphaSpeed * extrp; if (getAlpha() < 0) { alpha = 0.0; updater = this::updateStory1; rendererFade = RenderableVoid.getInstance(); } } /** * Update first story delay. * * @param extrp The extrapolation value. */ private void updateStory1(double extrp) { if (time.isAfter(TIME_STORY1_MS)) { stories.setStory(STORY1_INDEX); updater = this::updateStory2; } } /** * Update second story delay. * * @param extrp The extrapolation value. */ private void updateStory2(double extrp) { if (time.isAfter(TIME_STORY2_MS)) { stories.setStory(STORY2_INDEX); updater = this::updateStory3; } } /** * Update third story delay. * * @param extrp The extrapolation value. */ private void updateStory3(double extrp) { if (time.isAfter(TIME_STORY3_MS)) { stories.setStory(STORY3_INDEX); updater = this::updateFadeOutStart; } } /** * Update start fading out delay. * * @param extrp The extrapolation value. */ private void updateFadeOutStart(double extrp) { if (time.isAfter(TIME_END_MS)) { updater = this::updateFadeOut; rendererFade = this::renderFade; } } /** * Update fade out process until end. * * @param extrp The extrapolation value. */ private void updateFadeOut(double extrp) { alpha += alphaSpeed * extrp; if (getAlpha() > 255) { alpha = 255.0; audio.stop(); end(Menu.class, config); updater = UpdatableVoid.getInstance(); } } /** * Check skip routine. */ private void checkSkip() { if (device.isFiredOnce(DeviceMapping.ATTACK) || deviceCursor.isFiredOnce(DeviceMapping.LEFT)) { updater = this::updateFadeOut; rendererFade = this::renderFade; } } /** * Get alpha value. * * @return The alpha value. */ private int getAlpha() { return (int) Math.floor(alpha); } /** * Render fade. * * @param g The graphic output. */ private void renderFade(Graphic g) { final int a = getAlpha(); if (a > 0) { g.setColor(Constant.ALPHAS_BLACK[a]); g.drawRect(0, 0, getWidth(), getHeight(), true); g.setColor(ColorRgba.BLACK); } } @Override public void load() { stories.load(); } @Override public void update(double extrp) { device.update(extrp); deviceCursor.update(extrp); time.update(extrp); updater.update(extrp); info.update(extrp); checkSkip(); if (device.isFiredOnce(DeviceMapping.FORCE_EXIT)) { end(null); } } @Override public void render(Graphic g) { g.clear(0, 0, getWidth(), getHeight()); stories.render(g); rendererFade.render(g); info.render(g); } @Override public void onTerminated(boolean hasNextSequence) { super.onTerminated(hasNextSequence); stories.dispose(); if (!hasNextSequence) { audio.stop(); Engine.terminate(); } } }
412
0.675783
1
0.675783
game-dev
MEDIA
0.902837
game-dev
0.91391
1
0.91391
magefree/mage
3,121
Mage.Sets/src/mage/cards/r/RoarOfJukai.java
package mage.cards.r; import mage.abilities.Ability; import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition; import mage.abilities.costs.common.GainLifeOpponentCost; import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.continuous.BoostTargetEffect; import mage.abilities.keyword.SpliceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.SubType; import mage.filter.FilterPermanent; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.permanent.BlockedPredicate; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.targetpointer.FixedTarget; import java.util.UUID; /** * @author LevelX2 */ public final class RoarOfJukai extends CardImpl { public RoarOfJukai(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{G}"); this.subtype.add(SubType.ARCANE); // If you control a Forest, each blocked creature gets +2/+2 until end of turn. this.getSpellAbility().addEffect(new RoarOfJukaiEffect()); // Splice onto Arcane-An opponent gains 5 life. this.addAbility(new SpliceAbility(SpliceAbility.ARCANE, new GainLifeOpponentCost(5))); } private RoarOfJukai(final RoarOfJukai card) { super(card); } @Override public RoarOfJukai copy() { return new RoarOfJukai(this); } } class RoarOfJukaiEffect extends OneShotEffect { private static final FilterPermanent filter = new FilterPermanent("Forest"); private static final FilterCreaturePermanent filterBlocked = new FilterCreaturePermanent("blocked creature"); static { filter.add(SubType.FOREST.getPredicate()); filterBlocked.add(BlockedPredicate.instance); } static { } public RoarOfJukaiEffect() { super(Outcome.BoostCreature); this.staticText = "If you control a Forest, each blocked creature gets +2/+2 until end of turn"; } private RoarOfJukaiEffect(final RoarOfJukaiEffect effect) { super(effect); } @Override public RoarOfJukaiEffect copy() { return new RoarOfJukaiEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { if (new PermanentsOnTheBattlefieldCondition(filter).apply(game, source)) { for (Permanent permanent : game.getBattlefield().getActivePermanents(filterBlocked, source.getControllerId(), source, game)) { ContinuousEffect effect = new BoostTargetEffect(2, 2, Duration.EndOfTurn); effect.setTargetPointer(new FixedTarget(permanent, game)); game.addEffect(effect, source); } } return true; } return false; } }
412
0.953907
1
0.953907
game-dev
MEDIA
0.960843
game-dev
0.991678
1
0.991678
Dimbreath/AzurLaneData
4,217
zh-CN/view/activity/backhills/doalinkisland/doalinkislandscene.lua
slot0 = class("DOALinkIslandScene", import("..TemplateMV.BackHillTemplate")) function slot0.getUIName(slot0) return "DOALinkIslandUI" end slot0.edge2area = { default = "map_middle", ["2_2"] = "map_bridge" } function slot0.init(slot0) slot0.top = slot0:findTF("top") slot0._map = slot0:findTF("map") for slot4 = 0, slot0._map.childCount - 1 do slot5 = slot0._map:GetChild(slot4) slot0["map_" .. go(slot5).name] = slot5 end slot0._shipTpl = slot0._map:Find("ship") slot0._upper = slot0:findTF("upper") for slot4 = 0, slot0._upper.childCount - 1 do slot5 = slot0._upper:GetChild(slot4) slot0["upper_" .. go(slot5).name] = slot5 end slot0.containers = { slot0.map_middle } slot0.graphPath = GraphPath.New(import("GameCfg.BackHillGraphs.DOAIslandGraph")) slot2 = slot0._tf:GetComponentInParent(typeof(UnityEngine.Canvas)) and slot1.sortingOrder slot0._map:GetComponent(typeof(UnityEngine.Canvas)).sortingOrder = slot2 - 3 slot0.map_tebiezuozhan:GetComponent(typeof(UnityEngine.Canvas)).sortingOrder = slot2 - 1 slot0.map_bridge:GetComponent(typeof(UnityEngine.Canvas)).sortingOrder = slot2 - 1 for slot7 = 1, 1 do slot9 = tf(Instantiate(GetComponent(slot0._map, "ItemList").prefabItem[slot7 - 1])) pg.ViewUtils.SetSortingOrder(slot9, slot2 - 2) setParent(slot9, slot0._map) end slot0.loader = ThirdAnniversaryAutoloader.New() end function slot0.didEnter(slot0) onButton(slot0, slot0:findTF("top/return_btn"), function () uv0:emit(uv1.ON_BACK) end) onButton(slot0, slot0:findTF("top/return_main_btn"), function () uv0:emit(uv1.ON_HOME) end) onButton(slot0, slot0:findTF("top/help_btn"), function () pg.MsgboxMgr.GetInstance():ShowMsgBox({ type = MSGBOX_TYPE_HELP, helps = pg.gametip.doa_main.tip }) end) slot0:InitStudents(getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_MINIGAME) and slot1.id, 2, 3) slot0:InitFacilityCross(slot0._map, slot0._upper, "shatanpaiqiu", function () pg.m02:sendNotification(GAME.GO_MINI_GAME, 17) end) slot2 = getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_PT_BUFF) slot0:InitFacilityCross(slot0._map, slot0._upper, "daoyvjianshe", function () uv0:emit(DOALinkIslandMediator.GO_SCENE, SCENE.ACTIVITY, { id = uv1 and uv1.id }) end) slot0:InitFacilityCross(slot0._map, slot0._upper, "bujishangdian", function () uv0:emit(DOALinkIslandMediator.GO_SCENE, SCENE.SHOP, { warp = NewShopsScene.TYPE_ACTIVITY }) end) slot0:InitFacilityCross(slot0._map, slot0._upper, "huanzhuangshangdian", function () uv0:emit(DOALinkIslandMediator.GO_SCENE, SCENE.SKINSHOP) end) slot0:InitFacilityCross(slot0._map, slot0._upper, "xianshijianzao", function () uv0:emit(DOALinkIslandMediator.GO_SCENE, SCENE.GETBOAT, { projectName = "new", page = 1 }) end) slot0:InitFacilityCross(slot0._map, slot0._upper, "jinianzhang", function () uv0:emit(DOALinkIslandMediator.GO_SCENE, SCENE.DOA_MEDAL_COLLECTION_SCENE) end) slot0:InitFacilityCross(slot0._map, slot0._upper, "tebiezuozhan", function () slot1, slot2 = getProxy(ChapterProxy):getLastMapForActivity() if not slot1 or not slot0:getMapById(slot1):isUnlock() then pg.TipsMgr.GetInstance():ShowTips(i18n("common_activity_end")) else uv0:emit(DOALinkIslandMediator.GO_SCENE, SCENE.LEVEL, { chapterId = slot2, mapIdx = slot1 }) end end) slot0:UpdateView() end function slot0.UpdateView(slot0) slot2 = nil slot5 = getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_MINIGAME) and getProxy(MiniGameProxy):GetHubByHubId(slot3:getConfig("config_id")) setActive(slot0.upper_shatanpaiqiu:Find("tip"), slot5 and slot5.count > 0 or slot5:getConfig("reward_need") <= slot5.usedtime and slot5.ultimate == 0) slot0.loader:GetSprite("ui/DOALinkIslandUI_atlas", tostring(slot5.usedtime or 0), slot0.map_shatanpaiqiu:Find("Digit"), true) setActive(slot0.upper_daoyvjianshe:Find("tip"), slot1:getActivityByType(ActivityConst.ACTIVITY_TYPE_PT_BUFF) and slot7:readyToAchieve()) setActive(slot0.upper_jinianzhang:Find("tip"), DoaMedalCollectionView.isHaveActivableMedal()) end function slot0.willExit(slot0) slot0:clearStudents() uv0.super.willExit(slot0) end return slot0
412
0.790168
1
0.790168
game-dev
MEDIA
0.915854
game-dev
0.944287
1
0.944287
Dodging-Turtis/Dodging-Turtis
2,704
components/game/src/cfg/constants/game-constants.ts
// const purple = 0xd218ef; import { PowerUp } from "../../prefabs/abstract/PowerUp"; import { StarFish } from "../../prefabs/collectibles/StarFish"; import { Log } from "../../prefabs/logs/Log"; import { InvincibilityPowerUp } from "../../prefabs/powerups/InvincibilityPowerUp"; import { MovementSpeedPowerUp } from "../../prefabs/powerups/MovementSpeedPowerUp"; import { ScrollSlowPowerUp } from "../../prefabs/powerups/ScrollSlowPowerUp"; import { Rock } from "../../prefabs/rocks/Rock"; // const redHex = '#ff0000'; // const greenHex = '#00ff00'; // const gray = 0xdcdcdc; // const black = 0x000000; export const GAME_FONT = "JosefinSans"; export const BG_COLOR = 0x73B9EE; export const SHORE_WIDTH = 150; export const CONTAINER_GAP = 120; export const LANDSCAPE_ORIENTATION_CONFIG = { screenColor: 0x000000, depth: 15, }; export const DEPTH = { shadow: 1, obstacle: 2, collectible: 3, player: 4, overlay: 5, ui: 10, powerUpDisplay: 11 } export const SHADOW_ALPHA = 0.05; export const TAP_TO_PLAY_CONFIG = { fontSize: '48px', fontColor: '#ffffff', fontShadow: '#777777', screenColor: 0x000000, }; export const CUSTOM_EVENTS = { BUTTON_CLICKED: 'button-clicked', GO_TO_HOME_CLICKED: 'go-to-home-clicked', MINT_TURTIS: 'mint-turtis', START_GAME: 'start-game', ESCAPE: 'escape', PAWN_SPAWNED: 'pawn-spawned', PAWN_REVIVED: 'pawn-revived', PAWN_DEAD: 'pawn-dead', PAWN_STARVED: 'pawn-starved' }; export const PREFABS = [ 'rock-1-prefab', 'rock-2-prefab', 'rock-3-prefab', 'rock-4-prefab', 'log-1-prefab', 'log-2-prefab', 'log-3-prefab', 'log-4-prefab', 'mix-1-prefab', 'mix-2-prefab', ] export const OBSTACLE_CONSTRUCTORS = { 'Rock': Rock, 'Log': Log, } export type OBSTACLE_TYPES = keyof typeof OBSTACLE_CONSTRUCTORS; export const POWER_UP_CONSTRUCTORS = { 'InvincibilityPowerUp': InvincibilityPowerUp, 'MovementSpeedPowerUp': MovementSpeedPowerUp, 'ScrollSlowPowerUp': ScrollSlowPowerUp } export type POWER_UP_TYPES = keyof typeof POWER_UP_CONSTRUCTORS; export const COLLECTIBLE_CONSTRUCTORS = { 'StarFish': StarFish, } export type COLLECTIBLE_TYPES = keyof typeof COLLECTIBLE_CONSTRUCTORS; export const GAME_SOUNDS = [ { key: 'bgm', path: 'bgm', loop: true }, { key: 'click', path: 'click', loop: false }, { key: 'collision', path: 'collision', loop: false }, { key: 'newHighScore', path: 'newHighScore', loop: false }, { key: 'turtleMint', path: 'turtleMint', loop: false }, { key: 'turtleSwap', path: 'turtleSwap', loop: false }, { key: 'starFish', path: 'starFish', loop: false }, { key: 'powerup', path: 'powerup', loop: false }, { key: 'splash', path: 'splash', loop: false }, ]
412
0.813699
1
0.813699
game-dev
MEDIA
0.884829
game-dev
0.83509
1
0.83509
magefree/mage
2,197
Mage.Sets/src/mage/cards/w/WrithingChrysalis.java
package mage.cards.w; import mage.MageInt; import mage.abilities.common.SacrificePermanentTriggeredAbility; import mage.abilities.effects.common.CastSourceTriggeredAbility; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.keyword.DevoidAbility; import mage.abilities.keyword.ReachAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.counters.CounterType; import mage.filter.FilterPermanent; import mage.filter.common.FilterControlledPermanent; import mage.filter.predicate.mageobject.AnotherPredicate; import mage.game.permanent.token.EldraziSpawnToken; import java.util.UUID; /** * @author TheElk801 */ public final class WrithingChrysalis extends CardImpl { private static final FilterPermanent filter = new FilterControlledPermanent(SubType.ELDRAZI, "another Eldrazi"); static { filter.add(AnotherPredicate.instance); } public WrithingChrysalis(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{R}{G}"); this.subtype.add(SubType.ELDRAZI); this.subtype.add(SubType.DRONE); this.power = new MageInt(2); this.toughness = new MageInt(3); // Devoid this.addAbility(new DevoidAbility(this.color)); // When you cast this spell, create two 0/1 colorless Eldrazi Spawn creature tokens with "Sacrifice this creature: Add {C}." this.addAbility(new CastSourceTriggeredAbility(new CreateTokenEffect(new EldraziSpawnToken(), 2))); // Reach this.addAbility(ReachAbility.getInstance()); // Whenever you sacrifice another Eldrazi, put a +1/+1 counter on Writhing Chrysalis. this.addAbility(new SacrificePermanentTriggeredAbility( new AddCountersSourceEffect(CounterType.P1P1.createInstance()), filter )); } private WrithingChrysalis(final WrithingChrysalis card) { super(card); } @Override public WrithingChrysalis copy() { return new WrithingChrysalis(this); } }
412
0.952088
1
0.952088
game-dev
MEDIA
0.938548
game-dev
0.997149
1
0.997149
Pico-Developer/PICO-URP-Fork
3,914
Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentProvider.cs
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor.Rendering { using IProvider = FilterWindow.IProvider; using Element = FilterWindow.Element; using GroupElement = FilterWindow.GroupElement; class VolumeComponentProvider : IProvider { class VolumeComponentElement : Element { public Type type; public VolumeComponentElement(int level, string label, Type type) { this.level = level; this.type = type; // TODO: Add support for custom icons content = new GUIContent(label); } } class PathNode : IComparable<PathNode> { public List<PathNode> nodes = new List<PathNode>(); public string name; public Type type; public int CompareTo(PathNode other) { return name.CompareTo(other.name); } } public Vector2 position { get; set; } VolumeProfile m_Target; VolumeComponentListEditor m_TargetEditor; public VolumeComponentProvider(VolumeProfile target, VolumeComponentListEditor targetEditor) { m_Target = target; m_TargetEditor = targetEditor; } public void CreateComponentTree(List<Element> tree) { var currentPipeline = RenderPipelineManager.currentPipeline; if (currentPipeline == null) { tree.Add(new GroupElement(0, "No SRP in use")); return; } tree.Add(new GroupElement(0, "Volume Overrides")); var volumeComponentTypesFiltered = VolumeManager.GetSupportedVolumeComponents(currentPipeline.GetType()); if (volumeComponentTypesFiltered.Any()) { var rootNode = new PathNode(); foreach (var (path, t) in volumeComponentTypesFiltered) { // Skip components that have already been added to the volume if (m_Target.Has(t)) continue; // Prep the categories & types tree AddNode(rootNode, path, t); } // Recursively add all elements to the tree Traverse(rootNode, 1, tree); } } public bool GoToChild(Element element, bool addIfComponent) { if (element is VolumeComponentElement volumeComponentElement) { m_TargetEditor.AddComponent(volumeComponentElement.type); return true; } return false; } void AddNode(PathNode root, string path, Type type) { var current = root; var parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) { var child = current.nodes.Find(x => x.name == part); if (child == null) { child = new PathNode { name = part, type = type }; current.nodes.Add(child); } current = child; } } void Traverse(PathNode node, int depth, List<Element> tree) { node.nodes.Sort(); foreach (var n in node.nodes) { if (n.nodes.Count > 0) // Group { tree.Add(new GroupElement(depth, n.name)); Traverse(n, depth + 1, tree); } else // Element { tree.Add(new VolumeComponentElement(depth, n.name, n.type)); } } } } }
412
0.943136
1
0.943136
game-dev
MEDIA
0.531207
game-dev
0.993671
1
0.993671
heineman/algorithms-nutshell-2ed
2,327
JavaCode/src/algs/model/problems/tictactoe/model/PlayerFactory.java
package algs.model.problems.tictactoe.model; import algs.model.gametree.*; /** * Factory to properly construct Player objects representing the type of * agents playing TicTacToe. * * @author George Heineman * @version 1.0, 6/15/08 * @since 1.0 */ public class PlayerFactory { /** Known types. */ public static final String Random = "Random"; // Algorithms. /** Minimax algorithm */ public static final String MiniMax = "MiniMax"; /** Negmax algorithm */ public static final String NegMax = "NegMax"; /** AlphaBeta algorithm */ public static final String AlphaBeta = "AlphaBeta"; /** * Create a player just by the type. Return null if not random since that type might require parameters * of which this method is unaware. * * @param type Type of player * @param mark X or O mark for player * @return {@link Player} object representing given mark and type */ public static Player createPlayer(String type, char mark) { Player player = null; if (type.equals (Random)) { player = new RandomPlayer (mark); } else { return null; } // Default to include a quality evaluation function player.score(new BoardEvaluation()); return player; } /** * Create player with a fixed ply lookahead. * * Use the default Evaluation scoring method. Note that whoever invokes this method * must assign the opponent to be used before that player is asked to determine * its moves. * * @param type Type of player * @param mark Mark to use for player * @param ply Depth of ply to search. * @return {@link Player} object representing given type, mark and ply. */ public static Player createPlayerWithPly(String type, char mark, int ply) { Player player = null; if (type.equals (AlphaBeta)) { player = new IntelligentAgent (mark, new AlphaBetaEvaluation(ply)); } else if (type.equals (MiniMax)) { player = new IntelligentAgent (mark, new MinimaxEvaluation(ply)); } else if (type.equals (NegMax)) { player = new IntelligentAgent (mark, new NegMaxEvaluation(ply)); } else { throw new IllegalArgumentException("PlayerFactory.createPlayerWithPly received unknown type:" + type); } // Default to include a quality evaluation function player.score(new BoardEvaluation()); return player; } }
412
0.691885
1
0.691885
game-dev
MEDIA
0.681743
game-dev,web-backend
0.778788
1
0.778788
jorio/Nanosaur2
5,655
Source/Items/Crystals.c
/****************************/ /* CRYSTALS.C */ /* (c)2004 Pangea Software */ /* By Brian Greenstone */ /****************************/ /****************************/ /* EXTERNALS */ /****************************/ #include "game.h" /****************************/ /* PROTOTYPES */ /****************************/ static Boolean CrystalHitByWeaponCallback(ObjNode *bullet, ObjNode *crystal, OGLPoint3D *hitCoord, OGLVector3D *hitTriangleNormal); static void MoveCrystalShockwave(ObjNode *theNode); /****************************/ /* CONSTANTS */ /****************************/ /*********************/ /* VARIABLES */ /*********************/ /************************* ADD CRYSTAL *********************************/ Boolean AddCrystal(TerrainItemEntryType *itemPtr, float x, float z) { ObjNode *base, *crystal; if (itemPtr->parm[0] > 2) DoFatalAlert("AddCrystal: illegal subtype"); /*************/ /* MAKE BASE */ /*************/ NewObjectDefinitionType def = { .group = MODEL_GROUP_LEVELSPECIFIC, .type = LEVEL2_ObjType_Crystal1Base + itemPtr->parm[0], .scale = 1.5f + RandomFloat2() * .5f, .coord.x = x, .coord.z = z, .coord.y = itemPtr->terrainY, .flags = gAutoFadeStatusBits, .slot = SLOT_OF_DUMB-50, .moveCall = MoveStaticObject, .rot = RandomFloat()*PI2, }; base = MakeNewDisplayGroupObject(&def); base->TerrainItemPtr = itemPtr; // keep ptr to item list RotateOnTerrain(base, -2, nil); // keep flat on terrain SetObjectTransformMatrix(base); if (!(itemPtr->flags & ITEM_FLAGS_USER1)) // did we blow up the crystal previously? { /****************/ /* MAKE CRYSTAL */ /****************/ def.type = LEVEL2_ObjType_Crystal1 + itemPtr->parm[0]; def.slot = SLOT_OF_DUMB-3; def.moveCall = nil; crystal = MakeNewDisplayGroupObject(&def); /* SET COLLISION STUFF */ crystal->CType = CTYPE_SOLIDTOENEMY | CTYPE_PLAYERTEST | CTYPE_WEAPONTEST | CTYPE_MISC; crystal->CBits = CBITS_ALLSOLID; CalcObjectBoxFromNode(crystal); crystal->HitByWeaponHandler = CrystalHitByWeaponCallback; crystal->HeatSeekHotSpotOff.x = 0; crystal->HeatSeekHotSpotOff.y = 50.0f; crystal->HeatSeekHotSpotOff.z = 0; crystal->BaseTransformMatrix = base->BaseTransformMatrix; SetObjectTransformMatrix(crystal); base->ChainNode = crystal; crystal->ChainHead = base; } return(true); // item was added } /*************************** CRYSTAL HIT BY WEAPON CALLBACK *****************************/ // // Returns true if object should stop bullet. // static Boolean CrystalHitByWeaponCallback(ObjNode *bullet, ObjNode *crystal, OGLPoint3D *hitCoord, OGLVector3D *hitTriangleNormal) { ObjNode *base = crystal->ChainHead; long pg,i; OGLVector3D d; OGLPoint3D pt; NewParticleDefType newParticleDef; #pragma unused (hitCoord, hitTriangleNormal, bullet) PlayEffect_Parms3D(EFFECT_CRYSTALSHATTER, &crystal->Coord, NORMAL_CHANNEL_RATE + (MyRandomLong() & 0x3fff), 2.0); /***************/ /* MAKE SPARKS */ /***************/ gNewParticleGroupDef.magicNum = 0; gNewParticleGroupDef.type = PARTICLE_TYPE_FALLINGSPARKS; gNewParticleGroupDef.flags = PARTICLE_FLAGS_DONTCHECKGROUND; gNewParticleGroupDef.gravity = 500; gNewParticleGroupDef.magnetism = 0; gNewParticleGroupDef.baseScale = 15; gNewParticleGroupDef.decayRate = .5; gNewParticleGroupDef.fadeRate = 1.0; gNewParticleGroupDef.particleTextureNum = PARTICLE_SObjType_BlueSpark; gNewParticleGroupDef.srcBlend = GL_SRC_ALPHA; gNewParticleGroupDef.dstBlend = GL_ONE; pg = NewParticleGroup(&gNewParticleGroupDef); if (pg != -1) { float x,y,z; x = base->Coord.x; y = base->Coord.y; z = base->Coord.z; for (i = 0; i < 220; i++) { d.x = RandomFloat2() * 800.0f; d.y = RandomFloat2() * 500.0f; d.z = RandomFloat2() * 800.0f; pt.x = x + d.x * .05f; pt.y = y + RandomFloat() * 150.0f; pt.z = z + d.z * .05f; newParticleDef.groupNum = pg; newParticleDef.where = &pt; newParticleDef.delta = &d; newParticleDef.scale = RandomFloat() + 1.0f; newParticleDef.rotZ = 0; newParticleDef.rotDZ = 0; newParticleDef.alpha = 1.0f + (RandomFloat() * .3f); AddParticleToGroup(&newParticleDef); } } /* FRAGMENT */ ExplodeGeometry(crystal, 600, SHARD_MODE_FROMORIGIN, 1, 1.0); /* SHOCKWAVE */ NewObjectDefinitionType def = { .group = MODEL_GROUP_WEAPONS, .type = WEAPONS_ObjType_BombShockwave, .coord = base->Coord, .flags = STATUS_BIT_NOZWRITES|STATUS_BIT_NOFOG|STATUS_BIT_NOLIGHTING, .slot = SLOT_OF_DUMB + 40, .moveCall = MoveCrystalShockwave, .rot = 0, .scale = 1.0, }; ObjNode* newObj = MakeNewDisplayGroupObject(&def); newObj->ColorFilter.a = .8; newObj->Damage = .8f; /* DELETE */ base->ChainNode = nil; // separate crystal from base base->TerrainItemPtr->flags |= ITEM_FLAGS_USER1; // set flag so next time the crystal won't be created DeleteObject(crystal); return(true); } /*********************** MOVE CRYSTAL SHOCKWAVE *******************/ static void MoveCrystalShockwave(ObjNode *theNode) { float fps = gFramesPerSecondFrac; /* FADE */ theNode->ColorFilter.a -= fps * 1.4f; if (theNode->ColorFilter.a <= 0.0f) { DeleteObject(theNode); return; } theNode->Scale.x = theNode->Scale.y = theNode->Scale.z += fps * 220.0f; UpdateObjectTransforms(theNode); CauseBombShockwaveDamage(theNode, CTYPE_PLAYER1 | CTYPE_PLAYER2 | CTYPE_ENEMY | CTYPE_WEAPONTEST); }
412
0.914004
1
0.914004
game-dev
MEDIA
0.898007
game-dev
0.94552
1
0.94552
Minestom/Minestom
11,062
src/test/java/net/minestom/server/network/PacketWriteReadTest.java
package net.minestom.server.network; import com.google.gson.JsonObject; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.nbt.CompoundBinaryTag; import net.kyori.adventure.text.Component; import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Metadata; import net.minestom.server.entity.PlayerSkin; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; import net.minestom.server.network.packet.client.play.ClientVehicleMovePacket; import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.common.DisconnectPacket; import net.minestom.server.network.packet.server.common.PingResponsePacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.login.LoginSuccessPacket; import net.minestom.server.network.packet.server.login.SetCompressionPacket; import net.minestom.server.network.packet.server.play.*; import net.minestom.server.network.packet.server.status.ResponsePacket; import net.minestom.server.network.player.GameProfile; import net.minestom.server.recipe.Ingredient; import net.minestom.server.recipe.RecipeBookCategory; import net.minestom.server.recipe.RecipeProperty; import net.minestom.server.recipe.display.RecipeDisplay; import net.minestom.server.recipe.display.SlotDisplay; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Ensures that packet can be written and read correctly. */ public class PacketWriteReadTest { private static final List<ServerPacket> SERVER_PACKETS = new ArrayList<>(); private static final List<ClientPacket> CLIENT_PACKETS = new ArrayList<>(); private static final Component COMPONENT = Component.text("Hey"); private static final Vec VEC = new Vec(5, 5, 5); @BeforeAll public static void setupServer() { MinecraftServer.init(); // Need some tags in here, pretty gross. // Handshake SERVER_PACKETS.add(new ResponsePacket(new JsonObject().toString())); // Status SERVER_PACKETS.add(new PingResponsePacket(5)); // Login //SERVER_PACKETS.add(new EncryptionRequestPacket("server", generateByteArray(16), generateByteArray(16))); SERVER_PACKETS.add(new LoginDisconnectPacket(COMPONENT)); //SERVER_PACKETS.add(new LoginPluginRequestPacket(5, "id", generateByteArray(16))); SERVER_PACKETS.add(new LoginSuccessPacket(new GameProfile(UUID.randomUUID(), "TheMode911"))); SERVER_PACKETS.add(new SetCompressionPacket(256)); // Play SERVER_PACKETS.add(new AcknowledgeBlockChangePacket(0)); SERVER_PACKETS.add(new ActionBarPacket(COMPONENT)); SERVER_PACKETS.add(new AttachEntityPacket(5, 10)); SERVER_PACKETS.add(new BlockActionPacket(VEC, (byte) 5, (byte) 5, 5)); SERVER_PACKETS.add(new BlockBreakAnimationPacket(5, VEC, (byte) 5)); SERVER_PACKETS.add(new BlockChangePacket(VEC, 0)); SERVER_PACKETS.add(new BlockEntityDataPacket(VEC, 5, CompoundBinaryTag.builder().putString("key", "value").build())); SERVER_PACKETS.add(new BossBarPacket(UUID.randomUUID(), new BossBarPacket.AddAction(COMPONENT, 5f, BossBar.Color.BLUE, BossBar.Overlay.PROGRESS, (byte) 2))); SERVER_PACKETS.add(new BossBarPacket(UUID.randomUUID(), new BossBarPacket.RemoveAction())); SERVER_PACKETS.add(new BossBarPacket(UUID.randomUUID(), new BossBarPacket.UpdateHealthAction(5f))); SERVER_PACKETS.add(new BossBarPacket(UUID.randomUUID(), new BossBarPacket.UpdateTitleAction(COMPONENT))); SERVER_PACKETS.add(new BossBarPacket(UUID.randomUUID(), new BossBarPacket.UpdateStyleAction(BossBar.Color.BLUE, BossBar.Overlay.PROGRESS))); SERVER_PACKETS.add(new BossBarPacket(UUID.randomUUID(), new BossBarPacket.UpdateFlagsAction((byte) 5))); SERVER_PACKETS.add(new CameraPacket(5)); SERVER_PACKETS.add(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.RAIN_LEVEL_CHANGE, 2)); SERVER_PACKETS.add(new SystemChatPacket(COMPONENT, false)); SERVER_PACKETS.add(new ClearTitlesPacket(false)); SERVER_PACKETS.add(new CloseWindowPacket((byte) 2)); SERVER_PACKETS.add(new CollectItemPacket(5, 5, 5)); var recipeDisplay = new RecipeDisplay.CraftingShapeless( List.of(new SlotDisplay.Item(Material.STONE)), new SlotDisplay.Item(Material.STONE_BRICKS), new SlotDisplay.Item(Material.CRAFTING_TABLE) ); SERVER_PACKETS.add(new PlaceGhostRecipePacket(0, recipeDisplay)); SERVER_PACKETS.add(new DeathCombatEventPacket(5, COMPONENT)); SERVER_PACKETS.add(new DeclareRecipesPacket(Map.of( RecipeProperty.SMITHING_BASE, List.of(Material.STONE), RecipeProperty.SMITHING_TEMPLATE, List.of(Material.STONE), RecipeProperty.SMITHING_ADDITION, List.of(Material.STONE), RecipeProperty.FURNACE_INPUT, List.of(Material.STONE), RecipeProperty.BLAST_FURNACE_INPUT, List.of(Material.IRON_HOE, Material.DANDELION), RecipeProperty.SMOKER_INPUT, List.of(Material.STONE), RecipeProperty.CAMPFIRE_INPUT, List.of(Material.STONE)), List.of(new DeclareRecipesPacket.StonecutterRecipe(new Ingredient(Material.DIAMOND), new SlotDisplay.ItemStack(ItemStack.of(Material.GOLD_BLOCK)))) )); SERVER_PACKETS.add(new RecipeBookAddPacket(List.of(new RecipeBookAddPacket.Entry(1, recipeDisplay, null, RecipeBookCategory.CRAFTING_MISC, List.of(new Ingredient(Material.STONE)), true, true)), false)); SERVER_PACKETS.add(new RecipeBookRemovePacket(List.of(1))); SERVER_PACKETS.add(new DestroyEntitiesPacket(List.of(5, 5, 5))); SERVER_PACKETS.add(new DisconnectPacket(COMPONENT)); SERVER_PACKETS.add(new DisplayScoreboardPacket((byte) 5, "scoreboard")); SERVER_PACKETS.add(new WorldEventPacket(5, VEC, 5, false)); SERVER_PACKETS.add(new EndCombatEventPacket(5)); SERVER_PACKETS.add(new EnterCombatEventPacket()); SERVER_PACKETS.add(new EntityAnimationPacket(5, EntityAnimationPacket.Animation.TAKE_DAMAGE)); SERVER_PACKETS.add(new EntityEquipmentPacket(6, Map.of(EquipmentSlot.MAIN_HAND, ItemStack.of(Material.DIAMOND_SWORD)))); SERVER_PACKETS.add(new EntityHeadLookPacket(5, 90f)); SERVER_PACKETS.add(new EntityMetaDataPacket(5, Map.of())); SERVER_PACKETS.add(new EntityMetaDataPacket(5, Map.of(1, Metadata.VarInt(5)))); SERVER_PACKETS.add(new EntityPositionAndRotationPacket(5, (short) 0, (short) 0, (short) 0, 45f, 45f, false)); SERVER_PACKETS.add(new EntityPositionPacket(5, (short) 0, (short) 0, (short) 0, true)); SERVER_PACKETS.add(new EntityAttributesPacket(5, List.of())); SERVER_PACKETS.add(new EntityRotationPacket(5, 45f, 45f, false)); final PlayerSkin skin = new PlayerSkin("hh", "hh"); List<PlayerInfoUpdatePacket.Property> prop = List.of(new PlayerInfoUpdatePacket.Property("textures", skin.textures(), skin.signature())); SERVER_PACKETS.add(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.ADD_PLAYER, new PlayerInfoUpdatePacket.Entry(UUID.randomUUID(), "TheMode911", prop, false, 0, GameMode.SURVIVAL, null, null, 0, true))); SERVER_PACKETS.add(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, new PlayerInfoUpdatePacket.Entry(UUID.randomUUID(), "", List.of(), false, 0, GameMode.SURVIVAL, Component.text("NotTheMode911"), null, 0, true))); SERVER_PACKETS.add(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, new PlayerInfoUpdatePacket.Entry(UUID.randomUUID(), "", List.of(), false, 0, GameMode.CREATIVE, null, null, 0, true))); SERVER_PACKETS.add(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, new PlayerInfoUpdatePacket.Entry(UUID.randomUUID(), "", List.of(), false, 20, GameMode.SURVIVAL, null, null, 0, true))); SERVER_PACKETS.add(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LISTED, new PlayerInfoUpdatePacket.Entry(UUID.randomUUID(), "", List.of(), true, 0, GameMode.SURVIVAL, null, null, 0, true))); SERVER_PACKETS.add(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LIST_ORDER, new PlayerInfoUpdatePacket.Entry(UUID.randomUUID(), "", List.of(), false, 0, GameMode.SURVIVAL, null, null, 42, true))); SERVER_PACKETS.add(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_HAT, new PlayerInfoUpdatePacket.Entry(UUID.randomUUID(), "", List.of(), false, 0, GameMode.SURVIVAL, null, null, 0, false))); SERVER_PACKETS.add(new PlayerInfoRemovePacket(UUID.randomUUID())); } @BeforeAll public static void setupClient() { CLIENT_PACKETS.add(new ClientHandshakePacket(755, "localhost", 25565, ClientHandshakePacket.Intent.LOGIN)); CLIENT_PACKETS.add(new ClientVehicleMovePacket(new Pos(5, 5, 5, 45f, 45f), true)); CLIENT_PACKETS.add(new ClientVehicleMovePacket(new Pos(6, 5, 6, 82f, 12.5f), false)); } @SuppressWarnings("unchecked") @Test public void serverTest() throws NoSuchFieldException, IllegalAccessException { for (var packet : SERVER_PACKETS) { var packetClass = packet.getClass(); NetworkBuffer.Type<ServerPacket> serializer = (NetworkBuffer.Type<ServerPacket>) packetClass.getField("SERIALIZER").get(packetClass); testPacket(serializer, packet); } } @SuppressWarnings("unchecked") @Test public void clientTest() throws NoSuchFieldException, IllegalAccessException { for (var packet : CLIENT_PACKETS) { var packetClass = packet.getClass(); NetworkBuffer.Type<ClientPacket> serializer = (NetworkBuffer.Type<ClientPacket>) packetClass.getField("SERIALIZER").get(packetClass); testPacket(serializer, packet); } } private static <T> void testPacket(NetworkBuffer.Type<T> networkType, T packet) { byte[] bytes = NetworkBuffer.makeArray(networkType, packet); NetworkBuffer reader = NetworkBuffer.resizableBuffer(); reader.write(NetworkBuffer.RAW_BYTES, bytes); var createdPacket = networkType.read(reader); assertEquals(packet, createdPacket); } }
412
0.947316
1
0.947316
game-dev
MEDIA
0.797106
game-dev,networking
0.927423
1
0.927423
ucdavis/erplab
12,510
GUIs/savemyerpGUI.m
% % Author: Javier Lopez-Calderon & Steven Luck % Center for Mind and Brain % University of California, Davis, % Davis, CA % 2009 %b8d3721ed219e65100184c6b95db209bb8d3721ed219e65100184c6b95db209b % % ERPLAB Toolbox % Copyright 2007 The Regents of the University of California % Created by Javier Lopez-Calderon and Steven Luck % Center for Mind and Brain, University of California, Davis, % javlopez@ucdavis.edu, sjluck@ucdavis.edu % % 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/>. function varargout = savemyerpGUI(varargin) % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @savemyerpGUI_OpeningFcn, ... 'gui_OutputFcn', @savemyerpGUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) if isempty(strfind(varargin{1},' ')) && isempty(str2num(varargin{1})) && isempty(strfind(varargin{1},'&')) gui_State.gui_Callback = str2func(varargin{1}); end end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % ------------------------------------------------------------------------- function savemyerpGUI_OpeningFcn(hObject, eventdata, handles, varargin) % Choose default command line output for savemyerpGUI try erpname = varargin{1}; filename = varargin{2}; overw = varargin{3}; catch erpname = ''; filename = ''; overw = 0; end handles.erpnameor = erpname; handles.output = []; erpmenu = findobj('tag', 'erpsets'); if ~isempty(erpmenu) handles.menuerp = get(erpmenu); set(handles.menuerp.Children, 'Enable','off'); end handles.owfp = 0; % over write file permission % % Name & version % version = geterplabversion; set(handles.gui_chassis,'Name', ['ERPLAB ' version ' - Save Erpset GUI']) set(handles.edit_erpname, 'String', erpname); if ~isempty(filename) set(handles.edit_saveas, 'Enable', 'on'); set(handles.edit_saveas, 'String', filename); set(handles.radiobutton_saveas, 'Value', 1); set(handles.pushbutton_same_as_erpname, 'Enable', 'on'); set(handles.pushbutton_same_as_filename, 'Enable', 'on'); set(handles.pushbutton_browse, 'Enable', 'on'); else set(handles.edit_saveas, 'String', ''); set(handles.radiobutton_saveas, 'Value', 0); set(handles.edit_saveas, 'Enable', 'off'); set(handles.pushbutton_same_as_erpname, 'Enable', 'off'); set(handles.pushbutton_same_as_filename, 'Enable', 'off'); set(handles.pushbutton_browse, 'Enable', 'off'); end if overw==0 set(handles.radiobutton_newerpset, 'Value', 1); set(handles.radiobutton_overwrite, 'Value', 0); else set(handles.radiobutton_newerpset, 'Value', 0); set(handles.radiobutton_overwrite, 'Value', 1); end [nset CURRENTERP] = getallerpstate; if nset>0 set(handles.text_question,'String', ['Your active erpset is # ' num2str(CURRENTERP)],... 'FontWeight','Bold', 'FontSize', 12) set(handles.radiobutton_overwrite,'String', ['Overwrite in memory erpset # ' num2str(CURRENTERP)]) set(handles.radiobutton_newerpset,'String', ['Create a new erpset # ' num2str(nset+1)]) else set(handles.text_question,'String', 'You are creating a new erpset',... 'FontSize', 12, 'FontWeight','Bold') set(handles.radiobutton_overwrite,'String', 'Overwrite in memory') set(handles.radiobutton_newerpset, 'Value', 1); set(handles.radiobutton_overwrite, 'Value', 0); set(handles.radiobutton_overwrite,'Enable', 'off') set(handles.radiobutton_newerpset,'String', ['Create a new erpset # ' num2str(nset+1)]) end % % Color GUI % handles = painterplab(handles); % % Set font size % handles = setfonterplab(handles); % Update handles structure guidata(hObject, handles); % help % helpbutton % UIWAIT makes savemyerpGUI wait for user response (see UIRESUME) uiwait(handles.gui_chassis); % ------------------------------------------------------------------------- function varargout = savemyerpGUI_OutputFcn(hObject, eventdata, handles) % Get default command line output from handles structure try set(handles.menuerp.Children, 'Enable','on'); catch disp('ERPset menu was not found...') end varargout{1} = handles.output; % The figure can be deleted now delete(handles.gui_chassis); pause(0.1) % ------------------------------------------------------------------------- function edit_erpname_Callback(hObject, eventdata, handles) % ------------------------------------------------------------------------- function edit_erpname_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % ------------------------------------------------------------------------- function edit_saveas_Callback(hObject, eventdata, handles) % ------------------------------------------------------------------------- function edit_saveas_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % ------------------------------------------------------------------------- function pushbutton_browse_Callback(hObject, eventdata, handles) % % Save OUTPUT file % fndefault = get(handles.edit_saveas,'String'); [fname, pathname] = uiputfile({'*.erp', 'ERPset (*.erp)';... '*.mat', 'MAT-files (*.mat)';... '*.*' , 'All Files (*.*)'},'Save Output file as',... fndefault); if isequal(fname,0) disp('User selected Cancel') guidata(hObject, handles); handles.owfp = 0; % over write file permission guidata(hObject, handles); else set(handles.edit_saveas,'String', fullfile(pathname, fname)); disp(['To save ERP, user selected ', fullfile(pathname, fname)]) handles.owfp = 1; % over write file permission guidata(hObject, handles); end % ------------------------------------------------------------------------- function pushbutton_cancel_Callback(hObject, eventdata, handles) handles.output = []; % Update handles structure guidata(hObject, handles); uiresume(handles.gui_chassis); % ------------------------------------------------------------------------- function pushbutton_OK_Callback(hObject, eventdata, handles) erpname = strtrim(get(handles.edit_erpname, 'String')); if isempty(erpname) msgboxText = 'You must enter an erpname at least!'; title = 'ERPLAB: averager GUI empty erpname'; errorfound(msgboxText, title); return end fname = strtrim(get(handles.edit_saveas, 'String')); overw = get(handles.radiobutton_overwrite, 'Value'); if ~isempty(fname) && get(handles.radiobutton_saveas, 'Value') owfp = handles.owfp; % over write file permission [pathstr, name, ext] = fileparts(fname); if ~strcmp(ext,'.erp') && ~strcmp(ext,'.mat') ext = '.erp'; end if strcmp(pathstr,'') pathstr = cd; end fullname = fullfile(pathstr, [name ext]); if exist(fullname, 'file')~=0 && owfp ==0 question{1} = [fullname ' already exists!']; question{2} = 'Do you want to replace it?'; title = 'ERPLAB: Overwriting Confirmation'; button = askquest(question, title); if ~strcmpi(button, 'yes') return end end elseif isempty(fname) && get(handles.radiobutton_saveas, 'Value') msgboxText = 'You must enter a filename!'; title = 'ERPLAB: averager GUI empty filename'; errorfound(msgboxText, title); return else fullname = []; end handles.output = {erpname, fullname, overw}; % Update handles structure guidata(hObject, handles); uiresume(handles.gui_chassis); % ------------------------------------------------------------------------- function radiobutton_saveas_Callback(hObject, eventdata, handles) if get(hObject, 'Value') set(handles.edit_saveas, 'Enable', 'on'); set(handles.pushbutton_browse, 'Enable', 'on'); set(handles.pushbutton_same_as_erpname, 'Enable', 'on'); set(handles.pushbutton_same_as_filename, 'Enable', 'on'); else set(handles.edit_saveas, 'Enable', 'off'); set(handles.pushbutton_browse, 'Enable', 'off'); set(handles.pushbutton_same_as_erpname, 'Enable', 'off'); set(handles.pushbutton_same_as_filename, 'Enable', 'off'); set(handles.edit_saveas, 'String', ''); end % ----------------------------------------------------------------------- function pushbutton_same_as_filename_Callback(hObject, eventdata, handles) fname = get(handles.edit_saveas, 'String'); %erpname = get(handles.edit_erpname, 'String'); if strcmp(fname,'') msgboxText = 'You must enter a filename first!'; title = 'ERPLAB: averager GUI empty filename'; errorfound(msgboxText, title); return end [pathstr, fname, ext] = fileparts(fname); erpname = fname; set(handles.edit_erpname, 'String', erpname); % ------------------------------------------------------------------------- function pushbutton_same_as_erpname_Callback(hObject, eventdata, handles) fname = get(handles.edit_saveas, 'String'); erpname = get(handles.edit_erpname, 'String'); if strcmp(erpname,'') msgboxText = 'You must enter an erpname!'; title = 'ERPLAB: averager GUI empty erpname'; errorfound(msgboxText, title); return end if ~strcmp(fname,'') [pathstr, name, ext] = fileparts(fname); name = erpname; if ~strcmp(ext,'.erp') && ~strcmp(ext,'.mat'); ext = '.erp'; end fname = fullfile(pathstr,[name ext]); else fname=[erpname '.erp']; end set(handles.edit_saveas, 'String', fname); % ------------------------------------------------------------------------- function radiobutton_overwrite_Callback(hObject, eventdata, handles) if get(hObject,'Value') set(handles.radiobutton_newerpset,'Value',0) erpname = strtrim(get(handles.edit_erpname, 'String')); if isempty(erpname) erpname = handles.erpnameor; set(handles.edit_erpname, 'String', erpname); end else set(handles.radiobutton_overwrite, 'Value',1); end % ------------------------------------------------------------------------- function radiobutton_newerpset_Callback(hObject, eventdata, handles) if get(hObject,'Value') set(handles.radiobutton_overwrite, 'Value',0); erpname = strtrim(get(handles.edit_erpname, 'String')); if isempty(erpname) erpname = handles.erpnameor; set(handles.edit_erpname, 'String', erpname); end else set(handles.radiobutton_newerpset, 'Value',1); end % ----------------------------------------------------------------------- function gui_chassis_CloseRequestFcn(hObject, eventdata, handles) if isequal(get(handles.gui_chassis, 'waitstatus'), 'waiting') %The GUI is still in UIWAIT, us UIRESUME handles.output = ''; %Update handles structure guidata(hObject, handles); uiresume(handles.gui_chassis); else % The GUI is no longer waiting, just close it delete(handles.gui_chassis); end
412
0.968989
1
0.968989
game-dev
MEDIA
0.811862
game-dev
0.914361
1
0.914361
glKarin/com.n0n3m4.diii4a
2,826
Q3E/src/main/jni/source/game/client/lamphaloproxy.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "proxyentity.h" #include "materialsystem/imaterialvar.h" #include "materialsystem/imaterial.h" #include "view.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: Used for halos on lamps, this material fades the sprite IN // as the viewer nears. //----------------------------------------------------------------------------- class CLampHaloProxy : public CEntityMaterialProxy { public: CLampHaloProxy( void ); virtual ~CLampHaloProxy( void ); virtual bool Init( IMaterial *pMaterial, KeyValues *pKeyValues ); virtual void OnBind( C_BaseEntity *pC_BaseEntity ); virtual IMaterial * GetMaterial(); private: IMaterialVar *m_pFadeValue; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CLampHaloProxy::CLampHaloProxy( void ) { m_pFadeValue = NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CLampHaloProxy::~CLampHaloProxy( void ) { } //----------------------------------------------------------------------------- // Purpose: Get pointer to the color value // Input : *pMaterial - //----------------------------------------------------------------------------- bool CLampHaloProxy::Init( IMaterial *pMaterial, KeyValues *pKeyValues ) { assert( pMaterial ); // Get pointers to material vars. // Need to get the color variable. bool found; m_pFadeValue = pMaterial->FindVar( "$alpha", &found ); return found; } //----------------------------------------------------------------------------- // Purpose: // Input : *pC_BaseEntity - //----------------------------------------------------------------------------- #define FADE_DIST 150 void CLampHaloProxy::OnBind( C_BaseEntity *pEnt ) { if ( !m_pFadeValue ) return; Vector vecLocal = pEnt->GetAbsOrigin() - CurrentViewOrigin(); VectorNormalize( vecLocal ); float fade = fabs( vecLocal.z ); // I hate these magic numbers here, will have to revise // (sjb) if( fade < 0.25 ) { fade = 0.0; } else { fade = MIN( (fade - 0.25) * 1.35, 1.0f ); } m_pFadeValue->SetFloatValue( fade ); } IMaterial *CLampHaloProxy::GetMaterial() { if ( !m_pFadeValue ) return NULL; return m_pFadeValue->GetOwningMaterial(); } EXPOSE_INTERFACE( CLampHaloProxy, IMaterialProxy, "lamphalo" IMATERIAL_PROXY_INTERFACE_VERSION );
412
0.750518
1
0.750518
game-dev
MEDIA
0.727779
game-dev
0.525924
1
0.525924
ProjectIgnis/CardScripts
2,705
official/c12444060.lua
--アーティファクトの神智 --Artifact Sanctum local s,id=GetID() function s.initial_effect(c) --Activate 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:SetHintTiming(0,TIMINGS_CHECK_MONSTER_E|TIMING_ATTACK|TIMING_BATTLE_START) e1:SetCountLimit(1,id,EFFECT_COUNT_CODE_OATH) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) --Destroy 1 card on the field local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetCategory(CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_DESTROYED) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET) e2:SetCondition(s.descon) e2:SetTarget(s.destg) e2:SetOperation(s.desop) c:RegisterEffect(e2) end s.listed_series={SET_ARTIFACT} function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_BATTLE_PHASE)==0 end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_BP) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE|PHASE_END) Duel.RegisterEffect(e1,tp) aux.RegisterClientHint(e:GetHandler(),nil,tp,1,0,aux.Stringid(id,2),nil) end function s.filter(c,e,tp) return c:IsSetCard(SET_ARTIFACT) 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_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_DECK) end function s.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if #g>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end function s.descon(e,tp,eg,ep,ev,re,r,rp) return rp==1-tp and e:GetHandler():IsPreviousControler(tp) end function s.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() end if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function s.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end
412
0.900798
1
0.900798
game-dev
MEDIA
0.992351
game-dev
0.913916
1
0.913916
QuickCarpet/QuickCarpet
2,081
src/main/java/quickcarpet/client/ClientSetting.java
package quickcarpet.client; import fi.dy.masa.malilib.config.IConfigHandler; import java.util.function.Supplier; @SuppressWarnings("Convert2MethodRef") public class ClientSetting<T> { private static final boolean HAS_MALILIB; static { boolean malilib = false; try { IConfigHandler.class.getName(); malilib = true; } catch (LinkageError ignored) {} HAS_MALILIB = malilib; } public static final ClientSetting<Boolean> SYNC_LOW_TPS = new ClientSetting<>("syncLowTps", true, () -> Configs.Generic.SYNC_LOW_TPS.getBooleanValue()); public static final ClientSetting<Boolean> SYNC_HIGH_TPS = new ClientSetting<>("syncHighTps", false, () -> Configs.Generic.SYNC_HIGH_TPS.getBooleanValue()); public static final ClientSetting<Boolean> MOVING_BLOCK_CULLING = new ClientSetting<>("movingBlockCulling", false, () -> Configs.Rendering.MOVING_BLOCK_CULLING.getBooleanValue()); public static final ClientSetting<Boolean> CREATIVE_NO_CLIP = new ClientSetting<>("creativeNoClip", false, () -> Configs.Generic.CREATIVE_NO_CLIP.getBooleanValue()); public static final ClientSetting<Boolean> CREATIVE_NO_CLIP_OVERRIDE = new ClientSetting<>("creativeNoClipOverride", false, () -> Configs.Generic.CREATIVE_NO_CLIP_OVERRIDE.getBooleanValue()); public static final ClientSetting<Boolean> SOUND_ENGINE_FIX = new ClientSetting<>("soundEngineFix", true, () -> Configs.Generic.SOUND_ENGINE_FIX.getBooleanValue()); public static final ClientSetting<Boolean> REMOVE_NBT_SIZE_LIMIT = new ClientSetting<>("removeNbtSizeLimit", true, () -> Configs.Generic.REMOVE_NBT_SIZE_LIMIT.getBooleanValue()); public final String id; public final T defaultValue; private final Supplier<T> malilibGetter; private ClientSetting(String id, T defaultValue, Supplier<T> malilibGetter) { this.id = id; this.defaultValue = defaultValue; this.malilibGetter = malilibGetter; } public T get() { if (!HAS_MALILIB) return defaultValue; return malilibGetter.get(); } }
412
0.597339
1
0.597339
game-dev
MEDIA
0.586292
game-dev
0.527179
1
0.527179
aldostools/webMAN-MOD
8,490
include/ps3mapi/peek_poke.h
#define SC_PEEK_LV2 (6) #define SC_POKE_LV2 (7) #define SC_PEEK_LV1 (8) #define SC_POKE_LV1 (9) #define SC_PEEK_LV1_COBRA (11) #define PS3MAPI_OPCODE_LV2_PEEK 0x1006 #define PS3MAPI_OPCODE_LV2_POKE 0x1007 #define PS3MAPI_OPCODE_LV1_PEEK 0x1008 #define PS3MAPI_OPCODE_LV1_POKE 0x1009 #define SYSCALL8_OPCODE_PS3MAPI 0x7777 #define PS3MAPI_OPCODE_LV1_POKE 0x1009 #define CFW_SYSCALLS_REMOVED(a) ((lv2_peek_hen(a) & 0xFFFFFFFFFF000000ULL) != BASE_MEMORY) /////////////////// LV1 PEEK ////////////////////// static u64 lv1_peek_cfw(u64 addr) { system_call_1(SC_PEEK_LV1, addr); return (u64) p1; } #ifdef OVERCLOCKING static u64 lv1_peek_cobra(u64 addr) { system_call_1(SC_PEEK_LV1_COBRA, addr); return (u64) p1; } #endif #ifdef COBRA_ONLY /* static process_id_t vsh_pid = 0; static void get_vsh_pid(void) { #define MAX_PROCESS 16 char name[25]; u32 tmp_pid_list[MAX_PROCESS]; system_call_3(SC_COBRA_SYSCALL8, SYSCALL8_OPCODE_PS3MAPI, PS3MAPI_OPCODE_GET_ALL_PROC_PID, (u64)(u32)tmp_pid_list); for (int i = 0; i < MAX_PROCESS; i++) { system_call_4(SC_COBRA_SYSCALL8, SYSCALL8_OPCODE_PS3MAPI, PS3MAPI_OPCODE_GET_PROC_NAME_BY_PID, tmp_pid_list[i], (u64)(u32)name); if (strstr(name, "vsh")) { vsh_pid = tmp_pid_list[i]; break; } } } static void poke_vsh(u64 address, char *buf, int size) { if(!vsh_pid) get_vsh_pid(); if (vsh_pid) system_call_6(SC_COBRA_SYSCALL8, SYSCALL8_OPCODE_PS3MAPI, PS3MAPI_OPCODE_SET_PROC_MEM, vsh_pid, address, (u64)(u32)buf, size); } */ static u64 lv1_peek_ps3mapi(u64 addr) { system_call_3(SC_COBRA_SYSCALL8, SYSCALL8_OPCODE_PS3MAPI, PS3MAPI_OPCODE_LV1_PEEK, addr); return (u64) p1; } /////////////////// LV1 POKE ////////////////////// static void lv1_poke_ps3mapi(u64 addr, u64 value) { system_call_4(SC_COBRA_SYSCALL8, SYSCALL8_OPCODE_PS3MAPI, PS3MAPI_OPCODE_LV1_POKE, addr, value); } #endif //#ifdef COBRA_ONLY static void lv1_poke_cfw( u64 addr, u64 value) { system_call_2(SC_POKE_LV1, addr, value); } /////////////////// LV2 PEEK ////////////////////// static u64 lv2_peek_cfw(u64 addr) //sc8 + LV2_OFFSET_ON_LV1 { system_call_1(SC_PEEK_LV1, addr + LV2_OFFSET_ON_LV1); //old: {system_call_1(SC_PEEK_LV2, addr);} return (u64) p1; } static u64 lv2_peek_hen(u64 addr) //sc6 { system_call_1(SC_PEEK_LV2, addr); return (u64) p1; } #ifdef COBRA_ONLY static u64 lv2_peek_ps3mapi(u64 addr) //sc8 + ps3mapi { system_call_3(SC_COBRA_SYSCALL8, SYSCALL8_OPCODE_PS3MAPI, PS3MAPI_OPCODE_LV2_PEEK, addr); return (u64) p1; } /////////////////// LV2 POKE ////////////////////// static void lv2_poke_hen(u64 addr, u64 value) //sc7 { system_call_2(SC_POKE_LV2, addr, value); } static void lv2_poke_ps3mapi(u64 addr, u64 value) //sc8 + ps3mapi { system_call_4(SC_COBRA_SYSCALL8, SYSCALL8_OPCODE_PS3MAPI, PS3MAPI_OPCODE_LV2_POKE, addr, value); } #endif //#ifdef COBRA_ONLY static void lv2_poke_cfw(u64 addr, u64 value) //sc8 + LV2_OFFSET_ON_LV1 { system_call_2(SC_POKE_LV1, addr + LV2_OFFSET_ON_LV1, value); } /////////////////////////////////////////////////// static void (*lv2_poke_fan)(u64, u64) = lv2_poke_cfw; // ps3hen: lv2_poke_fan = lv2_poke_fan_hen; static u64 (*peekq)(u64) = lv2_peek_cfw; static void (*pokeq)(u64, u64) = lv2_poke_cfw; static u64 (*peek_lv1)(u64) = lv1_peek_cfw; static void (*poke_lv1)(u64, u64) = lv1_poke_cfw; static u64 peek(u64 addr) { return peekq(addr | BASE_MEMORY); } static bool is_ingame_first_15_seconds(void) { if(payload_ps3hen && IS_INGAME) { CellRtcTick pTick; cellRtcGetCurrentTick(&pTick); if(gTick.tick == rTick.tick) gTick.tick = pTick.tick; if(pTick.tick < gTick.tick + 15000000) return true; // do not poke within the first 15 seconds ingame } return false; } #ifdef COBRA_ONLY ///////////////// LV1/LV2 POKE HEN //////////////// static void lv2_poke_fan_hen(u64 addr, u64 value) { if(is_ingame_first_15_seconds()) return; // do not poke within the first 15 seconds ingame system_call_2(SC_POKE_LV2, addr, value); //{system_call_3(SC_COBRA_SYSCALL8, 0x7003ULL, addr, value);} // advanced poke (requires restore original value) } static void lv1_poke_hen(u64 addr, u64 value) { if(addr >= LV2_OFFSET_ON_LV1) pokeq((addr - LV2_OFFSET_ON_LV1) | BASE_MEMORY, value); else poke_lv1(addr, value); } static u64 lv1_peek_hen(u64 addr) { if(addr >= LV2_OFFSET_ON_LV1) return peek(addr - LV2_OFFSET_ON_LV1); else return peek_lv1(addr); } /////////////////////////////////////////////////// #endif #ifndef LITE_EDITION /*********************************************************************** * lv2 peek 32 bit ***********************************************************************/ static u32 lv2_peek_32(u64 addr) { return (u32)(peekq(addr) >>32); } /*********************************************************************** * lv2 poke 32 bit ***********************************************************************/ static void lv2_poke_32(u64 addr, u32 value) { u64 value_org = peekq(addr); pokeq(addr, (value_org & 0xFFFFFFFFULL) | (((u64)value) <<32)); } #endif #ifndef COBRA_ONLY static inline void remove_lv2_memory_protection(void) { u64 HV_START_OFFSET = 0; //Remove Lv2 memory protection if(c_firmware==3.55f) { HV_START_OFFSET = HV_START_OFFSET_355; } else if(c_firmware==4.21f) { HV_START_OFFSET = HV_START_OFFSET_421; } else if(c_firmware>=4.30f && c_firmware<=4.53f) { HV_START_OFFSET = HV_START_OFFSET_430; // same for 4.30-4.53 } else if(c_firmware>=4.55f /*&& c_firmware<=LATEST_CFW*/) { HV_START_OFFSET = HV_START_OFFSET_455; // same for 4.55-4.92 } if(!HV_START_OFFSET) return; poke_lv1(HV_START_OFFSET + 0x00, 0x0000000000000001ULL); poke_lv1(HV_START_OFFSET + 0x08, 0xe0d251b556c59f05ULL); poke_lv1(HV_START_OFFSET + 0x10, 0xc232fcad552c80d7ULL); poke_lv1(HV_START_OFFSET + 0x18, 0x65140cd200000000ULL); } static void install_peek_poke(void) { remove_lv2_memory_protection(); if(c_firmware>=4.30f /*&& c_firmware<=LATEST_CFW*/) { #define INSTALL_PEEK_POKE_OFFSET 0x800000000000171CULL // add lv2 peek/poke + lv1 peek/poke pokeq(INSTALL_PEEK_POKE_OFFSET + 0x00, 0x7C0802A6F8010010ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x08, 0x396000B644000022ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x10, 0x7C832378E8010010ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x18, 0x7C0803A64E800020ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x20, 0x7C0802A6F8010010ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x28, 0x396000B744000022ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x30, 0x38600000E8010010ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x38, 0x7C0803A64E800020ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x40, 0x7C0802A6F8010010ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x48, 0x7D4B537844000022ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x50, 0xE80100107C0803A6ULL); pokeq(INSTALL_PEEK_POKE_OFFSET + 0x58, 0x4E80002080000000ULL); // sc6 @ 0x8000000000001778 = 800000000000170C pokeq(INSTALL_PEEK_POKE_OFFSET + 0x60, 0x0000170C80000000ULL); // sc7 @ 0x8000000000001780 = 8000000000001714 pokeq(INSTALL_PEEK_POKE_OFFSET + 0x68, 0x0000171480000000ULL); // sc8 @ 0x8000000000001788 = 800000000000171C pokeq(INSTALL_PEEK_POKE_OFFSET + 0x70, 0x0000171C80000000ULL); // sc9 @ 0x8000000000001790 = 800000000000173C pokeq(INSTALL_PEEK_POKE_OFFSET + 0x78, 0x0000173C80000000ULL); // sc10 @ 0x8000000000001798 = 800000000000175C pokeq(INSTALL_PEEK_POKE_OFFSET + 0x80, 0x0000175C00000000ULL); // enable syscalls 6, 7, 8, 9, 10 for(u8 sc = 6; sc < 11; sc++) pokeq(SYSCALL_PTR(sc), 0x8000000000001748ULL + sc * 8ULL); // 0x8000000000001778 (sc6) to 0x8000000000001798 (sc10) } } #define MAX_PATH_MAP 384 typedef struct { char src[MAX_PATH_MAP]; char dst[MAX_PATH_MAP]; } redir_files_struct; static redir_files_struct file_to_map[10]; static void add_to_map(const char *path1, const char *path2) { if(max_mapped == 0) pokeq(MAP_BASE + 0x00, 0x0000000000000000ULL); if(max_mapped < 10) { for(u8 n = 0; n < max_mapped; n++) { if(IS(file_to_map[n].src, path1)) return; } strcpy(file_to_map[max_mapped].src, path1); strcpy(file_to_map[max_mapped].dst, path2); max_mapped++; } } static u16 string_to_lv2(const char *path, u64 addr) { u16 len = MIN(strlen(path), MAX_PATH_MAP - 1); u8 data[MAX_PATH_MAP]; u64 *data2 = (u64 *)data; _memset(data, MAX_PATH_MAP); memcpy(data, path, len); len = (len + 7) >> 3; for(u8 n = 0; n < (MAX_PATH_MAP / 8); n++, addr += 8) { pokeq(addr, data2[n]); } return len * 8; } #endif //#ifndef COBRA_ONLY
412
0.953557
1
0.953557
game-dev
MEDIA
0.624178
game-dev,drivers
0.914863
1
0.914863
CreatureChat/creature-chat
2,084
src/main/java/com/owlmaddie/message/MessageParser.java
// SPDX-FileCopyrightText: 2025 owlmaddie LLC // SPDX-License-Identifier: GPL-3.0-or-later // Assets CC-BY-NC-SA-4.0; CreatureChat™ trademark © owlmaddie LLC - unauthorized use prohibited package com.owlmaddie.message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The {@code MessageParser} class parses out behaviors that are included in messages, and outputs * a {@code ParsedMessage} result, which separates the cleaned message and the included behaviors. */ public class MessageParser { public static final Logger LOGGER = LoggerFactory.getLogger("creaturechat"); public static ParsedMessage parseMessage(String input) { LOGGER.debug("Parsing message: {}", input); StringBuilder cleanedMessage = new StringBuilder(); List<Behavior> behaviors = new ArrayList<>(); Pattern pattern = Pattern.compile("[<*](FOLLOW|LEAD|FLEE|ATTACK|PROTECT|FRIENDSHIP|UNFOLLOW|UNLEAD|UNPROTECT|UNFLEE)[:\\s]*(\\s*[+-]?\\d+)?[>*]", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String behaviorName = matcher.group(1); Integer argument = null; if (matcher.group(2) != null) { argument = Integer.valueOf(matcher.group(2)); } behaviors.add(new Behavior(behaviorName, argument)); LOGGER.debug("Found behavior: {} with argument: {}", behaviorName, argument); matcher.appendReplacement(cleanedMessage, ""); } matcher.appendTail(cleanedMessage); // Get final cleaned string String displayMessage = cleanedMessage.toString().trim(); // Remove all occurrences of "<>" and "**" (if any) displayMessage = displayMessage.replaceAll("<>", "").replaceAll("\\*\\*", "").trim(); LOGGER.debug("Cleaned message: {}", displayMessage); return new ParsedMessage(displayMessage, input.trim(), behaviors); } }
412
0.834993
1
0.834993
game-dev
MEDIA
0.145532
game-dev
0.93
1
0.93
Detanup01/gbe_fork
13,878
sdk/steam/isteamremoteplay.h
//============ Copyright (c) Valve Corporation, All rights reserved. ============ #ifndef ISTEAMREMOTEPLAY_H #define ISTEAMREMOTEPLAY_H #ifdef STEAM_WIN32 #pragma once #endif #include "steam_api_common.h" //----------------------------------------------------------------------------- // Purpose: The form factor of a device //----------------------------------------------------------------------------- enum ESteamDeviceFormFactor { k_ESteamDeviceFormFactorUnknown = 0, k_ESteamDeviceFormFactorPhone = 1, k_ESteamDeviceFormFactorTablet = 2, k_ESteamDeviceFormFactorComputer = 3, k_ESteamDeviceFormFactorTV = 4, k_ESteamDeviceFormFactorVRHeadset = 5, }; // Steam Remote Play session ID typedef uint32 RemotePlaySessionID_t; // Steam Remote Play mouse cursor ID typedef uint32 RemotePlayCursorID_t; //----------------------------------------------------------------------------- // Purpose: The type of input in ERemotePlayInput_t //----------------------------------------------------------------------------- enum ERemotePlayInputType { k_ERemotePlayInputUnknown, k_ERemotePlayInputMouseMotion, k_ERemotePlayInputMouseButtonDown, k_ERemotePlayInputMouseButtonUp, k_ERemotePlayInputMouseWheel, k_ERemotePlayInputKeyDown, k_ERemotePlayInputKeyUp }; //----------------------------------------------------------------------------- // Purpose: Mouse buttons in ERemotePlayInput_t //----------------------------------------------------------------------------- enum ERemotePlayMouseButton { k_ERemotePlayMouseButtonLeft = 0x0001, k_ERemotePlayMouseButtonRight = 0x0002, k_ERemotePlayMouseButtonMiddle = 0x0010, k_ERemotePlayMouseButtonX1 = 0x0020, k_ERemotePlayMouseButtonX2 = 0x0040, }; //----------------------------------------------------------------------------- // Purpose: Mouse wheel direction in ERemotePlayInput_t //----------------------------------------------------------------------------- enum ERemotePlayMouseWheelDirection { k_ERemotePlayMouseWheelUp = 1, k_ERemotePlayMouseWheelDown = 2, k_ERemotePlayMouseWheelLeft = 3, k_ERemotePlayMouseWheelRight = 4, }; //----------------------------------------------------------------------------- // Purpose: Key scancode in ERemotePlayInput_t // // This is a USB scancode value as defined for the Keyboard/Keypad Page (0x07) // This enumeration isn't a complete list, just the most commonly used keys. //----------------------------------------------------------------------------- enum ERemotePlayScancode { k_ERemotePlayScancodeUnknown = 0, k_ERemotePlayScancodeA = 4, k_ERemotePlayScancodeB = 5, k_ERemotePlayScancodeC = 6, k_ERemotePlayScancodeD = 7, k_ERemotePlayScancodeE = 8, k_ERemotePlayScancodeF = 9, k_ERemotePlayScancodeG = 10, k_ERemotePlayScancodeH = 11, k_ERemotePlayScancodeI = 12, k_ERemotePlayScancodeJ = 13, k_ERemotePlayScancodeK = 14, k_ERemotePlayScancodeL = 15, k_ERemotePlayScancodeM = 16, k_ERemotePlayScancodeN = 17, k_ERemotePlayScancodeO = 18, k_ERemotePlayScancodeP = 19, k_ERemotePlayScancodeQ = 20, k_ERemotePlayScancodeR = 21, k_ERemotePlayScancodeS = 22, k_ERemotePlayScancodeT = 23, k_ERemotePlayScancodeU = 24, k_ERemotePlayScancodeV = 25, k_ERemotePlayScancodeW = 26, k_ERemotePlayScancodeX = 27, k_ERemotePlayScancodeY = 28, k_ERemotePlayScancodeZ = 29, k_ERemotePlayScancode1 = 30, k_ERemotePlayScancode2 = 31, k_ERemotePlayScancode3 = 32, k_ERemotePlayScancode4 = 33, k_ERemotePlayScancode5 = 34, k_ERemotePlayScancode6 = 35, k_ERemotePlayScancode7 = 36, k_ERemotePlayScancode8 = 37, k_ERemotePlayScancode9 = 38, k_ERemotePlayScancode0 = 39, k_ERemotePlayScancodeReturn = 40, k_ERemotePlayScancodeEscape = 41, k_ERemotePlayScancodeBackspace = 42, k_ERemotePlayScancodeTab = 43, k_ERemotePlayScancodeSpace = 44, k_ERemotePlayScancodeMinus = 45, k_ERemotePlayScancodeEquals = 46, k_ERemotePlayScancodeLeftBracket = 47, k_ERemotePlayScancodeRightBracket = 48, k_ERemotePlayScancodeBackslash = 49, k_ERemotePlayScancodeSemicolon = 51, k_ERemotePlayScancodeApostrophe = 52, k_ERemotePlayScancodeGrave = 53, k_ERemotePlayScancodeComma = 54, k_ERemotePlayScancodePeriod = 55, k_ERemotePlayScancodeSlash = 56, k_ERemotePlayScancodeCapsLock = 57, k_ERemotePlayScancodeF1 = 58, k_ERemotePlayScancodeF2 = 59, k_ERemotePlayScancodeF3 = 60, k_ERemotePlayScancodeF4 = 61, k_ERemotePlayScancodeF5 = 62, k_ERemotePlayScancodeF6 = 63, k_ERemotePlayScancodeF7 = 64, k_ERemotePlayScancodeF8 = 65, k_ERemotePlayScancodeF9 = 66, k_ERemotePlayScancodeF10 = 67, k_ERemotePlayScancodeF11 = 68, k_ERemotePlayScancodeF12 = 69, k_ERemotePlayScancodeInsert = 73, k_ERemotePlayScancodeHome = 74, k_ERemotePlayScancodePageUp = 75, k_ERemotePlayScancodeDelete = 76, k_ERemotePlayScancodeEnd = 77, k_ERemotePlayScancodePageDown = 78, k_ERemotePlayScancodeRight = 79, k_ERemotePlayScancodeLeft = 80, k_ERemotePlayScancodeDown = 81, k_ERemotePlayScancodeUp = 82, k_ERemotePlayScancodeLeftControl = 224, k_ERemotePlayScancodeLeftShift = 225, k_ERemotePlayScancodeLeftAlt = 226, k_ERemotePlayScancodeLeftGUI = 227, // windows, command (apple), meta k_ERemotePlayScancodeRightControl = 228, k_ERemotePlayScancodeRightShift = 229, k_ERemotePlayScancodeRightALT = 230, k_ERemotePlayScancodeRightGUI = 231, // windows, command (apple), meta }; //----------------------------------------------------------------------------- // Purpose: Key modifier in ERemotePlayInput_t //----------------------------------------------------------------------------- enum ERemotePlayKeyModifier { k_ERemotePlayKeyModifierNone = 0x0000, k_ERemotePlayKeyModifierLeftShift = 0x0001, k_ERemotePlayKeyModifierRightShift = 0x0002, k_ERemotePlayKeyModifierLeftControl = 0x0040, k_ERemotePlayKeyModifierRightControl = 0x0080, k_ERemotePlayKeyModifierLeftAlt = 0x0100, k_ERemotePlayKeyModifierRightAlt = 0x0200, k_ERemotePlayKeyModifierLeftGUI = 0x0400, k_ERemotePlayKeyModifierRightGUI = 0x0800, k_ERemotePlayKeyModifierNumLock = 0x1000, k_ERemotePlayKeyModifierCapsLock = 0x2000, k_ERemotePlayKeyModifierMask = 0xFFFF, }; #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx #endif // Mouse motion event data, valid when m_eType is k_ERemotePlayInputMouseMotion struct RemotePlayInputMouseMotion_t { bool m_bAbsolute; // True if this is absolute mouse motion and m_flNormalizedX and m_flNormalizedY are valid float m_flNormalizedX; // The absolute X position of the mouse, normalized to the display, if m_bAbsolute is true float m_flNormalizedY; // The absolute Y position of the mouse, normalized to the display, if m_bAbsolute is true int m_nDeltaX; // Relative mouse motion in the X direction int m_nDeltaY; // Relative mouse motion in the Y direction }; // Mouse wheel event data, valid when m_eType is k_ERemotePlayInputMouseWheel struct RemotePlayInputMouseWheel_t { ERemotePlayMouseWheelDirection m_eDirection; float m_flAmount; // 1.0f is a single click of the wheel, 120 units on Windows }; // Key event data, valid when m_eType is k_ERemotePlayInputKeyDown or k_ERemotePlayInputKeyUp struct RemotePlayInputKey_t { int m_eScancode; // Keyboard scancode, common values are defined in ERemotePlayScancode uint32 m_unModifiers; // Mask of ERemotePlayKeyModifier active for this key event uint32 m_unKeycode; // UCS-4 character generated by the keypress, or 0 if it wasn't a character key, e.g. Delete or Left Arrow }; struct RemotePlayInput_t { RemotePlaySessionID_t m_unSessionID; ERemotePlayInputType m_eType; union { // Mouse motion event data, valid when m_eType is k_ERemotePlayInputMouseMotion RemotePlayInputMouseMotion_t m_MouseMotion; // Mouse button event data, valid when m_eType is k_ERemotePlayInputMouseButtonDown or k_ERemotePlayInputMouseButtonUp ERemotePlayMouseButton m_eMouseButton; // Mouse wheel event data, valid when m_eType is k_ERemotePlayInputMouseWheel RemotePlayInputMouseWheel_t m_MouseWheel; // Key event data, valid when m_eType is k_ERemotePlayInputKeyDown or k_ERemotePlayInputKeyUp RemotePlayInputKey_t m_Key; // Unused space for future use char padding[ 64 - ( sizeof( m_unSessionID ) + sizeof( m_eType ) ) ]; }; }; //COMPILE_TIME_ASSERT( sizeof( RemotePlayInput_t ) == 64 ); #pragma pack( pop ) //----------------------------------------------------------------------------- // Purpose: Functions to provide information about Steam Remote Play sessions //----------------------------------------------------------------------------- class ISteamRemotePlay { public: // Get the number of currently connected Steam Remote Play sessions virtual uint32 GetSessionCount() = 0; // Get the currently connected Steam Remote Play session ID at the specified index. Returns zero if index is out of bounds. virtual RemotePlaySessionID_t GetSessionID( int iSessionIndex ) = 0; // Get the SteamID of the connected user virtual CSteamID GetSessionSteamID( RemotePlaySessionID_t unSessionID ) = 0; // Get the name of the session client device // This returns NULL if the sessionID is not valid virtual const char *GetSessionClientName( RemotePlaySessionID_t unSessionID ) = 0; // Get the form factor of the session client device virtual ESteamDeviceFormFactor GetSessionClientFormFactor( RemotePlaySessionID_t unSessionID ) = 0; // Get the resolution, in pixels, of the session client device // This is set to 0x0 if the resolution is not available virtual bool BGetSessionClientResolution( RemotePlaySessionID_t unSessionID, int *pnResolutionX, int *pnResolutionY ) = 0; // Show the Remote Play Together UI in the game overlay // This returns false if your game is not configured for Remote Play Together virtual bool ShowRemotePlayTogetherUI() = 0; // Invite a friend to Remote Play Together, or create a guest invite if steamIDFriend is empty // This will automatically start Remote Play Together if it hasn't already been started // This returns false if the invite can't be sent or your game is not configured for Remote Play Together virtual bool BSendRemotePlayTogetherInvite( CSteamID steamIDFriend ) = 0; // Make mouse and keyboard input for Remote Play Together sessions available via GetInput() instead of being merged with local input virtual bool BEnableRemotePlayTogetherDirectInput() = 0; // Merge Remote Play Together mouse and keyboard input with local input virtual void DisableRemotePlayTogetherDirectInput() = 0; // Get input events from Remote Play Together sessions // This is available after calling BEnableRemotePlayTogetherDirectInput() // // pInput is an array of input events that will be filled in by this function, up to unMaxEvents. // This returns the number of events copied to pInput, or the number of events available if pInput is nullptr. virtual uint32 GetInput( RemotePlayInput_t *pInput, uint32 unMaxEvents ) = 0; // Set the mouse cursor visibility for a remote player // This is available after calling BEnableRemotePlayTogetherDirectInput() virtual void SetMouseVisibility( RemotePlaySessionID_t unSessionID, bool bVisible ) = 0; // Set the mouse cursor position for a remote player // This is available after calling BEnableRemotePlayTogetherDirectInput() // // This is used to warp the cursor to a specific location and isn't needed during normal event processing. // // The position is normalized relative to the window, where 0,0 is the upper left, and 1,1 is the lower right. virtual void SetMousePosition( RemotePlaySessionID_t unSessionID, float flNormalizedX, float flNormalizedY ) = 0; // Create a cursor that can be used with SetMouseCursor() // This is available after calling BEnableRemotePlayTogetherDirectInput() // // Parameters: // nWidth - The width of the cursor, in pixels // nHeight - The height of the cursor, in pixels // nHotX - The X coordinate of the cursor hot spot in pixels, offset from the left of the cursor // nHotY - The Y coordinate of the cursor hot spot in pixels, offset from the top of the cursor // pBGRA - A pointer to the cursor pixels, with the color channels in red, green, blue, alpha order // nPitch - The distance between pixel rows in bytes, defaults to nWidth * 4 virtual RemotePlayCursorID_t CreateMouseCursor( int nWidth, int nHeight, int nHotX, int nHotY, const void *pBGRA, int nPitch = 0 ) = 0; // Set the mouse cursor for a remote player // This is available after calling BEnableRemotePlayTogetherDirectInput() // // The cursor ID is a value returned by CreateMouseCursor() virtual void SetMouseCursor( RemotePlaySessionID_t unSessionID, RemotePlayCursorID_t unCursorID ) = 0; }; #define STEAMREMOTEPLAY_INTERFACE_VERSION "STEAMREMOTEPLAY_INTERFACE_VERSION003" // Global interface accessor inline ISteamRemotePlay *SteamRemotePlay(); STEAM_DEFINE_USER_INTERFACE_ACCESSOR( ISteamRemotePlay *, SteamRemotePlay, STEAMREMOTEPLAY_INTERFACE_VERSION ); // callbacks #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx #endif STEAM_CALLBACK_BEGIN( SteamRemotePlaySessionConnected_t, k_iSteamRemotePlayCallbacks + 1 ) STEAM_CALLBACK_MEMBER( 0, RemotePlaySessionID_t, m_unSessionID ) STEAM_CALLBACK_END( 0 ) STEAM_CALLBACK_BEGIN( SteamRemotePlaySessionDisconnected_t, k_iSteamRemotePlayCallbacks + 2 ) STEAM_CALLBACK_MEMBER( 0, RemotePlaySessionID_t, m_unSessionID ) STEAM_CALLBACK_END( 0 ) STEAM_CALLBACK_BEGIN( SteamRemotePlayTogetherGuestInvite_t, k_iSteamRemotePlayCallbacks + 3 ) STEAM_CALLBACK_MEMBER_ARRAY( 0, char, m_szConnectURL, 1024 ) STEAM_CALLBACK_END( 0 ) #pragma pack( pop ) #endif // #define ISTEAMREMOTEPLAY_H
412
0.832668
1
0.832668
game-dev
MEDIA
0.813079
game-dev
0.584525
1
0.584525
KAT-Advanced-Medical/KAM
1,704
addons/airway/functions/fnc_treatmentAdvanced_hyperextendHead.sqf
#include "..\script_component.hpp" /* * Author: Katalam * Overstretch the head of the patient for airway management without items * * Arguments: * 0: Medic <OBJECT> * 1: Patient <OBJECT> * * Return Value: * Succesful treatment <BOOL> * * Example: * [player, cursorTarget] call kat_airway_fnc_treatmentAdvanced_hyperextendHead; * * Public: No */ params ["_medic", "_patient"]; if (_patient getVariable [QGVAR(overstretch), false]) exitWith { [LLSTRING(Hyperextend_already), 1.5, _medic] call ACEFUNC(common,displayTextStructured); }; if !(_patient getVariable [QGVAR(obstruction), false]) exitWith { [LLSTRING(AirwayStatus_noObstruction), 1.5, _medic] call ACEFUNC(common,displayTextStructured); }; _patient setVariable [QGVAR(overstretch), true, true]; [LLSTRING(Hyperextend_Ready), 1.5, _medic, 11] call ACEFUNC(common,displayTextStructured); [_patient, "activity", LSTRING(Hyperextend_Log), [[_medic] call ACEFUNC(common,getName), [_patient] call ACEFUNC(common,getName)]] call ACEFUNC(medical_treatment,addToLog); [{ params ["_medic", "_patient"]; (_patient distance2D _medic) > 5; }, { params ["_medic", "_patient"]; if (_patient getVariable [QGVAR(recovery), false]) exitWith {}; _patient setVariable [QGVAR(overstretch), false, true]; [LLSTRING(Hyperextend_Cancel), 1.5, _medic] call ACEFUNC(common,displayTextStructured); }, [_medic, _patient], 3600, { params ["_medic", "_patient"]; if (_patient getVariable [QGVAR(recovery), false]) exitWith {}; _patient setVariable [QGVAR(overstretch), false, true]; [LLSTRING(Hyperextend_Cancel), 1.5, _medic] call ACEFUNC(common,displayTextStructured); }] call CBA_fnc_waitUntilAndExecute;
412
0.714413
1
0.714413
game-dev
MEDIA
0.311747
game-dev
0.79052
1
0.79052
kevinhuangdev/foundryvtt-importer
11,390
src/module/item/parsers/textBlock.ts
import { ActionType, Activation, ItemType, Damage, ShortAbility, Save, Uses, Target, Recharge, UniversalItemType, } from '../interfaces'; import { Range } from '../interfaces'; import { Feature, SectionLabel } from '../../actor/interfaces'; import { parseGenericFormula } from '../../actor/parsers/generic'; import { FifthItemType, FifthItem } from '../../actor/templates/fifthedition'; import { ItemParserInput } from '../typeGuardParserRunners'; function parseMeasurement(description: string, keyWord: string) { const unitText = description.split(keyWord)[0].trim(); const lastItem = unitText.split(' ').pop() || ''; return parseInt(lastItem.split('-')[0]); } export function parseSpellCone(description: string) { // like 20-foot-radius sphere return parseMeasurement(description, 'cone'); } export function parseSpellSphere(description: string) { // like 20-foot-radius sphere return parseMeasurement(description, 'radius'); } export function parseRange(description: string): Range | undefined { if (/reach/i.test(description)) { const stringValue = description.split(/reach/)[1].trim().split(' ')[0]; const value = parseInt(stringValue); if (!isNaN(value)) return { value, units: 'ft' }; } if (/range/i.test(description)) { const rangeStr = description.split(/range/i)[1].trim().split(' ')[0]; const [value, long] = rangeStr.split('/').map((str) => parseInt(str)); if (isNaN(value)) { const rangeRegex = /range (\d+) ft./; const rangeMatch = description.match(rangeRegex); if (rangeMatch) { const rangeValue = parseInt(rangeMatch[1]); if (!isNaN(rangeValue)) return { value: rangeValue, units: 'ft' }; } } if (!isNaN(value)) return { value, long, units: 'ft' }; } if (/cone/i.test(description)) { const value = parseSpellCone(description); if (!isNaN(value)) return { value, units: 'self' }; } if (/within/i.test(description)) { const rangeStr = description .split(/within/i)[1] .trim() .split('ft')[0] .trim(); const value = parseInt(rangeStr); if (!isNaN(value)) { return { value, units: 'ft' }; } } } export function parseDamageType(from: string): string { if (from.includes('piercing')) return 'piercing'; if (from.includes('slashing')) return 'slashing'; if (from.includes('bludgeoning')) return 'bludgeoning'; if (from.includes('fire')) return 'fire'; if (from.includes('cold')) return 'cold'; if (from.includes('lightning')) return 'lightning'; if (from.includes('acid')) return 'acid'; if (from.includes('poison')) return 'poison'; if (from.includes('psychic')) return 'psychic'; if (from.includes('radiant')) return 'radiant'; if (from.includes('thunder')) return 'thunder'; if (from.includes('force')) return 'force'; if (from.includes('necrotic')) return 'necrotic'; if (from.includes('psychic')) return 'psychic'; throw new Error(`Unable to parse damage type from ${from}`); } export function parseType(description: string): ItemType { // match if (1d8) if (isWeaponType(description)) return 'weapon'; if (/armor/i.test(description)) return 'equipment'; if (/unil the next dawn/i.test(description)) return 'consumable'; if (/beginning at/i.test(description)) return 'feat'; if (/starting at/i.test(description)) return 'feat'; return 'consumable'; } export function parseActivation(name: string, description: string, section?: SectionLabel): Activation | undefined { // cost parsed from something like Wings of Syranita (Costs 2 Actions) const costString = name.match(/\(Costs (\d+) Actions\)/); const cost = costString ? parseInt(costString[1]) : 1; if (section) { switch (section) { case 'action': { return { type: 'action', cost, }; } case 'bonus': { return { type: 'bonus', cost, }; } case 'reaction': { return { type: 'reaction', cost, }; } case 'legendary': { return { type: 'legendary', cost, }; } } } if (/attack/i.test(description)) return { type: 'action', cost, }; if (description.includes('action')) return { type: 'action', cost, }; if (description.includes('bonus action')) return { type: 'bonus', cost, }; if (description.includes('spell save')) return { type: 'action', cost, }; if (description.includes('saving throw')) return { type: 'action', cost, }; } export function buildDamageParts(description: string): string[][] { // description = 'Melee Weapon Attack: +6 to hit, reach 5 ft., one target.Hit: 8 (1d8 + 4) piercing damage.' const uncleanParts = description.split('plus'); if (!uncleanParts) throw new Error(`Unable to parse damage parts from ${description}`); const parts = uncleanParts.map((part) => { const parsed = parseGenericFormula(part, /Melee Weapon Attack: +/); if (!parsed || !parsed?.str) throw new Error(`Unable to parse damage parts from ${description}`); const fromString = parsed.afterFormula ? parsed.afterFormula : part; return [parsed.str, parseDamageType(fromString)]; }); return parts; } // regex to match a die formula export function isWeaponType(input: string): boolean { const dieRegex = /(\d+d\d+)/; return dieRegex.test(input) && /weapon/i.test(input); } // the logic for parsing type is different if it is sourced from a monster export function parseTypeFromActorFeature(input: string): ItemType { if (isWeaponType(input)) return 'weapon'; if (/weapon attack:/i.test(input)) return 'weapon'; if (/spell attack/i.test(input)) return 'spell'; if (/beginning at/i.test(input)) return 'feat'; if (/starting at/i.test(input)) return 'feat'; return 'feat'; } export function parseActionType(description: string): ActionType { if (/melee/i.test(description)) return 'mwak'; if (/ranged/i.test(description)) return 'rwak'; if (/spell save/i.test(description)) return 'save'; if (/saving throw/i.test(description)) return 'save'; throw new Error(`Could not parse action type from ${description}`); } export function parsePossibleActionType(description: string): ActionType | undefined { if (/Melee Weapon Attack/.test(description)) return 'mwak'; if (/Ranged Weapon Attack/.test(description)) return 'rwak'; if (/spell save/i.test(description)) return 'save'; if (/saving throw/i.test(description)) return 'save'; return; } function abilityToLongShort(ability: string) { if (/str/i.test(ability)) return ['str', 'strength']; if (/dex/i.test(ability)) return ['dex', 'dexterity']; if (/con/i.test(ability)) return ['con', 'constitution']; if (/int/i.test(ability)) return ['int', 'intelligence']; if (/wis/i.test(ability)) return ['wis', 'wisdom']; if (/cha/i.test(ability)) return ['cha', 'charisma']; return ['', '']; } export function actionTypeExtraData(actionType: string | undefined, { description }: Feature) { let building = {}; if (!actionType) return building; if (actionType === 'save') { const dc = description.split('DC')[1].trim().split(' ')[0].trim(); const uncleanAbility = description.split(dc)[1].trim().split(' ')[0].trim(); const [short] = abilityToLongShort(uncleanAbility); building = { ...building, ability: short, save: { ability: short, dc: parseInt(dc), scaling: 'spell', }, }; } return building; } /** * @param name the name of the spell * @param description the description of the spell * @returns { value: number, charged: boolean } * * @example * parseSpell('Poison Breath (Recharge 5-6)', 'A poisonous gas cloud spreads from the dragon\'s mouth, */ function parseRecharge(name: string): Recharge { if (!name.toLowerCase().includes('recharge')) { throw new Error(`${name} is not a recharge spell`); } const [, recharge] = name.toLowerCase().split('recharge'); let range: string[] = []; if (recharge.includes('-')) { range = recharge.split('-'); } else if (recharge.includes('–')) { range = recharge.split('–'); } const [lower, upper] = range; return { value: parseInt(lower), charged: upper ? true : false, }; } export function parseUses(name: string, description: string): Uses | undefined { function parseDay(from: string): Uses | undefined { const perDay = parseInt(from.split('/')[0].split('(')[1]); if (isNaN(perDay)) return; return { per: 'day', value: perDay, max: perDay, }; } if (/\/day/i.test(name)) { return parseDay(name); } if (/\/day/i.test(description)) { return parseDay(description); } } function parseTarget(description: string): Target { if (/radius/i.test(description)) { return { type: 'sphere', value: parseSpellSphere(description), units: 'ft', }; } if (/cone/i.test(description)) { return { type: 'cone', value: parseSpellCone(description), units: 'ft', }; } throw new Error(`Unable to parse target from ${description}`); } export function parseToItem({ name, description, ability, section }: ItemParserInput): UniversalItemType { const itemType: FifthItemType = parseTypeFromActorFeature(description); let damage: undefined | Damage = undefined; try { damage = { parts: buildDamageParts(description) }; } catch (_) { // spell doesn't require damage } const actionType = parsePossibleActionType(description); let save: Save | undefined = undefined; if (actionType === 'save') { const rawDC = description?.split('DC')[1]?.trim()?.split(' ')[0]?.trim() ?? ''; const uncleanAbility = description?.split(rawDC)[1]?.trim()?.split(' ')[0]?.trim() ?? ''; const [short] = abilityToLongShort(uncleanAbility); ability = short as ShortAbility; if (!rawDC) save = undefined; else { save = { ability: short, dc: parseInt(rawDC), scaling: 'flat', }; } } let uses; try { uses = parseUses(name, description); } catch (_) { // uses can be undefined } let recharge; try { recharge = parseRecharge(name); } catch (_) { // recharge can be undefined } let target; try { target = parseTarget(description); } catch (_) { // target can be undefined } let range; try { range = parseRange(description); } catch (_) { // range can be undefined } return { name, type: itemType, ability, uses, save, recharge, description, activation: parseActivation(name, description, section), damage, actionType, range, attackBonus: 0, target, }; } export function parsedToWeapon(name: string, inputDescription: string, inputAbility?: string): FifthItem { const parsedWeapon = parseToItem({ name, description: inputDescription, ability: inputAbility as ShortAbility }); const { type, description, activation, damage, actionType, range, ability, attackBonus } = parsedWeapon; return { name, type, data: { description: { value: description, }, activation, damage, actionType, range, ability, attackBonus: attackBonus?.toString(), }, }; }
412
0.866768
1
0.866768
game-dev
MEDIA
0.718975
game-dev
0.969355
1
0.969355
Secrets-of-Sosaria/World
1,107
Data/Scripts/Items/Magical/God/Shields/LevelChampionShield.cs
using System; using Server; namespace Server.Items { public class LevelChampionShield : BaseLevelShield { public override int BasePhysicalResistance{ get{ return 0; } } public override int BaseFireResistance{ get{ return 1; } } public override int BaseColdResistance{ get{ return 0; } } public override int BasePoisonResistance{ get{ return 0; } } public override int BaseEnergyResistance{ get{ return 0; } } public override int InitMinHits{ get{ return 50; } } public override int InitMaxHits{ get{ return 65; } } public override int AosStrReq{ get{ return 90; } } public override int ArmorBase{ get{ return 23; } } [Constructable] public LevelChampionShield() : base( 0x2B74 ) { Name = "champion shield"; Weight = 8.0; } public LevelChampionShield( Serial serial ) : base(serial) { } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 );//version } } }
412
0.878858
1
0.878858
game-dev
MEDIA
0.374508
game-dev
0.754926
1
0.754926
tgstation/tgstation
7,862
code/modules/clothing/under/jobs/Plasmaman/civilian_service.dm
//Basically the assistant suit /obj/item/clothing/under/plasmaman name = "plasma envirosuit" desc = "A special containment suit that allows plasma-based lifeforms to exist safely in an oxygenated environment, and automatically extinguishes them in a crisis. Despite being airtight, it's not spaceworthy." icon_state = "plasmaman" inhand_icon_state = "plasmaman" icon = 'icons/obj/clothing/under/plasmaman.dmi' worn_icon = 'icons/mob/clothing/under/plasmaman.dmi' clothing_flags = PLASMAMAN_PREVENT_IGNITION armor_type = /datum/armor/clothing_under/plasmaman body_parts_covered = CHEST|GROIN|LEGS|FEET|ARMS can_adjust = FALSE strip_delay = 8 SECONDS COOLDOWN_DECLARE(extinguish_timer) var/extinguish_cooldown = 100 var/extinguishes_left = 5 /datum/armor/clothing_under/plasmaman bio = 100 fire = 95 acid = 95 /obj/item/clothing/under/plasmaman/examine(mob/user) . = ..() . += span_notice("There [extinguishes_left == 1 ? "is" : "are"] [extinguishes_left] extinguisher charges left in this suit.") /obj/item/clothing/under/plasmaman/equipped(mob/living/user, slot) . = ..() if (slot & ITEM_SLOT_ICLOTHING) RegisterSignals(user, list(COMSIG_MOB_EQUIPPED_ITEM, COMSIG_LIVING_IGNITED, SIGNAL_ADDTRAIT(TRAIT_HEAD_ATMOS_SEALED)), PROC_REF(check_fire_state)) check_fire_state() /obj/item/clothing/under/plasmaman/dropped(mob/living/user) . = ..() UnregisterSignal(user, list(COMSIG_MOB_EQUIPPED_ITEM, COMSIG_LIVING_IGNITED, SIGNAL_ADDTRAIT(TRAIT_HEAD_ATMOS_SEALED))) /obj/item/clothing/under/plasmaman/proc/check_fire_state(datum/source) SIGNAL_HANDLER if (!ishuman(loc)) return // This is weird but basically we're calling this proc once the cooldown ends in case our wearer gets set on fire again during said cooldown // This is why we're ignoring source and instead checking by loc var/mob/living/carbon/human/owner = loc if (!owner.on_fire || !owner.is_atmos_sealed(additional_flags = PLASMAMAN_PREVENT_IGNITION, check_hands = TRUE)) return if (!extinguishes_left || !COOLDOWN_FINISHED(src, extinguish_timer)) return extinguishes_left -= 1 COOLDOWN_START(src, extinguish_timer, extinguish_cooldown) // Check if our (possibly other) wearer is on fire once the cooldown ends addtimer(CALLBACK(src, PROC_REF(check_fire_state)), extinguish_cooldown) owner.visible_message(span_warning("[owner]'s suit automatically extinguishes [owner.p_them()]!"), span_warning("Your suit automatically extinguishes you.")) owner.extinguish_mob() new /obj/effect/particle_effect/water(get_turf(owner)) /obj/item/clothing/under/plasmaman/item_interaction(mob/living/user, obj/item/tool, list/modifiers) if (!istype(tool, /obj/item/extinguisher_refill)) return ..() if (extinguishes_left == 5) to_chat(user, span_notice("The inbuilt extinguisher is full.")) return ITEM_INTERACT_BLOCKING extinguishes_left = 5 to_chat(user, span_notice("You refill the suit's built-in extinguisher, using up the cartridge.")) check_fire_state() qdel(tool) return ITEM_INTERACT_SUCCESS /obj/item/extinguisher_refill name = "envirosuit extinguisher cartridge" desc = "A cartridge loaded with a compressed extinguisher mix, used to refill the automatic extinguisher on plasma envirosuits." icon_state = "plasmarefill" icon = 'icons/obj/canisters.dmi' /obj/item/clothing/under/plasmaman/cargo name = "cargo plasma envirosuit" desc = "A joint envirosuit used by plasmamen quartermasters and cargo techs alike, due to the logistical problems of differentiating the two with the length of their pant legs." icon_state = "cargo_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/mining name = "mining plasma envirosuit" desc = "An airtight khaki suit designed for operations on lavaland by plasmamen." icon_state = "explorer_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/chef name = "chef's plasma envirosuit" desc = "A white plasmaman envirosuit designed for culinary practices. One might question why a member of a species that doesn't need to eat would become a chef." icon_state = "chef_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/enviroslacks name = "enviroslacks" desc = "The pet project of a particularly posh plasmaman, this custom suit was quickly appropriated by Nanotrasen for its lawyers, and bartenders alike." icon_state = "enviroslacks" inhand_icon_state = null /obj/item/clothing/under/plasmaman/chaplain name = "chaplain's plasma envirosuit" desc = "An envirosuit specially designed for only the most pious of plasmamen." icon_state = "chap_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/curator name = "curator's plasma envirosuit" desc = "Made out of a modified voidsuit, this suit was Nanotrasen's first solution to the *logistical problems* that come with employing plasmamen. Due to the modifications, the suit is no longer space-worthy. Despite their limitations, these suits are still in used by historian and old-styled plasmamen alike." icon_state = "prototype_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/janitor name = "janitor's plasma envirosuit" desc = "A grey and purple envirosuit designated for plasmamen janitors." icon_state = "janitor_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/botany name = "botany envirosuit" desc = "A green and blue envirosuit designed to protect plasmamen from minor plant-related injuries." icon_state = "botany_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/mime name = "mime envirosuit" desc = "It's not very colourful." icon_state = "mime_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/clown name = "clown envirosuit" desc = "<i>'HONK!'</i>" icon_state = "clown_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/bitrunner name = "bitrunner envirosuit" desc = "An envirosuit specially designed for plasmamen with bad posture." icon_state = "bitrunner_envirosuit" inhand_icon_state = null /obj/item/clothing/under/plasmaman/clown/Initialize(mapload) . = ..() AddElement(/datum/element/swabable, CELL_LINE_TABLE_CLOWN, CELL_VIRUS_TABLE_GENERIC, rand(2,3), 0) /obj/item/clothing/under/plasmaman/prisoner name = "prisoner envirosuit" desc = "An orange envirosuit identifying and protecting a criminal plasmaman. Its suit sensors are stuck in the \"Fully On\" position." icon_state = "prisoner_envirosuit" inhand_icon_state = null has_sensor = LOCKED_SENSORS sensor_mode = SENSOR_COORDS random_sensor = FALSE /obj/item/clothing/under/plasmaman/clown/check_fire_state(datum/source, datum/status_effect/fire_handler/status_effect) if (!ishuman(loc)) return // This is weird but basically we're calling this proc once the cooldown ends in case our wearer gets set on fire again during said cooldown // This is why we're ignoring source and instead checking by loc var/mob/living/carbon/human/owner = loc if (!owner.on_fire || !owner.is_atmos_sealed(additional_flags = PLASMAMAN_PREVENT_IGNITION, check_hands = TRUE)) return if (!extinguishes_left || !COOLDOWN_FINISHED(src, extinguish_timer)) return extinguishes_left -= 1 COOLDOWN_START(src, extinguish_timer, extinguish_cooldown) // Check if our (possibly other) wearer is on fire once the cooldown ends addtimer(CALLBACK(src, PROC_REF(check_fire_state)), extinguish_cooldown) owner.visible_message(span_warning("[owner]'s suit spews space lube everywhere!"), span_warning("Your suit spews space lube everywhere!")) owner.extinguish_mob() var/datum/effect_system/fluid_spread/foam/foam = new var/datum/reagents/foamreagent = new /datum/reagents(15) foamreagent.add_reagent(/datum/reagent/lube, 15) foam.set_up(4, holder = src, location = get_turf(owner), carry = foamreagent) foam.start() //Truly terrifying.
412
0.842726
1
0.842726
game-dev
MEDIA
0.968815
game-dev
0.643122
1
0.643122
ForestryMC/Binnie
3,929
core/src/main/java/binnie/core/machines/ManagerMachine.java
package binnie.core.machines; import binnie.core.BinnieCore; import binnie.core.ManagerBase; import binnie.core.machines.inventory.ValidatorSprite; import binnie.core.machines.render.RenderTESRMachine; import binnie.core.proxy.IBinnieProxy; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ManagerMachine extends ManagerBase { private static ValidatorSprite spriteBee; private static ValidatorSprite spriteFrame; private static ValidatorSprite spriteCircuit; private static ValidatorSprite spriteBlock; private final Map<Class<?>, Class<?>[]> componentInterfaceMap; private final Map<String, MachineGroup> machineGroups; private int nextNetworkID; public ManagerMachine() { this.componentInterfaceMap = new HashMap<>(); this.machineGroups = new HashMap<>(); this.nextNetworkID = 0; } public static ValidatorSprite getSpriteBee() { return spriteBee; } public static ValidatorSprite getSpriteFrame() { return spriteFrame; } public static ValidatorSprite getSpriteCircuit() { return spriteCircuit; } public static ValidatorSprite getSpriteBlock() { return spriteBlock; } public void registerMachineGroup(final MachineGroup group) { this.machineGroups.put(group.getUID(), group); } public MachineGroup getGroup(final String name) { return this.machineGroups.get(name); } public MachinePackage getPackage(final String group, final String name) { final MachineGroup machineGroup = this.getGroup(group); return (machineGroup == null) ? null : machineGroup.getPackage(name); } private void registerComponentClass(final Class<? extends MachineComponent> component) { if (this.componentInterfaceMap.containsKey(component)) { return; } final Set<Class<?>> interfaces = new HashSet<>(); for (Class<?> currentClass = component; currentClass != null; currentClass = currentClass.getSuperclass()) { Collections.addAll(interfaces, currentClass.getInterfaces()); } interfaces.remove(INbtWritable.class); interfaces.remove(INbtReadable.class); this.componentInterfaceMap.put(component, interfaces.toArray(new Class[0])); final int networkID = this.nextNetworkID++; } @Override public void preInit() { spriteBee = new ValidatorSprite(BinnieCore.getInstance(), "validator/bee.0", "validator/bee.1"); spriteFrame = new ValidatorSprite(BinnieCore.getInstance(), "validator/frame.0", "validator/frame.1"); spriteCircuit = new ValidatorSprite(BinnieCore.getInstance(), "validator/circuit.0", "validator/circuit.1"); spriteBlock = new ValidatorSprite(BinnieCore.getInstance(), "validator/block.0", "validator/block.1"); } @Override public void postInit() { // TODO fix rendering Object rendererMachine = null; // BinnieCore.proxy.createObject("binnie.core.machines.RendererMachine"); BinnieCore.getBinnieProxy().registerTileEntity(TileEntityMachine.class, new ResourceLocation("binniecore:tile.machine")); BinnieCore.getBinnieProxy().registerTileEntity(TileEntityTESRMachine.class, new ResourceLocation("binniecore:tile.machine.tesr"), new IBinnieProxy.ClientSupplier<TileEntitySpecialRenderer<TileEntityTESRMachine>>() { @SideOnly(Side.CLIENT) @Override public TileEntitySpecialRenderer<TileEntityTESRMachine> get() { return new RenderTESRMachine(); } }); } @Nullable public Class<?>[] getComponentInterfaces(final Class<? extends MachineComponent> clss) { if (!this.componentInterfaceMap.containsKey(clss)) { this.registerComponentClass(clss); } return this.componentInterfaceMap.get(clss); } }
412
0.830102
1
0.830102
game-dev
MEDIA
0.736974
game-dev,graphics-rendering
0.906936
1
0.906936
patrykcieslak/stonefish
4,378
3rdparty/BulletCollision/CollisionShapes/btConvexHullShape.h
/* 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. */ #ifndef BT_CONVEX_HULL_SHAPE_H #define BT_CONVEX_HULL_SHAPE_H #include "btPolyhedralConvexShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types #include "LinearMath/btAlignedObjectArray.h" ///The btConvexHullShape implements an implicit convex hull of an array of vertices. ///Bullet provides a general and fast collision detector for convex shapes based on GJK and EPA using localGetSupportingVertex. ATTRIBUTE_ALIGNED16(class) btConvexHullShape : public btPolyhedralConvexAabbCachingShape { btAlignedObjectArray<btVector3> m_unscaledPoints; public: BT_DECLARE_ALIGNED_ALLOCATOR(); ///this constructor optionally takes in a pointer to points. Each point is assumed to be 3 consecutive btScalar (x,y,z), the striding defines the number of bytes between each point, in memory. ///It is easier to not pass any points in the constructor, and just add one point at a time, using addPoint. ///btConvexHullShape make an internal copy of the points. btConvexHullShape(const btScalar* points = 0, int numPoints = 0, int stride = sizeof(btVector3)); void addPoint(const btVector3& point, bool recalculateLocalAabb = true); btVector3* getUnscaledPoints() { return &m_unscaledPoints[0]; } const btVector3* getUnscaledPoints() const { return &m_unscaledPoints[0]; } ///getPoints is obsolete, please use getUnscaledPoints const btVector3* getPoints() const { return getUnscaledPoints(); } void optimizeConvexHull(); SIMD_FORCE_INLINE btVector3 getScaledPoint(int i) const { return m_unscaledPoints[i] * m_localScaling; } SIMD_FORCE_INLINE int getNumPoints() const { return m_unscaledPoints.size(); } virtual btVector3 localGetSupportingVertex(const btVector3& vec) const; virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const; virtual void project(const btTransform& trans, const btVector3& dir, btScalar& minProj, btScalar& maxProj, btVector3& witnesPtMin, btVector3& witnesPtMax) const; //debugging virtual const char* getName() const { return "Convex"; } virtual int getNumVertices() const; virtual int getNumEdges() const; virtual void getEdge(int i, btVector3& pa, btVector3& pb) const; virtual void getVertex(int i, btVector3& vtx) const; virtual int getNumPlanes() const; virtual void getPlane(btVector3 & planeNormal, btVector3 & planeSupport, int i) const; virtual bool isInside(const btVector3& pt, btScalar tolerance) const; ///in case we receive negative scaling virtual void setLocalScaling(const btVector3& scaling); virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; }; // clang-format off ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btConvexHullShapeData { btConvexInternalShapeData m_convexInternalShapeData; btVector3FloatData *m_unscaledPointsFloatPtr; btVector3DoubleData *m_unscaledPointsDoublePtr; int m_numUnscaledPoints; char m_padding3[4]; }; // clang-format on SIMD_FORCE_INLINE int btConvexHullShape::calculateSerializeBufferSize() const { return sizeof(btConvexHullShapeData); } #endif //BT_CONVEX_HULL_SHAPE_H
412
0.936563
1
0.936563
game-dev
MEDIA
0.992596
game-dev
0.907387
1
0.907387
mega12345mega/NBT-Editor
2,158
src/main/java/com/luneruniverse/minecraft/mod/nbteditor/containers/SpawnEggContainerIO.java
package com.luneruniverse.minecraft.mod.nbteditor.containers; import com.luneruniverse.minecraft.mod.nbteditor.localnbt.LocalEntity; import com.luneruniverse.minecraft.mod.nbteditor.multiversion.MVMisc; import com.luneruniverse.minecraft.mod.nbteditor.tagreferences.TagNames; import com.luneruniverse.minecraft.mod.nbteditor.util.MainUtil; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; public class SpawnEggContainerIO implements ItemContainerIO { @Override public int getMaxItemSize(ItemStack item) { if (item == null) return 0; NbtCompound nbt = item.manager$getNbt(); NbtCompound entityTag = (nbt == null ? new NbtCompound() : nbt.getCompound(TagNames.ENTITY_TAG)); return ContainerIO.getMaxSize(new LocalEntity(MVMisc.getEntityType(item), entityTag)); } @Override public boolean isItemReadable(ItemStack item) { NbtCompound nbt = item.manager$getNbt(); NbtCompound entityTag = (nbt == null ? new NbtCompound() : nbt.getCompound(TagNames.ENTITY_TAG)); return ContainerIO.isContainer(new LocalEntity(MVMisc.getEntityType(item), entityTag)); } @Override public ItemStack[] readItem(ItemStack container) { NbtCompound nbt = container.manager$getNbt(); NbtCompound entityTag = (nbt == null ? new NbtCompound() : nbt.getCompound(TagNames.ENTITY_TAG)); return ContainerIO.read(new LocalEntity(MVMisc.getEntityType(container), entityTag)); } @Override public int writeItem(ItemStack container, ItemStack[] contents) { LocalEntity entity = new LocalEntity(MVMisc.getEntityType(container), container.manager$getOrCreateNbt().getCompound(TagNames.ENTITY_TAG)); int output = ContainerIO.write(entity, contents); container.manager$modifyNbt(nbt -> nbt.put(TagNames.ENTITY_TAG, MainUtil.fillId(entity.getNBT(), entity.getId().toString()))); return output; } @Override public int getWrittenItemSlotIndex(ItemStack container, ItemStack[] contents, int slot) { LocalEntity entity = new LocalEntity(MVMisc.getEntityType(container), container.manager$getOrCreateNbt().getCompound(TagNames.ENTITY_TAG)); return ContainerIO.getWrittenSlotIndex(entity, contents, slot); } }
412
0.905004
1
0.905004
game-dev
MEDIA
0.999005
game-dev
0.907258
1
0.907258
jiachengliu3/OpenTrajBooster
5,882
g1_deploy/HomieDeploy/unitree_sdk2/hand_control.cpp
#include <chrono> #include <thread> #include <lcm/lcm-cpp.hpp> #include <unitree/idl/hg/HandState_.hpp> #include <unitree/idl/hg/HandCmd_.hpp> #include <unitree/robot/channel/channel_publisher.hpp> #include <unitree/robot/channel/channel_subscriber.hpp> #include <iostream> #include <unistd.h> #include <atomic> #include <mutex> #include <cmath> #include <termios.h> #include <unistd.h> #include <eigen3/Eigen/Dense> #include "hand_action_lcmt.hpp" const float maxTorqueLimits_left[7]= { 1.05 , 1.05 , 1.75 , 0 , 0 , 0 , 0 }; const float minTorqueLimits_left[7]= { -1.05 , -0.724 , 0 , -1.57 , -1.75 , -1.57 ,-1.75}; const float maxTorqueLimits_right[7]= { 1.05 , 0.742 , 0 , 1.57 , 1.75 , 1.57 , 1.75}; const float minTorqueLimits_right[7]= { -1.05 , -1.05 , -1.75, 0 , 0 , 0 ,0 }; //1 fande 2 fande 3 // std::array<float, 7> q_left = {}; // std::array<float, 7> q_right = {}; #define MOTOR_MAX 7 #define SENSOR_MAX 9 uint8_t hand_id = 0; typedef struct { uint8_t id : 4; uint8_t status : 3; uint8_t timeout: 1; } RIS_Mode_t; std::string ldds_namespace = "rt/dex3/left"; std::string lsub_namespace = "rt/dex3/left/state"; unitree::robot::ChannelPublisherPtr<unitree_hg::msg::dds_::HandCmd_> lhandcmd_publisher; unitree::robot::ChannelSubscriberPtr<unitree_hg::msg::dds_::HandState_> lhandstate_subscriber; unitree_hg::msg::dds_::HandCmd_ msg; unitree_hg::msg::dds_::HandState_ lstate; std::string rdds_namespace = "rt/dex3/right"; std::string rsub_namespace = "rt/dex3/right/state"; unitree::robot::ChannelPublisherPtr<unitree_hg::msg::dds_::HandCmd_> rhandcmd_publisher; unitree::robot::ChannelSubscriberPtr<unitree_hg::msg::dds_::HandState_> rhandstate_subscriber; unitree_hg::msg::dds_::HandState_ rstate; std::mutex stateMutex; class HandControl { private: lcm::LCM _simpleLCM; std::thread _simple_LCM_thread; std::thread _simple_hand_thread; hand_action_lcmt hand_action_simple = {0}; float q_left[7] = {0}; float q_right[7] = {0}; float hand_action[14] = {0}; public: HandControl(int val){ unitree::robot::ChannelFactory::Instance()->Init(0); lhandcmd_publisher.reset(new unitree::robot::ChannelPublisher<unitree_hg::msg::dds_::HandCmd_>(ldds_namespace + "/cmd")); lhandstate_subscriber.reset(new unitree::robot::ChannelSubscriber<unitree_hg::msg::dds_::HandState_>(lsub_namespace)); lhandcmd_publisher->InitChannel(); lstate.motor_state().resize(MOTOR_MAX); lstate.press_sensor_state().resize(SENSOR_MAX); msg.motor_cmd().resize(MOTOR_MAX); rhandcmd_publisher.reset(new unitree::robot::ChannelPublisher<unitree_hg::msg::dds_::HandCmd_>(rdds_namespace + "/cmd")); rhandstate_subscriber.reset(new unitree::robot::ChannelSubscriber<unitree_hg::msg::dds_::HandState_>(rsub_namespace)); rhandcmd_publisher->InitChannel(); rstate.motor_state().resize(MOTOR_MAX); rstate.press_sensor_state().resize(SENSOR_MAX); _simpleLCM.subscribe("hand_action", &HandControl::handleHandLCM, this); _simple_LCM_thread = std::thread(&HandControl::simpleLCMThread, this); _simple_hand_thread = std::thread(&HandControl::simplehandThread, this); for (int item = 0; item < 7; item++){ hand_action_simple.act[item] = minTorqueLimits_left[item]; hand_action_simple.act[item+7] = maxTorqueLimits_right[item]; } hand_action_simple.act[0] = 0.0; hand_action_simple.act[1] = maxTorqueLimits_left[1]; hand_action_simple.act[2] = maxTorqueLimits_left[2]; hand_action_simple.act[7] = 0.0; hand_action_simple.act[8] = minTorqueLimits_right[1]; hand_action_simple.act[9] = minTorqueLimits_right[2]; } void rotateMotors(bool isLeftHand) { const float* maxTorqueLimits = isLeftHand ? maxTorqueLimits_left : maxTorqueLimits_right; const float* minTorqueLimits = isLeftHand ? minTorqueLimits_left : minTorqueLimits_right; float* target = isLeftHand ? q_left : q_right; for (int i = 0; i < MOTOR_MAX; i++) { RIS_Mode_t ris_mode; ris_mode.id = i; ris_mode.status = 0x01; ris_mode.timeout = 0x01; uint8_t mode = 0; mode |= (ris_mode.id & 0x0F); mode |= (ris_mode.status & 0x07) << 4; mode |= (ris_mode.timeout & 0x01) << 7; msg.motor_cmd()[i].mode(mode); msg.motor_cmd()[i].tau(0); msg.motor_cmd()[i].kp(0.5); msg.motor_cmd()[i].kd(0.1); // float q = mid + amplitude * sin(_count / 20000.0 * M_PI); msg.motor_cmd()[i].q(target[i]); } if (isLeftHand){ lhandcmd_publisher->Write(msg); } else{ rhandcmd_publisher->Write(msg); } usleep(100); } void handleHandLCM(const lcm::ReceiveBuffer *rbuf, const std::string & chan, const hand_action_lcmt * msg){ (void) rbuf; (void) chan; hand_action_simple = *msg; } void simpleLCMThread(){ while(true){ _simpleLCM.handle(); } } void simplehandThread(){ while (true) { for (int i = 0; i < 7; i++){ // q_right[i] = 0.0; // q_left[i] = 0.0; q_right[i] = hand_action_simple.act[i+7]; q_left[i] = hand_action_simple.act[i]; // q_right[i] += 0.01; } rotateMotors(true); rotateMotors(false); } } }; int main() { // rmsg.motor_cmd().resize(MOTOR_MAX); HandControl cus(0); while (true) usleep(20000); return 0; }
412
0.953535
1
0.953535
game-dev
MEDIA
0.276629
game-dev
0.792346
1
0.792346
ProjectIgnis/CardScripts
1,070
unofficial/c450000000.lua
--サザンクロス --Southern Stars local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.filter(c) local lv=c:GetLevel() return c:IsFaceup() and lv>0 and lv~=10 end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and s.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) end function s.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CHANGE_LEVEL) e1:SetValue(10) e1:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e1) end end
412
0.895964
1
0.895964
game-dev
MEDIA
0.98371
game-dev
0.875707
1
0.875707
KgDW/Melon-Fabric-leaks
3,096
src/main/java/dev/zenhao/melon/module/modules/render/HandView.kt
package dev.zenhao.melon.module.modules.render import dev.zenhao.melon.mixins.IHeldItemRenderer import dev.zenhao.melon.module.Category import dev.zenhao.melon.module.Module import dev.zenhao.melon.utils.TimerUtils import melon.events.render.ItemRenderEvent import melon.system.event.safeEventListener import net.minecraft.network.packet.c2s.play.HandSwingC2SPacket import net.minecraft.util.Hand object HandView : Module(name = "HandView", "手部渲染", category = Category.RENDER) { val swingSpeed by isetting("SlowVL", 6, 0, 20) val oldSwing by bsetting("OldSwing", true) private val disableSwapMain by bsetting("DisableSwapMain", false) private val disableSwapOff by bsetting("DisableSwapOff", false) private val resetSwing = bsetting("ResetSwing", false) private val delay by isetting("ResetDelay", 100, 0, 1000).isTrue(resetSwing) private val tick by isetting("ResetTick", 0, 0, 5).isTrue(resetSwing) private val mainHand = bsetting("MainHand", true) private val scaleX by fsetting("MainScaleX", 1.0f, 0.0f, 2.0f).isTrue(mainHand) private val scaleY by fsetting("MainScaleY", 1.0f, 0.0f, 2.0f).isTrue(mainHand) private val scaleZ by fsetting("MainScaleZ", 1.0f, 0.0f, 2.0f).isTrue(mainHand) private val offHand = bsetting("OffHand", true) private val offScaleX by fsetting("OffScaleX", 1.0f, 0.0f, 2.0f).isTrue(offHand) private val offScaleY by fsetting("OffScaleY", 1.0f, 0.0f, 2.0f).isTrue(offHand) private val offScaleZ by fsetting("OffScaleZ", 1.0f, 0.0f, 2.0f).isTrue(offHand) private val timer = TimerUtils() init { onPacketSend { if (it.packet is HandSwingC2SPacket && resetSwing.value && player.handSwinging) { if (timer.tickAndReset(delay)) { player.handSwingTicks = tick } } } onMotion { if (disableSwapMain && (mc.entityRenderDispatcher.heldItemRenderer as IHeldItemRenderer).getEquippedProgressMainHand() <= 1f) { (mc.entityRenderDispatcher.heldItemRenderer as IHeldItemRenderer).setEquippedProgressMainHand(1f) (mc.entityRenderDispatcher.heldItemRenderer as IHeldItemRenderer).setItemStackMainHand(mc.player!!.mainHandStack) } if (disableSwapOff && (mc.entityRenderDispatcher.heldItemRenderer as IHeldItemRenderer).getEquippedProgressOffHand() <= 1f) { (mc.entityRenderDispatcher.heldItemRenderer as IHeldItemRenderer).setEquippedProgressOffHand(1f) (mc.entityRenderDispatcher.heldItemRenderer as IHeldItemRenderer).setItemStackOffHand(mc.player!!.offHandStack) } } safeEventListener<ItemRenderEvent> { if (mainHand.value) { if (it.hand == Hand.MAIN_HAND) { it.matrices.scale(scaleX, scaleY, scaleZ) } } if (offHand.value) { if (it.hand == Hand.OFF_HAND) { it.matrices.scale(offScaleX, offScaleY, offScaleZ) } } } } }
412
0.876847
1
0.876847
game-dev
MEDIA
0.937373
game-dev
0.876978
1
0.876978
robotseu/ORB_Line_SLAM
2,757
Thirdparty/DBoW2/DUtils/Random.cpp
/* * File: Random.cpp * Project: DUtils library * Author: Dorian Galvez-Lopez * Date: April 2010 * Description: manages pseudo-random numbers * License: see the LICENSE.txt file * */ #include "Random.h" #include "Timestamp.h" #include <cstdlib> using namespace std; bool DUtils::Random::m_already_seeded = false; void DUtils::Random::SeedRand(){ Timestamp time; time.setToCurrentTime(); srand((unsigned)time.getFloatTime()); } void DUtils::Random::SeedRandOnce() { if(!m_already_seeded) { DUtils::Random::SeedRand(); m_already_seeded = true; } } void DUtils::Random::SeedRand(int seed) { srand(seed); } void DUtils::Random::SeedRandOnce(int seed) { if(!m_already_seeded) { DUtils::Random::SeedRand(seed); m_already_seeded = true; } } int DUtils::Random::RandomInt(int min, int max){ int d = max - min + 1; return int(((double)rand()/((double)RAND_MAX + 1.0)) * d) + min; } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- DUtils::Random::UnrepeatedRandomizer::UnrepeatedRandomizer(int min, int max) { if(min <= max) { m_min = min; m_max = max; } else { m_min = max; m_max = min; } createValues(); } // --------------------------------------------------------------------------- DUtils::Random::UnrepeatedRandomizer::UnrepeatedRandomizer (const DUtils::Random::UnrepeatedRandomizer& rnd) { *this = rnd; } // --------------------------------------------------------------------------- int DUtils::Random::UnrepeatedRandomizer::get() { if(empty()) createValues(); DUtils::Random::SeedRandOnce(); int k = DUtils::Random::RandomInt(0, m_values.size()-1); int ret = m_values[k]; m_values[k] = m_values.back(); m_values.pop_back(); return ret; } // --------------------------------------------------------------------------- void DUtils::Random::UnrepeatedRandomizer::createValues() { int n = m_max - m_min + 1; m_values.resize(n); for(int i = 0; i < n; ++i) m_values[i] = m_min + i; } // --------------------------------------------------------------------------- void DUtils::Random::UnrepeatedRandomizer::reset() { if((int)m_values.size() != m_max - m_min + 1) createValues(); } // --------------------------------------------------------------------------- DUtils::Random::UnrepeatedRandomizer& DUtils::Random::UnrepeatedRandomizer::operator= (const DUtils::Random::UnrepeatedRandomizer& rnd) { if(this != &rnd) { this->m_min = rnd.m_min; this->m_max = rnd.m_max; this->m_values = rnd.m_values; } return *this; } // ---------------------------------------------------------------------------
412
0.820166
1
0.820166
game-dev
MEDIA
0.300134
game-dev
0.906182
1
0.906182
gama-platform/gama.old
4,623
msi.gama.models/models/Visualization and User Interaction/User Interaction/models/Event Layer.gaml
/** * Name: Event Feature * Author: Arnaud Grignard & Patrick Taillandier & Jean-Daniel Zucker * Description: Model which shows how to use the event layer to trigger an action according to an event occuring in the display. The experiment * has two displays : one for the changing color event, one for the changing shape event. * Tags: gui */ model event_layer_model global { //number of agents to create int nbAgent <- 200; int radius <- 10; dummy pointClicked; init { //creation of the agents create cell number: nbAgent { colour <- #darkgreen; } create dummy number:1 returns: temp with: [dummyRadius :: radius]; pointClicked <- first(temp); } //Action to change the color of the agents, according to the point to know which agents we're in intersection with the point action change_color { //change the color of the agents list<cell> selected_agents <- cell overlapping (circle(10) at_location #user_location); ask selected_agents { colour <- colour = #lightgreen ? #darkgreen : #lightgreen; } } action draw_clicked_area_in_view_color { pointClicked.location <- #user_location; pointClicked.visibleViewColor <- true; } action draw_clicked_area_in_view_shape { pointClicked.location <- #user_location; pointClicked.visibleViewShape <- true; } action hide_clicked_area { pointClicked.visibleViewColor <- false; pointClicked.visibleViewShape <- false; } //Action to change the shape of the agents, according to the point to know which agents we're in intersection with the point action change_shape { list<cell> selected_agents <- cell overlapping (circle(radius) at_location #user_location); ask selected_agents { //change the bool attribute is_square to change the shape in the display is_square <- not (is_square); } } } //Species cells moving randomly species cell skills: [moving] { rgb colour; bool is_square <- false; reflex mm { do wander amplitude: 30.0; } aspect default { draw is_square ? square(2) : circle(1) color: colour; } } species dummy { int dummyRadius <- 10; bool visibleViewColor <- false; bool visibleViewShape <- false; aspect aspect4ViewChangeColor { if visibleViewColor {draw circle(radius) color: #grey;} } aspect aspect4ViewChangeShape { if visibleViewShape {draw circle(radius) color: #grey;} } } experiment Displays type: gui { parameter "Radius of selection" var: radius ; // The radius of the disk around the click output synchronized:true { layout horizontal([0::5000,1::5000]) tabs:true editors: false; display View_change_color { species cell; species dummy transparency:0.9 aspect: aspect4ViewChangeColor; // event, launches the action change_color if the event mouse_down (ie. the user clicks on the layer event) is triggered // the action can be either in the experiment or in the global section. If it is defined in both, the one in the experiment will be chosen in priority event #mouse_down {ask simulation {do change_color;}} event #mouse_move {ask simulation {do draw_clicked_area_in_view_color;}} event #mouse_exit {ask simulation {do hide_clicked_area;}} // Shows how to manipulate the cells using keyboard events event #arrow_left {ask (cell) {location <- location - {1,0};}} event #arrow_right {ask (cell) {location <- location + {1,0};}} event #arrow_up {ask (cell) {location <- location - {0,1};}} event #arrow_down {ask (cell) {location <- location + {0,1};}} event #escape {ask (cell) {location <- rnd(point(100,100));}} } display View_change_shape type: 3d { light #ambient active: false; species cell; species dummy transparency:0.9 aspect: aspect4ViewChangeShape ; //event, launches the action change_shape if the event mouse_down (ie. the user clicks on the layer event) is triggered // The block is executed in the context of the experiment, so we have to ask the simulation to do it. event #mouse_down {ask simulation {do change_shape;}} event #mouse_move {ask simulation {do draw_clicked_area_in_view_shape;}} event #mouse_exit {ask simulation {do hide_clicked_area;}} // Shows how to manipulate the cells using keyboard events, disactivating the "regular" arrow / esc keys behavior event #arrow_left {ask (cell) {location <- location - {1,0};}} event #arrow_right {ask (cell) {location <- location + {1,0};}} event #arrow_up {ask (cell) {location <- location - {0,1};}} event #arrow_down {ask (cell) {location <- location + {0,1};}} event #escape {ask (cell) {location <- rnd(point(100,100));}} } } }
412
0.882516
1
0.882516
game-dev
MEDIA
0.403893
game-dev
0.732962
1
0.732962
idsoftware/quake2
2,852
game/p_trail.c
/* Copyright (C) 1997-2001 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "g_local.h" /* ============================================================================== PLAYER TRAIL ============================================================================== This is a circular list containing the a list of points of where the player has been recently. It is used by monsters for pursuit. .origin the spot .owner forward link .aiment backward link */ #define TRAIL_LENGTH 8 edict_t *trail[TRAIL_LENGTH]; int trail_head; qboolean trail_active = false; #define NEXT(n) (((n) + 1) & (TRAIL_LENGTH - 1)) #define PREV(n) (((n) - 1) & (TRAIL_LENGTH - 1)) void PlayerTrail_Init (void) { int n; if (deathmatch->value /* FIXME || coop */) return; for (n = 0; n < TRAIL_LENGTH; n++) { trail[n] = G_Spawn(); trail[n]->classname = "player_trail"; } trail_head = 0; trail_active = true; } void PlayerTrail_Add (vec3_t spot) { vec3_t temp; if (!trail_active) return; VectorCopy (spot, trail[trail_head]->s.origin); trail[trail_head]->timestamp = level.time; VectorSubtract (spot, trail[PREV(trail_head)]->s.origin, temp); trail[trail_head]->s.angles[1] = vectoyaw (temp); trail_head = NEXT(trail_head); } void PlayerTrail_New (vec3_t spot) { if (!trail_active) return; PlayerTrail_Init (); PlayerTrail_Add (spot); } edict_t *PlayerTrail_PickFirst (edict_t *self) { int marker; int n; if (!trail_active) return NULL; for (marker = trail_head, n = TRAIL_LENGTH; n; n--) { if(trail[marker]->timestamp <= self->monsterinfo.trail_time) marker = NEXT(marker); else break; } if (visible(self, trail[marker])) { return trail[marker]; } if (visible(self, trail[PREV(marker)])) { return trail[PREV(marker)]; } return trail[marker]; } edict_t *PlayerTrail_PickNext (edict_t *self) { int marker; int n; if (!trail_active) return NULL; for (marker = trail_head, n = TRAIL_LENGTH; n; n--) { if(trail[marker]->timestamp <= self->monsterinfo.trail_time) marker = NEXT(marker); else break; } return trail[marker]; } edict_t *PlayerTrail_LastSpot (void) { return trail[PREV(trail_head)]; }
412
0.934659
1
0.934659
game-dev
MEDIA
0.77449
game-dev
0.556294
1
0.556294
dotnet/dotnet-api-docs
1,379
snippets/csharp/System/IntPtr/Overview/topointer.cs
//<snippet1> using System; using System.Runtime.InteropServices; class NotTooSafeStringReverse { static public void Main() { string stringA = "I seem to be turned around!"; int copylen = stringA.Length; // Allocate HGlobal memory for source and destination strings IntPtr sptr = Marshal.StringToHGlobalAnsi(stringA); IntPtr dptr = Marshal.AllocHGlobal(copylen + 1); // The unsafe section where byte pointers are used. unsafe { byte *src = (byte *)sptr.ToPointer(); byte *dst = (byte *)dptr.ToPointer(); if (copylen > 0) { // set the source pointer to the end of the string // to do a reverse copy. src += copylen - 1; while (copylen-- > 0) { *dst++ = *src--; } *dst = 0; } } string stringB = Marshal.PtrToStringAnsi(dptr); Console.WriteLine("Original:\n{0}\n", stringA); Console.WriteLine("Reversed:\n{0}", stringB); // Free HGlobal memory Marshal.FreeHGlobal(dptr); Marshal.FreeHGlobal(sptr); } } // The progam has the following output: // // Original: // I seem to be turned around! // // Reversed: // !dnuora denrut eb ot mees I //</snippet1>
412
0.699601
1
0.699601
game-dev
MEDIA
0.599204
game-dev,audio-video-media
0.851198
1
0.851198
LangYa466/MCPLite-all-source
25,641
src/main/java/net/minecraft/world/storage/WorldInfo.java
package net.minecraft.world.storage; import java.util.concurrent.Callable; import net.minecraft.crash.CrashReportCategory; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.GameRules; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; public class WorldInfo { public static final EnumDifficulty DEFAULT_DIFFICULTY = EnumDifficulty.NORMAL; /** Holds the seed of the currently world. */ private long randomSeed; private WorldType terrainType = WorldType.DEFAULT; private String generatorOptions = ""; /** The spawn zone position X coordinate. */ private int spawnX; /** The spawn zone position Y coordinate. */ private int spawnY; /** The spawn zone position Z coordinate. */ private int spawnZ; /** Total time for this world. */ private long totalTime; /** The current world time in ticks, ranging from 0 to 23999. */ private long worldTime; /** The last time the player was in this world. */ private long lastTimePlayed; /** The size of entire save of current world on the disk, isn't exactly. */ private long sizeOnDisk; private NBTTagCompound playerTag; private int dimension; /** The name of the save defined at world creation. */ private String levelName; /** Introduced in beta 1.3, is the save version for future control. */ private int saveVersion; private int cleanWeatherTime; /** True if it's raining, false otherwise. */ private boolean raining; /** Number of ticks until next rain. */ private int rainTime; /** Is thunderbolts failing now? */ private boolean thundering; /** Number of ticks untils next thunderbolt. */ private int thunderTime; /** The Game Type. */ private WorldSettings.GameType theGameType; /** * Whether the map features (e.g. strongholds) generation is enabled or disabled. */ private boolean mapFeaturesEnabled; /** Hardcore mode flag */ private boolean hardcore; private boolean allowCommands; private boolean initialized; private EnumDifficulty difficulty; private boolean difficultyLocked; private double borderCenterX = 0.0D; private double borderCenterZ = 0.0D; private double borderSize = 6.0E7D; private long borderSizeLerpTime = 0L; private double borderSizeLerpTarget = 0.0D; private double borderSafeZone = 5.0D; private double borderDamagePerBlock = 0.2D; private int borderWarningDistance = 5; private int borderWarningTime = 15; private GameRules theGameRules = new GameRules(); protected WorldInfo() { } public WorldInfo(NBTTagCompound nbt) { this.randomSeed = nbt.getLong("RandomSeed"); if (nbt.hasKey("generatorName", 8)) { String s = nbt.getString("generatorName"); this.terrainType = WorldType.parseWorldType(s); if (this.terrainType == null) { this.terrainType = WorldType.DEFAULT; } else if (this.terrainType.isVersioned()) { int i = 0; if (nbt.hasKey("generatorVersion", 99)) { i = nbt.getInteger("generatorVersion"); } this.terrainType = this.terrainType.getWorldTypeForGeneratorVersion(i); } if (nbt.hasKey("generatorOptions", 8)) { this.generatorOptions = nbt.getString("generatorOptions"); } } this.theGameType = WorldSettings.GameType.getByID(nbt.getInteger("GameType")); if (nbt.hasKey("MapFeatures", 99)) { this.mapFeaturesEnabled = nbt.getBoolean("MapFeatures"); } else { this.mapFeaturesEnabled = true; } this.spawnX = nbt.getInteger("SpawnX"); this.spawnY = nbt.getInteger("SpawnY"); this.spawnZ = nbt.getInteger("SpawnZ"); this.totalTime = nbt.getLong("Time"); if (nbt.hasKey("DayTime", 99)) { this.worldTime = nbt.getLong("DayTime"); } else { this.worldTime = this.totalTime; } this.lastTimePlayed = nbt.getLong("LastPlayed"); this.sizeOnDisk = nbt.getLong("SizeOnDisk"); this.levelName = nbt.getString("LevelName"); this.saveVersion = nbt.getInteger("version"); this.cleanWeatherTime = nbt.getInteger("clearWeatherTime"); this.rainTime = nbt.getInteger("rainTime"); this.raining = nbt.getBoolean("raining"); this.thunderTime = nbt.getInteger("thunderTime"); this.thundering = nbt.getBoolean("thundering"); this.hardcore = nbt.getBoolean("hardcore"); if (nbt.hasKey("initialized", 99)) { this.initialized = nbt.getBoolean("initialized"); } else { this.initialized = true; } if (nbt.hasKey("allowCommands", 99)) { this.allowCommands = nbt.getBoolean("allowCommands"); } else { this.allowCommands = this.theGameType == WorldSettings.GameType.CREATIVE; } if (nbt.hasKey("Player", 10)) { this.playerTag = nbt.getCompoundTag("Player"); this.dimension = this.playerTag.getInteger("Dimension"); } if (nbt.hasKey("GameRules", 10)) { this.theGameRules.readFromNBT(nbt.getCompoundTag("GameRules")); } if (nbt.hasKey("Difficulty", 99)) { this.difficulty = EnumDifficulty.getDifficultyEnum(nbt.getByte("Difficulty")); } if (nbt.hasKey("DifficultyLocked", 1)) { this.difficultyLocked = nbt.getBoolean("DifficultyLocked"); } if (nbt.hasKey("BorderCenterX", 99)) { this.borderCenterX = nbt.getDouble("BorderCenterX"); } if (nbt.hasKey("BorderCenterZ", 99)) { this.borderCenterZ = nbt.getDouble("BorderCenterZ"); } if (nbt.hasKey("BorderSize", 99)) { this.borderSize = nbt.getDouble("BorderSize"); } if (nbt.hasKey("BorderSizeLerpTime", 99)) { this.borderSizeLerpTime = nbt.getLong("BorderSizeLerpTime"); } if (nbt.hasKey("BorderSizeLerpTarget", 99)) { this.borderSizeLerpTarget = nbt.getDouble("BorderSizeLerpTarget"); } if (nbt.hasKey("BorderSafeZone", 99)) { this.borderSafeZone = nbt.getDouble("BorderSafeZone"); } if (nbt.hasKey("BorderDamagePerBlock", 99)) { this.borderDamagePerBlock = nbt.getDouble("BorderDamagePerBlock"); } if (nbt.hasKey("BorderWarningBlocks", 99)) { this.borderWarningDistance = nbt.getInteger("BorderWarningBlocks"); } if (nbt.hasKey("BorderWarningTime", 99)) { this.borderWarningTime = nbt.getInteger("BorderWarningTime"); } } public WorldInfo(WorldSettings settings, String name) { this.populateFromWorldSettings(settings); this.levelName = name; this.difficulty = DEFAULT_DIFFICULTY; this.initialized = false; } public void populateFromWorldSettings(WorldSettings settings) { this.randomSeed = settings.getSeed(); this.theGameType = settings.getGameType(); this.mapFeaturesEnabled = settings.isMapFeaturesEnabled(); this.hardcore = settings.getHardcoreEnabled(); this.terrainType = settings.getTerrainType(); this.generatorOptions = settings.getWorldName(); this.allowCommands = settings.areCommandsAllowed(); } public WorldInfo(WorldInfo worldInformation) { this.randomSeed = worldInformation.randomSeed; this.terrainType = worldInformation.terrainType; this.generatorOptions = worldInformation.generatorOptions; this.theGameType = worldInformation.theGameType; this.mapFeaturesEnabled = worldInformation.mapFeaturesEnabled; this.spawnX = worldInformation.spawnX; this.spawnY = worldInformation.spawnY; this.spawnZ = worldInformation.spawnZ; this.totalTime = worldInformation.totalTime; this.worldTime = worldInformation.worldTime; this.lastTimePlayed = worldInformation.lastTimePlayed; this.sizeOnDisk = worldInformation.sizeOnDisk; this.playerTag = worldInformation.playerTag; this.dimension = worldInformation.dimension; this.levelName = worldInformation.levelName; this.saveVersion = worldInformation.saveVersion; this.rainTime = worldInformation.rainTime; this.raining = worldInformation.raining; this.thunderTime = worldInformation.thunderTime; this.thundering = worldInformation.thundering; this.hardcore = worldInformation.hardcore; this.allowCommands = worldInformation.allowCommands; this.initialized = worldInformation.initialized; this.theGameRules = worldInformation.theGameRules; this.difficulty = worldInformation.difficulty; this.difficultyLocked = worldInformation.difficultyLocked; this.borderCenterX = worldInformation.borderCenterX; this.borderCenterZ = worldInformation.borderCenterZ; this.borderSize = worldInformation.borderSize; this.borderSizeLerpTime = worldInformation.borderSizeLerpTime; this.borderSizeLerpTarget = worldInformation.borderSizeLerpTarget; this.borderSafeZone = worldInformation.borderSafeZone; this.borderDamagePerBlock = worldInformation.borderDamagePerBlock; this.borderWarningTime = worldInformation.borderWarningTime; this.borderWarningDistance = worldInformation.borderWarningDistance; } /** * Gets the NBTTagCompound for the worldInfo */ public NBTTagCompound getNBTTagCompound() { NBTTagCompound nbttagcompound = new NBTTagCompound(); this.updateTagCompound(nbttagcompound, this.playerTag); return nbttagcompound; } /** * Creates a new NBTTagCompound for the world, with the given NBTTag as the "Player" */ public NBTTagCompound cloneNBTCompound(NBTTagCompound nbt) { NBTTagCompound nbttagcompound = new NBTTagCompound(); this.updateTagCompound(nbttagcompound, nbt); return nbttagcompound; } private void updateTagCompound(NBTTagCompound nbt, NBTTagCompound playerNbt) { nbt.setLong("RandomSeed", this.randomSeed); nbt.setString("generatorName", this.terrainType.getWorldTypeName()); nbt.setInteger("generatorVersion", this.terrainType.getGeneratorVersion()); nbt.setString("generatorOptions", this.generatorOptions); nbt.setInteger("GameType", this.theGameType.getID()); nbt.setBoolean("MapFeatures", this.mapFeaturesEnabled); nbt.setInteger("SpawnX", this.spawnX); nbt.setInteger("SpawnY", this.spawnY); nbt.setInteger("SpawnZ", this.spawnZ); nbt.setLong("Time", this.totalTime); nbt.setLong("DayTime", this.worldTime); nbt.setLong("SizeOnDisk", this.sizeOnDisk); nbt.setLong("LastPlayed", MinecraftServer.getCurrentTimeMillis()); nbt.setString("LevelName", this.levelName); nbt.setInteger("version", this.saveVersion); nbt.setInteger("clearWeatherTime", this.cleanWeatherTime); nbt.setInteger("rainTime", this.rainTime); nbt.setBoolean("raining", this.raining); nbt.setInteger("thunderTime", this.thunderTime); nbt.setBoolean("thundering", this.thundering); nbt.setBoolean("hardcore", this.hardcore); nbt.setBoolean("allowCommands", this.allowCommands); nbt.setBoolean("initialized", this.initialized); nbt.setDouble("BorderCenterX", this.borderCenterX); nbt.setDouble("BorderCenterZ", this.borderCenterZ); nbt.setDouble("BorderSize", this.borderSize); nbt.setLong("BorderSizeLerpTime", this.borderSizeLerpTime); nbt.setDouble("BorderSafeZone", this.borderSafeZone); nbt.setDouble("BorderDamagePerBlock", this.borderDamagePerBlock); nbt.setDouble("BorderSizeLerpTarget", this.borderSizeLerpTarget); nbt.setDouble("BorderWarningBlocks", (double)this.borderWarningDistance); nbt.setDouble("BorderWarningTime", (double)this.borderWarningTime); if (this.difficulty != null) { nbt.setByte("Difficulty", (byte)this.difficulty.getDifficultyId()); } nbt.setBoolean("DifficultyLocked", this.difficultyLocked); nbt.setTag("GameRules", this.theGameRules.writeToNBT()); if (playerNbt != null) { nbt.setTag("Player", playerNbt); } } /** * Returns the seed of current world. */ public long getSeed() { return this.randomSeed; } /** * Returns the x spawn position */ public int getSpawnX() { return this.spawnX; } /** * Return the Y axis spawning point of the player. */ public int getSpawnY() { return this.spawnY; } /** * Returns the z spawn position */ public int getSpawnZ() { return this.spawnZ; } public long getWorldTotalTime() { return this.totalTime; } /** * Get current world time */ public long getWorldTime() { return this.worldTime; } public long getSizeOnDisk() { return this.sizeOnDisk; } /** * Returns the player's NBTTagCompound to be loaded */ public NBTTagCompound getPlayerNBTTagCompound() { return this.playerTag; } /** * Set the x spawn position to the passed in value */ public void setSpawnX(int x) { this.spawnX = x; } /** * Sets the y spawn position */ public void setSpawnY(int y) { this.spawnY = y; } /** * Set the z spawn position to the passed in value */ public void setSpawnZ(int z) { this.spawnZ = z; } public void setWorldTotalTime(long time) { this.totalTime = time; } /** * Set current world time */ public void setWorldTime(long time) { this.worldTime = time; } public void setSpawn(BlockPos spawnPoint) { this.spawnX = spawnPoint.getX(); this.spawnY = spawnPoint.getY(); this.spawnZ = spawnPoint.getZ(); } /** * Get current world name */ public String getWorldName() { return this.levelName; } public void setWorldName(String worldName) { this.levelName = worldName; } /** * Returns the save version of this world */ public int getSaveVersion() { return this.saveVersion; } /** * Sets the save version of the world */ public void setSaveVersion(int version) { this.saveVersion = version; } /** * Return the last time the player was in this world. */ public long getLastTimePlayed() { return this.lastTimePlayed; } public int getCleanWeatherTime() { return this.cleanWeatherTime; } public void setCleanWeatherTime(int cleanWeatherTimeIn) { this.cleanWeatherTime = cleanWeatherTimeIn; } /** * Returns true if it is thundering, false otherwise. */ public boolean isThundering() { return this.thundering; } /** * Sets whether it is thundering or not. */ public void setThundering(boolean thunderingIn) { this.thundering = thunderingIn; } /** * Returns the number of ticks until next thunderbolt. */ public int getThunderTime() { return this.thunderTime; } /** * Defines the number of ticks until next thunderbolt. */ public void setThunderTime(int time) { this.thunderTime = time; } /** * Returns true if it is raining, false otherwise. */ public boolean isRaining() { return this.raining; } /** * Sets whether it is raining or not. */ public void setRaining(boolean isRaining) { this.raining = isRaining; } /** * Return the number of ticks until rain. */ public int getRainTime() { return this.rainTime; } /** * Sets the number of ticks until rain. */ public void setRainTime(int time) { this.rainTime = time; } /** * Gets the GameType. */ public WorldSettings.GameType getGameType() { return this.theGameType; } /** * Get whether the map features (e.g. strongholds) generation is enabled or disabled. */ public boolean isMapFeaturesEnabled() { return this.mapFeaturesEnabled; } public void setMapFeaturesEnabled(boolean enabled) { this.mapFeaturesEnabled = enabled; } /** * Sets the GameType. */ public void setGameType(WorldSettings.GameType type) { this.theGameType = type; } /** * Returns true if hardcore mode is enabled, otherwise false */ public boolean isHardcoreModeEnabled() { return this.hardcore; } public void setHardcore(boolean hardcoreIn) { this.hardcore = hardcoreIn; } public WorldType getTerrainType() { return this.terrainType; } public void setTerrainType(WorldType type) { this.terrainType = type; } public String getGeneratorOptions() { return this.generatorOptions; } /** * Returns true if commands are allowed on this World. */ public boolean areCommandsAllowed() { return this.allowCommands; } public void setAllowCommands(boolean allow) { this.allowCommands = allow; } /** * Returns true if the World is initialized. */ public boolean isInitialized() { return this.initialized; } /** * Sets the initialization status of the World. */ public void setServerInitialized(boolean initializedIn) { this.initialized = initializedIn; } /** * Gets the GameRules class Instance. */ public GameRules getGameRulesInstance() { return this.theGameRules; } /** * Returns the border center X position */ public double getBorderCenterX() { return this.borderCenterX; } /** * Returns the border center Z position */ public double getBorderCenterZ() { return this.borderCenterZ; } public double getBorderSize() { return this.borderSize; } /** * Sets the border size */ public void setBorderSize(double size) { this.borderSize = size; } /** * Returns the border lerp time */ public long getBorderLerpTime() { return this.borderSizeLerpTime; } /** * Sets the border lerp time */ public void setBorderLerpTime(long time) { this.borderSizeLerpTime = time; } /** * Returns the border lerp target */ public double getBorderLerpTarget() { return this.borderSizeLerpTarget; } /** * Sets the border lerp target */ public void setBorderLerpTarget(double lerpSize) { this.borderSizeLerpTarget = lerpSize; } /** * Sets the border center Z position */ public void getBorderCenterZ(double posZ) { this.borderCenterZ = posZ; } /** * Sets the border center X position */ public void getBorderCenterX(double posX) { this.borderCenterX = posX; } /** * Returns the border safe zone */ public double getBorderSafeZone() { return this.borderSafeZone; } /** * Sets the border safe zone */ public void setBorderSafeZone(double amount) { this.borderSafeZone = amount; } /** * Returns the border damage per block */ public double getBorderDamagePerBlock() { return this.borderDamagePerBlock; } /** * Sets the border damage per block */ public void setBorderDamagePerBlock(double damage) { this.borderDamagePerBlock = damage; } /** * Returns the border warning distance */ public int getBorderWarningDistance() { return this.borderWarningDistance; } /** * Returns the border warning time */ public int getBorderWarningTime() { return this.borderWarningTime; } /** * Sets the border warning distance */ public void setBorderWarningDistance(int amountOfBlocks) { this.borderWarningDistance = amountOfBlocks; } /** * Sets the border warning time */ public void setBorderWarningTime(int ticks) { this.borderWarningTime = ticks; } public EnumDifficulty getDifficulty() { return this.difficulty; } public void setDifficulty(EnumDifficulty newDifficulty) { this.difficulty = newDifficulty; } public boolean isDifficultyLocked() { return this.difficultyLocked; } public void setDifficultyLocked(boolean locked) { this.difficultyLocked = locked; } /** * Adds this WorldInfo instance to the crash report. */ public void addToCrashReport(CrashReportCategory category) { category.addCrashSectionCallable("Level seed", new Callable<String>() { public String call() throws Exception { return String.valueOf(WorldInfo.this.getSeed()); } }); category.addCrashSectionCallable("Level generator", new Callable<String>() { public String call() throws Exception { return String.format("ID %02d - %s, ver %d. Features enabled: %b", new Object[] {Integer.valueOf(WorldInfo.this.terrainType.getWorldTypeID()), WorldInfo.this.terrainType.getWorldTypeName(), Integer.valueOf(WorldInfo.this.terrainType.getGeneratorVersion()), Boolean.valueOf(WorldInfo.this.mapFeaturesEnabled)}); } }); category.addCrashSectionCallable("Level generator options", new Callable<String>() { public String call() throws Exception { return WorldInfo.this.generatorOptions; } }); category.addCrashSectionCallable("Level spawn location", new Callable<String>() { public String call() throws Exception { return CrashReportCategory.getCoordinateInfo((double)WorldInfo.this.spawnX, (double)WorldInfo.this.spawnY, (double)WorldInfo.this.spawnZ); } }); category.addCrashSectionCallable("Level time", new Callable<String>() { public String call() throws Exception { return String.format("%d game time, %d day time", new Object[] {Long.valueOf(WorldInfo.this.totalTime), Long.valueOf(WorldInfo.this.worldTime)}); } }); category.addCrashSectionCallable("Level dimension", new Callable<String>() { public String call() throws Exception { return String.valueOf(WorldInfo.this.dimension); } }); category.addCrashSectionCallable("Level storage version", new Callable<String>() { public String call() throws Exception { String s = "Unknown?"; try { switch (WorldInfo.this.saveVersion) { case 19132: s = "McRegion"; break; case 19133: s = "Anvil"; } } catch (Throwable var3) { ; } return String.format("0x%05X - %s", new Object[] {Integer.valueOf(WorldInfo.this.saveVersion), s}); } }); category.addCrashSectionCallable("Level weather", new Callable<String>() { public String call() throws Exception { return String.format("Rain time: %d (now: %b), thunder time: %d (now: %b)", new Object[] {Integer.valueOf(WorldInfo.this.rainTime), Boolean.valueOf(WorldInfo.this.raining), Integer.valueOf(WorldInfo.this.thunderTime), Boolean.valueOf(WorldInfo.this.thundering)}); } }); category.addCrashSectionCallable("Level game mode", new Callable<String>() { public String call() throws Exception { return String.format("Game mode: %s (ID %d). Hardcore: %b. Cheats: %b", new Object[] {WorldInfo.this.theGameType.getName(), Integer.valueOf(WorldInfo.this.theGameType.getID()), Boolean.valueOf(WorldInfo.this.hardcore), Boolean.valueOf(WorldInfo.this.allowCommands)}); } }); } }
412
0.895197
1
0.895197
game-dev
MEDIA
0.940691
game-dev
0.846851
1
0.846851
intel/linux-sgx
6,434
sdk/gperftools/gperftools-2.7/src/emergency_malloc.cc
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2014, gperftools Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "config.h" #include "emergency_malloc.h" #include <errno.h> // for ENOMEM, errno #include <string.h> // for memset #include "base/basictypes.h" #include "base/logging.h" #include "base/low_level_alloc.h" #include "base/spinlock.h" #include "internal_logging.h" namespace tcmalloc { __attribute__ ((visibility("internal"))) char *emergency_arena_start; __attribute__ ((visibility("internal"))) uintptr_t emergency_arena_start_shifted; static CACHELINE_ALIGNED SpinLock emergency_malloc_lock(base::LINKER_INITIALIZED); static char *emergency_arena_end; static LowLevelAlloc::Arena *emergency_arena; class EmergencyArenaPagesAllocator : public LowLevelAlloc::PagesAllocator { ~EmergencyArenaPagesAllocator() {} void *MapPages(int32 flags, size_t size) { char *new_end = emergency_arena_end + size; if (new_end > emergency_arena_start + kEmergencyArenaSize) { RAW_LOG(FATAL, "Unable to allocate %" PRIuS " bytes in emergency zone.", size); } char *rv = emergency_arena_end; emergency_arena_end = new_end; return static_cast<void *>(rv); } void UnMapPages(int32 flags, void *addr, size_t size) { RAW_LOG(FATAL, "UnMapPages is not implemented for emergency arena"); } }; static union { char bytes[sizeof(EmergencyArenaPagesAllocator)]; void *ptr; } pages_allocator_place; static void InitEmergencyMalloc(void) { const int32 flags = LowLevelAlloc::kAsyncSignalSafe; void *arena = LowLevelAlloc::GetDefaultPagesAllocator()->MapPages(flags, kEmergencyArenaSize * 2); uintptr_t arena_ptr = reinterpret_cast<uintptr_t>(arena); uintptr_t ptr = (arena_ptr + kEmergencyArenaSize - 1) & ~(kEmergencyArenaSize-1); emergency_arena_end = emergency_arena_start = reinterpret_cast<char *>(ptr); EmergencyArenaPagesAllocator *allocator = new (pages_allocator_place.bytes) EmergencyArenaPagesAllocator(); emergency_arena = LowLevelAlloc::NewArenaWithCustomAlloc(0, LowLevelAlloc::DefaultArena(), allocator); emergency_arena_start_shifted = reinterpret_cast<uintptr_t>(emergency_arena_start) >> kEmergencyArenaShift; uintptr_t head_unmap_size = ptr - arena_ptr; CHECK_CONDITION(head_unmap_size < kEmergencyArenaSize); if (head_unmap_size != 0) { LowLevelAlloc::GetDefaultPagesAllocator()->UnMapPages(flags, arena, ptr - arena_ptr); } uintptr_t tail_unmap_size = kEmergencyArenaSize - head_unmap_size; void *tail_start = reinterpret_cast<void *>(arena_ptr + head_unmap_size + kEmergencyArenaSize); LowLevelAlloc::GetDefaultPagesAllocator()->UnMapPages(flags, tail_start, tail_unmap_size); } PERFTOOLS_DLL_DECL void *EmergencyMalloc(size_t size) { SpinLockHolder l(&emergency_malloc_lock); if (emergency_arena_start == NULL) { InitEmergencyMalloc(); CHECK_CONDITION(emergency_arena_start != NULL); } void *rv = LowLevelAlloc::AllocWithArena(size, emergency_arena); if (rv == NULL) { errno = ENOMEM; } return rv; } PERFTOOLS_DLL_DECL void EmergencyFree(void *p) { SpinLockHolder l(&emergency_malloc_lock); if (emergency_arena_start == NULL) { InitEmergencyMalloc(); CHECK_CONDITION(emergency_arena_start != NULL); free(p); return; } CHECK_CONDITION(emergency_arena_start); LowLevelAlloc::Free(p); } PERFTOOLS_DLL_DECL void *EmergencyRealloc(void *_old_ptr, size_t new_size) { if (_old_ptr == NULL) { return EmergencyMalloc(new_size); } if (new_size == 0) { EmergencyFree(_old_ptr); return NULL; } SpinLockHolder l(&emergency_malloc_lock); CHECK_CONDITION(emergency_arena_start); char *old_ptr = static_cast<char *>(_old_ptr); CHECK_CONDITION(old_ptr <= emergency_arena_end); CHECK_CONDITION(emergency_arena_start <= old_ptr); // NOTE: we don't know previous size of old_ptr chunk. So instead // of trying to figure out right size of copied memory, we just // copy largest possible size. We don't care about being slow. size_t old_ptr_size = emergency_arena_end - old_ptr; size_t copy_size = (new_size < old_ptr_size) ? new_size : old_ptr_size; void *new_ptr = LowLevelAlloc::AllocWithArena(new_size, emergency_arena); if (new_ptr == NULL) { errno = ENOMEM; return NULL; } memcpy(new_ptr, old_ptr, copy_size); LowLevelAlloc::Free(old_ptr); return new_ptr; } PERFTOOLS_DLL_DECL void *EmergencyCalloc(size_t n, size_t elem_size) { // Overflow check const size_t size = n * elem_size; if (elem_size != 0 && size / elem_size != n) return NULL; void *rv = EmergencyMalloc(size); if (rv != NULL) { memset(rv, 0, size); } return rv; } };
412
0.985393
1
0.985393
game-dev
MEDIA
0.831506
game-dev
0.932401
1
0.932401
Hoto-Mocha/New-Blue-Archive-Pixel-Dungeon
5,619
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/potions/exotic/PotionOfDivineInspiration.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2025 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.potions.exotic; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Talent; import com.shatteredpixel.shatteredpixeldungeon.effects.Flare; import com.shatteredpixel.shatteredpixeldungeon.journal.Catalog; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.shatteredpixel.shatteredpixeldungeon.ui.StatusPane; import com.shatteredpixel.shatteredpixeldungeon.ui.TalentsPane; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.shatteredpixel.shatteredpixeldungeon.windows.WndHero; import com.shatteredpixel.shatteredpixeldungeon.windows.WndOptions; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Bundle; import com.watabou.utils.Random; public class PotionOfDivineInspiration extends ExoticPotion { { icon = ItemSpriteSheet.Icons.POTION_DIVINE; talentFactor = 2f; } protected static boolean identifiedByUse = false; @Override //need to override drink so that time isn't spent right away protected void drink(final Hero hero) { if (!isKnown()) { identify(); curItem = detach( hero.belongings.backpack ); identifiedByUse = true; } else { identifiedByUse = false; } boolean[] enabled = new boolean[5]; enabled[1] = enabled[2] = enabled[3] = enabled[4] = true; DivineInspirationTracker tracker = hero.buff(DivineInspirationTracker.class); if (tracker != null){ boolean allBoosted = true; for (int i = 1; i <= 4; i++){ if (tracker.isBoosted(i)){ enabled[i] = false; } else { allBoosted = false; } } if (allBoosted){ GLog.w(Messages.get(this, "no_more_points")); return; } } GameScene.show(new WndOptions( new ItemSprite(this), Messages.titleCase(trueName()), Messages.get(PotionOfDivineInspiration.class, "select_tier"), Messages.titleCase(Messages.get(TalentsPane.class, "tier", 1)), Messages.titleCase(Messages.get(TalentsPane.class, "tier", 2)), Messages.titleCase(Messages.get(TalentsPane.class, "tier", 3)), Messages.titleCase(Messages.get(TalentsPane.class, "tier", 4)) ){ @Override protected boolean enabled(int index) { return enabled[index+1]; } @Override protected void onSelect(int index) { super.onSelect(index); if (index != -1){ Buff.affect(curUser, DivineInspirationTracker.class).setBoosted(index+1); if (!identifiedByUse) { curItem.detach(curUser.belongings.backpack); } identifiedByUse = false; curUser.busy(); curUser.sprite.operate(curUser.pos); curUser.spendAndNext(1f); boolean unspentTalents = false; for (int i = 1; i <= Dungeon.hero.talents.size(); i++){ if (Dungeon.hero.talentPointsAvailable(i) > 0){ unspentTalents = true; break; } } if (unspentTalents){ StatusPane.talentBlink = 10f; WndHero.lastIdx = 1; } GameScene.showlevelUpStars(); Sample.INSTANCE.play( Assets.Sounds.DRINK ); Sample.INSTANCE.playDelayed(Assets.Sounds.LEVELUP, 0.3f, 0.7f, 1.2f); Sample.INSTANCE.playDelayed(Assets.Sounds.LEVELUP, 0.6f, 0.7f, 1.2f); new Flare( 6, 32 ).color(0xFFFF00, true).show( curUser.sprite, 2f ); GLog.p(Messages.get(PotionOfDivineInspiration.class, "bonus")); if (!anonymous) { Catalog.countUse(PotionOfDivineInspiration.class); if (Random.Float() < talentChance) { Talent.onPotionUsed(curUser, curUser.pos, talentFactor); } } } } @Override public void onBackPressed() { //window can be closed if potion is already IDed if (!identifiedByUse){ super.onBackPressed(); } } }); } public static class DivineInspirationTracker extends Buff { { type = buffType.POSITIVE; revivePersists = true; } private boolean[] boostedTiers = new boolean[5]; private static final String BOOSTED_TIERS = "boosted_tiers"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put(BOOSTED_TIERS, boostedTiers); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); boostedTiers = bundle.getBooleanArray(BOOSTED_TIERS); } public void setBoosted( int tier ){ boostedTiers[tier] = true; } public boolean isBoosted( int tier ){ return boostedTiers[tier]; } } }
412
0.910219
1
0.910219
game-dev
MEDIA
0.985064
game-dev
0.996411
1
0.996411
xfw5/Fear-SDK-1.08
70,571
Game/ObjectDLL/ControlPoint.cpp
// ----------------------------------------------------------------------- // // // MODULE : ControlPoint.cpp // // PURPOSE : ControlPoint object to place in Control Point level. // // CREATED : 02/09/06 // // (c) 2006 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // // // Includes... // #include "Stdafx.h" #include "ControlPoint.h" #include "PlayerObj.h" #include "ObjectMsgs.h" #include "PropsDB.h" #include "GameModeMgr.h" #include "StateMachine.h" #include "TeamMgr.h" #include "SFXMsgIds.h" #include "ServerConnectionMgr.h" #include "ServerMissionMgr.h" #include "ltintersect.h" #include "GameStartPointMgr.h" #include "ServerMissionMgr.h" #include "SurfaceFlagsOverrideHelpers.h" #include "CollisionsDB.h" #include "SurfaceFunctions.h" LINKFROM_MODULE( ControlPoint ) class ControlPoint; // Tracks which control point id's have been used. uint8 ControlPoint::m_nAllocatedControlPointIds = 0; // Control level value when team 0 has 100% control. static const float kControlLevel_Team0 = -1.0f; // Control level value when Neutral has 100% control. static const float kControlLevel_Neutral = 0.0f; // Control level value when team 1 has 100% control. static const float kControlLevel_Team1 = 1.0f; // Time period to send the control level to client. static const float kControlPoint_ControlLevelSendPeriod = 0.25f; // List of existing control point objects. ControlPoint::TControlPointList ControlPoint::m_lstControlPoints; // Statemachine to handle controlpoint states. class ControlPointStateMachine : public MacroStateMachine { public: ControlPointStateMachine( ); ~ControlPointStateMachine( ) { Term( ); } // Initialize to a ControlPoint. bool Init( ControlPoint& controPoint ) { m_pControlPoint = &controPoint; // Listen for player kill events. m_delegatePlayerKillEvent.Attach( this, NULL, CPlayerObj::PlayerScoredKillEvent ); m_lstCharactersInZone.resize( 0 ); m_nCharactersInZoneDiff = 0; // Add a gravity source object. if( DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_pControlPoint->m_hControlPointRec, AttractSpawns )) { GameStartPointMgr::GravitySource gravitySource; gravitySource.m_eTeamId = INVALID_TEAM; gravitySource.m_hObject = m_pControlPoint->m_hObject; GameStartPointMgr::Instance().AddManagedGravitySource( gravitySource ); } return true; } void Term( ) { // No longer listen for player kill events. m_delegatePlayerKillEvent.Detach(); // Remove our managed gravitysource object. if( m_pControlPoint && DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_pControlPoint->m_hControlPointRec, AttractSpawns )) { GameStartPointMgr::Instance().RemoveManagedGravitySource( m_pControlPoint->m_hObject ); } } // Send touch event to state. bool DoTouchEvent( HOBJECT hToucher ) { ControlPointEventParams eventParams; eventParams.m_hObject = hToucher; return DoUserEvent( eControlPointEvent_Touched, eventParams ); } // Send player kill event to state. bool DoPlayerKillEvent( HOBJECT hKiller, HOBJECT hVictim ) { PlayerKillEventParams eventParams; eventParams.m_hKiller = hKiller; eventParams.m_hVictim = hVictim; return DoUserEvent( eControlPointEvent_PlayerKilled, eventParams ); } // Gets the team that owns the controlpoint. ETeamId GetTeamId( ) const; // override of MacroStateMachine. using MacroStateMachine::SetState; virtual bool SetState( uint32 nNewState, ILTMessage_Write* pMsg ); protected: // Statemachine event handlers. bool Team0_OnEnter( MacroStateMachine::EventParams& eventParams ); bool Team0_OnUpdate( MacroStateMachine::EventParams& eventParams ); bool Team0_OnExit( MacroStateMachine::EventParams& eventParams ); bool Team1_OnEnter( MacroStateMachine::EventParams& eventParams ); bool Team1_OnUpdate( MacroStateMachine::EventParams& eventParams ); bool Team1_OnExit( MacroStateMachine::EventParams& eventParams ); bool Neutral_OnEnter( MacroStateMachine::EventParams& eventParams ); bool Neutral_OnUpdate( MacroStateMachine::EventParams& eventParams ); bool Neutral_OnExit( MacroStateMachine::EventParams& eventParams ); // Generalized functions for event handlers. bool TeamX_OnEnter( float fControlLevel, ETeamId eOwningTeamId, char const* pszTeamCapturedControlCmd ); bool TeamX_OnExit( ETeamId eOwningTeamId ); bool TeamX_OnPlayerKill( MacroStateMachine::EventParams& eventParams ); bool OnTouched( MacroStateMachine::EventParams& eventParams ); // ControlPoint event paramaters. struct ControlPointEventParams : public EventParams { ControlPointEventParams( ) { m_hObject = NULL; } HOBJECT m_hObject; }; // Params sent with player kill event. struct PlayerKillEventParams : public EventParams { PlayerKillEventParams( ) { m_hKiller = NULL; m_hVictim = NULL; } HOBJECT m_hKiller; HOBJECT m_hVictim; }; // Statemachine events for ControlPoint. enum EControlPointEvent { // Player killed event. eControlPointEvent_PlayerKilled = EVENT_User, // ControlPoint touched. eControlPointEvent_Touched, // ControlPoint capture. eControlPointEvent_Capture, }; // State table. MSM_BeginTable( ControlPointStateMachine ) MSM_BeginState( kControlPointState_Team0 ) MSM_OnEnter( Team0_OnEnter ) MSM_OnUpdate( Team0_OnUpdate ) MSM_OnEvent( eControlPointEvent_PlayerKilled, TeamX_OnPlayerKill ) MSM_OnEvent( eControlPointEvent_Touched, OnTouched ) MSM_OnExit( Team0_OnExit ) MSM_EndState( ) MSM_BeginState( kControlPointState_Team1 ) MSM_OnEnter( Team1_OnEnter ) MSM_OnUpdate( Team1_OnUpdate ) MSM_OnEvent( eControlPointEvent_PlayerKilled, TeamX_OnPlayerKill ) MSM_OnEvent( eControlPointEvent_Touched, OnTouched ) MSM_OnExit( Team1_OnExit ) MSM_EndState( ) MSM_BeginState( kControlPointState_Neutral ) MSM_OnEnter( Neutral_OnEnter ) MSM_OnUpdate( Neutral_OnUpdate ) MSM_OnEvent( eControlPointEvent_Touched, OnTouched ) MSM_OnExit( Neutral_OnExit ) MSM_EndState( ) MSM_EndTable( ) // Declare delegate to listen for player kill events. static void OnPlayerKillEvent( ControlPointStateMachine* pControlPointStateMachine, CPlayerObj* pPlayerObj, EventCaster::NotifyParams& notifyParams ) { CPlayerObj::PlayerScoredKillEventParams& playerScoredKillNotifyParams = ( CPlayerObj::PlayerScoredKillEventParams& )notifyParams; pControlPointStateMachine->DoPlayerKillEvent( playerScoredKillNotifyParams.m_hKiller, playerScoredKillNotifyParams.m_hVictim ); } Delegate< ControlPointStateMachine, CPlayerObj, ControlPointStateMachine::OnPlayerKillEvent > m_delegatePlayerKillEvent; // Cleans up the character in zone list to only contain valid characters. void CleanCharactersInZoneList( ); // Record the work done by a team influencing control. void RecordTeamWork( uint8 nTeamId, float fWorkTime ); // Record the work done by a character influencing control. void RecordCharacterWork( CCharacter& character, float fWorkTime ); // Give points to team. void AwardTeamPoints( int32 nPoints, uint8 nTeamId ); // Give the contributing characters the work award. void AwardCharacterWorkPoints( EControlPointFXMsgId eControlPointFXMsgId, int32 nPlayerPoints, uint8 nTeamId ); // Adds character influence to timed captures. bool AddCharacterInZone( HOBJECT hCharacter ); // Processes the inzone list. bool ProcessCharactersInZone( ); // Check for instant capture. bool CheckInstantCapture( HOBJECT hObject ); // Sends the client an event message. void SendClientEventMessage( HCLIENT hClient, uint32 nState, ILTMessage_Write* pEventMsg, bool bGuaranteed ); // Send the control level to the client. void SendControlLevel( bool bGuaranteed ); // Check if we are getting points for owning the CP. void UpdateOwnershipPoints( ETeamId eOwningTeamId ); // Data type to track the history of the character within the zone. struct CharacterWorkHistory { CharacterWorkHistory( ) { m_fTimeCapturing = 0.0f; } // Character reference. LTObjRef m_hCharacter; // Time spent doing work to capture cp. float m_fTimeCapturing; }; private: // The controlpoint that owns us. ControlPoint* m_pControlPoint; // List of characters that are within the zonedims. ObjRefVector m_lstCharactersInZone; // Effective number of characters, taking into account multiple teams in the zone together. int32 m_nCharactersInZoneDiff; // Data used to track character's history in zone. typedef std::vector< CharacterWorkHistory > TCharacterWorkHistoryList; TCharacterWorkHistoryList m_lstCharacterWorkHistory; // Timer to track when to send control level updates. StopWatchTimer m_tmrControlLevelUpdate; // Timer to track when to award team points for owning CP. StopWatchTimer m_tmrOwningControlPointScoring; // Control level. Varies from [-1,+1] based on controlling team. float m_fControlLevel; }; // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::ControlPointStateMachine // // PURPOSE: Constructor // // ----------------------------------------------------------------------- // ControlPointStateMachine::ControlPointStateMachine( ) { m_pControlPoint = NULL; m_fControlLevel = 0.0f; RealTimeTimer& realTimeTimer = RealTimeTimer::Instance( ); m_tmrControlLevelUpdate.SetEngineTimer( realTimeTimer ); m_tmrOwningControlPointScoring.SetEngineTimer( realTimeTimer ); m_nCharactersInZoneDiff = 0; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::SendClientEventMessage // // PURPOSE: Sends event message to client. // // ----------------------------------------------------------------------- // void ControlPointStateMachine::SendClientEventMessage( HCLIENT hClient, uint32 nState, ILTMessage_Write* pEventMsg, bool bGuaranteed ) { CAutoMessage cMsg; cMsg.Writeuint8( MID_SFX_MESSAGE ); cMsg.Writeuint8( SFX_CONTROLPOINT_ID ); cMsg.WriteObject( m_pControlPoint->m_hObject ); cMsg.WriteBits( nState, FNumBitsExclusive<kControlPointState_NumStates>::k_nValue ); // If there are any event data to go with it write it out here. if( pEventMsg ) { cMsg.Writebool( true ); cMsg.WriteMessageRaw( pEventMsg->Read( )); } else { cMsg.Writebool( false ); } g_pLTServer->SendToClient( cMsg.Read( ), hClient, bGuaranteed ? MESSAGE_GUARANTEED : 0 ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::SetState // // PURPOSE: Override of MacroStateMachine. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::SetState( uint32 nNewState, ILTMessage_Write* pEventMsg ) { // Let parent handle it first. if( !MacroStateMachine::SetState( nNewState )) return false; // Send the event message to client. SendClientEventMessage( NULL, nNewState, pEventMsg, true ); // Update the main sfx message. m_pControlPoint->CreateSpecialFX( false ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::GetTeamId // // PURPOSE: Gets the team that owns the control point. // // ----------------------------------------------------------------------- // inline ETeamId ControlPointStateMachine::GetTeamId( ) const { if( GetState( ) == kControlPointState_Team0 ) return kTeamId0; else if( GetState( ) == kControlPointState_Team1 ) return kTeamId1; else return INVALID_TEAM; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Team0_OnEnter // // PURPOSE: Handle a enter Team0 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Team0_OnEnter( MacroStateMachine::EventParams& eventParams ) { return TeamX_OnEnter( kControlLevel_Team0, kTeamId0, m_pControlPoint->m_pszTeam0CapturedControlCmd ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Team0_OnUpdate // // PURPOSE: Handle a update Team0 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Team0_OnUpdate( MacroStateMachine::EventParams& eventParams ) { // Process the inzone list. ProcessCharactersInZone( ); GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // See if we have been neutralized. if( m_fControlLevel >= kControlLevel_Neutral ) { // Go to the neutralized state. SetState( kControlPointState_Neutral, NULL ); return true; } // Give any fixup points for regaining full control. if( m_fControlLevel == kControlLevel_Team0 && m_lstCharacterWorkHistory.size( ) > 0 ) { AwardCharacterWorkPoints( kControlPointFXMsg_PlayerFixup, gameModeMgr.m_grnCPScoreCapturePlayer, kTeamId0 ); } // Update our ownership points. UpdateOwnershipPoints( kTeamId0 ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Team0_OnExit // // PURPOSE: Handle a exit Team0 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Team0_OnExit( MacroStateMachine::EventParams& eventParams ) { TeamX_OnExit( kTeamId0 ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Team1_OnEnter // // PURPOSE: Handle a enter Team1 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Team1_OnEnter( MacroStateMachine::EventParams& eventParams ) { return TeamX_OnEnter( kControlLevel_Team1, kTeamId1, m_pControlPoint->m_pszTeam1CapturedControlCmd ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Team1_OnUpdate // // PURPOSE: Handle a update Team1 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Team1_OnUpdate( MacroStateMachine::EventParams& eventParams ) { // Process the inzone list. ProcessCharactersInZone( ); GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // See if we have been neutralized. if( m_fControlLevel <= kControlLevel_Neutral ) { // Go to the neutralized state. SetState( kControlPointState_Neutral, NULL ); return true; } // Give any fixup points for regaining full control. if( m_fControlLevel == kControlLevel_Team1 && m_lstCharacterWorkHistory.size( ) > 0 ) { AwardCharacterWorkPoints( kControlPointFXMsg_PlayerFixup, gameModeMgr.m_grnCPScoreCapturePlayer, kTeamId1 ); } // Update our ownership points. UpdateOwnershipPoints( kTeamId1 ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Team1_OnExit // // PURPOSE: Handle a exit Team1 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Team1_OnExit( MacroStateMachine::EventParams& eventParams ) { TeamX_OnExit( kTeamId1 ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::TeamX_OnEnter // // PURPOSE: Handle a enter Team0/Team1 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::TeamX_OnEnter( float fControlLevel, ETeamId eOwningTeamId, char const* pszTeamCapturedControlCmd ) { // Don't allow caps after end round condition met. if( g_pServerMissionMgr->IsEndRoundConditionMet( )) return false; // Control level is fully in control when first entering state. m_fControlLevel = fControlLevel; // Don't need to send period control updates if we're fully controlled. m_tmrControlLevelUpdate.Stop( ); GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // Give the team the capture points. AwardTeamPoints( gameModeMgr.m_grnCPScoreCaptureTeam, eOwningTeamId ); // Give the contributing characters the work award. AwardCharacterWorkPoints( kControlPointFXMsg_PlayerCapture, gameModeMgr.m_grnCPScoreCapturePlayer, eOwningTeamId ); // Check if we need to award points to the team for owning the CP. float fOwnedScorePeriod = gameModeMgr.m_grfCPOwnedScorePeriod; m_tmrOwningControlPointScoring.Stop(); if( fOwnedScorePeriod > 0.0f ) { uint32 nOwnedScoreAmountTeam = gameModeMgr.m_grnCPOwnedScoreAmountTeam; if( nOwnedScoreAmountTeam ) { m_tmrOwningControlPointScoring.Start( fOwnedScorePeriod ); // Tell our parent object to update. m_pControlPoint->SetNextUpdate( UPDATE_NEXT_FRAME ); } } // Update the spawnpoint gravity. if( DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_pControlPoint->m_hControlPointRec, AttractSpawns )) { GameStartPointMgr::GravitySource* pGravitySource = GameStartPointMgr::Instance().GetManagedGravitySource( m_pControlPoint->m_hObject ); if( pGravitySource ) { pGravitySource->m_eTeamId = GetTeamId(); } } // Send the command that team 0 captures the CP. if( !LTStrEmpty( pszTeamCapturedControlCmd )) { g_pCmdMgr->QueueCommand( pszTeamCapturedControlCmd, m_pControlPoint->m_hObject, m_pControlPoint->m_hObject ); } // Checks to see if conquest has been achieved. ControlPoint::CheckForConquestWin( ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::TeamX_OnExit // // PURPOSE: Handle a exit Team0/1 state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::TeamX_OnExit( ETeamId eOwningTeamId ) { // Give the losing team the lost points. AwardTeamPoints( -(( int32 )GameModeMgr::Instance().m_grnCPScoreLoseTeam ), eOwningTeamId ); // No longer getting points for owning. m_tmrOwningControlPointScoring.Stop( ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::TeamX_OnPlayerKill // // PURPOSE: Handle a playerkilled event for Team0 or Team1 states. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::TeamX_OnPlayerKill( MacroStateMachine::EventParams& eventParams ) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: Entry", __FUNCTION__ ); #endif // DEBUG_DEFEND_MESSAGES PlayerKillEventParams& playerKilledEventParams = ( PlayerKillEventParams& )eventParams; GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // Make sure they can get points for this kill int32 nDefendScorePlayer = gameModeMgr.m_grnCPDefendScorePlayer; int32 nDefendScoreTeam = gameModeMgr.m_grbUseTeams ? gameModeMgr.m_grnCPDefendScoreTeam : 0; if( !nDefendScorePlayer && nDefendScoreTeam ) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: No defend score", __FUNCTION__ ); #endif // DEBUG_DEFEND_MESSAGES return false; } int32 nDefendRadius = gameModeMgr.m_grnCPDefendRadius; if( !nDefendRadius ) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: No defend radius", __FUNCTION__ ); #endif // DEBUG_DEFEND_MESSAGES return false; } // Only care about killers that are on our team. CPlayerObj* pKillerPlayerObj = CPlayerObj::DynamicCast( playerKilledEventParams.m_hKiller ); if( !pKillerPlayerObj ) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: no killer object", __FUNCTION__ ); #endif // DEBUG_DEFEND_MESSAGES return false; } #ifdef DEBUG_DEFEND_MESSAGES { GameClientData* pKillerGameClientData = ServerConnectionMgr::Instance().GetGameClientData( pKillerPlayerObj->GetClient( )); g_pLTBase->CPrint( "%s: pKillerGameClientData->GetUniqueName(%s), pKillerPlayerObj->GetTeamID(%d)", __FUNCTION__, MPW2A( pKillerGameClientData->GetUniqueName( )).c_str(), pKillerPlayerObj->GetTeamID()); } #endif // DEBUG_DEFEND_MESSAGES if( pKillerPlayerObj->GetTeamID() != GetTeamId( )) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: killer on different team than controlpoint", __FUNCTION__); #endif // DEBUG_DEFEND_MESSAGES return false; } // Only care about victims that are on the other team. CPlayerObj* pVictimPlayerObj = CPlayerObj::DynamicCast( playerKilledEventParams.m_hVictim ); if( !pVictimPlayerObj ) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: no victim object", __FUNCTION__ ); #endif // DEBUG_DEFEND_MESSAGES return false; } #ifdef DEBUG_DEFEND_MESSAGES { GameClientData* pVictimGameClientData = ServerConnectionMgr::Instance().GetGameClientData( pVictimPlayerObj->GetClient( )); g_pLTBase->CPrint( "%s: pVictimGameClientData->GetUniqueName(%s), pVictimPlayerObj->GetTeamID(%d)", __FUNCTION__, MPW2A( pVictimGameClientData->GetUniqueName( )).c_str(), pVictimPlayerObj->GetTeamID()); } #endif // DEBUG_DEFEND_MESSAGES if( pVictimPlayerObj->GetTeamID() == GetTeamId( )) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: victim on same team as controlpoint", __FUNCTION__ ); #endif // DEBUG_DEFEND_MESSAGES return false; } // Get the controlpoint position. LTVector vControlPointPos; g_pLTServer->GetObjectPos( m_pControlPoint->m_hObject, &vControlPointPos ); // Get the position of the victim. LTVector vVictimPos; g_pLTServer->GetObjectPos( pVictimPlayerObj->m_hObject, &vVictimPos ); #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: vVictimPos(%.3f,%.3f,%.3f), vControlPointPos(%.3f,%.3f,%.3f),dist(%.3f), nDefendRadius(%d)", __FUNCTION__, VEC_EXPAND( vVictimPos ), VEC_EXPAND( vControlPointPos ), vControlPointPos.Dist( vVictimPos ), nDefendRadius ); #endif // DEBUG_DEFEND_MESSAGES // See if the victim is beyond radius. if( vControlPointPos.DistSqr( vVictimPos ) > nDefendRadius * nDefendRadius ) { #ifdef DEBUG_DEFEND_MESSAGES g_pLTBase->CPrint( "%s: victim beyond radius", __FUNCTION__ ); #endif // DEBUG_DEFEND_MESSAGES return false; } #ifdef DEBUG_DEFEND_MESSAGES { GameClientData* pKillerGameClientData = ServerConnectionMgr::Instance().GetGameClientData( pKillerPlayerObj->GetClient( )); GameClientData* pVictimGameClientData = ServerConnectionMgr::Instance().GetGameClientData( pVictimPlayerObj->GetClient( )); g_pLTBase->CPrint( "%s: %s defended his controlpoint killing %s", __FUNCTION__, MPW2A( pKillerGameClientData->GetUniqueName( )).c_str(), MPW2A( pVictimGameClientData->GetUniqueName( )).c_str()); } #endif // DEBUG_DEFEND_MESSAGES // Give the killer some objective points. GameClientData* pGameClientData = ServerConnectionMgr::Instance().GetGameClientData( pKillerPlayerObj->GetClient( )); if( nDefendScorePlayer ) { if( pGameClientData ) pGameClientData->GetPlayerScore()->AddObjectiveScore( nDefendScorePlayer ); } if( nDefendScoreTeam ) { CTeamMgr::Instance().AddToScore( pKillerPlayerObj->GetTeamID(), nDefendScoreTeam ); } if( nDefendScorePlayer || nDefendScoreTeam ) { // Prepare the event message. CAutoMessage cEventMsg; cEventMsg.WriteBits( kControlPointFXMsg_PlayerControlPointDefend, FNumBitsExclusive<kControlPointFXMsg_NumIds>::k_nValue ); HCLIENT hKillerClient = pKillerPlayerObj->GetClient(); uint8 nKillerClientId = ( uint8 )g_pLTServer->GetClientID( hKillerClient ); cEventMsg.Writeuint8( nKillerClientId ); // Send event message. SendClientEventMessage( pGameClientData->GetClient(), GetState( ), cEventMsg, true ); } return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::OnTouched // // PURPOSE: Handle a touched event for Team0/1/Neutral. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::OnTouched( MacroStateMachine::EventParams& eventParams ) { ControlPointEventParams& controlPointEventParams = static_cast< ControlPointEventParams& >( eventParams ); // Add the character to the zone if capturing takes time. if( GameModeMgr::Instance().m_grfCPCapturingTime > 0.0f ) { AddCharacterInZone( controlPointEventParams.m_hObject ); } // Do instant capturing. else { CheckInstantCapture( controlPointEventParams.m_hObject ); } return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Neutral_OnEnter // // PURPOSE: Handle a enter Neutral state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Neutral_OnEnter( MacroStateMachine::EventParams& eventParams ) { // Don't allow neutral after end round condition met. if( g_pServerMissionMgr->IsEndRoundConditionMet( )) return false; // Make sure the control level is clamped within range. m_fControlLevel = LTCLAMP( m_fControlLevel, kControlLevel_Team0, kControlLevel_Team1 ); GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // Check if we've been neutralized from the Team0 state. if(( EControlPointState )eventParams.m_nPreviousState == kControlPointState_Team0 ) { // Give the neutralizing team the neutralize points. AwardTeamPoints( gameModeMgr.m_grnCPScoreNeutralizeTeam, kTeamId1 ); // Give the contributing characters the work award. AwardCharacterWorkPoints( kControlPointFXMsg_PlayerNeutralize, gameModeMgr.m_grnCPScoreNeutralizePlayer, kTeamId1 ); // Send the command that team 1 neutralized the CP. if( !LTStrEmpty( m_pControlPoint->m_pszTeam1NeutralizedControlCmd )) { g_pCmdMgr->QueueCommand( m_pControlPoint->m_pszTeam1NeutralizedControlCmd, m_pControlPoint->m_hObject, m_pControlPoint->m_hObject ); } } // Check if we've been neutralized from the Team1 state. else if(( EControlPointState )eventParams.m_nPreviousState == kControlPointState_Team1 ) { // Give the neutralizing team the neutralize points. AwardTeamPoints( gameModeMgr.m_grnCPScoreNeutralizeTeam, kTeamId0 ); // Give the contributing characters the work award. AwardCharacterWorkPoints( kControlPointFXMsg_PlayerNeutralize, gameModeMgr.m_grnCPScoreNeutralizePlayer, kTeamId0 ); // Send the command that team 0 neutralized the CP. if( !LTStrEmpty( m_pControlPoint->m_pszTeam0NeutralizedControlCmd )) { g_pCmdMgr->QueueCommand( m_pControlPoint->m_pszTeam0NeutralizedControlCmd, m_pControlPoint->m_hObject, m_pControlPoint->m_hObject ); } } // Update the spawnpoint gravity. if( DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_pControlPoint->m_hControlPointRec, AttractSpawns )) { GameStartPointMgr::GravitySource* pGravitySource = GameStartPointMgr::Instance().GetManagedGravitySource( m_pControlPoint->m_hObject ); if( pGravitySource ) { pGravitySource->m_eTeamId = GetTeamId(); } } return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Neutral_OnUpdate // // PURPOSE: Handle a update Neutral state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Neutral_OnUpdate( MacroStateMachine::EventParams& eventParams ) { // Process the inzone list. ProcessCharactersInZone( ); // See if we have been captured to team0. if( m_fControlLevel <= kControlLevel_Team0 ) { SetState( kControlPointState_Team0, NULL ); return true; } // See if we have been captured to team1. else if( m_fControlLevel >= kControlLevel_Team1 ) { SetState( kControlPointState_Team1, NULL ); return true; } return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::Neutral_OnExit // // PURPOSE: Handle a exit Neutral state. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::Neutral_OnExit( MacroStateMachine::EventParams& eventParams ) { return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::CheckInstantCapture // // PURPOSE: Check for instant capture. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::CheckInstantCapture( HOBJECT hObject ) { // Clear the work history, since we're playing with instant captures. ltstd::reset_vector( m_lstCharacterWorkHistory ); // Get the character. CCharacter* pCharacter = static_cast< CCharacter* >( g_pLTServer->HandleToObject( hObject )); // Check if the character is invalid. if( !pCharacter->IsAlive( ) || pCharacter->GetTeamID() == INVALID_TEAM ) return true; // Default to no points to award. bool bAwardCapturePoints = false; // Turn the CP in the team0 favor if not already fully controlled by team0. if( pCharacter->GetTeamID() == 0 && m_fControlLevel > kControlLevel_Team0 ) { // Make sure we're in the team0 state. SetState( kControlPointState_Team0, NULL ); bAwardCapturePoints = true; } // Turn the CP in the team1 favor if not already fully controlled by team1. else if( pCharacter->GetTeamID() == 1 && m_fControlLevel < kControlLevel_Team1 ) { // Make sure we're in the team0 state. SetState( kControlPointState_Team1, NULL ); bAwardCapturePoints = true; } // See if the player gets capture points. if( bAwardCapturePoints ) { GameModeMgr& gameModeMgr = GameModeMgr::Instance(); int32 nCPScoreCapturePlayer = gameModeMgr.m_grnCPScoreCapturePlayer; if( !nCPScoreCapturePlayer ) return true; // Give the player some objective points. CPlayerObj* pPlayerObj = CPlayerObj::DynamicCast( hObject ); if( !pPlayerObj ) return true; GameClientData* pGameClientData = ServerConnectionMgr::Instance().GetGameClientData( pPlayerObj->GetClient( )); if( !pGameClientData ) return true; pGameClientData->GetPlayerScore()->AddObjectiveScore( nCPScoreCapturePlayer ); // Tell the client of their event if points were awarded. CAutoMessage cEventMsg; cEventMsg.WriteBits( kControlPointFXMsg_PlayerCapture, FNumBitsExclusive<kControlPointFXMsg_NumIds>::k_nValue ); uint8 nPlayerId = ( uint8 )g_pLTServer->GetClientID( pGameClientData->GetClient( )); cEventMsg.Writeuint8( nPlayerId ); SendClientEventMessage( pGameClientData->GetClient(), GetState( ), cEventMsg, true ); } return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::UpdateOwnershipPoints // // PURPOSE: Check if we are getting points for owning the CP. // // ----------------------------------------------------------------------- // void ControlPointStateMachine::UpdateOwnershipPoints( ETeamId eOwningTeamId ) { GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // Check if we are getting points for owning the CP. if( m_tmrOwningControlPointScoring.IsStarted( )) { if( m_tmrOwningControlPointScoring.IsTimedOut( )) { // Award the points. AwardTeamPoints( gameModeMgr.m_grnCPOwnedScoreAmountTeam, eOwningTeamId ); // Start the next period. m_tmrOwningControlPointScoring.Start( gameModeMgr.m_grfCPOwnedScorePeriod ); } // Tell our parent object to update. m_pControlPoint->SetNextUpdate( UPDATE_NEXT_FRAME ); } } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::AddCharacterInZone // // PURPOSE: Handle a touched event. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::AddCharacterInZone( HOBJECT hObject ) { // Only applicable if capturing takes time. if( GameModeMgr::Instance().m_grfCPCapturingTime <= 0.0f ) return true; CCharacter* pCharacter = CCharacter::DynamicCast( hObject ); if( !pCharacter ) return true; // Check if we already have this object in the list. for( ObjRefVector::iterator iter = m_lstCharactersInZone.begin(); iter != m_lstCharactersInZone.end( ); iter++ ) { if( *iter == pCharacter->m_hObject ) return true; } // Add it to the list. m_lstCharactersInZone.push_back( pCharacter->m_hObject ); // Tell our parent object to update. m_pControlPoint->SetNextUpdate( UPDATE_NEXT_FRAME ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::CleanCharactersInZoneList // // PURPOSE: Cleans up the character in zone list to only contain valid characters. // // ----------------------------------------------------------------------- // void ControlPointStateMachine::CleanCharactersInZoneList( ) { // Clear our calculation of the difference in characters in zone. m_nCharactersInZoneDiff = 0; // Check if there are no characters in zone. if( m_lstCharactersInZone.size( ) == 0 ) return; // Get the AABB for the zone. LTVector vZonePos; g_pLTServer->GetObjectPos( m_pControlPoint->m_hObject, &vZonePos ); LTVector const& vZoneDims = m_pControlPoint->GetZoneDims(); LTRect3f rectZone( vZonePos - vZoneDims, vZonePos + vZoneDims ); // Check if we already have this object in the list. ObjRefVector::iterator iter = m_lstCharactersInZone.begin(); while( iter != m_lstCharactersInZone.end( )) { HOBJECT hToucher = *iter; if( !hToucher ) { iter = m_lstCharactersInZone.erase( iter ); continue; } // Get the character this is. CCharacter* pCharacter = static_cast< CCharacter* >( g_pLTServer->HandleToObject( hToucher )); // Ignore characters that aren't alive. if( !pCharacter->IsAlive( ) || pCharacter->GetTeamID() == INVALID_TEAM ) { iter = m_lstCharactersInZone.erase( iter ); continue; } // Check if character has left the zone. LTVector vCharacterPos; LTVector vCharacterDims; g_pLTServer->GetObjectPos( pCharacter->m_hObject, &vCharacterPos ); g_pLTServer->Physics()->GetObjectDims( pCharacter->m_hObject, &vCharacterDims ); if( !LTIntersect::AABB_AABB( LTRect3f( vCharacterPos - vCharacterDims, vCharacterPos + vCharacterDims ), rectZone )) { iter = m_lstCharactersInZone.erase( iter ); continue; } iter++; } } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::RecordTeamWork // // PURPOSE: Record the work done by a team influencing control. // // ----------------------------------------------------------------------- // void ControlPointStateMachine::RecordTeamWork( uint8 nTeamId, float fWorkTime ) { // Find all the team characters. for( ObjRefVector::iterator iter = m_lstCharactersInZone.begin( ); iter != m_lstCharactersInZone.end( ); iter++ ) { HOBJECT hCharacter = *iter; CCharacter* pCharacter = static_cast< CCharacter* >( g_pLTServer->HandleToObject( hCharacter )); // Ignore characters on other teams. if( pCharacter->GetTeamID() != nTeamId ) continue; // Give the character credit. RecordCharacterWork( *pCharacter, fWorkTime ); } } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::RecordCharacterWork // // PURPOSE: Record the work done by a character influencing control. // // ----------------------------------------------------------------------- // void ControlPointStateMachine::RecordCharacterWork( CCharacter& character, float fWorkTime ) { // Check if they are already part of the work history list. for( TCharacterWorkHistoryList::iterator iter = m_lstCharacterWorkHistory.begin( ); iter != m_lstCharacterWorkHistory.end( ); iter++ ) { CharacterWorkHistory& characterWorkHistory = *iter; if( character.m_hObject == characterWorkHistory.m_hCharacter ) { characterWorkHistory.m_fTimeCapturing += fWorkTime; return; } } // If they weren't part of the work history, then add them. CharacterWorkHistory characterWorkHistory; characterWorkHistory.m_hCharacter = character.m_hObject; characterWorkHistory.m_fTimeCapturing += fWorkTime; m_lstCharacterWorkHistory.push_back( characterWorkHistory ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::AwardTeamPoints // // PURPOSE: Give points to team. // // ----------------------------------------------------------------------- // void ControlPointStateMachine::AwardTeamPoints( int32 nPoints, uint8 nTeamId ) { // Check if no points to award. if( nPoints == 0 ) return; CTeamMgr::Instance().AddToScore( nTeamId, nPoints ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::AwardTeamPoints // // PURPOSE: Give the contributing characters the work award. // // ----------------------------------------------------------------------- // void ControlPointStateMachine::AwardCharacterWorkPoints( EControlPointFXMsgId eControlPointFXMsgId, int32 nPlayerPoints, uint8 nTeamId ) { // Make sure it takes time to capture. No work points if it takes no work. GameModeMgr& gameModeMgr = GameModeMgr::Instance(); if( gameModeMgr.m_grfCPCapturingTime <= 0.0f ) return; CAutoMessage cEventMsg; // Award points to each teammate that worked on control. for( TCharacterWorkHistoryList::iterator iter = m_lstCharacterWorkHistory.begin( ); iter != m_lstCharacterWorkHistory.end( ); iter++ ) { // Get the character object. CharacterWorkHistory& characterWorkHistory = *iter; if( !characterWorkHistory.m_hCharacter ) continue; // They have to be a player. CPlayerObj* pPlayerObj = CPlayerObj::DynamicCast( characterWorkHistory.m_hCharacter ); if( !pPlayerObj ) continue; // Make sure they match the team. if( pPlayerObj->GetTeamID() != nTeamId ) continue; // Get the gameclientdata for this player. GameClientData* pGameClientData = ServerConnectionMgr::Instance().GetGameClientData( pPlayerObj->GetClient( )); if( !pGameClientData ) continue; // Create an award that is proportional to the amount of time capturing divided by the amount of // time it requires to capture. float fAward = ( float )nPlayerPoints * ( characterWorkHistory.m_fTimeCapturing / gameModeMgr.m_grfCPCapturingTime ); // Round up. uint32 nAward = ( uint32 )( fAward + 0.5f ); // If they won't get any points, then skip them. if( nAward == 0 ) continue; // Give the player some objective points. pGameClientData->GetPlayerScore()->AddObjectiveScore( nAward ); // Tell the client of their event. cEventMsg.Reset(); cEventMsg.WriteBits( eControlPointFXMsgId, FNumBitsExclusive<kControlPointFXMsg_NumIds>::k_nValue ); uint8 nPlayerId = ( uint8 )g_pLTServer->GetClientID( pGameClientData->GetClient( )); cEventMsg.Writeuint8( nPlayerId ); SendClientEventMessage( pGameClientData->GetClient(), GetState( ), cEventMsg, true ); } // Clear the work history. ltstd::reset_vector( m_lstCharacterWorkHistory ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::ProcessCharactersInZone // // PURPOSE: Processes the inzone list. // // ----------------------------------------------------------------------- // bool ControlPointStateMachine::ProcessCharactersInZone( ) { // Don't allow action after end round condition met. if( g_pServerMissionMgr->IsEndRoundConditionMet( )) return false; GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // Nothing to do if captures are instant. if( gameModeMgr.m_grfCPCapturingTime <= 0.0f ) return true; // Clean up the list to only have valid characters. CleanCharactersInZoneList( ); // Check if we don't have any characters in the zone. if( m_lstCharactersInZone.size( ) == 0 ) { // See if we were waiting to tell the client about the control level. if( m_tmrControlLevelUpdate.IsStarted( )) { // Stop timing, since there's no one in the zone to tell the client about. m_tmrControlLevelUpdate.Stop(); // Send the control level to the client to make them aware no more clients are around. SendControlLevel( true ); } return true; } uint32 nNumTeam0 = 0; uint32 nNumTeam1 = 0; // Go through character in the zone and figure out what influence on the control they have. for( ObjRefVector::iterator iter = m_lstCharactersInZone.begin( ); iter != m_lstCharactersInZone.end( ); iter++ ) { HOBJECT hCharacter = *iter; CCharacter* pCharacter = static_cast< CCharacter* >( g_pLTServer->HandleToObject( hCharacter )); // Count the team0 character. if( pCharacter->GetTeamID() == 0 ) { nNumTeam0++; } // Count the team1 character. else { nNumTeam1++; } } // Get the difference between teams. m_nCharactersInZoneDiff = nNumTeam1 - nNumTeam0; // Get the time for this frame. float fElapsedTime = GameTimeTimer::Instance().GetTimerElapsedS( ); // Will be set if actual work being done to the control level. uint8 nTeamIdDoingWork = INVALID_TEAM; // Get the effective team count, where negative numbers means more team0 and postive numbers // means more team1. int32 nEffectiveTeamCount = 0; // Will be set to a +/-1 multiplier based on direction control point is getting captured. float fDirectionMultiplier = 0.0f; // Will contain the amount of control left to cap. float fControlDeltaMag = 0.0f; // If team0 has more influence and doesn't have full control, then they are doing work. if( m_nCharactersInZoneDiff < 0 && m_fControlLevel > kControlLevel_Team0 ) { nTeamIdDoingWork = kTeamId0; fDirectionMultiplier = -1.0f; nEffectiveTeamCount = -m_nCharactersInZoneDiff; fControlDeltaMag = m_fControlLevel - kControlLevel_Team0; } // If team1 has more influence and doesn't have full control, then they are doing work. else if( m_nCharactersInZoneDiff > 0 && m_fControlLevel < kControlLevel_Team1 ) { nTeamIdDoingWork = kTeamId1; fDirectionMultiplier = 1.0f; nEffectiveTeamCount = m_nCharactersInZoneDiff; fControlDeltaMag = kControlLevel_Team1 - m_fControlLevel; } // Check if we did actual work to the controllevel. if( nTeamIdDoingWork != INVALID_TEAM ) { // Adjust the control level. The delta to the control level is the amount of time spent // this frame divided by the total time needed. Since multiple people can capture, the time delta // is multiplied by the number of people. So the captures don't go too fast, the speed up // per person is multiplied by group capture factor. float fGroupMultiplier = gameModeMgr.m_grfCPGroupCaptureFactor * ( nEffectiveTeamCount - 1 ) + 1.0f; float fModifiedElapsedTime = fElapsedTime * fGroupMultiplier; // If we spent more time this frame than is needed, clamp to the time required. float fTimeDeltaLeft = fControlDeltaMag * gameModeMgr.m_grfCPCapturingTime; fModifiedElapsedTime = LTMIN( fModifiedElapsedTime, fTimeDeltaLeft ); // Give the team players credit for doing work. RecordTeamWork( nTeamIdDoingWork, fModifiedElapsedTime ); m_fControlLevel += fDirectionMultiplier * fModifiedElapsedTime / gameModeMgr.m_grfCPCapturingTime; m_fControlLevel = LTCLAMP( m_fControlLevel, kControlLevel_Team0, kControlLevel_Team1 ); // If we've reached a full control to one team, then don't need to keep sending. if( m_fControlLevel == kControlLevel_Team0 || m_fControlLevel == kControlLevel_Team1 ) { // Stop sending periodic control level updates since we're at the limit. m_tmrControlLevelUpdate.Stop(); // Tell all clients about it. SendControlLevel( true ); } // Check if it's time to send the control level to the client. else if( m_tmrControlLevelUpdate.IsStarted() && m_tmrControlLevelUpdate.IsTimedOut()) { // Start next period. m_tmrControlLevelUpdate.Start( kControlPoint_ControlLevelSendPeriod ); // Send unguaranteed, since we'll be sending it all the time. SendControlLevel( false ); } // Check if we haven't told the client yet about new characters in the zone. else if( !m_tmrControlLevelUpdate.IsStarted()) { // Start next period. m_tmrControlLevelUpdate.Start( kControlPoint_ControlLevelSendPeriod ); // Send guaranteed so they get the start. SendControlLevel( true ); } } // No one is doing work. Make sure client knows to stop if it was told to start. else if( m_tmrControlLevelUpdate.IsStarted( )) { // Stop sending periodic control level. m_tmrControlLevelUpdate.Stop(); // Tell all clients about it. SendControlLevel( true ); } // Need updates to happen to poll for players. m_pControlPoint->SetNextUpdate( UPDATE_NEXT_FRAME ); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointStateMachine::SendControlLevel // // PURPOSE: Sends client the control level // // ----------------------------------------------------------------------- // void ControlPointStateMachine::SendControlLevel( bool bGuaranteed ) { // Prepare the event message. CAutoMessage cEventMsg; cEventMsg.WriteBits( kControlPointFXMsg_ControlLevel, FNumBitsExclusive<kControlPointFXMsg_NumIds>::k_nValue ); // Make sure the control level sent is clamped to the valid range. float fClampedControlLevel = LTCLAMP( m_fControlLevel, kControlLevel_Team0, kControlLevel_Team1 ); // Map control level to 8 bits for optimization. uint8 nMappedControlLevel = ( uint8 )(( fClampedControlLevel + 1.0f ) * 127.5f ); cEventMsg.Writeuint8( nMappedControlLevel ); // Send whether characters are in the zone. cEventMsg.Writebool( abs( m_nCharactersInZoneDiff ) > 0 ); SendClientEventMessage( NULL, GetState( ), cEventMsg, bGuaranteed ); } // Plugin class for hooking into the level editor for displaying entries in listboxes and displaying the model... class ControlPointPlugin : public IObjectPlugin { public: // Methods... virtual LTRESULT PreHook_EditStringList( const char *szRezPath, const char *szPropName, char **aszStrings, uint32 *pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLen ); virtual LTRESULT PreHook_Dims( const char* szRezPath, const char* szPropName, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector & vDims, const char* pszObjName, ILTPreInterface *pInterface); virtual LTRESULT PreHook_PropChanged( const char *szObjName, const char *szPropName, const int nPropType, const GenericProp &gpPropValue, ILTPreInterface *pInterface, const char *szModifiers ); private: // Members... CCommandMgrPlugin m_CommandMgrPlugin; }; BEGIN_CLASS( ControlPoint ) ADD_STRINGPROP_FLAG( Filename, "", PF_HIDDEN | PF_MODEL, "This hidden property is needed in order to get the model visible within WorldEdit." ) ADD_STRINGPROP_FLAG( Type, "", PF_STATICLIST | PF_DIMS | PF_LOCALDIMS, "Record within the game database GameModes/CP/Types to use for defining control point." ) ADD_VECTORPROP_FLAG( ZoneDims, PF_STATICLIST | PF_DIMS | PF_LOCALDIMS, "The override dims to use for zone if OverrideZoneDims is true. Does not set the physical dims of the object. Override zonedims will be used if all components are greater than 0, otherwise the default zonedims from database will be used.") ADD_STRINGPROP_FLAG( Team, "NoTeam", PF_STATICLIST, "The initial owning team of the object.") ADD_STRINGPROP_FLAG( ControlPointId, "1", PF_STATICLIST, "Unique ID of this control point. All CP's in world must have different ID's.") ADD_BOOLPROP( MoveToFloor, true, "If true the object is moved to the floor when created in the game." ) PROP_DEFINEGROUP(Commands, PF_GROUP(1), "This is a subset that lets you write commands for specific states that the object will carry out when in that state.") ADD_COMMANDPROP_FLAG(Team0NeutralizedControlCmd, "", PF_GROUP(1) | PF_NOTIFYCHANGE, "Command sent if Team0 neutralizes control of the control point.") ADD_COMMANDPROP_FLAG(Team1NeutralizedControlCmd, "", PF_GROUP(1) | PF_NOTIFYCHANGE, "Command sent if Team1 neutralizes control of the control point.") ADD_COMMANDPROP_FLAG(Team0CapturedControlCmd, "", PF_GROUP(1) | PF_NOTIFYCHANGE, "Command sent if Team0 captures control of the control point.") ADD_COMMANDPROP_FLAG(Team1CapturedControlCmd, "", PF_GROUP(1) | PF_NOTIFYCHANGE, "Command sent if Team1 captures control of the control point.") ADD_PREFETCH_RESOURCE_PROPS() END_CLASS_FLAGS_PLUGIN_PREFETCH( ControlPoint, GameBase, CF_DONTSAVE, ControlPointPlugin, DefaultPrefetch<ControlPoint>, "Places a ControlPoint within the level." ) // Register with the CommandMgr... CMDMGR_BEGIN_REGISTER_CLASS( ControlPoint ) CMDMGR_END_REGISTER_CLASS( ControlPoint, GameBase ) LTRESULT ControlPointPlugin::PreHook_EditStringList( const char *szRezPath, const char *szPropName, char **aszStrings, uint32 *pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLen ) { if( !aszStrings || !pcStrings ) { LTERROR( "Invalid input parameters" ); return LT_UNSUPPORTED; } static CParsedMsg::CToken s_cTok_Type( "Type" ); static CParsedMsg::CToken s_cTok_Team( "Team" ); static CParsedMsg::CToken s_cTok_ControlPointId( "ControlPointId" ); // Tokenize the input for fast searching. CParsedMsg::CToken token( szPropName ); if( token == s_cTok_Type ) { // Fill the first string in the list with a <none> selection... LTStrCpy( aszStrings[(*pcStrings)++], "", cMaxStringLen ); // Add an entry for each type. uint8 nNumRecords = DATABASE_CATEGORY( CPTypes ).GetNumRecords(); for( uint8 nRecordIndex = 0; nRecordIndex < nNumRecords; ++nRecordIndex ) { LTASSERT( cMaxStrings > (*pcStrings) + 1, "Too many controlpoint types to fit in the list. Enlarge list size?" ); HRECORD hRecord = DATABASE_CATEGORY( CPTypes ).GetRecordByIndex( nRecordIndex ); if( !hRecord ) continue; const char *pszRecordName = DATABASE_CATEGORY( CPTypes ).GetRecordName( hRecord ); if( !pszRecordName ) continue; if( (LTStrLen( pszRecordName ) < cMaxStringLen) && ((*pcStrings) + 1 < cMaxStrings) ) { LTStrCpy( aszStrings[(*pcStrings)++], pszRecordName, cMaxStringLen ); } } // Sort the list so things are easier to find. Skip the first item, since it's the <none> selection. qsort( aszStrings + 1, *pcStrings - 1, sizeof(char *), CaseInsensitiveCompare ); return LT_OK; } // Handle team... else if( token == s_cTok_Team ) { TeamPopulateEditStringList( aszStrings, pcStrings, cMaxStrings, cMaxStringLen ); return LT_OK; } else if( token == s_cTok_ControlPointId ) { // Add an entry for each type. char szText[64]; for( uint8 nId = 1; nId <= MAX_CONTROLPOINT_OBJECTS; ++nId ) { LTASSERT( cMaxStrings > (*pcStrings) + 1, "Too many controlpoint types to fit in the list. Enlarge list size?" ); LTSNPrintF( szText, LTARRAYSIZE( szText ), "%d", nId ); if( (LTStrLen( szText ) < cMaxStringLen) && ((*pcStrings) + 1 < cMaxStrings) ) { LTStrCpy( aszStrings[(*pcStrings)++], szText, cMaxStringLen ); } } return LT_OK; } return LT_UNSUPPORTED; } // // NOTE TO INTEGRATIONS // // This function depends on the updates to PreHook_Dims made to the tools that will // not be propogated forward (changelist 59304). This will need to be updated to the new method upon integration. LTRESULT ControlPointPlugin::PreHook_Dims( const char* szRezPath, const char* szPropName, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector &vDims, const char* pszObjName, ILTPreInterface *pInterface) { if( LTStrIEquals( szPropName, "Type" )) { // Don't proceed without a value value. if( LTStrEmpty( szPropValue )) return LT_OK; // Get type used. HRECORD hRecord = DATABASE_CATEGORY( CPTypes ).GetRecordByName( szPropValue ); if( !hRecord ) return LT_UNSUPPORTED; // Get the prop used. HRECORD hProp = DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( hRecord, Prop ); if( !hProp ) return LT_UNSUPPORTED; // Get the model from the props category. const char *pszModel = g_pPropsDB->GetPropFilename( hProp ); if( !pszModel ) return LT_UNSUPPORTED; LTStrCpy( szModelFilenameBuf, pszModel, nModelFilenameBufLen ); } else if( LTStrIEquals( szPropName, "ZoneDims" )) { GenericProp genProp; if( pInterface->GetPropGeneric( pszObjName, "Type", &genProp ) != LT_OK ) return LT_UNSUPPORTED; szPropValue = genProp.GetString(); // Don't proceed without a value value. if( LTStrEmpty( szPropValue )) return LT_OK; // Get type used. HRECORD hRecord = DATABASE_CATEGORY( CPTypes ).GetRecordByName( szPropValue ); if( !hRecord ) return LT_UNSUPPORTED; // Get the prop used. HRECORD hProp = DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( hRecord, Prop ); if( !hProp ) return LT_UNSUPPORTED; // See if there are override dims for this instance. bool bGotOverrideDims = false; if( pInterface->GetPropGeneric( pszObjName, "ZoneDims", &genProp ) == LT_OK ) { LTVector const& vZoneDims = genProp.GetVector(); if( vZoneDims.x > 0.0f && vZoneDims.y > 0.0f && vZoneDims.z > 0.0f ) { bGotOverrideDims = true; vDims = vZoneDims; } } // See if we need to use the default dims. if( !bGotOverrideDims ) { vDims = DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( hRecord, DefaultZoneDims ); } } return LT_OK; } LTRESULT ControlPointPlugin::PreHook_PropChanged( const char *szObjName, const char *szPropName, const int nPropType, const GenericProp &gpPropValue, ILTPreInterface *pInterface, const char *szModifiers ) { // Only our command is marked for change notification so just send it to the CommandMgr.. if( m_CommandMgrPlugin.PreHook_PropChanged( szObjName, szPropName, nPropType, gpPropValue, pInterface, szModifiers ) == LT_OK ) { return LT_OK; } return LT_UNSUPPORTED; } // ----------------------------------------------------------------------- // // // ControlPointTouchMonitor // // Special class created by ControlPoint to monitor for touchnotifies. // // ----------------------------------------------------------------------- // class ControlPointTouchMonitor : public GameBase { public: // Accessors to controlpoint object. void SetControlPoint( HOBJECT hControlPoint ) { m_hControlPoint = hControlPoint; } HOBJECT GetControlPoint( ) const { return m_hControlPoint; } protected: // Methods... // Handle messages from the engine... uint32 EngineMessageFn( uint32 messageID, void *pData, float fData ); private: LTObjRef m_hControlPoint; }; // Special worker class for ControlPoint only. Used to receive // touch notifies. BEGIN_CLASS( ControlPointTouchMonitor ) END_CLASS_FLAGS( ControlPointTouchMonitor, GameBase, CF_DONTSAVE | CF_HIDDEN, "ControlPoint touchmonitor object for receiving touch notifies." ) // // ControlPoint class implementation... // // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::ControlPoint // // PURPOSE: Constructor... // // ----------------------------------------------------------------------- // ControlPoint::ControlPoint( ) : GameBase( OT_MODEL ) { m_pControlPointStateMachine = NULL; m_bMoveToFloor = true; m_hControlPointRec = NULL; m_nInitialTeamId = INVALID_TEAM; m_nControlPointId = CONTROLPOINT_INVALID_ID; m_vZoneDims.Init( ); m_pszTeam0NeutralizedControlCmd = NULL; m_pszTeam1NeutralizedControlCmd = NULL; m_pszTeam0CapturedControlCmd = NULL; m_pszTeam1CapturedControlCmd = NULL; // Add ourselves to the global list. m_lstControlPoints.push_back( this ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::~ControlPoint // // PURPOSE: Destructor... // // ----------------------------------------------------------------------- // ControlPoint::~ControlPoint( ) { if( m_pControlPointStateMachine ) { delete m_pControlPointStateMachine; m_pControlPointStateMachine = NULL; } if( m_hTouchMonitor ) { g_pLTServer->RemoveObject( m_hTouchMonitor ); m_hTouchMonitor = NULL; } // Clear out our controlpoint id from the allocated ones. if( m_nControlPointId != CONTROLPOINT_INVALID_ID ) { uint32 nControlPointBit = 1 << m_nControlPointId; m_nAllocatedControlPointIds &= ~nControlPointBit; } delete[] m_pszTeam0NeutralizedControlCmd; delete[] m_pszTeam1NeutralizedControlCmd; delete[] m_pszTeam0CapturedControlCmd; delete[] m_pszTeam1CapturedControlCmd; // Erase this instance from the list. TControlPointList::iterator it = std::find( m_lstControlPoints.begin( ), m_lstControlPoints.end( ), this ); if( it != m_lstControlPoints.end( )) { m_lstControlPoints.erase( it ); } } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::EngineMessageFn // // PURPOSE: Handle messages from the engine... // // ----------------------------------------------------------------------- // uint32 ControlPoint::EngineMessageFn( uint32 messageID, void *pData, float fData ) { switch(messageID) { case MID_PRECREATE: { uint32 dwRet = GameBase::EngineMessageFn( messageID, pData, fData ); ObjectCreateStruct* pStruct = (ObjectCreateStruct*)pData; if( fData == PRECREATE_WORLDFILE || fData == PRECREATE_STRINGPROP ) { if( !ReadProp( &pStruct->m_cProperties )) return 0; } if( !PostReadProp( pStruct )) return 0; return dwRet; } break; case MID_INITIALUPDATE: { uint32 dwRet = GameBase::EngineMessageFn( messageID, pData, fData ); if (fData != INITIALUPDATE_SAVEGAME) { InitialUpdate(); } return dwRet; } break; case MID_UPDATE: { Update( ); } break; default : break; } return GameBase::EngineMessageFn( messageID, pData, fData ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::ReadProp // // PURPOSE: Read in the properties of the object... // // ----------------------------------------------------------------------- // bool ControlPoint::ReadProp( const GenericPropList *pProps ) { char const* pszType = pProps->GetString( "Type", "" ); if( LTStrEmpty( pszType )) return false; m_hControlPointRec = DATABASE_CATEGORY( CPTypes ).GetRecordByName( pszType ); if( !m_hControlPointRec ) return false; GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // Don't allow CP's if this isn't CP game. if( !gameModeMgr.GetCPRulesRecord( )) return false; m_bMoveToFloor = pProps->GetBool( "MoveToFloor", m_bMoveToFloor ); const char *pszTeam = pProps->GetString( "Team", "" ); m_nInitialTeamId = TeamStringToTeamId( pszTeam ); const char *pszControlPointId = pProps->GetString( "ControlPointId", "" ); uint16 nControlPointId = ( uint16 )LTCLAMP( LTStrToLong( pszControlPointId ), 0, USHRT_MAX ); if( nControlPointId == CONTROLPOINT_INVALID_ID || nControlPointId > MAX_CONTROLPOINT_OBJECTS ) { LTERROR( "Invalid ControlPoint id" ); return false; } // Figure out what bit value this controlpoint id is. Make sure the id isn't already in use. // Control point id's must be unique. uint32 nControlPointBit = 1 << nControlPointId; if( m_nAllocatedControlPointIds & nControlPointBit ) { LTERROR( "ControlPoint id already used" ); return false; } // ControlPoint id checks out, we can use it. m_nControlPointId = nControlPointId; m_nAllocatedControlPointIds |= nControlPointBit; // Check if this object is overriding the zonedims. If not, then take the zone dims from the db. m_vZoneDims = pProps->GetVector( "ZoneDims", m_vZoneDims ); if( m_vZoneDims.x <= 0.0f || m_vZoneDims.y <= 0.0f || m_vZoneDims.z <= 0.0f ) { m_vZoneDims = DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_hControlPointRec, DefaultZoneDims ); } // Read in the commands for events. Note, team0 in code corresponds to team1 in worldedit. Team1 in // code corresponds to team2 in worldedit. delete[] m_pszTeam0NeutralizedControlCmd; m_pszTeam1NeutralizedControlCmd = LTStrDup( pProps->GetCommand( "Team0NeutralizedControlCmd", NULL )); delete[] m_pszTeam1NeutralizedControlCmd; m_pszTeam1NeutralizedControlCmd = LTStrDup( pProps->GetCommand( "Team1NeutralizedControlCmd", NULL )); delete[] m_pszTeam0CapturedControlCmd; m_pszTeam0CapturedControlCmd = LTStrDup( pProps->GetCommand( "Team0CapturedControlCmd", NULL )); delete[] m_pszTeam1CapturedControlCmd; m_pszTeam1CapturedControlCmd = LTStrDup( pProps->GetCommand( "Team1CapturedControlCmd", NULL )); return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::PostReadProp // // PURPOSE: Configure the ObjectCreateStruct for creating the object // // ----------------------------------------------------------------------- // bool ControlPoint::PostReadProp( ObjectCreateStruct *pStruct ) { // Get the prop used. HRECORD hProp = DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_hControlPointRec, Prop ); if( !hProp ) return false; // Fill in the model and material names. char const* pszPropFilename = g_pPropsDB->GetPropFilename( hProp ); if( LTStrEmpty( pszPropFilename )) return false; LTStrCpy( pStruct->m_Filename, pszPropFilename, LTARRAYSIZE( pStruct->m_Filename )); g_pPropsDB->CopyMaterialFilenames( hProp, pStruct->m_Materials[0], LTARRAYSIZE( pStruct->m_Materials ), LTARRAYSIZE( pStruct->m_Materials[0] )); // Make the object visible. pStruct->m_Flags |= FLAG_VISIBLE; // Turn on solid flag if desired. if( DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_hControlPointRec, Solid )) { pStruct->m_Flags |= ( FLAG_SOLID | FLAG_RAYHIT ); } return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::InitialUpdate // // PURPOSE: Handle a MID_INITIALUPDATE message from the engine.... // // ----------------------------------------------------------------------- // void ControlPoint::InitialUpdate( ) { // Set the model diminsions... LTVector vDims; HMODELANIM hAnim = INVALID_MODEL_ANIM; g_pModelLT->GetCurAnim( m_hObject, MAIN_TRACKER, hAnim ); g_pModelLT->GetModelAnimUserDims (m_hObject, hAnim, &vDims); g_pPhysicsLT->SetObjectDims( m_hObject, &vDims, 0 ); // Make sure object starts on floor if the flag is set... if( m_bMoveToFloor ) { MoveObjectToFloor( m_hObject ); } // Create the touchmonitor. CreateTouchMonitor( ); // Set the collisionproperty. HRECORD hCollisionPropertyRec = DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_hControlPointRec, CollisionProperty ); if( hCollisionPropertyRec ) { uint32 nUserFlags = CollisionPropertyRecordToUserFlag( hCollisionPropertyRec ); g_pLTServer->Common( )->SetObjectFlags( m_hObject, OFT_User, nUserFlags, USRFLG_COLLISIONPROPMASK ); } // Set the surface type. HSURFACE hSurfaceRec = DATABASE_CATEGORY( CPTypes ).GETRECORDATTRIB( m_hControlPointRec, SurfaceType ); if( hSurfaceRec ) { SurfaceType eSurfType = g_pSurfaceDB->GetSurfaceType(hSurfaceRec); uint32 dwSurfUsrFlgs = SurfaceToUserFlag(eSurfType); g_pCommonLT->SetObjectFlags(m_hObject, OFT_User, dwSurfUsrFlgs, USRFLG_SURFACEMASK); } // Create our statemachine object. LT_MEM_TRACK_ALLOC(m_pControlPointStateMachine = new ControlPointStateMachine, LT_MEM_TYPE_GAMECODE); m_pControlPointStateMachine->Init( *this ); // Start off based on initial team. EControlPointState eInitialState; switch( m_nInitialTeamId ) { case 0: eInitialState = kControlPointState_Team0; break; case 1: eInitialState = kControlPointState_Team1; break; default: eInitialState = kControlPointState_Neutral; break; } m_pControlPointStateMachine->SetState( eInitialState, NULL ); CreateSpecialFX( false ); // Don't need updates unless we're getting captured. SetNextUpdate( UPDATE_NEVER ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::Update // // PURPOSE: Handle a MID_UPDATE message from the engine.... // // ----------------------------------------------------------------------- // void ControlPoint::Update( ) { if( !m_pControlPointStateMachine ) return; // Update the statemachine. m_pControlPointStateMachine->Update(); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::CreateSpecialFX // // PURPOSE: Send relevant information to clients... // // ----------------------------------------------------------------------- // void ControlPoint::CreateSpecialFX( bool bUpdateClients ) { if( !m_pControlPointStateMachine ) return; CONTROLPOINTCREATESTRUCT cs; cs.m_eControlPointState = ( EControlPointState )m_pControlPointStateMachine->GetState( ); cs.m_hControlPointRec = m_hControlPointRec; cs.m_nControlPointId = m_nControlPointId; cs.m_vZoneDims = m_vZoneDims; { CAutoMessage cMsg; cMsg.Writeuint8( SFX_CONTROLPOINT_ID ); cs.Write( cMsg ); g_pLTServer->SetObjectSFXMessage( m_hObject, cMsg.Read( )); } } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::CreateTouchMonitor // // PURPOSE: Creates a touch monitor object to receive MID_TOUCHNOTIFY's. // // ----------------------------------------------------------------------- // bool ControlPoint::CreateTouchMonitor( ) { HCLASS hClass = g_pLTServer->GetClass("ControlPointTouchMonitor"); if( !hClass ) return false; // Create the object to monitor for touches. ObjectCreateStruct theStruct; g_pLTServer->GetObjectPos( m_hObject, &theStruct.m_Pos ); g_pLTServer->GetObjectRotation( m_hObject, &theStruct.m_Rotation ); theStruct.m_UserData = reinterpret_cast< uint32 >( m_hObject ); GameBase* pTouchMonitor = ( GameBase* )g_pLTServer->CreateObject( hClass, &theStruct ); if( !pTouchMonitor ) return false; m_hTouchMonitor = pTouchMonitor->m_hObject; return true; } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::OnTouched // // PURPOSE: Called by the touch monitor object. // // ----------------------------------------------------------------------- // void ControlPoint::OnTouched( HOBJECT hToucher ) { if( !m_pControlPointStateMachine ) return; // Make sure this is a character. Other objects are not tracked. CCharacter* pCharacter = CCharacter::DynamicCast( hToucher ); if( !pCharacter ) return; // Relay the touch event to the statemachine. m_pControlPointStateMachine->DoTouchEvent( hToucher ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::CheckForConquestWin // // PURPOSE: Checks for acheiving conquest win. Happens when all CP's are owned // by one team. // // ----------------------------------------------------------------------- // void ControlPoint::CheckForConquestWin( ) { // Check if end round condition already met. if( g_pServerMissionMgr->IsEndRoundConditionMet( )) return; GameModeMgr& gameModeMgr = GameModeMgr::Instance(); // Conquest win not an option. if( !gameModeMgr.m_grbCPConquestWin ) return; // Make sure we have some control points. uint32 nNumControlPoints = m_lstControlPoints.size( ); if( nNumControlPoints == 0 ) return; // Iterate through the control points and count the number controlled by each team. uint32 nNumTeam0 = 0; uint32 nNumTeam1 = 0; for( TControlPointList::iterator iter = m_lstControlPoints.begin( ); iter != m_lstControlPoints.end( ); iter++ ) { ControlPoint* pControlPoint = *iter; if( !pControlPoint->m_pControlPointStateMachine ) continue; switch( pControlPoint->m_pControlPointStateMachine->GetTeamId()) { case kTeamId0: nNumTeam0++; break; case kTeamId1: nNumTeam1++; break; } } // See if either team one. ETeamId eWinningTeam = INVALID_TEAM; if( nNumTeam0 == nNumControlPoints ) { eWinningTeam = kTeamId0; } else if( nNumTeam1 == nNumControlPoints ) { eWinningTeam = kTeamId1; } else { // Neither team has reached conquest. return; } // Set the winner. g_pServerMissionMgr->SetTeamWon( eWinningTeam ); g_pServerMissionMgr->SetEndRoundCondition( GameModeMgr::eEndRoundCondition_Conquest ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPoint::GetPrefetchResourceList // // PURPOSE: Determines the list of all needed resources // // ----------------------------------------------------------------------- // void ControlPoint::GetPrefetchResourceList(const char* pszObjectName, IObjectResourceGatherer* pInterface, ResourceList& Resources ) { // get the CP record char szType[256]; pInterface->GetPropString(pszObjectName, "Type", szType, LTARRAYSIZE(szType), NULL); if( LTStrEmpty( szType )) return; HRECORD hControlPointRec = DATABASE_CATEGORY( CPTypes ).GetRecordByName( szType ); if( !hControlPointRec ) return; GetRecordResources( Resources, hControlPointRec, true ); } // ----------------------------------------------------------------------- // // // ROUTINE: ControlPointTouchMonitor::EngineMessageFn // // PURPOSE: Handle messages from the engine... // // ----------------------------------------------------------------------- // uint32 ControlPointTouchMonitor::EngineMessageFn( uint32 messageID, void *pData, float fData ) { switch(messageID) { case MID_PRECREATE: { uint32 dwRet = GameBase::EngineMessageFn( messageID, pData, fData ); ObjectCreateStruct* pStruct = (ObjectCreateStruct*)pData; // Need to get touch notifies to send to the ControlPoint. pStruct->m_Flags |= FLAG_TOUCH_NOTIFY; // Remember our parent controlpoint. SetControlPoint( reinterpret_cast< HOBJECT >( pStruct->m_UserData )); return dwRet; } break; case MID_INITIALUPDATE: { uint32 dwRet = GameBase::EngineMessageFn( messageID, pData, fData ); ControlPoint* pControlPoint = static_cast< ControlPoint* >( g_pLTServer->HandleToObject( GetControlPoint( ))); if( pControlPoint ) { // Set our object dims. LTVector vDims = pControlPoint->GetZoneDims( ); g_pLTServer->Physics()->SetObjectDims( m_hObject, &vDims, 0 ); } return dwRet; } break; case MID_TOUCHNOTIFY: { uint32 dwRet = GameBase::EngineMessageFn( messageID, pData, fData ); ControlPoint* pControlPoint = static_cast< ControlPoint* >( g_pLTServer->HandleToObject( m_hControlPoint )); if( pControlPoint ) { // Give our parent object the touch. HOBJECT hToucher = reinterpret_cast< HOBJECT >( pData ); pControlPoint->OnTouched( hToucher ); } return dwRet; } break; default : break; } return GameBase::EngineMessageFn( messageID, pData, fData ); }
412
0.982912
1
0.982912
game-dev
MEDIA
0.935466
game-dev
0.732873
1
0.732873
ConsideredHamster/YetAnotherPixelDungeon
9,237
app/src/main/java/com/consideredhamster/yetanotherpixeldungeon/visuals/ui/StatusPane.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Yet Another Pixel Dungeon * Copyright (C) 2015-2016 Considered Hamster * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.consideredhamster.yetanotherpixeldungeon.visuals.ui; import com.consideredhamster.yetanotherpixeldungeon.YetAnotherPixelDungeon; import com.watabou.input.Touchscreen.Touch; import com.watabou.noosa.BitmapText; import com.watabou.noosa.Camera; import com.watabou.noosa.Image; import com.watabou.noosa.NinePatch; import com.watabou.noosa.TouchArea; import com.watabou.noosa.audio.Sample; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.ui.Button; import com.watabou.noosa.ui.Component; import com.consideredhamster.yetanotherpixeldungeon.visuals.Assets; import com.consideredhamster.yetanotherpixeldungeon.Dungeon; import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.Speck; import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.particles.BloodParticle; import com.consideredhamster.yetanotherpixeldungeon.items.keys.IronKey; import com.consideredhamster.yetanotherpixeldungeon.scenes.GameScene; import com.consideredhamster.yetanotherpixeldungeon.scenes.PixelScene; import com.consideredhamster.yetanotherpixeldungeon.visuals.sprites.HeroSprite; import com.consideredhamster.yetanotherpixeldungeon.visuals.windows.WndGame; import com.consideredhamster.yetanotherpixeldungeon.visuals.windows.WndHero; public class StatusPane extends Component { private NinePatch shield; private Image difficulty; private Image avatar; // private Emitter blood; private int lastTier = 0; private int bottom = 0; private Image hp; private Image exp; private int lastLvl = -1; private int lastKeys = -1; private BitmapText health; private BitmapText level; private BitmapText depth; private BitmapText keys; private TagDanger danger; private TagAttack attack; private TagPickup pickup; private TagResume resume; private BuffIndicator buffs; private Compass compass; private TagWaterskin btnWaterskin; private TagOilLantern btnOilLantern; private MenuButton btnMenu; public StatusPane( int bottom ) { super(); this.bottom = bottom; } @Override protected void createChildren() { shield = new NinePatch( Assets.STATUS, 80, 0, 48, 0 ); add( shield ); add( new TouchArea( 0, 1, 30, 30 ) { @Override protected void onClick( Touch touch ) { Image sprite = Dungeon.hero.sprite; if (!sprite.isVisible()) { Camera.main.focusOn( sprite ); } GameScene.show( new WndHero() ); }; } ); btnMenu = new MenuButton(); add( btnMenu ); difficulty = new IconDifficulty(); add(difficulty); avatar = HeroSprite.avatar( Dungeon.hero.heroClass, lastTier ); add(avatar); // blood = new Emitter(); // blood.pos(avatar); // blood.pour(BloodParticle.FACTORY, 0.3f); // blood.autoKill = false; // blood.on = false; // addFromDamage(blood); compass = new Compass( Dungeon.level.exit ); add( compass ); hp = new Image( Assets.HP_BAR ); add( hp ); exp = new Image( Assets.XP_BAR ); add(exp); level = new BitmapText( PixelScene.font1x ); level.hardlight(0xFFEBA4); add(level); health = new BitmapText( PixelScene.font1x ); health.hardlight(0xCACFC2); add(health); depth = new BitmapText( Integer.toString( Dungeon.depth ), PixelScene.font1x ); depth.hardlight(0xCACFC2); depth.measure(); add( depth ); Dungeon.hero.belongings.countIronKeys(); keys = new BitmapText( PixelScene.font1x ); keys.hardlight(0xCACFC2); add(keys); danger = new TagDanger(); add(danger); attack = new TagAttack(); add( attack ); pickup = new TagPickup(); add(pickup); resume = new TagResume(); add( resume ); btnWaterskin = new TagWaterskin(); add(btnWaterskin); btnOilLantern = new TagOilLantern(); add(btnOilLantern); buffs = new BuffIndicator( Dungeon.hero ); add( buffs ); } @Override protected void layout() { height = 32; shield.size( width, shield.height ); avatar.x = PixelScene.align( camera(), shield.x + 15 - avatar.width / 2 ); avatar.y = PixelScene.align( camera(), shield.y + 16 - avatar.height / 2 ); compass.x = avatar.x + avatar.width / 2 - compass.origin.x; compass.y = avatar.y + avatar.height / 2 - compass.origin.y; hp.x = 30; hp.y = 3; depth.x = width - 24 - depth.width() - 18; depth.y = 6; keys.y = 6; layoutTags( bottom ); // if( YetAnotherPixelDungeon.buttons() ){ btnWaterskin.setPos( 0, height + 2 ); btnOilLantern.setPos( 0, btnWaterskin.bottom() + 2 ); // } else { // btnWaterskin.setPos( width - btnWaterskin.width(), height + 10 ); // btnOilLantern.setPos( width - btnOilLantern.width(), btnWaterskin.bottom() + 3 ); // } buffs.setPos( 32, 11 ); btnMenu.setPos( width - btnMenu.width(), 1 ); difficulty.x = btnMenu.left() + btnMenu.width() / 2 - difficulty.width() / 2; difficulty.y = btnMenu.bottom() + 2; } private void layoutTags( int bottom ) { float pos = bottom - 1; if (tagDanger) { danger.setPos( width - danger.width(), pos - danger.height() ); pos = danger.top() - 1; } if (tagAttack) { attack.setPos( width - attack.width(), pos - attack.height() ); pos = attack.top() - 1; } if (tagPickup) { pickup.setPos( width - pickup.width(), pos - pickup.height() ); pos = pickup.top() - 1; } if (tagResume) { resume.setPos( width - resume.width(), pos - resume.height() ); } } private boolean tagDanger = false; private boolean tagAttack = false; private boolean tagPickup = false; private boolean tagResume = false; @Override public void update() { super.update(); if ( tagDanger != danger.visible || tagAttack != attack.visible || tagPickup != pickup.visible || tagResume != resume.visible ) { tagDanger = danger.visible; tagAttack = attack.visible; tagPickup = pickup.visible; tagResume = resume.visible; layoutTags( bottom ); } float health_percent = (float)Dungeon.hero.HP / Dungeon.hero.HT; if (health_percent == 0) { avatar.tint( 0x000000, 0.6f ); // blood.on = false; // } else if (health_percent < 0.25f) { // avatar.tint( 0xcc0000, 0.4f ); // blood.on = true; } else { avatar.resetColorAlpha(); // blood.on = false; } hp.scale.x = health_percent; exp.scale.x = (width / exp.width) * Dungeon.hero.exp / Dungeon.hero.maxExp(); if (Dungeon.hero.lvl != lastLvl) { if (lastLvl != -1) { Emitter emitter = (Emitter)recycle( Emitter.class ); emitter.revive(); emitter.pos( 26, 26 ); emitter.burst( Speck.factory( Speck.STAR ), 12 ); } lastLvl = Dungeon.hero.lvl; level.text( Integer.toString( lastLvl ) ); level.measure(); level.x = PixelScene.align( 26.0f - level.width() / 2 ); level.y = PixelScene.align( 26.5f - level.baseLine() / 2 ); } health.text( String.format( "%d/%d", Dungeon.hero.HP, Dungeon.hero.HT ) ); health.measure(); health.x = PixelScene.align( 53.0f - health.width() / 2 ); health.y = PixelScene.align( 4.0f - health.baseLine() / 2 ); health.alpha( 0.5f ); int k = IronKey.curDepthQuantity; if (k != lastKeys) { lastKeys = k; keys.text(Integer.toString(lastKeys)); keys.measure(); keys.x = width - 8 - keys.width() - 18; } int tier = Dungeon.hero.appearance(); if (tier != lastTier) { lastTier = tier; avatar.copy( HeroSprite.avatar( Dungeon.hero.heroClass, tier ) ); } } private static class MenuButton extends Button { private Image image; public MenuButton() { super(); width = image.width + 4; height = image.height + 4; } @Override protected void createChildren() { super.createChildren(); image = new Image( Assets.STATUS, 114, 3, 12, 11 ); add( image ); } @Override protected void layout() { super.layout(); image.x = x + 2; image.y = y + 2; } @Override protected void onTouchDown() { image.brightness( 1.5f ); Sample.INSTANCE.play( Assets.SND_CLICK ); } @Override protected void onTouchUp() { image.resetColorAlpha(); } @Override protected void onClick() { GameScene.show( new WndGame() ); } } }
412
0.935506
1
0.935506
game-dev
MEDIA
0.977801
game-dev
0.9958
1
0.9958
ForeignGods/Animated-Line-Renderer
1,697
Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Editor/TMP_StyleAssetMenu.cs
using UnityEngine; using UnityEditor; using System.IO; using System.Collections; namespace TMPro.EditorUtilities { public static class TMP_StyleAssetMenu { [MenuItem("Assets/Create/TextMeshPro/Style Sheet", false, 120)] public static void CreateTextMeshProObjectPerform() { string filePath; if (Selection.assetGUIDs.Length == 0) { // No asset selected. filePath = "Assets"; } else { // Get the path of the selected folder or asset. filePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]); // Get the file extension of the selected asset as it might need to be removed. string fileExtension = Path.GetExtension(filePath); if (fileExtension != "") { filePath = Path.GetDirectoryName(filePath); } } string filePathWithName = AssetDatabase.GenerateUniqueAssetPath(filePath + "/Text StyleSheet.asset"); //// Create new Style Sheet Asset. TMP_StyleSheet styleSheet = ScriptableObject.CreateInstance<TMP_StyleSheet>(); // Create Normal default style TMP_Style style = new TMP_Style("Normal", string.Empty, string.Empty); styleSheet.styles.Add(style); AssetDatabase.CreateAsset(styleSheet, filePathWithName); EditorUtility.SetDirty(styleSheet); AssetDatabase.SaveAssets(); EditorUtility.FocusProjectWindow(); EditorGUIUtility.PingObject(styleSheet); } } }
412
0.790227
1
0.790227
game-dev
MEDIA
0.858453
game-dev
0.645677
1
0.645677
asiekierka/FoamFix
4,925
src/main/java/pl/asie/foamfix/client/FoamFixModelRegistryDuplicateWipe.java
/** * Copyright (C) 2016, 2017, 2018, 2019, 2020, 2021 Adrian Siekierka * * This file is part of FoamFix. * * FoamFix 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. * * FoamFix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FoamFix. If not, see <http://www.gnu.org/licenses/>. */ /** * This file is part of FoamFixAPI. * * FoamFixAPI 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. * * FoamFixAPI 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 FoamFixAPI. If not, see <http://www.gnu.org/licenses/>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with the Minecraft game engine, the Mojang Launchwrapper, * the Mojang AuthLib and the Minecraft Realms library (and/or modified * versions of said software), containing parts covered by the terms of * their respective licenses, the licensors of this Program grant you * additional permission to convey the resulting work. */ package pl.asie.foamfix.client; import gnu.trove.map.hash.TIntObjectHashMap; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BlockModelShapes; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelManager; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.ItemModelMesherForge; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.registries.IRegistryDelegate; import pl.asie.foamfix.FoamFix; import pl.asie.foamfix.ProxyClient; import java.lang.reflect.Field; import java.util.Map; public class FoamFixModelRegistryDuplicateWipe { @SubscribeEvent public void onTextureStitchPost(TextureStitchEvent.Post event) { ItemModelMesher imm = Minecraft.getMinecraft().getRenderItem().getItemModelMesher(); BlockModelShapes bms = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes(); ModelManager mgr = bms.getModelManager(); Field f = ObfuscationReflectionHelper.findField(ModelManager.class, "field_174958_a"); try { IRegistry<ModelResourceLocation, IBakedModel> registry = (IRegistry<ModelResourceLocation, IBakedModel>) f.get(mgr); FoamFix.getLogger().info("Clearing unnecessary model registry of size " + registry.getKeys().size() + "."); for (ModelResourceLocation l : registry.getKeys()) { registry.putObject(l, ProxyClient.DUMMY_MODEL); } } catch (Exception e) { e.printStackTrace(); } f = ObfuscationReflectionHelper.findField(BlockModelShapes.class, "field_178129_a"); try { Map<IBlockState, IBakedModel> modelStore = (Map<IBlockState, IBakedModel>) f.get(bms); FoamFix.getLogger().info("Clearing unnecessary model store of size " + modelStore.size() + "."); modelStore.clear(); } catch (Exception e) { e.printStackTrace(); } if (imm instanceof ItemModelMesherForge) { f = ReflectionHelper.findField(ItemModelMesherForge.class, "models"); try { Map<IRegistryDelegate<Item>, TIntObjectHashMap<IBakedModel>> modelStore = (Map<IRegistryDelegate<Item>, TIntObjectHashMap<IBakedModel>>) f.get(imm); FoamFix.getLogger().info("Clearing unnecessary item shapes cache of size " + modelStore.size() + "."); modelStore.clear(); } catch (Exception e) { e.printStackTrace(); } } } }
412
0.725757
1
0.725757
game-dev
MEDIA
0.842772
game-dev,graphics-rendering
0.730353
1
0.730353
DISTRHO/DISTRHO-Ports
1,253
ports-juce6.0/vitalium/source/interface/wavetable/wavetable_playhead_info.cpp
/* Copyright 2013-2019 Matt Tytel * * vital 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. * * vital 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 vital. If not, see <http://www.gnu.org/licenses/>. */ #include "wavetable_playhead_info.h" #include "skin.h" void WavetablePlayheadInfo::paint(Graphics& g) { g.fillAll(findColour(Skin::kBody, true)); String position_text(playhead_position_); g.setColour(findColour(Skin::kBodyText, true)); Rectangle<int> bounds = getLocalBounds(); bounds.setWidth(bounds.getWidth() - bounds.getHeight() * 0.5f); g.drawText(position_text, bounds, Justification::centredRight ); } void WavetablePlayheadInfo::resized() { repaint(); } void WavetablePlayheadInfo::playheadMoved(int position) { playhead_position_ = position; repaint(); }
412
0.789936
1
0.789936
game-dev
MEDIA
0.748656
game-dev,graphics-rendering
0.599469
1
0.599469
chipwits/chipwits-forth
59,485
c64/forth/Joystick + Menu Bak.forth
════════════════════════════════════════ SCREEN 001 ( JOYSTICK MENU LOAD SCREEN) ( START FORTH INTERRUPT) 172 175 THRU ( VARS & SPRITE) G.M.I ( CHAR.COPY) 180 189 THRU ( JOYSTICK STUFF) 200 207 THRU ( MENU STUFF) 250 254 THRU ( MENU TEST) 260 LOAD ( FRAME) 279 284 THRU ( MACHINE LANG PROGS) FORTH A-REMOVE : IT ; ( 320 329 GAME & WORKSHOP SCREENS) ( 310 -311 ARE SCENARIO SAVERS) ════════════════════════════════════════ SCREEN 002 ( CURSOR VARS) VARIABLE B.D 0 B.D ! ( BUTTON.DOWN) VARIABLE B.X ( BUTTON DOWN POS) VARIABLE B.Y 0 B.Y ! 0 B.X ! EXIT ════════════════════════════════════════ SCREEN 003 ( CURS.SPR) EXIT 2 BASE ! S-DEF CURS.SPR 11111111 11110000 00000000 11111111 11100000 00000000 11111111 11000000 00000000 11111111 10000000 00000000 11111111 10000000 00000000 11111111 11000000 00000000 11111111 11100000 00000000 11111111 11110000 00000000 11110011 11111000 00000000 11100001 11111100 00000000 11000000 11111110 00000000 00000000 01111110 00000000 00000000 00111100 00000000 00000000 00011000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 DECIMAL ════════════════════════════════════════ SCREEN 004 ( GRAPH.MEM.INITGRAPH.LOAD,SET M.BAK1,2) : G.M.I ( ---^GRAPH.MEM.INIT) 3 BANK 3 SCREEN 3 16 * 4 + 53272 C! ( OUT TO 0 SCR) 204 648 C! ( SCR 192 * 256) 147 EMIT ( CLEAR SCREEN) 7 CHARBASE ; : GR.LD ( ---^GRAPH.LOAD) 63488 96 8 * - " CW.CHR" LR 57344 " CW.SPR" LR ; : M.BAK1 ( COLOR---^SET MULTI CLR1) 53282 C! ; : M.BAK2 ( COLOR---) 53283 C! ; EXIT : CHAR.COPY ( ---) 56334 C@ 254 AND 56334 C! 1 C@ 251 AND 1 C! 53248 61440 4096 CMOVE 1 C@ 4 OR 1 C! 56334 C@ 1 OR 56334 C! ; ════════════════════════════════════════ SCREEN 005 ( CHAR.COLOR COLOR ASSIGNMENTS) : CHAR.COLOR ( COLOR---) ( SWITCHES CHARACTER COLORS) CASE B% OF ." {$90}" ;; W% OF ." " ;; R% OF ." " ;; C% OF ." {$9F}" ;; P% OF ." {$9C}" ;; G% OF ." " ;; BL% OF ." " ;; Y% OF ." {$9E}" ;; O% OF ." {$81}" ;; BR% OF ." {$95}" ;; LR% OF ." {$96}" ;; DG% OF ." {$97}" ;; MG% OF ." {$98}" ;; LG% OF ." {$99}" ;; LB% OF ." {$9A}" ;; GL% OF ." {$9B}" ;; ENDCASE ; ════════════════════════════════════════ SCREEN 007 ( CODE TEST FOR JS OR KOALA) DECIMAL DP @ 1024 DP ! 0 C, HEX CREATE <T> ASSEMBLER PA@ STA, ( TRIGGER PADDLE) 80 # LDY, ( WAIT) BEGIN, NOP, DEY, 0= UNTIL, DECIMAL SID@ 25 + LDX, INX, 0= NOT IF, SID@ 26 + LDX, INX, HEX 0= NOT IF, 400 STA, THEN, THEN, RTS, CREATE <J?> XSAVE STX, PHP, SEI, ( DISABLE INTERRUPTS) PA@ LDA, PHA, CA@ LDA, PHA, ( SAVE POR VALUES FOR KBD) C0 # LDA, CA@ STA, ( DDR FOR PADDLE) 0 # LDA, 400 STA, ( CLEAR FLAG) 80 # LDA, ' <T> JSR, ( PORT ONE?) 40 # LDA, ' <T> JSR, PLA, CA@ STA, PLA, PA@ STA, ( PORT) PLP, XSAVE LDX, RTS, DECIMAL HERE DUP . ." END" CR DP ! ' <J?> . ." ' <J?> " 0 SAVENAME C! SAVENAME " @0:JS" $CONCAT 1024 SWAP SAVE ════════════════════════════════════════ SCREEN 008 ( <B.D> BUTTON DOWN SUB) HEX CREATE <B.D> ASSEMBLER 1 # LDA, B.D STA, ( TURN ON VAR) D001 LDA, ( SPR0 Y) B.Y STA, D000 LDA, ( SPR0 X LO) B.X STA, D010 LDA, ( SPR0 X HI) B.X 1+ STA, RTS, DECIMAL FORTH ════════════════════════════════════════ SCREEN 009 ( SV.SP R.SP 1OFF) VARIABLE SP^ : SV.SP ( ---^ SAVE SPRITES) 53269 C@ SP^ C! ; : R.SP ( ---^RESTORE SPRITES) SP^ C@ 53269 C! ; ════════════════════════════════════════ SCREEN 010 ( PT.IN.RECT) : PT.RCT ( LCRX/RX/TY/BY/PTX/PTY--FLAG) ( DETERMINE IF PT IS IN RECTANGLE) ( RECT COORD IN CHARACTER SCALE) SWAP >R 50 - 8 / ( Y IN CHAR COORDS) DUP ROT > ( LX/RX/TY/PTY/F) ROT ROT > OR NOT ( IN Y RANGE) IF R> 24 - 8 / ( X IN CHAR COORDS) DUP ROT > ( LX/PTX/F) ROT ROT > OR NOT ( IN X RANGE) IF 1 ELSE 0 THEN ELSE R> DROP DDROP 0 THEN ; ════════════════════════════════════════ SCREEN 011 ( JOY.READ VARS) 51 CONSTANT J.T ( JOY TOP) 235 CONSTANT J.B ( BOT) 25 CONSTANT J.L ( LEFT) 329 CONSTANT J.R ( RIGHT) J.R 256 - CONSTANT J.LO ( LOW BYTE) CREATE PD 1 ALLOT ( 0=JST 40,80 KOALA) HEX DC00 CONSTANT PA@ ( PORTA) DC02 CONSTANT CA@ ( CIDDRA) D400 CONSTANT SID@ DECIMAL EXIT FILE " JS" IS LOADED INTO RAM AT 1024 AND THE J? WORD WILL JUMP TO IT ════════════════════════════════════════ SCREEN 012 ( J? <KOAL>) DECIMAL CODE J? ( LOADS IN PADDLE CHECKER CODE) 1067 JSR, 1024 LDA, PD STA, NEXT JMP, END-CODE HEX CREATE TP 1 ALLOT CREATE <KOAL> ASSEMBLER ( PHP, SEI, ( DISABLE INTERRUPTS) PA@ LDA, PHA, CA@ LDA, PHA, ( SAVE KEYBOARD) C0 # LDA, CA@ STA, ( DDR) PD LDA, PA@ STA, ( TRIGGER RIGHT PAD) 80 # LDY, ( WAIT) BEGIN, NOP, DEY, 0= UNTIL, SID@ 19 + LDA, ( X VALUE) TP STA, .A LSR, .A LSR, CLC, TP ADC, ( MULTI BY 1.25) D000 STA, ( SET X.LO) 0 # LDA, .A ROL, TP STA, D010 LDA, FE # AND, TP ORA, D010 STA, ( SET X HI) ════════════════════════════════════════ SCREEN 013 ( <KOAL> CONT) HEX SID@ 1A + LDA, ( GET Y) D001 STA, PA@ LDA, PA@ 1+ AND, ( READ BOTH BUTTONS) 0C # AND, ( BITS 3,4) C # CMP, 0= NOT IF, ' <B.D> JSR, THEN, ( CARRY WILL INDICATE BUTTON ON) PLA, CA@ STA, PLA, PA@ STA, RTS, FORTH DECIMAL ════════════════════════════════════════ SCREEN 014 ( MACHINE LANG READ.JOY) HEX CODE R.JOY D019 LDA, ( GET INTERRUPT FLAGS) 1 # AND, 0= ( RASTER INTERRUPT?) IF, ' I-SYSTEM JMP, ( EXIT TO SYS) ELSE, ( MY INTERRUPT) D019 STA, ( CLEAR IT) 0 # LDX, B.D STX, ( CLEAR) PD LDA, 0 # CMP, 0= NOT IF, ' <KOAL> JSR, ELSE, DC00 LDA, 7F # CMP, ( 7F = NO JOY) 0= NOT IF, ( JOY ACTIVE) .A LSR, ( UP TEST) CS NOT IF, ( UP BUTTON) D001 LDY, ( GRAB SPR0 Y) J.T # CPY, ( AT TOP?) 0= NOT IF, DEY, DEY, THEN, ( NO) D001 STY, ( NEW SPR0 Y) THEN, .A LSR, ( DOWN TEST) CS NOT IF, ( DOWN THROWN) D001 LDY, ( GET SPR0 Y) J.B # CPY, ( AT BOT?) 0= NOT IF, INY, INY, THEN, ( NO) D001 STY, THEN, ════════════════════════════════════════ SCREEN 015 ( MACHINE READ.JOY CONT.D) .A LSR, ( LEFT.TEST) CS NOT IF, D010 LDX, D000 LDY, ( SPR0 X H/L) 1 # CPX, 0= NOT IF, ( SPR0<255) J.L # CPY, ( LEFT EDGE?) 0= IF, INY, INY, THEN, ( BACK) THEN, DEY, DEY, FF # CPY, ( CROSS SEAM) 0= IF, D010 DEC, THEN, D000 STY, ( NEW SPR0 X) THEN, .A LSR, ( RIGHT TEST) CS NOT IF, ( RIGHT BUTTON) D010 LDX, D000 LDY, 1 # CPX, ( SPR0 >255?) 0= IF, ( YES) J.LO # CPY, ( RT EDGE?) 0= IF, DEY, DEY, THEN, ( BACK) THEN, INY, INY, 1 # CPY, ( MOVE RIGHT) 0= IF, D010 INC, THEN, ( SPR0 HI) ( IF 1 THEN INC HI BIT) D000 STY, THEN, ════════════════════════════════════════ SCREEN 016 ( MACHINE READ.JOY END) .A LSR, CS NOT ( FIRE BUTTON PUSHED?) IF, ' <B.D> JSR, THEN, THEN, ( JOY STICK ACTIVE) THEN, ( BACK FROM KOALA?) THEN, ' BNC# LDA, 0= NOT IF, ( YES BOUNCER) ' GAME.STATUS LDA, 0= IF, ( NO DBG) A2 LDA, ( READ JIFFY TIMER) 6 # CMP, CS IF, ( 1/2 SECOND) ' <SPIN.B> JSR, 0 # LDA, A2 STA, THEN, THEN, THEN, ' I-USER JMP, ( NO SYS INTERRUPT) END-CODE DECIMAL ════════════════════════════════════════ SCREEN 017 ( MACHINE JOY.TEST) EXIT <<< S1 ON S-ENABLE 100 100 S-POSITION : JOY.TEST 10000 0 DO 100 0 DO READ.JOY LOOP LOOP ; : JOY.TIMER ( ---) 0. SETTIM 30000 0 DO LOOP RDTIM DROP 6 / . ." 30000 EMPTY LOOP" CR 0. SETTIM 30000 0 DO LOOP RDTIM DROP 6 / . ." 30000 EMPT LOOP" CR ; ════════════════════════════════════════ SCREEN 018 ( I-JOY) : I-T ( ---^RESTORE INTERRUPT) 251 53266 C! ( RASTER INT LO BYTE) 56334 C@ 254 AND 56334 C! ' R.JOY 6 I-SET 53274 0 MASK SBIT ( ENABLE RAST INT) 56334 C@ 1 OR 56334 C! 53265 7 MASK CBIT ( CLEAR HI BIT) ; : I-JOY ( ---) ( SET UP CURSOR JOYSTICK INTERRUPT) 788 @ 59953 = IF I-INIT THEN ( FORTH IRQ ROTUINE SETUP) ( -12352 CURS.SPR ( PUT CURSOR GR) S1 184 S-PT ON S-ML J.L J.T S-POSITION DG% S-C W% 1 S-M ON S-ENABLE I-T ; ════════════════════════════════════════ SCREEN 019 ( BUT.XY@) CODE BUT.XY@ ( ---BUTX/BUTY) ' B.X LDA, DEX, DEX, BOT STA, ' B.X 1+ LDA, BOT 1+ STA, ' B.Y LDA, PHA, 0 # LDA, PUSH JMP, END-CODE ════════════════════════════════════════ SCREEN 030 ( M.BAR ( DRAW.MENU.BAR) : M.BAR ( ---) 0 0 D-POSITION ." {$90} WAREHOUSE " ." WORKSHOP " ." GAMES " ." OPTIONS " ; CREATE M.X( ( X BOUNDS OF EACH MENU HEADING) 1 C, 9 C, ( WAREHOUSE) 12 C, 19 C, ( WORKSHOP) 22 C, 26 C, ( GAMES) 29 C, 35 C, ( OPTIONS) 1024 CONSTANT CL.B( CREATE SC.B( 800 ALLOT ( SCREEN.BUFF() : S.SC ( ---) COLOR-MEM CL.B( 800 CMOVE 'SCREEN SC.B( 800 CMOVE ; : R.SC ( ---^RESTORE.SCREEN) 0 19 DO SC.B( I 40 * + 'SCREEN I 40 * + 40 CMOVE CL.B( I 40 * + COLOR-MEM I 40 * + 40 CMOVE -1 +LOOP ; ════════════════════════════════════════ SCREEN 031 ( DISP.ITEM HILIGHT.ITEM) VARIABLE M.WD ( WIDTH OF ITEM $) VARIABLE M.HI ( # OF ITEMS) VARIABLE M.X ( LEFT EDGE OF MENU) VARIABLE M$.ADDR VARIABLE MENU( : D.IT ( COLOR/ITEM#---) M.X @ 1- OVER 1+ D-POSITION ." {$90}'" SWAP CHAR.COLOR DUP M.WD @ * ( INDEX INTO MEN$) M$.ADDR @ + 1+ ( ADDR$) M.WD @ TYPE ( COUNT) ." {$90})" DROP ; : BOT ( ---^BOTTOM SHADOW OF MENU) M.X @ 1- M.HI @ 1+ D-POSITION B% CHAR.COLOR 45 EMIT ( LEFT) M.WD @ 0 DO 38 EMIT LOOP 44 EMIT ( RT SHADOW) ; : H.IT ( COLOR/ITEM#---) 1+ 40 * M.X @ + COLOR-MEM + M.WD @ ROT FILL ; ════════════════════════════════════════ SCREEN 032 ( SHOW.MENU DISABLED, MEN$, ITEM.OFF) VARIABLE ARR^ ( MENU ARRAY) : SH.M ( STRING ADDR/ARR ADRR--) DUP C@ M.X ! DUP 1+ C@ M.WD ! DUP 2+ C@ M.HI ! ARR^ ! M$.ADDR ! M.HI @ 0 DO ARR^ @ 3 + I + C@ ( COLOR?) I D.IT LOOP BOT ; : D, ( ---) ( COMPILE 16 0'S FOR ITEM ENABLED ARRAY) 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, ; : M$, ( STRING ADDR---) M$.ADDR @ SWAP $+ ; : IT- ( ITEM#/COLOR---) SWAP 2+ MENU( @ + C! ; : IT+ ( ITEM#/FLAG/MENUAD---) MENU( ! 0 = IF R% ELSE B% THEN IT- ; ════════════════════════════════════════ SCREEN 033 ( WAREHOUSE) CREATE WH( 1 C, ( LEFT EDGE) 11 C, ( WIDTH) 16 C, ( HEIGHT) D, 16 11 * $V WH$ 0 WH$ C! 16 M.WD ! WH$ M$.ADDR ! " GREEDY " M$, " MISTER CW " M$, " 3 " M$, " 4 " M$, " 5 " M$, " 6 " M$, " 7 " M$, " 8 " M$, " 9 " M$, " 10 " M$, " 11 " M$, " 12 " M$, " 13 " M$, " 14 " M$, " 15 " M$, " 16 " M$, : WH.M. WH$ WH( SH.M ; ════════════════════════════════════════ SCREEN 034 ( WORKSHOP) CREATE WS( 12 C, ( LEFT EDGE) 12 C, ( WIDTH) 8 C, ( HEIGHT) D, 8 12 * $V WS$ 0 WS$ C! WS( MENU( ! 16 M.WD ! WS$ M$.ADDR ! " ENTER " M$, " ............" M$, 2 R% IT- " SAVE CHIPWIT" M$, " ............" M$, 4 R% IT- " CUT PANEL " M$, " COPY PANEL " M$, " PASTE PANEL " M$, " CLEAR PANEL " M$, : WS.M. WS$ WS( SH.M ; ════════════════════════════════════════ SCREEN 035 ( GAMES) CREATE GAMES( 22 C, ( LEFT EDGE) 15 C, ( WIDTH) 11 C, ( HEIGHT) D, GAMES( MENU( ! 11 15 * $V GAMES$ 0 GAMES$ C! 16 M.WD ! GAMES$ M$.ADDR ! " START GAME " M$, " SERIES " M$, " .............." M$, 3 R% IT- " GREEDVILLE " M$, " CHIPWIT CAVES " M$, " DOOM ROOMS " M$, " PEACE PATHS " M$, " MEMORY LANES " M$, " OCTOPUS GARDEN" M$, " MYSTERY MATRIX" M$, " BOOMTOWN " M$, : GM.M. GAMES$ GAMES( SH.M ; ════════════════════════════════════════ SCREEN 036 ( OPTIONS) CREATE OP( 29 C, ( LEFT EDGE) 9 C, ( WIDTH) 6 C, ( HEIGHT) D, 6 9 * $V OP$ 0 OP$ C! OP( MENU( ! 16 M.WD ! OP$ M$.ADDR ! " DEBUG ON " M$, " SEE ROBOT" M$, " SLOW " M$, " STEP " M$, " ........." M$, 5 R% IT- " QUIT " M$, : OP.M. OP$ OP( SH.M ; ════════════════════════════════════════ SCREEN 037 ( SET.ITEM$) : S.IT$ ( ITEM#/STRADDR/MEN$/MEN(--) 1 + C@ >R ( WIDTH) 1+ M$.ADDR ! SWAP 1- R@ * M$.ADDR @ + ( STR/IT$) ( START ADDRESS OF ITEM$) DUP R> 32 FILL ( ERASE OLD) SWAP COUNT ( IT$/STR$/CNT) SWAP ( IT$/CNT/STR$) ROT ROT CMOVE ; ════════════════════════════════════════ SCREEN 080 ( IN.MENU.BAR?) VARIABLE T.M VARIABLE T.I VARIABLE M.RT VARIABLE I# : BAR? ( ---FLAG) 0 39 0 0 ( X/X/Y/Y) BUT.XY@ PT.RCT ; CREATE M( WH( , WS( , GAMES( , OP( , CREATE MENU$( WH$ , WS$ , GAMES$ , OP$ , ════════════════════════════════════════ SCREEN 081 ( WHICH.MENU SHOW.MENU) : M# ( ---MENU# OR 0) 0 ( LEAVE FALSE ON STACK) 4 0 DO I 2* M.X( + DUP C@ SWAP 1+ C@ ( MENU X BOUNDS) 0 0 BUT.XY@ PT.RCT IF DROP I 1+ LEAVE THEN LOOP ; : SHOW.MENU ( MENU#---) ( DRAWS CORRECT MENU AND SETS VARS) DUP T.M ! ( MEN#) DUP 1- 2* M( + @ ( MENU ADR) MENU( ! ( MEN#) DUP 1- 2* MENU$( + @ M$.ADDR ! MENU( @ DUP C@ DUP M.X ! OVER 1+ C@ DUP M.WD ! + M.RT ! 2+ C@ M.HI ! 0 T.I ! CASE 1 OF WH.M. ;; 2 OF WS.M. ;; 3 OF GM.M. ;; 4 OF OP.M. ;; ENDCASE ; ════════════════════════════════════════ SCREEN 082 ( NEW.ITEM) : NEW.I ( ITEM#---) ( HILIGHT NEW ITEM OR NONE IF 0) ( OR DISABLED) T.I @ DUP 0> IF DUP 2+ MENU( @ + C@ ( BLACK,BLUE?) SWAP ( DESELECTED) 1- H.IT ELSE DROP THEN ( NONE SELECTED) DUP 2+ MENU( @ + C@ ( DISABLED) IF DROP 0 THEN DUP DUP 0> IF W% SWAP ( WHITE SELECTED) 1- H.IT ELSE DROP THEN T.I ! ; ════════════════════════════════════════ SCREEN 083 ( TRACK.CURSOR) : TR.C ( ---) ( FOLLOW CURSOR AND HILIGHT) ( ITEM SELECTIONS) M.X @ M.RT @ 1 M.HI @ BUT.XY@ PT.RCT ( IN THE MENU) IF B.Y @ 50 - 8 / ( ITEM #) DUP M.HI @ > IF DROP 0 THEN ELSE 0 ( NO ITEM) THEN DUP T.I @ = IF DROP ( SAME ITEM) ELSE NEW.I THEN ; ════════════════════════════════════════ SCREEN 084 ( DO.MENU.EVENTS) : M.EV ( ---FLAG^DO.MENU.EVENTS) B.D @ IF BAR? IF M# DUP IF S.SC SHOW.MENU BEGIN TR.C B.D @ NOT UNTIL T.I @ DUP 0= IF DROP ELSE ( FLASH) 3 0 DO 0 NEW.I DUP NEW.I LOOP DROP THEN R.SC T.I @ ( TRUE IF ITEM CHOSEN) THEN ( LEAVE 0) ELSE 0 THEN ELSE 0 THEN ; ════════════════════════════════════════ SCREEN 085 ( MENU.TEST) : MENU.TEST ( ---) S1 M.BAR ON S-ENABLE BEGIN M.EV IF 0 24 D-POSITION ." MENU:" T.M @ . ." ITEM:" T.I @ . ." " ." DEPTH:" DEPTH . ." " THEN AGAIN ; ════════════════════════════════════════ SCREEN 090 ( FRAME) CODE FRAME ( WAITS FOR RASTER TO REACH 240) 242 # LDA, ( BOTTOM OF SPRITE Y) BEGIN, 53266 CMP, ( THERE YET?) 0= UNTIL, NEXT JMP, END-CODE ════════════════════════════════════════ SCREEN 091 ( FTEST) : FTEST 1000 0 DO FRAME GREEN 53281 C! RED 53281 C! LOOP ; ════════════════════════════════════════ SCREEN 109 ( MACHINE LANG VARS) CREATE ROOM.DATA( 80 ALLOT VARIABLE WALL.COVERS VARIABLE ROBOT.ORIENTATION VARIABLE ROBOT.SQUARE 12 CONSTANT WALL@ ════════════════════════════════════════ SCREEN 110 ( BLOCK.) CODE BLOCK. ( XT/YT/BLOCK/CWD/CHT) ( PRINT A BLOCK AT XT YT) 3 # LDA, XSAVE STX, SETUPN JSR, ( MOVE 3 STACK TO N) XSAVE LDX, INX, INX, XSAVE STX, 0 # LDY, N 4 + ),Y LDA, ( GET COLOR BYTE) N 1 - STA, ( STORE AT N-1) SEC 2 + LDY, ( YTAB) CLC, 0 # LDA, 0 # LDX, ( INIT CHAR^ CALC) BEGIN, CLC, 40 # ADC, CS IF, INX, THEN, DEY, 0= ( DEC YTAB INDEX) UNTIL, N 6 + STX, XSAVE LDX, CLC, SEC 4 + ADC, N 6 + LDX, ( XTAB) CS IF, INX, THEN, N 6 + STA, ( LO SCREEN START) N 2 + STA, ( LO COLOR START) TXA, CLC, ( HI^ INTO A ) 'SCREEN 8 RSHIFT # ADC, ( HI SCREEN) N 7 + STA, ( STORE HI) TXA, CLC, COLOR-MEM 8 RSHIFT # ADC, ( HI COL) N 3 + STA, ( STORE COLOR HI) ════════════════════════════════════════ SCREEN 111 ( BLOCK. CONT'D) CLC, N 4 + INC, ( POINT TO 1ST CHAR) 0= IF, N 5 + INC, THEN, BEGIN, ( Y DRAW LOOP) N 1+ LDY, ( HT INDEX) XSAVE LDX, BOT LDA, ( WD COUNTER) BOT 1+ STA, ( STORE IT) BEGIN, ( X DRAW LOOP) N 1 - LDA, ( GET COLOR) N 2 + ),Y STA, ( STORE IT) TYA, PHA, 0 # LDY, ( SAVE SCR^) N 4 + ),Y LDA, ( GET CHAR) TAX, PLA, TAY, ( RECOVER SCR^) TXA, XSAVE LDX, CLC, N 6 + ),Y STA, ( STORE CHAR) N 4 + INC, ( NEXT CHAR) 0= IF, N 5 + INC, THEN, INY, BOT 1 + DEC, ( WD INDEX) 0= UNTIL, ( LAST IN ROW?) N 1+ LDA, CLC, ( GET HT INDEX) 40 # ADC, N 1+ STA, ( NEXT ROW^) N DEC, ( HEIGHT COUNTER DEC) 0= UNTIL, XSAVE LDX, INX, INX, INX, INX, POPTWO JMP, END-CODE ════════════════════════════════════════ SCREEN 112 ( CHECK.COVER ) ASSEMBLER CREATE <CHECK.COVER> ( SQ#--FLAG^WALL BELOW SQUARE? ) BOT LDA, 8 # ADC, ( SQUARE DOWN) TAY, ' ROOM.DATA( ,Y LDA, ( SQARE.OBJECT) WALL@ # CMP, 0= IF, TYA, ' WALL.COVERS STA, 1 # LDA, BOT STA, ( 1 FLAG ON STACK) ELSE, 0 # LDA, BOT STA, ( NO ON STACK) THEN, RTS, CODE CHECK.COVER ( SQ--FLAG) <CHECK.COVER> JSR, NEXT JMP, END-CODE ════════════════════════════════════════ SCREEN 113 ( ROB.OR.SQ@) CODE ROB.OR.SQ@ ( ---ORIENT/SQRE) ' ROBOT.ORIENTATION LDA, DEX, DEX, BOT STA, 0 # LDA, BOT 1+ STA, ' ROBOT.SQUARE LDA, PHA, 0 # LDA, PUSH JMP, END-CODE ════════════════════════════════════════ SCREEN 114 ( SQUARE.OBJECT) CODE SQUARE.OBJECT ( SQ#--OBJ#) ' ROOM.DATA( 255 AND # LDA, N STA, ' ROOM.DATA( 8 RSHIFT # LDA, N 1+ STA, BOT LDY, N ),Y LDA, ( GRAB OBJECT#) BOT STA, ( ON STACK) NEXT JMP, END-CODE ════════════════════════════════════════ SCREEN 120 ( P.IN.RECT TESTER) : PTEST CR 0. SETTIM 1000 0 DO 5 IRND 40 IRND 5 IRND 24 IRND 300 IRND 250 IRND DROP DROP DROP DROP DROP DROP LOOP RDTIM DROP 6 / . CR 0. SETTIM 1000 0 DO 5 IRND 40 IRND 5 IRND 24 IRND 300 IRND 250 IRND PT.IN.RECT DROP LOOP RDTIM DROP 6 / . ; ════════════════════════════════════════ SCREEN 130 ( DUMMY PROGRAM MAKER ) : P.STUFF ( OP/FLOW/ARG/FLOW/CH#--) CURRENT.INSTRUCTION ! + ROT ROT + SWAP !CHIP ; : BLANK.PANEL ( PAN#--) CURRENT.PANEL ! CHIP.COUNT@ 0 DO SOCKET@ RIGHT.F@ 0 0 I P.STUFF LOOP GO.MARKER@ RIGHT.F@ 0 0 0 P.STUFF ; : BLANK.ALL 10 0 DO I BLANK.PANEL LOOP 0 CURRENT.PANEL ! ; : SAVE.NEW.CW ( #---) BLANK.ALL CW.SAVE ; ════════════════════════════════════════ SCREEN 131 ( DUMMY PROGRAM <<<<<<) BLANK.ALL FEEL.FOR@ RIGHT.F@ FLOOR@ DOWN.F@ 1 P.STUFF MOVE@ RIGHT.F@ FORWARD@ 0 2 P.STUFF GOTO.GO@ 0 0 0 3 P.STUFF FLIP.COIN@ RIGHT.F@ 0 DOWN.F@ 9 P.STUFF MOVE@ DOWN.F@ TURN.RIGHT@ 0 10 P.STUFF MOVE@ RIGHT.F@ TURN.LEFT@ 0 17 P.STUFF GOTO.GO@ 0 0 0 18 P.STUFF 1 CW.SAVE ════════════════════════════════════════ SCREEN 132 ( CW2) BLANK.ALL FEEL.FOR@ RIGHT.F@ DISK@ DOWN.F@ 1 P.STUFF PICK.UP@ RIGHT.F@ 0 0 2 P.STUFF SING@ RIGHT.F@ RANGE.REG@ 0 3 P.STUFF GOTO.GO@ 0 0 0 4 P.STUFF LOOK.FOR@ RIGHT.F@ CREEP@ DOWN.F@ 9 P.STUFF QRAY@ RIGHT.F@ 0 0 10 P.STUFF FEEL.FOR@ RIGHT.F@ FLOOR@ DOWN.F@ 17 P.STUFF MOVE@ RIGHT.F@ FORWARD@ 0 18 P.STUFF GOTO.GO@ 0 0 0 19 P.STUFF FLIP.COIN@ RIGHT.F@ 0 DOWN.F@ 25 P.STUFF MOVE@ RIGHT.F@ TURN.LEFT@ 0 26 P.STUFF MOVE@ RIGHT.F@ TURN.RIGHT@ 0 33 P.STUFF MOVE@ RIGHT.F@ TURN.RIGHT@ 0 34 P.STUFF GOTO.GO@ 0 0 0 35 P.STUFF 2 CW.SAVE ════════════════════════════════════════ SCREEN 133 ( CW3) BLANK.ALL FEEL.FOR@ RIGHT.F@ DISK@ DOWN.F@ 1 P.STUFF PICK.UP@ RIGHT.F@ 0 0 2 P.STUFF FEEL.FOR@ RIGHT.F@ COFFEE@ DOWN.F@ 9 P.STUFF WIRE@ UP.F@ 0 0 10 P.STUFF FEEL.FOR@ RIGHT.F@ OIL@ DOWN.F@ 17 P.STUFF WIRE@ UP.F@ 0 0 18 P.STUFF LOOK.FOR@ RIGHT.F@ CREEP@ DOWN.F@ 25 P.STUFF QRAY@ RIGHT.F@ 0 0 26 P.STUFF FEEL.FOR@ LEFT.F@ FLOOR@ RIGHT.F@ 33 P.STUFF MOVE@ UP.F@ FORWARD@ 0 32 P.STUFF GOTO.GO@ 0 0 0 24 P.STUFF WIRE@ RIGHT.F@ 0 0 34 P.STUFF WIRE@ RIGHT.F@ 0 0 35 P.STUFF FLIP.COIN@ RIGHT.F@ 0 UP.F@ 36 P.STUFF MOVE@ RIGHT.F@ TURN.LEFT@ 0 37 P.STUFF MOVE@ RIGHT.F@ TURN.RIGHT@ 0 28 P.STUFF MOVE@ RIGHT.F@ TURN.LEFT@ 0 38 P.STUFF 3 CW.SAVE ════════════════════════════════════════ SCREEN 140 ( SCENARIO CHOPPER) 128 157 C! ( SHOW MESSAGES) CREATE CHOP( 5000 ALLOT 311 LOAD ( FIX.PP) : SAVE$ ( STR$---) 0 SAVENAME C! SAVENAME SWAP $CONCAT ; : CHOP.SAVE ( #ROOMS---) CHOP( 78 + DUP ROT 80 * + .S SAVE ; CHOP( " GREEDVILLE" LOADRAM " @:A1" SAVE$ 4 CHOP.SAVE CHOP( " CW CAVES" LOADRAM " @:A2" SAVE$ 8 CHOP.SAVE CHOP( " DOOM ROOMS" LOADRAM " @:A3" SAVE$ 13 CHOP.SAVE CHOP( " PEACE PATHS" LOADRAM " @:A4" FIX.PP SAVE$ 50 CHOP.SAVE " @:A7" SAVE$ 50 CHOP.SAVE ( TEMP) CHOP( " MEMORY LANES" LOADRAM " @:A5" SAVE$ 10 CHOP.SAVE CHOP( " OCTO GARDENS" LOADRAM " @:A6" SAVE$ 44 CHOP.SAVE CHOP( " BOOMTOWN" LOADRAM " @:A8" SAVE$ 9 CHOP.SAVE ════════════════════════════════════════ SCREEN 141 ( FIX.PP) : FIX.PP ( FIT PEACE PATHS IN 4K) CHOP( 78 + ( BASE) 49 OVER 67 + C! 49 OVER 68 + C! 49 OVER 69 + C! ( CONECT 1 TO 49) 32 OVER 75 + C! 40 OVER 76 + C! 48 OVER 77 + C! DUP 80 46 * + ( ROOM 47) 12 OVER 31 + C! ( CLOSE DOOR) 49 OVER 68 + C! 49 OVER 69 + C! 49 OVER 70 + C! ( SLIDE OVER PTRS) 1 OVER 76 + C! 2 OVER 77 + C! 3 OVER 78 + C! ( DOOR PTRS) DROP 80 48 * + ( ROOM 49) 1 OVER 67 + C! 1 OVER 68 + C! 1 OVER 69 + C! ( POINT TO 1) 23 OVER 75 + C! 31 OVER 76 + C! 39 OVER 77 + C! ( RIGHT DOORS) 57 + 12 SWAP C! ( CLOSE BTM DOOR) ; ════════════════════════════════════════ SCREEN 150 ( SHADOW SHADOW.BLOCK) : SHADOW ( L/B/R/T---) 4 PICK 1- 2 PICK 1- D-POSITION GM.BORD.COL@ 8 + CHAR.COLOR 64 EMIT SWAP 4 ROLL ( B/T/R/L) - DUP >R ( WIDTH) 0 DO 91 EMIT LOOP ( TOP MARGIN) 92 EMIT ." {$9D}" ( TOP RT EDGE) - DUP 0 DO ( HEIGHT) 93 EMIT ." {$9D}" LOOP ( RT SHAD) 95 EMIT ( LOWER RT SHADOW) ." {$9D}{$9D}" R> 0 DO 47 EMIT ." {$9D}{$9D}" LOOP 174 EMIT ( BOTTOM LEFT ) 0 DO ." {$91}{$9D}" 175 EMIT LOOP ( LEFT SHADW) ; : SHADOW.BLOCK ( L/T/R/B/COLOR---) 5 PICK 3 PICK 1+ 5 PICK 1+ 7 PICK SHADOW COLOR.BLOCK ; ════════════════════════════════════════ SCREEN 151 ( GAME.TITLE) CREATE CW.TITLE( BLACK C, 100 C, 101 C, 102 C, 103 C, 104 C, 105 C, 106 C, 107 C, 108 C, 32 C, 32 C, 109 C, 32 C, 32 C, 32 C, 32 C, 32 C, 32 C, : GAME.TITLE ( ---) 8 4 CW.TITLE( 9 2 BLOCK. ; ════════════════════════════════════════ SCREEN 152 ( SETUP.GAME.SCREEN) : SETUP.GAME.SCREEN ( ---) BLACK DUP BORDER BKGND 0 0 D-POSITION ." {$93}" 1 MULTI-COLOR 0 0 39 24 GM.BORD.COL@ COLOR.BLOCK 1 2 24 23 BAK.C SHADOW.BLOCK ." {$90}" 1 2 D-POSITION 24 0 DO 94 EMIT LOOP DRAW.MENU.BAR 27 2 38 22 BAK.C SHADOW.BLOCK 27 2 38 23 BAK.C COLOR.BLOCK ( STAT MEM WINDOW) 26 23 D-POSITION 175 EMIT 26 24 D-POSITION 174 EMIT GM.BORD.COL@ 8 + CHAR.COLOR 12 0 DO 47 EMIT LOOP 31 'SCREEN 999 + C! GM.BORD.COL@ 8 + DUP COLOR-MEM 999 + DUP >R C! R> 40 - C! 29 'SCREEN 959 + C! BLACK CHAR.COLOR GAME.TITLE ( 8 3 D-POSITION ." GREEDY IN" 8 4 D-POSITION ." GREEDVILLE" ) 2 4 D-POSITION ." SCORE" 18 4 D-POSITION ." CYCLES" 27 2 D-POSITION ." ^^ STATUS ^^" 27 12 D-POSITION ." ^^ MEMORY ^^" BAK.C BKGND GM.BORD.COL@ BORDER ; ════════════════════════════════════════ SCREEN 153 ( REGISTER.DRAW) : B ." {$9D}{$9D}{$9D}{$9D}" ; : REG.OUTLN ( HEIGHT/COLOR/X/Y---) D-POSITION CHAR.COLOR 34 EMIT 34 EMIT ." {$9D}" 38 EMIT 38 EMIT 35 EMIT B 0 DO 41 EMIT I 2 = NOT IF ." " ELSE ." .." THEN 39 EMIT B LOOP 37 EMIT 40 EMIT 40 EMIT 36 EMIT ; : REGISTER.DRAW ( ---) 27 3 D-POSITION ." PNL CHIP KEY" 27 4 D-POSITION 5 NC@ 27 5 REG.OUTLN 28 6 DAMAGE.REG@ O.D. 5 NC@ 31 5 REG.OUTLN 32 6 FUEL.REG@ O.D. 5 NC@ 35 5 REG.OUTLN 36 6 RANGE.REG@ O.D. 9 NC@ 27 13 REG.OUTLN 28 14 NUM.STACK@ O.D. 9 OC@ 31 13 REG.OUTLN 32 14 OBJ.STACK@ O.D. 9 MC@ 35 13 REG.OUTLN 36 14 MOV.STACK@ O.D. ; ════════════════════════════════════════ SCREEN 154 ( VERT.NUM) : VERT.NUM ( ---) ( NUMBER PANEL VERTICALLY) 0 3 D-POSITION 5 0 DO ." " I . ." {$9D} {$9D} {$9D}0{$9D} " LOOP ; ════════════════════════════════════════ SCREEN 155 ( SETUP.WORK.SCREEN) : SETUP.WORK.SCREEN ( ---) 0 MULTI-COLOR 0 0 D-POSITION ." {$93}" DRAW.MENU.BAR WS.CHAR 0 1 39 1 WS.BORD.COL@ COLOR.BLOCK ( 2 5 25 24 WS.BACK.COL@ COLOR.BLOCK) BLACK CHAR.COLOR 26 2 D-POSITION ." ^^^^ IBOL ^^^^" 26 3 D-POSITION ." ^^ OPERATORS ^" 26 4 39 17 AC@ COLOR.BLOCK ( 26 18 39 18 WHITE COLOR.BLOCK ) 26 17 D-POSITION ." ^^ ARGUMENTS ^" ( 26 19 39 24 TC@ COLOR.BLOCK ) WS.BACK.COL@ CHAR.COLOR 3 24 D-POSITION ." 0 1 2 3 4 5 6 7" VERT.NUM LT.GRAY BKGND ; ════════════════════════════════════════ SCREEN 156 ( WS.ACTION,THING.ICONS) : WS.ACTION.ICONS ( ---) ACTION.COUNT@ 1- GOTO.GO@ DO I OP.W.DRAW LOOP 26 6 39 6 AC@ COLOR.BLOCK 26 8 32 9 AC@ COLOR.BLOCK OBJECT=@ OP.W.DRAW MOVE=@ OP.W.DRAW NUMBER<@ OP.W.DRAW NUMBER=@ OP.W.DRAW SUBPANEL@ OP.W.DRAW WIRE@ OP.W.DRAW KEYPRESS@ OP.W.DRAW 26 8 32 8 AC@ COLOR.BLOCK 35 8 39 8 AC@ COLOR.BLOCK 26 10 39 10 AC@ COLOR.BLOCK 33 11 33 11 AC@ COLOR.BLOCK 29 7 29 7 AC@ COLOR.BLOCK 32 7 32 7 AC@ COLOR.BLOCK 35 7 35 7 AC@ COLOR.BLOCK ; ════════════════════════════════════════ SCREEN 159 ( SAVE.SCREENS) : SAVE.SCREENS 0 157 C! ( NO MSG) GAME.ON@ PROG.STATUS ! GRAPH.MEM.INIT GRAPH.LOAD SETUP.GAME.SCREEN GAME.TITLE REGISTER.DRAW 'SCREEN FIRST 1000 CMOVE COLOR-MEM FIRST 1000 + 1000 CMOVE WORKSHOP.ON@ PROG.STATUS ! SETUP.WORK.SCREEN WS.ACTION.ICONS 15 CW.LOAD 0 PANEL.DRAW 'SCREEN FIRST 2000 + 1000 CMOVE COLOR-MEM FIRST 3000 + 1000 CMOVE 0 SAVENAME C! SAVENAME " @0:CW.SCR" $CONCAT FIRST FIRST 4000 + SAVE EMPTY-BUFFERS ;
412
0.826651
1
0.826651
game-dev
MEDIA
0.47542
game-dev
0.951997
1
0.951997
stephengold/Libbulletjme
31,274
src/main/native/bullet3/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans https://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 "btGjkPairDetector.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h" #if defined(DEBUG) || defined(_DEBUG) //#define TEST_NON_VIRTUAL 1 #include <stdio.h> //for debug printf #ifdef __SPU__ #include <spu_printf.h> #define printf spu_printf #endif //__SPU__ #endif //must be above the machine epsilon #ifdef BT_USE_DOUBLE_PRECISION #define REL_ERROR2 btScalar(1.0e-12) btScalar gGjkEpaPenetrationTolerance = 1.0e-12; #else #define REL_ERROR2 btScalar(1.0e-6) btScalar gGjkEpaPenetrationTolerance = 0.001; #endif btGjkPairDetector::btGjkPairDetector(const btConvexShape *objectA, const btConvexShape *objectB, btSimplexSolverInterface *simplexSolver, btConvexPenetrationDepthSolver *penetrationDepthSolver) : m_cachedSeparatingAxis(btScalar(0.), btScalar(1.), btScalar(0.)), m_penetrationDepthSolver(penetrationDepthSolver), m_simplexSolver(simplexSolver), m_minkowskiA(objectA), m_minkowskiB(objectB), m_shapeTypeA(objectA->getShapeType()), m_shapeTypeB(objectB->getShapeType()), m_marginA(objectA->getMargin()), m_marginB(objectB->getMargin()), m_ignoreMargin(false), m_lastUsedMethod(-1), m_catchDegeneracies(1), m_fixContactNormalDirection(1) { } btGjkPairDetector::btGjkPairDetector(const btConvexShape *objectA, const btConvexShape *objectB, int shapeTypeA, int shapeTypeB, btScalar marginA, btScalar marginB, btSimplexSolverInterface *simplexSolver, btConvexPenetrationDepthSolver *penetrationDepthSolver) : m_cachedSeparatingAxis(btScalar(0.), btScalar(1.), btScalar(0.)), m_penetrationDepthSolver(penetrationDepthSolver), m_simplexSolver(simplexSolver), m_minkowskiA(objectA), m_minkowskiB(objectB), m_shapeTypeA(shapeTypeA), m_shapeTypeB(shapeTypeB), m_marginA(marginA), m_marginB(marginB), m_ignoreMargin(false), m_lastUsedMethod(-1), m_catchDegeneracies(1), m_fixContactNormalDirection(1) { } void btGjkPairDetector::getClosestPoints(const ClosestPointInput &input, Result &output, class btIDebugDraw *debugDraw, bool swapResults) { (void)swapResults; getClosestPointsNonVirtual(input, output, debugDraw); } static void btComputeSupport(const btConvexShape *convexA, const btTransform &localTransA, const btConvexShape *convexB, const btTransform &localTransB, const btVector3 &dir, bool check2d, btVector3 &supAworld, btVector3 &supBworld, btVector3 &aMinb) { btVector3 separatingAxisInA = (dir)*localTransA.getBasis(); btVector3 separatingAxisInB = (-dir) * localTransB.getBasis(); btVector3 pInANoMargin = convexA->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInA); btVector3 qInBNoMargin = convexB->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInB); btVector3 pInA = pInANoMargin; btVector3 qInB = qInBNoMargin; supAworld = localTransA(pInA); supBworld = localTransB(qInB); if (check2d) { supAworld[2] = 0.f; supBworld[2] = 0.f; } aMinb = supAworld - supBworld; } struct btSupportVector { btVector3 v; //!< Support point in minkowski sum btVector3 v1; //!< Support point in obj1 btVector3 v2; //!< Support point in obj2 }; struct btSimplex { btSupportVector ps[4]; int last; //!< index of last added point }; static btVector3 ccd_vec3_origin(0, 0, 0); inline void btSimplexInit(btSimplex *s) { s->last = -1; } inline int btSimplexSize(const btSimplex *s) { return s->last + 1; } inline const btSupportVector *btSimplexPoint(const btSimplex *s, int idx) { // here is no check on boundaries return &s->ps[idx]; } inline void btSupportCopy(btSupportVector *d, const btSupportVector *s) { *d = *s; } inline void btVec3Copy(btVector3 *v, const btVector3 *w) { *v = *w; } inline void ccdVec3Add(btVector3 *v, const btVector3 *w) { v->m_floats[0] += w->m_floats[0]; v->m_floats[1] += w->m_floats[1]; v->m_floats[2] += w->m_floats[2]; } inline void ccdVec3Sub(btVector3 *v, const btVector3 *w) { *v -= *w; } inline void btVec3Sub2(btVector3 *d, const btVector3 *v, const btVector3 *w) { *d = (*v) - (*w); } inline btScalar btVec3Dot(const btVector3 *a, const btVector3 *b) { btScalar dot; dot = a->dot(*b); return dot; } inline btScalar ccdVec3Dist2(const btVector3 *a, const btVector3 *b) { btVector3 ab; btVec3Sub2(&ab, a, b); return btVec3Dot(&ab, &ab); } inline void btVec3Scale(btVector3 *d, btScalar k) { d->m_floats[0] *= k; d->m_floats[1] *= k; d->m_floats[2] *= k; } inline void btVec3Cross(btVector3 *d, const btVector3 *a, const btVector3 *b) { d->m_floats[0] = (a->m_floats[1] * b->m_floats[2]) - (a->m_floats[2] * b->m_floats[1]); d->m_floats[1] = (a->m_floats[2] * b->m_floats[0]) - (a->m_floats[0] * b->m_floats[2]); d->m_floats[2] = (a->m_floats[0] * b->m_floats[1]) - (a->m_floats[1] * b->m_floats[0]); } inline void btTripleCross(const btVector3 *a, const btVector3 *b, const btVector3 *c, btVector3 *d) { btVector3 e; btVec3Cross(&e, a, b); btVec3Cross(d, &e, c); } inline int ccdEq(btScalar _a, btScalar _b) { btScalar ab; btScalar a, b; ab = btFabs(_a - _b); if (btFabs(ab) < SIMD_EPSILON) return 1; a = btFabs(_a); b = btFabs(_b); if (b > a) { return ab < SIMD_EPSILON * b; } else { return ab < SIMD_EPSILON * a; } } btScalar ccdVec3X(const btVector3 *v) { return v->x(); } btScalar ccdVec3Y(const btVector3 *v) { return v->y(); } btScalar ccdVec3Z(const btVector3 *v) { return v->z(); } inline int btVec3Eq(const btVector3 *a, const btVector3 *b) { return ccdEq(ccdVec3X(a), ccdVec3X(b)) && ccdEq(ccdVec3Y(a), ccdVec3Y(b)) && ccdEq(ccdVec3Z(a), ccdVec3Z(b)); } inline void btSimplexAdd(btSimplex *s, const btSupportVector *v) { // here is no check on boundaries in sake of speed ++s->last; btSupportCopy(s->ps + s->last, v); } inline void btSimplexSet(btSimplex *s, size_t pos, const btSupportVector *a) { btSupportCopy(s->ps + pos, a); } inline void btSimplexSetSize(btSimplex *s, int size) { s->last = size - 1; } inline const btSupportVector *ccdSimplexLast(const btSimplex *s) { return btSimplexPoint(s, s->last); } inline int ccdSign(btScalar val) { if (btFuzzyZero(val)) { return 0; } else if (val < btScalar(0)) { return -1; } return 1; } inline btScalar btVec3PointSegmentDist2(const btVector3 *P, const btVector3 *x0, const btVector3 *b, btVector3 *witness) { // The computation comes from solving equation of segment: // S(t) = x0 + t.d // where - x0 is initial point of segment // - d is direction of segment from x0 (|d| > 0) // - t belongs to <0, 1> interval // // Than, distance from a segment to some point P can be expressed: // D(t) = |x0 + t.d - P|^2 // which is distance from any point on segment. Minimization // of this function brings distance from P to segment. // Minimization of D(t) leads to simple quadratic equation that's // solving is straightforward. // // Bonus of this method is witness point for free. btScalar dist, t; btVector3 d, a; // direction of segment btVec3Sub2(&d, b, x0); // precompute vector from P to x0 btVec3Sub2(&a, x0, P); t = -btScalar(1.) * btVec3Dot(&a, &d); t /= btVec3Dot(&d, &d); if (t < btScalar(0) || btFuzzyZero(t)) { dist = ccdVec3Dist2(x0, P); if (witness) btVec3Copy(witness, x0); } else if (t > btScalar(1) || ccdEq(t, btScalar(1))) { dist = ccdVec3Dist2(b, P); if (witness) btVec3Copy(witness, b); } else { if (witness) { btVec3Copy(witness, &d); btVec3Scale(witness, t); ccdVec3Add(witness, x0); dist = ccdVec3Dist2(witness, P); } else { // recycling variables btVec3Scale(&d, t); ccdVec3Add(&d, &a); dist = btVec3Dot(&d, &d); } } return dist; } btScalar btVec3PointTriDist2(const btVector3 *P, const btVector3 *x0, const btVector3 *B, const btVector3 *C, btVector3 *witness) { // Computation comes from analytic expression for triangle (x0, B, C) // T(s, t) = x0 + s.d1 + t.d2, where d1 = B - x0 and d2 = C - x0 and // Then equation for distance is: // D(s, t) = | T(s, t) - P |^2 // This leads to minimization of quadratic function of two variables. // The solution from is taken only if s is between 0 and 1, t is // between 0 and 1 and t + s < 1, otherwise distance from segment is // computed. btVector3 d1, d2, a; double u, v, w, p, q, r; double s, t, dist, dist2; btVector3 witness2; btVec3Sub2(&d1, B, x0); btVec3Sub2(&d2, C, x0); btVec3Sub2(&a, x0, P); u = btVec3Dot(&a, &a); v = btVec3Dot(&d1, &d1); w = btVec3Dot(&d2, &d2); p = btVec3Dot(&a, &d1); q = btVec3Dot(&a, &d2); r = btVec3Dot(&d1, &d2); s = (q * r - w * p) / (w * v - r * r); t = (-s * r - q) / w; if ((btFuzzyZero(s) || s > btScalar(0)) && (ccdEq(s, btScalar(1)) || s < btScalar(1)) && (btFuzzyZero(t) || t > btScalar(0)) && (ccdEq(t, btScalar(1)) || t < btScalar(1)) && (ccdEq(t + s, btScalar(1)) || t + s < btScalar(1))) { if (witness) { btVec3Scale(&d1, s); btVec3Scale(&d2, t); btVec3Copy(witness, x0); ccdVec3Add(witness, &d1); ccdVec3Add(witness, &d2); dist = ccdVec3Dist2(witness, P); } else { dist = s * s * v; dist += t * t * w; dist += btScalar(2.) * s * t * r; dist += btScalar(2.) * s * p; dist += btScalar(2.) * t * q; dist += u; } } else { dist = btVec3PointSegmentDist2(P, x0, B, witness); dist2 = btVec3PointSegmentDist2(P, x0, C, &witness2); if (dist2 < dist) { dist = dist2; if (witness) btVec3Copy(witness, &witness2); } dist2 = btVec3PointSegmentDist2(P, B, C, &witness2); if (dist2 < dist) { dist = dist2; if (witness) btVec3Copy(witness, &witness2); } } return dist; } static int btDoSimplex2(btSimplex *simplex, btVector3 *dir) { const btSupportVector *A, *B; btVector3 AB, AO, tmp; btScalar dot; // get last added as A A = ccdSimplexLast(simplex); // get the other point B = btSimplexPoint(simplex, 0); // compute AB oriented segment btVec3Sub2(&AB, &B->v, &A->v); // compute AO vector btVec3Copy(&AO, &A->v); btVec3Scale(&AO, -btScalar(1)); // dot product AB . AO dot = btVec3Dot(&AB, &AO); // check if origin doesn't lie on AB segment btVec3Cross(&tmp, &AB, &AO); if (btFuzzyZero(btVec3Dot(&tmp, &tmp)) && dot > btScalar(0)) { return 1; } // check if origin is in area where AB segment is if (btFuzzyZero(dot) || dot < btScalar(0)) { // origin is in outside are of A btSimplexSet(simplex, 0, A); btSimplexSetSize(simplex, 1); btVec3Copy(dir, &AO); } else { // origin is in area where AB segment is // keep simplex untouched and set direction to // AB x AO x AB btTripleCross(&AB, &AO, &AB, dir); } return 0; } static int btDoSimplex3(btSimplex *simplex, btVector3 *dir) { const btSupportVector *A, *B, *C; btVector3 AO, AB, AC, ABC, tmp; btScalar dot, dist; // get last added as A A = ccdSimplexLast(simplex); // get the other points B = btSimplexPoint(simplex, 1); C = btSimplexPoint(simplex, 0); // check touching contact dist = btVec3PointTriDist2(&ccd_vec3_origin, &A->v, &B->v, &C->v, 0); if (btFuzzyZero(dist)) { return 1; } // check if triangle is really triangle (has area > 0) // if not simplex can't be expanded and thus no itersection is found if (btVec3Eq(&A->v, &B->v) || btVec3Eq(&A->v, &C->v)) { return -1; } // compute AO vector btVec3Copy(&AO, &A->v); btVec3Scale(&AO, -btScalar(1)); // compute AB and AC segments and ABC vector (perpendircular to triangle) btVec3Sub2(&AB, &B->v, &A->v); btVec3Sub2(&AC, &C->v, &A->v); btVec3Cross(&ABC, &AB, &AC); btVec3Cross(&tmp, &ABC, &AC); dot = btVec3Dot(&tmp, &AO); if (btFuzzyZero(dot) || dot > btScalar(0)) { dot = btVec3Dot(&AC, &AO); if (btFuzzyZero(dot) || dot > btScalar(0)) { // C is already in place btSimplexSet(simplex, 1, A); btSimplexSetSize(simplex, 2); btTripleCross(&AC, &AO, &AC, dir); } else { dot = btVec3Dot(&AB, &AO); if (btFuzzyZero(dot) || dot > btScalar(0)) { btSimplexSet(simplex, 0, B); btSimplexSet(simplex, 1, A); btSimplexSetSize(simplex, 2); btTripleCross(&AB, &AO, &AB, dir); } else { btSimplexSet(simplex, 0, A); btSimplexSetSize(simplex, 1); btVec3Copy(dir, &AO); } } } else { btVec3Cross(&tmp, &AB, &ABC); dot = btVec3Dot(&tmp, &AO); if (btFuzzyZero(dot) || dot > btScalar(0)) { dot = btVec3Dot(&AB, &AO); if (btFuzzyZero(dot) || dot > btScalar(0)) { btSimplexSet(simplex, 0, B); btSimplexSet(simplex, 1, A); btSimplexSetSize(simplex, 2); btTripleCross(&AB, &AO, &AB, dir); } else { btSimplexSet(simplex, 0, A); btSimplexSetSize(simplex, 1); btVec3Copy(dir, &AO); } } else { dot = btVec3Dot(&ABC, &AO); if (btFuzzyZero(dot) || dot > btScalar(0)) { btVec3Copy(dir, &ABC); } else { btSupportVector tmp; btSupportCopy(&tmp, C); btSimplexSet(simplex, 0, B); btSimplexSet(simplex, 1, &tmp); btVec3Copy(dir, &ABC); btVec3Scale(dir, -btScalar(1)); } } } return 0; } static int btDoSimplex4(btSimplex *simplex, btVector3 *dir) { const btSupportVector *A, *B, *C, *D; btVector3 AO, AB, AC, AD, ABC, ACD, ADB; int B_on_ACD, C_on_ADB, D_on_ABC; int AB_O, AC_O, AD_O; btScalar dist; // get last added as A A = ccdSimplexLast(simplex); // get the other points B = btSimplexPoint(simplex, 2); C = btSimplexPoint(simplex, 1); D = btSimplexPoint(simplex, 0); // check if tetrahedron is really tetrahedron (has volume > 0) // if it is not simplex can't be expanded and thus no intersection is // found dist = btVec3PointTriDist2(&A->v, &B->v, &C->v, &D->v, 0); if (btFuzzyZero(dist)) { return -1; } // check if origin lies on some of tetrahedron's face - if so objects // intersect dist = btVec3PointTriDist2(&ccd_vec3_origin, &A->v, &B->v, &C->v, 0); if (btFuzzyZero(dist)) return 1; dist = btVec3PointTriDist2(&ccd_vec3_origin, &A->v, &C->v, &D->v, 0); if (btFuzzyZero(dist)) return 1; dist = btVec3PointTriDist2(&ccd_vec3_origin, &A->v, &B->v, &D->v, 0); if (btFuzzyZero(dist)) return 1; dist = btVec3PointTriDist2(&ccd_vec3_origin, &B->v, &C->v, &D->v, 0); if (btFuzzyZero(dist)) return 1; // compute AO, AB, AC, AD segments and ABC, ACD, ADB normal vectors btVec3Copy(&AO, &A->v); btVec3Scale(&AO, -btScalar(1)); btVec3Sub2(&AB, &B->v, &A->v); btVec3Sub2(&AC, &C->v, &A->v); btVec3Sub2(&AD, &D->v, &A->v); btVec3Cross(&ABC, &AB, &AC); btVec3Cross(&ACD, &AC, &AD); btVec3Cross(&ADB, &AD, &AB); // side (positive or negative) of B, C, D relative to planes ACD, ADB // and ABC respectively B_on_ACD = ccdSign(btVec3Dot(&ACD, &AB)); C_on_ADB = ccdSign(btVec3Dot(&ADB, &AC)); D_on_ABC = ccdSign(btVec3Dot(&ABC, &AD)); // whether origin is on same side of ACD, ADB, ABC as B, C, D // respectively AB_O = ccdSign(btVec3Dot(&ACD, &AO)) == B_on_ACD; AC_O = ccdSign(btVec3Dot(&ADB, &AO)) == C_on_ADB; AD_O = ccdSign(btVec3Dot(&ABC, &AO)) == D_on_ABC; if (AB_O && AC_O && AD_O) { // origin is in tetrahedron return 1; // rearrange simplex to triangle and call btDoSimplex3() } else if (!AB_O) { // B is farthest from the origin among all of the tetrahedron's // points, so remove it from the list and go on with the triangle // case // D and C are in place btSimplexSet(simplex, 2, A); btSimplexSetSize(simplex, 3); } else if (!AC_O) { // C is farthest btSimplexSet(simplex, 1, D); btSimplexSet(simplex, 0, B); btSimplexSet(simplex, 2, A); btSimplexSetSize(simplex, 3); } else { // (!AD_O) btSimplexSet(simplex, 0, C); btSimplexSet(simplex, 1, B); btSimplexSet(simplex, 2, A); btSimplexSetSize(simplex, 3); } return btDoSimplex3(simplex, dir); } static int btDoSimplex(btSimplex *simplex, btVector3 *dir) { if (btSimplexSize(simplex) == 2) { // simplex contains segment only one segment return btDoSimplex2(simplex, dir); } else if (btSimplexSize(simplex) == 3) { // simplex contains triangle return btDoSimplex3(simplex, dir); } else { // btSimplexSize(simplex) == 4 // tetrahedron - this is the only shape which can encapsule origin // so btDoSimplex4() also contains test on it return btDoSimplex4(simplex, dir); } } #ifdef __SPU__ void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput &input, Result &output, class btIDebugDraw *debugDraw) #else void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput &input, Result &output, class btIDebugDraw *debugDraw) #endif { m_cachedSeparatingDistance = 0.f; btScalar distance = btScalar(0.); btVector3 normalInB(btScalar(0.), btScalar(0.), btScalar(0.)); btVector3 pointOnA, pointOnB; btTransform localTransA = input.m_transformA; btTransform localTransB = input.m_transformB; btVector3 positionOffset = (localTransA.getOrigin() + localTransB.getOrigin()) * btScalar(0.5); localTransA.getOrigin() -= positionOffset; localTransB.getOrigin() -= positionOffset; bool check2d = m_minkowskiA->isConvex2d() && m_minkowskiB->isConvex2d(); btScalar marginA = m_marginA; btScalar marginB = m_marginB; //for CCD we don't use margins if (m_ignoreMargin) { marginA = btScalar(0.); marginB = btScalar(0.); } m_curIter = 0; int gGjkMaxIter = 1000; //this is to catch invalid input, perhaps check for #NaN? m_cachedSeparatingAxis.setValue(0, 1, 0); bool isValid = false; bool checkSimplex = false; bool checkPenetration = true; m_degenerateSimplex = 0; m_lastUsedMethod = -1; int status = -2; btVector3 orgNormalInB(0, 0, 0); btScalar margin = marginA + marginB; //we add a separate implementation to check if the convex shapes intersect //See also "Real-time Collision Detection with Implicit Objects" by Leif Olvang //Todo: integrate the simplex penetration check directly inside the Bullet btVoronoiSimplexSolver //and remove this temporary code from libCCD //this fixes issue https://github.com/bulletphysics/bullet3/issues/1703 //note, for large differences in shapes, use double precision build! { btScalar squaredDistance = BT_LARGE_FLOAT; btScalar delta = btScalar(0.); btSimplex simplex1; btSimplex *simplex = &simplex1; btSimplexInit(simplex); btVector3 dir(1, 0, 0); { btVector3 lastSupV; btVector3 supAworld; btVector3 supBworld; btComputeSupport(m_minkowskiA, localTransA, m_minkowskiB, localTransB, dir, check2d, supAworld, supBworld, lastSupV); btSupportVector last; last.v = lastSupV; last.v1 = supAworld; last.v2 = supBworld; btSimplexAdd(simplex, &last); dir = -lastSupV; // start iterations for (int iterations = 0; iterations < gGjkMaxIter; iterations++) { // obtain support point btComputeSupport(m_minkowskiA, localTransA, m_minkowskiB, localTransB, dir, check2d, supAworld, supBworld, lastSupV); // check if farthest point in Minkowski difference in direction dir // isn't somewhere before origin (the test on negative dot product) // - because if it is, objects are not intersecting at all. btScalar delta = lastSupV.dot(dir); if (delta < 0) { //no intersection, besides margin status = -1; break; } // add last support vector to simplex last.v = lastSupV; last.v1 = supAworld; last.v2 = supBworld; btSimplexAdd(simplex, &last); // if btDoSimplex returns 1 if objects intersect, -1 if objects don't // intersect and 0 if algorithm should continue btVector3 newDir; int do_simplex_res = btDoSimplex(simplex, &dir); if (do_simplex_res == 1) { status = 0; // intersection found break; } else if (do_simplex_res == -1) { // intersection not found status = -1; break; } if (btFuzzyZero(btVec3Dot(&dir, &dir))) { // intersection not found status = -1; } if (dir.length2() < SIMD_EPSILON) { //no intersection, besides margin status = -1; break; } if (dir.fuzzyZero()) { // intersection not found status = -1; break; } } } m_simplexSolver->reset(); if (status == 0) { //status = 0; //printf("Intersect!\n"); } if (status == -1) { //printf("not intersect\n"); } //printf("dir=%f,%f,%f\n",dir[0],dir[1],dir[2]); if (1) { for (;;) //while (true) { btVector3 separatingAxisInA = (-m_cachedSeparatingAxis) * localTransA.getBasis(); btVector3 separatingAxisInB = m_cachedSeparatingAxis * localTransB.getBasis(); btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInA); btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInB); btVector3 pWorld = localTransA(pInA); btVector3 qWorld = localTransB(qInB); if (check2d) { pWorld[2] = 0.f; qWorld[2] = 0.f; } btVector3 w = pWorld - qWorld; delta = m_cachedSeparatingAxis.dot(w); // potential exit, they don't overlap if ((delta > btScalar(0.0)) && (delta * delta > squaredDistance * input.m_maximumDistanceSquared)) { m_degenerateSimplex = 10; checkSimplex = true; //checkPenetration = false; break; } //exit 0: the new point is already in the simplex, or we didn't come any closer if (m_simplexSolver->inSimplex(w)) { m_degenerateSimplex = 1; checkSimplex = true; break; } // are we getting any closer ? btScalar f0 = squaredDistance - delta; btScalar f1 = squaredDistance * REL_ERROR2; if (f0 <= f1) { if (f0 <= btScalar(0.)) { m_degenerateSimplex = 2; } else { m_degenerateSimplex = 11; } checkSimplex = true; break; } //add current vertex to simplex m_simplexSolver->addVertex(w, pWorld, qWorld); btVector3 newCachedSeparatingAxis; //calculate the closest point to the origin (update vector v) if (!m_simplexSolver->closest(newCachedSeparatingAxis)) { m_degenerateSimplex = 3; checkSimplex = true; break; } if (newCachedSeparatingAxis.length2() < REL_ERROR2) { m_cachedSeparatingAxis = newCachedSeparatingAxis; m_degenerateSimplex = 6; checkSimplex = true; break; } btScalar previousSquaredDistance = squaredDistance; squaredDistance = newCachedSeparatingAxis.length2(); #if 0 ///warning: this termination condition leads to some problems in 2d test case see Bullet/Demos/Box2dDemo if (squaredDistance > previousSquaredDistance) { m_degenerateSimplex = 7; squaredDistance = previousSquaredDistance; checkSimplex = false; break; } #endif // //redundant m_simplexSolver->compute_points(pointOnA, pointOnB); //are we getting any closer ? if (previousSquaredDistance - squaredDistance <= SIMD_EPSILON * previousSquaredDistance) { // m_simplexSolver->backup_closest(m_cachedSeparatingAxis); checkSimplex = true; m_degenerateSimplex = 12; break; } m_cachedSeparatingAxis = newCachedSeparatingAxis; //degeneracy, this is typically due to invalid/uninitialized worldtransforms for a btCollisionObject if (m_curIter++ > gGjkMaxIter) { #if defined(DEBUG) || defined(_DEBUG) printf("btGjkPairDetector maxIter exceeded:%i\n", m_curIter); printf("sepAxis=(%f,%f,%f), squaredDistance = %f, shapeTypeA=%i,shapeTypeB=%i\n", m_cachedSeparatingAxis.getX(), m_cachedSeparatingAxis.getY(), m_cachedSeparatingAxis.getZ(), squaredDistance, m_minkowskiA->getShapeType(), m_minkowskiB->getShapeType()); #endif break; } bool check = (!m_simplexSolver->fullSimplex()); //bool check = (!m_simplexSolver->fullSimplex() && squaredDistance > SIMD_EPSILON * m_simplexSolver->maxVertex()); if (!check) { //do we need this backup_closest here ? // m_simplexSolver->backup_closest(m_cachedSeparatingAxis); m_degenerateSimplex = 13; break; } } if (checkSimplex) { m_simplexSolver->compute_points(pointOnA, pointOnB); normalInB = m_cachedSeparatingAxis; btScalar lenSqr = m_cachedSeparatingAxis.length2(); //valid normal if (lenSqr < REL_ERROR2) { m_degenerateSimplex = 5; } if (lenSqr > SIMD_EPSILON * SIMD_EPSILON) { btScalar rlen = btScalar(1.) / btSqrt(lenSqr); normalInB *= rlen; //normalize btScalar s = btSqrt(squaredDistance); btAssert(s > btScalar(0.0)); pointOnA -= m_cachedSeparatingAxis * (marginA / s); pointOnB += m_cachedSeparatingAxis * (marginB / s); distance = ((btScalar(1.) / rlen) - margin); isValid = true; orgNormalInB = normalInB; m_lastUsedMethod = 1; } else { m_lastUsedMethod = 2; } } } bool catchDegeneratePenetrationCase = (m_catchDegeneracies && m_penetrationDepthSolver && m_degenerateSimplex && ((distance + margin) < gGjkEpaPenetrationTolerance)); //if (checkPenetration && !isValid) if ((checkPenetration && (!isValid || catchDegeneratePenetrationCase)) || (status == 0)) { //penetration case //if there is no way to handle penetrations, bail out if (m_penetrationDepthSolver) { // Penetration depth case. btVector3 tmpPointOnA, tmpPointOnB; m_cachedSeparatingAxis.setZero(); bool isValid2 = m_penetrationDepthSolver->calcPenDepth( *m_simplexSolver, m_minkowskiA, m_minkowskiB, localTransA, localTransB, m_cachedSeparatingAxis, tmpPointOnA, tmpPointOnB, debugDraw); if (m_cachedSeparatingAxis.length2()) { if (isValid2) { btVector3 tmpNormalInB = tmpPointOnB - tmpPointOnA; btScalar lenSqr = tmpNormalInB.length2(); if (lenSqr <= (SIMD_EPSILON * SIMD_EPSILON)) { tmpNormalInB = m_cachedSeparatingAxis; lenSqr = m_cachedSeparatingAxis.length2(); } if (lenSqr > (SIMD_EPSILON * SIMD_EPSILON)) { tmpNormalInB /= btSqrt(lenSqr); btScalar distance2 = -(tmpPointOnA - tmpPointOnB).length(); m_lastUsedMethod = 3; //only replace valid penetrations when the result is deeper (check) if (!isValid || (distance2 < distance)) { distance = distance2; pointOnA = tmpPointOnA; pointOnB = tmpPointOnB; normalInB = tmpNormalInB; isValid = true; } else { m_lastUsedMethod = 8; } } else { m_lastUsedMethod = 9; } } else { ///this is another degenerate case, where the initial GJK calculation reports a degenerate case ///EPA reports no penetration, and the second GJK (using the supporting vector without margin) ///reports a valid positive distance. Use the results of the second GJK instead of failing. ///thanks to Jacob.Langford for the reproduction case ///http://code.google.com/p/bullet/issues/detail?id=250 if (m_cachedSeparatingAxis.length2() > btScalar(0.)) { btScalar distance2 = (tmpPointOnA - tmpPointOnB).length() - margin; //only replace valid distances when the distance is less if (!isValid || (distance2 < distance)) { distance = distance2; pointOnA = tmpPointOnA; pointOnB = tmpPointOnB; pointOnA -= m_cachedSeparatingAxis * marginA; pointOnB += m_cachedSeparatingAxis * marginB; normalInB = m_cachedSeparatingAxis; normalInB.normalize(); isValid = true; m_lastUsedMethod = 6; } else { m_lastUsedMethod = 5; } } } } else { //printf("EPA didn't return a valid value\n"); } } } } if (isValid && ((distance < 0) || (distance * distance < input.m_maximumDistanceSquared))) { m_cachedSeparatingAxis = normalInB; m_cachedSeparatingDistance = distance; if (1) { ///todo: need to track down this EPA penetration solver degeneracy ///the penetration solver reports penetration but the contact normal ///connecting the contact points is pointing in the opposite direction ///until then, detect the issue and revert the normal btScalar d2 = 0.f; { btVector3 separatingAxisInA = (-orgNormalInB) * localTransA.getBasis(); btVector3 separatingAxisInB = orgNormalInB * localTransB.getBasis(); btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInA); btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInB); btVector3 pWorld = localTransA(pInA); btVector3 qWorld = localTransB(qInB); btVector3 w = pWorld - qWorld; d2 = orgNormalInB.dot(w) - margin; } btScalar d1 = 0; { btVector3 separatingAxisInA = (normalInB)*localTransA.getBasis(); btVector3 separatingAxisInB = -normalInB * localTransB.getBasis(); btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInA); btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInB); btVector3 pWorld = localTransA(pInA); btVector3 qWorld = localTransB(qInB); btVector3 w = pWorld - qWorld; d1 = (-normalInB).dot(w) - margin; } btScalar d0 = 0.f; { btVector3 separatingAxisInA = (-normalInB) * input.m_transformA.getBasis(); btVector3 separatingAxisInB = normalInB * input.m_transformB.getBasis(); btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInA); btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(separatingAxisInB); btVector3 pWorld = localTransA(pInA); btVector3 qWorld = localTransB(qInB); btVector3 w = pWorld - qWorld; d0 = normalInB.dot(w) - margin; } if (d1 > d0) { m_lastUsedMethod = 10; normalInB *= -1; } if (orgNormalInB.length2()) { if (d2 > d0 && d2 > d1 && d2 > distance) { normalInB = orgNormalInB; distance = d2; } } } output.addContactPoint( normalInB, pointOnB + positionOffset, distance); } else { //printf("invalid gjk query\n"); } }
412
0.977057
1
0.977057
game-dev
MEDIA
0.976596
game-dev
0.993947
1
0.993947
g3arshift/Space-Engineers-Mod-Manager
2,547
src/main/java/com/gearshiftgaming/se_mod_manager/backend/data/ModListProfileJaxbSerializer.java
package com.gearshiftgaming.se_mod_manager.backend.data; import com.gearshiftgaming.se_mod_manager.backend.models.ModListProfile; import com.gearshiftgaming.se_mod_manager.backend.models.Result; import com.gearshiftgaming.se_mod_manager.backend.models.ResultType; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; import java.io.*; import static org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace; /** * Copyright (C) 2025 Gear Shift Gaming - All Rights Reserved * You may use, distribute, and modify this code under the terms of the GPL3 license. * <p> * You should have received a copy of the GPL3 license with * this file. If not, please write to: gearshift@gearshiftgaming.com. */ public abstract class ModListProfileJaxbSerializer { public Result<ModListProfile> importModlist(File modlistLocation) { Result<ModListProfile> modlistProfileResult = new Result<>(); try { JAXBContext context = JAXBContext.newInstance(ModListProfile.class); Unmarshaller unmarshaller = context.createUnmarshaller(); ModListProfile modListProfile = (ModListProfile) unmarshaller.unmarshal(modlistLocation); modlistProfileResult.addMessage("Successfully loaded mod profile.", ResultType.SUCCESS); modlistProfileResult.setPayload(modListProfile); } catch (JAXBException e) { modlistProfileResult.addMessage("Failed to load mod profile. Error Details: " + e, ResultType.FAILED); } return modlistProfileResult; } public Result<Void> exportModlist(ModListProfile modListProfile, File modlistLocation) { ModListProfile copiedProfile = new ModListProfile(modListProfile); Result<Void> result = new Result<>(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(modlistLocation))) { JAXBContext context = JAXBContext.newInstance(ModListProfile.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); marshaller.marshal(copiedProfile, sw); bw.write(sw.toString()); result.addMessage("Successfully exported modlist.", ResultType.SUCCESS); } catch (JAXBException | IOException e) { result.addMessage(getStackTrace(e), ResultType.FAILED); } return result; } }
412
0.676835
1
0.676835
game-dev
MEDIA
0.273677
game-dev
0.842736
1
0.842736
sigeer/RuaMS
2,808
src/Application.Resources/scripts/event/AreaBossKingClang.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** -- Odin JavaScript -------------------------------------------------------------------------------- King Clang Spawner -- Edited by -------------------------------------------------------------------------------------- ThreeStep - based on xQuasar's King Clang spawner **/ var hotSand; function init() { hotSand = em.GetMap(110040000); scheduleNew(); } function scheduleNew() { setupTask = em.schedule("start", 0); //spawns upon server start. Each 3 hours an server event checks if boss exists, if not spawns it instantly. } function cancelSchedule() { if (setupTask != null) { setupTask.cancel(true); } } function start() { if (hotSand.getMonsterById(5220001) != null) { em.schedule("start", 3 * 60 * 60 * 1000); return; } var kingClang = LifeFactory.getMonster(5220001); var posX; var posY = 140; posX = Math.floor((Math.random() * 2400) - 1600); const spawnpoint = new Point(posX, posY); hotSand.spawnMonsterOnGroundBelow(kingClang, spawnpoint); hotSand.broadcastMessage(PacketCreator.serverNotice(6, "A strange turban shell has appeared on the beach.")); em.schedule("start", 3 * 60 * 60 * 1000); } // ---------- FILLER FUNCTIONS ---------- function dispose() { } function setup(eim, leaderid) { } function monsterValue(eim, mobid) { return 0; } function disbandParty(eim, player) { } function playerDisconnected(eim, player) { } function playerEntry(eim, player) { } function monsterKilled(mob, eim) { } function scheduledTimeout(eim) { } function afterSetup(eim) { } function changedLeader(eim, leader) { } function playerExit(eim, player) { } function leftParty(eim, player) { } function clearPQ(eim) { } function allMonstersDead(eim) { } function playerUnregistered(eim, player) { }
412
0.565131
1
0.565131
game-dev
MEDIA
0.932597
game-dev
0.65697
1
0.65697
ggnkua/Atari_ST_Sources
14,191
ASM/Digi Tallis/INTRO/MUG_5.S
* Intro for Mug Uk * Coded by ()rm of Digi Tallis of Humbug * (C) Humbug 1993/1994/eternity * The starfield rout may look like it can handle verticle starfields * but it CAN'T! Horizontal only! This is cos I was blind drunk when * I wrote the routine! Usually the best way to code, but not this time.. * Right, here we go with the explanation * If you whack space it will jump to QUIT_ALL. This is where you put your * usual trainer code. * I haven't made it so you include the game file. Either you do it, or you * give it to M.S.D. But I've been too busy on a game. Soz 'bout that.. * BUT! You DO get a rather nice point plotter. By all means spread it.. * If you want to change then sprite..tough! ;) Nah, drop us an e-mail, * and I'll send you the creator.. * Change the stars? Again, drop us an e-mail.. * Change the textprint font. nope. nah nah nah.. * Change the scrolly font. As above.. e-mail us. * Have fun matey, and I hope you like it. Would make a rather nice menu * for Magic Sector if you don't use it! opt x-,ow+ X_SPEED equ 4 ;change for sprite Y_SPEED equ 5 ;change for sprite. NUM_STARS equ 130 clr.l -(sp) move.w #$20,-(sp) trap #1 addq.w #6,sp move.l d0,savesp lea $80000,sp ;whack the stack in free space * Main Branch Table!! * bsr screen_in bsr store_p bsr pal_in rept 2 bsr clear_base jsr text_print bsr flipper endr move.w #1,d0 jsr music ;jess tune AHOY! bsr save_othershit bsr new_vecs **** You wanna wait a vbl? just JSR WAIT_VBL etern jsr wait_vbl move.l old_old_sprite_x_pos,d0 move.l old_old_sprite_y_pos,d1 jsr clear_sprite jsr calc_y_pos jsr calc_x_pos move.l sprite_x_pos,d0 move.l sprite_y_pos,d1 jsr draw_sprite move.l old_sprite_x_pos,old_old_sprite_x_pos move.l old_sprite_y_pos,old_old_sprite_y_pos move.l sprite_x_pos,old_sprite_x_pos move.l sprite_y_pos,old_sprite_y_pos jsr scroll_rout jsr copy_scroll jsr clear_points jsr do_starfield jsr flipper bra etern quit_all jsr music+4 bsr bang_um_back bsr pal_out bsr screen_out usr move.l savesp,-(sp) move.w #$20,-(sp) trap #1 addq.w #6,sp clr.w -(sp) trap #1 ********* Insert Relocation Code Here ! ********* Code from here on in.. screen_in move.w #0,-(sp) move.l base,-(sp) move.l base,-(sp) move.w #$5,-(sp) trap #14 add.w #12,sp rts screen_out move.w #0,-(sp) move.l #-1,-(sp) move.l #-1,-(sp) move.w #$5,-(sp) trap #14 add.w #12,sp rts pal_in move.l #pal,-(sp) move.w #$6,-(sp) trap #14 addq.w #6,sp rts pal_out move.l #gempal,-(sp) move.w #$6,-(sp) trap #14 addq.w #6,sp rts store_p movem.l $ffff8240.w,d0-d7 movem.l d0-d7,gempal rts clear_base move.l base,a0 move.w #32000-1,d0 clear_it clr.b (a0)+ dbra d0,clear_it rts flipper move.l base,nxt_base add.l #4,base_place lea flipper_dat,a0 add.l base_place,a0 cmpi.w #$ffffffff,(a0) bne go_flipper clr.l base_place lea flipper_dat,a0 go_flipper move.l (a0),base flip_screens move #$8201,a0 move.l base,d0 lsr.l #8,d0 movep d0,(a0) rts save_othershit move.l $70.w,old_vbl move.l $120.w,old_hbl move.b $fffffa1b,old_a1b move.b $fffffa21,old_a21 move.b $fffffa07,old_a07 move.b $fffffa09,old_a09 move.b $fffffa13,old_a13 move.b $fffffa15,old_a15 rts bang_um_back move.w #$2700,sr move.l old_vbl,$70.w move.l old_hbl,$120.w move.b old_a1b,$fffffa1b.w move.b old_a21,$fffffa21.w move.b old_a07,$fffffa07.w move.b old_a09,$fffffa09.w move.b old_a13,$fffffa13.w move.b old_a15,$fffffa15.w move.w #$2300,sr rts new_vecs move.w #$2700,sr ;tell everythinn to shut up move.l #vbl,$70.w move.l #hbl,$120.w clr.b $fffffa09.w move.b #1,$fffffa07 move.b #1,$fffffa13.w clr.b $fffffa1b.w bclr.b #6,$fffffa15 ;take no stick move.w #$2300,sr rts wait_vbl cmp.b #1,vbl_flag bne.s wait_vbl clr.b vbl_flag rts vbl cmpi.b #185,$fffc02 ;compare for space.. bne.s .no_space lea quit_all,a0 jmp (a0) .no_space clr.b $fffffa1b.w ;stop b move.b #2,$fffffa21 ;timer b count lea raster_cols,a6 move.b #8,$fffffa1b.w ;start b jsr music+8 ;yeah.... move.b #1,vbl_flag ;set it so other routs can go NOW! rte hbl move.w (a6)+,$ff8240 move.w (a6),$ff8250 move.w (a6),$ff8252 move.w (a6),$ff8254 move.w (a6),$ff8256 move.w (a6),$ff8258 move.w (a6),$ff825a move.w (a6)+,$ff825c bclr #0,$fffffa0f.w rte raster_cols ;first colour is the BACKGROUND colour ;second is the text and scroller colours! rept 31 ;text colours.. dc.w $0,$750 ;a total of 93 colours. dc.w $0,$720 ;if you change them, you MUST have dc.w $0,$600 ;93 colours! endr dc.w $0,$000 ;must be black dc.w $1,$322 ;don't ask! dc.w $3,$544 ;scroller colours dc.w $4,$777 dc.w $3,$544 dc.w $2,$322 dc.w $0,$0 even *********** Whack all your CODE here!! scroll_rout addq.w #1,bit_count ;add 1 to rol counter cmpi.w #9,bit_count ;compare it to end of word bne.s scroll_main ;NOOO clr.w bit_count scroll_update addq.w #1,letter lea text,a0 add.w letter,a0 cmpi.b #$ff,(a0) bne.s scroll_next_letter lea text,a0 clr.w letter scroll_next_letter moveq.w #0,d0 move.b (a0)+,d0 sub.w #32,d0 mulu.w #16,d0 lea font,a0 add.w d0,a0 lea temp_buffer,a1 rept 8 ; Y move.w (a0)+,(a1)+ endr scroll_main lea scroll_buffer,a0 add.l #2*160,a0 lea temp_buffer,a1 rept 8 ; Y roxl (a1) roxl.w 152(a0) roxl.w 144(a0) roxl.w 136(a0) roxl.w 128(a0) roxl.w 120(a0) roxl.w 112(a0) roxl.w 104(a0) roxl.w 96(a0) roxl.w 88(a0) roxl.w 80(a0) roxl.w 72(a0) roxl.w 64(a0) roxl.w 56(a0) roxl.w 48(a0) roxl.w 40(a0) roxl.w 32(a0) roxl.w 24(a0) roxl.w 16(a0) roxl.w 8(a0) roxl.w (a0) lea 160(a0),a0 addq.w #2,a1 endr rts copy_scroll add.l #4,scroll_place_y lea scroll_place_data,a0 add.l scroll_place_y,a0 cmpi.l #$ffffffff,(a0) bne.s .no_such_luck clr.l scroll_place_y lea scroll_place_data,a0 add.l scroll_place_y,a0 .no_such_luck move.l nxt_base,a1 move.l (a0),d0 mulu #160,d0 add.l d0,a1 add.l #6,a1 lea scroll_buffer,a2 i set 0 rept 12*20 ;copy_scroller move.w i(a2),i(a1) i set i+8 endr rts scroll_place_data dc.l 188,188,188,188,189,189 dc.l 190,191,191,192,192,192,192 dc.l 191,191,190,189,189 dc.l $ffffffff,$ffffffff,$ffffffff,$ffffffff even scroll_place_y dc.l 0 even ;pass in text location in a0 text_print clr.l bit_place lea test_text,a0 move.l x_text_pos,d0 move.l y_text_pos,d1 go_printer cmpi.b #0,(a0) ;terminate text!! beq quit_text_print cmpi.b #13,(a0) ;return to beginning of line. beq back_to_beginning cmpi.b #10,(a0) ;down a line. beq down_a_line cmp.b #32,(a0) ;less than space blt no_print cmp.b #126,(a0) ;bigger than lower z bgt no_print move.l base,a1 ;\ add.l #4,a1 add.l d0,a1 ;-get right place on screen! add.l d1,a1 ;/ lea text_font,a2 moveq.l #0,d2 move.b (a0)+,d2 ;store letter in data reg! sub.b #32,d2 ;right in bank lsl.l #3,d2 ;mulu #8,d2 add.l d2,a2 rept 8 move.b (a2)+,d3 or.b d3,0(a1) or.b d3,2(a1) lea 160(a1),a1 endr cmp.l #1,bit_place beq.s second_8 add.l #1,bit_place addq.l #1,d0 bra.s compare_for_end second_8 move.l #0,bit_place addq.l #7,d0 compare_for_end cmp.l #160,d0 beq.s back_and_down bra go_printer quit_text_print rts back_and_down move.l x_text_pos,d0 move.l #0,bit_place bra.s down_a_line bra go_printer ;security reasons!!! (ahah! lazy!) back_to_beginning addq.l #1,a0 move.l x_text_pos,d0 move.l #0,bit_place bra go_printer down_a_line addq.l #1,a0 add.l #(160*6),d1 cmp.l #(180*160),d1 bge.s quit_text_print bra go_printer no_print addq.l #1,a0 bra go_printer calc_x_pos move.l x_sprite_add,d1 add.l d1,sprite_x_pointer cmpi.l #(319*8),sprite_x_pointer ble.s .ok_pointy sub.l #(319*8),sprite_x_pointer .ok_pointy move.w x_sprite_amplitude,amplitude move.l sprite_x_pointer,pointer move.l x_sprite_origin,origin jsr sine_rout move.l d0,sprite_x_pos rts calc_y_pos move.l y_sprite_add,d1 add.l d1,sprite_y_pointer cmpi.l #(319*8),sprite_y_pointer ble.s .ok_pointy sub.l #(319*8),sprite_y_pointer .ok_pointy move.w y_sprite_amplitude,amplitude move.l sprite_y_pointer,pointer move.l y_sprite_origin,origin jsr sine_rout move.l d0,sprite_y_pos rts sine_rout ********************************************************* * sine calulator (un-optimised version 1) * * amplitude :amp of wave * * pointer :pointer into sine bank * * result :returned in d0 * * NB:- pointer = (deg*8) (can go by .5 degs) * * Mag of Digi Tallis (HUMBUG) * ********************************************************* lea sine,a0 moveq.l #0,d0 add.l pointer,a0 move.w (a0)+,d1 move.w (a0)+,d0 mulu.w amplitude,d0 asr.l #8,d0 cmpi.w #1,d1 bne.s positive moveq.l #0,d2 sub.l d0,d2 move.l d2,d0 positive add.l origin,d0 rts ***************************************** * data for sinerout * ***************************************** amplitude dc.w 0 even origin dc.l 0 sine rept 2 incbin sine.bin endr even pointer dc.l 0 even ***************************************** draw_sprite ;d0 = X d1 = Y mulu #160,d1 ;down screen move.l d0,d2 and.l #$f,d2 ;frame numba sub.l d2,d0 ;down to 16 lsr.l #1,d0 ;down to 8 mulu #3800,d2 ;to get correct place move.l nxt_base,a0 add.l #2,a0 add.l d1,a0 ;down screen add.l d0,a0 ;across screen lea mug_sprite,a1 add.l d2,a1 i set 0 rept 95 move.l (a1)+,i(a0) move.l (a1)+,i+8(a0) move.l (a1)+,i+16(a0) move.l (a1)+,i+24(a0) move.l (a1)+,i+32(a0) move.l (a1)+,i+40(a0) move.l (a1)+,i+48(a0) move.l (a1)+,i+56(a0) move.l (a1)+,i+64(a0) move.l (a1)+,i+72(a0) i set i+160 endr rts clear_sprite ;d0 = X d1 = Y mulu #160,d1 ;down screen move.l d0,d2 and.l #$f,d2 ;frame numba sub.l d2,d0 ;down to 16 lsr.l #1,d0 ;down to 8 mulu #3800,d2 ;to get correct place move.l nxt_base,a0 add.l #2,a0 add.l d1,a0 ;down screen add.l d0,a0 ;across screen lea mug_sprite,a1 add.l d2,a1 moveq.l #0,d0 i set 0 rept 95 move.l d0,i(a0) move.l d0,i+8(a0) move.l d0,i+16(a0) move.l d0,i+24(a0) move.l d0,i+32(a0) move.l d0,i+40(a0) move.l d0,i+48(a0) move.l d0,i+56(a0) move.l d0,i+64(a0) move.l d0,i+72(a0) i set i+160 endr rts point_plot opt o+,w- ;LEAVE THIS IN! To get the extra 10! ;d0=x d1=y ;910 1 colour points per frame ;If you use this, PLEASE credit me..cheers.. ;(C) ()rm of Digi Tallis of Humbug ;(C) Humbug 1993/1994/eternity move.l nxt_base,a0 ;screen lsl.l #2,d1 ;mulitply by 4 add.l mulu_table(pc,d1.l),a0 ;add right multiple of 160 lea point_data,a1 ;The actual point plot lsl.l #3,d0 ;multiply by 8 jmp (a1,d0.l) ;jmp da fnuker mulu_table i set 0 rept 200 dc.l i*160 i set i+1 endr even point_data i set 0 rept 40 or.w #32768,i(a0) rts or.w #16384,i(a0) rts or.w #8192,i(a0) rts or.w #4096,i(a0) rts or.w #2048,i(a0) rts or.w #1024,i(a0) rts or.w #512,i(a0) rts or.w #256,i(a0) rts or.w #128,i(a0) rts or.w #64,i(a0) rts or.w #32,i(a0) rts or.w #16,i(a0) rts or.w #8,i(a0) rts or.w #4,i(a0) rts or.w #2,i(a0) rts or.w #1,i(a0) rts i set i+8 endr opt o-,w+ ;LEAVE THIS IN! clear_points lea star_y,a3 moveq.w #0,d1 move.l #NUM_STARS-1,d5 .loop move.l (a3)+,d0 mulu #160,d0 ;down screen move.l nxt_base,a0 add.l d0,a0 i set 8 rept 18 move.w d1,i(a0) i set i+8 endr dbf d5,.loop rts move_stars lea star_x,a2 lea star_speed,a3 move.l #NUM_STARS-1,d5 .loop move.l (a2),d4 add.l (a3)+,d4 cmp.l #300,d4 blt .nope move.w #20,d4 .nope move.l d4,(a2)+ dbf d5,.loop rts do_starfield lea star_x,a2 lea star_y,a3 move.l #NUM_STARS-1,d5 ;num of stars .loop move.l (a2)+,d0 move.l (a3)+,d1 jsr point_plot dbf d5,.loop jsr move_stars rts ***************************************************************** * data * ***************************************************************** vbl_flag dc.b 0 savesp dc.l 0 pal dc.w $000,$070,$666,$666,$444,$444,$222,$222,$000,$000,$000,$000,$000,$000,$000,$000 gempal ds.w 16 base dc.l $70000 nxt_base dc.l $78000 flipper_dat dc.l $70000,$78000,$ffffffff base_place dc.l 0 old_vbl dc.l 0 old_hbl dc.l 0 old_a1b dc.b 0 old_a21 dc.b 0 old_a07 dc.b 0 old_a09 dc.b 0 old_a13 dc.b 0 old_a15 dc.b 0 old_x_positions ds.l NUM_STARS old_y_positions ds.l NUM_STARS old_old_x_positions ds.l NUM_STARS old_old_y_positions ds.l NUM_STARS x_text_pos dc.l 0 y_text_pos dc.l 1*160 bit_place dc.l 0 scroll_buffer ds.w 160*12 bit_count dc.w 0 temp_buffer ds.w 32 letter dc.w 0 sprite_x_pos dc.l 0 old_sprite_x_pos dc.l 0 old_old_sprite_x_pos dc.l 0 x_sprite_add dc.l X_SPEED*4 sprite_x_pointer dc.l 0 x_sprite_amplitude dc.w 80 x_sprite_origin dc.l 96 sprite_y_pos dc.l 0 old_sprite_y_pos dc.l 0 old_old_sprite_y_pos dc.l 0 y_sprite_add dc.l Y_SPEED*4 sprite_y_pointer dc.l 0 y_sprite_amplitude dc.w 47 y_sprite_origin dc.l 51 get_pos dc.l 0 test_text dc.b " __ __ __ __ _____ __ __ __",13,10 dc.b "/ \ / \ / I I \ / _ I / I I I/ /",13,10 dc.b "I \_/ I I I_I I I I_I I I I_I ( ",13,10 dc.b "I I\_/I I I_____I \____ I I I\ I",13,10 dc.b "I I I I _ I I \_____/I I",13,10 dc.b "I I I I / \_________/ / I I",13,10 dc.b "\__) (__/ \____________/ I_/",13,10 dc.b " ()rm",13,10 dc.b 13,10,13,10 dc.b "Yup. Thats right, its an 8 * 6 font!",13,10 dc.b "So that means more text on screen",13,10 dc.b "than usual... nice huh?",13,10 dc.b 13,10,13,10 dc.b "All code by ()rm of Digi Tallis",13,10 dc.b "(C) Humbug 1994/eternity",13,10 dc.b 0,0,0,0,0,0,0,0 even text dc.b " A-one-two-three-four.... HURL! " dc.b " Yup. Another intro for somebody else! " dc.b " All code by ()rm of Digi Tallis of Humbug" dc.b " (C) Humbug 1994/eternity " dc.b " " dc.b $ff,$ff,$ff even font incbin smallfnt.bin even music incbin jess1.mus even star_x incbin star_x.bin even star_y incbin star_y.bin even star_speed incbin star_spd.bin even mug_sprite incbin mug_uk.spr even text_font incbin win_fnt.bin even even
412
0.807455
1
0.807455
game-dev
MEDIA
0.639192
game-dev
0.991897
1
0.991897
VoxelSrv/voxelsrv
4,779
src/index.ts
import { isMobile } from 'mobile-device-detect'; import Engine2, { Engine } from 'noa-engine'; import * as BABYLON from '@babylonjs/core/Legacy/legacy'; import { rebindControls, setupControls } from './lib/player/controls'; import { defineModelComp } from './lib/helpers/model'; import { noaOpts, updateSettings, serverSettings, defaultFonts, setNoa, updateServerSettings, IGameSettings, defaultValues, gameSettings, gameVersion, singleplayerWorldTypes, singleplayerServerInfo, setAuthInfo, } from './values'; import { constructScreen, getScreen } from './gui/main'; import { getAuthData, getSettings } from './lib/helpers/storage'; import { setupClouds, setupSky } from './lib/gameplay/sky'; import { buildMainMenu } from './gui/menu/main'; import { connect, setupConnection } from './lib/gameplay/connect'; import { setupMobile } from './gui/mobile'; import { setupGamepad } from './lib/player/gamepad'; import { createInflateWorker, setupWorld } from './lib/gameplay/world'; import { setupToasts } from './gui/parts/toastMessage'; import { createProtocolWorker } from './socket'; import { PopupGUI } from './gui/parts/miniPopupHelper'; import { createSingleplayerServer } from './lib/singleplayer/setup'; defaultFonts.forEach((font) => document.fonts.load(`10pt "${font}"`)); getSettings().then(async (data: IGameSettings) => { updateSettings(data); // @ts-ignore const tempNoa = new Engine2(noaOpts()); const noa: Engine = tempNoa; constructScreen(noa); const loading = new PopupGUI([{ text: 'Loading...' }]); loading.setCenterText([{ text: 'Starting...' }]); getScreen(2).addControl(loading.main); const canvas: HTMLCanvasElement = noa.container.canvas; canvas.onwheel = function (event) { event.preventDefault(); }; window.addEventListener('beforeunload', function (e) { e.preventDefault(); e.returnValue = ''; }); canvas.addEventListener('keydown', (e) => { if (e.key == ' ') { e.preventDefault(); } }); rebindControls(noa, gameSettings.controls); noa.world.maxChunksPendingCreation = Infinity; noa.ents.createComponent({ name: 'inventory', state: { items: {}, selected: 0, tempslot: {}, armor: {}, crafting: {} }, }); setNoa(noa); noa.ents.getPhysics(noa.playerEntity).body.airDrag = 9999; setupToasts(); setupClouds(noa); setupSky(noa); defineModelComp(noa); const scene = noa.rendering.getScene(); scene.fogMode = defaultValues.fogMode; scene.fogStart = defaultValues.fogStart; scene.fogEnd = defaultValues.fogEnd; scene.fogDensity = defaultValues.fogDensity; scene.fogColor = new BABYLON.Color3(...defaultValues.fogColor); setupControls(noa); setupGamepad(noa); setupWorld(noa); let x = 0; noa.on('beforeRender', async () => { if (!serverSettings.ingame) { x++; noa.camera.heading = x / 2000; noa.camera.pitch = 0; } }); document.addEventListener( 'pointerlockchange', () => { if (!isMobile) { if (document.pointerLockElement == noa.container.canvas) { noa.ignorePointerLock = true; noa.ents.getState(noa.playerEntity, 'receivesInputs').ignore = false; } else { noa.ignorePointerLock = false; noa.ents.getState(noa.playerEntity, 'receivesInputs').ignore = true; } } else { } }, false ); loading.setCenterText([{ text: 'Creating workers...' }]); await createProtocolWorker(); await createInflateWorker(); loading.setCenterText([{ text: 'Checking login data...' }]); setAuthInfo(await getAuthData(), false); loading.setCenterText([{ text: 'Finishing...' }]); window['connect'] = (x) => { connect(noa, x); }; window['enableDebugSettings'] = () => { gameSettings.debugSettings.makeSettingsVisible = true; }; window['forceplay'] = () => { updateServerSettings({ ingame: true }); }; if (isMobile) { setupMobile(noa); const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'mobile.css'; document.head.appendChild(link); document.documentElement.addEventListener('click', function () { if (!document.fullscreenElement) { document.documentElement.requestFullscreen(); screen.orientation.lock('landscape'); } }); } // Default actions const options = new URLSearchParams(window.location.search); loading.dispose(); if (!!options.get('server')) { connect(noa, options.get('server')); } if (options.get('debugWorld') != undefined) { const socket = createSingleplayerServer('debugWorld', { gamemode: 'creative', gameVersion: gameVersion, serverVersion: '', worldsize: 32, version: 0, seed: 2021, generator: singleplayerWorldTypes[0], icon: 'voxelsrv', displayName: 'debugWorld' }, true); setupConnection(noa, socket, {...singleplayerServerInfo, motd: 'debugWorld' }); } else { buildMainMenu(noa); } });
412
0.938621
1
0.938621
game-dev
MEDIA
0.791318
game-dev
0.983926
1
0.983926
leighmacdonald/uncletopia
1,204
roles/sourcemod/files/addons/sourcemod/scripting/include/stocksoup/maps.inc
/** * Function stock to deal with maps and map names. */ #if defined __stocksoup_maps_included #endinput #endif #define __stocksoup_maps_included /** * Returns the workshop ID for the specified full map path, or 0 if the map does not have a * workshop ID. */ stock int GetMapWorkshopID(const char[] fullMapName) { EngineVersion currentGame = GetEngineVersion(); if (StrContains(fullMapName, "workshop/") == 0) { if (currentGame == Engine_TF2) { if (StrContains(fullMapName, ".ugc") > -1 ) { // workshop/some_map_name.ugc123456789 return StringToInt( fullMapName[ StrContains(fullMapName, ".ugc") + 4 ] ); } else { // workshop/123456789 return StringToInt( fullMapName[ StrContains(fullMapName, "/") + 1 ] ); } } // TODO other formats for workshop map names if (currentGame == Engine_CSGO) { // workshop/123456789/some_map_name ? int id; StringToIntEx(fullMapName[FindCharInString(fullMapName, '/') + 1], id); return id; } } return 0; } /** * Returns the current map's display name. */ stock bool GetCurrentMapDisplayName(char[] buffer, int maxlen) { GetCurrentMap(buffer, maxlen); return GetMapDisplayName(buffer, buffer, maxlen); }
412
0.707019
1
0.707019
game-dev
MEDIA
0.871011
game-dev
0.673106
1
0.673106
MARUI-PlugIn/BlenderXR
2,149
blender/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConstraintSolver.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_CONSTRAINT_SOLVER_H #define BT_CONSTRAINT_SOLVER_H #include "LinearMath/btScalar.h" class btPersistentManifold; class btRigidBody; class btCollisionObject; class btTypedConstraint; struct btContactSolverInfo; struct btBroadphaseProxy; class btIDebugDraw; class btStackAlloc; class btDispatcher; /// btConstraintSolver provides solver interface enum btConstraintSolverType { BT_SEQUENTIAL_IMPULSE_SOLVER=1, BT_MLCP_SOLVER=2, BT_NNCG_SOLVER=4 }; class btConstraintSolver { public: virtual ~btConstraintSolver() {} virtual void prepareSolve (int /* numBodies */, int /* numManifolds */) {;} ///solve a group of constraints virtual btScalar solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifold,int numManifolds,btTypedConstraint** constraints,int numConstraints, const btContactSolverInfo& info,class btIDebugDraw* debugDrawer,btDispatcher* dispatcher) = 0; virtual void allSolved (const btContactSolverInfo& /* info */,class btIDebugDraw* /* debugDrawer */) {;} ///clear internal cached data and reset random seed virtual void reset() = 0; virtual btConstraintSolverType getSolverType() const=0; }; #endif //BT_CONSTRAINT_SOLVER_H
412
0.721004
1
0.721004
game-dev
MEDIA
0.987366
game-dev
0.843147
1
0.843147
gcp/Leela
26,054
GTP.cpp
#include <vector> #include <iostream> #include <fstream> #include <cstdlib> #include <cctype> #include <string> #include <sstream> #include <cmath> #include <climits> #include <algorithm> #include "config.h" #include "Utils.h" #include "GameState.h" #include "GTP.h" #include "Playout.h" #include "UCTSearch.h" #include "UCTNode.h" #include "SGFTree.h" #include "AttribScores.h" #include "PNSearch.h" #include "Network.h" #include "Book.h" #include "TTable.h" #include "MCPolicy.h" using namespace Utils; // Configuration flags bool cfg_allow_pondering; bool cfg_allow_book; int cfg_num_threads; int cfg_max_playouts; bool cfg_enable_nets; bool cfg_komi_adjust; int cfg_mature_threshold; int cfg_expand_threshold; int cfg_lagbuffer_cs; #ifdef USE_OPENCL std::vector<int> cfg_gpus; int cfg_rowtiles; #endif float cfg_bound; float cfg_fpu; float cfg_cutoff_offset; float cfg_cutoff_ratio; float cfg_puct; float cfg_uct; float cfg_psa; float cfg_softmax_temp; float cfg_mix_opening; float cfg_mix_ending; float cfg_mc_softmax; int cfg_eval_thresh; float cfg_beta; float cfg_patternbonus; int cfg_rave_moves; int cfg_extra_symmetry; int cfg_random_loops; std::string cfg_logfile; FILE* cfg_logfile_handle; bool cfg_quiet; void GTP::setup_default_parameters() { cfg_allow_pondering = true; cfg_allow_book = true; cfg_num_threads = std::max(1, std::min(SMP::get_num_cpus(), MAX_CPUS)); cfg_enable_nets = true; cfg_komi_adjust = false; #ifdef USE_OPENCL cfg_mature_threshold = 25; cfg_extra_symmetry = 350; cfg_eval_thresh = 2; #else cfg_mature_threshold = 85; cfg_extra_symmetry = 3000; cfg_eval_thresh = 9; #endif cfg_max_playouts = INT_MAX; cfg_lagbuffer_cs = 100; #ifdef USE_OPENCL cfg_gpus = { }; cfg_rowtiles = 5; #endif cfg_bound = 32.0f; cfg_fpu = 1.1f; cfg_puct = 1.1f; cfg_psa = 0.0018f; #ifdef USE_SEARCH cfg_softmax_temp = 0.75f; #else cfg_softmax_temp = 0.094f; #endif cfg_cutoff_offset = 25.44f; cfg_cutoff_ratio = 4.72f; cfg_mix_opening = 0.66f; cfg_mix_ending = 0.49f; cfg_rave_moves = 10; cfg_mc_softmax = 1.0f; cfg_random_loops = 4; cfg_logfile_handle = nullptr; cfg_quiet = false; } bool GTP::perform_self_test(GameState & state) { bool testPassed = true; #ifdef USE_OPENCL #ifndef USE_TUNER myprintf("OpenCL self-test: "); // Perform self-test auto vec = Network::get_Network()->get_scored_moves( &state, Network::Ensemble::DIRECT, 0); testPassed &= vec[60].first > 0.176 && vec[60].first < 0.177; testPassed &= vec[60].second == 88; testPassed &= vec[72].first > 0.175 && vec[72].first < 0.176; testPassed &= vec[72].second == 100; if (testPassed) { myprintf("passed.\n"); } else { myprintf("failed. Check your OpenCL drivers.\n"); } #endif #endif return testPassed; } const std::string GTP::s_commands[] = { "protocol_version", "name", "version", "quit", "known_command", "list_commands", "quit", "boardsize", "clear_board", "komi", "play", "genmove", "showboard", "undo", "final_score", "final_status_list", "time_settings", "time_left", "fixed_handicap", "place_free_handicap", "set_free_handicap", "loadsgf", "printsgf", "kgs-genmove_cleanup", "kgs-time_settings", "kgs-game_over", "influence", "mc_score", "mc_winrate", "vn_winrate", "winrate", "heatmap", "" }; std::string GTP::get_life_list(GameState & game, bool live) { std::vector<std::string> stringlist; std::string result; FastBoard & board = game.board; std::vector<bool> dead = game.mark_dead(); for (int i = 0; i < board.get_boardsize(); i++) { for (int j = 0; j < board.get_boardsize(); j++) { int vertex = board.get_vertex(i, j); if (board.get_square(vertex) != FastBoard::EMPTY) { if (live ^ dead[vertex]) { stringlist.push_back(board.get_string(vertex)); } } } } // remove multiple mentions of the same string // unique reorders and returns new iterator, erase actually deletes std::sort(stringlist.begin(), stringlist.end()); stringlist.erase(std::unique(stringlist.begin(), stringlist.end()), stringlist.end()); for (size_t i = 0; i < stringlist.size(); i++) { result += (i == 0 ? "" : "\n") + stringlist[i]; } return result; } bool GTP::execute(GameState & game, std::string xinput) { std::string input; bool transform_lowercase = true; // Required on Unixy systems if (xinput.find("loadsgf") != std::string::npos) { transform_lowercase = false; } /* eat empty lines, simple preprocessing, lower case */ for (unsigned int tmp = 0; tmp < xinput.size(); tmp++) { if (xinput[tmp] == 9) { input += " "; } else if ((xinput[tmp] > 0 && xinput[tmp] <= 9) || (xinput[tmp] >= 11 && xinput[tmp] <= 31) || xinput[tmp] == 127) { continue; } else { if (transform_lowercase) { input += std::tolower(xinput[tmp]); } else { input += xinput[tmp]; } } // eat multi whitespace if (input.size() > 1) { if (std::isspace(input[input.size() - 2]) && std::isspace(input[input.size() - 1])) { input.resize(input.size() - 1); } } } std::string command; int id = -1; if (input == "") { return true; } else if (input == "exit") { exit(EXIT_SUCCESS); return true; } else if (input == "#") { return true; } else if (std::isdigit(input[0])) { std::istringstream strm(input); char spacer; strm >> id; strm >> std::noskipws >> spacer; std::getline(strm, command); } else { command = input; } /* process commands */ if (command == "protocol_version") { gtp_printf(id, "%d", GTP_VERSION); return true; } else if (command == "name") { gtp_printf(id, PROGRAM_NAME); return true; } else if (command == "version") { gtp_printf(id, PROGRAM_VERSION); return true; } else if (command == "quit") { gtp_printf(id, ""); exit(EXIT_SUCCESS); } else if (command.find("known_command") == 0) { std::istringstream cmdstream(command); std::string tmp; cmdstream >> tmp; /* remove known_command */ cmdstream >> tmp; for (int i = 0; s_commands[i].size() > 0; i++) { if (tmp == s_commands[i]) { gtp_printf(id, "true"); return 1; } } gtp_printf(id, "false"); return true; } else if (command.find("list_commands") == 0) { std::string outtmp(s_commands[0]); for (int i = 1; s_commands[i].size() > 0; i++) { outtmp = outtmp + "\n" + s_commands[i]; } gtp_printf(id, outtmp.c_str()); return true; } else if (command.find("boardsize") == 0) { std::istringstream cmdstream(command); std::string stmp; int tmp; cmdstream >> stmp; // eat boardsize cmdstream >> tmp; if (!cmdstream.fail()) { if (tmp < 2 || tmp > FastBoard::MAXBOARDSIZE) { gtp_fail_printf(id, "unacceptable size"); } else { float old_komi = game.get_komi(); game.init_game(tmp, old_komi); gtp_printf(id, ""); } } else { gtp_fail_printf(id, "syntax not understood"); } return true; } else if (command.find("clear_board") == 0) { game.reset_game(); gtp_printf(id, ""); return true; } else if (command.find("komi") == 0) { std::istringstream cmdstream(command); std::string tmp; float komi = 7.5f; float old_komi = game.get_komi(); cmdstream >> tmp; // eat komi cmdstream >> komi; if (!cmdstream.fail()) { if (komi != old_komi) { game.set_komi(komi); } gtp_printf(id, ""); } else { gtp_fail_printf(id, "syntax not understood"); } return true; } else if (command.find("play") == 0) { if (command.find("pass") != std::string::npos || command.find("resign") != std::string::npos) { game.play_pass(); gtp_printf(id, ""); } else { std::istringstream cmdstream(command); std::string tmp; std::string color, vertex; cmdstream >> tmp; //eat play cmdstream >> color; cmdstream >> vertex; if (!cmdstream.fail()) { if (!game.play_textmove(color, vertex)) { gtp_fail_printf(id, "illegal move"); } else { gtp_printf(id, ""); } } else { gtp_fail_printf(id, "syntax not understood"); } } return true; } else if (command.find("genmove") == 0) { std::istringstream cmdstream(command); std::string tmp; cmdstream >> tmp; // eat genmove cmdstream >> tmp; if (!cmdstream.fail()) { int who; if (tmp == "w" || tmp == "white") { who = FastBoard::WHITE; } else if (tmp == "b" || tmp == "black") { who = FastBoard::BLACK; } else { gtp_fail_printf(id, "syntax error"); return 1; } float old_komi = game.get_komi(); float new_komi = old_komi; if (cfg_komi_adjust) { if (who == FastBoard::BLACK) { new_komi = old_komi + 1.0f; } else { new_komi = old_komi - 1.0f; } } game.set_komi(new_komi); // start thinking { std::unique_ptr<UCTSearch> search(new UCTSearch(game)); int move = search->think(who); game.play_move(who, move); std::string vertex = game.move_to_text(move); gtp_printf(id, "%s", vertex.c_str()); } if (cfg_allow_pondering) { // now start pondering if (game.get_last_move() != FastBoard::RESIGN) { std::unique_ptr<UCTSearch> search(new UCTSearch(game)); search->ponder(); } } game.set_komi(old_komi); } else { gtp_fail_printf(id, "syntax not understood"); } return true; } else if (command.find("kgs-genmove_cleanup") == 0) { std::istringstream cmdstream(command); std::string tmp; cmdstream >> tmp; // eat kgs-genmove cmdstream >> tmp; if (!cmdstream.fail()) { int who; if (tmp == "w" || tmp == "white") { who = FastBoard::WHITE; } else if (tmp == "b" || tmp == "black") { who = FastBoard::BLACK; } else { gtp_fail_printf(id, "syntax error"); return 1; } float old_komi = game.get_komi(); float new_komi = old_komi; if (cfg_komi_adjust) { if (who == FastBoard::BLACK) { new_komi = old_komi + 1.0f; } else { new_komi = old_komi - 1.0f; } } game.set_komi(new_komi); game.set_passes(0); { std::unique_ptr<UCTSearch> search(new UCTSearch(game)); int move = search->think(who, UCTSearch::NOPASS); game.play_move(who, move); std::string vertex = game.move_to_text(move); gtp_printf(id, "%s", vertex.c_str()); } if (cfg_allow_pondering) { // now start pondering if (game.get_last_move() != FastBoard::RESIGN) { std::unique_ptr<UCTSearch> search(new UCTSearch(game)); search->ponder(); } } game.set_komi(old_komi); } else { gtp_fail_printf(id, "syntax not understood"); } return true; } else if (command.find("undo") == 0) { if (game.undo_move()) { gtp_printf(id, ""); } else { gtp_fail_printf(id, "cannot undo"); } return true; } else if (command.find("showboard") == 0) { gtp_printf(id, ""); game.display_state(); return true; } else if (command.find("mc_score") == 0) { float ftmp = game.board.final_mc_score(game.get_komi()); /* white wins */ if (ftmp < -0.1) { gtp_printf(id, "W+%3.1f", (float)fabs(ftmp)); } else if (ftmp > 0.1) { gtp_printf(id, "B+%3.1f", ftmp); } else { gtp_printf(id, "0"); } return true; } else if (command.find("final_score") == 0) { float ftmp = game.final_score(); /* white wins */ if (ftmp < -0.1) { gtp_printf(id, "W+%3.1f", (float)fabs(ftmp)); } else if (ftmp > 0.1) { gtp_printf(id, "B+%3.1f", ftmp); } else { gtp_printf(id, "0"); } return true; } else if (command.find("vn_winrate") == 0) { float net_score = Network::get_Network()->get_value(&game, Network::Ensemble::AVERAGE_ALL); gtp_printf(id, "%f", net_score); return true; } else if (command.find("mc_winrate") == 0) { float mc_winrate = Playout::mc_owner(game, 512); gtp_printf(id, "%f", mc_winrate); return true; } else if (command.find("winrate") == 0) { float mc_winrate = Playout::mc_owner(game, 512); float net_score = Network::get_Network()->get_value(&game, Network::Ensemble::AVERAGE_ALL); float comb_winrate = UCTNode::score_mix_function(game.get_movenum(), net_score, mc_winrate); gtp_printf(id, "%f", comb_winrate); return true; } else if (command.find("winrate") == 0) { float mc_winrate = Playout::mc_owner(game, 512); float net_score = Network::get_Network()->get_value(&game, Network::Ensemble::AVERAGE_ALL); float comb_winrate = UCTNode::score_mix_function(game.get_movenum(), net_score, mc_winrate); gtp_printf(id, "%f", comb_winrate); return true; } else if (command.find("final_status_list") == 0) { if (command.find("alive") != std::string::npos) { std::string livelist = get_life_list(game, true); gtp_printf(id, livelist.c_str()); } else if (command.find("dead") != std::string::npos) { std::string deadlist = get_life_list(game, false); gtp_printf(id, deadlist.c_str()); } else { gtp_printf(id, ""); } return true; } else if (command.find("time_settings") == 0) { std::istringstream cmdstream(command); std::string tmp; int maintime, byotime, byostones; cmdstream >> tmp >> maintime >> byotime >> byostones; if (!cmdstream.fail()) { // convert to centiseconds and set game.set_timecontrol(maintime * 100, byotime * 100, byostones, 0); gtp_printf(id, ""); } else { gtp_fail_printf(id, "syntax not understood"); } return true; } else if (command.find("time_left") == 0) { std::istringstream cmdstream(command); std::string tmp, color; int time, stones; cmdstream >> tmp >> color >> time >> stones; if (!cmdstream.fail()) { int icolor; if (color == "w" || color == "white") { icolor = FastBoard::WHITE; } else if (color == "b" || color == "black") { icolor = FastBoard::BLACK; } else { gtp_fail_printf(id, "Color in time adjust not understood.\n"); return 1; } game.adjust_time(icolor, time * 100, stones); gtp_printf(id, ""); if (cfg_allow_pondering) { // KGS sends this after our move // now start pondering if (game.get_last_move() != FastBoard::RESIGN) { float old_komi = game.get_komi(); float new_komi = old_komi; if (cfg_komi_adjust) { // We are the the color not to move int who = !game.get_to_move(); if (who == FastBoard::BLACK) { new_komi = old_komi + 1.0f; } else { new_komi = old_komi - 1.0f; } } game.set_komi(new_komi); std::unique_ptr<UCTSearch> search(new UCTSearch(game)); search->ponder(); game.set_komi(old_komi); } } } else { gtp_fail_printf(id, "syntax not understood"); } return true; } else if (command.find("auto") == 0) { do { std::unique_ptr<UCTSearch> search(new UCTSearch(game)); int move = search->think(game.get_to_move(), UCTSearch::NORMAL); game.play_move(move); game.display_state(); } while (game.get_passes() < 2 && game.get_last_move() != FastBoard::RESIGN); return true; } else if (command.find("bench") == 0) { Playout::do_playout_benchmark(game); return true; } else if (command.find("go") == 0) { std::unique_ptr<UCTSearch> search(new UCTSearch(game)); int move = search->think(game.get_to_move()); game.play_move(move); std::string vertex = game.move_to_text(move); myprintf("%s\n", vertex.c_str()); return true; } else if (command.find("influence") == 0) { gtp_printf(id, ""); game.board.display_map(game.board.influence()); return true; } else if (command.find("heatmap") == 0) { gtp_printf(id, ""); auto vec = Network::get_Network()->get_scored_moves( &game, Network::Ensemble::AVERAGE_ALL); Network::show_heatmap(&game, vec, false); return true; } else if (command.find("fixed_handicap") == 0) { std::istringstream cmdstream(command); std::string tmp; int stones; cmdstream >> tmp; // eat fixed_handicap cmdstream >> stones; if (game.set_fixed_handicap(stones)) { std::string stonestring = game.board.get_stone_list(); gtp_printf(id, "%s", stonestring.c_str()); } else { gtp_fail_printf(id, "Not a valid number of handicap stones"); } return true; } else if (command.find("place_free_handicap") == 0) { std::istringstream cmdstream(command); std::string tmp; int stones; cmdstream >> tmp; // eat place_free_handicap cmdstream >> stones; game.place_free_handicap(stones); std::string stonestring = game.board.get_stone_list(); gtp_printf(id, "%s", stonestring.c_str()); return true; } else if (command.find("set_free_handicap") == 0) { std::istringstream cmdstream(command); std::string tmp; cmdstream >> tmp; // eat set_free_handicap do { std::string vertex; cmdstream >> vertex; if (!cmdstream.fail()) { if (!game.play_textmove("black", vertex)) { gtp_fail_printf(id, "illegal move"); } else { game.set_handicap(game.get_handicap() + 1); } } } while (!cmdstream.fail()); std::string stonestring = game.board.get_stone_list(); gtp_printf(id, "%s", stonestring.c_str()); return true; } else if (command.find("loadsgf") == 0) { std::istringstream cmdstream(command); std::string tmp, filename; int movenum; cmdstream >> tmp; // eat loadsgf cmdstream >> filename; if (!cmdstream.fail()) { cmdstream >> movenum; if (cmdstream.fail()) { movenum = 999; } } else { gtp_fail_printf(id, "Missing filename."); return true; } std::unique_ptr<SGFTree> sgftree(new SGFTree); try { sgftree->load_from_file(filename); game = sgftree->follow_mainline_state(movenum - 1); gtp_printf(id, ""); } catch (const std::exception&) { gtp_fail_printf(id, "cannot load file"); } return true; } else if (command.find("kgs-chat") == 0) { // kgs-chat (game|private) Name Message std::istringstream cmdstream(command); std::string tmp; cmdstream >> tmp; // eat kgs-chat cmdstream >> tmp; // eat game|private cmdstream >> tmp; // eat player name do { cmdstream >> tmp; // eat message } while (!cmdstream.fail()); gtp_fail_printf(id, "I'm a go bot, not a chat bot."); return true; } else if (command.find("kgs-game_over") == 0) { // Do nothing. Particularly, don't ponder. gtp_printf(id, ""); return true; } else if (command.find("kgs-time_settings") == 0) { // none, absolute, byoyomi, or canadian std::istringstream cmdstream(command); std::string tmp; std::string tc_type; int maintime, byotime, byostones, byoperiods; cmdstream >> tmp >> tc_type; if (tc_type.find("none") != std::string::npos) { // 30 mins game.set_timecontrol(30 * 60 * 100, 0, 0, 0); } else if (tc_type.find("absolute") != std::string::npos) { cmdstream >> maintime; game.set_timecontrol(maintime * 100, 0, 0, 0); } else if (tc_type.find("canadian") != std::string::npos) { cmdstream >> maintime >> byotime >> byostones; // convert to centiseconds and set game.set_timecontrol(maintime * 100, byotime * 100, byostones, 0); } else if (tc_type.find("byoyomi") != std::string::npos) { // KGS style Fischer clock cmdstream >> maintime >> byotime >> byoperiods; game.set_timecontrol(maintime * 100, byotime * 100, 0, byoperiods); } else { gtp_fail_printf(id, "syntax not understood"); return true; } if (!cmdstream.fail()) { gtp_printf(id, ""); } else { gtp_fail_printf(id, "syntax not understood"); } return true; } else if (command.find("tune") == 0) { std::istringstream cmdstream(command); std::string tmp, filename; cmdstream >> tmp; // eat tune cmdstream >> filename; std::unique_ptr<AttribScores> scores(new AttribScores); scores->autotune_from_file(filename); gtp_printf(id, ""); return true; } else if (command.find("pn") == 0) { std::unique_ptr<PNSearch> pnsearch(new PNSearch(game)); pnsearch->classify_groups(); gtp_printf(id, ""); return true; } else if (command.find("nettune") == 0) { std::istringstream cmdstream(command); std::string tmp, filename; cmdstream >> tmp; // eat nettune cmdstream >> filename; std::unique_ptr<Network> network(new Network); network->autotune_from_file(filename); gtp_printf(id, ""); return true; } else if (command.find("netbench") == 0) { Network::get_Network()->benchmark(&game); gtp_printf(id, ""); return true; } else if (command.find("bookgen") == 0) { std::istringstream cmdstream(command); std::string tmp, filename; cmdstream >> tmp; // eat bookgen cmdstream >> filename; Book::bookgen_from_file(filename); return true; } else if (command.find("printsgf") == 0) { std::istringstream cmdstream(command); std::string tmp, filename; cmdstream >> tmp; // eat printsgf cmdstream >> filename; auto sgf_text = SGFTree::state_to_string(&game, 0); if (cmdstream.fail()) { gtp_printf(id, "%s\n", sgf_text.c_str()); } else { std::ofstream out(filename); out << sgf_text; out.close(); } return true; } else if (command.find("rltune") == 0) { std::istringstream cmdstream(command); std::string tmp, filename; cmdstream >> tmp; // eat rltune cmdstream >> filename; MCPolicy::mse_from_file(filename); return true; } else if (command.find("sltune") == 0) { std::istringstream cmdstream(command); std::string tmp, filename; cmdstream >> tmp; // eat rltune cmdstream >> filename; MCPolicy::mse_from_file2(filename); return true; } gtp_fail_printf(id, "unknown command"); return true; }
412
0.896943
1
0.896943
game-dev
MEDIA
0.501374
game-dev
0.953149
1
0.953149
RelativityMC/C2ME-forge
11,919
src/main/java/org/yatopiamc/c2me/mixin/threading/chunkio/MixinThreadedAnvilChunkStorage.java
package org.yatopiamc.c2me.mixin.threading.chunkio; import com.ibm.asyncutil.locks.AsyncNamedLock; import com.mojang.datafixers.DataFixer; import com.mojang.datafixers.util.Either; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.concurrent.ThreadTaskExecutor; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.palette.UpgradeData; import net.minecraft.village.PointOfInterestManager; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.chunk.ChunkStatus; import net.minecraft.world.chunk.IChunk; import net.minecraft.world.chunk.storage.ChunkLoader; import net.minecraft.world.chunk.storage.ChunkSerializer; import net.minecraft.world.gen.feature.structure.StructureStart; import net.minecraft.world.gen.feature.template.TemplateManager; import net.minecraft.world.server.ChunkHolder; import net.minecraft.world.server.ChunkManager; import net.minecraft.world.server.ServerWorld; import net.minecraft.world.storage.DimensionSavedDataManager; import org.apache.logging.log4j.Logger; 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.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.yatopiamc.c2me.common.threading.chunkio.AsyncSerializationManager; import org.yatopiamc.c2me.common.threading.chunkio.C2MECachedRegionStorage; import org.yatopiamc.c2me.common.threading.chunkio.ChunkIoMainThreadTaskUtils; import org.yatopiamc.c2me.common.threading.chunkio.ChunkIoThreadingExecutorUtils; import org.yatopiamc.c2me.common.threading.chunkio.IAsyncChunkStorage; import org.yatopiamc.c2me.common.threading.chunkio.ISerializingRegionBasedStorage; import org.yatopiamc.c2me.common.util.SneakyThrow; import java.io.File; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Supplier; @Mixin(ChunkManager.class) public abstract class MixinThreadedAnvilChunkStorage extends ChunkLoader implements ChunkHolder.IPlayerProvider { public MixinThreadedAnvilChunkStorage(File file, DataFixer dataFixer, boolean bl) { super(file, dataFixer, bl); } @Shadow @Final private ServerWorld level; @Shadow @Final private TemplateManager structureManager; @Shadow @Final private PointOfInterestManager poiManager; @Shadow protected abstract byte markPosition(ChunkPos chunkPos, ChunkStatus.Type chunkType); @Shadow @Final private static Logger LOGGER; @Shadow protected abstract void markPositionReplaceable(ChunkPos chunkPos); @Shadow @Final private Supplier<DimensionSavedDataManager> overworldDataStorage; @Shadow @Final private ThreadTaskExecutor<Runnable> mainThreadExecutor; @Shadow protected abstract boolean isExistingChunkFull(ChunkPos chunkPos); private AsyncNamedLock<ChunkPos> chunkLock = AsyncNamedLock.createFair(); @Inject(method = "<init>", at = @At("RETURN")) private void onInit(CallbackInfo info) { chunkLock = AsyncNamedLock.createFair(); } private Set<ChunkPos> scheduledChunks = new HashSet<>(); /** * @author ishland * @reason async io and deserialization */ @Overwrite private CompletableFuture<Either<IChunk, ChunkHolder.IChunkLoadingError>> scheduleChunkLoad(ChunkPos pos) { if (scheduledChunks == null) scheduledChunks = new HashSet<>(); synchronized (scheduledChunks) { if (scheduledChunks.contains(pos)) throw new IllegalArgumentException("Already scheduled"); scheduledChunks.add(pos); } final CompletableFuture<CompoundNBT> poiData = ((IAsyncChunkStorage) this.poiManager.worker).getNbtAtAsync(pos); final CompletableFuture<Either<IChunk, ChunkHolder.IChunkLoadingError>> future = getUpdatedChunkTagAtAsync(pos).thenApplyAsync(compoundTag -> { if (compoundTag != null) { try { if (compoundTag.contains("Level", 10) && compoundTag.getCompound("Level").contains("Status", 8)) { return ChunkSerializer.read(this.level, this.structureManager, this.poiManager, pos, compoundTag); } LOGGER.warn("Chunk file at {} is missing level data, skipping", pos); } catch (Throwable t) { LOGGER.error("Couldn't load chunk {}, chunk data will be lost!", pos, t); } } return null; }, ChunkIoThreadingExecutorUtils.serializerExecutor).thenCombine(poiData, (protoChunk, tag) -> protoChunk).thenApplyAsync(protoChunk -> { ((ISerializingRegionBasedStorage) this.poiManager).update(pos, poiData.join()); ChunkIoMainThreadTaskUtils.drainQueue(); if (protoChunk != null) { protoChunk.setLastSaveTime(this.level.getGameTime()); this.markPosition(pos, protoChunk.getStatus().getChunkType()); return Either.left(protoChunk); } else { this.markPositionReplaceable(pos); return Either.left(new ChunkPrimer(pos, UpgradeData.EMPTY)); } }, this.mainThreadExecutor); future.exceptionally(throwable -> null).thenRun(() -> { synchronized (scheduledChunks) { scheduledChunks.remove(pos); } }); return future; // [VanillaCopy] - for reference /* return CompletableFuture.supplyAsync(() -> { try { CompoundTag compoundTag = this.getUpdatedChunkTag(pos); if (compoundTag != null) { boolean bl = compoundTag.contains("Level", 10) && compoundTag.getCompound("Level").contains("Status", 8); if (bl) { Chunk chunk = ChunkSerializer.deserialize(this.world, this.structureManager, this.pointOfInterestStorage, pos, compoundTag); chunk.setLastSaveTime(this.world.getTime()); this.method_27053(pos, chunk.getStatus().getChunkType()); return Either.left(chunk); } LOGGER.error((String)"Chunk file at {} is missing level data, skipping", (Object)pos); } } catch (CrashException var5) { Throwable throwable = var5.getCause(); if (!(throwable instanceof IOException)) { this.method_27054(pos); throw var5; } LOGGER.error("Couldn't load chunk {}", pos, throwable); } catch (Exception var6) { LOGGER.error("Couldn't load chunk {}", pos, var6); } this.method_27054(pos); return Either.left(new ProtoChunk(pos, UpgradeData.NO_UPGRADE_DATA)); }, this.mainThreadExecutor); */ } private CompletableFuture<CompoundNBT> getUpdatedChunkTagAtAsync(ChunkPos pos) { return chunkLock.acquireLock(pos).toCompletableFuture().thenCompose(lockToken -> ((IAsyncChunkStorage) this.worker).getNbtAtAsync(pos).thenApply(compoundTag -> { if (compoundTag != null) return this.upgradeChunkTag(this.level.dimension(), this.overworldDataStorage, compoundTag); else return null; }).handle((tag, throwable) -> { lockToken.releaseLock(); if (throwable != null) SneakyThrow.sneaky(throwable); return tag; })); } private ConcurrentLinkedQueue<CompletableFuture<Void>> saveFutures = new ConcurrentLinkedQueue<>(); @Dynamic @Redirect(method = {"lambda$scheduleUnload$10", "func_219185_a"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/world/server/ChunkManager;save(Lnet/minecraft/world/chunk/IChunk;)Z")) // method: consumer in tryUnloadChunk private boolean asyncSave(ChunkManager tacs, IChunk p_219229_1_) { // TODO [VanillaCopy] - check when updating minecraft version this.poiManager.flush(p_219229_1_.getPos()); if (!p_219229_1_.isUnsaved()) { return false; } else { p_219229_1_.setLastSaveTime(this.level.getGameTime()); p_219229_1_.setUnsaved(false); ChunkPos chunkpos = p_219229_1_.getPos(); try { ChunkStatus chunkstatus = p_219229_1_.getStatus(); if (chunkstatus.getChunkType() != ChunkStatus.Type.LEVELCHUNK) { if (this.isExistingChunkFull(chunkpos)) { return false; } if (chunkstatus == ChunkStatus.EMPTY && p_219229_1_.getAllStarts().values().stream().noneMatch(StructureStart::isValid)) { return false; } } this.level.getProfiler().incrementCounter("chunkSave"); // C2ME start - async serialization if (saveFutures == null) saveFutures = new ConcurrentLinkedQueue<>(); AsyncSerializationManager.Scope scope = new AsyncSerializationManager.Scope(p_219229_1_, level); saveFutures.add(chunkLock.acquireLock(p_219229_1_.getPos()).toCompletableFuture().thenCompose(lockToken -> CompletableFuture.supplyAsync(() -> { scope.open(); AsyncSerializationManager.push(scope); try { return ChunkSerializer.write(this.level, p_219229_1_); } finally { AsyncSerializationManager.pop(scope); } }, ChunkIoThreadingExecutorUtils.serializerExecutor) .thenAcceptAsync(compoundTag -> { net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.world.ChunkDataEvent.Save(p_219229_1_, p_219229_1_.getWorldForge() != null ? p_219229_1_.getWorldForge() : this.level, compoundTag)); // [VanillaCopy] this.write(chunkpos, compoundTag); }, this.mainThreadExecutor) .handle((unused, throwable) -> { lockToken.releaseLock(); if (throwable != null) LOGGER.error("Failed to save chunk {},{}", chunkpos.x, chunkpos.z, throwable); return unused; }))); this.markPosition(chunkpos, chunkstatus.getChunkType()); // C2ME end return true; } catch (Exception exception) { LOGGER.error("Failed to save chunk {},{}", chunkpos.x, chunkpos.z, exception); return false; } } } @Inject(method = "tick(Ljava/util/function/BooleanSupplier;)V", at = @At("HEAD")) private void onTick(CallbackInfo info) { ChunkIoThreadingExecutorUtils.serializerExecutor.execute(() -> saveFutures.removeIf(CompletableFuture::isDone)); } @Override public void flushWorker() { final CompletableFuture<Void> future = CompletableFuture.allOf(saveFutures.toArray(new CompletableFuture[0])); this.mainThreadExecutor.managedBlock(future::isDone); // wait for serialization to complete super.flushWorker(); } }
412
0.924901
1
0.924901
game-dev
MEDIA
0.988429
game-dev
0.983268
1
0.983268
watabou/pixel-dungeon
7,345
src/com/watabou/pixeldungeon/items/potions/Potion.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */package com.watabou.pixeldungeon.items.potions; import java.util.ArrayList; import java.util.HashSet; import com.watabou.noosa.audio.Sample; import com.watabou.pixeldungeon.Assets; import com.watabou.pixeldungeon.Badges; import com.watabou.pixeldungeon.Dungeon; import com.watabou.pixeldungeon.actors.hero.Hero; import com.watabou.pixeldungeon.effects.Splash; import com.watabou.pixeldungeon.items.Item; import com.watabou.pixeldungeon.items.ItemStatusHandler; import com.watabou.pixeldungeon.levels.Level; import com.watabou.pixeldungeon.levels.Terrain; import com.watabou.pixeldungeon.scenes.GameScene; import com.watabou.pixeldungeon.sprites.ItemSprite; import com.watabou.pixeldungeon.sprites.ItemSpriteSheet; import com.watabou.pixeldungeon.utils.GLog; import com.watabou.pixeldungeon.windows.WndOptions; import com.watabou.utils.Bundle; public class Potion extends Item { public static final String AC_DRINK = "DRINK"; private static final String TXT_HARMFUL = "Harmful potion!"; private static final String TXT_BENEFICIAL = "Beneficial potion"; private static final String TXT_YES = "Yes, I know what I'm doing"; private static final String TXT_NO = "No, I changed my mind"; private static final String TXT_R_U_SURE_DRINK = "Are you sure you want to drink it? In most cases you should throw such potions at your enemies."; private static final String TXT_R_U_SURE_THROW = "Are you sure you want to throw it? In most cases it makes sense to drink it."; private static final float TIME_TO_DRINK = 1f; private static final Class<?>[] potions = { PotionOfHealing.class, PotionOfExperience.class, PotionOfToxicGas.class, PotionOfLiquidFlame.class, PotionOfStrength.class, PotionOfParalyticGas.class, PotionOfLevitation.class, PotionOfMindVision.class, PotionOfPurity.class, PotionOfInvisibility.class, PotionOfMight.class, PotionOfFrost.class }; private static final String[] colors = { "turquoise", "crimson", "azure", "jade", "golden", "magenta", "charcoal", "ivory", "amber", "bistre", "indigo", "silver"}; private static final Integer[] images = { ItemSpriteSheet.POTION_TURQUOISE, ItemSpriteSheet.POTION_CRIMSON, ItemSpriteSheet.POTION_AZURE, ItemSpriteSheet.POTION_JADE, ItemSpriteSheet.POTION_GOLDEN, ItemSpriteSheet.POTION_MAGENTA, ItemSpriteSheet.POTION_CHARCOAL, ItemSpriteSheet.POTION_IVORY, ItemSpriteSheet.POTION_AMBER, ItemSpriteSheet.POTION_BISTRE, ItemSpriteSheet.POTION_INDIGO, ItemSpriteSheet.POTION_SILVER}; private static ItemStatusHandler<Potion> handler; private String color; { stackable = true; defaultAction = AC_DRINK; } @SuppressWarnings("unchecked") public static void initColors() { handler = new ItemStatusHandler<Potion>( (Class<? extends Potion>[])potions, colors, images ); } public static void save( Bundle bundle ) { handler.save( bundle ); } @SuppressWarnings("unchecked") public static void restore( Bundle bundle ) { handler = new ItemStatusHandler<Potion>( (Class<? extends Potion>[])potions, colors, images, bundle ); } public Potion() { super(); image = handler.image( this ); color = handler.label( this ); } @Override public ArrayList<String> actions( Hero hero ) { ArrayList<String> actions = super.actions( hero ); actions.add( AC_DRINK ); return actions; } @Override public void execute( final Hero hero, String action ) { if (action.equals( AC_DRINK )) { if (isKnown() && ( this instanceof PotionOfLiquidFlame || this instanceof PotionOfToxicGas || this instanceof PotionOfParalyticGas)) { GameScene.show( new WndOptions( TXT_HARMFUL, TXT_R_U_SURE_DRINK, TXT_YES, TXT_NO ) { @Override protected void onSelect(int index) { if (index == 0) { drink( hero ); } }; } ); } else { drink( hero ); } } else { super.execute( hero, action ); } } @Override public void doThrow( final Hero hero ) { if (isKnown() && ( this instanceof PotionOfExperience || this instanceof PotionOfHealing || this instanceof PotionOfLevitation || this instanceof PotionOfMindVision || this instanceof PotionOfStrength || this instanceof PotionOfInvisibility || this instanceof PotionOfMight)) { GameScene.show( new WndOptions( TXT_BENEFICIAL, TXT_R_U_SURE_THROW, TXT_YES, TXT_NO ) { @Override protected void onSelect(int index) { if (index == 0) { Potion.super.doThrow( hero ); } }; } ); } else { super.doThrow( hero ); } } protected void drink( Hero hero ) { detach( hero.belongings.backpack ); hero.spend( TIME_TO_DRINK ); hero.busy(); onThrow( hero.pos ); Sample.INSTANCE.play( Assets.SND_DRINK ); hero.sprite.operate( hero.pos ); } @Override protected void onThrow( int cell ) { if (Dungeon.hero.pos == cell) { apply( Dungeon.hero ); } else if (Dungeon.level.map[cell] == Terrain.WELL || Level.pit[cell]) { super.onThrow( cell ); } else { shatter( cell ); } } protected void apply( Hero hero ) { shatter( hero.pos ); } public void shatter( int cell ) { if (Dungeon.visible[cell]) { GLog.i( "The flask shatters and " + color() + " liquid splashes harmlessly" ); Sample.INSTANCE.play( Assets.SND_SHATTER ); splash( cell ); } } public boolean isKnown() { return handler.isKnown( this ); } public void setKnown() { if (!isKnown()) { handler.know( this ); } Badges.validateAllPotionsIdentified(); } @Override public Item identify() { setKnown(); return this; } protected String color() { return color; } @Override public String name() { return isKnown() ? name : color + " potion"; } @Override public String info() { return isKnown() ? desc() : "This flask contains a swirling " + color + " liquid. " + "Who knows what it will do when drunk or thrown?"; } @Override public boolean isIdentified() { return isKnown(); } @Override public boolean isUpgradable() { return false; } public static HashSet<Class<? extends Potion>> getKnown() { return handler.known(); } public static HashSet<Class<? extends Potion>> getUnknown() { return handler.unknown(); } public static boolean allKnown() { return handler.known().size() == potions.length; } protected void splash( int cell ) { final int color = ItemSprite.pick( image, 8, 10 ); Splash.at( cell, color, 5 ); } @Override public int price() { return 20 * quantity; } }
412
0.791043
1
0.791043
game-dev
MEDIA
0.980125
game-dev
0.899874
1
0.899874
Tslat/Advent-Of-Ascension
1,657
source/content/item/armour/ElecanyteArmour.java
package net.tslat.aoa3.content.item.armour; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.neoforged.neoforge.event.entity.living.LivingDamageEvent; import net.tslat.aoa3.common.registration.custom.AoAResources; import net.tslat.aoa3.common.registration.item.AoAArmourMaterials; import net.tslat.aoa3.util.DamageUtil; import net.tslat.aoa3.util.LocaleUtil; import net.tslat.aoa3.util.PlayerUtil; import java.util.EnumSet; import java.util.List; public class ElecanyteArmour extends AdventArmour { public ElecanyteArmour(ArmorItem.Type slot) { super(AoAArmourMaterials.ELECANYTE, slot, 63); } @Override public void afterTakingDamage(LivingEntity entity, EnumSet<Piece> equippedPieces, LivingDamageEvent.Post ev) { if (ev.getNewDamage() > 0 && entity instanceof ServerPlayer pl && !DamageUtil.isEnvironmentalDamage(ev.getSource())) PlayerUtil.addResourceToPlayer(pl, AoAResources.SPIRIT.get(), ev.getNewDamage() * perPieceValue(equippedPieces, 2.5f)); } @Override public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltip, TooltipFlag tooltipFlag) { tooltip.add(LocaleUtil.getFormattedItemDescriptionText("item.aoa3.elecanyte_armour.desc.1", LocaleUtil.ItemDescriptionType.BENEFICIAL)); tooltip.add(pieceEffectHeader()); tooltip.add(LocaleUtil.getFormattedItemDescriptionText("item.aoa3.elecanyte_armour.desc.2", LocaleUtil.ItemDescriptionType.BENEFICIAL)); } }
412
0.892505
1
0.892505
game-dev
MEDIA
0.98661
game-dev
0.987618
1
0.987618
TeamHypersomnia/Hypersomnia
3,349
src/application/gui/client/demo_player_gui.hpp
#pragma once #include "application/gui/client/demo_player_gui.h" #include "application/setups/debugger/detail/maybe_different_colors.h" #include "augs/templates/chrono_templates.h" #include "augs/window_framework/window.h" #include "augs/misc/imgui/imgui_enum_radio.h" inline void demo_player_gui::perform( augs::window& window, client_demo_player& player ) { using namespace augs::imgui; auto scope = make_scoped_window(); if (!scope) { return; } checkbox("Show spectator overlay", show_spectator_overlay); checkbox("Draw enemy silhouettes", draw_enemy_silhouettes); text("POV:"); ImGui::SameLine(); if (enum_radio(shown_arena_type, true)) { pending_interpolation_snap = true; } ImGui::SameLine(); text_disabled("(?)"); if (ImGui::IsItemHovered()) { auto scope = scoped_tooltip(); text_color("Referential", yellow); ImGui::SameLine(); text("shows you the events as they have truly happened on the server."); text_color("Predicted", yellow); ImGui::SameLine(); text("shows you the events as they were seen by the player who has recorded the demo,\nwith effects of network lag reproduced exactly how they occured."); } { auto scope = maybe_disabled_cols({}, player.get_current_step() == 0); if (ImGui::Button("Rewind")) { player.seek_to(0); } ImGui::SameLine(); } { auto scope = maybe_disabled_cols({}, player.is_paused()); if (ImGui::Button("Pause")) { player.pause(); } ImGui::SameLine(); } { auto scope = maybe_disabled_cols({}, !player.is_paused()); if (ImGui::Button("Resume")) { player.resume(); } } text_disabled("Replaying:"); ImGui::SameLine(); #if !PLATFORM_WEB { const auto demo_path = player.source_path.string(); text_color(demo_path, cyan); ImGui::SameLine(); if (ImGui::Button("Reveal in explorer")) { window.reveal_in_explorer(demo_path); } } #else (void)window; #endif const auto current = player.get_current_secs(); if (player.get_total_steps() > 0) { auto mult = static_cast<float>(player.get_current_step()) / player.get_total_steps(); mult = std::clamp(mult, 0.f, 1.f); if (slider("Player position", mult, 0.f, 1.f)) { mult = std::clamp(mult, 0.f, 1.f); const auto target_step = player.get_total_steps() * mult; player.seek_to(target_step); } ImGui::ProgressBar(mult); } { auto step_str = std::to_string(player.get_current_step()); text("Current step:"); ImGui::SameLine(); auto scope = scoped_item_width(ImGui::CalcTextSize("9").x * 15); if (input_text<256>("##Current step", step_str, ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_EnterReturnsTrue)) { const auto changed_step = std::atoi(step_str.c_str()); player.seek_to(changed_step); } } ImGui::SameLine(); text("/%x", player.get_total_steps()); text("Current time: %x", ::format_mins_secs_ms(current)); text("Playback speed: %xx", player.speed); text_disabled("Press Alt+P to toggle this window visibility.\n"); const auto hotkeys = R"(Hotkeys: Left/Right - Seek backward/forward 5 seconds Shift + Left/Right - Seek backward/forward 1 second Up/Down - Seek backward/forward 10 seconds Space - Pause/Resume L - Resume Esc - Pause Numpad keys control speed (0 resets to 1x) )"; text_disabled(hotkeys); #if DEBUG_DESYNCS if (ImGui::Button("Dump state")) { pending_dump = true; } #endif }
412
0.901313
1
0.901313
game-dev
MEDIA
0.604845
game-dev,desktop-app
0.901361
1
0.901361
austinmao/reduxity
2,517
Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Triggers/ObservableTrigger2DTrigger.cs
using System; // require keep for Windows Universal App using UnityEngine; namespace UniRx.Triggers { [DisallowMultipleComponent] public class ObservableTrigger2DTrigger : ObservableTriggerBase { Subject<Collider2D> onTriggerEnter2D; /// <summary>Sent when another object enters a trigger collider attached to this object (2D physics only).</summary> void OnTriggerEnter2D(Collider2D other) { if (onTriggerEnter2D != null) onTriggerEnter2D.OnNext(other); } /// <summary>Sent when another object enters a trigger collider attached to this object (2D physics only).</summary> public IObservable<Collider2D> OnTriggerEnter2DAsObservable() { return onTriggerEnter2D ?? (onTriggerEnter2D = new Subject<Collider2D>()); } Subject<Collider2D> onTriggerExit2D; /// <summary>Sent when another object leaves a trigger collider attached to this object (2D physics only).</summary> void OnTriggerExit2D(Collider2D other) { if (onTriggerExit2D != null) onTriggerExit2D.OnNext(other); } /// <summary>Sent when another object leaves a trigger collider attached to this object (2D physics only).</summary> public IObservable<Collider2D> OnTriggerExit2DAsObservable() { return onTriggerExit2D ?? (onTriggerExit2D = new Subject<Collider2D>()); } Subject<Collider2D> onTriggerStay2D; /// <summary>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</summary> void OnTriggerStay2D(Collider2D other) { if (onTriggerStay2D != null) onTriggerStay2D.OnNext(other); } /// <summary>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</summary> public IObservable<Collider2D> OnTriggerStay2DAsObservable() { return onTriggerStay2D ?? (onTriggerStay2D = new Subject<Collider2D>()); } protected override void RaiseOnCompletedOnDestroy() { if (onTriggerEnter2D != null) { onTriggerEnter2D.OnCompleted(); } if (onTriggerExit2D != null) { onTriggerExit2D.OnCompleted(); } if (onTriggerStay2D != null) { onTriggerStay2D.OnCompleted(); } } } }
412
0.716648
1
0.716648
game-dev
MEDIA
0.94488
game-dev
0.806072
1
0.806072
crownengine/crown
2,820
3rdparty/bullet3/src/BulletCollision/CollisionShapes/btMinkowskiSumShape.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 "btMinkowskiSumShape.h" btMinkowskiSumShape::btMinkowskiSumShape(const btConvexShape* shapeA, const btConvexShape* shapeB) : btConvexInternalShape(), m_shapeA(shapeA), m_shapeB(shapeB) { m_shapeType = MINKOWSKI_DIFFERENCE_SHAPE_PROXYTYPE; m_transA.setIdentity(); m_transB.setIdentity(); } btVector3 btMinkowskiSumShape::localGetSupportingVertexWithoutMargin(const btVector3& vec) const { btVector3 supVertexA = m_transA(m_shapeA->localGetSupportingVertexWithoutMargin(vec * m_transA.m_basis)); btVector3 supVertexB = m_transB(m_shapeB->localGetSupportingVertexWithoutMargin(-vec * m_transB.m_basis)); return supVertexA - supVertexB; } void btMinkowskiSumShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const { ///@todo: could make recursive use of batching. probably this shape is not used frequently. for (int i = 0; i < numVectors; i++) { supportVerticesOut[i] = localGetSupportingVertexWithoutMargin(vectors[i]); } } btScalar btMinkowskiSumShape::getMargin() const { return m_shapeA->getMargin() + m_shapeB->getMargin(); } void btMinkowskiSumShape::calculateLocalInertia(btScalar mass, btVector3& inertia) const { (void)mass; //inertia of the AABB of the Minkowski sum btTransform identity; identity.setIdentity(); btVector3 aabbMin, aabbMax; getAabb(identity, aabbMin, aabbMax); btVector3 halfExtents = (aabbMax - aabbMin) * btScalar(0.5); btScalar margin = getMargin(); btScalar lx = btScalar(2.) * (halfExtents.x + margin); btScalar ly = btScalar(2.) * (halfExtents.y + margin); btScalar lz = btScalar(2.) * (halfExtents.z + margin); const btScalar x2 = lx * lx; const btScalar y2 = ly * ly; const btScalar z2 = lz * lz; const btScalar scaledmass = mass * btScalar(0.08333333); inertia = scaledmass * (btVector3(y2 + z2, x2 + z2, x2 + y2)); }
412
0.893905
1
0.893905
game-dev
MEDIA
0.987678
game-dev
0.968478
1
0.968478
theCapypara/GMnet-ENGINE
2,369
GMnetENGINE.gmx/scripts/htme_serverSendAllInstances.gml
///htme_serverSendAllInstances(player); /* ** Description: ** PRIVATE "METHOD" OF obj_htme! That means this script MUST be called with obj_htme! ** ** Sends all instances from globalInstances to player ** ...but only the instances in the same room ** (because htme_syncSingleVarGroup only syncs those)! ** ** Usage: ** <See above> ** ** Arguments: ** player string ip:port ** ** Returns: ** <nothing> ** */ var target = argument0; self.syncForce = true; htme_debugger("htme_serverSendAllInstances",htme_debug.DEBUG,"Sending all instances to "+target+" due to room change."); //This will loop through all var groups. for(var i=0; i<ds_list_size(self.grouplist); i+=1) { var group = ds_list_find_value(grouplist,i); /**RETRIEVE INFORMATION**/ var inst_hash = group[? "instancehash"]; var inst = group[? "instance"]; if (instance_exists(inst)) { var inst_player = (inst).htme_mp_player; } else if (self.isServer) { var backupEntry = ds_map_find_value(self.serverBackup,inst_hash); if (ds_exists(backupEntry,ds_type_map)) { var inst_player = backupEntry[? "player"]; } else { if (is_undefined(inst_hash) || is_undefined(group[? "name"])) { htme_debugger("htme_serverSendAllInstances",htme_debug.WARNING,"CORRUPTED VARGROUP! CONTENTS: "+json_encode(group)); } else { htme_debugger("htme_serverSendAllInstances",htme_debug.WARNING,"Could not check var-group "+group[? "name"]+" of instance "+inst_hash+". MISSING BACKUP ENTRY!"); } } } else { if (is_undefined(inst_hash) || is_undefined(group[? "name"])) { htme_debugger("htme_serverSendAllInstances",htme_debug.WARNING,"CORRUPTED VARGROUP! CONTENTS: "+json_encode(group)); } else { htme_debugger("htme_serverSendAllInstances",htme_debug.WARNING,"Could not check var-group "+group[? "name"]+" of instance "+inst_hash+". MISSING INSTANCE!"); } exit; } //Skip if own instance var phash = ds_map_find_value(self.playermap,target); if (inst_player == phash) {continue;} //FIXME: Only send to this player! - Sending a string as target is currently broken htme_syncSingleVarGroup(group,all); } self.syncForce = false;
412
0.921174
1
0.921174
game-dev
MEDIA
0.277072
game-dev
0.947596
1
0.947596
Fluorohydride/ygopro-scripts
1,690
c12682213.lua
--鉄騎の雷鎚 local s,id,o=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_CHAINING) e1:SetCondition(s.moncon) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) -- local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_ACTIVATE) e2:SetCode(EVENT_CHAINING) e2:SetCondition(s.accon) e2:SetCost(s.cost) e2:SetTarget(s.target) e2:SetOperation(s.activate) c:RegisterEffect(e2) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.PayLPCost(tp,math.floor(Duel.GetLP(tp)/2)) end function s.moncon(e,tp,eg,ep,ev,re,r,rp) local loc=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_LOCATION) return loc==LOCATION_MZONE and re:IsActiveType(TYPE_MONSTER) and Duel.IsChainNegatable(ev) end function s.accon(e,tp,eg,ep,ev,re,r,rp) return re:IsHasType(EFFECT_TYPE_ACTIVATE) and Duel.IsChainNegatable(ev) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0) end end function s.activate(e,tp,eg,ep,ev,re,r,rp) local rc=re:GetHandler() local dg=rc:GetColumnGroup() local c=e:GetHandler() if c:IsRelateToEffect(e) then dg:RemoveCard(c) end if Duel.NegateActivation(ev) and rc:IsRelateToEffect(re) and Duel.Destroy(eg,REASON_EFFECT)~=0 and dg:GetCount()>0 then Duel.BreakEffect() Duel.Destroy(dg,REASON_EFFECT) end end
412
0.815388
1
0.815388
game-dev
MEDIA
0.960955
game-dev
0.882222
1
0.882222
longturn/freeciv21
12,379
docs/Playing/cma.rst
.. SPDX-License-Identifier: GPL-3.0-or-later .. SPDX-FileCopyrightText: Freeciv21 and Freeciv Contributors .. SPDX-FileCopyrightText: James Robertson <jwrober@gmail.com> .. SPDX-FileCopyrightText: Louis Moureaux <m_louis30@yahoo.com> Citizen Governor (aka Citizen Management Agent, or CMA) ******************************************************* The Citizen Governor is designed to help you manage your cities, i.e. deploy the citizens on the available tiles around (or make them scientists, taxmen, or even entertainers), to get the most out of the city. You can switch the Governor on or off at any time for any city, but there are some handicaps (explained below), if you have governor controlled and non-governor-controlled cities nearby. The heart of the Governor system is an optimizing algorithm, that tries to deploy the citizens of a city in such a way, that a user-defined goal is achieved as much as possible. You know probably, there is already a kind of optimizing, when you open a city, and click on the center tile (the city symbol) of the map. This optimization tries to maximize mostly the food output, but it does not care about disorder. The City Management Agent goes far beyond this old form of optimizing. First, it performs this task every time anything changes with the city. If the city grows or shrinks, troops go in or out, tiles get irrigation or mining, or are occupied by an enemy, the Governor becomes active. Second, it supports all kinds of optimizing, like production (shields), gold, science, or luxury goods. Third, it gives the player a fine-grained control over this, with the possibility of setting constraints for any kind of city output. The latter includes the constraint of celebration, which makes it very easy to let your cities grow, even in harder times. The forth, and probably most valuable thing in war times, is that it keeps your cities content, preventing them from revolt. The legacy Freeciv Wiki also contains some other useful information related to the CMA: * https://freeciv.fandom.com/wiki/City_manager * https://freeciv.fandom.com/wiki/CMA Usage ===== You can set up the Governor for a city by opening the :doc:`City Dialog </Manuals/Game/city-dialog>` and clicking on the :guilabel:`Governor` tab. You can choose a preset for a specified goal in the middle and on the bottom you can specify more complex goals by moving the sliders. You can choose a preset at first, and then modify it. Once you have created a new setting, you can add a preset name for it. This is not required, but is very useful, since you can watch and even change the city's setting from within the city view, if it is given a name. Do not forget to save settings (in the :guilabel:`Game` menu), when you have created new presets. .. _CMA Dialog: .. figure:: /_static/images/gui-elements/city-dialog-governor.png :align: center :alt: Governor Tab in City Dialog :figclass: align-center Governor Tab in City Dialog The sliders are of two kinds: the rightmost sliders are factors, which gauges how much one product is worth compared to the others (e.g how much shields are worth with respect to everything else). The leftmost sliders are constraints. You can command the city not to lose food, e.g. by setting the surplus constraint to zero, and you can allow the city to lose gold by setting the gold surplus to -3, and urge them to make at least 5 shields per round by setting the production surplus to 5. The most powerful constraint, though, is the :guilabel:`Celebrate` constraint, which makes the city celebrate at once (which usually takes effect the round after you change it). .. note:: Celebration is a ruleset defined setting and is not available for all games. It is obvious that the Governor cannot fulfill all these constraints in every case. Whenever the constraints cannot be fulfilled, the Governor quits its service for that city, giving a message: :strong:`"The agent can't fulfill the requirements for [city name]. Passing back control."` You then have the choice of either managing the city on your own (which has some drawbacks, see below), or open that city and change the surplus requirements so that they can be fulfilled. When you have made a setup for a city, you need to click on :guilabel:`Enable` to switch on the Governor. If this button's text is greyed, either the Governor is already active, or the task is impossible. In the latter case you see dashes instead of numbers in the results block. If you ever want to switch off the Governor deliberately, click :guilabel:`Disable`. The :guilabel:`Optimize` option for Food output will ensure that the city is always growing. By enabling the :guilabel:`Allow Specialists` option, the Governor will pull citizens from working tiles and turn them into Entertainer, Scientist, or Taxmen specialists to meet the constraints. Lastly, enabling the :guilabel:`Allow Disorder` option will allow the city to go into disorder to meet constraints. Advanced Usage ============== Usually the goal(s) of your cities depend on the phase your game is in, whether you want to spread widely, grow quickly, research advanced techs or wage war. You may want to set up a high factor for science to research, or a high shields factor to produce units. The highest factor available is 25, that means: if the shields factor is set to 25, and other to 1, the Governor prefers a single shield over 25 gold (or trade also). This is pretty much because money can buy units too. That also means that the Governor is indifferent about producing gold, science, luxury goods, or food, but when you wage war, you usually prefer gold or luxury goods. So it is probably a good idea to set a second (or even third) preference for the city's output, e.g. gold factor 5. That still prefers 1 shield over 5 gold (and 1 gold over 5 food or anything else). Constraints are not useful in all cases. If you want a high income, it is probably better to set the gold factor to 25, than to set a minimal surplus of 5 or so. Because a big city can make more gold than a small one, you would end up setting a different surplus for each city. However, if the shields surplus of a city is below zero, it cannot support all of its units any more. You will lose some of the units the city supports. If the food surplus is negative, the city will starve and eventually (when the granary is empty) shrink. This may be intended, but if the city supports any settlers, you will lose them before the city shrinks. Constraints can also have a warning function. Which constraints can be fulfilled depends widely on the global science, tax, and luxury good rates. E.g. a gold surplus >= 0 is easier to fulfill with a higher tax rate than a lower one. You should always consider to change these rates, when you going to change the Governor settings for the most of your cities. Drawbacks ========= The Governor is a very powerful tool, which not only releases you from the micromanagement of your cities, but gives you more performance than you have ever seen (well, for most players). There are some drawbacks, though. Once you have switched on the Governor, it grabs any good tile it can get. So you encounter very hard times trying to manage a city nearby a Governor-controlled one. This is true for the city dialog and the main map worker's interface as well. If you want to have Governor-controlled and :strong:`handmade` cities, they probably should be on different islands. There are several situations where the Governor cannot fulfill the requirements just temporarily, e.g. when you move a ship from one city to another, or when an enemy walks through your country. The Governor passes back control in these cases, and you have to reenable it manually. A general approach to prevent this might be, to set the minimal surpluses as low as possible (-20). Of course you must be careful with the food and shield surpluses. While the Governor does a really good job for a single city, no tile will ever be released for the good of another city. Also, the Governor controlled cities are computed in a more random order. The results may depend on it and change, when a recalculation is done (e.g. when tax changes). So, no guarantee is given that the overall results are always optimal. Settings file ============= The game allows the user to load and save preset parameters for the agent. Choosing :menuselection:`Game --> Options --> Save Settings Now` will not only save your :ref:`interface options <game-manual-options>` and :ref:`message options <game-manual-message-options>`, but it will save any changes you made to you Governor presets as well. The format for the options file (usually :file:`~/.local/share/freeciv21/freeciv-client-rc-X.Y` , where X.Y is the version of Freeciv21 in use) is as follows (in case you which to change these presets manually, i.e. with a text editor). Under the heading :literal:`[cma]`, is a :literal:`number_of_presets`. This should be set to the number of presets that are present in the options file. If you manually add or remove a preset, you need to change this number as appropriate. After this, is an array that houses the presets. Here is the header: .. code-block:: ini preset={ "name","minsurp0","factor0","minsurp1","factor1","minsurp2", "factor2","minsurp3","factor3","minsurp4","factor4","minsurp5", "factor5","reqhappy","factortarget","happyfactor" so the order of the preset should be as follows: * name of preset, minimal surplus 0, factor 0, ... , * require city to be happy, what the target should be [0,1], * the happiness factor Currently there are 6 surpluses and factors. They are: * 0 = food * 1 = production * 2 = trade * 3 = gold * 4 = luxury goods * 5 = science Also currently, :literal:`factortarget` is not changeable within the client. The array should be terminated with a squirely brace :literal:`}`. Here are the 5 presets that come with Freeciv21 out of the box: .. code-block:: ini "Very happy",0,10,0,5,0,0,-20,4,0,0,0,4,FALSE,25 "Prefer food",-20,25,0,5,0,0,-20,4,0,0,0,4,FALSE,0 "Prefer production",0,10,-20,25,0,0,-20,4,0,0,0,4,FALSE,0 "Prefer gold",0,10,0,5,0,0,-20,25,0,0,0,4,FALSE,0 "Prefer science",0,10,0,5,0,0,-20,4,0,0,0,25,FALSE,01 Here are 16 more that you can add to your client RC file: .. code-block:: ini "+2 food",2,1,0,1,0,1,0,1,0,1,0,1,0,0,1 "+2 production",0,1,2,1,0,1,0,1,0,1,0,1,0,0,1 "+2 trade",0,1,0,1,2,1,0,1,0,1,0,1,0,0,1 "+2 gold",0,1,0,1,0,1,2,1,0,1,0,1,0,0,1 "+2 luxury",0,1,0,1,0,1,0,1,2,1,0,1,0,0,1 "+2 science",0,1,0,1,0,1,0,1,0,1,2,1,0,0,1 "+20 Celebrating for Gold",20,0,0,16,0,0,0,8,0,1,0,1,TRUE,0 "Max food no gold limit",0,10,0,1,0,1,-20,1,0,1,0,1,0,0,1 "Max production no gold limit",0,1,0,10,0,1,-20,1,0,1,0,1,0,0,1 "Max trade no gold limit",0,1,0,1,0,10,-20,1,0,1,0,1,0,0,1 "Max gold no gold limit",0,1,0,1,0,1,-20,10,0,1,0,1,0,0,1 "Max luxury no gold limit",0,1,0,1,0,1,-20,1,0,10,0,1,0,0,1 "Max science no gold limit",0,1,0,1,0,1,-20,1,0,1,0,10,0,0,1 "Max food+prod. no gold limit",0,10,0,10,0,1,-20,1,0,1,0,1,0,0,1 "Max food+prod.+trade",0,10,0,10,0,10,0,1,0,1,0,1,0,0,1 "Max all",0,1,0,1,0,1,0,1,0,1,0,1,0,0,1 Here are 6 more that have been added as an afterthought: .. code-block:: ini "+1 food, max prod. no gold limit",1,1,0,10,0,1,-20,1,0,1,0,1,0,0,1 "+2 food, max prod. no gold limit",2,1,0,10,0,1,-20,1,0,1,0,1,0,0,1 "+3 food, max prod. no gold limit",3,1,0,10,0,1,-20,1,0,1,0,1,0,0,1 "+4 food, max prod. no gold limit",4,1,0,10,0,1,-20,1,0,1,0,1,0,0,1 "+5 food, max prod. no gold limit",5,1,0,10,0,1,-20,1,0,1,0,1,0,0,1 "+6 food, max prod. no gold limit",6,1,0,10,0,1,-20,1,0,1,0,1,0,0,1 and even more, some with multiple goals: .. code-block:: ini "research at any cost",0,1,0,5,-20,1,-20,1,-20,1,-20,25,0,0,1 "celebration and growing",1,1,0,25,-20,1,-20,12,-20,1,-20,1,1,0,1 "grow at any cost",1,25,0,5,-20,1,-20,1,-20,1,-20,5,0,0,1 "research and some shields",0,1,0,8,0,1,-3,1,0,1,0,25,0,0,1 "shields and a bit money",0,1,0,25,0,1,-3,3,0,1,0,1,0,0,1 "many shields and some money",0,1,0,25,0,1,0,9,0,1,0,1,0,0,1 "shields and some research",0,1,0,25,0,1,-2,1,0,1,0,8,0,0,1 "celebrate and grow at once",1,1,0,25,-20,1,-20,1,-20,1,-20,8,1,0,1 Enjoy using your citizen Governors!
412
0.64783
1
0.64783
game-dev
MEDIA
0.911419
game-dev
0.622974
1
0.622974
ravendb/docs
5,137
versioned_docs/version-7.0/document-extensions/timeseries/client-api/session/_patch-python.mdx
import Admonition from '@theme/Admonition'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import CodeBlock from '@theme/CodeBlock'; <Admonition type="note" title=""> * Patching multiple time series entries (append or delete entries) can be performed via the _Session_ using [session.advanced.defer](../../../../client-api/operations/patching/single-document.mdx#session-api-using-defer), as described below. * You can handle a single document at a time. * The patching action is defined by the provided [JavaScript](../../../../document-extensions/timeseries/client-api/javascript-support.mdx). * Patching time series entries can also be done directly on the _Store_ via [Operations](../../../../client-api/operations/what-are-operations.mdx), where multiple documents can be handled at a time. Learn more in [Patching time series operations](../../../../document-extensions/timeseries/client-api/operations/patch.mdx). * In this page: * [Usage](../../../../document-extensions/timeseries/client-api/session/patch.mdx#usage) * [Patching examples](../../../../document-extensions/timeseries/client-api/session/patch.mdx#patching-examples) * [Append multiple entries](../../../../document-extensions/timeseries/client-api/session/patch.mdx#append-multiple-entries) * [Delete multiple entries](../../../../document-extensions/timeseries/client-api/session/patch.mdx#delete-multiple-entries) * [Syntax](../../../../document-extensions/timeseries/client-api/session/patch.mdx#syntax) </Admonition> ## Usage * Open a session * Construct a `PatchCommandData` instance and pass it the following: * The document ID that contains the time series * The document change vector (or `None`) * A `PatchRequest` instance with a JavaScript that appends or removes time series entries * Call `session.advanced.defer` and pass it the `PatchCommandData` command. Note that you can call _Defer_ multiple times prior to calling _SaveChanges_. * Call `session.save_changes`. All patch requests added via _Defer_ will be sent to the server for execution when _SaveChanges_ is called. ## Patching examples #### Append multiple entries: In this example, we append 100 time series entries with random heart rate values to a document. <TabItem value="TS_region-Session_Patch-Append-100-Random-TS-Entries" label="TS_region-Session_Patch-Append-100-Random-TS-Entries"> <CodeBlock language="python"> {`base_line = datetime.utcnow() # Create arrays of timestamps and random values to patch values = [] time_stamps = [] for i in range(100): values.append(68 + round(19 * random.uniform(0.0, 1.0))) time_stamps.append(base_line + timedelta(seconds=i)) session.advanced.defer( PatchCommandData( "users/1-A", None, PatchRequest( script=( "var i = 0;" "for(i = 0; i < $values.length; i++)" "\{" " timeseries(id(this), $timeseries)" " .append (" " new Date($time_stamps[i])," " $values[i]," " $tag);" "\}" ), values=\{ "timeseries": "HeartRates", "time_stamps": time_stamps, "values": values, "tag": "watches/fitbit", \}, ), None, ) ) session.save_changes() `} </CodeBlock> </TabItem> #### Delete multiple entries: In this example, we remove a range of 50 time series entries from a document. <TabItem value="TS_region-Session_Patch-Delete-50-TS-Entries" label="TS_region-Session_Patch-Delete-50-TS-Entries"> <CodeBlock language="python"> {`# Delete time-series entries session.advanced.defer( PatchCommandData( "users/1-A", None, PatchRequest( script=("timeseries(this, $timeseries)" ".delete(" " $from," " $to" ");"), values=\{ "timeseries": "HeartRates", "from": base_line, "to": base_line + timedelta(seconds=49), \}, ), None, ) ) `} </CodeBlock> </TabItem> ## Syntax **`PatchCommandData`** <TabItem value="PatchCommandData-definition" label="PatchCommandData-definition"> <CodeBlock language="python"> {`class PatchCommandData(CommandData): def __init__( self, key: str, change_vector: Union[None, str], patch: PatchRequest, patch_if_missing: Optional[PatchRequest] = None, ): ... `} </CodeBlock> </TabItem> Learn more about `PatchCommandData` [here](../../../../client-api/operations/patching/single-document.mdx#session-api-using-defer). **`PatchRequest`** <TabItem value="PatchRequest-definition" label="PatchRequest-definition"> <CodeBlock language="python"> {`class PatchRequest: def __init__(self, script: Optional[str] = "", values: Optional[Dict[str, object]] = None): ... `} </CodeBlock> </TabItem> Learn more about `PatchRequest` [here](../../../../client-api/operations/patching/single-document.mdx#session-api-using-defer).
412
0.696077
1
0.696077
game-dev
MEDIA
0.138031
game-dev
0.904768
1
0.904768
Secrets-of-Sosaria/World
1,554
Data/Scripts/Mobiles/Animals/Rodents/Weasel.cs
using System; using Server; using Server.Engines.Quests; namespace Server.Mobiles { [CorpseName( "a weasel corpse" )] public class Weasel : BaseCreature { [Constructable] public Weasel() : base( AIType.AI_Animal, FightMode.Aggressor, 10, 1, 0.2, 0.4 ) { Name = "a weasel"; Body = 0x117; Hue = 1705; SetStr( 41, 48 ); SetDex( 55 ); SetInt( 75 ); SetHits( 45, 50 ); SetDamage( 7, 9 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 45, 50 ); SetResistance( ResistanceType.Fire, 10, 14 ); SetResistance( ResistanceType.Cold, 30, 40 ); SetResistance( ResistanceType.Poison, 21, 25 ); SetResistance( ResistanceType.Energy, 20, 25 ); SetSkill( SkillName.MagicResist, 4.0 ); SetSkill( SkillName.Tactics, 4.0 ); SetSkill( SkillName.FistFighting, 4.0 ); Tamable = true; ControlSlots = 1; MinTameSkill = -21.3; } public override int Meat{ get{ return 1; } } public override int Hides{ get{ return 1; } } public override int Cloths{ get{ return 1; } } public override ClothType ClothType{ get{ return ClothType.Furry; } } public override FoodType FavoriteFood{ get{ return FoodType.FruitsAndVegies; } } public Weasel( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
412
0.866956
1
0.866956
game-dev
MEDIA
0.959939
game-dev
0.572051
1
0.572051
Simply-Love/Simply-Love-SM5
2,482
BGAnimations/ScreenGameplay underlay/default.lua
-- if the MenuTimer is enabled, we should reset SSM's MenuTimer now that we've reached Gameplay if PREFSMAN:GetPreference("MenuTimer") then SL.Global.MenuTimer.ScreenSelectMusic = ThemePrefs.Get("ScreenSelectMusicMenuTimer") end local Players = GAMESTATE:GetHumanPlayers() local holdingCtrl = false local RestartHandler = function(event) if not event then return end if event.type == "InputEventType_FirstPress" then if event.DeviceInput.button == "DeviceButton_left ctrl" then holdingCtrl = true elseif event.DeviceInput.button == "DeviceButton_r" then if holdingCtrl then SCREENMAN:GetTopScreen():SetPrevScreenName("ScreenGameplay"):SetNextScreenName("ScreenGameplay"):begin_backing_out() end end elseif event.type == "InputEventType_Release" then if event.DeviceInput.button == "DeviceButton_left ctrl" then holdingCtrl = false end end end local t = Def.ActorFrame{ Name="GameplayUnderlay", OnCommand=function(self) if ThemePrefs.Get("KeyboardFeatures") and PREFSMAN:GetPreference("EventMode") and not GAMESTATE:IsCourseMode() then SCREENMAN:GetTopScreen():AddInputCallback(RestartHandler) end end } for player in ivalues(Players) do t[#t+1] = LoadActor("./PerPlayer/Danger.lua", player) t[#t+1] = LoadActor("./PerPlayer/StepStatistics/default.lua", player) t[#t+1] = LoadActor("./PerPlayer/BackgroundFilter.lua", player) t[#t+1] = LoadActor("./PerPlayer/nice.lua", player) end -- UI elements shared by both players t[#t+1] = LoadActor("./Shared/VersusStepStatistics.lua") t[#t+1] = LoadActor("./Shared/Header.lua") t[#t+1] = LoadActor("./Shared/SongInfoBar.lua") -- song title and progress bar -- per-player UI elements for player in ivalues(Players) do -- Tournament Mode modifications. Put this before everything as it sets -- player mods and other actors below might depend on it. t[#t+1] = LoadActor("./PerPlayer/TournamentMode.lua", player) t[#t+1] = LoadActor("./PerPlayer/UpperNPSGraph.lua", player) t[#t+1] = LoadActor("./PerPlayer/Score.lua", player) t[#t+1] = LoadActor("./PerPlayer/DifficultyMeter.lua", player) t[#t+1] = LoadActor("./PerPlayer/LifeMeter/default.lua", player) t[#t+1] = LoadActor("./PerPlayer/TargetScore/default.lua", player) -- All NoteField specific actors are contained in this file. t[#t+1] = LoadActor("./PerPlayer/NoteField/default.lua", player) end -- add to the ActorFrame last; overlapped by StepStatistics otherwise t[#t+1] = LoadActor("./Shared/BPMDisplay.lua") return t
412
0.840989
1
0.840989
game-dev
MEDIA
0.932659
game-dev
0.897539
1
0.897539
FirelandsProject/firelands-cata
14,360
src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp
/* * This file is part of the FirelandsCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "shadowfang_keep.h" #include "AreaBoundary.h" #include "GameObject.h" #include "Player.h" #include "InstanceScript.h" #include "shadowfang_keep.h" #include "Map.h" #include "Creature.h" #include "EventMap.h" #include "CreatureAI.h" ObjectData const creatureData[] = { { BOSS_BARON_ASHBURY, DATA_BARON_ASHBURY }, { BOSS_BARON_SILVERLAINE, DATA_BARON_SILVERLAINE }, { BOSS_COMMANDER_SPRINGVALE, DATA_COMMANDER_SPRINGVALE }, { BOSS_LORD_WALDEN, DATA_LORD_WALDEN }, { BOSS_LORD_GODFREY, DATA_LORD_GODFREY }, { NPC_DEBUG_ANNOUNCER, DATA_DEBUG_ANNOUNCER }, { 0, 0 } // END }; ObjectData const gameobjectData[] = { { GO_COURTYARD_DOOR, DATA_COURTYARD_DOOR, }, { GO_SORCERERS_DOOR, DATA_SORCERER_GATE, }, { GO_ARUGALS_LAIR, DATA_ARUGAL_DOOR, }, { 0, 0 } // END }; DoorData const doorData[] = { { GO_ARUGALS_LAIR, DATA_LORD_GODFREY, DOOR_TYPE_ROOM }, { 0, 0, DOOR_TYPE_ROOM } // END }; BossBoundaryData const boundaries = { { DATA_COMMANDER_SPRINGVALE, new ParallelogramBoundary(Position(-222.75f, 2269.03f), Position(-217.60f, 2249.65f), Position(-267.47f, 2256.10f)) }, { DATA_LORD_WALDEN, new CircleBoundary(Position(-146.58f, 2173.037f), 17.0) }, }; enum SpawnGroups { SPAWN_GROUP_ENTRANCE_ALLIANCE = 412, // Spawned by default when Baron Ashbury is not defeated for Alliance players SPAWN_GROUP_ENTRANCE_HORDE = 413, // Spawned by default when Baron Ashbury is not defeated for Horde players SPAWN_GROUP_DISEASE_CLOUDS_ENTRANCE = 414, // Spawned by default for Horde players SPAWN_GROUP_DISEASE_CLOUDS_BARON_ASHBURY = 415, // Spawned for Horde players when Baron Ashbury has been defeated SPAWN_GROUP_DISEASE_CLOUDS_BARON_SILVERLAINE = 416, // Spawned for Horde players when Baron Silverlaine has been defeated SPAWN_GROUP_DISEASE_CLOUDS_COMMANDER_SPRINGVALE = 417, // Spawned for Horde players when Commander Springvale has been defeated SPAWN_GROUP_DISEASE_CLOUDS_LORD_WALDEN = 418, // Spawned for Horde players when Lord Walden has been defeated SPAWN_GROUP_LORD_GODFREY_DEAD_TROUPS_ALLIANCE = 419, // Spawned for Alliance players when Lord Walden has been defeated SPAWN_GROUP_LORD_GODFREY_DEAD_TROUPS_HORDE = 420, // Spawned for Horde players when Lord Walden has been defeated SPAWN_GROUP_BARON_ASHBURY_TROUPS_ALLIANCE = 421, // Spawned for Alliance players when Baron Ashbury has been defeated SPAWN_GROUP_BARON_ASHBURY_TROUPS_HORDE = 422, // Spawned for Horde players when Baron Ashbury has been defeated SPAWN_GROUP_BARON_SILVERLAINE_TROUPS_ALLIANCE = 423, // Spawned for Alliance players when Baron Silverlaine has been defeated SPAWN_GROUP_BARON_SILVERLAINE_TROUPS_HORDE = 424, // Spawned for Horde players when Baron Silverlaine has been defeated SPAWN_GROUP_COMMANDER_SPRINGVALE_TROUPS_ALLIANCE = 425, // Spawned for Alliance players when Commander Springvale has been defeated SPAWN_GROUP_OUTSIDE_TROUPS_ALLIANCE = 426, // Spawned for Alliance players when triggering an areatrigger after defeating Commander Springvale SPAWN_GROUP_LORD_WALDEN_TROUPS_ALLIANCE = 427, // Spawned for Alliance players when Lord Walden has been defeated SPAWN_GROUP_COMMANDER_SPRINGVALE_TROUPS_HORDE = 428, // Spawned for Horde players when Commander Springvale or Lord Walden has been defeated SPAWN_GROUP_COMMANDER_SPRINGVALE_BELMONT = 429, // Spawned for Horde players when Commander Springvale has been defeated SPAWN_GROUP_LORD_WALDEN_BELMONT = 430, // Spawned for Horde players when Lord Walden has been defeated SPAWN_GROUP_LORD_GODFREY_IVAR_BLOODFANG = 431, // Spawned for Alliance players when triggering an areatrigger near Lord Godfrey's room SPAWN_GROUP_LORD_GODFREY_BELMONT = 432 // Spawned for Horde players when triggering an areatrigger near Lord Godfrey's room }; struct SpawnGroupInfo { uint32 AllianceSpawnGroup = 0; uint32 HordeSpawnGroup = 0; uint32 DiseaseCloudsSpawnGroup = 0; }; std::unordered_map<uint32 /*bossStateId*/, SpawnGroupInfo> SpawnGroupsByBossStateId = { { DATA_BARON_ASHBURY, { SPAWN_GROUP_BARON_ASHBURY_TROUPS_ALLIANCE, SPAWN_GROUP_BARON_ASHBURY_TROUPS_HORDE, SPAWN_GROUP_DISEASE_CLOUDS_BARON_ASHBURY }}, { DATA_BARON_SILVERLAINE, { SPAWN_GROUP_BARON_SILVERLAINE_TROUPS_ALLIANCE, SPAWN_GROUP_BARON_SILVERLAINE_TROUPS_HORDE, SPAWN_GROUP_DISEASE_CLOUDS_BARON_SILVERLAINE }}, { DATA_COMMANDER_SPRINGVALE, { SPAWN_GROUP_COMMANDER_SPRINGVALE_TROUPS_ALLIANCE, SPAWN_GROUP_COMMANDER_SPRINGVALE_BELMONT, SPAWN_GROUP_DISEASE_CLOUDS_COMMANDER_SPRINGVALE }}, { DATA_LORD_WALDEN, { SPAWN_GROUP_LORD_WALDEN_TROUPS_ALLIANCE, SPAWN_GROUP_LORD_WALDEN_BELMONT, SPAWN_GROUP_DISEASE_CLOUDS_LORD_WALDEN }}, }; class instance_shadowfang_keep : public InstanceMapScript { public: instance_shadowfang_keep() : InstanceMapScript(SKScriptName, 33) { } struct instance_shadowfang_keep_InstanceMapScript : public InstanceScript { instance_shadowfang_keep_InstanceMapScript(InstanceMap* map) : InstanceScript(map) { SetHeaders(DataHeader); SetBossNumber(EncounterCount); LoadDoorData(doorData); LoadBossBoundaries(boundaries); LoadObjectData(creatureData, gameobjectData); } void OnPlayerEnter(Player* player) override { if (!_teamInInstance.has_value()) { _teamInInstance = player->GetTeam(); // Setting up entrance spawns when Baron Ashbury has not been defeated yet if (GetBossState(DATA_BARON_ASHBURY) != DONE) instance->SpawnGroupSpawn(*_teamInInstance == ALLIANCE ? SPAWN_GROUP_ENTRANCE_ALLIANCE : SPAWN_GROUP_ENTRANCE_HORDE); // Setting up disease clouds based on instance progress if (*_teamInInstance == HORDE) { for (uint32 bossId : { DATA_BARON_ASHBURY, DATA_BARON_SILVERLAINE, DATA_COMMANDER_SPRINGVALE, DATA_LORD_WALDEN }) { if (GetBossState(bossId) == DONE) { SpawnGroupInfo spawnGroupInfo = SpawnGroupsByBossStateId[bossId]; instance->SpawnGroupSpawn(spawnGroupInfo.DiseaseCloudsSpawnGroup); } } } // Setting up dead troup spawns when Lord Walden has been defeated already if (GetBossState(DATA_LORD_WALDEN) == DONE) instance->SpawnGroupSpawn(*_teamInInstance == ALLIANCE ? SPAWN_GROUP_LORD_GODFREY_DEAD_TROUPS_ALLIANCE : SPAWN_GROUP_LORD_GODFREY_DEAD_TROUPS_HORDE); } } void OnCreatureCreate(Creature* creature) override { InstanceScript::OnCreatureCreate(creature); switch (creature->GetEntry()) { case NPC_FORSAKEN_BLIGHTSPREADER: creature->SetDisplayId(creature->GetCreatureTemplate()->Modelid1); break; case NPC_HIGH_WARLORD_CROMUSH: if (creature->ToTempSummon()) _cromushGUID = creature->GetGUID(); break; case NPC_PISTOL_BARRAGE_DUMMY: if (Creature* godfrey = GetCreature(DATA_LORD_GODFREY)) if (godfrey->IsAIEnabled()) godfrey->AI()->JustSummoned(creature); break; default: break; } } void OnGameObjectCreate(GameObject* go) override { InstanceScript::OnGameObjectCreate(go); switch (go->GetEntry()) { case GO_COURTYARD_DOOR: if (GetBossState(DATA_BARON_ASHBURY) == DONE) go->SetGoState(GO_STATE_ACTIVE); break; case GO_SORCERERS_DOOR: if (GetBossState(DATA_LORD_WALDEN) == DONE) go->SetGoState(GO_STATE_ACTIVE); break; case GO_ARUGALS_LAIR: if (GetBossState(DATA_LORD_GODFREY) != DONE) go->SetGoState(GO_STATE_READY); break; default: break; } } bool SetBossState(uint32 type, EncounterState state) override { if (!InstanceScript::SetBossState(type, state)) return false; if (state != DONE || type == BOSS_LORD_GODFREY) return true; SpawnGroupInfo spawnGroupInfo = SpawnGroupsByBossStateId[type]; // Clean up previous spawned groups DespawnPreviousTroups(); // Spawn group linked to boss encounter instance->SpawnGroupSpawn(*_teamInInstance == ALLIANCE ? spawnGroupInfo.AllianceSpawnGroup : spawnGroupInfo.HordeSpawnGroup); // Spawn disease clouds linked to boss encounter if (*_teamInInstance == HORDE) instance->SpawnGroupSpawn(spawnGroupInfo.DiseaseCloudsSpawnGroup); // Spawn dead troups after defeating Lord Walden if (type == DATA_LORD_WALDEN) instance->SpawnGroupSpawn(*_teamInInstance == ALLIANCE ? SPAWN_GROUP_LORD_GODFREY_DEAD_TROUPS_ALLIANCE : SPAWN_GROUP_LORD_GODFREY_DEAD_TROUPS_HORDE); // Special case for Commander Springvale Horde troups if (*_teamInInstance == HORDE) { if ((type == DATA_LORD_WALDEN && GetBossState(DATA_COMMANDER_SPRINGVALE) != DONE) || (type == DATA_COMMANDER_SPRINGVALE && GetBossState(DATA_LORD_WALDEN) != DONE)) instance->SpawnGroupSpawn(SPAWN_GROUP_COMMANDER_SPRINGVALE_TROUPS_HORDE); } return true; } void SetData(uint32 type, uint32 /*value*/) override { switch (type) { case DATA_OUTSIDE_TROUPS_SPAWN: if (*_teamInInstance == ALLIANCE) instance->SpawnGroupSpawn(SPAWN_GROUP_OUTSIDE_TROUPS_ALLIANCE); break; case DATA_GODFREY_INTRO_SPAWN: if (*_teamInInstance == ALLIANCE) instance->SpawnGroupDespawn(SPAWN_GROUP_LORD_WALDEN_TROUPS_ALLIANCE); else { instance->SpawnGroupDespawn(SPAWN_GROUP_COMMANDER_SPRINGVALE_TROUPS_HORDE); instance->SpawnGroupDespawn(SPAWN_GROUP_LORD_WALDEN_BELMONT); } instance->SpawnGroupSpawn(*_teamInInstance == ALLIANCE ? SPAWN_GROUP_LORD_GODFREY_IVAR_BLOODFANG : SPAWN_GROUP_LORD_GODFREY_BELMONT); break; default: break; } } uint32 GetData(uint32 type) const override { switch (type) { case DATA_TEAM_IN_INSTANCE: return *_teamInInstance; default: break; } return 0; } void DespawnPreviousTroups() { if (*_teamInInstance == ALLIANCE) { instance->SpawnGroupDespawn(SPAWN_GROUP_ENTRANCE_ALLIANCE); instance->SpawnGroupDespawn(SPAWN_GROUP_BARON_ASHBURY_TROUPS_ALLIANCE); instance->SpawnGroupDespawn(SPAWN_GROUP_BARON_SILVERLAINE_TROUPS_ALLIANCE); instance->SpawnGroupDespawn(SPAWN_GROUP_COMMANDER_SPRINGVALE_TROUPS_ALLIANCE); instance->SpawnGroupDespawn(SPAWN_GROUP_OUTSIDE_TROUPS_ALLIANCE); } else { instance->SpawnGroupDespawn(SPAWN_GROUP_ENTRANCE_HORDE); instance->SpawnGroupDespawn(SPAWN_GROUP_BARON_ASHBURY_TROUPS_HORDE); instance->SpawnGroupDespawn(SPAWN_GROUP_BARON_SILVERLAINE_TROUPS_HORDE); instance->SpawnGroupDespawn(SPAWN_GROUP_COMMANDER_SPRINGVALE_BELMONT); // Despawn the summoned Cromush version as he is not a part of the spawn groups if (Creature* cromush = instance->GetCreature(_cromushGUID)) cromush->DespawnOrUnsummon(); } } protected: EventMap events; Optional<uint32>_teamInInstance; ObjectGuid _cromushGUID; }; InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_shadowfang_keep_InstanceMapScript(map); } }; void AddSC_instance_shadowfang_keep() { new instance_shadowfang_keep(); }
412
0.725429
1
0.725429
game-dev
MEDIA
0.993278
game-dev
0.839022
1
0.839022
EdenQwQ/nixos
3,137
home/lib/wallpaper/buildWallpaper.nix
{ pkgs, lib, config, ... }: with builtins; let inherit (config.lib.wallpapers) goNord lutgen; getWallpaper = wallpaper: let inherit (wallpaper) name baseImageName path convertMethod effects ; in { inherit name baseImageName convertMethod effects ; } // ( if path == null then { path = "${pkgs.wallpapers}/${name}"; } else { inherit path; } ); applyEffect = { name, path, }: effectName: effectOptions: if config.lib.wallpapers.effects ? ${effectName} then config.lib.wallpapers.effects.${effectName} ({ inherit name path; } // effectOptions.options) else path; # if hasAttr effect.name config.lib.wallpapers.effects then # config.lib.wallpapers.effects.${effect.name} { inherit name path; } // effect.passthru # else # path; applyEffects = wallpaper: let inherit (wallpaper) name baseImageName path convertMethod effects ; in { inherit name baseImageName convertMethod; } // ( if effects == null then { inherit path; } else { path = lib.attrsets.filterAttrs (_: v: v.enable == true) effects |> lib.attrsets.foldlAttrs ( acc: effectName: effectOptions: applyEffect { inherit name; path = acc; } effectName effectOptions ) path; } ); generateWallpaper = wallpaper: let inherit (wallpaper) path convertMethod; name = match "(.*)\\..*" wallpaper.name |> head; baseImageName = if wallpaper.baseImageName == null then name else wallpaper.baseImageName; live = (toString path |> match ".*gif$") != null; thisWallpaper = { inherit name path live; }; in { inherit name live; path = if lib.strings.hasPrefix baseImageName config.lib.stylix.colors.scheme then path else if convertMethod == "gonord" then goNord thisWallpaper else if convertMethod == "lutgen" then lutgen thisWallpaper else path; }; setWallpaper = wallpaper: let inherit (wallpaper) name live path; ext = if live then ".gif" else ".jpg"; in { name = "Pictures/Wallpapers/generated/${name}${ext}"; value = { source = path; }; }; blurWallpaper = wallpaper: let inherit (wallpaper) name path live; in if live then null else { name = "Pictures/Wallpapers/generated/${name}-blurred.jpg"; value = { source = pkgs.runCommand "${name}-blurred.jpg" { } '' ${pkgs.imagemagick}/bin/magick ${path} -blur 0x30 $out ''; }; }; in { lib.wallpapers = { inherit getWallpaper applyEffects convertWallpaper generateWallpaper setWallpaper blurWallpaper ; }; }
412
0.617334
1
0.617334
game-dev
MEDIA
0.383177
game-dev
0.501015
1
0.501015
nexusnode/crafting-dead
4,595
crafting-dead-decoration/src/main/java/com/craftingdead/decoration/CraftingDeadDecoration.java
/* * Crafting Dead * Copyright (C) 2022 NexusNode LTD * * This Non-Commercial Software License Agreement (the "Agreement") is made between * you (the "Licensee") and NEXUSNODE (BRAD HUNTER). (the "Licensor"). * By installing or otherwise using Crafting Dead (the "Software"), you agree to be * bound by the terms and conditions of this Agreement as may be revised from time * to time at Licensor's sole discretion. * * If you do not agree to the terms and conditions of this Agreement do not download, * copy, reproduce or otherwise use any of the source code available online at any time. * * https://github.com/nexusnode/crafting-dead/blob/1.18.x/LICENSE.txt * * https://craftingdead.net/terms.php */ package com.craftingdead.decoration; import org.slf4j.Logger; import com.craftingdead.decoration.client.ClientDist; import com.craftingdead.decoration.data.DecorationBlockModelProvider; import com.craftingdead.decoration.data.DecorationBlockStateProvider; import com.craftingdead.decoration.data.DecorationItemModelProvider; import com.craftingdead.decoration.data.DecorationRecipeProvider; import com.craftingdead.decoration.data.loot.DecorationLootTableProvider; import com.craftingdead.decoration.world.item.DecorationItems; import com.craftingdead.decoration.world.level.block.DecorationBlocks; import com.mojang.logging.LogUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.forge.event.lifecycle.GatherDataEvent; import net.minecraftforge.registries.ForgeRegistries; @Mod(CraftingDeadDecoration.ID) public class CraftingDeadDecoration { public static final String ID = "craftingdeaddecoration"; private static final String OLD_ID = "cityblocks"; private static final Logger logger = LogUtils.getLogger(); public CraftingDeadDecoration() { DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> ClientDist::new); var modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); modEventBus.addListener(this::handleGatherData); DecorationBlocks.deferredRegister.register(modEventBus); DecorationItems.deferredRegister.register(modEventBus); MinecraftForge.EVENT_BUS.addGenericListener(Block.class, this::handleMissingBlocks); MinecraftForge.EVENT_BUS.addGenericListener(Item.class, this::handleMissingItems); } private void handleGatherData(GatherDataEvent event) { var generator = event.getGenerator(); var existingFileHelper = event.getExistingFileHelper(); if (event.includeClient()) { generator.addProvider(new DecorationBlockModelProvider(generator, existingFileHelper)); generator.addProvider(new DecorationBlockStateProvider(generator, existingFileHelper)); generator.addProvider(new DecorationItemModelProvider(generator, existingFileHelper)); } else if (event.includeServer()) { generator.addProvider(new DecorationLootTableProvider(generator)); generator.addProvider(new DecorationRecipeProvider(generator)); } } private void handleMissingItems(RegistryEvent.MissingMappings<Item> event) { var missingMappings = event.getMappings(OLD_ID); for (var mapping : missingMappings) { var newKey = new ResourceLocation(ID, mapping.key.getPath()); var newValue = ForgeRegistries.ITEMS.getValue(newKey); if (newValue == null || newValue == Items.AIR) { throw new IllegalStateException("Failed to re-map: " + mapping.key.toString()); } mapping.remap(newValue); logger.info("Remapped item {} -> {}/{}", mapping.key, newKey, newValue); } } private void handleMissingBlocks(RegistryEvent.MissingMappings<Block> event) { var missingMappings = event.getMappings(OLD_ID); for (var mapping : missingMappings) { var newKey = new ResourceLocation(ID, mapping.key.getPath()); var newValue = ForgeRegistries.BLOCKS.getValue(newKey); if (newValue == null || newValue == Blocks.AIR) { throw new IllegalStateException("Failed to re-map: " + mapping.key.toString()); } mapping.remap(newValue); logger.info("Remapped block {} -> {}/{}", mapping.key, newKey, newValue); } } }
412
0.925575
1
0.925575
game-dev
MEDIA
0.993705
game-dev
0.928399
1
0.928399
maraakate/q2dos
41,701
dday/p_observer.c
/* D-Day: Normandy by Vipersoft ************************************ * $Source: /usr/local/cvsroot/dday/src/p_observer.c,v $ * $Revision: 1.20 $ * $Date: 2002/07/25 08:28:43 $ * *********************************** Copyright (C) 2002 Vipersoft This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "g_local.h" #include "p_menus.h" void Cmd_Objectives (edict_t *ent); void M_ChooseMOS(edict_t *ent); void Killed(edict_t * targ , edict_t * inflictor , edict_t * attacker , int damage , vec3_t point ); //this file is for all the stuff that relates to observer mode, particularly during the begingg //of the game when players are joining teams and setting mos. //faf: returns a count for # of players on team. using this to fix // bugs with auto-join team and to fix reporting team counts incorrectly int PlayerCountForTeam (int team_number, qboolean countbots) { int i; int playercount = 0; edict_t *check_ent; for (i = 1; i <= maxclients->value; i++) { check_ent = g_edicts + i; if (!check_ent->inuse) continue; if (!check_ent->client || !check_ent->client->resp.team_on) continue; if (countbots == false && check_ent->ai) continue; if (check_ent->client->resp.team_on->index == team_number) playercount++; } return playercount; } // clients will use these void SwitchToObserver(edict_t *ent) { // start as observer ent->movetype = MOVETYPE_NOCLIP; ent->solid = SOLID_NOT; ent->svflags |= SVF_NOCLIENT; ent->client->ps.gunindex = 0; //ent->client->pers.weapon=NULL; gi.linkentity (ent); ent->client->limbo_mode=true; // ent->client->deathfade = 0; if (!ent->client->display_info && ent->client->layout_type != SHOW_CAMPAIGN) { if(team_list[0]) MainMenu(ent); } } //faf parachutes :P void Chute_Think(edict_t *ent) { if (level.intermissiontime || ent->owner->deadflag) { ent->think = G_FreeEdict; ent->nextthink = level.time + .1; return; } //done with it if (ent->s.frame == 10) { if (ent->owner->client) ent->owner->client->landed = true; ent->movetype = MOVETYPE_NONE; ent->gravity = 0; ent->nextthink = level.time + 2; ent->think = G_FreeEdict; return; } ent->nextthink = level.time + .1; // gi.dprintf(DEVELOPER_MSG_GAME, "%f\n",ent->owner->client->jump_stamina); //we've touched the ground if (ent->owner->client && ent->owner->groundentity || ent->owner->velocity[2] > 0 || ent->owner->client->jump_stamina < 80 || ent->s.frame > 5) // ent->owner->client->ps.pmove.gravity == sv_gravity->value)//landed { if (ent->s.frame < 10) //start parachute falling { ent->owner->client->ps.pmove.gravity = sv_gravity->value; //ent->owner->client->landed = true; ent->s.sound = 0; ent->s.frame++; if (ent->owner->velocity[2] <= 0 || // keeps chute from floating when landing ent->s.frame < 3) ent->s.origin[2] = ent->owner->s.origin[2]; return; } } else //not on ground if (ent->owner->velocity[2] > 0) //just jumped { // ent->s.frame = 0; ent->s.origin[0] = ent->owner->s.origin[0]; ent->s.origin[1] = ent->owner->s.origin[1]; ent->gravity = 0; ent->s.sound = gi.soundindex("faf/flag.wav"); ent->owner->client->landed = false; ent->owner->client->ps.pmove.gravity = .25 * (sv_gravity->value) ; //parchute factor } else { ent->s.frame = 0; VectorCopy (ent->owner->s.origin, ent->s.origin); ent->gravity = .25; ent->s.sound = gi.soundindex("faf/flag.wav"); ent->movetype = MOVETYPE_TOSS; ent->owner->client->landed = false; } if (ent->velocity[2] <-500) ent->velocity [2] = -500; /* if (ent->s.frame < 10 && !ent->owner->groundentity) { ent->s.frame = 0;// restart the chute VectorCopy (ent->owner->s.origin, ent->s.origin); ent->movetype = MOVETYPE_TOSS; ent->s.sound = gi.soundindex("faf/flag.wav"); } */ } void Spawn_Chute(edict_t *ent) { //faf vec3_t start; vec3_t end; vec3_t world_up, down; trace_t tr; edict_t *chute; ent->client->landed = true; VectorCopy(ent->s.origin, start); VectorSet(world_up, 0, 0, 1); VectorMA(start, 8192, world_up, end); tr = gi.trace(start, NULL, NULL, end, ent, MASK_SHOT|CONTENTS_SLIME|CONTENTS_LAVA); if ( tr.surface && !(tr.surface->flags & SURF_SKY)) //under a roof { return; } VectorSet(down, 0, 0, -1); VectorMA(start, 100, down, end); tr = gi.trace(start, NULL, NULL, end, ent, MASK_SHOT|CONTENTS_SLIME|CONTENTS_LAVA); if ( tr.fraction < 1.0 ) //not high off ground { return; } ent->client->landed = false; chute = G_Spawn(); chute->movetype = MOVETYPE_TOSS; chute->solid = SOLID_TRIGGER; chute->gravity = .25; chute->s.modelindex = gi.modelindex ("models/objects/chute/tris.md2"); chute->s.sound = gi.soundindex("faf/flag.wav"); chute->think = Chute_Think; chute->nextthink = level.time + .1; chute->owner = ent; chute->clipmask = MASK_SHOT; VectorClear (chute->mins); VectorClear (chute->maxs); chute->classname = "chute"; VectorCopy (ent->s.origin, chute->s.origin); } void Spawn_Chute_Special(edict_t *ent) { //faf vec3_t start; vec3_t end; vec3_t world_up, down; trace_t tr; edict_t *chute; if (ent->client->has_chute == false) return; ent->client->landed = true; VectorCopy(ent->s.origin, start); VectorSet(world_up, 0, 0, 1); VectorMA(start, 8192, world_up, end); tr = gi.trace(start, NULL, NULL, end, ent, MASK_SHOT|CONTENTS_SLIME|CONTENTS_LAVA); // if ( tr.surface && !(tr.surface->flags & SURF_SKY)) //under a roof // { // return; // } VectorSet(down, 0, 0, -1); VectorMA(start, 100, down, end); tr = gi.trace(start, NULL, NULL, end, ent, MASK_SHOT|CONTENTS_SLIME|CONTENTS_LAVA); if ( tr.fraction < 1.0 ) //not high off ground { return; } ent->client->landed = false; ent->client->has_chute = false; chute = G_Spawn(); chute->movetype = MOVETYPE_TOSS; chute->solid = SOLID_TRIGGER; chute->gravity = .25; chute->s.modelindex = gi.modelindex ("models/objects/chute/tris.md2"); chute->s.sound = gi.soundindex("faf/flag.wav"); chute->think = Chute_Think; chute->nextthink = level.time + .1; chute->owner = ent; chute->clipmask = MASK_SHOT; VectorClear (chute->mins); VectorClear (chute->maxs); chute->classname = "chute"; VectorCopy (ent->s.origin, chute->s.origin); } //this function exits observer mode, presumably after they have chosen mos. They must have //joined a team, if one is avaiable... void Find_Mission_Start_Point(edict_t *ent, vec3_t origin, vec3_t angles); void EndObserverMode(edict_t* ent) { vec3_t spawn_origin, spawn_angles; if (!ent->client->limbo_mode) return; if (ent->leave_limbo_time > level.time) return; if( !team_list[0] || !ent->client->resp.team_on) { // safe_cprintf(ent,PRINT_HIGH,"You must join a team first!\n"); return; } if (!(ent->svflags & SVF_NOCLIENT)) return; // not in observer mode /* //if they are the first on team, make em captain if( ent->client->resp.team_on->units[0]==ent && deathmatch->value) { if (ent->client->resp.mos != OFFICER) safe_centerprintf(ent, "You have been promoted to Officer!\n"); ent->client->resp.team_on->officer_mos=ent->client->resp.mos; //store the new officer's old backup mos ent->client->resp.bkupmos=ent->client->resp.mos; ent->client->resp.mos=OFFICER; DoEndOM(ent); } */ DoEndOM(ent); //ok put the player where he's supposed to be ent->client->spawntime = level.time; Find_Mission_Start_Point(ent, spawn_origin, spawn_angles); // unlink to make sure it can't possibly interfere with KillBox gi.unlinkentity (ent); ent->client->ps.pmove.origin[0] = spawn_origin[0]*8; ent->client->ps.pmove.origin[1] = spawn_origin[1]*8; ent->client->ps.pmove.origin[2] = spawn_origin[2]*8; VectorCopy (spawn_origin, ent->s.origin); ent->s.origin[2] += 1; // make sure off ground VectorCopy (ent->s.origin, ent->s.old_origin); // clear the velocity and hold them in place briefly VectorClear (ent->velocity); ent->client->ps.pmove.pm_time = 160>>3; // hold time ent->client->ps.pmove.pm_flags |= PMF_TIME_LAND; // pbowens: changed from PMF_TIME_TELEPORT, no particles ent->client->limbo_mode=false; // VectorClear (ent->s.angles); // VectorClear (ent->client->ps.viewangles); // VectorClear (ent->client->v_angle); gi.linkentity (ent); ent->client->resp.AlreadySpawned=true; //safe_bprintf (PRINT_HIGH, "%s has entered the battle.\n", ent->client->pers.netname); WeighPlayer(ent); //moved up ent->client->spawntime = level.time; /*move to spawn_chute if (ent->client->resp.mos == SPECIAL) ent->client->landed = false; else ent->client->landed = true; */ ent->client->landed = true; //faf /*requires model*/ if (ent->client->resp.mos == SPECIAL) { ent->client->has_chute = true; Spawn_Chute(ent); } Remove_Nearby_Sandbags(ent); } void sandbag_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point); void Remove_Nearby_Sandbags(edict_t *ent) { vec3_t vdist; float tdist; int i; edict_t *e; for (i=0 ; i<game.maxentities ; i++) { e = &g_edicts[i]; if (!e->inuse) continue; if (!e->classnameb) continue; if (e->classnameb != SANDBAGS) continue; VectorSubtract (e->s.origin, ent->s.origin, vdist); tdist = VectorLength (vdist); if (tdist > 64) continue; //gi.dprintf(DEVELOPER_MSG_GAME, "djksflsdfjklsdfjkl\n"); sandbag_die (e, ent, ent, 99999999, e->s.origin); } } qboolean OpenSpot (edict_t *ent, mos_t class) { // int index; int spots, taken, j; TeamS_t *team; edict_t *cl_ent; team=ent->client->resp.team_on; if (class_limits->value == 0) // class limits turned off { team->mos[class]->available = 99; return true; } /* for (taken = 0, index = 0; index < MAX_TEAM_MATES; index++) { if (!team->units[index]) continue; if (team->units[index]->client->resp.mos == class) { // if you're already that class, leave a spot for yourself //if (team->units[index] == ent) // continue; taken++; } } */ //faf: hopefully fixes class bugs taken = 0; for (j=0 ; j < game.maxclients ; j++) { cl_ent = g_edicts + 1 + j; if (!cl_ent->inuse) continue; if (cl_ent->ai) continue; if (!cl_ent->client || !cl_ent->client->resp.team_on || !cl_ent->client->resp.team_on->mos || cl_ent->client->resp.team_on->index != ent->client->resp.team_on->index) continue; if (class == cl_ent->client->resp.mos) taken++; } // Not-so-good way of doing things, but it gets the job done switch (class) { case INFANTRY: spots = MAX_INFANTRY; team->mos[INFANTRY]->available = MAX_INFANTRY - taken; break; case OFFICER: spots = MAX_OFFICERS; team->mos[OFFICER]->available = MAX_OFFICERS - taken; break; case L_GUNNER: spots = MAX_L_GUNNER; team->mos[L_GUNNER]->available = MAX_L_GUNNER - taken; break; case H_GUNNER: spots = MAX_H_GUNNER; team->mos[H_GUNNER]->available = MAX_H_GUNNER - taken; break; case SNIPER: spots = MAX_SNIPER; team->mos[SNIPER]->available = MAX_SNIPER - taken; break; case SPECIAL: spots = MAX_SPECIAL; team->mos[SPECIAL]->available = MAX_SPECIAL - taken; break; case ENGINEER: spots = MAX_ENGINEER; team->mos[ENGINEER]->available = MAX_ENGINEER - taken; break; case MEDIC: spots = MAX_MEDIC; team->mos[MEDIC]->available = MAX_MEDIC - taken; break; case FLAMER: spots = MAX_FLAMER; team->mos[FLAMER]->available = MAX_FLAMER - taken; break; default: spots = 0; team->mos[class]->available = 0; break; } if (mapclasslimits[team->index][class].limit) { spots = mapclasslimits[team->index][class].limit; team->mos[class]->available = spots - taken; } if (spots < 0) spots = 0; /* safe_bprintf(PRINT_HIGH, "class_stat %s: %s -- %i/%i (%i)\n", ent->client->pers.netname, team->mos[class]->name, taken, spots, team->mos[class]->available);*/ if (team->mos[class]->available > 0) return true; else return false; } void DoEndOM(edict_t *ent /*,qboolean notOfficer*/) { /*if (!ent->client->resp.mos) { safe_cprintf(ent, PRINT_HIGH, "You aren't assigned to a class!\n"); return; }*/ if (!ent->client->resp.team_on) { safe_cprintf(ent, PRINT_HIGH, "You aren't assigned to any team!\n"); return; } // assign bkupmos to mos // ent->client->resp.bkupmos=ent->client->resp.mos; // if they changed class if (ent->client->resp.newmos) { if (ent->client->resp.mos == NONE || ent->client->resp.mos != ent->client->resp.newmos) { if (OpenSpot(ent, ent->client->resp.newmos)) { ent->client->resp.mos = ent->client->resp.newmos; ent->client->resp.team_on->mos[ent->client->resp.mos]->available--; } else { if (ent->client->resp.mos == NONE) { safe_centerprintf(ent, "Request for class denied: Infantry\n"); ent->client->resp.mos = INFANTRY; } else safe_centerprintf(ent, "Your new selected class already\nhas enough players. Retain your\nassignment.\n"); } ent->client->resp.newmos = NONE; } } // reset playermodel with team's SyncUserInfo(ent, true); ent->takedamage = DAMAGE_YES; ent->movetype = MOVETYPE_WALK; ent->viewheight = 20;//faf 22; ent->inuse = true; //ent->classname = "private"; ent->mass = 200; ent->solid = SOLID_TRIGGER; //don't set this until seconds after respawn //ent->client->OBTime=level.time+OBDELAY; ent->deadflag = DEAD_NO; ent->air_finished = level.time + 12; ent->clipmask = MASK_PLAYERSOLID; ent->svflags &= ~SVF_NOCLIENT; ent->wound_location=0; Give_Class_Weapon(ent); Give_Class_Ammo(ent); //if (ent->client->resp.mos == AIRBORNE) // ent->flags |= FL_BOOTS; safe_cprintf(ent,PRINT_HIGH, "Your class is %s.\n", ent->client->resp.team_on->mos[ent->client->resp.mos]->name); ent->client->limbo_mode = false; ent->client->resp.changeteam = false; ent->client->respawn_time = level.time; ent->client->layout_type = SHOW_OBJECTIVES_TEMP; ent->client->show_obj_temp_time = level.time; Cmd_Objectives(ent); ent->client->mg42_temperature = 0; } void M_MOS_Join(edict_t *ent, pmenu_t *p, int choice) { choice -= 6; PMenu_Close(ent); ent->client->resp.newmos = choice; if (ent->client->resp.AlreadySpawned && ent->client->resp.changeteam == false) { if (choice == ent->client->resp.mos) { // Already playing that class! safe_cprintf(ent, PRINT_HIGH, "You've already been assigned the %s class!\n", ent->client->resp.team_on->mos[choice]->name); } else { safe_cprintf(ent, PRINT_HIGH, "Requesting %s class assignment your next operation.\n", ent->client->resp.team_on->mos[choice]->name); } return; } if (ent->client->resp.changeteam) { ent->client->resp.mos = INFANTRY; //faf respawn(ent); } // } else // EndObserverMode(ent);//faf: handle this in begin client frame // else if (level.framenum > ((int)(level_wait->value * 10) + (ent->client->spawn_delay * 10)) ) // EndObserverMode(ent); } /* void SMOS_Join(edict_t *ent,int choice) { //pbowens: just in case safe_cprintf(ent, PRINT_HIGH, "Secondary MOS/CLASS has been disabled!\n"); return; if(choice!=0) choice--; ent->client->resp.smos=choice; ent->client->usr_menu_sel=NULL; EndObserverMode(ent); } */ // There are many ways to do this.. but this way was easier on the eyes void client_menu(edict_t *ent, int entry, char *text, int align, void *arg, void (*SelectFunc)(edict_t *ent, struct pmenu_s *entry, int choice)) { ent->client->menu_cur[entry].text = text; ent->client->menu_cur[entry].align = align; ent->client->menu_cur[entry].arg = arg; ent->client->menu_cur[entry].SelectFunc = SelectFunc; } void M_ChooseMOS(edict_t *ent) { int i,j; char* theText = NULL; int taken; int maxSlots; // int index; edict_t *cl_ent; //pmenu = (ent->client->resp.team_on->index) ? menu_classes_grm : menu_classes_usa; //memcpy(ent->client->menu_cur, menu_classes, sizeof(pmenu_t)); PMenu_Close(ent); client_menu( ent, 2, "*D-DAY: NORMANDY " /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu( ent, 3, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu( ent, 4, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu( ent, 5, "Choose a Class", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu( ent, 9, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu( ent, 17, NULL, PMENU_ALIGN_RIGHT, NULL, NULL ); client_menu( ent, 18, "Main Menu", PMENU_ALIGN_RIGHT, NULL, M_Main_Menu ); if (ent->client->limbo_mode && !ent->client->resp.AlreadySpawned && (!ent->client->resp.team_on || !ent->client->resp.team_on->teamname) ) return; if (ent->flyingnun) return; for(i=1; i < MAX_MOS;i++) { //faf: hopefully fixes class bugs taken = 0; maxSlots = 0; for (j=0 ; j < game.maxclients ; j++) { cl_ent = g_edicts + 1 + j; if (cl_ent->ai) continue; //don't count bots against class limits if (!cl_ent->inuse) continue; if (!cl_ent->client || !cl_ent->client->resp.team_on || !cl_ent->client->resp.team_on->mos || cl_ent->client->resp.team_on->index != ent->client->resp.team_on->index) continue; // if (cl_ent == ent && ent->client->resp.mos == INFANTRY) if (cl_ent == ent && (!ent->client->resp.AlreadySpawned || ent->client->resp.changeteam)) continue; if (ent->client->resp.team_on->mos[i]->mos == cl_ent->client->resp.mos) taken++; } // Now set the available for this class switch (ent->client->resp.team_on->mos[i]->mos) //crash { case INFANTRY: maxSlots = MAX_INFANTRY; ent->client->resp.team_on->mos[i]->available = MAX_INFANTRY - taken; break; case OFFICER: maxSlots = MAX_OFFICERS; ent->client->resp.team_on->mos[i]->available = MAX_OFFICERS - taken; break; case L_GUNNER: maxSlots = MAX_L_GUNNER; ent->client->resp.team_on->mos[i]->available = MAX_L_GUNNER - taken; break; case H_GUNNER: maxSlots = MAX_H_GUNNER; ent->client->resp.team_on->mos[i]->available = MAX_H_GUNNER - taken; break; case SNIPER: maxSlots = MAX_SNIPER; ent->client->resp.team_on->mos[i]->available = MAX_SNIPER - taken; break; case SPECIAL: maxSlots = MAX_SPECIAL; ent->client->resp.team_on->mos[i]->available = MAX_SPECIAL - taken; break; case ENGINEER: maxSlots = MAX_ENGINEER; ent->client->resp.team_on->mos[i]->available = MAX_ENGINEER - taken; break; case MEDIC: maxSlots = MAX_MEDIC; ent->client->resp.team_on->mos[i]->available = MAX_MEDIC - taken; break; case FLAMER: maxSlots = MAX_FLAMER; ent->client->resp.team_on->mos[i]->available = MAX_FLAMER - taken; break; default: maxSlots = 0; ent->client->resp.team_on->mos[i]->available = 0; break; } if (mapclasslimits[ent->client->resp.team_on->index][i].limit) { maxSlots = mapclasslimits[ent->client->resp.team_on->index][i].limit; ent->client->resp.team_on->mos[i]->available = maxSlots - taken; } if (maxSlots < 0) maxSlots = 0; // Setup text variable theText = gi.TagMalloc(sizeof("123456789012 [00/00]"), TAG_GAME); if (maxSlots == 0) { strcpy (theText, " "); } else strcpy(theText, va("%12s [%i/%i]", ent->client->resp.team_on->mos[i]->name, taken, maxSlots)); ent->client->menu_cur[i+6].text = (class_limits->value)?(char *)theText:ent->client->resp.team_on->mos[i]->name; ent->client->menu_cur[i+6].align = PMENU_ALIGN_LEFT; ent->client->menu_cur[i+6].arg = NULL; ent->client->menu_cur[i+6].SelectFunc = M_MOS_Join; } // You can't go back and change stuff before you've spawned if (ent->client->resp.AlreadySpawned || !ent->client->resp.changeteam) client_menu(ent, 18, "Main Menu", PMENU_ALIGN_RIGHT, NULL, M_Main_Menu ); client_menu(ent, 21, "*Use [ and ] to select", PMENU_ALIGN_CENTER, NULL, NULL ); PMenu_Open(ent, ent->client->menu_cur, 7, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); //gi.TagFree(theText); } void M_Team_Join(edict_t *ent, pmenu_t *p, int choice) { // qboolean foundspot=false; int i,j,k,l,m; if (ent->client->menu) PMenu_Close(ent); choice -= 11;//7; if (choice == -2) { // auto team i = j = k = 0; /*faf for (k = 0; k <= MAX_TEAM_MATES; k++) { if (team_list[0]->units[k]) i++; if (team_list[1]->units[k]) j++; }*/ //faf i = PlayerCountForTeam(0, true); j = PlayerCountForTeam(1, true); l = PlayerCountForTeam (0, false); m = PlayerCountForTeam (1, false); //faf: if theyre already on a team subtract them from the total if (ent->client->resp.team_on && ent->client->resp.team_on->index == 0) i--; if (ent->client->resp.team_on && ent->client->resp.team_on->index == 1) j--; if (i > j) choice = 1; else if (i < j) choice = 0; //else if there are bots, go to the team with fewer humans else if (l > m) choice = 1; else if (m > l) choice = 0; //otherwise go to losing team else if (team_list[0]->kills > team_list[1]->kills)//faf choice = 1; else if (team_list[1]->kills > team_list[0]->kills)//faf choice = 0; else { if (ent->client->resp.team_on) { PMenu_Close(ent); return; } choice = (int)(random() * 2); } } // if (ent->client->resp.AlreadySpawned) // { if (ent->client->resp.team_on && ent->client->resp.team_on->index == team_list[choice]->index) { safe_cprintf(ent, PRINT_HIGH, "Already on team %s!\n", team_list[choice]->teamname); PMenu_Close(ent); return; } // } /* for(i=0;i<MAX_TEAM_MATES;i++) { if (!team_list[choice]) continue; if (!team_list[choice]->units[i]) { if (ent->client->resp.team_on) { //faf: "total" not used now team_list[ent->client->resp.team_on->index]->total--; team_list[ent->client->resp.team_on->index]->units[ent->client->resp.unit_index] = NULL; ent->client->resp.unit_index = i; } ent->client->resp.team_on=team_list[choice]; //faf: not used team_list[choice]->total++; team_list[choice]->units[i]=ent; foundspot=true; ent->client->resp.mos = NONE; // reset MOS break; } }*/ if (ent->client->resp.AlreadySpawned) // used choose_team cmd { if (ent->health ==100) T_Damage(ent, world, world, vec3_origin, ent->s.origin, vec3_origin, ent->health + 999, 0, DAMAGE_NO_PROTECTION, MOD_CHANGETEAM); else T_Damage(ent, world, world, vec3_origin, ent->s.origin, vec3_origin, ent->health + 999, 0, DAMAGE_NO_PROTECTION, MOD_CHANGETEAM_WOUNDED); } if (ent->client->resp.team_on) { ent->client->resp.team_on=team_list[choice]; safe_bprintf(PRINT_HIGH, "%s has switched to team %s.\n", ent->client->pers.netname, ent->client->resp.team_on->teamname); } else { ent->client->resp.team_on=team_list[choice]; safe_bprintf(PRINT_HIGH, "%s has joined team %s.\n", ent->client->pers.netname, ent->client->resp.team_on->teamname); ent->client->pers.afk_check_time = level.framenum; } ent->client->resp.mos = NONE; // reset MOS ent->client->resp.mos = INFANTRY; ent->client->resp.changeteam = true; ent->client->forcespawn = level.time + .5;//faf: fixes standing corpse bug // stuffcmd(ent, va("play %s/shout/yes1.wav", team_list[choice]->teamid)); M_ChooseMOS(ent); //EndObserverMode(ent); // *RSH Copied this from SMOS_Join code to try and start the game. return; // gi.dprintf(DEVELOPER_MSG_GAME, "warning: %s got to end of M_Team_Join().\n", ent->client->pers.netname); } void ChooseTeam(edict_t *ent) { int i;//,j; char* theText = NULL; int max_clients; PMenu_Close(ent); if (ent->flyingnun) { safe_cprintf (ent, PRINT_HIGH, "You need to leave observer mode first. Type \"observer\".\n"); return; } // if (ent->client->resp.changeteam == true) { // safe_centerprintf(ent, "You have already changed teams once!\nYou must wait for your next assignment\n"); // return; // } // rezmoth - must wait until end of lobby time //faf: not //faf if (level.framenum < ((int)level_wait->value * 10)) //faf return; // Eliminates ghost-bug if ((ent->client->limbo_mode || ent->deadflag) && ent->client->resp.team_on) { safe_centerprintf(ent, "You must wait for your next assignment\nto change teams!"); return; } client_menu(ent, 4, "*D-DAY: NORMANDY " /*DEVVERSION*/,PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 5, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 2, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 7, "*Choose a Team", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 4, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); if (!force_auto_select->value)//faf { for(i=0;i<MAX_TEAMS;i++) { if (!team_list[i]) continue; //faf: password off teams if (i == 0) { if (Q_stricmp(allied_password->string, "") != 0) { if (Q_stricmp(allied_password->string, Info_ValueForKey (ent->client->pers.userinfo, "password")) != 0) { if (Q_stricmp(allied_password->string, "none") != 0) continue; } } } if (i == 1) { if (Q_stricmp(axis_password->string, "") != 0) { if (Q_stricmp(axis_password->string, Info_ValueForKey (ent->client->pers.userinfo, "password")) != 0) { if (Q_stricmp(axis_password->string, "none") != 0) continue; } } } // for (j=0; team_list[i]->units[j]; j++); max_clients = maxclients->value; // Make the text look good theText = gi.TagMalloc(sizeof("123456789012 [00/00]"), TAG_GAME); strcat(theText, va("%12s [%i/%i]", team_list[i]->teamname, PlayerCountForTeam(i, true), max_clients));//faf: removed "team_list[i]->total," // Put it on the menu client_menu(ent, (i + 11), theText, PMENU_ALIGN_LEFT, NULL, M_Team_Join ); } } // client_menu(ent, 7, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); if (!ent->client->resp.team_on) { if (((Q_stricmp(allied_password->string, "") == 0) || (Q_stricmp(allied_password->string, "none") == 0)) && ((Q_stricmp(axis_password->string, "") == 0) || (Q_stricmp(axis_password->string, "none") == 0))) client_menu(ent, 9, "Auto Select", PMENU_ALIGN_CENTER, NULL, M_Team_Join ); } // client_menu(ent, 9, NULL, PMENU_ALIGN_RIGHT, NULL, NULL ); client_menu(ent, 14, "Main Menu", PMENU_ALIGN_RIGHT, NULL, M_Main_Menu ); // client_menu(ent, 11, NULL, PMENU_ALIGN_RIGHT, NULL, NULL ); client_menu(ent, 17, "*Use [ and ] to select", PMENU_ALIGN_CENTER, NULL, NULL ); PMenu_Open(ent, ent->client->menu_cur , 5, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); //gi.TagFree(theText); } void M_Observe_Choose (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); Cmd_FlyingNunMode_f(ent); } void M_Binds_Choose (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); Cmd_DDHelp_f(ent); stuffcmd(ent, "toggleconsole;"); } void M_Name_Choose (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); stuffcmd(ent, "menu_playerconfig;"); } void MainMenu(edict_t *ent) { PMenu_Close(ent); client_menu(ent, 4, "*D-DAY: NORMANDY " /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 5, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 2, NULL, PMENU_ALIGN_CENTER, NULL, NULL ), client_menu(ent, 7, "Main Menu", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 4, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); if (!ent->flyingnun) { client_menu(ent, 9, "Join The Game ", PMENU_ALIGN_CENTER, NULL, M_Team_Choose ); if (ent->client && ent->client->resp.team_on) { client_menu(ent, 9, "Choose a Team ", PMENU_ALIGN_CENTER, NULL, M_Team_Choose ); client_menu(ent, 10, "Choose a Class", PMENU_ALIGN_CENTER, NULL, M_Class_Choose ); } else client_menu(ent, 9, "Join The Game ", PMENU_ALIGN_CENTER, NULL, M_Team_Choose ); } if (!ent->flyingnun) client_menu(ent, 11, "Observe ", PMENU_ALIGN_CENTER, NULL, M_Observe_Choose ); else client_menu(ent, 11, "Stop Observing", PMENU_ALIGN_CENTER, NULL, M_Observe_Choose ); client_menu(ent, 12, "Change Name ", PMENU_ALIGN_CENTER, NULL, M_Name_Choose ); client_menu(ent, 13, "Help ", PMENU_ALIGN_CENTER, NULL, M_Binds_Choose ); client_menu(ent, 14, "Credits ", PMENU_ALIGN_CENTER, NULL, M_View_Credits ); // client_menu(ent, 7, NULL, PMENU_ALIGN_RIGHT, NULL, NULL ); client_menu(ent, 17, "*Use [ and ] to select", PMENU_ALIGN_CENTER, NULL, NULL ); PMenu_Open(ent, ent->client->menu_cur, 9, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); } void M_Main_Menu (edict_t *ent, pmenu_t *p, int choice) { MainMenu(ent); } void M_Team_Choose (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); ChooseTeam(ent); } void M_Class_Choose (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); M_ChooseMOS(ent); } void M_View_Credits (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); client_menu(ent, 0, "*D-DAY: NORMANDY " /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 1, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 2, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 3, "*Development Credits", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 4, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 5, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 5, "D-Day: Normandy", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 6, "Was Created By", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 7, "*Vipersoft", PMENU_ALIGN_CENTER, NULL, M_View_Credits_Vipersoft); // client_menu(ent, 8, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 9, "Further", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 10, "Unofficial", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 11, "Development By...", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 12, "*SHAEF", PMENU_ALIGN_CENTER, NULL, M_View_Credits_Shaef); client_menu(ent, 14, "*British/Russian Team", PMENU_ALIGN_CENTER, NULL, M_View_Credits_GBR); client_menu(ent, 16, "*Japan/USMC Team", PMENU_ALIGN_CENTER, NULL, M_View_Credits_JPN); client_menu(ent, 18, "*Polish/Italian Team", PMENU_ALIGN_CENTER, NULL, M_View_Credits_ITA); client_menu(ent, 20, "And many others!", PMENU_ALIGN_CENTER, NULL, NULL); client_menu(ent, 22, "Visit DdayDev.com", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 24, "Main Menu", PMENU_ALIGN_RIGHT, NULL, M_Main_Menu ); client_menu(ent, 25, "*Use [ and ] to select", PMENU_ALIGN_CENTER, NULL, NULL ); PMenu_Open(ent, ent->client->menu_cur, 7, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); } void credit_sound (edict_t *ent, pmenu_t *p, int choice) { switch (choice) { case 6: stuffcmd(ent, "play usa/shout/follow2.wav"); break; case 9: stuffcmd(ent, "play inland/buzz2.wav"); break; case 14: stuffcmd(ent, "play jpn/katana/draw.wav"); break; case 17: stuffcmd(ent, "play usa/shout/smoke1.wav"); break; } PMenu_Close(ent); M_View_Credits_Vipersoft (ent, p, choice); } void M_View_Credits_Vipersoft (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); client_menu(ent, 0, "*D-DAY: NORMANDY" /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 1, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 2, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 3, "*Development Credits", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 4, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 5, "Project Leader", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 6, "*Jason 'Abaris' Mohr", PMENU_ALIGN_CENTER, NULL, credit_sound ); // client_menu(ent, 7, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); client_menu(ent, 8, "Programming", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 9, "*Phil Bowens", PMENU_ALIGN_CENTER, NULL, credit_sound ); client_menu(ent, 10, "*Species", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 11, "*Adam 'RezMoth' Sherburne", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 12, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); client_menu(ent, 13, "Level Design", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 14, "*Peter 'Castrator' Lipman", PMENU_ALIGN_CENTER, NULL, credit_sound ); // client_menu(ent, 15, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); client_menu(ent, 16, "Visual Artist", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 17, "*Darwin Allen", PMENU_ALIGN_CENTER, NULL, credit_sound ); // client_menu(ent, 18, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); // client_menu(ent, XX, "Sound Engineer", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, XX, "*Oliver 'JumperDude' Snavely", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 19, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); client_menu(ent, 20, "Webmistress", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 21, "*Wheaty", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 22, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); client_menu(ent, 25, "Back", PMENU_ALIGN_RIGHT, NULL, M_View_Credits ); if (choice == 7) choice = 25; PMenu_Open(ent, ent->client->menu_cur, choice, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); } void M_View_Credits_Shaef (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); client_menu(ent, 0, "*D-DAY: NORMANDY " /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 1, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 2, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 3, "*Supreme Headquarters,", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 4, "*Allied Expeditionary", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 5, "*Forces", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 6, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 7, "(Tons of bug fixes and", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 8, "gameplay enhancements)", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 10, "Programming", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 11, "*Fafner", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 12, "*Bill Stokes", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 14, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); client_menu(ent, 13, "Modelling", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 14, "*Parts", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 17, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); // client_menu(ent, 18, NULL, PMENU_ALIGN_LEFT, NULL, NULL ); client_menu(ent, 25, "Back", PMENU_ALIGN_RIGHT, NULL, M_View_Credits ); PMenu_Open(ent, ent->client->menu_cur, -1, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); } void M_View_Credits_GBR (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); client_menu(ent, 0, "*D-DAY: NORMANDY " /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 1, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 2, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 3, "British and Russian", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 4, "Add-ons Dev Team", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 6, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 6, "*Mjr Parts", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 7, "GBR Models/Skins", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 9, "*Bill Stokes", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 10, "Programming", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 12, "*Gen Pepper", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 13, "GBR Shouts", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 15, "*Karr", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 16, "RUS Shouts", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 18, "*Afrow UK", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 19, "Maps", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 21, "*Fafner", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 22, "Code/RUS weaps", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 25, "Back", PMENU_ALIGN_RIGHT, NULL, M_View_Credits ); PMenu_Open(ent, ent->client->menu_cur, -1, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); } void M_View_Credits_JPN (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); client_menu(ent, 0, "*D-DAY: NORMANDY " /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 1, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 2, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 3, "Japan and USMC", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 4, "Add-on Dev Team", PMENU_ALIGN_CENTER, NULL, NULL ); // client_menu(ent, 6, NULL, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 6, "*Julhelm", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 7, "Weapon Models/Skins", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 9, "*EON_Magicman", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 10, "Player Skins", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 12, "*Mjr Parts", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 13, "Player Models", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 15, "*Karr", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 16, "Shouts", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 18, "*Fafner & Van Wilder", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 19, "Code", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 25, "Back", PMENU_ALIGN_RIGHT, NULL, M_View_Credits ); PMenu_Open(ent, ent->client->menu_cur, -1, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); } void M_View_Credits_ITA (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); client_menu(ent, 0, "*D-DAY: NORMANDY " /*DEVVERSION*/, PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 1, "*by Vipersoft", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 3, "Polish and Italian", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 4, "Add-ons Dev Team", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 6, "*Wolf", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 7, "Models and POL maps", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 9, "*Fernan", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 10, "Models", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 12, "*Rab,d", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 13, "ITA Skins", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 15, "*Gypsyllama", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 16, "*Tanatovago", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 17, "*Mr. YOur no fun", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 18, "Maps", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 20, "*Mieker", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 21, "POL Shouts", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 23, "*Fafner", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 24, "Code", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 25, "Back", PMENU_ALIGN_RIGHT, NULL, M_View_Credits ); PMenu_Open(ent, ent->client->menu_cur, -1, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); } void VoteMap (edict_t *ent, pmenu_t *p, int choice) { PMenu_Close(ent); choice = (choice - 7)/2; //safe_bprintf (PRINT_HIGH, "%s voted for %s.\n", ent->client->pers.netname, votemaps[choice]); safe_bprintf (PRINT_HIGH, "1 vote for %s.\n", votemaps[choice]); mapvotes[choice]++; ent->client->voted = true; gi.WriteByte (svc_layout); gi.WriteString (""); gi.unicast (ent, true); level.last_vote_time = level.time; } void MapVote(edict_t *ent) { //int randstart, int i; char filename[100]; FILE *f; //qboolean botmap = false; char* theText = NULL; char *add; PMenu_Close(ent); client_menu(ent, 4, "*VOTE FOR THE NEXT MAP! " , PMENU_ALIGN_CENTER, NULL, NULL ); for (i=0; i <4; i++) { //check for bot support //gi.dprintf(DEVELOPER_MSG_GAME, "x%s\n",mapstring); if (bots->value) { sprintf(filename, "dday/navigation/%s.cmp", votemaps[i]); f = fopen (filename, "rb"); if (f) { fclose (f); add = "*"; // botmap = true; } else add = " "; } else add = ""; theText = gi.TagMalloc(sizeof("1234567890123456789012345"), TAG_GAME); strcat(theText, va(" %s %s",add,votemaps[i])); client_menu(ent, 7+(i*2), theText, PMENU_ALIGN_LEFT, NULL, VoteMap ); } if (bots->value) { client_menu(ent, 18, "** = Has bot support", PMENU_ALIGN_CENTER, NULL, NULL ); client_menu(ent, 21, "Use [ and ] to select", PMENU_ALIGN_CENTER, NULL, NULL ); } else client_menu(ent, 18, "Use [ and ] to select", PMENU_ALIGN_CENTER, NULL, NULL ); PMenu_Open(ent, ent->client->menu_cur, 7, sizeof(ent->client->menu_cur) / sizeof(pmenu_t)); }
412
0.771124
1
0.771124
game-dev
MEDIA
0.938993
game-dev
0.991244
1
0.991244
dhewm/dhewm3
8,781
neo/TypeInfo/main.cpp
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 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 3 of the License, or (at your option) any later version. Doom 3 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "sys/platform.h" #include "sys/sys_local.h" #include "TypeInfo/TypeInfoGen.h" idSession * session = NULL; idDeclManager * declManager = NULL; idEventLoop * eventLoop = NULL; int idEventLoop::JournalLevel( void ) const { return 0; } /* ============================================================== idCommon ============================================================== */ #define STDIO_PRINT( pre, post ) \ va_list argptr; \ va_start( argptr, fmt ); \ printf( pre ); \ vprintf( fmt, argptr ); \ printf( post ); \ va_end( argptr ) class idCommonLocal : public idCommon { public: idCommonLocal( void ) {} virtual void Init( int argc, const char **argv, const char *cmdline ) {} virtual void Shutdown( void ) {} virtual void Quit( void ) {} virtual bool IsInitialized( void ) const { return true; } virtual void Frame( void ) {} virtual void GUIFrame( bool execCmd, bool network ) {} virtual void Async( void ) {} virtual void StartupVariable( const char *match, bool once ) {} virtual void InitTool( const toolFlag_t tool, const idDict *dict ) {} virtual void ActivateTool( bool active ) {} virtual void WriteConfigToFile( const char *filename ) {} virtual void WriteFlaggedCVarsToFile( const char *filename, int flags, const char *setCmd ) {} virtual void BeginRedirect( char *buffer, int buffersize, void (*flush)( const char * ) ) {} virtual void EndRedirect( void ) {} virtual void SetRefreshOnPrint( bool set ) {} virtual void Printf( const char *fmt, ... ) { STDIO_PRINT( "", "" ); } virtual void VPrintf( const char *fmt, va_list arg ) { vprintf( fmt, arg ); } virtual void DPrintf( const char *fmt, ... ) { /*STDIO_PRINT( "", "" );*/ } virtual void Warning( const char *fmt, ... ) { STDIO_PRINT( "WARNING: ", "\n" ); } virtual void DWarning( const char *fmt, ...) { /*STDIO_PRINT( "WARNING: ", "\n" );*/ } virtual void PrintWarnings( void ) {} virtual void ClearWarnings( const char *reason ) {} virtual void Error( const char *fmt, ... ) { STDIO_PRINT( "ERROR: ", "\n" ); exit(0); } virtual void FatalError( const char *fmt, ... ) { STDIO_PRINT( "FATAL ERROR: ", "\n" ); exit(0); } virtual const idLangDict *GetLanguageDict() { return NULL; } virtual const char * KeysFromBinding( const char *bind ) { return NULL; } virtual const char * BindingFromKey( const char *key ) { return NULL; } virtual int ButtonState( int key ) { return 0; } virtual int KeyState( int key ) { return 0; } }; idCVar com_developer( "developer", "0", CVAR_BOOL|CVAR_SYSTEM, "developer mode" ); idCommonLocal commonLocal; idCommon * common = &commonLocal; /* ============================================================== idSys ============================================================== */ void Sys_Mkdir( const char *path ) {} ID_TIME_T Sys_FileTimeStamp( FILE *fp ) { return 0; } #ifdef _WIN32 #include <io.h> #include <direct.h> const char *Sys_Cwd( void ) { static char cwd[1024]; _getcwd( cwd, sizeof( cwd ) - 1 ); cwd[sizeof( cwd ) - 1] = 0; return cwd; } bool Sys_GetPath(sysPath_t type, idStr &path) { switch(type) { case PATH_BASE: path = Sys_Cwd(); return true; case PATH_SAVE: path = cvarSystem->GetCVarString("fs_basepath"); return true; case PATH_EXE: return false; } return false; } int Sys_ListFiles( const char *directory, const char *extension, idStrList &list ) { idStr search; struct _finddata_t findinfo; int findhandle; int flag; if ( !extension) { extension = ""; } // passing a slash as extension will find directories if ( extension[0] == '/' && extension[1] == 0 ) { extension = ""; flag = 0; } else { flag = _A_SUBDIR; } sprintf( search, "%s\\*%s", directory, extension ); // search list.Clear(); findhandle = _findfirst( search, &findinfo ); if ( findhandle == -1 ) { return -1; } do { if ( flag ^ ( findinfo.attrib & _A_SUBDIR ) ) { list.Append( findinfo.name ); } } while ( _findnext( findhandle, &findinfo ) != -1 ); _findclose( findhandle ); return list.Num(); } #else bool Sys_GetPath(sysPath_t, idStr &) { return false; } int Sys_ListFiles( const char *directory, const char *extension, idStrList &list ) { return 0; } #endif void Sys_CreateThread( xthread_t function, void *parms, xthreadInfo &info, const char *name ) {} void Sys_DestroyThread( xthreadInfo& info ) {} void Sys_EnterCriticalSection( int index ) {} void Sys_LeaveCriticalSection( int index ) {} void Sys_WaitForEvent( int index ) {} void Sys_TriggerEvent( int index ) {} /* ============== idSysLocal stub ============== */ void idSysLocal::DebugPrintf( const char *fmt, ... ) {} void idSysLocal::DebugVPrintf( const char *fmt, va_list arg ) {} double idSysLocal::GetClockTicks( void ) { return 0.0; } double idSysLocal::ClockTicksPerSecond( void ) { return 1.0; } int idSysLocal::GetProcessorId( void ) { return 0; } void idSysLocal::FPU_SetFTZ( bool enable ) {} void idSysLocal::FPU_SetDAZ( bool enable ) {} bool idSysLocal::LockMemory( void *ptr, int bytes ) { return false; } bool idSysLocal::UnlockMemory( void *ptr, int bytes ) { return false; } uintptr_t idSysLocal::DLL_Load( const char *dllName ) { return 0; } void * idSysLocal::DLL_GetProcAddress( uintptr_t dllHandle, const char *procName ) { return NULL; } void idSysLocal::DLL_Unload( uintptr_t dllHandle ) { } void idSysLocal::DLL_GetFileName( const char *baseName, char *dllName, int maxLength ) { } sysEvent_t idSysLocal::GenerateMouseButtonEvent( int button, bool down ) { sysEvent_t ev; memset( &ev, 0, sizeof( ev ) ); return ev; } sysEvent_t idSysLocal::GenerateMouseMoveEvent( int deltax, int deltay ) { sysEvent_t ev; memset( &ev, 0, sizeof( ev ) ); return ev; } void idSysLocal::OpenURL( const char *url, bool quit ) { } void idSysLocal::StartProcess( const char *exeName, bool quit ) { } idSysLocal sysLocal; idSys * sys = &sysLocal; /* ============================================================== main ============================================================== */ int main( int argc, char** argv ) { idStr fileName, sourcePath; idTypeInfoGen *generator; idLib::common = common; idLib::cvarSystem = cvarSystem; idLib::fileSystem = fileSystem; idLib::sys = sys; idLib::Init(); cmdSystem->Init(); cvarSystem->Init(); idCVar::RegisterStaticVars(); fileSystem->Init(); generator = new idTypeInfoGen; if ( argc > 1 ) { sourcePath = idStr( "../"SOURCE_CODE_BASE_FOLDER"/" ) + argv[1]; } else { sourcePath = "../"SOURCE_CODE_BASE_FOLDER"/game"; } if ( argc > 2 ) { fileName = idStr( "../"SOURCE_CODE_BASE_FOLDER"/" ) + argv[2]; } else { fileName = "../"SOURCE_CODE_BASE_FOLDER"/game/gamesys/GameTypeInfo.h"; } if ( argc > 3 ) { for ( int i = 3; i < argc; i++ ) { generator->AddDefine( argv[i] ); } } else { generator->AddDefine( "__cplusplus" ); generator->AddDefine( "GAME_DLL" ); generator->AddDefine( "ID_TYPEINFO" ); } generator->CreateTypeInfo( sourcePath ); generator->WriteTypeInfo( fileName ); delete generator; fileName.Clear(); sourcePath.Clear(); fileSystem->Shutdown( false ); cvarSystem->Shutdown(); cmdSystem->Shutdown(); idLib::ShutDown(); return 0; }
412
0.94021
1
0.94021
game-dev
MEDIA
0.424784
game-dev
0.688108
1
0.688108
RedPandaProjects/STALKERonUE
11,388
gamedata_cs/scripts/heli_move.script
--[[------------------------------------------------------------------------------------------------ Helicopter movement --------------------------------------------------------------------------------------------------]] local state_move = 0 ---------------------------------------------------------------------------------------------------- class "heli_move" function heli_move:__init( obj, storage ) self.object = obj self.heliObject = obj:get_helicopter() self.a = storage self.heli_fly = heli_fly.get_heli_flyer(obj) self.heli_fire = heli_fire.get_heli_firer(obj) self.heli_look = heli_look.get_heli_looker(obj) end function heli_move:reset_scheme( loading ) printf("heli_move: reset_scheme: %s", self.object:name()) self.a.signals = {} self.heliObject:TurnEngineSound( self.a.engine_sound ) ---------------------------------- - ------------------------------------------------ if not level.patrol_path_exists(self.a.path_move) then abort("Patrol path %s doesnt exist", self.a.path_move) end self.patrol_move = patrol(self.a.path_move) self.patrol_move_info = utils.path_parse_waypoints(self.a.path_move) if self.a.path_look then if self.a.path_look == "actor" then self.heli_fly:set_look_point(db.actor:position()) self:update_look_state() else self.patrol_look = patrol(self.a.path_look) self.heli_fly:set_look_point(self.patrol_look:point( 0 )) self:update_look_state() if not self.patrol_look then abort("object '%s': unable to find path_look '%s' on the map", self.object:name(), self.a.path_look) end end else self.patrol_look = nil end self.max_velocity = self.a.max_velocity if loading then self.state = xr_logic.pstor_retrieve( self.object, "st" ) self.last_index = xr_logic.pstor_retrieve( self.object, "li" ) or nil self.next_index = xr_logic.pstor_retrieve( self.object, "ni" ) or nil self.was_callback = xr_logic.pstor_retrieve( self.object, "wc" ) else self.last_index = nil self.next_index = nil self.heli_fly.max_velocity = self.max_velocity self.heli_fly.heliLAccFW = self.max_velocity / 15 self.heli_fly.heliLAccBW = 2 * self.heli_fly.heliLAccFW / 3 self.heliObject:SetLinearAcc(self.heli_fly.heliLAccFW, self.heli_fly.heliLAccBW); self.heliObject:SetMaxVelocity( self.max_velocity ) self.state = nil self.stop_point = nil self.by_stop_fire_fly = false self.was_callback = false self._flag_to_wp_callback = false self.heli_fire.enemy_ = self.a.enemy_ self.heli_fire.enemy = nil self.heli_fire.flag_by_enemy = true if self.a.fire_point then self.heli_fire.fire_point = patrol(self.a.fire_point):point( 0 ) end if self.a.max_mgun_dist then self.heliObject.m_max_mgun_dist = self.a.max_mgun_dist end if self.a.max_rocket_dist then self.heliObject.m_max_rocket_dist = self.a.max_rocket_dist end if self.a.min_mgun_dist then self.heliObject.m_min_mgun_dist = self.a.min_mgun_dist end if self.a.min_rocket_dist then self.heliObject.m_min_rocket_dist = self.a.min_rocket_dist end if self.a.use_mgun then self.heliObject.m_use_mgun_on_attack = true else self.heliObject.m_use_mgun_on_attack = false end if self.a.use_rocket then self.heliObject.m_use_rocket_on_attack = true else self.heliObject.m_use_rocket_on_attack = false end self.heli_fire.upd_vis = self.a.upd_vis self.heli_fire:update_enemy_state() self:update_movement_state() if self.a.show_health then self.heli_fire:cs_remove() self.heli_fire.show_health = true self.heli_fire:cs_heli() else self.heli_fire.show_health = false self.heli_fire:cs_remove() end self.heliObject:UseFireTrail(self.a.fire_trail) end end function heli_move:save() xr_logic.pstor_store( self.object, "st", self.state ) ---------------------------------- - ------------------------------------------------ xr_logic.pstor_store( self.object, "li", self.last_index or false ) xr_logic.pstor_store( self.object, "ni", self.next_index or false ) ---------------------------------- - ------------------------------------------------- xr_logic.pstor_store( self.object, "wc", self.was_callback ) end function heli_move:update( delta ) if xr_logic.try_switch_to_another_section(self.object, self.a, db.actor) then return end self.heli_fire:update_enemy_state() if self.was_callback then self:update_movement_state() self.was_callback = false end if self.a.path_look then if self.a.path_look == "actor" then self.heli_fly:set_look_point(db.actor:position()) if self.a.stop_fire then if self.heliObject:isVisible( db.actor ) then if not self.by_stop_fire_fly then self.stop_point = self.object:position() self.by_stop_fire_fly = true self.was_callback = true --'printf("Stop Fire!") end else --'printf("Fly to next point!") self.by_stop_fire_fly = false self.was_callback = true end end end self:update_look_state() end if not self.a.path_look and self.heli_look.look_state then self.heli_look:calc_look_point(self.heli_fly.dest_point, true) end end function heli_move:update_movement_state() --'printf("update_movement_state()") self.state = state_move if self.patrol_move then if not self.last_index then self.last_index = 0 self.next_index = 1 else self.next_index = self.last_index + 1 if self.next_index >= self.patrol_move:count() then self.next_index = 0 end end end if not self.by_stop_fire_fly then if self.patrol_move:count() > 2 then self._flag_to_wp_callback = self.heli_fly:fly_on_point_with_vector( self.patrol_move:point( self.last_index ), self.patrol_move:point( self.next_index ), self.max_velocity, self._flag_to_wp_callback, false) else if self.patrol_move:count() > 1 then self._flag_to_wp_callback = self.heli_fly:fly_on_point_with_vector( self.patrol_move:point( self.last_index ), self.patrol_move:point( self.next_index ), self.max_velocity, true, true) else self._flag_to_wp_callback = self.heli_fly:fly_on_point_with_vector( self.patrol_move:point( self.last_index ), self.patrol_move:point( self.last_index ), self.max_velocity, true, true) end end else self._flag_to_wp_callback = self.heli_fly:fly_on_point_with_vector( self.stop_point, self.stop_point, self.max_velocity, true, false) self._flag_to_wp_callback = true end end function heli_move:update_look_state() --' printf("update_look_state()") self.heli_fly:set_block_flook(true) self.heli_fly:look_at_position() end function heli_move:waypoint_callback( obj, action_type, index ) ---------------------------------- - ------------------------------------------------ if not self._flag_to_wp_callback then --'printf("heli_pos=[%d;%d;%d]",self.object:position().x,self.object:position().y,self.object:position().z) --'printf("dist_to_dest_point=%d",self.heliObject:GetDistanceToDestPosition()) if self.patrol_move then if index == self.last_index then return end if index ~= -1 then self.last_index = index else --' if self.patrol_move_info[self.last_index] ~= nil then local signal = self.patrol_move_info[self.last_index]["sig"] if signal ~= nil then self.a.signals[signal] = true end end if self.patrol_move:count()>1 then self.last_index = self.next_index end end end end ---------------------------------- - ------------------------------------------------- --' printf("Dist To Dest Point: %s", self.heliObject:GetDistanceToDestPosition()) --' printf("heli_move:waypoint_callback(): name=%s, index=%d", self.object:name(), index) self.was_callback = true end --------------------------------------------------------------------------------------------------------------------- function add_to_binder( npc, ini, scheme, section, storage ) printf( "DEBUG: add_to_binder: npc:name()='%s', scheme='%s', section='%s'", npc:name(), scheme, section ) local new_action = heli_move( npc, storage ) -- actions, reset_scheme : xr_logic.subscribe_action_for_events( npc, storage, new_action ) end function set_scheme( npc, ini, scheme, section ) local a = xr_logic.assign_storage_and_bind( npc, ini, scheme, section ) a.logic = xr_logic.cfg_get_switch_conditions( ini, section, npc ) a.path_move = utils.cfg_get_string( ini, section, "path_move", npc, true, "") a.path_look = utils.cfg_get_string( ini, section, "path_look", npc, false, "") a.max_velocity = utils.cfg_get_number( ini, section, "max_velocity", npc, true, max_velocity ) a.enemy_ = utils.cfg_get_string( ini, section, "enemy", npc, false, "") a.fire_point = utils.cfg_get_string( ini, section, "fire_point", npc, false, "") a.max_mgun_dist = utils.cfg_get_number( ini, section, "max_mgun_attack_dist", npc, false ) a.max_rocket_dist = utils.cfg_get_number( ini, section, "max_rocket_attack_dist", npc, false ) a.min_mgun_dist = utils.cfg_get_number( ini, section, "min_mgun_attack_dist", npc, false ) a.min_rocket_dist = utils.cfg_get_number( ini, section, "min_rocket_attack_dist", npc, false ) a.use_rocket = utils.cfg_get_bool( ini, section, "use_rocket", npc, false, true ) a.use_mgun = utils.cfg_get_bool( ini, section, "use_mgun", npc, false, true ) a.engine_sound = utils.cfg_get_bool( ini, section, "engine_sound", npc, false, true ) a.upd_vis = utils.cfg_get_number( ini, section, "upd_vis", npc, false, 10 ) a.stop_fire = utils.cfg_get_bool( ini, section, "stop_fire", npc, false, false ) a.show_health = utils.cfg_get_bool( ini, section, "show_health", npc, false, false ) a.fire_trail = utils.cfg_get_bool( ini, section, "fire_trail", npc, false, false ) local st = db.storage[npc:id()] st.invulnerable = utils.cfg_get_bool( ini, section, "invulnerable", npc, false, false ) st.immortal = utils.cfg_get_bool( ini, section, "immortal", npc, false, false ) st.mute = utils.cfg_get_bool( ini, section, "mute", npc, false, false ) end
412
0.958775
1
0.958775
game-dev
MEDIA
0.972728
game-dev
0.983431
1
0.983431
codetaylor/pyrotech-1.12
3,644
src/main/java/com/codetaylor/mc/pyrotech/modules/tech/bloomery/init/recipe/WitherForgeRecipesAdd.java
package com.codetaylor.mc.pyrotech.modules.tech.bloomery.init.recipe; import com.codetaylor.mc.athenaeum.util.RecipeHelper; import com.codetaylor.mc.pyrotech.modules.core.item.ItemMaterial; import com.codetaylor.mc.pyrotech.modules.tech.basic.recipe.AnvilRecipe; import com.codetaylor.mc.pyrotech.modules.tech.bloomery.ModuleTechBloomery; import com.codetaylor.mc.pyrotech.modules.tech.bloomery.ModuleTechBloomeryConfig; import com.codetaylor.mc.pyrotech.modules.tech.bloomery.recipe.BloomeryRecipe; import com.codetaylor.mc.pyrotech.modules.tech.bloomery.recipe.BloomeryRecipeBase; import com.codetaylor.mc.pyrotech.modules.tech.bloomery.recipe.WitherForgeRecipe; import com.codetaylor.mc.pyrotech.modules.tech.bloomery.recipe.WitherForgeRecipeBuilder; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.ResourceLocation; import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.IForgeRegistryModifiable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Function; public class WitherForgeRecipesAdd { private static final int DEFAULT_BURN_TIME_TICKS = 24 * 60 * 20; private static final float DEFAULT_FAILURE_CHANCE = 0.25f; public static final Function<BloomeryRecipe, WitherForgeRecipe> INHERIT_TRANSFORMER = recipe -> { // the registry name can be null here because it will be set by the inherit method WitherForgeRecipeBuilder builder = new WitherForgeRecipeBuilder(null, recipe.getOutput(), recipe.getInput()) .setBurnTimeTicks(recipe.getTimeTicks()) .setFailureChance(recipe.getFailureChance()) .setBloomYield(recipe.getBloomYieldMin(), recipe.getBloomYieldMax()) .setSlagItem(recipe.getSlagItemStack(), recipe.getSlagCount()) .setLangKey(recipe.getLangKey()); for (BloomeryRecipeBase.FailureItem item : recipe.getFailureItems()) { builder.addFailureItem(item.getItemStack(), item.getWeight()); } return builder.create(); }; public static void apply(IForgeRegistry<WitherForgeRecipe> registry) { // Obsidian Shards registry.register(new WitherForgeRecipeBuilder( new ResourceLocation(ModuleTechBloomery.MOD_ID, "bloom_from_obsidian"), ItemMaterial.EnumType.OBSIDIAN_SHARD.asStack(), Ingredient.fromStacks(new ItemStack(Blocks.OBSIDIAN)) ) .setBurnTimeTicks(DEFAULT_BURN_TIME_TICKS) .setFailureChance(DEFAULT_FAILURE_CHANCE) .setBloomYield(8, 12) .setSlagItem(new ItemStack(ModuleTechBloomery.Items.SLAG), 2) .setAnvilTiers(new AnvilRecipe.EnumTier[]{AnvilRecipe.EnumTier.IRONCLAD}) .setLangKey(Blocks.OBSIDIAN.getUnlocalizedName()) .create()); } public static void registerBloomAnvilRecipes( IForgeRegistry<WitherForgeRecipe> registryWitherForge, IForgeRegistry<AnvilRecipe> registryAnvil ) { Collection<WitherForgeRecipe> recipes = registryWitherForge.getValuesCollection(); List<WitherForgeRecipe> snapshot = new ArrayList<>(recipes); for (BloomeryRecipeBase<?> recipe : snapshot) { BloomeryRecipesAdd.registerBloomAnvilRecipe(registryAnvil, recipe); } } public static void registerInheritedRecipes( IForgeRegistryModifiable<BloomeryRecipe> bloomeryRegistry, IForgeRegistryModifiable<WitherForgeRecipe> witherForgeRegistry ) { if (ModuleTechBloomeryConfig.WITHER_FORGE.INHERIT_BLOOMERY_RECIPES) { RecipeHelper.inherit("bloomery", bloomeryRegistry, witherForgeRegistry, INHERIT_TRANSFORMER); } } }
412
0.911511
1
0.911511
game-dev
MEDIA
0.990889
game-dev
0.895168
1
0.895168
Secrets-of-Sosaria/World
1,688
Data/Scripts/Items/Magical/Gifts/Weapons/Knives/GiftButcherKnife.cs
using System; using Server.Network; using Server.Items; namespace Server.Items { [FlipableAttribute( 0x13F6, 0x13F7 )] public class GiftButcherKnife : BaseGiftKnife { public override WeaponAbility PrimaryAbility{ get{ return WeaponAbility.InfectiousStrike; } } public override WeaponAbility SecondaryAbility{ get{ return WeaponAbility.Disarm; } } public override WeaponAbility ThirdAbility{ get{ return WeaponAbility.ConsecratedStrike; } } public override WeaponAbility FourthAbility{ get{ return WeaponAbility.DoubleWhirlwindAttack; } } public override WeaponAbility FifthAbility{ get{ return WeaponAbility.MagicProtection2; } } public override int AosStrengthReq{ get{ return 5; } } public override int AosMinDamage{ get{ return 9; } } public override int AosMaxDamage{ get{ return 11; } } public override int AosSpeed{ get{ return 49; } } public override float MlSpeed{ get{ return 2.25f; } } public override int OldStrengthReq{ get{ return 5; } } public override int OldMinDamage{ get{ return 2; } } public override int OldMaxDamage{ get{ return 14; } } public override int OldSpeed{ get{ return 40; } } public override int InitMinHits{ get{ return 31; } } public override int InitMaxHits{ get{ return 40; } } [Constructable] public GiftButcherKnife() : base( 0x13F6 ) { Weight = 1.0; } public GiftButcherKnife( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
412
0.851323
1
0.851323
game-dev
MEDIA
0.932099
game-dev
0.728955
1
0.728955
mauge123/mechanical-blender
16,073
extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.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 "btRigidBody.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "LinearMath/btMinMax.h" #include "LinearMath/btTransformUtil.h" #include "LinearMath/btMotionState.h" #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" #include "LinearMath/btSerializer.h" //'temporarily' global variables btScalar gDeactivationTime = btScalar(2.); bool gDisableDeactivation = false; static int uniqueId = 0; btRigidBody::btRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo) { setupRigidBody(constructionInfo); } btRigidBody::btRigidBody(btScalar mass, btMotionState *motionState, btCollisionShape *collisionShape, const btVector3 &localInertia) { btRigidBodyConstructionInfo cinfo(mass,motionState,collisionShape,localInertia); setupRigidBody(cinfo); } void btRigidBody::setupRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo) { m_internalType=CO_RIGID_BODY; m_linearVelocity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); m_angularFactor.setValue(1,1,1); m_linearFactor.setValue(1,1,1); m_gravity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); m_gravity_acceleration.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)), setDamping(constructionInfo.m_linearDamping, constructionInfo.m_angularDamping); m_linearSleepingThreshold = constructionInfo.m_linearSleepingThreshold; m_angularSleepingThreshold = constructionInfo.m_angularSleepingThreshold; m_optionalMotionState = constructionInfo.m_motionState; m_contactSolverType = 0; m_frictionSolverType = 0; m_additionalDamping = constructionInfo.m_additionalDamping; m_additionalDampingFactor = constructionInfo.m_additionalDampingFactor; m_additionalLinearDampingThresholdSqr = constructionInfo.m_additionalLinearDampingThresholdSqr; m_additionalAngularDampingThresholdSqr = constructionInfo.m_additionalAngularDampingThresholdSqr; m_additionalAngularDampingFactor = constructionInfo.m_additionalAngularDampingFactor; if (m_optionalMotionState) { m_optionalMotionState->getWorldTransform(m_worldTransform); } else { m_worldTransform = constructionInfo.m_startWorldTransform; } m_interpolationWorldTransform = m_worldTransform; m_interpolationLinearVelocity.setValue(0,0,0); m_interpolationAngularVelocity.setValue(0,0,0); //moved to btCollisionObject m_friction = constructionInfo.m_friction; m_rollingFriction = constructionInfo.m_rollingFriction; m_restitution = constructionInfo.m_restitution; setCollisionShape( constructionInfo.m_collisionShape ); m_debugBodyId = uniqueId++; setMassProps(constructionInfo.m_mass, constructionInfo.m_localInertia); updateInertiaTensor(); m_rigidbodyFlags = BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY; m_deltaLinearVelocity.setZero(); m_deltaAngularVelocity.setZero(); m_invMass = m_inverseMass*m_linearFactor; m_pushVelocity.setZero(); m_turnVelocity.setZero(); } void btRigidBody::predictIntegratedTransform(btScalar timeStep,btTransform& predictedTransform) { btTransformUtil::integrateTransform(m_worldTransform,m_linearVelocity,m_angularVelocity,timeStep,predictedTransform); } void btRigidBody::saveKinematicState(btScalar timeStep) { //todo: clamp to some (user definable) safe minimum timestep, to limit maximum angular/linear velocities if (timeStep != btScalar(0.)) { //if we use motionstate to synchronize world transforms, get the new kinematic/animated world transform if (getMotionState()) getMotionState()->getWorldTransform(m_worldTransform); btVector3 linVel,angVel; btTransformUtil::calculateVelocity(m_interpolationWorldTransform,m_worldTransform,timeStep,m_linearVelocity,m_angularVelocity); m_interpolationLinearVelocity = m_linearVelocity; m_interpolationAngularVelocity = m_angularVelocity; m_interpolationWorldTransform = m_worldTransform; //printf("angular = %f %f %f\n",m_angularVelocity.getX(),m_angularVelocity.getY(),m_angularVelocity.getZ()); } } void btRigidBody::getAabb(btVector3& aabbMin,btVector3& aabbMax) const { getCollisionShape()->getAabb(m_worldTransform,aabbMin,aabbMax); } void btRigidBody::setGravity(const btVector3& acceleration) { if (m_inverseMass != btScalar(0.0)) { m_gravity = acceleration * (btScalar(1.0) / m_inverseMass); } m_gravity_acceleration = acceleration; } void btRigidBody::setDamping(btScalar lin_damping, btScalar ang_damping) { m_linearDamping = btClamped(lin_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); m_angularDamping = btClamped(ang_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); } ///applyDamping damps the velocity, using the given m_linearDamping and m_angularDamping void btRigidBody::applyDamping(btScalar timeStep) { //On new damping: see discussion/issue report here: http://code.google.com/p/bullet/issues/detail?id=74 //todo: do some performance comparisons (but other parts of the engine are probably bottleneck anyway //#define USE_OLD_DAMPING_METHOD 1 #ifdef USE_OLD_DAMPING_METHOD m_linearVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_linearDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); m_angularVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_angularDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); #else m_linearVelocity *= btPow(btScalar(1)-m_linearDamping, timeStep); m_angularVelocity *= btPow(btScalar(1)-m_angularDamping, timeStep); #endif if (m_additionalDamping) { //Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc. //Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete if ((m_angularVelocity.length2() < m_additionalAngularDampingThresholdSqr) && (m_linearVelocity.length2() < m_additionalLinearDampingThresholdSqr)) { m_angularVelocity *= m_additionalDampingFactor; m_linearVelocity *= m_additionalDampingFactor; } btScalar speed = m_linearVelocity.length(); if (speed < m_linearDamping) { btScalar dampVel = btScalar(0.005); if (speed > dampVel) { btVector3 dir = m_linearVelocity.normalized(); m_linearVelocity -= dir * dampVel; } else { m_linearVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } } btScalar angSpeed = m_angularVelocity.length(); if (angSpeed < m_angularDamping) { btScalar angDampVel = btScalar(0.005); if (angSpeed > angDampVel) { btVector3 dir = m_angularVelocity.normalized(); m_angularVelocity -= dir * angDampVel; } else { m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } } } } void btRigidBody::applyGravity() { if (isStaticOrKinematicObject()) return; applyCentralForce(m_gravity); } void btRigidBody::proceedToTransform(const btTransform& newTrans) { setCenterOfMassTransform( newTrans ); } void btRigidBody::setMassProps(btScalar mass, const btVector3& inertia) { if (mass == btScalar(0.)) { m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT; m_inverseMass = btScalar(0.); } else { m_collisionFlags &= (~btCollisionObject::CF_STATIC_OBJECT); m_inverseMass = btScalar(1.0) / mass; } //Fg = m * a m_gravity = mass * m_gravity_acceleration; m_invInertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x(): btScalar(0.0), inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y(): btScalar(0.0), inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z(): btScalar(0.0)); m_invMass = m_linearFactor*m_inverseMass; } void btRigidBody::updateInertiaTensor() { m_invInertiaTensorWorld = m_worldTransform.getBasis().scaled(m_invInertiaLocal) * m_worldTransform.getBasis().transpose(); } btVector3 btRigidBody::getLocalInertia() const { btVector3 inertiaLocal; const btVector3 inertia = m_invInertiaLocal; inertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x() : btScalar(0.0), inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y() : btScalar(0.0), inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z() : btScalar(0.0)); return inertiaLocal; } inline btVector3 evalEulerEqn(const btVector3& w1, const btVector3& w0, const btVector3& T, const btScalar dt, const btMatrix3x3 &I) { const btVector3 w2 = I*w1 + w1.cross(I*w1)*dt - (T*dt + I*w0); return w2; } inline btMatrix3x3 evalEulerEqnDeriv(const btVector3& w1, const btVector3& w0, const btScalar dt, const btMatrix3x3 &I) { btMatrix3x3 w1x, Iw1x; const btVector3 Iwi = (I*w1); w1.getSkewSymmetricMatrix(&w1x[0], &w1x[1], &w1x[2]); Iwi.getSkewSymmetricMatrix(&Iw1x[0], &Iw1x[1], &Iw1x[2]); const btMatrix3x3 dfw1 = I + (w1x*I - Iw1x)*dt; return dfw1; } btVector3 btRigidBody::computeGyroscopicForceExplicit(btScalar maxGyroscopicForce) const { btVector3 inertiaLocal = getLocalInertia(); btMatrix3x3 inertiaTensorWorld = getWorldTransform().getBasis().scaled(inertiaLocal) * getWorldTransform().getBasis().transpose(); btVector3 tmp = inertiaTensorWorld*getAngularVelocity(); btVector3 gf = getAngularVelocity().cross(tmp); btScalar l2 = gf.length2(); if (l2>maxGyroscopicForce*maxGyroscopicForce) { gf *= btScalar(1.)/btSqrt(l2)*maxGyroscopicForce; } return gf; } btVector3 btRigidBody::computeGyroscopicImpulseImplicit_Body(btScalar step) const { btVector3 idl = getLocalInertia(); btVector3 omega1 = getAngularVelocity(); btQuaternion q = getWorldTransform().getRotation(); // Convert to body coordinates btVector3 omegab = quatRotate(q.inverse(), omega1); btMatrix3x3 Ib; Ib.setValue(idl.x(),0,0, 0,idl.y(),0, 0,0,idl.z()); btVector3 ibo = Ib*omegab; // Residual vector btVector3 f = step * omegab.cross(ibo); btMatrix3x3 skew0; omegab.getSkewSymmetricMatrix(&skew0[0], &skew0[1], &skew0[2]); btVector3 om = Ib*omegab; btMatrix3x3 skew1; om.getSkewSymmetricMatrix(&skew1[0],&skew1[1],&skew1[2]); // Jacobian btMatrix3x3 J = Ib + (skew0*Ib - skew1)*step; // btMatrix3x3 Jinv = J.inverse(); // btVector3 omega_div = Jinv*f; btVector3 omega_div = J.solve33(f); // Single Newton-Raphson update omegab = omegab - omega_div;//Solve33(J, f); // Back to world coordinates btVector3 omega2 = quatRotate(q,omegab); btVector3 gf = omega2-omega1; return gf; } btVector3 btRigidBody::computeGyroscopicImpulseImplicit_World(btScalar step) const { // use full newton-euler equations. common practice to drop the wxIw term. want it for better tumbling behavior. // calculate using implicit euler step so it's stable. const btVector3 inertiaLocal = getLocalInertia(); const btVector3 w0 = getAngularVelocity(); btMatrix3x3 I; I = m_worldTransform.getBasis().scaled(inertiaLocal) * m_worldTransform.getBasis().transpose(); // use newtons method to find implicit solution for new angular velocity (w') // f(w') = -(T*step + Iw) + Iw' + w' + w'xIw'*step = 0 // df/dw' = I + 1xIw'*step + w'xI*step btVector3 w1 = w0; // one step of newton's method { const btVector3 fw = evalEulerEqn(w1, w0, btVector3(0, 0, 0), step, I); const btMatrix3x3 dfw = evalEulerEqnDeriv(w1, w0, step, I); btVector3 dw; dw = dfw.solve33(fw); //const btMatrix3x3 dfw_inv = dfw.inverse(); //dw = dfw_inv*fw; w1 -= dw; } btVector3 gf = (w1 - w0); return gf; } void btRigidBody::integrateVelocities(btScalar step) { if (isStaticOrKinematicObject()) return; m_linearVelocity += m_totalForce * (m_inverseMass * step); m_angularVelocity += m_invInertiaTensorWorld * m_totalTorque * step; #define MAX_ANGVEL SIMD_HALF_PI /// clamp angular velocity. collision calculations will fail on higher angular velocities btScalar angvel = m_angularVelocity.length(); if (angvel*step > MAX_ANGVEL) { m_angularVelocity *= (MAX_ANGVEL/step) /angvel; } } btQuaternion btRigidBody::getOrientation() const { btQuaternion orn; m_worldTransform.getBasis().getRotation(orn); return orn; } void btRigidBody::setCenterOfMassTransform(const btTransform& xform) { if (isKinematicObject()) { m_interpolationWorldTransform = m_worldTransform; } else { m_interpolationWorldTransform = xform; } m_interpolationLinearVelocity = getLinearVelocity(); m_interpolationAngularVelocity = getAngularVelocity(); m_worldTransform = xform; updateInertiaTensor(); } bool btRigidBody::checkCollideWithOverride(const btCollisionObject* co) const { const btRigidBody* otherRb = btRigidBody::upcast(co); if (!otherRb) return true; for (int i = 0; i < m_constraintRefs.size(); ++i) { const btTypedConstraint* c = m_constraintRefs[i]; if (c->isEnabled()) if (&c->getRigidBodyA() == otherRb || &c->getRigidBodyB() == otherRb) return false; } return true; } void btRigidBody::addConstraintRef(btTypedConstraint* c) { int index = m_constraintRefs.findLinearSearch(c); if (index == m_constraintRefs.size()) m_constraintRefs.push_back(c); m_checkCollideWith = true; } void btRigidBody::removeConstraintRef(btTypedConstraint* c) { m_constraintRefs.remove(c); m_checkCollideWith = m_constraintRefs.size() > 0; } int btRigidBody::calculateSerializeBufferSize() const { int sz = sizeof(btRigidBodyData); return sz; } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* btRigidBody::serialize(void* dataBuffer, class btSerializer* serializer) const { btRigidBodyData* rbd = (btRigidBodyData*) dataBuffer; btCollisionObject::serialize(&rbd->m_collisionObjectData, serializer); m_invInertiaTensorWorld.serialize(rbd->m_invInertiaTensorWorld); m_linearVelocity.serialize(rbd->m_linearVelocity); m_angularVelocity.serialize(rbd->m_angularVelocity); rbd->m_inverseMass = m_inverseMass; m_angularFactor.serialize(rbd->m_angularFactor); m_linearFactor.serialize(rbd->m_linearFactor); m_gravity.serialize(rbd->m_gravity); m_gravity_acceleration.serialize(rbd->m_gravity_acceleration); m_invInertiaLocal.serialize(rbd->m_invInertiaLocal); m_totalForce.serialize(rbd->m_totalForce); m_totalTorque.serialize(rbd->m_totalTorque); rbd->m_linearDamping = m_linearDamping; rbd->m_angularDamping = m_angularDamping; rbd->m_additionalDamping = m_additionalDamping; rbd->m_additionalDampingFactor = m_additionalDampingFactor; rbd->m_additionalLinearDampingThresholdSqr = m_additionalLinearDampingThresholdSqr; rbd->m_additionalAngularDampingThresholdSqr = m_additionalAngularDampingThresholdSqr; rbd->m_additionalAngularDampingFactor = m_additionalAngularDampingFactor; rbd->m_linearSleepingThreshold=m_linearSleepingThreshold; rbd->m_angularSleepingThreshold = m_angularSleepingThreshold; return btRigidBodyDataName; } void btRigidBody::serializeSingleObject(class btSerializer* serializer) const { btChunk* chunk = serializer->allocate(calculateSerializeBufferSize(),1); const char* structType = serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_RIGIDBODY_CODE,(void*)this); }
412
0.961807
1
0.961807
game-dev
MEDIA
0.99101
game-dev
0.990292
1
0.990292
JohannesMoersch/Functional
2,652
Functional.Primitives.Extensions/Helpers.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Functional { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false)] internal class AllowAllocationsAttribute : Attribute { } internal static class DelegateCache { public static readonly Func<bool> True = () => true; public static readonly Func<bool> False = () => false; public static readonly Action Void = () => { }; public static readonly Func<Task> Task = () => System.Threading.Tasks.Task.CompletedTask; } internal static class DelegateCache<T> { public static readonly Func<T, bool> True = _ => true; public static readonly Func<T, bool> False = _ => false; #pragma warning disable CS8603 // Possible null reference return. public static readonly Func<T> Default = () => default; #pragma warning restore CS8603 // Possible null reference return. public static readonly Func<T, T> Passthrough = _ => _; #pragma warning disable CS8714 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint. public static readonly Func<T, Option<T>> Some = _ => Option.Some(_); #pragma warning restore CS8714 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint. public static readonly Action<T> Void = _ => { }; public static readonly Func<T, Task> Task = _ => System.Threading.Tasks.Task.CompletedTask; } internal static class DelegateCache<TIn, TOut> { #pragma warning disable CS8603 // Possible null reference return. public static readonly Func<TIn, TOut> Default = _ => default; #pragma warning restore CS8603 // Possible null reference return. } internal static class Helpers { public static bool TryGetValue<TValue>(this Option<TValue> option, out TValue some) where TValue : notnull { some = option.Match(DelegateCache<TValue>.Passthrough, DelegateCache<TValue>.Default); return option.Match(DelegateCache<TValue>.True, DelegateCache.False); } public static bool TryGetValue<TSuccess, TFailure>(this Result<TSuccess, TFailure> result, out TSuccess success, out TFailure failure) where TSuccess : notnull where TFailure : notnull { success = result.Match(DelegateCache<TSuccess>.Passthrough, DelegateCache<TFailure, TSuccess>.Default); failure = result.Match(DelegateCache<TSuccess, TFailure>.Default, DelegateCache<TFailure>.Passthrough); return result.Match(DelegateCache<TSuccess>.True, DelegateCache<TFailure>.False); } } }
412
0.699282
1
0.699282
game-dev
MEDIA
0.224293
game-dev
0.940373
1
0.940373
magmafoundation/Magma-Neo
77,707
src/main/java/net/neoforged/neoforge/common/Tags.java
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.neoforged.neoforge.common; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.FluidTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; import net.minecraft.world.damagesource.DamageType; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.Item; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.material.Fluid; public class Tags { public static class Blocks { // `neoforge` tags for functional behavior provided by NeoForge /** * Controls what blocks Endermen cannot place blocks onto. * <p> * This is patched into the following method: {@link net.minecraft.world.entity.monster.EnderMan.EndermanLeaveBlockGoal#canPlaceBlock(Level, BlockPos, BlockState, BlockState, BlockState, BlockPos)} */ public static final TagKey<Block> ENDERMAN_PLACE_ON_BLACKLIST = neoforgeTag("enderman_place_on_blacklist"); /** * For denoting blocks that need tools that are Wood or higher to mine. * By default, this is not added to any Minecraft tag since Wood is in the lowest "tier". */ public static final TagKey<Block> NEEDS_WOOD_TOOL = neoforgeTag("needs_wood_tool"); /** * For denoting blocks that need tools that are Gold or higher to mine. * By default, this is not added to any Minecraft tag since Gold is in the lowest "tier". */ public static final TagKey<Block> NEEDS_GOLD_TOOL = neoforgeTag("needs_gold_tool"); /** * For denoting blocks that need tools that are Netherite or higher to mine. * Blocks in this tag gets added to the following Minecraft tags: * {@link BlockTags#INCORRECT_FOR_WOODEN_TOOL} * {@link BlockTags#INCORRECT_FOR_STONE_TOOL} * {@link BlockTags#INCORRECT_FOR_IRON_TOOL} * {@link BlockTags#INCORRECT_FOR_GOLD_TOOL} * {@link BlockTags#INCORRECT_FOR_DIAMOND_TOOL} */ public static final TagKey<Block> NEEDS_NETHERITE_TOOL = neoforgeTag("needs_netherite_tool"); // `c` tags for common conventions public static final TagKey<Block> BARRELS = tag("barrels"); public static final TagKey<Block> BARRELS_WOODEN = tag("barrels/wooden"); public static final TagKey<Block> BOOKSHELVES = tag("bookshelves"); /** * For blocks that are similar to amethyst where their budding block produces buds and cluster blocks */ public static final TagKey<Block> BUDDING_BLOCKS = tag("budding_blocks"); /** * For blocks that are similar to amethyst where they have buddings forming from budding blocks */ public static final TagKey<Block> BUDS = tag("buds"); public static final TagKey<Block> CHAINS = tag("chains"); public static final TagKey<Block> CHESTS = tag("chests"); public static final TagKey<Block> CHESTS_ENDER = tag("chests/ender"); public static final TagKey<Block> CHESTS_TRAPPED = tag("chests/trapped"); public static final TagKey<Block> CHESTS_WOODEN = tag("chests/wooden"); /** * For blocks that are similar to amethyst where they have clusters forming from budding blocks */ public static final TagKey<Block> CLUSTERS = tag("clusters"); public static final TagKey<Block> COBBLESTONES = tag("cobblestones"); public static final TagKey<Block> COBBLESTONES_NORMAL = tag("cobblestones/normal"); public static final TagKey<Block> COBBLESTONES_INFESTED = tag("cobblestones/infested"); public static final TagKey<Block> COBBLESTONES_MOSSY = tag("cobblestones/mossy"); public static final TagKey<Block> COBBLESTONES_DEEPSLATE = tag("cobblestones/deepslate"); public static final TagKey<Block> CONCRETES = tag("concretes"); /** * Tag that holds all blocks that can be dyed a specific color. * (Does not include color blending blocks that would behave similar to leather armor item) */ public static final TagKey<Block> DYED = tag("dyed"); public static final TagKey<Block> DYED_BLACK = tag("dyed/black"); public static final TagKey<Block> DYED_BLUE = tag("dyed/blue"); public static final TagKey<Block> DYED_BROWN = tag("dyed/brown"); public static final TagKey<Block> DYED_CYAN = tag("dyed/cyan"); public static final TagKey<Block> DYED_GRAY = tag("dyed/gray"); public static final TagKey<Block> DYED_GREEN = tag("dyed/green"); public static final TagKey<Block> DYED_LIGHT_BLUE = tag("dyed/light_blue"); public static final TagKey<Block> DYED_LIGHT_GRAY = tag("dyed/light_gray"); public static final TagKey<Block> DYED_LIME = tag("dyed/lime"); public static final TagKey<Block> DYED_MAGENTA = tag("dyed/magenta"); public static final TagKey<Block> DYED_ORANGE = tag("dyed/orange"); public static final TagKey<Block> DYED_PINK = tag("dyed/pink"); public static final TagKey<Block> DYED_PURPLE = tag("dyed/purple"); public static final TagKey<Block> DYED_RED = tag("dyed/red"); public static final TagKey<Block> DYED_WHITE = tag("dyed/white"); public static final TagKey<Block> DYED_YELLOW = tag("dyed/yellow"); public static final TagKey<Block> END_STONES = tag("end_stones"); public static final TagKey<Block> FENCE_GATES = tag("fence_gates"); public static final TagKey<Block> FENCE_GATES_WOODEN = tag("fence_gates/wooden"); public static final TagKey<Block> FENCES = tag("fences"); public static final TagKey<Block> FENCES_NETHER_BRICK = tag("fences/nether_brick"); public static final TagKey<Block> FENCES_WOODEN = tag("fences/wooden"); public static final TagKey<Block> GLASS_BLOCKS = tag("glass_blocks"); public static final TagKey<Block> GLASS_BLOCKS_COLORLESS = tag("glass_blocks/colorless"); /** * Glass which is made from cheap resources like sand and only minor additional ingredients like dyes */ public static final TagKey<Block> GLASS_BLOCKS_CHEAP = tag("glass_blocks/cheap"); public static final TagKey<Block> GLASS_BLOCKS_TINTED = tag("glass_blocks/tinted"); public static final TagKey<Block> GLASS_PANES = tag("glass_panes"); public static final TagKey<Block> GLASS_PANES_COLORLESS = tag("glass_panes/colorless"); public static final TagKey<Block> GLAZED_TERRACOTTAS = tag("glazed_terracottas"); public static final TagKey<Block> GRAVELS = tag("gravels"); /** * Tag that holds all blocks that recipe viewers should not show to users. * Recipe viewers may use this to automatically find the corresponding BlockItem to hide. */ public static final TagKey<Block> HIDDEN_FROM_RECIPE_VIEWERS = tag("hidden_from_recipe_viewers"); public static final TagKey<Block> NETHERRACKS = tag("netherracks"); public static final TagKey<Block> OBSIDIANS = tag("obsidians"); /** * For common obsidian that has no special quirks or behaviors. Ideal for recipe use. * Crying Obsidian, for example, is a light block and harder to obtain. So it gets its own tag instead of being under normal tag. */ public static final TagKey<Block> OBSIDIANS_NORMAL = tag("obsidians/normal"); public static final TagKey<Block> OBSIDIANS_CRYING = tag("obsidians/crying"); /** * Blocks which are often replaced by deepslate ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_DEEPSLATE}, during world generation. * (The block's registry name is used as the tag name) */ public static final TagKey<Block> ORE_BEARING_GROUND_DEEPSLATE = tag("ore_bearing_ground/deepslate"); /** * Blocks which are often replaced by netherrack ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_NETHERRACK}, during world generation. * (The block's registry name is used as the tag name) */ public static final TagKey<Block> ORE_BEARING_GROUND_NETHERRACK = tag("ore_bearing_ground/netherrack"); /** * Blocks which are often replaced by stone ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_STONE}, during world generation. * (The block's registry name is used as the tag name) */ public static final TagKey<Block> ORE_BEARING_GROUND_STONE = tag("ore_bearing_ground/stone"); /** * Ores which on average result in more than one resource worth of materials ignoring fortune and other modifiers. * (example, Copper Ore) */ public static final TagKey<Block> ORE_RATES_DENSE = tag("ore_rates/dense"); /** * Ores which on average result in one resource worth of materials ignoring fortune and other modifiers. * (Example, Iron Ore) */ public static final TagKey<Block> ORE_RATES_SINGULAR = tag("ore_rates/singular"); /** * Ores which on average result in less than one resource worth of materials ignoring fortune and other modifiers. * (Example, Nether Gold Ore as it drops 2 to 6 Gold Nuggets which is less than normal Gold Ore's Raw Gold drop) */ public static final TagKey<Block> ORE_RATES_SPARSE = tag("ore_rates/sparse"); public static final TagKey<Block> ORES = tag("ores"); public static final TagKey<Block> ORES_COAL = tag("ores/coal"); public static final TagKey<Block> ORES_COPPER = tag("ores/copper"); public static final TagKey<Block> ORES_DIAMOND = tag("ores/diamond"); public static final TagKey<Block> ORES_EMERALD = tag("ores/emerald"); public static final TagKey<Block> ORES_GOLD = tag("ores/gold"); public static final TagKey<Block> ORES_IRON = tag("ores/iron"); public static final TagKey<Block> ORES_LAPIS = tag("ores/lapis"); public static final TagKey<Block> ORES_NETHERITE_SCRAP = tag("ores/netherite_scrap"); public static final TagKey<Block> ORES_QUARTZ = tag("ores/quartz"); public static final TagKey<Block> ORES_REDSTONE = tag("ores/redstone"); /** * Ores in deepslate (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_DEEPSLATE}) which could logically use deepslate as recipe input or output. * (The block's registry name is used as the tag name) */ public static final TagKey<Block> ORES_IN_GROUND_DEEPSLATE = tag("ores_in_ground/deepslate"); /** * Ores in netherrack (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_NETHERRACK}) which could logically use netherrack as recipe input or output. * (The block's registry name is used as the tag name) */ public static final TagKey<Block> ORES_IN_GROUND_NETHERRACK = tag("ores_in_ground/netherrack"); /** * Ores in stone (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_STONE}) which could logically use stone as recipe input or output. * (The block's registry name is used as the tag name) */ public static final TagKey<Block> ORES_IN_GROUND_STONE = tag("ores_in_ground/stone"); public static final TagKey<Block> PUMPKINS = tag("pumpkins"); /** * For pumpkins that are not carved. */ public static final TagKey<Block> PUMPKINS_NORMAL = tag("pumpkins/normal"); /** * For pumpkins that are already carved but not a light source. */ public static final TagKey<Block> PUMPKINS_CARVED = tag("pumpkins/carved"); /** * For pumpkins that are already carved and a light source. */ public static final TagKey<Block> PUMPKINS_JACK_O_LANTERNS = tag("pumpkins/jack_o_lanterns"); public static final TagKey<Block> PLAYER_WORKSTATIONS_CRAFTING_TABLES = tag("player_workstations/crafting_tables"); public static final TagKey<Block> PLAYER_WORKSTATIONS_FURNACES = tag("player_workstations/furnaces"); /** * Blocks should be included in this tag if their movement/relocation can cause serious issues such * as world corruption upon being moved or for balance reason where the block should not be able to be relocated. * Example: Chunk loaders or pipes where other mods that move blocks do not respect * {@link BlockBehaviour.BlockStateBase#getPistonPushReaction}. */ public static final TagKey<Block> RELOCATION_NOT_SUPPORTED = tag("relocation_not_supported"); public static final TagKey<Block> ROPES = tag("ropes"); public static final TagKey<Block> SANDS = tag("sands"); public static final TagKey<Block> SANDS_COLORLESS = tag("sands/colorless"); public static final TagKey<Block> SANDS_RED = tag("sands/red"); public static final TagKey<Block> SANDSTONE_BLOCKS = tag("sandstone/blocks"); public static final TagKey<Block> SANDSTONE_SLABS = tag("sandstone/slabs"); public static final TagKey<Block> SANDSTONE_STAIRS = tag("sandstone/stairs"); public static final TagKey<Block> SANDSTONE_RED_BLOCKS = tag("sandstone/red_blocks"); public static final TagKey<Block> SANDSTONE_RED_SLABS = tag("sandstone/red_slabs"); public static final TagKey<Block> SANDSTONE_RED_STAIRS = tag("sandstone/red_stairs"); public static final TagKey<Block> SANDSTONE_UNCOLORED_BLOCKS = tag("sandstone/uncolored_blocks"); public static final TagKey<Block> SANDSTONE_UNCOLORED_SLABS = tag("sandstone/uncolored_slabs"); public static final TagKey<Block> SANDSTONE_UNCOLORED_STAIRS = tag("sandstone/uncolored_stairs"); /** * Tag that holds all head based blocks such as Skeleton Skull or Player Head. (Named skulls to match minecraft:skulls item tag) */ public static final TagKey<Block> SKULLS = tag("skulls"); /** * Natural stone-like blocks that can be used as a base ingredient in recipes that takes stone. */ public static final TagKey<Block> STONES = tag("stones"); /** * A storage block is generally a block that has a recipe to craft a bulk of 1 kind of resource to a block * and has a mirror recipe to reverse the crafting with no loss in resources. * <p> * Honey Block is special in that the reversing recipe is not a perfect mirror of the crafting recipe * and so, it is considered a special case and not given a storage block tag. */ public static final TagKey<Block> STORAGE_BLOCKS = tag("storage_blocks"); public static final TagKey<Block> STORAGE_BLOCKS_BONE_MEAL = tag("storage_blocks/bone_meal"); public static final TagKey<Block> STORAGE_BLOCKS_COAL = tag("storage_blocks/coal"); public static final TagKey<Block> STORAGE_BLOCKS_COPPER = tag("storage_blocks/copper"); public static final TagKey<Block> STORAGE_BLOCKS_DIAMOND = tag("storage_blocks/diamond"); public static final TagKey<Block> STORAGE_BLOCKS_DRIED_KELP = tag("storage_blocks/dried_kelp"); public static final TagKey<Block> STORAGE_BLOCKS_EMERALD = tag("storage_blocks/emerald"); public static final TagKey<Block> STORAGE_BLOCKS_GOLD = tag("storage_blocks/gold"); public static final TagKey<Block> STORAGE_BLOCKS_IRON = tag("storage_blocks/iron"); public static final TagKey<Block> STORAGE_BLOCKS_LAPIS = tag("storage_blocks/lapis"); public static final TagKey<Block> STORAGE_BLOCKS_NETHERITE = tag("storage_blocks/netherite"); public static final TagKey<Block> STORAGE_BLOCKS_RAW_COPPER = tag("storage_blocks/raw_copper"); public static final TagKey<Block> STORAGE_BLOCKS_RAW_GOLD = tag("storage_blocks/raw_gold"); public static final TagKey<Block> STORAGE_BLOCKS_RAW_IRON = tag("storage_blocks/raw_iron"); public static final TagKey<Block> STORAGE_BLOCKS_REDSTONE = tag("storage_blocks/redstone"); public static final TagKey<Block> STORAGE_BLOCKS_SLIME = tag("storage_blocks/slime"); public static final TagKey<Block> STORAGE_BLOCKS_WHEAT = tag("storage_blocks/wheat"); public static final TagKey<Block> STRIPPED_LOGS = tag("stripped_logs"); public static final TagKey<Block> STRIPPED_WOODS = tag("stripped_woods"); public static final TagKey<Block> VILLAGER_JOB_SITES = tag("villager_job_sites"); /** * Blocks tagged here will be tracked by Farmer Villagers who will attempt to plant crops on top. */ public static final TagKey<Block> VILLAGER_FARMLANDS = neoforgeTag("villager_farmlands"); private static TagKey<Block> tag(String name) { return BlockTags.create(ResourceLocation.fromNamespaceAndPath("c", name)); } private static TagKey<Block> neoforgeTag(String name) { return BlockTags.create(ResourceLocation.fromNamespaceAndPath("neoforge", name)); } } public static class EntityTypes { public static final TagKey<EntityType<?>> BOSSES = tag("bosses"); public static final TagKey<EntityType<?>> MINECARTS = tag("minecarts"); public static final TagKey<EntityType<?>> BOATS = tag("boats"); /** * Entities should be included in this tag if they are not allowed to be picked up by items or grabbed in a way * that a player can easily move the entity to anywhere they want. Ideal for special entities that should not * be able to be put into a mob jar for example. */ public static final TagKey<EntityType<?>> CAPTURING_NOT_SUPPORTED = tag("capturing_not_supported"); /** * Entities should be included in this tag if they are not allowed to be teleported in any way. * This is more for mods that allow teleporting entities within the same dimension. Any mod that is * teleporting entities to new dimensions should be checking canChangeDimensions method on the entity itself. */ public static final TagKey<EntityType<?>> TELEPORTING_NOT_SUPPORTED = tag("teleporting_not_supported"); private static TagKey<EntityType<?>> tag(String name) { return TagKey.create(Registries.ENTITY_TYPE, ResourceLocation.fromNamespaceAndPath("c", name)); } } public static class Items { // `neoforge` tags for functional behavior provided by NeoForge /** * Controls what items can be consumed for enchanting such as Enchanting Tables. * This tag defaults to {@link net.minecraft.world.item.Items#LAPIS_LAZULI} when not present in any datapacks, including forge client on vanilla server */ public static final TagKey<Item> ENCHANTING_FUELS = neoforgeTag("enchanting_fuels"); // `c` tags for common conventions public static final TagKey<Item> BARRELS = tag("barrels"); public static final TagKey<Item> BARRELS_WOODEN = tag("barrels/wooden"); public static final TagKey<Item> BONES = tag("bones"); public static final TagKey<Item> BOOKSHELVES = tag("bookshelves"); public static final TagKey<Item> BRICKS = tag("bricks"); public static final TagKey<Item> BRICKS_NORMAL = tag("bricks/normal"); public static final TagKey<Item> BRICKS_NETHER = tag("bricks/nether"); public static final TagKey<Item> BUCKETS = tag("buckets"); public static final TagKey<Item> BUCKETS_EMPTY = tag("buckets/empty"); /** * Does not include entity water buckets. * If checking for the fluid this bucket holds in code, please use {@link net.neoforged.neoforge.fluids.capability.wrappers.FluidBucketWrapper#getFluid} instead. */ public static final TagKey<Item> BUCKETS_WATER = tag("buckets/water"); /** * If checking for the fluid this bucket holds in code, please use {@link net.neoforged.neoforge.fluids.capability.wrappers.FluidBucketWrapper#getFluid} instead. */ public static final TagKey<Item> BUCKETS_LAVA = tag("buckets/lava"); public static final TagKey<Item> BUCKETS_MILK = tag("buckets/milk"); public static final TagKey<Item> BUCKETS_POWDER_SNOW = tag("buckets/powder_snow"); public static final TagKey<Item> BUCKETS_ENTITY_WATER = tag("buckets/entity_water"); /** * For blocks that are similar to amethyst where their budding block produces buds and cluster blocks */ public static final TagKey<Item> BUDDING_BLOCKS = tag("budding_blocks"); /** * For blocks that are similar to amethyst where they have buddings forming from budding blocks */ public static final TagKey<Item> BUDS = tag("buds"); public static final TagKey<Item> CHAINS = tag("chains"); public static final TagKey<Item> CHESTS = tag("chests"); public static final TagKey<Item> CHESTS_ENDER = tag("chests/ender"); public static final TagKey<Item> CHESTS_TRAPPED = tag("chests/trapped"); public static final TagKey<Item> CHESTS_WOODEN = tag("chests/wooden"); public static final TagKey<Item> COBBLESTONES = tag("cobblestones"); public static final TagKey<Item> COBBLESTONES_NORMAL = tag("cobblestones/normal"); public static final TagKey<Item> COBBLESTONES_INFESTED = tag("cobblestones/infested"); public static final TagKey<Item> COBBLESTONES_MOSSY = tag("cobblestones/mossy"); public static final TagKey<Item> COBBLESTONES_DEEPSLATE = tag("cobblestones/deepslate"); public static final TagKey<Item> CONCRETES = tag("concretes"); /** * Block tag equivalent is {@link BlockTags#CONCRETE_POWDER} */ public static final TagKey<Item> CONCRETE_POWDERS = tag("concrete_powders"); /** * For blocks that are similar to amethyst where they have clusters forming from budding blocks */ public static final TagKey<Item> CLUSTERS = tag("clusters"); /** * For raw materials harvested from growable plants. Crop items can be edible like carrots or * non-edible like wheat and cocoa beans. */ public static final TagKey<Item> CROPS = tag("crops"); public static final TagKey<Item> CROPS_BEETROOT = tag("crops/beetroot"); public static final TagKey<Item> CROPS_CACTUS = tag("crops/cactus"); public static final TagKey<Item> CROPS_CARROT = tag("crops/carrot"); public static final TagKey<Item> CROPS_COCOA_BEAN = tag("crops/cocoa_bean"); public static final TagKey<Item> CROPS_MELON = tag("crops/melon"); public static final TagKey<Item> CROPS_NETHER_WART = tag("crops/nether_wart"); public static final TagKey<Item> CROPS_POTATO = tag("crops/potato"); public static final TagKey<Item> CROPS_PUMPKIN = tag("crops/pumpkin"); public static final TagKey<Item> CROPS_SUGAR_CANE = tag("crops/sugar_cane"); public static final TagKey<Item> CROPS_WHEAT = tag("crops/wheat"); /** * Drinks are defined as (1) consumable items that (2) use the * {@linkplain net.minecraft.world.item.ItemUseAnimation#DRINK drink item use animation}, (3) can be consumed regardless of the * player's current hunger. * * <p>Drinks may provide nutrition and saturation, but are not required to do so. * * <p>More specific types of drinks, such as Water, Milk, or Juice should be placed in a sub-tag, such as * {@code #c:drinks/water}, {@code #c:drinks/milk}, and {@code #c:drinks/juice}. */ public static final TagKey<Item> DRINKS = tag("drinks"); /** * For consumable drinks that contain only water. */ public static final TagKey<Item> DRINKS_WATER = tag("drinks/water"); /** * For consumable drinks that are generally watery (such as potions). */ public static final TagKey<Item> DRINKS_WATERY = tag("drinks/watery"); public static final TagKey<Item> DRINKS_MILK = tag("drinks/milk"); public static final TagKey<Item> DRINKS_HONEY = tag("drinks/honey"); /** * For consumable drinks that are magic in nature and usually grant at least one * {@link net.minecraft.world.effect.MobEffect} when consumed. */ public static final TagKey<Item> DRINKS_MAGIC = tag("drinks/magic"); /** * For drinks that always grant the {@linkplain net.minecraft.world.effect.MobEffects#BAD_OMEN Bad Omen} effect. */ public static final TagKey<Item> DRINKS_OMINOUS = tag("drinks/ominous"); /** * Plant based fruit and vegetable juices belong in this tag, for example apple juice and carrot juice. * * <p>If tags for specific types of juices are desired, they may go in a sub-tag, using their regular name such as * {@code #c:drinks/apple_juice}. */ public static final TagKey<Item> DRINKS_JUICE = tag("drinks/juice"); /** * For non-empty bottles that are {@linkplain #DRINKS drinkable}. */ public static final TagKey<Item> DRINK_CONTAINING_BOTTLE = tag("drink_containing/bottle"); /** * For non-empty buckets that are {@linkplain #DRINKS drinkable}. */ public static final TagKey<Item> DRINK_CONTAINING_BUCKET = tag("drink_containing/bucket"); public static final TagKey<Item> DUSTS = tag("dusts"); public static final TagKey<Item> DUSTS_REDSTONE = tag("dusts/redstone"); public static final TagKey<Item> DUSTS_GLOWSTONE = tag("dusts/glowstone"); /** * Tag that holds all blocks and items that can be dyed a specific color. * (Does not include color blending items like leather armor * Use {@link net.minecraft.tags.ItemTags#DYEABLE} tag instead for color blending items) * <p> * Note: Use custom ingredients in recipes to do tag intersections and/or tag exclusions * to make more powerful recipes utilizing multiple tags such as dyed tags for an ingredient. * See {@link net.neoforged.neoforge.common.crafting.DifferenceIngredient} and {@link net.neoforged.neoforge.common.crafting.CompoundIngredient} * for various custom ingredients available that can also be used in data generation. */ public static final TagKey<Item> DYED = tag("dyed"); public static final TagKey<Item> DYED_BLACK = tag("dyed/black"); public static final TagKey<Item> DYED_BLUE = tag("dyed/blue"); public static final TagKey<Item> DYED_BROWN = tag("dyed/brown"); public static final TagKey<Item> DYED_CYAN = tag("dyed/cyan"); public static final TagKey<Item> DYED_GRAY = tag("dyed/gray"); public static final TagKey<Item> DYED_GREEN = tag("dyed/green"); public static final TagKey<Item> DYED_LIGHT_BLUE = tag("dyed/light_blue"); public static final TagKey<Item> DYED_LIGHT_GRAY = tag("dyed/light_gray"); public static final TagKey<Item> DYED_LIME = tag("dyed/lime"); public static final TagKey<Item> DYED_MAGENTA = tag("dyed/magenta"); public static final TagKey<Item> DYED_ORANGE = tag("dyed/orange"); public static final TagKey<Item> DYED_PINK = tag("dyed/pink"); public static final TagKey<Item> DYED_PURPLE = tag("dyed/purple"); public static final TagKey<Item> DYED_RED = tag("dyed/red"); public static final TagKey<Item> DYED_WHITE = tag("dyed/white"); public static final TagKey<Item> DYED_YELLOW = tag("dyed/yellow"); public static final TagKey<Item> DYES = tag("dyes"); public static final TagKey<Item> DYES_BLACK = DyeColor.BLACK.getTag(); public static final TagKey<Item> DYES_RED = DyeColor.RED.getTag(); public static final TagKey<Item> DYES_GREEN = DyeColor.GREEN.getTag(); public static final TagKey<Item> DYES_BROWN = DyeColor.BROWN.getTag(); public static final TagKey<Item> DYES_BLUE = DyeColor.BLUE.getTag(); public static final TagKey<Item> DYES_PURPLE = DyeColor.PURPLE.getTag(); public static final TagKey<Item> DYES_CYAN = DyeColor.CYAN.getTag(); public static final TagKey<Item> DYES_LIGHT_GRAY = DyeColor.LIGHT_GRAY.getTag(); public static final TagKey<Item> DYES_GRAY = DyeColor.GRAY.getTag(); public static final TagKey<Item> DYES_PINK = DyeColor.PINK.getTag(); public static final TagKey<Item> DYES_LIME = DyeColor.LIME.getTag(); public static final TagKey<Item> DYES_YELLOW = DyeColor.YELLOW.getTag(); public static final TagKey<Item> DYES_LIGHT_BLUE = DyeColor.LIGHT_BLUE.getTag(); public static final TagKey<Item> DYES_MAGENTA = DyeColor.MAGENTA.getTag(); public static final TagKey<Item> DYES_ORANGE = DyeColor.ORANGE.getTag(); public static final TagKey<Item> DYES_WHITE = DyeColor.WHITE.getTag(); /** * For eggs to use for culinary purposes in recipes such as baking a cake. */ public static final TagKey<Item> EGGS = tag("eggs"); public static final TagKey<Item> END_STONES = tag("end_stones"); public static final TagKey<Item> ENDER_PEARLS = tag("ender_pearls"); public static final TagKey<Item> FEATHERS = tag("feathers"); public static final TagKey<Item> FENCE_GATES = tag("fence_gates"); public static final TagKey<Item> FENCE_GATES_WOODEN = tag("fence_gates/wooden"); public static final TagKey<Item> FENCES = tag("fences"); public static final TagKey<Item> FENCES_NETHER_BRICK = tag("fences/nether_brick"); public static final TagKey<Item> FENCES_WOODEN = tag("fences/wooden"); /** * For bonemeal-like items that can grow plants. * (Note: Could include durability-based modded bonemeal-like items. Check for durability {@link net.minecraft.core.component.DataComponents#DAMAGE} DataComponent to handle them properly) */ public static final TagKey<Item> FERTILIZERS = tag("fertilizers"); public static final TagKey<Item> FOODS = tag("foods"); /** * Apples and other foods that are considered fruits in the culinary field belong in this tag. * Cherries would go here as they are considered a "stone fruit" within culinary fields. */ public static final TagKey<Item> FOODS_FRUIT = tag("foods/fruit"); /** * Tomatoes and other foods that are considered vegetables in the culinary field belong in this tag. */ public static final TagKey<Item> FOODS_VEGETABLE = tag("foods/vegetable"); /** * Strawberries, raspberries, and other berry foods belong in this tag. * Cherries would NOT go here as they are considered a "stone fruit" within culinary fields. */ public static final TagKey<Item> FOODS_BERRY = tag("foods/berry"); public static final TagKey<Item> FOODS_BREAD = tag("foods/bread"); public static final TagKey<Item> FOODS_COOKIE = tag("foods/cookie"); public static final TagKey<Item> FOODS_RAW_MEAT = tag("foods/raw_meat"); public static final TagKey<Item> FOODS_COOKED_MEAT = tag("foods/cooked_meat"); public static final TagKey<Item> FOODS_RAW_FISH = tag("foods/raw_fish"); public static final TagKey<Item> FOODS_COOKED_FISH = tag("foods/cooked_fish"); /** * Soups, stews, and other liquid food in bowls belongs in this tag. */ public static final TagKey<Item> FOODS_SOUP = tag("foods/soup"); /** * Sweets and candies like lollipops or chocolate belong in this tag. */ public static final TagKey<Item> FOODS_CANDY = tag("foods/candy"); /** * Pies and other pie-like foods belong in this tag. */ public static final TagKey<Item> FOODS_PIE = tag("foods/pie"); /** * Any gold-based foods would go in this tag. Such as Golden Apples or Glistering Melon Slice. */ public static final TagKey<Item> FOODS_GOLDEN = tag("foods/golden"); /** * Foods like cake that can be eaten when placed in the world belong in this tag. */ public static final TagKey<Item> FOODS_EDIBLE_WHEN_PLACED = tag("foods/edible_when_placed"); /** * For foods that inflict food poisoning-like effects. * Examples are Rotten Flesh's Hunger or Pufferfish's Nausea, or Poisonous Potato's Poison. */ public static final TagKey<Item> FOODS_FOOD_POISONING = tag("foods/food_poisoning"); /** * All foods edible by animals excluding poisonous foods. * (Does not include {@link ItemTags#PARROT_POISONOUS_FOOD}) */ public static final TagKey<Item> ANIMAL_FOODS = tag("animal_foods"); public static final TagKey<Item> GEMS = tag("gems"); public static final TagKey<Item> GEMS_DIAMOND = tag("gems/diamond"); public static final TagKey<Item> GEMS_EMERALD = tag("gems/emerald"); public static final TagKey<Item> GEMS_AMETHYST = tag("gems/amethyst"); public static final TagKey<Item> GEMS_LAPIS = tag("gems/lapis"); public static final TagKey<Item> GEMS_PRISMARINE = tag("gems/prismarine"); public static final TagKey<Item> GEMS_QUARTZ = tag("gems/quartz"); public static final TagKey<Item> GLASS_BLOCKS = tag("glass_blocks"); public static final TagKey<Item> GLASS_BLOCKS_COLORLESS = tag("glass_blocks/colorless"); /** * Glass which is made from cheap resources like sand and only minor additional ingredients like dyes */ public static final TagKey<Item> GLASS_BLOCKS_CHEAP = tag("glass_blocks/cheap"); public static final TagKey<Item> GLASS_BLOCKS_TINTED = tag("glass_blocks/tinted"); public static final TagKey<Item> GLASS_PANES = tag("glass_panes"); public static final TagKey<Item> GLASS_PANES_COLORLESS = tag("glass_panes/colorless"); public static final TagKey<Item> GLAZED_TERRACOTTAS = tag("glazed_terracottas"); public static final TagKey<Item> GRAVELS = tag("gravels"); public static final TagKey<Item> GUNPOWDERS = tag("gunpowders"); /** * Tag that holds all items that recipe viewers should not show to users. */ public static final TagKey<Item> HIDDEN_FROM_RECIPE_VIEWERS = tag("hidden_from_recipe_viewers"); public static final TagKey<Item> INGOTS = tag("ingots"); public static final TagKey<Item> INGOTS_COPPER = tag("ingots/copper"); public static final TagKey<Item> INGOTS_GOLD = tag("ingots/gold"); public static final TagKey<Item> INGOTS_IRON = tag("ingots/iron"); public static final TagKey<Item> INGOTS_NETHERITE = tag("ingots/netherite"); public static final TagKey<Item> LEATHERS = tag("leathers"); /** * Small mushroom items. Not the full block forms. */ public static final TagKey<Item> MUSHROOMS = tag("mushrooms"); /** * For music disc-like materials to be used in recipes. * A pancake with a JUKEBOX_PLAYABLE component attached to play in Jukeboxes as an Easter Egg is not a music disc and would not go in this tag. */ public static final TagKey<Item> MUSIC_DISCS = tag("music_discs"); public static final TagKey<Item> NETHER_STARS = tag("nether_stars"); public static final TagKey<Item> NETHERRACKS = tag("netherracks"); public static final TagKey<Item> NUGGETS = tag("nuggets"); public static final TagKey<Item> NUGGETS_GOLD = tag("nuggets/gold"); public static final TagKey<Item> NUGGETS_IRON = tag("nuggets/iron"); public static final TagKey<Item> OBSIDIANS = tag("obsidians"); /** * For common obsidian that has no special quirks or behaviors. Ideal for recipe use. * Crying Obsidian, for example, is a light block and harder to obtain. So it gets its own tag instead of being under normal tag. */ public static final TagKey<Item> OBSIDIANS_NORMAL = tag("obsidians/normal"); public static final TagKey<Item> OBSIDIANS_CRYING = tag("obsidians/crying"); /** * Blocks which are often replaced by deepslate ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_DEEPSLATE}, during world generation. * (The block's registry name is used as the tag name) */ public static final TagKey<Item> ORE_BEARING_GROUND_DEEPSLATE = tag("ore_bearing_ground/deepslate"); /** * Blocks which are often replaced by netherrack ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_NETHERRACK}, during world generation. * (The block's registry name is used as the tag name) */ public static final TagKey<Item> ORE_BEARING_GROUND_NETHERRACK = tag("ore_bearing_ground/netherrack"); /** * Blocks which are often replaced by stone ores, i.e. the ores in the tag {@link #ORES_IN_GROUND_STONE}, during world generation. * (The block's registry name is used as the tag name) */ public static final TagKey<Item> ORE_BEARING_GROUND_STONE = tag("ore_bearing_ground/stone"); /** * Ores which on average result in more than one resource worth of materials ignoring fortune and other modifiers. * (example, Copper Ore) */ public static final TagKey<Item> ORE_RATES_DENSE = tag("ore_rates/dense"); /** * Ores which on average result in one resource worth of materials ignoring fortune and other modifiers. * (Example, Iron Ore) */ public static final TagKey<Item> ORE_RATES_SINGULAR = tag("ore_rates/singular"); /** * Ores which on average result in less than one resource worth of materials ignoring fortune and other modifiers. * (Example, Nether Gold Ore as it drops 2 to 6 Gold Nuggets which is less than normal Gold Ore's Raw Gold drop) */ public static final TagKey<Item> ORE_RATES_SPARSE = tag("ore_rates/sparse"); public static final TagKey<Item> ORES = tag("ores"); public static final TagKey<Item> ORES_COAL = tag("ores/coal"); public static final TagKey<Item> ORES_COPPER = tag("ores/copper"); public static final TagKey<Item> ORES_DIAMOND = tag("ores/diamond"); public static final TagKey<Item> ORES_EMERALD = tag("ores/emerald"); public static final TagKey<Item> ORES_GOLD = tag("ores/gold"); public static final TagKey<Item> ORES_IRON = tag("ores/iron"); public static final TagKey<Item> ORES_LAPIS = tag("ores/lapis"); public static final TagKey<Item> ORES_NETHERITE_SCRAP = tag("ores/netherite_scrap"); public static final TagKey<Item> ORES_QUARTZ = tag("ores/quartz"); public static final TagKey<Item> ORES_REDSTONE = tag("ores/redstone"); /** * Ores in deepslate (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_DEEPSLATE}) which could logically use deepslate as recipe input or output. * (The block's registry name is used as the tag name) */ public static final TagKey<Item> ORES_IN_GROUND_DEEPSLATE = tag("ores_in_ground/deepslate"); /** * Ores in netherrack (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_NETHERRACK}) which could logically use netherrack as recipe input or output. * (The block's registry name is used as the tag name) */ public static final TagKey<Item> ORES_IN_GROUND_NETHERRACK = tag("ores_in_ground/netherrack"); /** * Ores in stone (or in equivalent blocks in the tag {@link #ORE_BEARING_GROUND_STONE}) which could logically use stone as recipe input or output. * (The block's registry name is used as the tag name) */ public static final TagKey<Item> ORES_IN_GROUND_STONE = tag("ores_in_ground/stone"); public static final TagKey<Item> PLAYER_WORKSTATIONS_CRAFTING_TABLES = tag("player_workstations/crafting_tables"); public static final TagKey<Item> PLAYER_WORKSTATIONS_FURNACES = tag("player_workstations/furnaces"); /** * Items that can hold various potion effects by making use of {@link net.minecraft.core.component.DataComponents#POTION_CONTENTS}. * Contents of this tag may not always be a kind of bottle. Buckets of potions could go here. * The subtags would be the name of the container that is holding the potion effects such as `c:potions/bucket` or `c:potions/vial` as examples. */ public static final TagKey<Item> POTIONS = tag("potions"); /** * Variations of the potion bottle that can hold various effects by using {@link net.minecraft.core.component.DataComponents#POTION_CONTENTS}. * Examples are splash and lingering potions from vanilla. * If a mod adds a new variant like a seeking potion that applies effect to the closest entity at impact, that would in this tag. */ public static final TagKey<Item> POTION_BOTTLE = tag("potions/bottle"); public static final TagKey<Item> PUMPKINS = tag("pumpkins"); /** * For pumpkins that are not carved. */ public static final TagKey<Item> PUMPKINS_NORMAL = tag("pumpkins/normal"); /** * For pumpkins that are already carved but not a light source. */ public static final TagKey<Item> PUMPKINS_CARVED = tag("pumpkins/carved"); /** * For pumpkins that are already carved and a light source. */ public static final TagKey<Item> PUMPKINS_JACK_O_LANTERNS = tag("pumpkins/jack_o_lanterns"); public static final TagKey<Item> RAW_MATERIALS = tag("raw_materials"); public static final TagKey<Item> RAW_MATERIALS_COPPER = tag("raw_materials/copper"); public static final TagKey<Item> RAW_MATERIALS_GOLD = tag("raw_materials/gold"); public static final TagKey<Item> RAW_MATERIALS_IRON = tag("raw_materials/iron"); /** * For rod-like materials to be used in recipes. */ public static final TagKey<Item> RODS = tag("rods"); public static final TagKey<Item> RODS_BLAZE = tag("rods/blaze"); public static final TagKey<Item> RODS_BREEZE = tag("rods/breeze"); /** * For stick-like materials to be used in recipes. * One example is a mod adds stick variants such as Spruce Sticks but would like stick recipes to be able to use it. */ public static final TagKey<Item> RODS_WOODEN = tag("rods/wooden"); public static final TagKey<Item> ROPES = tag("ropes"); public static final TagKey<Item> SANDS = tag("sands"); public static final TagKey<Item> SANDS_COLORLESS = tag("sands/colorless"); public static final TagKey<Item> SANDS_RED = tag("sands/red"); public static final TagKey<Item> SANDSTONE_BLOCKS = tag("sandstone/blocks"); public static final TagKey<Item> SANDSTONE_SLABS = tag("sandstone/slabs"); public static final TagKey<Item> SANDSTONE_STAIRS = tag("sandstone/stairs"); public static final TagKey<Item> SANDSTONE_RED_BLOCKS = tag("sandstone/red_blocks"); public static final TagKey<Item> SANDSTONE_RED_SLABS = tag("sandstone/red_slabs"); public static final TagKey<Item> SANDSTONE_RED_STAIRS = tag("sandstone/red_stairs"); public static final TagKey<Item> SANDSTONE_UNCOLORED_BLOCKS = tag("sandstone/uncolored_blocks"); public static final TagKey<Item> SANDSTONE_UNCOLORED_SLABS = tag("sandstone/uncolored_slabs"); public static final TagKey<Item> SANDSTONE_UNCOLORED_STAIRS = tag("sandstone/uncolored_stairs"); /** * For items that are explicitly seeds for use cases such as refilling a bird feeder block or certain seed-based recipes. */ public static final TagKey<Item> SEEDS = tag("seeds"); public static final TagKey<Item> SEEDS_BEETROOT = tag("seeds/beetroot"); public static final TagKey<Item> SEEDS_MELON = tag("seeds/melon"); public static final TagKey<Item> SEEDS_PUMPKIN = tag("seeds/pumpkin"); public static final TagKey<Item> SEEDS_TORCHFLOWER = tag("seeds/torchflower"); public static final TagKey<Item> SEEDS_WHEAT = tag("seeds/wheat"); /** * Block tag equivalent is {@link BlockTags#SHULKER_BOXES} */ public static final TagKey<Item> SHULKER_BOXES = tag("shulker_boxes"); public static final TagKey<Item> SLIME_BALLS = tag("slime_balls"); /** * Please use properly named {@link Tags.Items#SLIME_BALLS} tag and field instead * <p></p> * TODO: Remove in 1.21.1 */ @Deprecated(since = "1.21") public static final TagKey<Item> SLIMEBALLS = tag("slimeballs"); /** * Natural stone-like blocks that can be used as a base ingredient in recipes that takes stone. */ public static final TagKey<Item> STONES = tag("stones"); /** * A storage block is generally a block that has a recipe to craft a bulk of 1 kind of resource to a block * and has a mirror recipe to reverse the crafting with no loss in resources. * <p> * Honey Block is special in that the reversing recipe is not a perfect mirror of the crafting recipe * and so, it is considered a special case and not given a storage block tag. */ public static final TagKey<Item> STORAGE_BLOCKS = tag("storage_blocks"); public static final TagKey<Item> STORAGE_BLOCKS_BONE_MEAL = tag("storage_blocks/bone_meal"); public static final TagKey<Item> STORAGE_BLOCKS_COAL = tag("storage_blocks/coal"); public static final TagKey<Item> STORAGE_BLOCKS_COPPER = tag("storage_blocks/copper"); public static final TagKey<Item> STORAGE_BLOCKS_DIAMOND = tag("storage_blocks/diamond"); public static final TagKey<Item> STORAGE_BLOCKS_DRIED_KELP = tag("storage_blocks/dried_kelp"); public static final TagKey<Item> STORAGE_BLOCKS_EMERALD = tag("storage_blocks/emerald"); public static final TagKey<Item> STORAGE_BLOCKS_GOLD = tag("storage_blocks/gold"); public static final TagKey<Item> STORAGE_BLOCKS_IRON = tag("storage_blocks/iron"); public static final TagKey<Item> STORAGE_BLOCKS_LAPIS = tag("storage_blocks/lapis"); public static final TagKey<Item> STORAGE_BLOCKS_NETHERITE = tag("storage_blocks/netherite"); public static final TagKey<Item> STORAGE_BLOCKS_RAW_COPPER = tag("storage_blocks/raw_copper"); public static final TagKey<Item> STORAGE_BLOCKS_RAW_GOLD = tag("storage_blocks/raw_gold"); public static final TagKey<Item> STORAGE_BLOCKS_RAW_IRON = tag("storage_blocks/raw_iron"); public static final TagKey<Item> STORAGE_BLOCKS_REDSTONE = tag("storage_blocks/redstone"); public static final TagKey<Item> STORAGE_BLOCKS_SLIME = tag("storage_blocks/slime"); public static final TagKey<Item> STORAGE_BLOCKS_WHEAT = tag("storage_blocks/wheat"); public static final TagKey<Item> STRINGS = tag("strings"); public static final TagKey<Item> STRIPPED_LOGS = tag("stripped_logs"); public static final TagKey<Item> STRIPPED_WOODS = tag("stripped_woods"); public static final TagKey<Item> VILLAGER_JOB_SITES = tag("villager_job_sites"); // Tools and Armors /** * A tag containing all existing tools. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS = tag("tools"); /** * A tag containing all existing shields. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_SHIELD = tag("tools/shield"); /** * A tag containing all existing bows. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_BOW = tag("tools/bow"); /** * A tag containing all existing crossbows. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_CROSSBOW = tag("tools/crossbow"); /** * A tag containing all existing fishing rods. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_FISHING_ROD = tag("tools/fishing_rod"); /** * A tag containing all existing spears. Other tools such as throwing knives or boomerangs * should not be put into this tag and should be put into their own tool tags. * Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_SPEAR = tag("tools/spear"); /** * A tag containing all existing shears. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_SHEAR = tag("tools/shear"); /** * A tag containing all existing brushes. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_BRUSH = tag("tools/brush"); /** * A tag containing all existing fire starting tools such as Flint and Steel. * Fire Charge is not a tool (no durability) and thus, does not go in this tag. * Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_IGNITER = tag("tools/igniter"); /** * A tag containing all existing maces. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_MACE = tag("tools/mace"); /** * A tag containing all existing wrenches. Do not use this tag for determining a tool's behavior. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> TOOLS_WRENCH = tag("tools/wrench"); /** * A tag containing melee-based weapons for recipes and loot tables. * Tools are considered melee if they are intentionally intended to be used for melee attack as a primary purpose. * (In other words, Pickaxes are not melee weapons as they are not intended to be a weapon as a primary purpose) * Do not use this tag for determining a tool's behavior in-code. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> MELEE_WEAPON_TOOLS = tag("tools/melee_weapon"); /** * A tag containing ranged-based weapons for recipes and loot tables. * Tools are considered ranged if they can damage entities beyond the weapon's and player's melee attack range. * Do not use this tag for determining a tool's behavior in-code. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> RANGED_WEAPON_TOOLS = tag("tools/ranged_weapon"); /** * A tag containing mining-based tools for recipes and loot tables. * Do not use this tag for determining a tool's behavior in-code. * Please use {@link ItemAbilities} instead for what action a tool can do. * * @see ItemAbility * @see ItemAbilities */ public static final TagKey<Item> MINING_TOOL_TOOLS = tag("tools/mining_tool"); /** * Collects the 4 vanilla armor tags into one parent collection for ease. */ public static final TagKey<Item> ARMORS = tag("armors"); /** * Collects the many enchantable tags into one parent collection for ease. */ public static final TagKey<Item> ENCHANTABLES = tag("enchantables"); private static TagKey<Item> tag(String name) { return ItemTags.create(ResourceLocation.fromNamespaceAndPath("c", name)); } private static TagKey<Item> neoforgeTag(String name) { return ItemTags.create(ResourceLocation.fromNamespaceAndPath("neoforge", name)); } } /** * Note, fluid tags should not be plural to match the vanilla standard. * This is the only tag category exempted from many-different-types plural rule. */ public static class Fluids { /** * Holds all fluids related to water.<p> * This tag is done to help out multi-loader mods/datapacks where the vanilla water tag has attached behaviors outside Neo. */ public static final TagKey<Fluid> WATER = tag("water"); /** * Holds all fluids related to lava.<p> * This tag is done to help out multi-loader mods/datapacks where the vanilla lava tag has attached behaviors outside Neo. */ public static final TagKey<Fluid> LAVA = tag("lava"); /** * Holds all fluids related to milk. */ public static final TagKey<Fluid> MILK = tag("milk"); /** * Holds all fluids that are gaseous at room temperature. */ public static final TagKey<Fluid> GASEOUS = tag("gaseous"); /** * Holds all fluids related to honey. * <p> * (Standard unit for honey bottle is 250mb per bottle) */ public static final TagKey<Fluid> HONEY = tag("honey"); /** * Holds all fluids related to experience. * <p> * (Standard unit for experience is 20mb per 1 experience. However, extraction from Bottle o' Enchanting should yield 250mb while smashing yields less) */ public static final TagKey<Fluid> EXPERIENCE = tag("experience"); /** * Holds all fluids related to potions. The effects of the potion fluid should be read from DataComponents. * The effects and color of the potion fluid should be read from {@link net.minecraft.core.component.DataComponents#POTION_CONTENTS} * component that people should be attaching to the fluidstack of this fluid. * <p> * (Standard unit for potions is 250mb per bottle) */ public static final TagKey<Fluid> POTION = tag("potion"); /** * Holds all fluids related to Suspicious Stew. * The effects of the suspicious stew fluid should be read from {@link net.minecraft.core.component.DataComponents#SUSPICIOUS_STEW_EFFECTS} * component that people should be attaching to the fluidstack of this fluid. * <p> * (Standard unit for suspicious stew is 250mb per bowl) */ public static final TagKey<Fluid> SUSPICIOUS_STEW = tag("suspicious_stew"); /** * Holds all fluids related to Mushroom Stew. * <p> * (Standard unit for mushroom stew is 250mb per bowl) */ public static final TagKey<Fluid> MUSHROOM_STEW = tag("mushroom_stew"); /** * Holds all fluids related to Rabbit Stew. * <p> * (Standard unit for rabbit stew is 250mb per bowl) */ public static final TagKey<Fluid> RABBIT_STEW = tag("rabbit_stew"); /** * Holds all fluids related to Beetroot Soup. * <p> * (Standard unit for beetroot soup is 250mb per bowl) */ public static final TagKey<Fluid> BEETROOT_SOUP = tag("beetroot_soup"); /** * Tag that holds all fluids that recipe viewers should not show to users. */ public static final TagKey<Fluid> HIDDEN_FROM_RECIPE_VIEWERS = tag("hidden_from_recipe_viewers"); private static TagKey<Fluid> tag(String name) { return FluidTags.create(ResourceLocation.fromNamespaceAndPath("c", name)); } } public static class Enchantments { /** * A tag containing enchantments that increase the amount or * quality of drops from blocks, such as {@link net.minecraft.world.item.enchantment.Enchantments#FORTUNE}. */ public static final TagKey<Enchantment> INCREASE_BLOCK_DROPS = tag("increase_block_drops"); /** * A tag containing enchantments that increase the amount or * quality of drops from entities, such as {@link net.minecraft.world.item.enchantment.Enchantments#LOOTING}. */ public static final TagKey<Enchantment> INCREASE_ENTITY_DROPS = tag("increase_entity_drops"); /** * For enchantments that increase the damage dealt by an item. */ public static final TagKey<Enchantment> WEAPON_DAMAGE_ENHANCEMENTS = tag("weapon_damage_enhancements"); /** * For enchantments that increase movement speed for entity wearing armor enchanted with it. */ public static final TagKey<Enchantment> ENTITY_SPEED_ENHANCEMENTS = tag("entity_speed_enhancements"); /** * For enchantments that applies movement-based benefits unrelated to speed for the entity wearing armor enchanted with it. * Example: Reducing falling speeds ({@link net.minecraft.world.item.enchantment.Enchantments#FEATHER_FALLING}) or allowing walking on water ({@link net.minecraft.world.item.enchantment.Enchantments#FROST_WALKER}) */ public static final TagKey<Enchantment> ENTITY_AUXILIARY_MOVEMENT_ENHANCEMENTS = tag("entity_auxiliary_movement_enhancements"); /** * For enchantments that decrease damage taken or otherwise benefit, in regard to damage, the entity wearing armor enchanted with it. */ public static final TagKey<Enchantment> ENTITY_DEFENSE_ENHANCEMENTS = tag("entity_defense_enhancements"); private static TagKey<Enchantment> tag(String name) { return TagKey.create(Registries.ENCHANTMENT, ResourceLocation.fromNamespaceAndPath("c", name)); } } public static class Biomes { /** * For biomes that should not spawn monsters over time the normal way. * In other words, their Spawners and Spawn Cost entries have the monster category empty. * Example: Mushroom Biomes not having Zombies, Creepers, Skeleton, nor any other normal monsters. */ public static final TagKey<Biome> NO_DEFAULT_MONSTERS = tag("no_default_monsters"); /** * Biomes that should not be locatable/selectable by modded biome-locating items or abilities. */ public static final TagKey<Biome> HIDDEN_FROM_LOCATOR_SELECTION = tag("hidden_from_locator_selection"); public static final TagKey<Biome> IS_VOID = tag("is_void"); /** * Biomes that are above 0.8 temperature. (Excluding 0.8) */ public static final TagKey<Biome> IS_HOT = tag("is_hot"); public static final TagKey<Biome> IS_HOT_OVERWORLD = tag("is_hot/overworld"); public static final TagKey<Biome> IS_HOT_NETHER = tag("is_hot/nether"); public static final TagKey<Biome> IS_HOT_END = tag("is_hot/end"); /** * Biomes that are between 0.5 and 0.8 temperature range. (Including 0.5 and 0.8) */ public static final TagKey<Biome> IS_TEMPERATE = tag("is_temperate"); public static final TagKey<Biome> IS_TEMPERATE_OVERWORLD = tag("is_temperate/overworld"); public static final TagKey<Biome> IS_TEMPERATE_NETHER = tag("is_temperate/nether"); public static final TagKey<Biome> IS_TEMPERATE_END = tag("is_temperate/end"); /** * Biomes that are below 0.5 temperature. (Excluding 0.5) */ public static final TagKey<Biome> IS_COLD = tag("is_cold"); public static final TagKey<Biome> IS_COLD_OVERWORLD = tag("is_cold/overworld"); public static final TagKey<Biome> IS_COLD_NETHER = tag("is_cold/nether"); public static final TagKey<Biome> IS_COLD_END = tag("is_cold/end"); /** * If a biome has trees but spawn infrequently like a Savanna or Sparse Jungle, then the biome is considered having sparse vegetation. It does NOT mean no trees. */ public static final TagKey<Biome> IS_SPARSE_VEGETATION = tag("is_sparse_vegetation"); public static final TagKey<Biome> IS_SPARSE_VEGETATION_OVERWORLD = tag("is_sparse_vegetation/overworld"); public static final TagKey<Biome> IS_SPARSE_VEGETATION_NETHER = tag("is_sparse_vegetation/nether"); public static final TagKey<Biome> IS_SPARSE_VEGETATION_END = tag("is_sparse_vegetation/end"); /** * If a biome has more vegetation than a regular Forest biome, then it is considered having dense vegetation. * This is more subjective so simply do your best with classifying your biomes. */ public static final TagKey<Biome> IS_DENSE_VEGETATION = tag("is_dense_vegetation"); public static final TagKey<Biome> IS_DENSE_VEGETATION_OVERWORLD = tag("is_dense_vegetation/overworld"); public static final TagKey<Biome> IS_DENSE_VEGETATION_NETHER = tag("is_dense_vegetation/nether"); public static final TagKey<Biome> IS_DENSE_VEGETATION_END = tag("is_dense_vegetation/end"); public static final TagKey<Biome> IS_WET = tag("is_wet"); public static final TagKey<Biome> IS_WET_OVERWORLD = tag("is_wet/overworld"); public static final TagKey<Biome> IS_WET_NETHER = tag("is_wet/nether"); public static final TagKey<Biome> IS_WET_END = tag("is_wet/end"); public static final TagKey<Biome> IS_DRY = tag("is_dry"); public static final TagKey<Biome> IS_DRY_OVERWORLD = tag("is_dry/overworld"); public static final TagKey<Biome> IS_DRY_NETHER = tag("is_dry/nether"); public static final TagKey<Biome> IS_DRY_END = tag("is_dry/end"); /** * Biomes that spawn in the Overworld. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_OVERWORLD} * <p> * NOTE: If you do not add to the vanilla Overworld tag, be sure to add to * {@link net.minecraft.tags.BiomeTags#HAS_STRONGHOLD} so some Strongholds do not go missing.) */ public static final TagKey<Biome> IS_OVERWORLD = tag("is_overworld"); public static final TagKey<Biome> IS_CONIFEROUS_TREE = tag("is_tree/coniferous"); public static final TagKey<Biome> IS_SAVANNA_TREE = tag("is_tree/savanna"); public static final TagKey<Biome> IS_JUNGLE_TREE = tag("is_tree/jungle"); public static final TagKey<Biome> IS_DECIDUOUS_TREE = tag("is_tree/deciduous"); /** * Biomes that spawn as part of giant mountains. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_MOUNTAIN}) */ public static final TagKey<Biome> IS_MOUNTAIN = tag("is_mountain"); public static final TagKey<Biome> IS_MOUNTAIN_PEAK = tag("is_mountain/peak"); public static final TagKey<Biome> IS_MOUNTAIN_SLOPE = tag("is_mountain/slope"); /** * For temperate or warmer plains-like biomes. * For snowy plains-like biomes, see {@link #IS_SNOWY_PLAINS}. */ public static final TagKey<Biome> IS_PLAINS = tag("is_plains"); /** * For snowy plains-like biomes. * For warmer plains-like biomes, see {@link #IS_PLAINS}. */ public static final TagKey<Biome> IS_SNOWY_PLAINS = tag("is_snowy_plains"); /** * Biomes densely populated with deciduous trees. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_FOREST}) */ public static final TagKey<Biome> IS_FOREST = tag("is_forest"); public static final TagKey<Biome> IS_BIRCH_FOREST = tag("is_birch_forest"); public static final TagKey<Biome> IS_FLOWER_FOREST = tag("is_flower_forest"); /** * Biomes that spawn as a taiga. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_TAIGA}) */ public static final TagKey<Biome> IS_TAIGA = tag("is_taiga"); public static final TagKey<Biome> IS_OLD_GROWTH = tag("is_old_growth"); /** * Biomes that spawn as a hills biome. (Previously was called Extreme Hills biome in past) * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_HILL}) */ public static final TagKey<Biome> IS_HILL = tag("is_hill"); public static final TagKey<Biome> IS_WINDSWEPT = tag("is_windswept"); /** * Biomes that spawn as a jungle. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_JUNGLE}) */ public static final TagKey<Biome> IS_JUNGLE = tag("is_jungle"); /** * Biomes that spawn as a savanna. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_SAVANNA}) */ public static final TagKey<Biome> IS_SAVANNA = tag("is_savanna"); public static final TagKey<Biome> IS_SWAMP = tag("is_swamp"); public static final TagKey<Biome> IS_DESERT = tag("is_desert"); /** * Biomes that spawn as a badlands. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_BADLANDS}) */ public static final TagKey<Biome> IS_BADLANDS = tag("is_badlands"); /** * Biomes that are dedicated to spawning on the shoreline of a body of water. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_BEACH}) */ public static final TagKey<Biome> IS_BEACH = tag("is_beach"); public static final TagKey<Biome> IS_STONY_SHORES = tag("is_stony_shores"); public static final TagKey<Biome> IS_MUSHROOM = tag("is_mushroom"); /** * Biomes that spawn as a river. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_RIVER}) */ public static final TagKey<Biome> IS_RIVER = tag("is_river"); /** * Biomes that spawn as part of the world's oceans. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_OCEAN}) */ public static final TagKey<Biome> IS_OCEAN = tag("is_ocean"); /** * Biomes that spawn as part of the world's oceans that have low depth. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_DEEP_OCEAN}) */ public static final TagKey<Biome> IS_DEEP_OCEAN = tag("is_deep_ocean"); public static final TagKey<Biome> IS_SHALLOW_OCEAN = tag("is_shallow_ocean"); public static final TagKey<Biome> IS_UNDERGROUND = tag("is_underground"); public static final TagKey<Biome> IS_CAVE = tag("is_cave"); /** * Biomes whose flora primarily consists of vibrant thick vegetation and pools of water. Think of Lush Caves as an example. */ public static final TagKey<Biome> IS_LUSH = tag("is_lush"); /** * Biomes whose theme revolves around magic. Like a forest full of fairies or plants of magical abilities. */ public static final TagKey<Biome> IS_MAGICAL = tag("is_magical"); /** * Intended for biomes that spawns infrequently and can be difficult to find. */ public static final TagKey<Biome> IS_RARE = tag("is_rare"); /** * Biomes that spawn as a flat-topped hill often. */ public static final TagKey<Biome> IS_PLATEAU = tag("is_plateau"); /** * For biomes that are intended to be creepy or scary. For example, see Deep Dark biome or Dark Forest biome. */ public static final TagKey<Biome> IS_SPOOKY = tag("is_spooky"); /** * Biomes that lack any natural life or vegetation. * (Example, land destroyed and sterilized by nuclear weapons) */ public static final TagKey<Biome> IS_WASTELAND = tag("is_wasteland"); /** * Biomes whose flora primarily consists of dead or decaying vegetation. */ public static final TagKey<Biome> IS_DEAD = tag("is_dead"); /** * Biomes with a large amount of flowers. */ public static final TagKey<Biome> IS_FLORAL = tag("is_floral"); /** * Biomes that are able to spawn sand-based blocks on the surface. */ public static final TagKey<Biome> IS_SANDY = tag("is_sandy"); /** * For biomes that contains lots of naturally spawned snow. * For biomes where lot of ice is present, see {@link #IS_ICY}. * Biome with lots of both snow and ice may be in both tags. */ public static final TagKey<Biome> IS_SNOWY = tag("is_snowy"); /** * For land biomes where ice naturally spawns. * For biomes where snow alone spawns, see {@link #IS_SNOWY}. */ public static final TagKey<Biome> IS_ICY = tag("is_icy"); /** * Biomes consisting primarily of water. */ public static final TagKey<Biome> IS_AQUATIC = tag("is_aquatic"); /** * For water biomes where ice naturally spawns. * For biomes where snow alone spawns, see {@link #IS_SNOWY}. */ public static final TagKey<Biome> IS_AQUATIC_ICY = tag("is_aquatic_icy"); /** * Biomes that spawn in the Nether. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_NETHER}) */ public static final TagKey<Biome> IS_NETHER = tag("is_nether"); public static final TagKey<Biome> IS_NETHER_FOREST = tag("is_nether_forest"); /** * Biomes that spawn in the End. * (This is for people who want to tag their biomes without getting * side effects from {@link net.minecraft.tags.BiomeTags#IS_END}) */ public static final TagKey<Biome> IS_END = tag("is_end"); /** * Biomes that spawn as part of the large islands outside the center island in The End dimension. */ public static final TagKey<Biome> IS_OUTER_END_ISLAND = tag("is_outer_end_island"); /** * Old legacy tag that lost it's intended use case and is too unclear with regard to the current worldgen biome system today. * TODO: remove in 1.22 */ @Deprecated(forRemoval = true, since = "21.1") public static final TagKey<Biome> IS_MODIFIED = tag("is_modified"); private static TagKey<Biome> tag(String name) { return TagKey.create(Registries.BIOME, ResourceLocation.fromNamespaceAndPath("c", name)); } } public static class Structures { /** * Structures that should not show up on minimaps or world map views from mods/sites. * No effect on vanilla map items. */ public static final TagKey<Structure> HIDDEN_FROM_DISPLAYERS = tag("hidden_from_displayers"); /** * Structures that should not be locatable/selectable by modded structure-locating items or abilities. * No effect on vanilla map items. */ public static final TagKey<Structure> HIDDEN_FROM_LOCATOR_SELECTION = tag("hidden_from_locator_selection"); private static TagKey<Structure> tag(String name) { return TagKey.create(Registries.STRUCTURE, ResourceLocation.fromNamespaceAndPath("c", name)); } } public static class DamageTypes { /** * Damage types representing magic damage. */ public static final TagKey<DamageType> IS_MAGIC = neoforgeTag("is_magic"); /** * Damage types representing poison damage. */ public static final TagKey<DamageType> IS_POISON = neoforgeTag("is_poison"); /** * Damage types representing damage that can be attributed to withering or the wither. */ public static final TagKey<DamageType> IS_WITHER = neoforgeTag("is_wither"); /** * Damage types representing environmental damage, such as fire, lava, magma, cactus, lightning, etc. */ public static final TagKey<DamageType> IS_ENVIRONMENT = neoforgeTag("is_environment"); /** * Damage types representing physical damage.<br> * These are types that do not fit other #is_x tags (except #is_fall) * and would meet the general definition of physical damage. */ public static final TagKey<DamageType> IS_PHYSICAL = neoforgeTag("is_physical"); /** * Damage types representing damage from commands or other non-gameplay sources.<br> * Damage from these types should not be reduced, and bypasses invulnerability. */ public static final TagKey<DamageType> IS_TECHNICAL = neoforgeTag("is_technical"); /** * Damage types that will not cause the red flashing effect.<br> * This tag is empty by default. * * @see GameRenderer#bobHurt */ public static final TagKey<DamageType> NO_FLINCH = neoforgeTag("no_flinch"); private static TagKey<DamageType> neoforgeTag(String name) { return TagKey.create(Registries.DAMAGE_TYPE, ResourceLocation.fromNamespaceAndPath("neoforge", name)); } } /** * Use this to get a TagKey's translation key safely on any side. * * @return the translation key for a TagKey. */ public static String getTagTranslationKey(TagKey<?> tagKey) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("tag."); ResourceLocation registryIdentifier = tagKey.registry().location(); ResourceLocation tagIdentifier = tagKey.location(); stringBuilder.append(registryIdentifier.toShortLanguageKey().replace("/", ".")) .append(".") .append(tagIdentifier.getNamespace()) .append(".") .append(tagIdentifier.getPath().replace("/", ".")); return stringBuilder.toString(); } }
412
0.599734
1
0.599734
game-dev
MEDIA
0.999607
game-dev
0.763783
1
0.763783
BPzeBanshee/GMTunes
1,018
objects/obj_mouse_ctrl/Create_0.gml
// Inherit the parent event event_inherited(); held_x = -1; held_y = -1; hold_x = false; hold_y = false; note = 1; place_teleporter = false; tele_obj = []; if global.use_external_assets sprite_index = global.spr_ui.ctrl[note]; #region macros delete_teleporter_block = function(xx,yy,data) { var order = [0,1,2,3]; if data == 9 order = [2,3,0,1]; var ind = 0; for (var i=0; i<array_length(global.warp_list); i++) { if global.warp_list[i][order[0]] == xx && global.warp_list[i][order[1]] == yy ind = i; } var ox = global.warp_list[ind][order[2]]; var oy = global.warp_list[ind][order[3]]; global.ctrl_grid[ox][oy] = 0; (parent.field).update_surf_partial(ox,oy);//ctrl array_delete(global.warp_list,ind,1); trace(string("[{0},{1}]",xx,yy)+" removed from warp list\nUpdated warp list: "+string(global.warp_list)); } delete_flag = function(xx,yy) { for (var i=0;i<4;i++) { if xx == global.flag_list[i,0] && yy == global.flag_list[i,1] global.flag_list[i,2] = -1; } } #endregion
412
0.615626
1
0.615626
game-dev
MEDIA
0.634125
game-dev
0.862442
1
0.862442