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
Snaiel/Godot4ThirdPersonCombatPrototype
2,352
scripts/player/player_idle_state.gd
class_name PlayerIdleState extends PlayerStateMachine @export var walk_state: PlayerWalkState @export var dodge_state: PlayerDodgeState @export var jump_state: PlayerJumpState @export var attack_state: PlayerAttackState @export var block_state: PlayerBlockState @export var parry_state: PlayerParryState @export var backstab_state: PlayerBackstabState var _locked_on_turning_in_place: bool = false @onready var lock_on_system: LockOnSystem = Globals.lock_on_system func _ready(): super._ready() lock_on_system.lock_on.connect(_on_lock_on_system_lock_on) func enter() -> void: player.rotation_component.move_direction = Vector3.ZERO player.rotation_component.can_rotate = true func process_player() -> void: if Input.is_action_just_pressed("jump") and \ player.is_on_floor(): parent_state.change_state(jump_state) return if Input.is_action_just_pressed("run"): parent_state.change_state(dodge_state) return if Input.is_action_just_pressed("attack"): parent_state.change_state(attack_state) return if Input.is_action_just_pressed("block"): parent_state.change_state(parry_state) return if Input.is_action_pressed("block"): parent_state.change_state(block_state) return if Globals.backstab_system.backstab_victim: parent_state.change_state(backstab_state) return if player.input_direction.length() > 0: parent_state.change_state(walk_state) return player.set_rotation_target_to_lock_on_target() player.set_rotate_towards_target_if_lock_on_target() func process_movement_animations() -> void: var _animation_input_dir: Vector3 = player.input_direction if _locked_on_turning_in_place: _animation_input_dir = Vector3.FORWARD player.character.idle_animations.active = player.lock_on_target != null player.character.movement_animations.dir = _animation_input_dir func _on_lock_on_system_lock_on(target: LockOnComponent) -> void: if not target: return var rotation_difference: float = player\ .rotation_component\ .get_rotation_difference(target) if rotation_difference < 0.1: return _locked_on_turning_in_place = true var duration: float = clamp(rotation_difference / PI * 0.18, 0.1, 0.18) var pressed_lock_on_timer: SceneTreeTimer = get_tree()\ .create_timer(duration) pressed_lock_on_timer.timeout.connect( func(): _locked_on_turning_in_place = false )
412
0.888273
1
0.888273
game-dev
MEDIA
0.906847
game-dev
0.956955
1
0.956955
city41/ardynia
4,120
src/entity.cpp
#include "entity.h" #include "util.h" #include "tileRoom.h" #include "spriteBitmaps.h" #include "tileBitmaps.h" #include "state.h" #include "renderer.h" extern Renderer renderer; const uint8_t BOUNCE_AMOUNT = 16; const EntityType PROGMEM itemDropItems[] = { UNSET, HEART, BOMB }; void Entity::moveTowardsOtherEntity(Entity& other, uint8_t amount) { int16_t ox = other.x; int8_t oy = other.y; int16_t nx = x; int8_t ny = y; if (nx - ox > 0) { nx -= amount; mirror = 0; } else if (nx - ox < 0) { nx += amount; mirror = MIRROR_HORIZONTAL; } if (ny - oy > 0) { ny -= amount; } else if (ny - oy < 0) { ny += amount; } moveTo(nx, ny); } bool Entity::overlaps(Entity& other) { return !( other.x >= x + width || other.x + other.width <= x || other.y >= y + height || other.y + other.height <= y ); } void Entity::bounceBack(Entity& bounceAwayFromA, Entity& bounceAwayFromB) { int8_t acx = bounceAwayFromA.x + bounceAwayFromA.width / 2; int8_t acy = bounceAwayFromA.y + bounceAwayFromA.height / 2; int8_t bcx = bounceAwayFromB.x + bounceAwayFromB.width / 2; int8_t bcy = bounceAwayFromB.y + bounceAwayFromB.height / 2; int8_t diffX = acx - bcx; int8_t diffY = acy - bcy; int8_t bounceXAmount = 0; int8_t bounceYAmount = 0; if (abs(diffX) > abs(diffY)) { bounceXAmount = diffX > 0 ? BOUNCE_AMOUNT : -BOUNCE_AMOUNT; } else { bounceYAmount = diffY > 0 ? BOUNCE_AMOUNT : -BOUNCE_AMOUNT; } Direction curDir = dir; moveTo(Util::clamp(x + bounceXAmount, 0, WIDTH - 17 - width), Util::clamp(y + bounceYAmount, 0, HEIGHT - height - 1)); dir = curDir; } void Entity::rotateViaMirror(uint8_t frame) { MirrorMode newMirror = 0; if (frame > 49) { newMirror = MIRROR_HORIZONTAL | MIRROR_VERTICAL; } else if (frame > 39) { newMirror = MIRROR_HORIZONTAL; } else if (frame > 29) { newMirror = 0; } else if (frame > 19) { newMirror = MIRROR_HORIZONTAL | MIRROR_VERTICAL; } else if (frame > 9) { newMirror = MIRROR_HORIZONTAL; } mirror = newMirror; } void Entity::render(uint8_t renderFrame) { DrawMode drawMode = State::isInDungeon() ? (type == BAT ? Xor : Invert) : Normal; if (deathCount) { deathCount -= 1; renderer.drawPlusMask(x, y, deathPoof_plus_mask, 0, renderFrame & 1, drawMode); } if (type == UNSET) { return; } if (tookDamageCount > 0) { tookDamageCount -= 1; if (tookDamageCount % 3 == 1) { return; } } if (needsMask) { bool isNemesis = type == NEMESIS; int16_t offsetX = isNemesis ? -4 : 0; int8_t offsetY = isNemesis ? -8 : 0; renderer.drawPlusMask(x + offsetX, y + offsetY, tiles, currentFrame, mirror, drawMode); } else { renderer.drawOverwrite(x, y, tiles, currentFrame, mirror, drawMode); } #ifdef DRAW_HITBOXES renderer.drawRect(x, y, width, height, BLACK); #endif } EntityType Entity::update(Entity& player, uint8_t frame) { if (type == UNSET) { return UNSET; } if (stunCount > 0) { stunCount -= 1; return UNSET; } if (updatePtr != NULL) { return updatePtr(this, player, frame); } return UNSET; } EntityType Entity::onCollide(Entity& other, Entity& player) { if (type == UNSET) { return UNSET; } if (collideOtherEntityPtr != NULL) { EntityType result = collideOtherEntityPtr(this, other, player); if (type == UNSET) { deathCount = 10; } if (result == ITEM_DROP) { // in boss room, always drop something const uint8_t maxRoll = State::gameState.numAcquiredItems > 1 ? 3 : 2; uint8_t diceRoll = random(0, maxRoll); return pgm_read_byte(itemDropItems + diceRoll); } else { return result; } } return UNSET; }
412
0.968241
1
0.968241
game-dev
MEDIA
0.645145
game-dev,graphics-rendering
0.997277
1
0.997277
Arisotura/SM64DSe
2,479
ASMPatchTemplate/v2/source/L_BlockyBlockLand/BBL_Plank.cpp
#include "BBL_Plank.h" #include "BlockyBlockSpecifics.h" namespace { FixedSizeCLPS_Block<1> clpsBlock = { {'C', 'L', 'P', 'S'}, 8, 1, { CLPS(0x00, 0, 0x3f, 0x0, 0x0, 0x00, 0, 0, 0, 0xff) } }; constexpr Fix12i PIVOT_DIST = 0x00c37000_f; } SharedFilePtr BBL_Plank::modelFile; SharedFilePtr BBL_Plank::clsnFile; SpawnInfo<BBL_Plank> BBL_Plank::spawnData = { &BBL_Plank::Spawn, 0x0032, 0x00cd, 0x00000002, 0x00030000_f, 0x00180000_f, 0x08000000_f, 0x08000000_f, }; void BBL_Plank::UpdateModelTransform() { model.mat4x3.ThisFromRotationXYZExt(0, ang.y, ang.z); model.mat4x3.r0c3 = pos.x >> 3; model.mat4x3.r1c3 = pos.y >> 3; model.mat4x3.r2c3 = pos.z >> 3; } void BBL_Plank::UpdateClsnTransform() { clsnNextMat = model.mat4x3; clsnNextMat.r0c3 = pos.x; clsnNextMat.r1c3 = pos.y; clsnNextMat.r2c3 = pos.z; clsn.Transform(clsnNextMat, ang.y); } BBL_Plank* BBL_Plank::Spawn() { return new BBL_Plank; } int BBL_Plank::InitResources() { char* modelF = Model::LoadFile(modelFile); model.SetFile(modelF, 1, -1); UpdateModelTransform(); UpdateClsnTransform(); char* clsnF = MovingMeshCollider::LoadFile(clsnFile); clsn.SetFile(clsnF, clsnNextMat, 0x199_f, ang.y, clpsBlock); clsn.beforeClsnCallback = (decltype(clsn.beforeClsnCallback))0x02039348; moveState = 0; offsetY = 0_f; maxOffsetY = 0x3c0000_f; drawDistAsr3 = 0x1000000_f; //remember, Q23.9, also treat this like part of the level's main mesh rangeAsr3 = 0x400000_f; //remember, Q23.9 rangeOffsetY = 0x5a0000_f; return 1; } int BBL_Plank::CleanupResources() { if(clsn.IsEnabled()) clsn.Disable(); clsnFile.Release(); modelFile.Release(); return 1; } //0219007c is the experimental one //0211d028 is the vtable int BBL_Plank::Behavior() { if(moveState == 0 && towerStartedMoving) { moveState = 1; } if(moveState == 1) { offsetY += 0xc000_f; if(offsetY >= maxOffsetY) { offsetY = maxOffsetY; moveState = 2; } ang.z = -Atan2(offsetY, PIVOT_DIST); UpdateModelTransform(); if(IsClsnInRange(0_f, 0_f)) { UpdateClsnTransform(); } //*(int*)((char*)this + 0x38c) = Sound_Play2(*(int*)((char*)this + 0x38c), 3, 0x82, &camSpacePos, 0); } else if(moveState == 2) { IsClsnInRange(0_f, 0_f); UpdateClsnTransform(); moveState = 3; } else { IsClsnInRange(0_f, 0_f); //remember, this has side effects! } return 1; } int BBL_Plank::Render() { model.Render(nullptr); return 1; } BBL_Plank::~BBL_Plank() {}
412
0.883146
1
0.883146
game-dev
MEDIA
0.444525
game-dev
0.939898
1
0.939898
ihmcrobotics/ihmc-open-robotics-software
10,075
ihmc-manipulation-planning/src/main/java/us/ihmc/manipulation/planning/walkingpath/footstep/SkeletonPathFootStepPlanner.java
package us.ihmc.manipulation.planning.walkingpath.footstep; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.util.ArrayList; import us.ihmc.commons.PrintTools; import us.ihmc.robotics.robotSide.RobotSide; public class SkeletonPathFootStepPlanner { // footstep info public ArrayList<SkeletonPathFootStep> footSteps = new ArrayList<SkeletonPathFootStep>(); // path info public SkeletonPath skeletonPathSegments; public SkeletonPath pathSegmentsRightSide; public SkeletonPath pathSegmentsLeftSide; // L, w, d private double stepLength; private double stepWidth; private double stepStride; public Point2D tempPoint; public SkeletonPathFootStepPlanner(double[] skeletonPathX, double[] skeletonPathY, double stepLength, double stepWidth) { PrintTools.info("Number of path node is " + skeletonPathX.length); this.stepLength = stepLength; this.stepWidth = stepWidth; this.stepStride = Math.sqrt(this.stepLength * this.stepLength + this.stepWidth * this.stepWidth); this.skeletonPathSegments = new SkeletonPath(skeletonPathX, skeletonPathY); this.pathSegmentsRightSide = new SkeletonPath(-this.stepWidth / 2, this.skeletonPathSegments); this.pathSegmentsLeftSide = new SkeletonPath(this.stepWidth / 2, this.skeletonPathSegments); PrintTools.info("final " + skeletonPathSegments.getFinalPoint().getX() + " " + skeletonPathSegments.getFinalPoint().getY()); // for(int i =0;i<skeletonPathSegments.get().size();i++) // { // PrintTools.info(""+i+" seg "+skeletonPathSegments.get().get(i).getX1()+" "+skeletonPathSegments.get().get(i).getY1()+" "+ skeletonPathSegments.get().get(i).getX2()+" "+skeletonPathSegments.get().get(i).getY2()); // } } public void setZeroStep(RobotSide robotSide) { Point2D footStepLocation = new Point2D.Double(); if (robotSide == RobotSide.RIGHT) { footStepLocation.setLocation(0.0, -stepWidth / 2); SkeletonPathFootStep footStep = new SkeletonPathFootStep(RobotSide.RIGHT, footStepLocation, pathSegmentsRightSide.getYawAngleOfSegment(0)); footStep.setIndexOfSegment(0); footSteps.add(footStep); } else { footStepLocation.setLocation(0.0, stepWidth / 2); SkeletonPathFootStep footStep = new SkeletonPathFootStep(RobotSide.LEFT, footStepLocation, pathSegmentsLeftSide.getYawAngleOfSegment(0)); footStep.setIndexOfSegment(0); footSteps.add(footStep); } } public void createFootSteps() { for (int i = 0; i < 100; i++) { addNextStep(); if (footSteps.get(footSteps.size() - 1).getLocation().distance(skeletonPathSegments.getFinalPoint()) < stepWidth / 2 + 0.0001) { PrintTools.info("" + i + " " + footSteps.get(footSteps.size() - 1).getLocation().distance(skeletonPathSegments.getFinalPoint())); addNextStep(); PrintTools.info("numberof steps " + footSteps.size()); break; } } } private void addNextStep() { SkeletonPathFootStep newFootStep = new SkeletonPathFootStep(); SkeletonPathFootStep curFootStep = footSteps.get(footSteps.size() - 1); newFootStep = getNextStep(curFootStep); footSteps.add(newFootStep); } public SkeletonPathFootStep getNextStep(SkeletonPathFootStep curStep) { SkeletonPathFootStep newFootStep = new SkeletonPathFootStep(); if (curStep.getRobotSide() == RobotSide.RIGHT) { newFootStep = getNextLeftStep(curStep); } else { newFootStep = getNextRightStep(curStep); } return newFootStep; } public SkeletonPathFootStep getNextRightStep(SkeletonPathFootStep curStep) { SkeletonPathFootStep ret = new SkeletonPathFootStep(); int indexOfCurSegment = curStep.getIndexOfSegment(); Line2D curSegment = skeletonPathSegments.getSegment(indexOfCurSegment); double curMatric; double maxMatric = 0.0; int numberOfCandidates = 20; for (int i = 0; i < numberOfCandidates; i++) { double minSearching = Math.PI * (-0.9); double maxSearching = Math.PI * (-0.0); double angleOfCandidate = minSearching + i * (maxSearching - minSearching) / (numberOfCandidates - 1); Point2D aCandidate = getACandidate(curStep, this.stepStride, angleOfCandidate); SkeletonPathFootStep aProjectedCandidate = getProjectedFootStep(RobotSide.RIGHT, aCandidate); if (isValidStep(RobotSide.RIGHT, aProjectedCandidate.getLocation(), curSegment)) { if (aProjectedCandidate.getLocation().distance(curStep.getLocation()) < stepStride) { curMatric = getXMatric(aProjectedCandidate.getLocation(), curSegment); // PrintTools.info(""+i+" "+angleOfCandidate*180/Math.PI+" matric "+ curMatric); if (curMatric > maxMatric) { maxMatric = curMatric; ret = aProjectedCandidate; } } } } // PrintTools.info("!!! "+ret.getLocation().getX()+" "+ret.getLocation().getY()); tempPoint = new Point2D.Double(ret.getLocation().getX(), ret.getLocation().getY()); return ret; } public SkeletonPathFootStep getNextLeftStep(SkeletonPathFootStep curStep) { SkeletonPathFootStep ret = new SkeletonPathFootStep(); int indexOfCurSegment = curStep.getIndexOfSegment(); Line2D curSegment = skeletonPathSegments.getSegment(indexOfCurSegment); double curMatric; double maxMatric = 0.0; int numberOfCandidates = 20; for (int i = 0; i < numberOfCandidates; i++) { double minSearching = Math.PI * (0.0); double maxSearching = Math.PI * (0.9); double angleOfCandidate = minSearching + i * (maxSearching - minSearching) / (numberOfCandidates - 1); Point2D aCandidate = getACandidate(curStep, this.stepStride, angleOfCandidate); SkeletonPathFootStep aProjectedCandidate = getProjectedFootStep(RobotSide.LEFT, aCandidate); if (isValidStep(RobotSide.LEFT, aProjectedCandidate.getLocation(), curSegment)) { if (aProjectedCandidate.getLocation().distance(curStep.getLocation()) < stepStride) { curMatric = getXMatric(aProjectedCandidate.getLocation(), curSegment); //PrintTools.info(""+i+" "+angleOfCandidate*180/Math.PI+" matric "+ curMatric); if (curMatric > maxMatric) { maxMatric = curMatric; ret = aProjectedCandidate; } } } } //PrintTools.info("!!! "+ret.getLocation().getX()+" "+ret.getLocation().getY()); tempPoint = new Point2D.Double(ret.getLocation().getX(), ret.getLocation().getY()); return ret; } public SkeletonPathFootStep getProjectedFootStep(RobotSide robotSide, Point2D aPoint) { SkeletonPathFootStep retFootStep = new SkeletonPathFootStep(); SkeletonPath segments; if (robotSide == RobotSide.RIGHT) { segments = pathSegmentsRightSide; } else { segments = pathSegmentsLeftSide; } int indexOfClosestSegment = segments.getIndexOfClosestSegment(aPoint); Point2D locationOfProjectedFootStep = segments.getLocationOfClosestPointOnSegment(aPoint); double yawAngleOfProjectedFootStep = segments.getYawAngleOfClosestPointOnSegment(aPoint); retFootStep.setRobotSide(robotSide); retFootStep.setLocation(locationOfProjectedFootStep); retFootStep.setYawAngle(yawAngleOfProjectedFootStep); retFootStep.setIndexOfSegment(indexOfClosestSegment); return retFootStep; } public Point2D getACandidate(SkeletonPathFootStep curStep, double radius, double rotationAngle) { Point2D ret = new Point2D.Double(); Point2D curLocation = curStep.getLocation(); double finalAngle = curStep.getYawAngle() + rotationAngle; ret.setLocation(curLocation.getX() + radius * Math.cos(finalAngle), curLocation.getY() + radius * Math.sin(finalAngle)); return ret; } private boolean isValidStep(RobotSide robotSideOfStep, Point2D aPoint, Line2D curSegment) { if (robotSideOfStep == RobotSide.LEFT) { if (getYMatric(aPoint, curSegment) < 0) { return false; } else { return true; } } else { if (getYMatric(aPoint, curSegment) >= 0) { return false; } else { return true; } } } public double getXMatric(Point2D aPoint, Line2D curSegment) { Point2D aVector = new Point2D.Double(aPoint.getX() - curSegment.getX1(), aPoint.getY() - curSegment.getY1()); Point2D refVector = new Point2D.Double((curSegment.getX2() - curSegment.getX1()), curSegment.getY2() - curSegment.getY1()); double norm = Math.sqrt(refVector.getX() * refVector.getX() + refVector.getY() * refVector.getY()); Point2D refVectorNorm = new Point2D.Double(refVector.getX() / norm, refVector.getY() / norm); return aVector.getX() * refVectorNorm.getX() + aVector.getY() * refVectorNorm.getY(); } public double getYMatric(Point2D aPoint, Line2D curSegment) { Point2D aVector = new Point2D.Double(aPoint.getX() - curSegment.getX1(), aPoint.getY() - curSegment.getY1()); Point2D refVector = new Point2D.Double(-(curSegment.getY2() - curSegment.getY1()), curSegment.getX2() - curSegment.getX1()); double norm = Math.sqrt(refVector.getX() * refVector.getX() + refVector.getY() * refVector.getY()); Point2D refVectorNorm = new Point2D.Double(refVector.getX() / norm, refVector.getY() / norm); return aVector.getX() * refVectorNorm.getX() + aVector.getY() * refVectorNorm.getY(); } }
412
0.841012
1
0.841012
game-dev
MEDIA
0.841457
game-dev
0.879666
1
0.879666
DruidMech/GameplayAbilitySystem_Aura
3,764
Plugins/Developer/RiderLink/Source/RiderLink/Public/Model/Library/UE4Library/IScriptMsg.Generated.h
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a RdGen v1.11. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #ifndef ISCRIPTMSG_GENERATED_H #define ISCRIPTMSG_GENERATED_H #include "protocol/Protocol.h" #include "types/DateTime.h" #include "impl/RdSignal.h" #include "impl/RdProperty.h" #include "impl/RdList.h" #include "impl/RdSet.h" #include "impl/RdMap.h" #include "base/ISerializersOwner.h" #include "base/IUnknownInstance.h" #include "serialization/ISerializable.h" #include "serialization/Polymorphic.h" #include "serialization/NullableSerializer.h" #include "serialization/ArraySerializer.h" #include "serialization/InternedSerializer.h" #include "serialization/SerializationCtx.h" #include "serialization/Serializers.h" #include "ext/RdExtBase.h" #include "task/RdCall.h" #include "task/RdEndpoint.h" #include "task/RdSymmetricCall.h" #include "std/to_string.h" #include "std/hash.h" #include "std/allocator.h" #include "util/enum.h" #include "util/gen_util.h" #include <cstring> #include <cstdint> #include <vector> #include <ctime> #include "thirdparty.hpp" #include "instantiations_UE4Library.h" #include "UE4TypesMarshallers.h" #include "Runtime/Core/Public/Containers/Array.h" #include "Runtime/Core/Public/Containers/ContainerAllocationPolicies.h" #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable:4250 ) #pragma warning( disable:4307 ) #pragma warning( disable:4267 ) #pragma warning( disable:4244 ) #pragma warning( disable:4100 ) #endif /// <summary> /// <p>Generated from: UE4Library.kt:175</p> /// </summary> namespace JetBrains { namespace EditorPlugin { // abstract class RIDERLINK_API IScriptMsg : public rd::IPolymorphicSerializable { private: // custom serializers public: // constants static constexpr rd::wstring_view header{L"Script msg:", 11}; protected: // fields private: // initializer void initialize(); public: // default ctors and dtors IScriptMsg(); IScriptMsg(IScriptMsg const &) = default; IScriptMsg& operator=(IScriptMsg const &) = default; IScriptMsg(IScriptMsg &&) = default; IScriptMsg& operator=(IScriptMsg &&) = default; virtual ~IScriptMsg() = default; // reader static rd::Wrapper<IScriptMsg> readUnknownInstance(rd::SerializationCtx& ctx, rd::Buffer & buffer, rd::RdId const& unknownId, int32_t size); // writer virtual void write(rd::SerializationCtx& ctx, rd::Buffer& buffer) const override = 0; // virtual init // identify // getters // intern private: // equals trait public: // equality operators friend bool operator==(const IScriptMsg &lhs, const IScriptMsg &rhs); friend bool operator!=(const IScriptMsg &lhs, const IScriptMsg &rhs); // hash code trait virtual size_t hashCode() const noexcept override = 0; // type name trait std::string type_name() const override; // static type name trait static std::string static_type_name(); private: // polymorphic to string std::string toString() const override; public: // external to string friend std::string to_string(const IScriptMsg & value); }; } } // hash code trait namespace rd { template <> struct hash<JetBrains::EditorPlugin::IScriptMsg> { size_t operator()(const JetBrains::EditorPlugin::IScriptMsg & value) const noexcept { return value.hashCode(); } }; } #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // ISCRIPTMSG_GENERATED_H
412
0.809458
1
0.809458
game-dev
MEDIA
0.615419
game-dev
0.729125
1
0.729125
PCGen/pcgen
1,197
data/3e/dragonwing_games/bastion_press/efaeries_web/efaeries_classes.lst
# CVS $Revision$ $Author$ -- Mon Sep 15 21:55:54 2014 -- reformated by prettylst.pl v1.51 (build 25129) SOURCELONG:eFaeries SOURCESHORT:eFaeries SOURCEWEB:http://dragonwing.net/Faeries.htm SOURCEDATE:2003-01 #Original Entry: Andrew Maitland # Class Name Hit Dice Type Max Level Source Page Combat bonus Number of Feats Save bonus CLASS:The Master of the Hunt HD:10 TYPE:Monster MAXLEVEL:15 SOURCEPAGE:p.10 BONUS:COMBAT|BASEAB|classlevel("APPLIEDAS=NONEPIC")|TYPE=Base.REPLACE BONUS:FEAT|POOL|4 BONUS:SAVE|BASE.Will,BASE.Reflex|6 BONUS:SAVE|BASE.Fortitude|13 # Class Name Required Race CLASS:The Master of the Hunt PRERACE:1,RACETYPE=Fey # Class Name Skill Pts/Lvl Add INT to Skill Points? Class Skill CLASS:The Master of the Hunt STARTSKILLPTS:6 MODTOSKILLS:YES CSKILL:Climb|TYPE=Craft|Handle Animal|Hide|Intimidate|Intuit Direction|Jump|Knowledge (Nature)|Listen|Move Silently|Profession (Hunter/Tracker)|Spot|Tumble|Use Rope|Wilderness Lore 1 BONUS:CASTERLEVEL|Ranger|19 BONUS:PCLEVEL|Ranger|20 ADD:SPELLCASTER|Ranger ABILITY:Special Ability|AUTOMATIC|All Martial Weapon Proficiencies ABILITY:FEAT|AUTOMATIC|Armor Proficiency (Light)|Simple Weapon Proficiency # # End #
412
0.697348
1
0.697348
game-dev
MEDIA
0.980008
game-dev
0.8977
1
0.8977
danielkrupinski/GOESP
11,911
GOESP/imgui/imgui_impl_sdl.cpp
// dear imgui: Platform Binding for SDL2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // (Requires: SDL 2.0. Prefer SDL 2.0.4+ for full feature support.) // Implemented features: // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Clipboard support. // [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE). // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // Missing features: // [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends. // 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2). // 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state). // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application). // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'. // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls. // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. // 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples. // 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter. // 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText). // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. // 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. // 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS). // 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. #include "imgui.h" #include "imgui_impl_sdl.h" // SDL #include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> #if defined(__APPLE__) #include "TargetConditionals.h" #endif #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE SDL_VERSION_ATLEAST(2,0,4) #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) // Data static SDL_Window* g_Window = NULL; static Uint64 g_Time = 0; static bool g_MousePressed[3] = { false, false, false }; static char* g_ClipboardTextData = NULL; static const char* ImGui_ImplSDL2_GetClipboardText(void*) { if (g_ClipboardTextData) SDL_free(g_ClipboardTextData); g_ClipboardTextData = SDL_GetClipboardText(); return g_ClipboardTextData; } static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text) { SDL_SetClipboardText(text); } // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. // If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) { ImGuiIO& io = ImGui::GetIO(); switch (event->type) { case SDL_MOUSEWHEEL: { if (event->wheel.x > 0) io.MouseWheelH += 1; if (event->wheel.x < 0) io.MouseWheelH -= 1; if (event->wheel.y > 0) io.MouseWheel += 1; if (event->wheel.y < 0) io.MouseWheel -= 1; return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true; if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true; if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true; return true; } case SDL_TEXTINPUT: { io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_KEYDOWN: case SDL_KEYUP: { int key = event->key.keysym.scancode; IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown)); io.KeysDown[key] = (event->type == SDL_KEYDOWN); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); #ifdef _WIN32 io.KeySuper = false; #else io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0); #endif return true; } case SDL_MOUSEMOTION: return true; } return false; } static bool ImGui_ImplSDL2_Init(SDL_Window* window) { g_Window = window; // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) io.BackendPlatformName = "imgui_impl_sdl"; // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array. io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT; io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE; io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE; io.KeyMap[ImGuiKey_KeyPadEnter] = SDL_SCANCODE_KP_ENTER; io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A; io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C; io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V; io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X; io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y; io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z; io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; io.ClipboardUserData = NULL; return true; } bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) { (void)sdl_gl_context; // Viewport branch will need this. return ImGui_ImplSDL2_Init(window); } bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) { #if !SDL_HAS_VULKAN IM_ASSERT(0 && "Unsupported"); #endif return ImGui_ImplSDL2_Init(window); } bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) { #if !defined(_WIN32) IM_ASSERT(0 && "Unsupported"); #endif return ImGui_ImplSDL2_Init(window); } bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window) { return ImGui_ImplSDL2_Init(window); } void ImGui_ImplSDL2_Shutdown() { g_Window = NULL; // Destroy last known clipboard data if (g_ClipboardTextData) SDL_free(g_ClipboardTextData); g_ClipboardTextData = NULL; } static void ImGui_ImplSDL2_UpdateMousePosAndButtons() { ImGuiIO& io = ImGui::GetIO(); // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) if (io.WantSetMousePos) SDL_WarpMouseInWindow(g_Window, (int)io.MousePos.x, (int)io.MousePos.y); else io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); int mx, my; Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my); io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; if (SDL_GetWindowFlags(g_Window) & SDL_WINDOW_INPUT_FOCUS) io.MousePos = ImVec2((float)mx, (float)my); } void ImGui_ImplSDL2_NewFrame(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) int w, h; SDL_GetWindowSize(window, &w, &h); if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) w = h = 0; io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) { int display_w, display_h; SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); } // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f); g_Time = current_time; ImGui_ImplSDL2_UpdateMousePosAndButtons(); }
412
0.837415
1
0.837415
game-dev
MEDIA
0.654529
game-dev
0.809223
1
0.809223
P3pp3rF1y/AncientWarfare2
12,279
src/main/java/net/shadowmage/ancientwarfare/structure/gui/GuiSpawnerAdvanced.java
package net.shadowmage.ancientwarfare.structure.gui; import net.minecraft.client.Minecraft; import net.shadowmage.ancientwarfare.core.container.ContainerBase; import net.shadowmage.ancientwarfare.core.gui.GuiContainerBase; import net.shadowmage.ancientwarfare.core.gui.elements.Button; import net.shadowmage.ancientwarfare.core.gui.elements.Checkbox; import net.shadowmage.ancientwarfare.core.gui.elements.CompositeScrolled; import net.shadowmage.ancientwarfare.core.gui.elements.Label; import net.shadowmage.ancientwarfare.core.gui.elements.NumberInput; import net.shadowmage.ancientwarfare.structure.container.ContainerSpawnerAdvancedBase; import net.shadowmage.ancientwarfare.structure.tile.SpawnerSettings.EntitySpawnGroup; import net.shadowmage.ancientwarfare.structure.tile.SpawnerSettings.EntitySpawnSettings; import java.util.HashMap; import java.util.List; public class GuiSpawnerAdvanced extends GuiContainerBase<ContainerSpawnerAdvancedBase> { private CompositeScrolled area; private HashMap<NumberInput, EntitySpawnGroup> groupMapByInput = new HashMap<>(); private HashMap<Button, EntitySpawnGroup> groupMapByButton = new HashMap<>(); private HashMap<NumberInput, EntitySpawnSettings> settingsMapByInput = new HashMap<>(); private HashMap<Button, EntitySpawnSettings> settingsMapByButton = new HashMap<>(); public GuiSpawnerAdvanced(ContainerBase par1Container) { super(par1Container); } @Override protected boolean onGuiCloseRequested() { getContainer().sendSettingsToServer(); return true; } @Override public void initElements() { area = new CompositeScrolled(this, 0, 40, 256, 200); addGuiElement(area); Button done = new Button(256 - 8 - 55, 8, 55, 12, "guistrings.done") { @Override protected void onPressed() { closeGui(); } }; addGuiElement(done); Label label = new Label(8, 8, "guistrings.spawner.set_spawn_settings"); addGuiElement(label); } @Override public void setupElements() { area.clearElements(); groupMapByButton.clear(); groupMapByInput.clear(); settingsMapByButton.clear(); settingsMapByInput.clear(); int totalHeight = 3; Checkbox box = new Checkbox(8, totalHeight, 16, 16, "guistrings.spawner.light_sensitive") { @Override public void onToggled() { getContainer().settings.toggleLightSensitive(); } }; box.setChecked(getContainer().settings.isLightSensitive()); area.addGuiElement(box); totalHeight += 16; box = new Checkbox(8, totalHeight, 16, 16, "guistrings.spawner.redstone_sensitive") { @Override public void onToggled() { getContainer().settings.toggleRespondToRedstone(); } }; box.setChecked(getContainer().settings.isRespondToRedstone()); area.addGuiElement(box); totalHeight += 16; box = new Checkbox(8, totalHeight, 16, 16, "guistrings.spawner.redstone_mode") { @Override public void onToggled() { getContainer().settings.toggleRedstoneMode(); } }; box.setChecked(getContainer().settings.getRedstoneMode()); area.addGuiElement(box); totalHeight += 16; box = new Checkbox(8, totalHeight, 16, 16, "guistrings.spawner.transparent") { @Override public void onToggled() { getContainer().settings.toggleTransparent(); } }; box.setChecked(getContainer().settings.isTransparent()); area.addGuiElement(box); totalHeight += 16; box = new Checkbox(8, totalHeight, 16, 16, "guistrings.spawner.debug_mode") { @Override public void onToggled() { getContainer().settings.toggleDebugMode(); } }; box.setChecked(getContainer().settings.isDebugMode()); area.addGuiElement(box); totalHeight += 20; Label label = new Label(8, totalHeight, "guistrings.required_player_range"); area.addGuiElement(label); NumberInput input = new NumberInput(180, totalHeight, 50, getContainer().settings.getPlayerRange(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setPlayerRange((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.max_nearby_entities"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getMaxNearbyMonsters(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setMaxNearbyMonsters((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.mob_range"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getMobRange(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setMobRange((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.spawn_range"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getSpawnRange(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setSpawnRange((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.delay"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getSpawnDelay(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setSpawnDelay((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.min_spawn_delay"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getMinDelay(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setMinDelay((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.max_spawn_delay"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getMaxDelay(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setMaxDelay((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.xp_to_drop"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getXpToDrop(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setXpToDrop((int) value); } }; input.setIntegerValue(); area.addGuiElement(input); totalHeight += 12; label = new Label(8, totalHeight, "guistrings.spawner.block_hardness"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getBlockHardness(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setBlockHardness(value); } }; input.setAllowNegative(); area.addGuiElement(input); totalHeight += 16; label = new Label(8, totalHeight, "guistrings.spawner.spawn_y_offest"); area.addGuiElement(label); input = new NumberInput(180, totalHeight, 50, getContainer().settings.getSpawnYOffset(), this) { @Override public void onValueUpdated(float value) { getContainer().settings.setSpawnYOffset((int) value); } }; input.setIntegerValue(); input.setAllowNegative(); area.addGuiElement(input); totalHeight += 16; label = new Label(8, totalHeight, "guistrings.spawner.spawn_groups"); area.addGuiElement(label); totalHeight += 12; List<EntitySpawnGroup> spawnGroups = getContainer().settings.getSpawnGroups(); List<EntitySpawnSettings> entitySettings; Button button; for (EntitySpawnGroup group : spawnGroups) { button = new Button(256 - 16 - 95, totalHeight, 95, 12, "guistrings.spawner.remove_group") { @Override protected void onPressed() { EntitySpawnGroup g = groupMapByButton.get(this); getContainer().settings.getSpawnGroups().remove(g); groupMapByButton.remove(this); refreshGui(); } }; groupMapByButton.put(button, group); area.addGuiElement(button); label = new Label(8, totalHeight, "guistrings.spawner.group_weight"); area.addGuiElement(label); input = new NumberInput(100, totalHeight, 30, group.getWeight(), this) { @Override public void onValueUpdated(float value) { EntitySpawnGroup g = groupMapByInput.get(this); if (g != null) { g.setWeight((int) value); } } }; input.setIntegerValue(); groupMapByInput.put(input, group); area.addGuiElement(input); totalHeight += 14; label = new Label(8, totalHeight, "guistrings.spawner.entity_list"); area.addGuiElement(label); label = new Label(130, totalHeight, "guistrings.spawner.min"); area.addGuiElement(label); label = new Label(160, totalHeight, "guistrings.spawner.max"); area.addGuiElement(label); label = new Label(190, totalHeight, "guistrings.spawner.total"); area.addGuiElement(label); totalHeight += 12; entitySettings = group.getEntitiesToSpawn(); for (EntitySpawnSettings settings : entitySettings) { if (settings == null) { continue; } button = new Button(30, totalHeight, 100, 12, settings.getEntityName()) { @Override protected void onPressed() { EntitySpawnSettings set = settingsMapByButton.get(this); Minecraft.getMinecraft().displayGuiScreen(new GuiSpawnerAdvancedAddEntity(GuiSpawnerAdvanced.this, groupMapByButton.get(this), set)); } }; groupMapByButton.put(button, group); settingsMapByButton.put(button, settings); area.addGuiElement(button); input = new NumberInput(130, totalHeight, 30, settings.getSpawnMin(), this) { @Override public void onValueUpdated(float value) { settingsMapByInput.get(this).setSpawnCountMin((int) value); } }; settingsMapByInput.put(input, settings); area.addGuiElement(input); input.setIntegerValue();//for some reason, I have to set this _after_ adding to the setting map, or it NPEs on retrieval...a very large WTF input = new NumberInput(160, totalHeight, 30, settings.getSpawnMax(), this) { @Override public void onValueUpdated(float value) { settingsMapByInput.get(this).setSpawnCountMax((int) value); } }; settingsMapByInput.put(input, settings); area.addGuiElement(input); input.setIntegerValue(); input = new NumberInput(190, totalHeight, 30, settings.getSpawnTotal(), this) { @Override public void onValueUpdated(float value) { settingsMapByInput.get(this).setSpawnLimitTotal((int) value); } }; settingsMapByInput.put(input, settings); area.addGuiElement(input); input.setIntegerValue(); input.setAllowNegative(); button = new Button(220, totalHeight, 12, 12, "guistrings.spawner.remove") { @Override protected void onPressed() { EntitySpawnSettings set = settingsMapByButton.get(this); EntitySpawnGroup g = groupMapByButton.get(this); g.getEntitiesToSpawn().remove(set); refreshGui(); } }; settingsMapByButton.put(button, settings); groupMapByButton.put(button, group); area.addGuiElement(button); totalHeight += 12; } button = new Button(30, totalHeight, 120, 12, "guistrings.spawner.add_entity") { @Override protected void onPressed() { EntitySpawnGroup g = groupMapByButton.get(this); Minecraft.getMinecraft().displayGuiScreen(new GuiSpawnerAdvancedAddEntity(GuiSpawnerAdvanced.this, g, null)); } }; area.addGuiElement(button); groupMapByButton.put(button, group); totalHeight += 14; } totalHeight += 8; button = new Button(8, totalHeight, 120, 12, "guistrings.spawner.add_group") { @Override protected void onPressed() { getContainer().settings.addSpawnGroup(new EntitySpawnGroup(getContainer().settings)); refreshGui(); } }; area.addGuiElement(button); totalHeight += 12; area.setAreaSize(totalHeight); } }
412
0.895817
1
0.895817
game-dev
MEDIA
0.954731
game-dev
0.939966
1
0.939966
CNLouisLiu/LViewLoL
1,761
UtilityScripts/unit_data/practicetool_targetdummy
{"Characters/PracticeTool_TargetDummy/Skins/Meta": {"skinBasedRelativeColorScheme": true, "isRelativeColorCharacter": true, "relativeColorSwapTable": [1], "__type": "SkinCharacterMetaDataProperties"}, "Characters/PracticeTool_TargetDummy/CharacterRecords/Root": {"mCharacterName": "PracticeTool_TargetDummy", "baseHP": 1000.0, "baseStaticHPRegen": 0.0, "healthBarHeight": 95.0, "primaryAbilityResource": {"arType": 3, "arBaseStaticRegen": 0.0, "__type": "AbilityResourceSlotInfo"}, "baseDamage": 0.0, "baseArmor": 0.0, "baseMoveSpeed": 0.0, "attackRange": 175.0, "attackSpeed": 0.6579999923706055, "attackSpeedRatio": 0.6579999923706055, "acquisitionRange": 600.0, "basicAttack": {"mAttackDelayCastOffsetPercent": -0.09166666865348816, "mAttackProbability": 0.5, "__type": "AttackSlotData"}, "extraAttacks": [{"mAttackProbability": 0.5, "mAttackName": "TemplateFighterBasicAttack2", "__type": "AttackSlotData"}], "critAttacks": [{"mAttackDelayCastOffsetPercent": -0.09166666865348816, "mAttackName": "TemplateFighterCritAttack", "__type": "AttackSlotData"}], "selectionHeight": 122.0, "selectionRadius": 100.0, "pathfindingCollisionRadius": 30.0, "unitTagsString": "Champion", "characterToolData": {"mapAIPresence": {"0": {"__type": "{d01d25c0}"}, "1": {"__type": "{d01d25c0}"}, "2": {"__type": "{d01d25c0}"}}, "passiveData": [{"name": "game_character_passiveName_TemplateFighter", "__type": "ToolPassiveData"}], "searchTags": "Fighter,melee", "roles": "BRAWLER", "magicRank": 2, "difficultyRank": 3, "description": "game_character_description_TemplateFighter", "defenseRank": 5, "ChasingAttackRangePercent": 0.800000011920929, "championId": 994, "attackRank": 8, "__type": "CharacterToolData"}, "flags": 8398088, "deathTime": 0.5, "__type": "CharacterRecord"}}
412
0.681827
1
0.681827
game-dev
MEDIA
0.907739
game-dev
0.61122
1
0.61122
mastercomfig/tf2-patches-old
1,310
src/game/server/tf2/tf_flare.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef TF_FLARE_H #define TF_FLARE_H #pragma once #define SIGNALFLARE_NO_DLIGHT 0x01 #define SIGNALFLARE_NO_SMOKE 0x02 #define SIGNALFLARE_INFINITE 0x04 #define SIGNALFLARE_DURATION 5.0f //============================================================================= // // Signal Flare Class // class CSignalFlare : public CBaseAnimating { DECLARE_CLASS( CSignalFlare, CBaseAnimating ); public: DECLARE_DATADESC(); DECLARE_SERVERCLASS(); CSignalFlare( void ); static CSignalFlare *Create( Vector vecOrigin, QAngle vecAngles, CBaseEntity *pOwner, float lifetime ); // Initialization void Spawn( void ); void Precache( void ); // Think and Touch void FlareThink( void ); void FlareTouch( CBaseEntity *pOther ); public: CBaseEntity *m_pOwner; int m_nBounces; // how many times has this flare bounced? CNetworkVar( float, m_flDuration ); // when will the flare burn out? CNetworkVar( float, m_flScale ); float m_flNextDamage; bool m_bFading; CNetworkVar( bool, m_bLight ); CNetworkVar( bool, m_bSmoke ); }; EXTERN_SEND_TABLE( DT_SignalFlare ); #endif // TF_FLARE_H
412
0.766131
1
0.766131
game-dev
MEDIA
0.525866
game-dev
0.597737
1
0.597737
lge-ros2/cloisim
14,092
Assets/Scripts/Tools/SDF/Parser/Root.cs
/* * Copyright (c) 2020 LG Electronics Inc. * * SPDX-License-Identifier: MIT */ using System.Collections.Generic; using System.IO; using System.Xml; using System.Linq; using System.Text; using System; namespace SDF { public class Root { private readonly string[] SdfVersions = { "1.9", "1.8", "1.7", "1.6", "1.5", "1.4", "1.3", "1.2", "1.1", "1.0", string.Empty }; private static readonly string ProtocolModel = "model://"; private static readonly string ProtocolFile = "file://"; // {Model Name, (Model Config Name, Model Path, Model File)} public Dictionary<string, Tuple<string, string, string>> resourceModelTable = new Dictionary<string, Tuple<string, string, string>>(); private XmlDocument _doc = new XmlDocument(); private XmlDocument _originalDoc = null; // for Save private string _worldFileName = string.Empty; private string _sdfVersion = "1.7"; private DebugLogWriter _logger; private DebugLogWriter _loggerErr; public XmlDocument GetOriginalDocument() => _originalDoc; public List<string> fileDefaultPaths = new List<string>(); public List<string> modelDefaultPaths = new List<string>(); public List<string> worldDefaultPaths = new List<string>(); public Root() { _logger = new DebugLogWriter(); _loggerErr = new DebugLogWriter(true); Console.SetOut(_logger); Console.SetError(_loggerErr); } public bool DoParse(out World world, out string worldFilePath, in string worldFileName) { // Console.Write("Loading World File from SDF!!!!!"); world = null; worldFilePath = string.Empty; if (worldFileName.Trim().Length <= 0) { return false; } // Console.Write("World file, PATH: " + worldFileName); foreach (var worldPath in worldDefaultPaths) { var fullFilePath = worldPath + "/" + worldFileName; if (File.Exists(@fullFilePath)) { try { _doc.RemoveAll(); _doc.Load(fullFilePath); _originalDoc = (XmlDocument)_doc.CloneNode(true); _worldFileName = worldFileName; ReplaceAllIncludedModel(); ConvertPathToAbsolutePaths(); // Console.Write("Load World"); var worldNode = _doc.SelectSingleNode("/sdf/world"); world = new World(worldNode); worldFilePath = worldPath; _logger.Write($"World({worldFileName}) is loaded."); // _logger.SetShowOnDisplayOnce(); return true; } catch (XmlException ex) { _loggerErr.SetShowOnDisplayOnce(); _loggerErr.Write($"Failed to Load World({fullFilePath}) - {ex.Message}"); } } } _loggerErr.Write("World file not exist: " + worldFileName); return false; } public bool DoParse(out Model model, in string modelFullPath, in string modelFileName) { // Console.Write("Loading World File from SDF!!!!!"); model = null; var modelLocation = Path.Combine(modelFullPath, modelFileName); var modelName = Path.GetFileName(modelFullPath); // Console.Write(modelFullPath + " -> " + modelName); try { _doc.RemoveAll(); _doc.Load(modelLocation); ReplaceAllIncludedModel(); // Console.Write("Load World"); var modelNode = _doc.SelectSingleNode("/sdf/model"); StoreOriginalModelName(_doc, modelName, modelNode); ConvertPathToAbsolutePaths(); model = new Model(modelNode); // _logger.SetShowOnDisplayOnce(); // _logger.Write($"Model({modelName}) is loaded. > {model.Name}"); return true; } catch (XmlException ex) { var errorMessage = "Failed to Load Model file(" + modelLocation + ") file - " + ex.Message; _loggerErr.SetShowOnDisplayOnce(); _loggerErr.Write(errorMessage); } return false; } public void UpdateResourceModelTable() { if (resourceModelTable == null) { Console.Write("ERROR: Resource model table is not initialized!!!!"); return; } var failedModelTableList = new StringBuilder(); var numberOfFailedModelTable = 0; var modelConfigDoc = new XmlDocument(); // Loop model paths foreach (var modelPath in modelDefaultPaths) { if (!Directory.Exists(modelPath)) { Console.Write("Directory does not exists: " + modelPath); continue; } var rootDirectory = new DirectoryInfo(modelPath); //Console.Write(">>> Model Default Path: " + modelPath); // Loop models foreach (var subDirectory in rootDirectory.GetDirectories()) { if (subDirectory.Name.StartsWith(".")) { continue; } // Console.Write(subDirectory.Name + " => " + subDirectory.FullName); var modelConfig = subDirectory.FullName + "/model.config"; if (!File.Exists(modelConfig)) { Console.Write("File does not exists: " + modelConfig); continue; } try { modelConfigDoc.Load(modelConfig); } catch (XmlException e) { Console.Write($"Failed to Load model file({modelConfig}) - {e.Message}"); continue; } // Get Model root var modelNode = modelConfigDoc.SelectSingleNode("model"); // Get Model name var modelName = subDirectory.Name; var modelNameNode = modelNode.SelectSingleNode("name"); var modelConfigName = (modelNameNode == null) ? modelName : modelNameNode.InnerText; // Get Model SDF file name var sdfFileName = string.Empty; foreach (var version in SdfVersions) { // Console.Write(version); // Console.Write(modelNode); var sdfNode = modelNode.SelectSingleNode($"sdf[@version={version} or not(@version)]"); if (sdfNode != null) { sdfFileName = sdfNode.InnerText; _sdfVersion = version; //Console.Write(version + "," + sdfFileName); break; } } if (string.IsNullOrEmpty(sdfFileName)) { Console.Write($"{modelName}: SDF FileName is empty!!"); continue; } // Insert resource table var modelValue = new Tuple<string, string, string>(modelConfigName, subDirectory.FullName, sdfFileName); try { // Console.Write(modelName + ":" + subDirectory.FullName + ":" + sdfFileName); // Console.Write(modelName + ", " + modelValue); if (resourceModelTable.ContainsKey(modelName)) { failedModelTableList.AppendLine(string.Empty); failedModelTableList.Append(String.Concat(modelName, " => Cannot register", modelValue)); numberOfFailedModelTable++; } else { resourceModelTable.Add(modelName, modelValue); } } catch (NullReferenceException e) { Console.Write(e.Message); } } } if (numberOfFailedModelTable > 0) { failedModelTableList.Insert(0, $"All failed models({numberOfFailedModelTable}) are already registered."); _loggerErr.Write(failedModelTableList); } Console.Write($"Total Models: {resourceModelTable.Count}"); } private string FindParentModelFolderName(in XmlNode targetNode) { var modelName = string.Empty; var node = targetNode?.ParentNode; while (node != null) { // Console.Write(node.Name + " - " + node.LocalName); if (node.Name == "model") { modelName = node.Attributes["original_name"]?.Value; // Console.Write("Found model " + modelName); break; } node = node?.ParentNode; } if (modelName == null) { return string.Empty; } return modelName; } // Converting media/file uri private void ConvertPathToAbsolutePath(in string targetElement) { var nodeList = _doc.SelectNodes($"//{targetElement}"); // Console.Write("Target:" + targetElement + ", Num Of uri nodes: " + nodeList.Count); foreach (XmlNode node in nodeList) { var uri = node.InnerText; if (uri.StartsWith(ProtocolModel)) { var modelUri = uri.Replace(ProtocolModel, string.Empty); var stringArray = modelUri.Split('/'); // Get Model name from Uri var modelName = stringArray[0]; // remove Model name in array modelUri = string.Join("/", stringArray.Skip(1)); if (resourceModelTable.TryGetValue(modelName, out var value)) { node.InnerText = value.Item2 + "/" + modelUri; } } else if (uri.StartsWith(ProtocolFile)) { foreach (var filePath in fileDefaultPaths) { var fileUri = uri.Replace(ProtocolFile, filePath + "/"); if (File.Exists(@fileUri)) { node.InnerText = fileUri; break; } } } else { var currentModelName = FindParentModelFolderName(node); var meshUri = string.Join("/", uri); if (resourceModelTable.TryGetValue(currentModelName, out var value)) { node.InnerText = value.Item2 + "/" + meshUri; } // Console.Write($"Cannot convert: {uri}"); } } } private void DuplicateNode(in string targetElement, in string newName) { var nodeList = _doc.SelectNodes($"//{targetElement}"); foreach (XmlNode node in nodeList) { var newNode = _doc.CreateElement(newName); foreach (XmlNode childNode in node.ChildNodes) { newNode.AppendChild(childNode.CloneNode(true)); } node.ParentNode.AppendChild(newNode); } } private void ConvertPathToAbsolutePaths() { DuplicateNode("uri", "original_uri"); ConvertPathToAbsolutePath("uri"); ConvertPathToAbsolutePath("filename"); ConvertPathToAbsolutePath("texture/diffuse"); ConvertPathToAbsolutePath("texture/normal"); ConvertPathToAbsolutePath("normal_map"); } private void ReplaceAllIncludedModel() { // loop all include tag until all replaced. XmlNodeList nodes; do { nodes = _doc.SelectNodes("//include"); // if (nodes.Count > 0) // Console.Write("Num Of Included Model nodes: " + nodes.Count); foreach (XmlNode node in nodes) { var modelNode = GetIncludedModel(node); if (modelNode != null) { // Console.Write("Node - " + modelNode); var importNode = _doc.ImportNode(modelNode, true); var newAttr = _doc.CreateAttribute("is_nested"); newAttr.Value = "true"; importNode.Attributes.Append(newAttr); node.ParentNode.ReplaceChild(importNode, node); } else { node.ParentNode.RemoveChild(node); } } } while (nodes.Count != 0); } #region Segmentation Tag private void StoreOriginalModelName(in XmlDocument targetDoc, in string modelName, XmlNode targetNode) { // store original model's name for segmentation Tag var newAttr = targetDoc.CreateAttribute("original_name"); newAttr.Value = modelName; targetNode.Attributes.Append(newAttr); // Console.Write(targetNode.Name + " - " + targetNode.LocalName + " - " + modelName); } #endregion private XmlNode GetIncludedModel(XmlNode includedNode) { var uriNode = includedNode.SelectSingleNode("uri"); if (uriNode == null) { Console.Write("uri is empty."); return null; } var nameNode = includedNode.SelectSingleNode("name"); var name = (nameNode == null) ? null : nameNode.InnerText; var staticNode = includedNode.SelectSingleNode("static"); var isStatic = (staticNode == null) ? null : staticNode.InnerText; var placementFrameNode = includedNode.SelectSingleNode("placement_frame"); var placementFrame = (placementFrameNode == null) ? null : placementFrameNode.InnerText; var poseNode = includedNode.SelectSingleNode("pose"); var pose = (poseNode == null) ? null : poseNode.InnerText; var pluginNode = includedNode.SelectSingleNode("plugin"); // var plugin = (pluginNode == null) ? null : pluginNode.InnerText; var uri = uriNode.InnerText; var modelName = uri.Replace(ProtocolModel, string.Empty); if (resourceModelTable.TryGetValue(modelName, out var value)) { uri = value.Item2 + "/" + value.Item3; // Console.WriteLine($"include/modelname = {name} | {uri} | {modelName} | {pose} | {isStatic}"); } else { Console.Write("Not exists in database: " + uri); return null; } var modelSdfDoc = new XmlDocument(); try { modelSdfDoc.Load(uri); } catch (XmlException e) { _loggerErr.SetShowOnDisplayOnce(); _loggerErr.Write($"Failed to Load included model({modelName}) file - {e.Message}"); return null; } var sdfNode = modelSdfDoc.SelectSingleNode("/sdf/model"); if (sdfNode == null) { sdfNode = modelSdfDoc.SelectSingleNode("/sdf/light"); } var attributes = sdfNode.Attributes; if (attributes.GetNamedItem("version") != null) { var modelSdfDocVersion = attributes.GetNamedItem("version").Value; // TODO: Version check } StoreOriginalModelName(modelSdfDoc, modelName, sdfNode); // Edit custom parameter if (nameNode != null) { attributes.GetNamedItem("name").Value = name; } if (poseNode != null) { var poseElem = sdfNode.SelectSingleNode("pose"); if (poseElem != null) { poseElem.InnerText = pose; } else { var elem = sdfNode.OwnerDocument.CreateElement("pose"); elem.InnerText = pose; sdfNode.InsertBefore(elem, sdfNode.FirstChild); } } if (staticNode != null) { var staticElem = sdfNode.SelectSingleNode("static"); if (staticElem != null) { staticElem.InnerText = isStatic; } else { var elem = sdfNode.OwnerDocument.CreateElement("static"); elem.InnerText = isStatic; sdfNode.InsertBefore(elem, sdfNode.FirstChild); } } if (pluginNode != null) { sdfNode.InsertBefore(pluginNode, sdfNode.LastChild); } return sdfNode; } public void Save(in string filePath = "") { var fileName = Path.GetFileNameWithoutExtension(_worldFileName); var datetime = DateTime.Now.ToString("yyMMddHHmmss"); // DateTime.Now.ToString("yyyyMMddHHmmss"); var saveName = $"{filePath}/{fileName}{datetime}.world"; _originalDoc.Save(saveName); Console.Write($"Worldfile Saved: {saveName}"); } public void Print() { // Print all SDF contents var sw = new StringWriter(); var xw = new XmlTextWriter(sw); _doc.WriteTo(xw); Console.Write(sw.ToString()); } } }
412
0.898581
1
0.898581
game-dev
MEDIA
0.230076
game-dev
0.928299
1
0.928299
synfron/ReshaperForBurp
1,627
extension/src/main/java/synfron/reshaper/burp/core/rules/RuleResponse.java
package synfron.reshaper.burp.core.rules; import lombok.EqualsAndHashCode; import lombok.Getter; import java.util.List; import java.util.stream.Collectors; @EqualsAndHashCode public class RuleResponse { public static final RuleResponse Continue = new RuleResponse("Continue", 1); public static final RuleResponse BreakThens = new RuleResponse("Skip Next Thens", 2); public static final RuleResponse BreakRules = new RuleResponse("Skip Next Rules", 4); private static final List<RuleResponse> values = List.of( Continue, BreakThens, BreakRules ); @Getter private final String name; private final int flags; private RuleResponse() { this(Continue.name, Continue.flags); } private RuleResponse(String name, int flags) { this.name = name; this.flags = flags; } private RuleResponse(int flags) { this(getValues().stream() .filter(ruleResponse -> ruleResponse.hasFlags(flags)) .map(RuleResponse::getName) .collect(Collectors.joining(", ")), flags); } public static List<RuleResponse> getValues() { return values; } public boolean hasFlags(RuleResponse ruleResponse) { return hasFlags(ruleResponse.flags); } private boolean hasFlags(int flags) { return (this.flags & flags) == flags; } public RuleResponse or(RuleResponse ruleResponse) { int newFlag = flags | ruleResponse.flags; return new RuleResponse(newFlag); } @Override public String toString() { return name; } }
412
0.745039
1
0.745039
game-dev
MEDIA
0.863864
game-dev
0.543209
1
0.543209
KaboomB52/KewlSpigot
6,065
kewlspigot-server/src/main/java/net/minecraft/server/CommandTp.java
package net.minecraft.server; import java.util.EnumSet; import java.util.List; public class CommandTp extends CommandAbstract { public CommandTp() {} public String getCommand() { return "tp"; } public int a() { return 2; } public String getUsage(ICommandListener icommandlistener) { return "commands.tp.usage"; } public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { if (astring.length < 1) { throw new ExceptionUsage("commands.tp.usage", new Object[0]); } else { byte b0 = 0; Object object; if (astring.length != 2 && astring.length != 4 && astring.length != 6) { object = b(icommandlistener); } else { object = b(icommandlistener, astring[0]); b0 = 1; } if (astring.length != 1 && astring.length != 2) { if (astring.length < b0 + 3) { throw new ExceptionUsage("commands.tp.usage", new Object[0]); } else if (((Entity) object).world != null) { int i = b0 + 1; CommandAbstract.CommandNumber commandabstract_commandnumber = a(((Entity) object).locX, astring[b0], true); CommandAbstract.CommandNumber commandabstract_commandnumber1 = a(((Entity) object).locY, astring[i++], 0, 0, false); CommandAbstract.CommandNumber commandabstract_commandnumber2 = a(((Entity) object).locZ, astring[i++], true); CommandAbstract.CommandNumber commandabstract_commandnumber3 = a((double) ((Entity) object).yaw, astring.length > i ? astring[i++] : "~", false); CommandAbstract.CommandNumber commandabstract_commandnumber4 = a((double) ((Entity) object).pitch, astring.length > i ? astring[i] : "~", false); float f; if (object instanceof EntityPlayer) { EnumSet enumset = EnumSet.noneOf(PacketPlayOutPosition.EnumPlayerTeleportFlags.class); if (commandabstract_commandnumber.c()) { enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.X); } if (commandabstract_commandnumber1.c()) { enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y); } if (commandabstract_commandnumber2.c()) { enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Z); } if (commandabstract_commandnumber4.c()) { enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT); } if (commandabstract_commandnumber3.c()) { enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT); } f = (float) commandabstract_commandnumber3.b(); if (!commandabstract_commandnumber3.c()) { f = MathHelper.g(f); } float f1 = (float) commandabstract_commandnumber4.b(); if (!commandabstract_commandnumber4.c()) { f1 = MathHelper.g(f1); } if (f1 > 90.0F || f1 < -90.0F) { f1 = MathHelper.g(180.0F - f1); f = MathHelper.g(f + 180.0F); } ((Entity) object).mount((Entity) null); ((EntityPlayer) object).playerConnection.a(commandabstract_commandnumber.b(), commandabstract_commandnumber1.b(), commandabstract_commandnumber2.b(), f, f1, enumset); ((Entity) object).f(f); } else { float f2 = (float) MathHelper.g(commandabstract_commandnumber3.a()); f = (float) MathHelper.g(commandabstract_commandnumber4.a()); if (f > 90.0F || f < -90.0F) { f = MathHelper.g(180.0F - f); f2 = MathHelper.g(f2 + 180.0F); } ((Entity) object).setPositionRotation(commandabstract_commandnumber.a(), commandabstract_commandnumber1.a(), commandabstract_commandnumber2.a(), f2, f); ((Entity) object).f(f2); } a(icommandlistener, this, "commands.tp.success.coordinates", new Object[] { ((Entity) object).getName(), Double.valueOf(commandabstract_commandnumber.a()), Double.valueOf(commandabstract_commandnumber1.a()), Double.valueOf(commandabstract_commandnumber2.a())}); } } else { Entity entity = b(icommandlistener, astring[astring.length - 1]); // CraftBukkit Start // Use Bukkit teleport method in all cases. It has cross dimensional handling, events if (((Entity) object).getBukkitEntity().teleport(entity.getBukkitEntity(), org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.COMMAND)) { a(icommandlistener, this, "commands.tp.success", new Object[]{((Entity) object).getName(), entity.getName()}); // CraftBukkit End } } } } public List<String> tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { return astring.length != 1 && astring.length != 2 ? null : a(astring, MinecraftServer.getServer().getPlayers()); } public boolean isListStart(String[] astring, int i) { return i == 0; } // CraftBukkit start - fix decompile error @Override public int compareTo(ICommand o) { return a((ICommand) o); } // CraftBukkit end }
412
0.741683
1
0.741683
game-dev
MEDIA
0.726786
game-dev
0.740794
1
0.740794
lordofduct/spacepuppy-unity-framework-4.0
30,539
Framework/com.spacepuppy.core/Editor/src/Core/ReorderableArrayPropertyDrawer.cs
using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Collections.Generic; using System.Linq; using com.spacepuppy; using com.spacepuppy.Utils; using com.spacepuppyeditor.Internal; namespace com.spacepuppyeditor.Core { [CustomPropertyDrawer(typeof(ReorderableArrayAttribute))] public class ReorderableArrayPropertyDrawer : PropertyDrawer, IArrayHandlingPropertyDrawer { public event System.EventHandler ElementAdded; public delegate string FormatElementLabelCallback(SerializedProperty property, int index, bool isActive, bool isFocused); private static readonly float TOP_PAD = 2f + EditorGUIUtility.singleLineHeight; private const float BOTTOM_PAD = 4f; private const float MARGIN = 2f; private const float LENGTHFIIELD_WIDTH = 50f; private const float LENGTHFIIELD_MARGIN = 5f; #region Fields public GUIContent CustomLabel; private CachedReorderableList _lst; private GUIContent _labelContent; private bool _alwaysExpanded; private bool _removeBackgroundWhenCollapsed; private bool _draggable = true; private bool _drawElementAtBottom; private bool _hideElementLabel = false; private string _childPropertyAsLabel; private string _childPropertyAsEntry; private string _elementLabelFormatString; private bool _oneBasedLabelIndex; private float _elementPadding; private bool _allowDragAndDrop = true; private bool _allowDragAndDropSceneObjects = true; private bool _showTooltipInHeader; private bool _hideLengthField; private bool _elementLabelIsEditable; private PropertyDrawer _internalDrawer; #endregion #region CONSTRUCTOR public ReorderableArrayPropertyDrawer() { } /// <summary> /// Use this to set the element type of the list for drag & drop, if you're manually calling the drawer. /// </summary> /// <param name="elementType"></param> public ReorderableArrayPropertyDrawer(System.Type dragDropElementType) { this.DragDropElementType = dragDropElementType; } protected virtual CachedReorderableList GetList(SerializedProperty property, GUIContent label) { var lst = CachedReorderableList.GetListDrawer(property, _maskList_DrawHeader, _maskList_DrawElement, _maskList_OnElementAdded); lst.draggable = this.Draggable; if (property.arraySize > 0) { if (this.ElementEntryIsForcedSingleLine) { lst.elementHeight = EditorGUIUtility.singleLineHeight; } else { var pchild = property.GetArrayElementAtIndex(0); /* if (_internalDrawer != null) { lst.elementHeight = _internalDrawer.GetPropertyHeight(pchild, label); } else if (ElementIsFlatChildField(pchild)) { //we don't draw this way if it's a built-in type from Unity pchild.isExpanded = true; if (_hideElementLabel) { lst.elementHeight = SPEditorGUI.GetDefaultPropertyHeight(pchild, label, true) + 2f - EditorGUIUtility.singleLineHeight; } else { lst.elementHeight = SPEditorGUI.GetDefaultPropertyHeight(pchild, label, true) + 2f; //height when showing label } } else { lst.elementHeight = SPEditorGUI.GetDefaultPropertyHeight(pchild, label) + 1f; } */ lst.elementHeight = this.GetElementHeight(pchild, label, false) + 2f; } } else { lst.elementHeight = EditorGUIUtility.singleLineHeight; } return lst; } private void StartOnGUI(SerializedProperty property, GUIContent label) { _labelContent = label; _lst = this.GetList(property, label); if (_lst.index >= _lst.count) _lst.index = -1; if (this.fieldInfo != null && this.DragDropElementType == null) //validate if this hasn't already happened { this.DragDropElementType = TypeUtil.GetElementTypeOfListType(this.fieldInfo.FieldType); if (!string.IsNullOrEmpty(this.ChildPropertyAsEntry) && this.DragDropElementType != null) { var field = this.DragDropElementType.GetMember(this.ChildPropertyAsEntry, System.Reflection.MemberTypes.Field, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).FirstOrDefault() as System.Reflection.FieldInfo; if (field != null) this.DragDropElementType = field.FieldType; //HACK - add support for SceneRef cause of how weird they are if (string.Equals(this.DragDropElementType?.FullName, "com.spacepuppy.Scenes.SceneRef")) this.DragDropElementType = typeof(SceneAsset); } } } private void EndOnGUI(SerializedProperty property, GUIContent label) { //_lst.serializedProperty = null; _labelContent = null; } #endregion #region Properties /* * Current State */ public ReorderableList CurrentReorderableList { get { return _lst; } } public SerializedProperty CurrentArrayProperty { get { return _lst != null ? _lst.serializedProperty : null; } } /// <summary> /// During the drawelement callback this is set to the currently drawn array index. A custom 'InternalDrawer' can read this property during its OnGUI event to get the index it's on. /// </summary> public int CurrentDrawingArrayElementIndex { get; private set; } /* * Configuration */ public bool AlwaysExpanded { get { return (this.attribute as ReorderableArrayAttribute)?.AlwaysExpanded ?? _alwaysExpanded; } set { _alwaysExpanded = value; } } public bool RemoveBackgroundWhenCollapsed { get { return (this.attribute as ReorderableArrayAttribute)?.RemoveBackgroundWhenCollapsed ?? _removeBackgroundWhenCollapsed; } set { _removeBackgroundWhenCollapsed = value; } } public bool Draggable { get { return (this.attribute as ReorderableArrayAttribute)?.Draggable ?? _draggable; } set { _draggable = value; } } public bool DrawElementAtBottom { get { return (this.attribute as ReorderableArrayAttribute)?.DrawElementAtBottom ?? _drawElementAtBottom; } set { _drawElementAtBottom = value; } } public bool HideElementLabel { get { return (this.attribute as ReorderableArrayAttribute)?.HideElementLabel ?? _hideElementLabel; } set { _hideElementLabel = value; } } public string ChildPropertyAsLabel { get { return (this.attribute as ReorderableArrayAttribute)?.ChildPropertyToDrawAsElementLabel ?? _childPropertyAsLabel; } set { _childPropertyAsLabel = value; } } public string ChildPropertyAsEntry { get { return (this.attribute as ReorderableArrayAttribute)?.ChildPropertyToDrawAsElementEntry ?? _childPropertyAsEntry; } set { _childPropertyAsEntry = value; } } public string ElementLabelFormatString { get { return (this.attribute as ReorderableArrayAttribute)?.ElementLabelFormatString ?? _elementLabelFormatString; } set { _elementLabelFormatString = value; } } public bool OneBasedLabelIndex { get => (this.attribute as ReorderableArrayAttribute)?.OneBasedLabelIndex ?? _oneBasedLabelIndex; set => _oneBasedLabelIndex = value; } public float ElementPadding { get { return (this.attribute as ReorderableArrayAttribute)?.ElementPadding ?? _elementPadding; } set { _elementPadding = value; } } public FormatElementLabelCallback FormatElementLabel { get; set; } /// <summary> /// Can drag entries onto the inspector without needing to click + button. Only works for array/list of UnityEngine.Object sub/types. /// </summary> public bool AllowDragAndDrop { get { return (this.attribute as ReorderableArrayAttribute)?.AllowDragAndDrop ?? _allowDragAndDrop; } set { _allowDragAndDrop = value; } } public bool AllowDragAndDropSceneObjects { get { return (this.attribute as ReorderableArrayAttribute)?.AllowDragAndDropSceneObjects ?? _allowDragAndDropSceneObjects; } set { _allowDragAndDropSceneObjects = value; } } public bool ShowTooltipInHeader { get { return (this.attribute as ReorderableArrayAttribute)?.ShowTooltipInHeader ?? _showTooltipInHeader; } set { _showTooltipInHeader = value; } } public bool HideLengthField { get => (this.attribute as ReorderableArrayAttribute)?.HideLengthField ?? _hideLengthField; set => _hideLengthField = value; } public bool ElementLabelIsEditable { get => (this.attribute as ReorderableArrayAttribute)?.ElementLabelIsEditable ?? _elementLabelIsEditable; set => _elementLabelIsEditable = value; } /// <summary> /// The type of the element in the array/list, will effect drag & drop filtering (unless overriden). /// </summary> public System.Type DragDropElementType { get; set; } public System.Func<UnityEngine.Object, UnityEngine.Object> DragDropElementFilter { get; set; } public bool ElementEntryIsForcedSingleLine => this.DrawElementAtBottom || this.ElementLabelIsEditable; #endregion #region OnGUI public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { float h; if (EditorHelper.AssertMultiObjectEditingNotSupportedHeight(property, label, out h)) return h; if (this.AlwaysExpanded) property.isExpanded = true; if (property.isArray) { this.StartOnGUI(property, label); if (property.isExpanded) { h = _lst.GetHeight(); if (this.DrawElementAtBottom && _lst.index >= 0 && _lst.index < property.arraySize) { var pchild = property.GetArrayElementAtIndex(_lst.index); /* if (_internalDrawer != null) { h += _internalDrawer.GetPropertyHeight(pchild, label) + BOTTOM_PAD + TOP_PAD; } else if (ElementIsFlatChildField(pchild)) { //we don't draw this way if it's a built-in type from Unity pchild.isExpanded = true; h += SPEditorGUI.GetDefaultPropertyHeight(pchild, label, true) + BOTTOM_PAD + TOP_PAD - EditorGUIUtility.singleLineHeight; } else { h += SPEditorGUI.GetDefaultPropertyHeight(pchild, label, false) + BOTTOM_PAD + TOP_PAD; } */ h += this.GetElementHeight(pchild, label, true) + BOTTOM_PAD + TOP_PAD; } } else { h = EditorGUIUtility.singleLineHeight + BOTTOM_PAD; } } else { h = EditorGUIUtility.singleLineHeight; } return h; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { this.CurrentDrawingArrayElementIndex = -1; if (EditorHelper.AssertMultiObjectEditingNotSupported(position, property, label)) return; if (property.isArray) { if (this.CustomLabel != null) { label = this.CustomLabel; } else if (label != null) { label = label.Clone(); if (this.ShowTooltipInHeader) { label.text = string.Format("{0} [{1:0}] - {2}", label.text, property.arraySize, (string.IsNullOrEmpty(label.tooltip) ? property.tooltip : label.tooltip)); } else { label.text = string.Format("{0} [{1:0}]", label.text, property.arraySize); } if (string.IsNullOrEmpty(label.tooltip)) label.tooltip = property.tooltip; } else { label = EditorHelper.TempContent(property.displayName, property.tooltip); } //const float WIDTH_FOLDOUT = 5f; var foldoutRect = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight); var lengthFieldRect = new Rect(position.xMax - (LENGTHFIIELD_WIDTH + LENGTHFIIELD_MARGIN), position.yMin, LENGTHFIIELD_WIDTH, EditorGUIUtility.singleLineHeight); position = EditorGUI.IndentedRect(position); Rect listArea = position; if (this.AlwaysExpanded) { this.StartOnGUI(property, label); listArea = new Rect(position.xMin, position.yMin, position.width, _lst.GetHeight()); //_lst.DoList(EditorGUI.IndentedRect(position)); _lst.DoList(listArea); this.EndOnGUI(property, label); } else if (property.isExpanded) { this.StartOnGUI(property, label); listArea = new Rect(position.xMin, position.yMin, position.width, _lst.GetHeight()); property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, GUIContent.none); //_lst.DoList(EditorGUI.IndentedRect(position)); _lst.DoList(listArea); this.EndOnGUI(property, label); } else { if (this.RemoveBackgroundWhenCollapsed) { property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, label); } else { property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, GUIContent.none); //ReorderableListHelper.DrawRetractedHeader(EditorGUI.IndentedRect(position), label); ReorderableListHelper.DrawRetractedHeader(position, label); _lst.DoHeaderContextMenu(position); } } if (!this.HideLengthField) { var style = new GUIStyle(GUI.skin.textField); style.alignment = TextAnchor.MiddleRight; property.arraySize = EditorGUI.DelayedIntField(lengthFieldRect, property.arraySize, style); } this.DoDragAndDrop(property, listArea); if (property.isExpanded && this.DrawElementAtBottom && _lst.index >= 0 && _lst.index < property.arraySize) { var pchild = property.GetArrayElementAtIndex(_lst.index); var label2 = TempElementLabel(pchild, _lst.index, true, true); pchild.isExpanded = true; float h; if (_internalDrawer != null) { h = _internalDrawer.GetPropertyHeight(pchild, label2) + BOTTOM_PAD + TOP_PAD; } else if (pchild.hasChildren) { h = SPEditorGUI.GetDefaultPropertyHeight(pchild, label, true) + BOTTOM_PAD + TOP_PAD - EditorGUIUtility.singleLineHeight; } else { h = SPEditorGUI.GetDefaultPropertyHeight(pchild, label2, true) + BOTTOM_PAD + TOP_PAD; } var area = new Rect(position.xMin, position.yMax - h, position.width, h); var drawArea = new Rect(area.xMin, area.yMin + TOP_PAD, area.width - MARGIN, area.height - TOP_PAD); GUI.BeginGroup(area, label2, GUI.skin.box); GUI.EndGroup(); EditorGUI.indentLevel++; if (_internalDrawer != null) { _internalDrawer.OnGUI(drawArea, pchild, label2); } else if (pchild.hasChildren) { SPEditorGUI.FlatChildPropertyField(drawArea, pchild); } else { SPEditorGUI.DefaultPropertyField(drawArea, pchild, GUIContent.none, false); } EditorGUI.indentLevel--; } } else { SPEditorGUI.DefaultPropertyField(position, property, label, false); } this.CurrentDrawingArrayElementIndex = -1; } #endregion #region Masks ReorderableList Handlers protected virtual void _maskList_DrawHeader(Rect area) { if (_labelContent != null) { EditorGUI.LabelField(area, _labelContent); } } protected virtual void _maskList_DrawElement(Rect area, int index, bool isActive, bool isFocused) { var element = _lst.serializedProperty.GetArrayElementAtIndex(index); if (element == null) return; var label = this.GetFormattedElementLabel(area, index, isActive, isFocused); this.DrawElement(area, element, label, index); if (GUI.enabled) ReorderableListHelper.DrawDraggableElementDeleteContextMenu(_lst, area, index, isActive, isFocused); } private void _maskList_OnElementAdded(ReorderableList lst) { int i = lst.serializedProperty.arraySize; lst.serializedProperty.arraySize++; lst.index = i; var element = lst.serializedProperty.GetArrayElementAtIndex(i); var attrib = this.attribute as ReorderableArrayAttribute; if (attrib != null && !string.IsNullOrEmpty(attrib.OnAddCallback)) { lst.serializedProperty.serializedObject.ApplyModifiedProperties(); var obj = EditorHelper.GetTargetObjectOfProperty(element); obj = com.spacepuppy.Dynamic.DynamicUtil.InvokeMethod(lst.serializedProperty.serializedObject.targetObject, attrib.OnAddCallback, obj); EditorHelper.SetTargetObjectOfProperty(element, obj); lst.serializedProperty.serializedObject.Update(); } this.OnElementAdded(lst, element); } protected virtual void OnElementAdded(ReorderableList lst, SerializedProperty element) { var d = this.ElementAdded; if (d != null) d(this, System.EventArgs.Empty); } protected virtual GUIContent GetFormattedElementLabel(Rect area, int index, bool isActive, bool isFocused) { var element = _lst.serializedProperty.GetArrayElementAtIndex(index); if (element == null) return GUIContent.none; GUIContent label = null; if (this.ElementPadding > 0f) { area = new Rect(area.xMin + this.ElementPadding, area.yMin, Mathf.Max(0f, area.width - this.ElementPadding), area.height); } if (label == null) label = (this.HideElementLabel) ? GUIContent.none : TempElementLabel(element, index, isActive, isFocused); return label; } protected virtual void DrawElement(Rect area, SerializedProperty element, GUIContent label, int elementIndex) { this.CurrentDrawingArrayElementIndex = elementIndex; if (this.ElementEntryIsForcedSingleLine) { if (this.ElementLabelIsEditable && element.TryFindPropertyRelative(this.ChildPropertyAsLabel, out SerializedProperty labelprop)) { label = GUIContent.none; var rlabel = new Rect(area.xMin, area.yMin, EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight); area = new Rect(area.xMin + rlabel.width + 1, area.yMin, area.width - rlabel.width - 1, area.height); EditorGUI.PropertyField(rlabel, labelprop, GUIContent.none); } if (_internalDrawer is SerializeRefPickerPropertyDrawer pickerdrawer && pickerdrawer.RefType != null) { SerializeRefPickerPropertyDrawer.DrawRefPicker(area, element, label, pickerdrawer.RefType, pickerdrawer.AllowNull, pickerdrawer.NullLabel); } else if (element.TryFindPropertyRelative(this.ChildPropertyAsEntry, out SerializedProperty entryprop)) { SPEditorGUI.PropertyField(area, entryprop, label); } else { EditorGUI.LabelField(area, label); } } else { if (_internalDrawer != null) { _internalDrawer.OnGUI(area, element, label); } else if (ElementIsFlatChildField(element)) { //we don't draw this way if it's a built-in type from Unity if (this.HideElementLabel) { //no label SPEditorGUI.FlatChildPropertyField(area, element); } else { //showing label var labelArea = new Rect(area.xMin, area.yMin, area.width, EditorGUIUtility.singleLineHeight); EditorGUI.LabelField(labelArea, label); var childArea = new Rect(area.xMin, area.yMin + EditorGUIUtility.singleLineHeight + 1f, area.width, area.height - EditorGUIUtility.singleLineHeight); SPEditorGUI.FlatChildPropertyField(childArea, element); } } else { SPEditorGUI.DefaultPropertyField(area, element, label, false); } } } protected virtual float GetElementHeight(SerializedProperty element, GUIContent label, bool elementIsAtBottom) { if (_internalDrawer != null) { return _internalDrawer.GetPropertyHeight(element, label); } else if (ElementIsFlatChildField(element)) { //we don't draw this way if it's a built-in type from Unity element.isExpanded = true; if (this.HideElementLabel || elementIsAtBottom) { return SPEditorGUI.GetDefaultPropertyHeight(element, label, true) - EditorGUIUtility.singleLineHeight; } else { return SPEditorGUI.GetDefaultPropertyHeight(element, label, true); } } else { return SPEditorGUI.GetDefaultPropertyHeight(element, label, false); } } #endregion #region Drag & Drop protected virtual void DoDragAndDrop(SerializedProperty property, Rect listArea) { if (this.AllowDragAndDrop && (this.DragDropElementType != null || this.DragDropElementFilter != null) && Event.current != null) { var ev = Event.current; switch (ev.type) { case EventType.DragUpdated: case EventType.DragPerform: { if (listArea.Contains(ev.mousePosition)) { IEnumerable<UnityEngine.Object> refsource; if (this.AllowDragAndDropSceneObjects) { refsource = DragAndDrop.objectReferences; } else { refsource = DragAndDrop.objectReferences.Where(o => !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(o))); } IEnumerable<object> refs; if (this.DragDropElementFilter != null) { refs = (from o in refsource let obj = this.DragDropElementFilter(o) where obj != null select obj); } else { refs = (from o in refsource let obj = ObjUtil.GetAsFromSource(this.DragDropElementType, o, false) where obj != null select obj); } DragAndDrop.visualMode = refs.Any() ? DragAndDropVisualMode.Link : DragAndDropVisualMode.Rejected; if (ev.type == EventType.DragPerform && refs.Any()) { DragAndDrop.AcceptDrag(); AddObjectsToArray(property, refs.ToArray(), this.ChildPropertyAsEntry); GUI.changed = true; } } } break; } } } #endregion protected GUIContent TempElementLabel(SerializedProperty element, int index, bool isActive, bool isFocused) { var target = EditorHelper.GetTargetObjectOfProperty(element); string slbl = ConvertUtil.ToString(com.spacepuppy.Dynamic.DynamicUtil.GetValue(target, this.ChildPropertyAsLabel)); if (string.IsNullOrEmpty(slbl)) { var propLabel = (!string.IsNullOrEmpty(this.ChildPropertyAsLabel)) ? element.FindPropertyRelative(this.ChildPropertyAsLabel) : null; if (propLabel != null) slbl = ConvertUtil.ToString(EditorHelper.GetPropertyValue(propLabel)); } int lindex = this.OneBasedLabelIndex ? index + 1 : index; if (string.IsNullOrEmpty(slbl)) slbl = this.FormatElementLabel?.Invoke(element, lindex, isActive, isFocused); if (string.IsNullOrEmpty(slbl)) slbl = string.IsNullOrEmpty(this.ElementLabelFormatString) ? string.Format("Element {0:00}", lindex) : string.Format(this.ElementLabelFormatString, lindex); return EditorHelper.TempContent(slbl); } #region IArrayHandlingPropertyDrawer Interface public PropertyDrawer InternalDrawer { get { return _internalDrawer; } set { _internalDrawer = value; } } #endregion #region Static Utils protected static bool ElementIsFlatChildField(SerializedProperty property) { //return property.hasChildren && property.objectReferenceValue is MonoBehaviour; return property.hasChildren && property.propertyType == SerializedPropertyType.Generic; } private static void AddObjectsToArray(SerializedProperty listProp, object[] objs, string optionalChildProp = null) { if (listProp == null) throw new System.ArgumentNullException("listProp"); if (!listProp.isArray) throw new System.ArgumentException("Must be a SerializedProperty for an array/list.", "listProp"); if (objs == null || objs.Length == 0) return; try { int start = listProp.arraySize; listProp.arraySize += objs.Length; for (int i = 0; i < objs.Length; i++) { var element = listProp.GetArrayElementAtIndex(start + i); if (!string.IsNullOrEmpty(optionalChildProp)) element = element.FindPropertyRelative(optionalChildProp); if (element != null && element.propertyType == SerializedPropertyType.ObjectReference) { element.objectReferenceValue = objs[i] as UnityEngine.Object; } } } catch (System.Exception ex) { Debug.LogException(ex); } } #endregion } }
412
0.958836
1
0.958836
game-dev
MEDIA
0.53657
game-dev
0.951339
1
0.951339
DimensionalDevelopment/VanillaFix
1,236
src/main/java/org/dimdev/vanillafix/bugs/mixins/MixinInventoryPlayer.java
package org.dimdev.vanillafix.bugs.mixins; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(InventoryPlayer.class) public class MixinInventoryPlayer { /** * Compare items by item type and meta rather than NBT when looking for items for the * crafting recipe. Note that the item is still checked (in findSlotMatchingUnusedItem) * to make sure it is not enchanted or renamed. If the recipe item has meta 32767, any * item meta is accepted (see Ingredient.apply). * <p> * Bugs fixed: * - https://bugs.mojang.com/browse/MC-129057 */ @Redirect(method = "findSlotMatchingUnusedItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/InventoryPlayer;stackEqualExact(Lnet/minecraft/item/ItemStack;Lnet/minecraft/item/ItemStack;)Z")) private boolean stackEqualExact(InventoryPlayer inventoryPlayer, ItemStack stack1, ItemStack stack2) { return stack1.getItem() == stack2.getItem() && (stack1.getMetadata() == 32767 || stack1.getMetadata() == stack2.getMetadata()); } }
412
0.855575
1
0.855575
game-dev
MEDIA
0.999126
game-dev
0.937539
1
0.937539
CampagneLaboratory/MetaR
9,943
languages/org.campagnelab.metar.limma/languageModels/editor.mps
<?xml version="1.0" encoding="UTF-8"?> <model ref="r:294dc9c3-90f3-4113-9114-56d2e56639b7(org.campagnelab.metar.limma.editor)"> <persistence version="9" /> <languages> <use id="18bc6592-03a6-4e29-a83a-7ff23bde13ba" name="jetbrains.mps.lang.editor" version="7" /> <devkit ref="fbc25dd2-5da4-483a-8b19-70928e1b62d7(jetbrains.mps.devkit.general-purpose)" /> </languages> <imports> <import index="8gqa" ref="r:c14853f5-5f2e-4acc-825a-4fec67caca67(org.campagnelab.metar.tables.editor)" /> <import index="jl4n" ref="r:a4155731-8795-49bc-afc5-bf36983f9c0c(org.campagnelab.metar.limma.structure)" implicit="true" /> <import index="qrzj" ref="r:33ebfe68-dd35-4984-bf5b-c6afb777446c(org.campagnelab.metar.models.structure)" implicit="true" /> </imports> <registry> <language id="18bc6592-03a6-4e29-a83a-7ff23bde13ba" name="jetbrains.mps.lang.editor"> <concept id="1071666914219" name="jetbrains.mps.lang.editor.structure.ConceptEditorDeclaration" flags="ig" index="24kQdi"> <child id="1078153129734" name="inspectedCellModel" index="6VMZX" /> </concept> <concept id="1237303669825" name="jetbrains.mps.lang.editor.structure.CellLayout_Indent" flags="nn" index="l2Vlx" /> <concept id="1237307900041" name="jetbrains.mps.lang.editor.structure.IndentLayoutIndentStyleClassItem" flags="ln" index="lj46D" /> <concept id="1142886221719" name="jetbrains.mps.lang.editor.structure.QueryFunction_NodeCondition" flags="in" index="pkWqt" /> <concept id="1142886811589" name="jetbrains.mps.lang.editor.structure.ConceptFunctionParameter_node" flags="nn" index="pncrf" /> <concept id="1237385578942" name="jetbrains.mps.lang.editor.structure.IndentLayoutOnNewLineStyleClassItem" flags="ln" index="pVoyu" /> <concept id="1080736578640" name="jetbrains.mps.lang.editor.structure.BaseEditorComponent" flags="ig" index="2wURMF"> <child id="1080736633877" name="cellModel" index="2wV5jI" /> </concept> <concept id="1186403751766" name="jetbrains.mps.lang.editor.structure.FontStyleStyleClassItem" flags="ln" index="Vb9p2" /> <concept id="1186414536763" name="jetbrains.mps.lang.editor.structure.BooleanStyleSheetItem" flags="ln" index="VOi$J"> <property id="1186414551515" name="flag" index="VOm3f" /> </concept> <concept id="1186414928363" name="jetbrains.mps.lang.editor.structure.SelectableStyleSheetItem" flags="ln" index="VPM3Z" /> <concept id="1381004262292414836" name="jetbrains.mps.lang.editor.structure.ICellStyle" flags="ng" index="1k5N5V"> <reference id="1381004262292426837" name="parentStyleClass" index="1k5W1q" /> </concept> <concept id="1139848536355" name="jetbrains.mps.lang.editor.structure.CellModel_WithRole" flags="ng" index="1$h60E"> <reference id="1140103550593" name="relationDeclaration" index="1NtTu8" /> </concept> <concept id="1073389214265" name="jetbrains.mps.lang.editor.structure.EditorCellModel" flags="ng" index="3EYTF0"> <child id="1142887637401" name="renderingCondition" index="pqm2j" /> </concept> <concept id="1073389446423" name="jetbrains.mps.lang.editor.structure.CellModel_Collection" flags="sn" stub="3013115976261988961" index="3EZMnI"> <child id="1106270802874" name="cellLayout" index="2iSdaV" /> <child id="1073389446424" name="childCellModel" index="3EZMnx" /> </concept> <concept id="1073389577006" name="jetbrains.mps.lang.editor.structure.CellModel_Constant" flags="sn" stub="3610246225209162225" index="3F0ifn"> <property id="1073389577007" name="text" index="3F0ifm" /> </concept> <concept id="1073389658414" name="jetbrains.mps.lang.editor.structure.CellModel_Property" flags="sg" stub="730538219796134133" index="3F0A7n" /> <concept id="1219418625346" name="jetbrains.mps.lang.editor.structure.IStyleContainer" flags="ng" index="3F0Thp"> <child id="1219418656006" name="styleItem" index="3F10Kt" /> </concept> <concept id="1073389882823" name="jetbrains.mps.lang.editor.structure.CellModel_RefNode" flags="sg" stub="730538219795960754" index="3F1sOY" /> <concept id="1166049232041" name="jetbrains.mps.lang.editor.structure.AbstractComponent" flags="ng" index="1XWOmA"> <reference id="1166049300910" name="conceptDeclaration" index="1XX52x" /> </concept> </language> <language id="f3061a53-9226-4cc5-a443-f952ceaf5816" name="jetbrains.mps.baseLanguage"> <concept id="1197027756228" name="jetbrains.mps.baseLanguage.structure.DotExpression" flags="nn" index="2OqwBi"> <child id="1197027771414" name="operand" index="2Oq$k0" /> <child id="1197027833540" name="operation" index="2OqNvi" /> </concept> <concept id="1137021947720" name="jetbrains.mps.baseLanguage.structure.ConceptFunction" flags="in" index="2VMwT0"> <child id="1137022507850" name="body" index="2VODD2" /> </concept> <concept id="1068580123155" name="jetbrains.mps.baseLanguage.structure.ExpressionStatement" flags="nn" index="3clFbF"> <child id="1068580123156" name="expression" index="3clFbG" /> </concept> <concept id="1068580123136" name="jetbrains.mps.baseLanguage.structure.StatementList" flags="sn" stub="5293379017992965193" index="3clFbS"> <child id="1068581517665" name="statement" index="3cqZAp" /> </concept> </language> <language id="7866978e-a0f0-4cc7-81bc-4d213d9375e1" name="jetbrains.mps.lang.smodel"> <concept id="1138056022639" name="jetbrains.mps.lang.smodel.structure.SPropertyAccess" flags="nn" index="3TrcHB"> <reference id="1138056395725" name="property" index="3TsBF5" /> </concept> </language> </registry> <node concept="24kQdi" id="4ssfE$82mdM"> <ref role="1XX52x" to="jl4n:7$n2ViPrAVb" resolve="LimmaVoom" /> <node concept="3EZMnI" id="7$n2ViPs1kx" role="2wV5jI"> <node concept="3F0ifn" id="7$n2ViPs1kC" role="3EZMnx"> <property role="3F0ifm" value="limma voom" /> </node> <node concept="3F0ifn" id="7$n2ViPs1kI" role="3EZMnx"> <property role="3F0ifm" value="counts=" /> <ref role="1k5W1q" to="8gqa:7Hltlm8H6Z1" resolve="Descriptive" /> </node> <node concept="3F1sOY" id="7$n2ViPs1ln" role="3EZMnx"> <ref role="1NtTu8" to="jl4n:7$n2ViPrDvn" resolve="countsTable" /> </node> <node concept="3F0ifn" id="7$n2ViPs1lx" role="3EZMnx"> <property role="3F0ifm" value="model:" /> <ref role="1k5W1q" to="8gqa:7Hltlm8H6Z1" resolve="Descriptive" /> </node> <node concept="3F1sOY" id="7$n2ViPs1lH" role="3EZMnx"> <ref role="1NtTu8" to="qrzj:4ssfE$85c87" resolve="modelFormula" /> </node> <node concept="3F0ifn" id="7$n2ViPs1lV" role="3EZMnx"> <property role="3F0ifm" value="comparing" /> <ref role="1k5W1q" to="8gqa:7Hltlm8H6Z1" resolve="Descriptive" /> <node concept="pVoyu" id="7$n2ViPwM0I" role="3F10Kt"> <property role="VOm3f" value="true" /> </node> <node concept="lj46D" id="7$n2ViPwM0K" role="3F10Kt"> <property role="VOm3f" value="true" /> </node> </node> <node concept="3F1sOY" id="7$n2ViPwM11" role="3EZMnx"> <ref role="1NtTu8" to="qrzj:4ssfE$85cdC" resolve="contrasts" /> </node> <node concept="3F0ifn" id="7$n2ViPwM1S" role="3EZMnx"> <property role="3F0ifm" value="-&gt;" /> </node> <node concept="3F0ifn" id="1EG$v9O8LYU" role="3EZMnx"> <property role="3F0ifm" value="stats:" /> <node concept="Vb9p2" id="1EG$v9O8M3u" role="3F10Kt" /> </node> <node concept="3F1sOY" id="7$n2ViPs1mb" role="3EZMnx"> <ref role="1NtTu8" to="jl4n:7$n2ViPrFPR" resolve="destinationTable" /> </node> <node concept="3F0ifn" id="1EG$v9O8M6w" role="3EZMnx"> <property role="3F0ifm" value="normalized:" /> <node concept="Vb9p2" id="1EG$v9O8M9E" role="3F10Kt" /> </node> <node concept="3F1sOY" id="1EG$v9O8uk_" role="3EZMnx"> <ref role="1NtTu8" to="jl4n:1EG$v9O8udR" resolve="normalizedTable" /> </node> <node concept="3EZMnI" id="4ssfE$9PSsp" role="3EZMnx"> <node concept="VPM3Z" id="4ssfE$9PSsr" role="3F10Kt"> <property role="VOm3f" value="false" /> </node> <node concept="3F0ifn" id="4ssfE$9PSst" role="3EZMnx"> <property role="3F0ifm" value="adjusted counts:" /> <ref role="1k5W1q" to="8gqa:7Hltlm8H6Z1" resolve="Descriptive" /> </node> <node concept="3F1sOY" id="4ssfE$9PTHw" role="3EZMnx"> <ref role="1NtTu8" to="jl4n:4ssfE$9PTBv" resolve="adjustedCountsTable" /> </node> <node concept="l2Vlx" id="4ssfE$9PSsu" role="2iSdaV" /> <node concept="pkWqt" id="4ssfE$9PSsM" role="pqm2j"> <node concept="3clFbS" id="4ssfE$9PSsN" role="2VODD2"> <node concept="3clFbF" id="4ssfE$9PSxH" role="3cqZAp"> <node concept="2OqwBi" id="4ssfE$9PSBl" role="3clFbG"> <node concept="pncrf" id="4ssfE$9PSxG" role="2Oq$k0" /> <node concept="3TrcHB" id="4ssfE$9PTxk" role="2OqNvi"> <ref role="3TsBF5" to="jl4n:4ssfE$9PSrH" resolve="exportAdjustedCounts" /> </node> </node> </node> </node> </node> </node> <node concept="l2Vlx" id="7$n2ViPs1k$" role="2iSdaV" /> </node> <node concept="3EZMnI" id="4ssfE$9PSrA" role="6VMZX"> <node concept="3F0ifn" id="4ssfE$9PSrO" role="3EZMnx"> <property role="3F0ifm" value="export adjusted counts table" /> </node> <node concept="3F0A7n" id="4ssfE$9PSrU" role="3EZMnx"> <ref role="1NtTu8" to="jl4n:4ssfE$9PSrH" resolve="exportAdjustedCounts" /> </node> <node concept="l2Vlx" id="4ssfE$9PSrD" role="2iSdaV" /> </node> </node> </model>
412
0.840977
1
0.840977
game-dev
MEDIA
0.425373
game-dev
0.580158
1
0.580158
matrix-construct/construct
2,444
modules/m_profile.cc
// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2019 Jason Volk <jason@zemos.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. using namespace ircd; static void _rejoin_room(const m::room &room, const m::user &user); static void _rejoin_rooms(const m::user::id &user_id); static void handle_my_profile_changed__displayname(const m::event &event); static void handle_my_profile_changed__avatar_url(const m::event &event); static void handle_my_profile_changed(const m::event &, m::vm::eval &); mapi::header IRCD_MODULE { "Matrix profile." }; m::hookfn<m::vm::eval &> my_profile_changed { handle_my_profile_changed, { { "_site", "vm.effect" }, { "type", "ircd.profile" }, { "origin", my_host() }, } }; void handle_my_profile_changed(const m::event &event, m::vm::eval &eval) { const m::user::id &user_id { json::get<"sender"_>(event) }; if(!my(event) || !my(user_id)) return; // The event has to be an ircd.profile in the user's room, not just a // random ircd.profile typed event in some other room... const m::user::room user_room{user_id}; if(json::get<"room_id"_>(event) != user_room.room_id) return; if(json::get<"state_key"_>(event) == "displayname") return handle_my_profile_changed__displayname(event); if(json::get<"state_key"_>(event) == "avatar_url") return handle_my_profile_changed__avatar_url(event); } void handle_my_profile_changed__avatar_url(const m::event &event) { _rejoin_rooms(at<"sender"_>(event)); } void handle_my_profile_changed__displayname(const m::event &event) { _rejoin_rooms(at<"sender"_>(event)); } void _rejoin_rooms(const m::user::id &user_id) { assert(my(user_id)); const m::user::rooms &rooms { user_id }; rooms.for_each("join", [&user_id] (const m::room &room, const string_view &) { _rejoin_room(room, user_id); }); } void _rejoin_room(const m::room &room, const m::user &user) try { m::join(room, user); } catch(const std::exception &e) { log::error { "Failed to rejoin '%s' to room '%s' to update profile", string_view{user.user_id}, string_view{room.room_id} }; }
412
0.93874
1
0.93874
game-dev
MEDIA
0.234988
game-dev
0.960932
1
0.960932
mmalka/TheNoobBot
16,229
The Noob Bot/nManager/nManagerSetting.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Xml.Serialization; using nManager.Helpful; using nManager.Wow.Bot.States; using nManager.Wow.Class; using nManager.Wow.Enums; using nManager.Wow.Helpers; using nManager.Wow.Helpers.PathFinderClass; using nManager.Wow.MemoryClass; using nManager.Wow.ObjectManager; using Usefuls = nManager.Wow.Helpers.Usefuls; namespace nManager { [Serializable] // ReSharper disable InconsistentNaming public class nManagerSetting : Settings // ReSharper restore InconsistentNaming { private static nManagerSetting _currentSetting; private static string _lastName = ""; public static bool ActivateProductTipOff = true; public static bool AutoStartProduct = false; public static string AutoStartProductName = ""; public static string AutoStartProfileName = ""; public static string AutoStartEmail = ""; public static string AutoStartRealmName = ""; public static string AutoStartBattleNet = ""; public static string AutoStartCharacter = ""; public static string AutoStartPassword = ""; public static bool AutoStartLoggingInfoProvided = false; public static nManagerSetting CurrentSetting { get { if (_currentSetting == null || ObjectManager.Me.Name != _lastName && Usefuls.InGame) { Load(); _lastName = ObjectManager.Me.Name; } return _currentSetting; } set { _currentSetting = value; } } #region BlackListGuid private static readonly Dictionary<UInt128, int> _blackListGuidByTime = new Dictionary<UInt128, int>(); public static bool IsBlackListed(UInt128 guid) { try { if (_blackListGuidByTime.ContainsKey(guid)) { return ((_blackListGuidByTime[guid] >= Others.Times) || _blackListGuidByTime[guid] == -1); } return false; } catch (Exception e) { Logging.WriteError("IsBlackListed(UInt128 guid): " + e); return false; } } public static List<UInt128> GetListGuidBlackListed() { try { List<UInt128> ret = new List<UInt128>(); foreach (KeyValuePair<UInt128, int> i in _blackListGuidByTime) { if (i.Value == -1 || i.Value <= Others.Times) ret.Add(i.Key); } return ret; } catch (Exception e) { Logging.WriteError("GetListGuidBlackListed(): " + e); return new List<UInt128>(); } } public static void AddBlackList(UInt128 guid, int timeInMilisec = -1) { try { if (Information.DevMode) Logging.WriteDebug("Blacklist (" + guid + ") for " + timeInMilisec + "ms from " + Hook.CurrentCallStack); if (_blackListGuidByTime.ContainsKey(guid)) _blackListGuidByTime.Remove(guid); if (timeInMilisec >= 0) timeInMilisec = timeInMilisec + Others.Times; _blackListGuidByTime.Add(guid, timeInMilisec); } catch (Exception e) { Logging.WriteError("AddBlackList(UInt128 guid, int timeInMilisec = -1): " + e); } } #endregion #region AvoidZone public class DangerousZone { protected bool Equals(DangerousZone other) { return Equals(Position, other.Position) && string.Equals(ContinentId, other.ContinentId); } public override int GetHashCode() { unchecked { int hashCode = (Position != null ? Position.GetHashCode() : 0); hashCode = (hashCode*397) ^ Radius.GetHashCode(); hashCode = (hashCode*397) ^ (ContinentId != null ? ContinentId.GetHashCode() : 0); hashCode = (hashCode*397) ^ TileX.GetHashCode(); hashCode = (hashCode*397) ^ TileY.GetHashCode(); return hashCode; } } public Point Position { get; private set; } public float Radius { get; private set; } public string ContinentId { get; private set; } public float TileX { get; private set; } public float TileY { get; private set; } public DangerousZone(WoWUnit dangerousUnit) { try { if (dangerousUnit == null || !dangerousUnit.IsValid || !dangerousUnit.IsAlive) return; Position = dangerousUnit.Position; Radius = dangerousUnit.AggroDistance; ContinentId = Usefuls.ContinentNameMpq; float x, y; PathFinder.GetTileByPosition(Position, out x, out y, ContinentId); TileX = x; TileY = y; } catch (Exception exception) { Logging.WriteError("public DangerousZone(WoWUnit dangerousUnit): " + exception); } } public DangerousZone(Point position, float radius, string cId = "") { try { Position = position; Radius = radius; if (string.IsNullOrEmpty(cId)) cId = Usefuls.ContinentNameMpq; ContinentId = cId; float x, y; PathFinder.GetTileByPosition(Position, out x, out y, ContinentId); TileX = x; TileY = y; } catch (Exception exception) { Logging.WriteError("public DangerousZone(Point position, float radius, string cId = \"\"): " + exception); } } } public static List<DangerousZone> DangerousZones = new List<DangerousZone>(); public static bool IsBlackListedZone(Point position, string cId = "") { try { if (string.IsNullOrEmpty(cId)) cId = Usefuls.ContinentNameMpq; foreach (var zone in DangerousZones) { if (zone.ContinentId != cId) continue; if (position.DistanceTo(zone.Position) <= zone.Radius && position.DistanceTo(ObjectManager.Me.Position) > 6f) return true; } return false; } catch (Exception e) { Logging.WriteError("IsBlackListedZone(Point position): " + e); return false; } } public static void AddBlackListZone(Point position, float radius, string continent = "") { try { if (string.IsNullOrEmpty(continent)) continent = Usefuls.ContinentNameMpq; if (IsBlackListedZone(position, continent)) return; var danger = new DangerousZone(position, radius, continent); DangerousZones.Add(danger); if (continent == Usefuls.ContinentNameMpq) PathFinder.AddDangerousZone(danger); } catch (Exception e) { Logging.WriteError("AddBlackListZone(Point position, float radius): " + e); } } public static void AddBlackListZone(WoWUnit unit) { try { var danger = new DangerousZone(unit); if (IsBlackListedZone(danger.Position, danger.ContinentId)) return; DangerousZones.Add(danger); if (danger.ContinentId == Usefuls.ContinentNameMpq) PathFinder.AddDangerousZone(danger); } catch (Exception e) { Logging.WriteError("AddBlackListZone(WoWUnit unit): " + e); } } public static void AddRangeBlackListZone(List<BlackListZone> listBlackZone) { try { foreach (var zone in listBlackZone) { AddBlackListZone(zone.Position, zone.Radius, zone.ContinentId); } } catch (Exception e) { Logging.WriteError("AddRangeBlackListZone(List<BlackListZone> listBlackZone): " + e); } } [Serializable] public class BlackListZone { public Point Position = new Point(); [DefaultValue(5.0f)] public float Radius = 5.0f; [DefaultValue("")] public string ContinentId = ""; } #endregion // ---------------------- public bool Save() { try { return Save(AdviserFilePathAndName("General")); } catch (Exception e) { Logging.WriteError("nManagerSetting > Save(): " + e); return false; } } public static bool Load() { try { if (File.Exists(AdviserFilePathAndName("General"))) { CurrentSetting = Load<nManagerSetting>(AdviserFilePathAndName("General")); return true; } CurrentSetting = new nManagerSetting(); } catch (Exception e) { Logging.WriteError("nManagerSetting > Load(): " + e); } return false; } // Special DamageDealer: public bool ActivateAutoFacingDamageDealer = false; public bool ActivateMovementsDamageDealer = false; // Special HealerBot: public bool ActivateAutoFacingHealerBot = false; public bool ActivateMovementsHealerBot = false; // Global Settings: public string LastProductLoaded; public string CombatClass = "OfficialTnbClassSelector"; public string HealerClass = "Tnb_HealerClass.dll"; public bool AutoAssignTalents; // To be fixed. public bool ActivateSkillsAutoTraining = true; public bool OnlyTrainCurrentlyUsedSkills = true; public bool TrainMountingCapacity = true; public bool OnlyTrainIfWeHave2TimesMoreMoneyThanOurWishListSum = true; public bool BecomeApprenticeIfNeededByProduct = false; public bool BecomeApprenticeOfSecondarySkillsWhileQuesting = false; public bool CanPullUnitsAlreadyInFight = true; public bool DontPullMonsters; public bool UseSpiritHealer; public bool UseGroundMount = true; public string GroundMountName = ""; public uint MinimumDistanceToUseMount = 15; public bool IgnoreFightIfMounted = true; public string FlyingMountName = ""; public string AquaticMountName = ""; public string FoodName = ""; public int EatFoodWhenHealthIsUnderXPercent = 35; public string BeverageName = ""; public int DrinkBeverageWhenManaIsUnderXPercent = 35; public bool DoRegenManaIfLow; public bool ActivateMonsterLooting = true; public bool ActivateLootStatistics = true; public bool ActivateChestLooting; public bool ActivateBeastSkinning = true; public bool BeastNinjaSkinning; public bool ActivateVeinsHarvesting = true; public bool ActivateHerbsHarvesting = true; public float DontHarvestIfPlayerNearRadius = 0; public int DontHarvestIfMoreThanXUnitInAggroRange = 4; public float GatheringSearchRadius = 70; public bool HarvestDuringLongDistanceMovements; public bool ActivateAutoSmelting; public bool ActivateAutoProspecting; public bool OnlyUseProspectingInTown; public int TimeBetweenEachProspectingAttempt = 15; public List<string> MineralsToProspect = new List<string>(); public bool ActivateAutoMilling; public bool OnlyUseMillingInTown; public int TimeBetweenEachMillingAttempt = 15; public List<string> HerbsToBeMilled = new List<string>(); public List<string> DontHarvestTheFollowingObjects = new List<string>(); public bool MakeStackOfElementalsItems = true; public bool ActivateReloggerFeature; public string EmailOfTheBattleNetAccount = ""; public string PasswordOfTheBattleNetAccount = ""; public string BattleNetSubAccount = ""; public int NumberOfFoodsWeGot; // TODO Count the items instead (!?) public int NumberOfBeverageWeGot; // TODO Count the items instead (!?) public bool ActivateAutoRepairFeature = true; public bool ActivateAutoSellingFeature = true; public bool SellGray = true; public bool SellWhite = true; public bool SellGreen; public bool SellBlue; public bool SellPurple; public List<string> DontSellTheseItems = new List<string>(); public List<string> ForceToSellTheseItems = new List<string>(); public bool ActivateAutoMaillingFeature; public string MaillingFeatureRecipient = ""; public string MaillingFeatureSubject = "Hey"; public bool MailGray; public bool MailWhite = true; public bool MailGreen = true; public bool MailBlue = true; public bool MailPurple = true; public List<string> DontMailTheseItems = new List<string>(); public List<string> ForceToMailTheseItems = new List<string>(); public bool StopTNBIfBagAreFull; public bool StopTNBIfHonorPointsLimitReached; public bool StopTNBIfPlayerHaveBeenTeleported; public int StopTNBAfterXLevelup = 110; public int StopTNBIfReceivedAtMostXWhispers = 10; public int StopTNBAfterXStucks = 80; public int StopTNBAfterXMinutes = 1440; public bool PauseTNBIfNearByPlayer; public bool RecordWhispsInLogFiles = true; public bool PlayASongIfNewWhispReceived; public bool ActivatePathFindingFeature = true; public bool AllowTNBToSetYourMaxFps = true; public float MaxDistanceToGoToMailboxesOrNPCs = 4000; // PathFinder is much better now. public bool AutoConfirmOnBoPItems = true; public bool ActivateAlwaysOnTopFeature; public int RepairWhenDurabilityIsUnderPercent = 35; public int SendMailWhenLessThanXSlotLeft = 4; public int SellItemsWhenLessThanXSlotLeft = 4; public bool UseHearthstone; public bool ActiveStopTNBAfterXLevelup; public bool ActiveStopTNBAfterXMinutes; public bool ActiveStopTNBAfterXStucks; public bool ActiveStopTNBIfReceivedAtMostXWhispers; public bool UseMollE; public bool UseRobot; public bool AutoCloseChatFrame = true; public bool ActivateBroadcastingMimesis = false; public int BroadcastingPort = 6543; public List<string> ActivatedPluginsList = new List<string>(); public bool ActivatePluginsSystem = true; public bool LaunchExpiredPlugins = false; public bool HideSdkFiles = true; public bool UseFrameLock = false; public bool UseLootARange = true; public bool HideCharacterNameFromTitle = false; public bool ActivateSafeResurrectionSystem = true; public bool DontSellReagents = true; public bool DeactivateFlyingMount = false; public bool ActivateRegenerationSystem = true; } }
412
0.611351
1
0.611351
game-dev
MEDIA
0.879407
game-dev
0.967258
1
0.967258
DreamLife-Jianwei/Qt-Vtk
9,213
12_Vtk9ReadDicomDemoQmake/Vtk9/include/vtk-9.0/vtkOctreePointLocatorNode.h
/*========================================================================= Program: Visualization Toolkit Module: vtkOctreePointLocatorNode.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ /** * @class vtkOctreePointLocatorNode * @brief Octree node that has 8 children each of equal size * * * This class represents a single spatial region in a 3D axis octant * partitioning. It is intended to work efficiently with the * vtkOctreePointLocator and is not meant for general use. It is assumed * the region bounds some set of points. The ordering of the children is * (-x,-y,-z),(+x,-y,-z),(-x,+y,-z),(+x,+y,-z),(-x,-y,+z),(+x,-y,+z), * (-x,+y,+z),(+x,+y,+z). The portion of the domain assigned to an * octant is Min < x <= Max. * * @sa * vtkOctreePointLocator */ #ifndef vtkOctreePointLocatorNode_h #define vtkOctreePointLocatorNode_h #include "vtkCommonDataModelModule.h" // For export macro #include "vtkObject.h" class vtkCell; class vtkPlanesIntersection; class VTKCOMMONDATAMODEL_EXPORT vtkOctreePointLocatorNode : public vtkObject { public: vtkTypeMacro(vtkOctreePointLocatorNode, vtkObject); void PrintSelf(ostream& os, vtkIndent indent) override; static vtkOctreePointLocatorNode* New(); //@{ /** * Set/Get the number of points contained in this region. */ void SetNumberOfPoints(int numberOfPoints) { this->NumberOfPoints = numberOfPoints; } vtkGetMacro(NumberOfPoints, int); //@} //@{ /** * Set/Get the bounds of the spatial region represented by this node. * Caller allocates storage for 6-vector in GetBounds. */ void SetBounds(double xMin, double xMax, double yMin, double yMax, double zMin, double zMax); void SetBounds(const double b[6]) { this->SetBounds(b[0], b[1], b[2], b[3], b[4], b[5]); } void GetBounds(double* b) const; //@} //@{ /** * Set/Get the bounds of the points contained in this spatial region. * This may be smaller than the bounds of the region itself. * Caller allocates storage for 6-vector in GetDataBounds. */ void SetDataBounds(double xMin, double xMax, double yMin, double yMax, double zMin, double zMax); void GetDataBounds(double* b) const; //@} //@{ /** * Get a pointer to the 3 bound minima (xmin, ymin and zmin) or the * 3 bound maxima (xmax, ymax, zmax). Don't free this pointer. */ vtkGetMacro(MinBounds, double*); vtkGetMacro(MaxBounds, double*); //@} //@{ /** * Set the xmin, ymin and zmin value of the bounds of this region */ void SetMinBounds(double minBounds[3]) { this->MinBounds[0] = minBounds[0]; this->MinBounds[1] = minBounds[1]; this->MinBounds[2] = minBounds[2]; } //@} //@{ /** * Set the xmax, ymax and zmax value of the bounds of this region */ void SetMaxBounds(double maxBounds[3]) { this->MaxBounds[0] = maxBounds[0]; this->MaxBounds[1] = maxBounds[1]; this->MaxBounds[2] = maxBounds[2]; } //@} //@{ /** * Get a pointer to the 3 data bound minima (xmin, ymin and zmin) or the * 3 data bound maxima (xmax, ymax, zmax). Don't free this pointer. */ vtkGetMacro(MinDataBounds, double*); vtkGetMacro(MaxDataBounds, double*); //@} //@{ /** * Set the xmin, ymin and zmin value of the bounds of this * data within this region. */ void SetMinDataBounds(double minDataBounds[3]) { this->MinDataBounds[0] = minDataBounds[0]; this->MinDataBounds[1] = minDataBounds[1]; this->MinDataBounds[2] = minDataBounds[2]; } //@} //@{ /** * Set the xmax, ymax and zmax value of the bounds of this * data within this region. */ void SetMaxDataBounds(double maxDataBounds[3]) { this->MaxDataBounds[0] = maxDataBounds[0]; this->MaxDataBounds[1] = maxDataBounds[1]; this->MaxDataBounds[2] = maxDataBounds[2]; } //@} //@{ /** * Get the ID associated with the region described by this node. If * this is not a leaf node, this value should be -1. */ vtkGetMacro(ID, int); //@} //@{ /** * If this node is not a leaf node, there are leaf nodes below it whose * regions represent a partitioning of this region. The IDs of these * leaf nodes form a contiguous set. Get the first of the first point's * ID that is contained in this node. */ vtkGetMacro(MinID, int); //@} /** * Add the 8 children. */ void CreateChildNodes(); /** * Delete the 8 children. */ void DeleteChildNodes(); /** * Get a pointer to the ith child of this node. */ vtkOctreePointLocatorNode* GetChild(int i); /** * A vtkPlanesIntersection object represents a convex 3D region bounded * by planes, and it is capable of computing intersections of * boxes with itself. Return 1 if this spatial region intersects * the spatial region described by the vtkPlanesIntersection object. * Use the possibly smaller bounds of the points within the region * if useDataBounds is non-zero. */ int IntersectsRegion(vtkPlanesIntersection* pi, int useDataBounds); /** * Return 1 if this spatial region entirely contains the given point. * Use the possibly smaller bounds of the points within the region * if useDataBounds is non-zero. */ vtkTypeBool ContainsPoint(double x, double y, double z, int useDataBounds); /** * Calculate the distance squared from any point to the boundary of this * region. Use the boundary of the points within the region if useDataBounds * is non-zero. */ double GetDistance2ToBoundary( double x, double y, double z, vtkOctreePointLocatorNode* top, int useDataBounds); /** * Calculate the distance squared from any point to the boundary of this * region. Use the boundary of the points within the region if useDataBounds * is non-zero. Set boundaryPt to the point on the boundary. */ double GetDistance2ToBoundary(double x, double y, double z, double* boundaryPt, vtkOctreePointLocatorNode* top, int useDataBounds); /** * Calculate the distance from the specified point (which is required to * be inside this spatial region) to an interior boundary. An interior * boundary is one that is not also an boundary of the entire space * partitioned by the tree of vtkOctreePointLocatorNode's. */ double GetDistance2ToInnerBoundary(double x, double y, double z, vtkOctreePointLocatorNode* top); /** * Return the id of the suboctant that a given point is in. * If CheckContainment is non-zero then it checks whether * the point is in the actual bounding box of the suboctant, * otherwise it only checks which octant the point is in * that is created from the axis-aligned partitioning of * the domain at this octant's center. */ int GetSubOctantIndex(double* point, int CheckContainment); /** * Recursive function to compute ID, MinVal, MaxVal, and MinID. * Parent is used for MinVal and MaxVal in the case that no * points are in the leaf node. */ void ComputeOctreeNodeInformation( vtkOctreePointLocatorNode* Parent, int& NextLeafId, int& NextMinId, float* coordinates); protected: vtkOctreePointLocatorNode(); ~vtkOctreePointLocatorNode() override; private: double _GetDistance2ToBoundary(double x, double y, double z, double* boundaryPt, int innerBoundaryOnly, vtkOctreePointLocatorNode* top, int useDataBounds); /** * The minimum coordinate location of the node. */ double MinBounds[3]; /** * The maximum coordinate location of the node. */ double MaxBounds[3]; /** * The minimum coordinate location of the points contained * within this node. */ double MinDataBounds[3]; /** * The maximum coordinate location of the points contained * within this node. */ double MaxDataBounds[3]; /** * Get the number of points associated with this octant. * The octant does not have to be a leaf octant. For example, * for the root octant NumberOfPoints is equal to the number * of points in the dataset. */ int NumberOfPoints; /** * A pointer to the 8 children of this node. */ vtkOctreePointLocatorNode** Children; /** * The ID of this octant. If it is not a leaf octant then ID=-1. */ int ID; /** * The minimum Id of the ordered points in this octant (note that * this Id is different than the vtkIdType used for referencing * the point in the data set. */ int MinID; vtkOctreePointLocatorNode(const vtkOctreePointLocatorNode&) = delete; void operator=(const vtkOctreePointLocatorNode&) = delete; }; #endif
412
0.970949
1
0.970949
game-dev
MEDIA
0.327502
game-dev
0.990116
1
0.990116
sn-lab/MouseGoggles
9,629
Godot/MouseVR Godot Project V1.0/linearTrackScene.gd
extends Spatial #track parameters export var mouse_num = 1 #ID of mouse (determines which reward loc/track num to use) export var num_rewards_out_of_10 = 10 #number of trials (per 10) which are rewarded (randomly) export var lick_in_reward_required = 0 #whether the mouse has to lick in the reward zone first in order to be rewarded export var scene_name = "lineartrack" export var track_length = 1.5 export var track_width = 0.1 export var num_reps = 40 #max number of trials export var trial_duration = 60 #max duration of each trial export var reward_dur = 0.05 #duration to open liquid reward valve) export var mouse_num_reward_loc := [-0.25, -0.25, 0.25, 0.25, 0.25] #for mouse [1 2 3 4 5] export var mouse_num_track_num := [2, 2, 2, 2, 2] #for mouse [1 2 3 4 5] export var track1_xpos = 0 #center x of linear track export var track2_xpos = 0.5 export var guaranteed_rewards = 3 #number of beginning trials to guarantee rewards export var track_reward_range = 0.2 #size of reward zone after reward location start #eye parameters export var inter_eye_distance = 0.01 export var head_radius = 0.04 #must be large enough to keep eye cameras from getting too close to walls export var eye_pitch = 10 #degrees from the horizontal export var eye_yaw = 45 #degrees away from the head yaw export var max_yaw = 0 #amount of yaw turning allowed #movement parameters export var frames_per_second = 60.0 export var thrust_gain = -0.01 #meters per step export var slip_gain = 0.01 #meters per step export var yaw_gain = 5 #degrees per step export var mouse_gain = 0.0135 #viewport nodes onready var lefthead = get_node("HeadKinBody/Control/HBoxContainer/ViewportContainer/TextureRect/Viewport/LeftEyeBody") onready var righthead = get_node("HeadKinBody/Control/HBoxContainer/ViewportContainer2/TextureRect/Viewport/RightEyeBody") onready var lefteye = get_node("HeadKinBody/Control/HBoxContainer/ViewportContainer/TextureRect/Viewport/LeftEyeBody/LeftEyePivot") onready var righteye = get_node("HeadKinBody/Control/HBoxContainer/ViewportContainer2/TextureRect/Viewport/RightEyeBody/RightEyePivot") onready var colorrect = get_node("HeadKinBody/Control/HBoxContainer/ViewportContainer/ColorRect") onready var fpslabel = get_node("HeadKinBody/Control/HBoxContainer/ViewportContainer2/Label") #head/eye position variables var head_yaw = 0 #degrees; 0 points along -z; 90 points to +x var head_thrust = 0 #+ points to -z var head_slip = 0 #+ points to +x var head_x = 0 var head_z = 0 var head_y = 0 var head_yaw_angle = 0 var starting_head_yaw = 180 var LeftEyeDirection = Vector3.ZERO #direction the left eye is pointing var RightEyeDirection = Vector3.ZERO # #logging/saving stuff var reward_order := [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] var scene_duration = 0 #max duration of the scene var track_num = 0 var track_xpos = 0 var track_reward_loc = 0 var current_rep = 1 var rewarded = 0 var reward_trial = 1 var rewarded_frame = 0 var reward_out = 0 var lick_in = 0 var times := [] # Timestamps of frames rendered in the last second var fps := 0 # Frames per second var current_frame = 0 var dataNames = ['head_yaw', 'head_thrust', 'head_slip', 'head_x', 'head_z', 'head_yaw_angle', 'reward_out', 'lick_in', 'ms_now'] var dataArray := [] var dataLog := [] var timestamp = "_" var ms_start := OS.get_ticks_msec() var ms_now := OS.get_ticks_msec() # Called when the node enters the scene tree for the first time. func _ready(): var td = OS.get_datetime() # time dictionary ms_start = OS.get_ticks_msec() timestamp = String(td.year) + "_" + String(td.month) + "_" + String(td.day) + "_" + String(td.hour) + "_" + String(td.minute) + "_" + String(td.second) #determine whether to reward randomize() for i in range(num_rewards_out_of_10): reward_order[i] = 1 reward_order.shuffle() reward_trial = reward_order[current_rep] if reward_trial || guaranteed_rewards>0: print("rep " + String(current_rep)) reward_trial = 1 else: print("rep " + String(current_rep) + " (no reward)") track_reward_loc = mouse_num_reward_loc[mouse_num-1] track_num = mouse_num_track_num[mouse_num-1] if track_num==1: track_xpos = track1_xpos; if track_num==2: track_xpos = track2_xpos; #head positions head_y = head_radius head_yaw_angle = starting_head_yaw head_x = track_xpos head_z = -(track_length/2) + head_radius rewarded = 0 scene_duration = num_reps*trial_duration #input setup Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(delta): #calculate fps (method 2) ms_now = OS.get_ticks_msec() - ms_start times.append(ms_now) while times.size() > 0 and times[0] <= ms_now - 1000: times.pop_front() # Remove frames older than 1 second in the `times` array fps = times.size() current_frame += 1 #calculate head angle head_yaw_angle += mouse_gain*yaw_gain*head_yaw #keep mouse facing forward? if head_yaw_angle>(starting_head_yaw+max_yaw): head_yaw_angle = starting_head_yaw+max_yaw if head_yaw_angle<(starting_head_yaw-max_yaw): head_yaw_angle = starting_head_yaw-max_yaw #calculate head position head_z += mouse_gain*(thrust_gain*head_thrust*cos(deg2rad(head_yaw_angle)) + slip_gain*head_slip*sin(deg2rad(head_yaw_angle))) # head_x += mouse_gain*(-thrust_gain*head_thrust*sin(deg2rad(head_yaw_angle)) + slip_gain*head_slip*cos(deg2rad(head_yaw_angle))) fpslabel.text = str(head_x) #keep head inside of linear track if head_z>((track_length/2)-head_radius): head_z = (track_length/2)-head_radius if head_z<(-(track_length/2)+head_radius): head_z = -(track_length/2)+head_radius if head_x>(track_xpos+(track_width/2)-head_radius): head_x = (track_xpos+(track_width/2)-head_radius) if head_x<(track_xpos-(track_width/2)+head_radius): head_x = (track_xpos-(track_width/2)+head_radius) #translate body position righthead.translation.z = head_z righthead.translation.x = head_x righthead.translation.y = head_y lefthead.translation.z = head_z lefthead.translation.x = head_x lefthead.translation.y = head_y #translate eyes relative to body lefteye.translation.z = head_z - inter_eye_distance*sin(deg2rad(head_yaw_angle)) lefteye.translation.x = head_x - inter_eye_distance*cos(deg2rad(head_yaw_angle)) righteye.translation.z = head_z + inter_eye_distance*sin(deg2rad(head_yaw_angle)) righteye.translation.x = head_x + inter_eye_distance*cos(deg2rad(head_yaw_angle)) #rotate eyes relative to body lefteye.rotation_degrees.y = -head_yaw_angle+eye_yaw lefteye.rotation_degrees.x = eye_pitch righteye.rotation_degrees.y = -head_yaw_angle-eye_yaw righteye.rotation_degrees.x = eye_pitch #control color button based on current position if reward_trial && (head_z>=track_reward_loc) && (head_z<=(track_reward_loc+track_reward_range)) && rewarded==0: if (current_rep<=guaranteed_rewards) || (lick_in_reward_required==0) || (lick_in>0): Input.start_joy_vibration(0,1,1,reward_dur) #for using xinput rumble output colorrect.color = Color(1, 1, 1) rewarded = 1 reward_out = 1 rewarded_frame = current_frame else: if reward_trial && (reward_out==1) && ((current_frame-rewarded_frame)>=(reward_dur*frames_per_second)): reward_out = 0 colorrect.color = Color(0, 0, 0) #log data dataArray = [head_yaw, head_thrust, head_slip, head_x, head_z, head_yaw_angle, reward_out, lick_in, ms_now] for i in range(dataArray.size()): dataLog.append(dataArray[i]) #update text label # fpslabel.text = str(fps) + " FPS" fpslabel.text = str(lick_in) # fpslabel.text = "" #reset inputs head_thrust = 0 head_slip = 0 head_yaw = 0 #next trial if (head_z == (track_length/2)-head_radius) || (current_frame > trial_duration*frames_per_second): save_logs(current_rep,dataLog,dataNames) #save current logged data to a new file dataLog = [] #clear saved data current_frame = 1 current_rep += 1 if (current_rep>num_reps): get_tree().quit() else: head_yaw_angle = 180 head_x = track_xpos head_z = -(track_length/2) + head_radius rewarded = 0 if (((current_rep-1)%10)==0): reward_order.shuffle() reward_trial = reward_order[(current_rep-1)%10] if reward_trial || current_rep<=guaranteed_rewards: print("rep " + String(current_rep)) reward_trial = 1 else: print("rep " + String(current_rep) + " (no reward)") func _input(ev): if ev is InputEventKey and ev.is_pressed(): if ev.scancode == KEY_ESCAPE: get_tree().quit() if ev is InputEventMouseMotion: head_yaw += ev.relative.x head_thrust += ev.relative.y if ev is InputEventMouseButton: if ev.is_pressed(): if ev.button_index == BUTTON_WHEEL_UP: head_slip += 1 if ev.button_index == BUTTON_WHEEL_DOWN: head_slip -= 1 if ev is InputEventJoypadMotion: if ev.get_axis()==2: lick_in = round(1000*ev.get_axis_value()); else: print("Unexpected button pressed: ",ev.get_button_index(),", ",Input.get_joy_button_string(ev.get_button_index())) func save_logs(current_rep,dataLog,dataNames): var file = File.new() var numColumns = dataNames.size() var numRows = dataLog.size()/numColumns var n = 0 if (file.open("res://logs//" + timestamp + "_" + scene_name + "_rep" + String(current_rep) + "_godotlogs.txt", File.WRITE)== OK): for i in range(numColumns): file.store_string(String(dataNames[i])) if i<(numColumns-1): file.store_string(",") file.store_string("\r") for l in range(numRows): for i in range(numColumns): file.store_string(String(dataLog[n])) if i<(numColumns-1): file.store_string(",") n = n+1 file.store_string("\r") file.close()
412
0.55365
1
0.55365
game-dev
MEDIA
0.777526
game-dev
0.810042
1
0.810042
spoutcraft/Spoutcraft
2,448
src/main/java/net/minecraft/src/FallbackResourceManager.java
package net.minecraft.src; import com.google.common.collect.Lists; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; public class FallbackResourceManager implements ResourceManager { public final List resourcePacks = new ArrayList(); private final MetadataSerializer frmMetadataSerializer; public FallbackResourceManager(MetadataSerializer par1MetadataSerializer) { this.frmMetadataSerializer = par1MetadataSerializer; } public void addResourcePack(ResourcePack par1ResourcePack) { this.resourcePacks.add(par1ResourcePack); } public Set getResourceDomains() { return null; } public Resource getResource(ResourceLocation par1ResourceLocation) throws IOException { ResourcePack var2 = null; ResourceLocation var3 = getLocationMcmeta(par1ResourceLocation); for (int var4 = this.resourcePacks.size() - 1; var4 >= 0; --var4) { ResourcePack var5 = (ResourcePack)this.resourcePacks.get(var4); if (var2 == null && var5.resourceExists(var3)) { var2 = var5; } if (var5.resourceExists(par1ResourceLocation)) { InputStream var6 = null; if (var2 != null) { var6 = var2.getInputStream(var3); } return new SimpleResource(par1ResourceLocation, var5.getInputStream(par1ResourceLocation), var6, this.frmMetadataSerializer); } } throw new FileNotFoundException(par1ResourceLocation.toString()); } public List getAllResources(ResourceLocation par1ResourceLocation) throws IOException { ArrayList var2 = Lists.newArrayList(); ResourceLocation var3 = getLocationMcmeta(par1ResourceLocation); Iterator var4 = this.resourcePacks.iterator(); while (var4.hasNext()) { ResourcePack var5 = (ResourcePack)var4.next(); if (var5.resourceExists(par1ResourceLocation)) { InputStream var6 = var5.resourceExists(var3) ? var5.getInputStream(var3) : null; var2.add(new SimpleResource(par1ResourceLocation, var5.getInputStream(par1ResourceLocation), var6, this.frmMetadataSerializer)); } } if (var2.isEmpty()) { throw new FileNotFoundException(par1ResourceLocation.toString()); } else { return var2; } } static ResourceLocation getLocationMcmeta(ResourceLocation par0ResourceLocation) { return new ResourceLocation(par0ResourceLocation.getResourceDomain(), par0ResourceLocation.getResourcePath() + ".mcmeta"); } }
412
0.922626
1
0.922626
game-dev
MEDIA
0.884212
game-dev
0.948399
1
0.948399
audulus/rui
6,793
src/views/text.rs
use crate::*; pub trait TextModifiers: View + Sized { fn font_size(self, size: u32) -> Text; fn color(self, color: Color) -> Text; fn max_width(self, max_width: f32) -> Text; } /// Struct for `text`. #[derive(Clone)] pub struct Text { text: String, size: u32, color: Color, max_width: Option<f32>, } impl Text { pub const DEFAULT_SIZE: u32 = 18; pub fn color(self, color: Color) -> Text { Text { text: self.text, size: self.size, color, max_width: self.max_width, } } } impl DynView for Text { fn draw(&self, _path: &mut IdPath, args: &mut DrawArgs) { let vger = &mut args.vger; let origin = vger .text_bounds(self.text.as_str(), self.size, self.max_width) .origin; vger.save(); vger.translate([-origin.x, -origin.y]); vger.text(self.text.as_str(), self.size, self.color, self.max_width); vger.restore(); } fn layout(&self, _path: &mut IdPath, args: &mut LayoutArgs) -> LocalSize { (args.text_bounds)(self.text.as_str(), self.size, None).size } fn hittest(&self, _path: &mut IdPath, _pt: LocalPoint, _cx: &mut Context) -> Option<ViewId> { None } fn access( &self, path: &mut IdPath, cx: &mut Context, nodes: &mut Vec<(accesskit::NodeId, accesskit::Node)>, ) -> Option<accesskit::NodeId> { let aid = cx.view_id(path).access_id(); let mut builder = accesskit::NodeBuilder::new(accesskit::Role::Label); builder.set_name(self.text.clone()); nodes.push((aid, builder.build())); Some(aid) } } impl TextModifiers for Text { fn font_size(self, size: u32) -> Self { Self { text: self.text, color: self.color, size, max_width: self.max_width, } } fn color(self, color: Color) -> Text { Text { text: self.text, size: self.size, color, max_width: self.max_width, } } fn max_width(self, max_width: f32) -> Text { Text { text: self.text, size: self.size, color: self.color, max_width: Some(max_width), } } } impl private::Sealed for Text {} /// Shows a string as a label (not editable). pub fn text(name: &str) -> Text { Text { text: String::from(name), size: Text::DEFAULT_SIZE, color: TEXT_COLOR, max_width: None, } } macro_rules! impl_text { ( $ty:ident ) => { impl DynView for $ty { fn draw(&self, _path: &mut IdPath, args: &mut DrawArgs) { let txt = &format!("{}", self); let vger = &mut args.vger; let origin = vger.text_bounds(txt, Text::DEFAULT_SIZE, None).origin; vger.save(); vger.translate([-origin.x, -origin.y]); vger.text(txt, Text::DEFAULT_SIZE, TEXT_COLOR, None); vger.restore(); } fn layout(&self, _path: &mut IdPath, args: &mut LayoutArgs) -> LocalSize { let txt = &format!("{}", self); (args.text_bounds)(txt, Text::DEFAULT_SIZE, None).size } fn access( &self, path: &mut IdPath, cx: &mut Context, nodes: &mut Vec<(accesskit::NodeId, accesskit::Node)>, ) -> Option<accesskit::NodeId> { let aid = cx.view_id(path).access_id(); let mut builder = accesskit::NodeBuilder::new(accesskit::Role::Label); builder.set_name(format!("{}", self)); nodes.push((aid, builder.build())); Some(aid) } } impl TextModifiers for $ty { fn font_size(self, size: u32) -> Text { Text { text: format!("{}", self), size, color: TEXT_COLOR, max_width: None, } } fn color(self, color: Color) -> Text { Text { text: format!("{}", self), size: Text::DEFAULT_SIZE, color, max_width: None, } } fn max_width(self, max_width: f32) -> Text { Text { text: format!("{}", self), size: Text::DEFAULT_SIZE, color: TEXT_COLOR, max_width: Some(max_width), } } } }; } // XXX: this used to be generic for any Display but // that was causing trouble with adding Clone to view. // Perhaps a rust wizard can figure out why. impl_text!(String); impl_text!(u32); impl_text!(i32); impl_text!(u64); impl_text!(i64); impl_text!(f32); impl_text!(f64); // XXX: Can't do impl_text!(&'static str) impl DynView for &'static str { fn draw(&self, _path: &mut IdPath, args: &mut DrawArgs) { let txt = &format!("{}", self); let vger = &mut args.vger; let origin = vger.text_bounds(txt, Text::DEFAULT_SIZE, None).origin; vger.save(); vger.translate([-origin.x, -origin.y]); vger.text(txt, Text::DEFAULT_SIZE, TEXT_COLOR, None); vger.restore(); } fn layout(&self, _path: &mut IdPath, args: &mut LayoutArgs) -> LocalSize { let txt = &format!("{}", self); (args.text_bounds)(txt, Text::DEFAULT_SIZE, None).size } fn access( &self, path: &mut IdPath, cx: &mut Context, nodes: &mut Vec<(accesskit::NodeId, accesskit::Node)>, ) -> Option<accesskit::NodeId> { let aid = cx.view_id(path).access_id(); let mut builder = accesskit::NodeBuilder::new(accesskit::Role::Label); builder.set_name(format!("{}", self)); nodes.push((aid, builder.build())); Some(aid) } } impl TextModifiers for &'static str { fn font_size(self, size: u32) -> Text { Text { text: format!("{}", self), size, color: TEXT_COLOR, max_width: None, } } fn color(self, color: Color) -> Text { Text { text: format!("{}", self), size: Text::DEFAULT_SIZE, color, max_width: None, } } fn max_width(self, max_width: f32) -> Text { Text { text: format!("{}", self), size: Text::DEFAULT_SIZE, color: TEXT_COLOR, max_width: Some(max_width), } } } impl<V> private::Sealed for V where V: std::fmt::Display {}
412
0.911035
1
0.911035
game-dev
MEDIA
0.607686
game-dev
0.914124
1
0.914124
FMXExpress/Firemonkey
3,698
Embarcadero/Rio/CPP/TestBed/Tests/Tiles.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef TILES_H #define TILES_H /// This stress tests the dynamic tree broad-phase. This also shows that tile /// based collision is _not_ smooth due to Box2D not knowing about adjacency. class Tiles : public Test { public: enum { e_count = 20 }; Tiles() { m_fixtureCount = 0; b2Timer timer; { float32 a = 0.5f; b2BodyDef bd; bd.position.y = -a; b2Body* ground = m_world->CreateBody(&bd); #if 1 int32 N = 200; int32 M = 10; b2Vec2 position; position.y = 0.0f; for (int32 j = 0; j < M; ++j) { position.x = -N * a; for (int32 i = 0; i < N; ++i) { b2PolygonShape shape; shape.SetAsBox(a, a, position, 0.0f); ground->CreateFixture(&shape, 0.0f); ++m_fixtureCount; position.x += 2.0f * a; } position.y -= 2.0f * a; } #else int32 N = 200; int32 M = 10; b2Vec2 position; position.x = -N * a; for (int32 i = 0; i < N; ++i) { position.y = 0.0f; for (int32 j = 0; j < M; ++j) { b2PolygonShape shape; shape.SetAsBox(a, a, position, 0.0f); ground->CreateFixture(&shape, 0.0f); position.y -= 2.0f * a; } position.x += 2.0f * a; } #endif } { float32 a = 0.5f; b2PolygonShape shape; shape.SetAsBox(a, a); b2Vec2 x(-7.0f, 0.75f); b2Vec2 y; b2Vec2 deltaX(0.5625f, 1.25f); b2Vec2 deltaY(1.125f, 0.0f); for (int32 i = 0; i < e_count; ++i) { y = x; for (int32 j = i; j < e_count; ++j) { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position = y; //if (i == 0 && j == 0) //{ // bd.allowSleep = false; //} //else //{ // bd.allowSleep = true; //} b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 5.0f); ++m_fixtureCount; y += deltaY; } x += deltaX; } } m_createTime = timer.GetMilliseconds(); } void Step(Settings* settings) { const b2ContactManager& cm = m_world->GetContactManager(); int32 height = cm.m_broadPhase.GetTreeHeight(); int32 leafCount = cm.m_broadPhase.GetProxyCount(); int32 minimumNodeCount = 2 * leafCount - 1; float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f)); g_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); m_textLine += DRAW_STRING_NEW_LINE; Test::Step(settings); g_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", m_createTime, m_fixtureCount); m_textLine += DRAW_STRING_NEW_LINE; //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; //if (m_stepCount == 400) //{ // tree->RebuildBottomUp(); //} } static Test* Create() { return new Tiles; } int32 m_fixtureCount; float32 m_createTime; }; #endif
412
0.875026
1
0.875026
game-dev
MEDIA
0.555218
game-dev
0.911299
1
0.911299
Isol4tion/HexTech-nightly
3,414
src/main/java/me/hextech/asm/mixins/freelook/CameraMixin.java
package me.hextech.asm.mixins.freelook; import me.hextech.mod.modules.impl.player.freelook.CameraState; import me.hextech.mod.modules.impl.player.freelook.FreeLook; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.Camera; import net.minecraft.entity.Entity; import net.minecraft.util.math.MathHelper; import net.minecraft.world.BlockView; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; @Mixin(value = {Camera.class}) public abstract class CameraMixin { @Shadow private float cameraY; @Unique private float lastUpdate; @Inject(method = {"update"}, at = {@At(value = "HEAD")}) private void onCameraUpdate(BlockView area, Entity focusedEntity, boolean thirdPerson, boolean inverseView, float tickDelta, CallbackInfo ci) { CameraState camera = FreeLook.INSTANCE.getCameraState(); if (camera.doLock) { float limitNegativeYaw = camera.originalYaw() - 180.0f; float limitPositiveYaw = camera.originalYaw() + 180.0f; if (camera.lookYaw > limitPositiveYaw) { camera.lookYaw = limitPositiveYaw; } if (camera.lookYaw < limitNegativeYaw) { camera.lookYaw = limitNegativeYaw; } } } @ModifyArgs(method = {"update"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/Camera;setRotation(FF)V")) private void modifyRotationArgs(Args args) { CameraState camera = FreeLook.INSTANCE.getCameraState(); if (camera.doLock) { float yaw = camera.lookYaw; float pitch = camera.lookPitch; if (MinecraftClient.getInstance().options.getPerspective().isFrontView()) { yaw -= 180.0f; pitch = -pitch; } args.set(0, (Object) Float.valueOf(yaw)); args.set(1, (Object) Float.valueOf(pitch)); } else if (camera.doTransition) { float delta = this.getCurrentTime() - this.lastUpdate; float steps = 1.2f; float speed = 2.0f; float yawDiff = camera.lookYaw - camera.originalYaw(); float pitchDiff = camera.lookPitch - camera.originalPitch(); float yawStep = speed * (yawDiff * steps); float pitchStep = speed * (pitchDiff * steps); float yaw = MathHelper.stepTowards(camera.lookYaw, camera.originalYaw(), yawStep * delta); float pitch = MathHelper.stepTowards(camera.lookPitch, camera.originalPitch(), pitchStep * delta); camera.lookYaw = yaw; camera.lookPitch = pitch; args.set(0, (Object) Float.valueOf(yaw)); args.set(1, (Object) Float.valueOf(pitch)); camera.doTransition = (int) camera.originalYaw() != (int) camera.lookYaw || (int) camera.originalPitch() != (int) camera.lookPitch; } this.lastUpdate = this.getCurrentTime(); } @Unique private float getCurrentTime() { return (float) ((double) System.nanoTime() * 1.0E-8); } }
412
0.717942
1
0.717942
game-dev
MEDIA
0.733556
game-dev
0.973197
1
0.973197
jorgejgnz/HPTK
3,826
Runtime/Physics/Extensions/LinealConstraint.cs
using HandPhysicsToolkit.Helpers; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; namespace HandPhysicsToolkit.Physics { public class LinealConstraint : TargetExtension { [Header("Linear limit")] public Transform maxDistance; public float spring = 100.0f; public float damper = 1.0f; public bool showLimitedAxis = true; [Header("Threshold")] public bool detectThreshold = false; public bool inverted = false; [Range(0.0f, 1.0f)] public float threshold = 0.5f; public float minTimeBetweenDetections = 0.5f; public UnityEvent onOverThreshold = new UnityEvent(); public UnityEvent onUnderThreshold = new UnityEvent(); SoftJointLimit limit = new SoftJointLimit(); SoftJointLimitSpring limitSpring = new SoftJointLimitSpring(); float togglingThresholdDetectionIn = 0.0f; ThresholdState thresholdState = ThresholdState.None; Vector3 worldLimitStart, worldLimitEnd; Vector3 closestToLine; float positionLerp; public sealed override void InitExtension(TargetConstraint t) { base.InitExtension(t); if (!maxDistance) { Debug.LogError("Missing reference to Max Distance"); return; } t.axis.position = t.connectedAnchor.position; t.axis.LookAt(maxDistance); t.setAxisWhenEnabled = true; t.SetAxis(t.axis.rotation); limit.limit = Vector3.Distance(t.connectedAnchor.position, maxDistance.position); t.joint.linearLimit = limit; } public override sealed void UpdateExtension(TargetConstraint t) { // Linear limit t.joint.xMotion = ConfigurableJointMotion.Locked; t.joint.yMotion = ConfigurableJointMotion.Locked; t.joint.zMotion = ConfigurableJointMotion.Limited; limitSpring.spring = spring; limitSpring.damper = damper; t.joint.linearLimitSpring = limitSpring; worldLimitStart = t.connectedAnchor.position - t.GetJointAxisWorldRotation() * Vector3.forward * limit.limit; worldLimitEnd = t.connectedAnchor.position + t.GetJointAxisWorldRotation() * Vector3.forward * limit.limit; if (showLimitedAxis) Debug.DrawLine(worldLimitStart, worldLimitEnd, Color.black); // Threshold detection if (detectThreshold) { if (togglingThresholdDetectionIn <= 0.0f) { closestToLine = BasicHelpers.NearestPointOnFiniteLine(worldLimitStart, worldLimitEnd, t.anchor.position); if (inverted) positionLerp = Vector3.Distance(worldLimitStart, closestToLine) / (limit.limit * 2.0f); else positionLerp = Vector3.Distance(worldLimitEnd, closestToLine) / (limit.limit * 2.0f); if (positionLerp > threshold && thresholdState != ThresholdState.Over) { togglingThresholdDetectionIn = minTimeBetweenDetections; thresholdState = ThresholdState.Over; onOverThreshold.Invoke(); } else if (positionLerp < threshold && thresholdState != ThresholdState.Under) { togglingThresholdDetectionIn = minTimeBetweenDetections; thresholdState = ThresholdState.Under; onUnderThreshold.Invoke(); } } else togglingThresholdDetectionIn -= Time.deltaTime; } } } }
412
0.863177
1
0.863177
game-dev
MEDIA
0.896499
game-dev
0.945109
1
0.945109
MemoriesOfTime/Nukkit-MOT
2,388
src/main/java/cn/nukkit/block/BlockConcretePowder.java
package cn.nukkit.block; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.DyeColor; /** * Created by CreeperFace on 2.6.2017. */ public class BlockConcretePowder extends BlockFallableMeta { public BlockConcretePowder() { super(0); } public BlockConcretePowder(int meta) { super(meta); } @Override public int getFullId() { return (getId() << DATA_BITS) + getDamage(); } @Override public int getId() { return CONCRETE_POWDER; } @Override public String getName() { return "Concrete Powder"; } @Override public double getResistance() { return 2.5; } @Override public double getHardness() { return 0.5; } @Override public int getToolType() { return ItemTool.TYPE_SHOVEL; } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { super.onUpdate(Level.BLOCK_UPDATE_NORMAL); for (int side = 1; side <= 5; side++) { Block block = this.getSide(BlockFace.fromIndex(side)); if (block.getId() == Block.WATER || block.getId() == Block.STILL_WATER) { this.level.setBlock(this, Block.get(Block.CONCRETE, this.getDamage()), true, true); } } return Level.BLOCK_UPDATE_NORMAL; } return 0; } @Override public boolean place(Item item, Block b, Block target, BlockFace face, double fx, double fy, double fz, Player player) { boolean concrete = false; for (int side = 1; side <= 5; side++) { Block block = this.getSide(BlockFace.fromIndex(side)); if (block.getId() == Block.WATER || block.getId() == Block.STILL_WATER) { concrete = true; break; } } if (concrete) { this.level.setBlock(this, Block.get(Block.CONCRETE, this.getDamage()), true, true); } else { this.level.setBlock(this, this, true, true); } return true; } @Override public BlockColor getColor() { return DyeColor.getByWoolData(getDamage()).getColor(); } }
412
0.939149
1
0.939149
game-dev
MEDIA
0.982734
game-dev
0.841258
1
0.841258
TheAnswer/Core3
1,643
MMOCoreORB/src/server/zone/objects/tangible/variables/SkillModMap.cpp
/* * SkillModMap.cpp * * Created on: Jan 31, 2012 * Author: xyborn */ #include "SkillModMap.h" SkillModMap::SkillModMap() { skillMods.setNoDuplicateInsertPlan(); skillMods.setNullValue(0); addSerializableVariables(); } SkillModMap::SkillModMap(const SkillModMap& smm) : Object(), Serializable(smm) { skillMods = smm.skillMods; addSerializableVariables(); } SkillModMap& SkillModMap::operator=(const SkillModMap& smm) { if (this == &smm) return *this; skillMods = smm.skillMods; return *this; } void SkillModMap::add(const SkillModMap* smm) { for (int i = 0; i < smm->size(); ++i) { const auto& entry = smm->skillMods.elementAt(i); skillMods.put(entry.getKey(), skillMods.get(entry.getKey()) + entry.getValue()); } } void SkillModMap::add(const VectorMap<String, int64>* map) { for (int i = 0; i < map->size(); ++i) { const auto& entry = map->elementAt(i); skillMods.put(entry.getKey(), skillMods.get(entry.getKey()) + entry.getValue()); } } void SkillModMap::subtract(const SkillModMap* smm) { for (int i = 0; i < smm->skillMods.size(); ++i) { const auto& entry = smm->skillMods.elementAt(i); int val = skillMods.get(entry.getKey()) - entry.getValue(); if (val <= 0) { skillMods.drop(entry.getKey()); } else { skillMods.put(entry.getKey(), val); } } } void SkillModMap::subtract(const VectorMap<String, int64>* map) { for (int i = 0; i < map->size(); ++i) { const auto& entry = map->elementAt(i); int val = skillMods.get(entry.getKey()) - entry.getValue(); if (val <= 0) { skillMods.drop(entry.getKey()); } else { skillMods.put(entry.getKey(), val); } } }
412
0.548046
1
0.548046
game-dev
MEDIA
0.700052
game-dev
0.933945
1
0.933945
lzk228/space-axolotl-14
19,906
Content.Shared/Damage/Systems/DamageableSystem.cs
using System.Linq; using Content.Shared.CCVar; using Content.Shared.Chemistry; using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; using Content.Shared.Inventory; using Content.Shared.Mind.Components; using Content.Shared.Mobs.Components; using Content.Shared.Mobs.Systems; using Content.Shared.Radiation.Events; using Content.Shared.Rejuvenate; using Robust.Shared.Configuration; using Robust.Shared.GameStates; using Robust.Shared.Network; using Robust.Shared.Prototypes; using Robust.Shared.Utility; namespace Content.Shared.Damage { public sealed class DamageableSystem : EntitySystem { [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly SharedAppearanceSystem _appearance = default!; [Dependency] private readonly INetManager _netMan = default!; [Dependency] private readonly MobThresholdSystem _mobThreshold = default!; [Dependency] private readonly IConfigurationManager _config = default!; [Dependency] private readonly SharedChemistryGuideDataSystem _chemistryGuideData = default!; private EntityQuery<AppearanceComponent> _appearanceQuery; private EntityQuery<DamageableComponent> _damageableQuery; private EntityQuery<MindContainerComponent> _mindContainerQuery; public float UniversalAllDamageModifier { get; private set; } = 1f; public float UniversalAllHealModifier { get; private set; } = 1f; public float UniversalMeleeDamageModifier { get; private set; } = 1f; public float UniversalProjectileDamageModifier { get; private set; } = 1f; public float UniversalHitscanDamageModifier { get; private set; } = 1f; public float UniversalReagentDamageModifier { get; private set; } = 1f; public float UniversalReagentHealModifier { get; private set; } = 1f; public float UniversalExplosionDamageModifier { get; private set; } = 1f; public float UniversalThrownDamageModifier { get; private set; } = 1f; public float UniversalTopicalsHealModifier { get; private set; } = 1f; public float UniversalMobDamageModifier { get; private set; } = 1f; public override void Initialize() { SubscribeLocalEvent<DamageableComponent, ComponentInit>(DamageableInit); SubscribeLocalEvent<DamageableComponent, ComponentHandleState>(DamageableHandleState); SubscribeLocalEvent<DamageableComponent, ComponentGetState>(DamageableGetState); SubscribeLocalEvent<DamageableComponent, OnIrradiatedEvent>(OnIrradiated); SubscribeLocalEvent<DamageableComponent, RejuvenateEvent>(OnRejuvenate); _appearanceQuery = GetEntityQuery<AppearanceComponent>(); _damageableQuery = GetEntityQuery<DamageableComponent>(); _mindContainerQuery = GetEntityQuery<MindContainerComponent>(); // Damage modifier CVars are updated and stored here to be queried in other systems. // Note that certain modifiers requires reloading the guidebook. Subs.CVar(_config, CCVars.PlaytestAllDamageModifier, value => { UniversalAllDamageModifier = value; _chemistryGuideData.ReloadAllReagentPrototypes(); }, true); Subs.CVar(_config, CCVars.PlaytestAllHealModifier, value => { UniversalAllHealModifier = value; _chemistryGuideData.ReloadAllReagentPrototypes(); }, true); Subs.CVar(_config, CCVars.PlaytestProjectileDamageModifier, value => UniversalProjectileDamageModifier = value, true); Subs.CVar(_config, CCVars.PlaytestMeleeDamageModifier, value => UniversalMeleeDamageModifier = value, true); Subs.CVar(_config, CCVars.PlaytestProjectileDamageModifier, value => UniversalProjectileDamageModifier = value, true); Subs.CVar(_config, CCVars.PlaytestHitscanDamageModifier, value => UniversalHitscanDamageModifier = value, true); Subs.CVar(_config, CCVars.PlaytestReagentDamageModifier, value => { UniversalReagentDamageModifier = value; _chemistryGuideData.ReloadAllReagentPrototypes(); }, true); Subs.CVar(_config, CCVars.PlaytestReagentHealModifier, value => { UniversalReagentHealModifier = value; _chemistryGuideData.ReloadAllReagentPrototypes(); }, true); Subs.CVar(_config, CCVars.PlaytestExplosionDamageModifier, value => UniversalExplosionDamageModifier = value, true); Subs.CVar(_config, CCVars.PlaytestThrownDamageModifier, value => UniversalThrownDamageModifier = value, true); Subs.CVar(_config, CCVars.PlaytestTopicalsHealModifier, value => UniversalTopicalsHealModifier = value, true); Subs.CVar(_config, CCVars.PlaytestMobDamageModifier, value => UniversalMobDamageModifier = value, true); } /// <summary> /// Initialize a damageable component /// </summary> private void DamageableInit(EntityUid uid, DamageableComponent component, ComponentInit _) { if (component.DamageContainerID != null && _prototypeManager.Resolve<DamageContainerPrototype>(component.DamageContainerID, out var damageContainerPrototype)) { // Initialize damage dictionary, using the types and groups from the damage // container prototype foreach (var type in damageContainerPrototype.SupportedTypes) { component.Damage.DamageDict.TryAdd(type, FixedPoint2.Zero); } foreach (var groupId in damageContainerPrototype.SupportedGroups) { var group = _prototypeManager.Index<DamageGroupPrototype>(groupId); foreach (var type in group.DamageTypes) { component.Damage.DamageDict.TryAdd(type, FixedPoint2.Zero); } } } else { // No DamageContainerPrototype was given. So we will allow the container to support all damage types foreach (var type in _prototypeManager.EnumeratePrototypes<DamageTypePrototype>()) { component.Damage.DamageDict.TryAdd(type.ID, FixedPoint2.Zero); } } component.Damage.GetDamagePerGroup(_prototypeManager, component.DamagePerGroup); component.TotalDamage = component.Damage.GetTotal(); } /// <summary> /// Directly sets the damage specifier of a damageable component. /// </summary> /// <remarks> /// Useful for some unfriendly folk. Also ensures that cached values are updated and that a damage changed /// event is raised. /// </remarks> public void SetDamage(EntityUid uid, DamageableComponent damageable, DamageSpecifier damage) { damageable.Damage = damage; DamageChanged(uid, damageable); } /// <summary> /// If the damage in a DamageableComponent was changed, this function should be called. /// </summary> /// <remarks> /// This updates cached damage information, flags the component as dirty, and raises a damage changed event. /// The damage changed event is used by other systems, such as damage thresholds. /// </remarks> public void DamageChanged(EntityUid uid, DamageableComponent component, DamageSpecifier? damageDelta = null, bool interruptsDoAfters = true, EntityUid? origin = null) { component.Damage.GetDamagePerGroup(_prototypeManager, component.DamagePerGroup); component.TotalDamage = component.Damage.GetTotal(); Dirty(uid, component); if (_appearanceQuery.TryGetComponent(uid, out var appearance) && damageDelta != null) { var data = new DamageVisualizerGroupData(component.DamagePerGroup.Keys.ToList()); _appearance.SetData(uid, DamageVisualizerKeys.DamageUpdateGroups, data, appearance); } RaiseLocalEvent(uid, new DamageChangedEvent(component, damageDelta, interruptsDoAfters, origin)); } /// <summary> /// Applies damage specified via a <see cref="DamageSpecifier"/>. /// </summary> /// <remarks> /// <see cref="DamageSpecifier"/> is effectively just a dictionary of damage types and damage values. This /// function just applies the container's resistances (unless otherwise specified) and then changes the /// stored damage data. Division of group damage into types is managed by <see cref="DamageSpecifier"/>. /// </remarks> /// <returns> /// Returns a <see cref="DamageSpecifier"/> with information about the actual damage changes. This will be /// null if the user had no applicable components that can take damage. /// </returns> public DamageSpecifier? TryChangeDamage(EntityUid? uid, DamageSpecifier damage, bool ignoreResistances = false, bool interruptsDoAfters = true, DamageableComponent? damageable = null, EntityUid? origin = null) { if (!uid.HasValue || !_damageableQuery.Resolve(uid.Value, ref damageable, false)) { // TODO BODY SYSTEM pass damage onto body system return null; } if (damage.Empty) { return damage; } var before = new BeforeDamageChangedEvent(damage, origin); RaiseLocalEvent(uid.Value, ref before); if (before.Cancelled) return null; // Apply resistances if (!ignoreResistances) { if (damageable.DamageModifierSetId != null && _prototypeManager.Resolve<DamageModifierSetPrototype>(damageable.DamageModifierSetId, out var modifierSet)) { // TODO DAMAGE PERFORMANCE // use a local private field instead of creating a new dictionary here.. damage = DamageSpecifier.ApplyModifierSet(damage, modifierSet); } var ev = new DamageModifyEvent(damage, origin); RaiseLocalEvent(uid.Value, ev); damage = ev.Damage; if (damage.Empty) { return damage; } } damage = ApplyUniversalAllModifiers(damage); // TODO DAMAGE PERFORMANCE // Consider using a local private field instead of creating a new dictionary here. // Would need to check that nothing ever tries to cache the delta. var delta = new DamageSpecifier(); delta.DamageDict.EnsureCapacity(damage.DamageDict.Count); var dict = damageable.Damage.DamageDict; foreach (var (type, value) in damage.DamageDict) { // CollectionsMarshal my beloved. if (!dict.TryGetValue(type, out var oldValue)) continue; var newValue = FixedPoint2.Max(FixedPoint2.Zero, oldValue + value); if (newValue == oldValue) continue; dict[type] = newValue; delta.DamageDict[type] = newValue - oldValue; } if (delta.DamageDict.Count > 0) DamageChanged(uid.Value, damageable, delta, interruptsDoAfters, origin); return delta; } /// <summary> /// Applies the two univeral "All" modifiers, if set. /// Individual damage source modifiers are set in their respective code. /// </summary> /// <param name="damage">The damage to be changed.</param> public DamageSpecifier ApplyUniversalAllModifiers(DamageSpecifier damage) { // Checks for changes first since they're unlikely in normal play. if (UniversalAllDamageModifier == 1f && UniversalAllHealModifier == 1f) return damage; foreach (var (key, value) in damage.DamageDict) { if (value == 0) continue; if (value > 0) { damage.DamageDict[key] *= UniversalAllDamageModifier; continue; } if (value < 0) { damage.DamageDict[key] *= UniversalAllHealModifier; } } return damage; } /// <summary> /// Sets all damage types supported by a <see cref="DamageableComponent"/> to the specified value. /// </summary> /// <remakrs> /// Does nothing If the given damage value is negative. /// </remakrs> public void SetAllDamage(EntityUid uid, DamageableComponent component, FixedPoint2 newValue) { if (newValue < 0) { // invalid value return; } foreach (var type in component.Damage.DamageDict.Keys) { component.Damage.DamageDict[type] = newValue; } // Setting damage does not count as 'dealing' damage, even if it is set to a larger value, so we pass an // empty damage delta. DamageChanged(uid, component, new DamageSpecifier()); } public void SetDamageModifierSetId(EntityUid uid, string? damageModifierSetId, DamageableComponent? comp = null) { if (!_damageableQuery.Resolve(uid, ref comp)) return; comp.DamageModifierSetId = damageModifierSetId; Dirty(uid, comp); } private void DamageableGetState(EntityUid uid, DamageableComponent component, ref ComponentGetState args) { if (_netMan.IsServer) { args.State = new DamageableComponentState(component.Damage.DamageDict, component.DamageContainerID, component.DamageModifierSetId, component.HealthBarThreshold); } else { // avoid mispredicting damage on newly spawned entities. args.State = new DamageableComponentState(component.Damage.DamageDict.ShallowClone(), component.DamageContainerID, component.DamageModifierSetId, component.HealthBarThreshold); } } private void OnIrradiated(EntityUid uid, DamageableComponent component, OnIrradiatedEvent args) { var damageValue = FixedPoint2.New(args.TotalRads); // Radiation should really just be a damage group instead of a list of types. DamageSpecifier damage = new(); foreach (var typeId in component.RadiationDamageTypeIDs) { damage.DamageDict.Add(typeId, damageValue); } TryChangeDamage(uid, damage, interruptsDoAfters: false, origin: args.Origin); } private void OnRejuvenate(EntityUid uid, DamageableComponent component, RejuvenateEvent args) { TryComp<MobThresholdsComponent>(uid, out var thresholds); _mobThreshold.SetAllowRevives(uid, true, thresholds); // do this so that the state changes when we set the damage SetAllDamage(uid, component, 0); _mobThreshold.SetAllowRevives(uid, false, thresholds); } private void DamageableHandleState(EntityUid uid, DamageableComponent component, ref ComponentHandleState args) { if (args.Current is not DamageableComponentState state) { return; } component.DamageContainerID = state.DamageContainerId; component.DamageModifierSetId = state.ModifierSetId; component.HealthBarThreshold = state.HealthBarThreshold; // Has the damage actually changed? DamageSpecifier newDamage = new() { DamageDict = new(state.DamageDict) }; var delta = newDamage - component.Damage; delta.TrimZeros(); if (!delta.Empty) { component.Damage = newDamage; DamageChanged(uid, component, delta); } } } /// <summary> /// Raised before damage is done, so stuff can cancel it if necessary. /// </summary> [ByRefEvent] public record struct BeforeDamageChangedEvent(DamageSpecifier Damage, EntityUid? Origin = null, bool Cancelled = false); /// <summary> /// Raised on an entity when damage is about to be dealt, /// in case anything else needs to modify it other than the base /// damageable component. /// /// For example, armor. /// </summary> public sealed class DamageModifyEvent : EntityEventArgs, IInventoryRelayEvent { // Whenever locational damage is a thing, this should just check only that bit of armour. public SlotFlags TargetSlots { get; } = ~SlotFlags.POCKET; public readonly DamageSpecifier OriginalDamage; public DamageSpecifier Damage; public EntityUid? Origin; public DamageModifyEvent(DamageSpecifier damage, EntityUid? origin = null) { OriginalDamage = damage; Damage = damage; Origin = origin; } } public sealed class DamageChangedEvent : EntityEventArgs { /// <summary> /// This is the component whose damage was changed. /// </summary> /// <remarks> /// Given that nearly every component that cares about a change in the damage, needs to know the /// current damage values, directly passing this information prevents a lot of duplicate /// Owner.TryGetComponent() calls. /// </remarks> public readonly DamageableComponent Damageable; /// <summary> /// The amount by which the damage has changed. If the damage was set directly to some number, this will be /// null. /// </summary> public readonly DamageSpecifier? DamageDelta; /// <summary> /// Was any of the damage change dealing damage, or was it all healing? /// </summary> public readonly bool DamageIncreased; /// <summary> /// Does this event interrupt DoAfters? /// Note: As provided in the constructor, this *does not* account for DamageIncreased. /// As written into the event, this *does* account for DamageIncreased. /// </summary> public readonly bool InterruptsDoAfters; /// <summary> /// Contains the entity which caused the change in damage, if any was responsible. /// </summary> public readonly EntityUid? Origin; public DamageChangedEvent(DamageableComponent damageable, DamageSpecifier? damageDelta, bool interruptsDoAfters, EntityUid? origin) { Damageable = damageable; DamageDelta = damageDelta; Origin = origin; if (DamageDelta == null) return; foreach (var damageChange in DamageDelta.DamageDict.Values) { if (damageChange > 0) { DamageIncreased = true; break; } } InterruptsDoAfters = interruptsDoAfters && DamageIncreased; } } }
412
0.888077
1
0.888077
game-dev
MEDIA
0.968177
game-dev
0.68643
1
0.68643
remmintan/minefortress
2,208
src/main/java/org/minefortress/entity/ai/professions/AbstractAutomationAreaTask.java
package org.minefortress.entity.ai.professions; import net.minecraft.world.World; import net.remmintan.mods.minefortress.core.interfaces.automation.area.IAutomationArea; import net.remmintan.mods.minefortress.core.interfaces.automation.area.IAutomationBlockInfo; import net.remmintan.mods.minefortress.core.interfaces.blueprints.ProfessionType; import net.remmintan.mods.minefortress.core.utils.ServerModUtils; import org.minefortress.entity.Colonist; import java.util.Collections; import java.util.Iterator; import java.util.Optional; import java.util.Random; public abstract class AbstractAutomationAreaTask implements ProfessionDailyTask { private final Random rand = new Random(); protected IAutomationArea area; protected Iterator<IAutomationBlockInfo> iterator; private long stopTime = 0L; @Override public boolean canStart(Colonist colonist) { return colonist.getWorld().isDay() && isEnoughTimeSinceLastTimePassed(colonist); } @Override public void start(Colonist colonist) { colonist.resetControls(); colonist.setCurrentTaskDesc(getTaskDesc()); getArea(colonist).ifPresent(f -> this.area = f); initIterator(colonist.getWorld()); } @Override public void stop(Colonist colonist) { this.stopTime = colonist.getWorld().getTime(); this.area = null; this.iterator = Collections.emptyIterator(); colonist.resetControls(); } protected abstract ProfessionType getProfessionType(); protected abstract String getTaskDesc(); private boolean isEnoughTimeSinceLastTimePassed(Colonist colonist) { return colonist.getWorld().getTime() - stopTime > rand.nextInt(500) + 300; } private void initIterator(World world) { if(this.area == null) { this.iterator = Collections.emptyIterator(); } else { this.area.update(); this.iterator = this.area.iterator(world); } } private Optional<IAutomationArea> getArea(Colonist colonist) { return ServerModUtils.getFortressManager(colonist) .flatMap(it -> it.getAutomationAreaByProfessionType(getProfessionType())); } }
412
0.776153
1
0.776153
game-dev
MEDIA
0.701108
game-dev
0.53882
1
0.53882
paperManu/splash
3,761
src/userinput/userinput_joystick.cpp
#include "./userinput/userinput_joystick.h" #include <cmath> #include <regex> namespace Splash { /*************/ Joystick::Joystick(RootObject* root) : UserInput(root) { _type = "joystick"; } /*************/ Joystick::~Joystick() {} /*************/ void Joystick::detectJoysticks() { int nbrJoysticks = 0; for (int i = GLFW_JOYSTICK_1; i < GLFW_JOYSTICK_LAST; ++i) if (glfwJoystickPresent(i)) nbrJoysticks = i + 1 - GLFW_JOYSTICK_1; _joysticks.resize(nbrJoysticks); } /*************/ void Joystick::updateMethod() { detectJoysticks(); for (uint32_t i = 0; i < _joysticks.size(); ++i) { auto& joystick = _joysticks[i]; int count; auto bufferAxes = glfwGetJoystickAxes(GLFW_JOYSTICK_1 + i, &count); auto axes = std::vector<float>(bufferAxes, bufferAxes + count); // TODO: axes configuration, in this case for the dead zone for (auto& a : axes) if (std::abs(a) < 0.2f) a = 0.f; if (joystick.axes.size() < axes.size()) for (uint32_t a = 0; a < axes.size() - joystick.axes.size(); ++a) joystick.axes.push_back(0.f); // Axes values are accumulated until they are read for (uint32_t a = 0; a < joystick.axes.size(); ++a) joystick.axes[a] += axes[a]; auto bufferButtons = glfwGetJoystickButtons(GLFW_JOYSTICK_1 + i, &count); joystick.buttons = std::vector<uint8_t>(bufferButtons, bufferButtons + count); } } /*************/ void Joystick::updateCallbacks() { for (auto& callbackIt : _callbacks) { const auto& targetState = callbackIt.first; const auto& callback = callbackIt.second; int joystickIndex = -1; std::string joystickAction = ""; static std::regex regexAction("joystick_([0-9]+)_(.+)"); std::smatch match; try { if (std::regex_match(targetState.action, match, regexAction) && match.size() == 3) { joystickIndex = std::stoi(match[1].str()); joystickAction = match[2].str(); } } catch (...) { Log::get() << Log::WARNING << "Joystick::" << __FUNCTION__ << " - Error while matching regex" << Log::endl; return; } if (joystickIndex != -1 && joystickAction.size() != 0 && static_cast<int>(_joysticks.size()) > joystickIndex) { State state(targetState); if (joystickAction == "buttons") { for (auto& b : _joysticks[joystickIndex].buttons) state.value.push_back(b); } else if (joystickAction == "axes") { for (auto& a : _joysticks[joystickIndex].axes) { state.value.push_back(a); a = 0.f; // Reset joystick axis accumulation } } else { return; } callback(state); } } } /*************/ void Joystick::readState() { int index = 0; for (auto& joystick : _joysticks) { State joystate; joystate.action = "joystick_" + std::to_string(index) + "_axes"; for (auto& a : joystick.axes) { joystate.value.push_back(a); a = 0.f; // Reset joystick axis accumulation } _state.push_back(joystate); joystate.action = "joystick_" + std::to_string(index) + "_buttons"; joystate.value.clear(); for (auto& b : joystick.buttons) joystate.value.push_back(b); _state.push_back(joystate); ++index; } } } // namespace Splash
412
0.666633
1
0.666633
game-dev
MEDIA
0.836389
game-dev
0.618805
1
0.618805
Sigma-Skidder-Team/SigmaRemap
9,010
src/main/java/net/minecraft/potion/EffectInstance.java
package net.minecraft.potion; import com.google.common.collect.ComparisonChain; import mapped.Effect; import net.minecraft.entity.LivingEntity; import net.minecraft.nbt.CompoundNBT; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class EffectInstance implements Comparable<EffectInstance> { private static final Logger LOGGER = LogManager.getLogger(); private final Effect potion; private int duration; private int amplifier; private boolean isSplashPotion; private boolean ambient; private boolean isPotionDurationMax; private boolean showParticles; private boolean showIcon; private EffectInstance hiddenEffects; public EffectInstance(Effect potionIn) { this(potionIn, 0, 0); } public EffectInstance(Effect potionIn, int durationIn) { this(potionIn, durationIn, 0); } public EffectInstance(Effect potionIn, int durationIn, int amplifierIn) { this(potionIn, durationIn, amplifierIn, false, true); } public EffectInstance(Effect potionIn, int durationIn, int amplifierIn, boolean ambientIn, boolean showParticles) { this(potionIn, durationIn, amplifierIn, ambientIn, showParticles, showParticles); } public EffectInstance(Effect potionIn, int durationIn, int amplifierIn, boolean ambientIn, boolean showParticles, boolean showIcon) { this(potionIn, durationIn, amplifierIn, ambientIn, showParticles, showIcon, (EffectInstance)null); } public EffectInstance(Effect potionIn, int durationIn, int amplifier, boolean ambient, boolean showParticles, boolean showIcon, EffectInstance hiddenEffects) { this.potion = potionIn; this.duration = durationIn; this.amplifier = amplifier; this.ambient = ambient; this.showParticles = showParticles; this.showIcon = showIcon; this.hiddenEffects = hiddenEffects; } public EffectInstance(EffectInstance other) { this.potion = other.potion; this.copy(other); } public void copy(EffectInstance var1) { this.duration = var1.duration; this.amplifier = var1.amplifier; this.ambient = var1.ambient; this.showParticles = var1.showParticles; this.showIcon = var1.showIcon; } public boolean combine(EffectInstance other) { if (this.potion != other.potion) { LOGGER.warn("This method should only be called for matching effects!"); } boolean notEqual = false; if (other.amplifier <= this.amplifier) { if (other.duration > this.duration) { if (other.amplifier != this.amplifier) { if (this.hiddenEffects != null) { this.hiddenEffects.combine(other); } else { this.hiddenEffects = new EffectInstance(other); } } else { this.duration = other.duration; notEqual = true; } } } else { if (other.duration < this.duration) { EffectInstance var5 = this.hiddenEffects; this.hiddenEffects = new EffectInstance(this); this.hiddenEffects.hiddenEffects = var5; } this.amplifier = other.amplifier; this.duration = other.duration; notEqual = true; } if (!other.ambient && this.ambient || notEqual) { this.ambient = other.ambient; notEqual = true; } if (other.showParticles != this.showParticles) { this.showParticles = other.showParticles; notEqual = true; } if (other.showIcon != this.showIcon) { this.showIcon = other.showIcon; notEqual = true; } return notEqual; } public Effect getPotion() { return this.potion; } public int getDuration() { return this.duration; } public int getAmplifier() { return this.amplifier; } public boolean isAmbient() { return this.ambient; } public boolean doesShowParticles() { return this.showParticles; } public boolean doesShowIcon() { return this.showIcon; } public boolean tick(LivingEntity entityIn, Runnable onDurationDone) { if (this.duration > 0) { if (this.potion.isReady(this.duration, this.amplifier)) { this.performEffect(entityIn); } this.decrementDuration(); if (this.duration == 0 && this.hiddenEffects != null) { this.copy(this.hiddenEffects); this.hiddenEffects = this.hiddenEffects.hiddenEffects; onDurationDone.run(); } } return this.duration > 0; } private int decrementDuration() { if (this.hiddenEffects != null) { this.hiddenEffects.decrementDuration(); } return --this.duration; } public void performEffect(LivingEntity to) { if (this.duration > 0) { this.potion.performEffect(to, this.amplifier); } } public String getPotionName() { return this.potion.getName(); } @Override public String toString() { String result; if (this.amplifier <= 0) { result = this.getPotionName() + ", Duration: " + this.duration; } else { result = this.getPotionName() + " x " + (this.amplifier + 1) + ", Duration: " + this.duration; } if (this.isSplashPotion) { result = result + ", Splash: true"; } if (!this.showParticles) { result = result + ", Particles: false"; } if (!this.showIcon) { result = result + ", Show Icon: false"; } return result; } @Override public boolean equals(Object other) { if (this != other) { if (!(other instanceof EffectInstance)) { return false; } else { EffectInstance otherInstance = (EffectInstance)other; return this.duration == otherInstance.duration && this.amplifier == otherInstance.amplifier && this.isSplashPotion == otherInstance.isSplashPotion && this.ambient == otherInstance.ambient && this.potion.equals(otherInstance.potion); } } else { return true; } } @Override public int hashCode() { int hash = this.potion.hashCode(); hash = 31 * hash + this.duration; hash = 31 * hash + this.amplifier; hash = 31 * hash + (!this.isSplashPotion ? 0 : 1); return 31 * hash + (!this.ambient ? 0 : 1); } public CompoundNBT write(CompoundNBT nbt) { nbt.putByte("Id", (byte) Effect.getId(this.getPotion())); this.writeInternal(nbt); return nbt; } private void writeInternal(CompoundNBT nbt) { nbt.putByte("Amplifier", (byte)this.getAmplifier()); nbt.putInt("Duration", this.getDuration()); nbt.putBoolean("Ambient", this.isAmbient()); nbt.putBoolean("ShowParticles", this.doesShowParticles()); nbt.putBoolean("ShowIcon", this.doesShowIcon()); if (this.hiddenEffects != null) { CompoundNBT nbt2 = new CompoundNBT(); this.hiddenEffects.write(nbt2); nbt.put("HiddenEffect", nbt2); } } public static EffectInstance read(CompoundNBT nbt) { byte id = nbt.getByte("Id"); Effect effect = Effect.get(id); return effect != null ? readInternal(effect, nbt) : null; } private static EffectInstance readInternal(Effect effect, CompoundNBT nbt) { byte amplifier = nbt.getByte("Amplifier"); int duration = nbt.getInt("Duration"); boolean ambient = nbt.getBoolean("Ambient"); boolean showParticles = true; if (nbt.contains("ShowParticles", 1)) { showParticles = nbt.getBoolean("ShowParticles"); } boolean var8 = showParticles; if (nbt.contains("ShowIcon", 1)) { var8 = nbt.getBoolean("ShowIcon"); } EffectInstance var9 = null; if (nbt.contains("HiddenEffect", 10)) { var9 = readInternal(effect, nbt.getCompound("HiddenEffect")); } return new EffectInstance(effect, duration, amplifier >= 0 ? amplifier : 0, ambient, showParticles, var8, var9); } public void setIsPotionDurationMax(boolean var1) { this.isPotionDurationMax = var1; } public boolean isPotionDurationMax() { return this.isPotionDurationMax; } public int compareTo(EffectInstance that) { return this.getDuration() > 32147 && that.getDuration() > 32147 || this.isAmbient() && that.isAmbient() ? ComparisonChain.start() .compare(this.isAmbient(), that.isAmbient()) .compare(this.getPotion().getLiquidColor(), that.getPotion().getLiquidColor()) .result() : ComparisonChain.start() .compare(this.isAmbient(), that.isAmbient()) .compare(this.getDuration(), that.getDuration()) .compare(this.getPotion().getLiquidColor(), that.getPotion().getLiquidColor()) .result(); } }
412
0.91241
1
0.91241
game-dev
MEDIA
0.96039
game-dev
0.978791
1
0.978791
OrderOfThePorcupine/ProjectPorcupine
9,380
Assets/Scripts/Controllers/Events/SpawnInventoryController.cs
#region License // ==================================================== // Project Porcupine Copyright(C) 2016 Team Porcupine // This program comes with ABSOLUTELY NO WARRANTY; This is free software, // and you are welcome to redistribute it under certain conditions; See // file LICENSE, which is part of this source code package, for details. // ==================================================== #endregion using System; using System.Collections.Generic; using System.Linq; using ProjectPorcupine.Localization; using ProjectPorcupine.Mouse; using UnityEngine; using UnityEngine.UI; [MoonSharp.Interpreter.MoonSharpUserData] public class SpawnInventoryController : IMouseHandler { private GameObject spawnUI; public SpawnInventoryController() { CreateSpawnUI(); CreateInventoryEntries(); } public string InventoryToBuild { get; protected set; } public int AmountToCreate { get; protected set; } public Inventory CurrentInventory { get; protected set; } public bool DisableDragging { get { return true; } } public MouseHandlerCallbacks CallbacksEnabled { get { return MouseHandlerCallbacks.HANDLE_CLICK | MouseHandlerCallbacks.HANDLE_TOOLTIP | MouseHandlerCallbacks.HANDLE_DRAG_VISUAL; } } public void HideUI() { spawnUI.SetActive(false); } public void ShowUI() { spawnUI.SetActive(true); } public void SetUIVisibility(bool visibility) { spawnUI.SetActive(visibility); } public void SpawnInventory(Tile t) { // If the user clicks outside the game area t may be null. if (t == null) { return; } // You can't spawn on occupied tiles if (t.Furniture != null) { return; } if (t.Inventory == null || t.Inventory.Type == InventoryToBuild) { World.Current.InventoryManager.PlaceInventory(t, CurrentInventory); CurrentInventory = new Inventory(InventoryToBuild, AmountToCreate); } } public void HandleClick(Vector2 position, int mouseKey) { if (mouseKey == 0 && SettingsKeyHolder.DeveloperMode) { Tile t = WorldController.Instance.GetTileAtWorldCoord(position); SpawnInventory(t); } } public void HandleTooltip(Vector2 position, MouseCursor cursor, bool isDragging) { cursor.Reset(); cursor.DisplayCursorInfo(TextAnchor.MiddleRight, AmountToCreate + "x " + InventoryToBuild, MouseCursor.TextColor, false); } public List<GameObject> HandleDragVisual(MouseController.DragParameters parameters, Transform parent) { List<GameObject> objects = new List<GameObject>(); if (parameters.EndX != parameters.StartX) { // We should NEVER reach here, the disable dragging means that this should NEVER be true throw new ArgumentException("Parameters Start X/Y values should Equal End X/Y values, this is taken care by the DisableDragging = true property."); } Tile t = WorldController.Instance.World.GetTileAt(parameters.StartX, parameters.StartY, WorldController.Instance.CameraController.CurrentLayer); if (t != null) { // Show generic visuals GameObject go = new GameObject(); go.transform.SetParent(parent); go.transform.position = new Vector3(parameters.StartX, parameters.StartY); if (t.Furniture == null && (t.Inventory == null || t.Inventory.Type == InventoryToBuild) && t.Type != TileType.Empty) { InventorySpriteController.SetSprite(go, CurrentInventory).color = Color.green; // = new Color(0.5f, 1f, 0.5f, 0.25f); } else { InventorySpriteController.SetSprite(go, CurrentInventory).color = Color.red; // new Color(1f, 0.5f, 0.5f, 0.25f); } objects.Add(go); } return objects; } #region InvalidOperations /// <summary> /// NOT IMPLEMENTED BY SPAWN INVENTORY CONTROLLER. Will throw on call. /// NOT MEANT TO BE CALLED. /// </summary> public void HandleDragFinished(MouseController.DragParameters parameters) { throw new InvalidOperationException("Not supported by this class"); } /// <summary> /// NOT IMPLEMENTED BY SPAWN INVENTORY CONTROLLER. Will throw on call. /// NOT MEANT TO BE CALLED. /// </summary> public Vector3 HandlePlacingPosition(Vector3 position) { throw new InvalidOperationException("Not supported by this class"); } #endregion private void CreateSpawnUI() { spawnUI = new GameObject() { name = "Spawn Inventory UI", layer = LayerMask.NameToLayer("UI") }; Canvas canvas = GameObject.Find("Canvas").GetComponent<Canvas>(); spawnUI.transform.SetParent(canvas.transform, false); RectTransform rectTransform = spawnUI.AddComponent<RectTransform>(); rectTransform.pivot = new Vector2(0, 0.5f); rectTransform.anchorMin = new Vector2(0, 0.5f); rectTransform.anchorMax = new Vector2(0, 0.5f); rectTransform.anchoredPosition = new Vector2(0, 0); spawnUI.AddComponent<Image>(); VerticalLayoutGroup vlg = spawnUI.AddComponent<VerticalLayoutGroup>(); vlg.childForceExpandWidth = false; vlg.childForceExpandHeight = false; vlg.spacing = 0; ContentSizeFitter csf = spawnUI.AddComponent<ContentSizeFitter>(); csf.horizontalFit = ContentSizeFitter.FitMode.MinSize; csf.verticalFit = ContentSizeFitter.FitMode.MinSize; } private void CreateInventoryEntries() { foreach (Inventory inventory in PrototypeManager.Inventory.Values.OrderByDescending(inv => inv.Category)) { GameObject inventorySlot_go = new GameObject() { name = "Slot - " + inventory.Type, layer = LayerMask.NameToLayer("UI") }; inventorySlot_go.transform.SetParent(spawnUI.transform); HorizontalLayoutGroup hlg = inventorySlot_go.AddComponent<HorizontalLayoutGroup>(); hlg.childForceExpandWidth = false; hlg.childForceExpandHeight = false; hlg.spacing = 2; inventorySlot_go.AddComponent<Image>(); string localName = inventory.LocalizationName; GameObject textComponent = CreateTextComponent(inventorySlot_go, localName, TextAnchor.MiddleLeft); TextLocalizer textLocalizer = textComponent.AddComponent<TextLocalizer>(); textLocalizer.formatValues = new string[0]; CreateButtonComponents(inventorySlot_go, inventory, new int[] { 1, 20, 50 }); LayoutElement layoutElement = inventorySlot_go.AddComponent<LayoutElement>(); layoutElement.minWidth = 160; layoutElement.minHeight = 20; } } private void CreateButtonComponents(GameObject go, Inventory inventory, int[] amounts) { foreach (int amount in amounts) { GameObject button_go = new GameObject() { name = "Button", layer = LayerMask.NameToLayer("UI") }; button_go.AddComponent<Image>(); RectTransform rectTransform = button_go.GetComponent<RectTransform>(); rectTransform.SetParent(go.transform); Button button = button_go.AddComponent<Button>(); CreateTextComponent(button_go, amount.ToString(), TextAnchor.MiddleCenter); LayoutElement layoutElement = button_go.AddComponent<LayoutElement>(); layoutElement.minWidth = 20; layoutElement.minHeight = 20; int localAmount = amount; button.onClick.AddListener( () => OnButtonClick(inventory.Type, localAmount)); } } private GameObject CreateTextComponent(GameObject go, string invName, TextAnchor textAnchor) { GameObject text_go = new GameObject() { name = "Text", layer = LayerMask.NameToLayer("UI") }; RectTransform rectTransform = text_go.AddComponent<RectTransform>(); rectTransform.SetParent(go.transform); rectTransform.sizeDelta = Vector2.zero; rectTransform.anchorMax = Vector2.one; rectTransform.anchorMin = Vector2.zero; Text text = text_go.AddComponent<Text>(); text.font = Font.CreateDynamicFontFromOSFont("Arial", 14); text.alignment = textAnchor; text.color = Color.black; text.text = invName; text.horizontalOverflow = HorizontalWrapMode.Overflow; LayoutElement layoutElement = text_go.AddComponent<LayoutElement>(); layoutElement.minWidth = 100; layoutElement.minHeight = 20; return text_go; } private void OnButtonClick(string invName, int amount) { InventoryToBuild = invName; AmountToCreate = amount; CurrentInventory = new Inventory(InventoryToBuild, AmountToCreate); WorldController.Instance.MouseController.ChangeMouseMode(MouseMode.INVENTORY); } }
412
0.917642
1
0.917642
game-dev
MEDIA
0.976046
game-dev
0.964197
1
0.964197
kacperks/Fractal_Engine
3,540
Engine/Thirdparty/cmake/Engine/Thirdparty/cmake/openal-soft/core/mastering.h
#ifndef CORE_MASTERING_H #define CORE_MASTERING_H #include <memory> #include "almalloc.h" #include "bufferline.h" struct SlidingHold; using uint = unsigned int; /* General topology and basic automation was based on the following paper: * * D. Giannoulis, M. Massberg and J. D. Reiss, * "Parameter Automation in a Dynamic Range Compressor," * Journal of the Audio Engineering Society, v61 (10), Oct. 2013 * * Available (along with supplemental reading) at: * * http://c4dm.eecs.qmul.ac.uk/audioengineering/compressors/ */ struct Compressor { size_t mNumChans{0u}; struct { bool Knee : 1; bool Attack : 1; bool Release : 1; bool PostGain : 1; bool Declip : 1; } mAuto{}; uint mLookAhead{0}; float mPreGain{0.0f}; float mPostGain{0.0f}; float mThreshold{0.0f}; float mSlope{0.0f}; float mKnee{0.0f}; float mAttack{0.0f}; float mRelease{0.0f}; alignas(16) float mSideChain[2*BufferLineSize]{}; alignas(16) float mCrestFactor[BufferLineSize]{}; SlidingHold *mHold{nullptr}; FloatBufferLine *mDelay{nullptr}; float mCrestCoeff{0.0f}; float mGainEstimate{0.0f}; float mAdaptCoeff{0.0f}; float mLastPeakSq{0.0f}; float mLastRmsSq{0.0f}; float mLastRelease{0.0f}; float mLastAttack{0.0f}; float mLastGainDev{0.0f}; ~Compressor(); void process(const uint SamplesToDo, FloatBufferLine *OutBuffer); int getLookAhead() const noexcept { return static_cast<int>(mLookAhead); } DEF_PLACE_NEWDEL() /** * The compressor is initialized with the following settings: * * \param NumChans Number of channels to process. * \param SampleRate Sample rate to process. * \param AutoKnee Whether to automate the knee width parameter. * \param AutoAttack Whether to automate the attack time parameter. * \param AutoRelease Whether to automate the release time parameter. * \param AutoPostGain Whether to automate the make-up (post) gain * parameter. * \param AutoDeclip Whether to automate clipping reduction. Ignored * when not automating make-up gain. * \param LookAheadTime Look-ahead time (in seconds). * \param HoldTime Peak hold-time (in seconds). * \param PreGainDb Gain applied before detection (in dB). * \param PostGainDb Make-up gain applied after compression (in dB). * \param ThresholdDb Triggering threshold (in dB). * \param Ratio Compression ratio (x:1). Set to INFINIFTY for true * limiting. Ignored when automating knee width. * \param KneeDb Knee width (in dB). Ignored when automating knee * width. * \param AttackTime Attack time (in seconds). Acts as a maximum when * automating attack time. * \param ReleaseTime Release time (in seconds). Acts as a maximum when * automating release time. */ static std::unique_ptr<Compressor> Create(const size_t NumChans, const float SampleRate, const bool AutoKnee, const bool AutoAttack, const bool AutoRelease, const bool AutoPostGain, const bool AutoDeclip, const float LookAheadTime, const float HoldTime, const float PreGainDb, const float PostGainDb, const float ThresholdDb, const float Ratio, const float KneeDb, const float AttackTime, const float ReleaseTime); }; using CompressorPtr = std::unique_ptr<Compressor>; #endif /* CORE_MASTERING_H */
412
0.946471
1
0.946471
game-dev
MEDIA
0.658631
game-dev
0.886186
1
0.886186
SkyFangames/La-Base-de-Sky
32,630
LA BASE DE SKY/Data/Scripts/039_Battle triggering/002_Overworld_BattleStarting.rb
#=============================================================================== # Battle preparation #=============================================================================== class PokemonGlobalMetadata attr_accessor :nextBattleBGM attr_accessor :nextBattleVictoryBGM attr_accessor :nextBattleCaptureME attr_accessor :nextBattleBack end #=============================================================================== # #=============================================================================== class Game_Temp attr_accessor :encounter_triggered attr_accessor :encounter_type attr_accessor :party_levels_before_battle attr_accessor :party_critical_hits_dealt attr_accessor :party_direct_damage_taken def battle_rules @battle_rules = {} if !@battle_rules return @battle_rules end def clear_battle_rules self.battle_rules.clear end def add_battle_rule(rule, var = nil) rules = self.battle_rules case rule.to_s.downcase when "single", "1v1", "1v2", "2v1", "1v3", "3v1", "double", "2v2", "2v3", "3v2", "triple", "3v3" rules["size"] = rule.to_s.downcase when "canlose" then rules["canLose"] = true when "cannotlose" then rules["canLose"] = false when "canrun" then rules["canRun"] = true when "cannotrun" then rules["canRun"] = false when "roamerflees" then rules["roamerFlees"] = true when "canswitch" then rules["canSwitch"] = true when "cannotswitch" then rules["canSwitch"] = false when "noexp" then rules["expGain"] = false when "nomoney" then rules["moneyGain"] = false when "disablepokeballs" then rules["disablePokeBalls"] = true when "forcecatchintoparty" then rules["forceCatchIntoParty"] = true when "switchstyle" then rules["switchStyle"] = true when "setstyle" then rules["switchStyle"] = false when "anims" then rules["battleAnims"] = true when "noanims" then rules["battleAnims"] = false when "terrain" rules["defaultTerrain"] = GameData::BattleTerrain.try_get(var)&.id when "weather" rules["defaultWeather"] = GameData::BattleWeather.try_get(var)&.id when "environment", "environ" rules["environment"] = GameData::Environment.try_get(var)&.id when "backdrop", "battleback" then rules["backdrop"] = var when "base" then rules["base"] = var when "outcome", "outcomevar" then rules["outcomeVar"] = var when "nopartner" then rules["noPartner"] = true else raise _INTL("La regla de combate \"{1}\" no existe.", rule) end end end #=============================================================================== # #=============================================================================== def setBattleRule(*args) r = nil args.each do |arg| if r $game_temp.add_battle_rule(r, arg) r = nil else case arg.downcase when "terrain", "weather", "environment", "environ", "backdrop", "battleback", "base", "outcome", "outcomevar" r = arg next end $game_temp.add_battle_rule(arg) end end raise _INTL("Argumento {1} esperaba una variable después pero no la tiene.", r) if r end # Used to determine the environment in battle, and also the form of Burmy/ # Wormadam. def pbGetEnvironment ret = :None map_env = $game_map.metadata&.battle_environment ret = map_env if map_env if $game_temp.encounter_type && GameData::EncounterType.get($game_temp.encounter_type).type == :fishing terrainTag = $game_player.pbFacingTerrainTag else terrainTag = $game_player.terrain_tag end tile_environment = terrainTag.battle_environment if ret == :Forest && [:Grass, :TallGrass].include?(tile_environment) ret = :ForestGrass elsif tile_environment ret = tile_environment end return ret end # Record current levels of Pokémon in party, to see if they gain a level during # battle and may need to evolve afterwards EventHandlers.add(:on_start_battle, :record_party_status, proc { $game_temp.party_levels_before_battle = [] $game_temp.party_critical_hits_dealt = [] $game_temp.party_direct_damage_taken = [] $player.party.each_with_index do |pkmn, i| $game_temp.party_levels_before_battle[i] = pkmn.level $game_temp.party_critical_hits_dealt[i] = 0 $game_temp.party_direct_damage_taken[i] = 0 end } ) def pbCanDoubleBattle? return true if $player.able_pokemon_count >= 2 return $PokemonGlobal.partner && $player.able_pokemon_count >= 1 end def pbCanTripleBattle? return true if $player.able_pokemon_count >= 3 return $PokemonGlobal.partner && $player.able_pokemon_count >= 2 end #=============================================================================== # Helper methods for setting up and closing down battles #=============================================================================== module BattleCreationHelperMethods module_function # Skip battle if the player has no able Pokémon, or if holding Ctrl in Debug mode def skip_battle? return true if $player.able_pokemon_count == 0 return true if $DEBUG && Input.press?(Input::CTRL) return false end def skip_battle(outcome_variable, trainer_battle = false) pbMessage(_INTL("SALTANDO BATALLA...")) if !trainer_battle && $player.pokemon_count > 0 pbMessage(_INTL("SALTANDO BATALLA...")) if trainer_battle && $DEBUG pbMessage(_INTL("TRAS VENCER...")) if trainer_battle && $player.able_pokemon_count > 0 $game_temp.clear_battle_rules if $game_temp.memorized_bgm && $game_system.is_a?(Game_System) $game_system.bgm_pause $game_system.bgm_position = $game_temp.memorized_bgm_position $game_system.bgm_resume($game_temp.memorized_bgm) end $game_temp.memorized_bgm = nil $game_temp.memorized_bgm_position = 0 $PokemonGlobal.nextBattleBGM = nil $PokemonGlobal.nextBattleVictoryBGM = nil $PokemonGlobal.nextBattleCaptureME = nil $PokemonGlobal.nextBattleBack = nil $PokemonEncounters.reset_step_count outcome = 1 # Win outcome = 0 if trainer_battle && $player.able_pokemon_count == 0 # Undecided pbSet(outcome_variable, outcome) return outcome end def partner_can_participate?(foe_party) return false if !$PokemonGlobal.partner || $game_temp.battle_rules["noPartner"] return true if foe_party.length > 1 if $game_temp.battle_rules["size"] return false if $game_temp.battle_rules["size"] == "single" || $game_temp.battle_rules["size"][/^1v/i] # "1v1", "1v2", "1v3", etc. return true end return false end # Generate information for the player and partner trainer(s) def set_up_player_trainers(foe_party) trainer_array = [$player] ally_items = [] pokemon_array = $player.party party_starts = [0] if partner_can_participate?(foe_party) ally = NPCTrainer.new($PokemonGlobal.partner[1], $PokemonGlobal.partner[0]) ally.id = $PokemonGlobal.partner[2] ally.party = $PokemonGlobal.partner[3] ally_items[1] = ally.items.clone trainer_array.push(ally) pokemon_array = [] $player.party.each { |pkmn| pokemon_array.push(pkmn) } party_starts.push(pokemon_array.length) ally.party.each { |pkmn| pokemon_array.push(pkmn) } setBattleRule("double") if $game_temp.battle_rules["size"].nil? end return trainer_array, ally_items, pokemon_array, party_starts end def create_battle_scene return Battle::Scene.new end # Sets up various battle parameters and applies special rules. def prepare_battle(battle) battleRules = $game_temp.battle_rules # The size of the battle, i.e. how many Pokémon on each side (default: "single") battle.setBattleMode(battleRules["size"]) if !battleRules["size"].nil? # Whether the game won't black out even if the player loses (default: false) battle.canLose = battleRules["canLose"] if !battleRules["canLose"].nil? # Whether the player can choose to run from the battle (default: true) battle.canRun = battleRules["canRun"] if !battleRules["canRun"].nil? # Whether the player can manually choose to switch out Pokémon (default: true) battle.canSwitch = battleRules["canSwitch"] if !battleRules["canSwitch"].nil? # Whether wild Pokémon always try to run from battle (default: nil) battle.rules["alwaysflee"] = battleRules["roamerFlees"] # Whether Pokémon gain Exp/EVs from defeating/catching a Pokémon (default: true) battle.expGain = battleRules["expGain"] if !battleRules["expGain"].nil? # Whether the player gains/loses money at the end of the battle (default: true) battle.moneyGain = battleRules["moneyGain"] if !battleRules["moneyGain"].nil? # Whether Poké Balls cannot be thrown at all battle.disablePokeBalls = battleRules["disablePokeBalls"] if !battleRules["disablePokeBalls"].nil? # Whether the player is asked what to do with a new Pokémon when their party is full battle.sendToBoxes = $PokemonSystem.sendtoboxes if Settings::NEW_CAPTURE_CAN_REPLACE_PARTY_MEMBER battle.sendToBoxes = 2 if battleRules["forceCatchIntoParty"] # Whether the player is able to switch when an opponent's Pokémon faints battle.switchStyle = ($PokemonSystem.battlestyle == 0) battle.switchStyle = battleRules["switchStyle"] if !battleRules["switchStyle"].nil? # Whether battle animations are shown battle.showAnims = ($PokemonSystem.battlescene == 0) battle.showAnims = battleRules["battleAnims"] if !battleRules["battleAnims"].nil? # Terrain if battleRules["defaultTerrain"].nil? if Settings::OVERWORLD_WEATHER_SETS_BATTLE_TERRAIN case $game_screen.weather_type when :Storm battle.defaultTerrain = :Electric when :Fog battle.defaultTerrain = :Misty end end else battle.defaultTerrain = battleRules["defaultTerrain"] end # Weather if battleRules["defaultWeather"].nil? case GameData::Weather.get($game_screen.weather_type).category when :Rain, :Storm battle.defaultWeather = :Rain when :Hail battle.defaultWeather = :Hail when :Sandstorm battle.defaultWeather = :Sandstorm when :Sun battle.defaultWeather = :Sun end else battle.defaultWeather = battleRules["defaultWeather"] end # Environment if battleRules["environment"].nil? battle.environment = pbGetEnvironment else battle.environment = battleRules["environment"] end # Backdrop graphic filename if !battleRules["backdrop"].nil? backdrop = battleRules["backdrop"] elsif $PokemonGlobal.nextBattleBack backdrop = $PokemonGlobal.nextBattleBack elsif $PokemonGlobal.surfing backdrop = "water" # This applies wherever you are, including in caves elsif $game_map.metadata back = $game_map.metadata.battle_background backdrop = back if back && back != "" end backdrop = "indoor1" if !backdrop battle.backdrop = backdrop # Choose a name for bases depending on environment if battleRules["base"].nil? environment_data = GameData::Environment.try_get(battle.environment) base = environment_data.battle_base if environment_data else base = battleRules["base"] end battle.backdropBase = base if base # Time of day if $game_map.metadata&.battle_environment == :Cave battle.time = 2 # This makes Dusk Balls work properly in caves elsif Settings::TIME_SHADING timeNow = pbGetTimeNow if PBDayNight.isNight?(timeNow) battle.time = 2 elsif PBDayNight.isEvening?(timeNow) battle.time = 1 else battle.time = 0 end end end def after_battle(outcome, can_lose) $player.party.each do |pkmn| pkmn.statusCount = 0 if pkmn.status == :POISON # Bad poison becomes regular pkmn.makeUnmega pkmn.makeUnprimal end if $PokemonGlobal.partner $player.heal_party $PokemonGlobal.partner[3].each do |pkmn| pkmn.heal pkmn.makeUnmega pkmn.makeUnprimal end end if [2, 5].include?(outcome) && can_lose # if loss or draw $player.party.each { |pkmn| pkmn.heal } timer_start = System.uptime until System.uptime - timer_start >= 0.25 Graphics.update end end EventHandlers.trigger(:on_end_battle, outcome, can_lose) $game_player.straighten end # Save the result of the battle in a Game Variable (1 by default) # 0 - Undecided or aborted # 1 - Player won # 2 - Player lost # 3 - Player or wild Pokémon ran from battle, or player forfeited the match # 4 - Wild Pokémon was caught # 5 - Draw def set_outcome(outcome, outcome_variable = 1, trainer_battle = false) case outcome when 1, 4 # Won, caught $stats.wild_battles_won += 1 if !trainer_battle $stats.trainer_battles_won += 1 if trainer_battle when 2, 3, 5 # Lost, fled, draw $stats.wild_battles_lost += 1 if !trainer_battle $stats.trainer_battles_lost += 1 if trainer_battle end pbSet(outcome_variable, outcome) end end #=============================================================================== # Wild battles #=============================================================================== class WildBattle # Used when walking in tall grass, hence the additional code. def self.start(*args, can_override: false) foe_party = WildBattle.generate_foes(*args) # Potentially call a different WildBattle.start-type method instead (for # roaming Pokémon, Safari battles, Bug Contest battles) if foe_party.length == 1 && can_override handled = [nil] EventHandlers.trigger(:on_calling_wild_battle, foe_party[0], handled) return handled[0] if !handled[0].nil? end # Perform the battle outcome = WildBattle.start_core(*foe_party) # Used by the Poké Radar to update/break the chain if foe_party.length == 1 && can_override EventHandlers.trigger(:on_wild_battle_end, foe_party[0].species, foe_party[0].level, outcome) end # Return false if the player lost or drew the battle, and true if any other result return outcome != 2 && outcome != 5 end def self.start_core(*args) outcome_variable = $game_temp.battle_rules["outcomeVar"] || 1 can_lose = $game_temp.battle_rules["canLose"] || false # Skip battle if the player has no able Pokémon, or if holding Ctrl in Debug mode if BattleCreationHelperMethods.skip_battle? return BattleCreationHelperMethods.skip_battle(outcome_variable) end # Record information about party Pokémon to be used at the end of battle # (e.g. comparing levels for an evolution check) EventHandlers.trigger(:on_start_battle) # Generate array of foes foe_party = WildBattle.generate_foes(*args) # Generate information for the player and partner trainer(s) player_trainers, ally_items, player_party, player_party_starts = BattleCreationHelperMethods.set_up_player_trainers(foe_party) # Create the battle scene (the visual side of it) scene = BattleCreationHelperMethods.create_battle_scene # Create the battle class (the mechanics side of it) battle = Battle.new(scene, player_party, foe_party, player_trainers, nil) battle.party1starts = player_party_starts battle.ally_items = ally_items # Set various other properties in the battle class setBattleRule("#{foe_party.length}v#{foe_party.length}") if $game_temp.battle_rules["size"].nil? BattleCreationHelperMethods.prepare_battle(battle) $game_temp.clear_battle_rules # Perform the battle itself outcome = 0 pbBattleAnimation(pbGetWildBattleBGM(foe_party), (foe_party.length == 1) ? 0 : 2, foe_party) do pbSceneStandby { outcome = battle.pbStartBattle } BattleCreationHelperMethods.after_battle(outcome, can_lose) end Input.update # Save the result of the battle in a Game Variable (1 by default) BattleCreationHelperMethods.set_outcome(outcome, outcome_variable) return outcome end def self.generate_foes(*args) ret = [] species_id = nil args.each do |arg| case arg when Pokemon raise _INTL("La especie {1} se ha indicado pero no el nivel.", species_id) if species_id ret.push(arg) when Array raise _INTL("La especie {1} se ha indicado pero no el nivel.", species_id) if species_id species = GameData::Species.get(arg[0]).id pkmn = pbGenerateWildPokemon(species, arg[1]) ret.push(pkmn) else if species_id # Expecting level if !arg.is_a?(Integer) || !(1..GameData::GrowthRate.max_level).include?(arg) raise _INTL("Se esperaba un nivel (1..{1}) pero {2} no es un número o un nivel válido.", GameData::GrowthRate.max_level, arg) end ret.push(pbGenerateWildPokemon(species_id, arg)) species_id = nil else # Expecting species ID if !GameData::Species.exists?(arg) raise _INTL("La especie {1} no existe.", arg) end species_id = arg end end end raise _INTL("La especie {1} se ha indicado pero no un nivel.", species_id) if species_id return ret end end #=============================================================================== # Trainer battles #=============================================================================== class TrainerBattle # Used by most trainer events, which can be positioned in such a way that # multiple trainer events spot the player at once. The extra code in this # method deals with that case and can cause a double trainer battle instead. def self.start(*args) # If there is another NPC trainer who spotted the player at the same time, # and it is possible to have a double battle (the player has 2+ able Pokémon # or has a partner trainer), then record this first NPC trainer into # $game_temp.waiting_trainer and end this method. That second NPC event will # then trigger and cause the battle to happen against this first trainer and # themselves. if !$game_temp.waiting_trainer && pbMapInterpreterRunning? && pbCanDoubleBattle? thisEvent = pbMapInterpreter.get_self # Find all other triggered trainer events triggeredEvents = $game_player.pbTriggeredTrainerEvents([2], false, true) otherEvent = [] triggeredEvents.each do |i| next if i.id == thisEvent.id next if $game_self_switches[[$game_map.map_id, i.id, "A"]] otherEvent.push(i) end # If there is exactly 1 other triggered trainer event, this trainer can be # stored up to battle with that one if otherEvent.length == 1 trainers, _items, _end_speeches, _party, _party_starts = TrainerBattle.generate_foes(*args) # If this is just 1 trainer with 6 or fewer Pokémon, it can be stored up # to battle alongside the other trainer if trainers.length == 1 && trainers[0].party.length <= Settings::MAX_PARTY_SIZE $game_temp.waiting_trainer = [trainers[0], thisEvent.id] return false end end end # Perform the battle if $game_temp.waiting_trainer new_args = args + [$game_temp.waiting_trainer[0]] outcome = TrainerBattle.start_core(*new_args) pbMapInterpreter.pbSetSelfSwitch($game_temp.waiting_trainer[1], "A", true) if outcome == 1 $game_temp.waiting_trainer = nil else outcome = TrainerBattle.start_core(*args) end # Return true if the player won the battle, and false if any other result return outcome == 1 end def self.start_core(*args) outcome_variable = $game_temp.battle_rules["outcomeVar"] || 1 can_lose = $game_temp.battle_rules["canLose"] || false # Skip battle if the player has no able Pokémon, or if holding Ctrl in Debug mode if BattleCreationHelperMethods.skip_battle? return BattleCreationHelperMethods.skip_battle(outcome_variable, true) end # Record information about party Pokémon to be used at the end of battle (e.g. # comparing levels for an evolution check) EventHandlers.trigger(:on_start_battle) # Generate information for the foes foe_trainers, foe_items, foe_party, foe_party_starts = TrainerBattle.generate_foes(*args) # Generate information for the player and partner trainer(s) player_trainers, ally_items, player_party, player_party_starts = BattleCreationHelperMethods.set_up_player_trainers(foe_party) # Create the battle scene (the visual side of it) scene = BattleCreationHelperMethods.create_battle_scene # Create the battle class (the mechanics side of it) battle = Battle.new(scene, player_party, foe_party, player_trainers, foe_trainers) battle.party1starts = player_party_starts battle.party2starts = foe_party_starts battle.ally_items = ally_items battle.items = foe_items # Set various other properties in the battle class setBattleRule("#{foe_trainers.length}v#{foe_trainers.length}") if $game_temp.battle_rules["size"].nil? BattleCreationHelperMethods.prepare_battle(battle) $game_temp.clear_battle_rules # Perform the battle itself outcome = 0 pbBattleAnimation(pbGetTrainerBattleBGM(foe_trainers), (battle.singleBattle?) ? 1 : 3, foe_trainers) do pbSceneStandby { outcome = battle.pbStartBattle } BattleCreationHelperMethods.after_battle(outcome, can_lose) end Input.update # Save the result of the battle in a Game Variable (1 by default) BattleCreationHelperMethods.set_outcome(outcome, outcome_variable, true) return outcome end def self.generate_foes(*args) trainer_array = [] foe_items = [] pokemon_array = [] party_starts = [] trainer_type = nil trainer_name = nil args.each_with_index do |arg, i| case arg when NPCTrainer raise _INTL("El tipo de entrenador {1} se ha indicado pero no su nombre.", trainer_type) if trainer_type trainer_array.push(arg) foe_items.push(arg.items) party_starts.push(pokemon_array.length) arg.party.each { |pkmn| pokemon_array.push(pkmn) } when Array # [trainer type, trainer name, version number, speech (optional)] raise _INTL("El tipo de entrenador {1} se ha indicado pero no su nombre.", trainer_type) if trainer_type trainer = pbLoadTrainer(arg[0], arg[1], arg[2]) pbMissingTrainer(arg[0], arg[1], arg[2]) if !trainer trainer = pbLoadTrainer(arg[0], arg[1], arg[2]) if !trainer # Try again raise _INTL("Entrenador para datos '{1}' no se ha definido.", arg) if !trainer EventHandlers.trigger(:on_trainer_load, trainer) trainer.lose_text = arg[3] if arg[3] && !arg[3].empty? trainer_array.push(trainer) foe_items.push(trainer.items) party_starts.push(pokemon_array.length) trainer.party.each { |pkmn| pokemon_array.push(pkmn) } else if trainer_name # Expecting version number if !arg.is_a?(Integer) || arg < 0 raise _INTL("Se esperaba un número de versión de entrenador (0 o más) pero {1} no es un número o un valor válido.", arg) end trainer = pbLoadTrainer(trainer_type, trainer_name, arg) pbMissingTrainer(trainer_type, trainer_name, arg) if !trainer trainer = pbLoadTrainer(trainer_type, trainer_name, arg) if !trainer # Try again raise _INTL("Entrenador para datos '{1}, {2}, {3}' no se ha definido.", trainer_type, trainer_name, arg) if !trainer EventHandlers.trigger(:on_trainer_load, trainer) trainer_array.push(trainer) foe_items.push(trainer.items) party_starts.push(pokemon_array.length) trainer.party.each { |pkmn| pokemon_array.push(pkmn) } trainer_type = nil trainer_name = nil elsif trainer_type # Expecting trainer name if !arg.is_a?(String) || arg.strip.empty? raise _INTL("Se esperaba un nombre de entrenador, pero '{1}' no es un nombre válido.", arg) end if args[i + 1].is_a?(Integer) # Version number is next trainer_name = arg.strip else trainer = pbLoadTrainer(trainer_type, arg) pbMissingTrainer(trainer_type, arg, 0) if !trainer trainer = pbLoadTrainer(trainer_type, arg) if !trainer # Try again raise _INTL("Entrenador para datos '{1}, {2}' no se ha definido.", trainer_type, arg) if !trainer EventHandlers.trigger(:on_trainer_load, trainer) trainer_array.push(trainer) foe_items.push(trainer.items) party_starts.push(pokemon_array.length) trainer.party.each { |pkmn| pokemon_array.push(pkmn) } trainer_type = nil end else # Expecting trainer type if !GameData::TrainerType.exists?(arg) raise _INTL("El tipo de entrenador {1} no existe.", arg) end trainer_type = arg end end end raise _INTL("El tipo de entrenador {1} se ha indicado, pero no es válido.", trainer_type) if trainer_type return trainer_array, foe_items, pokemon_array, party_starts end end #=============================================================================== # After battles #=============================================================================== EventHandlers.add(:on_end_battle, :evolve_and_black_out, proc { |decision, canLose| # Check for evolutions pbEvolutionCheck if Settings::CHECK_EVOLUTION_AFTER_ALL_BATTLES || (decision != 2 && decision != 5) # not a loss or a draw $game_temp.party_levels_before_battle = nil $game_temp.party_critical_hits_dealt = nil $game_temp.party_direct_damage_taken = nil # Check for blacking out or gaining Pickup/Huney Gather items case decision when 1, 4 # Win, capture $player.pokemon_party.each do |pkmn| pbPickup(pkmn) pbHoneyGather(pkmn) end when 2, 5 # Lose, draw if !canLose $game_system.bgm_unpause $game_system.bgs_unpause pbStartOver end end } ) def pbEvolutionCheck $player.party.each_with_index do |pkmn, i| next if !pkmn || pkmn.egg? next if pkmn.fainted? && !Settings::CHECK_EVOLUTION_FOR_FAINTED_POKEMON # Find an evolution new_species = nil if new_species.nil? && $game_temp.party_levels_before_battle && $game_temp.party_levels_before_battle[i] && $game_temp.party_levels_before_battle[i] < pkmn.level new_species = pkmn.check_evolution_on_level_up end new_species = pkmn.check_evolution_after_battle(i) if new_species.nil? next if new_species.nil? # Evolve Pokémon if possible evo = PokemonEvolutionScene.new evo.pbStartScreen(pkmn, new_species) evo.pbEvolution evo.pbEndScreen end end def pbDynamicItemList(*args) ret = [] args.each { |arg| ret.push(arg) if GameData::Item.exists?(arg) } return ret end # Common items to find via Pickup. Items from this list are added to the pool in # order, starting from a point dependng on the Pokémon's level. The number of # items added is how many probabilities are in the PICKUP_COMMON_ITEM_CHANCES # array below. # There must be 9 + PICKUP_COMMON_ITEM_CHANCES.length number of items in this # array (18 by default). The 9 is actually (100 / num_rarity_levels) - 1, where # num_rarity_levels is in def pbPickup below. PICKUP_COMMON_ITEMS = [ :POTION, # Levels 1-10 :ANTIDOTE, # Levels 1-10, 11-20 :SUPERPOTION, # Levels 1-10, 11-20, 21-30 :GREATBALL, # Levels 1-10, 11-20, 21-30, 31-40 :REPEL, # Levels 1-10, 11-20, 21-30, 31-40, 41-50 :ESCAPEROPE, # Levels 1-10, 11-20, 21-30, 31-40, 41-50, 51-60 :FULLHEAL, # Levels 1-10, 11-20, 21-30, 31-40, 41-50, 51-60, 61-70 :HYPERPOTION, # Levels 1-10, 11-20, 21-30, 31-40, 41-50, 51-60, 61-70, 71-80 :ULTRABALL, # Levels 1-10, 11-20, 21-30, 31-40, 41-50, 51-60, 61-70, 71-80, 81-90 :REVIVE, # Levels 11-20, 21-30, 31-40, 41-50, 51-60, 61-70, 71-80, 81-90, 91-100 :RARECANDY, # Levels 21-30, 31-40, 41-50, 51-60, 61-70, 71-80, 81-90, 91-100 :SUNSTONE, # Levels 31-40, 41-50, 51-60, 61-70, 71-80, 81-90, 91-100 :MOONSTONE, # Levels 41-50, 51-60, 61-70, 71-80, 81-90, 91-100 :HEARTSCALE, # Levels 51-60, 61-70, 71-80, 81-90, 91-100 :FULLRESTORE, # Levels 61-70, 71-80, 81-90, 91-100 :MAXREVIVE, # Levels 71-80, 81-90, 91-100 :PPUP, # Levels 81-90, 91-100 :MAXELIXIR # Levels 91-100 ] # Chances to get each item added to the pool from the array above. PICKUP_COMMON_ITEM_CHANCES = [30, 10, 10, 10, 10, 10, 10, 4, 4] # Rare items to find via Pickup. Items from this list are added to the pool in # order, starting from a point dependng on the Pokémon's level. The number of # items added is how many probabilities are in the PICKUP_RARE_ITEM_CHANCES # array below. # There must be 9 + PICKUP_RARE_ITEM_CHANCES.length number of items in this # array (11 by default). The 9 is actually (100 / num_rarity_levels) - 1, where # num_rarity_levels is in def pbPickup below. PICKUP_RARE_ITEMS = [ :HYPERPOTION, # Levels 1-10 :NUGGET, # Levels 1-10, 11-20 :KINGSROCK, # Levels 11-20, 21-30 :FULLRESTORE, # Levels 21-30, 31-40 :ETHER, # Levels 31-40, 41-50 :IRONBALL, # Levels 41-50, 51-60 :DESTINYKNOT, # Levels 51-60, 61-70 :ELIXIR, # Levels 61-70, 71-80 :DESTINYKNOT, # Levels 71-80, 81-90 :LEFTOVERS, # Levels 81-90, 91-100 :DESTINYKNOT # Levels 91-100 ] # Chances to get each item added to the pool from the array above. PICKUP_RARE_ITEM_CHANCES = [1, 1] # Try to gain an item after a battle if a Pokemon has the ability Pickup. def pbPickup(pkmn) return if pkmn.egg? || !pkmn.hasAbility?(:PICKUP) return if pkmn.hasItem? return unless rand(100) < 10 # 10% chance for Pickup to trigger num_rarity_levels = 10 # Ensure common and rare item lists contain defined items common_items = pbDynamicItemList(*PICKUP_COMMON_ITEMS) rare_items = pbDynamicItemList(*PICKUP_RARE_ITEMS) return if common_items.length < num_rarity_levels - 1 + PICKUP_COMMON_ITEM_CHANCES.length return if rare_items.length < num_rarity_levels - 1 + PICKUP_RARE_ITEM_CHANCES.length # Determine the starting point for adding items from the above arrays into the # pool start_index = [([100, pkmn.level].min - 1) * num_rarity_levels / 100, 0].max # Generate a pool of items depending on the Pokémon's level items = [] PICKUP_COMMON_ITEM_CHANCES.length.times { |i| items.push(common_items[start_index + i]) } PICKUP_RARE_ITEM_CHANCES.length.times { |i| items.push(rare_items[start_index + i]) } # Randomly choose an item from the pool to give to the Pokémon all_chances = PICKUP_COMMON_ITEM_CHANCES + PICKUP_RARE_ITEM_CHANCES rnd = rand(all_chances.sum) cumul = 0 all_chances.each_with_index do |c, i| cumul += c next if rnd >= cumul pkmn.item = items[i] break end end # Try to gain a Honey item after a battle if a Pokemon has the ability Honey Gather. def pbHoneyGather(pkmn) return if !GameData::Item.exists?(:HONEY) return if pkmn.egg? || !pkmn.hasAbility?(:HONEYGATHER) || pkmn.hasItem? chance = 5 + (((pkmn.level - 1) / 10) * 5) return unless rand(100) < chance pkmn.item = :HONEY end
412
0.886366
1
0.886366
game-dev
MEDIA
0.956544
game-dev
0.925244
1
0.925244
spatialos/gdk-for-unity
1,983
workers/unity/Packages/io.improbable.gdk.mobile/Utility/LaunchArguments.cs
using System.Collections.Generic; using Improbable.Gdk.Core; using UnityEngine; #if UNITY_ANDROID || UNITY_IOS using System; #endif namespace Improbable.Gdk.Mobile { public static class LaunchArguments { public const string iOSEnvironmentKey = "SPATIALOS_ARGUMENTS"; public static CommandLineArgs GetArguments() { if (Application.isEditor) { return CommandLineArgs.From(new Dictionary<string, string>()); } #if UNITY_ANDROID try { using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) using (var currentActivity = unityPlayer.GetStatic<UnityEngine.AndroidJavaObject>("currentActivity")) using (var intent = currentActivity.Call<AndroidJavaObject>("getIntent")) { var hasExtra = intent.Call<bool>("hasExtra", "arguments"); if (hasExtra) { using (var extras = intent.Call<AndroidJavaObject>("getExtras")) { var arguments = extras.Call<string>("getString", "arguments").Split(' '); return CommandLineArgs.From(arguments); } } } } catch (Exception e) { Debug.LogException(e); } #elif UNITY_IOS try { var argumentsEnvVar = System.Environment.GetEnvironmentVariable(iOSEnvironmentKey); if (argumentsEnvVar != null) { return CommandLineArgs.From(argumentsEnvVar.Split(' ')); } } catch (Exception e) { Debug.LogException(e); } #endif return CommandLineArgs.From(new Dictionary<string, string>()); } } }
412
0.757383
1
0.757383
game-dev
MEDIA
0.627306
game-dev,mobile
0.774121
1
0.774121
glKarin/com.n0n3m4.diii4a
20,064
Q3E/src/main/jni/source/hammer/mapcylinder.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: This helper is used for entities that represent a line between two // entities. Examples of these are: beams and special node connections. // // The helper factory parameters are: // // <red> <green> <blue> <start key> <start key value> <end key> <end key value> // // The line helper looks in the given keys in its parent entity and // attaches itself to the entities with those key values. If only one // endpoint entity is specified, the other end is assumed to be the parent // entity. // //=============================================================================// #include "stdafx.h" #include "Box3D.h" #include "MapEntity.h" #include "MapCylinder.h" #include "MapWorld.h" #include "Render2D.h" #include "Render3D.h" #include "TextureSystem.h" #include "materialsystem/imesh.h" #include "Material.h" #include "mapdoc.h" #include "options.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> IMPLEMENT_MAPCLASS(CMapCylinder); #define CYLINDER_VERTEX_COUNT 16 #define CYLINDER_VERTEX_COUNT_2D 8 //----------------------------------------------------------------------------- // Purpose: Factory function. Used for creating a CMapCylinder from a set // of string parameters from the FGD file. // Input : *pInfo - Pointer to helper info class which gives us information // about how to create the class. // Output : Returns a pointer to the class, NULL if an error occurs. //----------------------------------------------------------------------------- CMapClass *CMapCylinder::Create(CHelperInfo *pHelperInfo, CMapEntity *pParent) { CMapCylinder *pCylinder = NULL; // // Extract the line color from the parameter list. // unsigned char chRed = 255; unsigned char chGreen = 255; unsigned char chBlue = 255; const char *pszParam = pHelperInfo->GetParameter(0); if (pszParam != NULL) { chRed = atoi(pszParam); } pszParam = pHelperInfo->GetParameter(1); if (pszParam != NULL) { chGreen = atoi(pszParam); } pszParam = pHelperInfo->GetParameter(2); if (pszParam != NULL) { chBlue = atoi(pszParam); } const char *pszStartKey = pHelperInfo->GetParameter(3); const char *pszStartValueKey = pHelperInfo->GetParameter(4); const char *pszStartRadiusKey = pHelperInfo->GetParameter(5); const char *pszEndKey = pHelperInfo->GetParameter(6); const char *pszEndValueKey = pHelperInfo->GetParameter(7); const char *pszEndRadiusKey = pHelperInfo->GetParameter(8); // // Make sure we'll have at least one endpoint to work with. // if ((pszStartKey == NULL) || (pszStartValueKey == NULL)) { return NULL; } pCylinder = new CMapCylinder(pszStartKey, pszStartValueKey, pszStartRadiusKey, pszEndKey, pszEndValueKey, pszEndRadiusKey); pCylinder->SetRenderColor(chRed, chGreen, chBlue); // // If they only specified a start entity, use our parent as the end entity. // if ((pszEndKey == NULL) || (pszEndValueKey == NULL)) { pCylinder->m_pEndEntity = pParent; } return(pCylinder); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CMapCylinder::CMapCylinder(void) { Initialize(); } //----------------------------------------------------------------------------- // Purpose: Constructor. Initializes data members. // Input : pszStartKey - The key to search in other entities for a match against the value of pszStartValueKey, ex 'targetname'. // pszStartValueKey - The key in our parent entity from which to get a search term for the start entity ex 'beamstart01'. // pszEndKey - The key to search in other entities for a match against the value of pszEndValueKey ex 'targetname'. // pszEndValueKey - The key in our parent entity from which to get a search term for the end entity ex 'beamend01'. //----------------------------------------------------------------------------- CMapCylinder::CMapCylinder(const char *pszStartKey, const char *pszStartValueKey, const char *pszStartRadiusKey, const char *pszEndKey, const char *pszEndValueKey, const char *pszEndRadiusKey ) { Initialize(); strcpy(m_szStartKey, pszStartKey); strcpy(m_szStartValueKey, pszStartValueKey); if ( pszStartRadiusKey != NULL ) { strcpy(m_szStartRadiusKey, pszStartRadiusKey); } if ((pszEndKey != NULL) && (pszEndValueKey != NULL)) { strcpy(m_szEndKey, pszEndKey); strcpy(m_szEndValueKey, pszEndValueKey); if ( pszEndRadiusKey != NULL ) { strcpy(m_szEndRadiusKey, pszEndRadiusKey); } } } //----------------------------------------------------------------------------- // Purpose: Sets data members to initial values. //----------------------------------------------------------------------------- void CMapCylinder::Initialize(void) { m_szStartKey[0] = '\0'; m_szStartValueKey[0] = '\0'; m_szStartRadiusKey[0] = '\0'; m_szEndKey[0] = '\0'; m_szEndValueKey[0] = '\0'; m_szEndRadiusKey[0] = '\0'; m_pStartEntity = NULL; m_pEndEntity = NULL; } //----------------------------------------------------------------------------- // Purpose: Destructor. //----------------------------------------------------------------------------- CMapCylinder::~CMapCylinder(void) { } //----------------------------------------------------------------------------- // Purpose: Calculates the midpoint of the line and sets our origin there. //----------------------------------------------------------------------------- void CMapCylinder::BuildCylinder(void) { if ((m_pStartEntity != NULL) && (m_pEndEntity != NULL)) { // // Set our origin to our midpoint. This moves our selection handle box to the // midpoint. // Vector Start; Vector End; m_pStartEntity->GetOrigin(Start); m_pEndEntity->GetOrigin(End); SetOrigin((Start + End) / 2); } CalcBounds(); } //----------------------------------------------------------------------------- // Purpose: Recalculates our bounding box. // Input : bFullUpdate - Whether to force our children to recalculate or not. //----------------------------------------------------------------------------- void CMapCylinder::CalcBounds(BOOL bFullUpdate) { CMapClass::CalcBounds(bFullUpdate); // // Don't calculate 2D bounds - we don't occupy any space in 2D. This keeps our // parent entity's bounds from expanding to encompass our endpoints. // // // Update our 3D culling box and possibly our origin. // // If our start and end entities are resolved, calcuate our bounds // based on the positions of the start and end entities. // if (m_pStartEntity && m_pEndEntity) { // // Update the 3D bounds. // Vector Start; Vector End; Vector pStartVerts[CYLINDER_VERTEX_COUNT]; Vector pEndVerts[CYLINDER_VERTEX_COUNT]; ComputeCylinderPoints( CYLINDER_VERTEX_COUNT, pStartVerts, pEndVerts ); for ( int i = 0; i < CYLINDER_VERTEX_COUNT; ++i ) { m_CullBox.UpdateBounds(pStartVerts[i]); m_CullBox.UpdateBounds(pEndVerts[i]); } m_BoundingBox = m_CullBox; } } //----------------------------------------------------------------------------- // Purpose: // Input : bUpdateDependencies - // Output : CMapClass //----------------------------------------------------------------------------- CMapClass *CMapCylinder::Copy(bool bUpdateDependencies) { CMapCylinder *pCopy = new CMapCylinder; if (pCopy != NULL) { pCopy->CopyFrom(this, bUpdateDependencies); } return(pCopy); } //----------------------------------------------------------------------------- // Purpose: Turns 'this' into an exact replica of 'pObject'. // Input : pObject - Object to replicate. // bUpdateDependencies - // Output : //----------------------------------------------------------------------------- CMapClass *CMapCylinder::CopyFrom(CMapClass *pObject, bool bUpdateDependencies) { CMapCylinder *pFrom = dynamic_cast <CMapCylinder *>(pObject); if (pFrom != NULL) { CMapClass::CopyFrom(pObject, bUpdateDependencies); if (bUpdateDependencies) { m_pStartEntity = (CMapEntity *)UpdateDependency(m_pStartEntity, pFrom->m_pStartEntity); m_pEndEntity = (CMapEntity *)UpdateDependency(m_pEndEntity, pFrom->m_pEndEntity); } else { m_pStartEntity = pFrom->m_pStartEntity; m_pEndEntity = pFrom->m_pEndEntity; } m_flStartRadius = pFrom->m_flStartRadius; m_flEndRadius = pFrom->m_flEndRadius; strcpy(m_szStartValueKey, pFrom->m_szStartValueKey); strcpy(m_szStartKey, pFrom->m_szStartKey); strcpy(m_szStartRadiusKey, pFrom->m_szStartRadiusKey); strcpy(m_szEndValueKey, pFrom->m_szEndValueKey); strcpy(m_szEndKey, pFrom->m_szEndKey); strcpy(m_szEndRadiusKey, pFrom->m_szEndRadiusKey); } return(this); } //----------------------------------------------------------------------------- // Purpose: Called after this object is added to the world. // // NOTE: This function is NOT called during serialization. Use PostloadWorld // to do similar bookkeeping after map load. // // Input : pWorld - The world that we have been added to. //----------------------------------------------------------------------------- void CMapCylinder::OnAddToWorld(CMapWorld *pWorld) { CMapClass::OnAddToWorld(pWorld); // // Updates our start and end entity pointers since we are being added // into the world. // UpdateDependencies(pWorld, NULL); } //----------------------------------------------------------------------------- // Purpose: Called just after this object has been removed from the world so // that it can unlink itself from other objects in the world. // Input : pWorld - The world that we were just removed from. // bNotifyChildren - Whether we should forward notification to our children. //----------------------------------------------------------------------------- void CMapCylinder::OnRemoveFromWorld(CMapWorld *pWorld, bool bNotifyChildren) { CMapClass::OnRemoveFromWorld(pWorld, bNotifyChildren); // // Detach ourselves from the endpoint entities. // m_pStartEntity = (CMapEntity *)UpdateDependency(m_pStartEntity, NULL); m_pEndEntity = (CMapEntity *)UpdateDependency(m_pEndEntity, NULL); } //----------------------------------------------------------------------------- // Purpose: Our start or end entity has changed; recalculate our bounds and midpoint. // Input : pObject - Entity that changed. //----------------------------------------------------------------------------- void CMapCylinder::OnNotifyDependent(CMapClass *pObject, Notify_Dependent_t eNotifyType) { CMapClass::OnNotifyDependent(pObject, eNotifyType); CMapWorld *pWorld = (CMapWorld *)GetWorldObject(this); UpdateDependencies(pWorld, pObject); } //----------------------------------------------------------------------------- // Purpose: // Input : key - // value - //----------------------------------------------------------------------------- void CMapCylinder::OnParentKeyChanged( const char* key, const char* value ) { CMapWorld *pWorld = (CMapWorld *)GetWorldObject(this); if (pWorld != NULL) { if (stricmp(key, m_szStartValueKey) == 0) { m_pStartEntity = (CMapEntity *)UpdateDependency(m_pStartEntity, pWorld->FindChildByKeyValue(m_szStartKey, value)); BuildCylinder(); } else if (stricmp(key, m_szEndValueKey) == 0) { m_pEndEntity = (CMapEntity *)UpdateDependency(m_pEndEntity, pWorld->FindChildByKeyValue(m_szEndKey, value)); BuildCylinder(); } if (m_pStartEntity && stricmp(key, m_szStartRadiusKey) == 0) { const char *pRadiusKey = m_pStartEntity->GetKeyValue( m_szStartRadiusKey ); m_flStartRadius = pRadiusKey ? atof( pRadiusKey ) : 0.0f; BuildCylinder(); } if (m_pEndEntity && stricmp(key, m_szEndRadiusKey) == 0) { const char *pRadiusKey = m_pEndEntity->GetKeyValue( m_szEndRadiusKey ); m_flEndRadius = pRadiusKey ? atof( pRadiusKey ) : 0.0f; BuildCylinder(); } } } //----------------------------------------------------------------------------- // Computes the vertices of the cylinder //----------------------------------------------------------------------------- void CMapCylinder::ComputeCylinderPoints( int nCount, Vector *pStartVerts, Vector *pEndVerts ) { Assert ((m_pStartEntity != NULL) && (m_pEndEntity != NULL)); Vector vecStart; Vector vecEnd; m_pStartEntity->GetOrigin(vecStart); m_pEndEntity->GetOrigin(vecEnd); // Compute a basis perpendicular to the entities Vector xvec, yvec, zvec; VectorSubtract( vecEnd, vecStart, zvec ); float flLength = VectorNormalize( zvec ); if ( flLength < 1e-3 ) { zvec.Init( 0, 0, 1 ); } VectorVectors( zvec, xvec, yvec ); int i; float flDAngle = 2.0f * M_PI / nCount; for ( i = 0; i < nCount; ++i ) { float flCosAngle = cos( flDAngle * i ); float flSinAngle = sin( flDAngle * i ); VectorMA( vecStart, flCosAngle * m_flStartRadius, xvec, pStartVerts[i] ); VectorMA( pStartVerts[i], flSinAngle * m_flStartRadius, yvec, pStartVerts[i] ); VectorMA( vecEnd, flCosAngle * m_flEndRadius, xvec, pEndVerts[i] ); VectorMA( pEndVerts[i], flSinAngle * m_flEndRadius, yvec, pEndVerts[i] ); } } //----------------------------------------------------------------------------- // Should we draw the cylinder as a line? //----------------------------------------------------------------------------- bool CMapCylinder::ShouldDrawAsLine() { return !IsSelected() || ((m_flStartRadius == 0.0f) && (m_flEndRadius == 0.0f)) || !Options.GetShowHelpers(); } //----------------------------------------------------------------------------- // Purpose: Renders the line helper in the 2D view. // Input : pRender - 2D rendering interface. //----------------------------------------------------------------------------- void CMapCylinder::Render2D(CRender2D *pRender) { if ((m_pStartEntity != NULL) && (m_pEndEntity != NULL)) { if (!ShouldDrawAsLine()) { pRender->SetDrawColor( SELECT_FACE_RED, SELECT_FACE_GREEN, SELECT_FACE_BLUE ); Vector pStartVerts[CYLINDER_VERTEX_COUNT_2D]; Vector pEndVerts[CYLINDER_VERTEX_COUNT_2D]; ComputeCylinderPoints( CYLINDER_VERTEX_COUNT_2D, pStartVerts, pEndVerts ); int j = CYLINDER_VERTEX_COUNT_2D - 1; for (int i = 0; i < CYLINDER_VERTEX_COUNT_2D; j = i++ ) { pRender->DrawLine(pStartVerts[i], pStartVerts[j]); pRender->DrawLine(pEndVerts[i], pEndVerts[j]); pRender->DrawLine(pStartVerts[i], pEndVerts[i]); } } else { pRender->SetDrawColor( r, g, b ); Vector Start; Vector End; m_pStartEntity->GetOrigin(Start); m_pEndEntity->GetOrigin(End); pRender->DrawLine(Start, End); } } } //----------------------------------------------------------------------------- // Purpose: // Input : pRender - //----------------------------------------------------------------------------- void CMapCylinder::Render3D(CRender3D *pRender) { if ( (m_pStartEntity == NULL) || (m_pEndEntity == NULL)) return; pRender->BeginRenderHitTarget(this); pRender->PushRenderMode(RENDER_MODE_WIREFRAME); Vector Start,End; m_pStartEntity->GetOrigin(Start); m_pEndEntity->GetOrigin(End); unsigned char color[3]; if (IsSelected()) { color[0] = SELECT_EDGE_RED; color[1] = SELECT_EDGE_GREEN; color[2] = SELECT_EDGE_BLUE; } else { color[0] = r; color[1] = g; color[2] = b; } CMeshBuilder meshBuilder; CMatRenderContextPtr pRenderContext( MaterialSystemInterface() ); IMesh* pMesh = pRenderContext->GetDynamicMesh(); if ( !ShouldDrawAsLine() ) { Vector pStartVerts[CYLINDER_VERTEX_COUNT]; Vector pEndVerts[CYLINDER_VERTEX_COUNT]; ComputeCylinderPoints( CYLINDER_VERTEX_COUNT, pStartVerts, pEndVerts ); meshBuilder.Begin( pMesh, MATERIAL_LINES, 3 * CYLINDER_VERTEX_COUNT ); int j = CYLINDER_VERTEX_COUNT - 1; for ( int i = 0; i < CYLINDER_VERTEX_COUNT; j = i++ ) { meshBuilder.Color3ubv( color ); meshBuilder.Position3f(pStartVerts[i].x, pStartVerts[i].y, pStartVerts[i].z); meshBuilder.AdvanceVertex(); meshBuilder.Color3ubv( color ); meshBuilder.Position3f(pStartVerts[j].x, pStartVerts[j].y, pStartVerts[j].z); meshBuilder.AdvanceVertex(); meshBuilder.Color3ubv( color ); meshBuilder.Position3f(pEndVerts[i].x, pEndVerts[i].y, pEndVerts[i].z); meshBuilder.AdvanceVertex(); meshBuilder.Color3ubv( color ); meshBuilder.Position3f(pEndVerts[j].x, pEndVerts[j].y, pEndVerts[j].z); meshBuilder.AdvanceVertex(); meshBuilder.Color3ubv( color ); meshBuilder.Position3f(pStartVerts[i].x, pStartVerts[i].y, pStartVerts[i].z); meshBuilder.AdvanceVertex(); meshBuilder.Color3ubv( color ); meshBuilder.Position3f(pEndVerts[i].x, pEndVerts[i].y, pEndVerts[i].z); meshBuilder.AdvanceVertex(); } meshBuilder.End(); } else { meshBuilder.Begin( pMesh, MATERIAL_LINES, 1 ); meshBuilder.Color3ubv( color ); meshBuilder.Position3f(Start.x, Start.y, Start.z); meshBuilder.AdvanceVertex(); meshBuilder.Color3ubv( color ); meshBuilder.Position3f(End.x, End.y, End.z); meshBuilder.AdvanceVertex(); meshBuilder.End(); } pMesh->Draw(); pRender->PopRenderMode(); pRender->EndRenderHitTarget(); } //----------------------------------------------------------------------------- // Purpose: // Input : File - // bRMF - // Output : int //----------------------------------------------------------------------------- int CMapCylinder::SerializeRMF(std::fstream &File, BOOL bRMF) { return(0); } //----------------------------------------------------------------------------- // Purpose: // Input : File - // bRMF - // Output : int //----------------------------------------------------------------------------- int CMapCylinder::SerializeMAP(std::fstream &File, BOOL bRMF) { return(0); } //----------------------------------------------------------------------------- // Purpose: // Input : pTransBox - //----------------------------------------------------------------------------- void CMapCylinder::DoTransform(const VMatrix &matrix) { CMapClass::DoTransform(matrix); BuildCylinder(); } //----------------------------------------------------------------------------- // Purpose: Updates the cached pointers to our start and end entities by looking // for them in the given world. // Input : pWorld - World to search. //----------------------------------------------------------------------------- void CMapCylinder::UpdateDependencies(CMapWorld *pWorld, CMapClass *pObject) { CMapClass::UpdateDependencies(pWorld, pObject); if (pWorld == NULL) { return; } CMapEntity *pEntity = dynamic_cast <CMapEntity *> (m_pParent); Assert(pEntity != NULL); if (pEntity != NULL) { const char *pszValue = pEntity->GetKeyValue(m_szStartValueKey); m_pStartEntity = (CMapEntity *)UpdateDependency(m_pStartEntity, pWorld->FindChildByKeyValue(m_szStartKey, pszValue)); if (m_szEndValueKey[0] != '\0') { pszValue = pEntity->GetKeyValue(m_szEndValueKey); m_pEndEntity = (CMapEntity *)UpdateDependency(m_pEndEntity, pWorld->FindChildByKeyValue(m_szEndKey, pszValue)); } else { // We don't have an end entity specified, use our parent as the end point. m_pEndEntity = (CMapEntity *)UpdateDependency(m_pEndEntity, GetParent()); } if (pObject == m_pStartEntity) { m_flStartRadius = 0.0f; if ( m_pStartEntity && m_szStartRadiusKey[0] != '\0' ) { const char *pRadiusKey = m_pStartEntity->GetKeyValue( m_szStartRadiusKey ); m_flStartRadius = pRadiusKey ? atof( pRadiusKey ) : 0.0f; } } if (pObject == m_pEndEntity) { m_flEndRadius = 0.0f; if ( m_pEndEntity && m_szEndRadiusKey[0] != '\0' ) { const char *pRadiusKey = m_pEndEntity->GetKeyValue( m_szEndRadiusKey ); m_flEndRadius = pRadiusKey ? atof( pRadiusKey ) : 0.0f; } } BuildCylinder(); } } //----------------------------------------------------------------------------- // Purpose: Never select anything because of this helper. //----------------------------------------------------------------------------- CMapClass *CMapCylinder::PrepareSelection(SelectMode_t eSelectMode) { return NULL; }
412
0.936732
1
0.936732
game-dev
MEDIA
0.840726
game-dev
0.976466
1
0.976466
RevereInc/alley-practice
3,088
src/main/java/dev/revere/alley/feature/party/command/impl/member/PartyInviteCommand.java
package dev.revere.alley.feature.party.command.impl.member; import dev.revere.alley.common.text.CC; import dev.revere.alley.core.locale.internal.impl.message.GlobalMessagesLocaleImpl; import dev.revere.alley.core.profile.Profile; import dev.revere.alley.core.profile.ProfileService; import dev.revere.alley.feature.party.Party; import dev.revere.alley.feature.party.PartyService; import dev.revere.alley.library.command.BaseCommand; import dev.revere.alley.library.command.CommandArgs; import dev.revere.alley.library.command.annotation.CommandData; import org.bukkit.Bukkit; import org.bukkit.entity.Player; /** * @author Emmy * @project Alley * @date 25/05/2024 - 18:27 */ public class PartyInviteCommand extends BaseCommand { @Override @CommandData( name = "party.invite", aliases = "p.invite", usage = "party invite <player>", description = "Invite a player to your party." ) public void onCommand(CommandArgs command) { Player player = command.getPlayer(); String[] args = command.getArgs(); PartyService partyService = this.plugin.getService(PartyService.class); ProfileService profileService = this.plugin.getService(ProfileService.class); if (command.length() < 1) { command.sendUsage(); return; } String target = args[0]; Player targetPlayer = Bukkit.getPlayer(target); if (targetPlayer == null) { player.sendMessage(CC.translate("&cThe player you are trying to invite is not online.")); return; } if (targetPlayer == command.getPlayer()) { player.sendMessage(CC.translate("&cYou cannot invite yourself to a party.")); return; } Party party = partyService.getPartyByMember(player.getUniqueId()); if (party == null) { player.sendMessage(CC.translate(this.getString(GlobalMessagesLocaleImpl.ERROR_YOU_NOT_IN_PARTY))); return; } if (party.getLeader() != player) { player.sendMessage(CC.translate("&cYou must be the party leader to invite players.")); return; } Profile targetProfile = profileService.getProfile(targetPlayer.getUniqueId()); if (!targetProfile.getProfileData().getSettingData().isPartyInvitesEnabled()) { player.sendMessage(CC.translate(this.getString(GlobalMessagesLocaleImpl.ERROR_PLAYER_PARTY_INVITES_DISABLED) .replace("{name-color}", String.valueOf(targetProfile.getNameColor())) .replace("{player}", target)) ); return; } if (party.getMembers().contains(targetPlayer.getUniqueId())) { player.sendMessage(CC.translate("&6" + targetPlayer.getName() + " &cis already in your party.")); return; } partyService.sendInvite(party, player, targetPlayer); party.notifyParty("&6" + targetPlayer.getName() + " &awas invited to the party by &6" + player.getName() + "&a."); } }
412
0.753386
1
0.753386
game-dev
MEDIA
0.589174
game-dev
0.83283
1
0.83283
digital-dream-labs/vector
29,968
3rd/protobuf/linux/include/google/protobuf/map_field.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. #ifndef GOOGLE_PROTOBUF_MAP_FIELD_H__ #define GOOGLE_PROTOBUF_MAP_FIELD_H__ #include <atomic> #include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/arena.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/map_entry.h> #include <google/protobuf/map_field_lite.h> #include <google/protobuf/map_type_handler.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/unknown_field_set.h> namespace google { namespace protobuf { class DynamicMessage; class MapKey; namespace internal { class ContendedMapCleanTest; class GeneratedMessageReflection; class MapFieldAccessor; // This class provides access to map field using reflection, which is the same // as those provided for RepeatedPtrField<Message>. It is used for internal // reflection implentation only. Users should never use this directly. class LIBPROTOBUF_EXPORT MapFieldBase { public: MapFieldBase() : arena_(NULL), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) {} explicit MapFieldBase(Arena* arena) : arena_(arena), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) { // Mutex's destructor needs to be called explicitly to release resources // acquired in its constructor. arena->OwnDestructor(&mutex_); } virtual ~MapFieldBase(); // Returns reference to internal repeated field. Data written using // google::protobuf::Map's api prior to calling this function is guarantted to be // included in repeated field. const RepeatedPtrFieldBase& GetRepeatedField() const; // Like above. Returns mutable pointer to the internal repeated field. RepeatedPtrFieldBase* MutableRepeatedField(); // Pure virtual map APIs for Map Reflection. virtual bool ContainsMapKey(const MapKey& map_key) const = 0; virtual bool InsertOrLookupMapValue( const MapKey& map_key, MapValueRef* val) = 0; // Returns whether changes to the map are reflected in the repeated field. bool IsRepeatedFieldValid() const; // Insures operations after won't get executed before calling this. bool IsMapValid() const; virtual bool DeleteMapValue(const MapKey& map_key) = 0; virtual bool EqualIterator(const MapIterator& a, const MapIterator& b) const = 0; virtual void MapBegin(MapIterator* map_iter) const = 0; virtual void MapEnd(MapIterator* map_iter) const = 0; // Sync Map with repeated field and returns the size of map. virtual int size() const = 0; // Returns the number of bytes used by the repeated field, excluding // sizeof(*this) size_t SpaceUsedExcludingSelfLong() const; int SpaceUsedExcludingSelf() const { return internal::ToIntSize(SpaceUsedExcludingSelfLong()); } protected: // Gets the size of space used by map field. virtual size_t SpaceUsedExcludingSelfNoLock() const; // Synchronizes the content in Map to RepeatedPtrField if there is any change // to Map after last synchronization. void SyncRepeatedFieldWithMap() const; virtual void SyncRepeatedFieldWithMapNoLock() const; // Synchronizes the content in RepeatedPtrField to Map if there is any change // to RepeatedPtrField after last synchronization. void SyncMapWithRepeatedField() const; virtual void SyncMapWithRepeatedFieldNoLock() const {} // Tells MapFieldBase that there is new change to Map. void SetMapDirty(); // Tells MapFieldBase that there is new change to RepeatedPTrField. void SetRepeatedDirty(); // Provides derived class the access to repeated field. void* MutableRepeatedPtrField() const; enum State { STATE_MODIFIED_MAP = 0, // map has newly added data that has not been // synchronized to repeated field STATE_MODIFIED_REPEATED = 1, // repeated field has newly added data that // has not been synchronized to map CLEAN = 2, // data in map and repeated field are same }; Arena* arena_; mutable RepeatedPtrField<Message>* repeated_field_; mutable Mutex mutex_; // The thread to synchronize map and repeated field // needs to get lock first; mutable std::atomic<State> state_; private: friend class ContendedMapCleanTest; friend class GeneratedMessageReflection; friend class MapFieldAccessor; friend class ::google::protobuf::DynamicMessage; // Virtual helper methods for MapIterator. MapIterator doesn't have the // type helper for key and value. Call these help methods to deal with // different types. Real helper methods are implemented in // TypeDefinedMapFieldBase. friend class ::google::protobuf::MapIterator; // Allocate map<...>::iterator for MapIterator. virtual void InitializeIterator(MapIterator* map_iter) const = 0; // DeleteIterator() is called by the destructor of MapIterator only. // It deletes map<...>::iterator for MapIterator. virtual void DeleteIterator(MapIterator* map_iter) const = 0; // Copy the map<...>::iterator from other_iterator to // this_iterator. virtual void CopyIterator(MapIterator* this_iterator, const MapIterator& other_iterator) const = 0; // IncreaseIterator() is called by operator++() of MapIterator only. // It implements the ++ operator of MapIterator. virtual void IncreaseIterator(MapIterator* map_iter) const = 0; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldBase); }; // This class provides common Map Reflection implementations for generated // message and dynamic message. template<typename Key, typename T> class TypeDefinedMapFieldBase : public MapFieldBase { public: TypeDefinedMapFieldBase() {} explicit TypeDefinedMapFieldBase(Arena* arena) : MapFieldBase(arena) {} ~TypeDefinedMapFieldBase() {} void MapBegin(MapIterator* map_iter) const; void MapEnd(MapIterator* map_iter) const; bool EqualIterator(const MapIterator& a, const MapIterator& b) const; virtual const Map<Key, T>& GetMap() const = 0; virtual Map<Key, T>* MutableMap() = 0; protected: typename Map<Key, T>::const_iterator& InternalGetIterator( const MapIterator* map_iter) const; private: void InitializeIterator(MapIterator* map_iter) const; void DeleteIterator(MapIterator* map_iter) const; void CopyIterator(MapIterator* this_iteratorm, const MapIterator& that_iterator) const; void IncreaseIterator(MapIterator* map_iter) const; virtual void SetMapIteratorValue(MapIterator* map_iter) const = 0; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeDefinedMapFieldBase); }; // This class provides access to map field using generated api. It is used for // internal generated message implentation only. Users should never use this // directly. template <typename Derived, typename Key, typename T, WireFormatLite::FieldType kKeyFieldType, WireFormatLite::FieldType kValueFieldType, int default_enum_value = 0> class MapField : public TypeDefinedMapFieldBase<Key, T> { // Provide utilities to parse/serialize key/value. Provide utilities to // manipulate internal stored type. typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler; typedef MapTypeHandler<kValueFieldType, T> ValueTypeHandler; // Define message type for internal repeated field. typedef Derived EntryType; typedef MapEntryLite<Derived, Key, T, kKeyFieldType, kValueFieldType, default_enum_value> EntryLiteType; // Define abbreviation for parent MapFieldLite typedef MapFieldLite<Derived, Key, T, kKeyFieldType, kValueFieldType, default_enum_value> MapFieldLiteType; // Enum needs to be handled differently from other types because it has // different exposed type in google::protobuf::Map's api and repeated field's api. For // details see the comment in the implementation of // SyncMapWithRepeatedFieldNoLock. static const bool kIsValueEnum = ValueTypeHandler::kIsEnum; typedef typename MapIf<kIsValueEnum, T, const T&>::type CastValueType; public: typedef typename Derived::SuperType EntryTypeTrait; typedef Map<Key, T> MapType; MapField() {} explicit MapField(Arena* arena) : TypeDefinedMapFieldBase<Key, T>(arena), impl_(arena) {} // Implement MapFieldBase bool ContainsMapKey(const MapKey& map_key) const; bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val); bool DeleteMapValue(const MapKey& map_key); const Map<Key, T>& GetMap() const { MapFieldBase::SyncMapWithRepeatedField(); return impl_.GetMap(); } Map<Key, T>* MutableMap() { MapFieldBase::SyncMapWithRepeatedField(); Map<Key, T>* result = impl_.MutableMap(); MapFieldBase::SetMapDirty(); return result; } // Convenient methods for generated message implementation. int size() const; void Clear(); void MergeFrom(const MapField& other); void Swap(MapField* other); // Used in the implementation of parsing. Caller should take the ownership iff // arena_ is NULL. EntryType* NewEntry() const { return impl_.NewEntry(); } // Used in the implementation of serializing enum value type. Caller should // take the ownership iff arena_ is NULL. EntryType* NewEnumEntryWrapper(const Key& key, const T t) const { return impl_.NewEnumEntryWrapper(key, t); } // Used in the implementation of serializing other value types. Caller should // take the ownership iff arena_ is NULL. EntryType* NewEntryWrapper(const Key& key, const T& t) const { return impl_.NewEntryWrapper(key, t); } private: MapFieldLiteType impl_; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; // Implements MapFieldBase void SyncRepeatedFieldWithMapNoLock() const; void SyncMapWithRepeatedFieldNoLock() const; size_t SpaceUsedExcludingSelfNoLock() const; void SetMapIteratorValue(MapIterator* map_iter) const; friend class ::google::protobuf::Arena; friend class MapFieldStateTest; // For testing, it needs raw access to impl_ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField); }; template <typename T, typename Key, typename Value, WireFormatLite::FieldType kKeyFieldType, WireFormatLite::FieldType kValueFieldType, int default_enum_value> struct MapEntryToMapField<MapEntry<T, Key, Value, kKeyFieldType, kValueFieldType, default_enum_value> > { typedef MapField<T, Key, Value, kKeyFieldType, kValueFieldType, default_enum_value> MapFieldType; }; class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase<MapKey, MapValueRef> { public: explicit DynamicMapField(const Message* default_entry); DynamicMapField(const Message* default_entry, Arena* arena); ~DynamicMapField(); // Implement MapFieldBase bool ContainsMapKey(const MapKey& map_key) const; bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val); bool DeleteMapValue(const MapKey& map_key); const Map<MapKey, MapValueRef>& GetMap() const; Map<MapKey, MapValueRef>* MutableMap(); int size() const; private: Map<MapKey, MapValueRef> map_; const Message* default_entry_; // Implements MapFieldBase void SyncRepeatedFieldWithMapNoLock() const; void SyncMapWithRepeatedFieldNoLock() const; size_t SpaceUsedExcludingSelfNoLock() const; void SetMapIteratorValue(MapIterator* map_iter) const; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMapField); }; } // namespace internal #define TYPE_CHECK(EXPECTEDTYPE, METHOD) \ if (type() != EXPECTEDTYPE) { \ GOOGLE_LOG(FATAL) \ << "Protocol Buffer map usage error:\n" \ << METHOD << " type does not match\n" \ << " Expected : " \ << FieldDescriptor::CppTypeName(EXPECTEDTYPE) << "\n" \ << " Actual : " \ << FieldDescriptor::CppTypeName(type()); \ } // MapKey is an union type for representing any possible // map key. class LIBPROTOBUF_EXPORT MapKey { public: MapKey() : type_(0) { } MapKey(const MapKey& other) : type_(0) { CopyFrom(other); } MapKey& operator=(const MapKey& other) { CopyFrom(other); return *this; } ~MapKey() { if (type_ == FieldDescriptor::CPPTYPE_STRING) { delete val_.string_value_; } } FieldDescriptor::CppType type() const { if (type_ == 0) { GOOGLE_LOG(FATAL) << "Protocol Buffer map usage error:\n" << "MapKey::type MapKey is not initialized. " << "Call set methods to initialize MapKey."; } return (FieldDescriptor::CppType)type_; } void SetInt64Value(int64 value) { SetType(FieldDescriptor::CPPTYPE_INT64); val_.int64_value_ = value; } void SetUInt64Value(uint64 value) { SetType(FieldDescriptor::CPPTYPE_UINT64); val_.uint64_value_ = value; } void SetInt32Value(int32 value) { SetType(FieldDescriptor::CPPTYPE_INT32); val_.int32_value_ = value; } void SetUInt32Value(uint32 value) { SetType(FieldDescriptor::CPPTYPE_UINT32); val_.uint32_value_ = value; } void SetBoolValue(bool value) { SetType(FieldDescriptor::CPPTYPE_BOOL); val_.bool_value_ = value; } void SetStringValue(const string& val) { SetType(FieldDescriptor::CPPTYPE_STRING); *val_.string_value_ = val; } int64 GetInt64Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapKey::GetInt64Value"); return val_.int64_value_; } uint64 GetUInt64Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapKey::GetUInt64Value"); return val_.uint64_value_; } int32 GetInt32Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapKey::GetInt32Value"); return val_.int32_value_; } uint32 GetUInt32Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapKey::GetUInt32Value"); return val_.uint32_value_; } bool GetBoolValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapKey::GetBoolValue"); return val_.bool_value_; } const string& GetStringValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapKey::GetStringValue"); return *val_.string_value_; } bool operator<(const MapKey& other) const { if (type_ != other.type_) { // We could define a total order that handles this case, but // there currently no need. So, for now, fail. GOOGLE_LOG(FATAL) << "Unsupported: type mismatch"; } switch (type()) { case FieldDescriptor::CPPTYPE_DOUBLE: case FieldDescriptor::CPPTYPE_FLOAT: case FieldDescriptor::CPPTYPE_ENUM: case FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Unsupported"; return false; case FieldDescriptor::CPPTYPE_STRING: return *val_.string_value_ < *other.val_.string_value_; case FieldDescriptor::CPPTYPE_INT64: return val_.int64_value_ < other.val_.int64_value_; case FieldDescriptor::CPPTYPE_INT32: return val_.int32_value_ < other.val_.int32_value_; case FieldDescriptor::CPPTYPE_UINT64: return val_.uint64_value_ < other.val_.uint64_value_; case FieldDescriptor::CPPTYPE_UINT32: return val_.uint32_value_ < other.val_.uint32_value_; case FieldDescriptor::CPPTYPE_BOOL: return val_.bool_value_ < other.val_.bool_value_; } return false; } bool operator==(const MapKey& other) const { if (type_ != other.type_) { // To be consistent with operator<, we don't allow this either. GOOGLE_LOG(FATAL) << "Unsupported: type mismatch"; } switch (type()) { case FieldDescriptor::CPPTYPE_DOUBLE: case FieldDescriptor::CPPTYPE_FLOAT: case FieldDescriptor::CPPTYPE_ENUM: case FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Unsupported"; break; case FieldDescriptor::CPPTYPE_STRING: return *val_.string_value_ == *other.val_.string_value_; case FieldDescriptor::CPPTYPE_INT64: return val_.int64_value_ == other.val_.int64_value_; case FieldDescriptor::CPPTYPE_INT32: return val_.int32_value_ == other.val_.int32_value_; case FieldDescriptor::CPPTYPE_UINT64: return val_.uint64_value_ == other.val_.uint64_value_; case FieldDescriptor::CPPTYPE_UINT32: return val_.uint32_value_ == other.val_.uint32_value_; case FieldDescriptor::CPPTYPE_BOOL: return val_.bool_value_ == other.val_.bool_value_; } GOOGLE_LOG(FATAL) << "Can't get here."; return false; } void CopyFrom(const MapKey& other) { SetType(other.type()); switch (type_) { case FieldDescriptor::CPPTYPE_DOUBLE: case FieldDescriptor::CPPTYPE_FLOAT: case FieldDescriptor::CPPTYPE_ENUM: case FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Unsupported"; break; case FieldDescriptor::CPPTYPE_STRING: *val_.string_value_ = *other.val_.string_value_; break; case FieldDescriptor::CPPTYPE_INT64: val_.int64_value_ = other.val_.int64_value_; break; case FieldDescriptor::CPPTYPE_INT32: val_.int32_value_ = other.val_.int32_value_; break; case FieldDescriptor::CPPTYPE_UINT64: val_.uint64_value_ = other.val_.uint64_value_; break; case FieldDescriptor::CPPTYPE_UINT32: val_.uint32_value_ = other.val_.uint32_value_; break; case FieldDescriptor::CPPTYPE_BOOL: val_.bool_value_ = other.val_.bool_value_; break; } } private: template <typename K, typename V> friend class internal::TypeDefinedMapFieldBase; friend class MapIterator; friend class internal::DynamicMapField; union KeyValue { KeyValue() {} string* string_value_; int64 int64_value_; int32 int32_value_; uint64 uint64_value_; uint32 uint32_value_; bool bool_value_; } val_; void SetType(FieldDescriptor::CppType type) { if (type_ == type) return; if (type_ == FieldDescriptor::CPPTYPE_STRING) { delete val_.string_value_; } type_ = type; if (type_ == FieldDescriptor::CPPTYPE_STRING) { val_.string_value_ = new string; } } // type_ is 0 or a valid FieldDescriptor::CppType. int type_; }; // MapValueRef points to a map value. class LIBPROTOBUF_EXPORT MapValueRef { public: MapValueRef() : data_(NULL), type_(0) {} void SetInt64Value(int64 value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapValueRef::SetInt64Value"); *reinterpret_cast<int64*>(data_) = value; } void SetUInt64Value(uint64 value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapValueRef::SetUInt64Value"); *reinterpret_cast<uint64*>(data_) = value; } void SetInt32Value(int32 value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapValueRef::SetInt32Value"); *reinterpret_cast<int32*>(data_) = value; } void SetUInt32Value(uint32 value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapValueRef::SetUInt32Value"); *reinterpret_cast<uint32*>(data_) = value; } void SetBoolValue(bool value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapValueRef::SetBoolValue"); *reinterpret_cast<bool*>(data_) = value; } // TODO(jieluo) - Checks that enum is member. void SetEnumValue(int value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, "MapValueRef::SetEnumValue"); *reinterpret_cast<int*>(data_) = value; } void SetStringValue(const string& value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapValueRef::SetStringValue"); *reinterpret_cast<string*>(data_) = value; } void SetFloatValue(float value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, "MapValueRef::SetFloatValue"); *reinterpret_cast<float*>(data_) = value; } void SetDoubleValue(double value) { TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, "MapValueRef::SetDoubleValue"); *reinterpret_cast<double*>(data_) = value; } int64 GetInt64Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapValueRef::GetInt64Value"); return *reinterpret_cast<int64*>(data_); } uint64 GetUInt64Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapValueRef::GetUInt64Value"); return *reinterpret_cast<uint64*>(data_); } int32 GetInt32Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapValueRef::GetInt32Value"); return *reinterpret_cast<int32*>(data_); } uint32 GetUInt32Value() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapValueRef::GetUInt32Value"); return *reinterpret_cast<uint32*>(data_); } bool GetBoolValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapValueRef::GetBoolValue"); return *reinterpret_cast<bool*>(data_); } int GetEnumValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, "MapValueRef::GetEnumValue"); return *reinterpret_cast<int*>(data_); } const string& GetStringValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapValueRef::GetStringValue"); return *reinterpret_cast<string*>(data_); } float GetFloatValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, "MapValueRef::GetFloatValue"); return *reinterpret_cast<float*>(data_); } double GetDoubleValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, "MapValueRef::GetDoubleValue"); return *reinterpret_cast<double*>(data_); } const Message& GetMessageValue() const { TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE, "MapValueRef::GetMessageValue"); return *reinterpret_cast<Message*>(data_); } Message* MutableMessageValue() { TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE, "MapValueRef::MutableMessageValue"); return reinterpret_cast<Message*>(data_); } private: template <typename Derived, typename K, typename V, internal::WireFormatLite::FieldType key_wire_type, internal::WireFormatLite::FieldType value_wire_type, int default_enum_value> friend class internal::MapField; template <typename K, typename V> friend class internal::TypeDefinedMapFieldBase; friend class MapIterator; friend class internal::GeneratedMessageReflection; friend class internal::DynamicMapField; void SetType(FieldDescriptor::CppType type) { type_ = type; } FieldDescriptor::CppType type() const { if (type_ == 0 || data_ == NULL) { GOOGLE_LOG(FATAL) << "Protocol Buffer map usage error:\n" << "MapValueRef::type MapValueRef is not initialized."; } return (FieldDescriptor::CppType)type_; } void SetValue(const void* val) { data_ = const_cast<void*>(val); } void CopyFrom(const MapValueRef& other) { type_ = other.type_; data_ = other.data_; } // Only used in DynamicMapField void DeleteData() { switch (type_) { #define HANDLE_TYPE(CPPTYPE, TYPE) \ case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \ delete reinterpret_cast<TYPE*>(data_); \ break; \ } HANDLE_TYPE(INT32, int32); HANDLE_TYPE(INT64, int64); HANDLE_TYPE(UINT32, uint32); HANDLE_TYPE(UINT64, uint64); HANDLE_TYPE(DOUBLE, double); HANDLE_TYPE(FLOAT, float); HANDLE_TYPE(BOOL, bool); HANDLE_TYPE(STRING, string); HANDLE_TYPE(ENUM, int32); HANDLE_TYPE(MESSAGE, Message); #undef HANDLE_TYPE } } // data_ point to a map value. MapValueRef does not // own this value. void* data_; // type_ is 0 or a valid FieldDescriptor::CppType. int type_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapValueRef); }; #undef TYPE_CHECK class LIBPROTOBUF_EXPORT MapIterator { public: MapIterator(Message* message, const FieldDescriptor* field) { const Reflection* reflection = message->GetReflection(); map_ = reflection->MapData(message, field); key_.SetType(field->message_type()->FindFieldByName("key")->cpp_type()); value_.SetType(field->message_type()->FindFieldByName("value")->cpp_type()); map_->InitializeIterator(this); } MapIterator(const MapIterator& other) { map_ = other.map_; map_->InitializeIterator(this); map_->CopyIterator(this, other); } ~MapIterator() { map_->DeleteIterator(this); } MapIterator& operator=(const MapIterator& other) { map_ = other.map_; map_->CopyIterator(this, other); return *this; } friend bool operator==(const MapIterator& a, const MapIterator& b) { return a.map_->EqualIterator(a, b); } friend bool operator!=(const MapIterator& a, const MapIterator& b) { return !a.map_->EqualIterator(a, b); } MapIterator& operator++() { map_->IncreaseIterator(this); return *this; } MapIterator operator++(int) { // iter_ is copied from Map<...>::iterator, no need to // copy from its self again. Use the same implementation // with operator++() map_->IncreaseIterator(this); return *this; } const MapKey& GetKey() { return key_; } const MapValueRef& GetValueRef() { return value_; } MapValueRef* MutableValueRef() { map_->SetMapDirty(); return &value_; } private: template <typename Key, typename T> friend class internal::TypeDefinedMapFieldBase; friend class internal::DynamicMapField; template <typename Derived, typename Key, typename T, internal::WireFormatLite::FieldType kKeyFieldType, internal::WireFormatLite::FieldType kValueFieldType, int default_enum_value> friend class internal::MapField; // reinterpret_cast from heap-allocated Map<...>::iterator*. MapIterator owns // the iterator. It is allocated by MapField<...>::InitializeIterator() called // in constructor and deleted by MapField<...>::DeleteIterator() called in // destructor. void* iter_; // Point to a MapField to call helper methods implemented in MapField. // MapIterator does not own this object. internal::MapFieldBase* map_; MapKey key_; MapValueRef value_; }; } // namespace protobuf } // namespace google GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START template<> struct hash<google::protobuf::MapKey> { size_t operator()(const google::protobuf::MapKey& map_key) const { switch (map_key.type()) { case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: GOOGLE_LOG(FATAL) << "Unsupported"; break; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: return hash<string>()(map_key.GetStringValue()); case google::protobuf::FieldDescriptor::CPPTYPE_INT64: return hash<::google::protobuf::int64>()(map_key.GetInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_INT32: return hash<::google::protobuf::int32>()(map_key.GetInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: return hash<::google::protobuf::uint64>()(map_key.GetUInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: return hash<::google::protobuf::uint32>()(map_key.GetUInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return hash<bool>()(map_key.GetBoolValue()); } GOOGLE_LOG(FATAL) << "Can't get here."; return 0; } bool operator()(const google::protobuf::MapKey& map_key1, const google::protobuf::MapKey& map_key2) const { return map_key1 < map_key2; } }; GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END #endif // GOOGLE_PROTOBUF_MAP_FIELD_H__
412
0.883834
1
0.883834
game-dev
MEDIA
0.767365
game-dev
0.810468
1
0.810468
ever-co/ever-rec-desktop
6,493
libs/electron/utils/src/lib/services/scheduler/timer-scheduler.ts
import { ILoggable, ILogger } from '@ever-co/shared-utils'; import { EventEmitter } from 'events'; import { join } from 'path'; import { ElectronLogger } from '../logger/electron-logger'; import { WorkerFactory } from '../worker-factory.service'; /** * TimerScheduler is a singleton class that manages a timer, which emits a 'tick' event every second. * The timer is efficiently managed and only one instance exists at a time. */ export class TimerScheduler implements ILoggable { private static instance: TimerScheduler; private secondsElapsed = 0; private worker = WorkerFactory.createWorker( join(__dirname, 'assets', 'workers', 'timer.worker') ); public logger: ILogger = new ElectronLogger('Timer Scheduler'); private emitter = new EventEmitter(); /** * Initializes a new instance of the TimerScheduler class. * Sets up event listeners for the worker to handle messages and errors. * The 'message' event is handled by binding the handleWorkerMessage function, * and the 'error' event logs the error using the logger. * This constructor is private to ensure that the TimerScheduler class remains a singleton. */ private constructor() { this.worker.on('message', this.handleWorkerMessage.bind(this)); this.worker.on('error', (error) => { this.logger.error('Worker error:', error); }); } /** * Handles messages from the worker. * The message will be an object with an 'action' and 'secondsElapsed' property. * The 'action' property can have the following values: * - 'tick': The worker emits this event every second. * - 'stop': The worker emits this event when it is stopped. * - 'start': The worker emits this event when it is started. * The 'secondsElapsed' property is the number of seconds that have elapsed since the worker was started. * @param message - The message object with 'action' and 'secondsElapsed' properties. */ private handleWorkerMessage({ action, secondsElapsed, error, }: { action: string; secondsElapsed: number; error?: Error; }): void { switch (action) { case 'tick': /** * Emits the 'tick' event with the number of seconds elapsed since the worker was started. * @event TimerScheduler#tick * @property {number} secondsElapsed - The number of seconds that have elapsed since the worker was started. */ this.secondsElapsed = secondsElapsed; this.emitter.emit('tick', this.secondsElapsed); break; case 'error': this.logger.error('Worker error:', error); break; case 'stop': /** * Removes all listeners for the 'tick' event. */ this.emitter.removeAllListeners('tick'); /** * Emits the 'stop' event with the number of seconds elapsed since the worker was started. * @event TimerScheduler#stop * @property {number} secondsElapsed - The number of seconds that have elapsed since the worker was started. */ this.emitter.emit('stop', this.secondsElapsed); this.secondsElapsed = 0; // Reset break; case 'start': /** * Emits the 'start' event. * @event TimerScheduler#start */ this.emitter.emit('start'); break; default: this.logger.warn('Unknown action:', action); break; } } /** * Returns the singleton instance of TimerScheduler. * Creates a new instance if it does not exist yet. * * @returns The singleton instance of TimerScheduler. */ public static getInstance(): TimerScheduler { if (!this.instance) { this.instance = new TimerScheduler(); } return this.instance; } /** * Starts the timer. * * If the timer is already running, this call has no effect. */ public start(): void { if (this.worker) { /** * Sends a message to the worker to start the timer. */ this.worker.postMessage({ action: 'start' }); } } /** * Pauses the timer. * * If the worker is available, sends a message to pause the timer. * This will result in the timer being paused until it is resumed or stopped. */ public pause(): void { if (this.worker) { /** * Sends a message to the worker to start the timer. */ this.worker.postMessage({ action: 'pause' }); } } /** * Resumes the timer from a paused state. * * If the timer is currently paused, this will resume it. If the timer is not paused, * this has no effect. */ public resume(): void { if (this.worker) { /** * Sends a message to the worker to start the timer. */ this.worker.postMessage({ action: 'resume' }); } } /** * Stops the timer. * * Sends a message to the worker to stop the timer if the worker is available. * This will result in the 'stop' event being emitted with the total seconds elapsed. */ public stop(): void { if (this.worker) { /** * Sends a message to the worker to stop the timer. */ this.worker.postMessage({ action: 'stop' }); } } /** * Returns the total number of seconds that have elapsed since the timer was started. * * @returns The number of seconds elapsed. */ public getSecondsElapsed(): number { return this.secondsElapsed; } /** * Registers a callback to be executed every time the 'tick' event is emitted. * The callback receives the total number of seconds elapsed as an argument. * * @param callback - Function that takes the total seconds elapsed as an argument. */ public onTick(callback: (secondsElapsed: number) => void): void { this.emitter.on('tick', callback); } /** * Registers a callback to be executed when the 'stop' event is emitted. * The callback will be triggered when the timer is stopped and receives the total elapsed time. * * @param callback - Function that will be executed when the timer is stopped. */ public onStop(callback: (elapsedTime: number) => void): void { this.emitter.on('stop', callback); } /** * Registers a callback to be executed when the 'start' event is emitted. * The callback will be triggered when the timer is started. * * @param callback - Function that will be executed when the timer is started. */ public onStart(callback: () => void): void { this.emitter.on('start', callback); } }
412
0.977014
1
0.977014
game-dev
MEDIA
0.188423
game-dev
0.922295
1
0.922295
jboss-modules/jboss-modules
2,895
src/main/java/org/jboss/modules/ClassifyingModuleLoader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.modules; import java.util.HashMap; import java.util.Map; /** * A module loader which selects a delegate module loader based upon the prefix of the module name. Longer * names are matched first always. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ClassifyingModuleLoader extends ModuleLoader { private volatile Map<String, ModuleLoader> delegates; private final ModuleLoader defaultLoader; private final String name; /** * Construct a new instance. The given delegates map is copied. * * @param delegates the default delegates map to use * @param defaultLoader the default loader to use if no delegate mapping exists */ public ClassifyingModuleLoader(final String name, final Map<String, ModuleLoader> delegates, final ModuleLoader defaultLoader) { super(true, false); this.defaultLoader = defaultLoader; this.delegates = new HashMap<>(delegates); this.name = name; } /** {@inheritDoc} */ protected Module preloadModule(String name) throws ModuleLoadException { int idx; final Map<String, ModuleLoader> delegates = this.delegates; for (;;) { final ModuleLoader loader = delegates.get(name); if (loader != null) { return preloadModule(name, loader); } idx = name.lastIndexOf('.'); if (idx == -1) { return preloadModule(name, defaultLoader); } name = name.substring(0, idx); } } /** {@inheritDoc} */ protected ModuleSpec findModule(final String name) throws ModuleLoadException { // We have no modules of our own! return null; } /** * Change the delegates map. A copy is made of the given map. * * @param delegates the new delegates map to use */ public void setDelegates(Map<String, ModuleLoader> delegates) { this.delegates = new HashMap<>(delegates); } public String toString() { return String.format("Classifying Module Loader @%x \"%s\"", Integer.valueOf(hashCode()), name); } }
412
0.831653
1
0.831653
game-dev
MEDIA
0.352797
game-dev
0.829894
1
0.829894
cms-sw/cmssw
4,604
SimG4CMS/Calo/interface/CaloG4Hit.h
#ifndef SimG4CMS_CaloG4Hit_h #define SimG4CMS_CaloG4Hit_h 1 /////////////////////////////////////////////////////////////////////////////// // File: CaloG4Hit.h // Date: 10.02 Taken from CMSCaloHit // // Hit class for Calorimeters (Ecal, Hcal, ...) // // One Hit object should be created // -for each new particle entering the calorimeter // -for each detector unit (= crystal or fibre or scintillator layer) // -for each nanosecond of the shower development // // This implies that all hit objects created for a given shower // have the same value for // - Entry (= local coordinates of the entrance point of the particle // in the unit where the shower starts) // - the TrackID (= Identification number of the incident particle) // - the IncidentEnergy (= energy of that particle) // // Modified: // /////////////////////////////////////////////////////////////////////////////// #include "SimG4CMS/Calo/interface/CaloHitID.h" #include "DataFormats/Math/interface/Point3D.h" #include <iostream> #include "G4Allocator.hh" #include "G4VHit.hh" class CaloG4Hit : public G4VHit { public: CaloG4Hit(); ~CaloG4Hit() override = default; CaloG4Hit(const CaloG4Hit& right); const CaloG4Hit& operator=(const CaloG4Hit& right); bool operator==(const CaloG4Hit&) { return false; } inline void* operator new(std::size_t); inline void operator delete(void* CaloG4Hit); void Draw() override {} void Print() override; public: math::XYZPoint getEntry() const { return entry; } void setEntry(double x, double y, double z) { entry.SetCoordinates(x, y, z); } math::XYZPoint getEntryLocal() const { return entryLocal; } void setEntryLocal(double x, double y, double z) { entryLocal.SetCoordinates(x, y, z); } math::XYZPoint getPosition() const { return pos; } void setPosition(double x, double y, double z) { pos.SetCoordinates(x, y, z); } double getEM() const { return elem; } void setEM(double e) { elem = e; } double getHadr() const { return hadr; } void setHadr(double e) { hadr = e; } double getIncidentEnergy() const { return theIncidentEnergy; } void setIncidentEnergy(double e) { theIncidentEnergy = e; } int getTrackID() const { return hitID.trackID(); } uint32_t getUnitID() const { return hitID.unitID(); } double getTimeSlice() const { return hitID.timeSlice(); } int getTimeSliceID() const { return hitID.timeSliceID(); } uint16_t getDepth() const { return hitID.depth(); } bool isFinecaloTrackID() const { return hitID.isFinecaloTrackID(); } CaloHitID getID() const { return hitID; } void setID(uint32_t i, double d, int j, uint16_t k = 0) { hitID.setID(i, d, j, k); } void setID(const CaloHitID& id) { hitID = id; } void addEnergyDeposit(double em, double hd); void addEnergyDeposit(const CaloG4Hit& aHit); double getEnergyDeposit() const { return (elem + hadr); } private: math::XYZPoint entry; //Entry point (Global coordinate) math::XYZPoint entryLocal; //Entry point (Local coordinate) math::XYZPoint pos; //Position (Global coordinate) double elem; //EnergyDeposit of EM particles double hadr; //EnergyDeposit of HD particles double theIncidentEnergy; //Energy of the primary particle CaloHitID hitID; //Identification number of the hit given //by primary particle, Cell ID, Time of //the hit }; class CaloG4HitLess { public: bool operator()(const CaloG4Hit* a, const CaloG4Hit* b) { if (a->getTrackID() != b->getTrackID()) { return (a->getTrackID() < b->getTrackID()); } else if (a->getUnitID() != b->getUnitID()) { return (a->getUnitID() < b->getUnitID()); } else if (a->getDepth() != b->getDepth()) { return (a->getDepth() < b->getDepth()); } else { return (a->getTimeSliceID() < b->getTimeSliceID()); } } }; class CaloG4HitEqual { public: bool operator()(const CaloG4Hit* a, const CaloG4Hit* b) { return (a->getTrackID() == b->getTrackID() && a->getUnitID() == b->getUnitID() && a->getDepth() == b->getDepth() && a->getTimeSliceID() == b->getTimeSliceID()); } }; extern G4ThreadLocal G4Allocator<CaloG4Hit>* fpCaloG4HitAllocator; inline void* CaloG4Hit::operator new(std::size_t) { if (!fpCaloG4HitAllocator) fpCaloG4HitAllocator = new G4Allocator<CaloG4Hit>; return (void*)fpCaloG4HitAllocator->MallocSingle(); } inline void CaloG4Hit::operator delete(void* aHit) { fpCaloG4HitAllocator->FreeSingle((CaloG4Hit*)aHit); } std::ostream& operator<<(std::ostream&, const CaloG4Hit&); #endif
412
0.911739
1
0.911739
game-dev
MEDIA
0.447775
game-dev
0.931231
1
0.931231
hzyhhzy/UmaAi
10,090
UmaSimulator/GameDatabase/KnownSupportCards.cpp
#include <iostream> #include <fstream> #include <sstream> #include <filesystem> #include "GameDatabase.h" #include "../Game/Game.h" using json = nlohmann::json; using namespace std; unordered_map<int, SupportCard> GameDatabase::AllCards; unordered_map<int, SupportCard> GameDatabase::DBCards; void GameDatabase::loadCards(const string& dir) { try { for (auto entry : filesystem::directory_iterator(dir + "/")) { //cout << entry.path() << endl; if (entry.path().extension() == ".json") { try { ifstream ifs(entry.path()); stringstream ss; ss << ifs.rdbuf(); ifs.close(); json j = json::parse(ss.str(), nullptr, true, true); SupportCard jdata[5]; for (int x = 0; x < 5; ++x) { jdata[x].load_from_json(j, x); } cout << "载入支援卡 #" << jdata[4].cardName << " --- " << jdata[4].cardID << endl; if (GameDatabase::AllCards.count(jdata[4].cardID) > 0) cout << "错误:重复支援卡 #" << jdata[4].cardName << " --- " << jdata[4].cardID << endl; else { for (int x = 0; x < 5; ++x) GameDatabase::AllCards[jdata[x].cardID] = jdata[x]; } } catch (exception& e) { cout << "支援卡信息JSON出错: " << entry.path() << endl << e.what() << endl; } } } cout << "共载入 " << GameDatabase::AllCards.size() << " 支援卡" << endl; } catch (exception& e) { cout << "\x1b[91m读取支援卡信息出错,请检查当前目录下是否有“db”文件夹: \x1b[0m" << endl << e.what() << endl; } catch (...) { cout << "读取支援卡信息出错:未知错误" << endl; } } void GameDatabase::loadDBCards(const string& pathname) { try { ifstream ifs(pathname); stringstream ss; ss << ifs.rdbuf(); ifs.close(); json j = json::parse(ss.str(), nullptr, true, true); for (auto & it : j.items()) { // cout << it.key() << endl; for (int x = 0; x < 5; ++x) { SupportCard jdata; jdata.load_from_json(it.value(),x); jdata.isDBCard = true; if (GameDatabase::AllCards.count(jdata.cardID) > 0) // 如果已经被loadCards载入(有手动数据) GameDatabase::DBCards[jdata.cardID] = jdata; // 仍然把数据暂存在DBCards里(现在没使用这个表),用于验算 else GameDatabase::AllCards[jdata.cardID] = jdata; // 没有手动数据则用自动数据 } } cout << "共载入 " << GameDatabase::AllCards.size()/5 << " 支援卡" << endl; } catch (exception& e) { cout << "\x1b[91m读取支援卡信息出错,请检查当前目录下是否有“db”文件夹: \x1b[0m" << endl << e.what() << endl; } catch (...) { cout << "读取支援卡信息出错:未知错误" << endl; } } CardTrainingEffect SupportCard::getCardEffect(const Game& game, bool isShining, int atTrain, int jiBan, int effectFactor, int trainingCardNum, int trainingShiningNum) const { CardTrainingEffect effect(this); //printf("This card is :%d", cardID); if (isDBCard || effectFactor==-1) // 暂时使用effectFactor=-1表示验算模式 { // 新的固有处理代码 // 由于不能维护isFixed状态,每次都要重新计算 double rate; int count, totalJiBan; double expectedVital; auto args = uniqueEffectParam; int type = uniqueEffectType; if (effectFactor == -1) { // 让手写卡也使用新代码/新数据计算,用来比对计算结果 // 重新用新卡数据初始化自己 effect = CardTrainingEffect(&GameDatabase::DBCards[cardID]); type = GameDatabase::DBCards[cardID].uniqueEffectType; args = GameDatabase::DBCards[cardID].uniqueEffectParam; } //已知的问题 // 1.智高峰等(根据xx技能个数),按回合数近似 // 2.根双涡轮等(友情训练次数),视为全开 // 3.智太阳神等(某条件提升得意率),视为全开 // 4.速成田路(粉丝数),按回合数估计 // 5.智波旁、智小栗帽等(初始状态相关),暂时没写 // 6.旧智中山(随机让失败率变成0),暂时没写 // 不确定还有没有其他的 switch (type) { case 0: break; case 1: // 羁绊>=args[1]时生效 case 2: if (jiBan >= args[1]) { if (args[2] > 0) effect.apply(args[2], args[3]); if (args[4] > 0) effect.apply(args[4], args[5]); if (cardID / 10 == 30137) // 神团额外词条特判 { effect.apply(1, 10).apply(2, 15); } } break; case 3: // 进王:羁绊+非擅长训练 if (jiBan >= args[1] && cardType != atTrain) effect.xunLian += 20; break; case 4: // 成田路。没有粉丝数,用回合数估算 rate = game.turn <= 33 ? 0 : game.turn <= 40 ? 0.2 : game.turn <= 42 ? 0.25 : game.turn <= 58 ? 0.7 : 1.0; effect.xunLian += rate * (double)args[2]; break; case 5: // 根据编成支援卡类型的初始属性加成(对应属性+10,友人/团队卡全属性+2), 暂不处理 break; case 6: // 天狼星,需要用到effectFactor effect.apply(1, max(0, min(args[1], args[1] - effectFactor)) * args[3]); break; case 7: // 青竹,等 // 需要计算训练后的体力,暂时以-20估算 expectedVital = game.vital + game.trainVitalChange[atTrain]; rate = clamp(expectedVital / game.maxVital, 0.3, 1.0); // (0.3, 1) --> (1, 0) effect.apply(1, args[5] + int(args[2] * (1 - rate) / 0.7)); break; case 8: // 彩珠 effect.xunLian += 5 + 3 * clamp((game.maxVital - 100) / 4, 0, 5); break; case 9: // 地堡,需要计算总羁绊 totalJiBan = 0; for (int i = 0; i < 6; ++i) totalJiBan += game.persons[i].friendship; rate = double(totalJiBan) / 600; effect.xunLian += rate * 20; break; case 10: // 根神鹰,需要计算同时训练的卡数量 effect.xunLian += args[2] * min(5, trainingCardNum); break; case 11: // 水司机,需要当前训练等级 effect.xunLian += args[2] * min(5, 1 + game.getTrainingLevel(atTrain)); break; case 12: // 智中山 break; case 13: // B95,麻酱 if (trainingShiningNum >= 1) effect.apply(args[1], args[2]); break; case 14: // 耐善信, 暂时按训练前体力算 rate = clamp((double)game.vital / 100, 0.0, 1.0); // >100也是满训练 effect.xunLian += 5 + 15 * rate; break; case 15: // 智帽,暂时不计 break; case 16: // x个xxx类型技能,获得xxx加成(例如智高峰) if (args[1] == 1)//速度技能 { count = 1 + game.turn / 6; } else if (args[1] == 2)//加速度技能 { count = int(0.7 + game.turn / 12.0); } else if (args[1] == 3)//回体技能 { count = int(0.4 + game.turn / 15.0); } else { count = 0; assert(false && "未知的购买技能型支援卡固有"); } if (count > args[4]) count = args[4]; effect.apply(args[2], args[3] * count); break; case 17: // 根大和 count = 0; for (int i = 0; i < 5; ++i) count += min(5, 1+game.getTrainingLevel(i)); effect.xunLian += (count / 25.0) * args[3]; break; case 18: // 佐岳 break; case 19: // 凉花 break; case 20: // 巨匠 if (jiBan >= 80) { int cardTypeCount[7] = { 0,0,0,0,0,0,0 }; for (int i = 0; i < 6; i++) { int t = game.persons[i].cardParam.cardType; assert(t <= 6 && t >= 0); cardTypeCount[t]++; } cardTypeCount[5] += cardTypeCount[6]; for (int i = 0; i < 6; i++) if (cardTypeCount[i] > 2)cardTypeCount[i] = 2; for (int i = 0; i < 5; i++) if (cardTypeCount[i] > 0) effect.apply(i + 3, cardTypeCount[i]); // 速耐力根智 = 0-4 = CardEffect词条3-7 if (cardTypeCount[5] > 0) effect.apply(30, cardTypeCount[5]); // pt = 30 } break; case 21: // 耐万籁,编入4种支援卡时+10训练 { int cardTypeCount[7] = { 0,0,0,0,0,0,0 }; for (int i = 0; i < 6; i++) { int t = game.persons[i].cardParam.cardType; assert(t <= 6 && t >= 0); cardTypeCount[t]++; } int cardTypes = 0; for (int i = 0; i < 7; i++) if (cardTypeCount[i] > 0) cardTypes++; if (cardTypes >= args[1]) effect.apply(args[2], args[3]); } break; case 22://理事长 break; default: // type == 0 if (uniqueEffectType != 0) { // cout << "未知固有 #" << uniqueEffectType << endl; } break; } // switch } else { cout << "\x1b[91m未知支援卡: #" << this->cardID << " " << this->cardName << ", 请更新AI数据\x1b[0m" << endl; cout << "\x1b[91m** 程序即将退出**\x1b[0m" << endl; system("pause"); assert(false); } return effect; }
412
0.62821
1
0.62821
game-dev
MEDIA
0.78087
game-dev
0.935208
1
0.935208
p1xel8ted/Game-Mods
9,855
Sun Haven/MoreJewelry/Patches.cs
namespace MoreJewelry; /// <summary> /// Contains Harmony patches for modifying and extending the functionality of various game methods. /// </summary> [Harmony] public static class Patches { /// <summary> /// A list of custom gear slots added by the mod. /// </summary> [UsedImplicitly] public static List<Slot> GearSlots = []; [HarmonyPostfix] [HarmonyPatch(typeof(PlayerInventory), nameof(PlayerInventory.SetUpInventoryData))] private static void PlayerInventory_SetUpInventoryData(PlayerInventory __instance) { foreach (var item in __instance.Items) { Plugin.LOG.LogWarning($"Item: {item.id}-{item.item.Type}, {item.item.ID()}, {item.slot.slotNumber}, {item.slotNumber}"); } } /// <summary> /// Harmony prefix patch for PlayerInventory's LoadPlayerInventory method. /// </summary> /// <param name="__instance">The instance of <see cref="PlayerInventory"/> being patched.</param> /// <remarks> /// Initializes and sets up custom gear slots and panels if they haven't been created already. /// </remarks> [HarmonyPrefix] [HarmonyPatch(typeof(PlayerInventory), nameof(PlayerInventory.OpenMajorPanel))] private static void PlayerInventory_Initialize(PlayerInventory __instance, int panelIndex) { if (!GameObject.Find(Const.PlayerInventoryPath)) return; if(panelIndex != 0) return; if (UI.SlotsCreated && UI.GearPanel != null) { Utils.Log("Slots already created. Skipping slot creation etc."); return; } UI.InitializeGearPanel(); //UI.CreateSlots(__instance, ArmorType.Ring, 2); // UI.CreateSlots(__instance, ArmorType.Keepsake, 2); // UI.CreateSlots(__instance, ArmorType.Amulet, 2); __instance.SetUpInventoryData(); var characterPanelSlots = GameObject.Find(Const.CharacterPanelSlotsPath); if (characterPanelSlots != null) { UI.GearPanel.transform.SetParent(characterPanelSlots.transform, true); UI.GearPanel.transform.SetAsLastSibling(); UI.GearPanel.transform.localPosition = Const.ShowPosition; } else { Plugin.LOG.LogError("Character Panel Slots not found. Please report this."); } UI.UpdatePanelVisibility(); UI.SlotsCreated = true; } /// <summary> /// Harmony prefix patch for the SwapItems method of the Inventory class. /// </summary> /// <param name="__instance">The instance of the Inventory being patched.</param> /// <param name="slot1">The first slot involved in the swap operation.</param> /// <remarks> /// This method modifies the behavior of the item swapping process in the inventory. /// It includes custom logic for handling the swapping of items in keepsake, amulet, and ring slots. /// <para>The method checks if the main slot for each item type is filled and attempts to swap with an alternate empty slot if available.</para> /// <para>Uses <see cref="Utils.SlotFilled"/> to check if a slot is filled and <see cref="Utils.GetSlotName"/> for logging purposes.</para> /// </remarks> [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), nameof(Inventory.SwapItems))] private static void Inventory_SwapItems(ref Inventory __instance, ref int slot1) { //TODO: Come back when main issue is fixed return; if (!Plugin.UseAdjustedEquipping.Value) { Utils.Log("Adjusted equipping disabled. Skipping slot swapping logic."); return; } // Helper method to handle slot swapping var inv = __instance; // Keepsake slot handling TrySwapSlot(ref slot1, Const.MainKeepsakeSlot, Const.NewKeepsakeSlotOne, Const.NewKeepsakeSlotTwo); // Amulet slot handling TrySwapSlot(ref slot1, Const.MainAmuletSlot, Const.NewAmuletSlotOne, Const.NewAmuletSlotTwo); // Ring slot handling TrySwapSlot(ref slot1, Const.MainRingSlot, Const.SecondaryRingSlot, Const.NewRingSlotOne, Const.NewRingSlotTwo); return; void TrySwapSlot(ref int slot, int mainSlot, params int[] alternateSlots) { if (slot != mainSlot || !Utils.SlotFilled(inv, mainSlot)) return; foreach (var altSlot in alternateSlots) { if (Utils.SlotFilled(inv, altSlot)) continue; slot = altSlot; Utils.Log($"Redirecting to empty slot: {Utils.GetSlotName(altSlot)}"); return; } Utils.Log($"No empty slots found for {Utils.GetSlotName(mainSlot)}. Redirect aborted."); } } /// <summary> /// Harmony postfix patch for PlayerInventory's GetStat method. /// </summary> /// <param name="__instance">The instance of <see cref="PlayerInventory"/> being patched.</param> /// <param name="stat">The type of stat being retrieved.</param> /// <param name="__result">The result value of the original GetStat method.</param> /// <remarks> /// Modifies the stat calculation to include custom gear slots. This method is called every frame. /// </remarks> [HarmonyPostfix] [HarmonyPatch(typeof(PlayerInventory), nameof(PlayerInventory.GetStat))] public static void PlayerInventory_GetStat(ref PlayerInventory __instance, StatType stat, ref float __result) { //TODO: Come back when main issue is fixed return; if (Plugin.MakeSlotsStorageOnly.Value) return; __result += __instance.GetStatValueFromSlot(ArmorType.Ring, Const.NewRingSlotOne, 2, stat); __result += __instance.GetStatValueFromSlot(ArmorType.Ring, Const.NewRingSlotTwo, 3, stat); __result += __instance.GetStatValueFromSlot(ArmorType.Keepsake, Const.NewKeepsakeSlotOne, 1, stat); __result += __instance.GetStatValueFromSlot(ArmorType.Keepsake, Const.NewKeepsakeSlotTwo, 2, stat); __result += __instance.GetStatValueFromSlot(ArmorType.Amulet, Const.NewAmuletSlotOne, 1, stat); __result += __instance.GetStatValueFromSlot(ArmorType.Amulet, Const.NewAmuletSlotTwo, 2, stat); } /// <summary> /// Harmony postfix patch for PlayerInventory's Awake method. /// </summary> /// <param name="__instance">The instance of <see cref="PlayerInventory"/> being patched.</param> /// <remarks> /// Attaches additional actions to the OnInventoryUpdated event for cleaning up armor dictionaries. This event is triggered when /// the player opens or closes their inventory. /// </remarks> [HarmonyPostfix] [HarmonyPatch(typeof(PlayerInventory), nameof(PlayerInventory.Awake))] public static void PlayerInventory_Awake(ref PlayerInventory __instance) { // //TODO: Come back when main issue is fixed // return; if (UI.ActionAttached) return; UI.ActionAttached = true; Utils.Log("Attaching RemoveNullValuesAndLogFromDictionary action to OnInventoryUpdated event."); var instance = __instance; __instance.OnInventoryUpdated += () => { if (instance == null || instance.currentRealArmor == null || instance.currentArmor == null) { Plugin.LOG.LogError("OnInventoryUpdated: PlayerInventory instance is null. It is advised to restart your game."); return; } Utils.Log("OnInventoryUpdated: Cleaning armor dictionaries."); Utils.RemoveNullValuesAndLogFromDictionary(instance.currentRealArmor, "CurrentRealArmor"); Utils.RemoveNullValuesAndLogFromDictionary(instance.currentArmor, "CurrentArmor"); }; } /// <summary> /// Harmony postfix patch for PlayerInventory's LateUpdate method. /// </summary> /// <param name="__instance">The instance of <see cref="PlayerInventory"/> being patched.</param> /// <remarks> /// Ensures custom gear slots are equipped with non-visual armor items. This is where the game begins to calculate stats the gear provides. /// </remarks> [HarmonyPostfix] [HarmonyPatch(typeof(PlayerInventory), nameof(PlayerInventory.LateUpdate))] private static void PlayerInventory_EquipNonVisualArmor(ref PlayerInventory __instance) { //TODO: Come back when main issue is fixed return; if (!UI.SlotsCreated) return; __instance.EquipNonVisualArmor(Const.NewRingSlotOne, ArmorType.Ring, 2); __instance.EquipNonVisualArmor(Const.NewRingSlotTwo, ArmorType.Ring, 3); __instance.EquipNonVisualArmor(Const.NewKeepsakeSlotOne, ArmorType.Keepsake, 1); __instance.EquipNonVisualArmor(Const.NewKeepsakeSlotTwo, ArmorType.Keepsake, 2); __instance.EquipNonVisualArmor(Const.NewAmuletSlotOne, ArmorType.Amulet, 1); __instance.EquipNonVisualArmor(Const.NewAmuletSlotTwo, ArmorType.Amulet, 2); } /// <summary> /// Harmony postfix patch for MainMenuController's EnableMenu method. /// </summary> /// <param name="__instance">The instance of <see cref="MainMenuController"/> being patched.</param> /// <param name="menu">The menu GameObject being enabled.</param> /// <remarks> /// Resets the mod to its initial state when certain menus are enabled. /// </remarks> [HarmonyPostfix] [HarmonyPatch(typeof(MainMenuController), nameof(MainMenuController.EnableMenu))] private static void MainMenuController_EnableMenu(ref MainMenuController __instance, ref GameObject menu) { if (menu == __instance.homeMenu || menu == __instance.newCharacterMenu || menu == __instance.loadCharacterMenu || menu == __instance.singlePlayerMenu || menu == __instance.multiplayerMenu) { Utils.ResetMod(); } } }
412
0.923177
1
0.923177
game-dev
MEDIA
0.960723
game-dev
0.930248
1
0.930248
BUGISU/BojamajaPlay2_mobile
2,674
Scripts/shop/ShopAppManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using System; using UnityEngine.UI; //전체적인 다이아상점 관리 public class ShopAppManager : MonoBehaviour { public GameObject Store; //광고 쿨타임 public GameObject HaveCoolOb; public Text CoolTimeStr; //광고 횟수 public GameObject DontHaveFreeAdOb; // public GameObject PurchasefailedOb; public GameObject PurchaseCompleteOb; public static ShopAppManager Instance { get; private set; } private void Awake() { if (Instance != null && Instance != this) Destroy(this); else Instance = this; } public void Update() { //광고 쿨타임이 남았으면 if (GameManager.Instance.AdCool.Equals(true)) { HaveCoolOb.SetActive(true); //판넬활성화 CoolTimeStr.text = GameManager.Instance.LeftTimeMin + ":" + GameManager.Instance.LeftTimeSec; } else { HaveCoolOb.SetActive(false); //판넬활성화 } } public void OnClickShopButton() { if (Store.activeSelf.Equals(false)) { PlayerPrefs.SetString("PlayEndTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //현재시간 저장 GameManager.ShopPanel = true; //팝업 활성화 중 MainUIManager.instance.ClassicModAni.Rebind(); //클래식 섬 애니메이션 Reset MainUIManager.instance.RankModAni.Rebind(); //랭킹 섬 애니메이션 Reset Store.SetActive(true); SoundManager.Instance.bgm.clip = SoundManager.Instance.GetClipByName("BoboShopBGM"); SoundManager.Instance.bgm.Play(); } else { GameManager.Instance.OnClick_BtnSound3(); } } ///////////////////////////무료 광고 보기///////////////////////////////////////// public void ClickShowAd() { //남은 광고가 있고 광고 쿨타임이 없을 경우, if (GameManager.Instance.FreeADCount > 0 && GameManager.Instance.AdCool.Equals(false)) { GameManager.Instance.OnClick_BtnSound1(); AdManager.Instance.ShowRewardAd(); //광고 보기 } // 오늘 볼수 있는 광고를 모두 보았거나 쿨타임이 남았을 경우, else if (GameManager.Instance.FreeADCount <= 0 || GameManager.Instance.AdCool.Equals(true)) { GameManager.Instance.OnClick_BtnSound3(); //오늘 볼수있는 광고 횟수를 초과 if (GameManager.Instance.FreeADCount <= 0) { // DontHaveFreeAdOb.SetActive(true); //판넬 활성화 PopUpSystem.Instance.ShowPopUp(DontHaveFreeAdOb); } } } ////////////////////////////////////////////////////////////////////////// }
412
0.647115
1
0.647115
game-dev
MEDIA
0.732329
game-dev
0.938219
1
0.938219
siconos/siconos
15,159
mechanics/src/collision/bullet/test/ContactTest.cpp
// -*- compile-command: "make -C ~/projects/siconos/bld/mechanics && valgrind --leak-check=full --suppressions=$HOME/projects/siconos/cmake/valgrind.supp ~/projects/siconos/bld/mechanics/src/collision/bullet/test/testContact ContactTest" -*- // make --no-print-directory -C ~/projects/siconos/bld/mechanics && ~/projects/siconos/bld/mechanics/src/collision/bullet/test/testContact ContactTest::t2 | grep pos, | cut -d, -f2-8 | plot.py -s #include "ContactTest.hpp" #include "SiconosContactor.hpp" #include "SiconosShape.hpp" #include "SiconosCollisionManager.hpp" #include "SiconosBulletCollisionManager.hpp" #include "RigidBodyDS.hpp" #include "SolverOptions.h" #include "SiconosKernel.hpp" #include <string> #include <sys/time.h> // Experimental settings for SiconosBulletCollisionManager extern double extra_margin; extern double breaking_threshold; extern double box_ch_added_dimension; extern double box_convex_hull_margin; extern double bullet_world_scaling; // Experimental statistics from SiconosBulletCollisionManager extern int new_interaction_counter; extern int existing_interaction_counter; extern int interaction_warning_counter; // test suite registration CPPUNIT_TEST_SUITE_REGISTRATION(ContactTest); void ContactTest::setUp() {} void ContactTest::tearDown() {} struct BounceParams { bool trace; bool dynamic; double size; double mass; double position; double timestep; double insideMargin; double outsideMargin; SiconosBulletOptions options; void dump() { printf(" trace: %s\n", trace?"on":"off"); printf(" dynamic: %s\n", trace?"on":"off"); printf(" size: %.3g\n", size); printf(" mass: %.3g\n", mass); printf(" position: %.3g\n", position); printf(" insideMargin: %.3g\n", insideMargin); printf(" outsideMargin: %.3g\n", outsideMargin); printf(" breakingThreshold: %.3g\n", options.contactBreakingThreshold); printf(" worldScale: %.3g\n", options.worldScale); } }; struct BounceResult { double bounce_error_sum; double bounce_error[6]; int n_bounce_error; double final_position; double final_position_std; int num_interactions; int num_interaction_warnings; int max_simultaneous_contacts; double avg_simultaneous_contacts; double displacement_on_first_contact; }; static BounceResult bounceTest(std::string moving, std::string ground, const BounceParams &params) { // User-defined main parameters double t0 = 0; // initial computation time double T = 20.0; // end of computation time double h = params.timestep; // time step double position_init = params.position; // initial position double velocity_init = 0.0; // initial velocity double g = 9.81; double theta = 0.5; // theta for MoreauJeanOSI integrator int steps = (T-t0)/h; // Statistics of this run int bounce_counter = 0; const int n_desired_bounces = 6; double desired_bounce_ratios[6] = { 0.6358, 0.4048, 0.2577, 0.1630, 0.1033, 0.0647 }; double actual_bounce_times[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; double actual_bounce_ratios[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; int local_new_interaction_count=0; int max_simultaneous_contacts=0; double avg_simultaneous_contacts=0.0; bool first_contact = true; double displacement_on_first_contact=0.0; // -- OneStepIntegrators -- SP::OneStepIntegrator osi; osi.reset(new MoreauJeanOSI(theta)); // -- Model -- SP::NonSmoothDynamicalSystem nsds(new NonSmoothDynamicalSystem(t0, T)); SP::SiconosVector q0(new SiconosVector(7)); SP::SiconosVector v0(new SiconosVector(6)); q0->zero(); v0->zero(); (*q0)(2) = position_init; (*q0)(3) = 1.0; (*v0)(2) = velocity_init; SP::SiconosVector q1(new SiconosVector(7)); SP::SiconosVector v1(new SiconosVector(6)); q1->zero(); (*q1)(3) = 1.0; v1->zero(); ///////// // Bodies printf("== Testing: %s falling on %s .. ", moving.c_str(), ground.c_str()); if(params.trace) printf("==\n"); fflush(stdout); // Set up a Siconos Mechanics environment: // A RigidBodyDS with a contactor consisting of a single sphere. SP::RigidBodyDS body(new RigidBodyDS(q0, v0, params.mass)); SP::SiconosContactorSet contactors(new SiconosContactorSet()); SP::SiconosSphere sphere; if(moving=="sphere") { sphere.reset(new SiconosSphere(params.size/2)); sphere->setInsideMargin(params.insideMargin); sphere->setOutsideMargin(params.outsideMargin); contactors->push_back(std::make_shared<SiconosContactor>(sphere)); } else if(moving=="box") { SP::SiconosBox box(new SiconosBox(params.size,params.size,params.size)); box->setInsideMargin(params.insideMargin); box->setOutsideMargin(params.outsideMargin); contactors->push_back(std::make_shared<SiconosContactor>(box)); } else if(moving=="ch") { float siz = params.size; SP::SiconosMatrix pts(new SimpleMatrix(4,3)); (*pts)(0,0) = 0.0; (*pts)(0,1) = 0.0; (*pts)(0,2) = 0.0; (*pts)(1,1) = siz; (*pts)(1,1) = 0.0; (*pts)(1,2) = 0.0; (*pts)(2,0) = 0.0; (*pts)(2,1) = siz; (*pts)(2,2) = 0.0; (*pts)(3,0) = 0.0; (*pts)(3,1) = 0.0; (*pts)(3,2) = siz; SP::SiconosConvexHull ch(new SiconosConvexHull(pts)); ch->setInsideMargin(params.insideMargin); ch->setOutsideMargin(params.outsideMargin); contactors->push_back(std::make_shared<SiconosContactor>(ch)); } body->setContactors(contactors); // A contactor with no body (static contactor) consisting of a plane // positioned such that bouncing and resting position = 0.0 SP::SiconosContactorSet static_contactors(std::make_shared<SiconosContactorSet>()); if(ground=="plane") { SP::SiconosPlane plane(new SiconosPlane()); plane->setInsideMargin(params.insideMargin); plane->setOutsideMargin(params.outsideMargin); static_contactors->push_back(std::make_shared<SiconosContactor>(plane)); } else if(ground=="box") { SP::SiconosBox floorbox(new SiconosBox(100,100,100)); floorbox->setInsideMargin(params.insideMargin); floorbox->setOutsideMargin(params.outsideMargin); SP::SiconosVector pos(new SiconosVector(7)); (*pos)(2) = -50-params.size/2; (*pos)(3) = 1.0; static_contactors->push_back(std::make_shared<SiconosContactor>(floorbox, pos)); } else if(ground=="sphere") { SP::SiconosSphere floorsphere(new SiconosSphere(1.0)); floorsphere->setInsideMargin(params.insideMargin); floorsphere->setOutsideMargin(params.outsideMargin); SP::SiconosVector pos(new SiconosVector(7)); (*pos)(2) = -1-params.size/2; (*pos)(3) = 1.0; static_contactors->push_back(std::make_shared<SiconosContactor>(floorsphere, pos)); } ///////// // -- Set external forces (weight) -- SP::SiconosVector FExt; FExt.reset(new SiconosVector(3)); FExt->zero(); FExt->setValue(2, - g * params.mass); body->setFExtPtr(FExt); // -- Add the dynamical systems into the non smooth dynamical system nsds->insertDynamicalSystem(body); // -- Time discretisation -- SP::TimeDiscretisation timedisc(new TimeDiscretisation(t0, h)); // -- OneStepNsProblem -- SP::FrictionContact osnspb(new FrictionContact(3)); // -- Some configuration osnspb->numericsSolverOptions()->iparam[SICONOS_IPARAM_MAX_ITER] = 1000; osnspb->numericsSolverOptions()->dparam[SICONOS_DPARAM_TOL] = 1e-5; osnspb->setMaxSize(16384); osnspb->setMStorageType(NM_SPARSE_BLOCK); osnspb->setNumericsVerboseMode(0); osnspb->setKeepLambdaAndYState(true); ///////// // -- MoreauJeanOSI Time Stepping SP::TimeStepping simulation(new TimeStepping(nsds, timedisc)); simulation->insertIntegrator(osi); simulation->insertNonSmoothProblem(osnspb); // Object to manage the Bullet implementation of collisionMan SP::SiconosBulletCollisionManager collisionMan( new SiconosBulletCollisionManager(params.options)); simulation->insertInteractionManager(collisionMan); // Add static shapes (centered at zero by default) collisionMan->addStaticBody(static_contactors); // Add a non-smooth law SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(0.8, 0., 0.0, 3)); collisionMan->insertNonSmoothLaw(nslaw, 0, 0); /////// int k=0; double std=0, final_pos=0; double last_pos=position_init, last_vel=0; while(simulation->hasNextEvent()) { // Update a property at step 500 if(params.dynamic && k==500 && moving=="sphere") { sphere->setRadius(0.3); } // Update integrator and solve constraints simulation->computeOneStep(); double vel = (*body->velocity())(2); double pos = (*body->q())(2); if(params.trace && (k+1) < steps) { printf("pos, %f, %f, %f\n", pos, last_pos - pos, vel); } // Peaks (velocity crosses zero towards positive) if(vel <= 0 && last_vel > 0) { if(bounce_counter < n_desired_bounces) { actual_bounce_times[bounce_counter] = k*h; actual_bounce_ratios[bounce_counter] = pos / position_init; bounce_counter ++; } } // Interaction statistics if(collisionMan->statistics().new_interactions_created > 0 && first_contact) { first_contact = false; displacement_on_first_contact = last_pos - pos; } int interactions = collisionMan->statistics().new_interactions_created + collisionMan->statistics().existing_interactions_processed; local_new_interaction_count += collisionMan->statistics().new_interactions_created; if(interactions > max_simultaneous_contacts) max_simultaneous_contacts = interactions; avg_simultaneous_contacts += interactions; // Standard deviation (cheating by not calculating mean!) if(k==(steps-100)) final_pos = pos; if(k>(steps-100)) { std += (pos-final_pos)*(pos-final_pos); } // State last_pos = pos; last_vel = vel; // Advance simulation simulation->nextStep(); k++; } if(!params.trace) printf("(done, iterations=%d)\n", k - 1); BounceResult r; r.bounce_error_sum = 0.0; r.n_bounce_error = 6; for(int i=0; i < r.n_bounce_error; i++) { double er = actual_bounce_ratios[i] - desired_bounce_ratios[i]; r.bounce_error[i] = fabs(er); r.bounce_error_sum += er*er; } r.bounce_error_sum = sqrt(r.bounce_error_sum/r.n_bounce_error); r.final_position = (*body->q())(2); r.final_position_std = sqrt(std/100); r.num_interactions = local_new_interaction_count; r.num_interaction_warnings = collisionMan->statistics().interaction_warnings; r.max_simultaneous_contacts = max_simultaneous_contacts; r.avg_simultaneous_contacts = avg_simultaneous_contacts / (double)k; r.displacement_on_first_contact = displacement_on_first_contact; return r; } void ContactTest::t1() { try { printf("\n==== t1\n"); BounceParams params; params.trace = true; params.dynamic = false; params.size = 1.0; params.mass = 1.0; params.position = 3.0; params.timestep = 0.005; params.insideMargin = 0.3; params.outsideMargin = 0.3; BounceResult r = bounceTest("box", "box", params); fprintf(stderr, "\nSize: %g\n", params.size); fprintf(stderr, "Final position: %g (std=%g)\n\n", r.final_position, r.final_position_std); } catch(...) { siconos::exception::process(); CPPUNIT_ASSERT(0); } CPPUNIT_ASSERT(1); } void ContactTest::t2() { try { printf("\n==== t2\n"); BounceParams params; params.trace = false; params.dynamic = false; params.size = 1.0; params.mass = 1.0; params.position = 3.0; params.timestep = 0.005; params.insideMargin = 0.1; params.outsideMargin = 0.1; BounceResult results[2][3]; results[0][0] = bounceTest("sphere", "sphere", params); results[1][0] = bounceTest("box", "sphere", params); results[0][1] = bounceTest("sphere", "box", params); results[1][1] = bounceTest("box", "box", params); results[0][2] = bounceTest("sphere", "plane", params); results[1][2] = bounceTest("box", "plane", params); // Report printf("\nParams:\n\n"); params.dump(); printf("\nFinal resting positions:\n\n"); printf(" | sphere | box | plane\n"); printf("-------+--------+--------+-------\n"); printf("sphere | %#6.3f | %#6.3f | %#6.3f\n", results[0][0].final_position, results[0][1].final_position, results[0][2].final_position); printf("box | %#6.3f | %#6.3f | %#6.3f\n", results[1][0].final_position, results[1][1].final_position, results[1][2].final_position); printf("\nFinal resting position standard deviation:\n\n"); printf(" | sphere | box | plane\n"); printf("-------+----------+----------+---------\n"); printf("sphere | %#.2e | %#.2e | %#.2e\n", results[0][0].final_position_std, results[0][1].final_position_std, results[0][2].final_position_std); printf("box | %#.2e | %#.2e | %#.2e\n", results[1][0].final_position_std, results[1][1].final_position_std, results[1][2].final_position_std); } catch(...) { siconos::exception::process(); CPPUNIT_ASSERT(0); } CPPUNIT_ASSERT(1); } void ContactTest::t3() { try { printf("\n==== t3\n"); BounceParams params[3]; params[0].trace = false; params[0].dynamic = false; params[0].size = 0.02; params[0].mass = 0.02; params[0].position = 10.0; params[0].timestep = 0.005; params[0].insideMargin = 0.005; params[0].outsideMargin = 0.005; params[1] = params[0]; params[1].size = 0.1; params[1].mass = 0.1; params[1].position = 10.0; params[2] = params[0]; params[2].size = 1.0; params[2].mass = 1.0; params[2].position = 10.0; BounceResult results[3]; int i; for(i=0; i<3; i++) { results[i] = bounceTest("box", "box", params[i]); } // Report fprintf(stderr, "\nFinal resting positions:\n\n"); for(i=0; i<3; i++) { fprintf(stderr, " pos %.2f: %f (std=%f)\n", params[i].position, results[i].final_position, results[i].final_position_std); } } catch(...) { siconos::exception::process(); CPPUNIT_ASSERT(0); } CPPUNIT_ASSERT(1); } void ContactTest::t4() { printf("\n==== t4\n"); BounceParams params; params.trace = false; params.dynamic = false; params.size = 1.0; params.mass = 1.0; params.position = 3.0; params.timestep = 0.005; params.insideMargin = 0.1; params.outsideMargin = 0.1; SiconosBulletOptions options; options.contactBreakingThreshold = 0.4; options.worldScale = 1.0; params.options = options; bool success = false; BounceResult results; try { results = bounceTest("ch", "plane", params); success = true; } catch(...) { siconos::exception::process(); CPPUNIT_ASSERT(1); } }
412
0.922845
1
0.922845
game-dev
MEDIA
0.535795
game-dev,testing-qa
0.924515
1
0.924515
GregTechCEu/GregTech-Modern
9,033
src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java
package com.gregtechceu.gtceu.common.machine.storage; import com.gregtechceu.gtceu.api.capability.recipe.IO; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.SlotWidget; import com.gregtechceu.gtceu.api.gui.widget.TankWidget; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.TickableSubscription; import com.gregtechceu.gtceu.api.machine.TieredMachine; import com.gregtechceu.gtceu.api.machine.feature.IAutoOutputBoth; import com.gregtechceu.gtceu.api.machine.feature.IFancyUIMachine; import com.gregtechceu.gtceu.api.machine.feature.IMachineLife; import com.gregtechceu.gtceu.api.machine.trait.NotifiableFluidTank; import com.gregtechceu.gtceu.api.machine.trait.NotifiableItemStackHandler; import com.gregtechceu.gtceu.utils.GTTransferUtils; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.syncdata.ISubscription; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.TickTask; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.Nullable; import java.util.Set; import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class BufferMachine extends TieredMachine implements IMachineLife, IAutoOutputBoth, IFancyUIMachine { protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(BufferMachine.class, MetaMachine.MANAGED_FIELD_HOLDER); public static final int TANK_SIZE = 64000; @Getter @Persisted @DescSynced @RequireRerender protected Direction outputFacingItems; @Getter @Persisted @DescSynced @RequireRerender protected Direction outputFacingFluids; @Getter @Persisted @DescSynced @RequireRerender protected boolean autoOutputItems; @Getter @Persisted @DescSynced @RequireRerender protected boolean autoOutputFluids; @Getter @Setter @Persisted protected boolean allowInputFromOutputSideItems; @Getter @Setter @Persisted protected boolean allowInputFromOutputSideFluids; @Persisted @Getter protected final NotifiableItemStackHandler inventory; @Persisted @Getter protected final NotifiableFluidTank tank; @Nullable protected TickableSubscription autoOutputSubs; @Nullable protected ISubscription invSubs, tankSubs; public BufferMachine(IMachineBlockEntity holder, int tier, Object... args) { super(holder, tier); this.inventory = createInventory(args); this.tank = createTank(args); } //////////////////////////////// // ***** Initialization ******// //////////////////////////////// @Override public ManagedFieldHolder getFieldHolder() { return MANAGED_FIELD_HOLDER; } public static int getInventorySize(int tier) { return (int) Math.pow(tier + 2, 2); } public static int getTankSize(int tier) { return tier + 2; } protected NotifiableItemStackHandler createInventory(Object... args) { return new NotifiableItemStackHandler(this, getInventorySize(tier), IO.BOTH); } protected NotifiableFluidTank createTank(Object... args) { return new NotifiableFluidTank(this, getTankSize(tier), TANK_SIZE, IO.BOTH); } @Override public void onLoad() { super.onLoad(); if (getLevel() instanceof ServerLevel serverLevel) { serverLevel.getServer().tell(new TickTask(0, this::updateAutoOutputSubscription)); } this.invSubs = inventory.addChangedListener(this::updateAutoOutputSubscription); this.tankSubs = tank.addChangedListener(this::updateAutoOutputSubscription); } @Override public void onUnload() { super.onUnload(); if (invSubs != null) { invSubs.unsubscribe(); this.invSubs = null; } if (tankSubs != null) { tankSubs.unsubscribe(); this.tankSubs = null; } } //////////////////////////////// // ******* Auto Output *******// //////////////////////////////// @Override public void setAutoOutputFluids(boolean allow) { this.autoOutputFluids = allow; updateAutoOutputSubscription(); } @Override public void setOutputFacingFluids(@Nullable Direction outputFacing) { this.outputFacingFluids = outputFacing; updateAutoOutputSubscription(); } @Override public void setAutoOutputItems(boolean allow) { this.autoOutputItems = allow; updateAutoOutputSubscription(); } @Override public void setOutputFacingItems(@Nullable Direction outputFacing) { this.outputFacingItems = outputFacing; updateAutoOutputSubscription(); } @Override public void onNeighborChanged(Block block, BlockPos fromPos, boolean isMoving) { super.onNeighborChanged(block, fromPos, isMoving); updateAutoOutputSubscription(); } protected void updateAutoOutputSubscription() { var outputFacingItems = getOutputFacingItems(); var outputFacingFluids = getOutputFacingFluids(); if ((isAutoOutputItems() && !inventory.isEmpty() && outputFacingItems != null && GTTransferUtils.hasAdjacentItemHandler(getLevel(), getPos(), outputFacingItems)) || (isAutoOutputFluids() && !tank.isEmpty() && outputFacingFluids != null && GTTransferUtils.hasAdjacentFluidHandler(getLevel(), getPos(), outputFacingFluids))) { autoOutputSubs = subscribeServerTick(autoOutputSubs, this::autoOutput); } else if (autoOutputSubs != null) { autoOutputSubs.unsubscribe(); autoOutputSubs = null; } } protected void autoOutput() { if (getOffsetTimer() % 5 == 0) { if (isAutoOutputFluids() && getOutputFacingFluids() != null) { tank.exportToNearby(getOutputFacingFluids()); } if (isAutoOutputItems() && getOutputFacingItems() != null) { inventory.exportToNearby(getOutputFacingItems()); } } updateAutoOutputSubscription(); } //////////////////////////////// // ********** GUI *********** // //////////////////////////////// @Override public Widget createUIWidget() { int invTier = getTankSize(tier); var group = new WidgetGroup(0, 0, 18 * (invTier + 1) + 16, 18 * invTier + 16); var container = new WidgetGroup(4, 4, 18 * (invTier + 1) + 8, 18 * invTier + 8); int index = 0; for (int y = 0; y < invTier; y++) { for (int x = 0; x < invTier; x++) { container.addWidget(new SlotWidget( getInventory().storage, index++, 4 + x * 18, 4 + y * 18, true, true) .setBackgroundTexture(GuiTextures.SLOT)); } } index = 0; for (int y = 0; y < invTier; y++) { container.addWidget(new TankWidget( tank.getStorages()[index++], 4 + invTier * 18, 4 + y * 18, true, true) .setBackground(GuiTextures.FLUID_SLOT)); } container.setBackground(GuiTextures.BACKGROUND_INVERSE); group.addWidget(container); return group; } /////////////////////////////// // ******* Rendering ********// /////////////////////////////// @Override public @Nullable ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, Set<GTToolType> toolTypes, Direction side) { if (toolTypes.contains(GTToolType.SCREWDRIVER)) { if (side == getOutputFacingItems() || side == getOutputFacingFluids()) { return GuiTextures.TOOL_ALLOW_INPUT; } } return super.sideTips(player, pos, state, toolTypes, side); } //////////////////////////////// // ********** Misc ***********// //////////////////////////////// @Override public void onMachineRemoved() { clearInventory(inventory.storage); } }
412
0.916522
1
0.916522
game-dev
MEDIA
0.263719
game-dev
0.973793
1
0.973793
coin-or/Clp
4,867
examples/event1.cpp
#include <cassert> #include <iomanip> #include "CoinPragma.hpp" #include "OsiClpSolverInterface.hpp" #include "ClpSimplex.hpp" //############################################################################# /************************************************************************ This keeps track of iterations using event handler Coding was thrown together - data should be saved more elagantly */ #define SAVE_ITS 3 // Sequence of In variable int sequenceIn[SAVE_ITS]={-1}; // Direction of In, 1 going up, -1 going down, 0 not a clue int directionIn[SAVE_ITS]={-1}; // Sequence of Out variable int sequenceOut[SAVE_ITS]={-1}; // Direction of Out, 1 to upper bound, -1 to lower bound, 0 - superbasic int directionOut[SAVE_ITS]={-1}; // Pivot Row int pivot[SAVE_ITS]={-1}; /** This is so user can trap events and do useful stuff. ClpSimplex model_ is available as well as anything else you care to pass in */ class MyEventHandler : public ClpEventHandler { public: /**@name Overrides */ //@{ virtual int event(Event whichEvent); //@} /**@name Constructors, destructor etc*/ //@{ /** Default constructor. */ MyEventHandler(); /// Constructor with pointer to model (redundant as setEventHandler does) MyEventHandler(ClpSimplex *model); /** Destructor */ virtual ~MyEventHandler(); /** The copy constructor. */ MyEventHandler(const MyEventHandler &rhs); /// Assignment MyEventHandler &operator=(const MyEventHandler &rhs); /// Clone virtual ClpEventHandler *clone() const; //@} protected: // data goes here }; //------------------------------------------------------------------- // Default Constructor //------------------------------------------------------------------- MyEventHandler::MyEventHandler() : ClpEventHandler() { } //------------------------------------------------------------------- // Copy constructor //------------------------------------------------------------------- MyEventHandler::MyEventHandler(const MyEventHandler &rhs) : ClpEventHandler(rhs) { } // Constructor with pointer to model MyEventHandler::MyEventHandler(ClpSimplex *model) : ClpEventHandler(model) { } //------------------------------------------------------------------- // Destructor //------------------------------------------------------------------- MyEventHandler::~MyEventHandler() { } //---------------------------------------------------------------- // Assignment operator //------------------------------------------------------------------- MyEventHandler & MyEventHandler::operator=(const MyEventHandler &rhs) { if (this != &rhs) { ClpEventHandler::operator=(rhs); } return *this; } //------------------------------------------------------------------- // Clone //------------------------------------------------------------------- ClpEventHandler *MyEventHandler::clone() const { return new MyEventHandler(*this); } int MyEventHandler::event(Event whichEvent) { if (whichEvent == endOfIteration) { // move up for (int i=SAVE_ITS-2;i>=0;i--) { sequenceIn[i+1] = sequenceIn[i]; directionIn[i+1] = directionIn[i]; sequenceOut[i+1] = sequenceOut[i]; directionOut[i+1] = directionOut[i]; pivot[i+1] = pivot[i]; } sequenceIn[0] = model_->sequenceIn(); directionIn[0] = model_->directionIn(); sequenceOut[0] = model_->sequenceOut(); directionOut[0] = model_->directionOut(); pivot[0] = model_->pivotRow(); } return -1; } int main(int argc, const char *argv[]) { #ifndef OSICLP // using ClpSimplex ClpSimplex model; #else OsiClpSolverInterface solver1; #endif // Read in model using argv[1] // and assert that it is a clean model std::string mpsFileName; if (argc >= 2) { mpsFileName = argv[1]; #ifndef OSICLP int numMpsReadErrors = model.readMps(mpsFileName.c_str()); #else int numMpsReadErrors = solver1.readMps(mpsFileName.c_str(), ""); #endif if (numMpsReadErrors != 0) { printf("%d errors reading MPS file\n", numMpsReadErrors); return numMpsReadErrors; } } else { printf("Need mps file\n"); return -1; } // allow Clp to track iterations MyEventHandler clpEventHandler; #ifndef OSICLP ClpSimplex * simplex = &model; #else // go over to Clp ClpSimplex * simplex = solver1.getModelPtr(); #endif simplex->passInEventHandler(&clpEventHandler); // If tiny problem more output if (simplex->numberRows()<40) simplex->setLogLevel(63); simplex->primal(); /* print last few iterations then can change basis etc */ printf("last few iterations\n"); int numberIterations = simplex->numberIterations(); for (int i=0;i<SAVE_ITS;i++) { printf("Iteration %d in %d direction %d out %d direction %d pivotrow %d\n", numberIterations-i,sequenceIn[i],directionIn[i], sequenceOut[i],directionOut[i],pivot[i]); } return 0; }
412
0.940002
1
0.940002
game-dev
MEDIA
0.377065
game-dev
0.902386
1
0.902386
CyanogenMod/android_external_webkit
6,611
Source/WebCore/rendering/TransformState.cpp
/* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "TransformState.h" namespace WebCore { void TransformState::move(int x, int y, TransformAccumulation accumulate) { if (m_accumulatingTransform && m_accumulatedTransform) { // If we're accumulating into an existing transform, apply the translation. if (m_direction == ApplyTransformDirection) m_accumulatedTransform->translateRight(x, y); else m_accumulatedTransform->translate(-x, -y); // We're unapplying, so negate // Then flatten if necessary. if (accumulate == FlattenTransform) flatten(); } else { // Just move the point and, optionally, the quad. m_lastPlanarPoint.move(x, y); if (m_mapQuad) m_lastPlanarQuad.move(x, y); } m_accumulatingTransform = accumulate == AccumulateTransform; } // FIXME: We transform AffineTransform to TransformationMatrix. This is rather inefficient. void TransformState::applyTransform(const AffineTransform& transformFromContainer, TransformAccumulation accumulate) { applyTransform(transformFromContainer.toTransformationMatrix(), accumulate); } void TransformState::applyTransform(const TransformationMatrix& transformFromContainer, TransformAccumulation accumulate) { // If we have an accumulated transform from last time, multiply in this transform if (m_accumulatedTransform) { if (m_direction == ApplyTransformDirection) m_accumulatedTransform.set(new TransformationMatrix(transformFromContainer * *m_accumulatedTransform)); else m_accumulatedTransform->multiply(transformFromContainer); } else if (accumulate == AccumulateTransform) { // Make one if we started to accumulate m_accumulatedTransform.set(new TransformationMatrix(transformFromContainer)); } if (accumulate == FlattenTransform) { const TransformationMatrix* finalTransform = m_accumulatedTransform ? m_accumulatedTransform.get() : &transformFromContainer; flattenWithTransform(*finalTransform); } m_accumulatingTransform = accumulate == AccumulateTransform; } void TransformState::flatten() { if (!m_accumulatedTransform) { m_accumulatingTransform = false; return; } flattenWithTransform(*m_accumulatedTransform); } FloatPoint TransformState::mappedPoint() const { if (!m_accumulatedTransform) return m_lastPlanarPoint; if (m_direction == ApplyTransformDirection) return m_accumulatedTransform->mapPoint(m_lastPlanarPoint); return m_accumulatedTransform->inverse().projectPoint(m_lastPlanarPoint); } FloatQuad TransformState::mappedQuad() const { if (!m_accumulatedTransform) return m_lastPlanarQuad; if (m_direction == ApplyTransformDirection) return m_accumulatedTransform->mapQuad(m_lastPlanarQuad); return m_accumulatedTransform->inverse().projectQuad(m_lastPlanarQuad); } void TransformState::flattenWithTransform(const TransformationMatrix& t) { if (m_direction == ApplyTransformDirection) { m_lastPlanarPoint = t.mapPoint(m_lastPlanarPoint); if (m_mapQuad) m_lastPlanarQuad = t.mapQuad(m_lastPlanarQuad); } else { TransformationMatrix inverseTransform = t.inverse(); m_lastPlanarPoint = inverseTransform.projectPoint(m_lastPlanarPoint); if (m_mapQuad) m_lastPlanarQuad = inverseTransform.projectQuad(m_lastPlanarQuad); } // We could throw away m_accumulatedTransform if we wanted to here, but that // would cause thrash when traversing hierarchies with alternating // preserve-3d and flat elements. if (m_accumulatedTransform) m_accumulatedTransform->makeIdentity(); m_accumulatingTransform = false; } // HitTestingTransformState methods void HitTestingTransformState::translate(int x, int y, TransformAccumulation accumulate) { m_accumulatedTransform.translate(x, y); if (accumulate == FlattenTransform) flattenWithTransform(m_accumulatedTransform); m_accumulatingTransform = accumulate == AccumulateTransform; } void HitTestingTransformState::applyTransform(const TransformationMatrix& transformFromContainer, TransformAccumulation accumulate) { m_accumulatedTransform.multiply(transformFromContainer); if (accumulate == FlattenTransform) flattenWithTransform(m_accumulatedTransform); m_accumulatingTransform = accumulate == AccumulateTransform; } void HitTestingTransformState::flatten() { flattenWithTransform(m_accumulatedTransform); } void HitTestingTransformState::flattenWithTransform(const TransformationMatrix& t) { TransformationMatrix inverseTransform = t.inverse(); m_lastPlanarPoint = inverseTransform.projectPoint(m_lastPlanarPoint); m_lastPlanarQuad = inverseTransform.projectQuad(m_lastPlanarQuad); m_accumulatedTransform.makeIdentity(); m_accumulatingTransform = false; } FloatPoint HitTestingTransformState::mappedPoint() const { return m_accumulatedTransform.inverse().projectPoint(m_lastPlanarPoint); } FloatQuad HitTestingTransformState::mappedQuad() const { return m_accumulatedTransform.inverse().projectQuad(m_lastPlanarQuad); } } // namespace WebCore
412
0.969609
1
0.969609
game-dev
MEDIA
0.483075
game-dev,graphics-rendering
0.974664
1
0.974664
googlestadia/kernel
5,180
drivers/gpu/drm/nouveau/nvkm/core/engine.c
/* * Copyright 2012 Red Hat Inc. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Ben Skeggs */ #include <core/engine.h> #include <core/device.h> #include <core/option.h> #include <subdev/fb.h> bool nvkm_engine_chsw_load(struct nvkm_engine *engine) { if (engine->func->chsw_load) return engine->func->chsw_load(engine); return false; } void nvkm_engine_unref(struct nvkm_engine **pengine) { struct nvkm_engine *engine = *pengine; if (engine) { mutex_lock(&engine->subdev.mutex); if (--engine->usecount == 0) nvkm_subdev_fini(&engine->subdev, false); mutex_unlock(&engine->subdev.mutex); *pengine = NULL; } } struct nvkm_engine * nvkm_engine_ref(struct nvkm_engine *engine) { if (engine) { mutex_lock(&engine->subdev.mutex); if (++engine->usecount == 1) { int ret = nvkm_subdev_init(&engine->subdev); if (ret) { engine->usecount--; mutex_unlock(&engine->subdev.mutex); return ERR_PTR(ret); } } mutex_unlock(&engine->subdev.mutex); } return engine; } void nvkm_engine_tile(struct nvkm_engine *engine, int region) { struct nvkm_fb *fb = engine->subdev.device->fb; if (engine->func->tile) engine->func->tile(engine, region, &fb->tile.region[region]); } static void nvkm_engine_intr(struct nvkm_subdev *subdev) { struct nvkm_engine *engine = nvkm_engine(subdev); if (engine->func->intr) engine->func->intr(engine); } static int nvkm_engine_info(struct nvkm_subdev *subdev, u64 mthd, u64 *data) { struct nvkm_engine *engine = nvkm_engine(subdev); if (engine->func->info) { if (!IS_ERR((engine = nvkm_engine_ref(engine)))) { int ret = engine->func->info(engine, mthd, data); nvkm_engine_unref(&engine); return ret; } return PTR_ERR(engine); } return -ENOSYS; } static int nvkm_engine_fini(struct nvkm_subdev *subdev, bool suspend) { struct nvkm_engine *engine = nvkm_engine(subdev); if (engine->func->fini) return engine->func->fini(engine, suspend); return 0; } static int nvkm_engine_init(struct nvkm_subdev *subdev) { struct nvkm_engine *engine = nvkm_engine(subdev); struct nvkm_fb *fb = subdev->device->fb; int ret = 0, i; s64 time; if (!engine->usecount) { nvkm_trace(subdev, "init skipped, engine has no users\n"); return ret; } if (engine->func->oneinit && !engine->subdev.oneinit) { nvkm_trace(subdev, "one-time init running...\n"); time = ktime_to_us(ktime_get()); ret = engine->func->oneinit(engine); if (ret) { nvkm_trace(subdev, "one-time init failed, %d\n", ret); return ret; } engine->subdev.oneinit = true; time = ktime_to_us(ktime_get()) - time; nvkm_trace(subdev, "one-time init completed in %lldus\n", time); } if (engine->func->init) ret = engine->func->init(engine); for (i = 0; fb && i < fb->tile.regions; i++) nvkm_engine_tile(engine, i); return ret; } static int nvkm_engine_preinit(struct nvkm_subdev *subdev) { struct nvkm_engine *engine = nvkm_engine(subdev); if (engine->func->preinit) engine->func->preinit(engine); return 0; } static void * nvkm_engine_dtor(struct nvkm_subdev *subdev) { struct nvkm_engine *engine = nvkm_engine(subdev); if (engine->func->dtor) return engine->func->dtor(engine); return engine; } static const struct nvkm_subdev_func nvkm_engine_func = { .dtor = nvkm_engine_dtor, .preinit = nvkm_engine_preinit, .init = nvkm_engine_init, .fini = nvkm_engine_fini, .info = nvkm_engine_info, .intr = nvkm_engine_intr, }; int nvkm_engine_ctor(const struct nvkm_engine_func *func, struct nvkm_device *device, int index, bool enable, struct nvkm_engine *engine) { nvkm_subdev_ctor(&nvkm_engine_func, device, index, &engine->subdev); engine->func = func; if (!nvkm_boolopt(device->cfgopt, nvkm_subdev_name[index], enable)) { nvkm_debug(&engine->subdev, "disabled\n"); return -ENODEV; } spin_lock_init(&engine->lock); return 0; } int nvkm_engine_new_(const struct nvkm_engine_func *func, struct nvkm_device *device, int index, bool enable, struct nvkm_engine **pengine) { if (!(*pengine = kzalloc(sizeof(**pengine), GFP_KERNEL))) return -ENOMEM; return nvkm_engine_ctor(func, device, index, enable, *pengine); }
412
0.842235
1
0.842235
game-dev
MEDIA
0.559341
game-dev
0.802343
1
0.802343
JaylyDev/ScriptAPI
2,576
scripts/anti-nuker/index.js
// Script example for ScriptAPI // Author: iBlqzed <https://github.com/iBlqzed> // Project: https://github.com/JaylyDev/ScriptAPI import { system, world } from "@minecraft/server" import { TickEventSignal } from "tick-event/index" const log = new Map() const blockLog = new Map() world.afterEvents.playerBreakBlock.subscribe(({ block, brokenBlockPermutation, dimension, player }) => { const old = log.get(player.name) log.set(player.name, { time: Date.now(), amount: old?.amount ?? 0 }) if (!old) return if ((old.time ?? Date.now()) < (Date.now() - 50)) return blockLog.set(player.name, { location: block.location, permutation: brokenBlockPermutation }) if (blockLog.has(player.name) && log.get(player.name).amount === 0) { dimension.getBlock(blockLog.get(player.name).location).setPermutation(blockLog.get(player.name).permutation) setTickTimeout(() => { dimension.getEntitiesAtBlockLocation(blockLog.get(player.name)?.location ?? block.location)?.filter((entity) => entity.typeId === "minecraft:item")?.forEach((item) => item.kill()) blockLog.delete(player.name) }, 0) } dimension.getBlock(block.location).setPermutation(brokenBlockPermutation) setTickTimeout(() => { dimension.getEntitiesAtBlockLocation(block.location)?.filter((entity) => entity.typeId === "minecraft:item").forEach((item) => item.kill()) }, 0) log.set(player.name, { time: Date.now(), amount: ++old.amount }) }) system.runInterval(() => { [...log.keys()]?.forEach(pN => { if (log.get(pN).amount > 5) { const player = [...world.getPlayers()].find(pL => pL.name === pN) player.runCommandAsync(`say NUKER`) } log.set(pN, Object.assign(log.get(pN), { amount: 0 })) }) }) world.afterEvents.playerLeave.subscribe((data) => (log.delete(data.playerName)) && (blockLog.delete(data.playerName))) /** * Delay executing a function * @param {() => void} callback Code you want to execute when the delay is finished * @param {number} tick Time in ticks until the callback runs * @param {boolean} loop Whether or not the code should loop or not * @example setTickTimeout(() => { * console.warn(`This was called after 20 ticks!`) * }, 20) */ function setTickTimeout(callback, tick, loop = false) { const tickEvent = new TickEventSignal(); let cT = 0 const tE = tickEvent.subscribe((data) => { if (cT === 0) cT = data.currentTick + tick if (cT <= data.currentTick) { try { callback() } catch (e) { console.warn(`${e} : ${e.stack}`) } if (loop) cT += tick else tickEvent.unsubscribe(tE) } }) }
412
0.808009
1
0.808009
game-dev
MEDIA
0.755115
game-dev
0.951406
1
0.951406
microsoft/microsoft-ui-xaml
5,318
src/dxaml/xcp/core/inc/ColorKeyFrame.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #pragma once #include "KeyFrame.h" #include "KeyFrameCollection.h" #include "DependencyObjectTraits.h" #include "DependencyObjectTraits.g.h" class CCoreServices; class CColorKeyFrame : public CKeyFrame { protected: CColorKeyFrame( _In_ CCoreServices *pCore ) : CKeyFrame(pCore) {} public: DECLARE_CREATE_RETURN(CColorKeyFrame, E_UNEXPECTED); KnownTypeIndex GetTypeIndex() const override { return DependencyObjectTraits<CColorKeyFrame>::Index; } public: XUINT32 m_uValue = 0xFF000000; }; class CLinearColorKeyFrame final : public CColorKeyFrame { protected: CLinearColorKeyFrame( _In_ CCoreServices *pCore ) : CColorKeyFrame(pCore) {} public: #if defined(__XAML_UNITTESTS__) CLinearColorKeyFrame() // !!! FOR UNIT TESTING ONLY !!! : CLinearColorKeyFrame(nullptr) {} #endif DECLARE_CREATE(CLinearColorKeyFrame); KnownTypeIndex GetTypeIndex() const override { return DependencyObjectTraits<CLinearColorKeyFrame>::Index; } bool IsDiscrete() override { return false; } float GetEffectiveProgress(_In_ XFLOAT rCurrentProgress) override { return rCurrentProgress; } #pragma region ::Windows::UI::Composition CompositionAnimationConversionResult AddCompositionKeyFrame( _In_ CompositionAnimationConversionContext* context, _Inout_ WUComp::IKeyFrameAnimation* animation) override; #pragma endregion }; class CDiscreteColorKeyFrame final : public CColorKeyFrame { protected: CDiscreteColorKeyFrame( _In_ CCoreServices *pCore ) : CColorKeyFrame(pCore) {} public: #if defined(__XAML_UNITTESTS__) CDiscreteColorKeyFrame() // !!! FOR UNIT TESTING ONLY !!! : CDiscreteColorKeyFrame(nullptr) {} #endif DECLARE_CREATE(CDiscreteColorKeyFrame); KnownTypeIndex GetTypeIndex() const override { return DependencyObjectTraits<CDiscreteColorKeyFrame>::Index; } bool IsDiscrete() override { return true; } float GetEffectiveProgress(float rCurrentProgress) override { UNREFERENCED_PARAMETER(rCurrentProgress); // Discrete keyframes clamp to the starting value of the time segment return 0; } #pragma region ::Windows::UI::Composition CompositionAnimationConversionResult AddCompositionKeyFrame( _In_ CompositionAnimationConversionContext* context, _Inout_ WUComp::IKeyFrameAnimation* animation) override; #pragma endregion }; class CSplineColorKeyFrame : public CColorKeyFrame { protected: CSplineColorKeyFrame( _In_ CCoreServices *pCore ) : CColorKeyFrame(pCore) {} public: #if defined(__XAML_UNITTESTS__) CSplineColorKeyFrame() // !!! FOR UNIT TESTING ONLY !!! : CSplineColorKeyFrame(nullptr) {} #endif ~CSplineColorKeyFrame() override; static _Check_return_ HRESULT Create( _Outptr_ CDependencyObject **ppObject, _In_ CREATEPARAMETERS *pCreate); KnownTypeIndex GetTypeIndex() const override { return DependencyObjectTraits<CSplineColorKeyFrame>::Index; } bool IsDiscrete() override { return false; } float GetEffectiveProgress(float rCurrentProgress) override; #pragma region ::Windows::UI::Composition CompositionAnimationConversionResult AddCompositionKeyFrame( _In_ CompositionAnimationConversionContext* context, _Inout_ WUComp::IKeyFrameAnimation* animation) override; #pragma endregion public: CKeySpline* m_pKeySpline = nullptr; }; class CEasingColorKeyFrame final : public CColorKeyFrame { protected: CEasingColorKeyFrame( _In_ CCoreServices *pCore ) : CColorKeyFrame(pCore) {} public: #if defined(__XAML_UNITTESTS__) CEasingColorKeyFrame() // !!! FOR UNIT TESTING ONLY !!! : CEasingColorKeyFrame(nullptr) {} #endif ~CEasingColorKeyFrame() override; DECLARE_CREATE(CEasingColorKeyFrame); KnownTypeIndex GetTypeIndex() const override { return DependencyObjectTraits<CEasingColorKeyFrame>::Index; } bool IsDiscrete() override { return false; } float GetEffectiveProgress(float rCurrentProgress) override; #pragma region ::Windows::UI::Composition CompositionAnimationConversionResult AddCompositionKeyFrame( _In_ CompositionAnimationConversionContext* context, _Inout_ WUComp::IKeyFrameAnimation* animation) override; #pragma endregion public: // Easing function for the animation. // Native easing functions all derive from CEasingFunctionBase. Managed ones must implement IEasingFunction. CDependencyObject *m_pEasingFunction = nullptr; }; class CColorKeyFrameCollection final : public CKeyFrameCollection { private: CColorKeyFrameCollection(_In_ CCoreServices *pCore) : CKeyFrameCollection(pCore) {} public: #if defined(__XAML_UNITTESTS__) CColorKeyFrameCollection() // !!! FOR UNIT TESTING ONLY !!! : CColorKeyFrameCollection(nullptr) {} #endif DECLARE_CREATE(CColorKeyFrameCollection); KnownTypeIndex GetTypeIndex() const override { return DependencyObjectTraits<CColorKeyFrameCollection>::Index; } };
412
0.699103
1
0.699103
game-dev
MEDIA
0.384848
game-dev,desktop-app
0.769059
1
0.769059
MohistMC/Youer
2,781
src/main/java/net/neoforged/neoforge/client/model/generators/loaders/CompositeModelBuilder.java
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.neoforged.neoforge.client.model.generators.loaders; import com.google.common.base.Preconditions; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.client.model.generators.CustomLoaderBuilder; import net.neoforged.neoforge.client.model.generators.ModelBuilder; import net.neoforged.neoforge.common.data.ExistingFileHelper; public class CompositeModelBuilder<T extends ModelBuilder<T>> extends CustomLoaderBuilder<T> { public static <T extends ModelBuilder<T>> CompositeModelBuilder<T> begin(T parent, ExistingFileHelper existingFileHelper) { return new CompositeModelBuilder<>(parent, existingFileHelper); } private final Map<String, T> childModels = new LinkedHashMap<>(); private final List<String> itemRenderOrder = new ArrayList<>(); protected CompositeModelBuilder(T parent, ExistingFileHelper existingFileHelper) { super(ResourceLocation.fromNamespaceAndPath("neoforge", "composite"), parent, existingFileHelper, false); } public CompositeModelBuilder<T> child(String name, T modelBuilder) { Preconditions.checkNotNull(name, "name must not be null"); Preconditions.checkNotNull(modelBuilder, "modelBuilder must not be null"); childModels.put(name, modelBuilder); itemRenderOrder.add(name); return this; } public CompositeModelBuilder<T> itemRenderOrder(String... names) { Preconditions.checkNotNull(names, "names must not be null"); Preconditions.checkArgument(names.length > 0, "names must contain at least one element"); for (String name : names) if (!childModels.containsKey(name)) throw new IllegalArgumentException("names contains \"" + name + "\", which is not a child of this model"); itemRenderOrder.clear(); itemRenderOrder.addAll(Arrays.asList(names)); return this; } @Override public JsonObject toJson(JsonObject json) { json = super.toJson(json); JsonObject children = new JsonObject(); for (Map.Entry<String, T> entry : childModels.entrySet()) { children.add(entry.getKey(), entry.getValue().toJson()); } json.add("children", children); JsonArray itemRenderOrder = new JsonArray(); for (String name : this.itemRenderOrder) { itemRenderOrder.add(name); } json.add("item_render_order", itemRenderOrder); return json; } }
412
0.85048
1
0.85048
game-dev
MEDIA
0.531556
game-dev
0.94196
1
0.94196
ForestDango/Hollow-Knight-Demo
1,203
Assets/PlayMaker/Actions/SceneManager/GetSceneIsLoaded.cs
// (c) Copyright HutongGames, LLC 2010-2016. All rights reserved. #if UNITY_5_3 || UNITY_5_3_OR_NEWER using System; using UnityEngine; using UnityEngine.SceneManagement; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Scene)] [Tooltip("Get a scene isLoaded flag.")] public class GetSceneIsLoaded : GetSceneActionBase { [ActionSection("Result")] [Tooltip("true if the scene is loaded.")] [UIHint(UIHint.Variable)] public FsmBool isLoaded; [Tooltip("Event sent if the scene is loaded.")] public FsmEvent isLoadedEvent; [Tooltip("Event sent if the scene is not loaded.")] public FsmEvent isNotLoadedEvent; [Tooltip("Repeat every Frame")] public bool everyFrame; public override void Reset() { base.Reset (); isLoaded = null; everyFrame = false; } public override void OnEnter() { base.OnEnter (); DoGetSceneIsLoaded(); if (!everyFrame) Finish(); } public override void OnUpdate() { DoGetSceneIsLoaded(); } void DoGetSceneIsLoaded() { if (!_sceneFound) { return; } if (!isLoaded.IsNone) { isLoaded.Value = _scene.isLoaded; } Fsm.Event(sceneFoundEvent); } } } #endif
412
0.664547
1
0.664547
game-dev
MEDIA
0.990415
game-dev
0.663785
1
0.663785
onepub-dev/dcli
1,028
dcli_sdk/lib/src/dcli/resource/generated/A167f5142b43ae331132efb64caa22da9.g.dart
import 'package:dcli/dcli.dart'; /// GENERATED -- GENERATED /// /// DO NOT MODIFIY /// /// This script is generated via [Resource.pack()]. /// /// GENERATED - GENERATED class A167f5142b43ae331132efb64caa22da9 extends PackedResource { /// PackedResource - ../../template/project/find/CHANGELOG.md const A167f5142b43ae331132efb64caa22da9(); /// A hash of the resource (pre packed) calculated by /// [calculateHash]. /// This hash can be used to check if the resource needs to /// be updated on the target system. /// Use : /// ```dart /// calculateHash(pathToResource).hexEncode() == packResource.checksum /// ``` /// to compare the checksum of the local file with /// this checksum @override String get checksum => 'b4f9da480bf1305f21dfdd1398621e92'; /// `<package>/resources` relative path to the original resource. @override String get originalPath => 'template/project/find/CHANGELOG.md'; @override String get content => ''' IyMgMS4wLjAKCi0gSW5pdGlhbCB2ZXJzaW9uLgo= '''; }
412
0.676126
1
0.676126
game-dev
MEDIA
0.804578
game-dev
0.842453
1
0.842453
AiMiDi/C4D_MMD_Tool
1,375
sdk_2025/frameworks/cinema.framework/source/description/flpolygonobject.h
#ifndef FLPOLYGONOBJECT_H__ #define FLPOLYGONOBJECT_H__ enum { FIELDLAYER_POLYGON_OBJECT = 1000, // Baselink FIELDLAYER_POLYGON_MODE = 1001, // Int Cycle FIELDLAYER_POLYGON_MODE_VOLUME = 0, FIELDLAYER_POLYGON_MODE_SURFACE = 1, FIELDLAYER_POLYGON_MODE_POINTS = 2, FIELDLAYER_POLYGON_MODE_CURVATURE = 3, FIELDLAYER_POLYGON_DISTANCE = 1002, // Real FIELDLAYER_POLYGON_VOLUME_CLIP = 1003, // Int Cycle FIELDLAYER_POLYGON_VOLUME_CLIP_NONE = 0, FIELDLAYER_POLYGON_VOLUME_CLIP_INSIDE = 1, FIELDLAYER_POLYGON_VOLUME_CLIP_OUTSIDE = 2, FIELDLAYER_POLYGON_VOLUME_CLIP_INSIDE_INVERT = 3, FIELDLAYER_POLYGON_CLIP = 1004, // Bool FIELDLAYER_POLYGON_CURVATURE_MODE = 1005, // Int Cycle FIELDLAYER_POLYGON_CURVATURE_MODE_DIRECT = 0, FIELDLAYER_POLYGON_CURVATURE_MODE_CONVEX = 1, FIELDLAYER_POLYGON_CURVATURE_MODE_CONCAVE = 2, FIELDLAYER_POLYGON_CURVATURE_MODE_BOTH = 3, FIELDLAYER_POLYGON_CURVATURE_RADIUS = 1006, // Real FIELDLAYER_POLYGON_CURVATURE_DERIVATIVE = 1007, // Bool FIELDLAYER_POLYGON_CURVATURE_CONTOUR = 1008, // Int Cycle FIELDLAYER_POLYGON_CURVATURE_CONTOUR_PRIMARY = 0, FIELDLAYER_POLYGON_CURVATURE_CONTOUR_SECONDARY = 1, FIELDLAYER_POLYGON_CURVATURE_USEUV = 1009, // Bool FIELDLAYER_POLYGON_USEDEFORMED = 1011, }; #endif // FLPOLYGONOBJECT_H__
412
0.697251
1
0.697251
game-dev
MEDIA
0.54335
game-dev
0.817923
1
0.817923
Stephan-S/FS25_AutoDrive
25,943
scripts/Modules/SpecialDrivingModule.lua
ADSpecialDrivingModule = {} ADSpecialDrivingModule.MAX_SPEED_DEVIATION = 6 function ADSpecialDrivingModule:new(vehicle) local o = {} setmetatable(o, self) self.__index = self o.vehicle = vehicle ADSpecialDrivingModule.reset(o) return o end function ADSpecialDrivingModule:reset() self.shouldStopOrHoldVehicle = false self.motorShouldNotBeStopped = false self.motorShouldBeStopped = false self.unloadingIntoBunkerSilo = false self.stoppedTimer = AutoDriveTON:new() self.vehicle.trailer = {} self.isReversing = false end function ADSpecialDrivingModule:stopVehicle(isBlocked, lx, lz) self.shouldStopOrHoldVehicle = true self.isBlocked = isBlocked self.targetLX = lx self.targetLZ = lz self.vehicle.trailer = {} end function ADSpecialDrivingModule:releaseVehicle() self.shouldStopOrHoldVehicle = false self.motorShouldBeStopped = false self.isBlocked = false self.stoppedTimer:timer(false) end function ADSpecialDrivingModule:update(dt) if self.shouldStopOrHoldVehicle then self:stopAndHoldVehicle(dt) end if AutoDrive.getDebugChannelIsSet(AutoDrive.DC_VEHICLEINFO) and self.vehicle.getIsEntered ~= nil and self.vehicle:getIsEntered() then local dbg = {} dbg.isStoppingVehicle = self:isStoppingVehicle() dbg.unloadingIntoBunkerSilo = self.unloadingIntoBunkerSilo dbg.shouldStopMotor = self:shouldStopMotor() dbg.shouldNotStopMotor = self:shouldNotStopMotor() dbg.stoppedTimer = self.stoppedTimer.elapsedTime AutoDrive.renderTable(0.6, 0.7, 0.009, dbg) end if not self.isReversing then self.reverseTarget = nil end self.isReversing = false end function ADSpecialDrivingModule:isStoppingVehicle() return self.shouldStopOrHoldVehicle end function ADSpecialDrivingModule:stopAndHoldVehicle(dt) if self.vehicle.spec_locomotive and self.vehicle.ad and self.vehicle.ad.trainModule then self.vehicle.ad.trainModule:stopAndHoldVehicle(dt) return end local finalSpeed = 0 local acc = -0.6 local allowedToDrive = false if math.abs(self.vehicle.lastSpeedReal) > 0.002 then finalSpeed = 0.01 allowedToDrive = true end local x, y, z = getWorldTranslation(self.vehicle.components[1].node) local lx, lz = self.targetLX, self.targetLZ if lx == nil or lz == nil then --If no target was provided, aim in front of te vehicle to prevent steering maneuvers local rx, _, rz = AutoDrive.localDirectionToWorld(self.vehicle, 0, 0, 1) x = x + rx z = z + rz lx, lz = AutoDrive.getDriveDirection(self.vehicle, x, y, z) end self.stoppedTimer:timer(self.vehicle.lastSpeedReal < 0.00028 and (self.vehicle.ad.trailerModule:getCanStopMotor()), 10000, dt) if self.stoppedTimer:done() then self.motorShouldBeStopped = true if self:shouldStopMotor() and self.vehicle:getIsMotorStarted() and (not g_currentMission.missionInfo.automaticMotorStartEnabled) then self.vehicle:stopMotor() end end self.vehicle.ad.trailerModule:handleTrailerReversing(false) AutoDrive.driveInDirection(self.vehicle, dt, 30, acc, 0.2, 20, allowedToDrive, true, lx, lz, finalSpeed, 1) end function ADSpecialDrivingModule:shouldStopMotor() return self.motorShouldBeStopped and (not self:shouldNotStopMotor()) end function ADSpecialDrivingModule:shouldNotStopMotor() return self.motorShouldNotBeStopped end function ADSpecialDrivingModule:driveForward(dt) local speed = 8 local acc = 0.6 local targetX, targetY, targetZ = AutoDrive.localToWorld(self.vehicle, 0, 0, 20) local lx, lz = AutoDrive.getDriveDirection(self.vehicle, targetX, targetY, targetZ) self:releaseVehicle() if self.vehicle.startMotor then if not self.vehicle:getIsMotorStarted() and self.vehicle:getCanMotorRun() and not self.vehicle.ad.specialDrivingModule:shouldStopMotor() then self.vehicle:startMotor() end end self.vehicle.ad.trailerModule:handleTrailerReversing(false) AutoDrive.driveInDirection(self.vehicle, dt, 30, acc, 0.2, 20, true, true, lx, lz, speed, 1) end function ADSpecialDrivingModule:driveReverse(dt, maxSpeed, maxAcceleration, guided) self.isReversing = true local speed = maxSpeed local acc = maxAcceleration if self.vehicle.ad.collisionDetectionModule:checkReverseCollision() then self:stopAndHoldVehicle(dt) else if guided ~= true then local targetX, targetY, targetZ = AutoDrive.localToWorld(self.vehicle, 0, 0, -20) local lx, lz = AutoDrive.getDriveDirection(self.vehicle, targetX, targetY, targetZ) self:releaseVehicle() if self.vehicle.startMotor then if not self.vehicle:getIsMotorStarted() and self.vehicle:getCanMotorRun() and not self.vehicle.ad.specialDrivingModule:shouldStopMotor() then self.vehicle:startMotor() end end -- Update trailers in case we need to lock the front axle self.vehicle.ad.trailerModule:handleTrailerReversing(true) local storedSmootherDriving = AutoDrive.smootherDriving AutoDrive.smootherDriving = false AutoDrive.driveInDirection(self.vehicle, dt, 30, acc, 0.2, 20, true, false, -lx, -lz, speed, 1) AutoDrive.smootherDriving = storedSmootherDriving else if self.reverseTarget == nil then local x, y, z = AutoDrive.localToWorld(self.vehicle, 0, 0 , -100) self.reverseTarget = {x=x, y=y, z=z} end self.vehicle.ad.specialDrivingModule:reverseToTargetLocation(dt, self.reverseTarget, maxSpeed) end end end function ADSpecialDrivingModule:driveToPoint(dt, point, maxFollowSpeed, checkDynamicCollision, maxAcc, maxSpeed) local speed = math.min(self.vehicle.ad.stateModule:getFieldSpeedLimit(), maxSpeed) local acc = math.max(0.75, maxAcc) local x, y, z = getWorldTranslation(self.vehicle.components[1].node) self.distanceToChasePos = MathUtil.vector2Length(x - point.x, z - point.z) if self.distanceToChasePos < 0.5 then speed = maxFollowSpeed * 1 elseif self.distanceToChasePos < 7 then speed = maxFollowSpeed + self.distanceToChasePos * 1.4 elseif self.distanceToChasePos < 20 then speed = maxFollowSpeed + self.distanceToChasePos * 2 end --print("Targetspeed: " .. speed .. " distance: " .. self.distanceToChasePos .. " maxFollowSpeed: " .. maxFollowSpeed) local lx, lz = AutoDrive.getDriveDirection(self.vehicle, point.x, point.y, point.z) if checkDynamicCollision and (self.vehicle.ad.collisionDetectionModule:hasDetectedObstable(dt) or self.vehicle.ad.sensors.frontSensor:pollInfo()) then self:stopVehicle(true, lx, lz) self:update(dt) else self:releaseVehicle() self.isBlocked = self.stoppedTimer:timer(self.vehicle.lastSpeedReal < 0.00028, 15000, dt) -- Allow active braking if vehicle is not 'following' targetSpeed precise enough if (self.vehicle.lastSpeedReal * 3600) > (speed + ADSpecialDrivingModule.MAX_SPEED_DEVIATION) then self.acceleration = -0.6 end --ADDrawingManager:addLineTask(x, y, z, point.x, point.y, point.z, 1, 1, 0, 0) if self.vehicle.startMotor then if not self.vehicle:getIsMotorStarted() and self.vehicle:getCanMotorRun() and not self.vehicle.ad.specialDrivingModule:shouldStopMotor() then self.vehicle:startMotor() end end self.vehicle.ad.trailerModule:handleTrailerReversing(false) local storedSmootherDriving = AutoDrive.smootherDriving AutoDrive.smootherDriving = false AutoDrive.driveInDirection(self.vehicle, dt, 30, acc, 0.2, 20, true, true, lx, lz, speed, 0.3) AutoDrive.smootherDriving = storedSmootherDriving end end function ADSpecialDrivingModule:handleReverseDriving(dt) self.wayPoints = self.vehicle.ad.drivePathModule:getWayPoints() self.currentWayPointIndex = self.vehicle.ad.drivePathModule:getCurrentWayPointIndex() AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving start self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) -- Update trailers in case we need to lock the front axle self.vehicle.ad.trailerModule:handleTrailerReversing(false) if self.vehicle.ad.trailerModule:isUnloadingToBunkerSilo() then AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving isUnloadingToBunkerSilo self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) if self.vehicle.ad.trailerModule:getIsBlocked(dt) then AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving isUnloadingToBunkerSilo driveForward self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) self:driveForward(dt) else AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving isUnloadingToBunkerSilo stopAndHoldVehicle self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) self:stopAndHoldVehicle(dt) end self.unloadingIntoBunkerSilo = true else if self.unloadingIntoBunkerSilo then AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving unloadingIntoBunkerSilo self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) self.vehicle.ad.drivePathModule:reachedTarget() else if self.wayPoints == nil or self.wayPoints[self.currentWayPointIndex] == nil then return end self.reverseNode = self:getReverseNode() if self.reverseNode == nil then AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving self.reverseNode == nil -> return self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) return end self.reverseTarget = self.wayPoints[self.currentWayPointIndex] -- if self.vehicle.getAISteeringNode ~= nil then -- local aix, aiy, aiz = getWorldTranslation(self.vehicle:getAISteeringNode()) -- ADDrawingManager:addLineTask(aix, aiy+3, aiz, self.reverseTarget.x, aiy+3, self.reverseTarget.z, 1, 1, 0, 0) -- end self:getBasicStates() if self:checkWayPointReached() then AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving self:checkWayPointReached -> handleReachedWayPoint / return self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) self.vehicle.ad.drivePathModule:handleReachedWayPoint() return end local inBunkerSilo = AutoDrive.isVehicleInBunkerSiloArea(self.vehicle) if not inBunkerSilo and (AutoDrive.getSetting("enableTrafficDetection") >= 1) and self.vehicle.ad.collisionDetectionModule:checkReverseCollision() then AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving self:stopAndHoldVehicle inBunkerSilo %s self.vehicle.ad.collisionDetectionModule:checkReverseCollision() %s self.currentWayPointIndex %s ", tostring(inBunkerSilo), tostring(self.vehicle.ad.collisionDetectionModule:checkReverseCollision()), tostring(self.currentWayPointIndex)) self:stopAndHoldVehicle(dt) else AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:handleReverseDriving reverseToPoint self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) -- open trailer cover if trigger is reachable local trailers, _ = AutoDrive.getAllUnits(self.vehicle) local isInRangeToLoadUnloadTarget = AutoDrive.isInRangeToLoadUnloadTarget(self.vehicle) AutoDrive.setTrailerCoverOpen(self.vehicle, trailers, isInRangeToLoadUnloadTarget) self:reverseToPoint(dt) end end self.unloadingIntoBunkerSilo = false end end function ADSpecialDrivingModule:getBasicStates() self.x, self.y, self.z = getWorldTranslation(self.vehicle:getAIDirectionNode()) self.vehicleVecX, _, self.vehicleVecZ = AutoDrive.localDirectionToWorld(self.vehicle, 0, 0, 1, self.vehicle:getAIDirectionNode()) self.rNx, self.rNy, self.rNz = getWorldTranslation(self.reverseNode) self.targetX, self.targetY, self.targetZ = AutoDrive.localToWorld(self.vehicle, 0, 0, 5, self.vehicle:getAIDirectionNode()) self.trailerVecX, _, self.trailerVecZ = AutoDrive.localDirectionToWorld(self.vehicle, 0, 0, 1, self.reverseNode) self.trailerRearVecX, _, self.trailerRearVecZ = AutoDrive.localDirectionToWorld(self.vehicle, 0, 0, -1, self.reverseNode) self.vecToPoint = {x = self.reverseTarget.x - self.rNx, z = self.reverseTarget.z - self.rNz} self.angleToTrailer = AutoDrive.angleBetween({x = self.vehicleVecX, z = self.vehicleVecZ}, {x = self.trailerVecX, z = self.trailerVecZ}) self.angleToPoint = AutoDrive.angleBetween({x = self.trailerRearVecX, z = self.trailerRearVecZ}, {x = self.vecToPoint.x, z = self.vecToPoint.z}) self.steeringAngle = math.deg(math.abs(self.vehicle.rotatedTime)) if self.reverseSolo then self.angleToTrailer = -math.deg(self.vehicle.rotatedTime) end self.trailerX, self.trailerY, self.trailerZ = AutoDrive.localToWorld(self.vehicle, 0, 0, 5, self.reverseNode) --ADDrawingManager:addLineTask(self.x, self.y+3, self.z, self.targetX, self.targetY+3, self.targetZ, 1, 1, 1, 1) --ADDrawingManager:addLineTask(self.rNx, self.rNy + 3, self.rNz, self.trailerX, self.trailerY + 3, self.trailerZ, 1, 1, 1, 1) --ADDrawingManager:addLineTask(self.reverseTarget.x, self.reverseTarget.y + 1, self.reverseTarget.z, self.trailerX, self.trailerY + 3, self.trailerZ, 1, 1, 1, 1) --ADDrawingManager:addLineTask(self.rNx, self.rNy + 3, self.rNz, self.rNx, self.rNy + 5, self.rNz, 1, 1, 1, 1) --print("AngleToTrailer: " .. self.angleToTrailer .. " angleToPoint: " .. self.angleToPoint) end function ADSpecialDrivingModule:getAngleToTrailer() self:getBasicStates() return self.angleToTrailer end function ADSpecialDrivingModule:checkWayPointReached() AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:checkWayPointReached start self.currentWayPointIndex %s ", tostring(self.currentWayPointIndex)) local distanceToTarget = MathUtil.vector2Length(self.reverseTarget.x - self.rNx, self.reverseTarget.z - self.rNz) local minDistance = 9 local angle = math.abs(self.angleToPoint) local storedIndex = self.vehicle.ad.drivePathModule.currentWayPoint self.vehicle.ad.drivePathModule.currentWayPoint = self.vehicle.ad.drivePathModule.currentWayPoint + 1 local _, isLastForward, isLastReverse = self.vehicle.ad.drivePathModule:checkForReverseSection() self.vehicle.ad.drivePathModule.currentWayPoint = storedIndex if self.reverseSolo then minDistance = AutoDrive.defineMinDistanceByVehicleType(self.vehicle, true) elseif self.currentWayPointIndex == #self.wayPoints or isLastForward or isLastReverse then minDistance = 3 end if distanceToTarget < minDistance or angle > 80 then AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:checkWayPointReached return true self.currentWayPointIndex %s minDistance=%.2f, distance=%.2f, angle=%.2f", tostring(self.currentWayPointIndex), minDistance, distanceToTarget, angle) return true end AutoDrive.debugPrint(self.vehicle, AutoDrive.DC_PATHINFO, "ADSpecialDrivingModule:checkWayPointReached end self.currentWayPointIndex %s minDistance=%.2f, distance=%.2f, angle=%.2f", tostring(self.currentWayPointIndex), minDistance, distanceToTarget, angle) return false end function ADSpecialDrivingModule:getReverseNode() local reverseNode local count = 1 if self.vehicle.trailer == nil then self.vehicle.trailer = {} end self.vehicle.trailer = nil for _, implement in pairs(AutoDrive.getAllImplements(self.vehicle, true)) do -- Logging.info("[AD] ADSpecialDrivingModule:getReverseNode count %s ", tostring(count)) if implement.ad == nil then implement.ad = {} end if (implement ~= self.vehicle or reverseNode == nil) and implement.spec_wheels ~= nil -- and AutoDrive.isImplementAllowedForReverseDriving(self.vehicle, implement) -- whitelist of implements allowed as reverse node then local implementX, implementY, implementZ = getWorldTranslation(implement.components[1].node) local _, _, diffZ = AutoDrive.worldToLocal(self.vehicle, implementX, implementY, implementZ) -- Logging.info("[AD] ADSpecialDrivingModule:getReverseNode diffZ %s ", tostring(diffZ)) if diffZ < 0 then -- if diffZ < 0 and math.abs(diffZ) >= (self.vehicle.size.length / 2) then local hasSynchronizedWheels = false local validWheel = false local centerX, centerZ = 0,0 local wheelCount = 0 for _, wheel in pairs(implement.spec_wheels.wheels) do validWheel = (wheel.physics.isSynchronized and wheel.physics.hasGroundContact) hasSynchronizedWheels = hasSynchronizedWheels or validWheel if validWheel then wheelCount = wheelCount + 1 local posX, _, posZ = localToLocal(wheel.node, implement.components[1].node, wheel.physics.positionX, wheel.physics.positionY, wheel.physics.positionZ) centerX = centerX + posX centerZ = centerZ + posZ end end -- Logging.info("[AD] ADSpecialDrivingModule:getReverseNode hasSynchronizedWheels %s ", tostring(hasSynchronizedWheels)) if hasSynchronizedWheels then if implement.spec_wheels.steeringCenterNode == nil then centerX = centerX / wheelCount centerZ = centerZ / wheelCount if not implement.ad.reverseNode then implement.ad.reverseNode = createTransformGroup("reverseNode") link(implement.components[1].node, implement.ad.reverseNode) end if centerX ~= nil and centerZ ~= nil then local vehX, _, vehZ = getWorldTranslation(self.vehicle.components[1].node) local implX, _, implZ = getWorldTranslation(implement.components[1].node) local trailerVecX, _, trailerVecZ = AutoDrive.localDirectionToWorld(implement, 0, 0, 1) local angleToVeh = AutoDrive.angleBetween({x = vehX - implX, z = vehZ - implZ}, {x = trailerVecX, z = trailerVecZ}) setTranslation(implement.ad.reverseNode, centerX, 0, centerZ) if angleToVeh > 60 then -- setRotation(implement.spec_wheels.steeringCenterNode, 0, math.rad(90), 0) setRotation(implement.ad.reverseNode, 0, math.rad(90), 0) elseif angleToVeh < -60 then -- setRotation(implement.spec_wheels.steeringCenterNode, 0, math.rad(-90), 0) setRotation(implement.ad.reverseNode, 0, math.rad(-90), 0) end end else implement.ad.reverseNode = implement.spec_wheels.steeringCenterNode end reverseNode = implement.ad.reverseNode self.reverseSolo = false self.vehicle.trailer = implement break end end end count = count + 1 end if reverseNode == nil then -- no implement with steeringCenterNode found if self.vehicle.spec_wheels and self.vehicle.spec_wheels.steeringCenterNode then local steeringCenterX, steeringCenterY, steeringCenterZ = getWorldTranslation(self.vehicle.spec_wheels.steeringCenterNode) local _, _, diffZ = AutoDrive.worldToLocal(self.vehicle, steeringCenterX, steeringCenterY, steeringCenterZ) -- use the more back node if diffZ < 0 then reverseNode = self.vehicle.spec_wheels.steeringCenterNode end end if reverseNode == nil then -- if no steeringCenterNode available use the vehicle itself reverseNode = self.vehicle.components[1].node end self.reverseSolo = true end return reverseNode end function ADSpecialDrivingModule:reverseToPoint(dt, maxSpeed) if maxSpeed == nil then maxSpeed = math.huge end local vehicleIsTruck = self:isTruck(self.vehicle) if self.lastAngleToPoint == nil then self.lastAngleToPoint = self.angleToPoint end -- TODO - this is never reset to 0, cause reverse drive circles become more and more tight -- if self.i == nil then self.i = 0 -- end local delta = self.angleToPoint -- - angleToTrailer local p = delta self.i = self.i + (delta) * 0.05 local d = delta - self.lastAngleToPoint self.pFactor = 6 --self.vehicle.ad.stateModule:getSpeedLimit() self.iFactor = 0.01 self.dFactor = 1400 --self.vehicle.ad.stateModule:getFieldSpeedLimit() * 100 if vehicleIsTruck then self.pFactor = 1 --self.vehicle.ad.stateModule:getSpeedLimit() * 0.05 --0.1 -- --0.1 self.iFactor = 0.00001 self.dFactor = 6.7 --self.vehicle.ad.stateModule:getFieldSpeedLimit() * 0.1 --10 end local targetAngleToTrailer = math.clamp((p * self.pFactor) + (self.i * self.iFactor) + (d * self.dFactor), -40, 40) local targetDiff = self.angleToTrailer - targetAngleToTrailer local offsetX = -targetDiff * 5 local offsetZ = -20 if vehicleIsTruck then offsetX = -targetDiff * 0.1 offsetZ = -100 end --print("p: " .. p .. " i: " .. self.i .. " d: " .. d) --print("p: " .. p * self.pFactor .. " i: " .. (self.i * self.iFactor) .. " d: " .. (d * self.dFactor)) --print("targetAngleToTrailer: " .. targetAngleToTrailer .. " targetDiff: " .. targetDiff .. " offsetX" .. offsetX) local speed = 5 + (6 * math.clamp((5 / math.max(1, self.steeringAngle, math.abs(self.angleToTrailer))), 0, 1)) local acc = 0.4 if vehicleIsTruck then speed = 3 end local node = self.vehicle:getAIDirectionNode() local rx, _, rz = AutoDrive.localDirectionToWorld(self.vehicle, offsetX, 0, offsetZ, node) local targetX = self.x + rx local targetZ = self.z + rz if self.reverseSolo then targetX = self.reverseTarget.x targetZ = self.reverseTarget.z end local lx, lz = AutoDrive.getDriveDirection(self.vehicle, targetX, self.y, targetZ, node) if self.reverseSolo then lx = -lx lz = -lz end local maxAngle = 60 if self.vehicle.maxRotation then if self.vehicle.maxRotation > (2 * math.pi) then maxAngle = self.vehicle.maxRotation else maxAngle = math.deg(self.vehicle.maxRotation) end end self:releaseVehicle() if self.vehicle.startMotor then if not self.vehicle:getIsMotorStarted() and self.vehicle:getCanMotorRun() and not self.vehicle.ad.specialDrivingModule:shouldStopMotor() then self.vehicle:startMotor() end end self.vehicle.ad.trailerModule:handleTrailerReversing(true) local storedSmootherDriving = AutoDrive.smootherDriving AutoDrive.smootherDriving = false speed = math.min(maxSpeed, speed) AutoDrive.driveInDirection(self.vehicle, dt, maxAngle, acc, 0.2, 20, true, false, lx, lz, speed, 1) AutoDrive.smootherDriving = storedSmootherDriving self.lastAngleToPoint = self.angleToPoint end function ADSpecialDrivingModule:reverseToTargetLocation(dt, location, maxSpeed) self.reverseNode = self:getReverseNode() if self.reverseNode == nil then return true end self.reverseTarget = location self.currentWayPointIndex = 0 self.wayPoints = {} self:getBasicStates() if self:checkWayPointReached() then return true end if self.vehicle.ad.collisionDetectionModule:checkReverseCollision() then self:stopAndHoldVehicle(dt) else self:reverseToPoint(dt, maxSpeed) end return false end function ADSpecialDrivingModule:isTruck(vehicle) local ret = false if vehicle == nil then return false end for _,joint in pairs(vehicle.spec_attacherJoints.attacherJoints) do if AttacherJoints.jointTypeNameToInt["semitrailer"] and joint.jointType == AttacherJoints.jointTypeNameToInt["semitrailer"] then ret = true break elseif AttacherJoints.jointTypeNameToInt["hookLift"] and joint.jointType == AttacherJoints.jointTypeNameToInt["hookLift"] then ret = true break elseif AttacherJoints.jointTypeNameToInt["terraVariant"] and joint.jointType == AttacherJoints.jointTypeNameToInt["terraVariant"] then ret = true break end end return ret end
412
0.769905
1
0.769905
game-dev
MEDIA
0.413539
game-dev
0.945076
1
0.945076
dreamanlan/CSharpGameFramework
1,045
Unity3d/Assets/Standard Assets/Utility/SimpleActivatorMenu.cs
using System; using UnityEngine; using UnityEngine.UI; namespace UnityStandardAssets.Utility { public class SimpleActivatorMenu : MonoBehaviour { // An incredibly simple menu which, when given references // to gameobjects in the scene public Text camSwitchButton; public GameObject[] objects; private int m_CurrentActiveObject; private void OnEnable() { // active object starts from first in array m_CurrentActiveObject = 0; camSwitchButton.text = objects[m_CurrentActiveObject].name; } public void NextCamera() { int nextactiveobject = m_CurrentActiveObject + 1 >= objects.Length ? 0 : m_CurrentActiveObject + 1; for (int i = 0; i < objects.Length; i++) { objects[i].SetActive(i == nextactiveobject); } m_CurrentActiveObject = nextactiveobject; camSwitchButton.text = objects[m_CurrentActiveObject].name; } } }
412
0.530578
1
0.530578
game-dev
MEDIA
0.95667
game-dev
0.64862
1
0.64862
BedwarsRel/BedwarsRel
6,226
common/src/main/java/io/github/bedwarsrel/game/GameLobbyCountdown.java
package io.github.bedwarsrel.game; import com.google.common.collect.ImmutableMap; import io.github.bedwarsrel.BedwarsRel; import io.github.bedwarsrel.utils.ChatWriter; import io.github.bedwarsrel.utils.SoundMachine; import java.lang.reflect.Method; import java.util.ArrayList; import lombok.Getter; import lombok.Setter; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; public class GameLobbyCountdown extends BukkitRunnable { @Getter @Setter private int counter = 0; private Game game = null; @Getter private int lobbytime; @Getter private int lobbytimeWhenFull; public GameLobbyCountdown(Game game) { this.game = game; this.counter = BedwarsRel.getInstance().getConfig().getInt("lobbytime"); this.lobbytime = this.counter; this.lobbytimeWhenFull = BedwarsRel.getInstance().getConfig().getInt("lobbytime-full"); } @Override public void run() { ArrayList<Player> players = this.game.getPlayers(); float xpPerLevel = 1.0F / this.lobbytime; if (this.game.getState() != GameState.WAITING) { this.game.setGameLobbyCountdown(null); this.cancel(); return; } if (this.counter > this.lobbytimeWhenFull && this.game.getPlayerAmount() == this.game.getMaxPlayers()) { this.counter = this.lobbytimeWhenFull; for (Player aPlayer : players) { if (aPlayer.isOnline()) { aPlayer.sendMessage(ChatWriter.pluginMessage(ChatColor.YELLOW + BedwarsRel ._l(aPlayer, "lobby.countdown", ImmutableMap.of("sec", ChatColor.RED.toString() + this.counter + ChatColor.YELLOW)))); } } } if (this.counter == this.lobbytimeWhenFull) { for (Player p : players) { if (p.getInventory().contains(Material.EMERALD)) { p.getInventory().remove(Material.EMERALD); } } } for (Player p : players) { p.setLevel(this.counter); if (this.counter == this.lobbytime) { p.setExp(1.0F); } else { p.setExp(1.0F - (xpPerLevel * (this.lobbytime - this.counter))); } } if (this.counter == this.lobbytime) { for (Player aPlayer : players) { if (aPlayer.isOnline()) { aPlayer.sendMessage(ChatWriter.pluginMessage(ChatColor.YELLOW + BedwarsRel ._l(aPlayer, "lobby.countdown", ImmutableMap.of("sec", ChatColor.RED.toString() + this.counter + ChatColor.YELLOW)))); } } for (Player p : players) { if (!p.getInventory().contains(Material.DIAMOND) && p.hasPermission("bw.vip.forcestart")) { this.game.getPlayerStorage(p).addGameStartItem(); } if (!p.getInventory().contains(Material.EMERALD) && (p.isOp() || p.hasPermission("bw.setup") || p.hasPermission("bw.vip.reducecountdown"))) { this.game.getPlayerStorage(p).addReduceCountdownItem(); } } } if (!this.game.isStartable()) { if (!this.game.hasEnoughPlayers()) { for (Player aPlayer : players) { if (aPlayer.isOnline()) { aPlayer.sendMessage(ChatWriter.pluginMessage( ChatColor.RED + BedwarsRel ._l(aPlayer, "lobby.cancelcountdown.not_enough_players"))); } } } else if (!this.game.hasEnoughTeams()) { for (Player aPlayer : players) { if (aPlayer.isOnline()) { aPlayer.sendMessage(ChatWriter.pluginMessage( ChatColor.RED + BedwarsRel._l(aPlayer, "lobby.cancelcountdown.not_enough_teams"))); } } } this.counter = this.lobbytime; for (Player p : players) { p.setLevel(0); p.setExp(0.0F); if (p.getInventory().contains(Material.EMERALD)) { p.getInventory().remove(Material.EMERALD); } } this.game.setGameLobbyCountdown(null); this.cancel(); } if (this.counter <= 10 && this.counter > 0) { for (Player aPlayer : players) { if (aPlayer.isOnline()) { aPlayer.sendMessage(ChatWriter.pluginMessage(ChatColor.YELLOW + BedwarsRel ._l(aPlayer, "lobby.countdown", ImmutableMap.of("sec", ChatColor.RED.toString() + this.counter + ChatColor.YELLOW)))); } } Class<?> titleClass = null; Method showTitle = null; String title = ChatColor.translateAlternateColorCodes('&', BedwarsRel.getInstance().getStringConfig("titles.countdown.format", "&3{countdown}")); title = title.replace("{countdown}", String.valueOf(this.counter)); if (BedwarsRel.getInstance().getBooleanConfig("titles.countdown.enabled", true)) { try { titleClass = BedwarsRel.getInstance().getVersionRelatedClass("Title"); showTitle = titleClass.getMethod("showTitle", Player.class, String.class, double.class, double.class, double.class); } catch (Exception ex) { BedwarsRel.getInstance().getBugsnag().notify(ex); ex.printStackTrace(); } } for (Player player : players) { player.playSound(player.getLocation(), SoundMachine.get("CLICK", "UI_BUTTON_CLICK"), Float.valueOf("1.0"), Float.valueOf("1.0")); if (titleClass == null) { continue; } try { showTitle.invoke(null, player, title, 0.2, 0.6, 0.2); } catch (Exception ex) { BedwarsRel.getInstance().getBugsnag().notify(ex); ex.printStackTrace(); } } } if (this.counter == 0) { this.game.setGameLobbyCountdown(null); this.cancel(); for (Player player : players) { player.playSound(player.getLocation(), SoundMachine.get("LEVEL_UP", "ENTITY_PLAYER_LEVELUP"), Float.valueOf("1.0"), Float.valueOf("1.0")); player.setLevel(0); player.setExp(0.0F); } this.game.start(BedwarsRel.getInstance().getServer().getConsoleSender()); return; } this.counter--; } }
412
0.919645
1
0.919645
game-dev
MEDIA
0.873788
game-dev
0.958424
1
0.958424
Ayfri/Kore
3,062
kore/src/test/kotlin/io/github/ayfri/kore/features/PredicateEntityTypeSpecificTests.kt
package io.github.ayfri.kore.features import io.github.ayfri.kore.DataPack import io.github.ayfri.kore.arguments.enums.Gamemode import io.github.ayfri.kore.arguments.numbers.ranges.rangeOrInt import io.github.ayfri.kore.assertions.assertsIs import io.github.ayfri.kore.features.predicates.conditions.entityProperties import io.github.ayfri.kore.features.predicates.predicate import io.github.ayfri.kore.features.predicates.sub.entityspecific.* import io.github.ayfri.kore.generated.* fun DataPack.predicateEntityTypeSpecificTests() { predicate("fishing_hook_type_specific") { entityProperties { fishingHookTypeSpecific(inOpenWater = true) } } predicates.last() assertsIs """ { "condition": "minecraft:entity_properties", "predicate": { "type_specific": { "type": "minecraft:fishing_hook", "in_open_water": true } } } """.trimIndent() predicate("lightning_type_specific") { entityProperties { lightningTypeSpecific { blocksSetOnFire = rangeOrInt(1..5) } } } predicates.last() assertsIs """ { "condition": "minecraft:entity_properties", "predicate": { "type_specific": { "type": "minecraft:lightning", "blocks_set_on_fire": { "min": 1, "max": 5 } } } } """.trimIndent() predicate("player_type_specific") { entityProperties { playerTypeSpecific { gamemodes(Gamemode.CREATIVE) recipes { this[Recipes.BOW] = true } input { forward = true backward = false left = true right = false jump = true sneak = false sprint = true } } } } predicates.last() assertsIs """ { "condition": "minecraft:entity_properties", "predicate": { "type_specific": { "type": "minecraft:player", "gamemode": [ "creative" ], "recipes": { "minecraft:bow": true }, "input": { "forward": true, "backward": false, "left": true, "right": false, "jump": true, "sneak": false, "sprint": true } } } } """.trimIndent() predicate("raider_type_specific") { entityProperties { raiderTypeSpecific(hasRaid = true, isCaptain = false) } } predicates.last() assertsIs """ { "condition": "minecraft:entity_properties", "predicate": { "type_specific": { "type": "minecraft:raider", "has_raid": true, "is_captain": false } } } """.trimIndent() predicate("sheep_type_specific") { entityProperties { sheepTypeSpecific(sheared = true) } } predicates.last() assertsIs """ { "condition": "minecraft:entity_properties", "predicate": { "type_specific": { "type": "minecraft:sheep", "sheared": true } } } """.trimIndent() predicate("slime_type_specific") { entityProperties { slimeTypeSpecific(rangeOrInt(2)) } } predicates.last() assertsIs """ { "condition": "minecraft:entity_properties", "predicate": { "type_specific": { "type": "minecraft:slime", "size": 2 } } } """.trimIndent() }
412
0.718559
1
0.718559
game-dev
MEDIA
0.894886
game-dev
0.602142
1
0.602142
mastercomfig/tf2-patches-old
3,646
src/game/client/tf/vgui/tf_intromenu.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef TF_INTROMENU_H #define TF_INTROMENU_H #ifdef _WIN32 #pragma once #endif #include "tf_vgui_video.h" #include "basemodelpanel.h" #define MAX_CAPTION_LENGTH 256 class CVideoCaption { public: CVideoCaption() { m_pszString = NULL; m_flStartTime = 0; m_flDisplayTime = 0; m_flCaptionStart = -1; } ~CVideoCaption() { if ( m_pszString && m_pszString[0] ) { delete [] m_pszString; m_pszString = NULL; } } const char *m_pszString; // the string to display (can be a localized # string) float m_flStartTime; // the offset from the beginning of the video when we should show this caption float m_flDisplayTime; // the length of time the string should be displayed once it's shown float m_flCaptionStart; // the time when the caption is shown (so we know when to turn it off }; //----------------------------------------------------------------------------- // Purpose: displays the Intro menu //----------------------------------------------------------------------------- class CTFIntroMenu : public CIntroMenu { private: DECLARE_CLASS_SIMPLE( CTFIntroMenu, CIntroMenu ); public: CTFIntroMenu( IViewPort *pViewPort ); ~CTFIntroMenu(); virtual void ApplySchemeSettings( vgui::IScheme *pScheme ); virtual void ShowPanel( bool bShow ); virtual void OnCommand( const char *command ); virtual void OnKeyCodePressed( KeyCode code ); virtual void OnTick() OVERRIDE; virtual void OnThink() OVERRIDE; //============================================================================= // HPE_BEGIN // [msmith] Some refactoring. //============================================================================= void StartVideo(); void ShutdownVideo(); //============================================================================= // HPE_END //============================================================================= MESSAGE_FUNC( OnIntroFinished, "IntroFinished" ); private: void SetNextThink( float flActionThink, int iAction ); void Shutdown( void ); bool LoadCaptions( void ); void UpdateCaptions( void ); //============================================================================= // HPE_BEGIN // [msmith] Added support for in game videos. //============================================================================= bool PendingInGameVideo( void ); const char *GetVideoFileName( bool withExtension = true ); void UnpauseGame( void ); void PauseGame( void ); //============================================================================= // HPE_END //============================================================================= CTFVideoPanel *m_pVideo; CModelPanel *m_pModel; CExLabel *m_pCaptionLabel; #ifdef _X360 CTFFooter *m_pFooter; #else CExButton *m_pBack; CExButton *m_pOK; CExButton *m_pReplayVideo; CExButton *m_pContinue; #endif float m_flActionThink; int m_iAction; CUtlVector< CVideoCaption* > m_Captions; int m_iCurrentCaption; float m_flVideoStartTime; //============================================================================= // HPE_BEGIN // [msmith] Added support for in game videos. //============================================================================= bool m_bPlayingInGameVideo; //============================================================================= // HPE_END //============================================================================= }; #endif // TF_INTROMENU_H
412
0.75574
1
0.75574
game-dev
MEDIA
0.929264
game-dev
0.506666
1
0.506666
netease-im/camellia
2,114
camellia-redis-proxy/camellia-redis-proxy-core/src/main/java/com/netease/nim/camellia/redis/proxy/netty/CommandPackRecycler.java
package com.netease.nim.camellia.redis.proxy.netty; import com.netease.nim.camellia.redis.proxy.command.Command; import com.netease.nim.camellia.redis.proxy.conf.ProxyDynamicConf; import com.netease.nim.camellia.redis.proxy.reply.Reply; import io.netty.channel.EventLoop; import java.util.List; import java.util.concurrent.CompletableFuture; /** * Created by caojiajun on 2023/4/8 */ public class CommandPackRecycler { private final EventLoop eventLoop; private CommandPack commandPack; private static boolean recycleEnable; static { reloadConf(); ProxyDynamicConf.registerCallback(CommandPackRecycler::reloadConf); } private static void reloadConf() { recycleEnable = ProxyDynamicConf.getBoolean("command.pack.recycle.enable", true); } public CommandPackRecycler(EventLoop eventLoop) { this.eventLoop = eventLoop; } public CommandPack newInstance(List<Command> commands, List<CompletableFuture<Reply>> completableFutureList, long startTime) { if (!recycleEnable) { return new CommandPack(commands, completableFutureList, startTime); } if (eventLoop.inEventLoop()) { CommandPack pack; if (commandPack != null) { pack = commandPack; commandPack = null; pack.setCommands(commands); pack.setCompletableFutureList(completableFutureList); pack.setStartTime(startTime); } else { pack = new CommandPack(commands, completableFutureList, startTime); } return pack; } else { return new CommandPack(commands, completableFutureList, startTime); } } //only invoke this method inEventLoop public void recycle(CommandPack commandPack) { if (!recycleEnable) return; if (this.commandPack == null) { commandPack.setCommands(null); commandPack.setCompletableFutureList(null); commandPack.setStartTime(0); this.commandPack = commandPack; } } }
412
0.916643
1
0.916643
game-dev
MEDIA
0.752993
game-dev
0.892976
1
0.892976
FTBTeam/FTB-Quests
2,216
common/src/main/java/dev/ftb/mods/ftbquests/net/EditObjectMessage.java
package dev.ftb.mods.ftbquests.net; import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftblibrary.util.NetworkHelper; import dev.ftb.mods.ftbquests.FTBQuests; import dev.ftb.mods.ftbquests.api.FTBQuestsAPI; import dev.ftb.mods.ftbquests.client.ClientQuestFile; import dev.ftb.mods.ftbquests.quest.QuestObjectBase; import dev.ftb.mods.ftbquests.quest.ServerQuestFile; import dev.ftb.mods.ftbquests.util.NetUtils; import net.minecraft.Util; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; public record EditObjectMessage(long id, CompoundTag nbt) implements CustomPacketPayload { public static final Type<EditObjectMessage> TYPE = new Type<>(FTBQuestsAPI.rl("edit_object_message")); public static final StreamCodec<FriendlyByteBuf, EditObjectMessage> STREAM_CODEC = StreamCodec.composite( ByteBufCodecs.VAR_LONG, EditObjectMessage::id, ByteBufCodecs.COMPOUND_TAG, EditObjectMessage::nbt, EditObjectMessage::new ); public static EditObjectMessage forQuestObject(QuestObjectBase qo) { FTBQuests.getRecipeModHelper().refreshRecipes(qo); ClientQuestFile.INSTANCE.clearCachedData(); return new EditObjectMessage(qo.id, Util.make(new CompoundTag(), nbt1 -> qo.writeData(nbt1, ClientQuestFile.INSTANCE.holderLookup()))); } public static void sendToServer(QuestObjectBase qo) { NetworkManager.sendToServer(forQuestObject(qo)); } @Override public Type<EditObjectMessage> type() { return TYPE; } public static void handle(EditObjectMessage message, NetworkManager.PacketContext context) { context.queue(() -> { if (NetUtils.canEdit(context)) { QuestObjectBase object = ServerQuestFile.INSTANCE.getBase(message.id); if (object != null) { object.readData(message.nbt, context.registryAccess()); ServerQuestFile.INSTANCE.clearCachedData(); ServerQuestFile.INSTANCE.markDirty(); NetworkHelper.sendToAll(context.getPlayer().getServer(), new EditObjectResponseMessage(object)); object.editedFromGUIOnServer(); } } }); } }
412
0.820296
1
0.820296
game-dev
MEDIA
0.919429
game-dev,networking
0.843081
1
0.843081
KryptonMC/Krypton
4,887
server/src/main/kotlin/org/kryptonmc/krypton/command/argument/ArgumentSerializers.kt
/* * This file is part of the Krypton project, licensed under the Apache License v2.0 * * Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kryptonmc.krypton.command.argument import com.mojang.brigadier.arguments.ArgumentType import com.mojang.brigadier.arguments.BoolArgumentType import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap import net.kyori.adventure.key.Key import org.kryptonmc.krypton.command.argument.serializer.ArgumentSerializer import org.kryptonmc.krypton.command.argument.serializer.DoubleArgumentSerializer import org.kryptonmc.krypton.command.argument.serializer.EntityArgumentSerializer import org.kryptonmc.krypton.command.argument.serializer.FloatArgumentSerializer import org.kryptonmc.krypton.command.argument.serializer.IntegerArgumentSerializer import org.kryptonmc.krypton.command.argument.serializer.LongArgumentSerializer import org.kryptonmc.krypton.command.argument.serializer.SingletonArgumentSerializer import org.kryptonmc.krypton.command.argument.serializer.StringArgumentSerializer import org.kryptonmc.krypton.command.arguments.GameProfileArgument import org.kryptonmc.krypton.command.arguments.NBTArgument import org.kryptonmc.krypton.command.arguments.NBTCompoundArgument import org.kryptonmc.krypton.command.arguments.SummonEntityArgument import org.kryptonmc.krypton.command.arguments.VectorArgument import org.kryptonmc.krypton.command.arguments.item.ItemStackArgumentType import org.kryptonmc.krypton.command.arguments.item.ItemStackPredicateArgument import org.kryptonmc.krypton.network.buffer.BinaryWriter import org.kryptonmc.krypton.util.writeVarInt import java.util.concurrent.ConcurrentHashMap /** * Holds all of the built-in argument serializers for all of the argument * types that we use that need to be sent to the client. */ object ArgumentSerializers { private val BY_CLASS = ConcurrentHashMap<Class<*>, Entry<*>>() private val BY_ID = Int2ObjectOpenHashMap<Entry<*>>() @JvmStatic fun bootstrap() { // Brigadier serializers singleton(0, "brigadier:bool", BoolArgumentType.bool()) register(1, "brigadier:float", FloatArgumentSerializer) register(2, "brigadier:double", DoubleArgumentSerializer) register(3, "brigadier:integer", IntegerArgumentSerializer) register(4, "brigadier:long", LongArgumentSerializer) register(5, "brigadier:string", StringArgumentSerializer) // Built-in serializers register(6, "entity", EntityArgumentSerializer) singleton(7, "game_profile", GameProfileArgument) singleton(10, "vec3", VectorArgument.normal()) singleton(14, "item_stack", ItemStackArgumentType) singleton(15, "item_predicate", ItemStackPredicateArgument) singleton(19, "nbt_compound_tag", NBTCompoundArgument) singleton(20, "nbt_tag", NBTArgument) singleton(40, "entity_summon", SummonEntityArgument) } @JvmStatic @Suppress("UNCHECKED_CAST") fun <T : ArgumentType<*>> getByType(type: T): Entry<T>? = BY_CLASS.get(type.javaClass) as? Entry<T> @JvmStatic @Suppress("UNCHECKED_CAST") fun <T : ArgumentType<*>> getById(id: Int): Entry<T>? = BY_ID.get(id) as? Entry<T> @JvmStatic private inline fun <reified T : ArgumentType<*>> register(id: Int, name: String, serializer: ArgumentSerializer<T>) { register(id, name, T::class.java, serializer) } @JvmStatic private fun <T : ArgumentType<*>> register(id: Int, name: String, type: Class<T>, serializer: ArgumentSerializer<T>) { val entry = Entry(id, Key.key(name), type, serializer) BY_CLASS.put(type, entry) BY_ID.put(id, entry) } @JvmStatic private inline fun <reified T : ArgumentType<*>> singleton(id: Int, name: String, value: T) { register(id, name, SingletonArgumentSerializer(value)) } @JvmStatic fun <T : ArgumentType<*>> write(writer: BinaryWriter, type: T) { val entry = checkNotNull(getByType(type)) { "Argument type for node must have registered serializer!" } writer.writeVarInt(entry.id) entry.serializer.write(writer, type) } @JvmRecord data class Entry<T : ArgumentType<*>>(val id: Int, val name: Key, val clazz: Class<T>, val serializer: ArgumentSerializer<T>) }
412
0.850849
1
0.850849
game-dev
MEDIA
0.563539
game-dev
0.917545
1
0.917545
indico/indico
1,145
indico/modules/events/management/templates/delete_event.html
{% from 'confirmation_dialog.html' import confirmation_dialog %} {% set num_bookings = event.all_room_reservation_occurrence_links.count() %} {% set confirmation_message %} {% if num_bookings %} {% trans strong='<strong>'|safe, endstrong='</strong>'|safe -%} Please note that if you delete the event you will lose all the information contained in it, {{ strong }}including {{ num_bookings }} Room Booking occurrence(s){{ endstrong }} linked to it. This operation is irreversible! {%- endtrans %} {% else %} {% trans -%} Please note that if you delete the event you will lose all the information contained in it. This operation is irreversible! {%- endtrans %} {% endif %} {% endset %} {% call confirmation_dialog('danger', message=confirmation_message, ok_text=_('Delete event')) %} {% trans event_title=event.title, event_date=event.start_dt|format_date(timezone=event.tzinfo) -%} You are about to <strong>delete</strong> the whole event <strong>{{ event_title }} ({{ event_date }})</strong> {%- endtrans %} {% endcall %}
412
0.814951
1
0.814951
game-dev
MEDIA
0.470018
game-dev,web-backend
0.867448
1
0.867448
anegostudios/vsapi
18,214
Common/Inventory/ItemSlot.cs
using System; using System.Collections.Generic; using Vintagestory.API.Client; using Vintagestory.API.MathTools; #nullable disable namespace Vintagestory.API.Common { /// <summary> /// The default item slot to item stacks /// </summary> public class ItemSlot { /// <summary> /// Can be used to interecept marked dirty calls. /// </summary> public event ActionConsumable MarkedDirty; /// <summary> /// The upper holding limit of the slot itself. Standard slots are only limited by the item stacks maxstack size. /// </summary> public virtual int MaxSlotStackSize { get; set; } = 999999; protected ItemStack itemstack; protected InventoryBase inventory; /// <summary> /// Gets the inventory attached to this ItemSlot. /// </summary> public InventoryBase Inventory { get { return inventory; } } /// <summary> /// Icon name to be drawn in the slot background /// </summary> public string BackgroundIcon; public virtual bool DrawUnavailable { get; set; } /// <summary> /// If set will be used as the background color /// </summary> public string HexBackgroundColor; /// <summary> /// The ItemStack contained within the slot. /// </summary> public ItemStack Itemstack { get { return itemstack; } set { itemstack = value; } } /// <summary> /// The number of items in the stack. /// </summary> public int StackSize { get { return itemstack == null ? 0 : itemstack.StackSize; } } /// <summary> /// Whether or not the stack is empty. /// </summary> public virtual bool Empty { get { return itemstack == null; } } /// <summary> /// The storage type of this slot. /// </summary> public virtual EnumItemStorageFlags StorageType { get; set; } = EnumItemStorageFlags.General | EnumItemStorageFlags.Agriculture | EnumItemStorageFlags.Alchemy | EnumItemStorageFlags.Jewellery | EnumItemStorageFlags.Metallurgy | EnumItemStorageFlags.Outfit; /// <summary> /// Create a new instance of an item slot /// </summary> /// <param name="inventory"></param> public ItemSlot(InventoryBase inventory) { this.inventory = inventory; } /// <summary> /// Amount of space left, independent of item MaxStacksize /// </summary> public virtual int GetRemainingSlotSpace(ItemStack forItemstack) { return Math.Max(0, MaxSlotStackSize - StackSize); } /// <summary> /// Whether or not this slot can take the item from the source slot. /// </summary> /// <param name="sourceSlot"></param> /// <param name="priority"></param> /// <returns></returns> public virtual bool CanTakeFrom(ItemSlot sourceSlot, EnumMergePriority priority = EnumMergePriority.AutoMerge) { if (inventory?.PutLocked == true) return false; ItemStack sourceStack = sourceSlot.Itemstack; if (sourceStack == null) return false; bool flagsok = (sourceStack.Collectible.GetStorageFlags(sourceStack) & StorageType) > 0; return flagsok && (itemstack == null || itemstack.Collectible.GetMergableQuantity(itemstack, sourceStack, priority) > 0) && GetRemainingSlotSpace(sourceStack) > 0; } /// <summary> /// Whether or not this slot can hold the item from the source slot. /// </summary> /// <param name="sourceSlot"></param> /// <returns></returns> public virtual bool CanHold(ItemSlot sourceSlot) { if (inventory?.PutLocked == true) return false; return sourceSlot?.Itemstack?.Collectible != null && ((sourceSlot.Itemstack.Collectible.GetStorageFlags(sourceSlot.Itemstack) & StorageType) > 0) && inventory.CanContain(this, sourceSlot) ; } /// <summary> /// Whether or not this slots item can be retrieved. /// </summary> /// <returns></returns> public virtual bool CanTake() { if (inventory?.TakeLocked == true) return false; return itemstack != null; } /// <summary> /// Gets the entire contents of the stack, setting the base stack to null. /// </summary> /// <returns></returns> public virtual ItemStack TakeOutWhole() { ItemStack stack = itemstack.Clone(); itemstack.StackSize = 0; itemstack = null; OnItemSlotModified(stack); return stack; } /// <summary> /// Gets some of the contents of the stack. /// </summary> /// <param name="quantity">The amount to get from the stack.</param> /// <returns>The stack with the quantity take out (or as much as was available)</returns> public virtual ItemStack TakeOut(int quantity) { if (itemstack == null) return null; if (quantity >= itemstack.StackSize) return TakeOutWhole(); ItemStack split = itemstack.GetEmptyClone(); split.StackSize = quantity; itemstack.StackSize -= quantity; if (itemstack.StackSize <= 0) itemstack = null; return split; } /// <summary> /// Attempts to place item in this slot into the target slot. /// </summary> /// <param name="world"></param> /// <param name="sinkSlot"></param> /// <param name="quantity"></param> /// <returns>Amount of moved items</returns> public virtual int TryPutInto(IWorldAccessor world, ItemSlot sinkSlot, int quantity = 1) { ItemStackMoveOperation op = new ItemStackMoveOperation(world, EnumMouseButton.Left, 0, EnumMergePriority.AutoMerge, quantity); return TryPutInto(sinkSlot, ref op); } /// <summary> /// Returns the quantity of items that were not merged (left over in the source slot) /// </summary> /// <param name="sinkSlot"></param> /// <param name="op"></param> /// <returns>Amount of moved items</returns> public virtual int TryPutInto(ItemSlot sinkSlot, ref ItemStackMoveOperation op) { if (!sinkSlot.CanTakeFrom(this) || !CanTake() || itemstack == null) { return 0; } if (sinkSlot.inventory?.CanContain(sinkSlot, this) == false) return 0; // Fill the destination slot with as many items as we can if (sinkSlot.Itemstack == null) { int q = Math.Min(sinkSlot.GetRemainingSlotSpace(itemstack), op.RequestedQuantity); if (q > 0) { sinkSlot.Itemstack = TakeOut(q); // Has to be above the modified calls because e.g. when moving stuff into the ground slot this will eject the item // onto the ground and sinkSlot.StackSize is 0 right after op.MovedQuantity = op.MovableQuantity = Math.Min(sinkSlot.StackSize, q); sinkSlot.OnItemSlotModified(sinkSlot.Itemstack); OnItemSlotModified(sinkSlot.Itemstack); } return op.MovedQuantity; } ItemStackMergeOperation mergeop = op.ToMergeOperation(sinkSlot, this); op = mergeop; int origRequestedQuantity = op.RequestedQuantity; op.RequestedQuantity = Math.Min(sinkSlot.GetRemainingSlotSpace(itemstack), op.RequestedQuantity); sinkSlot.Itemstack.Collectible.TryMergeStacks(mergeop); if (mergeop.MovedQuantity > 0) { sinkSlot.OnItemSlotModified(sinkSlot.Itemstack); OnItemSlotModified(sinkSlot.Itemstack); } op.RequestedQuantity = origRequestedQuantity; //ensures op.NotMovedQuantity will be correct in calling code if used with slots with limited slot maxStackSize, e.g. InventorySmelting with a cooking container has slots with maxStackSize == 6 return mergeop.MovedQuantity; } /// <summary> /// Attempts to flip the ItemSlots. /// </summary> /// <param name="itemSlot"></param> /// <returns>Whether or no the flip was successful.</returns> public virtual bool TryFlipWith(ItemSlot itemSlot) { if (itemSlot.StackSize > MaxSlotStackSize) return false; bool canHoldHis = itemSlot.Empty || CanHold(itemSlot); bool canIExchange = canHoldHis && (Empty || CanTake()); bool canHoldMine = Empty || itemSlot.CanHold(this); bool canHeExchange = canHoldMine && (itemSlot.Empty || itemSlot.CanTake()); if (canIExchange && canHeExchange) { itemSlot.FlipWith(this); itemSlot.OnItemSlotModified(itemstack); OnItemSlotModified(itemSlot.itemstack); return true; } return false; } /// <summary> /// Forces a flip with the given ItemSlot /// </summary> /// <param name="withSlot"></param> protected virtual void FlipWith(ItemSlot withSlot) { if (withSlot.StackSize > MaxSlotStackSize) { if (!Empty) return; this.itemstack = withSlot.TakeOut(MaxSlotStackSize); return; } ItemStack temp = withSlot.itemstack; withSlot.itemstack = itemstack; itemstack = temp; } /// <summary> /// Called when a player has clicked on this slot. The source slot is the mouse cursor slot. This handles the logic of either taking, putting or exchanging items. /// </summary> /// <param name="sourceSlot"></param> /// <param name="op"></param> public virtual void ActivateSlot(ItemSlot sourceSlot, ref ItemStackMoveOperation op) { if (Empty && sourceSlot.Empty) return; switch (op.MouseButton) { case EnumMouseButton.Left: ActivateSlotLeftClick(sourceSlot, ref op); return; case EnumMouseButton.Middle: ActivateSlotMiddleClick(sourceSlot, ref op); return; case EnumMouseButton.Right: ActivateSlotRightClick(sourceSlot, ref op); return; case EnumMouseButton.Wheel: if (op.WheelDir > 0) { sourceSlot.TryPutInto(this, ref op); } else { TryPutInto(sourceSlot, ref op); } return; } } /// <summary> /// Activates the left click functions of the given slot. /// </summary> /// <param name="sourceSlot"></param> /// <param name="op"></param> protected virtual void ActivateSlotLeftClick(ItemSlot sourceSlot, ref ItemStackMoveOperation op) { // 1. Current slot empty: Take items if (Empty) { if (!CanHold(sourceSlot)) return; int q = Math.Min(sourceSlot.StackSize, MaxSlotStackSize); q = Math.Min(q, GetRemainingSlotSpace(sourceSlot.itemstack)); itemstack = sourceSlot.TakeOut(q); op.MovedQuantity = itemstack.StackSize; OnItemSlotModified(itemstack); return; } // 2. Current slot non empty, source slot empty: Put items if (sourceSlot.Empty) { op.RequestedQuantity = StackSize; TryPutInto(sourceSlot, ref op); return; } // 3. Both slots not empty, and they are stackable: Fill slot int maxq = itemstack.Collectible.GetMergableQuantity(itemstack, sourceSlot.itemstack, op.CurrentPriority); if (maxq > 0) { int origRequestedQuantity = op.RequestedQuantity; op.RequestedQuantity = GameMath.Min(maxq, sourceSlot.itemstack.StackSize, GetRemainingSlotSpace(sourceSlot.itemstack)); ItemStackMergeOperation mergeop = op.ToMergeOperation(this, sourceSlot); op = mergeop; itemstack.Collectible.TryMergeStacks(mergeop); sourceSlot.OnItemSlotModified(itemstack); OnItemSlotModified(itemstack); op.RequestedQuantity = origRequestedQuantity; //ensures op.NotMovedQuantity will be correct in calling code if used with slots with limited slot maxStackSize, e.g. InventorySmelting with a cooking container has slots with maxStackSize == 6 return; } // 4. Both slots not empty and not stackable: Exchange items TryFlipWith(sourceSlot); } /// <summary> /// Activates the middle click functions of the given slot. /// </summary> /// <param name="sinkSlot"></param> /// <param name="op"></param> protected virtual void ActivateSlotMiddleClick(ItemSlot sinkSlot, ref ItemStackMoveOperation op) { if (Empty) return; if (op.ActingPlayer?.WorldData?.CurrentGameMode == EnumGameMode.Creative) { sinkSlot.Itemstack = Itemstack.Clone(); op.MovedQuantity = Itemstack.StackSize; sinkSlot.OnItemSlotModified(sinkSlot.Itemstack); } } /// <summary> /// Activates the right click functions of the given slot. /// </summary> /// <param name="sourceSlot"></param> /// <param name="op"></param> protected virtual void ActivateSlotRightClick(ItemSlot sourceSlot, ref ItemStackMoveOperation op) { // 1. Current slot empty: Take 1 item if (Empty) { if (CanHold(sourceSlot)) { itemstack = (ItemStack)sourceSlot.TakeOut(1); sourceSlot.OnItemSlotModified(itemstack); OnItemSlotModified(itemstack); } return; } // 2. Current slot non empty, source slot empty: Put half items if (sourceSlot.Empty) { op.RequestedQuantity = (int)Math.Ceiling(itemstack.StackSize / 2f); TryPutInto(sourceSlot, ref op); return; } // 3. Both slots not empty, and they are stackable: Fill slot with 1 item op.RequestedQuantity = 1; sourceSlot.TryPutInto(this, ref op); if (op.MovedQuantity > 0) return; // 4. Both slots not empty and not stackable: Exchange items TryFlipWith(sourceSlot); } /// <summary> /// The event fired when the slot is modified. /// </summary> /// <param name="sinkStack"></param> public virtual void OnItemSlotModified(ItemStack sinkStack) { if (inventory != null) { inventory.DidModifyItemSlot(this, sinkStack); if (itemstack?.Collectible != null) { itemstack.Collectible.UpdateAndGetTransitionStates(inventory.Api.World, this); } } } /// <summary> /// Marks the slot as dirty which queues it up for saving and resends it to the clients. Does not sync from client to server. /// </summary> public virtual void MarkDirty() { if (MarkedDirty != null) { if (MarkedDirty.Invoke()) { return; } } if (inventory != null) { inventory.DidModifyItemSlot(this); if (itemstack?.Collectible != null) { itemstack.Collectible.UpdateAndGetTransitionStates(inventory.Api.World, this); } } } /// <summary> /// Gets the name of the itemstack- if it exists. /// </summary> /// <returns>The name of the itemStack or null.</returns> public virtual string GetStackName() { return itemstack?.GetName(); } /// <summary> /// Gets the StackDescription for the item. /// </summary> /// <param name="world">The world the item resides in.</param> /// <param name="extendedDebugInfo">Whether or not we have Extended Debug Info enabled.</param> /// <returns></returns> public virtual string GetStackDescription(IClientWorldAccessor world, bool extendedDebugInfo) { return itemstack?.GetDescription(world, this, extendedDebugInfo); } public override string ToString() { if (Empty) { return base.ToString(); } else { return base.ToString() + " (" + itemstack.ToString() + ")"; } } public virtual WeightedSlot GetBestSuitedSlot(ItemSlot sourceSlot, ItemStackMoveOperation op = null, List<ItemSlot> skipSlots = null) { return inventory.GetBestSuitedSlot(sourceSlot, op, skipSlots); } public virtual void OnBeforeRender(ItemRenderInfo renderInfo) { // The default is to do nothing, but classes can override this to do something with the renderInfo.Transform } } }
412
0.9484
1
0.9484
game-dev
MEDIA
0.869555
game-dev
0.937272
1
0.937272
mastercomfig/tf2-patches-old
43,406
src/game/client/tf/tf_hud_weaponselection.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #include "cbase.h" #include "weapon_selection.h" #include "iclientmode.h" #include "history_resource.h" #include "hud_macros.h" #include <KeyValues.h> #include <vgui/IScheme.h> #include <vgui/ISurface.h> #include <vgui/ISystem.h> #include <vgui_controls/AnimationController.h> #include <vgui_controls/Panel.h> #include <vgui_controls/Label.h> #include <vgui_controls/TextImage.h> #include <vgui_controls/EditablePanel.h> #include "vgui/ILocalize.h" #include <string.h> #include "baseobject_shared.h" #include "tf_imagepanel.h" #include "item_model_panel.h" #include "c_tf_player.h" #include "c_tf_weapon_builder.h" #include "tf_spectatorgui.h" #include "tf_gamerules.h" #include "tf_logic_halloween_2014.h" #include "inputsystem/iinputsystem.h" #ifndef WIN32 #define _cdecl #endif #define SELECTION_TIMEOUT_THRESHOLD 2.5f // Seconds #define SELECTION_FADEOUT_TIME 3.0f #define FASTSWITCH_DISPLAY_TIMEOUT 0.5f #define FASTSWITCH_FADEOUT_TIME 0.5f ConVar tf_weapon_select_demo_start_delay( "tf_weapon_select_demo_start_delay", "1.0", FCVAR_CLIENTDLL | FCVAR_ARCHIVE, "Delay after spawning to start the weapon bucket demo." ); ConVar tf_weapon_select_demo_time( "tf_weapon_select_demo_time", "0.5", FCVAR_CLIENTDLL | FCVAR_ARCHIVE, "Time to pulse each weapon bucket upon spawning as a new class. 0 to turn off." ); //----------------------------------------------------------------------------- // Purpose: tf weapon selection hud element //----------------------------------------------------------------------------- class CHudWeaponSelection : public CBaseHudWeaponSelection, public vgui::EditablePanel { DECLARE_CLASS_SIMPLE( CHudWeaponSelection, vgui::Panel ); public: CHudWeaponSelection( const char *pElementName ); virtual ~CHudWeaponSelection( void ); virtual bool ShouldDraw(); virtual void OnWeaponPickup( C_BaseCombatWeapon *pWeapon ); virtual void SwitchToLastWeapon( void ) OVERRIDE; virtual void CycleToNextWeapon( void ); virtual void CycleToPrevWeapon( void ); virtual C_BaseCombatWeapon *GetWeaponInSlot( int iSlot, int iSlotPos ); virtual void SelectWeaponSlot( int iSlot ); virtual C_BaseCombatWeapon *GetSelectedWeapon( void ); virtual void OpenSelection( void ); virtual void HideSelection( void ); virtual void Init(); virtual void LevelInit(); virtual void LevelShutdown( void ); virtual void FireGameEvent( IGameEvent *event ); virtual void Reset(void) { CBaseHudWeaponSelection::Reset(); // selection time is a little farther back so we don't show it when we spawn m_flSelectionTime = gpGlobals->curtime - ( FASTSWITCH_DISPLAY_TIMEOUT + FASTSWITCH_FADEOUT_TIME + 0.1 ); } virtual void SelectSlot( int iSlot ); void _cdecl UserCmd_Slot11( void ); void _cdecl UserCmd_Slot12( void ); protected: struct SlotLayout_t { float x, y; float wide, tall; }; void ComputeSlotLayout( SlotLayout_t *rSlot, int nActiveSlot, int nSelectionMode ); virtual void OnThink(); virtual void PerformLayout( void ); virtual void PostChildPaint(); virtual void ApplySchemeSettings(vgui::IScheme *pScheme); void DrawSelection( C_BaseCombatWeapon *pSelectedWeapon ); virtual bool IsWeaponSelectable() { if (IsInSelectionMode()) return true; return false; } private: C_BaseCombatWeapon *FindNextWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition); C_BaseCombatWeapon *FindPrevWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition); void FastWeaponSwitch( int iWeaponSlot ); void PlusTypeFastWeaponSwitch( int iWeaponSlot, bool *pbPlaySwitchSound ); int GetNumVisibleSlots(); bool ShouldDrawInternal(); virtual void SetSelectedWeapon( C_BaseCombatWeapon *pWeapon ) { m_hSelectedWeapon = pWeapon; } virtual void SetSelectedSlot( int slot ) { m_iSelectedSlot = slot; } void DrawString( wchar_t *text, int xpos, int ypos, Color col, bool bCenter = false ); void DrawWeaponTexture( C_TFPlayer *pPlayer, C_BaseCombatWeapon *pWeapon, int xpos, int ypos, float flLargeBoxWide, float flLargeBoxTall ); CPanelAnimationVar( vgui::HFont, m_hNumberFont, "NumberFont", "HudSelectionText" ); CPanelAnimationVar( vgui::HFont, m_hTextFont, "TextFont", "HudSelectionText" ); CPanelAnimationVarAliasType( float, m_flSmallBoxWide, "SmallBoxWide", "32", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flSmallBoxTall, "SmallBoxTall", "21", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flPlusStyleBoxWide, "PlusStyleBoxWide", "120", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flPlusStyleBoxTall, "PlusStyleBoxTall", "84", "proportional_float" ); CPanelAnimationVar( float, m_flPlusStyleExpandPercent, "PlusStyleExpandSelected", "0.3" ) CPanelAnimationVarAliasType( float, m_flLargeBoxWide, "LargeBoxWide", "108", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flLargeBoxTall, "LargeBoxTall", "72", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flBoxGap, "BoxGap", "12", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flRightMargin, "RightMargin", "0", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flSelectionNumberXPos, "SelectionNumberXPos", "4", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flSelectionNumberYPos, "SelectionNumberYPos", "4", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flIconXPos, "IconXPos", "16", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flIconYPos, "IconYPos", "8", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flTextYPos, "TextYPos", "54", "proportional_float" ); CPanelAnimationVarAliasType( float, m_flErrorYPos, "ErrorYPos", "60", "proportional_float" ); CPanelAnimationVar( float, m_flAlphaOverride, "Alpha", "255" ); CPanelAnimationVar( float, m_flSelectionAlphaOverride, "SelectionAlpha", "255" ); CPanelAnimationVar( Color, m_TextColor, "TextColor", "SelectionTextFg" ); CPanelAnimationVar( Color, m_NumberColor, "NumberColor", "SelectionNumberFg" ); CPanelAnimationVar( Color, m_EmptyBoxColor, "EmptyBoxColor", "SelectionEmptyBoxBg" ); CPanelAnimationVar( Color, m_BoxColor, "BoxColor", "SelectionBoxBg" ); CPanelAnimationVar( Color, m_SelectedBoxColor, "SelectedBoxClor", "SelectionSelectedBoxBg" ); CPanelAnimationVar( float, m_flWeaponPickupGrowTime, "SelectionGrowTime", "0.1" ); CPanelAnimationVar( float, m_flTextScan, "TextScan", "1.0" ); CPanelAnimationVar( int, m_iMaxSlots, "MaxSlots", "6" ); CPanelAnimationVar( bool, m_bPlaySelectionSounds, "PlaySelectSounds", "1" ); CTFImagePanel *m_pActiveWeaponBG; CItemModelPanel *m_pModelPanels[MAX_WEAPON_SLOTS]; float m_flDemoStartTime; float m_flDemoModeChangeTime; int m_iDemoModeSlot; // HUDTYPE_PLUS weapon display int m_iSelectedBoxPosition; // in HUDTYPE_PLUS, the position within a slot int m_iSelectedSlot; // in HUDTYPE_PLUS, the slot we're currently moving in CPanelAnimationVar( float, m_flHorizWeaponSelectOffsetPoint, "WeaponBoxOffset", "0" ); int m_iActiveSlot; // used to store the active slot to refresh the layout when using hud_fastswitch }; DECLARE_HUDELEMENT( CHudWeaponSelection ); DECLARE_HUD_COMMAND_NAME( CHudWeaponSelection, Slot11, "CHudWeaponSelection"); DECLARE_HUD_COMMAND_NAME( CHudWeaponSelection, Slot12, "CHudWeaponSelection"); HOOK_COMMAND( slot11, Slot11 ); HOOK_COMMAND( slot12, Slot12 ); void CHudWeaponSelection::UserCmd_Slot11(void) { SelectSlot( 11 ); } void CHudWeaponSelection::UserCmd_Slot12(void) { SelectSlot( 12 ); } using namespace vgui; //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CHudWeaponSelection::CHudWeaponSelection( const char *pElementName ) : CBaseHudWeaponSelection( pElementName ), EditablePanel( NULL, "HudWeaponSelection" ) { vgui::Panel *pParent = g_pClientMode->GetViewport(); SetParent( pParent ); SetPostChildPaintEnabled( true ); m_flDemoStartTime = -1; m_flDemoModeChangeTime = 0; m_iDemoModeSlot = -1; m_iActiveSlot = -1; ListenForGameEvent( "localplayer_changeclass" ); for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ ) { m_pModelPanels[i] = new CItemModelPanel( this, VarArgs( "modelpanel%d", i ) ); } } CHudWeaponSelection::~CHudWeaponSelection( void ) { } //----------------------------------------------------------------------------- // Purpose: sets up display for showing weapon pickup //----------------------------------------------------------------------------- void CHudWeaponSelection::OnWeaponPickup( C_BaseCombatWeapon *pWeapon ) { // add to pickup history CHudHistoryResource *pHudHR = GET_HUDELEMENT( CHudHistoryResource ); if ( pHudHR ) { pHudHR->AddToHistory( pWeapon ); } } //----------------------------------------------------------------------------- // Purpose: updates animation status //----------------------------------------------------------------------------- void CHudWeaponSelection::OnThink() { float flSelectionTimeout = SELECTION_TIMEOUT_THRESHOLD; float flSelectionFadeoutTime = SELECTION_FADEOUT_TIME; if ( hud_fastswitch.GetBool() || (::input->IsSteamControllerActive()) ) { flSelectionTimeout = FASTSWITCH_DISPLAY_TIMEOUT; flSelectionFadeoutTime = FASTSWITCH_FADEOUT_TIME; } // Time out after awhile of inactivity if ( ( gpGlobals->curtime - m_flSelectionTime ) > flSelectionTimeout ) { // close if ( gpGlobals->curtime - m_flSelectionTime > flSelectionTimeout + flSelectionFadeoutTime ) { HideSelection(); } } } //----------------------------------------------------------------------------- // Purpose: returns true if the panel should draw //----------------------------------------------------------------------------- bool CHudWeaponSelection::ShouldDraw() { bool bShouldDraw = ShouldDrawInternal(); if ( !bShouldDraw && m_pActiveWeaponBG && m_pActiveWeaponBG->IsVisible() ) { m_pActiveWeaponBG->SetVisible( false ); } C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( pPlayer && pPlayer->m_Shared.InCond( TF_COND_HALLOWEEN_GHOST_MODE ) ) { bShouldDraw = false; } if ( TFGameRules() && TFGameRules()->ShowMatchSummary() ) { bShouldDraw = false; } if ( CTFMinigameLogic::GetMinigameLogic() && CTFMinigameLogic::GetMinigameLogic()->GetActiveMinigame() ) { bShouldDraw = false; } return bShouldDraw; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CHudWeaponSelection::ShouldDrawInternal() { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) { if ( IsInSelectionMode() ) { HideSelection(); } return false; } // Make sure the player's allowed to switch weapons if ( pPlayer->IsAllowedToSwitchWeapons() == false ) return false; if ( pPlayer->IsAlive() == false ) return false; // we only show demo mode in hud_fastswitch 0 if ( hud_fastswitch.GetInt() == 0 && !::input->IsSteamControllerActive() && ( m_iDemoModeSlot >= 0 || m_flDemoStartTime > 0 ) ) { return true; } bool bret = CBaseHudWeaponSelection::ShouldDraw(); if ( !bret ) return false; // draw weapon selection a little longer if in fastswitch so we can see what we've selected if ( (hud_fastswitch.GetBool() || ::input->IsSteamControllerActive()) && ( gpGlobals->curtime - m_flSelectionTime ) < (FASTSWITCH_DISPLAY_TIMEOUT + FASTSWITCH_FADEOUT_TIME) ) return true; return ( m_bSelectionVisible ) ? true : false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudWeaponSelection::Init() { CHudElement::Init(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudWeaponSelection::LevelInit() { CHudElement::LevelInit(); m_iMaxSlots = clamp( m_iMaxSlots, 0, MAX_WEAPON_SLOTS ); for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ ) { m_pModelPanels[i]->SetVisible( false ); } InvalidateLayout( false, true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudWeaponSelection::LevelShutdown( void ) { CHudElement::LevelShutdown(); // Clear out our weaponry on level change for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ ) { if ( m_pModelPanels[i] ) { m_pModelPanels[i]->SetItem( NULL ); } } } //------------------------------------------------------------------------- // Purpose: Calculates how many weapons slots need to be displayed //------------------------------------------------------------------------- int CHudWeaponSelection::GetNumVisibleSlots() { int nCount = 0; // iterate over all the weapon slots for ( int i = 0; i < m_iMaxSlots; i++ ) { if ( GetFirstPos( i ) ) { nCount++; } } return nCount; } //----------------------------------------------------------------------------- // Purpose: Figure out where to put the item model panels for this weapon // selection slot layout //----------------------------------------------------------------------------- void CHudWeaponSelection::ComputeSlotLayout( SlotLayout_t *rSlot, int nActiveSlot, int nSelectionMode ) { int nNumSlots = GetNumVisibleSlots(); if ( nNumSlots <= 0 ) return; switch( nSelectionMode ) { case HUDTYPE_CAROUSEL: case HUDTYPE_BUCKETS: case HUDTYPE_FASTSWITCH: { // calculate where to start drawing int nTotalHeight = ( nNumSlots - 1 ) * ( m_flSmallBoxTall + m_flBoxGap ) + m_flLargeBoxTall; int xStartPos = GetWide() - m_flBoxGap - m_flRightMargin; int ypos = ( GetTall() - nTotalHeight ) / 2; // iterate over all the weapon slots for ( int i = 0; i < m_iMaxSlots; i++ ) { if ( i == nActiveSlot ) { rSlot[i].wide = m_flLargeBoxWide; rSlot[i].tall = m_flLargeBoxTall; } else { rSlot[i].wide = m_flSmallBoxWide; rSlot[i].tall = m_flSmallBoxTall; } rSlot[i].x = xStartPos - ( rSlot[i].wide + m_flBoxGap ); rSlot[i].y = ypos; ypos += ( rSlot[i].tall + m_flBoxGap ); } } break; case HUDTYPE_PLUS: { // bucket style int screenCenterX = GetWide() / 2; int screenCenterY = GetTall() / 2; // Height isn't quite screen height, so adjust for center alignement // Modifiers for the four directions. Used to change the x and y offsets // of each box based on which bucket we're drawing. Bucket directions are // 0 = UP, 1 = RIGHT, 2 = DOWN, 3 = LEFT int xModifiers[] = { 0, 1, 0, -1, -1, 1 }; int yModifiers[] = { -1, 0, 1, 0, 1, 1 }; int boxWide = m_flPlusStyleBoxWide; int boxTall = m_flPlusStyleBoxTall; int boxWideSelected = m_flPlusStyleBoxWide * ( 1.f + m_flPlusStyleExpandPercent ); int boxTallSelected = m_flPlusStyleBoxTall * ( 1.f + m_flPlusStyleExpandPercent ); // Draw the four buckets for ( int i = 0; i < m_iMaxSlots; ++i ) { if( i == nActiveSlot ) { rSlot[i].wide = boxWideSelected; rSlot[i].tall = boxTallSelected; } else { rSlot[i].wide = boxWide; rSlot[i].tall = boxTall; } // Set the top left corner so the first box would be centered in the screen. int xPos = screenCenterX -( rSlot[i].wide / 2 ); int yPos = screenCenterY -( rSlot[i].tall / 2 ); // Offset the box position rSlot[ i ].x = xPos + ( rSlot[i].wide + 5 ) * xModifiers[ i ]; rSlot[ i ].y = yPos + ( rSlot[i].tall + 5 ) * yModifiers[ i ]; } } break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudWeaponSelection::PerformLayout( void ) { BaseClass::PerformLayout(); C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( !pPlayer ) return; int nNumSlots = GetNumVisibleSlots(); if ( nNumSlots <= 0 ) return; // find and display our current selection C_BaseCombatWeapon *pSelectedWeapon = NULL; int fastswitch = hud_fastswitch.GetInt(); if ( ::input->IsSteamControllerActive() ) { fastswitch = HUDTYPE_FASTSWITCH; } switch ( fastswitch ) { case HUDTYPE_FASTSWITCH: pSelectedWeapon = pPlayer->GetActiveWeapon(); break; default: pSelectedWeapon = GetSelectedWeapon(); break; } if ( !pSelectedWeapon ) return; // calculate where to start drawing int iActiveSlot = (pSelectedWeapon ? pSelectedWeapon->GetSlot() : -1); SlotLayout_t rSlot[ MAX_WEAPON_SLOTS ]; ComputeSlotLayout( rSlot, iActiveSlot, fastswitch ); // iterate over all the weapon slots for ( int i = 0; i < m_iMaxSlots; i++ ) { m_pModelPanels[i]->SetVisible( false ); if ( i == iActiveSlot ) { for ( int slotpos = 0; slotpos < MAX_WEAPON_POSITIONS; slotpos++ ) { C_BaseCombatWeapon *pWeapon = GetWeaponInSlot(i, slotpos); if ( !pWeapon ) continue; if ( !pWeapon->VisibleInWeaponSelection() ) continue; m_pModelPanels[i]->SetItem( pWeapon->GetAttributeContainer()->GetItem() ); m_pModelPanels[i]->SetSize( rSlot[i].wide, rSlot[ i ].tall ); vgui::IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() ); if ( pPlayer->GetTeamNumber() == TF_TEAM_BLUE ) { m_pModelPanels[i]->SetBorder( pScheme->GetBorder("TFFatLineBorderBlueBG") ); } else { m_pModelPanels[i]->SetBorder( pScheme->GetBorder("TFFatLineBorderRedBG") ); } m_pModelPanels[i]->SetPos( rSlot[i].x, rSlot[ i ].y ); m_pModelPanels[i]->SetVisible( true ); } } else { // check to see if there is a weapons in this bucket if ( GetFirstPos( i ) ) { C_BaseCombatWeapon *pWeapon = GetFirstPos( i ); if ( !pWeapon ) continue; m_pModelPanels[i]->SetItem( pWeapon->GetAttributeContainer()->GetItem() ); m_pModelPanels[i]->SetSize( rSlot[i].wide, rSlot[ i ].tall ); vgui::IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() ); m_pModelPanels[i]->SetBorder( pScheme->GetBorder("TFFatLineBorder") ); m_pModelPanels[i]->SetVisible( true ); m_pModelPanels[i]->SetPos( rSlot[i].x, rSlot[ i ].y ); } } } } //------------------------------------------------------------------------- // Purpose: draws the selection area //------------------------------------------------------------------------- void CHudWeaponSelection::PostChildPaint() { C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( !pPlayer ) return; int fastswitch = hud_fastswitch.GetInt(); if ( ::input->IsSteamControllerActive() ) { fastswitch = HUDTYPE_FASTSWITCH; } if ( fastswitch == 0 ) { // See if we should start the bucket demo if ( m_flDemoStartTime > 0 && m_flDemoStartTime < gpGlobals->curtime ) { float flDemoTime = tf_weapon_select_demo_time.GetFloat(); if ( flDemoTime > 0 ) { m_iDemoModeSlot = 0; m_flDemoModeChangeTime = gpGlobals->curtime + flDemoTime; gHUD.LockRenderGroup( gHUD.LookupRenderGroupIndexByName( "weapon_selection" ) ); } m_flDemoStartTime = -1; m_iSelectedSlot = m_iDemoModeSlot; InvalidateLayout(); } // scroll through the slots for demo mode if ( m_iDemoModeSlot >= 0 && m_flDemoModeChangeTime < gpGlobals->curtime ) { // Keep iterating until we find a slot that has a weapon in it while ( !GetFirstPos( ++m_iDemoModeSlot ) && m_iDemoModeSlot < m_iMaxSlots ) { // blank } m_flDemoModeChangeTime = gpGlobals->curtime + tf_weapon_select_demo_time.GetFloat(); InvalidateLayout(); } if ( m_iDemoModeSlot >= m_iMaxSlots ) { m_iDemoModeSlot = -1; gHUD.UnlockRenderGroup( gHUD.LookupRenderGroupIndexByName( "weapon_selection" ) ); } } // find and display our current selection C_BaseCombatWeapon *pSelectedWeapon = NULL; switch ( fastswitch ) { case HUDTYPE_FASTSWITCH: pSelectedWeapon = pPlayer->GetActiveWeapon(); break; default: pSelectedWeapon = GetSelectedWeapon(); break; } if ( !pSelectedWeapon ) return; if ( fastswitch == 0 ) { if ( m_iDemoModeSlot > -1 ) { pSelectedWeapon = GetWeaponInSlot( m_iDemoModeSlot, 0 ); m_iSelectedSlot = m_iDemoModeSlot; m_iSelectedBoxPosition = 0; } } if ( m_pActiveWeaponBG ) { m_pActiveWeaponBG->SetVisible( fastswitch != HUDTYPE_PLUS && pSelectedWeapon != NULL ); } int nNumSlots = GetNumVisibleSlots(); if ( nNumSlots <= 0 ) return; DrawSelection( pSelectedWeapon ); } //----------------------------------------------------------------------------- // Purpose: Draws the vertical style weapon selection buckets, for PC/mousewheel controls //----------------------------------------------------------------------------- void CHudWeaponSelection::DrawSelection( C_BaseCombatWeapon *pSelectedWeapon ) { // if we're not supposed to draw the selection, the don't draw the selection if( !m_bSelectionVisible ) return; C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( !pPlayer ) return; int nNumSlots = GetNumVisibleSlots(); if ( nNumSlots <= 0 ) return; // calculate where to start drawing int iActiveSlot = (pSelectedWeapon ? pSelectedWeapon->GetSlot() : -1); int nFastswitchMode = hud_fastswitch.GetInt(); if ( ::input->IsSteamControllerActive() ) { nFastswitchMode = HUDTYPE_FASTSWITCH; } if ( nFastswitchMode == HUDTYPE_FASTSWITCH ) { if ( m_iActiveSlot != iActiveSlot ) { m_iActiveSlot = iActiveSlot; InvalidateLayout( true ); } } // draw the bucket set // iterate over all the weapon slots for ( int i = 0; i < m_iMaxSlots; i++ ) { int xpos, ypos; m_pModelPanels[i]->GetPos( xpos, ypos ); int wide, tall; m_pModelPanels[i]->GetSize( wide, tall ); if ( i == iActiveSlot ) { bool bFirstItem = true; for ( int slotpos = 0; slotpos < MAX_WEAPON_POSITIONS; slotpos++ ) { C_BaseCombatWeapon *pWeapon = GetWeaponInSlot(i, slotpos); if ( !pWeapon ) continue; if ( !pWeapon->VisibleInWeaponSelection() ) continue; if ( !pWeapon->CanBeSelected() ) { int msgX = xpos + ( m_flLargeBoxWide * 0.5 ); int msgY = ypos + (int)m_flErrorYPos; Color ammoColor = Color( 255, 0, 0, 255 ); wchar_t *pText = g_pVGuiLocalize->Find( "#TF_OUT_OF_AMMO" ); DrawString( pText, msgX, msgY, ammoColor, true ); } if ( pWeapon == pSelectedWeapon || ( m_iDemoModeSlot == i ) ) { // draw the number int shortcut = bFirstItem ? i + 1 : -1; if ( IsPC() && shortcut >= 0 && nFastswitchMode != HUDTYPE_PLUS ) { Color numberColor = m_NumberColor; numberColor[3] *= m_flSelectionAlphaOverride / 255.0f; surface()->DrawSetTextColor(numberColor); surface()->DrawSetTextFont(m_hNumberFont); wchar_t wch = '0' + shortcut; surface()->DrawSetTextPos( xpos + wide - XRES(5) - m_flSelectionNumberXPos, ypos + YRES(5) + m_flSelectionNumberYPos ); surface()->DrawUnicodeChar(wch); } } bFirstItem = false; } } else { // check to see if there is a weapons in this bucket if ( GetFirstPos( i ) ) { C_BaseCombatWeapon *pWeapon = GetFirstPos( i ); if ( !pWeapon ) continue; // draw the number if ( IsPC() && nFastswitchMode != HUDTYPE_PLUS ) { int x = xpos + XRES(5); int y = ypos + YRES(5); Color numberColor = m_NumberColor; numberColor[3] *= m_flAlphaOverride / 255.0f; surface()->DrawSetTextColor(numberColor); surface()->DrawSetTextFont(m_hNumberFont); wchar_t wch = '0' + i + 1; surface()->DrawSetTextPos(x + m_flSmallBoxWide - XRES(10) - m_flSelectionNumberXPos, y + m_flSelectionNumberYPos); surface()->DrawUnicodeChar(wch); } } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudWeaponSelection::DrawWeaponTexture( C_TFPlayer *pPlayer, C_BaseCombatWeapon *pWeapon, int xpos, int ypos, float flLargeBoxWide, float flLargeBoxTall ) { // draw icon const CHudTexture *pTexture = pWeapon->GetSpriteInactive(); // red team if ( pPlayer ) { if ( pPlayer->GetTeamNumber() == TF_TEAM_BLUE ) { pTexture = pWeapon->GetSpriteActive(); } } if ( pTexture ) { Color col( 255, 255, 255, 255 ); pTexture->DrawSelf( xpos, ypos, flLargeBoxWide, flLargeBoxTall, col ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudWeaponSelection::DrawString( wchar_t *text, int xpos, int ypos, Color col, bool bCenter ) { surface()->DrawSetTextColor( col ); surface()->DrawSetTextFont( m_hTextFont ); // count the position int slen = 0, charCount = 0, maxslen = 0; { for (wchar_t *pch = text; *pch != 0; pch++) { if (*pch == '\n') { // newline character, drop to the next line if (slen > maxslen) { maxslen = slen; } slen = 0; } else if (*pch == '\r') { // do nothing } else { slen += surface()->GetCharacterWidth( m_hTextFont, *pch ); charCount++; } } } if (slen > maxslen) { maxslen = slen; } int x = xpos; if ( bCenter ) { x = xpos - slen * 0.5; } surface()->DrawSetTextPos( x, ypos ); // adjust the charCount by the scan amount charCount *= m_flTextScan; for (wchar_t *pch = text; charCount > 0; pch++) { if (*pch == '\n') { // newline character, move to the next line surface()->DrawSetTextPos( x + ((m_flLargeBoxWide - slen) / 2), ypos + (surface()->GetFontTall(m_hTextFont) * 1.1f)); } else if (*pch == '\r') { // do nothing } else { surface()->DrawUnicodeChar(*pch); charCount--; } } } //----------------------------------------------------------------------------- // Purpose: hud scheme settings //----------------------------------------------------------------------------- void CHudWeaponSelection::ApplySchemeSettings(vgui::IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); SetPaintBackgroundEnabled(false); // set our size int screenWide, screenTall; int x, y; GetPos(x, y); GetHudSize(screenWide, screenTall); SetBounds(0, 0, screenWide, screenTall); // load control settings... LoadControlSettings( "resource/UI/HudWeaponSelection.res" ); m_pActiveWeaponBG = dynamic_cast<CTFImagePanel*>( FindChildByName("ActiveWeapon") ); if ( m_pActiveWeaponBG ) { m_pActiveWeaponBG->SetVisible( false ); } } //----------------------------------------------------------------------------- // Purpose: Opens weapon selection control //----------------------------------------------------------------------------- void CHudWeaponSelection::OpenSelection( void ) { Assert(!IsInSelectionMode()); InvalidateLayout(); CBaseHudWeaponSelection::OpenSelection(); g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("OpenWeaponSelectionMenu"); m_iSelectedBoxPosition = 0; m_iSelectedSlot = -1; } //----------------------------------------------------------------------------- // Purpose: Closes weapon selection control immediately //----------------------------------------------------------------------------- void CHudWeaponSelection::HideSelection( void ) { for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ ) { if ( m_pModelPanels[i] ) { m_pModelPanels[i]->SetVisible( false ); } } m_flSelectionTime = 0; CBaseHudWeaponSelection::HideSelection(); g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("CloseWeaponSelectionMenu"); } //----------------------------------------------------------------------------- // Purpose: Returns the next available weapon item in the weapon selection //----------------------------------------------------------------------------- C_BaseCombatWeapon *CHudWeaponSelection::FindNextWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition) { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return NULL; C_BaseCombatWeapon *pNextWeapon = NULL; // search all the weapons looking for the closest next int iLowestNextSlot = MAX_WEAPON_SLOTS; int iLowestNextPosition = MAX_WEAPON_POSITIONS; for ( int i = 0; i < MAX_WEAPONS; i++ ) { C_BaseCombatWeapon *pWeapon = pPlayer->GetWeapon(i); if ( !pWeapon ) continue; if ( pWeapon->VisibleInWeaponSelection() ) { int weaponSlot = pWeapon->GetSlot(), weaponPosition = pWeapon->GetPosition(); // see if this weapon is further ahead in the selection list if ( weaponSlot > iCurrentSlot || (weaponSlot == iCurrentSlot && weaponPosition > iCurrentPosition) ) { // see if this weapon is closer than the current lowest if ( weaponSlot < iLowestNextSlot || (weaponSlot == iLowestNextSlot && weaponPosition < iLowestNextPosition) ) { iLowestNextSlot = weaponSlot; iLowestNextPosition = weaponPosition; pNextWeapon = pWeapon; } } } } return pNextWeapon; } //----------------------------------------------------------------------------- // Purpose: Returns the prior available weapon item in the weapon selection //----------------------------------------------------------------------------- C_BaseCombatWeapon *CHudWeaponSelection::FindPrevWeaponInWeaponSelection(int iCurrentSlot, int iCurrentPosition) { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return NULL; C_BaseCombatWeapon *pPrevWeapon = NULL; // search all the weapons looking for the closest next int iLowestPrevSlot = -1; int iLowestPrevPosition = -1; for ( int i = 0; i < MAX_WEAPONS; i++ ) { C_BaseCombatWeapon *pWeapon = pPlayer->GetWeapon(i); if ( !pWeapon ) continue; if ( pWeapon->VisibleInWeaponSelection() ) { int weaponSlot = pWeapon->GetSlot(), weaponPosition = pWeapon->GetPosition(); // see if this weapon is further ahead in the selection list if ( weaponSlot < iCurrentSlot || (weaponSlot == iCurrentSlot && weaponPosition < iCurrentPosition) ) { // see if this weapon is closer than the current lowest if ( weaponSlot > iLowestPrevSlot || (weaponSlot == iLowestPrevSlot && weaponPosition > iLowestPrevPosition) ) { iLowestPrevSlot = weaponSlot; iLowestPrevPosition = weaponPosition; pPrevWeapon = pWeapon; } } } } return pPrevWeapon; } //----------------------------------------------------------------------------- // Purpose: Moves the selection to the next item in the menu //----------------------------------------------------------------------------- void CHudWeaponSelection::CycleToNextWeapon( void ) { // Get the local player. C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return; if ( pPlayer->IsAlive() == false ) return; // PASSTIME don't CycleToNextWeapon if it's not allowed if ( !pPlayer->IsAllowedToSwitchWeapons() ) return; C_BaseCombatWeapon *pNextWeapon = NULL; if ( IsInSelectionMode() ) { // find the next selection spot C_BaseCombatWeapon *pWeapon = GetSelectedWeapon(); if ( !pWeapon ) return; pNextWeapon = FindNextWeaponInWeaponSelection( pWeapon->GetSlot(), pWeapon->GetPosition() ); } else { // open selection at the current place pNextWeapon = pPlayer->GetActiveWeapon(); if ( pNextWeapon ) { pNextWeapon = FindNextWeaponInWeaponSelection( pNextWeapon->GetSlot(), pNextWeapon->GetPosition() ); } } if ( !pNextWeapon ) { // wrap around back to start pNextWeapon = FindNextWeaponInWeaponSelection(-1, -1); } if ( pNextWeapon ) { SetSelectedWeapon( pNextWeapon ); if ( !IsInSelectionMode() ) { OpenSelection(); } InvalidateLayout(); // cancel demo mode m_iDemoModeSlot = -1; m_flDemoStartTime = -1; // Play the "cycle to next weapon" sound if( m_bPlaySelectionSounds ) pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" ); } } //----------------------------------------------------------------------------- // Purpose: Moves the selection to the previous item in the menu //----------------------------------------------------------------------------- void CHudWeaponSelection::CycleToPrevWeapon( void ) { // Get the local player. C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return; if ( pPlayer->IsAlive() == false ) return; // PASSTIME don't CycleToNextWeapon if it's not allowed if ( !pPlayer->IsAllowedToSwitchWeapons() ) return; C_BaseCombatWeapon *pNextWeapon = NULL; if ( IsInSelectionMode() ) { // find the next selection spot C_BaseCombatWeapon *pWeapon = GetSelectedWeapon(); if ( !pWeapon ) return; pNextWeapon = FindPrevWeaponInWeaponSelection( pWeapon->GetSlot(), pWeapon->GetPosition() ); } else { // open selection at the current place pNextWeapon = pPlayer->GetActiveWeapon(); if ( pNextWeapon ) { pNextWeapon = FindPrevWeaponInWeaponSelection( pNextWeapon->GetSlot(), pNextWeapon->GetPosition() ); } } if ( !pNextWeapon ) { // wrap around back to end of weapon list pNextWeapon = FindPrevWeaponInWeaponSelection(MAX_WEAPON_SLOTS, MAX_WEAPON_POSITIONS); } if ( pNextWeapon ) { SetSelectedWeapon( pNextWeapon ); if ( !IsInSelectionMode() ) { OpenSelection(); } InvalidateLayout(); // cancel demo mode m_iDemoModeSlot = -1; m_flDemoStartTime = -1; // Play the "cycle to next weapon" sound if( m_bPlaySelectionSounds ) pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" ); } } //----------------------------------------------------------------------------- // Purpose: returns the weapon in the specified slot //----------------------------------------------------------------------------- C_BaseCombatWeapon *CHudWeaponSelection::GetWeaponInSlot( int iSlot, int iSlotPos ) { C_BasePlayer *player = C_BasePlayer::GetLocalPlayer(); if ( !player ) return NULL; for ( int i = 0; i < MAX_WEAPONS; i++ ) { C_BaseCombatWeapon *pWeapon = player->GetWeapon(i); if ( pWeapon == NULL ) continue; if ( pWeapon->GetSlot() == iSlot && pWeapon->GetPosition() == iSlotPos ) return pWeapon; } return NULL; } C_BaseCombatWeapon *CHudWeaponSelection::GetSelectedWeapon( void ) { if ( hud_fastswitch.GetInt() == 0 && !::input->IsSteamControllerActive() && m_iDemoModeSlot >= 0 ) { C_BaseCombatWeapon *pWeapon = GetFirstPos( m_iDemoModeSlot ); return pWeapon; } else { return m_hSelectedWeapon; } } void CHudWeaponSelection::FireGameEvent( IGameEvent *event ) { const char * type = event->GetName(); if ( Q_strcmp(type, "localplayer_changeclass") == 0 ) { for ( int i = 0; i < MAX_WEAPON_SLOTS; i++ ) { if ( m_pModelPanels[i] ) { m_pModelPanels[i]->SetVisible( false ); } } int nUpdateType = event->GetInt( "updateType" ); bool bIsCreationUpdate = ( nUpdateType == DATA_UPDATE_CREATED ); // Don't demo selection in minmode ConVarRef cl_hud_minmode( "cl_hud_minmode", true ); if ( !cl_hud_minmode.IsValid() || cl_hud_minmode.GetBool() == false ) { if ( !bIsCreationUpdate ) { m_flDemoStartTime = gpGlobals->curtime + tf_weapon_select_demo_start_delay.GetFloat(); } } } else { CHudElement::FireGameEvent( event ); } } //----------------------------------------------------------------------------- // Purpose: Opens the next weapon in the slot //----------------------------------------------------------------------------- void CHudWeaponSelection::FastWeaponSwitch( int iWeaponSlot ) { // get the slot the player's weapon is in C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return; // see where we should start selection int iPosition = -1; C_BaseCombatWeapon *pActiveWeapon = pPlayer->GetActiveWeapon(); if ( pActiveWeapon && pActiveWeapon->GetSlot() == iWeaponSlot ) { // start after this weapon iPosition = pActiveWeapon->GetPosition(); } C_BaseCombatWeapon *pNextWeapon = NULL; // search for the weapon after the current one pNextWeapon = FindNextWeaponInWeaponSelection(iWeaponSlot, iPosition); // make sure it's in the same bucket if ( !pNextWeapon || pNextWeapon->GetSlot() != iWeaponSlot ) { // just look for any weapon in this slot pNextWeapon = FindNextWeaponInWeaponSelection(iWeaponSlot, -1); } // see if we found a weapon that's different from the current and in the selected slot if ( pNextWeapon && pNextWeapon != pActiveWeapon && pNextWeapon->GetSlot() == iWeaponSlot ) { // select the new weapon ::input->MakeWeaponSelection( pNextWeapon ); } else if ( pNextWeapon != pActiveWeapon ) { // error sound pPlayer->EmitSound( "Player.DenyWeaponSelection" ); } // kill any fastswitch display m_flSelectionTime = 0.0f; } //----------------------------------------------------------------------------- // Purpose: Opens the next weapon in the slot //----------------------------------------------------------------------------- void CHudWeaponSelection::PlusTypeFastWeaponSwitch( int iWeaponSlot, bool *pbPlaySwitchSound ) { // get the slot the player's weapon is in C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return; int newSlot = m_iSelectedSlot; // Changing slot number does not necessarily mean we need to change the slot - the player could be // scrolling through the same slot but in the opposite direction. Slot pairs are 0,2 and 1,3 - so // compare the 0 bits to see if we're within a pair. Otherwise, reset the box to the zero position. if ( -1 == m_iSelectedSlot || ( ( m_iSelectedSlot ^ iWeaponSlot ) & 1 ) ) { // Changing vertical/horizontal direction. Reset the selected box position to zero. m_iSelectedBoxPosition = 0; m_iSelectedSlot = iWeaponSlot; } else { // Still in the same horizontal/vertical direction. Determine which way we're moving in the slot. int increment = 1; if ( m_iSelectedSlot != iWeaponSlot ) { // Decrementing within the slot. If we're at the zero position in this slot, // jump to the zero position of the opposite slot. This also counts as our increment. increment = -1; if ( 0 == m_iSelectedBoxPosition ) { newSlot = ( m_iSelectedSlot + 2 ) % 4; increment = 0; } } // Find out of the box position is at the end of the slot int lastSlotPos = -1; for ( int slotPos = 0; slotPos < MAX_WEAPON_POSITIONS; ++slotPos ) { C_BaseCombatWeapon *pWeapon = GetWeaponInSlot( newSlot, slotPos ); if ( pWeapon ) { lastSlotPos = slotPos; } } // Increment/Decrement the selected box position if ( m_iSelectedBoxPosition + increment <= lastSlotPos ) { m_iSelectedBoxPosition += increment; m_iSelectedSlot = newSlot; } else { // error sound pPlayer->EmitSound( "Player.DenyWeaponSelection" ); *pbPlaySwitchSound = false; return; } } // Select the weapon in this position bool bWeaponSelected = false; C_BaseCombatWeapon *pActiveWeapon = pPlayer->GetActiveWeapon(); C_BaseCombatWeapon *pWeapon = GetWeaponInSlot( m_iSelectedSlot, m_iSelectedBoxPosition ); if ( pWeapon && CanBeSelectedInHUD( pWeapon ) ) { if ( pWeapon != pActiveWeapon ) { // Select the new weapon ::input->MakeWeaponSelection( pWeapon ); SetSelectedWeapon( pWeapon ); bWeaponSelected = true; } } if ( !bWeaponSelected ) { // Still need to set this to make hud display appear SetSelectedWeapon( pPlayer->GetActiveWeapon() ); } } //----------------------------------------------------------------------------- // Purpose: Moves selection to the specified slot //----------------------------------------------------------------------------- void CHudWeaponSelection::SelectWeaponSlot( int iSlot ) { // iSlot is one higher than it should be, since it's the number key, not the 0-based index into the weapons --iSlot; // Get the local player. C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return; // Don't try and read past our possible number of slots if ( iSlot >= MAX_WEAPON_SLOTS ) return; // Make sure the player's allowed to switch weapons if ( pPlayer->IsAllowedToSwitchWeapons() == false ) return; bool bPlaySwitchSound = true; int nFastswitchMode = hud_fastswitch.GetInt(); if ( ::input->IsSteamControllerActive() ) { nFastswitchMode = HUDTYPE_FASTSWITCH; } switch( nFastswitchMode ) { case HUDTYPE_FASTSWITCH: { FastWeaponSwitch( iSlot ); return; } case HUDTYPE_PLUS: PlusTypeFastWeaponSwitch( iSlot, &bPlaySwitchSound ); // ------------------------------------------------------ // FALLTHROUGH! Plus and buckets both use the item model // panels so fix them up in both cases. // ------------------------------------------------------ case HUDTYPE_BUCKETS: { int slotPos = 0; C_BaseCombatWeapon *pActiveWeapon = GetSelectedWeapon(); // start later in the list if ( IsInSelectionMode() && pActiveWeapon && pActiveWeapon->GetSlot() == iSlot ) { slotPos = pActiveWeapon->GetPosition() + 1; } // find the weapon in this slot pActiveWeapon = GetNextActivePos( iSlot, slotPos ); if ( !pActiveWeapon ) { pActiveWeapon = GetNextActivePos( iSlot, 0 ); } if ( pActiveWeapon != NULL ) { if ( !IsInSelectionMode() ) { // open the weapon selection OpenSelection(); } InvalidateLayout(); // Mark the change SetSelectedWeapon( pActiveWeapon ); m_iDemoModeSlot = -1; m_flDemoStartTime = -1; } } break; default: break; } if( m_bPlaySelectionSounds && bPlaySwitchSound ) pPlayer->EmitSound( "Player.WeaponSelectionMoveSlot" ); } //----------------------------------------------------------------------------- // Purpose: Menu Selection Code //----------------------------------------------------------------------------- void CHudWeaponSelection::SelectSlot( int iSlot ) { // A menu may be overriding weapon selection commands if ( HandleHudMenuInput( iSlot ) ) { return; } // If we're in observer mode, see if the spectator GUI wants to use it C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( pPlayer && pPlayer->IsObserver() ) { CTFSpectatorGUI *pPanel = (CTFSpectatorGUI*)gViewPortInterface->FindPanelByName( PANEL_SPECGUI ); if ( pPanel ) { pPanel->SelectSpec( iSlot ); } return; } // If we're not allowed to draw, ignore weapon selections if ( !CHudElement::ShouldDraw() ) { return; } // iSlot is one higher than it should be, since it's the number key, not the 0-based index into the weapons if ( !IsInSelectionMode() && ( iSlot - 1 >= MAX_WEAPON_SLOTS ) ) { OpenSelection(); } UpdateSelectionTime(); SelectWeaponSlot( iSlot ); } //----------------------------------------------------------------------------- // Purpose: Menu Selection Code //----------------------------------------------------------------------------- void CHudWeaponSelection::SwitchToLastWeapon() { C_TFPlayer *pTFPlayer = ToTFPlayer( C_BasePlayer::GetLocalPlayer() ); if ( !pTFPlayer ) return; if (TFGameRules() && TFGameRules()->IsPasstimeMode() && pTFPlayer->m_Shared.HasPasstimeBall() ) return; CBaseHudWeaponSelection::SwitchToLastWeapon(); }
412
0.963467
1
0.963467
game-dev
MEDIA
0.982198
game-dev
0.526957
1
0.526957
henkelmax/simple-voice-chat
1,873
common-client/src/main/java/de/maxhenkel/voicechat/voice/client/ChatUtils.java
package de.maxhenkel.voicechat.voice.client; import de.maxhenkel.voicechat.intercompatibility.CommonCompatibilityManager; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.ComponentUtils; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.MutableComponent; import javax.annotation.Nullable; public class ChatUtils { public static void sendModErrorMessage(String translationKey, @Nullable String errorMessage) { MutableComponent error = createModMessage(Component.translatable(translationKey).withStyle(ChatFormatting.RED)).withStyle(style -> { if (errorMessage != null) { return style.withHoverEvent(new HoverEvent.ShowText(Component.literal(errorMessage).withStyle(ChatFormatting.RED))); } return style; }); sendPlayerMessage(error); } public static void sendModErrorMessage(String translationKey, @Nullable Exception e) { sendModErrorMessage(translationKey, e == null ? null : e.getMessage()); } public static void sendModErrorMessage(String translationKey) { sendModErrorMessage(translationKey, (String) null); } public static void sendModMessage(Component message) { sendPlayerMessage(createModMessage(message)); } public static MutableComponent createModMessage(Component message) { return Component.empty() .append(ComponentUtils.wrapInSquareBrackets(Component.literal(CommonCompatibilityManager.INSTANCE.getModName())).withStyle(ChatFormatting.GREEN)) .append(" ") .append(message); } public static void sendPlayerMessage(Component component) { Minecraft.getInstance().gui.getChat().addMessage(component); } }
412
0.510127
1
0.510127
game-dev
MEDIA
0.882552
game-dev
0.596943
1
0.596943
Emudofus/Dofus
5,808
ui/ui/ConfigTheme.as
package ui { import flash.utils.Dictionary; import d2components.Grid; import d2components.Label; import d2components.TextArea; import d2components.Texture; import types.ConfigProperty; import d2hooks.*; import d2actions.*; public class ConfigTheme extends ConfigUi { public var output:Object; [Module(name="Ankama_Common")] public var modCommon:Object; private var _skins:Array; private var _choosenSkin:String; private var _selectedThemeName:String; private var _themeBtnList:Dictionary; public var grid_theme:Grid; public var lbl_name:Label; public var lbl_description:TextArea; public var tx_preview:Texture; public function ConfigTheme() { this._themeBtnList = new Dictionary(true); super(); } public function main(args:*):void { var skin:*; var properties:Array = new Array(); properties.push(new ConfigProperty("grid_theme", "switchUiSkin", "dofus")); init(properties); this._selectedThemeName = configApi.getCurrentTheme(); this._skins = new Array(); var selected:uint = 1; var i:uint; for each (skin in configApi.getAllThemes()) { this._skins.push(skin); if (skin.fileName == this._selectedThemeName) { selected = i; }; i++; }; this.grid_theme.dataProvider = this._skins; this.grid_theme.selectedIndex = selected; showDefaultBtn(false); } public function unload():void { } private function saveOptions():void { } private function undoOptions():void { } private function displayTheme(theme:*):void { var desc:String = theme.description; if (((!((desc.indexOf("[") == -1))) && (!((desc.indexOf("]") == -1))))) { desc = uiApi.getText(desc.slice(1, -1)); }; this.lbl_description.text = desc; var name:String = theme.name; if (((!((name.indexOf("[") == -1))) && (!((name.indexOf("]") == -1))))) { name = uiApi.getText(name.slice(1, -1)); }; this.lbl_name.text = name; if (theme.previewUri != "") { this.tx_preview.uri = uiApi.createUri(((((sysApi.getConfigEntry("config.content.path") + "themes/") + theme.fileName) + "/bitmap/") + theme.previewUri)); } else { this.tx_preview.uri = null; }; } public function updateThemeLine(data:*, componentsRef:*, selected:Boolean):void { var theme:Object; var name:String; if (!(this._themeBtnList[componentsRef.btn_selectTheme.name])) { uiApi.addComponentHook(componentsRef.btn_selectTheme, "onRelease"); }; this._themeBtnList[componentsRef.btn_selectTheme.name] = data; if (data) { componentsRef.btn_theme.visible = true; componentsRef.btn_theme.selected = selected; componentsRef.btn_theme.state = ((selected) ? (sysApi.getEnum("com.ankamagames.berilia.enums.StatesEnum").STATE_SELECTED) : (sysApi.getEnum("com.ankamagames.berilia.enums.StatesEnum").STATE_NORMAL)); theme = data; name = theme.name; if (((!((name.indexOf("[") == -1))) && (!((name.indexOf("]") == -1))))) { name = uiApi.getText(name.slice(1, -1)); }; componentsRef.lbl_name.text = name; componentsRef.btn_selectTheme.visible = true; componentsRef.btn_selectTheme.selected = (this._selectedThemeName == theme.fileName); } else { componentsRef.lbl_name.text = ""; componentsRef.btn_selectTheme.selected = false; componentsRef.btn_selectTheme.visible = false; componentsRef.btn_theme.visible = false; }; } override public function onRelease(target:Object):void { if (((!((target.name.indexOf("btn_selectTheme") == -1))) && (!((this._themeBtnList[target.name].fileName == this._selectedThemeName))))) { this._choosenSkin = this._themeBtnList[target.name].fileName; this.modCommon.openPopup(uiApi.getText("ui.popup.warning"), uiApi.getText("ui.option.resetGameForNewSkin"), [uiApi.getText("ui.common.yes"), uiApi.getText("ui.common.no")], [this.onConfirmChangeSkin, null]); }; } public function onSelectItem(target:Object, selectMethod:uint, isNewSelection:Boolean):void { switch (target) { case this.grid_theme: this.displayTheme(this.grid_theme.selectedItem); break; }; } public function onConfirmChangeSkin():void { setProperty("dofus", "switchUiSkin", this._choosenSkin); sysApi.clearCache(true); } public function onRollOver(target:Object):void { uiApi.showTooltip(uiApi.textTooltipInfo(uiApi.getText("ui.option.themeApply")), target, false, "standard", 7, 1, 3, null, null, null, "TextInfo"); } public function onRollOut(target:Object):void { uiApi.hideTooltip(); } } }//package ui
412
0.860086
1
0.860086
game-dev
MEDIA
0.77598
game-dev
0.974313
1
0.974313
mchorse/metamorph
2,392
src/main/java/mchorse/vanilla_pack/abilities/SunAllergy.java
package mchorse.vanilla_pack.abilities; import java.util.Random; import mchorse.metamorph.api.abilities.Ability; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos.MutableBlockPos; /** * Sun allergy ability * * This abilitiy does cool stuff. It sets player on fire when he's on the sun. * It will be used by the coolest mobs in the game skeleton and zombie. * * This is more like a disability than an ability *Ba-dum-pam-dum-tsss* */ public class SunAllergy extends Ability { private MutableBlockPos pos = new MutableBlockPos(0, 0, 0); private Random random = new Random(); @Override public void update(EntityLivingBase target) { if (!target.world.isDaytime() || target.world.isRemote) { return; } float brightness = target.getBrightness(); boolean random = this.random.nextFloat() * 30.0F < (brightness - 0.4F) * 2.0F; this.pos.setPos(target.posX, target.posY + target.getEyeHeight(), target.posZ); /* Taken from EntityZombie class and slightly modified */ if (brightness > 0.5 && random && target.world.canSeeSky(pos)) { boolean flag = true; ItemStack itemstack = target.getItemStackFromSlot(EntityEquipmentSlot.HEAD); /* If target has a head slot on the head, then damage it */ if (!itemstack.isEmpty()) { boolean isCreativePlayer = target instanceof EntityPlayer && ((EntityPlayer) target).isCreative(); /* Unless it's damagable or creative player wears it */ if (itemstack.isItemStackDamageable() && !isCreativePlayer) { itemstack.setItemDamage(itemstack.getItemDamage() + this.random.nextInt(2)); if (itemstack.getItemDamage() >= itemstack.getMaxDamage()) { target.renderBrokenItemStack(itemstack); target.setItemStackToSlot(EntityEquipmentSlot.HEAD, ItemStack.EMPTY); } } flag = false; } if (flag) { target.setFire(8); } } } }
412
0.893157
1
0.893157
game-dev
MEDIA
0.996994
game-dev
0.950068
1
0.950068
OpenMW/openmw
2,680
files/data/scripts/omw/console/global.lua
local util = require('openmw.util') local player = nil local function printToConsole(...) local strs = {} for i = 1, select('#', ...) do strs[i] = tostring(select(i, ...)) end player:sendEvent('OMWConsolePrint', table.concat(strs, '\t')) end local function printRes(...) if select('#', ...) >= 0 then printToConsole(...) end end local env = { I = require('openmw.interfaces'), util = require('openmw.util'), storage = require('openmw.storage'), core = require('openmw.core'), types = require('openmw.types'), vfs = require('openmw.vfs'), markup = require('openmw.markup'), async = require('openmw.async'), world = require('openmw.world'), aux_util = require('openmw_aux.util'), calendar = require('openmw_aux.calendar'), time = require('openmw_aux.time'), view = require('openmw_aux.util').deepToString, print = printToConsole, exit = function() player:sendEvent('OMWConsoleExit') end, help = function() player:sendEvent('OMWConsoleHelp') end, } env._G = env setmetatable(env, {__index = _G, __metatable = false}) _G = nil local function executeLuaCode(code) local fn local ok, err = pcall(function() fn = util.loadCode('return ' .. code, env) end) if ok then ok, err = pcall(function() printRes(fn()) end) else ok, err = pcall(function() util.loadCode(code, env)() end) end if not ok then player:sendEvent('OMWConsoleError', err) end end return { eventHandlers = { OMWConsoleEval = function(data) player = data.player env.selected = data.selected executeLuaCode(data.code) if env.selected ~= data.selected then local ok, err = pcall(function() player:sendEvent('OMWConsoleSetSelected', env.selected) end) if not ok then player:sendEvent('OMWConsoleError', err) end end end, OMWConsoleStartLocal = function(data) player = data.player ok, err = pcall(function() if not data.selected:hasScript('scripts/omw/console/local.lua') then data.selected:addScript('scripts/omw/console/local.lua') end end) if ok then player:sendEvent('OMWConsoleSetContext', data.selected) else player:sendEvent('OMWConsoleError', err) end end, OMWConsoleStopLocal = function(obj) if obj:hasScript('scripts/omw/console/local.lua') then obj:removeScript('scripts/omw/console/local.lua') end end, }, }
412
0.777622
1
0.777622
game-dev
MEDIA
0.704414
game-dev
0.758679
1
0.758679
blurite/rsprot
1,236
protocol/osrs-234/osrs-234-model/src/main/kotlin/net/rsprot/protocol/game/incoming/clan/ClanSettingsFullRequest.kt
package net.rsprot.protocol.game.incoming.clan import net.rsprot.protocol.ClientProtCategory import net.rsprot.protocol.game.incoming.GameClientProtCategory import net.rsprot.protocol.message.IncomingGameMessage /** * Clan settings requests are made whenever the server sends a clansettings * delta update, but the update counter in the clan settings message * is greater than that of the clan itself. In order to avoid problems, * the client requests for a full clan settings update from the server, * to re-synchronize all the values. * @property clanId the id of the clan to request, ranging from 0 to 3 (inclusive), * or a negative value if the request is for a guest-clan */ public class ClanSettingsFullRequest( public val clanId: Int, ) : IncomingGameMessage { override val category: ClientProtCategory get() = GameClientProtCategory.USER_EVENT override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ClanSettingsFullRequest return clanId == other.clanId } override fun hashCode(): Int = clanId override fun toString(): String = "ClanSettingsFullRequest(clanId=$clanId)" }
412
0.649364
1
0.649364
game-dev
MEDIA
0.837337
game-dev
0.805761
1
0.805761
JetBoom/zombiesurvival
1,334
gamemodes/zombiesurvival/entities/weapons/weapon_zs_t_resupplypack.lua
AddCSLuaFile() SWEP.Base = "weapon_zs_basetrinket" SWEP.PrintName = "Resupply Pack" SWEP.Description = "Allows humans to resupply from you.\nPress LMB with the pack in your hand to resupply yourself." if CLIENT then SWEP.VElements = { ["base"] = { type = "Model", model = "models/Items/ammocrate_ar2.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(4, 2, -1), angle = Angle(0, -90, 180), size = Vector(0.35, 0.35, 0.35), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.WElements = { ["base"] = { type = "Model", model = "models/Items/ammocrate_ar2.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(4, 2, -1), angle = Angle(0, -90, 180), size = Vector(0.35, 0.35, 0.35), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.ShowViewModel = false SWEP.ShowWorldModel = false end SWEP.Primary.Automatic = false SWEP.Primary.Delay = 1 function SWEP:PrimaryAttack() if not self:CanPrimaryAttack() then return end self:SetNextPrimaryFire(CurTime() + self.Primary.Delay) if CLIENT then return end local owner = self:GetOwner() for _, ent in pairs(ents.FindByClass("status_resupplypack")) do if ent:GetOwner() == owner then owner:Resupply(owner, ent) end end end
412
0.874674
1
0.874674
game-dev
MEDIA
0.624216
game-dev
0.751089
1
0.751089
worships/2021e-localhost-guide
30,511
coreguis/53878048
-- This script creates almost all gui elements found in the backpack (warning: there are a lot!) -- TODO: automate this process if game.CoreGui.Version < 3 then return end -- peace out if we aren't using the right client local gui = script.Parent -- A couple of necessary functions local function waitForChild(instance, name) while not instance:FindFirstChild(name) do instance.ChildAdded:wait() end end local function waitForProperty(instance, property) while not instance[property] do instance.Changed:wait() end end waitForChild(game,"Players") waitForProperty(game.Players,"LocalPlayer") local player = game.Players.LocalPlayer -- First up is the current loadout local CurrentLoadout = Instance.new("Frame") CurrentLoadout.Name = "CurrentLoadout" CurrentLoadout.Position = UDim2.new(0.5, -240, 1, -85) CurrentLoadout.Size = UDim2.new(0, 480, 0, 48) CurrentLoadout.BackgroundTransparency = 1 CurrentLoadout.RobloxLocked = true CurrentLoadout.Parent = gui local Debounce = Instance.new("BoolValue") Debounce.Name = "Debounce" Debounce.RobloxLocked = true Debounce.Parent = CurrentLoadout local BackpackButton = Instance.new("ImageButton") BackpackButton.RobloxLocked = true BackpackButton.Visible = false BackpackButton.Name = "BackpackButton" BackpackButton.BackgroundTransparency = 1 BackpackButton.Image = "rbxasset://textures/ui/backpackButton.png" BackpackButton.Position = UDim2.new(0.5, -195, 1, -30) BackpackButton.Size = UDim2.new(0,107,0,26) waitForChild(gui,"ControlFrame") BackpackButton.Parent = gui.ControlFrame for i = 0, 9 do local slotFrame = Instance.new("Frame") slotFrame.RobloxLocked = true slotFrame.BackgroundColor3 = Color3.new(0,0,0) slotFrame.BackgroundTransparency = 1 slotFrame.BorderColor3 = Color3.new(1,1,1) slotFrame.Name = "Slot" .. tostring(i) if i == 0 then slotFrame.Position = UDim2.new(0.9,0,0,0) else slotFrame.Position = UDim2.new((i - 1) * 0.1,0,0,0) end slotFrame.Size = UDim2.new(0.1,0,1,0) slotFrame.Parent = CurrentLoadout end local TempSlot = Instance.new("ImageButton") TempSlot.Name = "TempSlot" TempSlot.Active = true TempSlot.Size = UDim2.new(1,0,1,0) TempSlot.Style = Enum.ButtonStyle.RobloxButton TempSlot.Visible = false TempSlot.RobloxLocked = true TempSlot.Parent = CurrentLoadout -- TempSlot Children local GearReference = Instance.new("ObjectValue") GearReference.Name = "GearReference" GearReference.RobloxLocked = true GearReference.Parent = TempSlot local ToolTipLabel = Instance.new("TextLabel") ToolTipLabel.Name = "ToolTipLabel" ToolTipLabel.RobloxLocked = true ToolTipLabel.Text = "" ToolTipLabel.BackgroundTransparency = 0.5 ToolTipLabel.BorderSizePixel = 0 ToolTipLabel.Visible = false ToolTipLabel.TextColor3 = Color3.new(1,1,1) ToolTipLabel.BackgroundColor3 = Color3.new(0,0,0) ToolTipLabel.TextStrokeTransparency = 0 ToolTipLabel.Font = Enum.Font.ArialBold ToolTipLabel.FontSize = Enum.FontSize.Size14 --ToolTipLabel.TextWrap = true ToolTipLabel.Size = UDim2.new(1,60,0,20) ToolTipLabel.Position = UDim2.new(0,-30,0,-30) ToolTipLabel.Parent = TempSlot local Kill = Instance.new("BoolValue") Kill.Name = "Kill" Kill.RobloxLocked = true Kill.Parent = TempSlot local GearImage = Instance.new("ImageLabel") GearImage.Name = "GearImage" GearImage.BackgroundTransparency = 1 GearImage.Position = UDim2.new(0,-7,0,-7) GearImage.Size = UDim2.new(1,14,1,14) GearImage.ZIndex = 2 GearImage.RobloxLocked = true GearImage.Parent = TempSlot local SlotNumber = Instance.new("TextLabel") SlotNumber.Name = "SlotNumber" SlotNumber.BackgroundTransparency = 1 SlotNumber.BorderSizePixel = 0 SlotNumber.Font = Enum.Font.ArialBold SlotNumber.FontSize = Enum.FontSize.Size18 SlotNumber.Position = UDim2.new(0,-7,0,-7) SlotNumber.Size = UDim2.new(0,10,0,15) SlotNumber.TextColor3 = Color3.new(1,1,1) SlotNumber.TextTransparency = 0 SlotNumber.TextXAlignment = Enum.TextXAlignment.Left SlotNumber.TextYAlignment = Enum.TextYAlignment.Bottom SlotNumber.ZIndex = 4 SlotNumber.RobloxLocked = true SlotNumber.Parent = TempSlot local SlotNumberDownShadow = SlotNumber:clone() SlotNumberDownShadow.Name = "SlotNumberDownShadow" SlotNumberDownShadow.TextColor3 = Color3.new(0,0,0) SlotNumberDownShadow.ZIndex = 3 SlotNumberDownShadow.Position = UDim2.new(0,-6,0,-6) SlotNumberDownShadow.Parent = TempSlot local SlotNumberUpShadow = SlotNumberDownShadow:clone() SlotNumberUpShadow.Name = "SlotNumberUpShadow" SlotNumberUpShadow.Position = UDim2.new(0,-8,0,-8) SlotNumberUpShadow.Parent = TempSlot local GearText = Instance.new("TextLabel") GearText.RobloxLocked = true GearText.Name = "GearText" GearText.BackgroundTransparency = 1 GearText.Font = Enum.Font.Arial GearText.FontSize = Enum.FontSize.Size14 GearText.Position = UDim2.new(0,-8,0,-8) GearText.ZIndex = 2 GearText.Size = UDim2.new(1,16,1,16) GearText.Text = "" GearText.TextColor3 = Color3.new(1,1,1) GearText.TextWrap = true GearText.Parent = TempSlot --- Great, now lets make the inventory! local Backpack = Instance.new("Frame") Backpack.RobloxLocked = true Backpack.Visible = false Backpack.Name = "Backpack" Backpack.Position = UDim2.new(0.5,0,0.5,0) Backpack.BackgroundColor3 = Color3.new(0,0,0) Backpack.BackgroundTransparency = 0.08 Backpack.BorderSizePixel = 0 Backpack.Parent = gui Backpack.Active = true -- Backpack Children local SwapSlot = Instance.new("BoolValue") SwapSlot.RobloxLocked = true SwapSlot.Name = "SwapSlot" SwapSlot.Parent = Backpack -- SwapSlot Children local Slot = Instance.new("IntValue") Slot.RobloxLocked = true Slot.Name = "Slot" Slot.Parent = SwapSlot local GearButton = Instance.new("ObjectValue") GearButton.RobloxLocked = true GearButton.Name = "GearButton" GearButton.Parent = SwapSlot local Tabs = Instance.new("Frame") Tabs.Name = "Tabs" Tabs.Visible = true Tabs.RobloxLocked = true Tabs.BackgroundColor3 = Color3.new(0,0,0) Tabs.BackgroundTransparency = 0.08 Tabs.BorderSizePixel = 0 Tabs.Position = UDim2.new(0,0,-0.1,-4) Tabs.Size = UDim2.new(1,0,0.1,4) Tabs.Parent = Backpack -- Tabs Children local tabLine = Instance.new("Frame") tabLine.RobloxLocked = true tabLine.Name = "TabLine" tabLine.BackgroundColor3 = Color3.new(53/255, 53/255, 53/255) tabLine.BorderSizePixel = 0 tabLine.Position = UDim2.new(0,5,1,-4) tabLine.Size = UDim2.new(1,-10,0,4) tabLine.ZIndex = 2 tabLine.Parent = Tabs local InventoryButton = Instance.new("TextButton") InventoryButton.RobloxLocked = true InventoryButton.Name = "InventoryButton" InventoryButton.Size = UDim2.new(0,60,0,30) InventoryButton.Position = UDim2.new(0,7,1,-31) InventoryButton.BackgroundColor3 = Color3.new(1,1,1) InventoryButton.BorderColor3 = Color3.new(1,1,1) InventoryButton.Font = Enum.Font.ArialBold InventoryButton.FontSize = Enum.FontSize.Size18 InventoryButton.Text = "Gear" InventoryButton.AutoButtonColor = false InventoryButton.TextColor3 = Color3.new(0,0,0) InventoryButton.Selected = true InventoryButton.Active = true InventoryButton.ZIndex = 3 InventoryButton.Parent = Tabs if game.CoreGui.Version >= 8 then local WardrobeButton = Instance.new("TextButton") WardrobeButton.RobloxLocked = true WardrobeButton.Name = "WardrobeButton" WardrobeButton.Size = UDim2.new(0,90,0,30) WardrobeButton.Position = UDim2.new(0,77,1,-31) WardrobeButton.BackgroundColor3 = Color3.new(0,0,0) WardrobeButton.BorderColor3 = Color3.new(1,1,1) WardrobeButton.Font = Enum.Font.ArialBold WardrobeButton.FontSize = Enum.FontSize.Size18 WardrobeButton.Text = "Wardrobe" WardrobeButton.AutoButtonColor = false WardrobeButton.TextColor3 = Color3.new(1,1,1) WardrobeButton.Selected = false WardrobeButton.Active = true WardrobeButton.Parent = Tabs end local closeButton = Instance.new("TextButton") closeButton.RobloxLocked = true closeButton.Name = "CloseButton" closeButton.Font = Enum.Font.ArialBold closeButton.FontSize = Enum.FontSize.Size24 closeButton.Position = UDim2.new(1,-33,0,4) closeButton.Size = UDim2.new(0,30,0,30) closeButton.Style = Enum.ButtonStyle.RobloxButton closeButton.Text = "" closeButton.TextColor3 = Color3.new(1,1,1) closeButton.Parent = Tabs closeButton.Modal = true --closeButton child local XImage = Instance.new("ImageLabel") XImage.RobloxLocked = true XImage.Name = "XImage" game:GetService("ContentProvider"):Preload("http://www.roblox.com/asset/?id=75547445") XImage.Image = "http://www.roblox.com/asset/?id=75547445" --TODO: move to rbxasset XImage.BackgroundTransparency = 1 XImage.Position = UDim2.new(-.25,-1,-.25,-1) XImage.Size = UDim2.new(1.5,2,1.5,2) XImage.ZIndex = 2 XImage.Parent = closeButton -- Generic Search gui used across backpack local SearchFrame = Instance.new("Frame") SearchFrame.RobloxLocked = true SearchFrame.Name = "SearchFrame" SearchFrame.BackgroundTransparency = 1 SearchFrame.Position = UDim2.new(1,-220,0,2) SearchFrame.Size = UDim2.new(0,220,0,24) SearchFrame.Parent = Backpack -- SearchFrame Children local SearchButton = Instance.new("ImageButton") SearchButton.RobloxLocked = true SearchButton.Name = "SearchButton" SearchButton.Size = UDim2.new(0,25,0,25) SearchButton.BackgroundTransparency = 1 SearchButton.Image = "rbxasset://textures/ui/SearchIcon.png" SearchButton.Parent = SearchFrame local SearchBoxFrame = Instance.new("TextButton") SearchBoxFrame.RobloxLocked = true SearchBoxFrame.Position = UDim2.new(0,25,0,0) SearchBoxFrame.Size = UDim2.new(1,-28,0,26) SearchBoxFrame.Name = "SearchBoxFrame" SearchBoxFrame.Text = "" SearchBoxFrame.Style = Enum.ButtonStyle.RobloxButton SearchBoxFrame.Parent = SearchFrame -- SearchBoxFrame Children local SearchBox = Instance.new("TextBox") SearchBox.RobloxLocked = true SearchBox.Name = "SearchBox" SearchBox.BackgroundTransparency = 1 SearchBox.Font = Enum.Font.ArialBold SearchBox.FontSize = Enum.FontSize.Size12 SearchBox.Position = UDim2.new(0,-5,0,-5) SearchBox.Size = UDim2.new(1,10,1,10) SearchBox.TextColor3 = Color3.new(1,1,1) SearchBox.TextXAlignment = Enum.TextXAlignment.Left SearchBox.ZIndex = 2 SearchBox.TextWrap = true SearchBox.Text = "Search..." SearchBox.Parent = SearchBoxFrame local ResetButton = Instance.new("TextButton") ResetButton.RobloxLocked = true ResetButton.Visible = false ResetButton.Name = "ResetButton" ResetButton.Position = UDim2.new(1,-26,0,3) ResetButton.Size = UDim2.new(0,20,0,20) ResetButton.Style = Enum.ButtonStyle.RobloxButtonDefault ResetButton.Text = "X" ResetButton.TextColor3 = Color3.new(1,1,1) ResetButton.Font = Enum.Font.ArialBold ResetButton.FontSize = Enum.FontSize.Size18 ResetButton.ZIndex = 3 ResetButton.Parent = SearchFrame ------------------------------- GEAR ------------------------------------------------------- local Gear = Instance.new("Frame") Gear.Name = "Gear" Gear.RobloxLocked = true Gear.BackgroundTransparency = 1 Gear.Size = UDim2.new(1,0,1,0) Gear.Parent = Backpack -- Gear Children local AssetsList = Instance.new("Frame") AssetsList.RobloxLocked = true AssetsList.Name = "AssetsList" AssetsList.BackgroundTransparency = 1 AssetsList.Size = UDim2.new(0.2,0,1,0) AssetsList.Style = Enum.FrameStyle.RobloxSquare AssetsList.Visible = false AssetsList.Parent = Gear local GearGrid = Instance.new("Frame") GearGrid.RobloxLocked = true GearGrid.Name = "GearGrid" GearGrid.Size = UDim2.new(0.69,0,1,0) GearGrid.BackgroundTransparency = 1 GearGrid.Parent = Gear local GearButton = Instance.new("ImageButton") GearButton.RobloxLocked = true GearButton.Visible = false GearButton.Name = "GearButton" GearButton.Size = UDim2.new(0,64,0,64) GearButton.Style = Enum.ButtonStyle.RobloxButton GearButton.Parent = GearGrid -- GearButton Children local GearReference = Instance.new("ObjectValue") GearReference.RobloxLocked = true GearReference.Name = "GearReference" GearReference.Parent = GearButton local GreyOutButton = Instance.new("Frame") GreyOutButton.RobloxLocked = true GreyOutButton.Name = "GreyOutButton" GreyOutButton.BackgroundTransparency = 0.5 GreyOutButton.Size = UDim2.new(1,0,1,0) GreyOutButton.Active = true GreyOutButton.Visible = false GreyOutButton.ZIndex = 3 GreyOutButton.Parent = GearButton local GearText = Instance.new("TextLabel") GearText.RobloxLocked = true GearText.Name = "GearText" GearText.BackgroundTransparency = 1 GearText.Font = Enum.Font.Arial GearText.FontSize = Enum.FontSize.Size14 GearText.Position = UDim2.new(0,-8,0,-8) GearText.Size = UDim2.new(1,16,1,16) GearText.Text = "" GearText.ZIndex = 2 GearText.TextColor3 = Color3.new(1,1,1) GearText.TextWrap = true GearText.Parent = GearButton local GearGridScrollingArea = Instance.new("Frame") GearGridScrollingArea.RobloxLocked = true GearGridScrollingArea.Name = "GearGridScrollingArea" GearGridScrollingArea.Position = UDim2.new(0.7,0,0,35) GearGridScrollingArea.Size = UDim2.new(0,17,1,-45) GearGridScrollingArea.BackgroundTransparency = 1 GearGridScrollingArea.Parent = Gear local GearLoadouts = Instance.new("Frame") GearLoadouts.RobloxLocked = true GearLoadouts.Name = "GearLoadouts" GearLoadouts.BackgroundTransparency = 1 GearLoadouts.Position = UDim2.new(0.7,23,0.5,1) GearLoadouts.Size = UDim2.new(0.3,-23,0.5,-1) GearLoadouts.Parent = Gear GearLoadouts.Visible = false -- GearLoadouts Children local GearLoadoutsHeader = Instance.new("Frame") GearLoadoutsHeader.RobloxLocked = true GearLoadoutsHeader.Name = "GearLoadoutsHeader" GearLoadoutsHeader.BackgroundColor3 = Color3.new(0,0,0) GearLoadoutsHeader.BackgroundTransparency = 0.2 GearLoadoutsHeader.BorderColor3 = Color3.new(1,0,0) GearLoadoutsHeader.Size = UDim2.new(1,2,0.15,-1) GearLoadoutsHeader.Parent = GearLoadouts -- GearLoadoutsHeader Children local LoadoutsHeaderText = Instance.new("TextLabel") LoadoutsHeaderText.RobloxLocked = true LoadoutsHeaderText.Name = "LoadoutsHeaderText" LoadoutsHeaderText.BackgroundTransparency = 1 LoadoutsHeaderText.Font = Enum.Font.ArialBold LoadoutsHeaderText.FontSize = Enum.FontSize.Size18 LoadoutsHeaderText.Size = UDim2.new(1,0,1,0) LoadoutsHeaderText.Text = "Loadouts" LoadoutsHeaderText.TextColor3 = Color3.new(1,1,1) LoadoutsHeaderText.Parent = GearLoadoutsHeader local GearLoadoutsScrollingArea = GearGridScrollingArea:clone() GearLoadoutsScrollingArea.RobloxLocked = true GearLoadoutsScrollingArea.Name = "GearLoadoutsScrollingArea" GearLoadoutsScrollingArea.Position = UDim2.new(1,-15,0.15,2) GearLoadoutsScrollingArea.Size = UDim2.new(0,17,0.85,-2) GearLoadoutsScrollingArea.Parent = GearLoadouts local LoadoutsList = Instance.new("Frame") LoadoutsList.RobloxLocked = true LoadoutsList.Name = "LoadoutsList" LoadoutsList.Position = UDim2.new(0,0,0.15,2) LoadoutsList.Size = UDim2.new(1,-17,0.85,-2) LoadoutsList.Style = Enum.FrameStyle.RobloxSquare LoadoutsList.Parent = GearLoadouts local GearPreview = Instance.new("Frame") GearPreview.RobloxLocked = true GearPreview.Name = "GearPreview" GearPreview.Position = UDim2.new(0.7,23,0,0) GearPreview.Size = UDim2.new(0.3,-28,0.5,-1) GearPreview.BackgroundTransparency = 1 GearPreview.ZIndex = 7 GearPreview.Parent = Gear -- GearPreview Children local GearStats = Instance.new("Frame") GearStats.RobloxLocked = true GearStats.Name = "GearStats" GearStats.BackgroundTransparency = 1 GearStats.Position = UDim2.new(0,0,0.75,0) GearStats.Size = UDim2.new(1,0,0.25,0) GearStats.ZIndex = 8 GearStats.Parent = GearPreview -- GearStats Children local GearName = Instance.new("TextLabel") GearName.RobloxLocked = true GearName.Name = "GearName" GearName.BackgroundTransparency = 1 GearName.Font = Enum.Font.ArialBold GearName.FontSize = Enum.FontSize.Size18 GearName.Position = UDim2.new(0,-3,0,0) GearName.Size = UDim2.new(1,6,1,5) GearName.Text = "" GearName.TextColor3 = Color3.new(1,1,1) GearName.TextWrap = true GearName.ZIndex = 9 GearName.Parent = GearStats local GearImage = Instance.new("ImageLabel") GearImage.RobloxLocked = true GearImage.Name = "GearImage" GearImage.Image = "" GearImage.BackgroundTransparency = 1 GearImage.Position = UDim2.new(0.125,0,0,0) GearImage.Size = UDim2.new(0.75,0,0.75,0) GearImage.ZIndex = 8 GearImage.Parent = GearPreview --GearImage Children local GearIcons = Instance.new("Frame") GearIcons.BackgroundColor3 = Color3.new(0,0,0) GearIcons.BackgroundTransparency = 0.5 GearIcons.BorderSizePixel = 0 GearIcons.RobloxLocked = true GearIcons.Name = "GearIcons" GearIcons.Position = UDim2.new(0.4,2,0.85,-2) GearIcons.Size = UDim2.new(0.6,0,0.15,0) GearIcons.Visible = false GearIcons.ZIndex = 9 GearIcons.Parent = GearImage -- GearIcons Children local GenreImage = Instance.new("ImageLabel") GenreImage.RobloxLocked = true GenreImage.Name = "GenreImage" GenreImage.BackgroundColor3 = Color3.new(102/255,153/255,1) GenreImage.BackgroundTransparency = 0.5 GenreImage.BorderSizePixel = 0 GenreImage.Size = UDim2.new(0.25,0,1,0) GenreImage.Parent = GearIcons local AttributeOneImage = GenreImage:clone() AttributeOneImage.RobloxLocked = true AttributeOneImage.Name = "AttributeOneImage" AttributeOneImage.BackgroundColor3 = Color3.new(1,51/255,0) AttributeOneImage.Position = UDim2.new(0.25,0,0,0) AttributeOneImage.Parent = GearIcons local AttributeTwoImage = GenreImage:clone() AttributeTwoImage.RobloxLocked = true AttributeTwoImage.Name = "AttributeTwoImage" AttributeTwoImage.BackgroundColor3 = Color3.new(153/255,1,153/255) AttributeTwoImage.Position = UDim2.new(0.5,0,0,0) AttributeTwoImage.Parent = GearIcons local AttributeThreeImage = GenreImage:clone() AttributeThreeImage.RobloxLocked = true AttributeThreeImage.Name = "AttributeThreeImage" AttributeThreeImage.BackgroundColor3 = Color3.new(0,0.5,0.5) AttributeThreeImage.Position = UDim2.new(0.75,0,0,0) AttributeThreeImage.Parent = GearIcons ------------------------------- WARDROBE ------------------------------------------------------- if game.CoreGui.Version < 8 then -- no need for this to stick around, we aren't ready for wardrobe script:remove() return end local function makeCharFrame(frameName, parent) local frame = Instance.new("Frame") frame.RobloxLocked = true frame.Size = UDim2.new(1,0,1,-70) frame.Position = UDim2.new(0,0,0,20) frame.Name = frameName frame.BackgroundTransparency = 1 frame.Parent = parent frame.Visible = false return frame end local function makeZone( zoneName, image, size, position, parent ) local zone = Instance.new("ImageLabel") zone.RobloxLocked = true zone.Name = zoneName zone.Image = image zone.Size = size zone.BackgroundTransparency = 1 zone.Position = position zone.Parent = parent return zone end local function makeStyledButton( buttonName, size, position, parent, buttonStyle ) local button = Instance.new("ImageButton") button.RobloxLocked = true button.Name = buttonName button.Size = size button.Position = position if buttonStyle then button.Style = buttonStyle else button.BackgroundColor3 = Color3.new(0,0,0) button.BorderColor3 = Color3.new(1,1,1) end button.Parent = parent return button end local function makeTextLabel( TextLabelName,text,position,parent ) local label = Instance.new("TextLabel") label.RobloxLocked = true label.BackgroundTransparency = 1 label.Size = UDim2.new(0,32,0,14) label.Name = TextLabelName label.Font = Enum.Font.Arial label.TextColor3 = Color3.new(1,1,1) label.FontSize = Enum.FontSize.Size14 label.Text = text label.Position = position label.Parent = parent end local Wardrobe = Instance.new("Frame") Wardrobe.Name = "Wardrobe" Wardrobe.RobloxLocked = true Wardrobe.BackgroundTransparency = 1 Wardrobe.Visible = false Wardrobe.Size = UDim2.new(1,0,1,0) Wardrobe.Parent = Backpack local AssetList = Instance.new("Frame") AssetList.RobloxLocked = true AssetList.Name = "AssetList" AssetList.Position = UDim2.new(0,4,0,5) AssetList.Size = UDim2.new(0,85,1,-5) AssetList.BackgroundTransparency = 1 AssetList.Visible = true AssetList.Parent = Wardrobe local PreviewAssetFrame = Instance.new("Frame") PreviewAssetFrame.RobloxLocked = true PreviewAssetFrame.Name = "PreviewAssetFrame" PreviewAssetFrame.BackgroundTransparency = 1 PreviewAssetFrame.Position = UDim2.new(1,-240,0,30) PreviewAssetFrame.Size = UDim2.new(0,250,0,250) PreviewAssetFrame.Parent = Wardrobe local PreviewAssetBacking = Instance.new("TextButton") PreviewAssetBacking.RobloxLocked = true PreviewAssetBacking.Name = "PreviewAssetBacking" PreviewAssetBacking.Active = false PreviewAssetBacking.Text = "" PreviewAssetBacking.AutoButtonColor = false PreviewAssetBacking.Size = UDim2.new(1,0,1,0) PreviewAssetBacking.Style = Enum.ButtonStyle.RobloxButton PreviewAssetBacking.Visible = false PreviewAssetBacking.ZIndex = 9 PreviewAssetBacking.Parent = PreviewAssetFrame local PreviewAssetImage = Instance.new("ImageLabel") PreviewAssetImage.RobloxLocked = true PreviewAssetImage.Name = "PreviewAssetImage" PreviewAssetImage.BackgroundTransparency = 0.8 PreviewAssetImage.Position = UDim2.new(0.5,-100,0,0) PreviewAssetImage.Size = UDim2.new(0,200,0,200) PreviewAssetImage.BorderSizePixel = 0 PreviewAssetImage.ZIndex = 10 PreviewAssetImage.Parent = PreviewAssetBacking local AssetNameLabel = Instance.new("TextLabel") AssetNameLabel.Name = "AssetNameLabel" AssetNameLabel.RobloxLocked = true AssetNameLabel.BackgroundTransparency = 1 AssetNameLabel.Position = UDim2.new(0,0,1,-20) AssetNameLabel.Size = UDim2.new(0.5,0,0,24) AssetNameLabel.ZIndex = 10 AssetNameLabel.Font = Enum.Font.Arial AssetNameLabel.Text = "" AssetNameLabel.TextColor3 = Color3.new(1,1,1) AssetNameLabel.TextScaled = true AssetNameLabel.Parent = PreviewAssetBacking local AssetTypeLabel = AssetNameLabel:clone() AssetTypeLabel.RobloxLocked = true AssetTypeLabel.Name = "AssetTypeLabel" AssetTypeLabel.TextScaled = false AssetTypeLabel.FontSize = Enum.FontSize.Size18 AssetTypeLabel.Position = UDim2.new(0.5,3,1,-20) AssetTypeLabel.Parent = PreviewAssetBacking local PreviewButton = Instance.new("TextButton") PreviewButton.RobloxLocked = true PreviewButton.Name = "PreviewButton" PreviewButton.Text = "Rotate" PreviewButton.BackgroundColor3 = Color3.new(0,0,0) PreviewButton.BackgroundTransparency = 0.5 PreviewButton.BorderColor3 = Color3.new(1,1,1) PreviewButton.Position = UDim2.new(1.2,-62,1,-50) PreviewButton.Size = UDim2.new(0,125,0,50) PreviewButton.Font = Enum.Font.ArialBold PreviewButton.FontSize = Enum.FontSize.Size24 PreviewButton.TextColor3 = Color3.new(1,1,1) PreviewButton.TextWrapped = true PreviewButton.TextStrokeTransparency = 0 PreviewButton.Parent = Wardrobe local CharacterPane = Instance.new("Frame") CharacterPane.RobloxLocked = true CharacterPane.Name = "CharacterPane" CharacterPane.Position = UDim2.new(1,-220,0,32) CharacterPane.Size = UDim2.new(0,220,1,-40) CharacterPane.BackgroundTransparency = 1 CharacterPane.Visible = true CharacterPane.Parent = Wardrobe --CharacterPane Children local FaceFrame = makeCharFrame("FacesFrame", CharacterPane) game:GetService("ContentProvider"):Preload("http://www.roblox.com/asset/?id=75460621") makeZone("FaceZone","http://www.roblox.com/asset/?id=75460621",UDim2.new(0,157,0,137),UDim2.new(0.5,-78,0.5,-68),FaceFrame) makeStyledButton("Face",UDim2.new(0,64,0,64),UDim2.new(0.5,-32,0.5,-135),FaceFrame) local HeadFrame = makeCharFrame("HeadsFrame", CharacterPane) makeZone("FaceZone","http://www.roblox.com/asset/?id=75460621",UDim2.new(0,157,0,137),UDim2.new(0.5,-78,0.5,-68),HeadFrame) makeStyledButton("Head",UDim2.new(0,64,0,64),UDim2.new(0.5,-32,0.5,-135),HeadFrame) local HatsFrame = makeCharFrame("HatsFrame", CharacterPane) game:GetService("ContentProvider"):Preload("http://www.roblox.com/asset/?id=75457888") local HatsZone = makeZone("HatsZone","http://www.roblox.com/asset/?id=75457888",UDim2.new(0,186,0,184),UDim2.new(0.5,-93,0.5,-100), HatsFrame) makeStyledButton("Hat1Button",UDim2.new(0,64,0,64),UDim2.new(0,-1,0,-1),HatsZone,Enum.ButtonStyle.RobloxButton) makeStyledButton("Hat2Button",UDim2.new(0,64,0,64),UDim2.new(0,63,0,-1),HatsZone,Enum.ButtonStyle.RobloxButton) makeStyledButton("Hat3Button",UDim2.new(0,64,0,64),UDim2.new(0,127,0,-1),HatsZone,Enum.ButtonStyle.RobloxButton) local PantsFrame = makeCharFrame("PantsFrame", CharacterPane) game:GetService("ContentProvider"):Preload("http://www.roblox.com/asset/?id=75457920") makeZone("PantsZone","http://www.roblox.com/asset/?id=75457920",UDim2.new(0,121,0,99),UDim2.new(0.5,-60,0.5,-100),PantsFrame) local pantFrame = Instance.new("Frame") pantFrame.RobloxLocked = true pantFrame.Size = UDim2.new(0,25,0,56) pantFrame.Position = UDim2.new(0.5,-26,0.5,0) pantFrame.BackgroundColor3 = Color3.new(0,0,0) pantFrame.BorderColor3 = Color3.new(1,1,1) pantFrame.Name = "PantFrame" pantFrame.Parent = PantsFrame local otherPantFrame = pantFrame:clone() otherPantFrame.Position = UDim2.new(0.5,3,0.5,0) otherPantFrame.RobloxLocked = true otherPantFrame.Parent = PantsFrame local CurrentPants = Instance.new("ImageButton") CurrentPants.RobloxLocked = true CurrentPants.BackgroundTransparency = 1 CurrentPants.ZIndex = 2 CurrentPants.Name = "CurrentPants" CurrentPants.Position = UDim2.new(0.5,-31,0.5,-4) CurrentPants.Size = UDim2.new(0,54,0,59) CurrentPants.Parent = PantsFrame local MeshFrame = makeCharFrame("PackagesFrame", CharacterPane) local torsoButton = makeStyledButton("TorsoMeshButton", UDim2.new(0,64,0,64),UDim2.new(0.5,-32,0.5,-110),MeshFrame,Enum.ButtonStyle.RobloxButton) makeTextLabel("TorsoLabel","Torso",UDim2.new(0.5,-16,0,-25),torsoButton) local leftLegButton = makeStyledButton("LeftLegMeshButton", UDim2.new(0,64,0,64),UDim2.new(0.5,0,0.5,-25),MeshFrame,Enum.ButtonStyle.RobloxButton) makeTextLabel("LeftLegLabel","Left Leg",UDim2.new(0.5,-16,0,-25),leftLegButton) local rightLegButton = makeStyledButton("RightLegMeshButton", UDim2.new(0,64,0,64),UDim2.new(0.5,-64,0.5,-25),MeshFrame,Enum.ButtonStyle.RobloxButton) makeTextLabel("RightLegLabel","Right Leg",UDim2.new(0.5,-16,0,-25),rightLegButton) local rightArmButton = makeStyledButton("RightArmMeshButton", UDim2.new(0,64,0,64),UDim2.new(0.5,-96,0.5,-110),MeshFrame,Enum.ButtonStyle.RobloxButton) makeTextLabel("RightArmLabel","Right Arm",UDim2.new(0.5,-16,0,-25),rightArmButton) local leftArmButton = makeStyledButton("LeftArmMeshButton", UDim2.new(0,64,0,64),UDim2.new(0.5,32,0.5,-110),MeshFrame,Enum.ButtonStyle.RobloxButton) makeTextLabel("LeftArmLabel","Left Arm",UDim2.new(0.5,-16,0,-25),leftArmButton) local TShirtFrame = makeCharFrame("T-ShirtsFrame",CharacterPane) game:GetService("ContentProvider"):Preload("http://www.roblox.com/asset/?id=75460642") makeZone("TShirtZone","http://www.roblox.com/asset/?id=75460642",UDim2.new(0,121,0,154),UDim2.new(0.5,-60,0.5,-100),TShirtFrame) makeStyledButton("TShirtButton", UDim2.new(0,64,0,64),UDim2.new(0.5,-32,0.5,-64),TShirtFrame) local ShirtFrame = makeCharFrame("ShirtsFrame", CharacterPane) makeZone("ShirtZone","http://www.roblox.com/asset/?id=75460642",UDim2.new(0,121,0,154),UDim2.new(0.5,-60,0.5,-100),ShirtFrame) makeStyledButton("ShirtButton", UDim2.new(0,64,0,64),UDim2.new(0.5,-32,0.5,-64),ShirtFrame) local ColorFrame = makeCharFrame("ColorFrame", CharacterPane) game:GetService("ContentProvider"):Preload("http://www.roblox.com/asset/?id=76049888") local ColorZone = makeZone("ColorZone","http://www.roblox.com/asset/?id=76049888", UDim2.new(0,120,0,150),UDim2.new(0.5,-60,0.5,-100),ColorFrame) makeStyledButton("Head",UDim2.new(0.26,0,0.19,0),UDim2.new(0.37,0,0.02,0),ColorZone).AutoButtonColor = false makeStyledButton("LeftArm",UDim2.new(0.19,0,0.36,0),UDim2.new(0.78,0,0.26,0),ColorZone).AutoButtonColor = false makeStyledButton("RightArm",UDim2.new(0.19,0,0.36,0),UDim2.new(0.025,0,0.26,0),ColorZone).AutoButtonColor = false makeStyledButton("Torso",UDim2.new(0.43,0,0.36,0),UDim2.new(0.28,0,0.26,0),ColorZone).AutoButtonColor = false makeStyledButton("RightLeg",UDim2.new(0.19,0,0.31,0),UDim2.new(0.275,0,0.67,0),ColorZone).AutoButtonColor = false makeStyledButton("LeftLeg",UDim2.new(0.19,0,0.31,0),UDim2.new(0.525,0,0.67,0),ColorZone).AutoButtonColor = false -- Character Panel label (shows what category we are currently browsing) local CategoryLabel = Instance.new("TextLabel") CategoryLabel.RobloxLocked = true CategoryLabel.Name = "CategoryLabel" CategoryLabel.BackgroundTransparency = 1 CategoryLabel.Font = Enum.Font.ArialBold CategoryLabel.FontSize = Enum.FontSize.Size18 CategoryLabel.Position = UDim2.new(0,0,0,-7) CategoryLabel.Size = UDim2.new(1,0,0,20) CategoryLabel.TextXAlignment = Enum.TextXAlignment.Center CategoryLabel.Text = "All" CategoryLabel.TextColor3 = Color3.new(1,1,1) CategoryLabel.Parent = CharacterPane --Save Button local SaveButton = Instance.new("TextButton") SaveButton.RobloxLocked = true SaveButton.Name = "SaveButton" SaveButton.Size = UDim2.new(0.6,0,0,50) SaveButton.Position = UDim2.new(0.2,0,1,-50) SaveButton.Style = Enum.ButtonStyle.RobloxButton SaveButton.Selected = false SaveButton.Font = Enum.Font.ArialBold SaveButton.FontSize = Enum.FontSize.Size18 SaveButton.Text = "Save" SaveButton.TextColor3 = Color3.new(1,1,1) SaveButton.Parent = CharacterPane -- no need for this to stick around script:remove()
412
0.876284
1
0.876284
game-dev
MEDIA
0.969637
game-dev
0.927352
1
0.927352
unbrraise/Meteor-Client-addons-CH
6,412
MeteorPlus-1.20.2/src/main/java/nekiplay/meteorplus/features/modules/AutoAccept.java
package nekiplay.meteorplus.features.modules; import meteordevelopment.meteorclient.events.game.ReceiveMessageEvent; import meteordevelopment.meteorclient.settings.*; import meteordevelopment.meteorclient.systems.friends.Friends; import meteordevelopment.meteorclient.systems.modules.Module; import meteordevelopment.meteorclient.utils.player.ChatUtils; import meteordevelopment.orbit.EventHandler; import nekiplay.meteorplus.MeteorPlus; import nekiplay.meteorplus.utils.ColorRemover; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AutoAccept extends Module { public AutoAccept() { super(MeteorPlus.CATEGORY, "自动接受", "自动接受传入的传送请求"); } private final SettingGroup AASettings = settings.createGroup("Auto Accept Settings"); private final Setting<Mode> mode = AASettings.add(new EnumSetting.Builder<Mode>() .name("模式") .description("选择模式") .defaultValue(Mode.Auto) .build() ); private final Setting<String> custom_pattern = AASettings.add(new StringSetting.Builder() .name("模式指令") .description("正则表达式组") .defaultValue(".*Игрок (.*) просит телепортироваться к вам!.*") .visible(() -> mode.get() == Mode.Custom) .build() ); private final Setting<Integer> custom_group = AASettings.add(new IntSetting.Builder() .name("Pattern command(有点懵)") .description("Custom pattern.") .defaultValue(1) .visible(() -> mode.get() == Mode.Custom) .build() ); private final Setting<String> accept_command = AASettings.add(new StringSetting.Builder() .name("接受指令") .description("接受指令") .defaultValue("/cmi tpaccept {username} tpa") .visible(() -> mode.get() == Mode.Custom) .build() ); private final Setting<Boolean> FriendsOnly = AASettings.add(new BoolSetting.Builder() .name("仅接受好友") .description("仅接受好友请求") .defaultValue(true) .build() ); private final Setting<Integer> Delay = AASettings.add((new IntSetting.Builder()) .name("延迟") .defaultValue(0) .build() ); private final Setting<Boolean> Debug = AASettings.add(new BoolSetting.Builder() .name("调试") .description("是否将所有传入的消息以原始格式打印到控制台中") .defaultValue(false) .build() ); public enum Mode { Auto, Custom } private final ArrayList<TPPattern> patterns = new ArrayList<>(); @Override public void onActivate() { patterns.clear(); TPPattern MST_Network = new TPPattern(".*Игрок (.*) просит телепортироваться к вам!.*", 1, "/cmi tpaccept {username} tpa"); TPPattern HolyWorld = new TPPattern("(.*) просит телепортироваться.*", 1, "/tpaccept"); TPPattern SimpleTpa = new TPPattern(".*\\[SimpleTpa\\] (.*) has sent you a teleport request!.*", 1, "/tpaccept"); TPPattern EssentialsEN = new TPPattern("(.*) has requested to teleport to you\\..*", 1, "/tpaccept"); patterns.add(MST_Network); patterns.add(HolyWorld); patterns.add(SimpleTpa); patterns.add(EssentialsEN); } @Override public void onDeactivate() { patterns.clear(); } private void BetterAccept(String username, TPPattern pattern) { if (mc.player != null && FriendsOnly.get() && isFriend(username)) { info("Accepting request from " + "§c" + username); ChatUtils.sendPlayerMsg(pattern.command.replace("{username}", username)); } else if (!FriendsOnly.get()) { info("Accepting request from " + "§c" + username); ChatUtils.sendPlayerMsg(pattern.command.replace("{username}", username)); } } private void Accept(String username, TPPattern pattern, String message) { if (mc.player != null && mode.get() == Mode.Custom) { username = getName(pattern, message); if (FriendsOnly.get() && isFriend(username)) { info("Accepting request from " + "§c" + username); ChatUtils.sendPlayerMsg(accept_command.get().replace("{username}", username)); } else if (!FriendsOnly.get()) { info("Accepting request from " + "§c" + username); ChatUtils.sendPlayerMsg(accept_command.get().replace("{username}", username)); } } else { BetterAccept(username, pattern); } } @EventHandler() public void onMessageRecieve(ReceiveMessageEvent event) { if (event.getMessage() != null && mc.player != null) { String message = ColorRemover.GetVerbatim(event.getMessage().getString()); if (Debug.get()) { MeteorPlus.LOG.info(message); } Thread th = new Thread(() -> { TPPattern custom = new TPPattern(custom_pattern.get(), custom_group.get(), accept_command.get()); String nickname = getName(message); TPPattern pattern = getPattern(message); if (pattern != null && mode.get() != Mode.Custom) { try { Thread.sleep(Delay.get()); } catch (InterruptedException e) { e.printStackTrace(); } Accept(nickname, pattern, message); } else { nickname = getName(custom, message); if (!nickname.equals("")) { try { Thread.sleep(Delay.get()); } catch (InterruptedException e) { e.printStackTrace(); } Accept(nickname, pattern, message); } } }); th.start(); } } private String getName(String message) { String nickname = ""; for (TPPattern tpPattern : patterns) { String nn = getName(tpPattern, message); if (!nn.equals("")) { nickname = nn; } } return nickname; } private String getName(TPPattern tpPattern, String message) { String nickname = ""; Pattern pattern = Pattern.compile(tpPattern.pattern); Matcher matcher = pattern.matcher(message); if (matcher.find()) { String player = matcher.group(tpPattern.group); if (!player.equals("")) { nickname = player; } } return nickname; } private TPPattern getPattern(String message) { for (TPPattern tpPattern : patterns) { Pattern pattern = Pattern.compile(tpPattern.pattern); Matcher matcher = pattern.matcher(message); if (matcher.find()) { String player = matcher.group(tpPattern.group); if (!player.equals("")) { return tpPattern; } } } return null; } private boolean isFriend(String username) { Friends friends = Friends.get(); var it = friends.iterator(); while (it.hasNext()) { var f = it.next(); if (f.name.equals(username)) return true; } return false; } private static class TPPattern { public String pattern; public int group; public String command; public TPPattern(String pattern, int group, String command) { this.pattern = pattern; this.group = group; this.command = command; } } }
412
0.689214
1
0.689214
game-dev
MEDIA
0.732883
game-dev
0.860739
1
0.860739
Rz-C/Mohist
1,442
patches/minecraft/net/minecraft/world/level/gameevent/GameEventDispatcher.java.patch
--- a/net/minecraft/world/level/gameevent/GameEventDispatcher.java +++ b/net/minecraft/world/level/gameevent/GameEventDispatcher.java @@ -9,6 +_,10 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_20_R1.CraftGameEvent; +import org.bukkit.craftbukkit.v1_20_R1.util.CraftLocation; +import org.bukkit.event.world.GenericGameEvent; public class GameEventDispatcher { private final ServerLevel f_243917_; @@ -20,6 +_,14 @@ public void m_245905_(GameEvent p_251754_, Vec3 p_250613_, GameEvent.Context p_251777_) { int i = p_251754_.m_157827_(); BlockPos blockpos = BlockPos.m_274446_(p_250613_); + // CraftBukkit start + GenericGameEvent event = new GenericGameEvent(CraftGameEvent.minecraftToBukkit(p_251754_), CraftLocation.toBukkit(blockpos, f_243917_.getWorld()), (p_251777_.f_223711_() == null) ? null : p_251777_.f_223711_().getBukkitEntity(), i, !Bukkit.isPrimaryThread()); + f_243917_.getCraftServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + i = event.getRadius(); + // CraftBukkit end int j = SectionPos.m_123171_(blockpos.m_123341_() - i); int k = SectionPos.m_123171_(blockpos.m_123342_() - i); int l = SectionPos.m_123171_(blockpos.m_123343_() - i);
412
0.616743
1
0.616743
game-dev
MEDIA
0.996683
game-dev
0.80489
1
0.80489
glKarin/com.n0n3m4.diii4a
5,145
Q3E/src/main/jni/serioussam/SamTFE/Sources/Entities/WatchPlayers.es
/* Copyright (c) 2002-2012 Croteam Ltd. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ 702 %{ #include "Entities/StdH/StdH.h" %} class CWatchPlayers: CRationalEntity { name "Watch Players"; thumbnail "Thumbnails\\WatchPlayers.tbn"; features "HasName", "IsTargetable"; properties: 1 CEntityPointer m_penOwner "Owner/Target" 'O' COLOR(C_dBROWN|0xFF), // entity which owns it / target 2 FLOAT m_fWaitTime "Wait time" 'W' = 0.1f, // watch time 3 RANGE m_fDistance "Watch distance" 'D' = 100.0f, // distance when player is seen 4 BOOL m_bRangeWatcher "Range watcher" 'R' = TRUE, // range watcher 5 enum EventEType m_eetEventClose "Close Event type" 'T' = EET_TRIGGER, // type of event to send 6 enum EventEType m_eetEventFar "Far Event type" 'Y' = EET_ENVIRONMENTSTOP, // type of event to send 7 CEntityPointer m_penCurrentWatch, 8 BOOL m_bActive "Active" 'A' = TRUE, 9 CTString m_strName "Name" 'N' = "", components: 1 model MODEL_WATCHPLAYERS "Models\\Editor\\WatchPlayers.mdl", 2 texture TEXTURE_WATCHPLAYERS "Models\\Editor\\WatchPlayers.tex" functions: /************************************************************ * USER FUNCTIONS * ************************************************************/ // check if any player is close BOOL IsAnyPlayerClose(void) { // far enough to not move at all FLOAT fClosest = 100000.0f; FLOAT fDistance; m_penCurrentWatch = NULL; // for all players for (INDEX iPlayer=0; iPlayer<GetMaxPlayers(); iPlayer++) { CEntity *penPlayer = GetPlayerEntity(iPlayer); // if player is alive and visible if (penPlayer!=NULL && penPlayer->GetFlags()&ENF_ALIVE && !(penPlayer->GetFlags()&ENF_INVISIBLE)) { fDistance = 100000.0f; if (m_bRangeWatcher) { // calculate distance to player from wathcer fDistance = (penPlayer->GetPlacement().pl_PositionVector- GetPlacement().pl_PositionVector).Length(); } else { if (m_penOwner!=NULL) { // calculate distance to player from owner fDistance = (penPlayer->GetPlacement().pl_PositionVector- m_penOwner->GetPlacement().pl_PositionVector).Length(); } } if (fDistance<fClosest) { fClosest = fDistance; m_penCurrentWatch = penPlayer; } } } // if close enough start moving return (fClosest < m_fDistance); }; // send close event void SendCloseEvent(void) { // send range event if (m_bRangeWatcher && m_penOwner==NULL) { // SendInRange(this, m_eetEventClose, FLOATaabbox3D(GetPlacement().pl_PositionVector, m_fDistance)); // send to owner } else { SendToTarget(m_penOwner, m_eetEventClose, m_penCurrentWatch); } }; // send far event void SendFarEvent(void) { // send range event if (m_bRangeWatcher && m_penOwner==NULL) { // SendInRange(this, m_eetEventFar, FLOATaabbox3D(GetPlacement().pl_PositionVector, m_fDistance)); // send to owner } else { SendToTarget(m_penOwner, m_eetEventFar); } }; procedures: // main (initialization) Main(EVoid) { // init as nothing InitAsEditorModel(); SetPhysicsFlags(EPF_MODEL_IMMATERIAL); SetCollisionFlags(ECF_IMMATERIAL); // set appearance SetModel(MODEL_WATCHPLAYERS); SetModelMainTexture(TEXTURE_WATCHPLAYERS); if (m_fWaitTime<0.1f) { m_fWaitTime=0.1f; } if (m_bActive) { jump Active(); } else { jump Inactive(); } }; Active() { autocall FarWatch() EDeactivate; jump Inactive(); } Inactive() { wait() { on (EActivate) : { stop; }; otherwise() : { resume; }; } jump Active(); } // player is close CloseWatch(EVoid) { while (TRUE) { wait(m_fWaitTime) { on (EBegin) : { if (!IsAnyPlayerClose()) { // notify for player off range SendFarEvent(); jump FarWatch(); } resume; } on (ETimer) : { stop; } } } }; // player is far FarWatch(EVoid) { while (TRUE) { wait(m_fWaitTime) { on (EBegin) : { if (IsAnyPlayerClose()) { // notify for player in range SendCloseEvent(); jump CloseWatch(); } resume; } on (ETimer) : { stop; } } } }; };
412
0.960863
1
0.960863
game-dev
MEDIA
0.843093
game-dev
0.940388
1
0.940388
Holic75/KingmakerRebalance
27,485
CallOfTheWild/Classes/ShamanSpirits/Stone.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints.Classes.Prerequisites; using Kingmaker.Blueprints.Classes.Selection; using Kingmaker.Blueprints.Classes.Spells; using Kingmaker.Blueprints.Facts; using Kingmaker.Blueprints.Items.Ecnchantments; using Kingmaker.Blueprints.Root; using Kingmaker.Designers.EventConditionActionSystem.Actions; using Kingmaker.Designers.Mechanics.Facts; using Kingmaker.ElementsSystem; using Kingmaker.EntitySystem.Stats; using Kingmaker.Enums; using Kingmaker.Enums.Damage; using Kingmaker.Localization; using Kingmaker.ResourceLinks; using Kingmaker.RuleSystem; using Kingmaker.UI.Common; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Abilities.Blueprints; using Kingmaker.UnitLogic.Abilities.Components; using Kingmaker.UnitLogic.Abilities.Components.Base; using Kingmaker.UnitLogic.Abilities.Components.CasterCheckers; using Kingmaker.UnitLogic.Abilities.Components.TargetCheckers; using Kingmaker.UnitLogic.ActivatableAbilities; using Kingmaker.UnitLogic.Buffs.Blueprints; using Kingmaker.UnitLogic.Commands.Base; using Kingmaker.UnitLogic.FactLogic; using Kingmaker.UnitLogic.Mechanics; using Kingmaker.UnitLogic.Mechanics.Actions; using Kingmaker.UnitLogic.Mechanics.Components; using Kingmaker.UnitLogic.Mechanics.Conditions; using Kingmaker.UnitLogic.Parts; using Kingmaker.Utility; using static Kingmaker.UnitLogic.ActivatableAbilities.ActivatableAbilityResourceLogic; using static Kingmaker.UnitLogic.Commands.Base.UnitCommand; using Kingmaker.UnitLogic.Buffs; namespace CallOfTheWild { partial class SpiritsEngine { public class StoneSpirit { public BlueprintFeature spirit_ability; public BlueprintFeature greater_spirit_ability; public BlueprintFeature true_spirit_ability; public BlueprintFeature manifestation; public BlueprintFeature stone_stability; public BlueprintFeature loadstone; public BlueprintFeature metal_curse; public BlueprintFeature ward_of_stone; public BlueprintAbility[] spells; public BlueprintFeature[] hexes; public StatType primary_stat; public StatType secondary_stat; HexEngine hex_engine; string prefix; bool test_mode; public Oracle.Spirit createOracleSpirit(HexEngine associated_hex_engine, string asset_prefix, bool test = false) { test_mode = test; hex_engine = associated_hex_engine; prefix = asset_prefix; primary_stat = hex_engine.hex_stat; secondary_stat = hex_engine.hex_stat; createHexes(); createSpiritAbility(); createGreaterSpiritAbility(); spells = new BlueprintAbility[9] { library.Get<BlueprintAbility>("85067a04a97416949b5d1dbf986d93f3"), //stone fist library.Get<BlueprintAbility>("5181c2ed0190fc34b8a1162783af5bf4"), //stone call library.Get<BlueprintAbility>("1a36c8b9ed655c249a9f9e8d4731f001"), //soothing mud library.Get<BlueprintAbility>("d1afa8bc28c99104da7d784115552de5"), //spike stones library.Get<BlueprintAbility>("c66e86905f7606c4eaa5c774f0357b2b"), //stoneskin library.Get<BlueprintAbility>("989d3ed13d27d054ea2d26ab4956d075"), //summon elemental huge earth library.Get<BlueprintAbility>("facdc8851a0b3f44a8bed50f0199b83c"), //elemental body IV earth library.Get<BlueprintAbility>("65254c7a2cf18944287207e1de3e44e8"), //summon elemental elder earth library.Get<BlueprintAbility>("01300baad090d634cb1a1b2defe068d6"), //clashing rocks }; return new Oracle.Spirit("Stone", "Stone", "The skin of a shaman who selects the stone spirit takes on a rough, stony appearance. When the shaman calls upon one of this spirit’s abilities, tiny gemstones underneath her flesh pulse with a bright glow, like phosphorescent geodes glittering in a dark cave.", library.Get<BlueprintAbility>("01300baad090d634cb1a1b2defe068d6").Icon,//clashing rocks "", spirit_ability, greater_spirit_ability, spells, hexes ); } public Archetypes.SpiritWhisperer.Spirit createSpiritWhispererSpirit(HexEngine associated_hex_engine, string asset_prefix, bool test = false) { test_mode = test; hex_engine = associated_hex_engine; prefix = asset_prefix; primary_stat = hex_engine.hex_stat; secondary_stat = hex_engine.hex_secondary_stat; createHexes(); createSpiritAbility(); createGreaterSpiritAbility(); createManifestation(); return new Archetypes.SpiritWhisperer.Spirit("Stone", "Stone", "The skin of a shaman who selects the stone spirit takes on a rough, stony appearance. When the shaman calls upon one of this spirit’s abilities, tiny gemstones underneath her flesh pulse with a bright glow, like phosphorescent geodes glittering in a dark cave.", library.Get<BlueprintAbility>("01300baad090d634cb1a1b2defe068d6").Icon,//clashing rocks "", spirit_ability, greater_spirit_ability, manifestation, hexes); } public Summoner.Spirit createSummonerSpirit(HexEngine associated_hex_engine, string asset_prefix, bool test = false) { test_mode = test; hex_engine = associated_hex_engine; prefix = asset_prefix; primary_stat = hex_engine.hex_stat; secondary_stat = hex_engine.hex_secondary_stat; createHexes(); createSpiritAbility(); createGreaterSpiritAbility(); createTrueSpiritAbility(); spells = new BlueprintAbility[6] { library.Get<BlueprintAbility>("85067a04a97416949b5d1dbf986d93f3"), //stone fist library.Get<BlueprintAbility>("5181c2ed0190fc34b8a1162783af5bf4"), //stone call library.Get<BlueprintAbility>("1a36c8b9ed655c249a9f9e8d4731f001"), //soothing mud library.Get<BlueprintAbility>("d1afa8bc28c99104da7d784115552de5"), //spike stones library.Get<BlueprintAbility>("c66e86905f7606c4eaa5c774f0357b2b"), //stoneskin library.Get<BlueprintAbility>("989d3ed13d27d054ea2d26ab4956d075") //summon elemental huge earth }; return new Summoner.Spirit("Stone", "Stone", "The skin of a shaman who selects the stone spirit takes on a rough, stony appearance. When the shaman calls upon one of this spirit’s abilities, tiny gemstones underneath her flesh pulse with a bright glow, like phosphorescent geodes glittering in a dark cave.", library.Get<BlueprintAbility>("01300baad090d634cb1a1b2defe068d6").Icon,//clashing rocks "", spirit_ability, greater_spirit_ability, true_spirit_ability, spells, hexes); } public Shaman.Spirit createShamanSpirit(HexEngine associated_hex_engine, string asset_prefix, bool test = false) { test_mode = test; hex_engine = associated_hex_engine; prefix = asset_prefix; primary_stat = hex_engine.hex_stat; secondary_stat = hex_engine.hex_secondary_stat; createHexes(); createSpiritAbility(); createGreaterSpiritAbility(); createTrueSpiritAbility(); createManifestation(); spells = new BlueprintAbility[9] { library.Get<BlueprintAbility>("85067a04a97416949b5d1dbf986d93f3"), //stone fist library.Get<BlueprintAbility>("5181c2ed0190fc34b8a1162783af5bf4"), //stone call library.Get<BlueprintAbility>("1a36c8b9ed655c249a9f9e8d4731f001"), //soothing mud library.Get<BlueprintAbility>("d1afa8bc28c99104da7d784115552de5"), //spike stones library.Get<BlueprintAbility>("c66e86905f7606c4eaa5c774f0357b2b"), //stoneskin library.Get<BlueprintAbility>("989d3ed13d27d054ea2d26ab4956d075"), //summon elemental huge earth library.Get<BlueprintAbility>("facdc8851a0b3f44a8bed50f0199b83c"), //elemental body IV earth library.Get<BlueprintAbility>("65254c7a2cf18944287207e1de3e44e8"), //summon elemental elder earth library.Get<BlueprintAbility>("01300baad090d634cb1a1b2defe068d6"), //clashing rocks }; return new Shaman.Spirit("Stone", "Stone", "The skin of a shaman who selects the stone spirit takes on a rough, stony appearance. When the shaman calls upon one of this spirit’s abilities, tiny gemstones underneath her flesh pulse with a bright glow, like phosphorescent geodes glittering in a dark cave.", library.Get<BlueprintAbility>("01300baad090d634cb1a1b2defe068d6").Icon,//clashing rocks "", spirit_ability, greater_spirit_ability, true_spirit_ability, manifestation, hexes, spells); } void createHexes() { stone_stability = hex_engine.createStoneStability(prefix + "StoneStability", "Stone Stability", "The shaman receives a +4 bonus to her CMD when resisting bull rush or trip attempts as long as she is standing on the ground. At 5th level, the shaman receives Improved Trip as a bonus feat. At 10th level, the shaman receives Greater Trip as a bonus feat. The shaman does not need to meet the prerequisites of these feats." ); loadstone = hex_engine.createLoadStone(prefix + "Loadstone", "Loadstone", "The shaman causes one creature within 30 feet to become heavy and lethargic. The creature is treated as if it suffered effect of slow spell. The effect lasts for a number of rounds equal to the shaman’s level. A successful Will saving throw negates this effect. Whether or not the save is successful, the creature cannot be the target of this hex again for 24 hours." ); metal_curse = hex_engine.createMetalCurse(prefix + "MetalCurse", "Metal Curse", "The shaman causes a creature within 30 feet to become slightly magnetic until the end of the shaman’s next turn. Whenever the creature is attacked with a melee or ranged weapon constructed primarily of metal, it takes a –2 penalty to AC. At 8th and 16th levels, the penalty increases by –2 and the duration extends by 1 round. Once affected, the creature cannot be the target of this hex again for 24 hours." ); ward_of_stone = hex_engine.createWardOfStone(prefix + "WardOfStone", "Ward of Stone", "The shaman touches a willing creature (including herself ) and grants a ward of stoene. The next time the warded creature is struck with a melee attack, it is treated as if it has DR 5/adamantine. This ward lasts for 1 minute, after which it fades away if not already expended. At 8th and 16th levels, the ward lasts for one additional attack. A creature affected by this hex cannot be affected by it again for 24 hours." ); hexes = new BlueprintFeature[] { stone_stability, loadstone, metal_curse, ward_of_stone, }; } void createSpiritAbility() { var icon = library.Get<BlueprintAbility>("97d0a51ca60053047afb9aca900fb71b").Icon; //burning hands acid var resource = Helpers.CreateAbilityResource(prefix + "TouchOfAcidResource", "", "", "", null); resource.SetIncreasedByStat(3, secondary_stat); var touch_of_acid = library.CopyAndAdd<BlueprintAbility>("3ff40918d33219942929f0dbfe5d1dee", prefix + "TouchOfAcidAbility", ""); //earth domain acid dart touch_of_acid.AddComponent(Helpers.CreateSpellDescriptor(SpellDescriptor.Acid)); touch_of_acid.RemoveComponents<SpellComponent>(); touch_of_acid.RemoveComponents<AbilityResourceLogic>(); touch_of_acid.ReplaceComponent<AbilityDeliverProjectile>(Helpers.CreateDeliverTouch()); touch_of_acid.setMiscAbilityParametersTouchHarmful(); touch_of_acid.Type = AbilityType.Supernatural; touch_of_acid.Range = AbilityRange.Touch; touch_of_acid.SpellResistance = false; touch_of_acid.SetNameDescriptionIcon("Touch of Acid", Main.settings.balance_fixes ? "As a standard action, the shaman can make a melee touch attack that deals 1d8 points of acid damage plus 1d8 points for every 2 shaman levels she possesses beyond first. A shaman can use this ability a number of times per day equal to 3 + her Charisma modifier." : "As a standard action, the shaman can make a melee touch attack that deals 1d6 points of acid damage plus 1 point for every 2 shaman levels she possesses. A shaman can use this ability a number of times per day equal to 3 + her Charisma modifier.", icon); touch_of_acid.ReplaceComponent<ContextRankConfig>(c => Helpers.SetField(c, "m_Class", hex_engine.hex_classes)); var touch_of_acid_sticky = Helpers.CreateTouchSpellCast(touch_of_acid, resource); var corrosive = library.Get<BlueprintWeaponEnchantment>("633b38ff1d11de64a91d490c683ab1c8"); var corrosive_weapon_feature = Helpers.CreateFeature(prefix + "TouchOfAcidCorrosiveWeaponFeature", "", "", "", null, FeatureGroup.None, Helpers.Create<NewMechanics.EnchantmentMechanics.PersistentWeaponEnchantment>(p => p.enchant = corrosive) ); corrosive_weapon_feature.HideInCharacterSheetAndLevelUp = true; spirit_ability = Helpers.CreateFeature(prefix + "TouchOfAcidFeature", touch_of_acid.Name, touch_of_acid.Description + " At 11th level, any weapon she wields is treated as a corrosive weapon.", "", touch_of_acid.Icon, FeatureGroup.None, Helpers.CreateAddFact(touch_of_acid_sticky), Helpers.CreateAddAbilityResource(resource), Helpers.CreateAddFeatureOnClassLevel(corrosive_weapon_feature, 11, hex_engine.hex_classes) ); } void createGreaterSpiritAbility() { var resource = Helpers.CreateAbilityResource(prefix + "BodyOfEarthResource", "", "", "", null); resource.SetFixedResource(3); var icon = library.Get<BlueprintAbility>("4aa7942c3e62a164387a73184bca3fc1").Icon;//disintegrate var cooldown_buff = Helpers.CreateBuff(prefix + "BodyOfEarthCooldownBuff", "Body of Earth: Cooldown", $"As a standard action, she can cause jagged pieces of stone to explode from her body in a 10-foot-radius burst. This deals 1d{BalanceFixes.getDamageDie(DiceType.D6)} points of piercing damage per 2 shaman levels she possesses. A successful Reflex saving throw halves this damage. The shaman can use this ability three times per day, but she must wait 1d4 rounds between each use.", "", icon, null); var apply_cooldown = Common.createContextActionApplyBuff(cooldown_buff, Helpers.CreateContextDuration(0, diceType: DiceType.D4, diceCount: 1), dispellable: false); var dmg = Helpers.CreateActionDealDamage(PhysicalDamageForm.Piercing, Helpers.CreateContextDiceValue(BalanceFixes.getDamageDie(DiceType.D6), Helpers.CreateContextValue(AbilityRankType.Default)), isAoE: true, halfIfSaved: true); var effect = Helpers.CreateConditional(Common.createContextConditionIsCaster(), null, Common.createContextActionSavingThrow(SavingThrowType.Reflex, Helpers.CreateActionList(dmg)) ); var body_of_Earth_ability = Helpers.CreateAbility(prefix + "BodyOfEarthAbility", "Body of Earth", cooldown_buff.Description, "", icon, AbilityType.Supernatural, CommandType.Standard, AbilityRange.Personal, "", Helpers.reflexHalfDamage, Helpers.CreateRunActions(effect), Helpers.CreateContextRankConfig(baseValueType: ContextRankBaseValueType.ClassLevel, progression: ContextRankProgression.Div2, classes: hex_engine.hex_classes), Helpers.CreateAbilityTargetsAround(10.Feet(), TargetType.Any), Common.createAbilitySpawnFx("2644dac00cee8b840a35f2445c4dffd9", anchor: AbilitySpawnFxAnchor.Caster), Common.createContextCalculateAbilityParamsBasedOnClasses(hex_engine.hex_classes, primary_stat), Common.createAbilityExecuteActionOnCast(Helpers.CreateActionList(Common.createContextActionOnContextCaster(apply_cooldown))), Common.createAbilityCasterHasNoFacts(cooldown_buff), Helpers.CreateResourceLogic(resource) ); body_of_Earth_ability.setMiscAbilityParametersSelfOnly(); body_of_Earth_ability.AddComponent(Common.createAbilityCasterHasNoFacts(cooldown_buff)); greater_spirit_ability = Common.AbilityToFeature(body_of_Earth_ability, false); greater_spirit_ability.AddComponents(Common.createMaterialDR(Helpers.CreateContextValue(AbilityRankType.Default), PhysicalDamageMaterial.Adamantite), Helpers.CreateContextRankConfig(baseValueType: ContextRankBaseValueType.ClassLevel, progression: ContextRankProgression.DivStep, classes: hex_engine.hex_classes, stepLevel: 4), Helpers.CreateAddAbilityResource(resource) ); greater_spirit_ability.SetDescription("The shaman gains DR 2/adamantine. This DR increases by 1 for every 4 levels beyond 8th the shaman possesses. In addition, as a standard action, she can cause jagged pieces of stone to explode from her body in a 10-foot-radius burst. This deals 1d6 points of piercing damage per 2 shaman levels she possesses. A successful Reflex saving throw halves this damage. The shaman can use this ability three times per day, but she must wait 1d4 rounds between each use."); } void createTrueSpiritAbility() { var resource = Helpers.CreateAbilityResource(prefix + "StoneElementalFormResource", "", "", "", null); resource.SetFixedResource(1); var buff = library.CopyAndAdd<BlueprintBuff>("f0826c3794c158c4cbbe9ceb4210d6d6", prefix + "StoneElementalFormBuff", ""); buff.SetName("Elemental Form (Huge Earth Elemental)"); var ability = library.CopyAndAdd<BlueprintAbility>("e49d2cde42f25e546826600d11b4833e", prefix + "StoneElementalFormAbility", ""); ability.ReplaceComponent<ContextRankConfig>(c => Helpers.SetField(c, "m_Class", hex_engine.hex_classes)); ability.ReplaceComponent<AbilityResourceLogic>(a => a.RequiredResource = resource); ability.ReplaceComponent<AbilityTargetHasFact>(a => a.CheckedFacts = new BlueprintUnitFact[] { buff }); ability.ReplaceComponent<AbilityEffectRunAction>(a => a.Actions = Helpers.CreateActionList(Common.changeAction<ContextActionApplyBuff>(a.Actions.Actions, b => b.Buff = buff) ) ); ability.SetName("Elemental Form (Huge Earth Elemental)"); true_spirit_ability = Common.AbilityToFeature(ability, false); true_spirit_ability.SetDescription(Helpers.CreateString(true_spirit_ability.name + "2.Description", "As a standard action, the shaman assumes the form of a Huge (or smaller) earth elemental, as elemental body IV with a duration of 1 hour per level. The shaman can use this ability once per day.")); true_spirit_ability.AddComponent(Helpers.CreateAddAbilityResource(resource)); } void createManifestation() { manifestation = Helpers.CreateFeature(prefix + "StoneManifestationFeature", "Manifestation", "Upon reaching 20th level, the shaman becomes a being of acid and earth. The shaman gains acid resistance 30. She can also apply any one of the following feats to any acid or earth spell she casts without increasing the spell’s level or casting time: Reach Spell, Extend Spell. She doesn’t need to possess these feats to use this ability.", "", library.Get<BlueprintProgression>("32393034410fb2f4d9c8beaa5c8c8ab7").Icon, //wall of acid FeatureGroup.None, Common.createEnergyDR(30, DamageEnergyType.Acid)); var extend = Common.CreateMetamagicAbility(manifestation, "Extend", "Extend Spell (Acid)", Kingmaker.UnitLogic.Abilities.Metamagic.Extend, SpellDescriptor.Acid | (SpellDescriptor)AdditionalSpellDescriptors.ExtraSpellDescriptor.Earth, "", ""); extend.Group = ActivatableAbilityGroupExtension.ShamanStoneMetamagic.ToActivatableAbilityGroup(); var reach = Common.CreateMetamagicAbility(manifestation, "Reach", "Reach Spell (Acid)", Kingmaker.UnitLogic.Abilities.Metamagic.Reach, SpellDescriptor.Acid | (SpellDescriptor)AdditionalSpellDescriptors.ExtraSpellDescriptor.Earth, "", ""); reach.Group = ActivatableAbilityGroupExtension.ShamanStoneMetamagic.ToActivatableAbilityGroup(); manifestation.AddComponent(Helpers.CreateAddFacts(extend, reach)); } } } }
412
0.939865
1
0.939865
game-dev
MEDIA
0.718277
game-dev
0.601071
1
0.601071
MemoriesOfTime/Nukkit-MOT
1,158
src/main/java/cn/nukkit/event/entity/EntityDamageBlockedEvent.java
package cn.nukkit.event.entity; import cn.nukkit.entity.Entity; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class EntityDamageBlockedEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final EntityDamageEvent damage; private final boolean knockBackAttacker; private final boolean animation; public EntityDamageBlockedEvent(Entity entity, EntityDamageEvent damage, boolean knockBack, boolean animation) { this.entity = entity; this.damage = damage; this.knockBackAttacker = knockBack; this.animation = animation; } public EntityDamageEvent.DamageCause getCause() { return damage.getCause(); } public Entity getAttacker() { return damage.getEntity(); } public EntityDamageEvent getDamage() { return damage; } public boolean getKnockBackAttacker() { return knockBackAttacker; } public boolean getAnimation() { return animation; } }
412
0.688217
1
0.688217
game-dev
MEDIA
0.916582
game-dev
0.530616
1
0.530616
FrozenStormInteractive/Unreal-Batch-Rename-Tool
3,168
Source/BatchRenameTool/Private/BatchRenameToolModel.cpp
/* * MIT License * * Copyright (c) 2022 Frozen Storm Interactive, Yoann Potinet * * 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 "BatchRenameToolModel.h" void FBatchRenameToolModel::AddReferencedObjects(FReferenceCollector& Collector) { Collector.AddReferencedObjects(Operations); Collector.AddReferencedObject(SelectedOperation); } void FBatchRenameToolModel::AddOperation(TObjectPtr<UBatchRenamingOperation> Operation, bool bSelect) { if (IsValid(Operation) && !Operations.Contains(Operation)) { Operations.Add(Operation); OnOperationListModifiedDelegate.Broadcast(); if (bSelect) { SelectOperation(Operation); } } } void FBatchRenameToolModel::AddOperation(TObjectPtr<UBatchRenamingOperationFactory> Factory, bool bSelect) { AddOperation(Factory->Create(), bSelect); } void FBatchRenameToolModel::RemoveOperation(TObjectPtr<UBatchRenamingOperation> Operation) { if (IsValid(Operation)) { Operations.Remove(Operation); OnOperationListModifiedDelegate.Broadcast(); } } void FBatchRenameToolModel::MoveOperationUp(TObjectPtr<UBatchRenamingOperation> Operation) { if (IsValid(Operation)) { const int32 Index = Operations.Find(Operation); if (Index != INDEX_NONE && Index > 0) { Operations.Swap(Index, Index - 1); OnOperationListModifiedDelegate.Broadcast(); } } } void FBatchRenameToolModel::MoveOperationDown(TObjectPtr<UBatchRenamingOperation> Operation) { if (IsValid(Operation)) { const int32 Index = Operations.Find(Operation); if (Index != INDEX_NONE && Index < Operations.Num() - 1) { Operations.Swap(Index, Index + 1); OnOperationListModifiedDelegate.Broadcast(); } } } void FBatchRenameToolModel::SelectOperation(const TObjectPtr<UBatchRenamingOperation>& Operation) { if ((Operation == nullptr || Operations.Contains(Operation)) && Operation != SelectedOperation) { SelectedOperation = Operation; OnSelectionChangedDelegate.Broadcast(); } }
412
0.95252
1
0.95252
game-dev
MEDIA
0.434031
game-dev
0.946877
1
0.946877
Magneticraft-Team/Magneticraft
8,030
ignore/test/block/BlockElectricConnector.kt
@file:Suppress("DEPRECATION", "OverridingDeprecatedMember") package block import com.cout970.magneticraft.api.energy.IManualConnectionHandler import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.tileentity.TraitElectricity import com.cout970.magneticraft.misc.tileentity.getTile import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.ELECTRIC_NODE_HANDLER import com.cout970.magneticraft.registry.MANUAL_CONNECTION_HANDLER import com.cout970.magneticraft.registry.fromTile import com.cout970.magneticraft.tileentity.TileBase import com.cout970.magneticraft.tileentity.electric.TileElectricConnector import com.cout970.magneticraft.tilerenderer.PIXEL import com.cout970.magneticraft.util.vector.plus import com.cout970.magneticraft.util.vector.times import com.cout970.magneticraft.util.vector.toAABBWith import com.cout970.magneticraft.util.vector.toVec3d import net.minecraft.block.Block import net.minecraft.block.ITileEntityProvider import net.minecraft.block.material.Material import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumBlockRenderType import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.util.text.TextComponentTranslation import net.minecraft.world.IBlockAccess import net.minecraft.world.World import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.capabilities.ICapabilityProvider import tileentity.electric.TileElectricConnector /** * Created by cout970 on 29/06/2016. */ object BlockElectricConnector : BlockMultiState(Material.IRON, "electric_connector"), ITileEntityProvider, IManualConnectionHandler, ICapabilityProvider { override fun onBlockActivated(worldIn: World, pos: BlockPos, state: IBlockState?, playerIn: EntityPlayer, hand: EnumHand?, heldItem: ItemStack?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if (playerIn.isSneaking && playerIn.heldItemMainhand == null) { val te = worldIn.getTile<TileBase>(pos) if (te != null) { val trait = te.traits.find { it is TraitElectricity } if (trait is TraitElectricity) { trait.autoConnectWires = !trait.autoConnectWires if (!trait.autoConnectWires) { trait.clearWireConnections() } if (worldIn.isServer) { if (trait.autoConnectWires) { playerIn.addChatComponentMessage( TextComponentTranslation("text.magneticraft.auto_connect.activate")) } else { playerIn.addChatComponentMessage( TextComponentTranslation("text.magneticraft.auto_connect.deactivate")) } } return true } } } return super.onBlockActivated(worldIn, pos, state, playerIn, hand, heldItem, side, hitX, hitY, hitZ) } override fun getBoundingBox(state: IBlockState, source: IBlockAccess?, pos: BlockPos?): AxisAlignedBB { val facing = state[PROPERTY_FACING]!! return when (facing) { EnumFacing.DOWN -> { Vec3d(PIXEL * 5, 0.0, PIXEL * 5) toAABBWith Vec3d(1.0 - PIXEL * 5, PIXEL * 5, 1.0 - PIXEL * 5) } EnumFacing.UP -> { Vec3d(PIXEL * 5, 1.0 - PIXEL * 5, PIXEL * 5) toAABBWith Vec3d(1.0 - PIXEL * 5, 1.0, 1.0 - PIXEL * 5) } EnumFacing.NORTH -> { Vec3d(PIXEL * 5, PIXEL * 5, 0.0) toAABBWith Vec3d(1.0 - PIXEL * 5, 1.0 - PIXEL * 5, PIXEL * 5) } EnumFacing.SOUTH -> { Vec3d(PIXEL * 5, PIXEL * 5, 1.0 - PIXEL * 5) toAABBWith Vec3d(1.0 - PIXEL * 5, 1.0 - PIXEL * 5, 1.0) } EnumFacing.WEST -> { Vec3d(0.0, PIXEL * 5, PIXEL * 5) toAABBWith Vec3d(PIXEL * 5, 1.0 - PIXEL * 5, 1.0 - PIXEL * 5) } EnumFacing.EAST -> { Vec3d(1 - PIXEL * 5, PIXEL * 5, PIXEL * 5) toAABBWith Vec3d(1.0, 1.0 - PIXEL * 5, 1.0 - PIXEL * 5) } } } override fun isFullBlock(state: IBlockState?) = false override fun isOpaqueCube(state: IBlockState?) = false override fun isFullCube(state: IBlockState?) = false override fun isVisuallyOpaque() = false override fun createNewTileEntity(worldIn: World?, meta: Int): TileEntity = TileElectricConnector() override fun onBlockPlaced(worldIn: World?, pos: BlockPos?, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float, meta: Int, placer: EntityLivingBase?): IBlockState { return defaultState.withProperty(PROPERTY_FACING, facing.opposite) } override fun getRenderType(state: IBlockState): EnumBlockRenderType = EnumBlockRenderType.INVISIBLE override fun getMetaFromState(state: IBlockState): Int = state[PROPERTY_FACING].ordinal override fun getStateFromMeta(meta: Int): IBlockState = defaultState.withProperty(PROPERTY_FACING, EnumFacing.getFront(meta)) override fun createBlockState(): BlockStateContainer = BlockStateContainer(this, PROPERTY_FACING) override fun getBasePos(thisBlock: BlockPos?, world: World?, player: EntityPlayer?, side: EnumFacing?, stack: ItemStack?): BlockPos? = thisBlock override fun connectWire(otherBlock: BlockPos, thisBlock: BlockPos, world: World, player: EntityPlayer, side: EnumFacing, stack: ItemStack): Boolean { val tile = world.getTile<TileElectricConnector>(thisBlock) val other = world.getTileEntity(otherBlock) if (tile == null || other == null) { return false } val handler = ELECTRIC_NODE_HANDLER!!.fromTile(other) ?: return false return tile.connectWire(handler, side) } override fun canPlaceBlockOnSide(worldIn: World, pos: BlockPos, side: EnumFacing): Boolean { return super.canPlaceBlockOnSide(worldIn, pos, side) && canStayInSide(worldIn, pos, side.opposite) } //pos, block to place the connector //side PROPERTY_FACING in the connector fun canStayInSide(worldIn: World, pos: BlockPos, side: EnumFacing): Boolean { if (worldIn.isSideSolid(pos.offset(side), side.opposite, false)) return true var box = Vec3d(0.5 - PIXEL, 0.5 - PIXEL, 0.5 - PIXEL) toAABBWith Vec3d(0.5 + PIXEL, 0.5 + PIXEL, 0.5 + PIXEL) val temp = side.directionVec.toVec3d() * 0.625 + Vec3d(0.5, 0.5, 0.5) val blockPos = pos.offset(side) box = box.union(temp toAABBWith temp).offset(pos) val state = worldIn.getBlockState(blockPos) val list = mutableListOf<AxisAlignedBB>() state.addCollisionBoxToList(worldIn, blockPos, box, list, null) return list.isNotEmpty() } override fun neighborChanged(state: IBlockState, world: World, pos: BlockPos, blockIn: Block?) { val dir = state[PROPERTY_FACING] if (!canStayInSide(world, pos, dir)) { world.destroyBlock(pos, true) } super.neighborChanged(state, world, pos, blockIn) } @Suppress("UNCHECKED_CAST") override fun <T : Any?> getCapability(capability: Capability<T>?, facing: EnumFacing?): T = this as T override fun hasCapability(capability: Capability<*>?, facing: EnumFacing?): Boolean = capability == MANUAL_CONNECTION_HANDLER }
412
0.914185
1
0.914185
game-dev
MEDIA
0.992863
game-dev
0.915685
1
0.915685
Source-SDK-Archives/source-sdk-2004
185,037
src_mod/dlls/player.cpp
//========= Copyright 1996-2001, Valve LLC, All rights reserved. ============ // // Purpose: Functions dealing with the player. // //============================================================================= #include "cbase.h" #include "const.h" #include "baseplayer_shared.h" #include "trains.h" #include "soundent.h" #include "gib.h" #include "shake.h" #include "decals.h" #include "gamerules.h" #include "game.h" #include "entityapi.h" #include "entitylist.h" #include "eventqueue.h" #include "worldsize.h" #include "isaverestore.h" #include "globalstate.h" #include "basecombatweapon.h" #include "ai_basenpc.h" #include "ai_network.h" #include "ai_node.h" #include "ai_networkmanager.h" #include "ammodef.h" #include "mathlib.h" #include "ndebugoverlay.h" #include "baseviewmodel.h" #include "in_buttons.h" #include "client.h" #include "team.h" #include "particle_smokegrenade.h" #include "IEffects.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "movehelper_server.h" #include "igamemovement.h" #include "saverestoretypes.h" #include "iservervehicle.h" #include "movevars_shared.h" #include "vcollide_parse.h" #include "player_command.h" #include "vehicle_base.h" #include "AI_Criteria.h" #include "globals.h" #include "usermessages.h" #include "gamevars_shared.h" #include "world.h" #include "physobj.h" #include "KeyValues.h" #include "coordsize.h" #include "vphysics/player_controller.h" #include "saverestore_utlvector.h" #include "hltvdirector.h" #include "nav_mesh.h" #include "env_zoom.h" #ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out #include "bot/bot.h" #endif #ifdef HL2_DLL #include "combine_mine.h" #include "weapon_physcannon.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" static ConVar old_armor( "player_old_armor", "0" ); static ConVar physicsshadowupdate_render( "physicsshadowupdate_render", "0" ); // This is declared in the engine, too ConVar sv_noclipduringpause( "sv_noclipduringpause", "0", FCVAR_REPLICATED | FCVAR_CHEAT, "If cheats are enabled, then you can noclip with the game paused (for doing screenshots, etc.)." ); extern ConVar sv_maxunlag; // TIME BASED DAMAGE AMOUNT // tweak these values based on gameplay feedback: #define PARALYZE_DURATION 2 // number of 2 second intervals to take damage #define PARALYZE_DAMAGE 1.0 // damage to take each 2 second interval #define NERVEGAS_DURATION 2 #define NERVEGAS_DAMAGE 5.0 #define POISON_DURATION 5 #define POISON_DAMAGE 2.0 #define RADIATION_DURATION 2 #define RADIATION_DAMAGE 1.0 #define ACID_DURATION 2 #define ACID_DAMAGE 5.0 #define SLOWBURN_DURATION 2 #define SLOWBURN_DAMAGE 1.0 #define SLOWFREEZE_DURATION 2 #define SLOWFREEZE_DAMAGE 1.0 //---------------------------------------------------- // Player Physics Shadow //---------------------------------------------------- #define VPHYS_MAX_DISTANCE 2.0 #define VPHYS_MAX_VEL 10 #define VPHYS_MAX_DISTSQR (VPHYS_MAX_DISTANCE*VPHYS_MAX_DISTANCE) #define VPHYS_MAX_VELSQR (VPHYS_MAX_VEL*VPHYS_MAX_VEL) extern bool g_fDrawLines; int gEvilImpulse101; bool gInitHUD = true; extern void respawn(CBaseEntity *pEdict, bool fCopyCorpse); int MapTextureTypeStepType(char chTextureType); extern void SpawnBlood(Vector vecSpot, const Vector &vecDir, int bloodColor, float flDamage); extern void AddMultiDamage( const CTakeDamageInfo &info, CBaseEntity *pEntity ); #define CMD_MOSTRECENT 0 //#define FLASH_DRAIN_TIME 1.2 //100 units/3 minutes //#define FLASH_CHARGE_TIME 0.2 // 100 units/20 seconds (seconds per unit) //#define PLAYER_MAX_SAFE_FALL_DIST 20// falling any farther than this many feet will inflict damage //#define PLAYER_FATAL_FALL_DIST 60// 100% damage inflicted if player falls this many feet //#define DAMAGE_PER_UNIT_FALLEN (float)( 100 ) / ( ( PLAYER_FATAL_FALL_DIST - PLAYER_MAX_SAFE_FALL_DIST ) * 12 ) //#define MAX_SAFE_FALL_UNITS ( PLAYER_MAX_SAFE_FALL_DIST * 12 ) // player damage adjusters ConVar sk_player_head( "sk_player_head","2" ); ConVar sk_player_chest( "sk_player_chest","1" ); ConVar sk_player_stomach( "sk_player_stomach","1" ); ConVar sk_player_arm( "sk_player_arm","1" ); ConVar sk_player_leg( "sk_player_leg","1" ); // pl BEGIN_SIMPLE_DATADESC( CPlayerState ) // DEFINE_FIELD( netname, FIELD_STRING ), // Don't stomp player name with what's in save/restore DEFINE_FIELD( v_angle, FIELD_VECTOR ), DEFINE_FIELD( deadflag, FIELD_BOOLEAN ), // this is always set to true on restore, don't bother saving it. // DEFINE_FIELD( fixangle, FIELD_INTEGER ), // DEFINE_FIELD( anglechange, FIELD_FLOAT ), // DEFINE_FIELD( hltv, FIELD_BOOLEAN ), // DEFINE_FIELD( frags, FIELD_INTEGER ), // DEFINE_FIELD( deaths, FIELD_INTEGER ), END_DATADESC() // Global Savedata for player BEGIN_DATADESC( CBasePlayer ) DEFINE_EMBEDDED( m_Local ), DEFINE_UTLVECTOR( m_hTriggerSoundscapeList, FIELD_EHANDLE ), DEFINE_EMBEDDED( pl ), DEFINE_FIELD( m_StuckLast, FIELD_INTEGER ), DEFINE_FIELD( m_nButtons, FIELD_INTEGER ), DEFINE_FIELD( m_afButtonLast, FIELD_INTEGER ), DEFINE_FIELD( m_afButtonPressed, FIELD_INTEGER ), DEFINE_FIELD( m_afButtonReleased, FIELD_INTEGER ), //DEFINE_FIELD( m_fOnTarget, FIELD_BOOLEAN ), // Don't need to restore DEFINE_FIELD( m_iObserverMode, FIELD_INTEGER ), DEFINE_FIELD( m_iObserverLastMode, FIELD_INTEGER ), DEFINE_FIELD( m_hObserverTarget, FIELD_EHANDLE ), DEFINE_FIELD( m_bForcedObserverMode, FIELD_BOOLEAN ), // DEFINE_FIELD( m_bIsRecording, FIELD_BOOLEAN ), // DEFINE_FIELD( m_hAutoAimTarget, FIELD_EHANDLE ), DEFINE_AUTO_ARRAY( m_szAnimExtension, FIELD_CHARACTER ), // DEFINE_CUSTOM_FIELD( m_Activity, ActivityDataOps() ), DEFINE_FIELD( m_nUpdateRate, FIELD_INTEGER ), DEFINE_FIELD( m_fLerpTime, FIELD_FLOAT ), DEFINE_FIELD( m_bLagCompensation, FIELD_BOOLEAN ), DEFINE_FIELD( m_bPredictWeapons, FIELD_BOOLEAN ), DEFINE_FIELD( m_vecAdditionalPVSOrigin, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecCameraPVSOrigin, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_hUseEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_iTrain, FIELD_INTEGER ), DEFINE_FIELD( m_iRespawnFrames, FIELD_FLOAT ), DEFINE_FIELD( m_afPhysicsFlags, FIELD_INTEGER ), DEFINE_FIELD( m_hVehicle, FIELD_EHANDLE ), // recreate, don't restore // DEFINE_FIELD( m_CommandContext, CUtlVector < CCommandContext > ), //DEFINE_FIELD( m_pPhysicsController, FIELD_POINTER ), //DEFINE_FIELD( m_pShadowStand, FIELD_POINTER ), //DEFINE_FIELD( m_pShadowCrouch, FIELD_POINTER ), //DEFINE_FIELD( m_vphysicsCollisionState, FIELD_INTEGER ), // DEFINE_FIELD( m_lastNavArea, CNavArea ), DEFINE_ARRAY( m_szNetworkIDString, FIELD_CHARACTER, MAX_NETWORKID_LENGTH ), DEFINE_FIELD( m_oldOrigin, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecSmoothedVelocity, FIELD_VECTOR ), //DEFINE_FIELD( m_touchedPhysObject, FIELD_BOOLEAN ), //DEFINE_FIELD( m_iPlayerSound, FIELD_INTEGER ), // Don't restore, set in Precache() DEFINE_FIELD( m_iTargetVolume, FIELD_INTEGER ), DEFINE_AUTO_ARRAY( m_rgItems, FIELD_INTEGER ), //DEFINE_FIELD( m_fNextSuicideTime, FIELD_TIME ), DEFINE_FIELD( m_flTimeStepSound, FIELD_TIME ), DEFINE_FIELD( m_flSwimTime, FIELD_TIME ), DEFINE_FIELD( m_flDuckTime, FIELD_TIME ), DEFINE_FIELD( m_flDuckJumpTime, FIELD_TIME ), DEFINE_FIELD( m_flSuitUpdate, FIELD_TIME ), DEFINE_AUTO_ARRAY( m_rgSuitPlayList, FIELD_INTEGER ), DEFINE_FIELD( m_iSuitPlayNext, FIELD_INTEGER ), DEFINE_AUTO_ARRAY( m_rgiSuitNoRepeat, FIELD_INTEGER ), DEFINE_AUTO_ARRAY( m_rgflSuitNoRepeatTime, FIELD_TIME ), DEFINE_FIELD( m_lastDamageAmount, FIELD_INTEGER ), DEFINE_FIELD( m_tbdPrev, FIELD_TIME ), //DEFINE_FIELD( m_flgeigerRange, FIELD_FLOAT ), // Don't restore, reset in Precache() //DEFINE_FIELD( m_flgeigerDelay, FIELD_FLOAT ), // Don't restore, reset in Precache() //DEFINE_FIELD( m_igeigerRangePrev, FIELD_FLOAT ), // Don't restore, reset in Precache() //DEFINE_FIELD( m_iStepLeft, FIELD_INTEGER ), // Don't need to restore //DEFINE_FIELD( m_chTextureType, FIELD_CHARACTER ), // Don't need to restore DEFINE_FIELD( m_idrowndmg, FIELD_INTEGER ), DEFINE_FIELD( m_idrownrestored, FIELD_INTEGER ), DEFINE_FIELD( m_nPoisonDmg, FIELD_INTEGER ), DEFINE_FIELD( m_nPoisonRestored, FIELD_INTEGER ), DEFINE_FIELD( m_bitsHUDDamage, FIELD_INTEGER ), DEFINE_FIELD( m_fInitHUD, FIELD_BOOLEAN ), DEFINE_FIELD( m_flDeathTime, FIELD_TIME ), //DEFINE_FIELD( m_fGameHUDInitialized, FIELD_BOOLEAN ), // only used in multiplayer games //DEFINE_FIELD( m_fWeapon, FIELD_BOOLEAN ), // Don't restore, client needs reset //DEFINE_FIELD( m_iUpdateTime, FIELD_INTEGER ), // Don't need to restore //DEFINE_FIELD( m_iClientBattery, FIELD_INTEGER ), // Don't restore, client needs reset //DEFINE_FIELD( m_iClientHideHUD, FIELD_INTEGER ), // Don't restore, client needs reset //DEFINE_FIELD( m_vecAutoAim, FIELD_VECTOR ), // Don't save/restore - this is recomputed //DEFINE_FIELD( m_lastx, FIELD_INTEGER ), //DEFINE_FIELD( m_lasty, FIELD_INTEGER ), DEFINE_FIELD( m_iFrags, FIELD_INTEGER ), DEFINE_FIELD( m_iDeaths, FIELD_INTEGER ), DEFINE_FIELD( m_flNextDecalTime, FIELD_TIME ), //DEFINE_AUTO_ARRAY( m_szTeamName, FIELD_STRING ), // mp //DEFINE_FIELD( m_bConnected, FIELD_BOOLEAN ), // from edict_t DEFINE_FIELD( m_ArmorValue, FIELD_INTEGER ), DEFINE_FIELD( m_DmgOrigin, FIELD_VECTOR ), DEFINE_FIELD( m_DmgTake, FIELD_FLOAT ), DEFINE_FIELD( m_DmgSave, FIELD_FLOAT ), DEFINE_FIELD( m_AirFinished, FIELD_TIME ), DEFINE_FIELD( m_PainFinished, FIELD_TIME ), DEFINE_FIELD( m_iPlayerLocked, FIELD_INTEGER ), DEFINE_AUTO_ARRAY( m_hViewModel, FIELD_EHANDLE ), DEFINE_AUTO_ARRAY( m_hObserverViewModel, FIELD_EHANDLE ), DEFINE_FIELD( m_flMaxspeed, FIELD_FLOAT ), DEFINE_FIELD( m_flWaterJumpTime, FIELD_TIME ), DEFINE_FIELD( m_vecWaterJumpVel, FIELD_VECTOR ), DEFINE_FIELD( m_nImpulse, FIELD_INTEGER ), DEFINE_FIELD( m_flStepSoundTime, FIELD_TIME ), DEFINE_FIELD( m_flSwimSoundTime, FIELD_TIME ), DEFINE_FIELD( m_vecLadderNormal, FIELD_VECTOR ), DEFINE_FIELD( m_flFlashTime, FIELD_TIME ), DEFINE_FIELD( m_nDrownDmgRate, FIELD_INTEGER ), // NOT SAVED //DEFINE_FIELD( m_vForcedOrigin, FIELD_VECTOR ), //DEFINE_FIELD( m_bForceOrigin, FIELD_BOOLEAN ), //DEFINE_FIELD( m_nTickBase, FIELD_INTEGER ), //DEFINE_FIELD( m_LastCmd, FIELD_ ), // DEFINE_FIELD( m_pCurrentCommand, CUserCmd ), //DEFINE_FIELD( m_bGamePaused, FIELD_BOOLEAN ), DEFINE_FIELD( m_bitsDamageType, FIELD_INTEGER ), DEFINE_AUTO_ARRAY( m_rgbTimeBasedDamage, FIELD_CHARACTER ), DEFINE_FIELD( m_fLastPlayerTalkTime, FIELD_FLOAT ), DEFINE_FIELD( m_hLastWeapon, FIELD_EHANDLE ), // DEFINE_FIELD( m_SimulatedByThisPlayer, CUtlVector < CHandle < CBaseEntity > > ), DEFINE_FIELD( m_flOldPlayerZ, FIELD_FLOAT ), DEFINE_FIELD( m_flOldPlayerViewOffsetZ, FIELD_FLOAT ), DEFINE_FIELD( m_bPlayerUnderwater, FIELD_BOOLEAN ), DEFINE_FIELD( m_hViewEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_hConstraintEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_vecConstraintCenter, FIELD_VECTOR ), DEFINE_FIELD( m_flConstraintRadius, FIELD_FLOAT ), DEFINE_FIELD( m_flConstraintWidth, FIELD_FLOAT ), DEFINE_FIELD( m_flConstraintSpeedFactor, FIELD_FLOAT ), DEFINE_FIELD( m_hZoomOwner, FIELD_EHANDLE ), DEFINE_FIELD( m_flLaggedMovementValue, FIELD_FLOAT ), DEFINE_FIELD( m_vNewVPhysicsPosition, FIELD_VECTOR ), DEFINE_FIELD( m_vNewVPhysicsVelocity, FIELD_VECTOR ), // Function Pointers DEFINE_FUNCTION( PlayerDeathThink ), // Inputs DEFINE_INPUTFUNC( FIELD_INTEGER, "SetHealth", InputSetHealth ), END_DATADESC() BEGIN_PREDICTION_DATA_NO_BASE( CPlayerState ) END_PREDICTION_DATA() BEGIN_PREDICTION_DATA( CBasePlayer ) END_PREDICTION_DATA() int giPrecacheGrunt = 0; edict_t *CBasePlayer::s_PlayerEdict = NULL; inline bool ShouldRunCommandsInContext( const CCommandContext *ctx ) { // TODO: This should be enabled at some point. If usercmds can run while paused, then // they can create entities which will never die and it will fill up the entity list. #ifdef NO_USERCMDS_DURING_PAUSE return !ctx->paused || sv_noclipduringpause.GetInt(); #else return true; #endif } //----------------------------------------------------------------------------- // Purpose: // Output : CBaseViewModel //----------------------------------------------------------------------------- CBaseViewModel *CBasePlayer::GetViewModel( int index /*= 0*/ ) { Assert( index >= 0 && index < MAX_VIEWMODELS ); return m_hViewModel[ index ].Get(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::CreateViewModel( int index /*=0*/ ) { Assert( index >= 0 && index < MAX_VIEWMODELS ); if ( GetViewModel( index ) ) return; CBaseViewModel *vm = ( CBaseViewModel * )CreateEntityByName( "viewmodel" ); if ( vm ) { vm->SetAbsOrigin( GetAbsOrigin() ); vm->SetOwner( this ); vm->SetIndex( index ); DispatchSpawn( vm ); vm->FollowEntity( this ); m_hViewModel.Set( index, vm ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::DestroyViewModels( void ) { int i; for ( i = MAX_VIEWMODELS - 1; i >= 0; i-- ) { CBaseViewModel *vm = GetViewModel( i ); if ( !vm ) continue; UTIL_Remove( vm ); m_hViewModel.Set( i, NULL ); } } //----------------------------------------------------------------------------- // Purpose: Static member function to create a player of the specified class // Input : *className - // *ed - // Output : CBasePlayer //----------------------------------------------------------------------------- CBasePlayer *CBasePlayer::CreatePlayer( const char *className, edict_t *ed ) { CBasePlayer *player; CBasePlayer::s_PlayerEdict = ed; player = ( CBasePlayer * )CreateEntityByName( className ); return player; } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- CBasePlayer::CBasePlayer( ) { CONSTRUCT_PREDICTABLE( CBasePlayer ); AddEFlags( EFL_NO_AUTO_EDICT_ATTACH ); #ifdef _DEBUG m_vecAutoAim.Init(); m_vecAdditionalPVSOrigin.Init(); m_vecCameraPVSOrigin.Init(); m_DmgOrigin.Init(); m_vecLadderNormal.Init(); m_oldOrigin.Init(); m_vecSmoothedVelocity.Init(); #endif if ( s_PlayerEdict ) { // take the assigned edict_t and attach it Assert( s_PlayerEdict != NULL ); NetworkProp()->AttachEdict( s_PlayerEdict ); s_PlayerEdict = NULL; } m_flFlashTime = -1; pl.fixangle = FIXANGLE_ABSOLUTE; pl.hltv = false; pl.frags = 0; pl.deaths = 0; m_iHealth = 0; Weapon_SetLast( NULL ); m_bitsDamageType = 0; m_bForceOrigin = false; m_hVehicle = NULL; m_pCurrentCommand = NULL; // Setup our default FOV m_Local.m_iDefaultFOV = g_pGameRules->DefaultFOV(); m_hZoomOwner = NULL; m_nUpdateRate = 20; // cl_updaterate defualt m_fLerpTime = 0.1f; // cl_interp default m_bPredictWeapons = true; m_bLagCompensation = false; m_flLaggedMovementValue = 1.0f; m_StuckLast = 0; m_impactEnergyScale = 1.0f; m_fLastPlayerTalkTime = 0.0f; m_PlayerInfo.SetParent( this ); ResetObserverMode(); } CBasePlayer::~CBasePlayer( ) { VPhysicsDestroyObject(); } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- void CBasePlayer::UpdateOnRemove( void ) { VPhysicsDestroyObject(); // Remove him from his current team if ( GetTeam() ) { GetTeam()->RemovePlayer( this ); } // Chain at end to mimic destructor unwind order BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Purpose: // Input : **pvs - // **pas - //----------------------------------------------------------------------------- void CBasePlayer::SetupVisibility( CBaseEntity *pViewEntity, unsigned char *pvs, int pvssize ) { // If we have a viewentity, we don't add the player's origin. if ( pViewEntity ) return; Vector org; org = EyePosition(); engine->AddOriginToPVS( org ); } int CBasePlayer::UpdateTransmitState() { // always call ShouldTransmit() for players return SetTransmitState( FL_EDICT_FULLCHECK ); } int CBasePlayer::ShouldTransmit( const CCheckTransmitInfo *pInfo ) { // Allow me to introduce myself to, er, myself. // I.e., always update the recipient player data even if it's nodraw (first person mode) if ( pInfo->m_pClientEnt == edict() ) { return FL_EDICT_ALWAYS; } // when HLTV is connected and spectators press +USE, they // signal that they are recording a intersting scene // so transmit these 'cameramans' to the HLTV client if ( m_bIsRecording ) { CBaseEntity *pRecipientEntity = CBaseEntity::Instance( pInfo->m_pClientEnt ); Assert( pRecipientEntity->IsPlayer() ); CBasePlayer *pRecipientPlayer = static_cast<CBasePlayer*>( pRecipientEntity ); if ( pRecipientPlayer->IsHLTV() ) { // HACK force calling RecomputePVSInformation to update PVS data NetworkProp()->AreaNum(); return FL_EDICT_ALWAYS; } } if ( IsEffectActive( EF_NODRAW ) ) { return FL_EDICT_DONTSEND; } return BaseClass::ShouldTransmit( pInfo ); } bool CBasePlayer::WantsLagCompensationOnEntity( const CBasePlayer *pPlayer, const CUserCmd *pCmd, const CBitVec<MAX_EDICTS> *pEntityTransmitBits ) const { // Team members shouldn't be adjusted unless friendly fire is on. if ( !friendlyfire.GetInt() && pPlayer->GetTeamNumber() == GetTeamNumber() ) return false; // If this entity hasn't been transmitted to us and acked, then don't bother lag compensating it. if ( pEntityTransmitBits && !pEntityTransmitBits->Get( pPlayer->entindex() ) ) return false; const Vector &vMyOrigin = GetAbsOrigin(); const Vector &vHisOrigin = pPlayer->GetAbsOrigin(); // get max distance player could have moved within max lag compensation time, // multiply by 1.5 to to avoid "dead zones" (sqrt(2) would be the exact value) float maxDistance = 1.5 * pPlayer->MaxSpeed() * sv_maxunlag.GetFloat(); // If the player is within this distance, lag compensate them in case they're running past us. if ( vHisOrigin.DistTo( vMyOrigin ) < maxDistance ) return true; // If their origin is not within a 45 degree cone in front of us, no need to lag compensate. Vector vForward; AngleVectors( pCmd->viewangles, &vForward ); Vector vDiff = vHisOrigin - vMyOrigin; VectorNormalize( vDiff ); float flCosAngle = 0.707107f; // 45 degree angle if ( vForward.Dot( vDiff ) < flCosAngle ) return false; return true; } //----------------------------------------------------------------------------- // Sets the view angles //----------------------------------------------------------------------------- void CBasePlayer::SnapEyeAngles( const QAngle &viewAngles ) { pl.v_angle = viewAngles; pl.fixangle = FIXANGLE_ABSOLUTE; } //----------------------------------------------------------------------------- // Purpose: // Input : iSpeed - // iMax - // Output : int //----------------------------------------------------------------------------- int TrainSpeed(int iSpeed, int iMax) { float fSpeed, fMax; int iRet = 0; fMax = (float)iMax; fSpeed = iSpeed; fSpeed = fSpeed/fMax; if (iSpeed < 0) iRet = TRAIN_BACK; else if (iSpeed == 0) iRet = TRAIN_NEUTRAL; else if (fSpeed < 0.33) iRet = TRAIN_SLOW; else if (fSpeed < 0.66) iRet = TRAIN_MEDIUM; else iRet = TRAIN_FAST; return iRet; } void CBasePlayer::DeathSound( void ) { // temporarily using pain sounds for death sounds // Did we die from falling? if ( m_bitsDamageType & DMG_FALL ) { // They died in the fall. Play a splat sound. EmitSound( "Player.FallGib" ); } else { EmitSound( "Player.Death" ); } // play one of the suit death alarms if ( IsSuitEquipped() ) { UTIL_EmitGroupnameSuit(edict(), "HEV_DEAD"); } } // override takehealth // bitsDamageType indicates type of damage healed. int CBasePlayer::TakeHealth( float flHealth, int bitsDamageType ) { // clear out any damage types we healed. // UNDONE: generic health should not heal any // UNDONE: time-based damage if (m_takedamage) { m_bitsDamageType &= ~(bitsDamageType & ~DMG_TIMEBASED); } return BaseClass::TakeHealth (flHealth, bitsDamageType); } //----------------------------------------------------------------------------- // Purpose: Draw all overlays (should be implemented in cascade by subclass to add // any additional non-text overlays) // Input : // Output : Current text offset from the top //----------------------------------------------------------------------------- void CBasePlayer::DrawDebugGeometryOverlays(void) { // -------------------------------------------------------- // If in buddha mode and dead draw lines to indicate death // -------------------------------------------------------- if ((m_debugOverlays & OVERLAY_BUDDHA_MODE) && m_iHealth == 1) { Vector vBodyDir = BodyDirection2D( ); Vector eyePos = EyePosition() + vBodyDir*10.0; Vector vUp = Vector(0,0,8); Vector vSide; CrossProduct( vBodyDir, vUp, vSide); NDebugOverlay::Line(eyePos+vSide+vUp, eyePos-vSide-vUp, 255,0,0, false, 0); NDebugOverlay::Line(eyePos+vSide-vUp, eyePos-vSide+vUp, 255,0,0, false, 0); } BaseClass::DrawDebugGeometryOverlays(); } //========================================================= // TraceAttack //========================================================= void CBasePlayer::TraceAttack( const CTakeDamageInfo &inputInfo, const Vector &vecDir, trace_t *ptr ) { if ( m_takedamage ) { CTakeDamageInfo info = inputInfo; // -------------------------------------------------- // If an NPC check if friendly fire is disallowed // -------------------------------------------------- CAI_BaseNPC *pNPC = info.GetAttacker()->MyNPCPointer(); if ( pNPC && (pNPC->CapabilitiesGet() & bits_CAP_NO_HIT_PLAYER) && pNPC->IRelationType( this ) != D_HT ) { return; } // Prevent team damage here so blood doesn't appear if ( info.GetAttacker()->IsPlayer() ) { if ( !g_pGameRules->FPlayerCanTakeDamage( this, info.GetAttacker() ) ) return; } SetLastHitGroup( ptr->hitgroup ); switch ( ptr->hitgroup ) { case HITGROUP_GENERIC: break; case HITGROUP_HEAD: info.ScaleDamage( sk_player_head.GetFloat() ); break; case HITGROUP_CHEST: info.ScaleDamage( sk_player_chest.GetFloat() ); break; case HITGROUP_STOMACH: info.ScaleDamage( sk_player_stomach.GetFloat() ); break; case HITGROUP_LEFTARM: case HITGROUP_RIGHTARM: info.ScaleDamage( sk_player_arm.GetFloat() ); break; case HITGROUP_LEFTLEG: case HITGROUP_RIGHTLEG: info.ScaleDamage( sk_player_leg.GetFloat() ); break; default: break; } SpawnBlood(ptr->endpos, vecDir, BloodColor(), info.GetDamage());// a little surface blood. TraceBleed( info.GetDamage(), vecDir, ptr, info.GetDamageType() ); AddMultiDamage( info, this ); } } //------------------------------------------------------------------------------ // Purpose : Do some kind of damage effect for the type of damage // Input : // Output : //------------------------------------------------------------------------------ void CBasePlayer::DamageEffect(float flDamage, int fDamageType) { if (fDamageType & DMG_CRUSH) { //Red damage indicator color32 red = {128,0,0,128}; UTIL_ScreenFade( this, red, 1.0f, 0.1f, FFADE_IN ); } else if (fDamageType & DMG_DROWN) { //Red damage indicator color32 blue = {0,0,128,128}; UTIL_ScreenFade( this, blue, 1.0f, 0.1f, FFADE_IN ); } else if (fDamageType & DMG_SLASH) { // If slash damage shoot some blood SpawnBlood(EyePosition(), g_vecAttackDir, BloodColor(), flDamage); } else if (fDamageType & DMG_PLASMA) { // Blue screen fade color32 blue = {0,0,255,100}; UTIL_ScreenFade( this, blue, 0.2, 0.4, FFADE_MODULATE ); // Very small screen shake ViewPunch(QAngle(random->RandomInt(-0.1,0.1), random->RandomInt(-0.1,0.1), random->RandomInt(-0.1,0.1))); // Burn sound EmitSound( "Player.PlasmaDamage" ); } else if (fDamageType & DMG_SONIC) { // Sonic damage sound EmitSound( "Player.SonicDamage" ); } else if ( fDamageType & DMG_BULLET ) { EmitSound( "Flesh.BulletImpact" ); } } /* Take some damage. NOTE: each call to OnTakeDamage with bitsDamageType set to a time-based damage type will cause the damage time countdown to be reset. Thus the ongoing effects of poison, radiation etc are implemented with subsequent calls to OnTakeDamage using DMG_GENERIC. */ // Old values #define OLD_ARMOR_RATIO 0.2 // Armor Takes 80% of the damage #define OLD_ARMOR_BONUS 0.5 // Each Point of Armor is work 1/x points of health // New values #define ARMOR_RATIO 0.2 #define ARMOR_BONUS 1.0 int CBasePlayer::OnTakeDamage( const CTakeDamageInfo &inputInfo ) { // have suit diagnose the problem - ie: report damage type int bitsDamage = inputInfo.GetDamageType(); int ffound = true; int fmajor; int fcritical; int fTookDamage; int ftrivial; float flRatio; float flBonus; float flHealthPrev = m_iHealth; CTakeDamageInfo info = inputInfo; IServerVehicle *pVehicle = GetVehicle(); if ( pVehicle ) { // Players don't take blast or radiation damage while in vehicles. // The vehicle has to deal it to him if ( info.GetDamageType() & (DMG_BLAST|DMG_RADIATION) ) return 0; info.ScaleDamage(pVehicle->DamageModifier(info)); } if ( GetFlags() & FL_GODMODE ) return 0; if ( m_debugOverlays & OVERLAY_BUDDHA_MODE ) { if ((m_iHealth - info.GetDamage()) <= 0) { m_iHealth = 1; return 0; } } // Early out if there's no damage if ( !info.GetDamage() ) return 0; if( old_armor.GetBool() ) { flBonus = OLD_ARMOR_BONUS; flRatio = OLD_ARMOR_RATIO; } else { flBonus = ARMOR_BONUS; flRatio = ARMOR_RATIO; } if ( ( info.GetDamageType() & DMG_BLAST ) && g_pGameRules->IsMultiplayer() ) { // blasts damage armor more. flBonus *= 2; } // Already dead if ( !IsAlive() ) return 0; // go take the damage first if ( !g_pGameRules->FPlayerCanTakeDamage( this, info.GetAttacker() ) ) { // Refuse the damage return 0; } // keep track of amount of damage last sustained m_lastDamageAmount = info.GetDamage(); // Armor. if (m_ArmorValue && !(info.GetDamageType() & (DMG_FALL | DMG_DROWN | DMG_POISON | DMG_RADIATION)) )// armor doesn't protect against fall or drown damage! { float flNew = info.GetDamage() * flRatio; float flArmor; flArmor = (info.GetDamage() - flNew) * flBonus; if( !old_armor.GetBool() ) { if( flArmor < 1.0 ) { flArmor = 1.0; } } // Does this use more armor than we have? if (flArmor > m_ArmorValue) { flArmor = m_ArmorValue; flArmor *= (1/flBonus); flNew = info.GetDamage() - flArmor; m_DmgSave = m_ArmorValue; m_ArmorValue = 0; } else { m_DmgSave = flArmor; m_ArmorValue -= flArmor; } info.SetDamage( flNew ); } // this cast to INT is critical!!! If a player ends up with 0.5 health, the engine will get that // as an int (zero) and think the player is dead! (this will incite a clientside screentilt, etc) // NOTENOTE: jdw - We are now capable of retaining the matissa of this damage value and deferring its application // info.SetDamage( (int)info.GetDamage() ); // Call up to the base class fTookDamage = BaseClass::OnTakeDamage( info ); // Early out if the base class took no damage if ( !fTookDamage ) return 0; // add to the damage total for clients, which will be sent as a single // message at the end of the frame // todo: remove after combining shotgun blasts? if ( info.GetInflictor() && info.GetInflictor()->edict() ) m_DmgOrigin = info.GetInflictor()->GetAbsOrigin(); m_DmgTake += (int)info.GetDamage(); // reset damage time countdown for each type of time based damage player just sustained for (int i = 0; i < CDMG_TIMEBASED; i++) { if (info.GetDamageType() & (DMG_PARALYZE << i)) { m_rgbTimeBasedDamage[i] = 0; } } // Display any effect associate with this damage type DamageEffect(info.GetDamage(),bitsDamage); // how bad is it, doc? ftrivial = (m_iHealth > 75 || m_lastDamageAmount < 5); fmajor = (m_lastDamageAmount > 25); fcritical = (m_iHealth < 30); // handle all bits set in this damage message, // let the suit give player the diagnosis // UNDONE: add sounds for types of damage sustained (ie: burn, shock, slash ) // UNDONE: still need to record damage and heal messages for the following types // DMG_BURN // DMG_FREEZE // DMG_BLAST // DMG_SHOCK m_bitsDamageType |= bitsDamage; // Save this so we can report it to the client m_bitsHUDDamage = -1; // make sure the damage bits get resent while (fTookDamage && (!ftrivial || (bitsDamage & DMG_TIMEBASED)) && ffound && bitsDamage) { ffound = false; if (bitsDamage & DMG_CLUB) { if (fmajor) SetSuitUpdate("!HEV_DMG4", false, SUIT_NEXT_IN_30SEC); // minor fracture bitsDamage &= ~DMG_CLUB; ffound = true; } if (bitsDamage & (DMG_FALL | DMG_CRUSH)) { if (fmajor) SetSuitUpdate("!HEV_DMG5", false, SUIT_NEXT_IN_30SEC); // major fracture else SetSuitUpdate("!HEV_DMG4", false, SUIT_NEXT_IN_30SEC); // minor fracture bitsDamage &= ~(DMG_FALL | DMG_CRUSH); ffound = true; } if (bitsDamage & DMG_BULLET) { if (m_lastDamageAmount > 5) SetSuitUpdate("!HEV_DMG6", false, SUIT_NEXT_IN_30SEC); // blood loss detected //else // SetSuitUpdate("!HEV_DMG0", false, SUIT_NEXT_IN_30SEC); // minor laceration bitsDamage &= ~DMG_BULLET; ffound = true; } if (bitsDamage & DMG_SLASH) { if (fmajor) SetSuitUpdate("!HEV_DMG1", false, SUIT_NEXT_IN_30SEC); // major laceration else SetSuitUpdate("!HEV_DMG0", false, SUIT_NEXT_IN_30SEC); // minor laceration bitsDamage &= ~DMG_SLASH; ffound = true; } if (bitsDamage & DMG_SONIC) { if (fmajor) SetSuitUpdate("!HEV_DMG2", false, SUIT_NEXT_IN_1MIN); // internal bleeding bitsDamage &= ~DMG_SONIC; ffound = true; } if (bitsDamage & (DMG_POISON | DMG_PARALYZE)) { if (bitsDamage & DMG_POISON) { m_nPoisonDmg += info.GetDamage(); m_tbdPrev = gpGlobals->curtime; m_rgbTimeBasedDamage[itbd_PoisonRecover] = 0; } SetSuitUpdate("!HEV_DMG3", false, SUIT_NEXT_IN_1MIN); // blood toxins detected bitsDamage &= ~( DMG_POISON | DMG_PARALYZE ); ffound = true; } if (bitsDamage & DMG_ACID) { SetSuitUpdate("!HEV_DET1", false, SUIT_NEXT_IN_1MIN); // hazardous chemicals detected bitsDamage &= ~DMG_ACID; ffound = true; } if (bitsDamage & DMG_NERVEGAS) { SetSuitUpdate("!HEV_DET0", false, SUIT_NEXT_IN_1MIN); // biohazard detected bitsDamage &= ~DMG_NERVEGAS; ffound = true; } if (bitsDamage & DMG_RADIATION) { SetSuitUpdate("!HEV_DET2", false, SUIT_NEXT_IN_1MIN); // radiation detected bitsDamage &= ~DMG_RADIATION; ffound = true; } if (bitsDamage & DMG_SHOCK) { bitsDamage &= ~DMG_SHOCK; ffound = true; } } m_Local.m_vecPunchAngle.SetX( -2 ); if (fTookDamage && !ftrivial && fmajor && flHealthPrev >= 75) { // first time we take major damage... // turn automedic on if not on SetSuitUpdate("!HEV_MED1", false, SUIT_NEXT_IN_30MIN); // automedic on // give morphine shot if not given recently SetSuitUpdate("!HEV_HEAL7", false, SUIT_NEXT_IN_30MIN); // morphine shot } if (fTookDamage && !ftrivial && fcritical && flHealthPrev < 75) { // already took major damage, now it's critical... if (m_iHealth < 6) SetSuitUpdate("!HEV_HLTH3", false, SUIT_NEXT_IN_10MIN); // near death else if (m_iHealth < 20) SetSuitUpdate("!HEV_HLTH2", false, SUIT_NEXT_IN_10MIN); // health critical // give critical health warnings if (!random->RandomInt(0,3) && flHealthPrev < 50) SetSuitUpdate("!HEV_DMG7", false, SUIT_NEXT_IN_5MIN); //seek medical attention } // if we're taking time based damage, warn about its continuing effects if (fTookDamage && (info.GetDamageType() & DMG_TIMEBASED) && flHealthPrev < 75) { if (flHealthPrev < 50) { if (!random->RandomInt(0,3)) SetSuitUpdate("!HEV_DMG7", false, SUIT_NEXT_IN_5MIN); //seek medical attention } else SetSuitUpdate("!HEV_HLTH1", false, SUIT_NEXT_IN_10MIN); // health dropping } // Do special explosion damage effect if ( bitsDamage & DMG_BLAST ) { OnDamagedByExplosion( info ); } return fTookDamage; } //----------------------------------------------------------------------------- // Purpose: // Input : &info - // damageAmount - //----------------------------------------------------------------------------- #define MIN_SHOCK_AND_CONFUSION_DAMAGE 30.0f #define MIN_EAR_RINGING_DISTANCE 240.0f // 20 feet //----------------------------------------------------------------------------- // Purpose: // Input : &info - //----------------------------------------------------------------------------- void CBasePlayer::OnDamagedByExplosion( const CTakeDamageInfo &info ) { float lastDamage = info.GetDamage(); float distanceFromPlayer = 9999.0f; CBaseEntity *inflictor = info.GetInflictor(); if ( inflictor ) { Vector delta = GetAbsOrigin() - inflictor->GetAbsOrigin(); distanceFromPlayer = delta.Length(); } bool ear_ringing = distanceFromPlayer < MIN_EAR_RINGING_DISTANCE ? true : false; bool shock = lastDamage >= MIN_SHOCK_AND_CONFUSION_DAMAGE; if ( !shock && !ear_ringing ) return; int effect = shock ? random->RandomInt( 35, 37 ) : random->RandomInt( 32, 34 ); CSingleUserRecipientFilter user( this ); enginesound->SetPlayerDSP( user, effect, false ); } //========================================================= // PackDeadPlayerItems - call this when a player dies to // pack up the appropriate weapons and ammo items, and to // destroy anything that shouldn't be packed. // // This is pretty brute force :( //========================================================= void CBasePlayer::PackDeadPlayerItems( void ) { int iWeaponRules; int iAmmoRules; int i; CBaseCombatWeapon *rgpPackWeapons[ 20 ];// 20 hardcoded for now. How to determine exactly how many weapons we have? int iPackAmmo[ MAX_AMMO_SLOTS + 1]; int iPW = 0;// index into packweapons array int iPA = 0;// index into packammo array memset(rgpPackWeapons, NULL, sizeof(rgpPackWeapons) ); memset(iPackAmmo, -1, sizeof(iPackAmmo) ); // get the game rules iWeaponRules = g_pGameRules->DeadPlayerWeapons( this ); iAmmoRules = g_pGameRules->DeadPlayerAmmo( this ); if ( iWeaponRules == GR_PLR_DROP_GUN_NO && iAmmoRules == GR_PLR_DROP_AMMO_NO ) { // nothing to pack. Remove the weapons and return. Don't call create on the box! RemoveAllItems( true ); return; } // go through all of the weapons and make a list of the ones to pack for ( i = 0 ; i < WeaponCount() ; i++ ) { // there's a weapon here. Should I pack it? CBaseCombatWeapon *pPlayerItem = GetWeapon( i ); if ( pPlayerItem ) { switch( iWeaponRules ) { case GR_PLR_DROP_GUN_ACTIVE: if ( GetActiveWeapon() && pPlayerItem == GetActiveWeapon() ) { // this is the active item. Pack it. rgpPackWeapons[ iPW++ ] = pPlayerItem; } break; case GR_PLR_DROP_GUN_ALL: rgpPackWeapons[ iPW++ ] = pPlayerItem; break; default: break; } } } // now go through ammo and make a list of which types to pack. if ( iAmmoRules != GR_PLR_DROP_AMMO_NO ) { for ( i = 0 ; i < MAX_AMMO_SLOTS ; i++ ) { if ( GetAmmoCount( i ) > 0 ) { // player has some ammo of this type. switch ( iAmmoRules ) { case GR_PLR_DROP_AMMO_ALL: iPackAmmo[ iPA++ ] = i; break; case GR_PLR_DROP_AMMO_ACTIVE: // WEAPONTODO: Make this work /* if ( GetActiveWeapon() && i == GetActiveWeapon()->m_iPrimaryAmmoType ) { // this is the primary ammo type for the active weapon iPackAmmo[ iPA++ ] = i; } else if ( GetActiveWeapon() && i == GetActiveWeapon()->m_iSecondaryAmmoType ) { // this is the secondary ammo type for the active weapon iPackAmmo[ iPA++ ] = i; } */ break; default: break; } } } } RemoveAllItems( true );// now strip off everything that wasn't handled by the code above. } void CBasePlayer::RemoveAllItems( bool removeSuit ) { if (GetActiveWeapon()) { ResetAutoaim( ); GetActiveWeapon()->Holster( ); } Weapon_SetLast( NULL ); RemoveAllWeapons(); RemoveAllAmmo(); if ( removeSuit ) { m_Local.m_bWearingSuit = false; } UpdateClientData(); } bool CBasePlayer::IsDead() const { return m_lifeState == LIFE_DEAD; } static float DamageForce( const Vector &size, float damage ) { float force = damage * ((32 * 32 * 72.0) / (size.x * size.y * size.z)) * 5; if ( force > 1000.0) { force = 1000.0; } return force; } int CBasePlayer::OnTakeDamage_Alive( const CTakeDamageInfo &info ) { // set damage type sustained m_bitsDamageType |= info.GetDamageType(); if ( !BaseClass::OnTakeDamage_Alive( info ) ) return 0; Vector vecDir = vec3_origin; if ( info.GetInflictor() ) { vecDir = info.GetInflictor()->WorldSpaceCenter() - Vector ( 0, 0, 10 ) - WorldSpaceCenter(); VectorNormalize( vecDir ); } if ( info.GetInflictor() && (GetMoveType() == MOVETYPE_WALK) && (!info.GetAttacker() || !info.GetAttacker()->IsSolidFlagSet(FSOLID_TRIGGER)) ) { Vector force = vecDir * -DamageForce( WorldAlignSize(), info.GetBaseDamage() ); if ( force.z > 250.0f ) { force.z = 250.0f; } ApplyAbsVelocityImpulse( force ); } // fire global game event KeyValues * event = new KeyValues( "player_hurt" ); event->SetInt("userid", GetUserID() ); event->SetInt("health", max(0, m_iHealth) ); CBaseEntity * attacker = info.GetAttacker(); if ( attacker->IsPlayer() ) { CBasePlayer *player = ToBasePlayer( attacker ); event->SetInt("attacker", player->GetUserID() ); // hurt by other player } else { event->SetInt("attacker", 0 ); // hurt by "world" } gameeventmanager->FireEvent( event ); // Insert a combat sound so that nearby NPCs hear battle if ( attacker->IsNPC() ) { CSoundEnt::InsertSound( SOUND_COMBAT, GetAbsOrigin(), 512, 0.5, this );//<<TODO>>//magic number } return 1; } void CBasePlayer::Event_Killed( const CTakeDamageInfo &info ) { CSound *pSound; g_pGameRules->PlayerKilled( this, info ); ClearUseEntity(); // this client isn't going to be thinking for a while, so reset the sound until they respawn pSound = CSoundEnt::SoundPointerForIndex( CSoundEnt::ClientSoundIndex( edict() ) ); { if ( pSound ) { pSound->Reset(); } } // don't let the status bar glitch for players.with <0 health. if (m_iHealth < -99) { m_iHealth = 0; } // holster the current weapon if ( GetActiveWeapon() ) { GetActiveWeapon()->Holster(); } SetAnimation( PLAYER_DIE ); SetViewOffset( VEC_DEAD_VIEWHEIGHT ); m_lifeState = LIFE_DYING; pl.deadflag = true; AddSolidFlags( FSOLID_NOT_SOLID ); SetMoveType( MOVETYPE_FLYGRAVITY ); SetGroundEntity( NULL ); // clear out the suit message cache so we don't keep chattering SetSuitUpdate(NULL, false, 0); // reset FOV SetFOV( this, 0 ); if ( FlashlightIsOn() ) { FlashlightTurnOff(); } m_flDeathTime = gpGlobals->curtime; BaseClass::Event_Killed( info ); } void CBasePlayer::Event_Dying() { // NOT GIBBED, RUN THIS CODE DeathSound(); // The dead body rolls out of the vehicle. if ( IsInAVehicle() ) { LeaveVehicle(); } QAngle angles = GetLocalAngles(); angles.x = 0; angles.z = 0; SetLocalAngles( angles ); SetThink(&CBasePlayer::PlayerDeathThink); SetNextThink( gpGlobals->curtime + 0.1f ); BaseClass::Event_Dying(); } // Set the activity based on an event or current state void CBasePlayer::SetAnimation( PLAYER_ANIM playerAnim ) { int animDesired; char szAnim[64]; float speed; speed = GetAbsVelocity().Length2D(); if (GetFlags() & (FL_FROZEN|FL_ATCONTROLS)) { speed = 0; playerAnim = PLAYER_IDLE; } Activity idealActivity = ACT_WALK;// TEMP!!!!! // This could stand to be redone. Why is playerAnim abstracted from activity? (sjb) if (playerAnim == PLAYER_JUMP) { idealActivity = ACT_HOP; // allow bots to react #ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out TheBots->OnEvent( EVENT_PLAYER_JUMPED, this ); #endif } else if (playerAnim == PLAYER_SUPERJUMP) { idealActivity = ACT_LEAP; } else if (playerAnim == PLAYER_DIE) { if ( m_lifeState == LIFE_ALIVE ) { idealActivity = GetDeathActivity(); } } else if (playerAnim == PLAYER_ATTACK1) { if ( m_Activity == ACT_HOVER || m_Activity == ACT_SWIM || m_Activity == ACT_HOP || m_Activity == ACT_LEAP || m_Activity == ACT_DIESIMPLE ) { idealActivity = m_Activity; } else { idealActivity = ACT_RANGE_ATTACK1; } } else if (playerAnim == PLAYER_IDLE || playerAnim == PLAYER_WALK) { if ( !( GetFlags() & FL_ONGROUND ) && (m_Activity == ACT_HOP || m_Activity == ACT_LEAP) ) // Still jumping { idealActivity = m_Activity; } else if ( GetWaterLevel() > 1 ) { if ( speed == 0 ) idealActivity = ACT_HOVER; else idealActivity = ACT_SWIM; } else { idealActivity = ACT_WALK; } } if (idealActivity == ACT_RANGE_ATTACK1) { if ( GetFlags() & FL_DUCKING ) // crouching { Q_strncpy( szAnim, "crouch_shoot_" ,sizeof(szAnim)); } else { Q_strncpy( szAnim, "ref_shoot_" ,sizeof(szAnim)); } Q_strncat( szAnim, m_szAnimExtension ,sizeof(szAnim), COPY_ALL_CHARACTERS ); animDesired = LookupSequence( szAnim ); if (animDesired == -1) animDesired = 0; if ( GetSequence() != animDesired || !SequenceLoops() ) { SetCycle( 0 ); } // Tracker 24588: In single player when firing own weapon this causes eye and punchangle to jitter //if (!SequenceLoops()) //{ // AddEffects( EF_NOINTERP ); //} SetActivity( idealActivity ); ResetSequence( animDesired ); } else if (idealActivity == ACT_WALK) { if (GetActivity() != ACT_RANGE_ATTACK1 || IsActivityFinished()) { if ( GetFlags() & FL_DUCKING ) // crouching { Q_strncpy( szAnim, "crouch_aim_" ,sizeof(szAnim)); } else { Q_strncpy( szAnim, "ref_aim_" ,sizeof(szAnim)); } Q_strncat( szAnim, m_szAnimExtension,sizeof(szAnim), COPY_ALL_CHARACTERS ); animDesired = LookupSequence( szAnim ); if (animDesired == -1) animDesired = 0; SetActivity( ACT_WALK ); } else { animDesired = GetSequence(); } } else { if ( GetActivity() == idealActivity) return; SetActivity( idealActivity ); animDesired = SelectWeightedSequence( m_Activity ); // Already using the desired animation? if (GetSequence() == animDesired) return; ResetSequence( animDesired ); SetCycle( 0 ); return; } // Already using the desired animation? if (GetSequence() == animDesired) return; //Msg( "Set animation to %d\n", animDesired ); // Reset to first frame of desired animation ResetSequence( animDesired ); SetCycle( 0 ); } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- void CBasePlayer::SetPlayerUnderwater( bool state ) { m_bPlayerUnderwater = state; } /* =========== WaterMove ============ */ #ifdef HL2_DLL // test for HL2 drowning damage increase (aux power used instead) #define AIRTIME 7 // lung full of air lasts this many seconds #define DROWNING_DAMAGE_INITIAL 10 #define DROWNING_DAMAGE_MAX 10 #else #define AIRTIME 12 // lung full of air lasts this many seconds #define DROWNING_DAMAGE_INITIAL 2 #define DROWNING_DAMAGE_MAX 5 #endif void CBasePlayer::WaterMove() { int air; if ( ( GetMoveType() == MOVETYPE_NOCLIP ) && !GetMoveParent() ) { m_AirFinished = gpGlobals->curtime + AIRTIME; return; } if (m_iHealth < 0) return; // waterlevel 0 - not in water // waterlevel 1 - feet in water // waterlevel 2 - waist in water // waterlevel 3 - head in water if (GetWaterLevel() != 3 || CanBreatheUnderwater()) { // not underwater // play 'up for air' sound if (m_AirFinished < gpGlobals->curtime) { EmitSound( "Player.DrownStart" ); } m_AirFinished = gpGlobals->curtime + AIRTIME; m_nDrownDmgRate = DROWNING_DAMAGE_INITIAL; // if we took drowning damage, give it back slowly if (m_idrowndmg > m_idrownrestored) { // set drowning damage bit. hack - dmg_drownrecover actually // makes the time based damage code 'give back' health over time. // make sure counter is cleared so we start count correctly. // NOTE: this actually causes the count to continue restarting // until all drowning damage is healed. m_bitsDamageType |= DMG_DROWNRECOVER; m_bitsDamageType &= ~DMG_DROWN; m_rgbTimeBasedDamage[itbd_DrownRecover] = 0; } } else { // fully under water // stop restoring damage while underwater m_bitsDamageType &= ~DMG_DROWNRECOVER; m_rgbTimeBasedDamage[itbd_DrownRecover] = 0; if (m_AirFinished < gpGlobals->curtime && !(GetFlags() & FL_GODMODE) ) // drown! { if (m_PainFinished < gpGlobals->curtime) { // take drowning damage m_nDrownDmgRate += 1; if (m_nDrownDmgRate > DROWNING_DAMAGE_MAX) { m_nDrownDmgRate = DROWNING_DAMAGE_MAX; } OnTakeDamage( CTakeDamageInfo( GetContainingEntity(INDEXENT(0)), GetContainingEntity(INDEXENT(0)), m_nDrownDmgRate, DMG_DROWN ) ); m_PainFinished = gpGlobals->curtime + 1; // track drowning damage, give it back when // player finally takes a breath m_idrowndmg += m_nDrownDmgRate; } } else { m_bitsDamageType &= ~DMG_DROWN; } } if ( GetWaterLevel() < 3 ) { if ( m_bPlayerUnderwater ) { StopSound( "Player.AmbientUnderWater" ); SetPlayerUnderwater( false ); } } else if ( GetWaterLevel() < 2 ) { if ( GetWaterLevel() == 0 ) { if ( GetFlags() & FL_INWATER ) { EmitSound( "Player.Wade" ); RemoveFlag( FL_INWATER ); } return; } } else if ( GetWaterLevel() > 2 ) { if ( m_bPlayerUnderwater == false ) { EmitSound( "Player.AmbientUnderWater" ); SetPlayerUnderwater( true ); } return; } // make bubbles air = (int)( m_AirFinished - gpGlobals->curtime ); #if 0 if (GetWaterType() == CONTENT_LAVA) // do damage { if (m_flDamageTime < gpGlobals->curtime) { OnTakeDamage( GetContainingEntity(INDEXENT(0)), GetContainingEntity(INDEXENT(0)), 10 * GetWaterLevel(), DMG_BURN); } } else if (GetWaterType() == CONTENT_SLIME) // do damage { m_flDamageTime = gpGlobals->curtime + 1; OnTakeDamage(GetContainingEntity(INDEXENT(0)), GetContainingEntity(INDEXENT(0)), 4 * GetWaterLevel(), DMG_ACID); } #endif if (!(GetFlags() & FL_INWATER)) { // player enter water sound if (GetWaterType() == CONTENTS_WATER) { EmitSound( "Player.Wade" ); } AddFlag( FL_INWATER ); } } // true if the player is attached to a ladder bool CBasePlayer::IsOnLadder( void ) { return (GetMoveType() == MOVETYPE_LADDER); } float CBasePlayer::GetWaterJumpTime() const { return m_flWaterJumpTime; } void CBasePlayer::SetWaterJumpTime( float flWaterJumpTime ) { m_flWaterJumpTime = flWaterJumpTime; } float CBasePlayer::GetSwimSoundTime( void ) const { return m_flSwimSoundTime; } void CBasePlayer::SetSwimSoundTime( float flSwimSoundTime ) { m_flSwimSoundTime = flSwimSoundTime; } void CBasePlayer::ShowViewPortPanel( const char * name, bool bShow, KeyValues *data ) { CSingleUserRecipientFilter filter( this ); filter.MakeReliable(); int count = 0; KeyValues *subkey = NULL; if ( data ) { subkey = data->GetFirstSubKey(); while ( subkey ) { count++; subkey = subkey->GetNextKey(); } subkey = data->GetFirstSubKey(); // reset } UserMessageBegin( filter, "VGUIMenu" ); WRITE_STRING( name ); // menu name WRITE_BYTE( bShow?1:0 ); WRITE_BYTE( count ); // write additional data (be carefull not more than 192 bytes!) while ( subkey ) { WRITE_STRING( subkey->GetName() ); WRITE_STRING( subkey->GetString() ); subkey = subkey->GetNextKey(); } MessageEnd(); } void CBasePlayer::PlayerDeathThink(void) { float flForward; SetNextThink( gpGlobals->curtime + 0.1f ); if (GetFlags() & FL_ONGROUND) { flForward = GetAbsVelocity().Length() - 20; if (flForward <= 0) { SetAbsVelocity( vec3_origin ); } else { Vector vecNewVelocity = GetAbsVelocity(); VectorNormalize( vecNewVelocity ); vecNewVelocity *= flForward; SetAbsVelocity( vecNewVelocity ); } } if ( HasWeapons() ) { // we drop the guns here because weapons that have an area effect and can kill their user // will sometimes crash coming back from CBasePlayer::Killed() if they kill their owner because the // player class sometimes is freed. It's safer to manipulate the weapons once we know // we aren't calling into any of their code anymore through the player pointer. PackDeadPlayerItems(); } if (GetModelIndex() && (!IsSequenceFinished()) && (m_lifeState == LIFE_DYING)) { StudioFrameAdvance( ); m_iRespawnFrames++; if ( m_iRespawnFrames < 60 ) // animations should be no longer than this return; } if (m_lifeState == LIFE_DYING) m_lifeState = LIFE_DEAD; StopAnimation(); AddEffects( EF_NOINTERP ); m_flPlaybackRate = 0.0; int fAnyButtonDown = (m_nButtons & ~IN_SCORE); // wait for all buttons released if (m_lifeState == LIFE_DEAD) { if (fAnyButtonDown) return; if ( g_pGameRules->FPlayerCanRespawn( this ) ) { m_lifeState = LIFE_RESPAWNABLE; } return; } // if the player has been dead for one second longer than allowed by forcerespawn, // forcerespawn isn't on. Send the player off to an intermission camera until they // choose to respawn. if ( g_pGameRules->IsMultiplayer() && ( gpGlobals->curtime > (m_flDeathTime + DEATH_ANIMATION_TIME) ) && !IsObserver() ) { // go to dead camera. StartObserverMode( m_iObserverLastMode ); } // wait for any button down, or mp_forcerespawn is set and the respawn time is up if (!fAnyButtonDown && !( g_pGameRules->IsMultiplayer() && forcerespawn.GetInt() > 0 && (gpGlobals->curtime > (m_flDeathTime + 5))) ) return; m_nButtons = 0; m_iRespawnFrames = 0; //Msg( "Respawn\n"); respawn( this, !IsObserver() );// don't copy a corpse if we're in deathcam. SetNextThink( TICK_NEVER_THINK ); } /* //========================================================= // StartDeathCam - find an intermission spot and send the // player off into observer mode //========================================================= void CBasePlayer::StartDeathCam( void ) { CBaseEntity *pSpot, *pNewSpot; int iRand; if ( GetViewOffset() == vec3_origin ) { // don't accept subsequent attempts to StartDeathCam() return; } pSpot = gEntList.FindEntityByClassname( NULL, "info_intermission"); if ( pSpot ) { // at least one intermission spot in the world. iRand = random->RandomInt( 0, 3 ); while ( iRand > 0 ) { pNewSpot = gEntList.FindEntityByClassname( pSpot, "info_intermission"); if ( pNewSpot ) { pSpot = pNewSpot; } iRand--; } CreateCorpse(); StartObserverMode( pSpot->GetAbsOrigin(), pSpot->GetAbsAngles() ); } else { // no intermission spot. Push them up in the air, looking down at their corpse trace_t tr; CreateCorpse(); UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + Vector( 0, 0, 128 ), MASK_PLAYERSOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); QAngle angles; VectorAngles( GetAbsOrigin() - tr.endpos, angles ); StartObserverMode( tr.endpos, angles ); return; } } */ void CBasePlayer::StopObserverMode() { m_bForcedObserverMode = false; m_bIsRecording = false; m_afPhysicsFlags &= ~PFLAG_OBSERVER; if ( m_iObserverMode == OBS_MODE_NONE ) return; if ( m_iObserverMode > OBS_MODE_DEATHCAM ) { m_iObserverLastMode = m_iObserverMode; } m_iObserverMode = OBS_MODE_NONE; ShowViewPortPanel( "specmenu", false ); ShowViewPortPanel( "specgui", false ); ShowViewPortPanel( "overview", false ); } bool CBasePlayer::StartObserverMode(int mode) { if ( !IsObserver() ) { // set position to last view offset SetAbsOrigin( GetAbsOrigin() + GetViewOffset() ); SetViewOffset( vec3_origin ); } Assert( mode > OBS_MODE_NONE ); m_afPhysicsFlags |= PFLAG_OBSERVER; // Holster weapon immediately, to allow it to cleanup if ( GetActiveWeapon() ) GetActiveWeapon()->Holster(); // clear out the suit message cache so we don't keep chattering SetSuitUpdate(NULL, FALSE, 0); SetGroundEntity( (CBaseEntity *)NULL ); RemoveFlag( FL_DUCKING ); AddSolidFlags( FSOLID_NOT_SOLID ); SetObserverMode( mode, false ); ShowViewPortPanel( "specgui" ); // Setup flags m_Local.m_iHideHUD = HIDEHUD_HEALTH; m_takedamage = DAMAGE_NO; //Don't set the player to EF_NODRAW - the client can determine //whether to draw the player or not with ShouldDraw //AddEffects( EF_NODRAW ); m_iHealth = 1; m_lifeState = LIFE_DEAD; // Can't be dead, otherwise movement doesn't work right. pl.deadflag = true; return true; } bool CBasePlayer::SetObserverMode(int mode, bool ignoreDeadSpecMode) { if ( mode < OBS_MODE_NONE || mode > OBS_MODE_ROAMING ) return false; // check forcecamera settings for dead players if ( GetTeamNumber() != TEAM_SPECTATOR ) { switch ( mp_forcecamera.GetInt() ) { case OBS_ALLOW_ALL : break; case OBS_ALLOW_TEAM : if ( !ignoreDeadSpecMode ) mode = OBS_MODE_IN_EYE; break; case OBS_ALLOW_NONE : mode = OBS_MODE_FIXED; break; } } if ( m_iObserverMode > OBS_MODE_DEATHCAM ) { // remember mode if we were really spectating before m_iObserverLastMode = m_iObserverMode; } m_iObserverMode = mode; switch ( mode ) { case OBS_MODE_NONE: case OBS_MODE_FIXED : case OBS_MODE_DEATHCAM : SetFOV( this, 0 ); // Reset FOV SetViewOffset( vec3_origin ); SetMoveType( MOVETYPE_NONE ); break; case OBS_MODE_CHASE : case OBS_MODE_IN_EYE : // udpate FOV and viewmodels SetObserverTarget( m_hObserverTarget ); SetMoveType( MOVETYPE_OBSERVER ); break; case OBS_MODE_ROAMING : SetFOV( this, 0 ); // Reset FOV SetObserverTarget( m_hObserverTarget ); SetViewOffset( vec3_origin ); SetMoveType( MOVETYPE_OBSERVER ); break; } CheckObserverSettings(); return true; } int CBasePlayer::GetObserverMode() { return m_iObserverMode; } void CBasePlayer::ForceObserverMode(int mode, bool ignoreDeadSpecMode) { int tempMode = OBS_MODE_ROAMING; if ( m_iObserverMode == mode ) return; // don't change last mode if already in forced mode if ( m_bForcedObserverMode ) { tempMode = m_iObserverLastMode; } SetObserverMode( mode, ignoreDeadSpecMode ); if ( m_bForcedObserverMode ) { m_iObserverLastMode = tempMode; } m_bForcedObserverMode = true; } void CBasePlayer::CheckObserverSettings() { // check if we are in forced mode and may go back to old mode if ( m_bForcedObserverMode ) { CBaseEntity * target = m_hObserverTarget; if ( !IsValidObserverTarget(target) ) { // if old target is still invalid, try to find valid one target = FindNextObserverTarget( false ); } if ( target ) { // we found a valid target m_bForcedObserverMode = false; // disable force mode SetObserverMode( m_iObserverLastMode, false ); // switch to last mode SetObserverTarget( target ); // goto target // TODO check for HUD icons return; } else { // else stay in forced mode, no changes return; } } // make sure our last mode is valid if ( m_iObserverLastMode < OBS_MODE_FIXED ) { m_iObserverLastMode = OBS_MODE_ROAMING; } // check if our spectating target is still a valid one if ( m_iObserverMode == OBS_MODE_IN_EYE || m_iObserverMode == OBS_MODE_CHASE ) { if ( !IsValidObserverTarget( m_hObserverTarget.Get() ) ) { // our traget is not valid, try to find new target CBaseEntity * target = FindNextObserverTarget( false ); if ( target ) { // switch to new target SetObserverTarget( target ); } else { // couldn't find new taget, switch to temporary mode if ( mp_forcecamera.GetInt() == 1 ) { ForceObserverMode( OBS_MODE_FIXED, true ); } else { ForceObserverMode( OBS_MODE_ROAMING, false ); } } } CBasePlayer *target = ToBasePlayer( m_hObserverTarget.Get() ); // for ineye mode we have to copy several data to see exactly the same if ( target && m_iObserverMode == OBS_MODE_IN_EYE ) { float fFov = target->GetFOV(); if ( GetFOV() != fFov ) { SetFOV( this, fFov, 0 ); } int flagMask = FL_ONGROUND | FL_DUCKING ; int flags = target->GetFlags() & flagMask; if ( (GetFlags() & flagMask) != flags ) { flags |= GetFlags() & (~flagMask); // keep other flags ClearFlags(); AddFlag( flags ); } if ( target->GetViewOffset() != GetViewOffset() ) { SetViewOffset( target->GetViewOffset() ); } } } } CBaseEntity * CBasePlayer::GetObserverTarget() { return m_hObserverTarget.Get(); } void CBasePlayer::ObserverUse( bool bIsPressed ) { if ( !HLTVDirector()->IsActive() ) return; if ( GetTeamNumber() != TEAM_SPECTATOR ) return; // only pure spectators can play cameraman if ( !bIsPressed ) return; m_bIsRecording = !m_bIsRecording; KeyValues * event = new KeyValues( "hltv_cameraman" ); event->SetInt("index", entindex() ); event->SetInt("mode", m_bIsRecording ? GetObserverMode() : 0 ); HLTVDirector()->AddDirectorCommand( gpGlobals->tickcount, event ); event->deleteThis(); if ( m_bIsRecording ) { ClientPrint( this, HUD_PRINTTALK, "Recording..." ); } else { ClientPrint( this, HUD_PRINTTALK, "Recording..." ); } /* UTIL_SayText( "Spectator can not USE anything", this ); Vector dir,end; Vector start = GetAbsOrigin(); AngleVectors( GetAbsAngles(), &dir ); VectorNormalize( dir ); VectorMA( start, 32.0f, dir, end ); trace_t tr; UTIL_TraceLine( start, end, MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER_MOVEMENT, &tr ); if ( tr.fraction == 1.0f ) return; // no obstacles in spectators way VectorMA( start, 128.0f, dir, end ); Ray_t ray; ray.Init( end, start, VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX ); UTIL_TraceRay( ray, MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER_MOVEMENT, &tr ); if ( tr.startsolid || tr.allsolid ) return; SetAbsOrigin( tr.endpos ); */ } void CBasePlayer::JumptoPosition(const Vector &origin, const QAngle &angles) { SetAbsOrigin( origin ); SetAbsVelocity( vec3_origin ); // stop movement SetLocalAngles( angles ); SnapEyeAngles( angles ); } bool CBasePlayer::SetObserverTarget(CBaseEntity *target) { if ( !IsValidObserverTarget( target ) ) return false; // set new target m_hObserverTarget.Set( target ); // reset fov to default SetFOV( this, 0 ); if ( m_iObserverMode == OBS_MODE_ROAMING ) { Vector dir, end; Vector start = target->EyePosition(); AngleVectors( target->EyeAngles(), &dir ); VectorNormalize( dir ); VectorMA( start, -64.0f, dir, end ); Ray_t ray; ray.Init( start, end, VEC_DUCK_HULL_MIN , VEC_DUCK_HULL_MAX ); trace_t tr; UTIL_TraceRay( ray, MASK_PLAYERSOLID, target, COLLISION_GROUP_PLAYER_MOVEMENT, &tr ); JumptoPosition( tr.endpos, target->EyeAngles() ); } else if ( m_iObserverMode == OBS_MODE_IN_EYE ) { // only update view models in ineye mode if ( target->IsPlayer() ) { CBasePlayer * pPlayer = ToBasePlayer( target ); // copy viewmodels from target for ( int i = 0; i < MAX_VIEWMODELS; i++ ) { m_hObserverViewModel.Set( i, pPlayer->GetViewModel(i) ); } // set FOV of player we observe SetFOV( this, pPlayer->GetFOV() ); } } return true; } bool CBasePlayer::IsValidObserverTarget(CBaseEntity * target) { if ( target == NULL ) return false; // MOD AUTHORS: Add checks on target here or in derived methode if ( !target->IsPlayer() ) // only track players return false; CBasePlayer * player = ToBasePlayer( target ); /* Don't spec observers or players who haven't picked a class yet if ( player->IsObserver() ) return false; */ if ( player->IsEffectActive( EF_NODRAW ) ) // don't watch invisible players return false; if ( player->m_lifeState == LIFE_RESPAWNABLE ) // target is dead, waiting for respawn return false; if ( player->m_lifeState == LIFE_DEAD || player->m_lifeState == LIFE_DYING ) { if ( (player->m_flDeathTime + DEATH_ANIMATION_TIME ) < gpGlobals->curtime ) { return false; // allow watching until 2 seconds after death to see death animation } } switch ( mp_forcecamera.GetInt() ) // check forcecamera settings { case OBS_ALLOW_ALL : break; case OBS_ALLOW_TEAM : if ( (this->GetTeamNumber() != target->GetTeamNumber()) && (this->GetTeamNumber() != TEAM_SPECTATOR) ) return false; break; case OBS_ALLOW_NONE : return false; } return true; // passed all test } CBaseEntity * CBasePlayer::FindNextObserverTarget(bool bReverse) { // MOD AUTHORS: Modify the logic of this function if you want to restrict the observer to watching // only a subset of the players. e.g. Make it check the target's team. /* if ( m_flNextFollowTime && m_flNextFollowTime > gpGlobals->time ) { return; } m_flNextFollowTime = gpGlobals->time + 0.25; */ // TODO move outside this function int startIndex; if ( m_hObserverTarget ) { // start using last followed player startIndex = m_hObserverTarget->entindex(); } else { // start using own player index startIndex = this->entindex(); } int currentIndex = startIndex; int iDir = bReverse ? -1 : 1; do { currentIndex += iDir; // Loop through the clients if (currentIndex > gpGlobals->maxClients) currentIndex = 1; else if (currentIndex < 1) currentIndex = gpGlobals->maxClients; CBaseEntity * nextTarget = UTIL_PlayerByIndex( currentIndex ); if ( IsValidObserverTarget( nextTarget ) ) { return nextTarget; // found next valid player } } while ( currentIndex != startIndex ); return NULL; } //----------------------------------------------------------------------------- // Purpose: Return true if this object can be +used by the player //----------------------------------------------------------------------------- bool CBasePlayer::IsUseableEntity( CBaseEntity *pEntity, unsigned int requiredCaps ) { if ( pEntity ) { int caps = pEntity->ObjectCaps(); if ( caps & (FCAP_IMPULSE_USE|FCAP_CONTINUOUS_USE|FCAP_ONOFF_USE|FCAP_DIRECTIONAL_USE) ) { if ( (caps & requiredCaps) == requiredCaps ) return true; } } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CBasePlayer::CanPickupObject( CBaseEntity *pObject, float massLimit, float sizeLimit ) { // UNDONE: Make this virtual and move to HL2 player #ifdef HL2_DLL //Must be valid if ( pObject == NULL ) return false; //Must move with physics if ( pObject->GetMoveType() != MOVETYPE_VPHYSICS ) return false; IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT]; int count = pObject->VPhysicsGetObjectList( pList, ARRAYSIZE(pList) ); //Must have a physics object if (!count) return false; float objectMass = 0; bool checkEnable = false; for ( int i = 0; i < count; i++ ) { objectMass += pList[i]->GetMass(); if ( !pList[i]->IsMoveable() ) { checkEnable = true; } if ( pList[i]->GetGameFlags() & FVPHYSICS_NO_PLAYER_PICKUP ) return false; if ( pList[i]->IsHinged() ) return false; } //Msg( "Target mass: %f\n", pPhys->GetMass() ); //Must be under our threshold weight if ( massLimit > 0 && objectMass > massLimit ) return false; if ( checkEnable ) { // Allowing picking up of bouncebombs that player placed. CBounceBomb *pBomb = dynamic_cast<CBounceBomb*>(pObject); if( pBomb && pBomb->IsPlayerPlaced() ) return true; // Allow pickup of phys props that are motion enabled on player pickup CPhysicsProp *pProp = dynamic_cast<CPhysicsProp*>(pObject); CPhysBox *pBox = dynamic_cast<CPhysBox*>(pObject); if ( !pProp && !pBox ) return false; if ( pProp && !(pProp->HasSpawnFlags( SF_PHYSPROP_ENABLE_ON_PHYSCANNON )) ) return false; if ( pBox && !(pBox->HasSpawnFlags( SF_PHYSBOX_ENABLE_ON_PHYSCANNON )) ) return false; } if ( sizeLimit > 0 ) { const Vector &size = pObject->CollisionProp()->OBBSize(); if ( size.x > sizeLimit || size.y > sizeLimit || size.z > sizeLimit ) return false; } return true; #else return false; #endif } float CBasePlayer::GetHeldObjectMass( IPhysicsObject *pHeldObject ) { return 0; } //----------------------------------------------------------------------------- // Purpose: Server side of jumping rules. Most jumping logic is already // handled in shared gamemovement code. Put stuff here that should // only be done server side. //----------------------------------------------------------------------------- void CBasePlayer::Jump() { } void CBasePlayer::Duck( ) { if (m_nButtons & IN_DUCK) { if ( m_Activity != ACT_LEAP ) { SetAnimation( PLAYER_WALK ); } } } // // ID's player as such. // Class_T CBasePlayer::Classify ( void ) { return CLASS_PLAYER; } void CBasePlayer::ResetFragCount() { m_iFrags = 0; pl.frags = m_iFrags; } void CBasePlayer::IncrementFragCount( int nCount ) { m_iFrags += nCount; pl.frags = m_iFrags; } void CBasePlayer::ResetDeathCount() { m_iDeaths = 0; pl.deaths = m_iDeaths; } void CBasePlayer::IncrementDeathCount( int nCount ) { m_iDeaths += nCount; pl.deaths = m_iDeaths; } void CBasePlayer::AddPoints( int score, bool bAllowNegativeScore ) { // Positive score always adds if ( score < 0 ) { if ( !bAllowNegativeScore ) { if ( m_iFrags < 0 ) // Can't go more negative return; if ( -score > m_iFrags ) // Will this go negative? { score = -m_iFrags; // Sum will be 0 } } } m_iFrags += score; pl.frags = m_iFrags; } void CBasePlayer::AddPointsToTeam( int score, bool bAllowNegativeScore ) { int index = entindex(); for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBaseEntity *pPlayer = UTIL_PlayerByIndex( i ); if ( pPlayer && i != index ) { if ( g_pGameRules->PlayerRelationship( this, pPlayer ) == GR_TEAMMATE ) { pPlayer->AddPoints( score, bAllowNegativeScore ); } } } } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CBasePlayer::GetCommandContextCount( void ) const { return m_CommandContext.Count(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : CCommandContext //----------------------------------------------------------------------------- CCommandContext *CBasePlayer::GetCommandContext( int index ) { if ( index < 0 || index >= m_CommandContext.Count() ) return NULL; return &m_CommandContext[ index ]; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CCommandContext *CBasePlayer::AllocCommandContext( void ) { int idx = m_CommandContext.AddToTail(); return &m_CommandContext[ idx ]; } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void CBasePlayer::RemoveCommandContext( int index ) { m_CommandContext.Remove( index ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::RemoveAllCommandContexts() { m_CommandContext.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: Determine how much time we will be running this frame // Output : float //----------------------------------------------------------------------------- int CBasePlayer::DetermineSimulationTicks( void ) { int command_context_count = GetCommandContextCount(); int context_number; int simulation_ticks = 0; // Determine how much time we will be running this frame and fixup player clock as needed for ( context_number = 0; context_number < command_context_count; context_number++ ) { CCommandContext const *ctx = GetCommandContext( context_number ); Assert( ctx ); Assert( ctx->numcmds > 0 ); Assert( ctx->dropped_packets >= 0 ); // Determine how long it will take to run those packets simulation_ticks += ctx->numcmds + ctx->dropped_packets; } return simulation_ticks; } // 2 ticks ahead or behind current clock means we need to fix clock on client #define TARGET_CLOCK_CORRECTION_TICKS (TIME_TO_TICKS(0.06f)) extern ConVar skip; //----------------------------------------------------------------------------- // Purpose: Based upon amount of time in simulation time, adjust m_nTickBase so that // we just end at the end of the current frame (so the player is basically on clock // with the server) // Input : simulation_ticks - //----------------------------------------------------------------------------- void CBasePlayer::AdjustPlayerTimeBase( int simulation_ticks ) { Assert( simulation_ticks >= 0 ); if ( simulation_ticks < 0 ) return; // Start in the past so that we get to the sv.time that we'll hit at the end of the // frame, just as we process the final command if ( gpGlobals->maxClients == 1 ) { // set TickBase so that player simulation tick matches gpGlobals->tickcount after // all commands have been executed m_nTickBase = gpGlobals->tickcount - simulation_ticks + 1; } else // multiplayer { // set the target tick 2 ticks ahead in the future. this way the client can // alternate around this targettick without getting smaller than gpGlobals->tickcount // after running the commands simulation time should never be smaller than the // current gpGlobals->tickcount, otherwise the simulation time drops out of the // clientside view interpolation buffer. int end_of_frame_ticks = gpGlobals->tickcount + TARGET_CLOCK_CORRECTION_TICKS; int estimated_end_tick = m_nTickBase + simulation_ticks; // If client gets ahead of this, we'll need to correct int too_fast_limit = end_of_frame_ticks + TARGET_CLOCK_CORRECTION_TICKS; // If client falls behind this, we'll also need to correct int too_slow_limit = end_of_frame_ticks - TARGET_CLOCK_CORRECTION_TICKS; // See if we are too fast if ( estimated_end_tick > too_fast_limit ) { // DevMsg( "client too fast by %i ticks\n", estimated_end_tick - end_of_frame_ticks ); m_nTickBase = end_of_frame_ticks - simulation_ticks + 1; } // Or to slow else if ( estimated_end_tick < too_slow_limit ) { // DevMsg( "client too slow by %i ticks\n", end_of_frame_ticks - estimated_end_tick ); m_nTickBase = end_of_frame_ticks - simulation_ticks + 1; } } } void CBasePlayer::RunNullCommand( void ) { CUserCmd cmd; // NULL command // Store off the globals.. they're gonna get whacked float flOldFrametime = gpGlobals->frametime; float flOldCurtime = gpGlobals->curtime; pl.fixangle = FIXANGLE_NONE; cmd.viewangles = EyeAngles(); float flTimeBase = gpGlobals->curtime; SetTimeBase( flTimeBase ); MoveHelperServer()->SetHost( this ); PlayerRunCommand( &cmd, MoveHelperServer() ); // save off the last good usercmd SetLastUserCommand( cmd ); // Restore the globals.. gpGlobals->frametime = flOldFrametime; gpGlobals->curtime = flOldCurtime; } //----------------------------------------------------------------------------- // Purpose: Note, don't chain to BaseClass::PhysicsSimulate //----------------------------------------------------------------------------- void CBasePlayer::PhysicsSimulate( void ) { VPROF( "CBasePlayer::PhysicsSimulate" ); // If we've got a moveparent, we must simulate that first. CBaseEntity *pMoveParent = GetMoveParent(); if (pMoveParent) { pMoveParent->PhysicsSimulate(); } // Make sure not to simulate this guy twice per frame if (m_nSimulationTick == gpGlobals->tickcount ) { return; } m_nSimulationTick = gpGlobals->tickcount; // See how much time has queued up for running int simulation_ticks = DetermineSimulationTicks(); // If some time will elapse, make sure our clock (m_nTickBase) starts at the correct time if ( simulation_ticks > 0 ) { AdjustPlayerTimeBase( simulation_ticks ); } if ( IsHLTV() ) { // just run a single, empty command to makke sure // all preThink/Postthink functions are called as usual Assert ( GetCommandContextCount() == 0 ); RunNullCommand(); RemoveAllCommandContexts(); return; } // Store off true server timestamps float savetime = gpGlobals->curtime; float saveframetime = gpGlobals->frametime; int command_context_count = GetCommandContextCount(); for ( int context_number = 0; context_number < command_context_count; context_number++ ) { // Get oldest ( newer are added to tail ) CCommandContext *ctx = GetCommandContext( context_number ); Assert( ctx ); int i; int numbackup = ctx->totalcmds - ctx->numcmds; // If the server is paused, zero out motion,buttons,view changes if ( ctx->paused ) { bool clear_angles = true; // If no clipping and cheats enabled and noclipduring game enabled, then leave // forwardmove and angles stuff in usercmd if ( GetMoveType() == MOVETYPE_NOCLIP && sv_cheats->GetBool() && sv_noclipduringpause.GetBool() ) { clear_angles = false; } for ( i = 0; i < ctx->numcmds; i++ ) { ctx->cmds[ i ].buttons = 0; if ( clear_angles ) { ctx->cmds[ i ].forwardmove = 0; ctx->cmds[ i ].sidemove = 0; ctx->cmds[ i ].upmove = 0; VectorCopy ( pl.v_angle, ctx->cmds[ i ].viewangles ); } } ctx->dropped_packets = 0; } MoveHelperServer()->SetHost( this ); // Suppress predicted events, etc. if ( IsPredictingWeapons() ) { IPredictionSystem::SuppressHostEvents( this ); } // If we haven't dropped too many packets, then run some commands if ( ctx->dropped_packets < 24 ) { int droppedcmds = ctx->dropped_packets; if ( droppedcmds > numbackup ) { // Msg( "lost %i cmds\n", droppedcmds ); } // run the last known cmd for each dropped cmd we don't have a backup for while ( droppedcmds > numbackup ) { m_LastCmd.tick_count++; if ( ShouldRunCommandsInContext( ctx ) ) { PlayerRunCommand( &m_LastCmd, MoveHelperServer() ); } droppedcmds--; } // Now run the "history" commands if we still have dropped packets while ( droppedcmds > 0 ) { int cmdnum = ctx->numcmds + droppedcmds - 1; if ( ShouldRunCommandsInContext( ctx ) ) { PlayerRunCommand( &ctx->cmds[cmdnum], MoveHelperServer() ); } droppedcmds--; } } // Now run any new command(s). Go backward because the most recent command is at index 0. for ( i = ctx->numcmds - 1; i >= 0; i-- ) { if ( ShouldRunCommandsInContext( ctx ) ) { PlayerRunCommand( &ctx->cmds[ i ], MoveHelperServer() ); } } // Save off the last good command in case we drop > numbackup packets and need to rerun them // we'll use this to "guess" at what was in the missing packets m_LastCmd = ctx->cmds[ CMD_MOSTRECENT ]; // Update our vphysics object. if ( m_pPhysicsController ) { // If simulating at 2 * TICK_INTERVAL, add an extra TICK_INTERVAL to position arrival computation int additionalTick = CBaseEntity::IsSimulatingOnAlternateTicks() ? 1 : 0; float flSecondsToArrival = ( ctx->numcmds + ctx->dropped_packets + additionalTick ) * TICK_INTERVAL; UpdateVPhysicsPosition( m_vNewVPhysicsPosition, m_vNewVPhysicsVelocity, flSecondsToArrival ); } // Always reset after running commands IPredictionSystem::SuppressHostEvents( NULL ); } // Clear all contexts RemoveAllCommandContexts(); // Restore the true server clock // FIXME: Should this occur after simulation of children so // that they are in the timespace of the player? gpGlobals->curtime = savetime; gpGlobals->frametime = saveframetime; } unsigned int CBasePlayer::PhysicsSolidMaskForEntity() const { return MASK_PLAYERSOLID; } //----------------------------------------------------------------------------- // Purpose: // Input : *buf - // totalcmds - // dropped_packets - // ignore - // paused - // Output : float -- Time in seconds of last movement command //----------------------------------------------------------------------------- void CBasePlayer::ProcessUsercmds( CUserCmd *cmds, int numcmds, int totalcmds, int dropped_packets, bool paused ) { CCommandContext *ctx = AllocCommandContext(); Assert( ctx ); int i; for ( i = totalcmds - 1; i >= 0; i-- ) { ctx->cmds[ i ] = cmds[ i ]; } ctx->numcmds = numcmds; ctx->totalcmds = totalcmds, ctx->dropped_packets = dropped_packets; ctx->paused = paused; // Set global pause state for this player m_bGamePaused = paused; if ( paused ) { m_nSimulationTick = -1; // Just run the commands right away if paused PhysicsSimulate(); } } //----------------------------------------------------------------------------- // Purpose: // Input : *ucmd - // *moveHelper - //----------------------------------------------------------------------------- void CBasePlayer::PlayerRunCommand(CUserCmd *ucmd, IMoveHelper *moveHelper) { m_touchedPhysObject = false; if ( pl.fixangle == FIXANGLE_NONE) { VectorCopy ( ucmd->viewangles, pl.v_angle ); } // Handle FL_FROZEN. // Prevent player moving for some seconds after New Game, so that they pick up everything if( GetFlags() & FL_FROZEN || (developer.GetInt() == 0 && gpGlobals->eLoadType == MapLoad_NewGame && gpGlobals->curtime < 3.0 ) ) { ucmd->forwardmove = 0; ucmd->sidemove = 0; ucmd->upmove = 0; ucmd->buttons = 0; ucmd->impulse = 0; VectorCopy ( pl.v_angle, ucmd->viewangles ); } PlayerMove()->RunCommand(this, ucmd, moveHelper); } void CBasePlayer::HandleFuncTrain(void) { if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) AddFlag( FL_ONTRAIN ); else RemoveFlag( FL_ONTRAIN ); // Train speed control if (( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) == 0) { if (m_iTrain & TRAIN_ACTIVE) { m_iTrain = TRAIN_NEW; // turn off train } return; } CBaseEntity *pTrain = GetGroundEntity(); float vel; if ( pTrain ) { if ( !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) ) pTrain = NULL; } if ( !pTrain ) { if ( GetActiveWeapon()->ObjectCaps() & FCAP_DIRECTIONAL_USE ) { m_iTrain = TRAIN_ACTIVE | TRAIN_NEW; if ( m_nButtons & IN_FORWARD ) { m_iTrain |= TRAIN_FAST; } else if ( m_nButtons & IN_BACK ) { m_iTrain |= TRAIN_BACK; } else { m_iTrain |= TRAIN_NEUTRAL; } return; } else { trace_t trainTrace; // Maybe this is on the other side of a level transition UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + Vector(0,0,-38), MASK_PLAYERSOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trainTrace ); if ( trainTrace.fraction != 1.0 && trainTrace.m_pEnt ) pTrain = trainTrace.m_pEnt; if ( !pTrain || !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) || !pTrain->OnControls(this) ) { m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } } } else if ( !( GetFlags() & FL_ONGROUND ) || pTrain->HasSpawnFlags( SF_TRACKTRAIN_NOCONTROL ) || (m_nButtons & (IN_MOVELEFT|IN_MOVERIGHT) ) ) { // Turn off the train if you jump, strafe, or the train controls go dead m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } SetAbsVelocity( vec3_origin ); vel = 0; if ( m_afButtonPressed & IN_FORWARD ) { vel = 1; pTrain->Use( this, this, USE_SET, (float)vel ); } else if ( m_afButtonPressed & IN_BACK ) { vel = -1; pTrain->Use( this, this, USE_SET, (float)vel ); } if (vel) { m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed()); m_iTrain |= TRAIN_ACTIVE|TRAIN_NEW; } } void CBasePlayer::PreThink(void) { if ( g_fGameOver || m_iPlayerLocked ) return; // intermission or finale ItemPreFrame( ); WaterMove(); if ( g_pGameRules && g_pGameRules->FAllowFlashlight() ) m_Local.m_iHideHUD &= ~HIDEHUD_FLASHLIGHT; else m_Local.m_iHideHUD |= HIDEHUD_FLASHLIGHT; // checks if new client data (for HUD and view control) needs to be sent to the client UpdateClientData(); CheckTimeBasedDamage(); CheckSuitUpdate(); if ( GetObserverMode() > OBS_MODE_FIXED ) { CheckObserverSettings(); // do this each frame } if (m_lifeState >= LIFE_DYING) return; HandleFuncTrain(); if (m_nButtons & IN_JUMP) { // If on a ladder, jump off the ladder // else Jump Jump(); } // If trying to duck, already ducked, or in the process of ducking if ((m_nButtons & IN_DUCK) || (GetFlags() & FL_DUCKING) || (m_afPhysicsFlags & PFLAG_DUCKING) ) Duck(); // // If we're not on the ground, we're falling. Update our falling velocity. // if ( !( GetFlags() & FL_ONGROUND ) ) { m_Local.m_flFallVelocity = -GetAbsVelocity().z; } CNavArea *area = TheNavMesh->GetNavArea( &GetAbsOrigin() ); if (area && area != m_lastNavArea) { // player entered a new nav area m_lastNavArea = area; // generate event //KeyValues *event = new KeyValues( "player_entered_area" ); //event->SetInt( "userid", GetUserID() ); //event->SetInt( "areaid", area->GetID() ); //gameeventmanager->FireEvent( event ); } // StudioFrameAdvance( );//!!!HACKHACK!!! Can't be hit by traceline when not animating? } /* Time based Damage works as follows: 1) There are several types of timebased damage: #define DMG_PARALYZE (1 << 14) // slows affected creature down #define DMG_NERVEGAS (1 << 15) // nerve toxins, very bad #define DMG_POISON (1 << 16) // blood poisioning #define DMG_RADIATION (1 << 17) // radiation exposure #define DMG_DROWNRECOVER (1 << 18) // drown recovery #define DMG_ACID (1 << 19) // toxic chemicals or acid burns #define DMG_SLOWBURN (1 << 20) // in an oven 2) A new hit inflicting tbd restarts the tbd counter - each NPC has an 8bit counter, per damage type. The counter is decremented every second, so the maximum time an effect will last is 255/60 = 4.25 minutes. Of course, staying within the radius of a damaging effect like fire, nervegas, radiation will continually reset the counter to max. 3) Every second that a tbd counter is running, the player takes damage. The damage is determined by the type of tdb. Paralyze - 1/2 movement rate, 30 second duration. Nervegas - 5 points per second, 16 second duration = 80 points max dose. Poison - 2 points per second, 25 second duration = 50 points max dose. Radiation - 1 point per second, 50 second duration = 50 points max dose. Drown - 5 points per second, 2 second duration. Acid/Chemical - 5 points per second, 10 second duration = 50 points max. Burn - 10 points per second, 2 second duration. Freeze - 3 points per second, 10 second duration = 30 points max. 4) Certain actions or countermeasures counteract the damaging effects of tbds: Armor/Heater/Cooler - Chemical(acid),burn, freeze all do damage to armor power, then to body - recharged by suit recharger Air In Lungs - drowning damage is done to air in lungs first, then to body - recharged by poking head out of water - 10 seconds if swiming fast Air In SCUBA - drowning damage is done to air in tanks first, then to body - 2 minutes in tanks. Need new tank once empty. Radiation Syringe - Each syringe full provides protection vs one radiation dosage Antitoxin Syringe - Each syringe full provides protection vs one poisoning (nervegas or poison). Health kit - Immediate stop to acid/chemical, fire or freeze damage. Radiation Shower - Immediate stop to radiation damage, acid/chemical or fire damage. */ // If player is taking time based damage, continue doing damage to player - // this simulates the effect of being poisoned, gassed, dosed with radiation etc - // anything that continues to do damage even after the initial contact stops. // Update all time based damage counters, and shut off any that are done. // The m_bitsDamageType bit MUST be set if any damage is to be taken. // This routine will detect the initial on value of the m_bitsDamageType // and init the appropriate counter. Only processes damage every second. //#define PARALYZE_DURATION 30 // number of 2 second intervals to take damage //#define PARALYZE_DAMAGE 0.0 // damage to take each 2 second interval //#define NERVEGAS_DURATION 16 //#define NERVEGAS_DAMAGE 5.0 //#define POISON_DURATION 25 //#define POISON_DAMAGE 2.0 //#define RADIATION_DURATION 50 //#define RADIATION_DAMAGE 1.0 //#define ACID_DURATION 10 //#define ACID_DAMAGE 5.0 //#define SLOWBURN_DURATION 2 //#define SLOWBURN_DAMAGE 1.0 //#define SLOWFREEZE_DURATION 1.0 //#define SLOWFREEZE_DAMAGE 3.0 /* */ void CBasePlayer::CheckTimeBasedDamage() { int i; byte bDuration = 0; static float gtbdPrev = 0.0; if (!(m_bitsDamageType & DMG_TIMEBASED)) return; // only check for time based damage approx. every 2 seconds if (abs(gpGlobals->curtime - m_tbdPrev) < 2.0) return; m_tbdPrev = gpGlobals->curtime; for (i = 0; i < CDMG_TIMEBASED; i++) { // make sure bit is set for damage type if (m_bitsDamageType & (DMG_PARALYZE << i)) { switch (i) { case itbd_Paralyze: // UNDONE - flag movement as half-speed bDuration = PARALYZE_DURATION; break; case itbd_NerveGas: // OnTakeDamage(pev, pev, NERVEGAS_DAMAGE, DMG_GENERIC); bDuration = NERVEGAS_DURATION; break; // case itbd_Poison: // OnTakeDamage( CTakeDamageInfo( this, this, POISON_DAMAGE, DMG_GENERIC ) ); // bDuration = POISON_DURATION; // break; case itbd_Radiation: // OnTakeDamage(pev, pev, RADIATION_DAMAGE, DMG_GENERIC); bDuration = RADIATION_DURATION; break; case itbd_DrownRecover: // NOTE: this hack is actually used to RESTORE health // after the player has been drowning and finally takes a breath if (m_idrowndmg > m_idrownrestored) { int idif = min(m_idrowndmg - m_idrownrestored, 10); TakeHealth(idif, DMG_GENERIC); m_idrownrestored += idif; } bDuration = 4; // get up to 5*10 = 50 points back break; case itbd_PoisonRecover: { // NOTE: this hack is actually used to RESTORE health // after the player has been poisoned. if (m_nPoisonDmg > m_nPoisonRestored) { int nDif = min(m_nPoisonDmg - m_nPoisonRestored, 10); TakeHealth(nDif, DMG_GENERIC); m_nPoisonRestored += nDif; } bDuration = 9; // get up to 10*10 = 100 points back break; } case itbd_Acid: // OnTakeDamage(pev, pev, ACID_DAMAGE, DMG_GENERIC); bDuration = ACID_DURATION; break; case itbd_SlowBurn: // OnTakeDamage(pev, pev, SLOWBURN_DAMAGE, DMG_GENERIC); bDuration = SLOWBURN_DURATION; break; case itbd_SlowFreeze: // OnTakeDamage(pev, pev, SLOWFREEZE_DAMAGE, DMG_GENERIC); bDuration = SLOWFREEZE_DURATION; break; default: bDuration = 0; } if (m_rgbTimeBasedDamage[i]) { // decrement damage duration, detect when done. if (!m_rgbTimeBasedDamage[i] || --m_rgbTimeBasedDamage[i] == 0) { m_rgbTimeBasedDamage[i] = 0; // if we're done, clear damage bits m_bitsDamageType &= ~(DMG_PARALYZE << i); } } else // first time taking this damage type - init damage duration m_rgbTimeBasedDamage[i] = bDuration; } } } /* THE POWER SUIT The Suit provides 3 main functions: Protection, Notification and Augmentation. Some functions are automatic, some require power. The player gets the suit shortly after getting off the train in C1A0 and it stays with him for the entire game. Protection Heat/Cold When the player enters a hot/cold area, the heating/cooling indicator on the suit will come on and the battery will drain while the player stays in the area. After the battery is dead, the player starts to take damage. This feature is built into the suit and is automatically engaged. Radiation Syringe This will cause the player to be immune from the effects of radiation for N seconds. Single use item. Anti-Toxin Syringe This will cure the player from being poisoned. Single use item. Health Small (1st aid kits, food, etc.) Large (boxes on walls) Armor The armor works using energy to create a protective field that deflects a percentage of damage projectile and explosive attacks. After the armor has been deployed, it will attempt to recharge itself to full capacity with the energy reserves from the battery. It takes the armor N seconds to fully charge. Notification (via the HUD) x Health x Ammo x Automatic Health Care Notifies the player when automatic healing has been engaged. x Geiger counter Classic Geiger counter sound and status bar at top of HUD alerts player to dangerous levels of radiation. This is not visible when radiation levels are normal. x Poison Armor Displays the current level of armor. Augmentation Reanimation (w/adrenaline) Causes the player to come back to life after he has been dead for 3 seconds. Will not work if player was gibbed. Single use. Long Jump Used by hitting the ??? key(s). Caused the player to further than normal. SCUBA Used automatically after picked up and after player enters the water. Works for N seconds. Single use. Things powered by the battery Armor Uses N watts for every M units of damage. Heat/Cool Uses N watts for every second in hot/cold area. Long Jump Uses N watts for every jump. Alien Cloak Uses N watts for each use. Each use lasts M seconds. Alien Shield Augments armor. Reduces Armor drain by one half */ // if in range of radiation source, ping geiger counter #define GEIGERDELAY 0.25 void CBasePlayer::UpdateGeigerCounter( void ) { byte range; // delay per update ie: don't flood net with these msgs if (gpGlobals->curtime < m_flgeigerDelay) return; m_flgeigerDelay = gpGlobals->curtime + GEIGERDELAY; // send range to radition source to client range = (byte) clamp(m_flgeigerRange / 4, 0, 255); // This is to make sure you aren't driven crazy by geiger while in the airboat if ( IsInAVehicle() ) { range = clamp( (int)range * 4, 0, 255 ); } if (range != m_igeigerRangePrev) { m_igeigerRangePrev = range; CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "Geiger" ); WRITE_BYTE( range ); MessageEnd(); } // reset counter and semaphore if (!random->RandomInt(0,3)) { m_flgeigerRange = 1000; } } /* ================ CheckSuitUpdate Play suit update if it's time ================ */ #define SUITUPDATETIME 3.5 #define SUITFIRSTUPDATETIME 0.1 void CBasePlayer::CheckSuitUpdate() { int i; int isentence = 0; int isearch = m_iSuitPlayNext; // Ignore suit updates if no suit if ( !IsSuitEquipped() ) return; // if in range of radiation source, ping geiger counter UpdateGeigerCounter(); if ( g_pGameRules->IsMultiplayer() ) { // don't bother updating HEV voice in multiplayer. return; } if ( gpGlobals->curtime >= m_flSuitUpdate && m_flSuitUpdate > 0) { // play a sentence off of the end of the queue for (i = 0; i < CSUITPLAYLIST; i++) { if ((isentence = m_rgSuitPlayList[isearch]) != 0) break; if (++isearch == CSUITPLAYLIST) isearch = 0; } if (isentence) { m_rgSuitPlayList[isearch] = 0; if (isentence > 0) { // play sentence number char sentence[512]; Q_snprintf( sentence, sizeof( sentence ), "!%s", engine->SentenceNameFromIndex( isentence ) ); UTIL_EmitSoundSuit( edict(), sentence ); } else { // play sentence group UTIL_EmitGroupIDSuit(edict(), -isentence); } m_flSuitUpdate = gpGlobals->curtime + SUITUPDATETIME; } else // queue is empty, don't check m_flSuitUpdate = 0; } } // add sentence to suit playlist queue. if fgroup is true, then // name is a sentence group (HEV_AA), otherwise name is a specific // sentence name ie: !HEV_AA0. If iNoRepeat is specified in // seconds, then we won't repeat playback of this word or sentence // for at least that number of seconds. void CBasePlayer::SetSuitUpdate(char *name, int fgroup, int iNoRepeatTime) { int i; int isentence; int iempty = -1; // Ignore suit updates if no suit if ( !IsSuitEquipped() ) return; if ( g_pGameRules->IsMultiplayer() ) { // due to static channel design, etc. We don't play HEV sounds in multiplayer right now. return; } // if name == NULL, then clear out the queue if (!name) { for (i = 0; i < CSUITPLAYLIST; i++) m_rgSuitPlayList[i] = 0; return; } // get sentence or group number if (!fgroup) { isentence = SENTENCEG_Lookup(name); // Lookup sentence index (not group) by name if (isentence < 0) return; } else // mark group number as negative isentence = -SENTENCEG_GetIndex(name); // Lookup group index by name // check norepeat list - this list lets us cancel // the playback of words or sentences that have already // been played within a certain time. for (i = 0; i < CSUITNOREPEAT; i++) { if (isentence == m_rgiSuitNoRepeat[i]) { // this sentence or group is already in // the norepeat list if (m_rgflSuitNoRepeatTime[i] < gpGlobals->curtime) { // norepeat time has expired, clear it out m_rgiSuitNoRepeat[i] = 0; m_rgflSuitNoRepeatTime[i] = 0.0; iempty = i; break; } else { // don't play, still marked as norepeat return; } } // keep track of empty slot if (!m_rgiSuitNoRepeat[i]) iempty = i; } // sentence is not in norepeat list, save if norepeat time was given if (iNoRepeatTime) { if (iempty < 0) iempty = random->RandomInt(0, CSUITNOREPEAT-1); // pick random slot to take over m_rgiSuitNoRepeat[iempty] = isentence; m_rgflSuitNoRepeatTime[iempty] = iNoRepeatTime + gpGlobals->curtime; } // find empty spot in queue, or overwrite last spot m_rgSuitPlayList[m_iSuitPlayNext++] = isentence; if (m_iSuitPlayNext == CSUITPLAYLIST) m_iSuitPlayNext = 0; if (m_flSuitUpdate <= gpGlobals->curtime) { if (m_flSuitUpdate == 0) // play queue is empty, don't delay too long before playback m_flSuitUpdate = gpGlobals->curtime + SUITFIRSTUPDATETIME; else m_flSuitUpdate = gpGlobals->curtime + SUITUPDATETIME; } } //========================================================= // UpdatePlayerSound - updates the position of the player's // reserved sound slot in the sound list. //========================================================= void CBasePlayer::UpdatePlayerSound ( void ) { int iBodyVolume; int iVolume; CSound *pSound; pSound = CSoundEnt::SoundPointerForIndex( CSoundEnt::ClientSoundIndex( edict() ) ); if ( !pSound ) { Msg( "Client lost reserved sound!\n" ); return; } if (GetFlags() & FL_NOTARGET) { pSound->m_iVolume = 0; return; } // now figure out how loud the player's movement is. if ( GetFlags() & FL_ONGROUND ) { iBodyVolume = GetAbsVelocity().Length(); // clamp the noise that can be made by the body, in case a push trigger, // weapon recoil, or anything shoves the player abnormally fast. // NOTE: 512 units is a pretty large radius for a sound made by the player's body. // then again, I think some materials are pretty loud. if ( iBodyVolume > 512 ) { iBodyVolume = 512; } } else { iBodyVolume = 0; } if ( m_nButtons & IN_JUMP ) { // Jumping is a little louder. iBodyVolume += 100; } m_iTargetVolume = iBodyVolume; // if target volume is greater than the player sound's current volume, we paste the new volume in // immediately. If target is less than the current volume, current volume is not set immediately to the // lower volume, rather works itself towards target volume over time. This gives NPCs a much better chance // to hear a sound, especially if they don't listen every frame. iVolume = pSound->Volume(); if ( m_iTargetVolume > iVolume ) { iVolume = m_iTargetVolume; } else if ( iVolume > m_iTargetVolume ) { iVolume -= 250 * gpGlobals->frametime; if ( iVolume < m_iTargetVolume ) { iVolume = 0; } } if ( pSound ) { pSound->SetSoundOrigin( GetAbsOrigin() ); pSound->m_iType = SOUND_PLAYER; pSound->m_iVolume = iVolume; } // Below are a couple of useful little bits that make it easier to visualize just how much noise the // player is making. //Vector forward = UTIL_YawToVector( pl.v_angle.y ); //UTIL_Sparks( GetAbsOrigin() + forward * iVolume ); //Msg( "%d/%d\n", iVolume, m_iTargetVolume ); } // This is a glorious hack to find free space when you've crouched into some solid space // Our crouching collisions do not work correctly for some reason and this is easier // than fixing the problem :( void FixPlayerCrouchStuck( CBasePlayer *pPlayer ) { trace_t trace; // Move up as many as 18 pixels if the player is stuck. for ( int i = 0; i < 18; i++ ) { UTIL_TraceHull( pPlayer->GetAbsOrigin(), pPlayer->GetAbsOrigin(), VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX, MASK_PLAYERSOLID, pPlayer, COLLISION_GROUP_NONE, &trace ); if ( trace.startsolid ) { Vector origin = pPlayer->GetAbsOrigin(); origin.z += 1.0f; pPlayer->SetLocalOrigin( origin ); } else break; } } #define SMOOTHING_FACTOR 0.9 extern CMoveData *g_pMoveData; // UNDONE: Look and see if the ground entity is in hierarchy with a MOVETYPE_VPHYSICS? // Behavior in that case is not as good currently when the parent is rideable bool CBasePlayer::IsRideablePhysics( IPhysicsObject *pPhysics ) { if ( pPhysics ) { if ( pPhysics->GetMass() > (VPhysicsGetObject()->GetMass()*2) ) return true; } return false; } IPhysicsObject *CBasePlayer::GetGroundVPhysics() { CBaseEntity *pGroundEntity = GetGroundEntity(); if ( pGroundEntity && pGroundEntity->GetMoveType() == MOVETYPE_VPHYSICS ) { IPhysicsObject *pPhysGround = pGroundEntity->VPhysicsGetObject(); if ( pPhysGround && pPhysGround->IsMoveable() ) return pPhysGround; } return NULL; } //----------------------------------------------------------------------------- // For debugging... //----------------------------------------------------------------------------- void CBasePlayer::ForceOrigin( const Vector &vecOrigin ) { m_bForceOrigin = true; m_vForcedOrigin = vecOrigin; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::PostThink() { m_vecSmoothedVelocity = m_vecSmoothedVelocity * SMOOTHING_FACTOR + GetAbsVelocity() * ( 1 - SMOOTHING_FACTOR ); if ( !g_fGameOver && !m_iPlayerLocked && IsAlive() ) { // set correct collision bounds (may have changed in player movement code) if ( GetFlags() & FL_DUCKING ) { SetCollisionBounds( VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX ); } else { SetCollisionBounds( VEC_HULL_MIN, VEC_HULL_MAX ); } // Handle controlling an entity if ( m_hUseEntity != NULL ) { // if they've moved too far from the gun, or deployed another weapon, unuse the gun if ( m_hUseEntity->OnControls( this ) && ( !GetActiveWeapon() || GetActiveWeapon()->IsEffectActive( EF_NODRAW ) || ( GetActiveWeapon()->GetActivity() == ACT_VM_HOLSTER ) ) ) { m_hUseEntity->Use( this, this, USE_SET, 2 ); // try fire the gun } else { // they've moved off the controls ClearUseEntity(); } } // do weapon stuff ItemPostFrame(); if ( GetFlags() & FL_ONGROUND ) { if (m_Local.m_flFallVelocity > 64 && !g_pGameRules->IsMultiplayer()) { CSoundEnt::InsertSound ( SOUND_PLAYER, GetAbsOrigin(), m_Local.m_flFallVelocity, 0.2, this ); // Msg( "fall %f\n", m_Local.m_flFallVelocity ); } m_Local.m_flFallVelocity = 0; } // select the proper animation for the player character if ( IsAlive() ) { // If he's in a vehicle, sit down if ( IsInAVehicle() ) SetAnimation( PLAYER_IN_VEHICLE ); else if (!GetAbsVelocity().x && !GetAbsVelocity().y) SetAnimation( PLAYER_IDLE ); else if ((GetAbsVelocity().x || GetAbsVelocity().y) && ( GetFlags() & FL_ONGROUND )) SetAnimation( PLAYER_WALK ); else if (GetWaterLevel() > 1) SetAnimation( PLAYER_WALK ); } // Don't allow bogus sequence on player if ( GetSequence() == -1 ) { SetSequence( 0 ); } StudioFrameAdvance(); DispatchAnimEvents( this ); SetSimulationTime( gpGlobals->curtime ); //Let the weapon update as well Weapon_FrameUpdate(); UpdatePlayerSound(); if ( m_bForceOrigin ) { SetLocalOrigin( m_vForcedOrigin ); SetLocalAngles( m_Local.m_vecPunchAngle ); m_Local.m_vecPunchAngle = RandomAngle( -25, 25 ); m_Local.m_vecPunchAngleVel.Init(); } PostThinkVPhysics(); } // Even if dead simulate entities SimulatePlayerSimulatedEntities(); } // handles touching physics objects void CBasePlayer::Touch( CBaseEntity *pOther ) { if ( pOther == GetGroundEntity() ) return; if ( pOther->GetMoveType() != MOVETYPE_VPHYSICS || pOther->GetSolid() != SOLID_VPHYSICS || (pOther->GetSolidFlags() & FSOLID_TRIGGER) ) return; IPhysicsObject *pPhys = pOther->VPhysicsGetObject(); if ( !pPhys || !pPhys->IsMoveable() ) return; SetTouchedPhysics( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::PostThinkVPhysics( void ) { // Check to see if things are initialized! if ( !m_pPhysicsController ) return; Vector newPosition = GetAbsOrigin(); float frametime = gpGlobals->frametime; if ( frametime <= 0 || frametime > 0.1f ) frametime = 0.1f; IPhysicsObject *pPhysGround = GetGroundVPhysics(); if ( !pPhysGround && m_touchedPhysObject && g_pMoveData->m_outStepHeight <= 0.f && (GetFlags() & FL_ONGROUND) ) { newPosition = m_oldOrigin + frametime * g_pMoveData->m_outWishVel; newPosition = (GetAbsOrigin() * 0.5f) + (newPosition * 0.5f); } int collisionState = VPHYS_WALK; if ( GetMoveType() == MOVETYPE_NOCLIP || GetMoveType() == MOVETYPE_OBSERVER ) { collisionState = VPHYS_NOCLIP; } else if ( GetFlags() & FL_DUCKING ) { collisionState = VPHYS_CROUCH; } if ( collisionState != m_vphysicsCollisionState ) { SetVCollisionState( collisionState ); } if ( !(TouchedPhysics() || pPhysGround) ) { g_pMoveData->m_outWishVel.Init( m_flMaxspeed, m_flMaxspeed, m_flMaxspeed ); } // teleport the physics object up by stepheight (game code does this - reflect in the physics) if ( g_pMoveData->m_outStepHeight > 0.1f ) { if ( g_pMoveData->m_outStepHeight > 4.0f ) { VPhysicsGetObject()->SetPosition( GetAbsOrigin(), vec3_angle, true ); } else { // don't ever teleport into solid Vector position, end; VPhysicsGetObject()->GetPosition( &position, NULL ); end = position; end.z += g_pMoveData->m_outStepHeight; trace_t trace; UTIL_TraceEntity( this, position, end, MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER_MOVEMENT, &trace ); if ( trace.DidHit() ) { g_pMoveData->m_outStepHeight = trace.endpos.z - position.z; } m_pPhysicsController->StepUp( g_pMoveData->m_outStepHeight ); } m_pPhysicsController->Jump(); } g_pMoveData->m_outStepHeight = 0.0f; // Store these off because after running the usercmds, it'll pass them // to UpdateVPhysicsPosition. m_vNewVPhysicsPosition = newPosition; m_vNewVPhysicsVelocity = g_pMoveData->m_outWishVel; m_oldOrigin = GetAbsOrigin(); } void CBasePlayer::UpdateVPhysicsPosition( const Vector &position, const Vector &velocity, float secondsToArrival ) { bool onground = (GetFlags() & FL_ONGROUND) ? true : false; IPhysicsObject *pPhysGround = GetGroundVPhysics(); // if the object is much heavier than the player, treat it as a local coordinate system // the player controller will solve movement differently in this case. if ( !IsRideablePhysics(pPhysGround) ) { pPhysGround = NULL; } m_pPhysicsController->Update( position, velocity, secondsToArrival, onground, pPhysGround ); } void CBasePlayer::UpdatePhysicsShadowToCurrentPosition() { UpdateVPhysicsPosition( GetAbsOrigin(), vec3_origin, gpGlobals->frametime ); } Vector CBasePlayer::GetSmoothedVelocity( void ) { if ( IsInAVehicle() ) { return GetVehicle()->GetVehicleEnt()->GetSmoothedVelocity(); } return m_vecSmoothedVelocity; } CBaseEntity *g_pLastSpawn = NULL; //----------------------------------------------------------------------------- // Purpose: Finds a player start entity of the given classname. If any entity of // of the given classname has the SF_PLAYER_START_MASTER flag set, that // is the entity that will be returned. Otherwise, the first entity of // the given classname is returned. // Input : pszClassName - should be "info_player_start", "info_player_coop", or // "info_player_deathmatch" //----------------------------------------------------------------------------- CBaseEntity *FindPlayerStart(const char *pszClassName) { #define SF_PLAYER_START_MASTER 1 CBaseEntity *pStart = gEntList.FindEntityByClassname(NULL, pszClassName); CBaseEntity *pStartFirst = pStart; while (pStart != NULL) { if (pStart->HasSpawnFlags(SF_PLAYER_START_MASTER)) { return pStart; } pStart = gEntList.FindEntityByClassname(pStart, pszClassName); } return pStartFirst; } /* ============ EntSelectSpawnPoint Returns the entity to spawn at USES AND SETS GLOBAL g_pLastSpawn ============ */ CBaseEntity *CBasePlayer::EntSelectSpawnPoint() { CBaseEntity *pSpot; edict_t *player; player = edict(); // choose a info_player_deathmatch point if (g_pGameRules->IsCoOp()) { pSpot = gEntList.FindEntityByClassname( g_pLastSpawn, "info_player_coop"); if ( pSpot ) goto ReturnSpot; pSpot = gEntList.FindEntityByClassname( g_pLastSpawn, "info_player_start"); if ( pSpot ) goto ReturnSpot; } else if ( g_pGameRules->IsDeathmatch() ) { pSpot = g_pLastSpawn; // Randomize the start spot for ( int i = random->RandomInt(1,5); i > 0; i-- ) pSpot = gEntList.FindEntityByClassname( pSpot, "info_player_deathmatch" ); if ( !pSpot ) // skip over the null point pSpot = gEntList.FindEntityByClassname( pSpot, "info_player_deathmatch" ); CBaseEntity *pFirstSpot = pSpot; do { if ( pSpot ) { // check if pSpot is valid if ( g_pGameRules->IsSpawnPointValid( pSpot, this ) ) { if ( pSpot->GetLocalOrigin() == vec3_origin ) { pSpot = gEntList.FindEntityByClassname( pSpot, "info_player_deathmatch" ); continue; } // if so, go to pSpot goto ReturnSpot; } } // increment pSpot pSpot = gEntList.FindEntityByClassname( pSpot, "info_player_deathmatch" ); } while ( pSpot != pFirstSpot ); // loop if we're not back to the start // we haven't found a place to spawn yet, so kill any guy at the first spawn point and spawn there if ( pSpot ) { CBaseEntity *ent = NULL; for ( CEntitySphereQuery sphere( pSpot->GetAbsOrigin(), 128 ); (ent = sphere.GetCurrentEntity()) != NULL; sphere.NextEntity() ) { // if ent is a client, kill em (unless they are ourselves) if ( ent->IsPlayer() && !(ent->edict() == player) ) ent->TakeDamage( CTakeDamageInfo( GetContainingEntity(INDEXENT(0)), GetContainingEntity(INDEXENT(0)), 300, DMG_GENERIC ) ); } goto ReturnSpot; } } // If startspot is set, (re)spawn there. if ( !gpGlobals->startspot || !strlen(STRING(gpGlobals->startspot))) { pSpot = FindPlayerStart( "info_player_start" ); if ( pSpot ) goto ReturnSpot; } else { pSpot = gEntList.FindEntityByName( NULL, gpGlobals->startspot, NULL ); if ( pSpot ) goto ReturnSpot; } ReturnSpot: if ( !pSpot ) { Warning( "PutClientInServer: no info_player_start on level\n"); return CBaseEntity::Instance( INDEXENT( 0 ) ); } g_pLastSpawn = pSpot; return pSpot; } //----------------------------------------------------------------------------- // Purpose: Called the first time the player's created //----------------------------------------------------------------------------- void CBasePlayer::InitialSpawn( void ) { m_bConnected = true; } //----------------------------------------------------------------------------- // Purpose: Called everytime the player respawns //----------------------------------------------------------------------------- void CBasePlayer::Spawn( void ) { SetClassname( "player" ); // Shared spawning code.. SharedSpawn(); SetSimulatedEveryTick( true ); SetAnimatedEveryTick( true ); m_ArmorValue = 0; SetBlocksLOS( false ); m_iMaxHealth = m_iHealth; // Clear all flags except for FL_FULLEDICT if ( GetFlags() & FL_FAKECLIENT ) { ClearFlags(); AddFlag( FL_CLIENT | FL_FAKECLIENT ); } else { ClearFlags(); AddFlag( FL_CLIENT ); } AddFlag( FL_AIMTARGET ); m_AirFinished = gpGlobals->curtime + AIRTIME; m_nDrownDmgRate = DROWNING_DAMAGE_INITIAL; // only preserve the shadow flag int effects = GetEffects() & EF_NOSHADOW; SetEffects( effects ); m_DmgTake = 0; m_DmgSave = 0; m_bitsHUDDamage = -1; m_bitsDamageType = 0; m_afPhysicsFlags = 0; SetFOV( this, 0 ); m_flNextDecalTime = 0;// let this player decal as soon as he spawns. m_flgeigerDelay = gpGlobals->curtime + 2.0; // wait a few seconds until user-defined message registrations // are recieved by all clients m_flTimeStepSound = 0; m_flFieldOfView = 0.766;// some NPCs use this to determine whether or not the player is looking at them. m_vecAdditionalPVSOrigin = vec3_origin; m_vecCameraPVSOrigin = vec3_origin; if ( !m_fGameHUDInitialized ) g_pGameRules->SetDefaultPlayerTeam( this ); g_pGameRules->GetPlayerSpawnSpot( this ); SetViewOffset( VEC_VIEW ); Precache(); m_bitsDamageType = 0; m_bitsHUDDamage = -1; m_bPlayerUnderwater = false; m_iTrain = TRAIN_NEW; m_HackedGunPos = Vector( 0, 32, 0 ); if ( m_iPlayerSound == SOUNDLIST_EMPTY ) { Msg( "Couldn't alloc player sound slot!\n" ); } SetThink(NULL); m_fInitHUD = true; m_fWeapon = false; m_iClientBattery = -1; m_lastx = m_lasty = 0; m_lastNavArea = NULL; CSingleUserRecipientFilter user( this ); enginesound->SetPlayerDSP( user, 0, false ); CreateViewModel(); SetCollisionGroup( COLLISION_GROUP_PLAYER ); // if the player is locked, make sure he stays locked if ( m_iPlayerLocked ) { m_iPlayerLocked = false; LockPlayerInPlace(); } if ( GetTeamNumber() != TEAM_SPECTATOR ) { StopObserverMode(); } else { StartObserverMode( m_iObserverLastMode ); } // Clear any screenfade color32 nothing = {0,0,0,255}; UTIL_ScreenFade( this, nothing, 0, 0, FFADE_IN | FFADE_PURGE ); g_pGameRules->PlayerSpawn( this ); m_flLaggedMovementValue = 1.0f; m_vecSmoothedVelocity = vec3_origin; InitVCollision(); } void CBasePlayer::Activate( void ) { BaseClass::Activate(); AimTarget_ForceRepopulateList(); } void CBasePlayer::Precache( void ) { BaseClass::Precache(); PrecacheScriptSound( "Player.FallGib" ); PrecacheScriptSound( "Player.Death" ); PrecacheScriptSound( "Player.PlasmaDamage" ); PrecacheScriptSound( "Player.SonicDamage" ); PrecacheScriptSound( "Player.DrownStart" ); PrecacheScriptSound( "Player.DrownContinue" ); PrecacheScriptSound( "Player.Wade" ); PrecacheScriptSound( "Player.AmbientUnderWater" ); PrecacheScriptSound( "Player.Wade" ); // in the event that the player JUST spawned, and the level node graph // was loaded, fix all of the node graph pointers before the game starts. // !!!BUGBUG - now that we have multiplayer, this needs to be moved! /* todo - put in better spot and use new ainetowrk stuff if ( WorldGraph.m_fGraphPresent && !WorldGraph.m_fGraphPointersSet ) { if ( !WorldGraph.FSetGraphPointers() ) { Msg( "**Graph pointers were not set!\n"); } else { Msg( "**Graph Pointers Set!\n" ); } } */ // SOUNDS / MODELS ARE PRECACHED in ClientPrecache() (game specific) // because they need to precache before any clients have connected // init geiger counter vars during spawn and each time // we cross a level transition m_flgeigerRange = 1000; m_igeigerRangePrev = 1000; #if 0 // @Note (toml 04-19-04): These are saved, used to be slammed here m_bitsDamageType = 0; m_bitsHUDDamage = -1; m_bPlayerUnderwater = false; m_iTrain = TRAIN_NEW; #endif m_iClientBattery = -1; m_iUpdateTime = 5; // won't update for 1/2 a second if ( gInitHUD ) m_fInitHUD = true; } int CBasePlayer::Save( ISave &save ) { if ( !BaseClass::Save(save) ) return 0; return 1; } int CBasePlayer::Restore( IRestore &restore ) { int status = BaseClass::Restore(restore); if ( !status ) return 0; CSaveRestoreData *pSaveData = gpGlobals->pSaveData; // landmark isn't present. if ( !pSaveData->levelInfo.fUseLandmark ) { Msg( "No Landmark:%s\n", pSaveData->levelInfo.szLandmarkName ); // default to normal spawn CBaseEntity *pSpawnSpot = EntSelectSpawnPoint(); SetLocalOrigin( pSpawnSpot->GetLocalOrigin() + Vector(0,0,1) ); SetLocalAngles( pSpawnSpot->GetLocalAngles() ); } QAngle newViewAngles = pl.v_angle; newViewAngles.z = 0; // Clear out roll SetLocalAngles( newViewAngles ); SnapEyeAngles( newViewAngles ); // Copied from spawn() for now SetBloodColor( BLOOD_COLOR_RED ); if ( GetFlags() & FL_DUCKING ) { // Use the crouch HACK FixPlayerCrouchStuck( this ); UTIL_SetSize(this, VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX); m_Local.m_bDucked = true; } else { m_Local.m_bDucked = false; UTIL_SetSize(this, VEC_HULL_MIN, VEC_HULL_MAX); } InitVCollision(); // success return 1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::OnRestore( void ) { BaseClass::OnRestore(); SetViewEntity( m_hViewEntity ); } /* void CBasePlayer::SetTeamName( const char *pTeamName ) { Q_strncpy( m_szTeamName, pTeamName, TEAM_NAME_LENGTH ); } */ void CBasePlayer::SetArmorValue( int value ) { m_ArmorValue = value; } void CBasePlayer::IncrementArmorValue( int nCount, int nMaxValue ) { m_ArmorValue += nCount; if (nMaxValue > 0) { if (m_ArmorValue > nMaxValue) m_ArmorValue = nMaxValue; } } // Only used by the physics gun... is there a better interface? void CBasePlayer::SetPhysicsFlag( int nFlag, bool bSet ) { if (bSet) m_afPhysicsFlags |= nFlag; else m_afPhysicsFlags &= ~nFlag; } void CBasePlayer::NotifyNearbyRadiationSource( float flRange ) { // if player's current geiger counter range is larger // than range to this trigger hurt, reset player's // geiger counter range if (m_flgeigerRange >= flRange) m_flgeigerRange = flRange; } void CBasePlayer::AllowImmediateDecalPainting() { m_flNextDecalTime = gpGlobals->curtime; } // Suicide... void CBasePlayer::CommitSuicide() { if( !IsAlive() ) return; // prevent suiciding too often if ( m_fNextSuicideTime > gpGlobals->curtime ) return; // don't let them suicide for 5 seconds after suiciding m_fNextSuicideTime = gpGlobals->curtime + 5; // have the player kill themself m_iHealth = 0; Event_Killed( CTakeDamageInfo( this, this, 0, DMG_NEVERGIB ) ); Event_Dying(); } //============================================== // HasWeapons - do I have any weapons at all? //============================================== bool CBasePlayer::HasWeapons( void ) { int i; for ( i = 0 ; i < WeaponCount() ; i++ ) { if ( GetWeapon(i) ) { return true; } } return false; } //----------------------------------------------------------------------------- // Purpose: // Input : &vecForce - //----------------------------------------------------------------------------- void CBasePlayer::VelocityPunch( const Vector &vecForce ) { // Clear onground and add velocity. SetGroundEntity( NULL ); ApplyAbsVelocityImpulse(vecForce ); } //-------------------------------------------------------------------------------------------------------------- // VEHICLES //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Purpose: Put this player in a vehicle //----------------------------------------------------------------------------- void CBasePlayer::GetInVehicle( IServerVehicle *pVehicle, int nRole ) { Assert( NULL == m_hVehicle.Get() ); Assert( nRole >= 0 ); if ( pVehicle->GetPassenger( nRole ) ) return; CBaseEntity *pEnt = pVehicle->GetVehicleEnt(); Assert( pEnt ); if (!pVehicle->IsPassengerUsingStandardWeapons( nRole )) { CBaseCombatWeapon *pWeapon = GetActiveWeapon(); //Must be able to stow our weapon if ( ( pWeapon != NULL ) && ( pWeapon->Holster( NULL ) == false ) ) return; #ifndef HL2_DLL m_Local.m_iHideHUD |= HIDEHUD_WEAPONSELECTION; #endif m_Local.m_iHideHUD |= HIDEHUD_INVEHICLE; } if ( !pVehicle->IsPassengerVisible( nRole ) ) { AddEffects( EF_NODRAW ); } ViewPunchReset(); // Setting the velocity to 0 will cause the IDLE animation to play SetAbsVelocity( vec3_origin ); SetMoveType( MOVETYPE_NOCLIP ); // Choose the entry point of the vehicle, // By default, just stay at the point you started at... // NOTE: we have to set this first so that when the parent is set // the local position just works Vector vNewPos = GetAbsOrigin(); QAngle qAngles = GetAbsAngles(); pVehicle->GetPassengerStartPoint( nRole, &vNewPos, &qAngles ); SetAbsOrigin( vNewPos ); SetAbsAngles( qAngles ); SetParent( pEnt ); SetCollisionGroup( COLLISION_GROUP_IN_VEHICLE ); // We cannot be ducking -- do all this before SetPassenger because it // saves our view offset for restoration when we exit the vehicle. RemoveFlag( FL_DUCKING ); SetViewOffset( VEC_VIEW ); m_Local.m_bDucked = false; m_Local.m_bDucking = false; m_Local.m_flDucktime = 0; pVehicle->SetPassenger( nRole, this ); m_hVehicle = pEnt; // Throw an event indicating that the player entered the vehicle. g_pNotify->ReportNamedEvent( this, "PlayerEnteredVehicle" ); OnVehicleStart(); } //----------------------------------------------------------------------------- // Purpose: Remove this player from a vehicle //----------------------------------------------------------------------------- void CBasePlayer::LeaveVehicle( const Vector &vecExitPoint, const QAngle &vecExitAngles ) { if ( NULL == m_hVehicle.Get() ) return; IServerVehicle *pVehicle = GetVehicle(); Assert( pVehicle ); int nRole = pVehicle->GetPassengerRole( this ); Assert( nRole >= 0 ); SetParent( NULL ); // Find the first non-blocked exit point: Vector vNewPos = GetAbsOrigin(); QAngle qAngles = GetAbsAngles(); if ( vecExitPoint == vec3_origin ) { // FIXME: this might fail to find a safe exit point!! pVehicle->GetPassengerExitPoint( nRole, &vNewPos, &qAngles ); } else { vNewPos = vecExitPoint; qAngles = vecExitAngles; } OnVehicleEnd( vNewPos ); SetAbsOrigin( vNewPos ); SetAbsAngles( qAngles ); // Clear out any leftover velocity SetAbsVelocity( vec3_origin ); qAngles[ROLL] = 0; SnapEyeAngles( qAngles ); #ifndef HL2_DLL m_Local.m_iHideHUD &= ~HIDEHUD_WEAPONSELECTION; #endif m_Local.m_iHideHUD &= ~HIDEHUD_INVEHICLE; RemoveEffects( EF_NODRAW ); SetMoveType( MOVETYPE_WALK ); SetCollisionGroup( COLLISION_GROUP_PLAYER ); m_hVehicle = NULL; pVehicle->SetPassenger(nRole, NULL); // Re-deploy our weapon if ( IsAlive() ) { if ( GetActiveWeapon() && GetActiveWeapon()->IsWeaponVisible() == false ) { GetActiveWeapon()->Deploy(); ShowCrosshair( true ); } } } //============================================== // !!!UNDONE:ultra temporary SprayCan entity to apply // decal frame at a time. For PreAlpha CD //============================================== class CSprayCan : public CPointEntity { public: DECLARE_CLASS( CSprayCan, CPointEntity ); void Spawn ( CBasePlayer *pOwner ); void Think( void ); virtual void Precache(); virtual int ObjectCaps( void ) { return FCAP_DONT_SAVE; } }; LINK_ENTITY_TO_CLASS( spraycan, CSprayCan ); PRECACHE_REGISTER( spraycan ); void CSprayCan::Spawn ( CBasePlayer *pOwner ) { SetLocalOrigin( pOwner->WorldSpaceCenter() + Vector ( 0 , 0 , 32 ) ); SetLocalAngles( pOwner->EyeAngles() ); SetOwnerEntity( pOwner ); SetNextThink( gpGlobals->curtime ); EmitSound( "SprayCan.Paint" ); } void CSprayCan::Precache() { BaseClass::Precache(); PrecacheScriptSound( "SprayCan.Paint" ); } void CSprayCan::Think( void ) { trace_t tr; int playernum; int nFrames; CBasePlayer *pPlayer; pPlayer = ToBasePlayer( GetOwnerEntity() ); nFrames = 1; // FIXME, look up from material playernum = GetOwnerEntity()->entindex(); // Msg( "Spray by player %i, %i of %i\n", playernum, (int)(m_flFrame + 1), nFrames); Vector forward; AngleVectors( GetAbsAngles(), &forward ); UTIL_TraceLine ( GetAbsOrigin(), GetAbsOrigin() + forward * 128, MASK_SOLID_BRUSHONLY, pPlayer, COLLISION_GROUP_NONE, & tr); UTIL_PlayerDecalTrace( &tr, playernum ); // Just painted last custom frame. UTIL_Remove( this ); } class CBloodSplat : public CPointEntity { public: DECLARE_CLASS( CBloodSplat, CPointEntity ); void Spawn ( CBaseEntity *pOwner ); void Think ( void ); }; void CBloodSplat::Spawn ( CBaseEntity *pOwner ) { SetLocalOrigin( pOwner->WorldSpaceCenter() + Vector ( 0 , 0 , 32 ) ); SetLocalAngles( pOwner->GetLocalAngles() ); SetOwnerEntity( pOwner ); SetNextThink( gpGlobals->curtime + 0.1f ); } void CBloodSplat::Think( void ) { trace_t tr; if ( g_Language.GetInt() != LANGUAGE_GERMAN ) { CBasePlayer *pPlayer; pPlayer = ToBasePlayer( GetOwnerEntity() ); Vector forward; AngleVectors( GetAbsAngles(), &forward ); UTIL_TraceLine ( GetAbsOrigin(), GetAbsOrigin() + forward * 128, MASK_SOLID_BRUSHONLY, pPlayer, COLLISION_GROUP_NONE, & tr); UTIL_BloodDecalTrace( &tr, BLOOD_COLOR_RED ); } UTIL_Remove( this ); } //============================================== //----------------------------------------------------------------------------- // Purpose: Create and give the named item to the player. Then return it. //----------------------------------------------------------------------------- CBaseEntity *CBasePlayer::GiveNamedItem( const char *pszName, int iSubType ) { // If I already own this type don't create one if ( Weapon_OwnsThisType(pszName, iSubType) ) return NULL; // Msg( "giving %s\n", pszName ); EHANDLE pent; pent = CreateEntityByName(pszName); if ( pent == NULL ) { Msg( "NULL Ent in GiveNamedItem!\n" ); return NULL; } pent->SetLocalOrigin( GetLocalOrigin() ); pent->AddSpawnFlags( SF_NORESPAWN ); if ( iSubType ) { CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon*>( (CBaseEntity*)pent ); if ( pWeapon ) { pWeapon->SetSubType( iSubType ); } } DispatchSpawn( pent ); if ( pent != NULL && !(pent->IsMarkedForDeletion()) ) { pent->Touch( this ); } return pent; } //----------------------------------------------------------------------------- // Purpose: Returns the nearest COLLIBALE entity in front of the player // that has a clear line of sight with the given classname // Input : // Output : //----------------------------------------------------------------------------- CBaseEntity *FindEntityClassForward( CBasePlayer *pMe, char *classname ) { trace_t tr; Vector forward; pMe->EyeVectors( &forward ); UTIL_TraceLine(pMe->EyePosition(), pMe->EyePosition() + forward * MAX_COORD_RANGE, MASK_SOLID, pMe, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction != 1.0 && tr.DidHitNonWorldEntity() ) { CBaseEntity *pHit = tr.m_pEnt; if (FClassnameIs( pHit,classname ) ) { return pHit; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: Returns the nearest COLLIBALE entity in front of the player // that has a clear line of sight. If HULL is true, the trace will // hit the collision hull of entities. Otherwise, the trace will hit // hitboxes. // Input : // Output : //----------------------------------------------------------------------------- CBaseEntity *FindEntityForward( CBasePlayer *pMe, bool fHull ) { if ( pMe ) { trace_t tr; Vector forward; int mask; if( fHull ) { mask = MASK_SOLID; } else { mask = MASK_SHOT; } pMe->EyeVectors( &forward ); UTIL_TraceLine(pMe->EyePosition(), pMe->EyePosition() + forward * MAX_COORD_RANGE, mask, pMe, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction != 1.0 && tr.DidHitNonWorldEntity() ) { return tr.m_pEnt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: Finds the nearest entity in front of the player of the given // classname, preferring collidable entities, but allows selection of // enities that are on the other side of walls or objects // // Input : // Output : //----------------------------------------------------------------------------- CBaseEntity *FindPickerEntityClass( CBasePlayer *pPlayer, char *classname ) { // First try to trace a hull to an entity CBaseEntity *pEntity = FindEntityClassForward( pPlayer, classname ); // If that fails just look for the nearest facing entity if (!pEntity) { Vector forward; Vector origin; pPlayer->EyeVectors( &forward ); origin = pPlayer->WorldSpaceCenter(); pEntity = gEntList.FindEntityClassNearestFacing( origin, forward,0.95,classname); } return pEntity; } //----------------------------------------------------------------------------- // Purpose: Finds the nearest entity in front of the player, preferring // collidable entities, but allows selection of enities that are // on the other side of walls or objects // Input : // Output : //----------------------------------------------------------------------------- CBaseEntity *FindPickerEntity( CBasePlayer *pPlayer ) { // First try to trace a hull to an entity CBaseEntity *pEntity = FindEntityForward( pPlayer, true ); // If that fails just look for the nearest facing entity if (!pEntity) { Vector forward; Vector origin; pPlayer->EyeVectors( &forward ); origin = pPlayer->WorldSpaceCenter(); pEntity = gEntList.FindEntityNearestFacing( origin, forward,0.95); } return pEntity; } //----------------------------------------------------------------------------- // Purpose: Finds the nearest node in front of the player // Input : // Output : //----------------------------------------------------------------------------- CAI_Node *FindPickerAINode( CBasePlayer *pPlayer, NodeType_e nNodeType ) { Vector forward; Vector origin; pPlayer->EyeVectors( &forward ); origin = pPlayer->EyePosition(); return g_pAINetworkManager->GetEditOps()->FindAINodeNearestFacing( origin, forward,0.90, nNodeType); } //----------------------------------------------------------------------------- // Purpose: Finds the nearest link in front of the player // Input : // Output : //----------------------------------------------------------------------------- CAI_Link *FindPickerAILink( CBasePlayer* pPlayer ) { Vector forward; Vector origin; pPlayer->EyeVectors( &forward ); origin = pPlayer->EyePosition(); return g_pAINetworkManager->GetEditOps()->FindAILinkNearestFacing( origin, forward,0.90); } /* =============== ForceClientDllUpdate When recording a demo, we need to have the server tell us the entire client state so that the client side .dll can behave correctly. Reset stuff so that the state is transmitted. =============== */ void CBasePlayer::ForceClientDllUpdate( void ) { m_iClientBattery = -1; m_iTrain |= TRAIN_NEW; // Force new train message. m_fWeapon = false; // Force weapon send // Force all HUD data to be resent to client m_fInitHUD = true; // Now force all the necessary messages // to be sent. UpdateClientData(); UTIL_RestartAmbientSounds(); // MOTODO that updates the sounds for everybody } /* ============ ImpulseCommands ============ */ void CBasePlayer::ImpulseCommands( ) { trace_t tr; int iImpulse = (int)m_nImpulse; switch (iImpulse) { case 100: // temporary flashlight for level designers if ( FlashlightIsOn() ) { FlashlightTurnOff(); } else { FlashlightTurnOn(); } break; case 200: if ( sv_cheats->GetBool() ) { CBaseCombatWeapon *pWeapon; pWeapon = GetActiveWeapon(); if( pWeapon->IsEffectActive( EF_NODRAW ) ) { pWeapon->Deploy(); } else { pWeapon->Holster(); } } break; case 201:// paint decal if ( gpGlobals->curtime < m_flNextDecalTime ) { // too early! break; } { Vector forward; EyeVectors( &forward ); UTIL_TraceLine ( EyePosition(), EyePosition() + forward * 128, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, & tr); } if ( tr.fraction != 1.0 ) {// line hit something, so paint a decal m_flNextDecalTime = gpGlobals->curtime + decalfrequency.GetFloat(); CSprayCan *pCan = CREATE_UNSAVED_ENTITY( CSprayCan, "spraycan" ); pCan->Spawn( this ); } break; case 202:// player jungle sound if ( gpGlobals->curtime < m_flNextDecalTime ) { // too early! break; } EntityMessageBegin( this ); WRITE_BYTE( PLAY_PLAYER_JINGLE ); MessageEnd(); m_flNextDecalTime = gpGlobals->curtime + decalfrequency.GetFloat(); break; default: // check all of the cheat impulse commands now CheatImpulseCommands( iImpulse ); break; } m_nImpulse = 0; } //========================================================= //========================================================= void CBasePlayer::CheatImpulseCommands( int iImpulse ) { #if !defined( HLDEMO_BUILD ) if ( !sv_cheats->GetBool() ) { return; } CBaseEntity *pEntity; trace_t tr; switch ( iImpulse ) { case 76: { if (!giPrecacheGrunt) { giPrecacheGrunt = 1; Msg( "You must now restart to use Grunt-o-matic.\n"); } else { Vector forward = UTIL_YawToVector( EyeAngles().y ); Create("NPC_human_grunt", GetLocalOrigin() + forward * 128, GetLocalAngles()); } break; } case 81: GiveNamedItem( "weapon_cubemap" ); break; case 102: // Gibbage!!! CGib::SpawnRandomGibs( this, 1, GIB_HUMAN ); break; case 103: // What the hell are you doing? pEntity = FindEntityForward( this, true ); if ( pEntity ) { CAI_BaseNPC *pNPC = pEntity->MyNPCPointer(); if ( pNPC ) pNPC->ReportAIState(); } break; case 106: // Give me the classname and targetname of this entity. pEntity = FindEntityForward( this, true ); if ( pEntity ) { Msg( "Classname: %s", pEntity->GetClassname() ); if ( pEntity->GetEntityName() != NULL_STRING ) { Msg( " - Name: %s\n", STRING( pEntity->GetEntityName() ) ); } else { Msg( " - Name: No Targetname\n" ); } if ( pEntity->m_iParent != NULL_STRING ) Msg( "Parent: %s\n", STRING(pEntity->m_iParent) ); Msg( "Model: %s\n", STRING( pEntity->GetModelName() ) ); if ( pEntity->m_iGlobalname != NULL_STRING ) Msg( "Globalname: %s\n", STRING(pEntity->m_iGlobalname) ); } break; case 107: { trace_t tr; edict_t *pWorld = engine->PEntityOfEntIndex( 0 ); Vector start = EyePosition(); Vector forward; EyeVectors( &forward ); Vector end = start + forward * 1024; UTIL_TraceLine( start, end, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); if ( tr.m_pEnt ) pWorld = tr.m_pEnt->edict(); const char *pTextureName = tr.surface.name; if ( pTextureName ) Msg( "Texture: %s\n", pTextureName ); } break; // // Sets the debug NPC to be the NPC under the crosshair. // case 108: { pEntity = FindEntityForward( this, true ); if ( pEntity ) { CAI_BaseNPC *pNPC = pEntity->MyNPCPointer(); if ( pNPC != NULL ) { Msg( "Debugging %s (0x%x)\n", pNPC->GetClassname(), pNPC ); CAI_BaseNPC::SetDebugNPC( pNPC ); } } break; } case 195:// show shortest paths for entire level to nearest node { Create("node_viewer_fly", GetLocalOrigin(), GetLocalAngles()); } break; case 196:// show shortest paths for entire level to nearest node { Create("node_viewer_large", GetLocalOrigin(), GetLocalAngles()); } break; case 197:// show shortest paths for entire level to nearest node { Create("node_viewer_human", GetLocalOrigin(), GetLocalAngles()); } break; case 202:// Random blood splatter { Vector forward; EyeVectors( &forward ); UTIL_TraceLine ( EyePosition(), EyePosition() + forward * 128, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, & tr); if ( tr.fraction != 1.0 ) {// line hit something, so paint a decal CBloodSplat *pBlood = CREATE_UNSAVED_ENTITY( CBloodSplat, "bloodsplat" ); pBlood->Spawn( this ); } } break; case 203:// remove creature. pEntity = FindEntityForward( this, true ); if ( pEntity ) { UTIL_Remove( pEntity ); // if ( pEntity->m_takedamage ) // pEntity->SetThink(SUB_Remove); } break; } #endif // HLDEMO_BUILD } bool CBasePlayer::ClientCommand(const char *cmd) { #ifdef _DEBUG if( stricmp( cmd, "test_SmokeGrenade" ) == 0 ) { if ( sv_cheats && sv_cheats->GetBool() ) { ParticleSmokeGrenade *pSmoke = dynamic_cast<ParticleSmokeGrenade*>( CreateEntityByName(PARTICLESMOKEGRENADE_ENTITYNAME) ); if ( pSmoke ) { Vector vForward; AngleVectors( GetLocalAngles(), &vForward ); vForward.z = 0; VectorNormalize( vForward ); pSmoke->SetLocalOrigin( GetLocalOrigin() + vForward * 100 ); pSmoke->SetFadeTime(25, 30); // Fade out between 25 seconds and 30 seconds. pSmoke->Activate(); pSmoke->SetLifetime(30); pSmoke->FillVolume(); return true; } } } else #endif // _DEBUG if( stricmp( cmd, "vehicleRole" ) == 0 ) { // Get the vehicle role value. if ( engine->Cmd_Argc() == 2 ) { // Check to see if a player is in a vehicle. if ( IsInAVehicle() ) { int nRole = atoi( engine->Cmd_Argv( 1 ) ); IServerVehicle *pVehicle = GetVehicle(); if ( pVehicle ) { // Only switch roles if role is empty! if ( !pVehicle->GetPassenger( nRole ) ) { LeaveVehicle(); GetInVehicle( pVehicle, nRole ); } } } return true; } } else if ( stricmp( cmd, "spectate" ) == 0 ) // join spectator team & start observer mode { if ( GetTeamNumber() == TEAM_SPECTATOR ) return true; if ( !IsDead() ) { ClientKill( edict() ); // kill player // add 1 to frags to balance out the 1 subtracted for killing yourself IncrementFragCount( 1 ); } RemoveAllItems( true ); ChangeTeam( TEAM_SPECTATOR ); StartObserverMode( OBS_MODE_ROAMING ); return true; } else if ( stricmp( cmd, "spec_mode" ) == 0 ) // new observer mode { int mode; // check for parameters. if ( engine->Cmd_Argc() >= 2 ) { mode = atoi( engine->Cmd_Argv(1) ); if ( mode < OBS_MODE_IN_EYE || mode > OBS_MODE_ROAMING ) mode = OBS_MODE_IN_EYE; } else { // sitch to next spec mode if no parameter give mode = GetObserverMode() + 1; if ( mode > OBS_MODE_ROAMING ) { mode = OBS_MODE_IN_EYE; } else if ( mode < OBS_MODE_IN_EYE ) { mode = OBS_MODE_ROAMING; } } // don't allow input while player or death cam animation if ( GetObserverMode() > OBS_MODE_DEATHCAM ) { // set new spectator mode, don't allow OBS_MODE_NONE if ( !SetObserverMode( mode, false ) ) ClientPrint( this, HUD_PRINTCONSOLE, "#Spectator_Mode_Unkown"); } else { // remember spectator mode for later use m_iObserverLastMode = mode; } return true; } else if ( stricmp( cmd, "spec_next" ) == 0 ) // chase next player { if ( GetObserverMode() > OBS_MODE_FIXED ) { // set new spectator mode CBaseEntity * target = FindNextObserverTarget( false ); if ( target ) SetObserverTarget( target ); } return true; } else if ( stricmp( cmd, "spec_prev" ) == 0 ) // chase prevoius player { if ( GetObserverMode() > OBS_MODE_FIXED ) { // set new spectator mode CBaseEntity * target = FindNextObserverTarget( true ); if ( target ) SetObserverTarget( target ); } return true; } else if ( stricmp( cmd, "spec_player" ) == 0 ) // chase next player { if ( GetObserverMode() > OBS_MODE_FIXED && engine->Cmd_Argc() == 2 ) { int index = atoi( engine->Cmd_Argv(1) ); CBasePlayer * target; if ( index == 0 ) { target = UTIL_PlayerByName( engine->Cmd_Argv(1) ); } else { target = UTIL_PlayerByIndex( index ); } if ( IsValidObserverTarget( target ) ) { SetObserverTarget( target ); } } return true; } else if ( stricmp( cmd, "spec_goto" ) == 0 ) // chase next player { if ( ( GetObserverMode() == OBS_MODE_FIXED || GetObserverMode() == OBS_MODE_ROAMING ) && engine->Cmd_Argc() == 6 ) { Vector origin; origin.x = atof( engine->Cmd_Argv(1) ); origin.y = atof( engine->Cmd_Argv(2) ); origin.z = atof( engine->Cmd_Argv(3) ); QAngle angle; angle.x = atof( engine->Cmd_Argv(4) ); angle.y = atof( engine->Cmd_Argv(5) ); angle.z = 0.0f; JumptoPosition( origin, angle ); } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Player reacts to bumping a weapon. // Input : pWeapon - the weapon that the player bumped into. // Output : Returns true if player picked up the weapon //----------------------------------------------------------------------------- bool CBasePlayer::BumpWeapon( CBaseCombatWeapon *pWeapon ) { CBaseCombatCharacter *pOwner = pWeapon->GetOwner(); // Can I have this weapon type? if ( IsEFlagSet( EFL_NO_WEAPON_PICKUP ) ) return false; if ( pOwner || !Weapon_CanUse( pWeapon ) || !g_pGameRules->CanHavePlayerItem( this, pWeapon ) ) { if ( gEvilImpulse101 ) { UTIL_Remove( pWeapon ); } return false; } // Don't let the player fetch weapons through walls (use MASK_SOLID so that you can't pickup through windows) if( !pWeapon->FVisible( this, MASK_SOLID ) && !(GetFlags() & FL_NOTARGET) ) { return false; } // ---------------------------------------- // If I already have it just take the ammo // ---------------------------------------- if (Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType())) { if( Weapon_EquipAmmoOnly( pWeapon ) ) { // Only remove me if I have no ammo left if ( pWeapon->HasPrimaryAmmo() ) return false; UTIL_Remove( pWeapon ); return true; } else { return false; } } // ------------------------- // Otherwise take the weapon // ------------------------- else { pWeapon->CheckRespawn(); pWeapon->AddSolidFlags( FSOLID_NOT_SOLID ); pWeapon->AddEffects( EF_NODRAW ); Weapon_Equip( pWeapon ); if ( IsInAVehicle() ) { pWeapon->Holster(); } else { #ifdef HL2_DLL // Always switch to a newly-picked up weapon if ( !PlayerHasMegaPhysCannon() ) { // If it uses clips, load it full. (this is the first time you've picked up this type of weapon) if ( pWeapon->UsesClipsForAmmo1() ) { pWeapon->m_iClip1 = pWeapon->GetMaxClip1(); } Weapon_Switch( pWeapon ); } #endif } return true; } } bool CBasePlayer::RemovePlayerItem( CBaseCombatWeapon *pItem ) { if (GetActiveWeapon() == pItem) { ResetAutoaim( ); pItem->Holster( ); pItem->SetNextThink( TICK_NEVER_THINK );; // crowbar may be trying to swing again, etc pItem->SetThink( NULL ); } if ( m_hLastWeapon.Get() == pItem ) { Weapon_SetLast( NULL ); } return Weapon_Detach( pItem ); } //----------------------------------------------------------------------------- // Purpose: Hides or shows the player's view model. The "r_drawviewmodel" cvar // can still hide the viewmodel even if this is set to true. // Input : bShow - true to show, false to hide the view model. //----------------------------------------------------------------------------- void CBasePlayer::ShowViewModel(bool bShow) { m_Local.m_bDrawViewmodel = bShow ? 1 : 0; } //----------------------------------------------------------------------------- // Purpose: // Input : bDraw - //----------------------------------------------------------------------------- void CBasePlayer::ShowCrosshair( bool bShow ) { if ( bShow ) { m_Local.m_iHideHUD &= ~HIDEHUD_CROSSHAIR; } else { m_Local.m_iHideHUD |= HIDEHUD_CROSSHAIR; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- QAngle CBasePlayer::BodyAngles() { return EyeAngles(); } //------------------------------------------------------------------------------ // Purpose : Add noise to BodyTarget() to give enemy a better chance of // getting a clear shot when the player is peeking above a hole // or behind a ladder (eventually the randomly-picked point // along the spine will be one that is exposed above the hole or // between rungs of a ladder.) // Input : // Output : //------------------------------------------------------------------------------ Vector CBasePlayer::BodyTarget( const Vector &posSrc, bool bNoisy ) { if ( IsInAVehicle() ) { return GetVehicle()->GetVehicleEnt()->BodyTarget( posSrc, bNoisy ); } if (bNoisy) { return GetAbsOrigin() + (GetViewOffset() * random->RandomFloat( 0.7, 1.0 )); } else { return EyePosition(); } }; /* ========================================================= UpdateClientData resends any changed player HUD info to the client. Called every frame by PlayerPreThink Also called at start of demo recording and playback by ForceClientDllUpdate to ensure the demo gets messages reflecting all of the HUD state info. ========================================================= */ void CBasePlayer::UpdateClientData( void ) { CSingleUserRecipientFilter user( this ); user.MakeReliable(); if (m_fInitHUD) { m_fInitHUD = false; gInitHUD = false; UserMessageBegin( user, "ResetHUD" ); WRITE_BYTE( 0 ); MessageEnd(); if ( !m_fGameHUDInitialized ) { g_pGameRules->InitHUD( this ); InitHUD(); m_fGameHUDInitialized = true; if ( g_pGameRules->IsMultiplayer() ) { variant_t value; g_EventQueue.AddEvent( "game_player_manager", "OnPlayerJoin", value, 0, this, this ); } } variant_t value; g_EventQueue.AddEvent( "game_player_manager", "OnPlayerSpawn", value, 0, this, this ); } // HACKHACK -- send the message to display the game title CWorld *world = GetWorldEntity(); if ( world && world->GetDisplayTitle() ) { UserMessageBegin( user, "GameTitle" ); MessageEnd(); world->SetDisplayTitle( false ); } if (m_ArmorValue != m_iClientBattery) { m_iClientBattery = m_ArmorValue; // send "battery" update message if ( usermessages->LookupUserMessage( "Battery" ) != -1 ) { UserMessageBegin( user, "Battery" ); WRITE_SHORT( (int)m_ArmorValue); MessageEnd(); } } #if 0 // BYE BYE!! // Update Flashlight if ((m_flFlashLightTime) && (m_flFlashLightTime <= gpGlobals->curtime)) { if (FlashlightIsOn()) { if (m_iFlashBattery) { m_flFlashLightTime = FLASH_DRAIN_TIME + gpGlobals->curtime; m_iFlashBattery--; if (!m_iFlashBattery) FlashlightTurnOff(); } } else { if (m_iFlashBattery < 100) { m_flFlashLightTime = FLASH_CHARGE_TIME + gpGlobals->curtime; m_iFlashBattery++; } else m_flFlashLightTime = 0; } } #endif CheckTrainUpdate(); // Update all the items for ( int i = 0; i < WeaponCount(); i++ ) { if ( GetWeapon(i) ) // each item updates it's successors GetWeapon(i)->UpdateClientData( this ); } // update the client with our poison state m_Local.m_bPoisoned = ( m_bitsDamageType & DMG_POISON ) && ( m_nPoisonDmg > m_nPoisonRestored ) && ( m_iHealth < 100 ); // Let any global rules update the HUD, too g_pGameRules->UpdateClientData( this ); } void CBasePlayer::EnableControl(bool fControl) { if (!fControl) AddFlag( FL_FROZEN ); else RemoveFlag( FL_FROZEN ); } void CBasePlayer::CheckTrainUpdate( void ) { if (m_iTrain & TRAIN_NEW) { CSingleUserRecipientFilter user( this ); user.MakeReliable(); // send "Train" update message UserMessageBegin( user, "Train" ); WRITE_BYTE(m_iTrain & 0xF); MessageEnd(); m_iTrain &= ~TRAIN_NEW; } } //----------------------------------------------------------------------------- // Purpose: Returns whether the player should autoaim or not // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBasePlayer::ShouldAutoaim( void ) { // cannot be in multiplayer if ( gpGlobals->maxClients > 1 ) return false; // autoaiming is only for easy and medium skill return !g_pGameRules->IsSkillLevel(SKILL_HARD); } //========================================================= // Autoaim // set crosshair position to point to enemey //========================================================= Vector CBasePlayer::GetAutoaimVector( float flDelta ) { if ( ( ShouldAutoaim() == false ) || ( flDelta == 0 ) ) { Vector forward; AngleVectors( EyeAngles() + m_Local.m_vecPunchAngle, &forward ); return forward; } Vector vecSrc = Weapon_ShootPosition( ); float flDist = MAX_COORD_RANGE; m_vecAutoAim.Init( 0.0f, 0.0f, 0.0f ); QAngle angles = AutoaimDeflection( vecSrc, flDist, flDelta ); // update ontarget if changed if ( !g_pGameRules->AllowAutoTargetCrosshair() ) m_fOnTarget = 0; if (angles.x > 180) angles.x -= 360; if (angles.x < -180) angles.x += 360; if (angles.y > 180) angles.y -= 360; if (angles.y < -180) angles.y += 360; if (angles.x > 25) angles.x = 25; if (angles.x < -25) angles.x = -25; if (angles.y > 12) angles.y = 12; if (angles.y < -12) angles.y = -12; // always use non-sticky autoaim m_vecAutoAim = angles * 0.9f; Vector forward; AngleVectors( EyeAngles() + m_Local.m_vecPunchAngle + m_vecAutoAim, &forward ); return forward; } //----------------------------------------------------------------------------- // Purpose: // Input : &vecSrc - // flDist - // flDelta - // Output : Vector //----------------------------------------------------------------------------- QAngle CBasePlayer::AutoaimDeflection( Vector &vecSrc, float flDist, float flDelta ) { float bestdot; Vector bestdir; CBaseEntity *bestent; trace_t tr; Vector v_forward, v_right, v_up; if ( ShouldAutoaim() == false ) { m_fOnTarget = false; return vec3_angle; } AngleVectors( EyeAngles() + m_Local.m_vecPunchAngle + m_vecAutoAim, &v_forward, &v_right, &v_up ); // try all possible entities bestdir = v_forward; bestdot = flDelta; // +- 10 degrees bestent = NULL; //Reset this data m_fOnTarget = false; m_hAutoAimTarget = NULL; UTIL_TraceLine( vecSrc, vecSrc + bestdir * flDist, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); CBaseEntity *pEntHit = tr.m_pEnt; if ( pEntHit && pEntHit->m_takedamage != DAMAGE_NO) { m_hAutoAimTarget = pEntHit; // don't look through water if (!((GetWaterLevel() != 3 && pEntHit->GetWaterLevel() == 3) || (GetWaterLevel() == 3 && pEntHit->GetWaterLevel() == 0))) { if ( pEntHit->GetFlags() & FL_AIMTARGET ) { m_fOnTarget = true; } //Already on target, don't autoaim return vec3_angle; } } int count = AimTarget_ListCount(); if ( count ) { CBaseEntity **pList = (CBaseEntity **)stackalloc( sizeof(CBaseEntity *) * count ); AimTarget_ListCopy( pList, count ); for ( int i = 0; i < count; i++ ) { Vector center; Vector dir; float dot; CBaseEntity *pEntity = pList[i]; // Don't shoot yourself if ( pEntity == this ) continue; if (!pEntity->IsAlive() || !pEntity->edict() ) continue; if ( !g_pGameRules->ShouldAutoAim( this, pEntity->edict() ) ) continue; // don't look through water if ((GetWaterLevel() != 3 && pEntity->GetWaterLevel() == 3) || (GetWaterLevel() == 3 && pEntity->GetWaterLevel() == 0)) continue; // Only shoot enemies! if ( IRelationType( pEntity ) != D_HT ) { if ( !pEntity->IsPlayer() && !g_pGameRules->IsDeathmatch()) // Msg( "friend\n"); continue; } center = pEntity->BodyTarget( vecSrc ); dir = (center - vecSrc); VectorNormalize( dir ); // make sure it's in front of the player if (DotProduct (dir, v_forward ) < 0) continue; dot = fabs( DotProduct (dir, v_right ) ) + fabs( DotProduct (dir, v_up ) ) * 0.5; // tweak for distance dot *= 1.0 + 0.2 * ((center - vecSrc).Length() / flDist); if (dot > bestdot) continue; // to far to turn UTIL_TraceLine( vecSrc, center, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); if (tr.fraction != 1.0 && tr.m_pEnt != pEntity ) { // Msg( "hit %s, can't see %s\n", STRING( tr.u.ent->classname ), STRING( pEdict->classname ) ); continue; } // can shoot at this one bestdot = dot; bestent = pEntity; bestdir = dir; } if ( bestent ) { QAngle bestang; VectorAngles( bestdir, bestang ); bestang -= EyeAngles() - m_Local.m_vecPunchAngle; m_hAutoAimTarget = bestent; m_fOnTarget = true; return bestang; } } return QAngle( 0, 0, 0 ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::ResetAutoaim( void ) { if (m_vecAutoAim.x != 0 || m_vecAutoAim.y != 0) { m_vecAutoAim = QAngle( 0, 0, 0 ); engine->CrosshairAngle( edict(), 0, 0 ); } m_fOnTarget = false; } // ========================================================================== // > Weapon stuff // ========================================================================== //----------------------------------------------------------------------------- // Purpose: Override base class, player can always use weapon // Input : A weapon // Output : true or false //----------------------------------------------------------------------------- bool CBasePlayer::Weapon_CanUse( CBaseCombatWeapon *pWeapon ) { return true; } //----------------------------------------------------------------------------- // Purpose: Override to clear dropped weapon from the hud //----------------------------------------------------------------------------- void CBasePlayer::Weapon_Drop( CBaseCombatWeapon *pWeapon, const Vector *pvecTarget /* = NULL */, const Vector *pVelocity /* = NULL */ ) { bool bWasActiveWeapon = false; if ( pWeapon == GetActiveWeapon() ) { bWasActiveWeapon = true; } if ( pWeapon ) { if ( bWasActiveWeapon ) { pWeapon->SendWeaponAnim( ACT_VM_IDLE ); } } BaseClass::Weapon_Drop( pWeapon, pvecTarget, pVelocity ); if ( bWasActiveWeapon ) { if (!SwitchToNextBestWeapon( NULL )) { CBaseViewModel *vm = GetViewModel(); if ( vm ) { vm->AddEffects( EF_NODRAW ); } } } } //----------------------------------------------------------------------------- // Purpose: // Input : weaponSlot - //----------------------------------------------------------------------------- void CBasePlayer::Weapon_DropSlot( int weaponSlot ) { CBaseCombatWeapon *pWeapon; // Check for that slot being occupied already for ( int i=0; i < MAX_WEAPONS; i++ ) { pWeapon = GetWeapon( i ); if ( pWeapon != NULL ) { // If the slots match, it's already occupied if ( pWeapon->GetSlot() == weaponSlot ) { Weapon_Drop( pWeapon, NULL, NULL ); } } } } //----------------------------------------------------------------------------- // Purpose: Override to add weapon to the hud //----------------------------------------------------------------------------- void CBasePlayer::Weapon_Equip( CBaseCombatWeapon *pWeapon ) { BaseClass::Weapon_Equip( pWeapon ); // should we switch to this item? if ( g_pGameRules->FShouldSwitchWeapon( this, pWeapon ) ) { Weapon_Switch( pWeapon ); } } //========================================================= // HasNamedPlayerItem Does the player already have this item? //========================================================= CBaseEntity *CBasePlayer::HasNamedPlayerItem( const char *pszItemName ) { for ( int i = 0 ; i < WeaponCount() ; i++ ) { if ( !GetWeapon(i) ) continue; if ( FStrEq( pszItemName, GetWeapon(i)->GetClassname() ) ) { return GetWeapon(i); } } return NULL; } //================================================================================ // TEAM HANDLING //================================================================================ //----------------------------------------------------------------------------- // Purpose: Put the player in the specified team //----------------------------------------------------------------------------- void CBasePlayer::ChangeTeam( int iTeamNum, bool bDisconnecting ) { if ( !GetGlobalTeam( iTeamNum ) ) { Warning( "CBasePlayer::ChangeTeam( %d ) - invalid team index.\n", iTeamNum ); return; } // if this is our current team, just abort if ( iTeamNum == GetTeamNumber() ) { return; } // Immediately tell all clients that he's changing team. This has to be done // first, so that all user messages that follow as a result of the team change // come after this one, allowing the client to be prepared for them. KeyValues * event = new KeyValues( "player_team" ); event->SetInt("userid", GetUserID() ); event->SetInt("team", iTeamNum ); event->SetInt("oldteam", GetTeamNumber() ); event->SetInt("disconnect", bDisconnecting); gameeventmanager->FireEvent( event ); // Remove him from his current team if ( GetTeam() ) { GetTeam()->RemovePlayer( this ); } // Are we being added to a team? if ( iTeamNum ) { GetGlobalTeam( iTeamNum )->AddPlayer( this ); } BaseClass::ChangeTeam( iTeamNum ); } //----------------------------------------------------------------------------- // Purpose: Locks a player to the spot; they can't move, shoot, or be hurt //----------------------------------------------------------------------------- void CBasePlayer::LockPlayerInPlace( void ) { if ( m_iPlayerLocked ) return; AddFlag( FL_GODMODE | FL_FROZEN ); SetMoveType( MOVETYPE_NONE ); m_iPlayerLocked = true; // force a client data update, so that anything that has been done to // this player previously this frame won't get delayed in being sent UpdateClientData(); } //----------------------------------------------------------------------------- // Purpose: Unlocks a previously locked player //----------------------------------------------------------------------------- void CBasePlayer::UnlockPlayer( void ) { if ( !m_iPlayerLocked ) return; RemoveFlag( FL_GODMODE | FL_FROZEN ); SetMoveType( MOVETYPE_WALK ); m_iPlayerLocked = false; } bool CBasePlayer::ClearUseEntity() { if ( m_hUseEntity != NULL ) { // Stop controlling the train/object // TODO: Send HUD Update m_hUseEntity->Use( this, this, USE_OFF, 0 ); m_hUseEntity = NULL; return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::HideViewModels( void ) { for ( int i = 0 ; i < MAX_VIEWMODELS; i++ ) { CBaseViewModel *vm = GetViewModel( i ); if ( !vm ) continue; vm->SetWeaponModel( NULL, NULL ); } } class CStripWeapons : public CPointEntity { DECLARE_CLASS( CStripWeapons, CPointEntity ); public: void InputStripWeapons(inputdata_t &data); void InputStripWeaponsAndSuit(inputdata_t &data); void StripWeapons(inputdata_t &data, bool stripSuit); DECLARE_DATADESC(); }; LINK_ENTITY_TO_CLASS( player_weaponstrip, CStripWeapons ); BEGIN_DATADESC( CStripWeapons ) DEFINE_INPUTFUNC( FIELD_VOID, "Strip", InputStripWeapons ), DEFINE_INPUTFUNC( FIELD_VOID, "StripWeaponsAndSuit", InputStripWeaponsAndSuit ), END_DATADESC() void CStripWeapons::InputStripWeapons(inputdata_t &data) { StripWeapons(data, false); } void CStripWeapons::InputStripWeaponsAndSuit(inputdata_t &data) { StripWeapons(data, true); } void CStripWeapons::StripWeapons(inputdata_t &data, bool stripSuit) { CBasePlayer *pPlayer = NULL; if ( data.pActivator && data.pActivator->IsPlayer() ) { pPlayer = (CBasePlayer *)data.pActivator; } else if ( !g_pGameRules->IsDeathmatch() ) { pPlayer = UTIL_GetLocalPlayer(); } if ( pPlayer ) { pPlayer->RemoveAllItems( stripSuit ); } } class CRevertSaved : public CPointEntity { DECLARE_CLASS( CRevertSaved, CPointEntity ); public: void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void LoadThink( void ); DECLARE_DATADESC(); inline float Duration( void ) { return m_Duration; } inline float HoldTime( void ) { return m_HoldTime; } inline float LoadTime( void ) { return m_loadTime; } inline void SetDuration( float duration ) { m_Duration = duration; } inline void SetHoldTime( float hold ) { m_HoldTime = hold; } inline void SetLoadTime( float time ) { m_loadTime = time; } //Inputs void InputReload(inputdata_t &data); #ifdef HL1_DLL void MessageThink( void ); inline float MessageTime( void ) { return m_messageTime; } inline void SetMessageTime( float time ) { m_messageTime = time; } #endif private: float m_loadTime; float m_Duration; float m_HoldTime; #ifdef HL1_DLL string_t m_iszMessage; float m_messageTime; #endif }; LINK_ENTITY_TO_CLASS( player_loadsaved, CRevertSaved ); BEGIN_DATADESC( CRevertSaved ) #ifdef HL1_DLL DEFINE_KEYFIELD( m_iszMessage, FIELD_STRING, "message" ), DEFINE_KEYFIELD( m_messageTime, FIELD_FLOAT, "messagetime" ), // These are not actual times, but durations, so save as floats DEFINE_FUNCTION( MessageThink ), #endif DEFINE_KEYFIELD( m_loadTime, FIELD_FLOAT, "loadtime" ), DEFINE_KEYFIELD( m_Duration, FIELD_FLOAT, "duration" ), DEFINE_KEYFIELD( m_HoldTime, FIELD_FLOAT, "holdtime" ), DEFINE_INPUTFUNC( FIELD_VOID, "Reload", InputReload ), // Function Pointers DEFINE_FUNCTION( LoadThink ), END_DATADESC() void CRevertSaved::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { UTIL_ScreenFadeAll( m_clrRender, Duration(), HoldTime(), FFADE_OUT ); SetNextThink( gpGlobals->curtime + LoadTime() ); SetThink( &CRevertSaved::LoadThink ); CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer ) { //Adrian: Setting this flag so we can't move or save a game. pPlayer->pl.deadflag = true; pPlayer->AddFlag( FL_NOTARGET ); } } void CRevertSaved::InputReload( inputdata_t &inputdata ) { UTIL_ScreenFadeAll( m_clrRender, Duration(), HoldTime(), FFADE_OUT ); #ifdef HL1_DLL SetNextThink( gpGlobals->curtime + MessageTime() ); SetThink( &CRevertSaved::MessageThink ); #else SetNextThink( gpGlobals->curtime + LoadTime() ); SetThink( &CRevertSaved::LoadThink ); #endif CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer ) { //Adrian: Setting this flag so we can't move or save a game. pPlayer->pl.deadflag = true; pPlayer->AddFlag( FL_NOTARGET ); } } #ifdef HL1_DLL void CRevertSaved::MessageThink( void ) { UTIL_ShowMessageAll( STRING( m_iszMessage ) ); float nextThink = LoadTime() - MessageTime(); if ( nextThink > 0 ) { SetNextThink( gpGlobals->curtime + nextThink ); SetThink( &CRevertSaved::LoadThink ); } else LoadThink(); } #endif void CRevertSaved::LoadThink( void ) { if ( !gpGlobals->deathmatch ) { engine->ServerCommand("reload\n"); } } class CMovementSpeedMod : public CPointEntity { DECLARE_CLASS( CMovementSpeedMod, CPointEntity ); public: void InputSpeedMod(inputdata_t &data); DECLARE_DATADESC(); }; LINK_ENTITY_TO_CLASS( player_speedmod, CMovementSpeedMod ); BEGIN_DATADESC( CMovementSpeedMod ) DEFINE_INPUTFUNC( FIELD_FLOAT, "ModifySpeed", InputSpeedMod ), END_DATADESC() void CMovementSpeedMod::InputSpeedMod(inputdata_t &data) { CBasePlayer *pPlayer = NULL; if ( data.pActivator && data.pActivator->IsPlayer() ) { pPlayer = (CBasePlayer *)data.pActivator; } else if ( !g_pGameRules->IsDeathmatch() ) { pPlayer = UTIL_GetLocalPlayer(); } if ( pPlayer ) { pPlayer->SetLaggedMovementValue( data.value.Float() ); } } void SendProxy_CropFlagsToPlayerFlagBitsLength( const SendProp *pProp, const void *pStruct, const void *pVarData, DVariant *pOut, int iElement, int objectID) { int mask = (1<<PLAYER_FLAG_BITS) - 1; int data = *(int *)pVarData; pOut->m_Int = ( data & mask ); } // -------------------------------------------------------------------------------- // // SendTable for CPlayerState. // -------------------------------------------------------------------------------- // BEGIN_SEND_TABLE_NOBASE(CPlayerState, DT_PlayerState) SendPropInt (SENDINFO(deadflag), 1, SPROP_UNSIGNED ), END_SEND_TABLE() // -------------------------------------------------------------------------------- // // This data only gets sent to clients that ARE this player entity. // -------------------------------------------------------------------------------- // BEGIN_SEND_TABLE_NOBASE( CBasePlayer, DT_LocalPlayerExclusive ) SendPropDataTable ( SENDINFO_DT(m_Local), &REFERENCE_SEND_TABLE(DT_Local) ), SendPropFloat ( SENDINFO_VECTORELEM(m_vecViewOffset, 0), 8, 0, -32.0, 32.0f), SendPropFloat ( SENDINFO_VECTORELEM(m_vecViewOffset, 1), 8, 0, -32.0, 32.0f), SendPropFloat ( SENDINFO_VECTORELEM(m_vecViewOffset, 2), 10, SPROP_CHANGES_OFTEN, 0.0f, 128.0f), SendPropFloat ( SENDINFO(m_flFriction), 8, SPROP_ROUNDDOWN, 0.0f, 4.0f), SendPropArray3 ( SENDINFO_ARRAY3(m_iAmmo), SendPropInt( SENDINFO_ARRAY(m_iAmmo), 10, SPROP_UNSIGNED ) ), SendPropInt ( SENDINFO( m_fOnTarget ), 2, SPROP_UNSIGNED ), SendPropInt ( SENDINFO( m_nTickBase ), -1, SPROP_CHANGES_OFTEN ), SendPropInt ( SENDINFO( m_nNextThinkTick ) ), SendPropEHandle ( SENDINFO( m_hLastWeapon ) ), SendPropEHandle ( SENDINFO( m_hGroundEntity ), SPROP_CHANGES_OFTEN ), SendPropFloat ( SENDINFO_VECTORELEM(m_vecVelocity, 0), 20, SPROP_CHANGES_OFTEN, -2048.0f, 2048.0f ), SendPropFloat ( SENDINFO_VECTORELEM(m_vecVelocity, 1), 20, SPROP_CHANGES_OFTEN, -2048.0f, 2048.0f ), SendPropFloat ( SENDINFO_VECTORELEM(m_vecVelocity, 2), 16, SPROP_CHANGES_OFTEN, -2048.0f, 2048.0f ), SendPropVector ( SENDINFO( m_vecBaseVelocity ), 20, 0, -1000, 1000 ), SendPropArray ( SendPropEHandle( SENDINFO_ARRAY( m_hViewModel ) ), m_hViewModel ), SendPropArray ( SendPropEHandle( SENDINFO_ARRAY( m_hObserverViewModel ) ), m_hObserverViewModel ), SendPropEHandle ( SENDINFO( m_hConstraintEntity)), SendPropVector ( SENDINFO( m_vecConstraintCenter), 0, SPROP_NOSCALE ), SendPropFloat ( SENDINFO( m_flConstraintRadius ), 0, SPROP_NOSCALE ), SendPropFloat ( SENDINFO( m_flConstraintWidth ), 0, SPROP_NOSCALE ), SendPropFloat ( SENDINFO( m_flConstraintSpeedFactor ), 0, SPROP_NOSCALE ), SendPropFloat ( SENDINFO( m_flDeathTime ), 0, SPROP_NOSCALE ), SendPropInt ( SENDINFO( m_iObserverMode ), 3, SPROP_UNSIGNED ), SendPropEHandle ( SENDINFO( m_hObserverTarget ) ), SendPropInt ( SENDINFO( m_nWaterLevel ), 2, SPROP_UNSIGNED ), SendPropFloat ( SENDINFO( m_flLaggedMovementValue ), 0, SPROP_NOSCALE ), END_SEND_TABLE() // -------------------------------------------------------------------------------- // // DT_BasePlayer sendtable. // -------------------------------------------------------------------------------- // IMPLEMENT_SERVERCLASS_ST( CBasePlayer, DT_BasePlayer ) SendPropDataTable(SENDINFO_DT(pl), &REFERENCE_SEND_TABLE(DT_PlayerState), SendProxy_DataTableToDataTable), SendPropEHandle(SENDINFO(m_hVehicle)), SendPropInt (SENDINFO(m_MoveType),MOVETYPE_MAX_BITS, SPROP_UNSIGNED ), SendPropInt (SENDINFO(m_iHealth), 10 ), SendPropInt (SENDINFO(m_lifeState), 3, SPROP_UNSIGNED ), SendPropFloat (SENDINFO(m_flMaxspeed), 12, SPROP_ROUNDDOWN, 0.0f, 2048.0f ), // CL SendPropInt (SENDINFO(m_fFlags), PLAYER_FLAG_BITS, SPROP_UNSIGNED|SPROP_CHANGES_OFTEN, SendProxy_CropFlagsToPlayerFlagBitsLength ), // Data that only gets sent to the local player. SendPropDataTable( "localdata", 0, &REFERENCE_SEND_TABLE(DT_LocalPlayerExclusive), SendProxy_SendLocalDataTable ), END_SEND_TABLE() //============================================================================= // // Player Physics Shadow Code // void CBasePlayer::SetupVPhysicsShadow( CPhysCollide *pStandModel, const char *pStandHullName, CPhysCollide *pCrouchModel, const char *pCrouchHullName ) { solid_t solid; Q_strncpy( solid.surfaceprop, "player", sizeof(solid.surfaceprop) ); solid.params = g_PhysDefaultObjectParams; solid.params.mass = 85.0f; solid.params.inertia = 1e24f; solid.params.enableCollisions = false; //disable drag solid.params.dragCoefficient = 0; // create standing hull m_pShadowStand = PhysModelCreateCustom( this, pStandModel, GetLocalOrigin(), GetLocalAngles(), pStandHullName, false, &solid ); m_pShadowStand->SetCallbackFlags( CALLBACK_GLOBAL_COLLISION | CALLBACK_SHADOW_COLLISION ); // create crouchig hull m_pShadowCrouch = PhysModelCreateCustom( this, pCrouchModel, GetLocalOrigin(), GetLocalAngles(), pCrouchHullName, false, &solid ); m_pShadowCrouch->SetCallbackFlags( CALLBACK_GLOBAL_COLLISION | CALLBACK_SHADOW_COLLISION ); // default to stand VPhysicsSetObject( m_pShadowStand ); // tell physics lists I'm a shadow controller object PhysAddShadow( this ); m_pPhysicsController = physenv->CreatePlayerController( m_pShadowStand ); m_pPhysicsController->SetPushMassLimit( 350.0f ); m_pPhysicsController->SetPushSpeedLimit( 50.0f ); // Give the controller a valid position so it doesn't do anything rash. UpdatePhysicsShadowToCurrentPosition(); // init state if ( GetFlags() & FL_DUCKING ) { SetVCollisionState( VPHYS_CROUCH ); } else { SetVCollisionState( VPHYS_WALK ); } } //----------------------------------------------------------------------------- // Purpose: Empty, just want to keep the baseentity version from being called // current so we don't kick up dust, etc. //----------------------------------------------------------------------------- void CBasePlayer::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::VPhysicsUpdate( IPhysicsObject *pPhysics ) { float savedImpact = m_impactEnergyScale; // HACKHACK: Reduce player's stress by 1/8th m_impactEnergyScale *= 0.125f; ApplyStressDamage( pPhysics ); m_impactEnergyScale = savedImpact; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::VPhysicsShadowUpdate( IPhysicsObject *pPhysics ) { Vector newPosition; bool physicsUpdated = m_pPhysicsController->GetShadowPosition( &newPosition, NULL ) > 0 ? true : false; // UNDONE: If the player is penetrating, but the player's game collisions are not stuck, teleport the physics shadow to the game position if ( pPhysics->GetGameFlags() & FVPHYSICS_PENETRATING ) { CUtlVector<CBaseEntity *> list; PhysGetListOfPenetratingEntities( this, list ); for ( int i = list.Count()-1; i >= 0; --i ) { // filter out anything that isn't simulated by vphysics // UNDONE: Filter out motion disabled objects? if ( list[i]->GetMoveType() == MOVETYPE_VPHYSICS ) { // I'm currently stuck inside a moving object, so allow vphysics to // apply velocity to the player in order to separate these objects m_touchedPhysObject = true; } } } if ( m_pPhysicsController->IsInContact() || (m_afPhysicsFlags & PFLAG_VPHYSICS_MOTIONCONTROLLER) ) { m_touchedPhysObject = true; } if ( IsFollowingPhysics() ) { m_touchedPhysObject = true; } if ( GetMoveType() == MOVETYPE_NOCLIP ) { m_oldOrigin = GetAbsOrigin(); return; } if ( phys_timescale.GetFloat() == 0.0f ) { physicsUpdated = false; } if ( !physicsUpdated ) return; IPhysicsObject *pPhysGround = GetGroundVPhysics(); Vector newVelocity; pPhysics->GetPosition( &newPosition, 0 ); m_pPhysicsController->GetShadowVelocity( &newVelocity ); if ( physicsshadowupdate_render.GetBool() ) { NDebugOverlay::Box( GetAbsOrigin(), WorldAlignMins(), WorldAlignMaxs(), 255, 0, 0, 24, 15.0f ); NDebugOverlay::Box( newPosition, WorldAlignMins(), WorldAlignMaxs(), 0,0,255, 24, 15.0f); // NDebugOverlay::Box( newPosition, WorldAlignMins(), WorldAlignMaxs(), 0,0,255, 24, .01f); } Vector tmp = GetAbsOrigin() - newPosition; if ( !m_touchedPhysObject && !(GetFlags() & FL_ONGROUND) ) { tmp.z *= 0.5f; // don't care about z delta as much } float dist = tmp.LengthSqr(); float deltaV = (newVelocity - GetAbsVelocity()).LengthSqr(); float maxDistErrorSqr = VPHYS_MAX_DISTSQR; float maxVelErrorSqr = VPHYS_MAX_VELSQR; if ( IsRideablePhysics(pPhysGround) ) { maxDistErrorSqr *= 0.25; maxVelErrorSqr *= 0.25; } if ( dist >= maxDistErrorSqr || deltaV >= maxVelErrorSqr || (pPhysGround && !m_touchedPhysObject) ) { if ( m_touchedPhysObject || pPhysGround ) { // BUGBUG: Rewrite this code using fixed timestep if ( deltaV >= maxVelErrorSqr ) { Vector dir = GetAbsVelocity(); float len = VectorNormalize(dir); float dot = DotProduct( newVelocity, dir ); if ( dot > len ) { dot = len; } else if ( dot < -len ) { dot = -len; } VectorMA( newVelocity, -dot, dir, newVelocity ); if ( m_afPhysicsFlags & PFLAG_VPHYSICS_MOTIONCONTROLLER ) { float val = Lerp( 0.1f, len, dot ); VectorMA( newVelocity, val - len, dir, newVelocity ); } if ( !IsRideablePhysics(pPhysGround) ) { if ( !(m_afPhysicsFlags & PFLAG_VPHYSICS_MOTIONCONTROLLER ) && IsSimulatingOnAlternateTicks() ) { newVelocity *= 0.5f; } ApplyAbsVelocityImpulse( newVelocity ); } } trace_t trace; UTIL_TraceEntity( this, newPosition, newPosition, MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER_MOVEMENT, &trace ); if ( !trace.allsolid && !trace.startsolid ) { SetAbsOrigin( newPosition ); } } else { trace_t trace; UTIL_TraceEntity( this, GetAbsOrigin(), GetAbsOrigin(), MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER_MOVEMENT, &trace ); // current position is not ok, fixup if ( trace.allsolid || trace.startsolid ) { // STUCK!?!?! //Warning( "Stuck2 on %s!!\n", trace.m_pEnt->GetClassname() ); SetAbsOrigin( newPosition ); } } } else { if ( m_touchedPhysObject ) { // check my position (physics object could have simulated into my position // physics is not very far away, check my position trace_t trace; UTIL_TraceEntity( this, GetAbsOrigin(), GetAbsOrigin(), MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER_MOVEMENT, &trace ); // is current position ok? if ( trace.allsolid || trace.startsolid ) { // stuck????!?!? //Msg("Stuck on %s\n", trace.m_pEnt->GetClassName()); SetAbsOrigin( newPosition ); UTIL_TraceEntity( this, GetAbsOrigin(), GetAbsOrigin(), MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER_MOVEMENT, &trace ); if ( trace.allsolid || trace.startsolid ) { //Msg("Double Stuck\n"); SetAbsOrigin( m_oldOrigin ); } } } } m_oldOrigin = GetAbsOrigin(); // UNDONE: Force physics object to be at player position when not touching phys??? } // recreate physics on save/load, don't try to save the state! bool CBasePlayer::ShouldSavePhysics() { return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::InitVCollision( void ) { // Cleanup any old vphysics stuff. VPhysicsDestroyObject(); CPhysCollide *pModel = PhysCreateBbox( WorldAlignMins(), WorldAlignMaxs() ); CPhysCollide *pCrouchModel = PhysCreateBbox( VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX ); SetupVPhysicsShadow( pModel, "player_stand", pCrouchModel, "player_crouch" ); } void CBasePlayer::VPhysicsDestroyObject() { // Since CBasePlayer aliases its pointer to the physics object, tell CBaseEntity to // clear out its physics object pointer so we don't wind up deleting one of // the aliased objects twice. VPhysicsSetObject( NULL ); PhysRemoveShadow( this ); if ( m_pPhysicsController ) { physenv->DestroyPlayerController( m_pPhysicsController ); m_pPhysicsController = NULL; } if ( m_pShadowStand ) { PhysDestroyObject( m_pShadowStand ); m_pShadowStand = NULL; } if ( m_pShadowCrouch ) { PhysDestroyObject( m_pShadowCrouch ); m_pShadowCrouch = NULL; } BaseClass::VPhysicsDestroyObject(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::SetVCollisionState( int collisionState ) { Vector vel = vec3_origin; Vector pos = vec3_origin; vel = GetAbsVelocity(); pos = GetAbsOrigin(); m_vphysicsCollisionState = collisionState; switch( collisionState ) { case VPHYS_WALK: m_pShadowStand->SetPosition( pos, vec3_angle, true ); m_pShadowStand->SetVelocity( &vel, NULL ); m_pShadowCrouch->EnableCollisions( false ); m_pShadowStand->EnableCollisions( true ); m_pPhysicsController->SetObject( m_pShadowStand ); VPhysicsSwapObject( m_pShadowStand ); break; case VPHYS_CROUCH: m_pShadowCrouch->SetPosition( pos, vec3_angle, true ); m_pShadowCrouch->SetVelocity( &vel, NULL ); m_pShadowStand->EnableCollisions( false ); m_pShadowCrouch->EnableCollisions( true ); m_pPhysicsController->SetObject( m_pShadowCrouch ); VPhysicsSwapObject( m_pShadowCrouch ); break; case VPHYS_NOCLIP: m_pShadowCrouch->EnableCollisions( false ); m_pShadowStand->EnableCollisions( false ); break; } } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CBasePlayer::GetFOV( void ) const { int iFOV = ( m_Local.m_iFOV == 0 ) ? GetDefaultFOV() : m_Local.m_iFOV; return iFOV; } //----------------------------------------------------------------------------- // Purpose: // Input : FOV - // zoomRate - //----------------------------------------------------------------------------- bool CBasePlayer::SetFOV( CBaseEntity *pRequester, int FOV, float zoomRate ) { //NOTENOTE: You MUST specify who is requesting the zoom change assert( pRequester != NULL ); if ( pRequester == NULL ) return false; // If we already have an owner, we only allow requests from that owner if ( ( m_hZoomOwner != NULL ) && ( m_hZoomOwner != pRequester ) ) { if ( CanOverrideEnvZoomOwner( m_hZoomOwner ) == false ) return false; } else { //FIXME: Maybe do this is as an accessor instead if ( FOV == 0 ) { m_hZoomOwner = NULL; } else { m_hZoomOwner = pRequester; } } m_Local.m_iFOV = FOV; m_Local.m_flFOVRate = zoomRate; return true; } //----------------------------------------------------------------------------- // Purpose: Sets the default FOV for the player if nothing else is going on // Input : FOV - the new base FOV for this player //----------------------------------------------------------------------------- void CBasePlayer::SetDefaultFOV( int FOV ) { m_Local.m_iDefaultFOV = ( FOV == 0 ) ? g_pGameRules->DefaultFOV() : FOV; } //----------------------------------------------------------------------------- // Purpose: // static func // Input : set - //----------------------------------------------------------------------------- void CBasePlayer::ModifyOrAppendPlayerCriteria( AI_CriteriaSet& set ) { // Append our health set.AppendCriteria( "playerhealth", UTIL_VarArgs( "%i", GetHealth() ) ); float healthfrac = 0.0f; if ( GetMaxHealth() > 0 ) { healthfrac = (float)GetHealth() / (float)GetMaxHealth(); } set.AppendCriteria( "playerhealthfrac", UTIL_VarArgs( "%.3f", healthfrac ) ); CBaseCombatWeapon *weapon = GetActiveWeapon(); if ( weapon ) { set.AppendCriteria( "playerweapon", weapon->GetClassname() ); } else { set.AppendCriteria( "playerweapon", "none" ); } // Append current activity name set.AppendCriteria( "playeractivity", CAI_BaseNPC::GetActivityName( GetActivity() ) ); set.AppendCriteria( "playerspeed", UTIL_VarArgs( "%.3f", GetAbsVelocity().Length() ) ); AppendContextToCriteria( set, "player" ); } const QAngle& CBasePlayer::GetPunchAngle() { return m_Local.m_vecPunchAngle.Get(); } void CBasePlayer::SetPunchAngle( const QAngle &punchAngle ) { m_Local.m_vecPunchAngle = punchAngle; if ( IsAlive() ) { int index = entindex(); for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBasePlayer *pPlayer = UTIL_PlayerByIndex( i ); if ( pPlayer && i != index && pPlayer->GetObserverTarget() == this && pPlayer->GetObserverMode() == OBS_MODE_IN_EYE ) { pPlayer->SetPunchAngle( punchAngle ); } } } } //----------------------------------------------------------------------------- // Purpose: Apply a movement constraint to the player //----------------------------------------------------------------------------- void CBasePlayer::ActivateMovementConstraint( CBaseEntity *pEntity, const Vector &vecCenter, float flRadius, float flConstraintWidth, float flSpeedFactor ) { m_hConstraintEntity = pEntity; m_vecConstraintCenter = vecCenter; m_flConstraintRadius = flRadius; m_flConstraintWidth = flConstraintWidth; m_flConstraintSpeedFactor = flSpeedFactor; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::DeactivateMovementConstraint( ) { m_hConstraintEntity = NULL; m_flConstraintRadius = 0.0f; m_vecConstraintCenter = vec3_origin; } //----------------------------------------------------------------------------- // Perhaps a poorly-named function. This function traces against the supplied // NPC's hitboxes (instead of hull). If the trace hits a different NPC, the // new NPC is selected. Otherwise, the supplied NPC is determined to be the // one the citizen wants. This function allows the selection of a citizen over // another citizen's shoulder, which is impossible without tracing against // hitboxes instead of the hull (sjb) //----------------------------------------------------------------------------- CBaseEntity *CBasePlayer::DoubleCheckUseNPC( CBaseEntity *pNPC, const Vector &vecSrc, const Vector &vecDir ) { trace_t tr; UTIL_TraceLine( vecSrc, vecSrc + vecDir * 1024, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); if( tr.m_pEnt != NULL && tr.m_pEnt->MyNPCPointer() && tr.m_pEnt != pNPC ) { // Player is selecting a different NPC through some negative space // in the first NPC's hitboxes (between legs, over shoulder, etc). return tr.m_pEnt; } return pNPC; } bool CBasePlayer::IsBot() { return (GetFlags() & FL_FAKECLIENT) != 0; } void CBasePlayer::EquipSuit( void ) { m_Local.m_bWearingSuit = true; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CBasePlayer::GetTracerType( void ) { if ( GetActiveWeapon() ) { return GetActiveWeapon()->GetTracerType(); } return BaseClass::GetTracerType(); } //----------------------------------------------------------------------------- // Purpose: // Input : &tr - // nDamageType - //----------------------------------------------------------------------------- void CBasePlayer::DoImpactEffect( trace_t &tr, int nDamageType ) { if ( GetActiveWeapon() ) { GetActiveWeapon()->DoImpactEffect( tr, nDamageType ); return; } BaseClass::DoImpactEffect( tr, nDamageType ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBasePlayer::InputSetHealth( inputdata_t &inputdata ) { int iNewHealth = inputdata.value.Int(); int iDelta = abs(GetHealth() - iNewHealth); if ( iNewHealth > GetHealth() ) { TakeHealth( iDelta, DMG_GENERIC ); } else if ( iNewHealth < GetHealth() ) { // Strip off and restore armor so that it doesn't absorb any of this damage. int armor = m_ArmorValue; m_ArmorValue = 0; TakeDamage( CTakeDamageInfo( this, this, iDelta, DMG_GENERIC ) ); m_ArmorValue = armor; } } //----------------------------------------------------------------------------- // Purpose: // Input : *pEntity - //----------------------------------------------------------------------------- void CBasePlayer::SetViewEntity( CBaseEntity *pEntity ) { m_hViewEntity = pEntity; if ( m_hViewEntity ) { engine->SetView( edict(), m_hViewEntity->edict() ); } else { engine->SetView( edict(), edict() ); } } //----------------------------------------------------------------------------- // Purpose: Looks at the player's reserve ammo and also all his weapons for any ammo // of the specified type // Input : nAmmoIndex - ammo to look for // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBasePlayer::HasAnyAmmoOfType( int nAmmoIndex ) { // Must be a valid index if ( nAmmoIndex < 0 ) return false; // If we have some in reserve, we're already done if ( GetAmmoCount( nAmmoIndex ) ) return true; CBaseCombatWeapon *pWeapon; // Check all held weapons for ( int i=0; i < MAX_WEAPONS; i++ ) { pWeapon = GetWeapon( i ); if ( !pWeapon ) continue; // We must use clips and use this sort of ammo if ( pWeapon->UsesClipsForAmmo1() && pWeapon->GetPrimaryAmmoType() == nAmmoIndex ) { // If we have any ammo, we're done if ( pWeapon->HasPrimaryAmmo() ) return true; } // We'll check both clips for the same ammo type, just in case if ( pWeapon->UsesClipsForAmmo2() && pWeapon->GetSecondaryAmmoType() == nAmmoIndex ) { if ( pWeapon->HasSecondaryAmmo() ) return true; } } // We're completely without this type of ammo return false; } //----------------------------------------------------------------------------- // return a string version of the players network (i.e steam) ID. // //----------------------------------------------------------------------------- const char *CBasePlayer::GetNetworkIDString() { Q_strncpy( m_szNetworkIDString, engine->GetPlayerNetworkIDString( edict() ), sizeof(m_szNetworkIDString) ); return m_szNetworkIDString; } //----------------------------------------------------------------------------- // CPlayerInfo functions (simple passthroughts to get around the CBasePlayer multiple inheritence limitation) //----------------------------------------------------------------------------- const char *CPlayerInfo::GetName() { Assert( m_pParent ); return m_pParent->GetPlayerName(); } int CPlayerInfo::GetUserID() { Assert( m_pParent ); return engine->GetPlayerUserId( m_pParent->edict() ); } const char *CPlayerInfo::GetNetworkIDString() { Assert( m_pParent ); return m_pParent->GetNetworkIDString(); } int CPlayerInfo::GetTeamIndex() { Assert( m_pParent ); return m_pParent->GetTeamNumber(); } void CPlayerInfo::ChangeTeam( int iTeamNum ) { Assert( m_pParent ); m_pParent->ChangeTeam(iTeamNum); } int CPlayerInfo::GetFragCount() { Assert( m_pParent ); return m_pParent->FragCount(); } int CPlayerInfo::GetDeathCount() { Assert( m_pParent ); return m_pParent->DeathCount(); } bool CPlayerInfo::IsConnected() { Assert( m_pParent ); return m_pParent->IsConnected(); } int CPlayerInfo::GetArmorValue() { Assert( m_pParent ); return m_pParent->ArmorValue(); }
412
0.996142
1
0.996142
game-dev
MEDIA
0.966826
game-dev
0.803881
1
0.803881
rdk/p2rank
1,841
src/main/groovy/cz/siret/prank/features/implementation/ProteinMassFeature.groovy
package cz.siret.prank.features.implementation import cz.siret.prank.domain.Protein import cz.siret.prank.features.api.ProcessedItemContext import cz.siret.prank.features.api.SasFeatureCalculationContext import cz.siret.prank.features.api.SasFeatureCalculator import cz.siret.prank.program.params.Parametrized import groovy.transform.CompileStatic import org.biojava.nbio.structure.Atom import static cz.siret.prank.geom.Struct.dist /** * simple geometric feature based on distances of the point to the centers of the mass of prot. atoms, sas points ... */ @CompileStatic class ProteinMassFeature extends SasFeatureCalculator implements Parametrized { static final String NAME = 'pmass' @Override String getName() { NAME } @Override List<String> getHeader() { // ['protp', 'protn', 'protc', 'sasp'] ['protp'] } @Override void preProcessProtein(Protein protein, ProcessedItemContext context) { protein.proteinAtoms.withKdTreeConditional() // protein.accessibleSurface.points.buildKdTree() } @Override double[] calculateForSasPoint(Atom point, SasFeatureCalculationContext ctx) { Atom center1 = ctx.protein.proteinAtoms.cutoutSphere(point, params.feat_pmass_radius).centroid ?: point // Atom center2 = ctx.neighbourhoodAtoms.centerOfMass ?: point double protp = dist(point, center1) // double protn = dist(point, center2) // double protc = dist(point, ctx.protein.proteinAtoms.kdTree.findNearestNAtoms(point, params.feat_pmass_natoms, false).centerOfMass) // double sasp = dist(point, ctx.protein.accessibleSurface.points.kdTree.findNearestNDifferentAtoms(point, params.feat_pmass_nsasp, false).centerOfMass) // return [protp, protn, protc, sasp] as double[] return [protp] as double[] } }
412
0.8523
1
0.8523
game-dev
MEDIA
0.202292
game-dev
0.795594
1
0.795594
sebbas/blender-mantaflow
32,983
extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2007 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. */ ///btDbvt implementation by Nathanael Presson #ifndef BT_DYNAMIC_BOUNDING_VOLUME_TREE_H #define BT_DYNAMIC_BOUNDING_VOLUME_TREE_H #include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btVector3.h" #include "LinearMath/btTransform.h" #include "LinearMath/btAabbUtil2.h" // // Compile time configuration // // Implementation profiles #define DBVT_IMPL_GENERIC 0 // Generic implementation #define DBVT_IMPL_SSE 1 // SSE // Template implementation of ICollide #ifdef _WIN32 #if (defined (_MSC_VER) && _MSC_VER >= 1400) #define DBVT_USE_TEMPLATE 1 #else #define DBVT_USE_TEMPLATE 0 #endif #else #define DBVT_USE_TEMPLATE 0 #endif // Use only intrinsics instead of inline asm #define DBVT_USE_INTRINSIC_SSE 1 // Using memmov for collideOCL #define DBVT_USE_MEMMOVE 1 // Enable benchmarking code #define DBVT_ENABLE_BENCHMARK 0 // Inlining #define DBVT_INLINE SIMD_FORCE_INLINE // Specific methods implementation //SSE gives errors on a MSVC 7.1 #if defined (BT_USE_SSE) //&& defined (_WIN32) #define DBVT_SELECT_IMPL DBVT_IMPL_SSE #define DBVT_MERGE_IMPL DBVT_IMPL_SSE #define DBVT_INT0_IMPL DBVT_IMPL_SSE #else #define DBVT_SELECT_IMPL DBVT_IMPL_GENERIC #define DBVT_MERGE_IMPL DBVT_IMPL_GENERIC #define DBVT_INT0_IMPL DBVT_IMPL_GENERIC #endif #if (DBVT_SELECT_IMPL==DBVT_IMPL_SSE)|| \ (DBVT_MERGE_IMPL==DBVT_IMPL_SSE)|| \ (DBVT_INT0_IMPL==DBVT_IMPL_SSE) #include <emmintrin.h> #endif // // Auto config and checks // #if DBVT_USE_TEMPLATE #define DBVT_VIRTUAL #define DBVT_VIRTUAL_DTOR(a) #define DBVT_PREFIX template <typename T> #define DBVT_IPOLICY T& policy #define DBVT_CHECKTYPE static const ICollide& typechecker=*(T*)1;(void)typechecker; #else #define DBVT_VIRTUAL_DTOR(a) virtual ~a() {} #define DBVT_VIRTUAL virtual #define DBVT_PREFIX #define DBVT_IPOLICY ICollide& policy #define DBVT_CHECKTYPE #endif #if DBVT_USE_MEMMOVE #if !defined( __CELLOS_LV2__) && !defined(__MWERKS__) #include <memory.h> #endif #include <string.h> #endif #ifndef DBVT_USE_TEMPLATE #error "DBVT_USE_TEMPLATE undefined" #endif #ifndef DBVT_USE_MEMMOVE #error "DBVT_USE_MEMMOVE undefined" #endif #ifndef DBVT_ENABLE_BENCHMARK #error "DBVT_ENABLE_BENCHMARK undefined" #endif #ifndef DBVT_SELECT_IMPL #error "DBVT_SELECT_IMPL undefined" #endif #ifndef DBVT_MERGE_IMPL #error "DBVT_MERGE_IMPL undefined" #endif #ifndef DBVT_INT0_IMPL #error "DBVT_INT0_IMPL undefined" #endif // // Defaults volumes // /* btDbvtAabbMm */ struct btDbvtAabbMm { DBVT_INLINE btVector3 Center() const { return((mi+mx)/2); } DBVT_INLINE btVector3 Lengths() const { return(mx-mi); } DBVT_INLINE btVector3 Extents() const { return((mx-mi)/2); } DBVT_INLINE const btVector3& Mins() const { return(mi); } DBVT_INLINE const btVector3& Maxs() const { return(mx); } static inline btDbvtAabbMm FromCE(const btVector3& c,const btVector3& e); static inline btDbvtAabbMm FromCR(const btVector3& c,btScalar r); static inline btDbvtAabbMm FromMM(const btVector3& mi,const btVector3& mx); static inline btDbvtAabbMm FromPoints(const btVector3* pts,int n); static inline btDbvtAabbMm FromPoints(const btVector3** ppts,int n); DBVT_INLINE void Expand(const btVector3& e); DBVT_INLINE void SignedExpand(const btVector3& e); DBVT_INLINE bool Contain(const btDbvtAabbMm& a) const; DBVT_INLINE int Classify(const btVector3& n,btScalar o,int s) const; DBVT_INLINE btScalar ProjectMinimum(const btVector3& v,unsigned signs) const; DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a, const btDbvtAabbMm& b); DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a, const btVector3& b); DBVT_INLINE friend btScalar Proximity( const btDbvtAabbMm& a, const btDbvtAabbMm& b); DBVT_INLINE friend int Select( const btDbvtAabbMm& o, const btDbvtAabbMm& a, const btDbvtAabbMm& b); DBVT_INLINE friend void Merge( const btDbvtAabbMm& a, const btDbvtAabbMm& b, btDbvtAabbMm& r); DBVT_INLINE friend bool NotEqual( const btDbvtAabbMm& a, const btDbvtAabbMm& b); DBVT_INLINE btVector3& tMins() { return(mi); } DBVT_INLINE btVector3& tMaxs() { return(mx); } private: DBVT_INLINE void AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const; private: btVector3 mi,mx; }; // Types typedef btDbvtAabbMm btDbvtVolume; /* btDbvtNode */ struct btDbvtNode { btDbvtVolume volume; btDbvtNode* parent; DBVT_INLINE bool isleaf() const { return(childs[1]==0); } DBVT_INLINE bool isinternal() const { return(!isleaf()); } union { btDbvtNode* childs[2]; void* data; int dataAsInt; }; }; ///The btDbvt class implements a fast dynamic bounding volume tree based on axis aligned bounding boxes (aabb tree). ///This btDbvt is used for soft body collision detection and for the btDbvtBroadphase. It has a fast insert, remove and update of nodes. ///Unlike the btQuantizedBvh, nodes can be dynamically moved around, which allows for change in topology of the underlying data structure. struct btDbvt { /* Stack element */ struct sStkNN { const btDbvtNode* a; const btDbvtNode* b; sStkNN() {} sStkNN(const btDbvtNode* na,const btDbvtNode* nb) : a(na),b(nb) {} }; struct sStkNP { const btDbvtNode* node; int mask; sStkNP(const btDbvtNode* n,unsigned m) : node(n),mask(m) {} }; struct sStkNPS { const btDbvtNode* node; int mask; btScalar value; sStkNPS() {} sStkNPS(const btDbvtNode* n,unsigned m,btScalar v) : node(n),mask(m),value(v) {} }; struct sStkCLN { const btDbvtNode* node; btDbvtNode* parent; sStkCLN(const btDbvtNode* n,btDbvtNode* p) : node(n),parent(p) {} }; // Policies/Interfaces /* ICollide */ struct ICollide { DBVT_VIRTUAL_DTOR(ICollide) DBVT_VIRTUAL void Process(const btDbvtNode*,const btDbvtNode*) {} DBVT_VIRTUAL void Process(const btDbvtNode*) {} DBVT_VIRTUAL void Process(const btDbvtNode* n,btScalar) { Process(n); } DBVT_VIRTUAL bool Descent(const btDbvtNode*) { return(true); } DBVT_VIRTUAL bool AllLeaves(const btDbvtNode*) { return(true); } }; /* IWriter */ struct IWriter { virtual ~IWriter() {} virtual void Prepare(const btDbvtNode* root,int numnodes)=0; virtual void WriteNode(const btDbvtNode*,int index,int parent,int child0,int child1)=0; virtual void WriteLeaf(const btDbvtNode*,int index,int parent)=0; }; /* IClone */ struct IClone { virtual ~IClone() {} virtual void CloneLeaf(btDbvtNode*) {} }; // Constants enum { SIMPLE_STACKSIZE = 64, DOUBLE_STACKSIZE = SIMPLE_STACKSIZE*2 }; // Fields btDbvtNode* m_root; btDbvtNode* m_free; int m_lkhd; int m_leaves; unsigned m_opath; btAlignedObjectArray<sStkNN> m_stkStack; mutable btAlignedObjectArray<const btDbvtNode*> m_rayTestStack; // Methods btDbvt(); ~btDbvt(); void clear(); bool empty() const { return(0==m_root); } void optimizeBottomUp(); void optimizeTopDown(int bu_treshold=128); void optimizeIncremental(int passes); btDbvtNode* insert(const btDbvtVolume& box,void* data); void update(btDbvtNode* leaf,int lookahead=-1); void update(btDbvtNode* leaf,btDbvtVolume& volume); bool update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity,btScalar margin); bool update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity); bool update(btDbvtNode* leaf,btDbvtVolume& volume,btScalar margin); void remove(btDbvtNode* leaf); void write(IWriter* iwriter) const; void clone(btDbvt& dest,IClone* iclone=0) const; static int maxdepth(const btDbvtNode* node); static int countLeaves(const btDbvtNode* node); static void extractLeaves(const btDbvtNode* node,btAlignedObjectArray<const btDbvtNode*>& leaves); #if DBVT_ENABLE_BENCHMARK static void benchmark(); #else static void benchmark(){} #endif // DBVT_IPOLICY must support ICollide policy/interface DBVT_PREFIX static void enumNodes( const btDbvtNode* root, DBVT_IPOLICY); DBVT_PREFIX static void enumLeaves( const btDbvtNode* root, DBVT_IPOLICY); DBVT_PREFIX void collideTT( const btDbvtNode* root0, const btDbvtNode* root1, DBVT_IPOLICY); DBVT_PREFIX void collideTTpersistentStack( const btDbvtNode* root0, const btDbvtNode* root1, DBVT_IPOLICY); #if 0 DBVT_PREFIX void collideTT( const btDbvtNode* root0, const btDbvtNode* root1, const btTransform& xform, DBVT_IPOLICY); DBVT_PREFIX void collideTT( const btDbvtNode* root0, const btTransform& xform0, const btDbvtNode* root1, const btTransform& xform1, DBVT_IPOLICY); #endif DBVT_PREFIX void collideTV( const btDbvtNode* root, const btDbvtVolume& volume, DBVT_IPOLICY) const; ///rayTest is a re-entrant ray test, and can be called in parallel as long as the btAlignedAlloc is thread-safe (uses locking etc) ///rayTest is slower than rayTestInternal, because it builds a local stack, using memory allocations, and it recomputes signs/rayDirectionInverses each time DBVT_PREFIX static void rayTest( const btDbvtNode* root, const btVector3& rayFrom, const btVector3& rayTo, DBVT_IPOLICY); ///rayTestInternal is faster than rayTest, because it uses a persistent stack (to reduce dynamic memory allocations to a minimum) and it uses precomputed signs/rayInverseDirections ///rayTestInternal is used by btDbvtBroadphase to accelerate world ray casts DBVT_PREFIX void rayTestInternal( const btDbvtNode* root, const btVector3& rayFrom, const btVector3& rayTo, const btVector3& rayDirectionInverse, unsigned int signs[3], btScalar lambda_max, const btVector3& aabbMin, const btVector3& aabbMax, DBVT_IPOLICY) const; DBVT_PREFIX static void collideKDOP(const btDbvtNode* root, const btVector3* normals, const btScalar* offsets, int count, DBVT_IPOLICY); DBVT_PREFIX static void collideOCL( const btDbvtNode* root, const btVector3* normals, const btScalar* offsets, const btVector3& sortaxis, int count, DBVT_IPOLICY, bool fullsort=true); DBVT_PREFIX static void collideTU( const btDbvtNode* root, DBVT_IPOLICY); // Helpers static DBVT_INLINE int nearest(const int* i,const btDbvt::sStkNPS* a,btScalar v,int l,int h) { int m=0; while(l<h) { m=(l+h)>>1; if(a[i[m]].value>=v) l=m+1; else h=m; } return(h); } static DBVT_INLINE int allocate( btAlignedObjectArray<int>& ifree, btAlignedObjectArray<sStkNPS>& stock, const sStkNPS& value) { int i; if(ifree.size()>0) { i=ifree[ifree.size()-1];ifree.pop_back();stock[i]=value; } else { i=stock.size();stock.push_back(value); } return(i); } // private: btDbvt(const btDbvt&) {} }; // // Inline's // // inline btDbvtAabbMm btDbvtAabbMm::FromCE(const btVector3& c,const btVector3& e) { btDbvtAabbMm box; box.mi=c-e;box.mx=c+e; return(box); } // inline btDbvtAabbMm btDbvtAabbMm::FromCR(const btVector3& c,btScalar r) { return(FromCE(c,btVector3(r,r,r))); } // inline btDbvtAabbMm btDbvtAabbMm::FromMM(const btVector3& mi,const btVector3& mx) { btDbvtAabbMm box; box.mi=mi;box.mx=mx; return(box); } // inline btDbvtAabbMm btDbvtAabbMm::FromPoints(const btVector3* pts,int n) { btDbvtAabbMm box; box.mi=box.mx=pts[0]; for(int i=1;i<n;++i) { box.mi.setMin(pts[i]); box.mx.setMax(pts[i]); } return(box); } // inline btDbvtAabbMm btDbvtAabbMm::FromPoints(const btVector3** ppts,int n) { btDbvtAabbMm box; box.mi=box.mx=*ppts[0]; for(int i=1;i<n;++i) { box.mi.setMin(*ppts[i]); box.mx.setMax(*ppts[i]); } return(box); } // DBVT_INLINE void btDbvtAabbMm::Expand(const btVector3& e) { mi-=e;mx+=e; } // DBVT_INLINE void btDbvtAabbMm::SignedExpand(const btVector3& e) { if(e.x()>0) mx.setX(mx.x()+e[0]); else mi.setX(mi.x()+e[0]); if(e.y()>0) mx.setY(mx.y()+e[1]); else mi.setY(mi.y()+e[1]); if(e.z()>0) mx.setZ(mx.z()+e[2]); else mi.setZ(mi.z()+e[2]); } // DBVT_INLINE bool btDbvtAabbMm::Contain(const btDbvtAabbMm& a) const { return( (mi.x()<=a.mi.x())&& (mi.y()<=a.mi.y())&& (mi.z()<=a.mi.z())&& (mx.x()>=a.mx.x())&& (mx.y()>=a.mx.y())&& (mx.z()>=a.mx.z())); } // DBVT_INLINE int btDbvtAabbMm::Classify(const btVector3& n,btScalar o,int s) const { btVector3 pi,px; switch(s) { case (0+0+0): px=btVector3(mi.x(),mi.y(),mi.z()); pi=btVector3(mx.x(),mx.y(),mx.z());break; case (1+0+0): px=btVector3(mx.x(),mi.y(),mi.z()); pi=btVector3(mi.x(),mx.y(),mx.z());break; case (0+2+0): px=btVector3(mi.x(),mx.y(),mi.z()); pi=btVector3(mx.x(),mi.y(),mx.z());break; case (1+2+0): px=btVector3(mx.x(),mx.y(),mi.z()); pi=btVector3(mi.x(),mi.y(),mx.z());break; case (0+0+4): px=btVector3(mi.x(),mi.y(),mx.z()); pi=btVector3(mx.x(),mx.y(),mi.z());break; case (1+0+4): px=btVector3(mx.x(),mi.y(),mx.z()); pi=btVector3(mi.x(),mx.y(),mi.z());break; case (0+2+4): px=btVector3(mi.x(),mx.y(),mx.z()); pi=btVector3(mx.x(),mi.y(),mi.z());break; case (1+2+4): px=btVector3(mx.x(),mx.y(),mx.z()); pi=btVector3(mi.x(),mi.y(),mi.z());break; } if((btDot(n,px)+o)<0) return(-1); if((btDot(n,pi)+o)>=0) return(+1); return(0); } // DBVT_INLINE btScalar btDbvtAabbMm::ProjectMinimum(const btVector3& v,unsigned signs) const { const btVector3* b[]={&mx,&mi}; const btVector3 p( b[(signs>>0)&1]->x(), b[(signs>>1)&1]->y(), b[(signs>>2)&1]->z()); return(btDot(p,v)); } // DBVT_INLINE void btDbvtAabbMm::AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const { for(int i=0;i<3;++i) { if(d[i]<0) { smi+=mx[i]*d[i];smx+=mi[i]*d[i]; } else { smi+=mi[i]*d[i];smx+=mx[i]*d[i]; } } } // DBVT_INLINE bool Intersect( const btDbvtAabbMm& a, const btDbvtAabbMm& b) { #if DBVT_INT0_IMPL == DBVT_IMPL_SSE const __m128 rt(_mm_or_ps( _mm_cmplt_ps(_mm_load_ps(b.mx),_mm_load_ps(a.mi)), _mm_cmplt_ps(_mm_load_ps(a.mx),_mm_load_ps(b.mi)))); #if defined (_WIN32) const __int32* pu((const __int32*)&rt); #else const int* pu((const int*)&rt); #endif return((pu[0]|pu[1]|pu[2])==0); #else return( (a.mi.x()<=b.mx.x())&& (a.mx.x()>=b.mi.x())&& (a.mi.y()<=b.mx.y())&& (a.mx.y()>=b.mi.y())&& (a.mi.z()<=b.mx.z())&& (a.mx.z()>=b.mi.z())); #endif } // DBVT_INLINE bool Intersect( const btDbvtAabbMm& a, const btVector3& b) { return( (b.x()>=a.mi.x())&& (b.y()>=a.mi.y())&& (b.z()>=a.mi.z())&& (b.x()<=a.mx.x())&& (b.y()<=a.mx.y())&& (b.z()<=a.mx.z())); } ////////////////////////////////////// // DBVT_INLINE btScalar Proximity( const btDbvtAabbMm& a, const btDbvtAabbMm& b) { const btVector3 d=(a.mi+a.mx)-(b.mi+b.mx); return(btFabs(d.x())+btFabs(d.y())+btFabs(d.z())); } // DBVT_INLINE int Select( const btDbvtAabbMm& o, const btDbvtAabbMm& a, const btDbvtAabbMm& b) { #if DBVT_SELECT_IMPL == DBVT_IMPL_SSE #if defined (_WIN32) static ATTRIBUTE_ALIGNED16(const unsigned __int32) mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x7fffffff}; #else static ATTRIBUTE_ALIGNED16(const unsigned int) mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x00000000 /*0x7fffffff*/}; #endif ///@todo: the intrinsic version is 11% slower #if DBVT_USE_INTRINSIC_SSE union btSSEUnion ///NOTE: if we use more intrinsics, move btSSEUnion into the LinearMath directory { __m128 ssereg; float floats[4]; int ints[4]; }; __m128 omi(_mm_load_ps(o.mi)); omi=_mm_add_ps(omi,_mm_load_ps(o.mx)); __m128 ami(_mm_load_ps(a.mi)); ami=_mm_add_ps(ami,_mm_load_ps(a.mx)); ami=_mm_sub_ps(ami,omi); ami=_mm_and_ps(ami,_mm_load_ps((const float*)mask)); __m128 bmi(_mm_load_ps(b.mi)); bmi=_mm_add_ps(bmi,_mm_load_ps(b.mx)); bmi=_mm_sub_ps(bmi,omi); bmi=_mm_and_ps(bmi,_mm_load_ps((const float*)mask)); __m128 t0(_mm_movehl_ps(ami,ami)); ami=_mm_add_ps(ami,t0); ami=_mm_add_ss(ami,_mm_shuffle_ps(ami,ami,1)); __m128 t1(_mm_movehl_ps(bmi,bmi)); bmi=_mm_add_ps(bmi,t1); bmi=_mm_add_ss(bmi,_mm_shuffle_ps(bmi,bmi,1)); btSSEUnion tmp; tmp.ssereg = _mm_cmple_ss(bmi,ami); return tmp.ints[0]&1; #else ATTRIBUTE_ALIGNED16(__int32 r[1]); __asm { mov eax,o mov ecx,a mov edx,b movaps xmm0,[eax] movaps xmm5,mask addps xmm0,[eax+16] movaps xmm1,[ecx] movaps xmm2,[edx] addps xmm1,[ecx+16] addps xmm2,[edx+16] subps xmm1,xmm0 subps xmm2,xmm0 andps xmm1,xmm5 andps xmm2,xmm5 movhlps xmm3,xmm1 movhlps xmm4,xmm2 addps xmm1,xmm3 addps xmm2,xmm4 pshufd xmm3,xmm1,1 pshufd xmm4,xmm2,1 addss xmm1,xmm3 addss xmm2,xmm4 cmpless xmm2,xmm1 movss r,xmm2 } return(r[0]&1); #endif #else return(Proximity(o,a)<Proximity(o,b)?0:1); #endif } // DBVT_INLINE void Merge( const btDbvtAabbMm& a, const btDbvtAabbMm& b, btDbvtAabbMm& r) { #if DBVT_MERGE_IMPL==DBVT_IMPL_SSE __m128 ami(_mm_load_ps(a.mi)); __m128 amx(_mm_load_ps(a.mx)); __m128 bmi(_mm_load_ps(b.mi)); __m128 bmx(_mm_load_ps(b.mx)); ami=_mm_min_ps(ami,bmi); amx=_mm_max_ps(amx,bmx); _mm_store_ps(r.mi,ami); _mm_store_ps(r.mx,amx); #else for(int i=0;i<3;++i) { if(a.mi[i]<b.mi[i]) r.mi[i]=a.mi[i]; else r.mi[i]=b.mi[i]; if(a.mx[i]>b.mx[i]) r.mx[i]=a.mx[i]; else r.mx[i]=b.mx[i]; } #endif } // DBVT_INLINE bool NotEqual( const btDbvtAabbMm& a, const btDbvtAabbMm& b) { return( (a.mi.x()!=b.mi.x())|| (a.mi.y()!=b.mi.y())|| (a.mi.z()!=b.mi.z())|| (a.mx.x()!=b.mx.x())|| (a.mx.y()!=b.mx.y())|| (a.mx.z()!=b.mx.z())); } // // Inline's // // DBVT_PREFIX inline void btDbvt::enumNodes( const btDbvtNode* root, DBVT_IPOLICY) { DBVT_CHECKTYPE policy.Process(root); if(root->isinternal()) { enumNodes(root->childs[0],policy); enumNodes(root->childs[1],policy); } } // DBVT_PREFIX inline void btDbvt::enumLeaves( const btDbvtNode* root, DBVT_IPOLICY) { DBVT_CHECKTYPE if(root->isinternal()) { enumLeaves(root->childs[0],policy); enumLeaves(root->childs[1],policy); } else { policy.Process(root); } } // DBVT_PREFIX inline void btDbvt::collideTT( const btDbvtNode* root0, const btDbvtNode* root1, DBVT_IPOLICY) { DBVT_CHECKTYPE if(root0&&root1) { int depth=1; int treshold=DOUBLE_STACKSIZE-4; btAlignedObjectArray<sStkNN> stkStack; stkStack.resize(DOUBLE_STACKSIZE); stkStack[0]=sStkNN(root0,root1); do { sStkNN p=stkStack[--depth]; if(depth>treshold) { stkStack.resize(stkStack.size()*2); treshold=stkStack.size()-4; } if(p.a==p.b) { if(p.a->isinternal()) { stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]); stkStack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]); stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]); } } else if(Intersect(p.a->volume,p.b->volume)) { if(p.a->isinternal()) { if(p.b->isinternal()) { stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]); stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]); stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]); stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]); } else { stkStack[depth++]=sStkNN(p.a->childs[0],p.b); stkStack[depth++]=sStkNN(p.a->childs[1],p.b); } } else { if(p.b->isinternal()) { stkStack[depth++]=sStkNN(p.a,p.b->childs[0]); stkStack[depth++]=sStkNN(p.a,p.b->childs[1]); } else { policy.Process(p.a,p.b); } } } } while(depth); } } DBVT_PREFIX inline void btDbvt::collideTTpersistentStack( const btDbvtNode* root0, const btDbvtNode* root1, DBVT_IPOLICY) { DBVT_CHECKTYPE if(root0&&root1) { int depth=1; int treshold=DOUBLE_STACKSIZE-4; m_stkStack.resize(DOUBLE_STACKSIZE); m_stkStack[0]=sStkNN(root0,root1); do { sStkNN p=m_stkStack[--depth]; if(depth>treshold) { m_stkStack.resize(m_stkStack.size()*2); treshold=m_stkStack.size()-4; } if(p.a==p.b) { if(p.a->isinternal()) { m_stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]); m_stkStack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]); m_stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]); } } else if(Intersect(p.a->volume,p.b->volume)) { if(p.a->isinternal()) { if(p.b->isinternal()) { m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]); m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]); m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]); m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]); } else { m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b); m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b); } } else { if(p.b->isinternal()) { m_stkStack[depth++]=sStkNN(p.a,p.b->childs[0]); m_stkStack[depth++]=sStkNN(p.a,p.b->childs[1]); } else { policy.Process(p.a,p.b); } } } } while(depth); } } #if 0 // DBVT_PREFIX inline void btDbvt::collideTT( const btDbvtNode* root0, const btDbvtNode* root1, const btTransform& xform, DBVT_IPOLICY) { DBVT_CHECKTYPE if(root0&&root1) { int depth=1; int treshold=DOUBLE_STACKSIZE-4; btAlignedObjectArray<sStkNN> stkStack; stkStack.resize(DOUBLE_STACKSIZE); stkStack[0]=sStkNN(root0,root1); do { sStkNN p=stkStack[--depth]; if(Intersect(p.a->volume,p.b->volume,xform)) { if(depth>treshold) { stkStack.resize(stkStack.size()*2); treshold=stkStack.size()-4; } if(p.a->isinternal()) { if(p.b->isinternal()) { stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]); stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]); stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]); stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]); } else { stkStack[depth++]=sStkNN(p.a->childs[0],p.b); stkStack[depth++]=sStkNN(p.a->childs[1],p.b); } } else { if(p.b->isinternal()) { stkStack[depth++]=sStkNN(p.a,p.b->childs[0]); stkStack[depth++]=sStkNN(p.a,p.b->childs[1]); } else { policy.Process(p.a,p.b); } } } } while(depth); } } // DBVT_PREFIX inline void btDbvt::collideTT( const btDbvtNode* root0, const btTransform& xform0, const btDbvtNode* root1, const btTransform& xform1, DBVT_IPOLICY) { const btTransform xform=xform0.inverse()*xform1; collideTT(root0,root1,xform,policy); } #endif // DBVT_PREFIX inline void btDbvt::collideTV( const btDbvtNode* root, const btDbvtVolume& vol, DBVT_IPOLICY) const { DBVT_CHECKTYPE if(root) { ATTRIBUTE_ALIGNED16(btDbvtVolume) volume(vol); btAlignedObjectArray<const btDbvtNode*> stack; stack.resize(0); stack.reserve(SIMPLE_STACKSIZE); stack.push_back(root); do { const btDbvtNode* n=stack[stack.size()-1]; stack.pop_back(); if(Intersect(n->volume,volume)) { if(n->isinternal()) { stack.push_back(n->childs[0]); stack.push_back(n->childs[1]); } else { policy.Process(n); } } } while(stack.size()>0); } } DBVT_PREFIX inline void btDbvt::rayTestInternal( const btDbvtNode* root, const btVector3& rayFrom, const btVector3& rayTo, const btVector3& rayDirectionInverse, unsigned int signs[3], btScalar lambda_max, const btVector3& aabbMin, const btVector3& aabbMax, DBVT_IPOLICY) const { (void) rayTo; DBVT_CHECKTYPE if(root) { btVector3 resultNormal; int depth=1; int treshold=DOUBLE_STACKSIZE-2; btAlignedObjectArray<const btDbvtNode*>& stack = m_rayTestStack; stack.resize(DOUBLE_STACKSIZE); stack[0]=root; btVector3 bounds[2]; do { const btDbvtNode* node=stack[--depth]; bounds[0] = node->volume.Mins()-aabbMax; bounds[1] = node->volume.Maxs()-aabbMin; btScalar tmin=1.f,lambda_min=0.f; unsigned int result1=false; result1 = btRayAabb2(rayFrom,rayDirectionInverse,signs,bounds,tmin,lambda_min,lambda_max); if(result1) { if(node->isinternal()) { if(depth>treshold) { stack.resize(stack.size()*2); treshold=stack.size()-2; } stack[depth++]=node->childs[0]; stack[depth++]=node->childs[1]; } else { policy.Process(node); } } } while(depth); } } // DBVT_PREFIX inline void btDbvt::rayTest( const btDbvtNode* root, const btVector3& rayFrom, const btVector3& rayTo, DBVT_IPOLICY) { DBVT_CHECKTYPE if(root) { btVector3 rayDir = (rayTo-rayFrom); rayDir.normalize (); ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT btVector3 rayDirectionInverse; rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0]; rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1]; rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2]; unsigned int signs[3] = { rayDirectionInverse[0] < 0.0, rayDirectionInverse[1] < 0.0, rayDirectionInverse[2] < 0.0}; btScalar lambda_max = rayDir.dot(rayTo-rayFrom); btVector3 resultNormal; btAlignedObjectArray<const btDbvtNode*> stack; int depth=1; int treshold=DOUBLE_STACKSIZE-2; stack.resize(DOUBLE_STACKSIZE); stack[0]=root; btVector3 bounds[2]; do { const btDbvtNode* node=stack[--depth]; bounds[0] = node->volume.Mins(); bounds[1] = node->volume.Maxs(); btScalar tmin=1.f,lambda_min=0.f; unsigned int result1 = btRayAabb2(rayFrom,rayDirectionInverse,signs,bounds,tmin,lambda_min,lambda_max); #ifdef COMPARE_BTRAY_AABB2 btScalar param=1.f; bool result2 = btRayAabb(rayFrom,rayTo,node->volume.Mins(),node->volume.Maxs(),param,resultNormal); btAssert(result1 == result2); #endif //TEST_BTRAY_AABB2 if(result1) { if(node->isinternal()) { if(depth>treshold) { stack.resize(stack.size()*2); treshold=stack.size()-2; } stack[depth++]=node->childs[0]; stack[depth++]=node->childs[1]; } else { policy.Process(node); } } } while(depth); } } // DBVT_PREFIX inline void btDbvt::collideKDOP(const btDbvtNode* root, const btVector3* normals, const btScalar* offsets, int count, DBVT_IPOLICY) { DBVT_CHECKTYPE if(root) { const int inside=(1<<count)-1; btAlignedObjectArray<sStkNP> stack; int signs[sizeof(unsigned)*8]; btAssert(count<int (sizeof(signs)/sizeof(signs[0]))); for(int i=0;i<count;++i) { signs[i]= ((normals[i].x()>=0)?1:0)+ ((normals[i].y()>=0)?2:0)+ ((normals[i].z()>=0)?4:0); } stack.reserve(SIMPLE_STACKSIZE); stack.push_back(sStkNP(root,0)); do { sStkNP se=stack[stack.size()-1]; bool out=false; stack.pop_back(); for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1) { if(0==(se.mask&j)) { const int side=se.node->volume.Classify(normals[i],offsets[i],signs[i]); switch(side) { case -1: out=true;break; case +1: se.mask|=j;break; } } } if(!out) { if((se.mask!=inside)&&(se.node->isinternal())) { stack.push_back(sStkNP(se.node->childs[0],se.mask)); stack.push_back(sStkNP(se.node->childs[1],se.mask)); } else { if(policy.AllLeaves(se.node)) enumLeaves(se.node,policy); } } } while(stack.size()); } } // DBVT_PREFIX inline void btDbvt::collideOCL( const btDbvtNode* root, const btVector3* normals, const btScalar* offsets, const btVector3& sortaxis, int count, DBVT_IPOLICY, bool fsort) { DBVT_CHECKTYPE if(root) { const unsigned srtsgns=(sortaxis[0]>=0?1:0)+ (sortaxis[1]>=0?2:0)+ (sortaxis[2]>=0?4:0); const int inside=(1<<count)-1; btAlignedObjectArray<sStkNPS> stock; btAlignedObjectArray<int> ifree; btAlignedObjectArray<int> stack; int signs[sizeof(unsigned)*8]; btAssert(count<int (sizeof(signs)/sizeof(signs[0]))); for(int i=0;i<count;++i) { signs[i]= ((normals[i].x()>=0)?1:0)+ ((normals[i].y()>=0)?2:0)+ ((normals[i].z()>=0)?4:0); } stock.reserve(SIMPLE_STACKSIZE); stack.reserve(SIMPLE_STACKSIZE); ifree.reserve(SIMPLE_STACKSIZE); stack.push_back(allocate(ifree,stock,sStkNPS(root,0,root->volume.ProjectMinimum(sortaxis,srtsgns)))); do { const int id=stack[stack.size()-1]; sStkNPS se=stock[id]; stack.pop_back();ifree.push_back(id); if(se.mask!=inside) { bool out=false; for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1) { if(0==(se.mask&j)) { const int side=se.node->volume.Classify(normals[i],offsets[i],signs[i]); switch(side) { case -1: out=true;break; case +1: se.mask|=j;break; } } } if(out) continue; } if(policy.Descent(se.node)) { if(se.node->isinternal()) { const btDbvtNode* pns[]={ se.node->childs[0],se.node->childs[1]}; sStkNPS nes[]={ sStkNPS(pns[0],se.mask,pns[0]->volume.ProjectMinimum(sortaxis,srtsgns)), sStkNPS(pns[1],se.mask,pns[1]->volume.ProjectMinimum(sortaxis,srtsgns))}; const int q=nes[0].value<nes[1].value?1:0; int j=stack.size(); if(fsort&&(j>0)) { /* Insert 0 */ j=nearest(&stack[0],&stock[0],nes[q].value,0,stack.size()); stack.push_back(0); //void * memmove ( void * destination, const void * source, size_t num ); #if DBVT_USE_MEMMOVE { int num_items_to_move = stack.size()-1-j; if(num_items_to_move > 0) memmove(&stack[j+1],&stack[j],sizeof(int)*num_items_to_move); } #else for(int k=stack.size()-1;k>j;--k) { stack[k]=stack[k-1]; } #endif stack[j]=allocate(ifree,stock,nes[q]); /* Insert 1 */ j=nearest(&stack[0],&stock[0],nes[1-q].value,j,stack.size()); stack.push_back(0); #if DBVT_USE_MEMMOVE { int num_items_to_move = stack.size()-1-j; if(num_items_to_move > 0) memmove(&stack[j+1],&stack[j],sizeof(int)*num_items_to_move); } #else for(int k=stack.size()-1;k>j;--k) { stack[k]=stack[k-1]; } #endif stack[j]=allocate(ifree,stock,nes[1-q]); } else { stack.push_back(allocate(ifree,stock,nes[q])); stack.push_back(allocate(ifree,stock,nes[1-q])); } } else { policy.Process(se.node,se.value); } } } while(stack.size()); } } // DBVT_PREFIX inline void btDbvt::collideTU( const btDbvtNode* root, DBVT_IPOLICY) { DBVT_CHECKTYPE if(root) { btAlignedObjectArray<const btDbvtNode*> stack; stack.reserve(SIMPLE_STACKSIZE); stack.push_back(root); do { const btDbvtNode* n=stack[stack.size()-1]; stack.pop_back(); if(policy.Descent(n)) { if(n->isinternal()) { stack.push_back(n->childs[0]);stack.push_back(n->childs[1]); } else { policy.Process(n); } } } while(stack.size()>0); } } // // PP Cleanup // #undef DBVT_USE_MEMMOVE #undef DBVT_USE_TEMPLATE #undef DBVT_VIRTUAL_DTOR #undef DBVT_VIRTUAL #undef DBVT_PREFIX #undef DBVT_IPOLICY #undef DBVT_CHECKTYPE #undef DBVT_IMPL_GENERIC #undef DBVT_IMPL_SSE #undef DBVT_USE_INTRINSIC_SSE #undef DBVT_SELECT_IMPL #undef DBVT_MERGE_IMPL #undef DBVT_INT0_IMPL #endif
412
0.985887
1
0.985887
game-dev
MEDIA
0.657592
game-dev
0.930515
1
0.930515
OversizedSunCoreDev/ArtilleryPrototype
4,125
Source/ArtilleryRuntime/Public/TestTypes/FMockChairCannon.h
#pragma once #include "CoreMinimal.h" #include "ArtilleryProjectileDispatch.h" #include "FArtilleryGun.h" #include "FTSphereCast.h" #include "UArtilleryAbilityMinimum.h" #include "FMockChairCannon.generated.h" // I'mma firing my... chairs? Look I didn't have rockets ok USTRUCT(BlueprintType) struct ARTILLERYRUNTIME_API FMockChairCannon : public FArtilleryGun { GENERATED_BODY() public: friend class UArtilleryPerActorAbilityMinimum; FMockChairCannon(const FGunKey& KeyFromDispatch, int MaxAmmoIn, int FirerateIn, int ReloadTimeIn) { MyGunKey = KeyFromDispatch; MaxAmmo = MaxAmmoIn; Firerate = FirerateIn; ReloadTime = ReloadTimeIn; MyDispatch = nullptr; MyProjectileDispatch = nullptr; }; FMockChairCannon() : Super() { MyGunKey = Default; MaxAmmo = 10; Firerate = 60; ReloadTime = 150; MyDispatch = nullptr; MyProjectileDispatch = nullptr; }; virtual bool Initialize( const FGunKey& KeyFromDispatch, const bool MyCodeWillHandleKeys, UArtilleryPerActorAbilityMinimum* PF = nullptr, UArtilleryPerActorAbilityMinimum* PFC = nullptr, UArtilleryPerActorAbilityMinimum* F = nullptr, UArtilleryPerActorAbilityMinimum* FC = nullptr, UArtilleryPerActorAbilityMinimum* PtF = nullptr, UArtilleryPerActorAbilityMinimum* PtFc = nullptr, UArtilleryPerActorAbilityMinimum* FFC = nullptr) override { return ARTGUN_MACROAUTOINIT(MyCodeWillHandleKeys); } virtual void PreFireGun( const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData = nullptr, bool RerunDueToReconcile = false, int DallyFramesToOmit = 0) override { AttrPtr CooldownRemainingPtr = MyDispatch->GetAttrib(MyGunKey, COOLDOWN_REMAINING); AttrPtr AmmoRemainingPtr = MyDispatch->GetAttrib(MyGunKey, AMMO); if (!CooldownRemainingPtr.IsValid() || CooldownRemainingPtr->GetCurrentValue() > 0.f) { // Cooldown not up yet! return; } if (!AmmoRemainingPtr.IsValid() || AmmoRemainingPtr->GetCurrentValue() <= 0.f) { // No ammo! return; } FireGun(Fired, 0, ActorInfo, ActivationInfo, false, TriggerEventData, Handle); }; virtual void FireGun( FArtilleryStates OutcomeStates, int DallyFramesToOmit, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, bool RerunDueToReconcile, const FGameplayEventData* TriggerEventData, FGameplayAbilitySpecHandle Handle) override { if (PlayerCameraComponent.IsValid() && FiringPointComponent.IsValid()) { FVector StartLocation = PlayerCameraComponent->GetComponentLocation() + FVector(-10.0f, 0.0f, 0.0f); FRotator Rotation = PlayerCameraComponent->GetRelativeRotation(); FSkeletonKey ChairKey = GWorld->GetSubsystem<UArtilleryProjectileDispatch>()->CreateProjectileInstance(TEXT("ChairRocket"), PlayerCameraComponent->GetComponentTransform(), Rotation.Vector() * 1200, true); PostFireGun(Fired, 0, ActorInfo, ActivationInfo, false, TriggerEventData, Handle); } } virtual void PostFireGun( FArtilleryStates OutcomeStates, int DallyFramesToOmit, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, bool RerunDueToReconcile, const FGameplayEventData* TriggerEventData, FGameplayAbilitySpecHandle Handle) override { AttrPtr AmmoPtr = MyDispatch->GetAttrib(MyGunKey, AMMO); if (AmmoPtr.IsValid()) { AmmoPtr->SetCurrentValue(AmmoPtr->GetCurrentValue() - 1); } AttrPtr CooldownPtr = MyDispatch->GetAttrib(MyGunKey, COOLDOWN); AttrPtr CooldownRemainingPtr = MyDispatch->GetAttrib(MyGunKey, COOLDOWN_REMAINING); if (CooldownPtr.IsValid() && CooldownRemainingPtr.IsValid()) { CooldownRemainingPtr->SetCurrentValue(CooldownPtr->GetCurrentValue()); } MyDispatch->GetAttrib(MyGunKey, TICKS_SINCE_GUN_LAST_FIRED)->SetCurrentValue(0.f); MyDispatch->GetAttrib(MyGunKey, AttribKey::LastFiredTimestamp)->SetCurrentValue(static_cast<double>(MyDispatch->GetShadowNow())); }; private: static const inline FGunKey Default = FGunKey("ChairCannon", UINT64_MAX); };
412
0.740878
1
0.740878
game-dev
MEDIA
0.969998
game-dev
0.693662
1
0.693662
swgemu/Core3
1,564
MMOCoreORB/src/server/zone/objects/creature/commands/NextCraftingStageCommand.h
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #ifndef NEXTCRAFTINGSTAGECOMMAND_H_ #define NEXTCRAFTINGSTAGECOMMAND_H_ #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/player/sessions/TradeSession.h" class NextCraftingStageCommand : public QueueCommand { public: NextCraftingStageCommand(const String& name, ZoneProcessServer* server) : QueueCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const { if (!checkStateMask(creature)) return INVALIDSTATE; if (!checkInvalidLocomotions(creature)) return INVALIDLOCOMOTION; /** * Argument = 1 integer * This argument is the stage for nextCraftingStage */ if(!creature->isPlayerCreature()) return INVALIDTARGET; ManagedReference<TradeSession*> tradeContainer = creature->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>(); if (tradeContainer != nullptr) { server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(creature); } Reference<CraftingSession*> session = creature->getActiveSession(SessionFacadeType::CRAFTING).castTo<CraftingSession*>(); if(session == nullptr) { return GENERALERROR; } StringTokenizer tokenizer(arguments.toString()); int clientCounter = 0; if(tokenizer.hasMoreTokens()) { clientCounter = tokenizer.getIntToken(); } Locker locker(session); session->nextCraftingStage(clientCounter); return SUCCESS; } }; #endif //NEXTCRAFTINGSTAGECOMMAND_H_
412
0.945241
1
0.945241
game-dev
MEDIA
0.794633
game-dev
0.927786
1
0.927786
DivineRPG/DivineRPG
1,119
src/main/java/divinerpg/entities/projectile/arrows/EverArrow.java
package divinerpg.entities.projectile.arrows; import divinerpg.entities.projectile.DivineArrow; import net.minecraft.world.entity.*; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import org.jetbrains.annotations.Nullable; import static divinerpg.registries.EntityRegistry.EVER_ARROW; import static divinerpg.registries.ItemRegistry.ever_arrow; public class EverArrow extends DivineArrow { public EverArrow(EntityType<? extends DivineArrow> entityType, Level level) {super(entityType, level);} public EverArrow(Level level, LivingEntity owner, ItemStack pickupItemStack, @Nullable ItemStack firedFromWeapon) { super(EVER_ARROW.get(), level, owner, pickupItemStack, firedFromWeapon); } public EverArrow(Level level, double x, double y, double z, ItemStack pickupItemStack, @Nullable ItemStack firedFromWeapon) { super(EVER_ARROW.get(), level, x, y, z, pickupItemStack, firedFromWeapon); } @Override protected ItemStack getDefaultPickupItem() {return new ItemStack(ever_arrow.get());} @Override public float getArrowPower() {return 25;} }
412
0.687932
1
0.687932
game-dev
MEDIA
0.953208
game-dev
0.771792
1
0.771792
Joshua-F/osrs-dumps
2,599
script/[proc,hiscores_group_members_dropdown_setup].cs2
// 7505 [proc,hiscores_group_members_dropdown_setup](int $int0)(int) cc_deleteall(hiscores:hiscores_group_members_dropdown); if_setposition(0, $int0, ^setpos_abs_centre, ^setpos_abs_top, hiscores:hiscores_group_members_dropdown); def_int $int1 = 0; cc_create(hiscores:hiscores_group_members_dropdown, ^iftype_graphic, $int1); $int1 = calc($int1 + 1); cc_setsize(0, 0, ^setsize_minus, ^setsize_minus); cc_setposition(0, 0, ^setpos_abs_centre, ^setpos_abs_centre); cc_setgraphic(tradebacking_dark); cc_settiling(true); cc_create(hiscores:hiscores_group_members_dropdown, ^iftype_rectangle, $int1); $int1 = calc($int1 + 1); cc_setsize(0, 0, ^setsize_minus, ^setsize_minus); cc_setposition(0, 0, ^setpos_abs_centre, ^setpos_abs_centre); cc_setfill(false); cc_setcolour(0xe0e0c); cc_create(hiscores:hiscores_group_members_dropdown, ^iftype_rectangle, $int1); $int1 = calc($int1 + 1); cc_setsize(2, 2, ^setsize_minus, ^setsize_minus); cc_setposition(0, 0, ^setpos_abs_centre, ^setpos_abs_centre); cc_setfill(false); cc_setcolour(0x474745); cc_create(hiscores:hiscores_group_members_dropdown, ^iftype_graphic, $int1); def_int $int2 = $int1; $int1 = calc($int1 + 1); if (%hiscores_gim_group_found = 1) { cc_setsize(16, 16, ^setsize_abs, ^setsize_abs); cc_setposition(2, 0, ^setpos_abs_right, ^setpos_abs_centre); cc_setgraphic("scrollbar_v2,1"); } cc_create(hiscores:hiscores_group_members_dropdown, ^iftype_text, $int1); def_int $int3 = $int1; $int1 = calc($int1 + 1); cc_settextfont(p12_full); cc_settextshadow(true); cc_setcolour(0xff981f); cc_settextalign(^settextalign_centre, ^settextalign_centre, 0); def_string $string0 = "Select a group member"; if (%hiscores_gim_group_found = 0) { $string0 = "Search for a group to view members"; } def_int $int4 = parawidth($string0, 500, p12_full); cc_settext($string0); cc_setsize($int4, 20, ^setsize_abs, ^setsize_minus); cc_setposition(0, 0, ^setpos_abs_centre, ^setpos_abs_centre); if (%hiscores_gim_group_found = 1) { if (~on_enhanced_mobile = false) { if_setonmouseover("cc_settrans(hiscores:hiscores_group_members_dropdown, $int1, 220, null)", hiscores:hiscores_group_members_dropdown); if_setonmouseleave("cc_settrans(hiscores:hiscores_group_members_dropdown, $int1, 255, null)", hiscores:hiscores_group_members_dropdown); } if_setop(1, "Select <col=ff981f>Group member", hiscores:hiscores_group_members_dropdown); if_setonop("hiscores_group_members_show_dropdown($int2, $int3)", hiscores:hiscores_group_members_dropdown); } else { if_clearops(hiscores:hiscores_group_members_dropdown); } return(30);
412
0.872862
1
0.872862
game-dev
MEDIA
0.413781
game-dev
0.680903
1
0.680903
Gethe/wow-ui-source
1,926
Interface/AddOns/Blizzard_FrameXMLUtil/DragonridingUtil.lua
DragonridingUtil = {}; function DragonridingUtil.IsDragonridingUnlocked() return C_MountJournal.IsDragonridingUnlocked(); end function DragonridingUtil.IsDragonridingTreeOpen() if not GenericTraitFrame or not GenericTraitFrame:IsShown()then return false; end return GenericTraitFrame:GetConfigID() == C_Traits.GetConfigIDBySystemID(Constants.MountDynamicFlightConsts.TRAIT_SYSTEM_ID); end function DragonridingUtil.CanSpendDragonridingGlyphs() if not DragonridingUtil.IsDragonridingUnlocked() then return false; end local dragonridingConfigID = C_Traits.GetConfigIDBySystemID(Constants.MountDynamicFlightConsts.TRAIT_SYSTEM_ID); if not dragonridingConfigID then return false; end local excludeStagedChanges = false; local treeCurrencies = C_Traits.GetTreeCurrencyInfo(dragonridingConfigID, Constants.MountDynamicFlightConsts.TREE_ID, excludeStagedChanges); if #treeCurrencies <= 0 then return false; end local unspentGlyphCount = treeCurrencies[1].quantity; local hasUnspentDragonridingGlyphs = unspentGlyphCount > 0; if not hasUnspentDragonridingGlyphs then return false; end -- We have unspent glyphs, but can we actually purchase something? local dragonridingNodeIDs = C_Traits.GetTreeNodes(Constants.MountDynamicFlightConsts.TREE_ID); for _, nodeID in ipairs(dragonridingNodeIDs) do local nodeCosts = C_Traits.GetNodeCost(dragonridingConfigID, nodeID); local canAffordNode = (#nodeCosts == 0) or (unspentGlyphCount >= nodeCosts[1].amount); if canAffordNode then -- Some nodes give you multiple choices and let you pick one, let's see if you can purchase any of them local nodeInfo = C_Traits.GetNodeInfo(dragonridingConfigID, nodeID); for _, entryID in ipairs(nodeInfo.entryIDs) do if C_Traits.CanPurchaseRank(dragonridingConfigID, nodeID, entryID) then -- We can spend our glyphs on something! return true; end end end end return false; end
412
0.871009
1
0.871009
game-dev
MEDIA
0.661548
game-dev
0.830097
1
0.830097
google-research/falken
3,755
environments/unity/demos/Assets/Common/Scripts/Projectile.cs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// <c>Projectile</c> An object which flies through the air, intsersects objects, and applies damage. /// </summary> public class Projectile : MonoBehaviour { [Tooltip("The speed at which this projectile flies.")] [Range(0, 50)] public float speed = 1; [Tooltip("The amount of damage delivered on contact.")] [Range(0, 1000)] public int damage = 1; [Tooltip("The maximum number of seconds this projectile can exist.")] [Range(0, 100)] public int lifetime = 5; [Tooltip("Whether this projectile should fly straight or vector towards a target.")] public bool homing; [Tooltip("Maximum turning speed (only for homing projectiles).")] [Range(0, 1000)] public float maxTurnSpeed = 1; [Tooltip("Effect to spawn on impact")] public Transform impactEffect; private float length; private float expirationTime; private Vector3 lastPos; private GameObject target; private Vector3 targetPos; /// <summary> /// Sets the target object and/or position for this projectile. /// </summary> public void SetTarget(GameObject target, Vector3 targetPos) { this.target = target; this.targetPos = target ? target.transform.InverseTransformPoint(targetPos) : targetPos; } void Start() { lastPos = transform.position; expirationTime = Time.fixedTime + lifetime; MeshRenderer renderer = GetComponent<MeshRenderer>(); if (renderer) { length = renderer.bounds.extents.z; } } void FixedUpdate() { if (Time.fixedTime >= expirationTime) { Destroy(gameObject); return; } if (homing) { float step = maxTurnSpeed * Time.fixedDeltaTime; Vector3 targetWS = target ? target.transform.TransformPoint(targetPos) : targetPos; Quaternion rotationToTarget = Quaternion.LookRotation(targetWS - transform.position); transform.rotation = Quaternion.RotateTowards(transform.rotation, rotationToTarget, step); } float moveDistance = speed * Time.fixedDeltaTime; Vector3 newPosition = lastPos + transform.forward * moveDistance; RaycastHit hit; if (Physics.Raycast(lastPos, transform.forward, out hit, moveDistance + length)) { newPosition = hit.point; if (hit.collider) { Health health = hit.collider.GetComponent<Health>(); if (health) { health.TakeDamage(damage); } } if (impactEffect) { Transform impact = Instantiate(impactEffect, hit.point, Quaternion.identity); impact.forward = hit.normal; } // TO DO: This should turn off the mesh renderer and particle systems // but delay briefly before being destroyed so the particles can fade out GameObject.Destroy(gameObject); } transform.position = newPosition; lastPos = newPosition; } }
412
0.931387
1
0.931387
game-dev
MEDIA
0.99225
game-dev
0.982814
1
0.982814
electronicarts/CnC_Red_Alert
3,231
CODE/REGION.H
/* ** Command & Conquer Red Alert(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* $Header: /CounterStrike/REGION.H 1 3/03/97 10:25a Joe_bostic $ */ /*********************************************************************************************** *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** *********************************************************************************************** * * * Project Name : Command & Conquer * * * * File Name : REGION.H * * * * Programmer : Joe L. Bostic * * * * Start Date : 03/09/95 * * * * Last Update : March 9, 1995 [JLB] * * * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #ifndef REGION_H #define REGION_H class RegionClass { public: RegionClass(void) {Threat = 0;}; ~RegionClass(void) {}; int operator != (RegionClass const & region) {return memcmp(this, &region, sizeof(RegionClass));}; int operator == (RegionClass const & region) {return !memcmp(this, &region, sizeof(RegionClass));}; int operator > (RegionClass const & region) {return memcmp(this, &region, sizeof(RegionClass)) > 0;}; int operator < (RegionClass const & region) {return memcmp(this, &region, sizeof(RegionClass)) < 0;}; void Reset_Threat(void) {Threat = 0;}; void Adjust_Threat(int threat, int neg) {if (neg) Threat -= threat; else Threat+= threat;}; int Threat_Value(void) const {return Threat;}; protected: long Threat; }; #endif
412
0.914721
1
0.914721
game-dev
MEDIA
0.910801
game-dev
0.808262
1
0.808262
cvet/fonline
5,786
ThirdParty/spark/spark/src/Extensions/Modifiers/SPK_RandomForce.cpp
// // SPARK particle engine // // Copyright (C) 2008-2011 - Julien Fryer - julienfryer@gmail.com // Copyright (C) 2017 - Frederic Martin - fredakilla@gmail.com // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #include <SPARK_Core.h> #include "Extensions/Modifiers/SPK_RandomForce.h" namespace SPK { RandomForce::RandomForce(const Vector3D& minVector,const Vector3D& maxVector,float minPeriod,float maxPeriod) : Modifier(MODIFIER_PRIORITY_FORCE,true,true,false), minPeriod(1.0f), maxPeriod(1.0f) { setVectors(minVector,maxVector); setPeriods(minPeriod,maxPeriod); } void RandomForce::setVectors(const Vector3D& minVector,const Vector3D& maxVector) { this->minVector = minVector; this->maxVector = maxVector; this->minVector.setMin(maxVector); this->maxVector.setMax(minVector); transformDir(tMinVector,minVector); transformDir(tMaxVector,maxVector); tMinVector.setMin(tMaxVector); tMaxVector.setMax(tMinVector); } void RandomForce::setPeriods(float minPeriod,float maxPeriod) { if (minPeriod <= 0.0f || maxPeriod <= 0.0f) { SPK_LOG_WARNING("RandomForce::setPeriods(float,float) - Periods must be greater to 0, nothing is set"); return; } if (minPeriod > maxPeriod) { SPK_LOG_WARNING("RandomForce::setPeriods(float,float) - min periods is greater than max periods, values are swapped"); std::swap(minPeriod,maxPeriod); } this->minPeriod = minPeriod; this->maxPeriod = maxPeriod; } void RandomForce::innerUpdateTransform() { transformDir(tMinVector,minVector); transformDir(tMaxVector,maxVector); tMinVector.setMin(tMaxVector); tMaxVector.setMax(tMinVector); } void RandomForce::createData(DataSet& dataSet,const Group& group) const { dataSet.init(NB_DATA); dataSet.setData(FORCE_VECTOR_INDEX,SPK_NEW(Vector3DArrayData,group.getCapacity(),1)); dataSet.setData(REMAINING_TIME_INDEX,SPK_NEW(FloatArrayData,group.getCapacity(),1)); // Inits the data for (ConstGroupIterator particleIt(group); !particleIt.end(); ++particleIt) initParticle(*particleIt,&dataSet); } void RandomForce::init(Particle& particle,DataSet* dataSet) const { initParticle(particle,dataSet); } void RandomForce::advanceTime(const Particle& particle,DataSet* dataSet,float deltaTime,float& time) const { if (time <= 0.0f) initParticle(particle,dataSet); else time -= deltaTime; } void RandomForce::initParticle(const Particle& particle,DataSet* dataSet) const { size_t index = particle.getIndex(); *SPK_GET_DATA(Vector3DArrayData,dataSet,FORCE_VECTOR_INDEX).getParticleData(index) = SPK_RANDOM(tMinVector,tMaxVector); *SPK_GET_DATA(FloatArrayData,dataSet,REMAINING_TIME_INDEX).getParticleData(index) = SPK_RANDOM(minPeriod,maxPeriod); } void RandomForce::modify(Group& group,DataSet* dataSet,float deltaTime) const { Vector3D* forceIt = SPK_GET_DATA(Vector3DArrayData,dataSet,FORCE_VECTOR_INDEX).getData(); float* timeIt = SPK_GET_DATA(FloatArrayData,dataSet,REMAINING_TIME_INDEX).getData(); if (group.isEnabled(PARAM_MASS)) for (GroupIterator particleIt(group); !particleIt.end(); ++particleIt) { Particle& particle = *particleIt; advanceTime(particle,dataSet,deltaTime,*timeIt); particle.velocity() += *forceIt * deltaTime / particle.getParamNC(PARAM_MASS); ++forceIt; ++timeIt; } else for (GroupIterator particleIt(group); !particleIt.end(); ++particleIt) { Particle& particle = *particleIt; advanceTime(particle,dataSet,deltaTime,*timeIt); particle.velocity() += *forceIt * deltaTime; // opti for unset mass ++forceIt; ++timeIt; } } void RandomForce::innerImport(const IO::Descriptor& descriptor) { Modifier::innerImport(descriptor); const IO::Attribute* attrib = NULL; if ((attrib = descriptor.getAttributeWithValue("values"))) { std::vector<Vector3D> tmpValues = attrib->getValues<Vector3D>(); switch (tmpValues.size()) { case 1 : setVectors(tmpValues[0],tmpValues[0]); break; case 2 : setVectors(tmpValues[0],tmpValues[1]); break; default : SPK_LOG_ERROR("RandomForce::innerImport(const IO::Descriptor&) - Wrong number of values : " << tmpValues.size()); } } if ((attrib = descriptor.getAttributeWithValue("period"))) { std::vector<float> tmpPeriods = attrib->getValues<float>(); switch (tmpPeriods.size()) { case 1 : setPeriods(tmpPeriods[0],tmpPeriods[0]); break; case 2 : setPeriods(tmpPeriods[0],tmpPeriods[1]); break; default : SPK_LOG_ERROR("RandomForce::innerImport(const IO::Descriptor&) - Wrong number of periods : " << tmpPeriods.size()); } } } void RandomForce::innerExport(IO::Descriptor& descriptor) const { Modifier::innerExport(descriptor); Vector3D tmpValues[2] = {minVector,maxVector}; descriptor.getAttribute("values")->setValues(tmpValues,2); float tmpPeriods[2] = {minPeriod,maxPeriod}; descriptor.getAttribute("period")->setValues(tmpPeriods,minPeriod == maxPeriod ? 1 : 2); } }
412
0.982061
1
0.982061
game-dev
MEDIA
0.558946
game-dev
0.976863
1
0.976863
gawric/Unity-Client-for-L2J
6,938
l2-unity/Assets/Scripts/Game/Entity/Interlude/MapClassId.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering.Universal.Internal; using UnityEngine.UIElements; public class MapClassId { private static Dictionary<int, ClassIdTemplate> dict = new Dictionary<int, ClassIdTemplate>(); private static readonly string Fighter = "Fighter"; private static readonly string Human = "Human"; private static readonly string Ork = "Orc"; private static readonly string Dwarf = "Dwarf"; private static readonly string Dark_Elf = "Dark Elf"; private static readonly string Elf = "Elf"; public static void Init() { if(dict.Count == 0) { //Human AddClassId((int)ClassId.FIGHTER, false, InterludeRace.HUMAN, null); //AddClassId((int)ClassId.WARRIOR, false, InterludeRace.HUMAN, GetClassId((int)ClassId.FIGHTER)); AddClassId((int)ClassId.MAGE, true, InterludeRace.HUMAN, null); //Elven AddClassId((int)ClassId.ELVEN_FIGHTER, false, InterludeRace.ELF, null); AddClassId((int)ClassId.ELVEN_MAGE, true, InterludeRace.ELF, null); //Dark Elven AddClassId((int)ClassId.DARK_FIGHTER, false, InterludeRace.DARK_ELF, null); AddClassId((int)ClassId.DARK_MAGE, true, InterludeRace.DARK_ELF, null); //Ork AddClassId((int)ClassId.ORC_FIGHTER, false, InterludeRace.ORC, null); AddClassId((int)ClassId.ORC_MAGE, true, InterludeRace.ORC, null); //DWARVEN AddClassId((int)ClassId.DWARVEN_FIGHTER, false, InterludeRace.DWARF, null); } } public static CharacterRace GetRace(int race) { if(race == 0) { return CharacterRace.Human; }else if (race == 1) { return CharacterRace.Elf; } else if (race == 2) { return CharacterRace.DarkElf; } else if (race == 3) { return CharacterRace.Orc; } else if (race == 4) { return CharacterRace.Dwarf; } Debug.Log("Critical error: Not Found Race!!!"); return 0; } public static CharacterRace GetCharacterRace(int serverClassId) { if((int)ClassId.FIGHTER == serverClassId | (int)ClassId.WARRIOR == serverClassId | (int)ClassId.MAGE == serverClassId | (int)ClassId.WIZARD == serverClassId) { return CharacterRace.Human; }else if ((int)ClassId.ELVEN_FIGHTER == serverClassId | (int)ClassId.ELVEN_KNIGHT == serverClassId | (int)ClassId.ELVEN_MAGE == serverClassId | (int)ClassId.ELVEN_WIZARD == serverClassId) { return CharacterRace.Elf; } else if ((int)ClassId.DARK_FIGHTER == serverClassId | (int)ClassId.PALUS_KNIGHT == serverClassId | (int)ClassId.DARK_MAGE == serverClassId | (int)ClassId.DARK_WIZARD == serverClassId) { return CharacterRace.DarkElf; } else if ((int)ClassId.ORC_FIGHTER == serverClassId | (int)ClassId.ORC_RAIDER == serverClassId | (int)ClassId.ORC_MAGE == serverClassId | (int)ClassId.ORC_SHAMAN == serverClassId) { return CharacterRace.Orc; } //4 Dwarf Race else if ((int)ClassId.DWARVEN_FIGHTER == serverClassId | (int)ClassId.SCAVENGER == serverClassId | 4 == serverClassId) { return CharacterRace.Dwarf; } return CharacterRace.DarkElf; } public static bool IsMage(int serverClassId) { if ((int)ClassId.FIGHTER == serverClassId | (int)ClassId.WARRIOR == serverClassId) { return false; }else if ((int)ClassId.MAGE == serverClassId | (int)ClassId.WIZARD == serverClassId) { return true; } else if ((int)ClassId.ELVEN_FIGHTER == serverClassId | (int)ClassId.ELVEN_KNIGHT == serverClassId) { return false; }else if ((int)ClassId.ELVEN_MAGE == serverClassId | (int)ClassId.ELVEN_WIZARD == serverClassId) { return true; } else if ((int)ClassId.DARK_FIGHTER == serverClassId | (int)ClassId.PALUS_KNIGHT == serverClassId ) { return false; } else if ((int)ClassId.DARK_MAGE == serverClassId | (int)ClassId.DARK_WIZARD == serverClassId) { return true; } else if ((int)ClassId.ORC_FIGHTER == serverClassId | (int)ClassId.ORC_RAIDER == serverClassId ) { return false; } else if ((int)ClassId.ORC_MAGE == serverClassId | (int)ClassId.ORC_SHAMAN == serverClassId) { return true; } else if ((int)ClassId.DWARVEN_FIGHTER == serverClassId | (int)ClassId.SCAVENGER == serverClassId) { return false; } return false; } public static void AddClassId(int pId, bool mage , InterludeRace race, ClassIdTemplate pParent) { //TemplateClassId tamplate = new TemplateClassId(pId, mage, race, pParent); dict.Add(pId, new ClassIdTemplate(pId, mage, race, pParent)); } public static ClassIdTemplate GetClassId(int pId) { return (dict.ContainsKey(pId)) ? dict[pId] : null; } //"Human", "Elf", "Dark Elf", "Orc", "Dwarf" public static ClassIdTemplate GetClassIdByName(string className ,string raceName ) { if (raceName.Equals(Human)) { if (className.Equals(Fighter)) { return GetClassId((int) ClassId.FIGHTER); } else { return GetClassId((int)ClassId.MAGE); } }else if (raceName.Equals(Ork)) { if (className.Equals(Fighter)) { return GetClassId((int)ClassId.ORC_FIGHTER); } else { return GetClassId((int)ClassId.ORC_MAGE); } } else if (raceName.Equals(Dwarf)) { if (className.Equals(Fighter)) { return GetClassId((int)ClassId.DWARVEN_FIGHTER); } else { return GetClassId((int)ClassId.DWARVEN_FIGHTER); } } else if (raceName.Equals(Dark_Elf)) { if (className.Equals(Fighter)) { return GetClassId((int)ClassId.DARK_FIGHTER); } else { return GetClassId((int)ClassId.DARK_MAGE); } } else if (raceName.Equals(Elf)) { if (className.Equals(Fighter)) { return GetClassId((int)ClassId.ELVEN_FIGHTER); } else { return GetClassId((int)ClassId.ELVEN_MAGE); } } return null; } }
412
0.696114
1
0.696114
game-dev
MEDIA
0.798006
game-dev
0.84217
1
0.84217
CyanAsterisk/FreeCar
3,912
server/cmd/car/pkg/sim/sim.go
package sim import ( "context" "math/rand" "strconv" "time" "github.com/CyanAsterisk/FreeCar/server/cmd/car/pkg/mq" "github.com/CyanAsterisk/FreeCar/server/shared/kitex_gen/base" "github.com/CyanAsterisk/FreeCar/server/shared/kitex_gen/car" "github.com/CyanAsterisk/FreeCar/server/shared/kitex_gen/car/carservice" "github.com/cloudwego/kitex/pkg/klog" ) const ( minCarNum = 12 AccountId = "1024" CQUPTLatitude = 29.53832 CQUPTLongitude = 106.613922 ) // Controller defines a car simulation controller. type Controller struct { CarService carservice.Client Subscriber mq.Subscriber } // RunSimulations runs simulations for all cars. func (c *Controller) RunSimulations(ctx context.Context) { var cars []*base.CarEntity for { // Prevent vehicle information not being retrieved due to service failure time.Sleep(2 * time.Second) res, err := c.CarService.GetCars(ctx, &car.GetCarsRequest{}) if err != nil { klog.Errorf("cannot get cars: %s", err.Error()) continue } cars = res.Cars break } if len(cars) < minCarNum { for i := minCarNum - len(cars); i > 0; i-- { res, err := c.CarService.CreateCar(ctx, &car.CreateCarRequest{ AccountId: AccountId, PlateNum: genPlateNum(), }) if err != nil { klog.Fatalf("create cars error: %s", err.Error()) } cars = append(cars, res.CarEntity) } } klog.Infof("Running car simulations. car_count = %d", len(cars)) msgCh, cleanUp, err := c.Subscriber.Subscribe(ctx) defer cleanUp() if err != nil { klog.Errorf("cannot subscribe %s", err.Error()) return } for idx, _car := range cars { _car.Car.Position = &base.Position{ Latitude: CQUPTLatitude + (rand.Float64()-0.5)*0.1, Longitude: CQUPTLongitude + (rand.Float64()-0.5)*0.1, } req := &car.UpdateCarRequest{ Id: _car.Id, Position: _car.Car.Position, AccountId: AccountId, Power: 80 + rand.Float64()*20, } if idx < minCarNum-2 { req.Status = base.CarStatus_UNLOCKED } else { req.Status = base.CarStatus_LOCKED } _, err := c.CarService.UpdateCar(ctx, req) if err != nil { klog.Errorf("updateCar error: %s", err.Error()) } } carChans := make(map[string]chan *base.Car) for _, _car := range cars { ch := make(chan *base.Car) carChans[_car.Id] = ch go c.SimulateCar(context.Background(), _car, ch) } for carUpdate := range msgCh { if ch := carChans[carUpdate.Id]; ch != nil { ch <- carUpdate.Car } } } // SimulateCar simulates a single car. func (c *Controller) SimulateCar(ctx context.Context, carEntity *base.CarEntity, ch chan *base.Car) { tk := time.NewTicker(time.Second * 5) defer tk.Stop() klog.Infof("Simulating car: %s", carEntity.Id) for { time.Sleep(time.Millisecond * 500) var req car.UpdateCarRequest req.Id = carEntity.Id select { case update := <-ch: switch update.Status { case base.CarStatus_UNLOCKING: req.Status = base.CarStatus_UNLOCKED case base.CarStatus_LOCKING: req.Status = base.CarStatus_LOCKED case base.CarStatus_UNLOCKED: carEntity.Car.Position.Longitude += (rand.Float64() - 0.5) * 0.001 carEntity.Car.Position.Latitude += (rand.Float64() - 0.5) * 0.001 if update.Driver != nil { carEntity.Car.Power -= 0.02 * rand.Float64() } req.Position = carEntity.Car.Position req.Power = carEntity.Car.Power case base.CarStatus_LOCKED: if carEntity.Car.Power < 99 { carEntity.Car.Power += 0.01 * rand.Float64() } req.Power = carEntity.Car.Power } tk.Reset(time.Second * 5) case <-tk.C: } if _, err := c.CarService.UpdateCar(ctx, &req); err != nil { klog.Errorf("cannot update car: %s", err.Error()) } } } func genPlateNum() string { const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" plateNum := "渝" plateNum += string(letters[rand.Int()%26]) for i := 0; i < 5; i++ { plateNum += strconv.Itoa(rand.Int() % 10) } return plateNum }
412
0.852373
1
0.852373
game-dev
MEDIA
0.260696
game-dev
0.921486
1
0.921486
neuledge/ddb-table
1,594
src/queries/PutQuery.ts
import DynamoDBDocument, { Item, PutCommandInput, PutCommandOutput, } from '../DocumentClient'; import Query, { QueryRequest } from './Query'; import { ConditionExpression, ExpressionAttributeValues } from '../expressions'; import { ConditionGenerator } from '../expressions/ConditionExpression'; type QueryInput<T> = Omit<PutCommandInput, 'Item'> & { Item: T }; type QueryOutput<T> = Omit<PutCommandOutput, 'Attributes'> & { Attributes?: T; }; export default class PutQuery<T extends Item> extends Query< T, QueryInput<T>, QueryOutput<T> > { private values!: ExpressionAttributeValues; private conditions!: ConditionExpression<T>; public constructor(client: DynamoDBDocument, params: QueryInput<T>) { super( client.put.bind(client) as QueryRequest<QueryInput<T>, QueryOutput<T>>, params, ); this.handleInputUpdated(); } protected handleInputUpdated(): void { super.handleInputUpdated(); this.values = new ExpressionAttributeValues( this.input.ExpressionAttributeValues, ); this.conditions = new ConditionExpression( this.names, this.values, this.input.ConditionExpression, ); } protected syncInput(): void { super.syncInput(); this.input.ExpressionAttributeValues = this.values.serialize(); this.input.ConditionExpression = this.conditions.serialize(); } public condition(fn: ConditionGenerator<T>): this { this.conditions.and(fn); return this; } public return(values: 'ALL_OLD' | 'NONE'): this { this.input.ReturnValues = values; return this; } }
412
0.870123
1
0.870123
game-dev
MEDIA
0.23615
game-dev
0.943355
1
0.943355
Sandrem/FlyCasual
13,773
Assets/Scripts/Model/Editions/SecondEdition.cs
using ActionsList; using Arcs; using BoardTools; using Bombs; using GameModes; using Movement; using Obstacles; using Ship; using SquadBuilderNS; using SubPhases; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Tokens; using UnityEngine; using Upgrade; namespace Editions { public class SecondEdition : Edition { public override string Name { get { return "Second Edition"; } } public override string NameShort { get { return "SecondEdition"; } } public SecondEdition() { RuleSet = new RuleSets.RuleSet25(); } public override int MaxPoints { get { return 20; } } public override int MinShipsCount { get { return 3; } } public override int MaxShipsCount { get { return 8; } } public override string CombatPhaseName { get { return "Engagement"; } } public override Color MovementEasyColor { get { return new Color(0, 0.5f, 1); } } public override bool CanAttackBumpedTarget { get { return true; } } public override MovementComplexity IonManeuverComplexity { get { return MovementComplexity.Easy; } } public override string PathToSavedSquadrons { get { return "SavedSquadrons"; } } //RandomAiSquadrons public override string RootUrlForImages { get { return "https://squadbuilder.fantasyflightgames.com/card_images/"; } } // OBSOLETE public override Vector2 UpgradeCardSize { get { return new Vector2(418, 300); } } public override Vector2 UpgradeCardCompactOffset { get { return new Vector2(168, 2); } } public override Vector2 UpgradeCardCompactSize { get { return new Vector2(237, 296); } } public override Dictionary<Type, int> DamageDeckContent { get { return new Dictionary<Type, int>() { { typeof(DamageDeckCardSE.BlindedPilot), 2 }, { typeof(DamageDeckCardSE.ConsoleFire), 2 }, { typeof(DamageDeckCardSE.DamagedEngine), 2 }, { typeof(DamageDeckCardSE.DamagedSensorArray), 2 }, { typeof(DamageDeckCardSE.DirectHit), 5 }, { typeof(DamageDeckCardSE.DisabledPowerRegulator), 2 }, { typeof(DamageDeckCardSE.FuelLeak), 4 }, { typeof(DamageDeckCardSE.HullBreach), 2 }, { typeof(DamageDeckCardSE.LooseStabilizer), 2 }, { typeof(DamageDeckCardSE.PanickedPilot), 2 }, { typeof(DamageDeckCardSE.StructuralDamage), 2 }, { typeof(DamageDeckCardSE.StunnedPilot), 2 }, { typeof(DamageDeckCardSE.WeaponsFailure), 2 }, { typeof(DamageDeckCardSE.WoundedPilot), 2 }, }; } } public override Dictionary<BaseSize, int> NegativeTokensToAffectShip { get { return new Dictionary<BaseSize, int>() { { BaseSize.None, int.MaxValue }, { BaseSize.Small, 1 }, { BaseSize.Medium, 2 }, { BaseSize.Large, 3 } }; } } public override Dictionary<string, string> PreGeneratedAiSquadrons { get { return new Dictionary<string, string>() { }; } } public override int MinShipCost(Faction faction) { return 1; } private bool HasYv666InSquad() { return Global.SquadBuilder.CurrentSquad.Ships.Any(n => n.Instance is Ship.SecondEdition.YV666LightFreighter.YV666LightFreighter); } public override void EvadeDiceModification(DiceRoll diceRoll) { if (diceRoll.Blanks > 0) { diceRoll.ChangeOne(DieSide.Blank, DieSide.Success); } else if (diceRoll.Focuses > 0) { diceRoll.ChangeOne(DieSide.Focus, DieSide.Success); } else { Messages.ShowError("An Evade Token was spent, but there were no valid dice to change to evade"); } } public override void ActionIsFailed(GenericShip ship, GenericAction action, bool overWrittenInstead = false, bool hasSecondChance = false) { base.ActionIsFailed(ship, action, overWrittenInstead, hasSecondChance); // Temporary solution for off-the-board problem if (!hasSecondChance) { if (!IsTractorBeamFailed()) { Phases.CurrentSubPhase.IsReadyForCommands = true; Phases.CurrentSubPhase.SkipButton(); } else { (Phases.CurrentSubPhase as TractorBeamPlanningSubPhase).RegisterTractorPlanning(); } } } private bool IsTractorBeamFailed() { return Phases.CurrentSubPhase is TractorBeamPlanningSubPhase; } public override void AdaptShipToRules(GenericShip ship) { if (Edition.Current is SecondEdition) { if (ship.HotacManeuverTable != null) ship.HotacManeuverTable.AdaptToSecondEdition(); } } public override bool IsWeaponHaveRangeBonus(IShipWeapon weapon) { List<WeaponTypes> rangeEffectedWeaponTypes = new List<WeaponTypes>() { WeaponTypes.Cannon, WeaponTypes.PrimaryWeapon, WeaponTypes.Turret }; return rangeEffectedWeaponTypes.Contains(weapon.WeaponType) && !weapon.WeaponInfo.NoRangeBonus; } public override void SetShipBaseImage(GenericShip ship) { ship.SetShipBaseImageSecondEdition(); } public override void RotateMobileFiringArc(GenericArc arc, ArcFacing facing) { arc.ShipBase.Host.ShowMobileFiringArcHighlight(facing); } public override void RotateMobileFiringArcAlt(GenericArc arc, ArcFacing facing) { arc.ShipBase.Host.ShowMobileFiringArcAltHighlight(facing); } public override void BarrelRollTemplatePlanning() { (Phases.CurrentSubPhase as BarrelRollPlanningSubPhase).PerfromTemplatePlanningSecondEdition(); } public override void DecloakTemplatePlanning() { (Phases.CurrentSubPhase as DecloakPlanningSubPhase).PerfromTemplatePlanningSecondEdition(); } public override void SquadBuilderIsOpened() { MainMenu.CurrentMainMenu.ChangePanel("SquadBuilderPanel"); if (IsSquadBuilderLocked && Global.SquadBuilder.CurrentSquad.Points == 0) { MainMenu.CurrentMainMenu.ChangePanel("BrowseSavedSquadsPanel"); } } public override void WhenIonized(GenericShip ship) { ship.OnPerformActionStepStart += EnableIonizationActionEffect; ship.OnMovementActivationFinish += DisableIonizationActionEffect; } private void EnableIonizationActionEffect(GenericShip ship) { ship.OnTryAddAction += IonizedShipCanDoOnlyFocus; } private void DisableIonizationActionEffect(GenericShip ship) { ship.OnTryAddAction -= IonizedShipCanDoOnlyFocus; ship.OnPerformActionStepStart -= EnableIonizationActionEffect; ship.OnMovementActivationFinish -= DisableIonizationActionEffect; } private void IonizedShipCanDoOnlyFocus(GenericShip ship, GenericAction action, ref bool canBePerformed) { if (canBePerformed) { bool canPerformActionWhileIonized = ship.CallCanPerformActionWhileIonized(action); if (!canPerformActionWhileIonized) { canBePerformed = action is FocusAction; } } } public override bool ReinforceEffectCanBeUsed(ArcFacing facing) { return false; } public override bool DefenderIsReinforcedAgainstAttacker(ArcFacing facing, GenericShip defender, GenericShip attacker) { bool inFullFrontArc = defender.SectorsInfo.IsShipInSector(attacker, ArcType.FullFront); bool inFullRearArc = defender.SectorsInfo.IsShipInSector(attacker, ArcType.FullRear); return (facing == ArcFacing.FullFront) ? inFullFrontArc && !inFullRearArc : !inFullFrontArc && inFullRearArc; } public override bool ReinforcePostCombatEffectCanBeUsed(ArcFacing facing) { if (Combat.DiceRollAttack.Successes <= 1) return false; return DefenderIsReinforcedAgainstAttacker(facing, Combat.Defender, Combat.Attacker); } public override void TimedBombActivationTime(GenericShip ship) { ship.OnCheckSystemsAbilityActivation -= BombsManager.CheckBombDropAvailabilitySystemPhase; ship.OnCheckSystemsAbilityActivation += BombsManager.CheckBombDropAvailabilitySystemPhase; ship.OnSystemsAbilityActivation -= BombsManager.RegisterBombDropAvailabilitySystemPhase; ship.OnSystemsAbilityActivation += BombsManager.RegisterBombDropAvailabilitySystemPhase; } public override bool IsTokenCanBeDiscardedByJam(GenericToken token) { return token.TokenColor == TokenColors.Green || token is BlueTargetLockToken; } public override string GetPilotImageUrl(GenericShip ship, string filename) { return "https://infinitearenas.com/xw2/images/pilots/" + ship.PilotNameCanonical + ".png"; } public override string GetUpgradeImageUrl(GenericUpgrade upgrade, string filename = null) { return "https://infinitearenas.com/xw2/images/upgrades/" + upgrade.NameCanonical + ".png"; } public override string FactionToXws(Faction faction) { string result = ""; switch (faction) { case Faction.Rebel: result = "rebelalliance"; break; case Faction.Imperial: result = "galacticempire"; break; case Faction.Scum: result = "scumandvillainy"; break; case Faction.Resistance: result = "resistance"; break; case Faction.FirstOrder: result = "firstorder"; break; case Faction.Republic: result = "galacticrepublic"; break; case Faction.Separatists: result = "separatistalliance"; break; default: break; } return result; } public override Faction XwsToFaction(string factionXWS) { Faction result = Faction.None; switch (factionXWS) { case "rebelalliance": result = Faction.Rebel; break; case "galacticempire": result = Faction.Imperial; break; case "scumandvillainy": result = Faction.Scum; break; case "resistance": result = Faction.Resistance; break; case "firstorder": result = Faction.FirstOrder; break; case "galacticrepublic": result = Faction.Republic; break; case "separatistalliance": result = Faction.Separatists; break; default: break; } return result; } public override string UpgradeTypeToXws(UpgradeType upgradeType) { string result = ""; switch (upgradeType) { case UpgradeType.ForcePower: result = "force-power"; break; case UpgradeType.TacticalRelay: result = "tactical-relay"; break; default: result = upgradeType.ToString().ToLower(); break; } return result; } public override UpgradeType XwsToUpgradeType(string upgradeXws) { UpgradeType result = UpgradeType.Astromech; switch (upgradeXws) { case "force-power": result = UpgradeType.ForcePower; break; case "tactical-relay": case "tacticalrelay": result = UpgradeType.TacticalRelay; break; default: string capitalizedName = upgradeXws.First().ToString().ToUpper() + upgradeXws.Substring(1); result = (UpgradeType)Enum.Parse(typeof(UpgradeType), capitalizedName); break; } return result; } } }
412
0.936263
1
0.936263
game-dev
MEDIA
0.975645
game-dev
0.861371
1
0.861371
Secrets-of-Sosaria/World
6,924
Data/Scripts/Items/Trades/Thieving/DisguiseKit.cs
using System; using System.Collections; using Server; using Server.Gumps; using Server.Spells; using Server.Spells.Fifth; using Server.Spells.Seventh; using Server.Spells.Necromancy; using Server.Spells.Shinobi; using Server.Mobiles; using Server.Network; using Server.SkillHandlers; namespace Server.Items { public class DisguiseKit : Item { public override string DefaultDescription{ get{ return "These disguises can be used to appear as someone else. It is helpful if you are one trying to avoid the local guards. You need to be very skilled in hiding, stealth, ninjitsu, snooping, or psychology to use these."; } } [Constructable] public DisguiseKit() : base( 0xE05 ) { Name = "disguise kit"; Weight = 1.0; } public DisguiseKit( 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(); } public bool ValidateUse( Mobile from ) { PlayerMobile pm = from as PlayerMobile; if ( !IsChildOf( from.Backpack ) ) { // That must be in your pack for you to use it. from.SendLocalizedMessage( 1042001 ); } else if ( from.Skills[SkillName.Ninjitsu].Base < 50 && from.Skills[SkillName.Stealth].Base < 50 && from.Skills[SkillName.Hiding].Base < 50 && from.Skills[SkillName.Psychology].Base < 50 && from.Skills[SkillName.Snooping].Base < 50 ) { from.SendMessage("You don't seem to have the skills to apply this disguise."); return false; } else if ( !from.CanBeginAction( typeof( IncognitoSpell ) ) ) { // You cannot disguise yourself while incognitoed. from.SendLocalizedMessage( 501704 ); } else if ( !from.CanBeginAction( typeof( Deception ) ) ) { from.SendMessage("You cannot disguise yourself since you already are using deception."); } else if ( TransformationSpellHelper.UnderTransformation( from ) ) { // You cannot disguise yourself while in that form. from.SendLocalizedMessage( 1061634 ); } else if ( !from.CanBeginAction( typeof( PolymorphSpell ) ) || ( from.IsBodyMod && from.RaceID < 1 ) ) { // You cannot disguise yourself while polymorphed. from.SendLocalizedMessage( 501705 ); } else { return true; } return false; } public override void OnDoubleClick( Mobile from ) { if ( ValidateUse( from ) ) { if ( from.RaceID != 0 ) { from.HueMod = Utility.RandomColor( Utility.RandomMinMax( 1, 13 ) ); from.BodyMod = 970; from.NameMod = from.RaceWasFemale ? NameList.RandomName( "female" ) : NameList.RandomName( "male" ); from.SendLocalizedMessage( 501706 ); // Disguises wear off after 2 hours. DisguiseTimers.CreateTimer( from, TimeSpan.FromHours( 2.0 ) ); DisguiseTimers.StartTimer( from ); BuffInfo.AddBuff( from, new BuffInfo( BuffIcon.Incognito, 1075821, 1075820, TimeSpan.FromHours( 2.0 ), from ) ); this.Delete(); } else { from.HueMod = from.Race.RandomSkinHue(); from.NameMod = from.Female ? NameList.RandomName( "female" ) : NameList.RandomName( "male" ); PlayerMobile pm = from as PlayerMobile; if ( pm != null && pm.Race != null ) { pm.SetHairMods( pm.Race.RandomHair( pm.Female ), pm.Race.RandomFacialHair( pm.Female ) ); pm.HairHue = Utility.RandomHairHue(); pm.FacialHairHue = Utility.RandomHairHue(); } from.SendLocalizedMessage( 501706 ); // Disguises wear off after 2 hours. DisguiseTimers.CreateTimer( from, TimeSpan.FromHours( 2.0 ) ); DisguiseTimers.StartTimer( from ); BuffInfo.AddBuff( from, new BuffInfo( BuffIcon.Incognito, 1075821, 1075820, TimeSpan.FromHours( 2.0 ), from ) ); this.Delete(); } } } } public class DisguiseTimers { public static void Initialize() { new DisguisePersistance(); } private class InternalTimer : Timer { private Mobile m_Player; public InternalTimer( Mobile m, TimeSpan delay ) : base( delay ) { m_Player = m; Priority = TimerPriority.OneMinute; } protected override void OnTick() { m_Player.NameMod = null; if ( m_Player.RaceID != 0 ) { m_Player.HueMod = 0; m_Player.BodyMod = 0; m_Player.RaceBody(); } else if ( m_Player is PlayerMobile ) { ((PlayerMobile)m_Player).SetHairMods( -1, -1 ); m_Player.BodyMod = 0; m_Player.HueMod = -1; m_Player.NameMod = null; m_Player.RaceBody(); } DisguiseTimers.RemoveTimer( m_Player ); } } public static void CreateTimer( Mobile m, TimeSpan delay ) { if ( m != null ) if ( !m_Timers.Contains( m ) ) m_Timers[m] = new InternalTimer( m, delay ); } public static void StartTimer( Mobile m ) { Timer t = (Timer)m_Timers[m]; if ( t != null ) t.Start(); } public static bool IsDisguised( Mobile m ) { return m_Timers.Contains( m ); } public static bool StopTimer( Mobile m ) { Timer t = (Timer)m_Timers[m]; if ( t != null ) { t.Delay = t.Next - DateTime.Now; t.Stop(); } return ( t != null ); } public static bool RemoveTimer( Mobile m ) { Timer t = (Timer)m_Timers[m]; if ( t != null ) { t.Stop(); m_Timers.Remove( m ); } return ( t != null ); } public static TimeSpan TimeRemaining( Mobile m ) { Timer t = (Timer)m_Timers[m]; if ( t != null ) { return t.Next - DateTime.Now; } return TimeSpan.Zero; } private static Hashtable m_Timers = new Hashtable(); public static Hashtable Timers { get { return m_Timers; } } public static void RemoveDisguise( Mobile from ) { if ( TransformationSpellHelper.UnderTransformation( from, typeof( Spells.Necromancy.VampiricEmbraceSpell ) ) ){ /* IGNORE */ } else if ( TransformationSpellHelper.UnderTransformation( from, typeof( Spells.Necromancy.WraithFormSpell ) ) ){ /* IGNORE */ } else if ( TransformationSpellHelper.UnderTransformation( from, typeof( Spells.Necromancy.LichFormSpell ) ) ){ /* IGNORE */ } else if ( TransformationSpellHelper.UnderTransformation( from, typeof( Spells.Necromancy.HorrificBeastSpell ) ) ){ /* IGNORE */ } else if ( from.NameMod != null ) { BuffInfo.RemoveBuff( from, BuffIcon.Incognito ); from.HueMod = -1; from.NameMod = null; ((PlayerMobile)from).SavagePaintExpiration = TimeSpan.Zero; ((PlayerMobile)from).SetHairMods( -1, -1 ); PolymorphSpell.StopTimer( from ); IncognitoSpell.StopTimer( from ); Deception.StopTimer( from ); DisguiseTimers.RemoveTimer( from ); from.EndAction( typeof( PolymorphSpell ) ); from.EndAction( typeof( IncognitoSpell ) ); from.EndAction( typeof( Deception ) ); } } } }
412
0.934037
1
0.934037
game-dev
MEDIA
0.922627
game-dev
0.992747
1
0.992747
elBukkit/MagicPlugin
20,427
CompatibilityLib/v1_20_6/src/main/java/com/elmakers/mine/bukkit/utility/platform/v1_20_6/NBTUtils.java
package com.elmakers.mine.bukkit.utility.platform.v1_20_6; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; import com.elmakers.mine.bukkit.utility.CompatibilityConstants; import com.elmakers.mine.bukkit.utility.platform.Platform; import com.elmakers.mine.bukkit.utility.platform.base.NBTUtilsBase; import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.ByteArrayTag; import net.minecraft.nbt.ByteTag; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.DoubleTag; import net.minecraft.nbt.FloatTag; import net.minecraft.nbt.IntArrayTag; import net.minecraft.nbt.IntTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.LongArrayTag; import net.minecraft.nbt.LongTag; import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; import net.minecraft.nbt.ShortTag; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; import net.minecraft.world.item.component.CustomData; public class NBTUtils extends NBTUtilsBase { public NBTUtils(Platform platform) { super(platform); } @Override public Object getTag(ItemStack stack, String tag) { if (platform.getItemUtils().isEmpty(stack)) return null; Object tagObject = platform.getItemUtils().getTag(stack); if (tagObject == null || !(tagObject instanceof CompoundTag)) return null; return ((CompoundTag)tagObject).get(tag); } @Override public Object getTag(Object nbtBase, String tag) { if (nbtBase == null || !(nbtBase instanceof CompoundTag)) return null; return ((CompoundTag)nbtBase).get(tag); } @Override public Set<String> getAllKeys(Object nbtBase) { if (nbtBase == null || !(nbtBase instanceof CompoundTag)) return null; return ((CompoundTag)nbtBase).getAllKeys(); } @Override public boolean contains(Object nbtBase, String tag) { if (nbtBase == null || !(nbtBase instanceof CompoundTag)) return false; return ((CompoundTag)nbtBase).contains(tag); } @Override public Object createTag(Object nbtBase, String tag) { if (nbtBase == null || !(nbtBase instanceof CompoundTag)) return null; CompoundTag compoundTag = (CompoundTag)nbtBase; CompoundTag meta = compoundTag.getCompound(tag); // Strangely getCompound always returns non-null, but the tag it returns // if not found in the parent is not connected to the parent. compoundTag.put(tag, meta); return meta; } @Override public Object createTag(ItemStack stack, String tag) { if (platform.getItemUtils().isEmpty(stack)) return null; Object outputObject = getTag(stack, tag); if (outputObject == null || !(outputObject instanceof CompoundTag)) { Object craft = platform.getItemUtils().getHandle(stack); if (craft == null) return null; CompoundTag tagObject = (CompoundTag)platform.getItemUtils().getTag(craft); if (tagObject == null) { tagObject = new CompoundTag(); // This makes a copy CustomData customData = CustomData.of(tagObject); tagObject = customData.getUnsafe(); ((net.minecraft.world.item.ItemStack)craft).set(DataComponents.CUSTOM_DATA, customData); } outputObject = new CompoundTag(); tagObject.put(tag, (CompoundTag)outputObject); } return outputObject; } @Override public byte[] getByteArray(Object tag, String key) { if (tag == null || !(tag instanceof CompoundTag)) return null; return ((CompoundTag)tag).getByteArray(key); } @Override public int[] getIntArray(Object tag, String key) { if (tag == null || !(tag instanceof CompoundTag)) return null; return ((CompoundTag)tag).getIntArray(key); } @Override public String getString(Object node, String tag) { if (node == null || !(node instanceof CompoundTag)) return null; return ((CompoundTag)node).getString(tag); } @Override public String getString(ItemStack stack, String tag) { if (platform.getItemUtils().isEmpty(stack)) return null; String meta = null; Object tagObject = platform.getItemUtils().getTag(stack); if (tagObject == null || !(tagObject instanceof CompoundTag)) return null; meta = ((CompoundTag)tagObject).getString(tag); return meta; } @Override public Byte getOptionalByte(Object node, String tag) { if (node == null || !(node instanceof CompoundTag)) return null; return ((CompoundTag)node).getByte(tag); } @Override public Integer getOptionalInt(Object node, String tag) { if (node == null || !(node instanceof CompoundTag)) return null; return ((CompoundTag)node).getInt(tag); } @Override public Short getOptionalShort(Object node, String tag) { if (node == null || !(node instanceof CompoundTag)) return null; return ((CompoundTag)node).getShort(tag); } @Override public Double getOptionalDouble(Object node, String tag) { if (node == null || !(node instanceof CompoundTag)) return null; return ((CompoundTag)node).getDouble(tag); } @Override public Boolean getOptionalBoolean(Object node, String tag) { if (node == null || !(node instanceof CompoundTag)) return null; return ((CompoundTag)node).getBoolean(tag); } @Override public void setLong(Object node, String tag, long value) { if (node == null || !(node instanceof CompoundTag)) return; ((CompoundTag)node).putLong(tag, value); } @Override public void setBoolean(Object node, String tag, boolean value) { if (node == null || !(node instanceof CompoundTag)) return; ((CompoundTag)node).putBoolean(tag, value); } @Override public void setDouble(Object node, String tag, double value) { if (node == null || !(node instanceof CompoundTag)) return; ((CompoundTag)node).putDouble(tag, value); } @Override public void setInt(Object node, String tag, int value) { if (node == null || !(node instanceof CompoundTag)) return; ((CompoundTag)node).putInt(tag, value); } @Override public void setMetaShort(Object node, String tag, short value) { if (node == null || !(node instanceof CompoundTag)) return; ((CompoundTag)node).putShort(tag, value); } @Override public void removeMeta(Object node, String tag) { if (node == null || !(node instanceof CompoundTag)) return; ((CompoundTag)node).remove(tag); } @Override public void setTag(Object node, String tag, Object child) { if (node == null || !(node instanceof CompoundTag)) return; if (child == null) { ((CompoundTag)node).remove(tag); } else if (child instanceof Tag) { ((CompoundTag)node).put(tag, (Tag)child); } } @Override public boolean setTag(ItemStack stack, String tag, Object child) { if (platform.getItemUtils().isEmpty(stack)) return false; Object craft = platform.getItemUtils().getHandle(stack); if (craft == null) return false; Object node = platform.getItemUtils().getOrCreateTag(craft); if (node == null || !(node instanceof CompoundTag)) return false; if (child == null) { ((CompoundTag)node).remove(tag); } else { ((CompoundTag)node).put(tag, (Tag)child); } return true; } @Override public void setString(Object node, String tag, String value) { if (node == null || !(node instanceof CompoundTag)) return; ((CompoundTag)node).putString(tag, value); } @Override public void setString(ItemStack stack, String tag, String value) { if (platform.getItemUtils().isEmpty(stack)) return; Object craft = platform.getItemUtils().getHandle(stack); if (craft == null) return; Object tagObject = platform.getItemUtils().getOrCreateTag(craft); if (tagObject == null || !(tagObject instanceof CompoundTag)) return; ((CompoundTag)tagObject).putString(tag, value); } @Override public void setIntArray(Object tag, String key, int[] value) { if (tag == null || !(tag instanceof CompoundTag)) return; ((CompoundTag)tag).put(key, new IntArrayTag(value)); } @Override public void setByteArray(Object tag, String key, byte[] value) { if (tag == null || !(tag instanceof CompoundTag)) return; ((CompoundTag)tag).put(key, new ByteArrayTag(value)); } @Override public void setEmptyList(Object tag, String key) { if (tag == null || !(tag instanceof CompoundTag)) return; ((CompoundTag)tag).put(key, new ListTag()); } @Override public void addToList(Object listObject, Object node) { if (listObject == null || !(listObject instanceof ListTag) || !(node instanceof Tag)) return; ListTag list = (ListTag)listObject; list.add((Tag)node); } @Override public Object readTagFromStream(InputStream input) { CompoundTag tag = null; try { tag = NbtIo.readCompressed(input, NbtAccounter.unlimitedHeap()); } catch (Exception ex) { platform.getLogger().log(Level.WARNING, "Error reading from NBT input stream", ex); } return tag; } @Override public boolean writeTagToStream(Object tag, OutputStream output) { if (tag == null || !(tag instanceof CompoundTag)) return false; try { NbtIo.writeCompressed((CompoundTag)tag, output); } catch (Exception ex) { platform.getLogger().log(Level.WARNING, "Error writing NBT output stream", ex); return false; } return true; } @Override public Collection<Object> getTagList(Object tag, String key) { Collection<Object> list = new ArrayList<>(); if (tag == null || !(tag instanceof CompoundTag)) { return list; } ListTag listTag = ((CompoundTag)tag).getList(key, CompatibilityConstants.NBT_TYPE_COMPOUND); if (listTag != null) { int size = listTag.size(); for (int i = 0; i < size; i++) { Tag entry = listTag.get(i); list.add(entry); } } return list; } @Override public Object newCompoundTag() { return new CompoundTag(); } @Override public boolean setSpawnEggEntityData(ItemStack spawnEgg, Entity entity, Object entityData) { if (platform.getItemUtils().isEmpty(spawnEgg)) return false; if (entityData == null || !(entityData instanceof CompoundTag)) return false; Object handle = platform.getItemUtils().getHandle(spawnEgg); if (handle == null) return false; net.minecraft.world.item.ItemStack itemStack = (net.minecraft.world.item.ItemStack)handle; CustomData customData = CustomData.of((CompoundTag)entityData); itemStack.set(DataComponents.ENTITY_DATA, customData); return true; } @Override public boolean addTagsToNBT(Map<String, Object> tags, Object node) { if (node == null) { platform.getLogger().warning("Trying to save tags to a null node"); return false; } if (!(node instanceof CompoundTag)) { platform.getLogger().warning("Trying to save tags to a non-CompoundTag"); return false; } CompoundTag compoundTag = (CompoundTag)node; for (Map.Entry<String, Object> tag : tags.entrySet()) { Object value = tag.getValue(); try { Tag wrappedTag = wrapInTag(value); if (wrappedTag == null) continue; compoundTag.put(tag.getKey(), wrappedTag); } catch (Exception ex) { platform.getLogger().log(Level.WARNING, "Error saving item data tag " + tag.getKey(), ex); } } return true; } @Override public boolean saveTagsToNBT(Map<String, Object> tags, Object node, Set<String> tagNames) { if (node == null) { platform.getLogger().warning("Trying to save tags to a null node"); return false; } if (!(node instanceof CompoundTag)) { platform.getLogger().warning("Trying to save tags to a non-CompoundTag"); return false; } CompoundTag compoundTag = (CompoundTag)node; if (tagNames == null) { tagNames = tags.keySet(); } // Remove tags that were not included Set<String> currentTags = getTagKeys(node); if (currentTags != null && !tagNames.containsAll(currentTags)) { // Need to copy this, getKeys returns a live list and bad things can happen. currentTags = new HashSet<>(currentTags); } else { currentTags = null; } for (String tagName : tagNames) { if (currentTags != null) currentTags.remove(tagName); Object value = tags.get(tagName); try { Tag wrappedTag = wrapInTag(value); if (wrappedTag == null) continue; compoundTag.put(tagName, wrappedTag); } catch (Exception ex) { platform.getLogger().log(Level.WARNING, "Error saving item data tag " + tagName, ex); } } // Finish removing any remaining properties if (currentTags != null) { for (String currentTag : currentTags) { platform.getNBTUtils().removeMeta(node, currentTag); } } return true; } @Override public Tag wrapInTag(Object value) { if (value == null) return null; Tag wrappedValue = null; if (value instanceof Boolean) { wrappedValue = ByteTag.valueOf((byte)((boolean)value ? 1 : 0)); } else if (value instanceof Double) { wrappedValue = DoubleTag.valueOf((Double)value); } else if (value instanceof Float) { wrappedValue = FloatTag.valueOf((Float) value); } else if (value instanceof Integer) { wrappedValue = IntTag.valueOf((Integer)value); } else if (value instanceof Long) { wrappedValue = LongTag.valueOf((Long) value); } else if (value instanceof ConfigurationSection) { wrappedValue = new CompoundTag(); saveTagsToNBT((ConfigurationSection)value, wrappedValue, null); } else if (value instanceof Map) { wrappedValue = new CompoundTag(); @SuppressWarnings("unchecked") Map<String, Object> valueMap = (Map<String, Object>)value; addTagsToNBT(valueMap, wrappedValue); } else if (value instanceof Collection) { @SuppressWarnings("unchecked") Collection<Object> list = (Collection<Object>)value; ListTag listMeta = new ListTag(); if (list.size() > 1 && list instanceof List) { @SuppressWarnings("unchecked") List<Object> checkList = (List<Object>)value; Object first = checkList.get(0); Object second = checkList.get(1); if (first instanceof String && !(second instanceof String)) { list = new ArrayList<>(); for (int i = 1; i < checkList.size(); i++) { if (first.equals("I")) { list.add(convertToInteger(checkList.get(i))); } else if (first.equals("L")) { list.add(convertToLong(checkList.get(i))); } else if (first.equals("B")) { list.add(convertToByte(checkList.get(i))); } else { list.add(checkList.get(i)); } } if (first.equals("B")) { wrappedValue = new ByteArrayTag(makeByteArray((List<Object>)list)); } else if (first.equals("I")) { wrappedValue = new IntArrayTag(makeIntArray((List<Object>)list)); } else if (first.equals("L")) { wrappedValue = new LongArrayTag(makeLongArray((List<Object>)list)); } } } if (wrappedValue == null) { for (Object item : list) { if (item != null) { platform.getNBTUtils().addToList(listMeta, wrapInTag(item)); } } wrappedValue = listMeta; } } else { wrappedValue = StringTag.valueOf(value.toString()); } return wrappedValue; } @Override public Set<String> getTagKeys(Object tag) { if (tag == null || !(tag instanceof CompoundTag)) { return null; } return ((CompoundTag)tag).getAllKeys(); } @Override public Object getMetaObject(Object tag, String key) { if (tag == null || !(tag instanceof CompoundTag)) { return null; } try { Tag metaBase = ((CompoundTag)tag).get(key); return getTagValue(metaBase); } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override public Object getTagValue(Object tag) throws IllegalAccessException, InvocationTargetException { if (tag == null) return null; Object value; if (tag instanceof DoubleTag) { value = ((DoubleTag)tag).getAsDouble(); } else if (tag instanceof IntTag) { value = ((IntTag)tag).getAsInt(); } else if (tag instanceof LongTag) { value = ((LongTag)tag).getAsLong(); } else if (tag instanceof FloatTag) { value = ((FloatTag)tag).getAsFloat(); } else if (tag instanceof ShortTag) { value = ((ShortTag)tag).getAsShort(); } else if (tag instanceof ByteTag) { // This is kind of nasty. Really need a type-juggling container class for config properties. value = ((ByteTag)tag).getAsByte(); if (value.equals((byte)0)) { value = false; } else if (value.equals((byte)1)) { value = true; } } else if (tag instanceof ListTag) { List<Object> converted = new ArrayList<>(); for (Tag baseTag : (ListTag)tag) { Object convertedBase = getTagValue(baseTag); if (convertedBase != null) { converted.add(convertedBase); } } value = converted; } else if (tag instanceof StringTag) { value = ((StringTag)tag).getAsString(); } else if (tag instanceof IntArrayTag) { value = ((IntArrayTag)tag).getAsIntArray(); } else if (tag instanceof ByteArrayTag) { value = ((ByteArrayTag)tag).getAsByteArray(); } else if (tag instanceof LongArrayTag) { value = ((LongArrayTag)tag).getAsLongArray(); } else if (tag instanceof CompoundTag) { Map<String, Object> compoundMap = new HashMap<>(); Set<String> keys = getTagKeys(tag); for (String key : keys) { Tag baseTag = ((CompoundTag)tag).get(key); Object convertedBase = getTagValue(baseTag); if (convertedBase != null) { compoundMap.put(key, convertedBase); } } value = compoundMap; } else { value = null; // ??? } return value; } }
412
0.877593
1
0.877593
game-dev
MEDIA
0.997266
game-dev
0.885856
1
0.885856
google-deepmind/meltingpot
10,251
meltingpot/utils/substrates/game_object_utils_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for game_object_utils.""" from absl.testing import absltest from absl.testing import parameterized from meltingpot.utils.substrates import game_object_utils def get_transform(x, y, orientation): return game_object_utils.Transform(position=game_object_utils.Position(x, y), orientation=orientation) class ParseMapTest(parameterized.TestCase): @parameterized.parameters( ('\nHello', 'H', 1), ('\nHello', 'h', 0), ('\nHello', 'l', 2), ('\nHello\nWorld', 'l', 3), ('\nHello\nWorld', 'o', 2), ('\nHello\nWorld', 'd', 1), ('\nHello\nWorld', 'W', 1), ('\nWWWW\nW AW\nWWWW', 'A', 1), ('\nWWWW\nW AW\nWWWW', 'W', 10), ('\nWWWW\nW AW\nWWWW', 'P', 0), ) def test_get_positions_length(self, ascii_map, char, exp_len): transforms = game_object_utils.get_game_object_positions_from_map( ascii_map, char) self.assertLen(transforms, exp_len) def test_get_positions(self): # Locations of 'A' -> (2, 1) # Locations of ' ' -> (1, 1), (3, 1) and (4, 1) ascii_map = ''' WWWWWW W A W WWWWWW ''' transforms = game_object_utils.get_game_object_positions_from_map( ascii_map, 'A') self.assertSameElements( [get_transform(2, 1, game_object_utils.Orientation.NORTH)], transforms) transforms = game_object_utils.get_game_object_positions_from_map( ascii_map, ' ') self.assertSameElements( [ get_transform(1, 1, game_object_utils.Orientation.NORTH), get_transform(3, 1, game_object_utils.Orientation.NORTH), get_transform(4, 1, game_object_utils.Orientation.NORTH) ], transforms) transforms = game_object_utils.get_game_object_positions_from_map( ascii_map, 'W') self.assertSameElements( [ # Top walls get_transform(0, 0, game_object_utils.Orientation.NORTH), get_transform(1, 0, game_object_utils.Orientation.NORTH), get_transform(2, 0, game_object_utils.Orientation.NORTH), get_transform(3, 0, game_object_utils.Orientation.NORTH), get_transform(4, 0, game_object_utils.Orientation.NORTH), get_transform(5, 0, game_object_utils.Orientation.NORTH), # Side walls get_transform(0, 1, game_object_utils.Orientation.NORTH), get_transform(5, 1, game_object_utils.Orientation.NORTH), # Bottom walls get_transform(0, 2, game_object_utils.Orientation.NORTH), get_transform(1, 2, game_object_utils.Orientation.NORTH), get_transform(2, 2, game_object_utils.Orientation.NORTH), get_transform(3, 2, game_object_utils.Orientation.NORTH), get_transform(4, 2, game_object_utils.Orientation.NORTH), get_transform(5, 2, game_object_utils.Orientation.NORTH), ], transforms) def test_get_game_objects(self): ascii_map = ''' WWWWWW W A W WWWWWW ''' wall = { 'name': 'wall', 'components': [ { 'component': 'PieceTypeManager', 'kwargs': { 'initialPieceType': 'wall', 'pieceTypeConfigs': [{'pieceType': 'wall',}], }, }, { 'component': 'Transform', 'kwargs': { 'position': (0, 0), 'orientation': 'N' }, }, ] } apple = { 'name': 'apple', 'components': [ { 'component': 'PieceTypeManager', 'kwargs': { 'initialPieceType': 'apple', 'pieceTypeConfigs': [{'pieceType': 'apple',}], }, }, { 'component': 'Transform', 'kwargs': { 'position': (0, 0), 'orientation': 'N' }, }, ] } prefabs = {'wall': wall, 'apple': apple} game_objects = game_object_utils.get_game_objects_from_map( ascii_map, {'W': 'wall', 'A': 'apple'}, prefabs) self.assertLen(game_objects, 15) self.assertEqual( 1, sum([1 if go['name'] == 'apple' else 0 for go in game_objects])) self.assertEqual( 14, sum([1 if go['name'] == 'wall' else 0 for go in game_objects])) positions = [] for go in game_objects: if go['name'] == 'wall': positions.append(game_object_utils.get_first_named_component( go, 'Transform')['kwargs']['position']) self.assertSameElements( [ (0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), # Top walls (0, 1), (5, 1), # Side walls (0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), # Bottom walls ], positions) AVATAR = { 'name': 'avatar', 'components': [ { 'component': 'StateManager', 'kwargs': { 'initialState': 'player', 'stateConfigs': [ {'state': 'player', 'layer': 'upperPhysical', 'sprite': 'Avatar',}, # Will be overridden {'state': 'playerWait',}, ] } }, { 'component': 'Transform', 'kwargs': { 'position': (0, 0), 'orientation': 'N' } }, { 'component': 'Appearance', 'kwargs': { 'renderMode': 'ascii_shape', 'spriteNames': ['Avatar'], # Will be overridden 'spriteShapes': ["""*"""], 'palettes': [(0, 0, 255, 255)], # Will be overridden 'noRotates': [True] } }, { 'component': 'Avatar', 'kwargs': { 'index': -1, # Will be overridden 'spawnGroup': 'spawnPoints', 'aliveState': 'player', 'waitState': 'playerWait', 'actionOrder': ['move'], 'actionSpec': { 'move': {'default': 0, 'min': 0, 'max': 4}, }, } }, ], } BADGE = { 'name': 'avatar_badge', 'components': [ { 'component': 'StateManager', 'kwargs': { 'initialState': 'badgeWait', 'stateConfigs': [ {'state': 'badge', 'layer': 'overlay', 'sprite': 'Badge', 'groups': ['badges']}, {'state': 'badgeWait', 'groups': ['badgeWaits']}, ] } }, { 'component': 'Transform', 'kwargs': { 'position': (0, 0), 'orientation': 'N' } }, { 'component': 'Appearance', 'kwargs': { 'renderMode': 'ascii_shape', 'spriteNames': ['Badge'], 'spriteShapes': ['*'], 'palettes': [(0, 0, 255, 255)], 'noRotates': [False] } }, { 'component': 'AvatarConnector', 'kwargs': { 'playerIndex': -1, # player index to be overwritten. 'aliveState': 'badge', 'waitState': 'badgeWait' } }, ] } class BuildAvatarObjectsTest(parameterized.TestCase): @parameterized.parameters( [1], [2], [3], [4], [5] ) def test_simple_build(self, num_players): prefabs = {'avatar': AVATAR} avatars = game_object_utils.build_avatar_objects( num_players=num_players, prefabs=prefabs, player_palettes=None, ) self.assertLen(avatars, num_players) def test_with_palette_build(self): palettes = [(255, 0, 0, 255), (0, 255, 0, 255)] prefabs = {'avatar': AVATAR} avatars = game_object_utils.build_avatar_objects( num_players=2, prefabs=prefabs, player_palettes=palettes, ) self.assertLen(avatars, 2) self.assertEqual( game_object_utils.get_first_named_component( avatars[0], 'Appearance')['kwargs']['palettes'][0], palettes[0]) self.assertEqual( game_object_utils.get_first_named_component( avatars[1], 'Appearance')['kwargs']['palettes'][0], palettes[1]) class BuildAvatarBadgesTest(parameterized.TestCase): @parameterized.parameters( [1], [2], [3], [4], [5] ) def test_simple_build(self, num_players): prefabs = {'avatar_badge': BADGE} badges = game_object_utils.build_avatar_badges( num_players=num_players, prefabs=prefabs, badge_palettes=None, ) self.assertLen(badges, num_players) def test_with_palette_build(self): palettes = [(255, 0, 0, 255), (0, 255, 0, 255)] prefabs = {'avatar_badge': BADGE} badges = game_object_utils.build_avatar_badges( num_players=2, prefabs=prefabs, badge_palettes=palettes, ) self.assertLen(badges, 2) self.assertEqual( game_object_utils.get_first_named_component( badges[0], 'Appearance')['kwargs']['palettes'][0], palettes[0]) self.assertEqual( game_object_utils.get_first_named_component( badges[1], 'Appearance')['kwargs']['palettes'][0], palettes[1]) if __name__ == '__main__': absltest.main()
412
0.671807
1
0.671807
game-dev
MEDIA
0.692633
game-dev,graphics-rendering
0.553065
1
0.553065
RakambdaOrg/FallingTree
2,051
forge/src/main/java/fr/rakambda/fallingtree/forge/common/wrapper/BlockStateWrapper.java
package fr.rakambda.fallingtree.forge.common.wrapper; import fr.rakambda.fallingtree.common.wrapper.IBlock; import fr.rakambda.fallingtree.common.wrapper.IBlockPos; import fr.rakambda.fallingtree.common.wrapper.IBlockState; import fr.rakambda.fallingtree.common.wrapper.ILevel; import fr.rakambda.fallingtree.common.wrapper.IRandomSource; import fr.rakambda.fallingtree.common.wrapper.IServerLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.LeavesBlock; import net.minecraft.world.level.block.state.BlockState; import org.jspecify.annotations.NonNull; import java.util.Optional; @RequiredArgsConstructor @ToString public class BlockStateWrapper implements IBlockState{ @NonNull @Getter private final BlockState raw; @Override public void tick(@NonNull IServerLevel level, @NonNull IBlockPos blockPos, @NonNull IRandomSource random){ var l = (ServerLevel) level.getRaw(); var bp = (BlockPos) blockPos.getRaw(); raw.tick(l, bp, (RandomSource) random.getRaw()); //tick } @Override public void randomTick(@NonNull IServerLevel level, @NonNull IBlockPos blockPos, @NonNull IRandomSource random){ var l = (ServerLevel) level.getRaw(); var bp = (BlockPos) blockPos.getRaw(); raw.randomTick(l, bp, (RandomSource) random.getRaw()); //randomTick } @Override @NonNull public IBlock getBlock(){ return new BlockWrapper(raw.getBlock()); } @Override public boolean isRandomlyTicking(){ return raw.isRandomlyTicking(); } @Override @NonNull public Optional<Boolean> hasLeafPersistentFlag(){ return raw.getOptionalValue(LeavesBlock.PERSISTENT); } @Override public void dropResources(@NonNull ILevel level, @NonNull IBlockPos blockPos){ Block.dropResources(raw, (Level) level.getRaw(), (BlockPos) blockPos.getRaw()); } }
412
0.624284
1
0.624284
game-dev
MEDIA
0.990682
game-dev
0.864648
1
0.864648
corporateshark/Mastering-Android-NDK
10,947
Chapter9/2_UIPages/jni/SDL/src/dynapi/SDL_dynapi.c
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL_config.h" #include "SDL_dynapi.h" #if SDL_DYNAMIC_API #include "SDL.h" /* !!! FIXME: Shouldn't these be included in SDL.h? */ #include "SDL_shape.h" #include "SDL_syswm.h" /* This is the version of the dynamic API. This doesn't match the SDL version and should not change until there's been a major revamp in API/ABI. So 2.0.5 adds functions over 2.0.4? This number doesn't change; the sizeof (jump_table) changes instead. But 2.1.0 changes how a function works in an incompatible way or removes a function? This number changes, since sizeof (jump_table) isn't sufficient anymore. It's likely we'll forget to bump every time we add a function, so this is the failsafe switch for major API change decisions. Respect it and use it sparingly. */ #define SDL_DYNAPI_VERSION 1 static void SDL_InitDynamicAPI(void); /* BE CAREFUL CALLING ANY SDL CODE IN HERE, IT WILL BLOW UP. Even self-contained stuff might call SDL_Error and break everything. */ /* behold, the macro salsa! */ /* !!! FIXME: ...disabled...until we write it. :) */ #define DISABLE_JUMP_MAGIC 1 #if DISABLE_JUMP_MAGIC /* Can't use the macro for varargs nonsense. This is atrocious. */ #define SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, logname, prio) \ _static void SDL_Log##logname##name(int category, const char *fmt, ...) { \ va_list ap; initcall; va_start(ap, fmt); \ jump_table.SDL_LogMessageV(category, SDL_LOG_PRIORITY_##prio, fmt, ap); \ va_end(ap); \ } #define SDL_DYNAPI_VARARGS(_static, name, initcall) \ _static int SDL_SetError##name(const char *fmt, ...) { \ char buf[512]; /* !!! FIXME: dynamic allocation */ \ va_list ap; initcall; va_start(ap, fmt); \ jump_table.SDL_vsnprintf(buf, sizeof (buf), fmt, ap); \ va_end(ap); \ return jump_table.SDL_SetError("%s", buf); \ } \ _static int SDL_sscanf##name(const char *buf, const char *fmt, ...) { \ int retval; va_list ap; initcall; va_start(ap, fmt); \ retval = jump_table.SDL_vsscanf(buf, fmt, ap); \ va_end(ap); \ return retval; \ } \ _static int SDL_snprintf##name(char *buf, size_t buflen, const char *fmt, ...) { \ int retval; va_list ap; initcall; va_start(ap, fmt); \ retval = jump_table.SDL_vsnprintf(buf, buflen, fmt, ap); \ va_end(ap); \ return retval; \ } \ _static void SDL_Log##name(const char *fmt, ...) { \ va_list ap; initcall; va_start(ap, fmt); \ jump_table.SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); \ va_end(ap); \ } \ _static void SDL_LogMessage##name(int category, SDL_LogPriority priority, const char *fmt, ...) { \ va_list ap; initcall; va_start(ap, fmt); \ jump_table.SDL_LogMessageV(category, priority, fmt, ap); \ va_end(ap); \ } \ SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Verbose, VERBOSE) \ SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Debug, DEBUG) \ SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Info, INFO) \ SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Warn, WARN) \ SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Error, ERROR) \ SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Critical, CRITICAL) #endif /* Typedefs for function pointers for jump table, and predeclare funcs */ /* The DEFAULT funcs will init jump table and then call real function. */ /* The REAL funcs are the actual functions, name-mangled to not clash. */ #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \ typedef rc (*SDL_DYNAPIFN_##fn) params; \ static rc fn##_DEFAULT params; \ extern rc fn##_REAL params; #include "SDL_dynapi_procs.h" #undef SDL_DYNAPI_PROC /* The jump table! */ typedef struct { #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) SDL_DYNAPIFN_##fn fn; #include "SDL_dynapi_procs.h" #undef SDL_DYNAPI_PROC } SDL_DYNAPI_jump_table; /* Predeclare the default functions for initializing the jump table. */ #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) static rc fn##_DEFAULT params; #include "SDL_dynapi_procs.h" #undef SDL_DYNAPI_PROC /* The actual jump table. */ static SDL_DYNAPI_jump_table jump_table = { #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) fn##_DEFAULT, #include "SDL_dynapi_procs.h" #undef SDL_DYNAPI_PROC }; /* Default functions init the function table then call right thing. */ #if DISABLE_JUMP_MAGIC #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \ static rc fn##_DEFAULT params { \ SDL_InitDynamicAPI(); \ ret jump_table.fn args; \ } #define SDL_DYNAPI_PROC_NO_VARARGS 1 #include "SDL_dynapi_procs.h" #undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC_NO_VARARGS SDL_DYNAPI_VARARGS(static, _DEFAULT, SDL_InitDynamicAPI()) #else /* !!! FIXME: need the jump magic. */ #error Write me. #endif /* Public API functions to jump into the jump table. */ #if DISABLE_JUMP_MAGIC #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \ rc fn params { ret jump_table.fn args; } #define SDL_DYNAPI_PROC_NO_VARARGS 1 #include "SDL_dynapi_procs.h" #undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC_NO_VARARGS SDL_DYNAPI_VARARGS(,,) #else /* !!! FIXME: need the jump magic. */ #error Write me. #endif /* Here's the exported entry point that fills in the jump table. */ /* Use specific types when an "int" might suffice to keep this sane. */ typedef Sint32 (SDLCALL *SDL_DYNAPI_ENTRYFN)(Uint32 apiver, void *table, Uint32 tablesize); extern DECLSPEC Sint32 SDLCALL SDL_DYNAPI_entry(Uint32, void *, Uint32); Sint32 SDL_DYNAPI_entry(Uint32 apiver, void *table, Uint32 tablesize) { SDL_DYNAPI_jump_table *output_jump_table = (SDL_DYNAPI_jump_table *) table; if (apiver != SDL_DYNAPI_VERSION) { /* !!! FIXME: can maybe handle older versions? */ return -1; /* not compatible. */ } else if (tablesize > sizeof (jump_table)) { return -1; /* newer version of SDL with functions we can't provide. */ } /* Init our jump table first. */ #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) jump_table.fn = fn##_REAL; #include "SDL_dynapi_procs.h" #undef SDL_DYNAPI_PROC /* Then the external table... */ if (output_jump_table != &jump_table) { jump_table.SDL_memcpy(output_jump_table, &jump_table, tablesize); } /* Safe to call SDL functions now; jump table is initialized! */ return 0; /* success! */ } /* Obviously we can't use SDL_LoadObject() to load SDL. :) */ /* Also obviously, we never close the loaded library. */ #if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include <windows.h> static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym) { HANDLE lib = LoadLibraryA(fname); return lib ? GetProcAddress(lib, sym) : NULL; } #elif defined(__HAIKU__) #include <os/kernel/image.h> static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym) { image_id lib = load_add_on(fname); void *retval = NULL; if ((lib < 0) || (get_image_symbol(lib, sym, B_SYMBOL_TYPE_TEXT, &retval) != B_NO_ERROR)) { retval = NULL; } return retval; } #elif defined(unix) || defined(__unix__) || defined(__APPLE__) #include <dlfcn.h> static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym) { void *lib = dlopen(fname, RTLD_NOW | RTLD_LOCAL); return lib ? dlsym(lib, sym) : NULL; } #else #error Please define your platform. #endif static void SDL_InitDynamicAPILocked(void) { const char *libname = SDL_getenv_REAL("SDL_DYNAMIC_API"); SDL_DYNAPI_ENTRYFN entry = SDL_DYNAPI_entry; /* funcs from here by default. */ if (libname) { entry = (SDL_DYNAPI_ENTRYFN) get_sdlapi_entry(libname, "SDL_DYNAPI_entry"); if (!entry) { /* !!! FIXME: fail to startup here instead? */ /* !!! FIXME: definitely warn user. */ /* Just fill in the function pointers from this library. */ entry = SDL_DYNAPI_entry; } } if (entry(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table)) < 0) { /* !!! FIXME: fail to startup here instead? */ /* !!! FIXME: definitely warn user. */ /* Just fill in the function pointers from this library. */ if (entry != SDL_DYNAPI_entry) { if (!SDL_DYNAPI_entry(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table))) { /* !!! FIXME: now we're screwed. Should definitely abort now. */ } } } /* we intentionally never close the newly-loaded lib, of course. */ } static void SDL_InitDynamicAPI(void) { /* So the theory is that every function in the jump table defaults to * calling this function, and then replaces itself with a version that * doesn't call this function anymore. But it's possible that, in an * extreme corner case, you can have a second thread hit this function * while the jump table is being initialized by the first. * In this case, a spinlock is really painful compared to what spinlocks * _should_ be used for, but this would only happen once, and should be * insanely rare, as you would have to spin a thread outside of SDL (as * SDL_CreateThread() would also call this function before building the * new thread). */ static volatile SDL_bool already_initialized = SDL_FALSE; /* SDL_AtomicLock calls SDL mutex functions to emulate if SDL_ATOMIC_DISABLED, which we can't do here, so in such a configuration, you're on your own. */ #if !SDL_ATOMIC_DISABLED static SDL_SpinLock lock = 0; SDL_AtomicLock_REAL(&lock); #endif if (!already_initialized) { SDL_InitDynamicAPILocked(); already_initialized = SDL_TRUE; } #if !SDL_ATOMIC_DISABLED SDL_AtomicUnlock_REAL(&lock); #endif } #endif /* SDL_DYNAMIC_API */ /* vi: set ts=4 sw=4 expandtab: */
412
0.913871
1
0.913871
game-dev
MEDIA
0.522154
game-dev
0.913479
1
0.913479