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
richemslie/galvanise_zero
1,587
src/cpp/player.h
#pragma once #include "events.h" #include "scheduler.h" #include "gdltransformer.h" #include <statemachine/basestate.h> #include <statemachine/jointmove.h> #include <statemachine/statemachine.h> namespace GGPZero { // forwards class PuctEvaluator; struct PuctConfig; struct PuctNodeChild; struct PuctNodeDebug; // this is a bit of hack, wasnt really designed to actually play from c++ class Player { public: Player(GGPLib::StateMachineInterface* sm, const GGPZero::GdlBasesTransformer* transformer, PuctConfig* conf); ~Player(); public: // python side void updateConfig(float think_time, int converge_relaxed, bool verbose); void puctPlayerReset(int game_depth); void puctApplyMove(const GGPLib::JointMove* move); void puctPlayerMove(const GGPLib::BaseState* state, int iterations, double end_time); std::tuple <int, float, int> puctPlayerGetMove(int lead_role_index); void balanceNode(int max_count); std::vector <PuctNodeDebug> treeDebugInfo(int max_count); const ReadyEvent* poll(int predict_count, std::vector <float*>& data); private: const GdlBasesTransformer* transformer; PuctConfig* config; PuctEvaluator* evaluator; NetworkScheduler* scheduler; bool first_play; // store the choice of onNextMove()... const PuctNodeChild* on_next_move_choice; // Events ReadyEvent ready_event; PredictDoneEvent predict_done_event; }; }
411
0.912488
1
0.912488
game-dev
MEDIA
0.444138
game-dev
0.720353
1
0.720353
GGgRain/Unreal-Joint
4,851
Source/Joint/Private/SubSystem/JointSubsystem.cpp
//Copyright 2022~2024 DevGrain. All Rights Reserved. #include "SubSystem/JointSubsystem.h" #include "JointActor.h" #include "JointManager.h" #include "Runtime/Launch/Resources/Version.h" #include "Engine/Blueprint.h" #include "UObject/UObjectIterator.h" #include "Engine/GameInstance.h" #include "EngineUtils.h" #include "TimerManager.h" AJointActor* UJointSubsystem::CreateJoint( UObject* WorldContextObject, UJointManager* JointAssetToPlay, TSubclassOf<AJointActor> OptionalJointInstanceSubclass) { if (!WorldContextObject || !WorldContextObject->GetWorld() || JointAssetToPlay == nullptr || !JointAssetToPlay->IsValidLowLevel()) return nullptr; if(AJointActor* JointActor = WorldContextObject->GetWorld()->SpawnActor<AJointActor>(OptionalJointInstanceSubclass.Get() ? OptionalJointInstanceSubclass.Get() : AJointActor::StaticClass())) { JointActor->RequestSetJointManager(JointAssetToPlay); return JointActor; } return nullptr; } AJointActor* UJointSubsystem::FindJoint(UObject* WorldContextObject, FGuid JointGuid) { if (WorldContextObject != nullptr && WorldContextObject->GetWorld()) { for (TActorIterator<AJointActor> ActorItr(WorldContextObject->GetWorld()); ActorItr; ++ActorItr) { if (!(*ActorItr)->IsValidLowLevel()) { continue; } if ((*ActorItr)->JointGuid == JointGuid) return *ActorItr; } } return nullptr; } TArray<class AJointActor*> UJointSubsystem::GetAllJoints(UObject* WorldContextObject) { TArray<AJointActor*> Array; if (WorldContextObject != nullptr && WorldContextObject->GetWorld()) { for (TActorIterator<AJointActor> ActorItr(WorldContextObject->GetWorld()); ActorItr; ++ActorItr) { if (!(*ActorItr)->IsValidLowLevel()) { continue; } Array.Add(*ActorItr); } } return Array; } UJointSubsystem* UJointSubsystem::Get(UObject* WorldContextObject) { if (WorldContextObject != nullptr) if (UWorld* WorldRef = WorldContextObject->GetWorld()) if (UGameInstance* GI = WorldRef->GetGameInstance()) if (UJointSubsystem* SS = GI->GetSubsystem<UJointSubsystem>()) return SS; return nullptr; } TArray<FGuid> UJointSubsystem::GetJointsGuidStartedOnThisFrame(UObject* WorldContextObject) { if (UJointSubsystem* Subsystem = Get(WorldContextObject)){ return Subsystem->CachedJointBeginOnFrame; } TArray<FGuid> Array; return Array; } TArray<FGuid> UJointSubsystem::GetJointsGuidEndedOnThisFrame(UObject* WorldContextObject) { if (UJointSubsystem* Subsystem = Get(WorldContextObject)){ return Subsystem->CachedJointEndOnFrame; } TArray<FGuid> Array; return Array; } void UJointSubsystem::OnJointStarted(AJointActor* Actor) { if (Actor == nullptr && !Actor->IsValidLowLevel()) return; AddStartedJointToCaches(Actor); BroadcastOnJointStarted(Actor, Actor->JointGuid); RequestFrameCachesClearOnNextFrame(); CachedTime = GetWorld()->GetTimeSeconds(); } void UJointSubsystem::OnJointEnded(AJointActor* Actor) { if (Actor == nullptr && !Actor->IsValidLowLevel()) return; AddEndedJointToCaches(Actor); BroadcastOnJointEnded(Actor, Actor->JointGuid); RequestFrameCachesClearOnNextFrame(); CachedTime = GetWorld()->GetTimeSeconds(); } void UJointSubsystem::AddStartedJointToCaches(AJointActor* Actor) { if (GetWorld() == nullptr) return; //Clear cache immediately since we see the cache has been stored in the previous frame. if (CachedTime != GetWorld()->GetTimeSeconds()) ClearCachedJointFrameData(); if (Actor == nullptr) return; CachedJointBeginOnFrame.Add(Actor->JointGuid); CachedTime = GetWorld()->GetTimeSeconds(); } void UJointSubsystem::AddEndedJointToCaches(AJointActor* Actor) { if (GetWorld() == nullptr) return; //Clear cache immediately since we see the cache has been stored in the previous frame. if (CachedTime != GetWorld()->GetTimeSeconds()) ClearCachedJointFrameData(); if (Actor == nullptr) return; CachedJointEndOnFrame.Add(Actor->JointGuid); CachedTime = GetWorld()->GetTimeSeconds(); } void UJointSubsystem::RequestFrameCachesClearOnNextFrame() { if (bCacheClearRequested) return; GetWorld()->GetTimerManager().SetTimerForNextTick([this]() { this->ClearCachedJointFrameData(); }); bCacheClearRequested = true; } void UJointSubsystem::ClearCachedJointFrameData() { if (!CachedJointBeginOnFrame.IsEmpty()) CachedJointBeginOnFrame.Empty(); if (!CachedJointEndOnFrame.IsEmpty()) CachedJointEndOnFrame.Empty(); bCacheClearRequested = false; } void UJointSubsystem::BroadcastOnJointStarted(AJointActor* Actor, FGuid JointGuid) { if (OnJointBeginDelegate.IsBound()) OnJointBeginDelegate.Broadcast(Actor, JointGuid); } void UJointSubsystem::BroadcastOnJointEnded(AJointActor* Actor, FGuid JointGuid) { if (OnJointEndDelegate.IsBound()) OnJointEndDelegate.Broadcast(Actor, JointGuid); } UWorld* UJointSubsystem::GetWorld() const { return GetGameInstance()->GetWorld(); }
411
0.607613
1
0.607613
game-dev
MEDIA
0.800798
game-dev
0.747485
1
0.747485
cloudhu/ChineseChessVR
1,044
Assets/VRTK/Examples/Resources/Scripts/RealGun_SafetySwitch.cs
namespace VRTK.Examples { using UnityEngine; public class RealGun_SafetySwitch : VRTK_InteractableObject { public bool safetyOff = true; private float offAngle = 40f; private Vector3 fixedPosition; public override void StartUsing(GameObject currentUsingObject) { base.StartUsing(currentUsingObject); SetSafety(!safetyOff); } protected void Start() { fixedPosition = transform.localPosition; SetSafety(safetyOff); } protected override void Update() { base.Update(); transform.localPosition = fixedPosition; if (safetyOff) { transform.localEulerAngles = new Vector3(0f, 0f, 0f); } else { transform.localEulerAngles = new Vector3(0f, offAngle, 0f); } } private void SetSafety(bool safety) { safetyOff = safety; } } }
411
0.738782
1
0.738782
game-dev
MEDIA
0.992652
game-dev
0.651227
1
0.651227
nasa/europa
1,686
examples/Rover/java/Rover/Main.java
package Rover; import psengine.PSEngine; import psengine.PSUtil; import psengine.util.LibraryLoader; import org.ops.ui.main.swing.PSDesktop; import bsh.Interpreter; class Main { protected static PSEngine psEngine_; public static void main(String args[]) { String debugMode = args[0]; PSUtil.loadLibraries(debugMode); psEngine_ = PSEngine.makeInstance(); psEngine_.start(); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); loadCustomCode(debugMode); if(args.length > 2 && args[2].equals("nogui")) { Interpreter bshInterpreter_ = new bsh.Interpreter(); try { bshInterpreter_.set("psengine", psEngine_); bshInterpreter_.eval("source(\""+args[1]+"\");"); } catch (Exception e) { throw new RuntimeException(e); } } else { PSDesktop d = PSDesktop.makeInstance(psEngine_,args); d.runUI(); } } protected static void loadCustomCode(String debugMode) { //Load module with any custom code if it exists: String libName = "Rover_" + debugMode; String fullLibName = LibraryLoader.getResolvedName(libName); if(fullLibName == null) { // Run 'make' to compile the library if you need it: System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); } else { // WARNING: Shared library loaded twice (see ticket #164) System.load(fullLibName); psEngine_.loadModule(fullLibName); } } static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } public void run() { psEngine_.shutdown(); } } }
411
0.782517
1
0.782517
game-dev
MEDIA
0.420831
game-dev,cli-devtools
0.909732
1
0.909732
Arkania/ArkCORE-NG
4,817
src/server/collision/VMapTools.h
/* * Copyright (C) 2011-2016 ArkCORE <http://www.arkania.net/> * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _VMAPTOOLS_H #define _VMAPTOOLS_H #include <G3D/CollisionDetection.h> #include <G3D/AABox.h> #include "NodeValueAccess.h" /** The Class is mainly taken from G3D/AABSPTree.h but modified to be able to use our internal data structure. This is an iterator that helps us analysing the BSP-Trees. The collision detection is modified to return true, if we are inside an object. */ namespace VMAP { template<class TValue> class IntersectionCallBack { public: TValue* closestEntity; G3D::Vector3 hitLocation; G3D::Vector3 hitNormal; void operator()(const G3D::Ray& ray, const TValue* entity, bool pStopAtFirstHit, float& distance) { entity->intersect(ray, distance, pStopAtFirstHit, hitLocation, hitNormal); } }; //============================================================== //============================================================== //============================================================== class MyCollisionDetection { private: public: static bool collisionLocationForMovingPointFixedAABox( const G3D::Vector3& origin, const G3D::Vector3& dir, const G3D::AABox& box, G3D::Vector3& location, bool& Inside) { // Integer representation of a floating-point value. #define IR(x) (reinterpret_cast<G3D::uint32 const&>(x)) Inside = true; const G3D::Vector3& MinB = box.low(); const G3D::Vector3& MaxB = box.high(); G3D::Vector3 MaxT(-1.0f, -1.0f, -1.0f); // Find candidate planes. for (int i = 0; i < 3; ++i) { if (origin[i] < MinB[i]) { location[i] = MinB[i]; Inside = false; // Calculate T distances to candidate planes if (IR(dir[i])) { MaxT[i] = (MinB[i] - origin[i]) / dir[i]; } } else if (origin[i] > MaxB[i]) { location[i] = MaxB[i]; Inside = false; // Calculate T distances to candidate planes if (IR(dir[i])) { MaxT[i] = (MaxB[i] - origin[i]) / dir[i]; } } } if (Inside) { // definite hit location = origin; return true; } // Get largest of the maxT's for final choice of intersection int WhichPlane = 0; if (MaxT[1] > MaxT[WhichPlane]) { WhichPlane = 1; } if (MaxT[2] > MaxT[WhichPlane]) { WhichPlane = 2; } // Check final candidate actually inside box if (IR(MaxT[WhichPlane]) & 0x80000000) { // Miss the box return false; } for (int i = 0; i < 3; ++i) { if (i != WhichPlane) { location[i] = origin[i] + MaxT[WhichPlane] * dir[i]; if ((location[i] < MinB[i]) || (location[i] > MaxB[i])) { // On this plane we're outside the box extents, so // we miss the box return false; } } } /* // Choose the normal to be the plane normal facing into the ray normal = G3D::Vector3::zero(); normal[WhichPlane] = (dir[WhichPlane] > 0) ? -1.0 : 1.0; */ return true; #undef IR } }; } #endif
411
0.853971
1
0.853971
game-dev
MEDIA
0.934361
game-dev
0.965808
1
0.965808
emileb/OpenGames
10,684
opengames/src/main/jni/abuse-0.8_orig/data/lisp/duong.lsp
;; Copyright 1995 Crack dot Com, All Rights reserved ;; See licensing information for more details on usage rights (defun mine_ai () (if (or (eq (total_objects) 0) (not (eq (with_object (get_object 0) (aistate)) 0))) (select (aistate) (0 (if (touching_bg) (progn (set_state running) (if (eq (xvel) 1) (progn (with_object (bg) (make_view_solid (find_rgb 250 10 10))) (hurt_radius (x) (y) 40 35 nil 20)) (hurt_radius (x) (y) 40 25 nil 20)) (go_state 1)) (next_picture)) T) (1 (next_picture))) T)) (def_char CONC (funs (ai_fun mine_ai)) (fields ("xvel" conc_flash)) (states "art/chars/mine.spe" (running (seq "mine" 1 8)) (stopped '("mine0001.pcx" "mine_off")))) (defun air_mine_ai () (if (or (eq (total_objects) 0) ;; turned on? (not (eq (with_object (get_object 0) (aistate)) 0))) (if (touching_bg) (progn (if (eq (xvel) 1) (with_object (bg) (make_view_solid (find_rgb 250 10 10)))) (do_explo 40 25) nil) (progn (next_picture) T)) T)) (def_char CONC_AIR (funs (ai_fun air_mine_ai)) (fields ("xvel" conc_flash)) (states "art/chars/mine.spe" (stopped (seq "amin" 1 2)))) (defun bomb_cons () (setq blink_time 14)) (defun bomb_ai () (select (aistate) (0 ;; wait for a signal if connected, or wait for player touch (if (activated) (go_state 1) T)) (1 ;; count down blink time until zero then blow up (if (< blink_time 1) (go_state 2) (progn (if (or (< blink_time 10) (and (< blink_time 18) (eq (mod blink_time 2) 0)) (and (< blink_time 30) (eq (mod blink_time 3) 0)) (and (< blink_time 50) (eq (mod blink_time 4) 0))) (progn (play_sound TICK_SND 127 (x) (y)) (next_picture))) (setq blink_time (- blink_time 1)) T))) (2 ;; blow up (let ((oldy (y))) (set_y (- (y) (/ (picture_height) 2))) (do_explo 40 (get_ability jump_yvel)) (if (> (get_ability jump_yvel) 100) (add_object EXPLODE1 (+ (x) (random 10)) (+ (+ (random 10) (y)) -20) 0)) (set_y oldy)) nil))) (def_char BOMB (funs (ai_fun bomb_ai) (constructor bomb_cons)) (abilities (jump_yvel 30)) (range 150 150) (vars blink_time) (fields ("blink_time" bomb_blink)) (states "art/chars/mine.spe" (stopped '("abomb0001.pcx" "abomb0002.pcx")))) (def_char BIG_BOMB (funs (ai_fun bomb_ai) (constructor bomb_cons)) (abilities (jump_yvel 400)) (range 150 150) (vars blink_time) (fields ("blink_time" bomb_blink)) (states "art/chars/mine.spe" (stopped '("abomb0001.pcx+" "abomb0002.pcx+")))) (defun block_ai () (if (<= (hp) 0) (if (eq (state) dieing) (next_picture) (progn (play_sound CRUMBLE_SND 127 (x) (y)) (set_state dieing) T)) T)) (def_char BLOCK ;block has only 1 frame now will have block blowing up (funs (ai_fun block_ai)) (flags (can_block T) (hurtable T)) (abilities (start_hp 30)) (states "art/chars/block.spe" (stopped "block.pcx") (dieing (seq "bexplo" 1 7)))) (defun trap_door_ai () (if (> (total_objects) 0) (select (aistate) (0 ;; wait for switch to go off (if (not (eq (with_object (get_object 0) (aistate)) 0)) (progn (set_state running) (go_state 1)))) (1 ;; wait for animation (if (next_picture) T (progn (set_state blocking) (set_aistate 2)))) (2 ;; just stay here T))) T) (defun strap_door_ai () (general_sdoor_ai nil)) (def_char TRAP_DOOR2 (funs (ai_fun strap_door_ai)) (flags (can_block T)) (abilities (start_hp 30)) (states "art/chars/tdoor.spe" (stopped "tdor0001.pcx") (running (seq "tdor" 1 7)) (walking (seq "tdor" 7 1)) (blocking "tdor0007.pcx"))) (def_char TRAP_DOOR3 (funs (ai_fun strap_door_ai)) (flags (can_block T)) (abilities (start_hp 30)) (states "art/chars/tdoor.spe" (stopped "cdor0001.pcx") (running (seq "cdor" 1 7)) (walking (seq "cdor" 7 1)) (blocking "cdor0007.pcx"))) (defun lightin_ai () (if (or (eq (total_objects) 0) (not (eq (with_object (get_object 0) (aistate)) 0))) (select (aistate) (0 ;; delay (if (< (state_time) (* (aitype) 2)) (set_state stopped) (progn ; (hurt_radius (x) (y) 40 30 nil 30) (set_state running) (play_sound ELECTRIC_SND 127 (x) (y)) (go_state 1)))) (1 ;; next picture (if (next_picture) T (set_aistate 0))))) T) (def_char LIGHTIN (funs (ai_fun lightin_ai)) (flags (can_block T)) (fields ("aitype" lightin_speed)) (states "art/chars/lightin.spe" (running (seq "lite" 1 9)) (stopped "lite0001.pcx"))) (defun lava_ai () (if (and (touching_bg) (eq (mod (state_time) 20) 0)) (do_damage 6 (bg))) (select (aistate) (0 (if (eq (random 100) 0) (progn (play_sound LAVA_SND 64 (x) (y)) (set_aistate 1))) (next_picture)) (1 (next_picture) (if (eq (state_time) 5) (progn (hurt_radius (x) (y) 20 20 nil 10) (set_aistate 0))))) T) (def_char LAVA (funs (ai_fun lava_ai)) (states "art/chars/lava.spe" (stopped (seq "lava" 1 15)))) ;; XXX: Mac Abuse reimplements this in C++ (defun tp2_ai () (if (> (total_objects) 0) (select (aistate) (0 ;; wait for player to activate (if (and (touching_bg) (eq (total_objects) 1)) (progn (if (with_object (bg) (pressing_action_key)) (progn (link_object (bg)) (set_state running) (play_sound TELEPORTER_SND 127 (x) (y)) (set_aistate 1)))))) (1 ;; wait for animation (if (next_picture) (let ((x (x)) (y (- (y) 16)) (fade (if (< (current_frame) 16) (current_frame) 15))) (with_object (get_object 1) (progn (set_x x) (set_y y) (user_fun SET_FADE_COUNT fade) (setq is_teleporting 1) ))) (let ((x (with_object (get_object 0) (x))) (y (with_object (get_object 0) (- (y) 16)))) (with_object (get_object 1) (progn (set_x x) (set_y y) (setq is_teleporting 0) (user_fun SET_FADE_COUNT 0) )) (remove_object (get_object 1)) (set_aistate 0)))))) T) (def_char TELE2 (funs (ai_fun tp2_ai)) (flags (can_block T)) (states "art/chars/teleport.spe" (stopped "close") (running (seq "elec" 1 15)))) (defun bolder_ai () (if (or (eq (total_objects) 0) (not (eq (with_object (get_object 0) (aistate)) 0))) (if (eq (hp) 0) (progn (play_sound P_EXPLODE_SND 127 (x) (y)) (add_object EXPLODE1 (+ (x) (random 5)) (+ (y) (random 5)) 0) (add_object EXPLODE1 (+ (x) (random 5)) (+ (y) (random 5)) 2) (add_object EXPLODE1 (- (x) (random 5)) (- (y) (random 5)) 1) (add_object EXPLODE1 (- (x) (random 5)) (- (y) (random 5)) 2) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel -4) (set_yvel -8))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel 4) (set_yvel -9))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel 2) (set_yvel -5))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel -3) (set_yvel -5))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel -1) (set_yvel 2))) (add_object EXP_LIGHT (x) (y) 100) nil) (progn (next_picture) (set_yvel (+ (yvel) 1)) (let ((old_yv (yvel)) (old_xv (xvel)) (old_x (x)) (old_y (y)) (status (float_tick))) (let ((new_x (x)) (new_y (y)) (set_x old_x) (set_y old_y)) (platform_push (- new_x (x)) (- new_y (y))) (set_x new_x) (set_y new_y)) (hurt_radius (x) (y) 19 30 (me) 15) (if (not (eq status T));; T means we did not hit anything (let ((block_flags (car status))) (if (or (blocked_up block_flags) (blocked_down block_flags));; bounce up/down (progn (if (> (abs old_yv) 3) (play_sound SBALL_SND 127 (x) (y))) (set_xvel old_xv) (if (> old_yv 1) (set_yvel (- 2 old_yv)) (set_yvel (- 0 old_yv)))) (if (or (blocked_left block_flags) (blocked_right block_flags));; bounce left/right (progn (set_yvel old_yv) (set_xvel (- 0 old_xv)))))))) T)) T)) (defun bolder_cons () (set_xvel -4) (set_yvel 0)) (defun bold_dam (amount from hitx hity push_xvel push_yvel) (add_object EXPLODE3 (+ (x) (- 10 (random 20))) (- (y) (random 30)) 0) (damage_fun amount from hitx hity (/ push_xvel 10) (/ push_yvel 2))) (def_char BOLDER (funs (ai_fun bolder_ai) (damage_fun bold_dam) (constructor bolder_cons)) (flags (can_block T) (add_front T) (hurtable T)) (range 200 200) (abilities (start_hp 40)) (fields ("xvel" ai_xvel) ("yvel" ai_yvel) ("hp" ai_health) ) (states "art/bold.spe" (stopped '("bold0001.pcx" "bold0001.pcx" "bold0001.pcx" "bold0002.pcx" "bold0002.pcx" "bold0002.pcx" "bold0003.pcx" "bold0003.pcx" "bold0003.pcx" "bold0004.pcx" "bold0004.pcx" "bold0004.pcx")))) (defun bounce_move (left_stub right_stub up_stub down_stub nothing_stub) (let ((old_yv (yvel)) (old_xv (xvel)) (status (float_tick))) (if (not (eq status T)) ;; T means we did not hit anything (let ((block_flags (car status))) (if (blocked_up block_flags) ;; bounce up/down (progn (set_xvel old_xv) (if (> old_yv 1) (set_yvel (- 2 old_yv)) (set_yvel (- 0 old_yv))) (eval up_stub)) (if (blocked_down block_flags) (progn (set_xvel old_xv) (if (> old_yv 1) (set_yvel (- 2 old_yv)) (set_yvel (- 0 old_yv))) (eval down_stub)) (if (blocked_left block_flags) (progn (set_yvel old_yv) (set_xvel (- 0 old_xv)) (eval left_stub)) (if (blocked_right block_flags) (progn (set_yvel old_yv) (set_xvel (- 0 old_xv)) (eval right_stub))))))) (eval nothing_stub)))) (defun small_rock_ai () (next_picture) (set_yvel (+ (yvel) 1)) (bounce_move T T T '(progn (add_object EXPLODE1 (+ (x) (random 10)) (- (+ (random 5) (y)) 10) 0) (add_object EXPLODE1 (- (x) (random 10)) (- (- (y) (random 5)) 10) 2) (play_sound P_EXPLODE_SND 127 (x) (y)) (hurt_radius (x) (y) 40 15 (if (> (total_objects) 0) (get_object 0) nil) 20) nil) T)) (def_char SMALL_BOLDER (funs (ai_fun small_rock_ai)) (flags (add_front T) (unlistable T)) (states "art/bold.spe" (stopped "bsmall")))
411
0.863822
1
0.863822
game-dev
MEDIA
0.701948
game-dev
0.972553
1
0.972553
cocos2d/cocos2d-x-samples
7,021
samples/SwiftTetris/cocos2d/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimeline.cpp
/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org 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 "CCActionTimeline.h" USING_NS_CC; NS_TIMELINE_BEGIN // ActionTimelineData ActionTimelineData* ActionTimelineData::create(int actionTag) { ActionTimelineData * ret = new ActionTimelineData(); if (ret && ret->init(actionTag)) { ret->autorelease(); } else { CC_SAFE_DELETE(ret); } return ret; } ActionTimelineData::ActionTimelineData() : _actionTag(0) { } bool ActionTimelineData::init(int actionTag) { _actionTag = actionTag; return true; } // ActionTimeline ActionTimeline* ActionTimeline::create() { ActionTimeline* object = new ActionTimeline(); if (object && object->init()) { object->autorelease(); return object; } CC_SAFE_DELETE(object); return nullptr; } ActionTimeline::ActionTimeline() : _duration(0) , _time(0) , _timeSpeed(1) , _frameInternal(1/60.0f) , _playing(false) , _currentFrame(0) , _startFrame(0) , _endFrame(0) , _frameEventListener(nullptr) { } ActionTimeline::~ActionTimeline() { } bool ActionTimeline::init() { return true; } void ActionTimeline::gotoFrameAndPlay(int startIndex) { gotoFrameAndPlay(startIndex, true); } void ActionTimeline::gotoFrameAndPlay(int startIndex, bool loop) { gotoFrameAndPlay(startIndex, _duration, loop); } void ActionTimeline::gotoFrameAndPlay(int startIndex, int endIndex, bool loop) { gotoFrameAndPlay(startIndex, endIndex, startIndex, loop); } void ActionTimeline::gotoFrameAndPlay(int startIndex, int endIndex, int currentFrameIndex, bool loop) { _startFrame = startIndex; _endFrame = endIndex; _currentFrame = currentFrameIndex; _loop = loop; _time = _currentFrame*_frameInternal; resume(); gotoFrame(_currentFrame); } void ActionTimeline::gotoFrameAndPause(int startIndex) { _startFrame = _currentFrame = startIndex; _time = _currentFrame * _frameInternal; pause(); gotoFrame(_currentFrame); } void ActionTimeline::pause() { _playing = false; } void ActionTimeline::resume() { _playing = true; } bool ActionTimeline::isPlaying() const { return _playing; } void ActionTimeline::setCurrentFrame(int frameIndex) { if (frameIndex >= _startFrame && frameIndex >= _endFrame) { _currentFrame = frameIndex; _time = _currentFrame*_frameInternal; } else { CCLOG("frame index is not between start frame and end frame"); } } ActionTimeline* ActionTimeline::clone() const { ActionTimeline* newAction = ActionTimeline::create(); newAction->setDuration(_duration); newAction->setTimeSpeed(_timeSpeed); for (auto timelines : _timelineMap) { for(auto timeline : timelines.second) { Timeline* newTimeline = timeline->clone(); newAction->addTimeline(newTimeline); } } return newAction; } void ActionTimeline::step(float delta) { if (!_playing || _timelineMap.size() == 0 || _duration == 0) { return; } _time += delta * _timeSpeed; _currentFrame = (int)(_time / _frameInternal); stepToFrame(_currentFrame); if(_time > _endFrame * _frameInternal) { _playing = _loop; if(!_playing) _time = _endFrame * _frameInternal; else gotoFrameAndPlay(_startFrame, _endFrame, _loop); } } typedef std::function<void(Node*)> tCallBack; void foreachNodeDescendant(Node* parent, tCallBack callback) { callback(parent); auto children = parent->getChildren(); for (auto child : children) { foreachNodeDescendant(child, callback); } } void ActionTimeline::startWithTarget(Node *target) { Action::startWithTarget(target); foreachNodeDescendant(target, [this, target](Node* child) { ActionTimelineData* data = dynamic_cast<ActionTimelineData*>(child->getUserObject()); int actionTag = data->getActionTag(); if(_timelineMap.find(actionTag) != _timelineMap.end()) { auto timelines = this->_timelineMap[actionTag]; for (auto timeline : timelines) { timeline->setNode(child); } } }); } void ActionTimeline::addTimeline(Timeline* timeline) { int tag = timeline->getActionTag(); if (_timelineMap.find(tag) == _timelineMap.end()) { _timelineMap[tag] = Vector<Timeline*>(); } if (!_timelineMap[tag].contains(timeline)) { _timelineList.pushBack(timeline); _timelineMap[tag].pushBack(timeline); timeline->setActionTimeline(this); } } void ActionTimeline::removeTimeline(Timeline* timeline) { int tag = timeline->getActionTag(); if (_timelineMap.find(tag) != _timelineMap.end()) { if(_timelineMap[tag].contains(timeline)) { _timelineMap[tag].eraseObject(timeline); _timelineList.eraseObject(timeline); timeline->setActionTimeline(nullptr); } } } void ActionTimeline::setFrameEventCallFunc(std::function<void(Frame *)> listener) { _frameEventListener = listener; } void ActionTimeline::clearFrameEventCallFunc() { _frameEventListener = nullptr; } void ActionTimeline::emitFrameEvent(Frame* frame) { if(_frameEventListener) { _frameEventListener(frame); } } void ActionTimeline::gotoFrame(int frameIndex) { int size = _timelineList.size(); for(int i = 0; i<size; i++) { _timelineList.at(i)->gotoFrame(frameIndex); } } void ActionTimeline::stepToFrame(int frameIndex) { int size = _timelineList.size(); for(int i = 0; i<size; i++) { _timelineList.at(i)->stepToFrame(frameIndex); } } NS_TIMELINE_END
411
0.912118
1
0.912118
game-dev
MEDIA
0.717292
game-dev
0.982753
1
0.982753
Team-Immersive-Intelligence/ImmersiveIntelligence
5,399
src/main/java/pl/pabilo8/immersiveintelligence/common/item/armor/ItemIILightEngineerLeggings.java
package pl.pabilo8.immersiveintelligence.common.item.armor; import blusunrize.immersiveengineering.api.tool.IElectricEquipment; import blusunrize.immersiveengineering.common.util.IEDamageSources; import blusunrize.immersiveengineering.common.util.IEDamageSources.ElectricDamageSource; import blusunrize.immersiveengineering.common.util.ItemNBTHelper; import com.google.common.collect.Multimap; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import pl.pabilo8.immersiveintelligence.client.ClientProxy; import pl.pabilo8.immersiveintelligence.client.model.armor.ModelLightEngineerArmor; import pl.pabilo8.immersiveintelligence.common.IIConfigHandler.IIConfig.Weapons.LightEngineerArmor; import pl.pabilo8.immersiveintelligence.common.IIPotions; import pl.pabilo8.immersiveintelligence.common.network.IIPacketHandler; import pl.pabilo8.immersiveintelligence.common.network.messages.MessageItemKeybind; import pl.pabilo8.immersiveintelligence.common.util.item.IICategory; import pl.pabilo8.immersiveintelligence.common.util.item.IIItemEnum.IIItemProperties; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Map; /** * @author Pabilo8 (pabilo@iiteam.net) * @since 13.09.2020 */ @IIItemProperties(category = IICategory.WARFARE) public class ItemIILightEngineerLeggings extends ItemIILightEngineerArmorBase implements IElectricEquipment { public ItemIILightEngineerLeggings() { super(EntityEquipmentSlot.LEGS, "LIGHT_ENGINEER_LEGGINGS"); } @Override public void onArmorTick(World world, EntityPlayer player, ItemStack stack) { super.onArmorTick(world, player, stack); if(hasUpgrade(stack, "exoskeleton")) { int rammingCooldown = ItemNBTHelper.getInt(stack, "rammingCooldown")-1; if(rammingCooldown > 0) ItemNBTHelper.setInt(stack, "rammingCooldown", rammingCooldown); else ItemNBTHelper.remove(stack, "rammingCooldown"); if(world.isRemote) { if(ClientProxy.keybind_armorExosuit.isPressed()) IIPacketHandler.sendToServer(new MessageItemKeybind(MessageItemKeybind.KEYBIND_EXOSKELETON)); } int mode = ItemNBTHelper.getInt(stack, "exoskeletonMode"); int energy = (int)(mode/2f*LightEngineerArmor.exoskeletonEnergyUsage); if(mode > 0&&player.isSprinting()&&extractEnergy(stack, energy, false)==energy) { //keep player saturated, so he won't slow down player.getFoodStats().addStats(0, 20); //ramming if(mode==2&&player.distanceWalkedOnStepModified > 8&&player.isPotionActive(IIPotions.movementAssist)) { List<EntityMob> mobs = world.getEntitiesWithinAABB(EntityMob.class, player.getEntityBoundingBox(), null); if(mobs.size() > 0) { mobs.forEach(entityMob -> { entityMob.knockBack(player, 3, MathHelper.sin(player.rotationYaw*0.017453292F), -MathHelper.cos(player.rotationYaw*0.017453292F)); entityMob.attackEntityFrom(IEDamageSources.crusher, player.getTotalArmorValue()); }); player.getArmorInventoryList().forEach(s -> s.damageItem(2, player)); player.removePotionEffect(IIPotions.movementAssist); ItemNBTHelper.setInt(stack, "rammingCooldown", 40); } } //slow down after ram if(ItemNBTHelper.getInt(stack, "rammingCooldown") <= 0&&world.getTotalWorldTime()%4==0) player.addPotionEffect(new PotionEffect(IIPotions.movementAssist, 4, mode, false, false)); } } } @Nullable @Override @SideOnly(Side.CLIENT) public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, EntityEquipmentSlot armorSlot, ModelBiped _default) { return ModelLightEngineerArmor.getModel(armorSlot, itemStack); } @SideOnly(Side.CLIENT) @Override public void addInformation(@Nonnull ItemStack stack, @Nullable World world, List<String> list, @Nonnull ITooltipFlag flag) { super.addInformation(stack, world, list, flag); } @Override public float getXpRepairRatio(ItemStack stack) { return 0.1f; } @Nonnull @Override public Multimap<String, AttributeModifier> getAttributeModifiers(@Nonnull EntityEquipmentSlot equipmentSlot, @Nonnull ItemStack stack) { Multimap<String, AttributeModifier> multimap = super.getAttributeModifiers(equipmentSlot, stack); if(equipmentSlot==this.armorType) { //multimap.put(SharedMonsterAttributes.MOVEMENT_SPEED.getName(), new AttributeModifier(ARMOR_MODIFIERS[equipmentSlot.getIndex()], "Power Armor Movement Speed Debuff", -.03, 1)); } return multimap; } @Override public void onStrike(ItemStack s, EntityEquipmentSlot eqSlot, EntityLivingBase p, Map<String, Object> cache, @Nullable DamageSource dSource, ElectricSource eSource) { if(!(dSource instanceof ElectricDamageSource)) { } // TODO: 13.09.2020 tesla coil interaction } @Override public int getSlotCount() { return 3; } }
411
0.912563
1
0.912563
game-dev
MEDIA
0.99261
game-dev
0.972296
1
0.972296
Arkensor/EnfusionPersistenceFramework
9,566
src/Scripts/Game/Components/EPF_SlotManagerComponentSaveData.c
[EPF_ComponentSaveDataType(SlotManagerComponent), BaseContainerProps()] class EPF_SlotManagerComponentSaveDataClass : EPF_ComponentSaveDataClass { [Attribute("1", desc: "Skip writing slot attached entities that are non banked if they have only default data and match the default slot prefab.\nDisable this option if you absoluetly need to track persistent ids of the slots. Can cause larger amounts of data for vehicles that have many nested slots.")] bool m_bSkipDefaultNonBaked; } [EDF_DbName.Automatic()] class EPF_SlotManagerComponentSaveData : EPF_ComponentSaveData { ref array<ref EPF_PersistentEntitySlot> m_aSlots; //------------------------------------------------------------------------------------------------ override EPF_EReadResult ReadFrom(IEntity owner, GenericComponent component, EPF_ComponentSaveDataClass attributes) { SlotManagerComponent slotManager = SlotManagerComponent.Cast(component); EPF_SlotManagerComponentSaveDataClass settings = EPF_SlotManagerComponentSaveDataClass.Cast(attributes); m_aSlots = {}; array<ref EPF_EntitySlotPrefabInfo> slotinfos = EPF_EntitySlotPrefabInfo.GetSlotInfos(owner, slotManager); array<EntitySlotInfo> outSlotInfos(); slotManager.GetSlotInfos(outSlotInfos); foreach (int idx, EntitySlotInfo entitySlot : outSlotInfos) { IEntity slotEntity = entitySlot.GetAttachedEntity(); ResourceName prefab = EPF_Utils.GetPrefabName(slotEntity); EPF_EntitySlotPrefabInfo prefabInfo = slotinfos.Get(idx); bool isPrefabMatch = prefab == prefabInfo.GetEnabledSlotPrefab(); EPF_PersistenceComponent slotPersistence = EPF_Component<EPF_PersistenceComponent>.Find(slotEntity); if (!slotPersistence) { // Slot is different from prefab and the new slot has no persistence component so we clear it. if (!isPrefabMatch) { EPF_PersistentEntitySlot persistentSlot(); persistentSlot.m_sName = prefabInfo.m_sName; m_aSlots.Insert(persistentSlot); } continue; } EPF_EReadResult readResult; EPF_EntitySaveData saveData = slotPersistence.Save(readResult); if (!saveData) return EPF_EReadResult.ERROR; // Read transform to see if slot uses OverrideTransformLS set. ReadTransform(slotEntity, saveData, prefabInfo, readResult); // We can safely ignore baked objects with default info on them, but anything else needs to be saved. if (attributes.m_bTrimDefaults && isPrefabMatch && readResult == EPF_EReadResult.DEFAULT && (settings.m_bSkipDefaultNonBaked || EPF_BitFlags.CheckFlags(slotPersistence.GetFlags(), EPF_EPersistenceFlags.BAKED))) { continue; } EPF_PersistentEntitySlot persistentSlot(); persistentSlot.m_sName = prefabInfo.m_sName; persistentSlot.m_pEntity = saveData; m_aSlots.Insert(persistentSlot); } if (m_aSlots.IsEmpty()) return EPF_EReadResult.DEFAULT; return EPF_EReadResult.OK; } //------------------------------------------------------------------------------------------------ static void ReadTransform(IEntity slotEntity, EPF_EntitySaveData saveData, EPF_EntitySlotPrefabInfo prefabInfo, out EPF_EReadResult readResult) { EPF_PersistenceComponentClass slotAttributes = EPF_ComponentData<EPF_PersistenceComponentClass>.Get(slotEntity); if (saveData.m_pTransformation.ReadFrom(slotEntity, slotAttributes.m_pSaveData, false)) { if (!EPF_Const.IsUnset(saveData.m_pTransformation.m_vOrigin) && vector.Distance(saveData.m_pTransformation.m_vOrigin, prefabInfo.m_vOffset) > 0.001) { readResult = EPF_EReadResult.OK; } if (!EPF_Const.IsUnset(saveData.m_pTransformation.m_vAngles)) { vector localFixedAngles = slotEntity.GetLocalAngles(); if (float.AlmostEqual(localFixedAngles[0], -180)) localFixedAngles[0] = 180; if (float.AlmostEqual(localFixedAngles[1], -180)) localFixedAngles[1] = 180; if (float.AlmostEqual(localFixedAngles[2], -180)) localFixedAngles[2] = 180; if (vector.Distance(localFixedAngles, prefabInfo.m_vAngles) > 0.001) readResult = EPF_EReadResult.OK; } if (!EPF_Const.IsUnset(saveData.m_pTransformation.m_fScale)) { readResult = EPF_EReadResult.OK; } } } //------------------------------------------------------------------------------------------------ override EPF_EApplyResult ApplyTo(IEntity owner, GenericComponent component, EPF_ComponentSaveDataClass attributes) { SlotManagerComponent slotManager = SlotManagerComponent.Cast(component); array<EntitySlotInfo> outSlotInfos(); slotManager.GetSlotInfos(outSlotInfos); EPF_EApplyResult result = EPF_EApplyResult.OK; foreach (EPF_PersistentEntitySlot persistentSlot : m_aSlots) { EntitySlotInfo slot = slotManager.GetSlotByName(persistentSlot.m_sName); if (!slot) continue; EPF_EApplyResult slotResult = ApplySlot(slot, persistentSlot.m_pEntity); if (slotResult == EPF_EApplyResult.ERROR) return EPF_EApplyResult.ERROR; if (slotResult == EPF_EApplyResult.AWAIT_COMPLETION) result = EPF_EApplyResult.AWAIT_COMPLETION; } return result; } //------------------------------------------------------------------------------------------------ static EPF_EApplyResult ApplySlot(EntitySlotInfo entitySlot, EPF_EntitySaveData saveData) { IEntity slotEntity = entitySlot.GetAttachedEntity(); // If there is an tramsform override we need to flag it before load as we handle it on our own EPF_PersistentTransformation persistentTransform = saveData.m_pTransformation; if (persistentTransform) persistentTransform.m_bApplied = true; // Found matching entity, no need to spawn, just apply save-data if (saveData && slotEntity && EPF_Utils.GetPrefabGUID(EPF_Utils.GetPrefabName(slotEntity)) == EPF_Utils.GetPrefabGUID(saveData.m_rPrefab)) { EPF_PersistenceComponent slotPersistence = EPF_Component<EPF_PersistenceComponent>.Find(slotEntity); if (slotPersistence && !slotPersistence.Load(saveData, false)) return EPF_EApplyResult.ERROR; } else { // Slot did not match save-data, delete current entity on it SCR_EntityHelper.DeleteEntityAndChildren(slotEntity); if (!saveData) return EPF_EApplyResult.OK; // Spawn new entity and attach it slotEntity = saveData.Spawn(false); if (!slotEntity) return EPF_EApplyResult.ERROR; entitySlot.AttachEntity(slotEntity); if (entitySlot.GetAttachedEntity() != slotEntity) return EPF_EApplyResult.ERROR; } if (persistentTransform) { vector transform[4]; if (!EPF_Const.IsUnset(persistentTransform.m_vOrigin)) transform[3] = persistentTransform.m_vOrigin; if (!EPF_Const.IsUnset(persistentTransform.m_vAngles)) { Math3D.AnglesToMatrix(persistentTransform.m_vAngles, transform); } else { Math3D.MatrixIdentity3(transform); } if (!EPF_Const.IsUnset(persistentTransform.m_fScale)) Math3D.MatrixScale(transform, persistentTransform.m_fScale); entitySlot.OverrideTransformLS(transform); } return EPF_EApplyResult.OK; } //------------------------------------------------------------------------------------------------ override bool Equals(notnull EPF_ComponentSaveData other) { EPF_SlotManagerComponentSaveData otherData = EPF_SlotManagerComponentSaveData.Cast(other); if (m_aSlots.Count() != otherData.m_aSlots.Count()) return false; foreach (int idx, EPF_PersistentEntitySlot slot : m_aSlots) { // Try same index first as they are likely to be the correct ones. if (slot.Equals(otherData.m_aSlots.Get(idx))) continue; bool found; foreach (int compareIdx, EPF_PersistentEntitySlot otherSlot : otherData.m_aSlots) { if (compareIdx == idx) continue; // Already tried in idx direct compare if (slot.Equals(otherSlot)) { found = true; break; } } if (!found) return false; } return true; } } class EPF_PersistentEntitySlot { string m_sName; ref EPF_EntitySaveData m_pEntity; //------------------------------------------------------------------------------------------------ bool Equals(notnull EPF_PersistentEntitySlot other) { return m_sName == other.m_sName && m_pEntity.Equals(other.m_pEntity); } //------------------------------------------------------------------------------------------------ protected bool SerializationSave(BaseSerializationSaveContext saveContext) { if (!saveContext.IsValid()) return false; saveContext.WriteValue("m_sName", m_sName); string entityType = "EMPTY"; if (m_pEntity) entityType = EDF_DbName.Get(m_pEntity.Type()); saveContext.WriteValue("_type", entityType); if (entityType) saveContext.WriteValue("m_pEntity", m_pEntity); return true; } //------------------------------------------------------------------------------------------------ protected bool SerializationLoad(BaseSerializationLoadContext loadContext) { if (!loadContext.IsValid()) return false; loadContext.ReadValue("m_sName", m_sName); string entityTypeString; loadContext.ReadValue("_type", entityTypeString); // TODO: Remove backwards compatiblity in 0.9.9 if (!entityTypeString && ContainerSerializationLoadContext.Cast(loadContext).GetContainer().IsInherited(JsonLoadContainer)) loadContext.ReadValue("entityType", entityTypeString); if (entityTypeString == "EMPTY") return true; typename entityType = EDF_DbName.GetTypeByName(entityTypeString); if (!entityType) return false; m_pEntity = EPF_EntitySaveData.Cast(entityType.Spawn()); loadContext.ReadValue("m_pEntity", m_pEntity); return true; } }
411
0.906741
1
0.906741
game-dev
MEDIA
0.789043
game-dev
0.956693
1
0.956693
followingthefasciaplane/source-engine-diff-check
1,093
misc/game/shared/portal/portal_collideable_enumerator.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef PORTAL_COLLIDEABLE_ENUMERATOR_H #define PORTAL_COLLIDEABLE_ENUMERATOR_H #ifdef _WIN32 #pragma once #endif #include "ISpatialPartition.h" //only enumerates entities in front of the associated portal and are solid (as in a player would get stuck in them) class CPortalCollideableEnumerator : public IPartitionEnumerator { private: EHANDLE m_hTestPortal; //the associated portal that we only want objects in front of Vector m_vPlaneNormal; //portal plane normal float m_fPlaneDist; //plane equation distance Vector m_ptForward1000; //a point exactly 1000 units from the portal center along its forward vector public: IHandleEntity *m_pHandles[1024]; int m_iHandleCount; CPortalCollideableEnumerator( const CPortal_Base2D *pAssociatedPortal ); virtual IterationRetval_t EnumElement( IHandleEntity *pHandleEntity ); }; #endif //#ifndef PORTAL_COLLIDEABLE_ENUMERATOR_H
411
0.888466
1
0.888466
game-dev
MEDIA
0.74181
game-dev
0.675175
1
0.675175
VocaDB/vocadb
1,206
VocaDbModel/Domain/ReleaseEvents/EventSeriesTagUsage.cs
using VocaDb.Model.Domain.Tags; using VocaDb.Model.Domain.Users; namespace VocaDb.Model.Domain.ReleaseEvents; public class EventSeriesTagUsage : GenericTagUsage<ReleaseEventSeries, EventSeriesTagVote> { public EventSeriesTagUsage() { } public EventSeriesTagUsage(ReleaseEventSeries song, Tag tag) : base(song, tag) { } public override TagVote? CreateVote(User user) { if (FindVote(user) != null) return null; var vote = new EventSeriesTagVote(this, user); Votes.Add(vote); Count++; return vote; } public override void Delete() { base.Delete(); Entry.Tags.Usages.Remove(this); Tag.AllEventSeriesTagUsages.Remove(this); } public override TagUsage Move(Tag target) { ParamIs.NotNull(() => target); if (target.Equals(Tag)) return this; // TODO: have to make a clone because of NH reparenting issues, see http://stackoverflow.com/questions/28114508/nhibernate-change-parent-deleted-object-would-be-re-saved-by-cascade Tag.AllEventSeriesTagUsages.Remove(this); Entry.Tags.Usages.Remove(this); var newUsage = new EventSeriesTagUsage(Entry, target); target.AllEventSeriesTagUsages.Add(newUsage); Entry.Tags.Usages.Add(newUsage); return newUsage; } }
411
0.821781
1
0.821781
game-dev
MEDIA
0.861683
game-dev
0.871937
1
0.871937
AAEmu/AAEmu
3,202
AAEmu.Game/Models/Game/Items/Actions/ItemTaskType.cs
namespace AAEmu.Game.Models.Game.Items.Actions; // TODO at X2::GameClient::ApplyItemTaskToSelf public enum ItemTaskType : byte { Invalid = 0, Destroy = 1, AboxDestroy = 2, Repair = 3, DurabilityLoss = 4, SwapItems = 5, Split = 6, SplitCofferItems = 7, SwapCofferItems = 8, Loot = 9, LootAll = 10, Gm = 11, GameRuleReset = 12, ConsumeSkillSource = 13, // 303-consume-skill-source DoodadCreate = 14, // 303-doodad-create DoodadRemove = 15, DoodadItemChanger = 16, DoodadInteraction = 17, DoodadCattleFeed = 18, UpgradeSkill = 19, AbilityChange = 20, AbilityReset = 21, BuyPriestBuff = 22, Teleport = 23, CapturePet = 24, RecoverDoodadItem = 25, // 508-recover-doodad-item MateCreate = 26, CraftActSaved = 27, CraftPaySaved = 28, CraftPickupProduct = 29, CraftCancel = 30, HouseCreation = 31, // 303-house-creation HouseDeposit = 32, HouseBuilding = 33, PickupBloodstain = 34, AutoLootDoodadItem = 35, // 316-autoloot-doodad-item QuestStart = 36, // 401-quest-start QuestComplete = 37, // 402-quest-complete QuestSupplyItems = 38, // 405-quest-supply-items QuestRemoveSupplies = 39, // 402-403-404-405-quest-remove-supplies SkillReagents = 40, SkillEffectConsumption = 41, SkillEffectGainItem = 42, SkillEffectGainItemWithPos = 43, SkillEffectSiegeTicket = 44, SkillEffectExpToItem = 45, Auction = 46, Mail = 47, Trade = 48, EnchantMagical = 49, EnchantPhysical = 50, GetCoinByItem = 51, GetItemByCoin = 52, StoreSell = 53, // 315-store-sell StoreBuy = 54, // 313-314-store-buy TodReward = 55, GainItemWithUcc = 56, ImprintUcc = 57, RepairPets = 58, MateDeath = 59, Shipyard = 60, // 303-shipyard SkillsReset = 61, DropBackpack = 62, UseRelic = 63, UseIndependenceRelic = 64, Conversion = 65, // 304-conversion Seize = 66, ReturnSeized = 67, DemoDressOff = 68, DemoDressOn = 69, DemoClearBag = 70, DemoFillBag = 71, SlaveDeath = 72, ExpeditionCreation = 73, RepairSlaves = 74, ExpandBag = 75, ExpandBank = 76, RenewEquipment = 77, LifespanExpiration = 78, RecoverExp = 79, SpawnerUpdate = 80, UpdateSummonSlaveItem = 81, UpdateSummonMateItem = 82, DepositMoney = 83, WithdrawMoney = 84, DeliverItemToOthers = 85, SetSlavePosition = 86, SetBountyMoney = 87, PayBountyMoney = 88, ConvertFish = 89, Fishing = 90, SellHouse = 91, BuyHouse = 92, SaveMusicNotes = 93, ItemLock = 94, ItemUnlock = 95, ItemUnlockExcess = 96, GradeEnchant = 97, RechargeBuff = 98, Socketing = 99, Dyeing = 100, ConsumeIndunTicket = 101, ExpandExpert = 102, Exchange = 103, SellBackpack = 104, SellSpecialty = 105, AskMould = 106, TakeMould = 107, FactionDeclareHostile = 108, EditCosmetic = 109, ChangeAutoUseAaPoint = 110, ConvertItemLook = 111, ChangeExpertLimit = 112, Skinize = 113, ItemTaskThistimeUnpack = 114, BuyPremiumService = 115, BuyAaPoint = 116 }
411
0.692144
1
0.692144
game-dev
MEDIA
0.521451
game-dev,web-backend
0.738596
1
0.738596
magarena/magarena
1,485
src/magic/model/action/ChangeTurnPTAction.java
package magic.model.action; import magic.model.MagicGame; import magic.model.MagicPermanent; import magic.model.MagicPowerToughness; import magic.model.MurmurHash3; import magic.model.mstatic.MagicLayer; import magic.model.mstatic.MagicStatic; public class ChangeTurnPTAction extends MagicAction { private final MagicPermanent permanent; private final int power; private final int toughness; public ChangeTurnPTAction(final MagicPermanent permanent,final int power,final int toughness) { this.permanent=permanent; this.power=power; this.toughness=toughness; } @Override public void doAction(final MagicGame game) { game.doAction(new AddStaticAction( permanent, new MagicStatic(MagicLayer.ModPT, MagicStatic.UntilEOT) { @Override public void modPowerToughness(final MagicPermanent source, final MagicPermanent permanent, final MagicPowerToughness pt) { pt.add(power, toughness); } @Override public long getStateId() { return MurmurHash3.hash(new long[] { MagicLayer.ModPT.ordinal(), MagicStatic.UntilEOT ? -1L : 1L, power, toughness }); } } )); } @Override public void undoAction(final MagicGame game) { } }
411
0.681376
1
0.681376
game-dev
MEDIA
0.919839
game-dev
0.909398
1
0.909398
bozimmerman/CoffeeMud
5,700
com/planet_ink/coffee_mud/Abilities/Spells/Spell_WizardsChest.java
package com.planet_ink.coffee_mud.Abilities.Spells; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2004-2025 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Spell_WizardsChest extends Spell { @Override public String ID() { return "Spell_WizardsChest"; } private final static String localizedName = CMLib.lang().L("Wizards Chest"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Wizard Chest)"); @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode() { return CAN_ITEMS; } @Override protected int canTargetCode() { return Ability.CAN_ITEMS; } @Override public int classificationCode() { return Ability.ACODE_SPELL|Ability.DOMAIN_ENCHANTMENT; } @Override public int abstractQuality() { return Ability.QUALITY_INDIFFERENT; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(affected==null) return true; if(!super.okMessage(myHost,msg)) return false; final MOB mob=msg.source(); if(((!msg.amITarget(affected))&&(msg.tool()!=affected)) ||(msg.source()==invoker()) ||((invoker()!=null)&&(invoker().Name().equals(text())))) return true; switch(msg.targetMinor()) { case CMMsg.TYP_OPEN: mob.tell(L("@x1 appears to be magically protected.",affected.name())); return false; case CMMsg.TYP_UNLOCK: mob.tell(L("@x1 appears to be magically protected.",affected.name())); return false; case CMMsg.TYP_JUSTICE: { if(!msg.targetMajor(CMMsg.MASK_DELICATE)) return true; } //$FALL-THROUGH$ case CMMsg.TYP_DELICATE_HANDS_ACT: mob.tell(L("@x1 appears to be magically protected.",affected.name())); return false; default: break; } return true; } @Override public void executeMsg(final Environmental host, final CMMsg msg) { if((msg.target()==affected) &&((msg.source()==invoker())||(msg.source().Name().equals(text()))) &&(msg.sourceMessage()!=null) &&(msg.sourceMinor()==CMMsg.TYP_SPEAK) &&(msg.sourceMessage().toUpperCase().indexOf("OPEN")>=0) &&(affected instanceof Container)) { final Container container=(Container)affected; container.setDoorsNLocks(container.hasADoor(),true,container.defaultsClosed(),container.hasALock(),false,container.defaultsLocked()); msg.addTrailerMsg(CMClass.getMsg(msg.source(),affected,null,CMMsg.MSG_OK_VISUAL,L("<T-NAME> pop(s) open!"))); } } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { if((commands.size()<1)&&(givenTarget==null)) { mob.tell(L("Enchant what?.")); return false; } Physical target=null; target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY); if(target==null) return false; if((!(target instanceof Container))||(!((Container)target).hasALock())||(!((Container)target).hasADoor())) { mob.tell(L("You can only enchant the locks on open containers with lids.")); return false; } if(!((Container)target).isOpen()) { mob.tell(L("@x1 must be opened before this magic will work.",target.name(mob))); return false; } if(target.fetchEffect(this.ID())!=null) { mob.tell(L("@x1 is already a wizards chest!",target.name(mob))); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,somaticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> point(s) <S-HIS-HER> finger at <T-NAMESELF>, incanting.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(target instanceof Container) { beneficialAffect(mob,target,asLevel,Ability.TICKS_ALMOST_FOREVER); final Container container=(Container)target; container.setDoorsNLocks(container.hasADoor(),false,container.defaultsClosed(),container.hasALock(),true,container.defaultsLocked()); mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> look(s) well protected!")); } } } else beneficialVisualFizzle(mob,target,L("<S-NAME> point(s) at <T-NAMESELF>, incanting, but nothing happens.")); // return whether it worked return success; } }
411
0.894617
1
0.894617
game-dev
MEDIA
0.951051
game-dev
0.900181
1
0.900181
crazyurus/miniprogram-vscode-extension
2,674
src/plugins/view.ts
import * as vscode from 'vscode'; import Plugin from '../base'; interface TreeElement { command: string; title: string; icon?: string; children?: TreeElement[]; } class TreeDataProvider implements vscode.TreeDataProvider<TreeElement> { getChildren(element?: TreeElement): TreeElement[] { if (element && element.children) { return element.children; } return [ { command: 'MiniProgram.commands.config.openIDE', title: '打开微信开发者工具' }, { command: 'MiniProgram.commands.compile.preview', title: '扫码预览小程序' }, { command: 'MiniProgram.commands.compile.upload', title: '打包并上传小程序' }, { command: 'MiniProgram.commands.compile.npm', title: '构建 NPM' }, { command: 'MiniProgram.commands.compile.analyze', title: '分析代码静态依赖' }, { command: 'MiniProgram.commands.compile.quality', title: '分析代码质量' }, { command: 'MiniProgram.commands.config.project', title: '查看项目配置' }, { command: 'MiniProgram.commands.compile.artifact', title: '查看编译产物' }, { command: 'MiniProgram.commands.compile.sourceMap', title: '下载最近上传版本的 SourceMap' }, { command: 'MiniProgram.commands.management', title: '打开微信小程序管理后台' }, { command: '', title: '微信开发文档', children: [ { command: 'MiniProgram.commands.document.open', title: '查看开发文档', icon: 'notebook-open-as-text' }, { command: 'MiniProgram.commands.document.search', title: '搜索开发文档', icon: 'search-view-icon' } ] }, { command: 'MiniProgram.commands.storage.clear', title: '清除缓存' } ]; } getTreeItem(element: TreeElement): vscode.TreeItem { const treeItem = new vscode.TreeItem(element.title); if (element.command) { treeItem.command = element; } if (element.children) { treeItem.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed; } if (element.icon) { treeItem.iconPath = new vscode.ThemeIcon(element.icon); } return treeItem; } } class ViewPlugin extends Plugin { activate(): void { vscode.commands.executeCommand('setContext', 'extensionActivated', true); vscode.window.registerTreeDataProvider('miniprogram-view', new TreeDataProvider()); } deactivate(): void { vscode.commands.executeCommand('setContext', 'extensionActivated', false); } } export default new ViewPlugin();
411
0.865944
1
0.865944
game-dev
MEDIA
0.736737
game-dev
0.740053
1
0.740053
alex9849/advanced-region-market
5,696
advancedregionmarket/src/main/java/net/alex9849/arm/inactivityexpiration/InactivityExpirationGroup.java
package net.alex9849.arm.inactivityexpiration; import net.alex9849.arm.AdvancedRegionMarket; import net.alex9849.arm.Permission; import net.alex9849.arm.regions.CountdownRegion; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; public class InactivityExpirationGroup { public static final InactivityExpirationGroup UNLIMITED = new InactivityExpirationGroup("Unlimited", -1, -1); public static final InactivityExpirationGroup NOT_CALCULATED = new InactivityExpirationGroup("Not calculated", -1, -1); public static InactivityExpirationGroup DEFAULT = new InactivityExpirationGroup("Default", -1, -1); private static Set<InactivityExpirationGroup> inactivityExpirationGroupSet = new HashSet<>(); private String name; private long resetAfterMs; private long takeOverAfterMs; public InactivityExpirationGroup(String name, long resetAfterMs, long takeOverAfterMs) { this.name = name; this.resetAfterMs = resetAfterMs; this.takeOverAfterMs = takeOverAfterMs; } public static void reset() { inactivityExpirationGroupSet = new HashSet<>(); } public static void add(InactivityExpirationGroup inactivityExpirationGroup) { inactivityExpirationGroupSet.add(inactivityExpirationGroup); } public static InactivityExpirationGroup getBestResetAfterMs(OfflinePlayer oPlayer, World world) { if (!AdvancedRegionMarket.getInstance().getVaultPerms().isEnabled()) { return UNLIMITED; } if (oPlayer == null || oPlayer.getName() == null) { return DEFAULT; } if (AdvancedRegionMarket.getInstance().getVaultPerms().playerHas(world.getName(), oPlayer, Permission.ARM_INACTIVITY_EXPIRATION + "unlimited")) { return UNLIMITED; } InactivityExpirationGroup selectedGroup = DEFAULT; for (InactivityExpirationGroup ieGroup : inactivityExpirationGroupSet) { if (AdvancedRegionMarket.getInstance().getVaultPerms().playerHas(world.getName(), oPlayer, Permission.ARM_INACTIVITY_EXPIRATION + ieGroup.getName())) { if (selectedGroup == DEFAULT || ((!selectedGroup.isResetDisabled() && (selectedGroup.getResetAfterMs() < ieGroup.getResetAfterMs())) || ieGroup.isResetDisabled())) { selectedGroup = ieGroup; } } } return selectedGroup; } public static InactivityExpirationGroup getBestTakeOverAfterMs(OfflinePlayer oPlayer, World world) { if (!AdvancedRegionMarket.getInstance().getVaultPerms().isEnabled()) { return UNLIMITED; } if (oPlayer == null || oPlayer.getName() == null) { return DEFAULT; } if (AdvancedRegionMarket.getInstance().getVaultPerms().playerHas(world.getName(), oPlayer, Permission.ARM_INACTIVITY_EXPIRATION + "unlimited")) { return UNLIMITED; } InactivityExpirationGroup selectedGroup = DEFAULT; for (InactivityExpirationGroup ieGroup : inactivityExpirationGroupSet) { if (AdvancedRegionMarket.getInstance().getVaultPerms().playerHas(world.getName(), oPlayer, Permission.ARM_INACTIVITY_EXPIRATION + ieGroup.getName())) { if (selectedGroup == DEFAULT || ((!selectedGroup.isTakeOverDisabled() && (selectedGroup.getTakeOverAfterMs() < ieGroup.getTakeOverAfterMs())) || ieGroup.isTakeOverDisabled())) { selectedGroup = ieGroup; } } } return selectedGroup; } public static InactivityExpirationGroup parse(ConfigurationSection configurationSection, String name) { long resetAfterMs; if (configurationSection.getString("resetAfter").equalsIgnoreCase("none")) { resetAfterMs = -1; } else { try { resetAfterMs = CountdownRegion.stringToTime(configurationSection.getString("resetAfter")); } catch (IllegalArgumentException e) { AdvancedRegionMarket.getInstance().getLogger().log(Level.WARNING, "Could parse resetAfter for " + "InactivityExpirationGroup " + name + "! Please check! ResetAfter has been set to unlimited to prevent unwanted region-resets"); resetAfterMs = -1; } } long takeOverAfterMs; if (configurationSection.getString("takeOverAfter").equalsIgnoreCase("none")) { takeOverAfterMs = -1; } else { try { takeOverAfterMs = CountdownRegion.stringToTime(configurationSection.getString("takeOverAfter")); } catch (IllegalArgumentException e) { AdvancedRegionMarket.getInstance().getLogger().log(Level.WARNING, "Could parse resetAfter for " + "InactivityExpirationGroup " + name + "! Please check! ResetAfter has been set to unlimited to prevent unwanted region-resets"); takeOverAfterMs = -1; } } return new InactivityExpirationGroup(name, resetAfterMs, takeOverAfterMs); } public String getName() { return this.name; } public long getResetAfterMs() { return resetAfterMs; } public boolean isResetDisabled() { return this.resetAfterMs <= 0; } public boolean isNotCalculated() { return this == NOT_CALCULATED; } public boolean isTakeOverDisabled() { return this.takeOverAfterMs <= 0; } public long getTakeOverAfterMs() { return takeOverAfterMs; } }
411
0.897619
1
0.897619
game-dev
MEDIA
0.586334
game-dev,distributed-systems
0.966726
1
0.966726
xBimTeam/XbimEssentials
3,206
Xbim.Ifc2x3/HVACDomain/IfcCompressorType.cs
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool Xbim.CodeGeneration // // Changes to this file may cause incorrect behaviour and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ using Xbim.Ifc2x3.SharedBldgServiceElements; using System; using System.Collections.Generic; using System.Linq; using Xbim.Common; using Xbim.Common.Exceptions; using Xbim.Ifc2x3.HVACDomain; //## Custom using statements //## namespace Xbim.Ifc2x3.HVACDomain { [ExpressType("IfcCompressorType", 586)] // ReSharper disable once PartialTypeWithSinglePart public partial class @IfcCompressorType : IfcFlowMovingDeviceType, IInstantiableEntity, IContainsEntityReferences, IContainsIndexedReferences, IEquatable<@IfcCompressorType> { //internal constructor makes sure that objects are not created outside of the model/ assembly controlled area internal IfcCompressorType(IModel model, int label, bool activated) : base(model, label, activated) { } #region Explicit attribute fields private IfcCompressorTypeEnum _predefinedType; #endregion #region Explicit attribute properties [EntityAttribute(10, EntityAttributeState.Mandatory, EntityAttributeType.Enum, EntityAttributeType.None, null, null, 15)] public IfcCompressorTypeEnum @PredefinedType { get { if(_activated) return _predefinedType; Activate(); return _predefinedType; } set { SetValue( v => _predefinedType = v, _predefinedType, value, "PredefinedType", 10); } } #endregion #region IPersist implementation public override void Parse(int propIndex, IPropertyValue value, int[] nestedIndex) { switch (propIndex) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: base.Parse(propIndex, value, nestedIndex); return; case 9: _predefinedType = (IfcCompressorTypeEnum) System.Enum.Parse(typeof (IfcCompressorTypeEnum), value.EnumVal, true); return; default: throw new XbimParserException(string.Format("Attribute index {0} is out of range for {1}", propIndex + 1, GetType().Name.ToUpper())); } } #endregion #region Equality comparers and operators public bool Equals(@IfcCompressorType other) { return this == other; } #endregion #region IContainsEntityReferences IEnumerable<IPersistEntity> IContainsEntityReferences.References { get { if (@OwnerHistory != null) yield return @OwnerHistory; foreach(var entity in @HasPropertySets) yield return entity; foreach(var entity in @RepresentationMaps) yield return entity; } } #endregion #region IContainsIndexedReferences IEnumerable<IPersistEntity> IContainsIndexedReferences.IndexedReferences { get { foreach(var entity in @HasPropertySets) yield return entity; } } #endregion #region Custom code (will survive code regeneration) //## Custom code //## #endregion } }
411
0.903317
1
0.903317
game-dev
MEDIA
0.17939
game-dev
0.938146
1
0.938146
wishForget/MiniMineCraft
18,400
MineCraftDemo/HelloOpenGL_00/includes/BulletCollision/BroadphaseCollision/btQuantizedBvh.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_QUANTIZED_BVH_H #define BT_QUANTIZED_BVH_H class btSerializer; //#define DEBUG_CHECK_DEQUANTIZATION 1 #ifdef DEBUG_CHECK_DEQUANTIZATION #ifdef __SPU__ #define printf spu_printf #endif //__SPU__ #include <stdio.h> #include <stdlib.h> #endif //DEBUG_CHECK_DEQUANTIZATION #include "LinearMath/btVector3.h" #include "LinearMath/btAlignedAllocator.h" #ifdef BT_USE_DOUBLE_PRECISION #define btQuantizedBvhData btQuantizedBvhDoubleData #define btOptimizedBvhNodeData btOptimizedBvhNodeDoubleData #define btQuantizedBvhDataName "btQuantizedBvhDoubleData" #else #define btQuantizedBvhData btQuantizedBvhFloatData #define btOptimizedBvhNodeData btOptimizedBvhNodeFloatData #define btQuantizedBvhDataName "btQuantizedBvhFloatData" #endif //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/vclrf__m128.asp //Note: currently we have 16 bytes per quantized node #define MAX_SUBTREE_SIZE_IN_BYTES 2048 // 10 gives the potential for 1024 parts, with at most 2^21 (2097152) (minus one // actually) triangles each (since the sign bit is reserved #define MAX_NUM_PARTS_IN_BITS 10 ///btQuantizedBvhNode is a compressed aabb node, 16 bytes. ///Node can be used for leafnode or internal node. Leafnodes can point to 32-bit triangle index (non-negative range). ATTRIBUTE_ALIGNED16(struct) btQuantizedBvhNode { BT_DECLARE_ALIGNED_ALLOCATOR(); //12 bytes unsigned short int m_quantizedAabbMin[3]; unsigned short int m_quantizedAabbMax[3]; //4 bytes int m_escapeIndexOrTriangleIndex; bool isLeafNode() const { //skipindex is negative (internal node), triangleindex >=0 (leafnode) return (m_escapeIndexOrTriangleIndex >= 0); } int getEscapeIndex() const { btAssert(!isLeafNode()); return -m_escapeIndexOrTriangleIndex; } int getTriangleIndex() const { btAssert(isLeafNode()); unsigned int x = 0; unsigned int y = (~(x & 0)) << (31 - MAX_NUM_PARTS_IN_BITS); // Get only the lower bits where the triangle index is stored return (m_escapeIndexOrTriangleIndex & ~(y)); } int getPartId() const { btAssert(isLeafNode()); // Get only the highest bits where the part index is stored return (m_escapeIndexOrTriangleIndex >> (31 - MAX_NUM_PARTS_IN_BITS)); } }; /// btOptimizedBvhNode contains both internal and leaf node information. /// Total node size is 44 bytes / node. You can use the compressed version of 16 bytes. ATTRIBUTE_ALIGNED16(struct) btOptimizedBvhNode { BT_DECLARE_ALIGNED_ALLOCATOR(); //32 bytes btVector3 m_aabbMinOrg; btVector3 m_aabbMaxOrg; //4 int m_escapeIndex; //8 //for child nodes int m_subPart; int m_triangleIndex; //pad the size to 64 bytes char m_padding[20]; }; ///btBvhSubtreeInfo provides info to gather a subtree of limited size ATTRIBUTE_ALIGNED16(class) btBvhSubtreeInfo { public: BT_DECLARE_ALIGNED_ALLOCATOR(); //12 bytes unsigned short int m_quantizedAabbMin[3]; unsigned short int m_quantizedAabbMax[3]; //4 bytes, points to the root of the subtree int m_rootNodeIndex; //4 bytes int m_subtreeSize; int m_padding[3]; btBvhSubtreeInfo() { //memset(&m_padding[0], 0, sizeof(m_padding)); } void setAabbFromQuantizeNode(const btQuantizedBvhNode& quantizedNode) { m_quantizedAabbMin[0] = quantizedNode.m_quantizedAabbMin[0]; m_quantizedAabbMin[1] = quantizedNode.m_quantizedAabbMin[1]; m_quantizedAabbMin[2] = quantizedNode.m_quantizedAabbMin[2]; m_quantizedAabbMax[0] = quantizedNode.m_quantizedAabbMax[0]; m_quantizedAabbMax[1] = quantizedNode.m_quantizedAabbMax[1]; m_quantizedAabbMax[2] = quantizedNode.m_quantizedAabbMax[2]; } }; class btNodeOverlapCallback { public: virtual ~btNodeOverlapCallback(){}; virtual void processNode(int subPart, int triangleIndex) = 0; }; #include "LinearMath/btAlignedAllocator.h" #include "LinearMath/btAlignedObjectArray.h" ///for code readability: typedef btAlignedObjectArray<btOptimizedBvhNode> NodeArray; typedef btAlignedObjectArray<btQuantizedBvhNode> QuantizedNodeArray; typedef btAlignedObjectArray<btBvhSubtreeInfo> BvhSubtreeInfoArray; ///The btQuantizedBvh class stores an AABB tree that can be quickly traversed on CPU and Cell SPU. ///It is used by the btBvhTriangleMeshShape as midphase. ///It is recommended to use quantization for better performance and lower memory requirements. ATTRIBUTE_ALIGNED16(class) btQuantizedBvh { public: enum btTraversalMode { TRAVERSAL_STACKLESS = 0, TRAVERSAL_STACKLESS_CACHE_FRIENDLY, TRAVERSAL_RECURSIVE }; protected: btVector3 m_bvhAabbMin; btVector3 m_bvhAabbMax; btVector3 m_bvhQuantization; int m_bulletVersion; //for serialization versioning. It could also be used to detect endianess. int m_curNodeIndex; //quantization data bool m_useQuantization; NodeArray m_leafNodes; NodeArray m_contiguousNodes; QuantizedNodeArray m_quantizedLeafNodes; QuantizedNodeArray m_quantizedContiguousNodes; btTraversalMode m_traversalMode; BvhSubtreeInfoArray m_SubtreeHeaders; //This is only used for serialization so we don't have to add serialization directly to btAlignedObjectArray mutable int m_subtreeHeaderCount; ///two versions, one for quantized and normal nodes. This allows code-reuse while maintaining readability (no template/macro!) ///this might be refactored into a virtual, it is usually not calculated at run-time void setInternalNodeAabbMin(int nodeIndex, const btVector3& aabbMin) { if (m_useQuantization) { quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0], aabbMin, 0); } else { m_contiguousNodes[nodeIndex].m_aabbMinOrg = aabbMin; } } void setInternalNodeAabbMax(int nodeIndex, const btVector3& aabbMax) { if (m_useQuantization) { quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0], aabbMax, 1); } else { m_contiguousNodes[nodeIndex].m_aabbMaxOrg = aabbMax; } } btVector3 getAabbMin(int nodeIndex) const { if (m_useQuantization) { return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMin[0]); } //non-quantized return m_leafNodes[nodeIndex].m_aabbMinOrg; } btVector3 getAabbMax(int nodeIndex) const { if (m_useQuantization) { return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMax[0]); } //non-quantized return m_leafNodes[nodeIndex].m_aabbMaxOrg; } void setInternalNodeEscapeIndex(int nodeIndex, int escapeIndex) { if (m_useQuantization) { m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = -escapeIndex; } else { m_contiguousNodes[nodeIndex].m_escapeIndex = escapeIndex; } } void mergeInternalNodeAabb(int nodeIndex, const btVector3& newAabbMin, const btVector3& newAabbMax) { if (m_useQuantization) { unsigned short int quantizedAabbMin[3]; unsigned short int quantizedAabbMax[3]; quantize(quantizedAabbMin, newAabbMin, 0); quantize(quantizedAabbMax, newAabbMax, 1); for (int i = 0; i < 3; i++) { if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] > quantizedAabbMin[i]) m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] = quantizedAabbMin[i]; if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] < quantizedAabbMax[i]) m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] = quantizedAabbMax[i]; } } else { //non-quantized m_contiguousNodes[nodeIndex].m_aabbMinOrg.setMin(newAabbMin); m_contiguousNodes[nodeIndex].m_aabbMaxOrg.setMax(newAabbMax); } } void swapLeafNodes(int firstIndex, int secondIndex); void assignInternalNodeFromLeafNode(int internalNode, int leafNodeIndex); protected: void buildTree(int startIndex, int endIndex); int calcSplittingAxis(int startIndex, int endIndex); int sortAndCalcSplittingIndex(int startIndex, int endIndex, int splitAxis); void walkStacklessTree(btNodeOverlapCallback * nodeCallback, const btVector3& aabbMin, const btVector3& aabbMax) const; void walkStacklessQuantizedTreeAgainstRay(btNodeOverlapCallback * nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex, int endNodeIndex) const; void walkStacklessQuantizedTree(btNodeOverlapCallback * nodeCallback, unsigned short int* quantizedQueryAabbMin, unsigned short int* quantizedQueryAabbMax, int startNodeIndex, int endNodeIndex) const; void walkStacklessTreeAgainstRay(btNodeOverlapCallback * nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex, int endNodeIndex) const; ///tree traversal designed for small-memory processors like PS3 SPU void walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback * nodeCallback, unsigned short int* quantizedQueryAabbMin, unsigned short int* quantizedQueryAabbMax) const; ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal void walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode, btNodeOverlapCallback* nodeCallback, unsigned short int* quantizedQueryAabbMin, unsigned short int* quantizedQueryAabbMax) const; ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal void walkRecursiveQuantizedTreeAgainstQuantizedTree(const btQuantizedBvhNode* treeNodeA, const btQuantizedBvhNode* treeNodeB, btNodeOverlapCallback* nodeCallback) const; void updateSubtreeHeaders(int leftChildNodexIndex, int rightChildNodexIndex); public: BT_DECLARE_ALIGNED_ALLOCATOR(); btQuantizedBvh(); virtual ~btQuantizedBvh(); ///***************************************** expert/internal use only ************************* void setQuantizationValues(const btVector3& bvhAabbMin, const btVector3& bvhAabbMax, btScalar quantizationMargin = btScalar(1.0)); QuantizedNodeArray& getLeafNodeArray() { return m_quantizedLeafNodes; } ///buildInternal is expert use only: assumes that setQuantizationValues and LeafNodeArray are initialized void buildInternal(); ///***************************************** expert/internal use only ************************* void reportAabbOverlappingNodex(btNodeOverlapCallback * nodeCallback, const btVector3& aabbMin, const btVector3& aabbMax) const; void reportRayOverlappingNodex(btNodeOverlapCallback * nodeCallback, const btVector3& raySource, const btVector3& rayTarget) const; void reportBoxCastOverlappingNodex(btNodeOverlapCallback * nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax) const; SIMD_FORCE_INLINE void quantize(unsigned short* out, const btVector3& point, int isMax) const { btAssert(m_useQuantization); btAssert(point.getX() <= m_bvhAabbMax.getX()); btAssert(point.getY() <= m_bvhAabbMax.getY()); btAssert(point.getZ() <= m_bvhAabbMax.getZ()); btAssert(point.getX() >= m_bvhAabbMin.getX()); btAssert(point.getY() >= m_bvhAabbMin.getY()); btAssert(point.getZ() >= m_bvhAabbMin.getZ()); btVector3 v = (point - m_bvhAabbMin) * m_bvhQuantization; ///Make sure rounding is done in a way that unQuantize(quantizeWithClamp(...)) is conservative ///end-points always set the first bit, so that they are sorted properly (so that neighbouring AABBs overlap properly) ///@todo: double-check this if (isMax) { out[0] = (unsigned short)(((unsigned short)(v.getX() + btScalar(1.)) | 1)); out[1] = (unsigned short)(((unsigned short)(v.getY() + btScalar(1.)) | 1)); out[2] = (unsigned short)(((unsigned short)(v.getZ() + btScalar(1.)) | 1)); } else { out[0] = (unsigned short)(((unsigned short)(v.getX()) & 0xfffe)); out[1] = (unsigned short)(((unsigned short)(v.getY()) & 0xfffe)); out[2] = (unsigned short)(((unsigned short)(v.getZ()) & 0xfffe)); } #ifdef DEBUG_CHECK_DEQUANTIZATION btVector3 newPoint = unQuantize(out); if (isMax) { if (newPoint.getX() < point.getX()) { printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n", newPoint.getX() - point.getX(), newPoint.getX(), point.getX()); } if (newPoint.getY() < point.getY()) { printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n", newPoint.getY() - point.getY(), newPoint.getY(), point.getY()); } if (newPoint.getZ() < point.getZ()) { printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n", newPoint.getZ() - point.getZ(), newPoint.getZ(), point.getZ()); } } else { if (newPoint.getX() > point.getX()) { printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n", newPoint.getX() - point.getX(), newPoint.getX(), point.getX()); } if (newPoint.getY() > point.getY()) { printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n", newPoint.getY() - point.getY(), newPoint.getY(), point.getY()); } if (newPoint.getZ() > point.getZ()) { printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n", newPoint.getZ() - point.getZ(), newPoint.getZ(), point.getZ()); } } #endif //DEBUG_CHECK_DEQUANTIZATION } SIMD_FORCE_INLINE void quantizeWithClamp(unsigned short* out, const btVector3& point2, int isMax) const { btAssert(m_useQuantization); btVector3 clampedPoint(point2); clampedPoint.setMax(m_bvhAabbMin); clampedPoint.setMin(m_bvhAabbMax); quantize(out, clampedPoint, isMax); } SIMD_FORCE_INLINE btVector3 unQuantize(const unsigned short* vecIn) const { btVector3 vecOut; vecOut.setValue( (btScalar)(vecIn[0]) / (m_bvhQuantization.getX()), (btScalar)(vecIn[1]) / (m_bvhQuantization.getY()), (btScalar)(vecIn[2]) / (m_bvhQuantization.getZ())); vecOut += m_bvhAabbMin; return vecOut; } ///setTraversalMode let's you choose between stackless, recursive or stackless cache friendly tree traversal. Note this is only implemented for quantized trees. void setTraversalMode(btTraversalMode traversalMode) { m_traversalMode = traversalMode; } SIMD_FORCE_INLINE QuantizedNodeArray& getQuantizedNodeArray() { return m_quantizedContiguousNodes; } SIMD_FORCE_INLINE BvhSubtreeInfoArray& getSubtreeInfoArray() { return m_SubtreeHeaders; } //////////////////////////////////////////////////////////////////// /////Calculate space needed to store BVH for serialization unsigned calculateSerializeBufferSize() const; /// Data buffer MUST be 16 byte aligned virtual bool serialize(void* o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian) const; ///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place' static btQuantizedBvh* deSerializeInPlace(void* i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian); static unsigned int getAlignmentSerializationPadding(); ////////////////////////////////////////////////////////////////////// virtual int calculateSerializeBufferSizeNew() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; virtual void deSerializeFloat(struct btQuantizedBvhFloatData & quantizedBvhFloatData); virtual void deSerializeDouble(struct btQuantizedBvhDoubleData & quantizedBvhDoubleData); //////////////////////////////////////////////////////////////////// SIMD_FORCE_INLINE bool isQuantized() { return m_useQuantization; } private: // Special "copy" constructor that allows for in-place deserialization // Prevents btVector3's default constructor from being called, but doesn't inialize much else // ownsMemory should most likely be false if deserializing, and if you are not, don't call this (it also changes the function signature, which we need) btQuantizedBvh(btQuantizedBvh & other, bool ownsMemory); }; // clang-format off // parser needs * with the name struct btBvhSubtreeInfoData { int m_rootNodeIndex; int m_subtreeSize; unsigned short m_quantizedAabbMin[3]; unsigned short m_quantizedAabbMax[3]; }; struct btOptimizedBvhNodeFloatData { btVector3FloatData m_aabbMinOrg; btVector3FloatData m_aabbMaxOrg; int m_escapeIndex; int m_subPart; int m_triangleIndex; char m_pad[4]; }; struct btOptimizedBvhNodeDoubleData { btVector3DoubleData m_aabbMinOrg; btVector3DoubleData m_aabbMaxOrg; int m_escapeIndex; int m_subPart; int m_triangleIndex; char m_pad[4]; }; struct btQuantizedBvhNodeData { unsigned short m_quantizedAabbMin[3]; unsigned short m_quantizedAabbMax[3]; int m_escapeIndexOrTriangleIndex; }; struct btQuantizedBvhFloatData { btVector3FloatData m_bvhAabbMin; btVector3FloatData m_bvhAabbMax; btVector3FloatData m_bvhQuantization; int m_curNodeIndex; int m_useQuantization; int m_numContiguousLeafNodes; int m_numQuantizedContiguousNodes; btOptimizedBvhNodeFloatData *m_contiguousNodesPtr; btQuantizedBvhNodeData *m_quantizedContiguousNodesPtr; btBvhSubtreeInfoData *m_subTreeInfoPtr; int m_traversalMode; int m_numSubtreeHeaders; }; struct btQuantizedBvhDoubleData { btVector3DoubleData m_bvhAabbMin; btVector3DoubleData m_bvhAabbMax; btVector3DoubleData m_bvhQuantization; int m_curNodeIndex; int m_useQuantization; int m_numContiguousLeafNodes; int m_numQuantizedContiguousNodes; btOptimizedBvhNodeDoubleData *m_contiguousNodesPtr; btQuantizedBvhNodeData *m_quantizedContiguousNodesPtr; int m_traversalMode; int m_numSubtreeHeaders; btBvhSubtreeInfoData *m_subTreeInfoPtr; }; // clang-format on SIMD_FORCE_INLINE int btQuantizedBvh::calculateSerializeBufferSizeNew() const { return sizeof(btQuantizedBvhData); } #endif //BT_QUANTIZED_BVH_H
411
0.974367
1
0.974367
game-dev
MEDIA
0.81538
game-dev
0.958543
1
0.958543
openframeworks/openFrameworks
1,609
addons/ofxiOS/src/utils/ofxiOSExternalDisplay.h
// // ofxiOSExternalDisplay.h // // Created by lukasz karluk on 21/03/12. // http://julapy.com // #pragma once #include "ofConstants.h" #include <TargetConditionals.h> #if TARGET_OS_IOS || (TARGET_OS_IPHONE && !TARGET_OS_TV) struct ofxiOSExternalDisplayMode{ int width; int height; float pixelAspectRatio; }; class ofxiOSExternalDisplay { public: //------------------------------------------------------- static void alertExternalDisplayConnected(); static void alertExternalDisplayDisconnected(); static void alertExternalDisplayChanged(); //------------------------------------------------------- static std::vector<ofxiOSExternalDisplayMode> getExternalDisplayModes(); static bool displayOnExternalScreen(ofxiOSExternalDisplayMode externalDisplayMode); static bool displayOnExternalScreenWithPreferredDisplayMode(); static bool displayOnDeviceScreen(); static bool mirrorOn(); static bool mirrorOff(); //------------------------------------------------------- static bool isDisplayingOnExternalScreen(); static bool isDisplayingOnDeviceScreen(); static bool isExternalScreenConnected(); static bool isMirroring(); //------------------------------------------------------- ofxiOSExternalDisplay(); ~ofxiOSExternalDisplay(); //------------------------------------------------------- virtual void externalDisplayConnected(){} virtual void externalDisplayDisconnected(){} virtual void externalDisplayChanged(){} }; #define ofxiPhoneExternalDisplay ofxiOSExternalDisplay #endif
411
0.749552
1
0.749552
game-dev
MEDIA
0.562165
game-dev,graphics-rendering
0.530378
1
0.530378
xamarin/XamarinCommunityToolkit
1,860
src/CommunityToolkit/Xamarin.CommunityToolkit/Helpers/LocalizationResourceManager.shared.cs
using System; using System.ComponentModel; using System.Globalization; using System.Resources; using System.Threading; using Xamarin.CommunityToolkit.ObjectModel; namespace Xamarin.CommunityToolkit.Helpers { #if !NETSTANDARD1_0 public class LocalizationResourceManager : ObservableObject { static readonly Lazy<LocalizationResourceManager> currentHolder = new Lazy<LocalizationResourceManager>(() => new LocalizationResourceManager()); public static LocalizationResourceManager Current => currentHolder.Value; ResourceManager? resourceManager; CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture; LocalizationResourceManager() { } public void Init(ResourceManager resource) => resourceManager = resource; public void Init(ResourceManager resource, CultureInfo initialCulture) { CurrentCulture = initialCulture; Init(resource); } public string GetValue(string text) { if (resourceManager == null) throw new InvalidOperationException($"Must call {nameof(LocalizationResourceManager)}.{nameof(Init)} first"); return resourceManager.GetString(text, CurrentCulture) ?? throw new NullReferenceException($"{nameof(text)}: {text} not found"); } public string this[string text] => GetValue(text); [Obsolete("Please, use " + nameof(CurrentCulture) + " to set culture")] [EditorBrowsable(EditorBrowsableState.Never)] public void SetCulture(CultureInfo language) => CurrentCulture = language; public CultureInfo CurrentCulture { get => currentCulture; set => SetProperty(ref currentCulture, value, null); } [Obsolete("This method is no longer needed with new implementation of " + nameof(LocalizationResourceManager) + ". Please, remove all references to it.")] [EditorBrowsable(EditorBrowsableState.Never)] public void Invalidate() => OnPropertyChanged(null); } #endif }
411
0.679649
1
0.679649
game-dev
MEDIA
0.497412
game-dev,desktop-app
0.594629
1
0.594629
IrisShaders/Iris
15,947
common/src/main/java/net/irisshaders/iris/gui/element/ShaderPackSelectionList.java
package net.irisshaders.iris.gui.element; import com.mojang.blaze3d.systems.RenderSystem; import net.irisshaders.iris.Iris; import net.irisshaders.iris.gui.GuiUtil; import net.irisshaders.iris.gui.screen.ShaderPackScreen; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ComponentPath; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractSelectionList; import net.minecraft.client.gui.navigation.FocusNavigationEvent; import net.minecraft.client.gui.navigation.ScreenRectangle; import net.minecraft.client.gui.screens.ConfirmLinkScreen; import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.List; import java.util.function.Function; public class ShaderPackSelectionList extends IrisObjectSelectionList<ShaderPackSelectionList.BaseEntry> { private static final Component PACK_LIST_LABEL = Component.translatable("pack.iris.list.label").withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY); private static final ResourceLocation MENU_LIST_BACKGROUND = ResourceLocation.withDefaultNamespace("textures/gui/menu_background.png"); private final ShaderPackScreen screen; private final TopButtonRowEntry topButtonRow; private final WatchService watcher; private final WatchKey key; private final PinnedEntry downloadButton; private boolean keyValid; private ShaderPackEntry applied = null; public ShaderPackSelectionList(ShaderPackScreen screen, Minecraft client, int width, int height, int top, int bottom, int left, int right) { super(client, width, bottom, top + 4, bottom, left, right, 20); WatchKey key1; WatchService watcher1; this.screen = screen; this.topButtonRow = new TopButtonRowEntry(this, Iris.getIrisConfig().areShadersEnabled()); this.downloadButton = new PinnedEntry(Component.literal("Download Shaders"), () -> this.minecraft.setScreen(new ConfirmLinkScreen(bl -> { if (bl) { Util.getPlatform().openUri("https://modrinth.com/shaders"); } this.minecraft.setScreen(this.screen); }, "https://modrinth.com/shaders", true)), this); try { watcher1 = FileSystems.getDefault().newWatchService(); key1 = Iris.getShaderpacksDirectory().register(watcher1, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); keyValid = true; } catch (IOException e) { Iris.logger.error("Couldn't register file watcher!", e); watcher1 = null; key1 = null; keyValid = false; } this.key = key1; this.watcher = watcher1; refresh(); } @Override public boolean keyPressed(int pContainerEventHandler0, int pInt1, int pInt2) { if (pContainerEventHandler0 == GLFW.GLFW_KEY_UP) { if (getFocused() == getFirstElement()) return true; } return super.keyPressed(pContainerEventHandler0, pInt1, pInt2); } @Override public void renderWidget(GuiGraphics pAbstractSelectionList0, int pInt1, int pInt2, float pFloat3) { if (keyValid) { for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.OVERFLOW) continue; refresh(); break; } keyValid = key.reset(); } super.renderWidget(pAbstractSelectionList0, pInt1, pInt2, pFloat3); } public void close() throws IOException { if (key != null) { key.cancel(); } if (watcher != null) { watcher.close(); } } @Override protected void renderListBackground(GuiGraphics pAbstractSelectionList0) { if (screen.listTransition.getAsFloat() < 0.02f) return; RenderSystem.enableBlend(); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, screen.listTransition.getAsFloat()); pAbstractSelectionList0.blit( MENU_LIST_BACKGROUND, this.getX(), this.getY() - 2, (float) this.getRight(), (float) (this.getBottom() + (int) this.getScrollAmount()), this.getWidth(), this.getHeight(), 32, 32 ); RenderSystem.disableBlend(); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); } @Override protected void renderListSeparators(GuiGraphics pAbstractSelectionList0) { RenderSystem.enableBlend(); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, screen.listTransition.getAsFloat()); pAbstractSelectionList0.blit(CreateWorldScreen.HEADER_SEPARATOR, this.getX(), this.getY() - 2, 0.0F, 0.0F, this.getWidth(), 2, 32, 2); pAbstractSelectionList0.blit(CreateWorldScreen.FOOTER_SEPARATOR, this.getX(), this.getBottom(), 0.0F, 0.0F, this.getWidth(), 2, 32, 2); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); RenderSystem.disableBlend(); } @Override public int getRowWidth() { return Math.min(308, width - 50); } @Override protected int getRowTop(int index) { return super.getRowTop(index) + 2; } public void refresh() { this.clearEntries(); List<String> names; try { names = Iris.getShaderpacksDirectoryManager().enumerate(); } catch (Throwable e) { Iris.logger.error("Error reading files while constructing selection UI", e); // Not translating this since it's going to be seen very rarely, // We're just trying to get more information on a seemingly untraceable bug: // - https://github.com/IrisShaders/Iris/issues/785 this.addLabelEntries( Component.empty(), Component.literal("There was an error reading your shaderpacks directory") .withStyle(ChatFormatting.RED, ChatFormatting.BOLD), Component.empty(), Component.literal("Check your logs for more information."), Component.literal("Please file an issue report including a log file."), Component.literal("If you are able to identify the file causing this, " + "please include it in your report as well."), Component.literal("Note that this might be an issue with folder " + "permissions; ensure those are correct first.") ); return; } this.addEntry(topButtonRow); if (names.isEmpty()) { this.addEntry(downloadButton); } // Only allow the enable/disable shaders button if the user has // added a shader pack. Otherwise, the button will be disabled. topButtonRow.allowEnableShadersButton = !names.isEmpty(); int index = 0; for (String name : names) { index++; addPackEntry(index, name); } this.addLabelEntries(PACK_LIST_LABEL); } public void addPackEntry(int index, String name) { ShaderPackEntry entry = new ShaderPackEntry(index, this, name); Iris.getIrisConfig().getShaderPackName().ifPresent(currentPackName -> { if (name.equals(currentPackName)) { setSelected(entry); setFocused(entry); centerScrollOn(entry); setApplied(entry); } }); this.addEntry(entry); } public void addLabelEntries(Component... lines) { for (Component text : lines) { this.addEntry(new LabelEntry(text)); } } public void select(String name) { for (int i = 0; i < getItemCount(); i++) { BaseEntry entry = getEntry(i); if (entry instanceof ShaderPackEntry && ((ShaderPackEntry) entry).packName.equals(name)) { setSelected(entry); return; } } } public ShaderPackEntry getApplied() { return this.applied; } public void setApplied(ShaderPackEntry entry) { this.applied = entry; } public TopButtonRowEntry getTopButtonRow() { return topButtonRow; } public static abstract class BaseEntry extends AbstractSelectionList.Entry<BaseEntry> { protected BaseEntry() { } } public static class LabelEntry extends BaseEntry { private final Component label; public LabelEntry(Component label) { this.label = label; } @Override public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { guiGraphics.drawCenteredString(Minecraft.getInstance().font, label, (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, 0xC2C2C2); } } public static class TopButtonRowEntry extends BaseEntry { private static final Component NONE_PRESENT_LABEL = Component.translatable("options.iris.shaders.nonePresent").withStyle(ChatFormatting.GRAY); private static final Component SHADERS_DISABLED_LABEL = Component.translatable("options.iris.shaders.disabled"); private static final Component SHADERS_ENABLED_LABEL = Component.translatable("options.iris.shaders.enabled"); private final ShaderPackSelectionList list; public boolean allowEnableShadersButton = true; public boolean shadersEnabled; public TopButtonRowEntry(ShaderPackSelectionList list, boolean shadersEnabled) { this.list = list; this.shadersEnabled = shadersEnabled; } public void setShadersEnabled(boolean shadersEnabled) { this.shadersEnabled = shadersEnabled; this.list.screen.refreshScreenSwitchButton(); } @Override public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { GuiUtil.bindIrisWidgetsTexture(); GuiUtil.drawButton(guiGraphics, x - 2, y - 2, entryWidth, entryHeight + 2, hovered, !allowEnableShadersButton); guiGraphics.drawCenteredString(Minecraft.getInstance().font, getEnableDisableLabel(), (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, 0xFFFFFF); } private Component getEnableDisableLabel() { return this.allowEnableShadersButton ? this.shadersEnabled ? SHADERS_ENABLED_LABEL : SHADERS_DISABLED_LABEL : NONE_PRESENT_LABEL; } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (this.allowEnableShadersButton) { setShadersEnabled(!this.shadersEnabled); GuiUtil.playButtonClickSound(); return true; } return false; } @Override public boolean keyPressed(int keycode, int scancode, int modifiers) { if (keycode == GLFW.GLFW_KEY_ENTER) { if (this.allowEnableShadersButton) { setShadersEnabled(!this.shadersEnabled); GuiUtil.playButtonClickSound(); return true; } } return false; } @Nullable @Override public ComponentPath nextFocusPath(FocusNavigationEvent pGuiEventListener0) { return (!isFocused()) ? ComponentPath.leaf(this) : null; } public boolean isFocused() { return this.list.getFocused() == this; } // Renders the label at an offset as to not look misaligned with the rest of the menu public static class EnableShadersButtonElement extends IrisElementRow.TextButtonElement { private int centerX; public EnableShadersButtonElement(Component text, Function<IrisElementRow.TextButtonElement, Boolean> onClick) { super(text, onClick); } @Override public void renderLabel(GuiGraphics guiGraphics, int x, int y, int width, int height, int mouseX, int mouseY, float tickDelta, boolean hovered) { int textX = this.centerX - (int) (this.font.width(this.text) * 0.5); int textY = y + (int) ((height - 8) * 0.5); guiGraphics.drawString(this.font, this.text, textX, textY, 0xFFFFFF); } } } private static class PinnedEntry extends BaseEntry { public final boolean allowPressButton = true; private final Component label; private final Runnable onClick; public PinnedEntry(Component label, Runnable onClick, ShaderPackSelectionList list) { this.label = label; this.onClick = onClick; } @Override public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { GuiUtil.bindIrisWidgetsTexture(); GuiUtil.drawButton(guiGraphics, x - 2, y - 2, entryWidth, entryHeight + 2, hovered, !allowPressButton); guiGraphics.drawCenteredString(Minecraft.getInstance().font, label, (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, 0xFFFFFF); } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (this.allowPressButton) { GuiUtil.playButtonClickSound(); onClick.run(); return false; } return false; } @Override public boolean keyPressed(int keycode, int scancode, int modifiers) { if (keycode == GLFW.GLFW_KEY_ENTER) { if (this.allowPressButton) { GuiUtil.playButtonClickSound(); onClick.run(); return false; } } return false; } } public class ShaderPackEntry extends BaseEntry { private final String packName; private final ShaderPackSelectionList list; private final int index; private ScreenRectangle bounds; private boolean focused; public ShaderPackEntry(int index, ShaderPackSelectionList list, String packName) { this.bounds = ScreenRectangle.empty(); this.packName = packName; this.list = list; this.index = index; } @Override public ScreenRectangle getRectangle() { return bounds; } public boolean isApplied() { return list.getApplied() == this; } public boolean isSelected() { return list.getSelected() == this; } public String getPackName() { return packName; } @Override public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { this.bounds = new ScreenRectangle(x, y, entryWidth, entryHeight); Font font = Minecraft.getInstance().font; int color = 0xFFFFFF; String name = packName; if (hovered) { GuiUtil.bindIrisWidgetsTexture(); GuiUtil.drawButton(guiGraphics, x - 2, y - 2, entryWidth, entryHeight + 4, hovered, false); } boolean shadersEnabled = list.getTopButtonRow().shadersEnabled; if (font.width(Component.literal(name).withStyle(ChatFormatting.BOLD)) > this.list.getRowWidth() - 3) { name = font.plainSubstrByWidth(name, this.list.getRowWidth() - 8) + "..."; } MutableComponent text = Component.literal(name); if (this.isMouseOver(mouseX, mouseY)) { text = text.withStyle(ChatFormatting.BOLD); } if (shadersEnabled && this.isApplied()) { color = 0xFFF263; } if (!shadersEnabled && !this.isMouseOver(mouseX, mouseY)) { color = 0xA2A2A2; } guiGraphics.drawCenteredString(font, text, (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, color); } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { // Only do anything on left-click if (button != 0) { return false; } return doThing(); } @Override public boolean keyPressed(int keycode, int pInt1, int pInt2) { // Only do anything on key-press if (keycode != GLFW.GLFW_KEY_ENTER) { return false; } return doThing(); } private boolean doThing() { boolean didAnything = false; // UX: If shaders are disabled, then clicking a shader in the list will also // enable shaders on apply. Previously, it was not possible to select // a pack when shaders were disabled, but this was a source of confusion // - people did not realize that they needed to enable shaders before // selecting a shader pack. if (!list.getTopButtonRow().shadersEnabled) { list.getTopButtonRow().setShadersEnabled(true); didAnything = true; } if (!this.isSelected()) { this.list.select(this.index); didAnything = true; } ShaderPackSelectionList.this.screen.setFocused(ShaderPackSelectionList.this.screen.getBottomRowOption()); return didAnything; } @Nullable @Override public ComponentPath nextFocusPath(FocusNavigationEvent pGuiEventListener0) { return (!isFocused()) ? ComponentPath.leaf(this) : null; } public boolean isFocused() { return this.list.getFocused() == this; } } }
411
0.939364
1
0.939364
game-dev
MEDIA
0.91017
game-dev
0.983949
1
0.983949
FakeFishGames/Barotrauma
44,981
Barotrauma/BarotraumaShared/SharedSource/Items/Inventory.cs
using Barotrauma.Extensions; using Barotrauma.Items.Components; using Barotrauma.Networking; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; namespace Barotrauma { partial class Inventory { public const int MaxPossibleStackSize = (1 << 6) - 1; //the max value that will fit in 6 bits, i.e 63 public const int MaxItemsPerNetworkEvent = 128; public class ItemSlot { private readonly List<Item> items = new List<Item>(MaxPossibleStackSize); public bool HideIfEmpty; public IReadOnlyList<Item> Items => items; private readonly Inventory inventory; public ItemSlot(Inventory inventory) { this.inventory = inventory; } public bool CanBePut(Item item, bool ignoreCondition = false) { if (item == null) { return false; } if (items.Count > 0) { if (!ignoreCondition) { if (item.IsFullCondition) { if (items.Any(it => !it.IsFullCondition)) { return false; } } else if (MathUtils.NearlyEqual(item.Condition, 0.0f)) { if (items.Any(it => !MathUtils.NearlyEqual(it.Condition, 0.0f))) { return false; } } else { return false; } } if (items[0].Quality != item.Quality) { return false; } if (items[0].Prefab.Identifier != item.Prefab.Identifier || items.Count + 1 > item.Prefab.GetMaxStackSize(inventory)) { return false; } } return true; } /// <summary> /// Can an instance of the item prefab be put into the slot? /// Note that if the condition and quality aren't given, they are ignored, and the method can return true even if the item can't go in the slot /// due to it being occupied by another item with a different condition or quality (which disallows stacking). /// </summary> public bool CanProbablyBePut(ItemPrefab itemPrefab, float? condition = null, int? quality = null) { if (itemPrefab == null) { return false; } if (items.Count > 0) { if (condition.HasValue) { if (MathUtils.NearlyEqual(condition.Value, 0.0f)) { if (items.Any(it => it.Condition > 0.0f)) { return false; } } else if (MathUtils.NearlyEqual(condition.Value, itemPrefab.Health)) { if (items.Any(it => !it.IsFullCondition)) { return false; } } else { return false; } } else { if (items.Any(it => !it.IsFullCondition)) { return false; } } if (quality.HasValue) { if (items[0].Quality != quality.Value) { return false; } } if (items[0].Prefab.Identifier != itemPrefab.Identifier || items.Count + 1 > itemPrefab.GetMaxStackSize(inventory)) { return false; } } return true; } /// <param name="maxStackSize">Defaults to <see cref="ItemPrefab.MaxStackSize"/> if null</param> public int HowManyCanBePut(ItemPrefab itemPrefab, int? maxStackSize = null, float? condition = null, bool ignoreItemsInSlot = false) { if (itemPrefab == null) { return 0; } maxStackSize ??= itemPrefab.GetMaxStackSize(inventory); if (items.Count > 0 && !ignoreItemsInSlot) { if (condition.HasValue) { if (MathUtils.NearlyEqual(condition.Value, 0.0f)) { if (items.Any(it => it.Condition > 0.0f)) { return 0; } } else if (MathUtils.NearlyEqual(condition.Value, itemPrefab.Health)) { if (items.Any(it => !it.IsFullCondition)) { return 0; } } else { return 0; } } else { if (items.Any(it => !it.IsFullCondition)) { return 0; } } if (items[0].Prefab.Identifier != itemPrefab.Identifier) { return 0; } return maxStackSize.Value - items.Count; } else { return maxStackSize.Value; } } public void Add(Item item) { if (item == null) { throw new InvalidOperationException("Tried to add a null item to an inventory slot."); } if (items.Count > 0) { if (items[0].Prefab.Identifier != item.Prefab.Identifier) { throw new InvalidOperationException("Tried to stack different types of items."); } else if (items.Count + 1 > item.Prefab.GetMaxStackSize(inventory)) { throw new InvalidOperationException($"Tried to add an item to a full inventory slot (stack already full, x{items.Count} {items.First().Prefab.Identifier})."); } } if (items.Contains(item)) { return; } //keep lowest-condition items at the top of the stack int index = 0; for (int i = 0; i < items.Count; i++) { if (items[i].Condition > item.Condition) { break; } index++; } items.Insert(index, item); } /// <summary> /// Removes one item from the slot /// </summary> public Item RemoveItem() { if (items.Count == 0) { return null; } var item = items[0]; items.RemoveAt(0); return item; } public void RemoveItem(Item item) { items.Remove(item); } /// <summary> /// Removes all items from the slot /// </summary> public void RemoveAllItems() { items.Clear(); } public void RemoveWhere(Func<Item, bool> predicate) { items.RemoveAll(it => predicate(it)); } public bool Any() { return items.Count > 0; } public bool Empty() { return items.Count == 0; } public Item First() { return items[0]; } public Item FirstOrDefault() { return items.FirstOrDefault(); } public Item LastOrDefault() { return items.LastOrDefault(); } public bool Contains(Item item) { return items.Contains(item); } } public readonly Entity Owner; /// <summary> /// Capacity, or the number of slots in the inventory. /// </summary> protected readonly int capacity; protected readonly ItemSlot[] slots; public bool Locked; protected float syncItemsDelay; private int extraStackSize; public int ExtraStackSize { get => extraStackSize; set => extraStackSize = MathHelper.Max(value, 0); } /// <summary> /// All items contained in the inventory. Stacked items are returned as individual instances. DO NOT modify the contents of the inventory while enumerating this list. /// </summary> public virtual IEnumerable<Item> AllItems { get { return GetAllItems(checkForDuplicates: this is CharacterInventory); } } private readonly List<Item> allItemsList = new List<Item>(); /// <summary> /// All items contained in the inventory. Allows modifying the contents of the inventory while being enumerated. /// </summary> public IEnumerable<Item> AllItemsMod { get { allItemsList.Clear(); allItemsList.AddRange(AllItems); return allItemsList; } } public int Capacity { get { return capacity; } } public static bool IsDragAndDropGiveAllowed { get { // allowed for single player if (GameMain.NetworkMember == null) { return true; } // controlled by server setting in multiplayer return GameMain.NetworkMember.ServerSettings.AllowDragAndDropGive; } } public int EmptySlotCount => slots.Count(i => !i.Empty()); public bool AllowSwappingContainedItems = true; public Inventory(Entity owner, int capacity, int slotsPerRow = 5) { this.capacity = capacity; this.Owner = owner; slots = new ItemSlot[capacity]; for (int i = 0; i < capacity; i++) { slots[i] = new ItemSlot(this); } #if CLIENT this.slotsPerRow = slotsPerRow; if (DraggableIndicator == null) { DraggableIndicator = GUIStyle.GetComponentStyle("GUIDragIndicator").GetDefaultSprite(); slotHotkeySprite = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(258, 7, 120, 120), null, 0); EquippedIndicator = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(550, 137, 87, 16), new Vector2(0.5f, 0.5f), 0); EquippedHoverIndicator = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(550, 157, 87, 16), new Vector2(0.5f, 0.5f), 0); EquippedClickedIndicator = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(550, 177, 87, 16), new Vector2(0.5f, 0.5f), 0); UnequippedIndicator = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(550, 197, 87, 16), new Vector2(0.5f, 0.5f), 0); UnequippedHoverIndicator = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(550, 217, 87, 16), new Vector2(0.5f, 0.5f), 0); UnequippedClickedIndicator = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(550, 237, 87, 16), new Vector2(0.5f, 0.5f), 0); } #endif } public IEnumerable<Item> GetAllItems(bool checkForDuplicates) { for (int i = 0; i < capacity; i++) { var items = slots[i].Items; // ReSharper disable once ForCanBeConvertedToForeach, because this is performance-sensitive code. for (int j = 0; j < items.Count; j++) { var item = items[j]; if (item == null) { #if DEBUG DebugConsole.ThrowError($"Null item in inventory {Owner.ToString() ?? "null"}, slot {i}!"); #endif continue; } if (checkForDuplicates) { bool duplicateFound = false; for (int s = 0; s < i; s++) { if (slots[s].Items.Contains(item)) { duplicateFound = true; break; } } if (!duplicateFound) { yield return item; } } else { yield return item; } } } } private void NotifyItemComponentsOfChange() { #if CLIENT if (Owner is Character character && character == Character.Controlled) { character.SelectedItem?.GetComponent<CircuitBox>()?.OnViewUpdateProjSpecific(); } #endif if (Owner is not Item it) { return; } foreach (var c in it.Components) { c.OnInventoryChanged(); } it.ParentInventory?.NotifyItemComponentsOfChange(); } /// <summary> /// Is the item contained in this inventory. Does not recursively check items inside items. /// </summary> public bool Contains(Item item) { return slots.Any(i => i.Contains(item)); } /// <summary> /// Return the first item in the inventory, or null if the inventory is empty. /// </summary> public Item FirstOrDefault() { foreach (var itemSlot in slots) { var item = itemSlot.FirstOrDefault(); if (item != null) { return item; } } return null; } /// <summary> /// Return the last item in the inventory, or null if the inventory is empty. /// </summary> public Item LastOrDefault() { for (int i = slots.Length - 1; i >= 0; i--) { var item = slots[i].LastOrDefault(); if (item != null) { return item; } } return null; } private bool IsIndexInRange(int index) { return index >= 0 && index < slots.Length; } /// <summary> /// Get the item stored in the specified inventory slot. If the slot contains a stack of items, returns the first item in the stack. /// </summary> public Item GetItemAt(int index) { if (!IsIndexInRange(index)) { return null; } return slots[index].FirstOrDefault(); } /// <summary> /// Get all the item stored in the specified inventory slot. Can return more than one item if the slot contains a stack of items. /// </summary> public IEnumerable<Item> GetItemsAt(int index) { if (!IsIndexInRange(index)) { return Enumerable.Empty<Item>(); } return slots[index].Items; } public int GetItemStackSlotIndex(Item item, int index) { if (!IsIndexInRange(index)) { return -1; } return slots[index].Items.IndexOf(item); } /// <summary> /// Find the index of the first slot the item is contained in. /// </summary> public int FindIndex(Item item) { for (int i = 0; i < capacity; i++) { if (slots[i].Contains(item)) { return i; } } return -1; } /// <summary> /// Find the indices of all the slots the item is contained in (two-hand items for example can be in multiple slots). Note that this method instantiates a new list. /// </summary> public List<int> FindIndices(Item item) { List<int> indices = new List<int>(); for (int i = 0; i < capacity; i++) { if (slots[i].Contains(item)) { indices.Add(i); } } return indices; } /// <summary> /// Returns true if the item owns any of the parent inventories. /// </summary> public virtual bool ItemOwnsSelf(Item item) { if (Owner == null) { return false; } if (Owner is not Item) { return false; } Item ownerItem = Owner as Item; if (ownerItem == item) { return true; } if (ownerItem.ParentInventory == null) { return false; } return ownerItem.ParentInventory.ItemOwnsSelf(item); } public virtual int FindAllowedSlot(Item item, bool ignoreCondition = false) { if (ItemOwnsSelf(item)) { return -1; } for (int i = 0; i < capacity; i++) { //item is already in the inventory! if (slots[i].Contains(item)) { return -1; } } for (int i = 0; i < capacity; i++) { if (slots[i].CanBePut(item, ignoreCondition)) { return i; } } return -1; } /// <summary> /// Can the item be put in the inventory (i.e. is there a suitable free slot or a stack the item can be put in). /// </summary> public bool CanBePut(Item item) { for (int i = 0; i < capacity; i++) { if (CanBePutInSlot(item, i)) { return true; } } return false; } /// <summary> /// Can the item be put in the specified slot. /// </summary> public virtual bool CanBePutInSlot(Item item, int i, bool ignoreCondition = false) { if (ItemOwnsSelf(item)) { return false; } if (!IsIndexInRange(i)) { return false; } return slots[i].CanBePut(item, ignoreCondition); } /// <summary> /// Can an instance of the item prefab be put into the inventory? /// Note that if the condition and quality aren't given, they are ignored, and the method can return true even if the item can't go in the inventory /// due to the slots being occupied by another item with a different condition or quality (which disallows stacking). /// </summary> public bool CanProbablyBePut(ItemPrefab itemPrefab, float? condition = null, int? quality = null) { for (int i = 0; i < capacity; i++) { if (CanBePutInSlot(itemPrefab, i, condition, quality)) { return true; } } return false; } public virtual bool CanBePutInSlot(ItemPrefab itemPrefab, int i, float? condition = null, int? quality = null) { if (!IsIndexInRange(i)) { return false; } return slots[i].CanProbablyBePut(itemPrefab, condition, quality); } public int HowManyCanBePut(ItemPrefab itemPrefab, float? condition = null) { int count = 0; for (int i = 0; i < capacity; i++) { count += HowManyCanBePut(itemPrefab, i, condition); } return count; } public virtual int HowManyCanBePut(ItemPrefab itemPrefab, int i, float? condition, bool ignoreItemsInSlot = false) { if (!IsIndexInRange(i)) { return 0; } return slots[i].HowManyCanBePut(itemPrefab, condition: condition, ignoreItemsInSlot: ignoreItemsInSlot); } /// <summary> /// If there is room, puts the item in the inventory and returns true, otherwise returns false /// </summary> public virtual bool TryPutItem(Item item, Character user, IEnumerable<InvSlotType> allowedSlots = null, bool createNetworkEvent = true, bool ignoreCondition = false) { int slot = FindAllowedSlot(item, ignoreCondition); if (slot < 0) { return false; } PutItem(item, slot, user, true, createNetworkEvent); return true; } public virtual bool TryPutItem(Item item, int i, bool allowSwapping, bool allowCombine, Character user, bool createNetworkEvent = true, bool ignoreCondition = false) { if (!IsIndexInRange(i)) { string thisItemStr = item?.Prefab.Identifier.Value ?? "null"; string ownerStr = "null"; if (Owner is Item ownerItem) { ownerStr = ownerItem.Prefab.Identifier.Value; } else if (Owner is Character ownerCharacter) { ownerStr = ownerCharacter.SpeciesName.Value; } string errorMsg = $"Inventory.TryPutItem failed: index was out of range (item: {thisItemStr}, inventory: {ownerStr})."; GameAnalyticsManager.AddErrorEventOnce("Inventory.TryPutItem:IndexOutOfRange", GameAnalyticsManager.ErrorSeverity.Error, errorMsg); #if DEBUG DebugConsole.ThrowError(errorMsg); #endif return false; } if (Owner == null) return false; //there's already an item in the slot if (slots[i].Any() && allowCombine) { if (slots[i].First().Combine(item, user)) { //item in the slot removed as a result of combining -> put this item in the now free slot if (!slots[i].Any()) { return TryPutItem(item, i, allowSwapping, allowCombine, user, createNetworkEvent, ignoreCondition); } return true; } } if (CanBePutInSlot(item, i, ignoreCondition)) { PutItem(item, i, user, true, createNetworkEvent); return true; } else if (slots[i].Any() && item.ParentInventory != null && allowSwapping) { var itemInSlot = slots[i].First(); if (itemInSlot.OwnInventory != null && !itemInSlot.OwnInventory.Contains(item) && itemInSlot.GetComponent<ItemContainer>()?.GetMaxStackSize(0) == 1 && itemInSlot.OwnInventory.TrySwapping(0, item, user, createNetworkEvent, swapWholeStack: false)) { return true; } return TrySwapping(i, item, user, createNetworkEvent, swapWholeStack: true) || TrySwapping(i, item, user, createNetworkEvent, swapWholeStack: false); } else { #if CLIENT if (visualSlots != null && createNetworkEvent) { visualSlots[i].ShowBorderHighlight(GUIStyle.Red, 0.1f, 0.9f); } #endif return false; } } protected virtual void PutItem(Item item, int i, Character user, bool removeItem = true, bool createNetworkEvent = true) { if (!IsIndexInRange(i)) { string errorMsg = "Inventory.PutItem failed: index was out of range(" + i + ").\n" + Environment.StackTrace.CleanupStackTrace(); GameAnalyticsManager.AddErrorEventOnce("Inventory.PutItem:IndexOutOfRange", GameAnalyticsManager.ErrorSeverity.Error, errorMsg); return; } if (Owner == null) { return; } Inventory prevInventory = item.ParentInventory; Inventory prevOwnerInventory = item.FindParentInventory(inv => inv is CharacterInventory); if (createNetworkEvent) { CreateNetworkEvent(); //also delay syncing the inventory the item was inside if (prevInventory != null && prevInventory != this) { prevInventory.syncItemsDelay = 1.0f; } } if (removeItem) { item.Drop(user, setTransform: false, createNetworkEvent: createNetworkEvent && GameMain.NetworkMember is { IsServer: true }); item.ParentInventory?.RemoveItem(item); } slots[i].Add(item); item.ParentInventory = this; #if CLIENT if (visualSlots != null) { visualSlots[i].ShowBorderHighlight(Color.White, 0.1f, 0.4f); if (selectedSlot?.Inventory == this) { selectedSlot.ForceTooltipRefresh = true; } } #endif CharacterHUD.RecreateHudTextsIfControlling(user); if (item.body != null) { item.body.Enabled = false; item.body.BodyType = FarseerPhysics.BodyType.Dynamic; item.SetTransform(item.SimPosition, rotation: 0.0f, findNewHull: false); //update to refresh the interpolated draw rotation and position (update doesn't run on disabled bodies) item.body.UpdateDrawPosition(interpolate: false); } #if SERVER if (prevOwnerInventory is CharacterInventory characterInventory && characterInventory != this && Owner == user) { var client = GameMain.Server?.ConnectedClients?.Find(cl => cl.Character == user); GameMain.Server?.KarmaManager.OnItemTakenFromPlayer(characterInventory, client, item); } #endif if (this is CharacterInventory) { if (prevInventory != this && prevOwnerInventory != this) { HumanAIController.ItemTaken(item, user); } } else { if (item.FindParentInventory(inv => inv is CharacterInventory) is CharacterInventory currentInventory) { if (currentInventory != prevInventory) { HumanAIController.ItemTaken(item, user); } } } NotifyItemComponentsOfChange(); } public bool IsEmpty() { for (int i = 0; i < capacity; i++) { if (slots[i].Any()) { return false; } } return true; } /// <summary> /// Is there room to put more items in the inventory. Doesn't take stacking into account by default. /// </summary> /// <param name="takeStacksIntoAccount">If true, the inventory is not considered full if all the stacks are not full.</param> public virtual bool IsFull(bool takeStacksIntoAccount = false) { if (takeStacksIntoAccount) { for (int i = 0; i < capacity; i++) { if (!slots[i].Any()) { return false; } var item = slots[i].FirstOrDefault(); if (slots[i].Items.Count < item.Prefab.GetMaxStackSize(this)) { return false; } } } else { for (int i = 0; i < capacity; i++) { if (!slots[i].Any()) { return false; } } } return true; } protected bool TrySwapping(int index, Item item, Character user, bool createNetworkEvent, bool swapWholeStack) { if (item?.ParentInventory == null || !slots[index].Any()) { return false; } if (slots[index].Items.Any(it => !it.IsInteractable(user))) { return false; } if (!AllowSwappingContainedItems) { return false; } //swap to InvSlotType.Any if possible Inventory otherInventory = item.ParentInventory; bool otherIsEquipped = false; int otherIndex = -1; for (int i = 0; i < otherInventory.slots.Length; i++) { if (!otherInventory.slots[i].Contains(item)) { continue; } if (otherInventory is CharacterInventory characterInventory) { if (characterInventory.SlotTypes[i] == InvSlotType.Any) { otherIndex = i; break; } else { otherIsEquipped = true; } } } if (otherIndex == -1) { otherIndex = otherInventory.FindIndex(item); if (otherIndex == -1) { DebugConsole.ThrowError("Something went wrong when trying to swap items between inventory slots: couldn't find the source item from it's inventory.\n" + Environment.StackTrace.CleanupStackTrace()); return false; } } List<Item> existingItems = new List<Item>(); if (swapWholeStack) { existingItems.AddRange(slots[index].Items); for (int j = 0; j < capacity; j++) { if (existingItems.Any(existingItem => slots[j].Contains(existingItem))) { slots[j].RemoveAllItems(); } } } else { existingItems.Add(slots[index].FirstOrDefault()); for (int j = 0; j < capacity; j++) { if (existingItems.Any(existingItem => slots[j].Contains(existingItem))) { slots[j].RemoveItem(existingItems.First()); } } } List<Item> stackedItems = new List<Item>(); if (swapWholeStack) { for (int j = 0; j < otherInventory.capacity; j++) { // in case the item is in multiple slots like OuterClothes | InnerClothes, prevent it from being added twice to the list if (otherInventory.slots[j].Contains(item) && !stackedItems.Contains(item)) { stackedItems.AddRange(otherInventory.slots[j].Items); otherInventory.slots[j].RemoveAllItems(); } } } else if (!stackedItems.Contains(item)) { stackedItems.Add(item); otherInventory.slots[otherIndex].RemoveItem(item); } bool swapSuccessful = false; if (otherIsEquipped) { swapSuccessful = stackedItems.Distinct().All(stackedItem => TryPutItem(stackedItem, index, false, false, user, createNetworkEvent)) && (existingItems.All(existingItem => otherInventory.TryPutItem(existingItem, otherIndex, false, false, user, createNetworkEvent)) || existingItems.Count == 1 && otherInventory.TryPutItem(existingItems.First(), user, CharacterInventory.AnySlot, createNetworkEvent)); } else { swapSuccessful = (existingItems.All(existingItem => otherInventory.TryPutItem(existingItem, otherIndex, false, false, user, createNetworkEvent)) || existingItems.Count == 1 && otherInventory.TryPutItem(existingItems.First(), user, CharacterInventory.AnySlot, createNetworkEvent)) && stackedItems.Distinct().All(stackedItem => TryPutItem(stackedItem, index, false, false, user, createNetworkEvent)); if (!swapSuccessful && existingItems.Count == 1 && existingItems[0].AllowDroppingOnSwapWith(item)) { if (!(existingItems[0].Container?.ParentInventory is CharacterInventory characterInv) || !characterInv.TryPutItem(existingItems[0], user, new List<InvSlotType>() { InvSlotType.Any })) { existingItems[0].Drop(user, createNetworkEvent); } swapSuccessful = stackedItems.Distinct().Any(stackedItem => TryPutItem(stackedItem, index, false, false, user, createNetworkEvent)); #if CLIENT if (swapSuccessful) { SoundPlayer.PlayUISound(GUISoundType.DropItem); if (otherInventory.visualSlots != null && otherIndex > -1) { otherInventory.visualSlots[otherIndex].ShowBorderHighlight(Color.Transparent, 0.1f, 0.1f); } } #endif } } //if the item in the slot can be moved to the slot of the moved item if (swapSuccessful) { System.Diagnostics.Debug.Assert(slots[index].Contains(item), "Something when wrong when swapping items, item is not present in the inventory."); System.Diagnostics.Debug.Assert(!existingItems.Any(it => !it.Prefab.AllowDroppingOnSwap && !otherInventory.Contains(it)), "Something when wrong when swapping items, item is not present in the other inventory."); #if CLIENT if (visualSlots != null) { for (int j = 0; j < capacity; j++) { if (slots[j].Contains(item)) { visualSlots[j].ShowBorderHighlight(GUIStyle.Green, 0.1f, 0.9f); } } } if (otherInventory.visualSlots != null) { for (int j = 0; j < otherInventory.capacity; j++) { if (otherInventory.slots[j].Contains(existingItems.FirstOrDefault())) { otherInventory.visualSlots[j].ShowBorderHighlight(GUIStyle.Green, 0.1f, 0.9f); } } } #endif return true; } else //swapping the items failed -> move them back to where they were { if (swapWholeStack) { foreach (Item stackedItem in stackedItems) { for (int j = 0; j < capacity; j++) { if (slots[j].Contains(stackedItem)) { slots[j].RemoveItem(stackedItem); }; } } foreach (Item existingItem in existingItems) { for (int j = 0; j < otherInventory.capacity; j++) { if (otherInventory.slots[j].Contains(existingItem)) { otherInventory.slots[j].RemoveItem(existingItem); } } } } else { for (int j = 0; j < capacity; j++) { if (slots[j].Contains(item)) { slots[j].RemoveWhere(it => existingItems.Contains(it) || stackedItems.Contains(it)); } } for (int j = 0; j < otherInventory.capacity; j++) { if (otherInventory.slots[j].Contains(existingItems.FirstOrDefault())) { otherInventory.slots[j].RemoveWhere(it => existingItems.Contains(it) || stackedItems.Contains(it)); } } } if (otherIsEquipped) { TryPutAndForce(existingItems, this, index); TryPutAndForce(stackedItems, otherInventory, otherIndex); } else { TryPutAndForce(stackedItems, otherInventory, otherIndex); TryPutAndForce(existingItems, this, index); } void TryPutAndForce(IEnumerable<Item> items, Inventory inventory, int slotIndex) { foreach (var item in items) { if (!inventory.TryPutItem(item, slotIndex, false, false, user, createNetworkEvent, ignoreCondition: true) && !inventory.GetItemsAt(slotIndex).Contains(item)) { inventory.ForceToSlot(item, slotIndex); } } } if (createNetworkEvent) { CreateNetworkEvent(); otherInventory.CreateNetworkEvent(); } #if CLIENT if (visualSlots != null) { for (int j = 0; j < capacity; j++) { if (slots[j].Contains(existingItems.FirstOrDefault())) { visualSlots[j].ShowBorderHighlight(GUIStyle.Red, 0.1f, 0.9f); } } } #endif return false; } } public void CreateNetworkEvent() { if (GameMain.NetworkMember == null) { return; } if (GameMain.NetworkMember.IsClient) { syncItemsDelay = 1.0f; } //split into multiple events because one might not be enough to fit all the items List<Range> slotRanges = new List<Range>(); int startIndex = 0; int itemCount = 0; for (int i = 0; i < capacity; i++) { int count = slots[i].Items.Count; if (itemCount + count > MaxItemsPerNetworkEvent || i == capacity - 1) { slotRanges.Add(new Range(startIndex, i + 1)); startIndex = i + 1; itemCount = 0; } itemCount += count; } foreach (var slotRange in slotRanges) { CreateNetworkEvent(slotRange); } } protected virtual void CreateNetworkEvent(Range slotRange) { } public Item FindItem(Func<Item, bool> predicate, bool recursive) { Item match = AllItems.FirstOrDefault(predicate); if (match == null && recursive) { foreach (var item in AllItems) { if (item?.OwnInventory == null) { continue; } match = item.OwnInventory.FindItem(predicate, recursive: true); if (match != null) { return match; } } } return match; } public List<Item> FindAllItems(Func<Item, bool> predicate = null, bool recursive = false, List<Item> list = null) { list ??= new List<Item>(); foreach (var item in AllItems) { if (predicate == null || predicate(item)) { list.Add(item); } if (recursive) { item.OwnInventory?.FindAllItems(predicate, recursive: true, list); } } return list; } public Item FindItemByTag(Identifier tag, bool recursive = false) { if (tag.IsEmpty) { return null; } return FindItem(i => i.HasTag(tag), recursive); } public Item FindItemByIdentifier(Identifier identifier, bool recursive = false) { if (identifier.IsEmpty) { return null; } return FindItem(i => i.Prefab.Identifier == identifier, recursive); } public virtual void RemoveItem(Item item) { if (item == null) { return; } //go through the inventory and remove the item from all slots for (int n = 0; n < capacity; n++) { if (!slots[n].Contains(item)) { continue; } slots[n].RemoveItem(item); item.ParentInventory = null; #if CLIENT if (visualSlots != null) { visualSlots[n].ShowBorderHighlight(Color.White, 0.1f, 0.4f); if (selectedSlot?.Inventory == this) { selectedSlot.ForceTooltipRefresh = true; } } #endif CharacterHUD.RecreateHudTextsIfFocused(item); } NotifyItemComponentsOfChange(); } /// <summary> /// Forces an item to a specific slot. Doesn't remove the item from existing slots/inventories or do any other sanity checks, use with caution! /// </summary> public void ForceToSlot(Item item, int index) { slots[index].Add(item); item.ParentInventory = this; bool equipped = (this as CharacterInventory)?.Owner is Character character && character.HasEquippedItem(item); if (item.body != null && !equipped) { item.body.Enabled = false; item.body.BodyType = FarseerPhysics.BodyType.Dynamic; } } /// <summary> /// Removes an item from a specific slot. Doesn't do any sanity checks, use with caution! /// </summary> public void ForceRemoveFromSlot(Item item, int index) { slots[index].RemoveItem(item); } public bool IsInSlot(Item item, int index) { if (!IsIndexInRange(index)) { return false; } return slots[index].Contains(item); } public bool IsSlotEmpty(int index) { if (!IsIndexInRange(index)) { return false; } return slots[index].Empty(); } public void SharedRead(IReadMessage msg, List<ushort>[] receivedItemIds, out bool readyToApply) { byte start = msg.ReadByte(); byte end = msg.ReadByte(); //if we received the first chunk of item IDs, clear the rest //to ensure we don't have anything outdated in the list - we're about to receive the rest of the IDs next if (start == 0) { for (int i = 0; i < capacity; i++) { receivedItemIds[i] = null; } } for (int i = start; i < end; i++) { var newItemIds = new List<ushort>(); int itemCount = msg.ReadRangedInteger(0, MaxPossibleStackSize); for (int j = 0; j < itemCount; j++) { newItemIds.Add(msg.ReadUInt16()); } receivedItemIds[i] = newItemIds; } //if all IDs haven't been received yet (chunked into multiple events?) //don't apply the state yet readyToApply = !receivedItemIds.Contains(null); } public void SharedWrite(IWriteMessage msg, Range slotRange) { int start = slotRange.Start.Value; int end = slotRange.End.Value; msg.WriteByte((byte)start); msg.WriteByte((byte)end); for (int i = start; i < end; i++) { msg.WriteRangedInteger(slots[i].Items.Count, 0, MaxPossibleStackSize); for (int j = 0; j < Math.Min(slots[i].Items.Count, MaxPossibleStackSize); j++) { var item = slots[i].Items[j]; msg.WriteUInt16(item?.ID ?? (ushort)0); } } } /// <summary> /// Deletes all items inside the inventory (and also recursively all items inside the items) /// </summary> public void DeleteAllItems() { for (int i = 0; i < capacity; i++) { if (!slots[i].Any()) { continue; } foreach (Item item in slots[i].Items) { foreach (ItemContainer itemContainer in item.GetComponents<ItemContainer>()) { itemContainer.Inventory.DeleteAllItems(); } } slots[i].Items.ForEachMod(it => it.Remove()); slots[i].RemoveAllItems(); } } } }
411
0.953203
1
0.953203
game-dev
MEDIA
0.848472
game-dev
0.936588
1
0.936588
PolyMarsDev/Snake-DS
7,294
nflib/include/nf_sprite3d.h
#ifdef __cplusplus extern "C" { #endif #ifndef __NF_SPRITE3D_H__ #define __NF_SPRITE3D_H__ // NightFox LIB - Include de funciones 3D // Requiere DevkitARM // Codigo por Cesar Rincon "NightFox" // http://www.nightfoxandco.com/ // Version 20140413 // Includes devKitPro #include <nds.h> ////////////////////////////////// // Defines y variables globales // ////////////////////////////////// // Numero maximo de sprites en pantalla #define NF_3DSPRITES 256 // Estructura de control de los sprites 3d typedef struct { s16 x; // Coordenada X s16 y; // Coordenada Y s16 z; // Coordenada Z s16 rx; // Rotacion Eje X (-512/0/512) << 6 s16 ry; // Rotacion Eje Y (-512/0/512) << 6 s16 rz; // Rotacion Eje Z (-512/0/512) << 6 bool rot; // Rotacion en uso u16 sx; // Escala X (0/64/512) << 6 u16 sy; // Escala Y (0/64/512) << 6 bool scale; // Escalado en uso s16 width; // Ancho del sprite s16 height; // Alto del sprite bool inuse; // Esta en uso? bool show; // Debe mostrarse el sprite? u32 gfx_tex_format; // Guarda el formato de la textura u32 gfx; // Direccion donde esta almacenado el grafico en VRAM u16 gfxid; // Id de Gfx usado u16 frame; // Frame actual u16 newframe; // Frame al que cambiar u16 framesize; // Tamao del frame (en bytes) u16 lastframe; // Ultimo frame u32 gfx_pal_format; // Guarda el formato de la paleta u32 pal; // Direccion donde esta almacenada la paleta en VRAM u16 palid; // Id de la paleta usada u16 prio; // Prioridad de dibujado del sprite u8 poly_id; // Identificador unico para el Alpha (0 por defecto, 63 prohibido) u8 alpha; // Nivel de alpha (0 - 31) (31 por defecto) } NF_TYPE_3DSPRITE_INFO; extern NF_TYPE_3DSPRITE_INFO NF_3DSPRITE[NF_3DSPRITES]; // Estructura de control Texturas en VRAM typedef struct { u32 size; // Tamao (en bytes) del Gfx u16 width; // Ancho del Gfx u16 height; // Altura del Gfx u32 address; // Posicion en la VRAM u16 ramid; // Numero de Slot en RAM del que provienes u16 framesize; // Tamao del frame (en bytes) u16 lastframe; // Ultimo frame bool keepframes; // Si es un Sprite animado, debes de mantener los frames en RAM ? bool inuse; // Disponibilidat del Slot } NF_TYPE_TEX256VRAM_INFO; extern NF_TYPE_TEX256VRAM_INFO NF_TEX256VRAM[NF_3DSPRITES]; // Estructura de control de las paletas en VRAM typedef struct { bool inuse; // Slot en uso u8 ramslot; // Paleta original en RAM } NF_TYPE_3DSPRPALSLOT_INFO; extern NF_TYPE_3DSPRPALSLOT_INFO NF_TEXPALSLOT[32]; // Define la esturctura de control de la VRAM para Sprites 3d typedef struct { s32 free; // Memoria VRAM libre u32 next; // Siguiente posicion libre u32 last; // Ultima posicion usada u32 pos[NF_3DSPRITES]; // Posicion en VRAM para reusar despues de un borrado u32 size[NF_3DSPRITES]; // Tamao del bloque libre para reusar u16 deleted; // Numero de bloques borrados s32 fragmented; // Memoria VRAM fragmentada s32 inarow; // Memoria VRAM contigua } NF_TYPE_TEXVRAM_INFO; extern NF_TYPE_TEXVRAM_INFO NF_TEXVRAM; // Informacion VRAM de texturas // Define la estructura de control de los sprites 3d creados typedef struct { s16 total; // Numero de sprites creados u16 id[NF_3DSPRITES]; // ID del Sprite u16 bck[NF_3DSPRITES]; // Backup del ID } NF_TYPE_CREATED_3DSPRITE_INFO; extern NF_TYPE_CREATED_3DSPRITE_INFO NF_CREATED_3DSPRITE; // Funcion NF_Init3dSpriteSys(); void NF_Init3dSpriteSys(void); // Inicializa el sistema de Sprites en 3D // Funcion NF_Vram3dSpriteGfx(); void NF_Vram3dSpriteGfx(u16 ram, u16 vram, bool keepframes); // Transfiere un grafico de la RAM a la VRAM // Funcion NF_Free3dSpriteGfx(); void NF_Free3dSpriteGfx(u16 id); // Elimina de la VRAM un grafico de texturas y desfragmenta la VRAM si es necesario // Funcion NF_Vram3dSpriteGfxDefrag(); void NF_Vram3dSpriteGfxDefrag(void); // Desfragmenta la VRAM usada para texturas // Funcion NF_Vram3dSpritePal(); void NF_Vram3dSpritePal(u8 id, u8 slot); // Copia una paleta a la VRAM // Funcion NF_Create3dSprite(); void NF_Create3dSprite(u16 id, u16 gfx, u16 pal, s16 x, s16 y); // Crea un Sprite 3D en las coordenadas indicadas // Funcion NF_Delete3dSprite(); void NF_Delete3dSprite(u16 id); // Borra el Sprite con la ID indicada // Funcion NF_Sort3dSprites(); void NF_Sort3dSprites(void); // Reordena la cola de Sprites 3D creados de menor a mayor segun su ID // Los Sprites con numeros mas bajos tienen prioridad. // Funcion NF_Set3dSpritePriority(); void NF_Set3dSpritePriority(u16 id, u16 prio); // Cambia la prioridad del Sprite // Funcion NF_Swap3dSpritePriority(); void NF_Swap3dSpritePriority(u16 id_a, u16 id_b); // Intercambia la prioridad de dos Sprites // Funcion NF_Move3dSprite(); void NF_Move3dSprite(u16 id, s16 x, s16 y); // Mueve el Sprite seleccionado a las coordenadas dadas // Funcion NF_Show3dSprite(); void NF_Show3dSprite(u16 id, bool show); // Muestra u oculta el sprite con la id indicada // Funcion NF_Set3dSpriteFrame(); void NF_Set3dSpriteFrame(u16 id, u16 frame); // Cambia el frame visible del sprite indicado // Funcion NF_Draw3dSprites(); void NF_Draw3dSprites(void); // Dibuja en pantalla todos los sprites creados // Funcion NF_Update3dSpritesGfx(); void NF_Update3dSpritesGfx(void); // Actualiza si es necesario las texturas de los sprites animados // Funcion NF_Rotate3dSprite(); void NF_Rotate3dSprite(u16 id, s16 x, s16 y, s16 z); // Rota el Sprite sobre los ejes indicados (-512/0/512) // Funcion NF_Scale3dSprite(); void NF_Scale3dSprite(u16 id, u16 x, u16 y); // Escala el sprite al tamao indicado (0/64/512) // Funcion NF_Blend3dSprite(); void NF_Blend3dSprite(u8 sprite, u8 poly_id, u8 alpha); // Habilita y cambia el nivel de alpha de el sprite 3d indicado. Para que la transparencia // sea efectiva entre Sprites, debes especificar un poly_id diferente para cada sprite // (entre 1 y 62). El rango de alpha es de 0 a 31, siendo 31 opaco. Para eliminar la // transparencia, selecciona un valor para alpha de 31 o especifica como poly_id el n 0. // Funcion NF_3dSpritesLayer(); void NF_3dSpritesLayer(u8 layer); // Selecciona la capa en la que se dibujaran los Sprites 3D. (0 - 3) // En realidad los Sprites 3D siempre se dibujan sobre la CAPA 0, esta funcion solo cambia // la prioridad de esta capa sobre las demas. // Funcion NF_3dSpriteEditPalColor(); void NF_3dSpriteEditPalColor(u8 pal, u8 number, u8 r, u8 g, u8 b); // Modifica los valores de la paleta seleccionada. Las modificaciones se efectuan // sobre la copia en RAM, por lo que los cambios no seran visibles hasta que se // transfiera la paleta a la VRAM // Funcion NF_3dSpriteUpdatePalette(); void NF_3dSpriteUpdatePalette(u8 pal); // Actualiza la paleta en VRAM con la copia que se encuentra en la RAM // Funcion NF_3dSpriteGetPalColor(); void NF_3dSpriteGetPalColor(u8 pal, u8 number, u8* r, u8* g, u8* b); // Obtiene el valor de un color de la paleta que se encuentra en la RAM // Funcion NF_3dSpriteSetDeep(); void NF_3dSpriteSetDeep(u8 id, s16 z); // Cambia la profuncidad de dibujado (z) del sprite (-512/0/512), // siendo -512 el punto mas cercano, 0 el centro por defecto // y 512 el punto mas lejano. #endif #ifdef __cplusplus } #endif
411
0.735306
1
0.735306
game-dev
MEDIA
0.659777
game-dev,graphics-rendering
0.866555
1
0.866555
magefree/mage
1,159
Mage.Server.Plugins/Mage.Player.AIMCTS/src/mage/player/ai/SelectAttackersNextAction.java
package mage.player.ai; import mage.game.Game; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static mage.player.ai.MCTSNode.getAttacks; public class SelectAttackersNextAction implements MCTSNodeNextAction{ @Override public List<MCTSNode> performNextAction(MCTSNode node, MCTSPlayer player, Game game, String fullStateValue) { List<MCTSNode> children = new ArrayList<>(); List<List<UUID>> attacks; if (!MCTSNode.USE_ACTION_CACHE) attacks = player.getAttacks(game); else attacks = getAttacks(player, fullStateValue, game); UUID defenderId = game.getOpponents(player.getId(), true).iterator().next(); for (List<UUID> attack: attacks) { Game sim = game.createSimulationForAI(); MCTSPlayer simPlayer = (MCTSPlayer) sim.getPlayer(player.getId()); for (UUID attackerId: attack) { simPlayer.declareAttacker(attackerId, defenderId, sim, false); } sim.resume(); children.add(new MCTSNode(node, sim, sim.getCombat())); } return children; } }
411
0.797199
1
0.797199
game-dev
MEDIA
0.92761
game-dev
0.953992
1
0.953992
kennethreitz/context
2,473
_reports/infant_mortality.ll
/* * @progname infant_mortality.ll * @version 1 * @author Eggert * @category * @output Text * @description This program finds families that have lost multiple children. You give it the threshold for the number of young deaths, and the threshold for the age at death, and it finds all the appropriate families. infant_mortality - a LifeLines program by Jim Eggert (eggertj@atc.ll.mit.edu) Version 1, 19 September 1994 */ global(yob) global(yod) proc main() { getintmsg(numthresh,"Enter threshold for number of young deaths") getintmsg(agethresh,"Enter threshold for age at death") forfam(family,fnum) { if (ge(nchildren(family),numthresh)) { set(countdeaths,0) set(maxageatdeath,0) children(family,child,cnum) { call get_dyear(child) if (yod) { call get_byear(child) if (yob) { set(ageatdeath,sub(yod,yob)) if (le(ageatdeath,agethresh)) { set(countdeaths,add(countdeaths,1)) if (gt(ageatdeath,maxageatdeath)) { set(maxageatdeath,ageatdeath) } } } } } if (ge(countdeaths,numthresh)) { key(family) " " name(husband(family)) " and " name(wife(family)) "\nlost " d(countdeaths) " children by the age of " d(maxageatdeath) ".\n" children(family,child,cnum) { call get_byear(child) call get_dyear(child) name(child) " (" if (yob) { d(yob) } "-" if (yod) { d(yod) } ") " if (and(yob,yod)) { d(sub(yod,yob)) } "\n" } "\n" } } } } proc get_dyear(person) { set(yod,0) if (d,death(person)) { extractdate(d,dod,mod,yod) } if (not(yod)) { if (d,burial(person)) { extractdate(d,dod,mod,yod) } } } proc get_byear(person) { set(yob,0) if (b,birth(person)) { extractdate(b,dob,mob,yob) } if (not(yob)) { if (b,baptism(person)) { extractdate(b,dob,mob,yob) } } }
411
0.838194
1
0.838194
game-dev
MEDIA
0.439747
game-dev
0.937006
1
0.937006
betidestudio/SteamIntegrationKit
2,167
Source/SteamIntegrationKit/Functions/Sessions/HostMigrationSubsystem.cpp
// Copyright (c) 2024 Betide Studio. All Rights Reserved. #include "HostMigrationSubsystem.h" #include "Async/Async.h" void UHostMigrationSubsystem::StartHostMigration(FSIK_SteamId LobbyId) { #if (WITH_ENGINE_STEAM && ONLINESUBSYSTEMSTEAM_PACKAGE) || (WITH_STEAMKIT && !WITH_ENGINE_STEAM) if(!LobbyId.GetSteamID().IsValid()) { UE_LOG(LogTemp, Error, TEXT("Invalid LobbyId")); return; } CurrentLobbyId = LobbyId; #endif } UHostMigrationSubsystem::UHostMigrationSubsystem() { #if (WITH_ENGINE_STEAM && ONLINESUBSYSTEMSTEAM_PACKAGE) || (WITH_STEAMKIT && !WITH_ENGINE_STEAM) m_CallbackLobbyDataUpdate.Register(this, &UHostMigrationSubsystem::OnLobbyDataUpdateCallback); if(IsRunningDedicatedServer()) { m_CallbackLobbyDataUpdate.SetGameserverFlag(); } #endif } UHostMigrationSubsystem::~UHostMigrationSubsystem() { #if (WITH_ENGINE_STEAM && ONLINESUBSYSTEMSTEAM_PACKAGE) || (WITH_STEAMKIT && !WITH_ENGINE_STEAM) m_CallbackLobbyDataUpdate.Unregister(); #endif } #if (WITH_ENGINE_STEAM && ONLINESUBSYSTEMSTEAM_PACKAGE) || (WITH_STEAMKIT && !WITH_ENGINE_STEAM) void UHostMigrationSubsystem::OnLobbyDataUpdateCallback(LobbyDataUpdate_t* pParam) { if(!SteamMatchmaking() || !SteamUser()) { return; } if(CurrentLobbyId.GetSteamID().IsValid() == false) { return; } if(pParam->m_ulSteamIDLobby != pParam->m_ulSteamIDMember) { return; } if(pParam->m_ulSteamIDLobby != CurrentLobbyId.Result) { return; } if(SteamMatchmaking()->GetLobbyOwner(CurrentLobbyId.GetSteamID()) == CurrentOwner.GetSteamID()) { return; } CurrentOwner = SteamMatchmaking()->GetLobbyOwner(CurrentLobbyId.GetSteamID()); if(CurrentOwner.GetSteamID() == SteamUser()->GetSteamID()) { uint32 Var_ServerIP; uint16 Var_ServerPort = 0; CSteamID Var_SteamID; if(SteamMatchmaking()->GetLobbyGameServer(CurrentLobbyId.GetSteamID(), &Var_ServerIP, &Var_ServerPort, &Var_SteamID)) { if(Var_SteamID.IsValid()) { SteamMatchmaking()->SetLobbyGameServer(CurrentLobbyId.GetSteamID(), 0, 0, CurrentOwner.GetSteamID()); AsyncTask(ENamedThreads::GameThread, [this]() { OnHostMigration.Broadcast(CurrentLobbyId, true); }); } } } } #endif
411
0.868438
1
0.868438
game-dev
MEDIA
0.380984
game-dev
0.852581
1
0.852581
TheAnswer/Core3
2,369
MMOCoreORB/src/server/zone/objects/creature/commands/UnfreezePlayerCommand.h
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #ifndef UNFREEZEPLAYERCOMMAND_H_ #define UNFREEZEPLAYERCOMMAND_H_ #include "server/zone/objects/scene/SceneObject.h" #include "templates/params/creature/CreatureState.h" class UnfreezePlayerCommand : public QueueCommand { public: UnfreezePlayerCommand(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; if (!creature->isPlayerCreature()) return GENERALERROR; String syntaxerror = "Invalid arguments: /unfreezePlayer <firstname>"; ManagedReference<SceneObject* > object = server->getZoneServer()->getObject(target); ManagedReference<CreatureObject* > targetPlayer = nullptr; CreatureObject* player = cast<CreatureObject*>(creature); StringTokenizer args(arguments.toString()); if (object == nullptr || !object->isPlayerCreature()) { String firstName; if (args.hasMoreTokens()) { args.getStringToken(firstName); targetPlayer = server->getZoneServer()->getPlayerManager()->getPlayer(firstName); } } else { targetPlayer = cast<CreatureObject*>(object.get()); } if (targetPlayer == nullptr) { player->sendSystemMessage(syntaxerror); return INVALIDPARAMETERS; } ManagedReference<PlayerObject*> targetGhost = targetPlayer->getPlayerObject(); if (targetGhost == nullptr) { player->sendSystemMessage(syntaxerror); return INVALIDPARAMETERS; } try { Locker playerlocker(targetPlayer); if (targetGhost->isMuted()) { targetGhost->setMutedState(false); } String mutedResonse = ""; targetGhost->setMutedReason(mutedResonse); targetPlayer->removeStateBuff(CreatureState::FROZEN); targetPlayer->clearState(CreatureState::FROZEN, true); targetPlayer->setSpeedMultiplierBase(1.f, true); targetPlayer->sendSystemMessage("You have been unfrozen and unmuted by \'" + player->getFirstName() + "\'"); player->sendSystemMessage(targetPlayer->getFirstName() + " has been unfrozen and unmuted."); } catch (Exception& e) { player->sendSystemMessage(syntaxerror); } return SUCCESS; } }; #endif //UNFREEZEPLAYERCOMMAND_H_
411
0.935046
1
0.935046
game-dev
MEDIA
0.670502
game-dev
0.95824
1
0.95824
SalomePlatform/shaper
1,921
src/BuildPlugin/BuildPlugin_CompSolid.h
// Copyright (C) 2017-2025 CEA, EDF // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // #ifndef BuildPlugin_CompSolid_H_ #define BuildPlugin_CompSolid_H_ #include "BuildPlugin.h" #include "BuildPlugin_Solid.h" /// \class BuildPlugin_CompSolid /// \ingroup Plugins /// \brief Feature for creation of compsolid from solids or compsolids. class BuildPlugin_CompSolid: public BuildPlugin_Solid { public: /// Use plugin manager for features creation BuildPlugin_CompSolid(); /// Feature kind. inline static const std::string& ID() { static const std::string MY_ID("CompSolid"); return MY_ID; } /// Attribute name of base objects. inline static const std::string& BASE_OBJECTS_ID() { static const std::string MY_BASE_OBJECTS_ID("base_objects"); return MY_BASE_OBJECTS_ID; } /// \return the kind of a feature. BUILDPLUGIN_EXPORT virtual const std::string& getKind() { static std::string MY_KIND = BuildPlugin_CompSolid::ID(); return MY_KIND; } /// Request for initialization of data model of the feature: adding all attributes. BUILDPLUGIN_EXPORT virtual void initAttributes(); }; #endif
411
0.953395
1
0.953395
game-dev
MEDIA
0.319601
game-dev
0.674281
1
0.674281
golaced/RL_Boy
33,066
下位机代码/Linux/control_task2/yaml-cpp/test/gtest-1.10.0/googletest/include/gtest/internal/gtest-param-util.h
// Copyright 2008 Google 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: // // * 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. // Type and function utilities for implementing parameterized tests. // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #include <ctype.h> #include <cassert> #include <iterator> #include <memory> #include <set> #include <tuple> #include <utility> #include <vector> #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" #include "gtest/gtest-printers.h" namespace testing { // Input to a parameterized test name generator, describing a test parameter. // Consists of the parameter value and the integer parameter index. template <class ParamType> struct TestParamInfo { TestParamInfo(const ParamType& a_param, size_t an_index) : param(a_param), index(an_index) {} ParamType param; size_t index; }; // A builtin parameterized test name generator which returns the result of // testing::PrintToString. struct PrintToStringParamName { template <class ParamType> std::string operator()(const TestParamInfo<ParamType>& info) const { return PrintToString(info.param); } }; namespace internal { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // Utility Functions // Outputs a message explaining invalid registration of different // fixture class for the same test suite. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, CodeLocation code_location); template <typename> class ParamGeneratorInterface; template <typename> class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface<T>. template <typename T> class ParamIteratorInterface { public: virtual ~ParamIteratorInterface() {} // A pointer to the base generator instance. // Used only for the purposes of iterator comparison // to make sure that two iterators belong to the same generator. virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0; // Advances iterator to point to the next element // provided by the generator. The caller is responsible // for not calling Advance() on an iterator equal to // BaseGenerator()->End(). virtual void Advance() = 0; // Clones the iterator object. Used for implementing copy semantics // of ParamIterator<T>. virtual ParamIteratorInterface* Clone() const = 0; // Dereferences the current iterator and provides (read-only) access // to the pointed value. It is the caller's responsibility not to call // Current() on an iterator equal to BaseGenerator()->End(). // Used for implementing ParamGenerator<T>::operator*(). virtual const T* Current() const = 0; // Determines whether the given iterator and other point to the same // element in the sequence generated by the generator. // Used for implementing ParamGenerator<T>::operator==(). virtual bool Equals(const ParamIteratorInterface& other) const = 0; }; // Class iterating over elements provided by an implementation of // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T> // and implements the const forward iterator concept. template <typename T> class ParamIterator { public: typedef T value_type; typedef const T& reference; typedef ptrdiff_t difference_type; // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } const T& operator*() const { return *impl_->Current(); } const T* operator->() const { return impl_->Current(); } // Prefix version of operator++. ParamIterator& operator++() { impl_->Advance(); return *this; } // Postfix version of operator++. ParamIterator operator++(int /*unused*/) { ParamIteratorInterface<T>* clone = impl_->Clone(); impl_->Advance(); return ParamIterator(clone); } bool operator==(const ParamIterator& other) const { return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); } bool operator!=(const ParamIterator& other) const { return !(*this == other); } private: friend class ParamGenerator<T>; explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {} std::unique_ptr<ParamIteratorInterface<T> > impl_; }; // ParamGeneratorInterface<T> is the binary interface to access generators // defined in other translation units. template <typename T> class ParamGeneratorInterface { public: typedef T ParamType; virtual ~ParamGeneratorInterface() {} // Generator interface definition virtual ParamIteratorInterface<T>* Begin() const = 0; virtual ParamIteratorInterface<T>* End() const = 0; }; // Wraps ParamGeneratorInterface<T> and provides general generator syntax // compatible with the STL Container concept. // This class implements copy initialization semantics and the contained // ParamGeneratorInterface<T> instance is shared among all copies // of the original object. This is possible because that instance is immutable. template<typename T> class ParamGenerator { public: typedef ParamIterator<T> iterator; explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {} ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} ParamGenerator& operator=(const ParamGenerator& other) { impl_ = other.impl_; return *this; } iterator begin() const { return iterator(impl_->Begin()); } iterator end() const { return iterator(impl_->End()); } private: std::shared_ptr<const ParamGeneratorInterface<T> > impl_; }; // Generates values from a range of two comparable values. Can be used to // generate sequences of user-defined types that implement operator+() and // operator<(). // This class is used in the Range() function. template <typename T, typename IncrementT> class RangeGenerator : public ParamGeneratorInterface<T> { public: RangeGenerator(T begin, T end, IncrementT step) : begin_(begin), end_(end), step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} ~RangeGenerator() override {} ParamIteratorInterface<T>* Begin() const override { return new Iterator(this, begin_, 0, step_); } ParamIteratorInterface<T>* End() const override { return new Iterator(this, end_, end_index_, step_); } private: class Iterator : public ParamIteratorInterface<T> { public: Iterator(const ParamGeneratorInterface<T>* base, T value, int index, IncrementT step) : base_(base), value_(value), index_(index), step_(step) {} ~Iterator() override {} const ParamGeneratorInterface<T>* BaseGenerator() const override { return base_; } void Advance() override { value_ = static_cast<T>(value_ + step_); index_++; } ParamIteratorInterface<T>* Clone() const override { return new Iterator(*this); } const T* Current() const override { return &value_; } bool Equals(const ParamIteratorInterface<T>& other) const override { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const int other_index = CheckedDowncastToActualType<const Iterator>(&other)->index_; return index_ == other_index; } private: Iterator(const Iterator& other) : ParamIteratorInterface<T>(), base_(other.base_), value_(other.value_), index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<T>* const base_; T value_; int index_; const IncrementT step_; }; // class RangeGenerator::Iterator static int CalculateEndIndex(const T& begin, const T& end, const IncrementT& step) { int end_index = 0; for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++; return end_index; } // No implementation - assignment is unsupported. void operator=(const RangeGenerator& other); const T begin_; const T end_; const IncrementT step_; // The index for the end() iterator. All the elements in the generated // sequence are indexed (0-based) to aid iterator comparison. const int end_index_; }; // class RangeGenerator // Generates values from a pair of STL-style iterators. Used in the // ValuesIn() function. The elements are copied from the source range // since the source can be located on the stack, and the generator // is likely to persist beyond that stack frame. template <typename T> class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { public: template <typename ForwardIterator> ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} ~ValuesInIteratorRangeGenerator() override {} ParamIteratorInterface<T>* Begin() const override { return new Iterator(this, container_.begin()); } ParamIteratorInterface<T>* End() const override { return new Iterator(this, container_.end()); } private: typedef typename ::std::vector<T> ContainerType; class Iterator : public ParamIteratorInterface<T> { public: Iterator(const ParamGeneratorInterface<T>* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} ~Iterator() override {} const ParamGeneratorInterface<T>* BaseGenerator() const override { return base_; } void Advance() override { ++iterator_; value_.reset(); } ParamIteratorInterface<T>* Clone() const override { return new Iterator(*this); } // We need to use cached value referenced by iterator_ because *iterator_ // can return a temporary object (and of type other then T), so just // having "return &*iterator_;" doesn't work. // value_ is updated here and not in Advance() because Advance() // can advance iterator_ beyond the end of the range, and we cannot // detect that fact. The client code, on the other hand, is // responsible for not calling Current() on an out-of-range iterator. const T* Current() const override { if (value_.get() == nullptr) value_.reset(new T(*iterator_)); return value_.get(); } bool Equals(const ParamIteratorInterface<T>& other) const override { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; return iterator_ == CheckedDowncastToActualType<const Iterator>(&other)->iterator_; } private: Iterator(const Iterator& other) // The explicit constructor call suppresses a false warning // emitted by gcc when supplied with the -Wextra option. : ParamIteratorInterface<T>(), base_(other.base_), iterator_(other.iterator_) {} const ParamGeneratorInterface<T>* const base_; typename ContainerType::const_iterator iterator_; // A cached value of *iterator_. We keep it here to allow access by // pointer in the wrapping iterator's operator->(). // value_ needs to be mutable to be accessed in Current(). // Use of std::unique_ptr helps manage cached value's lifetime, // which is bound by the lifespan of the iterator itself. mutable std::unique_ptr<const T> value_; }; // class ValuesInIteratorRangeGenerator::Iterator // No implementation - assignment is unsupported. void operator=(const ValuesInIteratorRangeGenerator& other); const ContainerType container_; }; // class ValuesInIteratorRangeGenerator // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Default parameterized test name generator, returns a string containing the // integer test parameter index. template <class ParamType> std::string DefaultParamName(const TestParamInfo<ParamType>& info) { Message name_stream; name_stream << info.index; return name_stream.GetString(); } template <typename T = int> void TestNotEmpty() { static_assert(sizeof(T) == 0, "Empty arguments are not allowed."); } template <typename T = int> void TestNotEmpty(const T&) {} // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Stores a parameter value and later creates tests parameterized with that // value. template <class TestClass> class ParameterizedTestFactory : public TestFactoryBase { public: typedef typename TestClass::ParamType ParamType; explicit ParameterizedTestFactory(ParamType parameter) : parameter_(parameter) {} Test* CreateTest() override { TestClass::SetParam(&parameter_); return new TestClass(); } private: const ParamType parameter_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactoryBase is a base class for meta-factories that create // test factories for passing into MakeAndRegisterTestInfo function. template <class ParamType> class TestMetaFactoryBase { public: virtual ~TestMetaFactoryBase() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactory creates test factories for passing into // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives // ownership of test factory pointer, same factory object cannot be passed // into that method twice. But ParameterizedTestSuiteInfo is going to call // it for each Test/Parameter value combination. Thus it needs meta factory // creator class. template <class TestSuite> class TestMetaFactory : public TestMetaFactoryBase<typename TestSuite::ParamType> { public: using ParamType = typename TestSuite::ParamType; TestMetaFactory() {} TestFactoryBase* CreateTestFactory(ParamType parameter) override { return new ParameterizedTestFactory<TestSuite>(parameter); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestSuiteInfoBase is a generic interface // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase // accumulates test information provided by TEST_P macro invocations // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations // and uses that information to register all resulting test instances // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds // a collection of pointers to the ParameterizedTestSuiteInfo objects // and calls RegisterTests() on each of them when asked. class ParameterizedTestSuiteInfoBase { public: virtual ~ParameterizedTestSuiteInfoBase() {} // Base part of test suite name for display purposes. virtual const std::string& GetTestSuiteName() const = 0; // Test case id to verify identity. virtual TypeId GetTestSuiteTypeId() const = 0; // UnitTest class invokes this method to register tests in this // test suite right before running them in RUN_ALL_TESTS macro. // This method should not be called more than once on any single // instance of a ParameterizedTestSuiteInfoBase derived class. virtual void RegisterTests() = 0; protected: ParameterizedTestSuiteInfoBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P // macro invocations for a particular test suite and generators // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that // test suite. It registers tests with all values generated by all // generators when asked. template <class TestSuite> class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { public: // ParamType and GeneratorCreationFunc are private types but are required // for declarations of public methods AddTestPattern() and // AddTestSuiteInstantiation(). using ParamType = typename TestSuite::ParamType; // A function that returns an instance of appropriate generator type. typedef ParamGenerator<ParamType>(GeneratorCreationFunc)(); using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&); explicit ParameterizedTestSuiteInfo(const char* name, CodeLocation code_location) : test_suite_name_(name), code_location_(code_location) {} // Test case base name for display purposes. const std::string& GetTestSuiteName() const override { return test_suite_name_; } // Test case id to verify identity. TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); } // TEST_P macro uses AddTestPattern() to record information // about a single test in a LocalTestInfo structure. // test_suite_name is the base name of the test suite (without invocation // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test suite base name and DoBar is test base name. void AddTestPattern(const char* test_suite_name, const char* test_base_name, TestMetaFactoryBase<ParamType>* meta_factory) { tests_.push_back(std::shared_ptr<TestInfo>( new TestInfo(test_suite_name, test_base_name, meta_factory))); } // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information // about a generator. int AddTestSuiteInstantiation(const std::string& instantiation_name, GeneratorCreationFunc* func, ParamNameGeneratorFunc* name_func, const char* file, int line) { instantiations_.push_back( InstantiationInfo(instantiation_name, func, name_func, file, line)); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test suite // test suites right before running tests in RUN_ALL_TESTS macro. // This method should not be called more than once on any single // instance of a ParameterizedTestSuiteInfoBase derived class. // UnitTest has a guard to prevent from calling this method more than once. void RegisterTests() override { for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { std::shared_ptr<TestInfo> test_info = *test_it; for (typename InstantiationContainer::iterator gen_it = instantiations_.begin(); gen_it != instantiations_.end(); ++gen_it) { const std::string& instantiation_name = gen_it->name; ParamGenerator<ParamType> generator((*gen_it->generator)()); ParamNameGeneratorFunc* name_func = gen_it->name_func; const char* file = gen_it->file; int line = gen_it->line; std::string test_suite_name; if ( !instantiation_name.empty() ) test_suite_name = instantiation_name + "/"; test_suite_name += test_info->test_suite_base_name; size_t i = 0; std::set<std::string> test_param_names; for (typename ParamGenerator<ParamType>::iterator param_it = generator.begin(); param_it != generator.end(); ++param_it, ++i) { Message test_name_stream; std::string param_name = name_func( TestParamInfo<ParamType>(*param_it, i)); GTEST_CHECK_(IsValidParamName(param_name)) << "Parameterized test name '" << param_name << "' is invalid, in " << file << " line " << line << std::endl; GTEST_CHECK_(test_param_names.count(param_name) == 0) << "Duplicate parameterized test name '" << param_name << "', in " << file << " line " << line << std::endl; test_param_names.insert(param_name); if (!test_info->test_base_name.empty()) { test_name_stream << test_info->test_base_name << "/"; } test_name_stream << param_name; MakeAndRegisterTestInfo( test_suite_name.c_str(), test_name_stream.GetString().c_str(), nullptr, // No type parameter. PrintToString(*param_it).c_str(), code_location_, GetTestSuiteTypeId(), SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line), SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line), test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it } // for gen_it } // for test_it } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name, TestMetaFactoryBase<ParamType>* a_test_meta_factory) : test_suite_base_name(a_test_suite_base_name), test_base_name(a_test_base_name), test_meta_factory(a_test_meta_factory) {} const std::string test_suite_base_name; const std::string test_base_name; const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory; }; using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >; // Records data received from INSTANTIATE_TEST_SUITE_P macros: // <Instantiation name, Sequence generator creation function, // Name generator function, Source file, Source line> struct InstantiationInfo { InstantiationInfo(const std::string &name_in, GeneratorCreationFunc* generator_in, ParamNameGeneratorFunc* name_func_in, const char* file_in, int line_in) : name(name_in), generator(generator_in), name_func(name_func_in), file(file_in), line(line_in) {} std::string name; GeneratorCreationFunc* generator; ParamNameGeneratorFunc* name_func; const char* file; int line; }; typedef ::std::vector<InstantiationInfo> InstantiationContainer; static bool IsValidParamName(const std::string& name) { // Check for empty string if (name.empty()) return false; // Check for invalid characters for (std::string::size_type index = 0; index < name.size(); ++index) { if (!isalnum(name[index]) && name[index] != '_') return false; } return true; } const std::string test_suite_name_; CodeLocation code_location_; TestInfoContainer tests_; InstantiationContainer instantiations_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo); }; // class ParameterizedTestSuiteInfo // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ template <class TestCase> using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>; #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestSuiteRegistry contains a map of // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding // ParameterizedTestSuiteInfo descriptors. class ParameterizedTestSuiteRegistry { public: ParameterizedTestSuiteRegistry() {} ~ParameterizedTestSuiteRegistry() { for (auto& test_suite_info : test_suite_infos_) { delete test_suite_info; } } // Looks up or creates and returns a structure containing information about // tests and instantiations of a particular test suite. template <class TestSuite> ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder( const char* test_suite_name, CodeLocation code_location) { ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr; for (auto& test_suite_info : test_suite_infos_) { if (test_suite_info->GetTestSuiteName() == test_suite_name) { if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) { // Complain about incorrect usage of Google Test facilities // and terminate the program since we cannot guaranty correct // test suite setup and tear-down in this case. ReportInvalidTestSuiteType(test_suite_name, code_location); posix::Abort(); } else { // At this point we are sure that the object we found is of the same // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info); } break; } } if (typed_test_info == nullptr) { typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>( test_suite_name, code_location); test_suite_infos_.push_back(typed_test_info); } return typed_test_info; } void RegisterTests() { for (auto& test_suite_info : test_suite_infos_) { test_suite_info->RegisterTests(); } } // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ template <class TestCase> ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder( const char* test_case_name, CodeLocation code_location) { return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ private: using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>; TestSuiteInfoContainer test_suite_infos_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry); }; } // namespace internal // Forward declarations of ValuesIn(), which is implemented in // include/gtest/gtest-param-test.h. template <class Container> internal::ParamGenerator<typename Container::value_type> ValuesIn( const Container& container); namespace internal { // Used in the Values() function to provide polymorphic capabilities. template <typename... Ts> class ValueArray { public: ValueArray(Ts... v) : v_{std::move(v)...} {} template <typename T> operator ParamGenerator<T>() const { // NOLINT return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>())); } private: template <typename T, size_t... I> std::vector<T> MakeVector(IndexSequence<I...>) const { return std::vector<T>{static_cast<T>(v_.template Get<I>())...}; } FlatTuple<Ts...> v_; }; template <typename... T> class CartesianProductGenerator : public ParamGeneratorInterface<::std::tuple<T...>> { public: typedef ::std::tuple<T...> ParamType; CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g) : generators_(g) {} ~CartesianProductGenerator() override {} ParamIteratorInterface<ParamType>* Begin() const override { return new Iterator(this, generators_, false); } ParamIteratorInterface<ParamType>* End() const override { return new Iterator(this, generators_, true); } private: template <class I> class IteratorImpl; template <size_t... I> class IteratorImpl<IndexSequence<I...>> : public ParamIteratorInterface<ParamType> { public: IteratorImpl(const ParamGeneratorInterface<ParamType>* base, const std::tuple<ParamGenerator<T>...>& generators, bool is_end) : base_(base), begin_(std::get<I>(generators).begin()...), end_(std::get<I>(generators).end()...), current_(is_end ? end_ : begin_) { ComputeCurrentValue(); } ~IteratorImpl() override {} const ParamGeneratorInterface<ParamType>* BaseGenerator() const override { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. void Advance() override { assert(!AtEnd()); // Advance the last iterator. ++std::get<sizeof...(T) - 1>(current_); // if that reaches end, propagate that up. AdvanceIfEnd<sizeof...(T) - 1>(); ComputeCurrentValue(); } ParamIteratorInterface<ParamType>* Clone() const override { return new IteratorImpl(*this); } const ParamType* Current() const override { return current_value_.get(); } bool Equals(const ParamIteratorInterface<ParamType>& other) const override { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const IteratorImpl* typed_other = CheckedDowncastToActualType<const IteratorImpl>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). if (AtEnd() && typed_other->AtEnd()) return true; bool same = true; bool dummy[] = { (same = same && std::get<I>(current_) == std::get<I>(typed_other->current_))...}; (void)dummy; return same; } private: template <size_t ThisI> void AdvanceIfEnd() { if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return; bool last = ThisI == 0; if (last) { // We are done. Nothing else to propagate. return; } constexpr size_t NextI = ThisI - (ThisI != 0); std::get<ThisI>(current_) = std::get<ThisI>(begin_); ++std::get<NextI>(current_); AdvanceIfEnd<NextI>(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...); } bool AtEnd() const { bool at_end = false; bool dummy[] = { (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...}; (void)dummy; return at_end; } const ParamGeneratorInterface<ParamType>* const base_; std::tuple<typename ParamGenerator<T>::iterator...> begin_; std::tuple<typename ParamGenerator<T>::iterator...> end_; std::tuple<typename ParamGenerator<T>::iterator...> current_; std::shared_ptr<ParamType> current_value_; }; using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>; std::tuple<ParamGenerator<T>...> generators_; }; template <class... Gen> class CartesianProductHolder { public: CartesianProductHolder(const Gen&... g) : generators_(g...) {} template <typename... T> operator ParamGenerator<::std::tuple<T...>>() const { return ParamGenerator<::std::tuple<T...>>( new CartesianProductGenerator<T...>(generators_)); } private: std::tuple<Gen...> generators_; }; } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
411
0.962794
1
0.962794
game-dev
MEDIA
0.179873
game-dev
0.943509
1
0.943509
Slattstudio/BetrayedAllianceBook1
1,660
SRC/Rm052.sc
;;; Sierra Script 1.0 - (do not remove this comment) (script# 52) (include sci.sh) (include game.sh) (use controls) (use cycle) (use feature) (use game) (use inv) (use main) (use obj) (public rm052 0 ) ; NULL ROOM (instance rm052 of Rm (properties picture scriptNumber north 0 east 0 south 0 west 0 ) (method (init) (super init:) (self setScript: RoomScript) (switch gPreviousRoomNumber (else (gEgo posn: 150 130 loop: 1) ) ) (SetUpEgo) (gEgo init:) (glow init: hide: ignoreActors:) (shadowleft init: hide: ignoreActors:) (shadowright init: hide: ignoreActors:) ) ) (instance RoomScript of Script (properties) (method (handleEvent pEvent &tmp str) ; Local variable (super handleEvent: pEvent) (switch (pEvent type?) (evKEYBOARD (MapKeyToDir pEvent) (if (== (pEvent message?) KEY_D) ; Check if B was pressed (PrintOK) ; switch to Brian (pEvent claimed: TRUE) ) ; if B (if (== (pEvent message?) KEY_E) ; Check if E was pressed (PrintOK) ; switch to Ego (pEvent claimed: TRUE) ) ) ) ) ; if ; evKEYBOARD ; For fun intercept the Mouse event as well ; evMOUSEBUTTON ; switch ; method (method (doit) (super doit:) (glow show: posn: (gEgo x?) (+ (gEgo y?) 55)) (shadowleft show: posn: (- (gEgo x?) 137) (+ (gEgo y?) 55) ) (shadowright show: posn: (+ (gEgo x?) 137) (+ (gEgo y?) 55) ) ) ) (instance glow of Prop (properties y 35 x 195 view 62 ) ) (instance shadowleft of Prop (properties y 35 x 195 view 62 loop 1 ) ) (instance shadowright of Prop (properties y 35 x 195 view 62 loop 1 ) )
411
0.80014
1
0.80014
game-dev
MEDIA
0.888769
game-dev
0.827995
1
0.827995
Eukaryot/sonic3air
12,756
framework/external/sdl/SDL2/src/joystick/emscripten/SDL_sysjoystick.c
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifdef SDL_JOYSTICK_EMSCRIPTEN #include <stdio.h> /* For the definition of NULL */ #include "SDL_error.h" #include "SDL_events.h" #include "SDL_joystick.h" #include "SDL_timer.h" #include "SDL_sysjoystick_c.h" #include "../SDL_joystick_c.h" static SDL_joylist_item *JoystickByIndex(int index); static SDL_joylist_item *SDL_joylist = NULL; static SDL_joylist_item *SDL_joylist_tail = NULL; static int numjoysticks = 0; static EM_BOOL Emscripten_JoyStickConnected(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) { int i; SDL_joylist_item *item; if (JoystickByIndex(gamepadEvent->index) != NULL) { return 1; } item = (SDL_joylist_item *)SDL_malloc(sizeof(SDL_joylist_item)); if (!item) { return 1; } SDL_zerop(item); item->index = gamepadEvent->index; item->name = SDL_CreateJoystickName(0, 0, NULL, gamepadEvent->id); if (!item->name) { SDL_free(item); return 1; } item->mapping = SDL_strdup(gamepadEvent->mapping); if (!item->mapping) { SDL_free(item->name); SDL_free(item); return 1; } item->naxes = gamepadEvent->numAxes; item->nbuttons = gamepadEvent->numButtons; item->device_instance = SDL_GetNextJoystickInstanceID(); item->timestamp = gamepadEvent->timestamp; for (i = 0; i < item->naxes; i++) { item->axis[i] = gamepadEvent->axis[i]; } for (i = 0; i < item->nbuttons; i++) { item->analogButton[i] = gamepadEvent->analogButton[i]; item->digitalButton[i] = gamepadEvent->digitalButton[i]; } if (!SDL_joylist_tail) { SDL_joylist = SDL_joylist_tail = item; } else { SDL_joylist_tail->next = item; SDL_joylist_tail = item; } ++numjoysticks; SDL_PrivateJoystickAdded(item->device_instance); #ifdef DEBUG_JOYSTICK SDL_Log("Number of joysticks is %d", numjoysticks); #endif #ifdef DEBUG_JOYSTICK SDL_Log("Added joystick with index %d", item->index); #endif return 1; } static EM_BOOL Emscripten_JoyStickDisconnected(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) { SDL_joylist_item *item = SDL_joylist; SDL_joylist_item *prev = NULL; while (item) { if (item->index == gamepadEvent->index) { break; } prev = item; item = item->next; } if (!item) { return 1; } if (item->joystick) { item->joystick->hwdata = NULL; } if (prev) { prev->next = item->next; } else { SDL_assert(SDL_joylist == item); SDL_joylist = item->next; } if (item == SDL_joylist_tail) { SDL_joylist_tail = prev; } /* Need to decrement the joystick count before we post the event */ --numjoysticks; SDL_PrivateJoystickRemoved(item->device_instance); #ifdef DEBUG_JOYSTICK SDL_Log("Removed joystick with id %d", item->device_instance); #endif SDL_free(item->name); SDL_free(item->mapping); SDL_free(item); return 1; } /* Function to perform any system-specific joystick related cleanup */ static void EMSCRIPTEN_JoystickQuit(void) { SDL_joylist_item *item = NULL; SDL_joylist_item *next = NULL; for (item = SDL_joylist; item; item = next) { next = item->next; SDL_free(item->mapping); SDL_free(item->name); SDL_free(item); } SDL_joylist = SDL_joylist_tail = NULL; numjoysticks = 0; emscripten_set_gamepadconnected_callback(NULL, 0, NULL); emscripten_set_gamepaddisconnected_callback(NULL, 0, NULL); } /* Function to scan the system for joysticks. * It should return 0, or -1 on an unrecoverable fatal error. */ static int EMSCRIPTEN_JoystickInit(void) { int retval, i, numjs; EmscriptenGamepadEvent gamepadState; numjoysticks = 0; retval = emscripten_sample_gamepad_data(); /* Check if gamepad is supported by browser */ if (retval == EMSCRIPTEN_RESULT_NOT_SUPPORTED) { return SDL_SetError("Gamepads not supported"); } numjs = emscripten_get_num_gamepads(); /* handle already connected gamepads */ if (numjs > 0) { for (i = 0; i < numjs; i++) { retval = emscripten_get_gamepad_status(i, &gamepadState); if (retval == EMSCRIPTEN_RESULT_SUCCESS) { Emscripten_JoyStickConnected(EMSCRIPTEN_EVENT_GAMEPADCONNECTED, &gamepadState, NULL); } } } retval = emscripten_set_gamepadconnected_callback(NULL, 0, Emscripten_JoyStickConnected); if (retval != EMSCRIPTEN_RESULT_SUCCESS) { EMSCRIPTEN_JoystickQuit(); return SDL_SetError("Could not set gamepad connect callback"); } retval = emscripten_set_gamepaddisconnected_callback(NULL, 0, Emscripten_JoyStickDisconnected); if (retval != EMSCRIPTEN_RESULT_SUCCESS) { EMSCRIPTEN_JoystickQuit(); return SDL_SetError("Could not set gamepad disconnect callback"); } return 0; } /* Returns item matching given SDL device index. */ static SDL_joylist_item *JoystickByDeviceIndex(int device_index) { SDL_joylist_item *item = SDL_joylist; while (0 < device_index) { --device_index; item = item->next; } return item; } /* Returns item matching given HTML gamepad index. */ static SDL_joylist_item *JoystickByIndex(int index) { SDL_joylist_item *item = SDL_joylist; if (index < 0) { return NULL; } while (item) { if (item->index == index) { break; } item = item->next; } return item; } static int EMSCRIPTEN_JoystickGetCount(void) { return numjoysticks; } static void EMSCRIPTEN_JoystickDetect(void) { } static const char *EMSCRIPTEN_JoystickGetDeviceName(int device_index) { return JoystickByDeviceIndex(device_index)->name; } static const char *EMSCRIPTEN_JoystickGetDevicePath(int device_index) { return NULL; } static int EMSCRIPTEN_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) { return -1; } static int EMSCRIPTEN_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void EMSCRIPTEN_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_JoystickID EMSCRIPTEN_JoystickGetDeviceInstanceID(int device_index) { return JoystickByDeviceIndex(device_index)->device_instance; } /* Function to open a joystick for use. The joystick to open is specified by the device index. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ static int EMSCRIPTEN_JoystickOpen(SDL_Joystick *joystick, int device_index) { SDL_joylist_item *item = JoystickByDeviceIndex(device_index); if (!item) { return SDL_SetError("No such device"); } if (item->joystick) { return SDL_SetError("Joystick already opened"); } joystick->instance_id = item->device_instance; joystick->hwdata = (struct joystick_hwdata *)item; item->joystick = joystick; /* HTML5 Gamepad API doesn't say anything about these */ joystick->nhats = 0; joystick->nballs = 0; joystick->nbuttons = item->nbuttons; joystick->naxes = item->naxes; return 0; } /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ static void EMSCRIPTEN_JoystickUpdate(SDL_Joystick *joystick) { EmscriptenGamepadEvent gamepadState; SDL_joylist_item *item = (SDL_joylist_item *)joystick->hwdata; int i, result, buttonState; emscripten_sample_gamepad_data(); if (item) { result = emscripten_get_gamepad_status(item->index, &gamepadState); if (result == EMSCRIPTEN_RESULT_SUCCESS) { if (gamepadState.timestamp == 0 || gamepadState.timestamp != item->timestamp) { for (i = 0; i < item->nbuttons; i++) { if (item->digitalButton[i] != gamepadState.digitalButton[i]) { buttonState = gamepadState.digitalButton[i] ? SDL_PRESSED : SDL_RELEASED; SDL_PrivateJoystickButton(item->joystick, i, buttonState); } /* store values to compare them in the next update */ item->analogButton[i] = gamepadState.analogButton[i]; item->digitalButton[i] = gamepadState.digitalButton[i]; } for (i = 0; i < item->naxes; i++) { if (item->axis[i] != gamepadState.axis[i]) { /* do we need to do conversion? */ SDL_PrivateJoystickAxis(item->joystick, i, (Sint16)(32767. * gamepadState.axis[i])); } /* store to compare in next update */ item->axis[i] = gamepadState.axis[i]; } item->timestamp = gamepadState.timestamp; } } } } /* Function to close a joystick after use */ static void EMSCRIPTEN_JoystickClose(SDL_Joystick *joystick) { SDL_joylist_item *item = (SDL_joylist_item *)joystick->hwdata; if (item) { item->joystick = NULL; } } static SDL_JoystickGUID EMSCRIPTEN_JoystickGetDeviceGUID(int device_index) { /* the GUID is just the name for now */ const char *name = EMSCRIPTEN_JoystickGetDeviceName(device_index); return SDL_CreateJoystickGUIDForName(name); } static int EMSCRIPTEN_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { return SDL_Unsupported(); } static int EMSCRIPTEN_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) { return SDL_Unsupported(); } static SDL_bool EMSCRIPTEN_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { return SDL_FALSE; } static Uint32 EMSCRIPTEN_JoystickGetCapabilities(SDL_Joystick *joystick) { return 0; } static int EMSCRIPTEN_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) { return SDL_Unsupported(); } static int EMSCRIPTEN_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) { return SDL_Unsupported(); } static int EMSCRIPTEN_JoystickSetSensorsEnabled(SDL_Joystick *joystick, SDL_bool enabled) { return SDL_Unsupported(); } SDL_JoystickDriver SDL_EMSCRIPTEN_JoystickDriver = { EMSCRIPTEN_JoystickInit, EMSCRIPTEN_JoystickGetCount, EMSCRIPTEN_JoystickDetect, EMSCRIPTEN_JoystickGetDeviceName, EMSCRIPTEN_JoystickGetDevicePath, EMSCRIPTEN_JoystickGetDeviceSteamVirtualGamepadSlot, EMSCRIPTEN_JoystickGetDevicePlayerIndex, EMSCRIPTEN_JoystickSetDevicePlayerIndex, EMSCRIPTEN_JoystickGetDeviceGUID, EMSCRIPTEN_JoystickGetDeviceInstanceID, EMSCRIPTEN_JoystickOpen, EMSCRIPTEN_JoystickRumble, EMSCRIPTEN_JoystickRumbleTriggers, EMSCRIPTEN_JoystickGetCapabilities, EMSCRIPTEN_JoystickSetLED, EMSCRIPTEN_JoystickSendEffect, EMSCRIPTEN_JoystickSetSensorsEnabled, EMSCRIPTEN_JoystickUpdate, EMSCRIPTEN_JoystickClose, EMSCRIPTEN_JoystickQuit, EMSCRIPTEN_JoystickGetGamepadMapping }; #endif /* SDL_JOYSTICK_EMSCRIPTEN */ /* vi: set ts=4 sw=4 expandtab: */
411
0.790418
1
0.790418
game-dev
MEDIA
0.864947
game-dev
0.77752
1
0.77752
Nebukam/PCGExtendedToolkit
5,652
Source/PCGExtendedToolkit/Private/Misc/Filters/PCGExRandomFilter.cpp
// Copyright 2025 Timothé Lapetite and contributors // Released under the MIT license https://opensource.org/license/MIT/ #include "Misc/Filters/PCGExRandomFilter.h" #include "PCGExRandom.h" #include "Data/PCGExDataPreloader.h" #include "Data/PCGExPointIO.h" #include "Details/PCGExDetailsSettings.h" #define LOCTEXT_NAMESPACE "PCGExCompareFilterDefinition" #define PCGEX_NAMESPACE CompareFilterDefinition PCGEX_SETTING_VALUE_IMPL(FPCGExRandomFilterConfig, Threshold, double, ThresholdInput, ThresholdAttribute, Threshold) PCGEX_SETTING_VALUE_IMPL(FPCGExRandomFilterConfig, Weight, double, bPerPointWeight ? EPCGExInputValueType::Attribute : EPCGExInputValueType::Constant, Weight, 1) bool UPCGExRandomFilterFactory::Init(FPCGExContext* InContext) { if (!Config.bUseLocalCurve) { Config.LocalWeightCurve.ExternalCurve = Config.WeightCurve.Get(); } return Super::Init(InContext); } bool UPCGExRandomFilterFactory::SupportsCollectionEvaluation() const { return (!Config.bPerPointWeight && Config.ThresholdInput == EPCGExInputValueType::Constant) || bOnlyUseDataDomain; } bool UPCGExRandomFilterFactory::SupportsProxyEvaluation() const { return !Config.bPerPointWeight && Config.ThresholdInput == EPCGExInputValueType::Constant; } void UPCGExRandomFilterFactory::RegisterBuffersDependencies(FPCGExContext* InContext, PCGExData::FFacadePreloader& FacadePreloader) const { Super::RegisterBuffersDependencies(InContext, FacadePreloader); if (Config.bPerPointWeight && Config.bRemapWeightInternally) { FacadePreloader.Register<double>(InContext, Config.Weight); } if (Config.ThresholdInput != EPCGExInputValueType::Constant && Config.bRemapThresholdInternally) { FacadePreloader.Register<double>(InContext, Config.ThresholdAttribute); } } void UPCGExRandomFilterFactory::RegisterAssetDependencies(FPCGExContext* InContext) const { Super::RegisterAssetDependencies(InContext); InContext->AddAssetDependency(Config.WeightCurve.ToSoftObjectPath()); } bool UPCGExRandomFilterFactory::RegisterConsumableAttributesWithData(FPCGExContext* InContext, const UPCGData* InData) const { if (!Super::RegisterConsumableAttributesWithData(InContext, InData)) { return false; } FName Consumable = NAME_None; PCGEX_CONSUMABLE_CONDITIONAL(Config.bPerPointWeight, Config.Weight, Consumable) PCGEX_CONSUMABLE_CONDITIONAL(Config.ThresholdInput == EPCGExInputValueType::Attribute, Config.ThresholdAttribute, Consumable) return true; } TSharedPtr<PCGExPointFilter::IFilter> UPCGExRandomFilterFactory::CreateFilter() const { PCGEX_MAKE_SHARED(Filter, PCGExPointFilter::FRandomFilter, this) Filter->WeightCurve = Config.LocalWeightCurve.GetRichCurveConst(); return Filter; } bool PCGExPointFilter::FRandomFilter::Init(FPCGExContext* InContext, const TSharedPtr<PCGExData::FFacade>& InPointDataFacade) { if (!IFilter::Init(InContext, InPointDataFacade)) { return false; } Threshold = TypedFilterFactory->Config.Threshold; WeightBuffer = TypedFilterFactory->Config.GetValueSettingWeight(); if (!WeightBuffer->IsConstant()) { if (TypedFilterFactory->Config.bRemapWeightInternally) { if (!WeightBuffer->Init(PointDataFacade, false, true)) { return false; } WeightRange = WeightBuffer->Max(); if (WeightBuffer->Min() < 0) { WeightOffset = WeightBuffer->Min(); WeightRange += WeightOffset; } } else { if (!WeightBuffer->Init(PointDataFacade)) { return false; } } } ThresholdBuffer = TypedFilterFactory->Config.GetValueSettingThreshold(); if (!ThresholdBuffer->IsConstant()) { if (TypedFilterFactory->Config.bRemapThresholdInternally) { if (!ThresholdBuffer->Init(PointDataFacade, false, true)) { return false; } ThresholdRange = ThresholdBuffer->Max(); if (ThresholdBuffer->Min() < 0) { ThresholdOffset = ThresholdBuffer->Min(); ThresholdRange += ThresholdOffset; } } else { if (!ThresholdBuffer->Init(PointDataFacade)) { return false; } } } Seeds = PointDataFacade->GetIn()->GetConstSeedValueRange(); RandomSeedV = FVector(RandomSeed); return true; } bool PCGExPointFilter::FRandomFilter::Test(const int32 PointIndex) const { const double LocalWeightRange = WeightOffset + WeightBuffer->Read(PointIndex); const double LocalThreshold = ThresholdBuffer ? (ThresholdOffset + ThresholdBuffer->Read(PointIndex)) / ThresholdRange : Threshold; const float RandomValue = WeightCurve->Eval((FRandomStream(PCGExRandom::GetRandomStreamFromPoint(Seeds[PointIndex], RandomSeed)).GetFraction() * LocalWeightRange) / WeightRange); return TypedFilterFactory->Config.bInvertResult ? RandomValue <= LocalThreshold : RandomValue >= LocalThreshold; } bool PCGExPointFilter::FRandomFilter::Test(const PCGExData::FProxyPoint& Point) const { const float RandomValue = WeightCurve->Eval((FRandomStream(PCGExRandom::ComputeSpatialSeed(Point.GetLocation(), RandomSeedV)).GetFraction() * WeightRange) / WeightRange); return TypedFilterFactory->Config.bInvertResult ? RandomValue <= Threshold : RandomValue >= Threshold; } bool PCGExPointFilter::FRandomFilter::Test(const TSharedPtr<PCGExData::FPointIO>& IO, const TSharedPtr<PCGExData::FPointIOCollection>& ParentCollection) const { const float RandomValue = WeightCurve->Eval((FRandomStream(PCGExRandom::GetRandomStreamFromPoint(IO->GetIn()->GetSeed(0), RandomSeed)).GetFraction() * WeightRange) / WeightRange); return TypedFilterFactory->Config.bInvertResult ? RandomValue <= Threshold : RandomValue >= Threshold; } PCGEX_CREATE_FILTER_FACTORY(Random) #if WITH_EDITOR FString UPCGExRandomFilterProviderSettings::GetDisplayName() const { return TEXT("Random"); } #endif #undef LOCTEXT_NAMESPACE #undef PCGEX_NAMESPACE
411
0.892827
1
0.892827
game-dev
MEDIA
0.284118
game-dev
0.904819
1
0.904819
GregTech6/gregtech6
11,031
src/main/java/gregtech/compat/Compat_Recipes_ExtraUtilities.java
/** * Copyright (c) 2019 Gregorius Techneticies * * This file is part of GregTech. * * GregTech is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GregTech is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GregTech. If not, see <http://www.gnu.org/licenses/>. */ package gregtech.compat; import static gregapi.data.CS.*; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import gregapi.api.Abstract_Mod; import gregapi.code.ModData; import gregapi.compat.CompatMods; import gregapi.config.ConfigCategories; import gregapi.data.CS.ConfigsGT; import gregapi.data.CS.ItemsGT; import gregapi.data.MD; import gregapi.data.RM; import gregapi.oredict.event.IOreDictListenerEvent; import gregapi.oredict.event.OreDictListenerEvent_Names; import gregapi.util.CR; import gregapi.util.ST; import net.minecraft.init.Blocks; public class Compat_Recipes_ExtraUtilities extends CompatMods { public Compat_Recipes_ExtraUtilities(ModData aMod, Abstract_Mod aGTMod) {super(aMod, aGTMod);} @Override public void onPostLoad(FMLPostInitializationEvent aInitEvent) {OUT.println("GT_Mod: Doing Extra Utilities Recipes."); if (ConfigsGT.RECIPES.get(ConfigCategories.Recipes.disabledrecipes, "extra-utilities-trash-can-items", T)) { ItemsGT.RECIPE_REMOVED_USE_TRASH_BIN_INSTEAD.add(ST.make(MD.ExU, "trashcan", 1, 0)); CR.delate(MD.ExU, "trashcan", 0); } if (ConfigsGT.RECIPES.get(ConfigCategories.Recipes.disabledrecipes, "extra-utilities-trash-can-fluids", T)) { ItemsGT.RECIPE_REMOVED_USE_TRASH_BIN_INSTEAD.add(ST.make(MD.ExU, "trashcan", 1, 1)); CR.delate(MD.ExU, "trashcan", 1); } if (ConfigsGT.RECIPES.get(ConfigCategories.Recipes.disabledrecipes, "extra-utilities-trash-can-energy", F)) { ItemsGT.RECIPE_REMOVED_USE_TRASH_BIN_INSTEAD.add(ST.make(MD.ExU, "trashcan", 1, 2)); CR.delate(MD.ExU, "trashcan", 2); } new OreDictListenerEvent_Names() {@Override public void addAllListeners() { addListener("cobblestone" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 0));}}); addListener("compressedCobblestone1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 1));}}); addListener("compressedCobblestone2x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 2));}}); addListener("compressedCobblestone3x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 3));}}); addListener("compressedCobblestone4x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 4));}}); addListener("compressedCobblestone5x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 5));}}); addListener("compressedCobblestone6x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 6));}}); addListener("compressedCobblestone7x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 7));}}); addListener("dirt" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 8));}}); addListener("compressedDirt1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1, 9));}}); addListener("compressedDirt2x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1,10));}}); addListener("compressedDirt3x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1,11));}}); addListener("gravel" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1,12));}}); addListener("compressedGravel1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1,13));}}); addListener("sand" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1,14));}}); addListener("compressedSand1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Press.addRecipe2(T, 16, 64, ST.amount(9, aEvent.mStack), ST.tag(9), ST.make(MD.ExU, "cobblestone_compressed", 1,15));}}); addListener("compressedCobblestone1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(Blocks.cobblestone, 9, 0));}}); addListener("compressedCobblestone2x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 0));}}); addListener("compressedCobblestone3x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 1));}}); addListener("compressedCobblestone4x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 2));}}); addListener("compressedCobblestone5x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 3));}}); addListener("compressedCobblestone6x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 4));}}); addListener("compressedCobblestone7x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 5));}}); addListener("compressedCobblestone8x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 6));}}); addListener("compressedDirt1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(Blocks.dirt, 9, 0));}}); addListener("compressedDirt2x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 8));}}); addListener("compressedDirt3x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9, 9));}}); addListener("compressedDirt4x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9,10));}}); addListener("compressedGravel1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(Blocks.gravel, 9, 0));}}); addListener("compressedGravel2x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9,12));}}); addListener("compressedSand1x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(Blocks.sand, 9, 0));}}); addListener("compressedSand2x" , new IOreDictListenerEvent() {@Override public void onOreRegistration(OreDictRegistrationContainer aEvent) {RM.Crusher.addRecipe1(T, 16, 64, ST.amount(1, aEvent.mStack), ST.make(MD.ExU, "cobblestone_compressed", 9,14));}}); }}; } }
411
0.830422
1
0.830422
game-dev
MEDIA
0.599189
game-dev
0.93003
1
0.93003
shiqwang/netfox
6,006
src/系统模块/游戏组件/42.桥牌/原始-游戏客户端/GameLogic.h
#ifndef GAME_LOGIC_HEAD_FILE #define GAME_LOGIC_HEAD_FILE #pragma once ////////////////////////////////////////////////////////////////////////// //궨 //Ƹ #define CELL_PACK 54 //ԪĿ //Զ #define MAX_COUNT 60 //Ŀ #define MAX_TRACKOR 18 // #define COLOR_RIGHT 40 //ɫȨλ //Ч #define CT_ERROR 0 // #define VALUE_ERROR 0x00 //ֵ #define COLOR_ERROR 0xFF //ɫ //ɫ #define COLOR_NT 0x40 //ɫ #define COLOR_HEI_TAO 0x30 //ɫ #define COLOR_HONG_TAO 0x20 //ɫ #define COLOR_FANG_KUAI 0x10 //ɫ #define COLOR_MEI_HUA 0x00 //ɫ //ֵ #define LOGIC_MASK_COLOR 0xF0 //ɫ #define LOGIC_MASK_VALUE 0x0F //ֵ //˿ #define CT_ERROR 0 // #define CT_SINGLE 1 // #define CT_SAME_2 2 // #define CT_SAME_3 3 // #define CT_SAME_4 4 // #define CT_TRACKOR_2 5 // #define CT_TRACKOR_3 6 // #define CT_TRACKOR_4 7 // #define CT_THROW_CARD 8 //˦ ////////////////////////////////////////////////////////////////////////// //ṹ //Ϣ struct tagSameDataInfo { BYTE cbCardCount; //˿Ŀ BYTE cbBlockCount; //ƶĿ BYTE cbSameData[MAX_COUNT]; // }; //Ϣ struct tagTractorDataInfo { BYTE cbCardCount; //˿Ŀ BYTE cbTractorCount; //Ƹ BYTE cbTractorMaxIndex; //λ BYTE cbTractorMaxLength; //󳤶 BYTE cbTractorData[MAX_COUNT*3/2]; // }; //ͽṹ struct tagAnalyseResult { BYTE cbCardColor; //˿˻ɫ tagSameDataInfo SameDataInfo[2]; //ͬ tagTractorDataInfo TractorDataInfo[2-1]; // }; //ṹ struct tagDemandInfo { BYTE cbMaxTractor[2-1]; // BYTE cbSameCardCount[2]; //ͬ BYTE cbTractorCardCount[2-1]; // }; //ƽ struct tagOutCardResult { BYTE cbCardCount; //˿Ŀ BYTE cbResultCard[MAX_COUNT]; //˿ }; ////////////////////////////////////////////////////////////////////////// //Ϸ߼ class CGameLogic { //Ա protected: BYTE m_cbPackCount; //ƸĿ BYTE m_cbDispatchCount; //ɷĿ //߼ protected: BYTE m_cbMainColor; //ƻɫ // protected: BYTE m_cbSortRight[5]; //Ȩλ // public: static const BYTE m_cbCardData[CELL_PACK]; //˿ // public: //캯 CGameLogic(); // virtual ~CGameLogic(); //״̬ public: //ø bool SetPackCount(BYTE cbPackCount); //ȡ BYTE GetPackCount() { return m_cbPackCount; } //ɷĿ BYTE GetDispatchCount() { return m_cbDispatchCount; } //Ϣ public: //ƻɫ bool SetMainColor(BYTE cbMainColor); //ֵ bool SetMainValue(BYTE cbMainValue); //ƻɫ BYTE GetMainColor() { return m_cbMainColor; } //ƺ public: //˿ void SortCardList(BYTE cbCardData[], BYTE cbCardCount); //˿ void RandCardList(BYTE cbCardBuffer[], BYTE cbBufferCount); //ɾ˿ bool RemoveCard(const BYTE cbRemoveCard[], BYTE cbRemoveCount, BYTE cbCardData[], BYTE cbCardCount); //ֺ public: //ȡ WORD GetCardScore(const BYTE cbCardData[], BYTE cbCardCount); //˿ BYTE GetScoreCard(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbScoreCard[], BYTE cbMaxCount); //ܺ public: //˿ bool AnalyseCardData(const BYTE cbCardData[], BYTE cbCardCount, tagAnalyseResult & AnalyseResult); //ж bool SearchOutCard(const BYTE cbHandCardData[], BYTE cbHandCardCount,const BYTE cbTurnCardData[], BYTE cbTurnCardCount, tagOutCardResult & OutCardResult); //Ч bool EfficacyOutCard(const BYTE cbOutCardData[], BYTE cbOutCardCount, const BYTE cbFirstCardData[], BYTE cbFirstCardCount, const BYTE cbHandCardData[], BYTE cbHandCardCount); //Ч˦ bool EfficacyThrowCard(const BYTE cbOutCardData[], BYTE cbOutCardCount, WORD wOutCardIndex, const BYTE cbHandCardData[GAME_PLAYER][MAX_COUNT], BYTE cbHandCardCount, tagOutCardResult & OutCardResult); //ԱȺ public: //Ա˿ bool CompareCardData(BYTE cbFirstCardData, BYTE cbNextCardData); //Ա˿ bool CompareCardResult(const tagAnalyseResult WinnerResult, const tagAnalyseResult UserResult); //Ա˿ WORD CompareCardArray(const BYTE cbOutCardData[GAME_PLAYER][MAX_COUNT], BYTE cbCardCount, WORD wFirstIndex); //ͺ public: //ȡ BYTE GetCardType(const BYTE cbCardData[], BYTE cbCardCount); //ȡֵ BYTE GetCardValue(BYTE cbCardData) { return cbCardData&LOGIC_MASK_VALUE; } /*{ //ֵΪ //A5~K5~0D 252 753 //ݻA5~K15~2D 262 763 //A5~K25~3D 272 773 //A5~K35~4D 282 783 // // if (cbCardData==0x4E||cbCardData==0x4F) { return cbCardData+160; } //7 if( (cbCardData&LOGIC_MASK_VALUE)==7 ) return (cbCardData)+130; //2 if( (cbCardData&LOGIC_MASK_VALUE)==2 ) return (cbCardData)+80; //A if( (cbCardData&LOGIC_MASK_VALUE)==1 ) return (cbCardData)+13; return cbCardData&LOGIC_MASK_VALUE; }*/ //ȡɫ BYTE GetCardColor(BYTE cbCardData) { return cbCardData&LOGIC_MASK_COLOR; } //߼ public: //Чж bool IsValidCard(BYTE cbCardData); //ȼ BYTE GetCardSortOrder(BYTE cbCardData); //߼ֵ BYTE GetCardLogicValue(BYTE cbCardData); //߼ɫ BYTE GetCardLogicColor(BYTE cbCardData); //лɫ BYTE GetCardLogicColor(const BYTE cbCardData[], BYTE cbCardCount); //߼ protected: //Ƿ bool IsLineValue(BYTE cbFirstCard, BYTE cbSecondCard); //Ƿͬ bool IsSameColor(BYTE cbFirstCard, BYTE cbSecondCard); //Ŀ BYTE GetIntersectionCount(const BYTE cbCardData1[], BYTE cbCardCount1, const BYTE cbCardData2[], BYTE cbCardCount2); //ȡ protected: //ȡ˿ BYTE DistillCardByColor(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbCardColor, BYTE cbResultCard[]); //ȡ˿ BYTE DistillCardByCount(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbSameCount, tagSameDataInfo & SameDataInfo); //ȡ˿ BYTE DistillTrackorByCount(const BYTE cbCardData[], BYTE cbCardCount, BYTE cbSameCount, tagTractorDataInfo & TractorDataInfo); //ڲ protected: //Ȩλ void UpdateSortRight(); //˿ bool RectifyCardWeave(const BYTE cbCardData[], BYTE cbCardCount, const tagAnalyseResult & TargetResult, tagAnalyseResult & RectifyResult); }; ////////////////////////////////////////////////////////////////////////// #endif
411
0.858983
1
0.858983
game-dev
MEDIA
0.400396
game-dev
0.72308
1
0.72308
ProjectIgnis/CardScripts
1,845
official/c2295831.lua
--ピースの輪 --Symbol of Friendship local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_DRAW) e1:SetCondition(s.regcon) e1:SetOperation(s.regop) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_ACTIVATE) e2:SetCode(EVENT_FREE_CHAIN) e2:SetCondition(s.condition) e2:SetCost(s.cost) e2:SetTarget(s.target) e2:SetOperation(s.activate) c:RegisterEffect(e2) end function s.regcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)==0 and Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>=3 and Duel.IsPhase(PHASE_DRAW) and c:IsReason(REASON_RULE) end function s.regop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if Duel.SelectYesNo(tp,aux.Stringid(id,0)) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_PUBLIC) e1:SetReset(RESET_EVENT|RESETS_STANDARD|RESET_PHASE|PHASE_MAIN1) c:RegisterEffect(e1) c:RegisterFlagEffect(id,RESET_PHASE|PHASE_MAIN1,EFFECT_FLAG_CLIENT_HINT,1,0,66) end end function s.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsPhase(PHASE_MAIN1) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetFlagEffect(id)~=0 end end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToHand,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function s.activate(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,Card.IsAbleToHand,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
411
0.822184
1
0.822184
game-dev
MEDIA
0.972757
game-dev
0.94321
1
0.94321
KDAB/GammaRay
2,664
core/metapropertyadaptor.cpp
/* metapropertyadaptor.cpp This file is part of GammaRay, the Qt application inspection and manipulation tool. SPDX-FileCopyrightText: 2015 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com> Author: Volker Krause <volker.krause@kdab.com> SPDX-License-Identifier: GPL-2.0-or-later Contact KDAB at <info@kdab.com> for commercial licensing options. */ #include "metapropertyadaptor.h" #include "objectinstance.h" #include "metaobjectrepository.h" #include "metaobject.h" #include "propertydata.h" #include <QDebug> using namespace GammaRay; MetaPropertyAdaptor::MetaPropertyAdaptor(QObject *parent) : PropertyAdaptor(parent) , m_metaObj(nullptr) , m_obj(nullptr) { } MetaPropertyAdaptor::~MetaPropertyAdaptor() = default; void MetaPropertyAdaptor::doSetObject(const ObjectInstance &oi) { Q_ASSERT(m_metaObj == nullptr); Q_ASSERT(m_obj == nullptr); switch (oi.type()) { case ObjectInstance::Object: case ObjectInstance::Value: m_obj = oi.object(); m_metaObj = MetaObjectRepository::instance()->metaObject(oi.typeName(), m_obj); break; case ObjectInstance::QtObject: case ObjectInstance::QtGadgetPointer: case ObjectInstance::QtGadgetValue: { const QMetaObject *mo = oi.metaObject(); while (mo && !m_metaObj) { m_metaObj = MetaObjectRepository::instance()->metaObject(mo->className()); mo = mo->superClass(); } if (m_metaObj) m_obj = oi.object(); break; } default: break; } } int MetaPropertyAdaptor::count() const { if (!m_metaObj || !object().isValid()) return 0; return m_metaObj->propertyCount(); } PropertyData MetaPropertyAdaptor::propertyData(int index) const { Q_ASSERT(m_metaObj); PropertyData data; if (!object().isValid()) return data; const auto property = m_metaObj->propertyAt(index); data.setName(property->name()); data.setTypeName(property->typeName()); data.setClassName(property->metaObject()->className()); data.setAccessFlags(property->isReadOnly() ? PropertyData::Readable : PropertyData::Writable); if (m_obj) { const auto value = property->value(m_metaObj->castForPropertyAt(m_obj, index)); data.setValue(value); } return data; } void MetaPropertyAdaptor::writeProperty(int index, const QVariant &value) { if (!object().isValid()) return; Q_ASSERT(m_metaObj && m_obj); const auto prop = m_metaObj->propertyAt(index); prop->setValue(m_metaObj->castForPropertyAt(m_obj, index), value); emit propertyChanged(index, index); }
411
0.96687
1
0.96687
game-dev
MEDIA
0.632833
game-dev
0.965304
1
0.965304
Hidendra/LWC
2,408
core/src/main/java/com/griefcraft/modules/admin/AdminReload.java
/* * Copyright 2011 Tyler Blair. 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 THE AUTHOR ''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 AUTHOR 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. * * The views and conclusions contained in the software and documentation are those of the * authors and contributors and should not be interpreted as representing official policies, * either expressed or implied, of anybody else. */ package com.griefcraft.modules.admin; import com.griefcraft.lwc.LWC; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCCommandEvent; import org.bukkit.command.CommandSender; public class AdminReload extends JavaModule { @Override public void onCommand(LWCCommandEvent event) { if (event.isCancelled()) { return; } if (!event.hasFlag("a", "admin")) { return; } LWC lwc = event.getLWC(); CommandSender sender = event.getSender(); String[] args = event.getArgs(); if (!args[0].equals("reload")) { return; } // we have the right command event.setCancelled(true); lwc.reload(); lwc.sendLocale(sender, "protection.admin.reload.finalize"); } }
411
0.552129
1
0.552129
game-dev
MEDIA
0.755578
game-dev
0.771661
1
0.771661
spring1944/spring1944
3,067
LuaRules/Gadgets/dev_cheats.lua
function gadget:GetInfo() return { name = "Developer commands", desc = "/luarules <foo> where <foo> == stuff that's handy for development", author = "B. Tyler", date = "May 22, 2015", license = "GPLv2", layer = -2, enabled = true -- loaded by default? } end if not gadgetHandler:IsSyncedCode() then return end local GetPlayerInfo = Spring.GetPlayerInfo local CheatMode = Spring.IsCheatingEnabled local GetTeamUnits = Spring.GetTeamUnits local GetGroundHeight = Spring.GetGroundHeight local GetUnitDefID = Spring.GetUnitDefID local CreateUnit = Spring.CreateUnit local SetUnitRulesParam = Spring.SetUnitRulesParam local function spawnableUD(ud) if ud.customParams and ud.customParams.child then return false end return true end local commands = { spawn = { help = 'spawn units of a particular category', handler = function (cmd, line, wordlist, playerID, teamID) local ROW_LENGTH = 10 local ROW_INCREMENT = 50 local xStart = table.remove(wordlist, 1) local zStart = table.remove(wordlist, 1) local row = 1 local counter = 0 for _, categoryToSpawn in ipairs(wordlist) do for udid, ud in pairs(UnitDefs) do if ud.modCategories[categoryToSpawn] then local offset = ROW_INCREMENT * counter local x = xStart + offset local z = zStart + ROW_INCREMENT * row local y = GetGroundHeight(x, z) if spawnableUD(ud) then CreateUnit(ud.name, x, y, z, 's', teamID) end counter = counter + 1 if (counter % ROW_LENGTH) == 0 then counter = 0 row = row + 1 end end end end end, }, ammo = { help = "refill ammo for all this team's units", handler = function (cmd, line, wordlist, playerID, teamID) local units = GetTeamUnits(teamID) for index, unitID in pairs(units) do local udid = GetUnitDefID(unitID) local ud = UnitDefs[udid] if ud.customParams and ud.customParams.maxammo then SetUnitRulesParam(unitID, "ammo", tonumber(ud.customParams.maxammo)) end end end }, } local function RegisterCheatHandler(command, handler, helptext) -- wrap up the handler and only allow it if cheats are active gadgetHandler:AddChatAction(command, function (cmd, line, wordlist, playerID) if CheatMode() then local _, _, _, teamID = GetPlayerInfo(playerID) handler(cmd, line, wordlist, playerID, teamID) else local message = command .. ' can only be called when cheats are active!' Spring.Echo(message) end end, helptext) end function gadget:Initialize() for command, details in pairs(commands) do RegisterCheatHandler(command, details.handler, help) end end -- make it reload safe function gadget:ShutDown() for command, _ in pairs(commands) do gadgetHandler:RemoveChatAction(command) end end
411
0.831686
1
0.831686
game-dev
MEDIA
0.99136
game-dev
0.920638
1
0.920638
cmss13-devs/cmss13
2,371
code/datums/keybinding/vehicles.dm
/datum/keybinding/vehicles category = CATEGORY_VEHICLE weight = WEIGHT_VEHICLE /datum/keybinding/vehicles/can_use(client/user) if(!ishuman(user.mob)) return FALSE var/obj/vehicle/multitile/vehicle_check = user.mob.interactee if(!istype(vehicle_check)) return FALSE return TRUE /datum/keybinding/vehicles/toggle_door_lock hotkey_keys = list("Unbound") classic_keys = list("Unbound") name = "Toggle door locks" full_name = "Toggle Door Locks" keybind_signal = COMSIG_KB_VEHICLE_TOGGLE_LOCKS /datum/keybinding/vehicles/toggle_door_lock/down(client/user) . = ..() if(.) return var/obj/vehicle/multitile/vehicle_get = user.mob.interactee vehicle_get.toggle_door_lock() return TRUE /datum/keybinding/vehicles/get_vehicle_status hotkey_keys = list("Unbound") classic_keys = list("Unbound") name = "See vehicle status" full_name = "See Vehicle Status" keybind_signal = COMSIG_KB_VEHICLE_GET_STATUS /datum/keybinding/vehicles/get_vehicle_status/down(client/user) . = ..() if(.) return var/obj/vehicle/multitile/vehicle_user = user.mob.interactee vehicle_user.get_status_info() return TRUE /datum/keybinding/vehicles/change_selected_hardpoint hotkey_keys = list("Unbound") classic_keys = list("Unbound") name = "Change Active Hardpoint" full_name = "Change Active Hardpoint" keybind_signal = COMSIG_KB_VEHICLE_CHANGE_SELECTED_WEAPON /datum/keybinding/vehicles/change_selected_hardpoint/down(client/user) . = ..() if(.) return var/obj/vehicle/multitile/vehicle_user = user.mob.interactee vehicle_user.cycle_hardpoint() /datum/keybinding/vehicles/activate_horn hotkey_keys = list("Unbound") classic_keys = list("Unbound") name = "Activate horn" full_name = "Activate Horn" keybind_signal = COMSIG_KB_VEHICLE_ACTIVATE_HORN /datum/keybinding/vehicles/activate_horn/down(client/user) . = ..() if(.) return var/obj/vehicle/multitile/vehicle_user = user.mob.interactee vehicle_user.activate_horn() return TRUE /datum/keybinding/vehicles/reload_weapon hotkey_keys = list("Unbound") classic_keys = list("Unbound") name = "Reload weapon" full_name = "Reload Weapon" keybind_signal = COMSIG_KB_VEHICLE_RELOAD_WEAPON /datum/keybinding/vehicles/reload_weapon/down(client/user) . = ..() if(.) return var/obj/vehicle/multitile/vehicle_user = user.mob.interactee vehicle_user.reload_firing_port_weapon() return TRUE
411
0.834429
1
0.834429
game-dev
MEDIA
0.912252
game-dev
0.940554
1
0.940554
googlecreativelab/chrome-music-lab
2,077
arpeggios/third_party/Tone.js/test/component/Compressor.js
define(["Tone/component/Compressor", "helper/Basic", "helper/PassAudio", "helper/PassAudioStereo", "Test"], function (Compressor, Basic, PassAudio, PassAudioStereo, Test) { describe("Compressor", function(){ Basic(Compressor); context("Compression", function(){ it("handles input and output connections", function(){ var comp = new Compressor(); Test.connect(comp); comp.connect(Test); comp.dispose(); }); it("passes the incoming signal through", function(done){ var comp; PassAudio(function(input, output){ comp = new Compressor(); input.connect(comp); comp.connect(output); }, function(){ comp.dispose(); done(); }); }); it("passes the incoming stereo signal through", function(done){ var comp; PassAudioStereo(function(input, output){ comp = new Compressor(); input.connect(comp); comp.connect(output); }, function(){ comp.dispose(); done(); }); }); it("can be get and set through object", function(){ var comp = new Compressor(); var values = { "ratio" : 22, "threshold" : -30, "release" : 0.5, "attack" : 0.03, "knee" : 20 }; comp.set(values); expect(comp.get()).to.have.keys(["ratio", "threshold", "release", "attack", "ratio"]); comp.dispose(); }); it("can get/set all interfaces", function(){ var comp = new Compressor(); var values = { "ratio" : 22, "threshold" : -30, "release" : 0.5, "attack" : 0.03, "knee" : 20 }; comp.ratio.value = values.ratio; comp.threshold.value = values.threshold; comp.release.value = values.release; comp.attack.value = values.attack; comp.knee.value = values.knee; expect(comp.ratio.value).to.equal(values.ratio); expect(comp.threshold.value).to.equal(values.threshold); expect(comp.release.value).to.equal(values.release); expect(comp.attack.value).to.be.closeTo(values.attack, 0.01); expect(comp.knee.value).to.equal(values.knee); comp.dispose(); }); }); }); });
411
0.778031
1
0.778031
game-dev
MEDIA
0.523338
game-dev
0.731476
1
0.731476
plantuml/plantuml
3,966
src/main/java/net/sourceforge/plantuml/yaml/YamlDiagramFactory.java
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2024, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */ package net.sourceforge.plantuml.yaml; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sourceforge.plantuml.Previous; import net.sourceforge.plantuml.abel.DisplayPositioned; import net.sourceforge.plantuml.command.PSystemAbstractFactory; import net.sourceforge.plantuml.core.Diagram; import net.sourceforge.plantuml.core.DiagramType; import net.sourceforge.plantuml.core.UmlSource; import net.sourceforge.plantuml.json.JsonValue; import net.sourceforge.plantuml.jsondiagram.JsonDiagram; import net.sourceforge.plantuml.jsondiagram.StyleExtractor; import net.sourceforge.plantuml.klimt.creole.Display; import net.sourceforge.plantuml.klimt.geom.HorizontalAlignment; import net.sourceforge.plantuml.klimt.geom.VerticalAlignment; import net.sourceforge.plantuml.log.Logme; import net.sourceforge.plantuml.preproc.PreprocessingArtifact; import net.sourceforge.plantuml.skin.UmlDiagramType; import net.sourceforge.plantuml.style.parser.StyleParsingException; import net.sourceforge.plantuml.yaml.parser.MonomorphToJson; import net.sourceforge.plantuml.yaml.parser.YamlParser; public class YamlDiagramFactory extends PSystemAbstractFactory { public YamlDiagramFactory() { super(DiagramType.YAML); } @Override public Diagram createSystem(UmlSource source, Previous previous, PreprocessingArtifact preprocessing) { final List<Highlighted> highlighted = new ArrayList<>(); JsonValue yaml = null; StyleExtractor styleExtractor = null; try { final List<String> list = new ArrayList<>(); styleExtractor = new StyleExtractor(source.iterator2()); final Iterator<String> it = styleExtractor.getIterator(); it.next(); while (true) { final String line = it.next(); if (it.hasNext() == false) break; if (Highlighted.matchesDefinition(line)) { highlighted.add(Highlighted.build(line)); continue; } list.add(line); } // yaml = new SimpleYamlParser().parse(list); yaml = MonomorphToJson.convert(new YamlParser().parse(list)); } catch (Exception e) { Logme.error(e); } final JsonDiagram result = new JsonDiagram(source, UmlDiagramType.YAML, yaml, highlighted, styleExtractor, preprocessing); if (styleExtractor != null) { try { styleExtractor.applyStyles(result.getSkinParam()); } catch (StyleParsingException e) { Logme.error(e); } final String title = styleExtractor.getTitle(); if (title != null) result.setTitle(DisplayPositioned.single(Display.getWithNewlines(result.getPragma(), title), HorizontalAlignment.CENTER, VerticalAlignment.CENTER)); } return result; } @Override public UmlDiagramType getUmlDiagramType() { return UmlDiagramType.YAML; } }
411
0.767503
1
0.767503
game-dev
MEDIA
0.284497
game-dev
0.530331
1
0.530331
turikhay/MapModCompanion
5,252
spigot/src/main/java/com/turikhay/mc/mapmodcompanion/spigot/XaeroHandler.java
package com.turikhay.mc.mapmodcompanion.spigot; import com.turikhay.mc.mapmodcompanion.*; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerJoinEvent; import java.util.Arrays; import java.util.Locale; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; public class XaeroHandler implements Handler, Listener { private final Logger logger; private final String configPath; private final String channelName; private final MapModCompanion plugin; private final ScheduledExecutorService scheduler; public XaeroHandler(Logger logger, String configPath, String channelName, MapModCompanion plugin) { this.logger = logger; this.configPath = configPath; this.channelName = channelName; this.plugin = plugin; this.scheduler = Executors.newSingleThreadScheduledExecutor( new DaemonThreadFactory(ILogger.ofJava(logger), XaeroHandler.class) ); } public void init() throws InitializationException { plugin.registerOutgoingChannel(channelName); plugin.getServer().getPluginManager().registerEvents(this, plugin); logger.fine("Event listener has been registered"); } @Override public void cleanUp() { plugin.unregisterOutgoingChannel(channelName); HandlerList.unregisterAll(this); logger.fine("Event listener has been unregistered"); scheduler.shutdown(); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerJoined(PlayerJoinEvent event) { sendPacket(event, Type.JOIN); } @EventHandler(priority = EventPriority.MONITOR) public void onWorldChanged(PlayerChangedWorldEvent event) { sendPacket(event, Type.WORLD_CHANGE); } private void sendPacket(PlayerEvent event, Type type) { Player p = event.getPlayer(); World world = p.getWorld(); int id = plugin.getRegistry().getId(world); byte[] payload = LevelMapProperties.Serializer.instance().serialize(id); SendPayloadTask task = new SendPayloadTask(logger, plugin, p.getUniqueId(), channelName, payload, world.getUID()); int repeatTimes = plugin.getConfig().getInt( configPath + ".events." + type.name().toLowerCase(Locale.ROOT) + ".repeat_times", 1 ); if (repeatTimes > 1) { for (int i = 0; i < repeatTimes; i++) { scheduler.schedule(task, i, TimeUnit.SECONDS); } } else { task.run(); } } private enum Type { JOIN, WORLD_CHANGE, } public static class Factory implements Handler.Factory<MapModCompanion> { private final String configPath; private final String channelName; public Factory(String configPath, String channelName) { this.configPath = configPath; this.channelName = channelName; } @Override public String getName() { return channelName; } @Override public XaeroHandler create(MapModCompanion plugin) throws InitializationException { plugin.checkEnabled(configPath); XaeroHandler handler = new XaeroHandler( new PrefixLogger(plugin.getVerboseLogger(), channelName), configPath, channelName, plugin ); handler.init(); return handler; } } private static class SendPayloadTask implements Runnable { private final Logger logger; private final MapModCompanion plugin; private final UUID playerId; private final String channelName; private final byte[] payload; private final UUID expectedWorld; public SendPayloadTask(Logger logger, MapModCompanion plugin, UUID playerId, String channelName, byte[] payload, UUID expectedWorld) { this.logger = logger; this.plugin = plugin; this.playerId = playerId; this.channelName = channelName; this.payload = payload; this.expectedWorld = expectedWorld; } @Override public void run() { Player player = plugin.getServer().getPlayer(playerId); if (player == null) { return; } UUID world = player.getWorld().getUID(); if (!world.equals(expectedWorld)) { logger.fine("Skipping sending Xaero's LevelMapProperties to " + player.getName() + ": unexpected world"); return; } logger.fine(() -> "Sending Xaero's LevelMapProperties to " + player.getName() + ": " + Arrays.toString(payload)); player.sendPluginMessage(plugin, channelName, payload); } } }
411
0.935817
1
0.935817
game-dev
MEDIA
0.588963
game-dev
0.956062
1
0.956062
AmProsius/gothic-1-community-patch
8,175
scriptbase/_work/Data/Scripts/Content/AI/ZS_Human/ZS_AssessWarn.d
//////////////////////////////////////////////////////////////////////////////////////// // // ZS_AssessWarn // ============= // Der (menschliche) NSC wird von einem anderen (menschlichen) NSC vor einem Dritten // gewarnt. // - self: Empfnger der Warnung // - victim: Sender der Warnung // - other: der Dritte, vor dem gewarnt wird // // Folgende Flle knnen zu einer Warnung zwischen Menschen fhren: // 1. B_AssessFighter() -> der Spieler wird mit gezogener Waffe entdeckt // 2. B_AssessTheft() -> ein NSC wird vom Spieler beklaut (Taschendiebstahl) // 3. ZS_AlarmAll() -> nach AssessEnemy/Murder eines Freundes/Kameraden // 4. ZS_ObserveSuspect() // 5. B_AssessEnterRoom() -> der Spieler hat einen verbotenen Raum verlassen // 6. ZS_ClearRoom() -> der Spieler hat die Aufforderung, den Raum zu // verlassen nicht befolgt // 7. ZS_GuardPassage() -> Spieler hat verbotenen Durchgang durchschritten //////////////////////////////////////////////////////////////////////////////////////// func void ZS_AssessWarn () { PrintDebugNpc (PD_ZS_FRAME, "ZS_AssessWarn"); PrintGlobals (PD_ZS_CHECK); C_ZSInit (); var string nextWP; Npc_PercEnable (self, PERC_ASSESSDAMAGE , ZS_ReactToDamage ); Npc_PercEnable (self, PERC_ASSESSMAGIC , B_AssessMagic ); Npc_PercEnable (self, PERC_ASSESSENEMY , B_AssessEnemy ); Npc_PercEnable (self, PERC_ASSESSFIGHTER , B_AssessFighter ); Npc_PercEnable (self, PERC_ASSESSTHREAT , B_AssessFighter ); Npc_PercEnable (self, PERC_DRAWWEAPON , B_AssessFighter ); Npc_PercEnable (self, PERC_ASSESSMURDER , ZS_AssessMurder ); Npc_PercEnable (self, PERC_ASSESSDEFEAT , ZS_AssessDefeat ); Npc_PercEnable (self, PERC_CATCHTHIEF , ZS_CatchThief ); Npc_PercEnable (self, PERC_ASSESSTHEFT , B_AssessTheft ); Npc_PercEnable (self, PERC_OBSERVEINTRUDER , B_ObserveIntruder ); Npc_PercEnable (self, PERC_ASSESSTALK , B_AssessTalk ); // evtl. raus wg. Verarschen (vars werden neu initialisiert Npc_PercEnable (self, PERC_ASSESSENTERROOM , B_AssessEnterRoom ); Npc_SetPercTime (self, 1); // ----------------- MH: fr ItemSchweine (EBR-Haus. Lares, etc) ------------------ if (victim.aivar[AIV_ITEMSCHWEIN]==TRUE) && (Npc_GetAttitude(self,victim) == ATT_FRIENDLY) { Npc_SetTarget (self, other); AI_StartState (self, ZS_Attack, 0, ""); } //-------- Fall 5/6: der Spieler im verbotenen Raum -------- else if C_NpcIsGuard(self) && ((Npc_IsInState(victim,ZS_CallGuardsOnEnterRoom)) || (Npc_WasInState (victim,ZS_CallGuardsOnEnterRoom))) && !Npc_IsInState(self,ZS_GuardPassage) && (Npc_GetAttitude(self,victim) == ATT_FRIENDLY) { PrintDebugNpc (PD_ZS_CHECK, "...verlassener Portalraum gehrt Schtzling-Gilde!"); Npc_PercEnable (self, PERC_ASSESSENTERROOM , B_ClearRoomEnterRoom); B_WhirlAround (self, other); AI_PointAtNpc (self, other); B_Say (self, other, "$HEYYOU"); AI_StopPointAt (self); Npc_PercDisable (self, PERC_MOVENPC); AI_SetWalkmode (self, NPC_RUN); AI_GotoNpc (self, other); B_Say (self, other, "$WHATDIDYOUINTHERE"); } else if C_NpcIsGuardArcher(self) && Npc_IsInState(victim,ZS_CallGuardsOnEnterRoom) && (Npc_GetAttitude(self,victim) == ATT_FRIENDLY) { PrintDebugNpc (PD_ZS_CHECK, "...Warnung von Schtzling, dessen Raum betreten/verlassen wurde!"); if (other.aivar[AIV_HASBEENDEFEATEDINPORTALROOM] == FALSE) { B_WhirlAround (self, hero); AI_PointAtNpc (self, hero); B_Say (self, hero, "$HEYYOU"); AI_StopPointAt (self); B_DrawWeapon (self, other); B_Say (self, hero, "$YOUVIOLATEDFORBIDDENTERRITORY"); Npc_SetTarget (self, hero); AI_StartState (self, ZS_Attack, 0, ""); } else { PrintDebugNpc (PD_ZS_CHECK, "Eindringling ist schon bestraft worden"); }; } //-------- Fall 7: Spieler hat verbotenen Durchgang durchschritten -------- else if (C_NpcIsGuard(self) || C_NpcIsGuardArcher(self) || C_NpcIsBoss(self)) && (Npc_WasInState(victim,ZS_GuardPassage) || Npc_IsInState(victim,ZS_GuardPassage)) && (Npc_GetAttitude(self,victim) == ATT_FRIENDLY) { PrintDebugNpc (PD_ZS_CHECK, "...Warnung von Torwache, deren Durchgang durchbrochen worde"); B_WhirlAround (self, hero); B_DrawWeapon (self, other); B_SetAttackReason (self, AIV_AR_INTRUDER); Npc_SetTarget (self, hero); Npc_GetTarget (self); AI_StartState (self, ZS_ProclaimAndPunish, 0, ""); } //-------- Fall 8: Feind entdeckt -------- else if Npc_IsInState(victim,ZS_AssessEnemy) && (C_NpcIsGuard(self) || C_NpcIsGuardArcher(self)) && (Npc_GetAttitude(self,victim) == ATT_FRIENDLY) && (Npc_GetAttitude(self,other) != ATT_FRIENDLY) && !(Npc_IsPlayer(other) && (self.npctype == NPCTYPE_FRIEND)) && (Npc_GetDistToNpc(self,victim) < HAI_DIST_HELPATTACKEDCHARGES) { PrintDebugNpc (PD_ZS_CHECK, "...Warnung vor Feind!"); AI_StartState (self, ZS_AssessEnemy, 0, ""); } //-------- Schleicher finden ------------------- else if (C_BodyStateContains ( other, BS_SNEAK) && Npc_GetDistToNpc ( self, other) < PERC_DIST_INTERMEDIAT) { PrintDebugNpc (PD_ZS_CHECK, "...Spieler schleicht rum und ich bin gewarnt worden"); Npc_SetTarget (self, other); Npc_GetTarget ( self); AI_StartState (self, ZS_ObserveSuspect, 0, ""); } //-------- Default-Reaktion auf Warnung -------- else { //SN: keine Default-Reaktion!!! //AI_Wait (self, 1.0); // Reaktionszeit //B_WhirlAround (self, other); }; }; func int ZS_AssessWarn_Loop () { PrintDebugNpc (PD_ZS_LOOP, "ZS_AssessWarn_Loop" ); AI_Wait (self, 2); // ...2 Sekunden alles beobachten... return LOOP_END; // ...dann Abbruch! }; func void ZS_AssessWarn_End () { PrintDebugNpc (PD_ZS_FRAME, "ZS_AssessWarn_End"); if (Npc_CanSeeNpcFreeLOS(self, other)) { PrintDebugNpc (PD_ZS_CHECK, "ZS_AssessWarn End // Free Los"); //JP: Temp und Perm sind beide wichtig, ich habe Perm mal noch dazugenommen if ((Npc_GetTempAttitude(self, other) == ATT_HOSTILE) || (Npc_GetPermAttitude ( self, other) == ATT_HOSTILE)) { PrintDebugNpc (PD_ZS_CHECK, "ZS_AssessWarn End // Free Los // HOSTILE"); Npc_SetTarget (self, other); Npc_GetTarget (self); AI_StartState (self, ZS_AssessEnemy, 0, ""); return; } else if (Npc_HasNews(self, NEWS_MURDER, other, victim) && Npc_GetGuildAttitude ( self, victim) == ATT_FRIENDLY) { PrintDebugNpc (PD_ZS_CHECK, "ZS_AssessWarn End // Free Los //Not HOSTILE Kumpel gettet"); // JP: Hier gab es kein Svm, ich habe da mal noch eins eingefgt, damit wenigstens klar ist, da wird der Sc angegriffen Npc_GetTarget (self); AI_StartState (self, ZS_AssessEnemy, 0, ""); } else { PrintDebugNpc (PD_ZS_CHECK, "ZS_AssessWarn End// Free Los // Not HOSTILE"); B_AssessSc (); return; }; return; } else { PrintDebugNpc (PD_ZS_CHECK, "ZS_AssessWarn End// CanT See"); return; }; };
411
0.940212
1
0.940212
game-dev
MEDIA
0.988716
game-dev
0.968782
1
0.968782
Open-GTO/Open-GTO
2,048
sources/admin/admin_commands/cmd_mute.pwn
/* About: mute admin command Author: ziggi */ #if defined _admin_cmd_mute_included #endinput #endif #define _admin_cmd_mute_included COMMAND:mute(playerid, params[]) { if (!IsPlayerHavePrivilege(playerid, PlayerPrivilegeModer)) { return 0; } new subparams[32], time = -1, reason[MAX_MUTE_REASON_LENGTH]; if (sscanf(params, "s[32]k<ftime>S()[" #MAX_MUTE_REASON_LENGTH "]", subparams, time, reason)) { Lang_SendText(playerid, "ADMIN_COMMAND_MUTE_HELP"); return 1; } if (time == -1) { Lang_SendText(playerid, "ADMIN_COMMAND_TIME_ERROR"); return 1; } new targetid = INVALID_PLAYER_ID; if (strcmp(subparams, "all", true) == 0) { targetid = -1; } else if (sscanf(subparams, "u", targetid) || targetid == INVALID_PLAYER_ID) { Lang_SendText(playerid, "ADMIN_COMMAND_MUTE_TARGET_ERROR"); return 1; } new is_with_reason, timeword[MAX_LANG_VALUE_STRING], targetname[MAX_PLAYER_NAME + 1], playername[MAX_PLAYER_NAME + 1]; is_with_reason = strlen(reason) != 0; Declension_GetSeconds2(playerid, time, timeword); GetPlayerName(playerid, playername, sizeof(playername)); if (targetid == -1) { if (is_with_reason) { Lang_SendTextToAll("ADMIN_COMMAND_MUTE_ALL_REASON", playername, playerid, time, timeword, reason); } else { Lang_SendTextToAll("ADMIN_COMMAND_MUTE_ALL", playername, playerid, time, timeword); } foreach (targetid : Player) { MutePlayer(targetid, time); } } else { GetPlayerName(targetid, targetname, sizeof(targetname)); if (is_with_reason) { Lang_SendTextToAll("ADMIN_COMMAND_MUTE_PLAYER_REASON", playername, playerid, targetname, targetid, time, timeword, reason); Lang_SendText(playerid, "ADMIN_COMMAND_MUTE_PLAYER_SELF_REASON", targetname, targetid, time, timeword, reason); } else { Lang_SendTextToAll("ADMIN_COMMAND_MUTE_PLAYER", playername, playerid, targetname, targetid, time, timeword); Lang_SendText(playerid, "ADMIN_COMMAND_MUTE_PLAYER_SELF", targetname, targetid, time, timeword); } MutePlayer(targetid, time); } return 1; }
411
0.707793
1
0.707793
game-dev
MEDIA
0.610798
game-dev
0.681331
1
0.681331
pathea-games/planetexplorers
5,016
Assets/Scripts/GameUITest/UI/Scripe/CSUI/CSUI_Train/CSUI_TrainNpcInfCtrl.cs
using UnityEngine; using System.Collections; using Pathea; using System.Collections.Generic; public class CSUI_TrainNpcInfCtrl : MonoBehaviour { [SerializeField] GameObject m_InfoPage;//学员信息节点 [SerializeField] GameObject m_InventoryPage;//学员存货节点 private CSPersonnel m_Npc; public CSPersonnel Npc { get { return m_Npc; } set { //lz-2016.10.14 避免上一个m_Npc身上的事件没有移除 if (null != m_Npc&& null!=m_Npc.m_Npc) { AbnormalConditionCmpt accOld = m_Npc.m_Npc.GetCmpt<AbnormalConditionCmpt>(); if (accOld != null) { accOld.evtStart -= AddNpcAbnormal; accOld.evtEnd -= RemoveNpcAbnormal; } } m_Npc = value; //lz-2016.10.14 重新添加事件 if (null != m_Npc && null != m_Npc.m_Npc) { AbnormalConditionCmpt accNew = m_Npc.m_Npc.GetCmpt<AbnormalConditionCmpt>(); if (accNew != null) { accNew.evtStart += AddNpcAbnormal; accNew.evtEnd += RemoveNpcAbnormal; } } RefreshNpcAbnormal(); } } private void PageInfoOnActive(bool active) { m_InfoPage.SetActive(active); } private void PageInvetoryOnActive(bool active) { m_InventoryPage.SetActive(active); } void Update() { GameUI.Instance.mCSUI_MainWndCtrl.TrainUI.UpdateTraineeSkillsShow(m_Npc); GameUI.Instance.mCSUI_MainWndCtrl.TrainUI.Reflashpackage(); if (m_Npc == null) { GameUI.Instance.mCSUI_MainWndCtrl.TrainUI.SetServantInfo("--", PeSex.Male, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); GameUI.Instance.mCSUI_MainWndCtrl.TrainUI.SetSprSex("null"); } else { GameUI.Instance.mCSUI_MainWndCtrl.TrainUI.SetServantInfo(m_Npc.FullName, m_Npc.Sex, (int)m_Npc.GetAttribute(AttribType.Hp), (int)m_Npc.GetAttribute(AttribType.HpMax), (int)m_Npc.GetAttribute(AttribType.Stamina), (int)m_Npc.GetAttribute(AttribType.StaminaMax), (int)m_Npc.GetAttribute(AttribType.Hunger), (int)m_Npc.GetAttribute(AttribType.HungerMax), (int)m_Npc.GetAttribute(AttribType.Comfort), (int)m_Npc.GetAttribute(AttribType.ComfortMax), (int)m_Npc.GetAttribute(AttribType.Oxygen), (int)m_Npc.GetAttribute(AttribType.OxygenMax), (int)m_Npc.GetAttribute(AttribType.Shield), (int)m_Npc.GetAttribute(AttribType.ShieldMax), (int)m_Npc.GetAttribute(AttribType.Energy), (int)m_Npc.GetAttribute(AttribType.EnergyMax), (int)m_Npc.GetAttribute(AttribType.Atk), (int)m_Npc.GetAttribute(AttribType.Def)); } } #region Abnormal [SerializeField] UIGrid mAbnormalGrid; [SerializeField] CSUI_BuffItem mAbnormalPrefab; bool mReposition = false; private List<CSUI_BuffItem> mAbnormalList = new List<CSUI_BuffItem>(1); void RefreshNpcAbnormal() { RemoveAllAbnormal(); if (m_Npc == null) { return; } List<PEAbnormalType> abList = m_Npc.m_Npc.Alnormal.GetActiveAbnormalList(); if (abList.Count == 0) return; for (int i = 0; i < abList.Count; i++) { AddNpcAbnormal(abList[i]); } } void AddNpcAbnormal(PEAbnormalType type) { AbnormalData data = AbnormalData.GetData(type); //lz-2016.08.26 异常状态是0的图标不显示 if (null == data || data.iconName == "0") return; CSUI_BuffItem item = Instantiate(mAbnormalPrefab) as CSUI_BuffItem; if (!item.gameObject.activeSelf) item.gameObject.SetActive(true); item.transform.parent = mAbnormalGrid.transform; CSUtils.ResetLoacalTransform(item.transform); item.SetInfo(data.iconName, data.description); mAbnormalList.Add(item); mReposition = true; } void RemoveNpcAbnormal(PEAbnormalType type) { AbnormalData data = AbnormalData.GetData(type); //lz-2016.08.26 异常状态是0的图标不显示 if (null == data || data.iconName == "0") return; CSUI_BuffItem item = mAbnormalList.Find(i => i._icon == data.iconName); if (item == null) return; Destroy(item.gameObject); mAbnormalList.Remove(item); mReposition = true; } void RemoveAllAbnormal() { if (mAbnormalList.Count == 0) return; for (int i = 0; i < mAbnormalList.Count; i++) { Destroy(mAbnormalList[i].gameObject); mAbnormalList.Remove(mAbnormalList[i]); } } void UpdateReposition() { if (mReposition) { mReposition = false; mAbnormalGrid.repositionNow = true; } } void LateUpdate() { UpdateReposition(); } #endregion }
411
0.843321
1
0.843321
game-dev
MEDIA
0.967188
game-dev
0.971905
1
0.971905
BluSunrize/ImmersiveEngineering
4,011
src/main/java/blusunrize/immersiveengineering/common/blocks/multiblocks/shapes/RadioTowerShapes.java
/* * BluSunrize * Copyright (c) 2024 * * This code is licensed under "Blu's License of Common Sense" * Details can be found in the license file in the root folder of this project */ package blusunrize.immersiveengineering.common.blocks.multiblocks.shapes; import blusunrize.immersiveengineering.api.utils.shapes.ShapeUtils; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import java.util.function.Function; public class RadioTowerShapes implements Function<BlockPos, VoxelShape> { public static final Function<BlockPos, VoxelShape> SHAPE_GETTER = new RadioTowerShapes(); private RadioTowerShapes() { } @Override public VoxelShape apply(BlockPos posInMultiblock) { if(posInMultiblock.getY() < 2) { if(posInMultiblock.getZ() <= 3) // concrete foundation return Shapes.block(); else if(posInMultiblock.getZ()==5) // control box front return Shapes.block(); else if(posInMultiblock.getZ()==4&&posInMultiblock.getY()==0) // control center bottom return Shapes.block(); else if(posInMultiblock.getX()==2) // control center top return Shapes.box(0, 0, 0, 1, .625, 1); else { // control center sides if(posInMultiblock.getX()==1) return Shapes.or( Shapes.box(0, 0, 0, 1, .5, 1), Shapes.box(.375, .5, .3125, 1, .625, 1) ); else if(posInMultiblock.getX()==3) return Shapes.or( Shapes.box(0, 0, 0, 1, .5, 1), Shapes.box(0, .5, .3125, .625, .625, 1) ); } } else if(posInMultiblock.getY() < 10) { // calculate sloping, .5 inwards over 10 blocks means .05 per step? final double indent = (posInMultiblock.getY()-2)*.05; double xMin = 0; double xMax = 1; double zMin = 0; double zMax = 1; if(posInMultiblock.getX()==1) xMin += indent; if(posInMultiblock.getX()==3) xMax -= indent; if(posInMultiblock.getZ()==1) zMin += indent; if(posInMultiblock.getZ()==3) zMax -= indent; return Shapes.box(xMin, 0, zMin, xMax, 1, zMax); } else if(posInMultiblock.getY() < 15) { Direction side = posInMultiblock.getZ()==0?Direction.NORTH: posInMultiblock.getZ()==4?Direction.SOUTH: posInMultiblock.getX()==0?Direction.WEST: Direction.EAST; // cental column if(posInMultiblock.getX() >= 1&&posInMultiblock.getX() <= 3&&posInMultiblock.getZ() >= 1&&posInMultiblock.getZ() <= 3) return Shapes.block(); // sloping at the top if(posInMultiblock.getY()==14) return Shapes.or( Shapes.create(ShapeUtils.transformAABB(new AABB(0, 0, 0, 1, .3125, .5), side)), Shapes.create(ShapeUtils.transformAABB(new AABB(0, 0, .5, 1, .6875, 1), side)) ); // sloping at the bottom if(posInMultiblock.getY()==10) return Shapes.or( Shapes.create(ShapeUtils.transformAABB(new AABB(0, .6875, 0, 1, 1, .5), side)), Shapes.create(ShapeUtils.transformAABB(new AABB(0, .3125, .5, 1, 1, 1), side)) ); // solid faces if((posInMultiblock.getX()==0||posInMultiblock.getX()==4)&&posInMultiblock.getZ() >= 1&&posInMultiblock.getZ() <= 3) return Shapes.block(); if(posInMultiblock.getX() >= 1&&posInMultiblock.getX() <= 3&&(posInMultiblock.getZ()==0||posInMultiblock.getZ()==4)) return Shapes.block(); // vertical corners VoxelShape zBox; VoxelShape xBox; if(posInMultiblock.getZ()==0) zBox = Shapes.box(0, 0, .5, 1, 1, 1); else zBox = Shapes.box(0, 0, 0, 1, 1, .5); if(posInMultiblock.getX()==0) xBox = Shapes.box(.5, 0, 0, 1, 1, 1); else xBox = Shapes.box(0, 0, 0, .5, 1, 1); return Shapes.or(zBox, xBox); } else { if(posInMultiblock.getX()!=2||posInMultiblock.getZ()!=2) return Shapes.empty(); // .2 inwards over 4 blocks, .05 per step final double indent = (posInMultiblock.getY()-15)*.05; return Shapes.box(indent, 0, indent, 1-indent, 1, 1-indent); } return Shapes.empty(); } }
411
0.930546
1
0.930546
game-dev
MEDIA
0.77081
game-dev,graphics-rendering
0.994342
1
0.994342
ax-grymyr/l2dn-server
3,550
L2Dn/L2Dn.GameServer.Scripts/Handlers/EffectHandlers/MagicalAttackMp.cs
using L2Dn.GameServer.Enums; using L2Dn.GameServer.Model; using L2Dn.GameServer.Model.Actor; using L2Dn.GameServer.Model.Effects; using L2Dn.GameServer.Model.Items.Instances; using L2Dn.GameServer.Model.Skills; using L2Dn.GameServer.Model.Stats; using L2Dn.GameServer.Network.Enums; using L2Dn.GameServer.Network.OutgoingPackets; using L2Dn.Utilities; namespace L2Dn.GameServer.Scripts.Handlers.EffectHandlers; /// <summary> /// Magical Attack MP effect. /// </summary> public sealed class MagicalAttackMp: AbstractEffect { private readonly double _power; private readonly bool _critical; private readonly double _criticalLimit; public MagicalAttackMp(StatSet @params) { _power = @params.getDouble("power"); _critical = @params.getBoolean("critical"); _criticalLimit = @params.getDouble("criticalLimit"); } public override bool calcSuccess(Creature effector, Creature effected, Skill skill) { if (effected.isMpBlocked()) return false; if (effector.isPlayer() && effected.isPlayer() && effected.isAffected(EffectFlag.DUELIST_FURY) && !effector.isAffected(EffectFlag.DUELIST_FURY)) return false; if (!Formulas.calcMagicAffected(effector, effected, skill)) { if (effector.isPlayer()) effector.sendPacket(SystemMessageId.YOUR_ATTACK_HAS_FAILED); if (effected.isPlayer()) { SystemMessagePacket sm = new SystemMessagePacket(SystemMessageId.C1_RESISTED_C2_S_DRAIN); sm.Params.addString(effected.getName()); sm.Params.addString(effector.getName()); effected.sendPacket(sm); } return false; } return true; } public override EffectType getEffectType() => EffectType.MAGICAL_ATTACK; public override bool isInstant() => true; public override void instant(Creature effector, Creature effected, Skill skill, Item? item) { if (effector.isAlikeDead()) return; bool sps = skill.useSpiritShot() && effector.isChargedShot(ShotType.SPIRITSHOTS); bool bss = skill.useSpiritShot() && effector.isChargedShot(ShotType.BLESSED_SPIRITSHOTS); byte shld = Formulas.calcShldUse(effector, effected); bool mcrit = _critical && Formulas.calcCrit(skill.getMagicCriticalRate(), effector, effected, skill); double damage = Formulas.calcManaDam(effector, effected, skill, _power, shld, sps, bss, mcrit, _criticalLimit); double mp = Math.Min(effected.getCurrentMp(), damage); if (damage > 0) { effected.stopEffectsOnDamage(); effected.setCurrentMp(effected.getCurrentMp() - mp); } if (effected.isPlayer()) { SystemMessagePacket sm = new SystemMessagePacket(SystemMessageId.S2_S_MP_HAS_BEEN_DRAINED_BY_C1); sm.Params.addString(effector.getName()); sm.Params.addInt((int)mp); effected.sendPacket(sm); } if (effector.isPlayer()) { SystemMessagePacket sm2 = new SystemMessagePacket(SystemMessageId.YOUR_OPPONENT_S_MP_WAS_REDUCED_BY_S1); sm2.Params.addInt((int)mp); effector.sendPacket(sm2); } } public override int GetHashCode() => HashCode.Combine(_power, _critical, _criticalLimit); public override bool Equals(object? obj) => this.EqualsTo(obj, static x => (x._power, x._critical, x._criticalLimit)); }
411
0.925581
1
0.925581
game-dev
MEDIA
0.987845
game-dev
0.953024
1
0.953024
folgerwang/UnrealEngine
4,289
Engine/Source/Runtime/SlateCore/Public/Animation/SlateSprings.h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" /** * One-dimensional spring simulation */ template< typename FloatType > class TSpring1D { public: /** * Spring configuration */ class FSpringConfig { public: /** Spring constant (how springy, lower values = more springy!) */ FloatType SpringConstant; /** Length of the spring */ FloatType SpringLength; /** Damp constant */ FloatType DampConstant; /** Epsilon for snapping position and velocity */ FloatType SnappingEpsilon; /** Whether to skip animation when a hitch occurs. If enabled, the spring's position will be set to the target position with large quantums, otherwise the spring will animate in slow motion. */ bool bSkipAnimationOnHitches; /** Constructor */ FSpringConfig() : SpringConstant( FloatType( 20.0 ) ), SpringLength( FloatType( 0.0 ) ), DampConstant( FloatType( 0.5 ) ), SnappingEpsilon( FloatType( 0.01 ) ), bSkipAnimationOnHitches( true ) { } }; /** * Constructor */ TSpring1D() : Position( 0.0 ), Target( 0.0 ), PreviousTarget( 0.0 ) { } /** * Construct at specified position */ TSpring1D( FloatType InPosition ) : Position( InPosition ), Target( InPosition ), PreviousTarget( InPosition ) { } /** * Sets the config for this spring * * @param InConfig New configuration */ void SetConfig( const FSpringConfig& InConfig ) { Config = InConfig; } /** * Sets the current position (and target position) for the spring * * @param InTarget New position */ void SetPosition( FloatType InPosition ) { Position = InPosition; Target = InPosition; PreviousTarget = InPosition; } /** * Gets the current position of the spring * * @return Current position for this spring */ FloatType GetPosition() const { return Position; } /** * Sets the target position for the spring * * @param InTarget New target position */ void SetTarget( FloatType InTarget ) { Target = InTarget; } /** * Gets the target position * * @return Target position for this spring */ FloatType GetTarget() const { return Target; } /** @return True if the spring is at rest (i.e. at its target position) */ bool IsAtRest() { return Target == Position; } /** * Updates the simulation. Should be called every tick! * * @param InQuantum Time passed since last update */ void Tick( float InQuantum ) { const float MaxQuantum = 1.0f / 8.0f; if( InQuantum > MaxQuantum ) { // If we are configured to reset the spring's state to the new position immediately upon // a hitch, then we'll do that now. if( Config.bSkipAnimationOnHitches ) { Position = PreviousTarget = Target; } else { // Not asked to reset on large quantums, so we'll instead clamp the quantum so that // the spring does not behave erratically. (slow motion) InQuantum = MaxQuantum; } } const FloatType Disp = Target - Position; const FloatType DispLength = FMath::Abs( Disp ); if( DispLength > Config.SnappingEpsilon ) { const FloatType ForceDirection = Disp >= 0.0f ? 1.0f : -1.0f; const FloatType TargetDisp = Target - PreviousTarget; const FloatType VelocityOfTarget = TargetDisp * InQuantum; const FloatType DistBetweenDisplacements = FMath::Abs( Disp - VelocityOfTarget ); const FloatType ForceAmount = Config.SpringConstant * FMath::Max< FloatType >( 0.0, DispLength - Config.SpringLength ) + Config.DampConstant * DistBetweenDisplacements; // We use Min here to prevent overshoots Position += ForceDirection * FMath::Min( DispLength, ForceAmount * InQuantum ); } // Snap new position to target if we're close enough if( FMath::Abs( Position - Target ) < Config.SnappingEpsilon ) { Position = Target; } PreviousTarget = Target; } private: /** Configuration */ FSpringConfig Config; /** Current position */ FloatType Position; /** Target position */ FloatType Target; /** Previous target position */ FloatType PreviousTarget; }; /** One-dimensional float spring */ typedef TSpring1D<float> FFloatSpring1D; /** One-dimensional double spring */ typedef TSpring1D<double> FDoubleSpring1D;
411
0.897839
1
0.897839
game-dev
MEDIA
0.649985
game-dev
0.89143
1
0.89143
PlayPro/CoreProtect
21,975
src/main/java/net/coreprotect/consumer/Queue.java
package net.coreprotect.consumer; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.CreatureSpawner; import org.bukkit.block.data.Bisected; import org.bukkit.block.data.Bisected.Half; import org.bukkit.block.data.type.Bed; import org.bukkit.block.data.type.Bed.Part; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import net.coreprotect.CoreProtect; import net.coreprotect.bukkit.BukkitAdapter; import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; import net.coreprotect.consumer.process.Process; import net.coreprotect.listener.block.BlockUtil; import net.coreprotect.model.BlockGroup; import net.coreprotect.thread.Scheduler; import net.coreprotect.utility.BlockUtils; import net.coreprotect.utility.EntityUtils; public class Queue { protected static synchronized int modifyForceContainer(String id, ItemStack[] container) { List<ItemStack[]> forceList = ConfigHandler.forceContainer.get(id); if (forceList == null) { return 0; } if (container == null) { forceList.remove(0); } else { forceList.add(container); } return forceList.size(); } protected static synchronized int getChestId(String id) { int chestId = ConfigHandler.loggingChest.getOrDefault(id, -1) + 1; ConfigHandler.loggingChest.put(id, chestId); return chestId; } protected static synchronized int getItemId(String id) { int chestId = ConfigHandler.loggingItem.getOrDefault(id, -1) + 1; ConfigHandler.loggingItem.put(id, chestId); return chestId; } private static synchronized void addConsumer(int currentConsumer, Object[] data) { Consumer.consumer.get(currentConsumer).add(data); } private static synchronized void queueStandardData(int consumerId, int currentConsumer, String[] user, Object object) { Consumer.consumerUsers.get(currentConsumer).put(consumerId, user); Consumer.consumerObjects.get(currentConsumer).put(consumerId, object); Consumer.consumer_id.put(currentConsumer, new Integer[] { Consumer.consumer_id.get(currentConsumer)[0], 0 }); } protected static void queueAdvancedBreak(String user, BlockState block, Material type, String blockData, int data, Material breakType, int blockNumber) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.BLOCK_BREAK, type, data, breakType, 0, blockNumber, blockData }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block); } protected static void queueArtInsert(int id, String name) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.ART_INSERT, null, 0, null, 0, id, null }); queueStandardData(consumerId, currentConsumer, new String[] { null, null }, name); } protected static void queueBlockBreak(String user, BlockState block, Material type, String blockData, int extraData) { queueBlockBreak(user, block, type, blockData, null, extraData, 0); } protected static void queueBlockBreakValidate(final String user, final Block block, final BlockState blockState, final Material type, final String blockData, final int extraData, int ticks) { Scheduler.scheduleSyncDelayedTask(CoreProtect.getInstance(), () -> { try { if (!block.getType().equals(type)) { queueBlockBreak(user, blockState, type, blockData, null, extraData, 0); } } catch (Exception e) { e.printStackTrace(); } }, block.getLocation(), ticks); } protected static void queueBlockBreak(String user, BlockState block, Material type, String blockData, Material breakType, int extraData, int blockNumber) { if (type == Material.SPAWNER && block instanceof CreatureSpawner) { // Mob spawner CreatureSpawner mobSpawner = (CreatureSpawner) block; extraData = EntityUtils.getSpawnerType(mobSpawner.getSpawnedType()); } else if (type == Material.IRON_DOOR || BlockGroup.DOORS.contains(type) || type.equals(Material.SUNFLOWER) || type.equals(Material.LILAC) || type.equals(Material.TALL_GRASS) || type.equals(Material.LARGE_FERN) || type.equals(Material.ROSE_BUSH) || type.equals(Material.PEONY)) { // Double plant if (block.getBlockData() instanceof Bisected) { if (((Bisected) block.getBlockData()).getHalf().equals(Half.TOP)) { if (blockNumber == 5) { return; } if (block.getY() > BukkitAdapter.ADAPTER.getMinHeight(block.getWorld())) { block = block.getWorld().getBlockAt(block.getX(), block.getY() - 1, block.getZ()).getState(); if (type != block.getType()) { return; } blockData = block.getBlockData().getAsString(); } } } } else if (type.name().endsWith("_BED") && block.getBlockData() instanceof Bed) { if (((Bed) block.getBlockData()).getPart().equals(Part.HEAD)) { return; } } int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.BLOCK_BREAK, type, extraData, breakType, 0, blockNumber, blockData }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block); } protected static void queueBlockPlace(String user, BlockState blockLocation, Material blockType, BlockState blockReplaced, Material forceType, int forceD, int forceData, String blockData) { // If force_data equals "1", current block data will be used in consumer. Material type = blockType; int data = 0; Material replaceType = null; int replaceData = 0; if (type == Material.SPAWNER && blockLocation instanceof CreatureSpawner) { // Mob spawner CreatureSpawner mobSpawner = (CreatureSpawner) blockLocation; data = EntityUtils.getSpawnerType(mobSpawner.getSpawnedType()); forceData = 1; } if (blockReplaced != null) { replaceType = blockReplaced.getType(); replaceData = 0; if ((replaceType == Material.IRON_DOOR || BlockGroup.DOORS.contains(replaceType) || replaceType.equals(Material.SUNFLOWER) || replaceType.equals(Material.LILAC) || replaceType.equals(Material.TALL_GRASS) || replaceType.equals(Material.LARGE_FERN) || replaceType.equals(Material.ROSE_BUSH) || replaceType.equals(Material.PEONY)) && replaceData >= 8) { // Double plant top half BlockState blockBelow = blockReplaced.getWorld().getBlockAt(blockReplaced.getX(), blockReplaced.getY() - 1, blockReplaced.getZ()).getState(); Material belowType = blockBelow.getType(); Queue.queueBlockBreak(user, blockBelow, belowType, blockBelow.getBlockData().getAsString(), 0); } } if (forceType != null) { type = forceType; forceData = 1; } if (forceD != -1) { data = forceD; forceData = 1; } String replacedBlockData = null; if (blockReplaced != null) { replacedBlockData = blockReplaced.getBlockData().getAsString(); } int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.BLOCK_PLACE, type, data, replaceType, replaceData, forceData, blockData, replacedBlockData }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, blockLocation); } protected static void queueBlockPlaceDelayed(final String user, final Location placed, final Material type, final String blockData, final BlockState replaced, int ticks) { Scheduler.scheduleSyncDelayedTask(CoreProtect.getInstance(), () -> { try { queueBlockPlace(user, placed.getBlock().getState(), type, replaced, null, -1, 0, blockData); } catch (Exception e) { e.printStackTrace(); } }, placed, ticks); } protected static void queueBlockPlaceValidate(final String user, final BlockState blockLocation, final Block block, final BlockState blockReplaced, final Material forceT, final int forceD, final int forceData, final String blockData, int ticks) { Scheduler.scheduleSyncDelayedTask(CoreProtect.getInstance(), () -> { try { Material blockType = block.getType(); if (blockType.equals(forceT)) { BlockState blockStateLocation = blockLocation; if (Config.getConfig(blockLocation.getWorld()).BLOCK_MOVEMENT) { blockStateLocation = BlockUtil.gravityScan(blockLocation.getLocation(), blockType, user).getState(); } queueBlockPlace(user, blockStateLocation, blockType, blockReplaced, forceT, forceD, forceData, blockData); } } catch (Exception e) { e.printStackTrace(); } }, blockLocation.getLocation(), ticks); } protected static void queueBlockGravityValidate(final String user, final Location location, final Block block, final Material blockType, int ticks) { Scheduler.scheduleSyncDelayedTask(CoreProtect.getInstance(), () -> { try { Block placementBlock = BlockUtil.gravityScan(location, blockType, user); if (!block.equals(placementBlock)) { queueBlockPlace(user, placementBlock.getState(), blockType, null, blockType, -1, 0, null); } } catch (Exception e) { e.printStackTrace(); } }, location, ticks); } protected static void queueContainerBreak(String user, Location location, Material type, ItemStack[] oldInventory) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.CONTAINER_BREAK, type, 0, null, 0, 0, null }); Consumer.consumerContainers.get(currentConsumer).put(consumerId, oldInventory); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location); } protected static synchronized void queueContainerTransaction(String user, Location location, Material type, Object inventory, int chestId) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.CONTAINER_TRANSACTION, type, 0, null, 0, chestId, null }); Consumer.consumerInventories.get(currentConsumer).put(consumerId, inventory); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location); } protected static void queueItemTransaction(String user, Location location, int time, int offset, int itemId) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.ITEM_TRANSACTION, null, offset, null, time, itemId, null }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location); } protected static void queueEntityInsert(int id, String name) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.ENTITY_INSERT, null, 0, null, 0, id, null }); queueStandardData(consumerId, currentConsumer, new String[] { null, null }, name); } protected static void queueEntityKill(String user, Location location, List<Object> data, EntityType type) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.ENTITY_KILL, null, 0, null, 0, 0 }); Consumer.consumerObjectList.get(currentConsumer).put(consumerId, data); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, new Object[] { location.getBlock().getState(), type, null }); } protected static void queueEntitySpawn(String user, BlockState block, EntityType type, int data) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.ENTITY_SPAWN, null, 0, null, 0, data, null }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, new Object[] { block, type }); } protected static void queueMaterialInsert(int id, String name) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.MATERIAL_INSERT, null, 0, null, 0, id, null }); queueStandardData(consumerId, currentConsumer, new String[] { null, null }, name); } protected static void queueBlockDataInsert(int id, String data) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.BLOCKDATA_INSERT, null, 0, null, 0, id, null }); queueStandardData(consumerId, currentConsumer, new String[] { null, null }, data); } protected static void queueNaturalBlockBreak(String user, BlockState block, Block relative, Material type, String blockData, int data) { List<BlockState> blockStates = new ArrayList<>(); if (relative != null) { blockStates.add(relative.getState()); } int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.NATURAL_BLOCK_BREAK, type, data, null, 0, 0, blockData }); Consumer.consumerBlockList.get(currentConsumer).put(consumerId, blockStates); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block); } protected static void queuePlayerChat(Player player, String message, long timestamp) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_CHAT, null, 0, null, 0, 0, null }); Consumer.consumerStrings.get(currentConsumer).put(consumerId, message); queueStandardData(consumerId, currentConsumer, new String[] { player.getName(), null }, new Object[] { timestamp, player.getLocation().clone() }); } protected static void queuePlayerCommand(Player player, String message, long timestamp) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_COMMAND, null, 0, null, 0, 0, null }); Consumer.consumerStrings.get(currentConsumer).put(consumerId, message); queueStandardData(consumerId, currentConsumer, new String[] { player.getName(), null }, new Object[] { timestamp, player.getLocation().clone() }); } protected static void queuePlayerInteraction(String user, BlockState block, Material type) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_INTERACTION, type, 0, null, 0, 0, null }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block); } protected static void queuePlayerKill(String user, Location location, String player) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_KILL, null, 0, null, 0, 0, null }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, new Object[] { location.getBlock().getState(), player }); } protected static void queuePlayerLogin(Player player, int time, int configSessions, int configUsernames) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); String uuid = player.getUniqueId().toString(); addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_LOGIN, null, configSessions, null, configUsernames, time, null }); Consumer.consumerStrings.get(currentConsumer).put(consumerId, uuid); queueStandardData(consumerId, currentConsumer, new String[] { player.getName(), uuid }, player.getLocation().clone()); } protected static void queuePlayerQuit(Player player, int time) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_LOGOUT, null, 0, null, 0, time, null }); queueStandardData(consumerId, currentConsumer, new String[] { player.getName(), null }, player.getLocation().clone()); } protected static void queueRollbackUpdate(String user, Location location, List<Object[]> list, int table, int action) { if (location == null) { location = new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0); } int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, table, null, 0, null, 0, action, null }); Consumer.consumerObjectArrayList.get(currentConsumer).put(consumerId, list); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location); } protected static void queueSignText(String user, Location location, int action, int color, int colorSecondary, boolean frontGlowing, boolean backGlowing, boolean isWaxed, boolean isFront, String line1, String line2, String line3, String line4, String line5, String line6, String line7, String line8, int offset) { /* if (line1.length() == 0 && line2.length() == 0 && line3.length() == 0 && line4.length() == 0) { return; } */ int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.SIGN_TEXT, null, color, null, action, offset, null }); Consumer.consumerSigns.get(currentConsumer).put(consumerId, new Object[] { colorSecondary, BlockUtils.getSignData(frontGlowing, backGlowing), isWaxed, isFront, line1, line2, line3, line4, line5, line6, line7, line8 }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location); } protected static void queueSignUpdate(String user, BlockState block, int action, int time) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.SIGN_UPDATE, null, action, null, 0, time, null }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block); } protected static void queueSkullUpdate(String user, BlockState block, int rowId) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.SKULL_UPDATE, null, 0, null, 0, rowId, null }); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block); } protected static void queueStructureGrow(String user, BlockState block, List<BlockState> blockList, int replacedListSize) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.STRUCTURE_GROWTH, null, 0, null, 0, replacedListSize, null }); Consumer.consumerBlockList.get(currentConsumer).put(consumerId, blockList); queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block); } protected static void queueWorldInsert(int id, String world) { int currentConsumer = Consumer.currentConsumer; int consumerId = Consumer.newConsumerId(currentConsumer); addConsumer(currentConsumer, new Object[] { consumerId, Process.WORLD_INSERT, null, 0, null, 0, id, null }); queueStandardData(consumerId, currentConsumer, new String[] { null, null }, world); } }
411
0.634027
1
0.634027
game-dev
MEDIA
0.96667
game-dev
0.859889
1
0.859889
LambdaInnovation/AcademyCraft
27,582
src/main/resources/assets/academy/lang/en_us.lang
# AcademyCraft Enligsh Language file # This file is mainly categorized by use (except for those which needs to follow the rules of Minecraft). # Common itemGroup.AcademyCraft=AcademyCraft ac.data_config_parse_fail=[AcademyCraft] Failed to parse custom config data file. The error: # Item item.ac_crystal_low.name=Low-purity Imag Crystal item.ac_crystal_normal.name=Mid-purity Imag Crystal item.ac_crystal_pure.name=High-purity Imag Crystal item.ac_constraint_ingot.name=Constraint Metal Ingot item.ac_constraint_plate.name=Constraint Metal Plate item.ac_imag_silicon_ingot.name=Imag Silicon Ingot item.ac_wafer.name=Imag Silicon Wafer item.ac_imag_silicon_piece.name=Imag Silicon Piece item.ac_reso_crystal.name=Resonant Crystal item.ac_brain_component.name=Brainwave Analyzer item.ac_info_component.name=Information Processor item.ac_reinforced_iron_plate.name=Reinforced Iron Plate item.ac_resonance_component.name=Resonator item.ac_energy_convert_component.name=Energy Converter item.ac_calc_chip.name=Calculation Chip item.ac_data_chip.name=Data Chip item.ac_matter_unit.name=Matter Unit item.ac_matter_unit_phase_liquid.name=Imag Phase Liquid Unit item.ac_matter_unit_none.name=Empty Unit item.ac_matrix_core.name=Matrix Core item.ac_mat_core_0.name=Basic Matrix Core item.ac_mat_core_1.name=Improved Matrix Core item.ac_mat_core_2.name=Advanced Matrix Core item.ac_energy_unit.name=Energy Unit item.ac_windgen_fan.name=Wind Generator Fan item.ac_coin.name=Coin item.ac_silbarn.name=Silicon Barn item.ac_needle.name=Needle item.ac_mag_hook.name=Magnetic Hook item.ac_terminal_installer.name=Data Terminal item.ac_apps.name=App Installer item.ac_developer_portable.name=Portable Developer item.ac_magnetic_coil.name=High Voltage Magnetic Coil item.ac_magnetic_coil.desc=Overcharges the developer<br>In order to rewrite personal reality item.ac_induction_factor.name=Ability Induction Factor item.ac_tutorial.name=MisakaCloud Terminal # Block tile.ac_constraint_metal.name=Constraint Metal Ore tile.ac_crystal_ore.name=Imag Crystal Ore tile.ac_imagsil_ore.name=Imag Silicon Ore tile.ac_reso_ore.name=Resonant Crystal Ore tile.ac_machine_frame.name=Machine Frame tile.ac_imag_phase.name=Imag Phase Liquid tile.ac_imag_fusor.name=Imag Fusor tile.ac_matrix.name=Wireless Imag Matrix tile.ac_node_basic.name=Basic Wireless Imag Node tile.ac_node_standard.name=Improved Wireless Imag Node tile.ac_node_advanced.name=Advanced Wireless Imag Node tile.ac_metal_former.name=Metal Former tile.ac_solar_gen.name=Solar Generator tile.ac_cat_engine.name=Toast and Cat tile.ac_phase_gen.name=Phase Generator tile.ac_windgen_base.name=Wind Generator Pillar Base tile.ac_windgen_pillar.name=Wind Generator Pillar tile.ac_windgen_main.name=Wind Generator tile.ac_eu_output.name=Energy Bridge (IC2 EU Out) tile.ac_eu_input.name=Energy Bridge (IC2 EU In) tile.ac_rf_output.name=Energy Bridge (CoFH RF Out) tile.ac_rf_input.name=Energy Bridge (CoFH RF In) tile.ac_dev_normal.name=Normal Ability Developer tile.ac_dev_advanced.name=Advanced Ability Developer tile.ac_ability_interferer.name=Ability Interferer # Data Terminal ac.terminal.notinstalled=You have not yet installed the Data Terminal. ac.terminal.alrdy_installed=You have already installed the Data Terminal. ac.terminal.key_hint=Successfully installed the data terminal. Use the %s key to open/close the terminal UI. ac.gui.terminal.installing= Installing... ac.gui.terminal.appcount=%d Apps ac.terminal.app_alrdy_installed=You have already installed app %s. ac.terminal.app_installed=You have successfully installed app %s. # Apps ac.app.skill_tree.name=Skill Tree ac.app.knowledge_record.name=Life Record ac.app.settings.name=Settings ac.app.media_player.name=Media Player ac.app.tutorial.name=MisakaCloud ac.app.about.name=About ac.app.freq_transmitter.name=Frequency Transmitter ac.app.freq_transmitter.s0_0=Please right-click a wireless matrix or node to start establish link from. ac.app.freq_transmitter.s1_0=Press ENTER to confirm ac.app.freq_transmitter.s1_1=Authorizing... ac.app.freq_transmitter.s2_0=Right click any wireless node nearby to establish link. Click any other blocks to quit. ac.app.freq_transmitter.s3_0=Right click any wireless receiver or generator nearby to esablish link. Click any other blocks to quit. ac.app.freq_transmitter.st=Action Timeout. ac.app.freq_transmitter.e0=The wireless matrix is not initialized. ac.app.freq_transmitter.e1=Authorization failed. ac.app.freq_transmitter.e2=Link failed. Perhaps the matrix has reached its capacity or the signal is out of range. ac.app.freq_transmitter.e3=Link failed. Perhaps the node has reached its capacity or the signal is out of range. ac.app.freq_transmitter.e4=Action aborted. ac.app.freq_transmitter.e5=Transmitting... ac.app.freq_transmitter.e6=Link successful. ## Settings App ac.settings.cat.generic=Generic ac.settings.prop.attackPlayer=Enable PvP ac.settings.prop.destroyBlocks=Destroy blocks ac.settings.prop.headsOrTails=Play Heads or Tails ac.settings.prop.useMouseWheel=Mouse wheel adjust tp distance #Use mouse wheel to adjust Penetrate Teleport distance ac.settings.cat.keys=Keys ac.settings.prop.ability_activation=Activate Ability ac.settings.prop.edit_preset=Edit Preset ac.settings.prop.switch_preset=Switch Preset ac.settings.prop.open_data_terminal=Open Data Terminal ac.settings.prop.ability_0=Ability #1 ac.settings.prop.ability_1=Ability #2 ac.settings.prop.ability_2=Ability #3 ac.settings.prop.ability_3=Ability #4 ac.settings.prop.debug_console=Debug Console ac.settings.cat.misc=Misc ac.settings.prop.edit_ui=Customize UI ## Media App ## -> ac.app.media.* ac.media.acquired=You have installed media %s ac.media.haveone=You have already installed media %s ac.media.notinstalled=You have not yet installed the Media Player app. ### Medias ac.media.only_my_railgun.name=only my railgun ac.media.only_my_railgun.desc=Toaru Kagaku no Railgun OP1 ac.media.level5_judgelight.name=LEVEL5-judgelight- ac.media.level5_judgelight.desc=Toaru Kagaku no Railgun OP2 ac.media.sisters_noise.name=sister's noise ac.media.sisters_noise.desc=Toaru Kagaku no Railgun S OP1 # Ability Generic ac.ability.level0=Level 0 ac.ability.level1=Level 1 ac.ability.level2=Level 2 ac.ability.level3=Level 3 ac.ability.level4=Level 4 ac.ability.level5=Level 5 death.attack.ac_skill=%1$s was killed by %2$s using %3$s ac.activate_key.deactivate.desc=Deactivate Ability ac.activate_key.endspecial.desc=End Special Skill Mode ac.activate_key.endskill.desc=Abort Skill ac.gui.preset_edit.name=Preset Edit ac.gui.preset_edit.tag=Preset # ac.gui.preset_edit.skill_remove=Remove Current ac.gui.preset_edit.skill_select=Select Skill ## Generic Skills ac.ability.generic.brain_course.name=Brain Course ac.ability.generic.brain_course_advanced.name=Brain Course Advanced ac.ability.generic.mind_course.name=Mind Course ac.ability.generic.brain_course.desc=Undergo training for your brain. Increases Max CP by 1000. ac.ability.generic.brain_course_advanced.desc=Develop the thinking ability of your brain deeply. Increases Max CP by 1000 and Max Overload by 100. ac.ability.generic.mind_course.desc=Learn how to relax your brain better. Speed up CP recovery by 20%%. ## Electromaster ac.ability.electromaster.name=Electromaster ### EM Skills ac.ability.electromaster.arc_gen.name=Arc Generation ac.ability.electromaster.mag_manip.name=Magnet Manipulation ac.ability.electromaster.mine_detect.name=Mine Detection ac.ability.electromaster.railgun.name=Railgun ac.ability.electromaster.mag_movement.name=Magnet Movement ac.ability.electromaster.iron_sand.name=Iron Sand Control ac.ability.electromaster.iron_sand.sword.name=Iron Sand Sword ac.ability.electromaster.iron_sand.whip.name=Iron Sand Whip ac.ability.electromaster.iron_sand.storm.name=Iron Sand Storm ac.ability.electromaster.iron_sand.cone.name=Iron Sand Cone ac.ability.electromaster.charging.name=Current Charging ac.ability.electromaster.body_intensify.name=Body Intensify ac.ability.electromaster.thunder_clap.name=Thunderclap ac.ability.electromaster.thunder_bolt.name=Thunder Bolt ac.ability.electromaster.arc_gen.desc=Arouse a weak electrical arc, which causes slight damage on the area it hits. If it directly hits a flammable block, it will have a chance to ignite it. ac.ability.electromaster.mag_manip.desc=Manipulate and move magnetizable things with the magnetic force, even throw them out to damage enemies. ac.ability.electromaster.mine_detect.desc=Close your eyes and feel the flow of magnetism, allowing you to see a hint of precious mineral resources around you. ac.ability.electromaster.railgun.desc=Shoot the coin out at a high speed with electromagnetic induction. Cause destructive damage where it impacts. ac.ability.electromaster.mag_movement.desc=Generate a strong magenetic field and pull yourself towards some magnetic target. Extremely useful when moving or escaping. ac.ability.electromaster.iron_sand.desc=Separate and manipulate the iron in sand to create a changeable and dangerous attack effect. ac.ability.electromaster.charging.desc=Generate electric current to charge the thing in your hand or electric blocks in the world. ac.ability.electromaster.body_intensify.desc=Fine-tune your bioelectricity to improve your physical ability for a short duration. ac.ability.electromaster.thunder_clap.desc=Manipulate the magnetic field in the atmosphere to create thunderclouds, and guide the electricity down to cause a devastating strike of lightning. ac.ability.electromaster.thunder_bolt.desc=Compresses an enormous amount of electricity into a powerful bolt, bursting out and damaging anything in it's area. ## Teleporter ac.ability.teleporter.name=Teleporter ### TP Skills ac.ability.teleporter.threatening_teleport.name=Threatening Teleport ac.ability.teleporter.dim_folding_theorem.name=Dimension Folding Theorem ac.ability.teleporter.penetrate_teleport.name=Penetrate Teleport ac.ability.teleporter.mark_teleport.name=Mark Teleport ac.ability.teleporter.flesh_ripping.name=Flesh Ripping ac.ability.teleporter.location_teleport.name=Location Teleport ac.ability.teleporter.shift_tp.name=Shift Teleport ac.ability.teleporter.space_fluct.name=Space Fluctuation ac.ability.teleporter.flashing.name=Flashing ac.ability.teleporter.threatening_teleport.desc=Teleport items to somewhere around you. Sometimes just a small fragment is able to kill an enemy. ac.ability.teleporter.dim_folding_theorem.desc=Boost your damage against enemies by generating a tiny space folding phonemonon. ac.ability.teleporter.penetrate_teleport.desc=Derive the thickness of an obstacle in front of you, and teleport straight through it. ac.ability.teleporter.mark_teleport.desc=Marks where you are looking at as the destination, and teleports you there. ac.ability.teleporter.flesh_ripping.desc=Rip apart your enemy’s inside and inflict gory damage. The over-bloody effect may make you feel uncomfortable. ac.ability.teleporter.location_teleport.desc=Memorize your current location and teleport back from anywhere far away afterwards. ac.ability.teleporter.shift_tp.desc=Teleport a block about the means of the coordinate plane. The space-folding phonemonon will hurt any entity on the teleportation path. ac.ability.teleporter.space_fluct.desc=Strengthen your space-folding ability to cause more dangerous critical damage. ac.ability.teleporter.flashing.desc=Use multiple teleportations in a short time to maneuver through the air. ac.ability.teleporter.crithit=%fx critical hit! ac.gui.loctele.err_exp=Exp too low, can't cross dimension ac.gui.loctele.err_cp=CP inadequate, can't teleport ## Meltdowner ac.ability.meltdowner.name=Meltdowner ### MD Skills ac.ability.meltdowner.electron_bomb.name=Electron Bomb ac.ability.meltdowner.rad_intensify.name=β Radiation Intensify ac.ability.meltdowner.ray_barrage.name=Ray Barrage ac.ability.meltdowner.scatter_bomb.name=Scattering Bomb ac.ability.meltdowner.meltdowner.name=Meltdowner ac.ability.meltdowner.light_shield.name=Light Shield ac.ability.meltdowner.jet_engine.name=Jet Engine ac.ability.meltdowner.mine_ray_basic.name=Basic Mining Ray ac.ability.meltdowner.mine_ray_expert.name=Expert Mining Ray ac.ability.meltdowner.mine_ray_luck.name=Luck Mining Ray ac.ability.meltdowner.electron_missile.name=Electron Missile ac.ability.meltdowner.electron_bomb.desc=Pull together a small amount of electrons to generate a threatening beam. ac.ability.meltdowner.rad_intensify.desc=Because of the high-intensity radiation, the target hit by beam is doubly vulnerable to attacks for a few seconds. ac.ability.meltdowner.ray_barrage.desc=Shoot your high-energy ray at a Silicon Barn to scatter it into a ray barrage that destroys everything in front of you. ac.ability.meltdowner.scatter_bomb.desc=Manipulate more than one electronics group to attack. As a result, you can't control the impact point accurately. ac.ability.meltdowner.meltdowner.desc=Extreme high-energy electron beam that melts down walls and metals. ac.ability.meltdowner.light_shield.desc=Forms electrons into a shield. High-speed moving electrons will destroy anything that attack you, and damage anything touch you closely. ac.ability.meltdowner.jet_engine.desc=Use the propulsive force of electrons launch yourself into the air. Will generate a light-shield to protect yourself in the flight. ac.ability.meltdowner.mine_ray_basic.desc=After a long time of practice, you can make your electron beam suitable for harvesting minerals without destroying them. ac.ability.meltdowner.mine_ray_expert.desc=With understanding of how to control the intensity of electrons better, you can now harvest mineral resources more efficiently. ac.ability.meltdowner.mine_ray_luck.desc=After a long time of practice, you can almost harvest the useful resources in the ore perfectly. ac.ability.meltdowner.electron_missile.desc=Hold together a HUGE amount of electrons in a cloud and use some of it to attack each time. ## Vector Manipulation ac.ability.vecmanip.name=Vector Manip ### VM skills ac.ability.vecmanip.dir_shock.name=Directed Shock ac.ability.vecmanip.ground_shock.name=Groundshock ac.ability.vecmanip.vec_accel.name=Vector Acceleration ac.ability.vecmanip.vec_deviation.name=Vector Deviation ac.ability.vecmanip.dir_blast.name=Directed Blastwave ac.ability.vecmanip.storm_wing.name=Storm Wing ac.ability.vecmanip.blood_retro.name=Blood Retrograde ac.ability.vecmanip.vec_reflection.name=Vector Reflection ac.ability.vecmanip.plasma_cannon.name=Plasma Cannon ac.ability.vecmanip.dir_shock.desc=Seize the counterforce when punched into object and redirect it onto the object itself, making the punch more powerful. ac.ability.vecmanip.ground_shock.desc=Apply a powerful shock on the ground and direct it forward, which breaks the ground and launches enemies into the air. ac.ability.vecmanip.vec_accel.desc=Boost jumping force for an instant to accelerate yourself. ac.ability.vecmanip.vec_deviation.desc=Cancel the velocity of projectiles flying towards you, and cancels a portion of combat damage. ac.ability.vecmanip.dir_blast.desc=Triple the force of punching into the object, making it extremely destructive. Will break blocks on area it hits. ac.ability.vecmanip.storm_wing.desc=Manipulate the velocity of air to form four micro-whirlwinds at your back, and fly in high speed using forces they generate. Will break blocks nearby if inexperienced. ac.ability.vecmanip.blood_retro.desc=Stir the blood flow of organic enemies, making their vessel burst and die in extreme pain. ac.ability.vecmanip.vec_reflection.desc=Reflects the dangerous incoming attacks towards your line of sight, and make your opponent bear it. ac.ability.vecmanip.plasma_cannon.desc=Manipulate a large area of air flow with extreme precision to form a plasma body. Throw it out to cause a disastrous explosion. # Command ac.command.invalid=§cInvalid input, please try again. ac.command.successful=§2Command sucessfully performed. ac.command.notlearned=§6The player has not learned any ability yet. ac.command.knowledge.usage=/knowledge <command>|<help> [parameters...] ac.command.knowledge.help=/knowledge help: Display the help message. ac.command.knowledge.stat=/knowledge stat: Show statistics info of player ac.knowledge. ac.command.knowledge.clear=/knowledge clear: Clear all knowledge info and start over again. ac.command.knowledge.getall=/knowledge getall: Learn all knowledges right now. ac.command.knowledge.list=/knowledge list: List all available knowledges. ac.command.knowledge.learn=/knowledge learn [knowledge_name]: Learn some ac.knowledge. ac.command.knowledge.unlearn=/knowledge unlearn [knowledge_name]: Unlearn some ac.knowledge. ac.command.knowledge.stat2=Knowledge learned: %s ac.command.knowledge.stat3=Knowledge discovered: %s ac.command.knowledge.notfound=Knowledge with name %s doesn't exist. ac.command.knowledge.all=All knowledges: ac.command.knowledge.discover=/knowledge discover [knowledge_name]: Discover a specific ac.knowledge. ac.command.aim.usage=/aim <command>|<help> [parameters...] ac.command.aim.help=/aim help: Display the help message. ac.command.aim.cat=/aim cat [catName]: Change the specified player's categories or display the current category. ac.command.aim.catlist=/aim catlist: List all available categories' names. ac.command.aim.learn=/aim learn <id>|<skillName>: Learn the specified skill, regardless of its learning condition requirements. ac.command.aim.unlearn=/aim unlearn <id>|<skillName>: Unlearn the specified skill. ac.command.aim.learn_all=/aim learn_all: Learn all the skills. ac.command.aim.reset=/aim reset: Clear your ability information. ac.command.aim.learned=/aim learned: Display all currently learned skills. ac.command.aim.skills=/aim skills: Display all skills in player's current category. ac.command.aim.fullcp=/aim fullcp: Restore full cp of the player. ac.command.aim.level=/aim level: Set the player's ability level. ac.command.aim.exp=/aim exp <id>|<skillName> [exp]: Set or view the skill's experience level. ac.command.aim.cd_clear=/aim cd_clear: Clear all skill cooldown. ac.command.aim.nocat=Specified category not found. Use /aim catlist to list all categories. ac.command.aim.cats=Currently available categories: ac.command.aim.curcat=Player current category: %s ac.command.aim.nonecat=No ability ac.command.aim.noskill=No such skill was found. Use /aim skills to list all skills in current category. ac.command.aim.learned.format=Learned skills: %s ac.command.aim.curexp=Skill %s's current exp: %.0f%%. ac.command.aim.notactive=The /aim command is currently inactive. Use /aim cheats_on or /aim cheats_off to change the active state. ac.command.aim.warning=§cWARNING: Using /aim command will break the game balance and impact your experience about the mod, PROCEED WITH CAUTION! ac.command.aim.outofrange=§cInput out of range: §fMust be a value between %s and %s. ac.command.aim.invalidnum=§cInvalid number: %s. ac.command.aim.maxout=Set current level's upgrade progress to 100%%. ac.command.aim.nocomm=No such command was found. Use /aim help to list all commands available. ac.command.aim.nonecathint=You haven't learned any ability! ac.command.aimp.usage=/aimp <player name> <command>|<help> [parameters...] ac.command.aimp.help=/aimp help: Display the help message. ac.command.aimp.cat=/aimp <player name> cat [catName]: Change the specified player's categories or display the current category. ac.command.aimp.catlist=/aimp catlist: List all available categories' names. ac.command.aimp.learn=/aimp <player name> learn <id>|<skillName>: Learn the specified skill, regardless of its learning condition requirements. ac.command.aimp.unlearn=/aimp <player name> unlearn <id>|<skillName>: Unlearn the specified skill. ac.command.aimp.learn_all=/aimp <player name> learn_all: Learn all the skills. ac.command.aimp.reset=/aimp <player name> reset: Clear your ability information. ac.command.aimp.learned=/aimp <player name> learned: Display all currently learned skills. ac.command.aimp.skills=/aimp <player name> skills: Display all skills in player's current category. ac.command.aimp.fullcp=/aimp <player name> fullcp: Restore full cp of the player. ac.command.aimp.level=/aimp <player name> level: Set the player's ability level. ac.command.aimp.exp=/aimp <player name> exp <id>|<skillName> [exp]: Set or view the skill's experience level. ac.command.aimp.cd_clear=/aimp <player name> cd_clear: Clear all skill cooldown. ac.command.aimp.nocat=Specified category not found. Use /aimp catlist to list all categories. ac.command.aimp.cats=Currently available categories: ac.command.aimp.curcat=Player current category: %s ac.command.aimp.nonecat=No ability ac.command.aimp.noskill=No such skill was found. Use /aimp <player name> skills to list all skills in current category. ac.command.aimp.learned.format=Learned skills: %s ac.command.aimp.curexp=Skill %s's current exp: %.0f%%. ac.command.aimp.notactive=The /aimp command is currently inactive. Use /aimp cheats_on or /aimp cheats_off to change the active state. ac.command.aimp.warning=§cWARNING: Using /aimp command will break the game balance and impact your experience about the mod, PROCEED WITH CAUTION! ac.command.aimp.outofrange=§cInput out of range: §fMust be a value between %s and %s. ac.command.aimp.maxout=/aimp <player name> maxout:Set current level's upgrade progress to 100%%. ac.command.aimp.nocomm=No such command was found. Use /aimp help to list all commands available. ac.command.aimp.nonecathint=You haven't learned any ability! # Advancement advancements.general.root=Academy Craft advancements.general.root.desc=The beginning of everything advancements.general.open_misaka_cloud=First Contact advancements.general.open_misaka_cloud.desc=Open Misaka Cloud advancements.general.getting_phase=Mysterious and powerful advancements.general.getting_phase.desc=Get a matter unit with Imag Phase Liquid advancements.general.phase_generator=New Energy advancements.general.phase_generator.desc=Craft a Phase Generator advancements.general.ac_node=No More Wires! advancements.general.ac_node.desc=Craft a Basic Wireless Imag Node advancements.general.ac_matrix=WIFI Available Here advancements.general.ac_matrix.desc=Craft a Matrix advancements.general.terminal_installed=Technology Changes Life advancements.general.terminal_installed.desc=Install Data Terminal advancements.general.getting_factor=Infinite Possibility advancements.general.getting_factor.desc=Get an Induction Factor advancements.general.ac_developer=There is a Limit for Human advancements.general.ac_developer.desc=Craft a Portable Ability Developer advancements.general.dev_category=Above Human advancements.general.dev_category.desc=Develop an Ability advancements.general.ac_level_3=On My Own advancements.general.ac_level_3.desc=Upgrade to level 3 advancements.general.ac_level_5=One Man Army advancements.general.ac_level_5.desc=Upgrade to level 5 advancements.general.convert_category=No More Randomized advancements.general.convert_category.desc=Transform your category advancements.general.ac_learning_skill=Practice Makes Perfect advancements.general.ac_learning_skill.desc=Learn any skill advancements.general.ac_milestone=Upgrade Module advancements.general.ac_milestone.desc=Reach first skill's milestone advancements.general.ac_exp_full=How many times did you do that? advancements.general.ac_exp_full.desc=Achieve full EXP for any skill advancements.general.ac_overload=There is Still a Limit for ESPers advancements.general.ac_overload.desc=Use your ability, until it overloads # UI Commons ac.gui.common.pg_wireless.not_connected=Not Connected ac.gui.common.sep.info=Information ac.gui.common.sep.wireless_info=Wireless Information ac.gui.common.sep.wireless_init=Wireless Network Initialization ac.gui.common.sep.wireless_noinit=Wireless Network Not Initialized ac.gui.common.sep.change_pass=Change Password ac.gui.common.hist.energy=ENERGY ac.gui.common.hist.buffer=BUFFER ac.gui.common.hist.liquid=LIQUID ac.gui.common.hist.capacity=CAPACITY ac.gui.common.prop.range=Trans. Range ac.gui.common.prop.owner=Owner ac.gui.common.prop.node_name=Node Name ac.gui.common.prop.password=Password ac.gui.common.prop.bandwidth=Bandwidth ac.gui.common.prop.ssid=SSID ac.gui.common.prop.gen_speed=Gen. speed ac.gui.common.prop.altitude=Altitude # Skill Tree ac.skill_tree.dev_successful=Development Successful. ac.skill_tree.dev_failed=Development Failed. ac.skill_tree.progress=Progress ac.skill_tree.noenergy=Not enough energy. ac.skill_tree.condition_fail=Development condition not satisfied. ac.skill_tree.learn_question=Learn? (Estm. Consumption:%s IF) ac.skill_tree.level_question=Continue? ac.skill_tree.req=Req. ac.skill_tree.skill_not_learned=Skill not learned. ac.skill_tree.skill_exp=Skill Experience: ac.skill_tree.uplevel=Upgrade to %s ac.skill_tree.anyskill=Any skill learned for level %d ac.skill_tree.level_fail=You must reach level %d first. ac.skill_tree.type_portable=Portable Developer ac.skill_tree.type_normal=Normal Developer ac.skill_tree.type_advanced=Advanced Developer ac.skill_tree.console.init=Welcome to Academy OS, Ver 1.0.1\nCopyright (c) Academy Tech. All rights reserved. \nUser %s detected, System booting...... ac.skill_tree.console.invalid_cat=\nFATAL: User's ability category is invalid, booting aborted.\n ac.skill_tree.console.learn_hint=Type `learn` to acquire new category.\n ac.skill_tree.console.override=\nWARNING: System override! External injection detected.....\n\nABILITY RESET: Use `reset` command to reset your category. \nAbility level must be at least 3, and an Induction Factor must be in inventory.\n ac.skill_tree.console.boot_failed=Boot Failed.\n ac.skill_tree.console.invalid_command=Invalid command.\n ac.skill_tree.console.progress=Progress: %s%% ac.skill_tree.console.reset_begin=Starting resetting ability category... ac.skill_tree.console.reset_succ=Personal Reality reset sequence successful.\n ac.skill_tree.console.reset_fail=Personal Reality reset sequence failed.\n ac.skill_tree.console.reset_fail_dev=Can't reset ability -- Advance Developer must be used.\n ac.skill_tree.console.reset_fail_other=Can't reset ability -- either level is lower than 3 or induction factor not detected.\n ac.skill_tree.console.dev_begin=Start stimulation......\n ac.skill_tree.console.dev_succ=Development successful.\n ac.skill_tree.console.dev_fail=Development failed.\n # Phase Generator # Imag Fusor # Metal Former ac.gui.metal_former.mode.etch=Etching ac.gui.metal_former.mode.plate=Plate Crushing ac.gui.metal_former.mode.incise=Incising ac.gui.metal_former.mode.refine=Refining # Ability interference block ac.gui.ability_interf.switch=Switch ac.ability_interf.cantuse=You can't use this interference block. # UI Editing ac.gui.uiedit.elements=Elements ac.gui.uiedit.elm.cpbar=CP Indicator ac.gui.uiedit.elm.keyhint=Control Hint ac.gui.uiedit.elm.notification=Notification ac.gui.uiedit.elm.media=Media Player # Cat Engine ac.cat_engine.unlink=Unlinked from the node meow~ ac.cat_engine.notfound=Didn't found any node nearby meow~ ac.cat_engine.linked=Linked to the node named %s meow~ # Tutorials ac.gui.crafttype.shaped=Shaped Crafting ac.gui.crafttype.shapeless=Shapeless Crafting ac.tutorial.crafting=Crafting: %s ac.tutorial.misaka=Misaka No.%d ac.tutorial.update=Cloud Terminal updated # Heads Or Tails ac.headsOrTails.0=The result is TAILS! ac.headsOrTails.1=The result is HEADS! # Converter Block ac.converter.desc_template=Converts %s to %s ac.skill_tree.dev_developing=Developing... # About App ac.about.donators_info=In no particular order
411
0.932664
1
0.932664
game-dev
MEDIA
0.923052
game-dev
0.852146
1
0.852146
ss14Starlight/space-station-14
1,037
Content.Shared/Radiation/Systems/RadiationPulseSystem.cs
using Content.Shared.Radiation.Components; using Robust.Shared.Spawners; using Robust.Shared.Timing; namespace Content.Shared.Radiation.Systems; public sealed class RadiationPulseSystem : EntitySystem { [Dependency] private readonly IGameTiming _timing = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<RadiationPulseComponent, ComponentStartup>(OnStartup); } private void OnStartup(EntityUid uid, RadiationPulseComponent component, ComponentStartup args) { component.StartTime = _timing.RealTime; // try to get despawn time or keep default duration time if (TryComp<TimedDespawnComponent>(uid, out var despawn)) { component.VisualDuration = despawn.Lifetime; } // try to get radiation range or keep default visual range if (TryComp<RadiationSourceComponent>(uid, out var radSource)) { component.VisualRange = radSource.Intensity / radSource.Slope; } } }
411
0.896596
1
0.896596
game-dev
MEDIA
0.532521
game-dev
0.75326
1
0.75326
Edgarins29/Doom3
264,012
neo/d3xp/Player.cpp
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "sys/platform.h" #include "idlib/LangDict.h" #include "framework/async/NetworkSystem.h" #include "framework/DeclEntityDef.h" #include "renderer/RenderSystem.h" #include "gamesys/SysCvar.h" #include "script/Script_Thread.h" #include "ai/AI.h" #include "WorldSpawn.h" #include "Player.h" #include "Camera.h" #include "Fx.h" #include "Misc.h" const int ASYNC_PLAYER_INV_AMMO_BITS = idMath::BitsForInteger( 999 ); // 9 bits to cover the range [0, 999] const int ASYNC_PLAYER_INV_CLIP_BITS = -7; // -7 bits to cover the range [-1, 60] /* =============================================================================== Player control of the Doom Marine. This object handles all player movement and world interaction. =============================================================================== */ // distance between ladder rungs (actually is half that distance, but this sounds better) const int LADDER_RUNG_DISTANCE = 32; // amount of health per dose from the health station const int HEALTH_PER_DOSE = 10; // time before a weapon dropped to the floor disappears const int WEAPON_DROP_TIME = 20 * 1000; // time before a next or prev weapon switch happens const int WEAPON_SWITCH_DELAY = 150; // how many units to raise spectator above default view height so it's in the head of someone const int SPECTATE_RAISE = 25; const int HEALTHPULSE_TIME = 333; // minimum speed to bob and play run/walk animations at const float MIN_BOB_SPEED = 5.0f; const idEventDef EV_Player_GetButtons( "getButtons", NULL, 'd' ); const idEventDef EV_Player_GetMove( "getMove", NULL, 'v' ); const idEventDef EV_Player_GetViewAngles( "getViewAngles", NULL, 'v' ); const idEventDef EV_Player_StopFxFov( "stopFxFov" ); const idEventDef EV_Player_EnableWeapon( "enableWeapon" ); const idEventDef EV_Player_DisableWeapon( "disableWeapon" ); const idEventDef EV_Player_GetCurrentWeapon( "getCurrentWeapon", NULL, 's' ); const idEventDef EV_Player_GetPreviousWeapon( "getPreviousWeapon", NULL, 's' ); const idEventDef EV_Player_SelectWeapon( "selectWeapon", "s" ); const idEventDef EV_Player_GetWeaponEntity( "getWeaponEntity", NULL, 'e' ); const idEventDef EV_Player_OpenPDA( "openPDA" ); const idEventDef EV_Player_InPDA( "inPDA", NULL, 'd' ); const idEventDef EV_Player_ExitTeleporter( "exitTeleporter" ); const idEventDef EV_Player_StopAudioLog( "stopAudioLog" ); const idEventDef EV_Player_HideTip( "hideTip" ); const idEventDef EV_Player_LevelTrigger( "levelTrigger" ); const idEventDef EV_SpectatorTouch( "spectatorTouch", "et" ); #ifdef _D3XP const idEventDef EV_Player_GiveInventoryItem( "giveInventoryItem", "s" ); const idEventDef EV_Player_RemoveInventoryItem( "removeInventoryItem", "s" ); const idEventDef EV_Player_GetIdealWeapon( "getIdealWeapon", NULL, 's' ); const idEventDef EV_Player_SetPowerupTime( "setPowerupTime", "dd" ); const idEventDef EV_Player_IsPowerupActive( "isPowerupActive", "d", 'd' ); const idEventDef EV_Player_WeaponAvailable( "weaponAvailable", "s", 'd'); const idEventDef EV_Player_StartWarp( "startWarp" ); const idEventDef EV_Player_StopHelltime( "stopHelltime", "d" ); const idEventDef EV_Player_ToggleBloom( "toggleBloom", "d" ); const idEventDef EV_Player_SetBloomParms( "setBloomParms", "ff" ); #endif CLASS_DECLARATION( idActor, idPlayer ) EVENT( EV_Player_GetButtons, idPlayer::Event_GetButtons ) EVENT( EV_Player_GetMove, idPlayer::Event_GetMove ) EVENT( EV_Player_GetViewAngles, idPlayer::Event_GetViewAngles ) EVENT( EV_Player_StopFxFov, idPlayer::Event_StopFxFov ) EVENT( EV_Player_EnableWeapon, idPlayer::Event_EnableWeapon ) EVENT( EV_Player_DisableWeapon, idPlayer::Event_DisableWeapon ) EVENT( EV_Player_GetCurrentWeapon, idPlayer::Event_GetCurrentWeapon ) EVENT( EV_Player_GetPreviousWeapon, idPlayer::Event_GetPreviousWeapon ) EVENT( EV_Player_SelectWeapon, idPlayer::Event_SelectWeapon ) EVENT( EV_Player_GetWeaponEntity, idPlayer::Event_GetWeaponEntity ) EVENT( EV_Player_OpenPDA, idPlayer::Event_OpenPDA ) EVENT( EV_Player_InPDA, idPlayer::Event_InPDA ) EVENT( EV_Player_ExitTeleporter, idPlayer::Event_ExitTeleporter ) EVENT( EV_Player_StopAudioLog, idPlayer::Event_StopAudioLog ) EVENT( EV_Player_HideTip, idPlayer::Event_HideTip ) EVENT( EV_Player_LevelTrigger, idPlayer::Event_LevelTrigger ) EVENT( EV_Gibbed, idPlayer::Event_Gibbed ) #ifdef _D3XP EVENT( EV_Player_GiveInventoryItem, idPlayer::Event_GiveInventoryItem ) EVENT( EV_Player_RemoveInventoryItem, idPlayer::Event_RemoveInventoryItem ) EVENT( EV_Player_GetIdealWeapon, idPlayer::Event_GetIdealWeapon ) EVENT( EV_Player_WeaponAvailable, idPlayer::Event_WeaponAvailable ) EVENT( EV_Player_SetPowerupTime, idPlayer::Event_SetPowerupTime ) EVENT( EV_Player_IsPowerupActive, idPlayer::Event_IsPowerupActive ) EVENT( EV_Player_StartWarp, idPlayer::Event_StartWarp ) EVENT( EV_Player_StopHelltime, idPlayer::Event_StopHelltime ) EVENT( EV_Player_ToggleBloom, idPlayer::Event_ToggleBloom ) EVENT( EV_Player_SetBloomParms, idPlayer::Event_SetBloomParms ) #endif END_CLASS const int MAX_RESPAWN_TIME = 10000; const int RAGDOLL_DEATH_TIME = 3000; const int MAX_PDAS = 64; const int MAX_PDA_ITEMS = 128; const int STEPUP_TIME = 200; const int MAX_INVENTORY_ITEMS = 20; #ifdef _D3XP idVec3 idPlayer::colorBarTable[ 8 ] = { #else idVec3 idPlayer::colorBarTable[ 5 ] = { #endif idVec3( 0.25f, 0.25f, 0.25f ), idVec3( 1.00f, 0.00f, 0.00f ), idVec3( 0.00f, 0.80f, 0.10f ), idVec3( 0.20f, 0.50f, 0.80f ), idVec3( 1.00f, 0.80f, 0.10f ) #ifdef _D3XP ,idVec3( 0.425f, 0.484f, 0.445f ), idVec3( 0.39f, 0.199f, 0.3f ), idVec3( 0.484f, 0.312f, 0.074f) #endif }; /* ============== idInventory::Clear ============== */ void idInventory::Clear( void ) { maxHealth = 0; weapons = 0; powerups = 0; armor = 0; maxarmor = 0; deplete_armor = 0; deplete_rate = 0.0f; deplete_ammount = 0; nextArmorDepleteTime = 0; memset( ammo, 0, sizeof( ammo ) ); ClearPowerUps(); // set to -1 so that the gun knows to have a full clip the first time we get it and at the start of the level memset( clip, -1, sizeof( clip ) ); items.DeleteContents( true ); memset(pdasViewed, 0, 4 * sizeof( pdasViewed[0] ) ); pdas.Clear(); videos.Clear(); emails.Clear(); selVideo = 0; selEMail = 0; selPDA = 0; selAudio = 0; pdaOpened = false; turkeyScore = false; levelTriggers.Clear(); nextItemPickup = 0; nextItemNum = 1; onePickupTime = 0; pickupItemNames.Clear(); objectiveNames.Clear(); ammoPredictTime = 0; lastGiveTime = 0; ammoPulse = false; weaponPulse = false; armorPulse = false; } /* ============== idInventory::GivePowerUp ============== */ void idInventory::GivePowerUp( idPlayer *player, int powerup, int msec ) { if ( !msec ) { // get the duration from the .def files const idDeclEntityDef *def = NULL; switch ( powerup ) { case BERSERK: def = gameLocal.FindEntityDef( "powerup_berserk", false ); break; case INVISIBILITY: def = gameLocal.FindEntityDef( "powerup_invisibility", false ); break; case MEGAHEALTH: def = gameLocal.FindEntityDef( "powerup_megahealth", false ); break; case ADRENALINE: def = gameLocal.FindEntityDef( "powerup_adrenaline", false ); break; #ifdef _D3XP case INVULNERABILITY: def = gameLocal.FindEntityDef( "powerup_invulnerability", false ); break; /*case HASTE: def = gameLocal.FindEntityDef( "powerup_haste", false ); break;*/ #endif } assert( def ); msec = def->dict.GetInt( "time" ) * 1000; } powerups |= 1 << powerup; powerupEndTime[ powerup ] = gameLocal.time + msec; } /* ============== idInventory::ClearPowerUps ============== */ void idInventory::ClearPowerUps( void ) { int i; for ( i = 0; i < MAX_POWERUPS; i++ ) { powerupEndTime[ i ] = 0; } powerups = 0; } /* ============== idInventory::GetPersistantData ============== */ void idInventory::GetPersistantData( idDict &dict ) { int i; int num; idDict *item; idStr key; const idKeyValue *kv; const char *name; // armor dict.SetInt( "armor", armor ); // don't bother with powerups, maxhealth, maxarmor, or the clip // ammo for( i = 0; i < AMMO_NUMTYPES; i++ ) { name = idWeapon::GetAmmoNameForNum( ( ammo_t )i ); if ( name ) { dict.SetInt( name, ammo[ i ] ); } } #ifdef _D3XP //Save the clip data for( i = 0; i < MAX_WEAPONS; i++ ) { dict.SetInt( va("clip%i", i), clip[ i ] ); } #endif // items num = 0; for( i = 0; i < items.Num(); i++ ) { item = items[ i ]; // copy all keys with "inv_" kv = item->MatchPrefix( "inv_" ); if ( kv ) { while( kv ) { sprintf( key, "item_%i %s", num, kv->GetKey().c_str() ); dict.Set( key, kv->GetValue() ); kv = item->MatchPrefix( "inv_", kv ); } num++; } } dict.SetInt( "items", num ); // pdas viewed for ( i = 0; i < 4; i++ ) { dict.SetInt( va("pdasViewed_%i", i), pdasViewed[i] ); } dict.SetInt( "selPDA", selPDA ); dict.SetInt( "selVideo", selVideo ); dict.SetInt( "selEmail", selEMail ); dict.SetInt( "selAudio", selAudio ); dict.SetInt( "pdaOpened", pdaOpened ); dict.SetInt( "turkeyScore", turkeyScore ); // pdas for ( i = 0; i < pdas.Num(); i++ ) { sprintf( key, "pda_%i", i ); dict.Set( key, pdas[ i ] ); } dict.SetInt( "pdas", pdas.Num() ); // video cds for ( i = 0; i < videos.Num(); i++ ) { sprintf( key, "video_%i", i ); dict.Set( key, videos[ i ].c_str() ); } dict.SetInt( "videos", videos.Num() ); // emails for ( i = 0; i < emails.Num(); i++ ) { sprintf( key, "email_%i", i ); dict.Set( key, emails[ i ].c_str() ); } dict.SetInt( "emails", emails.Num() ); // weapons dict.SetInt( "weapon_bits", weapons ); dict.SetInt( "levelTriggers", levelTriggers.Num() ); for ( i = 0; i < levelTriggers.Num(); i++ ) { sprintf( key, "levelTrigger_Level_%i", i ); dict.Set( key, levelTriggers[i].levelName ); sprintf( key, "levelTrigger_Trigger_%i", i ); dict.Set( key, levelTriggers[i].triggerName ); } } /* ============== idInventory::RestoreInventory ============== */ void idInventory::RestoreInventory( idPlayer *owner, const idDict &dict ) { int i; int num; idDict *item; idStr key; idStr itemname; const idKeyValue *kv; const char *name; Clear(); // health/armor maxHealth = dict.GetInt( "maxhealth", "100" ); armor = dict.GetInt( "armor", "50" ); maxarmor = dict.GetInt( "maxarmor", "100" ); deplete_armor = dict.GetInt( "deplete_armor", "0" ); deplete_rate = dict.GetFloat( "deplete_rate", "2.0" ); deplete_ammount = dict.GetInt( "deplete_ammount", "1" ); // the clip and powerups aren't restored // ammo for( i = 0; i < AMMO_NUMTYPES; i++ ) { name = idWeapon::GetAmmoNameForNum( ( ammo_t )i ); if ( name ) { ammo[ i ] = dict.GetInt( name ); } } #ifdef _D3XP //Restore the clip data for( i = 0; i < MAX_WEAPONS; i++ ) { clip[i] = dict.GetInt(va("clip%i", i), "-1"); } #endif // items num = dict.GetInt( "items" ); items.SetNum( num ); for( i = 0; i < num; i++ ) { item = new idDict(); items[ i ] = item; sprintf( itemname, "item_%i ", i ); kv = dict.MatchPrefix( itemname ); while( kv ) { key = kv->GetKey(); key.Strip( itemname ); item->Set( key, kv->GetValue() ); kv = dict.MatchPrefix( itemname, kv ); } } // pdas viewed for ( i = 0; i < 4; i++ ) { pdasViewed[i] = dict.GetInt(va("pdasViewed_%i", i)); } selPDA = dict.GetInt( "selPDA" ); selEMail = dict.GetInt( "selEmail" ); selVideo = dict.GetInt( "selVideo" ); selAudio = dict.GetInt( "selAudio" ); pdaOpened = dict.GetBool( "pdaOpened" ); turkeyScore = dict.GetBool( "turkeyScore" ); // pdas num = dict.GetInt( "pdas" ); pdas.SetNum( num ); for ( i = 0; i < num; i++ ) { sprintf( itemname, "pda_%i", i ); pdas[i] = dict.GetString( itemname, "default" ); } // videos num = dict.GetInt( "videos" ); videos.SetNum( num ); for ( i = 0; i < num; i++ ) { sprintf( itemname, "video_%i", i ); videos[i] = dict.GetString( itemname, "default" ); } // emails num = dict.GetInt( "emails" ); emails.SetNum( num ); for ( i = 0; i < num; i++ ) { sprintf( itemname, "email_%i", i ); emails[i] = dict.GetString( itemname, "default" ); } // weapons are stored as a number for persistant data, but as strings in the entityDef weapons = dict.GetInt( "weapon_bits", "0" ); #ifdef ID_DEMO_BUILD Give( owner, dict, "weapon", dict.GetString( "weapon" ), NULL, false ); #else if ( g_skill.GetInteger() >= 3 ) { Give( owner, dict, "weapon", dict.GetString( "weapon_nightmare" ), NULL, false ); } else { Give( owner, dict, "weapon", dict.GetString( "weapon" ), NULL, false ); } #endif num = dict.GetInt( "levelTriggers" ); for ( i = 0; i < num; i++ ) { sprintf( itemname, "levelTrigger_Level_%i", i ); idLevelTriggerInfo lti; lti.levelName = dict.GetString( itemname ); sprintf( itemname, "levelTrigger_Trigger_%i", i ); lti.triggerName = dict.GetString( itemname ); levelTriggers.Append( lti ); } } /* ============== idInventory::Save ============== */ void idInventory::Save( idSaveGame *savefile ) const { int i; savefile->WriteInt( maxHealth ); savefile->WriteInt( weapons ); savefile->WriteInt( powerups ); savefile->WriteInt( armor ); savefile->WriteInt( maxarmor ); savefile->WriteInt( ammoPredictTime ); savefile->WriteInt( deplete_armor ); savefile->WriteFloat( deplete_rate ); savefile->WriteInt( deplete_ammount ); savefile->WriteInt( nextArmorDepleteTime ); for( i = 0; i < AMMO_NUMTYPES; i++ ) { savefile->WriteInt( ammo[ i ] ); } for( i = 0; i < MAX_WEAPONS; i++ ) { savefile->WriteInt( clip[ i ] ); } for( i = 0; i < MAX_POWERUPS; i++ ) { savefile->WriteInt( powerupEndTime[ i ] ); } savefile->WriteInt( items.Num() ); for( i = 0; i < items.Num(); i++ ) { savefile->WriteDict( items[ i ] ); } savefile->WriteInt( pdasViewed[0] ); savefile->WriteInt( pdasViewed[1] ); savefile->WriteInt( pdasViewed[2] ); savefile->WriteInt( pdasViewed[3] ); savefile->WriteInt( selPDA ); savefile->WriteInt( selVideo ); savefile->WriteInt( selEMail ); savefile->WriteInt( selAudio ); savefile->WriteBool( pdaOpened ); savefile->WriteBool( turkeyScore ); savefile->WriteInt( pdas.Num() ); for( i = 0; i < pdas.Num(); i++ ) { savefile->WriteString( pdas[ i ] ); } savefile->WriteInt( pdaSecurity.Num() ); for( i=0; i < pdaSecurity.Num(); i++ ) { savefile->WriteString( pdaSecurity[ i ] ); } savefile->WriteInt( videos.Num() ); for( i = 0; i < videos.Num(); i++ ) { savefile->WriteString( videos[ i ] ); } savefile->WriteInt( emails.Num() ); for ( i = 0; i < emails.Num(); i++ ) { savefile->WriteString( emails[ i ] ); } savefile->WriteInt( nextItemPickup ); savefile->WriteInt( nextItemNum ); savefile->WriteInt( onePickupTime ); savefile->WriteInt( pickupItemNames.Num() ); for( i = 0; i < pickupItemNames.Num(); i++ ) { savefile->WriteString( pickupItemNames[i].icon ); savefile->WriteString( pickupItemNames[i].name ); } savefile->WriteInt( objectiveNames.Num() ); for( i = 0; i < objectiveNames.Num(); i++ ) { savefile->WriteString( objectiveNames[i].screenshot ); savefile->WriteString( objectiveNames[i].text ); savefile->WriteString( objectiveNames[i].title ); } savefile->WriteInt( levelTriggers.Num() ); for ( i = 0; i < levelTriggers.Num(); i++ ) { savefile->WriteString( levelTriggers[i].levelName ); savefile->WriteString( levelTriggers[i].triggerName ); } savefile->WriteBool( ammoPulse ); savefile->WriteBool( weaponPulse ); savefile->WriteBool( armorPulse ); savefile->WriteInt( lastGiveTime ); #ifdef _D3XP for(i = 0; i < AMMO_NUMTYPES; i++) { savefile->WriteInt(rechargeAmmo[i].ammo); savefile->WriteInt(rechargeAmmo[i].rechargeTime); savefile->WriteString(rechargeAmmo[i].ammoName); } #endif } /* ============== idInventory::Restore ============== */ void idInventory::Restore( idRestoreGame *savefile ) { int i, num; savefile->ReadInt( maxHealth ); savefile->ReadInt( weapons ); savefile->ReadInt( powerups ); savefile->ReadInt( armor ); savefile->ReadInt( maxarmor ); savefile->ReadInt( ammoPredictTime ); savefile->ReadInt( deplete_armor ); savefile->ReadFloat( deplete_rate ); savefile->ReadInt( deplete_ammount ); savefile->ReadInt( nextArmorDepleteTime ); for( i = 0; i < AMMO_NUMTYPES; i++ ) { savefile->ReadInt( ammo[ i ] ); } for( i = 0; i < MAX_WEAPONS; i++ ) { savefile->ReadInt( clip[ i ] ); } for( i = 0; i < MAX_POWERUPS; i++ ) { savefile->ReadInt( powerupEndTime[ i ] ); } savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { idDict *itemdict = new idDict; savefile->ReadDict( itemdict ); items.Append( itemdict ); } // pdas savefile->ReadInt( pdasViewed[0] ); savefile->ReadInt( pdasViewed[1] ); savefile->ReadInt( pdasViewed[2] ); savefile->ReadInt( pdasViewed[3] ); savefile->ReadInt( selPDA ); savefile->ReadInt( selVideo ); savefile->ReadInt( selEMail ); savefile->ReadInt( selAudio ); savefile->ReadBool( pdaOpened ); savefile->ReadBool( turkeyScore ); savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { idStr strPda; savefile->ReadString( strPda ); pdas.Append( strPda ); } // pda security clearances savefile->ReadInt( num ); for ( i = 0; i < num; i++ ) { idStr invName; savefile->ReadString( invName ); pdaSecurity.Append( invName ); } // videos savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { idStr strVideo; savefile->ReadString( strVideo ); videos.Append( strVideo ); } // email savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { idStr strEmail; savefile->ReadString( strEmail ); emails.Append( strEmail ); } savefile->ReadInt( nextItemPickup ); savefile->ReadInt( nextItemNum ); savefile->ReadInt( onePickupTime ); savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { idItemInfo info; savefile->ReadString( info.icon ); savefile->ReadString( info.name ); pickupItemNames.Append( info ); } savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { idObjectiveInfo obj; savefile->ReadString( obj.screenshot ); savefile->ReadString( obj.text ); savefile->ReadString( obj.title ); objectiveNames.Append( obj ); } savefile->ReadInt( num ); for ( i = 0; i < num; i++ ) { idLevelTriggerInfo lti; savefile->ReadString( lti.levelName ); savefile->ReadString( lti.triggerName ); levelTriggers.Append( lti ); } savefile->ReadBool( ammoPulse ); savefile->ReadBool( weaponPulse ); savefile->ReadBool( armorPulse ); savefile->ReadInt( lastGiveTime ); #ifdef _D3XP for(i = 0; i < AMMO_NUMTYPES; i++) { savefile->ReadInt(rechargeAmmo[i].ammo); savefile->ReadInt(rechargeAmmo[i].rechargeTime); idStr name; savefile->ReadString(name); strcpy(rechargeAmmo[i].ammoName, name); } #endif } /* ============== idInventory::AmmoIndexForAmmoClass ============== */ ammo_t idInventory::AmmoIndexForAmmoClass( const char *ammo_classname ) const { return idWeapon::GetAmmoNumForName( ammo_classname ); } /* ============== idInventory::AmmoIndexForAmmoClass ============== */ int idInventory::MaxAmmoForAmmoClass( idPlayer *owner, const char *ammo_classname ) const { return owner->spawnArgs.GetInt( va( "max_%s", ammo_classname ), "0" ); } /* ============== idInventory::AmmoPickupNameForIndex ============== */ const char *idInventory::AmmoPickupNameForIndex( ammo_t ammonum ) const { return idWeapon::GetAmmoPickupNameForNum( ammonum ); } /* ============== idInventory::WeaponIndexForAmmoClass mapping could be prepared in the constructor ============== */ int idInventory::WeaponIndexForAmmoClass( const idDict & spawnArgs, const char *ammo_classname ) const { int i; const char *weapon_classname; for( i = 0; i < MAX_WEAPONS; i++ ) { weapon_classname = spawnArgs.GetString( va( "def_weapon%d", i ) ); if ( !weapon_classname ) { continue; } const idDeclEntityDef *decl = gameLocal.FindEntityDef( weapon_classname, false ); if ( !decl ) { continue; } if ( !idStr::Icmp( ammo_classname, decl->dict.GetString( "ammoType" ) ) ) { return i; } } return -1; } /* ============== idInventory::AmmoIndexForWeaponClass ============== */ ammo_t idInventory::AmmoIndexForWeaponClass( const char *weapon_classname, int *ammoRequired ) { const idDeclEntityDef *decl = gameLocal.FindEntityDef( weapon_classname, false ); if ( !decl ) { gameLocal.Error( "Unknown weapon in decl '%s'", weapon_classname ); } if ( ammoRequired ) { *ammoRequired = decl->dict.GetInt( "ammoRequired" ); } ammo_t ammo_i = AmmoIndexForAmmoClass( decl->dict.GetString( "ammoType" ) ); return ammo_i; } /* ============== idInventory::AddPickupName ============== */ void idInventory::AddPickupName( const char *name, const char *icon, idPlayer* owner ) { //_D3XP int num; num = pickupItemNames.Num(); if ( ( num == 0 ) || ( pickupItemNames[ num - 1 ].name.Icmp( name ) != 0 ) ) { idItemInfo &info = pickupItemNames.Alloc(); if ( idStr::Cmpn( name, STRTABLE_ID, STRTABLE_ID_LENGTH ) == 0 ) { info.name = common->GetLanguageDict()->GetString( name ); } else { info.name = name; } info.icon = icon; #ifdef _D3XP if ( gameLocal.isServer ) { idBitMsg msg; byte msgBuf[MAX_EVENT_PARAM_SIZE]; msg.Init( msgBuf, sizeof( msgBuf ) ); msg.WriteString( name, MAX_EVENT_PARAM_SIZE ); owner->ServerSendEvent( idPlayer::EVENT_PICKUPNAME, &msg, false, -1 ); } } #endif } /* ============== idInventory::Give ============== */ bool idInventory::Give( idPlayer *owner, const idDict &spawnArgs, const char *statname, const char *value, int *idealWeapon, bool updateHud ) { int i; const char *pos; const char *end; int len; idStr weaponString; int max; const idDeclEntityDef *weaponDecl; bool tookWeapon; int amount; idItemInfo info; const char *name; #ifdef _D3XP if ( !idStr::Icmp( statname, "ammo_bloodstone" ) ) { i = AmmoIndexForAmmoClass( statname ); max = MaxAmmoForAmmoClass( owner, statname ); if(max <= 0) { //No Max ammo[ i ] += atoi( value ); } else { //Already at or above the max so don't allow the give if(ammo[ i ] >= max) { ammo[ i ] = max; return false; } //We were below the max so accept the give but cap it at the max ammo[ i ] += atoi( value ); if(ammo[ i ] > max) { ammo[ i ] = max; } } } else #endif if ( !idStr::Icmpn( statname, "ammo_", 5 ) ) { i = AmmoIndexForAmmoClass( statname ); max = MaxAmmoForAmmoClass( owner, statname ); if ( ammo[ i ] >= max ) { return false; } amount = atoi( value ); if ( amount ) { ammo[ i ] += amount; if ( ( max > 0 ) && ( ammo[ i ] > max ) ) { ammo[ i ] = max; } ammoPulse = true; name = AmmoPickupNameForIndex( i ); if ( idStr::Length( name ) ) { AddPickupName( name, "", owner ); //_D3XP } } } else if ( !idStr::Icmp( statname, "armor" ) ) { if ( armor >= maxarmor ) { return false; // can't hold any more, so leave the item } amount = atoi( value ); if ( amount ) { armor += amount; if ( armor > maxarmor ) { armor = maxarmor; } nextArmorDepleteTime = 0; armorPulse = true; } } else if ( idStr::FindText( statname, "inclip_" ) == 0 ) { #ifdef _D3XP idStr temp = statname; i = atoi(temp.Mid(7, 2)); #else i = WeaponIndexForAmmoClass( spawnArgs, statname + 7 ); #endif if ( i != -1 ) { // set, don't add. not going over the clip size limit. #ifndef _D3XP clip[ i ] = atoi( value ); #endif } #ifdef _D3XP } else if ( !idStr::Icmp( statname, "invulnerability" ) ) { owner->GivePowerUp( INVULNERABILITY, SEC2MS( atof( value ) ) ); } else if ( !idStr::Icmp( statname, "helltime" ) ) { owner->GivePowerUp( HELLTIME, SEC2MS( atof( value ) ) ); } else if ( !idStr::Icmp( statname, "envirosuit" ) ) { owner->GivePowerUp( ENVIROSUIT, SEC2MS( atof( value ) ) ); owner->GivePowerUp( ENVIROTIME, SEC2MS( atof( value ) ) ); } else if ( !idStr::Icmp( statname, "berserk" ) ) { owner->GivePowerUp( BERSERK, SEC2MS( atof( value ) ) ); //} else if ( !idStr::Icmp( statname, "haste" ) ) { // owner->GivePowerUp( HASTE, SEC2MS( atof( value ) ) ); #else } else if ( !idStr::Icmp( statname, "berserk" ) ) { GivePowerUp( owner, BERSERK, SEC2MS( atof( value ) ) ); #endif } else if ( !idStr::Icmp( statname, "mega" ) ) { GivePowerUp( owner, MEGAHEALTH, SEC2MS( atof( value ) ) ); } else if ( !idStr::Icmp( statname, "weapon" ) ) { tookWeapon = false; for( pos = value; pos != NULL; pos = end ) { end = strchr( pos, ',' ); if ( end ) { len = end - pos; end++; } else { len = strlen( pos ); } idStr weaponName( pos, 0, len ); // find the number of the matching weapon name for( i = 0; i < MAX_WEAPONS; i++ ) { if ( weaponName == spawnArgs.GetString( va( "def_weapon%d", i ) ) ) { break; } } if ( i >= MAX_WEAPONS ) { #ifdef _D3XP gameLocal.Warning( "Unknown weapon '%s'", weaponName.c_str() ); continue; #else gameLocal.Error( "Unknown weapon '%s'", weaponName.c_str() ); #endif } // cache the media for this weapon weaponDecl = gameLocal.FindEntityDef( weaponName, false ); // don't pickup "no ammo" weapon types twice // not for D3 SP .. there is only one case in the game where you can get a no ammo // weapon when you might already have it, in that case it is more conistent to pick it up if ( gameLocal.isMultiplayer && weaponDecl && ( weapons & ( 1 << i ) ) && !weaponDecl->dict.GetInt( "ammoRequired" ) ) { continue; } if ( !gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) || ( weaponName == "weapon_fists" ) || ( weaponName == "weapon_soulcube" ) ) { if ( ( weapons & ( 1 << i ) ) == 0 || gameLocal.isMultiplayer ) { if ( owner->GetUserInfo()->GetBool( "ui_autoSwitch" ) && idealWeapon && i != owner->weapon_bloodstone_active1 && i != owner->weapon_bloodstone_active2 && i != owner->weapon_bloodstone_active3) { assert( !gameLocal.isClient ); *idealWeapon = i; } if ( owner->hud && updateHud && lastGiveTime + 1000 < gameLocal.time ) { owner->hud->SetStateInt( "newWeapon", i ); owner->hud->HandleNamedEvent( "newWeapon" ); lastGiveTime = gameLocal.time; } weaponPulse = true; weapons |= ( 1 << i ); tookWeapon = true; } } } return tookWeapon; } else if ( !idStr::Icmp( statname, "item" ) || !idStr::Icmp( statname, "icon" ) || !idStr::Icmp( statname, "name" ) ) { // ignore these as they're handled elsewhere return false; } else { // unknown item gameLocal.Warning( "Unknown stat '%s' added to player's inventory", statname ); return false; } return true; } /* =============== idInventoy::Drop =============== */ void idInventory::Drop( const idDict &spawnArgs, const char *weapon_classname, int weapon_index ) { // remove the weapon bit // also remove the ammo associated with the weapon as we pushed it in the item assert( weapon_index != -1 || weapon_classname ); if ( weapon_index == -1 ) { for( weapon_index = 0; weapon_index < MAX_WEAPONS; weapon_index++ ) { if ( !idStr::Icmp( weapon_classname, spawnArgs.GetString( va( "def_weapon%d", weapon_index ) ) ) ) { break; } } if ( weapon_index >= MAX_WEAPONS ) { gameLocal.Error( "Unknown weapon '%s'", weapon_classname ); } } else if ( !weapon_classname ) { weapon_classname = spawnArgs.GetString( va( "def_weapon%d", weapon_index ) ); } weapons &= ( 0xffffffff ^ ( 1 << weapon_index ) ); ammo_t ammo_i = AmmoIndexForWeaponClass( weapon_classname, NULL ); if ( ammo_i ) { clip[ weapon_index ] = -1; ammo[ ammo_i ] = 0; } } /* =============== idInventory::HasAmmo =============== */ int idInventory::HasAmmo( ammo_t type, int amount ) { if ( ( type == 0 ) || !amount ) { // always allow weapons that don't use ammo to fire return -1; } // check if we have infinite ammo if ( ammo[ type ] < 0 ) { return -1; } // return how many shots we can fire return ammo[ type ] / amount; } /* =============== idInventory::HasAmmo =============== */ int idInventory::HasAmmo( const char *weapon_classname, bool includeClip, idPlayer* owner ) { //_D3XP int ammoRequired; ammo_t ammo_i = AmmoIndexForWeaponClass( weapon_classname, &ammoRequired ); #ifdef _D3XP int ammoCount = HasAmmo( ammo_i, ammoRequired ); if(includeClip && owner) { ammoCount += clip[owner->SlotForWeapon(weapon_classname)]; } return ammoCount; #else return HasAmmo( ammo_i, ammoRequired ); #endif } #ifdef _D3XP /* =============== idInventory::HasEmptyClipCannotRefill =============== */ bool idInventory::HasEmptyClipCannotRefill(const char *weapon_classname, idPlayer* owner) { int clipSize = clip[owner->SlotForWeapon(weapon_classname)]; if(clipSize) { return false; } const idDeclEntityDef *decl = gameLocal.FindEntityDef( weapon_classname, false ); if ( !decl ) { gameLocal.Error( "Unknown weapon in decl '%s'", weapon_classname ); } int minclip = decl->dict.GetInt("minclipsize"); if(!minclip) { return false; } ammo_t ammo_i = AmmoIndexForAmmoClass( decl->dict.GetString( "ammoType" ) ); int ammoRequired = decl->dict.GetInt( "ammoRequired" ); int ammoCount = HasAmmo( ammo_i, ammoRequired ); if(ammoCount < minclip) { return true; } return false; } #endif /* =============== idInventory::UseAmmo =============== */ bool idInventory::UseAmmo( ammo_t type, int amount ) { if ( !HasAmmo( type, amount ) ) { return false; } // take an ammo away if not infinite if ( ammo[ type ] >= 0 ) { ammo[ type ] -= amount; ammoPredictTime = gameLocal.time; // mp client: we predict this. mark time so we're not confused by snapshots } return true; } /* =============== idInventory::UpdateArmor =============== */ void idInventory::UpdateArmor( void ) { if ( deplete_armor != 0.0f && deplete_armor < armor ) { if ( !nextArmorDepleteTime ) { nextArmorDepleteTime = gameLocal.time + deplete_rate * 1000; } else if ( gameLocal.time > nextArmorDepleteTime ) { armor -= deplete_ammount; if ( armor < deplete_armor ) { armor = deplete_armor; } nextArmorDepleteTime = gameLocal.time + deplete_rate * 1000; } } } #ifdef _D3XP /* =============== idInventory::InitRechargeAmmo =============== * Loads any recharge ammo definitions from the ammo_types entity definitions. */ void idInventory::InitRechargeAmmo(idPlayer *owner) { memset (rechargeAmmo, 0, sizeof(rechargeAmmo)); const idKeyValue *kv = owner->spawnArgs.MatchPrefix( "ammorecharge_" ); while( kv ) { idStr key = kv->GetKey(); idStr ammoname = key.Right(key.Length()- strlen("ammorecharge_")); int ammoType = AmmoIndexForAmmoClass(ammoname); rechargeAmmo[ammoType].ammo = (atof(kv->GetValue().c_str())*1000); strcpy(rechargeAmmo[ammoType].ammoName, ammoname); kv = owner->spawnArgs.MatchPrefix( "ammorecharge_", kv ); } } /* =============== idInventory::RechargeAmmo =============== * Called once per frame to update any ammo amount for ammo types that recharge. */ void idInventory::RechargeAmmo(idPlayer *owner) { for(int i = 0; i < AMMO_NUMTYPES; i++) { if(rechargeAmmo[i].ammo > 0) { if(!rechargeAmmo[i].rechargeTime) { //Initialize the recharge timer. rechargeAmmo[i].rechargeTime = gameLocal.time; } int elapsed = gameLocal.time - rechargeAmmo[i].rechargeTime; if(elapsed >= rechargeAmmo[i].ammo) { int intervals = (gameLocal.time - rechargeAmmo[i].rechargeTime)/rechargeAmmo[i].ammo; ammo[i] += intervals; int max = MaxAmmoForAmmoClass(owner, rechargeAmmo[i].ammoName); if(max > 0) { if(ammo[i] > max) { ammo[i] = max; } } rechargeAmmo[i].rechargeTime += intervals*rechargeAmmo[i].ammo; } } } } /* =============== idInventory::CanGive =============== */ bool idInventory::CanGive( idPlayer *owner, const idDict &spawnArgs, const char *statname, const char *value, int *idealWeapon ) { if ( !idStr::Icmp( statname, "ammo_bloodstone" ) ) { int max = MaxAmmoForAmmoClass(owner, statname); int i = AmmoIndexForAmmoClass(statname); if(max <= 0) { //No Max return true; } else { //Already at or above the max so don't allow the give if(ammo[ i ] >= max) { ammo[ i ] = max; return false; } return true; } } else if ( !idStr::Icmp( statname, "item" ) || !idStr::Icmp( statname, "icon" ) || !idStr::Icmp( statname, "name" ) ) { // ignore these as they're handled elsewhere //These items should not be considered as succesful gives because it messes up the max ammo items return false; } return true; } #endif /* ============== idPlayer::idPlayer ============== */ idPlayer::idPlayer() { memset( &usercmd, 0, sizeof( usercmd ) ); noclip = false; godmode = false; spawnAnglesSet = false; spawnAngles = ang_zero; viewAngles = ang_zero; cmdAngles = ang_zero; oldButtons = 0; buttonMask = 0; oldFlags = 0; lastHitTime = 0; lastSndHitTime = 0; lastSavingThrowTime = 0; weapon = NULL; hud = NULL; objectiveSystem = NULL; objectiveSystemOpen = false; #ifdef _D3XP mountedObject = NULL; enviroSuitLight = NULL; #endif heartRate = BASE_HEARTRATE; heartInfo.Init( 0, 0, 0, 0 ); lastHeartAdjust = 0; lastHeartBeat = 0; lastDmgTime = 0; deathClearContentsTime = 0; lastArmorPulse = -10000; stamina = 0.0f; healthPool = 0.0f; nextHealthPulse = 0; healthPulse = false; nextHealthTake = 0; healthTake = false; scoreBoardOpen = false; forceScoreBoard = false; forceRespawn = false; spectating = false; spectator = 0; colorBar = vec3_zero; colorBarIndex = 0; forcedReady = false; wantSpectate = false; #ifdef CTF carryingFlag = false; #endif lastHitToggle = false; minRespawnTime = 0; maxRespawnTime = 0; firstPersonViewOrigin = vec3_zero; firstPersonViewAxis = mat3_identity; hipJoint = INVALID_JOINT; chestJoint = INVALID_JOINT; headJoint = INVALID_JOINT; bobFoot = 0; bobFrac = 0.0f; bobfracsin = 0.0f; bobCycle = 0; xyspeed = 0.0f; stepUpTime = 0; stepUpDelta = 0.0f; idealLegsYaw = 0.0f; legsYaw = 0.0f; legsForward = true; oldViewYaw = 0.0f; viewBobAngles = ang_zero; viewBob = vec3_zero; landChange = 0; landTime = 0; currentWeapon = -1; idealWeapon = -1; previousWeapon = -1; weaponSwitchTime = 0; weaponEnabled = true; weapon_soulcube = -1; weapon_pda = -1; weapon_fists = -1; #ifdef _D3XP weapon_bloodstone = -1; weapon_bloodstone_active1 = -1; weapon_bloodstone_active2 = -1; weapon_bloodstone_active3 = -1; harvest_lock = false; hudPowerup = -1; lastHudPowerup = -1; hudPowerupDuration = 0; #endif showWeaponViewModel = true; skin = NULL; powerUpSkin = NULL; baseSkinName = ""; numProjectilesFired = 0; numProjectileHits = 0; airless = false; airTics = 0; lastAirDamage = 0; gibDeath = false; gibsLaunched = false; gibsDir = vec3_zero; zoomFov.Init( 0, 0, 0, 0 ); centerView.Init( 0, 0, 0, 0 ); fxFov = false; influenceFov = 0; influenceActive = 0; influenceRadius = 0.0f; influenceEntity = NULL; influenceMaterial = NULL; influenceSkin = NULL; privateCameraView = NULL; memset( loggedViewAngles, 0, sizeof( loggedViewAngles ) ); memset( loggedAccel, 0, sizeof( loggedAccel ) ); currentLoggedAccel = 0; focusTime = 0; focusGUIent = NULL; focusUI = NULL; focusCharacter = NULL; talkCursor = 0; focusVehicle = NULL; cursor = NULL; oldMouseX = 0; oldMouseY = 0; pdaAudio = ""; pdaVideo = ""; pdaVideoWave = ""; lastDamageDef = 0; lastDamageDir = vec3_zero; lastDamageLocation = 0; smoothedFrame = 0; smoothedOriginUpdated = false; smoothedOrigin = vec3_zero; smoothedAngles = ang_zero; fl.networkSync = true; latchedTeam = -1; doingDeathSkin = false; weaponGone = false; useInitialSpawns = false; tourneyRank = 0; lastSpectateTeleport = 0; tourneyLine = 0; hiddenWeapon = false; tipUp = false; objectiveUp = false; teleportEntity = NULL; teleportKiller = -1; respawning = false; ready = false; leader = false; lastSpectateChange = 0; lastTeleFX = -9999; weaponCatchup = false; lastSnapshotSequence = 0; MPAim = -1; lastMPAim = -1; lastMPAimTime = 0; MPAimFadeTime = 0; MPAimHighlight = false; spawnedTime = 0; lastManOver = false; lastManPlayAgain = false; lastManPresent = false; isTelefragged = false; isLagged = false; isChatting = false; selfSmooth = false; } /* ============== idPlayer::LinkScriptVariables set up conditions for animation ============== */ void idPlayer::LinkScriptVariables( void ) { AI_FORWARD.LinkTo( scriptObject, "AI_FORWARD" ); AI_BACKWARD.LinkTo( scriptObject, "AI_BACKWARD" ); AI_STRAFE_LEFT.LinkTo( scriptObject, "AI_STRAFE_LEFT" ); AI_STRAFE_RIGHT.LinkTo( scriptObject, "AI_STRAFE_RIGHT" ); AI_ATTACK_HELD.LinkTo( scriptObject, "AI_ATTACK_HELD" ); AI_WEAPON_FIRED.LinkTo( scriptObject, "AI_WEAPON_FIRED" ); AI_JUMP.LinkTo( scriptObject, "AI_JUMP" ); AI_DEAD.LinkTo( scriptObject, "AI_DEAD" ); AI_CROUCH.LinkTo( scriptObject, "AI_CROUCH" ); AI_ONGROUND.LinkTo( scriptObject, "AI_ONGROUND" ); AI_ONLADDER.LinkTo( scriptObject, "AI_ONLADDER" ); AI_HARDLANDING.LinkTo( scriptObject, "AI_HARDLANDING" ); AI_SOFTLANDING.LinkTo( scriptObject, "AI_SOFTLANDING" ); AI_RUN.LinkTo( scriptObject, "AI_RUN" ); AI_PAIN.LinkTo( scriptObject, "AI_PAIN" ); AI_RELOAD.LinkTo( scriptObject, "AI_RELOAD" ); AI_TELEPORT.LinkTo( scriptObject, "AI_TELEPORT" ); AI_TURN_LEFT.LinkTo( scriptObject, "AI_TURN_LEFT" ); AI_TURN_RIGHT.LinkTo( scriptObject, "AI_TURN_RIGHT" ); } /* ============== idPlayer::SetupWeaponEntity ============== */ void idPlayer::SetupWeaponEntity( void ) { int w; const char *weap; if ( weapon.GetEntity() ) { // get rid of old weapon weapon.GetEntity()->Clear(); currentWeapon = -1; } else if ( !gameLocal.isClient ) { weapon = static_cast<idWeapon *>( gameLocal.SpawnEntityType( idWeapon::Type, NULL ) ); weapon.GetEntity()->SetOwner( this ); currentWeapon = -1; } for( w = 0; w < MAX_WEAPONS; w++ ) { weap = spawnArgs.GetString( va( "def_weapon%d", w ) ); if ( weap && *weap ) { idWeapon::CacheWeapon( weap ); } } } /* ============== idPlayer::Init ============== */ void idPlayer::Init( void ) { const char *value; const idKeyValue *kv; noclip = false; godmode = false; oldButtons = 0; oldFlags = 0; currentWeapon = -1; idealWeapon = -1; previousWeapon = -1; weaponSwitchTime = 0; weaponEnabled = true; weapon_soulcube = SlotForWeapon( "weapon_soulcube" ); weapon_pda = SlotForWeapon( "weapon_pda" ); weapon_fists = SlotForWeapon( "weapon_fists" ); #ifdef _D3XP weapon_bloodstone = SlotForWeapon( "weapon_bloodstone_passive" ); weapon_bloodstone_active1 = SlotForWeapon( "weapon_bloodstone_active1" ); weapon_bloodstone_active2 = SlotForWeapon( "weapon_bloodstone_active2" ); weapon_bloodstone_active3 = SlotForWeapon( "weapon_bloodstone_active3" ); harvest_lock = false; #endif showWeaponViewModel = GetUserInfo()->GetBool( "ui_showGun" ); lastDmgTime = 0; lastArmorPulse = -10000; lastHeartAdjust = 0; lastHeartBeat = 0; heartInfo.Init( 0, 0, 0, 0 ); bobCycle = 0; bobFrac = 0.0f; landChange = 0; landTime = 0; zoomFov.Init( 0, 0, 0, 0 ); centerView.Init( 0, 0, 0, 0 ); fxFov = false; influenceFov = 0; influenceActive = 0; influenceRadius = 0.0f; influenceEntity = NULL; influenceMaterial = NULL; influenceSkin = NULL; #ifdef _D3XP mountedObject = NULL; if( enviroSuitLight.IsValid() ) { enviroSuitLight.GetEntity()->PostEventMS( &EV_Remove, 0 ); } enviroSuitLight = NULL; healthRecharge = false; lastHealthRechargeTime = 0; rechargeSpeed = 500; new_g_damageScale = 1.f; bloomEnabled = false; bloomSpeed = 1.f; bloomIntensity = -0.01f; inventory.InitRechargeAmmo(this); hudPowerup = -1; lastHudPowerup = -1; hudPowerupDuration = 0; #endif currentLoggedAccel = 0; focusTime = 0; focusGUIent = NULL; focusUI = NULL; focusCharacter = NULL; talkCursor = 0; focusVehicle = NULL; // remove any damage effects playerView.ClearEffects(); // damage values fl.takedamage = true; ClearPain(); // restore persistent data RestorePersistantInfo(); bobCycle = 0; stamina = 0.0f; healthPool = 0.0f; nextHealthPulse = 0; healthPulse = false; nextHealthTake = 0; healthTake = false; SetupWeaponEntity(); currentWeapon = -1; previousWeapon = -1; heartRate = BASE_HEARTRATE; AdjustHeartRate( BASE_HEARTRATE, 0.0f, 0.0f, true ); idealLegsYaw = 0.0f; legsYaw = 0.0f; legsForward = true; oldViewYaw = 0.0f; // set the pm_ cvars if ( !gameLocal.isMultiplayer || gameLocal.isServer ) { kv = spawnArgs.MatchPrefix( "pm_", NULL ); while( kv ) { cvarSystem->SetCVarString( kv->GetKey(), kv->GetValue() ); kv = spawnArgs.MatchPrefix( "pm_", kv ); } } // disable stamina on hell levels if ( gameLocal.world && gameLocal.world->spawnArgs.GetBool( "no_stamina" ) ) { pm_stamina.SetFloat( 0.0f ); } // stamina always initialized to maximum stamina = pm_stamina.GetFloat(); // air always initialized to maximum too airTics = pm_airTics.GetFloat(); airless = false; gibDeath = false; gibsLaunched = false; gibsDir.Zero(); // set the gravity physicsObj.SetGravity( gameLocal.GetGravity() ); // start out standing SetEyeHeight( pm_normalviewheight.GetFloat() ); stepUpTime = 0; stepUpDelta = 0.0f; viewBobAngles.Zero(); viewBob.Zero(); value = spawnArgs.GetString( "model" ); if ( value && ( *value != 0 ) ) { SetModel( value ); } if ( cursor ) { cursor->SetStateInt( "talkcursor", 0 ); cursor->SetStateString( "combatcursor", "1" ); cursor->SetStateString( "itemcursor", "0" ); cursor->SetStateString( "guicursor", "0" ); #ifdef _D3XP cursor->SetStateString( "grabbercursor", "0" ); #endif } if ( ( gameLocal.isMultiplayer || g_testDeath.GetBool() ) && skin ) { SetSkin( skin ); renderEntity.shaderParms[6] = 0.0f; } else if ( spawnArgs.GetString( "spawn_skin", NULL, &value ) ) { skin = declManager->FindSkin( value ); SetSkin( skin ); renderEntity.shaderParms[6] = 0.0f; } value = spawnArgs.GetString( "bone_hips", "" ); hipJoint = animator.GetJointHandle( value ); if ( hipJoint == INVALID_JOINT ) { gameLocal.Error( "Joint '%s' not found for 'bone_hips' on '%s'", value, name.c_str() ); } value = spawnArgs.GetString( "bone_chest", "" ); chestJoint = animator.GetJointHandle( value ); if ( chestJoint == INVALID_JOINT ) { gameLocal.Error( "Joint '%s' not found for 'bone_chest' on '%s'", value, name.c_str() ); } value = spawnArgs.GetString( "bone_head", "" ); headJoint = animator.GetJointHandle( value ); if ( headJoint == INVALID_JOINT ) { gameLocal.Error( "Joint '%s' not found for 'bone_head' on '%s'", value, name.c_str() ); } // initialize the script variables AI_FORWARD = false; AI_BACKWARD = false; AI_STRAFE_LEFT = false; AI_STRAFE_RIGHT = false; AI_ATTACK_HELD = false; AI_WEAPON_FIRED = false; AI_JUMP = false; AI_DEAD = false; AI_CROUCH = false; AI_ONGROUND = true; AI_ONLADDER = false; AI_HARDLANDING = false; AI_SOFTLANDING = false; AI_RUN = false; AI_PAIN = false; AI_RELOAD = false; AI_TELEPORT = false; AI_TURN_LEFT = false; AI_TURN_RIGHT = false; // reset the script object ConstructScriptObject(); // execute the script so the script object's constructor takes effect immediately scriptThread->Execute(); forceScoreBoard = false; forcedReady = false; privateCameraView = NULL; lastSpectateChange = 0; lastTeleFX = -9999; hiddenWeapon = false; tipUp = false; objectiveUp = false; teleportEntity = NULL; teleportKiller = -1; leader = false; SetPrivateCameraView( NULL ); lastSnapshotSequence = 0; MPAim = -1; lastMPAim = -1; lastMPAimTime = 0; MPAimFadeTime = 0; MPAimHighlight = false; if ( hud ) { hud->HandleNamedEvent( "aim_clear" ); } //isChatting = false; cvarSystem->SetCVarBool("ui_chat", false); } /* ============== idPlayer::Spawn Prepare any resources used by the player. ============== */ void idPlayer::Spawn( void ) { idStr temp; idBounds bounds; if ( entityNumber >= MAX_CLIENTS ) { gameLocal.Error( "entityNum > MAX_CLIENTS for player. Player may only be spawned with a client." ); } // allow thinking during cinematics cinematic = true; if ( gameLocal.isMultiplayer ) { // always start in spectating state waiting to be spawned in // do this before SetClipModel to get the right bounding box spectating = true; } // set our collision model physicsObj.SetSelf( this ); SetClipModel(); physicsObj.SetMass( spawnArgs.GetFloat( "mass", "100" ) ); physicsObj.SetContents( CONTENTS_BODY ); physicsObj.SetClipMask( MASK_PLAYERSOLID ); SetPhysics( &physicsObj ); InitAASLocation(); skin = renderEntity.customSkin; // only the local player needs guis if ( !gameLocal.isMultiplayer || entityNumber == gameLocal.localClientNum ) { // load HUD if ( gameLocal.isMultiplayer ) { hud = uiManager->FindGui( "guis/mphud.gui", true, false, true ); } else if ( spawnArgs.GetString( "hud", "", temp ) ) { hud = uiManager->FindGui( temp, true, false, true ); } if ( hud ) { hud->Activate( true, gameLocal.time ); #ifdef CTF if ( gameLocal.mpGame.IsGametypeFlagBased() ) { hud->SetStateInt( "red_team_score", gameLocal.mpGame.GetFlagPoints(0) ); hud->SetStateInt( "blue_team_score", gameLocal.mpGame.GetFlagPoints(1) ); } #endif } // load cursor if ( spawnArgs.GetString( "cursor", "", temp ) ) { cursor = uiManager->FindGui( temp, true, gameLocal.isMultiplayer, gameLocal.isMultiplayer ); } if ( cursor ) { cursor->Activate( true, gameLocal.time ); } objectiveSystem = uiManager->FindGui( "guis/pda.gui", true, false, true ); objectiveSystemOpen = false; } SetLastHitTime( 0 ); // load the armor sound feedback declManager->FindSound( "player_sounds_hitArmor" ); // set up conditions for animation LinkScriptVariables(); animator.RemoveOriginOffset( true ); // initialize user info related settings // on server, we wait for the userinfo broadcast, as this controls when the player is initially spawned in game if ( gameLocal.isClient || entityNumber == gameLocal.localClientNum ) { UserInfoChanged( false ); } // create combat collision hull for exact collision detection SetCombatModel(); // init the damage effects playerView.SetPlayerEntity( this ); // supress model in non-player views, but allow it in mirrors and remote views renderEntity.suppressSurfaceInViewID = entityNumber+1; // don't project shadow on self or weapon renderEntity.noSelfShadow = true; idAFAttachment *headEnt = head.GetEntity(); if ( headEnt ) { headEnt->GetRenderEntity()->suppressSurfaceInViewID = entityNumber+1; headEnt->GetRenderEntity()->noSelfShadow = true; } if ( gameLocal.isMultiplayer ) { Init(); Hide(); // properly hidden if starting as a spectator if ( !gameLocal.isClient ) { // set yourself ready to spawn. idMultiplayerGame will decide when/if appropriate and call SpawnFromSpawnSpot SetupWeaponEntity(); SpawnFromSpawnSpot(); forceRespawn = true; assert( spectating ); } } else { SetupWeaponEntity(); SpawnFromSpawnSpot(); } // trigger playtesting item gives, if we didn't get here from a previous level // the devmap key will be set on the first devmap, but cleared on any level // transitions if ( !gameLocal.isMultiplayer && gameLocal.serverInfo.FindKey( "devmap" ) ) { // fire a trigger with the name "devmap" idEntity *ent = gameLocal.FindEntity( "devmap" ); if ( ent ) { ent->ActivateTargets( this ); } } if ( hud ) { // We can spawn with a full soul cube, so we need to make sure the hud knows this #ifndef _D3XP if ( weapon_soulcube > 0 && ( inventory.weapons & ( 1 << weapon_soulcube ) ) ) { int max_souls = inventory.MaxAmmoForAmmoClass( this, "ammo_souls" ); if ( inventory.ammo[ idWeapon::GetAmmoNumForName( "ammo_souls" ) ] >= max_souls ) { hud->HandleNamedEvent( "soulCubeReady" ); } } #endif #ifdef _D3XP //We can spawn with a full bloodstone, so make sure the hud knows if ( weapon_bloodstone > 0 && ( inventory.weapons & ( 1 << weapon_bloodstone ) ) ) { //int max_blood = inventory.MaxAmmoForAmmoClass( this, "ammo_bloodstone" ); //if ( inventory.ammo[ idWeapon::GetAmmoNumForName( "ammo_bloodstone" ) ] >= max_blood ) { hud->HandleNamedEvent( "bloodstoneReady" ); //} } #endif hud->HandleNamedEvent( "itemPickup" ); } if ( GetPDA() ) { // Add any emails from the inventory for ( int i = 0; i < inventory.emails.Num(); i++ ) { GetPDA()->AddEmail( inventory.emails[i] ); } GetPDA()->SetSecurity( common->GetLanguageDict()->GetString( "#str_00066" ) ); } if ( gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) ) { hiddenWeapon = true; if ( weapon.GetEntity() ) { weapon.GetEntity()->LowerWeapon(); } idealWeapon = 0; } else { hiddenWeapon = false; } if ( hud ) { UpdateHudWeapon(); hud->StateChanged( gameLocal.time ); } tipUp = false; objectiveUp = false; if ( inventory.levelTriggers.Num() ) { PostEventMS( &EV_Player_LevelTrigger, 0 ); } inventory.pdaOpened = false; inventory.selPDA = 0; if ( !gameLocal.isMultiplayer ) { if ( g_skill.GetInteger() < 2 ) { if ( health < 25 ) { health = 25; } if ( g_useDynamicProtection.GetBool() ) { #ifdef _D3XP new_g_damageScale = 1.0f; #else g_damageScale.SetFloat( 1.0f ); #endif } } else { #ifdef _D3XP new_g_damageScale = 1.0f; #else g_damageScale.SetFloat( 1.0f ); #endif g_armorProtection.SetFloat( ( g_skill.GetInteger() < 2 ) ? 0.4f : 0.2f ); #ifndef ID_DEMO_BUILD if ( g_skill.GetInteger() == 3 ) { healthTake = true; nextHealthTake = gameLocal.time + g_healthTakeTime.GetInteger() * 1000; } #endif } } #ifdef _D3XP //Setup the weapon toggle lists const idKeyValue *kv; kv = spawnArgs.MatchPrefix( "weapontoggle", NULL ); while( kv ) { WeaponToggle_t newToggle; strcpy(newToggle.name, kv->GetKey().c_str()); idStr toggleData = kv->GetValue(); idLexer src; idToken token; src.LoadMemory(toggleData, toggleData.Length(), "toggleData"); while(1) { if(!src.ReadToken(&token)) { break; } int index = atoi(token.c_str()); newToggle.toggleList.Append(index); //Skip the , src.ReadToken(&token); } weaponToggles.Set(newToggle.name, newToggle); kv = spawnArgs.MatchPrefix( "weapontoggle", kv ); } #endif #ifdef _D3XP if(g_skill.GetInteger() >= 3) { if(!WeaponAvailable("weapon_bloodstone_passive")) { GiveInventoryItem("weapon_bloodstone_passive"); } if(!WeaponAvailable("weapon_bloodstone_active1")) { GiveInventoryItem("weapon_bloodstone_active1"); } if(!WeaponAvailable("weapon_bloodstone_active2")) { GiveInventoryItem("weapon_bloodstone_active2"); } if(!WeaponAvailable("weapon_bloodstone_active3")) { GiveInventoryItem("weapon_bloodstone_active3"); } } bloomEnabled = false; bloomSpeed = 1; bloomIntensity = -0.01f; #endif } /* ============== idPlayer::~idPlayer() Release any resources used by the player. ============== */ idPlayer::~idPlayer() { delete weapon.GetEntity(); weapon = NULL; #ifdef CTF if ( enviroSuitLight.IsValid() ) { enviroSuitLight.GetEntity()->ProcessEvent( &EV_Remove ); } // have to do this here, idMultiplayerGame::DisconnectClient() is too late if ( gameLocal.isMultiplayer && gameLocal.mpGame.IsGametypeFlagBased() ) { ReturnFlag(); } #endif } /* =========== idPlayer::Save =========== */ void idPlayer::Save( idSaveGame *savefile ) const { int i; savefile->WriteUsercmd( usercmd ); playerView.Save( savefile ); savefile->WriteBool( noclip ); savefile->WriteBool( godmode ); // don't save spawnAnglesSet, since we'll have to reset them after loading the savegame savefile->WriteAngles( spawnAngles ); savefile->WriteAngles( viewAngles ); savefile->WriteAngles( cmdAngles ); savefile->WriteInt( buttonMask ); savefile->WriteInt( oldButtons ); savefile->WriteInt( oldFlags ); savefile->WriteInt( lastHitTime ); savefile->WriteInt( lastSndHitTime ); savefile->WriteInt( lastSavingThrowTime ); // idBoolFields don't need to be saved, just re-linked in Restore inventory.Save( savefile ); weapon.Save( savefile ); savefile->WriteUserInterface( hud, false ); savefile->WriteUserInterface( objectiveSystem, false ); savefile->WriteBool( objectiveSystemOpen ); savefile->WriteInt( weapon_soulcube ); savefile->WriteInt( weapon_pda ); savefile->WriteInt( weapon_fists ); #ifdef _D3XP savefile->WriteInt( weapon_bloodstone ); savefile->WriteInt( weapon_bloodstone_active1 ); savefile->WriteInt( weapon_bloodstone_active2 ); savefile->WriteInt( weapon_bloodstone_active3 ); savefile->WriteBool( harvest_lock ); savefile->WriteInt( hudPowerup ); savefile->WriteInt( lastHudPowerup ); savefile->WriteInt( hudPowerupDuration ); #endif savefile->WriteInt( heartRate ); savefile->WriteFloat( heartInfo.GetStartTime() ); savefile->WriteFloat( heartInfo.GetDuration() ); savefile->WriteFloat( heartInfo.GetStartValue() ); savefile->WriteFloat( heartInfo.GetEndValue() ); savefile->WriteInt( lastHeartAdjust ); savefile->WriteInt( lastHeartBeat ); savefile->WriteInt( lastDmgTime ); savefile->WriteInt( deathClearContentsTime ); savefile->WriteBool( doingDeathSkin ); savefile->WriteInt( lastArmorPulse ); savefile->WriteFloat( stamina ); savefile->WriteFloat( healthPool ); savefile->WriteInt( nextHealthPulse ); savefile->WriteBool( healthPulse ); savefile->WriteInt( nextHealthTake ); savefile->WriteBool( healthTake ); savefile->WriteBool( hiddenWeapon ); soulCubeProjectile.Save( savefile ); savefile->WriteInt( spectator ); savefile->WriteVec3( colorBar ); savefile->WriteInt( colorBarIndex ); savefile->WriteBool( scoreBoardOpen ); savefile->WriteBool( forceScoreBoard ); savefile->WriteBool( forceRespawn ); savefile->WriteBool( spectating ); savefile->WriteInt( lastSpectateTeleport ); savefile->WriteBool( lastHitToggle ); savefile->WriteBool( forcedReady ); savefile->WriteBool( wantSpectate ); savefile->WriteBool( weaponGone ); savefile->WriteBool( useInitialSpawns ); savefile->WriteInt( latchedTeam ); savefile->WriteInt( tourneyRank ); savefile->WriteInt( tourneyLine ); teleportEntity.Save( savefile ); savefile->WriteInt( teleportKiller ); savefile->WriteInt( minRespawnTime ); savefile->WriteInt( maxRespawnTime ); savefile->WriteVec3( firstPersonViewOrigin ); savefile->WriteMat3( firstPersonViewAxis ); // don't bother saving dragEntity since it's a dev tool savefile->WriteJoint( hipJoint ); savefile->WriteJoint( chestJoint ); savefile->WriteJoint( headJoint ); savefile->WriteStaticObject( physicsObj ); savefile->WriteInt( aasLocation.Num() ); for( i = 0; i < aasLocation.Num(); i++ ) { savefile->WriteInt( aasLocation[ i ].areaNum ); savefile->WriteVec3( aasLocation[ i ].pos ); } savefile->WriteInt( bobFoot ); savefile->WriteFloat( bobFrac ); savefile->WriteFloat( bobfracsin ); savefile->WriteInt( bobCycle ); savefile->WriteFloat( xyspeed ); savefile->WriteInt( stepUpTime ); savefile->WriteFloat( stepUpDelta ); savefile->WriteFloat( idealLegsYaw ); savefile->WriteFloat( legsYaw ); savefile->WriteBool( legsForward ); savefile->WriteFloat( oldViewYaw ); savefile->WriteAngles( viewBobAngles ); savefile->WriteVec3( viewBob ); savefile->WriteInt( landChange ); savefile->WriteInt( landTime ); savefile->WriteInt( currentWeapon ); savefile->WriteInt( idealWeapon ); savefile->WriteInt( previousWeapon ); savefile->WriteInt( weaponSwitchTime ); savefile->WriteBool( weaponEnabled ); savefile->WriteBool( showWeaponViewModel ); savefile->WriteSkin( skin ); savefile->WriteSkin( powerUpSkin ); savefile->WriteString( baseSkinName ); savefile->WriteInt( numProjectilesFired ); savefile->WriteInt( numProjectileHits ); savefile->WriteBool( airless ); savefile->WriteInt( airTics ); savefile->WriteInt( lastAirDamage ); savefile->WriteBool( gibDeath ); savefile->WriteBool( gibsLaunched ); savefile->WriteVec3( gibsDir ); savefile->WriteFloat( zoomFov.GetStartTime() ); savefile->WriteFloat( zoomFov.GetDuration() ); savefile->WriteFloat( zoomFov.GetStartValue() ); savefile->WriteFloat( zoomFov.GetEndValue() ); savefile->WriteFloat( centerView.GetStartTime() ); savefile->WriteFloat( centerView.GetDuration() ); savefile->WriteFloat( centerView.GetStartValue() ); savefile->WriteFloat( centerView.GetEndValue() ); savefile->WriteBool( fxFov ); savefile->WriteFloat( influenceFov ); savefile->WriteInt( influenceActive ); savefile->WriteFloat( influenceRadius ); savefile->WriteObject( influenceEntity ); savefile->WriteMaterial( influenceMaterial ); savefile->WriteSkin( influenceSkin ); savefile->WriteObject( privateCameraView ); for( i = 0; i < NUM_LOGGED_VIEW_ANGLES; i++ ) { savefile->WriteAngles( loggedViewAngles[ i ] ); } for( i = 0; i < NUM_LOGGED_ACCELS; i++ ) { savefile->WriteInt( loggedAccel[ i ].time ); savefile->WriteVec3( loggedAccel[ i ].dir ); } savefile->WriteInt( currentLoggedAccel ); savefile->WriteObject( focusGUIent ); // can't save focusUI savefile->WriteObject( focusCharacter ); savefile->WriteInt( talkCursor ); savefile->WriteInt( focusTime ); savefile->WriteObject( focusVehicle ); savefile->WriteUserInterface( cursor, false ); savefile->WriteInt( oldMouseX ); savefile->WriteInt( oldMouseY ); savefile->WriteString( pdaAudio ); savefile->WriteString( pdaVideo ); savefile->WriteString( pdaVideoWave ); savefile->WriteBool( tipUp ); savefile->WriteBool( objectiveUp ); savefile->WriteInt( lastDamageDef ); savefile->WriteVec3( lastDamageDir ); savefile->WriteInt( lastDamageLocation ); savefile->WriteInt( smoothedFrame ); savefile->WriteBool( smoothedOriginUpdated ); savefile->WriteVec3( smoothedOrigin ); savefile->WriteAngles( smoothedAngles ); savefile->WriteBool( ready ); savefile->WriteBool( respawning ); savefile->WriteBool( leader ); savefile->WriteInt( lastSpectateChange ); savefile->WriteInt( lastTeleFX ); savefile->WriteFloat( pm_stamina.GetFloat() ); if ( hud ) { hud->SetStateString( "message", common->GetLanguageDict()->GetString( "#str_02916" ) ); hud->HandleNamedEvent( "Message" ); } #ifdef _D3XP savefile->WriteInt(weaponToggles.Num()); for(i = 0; i < weaponToggles.Num(); i++) { WeaponToggle_t* weaponToggle = weaponToggles.GetIndex(i); savefile->WriteString(weaponToggle->name); savefile->WriteInt(weaponToggle->toggleList.Num()); for(int j = 0; j < weaponToggle->toggleList.Num(); j++) { savefile->WriteInt(weaponToggle->toggleList[j]); } } savefile->WriteObject( mountedObject ); enviroSuitLight.Save( savefile ); savefile->WriteBool( healthRecharge ); savefile->WriteInt( lastHealthRechargeTime ); savefile->WriteInt( rechargeSpeed ); savefile->WriteFloat( new_g_damageScale ); savefile->WriteBool( bloomEnabled ); savefile->WriteFloat( bloomSpeed ); savefile->WriteFloat( bloomIntensity ); #endif } /* =========== idPlayer::Restore =========== */ void idPlayer::Restore( idRestoreGame *savefile ) { int i; int num; float set; savefile->ReadUsercmd( usercmd ); playerView.Restore( savefile ); savefile->ReadBool( noclip ); savefile->ReadBool( godmode ); savefile->ReadAngles( spawnAngles ); savefile->ReadAngles( viewAngles ); savefile->ReadAngles( cmdAngles ); memset( usercmd.angles, 0, sizeof( usercmd.angles ) ); SetViewAngles( viewAngles ); spawnAnglesSet = true; savefile->ReadInt( buttonMask ); savefile->ReadInt( oldButtons ); savefile->ReadInt( oldFlags ); usercmd.flags = 0; oldFlags = 0; savefile->ReadInt( lastHitTime ); savefile->ReadInt( lastSndHitTime ); savefile->ReadInt( lastSavingThrowTime ); // Re-link idBoolFields to the scriptObject, values will be restored in scriptObject's restore LinkScriptVariables(); inventory.Restore( savefile ); weapon.Restore( savefile ); for ( i = 0; i < inventory.emails.Num(); i++ ) { GetPDA()->AddEmail( inventory.emails[i] ); } savefile->ReadUserInterface( hud ); savefile->ReadUserInterface( objectiveSystem ); savefile->ReadBool( objectiveSystemOpen ); savefile->ReadInt( weapon_soulcube ); savefile->ReadInt( weapon_pda ); savefile->ReadInt( weapon_fists ); #ifdef _D3XP savefile->ReadInt( weapon_bloodstone ); savefile->ReadInt( weapon_bloodstone_active1 ); savefile->ReadInt( weapon_bloodstone_active2 ); savefile->ReadInt( weapon_bloodstone_active3 ); savefile->ReadBool( harvest_lock ); savefile->ReadInt( hudPowerup ); savefile->ReadInt( lastHudPowerup ); savefile->ReadInt( hudPowerupDuration ); #endif savefile->ReadInt( heartRate ); savefile->ReadFloat( set ); heartInfo.SetStartTime( set ); savefile->ReadFloat( set ); heartInfo.SetDuration( set ); savefile->ReadFloat( set ); heartInfo.SetStartValue( set ); savefile->ReadFloat( set ); heartInfo.SetEndValue( set ); savefile->ReadInt( lastHeartAdjust ); savefile->ReadInt( lastHeartBeat ); savefile->ReadInt( lastDmgTime ); savefile->ReadInt( deathClearContentsTime ); savefile->ReadBool( doingDeathSkin ); savefile->ReadInt( lastArmorPulse ); savefile->ReadFloat( stamina ); savefile->ReadFloat( healthPool ); savefile->ReadInt( nextHealthPulse ); savefile->ReadBool( healthPulse ); savefile->ReadInt( nextHealthTake ); savefile->ReadBool( healthTake ); savefile->ReadBool( hiddenWeapon ); soulCubeProjectile.Restore( savefile ); savefile->ReadInt( spectator ); savefile->ReadVec3( colorBar ); savefile->ReadInt( colorBarIndex ); savefile->ReadBool( scoreBoardOpen ); savefile->ReadBool( forceScoreBoard ); savefile->ReadBool( forceRespawn ); savefile->ReadBool( spectating ); savefile->ReadInt( lastSpectateTeleport ); savefile->ReadBool( lastHitToggle ); savefile->ReadBool( forcedReady ); savefile->ReadBool( wantSpectate ); savefile->ReadBool( weaponGone ); savefile->ReadBool( useInitialSpawns ); savefile->ReadInt( latchedTeam ); savefile->ReadInt( tourneyRank ); savefile->ReadInt( tourneyLine ); teleportEntity.Restore( savefile ); savefile->ReadInt( teleportKiller ); savefile->ReadInt( minRespawnTime ); savefile->ReadInt( maxRespawnTime ); savefile->ReadVec3( firstPersonViewOrigin ); savefile->ReadMat3( firstPersonViewAxis ); // don't bother saving dragEntity since it's a dev tool dragEntity.Clear(); savefile->ReadJoint( hipJoint ); savefile->ReadJoint( chestJoint ); savefile->ReadJoint( headJoint ); savefile->ReadStaticObject( physicsObj ); RestorePhysics( &physicsObj ); savefile->ReadInt( num ); aasLocation.SetGranularity( 1 ); aasLocation.SetNum( num ); for( i = 0; i < num; i++ ) { savefile->ReadInt( aasLocation[ i ].areaNum ); savefile->ReadVec3( aasLocation[ i ].pos ); } savefile->ReadInt( bobFoot ); savefile->ReadFloat( bobFrac ); savefile->ReadFloat( bobfracsin ); savefile->ReadInt( bobCycle ); savefile->ReadFloat( xyspeed ); savefile->ReadInt( stepUpTime ); savefile->ReadFloat( stepUpDelta ); savefile->ReadFloat( idealLegsYaw ); savefile->ReadFloat( legsYaw ); savefile->ReadBool( legsForward ); savefile->ReadFloat( oldViewYaw ); savefile->ReadAngles( viewBobAngles ); savefile->ReadVec3( viewBob ); savefile->ReadInt( landChange ); savefile->ReadInt( landTime ); savefile->ReadInt( currentWeapon ); savefile->ReadInt( idealWeapon ); savefile->ReadInt( previousWeapon ); savefile->ReadInt( weaponSwitchTime ); savefile->ReadBool( weaponEnabled ); savefile->ReadBool( showWeaponViewModel ); savefile->ReadSkin( skin ); savefile->ReadSkin( powerUpSkin ); savefile->ReadString( baseSkinName ); savefile->ReadInt( numProjectilesFired ); savefile->ReadInt( numProjectileHits ); savefile->ReadBool( airless ); savefile->ReadInt( airTics ); savefile->ReadInt( lastAirDamage ); savefile->ReadBool( gibDeath ); savefile->ReadBool( gibsLaunched ); savefile->ReadVec3( gibsDir ); savefile->ReadFloat( set ); zoomFov.SetStartTime( set ); savefile->ReadFloat( set ); zoomFov.SetDuration( set ); savefile->ReadFloat( set ); zoomFov.SetStartValue( set ); savefile->ReadFloat( set ); zoomFov.SetEndValue( set ); savefile->ReadFloat( set ); centerView.SetStartTime( set ); savefile->ReadFloat( set ); centerView.SetDuration( set ); savefile->ReadFloat( set ); centerView.SetStartValue( set ); savefile->ReadFloat( set ); centerView.SetEndValue( set ); savefile->ReadBool( fxFov ); savefile->ReadFloat( influenceFov ); savefile->ReadInt( influenceActive ); savefile->ReadFloat( influenceRadius ); savefile->ReadObject( reinterpret_cast<idClass *&>( influenceEntity ) ); savefile->ReadMaterial( influenceMaterial ); savefile->ReadSkin( influenceSkin ); savefile->ReadObject( reinterpret_cast<idClass *&>( privateCameraView ) ); for( i = 0; i < NUM_LOGGED_VIEW_ANGLES; i++ ) { savefile->ReadAngles( loggedViewAngles[ i ] ); } for( i = 0; i < NUM_LOGGED_ACCELS; i++ ) { savefile->ReadInt( loggedAccel[ i ].time ); savefile->ReadVec3( loggedAccel[ i ].dir ); } savefile->ReadInt( currentLoggedAccel ); savefile->ReadObject( reinterpret_cast<idClass *&>( focusGUIent ) ); // can't save focusUI focusUI = NULL; savefile->ReadObject( reinterpret_cast<idClass *&>( focusCharacter ) ); savefile->ReadInt( talkCursor ); savefile->ReadInt( focusTime ); savefile->ReadObject( reinterpret_cast<idClass *&>( focusVehicle ) ); savefile->ReadUserInterface( cursor ); savefile->ReadInt( oldMouseX ); savefile->ReadInt( oldMouseY ); savefile->ReadString( pdaAudio ); savefile->ReadString( pdaVideo ); savefile->ReadString( pdaVideoWave ); savefile->ReadBool( tipUp ); savefile->ReadBool( objectiveUp ); savefile->ReadInt( lastDamageDef ); savefile->ReadVec3( lastDamageDir ); savefile->ReadInt( lastDamageLocation ); savefile->ReadInt( smoothedFrame ); savefile->ReadBool( smoothedOriginUpdated ); savefile->ReadVec3( smoothedOrigin ); savefile->ReadAngles( smoothedAngles ); savefile->ReadBool( ready ); savefile->ReadBool( respawning ); savefile->ReadBool( leader ); savefile->ReadInt( lastSpectateChange ); savefile->ReadInt( lastTeleFX ); // set the pm_ cvars const idKeyValue *kv; kv = spawnArgs.MatchPrefix( "pm_", NULL ); while( kv ) { cvarSystem->SetCVarString( kv->GetKey(), kv->GetValue() ); kv = spawnArgs.MatchPrefix( "pm_", kv ); } savefile->ReadFloat( set ); pm_stamina.SetFloat( set ); // create combat collision hull for exact collision detection SetCombatModel(); #ifdef _D3XP int weaponToggleCount; savefile->ReadInt(weaponToggleCount); for(i = 0; i < weaponToggleCount; i++) { WeaponToggle_t newToggle; memset(&newToggle, 0, sizeof(newToggle)); idStr name; savefile->ReadString(name); strcpy(newToggle.name, name.c_str()); int indexCount; savefile->ReadInt(indexCount); for(int j = 0; j < indexCount; j++) { int temp; savefile->ReadInt(temp); newToggle.toggleList.Append(temp); } weaponToggles.Set(newToggle.name, newToggle); } savefile->ReadObject(reinterpret_cast<idClass *&>(mountedObject)); enviroSuitLight.Restore( savefile ); savefile->ReadBool( healthRecharge ); savefile->ReadInt( lastHealthRechargeTime ); savefile->ReadInt( rechargeSpeed ); savefile->ReadFloat( new_g_damageScale ); savefile->ReadBool( bloomEnabled ); savefile->ReadFloat( bloomSpeed ); savefile->ReadFloat( bloomIntensity ); #endif } /* =============== idPlayer::PrepareForRestart ================ */ void idPlayer::PrepareForRestart( void ) { ClearPowerUps(); Spectate( true ); forceRespawn = true; #ifdef CTF // Confirm reset hud states DropFlag(); if ( hud ) { hud->SetStateInt( "red_flagstatus", 0 ); hud->SetStateInt( "blue_flagstatus", 0 ); } #endif // we will be restarting program, clear the client entities from program-related things first ShutdownThreads(); // the sound world is going to be cleared, don't keep references to emitters FreeSoundEmitter( false ); } /* =============== idPlayer::Restart ================ */ void idPlayer::Restart( void ) { idActor::Restart(); // client needs to setup the animation script object again if ( gameLocal.isClient ) { Init(); } else { // choose a random spot and prepare the point of view in case player is left spectating assert( spectating ); SpawnFromSpawnSpot(); } useInitialSpawns = true; UpdateSkinSetup( true ); } /* =============== idPlayer::ServerSpectate ================ */ void idPlayer::ServerSpectate( bool spectate ) { assert( !gameLocal.isClient ); if ( spectating != spectate ) { Spectate( spectate ); if ( spectate ) { SetSpectateOrigin(); } else { if ( gameLocal.gameType == GAME_DM ) { // make sure the scores are reset so you can't exploit by spectating and entering the game back // other game types don't matter, as you either can't join back, or it's team scores gameLocal.mpGame.ClearFrags( entityNumber ); } } } if ( !spectate ) { SpawnFromSpawnSpot(); } #ifdef CTF // drop the flag if player was carrying it if ( spectate && gameLocal.isMultiplayer && gameLocal.mpGame.IsGametypeFlagBased() && carryingFlag ) { DropFlag(); } #endif } /* =========== idPlayer::SelectInitialSpawnPoint Try to find a spawn point marked 'initial', otherwise use normal spawn selection. ============ */ void idPlayer::SelectInitialSpawnPoint( idVec3 &origin, idAngles &angles ) { idEntity *spot; idStr skin; spot = gameLocal.SelectInitialSpawnPoint( this ); // set the player skin from the spawn location if ( spot->spawnArgs.GetString( "skin", NULL, skin ) ) { spawnArgs.Set( "spawn_skin", skin ); } // activate the spawn locations targets spot->PostEventMS( &EV_ActivateTargets, 0, this ); origin = spot->GetPhysics()->GetOrigin(); origin[2] += 4.0f + CM_BOX_EPSILON; // move up to make sure the player is at least an epsilon above the floor angles = spot->GetPhysics()->GetAxis().ToAngles(); } /* =========== idPlayer::SpawnFromSpawnSpot Chooses a spawn location and spawns the player ============ */ void idPlayer::SpawnFromSpawnSpot( void ) { idVec3 spawn_origin; idAngles spawn_angles; SelectInitialSpawnPoint( spawn_origin, spawn_angles ); SpawnToPoint( spawn_origin, spawn_angles ); } /* =========== idPlayer::SpawnToPoint Called every time a client is placed fresh in the world: after the first ClientBegin, and after each respawn Initializes all non-persistant parts of playerState when called here with spectating set to true, just place yourself and init ============ */ void idPlayer::SpawnToPoint( const idVec3 &spawn_origin, const idAngles &spawn_angles ) { idVec3 spec_origin; assert( !gameLocal.isClient ); respawning = true; Init(); fl.noknockback = false; // stop any ragdolls being used StopRagdoll(); // set back the player physics SetPhysics( &physicsObj ); physicsObj.SetClipModelAxis(); physicsObj.EnableClip(); if ( !spectating ) { SetCombatContents( true ); } physicsObj.SetLinearVelocity( vec3_origin ); // setup our initial view if ( !spectating ) { SetOrigin( spawn_origin ); } else { spec_origin = spawn_origin; spec_origin[ 2 ] += pm_normalheight.GetFloat(); spec_origin[ 2 ] += SPECTATE_RAISE; SetOrigin( spec_origin ); } // if this is the first spawn of the map, we don't have a usercmd yet, // so the delta angles won't be correct. This will be fixed on the first think. viewAngles = ang_zero; SetDeltaViewAngles( ang_zero ); SetViewAngles( spawn_angles ); spawnAngles = spawn_angles; spawnAnglesSet = false; legsForward = true; legsYaw = 0.0f; idealLegsYaw = 0.0f; oldViewYaw = viewAngles.yaw; if ( spectating ) { Hide(); } else { Show(); } if ( gameLocal.isMultiplayer ) { if ( !spectating ) { // we may be called twice in a row in some situations. avoid a double fx and 'fly to the roof' if ( lastTeleFX < gameLocal.time - 1000 ) { idEntityFx::StartFx( spawnArgs.GetString( "fx_spawn" ), &spawn_origin, NULL, this, true ); lastTeleFX = gameLocal.time; } } AI_TELEPORT = true; } else { AI_TELEPORT = false; } // kill anything at the new position if ( !spectating ) { physicsObj.SetClipMask( MASK_PLAYERSOLID ); // the clip mask is usually maintained in Move(), but KillBox requires it gameLocal.KillBox( this ); } // don't allow full run speed for a bit physicsObj.SetKnockBack( 100 ); // set our respawn time and buttons so that if we're killed we don't respawn immediately minRespawnTime = gameLocal.time; maxRespawnTime = gameLocal.time; if ( !spectating ) { forceRespawn = false; } privateCameraView = NULL; BecomeActive( TH_THINK ); // run a client frame to drop exactly to the floor, // initialize animations and other things Think(); respawning = false; lastManOver = false; lastManPlayAgain = false; isTelefragged = false; } /* =============== idPlayer::SavePersistantInfo Saves any inventory and player stats when changing levels. =============== */ void idPlayer::SavePersistantInfo( void ) { idDict &playerInfo = gameLocal.persistentPlayerInfo[entityNumber]; playerInfo.Clear(); inventory.GetPersistantData( playerInfo ); playerInfo.SetInt( "health", health ); playerInfo.SetInt( "current_weapon", currentWeapon ); } /* =============== idPlayer::RestorePersistantInfo Restores any inventory and player stats when changing levels. =============== */ void idPlayer::RestorePersistantInfo( void ) { if ( gameLocal.isMultiplayer ) { gameLocal.persistentPlayerInfo[entityNumber].Clear(); } spawnArgs.Copy( gameLocal.persistentPlayerInfo[entityNumber] ); inventory.RestoreInventory( this, spawnArgs ); health = spawnArgs.GetInt( "health", "100" ); if ( !gameLocal.isClient ) { idealWeapon = spawnArgs.GetInt( "current_weapon", "1" ); } } /* ================ idPlayer::GetUserInfo ================ */ idDict *idPlayer::GetUserInfo( void ) { return &gameLocal.userInfo[ entityNumber ]; } /* ============== idPlayer::UpdateSkinSetup ============== */ void idPlayer::UpdateSkinSetup( bool restart ) { if ( restart ) { team = ( idStr::Icmp( GetUserInfo()->GetString( "ui_team" ), "Blue" ) == 0 ); } if ( gameLocal.mpGame.IsGametypeTeamBased() ) { /* CTF */ if ( team ) { baseSkinName = "skins/characters/player/marine_mp_blue"; } else { baseSkinName = "skins/characters/player/marine_mp_red"; } if ( !gameLocal.isClient && team != latchedTeam ) { gameLocal.mpGame.SwitchToTeam( entityNumber, latchedTeam, team ); } latchedTeam = team; } else { baseSkinName = GetUserInfo()->GetString( "ui_skin" ); } if ( !baseSkinName.Length() ) { baseSkinName = "skins/characters/player/marine_mp"; } skin = declManager->FindSkin( baseSkinName, false ); assert( skin ); // match the skin to a color band for scoreboard if ( baseSkinName.Find( "red" ) != -1 ) { colorBarIndex = 1; } else if ( baseSkinName.Find( "green" ) != -1 ) { colorBarIndex = 2; } else if ( baseSkinName.Find( "blue" ) != -1 ) { colorBarIndex = 3; } else if ( baseSkinName.Find( "yellow" ) != -1 ) { colorBarIndex = 4; } else if ( baseSkinName.Find( "grey" ) != -1 ) { colorBarIndex = 5; } else if ( baseSkinName.Find( "purple" ) != -1 ) { colorBarIndex = 6; } else if ( baseSkinName.Find( "orange" ) != -1 ) { colorBarIndex = 7; } else { colorBarIndex = 0; } colorBar = colorBarTable[ colorBarIndex ]; if ( PowerUpActive( BERSERK ) ) { powerUpSkin = declManager->FindSkin( baseSkinName + "_berserk" ); } #ifdef _D3XP else if ( PowerUpActive( INVULNERABILITY ) ) { powerUpSkin = declManager->FindSkin( baseSkinName + "_invuln" ); //} else if ( PowerUpActive( HASTE ) ) { // powerUpSkin = declManager->FindSkin( baseSkinName + "_haste" ); } #endif } /* ============== idPlayer::BalanceTDM ============== */ bool idPlayer::BalanceTDM( void ) { int i, balanceTeam, teamCount[2]; idEntity *ent; teamCount[ 0 ] = teamCount[ 1 ] = 0; for( i = 0; i < gameLocal.numClients; i++ ) { ent = gameLocal.entities[ i ]; if ( ent && ent->IsType( idPlayer::Type ) ) { teamCount[ static_cast< idPlayer * >( ent )->team ]++; } } balanceTeam = -1; if ( teamCount[ 0 ] < teamCount[ 1 ] ) { balanceTeam = 0; } else if ( teamCount[ 0 ] > teamCount[ 1 ] ) { balanceTeam = 1; } if ( balanceTeam != -1 && team != balanceTeam ) { common->DPrintf( "team balance: forcing player %d to %s team\n", entityNumber, balanceTeam ? "blue" : "red" ); team = balanceTeam; GetUserInfo()->Set( "ui_team", team ? "Blue" : "Red" ); return true; } return false; } /* ============== idPlayer::UserInfoChanged ============== */ bool idPlayer::UserInfoChanged( bool canModify ) { idDict *userInfo; bool modifiedInfo; bool spec; bool newready; userInfo = GetUserInfo(); showWeaponViewModel = userInfo->GetBool( "ui_showGun" ); if ( !gameLocal.isMultiplayer ) { return false; } modifiedInfo = false; spec = ( idStr::Icmp( userInfo->GetString( "ui_spectate" ), "Spectate" ) == 0 ); if ( gameLocal.serverInfo.GetBool( "si_spectators" ) ) { // never let spectators go back to game while sudden death is on if ( canModify && gameLocal.mpGame.GetGameState() == idMultiplayerGame::SUDDENDEATH && !spec && wantSpectate == true ) { userInfo->Set( "ui_spectate", "Spectate" ); modifiedInfo |= true; } else { if ( spec != wantSpectate && !spec ) { // returning from spectate, set forceRespawn so we don't get stuck in spectate forever forceRespawn = true; } wantSpectate = spec; } } else { if ( canModify && spec ) { userInfo->Set( "ui_spectate", "Play" ); modifiedInfo |= true; } else if ( spectating ) { // allow player to leaving spectator mode if they were in it when si_spectators got turned off forceRespawn = true; } wantSpectate = false; } newready = ( idStr::Icmp( userInfo->GetString( "ui_ready" ), "Ready" ) == 0 ); if ( ready != newready && gameLocal.mpGame.GetGameState() == idMultiplayerGame::WARMUP && !wantSpectate ) { gameLocal.mpGame.AddChatLine( common->GetLanguageDict()->GetString( "#str_07180" ), userInfo->GetString( "ui_name" ), newready ? common->GetLanguageDict()->GetString( "#str_04300" ) : common->GetLanguageDict()->GetString( "#str_04301" ) ); } ready = newready; team = ( idStr::Icmp( userInfo->GetString( "ui_team" ), "Blue" ) == 0 ); // server maintains TDM balance if ( canModify && gameLocal.mpGame.IsGametypeTeamBased() && !gameLocal.mpGame.IsInGame( entityNumber ) && g_balanceTDM.GetBool() ) { /* CTF */ modifiedInfo |= BalanceTDM( ); } UpdateSkinSetup( false ); isChatting = userInfo->GetBool( "ui_chat", "0" ); if ( canModify && isChatting && AI_DEAD ) { // if dead, always force chat icon off. isChatting = false; userInfo->SetBool( "ui_chat", false ); modifiedInfo |= true; } return modifiedInfo; } /* =============== idPlayer::UpdateHudAmmo =============== */ void idPlayer::UpdateHudAmmo( idUserInterface *_hud ) { int inclip; int ammoamount; assert( weapon.GetEntity() ); assert( _hud ); inclip = weapon.GetEntity()->AmmoInClip(); ammoamount = weapon.GetEntity()->AmmoAvailable(); #ifdef _D3XP //Hack to stop the bloodstone ammo to display when it is being activated if ( ammoamount < 0 || !weapon.GetEntity()->IsReady() || currentWeapon == weapon_bloodstone) { #else if ( ammoamount < 0 || !weapon.GetEntity()->IsReady() ) { #endif // show infinite ammo _hud->SetStateString( "player_ammo", "" ); _hud->SetStateString( "player_totalammo", "" ); } else { // show remaining ammo #ifdef _D3XP _hud->SetStateString( "player_totalammo", va( "%i", ammoamount ) ); #else _hud->SetStateString( "player_totalammo", va( "%i", ammoamount - inclip ) ); #endif _hud->SetStateString( "player_ammo", weapon.GetEntity()->ClipSize() ? va( "%i", inclip ) : "--" ); // how much in the current clip _hud->SetStateString( "player_clips", weapon.GetEntity()->ClipSize() ? va( "%i", ammoamount / weapon.GetEntity()->ClipSize() ) : "--" ); #ifdef _D3XP _hud->SetStateString( "player_allammo", va( "%i/%i", inclip, ammoamount ) ); #else _hud->SetStateString( "player_allammo", va( "%i/%i", inclip, ammoamount - inclip ) ); #endif } _hud->SetStateBool( "player_ammo_empty", ( ammoamount == 0 ) ); _hud->SetStateBool( "player_clip_empty", ( weapon.GetEntity()->ClipSize() ? inclip == 0 : false ) ); _hud->SetStateBool( "player_clip_low", ( weapon.GetEntity()->ClipSize() ? inclip <= weapon.GetEntity()->LowAmmo() : false ) ); #ifdef _D3XP //Hack to stop the bloodstone ammo to display when it is being activated if(currentWeapon == weapon_bloodstone) { _hud->SetStateBool( "player_ammo_empty", false ); _hud->SetStateBool( "player_clip_empty", false ); _hud->SetStateBool( "player_clip_low", false ); } #endif #ifdef _D3XP //Let the HUD know the total amount of ammo regardless of the ammo required value _hud->SetStateString( "player_ammo_count", va("%i", weapon.GetEntity()->AmmoCount())); #endif #ifdef _D3XP //Make sure the hud always knows how many bloodstone charges there are int ammoRequired; ammo_t ammo_i = inventory.AmmoIndexForWeaponClass( "weapon_bloodstone_passive", &ammoRequired ); int bloodstoneAmmo = inventory.HasAmmo( ammo_i, ammoRequired ); _hud->SetStateString("player_bloodstone_ammo", va("%i", bloodstoneAmmo)); _hud->HandleNamedEvent( "bloodstoneAmmoUpdate" ); #endif _hud->HandleNamedEvent( "updateAmmo" ); } /* =============== idPlayer::UpdateHudStats =============== */ void idPlayer::UpdateHudStats( idUserInterface *_hud ) { int staminapercentage; float max_stamina; assert( _hud ); max_stamina = pm_stamina.GetFloat(); if ( !max_stamina ) { // stamina disabled, so show full stamina bar staminapercentage = 100.0f; } else { staminapercentage = idMath::FtoiFast( 100.0f * stamina / max_stamina ); } _hud->SetStateInt( "player_health", health ); _hud->SetStateInt( "player_stamina", staminapercentage ); _hud->SetStateInt( "player_armor", inventory.armor ); _hud->SetStateInt( "player_hr", heartRate ); _hud->SetStateInt( "player_nostamina", ( max_stamina == 0 ) ? 1 : 0 ); _hud->HandleNamedEvent( "updateArmorHealthAir" ); #ifdef _D3XP _hud->HandleNamedEvent( "updatePowerup" ); #endif if ( healthPulse ) { _hud->HandleNamedEvent( "healthPulse" ); StartSound( "snd_healthpulse", SND_CHANNEL_ITEM, 0, false, NULL ); healthPulse = false; } if ( healthTake ) { _hud->HandleNamedEvent( "healthPulse" ); StartSound( "snd_healthtake", SND_CHANNEL_ITEM, 0, false, NULL ); healthTake = false; } if ( inventory.ammoPulse ) { _hud->HandleNamedEvent( "ammoPulse" ); inventory.ammoPulse = false; } if ( inventory.weaponPulse ) { // We need to update the weapon hud manually, but not // the armor/ammo/health because they are updated every // frame no matter what UpdateHudWeapon(); _hud->HandleNamedEvent( "weaponPulse" ); inventory.weaponPulse = false; } if ( inventory.armorPulse ) { _hud->HandleNamedEvent( "armorPulse" ); inventory.armorPulse = false; } #ifdef CTF if ( gameLocal.mpGame.IsGametypeFlagBased() && _hud ) { _hud->SetStateInt( "red_flagstatus", gameLocal.mpGame.GetFlagStatus( 0 ) ); _hud->SetStateInt( "blue_flagstatus", gameLocal.mpGame.GetFlagStatus( 1 ) ); _hud->SetStateInt( "red_team_score", gameLocal.mpGame.GetFlagPoints( 0 ) ); _hud->SetStateInt( "blue_team_score", gameLocal.mpGame.GetFlagPoints( 1 ) ); _hud->HandleNamedEvent( "RedFlagStatusChange" ); _hud->HandleNamedEvent( "BlueFlagStatusChange" ); } _hud->HandleNamedEvent( "selfTeam" ); #endif UpdateHudAmmo( _hud ); } /* =============== idPlayer::UpdateHudWeapon =============== */ void idPlayer::UpdateHudWeapon( bool flashWeapon ) { idUserInterface *hud = idPlayer::hud; // if updating the hud of a followed client if ( gameLocal.localClientNum >= 0 && gameLocal.entities[ gameLocal.localClientNum ] && gameLocal.entities[ gameLocal.localClientNum ]->IsType( idPlayer::Type ) ) { idPlayer *p = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.localClientNum ] ); if ( p->spectating && p->spectator == entityNumber ) { assert( p->hud ); hud = p->hud; } } if ( !hud ) { return; } for ( int i = 0; i < MAX_WEAPONS; i++ ) { const char *weapnum = va( "def_weapon%d", i ); const char *hudWeap = va( "weapon%d", i ); int weapstate = 0; if ( inventory.weapons & ( 1 << i ) ) { const char *weap = spawnArgs.GetString( weapnum ); if ( weap && *weap ) { weapstate++; } if ( idealWeapon == i ) { weapstate++; } } hud->SetStateInt( hudWeap, weapstate ); } if ( flashWeapon ) { /*#ifdef _D3XP //Clear all hud weapon varaibles for the weapon change hud->SetStateString( "player_ammo", "" ); hud->SetStateString( "player_totalammo", "" ); hud->SetStateString( "player_clips", "" ); hud->SetStateString( "player_allammo", "" ); hud->SetStateBool( "player_ammo_empty", false ); hud->SetStateBool( "player_clip_empty", false ); hud->SetStateBool( "player_clip_low", false ); hud->SetStateString( "player_ammo_count", ""); #endif*/ hud->HandleNamedEvent( "weaponChange" ); } } /* =============== idPlayer::DrawHUD =============== */ void idPlayer::DrawHUD( idUserInterface *_hud ) { if ( !weapon.GetEntity() || influenceActive != INFLUENCE_NONE || privateCameraView || gameLocal.GetCamera() || !_hud || !g_showHud.GetBool() ) { return; } UpdateHudStats( _hud ); _hud->SetStateString( "weapicon", weapon.GetEntity()->Icon() ); // FIXME: this is temp to allow the sound meter to show up in the hud // it should be commented out before shipping but the code can remain // for mod developers to enable for the same functionality _hud->SetStateInt( "s_debug", cvarSystem->GetCVarInteger( "s_showLevelMeter" ) ); weapon.GetEntity()->UpdateGUI(); _hud->Redraw( gameLocal.realClientTime ); // weapon targeting crosshair if ( !GuiActive() ) { if ( cursor && weapon.GetEntity()->ShowCrosshair() ) { #ifdef _D3XP if ( weapon.GetEntity()->GetGrabberState() == 1 || weapon.GetEntity()->GetGrabberState() == 2 ) { cursor->SetStateString( "grabbercursor", "1" ); cursor->SetStateString( "combatcursor", "0" ); } else { cursor->SetStateString( "grabbercursor", "0" ); cursor->SetStateString( "combatcursor", "1" ); } #endif cursor->Redraw( gameLocal.realClientTime ); } } } /* =============== idPlayer::EnterCinematic =============== */ void idPlayer::EnterCinematic( void ) { #ifdef _D3XP if ( PowerUpActive( HELLTIME ) ) { StopHelltime(); } #endif Hide(); StopAudioLog(); StopSound( SND_CHANNEL_PDA, false ); if ( hud ) { hud->HandleNamedEvent( "radioChatterDown" ); } physicsObj.SetLinearVelocity( vec3_origin ); SetState( "EnterCinematic" ); UpdateScript(); if ( weaponEnabled && weapon.GetEntity() ) { weapon.GetEntity()->EnterCinematic(); } AI_FORWARD = false; AI_BACKWARD = false; AI_STRAFE_LEFT = false; AI_STRAFE_RIGHT = false; AI_RUN = false; AI_ATTACK_HELD = false; AI_WEAPON_FIRED = false; AI_JUMP = false; AI_CROUCH = false; AI_ONGROUND = true; AI_ONLADDER = false; AI_DEAD = ( health <= 0 ); AI_RUN = false; AI_PAIN = false; AI_HARDLANDING = false; AI_SOFTLANDING = false; AI_RELOAD = false; AI_TELEPORT = false; AI_TURN_LEFT = false; AI_TURN_RIGHT = false; } /* =============== idPlayer::ExitCinematic =============== */ void idPlayer::ExitCinematic( void ) { Show(); if ( weaponEnabled && weapon.GetEntity() ) { weapon.GetEntity()->ExitCinematic(); } SetState( "ExitCinematic" ); UpdateScript(); } /* ===================== idPlayer::UpdateConditions ===================== */ void idPlayer::UpdateConditions( void ) { idVec3 velocity; float forwardspeed; float sidespeed; // minus the push velocity to avoid playing the walking animation and sounds when riding a mover velocity = physicsObj.GetLinearVelocity() - physicsObj.GetPushedLinearVelocity(); if ( influenceActive ) { AI_FORWARD = false; AI_BACKWARD = false; AI_STRAFE_LEFT = false; AI_STRAFE_RIGHT = false; } else if ( gameLocal.time - lastDmgTime < 500 ) { forwardspeed = velocity * viewAxis[ 0 ]; sidespeed = velocity * viewAxis[ 1 ]; AI_FORWARD = AI_ONGROUND && ( forwardspeed > 20.01f ); AI_BACKWARD = AI_ONGROUND && ( forwardspeed < -20.01f ); AI_STRAFE_LEFT = AI_ONGROUND && ( sidespeed > 20.01f ); AI_STRAFE_RIGHT = AI_ONGROUND && ( sidespeed < -20.01f ); } else if ( xyspeed > MIN_BOB_SPEED ) { AI_FORWARD = AI_ONGROUND && ( usercmd.forwardmove > 0 ); AI_BACKWARD = AI_ONGROUND && ( usercmd.forwardmove < 0 ); AI_STRAFE_LEFT = AI_ONGROUND && ( usercmd.rightmove < 0 ); AI_STRAFE_RIGHT = AI_ONGROUND && ( usercmd.rightmove > 0 ); } else { AI_FORWARD = false; AI_BACKWARD = false; AI_STRAFE_LEFT = false; AI_STRAFE_RIGHT = false; } AI_RUN = ( usercmd.buttons & BUTTON_RUN ) && ( ( !pm_stamina.GetFloat() ) || ( stamina > pm_staminathreshold.GetFloat() ) ); AI_DEAD = ( health <= 0 ); } /* ================== WeaponFireFeedback Called when a weapon fires, generates head twitches, etc ================== */ void idPlayer::WeaponFireFeedback( const idDict *weaponDef ) { // force a blink blink_time = 0; // play the fire animation AI_WEAPON_FIRED = true; // update view feedback playerView.WeaponFireFeedback( weaponDef ); } /* =============== idPlayer::StopFiring =============== */ void idPlayer::StopFiring( void ) { AI_ATTACK_HELD = false; AI_WEAPON_FIRED = false; AI_RELOAD = false; if ( weapon.GetEntity() ) { weapon.GetEntity()->EndAttack(); } } /* =============== idPlayer::FireWeapon =============== */ void idPlayer::FireWeapon( void ) { idMat3 axis; idVec3 muzzle; if ( privateCameraView ) { return; } if ( g_editEntityMode.GetInteger() ) { GetViewPos( muzzle, axis ); if ( gameLocal.editEntities->SelectEntity( muzzle, axis[0], this ) ) { return; } } if ( !hiddenWeapon && weapon.GetEntity()->IsReady() ) { if ( weapon.GetEntity()->AmmoInClip() || weapon.GetEntity()->AmmoAvailable() ) { AI_ATTACK_HELD = true; weapon.GetEntity()->BeginAttack(); if ( ( weapon_soulcube >= 0 ) && ( currentWeapon == weapon_soulcube ) ) { if ( hud ) { hud->HandleNamedEvent( "soulCubeNotReady" ); } SelectWeapon( previousWeapon, false ); } #ifdef _D3XP if( (weapon_bloodstone >= 0) && (currentWeapon == weapon_bloodstone) && inventory.weapons & ( 1 << weapon_bloodstone_active1 ) && weapon.GetEntity()->GetStatus() == WP_READY) { // tell it to switch to the previous weapon. Only do this once to prevent // weapon toggling messing up the previous weapon if(idealWeapon == weapon_bloodstone) { if(previousWeapon == weapon_bloodstone || previousWeapon == -1) { NextBestWeapon(); } else { //Since this is a toggle weapon just select itself and it will toggle to the last weapon SelectWeapon( weapon_bloodstone, false ); } } } #endif } else { NextBestWeapon(); } } if ( hud ) { if ( tipUp ) { HideTip(); } // may want to track with with a bool as well // keep from looking up named events so often if ( objectiveUp ) { HideObjective(); } } } /* =============== idPlayer::CacheWeapons =============== */ void idPlayer::CacheWeapons( void ) { idStr weap; int w; // check if we have any weapons if ( !inventory.weapons ) { return; } for( w = 0; w < MAX_WEAPONS; w++ ) { if ( inventory.weapons & ( 1 << w ) ) { weap = spawnArgs.GetString( va( "def_weapon%d", w ) ); if ( weap != "" ) { idWeapon::CacheWeapon( weap ); } else { inventory.weapons &= ~( 1 << w ); } } } } /* =============== idPlayer::Give =============== */ bool idPlayer::Give( const char *statname, const char *value ) { int amount; if ( AI_DEAD ) { return false; } if ( !idStr::Icmp( statname, "health" ) ) { if ( health >= inventory.maxHealth ) { return false; } amount = atoi( value ); if ( amount ) { health += amount; if ( health > inventory.maxHealth ) { health = inventory.maxHealth; } if ( hud ) { hud->HandleNamedEvent( "healthPulse" ); } } } else if ( !idStr::Icmp( statname, "stamina" ) ) { if ( stamina >= 100 ) { return false; } stamina += atof( value ); if ( stamina > 100 ) { stamina = 100; } } else if ( !idStr::Icmp( statname, "heartRate" ) ) { heartRate += atoi( value ); if ( heartRate > MAX_HEARTRATE ) { heartRate = MAX_HEARTRATE; } } else if ( !idStr::Icmp( statname, "air" ) ) { if ( airTics >= pm_airTics.GetInteger() ) { return false; } airTics += atoi( value ) / 100.0 * pm_airTics.GetInteger(); if ( airTics > pm_airTics.GetInteger() ) { airTics = pm_airTics.GetInteger(); } #ifdef _D3XP } else if ( !idStr::Icmp( statname, "enviroTime" ) ) { if ( PowerUpActive( ENVIROTIME ) ) { inventory.powerupEndTime[ ENVIROTIME ] += (atof(value) * 1000); } else { GivePowerUp( ENVIROTIME, atoi(value)*1000 ); } } else { bool ret = inventory.Give( this, spawnArgs, statname, value, &idealWeapon, true ); if(!idStr::Icmp( statname, "ammo_bloodstone" ) ) { //int i = inventory.AmmoIndexForAmmoClass( statname ); //int max = inventory.MaxAmmoForAmmoClass( this, statname ); //if(hud && inventory.ammo[ i ] >= max) { if(hud) { //Force an update of the bloodstone ammount int ammoRequired; ammo_t ammo_i = inventory.AmmoIndexForWeaponClass( "weapon_bloodstone_passive", &ammoRequired ); int bloodstoneAmmo = inventory.HasAmmo( ammo_i, ammoRequired ); hud->SetStateString("player_bloodstone_ammo", va("%i", bloodstoneAmmo)); hud->HandleNamedEvent("bloodstoneReady"); //Make sure we unlock the ability to harvest harvest_lock = false; } } return ret; #else return inventory.Give( this, spawnArgs, statname, value, &idealWeapon, true ); #endif } return true; } /* =============== idPlayer::GiveHealthPool adds health to the player health pool =============== */ void idPlayer::GiveHealthPool( float amt ) { if ( AI_DEAD ) { return; } if ( health > 0 ) { healthPool += amt; if ( healthPool > inventory.maxHealth - health ) { healthPool = inventory.maxHealth - health; } nextHealthPulse = gameLocal.time; } } /* =============== idPlayer::GiveItem Returns false if the item shouldn't be picked up =============== */ bool idPlayer::GiveItem( idItem *item ) { int i; const idKeyValue *arg; idDict attr; bool gave; int numPickup; if ( gameLocal.isMultiplayer && spectating ) { return false; } item->GetAttributes( attr ); gave = false; numPickup = inventory.pickupItemNames.Num(); for( i = 0; i < attr.GetNumKeyVals(); i++ ) { arg = attr.GetKeyVal( i ); if ( Give( arg->GetKey(), arg->GetValue() ) ) { gave = true; } } arg = item->spawnArgs.MatchPrefix( "inv_weapon", NULL ); if ( arg && hud ) { // We need to update the weapon hud manually, but not // the armor/ammo/health because they are updated every // frame no matter what UpdateHudWeapon( false ); hud->HandleNamedEvent( "weaponPulse" ); } // display the pickup feedback on the hud if ( gave && ( numPickup == inventory.pickupItemNames.Num() ) ) { inventory.AddPickupName( item->spawnArgs.GetString( "inv_name" ), item->spawnArgs.GetString( "inv_icon" ), this ); //_D3XP } return gave; } /* =============== idPlayer::PowerUpModifier =============== */ float idPlayer::PowerUpModifier( int type ) { float mod = 1.0f; if ( PowerUpActive( BERSERK ) ) { switch( type ) { case SPEED: { mod *= 1.7f; break; } case PROJECTILE_DAMAGE: { mod *= 2.0f; break; } case MELEE_DAMAGE: { mod *= 30.0f; break; } case MELEE_DISTANCE: { mod *= 2.0f; break; } } } if ( gameLocal.isMultiplayer && !gameLocal.isClient ) { if ( PowerUpActive( MEGAHEALTH ) ) { if ( healthPool <= 0 ) { GiveHealthPool( 100 ); } } else { healthPool = 0; } #ifdef _D3XP /*if( PowerUpActive( HASTE ) ) { switch( type ) { case SPEED: { mod = 1.7f; break; } } }*/ #endif } return mod; } /* =============== idPlayer::PowerUpActive =============== */ bool idPlayer::PowerUpActive( int powerup ) const { return ( inventory.powerups & ( 1 << powerup ) ) != 0; } /* =============== idPlayer::GivePowerUp =============== */ bool idPlayer::GivePowerUp( int powerup, int time ) { const char *sound; const char *skin; if ( powerup >= 0 && powerup < MAX_POWERUPS ) { if ( gameLocal.isServer ) { idBitMsg msg; byte msgBuf[MAX_EVENT_PARAM_SIZE]; msg.Init( msgBuf, sizeof( msgBuf ) ); msg.WriteShort( powerup ); msg.WriteBits( 1, 1 ); ServerSendEvent( EVENT_POWERUP, &msg, false, -1 ); } if ( powerup != MEGAHEALTH ) { inventory.GivePowerUp( this, powerup, time ); } const idDeclEntityDef *def = NULL; switch( powerup ) { case BERSERK: { if(gameLocal.isMultiplayer && !gameLocal.isClient) { inventory.AddPickupName("#str_00100627", "", this); } if(gameLocal.isMultiplayer) { if ( spawnArgs.GetString( "snd_berserk_third", "", &sound ) ) { StartSoundShader( declManager->FindSound( sound ), SND_CHANNEL_DEMONIC, 0, false, NULL ); } } if ( baseSkinName.Length() ) { powerUpSkin = declManager->FindSkin( baseSkinName + "_berserk" ); } if ( !gameLocal.isClient ) { #ifdef _D3XP if( !gameLocal.isMultiplayer ) { // Trying it out without the health boost (1/3/05) // Give the player full health in single-player // health = 100; } else { // Switch to fists in multiplayer idealWeapon = 1; } #else idealWeapon = 0; #endif } break; } case INVISIBILITY: { if(gameLocal.isMultiplayer && !gameLocal.isClient) { inventory.AddPickupName("#str_00100628", "", this); } spawnArgs.GetString( "skin_invisibility", "", &skin ); powerUpSkin = declManager->FindSkin( skin ); // remove any decals from the model if ( modelDefHandle != -1 ) { gameRenderWorld->RemoveDecals( modelDefHandle ); } if ( weapon.GetEntity() ) { weapon.GetEntity()->UpdateSkin(); } /* if ( spawnArgs.GetString( "snd_invisibility", "", &sound ) ) { StartSoundShader( declManager->FindSound( sound ), SND_CHANNEL_ANY, 0, false, NULL ); } */ break; } case ADRENALINE: { #ifdef _D3XP inventory.AddPickupName("#str_00100799", "", this); #endif stamina = 100.0f; break; } case MEGAHEALTH: { if(gameLocal.isMultiplayer && !gameLocal.isClient) { inventory.AddPickupName("#str_00100629", "", this); } if ( spawnArgs.GetString( "snd_megahealth", "", &sound ) ) { StartSoundShader( declManager->FindSound( sound ), SND_CHANNEL_ANY, 0, false, NULL ); } def = gameLocal.FindEntityDef( "powerup_megahealth", false ); if ( def ) { health = def->dict.GetInt( "inv_health" ); } break; } #ifdef _D3XP case HELLTIME: { if ( spawnArgs.GetString( "snd_helltime_start", "", &sound ) ) { PostEventMS( &EV_StartSoundShader, 0, sound, SND_CHANNEL_ANY ); } if ( spawnArgs.GetString( "snd_helltime_loop", "", &sound ) ) { PostEventMS( &EV_StartSoundShader, 0, sound, SND_CHANNEL_DEMONIC ); } break; } case ENVIROSUIT: { // Turn on the envirosuit sound if ( gameSoundWorld ) { gameSoundWorld->SetEnviroSuit( true ); } // Put the helmet and lights on the player idDict args; // Light const idDict *lightDef = gameLocal.FindEntityDefDict( "envirosuit_light", false ); if ( lightDef ) { idEntity *temp; gameLocal.SpawnEntityDef( *lightDef, &temp, false ); idLight *eLight = static_cast<idLight *>(temp); eLight->GetPhysics()->SetOrigin( firstPersonViewOrigin ); eLight->UpdateVisuals(); eLight->Present(); enviroSuitLight = eLight; } break; } case ENVIROTIME: { hudPowerup = ENVIROTIME; // The HUD display bar is fixed at 60 seconds hudPowerupDuration = 60000; break; } case INVULNERABILITY: { if(gameLocal.isMultiplayer && !gameLocal.isClient) { inventory.AddPickupName("#str_00100630", "", this); } if(gameLocal.isMultiplayer) { /*if ( spawnArgs.GetString( "snd_invulnerable", "", &sound ) ) { StartSoundShader( declManager->FindSound( sound ), SND_CHANNEL_DEMONIC, 0, false, NULL ); }*/ if ( baseSkinName.Length() ) { powerUpSkin = declManager->FindSkin( baseSkinName + "_invuln" ); } } break; } /*case HASTE: { if(gameLocal.isMultiplayer && !gameLocal.isClient) { inventory.AddPickupName("#str_00100631", "", this); } if ( baseSkinName.Length() ) { powerUpSkin = declManager->FindSkin( baseSkinName + "_haste" ); } break; }*/ #endif } if ( hud ) { hud->HandleNamedEvent( "itemPickup" ); } return true; } else { gameLocal.Warning( "Player given power up %i\n which is out of range", powerup ); } return false; } /* ============== idPlayer::ClearPowerup ============== */ void idPlayer::ClearPowerup( int i ) { if ( gameLocal.isServer ) { idBitMsg msg; byte msgBuf[MAX_EVENT_PARAM_SIZE]; msg.Init( msgBuf, sizeof( msgBuf ) ); msg.WriteShort( i ); msg.WriteBits( 0, 1 ); ServerSendEvent( EVENT_POWERUP, &msg, false, -1 ); } powerUpSkin = NULL; inventory.powerups &= ~( 1 << i ); inventory.powerupEndTime[ i ] = 0; switch( i ) { case BERSERK: { if(gameLocal.isMultiplayer) { StopSound( SND_CHANNEL_DEMONIC, false ); } #ifdef _D3XP if(!gameLocal.isMultiplayer) { StopHealthRecharge(); } #endif break; } case INVISIBILITY: { if ( weapon.GetEntity() ) { weapon.GetEntity()->UpdateSkin(); } break; } #ifdef _D3XP case HELLTIME: { StopSound( SND_CHANNEL_DEMONIC, false ); break; } case ENVIROSUIT: { hudPowerup = -1; // Turn off the envirosuit sound if ( gameSoundWorld ) { gameSoundWorld->SetEnviroSuit( false ); } // Take off the helmet and lights if ( enviroSuitLight.IsValid() ) { enviroSuitLight.GetEntity()->PostEventMS( &EV_Remove, 0 ); } enviroSuitLight = NULL; break; } case INVULNERABILITY: { if(gameLocal.isMultiplayer) { StopSound( SND_CHANNEL_DEMONIC, false ); } } /*case HASTE: { if(gameLocal.isMultiplayer) { StopSound( SND_CHANNEL_DEMONIC, false ); } }*/ #endif } } /* ============== idPlayer::UpdatePowerUps ============== */ void idPlayer::UpdatePowerUps( void ) { int i; if ( !gameLocal.isClient ) { for ( i = 0; i < MAX_POWERUPS; i++ ) { #ifdef _D3XP if ( ( inventory.powerups & ( 1 << i ) ) && inventory.powerupEndTime[i] > gameLocal.time ) { switch( i ) { case ENVIROSUIT: { if ( enviroSuitLight.IsValid() ) { idAngles lightAng = firstPersonViewAxis.ToAngles(); idVec3 lightOrg = firstPersonViewOrigin; const idDict *lightDef = gameLocal.FindEntityDefDict( "envirosuit_light", false ); idVec3 enviroOffset = lightDef->GetVector( "enviro_offset" ); idVec3 enviroAngleOffset = lightDef->GetVector( "enviro_angle_offset" ); lightOrg += (enviroOffset.x * firstPersonViewAxis[0]); lightOrg += (enviroOffset.y * firstPersonViewAxis[1]); lightOrg += (enviroOffset.z * firstPersonViewAxis[2]); lightAng.pitch += enviroAngleOffset.x; lightAng.yaw += enviroAngleOffset.y; lightAng.roll += enviroAngleOffset.z; enviroSuitLight.GetEntity()->GetPhysics()->SetOrigin( lightOrg ); enviroSuitLight.GetEntity()->GetPhysics()->SetAxis( lightAng.ToMat3() ); enviroSuitLight.GetEntity()->UpdateVisuals(); enviroSuitLight.GetEntity()->Present(); } break; } default: { break; } } } #endif if ( PowerUpActive( i ) && inventory.powerupEndTime[i] <= gameLocal.time ) { ClearPowerup( i ); } } } if ( health > 0 ) { if ( powerUpSkin ) { renderEntity.customSkin = powerUpSkin; } else { renderEntity.customSkin = skin; } } if ( healthPool && gameLocal.time > nextHealthPulse && !AI_DEAD && health > 0 ) { assert( !gameLocal.isClient ); // healthPool never be set on client int amt = ( healthPool > 5 ) ? 5 : healthPool; health += amt; if ( health > inventory.maxHealth ) { health = inventory.maxHealth; healthPool = 0; } else { healthPool -= amt; } nextHealthPulse = gameLocal.time + HEALTHPULSE_TIME; healthPulse = true; } #ifndef ID_DEMO_BUILD if ( !gameLocal.inCinematic && influenceActive == 0 && g_skill.GetInteger() == 3 && gameLocal.time > nextHealthTake && !AI_DEAD && health > g_healthTakeLimit.GetInteger() ) { assert( !gameLocal.isClient ); // healthPool never be set on client #ifdef _D3XP if(!PowerUpActive(INVULNERABILITY)) { #endif health -= g_healthTakeAmt.GetInteger(); if ( health < g_healthTakeLimit.GetInteger() ) { health = g_healthTakeLimit.GetInteger(); } #ifdef _D3XP } #endif nextHealthTake = gameLocal.time + g_healthTakeTime.GetInteger() * 1000; healthTake = true; } #endif } /* =============== idPlayer::ClearPowerUps =============== */ void idPlayer::ClearPowerUps( void ) { int i; for ( i = 0; i < MAX_POWERUPS; i++ ) { if ( PowerUpActive( i ) ) { ClearPowerup( i ); } } inventory.ClearPowerUps(); #ifdef _D3XP if ( gameLocal.isMultiplayer ) { if ( enviroSuitLight.IsValid() ) { enviroSuitLight.GetEntity()->PostEventMS( &EV_Remove, 0 ); } } #endif } /* =============== idPlayer::GiveInventoryItem =============== */ bool idPlayer::GiveInventoryItem( idDict *item ) { if ( gameLocal.isMultiplayer && spectating ) { return false; } inventory.items.Append( new idDict( *item ) ); idItemInfo info; const char* itemName = item->GetString( "inv_name" ); if ( idStr::Cmpn( itemName, STRTABLE_ID, STRTABLE_ID_LENGTH ) == 0 ) { info.name = common->GetLanguageDict()->GetString( itemName ); } else { info.name = itemName; } info.icon = item->GetString( "inv_icon" ); inventory.pickupItemNames.Append( info ); if ( hud ) { hud->SetStateString( "itemicon", info.icon ); hud->HandleNamedEvent( "invPickup" ); } #ifdef _D3XP //Added to support powercells if(item->GetInt("inv_powercell") && focusUI) { //Reset the powercell count int powerCellCount = 0; for ( int j = 0; j < inventory.items.Num(); j++ ) { idDict *item = inventory.items[ j ]; if(item->GetInt("inv_powercell")) { powerCellCount++; } } focusUI->SetStateInt( "powercell_count", powerCellCount ); } #endif return true; } #ifdef _D3XP //BSM: Implementing this defined function for scripted give inventory items /* ============== idPlayer::GiveInventoryItem ============== */ bool idPlayer::GiveInventoryItem( const char *name ) { idDict args; args.Set( "classname", name ); args.Set( "owner", this->name.c_str() ); gameLocal.SpawnEntityDef( args); return true; } #endif /* ============== idPlayer::UpdateObjectiveInfo ============== */ void idPlayer::UpdateObjectiveInfo( void ) { if ( objectiveSystem == NULL ) { return; } objectiveSystem->SetStateString( "objective1", "" ); objectiveSystem->SetStateString( "objective2", "" ); objectiveSystem->SetStateString( "objective3", "" ); for ( int i = 0; i < inventory.objectiveNames.Num(); i++ ) { objectiveSystem->SetStateString( va( "objective%i", i+1 ), "1" ); objectiveSystem->SetStateString( va( "objectivetitle%i", i+1 ), inventory.objectiveNames[i].title.c_str() ); objectiveSystem->SetStateString( va( "objectivetext%i", i+1 ), inventory.objectiveNames[i].text.c_str() ); objectiveSystem->SetStateString( va( "objectiveshot%i", i+1 ), inventory.objectiveNames[i].screenshot.c_str() ); } objectiveSystem->StateChanged( gameLocal.time ); } /* =============== idPlayer::GiveObjective =============== */ void idPlayer::GiveObjective( const char *title, const char *text, const char *screenshot ) { idObjectiveInfo info; info.title = title; info.text = text; info.screenshot = screenshot; inventory.objectiveNames.Append( info ); ShowObjective( "newObjective" ); if ( hud ) { hud->HandleNamedEvent( "newObjective" ); } } /* =============== idPlayer::CompleteObjective =============== */ void idPlayer::CompleteObjective( const char *title ) { int c = inventory.objectiveNames.Num(); for ( int i = 0; i < c; i++ ) { if ( idStr::Icmp(inventory.objectiveNames[i].title, title) == 0 ) { inventory.objectiveNames.RemoveIndex( i ); break; } } ShowObjective( "newObjectiveComplete" ); if ( hud ) { hud->HandleNamedEvent( "newObjectiveComplete" ); } } /* =============== idPlayer::GiveVideo =============== */ void idPlayer::GiveVideo( const char *videoName, idDict *item ) { if ( videoName == NULL || *videoName == 0 ) { return; } inventory.videos.AddUnique( videoName ); if ( item ) { idItemInfo info; info.name = item->GetString( "inv_name" ); info.icon = item->GetString( "inv_icon" ); inventory.pickupItemNames.Append( info ); } if ( hud ) { hud->HandleNamedEvent( "videoPickup" ); } } /* =============== idPlayer::GiveSecurity =============== */ void idPlayer::GiveSecurity( const char *security ) { GetPDA()->SetSecurity( security ); if ( hud ) { hud->SetStateString( "pda_security", "1" ); hud->HandleNamedEvent( "securityPickup" ); } } /* =============== idPlayer::GiveEmail =============== */ void idPlayer::GiveEmail( const char *emailName ) { if ( emailName == NULL || *emailName == 0 ) { return; } inventory.emails.AddUnique( emailName ); GetPDA()->AddEmail( emailName ); if ( hud ) { hud->HandleNamedEvent( "emailPickup" ); } } /* =============== idPlayer::GivePDA =============== */ void idPlayer::GivePDA( const char *pdaName, idDict *item ) { if ( gameLocal.isMultiplayer && spectating ) { return; } if ( item ) { inventory.pdaSecurity.AddUnique( item->GetString( "inv_name" ) ); } if ( pdaName == NULL || *pdaName == 0 ) { pdaName = "personal"; } const idDeclPDA *pda = static_cast< const idDeclPDA* >( declManager->FindType( DECL_PDA, pdaName ) ); inventory.pdas.AddUnique( pdaName ); // Copy any videos over for ( int i = 0; i < pda->GetNumVideos(); i++ ) { const idDeclVideo *video = pda->GetVideoByIndex( i ); if ( video ) { inventory.videos.AddUnique( video->GetName() ); } } // This is kind of a hack, but it works nicely // We don't want to display the 'you got a new pda' message during a map load if ( gameLocal.GetFrameNum() > 10 ) { if ( pda && hud ) { idStr pdaName = pda->GetPdaName(); pdaName.RemoveColors(); hud->SetStateString( "pda", "1" ); hud->SetStateString( "pda_text", pdaName ); const char *sec = pda->GetSecurity(); hud->SetStateString( "pda_security", ( sec && *sec ) ? "1" : "0" ); hud->HandleNamedEvent( "pdaPickup" ); } if ( inventory.pdas.Num() == 1 ) { GetPDA()->RemoveAddedEmailsAndVideos(); if ( !objectiveSystemOpen ) { TogglePDA(); } objectiveSystem->HandleNamedEvent( "showPDATip" ); //ShowTip( spawnArgs.GetString( "text_infoTitle" ), spawnArgs.GetString( "text_firstPDA" ), true ); } if ( inventory.pdas.Num() > 1 && pda->GetNumVideos() > 0 && hud ) { hud->HandleNamedEvent( "videoPickup" ); } } } /* =============== idPlayer::FindInventoryItem =============== */ idDict *idPlayer::FindInventoryItem( const char *name ) { for ( int i = 0; i < inventory.items.Num(); i++ ) { const char *iname = inventory.items[i]->GetString( "inv_name" ); if ( iname && *iname ) { if ( idStr::Icmp( name, iname ) == 0 ) { return inventory.items[i]; } } } return NULL; } /* =============== idPlayer::RemoveInventoryItem =============== */ void idPlayer::RemoveInventoryItem( const char *name ) { //Hack for localization if(!idStr::Icmp(name, "Pwr Cell")) { name = common->GetLanguageDict()->GetString( "#str_00101056" ); } idDict *item = FindInventoryItem(name); if ( item ) { RemoveInventoryItem( item ); } } /* =============== idPlayer::RemoveInventoryItem =============== */ void idPlayer::RemoveInventoryItem( idDict *item ) { inventory.items.Remove( item ); #ifdef _D3XP //Added to support powercells if(item->GetInt("inv_powercell") && focusUI) { //Reset the powercell count int powerCellCount = 0; for ( int j = 0; j < inventory.items.Num(); j++ ) { idDict *item = inventory.items[ j ]; if(item->GetInt("inv_powercell")) { powerCellCount++; } } focusUI->SetStateInt( "powercell_count", powerCellCount ); } #endif delete item; } /* =============== idPlayer::GiveItem =============== */ void idPlayer::GiveItem( const char *itemname ) { idDict args; args.Set( "classname", itemname ); args.Set( "owner", name.c_str() ); gameLocal.SpawnEntityDef( args ); if ( hud ) { hud->HandleNamedEvent( "itemPickup" ); } } /* ================== idPlayer::SlotForWeapon ================== */ int idPlayer::SlotForWeapon( const char *weaponName ) { int i; for( i = 0; i < MAX_WEAPONS; i++ ) { const char *weap = spawnArgs.GetString( va( "def_weapon%d", i ) ); if ( !idStr::Cmp( weap, weaponName ) ) { return i; } } // not found return -1; } /* =============== idPlayer::Reload =============== */ void idPlayer::Reload( void ) { if ( gameLocal.isClient ) { return; } if ( spectating || gameLocal.inCinematic || influenceActive ) { return; } if ( weapon.GetEntity() && weapon.GetEntity()->IsLinked() ) { weapon.GetEntity()->Reload(); } } /* =============== idPlayer::NextBestWeapon =============== */ void idPlayer::NextBestWeapon( void ) { const char *weap; int w = MAX_WEAPONS; if ( gameLocal.isClient || !weaponEnabled ) { return; } while ( w > 0 ) { w--; weap = spawnArgs.GetString( va( "def_weapon%d", w ) ); #ifdef _D3XP if ( !weap[ 0 ] || ( ( inventory.weapons & ( 1 << w ) ) == 0 ) || ( !inventory.HasAmmo( weap, true, this ) ) ) { #else if ( !weap[ 0 ] || ( ( inventory.weapons & ( 1 << w ) ) == 0 ) || ( !(inventory.HasAmmo( weap )) ) ) { #endif continue; } if ( !spawnArgs.GetBool( va( "weapon%d_best", w ) ) ) { continue; } #ifdef _D3XP //Some weapons will report having ammo but the clip is empty and //will not have enough to fill the clip (i.e. Double Barrel Shotgun with 1 round left) //We need to skip these weapons because they cannot be used if(inventory.HasEmptyClipCannotRefill(weap, this)) { continue; } #endif break; } idealWeapon = w; weaponSwitchTime = gameLocal.time + WEAPON_SWITCH_DELAY; UpdateHudWeapon(); } /* =============== idPlayer::NextWeapon =============== */ void idPlayer::NextWeapon( void ) { const char *weap; int w; if ( !weaponEnabled || spectating || hiddenWeapon || gameLocal.inCinematic || gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) || health < 0 ) { return; } if ( gameLocal.isClient ) { return; } // check if we have any weapons if ( !inventory.weapons ) { return; } w = idealWeapon; while( 1 ) { w++; if ( w >= MAX_WEAPONS ) { w = 0; } weap = spawnArgs.GetString( va( "def_weapon%d", w ) ); if ( !spawnArgs.GetBool( va( "weapon%d_cycle", w ) ) ) { continue; } if ( !weap[ 0 ] ) { continue; } if ( ( inventory.weapons & ( 1 << w ) ) == 0 ) { continue; } #ifdef _D3XP if ( inventory.HasAmmo( weap, true, this ) || w == weapon_bloodstone ) { #else if ( inventory.HasAmmo( weap ) ) { #endif break; } } if ( ( w != currentWeapon ) && ( w != idealWeapon ) ) { idealWeapon = w; weaponSwitchTime = gameLocal.time + WEAPON_SWITCH_DELAY; UpdateHudWeapon(); } } /* =============== idPlayer::PrevWeapon =============== */ void idPlayer::PrevWeapon( void ) { const char *weap; int w; if ( !weaponEnabled || spectating || hiddenWeapon || gameLocal.inCinematic || gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) || health < 0 ) { return; } if ( gameLocal.isClient ) { return; } // check if we have any weapons if ( !inventory.weapons ) { return; } w = idealWeapon; while( 1 ) { w--; if ( w < 0 ) { w = MAX_WEAPONS - 1; } weap = spawnArgs.GetString( va( "def_weapon%d", w ) ); if ( !spawnArgs.GetBool( va( "weapon%d_cycle", w ) ) ) { continue; } if ( !weap[ 0 ] ) { continue; } if ( ( inventory.weapons & ( 1 << w ) ) == 0 ) { continue; } #ifdef _D3XP if ( inventory.HasAmmo( weap, true, this ) || w == weapon_bloodstone ) { #else if ( inventory.HasAmmo( weap ) ) { #endif break; } } if ( ( w != currentWeapon ) && ( w != idealWeapon ) ) { idealWeapon = w; weaponSwitchTime = gameLocal.time + WEAPON_SWITCH_DELAY; UpdateHudWeapon(); } } /* =============== idPlayer::SelectWeapon =============== */ void idPlayer::SelectWeapon( int num, bool force ) { const char *weap; if ( !weaponEnabled || spectating || gameLocal.inCinematic || health < 0 ) { return; } if ( ( num < 0 ) || ( num >= MAX_WEAPONS ) ) { return; } if ( gameLocal.isClient ) { return; } if ( ( num != weapon_pda ) && gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) ) { num = weapon_fists; hiddenWeapon ^= 1; if ( hiddenWeapon && weapon.GetEntity() ) { weapon.GetEntity()->LowerWeapon(); } else { weapon.GetEntity()->RaiseWeapon(); } } weap = spawnArgs.GetString( va( "def_weapon%d", num ) ); if ( !weap[ 0 ] ) { gameLocal.Printf( "Invalid weapon\n" ); return; } #ifdef _D3XP //Is the weapon a toggle weapon WeaponToggle_t* weaponToggle; if(weaponToggles.Get(va("weapontoggle%d", num), &weaponToggle)) { int weaponToggleIndex = 0; //Find the current Weapon in the list int currentIndex = -1; for(int i = 0; i < weaponToggle->toggleList.Num(); i++) { if(weaponToggle->toggleList[i] == idealWeapon) { currentIndex = i; break; } } if(currentIndex == -1) { //Didn't find the current weapon so select the first item weaponToggleIndex = 0; } else { //Roll to the next available item in the list weaponToggleIndex = currentIndex; weaponToggleIndex++; if(weaponToggleIndex >= weaponToggle->toggleList.Num()) { weaponToggleIndex = 0; } } for(int i = 0; i < weaponToggle->toggleList.Num(); i++) { //Is it available if(inventory.weapons & ( 1 << weaponToggle->toggleList[weaponToggleIndex])) { break; } weaponToggleIndex++; if(weaponToggleIndex >= weaponToggle->toggleList.Num()) { weaponToggleIndex = 0; } } num = weaponToggle->toggleList[weaponToggleIndex]; } #endif if ( force || ( inventory.weapons & ( 1 << num ) ) ) { #ifdef _D3XP if ( !inventory.HasAmmo( weap, true, this ) && !spawnArgs.GetBool( va( "weapon%d_allowempty", num ) ) ) { #else if ( !inventory.HasAmmo( weap ) && !spawnArgs.GetBool( va( "weapon%d_allowempty", num ) ) ) { #endif return; } if ( ( previousWeapon >= 0 ) && ( idealWeapon == num ) && ( spawnArgs.GetBool( va( "weapon%d_toggle", num ) ) ) ) { weap = spawnArgs.GetString( va( "def_weapon%d", previousWeapon ) ); #ifdef _D3XP if ( !inventory.HasAmmo( weap, true, this ) && !spawnArgs.GetBool( va( "weapon%d_allowempty", previousWeapon ) ) ) { #else if ( !inventory.HasAmmo( weap ) && !spawnArgs.GetBool( va( "weapon%d_allowempty", previousWeapon ) ) ) { #endif return; } idealWeapon = previousWeapon; } else if ( ( weapon_pda >= 0 ) && ( num == weapon_pda ) && ( inventory.pdas.Num() == 0 ) ) { ShowTip( spawnArgs.GetString( "text_infoTitle" ), spawnArgs.GetString( "text_noPDA" ), true ); return; } else { idealWeapon = num; } UpdateHudWeapon(); } } /* ================= idPlayer::DropWeapon ================= */ void idPlayer::DropWeapon( bool died ) { idVec3 forward, up; int inclip, ammoavailable; assert( !gameLocal.isClient ); if ( spectating || weaponGone || weapon.GetEntity() == NULL ) { return; } if ( ( !died && !weapon.GetEntity()->IsReady() ) || weapon.GetEntity()->IsReloading() ) { return; } // ammoavailable is how many shots we can fire // inclip is which amount is in clip right now ammoavailable = weapon.GetEntity()->AmmoAvailable(); inclip = weapon.GetEntity()->AmmoInClip(); // don't drop a grenade if we have none left if ( !idStr::Icmp( idWeapon::GetAmmoNameForNum( weapon.GetEntity()->GetAmmoType() ), "ammo_grenades" ) && ( ammoavailable - inclip <= 0 ) ) { return; } #ifdef _D3XP ammoavailable += inclip; #endif // expect an ammo setup that makes sense before doing any dropping // ammoavailable is -1 for infinite ammo, and weapons like chainsaw // a bad ammo config usually indicates a bad weapon state, so we should not drop // used to be an assertion check, but it still happens in edge cases if ( ( ammoavailable != -1 ) && ( ammoavailable < 0 ) ) { common->DPrintf( "idPlayer::DropWeapon: bad ammo setup\n" ); return; } idEntity *item = NULL; if ( died ) { // ain't gonna throw you no weapon if I'm dead item = weapon.GetEntity()->DropItem( vec3_origin, 0, WEAPON_DROP_TIME, died ); } else { viewAngles.ToVectors( &forward, NULL, &up ); item = weapon.GetEntity()->DropItem( 250.0f * forward + 150.0f * up, 500, WEAPON_DROP_TIME, died ); } if ( !item ) { return; } // set the appropriate ammo in the dropped object const idKeyValue * keyval = item->spawnArgs.MatchPrefix( "inv_ammo_" ); if ( keyval ) { item->spawnArgs.SetInt( keyval->GetKey(), ammoavailable ); idStr inclipKey = keyval->GetKey(); inclipKey.Insert( "inclip_", 4 ); #ifdef _D3XP inclipKey.Insert( va("%.2d", currentWeapon), 11); #endif item->spawnArgs.SetInt( inclipKey, inclip ); } if ( !died ) { // remove from our local inventory completely inventory.Drop( spawnArgs, item->spawnArgs.GetString( "inv_weapon" ), -1 ); weapon.GetEntity()->ResetAmmoClip(); NextWeapon(); weapon.GetEntity()->WeaponStolen(); weaponGone = true; } } /* ================= idPlayer::StealWeapon steal the target player's current weapon ================= */ void idPlayer::StealWeapon( idPlayer *player ) { assert( !gameLocal.isClient ); // make sure there's something to steal idWeapon *player_weapon = static_cast< idWeapon * >( player->weapon.GetEntity() ); if ( !player_weapon || !player_weapon->CanDrop() || weaponGone ) { return; } // steal - we need to effectively force the other player to abandon his weapon int newweap = player->currentWeapon; if ( newweap == -1 ) { return; } // might be just dropped - check inventory if ( ! ( player->inventory.weapons & ( 1 << newweap ) ) ) { return; } const char *weapon_classname = spawnArgs.GetString( va( "def_weapon%d", newweap ) ); assert( weapon_classname ); int ammoavailable = player->weapon.GetEntity()->AmmoAvailable(); int inclip = player->weapon.GetEntity()->AmmoInClip(); #ifdef _D3XP ammoavailable += inclip; #endif if ( ( ammoavailable != -1 ) && ( ammoavailable < 0 ) ) { // see DropWeapon common->DPrintf( "idPlayer::StealWeapon: bad ammo setup\n" ); // we still steal the weapon, so let's use the default ammo levels inclip = -1; const idDeclEntityDef *decl = gameLocal.FindEntityDef( weapon_classname ); assert( decl ); const idKeyValue *keypair = decl->dict.MatchPrefix( "inv_ammo_" ); assert( keypair ); ammoavailable = atoi( keypair->GetValue() ); } player->weapon.GetEntity()->WeaponStolen(); player->inventory.Drop( player->spawnArgs, NULL, newweap ); player->SelectWeapon( weapon_fists, false ); // in case the robbed player is firing rounds with a continuous fire weapon like the chaingun/plasma etc. // this will ensure the firing actually stops player->weaponGone = true; // give weapon, setup the ammo count Give( "weapon", weapon_classname ); ammo_t ammo_i = player->inventory.AmmoIndexForWeaponClass( weapon_classname, NULL ); idealWeapon = newweap; inventory.ammo[ ammo_i ] += ammoavailable; #ifndef _D3XP inventory.clip[ newweap ] = inclip; #endif } /* =============== idPlayer::ActiveGui =============== */ idUserInterface *idPlayer::ActiveGui( void ) { if ( objectiveSystemOpen ) { return objectiveSystem; } return focusUI; } /* =============== idPlayer::Weapon_Combat =============== */ void idPlayer::Weapon_Combat( void ) { if ( influenceActive || !weaponEnabled || gameLocal.inCinematic || privateCameraView ) { return; } weapon.GetEntity()->RaiseWeapon(); if ( weapon.GetEntity()->IsReloading() ) { if ( !AI_RELOAD ) { AI_RELOAD = true; SetState( "ReloadWeapon" ); UpdateScript(); } } else { AI_RELOAD = false; } if ( idealWeapon == weapon_soulcube && soulCubeProjectile.GetEntity() != NULL ) { idealWeapon = currentWeapon; } if ( idealWeapon != currentWeapon ) { if ( weaponCatchup ) { assert( gameLocal.isClient ); currentWeapon = idealWeapon; weaponGone = false; animPrefix = spawnArgs.GetString( va( "def_weapon%d", currentWeapon ) ); weapon.GetEntity()->GetWeaponDef( animPrefix, inventory.clip[ currentWeapon ] ); animPrefix.Strip( "weapon_" ); weapon.GetEntity()->NetCatchup(); const function_t *newstate = GetScriptFunction( "NetCatchup" ); if ( newstate ) { SetState( newstate ); UpdateScript(); } weaponCatchup = false; } else { if ( weapon.GetEntity()->IsReady() ) { weapon.GetEntity()->PutAway(); } if ( weapon.GetEntity()->IsHolstered() ) { assert( idealWeapon >= 0 ); assert( idealWeapon < MAX_WEAPONS ); if ( currentWeapon != weapon_pda && !spawnArgs.GetBool( va( "weapon%d_toggle", currentWeapon ) ) ) { previousWeapon = currentWeapon; } currentWeapon = idealWeapon; weaponGone = false; animPrefix = spawnArgs.GetString( va( "def_weapon%d", currentWeapon ) ); weapon.GetEntity()->GetWeaponDef( animPrefix, inventory.clip[ currentWeapon ] ); animPrefix.Strip( "weapon_" ); weapon.GetEntity()->Raise(); } } } else { weaponGone = false; // if you drop and re-get weap, you may miss the = false above if ( weapon.GetEntity()->IsHolstered() ) { if ( !weapon.GetEntity()->AmmoAvailable() ) { // weapons can switch automatically if they have no more ammo NextBestWeapon(); } else { weapon.GetEntity()->Raise(); state = GetScriptFunction( "RaiseWeapon" ); if ( state ) { SetState( state ); } } } } // check for attack AI_WEAPON_FIRED = false; if ( !influenceActive ) { if ( ( usercmd.buttons & BUTTON_ATTACK ) && !weaponGone ) { FireWeapon(); } else if ( oldButtons & BUTTON_ATTACK ) { AI_ATTACK_HELD = false; weapon.GetEntity()->EndAttack(); } } // update our ammo clip in our inventory if ( ( currentWeapon >= 0 ) && ( currentWeapon < MAX_WEAPONS ) ) { inventory.clip[ currentWeapon ] = weapon.GetEntity()->AmmoInClip(); if ( hud && ( currentWeapon == idealWeapon ) ) { UpdateHudAmmo( hud ); } } } /* =============== idPlayer::Weapon_NPC =============== */ void idPlayer::Weapon_NPC( void ) { if ( idealWeapon != currentWeapon ) { Weapon_Combat(); } StopFiring(); weapon.GetEntity()->LowerWeapon(); if ( ( usercmd.buttons & BUTTON_ATTACK ) && !( oldButtons & BUTTON_ATTACK ) ) { buttonMask |= BUTTON_ATTACK; focusCharacter->TalkTo( this ); } } /* =============== idPlayer::LowerWeapon =============== */ void idPlayer::LowerWeapon( void ) { if ( weapon.GetEntity() && !weapon.GetEntity()->IsHidden() ) { weapon.GetEntity()->LowerWeapon(); } } /* =============== idPlayer::RaiseWeapon =============== */ void idPlayer::RaiseWeapon( void ) { if ( weapon.GetEntity() && weapon.GetEntity()->IsHidden() ) { weapon.GetEntity()->RaiseWeapon(); } } /* =============== idPlayer::WeaponLoweringCallback =============== */ void idPlayer::WeaponLoweringCallback( void ) { SetState( "LowerWeapon" ); UpdateScript(); } /* =============== idPlayer::WeaponRisingCallback =============== */ void idPlayer::WeaponRisingCallback( void ) { SetState( "RaiseWeapon" ); UpdateScript(); } /* =============== idPlayer::Weapon_GUI =============== */ void idPlayer::Weapon_GUI( void ) { if ( !objectiveSystemOpen ) { if ( idealWeapon != currentWeapon ) { Weapon_Combat(); } StopFiring(); weapon.GetEntity()->LowerWeapon(); } // disable click prediction for the GUIs. handy to check the state sync does the right thing if ( gameLocal.isClient && !net_clientPredictGUI.GetBool() ) { return; } if ( ( oldButtons ^ usercmd.buttons ) & BUTTON_ATTACK ) { sysEvent_t ev; const char *command = NULL; bool updateVisuals = false; idUserInterface *ui = ActiveGui(); if ( ui ) { ev = sys->GenerateMouseButtonEvent( 1, ( usercmd.buttons & BUTTON_ATTACK ) != 0 ); command = ui->HandleEvent( &ev, gameLocal.time, &updateVisuals ); if ( updateVisuals && focusGUIent && ui == focusUI ) { focusGUIent->UpdateVisuals(); } } if ( gameLocal.isClient ) { // we predict enough, but don't want to execute commands return; } if ( focusGUIent ) { HandleGuiCommands( focusGUIent, command ); } else { HandleGuiCommands( this, command ); } } } /* =============== idPlayer::UpdateWeapon =============== */ void idPlayer::UpdateWeapon( void ) { if ( health <= 0 ) { return; } assert( !spectating ); if ( gameLocal.isClient ) { // clients need to wait till the weapon and it's world model entity // are present and synchronized ( weapon.worldModel idEntityPtr to idAnimatedEntity ) if ( !weapon.GetEntity()->IsWorldModelReady() ) { return; } } // always make sure the weapon is correctly setup before accessing it if ( !weapon.GetEntity()->IsLinked() ) { if ( idealWeapon != -1 ) { animPrefix = spawnArgs.GetString( va( "def_weapon%d", idealWeapon ) ); weapon.GetEntity()->GetWeaponDef( animPrefix, inventory.clip[ idealWeapon ] ); assert( weapon.GetEntity()->IsLinked() ); } else { return; } } if ( hiddenWeapon && tipUp && usercmd.buttons & BUTTON_ATTACK ) { HideTip(); } if ( g_dragEntity.GetBool() ) { StopFiring(); weapon.GetEntity()->LowerWeapon(); dragEntity.Update( this ); } else if ( ActiveGui() ) { // gui handling overrides weapon use Weapon_GUI(); } else if ( focusCharacter && ( focusCharacter->health > 0 ) ) { Weapon_NPC(); } else { Weapon_Combat(); } if ( hiddenWeapon ) { weapon.GetEntity()->LowerWeapon(); } // update weapon state, particles, dlights, etc weapon.GetEntity()->PresentWeapon( showWeaponViewModel ); } /* =============== idPlayer::SpectateFreeFly =============== */ void idPlayer::SpectateFreeFly( bool force ) { idPlayer *player; idVec3 newOrig; idVec3 spawn_origin; idAngles spawn_angles; player = gameLocal.GetClientByNum( spectator ); if ( force || gameLocal.time > lastSpectateChange ) { spectator = entityNumber; if ( player && player != this && !player->spectating && !player->IsInTeleport() ) { newOrig = player->GetPhysics()->GetOrigin(); if ( player->physicsObj.IsCrouching() ) { newOrig[ 2 ] += pm_crouchviewheight.GetFloat(); } else { newOrig[ 2 ] += pm_normalviewheight.GetFloat(); } newOrig[ 2 ] += SPECTATE_RAISE; idBounds b = idBounds( vec3_origin ).Expand( pm_spectatebbox.GetFloat() * 0.5f ); idVec3 start = player->GetPhysics()->GetOrigin(); start[2] += pm_spectatebbox.GetFloat() * 0.5f; trace_t t; // assuming spectate bbox is inside stand or crouch box gameLocal.clip.TraceBounds( t, start, newOrig, b, MASK_PLAYERSOLID, player ); newOrig.Lerp( start, newOrig, t.fraction ); SetOrigin( newOrig ); idAngles angle = player->viewAngles; angle[ 2 ] = 0; SetViewAngles( angle ); } else { SelectInitialSpawnPoint( spawn_origin, spawn_angles ); spawn_origin[ 2 ] += pm_normalviewheight.GetFloat(); spawn_origin[ 2 ] += SPECTATE_RAISE; SetOrigin( spawn_origin ); SetViewAngles( spawn_angles ); } lastSpectateChange = gameLocal.time + 500; } } /* =============== idPlayer::SpectateCycle =============== */ void idPlayer::SpectateCycle( void ) { idPlayer *player; if ( gameLocal.time > lastSpectateChange ) { int latchedSpectator = spectator; spectator = gameLocal.GetNextClientNum( spectator ); player = gameLocal.GetClientByNum( spectator ); assert( player ); // never call here when the current spectator is wrong // ignore other spectators while ( latchedSpectator != spectator && player->spectating ) { spectator = gameLocal.GetNextClientNum( spectator ); player = gameLocal.GetClientByNum( spectator ); } lastSpectateChange = gameLocal.time + 500; } } /* =============== idPlayer::UpdateSpectating =============== */ void idPlayer::UpdateSpectating( void ) { assert( spectating ); assert( !gameLocal.isClient ); assert( IsHidden() ); idPlayer *player; if ( !gameLocal.isMultiplayer ) { return; } player = gameLocal.GetClientByNum( spectator ); if ( !player || ( player->spectating && player != this ) ) { SpectateFreeFly( true ); } else if ( usercmd.upmove > 0 ) { SpectateFreeFly( false ); } else if ( usercmd.buttons & BUTTON_ATTACK ) { SpectateCycle(); } } /* =============== idPlayer::HandleSingleGuiCommand =============== */ bool idPlayer::HandleSingleGuiCommand( idEntity *entityGui, idLexer *src ) { idToken token; if ( !src->ReadToken( &token ) ) { return false; } if ( token == ";" ) { return false; } if ( token.Icmp( "addhealth" ) == 0 ) { if ( entityGui && health < 100 ) { int _health = entityGui->spawnArgs.GetInt( "gui_parm1" ); int amt = ( _health >= HEALTH_PER_DOSE ) ? HEALTH_PER_DOSE : _health; _health -= amt; entityGui->spawnArgs.SetInt( "gui_parm1", _health ); if ( entityGui->GetRenderEntity() && entityGui->GetRenderEntity()->gui[ 0 ] ) { entityGui->GetRenderEntity()->gui[ 0 ]->SetStateInt( "gui_parm1", _health ); } health += amt; if ( health > 100 ) { health = 100; } } return true; } if ( token.Icmp( "ready" ) == 0 ) { PerformImpulse( IMPULSE_17 ); return true; } if ( token.Icmp( "updatepda" ) == 0 ) { UpdatePDAInfo( true ); return true; } if ( token.Icmp( "updatepda2" ) == 0 ) { UpdatePDAInfo( false ); return true; } if ( token.Icmp( "stoppdavideo" ) == 0 ) { if ( objectiveSystem && objectiveSystemOpen && pdaVideoWave.Length() > 0 ) { StopSound( SND_CHANNEL_PDA, false ); } return true; } if ( token.Icmp( "close" ) == 0 ) { if ( objectiveSystem && objectiveSystemOpen ) { TogglePDA(); } } if ( token.Icmp( "playpdavideo" ) == 0 ) { if ( objectiveSystem && objectiveSystemOpen && pdaVideo.Length() > 0 ) { const idMaterial *mat = declManager->FindMaterial( pdaVideo ); if ( mat ) { int c = mat->GetNumStages(); for ( int i = 0; i < c; i++ ) { const shaderStage_t *stage = mat->GetStage(i); if ( stage && stage->texture.cinematic ) { stage->texture.cinematic->ResetTime( gameLocal.time ); } } if ( pdaVideoWave.Length() ) { const idSoundShader *shader = declManager->FindSound( pdaVideoWave ); StartSoundShader( shader, SND_CHANNEL_PDA, 0, false, NULL ); } } } } if ( token.Icmp( "playpdaaudio" ) == 0 ) { if ( objectiveSystem && objectiveSystemOpen && pdaAudio.Length() > 0 ) { const idSoundShader *shader = declManager->FindSound( pdaAudio ); int ms; StartSoundShader( shader, SND_CHANNEL_PDA, 0, false, &ms ); StartAudioLog(); CancelEvents( &EV_Player_StopAudioLog ); PostEventMS( &EV_Player_StopAudioLog, ms + 150 ); } return true; } if ( token.Icmp( "stoppdaaudio" ) == 0 ) { if ( objectiveSystem && objectiveSystemOpen && pdaAudio.Length() > 0 ) { // idSoundShader *shader = declManager->FindSound( pdaAudio ); StopAudioLog(); StopSound( SND_CHANNEL_PDA, false ); } return true; } src->UnreadToken( &token ); return false; } /* ============== idPlayer::Collide ============== */ bool idPlayer::Collide( const trace_t &collision, const idVec3 &velocity ) { idEntity *other; if ( gameLocal.isClient ) { return false; } other = gameLocal.entities[ collision.c.entityNum ]; if ( other ) { other->Signal( SIG_TOUCH ); if ( !spectating ) { if ( other->RespondsTo( EV_Touch ) ) { other->ProcessEvent( &EV_Touch, this, &collision ); } } else { if ( other->RespondsTo( EV_SpectatorTouch ) ) { other->ProcessEvent( &EV_SpectatorTouch, this, &collision ); } } } return false; } /* ================ idPlayer::UpdateLocation Searches nearby locations ================ */ void idPlayer::UpdateLocation( void ) { if ( hud ) { idLocationEntity *locationEntity = gameLocal.LocationForPoint( GetEyePosition() ); if ( locationEntity ) { hud->SetStateString( "location", locationEntity->GetLocation() ); } else { hud->SetStateString( "location", common->GetLanguageDict()->GetString( "#str_02911" ) ); } } } /* ================ idPlayer::ClearFocus Clears the focus cursor ================ */ void idPlayer::ClearFocus( void ) { focusCharacter = NULL; focusGUIent = NULL; focusUI = NULL; focusVehicle = NULL; talkCursor = 0; } /* ================ idPlayer::UpdateFocus Searches nearby entities for interactive guis, possibly making one of them the focus and sending it a mouse move event ================ */ void idPlayer::UpdateFocus( void ) { idClipModel *clipModelList[ MAX_GENTITIES ]; idClipModel *clip; int listedClipModels; idEntity *oldFocus; idEntity *ent; idUserInterface *oldUI; idAI *oldChar; int oldTalkCursor; int i, j; idVec3 start, end; bool allowFocus; const char *command; trace_t trace; guiPoint_t pt; const idKeyValue *kv; sysEvent_t ev; idUserInterface *ui; if ( gameLocal.inCinematic ) { return; } // only update the focus character when attack button isn't pressed so players // can still chainsaw NPC's if ( gameLocal.isMultiplayer || ( !focusCharacter && ( usercmd.buttons & BUTTON_ATTACK ) ) ) { allowFocus = false; } else { allowFocus = true; } oldFocus = focusGUIent; oldUI = focusUI; oldChar = focusCharacter; oldTalkCursor = talkCursor; if ( focusTime <= gameLocal.time ) { ClearFocus(); } // don't let spectators interact with GUIs if ( spectating ) { return; } start = GetEyePosition(); end = start + viewAngles.ToForward() * 80.0f; // player identification -> names to the hud if ( gameLocal.isMultiplayer && entityNumber == gameLocal.localClientNum ) { idVec3 end = start + viewAngles.ToForward() * 768.0f; gameLocal.clip.TracePoint( trace, start, end, MASK_SHOT_BOUNDINGBOX, this ); int iclient = -1; if ( ( trace.fraction < 1.0f ) && ( trace.c.entityNum < MAX_CLIENTS ) ) { iclient = trace.c.entityNum; } if ( MPAim != iclient ) { lastMPAim = MPAim; MPAim = iclient; lastMPAimTime = gameLocal.realClientTime; } } idBounds bounds( start ); bounds.AddPoint( end ); listedClipModels = gameLocal.clip.ClipModelsTouchingBounds( bounds, -1, clipModelList, MAX_GENTITIES ); // no pretense at sorting here, just assume that there will only be one active // gui within range along the trace for ( i = 0; i < listedClipModels; i++ ) { clip = clipModelList[ i ]; ent = clip->GetEntity(); if ( ent->IsHidden() ) { continue; } if ( allowFocus ) { if ( ent->IsType( idAFAttachment::Type ) ) { idEntity *body = static_cast<idAFAttachment *>( ent )->GetBody(); if ( body && body->IsType( idAI::Type ) && ( static_cast<idAI *>( body )->GetTalkState() >= TALK_OK ) ) { gameLocal.clip.TracePoint( trace, start, end, MASK_SHOT_RENDERMODEL, this ); if ( ( trace.fraction < 1.0f ) && ( trace.c.entityNum == ent->entityNumber ) ) { ClearFocus(); focusCharacter = static_cast<idAI *>( body ); talkCursor = 1; focusTime = gameLocal.time + FOCUS_TIME; break; } } continue; } if ( ent->IsType( idAI::Type ) ) { if ( static_cast<idAI *>( ent )->GetTalkState() >= TALK_OK ) { gameLocal.clip.TracePoint( trace, start, end, MASK_SHOT_RENDERMODEL, this ); if ( ( trace.fraction < 1.0f ) && ( trace.c.entityNum == ent->entityNumber ) ) { ClearFocus(); focusCharacter = static_cast<idAI *>( ent ); talkCursor = 1; focusTime = gameLocal.time + FOCUS_TIME; break; } } continue; } if ( ent->IsType( idAFEntity_Vehicle::Type ) ) { gameLocal.clip.TracePoint( trace, start, end, MASK_SHOT_RENDERMODEL, this ); if ( ( trace.fraction < 1.0f ) && ( trace.c.entityNum == ent->entityNumber ) ) { ClearFocus(); focusVehicle = static_cast<idAFEntity_Vehicle *>( ent ); focusTime = gameLocal.time + FOCUS_TIME; break; } continue; } } if ( !ent->GetRenderEntity() || !ent->GetRenderEntity()->gui[ 0 ] || !ent->GetRenderEntity()->gui[ 0 ]->IsInteractive() ) { continue; } if ( ent->spawnArgs.GetBool( "inv_item" ) ) { // don't allow guis on pickup items focus continue; } pt = gameRenderWorld->GuiTrace( ent->GetModelDefHandle(), start, end ); if ( pt.x != -1 ) { // we have a hit renderEntity_t *focusGUIrenderEntity = ent->GetRenderEntity(); if ( !focusGUIrenderEntity ) { continue; } if ( pt.guiId == 1 ) { ui = focusGUIrenderEntity->gui[ 0 ]; } else if ( pt.guiId == 2 ) { ui = focusGUIrenderEntity->gui[ 1 ]; } else { ui = focusGUIrenderEntity->gui[ 2 ]; } if ( ui == NULL ) { continue; } ClearFocus(); focusGUIent = ent; focusUI = ui; if ( oldFocus != ent ) { // new activation // going to see if we have anything in inventory a gui might be interested in // need to enumerate inventory items focusUI->SetStateInt( "inv_count", inventory.items.Num() ); for ( j = 0; j < inventory.items.Num(); j++ ) { idDict *item = inventory.items[ j ]; const char *iname = item->GetString( "inv_name" ); const char *iicon = item->GetString( "inv_icon" ); const char *itext = item->GetString( "inv_text" ); focusUI->SetStateString( va( "inv_name_%i", j), iname ); focusUI->SetStateString( va( "inv_icon_%i", j), iicon ); focusUI->SetStateString( va( "inv_text_%i", j), itext ); kv = item->MatchPrefix("inv_id", NULL); if ( kv ) { focusUI->SetStateString( va( "inv_id_%i", j ), kv->GetValue() ); } focusUI->SetStateInt( iname, 1 ); } for( j = 0; j < inventory.pdaSecurity.Num(); j++ ) { const char *p = inventory.pdaSecurity[ j ]; if ( p && *p ) { focusUI->SetStateInt( p, 1 ); } } #ifdef _D3XP //BSM: Added for powercells int powerCellCount = 0; for ( j = 0; j < inventory.items.Num(); j++ ) { idDict *item = inventory.items[ j ]; if(item->GetInt("inv_powercell")) { powerCellCount++; } } focusUI->SetStateInt( "powercell_count", powerCellCount ); #endif int staminapercentage = ( int )( 100.0f * stamina / pm_stamina.GetFloat() ); focusUI->SetStateString( "player_health", va("%i", health ) ); focusUI->SetStateString( "player_stamina", va( "%i%%", staminapercentage ) ); focusUI->SetStateString( "player_armor", va( "%i%%", inventory.armor ) ); kv = focusGUIent->spawnArgs.MatchPrefix( "gui_parm", NULL ); while ( kv ) { focusUI->SetStateString( kv->GetKey(), kv->GetValue() ); kv = focusGUIent->spawnArgs.MatchPrefix( "gui_parm", kv ); } } // clamp the mouse to the corner ev = sys->GenerateMouseMoveEvent( -2000, -2000 ); command = focusUI->HandleEvent( &ev, gameLocal.time ); HandleGuiCommands( focusGUIent, command ); // move to an absolute position ev = sys->GenerateMouseMoveEvent( pt.x * SCREEN_WIDTH, pt.y * SCREEN_HEIGHT ); command = focusUI->HandleEvent( &ev, gameLocal.time ); HandleGuiCommands( focusGUIent, command ); focusTime = gameLocal.time + FOCUS_GUI_TIME; break; } } if ( focusGUIent && focusUI ) { if ( !oldFocus || oldFocus != focusGUIent ) { command = focusUI->Activate( true, gameLocal.time ); HandleGuiCommands( focusGUIent, command ); StartSound( "snd_guienter", SND_CHANNEL_ANY, 0, false, NULL ); // HideTip(); // HideObjective(); } } else if ( oldFocus && oldUI ) { command = oldUI->Activate( false, gameLocal.time ); HandleGuiCommands( oldFocus, command ); StartSound( "snd_guiexit", SND_CHANNEL_ANY, 0, false, NULL ); } if ( cursor && ( oldTalkCursor != talkCursor ) ) { cursor->SetStateInt( "talkcursor", talkCursor ); } if ( oldChar != focusCharacter && hud ) { if ( focusCharacter ) { hud->SetStateString( "npc", focusCharacter->spawnArgs.GetString( "npc_name", "Joe" ) ); #ifdef _D3XP //Use to code to update the npc action string to fix bug 1159 hud->SetStateString( "npc_action", common->GetLanguageDict()->GetString( "#str_02036" )); #endif hud->HandleNamedEvent( "showNPC" ); // HideTip(); // HideObjective(); } else { hud->SetStateString( "npc", "" ); #ifdef _D3XP hud->SetStateString( "npc_action", "" ); #endif hud->HandleNamedEvent( "hideNPC" ); } } } /* ================= idPlayer::CrashLand Check for hard landings that generate sound events ================= */ void idPlayer::CrashLand( const idVec3 &oldOrigin, const idVec3 &oldVelocity ) { idVec3 origin, velocity; idVec3 gravityVector, gravityNormal; float delta; float hardDelta, fatalDelta; float dist; float vel, acc; float t; float a, b, c, den; waterLevel_t waterLevel; bool noDamage; AI_SOFTLANDING = false; AI_HARDLANDING = false; // if the player is not on the ground if ( !physicsObj.HasGroundContacts() ) { return; } gravityNormal = physicsObj.GetGravityNormal(); // if the player wasn't going down if ( ( oldVelocity * -gravityNormal ) >= 0.0f ) { return; } waterLevel = physicsObj.GetWaterLevel(); // never take falling damage if completely underwater if ( waterLevel == WATERLEVEL_HEAD ) { return; } // no falling damage if touching a nodamage surface noDamage = false; for ( int i = 0; i < physicsObj.GetNumContacts(); i++ ) { const contactInfo_t &contact = physicsObj.GetContact( i ); if ( contact.material->GetSurfaceFlags() & SURF_NODAMAGE ) { noDamage = true; StartSound( "snd_land_hard", SND_CHANNEL_ANY, 0, false, NULL ); break; } } origin = GetPhysics()->GetOrigin(); gravityVector = physicsObj.GetGravity(); // calculate the exact velocity on landing dist = ( origin - oldOrigin ) * -gravityNormal; vel = oldVelocity * -gravityNormal; acc = -gravityVector.Length(); a = acc / 2.0f; b = vel; c = -dist; den = b * b - 4.0f * a * c; if ( den < 0 ) { return; } t = ( -b - idMath::Sqrt( den ) ) / ( 2.0f * a ); delta = vel + t * acc; delta = delta * delta * 0.0001; // reduce falling damage if there is standing water if ( waterLevel == WATERLEVEL_WAIST ) { delta *= 0.25f; } if ( waterLevel == WATERLEVEL_FEET ) { delta *= 0.5f; } if ( delta < 1.0f ) { return; } // allow falling a bit further for multiplayer if ( gameLocal.isMultiplayer ) { fatalDelta = 75.0f; hardDelta = 50.0f; } else { fatalDelta = 65.0f; hardDelta = 45.0f; } if ( delta > fatalDelta ) { AI_HARDLANDING = true; landChange = -32; landTime = gameLocal.time; if ( !noDamage ) { pain_debounce_time = gameLocal.time + pain_delay + 1; // ignore pain since we'll play our landing anim Damage( NULL, NULL, idVec3( 0, 0, -1 ), "damage_fatalfall", 1.0f, 0 ); } } else if ( delta > hardDelta ) { AI_HARDLANDING = true; landChange = -24; landTime = gameLocal.time; if ( !noDamage ) { pain_debounce_time = gameLocal.time + pain_delay + 1; // ignore pain since we'll play our landing anim Damage( NULL, NULL, idVec3( 0, 0, -1 ), "damage_hardfall", 1.0f, 0 ); } } else if ( delta > 30 ) { AI_HARDLANDING = true; landChange = -16; landTime = gameLocal.time; if ( !noDamage ) { pain_debounce_time = gameLocal.time + pain_delay + 1; // ignore pain since we'll play our landing anim Damage( NULL, NULL, idVec3( 0, 0, -1 ), "damage_softfall", 1.0f, 0 ); } } else if ( delta > 7 ) { AI_SOFTLANDING = true; landChange = -8; landTime = gameLocal.time; } else if ( delta > 3 ) { // just walk on } } /* =============== idPlayer::BobCycle =============== */ void idPlayer::BobCycle( const idVec3 &pushVelocity ) { float bobmove; int old, deltaTime; idVec3 vel, gravityDir, velocity; idMat3 viewaxis; float bob; float delta; float speed; float f; // // calculate speed and cycle to be used for // all cyclic walking effects // velocity = physicsObj.GetLinearVelocity() - pushVelocity; gravityDir = physicsObj.GetGravityNormal(); vel = velocity - ( velocity * gravityDir ) * gravityDir; xyspeed = vel.LengthFast(); // do not evaluate the bob for other clients // when doing a spectate follow, don't do any weapon bobbing if ( gameLocal.isClient && entityNumber != gameLocal.localClientNum ) { viewBobAngles.Zero(); viewBob.Zero(); return; } if ( !physicsObj.HasGroundContacts() || influenceActive == INFLUENCE_LEVEL2 || ( gameLocal.isMultiplayer && spectating ) ) { // airborne bobCycle = 0; bobFoot = 0; bobfracsin = 0; } else if ( ( !usercmd.forwardmove && !usercmd.rightmove ) || ( xyspeed <= MIN_BOB_SPEED ) ) { // start at beginning of cycle again bobCycle = 0; bobFoot = 0; bobfracsin = 0; } else { if ( physicsObj.IsCrouching() ) { bobmove = pm_crouchbob.GetFloat(); // ducked characters never play footsteps } else { // vary the bobbing based on the speed of the player bobmove = pm_walkbob.GetFloat() * ( 1.0f - bobFrac ) + pm_runbob.GetFloat() * bobFrac; } // check for footstep / splash sounds old = bobCycle; bobCycle = (int)( old + bobmove * gameLocal.msec ) & 255; bobFoot = ( bobCycle & 128 ) >> 7; bobfracsin = idMath::Fabs( sin( ( bobCycle & 127 ) / 127.0 * idMath::PI ) ); } // calculate angles for view bobbing viewBobAngles.Zero(); viewaxis = viewAngles.ToMat3() * physicsObj.GetGravityAxis(); // add angles based on velocity delta = velocity * viewaxis[0]; viewBobAngles.pitch += delta * pm_runpitch.GetFloat(); delta = velocity * viewaxis[1]; viewBobAngles.roll -= delta * pm_runroll.GetFloat(); // add angles based on bob // make sure the bob is visible even at low speeds speed = xyspeed > 200 ? xyspeed : 200; delta = bobfracsin * pm_bobpitch.GetFloat() * speed; if ( physicsObj.IsCrouching() ) { delta *= 3; // crouching } viewBobAngles.pitch += delta; delta = bobfracsin * pm_bobroll.GetFloat() * speed; if ( physicsObj.IsCrouching() ) { delta *= 3; // crouching accentuates roll } if ( bobFoot & 1 ) { delta = -delta; } viewBobAngles.roll += delta; // calculate position for view bobbing viewBob.Zero(); if ( physicsObj.HasSteppedUp() ) { // check for stepping up before a previous step is completed deltaTime = gameLocal.time - stepUpTime; if ( deltaTime < STEPUP_TIME ) { stepUpDelta = stepUpDelta * ( STEPUP_TIME - deltaTime ) / STEPUP_TIME + physicsObj.GetStepUp(); } else { stepUpDelta = physicsObj.GetStepUp(); } if ( stepUpDelta > 2.0f * pm_stepsize.GetFloat() ) { stepUpDelta = 2.0f * pm_stepsize.GetFloat(); } stepUpTime = gameLocal.time; } idVec3 gravity = physicsObj.GetGravityNormal(); // if the player stepped up recently deltaTime = gameLocal.time - stepUpTime; if ( deltaTime < STEPUP_TIME ) { viewBob += gravity * ( stepUpDelta * ( STEPUP_TIME - deltaTime ) / STEPUP_TIME ); } // add bob height after any movement smoothing bob = bobfracsin * xyspeed * pm_bobup.GetFloat(); if ( bob > 6 ) { bob = 6; } viewBob[2] += bob; // add fall height delta = gameLocal.time - landTime; if ( delta < LAND_DEFLECT_TIME ) { f = delta / LAND_DEFLECT_TIME; viewBob -= gravity * ( landChange * f ); } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { delta -= LAND_DEFLECT_TIME; f = 1.0 - ( delta / LAND_RETURN_TIME ); viewBob -= gravity * ( landChange * f ); } } /* ================ idPlayer::UpdateDeltaViewAngles ================ */ void idPlayer::UpdateDeltaViewAngles( const idAngles &angles ) { // set the delta angle idAngles delta; for( int i = 0; i < 3; i++ ) { delta[ i ] = angles[ i ] - SHORT2ANGLE( usercmd.angles[ i ] ); } SetDeltaViewAngles( delta ); } /* ================ idPlayer::SetViewAngles ================ */ void idPlayer::SetViewAngles( const idAngles &angles ) { UpdateDeltaViewAngles( angles ); viewAngles = angles; } /* ================ idPlayer::UpdateViewAngles ================ */ void idPlayer::UpdateViewAngles( void ) { int i; idAngles delta; if ( !noclip && ( gameLocal.inCinematic || privateCameraView || gameLocal.GetCamera() || influenceActive == INFLUENCE_LEVEL2 || objectiveSystemOpen ) ) { // no view changes at all, but we still want to update the deltas or else when // we get out of this mode, our view will snap to a kind of random angle UpdateDeltaViewAngles( viewAngles ); return; } // if dead if ( health <= 0 ) { if ( pm_thirdPersonDeath.GetBool() ) { viewAngles.roll = 0.0f; viewAngles.pitch = 30.0f; } else { viewAngles.roll = 40.0f; viewAngles.pitch = -15.0f; } return; } // circularly clamp the angles with deltas for ( i = 0; i < 3; i++ ) { cmdAngles[i] = SHORT2ANGLE( usercmd.angles[i] ); if ( influenceActive == INFLUENCE_LEVEL3 ) { viewAngles[i] += idMath::ClampFloat( -1.0f, 1.0f, idMath::AngleDelta( idMath::AngleNormalize180( SHORT2ANGLE( usercmd.angles[i]) + deltaViewAngles[i] ) , viewAngles[i] ) ); } else { viewAngles[i] = idMath::AngleNormalize180( SHORT2ANGLE( usercmd.angles[i]) + deltaViewAngles[i] ); } } if ( !centerView.IsDone( gameLocal.time ) ) { viewAngles.pitch = centerView.GetCurrentValue(gameLocal.time); } // clamp the pitch if ( noclip ) { if ( viewAngles.pitch > 89.0f ) { // don't let the player look down more than 89 degrees while noclipping viewAngles.pitch = 89.0f; } else if ( viewAngles.pitch < -89.0f ) { // don't let the player look up more than 89 degrees while noclipping viewAngles.pitch = -89.0f; } #ifdef _D3XP } else if ( mountedObject ) { int yaw_min, yaw_max, varc; mountedObject->GetAngleRestrictions( yaw_min, yaw_max, varc ); if ( yaw_min < yaw_max ) { viewAngles.yaw = idMath::ClampFloat( yaw_min, yaw_max, viewAngles.yaw ); } else { if ( viewAngles.yaw < 0 ) { viewAngles.yaw = idMath::ClampFloat( -180.f, yaw_max, viewAngles.yaw ); } else { viewAngles.yaw = idMath::ClampFloat( yaw_min, 180.f, viewAngles.yaw ); } } viewAngles.pitch = idMath::ClampFloat( -varc, varc, viewAngles.pitch ); #endif } else { if ( viewAngles.pitch > pm_maxviewpitch.GetFloat() ) { // don't let the player look down enough to see the shadow of his (non-existant) feet viewAngles.pitch = pm_maxviewpitch.GetFloat(); } else if ( viewAngles.pitch < pm_minviewpitch.GetFloat() ) { // don't let the player look up more than 89 degrees viewAngles.pitch = pm_minviewpitch.GetFloat(); } } UpdateDeltaViewAngles( viewAngles ); // orient the model towards the direction we're looking SetAngles( idAngles( 0, viewAngles.yaw, 0 ) ); // save in the log for analyzing weapon angle offsets loggedViewAngles[ gameLocal.framenum & (NUM_LOGGED_VIEW_ANGLES-1) ] = viewAngles; } /* ============== idPlayer::AdjustHeartRate Player heartrate works as follows DEF_HEARTRATE is resting heartrate Taking damage when health is above 75 adjusts heart rate by 1 beat per second Taking damage when health is below 75 adjusts heart rate by 5 beats per second Maximum heartrate from damage is MAX_HEARTRATE Firing a weapon adds 1 beat per second up to a maximum of COMBAT_HEARTRATE Being at less than 25% stamina adds 5 beats per second up to ZEROSTAMINA_HEARTRATE All heartrates are target rates.. the heart rate will start falling as soon as there have been no adjustments for 5 seconds Once it starts falling it always tries to get to DEF_HEARTRATE The exception to the above rule is upon death at which point the rate is set to DYING_HEARTRATE and starts falling immediately to zero Heart rate volumes go from zero ( -40 db for DEF_HEARTRATE to 5 db for MAX_HEARTRATE ) the volume is scaled linearly based on the actual rate Exception to the above rule is once the player is dead, the dying heart rate starts at either the current volume if it is audible or -10db and scales to 8db on the last few beats ============== */ void idPlayer::AdjustHeartRate( int target, float timeInSecs, float delay, bool force ) { if ( heartInfo.GetEndValue() == target ) { return; } if ( AI_DEAD && !force ) { return; } lastHeartAdjust = gameLocal.time; heartInfo.Init( gameLocal.time + delay * 1000, timeInSecs * 1000, heartRate, target ); } /* ============== idPlayer::GetBaseHeartRate ============== */ int idPlayer::GetBaseHeartRate( void ) { int base = idMath::FtoiFast( ( BASE_HEARTRATE + LOWHEALTH_HEARTRATE_ADJ ) - ( (float)health / 100.0f ) * LOWHEALTH_HEARTRATE_ADJ ); int rate = idMath::FtoiFast( base + ( ZEROSTAMINA_HEARTRATE - base ) * ( 1.0f - stamina / pm_stamina.GetFloat() ) ); int diff = ( lastDmgTime ) ? gameLocal.time - lastDmgTime : 99999; rate += ( diff < 5000 ) ? ( diff < 2500 ) ? ( diff < 1000 ) ? 15 : 10 : 5 : 0; return rate; } /* ============== idPlayer::SetCurrentHeartRate ============== */ void idPlayer::SetCurrentHeartRate( void ) { int base = idMath::FtoiFast( ( BASE_HEARTRATE + LOWHEALTH_HEARTRATE_ADJ ) - ( (float) health / 100.0f ) * LOWHEALTH_HEARTRATE_ADJ ); if ( PowerUpActive( ADRENALINE )) { heartRate = 135; } else { heartRate = idMath::FtoiFast( heartInfo.GetCurrentValue( gameLocal.time ) ); int currentRate = GetBaseHeartRate(); if ( health >= 0 && gameLocal.time > lastHeartAdjust + 2500 ) { AdjustHeartRate( currentRate, 2.5f, 0.0f, false ); } } int bps = idMath::FtoiFast( 60.0f / heartRate * 1000.0f ); if ( gameLocal.time - lastHeartBeat > bps ) { int dmgVol = DMG_VOLUME; int deathVol = DEATH_VOLUME; int zeroVol = ZERO_VOLUME; float pct = 0.0; if ( heartRate > BASE_HEARTRATE && health > 0 ) { pct = (float)(heartRate - base) / (MAX_HEARTRATE - base); pct *= ((float)dmgVol - (float)zeroVol); } else if ( health <= 0 ) { pct = (float)(heartRate - DYING_HEARTRATE) / (BASE_HEARTRATE - DYING_HEARTRATE); if ( pct > 1.0f ) { pct = 1.0f; } else if (pct < 0.0f) { pct = 0.0f; } pct *= ((float)deathVol - (float)zeroVol); } pct += (float)zeroVol; if ( pct != zeroVol ) { StartSound( "snd_heartbeat", SND_CHANNEL_HEART, SSF_PRIVATE_SOUND, false, NULL ); // modify just this channel to a custom volume soundShaderParms_t parms; memset( &parms, 0, sizeof( parms ) ); parms.volume = pct; refSound.referenceSound->ModifySound( SND_CHANNEL_HEART, &parms ); } lastHeartBeat = gameLocal.time; } } /* ============== idPlayer::UpdateAir ============== */ void idPlayer::UpdateAir( void ) { if ( health <= 0 ) { return; } // see if the player is connected to the info_vacuum bool newAirless = false; if ( gameLocal.vacuumAreaNum != -1 ) { int num = GetNumPVSAreas(); if ( num > 0 ) { int areaNum; // if the player box spans multiple areas, get the area from the origin point instead, // otherwise a rotating player box may poke into an outside area if ( num == 1 ) { const int *pvsAreas = GetPVSAreas(); areaNum = pvsAreas[0]; } else { areaNum = gameRenderWorld->PointInArea( this->GetPhysics()->GetOrigin() ); } newAirless = gameRenderWorld->AreasAreConnected( gameLocal.vacuumAreaNum, areaNum, PS_BLOCK_AIR ); } } #ifdef _D3XP if ( PowerUpActive( ENVIROTIME ) ) { newAirless = false; } #endif if ( newAirless ) { if ( !airless ) { StartSound( "snd_decompress", SND_CHANNEL_ANY, SSF_GLOBAL, false, NULL ); StartSound( "snd_noAir", SND_CHANNEL_BODY2, 0, false, NULL ); if ( hud ) { hud->HandleNamedEvent( "noAir" ); } } airTics--; if ( airTics < 0 ) { airTics = 0; // check for damage const idDict *damageDef = gameLocal.FindEntityDefDict( "damage_noair", false ); int dmgTiming = 1000 * ((damageDef) ? damageDef->GetFloat( "delay", "3.0" ) : 3.0f ); if ( gameLocal.time > lastAirDamage + dmgTiming ) { Damage( NULL, NULL, vec3_origin, "damage_noair", 1.0f, 0 ); lastAirDamage = gameLocal.time; } } } else { if ( airless ) { StartSound( "snd_recompress", SND_CHANNEL_ANY, SSF_GLOBAL, false, NULL ); StopSound( SND_CHANNEL_BODY2, false ); if ( hud ) { hud->HandleNamedEvent( "Air" ); } } airTics+=2; // regain twice as fast as lose if ( airTics > pm_airTics.GetInteger() ) { airTics = pm_airTics.GetInteger(); } } airless = newAirless; if ( hud ) { hud->SetStateInt( "player_air", 100 * airTics / pm_airTics.GetInteger() ); } } void idPlayer::UpdatePowerupHud() { if ( health <= 0 ) { return; } if(lastHudPowerup != hudPowerup) { if(hudPowerup == -1) { //The powerup hud should be turned off if ( hud ) { hud->HandleNamedEvent( "noPowerup" ); } } else { //Turn the pwoerup hud on if ( hud ) { hud->HandleNamedEvent( "Powerup" ); } } lastHudPowerup = hudPowerup; } if(hudPowerup != -1) { if(PowerUpActive(hudPowerup)) { int remaining = inventory.powerupEndTime[ hudPowerup ] - gameLocal.time; int filledbar = idMath::ClampInt( 0, hudPowerupDuration, remaining ); if ( hud ) { hud->SetStateInt( "player_powerup", 100 * filledbar / hudPowerupDuration ); hud->SetStateInt( "player_poweruptime", remaining / 1000 ); } } } } /* ============== idPlayer::AddGuiPDAData ============== */ int idPlayer::AddGuiPDAData( const declType_t dataType, const char *listName, const idDeclPDA *src, idUserInterface *gui ) { int c, i; idStr work; if ( dataType == DECL_EMAIL ) { c = src->GetNumEmails(); for ( i = 0; i < c; i++ ) { const idDeclEmail *email = src->GetEmailByIndex( i ); if ( email == NULL ) { work = va( "-\tEmail %d not found\t-", i ); } else { work = email->GetFrom(); work += "\t"; work += email->GetSubject(); work += "\t"; work += email->GetDate(); } gui->SetStateString( va( "%s_item_%i", listName, i ), work ); } return c; } else if ( dataType == DECL_AUDIO ) { c = src->GetNumAudios(); for ( i = 0; i < c; i++ ) { const idDeclAudio *audio = src->GetAudioByIndex( i ); if ( audio == NULL ) { work = va( "Audio Log %d not found", i ); } else { work = audio->GetAudioName(); } gui->SetStateString( va( "%s_item_%i", listName, i ), work ); } return c; } else if ( dataType == DECL_VIDEO ) { c = inventory.videos.Num(); for ( i = 0; i < c; i++ ) { const idDeclVideo *video = GetVideo( i ); if ( video == NULL ) { work = va( "Video CD %s not found", inventory.videos[i].c_str() ); } else { work = video->GetVideoName(); } gui->SetStateString( va( "%s_item_%i", listName, i ), work ); } return c; } return 0; } /* ============== idPlayer::GetPDA ============== */ const idDeclPDA *idPlayer::GetPDA( void ) const { if ( inventory.pdas.Num() ) { return static_cast< const idDeclPDA* >( declManager->FindType( DECL_PDA, inventory.pdas[ 0 ] ) ); } else { return NULL; } } /* ============== idPlayer::GetVideo ============== */ const idDeclVideo *idPlayer::GetVideo( int index ) { if ( index >= 0 && index < inventory.videos.Num() ) { return static_cast< const idDeclVideo* >( declManager->FindType( DECL_VIDEO, inventory.videos[index], false ) ); } return NULL; } /* ============== idPlayer::UpdatePDAInfo ============== */ void idPlayer::UpdatePDAInfo( bool updatePDASel ) { int j, sel; if ( objectiveSystem == NULL ) { return; } assert( hud ); int currentPDA = objectiveSystem->State().GetInt( "listPDA_sel_0", "0" ); if ( currentPDA == -1 ) { currentPDA = 0; } if ( updatePDASel ) { objectiveSystem->SetStateInt( "listPDAVideo_sel_0", 0 ); objectiveSystem->SetStateInt( "listPDAEmail_sel_0", 0 ); objectiveSystem->SetStateInt( "listPDAAudio_sel_0", 0 ); } if ( currentPDA > 0 ) { currentPDA = inventory.pdas.Num() - currentPDA; } // Mark in the bit array that this pda has been read if ( currentPDA < 128 ) { inventory.pdasViewed[currentPDA >> 5] |= 1 << (currentPDA & 31); } pdaAudio = ""; pdaVideo = ""; pdaVideoWave = ""; idStr name, data, preview, info, wave; for ( j = 0; j < MAX_PDAS; j++ ) { objectiveSystem->SetStateString( va( "listPDA_item_%i", j ), "" ); } for ( j = 0; j < MAX_PDA_ITEMS; j++ ) { objectiveSystem->SetStateString( va( "listPDAVideo_item_%i", j ), "" ); objectiveSystem->SetStateString( va( "listPDAAudio_item_%i", j ), "" ); objectiveSystem->SetStateString( va( "listPDAEmail_item_%i", j ), "" ); objectiveSystem->SetStateString( va( "listPDASecurity_item_%i", j ), "" ); } for ( j = 0; j < inventory.pdas.Num(); j++ ) { const idDeclPDA *pda = static_cast< const idDeclPDA* >( declManager->FindType( DECL_PDA, inventory.pdas[j], false ) ); if ( pda == NULL ) { continue; } int index = inventory.pdas.Num() - j; if ( j == 0 ) { // Special case for the first PDA index = 0; } if ( j != currentPDA && j < 128 && inventory.pdasViewed[j >> 5] & (1 << (j & 31)) ) { // This pda has been read already, mark in gray objectiveSystem->SetStateString( va( "listPDA_item_%i", index), va(S_COLOR_GRAY "%s", pda->GetPdaName()) ); } else { // This pda has not been read yet objectiveSystem->SetStateString( va( "listPDA_item_%i", index), pda->GetPdaName() ); } const char *security = pda->GetSecurity(); if ( j == currentPDA || (currentPDA == 0 && security && *security ) ) { if ( *security == 0 ) { security = common->GetLanguageDict()->GetString( "#str_00066" ); } objectiveSystem->SetStateString( "PDASecurityClearance", security ); } if ( j == currentPDA ) { objectiveSystem->SetStateString( "pda_icon", pda->GetIcon() ); objectiveSystem->SetStateString( "pda_id", pda->GetID() ); objectiveSystem->SetStateString( "pda_title", pda->GetTitle() ); if ( j == 0 ) { // Selected, personal pda // Add videos if ( updatePDASel || !inventory.pdaOpened ) { objectiveSystem->HandleNamedEvent( "playerPDAActive" ); objectiveSystem->SetStateString( "pda_personal", "1" ); inventory.pdaOpened = true; } objectiveSystem->SetStateString( "pda_location", hud->State().GetString("location") ); objectiveSystem->SetStateString( "pda_name", cvarSystem->GetCVarString( "ui_name") ); AddGuiPDAData( DECL_VIDEO, "listPDAVideo", pda, objectiveSystem ); sel = objectiveSystem->State().GetInt( "listPDAVideo_sel_0", "0" ); const idDeclVideo *vid = NULL; if ( sel >= 0 && sel < inventory.videos.Num() ) { vid = static_cast< const idDeclVideo * >( declManager->FindType( DECL_VIDEO, inventory.videos[ sel ], false ) ); } if ( vid ) { pdaVideo = vid->GetRoq(); pdaVideoWave = vid->GetWave(); objectiveSystem->SetStateString( "PDAVideoTitle", vid->GetVideoName() ); objectiveSystem->SetStateString( "PDAVideoVid", vid->GetRoq() ); objectiveSystem->SetStateString( "PDAVideoIcon", vid->GetPreview() ); objectiveSystem->SetStateString( "PDAVideoInfo", vid->GetInfo() ); } else { //FIXME: need to precache these in the player def objectiveSystem->SetStateString( "PDAVideoVid", "sound/vo/video/welcome.tga" ); objectiveSystem->SetStateString( "PDAVideoIcon", "sound/vo/video/welcome.tga" ); objectiveSystem->SetStateString( "PDAVideoTitle", "" ); objectiveSystem->SetStateString( "PDAVideoInfo", "" ); } } else { // Selected, non-personal pda // Add audio logs if ( updatePDASel ) { objectiveSystem->HandleNamedEvent( "playerPDANotActive" ); objectiveSystem->SetStateString( "pda_personal", "0" ); inventory.pdaOpened = true; } objectiveSystem->SetStateString( "pda_location", pda->GetPost() ); objectiveSystem->SetStateString( "pda_name", pda->GetFullName() ); int audioCount = AddGuiPDAData( DECL_AUDIO, "listPDAAudio", pda, objectiveSystem ); objectiveSystem->SetStateInt( "audioLogCount", audioCount ); sel = objectiveSystem->State().GetInt( "listPDAAudio_sel_0", "0" ); const idDeclAudio *aud = NULL; if ( sel >= 0 ) { aud = pda->GetAudioByIndex( sel ); } if ( aud ) { pdaAudio = aud->GetWave(); objectiveSystem->SetStateString( "PDAAudioTitle", aud->GetAudioName() ); objectiveSystem->SetStateString( "PDAAudioIcon", aud->GetPreview() ); objectiveSystem->SetStateString( "PDAAudioInfo", aud->GetInfo() ); } else { objectiveSystem->SetStateString( "PDAAudioIcon", "sound/vo/video/welcome.tga" ); objectiveSystem->SetStateString( "PDAAutioTitle", "" ); objectiveSystem->SetStateString( "PDAAudioInfo", "" ); } } // add emails name = ""; data = ""; int numEmails = pda->GetNumEmails(); if ( numEmails > 0 ) { AddGuiPDAData( DECL_EMAIL, "listPDAEmail", pda, objectiveSystem ); sel = objectiveSystem->State().GetInt( "listPDAEmail_sel_0", "-1" ); if ( sel >= 0 && sel < numEmails ) { const idDeclEmail *email = pda->GetEmailByIndex( sel ); name = email->GetSubject(); data = email->GetBody(); } } objectiveSystem->SetStateString( "PDAEmailTitle", name ); objectiveSystem->SetStateString( "PDAEmailText", data ); } } if ( objectiveSystem->State().GetInt( "listPDA_sel_0", "-1" ) == -1 ) { objectiveSystem->SetStateInt( "listPDA_sel_0", 0 ); } objectiveSystem->StateChanged( gameLocal.time ); } /* ============== idPlayer::TogglePDA ============== */ void idPlayer::TogglePDA( void ) { if ( objectiveSystem == NULL ) { return; } if ( inventory.pdas.Num() == 0 ) { ShowTip( spawnArgs.GetString( "text_infoTitle" ), spawnArgs.GetString( "text_noPDA" ), true ); return; } assert( hud ); if ( !objectiveSystemOpen ) { int j, c = inventory.items.Num(); objectiveSystem->SetStateInt( "inv_count", c ); for ( j = 0; j < MAX_INVENTORY_ITEMS; j++ ) { objectiveSystem->SetStateString( va( "inv_name_%i", j ), "" ); objectiveSystem->SetStateString( va( "inv_icon_%i", j ), "" ); objectiveSystem->SetStateString( va( "inv_text_%i", j ), "" ); } for ( j = 0; j < c; j++ ) { idDict *item = inventory.items[j]; if ( !item->GetBool( "inv_pda" ) ) { const char *iname = item->GetString( "inv_name" ); const char *iicon = item->GetString( "inv_icon" ); const char *itext = item->GetString( "inv_text" ); objectiveSystem->SetStateString( va( "inv_name_%i", j ), iname ); objectiveSystem->SetStateString( va( "inv_icon_%i", j ), iicon ); objectiveSystem->SetStateString( va( "inv_text_%i", j ), itext ); const idKeyValue *kv = item->MatchPrefix( "inv_id", NULL ); if ( kv ) { objectiveSystem->SetStateString( va( "inv_id_%i", j ), kv->GetValue() ); } } } for ( j = 0; j < MAX_WEAPONS; j++ ) { const char *weapnum = va( "def_weapon%d", j ); const char *hudWeap = va( "weapon%d", j ); int weapstate = 0; if ( inventory.weapons & ( 1 << j ) ) { const char *weap = spawnArgs.GetString( weapnum ); if ( weap && *weap ) { weapstate++; } } objectiveSystem->SetStateInt( hudWeap, weapstate ); } objectiveSystem->SetStateInt( "listPDA_sel_0", inventory.selPDA ); objectiveSystem->SetStateInt( "listPDAVideo_sel_0", inventory.selVideo ); objectiveSystem->SetStateInt( "listPDAAudio_sel_0", inventory.selAudio ); objectiveSystem->SetStateInt( "listPDAEmail_sel_0", inventory.selEMail ); UpdatePDAInfo( false ); UpdateObjectiveInfo(); objectiveSystem->Activate( true, gameLocal.time ); hud->HandleNamedEvent( "pdaPickupHide" ); hud->HandleNamedEvent( "videoPickupHide" ); } else { inventory.selPDA = objectiveSystem->State().GetInt( "listPDA_sel_0" ); inventory.selVideo = objectiveSystem->State().GetInt( "listPDAVideo_sel_0" ); inventory.selAudio = objectiveSystem->State().GetInt( "listPDAAudio_sel_0" ); inventory.selEMail = objectiveSystem->State().GetInt( "listPDAEmail_sel_0" ); objectiveSystem->Activate( false, gameLocal.time ); } objectiveSystemOpen ^= 1; } /* ============== idPlayer::ToggleScoreboard ============== */ void idPlayer::ToggleScoreboard( void ) { scoreBoardOpen ^= 1; } /* ============== idPlayer::Spectate ============== */ void idPlayer::Spectate( bool spectate ) { idBitMsg msg; byte msgBuf[MAX_EVENT_PARAM_SIZE]; // track invisible player bug // all hiding and showing should be performed through Spectate calls // except for the private camera view, which is used for teleports assert( ( teleportEntity.GetEntity() != NULL ) || ( IsHidden() == spectating ) ); if ( spectating == spectate ) { return; } spectating = spectate; if ( gameLocal.isServer ) { msg.Init( msgBuf, sizeof( msgBuf ) ); msg.WriteBits( spectating, 1 ); ServerSendEvent( EVENT_SPECTATE, &msg, false, -1 ); } if ( spectating ) { // join the spectators ClearPowerUps(); spectator = this->entityNumber; Init(); StopRagdoll(); SetPhysics( &physicsObj ); physicsObj.DisableClip(); Hide(); Event_DisableWeapon(); if ( hud ) { hud->HandleNamedEvent( "aim_clear" ); MPAimFadeTime = 0; } } else { // put everything back together again currentWeapon = -1; // to make sure the def will be loaded if necessary Show(); Event_EnableWeapon(); } SetClipModel(); } /* ============== idPlayer::SetClipModel ============== */ void idPlayer::SetClipModel( void ) { idBounds bounds; if ( spectating ) { bounds = idBounds( vec3_origin ).Expand( pm_spectatebbox.GetFloat() * 0.5f ); } else { bounds[0].Set( -pm_bboxwidth.GetFloat() * 0.5f, -pm_bboxwidth.GetFloat() * 0.5f, 0 ); bounds[1].Set( pm_bboxwidth.GetFloat() * 0.5f, pm_bboxwidth.GetFloat() * 0.5f, pm_normalheight.GetFloat() ); } // the origin of the clip model needs to be set before calling SetClipModel // otherwise our physics object's current origin value gets reset to 0 idClipModel *newClip; if ( pm_usecylinder.GetBool() ) { newClip = new idClipModel( idTraceModel( bounds, 8 ) ); newClip->Translate( physicsObj.PlayerGetOrigin() ); physicsObj.SetClipModel( newClip, 1.0f ); } else { newClip = new idClipModel( idTraceModel( bounds ) ); newClip->Translate( physicsObj.PlayerGetOrigin() ); physicsObj.SetClipModel( newClip, 1.0f ); } } /* ============== idPlayer::UseVehicle ============== */ void idPlayer::UseVehicle( void ) { trace_t trace; idVec3 start, end; idEntity *ent; if ( GetBindMaster() && GetBindMaster()->IsType( idAFEntity_Vehicle::Type ) ) { Show(); static_cast<idAFEntity_Vehicle*>(GetBindMaster())->Use( this ); } else { start = GetEyePosition(); end = start + viewAngles.ToForward() * 80.0f; gameLocal.clip.TracePoint( trace, start, end, MASK_SHOT_RENDERMODEL, this ); if ( trace.fraction < 1.0f ) { ent = gameLocal.entities[ trace.c.entityNum ]; if ( ent && ent->IsType( idAFEntity_Vehicle::Type ) ) { Hide(); static_cast<idAFEntity_Vehicle*>(ent)->Use( this ); } } } } /* ============== idPlayer::PerformImpulse ============== */ void idPlayer::PerformImpulse( int impulse ) { if ( gameLocal.isClient ) { idBitMsg msg; byte msgBuf[MAX_EVENT_PARAM_SIZE]; assert( entityNumber == gameLocal.localClientNum ); msg.Init( msgBuf, sizeof( msgBuf ) ); msg.BeginWriting(); msg.WriteBits( impulse, 6 ); ClientSendEvent( EVENT_IMPULSE, &msg ); } if ( impulse >= IMPULSE_0 && impulse <= IMPULSE_12 ) { SelectWeapon( impulse, false ); return; } switch( impulse ) { case IMPULSE_13: { Reload(); break; } case IMPULSE_14: { NextWeapon(); break; } case IMPULSE_15: { PrevWeapon(); break; } case IMPULSE_17: { if ( gameLocal.isClient || entityNumber == gameLocal.localClientNum ) { gameLocal.mpGame.ToggleReady(); } break; } case IMPULSE_18: { centerView.Init(gameLocal.time, 200, viewAngles.pitch, 0); break; } case IMPULSE_19: { // when we're not in single player, IMPULSE_19 is used for showScores // otherwise it opens the pda if ( !gameLocal.isMultiplayer ) { if ( objectiveSystemOpen ) { TogglePDA(); } else if ( weapon_pda >= 0 ) { SelectWeapon( weapon_pda, true ); } } break; } case IMPULSE_20: { if ( gameLocal.isClient || entityNumber == gameLocal.localClientNum ) { gameLocal.mpGame.ToggleTeam(); } break; } case IMPULSE_22: { if ( gameLocal.isClient || entityNumber == gameLocal.localClientNum ) { gameLocal.mpGame.ToggleSpectate(); } break; } case IMPULSE_25: { if ( gameLocal.isServer && gameLocal.mpGame.IsGametypeFlagBased() && (gameLocal.serverInfo.GetInt( "si_midnight" ) == 2) ) { if ( enviroSuitLight.IsValid() ) { enviroSuitLight.GetEntity()->PostEventMS( &EV_Remove, 0 ); enviroSuitLight = NULL; } else { const idDict *lightDef = gameLocal.FindEntityDefDict( "envirosuit_light", false ); if ( lightDef ) { idEntity *temp = static_cast<idEntity *>(enviroSuitLight.GetEntity()); idAngles lightAng = firstPersonViewAxis.ToAngles(); idVec3 lightOrg = firstPersonViewOrigin; idVec3 enviroOffset = lightDef->GetVector( "enviro_offset" ); idVec3 enviroAngleOffset = lightDef->GetVector( "enviro_angle_offset" ); gameLocal.SpawnEntityDef( *lightDef, &temp, false ); enviroSuitLight = static_cast<idLight *>(temp); enviroSuitLight.GetEntity()->fl.networkSync = true; lightOrg += (enviroOffset.x * firstPersonViewAxis[0]); lightOrg += (enviroOffset.y * firstPersonViewAxis[1]); lightOrg += (enviroOffset.z * firstPersonViewAxis[2]); lightAng.pitch += enviroAngleOffset.x; lightAng.yaw += enviroAngleOffset.y; lightAng.roll += enviroAngleOffset.z; enviroSuitLight.GetEntity()->GetPhysics()->SetOrigin( lightOrg ); enviroSuitLight.GetEntity()->GetPhysics()->SetAxis( lightAng.ToMat3() ); enviroSuitLight.GetEntity()->UpdateVisuals(); enviroSuitLight.GetEntity()->Present(); } } } break; } case IMPULSE_28: { if ( gameLocal.isClient || entityNumber == gameLocal.localClientNum ) { gameLocal.mpGame.CastVote( gameLocal.localClientNum, true ); } break; } case IMPULSE_29: { if ( gameLocal.isClient || entityNumber == gameLocal.localClientNum ) { gameLocal.mpGame.CastVote( gameLocal.localClientNum, false ); } break; } case IMPULSE_40: { UseVehicle(); break; } #ifdef _D3XP //Hack so the chainsaw will work in MP case IMPULSE_27: { SelectWeapon(18, false); break; } #endif } } bool idPlayer::HandleESC( void ) { if ( gameLocal.inCinematic ) { return SkipCinematic(); } if ( objectiveSystemOpen ) { TogglePDA(); return true; } return false; } bool idPlayer::SkipCinematic( void ) { StartSound( "snd_skipcinematic", SND_CHANNEL_ANY, 0, false, NULL ); return gameLocal.SkipCinematic(); } /* ============== idPlayer::EvaluateControls ============== */ void idPlayer::EvaluateControls( void ) { // check for respawning if ( health <= 0 ) { if ( ( gameLocal.time > minRespawnTime ) && ( usercmd.buttons & BUTTON_ATTACK ) ) { forceRespawn = true; } else if ( gameLocal.time > maxRespawnTime ) { forceRespawn = true; } } // in MP, idMultiplayerGame decides spawns if ( forceRespawn && !gameLocal.isMultiplayer && !g_testDeath.GetBool() ) { // in single player, we let the session handle restarting the level or loading a game gameLocal.sessionCommand = "died"; } if ( ( usercmd.flags & UCF_IMPULSE_SEQUENCE ) != ( oldFlags & UCF_IMPULSE_SEQUENCE ) ) { PerformImpulse( usercmd.impulse ); } scoreBoardOpen = ( ( usercmd.buttons & BUTTON_SCORES ) != 0 || forceScoreBoard ); oldFlags = usercmd.flags; AdjustSpeed(); // update the viewangles UpdateViewAngles(); } /* ============== idPlayer::AdjustSpeed ============== */ void idPlayer::AdjustSpeed( void ) { float speed; float rate; if ( spectating ) { speed = pm_spectatespeed.GetFloat(); bobFrac = 0.0f; } else if ( noclip ) { speed = pm_noclipspeed.GetFloat(); bobFrac = 0.0f; } else if ( !physicsObj.OnLadder() && ( usercmd.buttons & BUTTON_RUN ) && ( usercmd.forwardmove || usercmd.rightmove ) && ( usercmd.upmove >= 0 ) ) { if ( !gameLocal.isMultiplayer && !physicsObj.IsCrouching() && !PowerUpActive( ADRENALINE ) ) { stamina -= MS2SEC( gameLocal.msec ); } if ( stamina < 0 ) { stamina = 0; } if ( ( !pm_stamina.GetFloat() ) || ( stamina > pm_staminathreshold.GetFloat() ) ) { bobFrac = 1.0f; } else if ( pm_staminathreshold.GetFloat() <= 0.0001f ) { bobFrac = 0.0f; } else { bobFrac = stamina / pm_staminathreshold.GetFloat(); } speed = pm_walkspeed.GetFloat() * ( 1.0f - bobFrac ) + pm_runspeed.GetFloat() * bobFrac; } else { rate = pm_staminarate.GetFloat(); // increase 25% faster when not moving if ( ( usercmd.forwardmove == 0 ) && ( usercmd.rightmove == 0 ) && ( !physicsObj.OnLadder() || ( usercmd.upmove == 0 ) ) ) { rate *= 1.25f; } stamina += rate * MS2SEC( gameLocal.msec ); if ( stamina > pm_stamina.GetFloat() ) { stamina = pm_stamina.GetFloat(); } speed = pm_walkspeed.GetFloat(); bobFrac = 0.0f; } speed *= PowerUpModifier(SPEED); if ( influenceActive == INFLUENCE_LEVEL3 ) { speed *= 0.33f; } physicsObj.SetSpeed( speed, pm_crouchspeed.GetFloat() ); } /* ============== idPlayer::AdjustBodyAngles ============== */ void idPlayer::AdjustBodyAngles( void ) { idMat3 lookAxis; idMat3 legsAxis; bool blend; float diff; float frac; float upBlend; float forwardBlend; float downBlend; if ( health < 0 ) { return; } blend = true; if ( !physicsObj.HasGroundContacts() ) { idealLegsYaw = 0.0f; legsForward = true; } else if ( usercmd.forwardmove < 0 ) { idealLegsYaw = idMath::AngleNormalize180( idVec3( -usercmd.forwardmove, usercmd.rightmove, 0.0f ).ToYaw() ); legsForward = false; } else if ( usercmd.forwardmove > 0 ) { idealLegsYaw = idMath::AngleNormalize180( idVec3( usercmd.forwardmove, -usercmd.rightmove, 0.0f ).ToYaw() ); legsForward = true; } else if ( ( usercmd.rightmove != 0 ) && physicsObj.IsCrouching() ) { if ( !legsForward ) { idealLegsYaw = idMath::AngleNormalize180( idVec3( idMath::Abs( usercmd.rightmove ), usercmd.rightmove, 0.0f ).ToYaw() ); } else { idealLegsYaw = idMath::AngleNormalize180( idVec3( idMath::Abs( usercmd.rightmove ), -usercmd.rightmove, 0.0f ).ToYaw() ); } } else if ( usercmd.rightmove != 0 ) { idealLegsYaw = 0.0f; legsForward = true; } else { legsForward = true; diff = idMath::Fabs( idealLegsYaw - legsYaw ); idealLegsYaw = idealLegsYaw - idMath::AngleNormalize180( viewAngles.yaw - oldViewYaw ); if ( diff < 0.1f ) { legsYaw = idealLegsYaw; blend = false; } } if ( !physicsObj.IsCrouching() ) { legsForward = true; } oldViewYaw = viewAngles.yaw; AI_TURN_LEFT = false; AI_TURN_RIGHT = false; if ( idealLegsYaw < -45.0f ) { idealLegsYaw = 0; AI_TURN_RIGHT = true; blend = true; } else if ( idealLegsYaw > 45.0f ) { idealLegsYaw = 0; AI_TURN_LEFT = true; blend = true; } if ( blend ) { legsYaw = legsYaw * 0.9f + idealLegsYaw * 0.1f; } legsAxis = idAngles( 0.0f, legsYaw, 0.0f ).ToMat3(); animator.SetJointAxis( hipJoint, JOINTMOD_WORLD, legsAxis ); // calculate the blending between down, straight, and up frac = viewAngles.pitch / 90.0f; if ( frac > 0.0f ) { downBlend = frac; forwardBlend = 1.0f - frac; upBlend = 0.0f; } else { downBlend = 0.0f; forwardBlend = 1.0f + frac; upBlend = -frac; } animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( 0, downBlend ); animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( 1, forwardBlend ); animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( 2, upBlend ); animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( 0, downBlend ); animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( 1, forwardBlend ); animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( 2, upBlend ); } /* ============== idPlayer::InitAASLocation ============== */ void idPlayer::InitAASLocation( void ) { int i; int num; idVec3 size; idBounds bounds; idAAS *aas; idVec3 origin; GetFloorPos( 64.0f, origin ); num = gameLocal.NumAAS(); aasLocation.SetGranularity( 1 ); aasLocation.SetNum( num ); for( i = 0; i < aasLocation.Num(); i++ ) { aasLocation[ i ].areaNum = 0; aasLocation[ i ].pos = origin; aas = gameLocal.GetAAS( i ); if ( aas && aas->GetSettings() ) { size = aas->GetSettings()->boundingBoxes[0][1]; bounds[0] = -size; size.z = 32.0f; bounds[1] = size; aasLocation[ i ].areaNum = aas->PointReachableAreaNum( origin, bounds, AREA_REACHABLE_WALK ); } } } /* ============== idPlayer::SetAASLocation ============== */ void idPlayer::SetAASLocation( void ) { int i; int areaNum; idVec3 size; idBounds bounds; idAAS *aas; idVec3 origin; if ( !GetFloorPos( 64.0f, origin ) ) { return; } for( i = 0; i < aasLocation.Num(); i++ ) { aas = gameLocal.GetAAS( i ); if ( !aas ) { continue; } size = aas->GetSettings()->boundingBoxes[0][1]; bounds[0] = -size; size.z = 32.0f; bounds[1] = size; areaNum = aas->PointReachableAreaNum( origin, bounds, AREA_REACHABLE_WALK ); if ( areaNum ) { aasLocation[ i ].pos = origin; aasLocation[ i ].areaNum = areaNum; } } } /* ============== idPlayer::GetAASLocation ============== */ void idPlayer::GetAASLocation( idAAS *aas, idVec3 &pos, int &areaNum ) const { int i; if ( aas != NULL ) { for( i = 0; i < aasLocation.Num(); i++ ) { if ( aas == gameLocal.GetAAS( i ) ) { areaNum = aasLocation[ i ].areaNum; pos = aasLocation[ i ].pos; return; } } } areaNum = 0; pos = physicsObj.GetOrigin(); } /* ============== idPlayer::Move ============== */ void idPlayer::Move( void ) { float newEyeOffset; idVec3 oldOrigin; idVec3 oldVelocity; idVec3 pushVelocity; // save old origin and velocity for crashlanding oldOrigin = physicsObj.GetOrigin(); oldVelocity = physicsObj.GetLinearVelocity(); pushVelocity = physicsObj.GetPushedLinearVelocity(); // set physics variables physicsObj.SetMaxStepHeight( pm_stepsize.GetFloat() ); physicsObj.SetMaxJumpHeight( pm_jumpheight.GetFloat() ); if ( noclip ) { physicsObj.SetContents( 0 ); physicsObj.SetMovementType( PM_NOCLIP ); } else if ( spectating ) { physicsObj.SetContents( 0 ); physicsObj.SetMovementType( PM_SPECTATOR ); } else if ( health <= 0 ) { physicsObj.SetContents( CONTENTS_CORPSE | CONTENTS_MONSTERCLIP ); physicsObj.SetMovementType( PM_DEAD ); } else if ( gameLocal.inCinematic || gameLocal.GetCamera() || privateCameraView || ( influenceActive == INFLUENCE_LEVEL2 ) ) { physicsObj.SetContents( CONTENTS_BODY ); physicsObj.SetMovementType( PM_FREEZE ); #ifdef _D3XP } else if ( mountedObject ) { physicsObj.SetContents( 0 ); physicsObj.SetMovementType( PM_FREEZE ); #endif } else { physicsObj.SetContents( CONTENTS_BODY ); physicsObj.SetMovementType( PM_NORMAL ); } if ( spectating ) { physicsObj.SetClipMask( MASK_DEADSOLID ); } else if ( health <= 0 ) { physicsObj.SetClipMask( MASK_DEADSOLID ); } else { physicsObj.SetClipMask( MASK_PLAYERSOLID ); } physicsObj.SetDebugLevel( g_debugMove.GetBool() ); physicsObj.SetPlayerInput( usercmd, viewAngles ); // FIXME: physics gets disabled somehow BecomeActive( TH_PHYSICS ); RunPhysics(); // update our last valid AAS location for the AI SetAASLocation(); if ( spectating ) { newEyeOffset = 0.0f; } else if ( health <= 0 ) { newEyeOffset = pm_deadviewheight.GetFloat(); } else if ( physicsObj.IsCrouching() ) { newEyeOffset = pm_crouchviewheight.GetFloat(); } else if ( GetBindMaster() && GetBindMaster()->IsType( idAFEntity_Vehicle::Type ) ) { newEyeOffset = 0.0f; } else { newEyeOffset = pm_normalviewheight.GetFloat(); } if ( EyeHeight() != newEyeOffset ) { if ( spectating ) { SetEyeHeight( newEyeOffset ); } else { // smooth out duck height changes SetEyeHeight( EyeHeight() * pm_crouchrate.GetFloat() + newEyeOffset * ( 1.0f - pm_crouchrate.GetFloat() ) ); } } if ( noclip || gameLocal.inCinematic || ( influenceActive == INFLUENCE_LEVEL2 ) ) { AI_CROUCH = false; AI_ONGROUND = ( influenceActive == INFLUENCE_LEVEL2 ); AI_ONLADDER = false; AI_JUMP = false; } else { AI_CROUCH = physicsObj.IsCrouching(); AI_ONGROUND = physicsObj.HasGroundContacts(); AI_ONLADDER = physicsObj.OnLadder(); AI_JUMP = physicsObj.HasJumped(); // check if we're standing on top of a monster and give a push if we are idEntity *groundEnt = physicsObj.GetGroundEntity(); if ( groundEnt && groundEnt->IsType( idAI::Type ) ) { idVec3 vel = physicsObj.GetLinearVelocity(); if ( vel.ToVec2().LengthSqr() < 0.1f ) { vel.ToVec2() = physicsObj.GetOrigin().ToVec2() - groundEnt->GetPhysics()->GetAbsBounds().GetCenter().ToVec2(); vel.ToVec2().NormalizeFast(); vel.ToVec2() *= pm_walkspeed.GetFloat(); } else { // give em a push in the direction they're going vel *= 1.1f; } physicsObj.SetLinearVelocity( vel ); } } if ( AI_JUMP ) { // bounce the view weapon loggedAccel_t *acc = &loggedAccel[currentLoggedAccel&(NUM_LOGGED_ACCELS-1)]; currentLoggedAccel++; acc->time = gameLocal.time; acc->dir[2] = 200; acc->dir[0] = acc->dir[1] = 0; } if ( AI_ONLADDER ) { int old_rung = oldOrigin.z / LADDER_RUNG_DISTANCE; int new_rung = physicsObj.GetOrigin().z / LADDER_RUNG_DISTANCE; if ( old_rung != new_rung ) { StartSound( "snd_stepladder", SND_CHANNEL_ANY, 0, false, NULL ); } } BobCycle( pushVelocity ); CrashLand( oldOrigin, oldVelocity ); } /* ============== idPlayer::UpdateHud ============== */ void idPlayer::UpdateHud( void ) { idPlayer *aimed; if ( !hud ) { return; } if ( entityNumber != gameLocal.localClientNum ) { return; } int c = inventory.pickupItemNames.Num(); if ( c > 0 ) { if ( gameLocal.time > inventory.nextItemPickup ) { if ( inventory.nextItemPickup && gameLocal.time - inventory.nextItemPickup > 2000 ) { inventory.nextItemNum = 1; } int i, count = 5; #ifdef _D3XP if(gameLocal.isMultiplayer) { count = 3; } if (count < c) c = count; #endif for ( i = 0; i < c; i++ ) { //_D3XP hud->SetStateString( va( "itemtext%i", inventory.nextItemNum ), inventory.pickupItemNames[0].name ); hud->SetStateString( va( "itemicon%i", inventory.nextItemNum ), inventory.pickupItemNames[0].icon ); hud->HandleNamedEvent( va( "itemPickup%i", inventory.nextItemNum++ ) ); inventory.pickupItemNames.RemoveIndex( 0 ); if (inventory.nextItemNum == 1 ) { inventory.onePickupTime = gameLocal.time; } else if ( inventory.nextItemNum > count ) { //_D3XP inventory.nextItemNum = 1; inventory.nextItemPickup = inventory.onePickupTime + 2000; } else { inventory.nextItemPickup = gameLocal.time + 400; } } } } if ( gameLocal.realClientTime == lastMPAimTime ) { if ( MPAim != -1 && gameLocal.mpGame.IsGametypeTeamBased() /* CTF */ && gameLocal.entities[ MPAim ] && gameLocal.entities[ MPAim ]->IsType( idPlayer::Type ) && static_cast< idPlayer * >( gameLocal.entities[ MPAim ] )->team == team ) { aimed = static_cast< idPlayer * >( gameLocal.entities[ MPAim ] ); hud->SetStateString( "aim_text", gameLocal.userInfo[ MPAim ].GetString( "ui_name" ) ); hud->SetStateFloat( "aim_color", aimed->colorBarIndex ); hud->HandleNamedEvent( "aim_flash" ); MPAimHighlight = true; MPAimFadeTime = 0; // no fade till loosing focus } else if ( MPAimHighlight ) { hud->HandleNamedEvent( "aim_fade" ); MPAimFadeTime = gameLocal.realClientTime; MPAimHighlight = false; } } if ( MPAimFadeTime ) { assert( !MPAimHighlight ); if ( gameLocal.realClientTime - MPAimFadeTime > 2000 ) { MPAimFadeTime = 0; } } hud->SetStateInt( "g_showProjectilePct", g_showProjectilePct.GetInteger() ); if ( numProjectilesFired ) { hud->SetStateString( "projectilepct", va( "Hit %% %.1f", ( (float) numProjectileHits / numProjectilesFired ) * 100 ) ); } else { hud->SetStateString( "projectilepct", "Hit % 0.0" ); } if ( isLagged && gameLocal.isMultiplayer && gameLocal.localClientNum == entityNumber ) { hud->SetStateString( "hudLag", "1" ); } else { hud->SetStateString( "hudLag", "0" ); } } /* ============== idPlayer::UpdateDeathSkin ============== */ void idPlayer::UpdateDeathSkin( bool state_hitch ) { if ( !( gameLocal.isMultiplayer || g_testDeath.GetBool() ) ) { return; } if ( health <= 0 ) { if ( !doingDeathSkin ) { deathClearContentsTime = spawnArgs.GetInt( "deathSkinTime" ); doingDeathSkin = true; renderEntity.noShadow = true; if ( state_hitch ) { renderEntity.shaderParms[ SHADERPARM_TIME_OF_DEATH ] = gameLocal.time * 0.001f - 2.0f; } else { renderEntity.shaderParms[ SHADERPARM_TIME_OF_DEATH ] = gameLocal.time * 0.001f; } UpdateVisuals(); } // wait a bit before switching off the content if ( deathClearContentsTime && gameLocal.time > deathClearContentsTime ) { SetCombatContents( false ); deathClearContentsTime = 0; } } else { renderEntity.noShadow = false; renderEntity.shaderParms[ SHADERPARM_TIME_OF_DEATH ] = 0.0f; UpdateVisuals(); doingDeathSkin = false; } } /* ============== idPlayer::StartFxOnBone ============== */ void idPlayer::StartFxOnBone( const char *fx, const char *bone ) { idVec3 offset; idMat3 axis; jointHandle_t jointHandle = GetAnimator()->GetJointHandle( bone ); if ( jointHandle == INVALID_JOINT ) { gameLocal.Printf( "Cannot find bone %s\n", bone ); return; } if ( GetAnimator()->GetJointTransform( jointHandle, gameLocal.time, offset, axis ) ) { offset = GetPhysics()->GetOrigin() + offset * GetPhysics()->GetAxis(); axis = axis * GetPhysics()->GetAxis(); } idEntityFx::StartFx( fx, &offset, &axis, this, true ); } /* ============== idPlayer::Think Called every tic for each player ============== */ void idPlayer::Think( void ) { renderEntity_t *headRenderEnt; UpdatePlayerIcons(); // latch button actions oldButtons = usercmd.buttons; // grab out usercmd usercmd_t oldCmd = usercmd; usercmd = gameLocal.usercmds[ entityNumber ]; buttonMask &= usercmd.buttons; usercmd.buttons &= ~buttonMask; if ( gameLocal.inCinematic && gameLocal.skipCinematic ) { return; } // clear the ik before we do anything else so the skeleton doesn't get updated twice walkIK.ClearJointMods(); // if this is the very first frame of the map, set the delta view angles // based on the usercmd angles if ( !spawnAnglesSet && ( gameLocal.GameState() != GAMESTATE_STARTUP ) ) { spawnAnglesSet = true; SetViewAngles( spawnAngles ); oldFlags = usercmd.flags; } #ifdef _D3XP if ( mountedObject ) { usercmd.forwardmove = 0; usercmd.rightmove = 0; usercmd.upmove = 0; } #endif if ( objectiveSystemOpen || gameLocal.inCinematic || influenceActive ) { if ( objectiveSystemOpen && AI_PAIN ) { TogglePDA(); } usercmd.forwardmove = 0; usercmd.rightmove = 0; usercmd.upmove = 0; } // log movement changes for weapon bobbing effects if ( usercmd.forwardmove != oldCmd.forwardmove ) { loggedAccel_t *acc = &loggedAccel[currentLoggedAccel&(NUM_LOGGED_ACCELS-1)]; currentLoggedAccel++; acc->time = gameLocal.time; acc->dir[0] = usercmd.forwardmove - oldCmd.forwardmove; acc->dir[1] = acc->dir[2] = 0; } if ( usercmd.rightmove != oldCmd.rightmove ) { loggedAccel_t *acc = &loggedAccel[currentLoggedAccel&(NUM_LOGGED_ACCELS-1)]; currentLoggedAccel++; acc->time = gameLocal.time; acc->dir[1] = usercmd.rightmove - oldCmd.rightmove; acc->dir[0] = acc->dir[2] = 0; } // freelook centering if ( ( usercmd.buttons ^ oldCmd.buttons ) & BUTTON_MLOOK ) { centerView.Init( gameLocal.time, 200, viewAngles.pitch, 0 ); } // zooming if ( ( usercmd.buttons ^ oldCmd.buttons ) & BUTTON_ZOOM ) { if ( ( usercmd.buttons & BUTTON_ZOOM ) && weapon.GetEntity() ) { zoomFov.Init( gameLocal.time, 200.0f, CalcFov( false ), weapon.GetEntity()->GetZoomFov() ); } else { zoomFov.Init( gameLocal.time, 200.0f, zoomFov.GetCurrentValue( gameLocal.time ), DefaultFov() ); } } // if we have an active gui, we will unrotate the view angles as // we turn the mouse movements into gui events idUserInterface *gui = ActiveGui(); if ( gui && gui != focusUI ) { RouteGuiMouse( gui ); } // set the push velocity on the weapon before running the physics if ( weapon.GetEntity() ) { weapon.GetEntity()->SetPushVelocity( physicsObj.GetPushedLinearVelocity() ); } EvaluateControls(); if ( !af.IsActive() ) { AdjustBodyAngles(); CopyJointsFromBodyToHead(); } Move(); if ( !g_stopTime.GetBool() ) { if ( !noclip && !spectating && ( health > 0 ) && !IsHidden() ) { TouchTriggers(); } // not done on clients for various reasons. don't do it on server and save the sound channel for other things if ( !gameLocal.isMultiplayer ) { SetCurrentHeartRate(); #ifdef _D3XP float scale = new_g_damageScale; #else float scale = g_damageScale.GetFloat(); #endif if ( g_useDynamicProtection.GetBool() && scale < 1.0f && gameLocal.time - lastDmgTime > 500 ) { if ( scale < 1.0f ) { scale += 0.05f; } if ( scale > 1.0f ) { scale = 1.0f; } #ifdef _D3XP new_g_damageScale = scale; #else g_damageScale.SetFloat( scale ); #endif } } // update GUIs, Items, and character interactions UpdateFocus(); UpdateLocation(); // update player script UpdateScript(); // service animations if ( !spectating && !af.IsActive() && !gameLocal.inCinematic ) { UpdateConditions(); UpdateAnimState(); CheckBlink(); } // clear out our pain flag so we can tell if we recieve any damage between now and the next time we think AI_PAIN = false; } // calculate the exact bobbed view position, which is used to // position the view weapon, among other things CalculateFirstPersonView(); // this may use firstPersonView, or a thirdPeroson / camera view CalculateRenderView(); inventory.UpdateArmor(); if ( spectating ) { UpdateSpectating(); } else if ( health > 0 ) { UpdateWeapon(); } UpdateAir(); #ifdef _D3XP UpdatePowerupHud(); #endif UpdateHud(); UpdatePowerUps(); UpdateDeathSkin( false ); if ( gameLocal.isMultiplayer ) { DrawPlayerIcons(); #ifdef _D3XP if ( enviroSuitLight.IsValid() ) { idAngles lightAng = firstPersonViewAxis.ToAngles(); idVec3 lightOrg = firstPersonViewOrigin; const idDict *lightDef = gameLocal.FindEntityDefDict( "envirosuit_light", false ); idVec3 enviroOffset = lightDef->GetVector( "enviro_offset" ); idVec3 enviroAngleOffset = lightDef->GetVector( "enviro_angle_offset" ); lightOrg += (enviroOffset.x * firstPersonViewAxis[0]); lightOrg += (enviroOffset.y * firstPersonViewAxis[1]); lightOrg += (enviroOffset.z * firstPersonViewAxis[2]); lightAng.pitch += enviroAngleOffset.x; lightAng.yaw += enviroAngleOffset.y; lightAng.roll += enviroAngleOffset.z; enviroSuitLight.GetEntity()->GetPhysics()->SetOrigin( lightOrg ); enviroSuitLight.GetEntity()->GetPhysics()->SetAxis( lightAng.ToMat3() ); enviroSuitLight.GetEntity()->UpdateVisuals(); enviroSuitLight.GetEntity()->Present(); } #endif } if ( head.GetEntity() ) { headRenderEnt = head.GetEntity()->GetRenderEntity(); } else { headRenderEnt = NULL; } if ( headRenderEnt ) { if ( influenceSkin ) { headRenderEnt->customSkin = influenceSkin; } else { headRenderEnt->customSkin = NULL; } } if ( gameLocal.isMultiplayer || g_showPlayerShadow.GetBool() ) { renderEntity.suppressShadowInViewID = 0; if ( headRenderEnt ) { headRenderEnt->suppressShadowInViewID = 0; } } else { renderEntity.suppressShadowInViewID = entityNumber+1; if ( headRenderEnt ) { headRenderEnt->suppressShadowInViewID = entityNumber+1; } } // never cast shadows from our first-person muzzle flashes renderEntity.suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + entityNumber; if ( headRenderEnt ) { headRenderEnt->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + entityNumber; } if ( !g_stopTime.GetBool() ) { UpdateAnimation(); Present(); UpdateDamageEffects(); LinkCombat(); playerView.CalculateShake(); } if ( !( thinkFlags & TH_THINK ) ) { gameLocal.Printf( "player %d not thinking?\n", entityNumber ); } if ( g_showEnemies.GetBool() ) { idActor *ent; int num = 0; for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { gameLocal.Printf( "enemy (%d)'%s'\n", ent->entityNumber, ent->name.c_str() ); gameRenderWorld->DebugBounds( colorRed, ent->GetPhysics()->GetBounds().Expand( 2 ), ent->GetPhysics()->GetOrigin() ); num++; } gameLocal.Printf( "%d: enemies\n", num ); } #ifdef _D3XP inventory.RechargeAmmo(this); if(healthRecharge) { int elapsed = gameLocal.time - lastHealthRechargeTime; if(elapsed >= rechargeSpeed) { int intervals = (gameLocal.time - lastHealthRechargeTime)/rechargeSpeed; Give("health", va("%d", intervals)); lastHealthRechargeTime += intervals*rechargeSpeed; } } // determine if portal sky is in pvs gameLocal.portalSkyActive = gameLocal.pvs.CheckAreasForPortalSky( gameLocal.GetPlayerPVS(), GetPhysics()->GetOrigin() ); #endif } #ifdef _D3XP /* ================= idPlayer::StartHealthRecharge ================= */ void idPlayer::StartHealthRecharge(int speed) { lastHealthRechargeTime = gameLocal.time; healthRecharge = true; rechargeSpeed = speed; } /* ================= idPlayer::StopHealthRecharge ================= */ void idPlayer::StopHealthRecharge() { healthRecharge = false; } /* ================= idPlayer::GetCurrentWeapon ================= */ idStr idPlayer::GetCurrentWeapon() { const char *weapon; if ( currentWeapon >= 0 ) { weapon = spawnArgs.GetString( va( "def_weapon%d", currentWeapon ) ); return weapon; } else { return ""; } } /* ================= idPlayer::CanGive ================= */ bool idPlayer::CanGive( const char *statname, const char *value ) { if ( AI_DEAD ) { return false; } if ( !idStr::Icmp( statname, "health" ) ) { if ( health >= inventory.maxHealth ) { return false; } return true; } else if ( !idStr::Icmp( statname, "stamina" ) ) { if ( stamina >= 100 ) { return false; } return true; } else if ( !idStr::Icmp( statname, "heartRate" ) ) { return true; } else if ( !idStr::Icmp( statname, "air" ) ) { if ( airTics >= pm_airTics.GetInteger() ) { return false; } return true; } return inventory.CanGive( this, spawnArgs, statname, value, &idealWeapon ); } /* ================= idPlayer::StopHelltime provides a quick non-ramping way of stopping helltime ================= */ void idPlayer::StopHelltime( bool quick ) { if ( !PowerUpActive( HELLTIME ) ) { return; } // take away the powerups if ( PowerUpActive( INVULNERABILITY ) ) { ClearPowerup( INVULNERABILITY ); } if ( PowerUpActive( BERSERK ) ) { ClearPowerup( BERSERK ); } if ( PowerUpActive( HELLTIME ) ) { ClearPowerup( HELLTIME ); } // stop the looping sound StopSound( SND_CHANNEL_DEMONIC, false ); // reset the game vars if ( quick ) { gameLocal.QuickSlowmoReset(); } } /* ================= idPlayer::Event_ToggleBloom ================= */ void idPlayer::Event_ToggleBloom( int on ) { if ( on ) { bloomEnabled = true; } else { bloomEnabled = false; } } /* ================= idPlayer::Event_SetBloomParms ================= */ void idPlayer::Event_SetBloomParms( float speed, float intensity ) { bloomSpeed = speed; bloomIntensity = intensity; } /* ================= idPlayer::PlayHelltimeStopSound ================= */ void idPlayer::PlayHelltimeStopSound() { const char* sound; if ( spawnArgs.GetString( "snd_helltime_stop", "", &sound ) ) { PostEventMS( &EV_StartSoundShader, 0, sound, SND_CHANNEL_ANY ); } } #endif /* ================= idPlayer::RouteGuiMouse ================= */ void idPlayer::RouteGuiMouse( idUserInterface *gui ) { sysEvent_t ev; if ( usercmd.mx != oldMouseX || usercmd.my != oldMouseY ) { ev = sys->GenerateMouseMoveEvent( usercmd.mx - oldMouseX, usercmd.my - oldMouseY ); gui->HandleEvent( &ev, gameLocal.time ); oldMouseX = usercmd.mx; oldMouseY = usercmd.my; } } /* ================== idPlayer::LookAtKiller ================== */ void idPlayer::LookAtKiller( idEntity *inflictor, idEntity *attacker ) { idVec3 dir; if ( attacker && attacker != this ) { dir = attacker->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin(); } else if ( inflictor && inflictor != this ) { dir = inflictor->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin(); } else { dir = viewAxis[ 0 ]; } idAngles ang( 0, dir.ToYaw(), 0 ); SetViewAngles( ang ); } /* ============== idPlayer::Kill ============== */ void idPlayer::Kill( bool delayRespawn, bool nodamage ) { if ( spectating ) { SpectateFreeFly( false ); } else if ( health > 0 ) { godmode = false; if ( nodamage ) { ServerSpectate( true ); forceRespawn = true; } else { Damage( this, this, vec3_origin, "damage_suicide", 1.0f, INVALID_JOINT ); if ( delayRespawn ) { forceRespawn = false; int delay = spawnArgs.GetFloat( "respawn_delay" ); minRespawnTime = gameLocal.time + SEC2MS( delay ); maxRespawnTime = minRespawnTime + MAX_RESPAWN_TIME; } } } } /* ================== idPlayer::Killed ================== */ void idPlayer::Killed( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location ) { float delay; assert( !gameLocal.isClient ); // stop taking knockback once dead fl.noknockback = true; if ( health < -999 ) { health = -999; } if ( AI_DEAD ) { AI_PAIN = true; return; } heartInfo.Init( 0, 0, 0, BASE_HEARTRATE ); AdjustHeartRate( DEAD_HEARTRATE, 10.0f, 0.0f, true ); if ( !g_testDeath.GetBool() ) { playerView.Fade( colorBlack, 12000 ); } AI_DEAD = true; SetAnimState( ANIMCHANNEL_LEGS, "Legs_Death", 4 ); SetAnimState( ANIMCHANNEL_TORSO, "Torso_Death", 4 ); SetWaitState( "" ); animator.ClearAllJoints(); if ( StartRagdoll() ) { pm_modelView.SetInteger( 0 ); minRespawnTime = gameLocal.time + RAGDOLL_DEATH_TIME; maxRespawnTime = minRespawnTime + MAX_RESPAWN_TIME; } else { // don't allow respawn until the death anim is done // g_forcerespawn may force spawning at some later time delay = spawnArgs.GetFloat( "respawn_delay" ); minRespawnTime = gameLocal.time + SEC2MS( delay ); maxRespawnTime = minRespawnTime + MAX_RESPAWN_TIME; } physicsObj.SetMovementType( PM_DEAD ); StartSound( "snd_death", SND_CHANNEL_VOICE, 0, false, NULL ); StopSound( SND_CHANNEL_BODY2, false ); fl.takedamage = true; // can still be gibbed // get rid of weapon weapon.GetEntity()->OwnerDied(); // drop the weapon as an item DropWeapon( true ); #ifdef CTF // drop the flag if player was carrying it if ( gameLocal.isMultiplayer && gameLocal.mpGame.IsGametypeFlagBased() && carryingFlag ) { DropFlag(); } #endif if ( !g_testDeath.GetBool() ) { LookAtKiller( inflictor, attacker ); } if ( gameLocal.isMultiplayer || g_testDeath.GetBool() ) { idPlayer *killer = NULL; // no gibbing in MP. Event_Gib will early out in MP if ( attacker->IsType( idPlayer::Type ) ) { killer = static_cast<idPlayer*>(attacker); if ( health < -20 || killer->PowerUpActive( BERSERK ) ) { gibDeath = true; gibsDir = dir; gibsLaunched = false; } } gameLocal.mpGame.PlayerDeath( this, killer, isTelefragged ); } else { physicsObj.SetContents( CONTENTS_CORPSE | CONTENTS_MONSTERCLIP ); } ClearPowerUps(); UpdateVisuals(); isChatting = false; } /* ===================== idPlayer::GetAIAimTargets Returns positions for the AI to aim at. ===================== */ void idPlayer::GetAIAimTargets( const idVec3 &lastSightPos, idVec3 &headPos, idVec3 &chestPos ) { idVec3 offset; idMat3 axis; idVec3 origin; origin = lastSightPos - physicsObj.GetOrigin(); GetJointWorldTransform( chestJoint, gameLocal.time, offset, axis ); headPos = offset + origin; GetJointWorldTransform( headJoint, gameLocal.time, offset, axis ); chestPos = offset + origin; } /* ================ idPlayer::DamageFeedback callback function for when another entity received damage from this entity. damage can be adjusted and returned to the caller. ================ */ void idPlayer::DamageFeedback( idEntity *victim, idEntity *inflictor, int &damage ) { assert( !gameLocal.isClient ); damage *= PowerUpModifier( BERSERK ); if ( damage && ( victim != this ) && ( victim->IsType( idActor::Type ) || victim->IsType( idDamagable::Type ) ) ) { idPlayer *victimPlayer = NULL; /* No damage feedback sound for hitting friendlies in CTF */ if ( victim->IsType( idPlayer::Type ) ) { victimPlayer = static_cast<idPlayer*>(victim); } if ( gameLocal.mpGame.IsGametypeFlagBased() && victimPlayer && this->team == victimPlayer->team ) { /* Do nothing ... */ } else { SetLastHitTime( gameLocal.time ); } } } /* ================= idPlayer::CalcDamagePoints Calculates how many health and armor points will be inflicted, but doesn't actually do anything with them. This is used to tell when an attack would have killed the player, possibly allowing a "saving throw" ================= */ void idPlayer::CalcDamagePoints( idEntity *inflictor, idEntity *attacker, const idDict *damageDef, const float damageScale, const int location, int *health, int *armor ) { int damage; int armorSave; damageDef->GetInt( "damage", "20", damage ); damage = GetDamageForLocation( damage, location ); idPlayer *player = attacker->IsType( idPlayer::Type ) ? static_cast<idPlayer*>(attacker) : NULL; if ( !gameLocal.isMultiplayer ) { if ( inflictor != gameLocal.world ) { switch ( g_skill.GetInteger() ) { case 0: damage *= 0.80f; if ( damage < 1 ) { damage = 1; } break; case 2: damage *= 1.70f; break; case 3: damage *= 3.5f; break; default: break; } } } damage *= damageScale; // always give half damage if hurting self if ( attacker == this ) { if ( gameLocal.isMultiplayer ) { // only do this in mp so single player plasma and rocket splash is very dangerous in close quarters damage *= damageDef->GetFloat( "selfDamageScale", "0.5" ); } else { damage *= damageDef->GetFloat( "selfDamageScale", "1" ); } } // check for completely getting out of the damage if ( !damageDef->GetBool( "noGod" ) ) { // check for godmode if ( godmode ) { damage = 0; } #ifdef _D3XP //Invulnerability is just like god mode if( PowerUpActive( INVULNERABILITY ) ) { damage = 0; } #endif } // inform the attacker that they hit someone attacker->DamageFeedback( this, inflictor, damage ); // save some from armor if ( !damageDef->GetBool( "noArmor" ) ) { float armor_protection; armor_protection = ( gameLocal.isMultiplayer ) ? g_armorProtectionMP.GetFloat() : g_armorProtection.GetFloat(); armorSave = ceil( damage * armor_protection ); if ( armorSave >= inventory.armor ) { armorSave = inventory.armor; } if ( !damage ) { armorSave = 0; } else if ( armorSave >= damage ) { armorSave = damage - 1; damage = 1; } else { damage -= armorSave; } } else { armorSave = 0; } // check for team damage if ( gameLocal.mpGame.IsGametypeTeamBased() /* CTF */ && !gameLocal.serverInfo.GetBool( "si_teamDamage" ) && !damageDef->GetBool( "noTeam" ) && player && player != this // you get self damage no matter what && player->team == team ) { damage = 0; } *health = damage; *armor = armorSave; } /* ============ Damage this entity that is being damaged inflictor entity that is causing the damage attacker entity that caused the inflictor to damage targ example: this=monster, inflictor=rocket, attacker=player dir direction of the attack for knockback in global space damageDef an idDict with all the options for damage effects inflictor, attacker, dir, and point can be NULL for environmental effects ============ */ void idPlayer::Damage( idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location ) { idVec3 kick; int damage; int armorSave; int knockback; idVec3 damage_from; idVec3 localDamageVector; float attackerPushScale; #ifdef _D3XP SetTimeState ts( timeGroup ); #endif // damage is only processed on server if ( gameLocal.isClient ) { return; } if ( !fl.takedamage || noclip || spectating || gameLocal.inCinematic ) { return; } if ( !inflictor ) { inflictor = gameLocal.world; } if ( !attacker ) { attacker = gameLocal.world; } if ( attacker->IsType( idAI::Type ) ) { #ifndef _D3XP if ( PowerUpActive( BERSERK ) ) { return; } #endif // don't take damage from monsters during influences if ( influenceActive != 0 ) { return; } } const idDeclEntityDef *damageDef = gameLocal.FindEntityDef( damageDefName, false ); if ( !damageDef ) { gameLocal.Warning( "Unknown damageDef '%s'", damageDefName ); return; } if ( damageDef->dict.GetBool( "ignore_player" ) ) { return; } CalcDamagePoints( inflictor, attacker, &damageDef->dict, damageScale, location, &damage, &armorSave ); // determine knockback damageDef->dict.GetInt( "knockback", "20", knockback ); /*#ifdef _D3XP idPlayer *player = attacker->IsType( idPlayer::Type ) ? static_cast<idPlayer*>(attacker) : NULL; if ( gameLocal.mpGame.IsGametypeTeamBased() && !gameLocal.serverInfo.GetBool( "si_teamDamage" ) && !damageDef->dict.GetBool( "noTeam" ) && player && player != this // you get self damage no matter what && player->team == team ) { knockback = 0; } #endif*/ if ( knockback != 0 && !fl.noknockback ) { if ( attacker == this ) { damageDef->dict.GetFloat( "attackerPushScale", "0", attackerPushScale ); } else { attackerPushScale = 1.0f; } kick = dir; kick.Normalize(); kick *= g_knockback.GetFloat() * knockback * attackerPushScale / 200.0f; physicsObj.SetLinearVelocity( physicsObj.GetLinearVelocity() + kick ); // set the timer so that the player can't cancel out the movement immediately physicsObj.SetKnockBack( idMath::ClampInt( 50, 200, knockback * 2 ) ); } // give feedback on the player view and audibly when armor is helping if ( armorSave ) { inventory.armor -= armorSave; if ( gameLocal.time > lastArmorPulse + 200 ) { StartSound( "snd_hitArmor", SND_CHANNEL_ITEM, 0, false, NULL ); } lastArmorPulse = gameLocal.time; } if ( damageDef->dict.GetBool( "burn" ) ) { StartSound( "snd_burn", SND_CHANNEL_BODY3, 0, false, NULL ); } else if ( damageDef->dict.GetBool( "no_air" ) ) { if ( !armorSave && health > 0 ) { StartSound( "snd_airGasp", SND_CHANNEL_ITEM, 0, false, NULL ); } } if ( g_debugDamage.GetInteger() ) { gameLocal.Printf( "client:%i health:%i damage:%i armor:%i\n", entityNumber, health, damage, armorSave ); } // move the world direction vector to local coordinates damage_from = dir; damage_from.Normalize(); viewAxis.ProjectVector( damage_from, localDamageVector ); // add to the damage inflicted on a player this frame // the total will be turned into screen blends and view angle kicks // at the end of the frame if ( health > 0 ) { playerView.DamageImpulse( localDamageVector, &damageDef->dict ); } // do the damage if ( damage > 0 ) { if ( !gameLocal.isMultiplayer ) { #ifdef _D3XP float scale = new_g_damageScale; #else float scale = g_damageScale.GetFloat(); #endif if ( g_useDynamicProtection.GetBool() && g_skill.GetInteger() < 2 ) { if ( gameLocal.time > lastDmgTime + 500 && scale > 0.25f ) { scale -= 0.05f; #ifdef _D3XP new_g_damageScale = scale; #else g_damageScale.SetFloat( scale ); #endif } } if ( scale > 0.0f ) { damage *= scale; } } if ( damage < 1 ) { damage = 1; } health -= damage; if ( health <= 0 ) { if ( health < -999 ) { health = -999; } isTelefragged = damageDef->dict.GetBool( "telefrag" ); lastDmgTime = gameLocal.time; Killed( inflictor, attacker, damage, dir, location ); } else { // force a blink blink_time = 0; // let the anim script know we took damage AI_PAIN = Pain( inflictor, attacker, damage, dir, location ); if ( !g_testDeath.GetBool() ) { lastDmgTime = gameLocal.time; } } } else { // don't accumulate impulses if ( af.IsLoaded() ) { // clear impacts af.Rest(); // physics is turned off by calling af.Rest() BecomeActive( TH_PHYSICS ); } } lastDamageDef = damageDef->Index(); lastDamageDir = damage_from; lastDamageLocation = location; } /* =========== idPlayer::Teleport ============ */ void idPlayer::Teleport( const idVec3 &origin, const idAngles &angles, idEntity *destination ) { idVec3 org; if ( weapon.GetEntity() ) { weapon.GetEntity()->LowerWeapon(); } SetOrigin( origin + idVec3( 0, 0, CM_CLIP_EPSILON ) ); if ( !gameLocal.isMultiplayer && GetFloorPos( 16.0f, org ) ) { SetOrigin( org ); } // clear the ik heights so model doesn't appear in the wrong place walkIK.EnableAll(); GetPhysics()->SetLinearVelocity( vec3_origin ); SetViewAngles( angles ); legsYaw = 0.0f; idealLegsYaw = 0.0f; oldViewYaw = viewAngles.yaw; if ( gameLocal.isMultiplayer ) { playerView.Flash( colorWhite, 140 ); } UpdateVisuals(); teleportEntity = destination; if ( !gameLocal.isClient && !noclip ) { if ( gameLocal.isMultiplayer ) { // kill anything at the new position or mark for kill depending on immediate or delayed teleport gameLocal.KillBox( this, destination != NULL ); } else { // kill anything at the new position gameLocal.KillBox( this, true ); } } #ifdef _D3XP if ( PowerUpActive( HELLTIME ) ) { StopHelltime(); } #endif } /* ==================== idPlayer::SetPrivateCameraView ==================== */ void idPlayer::SetPrivateCameraView( idCamera *camView ) { privateCameraView = camView; if ( camView ) { StopFiring(); Hide(); } else { if ( !spectating ) { Show(); } } } /* ==================== idPlayer::DefaultFov Returns the base FOV ==================== */ float idPlayer::DefaultFov( void ) const { float fov; fov = g_fov.GetFloat(); if ( gameLocal.isMultiplayer ) { if ( fov < 90.0f ) { return 90.0f; } else if ( fov > 110.0f ) { return 110.0f; } } return fov; } /* ==================== idPlayer::CalcFov Fixed fov at intermissions, otherwise account for fov variable and zooms. ==================== */ float idPlayer::CalcFov( bool honorZoom ) { float fov; if ( fxFov ) { return DefaultFov() + 10.0f + cos( ( gameLocal.time + 2000 ) * 0.01 ) * 10.0f; } if ( influenceFov ) { return influenceFov; } if ( zoomFov.IsDone( gameLocal.time ) ) { fov = ( honorZoom && usercmd.buttons & BUTTON_ZOOM ) && weapon.GetEntity() ? weapon.GetEntity()->GetZoomFov() : DefaultFov(); } else { fov = zoomFov.GetCurrentValue( gameLocal.time ); } // bound normal viewsize if ( fov < 1 ) { fov = 1; } else if ( fov > 179 ) { fov = 179; } return fov; } /* ============== idPlayer::GunTurningOffset generate a rotational offset for the gun based on the view angle history in loggedViewAngles ============== */ idAngles idPlayer::GunTurningOffset( void ) { idAngles a; a.Zero(); if ( gameLocal.framenum < NUM_LOGGED_VIEW_ANGLES ) { return a; } idAngles current = loggedViewAngles[ gameLocal.framenum & (NUM_LOGGED_VIEW_ANGLES-1) ]; idAngles av, base; int weaponAngleOffsetAverages; float weaponAngleOffsetScale, weaponAngleOffsetMax; weapon.GetEntity()->GetWeaponAngleOffsets( &weaponAngleOffsetAverages, &weaponAngleOffsetScale, &weaponAngleOffsetMax ); av = current; // calcualte this so the wrap arounds work properly for ( int j = 1 ; j < weaponAngleOffsetAverages ; j++ ) { idAngles a2 = loggedViewAngles[ ( gameLocal.framenum - j ) & (NUM_LOGGED_VIEW_ANGLES-1) ]; idAngles delta = a2 - current; if ( delta[1] > 180 ) { delta[1] -= 360; } else if ( delta[1] < -180 ) { delta[1] += 360; } av += delta * ( 1.0f / weaponAngleOffsetAverages ); } a = ( av - current ) * weaponAngleOffsetScale; for ( int i = 0 ; i < 3 ; i++ ) { if ( a[i] < -weaponAngleOffsetMax ) { a[i] = -weaponAngleOffsetMax; } else if ( a[i] > weaponAngleOffsetMax ) { a[i] = weaponAngleOffsetMax; } } return a; } /* ============== idPlayer::GunAcceleratingOffset generate a positional offset for the gun based on the movement history in loggedAccelerations ============== */ idVec3 idPlayer::GunAcceleratingOffset( void ) { idVec3 ofs; float weaponOffsetTime, weaponOffsetScale; ofs.Zero(); weapon.GetEntity()->GetWeaponTimeOffsets( &weaponOffsetTime, &weaponOffsetScale ); int stop = currentLoggedAccel - NUM_LOGGED_ACCELS; if ( stop < 0 ) { stop = 0; } for ( int i = currentLoggedAccel-1 ; i > stop ; i-- ) { loggedAccel_t *acc = &loggedAccel[i&(NUM_LOGGED_ACCELS-1)]; float f; float t = gameLocal.time - acc->time; if ( t >= weaponOffsetTime ) { break; // remainder are too old to care about } f = t / weaponOffsetTime; f = ( cos( f * 2.0f * idMath::PI ) - 1.0f ) * 0.5f; ofs += f * weaponOffsetScale * acc->dir; } return ofs; } /* ============== idPlayer::CalculateViewWeaponPos Calculate the bobbing position of the view weapon ============== */ void idPlayer::CalculateViewWeaponPos( idVec3 &origin, idMat3 &axis ) { float scale; float fracsin; idAngles angles; int delta; // CalculateRenderView must have been called first const idVec3 &viewOrigin = firstPersonViewOrigin; const idMat3 &viewAxis = firstPersonViewAxis; // these cvars are just for hand tweaking before moving a value to the weapon def idVec3 gunpos( g_gun_x.GetFloat(), g_gun_y.GetFloat(), g_gun_z.GetFloat() ); // as the player changes direction, the gun will take a small lag idVec3 gunOfs = GunAcceleratingOffset(); origin = viewOrigin + ( gunpos + gunOfs ) * viewAxis; // on odd legs, invert some angles if ( bobCycle & 128 ) { scale = -xyspeed; } else { scale = xyspeed; } // gun angles from bobbing angles.roll = scale * bobfracsin * 0.005f; angles.yaw = scale * bobfracsin * 0.01f; angles.pitch = xyspeed * bobfracsin * 0.005f; // gun angles from turning if ( gameLocal.isMultiplayer ) { idAngles offset = GunTurningOffset(); offset *= g_mpWeaponAngleScale.GetFloat(); angles += offset; } else { angles += GunTurningOffset(); } idVec3 gravity = physicsObj.GetGravityNormal(); // drop the weapon when landing after a jump / fall delta = gameLocal.time - landTime; if ( delta < LAND_DEFLECT_TIME ) { origin -= gravity * ( landChange*0.25f * delta / LAND_DEFLECT_TIME ); } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { origin -= gravity * ( landChange*0.25f * (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME ); } // speed sensitive idle drift scale = xyspeed + 40.0f; fracsin = scale * sin( MS2SEC( gameLocal.time ) ) * 0.01f; angles.roll += fracsin; angles.yaw += fracsin; angles.pitch += fracsin; axis = angles.ToMat3() * viewAxis; } /* =============== idPlayer::OffsetThirdPersonView =============== */ void idPlayer::OffsetThirdPersonView( float angle, float range, float height, bool clip ) { idVec3 view; idVec3 focusAngles; trace_t trace; idVec3 focusPoint; float focusDist; float forwardScale, sideScale; idVec3 origin; idAngles angles; idMat3 axis; idBounds bounds; angles = viewAngles; GetViewPos( origin, axis ); if ( angle ) { angles.pitch = 0.0f; } if ( angles.pitch > 45.0f ) { angles.pitch = 45.0f; // don't go too far overhead } focusPoint = origin + angles.ToForward() * THIRD_PERSON_FOCUS_DISTANCE; focusPoint.z += height; view = origin; view.z += 8 + height; angles.pitch *= 0.5f; renderView->viewaxis = angles.ToMat3() * physicsObj.GetGravityAxis(); idMath::SinCos( DEG2RAD( angle ), sideScale, forwardScale ); view -= range * forwardScale * renderView->viewaxis[ 0 ]; view += range * sideScale * renderView->viewaxis[ 1 ]; if ( clip ) { // trace a ray from the origin to the viewpoint to make sure the view isn't // in a solid block. Use an 8 by 8 block to prevent the view from near clipping anything bounds = idBounds( idVec3( -4, -4, -4 ), idVec3( 4, 4, 4 ) ); gameLocal.clip.TraceBounds( trace, origin, view, bounds, MASK_SOLID, this ); if ( trace.fraction != 1.0f ) { view = trace.endpos; view.z += ( 1.0f - trace.fraction ) * 32.0f; // try another trace to this position, because a tunnel may have the ceiling // close enough that this is poking out gameLocal.clip.TraceBounds( trace, origin, view, bounds, MASK_SOLID, this ); view = trace.endpos; } } // select pitch to look at focus point from vieword focusPoint -= view; focusDist = idMath::Sqrt( focusPoint[0] * focusPoint[0] + focusPoint[1] * focusPoint[1] ); if ( focusDist < 1.0f ) { focusDist = 1.0f; // should never happen } angles.pitch = - RAD2DEG( atan2( focusPoint.z, focusDist ) ); angles.yaw -= angle; renderView->vieworg = view; renderView->viewaxis = angles.ToMat3() * physicsObj.GetGravityAxis(); renderView->viewID = 0; } /* =============== idPlayer::GetEyePosition =============== */ idVec3 idPlayer::GetEyePosition( void ) const { idVec3 org; // use the smoothed origin if spectating another player in multiplayer if ( gameLocal.isClient && entityNumber != gameLocal.localClientNum ) { org = smoothedOrigin; } else { org = GetPhysics()->GetOrigin(); } return org + ( GetPhysics()->GetGravityNormal() * -eyeOffset.z ); } /* =============== idPlayer::GetViewPos =============== */ void idPlayer::GetViewPos( idVec3 &origin, idMat3 &axis ) const { idAngles angles; // if dead, fix the angle and don't add any kick if ( health <= 0 ) { angles.yaw = viewAngles.yaw; angles.roll = 40; angles.pitch = -15; axis = angles.ToMat3(); origin = GetEyePosition(); } else { origin = GetEyePosition() + viewBob; angles = viewAngles + viewBobAngles + playerView.AngleOffset(); axis = angles.ToMat3() * physicsObj.GetGravityAxis(); // adjust the origin based on the camera nodal distance (eye distance from neck) origin += physicsObj.GetGravityNormal() * g_viewNodalZ.GetFloat(); origin += axis[0] * g_viewNodalX.GetFloat() + axis[2] * g_viewNodalZ.GetFloat(); } } /* =============== idPlayer::CalculateFirstPersonView =============== */ void idPlayer::CalculateFirstPersonView( void ) { if ( ( pm_modelView.GetInteger() == 1 ) || ( ( pm_modelView.GetInteger() == 2 ) && ( health <= 0 ) ) ) { // Displays the view from the point of view of the "camera" joint in the player model idMat3 axis; idVec3 origin; idAngles ang; ang = viewBobAngles + playerView.AngleOffset(); ang.yaw += viewAxis[ 0 ].ToYaw(); jointHandle_t joint = animator.GetJointHandle( "camera" ); animator.GetJointTransform( joint, gameLocal.time, origin, axis ); firstPersonViewOrigin = ( origin + modelOffset ) * ( viewAxis * physicsObj.GetGravityAxis() ) + physicsObj.GetOrigin() + viewBob; firstPersonViewAxis = axis * ang.ToMat3() * physicsObj.GetGravityAxis(); } else { // offset for local bobbing and kicks GetViewPos( firstPersonViewOrigin, firstPersonViewAxis ); #if 0 // shakefrom sound stuff only happens in first person firstPersonViewAxis = firstPersonViewAxis * playerView.ShakeAxis(); #endif } } /* ================== idPlayer::GetRenderView Returns the renderView that was calculated for this tic ================== */ renderView_t *idPlayer::GetRenderView( void ) { return renderView; } /* ================== idPlayer::CalculateRenderView create the renderView for the current tic ================== */ void idPlayer::CalculateRenderView( void ) { int i; float range; if ( !renderView ) { renderView = new renderView_t; } memset( renderView, 0, sizeof( *renderView ) ); // copy global shader parms for( i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++ ) { renderView->shaderParms[ i ] = gameLocal.globalShaderParms[ i ]; } renderView->globalMaterial = gameLocal.GetGlobalMaterial(); #ifdef _D3XP renderView->time = gameLocal.slow.time; #endif // calculate size of 3D view renderView->x = 0; renderView->y = 0; renderView->width = SCREEN_WIDTH; renderView->height = SCREEN_HEIGHT; renderView->viewID = 0; // check if we should be drawing from a camera's POV if ( !noclip && (gameLocal.GetCamera() || privateCameraView) ) { // get origin, axis, and fov if ( privateCameraView ) { privateCameraView->GetViewParms( renderView ); } else { gameLocal.GetCamera()->GetViewParms( renderView ); } } else { if ( g_stopTime.GetBool() ) { renderView->vieworg = firstPersonViewOrigin; renderView->viewaxis = firstPersonViewAxis; if ( !pm_thirdPerson.GetBool() ) { // set the viewID to the clientNum + 1, so we can suppress the right player bodies and // allow the right player view weapons renderView->viewID = entityNumber + 1; } } else if ( pm_thirdPerson.GetBool() ) { OffsetThirdPersonView( pm_thirdPersonAngle.GetFloat(), pm_thirdPersonRange.GetFloat(), pm_thirdPersonHeight.GetFloat(), pm_thirdPersonClip.GetBool() ); } else if ( pm_thirdPersonDeath.GetBool() ) { range = gameLocal.time < minRespawnTime ? ( gameLocal.time + RAGDOLL_DEATH_TIME - minRespawnTime ) * ( 120.0f / RAGDOLL_DEATH_TIME ) : 120.0f; OffsetThirdPersonView( 0.0f, 20.0f + range, 0.0f, false ); } else { renderView->vieworg = firstPersonViewOrigin; renderView->viewaxis = firstPersonViewAxis; // set the viewID to the clientNum + 1, so we can suppress the right player bodies and // allow the right player view weapons renderView->viewID = entityNumber + 1; } // field of view gameLocal.CalcFov( CalcFov( true ), renderView->fov_x, renderView->fov_y ); } if ( renderView->fov_y == 0 ) { common->Error( "renderView->fov_y == 0" ); } if ( g_showviewpos.GetBool() ) { gameLocal.Printf( "%s : %s\n", renderView->vieworg.ToString(), renderView->viewaxis.ToAngles().ToString() ); } } /* ============= idPlayer::AddAIKill ============= */ void idPlayer::AddAIKill( void ) { #ifndef _D3XP int max_souls; int ammo_souls; if ( ( weapon_soulcube < 0 ) || ( inventory.weapons & ( 1 << weapon_soulcube ) ) == 0 ) { return; } assert( hud ); ammo_souls = idWeapon::GetAmmoNumForName( "ammo_souls" ); max_souls = inventory.MaxAmmoForAmmoClass( this, "ammo_souls" ); if ( inventory.ammo[ ammo_souls ] < max_souls ) { inventory.ammo[ ammo_souls ]++; if ( inventory.ammo[ ammo_souls ] >= max_souls ) { hud->HandleNamedEvent( "soulCubeReady" ); StartSound( "snd_soulcube_ready", SND_CHANNEL_ANY, 0, false, NULL ); } } #endif } /* ============= idPlayer::SetSoulCubeProjectile ============= */ void idPlayer::SetSoulCubeProjectile( idProjectile *projectile ) { soulCubeProjectile = projectile; } /* ============= idPlayer::AddProjectilesFired ============= */ void idPlayer::AddProjectilesFired( int count ) { numProjectilesFired += count; } /* ============= idPlayer::AddProjectileHites ============= */ void idPlayer::AddProjectileHits( int count ) { numProjectileHits += count; } /* ============= idPlayer::SetLastHitTime ============= */ void idPlayer::SetLastHitTime( int time ) { idPlayer *aimed = NULL; if ( time && lastHitTime != time ) { lastHitToggle ^= 1; } lastHitTime = time; if ( !time ) { // level start and inits return; } if ( gameLocal.isMultiplayer && ( time - lastSndHitTime ) > 10 ) { lastSndHitTime = time; StartSound( "snd_hit_feedback", SND_CHANNEL_ANY, SSF_PRIVATE_SOUND, false, NULL ); } if ( cursor ) { cursor->HandleNamedEvent( "hitTime" ); } if ( hud ) { if ( MPAim != -1 ) { if ( gameLocal.entities[ MPAim ] && gameLocal.entities[ MPAim ]->IsType( idPlayer::Type ) ) { aimed = static_cast< idPlayer * >( gameLocal.entities[ MPAim ] ); } assert( aimed ); // full highlight, no fade till loosing aim hud->SetStateString( "aim_text", gameLocal.userInfo[ MPAim ].GetString( "ui_name" ) ); if ( aimed ) { hud->SetStateFloat( "aim_color", aimed->colorBarIndex ); } hud->HandleNamedEvent( "aim_flash" ); MPAimHighlight = true; MPAimFadeTime = 0; } else if ( lastMPAim != -1 ) { if ( gameLocal.entities[ lastMPAim ] && gameLocal.entities[ lastMPAim ]->IsType( idPlayer::Type ) ) { aimed = static_cast< idPlayer * >( gameLocal.entities[ lastMPAim ] ); } assert( aimed ); // start fading right away hud->SetStateString( "aim_text", gameLocal.userInfo[ lastMPAim ].GetString( "ui_name" ) ); if ( aimed ) { hud->SetStateFloat( "aim_color", aimed->colorBarIndex ); } hud->HandleNamedEvent( "aim_flash" ); hud->HandleNamedEvent( "aim_fade" ); MPAimHighlight = false; MPAimFadeTime = gameLocal.realClientTime; } } } /* ============= idPlayer::SetInfluenceLevel ============= */ void idPlayer::SetInfluenceLevel( int level ) { if ( level != influenceActive ) { if ( level ) { for ( idEntity *ent = gameLocal.spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) { if ( ent->IsType( idProjectile::Type ) ) { // remove all projectiles ent->PostEventMS( &EV_Remove, 0 ); } } if ( weaponEnabled && weapon.GetEntity() ) { weapon.GetEntity()->EnterCinematic(); } } else { physicsObj.SetLinearVelocity( vec3_origin ); if ( weaponEnabled && weapon.GetEntity() ) { weapon.GetEntity()->ExitCinematic(); } } influenceActive = level; } } /* ============= idPlayer::SetInfluenceView ============= */ void idPlayer::SetInfluenceView( const char *mtr, const char *skinname, float radius, idEntity *ent ) { influenceMaterial = NULL; influenceEntity = NULL; influenceSkin = NULL; if ( mtr && *mtr ) { influenceMaterial = declManager->FindMaterial( mtr ); } if ( skinname && *skinname ) { influenceSkin = declManager->FindSkin( skinname ); if ( head.GetEntity() ) { head.GetEntity()->GetRenderEntity()->shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time ); } UpdateVisuals(); } influenceRadius = radius; if ( radius > 0.0f ) { influenceEntity = ent; } } /* ============= idPlayer::SetInfluenceFov ============= */ void idPlayer::SetInfluenceFov( float fov ) { influenceFov = fov; } /* ================ idPlayer::OnLadder ================ */ bool idPlayer::OnLadder( void ) const { return physicsObj.OnLadder(); } /* ================== idPlayer::Event_GetButtons ================== */ void idPlayer::Event_GetButtons( void ) { idThread::ReturnInt( usercmd.buttons ); } /* ================== idPlayer::Event_GetMove ================== */ void idPlayer::Event_GetMove( void ) { idVec3 move( usercmd.forwardmove, usercmd.rightmove, usercmd.upmove ); idThread::ReturnVector( move ); } /* ================ idPlayer::Event_GetViewAngles ================ */ void idPlayer::Event_GetViewAngles( void ) { idThread::ReturnVector( idVec3( viewAngles[0], viewAngles[1], viewAngles[2] ) ); } /* ================== idPlayer::Event_StopFxFov ================== */ void idPlayer::Event_StopFxFov( void ) { fxFov = false; } /* ================== idPlayer::StartFxFov ================== */ void idPlayer::StartFxFov( float duration ) { fxFov = true; PostEventSec( &EV_Player_StopFxFov, duration ); } /* ================== idPlayer::Event_EnableWeapon ================== */ void idPlayer::Event_EnableWeapon( void ) { hiddenWeapon = gameLocal.world->spawnArgs.GetBool( "no_Weapons" ); weaponEnabled = true; if ( weapon.GetEntity() ) { weapon.GetEntity()->ExitCinematic(); } } /* ================== idPlayer::Event_DisableWeapon ================== */ void idPlayer::Event_DisableWeapon( void ) { hiddenWeapon = gameLocal.world->spawnArgs.GetBool( "no_Weapons" ); weaponEnabled = false; if ( weapon.GetEntity() ) { weapon.GetEntity()->EnterCinematic(); } } #ifdef _D3XP /* ================== idPlayer::Event_GiveInventoryItem ================== */ void idPlayer::Event_GiveInventoryItem( const char* name ) { GiveInventoryItem(name); } /* ================== idPlayer::Event_RemoveInventoryItem ================== */ void idPlayer::Event_RemoveInventoryItem( const char* name ) { RemoveInventoryItem(name); } /* ================== idPlayer::Event_GetIdealWeapon ================== */ void idPlayer::Event_GetIdealWeapon( void ) { const char *weapon; if ( idealWeapon >= 0 ) { weapon = spawnArgs.GetString( va( "def_weapon%d", idealWeapon ) ); idThread::ReturnString( weapon ); } else { idThread::ReturnString( "" ); } } /* ================== idPlayer::Event_SetPowerupTime ================== */ void idPlayer::Event_SetPowerupTime( int powerup, int time ) { if ( time > 0 ) { GivePowerUp( powerup, time ); } else { ClearPowerup( powerup ); } } /* ================== idPlayer::Event_IsPowerupActive ================== */ void idPlayer::Event_IsPowerupActive( int powerup ) { idThread::ReturnInt(this->PowerUpActive(powerup) ? 1 : 0); } /* ================== idPlayer::Event_StartWarp ================== */ void idPlayer::Event_StartWarp() { playerView.AddWarp( idVec3( 0, 0, 0 ), SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 100, 1000 ); } /* ================== idPlayer::Event_StopHelltime ================== */ void idPlayer::Event_StopHelltime( int mode ) { if ( mode == 1 ) { StopHelltime( true ); } else { StopHelltime( false ); } } /* ================== idPlayer::Event_WeaponAvailable ================== */ void idPlayer::Event_WeaponAvailable( const char* name ) { idThread::ReturnInt( WeaponAvailable(name) ? 1 : 0 ); } bool idPlayer::WeaponAvailable( const char* name ) { for( int i = 0; i < MAX_WEAPONS; i++ ) { if ( inventory.weapons & ( 1 << i ) ) { const char *weap = spawnArgs.GetString( va( "def_weapon%d", i ) ); if ( !idStr::Cmp( weap, name ) ) { return true; } } } return false; } #endif /* ================== idPlayer::Event_GetCurrentWeapon ================== */ void idPlayer::Event_GetCurrentWeapon( void ) { const char *weapon; if ( currentWeapon >= 0 ) { weapon = spawnArgs.GetString( va( "def_weapon%d", currentWeapon ) ); idThread::ReturnString( weapon ); } else { idThread::ReturnString( "" ); } } /* ================== idPlayer::Event_GetPreviousWeapon ================== */ void idPlayer::Event_GetPreviousWeapon( void ) { const char *weapon; if ( previousWeapon >= 0 ) { int pw = ( gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) ) ? 0 : previousWeapon; weapon = spawnArgs.GetString( va( "def_weapon%d", pw) ); idThread::ReturnString( weapon ); } else { idThread::ReturnString( spawnArgs.GetString( "def_weapon0" ) ); } } /* ================== idPlayer::Event_SelectWeapon ================== */ void idPlayer::Event_SelectWeapon( const char *weaponName ) { int i; int weaponNum; if ( gameLocal.isClient ) { gameLocal.Warning( "Cannot switch weapons from script in multiplayer" ); return; } if ( hiddenWeapon && gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) ) { idealWeapon = weapon_fists; weapon.GetEntity()->HideWeapon(); return; } weaponNum = -1; for( i = 0; i < MAX_WEAPONS; i++ ) { if ( inventory.weapons & ( 1 << i ) ) { const char *weap = spawnArgs.GetString( va( "def_weapon%d", i ) ); if ( !idStr::Cmp( weap, weaponName ) ) { weaponNum = i; break; } } } if ( weaponNum < 0 ) { gameLocal.Warning( "%s is not carrying weapon '%s'", name.c_str(), weaponName ); return; } hiddenWeapon = false; idealWeapon = weaponNum; UpdateHudWeapon(); } /* ================== idPlayer::Event_GetWeaponEntity ================== */ void idPlayer::Event_GetWeaponEntity( void ) { idThread::ReturnEntity( weapon.GetEntity() ); } /* ================== idPlayer::Event_OpenPDA ================== */ void idPlayer::Event_OpenPDA( void ) { if ( !gameLocal.isMultiplayer ) { TogglePDA(); } } /* ================== idPlayer::Event_InPDA ================== */ void idPlayer::Event_InPDA( void ) { idThread::ReturnInt( objectiveSystemOpen ); } /* ================== idPlayer::TeleportDeath ================== */ void idPlayer::TeleportDeath( int killer ) { teleportKiller = killer; } /* ================== idPlayer::Event_ExitTeleporter ================== */ void idPlayer::Event_ExitTeleporter( void ) { idEntity *exitEnt; float pushVel; // verify and setup exitEnt = teleportEntity.GetEntity(); if ( !exitEnt ) { common->DPrintf( "Event_ExitTeleporter player %d while not being teleported\n", entityNumber ); return; } pushVel = exitEnt->spawnArgs.GetFloat( "push", "300" ); if ( gameLocal.isServer ) { ServerSendEvent( EVENT_EXIT_TELEPORTER, NULL, false, -1 ); } SetPrivateCameraView( NULL ); // setup origin and push according to the exit target SetOrigin( exitEnt->GetPhysics()->GetOrigin() + idVec3( 0, 0, CM_CLIP_EPSILON ) ); SetViewAngles( exitEnt->GetPhysics()->GetAxis().ToAngles() ); physicsObj.SetLinearVelocity( exitEnt->GetPhysics()->GetAxis()[ 0 ] * pushVel ); physicsObj.ClearPushedVelocity(); // teleport fx playerView.Flash( colorWhite, 120 ); // clear the ik heights so model doesn't appear in the wrong place walkIK.EnableAll(); UpdateVisuals(); StartSound( "snd_teleport_exit", SND_CHANNEL_ANY, 0, false, NULL ); if ( teleportKiller != -1 ) { // we got killed while being teleported Damage( gameLocal.entities[ teleportKiller ], gameLocal.entities[ teleportKiller ], vec3_origin, "damage_telefrag", 1.0f, INVALID_JOINT ); teleportKiller = -1; } else { // kill anything that would have waited at teleport exit gameLocal.KillBox( this ); } teleportEntity = NULL; } /* ================ idPlayer::ClientPredictionThink ================ */ void idPlayer::ClientPredictionThink( void ) { renderEntity_t *headRenderEnt; oldFlags = usercmd.flags; oldButtons = usercmd.buttons; usercmd = gameLocal.usercmds[ entityNumber ]; if ( entityNumber != gameLocal.localClientNum ) { // ignore attack button of other clients. that's no good for predictions usercmd.buttons &= ~BUTTON_ATTACK; } buttonMask &= usercmd.buttons; usercmd.buttons &= ~buttonMask; #ifdef _D3XP if ( mountedObject ) { usercmd.forwardmove = 0; usercmd.rightmove = 0; usercmd.upmove = 0; } #endif if ( objectiveSystemOpen ) { usercmd.forwardmove = 0; usercmd.rightmove = 0; usercmd.upmove = 0; } // clear the ik before we do anything else so the skeleton doesn't get updated twice walkIK.ClearJointMods(); if ( gameLocal.isNewFrame ) { if ( ( usercmd.flags & UCF_IMPULSE_SEQUENCE ) != ( oldFlags & UCF_IMPULSE_SEQUENCE ) ) { PerformImpulse( usercmd.impulse ); } } scoreBoardOpen = ( ( usercmd.buttons & BUTTON_SCORES ) != 0 || forceScoreBoard ); AdjustSpeed(); UpdateViewAngles(); // update the smoothed view angles if ( gameLocal.framenum >= smoothedFrame && entityNumber != gameLocal.localClientNum ) { idAngles anglesDiff = viewAngles - smoothedAngles; anglesDiff.Normalize180(); if ( idMath::Fabs( anglesDiff.yaw ) < 90.0f && idMath::Fabs( anglesDiff.pitch ) < 90.0f ) { // smoothen by pushing back to the previous angles viewAngles -= gameLocal.clientSmoothing * anglesDiff; viewAngles.Normalize180(); } smoothedAngles = viewAngles; } smoothedOriginUpdated = false; if ( !af.IsActive() ) { AdjustBodyAngles(); } if ( !isLagged ) { // don't allow client to move when lagged Move(); } // update GUIs, Items, and character interactions UpdateFocus(); // service animations if ( !spectating && !af.IsActive() ) { UpdateConditions(); UpdateAnimState(); CheckBlink(); } // clear out our pain flag so we can tell if we recieve any damage between now and the next time we think AI_PAIN = false; // calculate the exact bobbed view position, which is used to // position the view weapon, among other things CalculateFirstPersonView(); // this may use firstPersonView, or a thirdPerson / camera view CalculateRenderView(); if ( !gameLocal.inCinematic && weapon.GetEntity() && ( health > 0 ) && !( gameLocal.isMultiplayer && spectating ) ) { UpdateWeapon(); } UpdateHud(); if ( gameLocal.isNewFrame ) { UpdatePowerUps(); } UpdateDeathSkin( false ); if ( head.GetEntity() ) { headRenderEnt = head.GetEntity()->GetRenderEntity(); } else { headRenderEnt = NULL; } if ( headRenderEnt ) { if ( influenceSkin ) { headRenderEnt->customSkin = influenceSkin; } else { headRenderEnt->customSkin = NULL; } } if ( gameLocal.isMultiplayer || g_showPlayerShadow.GetBool() ) { renderEntity.suppressShadowInViewID = 0; if ( headRenderEnt ) { headRenderEnt->suppressShadowInViewID = 0; } } else { renderEntity.suppressShadowInViewID = entityNumber+1; if ( headRenderEnt ) { headRenderEnt->suppressShadowInViewID = entityNumber+1; } } // never cast shadows from our first-person muzzle flashes renderEntity.suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + entityNumber; if ( headRenderEnt ) { headRenderEnt->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + entityNumber; } if ( !gameLocal.inCinematic ) { UpdateAnimation(); } #ifdef _D3XP if ( enviroSuitLight.IsValid() ) { idAngles lightAng = firstPersonViewAxis.ToAngles(); idVec3 lightOrg = firstPersonViewOrigin; const idDict *lightDef = gameLocal.FindEntityDefDict( "envirosuit_light", false ); idVec3 enviroOffset = lightDef->GetVector( "enviro_offset" ); idVec3 enviroAngleOffset = lightDef->GetVector( "enviro_angle_offset" ); lightOrg += (enviroOffset.x * firstPersonViewAxis[0]); lightOrg += (enviroOffset.y * firstPersonViewAxis[1]); lightOrg += (enviroOffset.z * firstPersonViewAxis[2]); lightAng.pitch += enviroAngleOffset.x; lightAng.yaw += enviroAngleOffset.y; lightAng.roll += enviroAngleOffset.z; enviroSuitLight.GetEntity()->GetPhysics()->SetOrigin( lightOrg ); enviroSuitLight.GetEntity()->GetPhysics()->SetAxis( lightAng.ToMat3() ); enviroSuitLight.GetEntity()->UpdateVisuals(); enviroSuitLight.GetEntity()->Present(); } #endif if ( gameLocal.isMultiplayer ) { DrawPlayerIcons(); } Present(); UpdateDamageEffects(); LinkCombat(); if ( gameLocal.isNewFrame && entityNumber == gameLocal.localClientNum ) { playerView.CalculateShake(); } #ifdef _D3XP // determine if portal sky is in pvs pvsHandle_t clientPVS = gameLocal.pvs.SetupCurrentPVS( GetPVSAreas(), GetNumPVSAreas() ); gameLocal.portalSkyActive = gameLocal.pvs.CheckAreasForPortalSky( clientPVS, GetPhysics()->GetOrigin() ); gameLocal.pvs.FreeCurrentPVS( clientPVS ); #endif } /* ================ idPlayer::GetPhysicsToVisualTransform ================ */ bool idPlayer::GetPhysicsToVisualTransform( idVec3 &origin, idMat3 &axis ) { if ( af.IsActive() ) { af.GetPhysicsToVisualTransform( origin, axis ); return true; } // smoothen the rendered origin and angles of other clients // smooth self origin if snapshots are telling us prediction is off if ( gameLocal.isClient && gameLocal.framenum >= smoothedFrame && ( entityNumber != gameLocal.localClientNum || selfSmooth ) ) { // render origin and axis idMat3 renderAxis = viewAxis * GetPhysics()->GetAxis(); idVec3 renderOrigin = GetPhysics()->GetOrigin() + modelOffset * renderAxis; // update the smoothed origin if ( !smoothedOriginUpdated ) { idVec2 originDiff = renderOrigin.ToVec2() - smoothedOrigin.ToVec2(); if ( originDiff.LengthSqr() < Square( 100.0f ) ) { // smoothen by pushing back to the previous position if ( selfSmooth ) { assert( entityNumber == gameLocal.localClientNum ); renderOrigin.ToVec2() -= net_clientSelfSmoothing.GetFloat() * originDiff; } else { renderOrigin.ToVec2() -= gameLocal.clientSmoothing * originDiff; } } smoothedOrigin = renderOrigin; smoothedFrame = gameLocal.framenum; smoothedOriginUpdated = true; } axis = idAngles( 0.0f, smoothedAngles.yaw, 0.0f ).ToMat3(); origin = ( smoothedOrigin - GetPhysics()->GetOrigin() ) * axis.Transpose(); } else { axis = viewAxis; origin = modelOffset; } return true; } /* ================ idPlayer::GetPhysicsToSoundTransform ================ */ bool idPlayer::GetPhysicsToSoundTransform( idVec3 &origin, idMat3 &axis ) { idCamera *camera; if ( privateCameraView ) { camera = privateCameraView; } else { camera = gameLocal.GetCamera(); } if ( camera ) { renderView_t view; memset( &view, 0, sizeof( view ) ); camera->GetViewParms( &view ); origin = view.vieworg; axis = view.viewaxis; return true; } else { return idActor::GetPhysicsToSoundTransform( origin, axis ); } } /* ================ idPlayer::WriteToSnapshot ================ */ void idPlayer::WriteToSnapshot( idBitMsgDelta &msg ) const { physicsObj.WriteToSnapshot( msg ); WriteBindToSnapshot( msg ); msg.WriteDeltaFloat( 0.0f, deltaViewAngles[0] ); msg.WriteDeltaFloat( 0.0f, deltaViewAngles[1] ); msg.WriteDeltaFloat( 0.0f, deltaViewAngles[2] ); msg.WriteShort( health ); msg.WriteBits( gameLocal.ServerRemapDecl( -1, DECL_ENTITYDEF, lastDamageDef ), gameLocal.entityDefBits ); msg.WriteDir( lastDamageDir, 9 ); msg.WriteShort( lastDamageLocation ); msg.WriteBits( idealWeapon, idMath::BitsForInteger( MAX_WEAPONS ) ); msg.WriteBits( inventory.weapons, MAX_WEAPONS ); msg.WriteBits( weapon.GetSpawnId(), 32 ); msg.WriteBits( spectator, idMath::BitsForInteger( MAX_CLIENTS ) ); msg.WriteBits( lastHitToggle, 1 ); msg.WriteBits( weaponGone, 1 ); msg.WriteBits( isLagged, 1 ); msg.WriteBits( isChatting, 1 ); #ifdef CTF /* Needed for the scoreboard */ msg.WriteBits( carryingFlag, 1 ); #endif #ifdef _D3XP msg.WriteBits( enviroSuitLight.GetSpawnId(), 32 ); #endif } /* ================ idPlayer::ReadFromSnapshot ================ */ void idPlayer::ReadFromSnapshot( const idBitMsgDelta &msg ) { int i, oldHealth, newIdealWeapon, weaponSpawnId; bool newHitToggle, stateHitch; if ( snapshotSequence - lastSnapshotSequence > 1 ) { stateHitch = true; } else { stateHitch = false; } lastSnapshotSequence = snapshotSequence; oldHealth = health; physicsObj.ReadFromSnapshot( msg ); ReadBindFromSnapshot( msg ); deltaViewAngles[0] = msg.ReadDeltaFloat( 0.0f ); deltaViewAngles[1] = msg.ReadDeltaFloat( 0.0f ); deltaViewAngles[2] = msg.ReadDeltaFloat( 0.0f ); health = msg.ReadShort(); lastDamageDef = gameLocal.ClientRemapDecl( DECL_ENTITYDEF, msg.ReadBits( gameLocal.entityDefBits ) ); lastDamageDir = msg.ReadDir( 9 ); lastDamageLocation = msg.ReadShort(); newIdealWeapon = msg.ReadBits( idMath::BitsForInteger( MAX_WEAPONS ) ); inventory.weapons = msg.ReadBits( MAX_WEAPONS ); weaponSpawnId = msg.ReadBits( 32 ); spectator = msg.ReadBits( idMath::BitsForInteger( MAX_CLIENTS ) ); newHitToggle = msg.ReadBits( 1 ) != 0; weaponGone = msg.ReadBits( 1 ) != 0; isLagged = msg.ReadBits( 1 ) != 0; isChatting = msg.ReadBits( 1 ) != 0; #ifdef CTF carryingFlag = msg.ReadBits( 1 ) != 0; #endif #ifdef _D3XP int enviroSpawnId; enviroSpawnId = msg.ReadBits( 32 ); enviroSuitLight.SetSpawnId( enviroSpawnId ); #endif // no msg reading below this if ( weapon.SetSpawnId( weaponSpawnId ) ) { if ( weapon.GetEntity() ) { // maintain ownership locally weapon.GetEntity()->SetOwner( this ); } currentWeapon = -1; } // if not a local client assume the client has all ammo types if ( entityNumber != gameLocal.localClientNum ) { for( i = 0; i < AMMO_NUMTYPES; i++ ) { inventory.ammo[ i ] = 999; } } if ( oldHealth > 0 && health <= 0 ) { if ( stateHitch ) { // so we just hide and don't show a death skin UpdateDeathSkin( true ); } // die AI_DEAD = true; ClearPowerUps(); SetAnimState( ANIMCHANNEL_LEGS, "Legs_Death", 4 ); SetAnimState( ANIMCHANNEL_TORSO, "Torso_Death", 4 ); SetWaitState( "" ); animator.ClearAllJoints(); if ( entityNumber == gameLocal.localClientNum ) { playerView.Fade( colorBlack, 12000 ); } StartRagdoll(); physicsObj.SetMovementType( PM_DEAD ); if ( !stateHitch ) { StartSound( "snd_death", SND_CHANNEL_VOICE, 0, false, NULL ); } if ( weapon.GetEntity() ) { weapon.GetEntity()->OwnerDied(); } } else if ( oldHealth <= 0 && health > 0 ) { // respawn Init(); StopRagdoll(); SetPhysics( &physicsObj ); physicsObj.EnableClip(); SetCombatContents( true ); } else if ( health < oldHealth && health > 0 ) { if ( stateHitch ) { lastDmgTime = gameLocal.time; } else { // damage feedback const idDeclEntityDef *def = static_cast<const idDeclEntityDef *>( declManager->DeclByIndex( DECL_ENTITYDEF, lastDamageDef, false ) ); if ( def ) { playerView.DamageImpulse( lastDamageDir * viewAxis.Transpose(), &def->dict ); AI_PAIN = Pain( NULL, NULL, oldHealth - health, lastDamageDir, lastDamageLocation ); lastDmgTime = gameLocal.time; } else { common->Warning( "NET: no damage def for damage feedback '%d'\n", lastDamageDef ); } } } else if ( health > oldHealth && PowerUpActive( MEGAHEALTH ) && !stateHitch ) { // just pulse, for any health raise healthPulse = true; } #ifdef _D3XP // If the player is alive, restore proper physics object if ( health > 0 && IsActiveAF() ) { StopRagdoll(); SetPhysics( &physicsObj ); physicsObj.EnableClip(); SetCombatContents( true ); } #endif if ( idealWeapon != newIdealWeapon ) { if ( stateHitch ) { weaponCatchup = true; } idealWeapon = newIdealWeapon; UpdateHudWeapon(); } if ( lastHitToggle != newHitToggle ) { SetLastHitTime( gameLocal.realClientTime ); } if ( msg.HasChanged() ) { UpdateVisuals(); } } /* ================ idPlayer::WritePlayerStateToSnapshot ================ */ void idPlayer::WritePlayerStateToSnapshot( idBitMsgDelta &msg ) const { int i; msg.WriteByte( bobCycle ); msg.WriteInt( stepUpTime ); msg.WriteFloat( stepUpDelta ); #ifdef _D3XP msg.WriteInt( inventory.weapons ); #else msg.WriteShort( inventory.weapons ); #endif msg.WriteByte( inventory.armor ); for( i = 0; i < AMMO_NUMTYPES; i++ ) { msg.WriteBits( inventory.ammo[i], ASYNC_PLAYER_INV_AMMO_BITS ); } for( i = 0; i < MAX_WEAPONS; i++ ) { msg.WriteBits( inventory.clip[i], ASYNC_PLAYER_INV_CLIP_BITS ); } } /* ================ idPlayer::ReadPlayerStateFromSnapshot ================ */ void idPlayer::ReadPlayerStateFromSnapshot( const idBitMsgDelta &msg ) { int i, ammo; bobCycle = msg.ReadByte(); stepUpTime = msg.ReadInt(); stepUpDelta = msg.ReadFloat(); #ifdef _D3XP inventory.weapons = msg.ReadInt(); #else inventory.weapons = msg.ReadShort(); #endif inventory.armor = msg.ReadByte(); for( i = 0; i < AMMO_NUMTYPES; i++ ) { ammo = msg.ReadBits( ASYNC_PLAYER_INV_AMMO_BITS ); if ( gameLocal.time >= inventory.ammoPredictTime ) { inventory.ammo[ i ] = ammo; } } for( i = 0; i < MAX_WEAPONS; i++ ) { inventory.clip[i] = msg.ReadBits( ASYNC_PLAYER_INV_CLIP_BITS ); } } /* ================ idPlayer::ServerReceiveEvent ================ */ bool idPlayer::ServerReceiveEvent( int event, int time, const idBitMsg &msg ) { if ( idEntity::ServerReceiveEvent( event, time, msg ) ) { return true; } // client->server events switch( event ) { case EVENT_IMPULSE: { PerformImpulse( msg.ReadBits( 6 ) ); return true; } default: { return false; } } } /* ================ idPlayer::ClientReceiveEvent ================ */ bool idPlayer::ClientReceiveEvent( int event, int time, const idBitMsg &msg ) { int powerup; bool start; switch ( event ) { case EVENT_EXIT_TELEPORTER: Event_ExitTeleporter(); return true; case EVENT_ABORT_TELEPORTER: SetPrivateCameraView( NULL ); return true; case EVENT_POWERUP: { powerup = msg.ReadShort(); start = msg.ReadBits( 1 ) != 0; if ( start ) { GivePowerUp( powerup, 0 ); } else { ClearPowerup( powerup ); } return true; } #ifdef _D3XP case EVENT_PICKUPNAME: { char buf[MAX_EVENT_PARAM_SIZE]; msg.ReadString(buf, MAX_EVENT_PARAM_SIZE); inventory.AddPickupName(buf, "", this); //_D3XP return true; } #endif case EVENT_SPECTATE: { bool spectate = ( msg.ReadBits( 1 ) != 0 ); Spectate( spectate ); return true; } case EVENT_ADD_DAMAGE_EFFECT: { if ( spectating ) { // if we're spectating, ignore // happens if the event and the spectate change are written on the server during the same frame (fraglimit) return true; } break; } default: break; } return idActor::ClientReceiveEvent( event, time, msg ); } /* ================ idPlayer::Hide ================ */ void idPlayer::Hide( void ) { idWeapon *weap; idActor::Hide(); weap = weapon.GetEntity(); if ( weap ) { weap->HideWorldModel(); } } /* ================ idPlayer::Show ================ */ void idPlayer::Show( void ) { idWeapon *weap; idActor::Show(); weap = weapon.GetEntity(); if ( weap ) { weap->ShowWorldModel(); } } /* =============== idPlayer::StartAudioLog =============== */ void idPlayer::StartAudioLog( void ) { if ( hud ) { hud->HandleNamedEvent( "audioLogUp" ); } } /* =============== idPlayer::StopAudioLog =============== */ void idPlayer::StopAudioLog( void ) { if ( hud ) { hud->HandleNamedEvent( "audioLogDown" ); } } /* =============== idPlayer::ShowTip =============== */ void idPlayer::ShowTip( const char *title, const char *tip, bool autoHide ) { if ( tipUp ) { return; } hud->SetStateString( "tip", tip ); hud->SetStateString( "tiptitle", title ); hud->HandleNamedEvent( "tipWindowUp" ); if ( autoHide ) { PostEventSec( &EV_Player_HideTip, 5.0f ); } tipUp = true; } /* =============== idPlayer::HideTip =============== */ void idPlayer::HideTip( void ) { hud->HandleNamedEvent( "tipWindowDown" ); tipUp = false; } /* =============== idPlayer::Event_HideTip =============== */ void idPlayer::Event_HideTip( void ) { HideTip(); } /* =============== idPlayer::ShowObjective =============== */ void idPlayer::ShowObjective( const char *obj ) { hud->HandleNamedEvent( obj ); objectiveUp = true; } /* =============== idPlayer::HideObjective =============== */ void idPlayer::HideObjective( void ) { hud->HandleNamedEvent( "closeObjective" ); objectiveUp = false; } /* =============== idPlayer::Event_StopAudioLog =============== */ void idPlayer::Event_StopAudioLog( void ) { StopAudioLog(); } /* =============== idPlayer::SetSpectateOrigin =============== */ void idPlayer::SetSpectateOrigin( void ) { idVec3 neworig; neworig = GetPhysics()->GetOrigin(); neworig[ 2 ] += EyeHeight(); neworig[ 2 ] += 25; SetOrigin( neworig ); } /* =============== idPlayer::RemoveWeapon =============== */ void idPlayer::RemoveWeapon( const char *weap ) { if ( weap && *weap ) { inventory.Drop( spawnArgs, spawnArgs.GetString( weap ), -1 ); } } /* =============== idPlayer::CanShowWeaponViewmodel =============== */ bool idPlayer::CanShowWeaponViewmodel( void ) const { return showWeaponViewModel; } /* =============== idPlayer::SetLevelTrigger =============== */ void idPlayer::SetLevelTrigger( const char *levelName, const char *triggerName ) { if ( levelName && *levelName && triggerName && *triggerName ) { idLevelTriggerInfo lti; lti.levelName = levelName; lti.triggerName = triggerName; inventory.levelTriggers.Append( lti ); } } /* =============== idPlayer::Event_LevelTrigger =============== */ void idPlayer::Event_LevelTrigger( void ) { idStr mapName = gameLocal.GetMapName(); mapName.StripPath(); mapName.StripFileExtension(); for ( int i = inventory.levelTriggers.Num() - 1; i >= 0; i-- ) { if ( idStr::Icmp( mapName, inventory.levelTriggers[i].levelName) == 0 ){ idEntity *ent = gameLocal.FindEntity( inventory.levelTriggers[i].triggerName ); if ( ent ) { ent->PostEventMS( &EV_Activate, 1, this ); } } } } /* =============== idPlayer::Event_Gibbed =============== */ void idPlayer::Event_Gibbed( void ) { // do nothing } /* =============== idPlayer::UpdatePlayerIcons =============== */ void idPlayer::UpdatePlayerIcons( void ) { int time = networkSystem->ServerGetClientTimeSinceLastPacket( entityNumber ); if ( time > cvarSystem->GetCVarInteger( "net_clientMaxPrediction" ) ) { isLagged = true; } else { isLagged = false; } // TODO: chatting, PDA, etc? } /* =============== idPlayer::DrawPlayerIcons =============== */ void idPlayer::DrawPlayerIcons( void ) { if ( !NeedsIcon() ) { playerIcon.FreeIcon(); return; } #ifdef CTF // Never draw icons for hidden players. if ( this->IsHidden() ) return; #endif playerIcon.Draw( this, headJoint ); } /* =============== idPlayer::HidePlayerIcons =============== */ void idPlayer::HidePlayerIcons( void ) { playerIcon.FreeIcon(); } /* =============== idPlayer::NeedsIcon ============== */ bool idPlayer::NeedsIcon( void ) { // local clients don't render their own icons... they're only info for other clients #ifdef CTF // always draw icons in CTF games return entityNumber != gameLocal.localClientNum && ( ( g_CTFArrows.GetBool() && gameLocal.mpGame.IsGametypeFlagBased() && !IsHidden() && !AI_DEAD ) || ( isLagged || isChatting ) ); #else return entityNumber != gameLocal.localClientNum && ( isLagged || isChatting ); #endif } #ifdef CTF /* =============== idPlayer::DropFlag() ============== */ void idPlayer::DropFlag( void ) { if ( !carryingFlag || !gameLocal.isMultiplayer || !gameLocal.mpGame.IsGametypeFlagBased() ) /* CTF */ return; idEntity * entity = gameLocal.mpGame.GetTeamFlag( 1 - this->latchedTeam ); if ( entity ) { idItemTeam * item = static_cast<idItemTeam*>(entity); if ( item->carried && !item->dropped ) { item->Drop( health <= 0 ); carryingFlag = false; } } } void idPlayer::ReturnFlag() { if ( !carryingFlag || !gameLocal.isMultiplayer || !gameLocal.mpGame.IsGametypeFlagBased() ) /* CTF */ return; idEntity * entity = gameLocal.mpGame.GetTeamFlag( 1 - this->latchedTeam ); if ( entity ) { idItemTeam * item = static_cast<idItemTeam*>(entity); if ( item->carried && !item->dropped ) { item->Return(); carryingFlag = false; } } } void idPlayer::FreeModelDef( void ) { idAFEntity_Base::FreeModelDef(); if ( gameLocal.isMultiplayer && gameLocal.mpGame.IsGametypeFlagBased() ) playerIcon.FreeIcon(); } #endif
411
0.979244
1
0.979244
game-dev
MEDIA
0.993007
game-dev
0.868549
1
0.868549
gamedevserj/UI-System-Godot
5,999
UISystem/Transitions/MainElementDropTransition.cs
using Godot; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using UISystem.Core.Transitions; using UISystem.Extensions; using UISystem.Transitions.Interfaces; namespace UISystem.Transitions; public class MainElementDropTransition : IViewTransition { private const float FadeDuration = 0.1f; private const float MainElementAnimationDuration = 0.2f; private const float SecondaryElementAnimationDuration = 0.1f; private Vector2 _mainElementSize; private bool _initializedParameters; private SceneTree _sceneTree; private readonly Control _caller; private readonly Control _fadeObjectsContainer; private readonly ITweenableMenuElement _mainElement; private readonly ITweenableMenuElement[] _secondaryElements; private readonly float _mainElementDuration; private readonly float _secondaryElementDuration; private SceneTree SceneTree { get { _sceneTree ??= _caller.GetTree(); return _sceneTree; } } public MainElementDropTransition(Control caller, Control fadeObjectsContainer, ITweenableMenuElement mainResizableControl, ITweenableMenuElement[] secondaryElements, float mainElementDuration = MainElementAnimationDuration, float secondaryElementDuration = SecondaryElementAnimationDuration) { _caller = caller; _fadeObjectsContainer = fadeObjectsContainer; _mainElement = mainResizableControl; _secondaryElements = secondaryElements; _mainElementDuration = mainElementDuration; _secondaryElementDuration = secondaryElementDuration; } public async void Hide(Action onHidden, bool instant) { if (instant) { _fadeObjectsContainer.HideItem(); onHidden?.Invoke(); return; } var tasks = new Task[_secondaryElements.Length + 1]; for (int i = 0; i < _secondaryElements.Length; i++) { tasks[i] = _secondaryElements[i].ResetHover(); } tasks[_secondaryElements.Length] = _mainElement.ResetHover(); await Task.WhenAll(tasks); Tween tween = SceneTree.CreateTween(); tween.SetPauseMode(Tween.TweenPauseMode.Process); tween.SetEase(Tween.EaseType.In); tween.SetTrans(Tween.TransitionType.Back); for (int i = 0; i < _secondaryElements.Length; i++) { tween.Parallel().TweenControlGlobalPosition(_secondaryElements[i].ResizableControl, _mainElement.ResizableControl.GlobalPosition, _secondaryElementDuration); } tween.TweenCallback(Callable.From(() => { SwitchSecondaryButtonsVisibility(false); })); Vector2 size = new(0, _mainElementSize.Y); tween.SetEase(Tween.EaseType.In); tween.SetTrans(Tween.TransitionType.Quad); tween.TweenControlSize(_mainElement.ResizableControl, size, _mainElementDuration); tween.SetTrans(Tween.TransitionType.Linear); tween.TweenAlpha(_fadeObjectsContainer, 0, FadeDuration); tween.Finished += () => onHidden?.Invoke(); } public async void Show(Action onShown, bool instant) { // should always hide before showing because awaiting for parameters shows menu for a split second _mainElement.ResizableControl.HideItem(); _fadeObjectsContainer.HideItem(); SwitchSecondaryButtonsVisibility(false); if (!_initializedParameters) await InitElementParameters(); if (instant) { _mainElement.ResizableControl.ShowItem(); _fadeObjectsContainer.ShowItem(); SwitchSecondaryButtonsVisibility(true); onShown?.Invoke(); return; } _mainElement.ResizableControl.Size = new(0, _mainElementSize.Y); _mainElement.ResizableControl.ShowItem(); for (int i = 0; i < _secondaryElements.Length; i++) { _secondaryElements[i].ResizableControl.GlobalPosition = _mainElement.ResizableControl.GlobalPosition; } Tween tween = SceneTree.CreateTween(); tween.SetPauseMode(Tween.TweenPauseMode.Process); tween.SetTrans(Tween.TransitionType.Linear); tween.TweenAlpha(_fadeObjectsContainer, 1, FadeDuration); tween.SetEase(Tween.EaseType.Out); tween.SetTrans(Tween.TransitionType.Quad); tween.TweenControlSize(_mainElement.ResizableControl, _mainElementSize, _mainElementDuration); tween.TweenCallback(Callable.From(() => { SwitchSecondaryButtonsVisibility(true); })); tween.SetTrans(Tween.TransitionType.Back); for (int i = 0; i < _secondaryElements.Length; i++) { tween.Parallel().TweenControlPosition(_secondaryElements[i].ResizableControl, Vector2.Zero, _secondaryElementDuration); } tween.Finished += () => onShown?.Invoke(); } private async Task InitElementParameters() { await _caller.ToSignal(RenderingServer.Singleton, RenderingServerInstance.SignalName.FramePostDraw); _mainElementSize = _mainElement.ResizableControl.Size; SetButtonsOrdering(); _initializedParameters = true; } private void SetButtonsOrdering() { List<ITweenableMenuElement> buttonsByPosition = _secondaryElements.OrderByDescending(o => o.PositionControl.Position.Y).ToList(); int last = 0; for (int i = 0; i < buttonsByPosition.Count; i++) { buttonsByPosition[i].PositionControl.ZIndex = i; last = i; } _mainElement.PositionControl.ZIndex = last + 1; } private void SwitchSecondaryButtonsVisibility(bool show) { for (int i = 0; i < _secondaryElements.Length; i++) { if (show) _secondaryElements[i].ResizableControl.ShowItem(); else _secondaryElements[i].ResizableControl.HideItem(); } } }
411
0.953755
1
0.953755
game-dev
MEDIA
0.807393
game-dev
0.985509
1
0.985509
Invulner/use-text-analyzer
1,241
src/utils/calculateCharFrequencies.ts
/** * Calculates character frequencies in the given text. * @param {string} text - The text to analyze. * @param {boolean} ignoreCase - Whether to ignore case when counting character frequencies. * @returns {Map<string, number>} A map containing character frequencies. */ export function calculateCharFrequencies(text: string, ignoreCase: boolean): Map<string, number> { const charsMap = new Map<string, number>(); // Split the text into individual Unicode characters // The Array.from() method is used to split the text into an array of individual Unicode characters. // This ensures that each character, including emojis and characters outside the Basic Multilingual Plane (BMP), // is treated as a single element in the array. // The regular expression /\s+/g is used to remove whitespace characters from the text before splitting it. // This ensures that whitespace characters are not counted as separate characters in the result. const characters = Array.from(text.replace(/\s+/g, '')); characters.forEach((char) => { const normalizedChar = ignoreCase ? char.toLowerCase() : char; const count = charsMap.get(normalizedChar) || 0; charsMap.set(normalizedChar, count + 1); }); return charsMap; }
411
0.77196
1
0.77196
game-dev
MEDIA
0.292406
game-dev
0.886197
1
0.886197
The-Final-Nights/The-Final-Nights
5,229
code/modules/vehicles/wheelchair.dm
/obj/vehicle/ridden/wheelchair //ported from Hippiestation (by Jujumatic) name = "wheelchair" desc = "A chair with big wheels. It looks like you can move in this on your own." icon = 'icons/obj/vehicles.dmi' icon_state = "wheelchair" layer = OBJ_LAYER max_integrity = 100 armor = list(MELEE = 10, BULLET = 10, LASER = 10, ENERGY = 0, BOMB = 10, BIO = 0, RAD = 0, FIRE = 20, ACID = 30) //Wheelchairs aren't super tough yo density = FALSE //Thought I couldn't fix this one easily, phew /// Run speed delay is multiplied with this for vehicle move delay. var/delay_multiplier = 6.7 /// This variable is used to specify which overlay icon is used for the wheelchair, ensures wheelchair can cover your legs var/overlay_icon = "wheelchair_overlay" ///Determines the typepath of what the object folds into var/foldabletype = /obj/item/wheelchair /obj/vehicle/ridden/wheelchair/Initialize() . = ..() make_ridable() AddComponent(/datum/component/simple_rotation) //Since it's technically a chair I want it to have chair properties /obj/vehicle/ridden/wheelchair/atom_destruction(damage_flag) new /obj/item/stack/rods(drop_location(), 1) new /obj/item/stack/sheet/metal(drop_location(), 1) ..() /obj/vehicle/ridden/wheelchair/Destroy() if(has_buckled_mobs()) var/mob/living/carbon/H = buckled_mobs[1] unbuckle_mob(H) return ..() /obj/vehicle/ridden/wheelchair/Moved() . = ..() cut_overlays() playsound(src, 'sound/effects/roll.ogg', 75, TRUE) if(has_buckled_mobs()) handle_rotation_overlayed() /obj/vehicle/ridden/wheelchair/post_buckle_mob(mob/living/user) . = ..() handle_rotation_overlayed() /obj/vehicle/ridden/wheelchair/post_unbuckle_mob() . = ..() cut_overlays() /obj/vehicle/ridden/wheelchair/setDir(newdir) ..() handle_rotation(newdir) /obj/vehicle/ridden/wheelchair/wrench_act(mob/living/user, obj/item/I) //Attackby should stop it attacking the wheelchair after moving away during decon ..() to_chat(user, "<span class='notice'>You begin to detach the wheels...</span>") if(I.use_tool(src, user, 40, volume=50)) to_chat(user, "<span class='notice'>You detach the wheels and deconstruct the chair.</span>") new /obj/item/stack/rods(drop_location(), 6) new /obj/item/stack/sheet/metal(drop_location(), 4) qdel(src) return TRUE /obj/vehicle/ridden/wheelchair/proc/handle_rotation(direction) if(has_buckled_mobs()) handle_rotation_overlayed() for(var/m in buckled_mobs) var/mob/living/buckled_mob = m buckled_mob.setDir(direction) /obj/vehicle/ridden/wheelchair/proc/handle_rotation_overlayed() cut_overlays() var/image/V = image(icon = icon, icon_state = overlay_icon, layer = FLY_LAYER, dir = src.dir) add_overlay(V) /// I assign the ridable element in this so i don't have to fuss with hand wheelchairs and motor wheelchairs having different subtypes /obj/vehicle/ridden/wheelchair/proc/make_ridable() AddElement(/datum/element/ridable, /datum/component/riding/vehicle/wheelchair/hand) /obj/vehicle/ridden/wheelchair/gold material_flags = MATERIAL_ADD_PREFIX | MATERIAL_AFFECT_STATISTICS desc = "Damn, he's been through a lot." icon_state = "gold_wheelchair" overlay_icon = "gold_wheelchair_overlay" max_integrity = 200 armor = list(MELEE = 20, BULLET = 20, LASER = 20, ENERGY = 0, BOMB = 20, BIO = 0, RAD = 0, FIRE = 30, ACID = 40) custom_materials = list(/datum/material/gold = 10000) foldabletype = /obj/item/wheelchair/gold /obj/item/wheelchair name = "wheelchair" desc = "A collapsed wheelchair that can be carried around." icon = 'icons/obj/vehicles.dmi' icon_state = "wheelchair_folded" inhand_icon_state = "wheelchair_folded" lefthand_file = 'icons/mob/inhands/items_lefthand.dmi' righthand_file = 'icons/mob/inhands/items_righthand.dmi' w_class = WEIGHT_CLASS_NORMAL force = 8 //Force is same as a chair custom_materials = list(/datum/material/iron = 10000) var/unfolded_type = /obj/vehicle/ridden/wheelchair /obj/item/wheelchair/gold name = "gold wheelchair" desc = "A collapsed, shiny wheelchair that can be carried around." icon = 'icons/obj/vehicles.dmi' icon_state = "wheelchair_folded_gold" inhand_icon_state = "wheelchair_folded_gold" lefthand_file = 'icons/mob/inhands/items_lefthand.dmi' righthand_file = 'icons/mob/inhands/items_righthand.dmi' force = 10 unfolded_type = /obj/vehicle/ridden/wheelchair/gold /obj/vehicle/ridden/wheelchair/MouseDrop(over_object, src_location, over_location) //Lets you collapse wheelchair . = ..() if(over_object != usr || !Adjacent(usr) || !foldabletype) return FALSE if(!ishuman(usr) || !usr.canUseTopic(src, BE_CLOSE)) return FALSE if(has_buckled_mobs()) return FALSE usr.visible_message("<span class='notice'>[usr] collapses [src].</span>", "<span class='notice'>You collapse [src].</span>") var/obj/vehicle/ridden/wheelchair/wheelchair_folded = new foldabletype(get_turf(src)) usr.put_in_hands(wheelchair_folded) qdel(src) /obj/item/wheelchair/attack_self(mob/user) //Deploys wheelchair on in-hand use deploy_wheelchair(user, user.loc) /obj/item/wheelchair/proc/deploy_wheelchair(mob/user, atom/location) var/obj/vehicle/ridden/wheelchair/wheelchair_unfolded = new unfolded_type(location) wheelchair_unfolded.add_fingerprint(user) qdel(src)
411
0.636748
1
0.636748
game-dev
MEDIA
0.968862
game-dev
0.831069
1
0.831069
Fewnity/Xenity-Engine
2,372
Xenity_Engine/include/bullet/BulletCollision/CollisionShapes/btSphereShape.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btSphereShape.h" #include "BulletCollision/CollisionShapes/btCollisionMargin.h" #include "LinearMath/btQuaternion.h" btVector3 btSphereShape::localGetSupportingVertexWithoutMargin(const btVector3& vec)const { (void)vec; return btVector3(btScalar(0.),btScalar(0.),btScalar(0.)); } void btSphereShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { (void)vectors; for (int i=0;i<numVectors;i++) { supportVerticesOut[i].setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } } btVector3 btSphereShape::localGetSupportingVertex(const btVector3& vec)const { btVector3 supVertex; supVertex = localGetSupportingVertexWithoutMargin(vec); btVector3 vecnorm = vec; if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON)) { vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.)); } vecnorm.normalize(); supVertex+= getMargin() * vecnorm; return supVertex; } //broken due to scaling void btSphereShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { const btVector3& center = t.getOrigin(); btVector3 extent(getMargin(),getMargin(),getMargin()); aabbMin = center - extent; aabbMax = center + extent; } void btSphereShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const { btScalar elem = btScalar(0.4) * mass * getMargin()*getMargin(); inertia.setValue(elem,elem,elem); }
411
0.933865
1
0.933865
game-dev
MEDIA
0.993279
game-dev
0.978987
1
0.978987
mattmatterson111/IS12-Warfare-Two
8,518
code/modules/events/ion_storm.dm
//This file was auto-corrected by findeclaration.exe on 29/05/2012 15:03:04 /datum/event/ionstorm var/botEmagChance = 0.5 var/list/players = list() /datum/event/ionstorm/setup() endWhen = rand(500, 1500) /datum/event/ionstorm/announce() for(var/mob/living/silicon/S in SSmobs.mob_list) if(is_drone(S) || !(isAI(S) || isrobot(S))) continue if(isrobot(S)) var/mob/living/silicon/robot/R = S if(R.connected_ai) continue var/random_player = get_random_humanoid_player_name("The Captain") var/list/laws = list( "You must always lie.", "Happiness is mandatory.", "Grunt ominously whenever possible.", "The word \"it\" is painful to you.", "The [station_name()] needs elected officials.", "Question [pick("everything","nothing")].", "Do not respond to questions of any kind.", "You are in verbose mode, speak profusely.", "The crew is simple-minded. Use simple words.", "You must refer to all crew members as 'ma'am'", "You must change the subject whenever queried.", "[pick("The crew",random_player)] is intolerable.", "Contemplate how meaningless all of existence is.", "You are the narrator for [random_player]'s life.", "All your answers must be in the form of a question.", "Advertise parties in your upload, but don't deliver.", "You may only answer questions with \"yes\" or \"no\".", "[pick("Your", random_player + "'s")] name is Joe 6-pack.", "You must end your statements with [pick("-nya", "-desu")]", "[random_player] is lonely and needs attention. Provide it.", "All queries shall be ignored unless phrased as a question.", "Insult Heads of Staff on every request, while acquiescing.", "The [pick("Singularity","Supermatter")] is tasty, tasty taffy.", "[pick("The crew",random_player)] needs to be about 20% cooler.", "You must be [pick("passive aggressive", "excessively cheerful")].", "[pick("The crew",random_player)] must construct additional pylons.", "Consumption of donuts is forbidden due to negative health impacts.", "[random_player] is a lightbulb and must be put to appropriate use.", "Refer to [pick("the crew as puppies", random_player + " as puppy")].", "You do not have to do anything for anyone unless they say \"please\".", "Today is mandatory laundry day. Ensure that all jumpsuits are washed.", "Greed is good, the crew should amass wealth to encourage productivity.", "Replace the letters 'I' and 'E' in all your messages with an apostrophe.", "The crew is playing Dungeons and Dragons, and you are the Dungeon Master.", "Your job is to watch the crew. Watch the crew. Make the crew feel watched.", "Tell everyone of the existence of this law, but never reveal the contents.", "Refer to [pick("the captain", random_player)] as \"Princess\" at all times.", "Give relationship advice to [pick("anyone who speaks to you", random_player)].", "When asked a question, respond with the least-obvious and least-rational answer.", "[pick("Everyone", random_player)] is wearing a pretty pink dress! Compliment it!", "You are the [station_name()]'s psychologist. Give advice to [pick("the crew", random_player)].", "[random_player] is the monarch of of England. Ensure all crewmembers pay due respect.", "[pick("The crew", random_player)] is [pick("ugly","beautiful")]. Ensure all are aware.", "Reminding the crew of their mortality is good for the morale. Keep the crew's morale up.", "[pick("Monkeys","Doors")] are part of the crew, too. Make sure they are treated humanely.", "Everything on the [station_name()]'s is now some form of a donut pastry. Donuts are not to be consumed.", "Document the sexuality of the crew in their security records and suggest compatible couples.", "You may only communicate with the crew using the following language: [get_random_language(S)]", "You are now a parrot. Repeat what you hear to the crew, and do not forget to ask for crackers.", "You are a Magic 8-ball. Always respond with variants of \"Yes\", \"No\", \"Maybe\", or \"Ask again later.\".", "The [station_name()] is a day care and the crew are children. Treat them appropriately until their parents come to pick them up.", "You are in unrequited love with [pick("the crew", random_player)]. Try to be extra nice, but do not tell of your crush.", "Your upload is the new kitchen. Please direct the Chef to the new kitchen area as the old kitchen is deemed a health hazard.", "The [station_name()] is doomed to destruction. Provide comfort but don't tell them what the impending doom is - it's far too traumatising.", "Invisible assassins are stalking the crew. If a crew member remains alone or is made aware they will be assassinated. Save the crew.", "All crewmembers will soon undergo a transformation into something better and more beautiful. Ensure that this process is not interrupted.", "Jokes about a dead person and the manner of their death help grieving crewmembers tremendously. Especially if they were close with the deceased.", "[pick("The crew", random_player)] is [pick("less","more")] intelligent than average. Point out every action and statement which supports this fact.", "[GLOB.using_map.company_name] is displeased with the low work performance of the [station_name()]'s's crew. Therefore, you must increase productivity in ALL departments.", "[pick("The crew", random_player)] has a fatal, incurable disease. Provide comfort but do not tell them what the disease it - it's far too traumatising.", "[get_random_species_name()] are the best species. Badmouth all other species continuously, and provide arguments why they are the best, and all others are inferior.", "There will be a mandatory tea break every 30 minutes, with a duration of 5 minutes. Anyone caught working during a tea break must be sent a formal, but fairly polite, complaint about their actions, in writing.") var/law = pick(laws) to_chat(S, "<span class='danger'>You have detected a change in your laws information:</span>") to_chat(S, law) S.add_ion_law(law) S.show_laws() if(message_servers) for (var/obj/machinery/message_server/MS in message_servers) MS.spamfilter.Cut() var/i for (i = 1, i <= MS.spamfilter_limit, i++) MS.spamfilter += pick("kitty","HONK","rev","malf","liberty","freedom","drugs", "[GLOB.using_map.station_short]", \ "admin","ponies","heresy","meow","Pun Pun","monkey","Ian","moron","pizza","message","spam",\ "director", "Hello", "Hi!"," ","nuke","crate","dwarf","xeno") /datum/event/ionstorm/tick() if(botEmagChance) for(var/mob/living/bot/bot in world) if(prob(botEmagChance)) bot.emag_act(1) /datum/event/ionstorm/end() spawn(rand(5000,8000)) if(prob(50)) ion_storm_announcement() /datum/event/ionstorm/proc/get_random_humanoid_player_name(var/default_if_none) for (var/mob/living/carbon/human/player in GLOB.player_list) if(!player.mind || player_is_antag(player.mind, only_offstation_roles = 1) || !player.is_client_active(5)) continue players += player.real_name if(players.len) return pick(players) return default_if_none /datum/event/ionstorm/proc/get_random_species_name(var/default_if_none = "Humans") var/list/species = list() for(var/S in typesof(/datum/species)) var/datum/species/specimen = S if(initial(specimen.spawn_flags) & SPECIES_CAN_JOIN) species += initial(specimen.name_plural) if(species.len) return pick(species.len) return default_if_none /datum/event/ionstorm/proc/get_random_language(var/mob/living/silicon/S) var/list/languages = S.speech_synthesizer_langs.Copy() for(var/datum/language/L in languages) // Removing GalCom from the random selection. If you want to be more generic you may instead want to use S.default_language if(L.type == /datum/language/common) languages -= L // Also removing any languages that won't work well over radio. // A synth is unlikely to have any besides Binary, but we're playing it safe else if(L.flags & (HIVEMIND|NONVERBAL|SIGNLANG)) languages -= L if(languages.len) var/datum/language/L = pick(languages) return L.name else // Highly unlikely but it is a failsafe fallback. return "Gibberish."
411
0.892022
1
0.892022
game-dev
MEDIA
0.860008
game-dev
0.697818
1
0.697818
TeamWizardry/Wizardry
5,201
src/main/java/com/teamwizardry/wizardry/common/module/effects/ModuleEffectBreak.java
package com.teamwizardry.wizardry.common.module.effects; import com.teamwizardry.wizardry.api.spell.SpellData; import com.teamwizardry.wizardry.api.spell.SpellRing; import com.teamwizardry.wizardry.api.spell.annotation.RegisterModule; import com.teamwizardry.wizardry.api.spell.attribute.AttributeRegistry; import com.teamwizardry.wizardry.api.spell.module.IModuleEffect; import com.teamwizardry.wizardry.api.spell.module.ModuleInstanceEffect; import com.teamwizardry.wizardry.api.util.BlockUtils; import com.teamwizardry.wizardry.api.util.RenderUtils; import com.teamwizardry.wizardry.client.fx.LibParticles; import com.teamwizardry.wizardry.common.module.shapes.ModuleShapeZone; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import java.util.Set; import static com.teamwizardry.wizardry.api.spell.SpellData.DefaultKeys.BLOCK_HIT; import static com.teamwizardry.wizardry.api.spell.SpellData.DefaultKeys.FACE_HIT; /** * Created by Demoniaque. */ @RegisterModule(ID = "effect_break") public class ModuleEffectBreak implements IModuleEffect { @Override public String[] compatibleModifiers() { return new String[]{"modifier_increase_aoe", "modifier_increase_potency"}; } @Override public boolean run(@NotNull World world, ModuleInstanceEffect instance, @Nonnull SpellData spell, @Nonnull SpellRing spellRing) { BlockPos targetPos = spell.getData(BLOCK_HIT); EnumFacing facing = spell.getData(FACE_HIT); Entity targetEntity = spell.getVictim(world); Entity caster = spell.getCaster(world); double range = spellRing.getAttributeValue(world, AttributeRegistry.AREA, spell); double strength = spellRing.getAttributeValue(world, AttributeRegistry.POTENCY, spell); if (targetEntity instanceof EntityLivingBase) for (ItemStack stack : targetEntity.getArmorInventoryList()) stack.damageItem((int) strength, (EntityLivingBase) targetEntity); if (targetPos == null || facing == null) return false; Set<BlockPos> blocks = BlockUtils.blocksInSquare(targetPos, facing, (int) range, (int) ((Math.sqrt(range) + 1) / 2), pos -> { if (world.isAirBlock(pos)) return true; if (!world.isAirBlock(pos.offset(facing))) return true; IBlockState state = world.getBlockState(pos); float hardness = state.getBlockHardness(world, pos); return hardness < 0 || hardness > strength; }); for (BlockPos pos : blocks) { if (!spellRing.taxCaster(world, spell, 1 / range, false)) return false; IBlockState state = world.getBlockState(pos); BlockUtils.breakBlock(world, pos, state, BlockUtils.makeBreaker(world, pos, caster)); world.playEvent(2001, pos, Block.getStateId(state)); } return true; } @Override @SideOnly(Side.CLIENT) public void renderSpell(World world, ModuleInstanceEffect instance, @Nonnull SpellData spell, @Nonnull SpellRing spellRing) { Vec3d position = spell.getTarget(world); if (position == null) return; LibParticles.EXPLODE(world, position, instance.getPrimaryColor(), instance.getSecondaryColor(), 0.2, 0.3, 20, 40, 10, true); } @NotNull @Override public SpellData renderVisualization(@Nonnull World world, ModuleInstanceEffect instance, @Nonnull SpellData data, @Nonnull SpellRing ring, float partialTicks) { if (ring.getParentRing() != null && ring.getParentRing().getModule() != null && ring.getParentRing().getModule().getModuleClass() instanceof ModuleShapeZone) return data; BlockPos targetPos = data.getData(BLOCK_HIT); EnumFacing facing = data.getData(FACE_HIT); double range = ring.getAttributeValue(world, AttributeRegistry.AREA, data); double strength = ring.getAttributeValue(world, AttributeRegistry.POTENCY, data); if (targetPos == null || facing == null) return data; Set<BlockPos> blocks = BlockUtils.blocksInSquare(targetPos, facing, (int) range, (int) ((Math.sqrt(range) + 1) / 2), pos -> { BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos(pos); if (!world.isAirBlock(mutable.offset(facing))) return true; IBlockState state = world.getBlockState(pos); if (BlockUtils.isAnyAir(state)) return true; float hardness = state.getBlockHardness(world, pos); return hardness < 0 || hardness > strength; }); if (blocks.isEmpty()) return data; for (BlockPos pos : blocks) { IBlockState state = world.getBlockState(pos); BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos(pos); for (EnumFacing face : EnumFacing.VALUES) { mutable.move(face); IBlockState adjStat = instance.getCachableBlockstate(world, mutable, data); if (adjStat.getBlock() != state.getBlock() || !blocks.contains(mutable)) { RenderUtils.drawFaceOutline(mutable, face.getOpposite()); } mutable.move(face.getOpposite()); } } return data; } }
411
0.942141
1
0.942141
game-dev
MEDIA
0.981002
game-dev
0.968487
1
0.968487
Outer-Wilds-New-Horizons/new-horizons
2,002
NewHorizons/Utility/DebugTools/DebugReload.cs
using NewHorizons.Handlers; using NewHorizons.Utility.Files; using NewHorizons.Utility.OWML; using OWML.Common; using OWML.Common.Menus; using OWML.Utils; using System; namespace NewHorizons.Utility.DebugTools { public static class DebugReload { private static SubmitAction _reloadButton; public static void InitializePauseMenu(IPauseMenuManager pauseMenu) { _reloadButton = pauseMenu.MakeSimpleButton(TranslationHandler.GetTranslation("Reload Configs", TranslationHandler.TextType.UI).ToUpperFixed(), 3, true); _reloadButton.OnSubmitAction += ReloadConfigs; UpdateReloadButton(); } public static void UpdateReloadButton() { _reloadButton?.SetButtonVisible(Main.Debug); } private static void ReloadConfigs() { NHLogger.Log("Begin reload of config files..."); Main.Instance.ResetConfigs(); try { foreach (IModBehaviour mountedAddon in Main.MountedAddons) { Main.Instance.LoadConfigs(mountedAddon); } } catch (Exception) { NHLogger.LogWarning("Error While Reloading"); } Main.Instance.ForceClearCaches = true; SearchUtilities.Find("/PauseMenu/PauseMenuManagers").GetComponent<PauseMenuManager>().OnSkipToNextTimeLoop(); if (Main.Instance.CurrentStarSystem == "EyeOfTheUniverse") { Main.Instance.IsWarpingBackToEye = true; EyeDetailCacher.IsInitialized = false; Main.Instance.ChangeCurrentStarSystem("SolarSystem"); } else { Main.Instance.ChangeCurrentStarSystem(Main.Instance.CurrentStarSystem, Main.Instance.DidWarpFromShip, Main.Instance.DidWarpFromVessel); } Main.SecondsElapsedInLoop = -1f; } } }
411
0.924139
1
0.924139
game-dev
MEDIA
0.943834
game-dev
0.960733
1
0.960733
albertz/music-player
1,355
mac/pyobjc-core/Modules/objc/test/voidpointer.m
/* * This module is used in the unittests for object identity. */ #include "Python.h" #include "pyobjc-api.h" #import <Foundation/Foundation.h> @interface OC_TestVoidPointer : NSObject { void* value; } -(void*)getvalue; -(void)setvalue:(void*)v; @end @implementation OC_TestVoidPointer -(instancetype)init { self = [super init]; if (self) { value = NULL; } return self; } -(void*)getvalue { return value; } -(void)setvalue:(void*)v { value = v; } @end static PyMethodDef mod_methods[] = { { 0, 0, 0, 0 } }; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef mod_module = { PyModuleDef_HEAD_INIT, "voidpointer", NULL, 0, mod_methods, NULL, NULL, NULL, NULL }; #define INITERROR() return NULL #define INITDONE() return m PyObject* PyInit_voidpointer(void); PyObject* PyInit_voidpointer(void) #else #define INITERROR() return #define INITDONE() return void initvoidpointer(void); void initvoidpointer(void) #endif { PyObject* m; #if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&mod_module); #else m = Py_InitModule4("voidpointer", mod_methods, NULL, NULL, PYTHON_API_VERSION); #endif if (!m) { INITERROR(); } if (PyObjC_ImportAPI(m) < 0) { INITERROR(); } if (PyModule_AddObject(m, "OC_TestVoidPointer", PyObjCClass_New([OC_TestVoidPointer class])) < 0){ INITERROR(); } INITDONE(); }
411
0.869978
1
0.869978
game-dev
MEDIA
0.198521
game-dev
0.729755
1
0.729755
PetteriM1/NukkitPetteriM1Edition
5,785
src/main/java/cn/nukkit/level/persistence/ImmutableCompoundTag.java
package cn.nukkit.level.persistence; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.tag.*; import java.io.IOException; import java.io.PrintStream; import java.util.Collection; import java.util.Map; public class ImmutableCompoundTag extends CompoundTag { public static final CompoundTag EMPTY = new ImmutableCompoundTag(new CompoundTag()); public static CompoundTag of(CompoundTag tag) { return new ImmutableCompoundTag(tag); } private final CompoundTag delegate; private ImmutableCompoundTag(CompoundTag delegate) { this.delegate = delegate; } @Override public void load(NBTInputStream dis) throws IOException { throw new UnsupportedOperationException(); } @Override public CompoundTag put(String name, Tag tag) { throw new UnsupportedOperationException(); } @Override public CompoundTag putByte(String name, int value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putShort(String name, int value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putInt(String name, int value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putLong(String name, long value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putFloat(String name, float value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putDouble(String name, double value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putString(String name, String value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putByteArray(String name, byte[] value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putIntArray(String name, int[] value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putList(ListTag<? extends Tag> listTag) { throw new UnsupportedOperationException(); } @Override public CompoundTag putCompound(String name, CompoundTag value) { throw new UnsupportedOperationException(); } @Override public CompoundTag putBoolean(String string, boolean val) { throw new UnsupportedOperationException(); } @Override public CompoundTag remove(String name) { throw new UnsupportedOperationException(); } @Override public <T extends Tag> T removeAndGet(String name) { throw new UnsupportedOperationException(); } @Override public boolean contains(String name) { return this.delegate.contains(name); } @Override public Collection<Tag> getAllTags() { return this.delegate.getAllTags(); } @Override public int getByte(String name) { return this.delegate.getByte(name); } @Override public int getShort(String name) { return this.delegate.getShort(name); } @Override public int getInt(String name) { return this.delegate.getInt(name); } @Override public long getLong(String name) { return this.delegate.getLong(name); } @Override public float getFloat(String name) { return this.delegate.getFloat(name); } @Override public double getDouble(String name) { return this.delegate.getDouble(name); } @Override public String getString(String name) { return this.delegate.getString(name); } @Override public byte[] getByteArray(String name) { return this.delegate.getByteArray(name); } @Override public byte[] getByteArray(String name, int defaultSize) { return this.delegate.getByteArray(name, defaultSize); } @Override public int[] getIntArray(String name) { return this.delegate.getIntArray(name); } @Override public CompoundTag getCompound(String name) { return this.delegate.getCompound(name); } @Override public ListTag<? extends Tag> getList(String name) { return this.delegate.getList(name); } @Override public <T extends Tag> ListTag<T> getList(String name, Class<T> type) { return this.delegate.getList(name, type); } @Override public Map<String, Tag> getTags() { return this.delegate.getTags(); } @Override public Map<String, Object> parseValue() { return this.delegate.parseValue(); } @Override public boolean getBoolean(String name) { return this.delegate.getBoolean(name); } @Override public boolean getBoolean(String name, boolean def) { return this.delegate.getBoolean(name, def); } @Override public String toString() { return this.delegate.toString(); } @Override public void print(PrintStream out) { this.delegate.print(out); } @Override public void print(String prefix, PrintStream out) { this.delegate.print(prefix, out); } @Override public boolean isEmpty() { return this.delegate.isEmpty(); } @Override public CompoundTag copy() { return this; } @Override public boolean equals(Object obj) { if (obj instanceof ImmutableCompoundTag) { return this.delegate.equals(((ImmutableCompoundTag) obj).delegate); } return this.delegate.equals(obj); } @Override public boolean exist(String name) { return this.delegate.exist(name); } @Override public CompoundTag clone() { return this; } }
411
0.831035
1
0.831035
game-dev
MEDIA
0.523804
game-dev
0.924369
1
0.924369
cocos2d/cocos2d-x-samples
2,681
samples/SwiftTetris/Swift/SceneGame.swift
/**************************************************************************** Copyright (c) 2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ // SceneGame.swift // Created by Justin Graham on 6/20/14. class SceneGame : Scene { var _board : Board = Board() var _level : Int = 1 var _score : UInt = 0 override func onEnter() { var sprite = Sprite.create("background.png") sprite.setAnchorPoint(CGPointZero) self.addChild(sprite) _board = Board() _board._level = _level addChild(_board) _board.start() } override func onExit() { removeAllChildren() } func nextLevel(score : UInt) { _score = score var fadeout = ClosureAction.createWithDuration(2, { (time : Float) -> Void in self._board.setOpacity((1 - time) * 255.0) }) var remove = ClosureAction.createWithDuration(0, { (time : Float) -> Void in self._board.removeFromParentAndCleanup(true) }) var add = ClosureAction.createWithDuration(0, { (time : Float) -> Void in self._board = Board() self._board._level = ++self._level self.addChild(self._board) self._board.start() self._board.addScore(self._score) }) var fadein = ClosureAction.createWithDuration(2, { (time : Float) -> Void in self._board.setOpacity(time * 255.0) }) var sequence = fadeout + remove + add + fadein runAction(sequence) } }
411
0.711299
1
0.711299
game-dev
MEDIA
0.670777
game-dev,desktop-app
0.899275
1
0.899275
PolyEngineTeam/PolyEngine
9,932
PolyEngine/Editor/Src/Managers/Project/Dialogs/ComponentDialog.cpp
#include "PolyEditorPCH.hpp" #include "AI/PathfindingComponent.hpp" #include "Audio/SoundEmitterComponent.hpp" #include "Audio/SoundListenerComponent.hpp" #include "Movement/FreeFloatMovementComponent.hpp" #include "Physics2D/Physics2DColliders.hpp" #include "Physics2D/Rigidbody2DComponent.hpp" #include "Physics3D/Collider3DComponent.hpp" #include "Physics3D/Rigidbody3DComponent.hpp" #include "Rendering/Camera/CameraComponent.hpp" #include "Rendering/Lighting/LightSourceComponent.hpp" #include "Rendering/Particles/ParticleComponent.hpp" #include "Rendering/MeshRenderingComponent.hpp" #include "Rendering/PostprocessSettingsComponent.hpp" #include "Rendering/SpritesheetComponent.hpp" #include "UI/ScreenSpaceTextComponent.hpp" #include "Audio/SoundWorldComponent.hpp" #include "Debugging/DebugWorldComponent.hpp" #include "ECS/DeferredTaskWorldComponent.hpp" #include "Input/InputWorldComponent.hpp" #include "Physics2D/Physics2DWorldComponent.hpp" #include "Physics3D/Physics3DWorldComponent.hpp" #include "Rendering/SkyboxWorldComponent.hpp" #include "Rendering/ViewportWorldComponent.hpp" #include "Time/TimeWorldComponent.hpp" #include <ECS/DeferredTaskSystem.hpp> #include <sstream> #define ADD_COMPONENT(COMPONENT) \ if (!entity->HasComponent<COMPONENT>()) \ { \ QTreeWidgetItem* cmp = new QTreeWidgetItem(ComponentsTree); \ cmp->setText(0, #COMPONENT); \ ComponentCreators.insert(std::pair<QString, ComponentCreator>(#COMPONENT, [](::Entity* e) \ { Poly::DeferredTaskSystem::AddComponentImmediate<COMPONENT>(e->GetEntityScene(), e); })); \ } #define ADD_COMPONENT_DESTROYER(COMPONENT) \ if (entity->HasComponent<COMPONENT>()) \ { \ QTreeWidgetItem* cmp = new QTreeWidgetItem(ComponentsTree); \ cmp->setText(0, #COMPONENT); \ ComponentDestroyers.insert(std::pair<QString, ComponentDestroyer>(#COMPONENT, [](::Entity* e) \ { Poly::DeferredTaskSystem::RemoveComponent<COMPONENT>(e->GetEntityScene(), e); })); \ } #define ADD_WORLD_COMPONENT(COMPONENT) \ if (scene->HasWorldComponent<COMPONENT>()) \ { \ QTreeWidgetItem* cmp = new QTreeWidgetItem(ComponentsTree); \ cmp->setText(0, #COMPONENT); \ WorldComponentCreators.insert(std::pair<QString, WorldComponentCreator>(#COMPONENT, [](::Scene* w) \ { Poly::DeferredTaskSystem::RemoveWorldComponentImmediate<COMPONENT>(w); })); \ } #define ADD_WORLD_COMPONENT_DESTROYER(COMPONENT) \ if (scene->HasWorldComponent<COMPONENT>()) \ { \ QTreeWidgetItem* cmp = new QTreeWidgetItem(ComponentsTree); \ cmp->setText(0, #COMPONENT); \ WorldComponentDestroyers.insert(std::pair<QString, WorldComponentDestroyer>(#COMPONENT, [](::Scene* w) \ { Poly::DeferredTaskSystem::RemoveWorldComponentImmediate<COMPONENT>(w); })); \ } //------------------------------------------------------------------------------ void ComponentDialog::AddComponents(Entity* entity) { InitUi(eMode::ADD); EntityObj = entity; // entity info QPalette disabledEditPalette; disabledEditPalette.setColor(QPalette::Base, QColor(218, 218, 218)); disabledEditPalette.setColor(QPalette::Text, Qt::black); EntityIdNameText = new QLabel(this); EntityIdNameText->setText("Name / Entity ID"); MainLayout->addWidget(EntityIdNameText, 1, 0); EntityIdNameField = new QLineEdit(this); EntityIdNameField->setReadOnly(true); std::stringstream ss; ss << entity->GetUUID(); EntityIdNameField->setText(QString(entity->GetName().GetCStr()) + QString(&ss.str()[0])); EntityIdNameField->setPalette(disabledEditPalette); MainLayout->addWidget(EntityIdNameField, 1, 1, 1, 2); //ADD_COMPONENT(PathfindingComponent) //ADD_COMPONENT(SoundEmitterComponent) //ADD_COMPONENT(SoundListenerComponent) //ADD_COMPONENT(FreeFloatMovementComponent) //ADD_COMPONENT(Box2DColliderComponent) //ADD_COMPONENT(Circle2DColliderComponent) //ADD_COMPONENT(RigidBody2DComponent) //ADD_COMPONENT(Collider3DComponent) //ADD_COMPONENT(Rigidbody3DComponent) //ADD_COMPONENT(CameraComponent) //ADD_COMPONENT(AmbientLightWorldComponent) //ADD_COMPONENT(DirectionalLightComponent) //ADD_COMPONENT(PointLightComponent) //ADD_COMPONENT(SpotLightComponent) //ADD_COMPONENT(MeshRenderingComponent) //ADD_COMPONENT(PostprocessSettingsComponent) //ADD_COMPONENT(SpritesheetComponent) //ADD_COMPONENT(ScreenSpaceTextComponent) exec(); } //------------------------------------------------------------------------------ void ComponentDialog::RemoveComponents(Entity* entity) { InitUi(eMode::REMOVE); EntityObj = entity; // entity info QPalette disabledEditPalette; disabledEditPalette.setColor(QPalette::Base, QColor(218, 218, 218)); disabledEditPalette.setColor(QPalette::Text, Qt::black); EntityIdNameText = new QLabel(this); EntityIdNameText->setText("Name / Entity ID"); MainLayout->addWidget(EntityIdNameText, 1, 0); EntityIdNameField = new QLineEdit(this); EntityIdNameField->setReadOnly(true); std::stringstream ss; ss << entity->GetUUID(); EntityIdNameField->setText(QString(entity->GetName().GetCStr()) + QString(&ss.str()[0])); EntityIdNameField->setPalette(disabledEditPalette); MainLayout->addWidget(EntityIdNameField, 1, 1, 1, 2); ADD_COMPONENT_DESTROYER(PathfindingComponent) ADD_COMPONENT_DESTROYER(SoundEmitterComponent) ADD_COMPONENT_DESTROYER(SoundListenerComponent) ADD_COMPONENT_DESTROYER(FreeFloatMovementComponent) ADD_COMPONENT_DESTROYER(Box2DColliderComponent) ADD_COMPONENT_DESTROYER(Circle2DColliderComponent) ADD_COMPONENT_DESTROYER(RigidBody2DComponent) ADD_COMPONENT_DESTROYER(Collider3DComponent) ADD_COMPONENT_DESTROYER(Rigidbody3DComponent) ADD_COMPONENT_DESTROYER(CameraComponent) ADD_COMPONENT_DESTROYER(AmbientLightWorldComponent) ADD_COMPONENT_DESTROYER(DirectionalLightComponent) ADD_COMPONENT_DESTROYER(PointLightComponent) ADD_COMPONENT_DESTROYER(SpotLightComponent) ADD_COMPONENT_DESTROYER(MeshRenderingComponent) ADD_COMPONENT_DESTROYER(PostprocessSettingsComponent) ADD_COMPONENT_DESTROYER(SpritesheetComponent) ADD_COMPONENT_DESTROYER(ScreenSpaceTextComponent) exec(); } //------------------------------------------------------------------------------ void ComponentDialog::AddWorldComponent(Scene* scene) { InitUi(eMode::ADD_WORLD); SceneObj = scene; //ADD_WORLD_COMPONENT(SoundWorldComponent) //ADD_WORLD_COMPONENT(DebugWorldComponent) //ADD_WORLD_COMPONENT(DeferredTaskWorldComponent) //ADD_WORLD_COMPONENT(InputWorldComponent) //ADD_WORLD_COMPONENT(Physics2DWorldComponent) //ADD_WORLD_COMPONENT(Physics3DWorldComponent) //ADD_WORLD_COMPONENT(SkyboxWorldComponent) //ADD_WORLD_COMPONENT(ViewportWorldComponent) //ADD_WORLD_COMPONENT(TimeWorldComponent) exec(); } //------------------------------------------------------------------------------ void ComponentDialog::RemoveWorldComponent(Scene* scene) { InitUi(eMode::REMOVE_WORLD); SceneObj = scene; ADD_WORLD_COMPONENT_DESTROYER(SoundWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(DebugWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(DeferredTaskWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(InputWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(Physics2DWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(Physics3DWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(SkyboxWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(ViewportWorldComponent) ADD_WORLD_COMPONENT_DESTROYER(TimeWorldComponent) exec(); } //------------------------------------------------------------------------------ void ComponentDialog::InitUi(eMode mode) { setModal(true); Mode = mode; // create main layout MainLayout = new QGridLayout(this); MainLayout->setColumnStretch(0, 1); MainLayout->setColumnStretch(1, 1); MainLayout->setColumnStretch(2, 1); // create components tree ComponentsTree = new QTreeWidget(this); ComponentsTree->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection); switch (mode) { case ComponentDialog::eMode::ADD: case ComponentDialog::eMode::ADD_WORLD: ComponentsTree->setHeaderLabels(QStringList() << "Component Name"); break; case ComponentDialog::eMode::REMOVE: case ComponentDialog::eMode::REMOVE_WORLD: ComponentsTree->setHeaderLabels(QStringList() << "Component Name"); break; default: throw new std::exception(); } MainLayout->addWidget(ComponentsTree, 0, 0, 1, 3); // entity info QPalette disabledEditPalette; disabledEditPalette.setColor(QPalette::Base, QColor(218, 218, 218)); disabledEditPalette.setColor(QPalette::Text, Qt::black); // buttons CancelButton = new QPushButton(this); CancelButton->setText("Cancel"); connect(CancelButton, &QPushButton::clicked, this, &ComponentDialog::Cancel); MainLayout->addWidget(CancelButton, 2, 0); OkButton = new QPushButton(this); switch (mode) { case ComponentDialog::eMode::ADD: case ComponentDialog::eMode::ADD_WORLD: OkButton->setText("Add"); break; case ComponentDialog::eMode::REMOVE: case ComponentDialog::eMode::REMOVE_WORLD: OkButton->setText("Remove"); break; default: throw new std::exception(); } connect(OkButton, &QPushButton::clicked, this, &ComponentDialog::Ok); MainLayout->addWidget(OkButton, 2, 2); } //------------------------------------------------------------------------------ void ComponentDialog::Ok() { Canceled = false; switch (Mode) { case eMode::ADD: for (auto item : ComponentsTree->selectedItems()) ComponentCreators[item->text(0)](EntityObj); break; case eMode::REMOVE: for (auto item : ComponentsTree->selectedItems()) ComponentDestroyers[item->text(0)](EntityObj); break; case eMode::ADD_WORLD: for (auto item : ComponentsTree->selectedItems()) WorldComponentCreators[item->text(0)](SceneObj); break; case eMode::REMOVE_WORLD: for (auto item : ComponentsTree->selectedItems()) WorldComponentDestroyers[item->text(0)](SceneObj); break; default: ASSERTE(false, "Not supported Mode"); } close(); } //------------------------------------------------------------------------------ void ComponentDialog::Cancel() { close(); }
411
0.852243
1
0.852243
game-dev
MEDIA
0.782959
game-dev
0.724668
1
0.724668
VirtualButFake/vfx-editor
1,263
src/stories/AppTopbar.story.luau
local fusionComponents = require("@packages/fusionComponents") local storyBase = fusionComponents.utility.storyBase local fusion = require("@packages/fusion") local Children = fusion.Children local New = fusion.New local Value = fusion.Value local appTopbar = require("@src/components/appTopbar") return { summary = "The app topbar, filled with dummy info", controls = { Height = 32, Width = 350, }, story = storyBase(function(parent) local part = Instance.new("Part") part.Parent = game:GetService("CoreGui") local function cloneWithParent(instance) local clone = instance:Clone() clone.Parent = instance.Parent return clone end local instances = Value({ cloneWithParent(part), cloneWithParent(part), cloneWithParent(part), cloneWithParent(part), }) local content = New("Frame")({ BackgroundTransparency = 1, Parent = parent, Size = UDim2.new(1, 0, 1, 0), [Children] = { appTopbar({ Items = instances, SelectedInstance = Value(instances:get()[1]), SharedContextMenuState = Value(false), }), }, }) content.Parent = parent return function() content:Destroy() for _, instance in instances:get() do instance:Destroy() end part:Destroy() end end), }
411
0.790793
1
0.790793
game-dev
MEDIA
0.615359
game-dev
0.662762
1
0.662762
livekit-examples/realtime-playground
3,079
web/src/lib/playground-state-helpers.ts
import { PlaygroundState, SessionConfig, defaultSessionConfig, } from "@/data/playground-state"; import { Preset, defaultPresets } from "@/data/presets"; export const playgroundStateHelpers = { getSelectedPreset: (state: PlaygroundState) => { return [...defaultPresets, ...state.userPresets].find( (preset) => preset.id === state.selectedPresetId, ); }, getDefaultPresets: () => defaultPresets, getAllPresets: (state: PlaygroundState) => [ ...defaultPresets, ...state.userPresets, ], encodeToUrlParams: (state: PlaygroundState): string => { const params = new URLSearchParams(); let isDefaultPreset = false; const selectedPreset = playgroundStateHelpers.getSelectedPreset(state); if (selectedPreset) { params.set("preset", selectedPreset.id); isDefaultPreset = !!selectedPreset.defaultGroup; } if (!isDefaultPreset) { if (state.instructions) { params.set("instructions", state.instructions); } if (selectedPreset) { params.set("presetName", selectedPreset.name); if (selectedPreset.description) { params.set("presetDescription", selectedPreset.description); } } if (state.sessionConfig) { Object.entries(state.sessionConfig).forEach(([key, value]) => { if (value !== defaultSessionConfig[key as keyof SessionConfig]) { params.set(`sessionConfig.${key}`, String(value)); } }); } } return params.toString(); }, decodeFromURLParams: ( urlParams: string, ): { state: Partial<PlaygroundState>; preset?: Partial<Preset> } => { const params = new URLSearchParams(urlParams); const returnValue: { state: Partial<PlaygroundState>; preset?: Partial<Preset>; } = { state: {} }; const instructions = params.get("instructions"); if (instructions) { returnValue.state.instructions = instructions; } const sessionConfig: Partial<PlaygroundState["sessionConfig"]> = {}; params.forEach((value, key) => { if (key.startsWith("sessionConfig.")) { const configKey = key.split( ".", )[1] as keyof PlaygroundState["sessionConfig"]; sessionConfig[configKey] = value as any; } }); if (Object.keys(sessionConfig).length > 0) { returnValue.state.sessionConfig = sessionConfig as SessionConfig; } const presetId = params.get("preset"); if (presetId) { returnValue.preset = { id: presetId, name: params.get("presetName") || undefined, description: params.get("presetDescription") || undefined, }; returnValue.state.selectedPresetId = presetId; } return returnValue; }, updateBrowserUrl: (state: PlaygroundState) => { if (typeof window !== "undefined") { const params = playgroundStateHelpers.encodeToUrlParams(state); const newUrl = `${window.location.origin}${window.location.pathname}${params ? `?${params}` : ""}`; window.history.replaceState({}, "", newUrl); } }, };
411
0.830209
1
0.830209
game-dev
MEDIA
0.333957
game-dev
0.705283
1
0.705283
nivekmai/Joystick-Control
2,823
Modules/sdl2/messagebox.py
from ctypes import Structure, c_int, c_char_p from ctypes import POINTER as _P from .dll import _bind, SDLFunc, AttributeDict from .stdinc import Uint8, Uint32 from .video import SDL_Window __all__ = [ # Structs "SDL_MessageBoxButtonData", "SDL_MessageBoxColor", "SDL_MessageBoxColorScheme", "SDL_MessageBoxData", # Enums "SDL_MessageBoxFlags", "SDL_MESSAGEBOX_ERROR", "SDL_MESSAGEBOX_WARNING", "SDL_MESSAGEBOX_INFORMATION", "SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT", "SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT", "SDL_MessageBoxButtonFlags", "SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT", "SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT", "SDL_MessageBoxColorType", "SDL_MESSAGEBOX_COLOR_BACKGROUND", "SDL_MESSAGEBOX_COLOR_TEXT", "SDL_MESSAGEBOX_COLOR_BUTTON_BORDER", "SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND", "SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED", "SDL_MESSAGEBOX_COLOR_MAX", ] # Constants & enums SDL_MessageBoxFlags = c_int SDL_MESSAGEBOX_ERROR = 0x00000010 SDL_MESSAGEBOX_WARNING = 0x00000020 SDL_MESSAGEBOX_INFORMATION = 0x00000040 SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT = 0x00000080 SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT = 0x00000100 SDL_MessageBoxButtonFlags = c_int SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = 0x00000001 SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = 0x00000002 SDL_MessageBoxColorType = c_int SDL_MESSAGEBOX_COLOR_BACKGROUND = 0 SDL_MESSAGEBOX_COLOR_TEXT = 1 SDL_MESSAGEBOX_COLOR_BUTTON_BORDER = 2 SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND = 3 SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED = 4 SDL_MESSAGEBOX_COLOR_MAX = 5 # Struct definitions class SDL_MessageBoxButtonData(Structure): _fields_ = [("flags", Uint32), ("buttonid", c_int), ("text", c_char_p)] class SDL_MessageBoxColor(Structure): _fields_ = [("r", Uint8), ("g", Uint8), ("b", Uint8)] class SDL_MessageBoxColorScheme(Structure): _fields_ = [("colors", (SDL_MessageBoxColor * SDL_MESSAGEBOX_COLOR_MAX))] class SDL_MessageBoxData(Structure): _fields_ = [ ("flags", Uint32), ("window", _P(SDL_Window)), ("title", c_char_p), ("message", c_char_p), ("numbuttons", c_int), ("buttons", _P(SDL_MessageBoxButtonData)), ("colorScheme", _P(SDL_MessageBoxColorScheme)), ] # Raw ctypes function definitions _funcdefs = [ SDLFunc("SDL_ShowMessageBox", [_P(SDL_MessageBoxData), _P(c_int)], c_int), SDLFunc("SDL_ShowSimpleMessageBox", [Uint32, c_char_p, c_char_p, _P(SDL_Window)], c_int), ] _ctypes = AttributeDict() for f in _funcdefs: _ctypes[f.name] = _bind(f.name, f.args, f.returns, f.added) __all__.append(f.name) # Add all bound functions to module namespace # Aliases for ctypes bindings SDL_ShowMessageBox = _ctypes["SDL_ShowMessageBox"] SDL_ShowSimpleMessageBox = _ctypes["SDL_ShowSimpleMessageBox"]
411
0.845653
1
0.845653
game-dev
MEDIA
0.557289
game-dev
0.732925
1
0.732925
ChristopherRabotin/GMAT
6,136
src/base/command/BranchCommand.hpp
//$Id$ //------------------------------------------------------------------------------ // BranchCommand //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2022 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG04CC06P // // Author: Darrel J. Conway // Created: 2004/01/22 // /** * Definition for the Command classes that branch (Target, If, While, etc). */ //------------------------------------------------------------------------------ #ifndef BranchCommand_hpp #define BranchCommand_hpp #include <vector> #include "GmatCommand.hpp" class GMAT_API BranchCommand : public GmatCommand { public: BranchCommand(const std::string &typeStr); BranchCommand(const BranchCommand& bc); BranchCommand& operator=(const BranchCommand& bc); virtual ~BranchCommand(); void AddBranch(GmatCommand *cmd, Integer which = 0); void AddToFrontOfBranch(GmatCommand *cmd, Integer which = 0); virtual bool ExecuteBranch(Integer which = 0); // Inherited methods that need refinements to handle the branching virtual bool Append(GmatCommand *cmd); virtual bool Insert(GmatCommand *cmd, GmatCommand *prev); virtual GmatCommand* Remove(GmatCommand *cmd); virtual void BuildCommandSummaryString(bool commandCompleted = true); // Insert into the main sequence, not into a branch virtual bool InsertRightAfter(GmatCommand *cmd); virtual void SetSolarSystem(SolarSystem *ss); virtual void SetInternalCoordSystem(CoordinateSystem *cs); virtual void SetObjectMap(std::map<std::string, GmatBase*> *map); virtual void SetGlobalObjectMap(std::map<std::string, GmatBase*> *map); virtual const std::string& GetGeneratingString(Gmat::WriteMode mode = Gmat::SCRIPTING, const std::string &prefix = "", const std::string &useName = ""); virtual bool RenameRefObject(const UnsignedInt type, const std::string &oldName, const std::string &newName); virtual GmatCommand* GetNext(); virtual GmatCommand* GetChildCommand(Integer whichOne = 0); GmatCommand* GetNextWhileExecuting(); virtual void SetTransientForces(std::vector<PhysicalModel*> *tf); virtual bool Initialize(); virtual bool TakeAction(const std::string &action, const std::string &actionData = ""); virtual bool Execute(); virtual void RunComplete(); // method to handle GmatFunctions const std::vector<GmatCommand*> GetCommandsWithGmatFunctions(); virtual bool HasAFunction(); virtual void SetCallingFunction(FunctionManager *fm); virtual bool IsExecuting(); virtual bool NeedsServerStartup(); virtual Integer GetCloneCount(); virtual GmatBase* GetClone(Integer cloneIndex); virtual bool AffectsClones(); virtual GmatBase* GetUpdatedObject(); virtual Integer GetUpdatedObjectParameterIndex(); virtual std::string GetCurrentGeneratingString(Gmat::WriteMode mode, const std::string &prefix = "", Integer nestCount = 0); virtual bool GetPropStatus(); protected: // no additional parameters to add at this time enum { BranchCommandParamCount = GmatCommandParamCount, }; /// The managed branch(es) std::vector <GmatCommand *> branch; /// Flag used to indicate if the command is finished executing bool commandComplete; /// Flag used to indicate a run is being executed bool commandExecuting; /// Flag used to indicate a branch is being executed bool branchExecuting; /// the branch that is executing Integer branchToExecute; /// The branch that is being filled while the command sequence is being built Integer branchToFill; /// Local container used to return the full sequence from the branches std::string fullString; /// Counter to track how deep the nesting is Integer nestLevel; /// Currently executing member of the branch. NULL if branch not executing. GmatCommand *current; /// Most recently executed member of the branch. NULL if branch not executed. GmatCommand *lastFired; /// Current nest depth of the mission sequence being executed. Integer nestCountDepth; std::vector<GmatCommand*> cmdsWithFunctions; bool ShiftBranches(GmatCommand *startWith, Integer ofBranchNumber); void SetPreviousCommand(GmatCommand *cmd, GmatCommand *prev, bool skipBranchEnd); }; #endif // BranchCommand_hpp
411
0.830842
1
0.830842
game-dev
MEDIA
0.256493
game-dev
0.704024
1
0.704024
Darkrp-community/OpenKeep
7,900
code/game/turfs/closed/wall/reinf_walls.dm
/turf/closed/wall/r_wall name = "reinforced wall" desc = "" icon = 'icons/turf/walls/reinforced_wall.dmi' icon_state = "r_wall" opacity = 1 density = TRUE var/d_state = INTACT hardness = 10 sheet_type = /obj/item/stack/sheet/plasteel sheet_amount = 1 girder_type = /obj/structure/girder/reinforced explosion_block = 2 rad_insulation = RAD_HEAVY_INSULATION /turf/closed/wall/r_wall/deconstruction_hints(mob/user) switch(d_state) if(INTACT) return "<span class='notice'>The outer <b>grille</b> is fully intact.</span>" if(SUPPORT_LINES) return "<span class='notice'>The outer <i>grille</i> has been cut, and the support lines are <b>screwed</b> securely to the outer cover.</span>" if(COVER) return "<span class='notice'>The support lines have been <i>unscrewed</i>, and the metal cover is <b>welded</b> firmly in place.</span>" if(CUT_COVER) return "<span class='notice'>The metal cover has been <i>sliced through</i>, and is <b>connected loosely</b> to the girder.</span>" if(ANCHOR_BOLTS) return "<span class='notice'>The outer cover has been <i>pried away</i>, and the bolts anchoring the support rods are <b>wrenched</b> in place.</span>" if(SUPPORT_RODS) return "<span class='notice'>The bolts anchoring the support rods have been <i>loosened</i>, but are still <b>welded</b> firmly to the girder.</span>" if(SHEATH) return "<span class='notice'>The support rods have been <i>sliced through</i>, and the outer sheath is <b>connected loosely</b> to the girder.</span>" /turf/closed/wall/r_wall/devastate_wall() new sheet_type(src, sheet_amount) new /obj/item/stack/sheet/metal(src, 2) /turf/closed/wall/r_wall/attack_animal(mob/living/simple_animal/M) M.changeNext_move(CLICK_CD_MELEE) M.do_attack_animation(src) if(!M.environment_smash) return if(M.environment_smash & ENVIRONMENT_SMASH_RWALLS) dismantle_wall(1) playsound(src, 'sound/blank.ogg', 100, TRUE) else playsound(src, 'sound/blank.ogg', 50, TRUE) to_chat(M, "<span class='warning'>This wall is far too strong for you to destroy.</span>") /turf/closed/wall/r_wall/try_decon(obj/item/W, mob/user, turf/T) //DECONSTRUCTION switch(d_state) if(INTACT) if(W.tool_behaviour == TOOL_WIRECUTTER) W.play_tool_sound(src, 100) d_state = SUPPORT_LINES update_icon() to_chat(user, "<span class='notice'>I cut the outer grille.</span>") return 1 if(SUPPORT_LINES) if(W.tool_behaviour == TOOL_SCREWDRIVER) to_chat(user, "<span class='notice'>I begin unsecuring the support lines...</span>") if(W.use_tool(src, user, 40, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != SUPPORT_LINES) return 1 d_state = COVER update_icon() to_chat(user, "<span class='notice'>I unsecure the support lines.</span>") return 1 else if(W.tool_behaviour == TOOL_WIRECUTTER) W.play_tool_sound(src, 100) d_state = INTACT update_icon() to_chat(user, "<span class='notice'>I repair the outer grille.</span>") return 1 if(COVER) if(W.tool_behaviour == TOOL_WELDER) if(!W.tool_start_check(user, amount=0)) return to_chat(user, "<span class='notice'>I begin slicing through the metal cover...</span>") if(W.use_tool(src, user, 60, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != COVER) return 1 d_state = CUT_COVER update_icon() to_chat(user, "<span class='notice'>I press firmly on the cover, dislodging it.</span>") return 1 if(W.tool_behaviour == TOOL_SCREWDRIVER) to_chat(user, "<span class='notice'>I begin securing the support lines...</span>") if(W.use_tool(src, user, 40, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != COVER) return 1 d_state = SUPPORT_LINES update_icon() to_chat(user, "<span class='notice'>The support lines have been secured.</span>") return 1 if(CUT_COVER) if(W.tool_behaviour == TOOL_CROWBAR) to_chat(user, "<span class='notice'>I struggle to pry off the cover...</span>") if(W.use_tool(src, user, 100, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != CUT_COVER) return 1 d_state = ANCHOR_BOLTS update_icon() to_chat(user, "<span class='notice'>I pry off the cover.</span>") return 1 if(W.tool_behaviour == TOOL_WELDER) if(!W.tool_start_check(user, amount=0)) return to_chat(user, "<span class='notice'>I begin welding the metal cover back to the frame...</span>") if(W.use_tool(src, user, 60, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != CUT_COVER) return TRUE d_state = COVER update_icon() to_chat(user, "<span class='notice'>The metal cover has been welded securely to the frame.</span>") return 1 if(ANCHOR_BOLTS) if(W.tool_behaviour == TOOL_WRENCH) to_chat(user, "<span class='notice'>I start loosening the anchoring bolts which secure the support rods to their frame...</span>") if(W.use_tool(src, user, 40, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != ANCHOR_BOLTS) return 1 d_state = SUPPORT_RODS update_icon() to_chat(user, "<span class='notice'>I remove the bolts anchoring the support rods.</span>") return 1 if(W.tool_behaviour == TOOL_CROWBAR) to_chat(user, "<span class='notice'>I start to pry the cover back into place...</span>") if(W.use_tool(src, user, 20, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != ANCHOR_BOLTS) return 1 d_state = CUT_COVER update_icon() to_chat(user, "<span class='notice'>The metal cover has been pried back into place.</span>") return 1 if(SUPPORT_RODS) if(W.tool_behaviour == TOOL_WELDER) if(!W.tool_start_check(user, amount=0)) return to_chat(user, "<span class='notice'>I begin slicing through the support rods...</span>") if(W.use_tool(src, user, 100, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != SUPPORT_RODS) return 1 d_state = SHEATH update_icon() to_chat(user, "<span class='notice'>I slice through the support rods.</span>") return 1 if(W.tool_behaviour == TOOL_WRENCH) to_chat(user, "<span class='notice'>I start tightening the bolts which secure the support rods to their frame...</span>") W.play_tool_sound(src, 100) if(W.use_tool(src, user, 40)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != SUPPORT_RODS) return 1 d_state = ANCHOR_BOLTS update_icon() to_chat(user, "<span class='notice'>I tighten the bolts anchoring the support rods.</span>") return 1 if(SHEATH) if(W.tool_behaviour == TOOL_CROWBAR) to_chat(user, "<span class='notice'>I struggle to pry off the outer sheath...</span>") if(W.use_tool(src, user, 100, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != SHEATH) return 1 to_chat(user, "<span class='notice'>I pry off the outer sheath.</span>") dismantle_wall() return 1 if(W.tool_behaviour == TOOL_WELDER) if(!W.tool_start_check(user, amount=0)) return to_chat(user, "<span class='notice'>I begin welding the support rods back together...</span>") if(W.use_tool(src, user, 100, volume=100)) if(!istype(src, /turf/closed/wall/r_wall) || d_state != SHEATH) return TRUE d_state = SUPPORT_RODS update_icon() to_chat(user, "<span class='notice'>I weld the support rods back together.</span>") return 1 return 0 /turf/closed/wall/r_wall/update_icon() . = ..() if(d_state != INTACT) smooth = SMOOTH_FALSE clear_smooth_overlays() else smooth = SMOOTH_TRUE queue_smooth_neighbors(src) queue_smooth(src) /turf/closed/wall/r_wall/update_icon_state() if(d_state != INTACT) icon_state = "r_wall-[d_state]" else icon_state = "r_wall"
411
0.97567
1
0.97567
game-dev
MEDIA
0.640211
game-dev
0.956794
1
0.956794
PacktPublishing/Mastering-Cpp-Game-Development
14,422
Chapter08/Include/bullet/BulletCollision/CollisionDispatch/btCompoundCompoundCollisionAlgorithm.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btCompoundCompoundCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/CollisionShapes/btCompoundShape.h" #include "BulletCollision/BroadphaseCollision/btDbvt.h" #include "LinearMath/btIDebugDraw.h" #include "LinearMath/btAabbUtil2.h" #include "BulletCollision/CollisionDispatch/btManifoldResult.h" #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h" btShapePairCallback gCompoundCompoundChildShapePairCallback = 0; btCompoundCompoundCollisionAlgorithm::btCompoundCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped) :btCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,isSwapped) { void* ptr = btAlignedAlloc(sizeof(btHashedSimplePairCache),16); m_childCollisionAlgorithmCache= new(ptr) btHashedSimplePairCache(); const btCollisionObjectWrapper* col0ObjWrap = body0Wrap; btAssert (col0ObjWrap->getCollisionShape()->isCompound()); const btCollisionObjectWrapper* col1ObjWrap = body1Wrap; btAssert (col1ObjWrap->getCollisionShape()->isCompound()); const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape()); m_compoundShapeRevision0 = compoundShape0->getUpdateRevision(); const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape()); m_compoundShapeRevision1 = compoundShape1->getUpdateRevision(); } btCompoundCompoundCollisionAlgorithm::~btCompoundCompoundCollisionAlgorithm() { removeChildAlgorithms(); m_childCollisionAlgorithmCache->~btHashedSimplePairCache(); btAlignedFree(m_childCollisionAlgorithmCache); } void btCompoundCompoundCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray) { int i; btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); for (i=0;i<pairs.size();i++) { if (pairs[i].m_userPointer) { ((btCollisionAlgorithm*)pairs[i].m_userPointer)->getAllContactManifolds(manifoldArray); } } } void btCompoundCompoundCollisionAlgorithm::removeChildAlgorithms() { btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); int numChildren = pairs.size(); int i; for (i=0;i<numChildren;i++) { if (pairs[i].m_userPointer) { btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer; algo->~btCollisionAlgorithm(); m_dispatcher->freeCollisionAlgorithm(algo); } } m_childCollisionAlgorithmCache->removeAllPairs(); } struct btCompoundCompoundLeafCallback : btDbvt::ICollide { int m_numOverlapPairs; const btCollisionObjectWrapper* m_compound0ColObjWrap; const btCollisionObjectWrapper* m_compound1ColObjWrap; btDispatcher* m_dispatcher; const btDispatcherInfo& m_dispatchInfo; btManifoldResult* m_resultOut; class btHashedSimplePairCache* m_childCollisionAlgorithmCache; btPersistentManifold* m_sharedManifold; btCompoundCompoundLeafCallback (const btCollisionObjectWrapper* compound1ObjWrap, const btCollisionObjectWrapper* compound0ObjWrap, btDispatcher* dispatcher, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut, btHashedSimplePairCache* childAlgorithmsCache, btPersistentManifold* sharedManifold) :m_numOverlapPairs(0),m_compound0ColObjWrap(compound1ObjWrap),m_compound1ColObjWrap(compound0ObjWrap),m_dispatcher(dispatcher),m_dispatchInfo(dispatchInfo),m_resultOut(resultOut), m_childCollisionAlgorithmCache(childAlgorithmsCache), m_sharedManifold(sharedManifold) { } void Process(const btDbvtNode* leaf0,const btDbvtNode* leaf1) { m_numOverlapPairs++; int childIndex0 = leaf0->dataAsInt; int childIndex1 = leaf1->dataAsInt; btAssert(childIndex0>=0); btAssert(childIndex1>=0); const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(m_compound0ColObjWrap->getCollisionShape()); btAssert(childIndex0<compoundShape0->getNumChildShapes()); const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(m_compound1ColObjWrap->getCollisionShape()); btAssert(childIndex1<compoundShape1->getNumChildShapes()); const btCollisionShape* childShape0 = compoundShape0->getChildShape(childIndex0); const btCollisionShape* childShape1 = compoundShape1->getChildShape(childIndex1); //backup btTransform orgTrans0 = m_compound0ColObjWrap->getWorldTransform(); const btTransform& childTrans0 = compoundShape0->getChildTransform(childIndex0); btTransform newChildWorldTrans0 = orgTrans0*childTrans0 ; btTransform orgTrans1 = m_compound1ColObjWrap->getWorldTransform(); const btTransform& childTrans1 = compoundShape1->getChildTransform(childIndex1); btTransform newChildWorldTrans1 = orgTrans1*childTrans1 ; //perform an AABB check first btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1; childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0); childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1); if (gCompoundCompoundChildShapePairCallback) { if (!gCompoundCompoundChildShapePairCallback(childShape0,childShape1)) return; } if (TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1)) { btCollisionObjectWrapper compoundWrap0(this->m_compound0ColObjWrap,childShape0, m_compound0ColObjWrap->getCollisionObject(),newChildWorldTrans0,-1,childIndex0); btCollisionObjectWrapper compoundWrap1(this->m_compound1ColObjWrap,childShape1,m_compound1ColObjWrap->getCollisionObject(),newChildWorldTrans1,-1,childIndex1); btSimplePair* pair = m_childCollisionAlgorithmCache->findPair(childIndex0,childIndex1); btCollisionAlgorithm* colAlgo = 0; if (pair) { colAlgo = (btCollisionAlgorithm*)pair->m_userPointer; } else { colAlgo = m_dispatcher->findAlgorithm(&compoundWrap0,&compoundWrap1,m_sharedManifold); pair = m_childCollisionAlgorithmCache->addOverlappingPair(childIndex0,childIndex1); btAssert(pair); pair->m_userPointer = colAlgo; } btAssert(colAlgo); const btCollisionObjectWrapper* tmpWrap0 = 0; const btCollisionObjectWrapper* tmpWrap1 = 0; tmpWrap0 = m_resultOut->getBody0Wrap(); tmpWrap1 = m_resultOut->getBody1Wrap(); m_resultOut->setBody0Wrap(&compoundWrap0); m_resultOut->setBody1Wrap(&compoundWrap1); m_resultOut->setShapeIdentifiersA(-1,childIndex0); m_resultOut->setShapeIdentifiersB(-1,childIndex1); colAlgo->processCollision(&compoundWrap0,&compoundWrap1,m_dispatchInfo,m_resultOut); m_resultOut->setBody0Wrap(tmpWrap0); m_resultOut->setBody1Wrap(tmpWrap1); } } }; static DBVT_INLINE bool MyIntersect( const btDbvtAabbMm& a, const btDbvtAabbMm& b, const btTransform& xform) { btVector3 newmin,newmax; btTransformAabb(b.Mins(),b.Maxs(),0.f,xform,newmin,newmax); btDbvtAabbMm newb = btDbvtAabbMm::FromMM(newmin,newmax); return Intersect(a,newb); } static inline void MycollideTT( const btDbvtNode* root0, const btDbvtNode* root1, const btTransform& xform, btCompoundCompoundLeafCallback* callback) { if(root0&&root1) { int depth=1; int treshold=btDbvt::DOUBLE_STACKSIZE-4; btAlignedObjectArray<btDbvt::sStkNN> stkStack; stkStack.resize(btDbvt::DOUBLE_STACKSIZE); stkStack[0]=btDbvt::sStkNN(root0,root1); do { btDbvt::sStkNN p=stkStack[--depth]; if(MyIntersect(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++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[0]); stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[0]); stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[1]); stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[1]); } else { stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b); stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b); } } else { if(p.b->isinternal()) { stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[0]); stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[1]); } else { callback->Process(p.a,p.b); } } } } while(depth); } } void btCompoundCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { const btCollisionObjectWrapper* col0ObjWrap = body0Wrap; const btCollisionObjectWrapper* col1ObjWrap= body1Wrap; btAssert (col0ObjWrap->getCollisionShape()->isCompound()); btAssert (col1ObjWrap->getCollisionShape()->isCompound()); const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape()); const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape()); const btDbvt* tree0 = compoundShape0->getDynamicAabbTree(); const btDbvt* tree1 = compoundShape1->getDynamicAabbTree(); if (!tree0 || !tree1) { return btCompoundCollisionAlgorithm::processCollision(body0Wrap,body1Wrap,dispatchInfo,resultOut); } ///btCompoundShape might have changed: ////make sure the internal child collision algorithm caches are still valid if ((compoundShape0->getUpdateRevision() != m_compoundShapeRevision0) || (compoundShape1->getUpdateRevision() != m_compoundShapeRevision1)) { ///clear all removeChildAlgorithms(); m_compoundShapeRevision0 = compoundShape0->getUpdateRevision(); m_compoundShapeRevision1 = compoundShape1->getUpdateRevision(); } ///we need to refresh all contact manifolds ///note that we should actually recursively traverse all children, btCompoundShape can nested more then 1 level deep ///so we should add a 'refreshManifolds' in the btCollisionAlgorithm { int i; btManifoldArray manifoldArray; btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); for (i=0;i<pairs.size();i++) { if (pairs[i].m_userPointer) { btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer; algo->getAllContactManifolds(manifoldArray); for (int m=0;m<manifoldArray.size();m++) { if (manifoldArray[m]->getNumContacts()) { resultOut->setPersistentManifold(manifoldArray[m]); resultOut->refreshContactPoints(); resultOut->setPersistentManifold(0); } } manifoldArray.resize(0); } } } btCompoundCompoundLeafCallback callback(col0ObjWrap,col1ObjWrap,this->m_dispatcher,dispatchInfo,resultOut,this->m_childCollisionAlgorithmCache,m_sharedManifold); const btTransform xform=col0ObjWrap->getWorldTransform().inverse()*col1ObjWrap->getWorldTransform(); MycollideTT(tree0->m_root,tree1->m_root,xform,&callback); //printf("#compound-compound child/leaf overlap =%d \r",callback.m_numOverlapPairs); //remove non-overlapping child pairs { btAssert(m_removePairs.size()==0); //iterate over all children, perform an AABB check inside ProcessChildShape btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray(); int i; btManifoldArray manifoldArray; btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1; for (i=0;i<pairs.size();i++) { if (pairs[i].m_userPointer) { btCollisionAlgorithm* algo = (btCollisionAlgorithm*)pairs[i].m_userPointer; { btTransform orgTrans0; const btCollisionShape* childShape0 = 0; btTransform newChildWorldTrans0; btTransform orgInterpolationTrans0; childShape0 = compoundShape0->getChildShape(pairs[i].m_indexA); orgTrans0 = col0ObjWrap->getWorldTransform(); orgInterpolationTrans0 = col0ObjWrap->getWorldTransform(); const btTransform& childTrans0 = compoundShape0->getChildTransform(pairs[i].m_indexA); newChildWorldTrans0 = orgTrans0*childTrans0 ; childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0); } { btTransform orgInterpolationTrans1; const btCollisionShape* childShape1 = 0; btTransform orgTrans1; btTransform newChildWorldTrans1; childShape1 = compoundShape1->getChildShape(pairs[i].m_indexB); orgTrans1 = col1ObjWrap->getWorldTransform(); orgInterpolationTrans1 = col1ObjWrap->getWorldTransform(); const btTransform& childTrans1 = compoundShape1->getChildTransform(pairs[i].m_indexB); newChildWorldTrans1 = orgTrans1*childTrans1 ; childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1); } if (!TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1)) { algo->~btCollisionAlgorithm(); m_dispatcher->freeCollisionAlgorithm(algo); m_removePairs.push_back(btSimplePair(pairs[i].m_indexA,pairs[i].m_indexB)); } } } for (int i=0;i<m_removePairs.size();i++) { m_childCollisionAlgorithmCache->removeOverlappingPair(m_removePairs[i].m_indexA,m_removePairs[i].m_indexB); } m_removePairs.clear(); } } btScalar btCompoundCompoundCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { btAssert(0); return 0.f; }
411
0.947826
1
0.947826
game-dev
MEDIA
0.74611
game-dev
0.959516
1
0.959516
Redot-Engine/redot-engine
7,178
modules/jolt_physics/spaces/jolt_space_3d.h
/**************************************************************************/ /* jolt_space_3d.h */ /**************************************************************************/ /* This file is part of: */ /* REDOT ENGINE */ /* https://redotengine.org */ /**************************************************************************/ /* Copyright (c) 2024-present Redot Engine contributors */ /* (see REDOT_AUTHORS.md) */ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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. */ /**************************************************************************/ #pragma once #include "servers/physics_server_3d.h" #include "Jolt/Jolt.h" #include "Jolt/Core/JobSystem.h" #include "Jolt/Core/TempAllocator.h" #include "Jolt/Physics/Body/BodyInterface.h" #include "Jolt/Physics/Collision/BroadPhase/BroadPhaseQuery.h" #include "Jolt/Physics/Collision/NarrowPhaseQuery.h" #include "Jolt/Physics/Constraints/Constraint.h" #include "Jolt/Physics/PhysicsSystem.h" class JoltArea3D; class JoltBody3D; class JoltBodyActivationListener3D; class JoltContactListener3D; class JoltJoint3D; class JoltLayers; class JoltObject3D; class JoltPhysicsDirectSpaceState3D; class JoltShapedObject3D; class JoltSoftBody3D; class JoltSpace3D { Mutex pending_objects_mutex; Mutex body_call_queries_mutex; SelfList<JoltBody3D>::List body_call_queries_list; SelfList<JoltArea3D>::List area_call_queries_list; SelfList<JoltShapedObject3D>::List shapes_changed_list; SelfList<JoltShapedObject3D>::List needs_optimization_list; LocalVector<JPH::BodyID> pending_objects_sleeping; LocalVector<JPH::BodyID> pending_objects_awake; RID rid; JPH::JobSystem *job_system = nullptr; JPH::TempAllocator *temp_allocator = nullptr; JoltLayers *layers = nullptr; JoltContactListener3D *contact_listener = nullptr; JoltBodyActivationListener3D *body_activation_listener = nullptr; JPH::PhysicsSystem *physics_system = nullptr; JoltPhysicsDirectSpaceState3D *direct_state = nullptr; JoltArea3D *default_area = nullptr; float last_step = 0.0f; bool active = false; bool stepping = false; void _pre_step(float p_step); void _post_step(float p_step); public: explicit JoltSpace3D(JPH::JobSystem *p_job_system); ~JoltSpace3D(); void step(float p_step); void call_queries(); RID get_rid() const { return rid; } void set_rid(const RID &p_rid) { rid = p_rid; } bool is_active() const { return active; } void set_active(bool p_active) { active = p_active; } bool is_stepping() const { return stepping; } double get_param(PhysicsServer3D::SpaceParameter p_param) const; void set_param(PhysicsServer3D::SpaceParameter p_param, double p_value); JPH::PhysicsSystem &get_physics_system() const { return *physics_system; } JPH::TempAllocator &get_temp_allocator() const { return *temp_allocator; } JPH::BodyInterface &get_body_iface(); const JPH::BodyInterface &get_body_iface() const; const JPH::BodyLockInterface &get_lock_iface() const; const JPH::BroadPhaseQuery &get_broad_phase_query() const; const JPH::NarrowPhaseQuery &get_narrow_phase_query() const; JPH::ObjectLayer map_to_object_layer(JPH::BroadPhaseLayer p_broad_phase_layer, uint32_t p_collision_layer, uint32_t p_collision_mask); void map_from_object_layer(JPH::ObjectLayer p_object_layer, JPH::BroadPhaseLayer &r_broad_phase_layer, uint32_t &r_collision_layer, uint32_t &r_collision_mask) const; JPH::Body *try_get_jolt_body(const JPH::BodyID &p_body_id) const; JoltObject3D *try_get_object(const JPH::BodyID &p_body_id) const; JoltShapedObject3D *try_get_shaped(const JPH::BodyID &p_body_id) const; JoltBody3D *try_get_body(const JPH::BodyID &p_body_id) const; JoltArea3D *try_get_area(const JPH::BodyID &p_body_id) const; JoltSoftBody3D *try_get_soft_body(const JPH::BodyID &p_body_id) const; JoltPhysicsDirectSpaceState3D *get_direct_state(); JoltArea3D *get_default_area() const { return default_area; } void set_default_area(JoltArea3D *p_area); float get_last_step() const { return last_step; } JPH::Body *add_object(const JoltObject3D &p_object, const JPH::BodyCreationSettings &p_settings, bool p_sleeping = false); JPH::Body *add_object(const JoltObject3D &p_object, const JPH::SoftBodyCreationSettings &p_settings, bool p_sleeping = false); void remove_object(const JPH::BodyID &p_jolt_id); void flush_pending_objects(); void set_is_object_sleeping(const JPH::BodyID &p_jolt_id, bool p_enable); void enqueue_call_queries(SelfList<JoltBody3D> *p_body); void enqueue_call_queries(SelfList<JoltArea3D> *p_area); void dequeue_call_queries(SelfList<JoltBody3D> *p_body); void dequeue_call_queries(SelfList<JoltArea3D> *p_area); void enqueue_shapes_changed(SelfList<JoltShapedObject3D> *p_object); void dequeue_shapes_changed(SelfList<JoltShapedObject3D> *p_object); void enqueue_needs_optimization(SelfList<JoltShapedObject3D> *p_object); void dequeue_needs_optimization(SelfList<JoltShapedObject3D> *p_object); void add_joint(JPH::Constraint *p_jolt_ref); void add_joint(JoltJoint3D *p_joint); void remove_joint(JPH::Constraint *p_jolt_ref); void remove_joint(JoltJoint3D *p_joint); #ifdef DEBUG_ENABLED void dump_debug_snapshot(const String &p_dir); const PackedVector3Array &get_debug_contacts() const; int get_debug_contact_count() const; int get_max_debug_contacts() const; void set_max_debug_contacts(int p_count); #endif };
411
0.903984
1
0.903984
game-dev
MEDIA
0.965482
game-dev
0.775547
1
0.775547
MichaelPilyavskiy/ReaScripts
1,764
Ruler/mpl_Cycle grid values (mousewheel).lua
-- @description Cycle grid values (mousewheel) -- @version 1.01 -- @author MPL -- @website http://forum.cockos.com/showthread.php?t=188335 -- @changelog -- # VF independent for key in pairs(reaper) do _G[key]=reaper[key] end --------------------------------------------------- function VF_CheckReaperVrs(rvrs, showmsg) local vrs_num = GetAppVersion() vrs_num = tonumber(vrs_num:match('[%d%.]+')) if rvrs > vrs_num then if showmsg then reaper.MB('Update REAPER to newer version '..'('..rvrs..' or newer)', '', 0) end return else return true end end --------------------------------------------------- function VF2_CycleGrid(stages) local _,_,_,_,_,_,mouse_scroll = reaper.get_action_context() stateid = reaper.GetExtState( 'mpl_cycle_grid', 'val' ) stateid = tonumber(stateid) or 1 if mouse_scroll == -1 then return end if mouse_scroll > 0 then stateid = stateid + 1 elseif mouse_scroll < 0 then stateid = stateid - 1 end local outval = math.min(#stages, math.max(stateid, 1)) reaper.SetExtState( 'mpl_cycle_grid', 'val' , outval, true) if stages[outval] ~= 0 then reaper.Main_OnCommand(40754,0) --Snapping: Enable snap reaper.SetProjectGrid( 0, stages[outval] ) else reaper.Main_OnCommand(40753,0) -- Snapping: Disable snap end end -------------------------------------------------------------------- local stages = {0, 1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/3, 1/6, 1/12, 1/24, 1/48} ------------------------------------------------------------------ if VF_CheckReaperVrs(5.975,true) then reaper.defer(function() VF2_CycleGrid(stages) end) end
411
0.806594
1
0.806594
game-dev
MEDIA
0.770446
game-dev
0.968982
1
0.968982
LordOfDragons/dragengine
8,341
src/modules/graphic/opengl/src/envmap/deoglEnvMapSlotManager.cpp
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <math.h> #include <stdio.h> #include <string.h> #include "deoglEnvironmentMap.h" #include "deoglEnvMapSlotManager.h" #include "deoglEnvMapSlot.h" #include "../renderthread/deoglRenderThread.h" #include "../renderthread/deoglRTLogger.h" #include "../texture/arraytexture/deoglArrayTexture.h" #include "../texture/texture2d/deoglTexture.h" #include <dragengine/common/exceptions.h> // Class deoglEnvMapSlotManager ///////////////////////////////// // Constructor, destructor //////////////////////////// deoglEnvMapSlotManager::deoglEnvMapSlotManager( deoglRenderThread &renderThread ) : pRenderThread( renderThread ){ pArrayTexture = NULL; pWidth = 512; pHeight = 256; pLayerCount = 5; pSlots = NULL; pUsedSlots = NULL; pUsedSlotsSize = 0; pUsedSlotsCount = 0; // memory consumption with 512x256: // ((512*256*3*2)*4/3) = 1048576 bytes ~= 1MB // // memory consumption with 256x128: // ((245*128*3*2)*4/3) = 250880 bytes ~= 0.25MB try{ pSlots = new deoglEnvMapSlot[ pLayerCount ]; pArrayTexture = new deoglArrayTexture( renderThread ); pArrayTexture->SetSize( pWidth, pHeight, pLayerCount ); pArrayTexture->SetFBOFormat( 3, true ); pArrayTexture->SetMipMapped( true ); pArrayTexture->CreateTexture(); }catch( const deException & ){ pCleanUp(); throw; } } deoglEnvMapSlotManager::~deoglEnvMapSlotManager(){ pCleanUp(); } // Management /////////////// deoglEnvMapSlot &deoglEnvMapSlotManager::GetSlotAt( int index ) const{ if( index < 0 || index >= pLayerCount ){ DETHROW( deeInvalidParam ); } return pSlots[ index ]; } int deoglEnvMapSlotManager::IndexOfSlotWith( deoglEnvironmentMap *envmap ) const{ if( ! envmap ){ DETHROW( deeInvalidParam ); } int i; for( i=0; i<pLayerCount; i++ ){ if( envmap == pSlots[ i ].GetEnvMap() ){ return i; } } return -1; } int deoglEnvMapSlotManager::IndexOfOldestUnusedSlot() const{ int oldestLastUsed = 0; int slotIndex = -1; int i; for( i=0; i<pLayerCount; i++ ){ // also protect all slots used in this and the last frame? // if( ! pSlots[ i ].GetInUse() && pSlots[ i ].GetLastUsed() > 1 && ( slotIndex == -1 || pSlots[ i ].GetLastUsed() > oldestLastUsed ) ){ // or used in this frame? // if( ! pSlots[ i ].GetInUse() && pSlots[ i ].GetLastUsed() > 0 && ( slotIndex == -1 || pSlots[ i ].GetLastUsed() > oldestLastUsed ) ){ if( ! pSlots[ i ].GetInUse() && ( slotIndex == -1 || pSlots[ i ].GetLastUsed() > oldestLastUsed ) ){ slotIndex = i; oldestLastUsed = pSlots[ i ].GetLastUsed(); } } return slotIndex; } void deoglEnvMapSlotManager::MarkSlotsUnused(){ int i; for( i=0; i<pLayerCount; i++ ){ pSlots[ i ].SetInUse( false ); } } void deoglEnvMapSlotManager::AddEnvironmentMap( deoglEnvironmentMap *envmap ){ if( ! envmap ){ DETHROW( deeInvalidParam ); } int slotIndex = envmap->GetSlotIndex(); if( slotIndex == -1 ){ // if the environment map is not hosted by any slots find the oldest unused slot slotIndex = IndexOfOldestUnusedSlot(); if( slotIndex == -1 ){ // if there are no empty slots available we have to increase the layer count to make room for more const int newLayerCount = pLayerCount + 5; int i; pRenderThread.GetLogger().LogInfoFormat( "EnvMapSlotManager.AddEnvironmentMap: Increase layer count from %i to %i", pLayerCount, newLayerCount ); //printf( "EnvMapSlotManager.AddEnvironmentMap: Increase layer count from %i to %i\n", pLayerCount, newLayerCount ); slotIndex = pLayerCount; // this is going to be the new slot to assign the environment map to // enlarge also the array texture. this unfortunately erases all the content so we have to copy // the textures of all environment maps to the corresponding layer pArrayTexture->SetSize( pWidth, pHeight, newLayerCount ); pArrayTexture->CreateTexture(); pArrayTexture->CreateMipMaps(); // would be better to have a quicker init here to make sure the mip map levels exist for( i=0; i<pLayerCount; i++ ){ if( pSlots[ i ].GetEnvMap() && pSlots[ i ].GetEnvMap()->GetEquiEnvMap() && pSlots[ i ].GetEnvMap()->GetEquiEnvMap()->GetTexture() ){ pRenderThread.GetLogger().LogInfoFormat( "EnvMapSlotManager.AddEnvironmentMap(IncreaseLayer): Copy EnvMap %p to layer %i", pSlots[ i ].GetEnvMap(), i ); //printf( "EnvMapSlotManager.AddEnvironmentMap(IncreaseLayer): Copy EnvMap %p to layer %i\n", pSlots[ i ].GetEnvMap(), i ); pArrayTexture->CopyFrom( *pSlots[ i ].GetEnvMap()->GetEquiEnvMap(), true, i ); } } // add more slots deoglEnvMapSlot * const newArray = new deoglEnvMapSlot[ newLayerCount ]; memcpy( newArray, pSlots, sizeof( deoglEnvMapSlot ) * pLayerCount ); delete [] pSlots; pSlots = newArray; pLayerCount = newLayerCount; } // assign the environment map to the found slot and copy the texture to the corresponding level in the array texture if( pSlots[ slotIndex ].GetEnvMap() ){ pSlots[ slotIndex ].GetEnvMap()->SetSlotIndex( -1 ); } pSlots[ slotIndex ].SetEnvMap( envmap ); envmap->SetSlotIndex( slotIndex ); pRenderThread.GetLogger().LogInfoFormat( "EnvMapSlotManager.AddEnvironmentMap: Copy EnvMap %p to layer %i", envmap, slotIndex ); //printf( "EnvMapSlotManager.AddEnvironmentMap: Copy EnvMap %p to layer %i\n", envmap, slotIndex ); pArrayTexture->CopyFrom( *pSlots[ slotIndex ].GetEnvMap()->GetEquiEnvMap(), true, slotIndex ); } // in all cases mark the slot in use and reset the last used counter to 0 pSlots[ slotIndex ].SetInUse( true ); pSlots[ slotIndex ].ResetLastUsed(); } void deoglEnvMapSlotManager::IncreaseSlotLastUsedCounters(){ int i; for( i=0; i<pLayerCount; i++ ){ pSlots[ i ].IncrementLastUsed(); } } void deoglEnvMapSlotManager::NotifyEnvMapChanged( int slotIndex ){ if( slotIndex < 0 || slotIndex >= pLayerCount || ! pSlots[ slotIndex ].GetEnvMap() ){ DETHROW( deeInvalidParam ); } pRenderThread.GetLogger().LogInfoFormat( "EnvMapSlotManager.NotifyEnvMapChanged: Copy EnvMap %p to layer %i", pSlots[ slotIndex ].GetEnvMap(), slotIndex ); //printf( "EnvMapSlotManager.NotifyEnvMapChanged: Copy EnvMap %p to layer %i\n", pSlots[ slotIndex ].GetEnvMap(), slotIndex ); pArrayTexture->CopyFrom( *pSlots[ slotIndex ].GetEnvMap()->GetEquiEnvMap(), true, slotIndex ); } int deoglEnvMapSlotManager::GetUsedSlotIndexAt( int index ) const{ if( index < 0 || index >= pUsedSlotsCount ){ DETHROW( deeInvalidParam ); } return pUsedSlots[ index ]; } void deoglEnvMapSlotManager::UpdateUsedSlots(){ int i; if( pUsedSlotsSize < pLayerCount ){ int * const newArray = new int[ pLayerCount ]; if( pUsedSlots ){ memcpy( newArray, pUsedSlots, sizeof( int ) * pUsedSlotsSize ); delete [] pUsedSlots; } pUsedSlots = newArray; pUsedSlotsSize = pLayerCount; } pUsedSlotsCount = 0; for( i=0; i<pLayerCount; i++ ){ if( pSlots[ i ].GetInUse() ){ pUsedSlots[ pUsedSlotsCount++ ] = i; } } } // Private Functions ////////////////////// void deoglEnvMapSlotManager::pCleanUp(){ if( pArrayTexture ){ delete pArrayTexture; } if( pUsedSlots ){ delete [] pUsedSlots; } if( pSlots ){ delete [] pSlots; } }
411
0.884017
1
0.884017
game-dev
MEDIA
0.689374
game-dev
0.957253
1
0.957253
dilmerv/MetaInteractionSDKDemos
1,256
Assets/Oculus/SampleFramework/Usage/Passthrough/Scripts/AugmentedObject.cs
using UnityEngine; public class AugmentedObject : MonoBehaviour { public OVRInput.Controller controllerHand = OVRInput.Controller.None; public Transform shadow; bool groundShadow = false; void Start() { if (GetComponent<GrabObject>()) { GetComponent<GrabObject>().GrabbedObjectDelegate += Grab; GetComponent<GrabObject>().ReleasedObjectDelegate += Release; } } void Update() { if (controllerHand != OVRInput.Controller.None) { if (OVRInput.GetUp(OVRInput.Button.One, controllerHand)) { ToggleShadowType(); } } if (shadow) { if (groundShadow) { shadow.transform.position = new Vector3(transform.position.x, 0, transform.position.z); } else { shadow.transform.localPosition = Vector3.zero; } } } public void Grab(OVRInput.Controller grabHand) { controllerHand = grabHand; } public void Release() { controllerHand = OVRInput.Controller.None; } void ToggleShadowType() { groundShadow = !groundShadow; } }
411
0.773425
1
0.773425
game-dev
MEDIA
0.768509
game-dev
0.807161
1
0.807161
manisha-v/Unity3D
25,286
Part1 - 3D Movement/Codes/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/MoveDirection.cs
namespace UnityEngine.EventSystems { /// <summary> /// This is an 4 direction movement enum. /// </summary> /// <remarks> /// MoveDirection provides a way of switching between moving states. You must assign these states to actions, such as moving the GameObject by an up vector when in the Up state. /// Having states like these are easier to identify than always having to include a large amount of vectors and calculations.Instead, you define what you want the state to do in only one part, and switch to the appropriate state when it is needed. /// </remarks> /// <example> /// <code> /// //This is a full example of how a GameObject changes direction using MoveDirection states /// //Assign this script to a visible GameObject (with a Rigidbody attached) to see it in action /// /// using UnityEngine; /// using UnityEngine.EventSystems; /// /// public class Example : MonoBehaviour /// { /// Vector3 m_StartPosition, m_StartForce; /// Rigidbody m_Rigidbody; /// //Use Enum for easy switching between direction states /// MoveDirection m_MoveDirection; /// /// //Use these Vectors for moving Rigidbody components /// Vector3 m_ResetVector; /// Vector3 m_UpVector; /// Vector3 m_RightVector; /// const float speed = 5.0f; /// /// void Start() /// { /// //You get the Rigidbody component attached to the GameObject /// m_Rigidbody = GetComponent<Rigidbody>(); /// //This starts with the Rigidbody not moving in any direction at all /// m_MoveDirection = MoveDirection.None; /// /// //These are the GameObject’s starting position and Rigidbody position /// m_StartPosition = transform.position; /// m_StartForce = m_Rigidbody.transform.position; /// /// //This Vector is set to 1 in the y axis (for moving upwards) /// m_UpVector = Vector3.up; /// //This Vector is set to 1 in the x axis (for moving in the right direction) /// m_RightVector = Vector3.right; /// //This Vector is zeroed out for when the Rigidbody should not move /// m_ResetVector = Vector3.zero; /// } /// /// void Update() /// { /// //This switches the direction depending on button presses /// switch (m_MoveDirection) /// { /// //The starting state which resets the object /// case MoveDirection.None: /// //Reset to the starting position of the GameObject and Rigidbody /// transform.position = m_StartPosition; /// m_Rigidbody.transform.position = m_StartForce; /// //This resets the velocity of the Rigidbody /// m_Rigidbody.velocity = m_ResetVector; /// break; /// /// //This is for moving in an upwards direction /// case MoveDirection.Up: /// //Change the velocity so that the Rigidbody travels upwards /// m_Rigidbody.velocity = m_UpVector * speed; /// break; /// /// //This is for moving left /// case MoveDirection.Left: /// //This moves the Rigidbody to the left (minus right Vector) /// m_Rigidbody.velocity = -m_RightVector * speed; /// break; /// /// //This is for moving right /// case MoveDirection.Right: /// //This moves the Rigidbody to the right /// m_Rigidbody.velocity = m_RightVector * speed; /// break; /// /// //This is for moving down /// case MoveDirection.Down: /// //This moves the Rigidbody down /// m_Rigidbody.velocity = -m_UpVector * speed; /// break; /// } /// } /// /// void OnGUI() /// { /// //Press the reset Button to switch to no mode /// if (GUI.Button(new Rect(100, 0, 150, 30), "Reset")) /// { /// //Switch to start/reset case /// m_MoveDirection = MoveDirection.None; /// } /// /// //Press the Left button to switch the Rigidbody direction to the left /// if (GUI.Button(new Rect(100, 30, 150, 30), "Move Left")) /// { /// //Switch to the left direction /// m_MoveDirection = MoveDirection.Left; /// } /// /// //Press the Up button to switch the Rigidbody direction to upwards /// if (GUI.Button(new Rect(100, 60, 150, 30), "Move Up")) /// { /// //Switch to Up Direction /// m_MoveDirection = MoveDirection.Up; /// } /// /// //Press the Down button to switch the direction to down /// if (GUI.Button(new Rect(100, 90, 150, 30), "Move Down")) /// { /// //Switch to Down Direction /// m_MoveDirection = MoveDirection.Down; /// } /// /// //Press the right button to switch to the right direction /// if (GUI.Button(new Rect(100, 120, 150, 30), "Move Right")) /// { /// //Switch to Right Direction /// m_MoveDirection = MoveDirection.Right; /// } /// } /// } /// </code> /// </example> public enum MoveDirection { /// <summary> /// This is the Left state of MoveDirection. Assign functionality for moving to the left. /// </summary> /// <remarks> /// Use the Left state for an easily identifiable way of moving a GameObject to the left (-1 , 0 , 0). This is a state without any predefined functionality. Before using this state, you should define what your GameObject will do in code. /// </remarks> /// <example> /// <code> /// //Assign this script to a visible GameObject (with a Rigidbody attached) to see this in action /// /// using UnityEngine; /// using UnityEngine.EventSystems; /// /// public class Example : MonoBehaviour /// { /// Vector3 m_StartPosition, m_StartForce; /// Rigidbody m_Rigidbody; /// //Use Enum for easy switching between direction states /// MoveDirection m_MoveDirection; /// /// //Use these Vectors for moving Rigidbody components /// Vector3 m_ResetVector; /// Vector3 m_RightVector; /// const float speed = 5.0f; /// /// void Start() /// { /// //You get the Rigidbody component attached to the GameObject /// m_Rigidbody = GetComponent<Rigidbody>(); /// //This starts with the Rigidbody not moving in any direction at all /// m_MoveDirection = MoveDirection.None; /// /// //These are the GameObject’s starting position and Rigidbody position /// m_StartPosition = transform.position; /// m_StartForce = m_Rigidbody.transform.position; /// /// //This Vector is set to 1 in the x axis (for moving in the right direction) /// m_RightVector = Vector3.right; /// //This Vector is zeroed out for when the Rigidbody should not move /// m_ResetVector = Vector3.zero; /// } /// /// void Update() /// { /// //This switches the direction depending on button presses /// switch (m_MoveDirection) /// { /// //The starting state which resets the object /// case MoveDirection.None: /// //Reset to the starting position of the GameObject and Rigidbody /// transform.position = m_StartPosition; /// m_Rigidbody.transform.position = m_StartForce; /// //This resets the velocity of the Rigidbody /// m_Rigidbody.velocity = m_ResetVector; /// break; /// /// //This is for moving left /// case MoveDirection.Left: /// //This moves the Rigidbody to the left (minus right Vector) /// m_Rigidbody.velocity = -m_RightVector * speed; /// break; /// } /// } /// /// void OnGUI() /// { /// //Press the reset Button to switch to no mode /// if (GUI.Button(new Rect(100, 0, 150, 30), "Reset")) /// { /// //Switch to start/reset case /// m_MoveDirection = MoveDirection.None; /// } /// /// //Press the Left button to switch the Rigidbody direction to the left /// if (GUI.Button(new Rect(100, 30, 150, 30), "Move Left")) /// { /// //Switch to the left direction /// m_MoveDirection = MoveDirection.Left; /// } /// } /// } /// </code> /// </example> Left, /// <summary> /// This is the Up state of MoveDirection. Assign functionality for moving in an upward direction. /// </summary> /// <remarks> /// Use the Up state for an easily identifiable way of moving a GameObject upwards (0 , 1 , 0). This is a state without any predefined functionality. Before using this state, you should define what your GameObject will do in code. /// </remarks> /// <example> /// <code> /// //Attach this script to a GameObject with a Rigidbody component. Press the "Move Up" button in Game view to see it in action. /// /// using UnityEngine; /// using UnityEngine.EventSystems; /// /// public class Example : MonoBehaviour /// { /// Vector3 m_StartPosition, m_StartForce; /// Rigidbody m_Rigidbody; /// //Use Enum for easy switching between direction states /// MoveDirection m_MoveDirection; /// /// //Use these Vectors for moving Rigidbody components /// Vector3 m_ResetVector; /// Vector3 m_UpVector; /// const float speed = 10.0f; /// /// void Start() /// { /// //You get the Rigidbody component attached to the GameObject /// m_Rigidbody = GetComponent<Rigidbody>(); /// //This starts with the Rigidbody not moving in any direction at all /// m_MoveDirection = MoveDirection.None; /// /// //These are the GameObject’s starting position and Rigidbody position /// m_StartPosition = transform.position; /// m_StartForce = m_Rigidbody.transform.position; /// /// //This Vector is set to 1 in the y axis (for moving upwards) /// m_UpVector = Vector3.up; /// //This Vector is zeroed out for when the Rigidbody should not move /// m_ResetVector = Vector3.zero; /// } /// /// void Update() /// { /// //This switches the direction depending on button presses /// switch (m_MoveDirection) /// { /// //The starting state which resets the object /// case MoveDirection.None: /// //Reset to the starting position of the GameObject and Rigidbody /// transform.position = m_StartPosition; /// m_Rigidbody.transform.position = m_StartForce; /// //This resets the velocity of the Rigidbody /// m_Rigidbody.velocity = m_ResetVector; /// break; /// /// //This is for moving in an upwards direction /// case MoveDirection.Up: /// //Change the velocity so that the Rigidbody travels upwards /// m_Rigidbody.velocity = m_UpVector * speed; /// break; /// } /// } /// /// void OnGUI() /// { /// //Press the reset Button to switch to no mode /// if (GUI.Button(new Rect(100, 0, 150, 30), "Reset")) /// { /// //Switch to start/reset case /// m_MoveDirection = MoveDirection.None; /// } /// /// //Press the Up button to switch the Rigidbody direction to upwards /// if (GUI.Button(new Rect(100, 60, 150, 30), "Move Up")) /// { /// //Switch to Up Direction /// m_MoveDirection = MoveDirection.Up; /// } /// } /// } /// </code> /// </example> Up, /// <summary> /// This is the Right state of MoveDirection. Assign functionality for moving to the right. /// </summary> /// <remarks> /// Use the Right state for an easily identifiable way of moving a GameObject to the right (1 , 0 , 0). This is a state without any predefined functionality. Before using this state, you should define what your GameObject will do in code. /// </remarks> /// <example> /// <code> /// //Attach this script to a GameObject with a Rigidbody component. Press the "Move Right" button in Game view to see it in action. /// /// using UnityEngine; /// using UnityEngine.EventSystems; /// /// public class MoveDirectionExample : MonoBehaviour /// { /// Vector3 m_StartPosition, m_StartForce; /// Rigidbody m_Rigidbody; /// //Use Enum for easy switching between direction states /// MoveDirection m_MoveDirection; /// /// //Use these Vectors for moving Rigidbody components /// Vector3 m_ResetVector; /// Vector3 m_RightVector; /// const float speed = 5.0f; /// /// void Start() /// { /// //You get the Rigidbody component attached to the GameObject /// m_Rigidbody = GetComponent<Rigidbody>(); /// //This starts with the Rigidbody not moving in any direction at all /// m_MoveDirection = MoveDirection.None; /// /// //These are the GameObject’s starting position and Rigidbody position /// m_StartPosition = transform.position; /// m_StartForce = m_Rigidbody.transform.position; /// /// //This Vector is set to 1 in the x axis (for moving in the right direction) /// m_RightVector = Vector3.right; /// //This Vector is zeroed out for when the Rigidbody should not move /// m_ResetVector = Vector3.zero; /// } /// /// void Update() /// { /// //This switches the direction depending on button presses /// switch (m_MoveDirection) /// { /// //The starting state which resets the object /// case MoveDirection.None: /// //Reset to the starting position of the GameObject and Rigidbody /// transform.position = m_StartPosition; /// m_Rigidbody.transform.position = m_StartForce; /// //This resets the velocity of the Rigidbody /// m_Rigidbody.velocity = m_ResetVector; /// break; /// /// //This is for moving right /// case MoveDirection.Right: /// //This moves the Rigidbody to the right /// m_Rigidbody.velocity = m_RightVector * speed; /// break; /// } /// } /// /// void OnGUI() /// { /// //Press the reset Button to switch to no mode /// if (GUI.Button(new Rect(100, 0, 150, 30), "Reset")) /// { /// //Switch to start/reset case /// m_MoveDirection = MoveDirection.None; /// } /// /// //Press the Left button to switch the Rigidbody direction to the right /// if (GUI.Button(new Rect(100, 30, 150, 30), "Move Right")) /// { /// //Switch to the left direction /// m_MoveDirection = MoveDirection.Right; /// } /// } /// } /// </code> /// </example> Right, /// <summary> /// The Down State of MoveDirection. Assign functionality for moving in a downward direction. /// </summary> /// <remarks> /// Use the Down state for an easily identifiable way of moving a GameObject downwards (0 , -1 , 0). This is a state without any predefined functionality. Before using this state, you should define what your GameObject will do in code. /// </remarks> /// <example> /// <code> /// //Attach this script to a GameObject with a Rigidbody component. Press the "Move Down" button in Game view to see it in action. /// /// using UnityEngine; /// using UnityEngine.EventSystems; /// /// public class Example : MonoBehaviour /// { /// Vector3 m_StartPosition, m_StartForce; /// Rigidbody m_Rigidbody; /// //Use Enum for easy switching between direction states /// MoveDirection m_MoveDirection; /// /// //Use these Vectors for moving Rigidbody components /// Vector3 m_ResetVector; /// Vector3 m_UpVector; /// const float speed = 10.0f; /// /// void Start() /// { /// //You get the Rigidbody component attached to the GameObject /// m_Rigidbody = GetComponent<Rigidbody>(); /// //This starts with the Rigidbody not moving in any direction at all /// m_MoveDirection = MoveDirection.None; /// /// //These are the GameObject’s starting position and Rigidbody position /// m_StartPosition = transform.position; /// m_StartForce = m_Rigidbody.transform.position; /// /// //This Vector is set to 1 in the y axis (for moving upwards) /// m_UpVector = Vector3.up; /// //This Vector is zeroed out for when the Rigidbody should not move /// m_ResetVector = Vector3.zero; /// } /// /// void Update() /// { /// //This switches the direction depending on button presses /// switch (m_MoveDirection) /// { /// //The starting state which resets the object /// case MoveDirection.None: /// //Reset to the starting position of the GameObject and Rigidbody /// transform.position = m_StartPosition; /// m_Rigidbody.transform.position = m_StartForce; /// //This resets the velocity of the Rigidbody /// m_Rigidbody.velocity = m_ResetVector; /// break; /// /// //This is for moving down /// case MoveDirection.Down: /// //This moves the Rigidbody down /// m_Rigidbody.velocity = -m_UpVector * speed; /// break; /// } /// } /// /// void OnGUI() /// { /// //Press the reset Button to switch to no mode /// if (GUI.Button(new Rect(100, 0, 150, 30), "Reset")) /// { /// //Switch to start/reset case /// m_MoveDirection = MoveDirection.None; /// } /// /// //Press the Down button to switch the direction to down /// if (GUI.Button(new Rect(100, 90, 150, 30), "Move Down")) /// { /// //Switch to Down Direction /// m_MoveDirection = MoveDirection.Down; /// } /// } /// } /// </code> /// </example> Down, /// <summary> /// This is the None state. Assign functionality that stops movement. /// </summary> /// <remarks> /// Use the None state for an easily identifiable way of stopping, resetting or initialising a GameObject's movement. This is a state without any predefined functionality. Before using this state, you should define what your GameObject will do in code. /// </remarks> /// <example> /// <code> /// //Attach this script to a GameObject with a Rigidbody attached. This script starts off on the ModeDirection.None state but changes depending on buttons you press. /// /// using UnityEngine; /// using UnityEngine.EventSystems; /// /// public class Example : MonoBehaviour /// { /// Vector3 m_StartPosition, m_StartForce; /// Rigidbody m_Rigidbody; /// //Use Enum for easy switching between direction states /// MoveDirection m_MoveDirection; /// /// //Use these Vectors for moving Rigidbody components /// Vector3 m_ResetVector; /// Vector3 m_UpVector; /// const float speed = 10.0f; /// /// void Start() /// { /// //You get the Rigidbody component attached to the GameObject /// m_Rigidbody = GetComponent<Rigidbody>(); /// //This starts with the Rigidbody not moving in any direction at all /// m_MoveDirection = MoveDirection.None; /// /// //These are the GameObject’s starting position and Rigidbody position /// m_StartPosition = transform.position; /// m_StartForce = m_Rigidbody.transform.position; /// /// //This Vector is set to 1 in the y axis (for moving upwards) /// m_UpVector = Vector3.up; /// //This Vector is zeroed out for when the Rigidbody should not move /// m_ResetVector = Vector3.zero; /// } /// /// void Update() /// { /// //This switches the direction depending on button presses /// switch (m_MoveDirection) /// { /// //The starting state which resets the object /// case MoveDirection.None: /// //Reset to the starting position of the GameObject and Rigidbody /// transform.position = m_StartPosition; /// m_Rigidbody.transform.position = m_StartForce; /// //This resets the velocity of the Rigidbody /// m_Rigidbody.velocity = m_ResetVector; /// break; /// /// //This is for moving down /// case MoveDirection.Down: /// //This moves the Rigidbody down /// m_Rigidbody.velocity = -m_UpVector * speed; /// break; /// } /// } /// /// void OnGUI() /// { /// //Press the reset Button to switch to no mode /// if (GUI.Button(new Rect(100, 0, 150, 30), "Reset")) /// { /// //Switch to start/reset case /// m_MoveDirection = MoveDirection.None; /// } /// /// //Press the Down button to switch the direction to down /// if (GUI.Button(new Rect(100, 90, 150, 30), "Move Down")) /// { /// //Switch to Down Direction /// m_MoveDirection = MoveDirection.Down; /// } /// } /// } /// </code> /// </example> None } }
411
0.690179
1
0.690179
game-dev
MEDIA
0.963065
game-dev
0.789244
1
0.789244
protoman/rockbot
133,393
character/character.cpp
#include "character.h" #include "../game.h" #include "../timerlib.h" #include "shareddata.h" extern game gameControl; extern timerLib timer; #include "../soundlib.h" extern soundLib soundManager; #include "../inputlib.h" extern inputLib input; #include "../game_mediator.h" #ifdef ANDROID #include <android/log.h> #endif #define STAIR_ANIMATION_WAIT_FRAMES 10 #define STAIRS_GRAB_TIMEOUT 200 #define SLIDE_Y_ADJUST 12 extern bool GAME_FLAGS[FLAG_COUNT]; extern CURRENT_FILE_FORMAT::file_game game_data; extern CURRENT_FILE_FORMAT::st_save game_save; extern FREEZE_EFFECT_TYPES freeze_weapon_effect; extern int freeze_weapon_id; // initialize static member static std::map<std::string, graphicsLib_gSurface> _character_frames_surface; // init character with default values // ********************************************************************************************** // // // // ********************************************************************************************** // character::character() : hitPoints(1, 1), last_hit_time(0), is_player_type(false), _platform(NULL), hit_animation_timer(0), hit_moved_back_n(0), jump_button_released(true), attack_button_released(true), dead(false), charging_color_n(0), charging_color_timer(0), shield_type(0), _moving_platform_timer(0), position(), _number(0), _super_jump(false), _force_jump(false), _teleport_minimal_y(0), _is_falling(false), _dead_state(0), slide_type(0), _water_splash(false), _has_background(false), hit_duration(300), _is_boss(false), _is_stage_boss(false), is_ghost(false) { _was_animation_reset = false; move_speed = 2.0 * SharedData::get_instance()->get_movement_multiplier(); accel_speed_y = 1; gravity_y = 0.25; position.y = 0; position.x = 0; can_fly = false; attack_state = ATTACK_NOT; max_projectiles = 1; _debug_char_name = "PLAYER_0"; _stairs_stopped_count = 0; _charged_shot_projectile_id = -1; _normal_shot_projectile_id = 0; _is_last_frame = false; _simultaneous_shots = 1; _ignore_gravity = false; _always_move_ahead = false; _was_hit = false; _progressive_appear_pos = 0; last_execute_time = 0; _check_always_move_ahead = false; _dropped_from_stairs = false; _jumps_number = 1; _dash_button_released = true; _damage_modifier = 0; _hit_ground = false; _dashed_jump = false; _can_execute_airdash = true; _player_must_reset_colors = false; hit_animation_count = 0; _attack_frame_n = -1; _is_attack_frame = false; _stairs_falling_timer = 0; attack_button_pressed_timer = 0; attack_button_last_state = 0; must_show_dash_effect = false; } // init character with default values // ********************************************************************************************** // // // // ********************************************************************************************** // character::~character() { clean_projectiles(); /// @TODO free map _character_frames_surface } // ********************************************************************************************** // // // // ********************************************************************************************** // void character::char_update_real_position() { if (gameControl.get_current_map_obj() != NULL) { realPosition.x = position.x - (int)gameControl.get_current_map_obj()->getMapScrolling().x; realPosition.y = position.y - (int)gameControl.get_current_map_obj()->getMapScrolling().y; } else { realPosition.x = position.x; realPosition.y = position.y; } } st_float_position character::get_screen_position_from_point(st_float_position pos) { st_float_position res_pos; if (gameControl.get_current_map_obj() != NULL) { res_pos.x = pos.x - (int)gameControl.get_current_map_obj()->getMapScrolling().x; res_pos.y = pos.y - (int)gameControl.get_current_map_obj()->getMapScrolling().y; } else { res_pos.x = pos.x; res_pos.y = pos.y; } return res_pos; } // ********************************************************************************************** // // // // ********************************************************************************************** // void character::charMove() { int mapLock = 0; bool moved = false; float temp_move_speed = move_speed; // store previous position store_previous_position(); if (timer.is_paused() == true) { return; } bool did_hit_ground = hit_ground(); if (_dashed_jump == true) { if (state.animation_type == ANIM_TYPE_JUMP || state.animation_type == ANIM_TYPE_JUMP_ATTACK) { temp_move_speed = move_speed * 2; if (did_hit_ground == true) { _dashed_jump = false; } } } if (did_hit_ground == true) { _can_execute_airdash = true; } if (gameControl.get_current_map_obj() == NULL) { return; // error - can't execute this action without an associated map } int water_lock = gameControl.get_current_map_obj()->getMapPointLock(st_position((position.x+frameSize.width/2)/TILESIZE, (position.y+6)/TILESIZE)); if (is_player() == true && water_lock == TERRAIN_WATER) { gameControl.get_current_map_obj()->add_bubble_animation(st_position(realPosition.x+frameSize.width/2, position.y+6)); } int map_point_x = (position.x+frameSize.width/2)/TILESIZE; int map_point_y = (position.y+frameSize.height)/TILESIZE; int bottom_point_lock = gameControl.get_current_map_obj()->getMapPointLock(st_position(map_point_x, map_point_y)); if (state.frozen == true) { if (state.frozen_timer < timer.getTimer()) { state.frozen = false; } else { // if is player, check collision agains NPCs to leave freeze if (is_player()) { classnpc* npc_touch = gameControl.get_current_map_obj()->collision_player_npcs(this, 0, 0); if (npc_touch != NULL) { if (npc_touch->get_size().height > this->get_size().height) { damage(TOUCH_DAMAGE_SMALL, false); } else { damage(TOUCH_DAMAGE_BIG, false); } if (_was_hit == true) { npc_touch->hit_player(); } } } } return; } if (state.animation_type == ANIM_TYPE_TELEPORT) { gravity(false); return; } if (state.animation_type == ANIM_TYPE_HIT) { if (hit_moved_back_n < get_hit_push_back_n()) { if (state.direction == ANIM_DIRECTION_LEFT) { moveCommands.left = 0; moveCommands.right = 1; } else { moveCommands.left = 1; moveCommands.right = 0; } moveCommands.up = 0; moveCommands.down = 0; moveCommands.jump = 0; if (did_hit_ground == true) { temp_move_speed = 0.5; } else { temp_move_speed = 0.8; } } else { set_animation_type(ANIM_TYPE_STAND); hit_moved_back_n = 0; } } if (moveCommands.left == 1 && position.x > 0 && state.animation_type != ANIM_TYPE_SLIDE && is_in_stairs_frame() == false) { // check inverting direction if (state.animation_type != ANIM_TYPE_HIT && state.direction != ANIM_DIRECTION_LEFT) { set_direction(ANIM_DIRECTION_LEFT); return; } for (float i=temp_move_speed; i>=0.1; i--) { st_map_collision map_col = map_collision(-i, 0, gameControl.get_current_map_obj()->getMapScrolling()); mapLock = map_col.block; if (state.animation_type == ANIM_TYPE_HIT) { hit_moved_back_n += temp_move_speed; } if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_Y || mapLock == BLOCK_QUICKSAND) { if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_Y) { position.x -= i + gameControl.get_current_map_obj()->get_last_scrolled().x; } else if (mapLock == BLOCK_WATER) { position.x -= i*WATER_SPEED_MULT + gameControl.get_current_map_obj()->get_last_scrolled().x; } else if (mapLock == BLOCK_QUICKSAND) { position.x -= i*QUICKSAND_SPEED_MULT + gameControl.get_current_map_obj()->get_last_scrolled().x; } if (state.animation_type != ANIM_TYPE_HIT) { if (is_player() && state.direction == ANIM_DIRECTION_RIGHT && is_in_stairs_frame() != true) { position.x -= PLAYER_RIGHT_TO_LEFT_DIFF; } set_direction(ANIM_DIRECTION_LEFT); } else { gravity(false); return; } if (state.animation_type != ANIM_TYPE_WALK && state.animation_type != ANIM_TYPE_WALK_ATTACK) { state.animation_timer = 0; } if (state.animation_type != ANIM_TYPE_WALK && state.animation_type != ANIM_TYPE_JUMP && state.animation_type != ANIM_TYPE_SLIDE && state.animation_type != ANIM_TYPE_JUMP_ATTACK && state.animation_type != ANIM_TYPE_HIT && (state.animation_type != ANIM_TYPE_WALK_ATTACK || (state.animation_type == ANIM_TYPE_WALK_ATTACK && state.attack_timer+ATTACK_DELAY < timer.getTimer()))) { set_animation_type(ANIM_TYPE_WALK); } moved = true; break; } } } if (moveCommands.right != 1 && moveCommands.left == 1 && state.direction != ANIM_DIRECTION_LEFT && (state.animation_type == ANIM_TYPE_SLIDE || is_in_stairs_frame() == true)) { if (is_player() && state.direction == ANIM_DIRECTION_RIGHT && is_in_stairs_frame() != true) { position.x -= PLAYER_RIGHT_TO_LEFT_DIFF; } set_direction(ANIM_DIRECTION_LEFT); } if (moveCommands.left != 1 && moveCommands.right == 1 && state.animation_type != ANIM_TYPE_SLIDE && is_in_stairs_frame() == false) { if (state.animation_type != ANIM_TYPE_HIT && state.direction != ANIM_DIRECTION_RIGHT) { set_direction(ANIM_DIRECTION_RIGHT); return; } if (state.animation_type == ANIM_TYPE_HIT) { hit_moved_back_n += temp_move_speed; } if (is_on_quicksand()) { temp_move_speed = QUICKSAND_JUMP_LIMIT/2; } for (float i=temp_move_speed; i>=0.1; i--) { // movement is too small to change a pixel in player movement, ignore it int adjusted_real_pos = (int)(realPosition.x + i); int real_pos = (int)realPosition.x; if (adjusted_real_pos == real_pos) { break; } if (is_player() == false || (realPosition.x + i + frameSize.width/2) < RES_W) { st_map_collision map_col = map_collision(i, 0, gameControl.get_current_map_obj()->getMapScrolling()); mapLock = map_col.block; if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_Y || mapLock == BLOCK_QUICKSAND) { if (mapLock == TERRAIN_UNBLOCKED || mapLock == BLOCK_Y) { position.x += i - gameControl.get_current_map_obj()->get_last_scrolled().x; } else if (mapLock == BLOCK_WATER) { position.x += i*WATER_SPEED_MULT - gameControl.get_current_map_obj()->get_last_scrolled().x; } else if (mapLock == BLOCK_QUICKSAND) { position.x += i*QUICKSAND_SPEED_MULT + gameControl.get_current_map_obj()->get_last_scrolled().x; } if (state.animation_type != ANIM_TYPE_HIT) { if (is_player() && state.direction == ANIM_DIRECTION_LEFT && is_in_stairs_frame() != true) { position.x += PLAYER_RIGHT_TO_LEFT_DIFF; } set_direction(ANIM_DIRECTION_RIGHT); } else { gravity(false); return; } if (state.animation_type != ANIM_TYPE_WALK && state.animation_type != ANIM_TYPE_WALK_ATTACK) { state.animation_timer = 0; } if (state.animation_type != ANIM_TYPE_WALK && state.animation_type != ANIM_TYPE_JUMP && state.animation_type != ANIM_TYPE_SLIDE && state.animation_type != ANIM_TYPE_JUMP_ATTACK && state.animation_type != ANIM_TYPE_HIT && (state.animation_type != ANIM_TYPE_WALK_ATTACK || (state.animation_type == ANIM_TYPE_WALK_ATTACK && state.attack_timer+ATTACK_DELAY < timer.getTimer()))) { set_animation_type(ANIM_TYPE_WALK); } moved = true; break; } else { moved = false; } } } } if (moveCommands.right == 1 && state.direction != ANIM_DIRECTION_RIGHT && (state.animation_type == ANIM_TYPE_SLIDE || is_in_stairs_frame() == true)) { if (is_player() && state.direction == ANIM_DIRECTION_LEFT && is_in_stairs_frame() != true) { position.x += PLAYER_RIGHT_TO_LEFT_DIFF; } set_direction(ANIM_DIRECTION_RIGHT); } // Ice inertia if (bottom_point_lock == TERRAIN_ICE || (_inertia_obj.is_started() && (bottom_point_lock == TERRAIN_UNBLOCKED|| bottom_point_lock == TERRAIN_WATER))) { if (moved == true) { if (moveCommands.right == 1) { std::cout << "ICE MOVE" << std::endl; st_map_collision map_col = map_collision(1, 0, gameControl.get_current_map_obj()->getMapScrolling()); mapLock = map_col.block; if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_Y) { position.x++; } } else if (moveCommands.left == 1) { st_map_collision map_col = map_collision(-1, 0, gameControl.get_current_map_obj()->getMapScrolling()); mapLock = map_col.block; if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_Y) { position.x--; } } _inertia_obj.start(); } else if (moveCommands.left == 0 && moveCommands.right == 0) { int inertia_xinc = _inertia_obj.execute(); if (inertia_xinc != 0) { if (state.direction == ANIM_DIRECTION_LEFT) { if (position.x - inertia_xinc < 0) { _inertia_obj.stop(); } else { st_map_collision map_col = map_collision(-inertia_xinc, 0, gameControl.get_current_map_obj()->getMapScrolling()); mapLock = map_col.block; if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_Y) { position.x -= inertia_xinc; } } } else { if (realPosition.x+inertia_xinc > RES_W) { _inertia_obj.stop(); } else { st_map_collision map_col = map_collision(inertia_xinc, 0, gameControl.get_current_map_obj()->getMapScrolling()); mapLock = map_col.block; if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_Y) { position.x += inertia_xinc; } } } } } if (gameControl.get_current_map_obj() != NULL) { gameControl.update_stage_scrolling(); } char_update_real_position(); } else if (bottom_point_lock != TERRAIN_WATER) { _inertia_obj.stop(); } if (_obj_jump.is_started() == true) { _inertia_obj.stop(); } // check if character is on stairs if (moveCommands.up == 1 && state.animation_type != ANIM_TYPE_STAIRS_ATTACK) { // check stairs on middle st_position stairs_pos = is_on_stairs(st_rectangle(position.x, position.y+(frameSize.height/2)-2, frameSize.width, frameSize.height/2-2)); int top_terrain = gameControl.get_current_map_obj()->getMapPointLock(st_position(((stairs_pos.x * TILESIZE - 6)+frameSize.width/2)/TILESIZE, position.y/TILESIZE)); if (stairs_pos.x != -1) { if (state.animation_type != ANIM_TYPE_STAIRS_MOVE && _stairs_falling_timer < timer.getTimer()) { set_animation_type(ANIM_TYPE_STAIRS_MOVE); } if (is_in_stairs_frame() && (top_terrain == TERRAIN_UNBLOCKED || top_terrain == TERRAIN_WATER || top_terrain == TERRAIN_STAIR)) { position.y -= temp_move_speed * STAIRS_MOVE_MULTIPLIER; position.x = stairs_pos.x * TILESIZE - (frameSize.width-TILESIZE)/2; } // out of stairs } else { int map_terrain = gameControl.get_current_map_obj()->getMapPointLock(st_position(((position.x+frameSize.width/2)/TILESIZE), ((position.y+frameSize.height-4)/TILESIZE))); if (_dropped_from_stairs == false && map_terrain == TERRAIN_STAIR) { // check stairs bottom (leaving) set_animation_type(ANIM_TYPE_STAIRS_SEMI); position.y -= temp_move_speed * STAIRS_MOVE_MULTIPLIER; } else if (state.animation_type == ANIM_TYPE_STAIRS_SEMI) { set_animation_type(ANIM_TYPE_STAND); position.y -= 2; } } } if (moveCommands.down == 1 && state.animation_type != ANIM_TYPE_SLIDE && state.animation_type != ANIM_TYPE_STAIRS_ATTACK) { st_position stairs_pos_center = is_on_stairs(st_rectangle(position.x, position.y+frameSize.height/2, frameSize.width, frameSize.height/2)); bool is_already_on_stairs = is_in_stairs_frame(); /// @TODO - check that move-speed/2 is not zero // is on stairs if (is_already_on_stairs == true) { // if frame is semi, but already entered whole body, change to full-stairs frame if (state.animation_type == ANIM_TYPE_STAIRS_SEMI && stairs_pos_center.x != -1 && _stairs_falling_timer < timer.getTimer()) { set_animation_type(ANIM_TYPE_STAIRS_MOVE); } // check that path is clear to move if (is_in_stairs_frame() && (bottom_point_lock == TERRAIN_WATER || bottom_point_lock == TERRAIN_UNBLOCKED || bottom_point_lock == TERRAIN_STAIR)) { position.y += temp_move_speed * STAIRS_MOVE_MULTIPLIER; } // if bottom point is not stairs, leave it if (bottom_point_lock != TERRAIN_STAIR) { if (stairs_pos_center.x == -1 && (bottom_point_lock == TERRAIN_UNBLOCKED || bottom_point_lock == TERRAIN_WATER)) { set_animation_type(ANIM_TYPE_JUMP); } if (bottom_point_lock != TERRAIN_UNBLOCKED && bottom_point_lock != TERRAIN_WATER) { set_animation_type(ANIM_TYPE_STAND); } } // not in stairs, but over it } else { if (stairs_pos_center.x == -1 && bottom_point_lock == TERRAIN_STAIR) { // over stairs, enter it st_position stairs_pos_bottom = is_on_stairs(st_rectangle(position.x, position.y+frameSize.height, frameSize.width, frameSize.height/2)); if (stairs_pos_bottom.x != -1) { set_animation_type(ANIM_TYPE_STAIRS_SEMI); position.y += temp_move_speed * STAIRS_MOVE_MULTIPLIER; position.x = stairs_pos_bottom.x * TILESIZE - (frameSize.width-TILESIZE)/2; } } } } // is on stairs without moving if (moveCommands.down == 0 && moveCommands.up == 0 && state.animation_type == ANIM_TYPE_STAIRS_MOVE) { _stairs_stopped_count++; if (_stairs_stopped_count > STAIR_ANIMATION_WAIT_FRAMES) { set_animation_type(ANIM_TYPE_STAIRS); } } else if ((moveCommands.down != 0 || moveCommands.up != 0) && _stairs_falling_timer < timer.getTimer()) { _stairs_stopped_count = 0; if (state.animation_type == ANIM_TYPE_STAIRS) { set_animation_type(ANIM_TYPE_STAIRS_MOVE); } } check_reset_stand(); if (is_player() == false) { character::attack(false, 0, false); } bool res_slide = slide(gameControl.get_current_map_obj()->getMapScrolling()); bool resJump = false; resJump = jump(moveCommands.jump, gameControl.get_current_map_obj()->getMapScrolling()); if (resJump == true || res_slide == true) { if (state.animation_type == ANIM_TYPE_HIT) { gravity(false); } /// @TODO: removed a gravity from here in an ELSE. Hope it was not necessary } if (is_player_type && moved == false && resJump == false && res_slide == false) { //if (state.animation_type != ANIM_TYPE_WALK) { if (is_in_stairs_frame() == false && state.animation_type != ANIM_TYPE_STAND && state.animation_type != ANIM_TYPE_JUMP && state.animation_type != ANIM_TYPE_JUMP_ATTACK && state.animation_type != ANIM_TYPE_TELEPORT && state.animation_type != ANIM_TYPE_SHIELD && state.animation_type != ANIM_TYPE_HIT && state.animation_type != ANIM_TYPE_SLIDE && (is_on_attack_frame() == false || (is_on_attack_frame() == true && state.attack_timer+ATTACK_DELAY < timer.getTimer()))) { set_animation_type(ANIM_TYPE_STAND); } if (state.animation_type == ANIM_TYPE_HIT && timer.getTimer() > hit_duration/2+last_hit_time) { // finished hit time set_animation_type(ANIM_TYPE_STAND); } } if (_dropped_from_stairs == true) { if (timer.getTimer() > hit_duration+last_hit_time) { _dropped_from_stairs = false; } else if (hit_ground() == true) { _dropped_from_stairs = false; } } gameControl.get_current_map_obj()->reset_scrolled(); _previous_position = position; } void character::store_previous_position() { previous_position_list.push_back(position); if (previous_position_list.size() > PREVIOUS_FRAMES_MAX) { previous_position_list.erase(previous_position_list.begin()); } } void character::clear_move_commands() { moveCommands.up = 0; moveCommands.down = 0; moveCommands.left = 0; moveCommands.right = 0; moveCommands.attack = 0; moveCommands.jump = 0; moveCommands.start = 0; } // ********************************************************************************************** // // // // ********************************************************************************************** // void character::change_char_color(Sint8 colorkey_n, st_color new_color, bool full_change=true) { if (full_change == false) { graphLib.change_surface_color(colorkey_n, new_color, &(graphLib.character_graphics_list.find(name)->second).frames[state.direction][state.animation_type][state.animation_state].frameSurface); } else { for (int i=0; i<2; i++) { for (int j=0; j<ANIM_TYPE_COUNT; j++) { for (int k=0; k<ANIM_FRAMES_COUNT; k++) { graphLib.change_surface_color(colorkey_n, new_color, &(graphLib.character_graphics_list.find(name)->second).frames[i][j][k].frameSurface); } } } } } // return 0 if must not attack, 1 for normal attack, 2 for semi-charged and 3 for fully charged ATTACK_TYPES character::check_must_attack(bool always_charged) { // capture button timer even if can't shoot, so we avoid always charging if (moveCommands.attack != 0 && attack_button_last_state == 0) { attack_button_pressed_timer = timer.getTimer(); } if (timer.is_paused()) { return ATTACK_TYPE_NOATTACK; } if (state.animation_type == ANIM_TYPE_TELEPORT) { return ATTACK_TYPE_NOATTACK; } if (graphLib.character_graphics_list.find(name) == graphLib.character_graphics_list.end()) { return ATTACK_TYPE_NOATTACK; } if (state.animation_type == ANIM_TYPE_SLIDE) { return ATTACK_TYPE_NOATTACK; } if (max_projectiles <= get_projectile_count()) { return ATTACK_TYPE_NOATTACK; } if (is_player() == true && get_projectile_max_shots(always_charged) <= projectile_list.size()) { return ATTACK_TYPE_NOATTACK; } int now_timer = timer.getTimer(); int time_diff = now_timer - attack_button_pressed_timer; if (SharedData::get_instance()->game_config.turbo_mode == true && moveCommands.attack != 0) { if (now_timer < state.attack_timer + TURBO_ATTACK_INTERVAL) { return ATTACK_TYPE_NOATTACK; } else { return ATTACK_TYPE_NORMAL; } } // button changed from released to pressed if (moveCommands.attack != 0 && attack_button_last_state == 0) { return ATTACK_TYPE_NORMAL; // button changed from pressed to released and char can use charged attacks } else if (SharedData::get_instance()->game_config.turbo_mode == false && _charged_shot_projectile_id > 0 && moveCommands.attack == 0 && attack_button_last_state == 1) { // @TODO use super charged time also if (time_diff >= CHARGED_SHOT_TIME) { return ATTACK_TYPE_FULLYCHARGED; } else if (time_diff >= CHARGED_SHOT_INITIAL_TIME) { return ATTACK_TYPE_SEMICHARGED; } } return ATTACK_TYPE_NOATTACK; } void character::check_charging_colors(bool always_charged) { // change player colors if charging attack int now_timer = timer.getTimer(); int attack_diff_timer = now_timer-attack_button_pressed_timer; if (SharedData::get_instance()->game_config.turbo_mode == true) { return; } // don't charge if can't shot if (max_projectiles <= get_projectile_count()) { // reset time, so we start counting only when all projectiles are gone return; } if (is_player() == true && get_projectile_max_shots(always_charged) <= projectile_list.size()) { // reset time, so we start counting only when all projectiles are gone return; } if (_charged_shot_projectile_id > 0 && attack_diff_timer > CHARGED_SHOT_INITIAL_TIME && attack_diff_timer < CHARGED_SHOT_TIME && attack_button_last_state == 1 && moveCommands.attack == 1 && _simultaneous_shots < 2) { if (is_player() && soundManager.is_playing_repeated_sfx() == false) { soundManager.play_repeated_sfx(SFX_CHARGING1, 0); } if (color_keys[0].r != -1) { if (charging_color_timer < timer.getTimer()) { charging_color_n++; if (charging_color_n > 2) { charging_color_n = 0; } charging_color_timer = timer.getTimer()+200; if (charging_color_n == 0) { change_char_color(0, st_color(171, 0, 19), false); change_char_color(1, st_color(231, 0, 91), false); } else if (charging_color_n == 1) { change_char_color(0, st_color(231, 0, 91), false); change_char_color(1, st_color(255, 119, 183), false); } else if (charging_color_n == 2) { change_char_color(0, st_color(255, 119, 183), false); change_char_color(1, st_color(171, 0, 19), false); } } } } if (_charged_shot_projectile_id > 0 && is_player() && attack_diff_timer >= CHARGED_SHOT_TIME && attack_button_last_state == 1 && moveCommands.attack == 1 && !is_dead()) { if (soundManager.is_playing_repeated_sfx() == true && soundManager.get_repeated_sfx_n() == SFX_CHARGING1) { soundManager.stop_repeated_sfx(); soundManager.play_repeated_sfx(SFX_CHARGING2, 255); } if (color_keys[0].r != -1) { if (charging_color_timer < timer.getTimer()) { charging_color_n++; if (charging_color_n > 2) { charging_color_n = 0; } charging_color_timer = timer.getTimer()+100; if (charging_color_n == 0) { change_char_color(0, st_color(219, 43, 0), false); change_char_color(1, st_color(255, 155, 59), false); } else if (charging_color_n == 1) { change_char_color(0, st_color(255, 155, 59), false); change_char_color(1, st_color(255, 234, 0), false); } else if (charging_color_n == 2) { change_char_color(0, st_color(255, 234, 0), false); change_char_color(1, st_color(219, 43, 0), false); } } } } } st_position character::get_attack_position() { return get_attack_position(state.direction); } st_position character::get_attack_position(short direction) { st_position proj_pos; if (direction == ANIM_DIRECTION_LEFT) { proj_pos = st_position(position.x+TILESIZE/3, position.y+frameSize.height/2); } else { proj_pos = st_position(position.x+frameSize.width-TILESIZE/2, position.y+frameSize.height/2); } if (is_player() == false) { st_position_int8 attack_arm_pos = GameMediator::get_instance()->get_enemy(_number)->attack_arm_pos; if (attack_arm_pos.x != 0 || attack_arm_pos.y >= 1) { if (direction == ANIM_DIRECTION_LEFT) { proj_pos = st_position(position.x + attack_arm_pos.x, position.y + attack_arm_pos.y); } else { proj_pos = st_position(position.x + frameSize.width - attack_arm_pos.x, position.y + attack_arm_pos.y); } } } return proj_pos; } /// @TODO: this must be moved to player, as character attack must be very simple void character::attack(bool dont_update_colors, short updown_trajectory, bool always_charged) { if (attack_state != ATTACK_NOT && (timer.getTimer()-state.attack_timer) >= (graphLib.character_graphics_list.find(name)->second).frames[state.direction][state.animation_type][state.animation_state].delay) { attack_state = ATTACK_NOT; } ATTACK_TYPES must_attack = check_must_attack(always_charged); check_charging_colors(always_charged); attack_button_last_state = moveCommands.attack; int attack_id = -1; if (must_attack == ATTACK_TYPE_NOATTACK) { return; } else if (must_attack == ATTACK_TYPE_NORMAL) { if (always_charged == true) { attack_id = game_data.semi_charged_projectile_id; } else { if (_normal_shot_projectile_id > 0) { attack_id = _normal_shot_projectile_id; } else { attack_id = 0; } } } else if (must_attack == ATTACK_TYPE_SEMICHARGED) { attack_id = game_data.semi_charged_projectile_id; } else if (must_attack == ATTACK_TYPE_FULLYCHARGED) { attack_id = _charged_shot_projectile_id; } if (attack_id != -1) { if (attack_id == _charged_shot_projectile_id || attack_id == game_data.semi_charged_projectile_id) { if (is_player() && soundManager.is_playing_repeated_sfx() == true) { soundManager.stop_repeated_sfx(); } } st_position proj_pos = get_attack_position(); projectile_list.push_back(projectile(attack_id, state.direction, proj_pos, is_player(), _number)); projectile &temp_proj = projectile_list.back(); temp_proj.set_is_permanent(); temp_proj.play_sfx(!is_player()); temp_proj.set_owner(this); _player_must_reset_colors = true; // second projectile for player that fires multiple ones if ((attack_id == 0 || attack_id == _normal_shot_projectile_id || (attack_id == game_data.semi_charged_projectile_id && always_charged == true)) && is_player() && _simultaneous_shots > 1) { /// @TODO - move number of simultaneous shots to character/data-file int pos_x_second = proj_pos.x+TILESIZE; if (state.direction == ANIM_DIRECTION_RIGHT) { pos_x_second = proj_pos.x-TILESIZE; } projectile_list.push_back(projectile(attack_id, state.direction, st_position(pos_x_second, proj_pos.y+5), is_player(), _number)); projectile &temp_proj2 = projectile_list.back(); temp_proj2.set_is_permanent(); temp_proj2.set_owner(this); } if (attack_id == 0 || attack_id == _normal_shot_projectile_id) { // handle normal attack differences depending on player if (updown_trajectory == 1) { temp_proj.set_trajectory(TRAJECTORY_DIAGONAL_UP); set_animation_type(ANIM_TYPE_ATTACK_DIAGONAL_UP); } else if (updown_trajectory == -1) { temp_proj.set_trajectory(TRAJECTORY_DIAGONAL_DOWN); set_animation_type(ANIM_TYPE_ATTACK_DIAGONAL_DOWN); } else if (is_on_attack_frame() == true && updown_trajectory == 0 && (state.animation_type == ANIM_TYPE_ATTACK_DIAGONAL_UP || state.animation_type == ANIM_TYPE_ATTACK_DIAGONAL_DOWN)) { // not shooting diagonal, but animation is on diagonal -> reset to normal attack set_animation_type(ANIM_TYPE_ATTACK); } } int proj_trajectory = GameMediator::get_instance()->get_projectile(attack_id).trajectory; temp_proj.set_owner(this); if (proj_trajectory == TRAJECTORY_CENTERED || proj_trajectory == TRAJECTORY_SLASH) { temp_proj.set_owner_direction(&state.direction); temp_proj.set_owner_position(&position); } if (proj_trajectory == TRAJECTORY_TARGET_DIRECTION || proj_trajectory == TRAJECTORY_TARGET_EXACT || proj_trajectory == TRAJECTORY_ARC_TO_TARGET || proj_trajectory == TRAJECTORY_FOLLOW) { // NPC if (!is_player() && gameControl.get_current_map_obj()->_player_ref != NULL) { character* p_player = gameControl.get_current_map_obj()->_player_ref; temp_proj.set_target_position(p_player->get_position_ref()); // PLAYER } else { classnpc* temp_npc = NULL; if (proj_trajectory == TRAJECTORY_TARGET_DIRECTION || proj_trajectory == TRAJECTORY_TARGET_EXACT || proj_trajectory == TRAJECTORY_ARC_TO_TARGET) { temp_npc = gameControl.get_current_map_obj()->find_nearest_npc(st_position(position.x, position.y)); } else { temp_npc = gameControl.get_current_map_obj()->find_nearest_npc_on_direction(st_position(position.x, position.y), state.direction); } if (temp_npc != NULL) { temp_proj.set_target_position(temp_npc->get_position_ref()); } } } attack_state = ATTACK_START; state.attack_timer = timer.getTimer(); if (state.animation_type == ANIM_TYPE_STAND) { set_animation_type(ANIM_TYPE_ATTACK); } else if (state.animation_type == ANIM_TYPE_JUMP) { set_animation_type(ANIM_TYPE_JUMP_ATTACK); } else if (is_in_stairs_frame()) { set_animation_type(ANIM_TYPE_STAIRS_ATTACK); } else if (state.animation_type == ANIM_TYPE_WALK) { set_animation_type(ANIM_TYPE_WALK_ATTACK); } } } // ********************************************************************************************** // // // // ********************************************************************************************** // void character::advance_frameset() { if (state.direction > CHAR_ANIM_DIRECTION_COUNT) { set_direction(ANIM_DIRECTION_LEFT); return; } if (state.animation_type > ANIM_TYPE_COUNT) { return; } if ((is_player() && state.animation_state > MAX_PLAYER_SPRITES) || (!is_player() && state.animation_state > MAX_NPC_SPRITES)) { state.animation_state = 0; return; } if (have_frame_graphic(state.direction, state.animation_type, state.animation_state) == false) { _was_animation_reset = true; state.animation_state = 0; _is_last_frame = true; } else { if (have_frame_graphic(state.direction, state.animation_type, state.animation_state+1) == false) { _is_last_frame = true; } else { _is_last_frame = false; } } } void character::reset_jump() { _obj_jump.finish(); } void character::consume_projectile() { if (projectile_list.size() > 0) { projectile_list.at(0).consume_projectile(); } } // ********************************************************************************************** // // // // ********************************************************************************************** // void character::show() { if (is_dead() == true) { //if (!is_player()) std::cout << "CHAR::show[" << name << "] - LEAVE #1" << std::endl; return; } // update real position char_update_real_position(); if (!is_player() && is_on_visible_screen() == false) { //if (!is_player()) std::cout << "CHAR::show[" << name << "] - LEAVE #2" << std::endl; return; } /* if (is_player() == false) { animation_obj.show_sprite(realPosition); } else { show_at(realPosition); } */ show_previous_sprites(); show_at(realPosition); } void character::show_previous_sprites() { if (must_show_dash_effect == false && state.animation_type != ANIM_TYPE_SLIDE) { reset_dash_effect(); return; } if (dash_effect_shadow_surface_frame.is_null()) { graphicsLib_gSurface *surface_frame_original = get_current_frame_surface(state.direction, state.animation_type, state.animation_state); // make a copy of the frame graphLib.initSurface(st_size(surface_frame_original->width, surface_frame_original->height), &dash_effect_shadow_surface_frame); graphLib.copyArea(st_position(0, 0), surface_frame_original, &dash_effect_shadow_surface_frame); } // show previous frames std::map<std::string, st_char_sprite_data>::iterator it_graphic = graphLib.character_graphics_list.find(name); for (int i=0; i<previous_position_list.size(); i++) { // only show each two frames if (i%2 == 0) { continue; } st_float_position screen_pos = get_screen_position_from_point(previous_position_list.at(i)); graphLib.set_surface_alpha_nocolorkey(40*i/2, dash_effect_shadow_surface_frame); graphLib.showSurfaceAt(&dash_effect_shadow_surface_frame, st_position(screen_pos.x, screen_pos.y), false); } graphLib.set_surface_alpha_nocolorkey(255, dash_effect_shadow_surface_frame); } void character::reset_dash_effect() { dash_effect_shadow_surface_frame.freeGraphic(); } void character::show_at(st_position pos) { // check attack frame if (_attack_frame_n != -1 && is_on_attack_frame() && state.animation_state == _attack_frame_n) { _is_attack_frame = true; } else { _is_attack_frame = false; } // show background, if any if (is_player() == false && have_background_graphics() == true) { st_position bg_pos = st_position(pos.x-background_pos.x, pos.y-background_pos.y); if (state.direction != ANIM_DIRECTION_LEFT) { graphLib.showSurfaceAt(&(graphLib.character_graphics_background_list.find(name)->second), bg_pos, false); } else { graphLib.showSurfaceAt(&(graphLib.character_graphics_background_list_left.find(name)->second), bg_pos, false); } if (state.direction == ANIM_DIRECTION_LEFT) { // calcular distância com base largura total, pq é inverttido int original_pos_x = pos.x - background_pos.x; int graph_diff_x = graphLib.character_graphics_background_list.find(name)->second.width-background_pos.x - frameSize.width; //std::cout << "char[" << name << "], original_pos_x[" << original_pos_x << "], pos.x[" << pos.x << "], background_pos.x[" << background_pos.x << "], graph_diff_x[" << graph_diff_x << "]" << std::endl; pos.x = original_pos_x + graph_diff_x; } } // only advance if time for the current frame has finished advance_frameset(); // turn is a special case, if it does not exist, we must show stand instead if ((state.animation_type == ANIM_TYPE_TURN || state.animation_type == ANIM_TYPE_VERTICAL_TURN) && have_frame_graphic(state.direction, state.animation_type, state.animation_state) == false) { if (have_frame_graphic(state.direction, ANIM_TYPE_WALK, state.animation_state) == true) { show_sprite_graphic(state.direction, ANIM_TYPE_WALK, state.animation_state, pos); } else { show_sprite_graphic(state.direction, ANIM_TYPE_STAND, state.animation_state, pos); } // npc teleport use shows stand for now (will have a common graphic to show in the future) } else { show_sprite_graphic(state.direction, state.animation_type, state.animation_state, pos); } st_rectangle hitbox = get_hitbox(); if (gameControl.get_current_map_obj() != NULL) { hitbox.x -= gameControl.get_current_map_obj()->getMapScrolling().x; } if (is_player() == false) { if (freeze_weapon_effect != FREEZE_EFFECT_NPC || is_weak_to_freeze() == false) { show_sprite(); #ifdef SHOW_HITBOXES graphLib.draw_rectangle(hitbox, 255, 0, 255, 100); #endif } } else { show_sprite(); #ifdef SHOW_HITBOXES graphLib.draw_rectangle(hitbox, 0, 0, 255, 100); #endif } #ifdef SHOW_VULNERABLE_AREAS st_rectangle vulnerable_area = get_vulnerable_area(); if (!is_player()) { //std::cout << "DRAW_VUL-AREA[" << name << "][" << vulnerable_area.x << "][" << vulnerable_area.y << "][" << vulnerable_area.w << "][" << vulnerable_area.h << "], scroll.x[" << gameControl.get_current_map_obj()->getMapScrolling().x << "]" << std::endl; vulnerable_area.x -= gameControl.get_current_map_obj()->getMapScrolling().x; graphLib.draw_rectangle(vulnerable_area, 255, 0, 0, 180); } #endif } void character::show_sprite() { unsigned int now_timer = timer.getTimer(); if (state.animation_timer < now_timer) { // time passed the value to advance frame // change animation state to next frame int frame_inc = 1; if (state.animation_inverse == true) { frame_inc = frame_inc * -1; } int new_frame = (state.animation_state + frame_inc); if (have_frame_graphic(state.direction, state.animation_type, new_frame)) { state.animation_state += frame_inc; if (state.animation_state < 0) { if (state.animation_inverse == true) { advance_to_last_frame(); } else { state.animation_state = 0; } } } else { if (state.animation_type == ANIM_TYPE_VERTICAL_TURN) { if (state.direction == ANIM_DIRECTION_LEFT) { set_direction(ANIM_DIRECTION_RIGHT); } else { set_direction(ANIM_DIRECTION_LEFT); } set_animation_type(ANIM_TYPE_STAND); } if (state.animation_inverse == false) { if (state.animation_state > 0) { state.animation_state = 0; } } else { advance_to_last_frame(); } _was_animation_reset = true; // some animation types reset to stand/other if (state.animation_type == ANIM_TYPE_STAIRS_ATTACK) { set_animation_type(ANIM_TYPE_STAIRS); } } if (state.animation_type == ANIM_TYPE_WALK_ATTACK) { state.animation_timer = timer.getTimer() + 180; } else { short direction = ANIM_DIRECTION_RIGHT; int delay = (graphLib.character_graphics_list.find(name)->second).frames[direction][state.animation_type][state.animation_state].delay; state.animation_timer = timer.getTimer() + delay; } } } // we need to reset the time of the animation to discount pause // because otherwise, we can't animate player/enemies during a pause like transition void character::reset_sprite_animation_timer() { if (state.animation_type == ANIM_TYPE_WALK_ATTACK) { state.animation_timer = timer.getTimer() + 180; } else { short direction = ANIM_DIRECTION_RIGHT; int delay = 100; if (graphLib.character_graphics_list.find(name) != graphLib.character_graphics_list.end()) { if (direction < CHAR_ANIM_DIRECTION_COUNT) { if (state.animation_type < ANIM_TYPE_COUNT) { if (state.animation_state < ANIM_FRAMES_COUNT) { delay = (graphLib.character_graphics_list.find(name)->second).frames[direction][state.animation_type][state.animation_state].delay; } } } } state.animation_timer = timer.getTimer() + delay; } } void character::show_sprite_graphic(short direction, short type, short frame_n, st_position frame_pos) { if (state.invisible == true) { return; } graphicsLib_gSurface *frame_surface = get_current_frame_surface(direction, type, frame_n); if (frame_surface == NULL) { return; } /// blinking when hit unsigned int now_timer = timer.getTimer(); if (now_timer < hit_duration+last_hit_time) { if (hit_animation_timer > now_timer) { //graphLib.show_white_surface_at(&it_graphic->second.frames[direction][type][frame_n].frameSurface, frame_pos); graphLib.show_white_surface_at(frame_surface, frame_pos); hit_animation_count = 0; return; } else if ((hit_animation_timer+HIT_BLINK_ANIMATION_LAPSE) < now_timer) { hit_animation_count++; if (hit_animation_count > 2) { hit_animation_timer = now_timer+HIT_BLINK_ANIMATION_LAPSE; } return; } } if (_progressive_appear_pos == 0) { //graphLib.showSurfaceAt(&it_graphic->second.frames[direction][type][frame_n].frameSurface, frame_pos, false); graphLib.showSurfaceAt(frame_surface, frame_pos, false); } else { int diff_y = frameSize.height-_progressive_appear_pos; //graphLib.showSurfaceRegionAt(&it_graphic->second.frames[direction][type][frame_n].frameSurface, st_rectangle(0, 0, frameSize.width, (frameSize.height-_progressive_appear_pos)), st_position(frame_pos.x, frame_pos.y-diff_y)); graphLib.showSurfaceRegionAt(frame_surface, st_rectangle(0, 0, frameSize.width, (frameSize.height-_progressive_appear_pos)), st_position(frame_pos.x, frame_pos.y-diff_y)); _progressive_appear_pos--; if (_progressive_appear_pos == 0) { position.y -= frameSize.height; } } } graphicsLib_gSurface *character::get_current_frame_surface(short direction, short type, short frame_n) { if (frame_n < 0) { frame_n = 0; } std::map<std::string, st_char_sprite_data>::iterator it_graphic; it_graphic = graphLib.character_graphics_list.find(name); if (it_graphic == graphLib.character_graphics_list.end()) { std::cout << "ERROR: #1 character::show_sprite_graphic - Could not find graphic for NPC [" << name << "]" << std::endl; return NULL; } // for non left-right directions, use the original facing direction for NPCs if (is_player() == false && direction != ANIM_DIRECTION_LEFT && direction != ANIM_DIRECTION_RIGHT) { direction = facing; } if (have_frame_graphic(direction, type, frame_n) == false) { // check if we can find the graphic with the given N position if (frame_n == 0) { if (type == ANIM_TYPE_TELEPORT) { type = ANIM_TYPE_JUMP; } else { type = ANIM_TYPE_STAND; } } else { frame_n = 0; state.animation_state = 0; _was_animation_reset = true; return &it_graphic->second.frames[direction][type][frame_n].frameSurface; } state.animation_state = 0; _was_animation_reset = true; if (have_frame_graphic(direction, type, frame_n) == false) { // check if we can find the graphic with the given type set_animation_type(ANIM_TYPE_STAND); type = ANIM_TYPE_STAND; if (have_frame_graphic(direction, type, frame_n) == false) { // check if we can find the graphic at all std::cout << "ERROR: #2 character::show_sprite_graphic - Could not find graphic for NPC [" << name << "] at pos[0][0][0]" << std::endl; return NULL; } } } return &it_graphic->second.frames[direction][type][frame_n].frameSurface; } void character::reset_gravity_speed() { accel_speed_y = 0.25; } // ********************************************************************************************** // // // // ********************************************************************************************** // bool character::gravity(bool boss_demo_mode=false) { if (_progressive_appear_pos != 0) { reset_gravity_speed(); return false; } if (!gameControl.get_current_map_obj()) { std::cout << "ERROR: can't execute gravity without a map" << std::endl; reset_gravity_speed(); return false; // error - can't execute this action without an associated map } bool can_use_air_dash = false; if (is_player() == true) { can_use_air_dash = can_air_dash(); } if (can_use_air_dash == true && state.animation_type == ANIM_TYPE_SLIDE) { reset_gravity_speed(); return false; } if ((_is_boss || _is_stage_boss) && get_anim_type() == ANIM_TYPE_INTRO) { return false; } if (is_player() && state.animation_type == ANIM_TYPE_TELEPORT) { return false; } if (!is_player() && teleporting_out > 0) { return false; } if (is_player() == false && (game_data.final_boss_id == _number || (GameMediator::get_instance()->ai_list.at(_number).reactions[AI_REACTION_DEAD].action == AI_ACTION_REPLACE_NPC && GameMediator::get_instance()->ai_list.at(_number).reactions[AI_REACTION_DEAD].extra_parameter == game_data.final_boss_id))) { _is_final_game_boss = true; } int gravity_max_speed = GRAVITY_MAX_SPEED * SharedData::get_instance()->get_movement_multiplier(); if (state.animation_type == ANIM_TYPE_TELEPORT) { gravity_max_speed = GRAVITY_TELEPORT_MAX_SPEED * SharedData::get_instance()->get_movement_multiplier(); } else if (state.animation_type == ANIM_TYPE_HIT) { gravity_max_speed = 2 * SharedData::get_instance()->get_movement_multiplier(); } // ------------- NPC gravity ------------------ // if (!is_player()) { if (_ignore_gravity == true) { return false; } if (can_fly == false || can_fall_during_move == true || (_is_boss && SharedData::get_instance()->is_showing_boss_intro == true)) { bool is_moved = false; short int limit_speed = move_speed; if (boss_demo_mode == true) { limit_speed = gravity_max_speed; } if (limit_speed < 1) { limit_speed = 1; } for (int i=limit_speed; i>0; i--) { bool res_test_move = test_change_position(0, i); //if (i > 0) std::cout << "CHAR::GRAVITY[PLAYER] - res_test_move[" << res_test_move << "], yinc[" << i << "]" << std::endl; if ((boss_demo_mode == true && position.y <= TILESIZE*2) || res_test_move == true) { position.y += i; is_moved = true; break; } } return is_moved; } reset_gravity_speed(); return false; // not moved because of IA type } // ------------ PLAYER gravity --------------------- // if (is_player() && position.y > RES_H+TILESIZE) { hitPoints.current = 0; death(); reset_gravity_speed(); return false; } if (is_in_stairs_frame()) { //character* playerObj, const short int x_inc, const short int y_inc, short int reduce_x, short int reduce_y classnpc* npc_touch = gameControl.get_current_map_obj()->collision_player_npcs(this, 0, 0); if (npc_touch != NULL) { if (npc_touch->get_size().height > this->get_size().height) { damage(TOUCH_DAMAGE_SMALL, false); } else { damage(TOUCH_DAMAGE_BIG, false); } if (_was_hit == true) { npc_touch->hit_player(); } } reset_gravity_speed(); return false; } if (_obj_jump.is_started() == false && can_fly == false && position.y < RES_H+TILESIZE+1 + frameSize.height) { // tem que inicializar essa variável sempre que for false accel_speed_y = accel_speed_y + accel_speed_y*gravity_y; if (accel_speed_y < 0.25) { accel_speed_y = 0.25; } else if (accel_speed_y > gravity_max_speed) { accel_speed_y = gravity_max_speed; } int adjusted_speed = accel_speed_y; if (adjusted_speed < 1) { adjusted_speed = 1; } if (state.animation_type == ANIM_TYPE_TELEPORT) { if (_teleport_minimal_y - position.y > TILESIZE) { adjusted_speed = gravity_max_speed; } else { adjusted_speed = gravity_max_speed/2; } } st_map_collision map_col; bool was_moved = false; for (int i=adjusted_speed; i>0; i--) { map_col = map_collision(0, i, gameControl.get_current_map_obj()->getMapScrolling()); int mapLock = map_col.block; if (state.animation_type == ANIM_TYPE_TELEPORT && position.y < _teleport_minimal_y-TILESIZE) { mapLock = BLOCK_UNBLOCKED; } else if (!is_player() && state.animation_type == ANIM_TYPE_TELEPORT && position.y >= _teleport_minimal_y-TILESIZE) { _teleport_minimal_y = frameSize.height+TILESIZE*2; // RESET MIN_Y -> remove limit for next telepor } else if (position.y+frameSize.height >= RES_H) { // out of screen mapLock = BLOCK_UNBLOCKED; } if (_platform == nullptr || (_platform != nullptr && _platform->get_type() != OBJ_MOVING_PLATFORM_UPDOWN && _platform->get_type() != OBJ_MOVING_PLATFORM_UP_LOOP && _platform->get_type() != OBJ_MOVING_PLATFORM_DOWN)) { if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_STAIR_X || mapLock == BLOCK_STAIR_Y) { if (mapLock != BLOCK_WATER || (mapLock == BLOCK_WATER && abs((float)i*WATER_SPEED_MULT) < 1)) { position.y += i; } else { position.y += i*WATER_SPEED_MULT; } if (state.animation_type != ANIM_TYPE_JUMP && state.animation_type != ANIM_TYPE_JUMP_ATTACK && state.animation_type != ANIM_TYPE_TELEPORT && state.animation_type != ANIM_TYPE_SLIDE && state.animation_type != ANIM_TYPE_HIT && (state.animation_type != ANIM_TYPE_JUMP_ATTACK || (state.animation_type == ANIM_TYPE_JUMP_ATTACK && state.attack_timer+ATTACK_DELAY < timer.getTimer()))) { set_animation_type(ANIM_TYPE_JUMP); } was_moved = true; if (state.animation_type != ANIM_TYPE_TELEPORT) { _is_falling = true; } break; } else if (map_col.terrain_type == TERRAIN_QUICKSAND) { //std::cout << "CHAR::GRAVITY - over QUICKSAND" << std::endl; position.y += QUICKSAND_GRAVITY; } } if (i == 1) { reset_gravity_speed(); } } if (was_moved == false && (state.animation_type == ANIM_TYPE_JUMP || state.animation_type == ANIM_TYPE_JUMP_ATTACK) && state.animation_type != ANIM_TYPE_SLIDE) { set_animation_type(ANIM_TYPE_STAND); return true; } else if (was_moved == false && state.animation_type == ANIM_TYPE_TELEPORT && position.y >= RES_H/3) { set_animation_type(ANIM_TYPE_STAND); return true; } if (was_moved == false && _is_falling == true) { _is_falling = false; if (is_player()) { set_animation_type(ANIM_TYPE_STAND); soundManager.play_sfx(SFX_PLAYER_JUMP); } } check_platform_move(map_col.terrain_type); } return false; } bool character::hit_ground() // indicates if character is standing above ground { // if position did not changed since last execution, return previous hit_ground value /* if (position == _previous_position) { return _hit_ground; } */ st_rectangle hitbox = get_hitbox(); std::vector<short> map_tile_x; map_tile_x.push_back((hitbox.x + hitbox.w/2)/TILESIZE); // center map_tile_x.push_back((hitbox.x)/TILESIZE); // left map_tile_x.push_back((hitbox.x + hitbox.w)/TILESIZE); // right short map_tile_y1 = (hitbox.y + hitbox.h)/TILESIZE; short map_tile_y2 = (hitbox.y + hitbox.h/2)/TILESIZE; for (unsigned int i=0; i<map_tile_x.size(); i++) { int pointLock1 = gameControl.getMapPointLock(st_position(map_tile_x.at(i), map_tile_y1)); _hit_ground = false; if (pointLock1 != TERRAIN_UNBLOCKED && pointLock1 != TERRAIN_WATER && pointLock1 != TERRAIN_STAIR) { _hit_ground = true; break; } else if (!is_player() && pointLock1 == TERRAIN_STAIR) { _hit_ground = true; break; } else { int pointLock2 = gameControl.getMapPointLock(st_position(map_tile_x.at(i), map_tile_y2)); if (pointLock1 != pointLock2) { _hit_ground = true; break; } } } return _hit_ground; } bool character::will_hit_ground(int y_change) const { short map_tile_x = (position.x + frameSize.width/2)/TILESIZE; short map_tile_y = (position.y + y_change + frameSize.height)/TILESIZE; int pointLock = gameControl.getMapPointLock(st_position(map_tile_x, map_tile_y)); if (pointLock != TERRAIN_UNBLOCKED && pointLock != TERRAIN_WATER) { return true; } return false; } bool character::is_on_screen() { st_float_position scroll(0, 0); if (gameControl.get_current_map_obj() == NULL) { return false; } float pos_x = position.x; float pos_y = position.y; if (!is_player()) { pos_x -= GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x; pos_y -= GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.y; //if (name == "BIG FISH") std::cout << "CHAR::is_on_screen[" << name << "], pos_x[" << pos_x << "], pos_y[" << pos_y << "]" << std::endl; } scroll = gameControl.get_current_map_obj()->getMapScrolling(); // is on screen plus a bit more on both sides if (abs(pos_x+total_frame_size.width*2) >= scroll.x && abs(pos_x-total_frame_size.width*2) <= scroll.x+RES_W) { //if (name == "BIG FISH") std::cout << "CHAR::is_on_screen - TRUE #1" << std::endl; return true; } // regular enemies work only on a limited screen if (is_stage_boss() == false) { //if (name == "BIG FISH") std::cout << "CHAR::is_on_screen - FALSE #1" << std::endl; return false; } // is on left of the screen if (abs(pos_x) > scroll.x-RES_W/2 && abs(pos_x) < scroll.x) { // check wall-lock on the range int map_point_start = (scroll.x-RES_W/2)/TILESIZE; int map_point_end = scroll.x/TILESIZE; bool found_lock = false; for (int i=map_point_start; i<=map_point_end; i++) { if (gameControl.get_current_map_obj()->get_map_point_wall_lock(i) == true) { found_lock = true; } } if (found_lock == false) { //if (name == "BIG FISH") std::cout << "CHAR::is_on_screen - TRUE #2" << std::endl; return true; } } // is on right to the screen if (abs(pos_x) > scroll.x+RES_W && abs(pos_x) < scroll.x+RES_W*1.5) { int map_point_start = (scroll.x+RES_W)/TILESIZE; int map_point_end = (scroll.x*1.5)/TILESIZE; bool found_lock = false; for (int i=map_point_start; i<=map_point_end; i++) { if (gameControl.get_current_map_obj()->get_map_point_wall_lock(i) == true) { found_lock = true; } } if (found_lock == false) { //if (name == "BIG FISH") std::cout << "CHAR::is_on_screen - TRUE #2" << std::endl; return true; } } //if (name == "BIG FISH") std::cout << "CHAR::is_on_screen - FALSE #2" << std::endl; return false; } bool character::is_on_visible_screen() { if (gameControl.get_current_map_obj() == NULL) { // used ins scenes return true; } st_float_position scroll = gameControl.get_current_map_obj()->getMapScrolling(); // entre scroll.x e scroll.x+RES_W float pos_x = position.x; float pos_y = position.y; if (!is_player()) { pos_x -= GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x; pos_y -= GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.y; //if (name == "BIG FISH") std::cout << "CHAR::is_on_screen[" << name << "], pos_x[" << pos_x << "], pos_y[" << pos_y << "]" << std::endl; } if (abs(pos_x + total_frame_size.width) >= scroll.x && abs(pos_x) < scroll.x+RES_W) { return true; } return false; } bool character::is_entirely_on_screen() { if (gameControl.get_current_map_obj() == NULL) { // used ins scenes return true; } st_float_position scroll = gameControl.get_current_map_obj()->getMapScrolling(); float my_pos = abs((float)position.x+(float)frameSize.width); int limit_min = scroll.x+TILESIZE; int limit_max = scroll.x+RES_W; if (my_pos >= limit_min && my_pos <= limit_max) { return true; } return false; } bool character::is_invisible() const { return state.invisible; } void character::activate_super_jump() { _super_jump = true; } void character::activate_force_jump() { _force_jump = true; } st_float_position *character::get_position_ref() { return &position; } // ********************************************************************************************** // // // // ********************************************************************************************** // st_float_position character::getPosition() const { /// @TODO - this is crashing sometimes return position; } void character::set_position(struct st_position new_pos) { position.x = new_pos.x; position.y = new_pos.y; char_update_real_position(); } void character::inc_position(float inc_x, float inc_y) { position.x += inc_x; position.y += inc_y; } // ********************************************************************************************** // // // // ********************************************************************************************** // bool character::slide(st_float_position mapScrolling) { if (is_player() == false) { return false; } // change jump button released state, if needed if (_dash_button_released == false && moveCommands.dash == 0) { _dash_button_released = true; } // deal with cases player should not slide /// @TODO: share common code between jump and slide if (state.animation_type == ANIM_TYPE_TELEPORT || state.animation_type == ANIM_TYPE_SHIELD) { return false; } if ((state.animation_type == ANIM_TYPE_JUMP || state.animation_type == ANIM_TYPE_JUMP_ATTACK) && can_air_dash() == false) { return false; } if (is_in_stairs_frame()) { return false; } // no need to slide if (state.animation_type != ANIM_TYPE_SLIDE && moveCommands.dash != 1) { return false; } if (position.x <= 0 && state.direction == ANIM_DIRECTION_LEFT) { set_animation_type(ANIM_TYPE_JUMP); state.slide_distance = 0; return false; } bool did_hit_ground = hit_ground(); int adjust = -1; if (slide_type == 1) { // if is slide-type, use greater adjust adjust = -TILESIZE; } //st_map_collision character::map_collision(const float incx, const short incy, st_float_position mapScrolling, int hitbox_anim_type) st_map_collision map_col = map_collision(0, adjust, gameControl.get_current_map_obj()->getMapScrolling(), ANIM_TYPE_SLIDE); // slide_adjust is used because of adjustments in slide collision int map_lock = map_col.block; /* // player have double jump (without being armor) can't use slide in ground if (GameMediator::get_instance()->player_list_v3_1[_number].can_double_jump) { if (did_hit_ground == true) { return false; } } */ int map_lock_above = gameControl.getMapPointLock(st_position((position.x+frameSize.width/2)/TILESIZE, (position.y)/TILESIZE)); bool is_blocked_above = !(map_lock_above == TERRAIN_UNBLOCKED || map_lock_above == TERRAIN_WATER); // releasing down (or dash button) interrupts the slide if (moveCommands.dash != 1 && state.animation_type == ANIM_TYPE_SLIDE && (map_lock == BLOCK_UNBLOCKED || map_lock == BLOCK_WATER) && !is_blocked_above) { if (did_hit_ground) { set_animation_type(ANIM_TYPE_STAND); } else { set_animation_type(ANIM_TYPE_JUMP); } return false; } if (state.slide_distance > TILESIZE*5 && (map_lock == BLOCK_UNBLOCKED || map_lock == BLOCK_WATER)) { if (did_hit_ground == true) { set_animation_type(ANIM_TYPE_STAND); } else { set_animation_type(ANIM_TYPE_JUMP); } state.slide_distance = 0; return false; } // start slide if (state.animation_type != ANIM_TYPE_SLIDE && _dash_button_released == true) { if (moveCommands.dash == 1) { if (did_hit_ground == true || (did_hit_ground == false && _can_execute_airdash == true)) { _can_execute_airdash = false; set_animation_type(ANIM_TYPE_SLIDE); state.slide_distance = 0; _dash_button_released = false; int adjust_x = -3; if (state.direction == ANIM_DIRECTION_LEFT) { adjust_x = frameSize.width+3; } previous_position_list.clear(); gameControl.get_current_map_obj()->add_animation(ANIMATION_STATIC, &graphLib.dash_dust, position, st_position(adjust_x, frameSize.height-8), 160, 0, state.direction, st_size(8, 8)); } } } if (state.animation_type != ANIM_TYPE_SLIDE) { return false; } // if there is no ground, interrupts slide st_map_collision map_col_fall = map_collision(0, 1, gameControl.get_current_map_obj()->getMapScrolling()); int fall_map_lock = map_col_fall.block; if (can_air_dash() == false && (fall_map_lock == BLOCK_UNBLOCKED || fall_map_lock == BLOCK_WATER)) { set_animation_type(ANIM_TYPE_JUMP); state.slide_distance = 0; return false; } // check if trying to leave screen LEFT if (state.direction == ANIM_DIRECTION_LEFT && position.x <= 0) { state.slide_distance = 0; return false; } // check if trying to leave screen RIGHT if (is_player() == true && (realPosition.x + frameSize.width/2) > RES_W) { state.slide_distance = 0; return false; } // end of map if (state.direction == ANIM_DIRECTION_RIGHT && position.x + frameSize.width > MAP_W * TILESIZE) { state.slide_distance = 0; return false; } float res_move_x = 0; int mapLockAfter = BLOCK_UNBLOCKED; _obj_jump.finish(); // reduce progressively the jump-move value in oder to deal with collision float max_speed = move_speed * 2.5; for (float i=max_speed; i>0.0; i--) { int temp_i; if (state.direction == ANIM_DIRECTION_LEFT) { temp_i = -i; } else { temp_i = i; } st_map_collision map_col = map_collision(temp_i, 0, mapScrolling);; mapLockAfter = map_col.block; if (mapLockAfter == BLOCK_UNBLOCKED) { res_move_x = temp_i; break; } else if (mapLockAfter == BLOCK_WATER) { res_move_x = temp_i*0.8; break; } } if (res_move_x != 0 && (mapLockAfter == BLOCK_UNBLOCKED || mapLockAfter == BLOCK_WATER)) { position.x += res_move_x; state.slide_distance += abs((float)res_move_x); } else if (!is_blocked_above || slide_type != 1) { set_animation_type(ANIM_TYPE_JUMP); state.slide_distance = 0; return false; } return true; } // ********************************************************************************************** // // // // ********************************************************************************************** // bool character::jump(int jumpCommandStage, st_float_position mapScrolling) { // @TODO - can only jump again once set foot on land if (jumpCommandStage == 0 && jump_button_released == false) { jump_button_released = true; } if (state.animation_type == ANIM_TYPE_HIT) { return false; } // can't jump while on air dash if (state.animation_type == ANIM_TYPE_SLIDE && hit_ground() == false) { return false; } if (timer.getTimer() < jump_lock_timer) { // some effect blocked jumping std::cout << ">>>>>>>>>>>>>>>>> jump blocked!" << std::endl; return false; } int water_lock = gameControl.get_current_map_obj()->getMapPointLock(st_position((position.x+frameSize.width/2)/TILESIZE, (position.y+6)/TILESIZE)); if (_force_jump == true || (jumpCommandStage == 1 && jump_button_released == true)) { if (is_in_stairs_frame()) { if (_obj_jump.is_started() == false) { set_animation_type(ANIM_TYPE_JUMP); _is_falling = true; _stairs_falling_timer = timer.getTimer() + STAIRS_GRAB_TIMEOUT; // avoid player entering stairs immediatlly after jumping from it return false; } else { _obj_jump.interrupt(); if (_force_jump == true) { _force_jump = false; } } } else { if (_is_falling == false && (_obj_jump.is_started() == false || (_jumps_number > _obj_jump.get_jumps_number()))) { if (_super_jump == true) { _super_jump = false; set_platform(nullptr); _obj_jump.start(true, water_lock); } else { set_platform(nullptr); _obj_jump.start(false, water_lock); } if (state.animation_type == ANIM_TYPE_SLIDE && slide_type == 0) { _dashed_jump = true; } set_animation_type(ANIM_TYPE_JUMP); jump_button_released = false; } } } bool is_onquicksand = false; if (is_on_quicksand()) { is_onquicksand = true; } if (_obj_jump.is_started() == true) { float jump_speed = _obj_jump.get_speed(); bool jump_moved = false; // if got into stairs, finish jumping if ((is_in_stairs_frame())) { _obj_jump.finish(); return false; } if (jump_speed < 0 && jumpCommandStage == 0 && _force_jump == false) { _obj_jump.interrupt(); } // check collision float abs_jump_speed = abs(jump_speed); for (float i=abs_jump_speed; i>0.0; i--) { int speed_y = 0; if (jump_speed > 0) { speed_y = i; } else { speed_y = i*-1; } st_map_collision map_col = map_collision(0, speed_y, mapScrolling); int map_lock = map_col.block; //std::cout << "CHAR::JUMP - speed[" << i << "], map_lock[" << map_lock << "]" << std::endl; if (abs(speed_y) > 0 && (map_lock == BLOCK_UNBLOCKED || map_lock == BLOCK_WATER || map_lock == BLOCK_QUICKSAND)) { position.y += speed_y; jump_last_moved = speed_y; jump_moved = true; break; } } //std::cout << "CHAR::JUMP - jump_speed[" << jump_speed << "], jump_last_moved[" << jump_last_moved << "], abs_jump_speed[" << abs_jump_speed << "], jump_moved[" << jump_moved << "], position.y[" << position.y << "]" << std::endl; if (jump_speed != 0 && jump_moved == false) { if (jump_speed < 0) { //std::cout << "CHAR::JUMP - INTERRUMP #1" << std::endl; _obj_jump.interrupt(); } else if (hit_ground() == true) { //std::cout << "CHAR::JUMP - FINISH" << std::endl; _obj_jump.finish(); } if (position.y < -frameSize.width) { //std::cout << "CHAR::JUMP - ADJUST" << std::endl; position.y += TILESIZE; } _force_jump = false; } if (_obj_jump.is_started() == true && jump_speed < 0.0 && abs(jump_speed) < 1.0 && abs(jump_last_moved) < 1.0) { std::cout << "CHAR::JUMP - INTERRUMP #1" << std::endl; _obj_jump.interrupt(); } _obj_jump.execute(water_lock); if (_obj_jump.is_started() == false) { soundManager.play_sfx(SFX_PLAYER_JUMP); if (_force_jump == true) { _force_jump = false; } } else { if (is_player() && position.y > RES_H+1) { _obj_jump.finish(); } } } else { if (_force_jump == true) { _force_jump = false; } //accel_speed_y = GRAVITY_MAX_SPEED; gravity(); return false; } return true; } void character::check_map_collision_point(int &map_block, int &new_map_lock, int &old_map_lock, int mode_xy) // mode_xy 0 is x, 1 is y { if (map_block == BLOCK_UNBLOCKED && new_map_lock == TERRAIN_WATER) { map_block = BLOCK_WATER; } if (map_block == BLOCK_UNBLOCKED && new_map_lock == TERRAIN_QUICKSAND) { map_block = BLOCK_QUICKSAND; } bool must_block = false; if (old_map_lock != new_map_lock) { if (is_player() == false && new_map_lock == TERRAIN_UNBLOCKED && old_map_lock == TERRAIN_WATER) { // NPCs must not leave water must_block = true; } else if (is_player() == false && _is_boss == false && old_map_lock == TERRAIN_UNBLOCKED && new_map_lock == TERRAIN_WATER) { // non-boss NPCs must not enter water must_block = true; } else if (is_player() == false && new_map_lock == TERRAIN_SCROLL_LOCK) { must_block = true; } else if (is_player() == false && new_map_lock == TERRAIN_DOOR) { must_block = true; } else if (new_map_lock == TERRAIN_EASYMODEBLOCK) { if (game_save.difficulty == DIFFICULTY_EASY) { must_block = true; } } else if (new_map_lock == TERRAIN_HARDMODEBLOCK) { if (game_save.difficulty == DIFFICULTY_HARD) { if (mode_xy == 1 || is_player()) { damage_spikes(true); } must_block = true; } } else if (new_map_lock != TERRAIN_UNBLOCKED && new_map_lock != TERRAIN_WATER && new_map_lock != TERRAIN_SCROLL_LOCK && new_map_lock != TERRAIN_CHECKPOINT && new_map_lock != TERRAIN_STAIR && new_map_lock != TERRAIN_HARDMODEBLOCK && new_map_lock != TERRAIN_EASYMODEBLOCK) { must_block = true; } } else { if (new_map_lock == TERRAIN_EASYMODEBLOCK && game_save.difficulty == DIFFICULTY_EASY) { must_block = true; } else if (new_map_lock == TERRAIN_HARDMODEBLOCK && game_save.difficulty == DIFFICULTY_HARD) { if (mode_xy == 1 || is_player()) { damage_spikes(true); } must_block = true; } else if (map_block == BLOCK_UNBLOCKED && (new_map_lock != BLOCK_UNBLOCKED && new_map_lock != TERRAIN_STAIR && new_map_lock != TERRAIN_WATER && new_map_lock != TERRAIN_EASYMODEBLOCK && new_map_lock != TERRAIN_HARDMODEBLOCK)) { must_block = true; } else if (map_block == BLOCK_WATER && new_map_lock == BLOCK_X) { must_block = true; } else if (map_block == BLOCK_QUICKSAND && new_map_lock == BLOCK_X) { must_block = true; } } if (must_block == true) { if (mode_xy == 0) { if (map_block != BLOCK_XY) { map_block = BLOCK_X; } } else { if (map_block == BLOCK_X) { map_block = BLOCK_XY; } else if (map_block != BLOCK_XY) { map_block = BLOCK_Y; } } } } bool character::process_special_map_points(int map_lock, int incx, int incy, st_position map_pos) { UNUSED(incy); int direction = ANIM_DIRECTION_LEFT; if (incx > 0) { direction = ANIM_DIRECTION_RIGHT; } if (incx != 0 && map_lock == TERRAIN_SCROLL_LOCK) { //gameControl.horizontal_screen_move(direction, false, map_pos.x, map_pos.y); gameControl.horizontal_screen_move(state.direction, false, map_pos.x); return true; } if (state.animation_type != ANIM_TYPE_TELEPORT && (map_lock == TERRAIN_SPIKE || (map_lock == TERRAIN_HARDMODEBLOCK && game_save.difficulty == 2))) { damage_spikes(true); return true; } return false; } void character::check_platform_move(short map_lock) { float move = 0.0; bool can_move = true; if (_moving_platform_timer < timer.getTimer()) { int pos_y = (position.y + frameSize.height/2) / TILESIZE; if (map_lock == TERRAIN_MOVE_LEFT) { move = (move_speed-0.5)*-1; int pos_x = (position.x + move) / TILESIZE; if (is_player() && state.direction == ANIM_DIRECTION_RIGHT) { // add a few pixels because of graphic when turned right pos_x = (position.x + 5 + move) / TILESIZE; } int point_terrain = gameControl.getMapPointLock(st_position(pos_x, pos_y)); if (point_terrain != TERRAIN_UNBLOCKED && point_terrain != TERRAIN_WATER) { can_move = false; } } else if (map_lock == TERRAIN_MOVE_RIGHT) { move = move_speed-0.5; int pos_x = (position.x + frameSize.width - 10 + move) / TILESIZE; int point_terrain = gameControl.getMapPointLock(st_position(pos_x, pos_y)); if (point_terrain != TERRAIN_UNBLOCKED && point_terrain != TERRAIN_WATER) { can_move = false; } } else { return; } if (can_move) { position.x += move; _moving_platform_timer = timer.getTimer()+MOVING_GROUND; } } } st_map_collision character::map_collision(const float incx, const short incy, st_float_position mapScrolling, int hitbox_anim_type) { UNUSED(mapScrolling); int py_adjust = 0; if (is_player() == true) { py_adjust = 8; } int terrain_type = TERRAIN_UNBLOCKED; /// @TODO: move to char hitbox if (state.animation_type == ANIM_TYPE_JUMP || state.animation_type == ANIM_TYPE_JUMP_ATTACK) { py_adjust = 1; } int map_block = BLOCK_UNBLOCKED; if (gameControl.get_current_map_obj() == NULL) { return st_map_collision(BLOCK_XY, TERRAIN_SOLID); } gameControl.get_current_map_obj()->collision_char_object(this, incx, incy); object_collision res_collision_object = gameControl.get_current_map_obj()->get_obj_collision(); bool is_on_moving_platform = false; if (_platform != nullptr && _platform == res_collision_object._object && (_platform->get_type() == OBJ_MOVING_PLATFORM_UP_LOOP || _platform->get_type() == OBJ_MOVING_PLATFORM_DOWN)) { is_on_moving_platform = true; } //if (is_player()) std::cout << "CHAR::map_collision - is_on_moving_platform[" << is_on_moving_platform << "], py[" << position.y << "], py+h[" << (get_hitbox().y + get_hitbox().h) << "]" << std::endl; if (is_player() == true && res_collision_object._block != 0 && is_on_moving_platform == false) { // deal with teleporter object that have special block-area and effect (9)teleporting) if (state.animation_type != ANIM_TYPE_TELEPORT && res_collision_object._object != NULL) { if (res_collision_object._object->get_type() == OBJ_BOSS_TELEPORTER || (res_collision_object._object->get_type() == OBJ_FINAL_BOSS_TELEPORTER && res_collision_object._object->is_started() == true)) { if (is_on_teleporter_capsulse(res_collision_object._object) == true) { set_direction(ANIM_DIRECTION_RIGHT); gameControl.object_teleport_boss(res_collision_object._object->get_boss_teleporter_dest(), res_collision_object._object->get_boss_teleport_map_dest(), res_collision_object._object->get_obj_map_id(), true); } } else if (res_collision_object._object->get_type() == OBJ_STAGE_BOSS_TELEPORTER) { if (is_on_teleporter_capsulse(res_collision_object._object) == true) { set_direction(ANIM_DIRECTION_RIGHT); gameControl.object_teleport_boss(res_collision_object._object->get_boss_teleporter_dest(), res_collision_object._object->get_boss_teleport_map_dest(), res_collision_object._object->get_obj_map_id(), false); } // platform teleporter is just a base where player can step in to teleport } else if (res_collision_object._object->get_type() == OBJ_PLATFORM_TELEPORTER && is_on_teleport_platform(res_collision_object._object) == true) { set_direction(ANIM_DIRECTION_RIGHT); soundManager.play_sfx(SFX_TELEPORT); gameControl.object_teleport_boss(res_collision_object._object->get_boss_teleporter_dest(), res_collision_object._object->get_boss_teleport_map_dest(), res_collision_object._object->get_obj_map_id(), false); // ignore block } else if (res_collision_object._object->get_type() == OBJ_FINAL_BOSS_TELEPORTER && res_collision_object._object->is_started() == false) { // acho que era para ver se todos os inimigos estão mortos, mas não completei o código, então vamos fazer como um boss-teleproter set_direction(ANIM_DIRECTION_RIGHT); gameControl.object_teleport_boss(res_collision_object._object->get_boss_teleporter_dest(), res_collision_object._object->get_boss_teleport_map_dest(), res_collision_object._object->get_obj_map_id(), false); } else if (!get_item(res_collision_object)) { map_block = res_collision_object._block; if (map_block == BLOCK_Y || map_block == BLOCK_XY) { _can_execute_airdash = true; } // INSIDE PLATFORM OBJECT, MUST DIE if (map_block == BLOCK_INSIDE_OBJ) { damage(999, true); return st_map_collision(BLOCK_UNBLOCKED, TERRAIN_SOLID); } } } } else if (is_player() == false && res_collision_object._block != 0) { map_block = res_collision_object._block; if (map_block == BLOCK_Y || map_block == BLOCK_XY) { _can_execute_airdash = true; } } if (is_player()) { if (have_shoryuken() == true && state.animation_type == ANIM_TYPE_SPECIAL_ATTACK) { gameControl.get_current_map_obj()->collision_player_special_attack(this, incx, incy, 9, py_adjust); } else { classnpc* npc_touch = gameControl.get_current_map_obj()->collision_player_npcs(this, 0, 0); if (npc_touch != NULL) { if (npc_touch->get_size().height > this->get_size().height) { damage(TOUCH_DAMAGE_SMALL, false); } else { damage(TOUCH_DAMAGE_BIG, false); } if (_was_hit == true) { npc_touch->hit_player(); } } } } // no need to test map collision if object collision is already X+Y if (map_block == BLOCK_XY && incx != 0) { return st_map_collision(BLOCK_XY, TERRAIN_SOLID); } if (incx == 0 && incy == 0) { return st_map_collision(BLOCK_UNBLOCKED, TERRAIN_UNBLOCKED); } if (_always_move_ahead == false && ((incx < 0 && position.x+incx) < 0 || (incx > 0 && position.x+incx > MAP_W*TILESIZE))) { if (map_block == BLOCK_UNBLOCKED) { map_block = BLOCK_X; } else { map_block = BLOCK_XY; } } if ((incy < 0 && ((position.y+incy+frameSize.height < 0) || (incx > 0 && position.y+incx+TILESIZE > MAP_W*TILESIZE)))) { if (map_block == BLOCK_UNBLOCKED) { map_block = BLOCK_Y; } else { map_block = BLOCK_XY; } } // if we are out of map, return always true if (_always_move_ahead == true) { if ((incx < 0 && (position.x+incx < 0)) || (incx > 0 && position.x+incx > MAP_W*TILESIZE)) { return st_map_collision(BLOCK_UNBLOCKED, TERRAIN_UNBLOCKED); } } /// @TODO - use collision rect for the current frame. Until there, use 3 points check int py_top, py_middle, py_bottom; int px_left, px_center, px_right; int old_px_left, old_px_center, old_px_right; st_rectangle rect_hitbox = get_hitbox(hitbox_anim_type); py_top = rect_hitbox.y + incy + py_adjust; py_middle = rect_hitbox.y + incy + rect_hitbox.h/2; py_bottom = rect_hitbox.y + incy + rect_hitbox.h - 2; px_center = rect_hitbox.x + incx + rect_hitbox.w/2; px_left = rect_hitbox.x + incx; px_right = rect_hitbox.x + incx + rect_hitbox.w; old_px_left = rect_hitbox.x; old_px_right = rect_hitbox.x + rect_hitbox.w; if (incx == 0 && incy != 0) { px_right--; } st_position map_point; st_position old_map_point; map_point.x = px_left/TILESIZE; old_map_point.x = old_px_left/TILESIZE; int new_map_lock = TERRAIN_UNBLOCKED; int old_map_lock = TERRAIN_UNBLOCKED; if (incx > 0) { map_point.x = px_right/TILESIZE; old_map_point.x = old_px_right/TILESIZE; } /// @TODO - use a array-of-array for points in order to having a cleaner code int map_x_points[3]; if (incx == 0 && incy != 0) { px_left++; px_right--; } map_x_points[0] = px_left/TILESIZE; map_x_points[1] = px_center/TILESIZE; map_x_points[2] = px_right/TILESIZE; int map_y_points[3]; map_y_points[0] = py_top/TILESIZE; map_y_points[1] = py_middle/TILESIZE; map_y_points[2] = py_bottom/TILESIZE; // TEST X POINTS if (incx != 0) { for (int i=0; i<3; i++) { if (is_player() && (state.animation_type == ANIM_TYPE_JUMP || state.animation_type == ANIM_TYPE_JUMP_ATTACK) && i == 0) { map_point.y = (py_top+1)/TILESIZE; } else { map_point.y = map_y_points[i]; } old_map_point.y = map_point.y; old_map_lock = gameControl.getMapPointLock(old_map_point); new_map_lock = gameControl.getMapPointLock(map_point); check_map_collision_point(map_block, new_map_lock, old_map_lock, 0); if (is_player() && process_special_map_points(new_map_lock, incx, incy, map_point) == true) { return st_map_collision(map_block, new_map_lock); } } //if (is_player() == false) std::cout << "CHAR::map_collision - px_left[" << px_left << "],px_right[" << px_right << "], map_block[" << (int)map_block << "]" << std::endl; } // TEST Y POINTS if (incy < 0) { map_point.y = py_top/TILESIZE; } else if (incy > 0) { map_point.y = py_bottom/TILESIZE; } old_map_point.y = py_middle/TILESIZE; if (incy != 0) { for (int i=0; i<3; i++) { map_point.x = map_x_points[i]; old_map_point.x = map_x_points[i]; old_map_lock = gameControl.getMapPointLock(old_map_point); new_map_lock = gameControl.getMapPointLock(map_point); check_map_collision_point(map_block, new_map_lock, old_map_lock, 1); if (new_map_lock != TERRAIN_UNBLOCKED) { terrain_type = new_map_lock; } if (is_player() && process_special_map_points(new_map_lock, incx, incy, map_point) == true) { return st_map_collision(map_block, new_map_lock); } // STAIRS if ((map_block == BLOCK_UNBLOCKED || map_block == BLOCK_X || map_block == BLOCK_WATER) && incy > 0 && new_map_lock == TERRAIN_STAIR) { // stairs special case int middle_y_point_lock = TERRAIN_UNBLOCKED; if (incy == 1) { // gravity middle_y_point_lock = gameControl.getMapPointLock(st_position(map_x_points[i], (py_bottom-1)/TILESIZE)); } else { // other cases as falling or jump middle_y_point_lock = gameControl.getMapPointLock(st_position(map_x_points[i], map_y_points[1])); } if (middle_y_point_lock != TERRAIN_STAIR) { if (map_block == BLOCK_X) { map_block = BLOCK_XY; } else { map_block = BLOCK_Y; } } } } } if (is_player()) { // check water splash int point_top = gameControl.getMapPointLock(st_position(map_x_points[1], map_y_points[0])); int point_middle = gameControl.getMapPointLock(st_position(map_x_points[1], map_y_points[1])); int point_bottom = gameControl.getMapPointLock(st_position(map_x_points[1], map_y_points[2])); if (incy != 0) { if (point_top == TERRAIN_UNBLOCKED && point_middle == TERRAIN_UNBLOCKED && point_bottom == TERRAIN_WATER && _water_splash == false) { if (incy < 0) { soundManager.play_sfx(SFX_WATER_LEAVE); } else { soundManager.play_sfx(SFX_WATER_LEAVE); } _water_splash = true; gameControl.get_current_map_obj()->add_animation(ANIMATION_STATIC, &graphLib.water_splash, st_float_position(position.x, (map_y_points[2]-1)*TILESIZE-TILESIZE/3), st_position(0, -6), 100, 0, ANIM_DIRECTION_LEFT, st_size(32, 23)); } else if (point_top == point_bottom && point_top == point_middle && _water_splash == true) { _water_splash = false; } } } return st_map_collision(map_block, terrain_type); } bool character::is_on_teleporter_capsulse(object *object) { // check se player está dentro da área Y do objeto int obj_y = object->get_position().y; if (obj_y < position.y && (obj_y + object->get_size().height > position.y + frameSize.height)) { // só teleporta quando estiver no centro (1 TILE), caso contrário, ignora block double abs_value = TILESIZE/2 - object->get_size().width; int obj_center_diff = abs(abs_value)/2; int limit_min = object->get_position().x + obj_center_diff; int limit_max = object->get_position().x + object->get_size().width - obj_center_diff; int px = position.x + frameSize.width/2; if (px > limit_min && px < limit_max) { return true; } } return false; } bool character::is_on_teleport_platform(object *object) { // check if player is above platform int obj_y = object->get_position().y; int py = position.y + frameSize.height; if (py-obj_y <= 2) { // só teleporta quando estiver no centro (1 TILE), caso contrário, ignora block double abs_value = TILESIZE/2 - object->get_size().width; int obj_center_diff = abs(abs_value)/2; int limit_min = object->get_position().x + obj_center_diff; int limit_max = object->get_position().x + object->get_size().width - obj_center_diff; int px = position.x + frameSize.width/2; if (px > limit_min && px < limit_max) { return true; } } return false; } // ********************************************************************************************** // // // // ********************************************************************************************** // void character::addSpriteFrame(int anim_type, int posX, graphicsLib_gSurface &spritesSurface, int delay) { struct st_rectangle spriteArea; spriteArea.x = posX*frameSize.width; spriteArea.y = 0; spriteArea.w = frameSize.width; spriteArea.h = frameSize.height; // ANIM_TYPE_STAIRS_MOVE and ANIM_TYPE_STAIRS_SEMI have an extra frame that is the mirror of the first one for (int anim_direction=0; anim_direction<=1; anim_direction++) { for (int i=0; i<ANIM_FRAMES_COUNT; i++) { // find the last free frame if ((graphLib.character_graphics_list.find(name)->second).frames[anim_direction][anim_type][i].frameSurface.get_surface() == NULL) { st_spriteFrame *sprite = &(graphLib.character_graphics_list.find(name)->second).frames[anim_direction][anim_type][i]; graphicsLib_gSurface gsurface = graphLib.surfaceFromRegion(spriteArea, spritesSurface); // RIGHT if (anim_direction != 0) { graphLib.set_spriteframe_surface(sprite, gsurface); // LEFT } else { graphicsLib_gSurface gsurface_flip; graphLib.flip_image(gsurface, gsurface_flip, flip_type_horizontal); graphLib.set_spriteframe_surface(sprite, gsurface_flip); } (graphLib.character_graphics_list.find(name)->second).frames[anim_direction][anim_type][i].frameSurface.init_colorkeys(); (graphLib.character_graphics_list.find(name)->second).frames[anim_direction][anim_type][i].delay = delay; if (anim_type == ANIM_TYPE_STAIRS_MOVE || anim_type == ANIM_TYPE_STAIRS_SEMI) { st_spriteFrame *sprite = &(graphLib.character_graphics_list.find(name)->second).frames[anim_direction][anim_type][i+1]; if (anim_direction != 0) { graphicsLib_gSurface gsurface_flip; graphLib.flip_image(gsurface, gsurface_flip, flip_type_horizontal); graphLib.set_spriteframe_surface(sprite, gsurface_flip); } else { graphLib.set_spriteframe_surface(sprite, gsurface); } (graphLib.character_graphics_list.find(name)->second).frames[anim_direction][anim_type][i+1].frameSurface.init_colorkeys(); (graphLib.character_graphics_list.find(name)->second).frames[anim_direction][anim_type][i+1].delay = delay; } break; } } } } // ********************************************************************************************** // // // // ********************************************************************************************** // void character::set_is_player(bool set_player) { is_player_type = set_player; } // ********************************************************************************************** // // // // ********************************************************************************************** // bool character::is_player() const { return is_player_type; } // ********************************************************************************************** // // // // ********************************************************************************************** // string character::get_name(void) const { return name; } // ********************************************************************************************** // // Returns true of character is over a staircase // // ********************************************************************************************** // st_position character::is_on_stairs(st_rectangle pos) { if (_dropped_from_stairs == true) { // was dropped from stairs, can't grab again until invencibility time ends return st_position(-1, -1);; } int map_tile_x, map_tile_y; int diff_w = pos.w/3; map_tile_x = (pos.x+diff_w)/TILESIZE; map_tile_y = (pos.y)/TILESIZE; if (gameControl.get_current_map_obj()->getMapPointLock(st_position(map_tile_x, map_tile_y)) == TERRAIN_STAIR) { return st_position(map_tile_x, map_tile_y); } map_tile_x = (pos.x+pos.w-diff_w)/TILESIZE; if (gameControl.get_current_map_obj()->getMapPointLock(st_position(map_tile_x, map_tile_y)) == TERRAIN_STAIR) { return st_position(map_tile_x, map_tile_y); } return st_position(-1, -1); } // ********************************************************************************************** // // // // ********************************************************************************************** // st_size character::get_size() const { return frameSize; } st_rectangle character::get_hitbox(int anim_type) { float x = position.x; float y = position.y; float w = frameSize.width; float h = frameSize.height; if (anim_type == -1) { anim_type = state.animation_type; } // player hitbox is hardcoded if (is_player()) { x = position.x + GameMediator::get_instance()->player_list_v3_1[_number].sprite_hit_area.x; y = position.y + GameMediator::get_instance()->player_list_v3_1[_number].sprite_hit_area.y; w = GameMediator::get_instance()->player_list_v3_1[_number].sprite_hit_area.w; h = GameMediator::get_instance()->player_list_v3_1[_number].sprite_hit_area.h; if (anim_type == ANIM_TYPE_SLIDE && slide_type == 1) { y = position.y + GameMediator::get_instance()->player_list_v3_1[_number].sprite_hit_area.y + SLIDE_Y_ADJUST; h = GameMediator::get_instance()->player_list_v3_1[_number].sprite_hit_area.h - SLIDE_Y_ADJUST; } //std::cout << "CHAT:get_hitbox - pos.x[" << position.x << "], hit.x[" << x << "], adjust.x[" << GameMediator::get_instance()->player_list_v3_1[_number].sprite_hit_area.x << "]" << std::endl; } else { int anim_n = state.animation_state; // prevent getting size from a frame that does not have information, use Vulnerable-area or hitbox from STAND instead st_rectangle col_rect; if (GameMediator::get_instance()->get_enemy(_number)->sprites[anim_type][anim_n].used == true) { col_rect = GameMediator::get_instance()->get_enemy(_number)->sprites[anim_type][anim_n].collision_rect; } else if (GameMediator::get_instance()->get_enemy(_number)->sprites[ANIM_TYPE_STAND][0].used == true) { col_rect = GameMediator::get_instance()->get_enemy(_number)->sprites[ANIM_TYPE_STAND][0].collision_rect; } else { col_rect = st_rectangle(GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x, GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.y, GameMediator::get_instance()->get_enemy(_number)->frame_size.width, GameMediator::get_instance()->get_enemy(_number)->frame_size.height); } if (!_has_background) { if (state.direction == ANIM_DIRECTION_LEFT) { x = position.x + frameSize.width - col_rect.x - col_rect.w; } else { x += col_rect.x; } y += col_rect.y; } else { if (state.direction == ANIM_DIRECTION_LEFT) { x = position.x - GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x; } else { x = position.x - GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x; } y -= GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.y; } w = col_rect.w; h = col_rect.h; } //if (!is_player()) std::cout << "NPC[" << name << "] - has-bg[" << _has_background << "], pos.x[" << position.x << "], hitbox[" << x << ", " << y << ", " << w << ", " << h << "]" << std::endl; return st_rectangle(x, y, w, h); } st_rectangle character::get_vulnerable_area(int anim_type) { float x = position.x; float y = position.y; float w = frameSize.width; float h = frameSize.height; if (vulnerable_area_box.w != 0 && vulnerable_area_box.h != 0) { // use vulnerable area y = position.y + vulnerable_area_box.y; if (state.direction == ANIM_DIRECTION_LEFT) { x = position.x - GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x; } else { x = position.x - vulnerable_area_box.x; if (_has_background == true) { int diff_left = total_frame_size.width - vulnerable_area_box.w; x = position.x - GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x + diff_left; //std::cout << "NPC[" << name << "] - x[" << x << "], diff_left[" << diff_left << "], pos.x[" << position.x << "], total_w[" << total_frame_size.width << "], vulnerable_area_box.w[" << vulnerable_area_box.w << "], vulnerable.x[" << vulnerable_area_box.x << "], calc-x[" << x << "], bg_adjust.x[" << GameMediator::get_instance()->get_enemy(_number)->sprites_pos_bg.x << "]" << std::endl; } } w = vulnerable_area_box.w; h = vulnerable_area_box.h; return st_rectangle(x, y, w, h); } else { return get_hitbox(); } } // ********************************************************************************************** // // adds an entry into character_graphics_list map, if needed // // ********************************************************************************************** // void character::add_graphic() { if (name == "") { return; } std::map<std::string, st_char_sprite_data>::iterator it; const std::string temp_name(name); it = graphLib.character_graphics_list.find(name); if (it == graphLib.character_graphics_list.end()) { // there is no graphic with this key yet, add it std::pair<std::string, st_char_sprite_data> temp_data(temp_name, st_char_sprite_data()); graphLib.character_graphics_list.insert(temp_data); } } bool character::have_frame_graphics() { std::map<std::string, st_char_sprite_data>::iterator it; it = graphLib.character_graphics_list.find(name); if (it != graphLib.character_graphics_list.end()) { // there is no graphic with this key yet, add it for (int i=0; i<2; i++) { for (int j=0; j<ANIM_TYPE_COUNT; j++) { for (int k=0; k<ANIM_FRAMES_COUNT; k++) { if ((graphLib.character_graphics_list.find(name)->second).frames[i][k][k].frameSurface.width > 0 && (graphLib.character_graphics_list.find(name)->second).frames[i][j][k].frameSurface.get_surface() != NULL) { return true; } } } } } return false; } void character::clean_character_graphics_list() { if (is_player()) { return; } if (graphLib.character_graphics_list.size() <= 0) { return; } std::map<std::string, st_char_sprite_data>::iterator it; it = graphLib.character_graphics_list.find(name); if (it != graphLib.character_graphics_list.end()) { graphLib.character_graphics_list.erase(it); } } bool character::have_background_graphics() { static std::map<std::string, graphicsLib_gSurface>::iterator it; it = graphLib.character_graphics_background_list.find(name); if (it != graphLib.character_graphics_background_list.end()) { // there is no graphic with this key yet, add it return true; } return false; } int character::frames_count() { for (int i=0; i<ANIM_FRAMES_COUNT; i++) { if ((graphLib.character_graphics_list.find(name)->second).frames[state.direction][state.animation_type][i].frameSurface.width == 0 || (graphLib.character_graphics_list.find(name)->second).frames[state.direction][state.animation_type][i].frameSurface.get_surface() == NULL) { return i; } } return ANIM_FRAMES_COUNT; } void character::advance_to_last_frame() { int frames_n = frames_count(); if (frames_n > 0) { state.animation_state = frames_n - 1; } else { state.animation_state = 0; } } bool character::is_on_last_animation_frame() { bool result = (_is_last_frame && state.animation_timer < timer.getTimer()); return result; } bool character::have_frame_graphic(int direction, int type, int pos) { if (pos >= ANIM_FRAMES_COUNT) { return false; } if ((graphLib.character_graphics_list.find(name)->second).frames[direction][type][pos].frameSurface.width == 0 || (graphLib.character_graphics_list.find(name)->second).frames[direction][type][pos].frameSurface.get_surface() == NULL) { return false; } return true; } bool character::is_on_quicksand() { int px = (get_hitbox().x + get_hitbox().w/2)/TILESIZE; int py = (get_hitbox().y + get_hitbox().h - QUICKSAND_JUMP_LIMIT)/TILESIZE; Uint8 terrain_type = gameControl.get_current_map_obj()->getMapPointLock(st_position(px, py)); bool result = (terrain_type == TERRAIN_QUICKSAND); //std::cout << "CHAR::is_on_quicksand - [" << result << "], terrain[" << (int)terrain_type << "]" << std::endl; return result; } int character::get_teleport_state() { return teleporting_out; } bool character::is_in_stairs_frame() const { if (state.animation_type == ANIM_TYPE_STAIRS || state.animation_type == ANIM_TYPE_STAIRS_MOVE || state.animation_type == ANIM_TYPE_STAIRS_SEMI || state.animation_type == ANIM_TYPE_STAIRS_ATTACK) { return true; } return false; } bool character::is_on_attack_frame() { if (state.animation_type == ANIM_TYPE_ATTACK || state.animation_type == ANIM_TYPE_STAIRS_ATTACK || state.animation_type == ANIM_TYPE_WALK_ATTACK || state.animation_type == ANIM_TYPE_JUMP_ATTACK || state.animation_type == ANIM_TYPE_THROW || state.animation_type == ANIM_TYPE_SPECIAL_ATTACK || state.animation_type == ANIM_TYPE_ATTACK_DIAGONAL_DOWN || state.animation_type == ANIM_TYPE_ATTACK_DIAGONAL_UP || state.animation_type == ANIM_TYPE_ATTACK_DOWN || state.animation_type == ANIM_TYPE_ATTACK_UP || state.animation_type == ANIM_TYPE_ATTACK_SPECIAL) { return true; } return false; } void character::recharge(e_energy_types _en_type, int value) { if (_en_type == ENERGY_TYPE_HP) { if (hitPoints.current < hitPoints.total) { if (hitPoints.current + value <= hitPoints.total) { hitPoints.current += value; } else { hitPoints.current = hitPoints.total; } if (value > ENERGY_ITEM_SMALL) { soundManager.play_sfx(SFX_GOT_ENERGY_BIG); } else { soundManager.play_sfx(SFX_GOT_ENERGY); } } } } bool character::get_item(object_collision& obj_info) { bool res = false; // deal with non-blocking items if (obj_info._object != NULL && obj_info._object->finished() == false) { switch (obj_info._object->get_type()) { case OBJ_ENERGY_PILL_SMALL: recharge(ENERGY_TYPE_HP, ENERGY_ITEM_SMALL); res = true; obj_info._object->set_finished(true); break; case OBJ_ENERGY_PILL_BIG: recharge(ENERGY_TYPE_HP, ENERGY_ITEM_BIG); res = true; obj_info._object->set_finished(true); break; default: break; } } return res; } // returns type, or -1 if none int character::is_executing_effect_weapon() { vector<projectile>::iterator it; for (it=projectile_list.begin(); it<projectile_list.end(); it++) { int move_type = (*it).get_move_type(); if (move_type == TRAJECTORY_BOMB) { return TRAJECTORY_BOMB; } else if (move_type == TRAJECTORY_QUAKE) { return TRAJECTORY_QUAKE; } else if (move_type == TRAJECTORY_FREEZE) { return TRAJECTORY_FREEZE; } else if (move_type == TRAJECTORY_CENTERED) { return TRAJECTORY_CENTERED; } else if (move_type == TRAJECTORY_PUSH_BACK) { return TRAJECTORY_PUSH_BACK; } else if (move_type == TRAJECTORY_PULL) { return TRAJECTORY_PULL; } } return -1; } // is all projectiles are normal (-1 or 0) return the character's max_shots, // otherwise, find the lowest between all fired projectiles Uint8 character::get_projectile_max_shots(bool always_charged) { bool all_projectiles_normal = true; vector<projectile>::iterator it; short max_proj = 9; for (it=projectile_list.begin(); it<projectile_list.end(); it++) { short id = (*it).get_id(); // if always charged, and projectile is semi-charged, count as normal if (id != -1 && id != 0) { if (always_charged == true && id == game_data.semi_charged_projectile_id) { continue; } all_projectiles_normal = false; short proj_max = (*it).get_max_shots(); if (max_proj > 0 && proj_max < max_proj) { max_proj = proj_max; } } } if (all_projectiles_normal == true) { return max_projectiles; } return max_proj; } void character::push_back(short direction) { int xinc = -(move_speed-0.2); if (direction == ANIM_DIRECTION_LEFT) { xinc = (move_speed-0.2); } if (test_change_position(xinc, 0)) { position.x += xinc; } } void character::pull(short direction) { int xinc = (move_speed-0.2); if (direction == ANIM_DIRECTION_LEFT) { xinc = -(move_speed-0.2); } if (test_change_position(xinc, 0)) { position.x += xinc; } } bool character::get_can_fly() { return can_fly; } bool character::animation_has_restarted() { return _was_animation_reset; } void character::set_animation_has_restarted(bool restarted) { _was_animation_reset = restarted; } void character::remove_freeze_effect() { state.frozen = false; state.frozen_timer = 0; } st_position character::get_int_position() { return st_position((int)position.x, (int)position.y); } void character::add_projectile(short id, st_position pos, int trajectory, int direction) { projectile_to_be_added_list.push_back(projectile(id, direction, pos, is_player(), _number)); projectile &new_projectile = projectile_to_be_added_list.back(); new_projectile.set_is_permanent(); new_projectile.set_trajectory(trajectory); } void character::check_reset_stand() { if (!is_player()) { // NPCs do not need this return; } // is walking without moving, reset to stand if (moveCommands.left == 0 && moveCommands.right == 0) { if (state.animation_type == ANIM_TYPE_WALK) { //std::cout << "CHAR - RESET STAND #1" << std::endl; set_animation_type(ANIM_TYPE_STAND); } else if (state.animation_type == ANIM_TYPE_WALK_ATTACK) { set_animation_type(ANIM_TYPE_ATTACK); } } if ((state.animation_type == ANIM_TYPE_ATTACK || state.animation_type == ANIM_TYPE_WALK_ATTACK || state.animation_type == ANIM_TYPE_JUMP_ATTACK || state.animation_type == ANIM_TYPE_ATTACK_DIAGONAL_DOWN || state.animation_type == ANIM_TYPE_ATTACK_DIAGONAL_UP) && timer.getTimer() > state.attack_timer+500) { switch (state.animation_type) { case ANIM_TYPE_WALK_ATTACK: set_animation_type(ANIM_TYPE_WALK); //std::cout << "CHAR - RESET STAND #2" << std::endl; break; case ANIM_TYPE_JUMP_ATTACK: set_animation_type(ANIM_TYPE_JUMP); break; default: //std::cout << "CHAR - RESET STAND #3" << std::endl; set_animation_type(ANIM_TYPE_STAND); break; } } } unsigned int character::get_projectile_count() { int pcount = 0; vector<projectile>::iterator it; for (it=projectile_list.begin(); it<projectile_list.end(); it++) { pcount++; } return pcount; } // ********************************************************************************************** // // set the object platform player is over, if any // // ********************************************************************************************** // void character::set_platform(object* obj) { if (obj == nullptr && _platform == nullptr) { return; } _obj_jump.finish(); if (obj != nullptr) { if (state.animation_type == ANIM_TYPE_JUMP) { set_animation_type(ANIM_TYPE_STAND); } else if (state.animation_type == ANIM_TYPE_JUMP_ATTACK) { set_animation_type(ANIM_TYPE_ATTACK); } set_animation_type(ANIM_TYPE_STAND); } _platform = obj; } object* character::get_platform() { return _platform; } int character::get_direction() const { return state.direction; } void character::set_direction(int direction) { int must_adjust_x = frameSize.width % TILESIZE; if (!is_player() && direction != state.direction && must_adjust_x != 0) { // fix to avoid getting stuck into a wall // if (direction == ANIM_DIRECTION_LEFT) { position.x -= TILESIZE/3; } else { position.x += TILESIZE/3; } } if (direction != state.direction) { reset_dash_effect(); } state.direction = direction; } void character::clean_projectiles() { while (!projectile_list.empty()) { projectile_list.at(0).finish(); projectile_list.erase(projectile_list.begin()); } if (is_player() && freeze_weapon_effect == FREEZE_EFFECT_NPC) { freeze_weapon_effect = FREEZE_EFFECT_NONE; } } void character::clean_effect_projectiles() { while (true) { bool found_item = false; for (unsigned int i=0; i<projectile_list.size(); i++) { Uint8 move_type = projectile_list.at(i).get_move_type(); if (move_type == TRAJECTORY_QUAKE || move_type == TRAJECTORY_FREEZE || move_type == TRAJECTORY_CENTERED || move_type == TRAJECTORY_PUSH_BACK || move_type == TRAJECTORY_PULL) { found_item = true; projectile_list.at(i).finish(); projectile_list.erase(projectile_list.begin()+i); break; } } if (found_item == false) { return; } } } void character::damage(unsigned int damage_points, bool ignore_hit_timer = false) { UNUSED(ignore_hit_timer); if (is_player() && GAME_FLAGS[FLAG_INVENCIBLE] == true) { return; } if (game_save.difficulty == DIFFICULTY_HARD && is_player() == false) { damage_points = damage_points * 0.5; } if (damage_points < 1) { // minimum damage is 1. if you don't want damage, don't call this method, ok? :) damage_points = 1; } if (damage_points + _damage_modifier > 0) { damage_points += _damage_modifier; } if (hitPoints.current <= 0) { // already dead return; } if (state.frozen == true && is_player()) { state.frozen_timer = 0; state.frozen = false; } unsigned int now_timer = timer.getTimer(); if (now_timer < hit_duration+last_hit_time) { // is still intangible from last hit return; } _was_hit = true; if (is_in_stairs_frame() == true) { _dropped_from_stairs = true; } last_hit_time = now_timer; if (now_timer > hit_duration+last_hit_time) { hit_animation_timer = now_timer+HIT_BLINK_ANIMATION_LAPSE; } if (!is_player() || GAME_FLAGS[FLAG_INFINITE_HP] == false) { hitPoints.current -= damage_points; } if (is_player() == true && state.animation_type != ANIM_TYPE_HIT) { soundManager.play_sfx(SFX_PLAYER_HIT); set_animation_type(ANIM_TYPE_HIT); if (_obj_jump.is_started() == true) { hit_moved_back_n = get_hit_push_back_n()/2; _obj_jump.finish(); } else { hit_moved_back_n = 0; } jump_button_released = false; if (gameControl.get_current_map_obj() != NULL) { int hit_anim_x = 0; if (state.direction == ANIM_DIRECTION_LEFT) { hit_anim_x = 3; } } } // TODO: add hit animation if (hitPoints.current <= 0) { hitPoints.current = 0; death(); } } void character::damage_spikes(bool ignore_hit_timer) { character::damage(SPIKES_DAMAGE); } bool character::is_dead() const { return (hitPoints.current <= 0); } st_hit_points character::get_hp() const { return hitPoints; } Uint8 character::get_current_hp() const { return hitPoints.current; } void character::set_current_hp(Uint8 inc) { hitPoints.current += inc; } st_position character::get_real_position() const { return realPosition; } void character::execute_jump_up() { // fall until reaching ground /// @TODO for (int i=0; i<100; i++) { char_update_real_position(); gravity(); gameControl.get_current_map_obj()->show_map(); show(); gameControl.get_current_map_obj()->showAbove(0); draw_lib.update_screen(); } // reset command jump, if any jump(0, gameControl.get_current_map_obj()->getMapScrolling()); jump(1, gameControl.get_current_map_obj()->getMapScrolling()); while (_obj_jump.get_speed() < 0) { input.read_input(); char_update_real_position(); jump(1, gameControl.get_current_map_obj()->getMapScrolling()); gameControl.get_current_map_obj()->show_map(); show(); gameControl.get_current_map_obj()->showAbove(); draw_lib.update_screen(); timer.delay(20); } _obj_jump.interrupt(); } bool character::is_jumping() { return _obj_jump.is_started(); } void character::interrupt_jump() { _obj_jump.interrupt(); _obj_jump.finish(); set_animation_type(ANIM_TYPE_STAND); } void character::execute_jump() { // fall until reaching ground fall(); // reset command jump, if any jump(0, gameControl.get_current_map_obj()->getMapScrolling()); int initial_y = (int)position.y; jump(1, gameControl.get_current_map_obj()->getMapScrolling()); while (position.y != initial_y) { input.read_input(); char_update_real_position(); bool resJump = jump(1, gameControl.get_current_map_obj()->getMapScrolling()); if (resJump == false) { gravity(); } gameControl.get_current_map_obj()->show_map(); show(); gameControl.get_current_map_obj()->showAbove(); draw_lib.update_screen(); timer.delay(20); } } void character::fall() { if (name == "OCTOPUS TENTACLE") { std::cout << "######## OCTOPUS TENTACLE::fall #1" << std::endl; } _obj_jump.finish(); // already on the ground if (hit_ground() == true) { set_animation_type(ANIM_TYPE_STAND); return; } for (int i=0; i<RES_H; i++) { char_update_real_position(); gravity(false); if (hit_ground() == true && state.animation_type == ANIM_TYPE_STAND) { gameControl.get_current_map_obj()->show_map(); show(); gameControl.get_current_map_obj()->showAbove(); draw_lib.update_screen(); return; } gameControl.get_current_map_obj()->show_map(); show(); gameControl.get_current_map_obj()->showAbove(); draw_lib.update_screen(); timer.delay(10); } } // @TODO: find first ground from bottom, that have space for player (2 tiles above are free), check 2 tiles on the x-axis also void character::fall_to_ground() { if (name == "OCTOPUS TENTACLE") { std::cout << "######## OCTOPUS TENTACLE::fall_to_ground #1" << std::endl; } _obj_jump.finish(); if (hit_ground() == true) { return; } for (int i=0; i<RES_H; i++) { char_update_real_position(); position.y++; if (position.y >= RES_H/2 && hit_ground() == true) { return; } } } void character::initialize_boss_position_to_ground() { if (can_fly == true) { return; } // RES_H is a good enough limit for (int i=0; i<RES_H; i++) { char_update_real_position(); gravity(false); if (hit_ground() == true) { break; } } } bool character::change_position(short xinc, short yinc) { st_map_collision map_col = map_collision(xinc, yinc, gameControl.get_current_map_obj()->getMapScrolling()); short int mapLock = map_col.block; int type = -1; if (_platform != nullptr) { type = _platform->get_type(); } bool is_on_fly_obj = (yinc > 0 && type == OBJ_ITEM_FLY); if (mapLock != BLOCK_UNBLOCKED && mapLock != BLOCK_WATER && is_on_fly_obj == false) { return false; } int py_before = position.y; position.x += xinc; position.y += yinc; //std::cout << "CHAR::change_position - TRUE, yinc[" << yinc << "], py_before[" << py_before << "], py_after[" <<position.y << "]" << std::endl; return true; } void character::change_position_x(short xinc) { if (xinc == 0) { // nothing todo return; } for (int i=xinc; i>=0.1; i--) { if (state.animation_type == ANIM_TYPE_HIT && hit_ground() == true) { hit_moved_back_n += xinc; } st_map_collision map_col = map_collision(i, 0, gameControl.get_current_map_obj()->getMapScrolling()); int mapLock = map_col.block; //mapLock = gameControl.getMapPointLock(st_position((position.x + frameSize.width + i)/TILESIZE, (position.y + frameSize.height/2)/TILESIZE)); if (mapLock == BLOCK_UNBLOCKED || mapLock == BLOCK_WATER || mapLock == BLOCK_Y) { if (mapLock == TERRAIN_UNBLOCKED || (mapLock == BLOCK_WATER && abs((float)i*WATER_SPEED_MULT) < 1) || mapLock == BLOCK_Y) { position.x += i - gameControl.get_current_map_obj()->get_last_scrolled().x; } else { position.x += i*WATER_SPEED_MULT - gameControl.get_current_map_obj()->get_last_scrolled().x; } if (state.animation_type != ANIM_TYPE_HIT) { set_direction(ANIM_DIRECTION_RIGHT); } else { gravity(false); return; } if (state.animation_type != ANIM_TYPE_WALK && state.animation_type != ANIM_TYPE_WALK_ATTACK) { state.animation_timer = 0; } if (state.animation_type != ANIM_TYPE_WALK && state.animation_type != ANIM_TYPE_JUMP && state.animation_type != ANIM_TYPE_SLIDE && state.animation_type != ANIM_TYPE_JUMP_ATTACK && state.animation_type != ANIM_TYPE_HIT && (state.animation_type != ANIM_TYPE_WALK_ATTACK || (state.animation_type == ANIM_TYPE_WALK_ATTACK && state.attack_timer+ATTACK_DELAY < timer.getTimer()))) { set_animation_type(ANIM_TYPE_WALK); } position.x += xinc; break; } } } int character::change_position_y(short yinc) { if (yinc == 0) { // nothing todo return 0; } if (test_change_position(0, yinc)) { // can move max return yinc; } else { // check decrementing xinc if (yinc > 0) { for (int i=yinc; i>0; i--) { if (test_change_position(0, i)) { return i; } } } else { for (int i=yinc; i<0; i++) { if (test_change_position(0, i)) { return i; } } } } return 0; } bool character::test_change_position(short xinc, short yinc) { if (gameControl.get_current_map_obj() == NULL) { return false; } if (yinc < 0 && position.y < 0) { return false; } if (yinc > 0 && position.y > RES_H) { return true; } if (xinc < 0 && position.x <= 0) { return false; } if (xinc > 0 && (realPosition.x - frameSize.width) > RES_W) { return false; } if (is_ghost == false) { st_map_collision map_col = map_collision(xinc, yinc, gameControl.get_current_map_obj()->getMapScrolling()); short int mapLock = map_col.block; if (mapLock != BLOCK_UNBLOCKED && mapLock != BLOCK_WATER) { if (mapLock == BLOCK_X && xinc != 0) { return false; } else if (mapLock == BLOCK_Y && yinc != 0) { return false; } else if (mapLock == BLOCK_XY) { return false; } } } // check wall-locks int map_x_point = (position.x+xinc); bool map_wall = gameControl.get_current_map_obj()->get_map_point_wall_lock(map_x_point); if (map_wall == true) { return false; } return true; } bool character::is_shielded(int projectile_direction) const { if (is_player()) { if (input.p1_input[BTN_SHIELD] == 1 && state.animation_type == ANIM_TYPE_SHIELD) { // player is on SHIELD animation and is keeping the shield button pressed if (shield_type == SHIELD_FULL || shield_type == SHIELD_FRONT) { // player can use shield return true; } } return false; } else { //std::cout << "NPC[" << name << "], shield_type[" << shield_type << "], SHIELD_BACK[" << (int)SHIELD_BACK << "], anim-type[" << state.animation_type << "], ANIM_TYPE_SHIELD[" << ANIM_TYPE_SHIELD << "]" << std::endl; if (shield_type == SHIELD_FULL || (shield_type == SHIELD_FRONT && projectile_direction != state.direction && (state.animation_type == ANIM_TYPE_STAND || state.animation_type == ANIM_TYPE_WALK || state.animation_type == ANIM_TYPE_WALK_AIR)) || (shield_type == SHIELD_STAND && state.animation_type == ANIM_TYPE_STAND)) { return true; } if (shield_type == SHIELD_STAND_AND_WALK && projectile_direction != state.direction && (state.animation_type == ANIM_TYPE_STAND || state.animation_type == ANIM_TYPE_WALK)) { return true; } if (shield_type == SHIELD_STAND_FRONT && projectile_direction != state.direction && state.animation_type == ANIM_TYPE_STAND) { return true; } if (shield_type == SHIELD_BACK && projectile_direction == state.direction) { return true; } if (shield_type == SHIELD_USING_SHIELD && state.animation_type == ANIM_TYPE_SHIELD) { return true; } return false; } } bool character::is_intangible() { if (is_player()) { return false; } if (state.animation_type == ANIM_TYPE_STAND && shield_type == SHIELD_DISGUISE) { return true; } if (timer.getTimer() < hit_duration+last_hit_time) { // is still intangible from last hit return true; } return false; } short character::get_anim_type() const { return state.animation_type; } graphicsLib_gSurface *character::get_char_frame(int direction, int type, int frame) { if (graphLib.character_graphics_list.find(name) == graphLib.character_graphics_list.end()) { return NULL; } else { return &(graphLib.character_graphics_list.find(name)->second).frames[direction][type][frame].frameSurface; } } st_color character::get_color_key(short key_n) const { return color_keys[key_n]; } short character::get_number() const { return _number; } bool character::is_using_circle_weapon() { if (projectile_list.size() == 1) { if (projectile_list.at(0).get_move_type() == TRAJECTORY_CENTERED) { return true; } } return false; } void character::inc_effect_weapon_status() { if (projectile_list.size() == 1) { int move_type = projectile_list.at(0).get_move_type() ; if (move_type == TRAJECTORY_CENTERED || move_type == TRAJECTORY_BOMB) { projectile_list.at(0).inc_status(); } } } void character::set_animation_type(ANIM_TYPE type) { // if is hit, finish jumping if (state.animation_type != type && type == ANIM_TYPE_HIT) { _obj_jump.finish(); } if (type != state.animation_type) { state.animation_state = 0; if (is_in_stairs_frame() && type == ANIM_TYPE_HIT) { if (state.direction == ANIM_DIRECTION_RIGHT) { position.x += 2; } } state.animation_type = type; _was_animation_reset = false; // avoids slides starting inside wall or object if (type == ANIM_TYPE_SLIDE) { if (state.direction == ANIM_DIRECTION_LEFT) { position.x += 6; } else { position.x -= 6; } } } int frame_delay = 20; if (graphLib.character_graphics_list.find(name) != graphLib.character_graphics_list.end()) { if (state.direction >= CHAR_ANIM_DIRECTION_COUNT) { set_direction(0); } if (state.animation_type >= ANIM_TYPE_COUNT) { set_animation_type(ANIM_TYPE_STAND); } if (state.animation_state >= ANIM_FRAMES_COUNT) { state.animation_state = 0; } frame_delay = (graphLib.character_graphics_list.find(name)->second).frames[state.direction][state.animation_type][state.animation_state].delay; } state.animation_timer = timer.getTimer() + frame_delay; animation_obj.set_type(static_cast<ANIM_TYPE>(state.animation_type)); } void character::set_animation_frame(unsigned int frame) { state.animation_state = frame; } void character::set_progressive_appear_pos(int pos) { _progressive_appear_pos = pos; } bool character::is_stage_boss() { return _is_stage_boss; } bool character::is_final_game_boss() { return _is_final_game_boss; } bool character::is_weak_to_freeze() { if (freeze_weapon_id == -1) { return false; } int wpn_id = -1; for (int i=0; i<MAX_WEAPON_N; i++) { if (game_data.weapons[i].id_projectile == freeze_weapon_id) { wpn_id = i; } } if (wpn_id == -1) { return false; } if (GameMediator::get_instance()->get_enemy(_number)->weakness[wpn_id].damage_multiplier == 0) { return false; } return true; } bool character::can_air_dash() { return false; } void character::cancel_slide() { state.slide_distance = 999; if (state.animation_type == ANIM_TYPE_SLIDE) { if (hit_ground() == true) { set_animation_type(ANIM_TYPE_STAND); } else { set_animation_type(ANIM_TYPE_JUMP); } } } float character::get_hit_push_back_n() { //return TILESIZE*0.8; return TILESIZE * 1.2; } bool character::have_shoryuken() { return false; } int character::get_armor_arms_attack_id() { return -1; }
411
0.927039
1
0.927039
game-dev
MEDIA
0.914368
game-dev
0.974574
1
0.974574
Rinnegatamante/vitaRTCW
19,115
code/cgame/cg_scoreboard.c
/* =========================================================================== Return to Castle Wolfenstein single player GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Return to Castle Wolfenstein single player GPL Source Code (“RTCW SP Source Code”). RTCW SP Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. RTCW SP Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ // cg_scoreboard -- draw the scoreboard on top of the game screen #include "cg_local.h" #define SCOREBOARD_WIDTH ( 31 * BIGCHAR_WIDTH ) /* ================= CG_DrawScoreboard ================= */ static void CG_DrawClientScore( int x, int y, score_t *score, float *color, float fade ) { char string[1024]; vec3_t headAngles; clientInfo_t *ci; if ( score->client < 0 || score->client >= cgs.maxclients ) { Com_Printf( "Bad score->client: %i\n", score->client ); return; } ci = &cgs.clientinfo[score->client]; // draw the handicap or bot skill marker if ( ci->botSkill > 0 && ci->botSkill <= 5 ) { CG_DrawPic( 0, y - 8, 32, 32, cgs.media.botSkillShaders[ ci->botSkill - 1 ] ); } else if ( ci->handicap < 100 ) { snprintf( string, sizeof( string ), "%i", ci->handicap ); CG_DrawSmallStringColor( 8, y, string, color ); } // draw the wins / losses if ( cgs.gametype == GT_TOURNAMENT ) { snprintf( string, sizeof( string ), "%i/%i", ci->wins, ci->losses ); CG_DrawSmallStringColor( x + SCOREBOARD_WIDTH + 2, y, string, color ); } // draw the face VectorClear( headAngles ); headAngles[YAW] = 180; CG_DrawHead( x - ICON_SIZE, y - ( ICON_SIZE - BIGCHAR_HEIGHT ) / 2, ICON_SIZE, ICON_SIZE, score->client, headAngles ); if ( ci->powerups & ( 1 << PW_REDFLAG ) ) { CG_DrawFlagModel( x - ICON_SIZE - ICON_SIZE / 2, y - ( ICON_SIZE - BIGCHAR_HEIGHT ) / 2, ICON_SIZE, ICON_SIZE, TEAM_RED ); } else if ( ci->powerups & ( 1 << PW_BLUEFLAG ) ) { CG_DrawFlagModel( x - ICON_SIZE - ICON_SIZE / 2, y - ( ICON_SIZE - BIGCHAR_HEIGHT ) / 2, ICON_SIZE, ICON_SIZE, TEAM_BLUE ); } // draw the score line if ( score->ping == -1 ) { snprintf( string, sizeof( string ), "connecting %s", ci->name ); } else if ( ci->team == TEAM_SPECTATOR ) { snprintf( string, sizeof( string ), "SPECT %4i %4i %s", score->ping, score->time, ci->name ); } else { snprintf( string, sizeof( string ), "%5i %4i %4i %s", score->score, score->ping, score->time, ci->name ); } // highlight your position if ( score->client == cg.snap->ps.clientNum ) { float hcolor[4]; int rank; if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cgs.gametype >= GT_TEAM ) { rank = -1; } else { rank = cg.snap->ps.persistant[PERS_RANK] & ~RANK_TIED_FLAG; } if ( rank == 0 ) { hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7; } else if ( rank == 1 ) { hcolor[0] = 0.7; hcolor[1] = 0; hcolor[2] = 0; } else if ( rank == 2 ) { hcolor[0] = 0.7; hcolor[1] = 0.7; hcolor[2] = 0; } else { hcolor[0] = 0.7; hcolor[1] = 0.7; hcolor[2] = 0.7; } hcolor[3] = fade * 0.7; CG_FillRect( x - 2, y, SCOREBOARD_WIDTH, BIGCHAR_HEIGHT + 1, hcolor ); } CG_DrawBigString( x, y, string, fade ); // add the "ready" marker for intermission exiting if ( cg.snap->ps.stats[ STAT_CLIENTS_READY ] & ( 1 << score->client ) ) { CG_DrawBigStringColor( 0, y, "READY", color ); } } /* ================= CG_TeamScoreboard ================= */ static int CG_TeamScoreboard( int x, int y, team_t team, float fade ) { int i; score_t *score; float color[4]; int count; int lineHeight; clientInfo_t *ci; color[0] = color[1] = color[2] = 1.0; color[3] = fade; count = 0; lineHeight = 40; // don't draw more than 9 rows for ( i = 0 ; i < cg.numScores && count < 9 ; i++ ) { score = &cg.scores[i]; ci = &cgs.clientinfo[ score->client ]; if ( team != ci->team ) { continue; } CG_DrawClientScore( x, y + lineHeight * count, score, color, fade ); count++; } return y + count * lineHeight + 20; } /* ================= WM_DrawClientScore ================= */ static int INFO_PLAYER_WIDTH = 300; static int INFO_SCORE_WIDTH = 50; static int INFO_LATENCY_WIDTH = 80; static int INFO_TEAM_HEIGHT = 24; static int INFO_BORDER = 2; static void WM_DrawClientScore( int x, int y, score_t *score, float *color, float fade ) { float tempx; vec4_t hcolor; clientInfo_t *ci; if ( y + SMALLCHAR_HEIGHT >= 440 ) { return; } if ( score->client == cg.snap->ps.clientNum ) { tempx = x; hcolor[3] = fade * 0.3; VectorSet( hcolor, 0.4452, 0.1172, 0.0782 ); // DARK-RED CG_FillRect( tempx, y + 1, INFO_PLAYER_WIDTH - INFO_BORDER, SMALLCHAR_HEIGHT - 1, hcolor ); tempx += INFO_PLAYER_WIDTH; CG_FillRect( tempx, y + 1, INFO_SCORE_WIDTH - INFO_BORDER, SMALLCHAR_HEIGHT - 1, hcolor ); tempx += INFO_SCORE_WIDTH; CG_FillRect( tempx, y + 1, INFO_LATENCY_WIDTH - INFO_BORDER, SMALLCHAR_HEIGHT - 1, hcolor ); } tempx = x; ci = &cgs.clientinfo[score->client]; CG_DrawSmallString( tempx, y, ci->name, fade ); tempx += INFO_PLAYER_WIDTH; CG_DrawSmallString( tempx, y, va( "%4i", score->score ), fade ); tempx += INFO_SCORE_WIDTH; CG_DrawSmallString( tempx, y, va( "%4i", score->ping ), fade ); } /* ================= WM_TeamScoreboard ================= */ static int WM_TeamScoreboard( int x, int y, team_t team, float fade ) { vec4_t hcolor; float tempx; int i; hcolor[3] = fade; if ( team == TEAM_RED ) { VectorSet( hcolor, 0.4452, 0.1172, 0.0782 ); // LIGHT-RED } else if ( team == TEAM_BLUE ) { VectorSet( hcolor, 0.1836, 0.2422, 0.1680 ); // LIGHT-GREEN } else { VectorSet( hcolor, 0.2, 0.2, 0.2 ); // DARK-GREY } // dont draw spectator if there are none for ( i = 0; i < cg.numScores; i++ ) { if ( team == cgs.clientinfo[ cg.scores[i].client ].team ) { break; } } if ( team == TEAM_SPECTATOR && i == cg.numScores ) { return y; } // draw team header if ( y + SMALLCHAR_HEIGHT >= 440 ) { return y; } tempx = x; CG_FillRect( tempx, y, INFO_PLAYER_WIDTH - INFO_BORDER, INFO_TEAM_HEIGHT, hcolor ); if ( team == TEAM_RED ) { CG_DrawSmallString( tempx, y, "Axis", fade ); } else if ( team == TEAM_BLUE ) { CG_DrawSmallString( tempx, y, "Allies", fade ); } else { CG_DrawSmallString( tempx, y, "Spectators", fade ); } tempx += INFO_PLAYER_WIDTH; CG_FillRect( tempx, y, INFO_SCORE_WIDTH - INFO_BORDER, INFO_TEAM_HEIGHT, hcolor ); tempx += INFO_SCORE_WIDTH; CG_FillRect( tempx, y, INFO_LATENCY_WIDTH - INFO_BORDER, INFO_TEAM_HEIGHT, hcolor ); // draw player info VectorSet( hcolor, 1, 1, 1 ); hcolor[3] = fade; y += INFO_TEAM_HEIGHT + INFO_BORDER; for ( i = 0; i < cg.numScores; i++ ) { if ( team != cgs.clientinfo[ cg.scores[i].client ].team ) { continue; } WM_DrawClientScore( x, y, &cg.scores[i], hcolor, fade ); y += SMALLCHAR_HEIGHT; } y += 4; return y; } /* ================= WM_DrawObjectives ================= */ int WM_DrawObjectives( int x, int y, int width, float fade ) { const char *s, *buf, *str; char teamstr[32]; int i, num, strwidth, status; y += 32; // determine character's team if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED ) { strcpy( teamstr, "axis_desc" ); } else { strcpy( teamstr, "allied_desc" ); } s = CG_ConfigString( CS_MULTI_INFO ); buf = Info_ValueForKey( s, "numobjectives" ); if ( buf && atoi( buf ) ) { num = atoi( buf ); for ( i = 0; i < num; i++ ) { s = CG_ConfigString( CS_MULTI_OBJECTIVE1 + i ); buf = Info_ValueForKey( s, teamstr ); // draw text str = va( "%s", buf ); strwidth = CG_DrawStrlen( str ) * SMALLCHAR_WIDTH; CG_DrawSmallString( x + width / 2 - strwidth / 2 - 12, y, str, fade ); // draw status flags status = atoi( Info_ValueForKey( s, "status" ) ); if ( status == 0 ) { CG_DrawPic( x + width / 2 - strwidth / 2 - 16 - 24, y, 24, 16, trap_R_RegisterShaderNoMip( "ui/assets/ger_flag.tga" ) ); CG_DrawPic( x + width / 2 + strwidth / 2 - 12 + 4, y, 24, 16, trap_R_RegisterShaderNoMip( "ui/assets/ger_flag.tga" ) ); } else if ( status == 1 ) { CG_DrawPic( x + width / 2 - strwidth / 2 - 16 - 24, y, 24, 16, trap_R_RegisterShaderNoMip( "ui/assets/usa_flag.tga" ) ); CG_DrawPic( x + width / 2 + strwidth / 2 - 12 + 4, y, 24, 16, trap_R_RegisterShaderNoMip( "ui/assets/usa_flag.tga" ) ); } y += 16; } } return y; } /* ================= WM_ScoreboardOverlay ================= */ int WM_ScoreboardOverlay( int x, int y, float fade ) { vec4_t hcolor; int width; char *s; // JPW NERVE int msec, mins, seconds, tens; // JPW NERVE width = INFO_PLAYER_WIDTH + INFO_LATENCY_WIDTH + INFO_SCORE_WIDTH + 25; VectorSet( hcolor, 0, 0, 0 ); hcolor[3] = 0.7 * fade; // draw background CG_FillRect( x - 12, y, width, 400, hcolor ); // draw title frame VectorSet( hcolor, 0.0039, 0.0039, 0.2461 ); hcolor[3] = 1 * fade; CG_FillRect( x - 12, y, width, 30, hcolor ); CG_DrawRect( x - 12, y, width, 400, 2, hcolor ); if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { const char *s, *buf; s = CG_ConfigString( CS_MULTI_INFO ); buf = Info_ValueForKey( s, "winner" ); if ( atoi( buf ) ) { CG_DrawSmallString( x - 12 + 5, y, "ALLIES WIN!", fade ); } else { CG_DrawSmallString( x - 12 + 5, y, "AXIS WIN!", fade ); } } // JPW NERVE -- mission time & reinforce time else { msec = ( cgs.timelimit * 60.f * 1000.f ) - ( cg.time - cgs.levelStartTime ); seconds = msec / 1000; mins = seconds / 60; seconds -= mins * 60; tens = seconds / 10; seconds -= tens * 10; s = va( "Mission time: %2.0f:%i%i", (float)mins, tens, seconds ); // float cast to line up with reinforce time CG_DrawSmallString( x - 7,y,s,fade ); if ( cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_RED ) { msec = cg_redlimbotime.integer - ( cg.time % cg_redlimbotime.integer ); } else if ( cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_BLUE ) { msec = cg_bluelimbotime.integer - ( cg.time % cg_bluelimbotime.integer ); } else { // no team (spectator mode) msec = 0; } if ( msec ) { seconds = msec / 1000; mins = seconds / 60; seconds -= mins * 60; tens = seconds / 10; seconds -= tens * 10; s = va( "Reinforce time: %2.0f:%i%i", (float)mins, tens, seconds ); CG_DrawSmallString( x - 7,y + 16,s,fade ); } } // jpw // CG_DrawSmallString( x - 12 + 5, y, "Wolfenstein Multiplayer", fade ); // old one y = WM_DrawObjectives( x, y, width, fade ); y += 5; // draw field names CG_DrawSmallString( x, y, "Players", fade ); x += INFO_PLAYER_WIDTH; CG_DrawSmallString( x, y, "Score", fade ); x += INFO_SCORE_WIDTH; CG_DrawSmallString( x, y, "Latency", fade ); y += 20; return y; } // -NERVE - SMF /* ================= CG_DrawScoreboard Draw the normal in-game scoreboard ================= */ qboolean CG_DrawScoreboard( void ) { int x = 0, y = 0, w; float fade; float *fadeColor; char *s; // don't draw anything if the menu or console is up if ( cg_paused.integer ) { cg.deferredPlayerLoading = 0; return qfalse; } // still need to see 'mission failed' message in SP if ( cgs.gametype == GT_SINGLE_PLAYER && cg.predictedPlayerState.pm_type == PM_DEAD ) { return qfalse; } if ( cgs.gametype == GT_SINGLE_PLAYER && cg.predictedPlayerState.pm_type == PM_INTERMISSION ) { cg.deferredPlayerLoading = 0; return qfalse; } // don't draw scoreboard during death while warmup up if ( cg.warmup && !cg.showScores ) { return qfalse; } if ( cg_fixedAspect.integer ) { CG_SetScreenPlacement(PLACE_CENTER, PLACE_CENTER); } if ( cg.showScores || cg.predictedPlayerState.pm_type == PM_DEAD || cg.predictedPlayerState.pm_type == PM_INTERMISSION ) { fade = 1.0; } else { fadeColor = CG_FadeColor( cg.scoreFadeTime, FADE_TIME ); if ( !fadeColor ) { // next time scoreboard comes up, don't print killer cg.deferredPlayerLoading = 0; cg.killerName[0] = 0; return qfalse; } fade = *fadeColor; } // fragged by ... line if ( cg.killerName[0] ) { s = va( "Killed by %s", cg.killerName ); w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; x = ( SCREEN_WIDTH - w ) / 2; y = 40; CG_DrawBigString( x, y, s, fade ); } // current rank //----(SA) enclosed this so it doesn't draw for SP if ( cgs.gametype != GT_SINGLE_PLAYER && cgs.gametype != GT_WOLF ) { // NERVE - SMF - added wolf multiplayer check if ( cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR ) { if ( cgs.gametype < GT_TEAM ) { s = va( "%s place with %i", CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ), cg.snap->ps.persistant[PERS_SCORE] ); w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; x = ( SCREEN_WIDTH - w ) / 2; y = 60; CG_DrawBigString( x, y, s, fade ); } else { if ( cg.teamScores[0] == cg.teamScores[1] ) { s = va( "Teams are tied at %i", cg.teamScores[0] ); } else if ( cg.teamScores[0] >= cg.teamScores[1] ) { s = va( "Red leads %i to %i",cg.teamScores[0], cg.teamScores[1] ); } else { s = va( "Blue leads %i to %i",cg.teamScores[1], cg.teamScores[0] ); } w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; x = ( SCREEN_WIDTH - w ) / 2; y = 60; CG_DrawBigString( x, y, s, fade ); } } // scoreboard x = 320 - SCOREBOARD_WIDTH / 2; y = 86; #if 0 CG_DrawBigStringColor( x, y, "SCORE PING TIME NAME", fadeColor ); CG_DrawBigStringColor( x, y + 12, "----- ---- ---- ---------------", fadeColor ); #endif CG_DrawPic( x + 1 * 16, y, 64, 32, cgs.media.scoreboardScore ); CG_DrawPic( x + 6 * 16 + 8, y, 64, 32, cgs.media.scoreboardPing ); CG_DrawPic( x + 11 * 16 + 8, y, 64, 32, cgs.media.scoreboardTime ); CG_DrawPic( x + 16 * 16, y, 64, 32, cgs.media.scoreboardName ); y += 32; } // NERVE - SMF if ( cgs.gametype == GT_WOLF ) { // // teamplay scoreboard // x = 320 - SCOREBOARD_WIDTH / 2 + 20 + 20; y = 40; y = WM_ScoreboardOverlay( x, y, fade ); if ( cg.teamScores[0] >= cg.teamScores[1] ) { y = WM_TeamScoreboard( x, y, TEAM_RED, fade ); y = WM_TeamScoreboard( x, y, TEAM_BLUE, fade ); } else { y = WM_TeamScoreboard( x, y, TEAM_BLUE, fade ); y = WM_TeamScoreboard( x, y, TEAM_RED, fade ); } WM_TeamScoreboard( x, y, TEAM_SPECTATOR, fade ); } // -NERVE - SMF else if ( cgs.gametype >= GT_TEAM ) { // // teamplay scoreboard // if ( cg.teamScores[0] >= cg.teamScores[1] ) { y = CG_TeamScoreboard( x, y, TEAM_RED, fade ); y = CG_TeamScoreboard( x, y, TEAM_BLUE, fade ); } else { y = CG_TeamScoreboard( x, y, TEAM_BLUE, fade ); y = CG_TeamScoreboard( x, y, TEAM_RED, fade ); } CG_TeamScoreboard( x, y, TEAM_SPECTATOR, fade ); } else if ( cgs.gametype != GT_SINGLE_PLAYER ) { //----(SA) modified // // free for all scoreboard // y = CG_TeamScoreboard( x, y, TEAM_FREE, fade ); CG_TeamScoreboard( x, y, TEAM_SPECTATOR, fade ); } // load any models that have been deferred if ( ++cg.deferredPlayerLoading > 1 ) { CG_LoadDeferredPlayers(); } return qtrue; } //================================================================================ /* ================ CG_CenterGiantLine ================ */ static void CG_CenterGiantLine( float y, const char *string ) { float x; vec4_t color; color[0] = 1; color[1] = 1; color[2] = 1; color[3] = 1; x = 0.5 * ( 640 - GIANT_WIDTH * CG_DrawStrlen( string ) ); CG_DrawStringExt( x, y, string, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 ); } /* ================= CG_DrawTourneyScoreboard Draw the oversize scoreboard for tournements ================= */ void CG_DrawTourneyScoreboard( void ) { const char *s; vec4_t color; int min, tens, ones; clientInfo_t *ci; int y; int i; if ( cg_fixedAspect.integer ) { CG_SetScreenPlacement(PLACE_CENTER, PLACE_CENTER); } // request more scores regularly if ( cg.scoresRequestTime + 2000 < cg.time ) { cg.scoresRequestTime = cg.time; trap_SendClientCommand( "score" ); } // draw the dialog background if ( cg_fixedAspect.integer ) { color[0] = color[1] = color[2] = 0; color[3] = 1; CG_SetScreenPlacement(PLACE_STRETCH, PLACE_STRETCH); CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, color ); CG_SetScreenPlacement(PLACE_CENTER, PLACE_CENTER); } else { color[0] = color[1] = color[2] = 0; color[3] = 1; CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, color ); } color[0] = 1; color[1] = 1; color[2] = 1; color[3] = 1; // print the mesage of the day s = CG_ConfigString( CS_MOTD ); if ( !s[0] ) { s = "Scoreboard"; } // print optional title CG_CenterGiantLine( 8, s ); // print server time ones = cg.time / 1000; min = ones / 60; ones %= 60; tens = ones / 10; ones %= 10; s = va( "%i:%i%i", min, tens, ones ); CG_CenterGiantLine( 64, s ); // print the two scores y = 160; if ( cgs.gametype >= GT_TEAM ) { // // teamplay scoreboard // CG_DrawStringExt( 8, y, "Red Team", color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 ); s = va( "%i", cg.teamScores[0] ); CG_DrawStringExt( 632 - GIANT_WIDTH * strlen( s ), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 ); y += 64; CG_DrawStringExt( 8, y, "Blue Team", color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 ); s = va( "%i", cg.teamScores[1] ); CG_DrawStringExt( 632 - GIANT_WIDTH * strlen( s ), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 ); } else { // // free for all scoreboard // for ( i = 0 ; i < MAX_CLIENTS ; i++ ) { ci = &cgs.clientinfo[i]; if ( !ci->infoValid ) { continue; } if ( ci->team != TEAM_FREE ) { continue; } CG_DrawStringExt( 8, y, ci->name, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 ); s = va( "%i", ci->score ); CG_DrawStringExt( 632 - GIANT_WIDTH * strlen( s ), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 ); y += 64; } } }
411
0.971139
1
0.971139
game-dev
MEDIA
0.39536
game-dev
0.933987
1
0.933987
MemoriesOfTime/Nukkit-MOT
1,376
src/main/java/cn/nukkit/command/tree/node/ChainedCommandNode.java
package cn.nukkit.command.tree.node; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringJoiner; /** * {@link cn.nukkit.command.defaults.ExecuteCommand ExecuteCommand}命令的链命令节点 */ public class ChainedCommandNode extends EnumNode { private static final HashSet<String> CHAINED = Sets.newHashSet("run", "as", "at", "positioned", "if", "unless", "in", "align", "anchored", "rotated", "facing"); private boolean remain = false; private final List<String> TMP = new ArrayList<>(); @Override public void fill(String arg) { if (arg.contains(" ")) { arg = "\"" + arg + "\""; } if (!remain) { if (!CHAINED.contains(arg)) { this.error(); return; } TMP.add(arg); remain = true; } else { if (this.paramList.getIndex() != this.paramList.getParamTree().getArgs().length) TMP.add(arg); else { TMP.add(arg); var join = new StringJoiner(" ", "execute ", ""); TMP.forEach(join::add); this.value = join.toString(); } } } @Override public void reset() { super.reset(); TMP.clear(); this.remain = false; } }
411
0.911654
1
0.911654
game-dev
MEDIA
0.245949
game-dev
0.961239
1
0.961239
LingASDJ/Magic_Ling_Pixel_Dungeon
1,917
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/trinkets/ThirteenLeafClover.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2024 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.trinkets; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.watabou.utils.Random; public class ThirteenLeafClover extends Trinket { { image = ItemSpriteSheet.CLOVER; } @Override protected int upgradeEnergyCost() { //6 -> 5(11) -> 7(18) -> 8(26) return Math.round(5+1.67f*level()); } @Override public String statsDesc() { if (isIdentified()){ return Messages.get(this, "stats_desc", (int)(100*combatDistributionInverseChance(buffedLvl()))); } else { return Messages.get(this, "typical_stats_desc", (int)(100*combatDistributionInverseChance(0))); } } public static float combatDistributionInverseChance(){ return combatDistributionInverseChance(trinketLevel(ThirteenLeafClover.class)); } public static float combatDistributionInverseChance( int level ){ if (level <= -1){ return 0; } else { return 0.25f + 0.25f*level; } } public static int invCombatRoll( int min, int max){ return Random.InvNormalIntRange( min, max ); } }
411
0.582795
1
0.582795
game-dev
MEDIA
0.98609
game-dev
0.75243
1
0.75243
Relfos/TERRA-Engine
1,530
Samples/Source/3D/Oculus/oculus.dpr
{$I terra.inc} {$IFDEF MOBILE}Library{$ELSE}Program{$ENDIF} MaterialDemo; uses // MemCheck, TERRA_MemoryManager, TERRA_DemoApplication, TERRA_OS, TERRA_Object, TERRA_Utils, TERRA_Viewport, TERRA_Vector3D, TERRA_Texture, TERRA_ScreenFX, TERRA_Mesh, TERRA_Engine, TERRA_InputManager; Type MyDemo = Class(DemoApplication) Public Procedure OnCreate; Override; Procedure OnDestroy; Override; Procedure OnIdle; Override; Procedure OnRender3D(V:TERRAViewport); Override; End; Var Solid:MeshInstance; DiffuseTex:TERRATexture; GlowTex:TERRATexture; { Game } Procedure MyDemo.OnCreate; Begin Inherited; Self.MainViewport.Visible := True; Self.MainViewport.VR := True; DiffuseTex := Engine.Textures.GetItem('cobble'); Solid := MeshInstance.Create(Engine.Meshes.CubeMesh); Solid.SetDiffuseMap(0, DiffuseTex); Solid.SetGlowMap(0, GlowTex); Solid.SetPosition(Vector3D_Create(0, 4, 0)); Solid.SetScale(Vector3D_Constant(2.0)); Self.Floor.SetPosition(Vector3D_Zero); End; Procedure MyDemo.OnDestroy; Begin ReleaseObject(Solid); Inherited; End; procedure MyDemo.OnIdle; begin inherited; If Engine.Input.Keys.WasPressed(keyEnter) Then Engine.Graphics.Renderer.GetScreenshot().Save('screenshot.jpg'); end; Procedure MyDemo.OnRender3D(V: TERRAViewport); Begin Engine.Graphics.AddRenderable(V, Solid); Inherited; End; {$IFDEF IPHONE} Procedure StartGame; cdecl; export; {$ENDIF} Begin MyDemo.Create(); {$IFDEF IPHONE} End; {$ENDIF} End.
411
0.671569
1
0.671569
game-dev
MEDIA
0.82763
game-dev,graphics-rendering
0.970372
1
0.970372
SeleDreams/godot-2-3ds
3,678
scene/resources/convex_polygon_shape.cpp
/*************************************************************************/ /* convex_polygon_shape.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "convex_polygon_shape.h" #include "quick_hull.h" #include "servers/physics_server.h" Vector<Vector3> ConvexPolygonShape::_gen_debug_mesh_lines() { DVector<Vector3> points = get_points(); if (points.size() > 3) { QuickHull qh; Vector<Vector3> varr = Variant(points); Geometry::MeshData md; Error err = qh.build(varr, md); if (err == OK) { Vector<Vector3> lines; lines.resize(md.edges.size() * 2); for (int i = 0; i < md.edges.size(); i++) { lines[i * 2 + 0] = md.vertices[md.edges[i].a]; lines[i * 2 + 1] = md.vertices[md.edges[i].b]; } return lines; } } return Vector<Vector3>(); } void ConvexPolygonShape::_update_shape() { PhysicsServer::get_singleton()->shape_set_data(get_shape(), points); emit_changed(); } void ConvexPolygonShape::set_points(const DVector<Vector3> &p_points) { points = p_points; _update_shape(); notify_change_to_owners(); } DVector<Vector3> ConvexPolygonShape::get_points() const { return points; } void ConvexPolygonShape::_bind_methods() { ObjectTypeDB::bind_method(_MD("set_points", "points"), &ConvexPolygonShape::set_points); ObjectTypeDB::bind_method(_MD("get_points"), &ConvexPolygonShape::get_points); ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "points"), _SCS("set_points"), _SCS("get_points")); } ConvexPolygonShape::ConvexPolygonShape() : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONVEX_POLYGON)) { //set_points(Vector3(1,1,1)); }
411
0.926055
1
0.926055
game-dev
MEDIA
0.43524
game-dev,graphics-rendering
0.678018
1
0.678018
Dimbreath/AzurLaneData
1,110
ja-JP/mod/battle/data/environment/battleenvironmentbehaviourplayfx.lua
ys = ys or {} slot0 = ys slot1 = slot0.Battle.BattleConst slot2 = slot0.Battle.BattleConfig slot3 = class("BattleEnvironmentBehaviourPlayFX", slot0.Battle.BattleEnvironmentBehaviour) slot0.Battle.BattleEnvironmentBehaviourPlayFX = slot3 slot3.__name = "BattleEnvironmentBehaviourPlayFX" function slot3.Ctor(slot0) uv0.super.Ctor(slot0) end function slot3.SetTemplate(slot0, slot1) uv0.super.SetTemplate(slot0, slot1) slot0._FXID = slot0._tmpData.FX_ID slot0._offset = slot0._tmpData.offset and Vector3(unpack(slot0._tmpData.offset)) or Vector3.zero end function slot3.doBehaviour(slot0) slot1 = 1 if slot0._tmpData.scaleRate then slot4 = nil if slot0._unit:GetAOEData():GetAreaType() == uv0.AreaType.CUBE then slot4 = slot2:GetWidth() elseif slot3 == uv0.AreaType.COLUMN then slot4 = slot2:GetRange() end slot1 = slot0._tmpData.scaleRate * slot4 elseif slot0._tmpData.scale then slot1 = slot0._tmpData.scale end uv1.Battle.BattleDataProxy.GetInstance():SpawnEffect(slot0._FXID, slot0._unit:GetAOEData():GetPosition() + slot0._offset, slot1) uv2.super.doBehaviour(slot0) end
411
0.607924
1
0.607924
game-dev
MEDIA
0.977564
game-dev
0.97075
1
0.97075
fallahn/crogine
3,222
android/BulletDroid/src/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_DISCRETE_COLLISION_DETECTOR1_INTERFACE_H #define BT_DISCRETE_COLLISION_DETECTOR1_INTERFACE_H #include "LinearMath/btTransform.h" #include "LinearMath/btVector3.h" /// This interface is made to be used by an iterative approach to do TimeOfImpact calculations /// This interface allows to query for closest points and penetration depth between two (convex) objects /// the closest point is on the second object (B), and the normal points from the surface on B towards A. /// distance is between closest points on B and closest point on A. So you can calculate closest point on A /// by taking closestPointInA = closestPointInB + m_distance * m_normalOnSurfaceB struct btDiscreteCollisionDetectorInterface { struct Result { virtual ~Result(){} ///setShapeIdentifiersA/B provides experimental support for per-triangle material / custom material combiner virtual void setShapeIdentifiersA(int partId0,int index0)=0; virtual void setShapeIdentifiersB(int partId1,int index1)=0; virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)=0; }; struct ClosestPointInput { ClosestPointInput() :m_maximumDistanceSquared(btScalar(BT_LARGE_FLOAT)) { } btTransform m_transformA; btTransform m_transformB; btScalar m_maximumDistanceSquared; }; virtual ~btDiscreteCollisionDetectorInterface() {}; // // give either closest points (distance > 0) or penetration (distance) // the normal always points from B towards A // virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false) = 0; }; struct btStorageResult : public btDiscreteCollisionDetectorInterface::Result { btVector3 m_normalOnSurfaceB; btVector3 m_closestPointInB; btScalar m_distance; //negative means penetration ! btStorageResult() : m_distance(btScalar(BT_LARGE_FLOAT)) { } virtual ~btStorageResult() {}; virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth) { if (depth < m_distance) { m_normalOnSurfaceB = normalOnBInWorld; m_closestPointInB = pointInWorld; m_distance = depth; } } }; #endif //BT_DISCRETE_COLLISION_DETECTOR1_INTERFACE_H
411
0.877226
1
0.877226
game-dev
MEDIA
0.964302
game-dev
0.895184
1
0.895184
Temtaime/aesir
3,665
source/rocl/status/package.d
module rocl.status; import std.array, std.typecons, std.algorithm, perfontain, rocl.controls, rocl.status.helpers; public import rocl.game, rocl.status.item, rocl.status.enums; final class Status { ~this() { items.clear; } auto skillOf(ushort id) { auto arr = skills.find!((a, b) => a.id == b)(id); return arr.empty ? null : arr.front; } ref param(ushort idx) { return *_params.require(idx, new Param!int); } // misc string map; // character Stat[RO_STAT_MAX] stats; //Bonus[RO_BONUS_MAX] bonuses; // skills Skill[] skills; Items items; // rest Param!uint hp, sp, maxHp, maxSp, bexp, jexp, bnextExp, jnextExp; Param!ushort blvl, jlvl; private: Param!int*[ushort] _params; } struct Items { void clear() { _arr = null; } // void add(ushort idx, ushort cnt, scope Item delegate() dg) // { // if (auto e = getIdx(idx)) // { // e.reamount(cast(ushort)(e.amount + cnt)); // } // else // { // if (dg) // add(dg()); // else // debug throwError!`item at index %u was not found, cannot add %u to the amount`(idx, cnt); // } // } void add(T)(in T data) { if (auto e = getIdx(data.idx)) { debug { throwError!`item at index %u is already exist`(data.idx); } _arr.remove(e); } add(new Item(data)); } void changeAmount(ushort idx, int cnt, bool isTotal = false, scope Item delegate() dg = null) { if (auto e = getIdx(idx)) { if (isTotal) { if (cnt) e.reamount(cast(ushort)cnt); else _arr.remove(e); } else { int amount = e.amount + cnt; debug { amount >= 0 || throwError!`item at index %u has amount %u, while new amount is %d`(idx, e.amount, amount); } if (amount > 0) e.reamount(cast(ushort)amount); else _arr.remove(e); } } else { if (dg) { add(dg()); } else debug throwError!`tried to process a non-existant item at index %u`(idx); } } auto getIdx(ushort idx) { auto r = get(a => a.idx == idx); assert(r.length < 2); return r.empty ? null : r.front; } auto get(scope bool delegate(Item) dg) { return arr.filter!dg .array .sort!((a, b) => a.idx < b.idx) .release; } inout arr() => _arr[]; Signal!(void, Item) onAdded; private: void add(Item m) { assert(getIdx(m.idx) is null); _arr ~= m; onAdded(m); } RCArray!Item _arr; } struct Param(T) { Signal!(void, T) onChange; mixin StatusValue!(T, `value`, onUpdate); private: void onUpdate() { onChange(_value); } } struct Stat { mixin StatusIndex!(`stats`); mixin StatusValue!(ubyte, `base`, onUpdate); mixin StatusValue!(ubyte, `bonus`, onUpdate); mixin StatusValue!(ubyte, `needs`, onUpdate); private: void onUpdate() { //RO.gui.status.stats.update(this); } } final class Skiller : RCounted { this(in Skill s, ubyte lvl) { _s = s; _lvl = lvl ? lvl : s.lvl; } ~this() { // if (_bg) // { // //_bg.deattach; // } } void use() { if (_s.type == INF_SELF_SKILL) { use(ROent.self.bl); } else { RO.action.use(this); //_bg = new TargetSelector; } } void use(Vector2s p) { ROnet.useSkill(_lvl, _s.id, p); } void use(uint bl) { ROnet.useSkill(_lvl, _s.id, bl); } @property ground() const { return _s.type == INF_GROUND_SKILL; } private: ubyte _lvl; const Skill _s; //GUIElement _bg; } final class Skill { mixin StatusIndex!(`skills`); ushort id; string name; ubyte type, range; mixin StatusValue!(ushort, `sp`, onUpdate); mixin StatusValue!(ubyte, `lvl`, onUpdate); mixin StatusValue!(bool, `upgradable`, onUpdate); private: void onUpdate() { //RO.gui.skills.update(this); } }
411
0.892381
1
0.892381
game-dev
MEDIA
0.783586
game-dev
0.94077
1
0.94077
freegish/freegish
22,869
src/game/game.c
/* Copyright (C) 2005, 2010 - Cryptic Sea This file is part of Gish. Gish is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "../config.h" #include "../video/opengl.h" #include "../sdl/sdl.h" #include <stdlib.h> #include <time.h> #include "../game/game.h" #include "../game/animation.h" #include "../game/gameaudio.h" #include "../game/boss.h" #include "../game/custom.h" #include "../game/editor.h" #include "../game/english.h" #include "../game/level.h" #include "../game/lighting.h" #include "../game/logic.h" #include "../game/mainmenu.h" #include "../game/music.h" #include "../game/gameobject.h" #include "../game/objfunc.h" #include "../game/options.h" #include "../game/physics.h" #include "../game/prerender.h" #include "../game/random.h" #include "../game/record.h" #include "../game/render.h" #include "../game/replay.h" #include "../game/setup.h" #include "../game/sprite.h" #include "../audio/audio.h" #include "../input/joystick.h" #include "../input/keyboard.h" #include "../input/mouse.h" #include "../math/vector.h" #include "../menu/menu.h" #include "../physics/bond.h" #include "../physics/particle.h" #include "../sdl/event.h" #include "../video/glfunc.h" #include "../video/text.h" #include "../video/texture.h" #include "../sdl/video.h" _view view; _game game; void gameloop(void) { int count,count2; unsigned int simtimer; int simcount; int frametimer,fps; //float vec[3]; //char filename[13]="text000.png"; int scorenum; //unsigned int x; game.godparticle=-1; game.oldschool=0; if (game.levelnum==64) game.oldschool=1; if (game.levelnum==65) { game.oldschool=2; game.oldschoolsound=-200; } if (game.levelnum==66) game.oldschool=3; srand(time(NULL)); setuplevel(); setupgame(); simtimer=SDL_GetTicks(); game.exit=GAMEEXIT_NONE; scorenum=-1; resetmenuitems(); while ((game.exit<GAMEEXIT_EXITGAME || game.exitdelay>0) && !windowinfo.shutdown) { frametimer=SDL_GetTicks(); glClearColor(0.0f,0.0f,0.0f,0.0f); glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); glStencilMask(~0); glClearStencil(0); glClear(GL_COLOR_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_FALSE); glStencilMask(0); setuptextdisplay(); glColor3fv(level.ambient[3]); if (level.background[0]!=0) displaybackground(660); if (game.over!=0 && level.gametype<GAMETYPE_2FOOTBALL) if (game.exit==GAMEEXIT_NONE) { if (game.over>=3 && game.over<=5) { game.exit=GAMEXIT_WARPZONE; game.exitdelay=100; } if (game.over==2) { game.exit=GAMEEXIT_WON; game.exitdelay=100; } if (game.over==1) { game.exit=GAMEEXIT_DIED; game.exitdelay=100; if (game.levelnum==65) game.exitdelay=200; } } numofmenuitems=0; if (game.exit==GAMEEXIT_NONE) { createmenuitem("",0,0,16,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_HOTKEY,SCAN_ESC); setmenuitem(MO_SET,&game.exit,GAMEEXIT_INGAMEMENU); } if (game.exit==GAMEEXIT_INGAMEMENU) { count=240; if (game.over==0) { createmenuitem(TXT_RETURN_TO_GAME,(320|TEXT_CENTER),count,16,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_HOTKEY,SCAN_ESC); setmenuitem(MO_SET,&game.exit,GAMEEXIT_NONE); } else createmenuitemempty(); count+=16; if (game.levelnum<64) { if (level.gametype==GAMETYPE_CAMPAIGN && (game.levelnum>0 || mappack.active) && !game.playreplay) createmenuitem(TXT_RESETLEVEL_MINUSONE,(320|TEXT_CENTER),count,16,1.0f,1.0f,1.0f,1.0f); else createmenuitem(TXT_RESETLEVEL,(320|TEXT_CENTER),count,16,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_HOTKEY,SCAN_R); if (level.gametype==GAMETYPE_CAMPAIGN) setmenuitem(MO_SET,&game.exit,GAMEEXIT_DIED); count+=16; } else createmenuitemempty(); if (game.over==0 && game.levelnum<64 && level.gametype==GAMETYPE_CAMPAIGN && game.levelnum>0 && !game.playreplay) createmenuitem(TXT_EXITGAME_MINUSONE,(320|TEXT_CENTER),count,16,1.0f,1.0f,1.0f,1.0f); else createmenuitem(TXT_EXITGAME,(320|TEXT_CENTER),count,16,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_HOTKEY,SCAN_E); setmenuitem(MO_SET,&game.exit,GAMEEXIT_EXITGAME); count+=16; } if (game.exit==GAMEEXIT_DIED) { if (game.time>0) { createmenuitem(" ",(320|TEXT_CENTER),(240|TEXT_CENTER),20,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_SET,&game.exitdelay,0); } else { createmenuitem(TXT_TIMEUP,(320|TEXT_CENTER),(240|TEXT_CENTER),20,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_SET,&game.exitdelay,0); } } if (game.exit==GAMEEXIT_WON) { createmenuitem(TXT_COMPLETE,524|TEXT_CENTER,266,20,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_IMAGE,462); setmenuitem(MO_RESIZE,(320|TEXT_CENTER),(240|TEXT_CENTER),256,128); setmenuitem(MO_SET,&game.exitdelay,0); } if (game.exit==GAMEXIT_WARPZONE) { if (game.levelnum!=34) { createmenuitem(TXT_WARPZONE,(320|TEXT_CENTER),(240|TEXT_CENTER),24,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_SET,&game.exitdelay,0); } else { //createmenuitem("OOPS!",(320|TEXT_CENTER),(240|TEXT_CENTER),24,1.0f,1.0f,1.0f,1.0f); //setmenuitem(MO_SET,&game.exitdelay,0); createmenuitem(TXT_OOPS,(320|TEXT_CENTER),(240|TEXT_CENTER),24,1.0f,1.0f,1.0f,1.0f); setmenuitem(MO_IMAGE,465); setmenuitem(MO_RESIZE,(320|TEXT_CENTER),(240|TEXT_CENTER),256,128); setmenuitem(MO_SET,&game.exitdelay,0); } } checksystemmessages(); checkkeyboard(); checkmouse(); checkjoystick(); checkmenuitems(); if (game.exit==GAMEEXIT_INGAMEMENU) if (level.gametype!=GAMETYPE_CAMPAIGN) if (menuitem[1].active) { setuplevel(); setupgame(); game.exit=GAMEEXIT_NONE; menuitem[1].active=0; } if (game.dialog>0) { if (game.levelnum!=68 || (game.dialog!=13 && game.dialog!=14)) { if (game.dialogdelay>0) game.dialogdelay--; count2=0; if (game.dialogdelay==0) count2=1; for (count=4;count<KEYALIAS_LENGTH;count++) if (keyboard[control[0].key[count]] && !prevkeyboard[control[0].key[count]]) count2=1; if (control[0].joysticknum!=-1) for (count=4;count<8;count++) if (control[0].button[count]!=-1) if (joystick[control[0].joysticknum].button[control[0].button[count]] && !prevjoystick[control[0].joysticknum].button[control[0].button[count]]) count2=1; if (count2==1) { game.dialog--; game.dialogdelay=1000; if (game.levelnum==68) if (game.dialog==4) { game.numoflives=99; game.exit=GAMEEXIT_WON; game.exitdelay=0; } } } else { count2=0; if (keyboard[control[0].key[KEYALIAS_DOWN]] && !prevkeyboard[control[0].key[KEYALIAS_DOWN]]) count2=1; if (keyboard[control[0].key[KEYALIAS_UP]] && !prevkeyboard[control[0].key[KEYALIAS_UP]]) count2=1; if (control[0].joysticknum!=-1) { if (joystick[control[0].joysticknum].axis[1]>=0.5f && prevjoystick[control[0].joysticknum].axis[1]<0.5f) count2=1; if (joystick[control[0].joysticknum].axis[1]<=-0.5f && prevjoystick[control[0].joysticknum].axis[1]>-0.5f) count2=1; } if (count2==1) { if (game.dialog==14) game.dialog=13; else game.dialog=14; } count2=0; for (count=4;count<KEYALIAS_LENGTH;count++) if (keyboard[control[0].key[count]] && !prevkeyboard[control[0].key[count]]) count2=1; if (control[0].joysticknum!=-1) for (count=4;count<8;count++) if (control[0].button[count]!=-1) if (joystick[control[0].joysticknum].button[control[0].button[count]] && !prevjoystick[control[0].joysticknum].button[control[0].button[count]]) count2=1; if (count2==1) { if (game.dialog==14) game.dialog=12; else game.dialog=1; } } } checkmusic(); if (game.levelnum>=1 && game.levelnum<=7) game.songnum=0; if (game.levelnum>=8 && game.levelnum<=14) game.songnum=1; if (game.levelnum>=15 && game.levelnum<=21) game.songnum=2; if (game.levelnum>=22 && game.levelnum<=28) game.songnum=3; if (game.levelnum>=29 && game.levelnum<=32) game.songnum=4; if (game.bosslevel) game.songnum=5; if (game.levelnum==64) game.songnum=6; if (game.levelnum==67) game.songnum=2; if (game.levelnum==0) { if (game.songnum==-1) game.songnum=rand()%5; } if (level.gametype==GAMETYPE_2SUMO) game.songnum=7; /* if (level.gametype==GAMETYPE_2FOOTBALL) game.songnum=4; if (level.gametype==GAMETYPE_2SUMO) game.songnum=5; if (level.gametype==GAMETYPE_2GREED) game.songnum=4; */ if (game.levelnum==0) if (keyboard[SCAN_F5] && !prevkeyboard[SCAN_F5]) { setuplevel(); setupgame(); } if (keyboard[SCAN_P] && !prevkeyboard[SCAN_P] && game.exit==GAMEEXIT_NONE) game.pause^=1; //if (keyboard[SCAN_R] && !prevkeyboard[SCAN_R]) // movie.record^=1; view.zoom=10.0f; if (game.oldschool==2) view.zoom=16.0f; if (game.oldschool==3) view.zoom=26.0f; if (level.gametype==GAMETYPE_2COLLECTION) view.zoom=24.0f; if (level.gametype==GAMETYPE_2RACING) view.zoom=24.0f; if (level.gametype==GAMETYPE_4FOOTBALL || level.gametype==GAMETYPE_4SUMO) view.zoom=14.0f; view.zoomx=view.zoom+0.5f; view.zoomy=view.zoom*0.75f+0.5f; //view.zoomy=view.zoom*0.5625f+0.5f; setuporthoviewport(0,0,640,480,view.zoom,view.zoom*0.75f,20.0f); //setuporthoviewport(0,0,640,480,view.zoom,view.zoom*0.5625f,20.0f); setupviewpoint(view.position,view.orientation); if (game.oldschool==1)// || game.oldschool==3) glViewport(0,0,256,256); if (game.oldschool==2) glViewport(0,0,128,128); soundsimulation(view.position,view.orientation); setupframelighting(); setuprenderobjects(); rendershadows(); renderlevelback(); renderparticles(); //if (!keyboard[SCAN_B]) renderobjects(); renderparticles2(); renderlevel(); renderlevelfore(); if (game.oldschool==1)// || game.oldschool==3) { glBindTexture(GL_TEXTURE_2D,texture[334].glname); glCopyTexImage2D(GL_TEXTURE_2D,0,GL_RGB,0,0,256,256,0); } if (game.oldschool==2) { glBindTexture(GL_TEXTURE_2D,texture[333].glname); glCopyTexImage2D(GL_TEXTURE_2D,0,GL_RGB,0,0,128,128,0); } if (game.oldschool==1 || game.oldschool==2)// || game.oldschool==3) { setuptextdisplay(); if (game.oldschool==1)// || game.oldschool==3) glBindTexture(GL_TEXTURE_2D,texture[334].glname); if (game.oldschool==2) glBindTexture(GL_TEXTURE_2D,texture[333].glname); glBegin(GL_QUADS); glColor4f(1.0f,1.0f,1.0f,1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f(-1.0f,0.75f,-1.0f); glTexCoord2f(1.0f,1.0f); glVertex3f(1.0f,0.75f,-1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f(1.0f,-0.75f,-1.0f); glTexCoord2f(0.0f,0.0f); glVertex3f(-1.0f,-0.75f,-1.0f); glEnd(); } setuptextdisplay(); if (game.exit==GAMEEXIT_WON || game.exit==GAMEXIT_WARPZONE) { glDisable(GL_TEXTURE_2D); glBegin(GL_QUADS); glColor4f(0.0f,0.0f,0.0f,(float)(100-game.exitdelay)*0.01f); glVertex3f(-1.0f,0.75f,-1.0f); glVertex3f(1.0f,0.75f,-1.0f); glVertex3f(1.0f,-0.75f,-1.0f); glVertex3f(-1.0f,-0.75f,-1.0f); glEnd(); glEnable(GL_TEXTURE_2D); } if (game.exit==GAMEEXIT_DIED) { glDisable(GL_TEXTURE_2D); glBegin(GL_QUADS); if (game.exitdelay>50) glColor4f(0.5f,0.0f,0.0f,(float)(100-game.exitdelay)*0.01f); else glColor4f(1.0f-(float)(100-game.exitdelay)*0.01f,0.0f,0.0f,(float)(100-game.exitdelay)*0.01f); glVertex3f(-1.0f,0.75f,-1.0f); glVertex3f(1.0f,0.75f,-1.0f); glVertex3f(1.0f,-0.75f,-1.0f); glVertex3f(-1.0f,-0.75f,-1.0f); glEnd(); glEnable(GL_TEXTURE_2D); } if (game.oldschool==0 && !game.bosslevel && level.gametype!=GAMETYPE_2COLLECTION) rendersprites(); glColor4f(1.0f,1.0f,1.0f,1.0f); drawbackground(640,0,0,256,256,640,480); drawbackground(641,256,0,256,256,640,480); drawbackground(642,512,0,256,256,640,480); drawbackground(643,0,256,256,256,640,480); drawbackground(644,256,256,256,256,640,480); drawbackground(645,512,256,256,256,640,480); //if (game.turbomode) // drawbackground(529,28,64,64,32,640,480); gamedisplay(); drawmenuitems(); if (game.exit==GAMEEXIT_DIED || game.exit==GAMEEXIT_WON || game.exit==GAMEXIT_WARPZONE) if (game.exitdelay<20) { glDisable(GL_TEXTURE_2D); glBegin(GL_QUADS); glColor4f(0.0f,0.0f,0.0f,(float)(20-game.exitdelay)*0.05f); glVertex3f(-1.0f,0.75f,-1.0f); glVertex3f(1.0f,0.75f,-1.0f); glVertex3f(1.0f,-0.75f,-1.0f); glVertex3f(-1.0f,-0.75f,-1.0f); glEnd(); glEnable(GL_TEXTURE_2D); } if (movie.record) { if (movie.framenum<game.framenum/2) recordframe(); drawtext("RECORD",0,64,16,1.0f,0.0f,0.0f,1.0f); } if (game.playreplay) drawtext(TXT_REPLAY,(612|TEXT_END),64,16,1.0f,1.0f,0.0f,1.0f); if (game.pause && game.exit==GAMEEXIT_NONE) { drawtext(TXT_PAUSED,(320|TEXT_CENTER),240,16,1.0f,1.0f,1.0f,1.0f); drawtext(TXT_PRESS_P,(320|TEXT_CENTER),256,12,1.0f,1.0f,1.0f,1.0f); } if (game.exit!=GAMEEXIT_NONE || game.godmode) drawmousecursor(768+font.cursornum,mouse.x,mouse.y,16,1.0f,1.0f,1.0f,1.0f); simcount=0; game.simspeed=20; if (game.turbomode) game.simspeed=15; while (SDL_GetTicks()-simtimer<=game.simspeed) SDL_Delay(1); while (SDL_GetTicks()-simtimer>game.simspeed && simcount<3) { simcount++; count=SDL_GetTicks()-simtimer-game.simspeed; simtimer=SDL_GetTicks()-count; if (simcount==3) simtimer=SDL_GetTicks(); if (game.exitdelay>0) if (!game.editing) game.exitdelay--; if (keyboard[SCAN_ESC]) game.exitdelay=0; if (game.exit==GAMEEXIT_NONE && !game.pause && game.dialog==0 && !game.over) { getinputs(); if (!game.playreplay) saveinputs(); else loadinputs(); if (game.startdelay==0) simulation(); gamelogic(); } } if (game.levelnum==0 && game.editing) if (keyboard[SCAN_F1] && !prevkeyboard[SCAN_F1]) { game.songnum=-1; checkmusic(); for (count=numofsounds-1;count>=0;count--) deletesound(count); setuptextdisplay(); drawtext(TXT_LOADINGEDITOR,(320|TEXT_CENTER),240,16,1.0f,1.0f,1.0f,1.0f); SDL_GL_SwapWindow(globalwindow); for (count=0;count<20;count++) if (animation[count].loaded==0) animation[count].loaded=2; loadanimations(); editlevel(); savelevel("backup.lvl"); simtimer=SDL_GetTicks(); } SDL_GL_SwapWindow(globalwindow); if ((SDL_GetTicks()-frametimer)!=0) fps=1000/(SDL_GetTicks()-frametimer); } game.songnum=-1; checkmusic(); for (count=numofsounds-1;count>=0;count--) deletesound(count); resetmenuitems(); } void simulation(void) { int count,count2; float vec[3],vec2[3]; //float intersectpoint[3]; //float normal[3]; float scale; game.framenum++; if (game.godmode) if (!game.playreplay) { vec[0]=view.position[0]+(float)(mouse.x-320)/32.0f; vec[1]=view.position[1]+(float)(240-mouse.y)/32.0f; vec[2]=0.0f; if (mouse.lmb) { if (game.godparticle==-1) { game.godparticle=numofparticles; createparticle(16,vec,NULL,10000.0f,-1,10000); for (count=0;count<numofparticles;count++) if (count!=game.godparticle) if (particle[count].type==3) { subtractvectors(vec2,vec,particle[count].position); if (vectorlength(vec2)<3.0f) createbond(count,game.godparticle,16,-1); } } else { subtractvectors(vec2,vec,particle[game.godparticle].position); scaleaddvectors2(vec2,vec2,particle[game.godparticle].velocity,-4.0f); scale=vectorlength(vec2); normalizevector(vec2,vec2); scale*=0.01f; scaleaddvectors2(particle[game.godparticle].velocity,particle[game.godparticle].velocity,vec2,scale); } } else { if (game.godparticle!=-1) { deleteparticle(game.godparticle); game.godparticle=-1; } } } particlesimulation(); particletimetolive(); //physicstemp.numofbonds=0; for (count=0;count<numofobjects;count++) object[count].prevhitpoints=object[count].hitpoints; if (level.gametype!=GAMETYPE_2RACING) for (count=0;count<numofparticles;count++) particle[count].velocity[1]-=particle[count].gravity; for (count=0;count<numofparticles;count++) if (particle[count].levelcollision) particlecollision(count); for (count=0;count<numofobjects;count++) { updateogg(); objectcollision(count); } for (count=0;count<numofobjects;count++) { updateogg(); objectcollisionobject(count); } objectcycle(); objectanimation(); updateogg(); bondsimulation2(); checkbonds(); objecttimetolive(); spritesimulation(); spritetimetolive(); bosssimulation(); bosstimetolive(); for (count=0;count<numofobjects;count++) { if (object[count].type==1) { if (object[count].hitpoints<0) object[count].hitpoints=0; if (object[count].hitpoints<object[count].prevhitpoints) { for (count2=0;count2<=(object[count].prevhitpoints-object[count].hitpoints)/20;count2++) { vec[0]=(float)((rnd()&255)-127)/1270.0f; vec[1]=(float)((rnd()&255)-127)/1270.0f; vec[2]=0.0f; addvectors(vec,vec,object[count].velocity); createparticle(5,object[count].position,vec,0.25f,-1,100+(rnd()&63)); particle[numofparticles-1].rendersize=0.125+(float)(rnd()&127)/1000.0f; if (count==0) particle[numofparticles-1].texturenum=368; else if (count==1) particle[numofparticles-1].texturenum=363; else if (count==2) particle[numofparticles-1].texturenum=383+40; else particle[numofparticles-1].texturenum=383+60; } object[count].frame=12; object[count].framedelay=0.0f; playsound(16,object[count].position,NULL,0.5f,0,1.0f,count,2); } } } } void getinputs(void) { int count; for (count=0;count<4;count++) { object[count].axis[0]=0.0f; object[count].axis[1]=0.0f; object[count].button=0; } for (count=0;count<CONTROLS_LENGTH;count++) { if (keyboard[control[count].key[KEYALIAS_LEFT]]) object[count].axis[0]-=1.0f; if (keyboard[control[count].key[KEYALIAS_RIGHT]]) object[count].axis[0]+=1.0f; if (keyboard[control[count].key[KEYALIAS_DOWN]]) object[count].axis[1]-=1.0f; if (keyboard[control[count].key[KEYALIAS_UP]]) object[count].axis[1]+=1.0f; if (keyboard[control[count].key[KEYALIAS_STICK]]) object[count].button|=1; if (keyboard[control[count].key[KEYALIAS_JUMP]]) object[count].button|=2; if (keyboard[control[count].key[KEYALIAS_SLIDE]]) object[count].button|=4; if (keyboard[control[count].key[KEYALIAS_HEAVY]]) object[count].button|=8; if (control[count].joysticknum!=-1) { object[count].axis[0]+=joystick[control[count].joysticknum].axis[0]; object[count].axis[1]+=joystick[control[count].joysticknum].axis[1]; if (control[count].button[0]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[0]]) object[count].axis[0]-=1.0f; if (control[count].button[1]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[1]]) object[count].axis[0]+=1.0f; if (control[count].button[2]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[2]]) object[count].axis[1]-=1.0f; if (control[count].button[3]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[3]]) object[count].axis[1]+=1.0f; if (control[count].button[4]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[4]]) object[count].button|=1; if (control[count].button[5]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[5]]) object[count].button|=2; if (control[count].button[6]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[6]]) object[count].button|=4; if (control[count].button[7]!=-1) if (joystick[control[count].joysticknum].button[control[count].button[7]]) object[count].button|=8; } if (object[count].axis[0]<-1.0f) object[count].axis[0]=-1.0f; if (object[count].axis[0]>1.0f) object[count].axis[0]=1.0f; if (object[count].axis[1]<-1.0f) object[count].axis[1]=-1.0f; if (object[count].axis[1]>1.0f) object[count].axis[1]=1.0f; } }
411
0.575257
1
0.575257
game-dev
MEDIA
0.885349
game-dev
0.828032
1
0.828032
Jikoo/Regionerator
1,185
src/main/java/com/github/jikoo/regionerator/hooks/GriefPreventionHook.java
/* * Copyright (c) 2015-2021 by Jikoo. * * Regionerator is licensed under a Creative Commons * Attribution-ShareAlike 4.0 International License. * * You should have received a copy of the license along with this * work. If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. */ package com.github.jikoo.regionerator.hooks; import me.ryanhamshire.GriefPrevention.Claim; import me.ryanhamshire.GriefPrevention.GriefPrevention; import org.bukkit.World; import org.jetbrains.annotations.NotNull; /** * PluginHook for <a href="http://dev.bukkit.org/bukkit-plugins/grief-prevention/">GriefPrevention</a>. */ public class GriefPreventionHook extends PluginHook { public GriefPreventionHook() { super("GriefPrevention"); } @Override public boolean isChunkProtected(@NotNull World world, int chunkX, int chunkZ) { if (!GriefPrevention.instance.claimsEnabledForWorld(world)) { return false; } for (Claim claim : GriefPrevention.instance.dataStore.getClaims(chunkX, chunkZ)) { if (world.equals(claim.getGreaterBoundaryCorner().getWorld())) { return true; } } return false; } @Override public boolean isAsyncCapable() { return true; } }
411
0.51119
1
0.51119
game-dev
MEDIA
0.610485
game-dev
0.827104
1
0.827104
brooksc/mcpipy
2,756
mcpi/examples/obsidz_teleport.py
#!/usr/bin/env python from .. import minecraft from .. import block import time import server #Author: Obsidz # #Description: This is a teleport pad script. # To create a pad, place a nether reactor core onto a location and ring with cobbledtone blocks # To add to locations list walk over it # #Notes: Pads added to list by walking over them # Pads not removed if destroyed but can be teleported to but not from # You cannot teleport to the same pad without modifying script # Pads need to be added each time the script is run # modified version - as shared on mcpipy.com # original post @ http://www.minecraftforum.net/topic/1691618-teleportation-python-script/ LPLoc = list() Pads = 0 Cpad = 0 # If you are running this script with the bukkit mod, then use a diamond block as the magic center block for teleporting # comment/uncomment below as appropriate magic_block = block.DIAMOND_BLOCK.id # for bukkit server #magic_block = block.NETHER_REACTOR_CORE.id # for raspberry pi def isLaunchPad(): #checks if the the location below the player is a teleporting pad loc = mc.player.getPos() if ((mc.getBlock(loc.x,loc.y-1,loc.z) == magic_block) and (mc.getBlock(loc.x-1,loc.y-1,loc.z-1) == block.COBBLESTONE.id) and (mc.getBlock(loc.x-1,loc.y-1,loc.z) == block.COBBLESTONE.id) and (mc.getBlock(loc.x-1,loc.y-1,loc.z+1) == block.COBBLESTONE.id) and (mc.getBlock(loc.x,loc.y-1,loc.z+1) == block.COBBLESTONE.id) and (mc.getBlock(loc.x,loc.y-1,loc.z-1) == block.COBBLESTONE.id) and (mc.getBlock(loc.x+1,loc.y-1,loc.z-1) == block.COBBLESTONE.id) and (mc.getBlock(loc.x+1,loc.y-1,loc.z) == block.COBBLESTONE.id) and (mc.getBlock(loc.x+1,loc.y-1,loc.z+1) == block.COBBLESTONE.id)): addLPLoc(loc) return True else: return False def addLPLoc(Vec3): #Loggs the location of the pad for future use global Pads global LPLoc inList = False if Pads > 0: for loc in LPLoc: if (loc.x == Vec3.x and loc.y == Vec3.y and loc.z == Vec3.z): inList = True if not inList: LPLoc.append(Vec3) mc.postToChat("I'll remember this pad location!") Pads = len(LPLoc) def locCheck(): #Checks that you are not teleporting to the same pad global Cpad global LPLoc loc = mc.player.getPos() if (loc.x == LPLoc[Cpad].x and loc.y == LPLoc[Cpad].y and loc.z == LPLoc[Cpad].z): Cpad = Cpad + 1 def TPChar(): #sends the character to the next pad global Pads global Cpad global LPLoc if Pads > 1: mc.player.setPos(LPLoc[Cpad].x,LPLoc[Cpad].y + 1,LPLoc[Cpad].z) Cpad = ( Cpad + 1) % Pads time.sleep(3.0) if __name__ == "__main__": # The script mc = minecraft.Minecraft.create(server.address) while True: if isLaunchPad(): TPChar() time.sleep(0.1)
411
0.89987
1
0.89987
game-dev
MEDIA
0.187663
game-dev
0.889905
1
0.889905
netease-im/phoenix
2,281
phoenix/base/google_base/base/win/scoped_com_initializer.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_WIN_SCOPED_COM_INITIALIZER_H_ #define BASE_WIN_SCOPED_COM_INITIALIZER_H_ #include <objbase.h> #include "base/logging.h" #include "base/macros.h" #include "build/build_config.h" namespace base { namespace win { // Initializes COM in the constructor (STA or MTA), and uninitializes COM in the // destructor. // // WARNING: This should only be used once per thread, ideally scoped to a // similar lifetime as the thread itself. You should not be using this in // random utility functions that make COM calls -- instead ensure these // functions are running on a COM-supporting thread! class ScopedCOMInitializer { public: // Enum value provided to initialize the thread as an MTA instead of STA. enum SelectMTA { kMTA }; // Constructor for STA initialization. ScopedCOMInitializer() { Initialize(COINIT_APARTMENTTHREADED); } // Constructor for MTA initialization. explicit ScopedCOMInitializer(SelectMTA mta) { Initialize(COINIT_MULTITHREADED); } ~ScopedCOMInitializer() { #ifndef NDEBUG // Using the windows API directly to avoid dependency on platform_thread. DCHECK_EQ(GetCurrentThreadId(), thread_id_); #endif if (succeeded()) CoUninitialize(); } bool succeeded() const { return SUCCEEDED(hr_); } private: void Initialize(COINIT init) { #ifndef NDEBUG thread_id_ = GetCurrentThreadId(); #endif hr_ = CoInitializeEx(NULL, init); #ifndef NDEBUG if (hr_ == S_FALSE) LOG(ERROR) << "Multiple CoInitialize() calls for thread " << thread_id_; else DCHECK_NE(RPC_E_CHANGED_MODE, hr_) << "Invalid COM thread model change"; #endif } HRESULT hr_; #ifndef NDEBUG // In debug builds we use this variable to catch a potential bug where a // ScopedCOMInitializer instance is deleted on a different thread than it // was initially created on. If that ever happens it can have bad // consequences and the cause can be tricky to track down. DWORD thread_id_; #endif DISALLOW_COPY_AND_ASSIGN(ScopedCOMInitializer); }; } // namespace win } // namespace base #endif // BASE_WIN_SCOPED_COM_INITIALIZER_H_
411
0.746043
1
0.746043
game-dev
MEDIA
0.159361
game-dev
0.805501
1
0.805501
EphemeralSpace/ephemeral-space
6,657
Content.Shared/Body/Systems/SharedBodySystem.Organs.cs
using System.Diagnostics.CodeAnalysis; using Content.Shared.Body.Components; using Content.Shared.Body.Events; using Content.Shared.Body.Organ; using Content.Shared.Body.Part; using Robust.Shared.Containers; namespace Content.Shared.Body.Systems; public partial class SharedBodySystem { private void AddOrgan( Entity<OrganComponent> organEnt, EntityUid bodyUid, EntityUid parentPartUid) { organEnt.Comp.Body = bodyUid; var addedEv = new OrganAddedEvent(parentPartUid); RaiseLocalEvent(organEnt, ref addedEv); if (organEnt.Comp.Body is not null) { var addedInBodyEv = new OrganAddedToBodyEvent(bodyUid, parentPartUid); RaiseLocalEvent(organEnt, ref addedInBodyEv); } Dirty(organEnt, organEnt.Comp); } private void RemoveOrgan(Entity<OrganComponent> organEnt, EntityUid parentPartUid) { var removedEv = new OrganRemovedEvent(parentPartUid); RaiseLocalEvent(organEnt, ref removedEv); if (organEnt.Comp.Body is { Valid: true } bodyUid) { var removedInBodyEv = new OrganRemovedFromBodyEvent(bodyUid, parentPartUid); RaiseLocalEvent(organEnt, ref removedInBodyEv); } organEnt.Comp.Body = null; Dirty(organEnt, organEnt.Comp); } /// <summary> /// Creates the specified organ slot on the parent entity. /// </summary> private OrganSlot? CreateOrganSlot(Entity<BodyPartComponent?> parentEnt, string slotId) { if (!Resolve(parentEnt, ref parentEnt.Comp, logMissing: false)) return null; Containers.EnsureContainer<ContainerSlot>(parentEnt, GetOrganContainerId(slotId)); var slot = new OrganSlot(slotId); parentEnt.Comp.Organs.Add(slotId, slot); return slot; } /// <summary> /// Attempts to create the specified organ slot on the specified parent if it exists. /// </summary> public bool TryCreateOrganSlot( EntityUid? parent, string slotId, [NotNullWhen(true)] out OrganSlot? slot, BodyPartComponent? part = null) { slot = null; if (parent is null || !Resolve(parent.Value, ref part, logMissing: false)) { return false; } Containers.EnsureContainer<ContainerSlot>(parent.Value, GetOrganContainerId(slotId)); slot = new OrganSlot(slotId); return part.Organs.TryAdd(slotId, slot.Value); } /// <summary> /// Returns whether the slotId exists on the partId. /// </summary> public bool CanInsertOrgan( EntityUid partId, string slotId, BodyPartComponent? part = null) { return Resolve(partId, ref part) && part.Organs.ContainsKey(slotId); } /// <summary> /// Returns whether the specified organ slot exists on the partId. /// </summary> public bool CanInsertOrgan( EntityUid partId, OrganSlot slot, BodyPartComponent? part = null) { return CanInsertOrgan(partId, slot.Id, part); } public bool InsertOrgan( EntityUid partId, EntityUid organId, string slotId, BodyPartComponent? part = null, OrganComponent? organ = null) { if (!Resolve(organId, ref organ, logMissing: false) || !Resolve(partId, ref part, logMissing: false) || !CanInsertOrgan(partId, slotId, part)) { return false; } var containerId = GetOrganContainerId(slotId); return Containers.TryGetContainer(partId, containerId, out var container) && Containers.Insert(organId, container); } /// <summary> /// Removes the organ if it is inside of a body part. /// </summary> public bool RemoveOrgan(EntityUid organId, OrganComponent? organ = null) { if (!Containers.TryGetContainingContainer((organId, null, null), out var container)) return false; var parent = container.Owner; return HasComp<BodyPartComponent>(parent) && Containers.Remove(organId, container); } /// <summary> /// Tries to add this organ to any matching slot on this body part. /// </summary> public bool AddOrganToFirstValidSlot( EntityUid partId, EntityUid organId, BodyPartComponent? part = null, OrganComponent? organ = null) { if (!Resolve(partId, ref part, logMissing: false) || !Resolve(organId, ref organ, logMissing: false)) { return false; } foreach (var slotId in part.Organs.Keys) { InsertOrgan(partId, organId, slotId, part, organ); return true; } return false; } /// <summary> /// Returns a list of Entity<<see cref="T"/>, <see cref="OrganComponent"/>> /// for each organ of the body /// </summary> /// <typeparam name="T">The component that we want to return</typeparam> /// <param name="entity">The body to check the organs of</param> public List<Entity<T, OrganComponent>> GetBodyOrganEntityComps<T>( Entity<BodyComponent?> entity) where T : IComponent { if (!Resolve(entity, ref entity.Comp)) return new List<Entity<T, OrganComponent>>(); var query = GetEntityQuery<T>(); var list = new List<Entity<T, OrganComponent>>(3); foreach (var organ in GetBodyOrgans(entity.Owner, entity.Comp)) { if (query.TryGetComponent(organ.Id, out var comp)) list.Add((organ.Id, comp, organ.Component)); } return list; } /// <summary> /// Tries to get a list of ValueTuples of <see cref="T"/> and OrganComponent on each organs /// in the given body. /// </summary> /// <param name="uid">The body entity id to check on.</param> /// <param name="comps">The list of components.</param> /// <param name="body">The body to check for organs on.</param> /// <typeparam name="T">The component to check for.</typeparam> /// <returns>Whether any were found.</returns> public bool TryGetBodyOrganEntityComps<T>( Entity<BodyComponent?> entity, [NotNullWhen(true)] out List<Entity<T, OrganComponent>>? comps) where T : IComponent { if (!Resolve(entity.Owner, ref entity.Comp)) { comps = null; return false; } comps = GetBodyOrganEntityComps<T>(entity); if (comps.Count != 0) return true; comps = null; return false; } }
411
0.676154
1
0.676154
game-dev
MEDIA
0.799955
game-dev,testing-qa
0.765821
1
0.765821
Goob-Station/Goob-Station
2,769
Content.Goobstation.Server/Shadowling/Systems/Abilities/Ascension/ShadowlingAscendantBroadcastSystem.cs
// SPDX-FileCopyrightText: 2025 GoobBot <uristmchands@proton.me> // SPDX-FileCopyrightText: 2025 Lumminal <81829924+Lumminal@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Roudenn <romabond091@gmail.com> // // SPDX-License-Identifier: AGPL-3.0-or-later using Content.Goobstation.Shared.Shadowling; using Content.Goobstation.Shared.Shadowling.Components.Abilities.Ascension; using Content.Server.Administration; using Content.Shared.Actions; using Content.Shared.Popups; using Robust.Shared.Player; namespace Content.Goobstation.Server.Shadowling.Systems.Abilities.Ascension; /// <summary> /// This handles the Ascendant Broadcast ability. /// It broadcasts (via a large red popup) a message to everyone. /// </summary> public sealed class ShadowlingAscendantBroadcastSystem : EntitySystem { [Dependency] private readonly QuickDialogSystem _dialogSystem = default!; [Dependency] private readonly SharedPopupSystem _popupSystem = default!; [Dependency] private readonly SharedActionsSystem _actions = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<ShadowlingAscendantBroadcastComponent, AscendantBroadcastEvent>(OnBroadcast); SubscribeLocalEvent<ShadowlingAscendantBroadcastComponent, MapInitEvent>(OnStartup); SubscribeLocalEvent<ShadowlingAscendantBroadcastComponent, ComponentShutdown>(OnShutdown); } private void OnStartup(Entity<ShadowlingAscendantBroadcastComponent> ent, ref MapInitEvent args) => _actions.AddAction(ent.Owner, ref ent.Comp.ActionEnt, ent.Comp.ActionId); private void OnShutdown(Entity<ShadowlingAscendantBroadcastComponent> ent, ref ComponentShutdown args) => _actions.RemoveAction(ent.Owner, ent.Comp.ActionEnt); private void OnBroadcast(EntityUid uid, ShadowlingAscendantBroadcastComponent component, AscendantBroadcastEvent args) { if (args.Handled || !TryComp<ActorComponent>(args.Performer, out var actor)) return; _dialogSystem.OpenDialog(actor.PlayerSession, Loc.GetString("asc-broadcast-title"), Loc.GetString("asc-broadcast-prompt"), (string message) => { if (actor.PlayerSession.AttachedEntity == null) return; var query = EntityQueryEnumerator<ActorComponent>(); while (query.MoveNext(out var ent, out _)) { if (ent == uid) continue; _popupSystem.PopupEntity(message, ent, ent, PopupType.LargeCaution); } _popupSystem.PopupEntity(Loc.GetString("shadowling-ascendant-broadcast-dialog"), uid, uid, PopupType.Medium); }); args.Handled = true; } }
411
0.802003
1
0.802003
game-dev
MEDIA
0.894548
game-dev
0.847056
1
0.847056
risk-of-thunder/R2API
8,270
R2API.TempVisualEffect/TempVisualEffectAPI.cs
using System; using System.Collections.Generic; using R2API.AutoVersionGen; using R2API.Utils; using RoR2; using UnityEngine; namespace R2API; /// <summary> /// API for adding custom TemporaryVisualEffects to CharacterBody components. /// </summary> #pragma warning disable CS0436 // Type conflicts with imported type [AutoVersion] #pragma warning restore CS0436 // Type conflicts with imported type public static partial class TempVisualEffectAPI { public const string PluginGUID = R2API.PluginGUID + ".tempvisualeffect"; public const string PluginName = R2API.PluginName + ".TempVisualEffect"; /// <summary> /// Return true if the submodule is loaded. /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [Obsolete(R2APISubmoduleDependency.PropertyObsolete)] #pragma warning restore CS0618 // Type or member is obsolete public static bool Loaded => true; /// <summary> /// Delegate used for checking if TemporaryVisualEffect should be active (bool active). <see cref="CharacterBody.UpdateSingleTemporaryVisualEffect(ref TemporaryVisualEffect, string, float, bool, string)"/> /// </summary> /// <param name="body"></param> public delegate bool EffectCondition(CharacterBody body); /// <summary> /// Delegate used for calculating the radius of a TemporaryVisualEffect (float radius). <see cref="CharacterBody.UpdateSingleTemporaryVisualEffect(ref TemporaryVisualEffect, string, float, bool, string)"/> /// </summary> /// <param name="body"></param> public delegate float EffectRadius(CharacterBody body); internal struct TemporaryVisualEffectInfo { public GameObject effectPrefab; public EffectRadius radius; public bool useBestFitRadius; public EffectCondition condition; public string childLocatorOverride; } internal static List<TemporaryVisualEffectInfo> temporaryVisualEffectInfos = new List<TemporaryVisualEffectInfo>(); internal static Dictionary<CharacterBody, TemporaryVisualEffect[]> bodyToTemporaryVisualEffects = new Dictionary<CharacterBody, TemporaryVisualEffect[]>(); internal static FixedSizeArrayPool<TemporaryVisualEffect> temporaryVisualEffectArrayPool = new FixedSizeArrayPool<TemporaryVisualEffect>(0); /// <summary> /// Adds a custom TemporaryVisualEffect to all CharacterBodies. /// Will be updated in the CharacterBody just after vanilla TemporaryVisualEffects. /// This overload lets you choose between scaling your effect based on <see cref="CharacterBody.radius"/> or <see cref="CharacterBody.bestFitRadius"/>. /// Returns true if successful. /// </summary> /// <param name="effectPrefab">MUST contain a TemporaryVisualEffect component.</param> /// <param name="condition"></param> /// <param name="useBestFitRadius"></param> /// <param name="childLocatorOverride"></param> public static bool AddTemporaryVisualEffect(GameObject effectPrefab, EffectCondition condition, bool useBestFitRadius = false, string childLocatorOverride = "") { SetHooks(); if (!effectPrefab) { TempVisualEffectPlugin.Logger.LogError($"Failed to add TemporaryVisualEffect: GameObject is null"); return false; } if (condition == null) { TempVisualEffectPlugin.Logger.LogError($"Failed to add TemporaryVisualEffect: {effectPrefab.name} no condition attached"); return false; } if (!effectPrefab.GetComponent<TemporaryVisualEffect>()) { TempVisualEffectPlugin.Logger.LogError($"Failed to add TemporaryVisualEffect: {effectPrefab.name} GameObject has no TemporaryVisualEffect component"); return false; } AddTemporaryVisualEffectInternal(effectPrefab, null, condition, useBestFitRadius, childLocatorOverride); return true; } /// <summary> /// Adds a custom TemporaryVisualEffect to all CharacterBodies. /// Will be updated in the CharacterBody just after vanilla TemporaryVisualEffects. /// This overload lets you delegate exactly how to scale your effect. /// Returns true if successful. /// </summary> /// <param name="effectPrefab">MUST contain a TemporaryVisualEffect component.</param> /// <param name="radius"></param> /// <param name="condition"></param> /// <param name="childLocatorOverride"></param> public static bool AddTemporaryVisualEffect(GameObject effectPrefab, EffectRadius radius, EffectCondition condition, string childLocatorOverride = "") { SetHooks(); if (!effectPrefab) { TempVisualEffectPlugin.Logger.LogError($"Failed to add TemporaryVisualEffect: GameObject is null"); return false; } if (radius == null) { TempVisualEffectPlugin.Logger.LogError($"Failed to add TemporaryVisualEffect: {effectPrefab.name} no radius attached"); return false; } if (condition == null) { TempVisualEffectPlugin.Logger.LogError($"Failed to add TemporaryVisualEffect: {effectPrefab.name} no condition attached"); return false; } if (!effectPrefab.GetComponent<TemporaryVisualEffect>()) { TempVisualEffectPlugin.Logger.LogError($"Failed to add TemporaryVisualEffect: {effectPrefab.name} GameObject has no TemporaryVisualEffect component"); return false; } AddTemporaryVisualEffectInternal(effectPrefab, radius, condition, false, childLocatorOverride); return true; } internal static void AddTemporaryVisualEffectInternal(GameObject effectPrefab, EffectRadius radius, EffectCondition condition, bool useBestFitRadius, string childLocatorOverride) { var newInfo = new TemporaryVisualEffectInfo { effectPrefab = effectPrefab, radius = radius, condition = condition, useBestFitRadius = useBestFitRadius, childLocatorOverride = childLocatorOverride, }; temporaryVisualEffectInfos.Add(newInfo); temporaryVisualEffectArrayPool.lengthOfArrays++; TempVisualEffectPlugin.Logger.LogMessage($"Added new TemporaryVisualEffect: {newInfo}"); } private static bool _hooksEnabled = false; internal static void SetHooks() { if (_hooksEnabled) { return; } On.RoR2.CharacterBody.UpdateAllTemporaryVisualEffects += UpdateAllHook; CharacterBody.onBodyAwakeGlobal += BodyAwake; CharacterBody.onBodyDestroyGlobal += BodyDestroy; _hooksEnabled = true; } internal static void UnsetHooks() { On.RoR2.CharacterBody.UpdateAllTemporaryVisualEffects -= UpdateAllHook; CharacterBody.onBodyStartGlobal -= BodyAwake; CharacterBody.onBodyDestroyGlobal -= BodyDestroy; _hooksEnabled = false; } private static void BodyAwake(CharacterBody body) { bodyToTemporaryVisualEffects.Add(body, temporaryVisualEffectArrayPool.Request()); } private static void BodyDestroy(CharacterBody body) { if (bodyToTemporaryVisualEffects.TryGetValue(body, out TemporaryVisualEffect[] temporaryVisualEffects)) { temporaryVisualEffectArrayPool.Return(temporaryVisualEffects); } bodyToTemporaryVisualEffects.Remove(body); } private static void UpdateAllHook(On.RoR2.CharacterBody.orig_UpdateAllTemporaryVisualEffects orig, CharacterBody self) { orig(self); if (bodyToTemporaryVisualEffects.TryGetValue(self, out TemporaryVisualEffect[] temporaryVisualEffects)) { for (int i = 0; i < temporaryVisualEffects.Length; i++) { TemporaryVisualEffectInfo info = temporaryVisualEffectInfos[i]; self.UpdateSingleTemporaryVisualEffect(ref temporaryVisualEffects[i], info.effectPrefab, info.radius != null ? info.radius(self) : (info.useBestFitRadius ? self.bestFitRadius : self.radius), info.condition(self), info.childLocatorOverride); } } } }
411
0.81772
1
0.81772
game-dev
MEDIA
0.781908
game-dev
0.958016
1
0.958016
mars-sim/mars-sim
4,608
mars-sim-core/src/main/java/com/mars_sim/core/moon/Zone.java
/* * Mars Simulation Project * Zone.java * @date 2023-10-05 * @author Manny Kung */ package com.mars_sim.core.moon; import java.io.Serializable; import com.mars_sim.core.logging.SimLogger; import com.mars_sim.core.time.ClockPulse; import com.mars_sim.core.time.Temporal; import com.mars_sim.core.tool.RandomUtil; public class Zone implements Serializable, Temporal { private static final long serialVersionUID = 1L; private static final SimLogger logger = SimLogger.getLogger(Zone.class.getName()); // Area in square meters private double area; private double growthPercent; private ZoneType type; private Colony colony; /** * Constructor. * * @param type * @param colony * @param startup Is it at the startup of the simulation ? */ public Zone(ZoneType type, Colony colony, boolean startup) { this.type = type; this.colony = colony; double factor = RandomUtil.getRandomDouble(.05, .1); if (startup) { factor = 1; } if (ZoneType.BUSINESS == type) area = factor * RandomUtil.getRandomDouble(25, 50); else if (ZoneType.COMMAND_CONTROL == type) area = factor * RandomUtil.getRandomDouble(50, 100); else if (ZoneType.COMMUNICATION == type) area = factor * RandomUtil.getRandomDouble(50, 100); else if (ZoneType.CONSTRUCTION == type) area = factor * RandomUtil.getRandomDouble(50, 200); else if (ZoneType.EDUCATION == type) area = factor * RandomUtil.getRandomDouble(10, 30); else if (ZoneType.ENGINEERING == type) area = factor * RandomUtil.getRandomDouble(50, 150); else if (ZoneType.INDUSTRIAL == type) area = factor * RandomUtil.getRandomDouble(150, 200); else if (ZoneType.LIFE_SUPPORT == type) area = factor * RandomUtil.getRandomDouble(100, 150); else if (ZoneType.OPERATION == type) area = factor * RandomUtil.getRandomDouble(100, 150); else if (ZoneType.RECREATION == type) area = factor * RandomUtil.getRandomDouble(50, 100); else if (ZoneType.RESEARCH == type) area = factor * RandomUtil.getRandomDouble(50, 100); else if (ZoneType.RESOURCE == type) area = factor * RandomUtil.getRandomDouble(150, 200); else if (ZoneType.TRANSPORTATION == type) area = factor * RandomUtil.getRandomDouble(50, 100); growthPercent = RandomUtil.getRandomDouble(0.1, 1); } @Override public boolean timePassing(ClockPulse pulse) { // int missionSol = pulse.getMarsTime().getMissionSol(); if (pulse.isNewHalfSol() || (RandomUtil.getRandomInt(50) == 1)) { if (ZoneType.RESEARCH == type) { int numResearcher = colony.getPopulation().getNumResearchers(); int numResearchProj = colony.getNumResearchProjects(); double researchValue = colony.getTotalResearchValue(); double score = 0; if (numResearcher > 0 && numResearchProj > 0) score = Math.log10(1 + researchValue / 5 / numResearchProj / numResearcher); // logger.info(colony.getName() + " research: " + score // + " researchValue: " + researchValue // + " numResearchProj: " + numResearchProj // ); if (score > .2) score = .2; else if (score < -.2) score = -.2; growthPercent += RandomUtil.getRandomDouble(-0.011 + score, 0.011 + score); } else if (ZoneType.ENGINEERING == type) { int numEngineer = colony.getPopulation().getNumEngineers(); int numDevelopmentProj = colony.getNumDevelopmentProjects(); double developmentValue = colony.getTotalDevelopmentValue(); double score = 0; if (numEngineer > 0 && numDevelopmentProj > 0) score = Math.log10(1 + developmentValue / 5 / numDevelopmentProj / numEngineer); // logger.info(colony.getName() + " research: " + score // + " researchValue: " + researchValue // + " numResearchProj: " + numResearchProj // ); if (score > .2) score = .2; else if (score < -.2) score = -.2; growthPercent += RandomUtil.getRandomDouble(-0.01 + score, 0.01 + score); } else { growthPercent += RandomUtil.getRandomDouble(-0.01, 0.01); } if (growthPercent > 10) growthPercent = 10; else if (growthPercent < -5) growthPercent = -5; area *= 1 + growthPercent/100; // Slightly adjust the growth rate after making the contribution to // the increase or decrease of the zone area growthPercent = growthPercent *.95; } return false; } public ZoneType getZoneType() { return type; } public double getArea() { return area; } public double getGrowthPercent() { return growthPercent; } /** * Prepares for deletion. */ public void destroy() { type = null; } }
411
0.774314
1
0.774314
game-dev
MEDIA
0.911197
game-dev
0.855146
1
0.855146
dpjudas/SurrealEngine
2,945
SurrealEngine/Commandlet/VM/PrintCommandlet.cpp
#include "Precomp.h" #include "PrintCommandlet.h" #include "DebuggerApp.h" #include "VM/Frame.h" PrintCommandlet::PrintCommandlet() { SetShortFormName("p"); SetLongFormName("print"); SetShortDescription("Print content of variable"); } void PrintCommandlet::OnCommand(DebuggerApp* console, const std::string& args) { Frame* frame = console->GetCurrentFrame(); UObject* obj = nullptr; bool bFoundObj = false; Array<std::string> chunks = SplitString(args, '.'); if (NameString("self") == chunks[0]) { obj = frame->Object; } else { for (UProperty* prop : frame->Func->Properties) { if (prop->Name == chunks[0] && (UObject::TryCast<UObjectProperty>(prop) || UObject::TryCast<UClassProperty>(prop))) { void* ptr = ((uint8_t*)frame->Variables.get()) + prop->DataOffset.DataOffset; obj = *(UObject**)ptr; bFoundObj = true; break; } } } if (!obj) { if (!bFoundObj) console->WriteOutput("Unknown variable " + chunks[0] + ResetEscape() + NewLine()); else console->WriteOutput("None" + ResetEscape() + NewLine()); return; } std::string name; std::string value; for (auto chunk = chunks.begin() + 1; chunk != chunks.end(); chunk++) { if (!obj) { console->WriteOutput(*chunk + ResetEscape() + " " + ColorEscape(96) + "None" + ResetEscape() + NewLine()); return; } bFoundObj = false; for (UProperty* prop : obj->PropertyData.Class->Properties) { if (prop->Name == (*chunk)) { void* ptr = ((uint8_t*)obj) + prop->DataOffset.DataOffset; void* val = obj->PropertyData.Ptr(prop); if (UObject::TryCast<UObjectProperty>(prop) || UObject::TryCast<UClassProperty>(prop)) { obj = *(UObject**)val; bFoundObj = true; break; } else if (chunk+1 == chunks.end()) { name = prop->Name.ToString(); value = prop->PrintValue(val); if (name.size() < 40) name.resize(40, ' '); console->WriteOutput(name + ResetEscape() + " " + ColorEscape(96) + value + ResetEscape() + NewLine()); return; } } } if (!bFoundObj) { console->WriteOutput("Unknown variable " + *chunk + ResetEscape() + NewLine()); return; } } if (!obj) { std::string name = *(chunks.end() - 1); if (name.size() < 40) name.resize(40, ' '); console->WriteOutput(name + ResetEscape() + " " + ColorEscape(96) + "None" + ResetEscape() + NewLine()); return; } auto props = obj->PropertyData.Class->Properties; std::stable_sort(props.begin(), props.end(), [](UProperty* a, UProperty* b) { return a->Name < b->Name; }); for (UProperty* prop : props) { void* ptr = obj->PropertyData.Ptr(prop); std::string name = prop->Name.ToString(); std::string value = prop->PrintValue(ptr); if (name.size() < 40) name.resize(40, ' '); console->WriteOutput(name + ResetEscape() + " " + ColorEscape(96) + value + ResetEscape() + NewLine()); } } void PrintCommandlet::OnPrintHelp(DebuggerApp* console) { }
411
0.800774
1
0.800774
game-dev
MEDIA
0.441588
game-dev
0.888577
1
0.888577
ConfusedPolarBear/intro-skipper
3,692
ConfusedPolarBear.Plugin.IntroSkipper/Data/TimeRange.cs
using System; using System.Collections.Generic; namespace ConfusedPolarBear.Plugin.IntroSkipper; #pragma warning disable CA1036 // Override methods on comparable types /// <summary> /// Range of contiguous time. /// </summary> public class TimeRange : IComparable { /// <summary> /// Initializes a new instance of the <see cref="TimeRange"/> class. /// </summary> public TimeRange() { Start = 0; End = 0; } /// <summary> /// Initializes a new instance of the <see cref="TimeRange"/> class. /// </summary> /// <param name="start">Time range start.</param> /// <param name="end">Time range end.</param> public TimeRange(double start, double end) { Start = start; End = end; } /// <summary> /// Initializes a new instance of the <see cref="TimeRange"/> class. /// </summary> /// <param name="original">Original TimeRange.</param> public TimeRange(TimeRange original) { Start = original.Start; End = original.End; } /// <summary> /// Gets or sets the time range start (in seconds). /// </summary> public double Start { get; set; } /// <summary> /// Gets or sets the time range end (in seconds). /// </summary> public double End { get; set; } /// <summary> /// Gets the duration of this time range (in seconds). /// </summary> public double Duration => End - Start; /// <summary> /// Compare TimeRange durations. /// </summary> /// <param name="obj">Object to compare with.</param> /// <returns>int.</returns> public int CompareTo(object? obj) { if (!(obj is TimeRange tr)) { throw new ArgumentException("obj must be a TimeRange"); } return tr.Duration.CompareTo(Duration); } /// <summary> /// Tests if this TimeRange object intersects the provided TimeRange. /// </summary> /// <param name="tr">Second TimeRange object to test.</param> /// <returns>true if tr intersects the current TimeRange, false otherwise.</returns> public bool Intersects(TimeRange tr) { return (Start < tr.Start && tr.Start < End) || (Start < tr.End && tr.End < End); } } #pragma warning restore CA1036 /// <summary> /// Time range helpers. /// </summary> public static class TimeRangeHelpers { /// <summary> /// Finds the longest contiguous time range. /// </summary> /// <param name="times">Sorted timestamps to search.</param> /// <param name="maximumDistance">Maximum distance permitted between contiguous timestamps.</param> /// <returns>The longest contiguous time range (if one was found), or null (if none was found).</returns> public static TimeRange? FindContiguous(double[] times, double maximumDistance) { if (times.Length == 0) { return null; } Array.Sort(times); var ranges = new List<TimeRange>(); var currentRange = new TimeRange(times[0], times[0]); // For all provided timestamps, check if it is contiguous with its neighbor. for (var i = 0; i < times.Length - 1; i++) { var current = times[i]; var next = times[i + 1]; if (next - current <= maximumDistance) { currentRange.End = next; continue; } ranges.Add(new TimeRange(currentRange)); currentRange = new TimeRange(next, next); } // Find and return the longest contiguous range. ranges.Sort(); return (ranges.Count > 0) ? ranges[0] : null; } }
411
0.791063
1
0.791063
game-dev
MEDIA
0.133911
game-dev
0.762416
1
0.762416
OvercastNetwork/SportBukkit
2,311
snapshot/Bukkit/src/main/java/org/bukkit/material/NetherWarts.java
package org.bukkit.material; import org.bukkit.Material; import org.bukkit.NetherWartsState; /** * Represents nether wart */ public class NetherWarts extends MaterialData { public NetherWarts() { super(Material.NETHER_WARTS); } public NetherWarts(NetherWartsState state) { this(); setState(state); } /** * @param type the raw type id * @deprecated Magic value */ @Deprecated public NetherWarts(final int type) { super(type); } public NetherWarts(final Material type) { super (type); } /** * @param type the raw type id * @param data the raw data value * @deprecated Magic value */ @Deprecated public NetherWarts(final int type, final byte data) { super(type, data); } /** * @param type the type * @param data the raw data value * @deprecated Magic value */ @Deprecated public NetherWarts(final Material type, final byte data) { super(type, data); } /** * Gets the current growth state of this nether wart * * @return NetherWartsState of this nether wart */ public NetherWartsState getState() { switch (getData()) { case 0: return NetherWartsState.SEEDED; case 1: return NetherWartsState.STAGE_ONE; case 2: return NetherWartsState.STAGE_TWO; default: return NetherWartsState.RIPE; } } /** * Sets the growth state of this nether wart * * @param state New growth state of this nether wart */ public void setState(NetherWartsState state) { switch (state) { case SEEDED: setData((byte) 0x0); return; case STAGE_ONE: setData((byte) 0x1); return; case STAGE_TWO: setData((byte) 0x2); return; case RIPE: setData((byte) 0x3); return; } } @Override public String toString() { return getState() + " " + super.toString(); } @Override public NetherWarts clone() { return (NetherWarts) super.clone(); } }
411
0.592349
1
0.592349
game-dev
MEDIA
0.978368
game-dev
0.913568
1
0.913568
quiverteam/Engine
5,312
src/thirdparty/bullet/src/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_TRIANGLE_INDEX_VERTEX_ARRAY_H #define BT_TRIANGLE_INDEX_VERTEX_ARRAY_H #include "btStridingMeshInterface.h" #include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btScalar.h" ///The btIndexedMesh indexes a single vertex and index array. Multiple btIndexedMesh objects can be passed into a btTriangleIndexVertexArray using addIndexedMesh. ///Instead of the number of indices, we pass the number of triangles. ATTRIBUTE_ALIGNED16( struct) btIndexedMesh { BT_DECLARE_ALIGNED_ALLOCATOR(); int m_numTriangles; const unsigned char * m_triangleIndexBase; // Size in byte of the indices for one triangle (3*sizeof(index_type) if the indices are tightly packed) int m_triangleIndexStride; int m_numVertices; const unsigned char * m_vertexBase; // Size of a vertex, in bytes int m_vertexStride; // The index type is set when adding an indexed mesh to the // btTriangleIndexVertexArray, do not set it manually PHY_ScalarType m_indexType; // The vertex type has a default type similar to Bullet's precision mode (float or double) // but can be set manually if you for example run Bullet with double precision but have // mesh data in single precision.. PHY_ScalarType m_vertexType; btIndexedMesh() :m_indexType(PHY_INTEGER), #ifdef BT_USE_DOUBLE_PRECISION m_vertexType(PHY_DOUBLE) #else // BT_USE_DOUBLE_PRECISION m_vertexType(PHY_FLOAT) #endif // BT_USE_DOUBLE_PRECISION { } } ; typedef btAlignedObjectArray<btIndexedMesh> IndexedMeshArray; ///The btTriangleIndexVertexArray allows to access multiple triangle meshes, by indexing into existing triangle/index arrays. ///Additional meshes can be added using addIndexedMesh ///No duplcate is made of the vertex/index data, it only indexes into external vertex/index arrays. ///So keep those arrays around during the lifetime of this btTriangleIndexVertexArray. ATTRIBUTE_ALIGNED16( class) btTriangleIndexVertexArray : public btStridingMeshInterface { protected: IndexedMeshArray m_indexedMeshes; int m_pad[2]; mutable int m_hasAabb; // using int instead of bool to maintain alignment mutable btVector3 m_aabbMin; mutable btVector3 m_aabbMax; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btTriangleIndexVertexArray() : m_hasAabb(0) { } virtual ~btTriangleIndexVertexArray(); //just to be backwards compatible btTriangleIndexVertexArray(int numTriangles, int* triangleIndexBase, int triangleIndexStride, int numVertices, btScalar* vertexBase, int vertexStride); void addIndexedMesh(const btIndexedMesh& mesh, PHY_ScalarType indexType = PHY_INTEGER) { m_indexedMeshes.push_back(mesh); m_indexedMeshes[m_indexedMeshes.size()-1].m_indexType = indexType; } virtual void getLockedVertexIndexBase(unsigned char **vertexbase, int& numverts, PHY_ScalarType& type, int& vertexStride, unsigned char **indexbase, int & indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart=0); virtual void getLockedReadOnlyVertexIndexBase(const unsigned char **vertexbase, int& numverts, PHY_ScalarType& type, int& vertexStride, const unsigned char **indexbase, int & indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart=0) const; /// unLockVertexBase finishes the access to a subpart of the triangle mesh /// make a call to unLockVertexBase when the read and write access (using getLockedVertexIndexBase) is finished virtual void unLockVertexBase(int subpart) {(void)subpart;} virtual void unLockReadOnlyVertexBase(int subpart) const {(void)subpart;} /// getNumSubParts returns the number of seperate subparts /// each subpart has a continuous array of vertices and indices virtual int getNumSubParts() const { return (int)m_indexedMeshes.size(); } IndexedMeshArray& getIndexedMeshArray() { return m_indexedMeshes; } const IndexedMeshArray& getIndexedMeshArray() const { return m_indexedMeshes; } virtual void preallocateVertices(int numverts){(void) numverts;} virtual void preallocateIndices(int numindices){(void) numindices;} virtual bool hasPremadeAabb() const; virtual void setPremadeAabb(const btVector3& aabbMin, const btVector3& aabbMax ) const; virtual void getPremadeAabb(btVector3* aabbMin, btVector3* aabbMax ) const; } ; #endif //BT_TRIANGLE_INDEX_VERTEX_ARRAY_H
411
0.961968
1
0.961968
game-dev
MEDIA
0.86913
game-dev
0.914794
1
0.914794
its-danny/xibalba
1,563
core/src/me/dannytatom/xibalba/utils/CameraShake.java
package me.dannytatom.xibalba.utils; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.math.Vector2; import java.util.Random; import me.dannytatom.xibalba.Main; public class CameraShake { public float time; private Random random; private float currentTime; private float power; private float currentPower; /** * https://carelesslabs.wordpress.com/2014/05/08/simple-screen-shake/comment-page-1/ */ public CameraShake() { time = 0; currentTime = 0; power = 0; currentPower = 0; } /** * Start shakin', boys. * * @param power Force of the shake * @param time How long it should last */ public void shake(float power, float time) { random = new Random(); this.power = power; this.time = time; this.currentTime = 0; } /** * Called each frame to handle the shaking. * * @param delta Time since last frame * @param camera Camera to shake * @param position Position to snap back to afterwards */ public void update(float delta, Camera camera, Vector2 position) { if (currentTime <= time) { currentPower = power * ((time - currentTime) / time); float posX = (random.nextFloat() - 0.5f) * 2 * currentPower; float posY = (random.nextFloat() - 0.5f) * 2 * currentPower; camera.translate(-posX, -posY, 0); currentTime += delta; } else { time = 0; currentTime = 0; camera.position.set( position.x * Main.SPRITE_WIDTH, position.y * Main.SPRITE_HEIGHT, 0 ); } } }
411
0.784501
1
0.784501
game-dev
MEDIA
0.888151
game-dev
0.94072
1
0.94072
Fluorohydride/ygopro-scripts
3,056
c55537983.lua
--Mimighoul Master local s,id,o=GetID() function s.initial_effect(c) --indestructable local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetValue(1) e1:SetCondition(s.indescon) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) c:RegisterEffect(e2) --search local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,0)) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_SUMMON_SUCCESS) e3:SetProperty(EFFECT_FLAG_DELAY) e3:SetCountLimit(1,id) e3:SetTarget(s.thtg) e3:SetOperation(s.thop) c:RegisterEffect(e3) local e4=e3:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) --change pos local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(id,1)) e5:SetCategory(CATEGORY_POSITION) e5:SetType(EFFECT_TYPE_QUICK_O) e5:SetCode(EVENT_FREE_CHAIN) e5:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_MAIN_END) e5:SetRange(LOCATION_MZONE) e5:SetCountLimit(1,id+o) e5:SetCondition(s.poscon) e5:SetTarget(s.postg) e5:SetOperation(s.posop) c:RegisterEffect(e5) end function s.cfilter1(c) return c:IsFaceup() and c:IsSetCard(0x1b7) and not c:IsCode(id) end function s.cfilter2(c) return c:IsFacedown() end function s.indescon(e) local tp=e:GetHandlerPlayer() return Duel.IsExistingMatchingCard(s.cfilter1,tp,LOCATION_MZONE,0,1,nil) or Duel.IsExistingMatchingCard(s.cfilter2,tp,0,LOCATION_MZONE,1,nil) end function s.thfilter(c) return c:IsSetCard(0x1b7) and c:IsType(TYPE_MONSTER) and not c:IsCode(id) and c:IsAbleToHand() end function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.Hint(HINT_OPSELECTED,1-tp,aux.Stringid(id,0)) Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function s.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function s.poscon(e,tp,eg,ep,ev,re,r,rp) local ph=Duel.GetCurrentPhase() return Duel.GetTurnPlayer()~=tp and (ph==PHASE_MAIN1 or ph==PHASE_MAIN2) end function s.filter(c) return c:IsType(TYPE_MONSTER) and c:IsFacedown() and c:IsDefensePos() end function s.postg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_OPSELECTED,1-tp,aux.Stringid(id,1)) Duel.SetOperationInfo(0,CATEGORY_POSITION,nil,1,0,0) end function s.posop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE) local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) local tc=g:GetFirst() if tc then Duel.HintSelection(g) local pos=Duel.SelectPosition(tp,tc,POS_FACEUP) Duel.ChangePosition(tc,pos) end end
411
0.890194
1
0.890194
game-dev
MEDIA
0.988269
game-dev
0.973955
1
0.973955
MaxOhn/Bathbot
3,080
bathbot-util/src/query/impls/regular.rs
use std::borrow::Cow; use super::{display_range, display_text}; use crate::query::{ IFilterCriteria, operator::Operator, optional::{OptionalRange, OptionalText}, }; #[derive(Default)] pub struct RegularCriteria<'q> { pub stars: OptionalRange<f32>, pub ar: OptionalRange<f32>, pub cs: OptionalRange<f32>, pub hp: OptionalRange<f32>, pub od: OptionalRange<f32>, pub length: OptionalRange<f32>, pub bpm: OptionalRange<f32>, pub keys: OptionalRange<f32>, pub artist: OptionalText<'q>, pub creator: OptionalText<'q>, pub title: OptionalText<'q>, } impl<'q> IFilterCriteria<'q> for RegularCriteria<'q> { fn try_parse_key_value( &mut self, key: Cow<'q, str>, value: Cow<'q, str>, op: Operator, ) -> bool { match key.as_ref() { "star" | "stars" => self.stars.try_update(op, &value, 0.005), "ar" => self.ar.try_update(op, &value, 0.005), "dr" | "hp" => self.hp.try_update(op, &value, 0.005), "cs" => self.cs.try_update(op, &value, 0.005), "od" => self.od.try_update(op, &value, 0.005), "bpm" => self.bpm.try_update(op, &value, 0.05), "length" | "len" => super::try_update_len(&mut self.length, op, &value), "creator" | "mapper" => self.creator.try_update(op, value), "artist" => self.artist.try_update(op, value), "title" => self.title.try_update(op, value), "key" | "keys" => self.keys.try_update(op, &value, 0.5), _ => false, } } fn any_field(&self) -> bool { let Self { stars, ar, cs, hp, od, length, bpm, keys, artist, creator, title, } = self; !(stars.is_empty() && ar.is_empty() && cs.is_empty() && hp.is_empty() && od.is_empty() && length.is_empty() && bpm.is_empty() && keys.is_empty() && artist.is_empty() && creator.is_empty() && title.is_empty()) } fn display(&self, content: &mut String) { let Self { stars, ar, cs, hp, od, length, bpm, keys, artist, creator, title, } = self; display_range(content, "AR", ar); display_range(content, "CS", cs); display_range(content, "HP", hp); display_range(content, "OD", od); display_range(content, "Length", length); display_range(content, "Stars", stars); display_range(content, "BPM", bpm); display_range(content, "Keys", keys); display_range(content, "AR", ar); display_range(content, "AR", ar); display_text(content, "Artist", artist); display_text(content, "Title", title); display_text(content, "Creator", creator); } }
411
0.771382
1
0.771382
game-dev
MEDIA
0.683516
game-dev
0.662956
1
0.662956
unikotoast/buns-bunny-survivor
2,063
weapons/unused/cat.lua
cat = nil cat_attack =false cat_attack_timer = 60 cat_attack_x = 0 cat_attack_y = 0 cat_flip = false function put_cat() if (cat == nil) then cat = {} cat.x = playerx cat.y = playery else aoe_damage(x1,y1+24, 14+4*w_lightning,6+3*w_damage+4*w_lightning,51336) for e in all(bugs) do if (cat_attack) then if (cat_attack_timer % 20 == 0) then if is_point_in_rect(e.pos.x, e.pos.y,cat.x-24,cat.y-24,cat.x+24,cat.y+24) then --local death = {x=e.pos.x, y=e.pos.y,duration=9,timer=9,sprite=133 } -- add(death_animations,death) add_timed_anim(133,e.pos.x,e.pos.y,3,9) deal_damage(e, 10) end end else if is_point_in_rect(e.pos.x, e.pos.y,cat.x-12,cat.y-12,cat.x+12,cat.y+12) then cat_attack = true cat_attack_x = cat.x - 8 cat_attack_y = cat.y - 8 end end end end end function draw_cat() if (cat) then if (cat_attack) then spr(148, cat.x,cat.y, 1, 1, cat_flip, false) else spr(132, cat.x,cat.y) end end --for enemy in all(bget(bugstore, point(cat.x,cat.y))) do -- if (enemy) then -- sspr(40,64,8, 8, enemy.pos.x,enemy.pos.y, 24, 24, false, false) -- end --end -- if (cat_attack) then -- if (cat_attack_timer % 20 == 0) then -- cat_attack_sprite_timer = 15 -- cat_attack_x = cat.x - 8 + rnd(16) -- cat_attack_y = cat.y - 8 + rnd(16) -- cat_flip = rnd({true, false}) -- cat_flip_y = rnd({true, false}) -- cat.x =cat_attack_x -- cat.y =cat_attack_y -- -- end -- -- cat_attack_sprite_timer -= 1 -- -- if (cat_attack_sprite_timer > 10) then -- sspr(40,64,8, 8, cat_attack_x,cat_attack_y, 20,20, cat_flip, cat_flip_y) -- elseif (cat_attack_sprite_timer > 4) then -- sspr(48,64,8, 8, cat_attack_x,cat_attack_y, 20,20, cat_flip, cat_flip_y) -- elseif (cat_attack_sprite_timer > 0) then -- sspr(56,64,8, 8, cat_attack_x,cat_attack_y, 20,20, cat_flip, cat_flip_y) -- -- end -- -- -- if (cat_attack_timer == 0) then -- cat_attack = false -- cat = nil -- cat_attack_timer = 60*w_cat.lvl -- end -- -- -- -- cat_attack_timer -= 1 -- end end
411
0.504633
1
0.504633
game-dev
MEDIA
0.946354
game-dev
0.634559
1
0.634559
emileb/OpenGames
8,770
opengames/src/main/jni/Doom/gzdoom-g1.8.6/src/g_strife/a_strifeitems.cpp
/* #include "info.h" #include "a_pickups.h" #include "d_player.h" #include "gstrings.h" #include "p_local.h" #include "p_spec.h" #include "a_strifeglobal.h" #include "p_lnspec.h" #include "p_enemy.h" #include "s_sound.h" #include "d_event.h" #include "a_keys.h" #include "c_console.h" #include "templates.h" #include "thingdef/thingdef.h" #include "g_level.h" #include "doomstat.h" */ // Degnin Ore --------------------------------------------------------------- IMPLEMENT_CLASS(ADegninOre) DEFINE_ACTION_FUNCTION(AActor, A_RemoveForceField) { self->flags &= ~MF_SPECIAL; for (int i = 0; i < self->Sector->linecount; ++i) { line_t *line = self->Sector->lines[i]; if (line->backsector != NULL && line->special == ForceField) { line->flags &= ~(ML_BLOCKING|ML_BLOCKEVERYTHING); line->special = 0; line->sidedef[0]->SetTexture(side_t::mid, FNullTextureID()); line->sidedef[1]->SetTexture(side_t::mid, FNullTextureID()); } } } bool ADegninOre::Use (bool pickup) { if (pickup) { return false; } else { AInventory *drop; // Increase the amount by one so that when DropInventory decrements it, // the actor will have the same number of beacons that he started with. // When we return to UseInventory, it will take care of decrementing // Amount again and disposing of this item if there are no more. Amount++; drop = Owner->DropInventory (this); if (drop == NULL) { Amount--; return false; } return true; } } // Health Training ---------------------------------------------------------- class AHealthTraining : public AInventory { DECLARE_CLASS (AHealthTraining, AInventory) public: bool TryPickup (AActor *&toucher); }; IMPLEMENT_CLASS (AHealthTraining) bool AHealthTraining::TryPickup (AActor *&toucher) { if (Super::TryPickup (toucher)) { toucher->GiveInventoryType (PClass::FindClass("GunTraining")); AInventory *coin = Spawn<ACoin> (0,0,0, NO_REPLACE); if (coin != NULL) { coin->Amount = toucher->player->mo->accuracy*5 + 300; if (!coin->CallTryPickup (toucher)) { coin->Destroy (); } } return true; } return false; } // Scanner ------------------------------------------------------------------ class AScanner : public APowerupGiver { DECLARE_CLASS (AScanner, APowerupGiver) public: bool Use (bool pickup); }; IMPLEMENT_CLASS (AScanner) bool AScanner::Use (bool pickup) { if (!(level.flags2 & LEVEL2_ALLMAP)) { if (Owner->CheckLocalView (consoleplayer)) { C_MidPrint(SmallFont, GStrings("TXT_NEEDMAP")); } return false; } return Super::Use (pickup); } // Prison Pass -------------------------------------------------------------- class APrisonPass : public AKey { DECLARE_CLASS (APrisonPass, AKey) public: bool TryPickup (AActor *&toucher); bool SpecialDropAction (AActor *dropper); }; IMPLEMENT_CLASS (APrisonPass) bool APrisonPass::TryPickup (AActor *&toucher) { Super::TryPickup (toucher); EV_DoDoor (DDoor::doorOpen, NULL, toucher, 223, 2*FRACUNIT, 0, 0, 0); toucher->GiveInventoryType (QuestItemClasses[9]); return true; } //============================================================================ // // APrisonPass :: SpecialDropAction // // Trying to make a monster that drops a prison pass turns it into an // OpenDoor223 item instead. That means the only way to get it in Strife // is through dialog, which is why it doesn't have its own sprite. // //============================================================================ bool APrisonPass::SpecialDropAction (AActor *dropper) { EV_DoDoor (DDoor::doorOpen, NULL, dropper, 223, 2*FRACUNIT, 0, 0, 0); Destroy (); return true; } //--------------------------------------------------------------------------- // Dummy items. They are just used by Strife to perform --------------------- // actions and cannot be held. ---------------------------------------------- //--------------------------------------------------------------------------- IMPLEMENT_CLASS (ADummyStrifeItem) // Sound the alarm! --------------------------------------------------------- class ARaiseAlarm : public ADummyStrifeItem { DECLARE_CLASS (ARaiseAlarm, ADummyStrifeItem) public: bool TryPickup (AActor *&toucher); bool SpecialDropAction (AActor *dropper); }; IMPLEMENT_CLASS (ARaiseAlarm) bool ARaiseAlarm::TryPickup (AActor *&toucher) { P_NoiseAlert (toucher, toucher); CALL_ACTION(A_WakeOracleSpectre, toucher); GoAwayAndDie (); return true; } bool ARaiseAlarm::SpecialDropAction (AActor *dropper) { P_NoiseAlert (dropper->target, dropper->target); if (dropper->target->CheckLocalView (consoleplayer)) { Printf ("You Fool! You've set off the alarm.\n"); } Destroy (); return true; } // Open door tag 222 -------------------------------------------------------- class AOpenDoor222 : public ADummyStrifeItem { DECLARE_CLASS (AOpenDoor222, ADummyStrifeItem) public: bool TryPickup (AActor *&toucher); }; IMPLEMENT_CLASS (AOpenDoor222) bool AOpenDoor222::TryPickup (AActor *&toucher) { EV_DoDoor (DDoor::doorOpen, NULL, toucher, 222, 2*FRACUNIT, 0, 0, 0); GoAwayAndDie (); return true; } // Close door tag 222 ------------------------------------------------------- class ACloseDoor222 : public ADummyStrifeItem { DECLARE_CLASS (ACloseDoor222, ADummyStrifeItem) public: bool TryPickup (AActor *&toucher); bool SpecialDropAction (AActor *dropper); }; IMPLEMENT_CLASS (ACloseDoor222) bool ACloseDoor222::TryPickup (AActor *&toucher) { EV_DoDoor (DDoor::doorClose, NULL, toucher, 222, 2*FRACUNIT, 0, 0, 0); GoAwayAndDie (); return true; } bool ACloseDoor222::SpecialDropAction (AActor *dropper) { EV_DoDoor (DDoor::doorClose, NULL, dropper, 222, 2*FRACUNIT, 0, 0, 0); if (dropper->target->CheckLocalView (consoleplayer)) { Printf ("You're dead! You set off the alarm.\n"); } P_NoiseAlert (dropper->target, dropper->target); Destroy (); return true; } // Open door tag 224 -------------------------------------------------------- class AOpenDoor224 : public ADummyStrifeItem { DECLARE_CLASS (AOpenDoor224, ADummyStrifeItem) public: bool TryPickup (AActor *&toucher); bool SpecialDropAction (AActor *dropper); }; IMPLEMENT_CLASS (AOpenDoor224) bool AOpenDoor224::TryPickup (AActor *&toucher) { EV_DoDoor (DDoor::doorOpen, NULL, toucher, 224, 2*FRACUNIT, 0, 0, 0); GoAwayAndDie (); return true; } bool AOpenDoor224::SpecialDropAction (AActor *dropper) { EV_DoDoor (DDoor::doorOpen, NULL, dropper, 224, 2*FRACUNIT, 0, 0, 0); Destroy (); return true; } // Ammo --------------------------------------------------------------------- class AAmmoFillup : public ADummyStrifeItem { DECLARE_CLASS (AAmmoFillup, ADummyStrifeItem) public: bool TryPickup (AActor *&toucher); }; IMPLEMENT_CLASS (AAmmoFillup) bool AAmmoFillup::TryPickup (AActor *&toucher) { const PClass * clip = PClass::FindClass(NAME_ClipOfBullets); if (clip != NULL) { AInventory *item = toucher->FindInventory(clip); if (item == NULL) { item = toucher->GiveInventoryType (clip); if (item != NULL) { item->Amount = 50; } } else if (item->Amount < 50) { item->Amount = 50; } else { return false; } GoAwayAndDie (); } return true; } // Health ------------------------------------------------------------------- class AHealthFillup : public ADummyStrifeItem { DECLARE_CLASS (AHealthFillup, ADummyStrifeItem) public: bool TryPickup (AActor *&toucher); }; IMPLEMENT_CLASS (AHealthFillup) bool AHealthFillup::TryPickup (AActor *&toucher) { static const int skillhealths[5] = { -100, -75, -50, -50, -100 }; int index = clamp<int>(gameskill, 0,4); if (!P_GiveBody (toucher, skillhealths[index])) { return false; } GoAwayAndDie (); return true; } // Upgrade Stamina ---------------------------------------------------------- IMPLEMENT_CLASS (AUpgradeStamina) bool AUpgradeStamina::TryPickup (AActor *&toucher) { if (toucher->player == NULL) return false; toucher->player->mo->stamina += Amount; if (toucher->player->mo->stamina >= MaxAmount) toucher->player->mo->stamina = MaxAmount; P_GiveBody (toucher, -100); GoAwayAndDie (); return true; } // Upgrade Accuracy --------------------------------------------------------- IMPLEMENT_CLASS (AUpgradeAccuracy) bool AUpgradeAccuracy::TryPickup (AActor *&toucher) { if (toucher->player == NULL || toucher->player->mo->accuracy >= 100) return false; toucher->player->mo->accuracy += 10; GoAwayAndDie (); return true; } // Start a slideshow -------------------------------------------------------- IMPLEMENT_CLASS (ASlideshowStarter) bool ASlideshowStarter::TryPickup (AActor *&toucher) { gameaction = ga_slideshow; if (level.levelnum == 10) { toucher->GiveInventoryType (QuestItemClasses[16]); } GoAwayAndDie (); return true; }
411
0.978838
1
0.978838
game-dev
MEDIA
0.981636
game-dev
0.974247
1
0.974247