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
JACoders/OpenJK
9,385
codeJK2/cgame/cg_servercmds.cpp
/* =========================================================================== Copyright (C) 1999 - 2005, Id Software, Inc. Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ // cg_servercmds.c -- text commands sent by the server #include "cg_local.h" #include "cg_media.h" #include "FxScheduler.h" /* ================ CG_ParseServerinfo This is called explicitly when the gamestate is first received, and whenever the server updates any serverinfo flagged cvars ================ */ void CG_ParseServerinfo( void ) { const char *info; const char *mapname; info = CG_ConfigString( CS_SERVERINFO ); cgs.dmflags = atoi( Info_ValueForKey( info, "dmflags" ) ); cgs.teamflags = atoi( Info_ValueForKey( info, "teamflags" ) ); cgs.timelimit = atoi( Info_ValueForKey( info, "timelimit" ) ); cgs.maxclients = 1; mapname = Info_ValueForKey( info, "mapname" ); Com_sprintf( cgs.mapname, sizeof( cgs.mapname ), "maps/%s.bsp", mapname ); const char *p = strrchr(mapname,'/'); Q_strncpyz( cgs.stripLevelName[0], p?p+1:mapname, sizeof(cgs.stripLevelName[0]) ); Q_strupr( cgs.stripLevelName[0] ); for (int i=1; i<STRIPED_LEVELNAME_VARIATIONS; i++) // clear retry-array { cgs.stripLevelName[i][0]='\0'; } // be careful with the []-numbers here. Currently I use 0,1,2 for replacements or substitution, and [3] for "INGAME" // I know, if I'd known there was going to be this much messing about I'd have subroutinised it all and done it // neater, but it kinda evolved... Feel free to bug me if you want to add to it... ? -Ste. // if (!cgi_SP_Register(cgs.stripLevelName[0], qfalse)) { // failed to load SP file, maybe it's one of the ones they renamed?... // if (!Q_stricmp(cgs.stripLevelName[0],"YAVIN_FINAL") || !Q_stricmp(cgs.stripLevelName[0],"YAVIN_SWAMP")) { Q_strncpyz( cgs.stripLevelName[0], "YAVIN_CANYON", sizeof(cgs.stripLevelName[0]) ); if (!cgi_SP_Register(cgs.stripLevelName[0], qfalse)) { // failed again, give up for now... // } } else if (!Q_stricmp(cgs.stripLevelName[0],"YAVIN_TRIAL")) { Q_strncpyz( cgs.stripLevelName[0], "YAVIN_TEMPLE", sizeof(cgs.stripLevelName[0]) ); if (!cgi_SP_Register(cgs.stripLevelName[0], qfalse)) { // failed again, give up for now... // } } else if (!Q_stricmp(cgs.stripLevelName[0],"VALLEY")) { Q_strncpyz( cgs.stripLevelName[0], "ARTUS_TOPSIDE", sizeof(cgs.stripLevelName[0]) ); if (!cgi_SP_Register(cgs.stripLevelName[0], qfalse)) { // failed again, give up for now... // } } } else { // additional SP files needed for some levels... // if (!Q_stricmp(cgs.stripLevelName[0],"KEJIM_BASE") || !Q_stricmp(cgs.stripLevelName[0],"KEJIM_POST") ) { Q_strncpyz( cgs.stripLevelName[1], "ARTUS_MINE", sizeof(cgs.stripLevelName[1]) ); if (!cgi_SP_Register(cgs.stripLevelName[1], qfalse)) { // failed again, give up for now... // } } if (!Q_stricmp(cgs.stripLevelName[0],"DOOM_DETENTION") || !Q_stricmp(cgs.stripLevelName[0],"DOOM_SHIELDS") ) { Q_strncpyz( cgs.stripLevelName[1], "DOOM_COMM", sizeof(cgs.stripLevelName[1]) ); if (!cgi_SP_Register(cgs.stripLevelName[1], qfalse)) { // failed again, give up for now... // } } if (!Q_stricmp(cgs.stripLevelName[0],"DOOM_COMM")) { Q_strncpyz( cgs.stripLevelName[1], "CAIRN_BAY", sizeof(cgs.stripLevelName[1]) ); if (!cgi_SP_Register(cgs.stripLevelName[1], qfalse)) { // failed again, give up for now... // } } if (!Q_stricmp(cgs.stripLevelName[0],"NS_STARPAD")) { Q_strncpyz( cgs.stripLevelName[1], "ARTUS_TOPSIDE", sizeof(cgs.stripLevelName[1]) ); // for dream sequence... if (!cgi_SP_Register(cgs.stripLevelName[1], qfalse)) { // failed again, give up for now... // } Q_strncpyz( cgs.stripLevelName[2], "BESPIN_UNDERCITY", sizeof(cgs.stripLevelName[1]) ); // for dream sequence... if (!cgi_SP_Register(cgs.stripLevelName[2], qfalse)) { // failed again, give up for now... // } } if (!Q_stricmp(cgs.stripLevelName[0],"BESPIN_PLATFORM")) { Q_strncpyz( cgs.stripLevelName[1], "BESPIN_UNDERCITY", sizeof(cgs.stripLevelName[1]) ); if (!cgi_SP_Register(cgs.stripLevelName[1], qfalse)) { // failed again, give up for now... // } } } } /* ================ CG_ConfigStringModified ================ */ void CG_RegisterClientModels (int entityNum); extern void cgi_R_WorldEffectCommand( const char *command ); static void CG_ConfigStringModified( void ) { const char *str; int num; num = atoi( CG_Argv( 1 ) ); // get the gamestate from the client system, which will have the // new configstring already integrated cgi_GetGameState( &cgs.gameState ); // look up the individual string that was modified str = CG_ConfigString( num ); // do something with it if necessary if ( num == CS_ITEMS ) { int i; for ( i = 1 ; i < bg_numItems ; i++ ) { if ( str[ i ] == '1' ) { if (bg_itemlist[i].classname) { CG_RegisterItemSounds( i ); CG_RegisterItemVisuals( i ); } } } } else if ( num == CS_MUSIC ) { CG_StartMusic( qtrue ); } else if ( num == CS_SERVERINFO ) { CG_ParseServerinfo(); } else if ( num >= CS_MODELS && num < CS_MODELS+MAX_MODELS ) { cgs.model_draw[ num-CS_MODELS ] = cgi_R_RegisterModel( str ); // OutputDebugString(va("### CG_ConfigStringModified(): cgs.model_draw[%d] = \"%s\"\n",num-CS_MODELS,str)); // GHOUL2 Insert start } else if ( num >= CS_CHARSKINS && num < CS_CHARSKINS+MAX_CHARSKINS ) { cgs.skins[ num-CS_CHARSKINS ] = cgi_R_RegisterSkin( str ); // Ghoul2 Insert end } else if ( num >= CS_SOUNDS && num < CS_SOUNDS+MAX_SOUNDS ) { if ( str[0] != '*' ) { cgs.sound_precache[ num-CS_SOUNDS] = cgi_S_RegisterSound( str ); } } else if ( num >= CS_EFFECTS && num < CS_EFFECTS + MAX_FX ) { theFxScheduler.RegisterEffect( str ); } else if ( num >= CS_PLAYERS && num < CS_PLAYERS+MAX_CLIENTS ) { CG_NewClientinfo( num - CS_PLAYERS ); CG_RegisterClientModels( num - CS_PLAYERS ); } else if ( num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES*3)) { CG_SetLightstyle(num - CS_LIGHT_STYLES); } else if ( num >= CS_WORLD_FX && num < CS_WORLD_FX + MAX_WORLD_FX ) { cgi_R_WorldEffectCommand( str ); } } static void CG_CenterPrint_f( void ) { CG_CenterPrint( CG_Argv( 1 ), SCREEN_HEIGHT * 0.25 ); } static void CG_Print_f( void ) { CG_Printf( "%s", CG_Argv( 1 ) ); } static void CG_CaptionText_f( void ) { sfxHandle_t sound = (sfxHandle_t)atoi( CG_Argv( 2 ) ); CG_CaptionText( CG_Argv( 1 ), sound >= 0 && sound < MAX_SOUNDS ? cgs.sound_precache[sound] : NULL_SOUND ); } static void CG_ScrollText_f( void ) { CG_ScrollText( CG_Argv( 1 ), SCREEN_WIDTH - 16 ); } static void CG_LCARSText_f( void ) { CG_Printf( "CG_LCARSText() being called. Tell Ste\n" "String: \"%s\"\n", CG_Argv( 1 ) ); } static void CG_ClientLevelShot_f( void ) { // clientLevelShot is sent before taking a special screenshot for // the menu system during development cg.levelShot = qtrue; } typedef struct serverCommand_s { const char *cmd; void( *func )(void); } serverCommand_t; static int svcmdcmp( const void *a, const void *b ) { return Q_stricmp( (const char *)a, ((serverCommand_t*)b)->cmd ); } /* This array MUST be sorted correctly by alphabetical name field */ static serverCommand_t commands[] = { { "chat", CG_Print_f }, { "clientLevelShot", CG_ClientLevelShot_f }, { "cp", CG_CenterPrint_f }, { "cs", CG_ConfigStringModified }, { "ct", CG_CaptionText_f }, { "cts", CG_CaptionTextStop }, { "lt", CG_LCARSText_f }, { "print", CG_Print_f }, { "st", CG_ScrollText_f }, }; static const size_t numCommands = ARRAY_LEN( commands ); /* ================= CG_ServerCommand The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ static void CG_ServerCommand( void ) { const char *cmd = CG_Argv( 0 ); serverCommand_t *command = NULL; if ( !cmd[0] ) { // server claimed the command return; } command = (serverCommand_t *)Q_LinearSearch( cmd, commands, numCommands, sizeof( commands[0] ), svcmdcmp ); if ( command ) { command->func(); return; } CG_Printf( "Unknown client game command: %s\n", cmd ); } /* ==================== CG_ExecuteNewServerCommands Execute all of the server commands that were received along with this this snapshot. ==================== */ void CG_ExecuteNewServerCommands( int latestSequence ) { while ( cgs.serverCommandSequence < latestSequence ) { if ( cgi_GetServerCommand( ++cgs.serverCommandSequence ) ) { CG_ServerCommand(); } } }
1
0.932649
1
0.932649
game-dev
MEDIA
0.887722
game-dev
0.90769
1
0.90769
google/google-ctf
14,566
2025/hackceler8/rounds/7/game/build.rs
use std::env::current_dir; use std::path::PathBuf; use convert::GamePalette; /// Gets the repository root pub fn repository_root_dir() -> PathBuf { let cwd = current_dir().expect("Could not find own path"); let root = cwd .join("../") .canonicalize() .expect("Could not get parent directory"); assert!( root.join("game").is_dir(), "We're in the wrong folder! Make sure you run convert in ./targets/<debug/release>. Ended up in {root:?} | {:?}", std::env::current_dir() ); root } /// The root the output resources (as rust files) are written to pub fn output_dir() -> PathBuf { repository_root_dir().join("game/src/res").to_path_buf() } /// Input resources pub fn resources_root() -> PathBuf { repository_root_dir().join("resources").to_path_buf() } fn main() -> Result<(), Box<dyn std::error::Error>> { // Monitor resources and rerun build.rs if needed. println!("cargo::rerun-if-changed=../resources"); let mut converter = convert::Converter::new(output_dir()); // List of static images. let image_list = [ ( resources_root().join("ui/text.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/heart.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/health-bar.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/flag.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/inventory-border.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/inventory-border-selected.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/inventory-text.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/choice-arrow.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/text-arrow.png"), &GamePalette::UI.global(), ), ( resources_root().join("ui/game-over.png"), &GamePalette::UI.global(), ), ]; // List of sprites. Do not use map tilesets here. let sprite_list = [ ( resources_root().join("sprites/player/player-base.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team1.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team2.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team3.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team4.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team5.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team6.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team7.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/player-team8.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-base.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team1.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team2.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team3.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team4.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team5.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team6.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team7.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/player/hat-team8.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/switch.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/items/heart-item.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/items/key.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/items/goggles.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/items/sword.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/items/boots.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/crown.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/items/cloak.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/fall.tsx"), &GamePalette::Player.global(), ), ( resources_root().join("sprites/grey-door-h.tsx"), &GamePalette::Background.for_world("overworld"), ), ( resources_root().join("sprites/grey-door-v.tsx"), &GamePalette::Background.for_world("overworld"), ), ( resources_root().join("sprites/rabbit.tsx"), &GamePalette::Enemy.for_world("overworld"), ), ( resources_root().join("sprites/dog-npc.tsx"), &GamePalette::Enemy.for_world("overworld"), ), ( resources_root().join("sprites/blue-door-h.tsx"), &GamePalette::Background.for_world("water-temple"), ), ( resources_root().join("sprites/blue-door-v.tsx"), &GamePalette::Background.for_world("water-temple"), ), ( resources_root().join("sprites/octopus.tsx"), &GamePalette::Enemy.for_world("water-temple"), ), ( resources_root().join("sprites/siren.tsx"), &GamePalette::Enemy.for_world("water-temple"), ), ( resources_root().join("sprites/duck-npc.tsx"), &GamePalette::Enemy.for_world("water-temple"), ), ( resources_root().join("sprites/green-door-h.tsx"), &GamePalette::Background.for_world("forest-temple"), ), ( resources_root().join("sprites/green-door-v.tsx"), &GamePalette::Background.for_world("forest-temple"), ), ( resources_root().join("sprites/orc.tsx"), &GamePalette::Enemy.for_world("forest-temple"), ), ( resources_root().join("sprites/goblin.tsx"), &GamePalette::Enemy.for_world("forest-temple"), ), ( resources_root().join("sprites/racoon-npc.tsx"), &GamePalette::Enemy.for_world("forest-temple"), ), ( resources_root().join("sprites/red-door-h.tsx"), &GamePalette::Background.for_world("fire-temple"), ), ( resources_root().join("sprites/red-door-v.tsx"), &GamePalette::Background.for_world("fire-temple"), ), ( resources_root().join("sprites/chest-npc.tsx"), &GamePalette::Background.for_world("fire-temple"), ), ( resources_root().join("sprites/mimic-npc.tsx"), &GamePalette::Background.for_world("fire-temple"), ), ( resources_root().join("sprites/blob.tsx"), &GamePalette::Enemy.for_world("fire-temple"), ), ( resources_root().join("sprites/flameboi.tsx"), &GamePalette::Enemy.for_world("fire-temple"), ), ( resources_root().join("sprites/cat-npc.tsx"), &GamePalette::Enemy.for_world("fire-temple"), ), ( resources_root().join("sprites/fireball.tsx"), &GamePalette::Enemy.for_world("fire-temple"), ), ( resources_root().join("sprites/white-door-h.tsx"), &GamePalette::Background.for_world("sky-temple"), ), ( resources_root().join("sprites/white-door-v.tsx"), &GamePalette::Background.for_world("sky-temple"), ), ( resources_root().join("sprites/archer.tsx"), &GamePalette::Enemy.for_world("sky-temple"), ), ( resources_root().join("sprites/angel.tsx"), &GamePalette::Enemy.for_world("sky-temple"), ), ( resources_root().join("sprites/snake-npc.tsx"), &GamePalette::Enemy.for_world("sky-temple"), ), ( resources_root().join("sprites/arrow.tsx"), &GamePalette::Enemy.for_world("sky-temple"), ), ( resources_root().join("sprites/boss.tsx"), &GamePalette::Enemy.for_world("boss-temple"), ), ( resources_root().join("sprites/swirl.tsx"), &GamePalette::Enemy.for_world("boss-temple"), ), ( resources_root().join("sprites/angel-minion.tsx"), &GamePalette::Enemy.for_world("boss-temple"), ), ( resources_root().join("sprites/orc-minion.tsx"), &GamePalette::Enemy.for_world("boss-temple"), ), ( resources_root().join("sprites/explosion.tsx"), &GamePalette::Enemy.for_world("boss-temple"), ), ]; // List of worlds. let overworld = convert::World::new( resources_root() .join("maps") .join("overworld") .join("overworld.world"), "overworld".to_string(), ) .expect("Loading overworld failed"); let fire_temple = convert::World::new( resources_root() .join("maps") .join("fire-temple") .join("fire-temple.world"), "fire-temple".to_string(), ) .expect("Loading fire-temple failed"); let forest_temple = convert::World::new( resources_root() .join("maps") .join("forest-temple") .join("forest-temple.world"), "forest-temple".to_string(), ) .expect("Loading forest-temple failed"); let water_temple = convert::World::new( resources_root() .join("maps") .join("water-temple") .join("water-temple.world"), "water-temple".to_string(), ) .expect("Loading water-temple failed"); let sky_temple = convert::World::new( resources_root() .join("maps") .join("sky-temple") .join("sky-temple.world"), "sky-temple".to_string(), ) .expect("Loading water-temple failed"); let boss_temple = convert::World::new( resources_root() .join("maps") .join("boss-temple") .join("boss-temple.world"), "boss-temple".to_string(), ) .expect("Loading boss-temple failed"); // Remove previous directory if it exists. let _ = std::fs::remove_dir_all(output_dir()); std::fs::create_dir_all(output_dir())?; // Convert all static images. for (file, palette_id) in image_list { converter .convert_image(file, palette_id) .expect("Converting {file} failed"); } // Convert all sprites. for (file, palette_id) in sprite_list { if let Some(extension) = file.extension() { match extension.to_str().unwrap() { "tsx" => { converter.convert_sprite(&file, palette_id)?; } val => { panic!("Bad file suffix {val}, only tsx files are expected."); } } } else { panic!("No file suffix!") } } // Convert worlds. converter .convert_world(&overworld) .expect("Converting overworld failed"); converter .convert_world(&fire_temple) .expect("Converting fire temple failed"); converter .convert_world(&forest_temple) .expect("Converting forest temple failed"); converter .convert_world(&sky_temple) .expect("Converting sky temple failed"); converter .convert_world(&water_temple) .expect("Converting water temple failed"); converter .convert_world(&boss_temple) .expect("Converting boss temple failed"); converter .write_palettes(output_dir().join("palettes.rs")) .expect("Writing palettes failed"); converter .write_sprite_mod(output_dir().join("sprites/mod.rs")) .expect("Writing sprites/mod.rs failed"); converter .write_tilesets_mod(output_dir().join("tileset/mod.rs")) .expect("Writing tileset/mod.rs failed"); converter .write_image_mod(output_dir().join("images/mod.rs")) .expect("Writing images/mod.rs failed"); converter .write_map_mod(output_dir().join("maps/mod.rs")) .expect("Writing maps/mod.rs failed"); converter .write_main_mod(output_dir().join("mod.rs")) .expect("Writing mod.rs failed"); converter .write_enemies(output_dir().join("enemies.rs")) .expect("Writing enemies.rs failed"); converter .write_npcs(output_dir().join("npcs.rs")) .expect("Writing npcs.rs failed"); converter .write_items(output_dir().join("items.rs")) .expect("Writing items.rs failed"); Ok(()) }
1
0.583522
1
0.583522
game-dev
MEDIA
0.971843
game-dev
0.537579
1
0.537579
cryfs/cryfs
1,037
src/blobstore/interface/BlobStore.h
#pragma once #ifndef MESSMER_BLOBSTORE_INTERFACE_BLOBSTORE_H_ #define MESSMER_BLOBSTORE_INTERFACE_BLOBSTORE_H_ #include "Blob.h" #include <string> #include <memory> #include <blockstore/utils/BlockId.h> #include <cpp-utils/pointer/unique_ref.h> namespace blobstore { //TODO Remove this interface. We'll only use BlobStoreOnBlocks and never a different one. Rename BlobStoreOnBlocks to simply BlobStore. class BlobStore { public: virtual ~BlobStore() {} virtual cpputils::unique_ref<Blob> create() = 0; virtual boost::optional<cpputils::unique_ref<Blob>> load(const blockstore::BlockId &blockId) = 0; virtual void remove(cpputils::unique_ref<Blob> blob) = 0; virtual void remove(const blockstore::BlockId &blockId) = 0; virtual uint64_t numBlocks() const = 0; virtual uint64_t estimateSpaceForNumBlocksLeft() const = 0; //virtual means "space we can use" as opposed to "space it takes on the disk" (i.e. virtual is without headers, checksums, ...) virtual uint64_t virtualBlocksizeBytes() const = 0; }; } #endif
1
0.870786
1
0.870786
game-dev
MEDIA
0.593228
game-dev
0.674221
1
0.674221
OpenNefia/OpenNefia
1,908
OpenNefia.Content/DebugView/Controls/NewMapDialog.xaml.cs
using OpenNefia.Content.Maps; using OpenNefia.Content.Prototypes; using OpenNefia.Core.Game; using OpenNefia.Core.GameObjects; using OpenNefia.Core.IoC; using OpenNefia.Core.Maps; using OpenNefia.Core.UI.Wisp.Controls; using OpenNefia.Core.UI.Wisp.CustomControls; using OpenNefia.Core.UserInterface.XAML; namespace OpenNefia.Content.DebugView { public partial class NewMapDialog : DefaultWindow { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IEntityManager _entityManager = default!; [Dependency] private readonly IMapTransferSystem _mapTransfer = default!; [Dependency] private readonly IGameSessionManager _gameSession = default!; public NewMapDialog() { EntitySystem.InjectDependencies(this); OpenNefiaXamlLoader.Load(this); OKButton.OnPressed += OnOKButtonPressed; CancelButton.OnPressed += OnCancelButtonPressed; } private void OnOKButtonPressed(BaseButton.ButtonEventArgs obj) { // TODO number control... var widthStr = WidthLineEdit.Text; var heightStr = HeightLineEdit.Text; if (!int.TryParse(widthStr, out var width) || !int.TryParse(heightStr, out var height) || width < 1 || height < 1) return; var map = _mapManager.CreateMap(width, height); foreach (var tile in map.AllTiles) map.SetTile(tile.Position, Protos.Tile.Grass); var player = _gameSession.Player; var spatial = _entityManager.GetComponent<SpatialComponent>(player); _mapTransfer.DoMapTransfer(spatial, map, new CenterMapLocation(), MapLoadType.Full); Close(); } private void OnCancelButtonPressed(BaseButton.ButtonEventArgs obj) { Close(); } } }
1
0.760554
1
0.760554
game-dev
MEDIA
0.632267
game-dev,desktop-app
0.933184
1
0.933184
enz/pentobi
2,195
libpentobi_mcts/AnalyzeGame.h
//----------------------------------------------------------------------------- /** @file libpentobi_mcts/AnalyzeGame.h @author Markus Enzenberger @copyright GNU General Public License version 3 or later */ //----------------------------------------------------------------------------- #ifndef LIBPENTOBI_MCTS_ANALYZE_GAME_H #define LIBPENTOBI_MCTS_ANALYZE_GAME_H #include <functional> #include <vector> #include "libpentobi_base/Game.h" namespace libpentobi_mcts { class Search; using namespace std; using libpentobi_base::ColorMove; using libpentobi_base::Game; using libpentobi_base::Variant; //----------------------------------------------------------------------------- /** Evaluate each position in the main variation of a game. */ class AnalyzeGame { public: void clear(); /** Run the analysis. The analysis can be aborted from a different thread with Search::abort(). @param game @param search @param nu_simulations @param progress_callback Function that will be called at the beginning of the analysis of each position. */ void run(const Game& game, Search& search, size_t nu_simulations, const function<void()>& progress_callback); Variant get_variant() const; unsigned get_nu_moves() const; ColorMove get_move(unsigned i) const; double get_value(unsigned i) const; void set(Variant variant, const vector<ColorMove>& moves, const vector<double>& values); private: Variant m_variant; vector<ColorMove> m_moves; vector<double> m_values; }; inline ColorMove AnalyzeGame::get_move(unsigned i) const { LIBBOARDGAME_ASSERT(i < m_moves.size()); return m_moves[i]; } inline unsigned AnalyzeGame::get_nu_moves() const { return static_cast<unsigned>(m_moves.size()); } inline double AnalyzeGame::get_value(unsigned i) const { LIBBOARDGAME_ASSERT(i < m_values.size()); return m_values[i]; } inline Variant AnalyzeGame::get_variant() const { return m_variant; } //----------------------------------------------------------------------------- } // namespace libpentobi_mcts #endif // LIBPENTOBI_MCTS_ANALYZE_GAME_H
1
0.80401
1
0.80401
game-dev
MEDIA
0.605884
game-dev
0.634829
1
0.634829
Poobslag/turbofat
1,569
project/src/demo/editor/creature-old/tweak-eye-row.gd
extends HBoxContainer ## UI control for tweaking a creature's eye color. ## ## The eye uses two different colors, and requires a specialized tool. export (NodePath) var creature_editor_path: NodePath onready var _creature_editor: CreatureEditorOld = get_node(creature_editor_path) func _ready() -> void: _creature_editor.connect("center_creature_changed", self, "_on_CreatureEditor_center_creature_changed") ## Update the creature with the player's chosen eye color. func _on_Edit_color_changed(_color: Color) -> void: _creature_editor.center_creature.dna["eye_rgb_0"] = $Edit1.color.to_html(false).to_lower() _creature_editor.center_creature.dna["eye_rgb_1"] = $Edit2.color.to_html(false).to_lower() _creature_editor.center_creature.refresh_dna() func _on_Edit_popup_closed() -> void: Pauser.toggle_pause("creature-editor", false) func _on_Edit_pressed() -> void: Pauser.toggle_pause("creature-editor", true) func _on_GrayDna_pressed() -> void: _creature_editor.tweak_all_creatures("eye_rgb_0", CreatureEditorOld.SIMILAR_COLORS) func _on_PurpleDna_pressed() -> void: _creature_editor.tweak_all_creatures("eye_rgb_0", CreatureEditorOld.THEME_COLORS) func _on_RainbowDna_pressed() -> void: _creature_editor.tweak_all_creatures("eye_rgb_0", CreatureEditorOld.RANDOM_COLORS) ## Update the color picker buttons with the creature's eye color. func _on_CreatureEditor_center_creature_changed() -> void: $Edit1.color = Color(_creature_editor.center_creature.dna["eye_rgb_0"]) $Edit2.color = Color(_creature_editor.center_creature.dna["eye_rgb_1"])
1
0.861553
1
0.861553
game-dev
MEDIA
0.633277
game-dev
0.935835
1
0.935835
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
4,491
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/SWAT.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2021 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.actors.mobs; import static com.shatteredpixel.shatteredpixeldungeon.Dungeon.depth; import com.shatteredpixel.shatteredpixeldungeon.Badges; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.Statistics; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Light; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.alchemy.HG_T6; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.alchemy.SR_T6; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.gun.MG.MG_T5; import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.sprites.SWATSprite; import com.watabou.utils.Random; public class SWAT extends Mob { { spriteClass = SWATSprite.class; HP = HT = 150; defenseSkill = 20; viewDistance = Light.DISTANCE; EXP = 15; maxLvl = 30; lootChance = 1; } public enum SWATWeapon { HANDGUN, SNIPER, MACHINEGUN } public SWATWeapon swatWeapon = Random.oneOf(SWATWeapon.HANDGUN, SWATWeapon.SNIPER, SWATWeapon.MACHINEGUN); @Override public int damageRoll() { int dmg; switch (swatWeapon) { case HANDGUN: default: dmg = Random.NormalIntRange( 40, 50 ); break; case SNIPER: dmg = Random.NormalIntRange( 60, 90 ); break; case MACHINEGUN: dmg = Random.NormalIntRange( 10, 30 ); break; } return dmg; } @Override public float speed() { switch (swatWeapon) { case HANDGUN: default: return super.speed()*2f; case SNIPER: return super.speed(); case MACHINEGUN: return super.speed()*0.5f; } } @Override public int attackSkill( Char target ) { int accuracy; switch (swatWeapon) { case HANDGUN: default: accuracy = 45; break; case SNIPER: accuracy = 60; break; case MACHINEGUN: accuracy = 20; break; } return accuracy; } @Override public int drRoll() { return Random.NormalIntRange(5, 20); } @Override public float attackDelay() { if (swatWeapon == SWATWeapon.SNIPER) { return super.attackDelay()*3f; } else if (swatWeapon == SWATWeapon.HANDGUN) { return super.attackDelay()*0.5f; } else { return super.attackDelay()*0.333f; } } @Override protected boolean canAttack( Char enemy ) { Ballistica attack = new Ballistica( pos, enemy.pos, Ballistica.PROJECTILE); return !Dungeon.level.adjacent( pos, enemy.pos ) && attack.collisionPos == enemy.pos; } @Override protected boolean getCloser( int target ) { if (state == HUNTING) { return enemySeen && getFurther( target ); } else { return super.getCloser( target ); } } @Override public void aggro(Char ch) { //cannot be aggroed to something it can't see if (ch == null || fieldOfView == null || fieldOfView[ch.pos]) { super.aggro(ch); } } @Override public Item createLoot(){ if (depth == 30) { return null; } else { switch (swatWeapon) { case HANDGUN: default: return new HG_T6().upgrade(Random.Int(1, 4)); case SNIPER: return new SR_T6().upgrade(Random.Int(1, 4)); case MACHINEGUN: return new MG_T5().upgrade(Random.Int(1, 4)); } } } @Override public String description() { switch (swatWeapon) { case HANDGUN: default: return Messages.get(this, "handgun_desc"); case SNIPER: return Messages.get(this, "sniper_desc"); case MACHINEGUN: return Messages.get(this, "machinegun_desc"); } } }
1
0.884375
1
0.884375
game-dev
MEDIA
0.99615
game-dev
0.985394
1
0.985394
OpenXRay/xray-15
2,734
cs/sdk/sources/MagicSoftware/FreeMagic/Include/MgcCommand.h
// Magic Software, Inc. // http://www.magic-software.com // Copyright (c) 2000-2002. All Rights Reserved // // Source code from Magic Software is supplied under the terms of a license // agreement and may not be copied or disclosed except in accordance with the // terms of that agreement. The various license agreements may be found at // the Magic Software web site. This file is subject to the license // // FREE SOURCE CODE // http://www.magic-software.com/License/free.pdf #ifndef MGCCOMMAND_H #define MGCCOMMAND_H #include "MagicFMLibType.h" namespace Mgc { class MAGICFM Command { public: Command (int iQuantity, char** apcArgument); Command (char* acCmdline); ~Command (); // return value is index of first excess argument int ExcessArguments (); // Set bounds for numerical arguments. If bounds are required, they must // be set for each argument. Command& Min (double dValue); Command& Max (double dValue); Command& Inf (double dValue); Command& Sup (double dValue); // The return value of the following methods is the option index within // the argument array. // Use the boolean methods for options which take no argument, for // example in // myprogram -debug -x 10 -y 20 filename // the option -debug has no argument. int Boolean (char* acName); // returns existence of option int Boolean (char* acName, bool& rbValue); int Integer (char* acName, int& riValue); int Float (char* acName, float& rfValue); int Double (char* acName, double& rdValue); int String (char* acName, char*& racValue); int Filename (char*& racName); // last error reporting const char* GetLastError (); protected: // constructor support void Initialize (); // command line information int m_iQuantity; // number of arguments char** m_apcArgument; // argument list (array of strings) char* m_acCmdline; // argument list (single string) bool* m_abUsed; // keeps track of arguments already processed // parameters for bounds checking double m_dSmall; // lower bound for numerical argument (min or inf) double m_dLarge; // upper bound for numerical argument (max or sup) bool m_bMinSet; // if true, compare: small <= arg bool m_bMaxSet; // if true, compare: arg <= large bool m_bInfSet; // if true, compare: small < arg bool m_bSupSet; // if true, compare: arg < large // last error strings const char* m_acLastError; static char ms_acOptionNotFound[]; static char ms_acArgumentRequired[]; static char ms_acArgumentOutOfRange[]; static char ms_acFilenameNotFound[]; }; } // namespace Mgc #endif
1
0.640929
1
0.640929
game-dev
MEDIA
0.442493
game-dev
0.599191
1
0.599191
indilib/indi
10,115
drivers/telescope/astrotrac.h
/******************************************************************************* Copyright(c) 2021 Jasem Mutlaq. All rights reserved. AstroTrac Mount Driver. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. . 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 Library General Public License for more details. . You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *******************************************************************************/ #pragma once #include "inditelescope.h" #include "indiguiderinterface.h" #include "alignment/AlignmentSubsystemForDrivers.h" #include "indipropertynumber.h" #include "indipropertytext.h" #include "indipropertyswitch.h" #include "indielapsedtimer.h" class AstroTrac : public INDI::Telescope, public INDI::GuiderInterface, public INDI::AlignmentSubsystem::AlignmentSubsystemForDrivers { public: AstroTrac(); virtual ~AstroTrac() = default; virtual const char *getDefaultName() override; virtual bool Handshake() override; virtual bool ReadScopeStatus() override; virtual void ISGetProperties(const char *dev) override; virtual bool initProperties() override; virtual bool updateProperties() override; virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override; virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override; virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override; virtual bool ISNewBLOB(const char *dev, const char *name, int sizes[], int blobsizes[], char *blobs[], char *formats[], char *names[], int n) override; protected: // Motion virtual bool MoveNS(INDI_DIR_NS dir, TelescopeMotionCommand command) override; virtual bool MoveWE(INDI_DIR_WE dir, TelescopeMotionCommand command) override; virtual bool Abort() override; // Time & Location virtual bool updateLocation(double latitude, double longitude, double elevation) override; virtual bool updateTime(ln_date *utc, double utc_offset) override; // GOTO & SYNC virtual bool Goto(double ra, double dec) override; virtual bool Sync(double ra, double dec) override; // Tracking virtual bool SetTrackMode(uint8_t mode) override; virtual bool SetTrackRate(double raRate, double deRate) override; virtual bool SetTrackEnabled(bool enabled) override; // Parking virtual bool SetCurrentPark() override; virtual bool SetDefaultPark() override; virtual bool Park() override; virtual bool UnPark() override; // Guiding virtual IPState GuideNorth(uint32_t ms) override; virtual IPState GuideSouth(uint32_t ms) override; virtual IPState GuideEast(uint32_t ms) override; virtual IPState GuideWest(uint32_t ms) override; // Simulation virtual void simulationTriggered(bool enable) override; // Config items virtual bool saveConfigItems(FILE *fp) override; private: /////////////////////////////////////////////////////////////////////////////////////////////// /// Utility /////////////////////////////////////////////////////////////////////////////////////////////// bool getVersion(); void getRADEFromEncoders(double haEncoder, double deEncoder, double &ra, double &de, TelescopePierSide &pierSide); void getEncodersFromRADE(double ra, double de, double &raEncoder, double &deEncoder); double calculateSlewTime(double distance); bool getTelescopeFromSkyCoordinates(double ra, double de, INDI::IEquatorialCoordinates &telescopeCoordinates); /////////////////////////////////////////////////////////////////////////////////////////////// /// Acceleration /////////////////////////////////////////////////////////////////////////////////////////////// bool getAcceleration(INDI_EQ_AXIS axis); bool setAcceleration(INDI_EQ_AXIS axis, uint32_t a); /////////////////////////////////////////////////////////////////////////////////////////////// /// Velocity /////////////////////////////////////////////////////////////////////////////////////////////// bool getVelocity(INDI_EQ_AXIS axis); bool getVelocity(INDI_EQ_AXIS axis, double &value); /** * @brief setVelocity set motor velocity * @param axis Motor axis * @param v velocity in arcsec/sec * @return bool if successful, false otherwise. */ bool setVelocity(INDI_EQ_AXIS axis, double value); bool getMaximumSlewVelocity(); /////////////////////////////////////////////////////////////////////////////////////////////// /// GOTO & SYNC /////////////////////////////////////////////////////////////////////////////////////////////// bool isSlewComplete(); bool syncEncoder(INDI_EQ_AXIS axis, double value); bool slewEncoder(INDI_EQ_AXIS axis, double value); bool getEncoderPosition(INDI_EQ_AXIS axis); bool stopMotion(INDI_EQ_AXIS axis); /////////////////////////////////////////////////////////////////////////////////////////////// /// Communication /////////////////////////////////////////////////////////////////////////////////////////////// /** * @brief sendCommand Send a string command to device. * @param cmd Command to be sent. Can be either NULL TERMINATED or just byte buffer. * @param res If not nullptr, the function will wait for a response from the device. If nullptr, it returns true immediately * after the command is successfully sent. * @param cmd_len if -1, it is assumed that the @a cmd is a null-terminated string. Otherwise, it would write @a cmd_len bytes from * the @a cmd buffer. * @param res_len if -1 and if @a res is not nullptr, the function will read until it detects the default delimiter DRIVER_STOP_CHAR * up to DRIVER_LEN length. Otherwise, the function will read @a res_len from the device and store it in @a res. * @return True if successful, false otherwise. */ bool sendCommand(const char * cmd, char * res = nullptr, int cmd_len = -1, int res_len = -1); void hexDump(char * buf, const char * data, int size); std::vector<std::string> split(const std::string &input, const std::string &regex); /////////////////////////////////////////////////////////////////////////////////////////////// /// INDI Properties /////////////////////////////////////////////////////////////////////////////////////////////// // Mount Type INDI::PropertySwitch MountTypeSP {2}; enum { MOUNT_GEM, MOUNT_SINGLE_ARM }; // Guide Rate INDI::PropertyNumber GuideRateNP {2}; // Firmware Version INDI::PropertyText FirmwareTP {1}; // Acceleration INDI::PropertyNumber AccelerationNP {2}; // Encoders INDI::PropertyNumber EncoderNP {2}; /////////////////////////////////////////////////////////////////////////////////////////////// /// Simulation /////////////////////////////////////////////////////////////////////////////////////////////// struct { // -90 to + 90 degrees. double currentMechanicalHA {0}, targetMechanicalHA {0}; // -180 to +180 degrees. double currentMechanicalDE {0}, targetMechanicalDE {0}; // arcsec/sec double velocity[2] = {TRACKRATE_SIDEREAL, 0}; // arcsec/sec^2 uint32_t acceleration[2] = {3600, 3600}; // 1 Slewing, 0 Stopped uint8_t status[2] = {0, 0}; } SimData; INDI::ElapsedTimer m_SimulationTimer; // Process very simply mount simulation. No meridian flips. void simulateMount(); // Process basic commands. bool handleSimulationCommand(const char * cmd, char * res, int cmd_len, int res_len); /// Mount internal coordinates INDI::IEquatorialCoordinates m_MountInternalCoordinates; /////////////////////////////////////////////////////////////////////////////////////////////// /// Static Constants /////////////////////////////////////////////////////////////////////////////////////////////// // > is the stop char static const char DRIVER_STOP_CHAR { 0x3E }; // Wait up to a maximum of 3 seconds for serial input static constexpr const uint8_t DRIVER_TIMEOUT {3}; // Maximum buffer for sending/receiving. static constexpr const uint8_t DRIVER_LEN {64}; // Slew Modes static constexpr const uint8_t SLEW_MODES {10}; // Slew Speeds static const std::array<uint32_t, SLEW_MODES> SLEW_SPEEDS; // Maximum Slew Velocity. This cannot be set now so it's considered constant until until it can be altered. // arcsec/sec static constexpr double MAX_SLEW_VELOCITY {10800.0}; // Target threshold in degrees between mechanical target and current coordinates // If they are within 0.1 degrees, then we consider motion complete static constexpr double DIFF_THRESHOLD {0.1}; };
1
0.741112
1
0.741112
game-dev
MEDIA
0.695599
game-dev
0.555547
1
0.555547
AngleSharp/AngleSharp
3,198
src/AngleSharp/Dom/Internal/TokenList.cs
namespace AngleSharp.Dom { using AngleSharp.Common; using AngleSharp.Text; using System; using System.Collections; using System.Collections.Generic; /// <summary> /// A simple list of tokens that is immutable. /// </summary> class TokenList : ITokenList, IBindable { #region Fields private readonly List<String> _tokens; #endregion #region Events public event Action<String>? Changed; #endregion #region ctor internal TokenList(String? value) { _tokens = []; Update(value); } #endregion #region Index public String this[Int32 index] => _tokens[index]; #endregion #region Properties public Int32 Length => _tokens.Count; #endregion #region Methods public void Update(String? value) { _tokens.Clear(); if (value is { Length: > 0 }) { var elements = value.SplitSpaces(); for (var i = 0; i < elements.Length; i++) { if (!_tokens.Contains(elements[i])) { _tokens.Add(elements[i]); } } } } public Boolean Contains(String token) => _tokens.Contains(token); public void Remove(params String[] tokens) { var changed = false; foreach (var token in tokens) { if (_tokens.Contains(token)) { _tokens.Remove(token); changed = true; } } if (changed) { RaiseChanged(); } } public void Add(params String[] tokens) { var changed = false; foreach (var token in tokens) { if (!_tokens.Contains(token)) { _tokens.Add(token); changed = true; } } if (changed) { RaiseChanged(); } } public Boolean Toggle(String token, Boolean force = false) { var contains = _tokens.Contains(token); if (contains && force) { return true; } if (contains) { _tokens.Remove(token); } else { _tokens.Add(token); } RaiseChanged(); return !contains; } #endregion #region Helper private void RaiseChanged() => Changed?.Invoke(ToString()); #endregion #region IEnumerable Implementation public IEnumerator<String> GetEnumerator() => _tokens.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion #region String representation public override String ToString() => String.Join(" ", _tokens); #endregion } }
1
0.976794
1
0.976794
game-dev
MEDIA
0.747028
game-dev
0.971564
1
0.971564
prism/PrismRefracted
1,039
Prism/src/main/java/network/darkhelmet/prism/bridge/PrismBlockEditHandler.java
package network.darkhelmet.prism.bridge; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.event.extent.EditSessionEvent; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.util.eventbus.Subscribe; import network.darkhelmet.prism.ApiHandler; import org.bukkit.Bukkit; public class PrismBlockEditHandler { private final ApiHandler.WEType weType; public PrismBlockEditHandler(ApiHandler.WEType weType) { this.weType = weType; } /** * Wrap and edit session so it can be logged. * * @param event EditSessionEvent */ @Subscribe public void wrapForLogging(EditSessionEvent event) { if (!weType.shouldLog(event)) { return; } Actor actor = event.getActor(); org.bukkit.World world = Bukkit.getWorld(event.getWorld().getName()); if (actor != null && actor.isPlayer() && world != null) { event.setExtent(new PrismWorldEditLogger(actor, event.getExtent(), world)); } } }
1
0.609173
1
0.609173
game-dev
MEDIA
0.510296
game-dev
0.901028
1
0.901028
Dimbreath/AzurLaneData
11,249
zh-CN/controller/command/stage/chapteroproutine.lua
slot0 = class("ChapterOpRoutine", pm.SimpleCommand) function slot0.execute(slot0, slot1) end function slot0.initData(slot0, slot1, slot2, slot3) slot0.op = slot1 slot0.data = slot2 slot0.chapter = slot3 slot0.items = {} slot0.fullpath = nil slot0.flag = 0 end function slot0.doDropUpdate(slot0) slot0.items = PlayerConst.addTranDrop(slot0.data.drop_list) end function slot0.doMapUpdate(slot0) slot4 = slot0.chapter if #slot0.data.map_update > 0 then _.each(slot1.map_update, function (slot0) if slot0.item_type == ChapterConst.AttachStory and slot0.item_data == ChapterConst.StoryTrigger then if uv0:GetChapterCellAttachemnts()[ChapterCell.Line2Name(slot0.pos.row, slot0.pos.column)] then if slot3.flag == ChapterConst.CellFlagTriggerActive and slot0.item_flag == ChapterConst.CellFlagTriggerDisabled and pg.map_event_template[slot3.attachmentId].gametip ~= "" then pg.TipsMgr.GetInstance():ShowTips(i18n(slot4)) end slot3.attachment = slot0.item_type slot3.attachmentId = slot0.item_id slot3.flag = slot0.item_flag slot3.data = slot0.item_data else slot2[slot1] = ChapterCell.New(slot0) end elseif slot0.item_type ~= ChapterConst.AttachNone and slot0.item_type ~= ChapterConst.AttachBorn and slot0.item_type ~= ChapterConst.AttachBorn_Sub then uv0:mergeChapterCell(ChapterCell.New(slot0)) end end) slot2 = bit.bor(slot0.flag, ChapterConst.DirtyAttachment) slot3 = bit.bor(slot0.extraFlag or 0, ChapterConst.DirtyAutoAction) end slot0.flag = slot2 slot0.extraFlag = slot3 end function slot0.doCellFlagUpdate(slot0) slot3 = slot0.chapter if #slot0.data.cell_flag_list > 0 then _.each(slot1.cell_flag_list, function (slot0) if uv0:getChapterCell(slot0.pos.row, slot0.pos.column) then slot1:updateFlagList(slot0) else slot1 = ChapterCell.New(slot0) end uv1.chapter:updateChapterCell(slot1) end) slot2 = bit.bor(slot0.flag, ChapterConst.DirtyCellFlag) end slot0.flag = slot2 end function slot0.doAIUpdate(slot0) slot4 = slot0.chapter if #slot0.data.ai_list > 0 then _.each(slot1.ai_list, function (slot0) uv0:mergeChampion(ChapterChampionPackage.New(slot0)) end) slot2 = bit.bor(slot0.flag, ChapterConst.DirtyChampion) slot3 = bit.bor(slot0.extraFlag or 0, ChapterConst.DirtyAutoAction) end slot0.flag = slot2 slot0.extraFlag = slot3 end function slot0.doShipUpdate(slot0) slot4 = slot0.chapter.fleet if #slot0.data.ship_update > 0 then _.each(slot1.ship_update, function (slot0) if uv0:getShip(slot0.id) and slot1.hpRant * slot0.hp_rant == 0 and slot1:getShipType() == ShipType.WeiXiu then uv1 = bit.bor(uv1, ChapterConst.DirtyStrategy) end uv0:updateShipHp(slot0.id, slot0.hp_rant) end) slot2 = bit.bor(slot0.flag, ChapterConst.DirtyFleet) end slot0.flag = slot2 end function slot0.doBuffUpdate(slot0) slot0.chapter:UpdateBuffList(slot0.data.buff_list) end function slot0.doExtraFlagUpdate(slot0) if #slot0.data.add_flag_list > 0 or #slot1.del_flag_list > 0 then getProxy(ChapterProxy):updateExtraFlag(slot0.chapter, slot1.add_flag_list, slot1.del_flag_list) slot0.flag = bit.bor(slot0.flag, ChapterConst.DirtyFleet, ChapterConst.DirtyStrategy, ChapterConst.DirtyCellFlag, ChapterConst.DirtyFloatItems) end end function slot0.doRetreat(slot0) slot2 = slot0.data slot3 = slot0.flag slot4 = slot0.chapter if slot0.op.id then if #slot4.fleets > 0 then slot4.fleets = _.filter(slot4.fleets, function (slot0) return slot0.id ~= uv0.id end) if slot4.fleets[slot1.id] and slot5:getFleetType() == FleetType.Normal then slot4.findex = 1 end slot3 = bit.bor(slot3, ChapterConst.DirtyFleet, ChapterConst.DirtyAttachment, ChapterConst.DirtyChampion, ChapterConst.DirtyStrategy) end else slot4:retreat(slot1.win) slot3 = ChapterConst.DirtyMapItems end slot0.flag = slot3 end function slot0.doMove(slot0) slot1 = slot0.op slot3 = slot0.chapter slot4 = nil if #slot0.data.move_path > 0 then slot4 = _.map(_.rest(slot2.move_path, 1), function (slot0) return { row = slot0.row, column = slot0.column } end) end slot0.fullpath = slot4 slot3:IncreaseRound() end function slot0.doOpenBox(slot0) slot3 = slot0.chapter slot5 = slot3.fleet.line slot6 = slot3:getChapterCell(slot5.row, slot5.column) slot6.flag = ChapterConst.CellFlagDisabled slot3:updateChapterCell(slot6) if pg.box_data_template[slot6.attachmentId].type == ChapterConst.BoxStrategy then slot8 = slot7.effect_id slot9 = slot7.effect_arg slot4:achievedStrategy(slot8, slot9) table.insert(slot0.items, Item.New({ type = DROP_TYPE_STRATEGY, id = slot8, count = slot9 })) slot2 = bit.bor(bit.bor(slot0.flag, ChapterConst.DirtyAttachment), ChapterConst.DirtyStrategy) elseif slot7.type == ChapterConst.BoxSupply then slot8, slot9 = slot3:getFleetAmmo(slot4) slot4.restAmmo = slot4.restAmmo + math.min(slot8 - slot9, slot7.effect_id) slot2 = bit.bor(slot2, ChapterConst.DirtyFleet) pg.TipsMgr.GetInstance():ShowTips(i18n("level_ammo_supply_p1", slot7.effect_id)) end slot0.flag = slot2 end function slot0.doPlayStory(slot0) slot2 = slot0.chapter slot4 = slot2.fleet.line slot5 = slot2:getChapterCell(slot4.row, slot4.column) slot5.flag = ChapterConst.CellFlagDisabled slot2:updateChapterCell(slot5) slot0.flag = bit.bor(slot0.flag, ChapterConst.DirtyAttachment) end function slot0.doAmbush(slot0) if slot0.op.arg1 == 1 then slot4 = slot0.chapter.fleet.line if slot2:getChapterCell(slot4.row, slot4.column).flag == ChapterConst.CellFlagAmbush then slot2:clearChapterCell(slot4.row, slot4.column) end pg.TipsMgr.GetInstance():ShowTips(slot5.flag == ChapterConst.CellFlagActive and i18n("chapter_tip_aovid_failed") or i18n("chapter_tip_aovid_succeed")) end end function slot0.doStrategy(slot0) slot1 = slot0.flag slot4 = slot0.chapter.fleet if pg.strategy_data_template[slot0.op.arg1].type == ChapterConst.StgTypeForm then for slot9, slot10 in ipairs(slot4.stgIds) do if pg.strategy_data_template[slot10].type == ChapterConst.StgTypeForm then slot4.stgIds[slot9] = slot5.id end end PlayerPrefs.SetInt("team_formation_" .. slot4.id, slot5.id) pg.TipsMgr.GetInstance():ShowTips(i18n("chapter_tip_change", slot5.name)) elseif slot5.type == ChapterConst.StgTypeConsume then slot4:consumeOneStrategy(slot5.id) pg.TipsMgr.GetInstance():ShowTips(i18n("chapter_tip_use", slot5.name)) end if slot5.id == ChapterConst.StrategyExchange then slot6 = slot3:getFleetById(slot2.id) slot7 = slot3:getFleetById(slot2.arg2) slot7.line = slot6.line slot6.line = slot7.line slot1 = bit.bor(slot1, ChapterConst.DirtyFleet) end slot0.flag = bit.bor(slot1, ChapterConst.DirtyStrategy) end function slot0.doRepair(slot0) slot1 = getProxy(ChapterProxy) slot1.repairTimes = slot1.repairTimes + 1 slot2, slot3, slot4 = ChapterConst.GetRepairParams() if slot2 < slot1.repairTimes then slot5 = getProxy(PlayerProxy) slot6 = slot5:getData() slot6:consume({ gem = slot4 }) slot5:updatePlayer(slot6) end end function slot0.doSupply(slot0) slot1 = slot0.flag slot2 = slot0.chapter slot3 = slot2.fleet slot4, slot5 = slot2:getFleetAmmo(slot3) slot6 = slot3.line slot7 = slot2:getChapterCell(slot6.row, slot6.column) slot8 = math.min(slot7.attachmentId, slot4 - slot5) slot7.attachmentId = slot7.attachmentId - slot8 slot3.restAmmo = slot3.restAmmo + slot8 slot2:updateChapterCell(slot7) if slot7.attachmentId > 20 then pg.TipsMgr.GetInstance():ShowTips(i18n("level_ammo_supply_p1", slot8)) elseif slot7.attachmentId > 0 then pg.TipsMgr.GetInstance():ShowTips(i18n("level_ammo_supply", slot8, slot7.attachmentId)) else pg.TipsMgr.GetInstance():ShowTips(i18n("level_ammo_empty", slot8)) end slot0.flag = bit.bor(slot1, ChapterConst.DirtyAttachment, ChapterConst.DirtyFleet) end function slot0.doSubState(slot0) slot0.chapter.subAutoAttack = slot0.op.arg1 slot0.flag = bit.bor(slot0.flag, ChapterConst.DirtyStrategy) end function slot0.doCollectAI(slot0) slot2 = slot0.flag slot3 = slot0.chapter slot0.aiActs = slot0.aiActs or {} if slot0.data.submarine_act_list then _.each(slot1.submarine_act_list, function (slot0) table.insert(uv0.aiActs, SubAIAction.New(slot0)) end) end if slot1.escort_act_list then _.each(slot1.escort_act_list, function (slot0) table.insert(uv0.aiActs, TransportAIAction.New(slot0)) end) end _.each(slot1.ai_act_list, function (slot0) table.insert(uv0.aiActs, ChapterAIAction.New(slot0)) end) _.each(slot1.fleet_act_list, function (slot0) table.insert(uv0.aiActs, FleetAIAction.New(slot0)) end) end function slot0.doBarrier(slot0) slot1 = slot0.flag slot2 = slot0.op slot3 = slot0.chapter slot6 = _.detect(pg.box_data_template.all, function (slot0) return pg.box_data_template[slot0].type == ChapterConst.BoxBarrier end) if slot3:getChapterCell(slot2.arg1, slot2.arg2).attachment ~= ChapterConst.AttachBox or slot4.attachmentId ~= slot6 then slot4.attachment = slot5 slot4.attachmentId = slot6 slot4.flag = ChapterConst.CellFlagDisabled end slot3.modelCount = slot3.modelCount + (slot4.flag == 1 and -1 or 1) slot4.flag = 1 - slot4.flag slot3:updateChapterCell(slot4) slot0.flag = bit.bor(slot1, ChapterConst.DirtyAttachment, ChapterConst.DirtyStrategy) end function slot0.doRequest(slot0) if #slot0.data.move_path > 0 then slot5 = slot1.move_path[#slot1.move_path] slot0.chapter.fleet.line = { row = slot5.row, column = slot5.column } slot2 = bit.bor(slot0.flag, ChapterConst.DirtyFleet) end slot0.flag = slot2 end function slot0.doSkipBattle(slot0) slot0.flag = bit.bor(slot0.flag, ChapterConst.DirtyStrategy, ChapterConst.DirtyAttachment, ChapterConst.DirtyAchieve, ChapterConst.DirtyFleet, ChapterConst.DirtyChampion) end function slot0.doTeleportSub(slot0) slot1 = slot0.op slot0.fullpath = { _.detect(slot0.chapter.fleets, function (slot0) return slot0.id == uv0.id end).startPos, { row = slot1.arg1, column = slot1.arg2 } } end function slot0.doEnemyRound(slot0) slot1 = slot0.chapter slot1:IncreaseRound() if slot1:getPlayType() == ChapterConst.TypeDefence then slot0.flag = bit.bor(slot0.flag, ChapterConst.DirtyAttachment) end end function slot0.doTeleportByPortal(slot0) if not (slot0.fullpath and slot0.fullpath[#slot0.fullpath]) then return end slot3 = nil if slot0.op.type == ChapterConst.OpMove then slot3 = slot0.chapter:GetCellEventByKey("jump", slot1.row, slot1.column) elseif slot0.op.type == ChapterConst.OpSubTeleport then slot3 = slot2:GetCellEventByKey("jumpsub", slot1.row, slot1.column) end if not slot3 then return end slot4 = { row = slot3[1], column = slot3[2] } if slot0.op.type == ChapterConst.OpMove and slot2:getFleet(FleetType.Normal, slot4.row, slot4.column) then return end slot0.teleportPaths = slot0.teleportPaths or {} table.insert(slot0.teleportPaths, { row = slot1.row, column = slot1.column }) table.insert(slot0.teleportPaths, slot4) end function slot0.doCollectCommonAction(slot0) slot0.aiActs = slot0.aiActs or {} table.insert(slot0.aiActs, ChapterCommonAction.New(slot0.op, slot0.data)) end return slot0
1
0.759073
1
0.759073
game-dev
MEDIA
0.936051
game-dev
0.913151
1
0.913151
HaHaWTH/HybridFix
1,865
src/main/java/io/wdsj/hybridfix/entry/bukkit/hook/worldguard/WGHookBlockFormListener.java
package io.wdsj.hybridfix.entry.bukkit.hook.worldguard; import com.sk89q.worldguard.bukkit.ConfigurationManager; import com.sk89q.worldguard.bukkit.WorldConfiguration; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.flags.DefaultFlag; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.Snowman; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockFormEvent; import org.bukkit.event.block.EntityBlockFormEvent; public class WGHookBlockFormListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) // Higher than WorldGuard public void onBlockForm(BlockFormEvent event) { WorldGuardPlugin plugin = WorldGuardPlugin.inst(); if (plugin == null) return; Block block = event.getBlock(); ConfigurationManager cfg = plugin.getGlobalStateManager(); WorldConfiguration wcfg = cfg.get(block.getWorld()); // Skip checks that have already been done by WorldGuard if (event instanceof EntityBlockFormEvent && ((EntityBlockFormEvent) event).getEntity() instanceof Snowman) return; final BlockState newBs = event.getNewState(); Material newType = newBs.getType(); if (newType == Material.SNOW || newType == Material.ICE || newType == Material.FROSTED_ICE) return; // End if (cfg.activityHaltToggle) { event.setCancelled(true); return; } if (wcfg.useRegions) { // noinspection deprecation if (!plugin.getGlobalRegionManager().allows(DefaultFlag.BLOCK_BREAK, block.getLocation())) { event.setCancelled(true); } } } }
1
0.643482
1
0.643482
game-dev
MEDIA
0.945201
game-dev
0.566368
1
0.566368
KoshakMineDEV/Lumi
2,308
src/main/java/cn/nukkit/block/BlockSlabStone3.java
package cn.nukkit.block; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.block.data.BlockColor; public class BlockSlabStone3 extends BlockSlab { public static final int END_STONE_BRICKS = 0; public static final int SMOOTH_RED_SANDSTONE = 1; public static final int POLISHED_ANDESITE = 2; public static final int ANDESITE = 3; public static final int DIORITE = 4; public static final int POLISHED_DIORITE = 5; public static final int GRANITE = 6; public static final int POLISHED_GRANITE = 7; public BlockSlabStone3() { this(0); } public BlockSlabStone3(int meta) { super(meta, DOUBLE_STONE_SLAB3); } @Override public int getId() { return STONE_SLAB3; } @Override public String getName() { String[] names = new String[]{ "End Stone Brick", "Smooth Red Sandstone", "Polished Andesite", "Andesite", "Diorite", "Polished Diorite", "Granite", "Polisehd Granite" }; return ((this.getDamage() & 0x08) > 0 ? "Upper " : "") + names[this.getDamage() & 0x07] + " Slab"; } @Override public BlockColor getColor() { switch (this.getDamage() & 0x07) { case END_STONE_BRICKS: return BlockColor.SAND_BLOCK_COLOR; case SMOOTH_RED_SANDSTONE: return BlockColor.ORANGE_BLOCK_COLOR; default: case POLISHED_ANDESITE: case ANDESITE: return BlockColor.STONE_BLOCK_COLOR; case DIORITE: case POLISHED_DIORITE: return BlockColor.QUARTZ_BLOCK_COLOR; case GRANITE: case POLISHED_GRANITE: return BlockColor.DIRT_BLOCK_COLOR; } } @Override public Item toItem() { return new ItemBlock(this, this.getDamage() & 0x07); } @Override public int getToolTier() { return ItemTool.TIER_WOODEN; } @Override public int getToolType() { return ItemTool.TYPE_PICKAXE; } @Override public boolean canHarvestWithHand() { return false; } }
1
0.646418
1
0.646418
game-dev
MEDIA
0.980367
game-dev
0.65513
1
0.65513
RaphiMC/ViaBedrock
1,568
src/main/java/net/raphimc/viabedrock/protocol/data/enums/bedrock/generated/AnimatePacket_Action.java
// THIS FILE IS AUTO-GENERATED. DO NOT EDIT! package net.raphimc.viabedrock.protocol.data.enums.bedrock.generated; import com.viaversion.viaversion.libs.fastutil.ints.Int2ObjectMap; import com.viaversion.viaversion.libs.fastutil.ints.Int2ObjectOpenHashMap; public enum AnimatePacket_Action { /** * Unused */ NoAction(0), /** * Server bound notification to swing the player's arm. Server is expected to rebroadcast to all that should see the arm move<br> * See also PlayerAuthInputPacket::InputData::MissedSwing for a very similar action */ Swing(1), /** * Client bound notification to stop sleeping in a bed */ WakeUp(3), /** * Client-bound notification to play critical hit particles */ CriticalHit(4), /** * Unused */ MagicCriticalHit(5); private static final Int2ObjectMap<AnimatePacket_Action> BY_VALUE = new Int2ObjectOpenHashMap<>(); static { for (AnimatePacket_Action value : values()) { if (!BY_VALUE.containsKey(value.value)) BY_VALUE.put(value.value, value); } } public static AnimatePacket_Action getByValue(final int value) { return BY_VALUE.get(value); } public static AnimatePacket_Action getByValue(final int value, final AnimatePacket_Action fallback) { return BY_VALUE.getOrDefault(value, fallback); } private final int value; AnimatePacket_Action(final int value) { this.value = value; } public int getValue() { return this.value; } }
1
0.500732
1
0.500732
game-dev
MEDIA
0.706121
game-dev,networking
0.8668
1
0.8668
showlab/BYOC
5,530
BlendshapeToolkit/Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_EditorResourceManager.cs
#if UNITY_EDITOR using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace TMPro { public class TMP_EditorResourceManager { private static TMP_EditorResourceManager s_Instance; private readonly List<Object> m_ObjectUpdateQueue = new List<Object>(); private HashSet<int> m_ObjectUpdateQueueLookup = new HashSet<int>(); private readonly List<Object> m_ObjectReImportQueue = new List<Object>(); private HashSet<int> m_ObjectReImportQueueLookup = new HashSet<int>(); private readonly List<TMP_FontAsset> m_FontAssetDefinitionRefreshQueue = new List<TMP_FontAsset>(); private HashSet<int> m_FontAssetDefinitionRefreshQueueLookup = new HashSet<int>(); /// <summary> /// Get a singleton instance of the manager. /// </summary> public static TMP_EditorResourceManager instance { get { if (s_Instance == null) s_Instance = new TMP_EditorResourceManager(); return s_Instance; } } /// <summary> /// Register to receive rendering callbacks. /// </summary> private TMP_EditorResourceManager() { Camera.onPostRender += OnCameraPostRender; Canvas.willRenderCanvases += OnPreRenderCanvases; } void OnCameraPostRender(Camera cam) { // Exclude the PreRenderCamera if (cam.cameraType != CameraType.SceneView) return; DoPostRenderUpdates(); } void OnPreRenderCanvases() { DoPreRenderUpdates(); } /// <summary> /// Register resource for re-import. /// </summary> /// <param name="obj"></param> internal static void RegisterResourceForReimport(Object obj) { instance.InternalRegisterResourceForReimport(obj); } private void InternalRegisterResourceForReimport(Object obj) { int id = obj.GetInstanceID(); if (m_ObjectReImportQueueLookup.Contains(id)) return; m_ObjectReImportQueueLookup.Add(id); m_ObjectReImportQueue.Add(obj); } /// <summary> /// Register resource to be updated. /// </summary> /// <param name="textObject"></param> internal static void RegisterResourceForUpdate(Object obj) { instance.InternalRegisterResourceForUpdate(obj); } private void InternalRegisterResourceForUpdate(Object obj) { int id = obj.GetInstanceID(); if (m_ObjectUpdateQueueLookup.Contains(id)) return; m_ObjectUpdateQueueLookup.Add(id); m_ObjectUpdateQueue.Add(obj); } /// <summary> /// /// </summary> /// <param name="fontAsset"></param> internal static void RegisterFontAssetForDefinitionRefresh(TMP_FontAsset fontAsset) { instance.InternalRegisterFontAssetForDefinitionRefresh(fontAsset); } private void InternalRegisterFontAssetForDefinitionRefresh(TMP_FontAsset fontAsset) { int id = fontAsset.GetInstanceID(); if (m_FontAssetDefinitionRefreshQueueLookup.Contains(id)) return; m_FontAssetDefinitionRefreshQueueLookup.Add(id); m_FontAssetDefinitionRefreshQueue.Add(fontAsset); } void DoPostRenderUpdates() { // Handle objects that need updating int objUpdateCount = m_ObjectUpdateQueue.Count; for (int i = 0; i < objUpdateCount; i++) { Object obj = m_ObjectUpdateQueue[i]; if (obj != null) { EditorUtility.SetDirty(obj); } } if (objUpdateCount > 0) { //Debug.Log("Saving assets"); //AssetDatabase.SaveAssets(); m_ObjectUpdateQueue.Clear(); m_ObjectUpdateQueueLookup.Clear(); } // Handle objects that need re-importing int objReImportCount = m_ObjectReImportQueue.Count; for (int i = 0; i < objReImportCount; i++) { Object obj = m_ObjectReImportQueue[i]; if (obj != null) { AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(obj)); } } if (objReImportCount > 0) { m_ObjectReImportQueue.Clear(); m_ObjectReImportQueueLookup.Clear(); } } void DoPreRenderUpdates() { // Handle Font Asset Definition Refresh for (int i = 0; i < m_FontAssetDefinitionRefreshQueue.Count; i++) { TMP_FontAsset fontAsset = m_FontAssetDefinitionRefreshQueue[i]; if (fontAsset != null) { fontAsset.ReadFontAssetDefinition(); TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset); } } if (m_FontAssetDefinitionRefreshQueue.Count > 0) { m_FontAssetDefinitionRefreshQueue.Clear(); m_FontAssetDefinitionRefreshQueueLookup.Clear(); } } } } #endif
1
0.911542
1
0.911542
game-dev
MEDIA
0.709809
game-dev
0.994408
1
0.994408
superwall/Superwall-iOS
1,615
Sources/SuperwallKit/Misc/Extensions/GCControllerElement+buttonName.swift
// // File.swift // // // Created by Yusuf Tör on 29/09/2022. // import GameController extension GCControllerElement { // the identifier of this gamecontroller element that is accepted by the paywall javascript event listeners func buttonName(gamepad: GCExtendedGamepad) -> String { switch self { case gamepad.leftTrigger: return "L2 Button" case gamepad.leftShoulder: return "L1 Button" case gamepad.rightTrigger: return "R2 Button" case gamepad.rightShoulder: return "R1 Button" case gamepad.leftThumbstick: return "Left Thumbstick" case gamepad.leftThumbstickButton: return "Left Thumbstick Button" case gamepad.rightThumbstick: return "Right Thumbstick" case gamepad.rightThumbstickButton: return "Right Thumbstick Button" case gamepad.dpad: return "Direction Pad" case gamepad.dpad.down: return "Direction Pad" case gamepad.dpad.right: return "Direction Pad" case gamepad.dpad.up: return "Direction Pad" case gamepad.dpad.left: return "Direction Pad" case gamepad.buttonA: return "A Button" case gamepad.buttonB: return "B Button" case gamepad.buttonX: return "X Button" case gamepad.buttonY: return "Y Button" case gamepad.buttonMenu: return "Menu Button" case gamepad.buttonOptions: return "Options Button" default: // Logger.debug(logLevel: .debug, scope: .gameControllerManager, message: "Unrecognized Button", info: ["button": element], error: nil) return "Unknown Button" } } }
1
0.880292
1
0.880292
game-dev
MEDIA
0.655073
game-dev
0.521886
1
0.521886
GMLambda/Lambda
6,673
gamemode/sh_lambda.lua
if SERVER then AddCSLuaFile() end LAMBDA_TEAM_CONNECTING = 1200 LAMBDA_TEAM_ALIVE = 1 LAMBDA_TEAM_DEAD = 2 LAMBDA_TEAM_SPECTATOR = 5 -- TDM Teams LAMBDA_TEAM_REBEL = 3 LAMBDA_TEAM_COMBINE = 4 DEATH_BYSELF = 1 DEATH_BYPLAYER = 2 DEATH_NORMAL = 3 DEATH_BYNPC = 4 DEATH_NPC = 5 sk_max_pistol = GetConVar("sk_max_pistol") sk_max_smg1 = GetConVar("sk_max_smg1") sk_max_smg1_grenade = GetConVar("sk_max_smg1_grenade") sk_max_357 = GetConVar("sk_max_357") sk_max_ar2 = GetConVar("sk_max_ar2") sk_max_ar2_altfire = GetConVar("sk_max_ar2_altfire") sk_max_buckshot = GetConVar("sk_max_buckshot") sk_max_crossbow = GetConVar("sk_max_crossbow") sk_max_grenade = GetConVar("sk_max_grenade") sk_max_rpg_round = GetConVar("sk_max_rpg_round") -- For compatibility reasons we need those ConVars. sk_max_slam = CreateConVar("sk_max_slam", "3", bit.bor(FCVAR_ARCHIVE, FCVAR_NOTIFY, FCVAR_REPLICATED), "") sk_plr_dmg_crowbar = CreateConVar("sk_plr_dmg_crowbar", 10, bit.bor(0, FCVAR_ARCHIVE, FCVAR_NOTIFY, FCVAR_REPLICATED), "") sk_npc_dmg_crowbar = CreateConVar("sk_npc_dmg_crowbar", 5, bit.bor(0, FCVAR_ARCHIVE, FCVAR_NOTIFY, FCVAR_REPLICATED), "") sk_plr_dmg_stunstick = CreateConVar("sk_plr_dmg_stunstick", 10, bit.bor(0, FCVAR_ARCHIVE, FCVAR_NOTIFY, FCVAR_REPLICATED), "") sk_npc_dmg_stunstick = CreateConVar("sk_npc_dmg_stunstick", 40, bit.bor(0, FCVAR_ARCHIVE, FCVAR_NOTIFY, FCVAR_REPLICATED), "") GM.MAX_AMMO_DEF = { ["Pistol"] = sk_max_pistol, ["SMG1"] = sk_max_smg1, ["SMG1_Grenade"] = sk_max_smg1_grenade, ["357"] = sk_max_357, ["AR2"] = sk_max_ar2, ["Buckshot"] = sk_max_buckshot, ["AR2AltFire"] = sk_max_ar2_altfire, ["XBowBolt"] = sk_max_crossbow, ["Grenade"] = sk_max_grenade, ["RPG_Round"] = sk_max_rpg_round, ["slam"] = sk_max_slam } GM.ITEM_DEF = { ["item_ammo_pistol"] = { ["Type"] = "Pistol", ["Max"] = sk_max_pistol, ["1"] = 24, ["2"] = 20, ["3"] = 12 }, ["item_ammo_pistol_large"] = { ["Type"] = "Pistol", ["Max"] = sk_max_pistol, ["1"] = 120, ["2"] = 100, ["3"] = 60 }, ["item_ammo_smg1"] = { ["Type"] = "SMG1", ["Max"] = sk_max_smg1, ["1"] = 54, ["2"] = 45, ["3"] = 27 }, ["item_ammo_smg1_large"] = { ["Type"] = "SMG1", ["Max"] = sk_max_smg1, ["1"] = 225, ["2"] = 225, ["3"] = 135 }, ["item_ammo_smg1_grenade"] = { ["Type"] = "SMG1_Grenade", ["Max"] = sk_max_smg1_grenade, ["1"] = 1, ["2"] = 1, ["3"] = 1 }, ["item_ammo_357"] = { ["Type"] = "357", ["Max"] = sk_max_357, ["1"] = 7, ["2"] = 6, ["3"] = 3 }, ["item_ammo_357_large"] = { ["Type"] = "357", ["Max"] = sk_max_357, ["1"] = 12, ["2"] = 12, ["3"] = 12 }, ["item_ammo_ar2"] = { ["Type"] = "AR2", ["Max"] = sk_max_ar2, ["1"] = 24, ["2"] = 20, ["3"] = 12 }, ["item_ammo_ar2_large"] = { ["Type"] = "AR2", ["Max"] = sk_max_ar2, ["1"] = 60, ["2"] = 60, ["3"] = 60 }, ["item_ammo_ar2_altfire"] = { ["Type"] = "AR2AltFire", ["Max"] = sk_max_ar2_altfire, ["1"] = 1, ["2"] = 1, ["3"] = 1 }, ["item_box_buckshot"] = { ["Type"] = "Buckshot", ["Max"] = sk_max_buckshot, ["1"] = 24, ["2"] = 20, ["3"] = 12 }, ["item_ammo_crossbow"] = { ["Type"] = "XBowBolt", ["Max"] = sk_max_crossbow, ["1"] = 7, ["2"] = 6, ["3"] = 3 }, ["item_ammo_crossbow"] = { ["Type"] = "XBowBolt", ["Max"] = sk_max_crossbow, ["1"] = 7, ["2"] = 6, ["3"] = 3 }, ["item_rpg_round"] = { ["Type"] = "RPG_Round", ["Max"] = sk_max_rpg_round, ["1"] = 1, ["2"] = 1, ["3"] = 1 }, ["weapon_frag"] = { ["Type"] = "Grenade", ["Max"] = sk_max_grenade, ["1"] = 1, ["2"] = 1, ["3"] = 1 }, ["weapon_slam"] = { ["Type"] = "slam", ["Max"] = sk_max_slam, ["1"] = 1, ["2"] = 1, ["3"] = 1 } } GM.PLAYER_WEAPON_DAMAGE = { ["weapon_crowbar"] = GetConVar("sk_plr_dmg_crowbar"), ["weapon_stunstick"] = GetConVar("sk_plr_dmg_stunstick"), ["weapon_ar2"] = GetConVar("sk_plr_dmg_ar2"), ["weapon_357"] = GetConVar("sk_plr_dmg_357"), ["weapon_smg1"] = GetConVar("sk_plr_dmg_smg1"), ["weapon_shotgun"] = GetConVar("sk_plr_dmg_buckshot"), ["weapon_pistol"] = GetConVar("sk_plr_dmg_pistol"), ["weapon_physcannon"] = GetConVar("string name") } GM.NPC_WEAPON_DAMAGE = { ["weapon_crowbar"] = GetConVar("sk_npc_dmg_crowbar"), ["weapon_stunstick"] = GetConVar("sk_npc_dmg_stunstick"), ["weapon_ar2"] = GetConVar("sk_npc_dmg_ar2"), ["weapon_357"] = GetConVar("sk_npc_dmg_357"), ["weapon_shotgun"] = GetConVar("sk_npc_dmg_buckshot") } GM.GameWeapons = { ["weapon_357"] = true, ["weapon_alyxgun"] = true, ["weapon_annabelle"] = true, ["weapon_ar2"] = true, ["weapon_brickbat"] = true, ["weapon_bugbait"] = true, ["weapon_crossbow"] = true, ["weapon_crowbar"] = true, ["weapon_frag"] = true, ["weapon_physcannon"] = true, ["weapon_pistol"] = true, ["weapon_rpg"] = true, ["weapon_shotgun"] = true, ["weapon_smg1"] = true, ["weapon_striderbuster"] = true, ["weapon_stunstick"] = true } -- FIXME: No longer required but keep for now. GM.AITranslatedGameWeapons = { ["ai_weapon_357"] = "weapon_357", ["ai_weapon_ar2"] = "weapon_ar2", ["ai_weapon_smg1"] = "weapon_smg1", ["ai_weapon_shotgun"] = "weapon_shotgun" } function GM:CreateTeams() team.SetUp(LAMBDA_TEAM_ALIVE, "Alive", Color(255, 130, 0), true) team.SetUp(LAMBDA_TEAM_DEAD, "Dead", Color(255, 30, 0), true) team.SetUp(LAMBDA_TEAM_SPECTATOR, "Spectating", Color(100, 100, 100), true) team.SetUp(LAMBDA_TEAM_CONNECTING, "Connecting", Color(100, 100, 100), true) team.SetUp(LAMBDA_TEAM_REBEL, "Rebels", Color(255, 0, 0, 100), true) team.SetUp(LAMBDA_TEAM_COMBINE, "Combine", Color(0, 0, 255, 100), true) end if CLIENT then language.Add("LAMBDA_Timeleft", "TIME LEFT") language.Add("LAMBDA_Map", "MAP") language.Add("LAMBDA_Uptime", "UPTIME") language.Add("LAMBDA_Campaign", "CAMPAIGN") language.Add("LAMBDA_Chapter", "CHAPTER") language.Add("LAMBDA_Frags", "FRAGS LEFT") language.Add("LAMBDA_ChangingLevelMap", "CHANGING TO LEVEL") end
1
0.755911
1
0.755911
game-dev
MEDIA
0.989687
game-dev
0.526672
1
0.526672
takenet/lime-csharp
1,372
src/Lime.Protocol/Network/Modules/ChannelModule.cs
using System; using System.Threading; using System.Threading.Tasks; namespace Lime.Protocol.Network.Modules { public sealed class ChannelModule<T> : ChannelModuleBase<T> where T : Envelope, new() { private Func<T, CancellationToken, Task<T>> _onReceivingFunc; private Func<T, CancellationToken, Task<T>> _onSendingFunc; private Action<SessionState> _onStateChangedAction; public ChannelModule(Func<T, CancellationToken, Task<T>> onReceivingFunc, Func<T, CancellationToken, Task<T>> onSendingFunc, Action<SessionState> onStateChangedAction) { _onReceivingFunc = onReceivingFunc ?? throw new ArgumentNullException(nameof(onReceivingFunc)); _onSendingFunc = onSendingFunc ?? throw new ArgumentNullException(nameof(onSendingFunc)); _onStateChangedAction = onStateChangedAction ?? throw new ArgumentNullException(nameof(onStateChangedAction)); } public override Task<T> OnReceivingAsync(T envelope, CancellationToken cancellationToken) => _onReceivingFunc(envelope, cancellationToken); public override Task<T> OnSendingAsync(T envelope, CancellationToken cancellationToken) => _onSendingFunc(envelope, cancellationToken); public override void OnStateChanged(SessionState state) => _onStateChangedAction(state); } }
1
0.865512
1
0.865512
game-dev
MEDIA
0.287636
game-dev
0.629739
1
0.629739
kennyalive/Quake-III-Arena-Kenny-Edition
8,450
src/engine/botlib/be_aas_def.h
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ /***************************************************************************** * name: be_aas_def.h * * desc: AAS * * $Archive: /source/code/botlib/be_aas_def.h $ * *****************************************************************************/ //debugging on #define AAS_DEBUG #define MAX_CLIENTS 64 #define MAX_MODELS 256 // these are sent over the net as 8 bits #define MAX_SOUNDS 256 // so they cannot be blindly increased #define MAX_CONFIGSTRINGS 1024 #define CS_SCORES 32 #define CS_MODELS (CS_SCORES+MAX_CLIENTS) #define CS_SOUNDS (CS_MODELS+MAX_MODELS) #define DF_AASENTNUMBER(x) (x - aasworld.entities) #define DF_NUMBERAASENT(x) (&aasworld.entities[x]) #define DF_AASENTCLIENT(x) (x - aasworld.entities - 1) #define DF_CLIENTAASENT(x) (&aasworld.entities[x + 1]) #ifndef MAX_PATH #define MAX_PATH MAX_QPATH #endif //string index (for model, sound and image index) typedef struct aas_stringindex_s { int numindexes; char **index; } aas_stringindex_t; //structure to link entities to areas and areas to entities typedef struct aas_link_s { int entnum; int areanum; struct aas_link_s *next_ent, *prev_ent; struct aas_link_s *next_area, *prev_area; } aas_link_t; //structure to link entities to leaves and leaves to entities typedef struct bsp_link_s { int entnum; int leafnum; struct bsp_link_s *next_ent, *prev_ent; struct bsp_link_s *next_leaf, *prev_leaf; } bsp_link_t; typedef struct bsp_entdata_s { vec3_t origin; vec3_t angles; vec3_t absmins; vec3_t absmaxs; int solid; int modelnum; } bsp_entdata_t; //entity typedef struct aas_entity_s { //entity info aas_entityinfo_t i; //links into the AAS areas aas_link_t *areas; //links into the BSP leaves bsp_link_t *leaves; } aas_entity_t; typedef struct aas_settings_s { vec3_t phys_gravitydirection; float phys_friction; float phys_stopspeed; float phys_gravity; float phys_waterfriction; float phys_watergravity; float phys_maxvelocity; float phys_maxwalkvelocity; float phys_maxcrouchvelocity; float phys_maxswimvelocity; float phys_walkaccelerate; float phys_airaccelerate; float phys_swimaccelerate; float phys_maxstep; float phys_maxsteepness; float phys_maxwaterjump; float phys_maxbarrier; float phys_jumpvel; float phys_falldelta5; float phys_falldelta10; float rs_waterjump; float rs_teleport; float rs_barrierjump; float rs_startcrouch; float rs_startgrapple; float rs_startwalkoffledge; float rs_startjump; float rs_rocketjump; float rs_bfgjump; float rs_jumppad; float rs_aircontrolledjumppad; float rs_funcbob; float rs_startelevator; float rs_falldamage5; float rs_falldamage10; float rs_maxfallheight; float rs_maxjumpfallheight; } aas_settings_t; #define CACHETYPE_PORTAL 0 #define CACHETYPE_AREA 1 //routing cache typedef struct aas_routingcache_s { byte type; //portal or area cache float time; //last time accessed or updated int size; //size of the routing cache int cluster; //cluster the cache is for int areanum; //area the cache is created for vec3_t origin; //origin within the area float starttraveltime; //travel time to start with int travelflags; //combinations of the travel flags struct aas_routingcache_s *prev, *next; struct aas_routingcache_s *time_prev, *time_next; unsigned char *reachabilities; //reachabilities used for routing unsigned short int traveltimes[1]; //travel time for every area (variable sized) } aas_routingcache_t; //fields for the routing algorithm typedef struct aas_routingupdate_s { int cluster; int areanum; //area number of the update vec3_t start; //start point the area was entered unsigned short int tmptraveltime; //temporary travel time unsigned short int *areatraveltimes; //travel times within the area qboolean inlist; //true if the update is in the list struct aas_routingupdate_s *next; struct aas_routingupdate_s *prev; } aas_routingupdate_t; //reversed reachability link typedef struct aas_reversedlink_s { int linknum; //the aas_areareachability_t int areanum; //reachable from this area struct aas_reversedlink_s *next; //next link } aas_reversedlink_t; //reversed area reachability typedef struct aas_reversedreachability_s { int numlinks; aas_reversedlink_t *first; } aas_reversedreachability_t; //areas a reachability goes through typedef struct aas_reachabilityareas_s { int firstarea, numareas; } aas_reachabilityareas_t; typedef struct aas_s { int loaded; //true when an AAS file is loaded int initialized; //true when AAS has been initialized int savefile; //set true when file should be saved int bspchecksum; //current time float time; int numframes; //name of the aas file char filename[MAX_PATH]; char mapname[MAX_PATH]; //bounding boxes int numbboxes; aas_bbox_t *bboxes; //vertexes int numvertexes; aas_vertex_t *vertexes; //planes int numplanes; aas_plane_t *planes; //edges int numedges; aas_edge_t *edges; //edge index int edgeindexsize; aas_edgeindex_t *edgeindex; //faces int numfaces; aas_face_t *faces; //face index int faceindexsize; aas_faceindex_t *faceindex; //convex areas int numareas; aas_area_t *areas; //convex area settings int numareasettings; aas_areasettings_t *areasettings; //reachablity list int reachabilitysize; aas_reachability_t *reachability; //nodes of the bsp tree int numnodes; aas_node_t *nodes; //cluster portals int numportals; aas_portal_t *portals; //cluster portal index int portalindexsize; aas_portalindex_t *portalindex; //clusters int numclusters; aas_cluster_t *clusters; // int numreachabilityareas; float reachabilitytime; //enities linked in the areas aas_link_t *linkheap; //heap with link structures int linkheapsize; //size of the link heap aas_link_t *freelinks; //first free link aas_link_t **arealinkedentities; //entities linked into areas //entities int maxentities; int maxclients; aas_entity_t *entities; //string indexes char *configstrings[MAX_CONFIGSTRINGS]; int indexessetup; //index to retrieve travel flag for a travel type int travelflagfortype[MAX_TRAVELTYPES]; //travel flags for each area based on contents int *areacontentstravelflags; //routing update aas_routingupdate_t *areaupdate; aas_routingupdate_t *portalupdate; //number of routing updates during a frame (reset every frame) int frameroutingupdates; //reversed reachability links aas_reversedreachability_t *reversedreachability; //travel times within the areas unsigned short ***areatraveltimes; //array of size numclusters with cluster cache aas_routingcache_t ***clusterareacache; aas_routingcache_t **portalcache; //cache list sorted on time aas_routingcache_t *oldestcache; // start of cache list sorted on time aas_routingcache_t *newestcache; // end of cache list sorted on time //maximum travel time through portal areas int *portalmaxtraveltimes; //areas the reachabilities go through int *reachabilityareaindex; aas_reachabilityareas_t *reachabilityareas; } aas_t; #define AASINTERN #ifndef BSPCINCLUDE #include "be_aas_main.h" #include "be_aas_entity.h" #include "be_aas_sample.h" #include "be_aas_cluster.h" #include "be_aas_reach.h" #include "be_aas_route.h" #include "be_aas_routealt.h" #include "be_aas_debug.h" #include "be_aas_file.h" #include "be_aas_optimize.h" #include "be_aas_bsp.h" #include "be_aas_move.h" #endif //BSPCINCLUDE
1
0.747221
1
0.747221
game-dev
MEDIA
0.840976
game-dev
0.597558
1
0.597558
Histidine91/Nexerelin
13,122
jars/sources/ExerelinCore/exerelin/campaign/intel/agents/Travel.java
package exerelin.campaign.intel.agents; import com.fs.starfarer.api.Global; import com.fs.starfarer.api.campaign.FactionAPI; import com.fs.starfarer.api.campaign.SectorEntityToken; import com.fs.starfarer.api.campaign.TextPanelAPI; import com.fs.starfarer.api.campaign.comm.IntelInfoPlugin; import com.fs.starfarer.api.campaign.econ.MarketAPI; import com.fs.starfarer.api.combat.MutableStat; import com.fs.starfarer.api.impl.campaign.ids.Factions; import com.fs.starfarer.api.impl.campaign.rulecmd.Nex_FleetRequest; import com.fs.starfarer.api.ui.LabelAPI; import com.fs.starfarer.api.ui.TooltipMakerAPI; import com.fs.starfarer.api.util.Misc; import exerelin.campaign.CovertOpsManager; import exerelin.campaign.CovertOpsManager.CovertActionResult; import exerelin.utilities.NexConfig; import exerelin.utilities.NexFactionConfig; import exerelin.utilities.NexUtilsMarket; import exerelin.utilities.StringHelper; import lombok.NoArgsConstructor; import java.awt.*; import java.util.List; import java.util.*; @NoArgsConstructor public class Travel extends CovertActionIntel { public static final float DAYS_PER_LY = 0.5f; protected float timeElapsed; protected MutableStat departTime; protected MutableStat travelTime; protected MutableStat arriveTime; // 0 = at starting market, preparing to leave // 1 = travelling between markets // 2 = at destination market, preparing to insert // 3 = embedded at destination market protected int status = 0; protected MarketAPI from; public Travel(AgentIntel agent, MarketAPI market, FactionAPI agentFaction, FactionAPI targetFaction, boolean playerInvolved, Map<String, Object> params) { super(agent, market, agentFaction, targetFaction, playerInvolved, params); from = agent.getMarket(); } @Override public void init() { getTimeNeeded(true); } /** * Gets the travel time to the current destination. * @param resetVars If true, reapplies the object variables {@code departTime}, {@code travelTime} and {@code arriveTime}. * @return */ public float getTimeNeeded(boolean resetVars) { if (market == null) return 0; MutableStat departTime = getDepartOrArriveTime(agent.getMarket(), true); MutableStat travelTime = getTravelTime(agent.getMarket(), market); MutableStat arriveTime = getDepartOrArriveTime(market, false); float days = departTime.getModifiedValue() + travelTime.getModifiedValue() + arriveTime.getModifiedValue(); if (resetVars) { this.departTime = departTime; this.travelTime = travelTime; this.arriveTime = arriveTime; daysRemaining = days; } return days; } @Override public float getTimeNeeded() { return getTimeNeeded(false); } public MutableStat getDepartTime() { return departTime; } public MutableStat getTravelTime() { return travelTime; } public MutableStat getArriveTime() { return arriveTime; } protected MutableStat getDepartOrArriveTime(MarketAPI market, boolean departing) { MutableStat time = new MutableStat(0); if (market == null) return time; String str = getString("travelTimeStatBase"); String departureOrArrival = StringHelper.getString(departing ? "departure" : "arrival"); str = StringHelper.substituteToken(str, "$departureOrArrival", departureOrArrival); float baseTime = 2; float penalty = 0; boolean deciv = false; boolean unfriendly = false; // market decivilized if (!market.isInEconomy()) { deciv = true; if (!departing) { baseTime = 1; } else { baseTime = 0; penalty = 12; } } // unfriendly market else { switch (market.getFaction().getRelationshipLevel(Factions.PLAYER)) { case SUSPICIOUS: penalty = 2; unfriendly = true; break; case INHOSPITABLE: penalty = 4; unfriendly = true; break; case HOSTILE: case VENGEFUL: penalty = 7; unfriendly = true; break; } if (market.isFreePort()) penalty = 0; } time.modifyFlat("base", baseTime, str); // reduce penalty based on agent level if (penalty > 0) { int level = getLevel(); penalty *= 1 - 0.15f * (level - 1); } if (deciv && departing) { str = getString("travelTimeStatDeciv"); time.modifyFlat("departDeciv", penalty, str); } if (unfriendly) { str = getString("travelTimeStatRepLevel"); String sub = market.getFaction().getRelationshipLevel(Factions.PLAYER).getDisplayName().toLowerCase(); //if (market.isFreePort()) sub = StringHelper.getString("freePort"); // doesn't display anyway in this case str = StringHelper.substituteToken(str, "$repLevel", sub); time.modifyFlat("security", penalty, str); } return time; } // can't abort once we've departed the planet @Override public boolean canAbort() { return status == 0; } // clear queued action (if any) // since the queued action assumes we completed our travel, which we won't now @Override public void abort() { super.abort(); CovertActionIntel next = agent.getNextAction(); if (this == agent.getCurrentAction() && next != null) { next.abort(); agent.removeActionFromQueue(next); } } protected MutableStat getTravelTime(MarketAPI one, MarketAPI two) { MutableStat stat = new MutableStat(0); float time; String distStr = "??"; if (one == null || two == null) time = 15; else { float dist = Misc.getDistanceLY(one.getLocationInHyperspace(), two.getLocationInHyperspace()); time = dist * DAYS_PER_LY; distStr = String.format("%.1f", dist); } String desc = StringHelper.getStringAndSubstituteToken("nex_agentActions", "travelTimeStatTravel", "$dist", distStr); stat.modifyFlat("distance", time, desc); return stat; } @Override public void setMarket(MarketAPI market) { super.setMarket(market); getTimeNeeded(true); } @Override public void advanceImpl(float amount) { float days = Global.getSector().getClock().convertToDays(amount); timeElapsed += days; if (status == 0 && timeElapsed > departTime.modified) { status = 1; agent.setMarket(null); } else if (status == 1 && timeElapsed > departTime.modified + travelTime.modified) { status = 2; } else if (status == 2 && timeElapsed > departTime.modified + travelTime.modified + arriveTime.modified) { status = 3; // done } super.advanceImpl(amount); } @Override public CovertOpsManager.CovertActionResult execute() { result = CovertActionResult.SUCCESS; onSuccess(); CovertOpsManager.reportAgentAction(this); return result; } @Override protected void addBulletPoints(TooltipMakerAPI info, ListInfoMode mode, boolean isUpdate, Color tc, float initPad){ info.addPara(getString("intelBulletTarget"), initPad, tc, market.getTextColorForFactionOrPlanet(), market.getName()); } @Override public void addCurrentActionPara(TooltipMakerAPI info, float pad) { String action = getActionString("intelStatus_travel"); if (started) { String statusStr = getString("intelStatus_travel" + status); action = StringHelper.substituteToken(action, "$status", statusStr); } else { action = getActionString("intelStatus_travelShort"); } action = StringHelper.substituteToken(action, "$market", market.getName()); info.addPara(action, pad, market.getFaction().getBaseUIColor(), market.getName()); } @Override public void addCurrentActionBullet(TooltipMakerAPI info, Color color, float pad) { String action = getActionString("intelStatus_travelShort", true); action = StringHelper.substituteToken(action, "$market", market.getName()); String daysLeft = Math.round(daysRemaining) + ""; LabelAPI label = info.addPara(action, pad, color, Misc.getHighlightColor(), daysLeft); label.setHighlight(market.getName(), daysLeft); label.setHighlightColors(market.getTextColorForFactionOrPlanet(), Misc.getHighlightColor()); } @Override public boolean showSuccessChance() { return false; } @Override protected void onSuccess() { agent.setMarket(market); agent.sendUpdateIfPlayerHasIntel(AgentIntel.UPDATE_ARRIVED, false); agent.notifyActionCompleted(); CovertOpsManager.getRandom(market).nextFloat(); // change the next result } @Override protected void onFailure() { // do nothing } @Override public boolean allowOwnMarket() { return true; } @Override public String getIcon() { return "graphics/icons/intel/stars.png"; } @Override public Set<FactionAPI> dialogGetFactions(AgentOrdersDialog dialog) { Set<FactionAPI> factionsSet = new HashSet<>(); Set<FactionAPI> temp = new HashSet<>(); for (MarketAPI market : Global.getSector().getEconomy().getMarketsCopy()) { if (market.isHidden()) continue; temp.add(market.getFaction()); } for (FactionAPI faction : temp) { NexFactionConfig conf = NexConfig.getFactionConfig(faction.getId()); if (conf.allowAgentActions) factionsSet.add(faction); } return factionsSet; } @Override public List<Object> dialogGetTargets(AgentOrdersDialog dialog) { List<Object> targets = new ArrayList<>(); Set<FactionAPI> validFactions = new HashSet<>(dialogGetFactions(dialog)); for (MarketAPI market : Global.getSector().getEconomy().getMarketsCopy()) { if (market.isHidden()) continue; if (market == agent.getMarket()) continue; if (!validFactions.contains(market.getFaction())) continue; targets.add(market); } return targets; } @Override public void dialogSetTarget(AgentOrdersDialog dialog, Object target) { market = (MarketAPI)target; getTimeNeeded(true); dialog.printActionInfo(); } @Override public void dialogAutopickTarget(AgentOrdersDialog dialog, List<Object> targets) { if (targets == null) { dialogSetTarget(dialog, null); return; } } @Override public void dialogPrintActionInfo(AgentOrdersDialog dialog) { if (market == null) return; TextPanelAPI text = dialog.getText(); Color hl = Misc.getHighlightColor(); Color neg = Misc.getNegativeHighlightColor(); text.addPara(getString("dialogInfoHeaderTravel"), market.getFaction().getBaseUIColor(), market.getName()); String days = String.format("%.0f", this.getTimeNeeded()); text.addPara(getString("dialogInfoTimeNeeded"), hl, days); dialog.printStat(getDepartTime(), false); dialog.printStat(getTravelTime(), false); dialog.printStat(getArriveTime(), false); if (getTimeMultForOverMaxAgents() > 1) { text.addPara(getString("dialogInfoTimeNeededOverAgents"), neg, hl, CovertOpsManager.getManager().getAgents().size() + "", CovertOpsManager.getManager().getMaxAgents().getModifiedInt() + ""); } MutableStat cost = getCostStat(); int costInt = cost.getModifiedInt(); if (costInt > 0) { String costDGS = Misc.getDGSCredits(costInt); text.addPara(getString("dialogInfoCost"), hasEnoughCredits() ? hl : Misc.getNegativeHighlightColor(), costDGS); dialog.printStat(cost, true); } } @Override protected void dialogPopulateMainMenuOptions(AgentOrdersDialog dialog) { String str = getString("dialogOption_target"); String target = market != null? market.getName() : StringHelper.getString("none"); str = StringHelper.substituteToken(str, "$target", target); dialog.getOptions().addOption(str, AgentOrdersDialog.Menu.TARGET); } @Override protected void dialogPopulateTargetOptions(final AgentOrdersDialog dialog) { List<SectorEntityToken> dests = new ArrayList<>(); for (Object marketRaw : dialog.getCachedTargets()) { MarketAPI market = (MarketAPI)marketRaw; dests.add(market.getPrimaryEntity()); } List<IntelInfoPlugin.ArrowData> arrows = getDestinationArrows(); NexUtilsMarket.pickEntityDestination(dialog.getDialog(), dests, StringHelper.getString("confirm", true), new NexUtilsMarket.CampaignEntityPickerWrapper(){ @Override public void reportEntityPicked(SectorEntityToken token) { dialogSetTarget(dialog, token.getMarket()); dialog.optionSelected(null, AgentOrdersDialog.Menu.MAIN_MENU); // to refresh option text } @Override public void reportEntityPickCancelled() {} @Override public void createInfoText(TooltipMakerAPI info, SectorEntityToken entity) { MarketAPI market = agent.getMarket(); Nex_FleetRequest.createInfoTextBasic(info, entity, market != null ? market.getPrimaryEntity() : null); } }, arrows); dialog.optionSelected(null, AgentOrdersDialog.Menu.MAIN_MENU); } protected List<IntelInfoPlugin.ArrowData> getDestinationArrows() { List<IntelInfoPlugin.ArrowData> arrows = new ArrayList<>(); for (AgentIntel intel : CovertOpsManager.getManager().getAgents()) { arrows.addAll(intel.getArrowData(null)); } return arrows; } @Override public void dialogInitAction(AgentOrdersDialog dialog) { super.dialogInitAction(dialog); market = null; from = agent.getMarket(); dialog.getTargets(); dialogPopulateTargetOptions(dialog); } @Override public boolean dialogCanShowAction(AgentOrdersDialog dialog) { return true; } @Override public boolean dialogCanActionProceed(AgentOrdersDialog dialog) { return market != null; } @Override public String getDefId() { return "travel"; } }
1
0.878039
1
0.878039
game-dev
MEDIA
0.720726
game-dev
0.97247
1
0.97247
sifteo/thundercracker
3,079
emulator/src/Box2D/Collision/Shapes/b2CircleShape.cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <new> using namespace std; b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const { void* mem = allocator->Allocate(sizeof(b2CircleShape)); b2CircleShape* clone = new (mem) b2CircleShape; *clone = *this; return clone; } int32 b2CircleShape::GetChildCount() const { return 1; } bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const { b2Vec2 center = transform.p + b2Mul(transform.q, m_p); b2Vec2 d = p - center; return b2Dot(d, d) <= m_radius * m_radius; } // Collision Detection in Interactive 3D Environments by Gino van den Bergen // From Section 3.1.2 // x = s + a * r // norm(x) = radius bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform, int32 childIndex) const { B2_NOT_USED(childIndex); b2Vec2 position = transform.p + b2Mul(transform.q, m_p); b2Vec2 s = input.p1 - position; float32 b = b2Dot(s, s) - m_radius * m_radius; // Solve quadratic equation. b2Vec2 r = input.p2 - input.p1; float32 c = b2Dot(s, r); float32 rr = b2Dot(r, r); float32 sigma = c * c - rr * b; // Check for negative discriminant and short segment. if (sigma < 0.0f || rr < b2_epsilon) { return false; } // Find the point of intersection of the line with the circle. float32 a = -(c + b2Sqrt(sigma)); // Is the intersection point on the segment? if (0.0f <= a && a <= input.maxFraction * rr) { a /= rr; output->fraction = a; output->normal = s + a * r; output->normal.Normalize(); return true; } return false; } void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const { B2_NOT_USED(childIndex); b2Vec2 p = transform.p + b2Mul(transform.q, m_p); aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); } void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const { massData->mass = density * b2_pi * m_radius * m_radius; massData->center = m_p; // inertia about the local origin massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); }
1
0.980879
1
0.980879
game-dev
MEDIA
0.919605
game-dev
0.993469
1
0.993469
SHNecro/ShanghaiJAR
3,559
ShanghaiEXE/Chip/GraviBall1.cs
using NSAttack; using NSBattle; using NSBattle.Character; using NSShanghaiEXE.InputOutput.Audio; using NSShanghaiEXE.InputOutput.Rendering; using Common.Vectors; using System.Drawing; namespace NSChip { internal class GraviBall1 : ChipBase { private const int speed = 4; private const int shotend = 16; public GraviBall1(IAudioEngine s) : base(s) { this.rockOnPoint = new Point(-1, 0); this.number = 40; this.name = NSGame.ShanghaiEXE.Translate("Chip.GraviBall1Name"); this.element = ChipBase.ELEMENT.earth; this.power = 40; this.subpower = 0; this.regsize = 12; this.reality = 2; this.crack = true; this._break = false; this.powerprint = true; this.code[0] = ChipFolder.CODE.A; this.code[1] = ChipFolder.CODE.J; this.code[2] = ChipFolder.CODE.S; this.code[3] = ChipFolder.CODE.asterisk; var information = NSGame.ShanghaiEXE.Translate("Chip.GraviBall1Desc"); this.information[0] = information[0]; this.information[1] = information[1]; this.information[2] = information[2]; this.Init(); } public override void Action(CharacterBase character, SceneBattle battle) { if (character.waittime < 5) character.animationpoint = new Point(4, 0); else if (character.waittime < 15) character.animationpoint = new Point(5, 0); else if (character.waittime < 16) character.animationpoint = new Point(6, 0); else if (character.waittime < 21) character.animationpoint = new Point(5, 0); else if (character.waittime == 40) base.Action(character, battle); if (character.waittime != 16) return; int num = this.power + this.pluspower; GravityBallAttack gravityBallAttack = new GravityBallAttack(this.sound, character.parent, character.position.X + this.UnionRebirth(character.union), character.position.Y, character.union, this.Power(character), 2, new Vector2(character.positionDirect.X + 20 * this.UnionRebirth(character.union), character.positionDirect.Y + 16f), this.element); gravityBallAttack.BadStatusSet(CharacterBase.BADSTATUS.heavy, 1200); character.parent.attacks.Add(this.Paralyze(gravityBallAttack)); } public override void GraphicsRender( IRenderer dg, Vector2 p, int c, bool printgraphics, bool printstatus) { if (printgraphics) { this._rect = new Rectangle(224, 0, 56, 48); dg.DrawImage(dg, "chipgraphic2", this._rect, true, p, Color.White); } base.GraphicsRender(dg, p, c, printgraphics, printstatus); } public override void IconRender( IRenderer dg, Vector2 p, bool select, bool custom, int c, bool noicon) { if (!noicon) { this._rect = this.IconRect(select); dg.DrawImage(dg, "chipicon", this._rect, true, p, Color.White); } base.IconRender(dg, p, select, custom, c, noicon); } public override void Render(IRenderer dg, CharacterBase character) { if (character.waittime < 5) return; this._rect = new Rectangle(character.Wide, character.Height, character.Wide, character.Height); this._position = new Vector2(character.positionDirect.X + Shake.X, character.positionDirect.Y + Shake.Y); if (character.waittime < 10) this._rect.X = 0; dg.DrawImage(dg, "weapons", this._rect, false, this._position, character.union == Panel.COLOR.blue, Color.White); } } }
1
0.913541
1
0.913541
game-dev
MEDIA
0.964784
game-dev
0.96001
1
0.96001
VisualGMQ/NickelEngine
5,376
engine/engine/3rdlibs/physx/physx/source/physxvehicle2/src/pvd/VhPvdAttributeHandles.h
// 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 NVIDIA CORPORATION 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 ''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. // // Copyright (c) 2008-2024 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/pvd/PxVehiclePvdHelpers.h" #include "VhPvdWriter.h" #if !PX_DOXYGEN namespace physx { namespace vehicle2 { #endif struct PxVehiclePvdAttributeHandles { #if PX_SUPPORT_OMNI_PVD ///////////////////// //RIGID BODY ///////////////////////// RigidBodyParams rigidBodyParams; RigidBodyState rigidBodyState; ///////////////////////// //SUSP STATE CALC PARAMS ///////////////////////// SuspStateCalcParams suspStateCalcParams; ///////////////////////// //CONTROL ATTRIBUTES ///////////////////////// WheelResponseParams brakeCommandResponseParams; WheelResponseParams steerCommandResponseParams; AckermannParams ackermannParams; WheelResponseStates brakeCommandResponseStates; WheelResponseStates steerCommandResponseStates; ///////////////////////////////// //WHEEL ATTACHMENT ATTRIBUTES ///////////////////////////////// WheelParams wheelParams; WheelActuationState wheelActuationState; WheelRigidBody1dState wheelRigidBody1dState; WheelLocalPoseState wheelLocalPoseState; RoadGeometryState roadGeomState; SuspParams suspParams; SuspCompParams suspCompParams; SuspForceParams suspForceParams; SuspState suspState; SuspCompState suspCompState; SuspForce suspForce; TireParams tireParams; TireDirectionState tireDirectionState; TireSpeedState tireSpeedState; TireSlipState tireSlipState; TireStickyState tireStickyState; TireGripState tireGripState; TireCamberState tireCamberState; TireForce tireForce; WheelAttachment wheelAttachment; /////////////////////// //ANTIROLL BARS /////////////////////// AntiRollParams antiRollParams; AntiRollForce antiRollForce; /////////////////////////////////// //DIRECT DRIVETRAIN /////////////////////////////////// DirectDriveCommandState directDriveCommandState; DirectDriveTransmissionCommandState directDriveTransmissionCommandState; WheelResponseParams directDriveThrottleCommandResponseParams; DirectDriveThrottleResponseState directDriveThrottleCommandResponseState; DirectDrivetrain directDrivetrain; ////////////////////////////////// //ENGINE DRIVETRAIN ATTRIBUTES ////////////////////////////////// EngineDriveCommandState engineDriveCommandState; EngineDriveTransmissionCommandState engineDriveTransmissionCommandState; TankDriveTransmissionCommandState tankDriveTransmissionCommandState; ClutchResponseParams clutchCommandResponseParams; ClutchParams clutchParams; EngineParams engineParams; GearboxParams gearboxParams; AutoboxParams autoboxParams; MultiWheelDiffParams multiwheelDiffParams; FourWheelDiffParams fourwheelDiffParams; TankDiffParams tankDiffParams; ClutchResponseState clutchResponseState; ThrottleResponseState throttleResponseState; EngineState engineState; GearboxState gearboxState; AutoboxState autoboxState; DiffState diffState; ClutchSlipState clutchSlipState; EngineDrivetrain engineDrivetrain; ////////////////////////////////////// //PHYSX WHEEL ATTACHMENT INTEGRATION ////////////////////////////////////// PhysXSuspensionLimitConstraintParams physxSuspLimitConstraintParams; PhysXWheelShape physxWheelShape; PhysXRoadGeomState physxRoadGeomState; PhysXConstraintState physxConstraintState; PhysXMaterialFriction physxMaterialFriction; PhysXWheelAttachment physxWheelAttachment; //////////////////// //PHYSX RIGID ACTOR //////////////////// PhysXRoadGeometryQueryParams physxRoadGeometryQueryParams; PhysXRigidActor physxRigidActor; PhysXSteerState physxSteerState; ////////////////////////////////// //VEHICLE ATTRIBUTES ////////////////////////////////// Vehicle vehicle; #endif }; #if !PX_DOXYGEN } // namespace vehicle2 } // namespace physx #endif
1
0.584834
1
0.584834
game-dev
MEDIA
0.9022
game-dev
0.664
1
0.664
jorio/Bugdom
18,484
src/Enemies/Enemy_QueenBee.c
/****************************/ /* ENEMY: QUEENBEE.C */ /* (c)1999 Pangea Software */ /* By Brian Greenstone */ /****************************/ /****************************/ /* EXTERNALS */ /****************************/ #include "game.h" /****************************/ /* PROTOTYPES */ /****************************/ static void MoveQueenBee(ObjNode *theNode); static void MoveQueenBee_Waiting(ObjNode *theNode); static void MoveQueenBee_Spitting(ObjNode *theNode); static void MoveQueenBee_Death(ObjNode *theNode); static void UpdateQueenBee(ObjNode *theNode); static void FindQueenBases(void); static void MoveQueenBee_Fly(ObjNode *theNode); static void ShootSpit(ObjNode *bee); static void MoveQueenSpit(ObjNode *theNode); static void MoveQueenBee_OnButt(ObjNode *theNode); /****************************/ /* CONSTANTS */ /****************************/ #define QUEENBEE_KNOCKDOWN_SPEED 1400.0f // speed ball needs to go to knock this down #define QUEENBEE_SCALE 1.5f #define QUEENBEE_CHASE_DIST 900.0f #define QUEENBEE_ATTACK_DIST 300.0f #define QUEENBEE_TURN_SPEED 2.0f #define QUEENBEE_WALK_SPEED 600.0f #define QUEENBEE_FOOT_OFFSET -90.0f #define QUEENBEE_HOVER_HEIGHT 400.0f; enum { QUEENBEE_MODE_FLYTOMID, QUEENBEE_MODE_HOVER, QUEENBEE_MODE_LAND }; /* ANIMS */ enum { QUEENBEE_ANIM_WAIT, QUEENBEE_ANIM_SPITTING, QUEENBEE_ANIM_FLY, QUEENBEE_ANIM_ONBUTT, QUEENBEE_ANIM_DEATH }; #define MAX_QUEEN_BASES 15 #define QUEENBEE_JOINT_HEAD 2 #define SPIT_SPEED 500.0f /*********************/ /* VARIABLES */ /*********************/ ObjNode *gTheQueen; static short gNumQueenBases,gCurrentQueenBase; static TQ3Point2D gQueenBase[MAX_QUEEN_BASES]; static Byte gQueenBaseID[MAX_QUEEN_BASES]; static TQ3Point3D gMidPoint,gEndPoint; #define WaitTimer SpecialF[0] #define SpitTimer SpecialF[0] #define ButtTimer SpecialF[1] #define SpitNowFlag Flag[0] #define CanSpit Flag[1] #define DeathTimer SpecialF[2] #define HasSpawned Flag[0] #define PollenTimer SpecialF[1] #define WobbleX SpecialF[2] #define WobbleY SpecialF[3] #define WobbleZ SpecialF[4] #define WobbleBase SpecialF[5] /************************ ADD QUEENBEE ENEMY *************************/ // // A skeleton character // // NOTE: the parm[3] bits are used as special Queen Bee flags // Boolean AddEnemy_QueenBee(TerrainItemEntryType *itemPtr, long x, long z) { ObjNode *newObj; if (itemPtr->parm[0] != 0) // queen is at base #0 return(true); /* SCAN ITEM LIST FOR QUEEN BASE OBJECTS */ FindQueenBases(); /*******************************/ /* MAKE DEFAULT SKELETON ENEMY */ /*******************************/ gCurrentQueenBase = 0; x = gQueenBase[0].x; // start at 1st base z = gQueenBase[0].y; gTheQueen = newObj = MakeEnemySkeleton(SKELETON_TYPE_QUEENBEE,x,z, QUEENBEE_SCALE); if (newObj == nil) return(false); newObj->TerrainItemPtr = itemPtr; SetSkeletonAnim(newObj->Skeleton, QUEENBEE_ANIM_WAIT); /*******************/ /* SET BETTER INFO */ /*******************/ newObj->Coord.y -= QUEENBEE_FOOT_OFFSET; newObj->MoveCall = MoveQueenBee; // set move call newObj->Health = QUEENBEE_HEALTH; // LOTS of health! newObj->Damage = 0; newObj->Kind = ENEMY_KIND_QUEENBEE; newObj->WaitTimer = 3; /* SET COLLISION INFO */ SetObjectCollisionBounds(newObj, 100,QUEENBEE_FOOT_OFFSET,-130,130,130,-130); /* MAKE SHADOW */ AttachShadowToObject(newObj, 13, 13,false); gNumEnemies++; gNumEnemyOfKind[ENEMY_KIND_QUEENBEE]++; return(true); } /********************* MOVE QUEENBEE **************************/ static void MoveQueenBee(ObjNode *theNode) { static void(*myMoveTable[])(ObjNode *) = { MoveQueenBee_Waiting, MoveQueenBee_Spitting, MoveQueenBee_Fly, MoveQueenBee_OnButt, MoveQueenBee_Death, }; /* note: we dont track the queen since she is always active and never goes away! */ GetObjectInfo(theNode); myMoveTable[theNode->Skeleton->AnimNum](theNode); } /********************** MOVE QUEENBEE: WAITING ******************************/ static void MoveQueenBee_Waiting(ObjNode *theNode) { float fps = gFramesPerSecondFrac; /* AIM AT PLAYER */ TurnObjectTowardTarget(theNode, &gCoord, gMyCoord.x, gMyCoord.z, QUEENBEE_TURN_SPEED, false); /* MOVE */ gDelta.y -= ENEMY_GRAVITY*fps; MoveEnemy(theNode); /* DO ENEMY COLLISION */ if (DoEnemyCollisionDetect(theNode,DEFAULT_ENEMY_COLLISION_CTYPES)) return; /* SEE IF TIME TO SPIT HONEY */ theNode->WaitTimer -= fps; if (theNode->WaitTimer <= 0.0f) { MorphToSkeletonAnim(theNode->Skeleton, QUEENBEE_ANIM_SPITTING, 6); theNode->SpitTimer = 2; theNode->SpitNowFlag = false; theNode->CanSpit = true; } UpdateQueenBee(theNode); } /********************** MOVE QUEENBEE: SPITTING ******************************/ static void MoveQueenBee_Spitting(ObjNode *theNode) { float fps; u_short b; fps = gFramesPerSecondFrac; gDelta.y -= ENEMY_GRAVITY*fps; // add gravity MoveEnemy(theNode); /* DO ENEMY COLLISION */ if (DoEnemyCollisionDetect(theNode,DEFAULT_ENEMY_COLLISION_CTYPES)) return; /*************************/ /* SEE IF SHOOT SPIT NOW */ /*************************/ if (theNode->CanSpit) { if (theNode->SpitNowFlag) { theNode->SpitNowFlag = false; theNode->CanSpit = false; ShootSpit(theNode); } } /*******************************************/ /* IF DONE SPITTING, THEN FLY TO NEXT BASE */ /*******************************************/ theNode->SpitTimer -= fps; if (theNode->SpitTimer <= 0.0f) { /* PICK NEXT BASE TO FLY TO */ if (++gCurrentQueenBase >= gNumQueenBases) // inc base # and see if wrap gCurrentQueenBase = 0; for (b = 0; b < gNumQueenBases; b++) // find base # in list { if (gQueenBaseID[b] == gCurrentQueenBase) break; } /* CALC MIDPOINT TO FLY TO */ gEndPoint.x = gQueenBase[b].x; gEndPoint.z = gQueenBase[b].y; gMidPoint.x = (gCoord.x + gQueenBase[b].x) * .5f; gMidPoint.z = (gCoord.z + gQueenBase[b].y) * .5f; gMidPoint.y = GetTerrainHeightAtCoord(gMidPoint.x, gMidPoint.z, FLOOR) + QUEENBEE_HOVER_HEIGHT; /* DO FLY ANIM */ MorphToSkeletonAnim(theNode->Skeleton, QUEENBEE_ANIM_FLY, 6); theNode->Mode = QUEENBEE_MODE_FLYTOMID; } UpdateQueenBee(theNode); } /********************** MOVE QUEENBEE: FLY ******************************/ static void MoveQueenBee_Fly(ObjNode *theNode) { float fps = gFramesPerSecondFrac; TQ3Vector2D aim; Boolean checkSolid = false; /* AIM AT PLAYER */ TurnObjectTowardTarget(theNode, &gCoord, gMyCoord.x, gMyCoord.z, QUEENBEE_TURN_SPEED, false); switch(theNode->Mode) { /********************/ /* FLY TO MID POINT */ /********************/ case QUEENBEE_MODE_FLYTOMID: /* CALC VECTOR TO TARGET */ FastNormalizeVector2D(gMidPoint.x - gCoord.x, gMidPoint.z - gCoord.z, &aim); gDelta.x = aim.x * 400.0f; gDelta.z = aim.y * 400.0f; if (gCoord.y < gMidPoint.y) gDelta.y = 400.0f; else { gDelta.y = 0; checkSolid = true; } MoveEnemy(theNode); /* SEE IF REACHED TARGET */ if (CalcQuickDistance(gCoord.x, gCoord.z, gMidPoint.x, gMidPoint.z) < 150.0f) { theNode->Mode = QUEENBEE_MODE_HOVER; theNode->WaitTimer = 3; } break; /**************************************/ /* HOVER WHILE ENEMIES DO THEIR THING */ /**************************************/ case QUEENBEE_MODE_HOVER: ApplyFrictionToDeltas(5, &gDelta); MoveEnemy(theNode); checkSolid = true; theNode->WaitTimer -= fps; if (theNode->WaitTimer <= 0.0f) { theNode->Mode = QUEENBEE_MODE_LAND; } break; /******************/ /* LAND AT TARGET */ /******************/ case QUEENBEE_MODE_LAND: /* CALC VECTOR TO TARGET */ FastNormalizeVector2D(gEndPoint.x - gCoord.x, gEndPoint.z - gCoord.z, &aim); gDelta.x = aim.x * 400.0f; gDelta.z = aim.y * 400.0f; MoveEnemy(theNode); /* SEE IF REACHED TARGET */ if (CalcQuickDistance(gCoord.x, gCoord.z, gEndPoint.x, gEndPoint.z) < 100.0f) { gDelta.x = gDelta.y = gDelta.z = 0; MorphToSkeletonAnim(theNode->Skeleton, QUEENBEE_ANIM_WAIT, 5); theNode->WaitTimer = 1.5; } break; } /**********************/ /* DO ENEMY COLLISION */ /**********************/ if (DoEnemyCollisionDetect(theNode,DEFAULT_ENEMY_COLLISION_CTYPES)) return; /* IF HIT SOMETHING SOLID WHILE FLYING, THEN LAND */ if (checkSolid && gTotalSides) { theNode->Mode = QUEENBEE_MODE_LAND; theNode->WaitTimer = 0; gEndPoint.x = gCoord.x; gEndPoint.z = gCoord.z; } UpdateQueenBee(theNode); } /********************** MOVE QUEENBEE: ON BUTT ******************************/ static void MoveQueenBee_OnButt(ObjNode *theNode) { float fps = gFramesPerSecondFrac; /* MOVE IT */ if (theNode->StatusBits & STATUS_BIT_ONGROUND) // if on ground, add friction ApplyFrictionToDeltas(60.0,&gDelta); gDelta.y -= ENEMY_GRAVITY*fps; // add gravity MoveEnemy(theNode); /* DO ENEMY COLLISION */ if (DoEnemyCollisionDetect(theNode,DEFAULT_ENEMY_COLLISION_CTYPES)) return; theNode->ButtTimer -= fps; if (theNode->ButtTimer <= 0.0f) { MorphToSkeletonAnim(theNode->Skeleton, QUEENBEE_ANIM_WAIT, 6); theNode->WaitTimer = 0; } /* UPDATE */ UpdateQueenBee(theNode); } /********************** MOVE QUEENBEE: DEATH ******************************/ static void MoveQueenBee_Death(ObjNode *theNode) { float fps = gFramesPerSecondFrac; theNode->DeathTimer -= fps; if (theNode->DeathTimer <= 0.0f) gAreaCompleted = true; /* MOVE IT */ if (theNode->StatusBits & STATUS_BIT_ONGROUND) // if on ground, add friction ApplyFrictionToDeltas(60.0,&gDelta); gDelta.y -= ENEMY_GRAVITY*fps; // add gravity MoveEnemy(theNode); /* DO ENEMY COLLISION */ if (DoEnemyCollisionDetect(theNode,DEATH_ENEMY_COLLISION_CTYPES)) return; /* UPDATE */ UpdateQueenBee(theNode); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== #pragma mark - /******************* BALL HIT QUEENBEE *********************/ // // OUTPUT: true if enemy gets killed // // Worker bees cannot be knocked down. Instead, it just pisses them off. // Boolean BallHitQueenBee(ObjNode *me, ObjNode *enemy) { Boolean killed = false; if (me->Speed > QUEENBEE_KNOCKDOWN_SPEED) { /*****************/ /* KNOCK ON BUTT */ /*****************/ killed = KnockQueenBeeOnButt(enemy, me->Delta.x * .3f, me->Delta.z * .3f, .7); PlayEffect_Parms3D(EFFECT_POUND, &gCoord, kMiddleC+2, 2.0); } return(killed); } /***************** KNOCK QUEEN BEE ON BUTT *****************/ // // INPUT: dx,y,z = delta to apply to fireant // Boolean KnockQueenBeeOnButt(ObjNode *enemy, float dx, float dz, float damage) { TQ3Vector3D delta; if (enemy->Skeleton->AnimNum == QUEENBEE_ANIM_ONBUTT) // see if already in butt mode return(false); /* DO BUTT ANIM */ MorphToSkeletonAnim(enemy->Skeleton, QUEENBEE_ANIM_ONBUTT, 7.0); enemy->ButtTimer = 2.0; /* GET IT MOVING */ enemy->Delta.x = dx; enemy->Delta.z = dz; enemy->Delta.y = 600; /* SLOW DOWN PLAYER */ gDelta.x *= .2f; gDelta.y *= .2f; gDelta.z *= .2f; /*******************/ /* SPARK EXPLOSION */ /*******************/ /* white sparks */ int32_t pg = NewParticleGroup( PARTICLE_TYPE_FALLINGSPARKS, // type PARTICLE_FLAGS_BOUNCE, // flags 500, // gravity 0, // magnetism 20, // base scale .9, // decay rate 0, // fade rate PARTICLE_TEXTURE_YELLOWBALL); // texture for (int i = 0; i < 35; i++) { delta.x = (RandomFloat()-.5f) * 1000.0f; delta.y = (RandomFloat()-.5f) * 1000.0f; delta.z = (RandomFloat()-.5f) * 1000.0f; AddParticleToGroup(pg, &enemy->Coord, &delta, RandomFloat() + 1.0f, FULL_ALPHA); } /* HURT & SEE IF KILLED */ if (EnemyGotHurt(enemy, damage)) return(true); gInfobarUpdateBits |= UPDATE_BOSS; return(false); } /****************** KILL FIRE QUEENBEE *********************/ // // OUTPUT: true if ObjNode was deleted // Boolean KillQueenBee(ObjNode *theNode) { TQ3Vector3D delta; /* STOP BUZZ */ if (theNode->EffectChannel != -1) StopAChannel(&theNode->EffectChannel); /* DEACTIVATE */ theNode->TerrainItemPtr = nil; // dont ever come back theNode->CType = CTYPE_MISC; MorphToSkeletonAnim(theNode->Skeleton, QUEENBEE_ANIM_DEATH, 8); /*******************/ /* SPARK EXPLOSION */ /*******************/ /* white sparks */ int32_t pg = NewParticleGroup( PARTICLE_TYPE_FALLINGSPARKS, // type PARTICLE_FLAGS_BOUNCE, // flags 400, // gravity 0, // magnetism 20, // base scale .8, // decay rate 0, // fade rate PARTICLE_TEXTURE_YELLOWBALL); // texture if (pg != -1) { for (int i = 0; i < 60; i++) { delta.x = (RandomFloat()-.5f) * 1400.0f; delta.y = (RandomFloat()-.5f) * 1400.0f; delta.z = (RandomFloat()-.5f) * 1400.0f; AddParticleToGroup(pg, &theNode->Coord, &delta, RandomFloat() + 1.0f, FULL_ALPHA); } } theNode->DeathTimer = 4; return(false); } /***************** UPDATE QUEENBEE ************************/ static void UpdateQueenBee(ObjNode *theNode) { /* SEE IF DO BUZZ */ if (theNode->Skeleton->AnimNum == QUEENBEE_ANIM_FLY) { if (theNode->EffectChannel == -1) theNode->EffectChannel = PlayEffect_Parms3D(EFFECT_BUZZ, &theNode->Coord, kMiddleC-3, 3.0); else Update3DSoundChannel(EFFECT_BUZZ, &theNode->EffectChannel, &theNode->Coord); } /* SEE IF TURN OFF BUZZ */ else { if (theNode->EffectChannel != -1) { StopAChannel(&theNode->EffectChannel); } } UpdateEnemy(theNode); } #pragma mark - /******************** FIND QUEEN BASES *******************/ // // Scans the map item list for queen bases and adds them to the list. // static void FindQueenBases(void) { long i; TerrainItemEntryType *itemPtr; gNumQueenBases = 0; itemPtr = *gMasterItemList; for (i= 0; i < gNumTerrainItems; i++) { if (itemPtr[i].type == MAP_ITEM_QUEENBEEBASE) { gQueenBase[gNumQueenBases].x = itemPtr[i].x * MAP2UNIT_VALUE; // convert to world coords gQueenBase[gNumQueenBases].y = itemPtr[i].y * MAP2UNIT_VALUE; gQueenBaseID[gNumQueenBases] = itemPtr[i].parm[0]; // remember ID# gNumQueenBases++; if (gNumQueenBases >= MAX_QUEEN_BASES) // see if @ max break; } } GAME_ASSERT_MESSAGE(gNumQueenBases > 0, "No bases found"); } #pragma mark - /********************** SHOOT SPIT ***********************/ static void ShootSpit(ObjNode *bee) { float r; ObjNode *spit; static const TQ3Point3D off = {0,-25,-55}; /*******************/ /* CREATE SPIT WAD */ /*******************/ FindCoordOnJoint(bee, QUEENBEE_JOINT_HEAD, &off, &gNewObjectDefinition.coord); gNewObjectDefinition.group = MODEL_GROUP_LEVELSPECIFIC; gNewObjectDefinition.type = HIVE_MObjType_HoneyBlob; gNewObjectDefinition.flags = 0; gNewObjectDefinition.slot = 550; gNewObjectDefinition.moveCall = MoveQueenSpit; gNewObjectDefinition.rot = 0; gNewObjectDefinition.scale = .15; spit = MakeNewDisplayGroupObject(&gNewObjectDefinition); if (spit == nil) return; spit->WobbleBase = spit->Scale.x; /* SET COLLISION INFO */ spit->CType = CTYPE_VISCOUS; spit->CBits = CBITS_TOUCHABLE; SetObjectCollisionBounds(spit,300,0,-200,200,200,-200); spit->BoundingSphere.radius = 250; // Source port fix: Give it a generous culling sphere /* SET DELTAS */ r = bee->Rot.y; spit->Delta.x = -sin(r) * SPIT_SPEED; spit->Delta.z = -cos(r) * SPIT_SPEED; spit->Delta.y = 250; spit->HasSpawned = false; spit->SpitTimer = 80; } /**************** MOVE QUEEN SPIT ******************/ static void MoveQueenSpit(ObjNode *theNode) { float fps = gFramesPerSecondFrac; float y; float base; GetObjectInfo(theNode); theNode->SpitTimer -= fps; /****************/ /* MAKE GO AWAY */ /****************/ if (theNode->SpitTimer < 0.0f) { gCoord.y -= 40.0 * fps; if (gCoord.y < GetTerrainHeightAtCoord(gCoord.x, gCoord.z, FLOOR) - 400.0f) { DeleteObject(theNode); return; } } /*******************/ /* ACTIVE SPIT WAD */ /*******************/ else { /* MOVE */ ApplyFrictionToDeltas(5, &gDelta); gDelta.y -= 800.0f * fps; // gravity gCoord.x += gDelta.x * fps; gCoord.y += gDelta.y * fps; gCoord.z += gDelta.z * fps; y = GetTerrainHeightAtCoord(gCoord.x, gCoord.z, FLOOR) + 20.0f; if (gCoord.y < y) { gDelta.y *= -.3f; gCoord.y = y; } /* FADE */ // if (theNode->Health < .95f) // { // theNode->Health += fps * .05f; // if (theNode->Health > .95f) // theNode->Health = .95f; // // MakeObjectTransparent(theNode, theNode->Health); // } /* SCALE */ base = theNode->WobbleBase; theNode->WobbleX += fps * 4.5f; theNode->WobbleY -= fps * 5.0f; theNode->WobbleZ += fps * 4.0f; theNode->Scale.x = base + sin(theNode->WobbleX) * .2f * base; theNode->Scale.y = base + sin(theNode->WobbleY) * .2f * base; theNode->Scale.z = base + cos(theNode->WobbleZ) * .2f * base; if (theNode->WobbleBase < 2.2f) theNode->WobbleBase += fps * .5f; /***************/ /* SPAWN ENEMY */ /***************/ else { if (!theNode->HasSpawned) { theNode->HasSpawned = true; /* SEE WHICH ENEMY TO SPAWN */ if (gTheQueen->Health < (QUEENBEE_HEALTH/2)) { MakeFlyingBee(&gCoord); } else MakeLarvaEnemy(gCoord.x, gCoord.z); } } } /* UPDATE */ UpdateObject(theNode); }
1
0.862773
1
0.862773
game-dev
MEDIA
0.942779
game-dev
0.808377
1
0.808377
proletariatgames/unreal.hx
1,134
Haxe/Externs/UE4.19/unreal/UCloudStorageBase.hx
/** * * WARNING! This file was autogenerated by: * _ _ _ _ __ __ * | | | | | | |\ \ / / * | | | | |_| | \ V / * | | | | _ | / \ * | |_| | | | |/ /^\ \ * \___/\_| |_/\/ \/ * * This file was autogenerated by UnrealHxGenerator using UHT definitions. * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it! * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix **/ package unreal; /** WARNING: This type was not defined as DLL export on its declaration. Because of that, some of its methods are inaccessible Base class for the various platform interface classes. **/ @:glueCppIncludes("Engine/CloudStorageBase.h") @:noClass @:uextern @:uclass extern class UCloudStorageBase extends unreal.UPlatformInterfaceBase { /** If true, delegate callbacks should be skipped. **/ @:uproperty public var bSuppressDelegateCalls : Bool; /** When using local storage (aka "cloud emulation"), this maintains a list of the file paths. **/ @:uproperty public var LocalCloudFiles : unreal.TArray<unreal.FString>; }
1
0.761635
1
0.761635
game-dev
MEDIA
0.502527
game-dev
0.50134
1
0.50134
Balatro-Multiplayer/BalatroMultiplayer
1,721
objects/jokers/speedrun.lua
SMODS.Atlas({ key = "speedrun", path = "j_speedrun.png", px = 71, py = 95, }) SMODS.Joker({ key = "speedrun", atlas = "speedrun", rarity = 2, cost = 6, unlocked = true, discovered = true, blueprint_compat = true, eternal_compat = true, perishable_compat = true, loc_vars = function(self, info_queue, card) MP.UTILS.add_nemesis_info(info_queue) return { vars = {} } end, in_pool = function(self) return MP.LOBBY.code and MP.LOBBY.config.multiplayer_jokers end, calculate = function(self, card, context) if context.mp_speedrun and (not card.edition or card.edition.type ~= "mp_phantom") and #G.consumeables.cards + G.GAME.consumeable_buffer < G.consumeables.config.card_limit then G.GAME.consumeable_buffer = G.GAME.consumeable_buffer + 1 G.E_MANAGER:add_event(Event({ trigger = "before", delay = 0.0, func = function() local card = create_card("Spectral", G.consumeables, nil, nil, nil, nil, nil, "mp_speedrun") card:add_to_deck() G.consumeables:emplace(card) G.GAME.consumeable_buffer = 0 return true end, })) return { message = localize("k_plus_spectral"), colour = G.C.SECONDARY_SET.Spectral, card = card, } end end, add_to_deck = function(self, card, from_debuffed) if not from_debuffed and (not card.edition or card.edition.type ~= "mp_phantom") then MP.ACTIONS.send_phantom("j_mp_speedrun") end end, remove_from_deck = function(self, card, from_debuff) if not from_debuff and (not card.edition or card.edition.type ~= "mp_phantom") then MP.ACTIONS.remove_phantom("j_mp_speedrun") end end, mp_credits = { idea = { "Virtualized" }, art = { "Aura!" }, code = { "Virtualized" }, }, })
1
0.888253
1
0.888253
game-dev
MEDIA
0.98364
game-dev
0.979088
1
0.979088
crossmob/CrossMobile
4,335
cmioslayer/src/main/java/crossmobile/ios/uikit/UIPinchGestureRecognizer.java
/* * (c) 2023 by Panayotis Katsaloulis * * SPDX-License-Identifier: LGPL-3.0-only */ package crossmobile.ios.uikit; import crossmobile.ios.foundation.NSSelector; import org.crossmobile.bind.graphics.Geometry; import org.crossmobile.bind.system.VelocityFilter; import org.crossmobile.bridge.ann.*; import java.util.Iterator; import java.util.Set; import static crossmobile.ios.uikit.UIGestureRecognizerState.*; /** * UIPinchGestureRecognizer class extends UIGestureRecognizer and recognizes * pinch gestures when two fingers touching the screen get near or move away * translated to zoom in and zoom out respectively. */ @CMClass public class UIPinchGestureRecognizer extends UIGestureRecognizer { private double scale; private float last_distance; private float initial_distance; private final VelocityFilter velocity; /** * Constructs a new UIPinchGestureRecognizer object and attaches it to the * specified UIGestureRecognizer. * * @param target The UIGestureRecognizer to which the new object is attached * to. */ public UIPinchGestureRecognizer(@CMParamMod(association = AssociationType.ADDSELF) @CMJoinSEL(selector = "action", target = "target") NSSelector<UIGestureRecognizer> target) { super(target); velocity = new VelocityFilter(); } /** * Returns the scale factor relative to the point of the two touches.The * points are expressed in screen's coordinates. * * @return The scale factor relative to the point of the two touches. */ @CMGetter("@property(nonatomic) CGFloat scale;") public double scale() { return scale; } /** * Sets the scale factor relative to the point of the two touches. The * points are expressed in screen's coordinates. * * @param scale The scale factor relative to the point of the two touches. */ @CMSetter("@property(nonatomic) CGFloat scale;") public void setScale(double scale) { this.scale = scale; velocity.reset(); initial_distance = last_distance; } /** * Returns the velocity of the pinch.(in scale factor per sec) * * @return The velocity of the pinch */ @CMGetter("@property(nonatomic, readonly) CGFloat velocity;") public double velocity() { return velocity.getValue(); } @Override public void reset() { if (velocity != null) velocity.reset(); scale = 1; initial_distance = 0; last_distance = 0; } private void update(UITouch one, UITouch two, boolean asFirst) { last_distance = distance(one, two); if (asFirst) initial_distance = last_distance; velocity.put(one.timestamp, 1); } @Override public void touchesBegan(Set<UITouch> touches, UIEvent event) { Iterator<UITouch> iterator = touches.iterator(); if (state() == Possible) { if (touches.size() == 2) { setState(Began); update(iterator.next(), iterator.next(), true); } } else if (state() == Began || state() == Changed) if (touches.size() == 2) { setState(Changed); update(iterator.next(), iterator.next(), false); } else setState(Ended); } @Override public void touchesMoved(Set<UITouch> touches, UIEvent event) { touchesBegan(touches, event); } @Override public void touchesEnded(Set<UITouch> touches, UIEvent event) { touchesBegan(touches, event); if (state() == Began || state() == Changed) setState(Ended); } @Override public void touchesCancelled(Set<UITouch> touches, UIEvent event) { setState(Cancelled); } @Override public boolean canBePreventedByGestureRecognizer(UIGestureRecognizer preventing) { return false; } @Override public boolean canPreventGestureRecognizer(UIGestureRecognizer preventing) { return false; } private static float distance(UITouch one, UITouch two) { float distance = Geometry.distance(one.locationInView(one.view), two.locationInView(one.view)); if (distance < 1) distance = 1; return distance; } }
1
0.907763
1
0.907763
game-dev
MEDIA
0.52026
game-dev,mobile
0.959033
1
0.959033
activityworkshop/GpsPrune
2,096
src/tim/prune/function/filesleuth/data/LocationFilter.java
package tim.prune.function.filesleuth.data; import tim.prune.data.DataPoint; import tim.prune.data.Distance; import tim.prune.data.Unit; import tim.prune.data.UnitSetLibrary; public class LocationFilter { private final DataPoint _point; private final String _pointDescription; private final int _distanceValue; private final Unit _distanceUnit; private final double _distanceInMetres; private final double _distanceInRadians; public LocationFilter(DataPoint inPoint, String inDescription, int inDistanceValue, Unit inDistanceUnit) { _point = inPoint; _pointDescription = inDescription; _distanceValue = inDistanceValue; _distanceUnit = inDistanceUnit; _distanceInMetres = Distance.convertBetweenUnits(inDistanceValue, inDistanceUnit, UnitSetLibrary.UNITS_METRES); _distanceInRadians = Distance.convertDistanceToRadians( inDistanceValue, inDistanceUnit); } public DataPoint getPoint() { return _point; } public String getPointDescription() { return _pointDescription; } public int getDistanceValue() { return _distanceValue; } public Unit getDistanceUnit() { return _distanceUnit; } public double getDistanceInMetres() { return _distanceInMetres; } public double getDistanceInRadians() { return _distanceInRadians; } /** Check if the given point coordinates lies within this filter */ public boolean doesLocationMatch(double inLatitude, double inLongitude) { final double filterLatitude = _point.getLatitude().getDouble(); final double filterLongitude = _point.getLongitude().getDouble(); final double calculatedRadians = Distance.calculateRadiansBetween(filterLatitude, filterLongitude, inLatitude, inLongitude); return calculatedRadians <= _distanceInRadians; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } LocationFilter other = (LocationFilter) obj; return _point == other._point && _distanceUnit == other._distanceUnit && _distanceValue == other._distanceValue; } }
1
0.688476
1
0.688476
game-dev
MEDIA
0.375731
game-dev
0.858534
1
0.858534
codingburgas/Control-Break
3,662
Soultern/Assets/Scripts/MenuManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class MenuManager : MonoBehaviour { private DeathManager DeathManager; private CheckpointManager CheckpointManager; private ExtraFunctions ExtraFunctions; private GameObject YouDiedMenu; private GameObject GameOverMenu; private GameObject PauseMenu; private GameObject StaminaBar; [HideInInspector] public bool YouDied; [HideInInspector] public bool IsGameOver; [HideInInspector] public bool IsPaused; void Start() { if (SceneManager.GetActiveScene().name != "Game") return; DeathManager = GameObject.Find("DeathManager").GetComponent<DeathManager>(); CheckpointManager = GameObject.Find("CheckpointManager").GetComponent<CheckpointManager>(); ExtraFunctions = GameObject.Find("ExtraFunctions").GetComponent<ExtraFunctions>(); YouDiedMenu = ExtraFunctions.FindInactive("You Died Menu"); GameOverMenu = ExtraFunctions.FindInactive("Game Over Menu"); PauseMenu = ExtraFunctions.FindInactive("Pause Menu"); StaminaBar = GameObject.Find("Stamina Bar"); } void Update() { if (SceneManager.GetActiveScene().name != "Game") return; if (DeathManager.IsDead && !YouDied && CheckpointManager.Lives > 0) DisplayYouDiedMenu(); if (DeathManager.IsDead && !IsGameOver && CheckpointManager.Lives == 0) DisplayGameOverMenu(); if (Input.GetKeyDown(KeyCode.Escape)) DisplayPauseMenu(); } public void DisplayYouDiedMenu() { YouDiedMenu.SetActive(!YouDied); StaminaBar.SetActive(YouDied); Time.timeScale = System.Convert.ToSingle(YouDied); ToggleDialogueBox(YouDied); YouDied = !YouDied; PauseMusic(); } public void DisplayGameOverMenu() { GameOverMenu.SetActive(!IsGameOver); StaminaBar.SetActive(IsGameOver); Time.timeScale = System.Convert.ToSingle(IsGameOver); ToggleDialogueBox(IsGameOver); IsGameOver = !IsGameOver; PauseMusic(); } public void DisplayPauseMenu() { PauseMenu.SetActive(!IsPaused); StaminaBar.SetActive(IsPaused); Time.timeScale = System.Convert.ToSingle(IsPaused); ToggleDialogueBox(IsPaused); IsPaused = !IsPaused; PauseMusic(); } void PauseMusic() { AudioSource Music = Camera.main.GetComponent<AudioSource>(); if (Music.isPlaying) Music.Pause(); else Music.Play(); } void ToggleDialogueBox(bool State) { GameObject DialogueBox = ExtraFunctions.FindInactive("Dialogue Box"); if (DialogueBox.activeSelf) DialogueBox.SetActive(State); } // Difficulty public void SaveDifficulty() { PlayerPrefs.SetInt("Difficulty", GameObject.Find("Difficulty").GetComponent<Dropdown>().value); } // Main Menu public void MainMenu() { SceneManager.LoadScene("Main Menu", LoadSceneMode.Single); } public void Difficulty() { SceneManager.LoadScene("Difficulty", LoadSceneMode.Single); } public void NewGame() { SceneManager.LoadScene("Game", LoadSceneMode.Single); } public void Settings() { SceneManager.LoadScene("Settings", LoadSceneMode.Single); } public void Quit() { Application.Quit(); } public void Credits() { SceneManager.LoadScene("Credits", LoadSceneMode.Single); } }
1
0.816649
1
0.816649
game-dev
MEDIA
0.922059
game-dev
0.887618
1
0.887618
Planimeter/hl2sb-src
2,161
src/game/client/playerandobjectenumerator.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "playerandobjectenumerator.h" #include "c_ai_basenpc.h" #ifdef INVASION_CLIENT_DLL #include "tf_shareddefs.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Enumator class for ragdolls being affected by explosive forces CPlayerAndObjectEnumerator::CPlayerAndObjectEnumerator( float radius ) { m_flRadiusSquared = radius * radius; m_Objects.RemoveAll(); m_pLocal = C_BasePlayer::GetLocalPlayer(); } int CPlayerAndObjectEnumerator::GetObjectCount() { return m_Objects.Size(); } C_BaseEntity *CPlayerAndObjectEnumerator::GetObject( int index ) { if ( index < 0 || index >= GetObjectCount() ) return NULL; return m_Objects[ index ]; } // Actual work code IterationRetval_t CPlayerAndObjectEnumerator::EnumElement( IHandleEntity *pHandleEntity ) { if ( !m_pLocal ) return ITERATION_STOP; C_BaseEntity *pEnt = ClientEntityList().GetBaseEntityFromHandle( pHandleEntity->GetRefEHandle() ); if ( pEnt == NULL ) return ITERATION_CONTINUE; if ( pEnt == m_pLocal ) return ITERATION_CONTINUE; if ( !pEnt->IsPlayer() && !pEnt->IsNPC() ) { return ITERATION_CONTINUE; } if ( pEnt->IsNPC() ) { C_AI_BaseNPC *pNPC = (C_AI_BaseNPC *)pEnt; if ( !pNPC->ShouldAvoidObstacle() ) return ITERATION_CONTINUE; } // Ignore vehicles, since they have vcollide collisions that's push me away if ( pEnt->GetCollisionGroup() == COLLISION_GROUP_VEHICLE ) return ITERATION_CONTINUE; #ifdef INVASION_CLIENT_DLL // If it's solid to player movement, don't steer around it since we'll just bump into it if ( pEnt->GetCollisionGroup() == TFCOLLISION_GROUP_OBJECT_SOLIDTOPLAYERMOVEMENT ) return ITERATION_CONTINUE; #endif Vector deltaPos = pEnt->GetAbsOrigin() - m_pLocal->GetAbsOrigin(); if ( deltaPos.LengthSqr() > m_flRadiusSquared ) return ITERATION_CONTINUE; CHandle< C_BaseEntity > h; h = pEnt; m_Objects.AddToTail( h ); return ITERATION_CONTINUE; }
1
0.988132
1
0.988132
game-dev
MEDIA
0.368116
game-dev
0.994691
1
0.994691
Earthcomputer/clientcommands
1,403
src/main/java/net/earthcomputer/clientcommands/event/MoreWorldRenderEvents.java
package net.earthcomputer.clientcommands.event; import com.mojang.blaze3d.vertex.PoseStack; import net.fabricmc.fabric.api.event.Event; import net.fabricmc.fabric.api.event.EventFactory; import net.minecraft.client.Camera; import net.minecraft.client.DeltaTracker; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.state.LevelRenderState; public final class MoreWorldRenderEvents { private MoreWorldRenderEvents() { } public static final Event<ExtractState> EXTRACT_STATE = EventFactory.createArrayBacked(ExtractState.class, listeners -> (state, camera, deltaTracker) -> { for (ExtractState listener : listeners) { listener.extractState(state, camera, deltaTracker); } }); public static final Event<EndMainPass> END_MAIN_PASS = EventFactory.createArrayBacked(EndMainPass.class, listeners -> (bufferSource, poseStack, state) -> { for (EndMainPass listener : listeners) { listener.endMainPass(bufferSource, poseStack, state); } }); @FunctionalInterface public interface ExtractState { void extractState(LevelRenderState state, Camera camera, DeltaTracker deltaTracker); } @FunctionalInterface public interface EndMainPass { void endMainPass(MultiBufferSource.BufferSource bufferSource, PoseStack poseStack, LevelRenderState state); } }
1
0.767914
1
0.767914
game-dev
MEDIA
0.765068
game-dev
0.617533
1
0.617533
keijiro/Lasp
4,061
Assets/Test/DeviceSelector.cs
using UnityEngine; using UnityEngine.UI; using System.Linq; // // Runtime device selection and AudioLevelTracker instantiation example // // Usually, autio level trackers are configured on Editor, but in some use // cases, you may want to instantiate and configure them at run time. This // example shows how to select an input device using the AudioSystem properties // and instantiate an audio level tracker from it at run time. It also shows // how to construct property binders programmatically. // sealed class DeviceSelector : MonoBehaviour { #region Scene object references [SerializeField] Dropdown _deviceList = null; [SerializeField] Dropdown _channelList = null; [SerializeField] Transform _targetTransform = null; #endregion #region Custom dropdown item class // // We want the dropdown items to have device identifier, so we extend the // OptionData class to add an ID field. Also we add a constructor that // initializes the data from a device descriptor. // class DeviceItem : Dropdown.OptionData { public string id; public DeviceItem(in Lasp.DeviceDescriptor device) => (text, id) = (device.Name, device.ID); } #endregion #region MonoBehaviour implementation Lasp.AudioLevelTracker _tracker; void Start() { _deviceList.ClearOptions(); _channelList.ClearOptions(); // // Construct the device selection dropdown list. // // LASP provides IEnumerable of currently available audio input devices // via AudioSystem.InputDevices. Here we construct a dropdown list from // it using LINQ. // _deviceList.options.AddRange (Lasp.AudioSystem.InputDevices.Select(dev => new DeviceItem(dev))); _deviceList.RefreshShownValue(); // // If there is any input device, select the first one (the system // default input device). // if (Lasp.AudioSystem.InputDevices.Any()) OnDeviceSelected(0); } void Update() { // // Apply the channel selection to the audio level tracker. // if (_tracker != null) _tracker.channel = _channelList.value; } #endregion #region UI callback public void OnDeviceSelected(int index) { // Retrieve the device ID from the dropdown item data. var id = ((DeviceItem)_deviceList.options[index]).id; // // Retrieve a descriptor of the selected device using the ID. // var dev = Lasp.AudioSystem.GetInputDevice(id); // // The device descriptor struct has several attributes, like the number // of the channels, the sampling rate, etc. Here we construct the // channel selection dropdown list from the descriptor. // _channelList.options = Enumerable.Range(0, dev.ChannelCount). Select(i => $"Channel {i + 1}"). Select(text => new Dropdown.OptionData(){ text = text }).ToList(); _channelList.value = 0; _channelList.RefreshShownValue(); // Destroy the previously created level tracker object... if (_tracker != null) Destroy(_tracker.gameObject); // ...then create a new one. var gameObject = new GameObject("Level Tracker"); // // Add the LASP audio level tracker component to the game object and // make it use the selected device. // _tracker = gameObject.AddComponent<Lasp.AudioLevelTracker>(); _tracker.deviceID = dev.ID; // // Add a property binder to the tracker that controls the scale of the // target transform based on a normalize audio level. // _tracker.propertyBinders = new [] { new Lasp.Vector3PropertyBinder { Target = _targetTransform, PropertyName = "localScale", Value0 = Vector3.zero, Value1 = Vector3.one } }; } #endregion }
1
0.891173
1
0.891173
game-dev
MEDIA
0.640903
game-dev,desktop-app
0.941218
1
0.941218
Minecraft-LightLand/Youkai-Homecoming
2,322
src/main/java/dev/xkmc/youkaishomecoming/compat/food/FruitsDelightCompatDrink.java
package dev.xkmc.youkaishomecoming.compat.food; import com.tterrag.registrate.util.entry.FluidEntry; import com.tterrag.registrate.util.entry.ItemEntry; import dev.xkmc.youkaishomecoming.content.item.fluid.*; import dev.xkmc.youkaishomecoming.init.food.EffectEntry; import dev.xkmc.youkaishomecoming.init.food.FoodType; import dev.xkmc.youkaishomecoming.init.registrate.YHEffects; import net.minecraft.tags.TagKey; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Locale; public enum FruitsDelightCompatDrink implements IYHFluidHolder { MOON_ROCKET(FoodType.BOTTLE_FAST, 0xffffffff, List.of( new EffectEntry(() -> MobEffects.JUMP, 100, 1))), LEMON_BLACK_TEA(FoodType.BOTTLE_FAST, 0xffffffff, List.of( new EffectEntry(YHEffects.SOBER, 600, 0, 1), new EffectEntry(YHEffects.THICK, 600, 0, 1) )), ; public final int color; public final String folder; public final FluidEntry<YHFluid> fluid; public final ItemEntry<Item> item; @SafeVarargs FruitsDelightCompatDrink(FoodType type, int color, List<EffectEntry> effs, TagKey<Item>... tags) { this.color = color; String name = name().toLowerCase(Locale.ROOT); fluid = BottledFluid.water(name, (p, s, f) -> new YHFluidType(p, s, f, this), p -> new YHFluid(p, this)) .defaultLang().register(); folder = "fruitsdelight"; item = type.build(p -> new SakeBottleItem(fluid::getSource, p), folder + "/", name, 0, 0, tags, effs); } @Override public int getColor() { return color; } @Override public ItemEntry<?> item() { return item; } @Override public YHFluid source() { return fluid.getSource(); } @Override public @Nullable String bottleTextureFolder() { return folder; } @Override public Item asItem() { return item.asItem(); } @SuppressWarnings("deprecation") public Item getContainer() { Item ans = item.get().getCraftingRemainingItem(); if (ans == null) return Items.AIR; return ans; } public String getName() { return name().toLowerCase(Locale.ROOT); } @Override public ItemStack asStack(int count) { return item.asStack(count); } public static void register() { } }
1
0.818237
1
0.818237
game-dev
MEDIA
0.957579
game-dev
0.979212
1
0.979212
Goob-Station/Goob-Station-MRP
4,369
Content.Server/Punpun/PunpunSystem.cs
using System.Linq; using Content.Server.GameTicking; using Content.Shared.Containers.ItemSlots; using Content.Shared.Inventory; using Content.Shared.Mobs; using Content.Shared.Mobs.Components; using Robust.Server.GameObjects; namespace Content.Server.Punpun; public sealed class PunpunSystem : EntitySystem { [Dependency] private readonly InventorySystem _inventory = default!; [Dependency] private readonly ServerMetaDataSystem _meta = default!; private (int, string, string, string) _punpunData = (1, string.Empty, string.Empty, string.Empty); public override void Initialize() { base.Initialize(); SubscribeLocalEvent<PunpunComponent, ComponentStartup>(OnRoundStart); SubscribeLocalEvent<RoundEndTextAppendEvent>(OnRoundEnd); } // Checks if the Punpun data has any items to equip, and names the Punpun upon initialization private void OnRoundStart(EntityUid uid, PunpunComponent component, ComponentStartup args) { if (_punpunData.Item1 > component.Lifetime) { EntityManager.SpawnEntity("PaperWrittenPunpunNote", Transform(uid).Coordinates); EntityManager.QueueDeleteEntity(uid); _punpunData = (1, string.Empty, string.Empty, string.Empty); return; } var meta = MetaData(uid); _meta.SetEntityName(uid, $"{meta.EntityName} {ToRomanNumeral(_punpunData.Item1)}", meta); if (!EntityManager.TryGetComponent<InventoryComponent>(uid, out _)) return; EquipItem(uid, "head", _punpunData.Item2); EquipItem(uid, "mask", _punpunData.Item3); EquipItem(uid, "jumpsuit", _punpunData.Item4); } // Checks if Punpun exists, and is alive at round end // If so, stores the items and increments the Punpun count private void OnRoundEnd(RoundEndTextAppendEvent ev) { // I couldn't find a method to get a single entity, so this just enumerates over the first and disposes it var punpunComponents = EntityManager.EntityQueryEnumerator<PunpunComponent>(); punpunComponents.MoveNext(out var punpun, out _); if (!EntityManager.TryGetComponent<MobStateComponent>(punpun, out var mobState) || mobState.CurrentState == MobState.Dead) _punpunData = (1, string.Empty, string.Empty, string.Empty); _punpunData.Item1++; if (EntityManager.HasComponent<InventoryComponent>(punpun)) { _punpunData.Item2 = CheckSlot(punpun, "head"); _punpunData.Item3 = CheckSlot(punpun, "mask"); _punpunData.Item4 = CheckSlot(punpun, "jumpsuit"); } punpunComponents.Dispose(); } // Equips an item to a slot, and names it. private void EquipItem(EntityUid uid, string slot, string item) { if (item == string.Empty) return; var itemEnt = EntityManager.SpawnEntity(item, EntityManager.GetComponent<TransformComponent>(uid).Coordinates); if (_inventory.TryEquip(uid, itemEnt, slot, true, true)) _meta.SetEntityName(itemEnt, $"{MetaData(uid).EntityName}'s {MetaData(itemEnt).EntityName}"); else EntityManager.DeleteEntity(itemEnt); } // Checks if an item exists in a slot, and returns its name private string CheckSlot(EntityUid uid, string slot) { return _inventory.TryGetSlotEntity(uid, slot, out var item) ? EntityManager.GetComponent<MetaDataComponent>(item.Value).EntityPrototype!.ID : string.Empty; } // Punpun, the lord of Roman Numerals public static List<string> RomanNumerals = new() { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; public static List<int> Numerals = new() { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; public static string ToRomanNumeral(int number) { var romanNumeral = string.Empty; while (number > 0) { // Find the biggest numeral that is less than equal to number var index = Numerals.FindIndex(x => x <= number); // Subtract its value from your number number -= Numerals[index]; // Add it onto the end of your roman numeral romanNumeral += RomanNumerals[index]; } return romanNumeral; } }
1
0.80341
1
0.80341
game-dev
MEDIA
0.926364
game-dev
0.82451
1
0.82451
Ayfri/Kore
2,443
kore/src/main/kotlin/io/github/ayfri/kore/arguments/components/item/BlockEntityDataComponent.kt
package io.github.ayfri.kore.arguments.components.item import io.github.ayfri.kore.arguments.components.Component import io.github.ayfri.kore.arguments.components.ComponentsScope import io.github.ayfri.kore.arguments.types.resources.BlockArgument import io.github.ayfri.kore.generated.ItemComponentTypes import io.github.ayfri.kore.serializers.NbtAsJsonSerializer import io.github.ayfri.kore.utils.nbt import io.github.ayfri.kore.utils.set import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.json.JsonEncoder import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.put import net.benwoodworth.knbt.NbtCompound import net.benwoodworth.knbt.NbtCompoundBuilder import net.benwoodworth.knbt.NbtEncoder @Serializable(with = BlockEntityDataComponent.Companion.BlockEntityDataComponentSerializer::class) data class BlockEntityDataComponent( var id: BlockArgument, var data: NbtCompound? = null, ) : Component() { companion object { object BlockEntityDataComponentSerializer : KSerializer<BlockEntityDataComponent> { override val descriptor = NbtCompound.serializer().descriptor override fun serialize(encoder: Encoder, value: BlockEntityDataComponent) = when (encoder) { is NbtEncoder -> { encoder.encodeNbtTag(nbt { this["id"] = value.id.asId() value.data?.forEach { (key, value) -> this[key] = value } }) } is JsonEncoder -> { encoder.encodeJsonElement(buildJsonObject { val data = value.data ?: nbt {} val dataAsJson = encoder.json.encodeToJsonElement(NbtAsJsonSerializer, data).jsonObject put("id", value.id.asId()) dataAsJson.forEach { (key, value) -> put(key, value) } }) } else -> error("BlockEntityDataComponent is not serializable.") } override fun deserialize(decoder: Decoder) = error("BlockEntityDataComponent is not deserializable.") } } } fun ComponentsScope.blockEntityData(id: BlockArgument, data: NbtCompound? = null) = apply { this[ItemComponentTypes.BLOCK_ENTITY_DATA] = BlockEntityDataComponent(id, data) } fun ComponentsScope.blockEntityData(id: BlockArgument, block: NbtCompoundBuilder.() -> Unit) = apply { this[ItemComponentTypes.BLOCK_ENTITY_DATA] = BlockEntityDataComponent(id, nbt(block)) }
1
0.874876
1
0.874876
game-dev
MEDIA
0.634552
game-dev
0.673505
1
0.673505
BahamutDragon/pcgen
12,447
data/starwars/wizards_of_the_coast/starwars_core_rulebook/sw__sizes.lst
Fine ABB:F DISPLAYNAME:Fine BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|0.5 F.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|0.1 BONUS:ITEMWEIGHT|TYPE=Goods|0.25 F.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|0.5 BONUS:COMBAT|AC|8|TYPE=Size BONUS:COMBAT|TOHIT|8|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|-24|TYPE=Size F.MOD BONUS:ITEMCAPACITY|TYPE=Goods|0.25 F.MOD BONUS:SKILL|Hide|16|TYPE=SIZE F.MOD BONUS:LOADMULT|TYPE=SIZE|0.125|PRELEGSGTEQ:4 # Diminutive ABB:D DISPLAYNAME:Diminutive BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|0.5 D.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|0.1 BONUS:ITEMWEIGHT|TYPE=Goods|0.25 D.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|0.5 BONUS:COMBAT|AC|4|TYPE=Size BONUS:COMBAT|TOHIT|4|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|-16|TYPE=Size D.MOD BONUS:ITEMCAPACITY|TYPE=Goods|0.25 D.MOD BONUS:SKILL|Hide|12|TYPE=SIZE D.MOD BONUS:LOADMULT|TYPE=SIZE|0.25|PRELEGSGTEQ:4 D.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 # Tiny ABB:T DISPLAYNAME:Tiny BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|0.5 T.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|0.1 BONUS:ITEMWEIGHT|TYPE=Goods|0.25 T.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|0.5 BONUS:COMBAT|AC|2|TYPE=Size BONUS:COMBAT|TOHIT|2|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|-10|TYPE=Size T.MOD BONUS:ITEMCAPACITY|TYPE=Goods|0.25 T.MOD BONUS:SKILL|Hide|8|TYPE=SIZE T.MOD BONUS:LOADMULT|TYPE=SIZE|0.25|PRELEGSGTEQ:4 T.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 T.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 # Small ABB:S DISPLAYNAME:Small BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|1 S.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|0.5 BONUS:ITEMWEIGHT|TYPE=Goods|0.25 S.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|1 BONUS:COMBAT|AC|1|TYPE=Size BONUS:COMBAT|TOHIT|1|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|-5|TYPE=Size S.MOD BONUS:ITEMCAPACITY|TYPE=Goods|0.25 S.MOD BONUS:SKILL|Hide|4|TYPE=SIZE S.MOD BONUS:LOADMULT|TYPE=SIZE|0.25|PRELEGSGTEQ:4 S.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 S.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 # Medium ABB:M DISPLAYNAME:Medium BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|1 M.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|1 BONUS:ITEMWEIGHT|TYPE=Goods|1 M.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|1 M.MOD BONUS:ITEMCAPACITY|TYPE=Goods|1 ISDEFAULTSIZE:Y M.MOD BONUS:LOADMULT|TYPE=SIZE|0.5|PRELEGSGTEQ:4 M.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 M.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 M.MOD BONUS:STAT|CON|2|PREBASESIZELT:Medium # Large ABB:L DISPLAYNAME:Large BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|2 L.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|2 BONUS:ITEMWEIGHT|TYPE=Goods|1 L.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|1 BONUS:COMBAT|AC|-1|TYPE=Size BONUS:COMBAT|TOHIT|-1|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|5|TYPE=Size L.MOD BONUS:ITEMCAPACITY|TYPE=Goods|1 L.MOD BONUS:SKILL|Hide|-4|TYPE=SIZE L.MOD BONUS:LOADMULT|TYPE=SIZE|1|PRELEGSGTEQ:4 L.MOD BONUS:COMBAT|AC|2|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Medium|PREVAREQ:BypassSizeMods,0 L.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 L.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 L.MOD BONUS:STAT|CON|2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 # Huge ABB:H DISPLAYNAME:Huge BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|4 H.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|5 BONUS:ITEMWEIGHT|TYPE=Goods|1 H.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|1 BONUS:COMBAT|AC|-2|TYPE=Size BONUS:COMBAT|TOHIT|-2|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|10|TYPE=Size H.MOD BONUS:ITEMCAPACITY|TYPE=Goods|1 H.MOD BONUS:SKILL|Hide|-8|TYPE=SIZE H.MOD BONUS:LOADMULT|TYPE=SIZE|2|PRELEGSGTEQ:4 H.MOD BONUS:COMBAT|AC|2|PREBASESIZELTEQ:Medium|TYPE=NaturalArmor.STACK BONUS:COMBAT|AC|3|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Large|PREVAREQ:BypassSizeMods,0 H.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 H.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 H.MOD BONUS:STAT|CON|2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 # Gargantuan ABB:G DISPLAYNAME:Gargantuan BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|8 G.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|8 BONUS:ITEMWEIGHT|TYPE=Goods|1 G.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|1 BONUS:COMBAT|AC|-4|TYPE=Size BONUS:COMBAT|TOHIT|-4|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|16|TYPE=Size G.MOD BONUS:ITEMCAPACITY|TYPE=Goods|1 G.MOD BONUS:SKILL|Hide|-12|TYPE=SIZE G.MOD BONUS:LOADMULT|TYPE=SIZE|4|PRELEGSGTEQ:4 G.MOD BONUS:COMBAT|AC|2|PREBASESIZELTEQ:Medium|TYPE=NaturalArmor.STACK|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|3|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Large|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|4|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Huge|PREVAREQ:BypassSizeMods,0 G.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Gargantuan|PREVAREQ:BypassSizeMods,0 G.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 G.MOD BONUS:STAT|CON|2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Gargantuan|PREVAREQ:BypassSizeMods,0 # Colossal ABB:C DISPLAYNAME:Colossal BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|16 C.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|12 BONUS:ITEMWEIGHT|TYPE=Goods|1 C.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|1 BONUS:COMBAT|AC|-8|TYPE=Size BONUS:COMBAT|TOHIT|-8|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|24|TYPE=Size C.MOD BONUS:ITEMCAPACITY|TYPE=Goods|1 C.MOD BONUS:SKILL|Hide|-16|TYPE=SIZE C.MOD BONUS:LOADMULT|TYPE=SIZE|8|PRELEGSGTEQ:4 C.MOD BONUS:COMBAT|AC|2|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Medium|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|3|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Large|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|4|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Huge|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|5|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Gargantuan|PREVAREQ:BypassSizeMods,0 C.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Gargantuan BONUS:STAT|STR|8|PREBASESIZELT:Colossal|PREVAREQ:BypassSizeMods,0 C.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 C.MOD BONUS:STAT|CON|2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Gargantuan|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Colossal|PREVAREQ:BypassSizeMods,0 # ColossalPlus ABB:P DISPLAYNAME:Colossal+ BONUS:ITEMCOST|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|16 P.MOD BONUS:ITEMWEIGHT|TYPE=Ammunition,TYPE=Armor,TYPE=Shield,TYPE=Weapon|12 BONUS:ITEMWEIGHT|TYPE=Goods|1 P.MOD BONUS:ACVALUE|TYPE.Armor,TYPE.Shield|1 BONUS:COMBAT|AC|-8|TYPE=Size BONUS:COMBAT|TOHIT|-8|TYPE=SIZE BONUS:COMBAT|TOHIT.GRAPPLE|24|TYPE=Size P.MOD BONUS:ITEMCAPACITY|TYPE=Goods|1 P.MOD BONUS:SKILL|Hide|-16|TYPE=SIZE P.MOD BONUS:LOADMULT|TYPE=SIZE|8|PRELEGSGTEQ:4 P.MOD BONUS:COMBAT|AC|2|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Medium|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|3|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Large|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|4|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Huge|PREVAREQ:BypassSizeMods,0 BONUS:COMBAT|AC|5|TYPE=NaturalArmor.STACK|PREBASESIZELTEQ:Gargantuan|PREVAREQ:BypassSizeMods,0 P.MOD BONUS:STAT|STR|2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|4|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Gargantuan|PREVAREQ:BypassSizeMods,0 BONUS:STAT|STR|8|PREBASESIZELT:Colossal|PREVAREQ:BypassSizeMods,0 P.MOD BONUS:STAT|DEX|-2|PREBASESIZEEQ:Fine|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Tiny|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Small|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|DEX|-2|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 P.MOD BONUS:STAT|CON|2|PREBASESIZELT:Medium|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Large|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Huge|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Gargantuan|PREVAREQ:BypassSizeMods,0 BONUS:STAT|CON|4|PREBASESIZELT:Colossal|PREVAREQ:BypassSizeMods,0 ###Block: SIZENUM F.MOD SIZENUM:010 D.MOD SIZENUM:020 T.MOD SIZENUM:030 S.MOD SIZENUM:040 M.MOD SIZENUM:050 L.MOD SIZENUM:060 H.MOD SIZENUM:070 G.MOD SIZENUM:080 C.MOD SIZENUM:090 P.MOD SIZENUM:100
1
0.945499
1
0.945499
game-dev
MEDIA
0.964968
game-dev
0.827088
1
0.827088
bberberov/scorched3d
2,309
src/common/placement/PlacementTypeDirect.cpp
//////////////////////////////////////////////////////////////////////////////// // Scorched3D (c) 2000-2011 // // This file is part of Scorched3D. // // Scorched3D 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. // // Scorched3D is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //////////////////////////////////////////////////////////////////////////////// #include <placement/PlacementTypeDirect.hpp> #include <landscapemap/LandscapeMaps.hpp> #include <engine/ScorchedContext.hpp> #include <common/ProgressCounter.hpp> #include <XML/XMLParser.hpp> PlacementTypeDirect::PlacementTypeDirect() { } PlacementTypeDirect::~PlacementTypeDirect() { } bool PlacementTypeDirect::readXML(XMLNode *node) { XMLNode *positionNode; while (node->getNamedChild("position", positionNode, false)) { Position position; if (!positionNode->getNamedChild("position", position.position)) return false; positions.push_back(position); if (!positionNode->failChildren()) return false; } return PlacementType::readXML(node); } void PlacementTypeDirect::getPositions(ScorchedContext &context, RandomGenerator &generator, std::list<Position> &returnPositions, ProgressCounter *counter) { std::list<Position>::iterator itor; int i = 0; for (itor = positions.begin(); itor != positions.end(); ++itor, i++) { if (i % 10 == 0) if (counter) counter->setNewPercentage(float(i)/float(positions.size())*100.0f); Position position = (*itor); fixed height = context.getLandscapeMaps(). getGroundMaps().getInterpHeight(position.position[0], position.position[1]); if (position.position[2] == 0) position.position[2] = height; returnPositions.push_back(position); } }
1
0.91751
1
0.91751
game-dev
MEDIA
0.302854
game-dev
0.839408
1
0.839408
mars-sim/mars-sim
2,743
mars-sim-core/src/main/java/com/mars_sim/core/person/ai/task/meta/DelegateWorkMeta.java
/* * Mars Simulation Project * DelegateWorkMeta.java * @date 2023-06-16 * @author Manny Kung */ package com.mars_sim.core.person.ai.task.meta; import java.util.List; import com.mars_sim.core.building.Building; import com.mars_sim.core.building.BuildingManager; import com.mars_sim.core.building.function.FunctionType; import com.mars_sim.core.data.RatingScore; import com.mars_sim.core.person.Person; import com.mars_sim.core.person.ai.role.RoleType; import com.mars_sim.core.person.ai.task.DelegateWork; import com.mars_sim.core.person.ai.task.util.FactoryMetaTask; import com.mars_sim.core.person.ai.task.util.Task; import com.mars_sim.core.person.ai.task.util.TaskJob; import com.mars_sim.core.person.ai.task.util.TaskTrait; import com.mars_sim.core.tool.Msg; /** * The meta task for delegating work. */ public class DelegateWorkMeta extends FactoryMetaTask { /** Task name */ private static final String NAME = Msg.getString( "Task.description.delegateWork"); //$NON-NLS-1$ public DelegateWorkMeta() { super(NAME, WorkerType.PERSON, TaskScope.ANY_HOUR); setTrait(TaskTrait.ORGANIZATION, TaskTrait.LEADERSHIP); setPreferredRole(RoleType.CREW_OPERATION_OFFICER); addAllLeadershipRoles(); } @Override public Task constructInstance(Person person) { return new DelegateWork(person); } @Override public List<TaskJob> getTaskJobs(Person person) { RoleType roleType = person.getRole().getType(); if (!person.isInside() || !roleType.isLeadership() || !person.getPhysicalCondition().isFitByLevel(1000, 70, 1000)) { return EMPTY_TASKLIST; } double base; if (roleType.equals(RoleType.PRESIDENT)) base = 45D; else if (roleType.equals(RoleType.MAYOR)) base = 40D; else if (roleType.equals(RoleType.ADMINISTRATOR)) base = 35D; else if (roleType.equals(RoleType.DEPUTY_ADMINISTRATOR)) base = 30D; else if (roleType.equals(RoleType.COMMANDER)) base = 25D; else if (roleType.equals(RoleType.SUB_COMMANDER)) base = 20D; else if (roleType.isChief()) base = 15D; else return EMPTY_TASKLIST; var score = new RatingScore(base); // Get an available office space. if (person.isInSettlement()) { Building building = BuildingManager.getAvailableFunctionTypeBuilding(person, FunctionType.ADMINISTRATION); score = assessBuildingSuitability(score, building, person); score = assessPersonSuitability(score, person); } return createTaskJobs(score); } }
1
0.747232
1
0.747232
game-dev
MEDIA
0.245518
game-dev
0.825935
1
0.825935
AnthorNet/SC-InteractiveMap
7,472
src/Spawn/Node.js
/* global gtag, BaseLayout_Modal */ import BaseLayout_Math from '../BaseLayout/Math.js'; export default class Spawn_Node { constructor(options) { this.marker = options.marker; this.baseLayout = options.marker.baseLayout; this.foundationType = options.foundationType; this.minerType = options.minerType; this.rotation = options.rotation; this.minerCount = Math.max(1, Math.min(options.minerCount, 12)); this.minerOffsetY = 0; this.minerOffsetZ = 0; let foundationData = this.baseLayout.getBuildingDataFromClassName(this.foundationType); if(foundationData !== null) { this.minerOffsetZ += foundationData.height * 100 / 2; } if(this.minerType.startsWith('/Game/FactoryGame/Buildable/Factory/OilPump')) { this.minerOffsetY -= 200; } this.useOwnMaterials = options.useOwnMaterials; this.centerObject = this.baseLayout.saveGameParser.getTargetObject(this.marker.relatedTarget.options.pathName); if(typeof gtag === 'function') { gtag('event', 'Node', {event_category: 'Spawn'}); } return this.spawn(); } spawn() { console.time('spawnOnNode'); $('#liveLoader').show() .find('.progress-bar').css('width', '0%'); this.history = []; this.startPosition = [ this.centerObject.transform.translation[0], this.centerObject.transform.translation[1] ]; let status = true; let steps = []; for(let i = 1; i <= this.minerCount; i++) { let rotation = BaseLayout_Math.getNewQuaternionRotate([0, 0, 0, 1], this.rotation + (360 / this.minerCount * (i - 1))); steps.push({ className : this.foundationType, x : this.centerObject.transform.translation[0], y : this.centerObject.transform.translation[1] + this.minerOffsetY, z : this.centerObject.transform.translation[2], rotation : rotation }); steps.push({ className : this.foundationType, x : this.centerObject.transform.translation[0], y : this.centerObject.transform.translation[1] + 800 + this.minerOffsetY, z : this.centerObject.transform.translation[2], rotation : rotation }); steps.push({ className : this.minerType, x : this.centerObject.transform.translation[0], y : this.centerObject.transform.translation[1], z : this.centerObject.transform.translation[2] + this.minerOffsetZ, rotation : rotation }); } for(let i = 0; i < steps.length; i++) { $('#liveLoader').find('.progress-bar').css('width', ((i + 1) / steps.length * 100) + '%'); status = this.spawnBuilding.call(this, steps[i]); if(status === false) { break; } } return this.release(); } spawnBuilding(options) { let pathName = options.className.split('.'); pathName = 'Persistent_Level:PersistentLevel.' + pathName.pop() + '_XXX'; let fakeBuilding = { type : 1, className : options.className, pathName : pathName, transform : { rotation : options.rotation, translation : [options.x, options.y, options.z] }, properties : [ { name: 'mBuiltWithRecipe', type: 'Object', value: { levelName: '', pathName: '' } }, { name: 'mBuildTimeStamp', type: 'Float', value: 0 } ], entity: {pathName: 'Persistent_Level:PersistentLevel.BuildableSubsystem'} }; this.baseLayout.buildableSubSystem.setObjectDefaultColorSlot(fakeBuilding); fakeBuilding.pathName = this.baseLayout.generateFastPathName(fakeBuilding); this.baseLayout.updateBuiltWithRecipe(fakeBuilding); if(options.className.startsWith('/Game/FactoryGame/Buildable/Factory/Miner') || options.className.startsWith('/Game/FactoryGame/Buildable/Factory/OilPump') || options.className.startsWith('/Game/FactoryGame/Buildable/Factory/GeneratorGeoThermal')) { fakeBuilding.properties.push({ name : 'mExtractableResource', type : 'Object', value : {pathName: this.centerObject.pathName} }); } if(options.className.startsWith('/Game/FactoryGame/Buildable/Factory/GeneratorGeoThermal')) { } // Check around for materials! if(this.useOwnMaterials === 1) { let result = this.baseLayout.removeFromStorage(fakeBuilding); if(result === false) { BaseLayout_Modal.alert('We could not find enough materials and stopped your construction!'); return false; // Don't have materials, stop it... } } // Calculate new position let rotation = BaseLayout_Math.getPointRotation(fakeBuilding.transform.translation, this.centerObject.transform.translation, fakeBuilding.transform.rotation); fakeBuilding.transform.translation[0] = rotation[0]; fakeBuilding.transform.translation[1] = rotation[1]; // Insert building new Promise((resolve) => { this.baseLayout.saveGameParser.addObject(fakeBuilding); return this.baseLayout.parseObject(fakeBuilding, resolve); }).then((result) => { this.history.push({ pathName: fakeBuilding.pathName, layerId: result.layer, callback: 'deleteGenericBuilding', properties: {fastDelete: true} }); this.baseLayout.addElementToLayer(result.layer, result.marker); this.baseLayout.setBadgeLayerCount(result.layer); }); return true; } release() { if(this.baseLayout.history !== null) { this.baseLayout.history.add({ name : ((this.minerType.startsWith('/Game/FactoryGame/Buildable/Factory/OilPump')) ? 'Undo: Spawn an Oil Extractor' : 'Undo: Spawn a Miner'), values : this.history }); } $('#liveLoader').hide().find('.progress-bar').css('width', '0%'); console.timeEnd('spawnOnNode'); } }
1
0.855656
1
0.855656
game-dev
MEDIA
0.799906
game-dev
0.811002
1
0.811002
beyond-aion/aion-server
3,036
game-server/src/com/aionemu/gameserver/ai/handler/TargetEventHandler.java
package com.aionemu.gameserver.ai.handler; import com.aionemu.gameserver.ai.AILogger; import com.aionemu.gameserver.ai.AIState; import com.aionemu.gameserver.ai.AISubState; import com.aionemu.gameserver.ai.NpcAI; import com.aionemu.gameserver.ai.event.AIEventType; import com.aionemu.gameserver.ai.manager.AttackManager; import com.aionemu.gameserver.ai.manager.FollowManager; import com.aionemu.gameserver.ai.manager.WalkManager; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.VisibleObject; /** * @author ATracer */ public class TargetEventHandler { /** * @param npcAI */ public static void onTargetReached(NpcAI npcAI) { if (npcAI.isLogging()) { AILogger.info(npcAI, "onTargetReached"); } AIState currentState = npcAI.getState(); switch (currentState) { case FIGHT: npcAI.getOwner().getMoveController().abortMove(); AttackManager.scheduleNextAttack(npcAI); break; case RETURNING: npcAI.getOwner().getMoveController().abortMove(); if (npcAI.getOwner().isAtSpawnLocation()) npcAI.onGeneralEvent(AIEventType.BACK_HOME); else { npcAI.setStateIfNot(AIState.IDLE); npcAI.onGeneralEvent(AIEventType.NOT_AT_HOME); } break; case FOLLOWING: case CONFUSE: case FEAR: npcAI.getOwner().getMoveController().abortMove(); break; case WALKING: WalkManager.targetReached(npcAI); checkAggro(npcAI); break; case FORCED_WALKING: WalkManager.targetReached(npcAI); break; } } /** * @param npcAI */ public static void onTargetTooFar(NpcAI npcAI) { if (npcAI.isLogging()) { AILogger.info(npcAI, "onTargetTooFar"); } switch (npcAI.getState()) { case FIGHT: AttackManager.targetTooFar(npcAI); break; case FOLLOWING: FollowManager.targetTooFar(npcAI); break; case CONFUSE: case FEAR: break; default: if (npcAI.isLogging()) { AILogger.info(npcAI, "default onTargetTooFar"); } } } /** * @param npcAI */ public static void onTargetGiveup(NpcAI npcAI) { if (npcAI.isLogging()) { AILogger.info(npcAI, "onTargetGiveup"); } VisibleObject target = npcAI.getOwner().getTarget(); if (target != null) { if (npcAI.getSubState() == AISubState.TARGET_LOST) npcAI.setSubStateIfNot(AISubState.NONE); npcAI.getOwner().getAggroList().stopHating(target); } if (npcAI.isMoveSupported()) { npcAI.getOwner().getMoveController().abortMove(); } if (!npcAI.isDead()) npcAI.think(); } /** * @param npcAI */ public static void onTargetChange(NpcAI npcAI, Creature creature) { if (npcAI.isLogging()) { AILogger.info(npcAI, "onTargetChange"); } if (npcAI.isInState(AIState.FIGHT)) { npcAI.getOwner().setTarget(creature); AttackManager.scheduleNextAttack(npcAI); } } private static void checkAggro(NpcAI npcAI) { npcAI.getOwner().getKnownList().forEachObject(obj -> { if (obj instanceof Creature) CreatureEventHandler.checkAggro(npcAI, (Creature) obj); }); } }
1
0.960224
1
0.960224
game-dev
MEDIA
0.974308
game-dev
0.982096
1
0.982096
Goob-Station/Goob-Station-MRP
12,145
Content.Server/Kitchen/EntitySystems/KitchenSpikeSystem.cs
using Content.Server.Administration.Logs; using Content.Server.Body.Systems; using Content.Server.Kitchen.Components; using Content.Server.Popups; using Content.Shared.Chat; using Content.Shared.Damage; using Content.Shared.Database; using Content.Shared.DoAfter; using Content.Shared.DragDrop; using Content.Shared.IdentityManagement; using Content.Shared.Interaction; using Content.Shared.Interaction.Events; using Content.Shared.Kitchen; using Content.Shared.Kitchen.Components; using Content.Shared.Mobs.Components; using Content.Shared.Mobs.Systems; using Content.Shared.Nutrition.Components; using Content.Shared.Popups; using Content.Shared.Storage; using Robust.Server.GameObjects; using Robust.Shared.Audio.Systems; using Robust.Shared.Player; using Robust.Shared.Random; using static Content.Shared.Kitchen.Components.KitchenSpikeComponent; namespace Content.Server.Kitchen.EntitySystems { public sealed class KitchenSpikeSystem : SharedKitchenSpikeSystem { [Dependency] private readonly PopupSystem _popupSystem = default!; [Dependency] private readonly SharedDoAfterSystem _doAfter = default!; [Dependency] private readonly IAdminLogManager _logger = default!; [Dependency] private readonly MobStateSystem _mobStateSystem = default!; [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly TransformSystem _transform = default!; [Dependency] private readonly BodySystem _bodySystem = default!; [Dependency] private readonly SharedAppearanceSystem _appearance = default!; [Dependency] private readonly SharedAudioSystem _audio = default!; [Dependency] private readonly MetaDataSystem _metaData = default!; [Dependency] private readonly SharedSuicideSystem _suicide = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<KitchenSpikeComponent, InteractUsingEvent>(OnInteractUsing); SubscribeLocalEvent<KitchenSpikeComponent, InteractHandEvent>(OnInteractHand); SubscribeLocalEvent<KitchenSpikeComponent, DragDropTargetEvent>(OnDragDrop); //DoAfter SubscribeLocalEvent<KitchenSpikeComponent, SpikeDoAfterEvent>(OnDoAfter); SubscribeLocalEvent<KitchenSpikeComponent, SuicideByEnvironmentEvent>(OnSuicideByEnvironment); SubscribeLocalEvent<ButcherableComponent, CanDropDraggedEvent>(OnButcherableCanDrop); } private void OnButcherableCanDrop(Entity<ButcherableComponent> entity, ref CanDropDraggedEvent args) { args.Handled = true; args.CanDrop |= entity.Comp.Type != ButcheringType.Knife; } /// <summary> /// TODO: Update this so it actually meatspikes the user instead of applying lethal damage to them. /// </summary> private void OnSuicideByEnvironment(Entity<KitchenSpikeComponent> entity, ref SuicideByEnvironmentEvent args) { if (args.Handled) return; if (!TryComp<DamageableComponent>(args.Victim, out var damageableComponent)) return; _suicide.ApplyLethalDamage((args.Victim, damageableComponent), "Piercing"); var othersMessage = Loc.GetString("comp-kitchen-spike-suicide-other", ("victim", args.Victim)); _popupSystem.PopupEntity(othersMessage, args.Victim, Filter.PvsExcept(args.Victim), true); var selfMessage = Loc.GetString("comp-kitchen-spike-suicide-self"); _popupSystem.PopupEntity(selfMessage, args.Victim, args.Victim); args.Handled = true; } private void OnDoAfter(Entity<KitchenSpikeComponent> entity, ref SpikeDoAfterEvent args) { if (args.Args.Target == null) return; if (TryComp<ButcherableComponent>(args.Args.Target.Value, out var butcherable)) butcherable.BeingButchered = false; if (args.Cancelled) { entity.Comp.InUse = false; return; } if (args.Handled) return; if (Spikeable(entity, args.Args.User, args.Args.Target.Value, entity.Comp, butcherable)) Spike(entity, args.Args.User, args.Args.Target.Value, entity.Comp); entity.Comp.InUse = false; args.Handled = true; } private void OnDragDrop(Entity<KitchenSpikeComponent> entity, ref DragDropTargetEvent args) { if (args.Handled) return; args.Handled = true; if (Spikeable(entity, args.User, args.Dragged, entity.Comp)) TrySpike(entity, args.User, args.Dragged, entity.Comp); } private void OnInteractHand(Entity<KitchenSpikeComponent> entity, ref InteractHandEvent args) { if (args.Handled) return; if (entity.Comp.PrototypesToSpawn?.Count > 0) { _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-knife-needed"), entity, args.User); args.Handled = true; } } private void OnInteractUsing(Entity<KitchenSpikeComponent> entity, ref InteractUsingEvent args) { if (args.Handled) return; if (TryGetPiece(entity, args.User, args.Used)) args.Handled = true; } private void Spike(EntityUid uid, EntityUid userUid, EntityUid victimUid, KitchenSpikeComponent? component = null, ButcherableComponent? butcherable = null) { if (!Resolve(uid, ref component) || !Resolve(victimUid, ref butcherable)) return; _logger.Add(LogType.Gib, LogImpact.Extreme, $"{ToPrettyString(userUid):user} kitchen spiked {ToPrettyString(victimUid):target}"); // TODO VERY SUS component.PrototypesToSpawn = EntitySpawnCollection.GetSpawns(butcherable.SpawnedEntities, _random); // This feels not okay, but entity is getting deleted on "Spike", for now... component.MeatSource1p = Loc.GetString("comp-kitchen-spike-remove-meat", ("victim", victimUid)); component.MeatSource0 = Loc.GetString("comp-kitchen-spike-remove-meat-last", ("victim", victimUid)); component.Victim = Name(victimUid); UpdateAppearance(uid, null, component); _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-kill", ("user", Identity.Entity(userUid, EntityManager)), ("victim", victimUid)), uid, PopupType.LargeCaution); _transform.SetCoordinates(victimUid, Transform(uid).Coordinates); // THE WHAT? // TODO: Need to be able to leave them on the spike to do DoT, see ss13. var gibs = _bodySystem.GibBody(victimUid); foreach (var gib in gibs) { QueueDel(gib); } _audio.PlayEntity(component.SpikeSound, Filter.Pvs(uid), uid, true); } private bool TryGetPiece(EntityUid uid, EntityUid user, EntityUid used, KitchenSpikeComponent? component = null, SharpComponent? sharp = null) { if (!Resolve(uid, ref component) || component.PrototypesToSpawn == null || component.PrototypesToSpawn.Count == 0) return false; // Is using knife if (!Resolve(used, ref sharp, false) ) { return false; } var item = _random.PickAndTake(component.PrototypesToSpawn); var ent = Spawn(item, Transform(uid).Coordinates); _metaData.SetEntityName(ent, Loc.GetString("comp-kitchen-spike-meat-name", ("name", Name(ent)), ("victim", component.Victim))); if (component.PrototypesToSpawn.Count != 0) _popupSystem.PopupEntity(component.MeatSource1p, uid, user, PopupType.MediumCaution); else { UpdateAppearance(uid, null, component); _popupSystem.PopupEntity(component.MeatSource0, uid, user, PopupType.MediumCaution); } return true; } private void UpdateAppearance(EntityUid uid, AppearanceComponent? appearance = null, KitchenSpikeComponent? component = null) { if (!Resolve(uid, ref component, ref appearance, false)) return; _appearance.SetData(uid, KitchenSpikeVisuals.Status, component.PrototypesToSpawn?.Count > 0 ? KitchenSpikeStatus.Bloody : KitchenSpikeStatus.Empty, appearance); } private bool Spikeable(EntityUid uid, EntityUid userUid, EntityUid victimUid, KitchenSpikeComponent? component = null, ButcherableComponent? butcherable = null) { if (!Resolve(uid, ref component)) return false; if (component.PrototypesToSpawn?.Count > 0) { _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-collect", ("this", uid)), uid, userUid); return false; } if (!Resolve(victimUid, ref butcherable, false)) { _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-butcher", ("victim", Identity.Entity(victimUid, EntityManager)), ("this", uid)), victimUid, userUid); return false; } switch (butcherable.Type) { case ButcheringType.Spike: return true; case ButcheringType.Knife: _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-butcher-knife", ("victim", Identity.Entity(victimUid, EntityManager)), ("this", uid)), victimUid, userUid); return false; default: _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-butcher", ("victim", Identity.Entity(victimUid, EntityManager)), ("this", uid)), victimUid, userUid); return false; } } public bool TrySpike(EntityUid uid, EntityUid userUid, EntityUid victimUid, KitchenSpikeComponent? component = null, ButcherableComponent? butcherable = null, MobStateComponent? mobState = null) { if (!Resolve(uid, ref component) || component.InUse || !Resolve(victimUid, ref butcherable) || butcherable.BeingButchered) return false; // THE WHAT? (again) // Prevent dead from being spiked TODO: Maybe remove when rounds can be played and DOT is implemented if (Resolve(victimUid, ref mobState, false) && _mobStateSystem.IsAlive(victimUid, mobState)) { _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-not-dead", ("victim", Identity.Entity(victimUid, EntityManager))), victimUid, userUid); return true; } if (userUid != victimUid) { _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-begin-hook-victim", ("user", Identity.Entity(userUid, EntityManager)), ("this", uid)), victimUid, victimUid, PopupType.LargeCaution); } // TODO: make it work when SuicideEvent is implemented // else // _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-begin-hook-self", ("this", uid)), victimUid, Filter.Pvs(uid)); // This is actually unreachable and should be in SuicideEvent butcherable.BeingButchered = true; component.InUse = true; var doAfterArgs = new DoAfterArgs(EntityManager, userUid, component.SpikeDelay + butcherable.ButcherDelay, new SpikeDoAfterEvent(), uid, target: victimUid, used: uid) { BreakOnDamage = true, BreakOnMove = true, NeedHand = true }; _doAfter.TryStartDoAfter(doAfterArgs); return true; } } }
1
0.908367
1
0.908367
game-dev
MEDIA
0.831455
game-dev
0.890879
1
0.890879
rlf/uSkyBlock
7,294
uSkyBlock-Core/src/main/java/us/talabrek/ultimateskyblock/island/IslandLocatorLogic.java
package us.talabrek.ultimateskyblock.island; import dk.lockfuglsang.minecraft.file.FileUtil; import org.bukkit.Location; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import us.talabrek.ultimateskyblock.Settings; import us.talabrek.ultimateskyblock.uSkyBlock; import us.talabrek.ultimateskyblock.util.LocationUtil; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import static dk.lockfuglsang.minecraft.po.I18nUtil.tr; /** * Responsible for keeping track of and locating island locations for new islands. */ public class IslandLocatorLogic { private static final Logger log = Logger.getLogger(IslandLocatorLogic.class.getName()); private final uSkyBlock plugin; private final File configFile; private final FileConfiguration config; private final Map<String, Long> reservations = new ConcurrentHashMap<>(); private Location lastIsland = null; private long reservationTimeout; public IslandLocatorLogic(final uSkyBlock plugin) { this.plugin = plugin; this.configFile = new File(plugin.getDataFolder(), "lastIslandConfig.yml"); this.config = new YamlConfiguration(); FileUtil.readConfig(config, configFile); // Backward compatibility if (!config.contains("options.general.lastIslandX") && plugin.getConfig().contains("options.general.lastIslandX")) { config.set("options.general.lastIslandX", plugin.getConfig().getInt("options.general.lastIslandX")); config.set("options.general.lastIslandZ", plugin.getConfig().getInt("options.general.lastIslandZ")); plugin.getConfig().set("options.general.lastIslandX", null); plugin.getConfig().set("options.general.lastIslandZ", null); } reservationTimeout = plugin.getConfig().getLong("options.island.reservationTimeout", 5 * 60000); } private Location getLastIsland() { if (lastIsland == null) { lastIsland = new Location(plugin.getWorldManager().getWorld(), config.getInt("options.general.lastIslandX", 0), Settings.island_height, config.getInt("options.general.lastIslandZ", 0)); } return LocationUtil.alignToDistance(lastIsland, Settings.island_distance); } public synchronized Location getNextIslandLocation(Player player) { Location islandLocation = getNext(player); reserve(islandLocation); return islandLocation.clone(); } private void reserve(Location islandLocation) { final String islandName = LocationUtil.getIslandName(islandLocation); final long tstamp = System.currentTimeMillis(); reservations.put(islandName, tstamp); plugin.async(new Runnable() { @Override public void run() { synchronized (reservations) { Long tReserved = reservations.get(islandName); if (tReserved != null && tReserved == tstamp) { reservations.remove(islandName); } } } }, reservationTimeout); } private synchronized Location getNext(Player player) { Location last = getLastIsland(); if (plugin.getWorldManager().isSkyWorld(player.getWorld()) && !plugin.islandInSpawn(player.getLocation())) { Location location = LocationUtil.alignToDistance(player.getLocation(), Settings.island_distance); if (isAvailableLocation(location)) { player.sendMessage(tr("\u00a79Creating an island at your location")); return location; } Vector v = player.getLocation().getDirection().normalize(); location = LocationUtil.alignToDistance(location.add(v.multiply(Settings.island_distance)), Settings.island_distance); if (isAvailableLocation(location)) { player.sendMessage(tr("\u00a79Creating an island \u00a77{0}\u00a79 of you", LocationUtil.getCardinalDirection(player.getLocation().getYaw()))); return location; } } Location next = plugin.getOrphanLogic().getNextValidOrphan(); if (next == null) { next = last; // Ensure the found location is valid (or find one that is). while (!isAvailableLocation(next)) { next = nextIslandLocation(next); } } lastIsland = next; save(); return next; } private void save() { final Location locationToSave = lastIsland; plugin.async(new Runnable() { @Override public void run() { try { config.set("options.general.lastIslandX", locationToSave.getBlockX()); config.set("options.general.lastIslandZ", locationToSave.getBlockZ()); config.save(configFile); } catch (IOException e) { log.warning("Unable to save " + configFile); } } }); } public boolean isAvailableLocation(Location next) { return !(plugin.islandInSpawn(next) || plugin.islandAtLocation(next) || isReserved(next)); } private boolean isReserved(Location next) { return reservations.containsKey(LocationUtil.getIslandName(next)); } /** * <pre> * z * x = -z ^ x = z * \ -x < z | x < z / * \ | / * \ | / * \ | / * \ | / x > z * -x > z \ | / * \ | / * -----------------------+-----------------------------> x * / | \ * -x > -z / | \ * (x < z) / | \ x > -z * / | \ * / | \ * / -x < -z | x < -z \ * x = z | x = -z * | * v * </pre> */ static Location nextIslandLocation(final Location lastIsland) { int d = Settings.island_distance; LocationUtil.alignToDistance(lastIsland, d); int x = lastIsland.getBlockX(); int z = lastIsland.getBlockZ(); if (x < z) { if (-1 * x < z) { x += d; } else { z += d; } } else if (x > z) { if (-1 * x >= z) { x -= d; } else { z -= d; } } else { // x == z if (x <= 0) { z += d; } else { z -= d; } } lastIsland.setX(x); lastIsland.setZ(z); return lastIsland; } }
1
0.746201
1
0.746201
game-dev
MEDIA
0.555412
game-dev
0.834244
1
0.834244
huawei-noah/SMARTS
3,233
docs/sim/bubbles.rst
.. _bubbles: Bubbles ======= SMARTS provides the concept of a spatial-temporal bubble which allows for focused simulation interaction. Bubbles are intended to address the problem of scaling of interaction. Using resources globally results in wasted simulation resources if the most important behavior to an autonomous vehicle is in the nearby vicinity of that vehicle. A bubble covers an area and filters traffic vehicles that pass through that zone. A vehicle entering the bubble will first pass into an ``airlock`` buffer area of ``shadowing`` where an agent may begin observing from the vehicle. The agent may then fully take over control of that vehicle when it enters the bubble proper. SMARTS will replace control of the traffic vehicles with the agents specified by the bubble definition. The bubble agent will relinquish its control to a suitable traffic provider when its controlled vehicle exits the bubble and airlock regions. Limitations ----------- If a vehicle whose trajectory is being provided from a traffic history dataset is taken over by an agent within a bubble, the vehicle generally cannot be returned to the trajectory specified in the history dataset upon bubble exit without a "jump" or "glitch" due to the plurality of situations where there is a divergence of vehicle states from the history within the bubble. So instead, the simple SMARTS traffic provider assumes control of it at this point and will attempt to navigate it to its original destination, avoiding collisions along the way. Usage ----- Fixed bubbles ^^^^^^^^^^^^^ Bubbles can be fixed to a static location defined either as an edge or a position. .. code-block:: python import smarts.sstudio.sstypes as t zoo_agent_actor = t.SocialAgentActor( # Unique agent name name="zoo-agent", # Formatted like (<python_module>\.*)+:[A-Za-z\-_]+(-v[0-9]+)? agent_locator=f"zoo.policies:zoo-agent-v0", ) t.Bubble( # Edge snapped bubble zone=t.MapZone(start=("edge-west-WE", 0, 50), length=10, n_lanes=1), # Margin is an area where agents get observations but not control margin=2, # Agent actor information actor=zoo_agent_actor, ), Moving bubbles ^^^^^^^^^^^^^^ Bubbles that are vehicle-relative can be attached to specific actors by specifying the id of the actor in the bubble definition. .. code-block:: python import smarts.sstudio.sstypes as t t.Bubble( ..., # The target of the bubble to follow the given actor follow_actor_id=t.Bubble.to_actor_id(laner_actor, mission_group="all"), # The offset from the target actor's vehicle(aligned with that vehicle's orientation) follow_offset=(-7, 10), ), Dynamic Bubbles --------------- There is currently no interface for dynamically-created bubbles. However, if the ``scenario`` is exposed then the following is possible to define a bubble outside of ``scenario studio``: .. code-block:: python import smarts.sstudio.sstypes as t scenario_iter = Scenario.scenario_variations(path) scenario = next(scenario) scenario.bubbles.append( t.Bubble( ..., ), ) smarts.reset(scenario)
1
0.828783
1
0.828783
game-dev
MEDIA
0.877259
game-dev
0.704878
1
0.704878
mickem/nscp
10,383
libs/lua_nscp/lua_core.cpp
#include <boost/optional/optional.hpp> #include <lua/lua_core.hpp> #include <lua/lua_cpp.hpp> #include <nscapi/macros.hpp> #include <nscapi/nscapi_helper_singleton.hpp> #include <nscapi/nscapi_plugin_wrapper.hpp> #include <nscapi/nscapi_protobuf_functions.hpp> void lua::lua_runtime::register_query(const std::string &command, const std::string &description) { throw lua_exception("The method or operation is not implemented(reg_query)."); } void lua::lua_runtime::register_subscription(const std::string &channel, const std::string &description) { throw lua_exception("The method or operation is not implemented(reg_sub)."); } void lua::lua_runtime::on_query(std::string command, script_information *information, lua::lua_traits::function_type function, bool simple, const PB::Commands::QueryRequestMessage::Request &request, PB::Commands::QueryResponseMessage::Response *response, const PB::Commands::QueryRequestMessage &request_message) { lua_wrapper lua(prep_function(information, function)); int args = 2; if (function.object_ref != 0) args = 3; if (simple) { std::list<std::string> argslist; for (int i = 0; i < request.arguments_size(); i++) argslist.push_back(request.arguments(i)); lua.push_string(command); lua.push_array(argslist); if (lua.pcall(args, 3, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command: " + command + ": " + lua.pop_string()); NSCAPI::nagiosReturn ret = NSCAPI::query_return_codes::returnUNKNOWN; if (lua.size() < 3) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_query_response_payload(response, command, NSCAPI::query_return_codes::returnUNKNOWN, "Invalid return", ""); return; } std::string msg, perf; perf = lua.pop_string(); msg = lua.pop_string(); ret = lua.pop_code(); lua.gc(LUA_GCCOLLECT, 0); nscapi::protobuf::functions::append_simple_query_response_payload(response, command, ret, msg, perf); } else { lua.push_string(command); lua.push_raw_string(request.SerializeAsString()); lua.push_raw_string(request_message.SerializeAsString()); args++; if (lua.pcall(args, 1, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command: " + command + ": " + lua.pop_string()); if (lua.size() < 1) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_query_response_payload(response, command, NSCAPI::query_return_codes::returnUNKNOWN, "Invalid return data", ""); return; } PB::Commands::QueryResponseMessage local_response; std::string data = lua.pop_raw_string(); response->ParseFromString(data); lua.gc(LUA_GCCOLLECT, 0); } } void lua::lua_runtime::exec_main(script_information *information, const std::vector<std::string> &opts, PB::Commands::ExecuteResponseMessage::Response *response) { lua_wrapper lua(prep_function(information, "main")); lua.push_array(opts); if (lua.pcall(1, 2, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command main: " + lua.pop_string()); NSCAPI::nagiosReturn ret = NSCAPI::exec_return_codes::returnERROR; if (lua.size() < 2) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_exec_response_payload(response, "", NSCAPI::exec_return_codes::returnERROR, "Invalid return"); return; } std::string msg; msg = lua.pop_string(); ret = lua.pop_code(); lua.gc(LUA_GCCOLLECT, 0); nscapi::protobuf::functions::append_simple_exec_response_payload(response, "", ret, msg); } void lua::lua_runtime::on_exec(std::string command, script_information *information, lua::lua_traits::function_type function, bool simple, const PB::Commands::ExecuteRequestMessage::Request &request, PB::Commands::ExecuteResponseMessage::Response *response, const PB::Commands::ExecuteRequestMessage &request_message) { lua_wrapper lua(prep_function(information, function)); int args = 2; if (function.object_ref != 0) args = 3; if (simple) { std::list<std::string> argslist; for (int i = 0; i < request.arguments_size(); i++) argslist.push_back(request.arguments(i)); lua.push_string(command); lua.push_array(argslist); if (lua.pcall(args, 2, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command: " + command + ": " + lua.pop_string()); NSCAPI::nagiosReturn ret = NSCAPI::exec_return_codes::returnERROR; if (lua.size() < 3) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_exec_response_payload(response, command, NSCAPI::exec_return_codes::returnERROR, "Invalid return"); return; } std::string msg, perf; msg = lua.pop_string(); ret = lua.pop_code(); lua.gc(LUA_GCCOLLECT, 0); nscapi::protobuf::functions::append_simple_exec_response_payload(response, command, ret, msg); } else { lua.push_string(command); lua.push_raw_string(request.SerializeAsString()); lua.push_raw_string(request_message.SerializeAsString()); args++; if (lua.pcall(args, 1, 0) != 0) return nscapi::protobuf::functions::set_response_bad(*response, "Failed to handle command: " + command + ": " + lua.pop_string()); if (lua.size() < 1) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_exec_response_payload(response, command, NSCAPI::exec_return_codes::returnERROR, "Invalid return data"); return; } PB::Commands::QueryResponseMessage local_response; std::string data = lua.pop_raw_string(); response->ParseFromString(data); lua.gc(LUA_GCCOLLECT, 0); } } void lua::lua_runtime::on_submit(std::string channel, script_information *information, lua::lua_traits::function_type function, bool simple, const PB::Commands::QueryResponseMessage::Response &request, PB::Commands::SubmitResponseMessage::Response *response) { lua_wrapper lua(prep_function(information, function)); int cmd_args = 1; if (function.object_ref != 0) cmd_args = 2; if (simple) { lua.push_string(channel); lua.push_string(request.command()); auto code = nscapi::protobuf::functions::gbp_to_nagios_status(request.result()); lua.push_string(lua.code_to_string(code)); lua_createtable(lua.L, 0, static_cast<int>(request.lines_size())); for (auto &line : request.lines()) { lua.push_string(line.message()); std::string perf = nscapi::protobuf::functions::build_performance_data(line, nscapi::protobuf::functions::no_truncation); lua.push_string(perf); lua_settable(lua.L, -3); } if (lua.pcall(cmd_args + 4, 2, 0) != 0) { NSC_LOG_ERROR_STD("Failed to handle channel: " + channel + ": " + lua.pop_string()); return; } if (lua.size() < 2) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_submit_response_payload(response, channel, NSCAPI::bool_return::isfalse, "Invalid return"); return; } std::string msg, perf; msg = lua.pop_string(); bool ret = lua.pop_boolean(); lua.gc(LUA_GCCOLLECT, 0); nscapi::protobuf::functions::append_simple_submit_response_payload(response, channel, ret ? NSCAPI::bool_return::istrue : NSCAPI::bool_return::isfalse, msg); } else { lua.push_string(channel); lua.push_raw_string(request.SerializeAsString()); if (lua.pcall(cmd_args + 2, 1, 0) != 0) return nscapi::protobuf::functions::append_simple_submit_response_payload(response, channel, NSCAPI::bool_return::isfalse, "Failed to handle command: " + channel + ": " + lua.pop_string()); if (lua.size() < 1) { NSC_LOG_ERROR_STD("Invalid return: " + lua.dump_stack()); nscapi::protobuf::functions::append_simple_submit_response_payload(response, channel, NSCAPI::bool_return::isfalse, "Invalid return"); return; } PB::Commands::SubmitResponseMessage local_response; std::string data = lua.pop_raw_string(); response->ParseFromString(data); lua.gc(LUA_GCCOLLECT, 0); } } void lua::lua_runtime::create_user_data(scripts::script_information<lua_traits> *info) { info->user_data.base_path_ = base_path; } void lua::lua_runtime::load(scripts::script_information<lua_traits> *info) { std::string base_path = info->user_data.base_path_; lua_wrapper lua_instance(info->user_data.L); lua_instance.set_userdata(lua::lua_traits::user_data_tag, info); lua_instance.openlibs(); lua_script::luaopen(info->user_data.L); for (lua_runtime_plugin_type &plugin : plugins) { plugin->load(lua_instance); } lua_instance.append_path(base_path + "/scripts/lua/lib/?.lua;" + base_path + "scripts/lua/?;"); if (lua_instance.loadfile(info->script) != 0) throw lua::lua_exception("Failed to load script: " + info->script + ": " + lua_instance.pop_string()); if (lua_instance.pcall(0, 0, 0) != 0) throw lua::lua_exception("Failed to execute script: " + info->script + ": " + lua_instance.pop_string()); lua_instance.gc(LUA_GCCOLLECT, 0); } void lua::lua_runtime::start(scripts::script_information<lua_traits> *info) { lua_wrapper lua_instance(info->user_data.L); int index = lua_instance.getglobal("on_start"); if (lua_instance.is_function()) { int index = lua_instance.getglobal("on_start"); if (lua_instance.pcall(0, 0, 0) != 0) { throw lua_exception("Failed to start script: " + info->script + ": " + lua_instance.pop_string()); } } } void lua::lua_runtime::unload(scripts::script_information<lua_traits> *info) { lua_wrapper lua_instance(info->user_data.L); for (lua_runtime_plugin_type &plugin : plugins) { plugin->unload(lua_instance); } lua_instance.gc(LUA_GCCOLLECT, 0); lua_instance.remove_userdata(lua::lua_traits::user_data_tag); }
1
0.84028
1
0.84028
game-dev
MEDIA
0.303971
game-dev
0.692912
1
0.692912
jazware/bsky-experiments
1,143
pkg/feeds/language/cursor.go
package language import ( "fmt" "strconv" "strings" "time" ) type ErrInvalidCursor struct { error } // ParseCursor takes a cursor string and returns the created_at, actor_did, and rkey // <created_at>:<actor_did>:<rkey> func ParseCursor(cursor string) (time.Time, string, string, error) { var err error createdAt := time.Now() actorDID := "" rkey := "" if cursor != "" { cursorParts := strings.Split(cursor, "|") if len(cursorParts) != 3 { return createdAt, actorDID, rkey, ErrInvalidCursor{fmt.Errorf("cursor is invalid (wrong number of parts)")} } createdAtStr := cursorParts[0] createdAtUnixMili := int64(0) createdAtUnixMili, err = strconv.ParseInt(createdAtStr, 10, 64) if err != nil { return createdAt, actorDID, rkey, ErrInvalidCursor{fmt.Errorf("cursor is invalid (failed to parse createdAt)")} } createdAt = time.UnixMilli(createdAtUnixMili) actorDID = cursorParts[1] rkey = cursorParts[2] } return createdAt, actorDID, rkey, nil } func AssembleCursor(createdAt time.Time, actorDID string, rkey string) string { return fmt.Sprintf("%d|%s|%s", createdAt.UnixMilli(), actorDID, rkey) }
1
0.582398
1
0.582398
game-dev
MEDIA
0.301408
game-dev
0.753201
1
0.753201
BlesseNtumble/GalaxySpace
2,947
src/main/java/galaxyspace/systems/SolarSystem/planets/overworld/recipes/RecyclerRecipes.java
package galaxyspace.systems.SolarSystem.planets.overworld.recipes; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; public class RecyclerRecipes { private static final RecyclerRecipes recyclerBase = new RecyclerRecipes(); private List<RecycleRecipe> recipes = new ArrayList<RecycleRecipe>(); public static RecyclerRecipes recycling() { return recyclerBase; } public void addNewRecipe(ItemStack stack, ItemStack result, FluidStack fluidstack) { this.recipes.add(new RecycleRecipe(stack, result, fluidstack)); } public void addNewRecipe(ItemStack stack, ItemStack result, int chance, FluidStack fluidstack) { this.recipes.add(new RecycleRecipe(stack, result, fluidstack, chance)); } public void addNewRecipe(ItemStack stack, ItemStack result, ItemStack result_2, int chance, int chance_2, FluidStack fluidstack) { this.recipes.add(new RecycleRecipe(stack, result, result_2, fluidstack, chance, chance_2)); } public void removeRecipe(ItemStack stack) { recipes.remove(getRecipe(stack)); } public List<RecycleRecipe> getRecipes() { return this.recipes; } public RecycleRecipe getRecipe(ItemStack stack) { for(RecycleRecipe recipe : this.recipes) if(recipe.getInput().isItemEqual(stack)) return recipe; return null; } public class RecycleRecipe { private ItemStack input = ItemStack.EMPTY, output = ItemStack.EMPTY, output_2 = ItemStack.EMPTY; private FluidStack fluid; private int chance_procent = 100; private int chance_procent_2 = 100; public RecycleRecipe(ItemStack input, ItemStack output, FluidStack fluid) { this(input, output, fluid, 100); } public RecycleRecipe(ItemStack input, ItemStack output, FluidStack fluid, int chance) { this.input = input; this.output = output; this.fluid = fluid; this.chance_procent = chance; } public RecycleRecipe(ItemStack input, ItemStack output, ItemStack output_2, FluidStack fluid, int chance, int chance_2) { this.input = input; this.output = output; this.fluid = fluid; this.chance_procent = chance; this.output_2 = output_2; this.chance_procent_2 = chance_2; } public ItemStack getInput() { return this.input; } public ItemStack getOutput() { return this.output; } public ItemStack getOutput_2() { return this.output_2; } public FluidStack getFluidStack() { return this.fluid; } public boolean hasChance() { return chance_procent != 100; } public int getChance() { return this.chance_procent; } public boolean hasChance_2() { return this.chance_procent_2 != 100; } public int getChance_2() { return this.chance_procent_2; } } }
1
0.592877
1
0.592877
game-dev
MEDIA
0.921035
game-dev
0.517845
1
0.517845
Havret/dotnet-activemq-artemis-client
2,248
src/ArtemisNetClient/Message/MessageAnnotations.cs
using Amqp.Types; namespace ActiveMQ.Artemis.Client { internal sealed class MessageAnnotations { private static readonly Symbol _scheduledDeliveryTime = new Symbol("x-opt-delivery-time"); private static readonly Symbol _scheduledDeliveryDelay = new Symbol("x-opt-delivery-delay"); private readonly Amqp.Framing.MessageAnnotations _innerProperties; public MessageAnnotations(Amqp.Message innerMessage) { _innerProperties = innerMessage.MessageAnnotations ??= new Amqp.Framing.MessageAnnotations(); } public object this[Symbol key] { get => _innerProperties.Map[key]; set => _innerProperties.Map[key] = value; } public long? ScheduledDeliveryTime { get { if (_innerProperties.Map.TryGetValue(_scheduledDeliveryTime, out var value)) { if (value is long scheduledDeliveryTime) { return scheduledDeliveryTime; } } return null; } set { if (value != default) { _innerProperties.Map[_scheduledDeliveryTime] = value; } else { _innerProperties.Map.Remove(_scheduledDeliveryTime); } } } public long? ScheduledDeliveryDelay { get { if (_innerProperties.Map.TryGetValue(_scheduledDeliveryDelay, out var value)) { if (value is long scheduledDeliveryDelay) { return scheduledDeliveryDelay; } } return null; } set { if (value != default) { _innerProperties.Map[_scheduledDeliveryDelay] = value; } else { _innerProperties.Map.Remove(_scheduledDeliveryDelay); } } } } }
1
0.879618
1
0.879618
game-dev
MEDIA
0.254436
game-dev
0.827719
1
0.827719
stubma/cocos2dx-classical
33,358
cocos2dx/support/aosp/android_input.h
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _ANDROID_INPUT_H #define _ANDROID_INPUT_H /****************************************************************** * * IMPORTANT NOTICE: * * This file is part of Android's set of stable system headers * exposed by the Android NDK (Native Development Kit). * * Third-party source AND binary code relies on the definitions * here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES. * * - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES) * - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS * - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY * - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES */ /* * Structures and functions to receive and process input events in * native code. * * NOTE: These functions MUST be implemented by /system/lib/libui.so */ #include <stdint.h> #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif /* * Key states (may be returned by queries about the current state of a * particular key code, scan code or switch). */ enum { /* The key state is unknown or the requested key itself is not supported. */ AKEY_STATE_UNKNOWN = -1, /* The key is up. */ AKEY_STATE_UP = 0, /* The key is down. */ AKEY_STATE_DOWN = 1, /* The key is down but is a virtual key press that is being emulated by the system. */ AKEY_STATE_VIRTUAL = 2 }; /* * Meta key / modifer state. */ enum { /* No meta keys are pressed. */ AMETA_NONE = 0, /* This mask is used to check whether one of the ALT meta keys is pressed. */ AMETA_ALT_ON = 0x02, /* This mask is used to check whether the left ALT meta key is pressed. */ AMETA_ALT_LEFT_ON = 0x10, /* This mask is used to check whether the right ALT meta key is pressed. */ AMETA_ALT_RIGHT_ON = 0x20, /* This mask is used to check whether one of the SHIFT meta keys is pressed. */ AMETA_SHIFT_ON = 0x01, /* This mask is used to check whether the left SHIFT meta key is pressed. */ AMETA_SHIFT_LEFT_ON = 0x40, /* This mask is used to check whether the right SHIFT meta key is pressed. */ AMETA_SHIFT_RIGHT_ON = 0x80, /* This mask is used to check whether the SYM meta key is pressed. */ AMETA_SYM_ON = 0x04, /* This mask is used to check whether the FUNCTION meta key is pressed. */ AMETA_FUNCTION_ON = 0x08, /* This mask is used to check whether one of the CTRL meta keys is pressed. */ AMETA_CTRL_ON = 0x1000, /* This mask is used to check whether the left CTRL meta key is pressed. */ AMETA_CTRL_LEFT_ON = 0x2000, /* This mask is used to check whether the right CTRL meta key is pressed. */ AMETA_CTRL_RIGHT_ON = 0x4000, /* This mask is used to check whether one of the META meta keys is pressed. */ AMETA_META_ON = 0x10000, /* This mask is used to check whether the left META meta key is pressed. */ AMETA_META_LEFT_ON = 0x20000, /* This mask is used to check whether the right META meta key is pressed. */ AMETA_META_RIGHT_ON = 0x40000, /* This mask is used to check whether the CAPS LOCK meta key is on. */ AMETA_CAPS_LOCK_ON = 0x100000, /* This mask is used to check whether the NUM LOCK meta key is on. */ AMETA_NUM_LOCK_ON = 0x200000, /* This mask is used to check whether the SCROLL LOCK meta key is on. */ AMETA_SCROLL_LOCK_ON = 0x400000, }; /* * Input events. * * Input events are opaque structures. Use the provided accessors functions to * read their properties. */ struct AInputEvent; typedef struct AInputEvent AInputEvent; /* * Input event types. */ enum { /* Indicates that the input event is a key event. */ AINPUT_EVENT_TYPE_KEY = 1, /* Indicates that the input event is a motion event. */ AINPUT_EVENT_TYPE_MOTION = 2 }; /* * Key event actions. */ enum { /* The key has been pressed down. */ AKEY_EVENT_ACTION_DOWN = 0, /* The key has been released. */ AKEY_EVENT_ACTION_UP = 1, /* Multiple duplicate key events have occurred in a row, or a complex string is * being delivered. The repeat_count property of the key event contains the number * of times the given key code should be executed. */ AKEY_EVENT_ACTION_MULTIPLE = 2 }; /* * Key event flags. */ enum { /* This mask is set if the device woke because of this key event. */ AKEY_EVENT_FLAG_WOKE_HERE = 0x1, /* This mask is set if the key event was generated by a software keyboard. */ AKEY_EVENT_FLAG_SOFT_KEYBOARD = 0x2, /* This mask is set if we don't want the key event to cause us to leave touch mode. */ AKEY_EVENT_FLAG_KEEP_TOUCH_MODE = 0x4, /* This mask is set if an event was known to come from a trusted part * of the system. That is, the event is known to come from the user, * and could not have been spoofed by a third party component. */ AKEY_EVENT_FLAG_FROM_SYSTEM = 0x8, /* This mask is used for compatibility, to identify enter keys that are * coming from an IME whose enter key has been auto-labelled "next" or * "done". This allows TextView to dispatch these as normal enter keys * for old applications, but still do the appropriate action when * receiving them. */ AKEY_EVENT_FLAG_EDITOR_ACTION = 0x10, /* When associated with up key events, this indicates that the key press * has been canceled. Typically this is used with virtual touch screen * keys, where the user can slide from the virtual key area on to the * display: in that case, the application will receive a canceled up * event and should not perform the action normally associated with the * key. Note that for this to work, the application can not perform an * action for a key until it receives an up or the long press timeout has * expired. */ AKEY_EVENT_FLAG_CANCELED = 0x20, /* This key event was generated by a virtual (on-screen) hard key area. * Typically this is an area of the touchscreen, outside of the regular * display, dedicated to "hardware" buttons. */ AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY = 0x40, /* This flag is set for the first key repeat that occurs after the * long press timeout. */ AKEY_EVENT_FLAG_LONG_PRESS = 0x80, /* Set when a key event has AKEY_EVENT_FLAG_CANCELED set because a long * press action was executed while it was down. */ AKEY_EVENT_FLAG_CANCELED_LONG_PRESS = 0x100, /* Set for AKEY_EVENT_ACTION_UP when this event's key code is still being * tracked from its initial down. That is, somebody requested that tracking * started on the key down and a long press has not caused * the tracking to be canceled. */ AKEY_EVENT_FLAG_TRACKING = 0x200, /* Set when a key event has been synthesized to implement default behavior * for an event that the application did not handle. * Fallback key events are generated by unhandled trackball motions * (to emulate a directional keypad) and by certain unhandled key presses * that are declared in the key map (such as special function numeric keypad * keys when numlock is off). */ AKEY_EVENT_FLAG_FALLBACK = 0x400, }; /* * Motion event actions. */ /* Bit shift for the action bits holding the pointer index as * defined by AMOTION_EVENT_ACTION_POINTER_INDEX_MASK. */ #define AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT 8 enum { /* Bit mask of the parts of the action code that are the action itself. */ AMOTION_EVENT_ACTION_MASK = 0xff, /* Bits in the action code that represent a pointer index, used with * AMOTION_EVENT_ACTION_POINTER_DOWN and AMOTION_EVENT_ACTION_POINTER_UP. Shifting * down by AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT provides the actual pointer * index where the data for the pointer going up or down can be found. */ AMOTION_EVENT_ACTION_POINTER_INDEX_MASK = 0xff00, /* A pressed gesture has started, the motion contains the initial starting location. */ AMOTION_EVENT_ACTION_DOWN = 0, /* A pressed gesture has finished, the motion contains the final release location * as well as any intermediate points since the last down or move event. */ AMOTION_EVENT_ACTION_UP = 1, /* A change has happened during a press gesture (between AMOTION_EVENT_ACTION_DOWN and * AMOTION_EVENT_ACTION_UP). The motion contains the most recent point, as well as * any intermediate points since the last down or move event. */ AMOTION_EVENT_ACTION_MOVE = 2, /* The current gesture has been aborted. * You will not receive any more points in it. You should treat this as * an up event, but not perform any action that you normally would. */ AMOTION_EVENT_ACTION_CANCEL = 3, /* A movement has happened outside of the normal bounds of the UI element. * This does not provide a full gesture, but only the initial location of the movement/touch. */ AMOTION_EVENT_ACTION_OUTSIDE = 4, /* A non-primary pointer has gone down. * The bits in AMOTION_EVENT_ACTION_POINTER_INDEX_MASK indicate which pointer changed. */ AMOTION_EVENT_ACTION_POINTER_DOWN = 5, /* A non-primary pointer has gone up. * The bits in AMOTION_EVENT_ACTION_POINTER_INDEX_MASK indicate which pointer changed. */ AMOTION_EVENT_ACTION_POINTER_UP = 6, /* A change happened but the pointer is not down (unlike AMOTION_EVENT_ACTION_MOVE). * The motion contains the most recent point, as well as any intermediate points since * the last hover move event. */ AMOTION_EVENT_ACTION_HOVER_MOVE = 7, /* The motion event contains relative vertical and/or horizontal scroll offsets. * Use getAxisValue to retrieve the information from AMOTION_EVENT_AXIS_VSCROLL * and AMOTION_EVENT_AXIS_HSCROLL. * The pointer may or may not be down when this event is dispatched. * This action is always delivered to the winder under the pointer, which * may not be the window currently touched. */ AMOTION_EVENT_ACTION_SCROLL = 8, /* The pointer is not down but has entered the boundaries of a window or view. */ AMOTION_EVENT_ACTION_HOVER_ENTER = 9, /* The pointer is not down but has exited the boundaries of a window or view. */ AMOTION_EVENT_ACTION_HOVER_EXIT = 10, }; /* * Motion event flags. */ enum { /* This flag indicates that the window that received this motion event is partly * or wholly obscured by another visible window above it. This flag is set to true * even if the event did not directly pass through the obscured area. * A security sensitive application can check this flag to identify situations in which * a malicious application may have covered up part of its content for the purpose * of misleading the user or hijacking touches. An appropriate response might be * to drop the suspect touches or to take additional precautions to confirm the user's * actual intent. */ AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED = 0x1, }; /* * Motion event edge touch flags. */ enum { /* No edges intersected */ AMOTION_EVENT_EDGE_FLAG_NONE = 0, /* Flag indicating the motion event intersected the top edge of the screen. */ AMOTION_EVENT_EDGE_FLAG_TOP = 0x01, /* Flag indicating the motion event intersected the bottom edge of the screen. */ AMOTION_EVENT_EDGE_FLAG_BOTTOM = 0x02, /* Flag indicating the motion event intersected the left edge of the screen. */ AMOTION_EVENT_EDGE_FLAG_LEFT = 0x04, /* Flag indicating the motion event intersected the right edge of the screen. */ AMOTION_EVENT_EDGE_FLAG_RIGHT = 0x08 }; /* * Constants that identify each individual axis of a motion event. * Refer to the documentation on the MotionEvent class for descriptions of each axis. */ enum { AMOTION_EVENT_AXIS_X = 0, AMOTION_EVENT_AXIS_Y = 1, AMOTION_EVENT_AXIS_PRESSURE = 2, AMOTION_EVENT_AXIS_SIZE = 3, AMOTION_EVENT_AXIS_TOUCH_MAJOR = 4, AMOTION_EVENT_AXIS_TOUCH_MINOR = 5, AMOTION_EVENT_AXIS_TOOL_MAJOR = 6, AMOTION_EVENT_AXIS_TOOL_MINOR = 7, AMOTION_EVENT_AXIS_ORIENTATION = 8, AMOTION_EVENT_AXIS_VSCROLL = 9, AMOTION_EVENT_AXIS_HSCROLL = 10, AMOTION_EVENT_AXIS_Z = 11, AMOTION_EVENT_AXIS_RX = 12, AMOTION_EVENT_AXIS_RY = 13, AMOTION_EVENT_AXIS_RZ = 14, AMOTION_EVENT_AXIS_HAT_X = 15, AMOTION_EVENT_AXIS_HAT_Y = 16, AMOTION_EVENT_AXIS_LTRIGGER = 17, AMOTION_EVENT_AXIS_RTRIGGER = 18, AMOTION_EVENT_AXIS_THROTTLE = 19, AMOTION_EVENT_AXIS_RUDDER = 20, AMOTION_EVENT_AXIS_WHEEL = 21, AMOTION_EVENT_AXIS_GAS = 22, AMOTION_EVENT_AXIS_BRAKE = 23, AMOTION_EVENT_AXIS_DISTANCE = 24, AMOTION_EVENT_AXIS_TILT = 25, AMOTION_EVENT_AXIS_GENERIC_1 = 32, AMOTION_EVENT_AXIS_GENERIC_2 = 33, AMOTION_EVENT_AXIS_GENERIC_3 = 34, AMOTION_EVENT_AXIS_GENERIC_4 = 35, AMOTION_EVENT_AXIS_GENERIC_5 = 36, AMOTION_EVENT_AXIS_GENERIC_6 = 37, AMOTION_EVENT_AXIS_GENERIC_7 = 38, AMOTION_EVENT_AXIS_GENERIC_8 = 39, AMOTION_EVENT_AXIS_GENERIC_9 = 40, AMOTION_EVENT_AXIS_GENERIC_10 = 41, AMOTION_EVENT_AXIS_GENERIC_11 = 42, AMOTION_EVENT_AXIS_GENERIC_12 = 43, AMOTION_EVENT_AXIS_GENERIC_13 = 44, AMOTION_EVENT_AXIS_GENERIC_14 = 45, AMOTION_EVENT_AXIS_GENERIC_15 = 46, AMOTION_EVENT_AXIS_GENERIC_16 = 47, // NOTE: If you add a new axis here you must also add it to several other files. // Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list. }; /* * Constants that identify buttons that are associated with motion events. * Refer to the documentation on the MotionEvent class for descriptions of each button. */ enum { AMOTION_EVENT_BUTTON_PRIMARY = 1 << 0, AMOTION_EVENT_BUTTON_SECONDARY = 1 << 1, AMOTION_EVENT_BUTTON_TERTIARY = 1 << 2, AMOTION_EVENT_BUTTON_BACK = 1 << 3, AMOTION_EVENT_BUTTON_FORWARD = 1 << 4, }; /* * Constants that identify tool types. * Refer to the documentation on the MotionEvent class for descriptions of each tool type. */ enum { AMOTION_EVENT_TOOL_TYPE_UNKNOWN = 0, AMOTION_EVENT_TOOL_TYPE_FINGER = 1, AMOTION_EVENT_TOOL_TYPE_STYLUS = 2, AMOTION_EVENT_TOOL_TYPE_MOUSE = 3, AMOTION_EVENT_TOOL_TYPE_ERASER = 4, }; /* * Input sources. * * Refer to the documentation on android.view.InputDevice for more details about input sources * and their correct interpretation. */ enum { AINPUT_SOURCE_CLASS_MASK = 0x000000ff, AINPUT_SOURCE_CLASS_BUTTON = 0x00000001, AINPUT_SOURCE_CLASS_POINTER = 0x00000002, AINPUT_SOURCE_CLASS_NAVIGATION = 0x00000004, AINPUT_SOURCE_CLASS_POSITION = 0x00000008, AINPUT_SOURCE_CLASS_JOYSTICK = 0x00000010, }; enum { AINPUT_SOURCE_UNKNOWN = 0x00000000, AINPUT_SOURCE_KEYBOARD = 0x00000100 | AINPUT_SOURCE_CLASS_BUTTON, AINPUT_SOURCE_DPAD = 0x00000200 | AINPUT_SOURCE_CLASS_BUTTON, AINPUT_SOURCE_GAMEPAD = 0x00000400 | AINPUT_SOURCE_CLASS_BUTTON, AINPUT_SOURCE_TOUCHSCREEN = 0x00001000 | AINPUT_SOURCE_CLASS_POINTER, AINPUT_SOURCE_MOUSE = 0x00002000 | AINPUT_SOURCE_CLASS_POINTER, AINPUT_SOURCE_STYLUS = 0x00004000 | AINPUT_SOURCE_CLASS_POINTER, AINPUT_SOURCE_TRACKBALL = 0x00010000 | AINPUT_SOURCE_CLASS_NAVIGATION, AINPUT_SOURCE_TOUCHPAD = 0x00100000 | AINPUT_SOURCE_CLASS_POSITION, AINPUT_SOURCE_JOYSTICK = 0x01000000 | AINPUT_SOURCE_CLASS_JOYSTICK, AINPUT_SOURCE_ANY = 0xffffff00, }; /* * Keyboard types. * * Refer to the documentation on android.view.InputDevice for more details. */ enum { AINPUT_KEYBOARD_TYPE_NONE = 0, AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC = 1, AINPUT_KEYBOARD_TYPE_ALPHABETIC = 2, }; /* * Constants used to retrieve information about the range of motion for a particular * coordinate of a motion event. * * Refer to the documentation on android.view.InputDevice for more details about input sources * and their correct interpretation. * * DEPRECATION NOTICE: These constants are deprecated. Use AMOTION_EVENT_AXIS_* constants instead. */ enum { AINPUT_MOTION_RANGE_X = AMOTION_EVENT_AXIS_X, AINPUT_MOTION_RANGE_Y = AMOTION_EVENT_AXIS_Y, AINPUT_MOTION_RANGE_PRESSURE = AMOTION_EVENT_AXIS_PRESSURE, AINPUT_MOTION_RANGE_SIZE = AMOTION_EVENT_AXIS_SIZE, AINPUT_MOTION_RANGE_TOUCH_MAJOR = AMOTION_EVENT_AXIS_TOUCH_MAJOR, AINPUT_MOTION_RANGE_TOUCH_MINOR = AMOTION_EVENT_AXIS_TOUCH_MINOR, AINPUT_MOTION_RANGE_TOOL_MAJOR = AMOTION_EVENT_AXIS_TOOL_MAJOR, AINPUT_MOTION_RANGE_TOOL_MINOR = AMOTION_EVENT_AXIS_TOOL_MINOR, AINPUT_MOTION_RANGE_ORIENTATION = AMOTION_EVENT_AXIS_ORIENTATION, } __attribute__ ((deprecated)); /* * Input event accessors. * * Note that most functions can only be used on input events that are of a given type. * Calling these functions on input events of other types will yield undefined behavior. */ /*** Accessors for all input events. ***/ /* Get the input event type. */ int32_t AInputEvent_getType(const AInputEvent* event); /* Get the id for the device that an input event came from. * * Input events can be generated by multiple different input devices. * Use the input device id to obtain information about the input * device that was responsible for generating a particular event. * * An input device id of 0 indicates that the event didn't come from a physical device; * other numbers are arbitrary and you shouldn't depend on the values. * Use the provided input device query API to obtain information about input devices. */ int32_t AInputEvent_getDeviceId(const AInputEvent* event); /* Get the input event source. */ int32_t AInputEvent_getSource(const AInputEvent* event); /*** Accessors for key events only. ***/ /* Get the key event action. */ int32_t AKeyEvent_getAction(const AInputEvent* key_event); /* Get the key event flags. */ int32_t AKeyEvent_getFlags(const AInputEvent* key_event); /* Get the key code of the key event. * This is the physical key that was pressed, not the Unicode character. */ int32_t AKeyEvent_getKeyCode(const AInputEvent* key_event); /* Get the hardware key id of this key event. * These values are not reliable and vary from device to device. */ int32_t AKeyEvent_getScanCode(const AInputEvent* key_event); /* Get the meta key state. */ int32_t AKeyEvent_getMetaState(const AInputEvent* key_event); /* Get the repeat count of the event. * For both key up an key down events, this is the number of times the key has * repeated with the first down starting at 0 and counting up from there. For * multiple key events, this is the number of down/up pairs that have occurred. */ int32_t AKeyEvent_getRepeatCount(const AInputEvent* key_event); /* Get the time of the most recent key down event, in the * java.lang.System.nanoTime() time base. If this is a down event, * this will be the same as eventTime. * Note that when chording keys, this value is the down time of the most recently * pressed key, which may not be the same physical key of this event. */ int64_t AKeyEvent_getDownTime(const AInputEvent* key_event); /* Get the time this event occurred, in the * java.lang.System.nanoTime() time base. */ int64_t AKeyEvent_getEventTime(const AInputEvent* key_event); /*** Accessors for motion events only. ***/ /* Get the combined motion event action code and pointer index. */ int32_t AMotionEvent_getAction(const AInputEvent* motion_event); /* Get the motion event flags. */ int32_t AMotionEvent_getFlags(const AInputEvent* motion_event); /* Get the state of any meta / modifier keys that were in effect when the * event was generated. */ int32_t AMotionEvent_getMetaState(const AInputEvent* motion_event); /* Get the button state of all buttons that are pressed. */ int32_t AMotionEvent_getButtonState(const AInputEvent* motion_event); /* Get a bitfield indicating which edges, if any, were touched by this motion event. * For touch events, clients can use this to determine if the user's finger was * touching the edge of the display. */ int32_t AMotionEvent_getEdgeFlags(const AInputEvent* motion_event); /* Get the time when the user originally pressed down to start a stream of * position events, in the java.lang.System.nanoTime() time base. */ int64_t AMotionEvent_getDownTime(const AInputEvent* motion_event); /* Get the time when this specific event was generated, * in the java.lang.System.nanoTime() time base. */ int64_t AMotionEvent_getEventTime(const AInputEvent* motion_event); /* Get the X coordinate offset. * For touch events on the screen, this is the delta that was added to the raw * screen coordinates to adjust for the absolute position of the containing windows * and views. */ float AMotionEvent_getXOffset(const AInputEvent* motion_event); /* Get the precision of the Y coordinates being reported. * For touch events on the screen, this is the delta that was added to the raw * screen coordinates to adjust for the absolute position of the containing windows * and views. */ float AMotionEvent_getYOffset(const AInputEvent* motion_event); /* Get the precision of the X coordinates being reported. * You can multiply this number with an X coordinate sample to find the * actual hardware value of the X coordinate. */ float AMotionEvent_getXPrecision(const AInputEvent* motion_event); /* Get the precision of the Y coordinates being reported. * You can multiply this number with a Y coordinate sample to find the * actual hardware value of the Y coordinate. */ float AMotionEvent_getYPrecision(const AInputEvent* motion_event); /* Get the number of pointers of data contained in this event. * Always >= 1. */ size_t AMotionEvent_getPointerCount(const AInputEvent* motion_event); /* Get the pointer identifier associated with a particular pointer * data index in this event. The identifier tells you the actual pointer * number associated with the data, accounting for individual pointers * going up and down since the start of the current gesture. */ int32_t AMotionEvent_getPointerId(const AInputEvent* motion_event, size_t pointer_index); /* Get the tool type of a pointer for the given pointer index. * The tool type indicates the type of tool used to make contact such as a * finger or stylus, if known. */ int32_t AMotionEvent_getToolType(const AInputEvent* motion_event, size_t pointer_index); /* Get the original raw X coordinate of this event. * For touch events on the screen, this is the original location of the event * on the screen, before it had been adjusted for the containing window * and views. */ float AMotionEvent_getRawX(const AInputEvent* motion_event, size_t pointer_index); /* Get the original raw X coordinate of this event. * For touch events on the screen, this is the original location of the event * on the screen, before it had been adjusted for the containing window * and views. */ float AMotionEvent_getRawY(const AInputEvent* motion_event, size_t pointer_index); /* Get the current X coordinate of this event for the given pointer index. * Whole numbers are pixels; the value may have a fraction for input devices * that are sub-pixel precise. */ float AMotionEvent_getX(const AInputEvent* motion_event, size_t pointer_index); /* Get the current Y coordinate of this event for the given pointer index. * Whole numbers are pixels; the value may have a fraction for input devices * that are sub-pixel precise. */ float AMotionEvent_getY(const AInputEvent* motion_event, size_t pointer_index); /* Get the current pressure of this event for the given pointer index. * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure), * although values higher than 1 may be generated depending on the calibration of * the input device. */ float AMotionEvent_getPressure(const AInputEvent* motion_event, size_t pointer_index); /* Get the current scaled value of the approximate size for the given pointer index. * This represents some approximation of the area of the screen being * pressed; the actual value in pixels corresponding to the * touch is normalized with the device specific range of values * and scaled to a value between 0 and 1. The value of size can be used to * determine fat touch events. */ float AMotionEvent_getSize(const AInputEvent* motion_event, size_t pointer_index); /* Get the current length of the major axis of an ellipse that describes the touch area * at the point of contact for the given pointer index. */ float AMotionEvent_getTouchMajor(const AInputEvent* motion_event, size_t pointer_index); /* Get the current length of the minor axis of an ellipse that describes the touch area * at the point of contact for the given pointer index. */ float AMotionEvent_getTouchMinor(const AInputEvent* motion_event, size_t pointer_index); /* Get the current length of the major axis of an ellipse that describes the size * of the approaching tool for the given pointer index. * The tool area represents the estimated size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. */ float AMotionEvent_getToolMajor(const AInputEvent* motion_event, size_t pointer_index); /* Get the current length of the minor axis of an ellipse that describes the size * of the approaching tool for the given pointer index. * The tool area represents the estimated size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. */ float AMotionEvent_getToolMinor(const AInputEvent* motion_event, size_t pointer_index); /* Get the current orientation of the touch area and tool area in radians clockwise from * vertical for the given pointer index. * An angle of 0 degrees indicates that the major axis of contact is oriented * upwards, is perfectly circular or is of unknown orientation. A positive angle * indicates that the major axis of contact is oriented to the right. A negative angle * indicates that the major axis of contact is oriented to the left. * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians * (finger pointing fully right). */ float AMotionEvent_getOrientation(const AInputEvent* motion_event, size_t pointer_index); /* Get the value of the request axis for the given pointer index. */ float AMotionEvent_getAxisValue(const AInputEvent* motion_event, int32_t axis, size_t pointer_index); /* Get the number of historical points in this event. These are movements that * have occurred between this event and the previous event. This only applies * to AMOTION_EVENT_ACTION_MOVE events -- all other actions will have a size of 0. * Historical samples are indexed from oldest to newest. */ size_t AMotionEvent_getHistorySize(const AInputEvent* motion_event); /* Get the time that a historical movement occurred between this event and * the previous event, in the java.lang.System.nanoTime() time base. */ int64_t AMotionEvent_getHistoricalEventTime(const AInputEvent* motion_event, size_t history_index); /* Get the historical raw X coordinate of this event for the given pointer index that * occurred between this event and the previous motion event. * For touch events on the screen, this is the original location of the event * on the screen, before it had been adjusted for the containing window * and views. * Whole numbers are pixels; the value may have a fraction for input devices * that are sub-pixel precise. */ float AMotionEvent_getHistoricalRawX(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical raw Y coordinate of this event for the given pointer index that * occurred between this event and the previous motion event. * For touch events on the screen, this is the original location of the event * on the screen, before it had been adjusted for the containing window * and views. * Whole numbers are pixels; the value may have a fraction for input devices * that are sub-pixel precise. */ float AMotionEvent_getHistoricalRawY(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical X coordinate of this event for the given pointer index that * occurred between this event and the previous motion event. * Whole numbers are pixels; the value may have a fraction for input devices * that are sub-pixel precise. */ float AMotionEvent_getHistoricalX(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical Y coordinate of this event for the given pointer index that * occurred between this event and the previous motion event. * Whole numbers are pixels; the value may have a fraction for input devices * that are sub-pixel precise. */ float AMotionEvent_getHistoricalY(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical pressure of this event for the given pointer index that * occurred between this event and the previous motion event. * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure), * although values higher than 1 may be generated depending on the calibration of * the input device. */ float AMotionEvent_getHistoricalPressure(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the current scaled value of the approximate size for the given pointer index that * occurred between this event and the previous motion event. * This represents some approximation of the area of the screen being * pressed; the actual value in pixels corresponding to the * touch is normalized with the device specific range of values * and scaled to a value between 0 and 1. The value of size can be used to * determine fat touch events. */ float AMotionEvent_getHistoricalSize(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical length of the major axis of an ellipse that describes the touch area * at the point of contact for the given pointer index that * occurred between this event and the previous motion event. */ float AMotionEvent_getHistoricalTouchMajor(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical length of the minor axis of an ellipse that describes the touch area * at the point of contact for the given pointer index that * occurred between this event and the previous motion event. */ float AMotionEvent_getHistoricalTouchMinor(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical length of the major axis of an ellipse that describes the size * of the approaching tool for the given pointer index that * occurred between this event and the previous motion event. * The tool area represents the estimated size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. */ float AMotionEvent_getHistoricalToolMajor(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical length of the minor axis of an ellipse that describes the size * of the approaching tool for the given pointer index that * occurred between this event and the previous motion event. * The tool area represents the estimated size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. */ float AMotionEvent_getHistoricalToolMinor(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical orientation of the touch area and tool area in radians clockwise from * vertical for the given pointer index that * occurred between this event and the previous motion event. * An angle of 0 degrees indicates that the major axis of contact is oriented * upwards, is perfectly circular or is of unknown orientation. A positive angle * indicates that the major axis of contact is oriented to the right. A negative angle * indicates that the major axis of contact is oriented to the left. * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians * (finger pointing fully right). */ float AMotionEvent_getHistoricalOrientation(const AInputEvent* motion_event, size_t pointer_index, size_t history_index); /* Get the historical value of the request axis for the given pointer index * that occurred between this event and the previous motion event. */ float AMotionEvent_getHistoricalAxisValue(const AInputEvent* motion_event, int32_t axis, size_t pointer_index, size_t history_index); #ifdef __cplusplus } #endif #endif // _ANDROID_INPUT_H
1
0.87095
1
0.87095
game-dev
MEDIA
0.474793
game-dev
0.774808
1
0.774808
MonsterDruide1/OdysseyDecomp
1,998
src/Npc/RaceAudienceNpc.cpp
#include "Npc/RaceAudienceNpc.h" #include "Library/LiveActor/ActorActionFunction.h" #include "Library/LiveActor/ActorInitUtil.h" #include "Library/Math/MathUtil.h" #include "Library/Nerve/NerveSetupUtil.h" #include "Library/Nerve/NerveUtil.h" #include "Library/Placement/PlacementFunction.h" namespace { NERVE_IMPL(RaceAudienceNpc, Wait); NERVE_IMPL(RaceAudienceNpc, Dance); NERVE_IMPL(RaceAudienceNpc, Jump); NERVE_IMPL(RaceAudienceNpc, DanceRandom); NERVES_MAKE_STRUCT(RaceAudienceNpc, Wait, Dance, Jump, DanceRandom); } // namespace RaceAudienceNpc::RaceAudienceNpc(const char* name) : al::LiveActor(name) {} void RaceAudienceNpc::init(const al::ActorInitInfo& info) { al::initActor(this, info); al::getArg((s32*)&mAudienceActionType, info, "AudienceActionType"); switch (mAudienceActionType) { case ActionType::Wait: al::initNerve(this, &NrvRaceAudienceNpc.Wait, 0); break; case ActionType::Dance: al::initNerve(this, &NrvRaceAudienceNpc.Dance, 0); break; case ActionType::Jump: al::initNerve(this, &NrvRaceAudienceNpc.Jump, 0); break; } makeActorAlive(); } void RaceAudienceNpc::exeWait() { if (al::isFirstStep(this)) al::startAction(this, "WaitHappy"); } void RaceAudienceNpc::exeDance() { if (al::isFirstStep(this)) { al::startAction(this, "Excited"); mDanceTimer = al::getRandom(600) + 600; } if (al::isGreaterEqualStep(this, mDanceTimer)) { if (mAudienceActionType == ActionType::Jump) al::setNerve(this, &NrvRaceAudienceNpc.Jump); else al::setNerve(this, &NrvRaceAudienceNpc.DanceRandom); } } void RaceAudienceNpc::exeDanceRandom() { if (al::isFirstStep(this)) al::startAction(this, "ExcitedRandom"); if (al::isActionEnd(this)) al::setNerve(this, &NrvRaceAudienceNpc.Dance); } void RaceAudienceNpc::exeJump() { if (al::isFirstStep(this)) al::startAction(this, "ExcitedJump"); }
1
0.859456
1
0.859456
game-dev
MEDIA
0.901199
game-dev
0.70665
1
0.70665
Almamu/EVESharp
5,518
Server/EVESharp.Common/Configuration/Loader.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using EVESharp.Common.Configuration.Attributes; using IniParser; using IniParser.Model; namespace EVESharp.Common.Configuration; public static class Loader { public static T Load <T> (string filename) where T : class { // parse the ini file first FileIniDataParser parser = new FileIniDataParser (); IniData data = parser.ReadFile (filename); // create an instance of the result type T result = Activator.CreateInstance <T> (); // get members inside PropertyInfo[] properties = typeof (T).GetProperties (); // parse each member foreach (PropertyInfo property in properties) { Type propertyType = property.PropertyType; // create a new instance of the properties' type object newObject = Activator.CreateInstance (propertyType); // store the new property back property.SetValue (result, newObject); // get section attribute ConfigSection section = propertyType.GetCustomAttribute <ConfigSection> (); // cannot load members that do not have a section name if (section is null) continue; // ensure the section exists if required, otherwise leave the defaults if (data.Sections.ContainsSection (section.Section) == false) { if (section.Optional == false) throw new KeyNotFoundException ($"Cannot find ini section {section.Section}"); continue; } KeyDataCollection collection = data [section.Section]; // get all the members and check their ConfigValue attribute PropertyInfo [] values = propertyType.GetProperties (); foreach (PropertyInfo value in values) { Type valueType = value.PropertyType; // get the ConfigValue attribute ConfigValue configValue = value.GetCustomAttribute <ConfigValue> (); if (configValue is null) continue; // check if the value exists in the file, otherwise go with the default if (collection.ContainsKey (configValue.Name) == false) { if (configValue.Optional == false) throw new Exception ($"Expected {configValue.Name} inside {section.Section}"); continue; } string iniValue = collection [configValue.Name]; // got the value name, set based on type // first check if the configValue is a transform if (configValue is TransformConfigValue transform) { value.SetValue (newObject, transform.Transform (iniValue)); } else if (typeof (bool) == valueType) { iniValue = iniValue.ToUpper (); // booleans can be casted based on different values, just in case value.SetValue (newObject, iniValue == "YES" || iniValue == "1" || iniValue == "TRUE"); } else if (typeof (List <string>) == valueType) { // comma-separated list value.SetValue ( newObject, iniValue .Split (",") .Select (x => x.Trim()) .ToList () ); } else if (typeof (uint) == valueType) value.SetValue (newObject, uint.Parse (iniValue)); else if (typeof (int) == valueType) value.SetValue (newObject, int.Parse (iniValue)); else if (typeof (ulong) == valueType) value.SetValue (newObject, ulong.Parse (iniValue)); else if (typeof (long) == valueType) value.SetValue (newObject, long.Parse (iniValue)); else if (typeof (ushort) == valueType) value.SetValue (newObject, ushort.Parse (iniValue)); else if (typeof (short) == valueType) value.SetValue (newObject, short.Parse (iniValue)); else if (typeof (byte) == valueType) value.SetValue (newObject, byte.Parse (iniValue)); else if (typeof (sbyte) == valueType) value.SetValue (newObject, sbyte.Parse (iniValue)); else if (typeof (float) == valueType) value.SetValue (newObject, float.Parse (iniValue)); else if (typeof (double) == valueType) value.SetValue (newObject, double.Parse (iniValue)); else if (typeof (string) == valueType) { // try to set it directly value.SetValue (newObject, iniValue); } else { throw new Exception ($"Cannot convert ini value {section.Section}.{configValue.Name} to type"); } } } return result; } }
1
0.949331
1
0.949331
game-dev
MEDIA
0.883658
game-dev
0.995297
1
0.995297
ray-cast/Cubizer
7,112
Standard Assets/Utility/AutoMobileShaderSwitch.cs
using System; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityStandardAssets.Utility { public class AutoMobileShaderSwitch : MonoBehaviour { [SerializeField] private ReplacementList m_ReplacementList; // Use this for initialization private void OnEnable() { #if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_TIZEN || UNITY_STV var renderers = FindObjectsOfType<Renderer>(); Debug.Log (renderers.Length+" renderers"); var oldMaterials = new List<Material>(); var newMaterials = new List<Material>(); int materialsReplaced = 0; int materialInstancesReplaced = 0; foreach(ReplacementDefinition replacementDef in m_ReplacementList.items) { foreach(var r in renderers) { Material[] modifiedMaterials = null; for(int n=0; n<r.sharedMaterials.Length; ++n) { var material = r.sharedMaterials[n]; if (material.shader == replacementDef.original) { if (modifiedMaterials == null) { modifiedMaterials = r.materials; } if (!oldMaterials.Contains(material)) { oldMaterials.Add(material); Material newMaterial = (Material)Instantiate(material); newMaterial.shader = replacementDef.replacement; newMaterials.Add(newMaterial); ++materialsReplaced; } Debug.Log ("replacing "+r.gameObject.name+" renderer "+n+" with "+newMaterials[oldMaterials.IndexOf(material)].name); modifiedMaterials[n] = newMaterials[oldMaterials.IndexOf(material)]; ++materialInstancesReplaced; } } if (modifiedMaterials != null) { r.materials = modifiedMaterials; } } } Debug.Log (materialInstancesReplaced+" material instances replaced"); Debug.Log (materialsReplaced+" materials replaced"); for(int n=0; n<oldMaterials.Count; ++n) { Debug.Log (oldMaterials[n].name+" ("+oldMaterials[n].shader.name+")"+" replaced with "+newMaterials[n].name+" ("+newMaterials[n].shader.name+")"); } #endif } [Serializable] public class ReplacementDefinition { public Shader original = null; public Shader replacement = null; } [Serializable] public class ReplacementList { public ReplacementDefinition[] items = new ReplacementDefinition[0]; } } } namespace UnityStandardAssets.Utility.Inspector { #if UNITY_EDITOR [CustomPropertyDrawer(typeof (AutoMobileShaderSwitch.ReplacementList))] public class ReplacementListDrawer : PropertyDrawer { const float k_LineHeight = 18; const float k_Spacing = 4; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); float x = position.x; float y = position.y; float inspectorWidth = position.width; // Don't make child fields be indented var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; var items = property.FindPropertyRelative("items"); var titles = new string[] {"Original", "Replacement", ""}; var props = new string[] {"original", "replacement", "-"}; var widths = new float[] {.45f, .45f, .1f}; const float lineHeight = 18; bool changedLength = false; if (items.arraySize > 0) { for (int i = -1; i < items.arraySize; ++i) { var item = items.GetArrayElementAtIndex(i); float rowX = x; for (int n = 0; n < props.Length; ++n) { float w = widths[n]*inspectorWidth; // Calculate rects Rect rect = new Rect(rowX, y, w, lineHeight); rowX += w; if (i == -1) { // draw title labels EditorGUI.LabelField(rect, titles[n]); } else { if (props[n] == "-" || props[n] == "^" || props[n] == "v") { if (GUI.Button(rect, props[n])) { switch (props[n]) { case "-": items.DeleteArrayElementAtIndex(i); items.DeleteArrayElementAtIndex(i); changedLength = true; break; case "v": if (i > 0) { items.MoveArrayElement(i, i + 1); } break; case "^": if (i < items.arraySize - 1) { items.MoveArrayElement(i, i - 1); } break; } } } else { SerializedProperty prop = item.FindPropertyRelative(props[n]); EditorGUI.PropertyField(rect, prop, GUIContent.none); } } } y += lineHeight + k_Spacing; if (changedLength) { break; } } } // add button var addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y, widths[widths.Length - 1]*inspectorWidth, lineHeight); if (GUI.Button(addButtonRect, "+")) { items.InsertArrayElementAtIndex(items.arraySize); } y += lineHeight + k_Spacing; // Set indent back to what it was EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { SerializedProperty items = property.FindPropertyRelative("items"); float lineAndSpace = k_LineHeight + k_Spacing; return 40 + (items.arraySize*lineAndSpace) + lineAndSpace; } } #endif }
1
0.760853
1
0.760853
game-dev
MEDIA
0.793076
game-dev
0.805219
1
0.805219
SpitefulFox/Avaritia
3,817
src/main/java/fox/spiteful/avaritia/crafting/ExtremeShapedRecipe.java
package fox.spiteful.avaritia.crafting; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; public class ExtremeShapedRecipe implements IRecipe { /** How many horizontal slots this recipe is wide. */ public final int recipeWidth; /** How many vertical slots this recipe uses. */ public final int recipeHeight; /** Is a array of ItemStack that composes the recipe. */ public final ItemStack[] recipeItems; /** Is the ItemStack that you get when craft the recipe. */ private ItemStack recipeOutput; public ExtremeShapedRecipe(int width, int height, ItemStack[] ingredients, ItemStack result) { this.recipeWidth = width; this.recipeHeight = height; this.recipeItems = ingredients; this.recipeOutput = result; } public ItemStack getRecipeOutput() { return this.recipeOutput; } /** * Used to check if a recipe matches current crafting inventory */ public boolean matches(InventoryCrafting matrix, World world) { for (int i = 0; i <= 9 - this.recipeWidth; ++i) { for (int j = 0; j <= 9 - this.recipeHeight; ++j) { if (this.checkMatch(matrix, i, j, true)) { return true; } if (this.checkMatch(matrix, i, j, false)) { return true; } } } return false; } /** * Checks if the region of a crafting inventory is match for the recipe. */ private boolean checkMatch(InventoryCrafting matrix, int x, int y, boolean mirrored) { for (int k = 0; k < 9; ++k) { for (int l = 0; l < 9; ++l) { int i1 = k - x; int j1 = l - y; ItemStack itemstack = null; if (i1 >= 0 && j1 >= 0 && i1 < this.recipeWidth && j1 < this.recipeHeight) { if (mirrored) { itemstack = this.recipeItems[this.recipeWidth - i1 - 1 + j1 * this.recipeWidth]; } else { itemstack = this.recipeItems[i1 + j1 * this.recipeWidth]; } } ItemStack itemstack1 = matrix.getStackInRowAndColumn(k, l); if (itemstack1 != null || itemstack != null) { if (itemstack1 == null && itemstack != null || itemstack1 != null && itemstack == null) { return false; } if (itemstack.getItem() != itemstack1.getItem()) { return false; } if (itemstack.getItemDamage() != 32767 && itemstack.getItemDamage() != itemstack1.getItemDamage()) { return false; } if (itemstack.hasTagCompound() && !ItemStack.areItemStackTagsEqual(itemstack, itemstack1)) { return false; } } } } return true; } /** * Returns an Item that is the result of this recipe */ public ItemStack getCraftingResult(InventoryCrafting p_77572_1_) { return this.getRecipeOutput().copy(); } /** * Returns the size of the recipe area */ public int getRecipeSize() { return this.recipeWidth * this.recipeHeight; } }
1
0.643301
1
0.643301
game-dev
MEDIA
0.996717
game-dev
0.742874
1
0.742874
rtv/Stage
6,342
libstage/model_bumper.cc
/////////////////////////////////////////////////////////////////////////// // // File: model_bumper.cc // Author: Richard Vaughan // Date: 28 March 2006 // // CVS info: // $Source: // /home/tcollett/stagecvs/playerstage-cvs/code/stage/src/model_bumper.c,v $ // $Author: rtv $ // $Revision: 1.1 $ // /////////////////////////////////////////////////////////////////////////// /** @ingroup model @defgroup model_bumper Bumper/Whisker model The bumper model simulates an array of binary touch sensors. <h2>Worldfile properties</h2> @par Summary and default values @verbatim bumper ( # bumper properties bcount 1 bpose[0] [ 0 0 0 0 ] blength 0.1 ) @endverbatim @par Notes The bumper model allows configuration of the pose and length parameters of each transducer seperately using bpose[index] and blength[index]. For convenience, the length of all bumpers in the array can be set at once with the blength property. If a blength with no index is specified, this global setting is applied first, then specific blengh[index] properties are applied afterwards. Note that the order in the worldfile is ignored. @par Details - bcount int - the number of bumper transducers - bpose[\<transducer index\>] [float float float float] - [x y z theta] - pose of the center of the transducer relative to its parent. - blength float - sets the length in meters of all transducers in the array - blength[\<transducer index\>] float - length in meters of a specific transducer. This is applied after the global setting above. */ #include "option.hh" #include "stage.hh" #include "worldfile.hh" using namespace Stg; #include <math.h> static const watts_t BUMPER_WATTS = 0.1; // bumper power consumption static const Color BUMPER_HIT_RGB(1, 0, 0, 1); // red static const Color BUMPER_NOHIT_RGB(0, 1, 0, 1);// green Option ModelBumper::showBumperData("Show Bumper Data", "show_bumper", "", true, NULL); ModelBumper::ModelBumper(World *world, Model *parent, const std::string &type) : Model(world, parent, type), bumpervis() { PRINT_DEBUG2("Constructing ModelBumper %u (%s)\n", id, type.c_str()); // Set up sensible defaults // assert that Update() is reentrant for this derived model thread_safe = true; bumpers = NULL; samples = NULL; bumper_count = 0; AddVisualizer(&bumpervis, true); } ModelBumper::~ModelBumper() { if (bumpers) delete[] bumpers; if (samples) delete[] samples; } void ModelBumper::Startup(void) { Model::Startup(); PRINT_DEBUG("bumper startup"); this->SetWatts(BUMPER_WATTS); } void ModelBumper::Shutdown(void) { PRINT_DEBUG("bumper shutdown"); this->SetWatts(0); if (this->samples) { delete[] samples; samples = NULL; } Model::Shutdown(); } void ModelBumper::Load(void) { Model::Load(); if (wf->PropertyExists(wf_entity, "bcount")) { PRINT_DEBUG("Loading bumper array"); // Load the geometry of a bumper array bumper_count = wf->ReadInt(wf_entity, "bcount", 0); assert(bumper_count > 0); char key[256]; if (bumpers) delete[] bumpers; bumpers = new BumperConfig[bumper_count]; meters_t common_length; common_length = wf->ReadLength(wf_entity, "blength", 0); // set all transducers with the common settings for (unsigned int i = 0; i < bumper_count; i++) { bumpers[i].length = common_length; } // allow individual configuration of transducers for (unsigned int i = 0; i < bumper_count; i++) { snprintf(key, sizeof(key), "bpose[%u]", i); wf->ReadTuple(wf_entity, key, 0, 4, "llla", &bumpers[i].pose.x, &bumpers[i].pose.y, &bumpers[i].pose.z, &bumpers[i].pose.a); snprintf(key, sizeof(key), "blength[%u]", i); bumpers[i].length = wf->ReadLength(wf_entity, key, bumpers[i].length); } PRINT_DEBUG1("loaded %d bumpers configs", (int)bumper_count); } } static bool bumper_match(Model *candidate, const Model *finder, const void *) { // Ignore myself, my children, and my ancestors. return ( // candidate->vis.obstacle_return && !finder->IsRelated(candidate)); } void ModelBumper::Update(void) { Model::Update(); if ((bumpers == NULL) || (bumper_count < 1)) { return; } if (samples == NULL) { samples = new BumperSample[bumper_count]; } assert(samples); for (unsigned int t = 0; t < bumper_count; t++) { // change the pose of bumper to act as a sensor rotated of PI/2, positioned // at // an extremity of the bumper, and with a range of "length" Pose bpose; bpose.a = bumpers[t].pose.a + M_PI / 2.0; bpose.x = bumpers[t].pose.x - bumpers[t].length / 2.0 * cos(bpose.a); bpose.y = bumpers[t].pose.y - bumpers[t].length / 2.0 * sin(bpose.a); RaytraceResult ray = Raytrace(bpose, bumpers[t].length, bumper_match, NULL, false); samples[t].hit = ray.mod; if (ray.mod) { samples[t].hit_point = point_t(ray.pose.x, ray.pose.y); } } } void ModelBumper::Print(char *prefix) const { Model::Print(prefix); printf("\tBumpers[ "); for (unsigned int i = 0; i < bumper_count; i++) printf("%d ", samples[i].hit ? 1 : 0); puts(" ]"); } ModelBumper::BumperVis::BumperVis() : Visualizer("Bumper hits", "show_bumper_hits") { // Nothing to do here } ModelBumper::BumperVis::~BumperVis() { // Nothing to do here } void ModelBumper::BumperVis::Visualize(Model *mod, Camera *) { ModelBumper *bump = dynamic_cast<ModelBumper *>(mod); if (!(bump->samples && bump->bumpers && bump->bumper_count)) { return; } if (!bump->showBumperData) { return; } /* * draw the sensitive area of the bumper, with a color indicating if it is hit. */ for (unsigned int t = 0; t < bump->bumper_count; t++) { // This is how wide the active area rectangle will be. float thickness = 0.01; glPushMatrix(); // draw the active area with a different color if it is hit if (bump->samples[t].hit) { glColor3f(1.0f, 0.0f, 0.0f); } else { glColor3f(0.0f, 1.0f, 0.0f); } const float rad2deg = 180.0 / M_PI; glTranslatef(bump->bumpers[t].pose.x, bump->bumpers[t].pose.y, 0); glRotatef(bump->bumpers[t].pose.a * rad2deg, 0, 0, 1); glRectf(-thickness / 2.0f, -bump->bumpers[t].length / 2.0, thickness / 2.0f, bump->bumpers[t].length / 2.0); glPopMatrix(); } }
1
0.863747
1
0.863747
game-dev
MEDIA
0.40074
game-dev
0.899696
1
0.899696
Flectone/FlectonePulse
11,310
core/src/main/java/net/flectone/pulse/module/command/chatsetting/builder/DialogMenuBuilder.java
package net.flectone.pulse.module.command.chatsetting.builder; import com.github.retrooper.packetevents.protocol.dialog.CommonDialogData; import com.github.retrooper.packetevents.protocol.dialog.DialogAction; import com.github.retrooper.packetevents.protocol.dialog.action.DynamicCustomAction; import com.github.retrooper.packetevents.protocol.dialog.body.DialogBody; import com.github.retrooper.packetevents.protocol.dialog.body.PlainMessage; import com.github.retrooper.packetevents.protocol.dialog.body.PlainMessageDialogBody; import com.github.retrooper.packetevents.protocol.dialog.button.ActionButton; import com.github.retrooper.packetevents.protocol.dialog.button.CommonButtonData; import com.github.retrooper.packetevents.resources.ResourceLocation; import com.google.inject.Inject; import com.google.inject.Singleton; import lombok.RequiredArgsConstructor; import net.flectone.pulse.config.Command; import net.flectone.pulse.config.localization.Localization; import net.flectone.pulse.execution.pipeline.MessagePipeline; import net.flectone.pulse.model.FColor; import net.flectone.pulse.model.dialog.Dialog; import net.flectone.pulse.model.entity.FPlayer; import net.flectone.pulse.module.command.chatsetting.ChatsettingModule; import net.flectone.pulse.module.command.chatsetting.handler.ChatsettingHandler; import net.flectone.pulse.module.command.chatsetting.model.SubMenuItem; import net.flectone.pulse.platform.controller.DialogController; import net.kyori.adventure.text.Component; import org.apache.commons.lang3.Strings; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; @Singleton @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class DialogMenuBuilder implements MenuBuilder { private final ChatsettingModule chatsettingModule; private final MessagePipeline messagePipeline; private final DialogController dialogController; private final ChatsettingHandler chatsettingHandler; @Override public void open(FPlayer fPlayer, FPlayer fTarget) { Localization.Command.Chatsetting localization = chatsettingModule.localization(fPlayer); Component header = messagePipeline.builder(fPlayer, fTarget, localization.getInventory().trim()).build(); DialogBody dialogBody = new PlainMessageDialogBody(new PlainMessage(Component.empty(), 10)); CommonDialogData commonDialogData = new CommonDialogData( header, null, true, false, DialogAction.CLOSE, List.of(dialogBody), List.of() ); Dialog.Builder dialogBuilder = new Dialog.Builder(commonDialogData, chatsettingModule.config().getModern().getColumns()); dialogBuilder = createDialogChatMenu(fPlayer, fTarget, dialogBuilder, localization); dialogBuilder = createDialogFColorMenu(fPlayer, fTarget, FColor.Type.SEE, dialogBuilder, chatsettingModule.config().getMenu().getSee(), localization.getMenu().getSee()); dialogBuilder = createDialogFColorMenu(fPlayer, fTarget, FColor.Type.OUT, dialogBuilder, chatsettingModule.config().getMenu().getOut(), localization.getMenu().getOut()); for (String setting : chatsettingModule.config().getCheckbox().getTypes().keySet()) { dialogBuilder = createDialogCheckbox(fPlayer, fTarget, setting, dialogBuilder); } dialogController.open(fPlayer, dialogBuilder.build(), false); } private Dialog.Builder createDialogCheckbox(FPlayer fPlayer, FPlayer fTarget, String messageType, Dialog.Builder dialogBuilder) { Command.Chatsetting.Checkbox checkbox = chatsettingModule.config().getCheckbox(); int slot = checkbox.getTypes().get(messageType); if (slot == -1) return dialogBuilder; boolean enabled = fTarget.isSetting(messageType); String title = chatsettingModule.getCheckboxTitle(fPlayer, messageType, enabled); Component componentTitle = messagePipeline.builder(fPlayer, fTarget, title).build(); String lore = chatsettingModule.getCheckboxLore(fPlayer, enabled); Component componentLore = messagePipeline.builder(fPlayer, fTarget, lore).build(); String id = "fp_" + UUID.randomUUID(); ActionButton button = new ActionButton( new CommonButtonData(componentTitle, componentLore, chatsettingModule.config().getModern().getButtonWidth()), new DynamicCustomAction(ResourceLocation.minecraft(id), null) ); return dialogBuilder .addButton(slot, button) .addClickHandler(id, dialog -> { ChatsettingHandler.Status status = chatsettingHandler.handleCheckbox(fPlayer, fTarget, messageType); if (status == ChatsettingHandler.Status.DENIED) return; boolean currentEnabled = status.toBoolean(); String invertTitle = chatsettingModule.getCheckboxTitle(fPlayer, messageType, !currentEnabled); Component componentInvertTitle = messagePipeline.builder(fPlayer, fTarget, invertTitle).build(); String invertLore = chatsettingModule.getCheckboxLore(fPlayer, !currentEnabled); Component componentInvertLore = messagePipeline.builder(fPlayer, fTarget, invertLore).build(); ActionButton invertButton = new ActionButton( new CommonButtonData(componentInvertTitle, componentInvertLore, chatsettingModule.config().getModern().getButtonWidth()), new DynamicCustomAction(ResourceLocation.minecraft(id), null) ); dialogController.changeButton(fPlayer, dialog, id, invertButton); chatsettingModule.saveSetting(fPlayer, messageType); }); } private Dialog.Builder createDialogChatMenu(FPlayer fPlayer, FPlayer fTarget, Dialog.Builder dialogBuilder, Localization.Command.Chatsetting localization) { Command.Chatsetting.Menu.Chat chat = chatsettingModule.config().getMenu().getChat(); int slot = chat.getSlot(); if (slot == -1) return dialogBuilder; String currentChat = chatsettingModule.getPlayerChat(fTarget); String[] messages = Strings.CS.replace( localization.getMenu().getChat().getItem(), "<chat>", currentChat ).split("<br>"); String title = messages.length > 0 ? messages[0] : ""; String lore = messages.length > 1 ? String.join("<br>", Arrays.copyOfRange(messages, 1, messages.length)) : ""; Component componentTitle = messagePipeline.builder(fTarget, title).build(); Component componentLore = messagePipeline.builder(fTarget, lore).build(); String id = "fp_chat"; ActionButton button = new ActionButton( new CommonButtonData(componentTitle, componentLore, chatsettingModule.config().getModern().getButtonWidth()), new DynamicCustomAction(ResourceLocation.minecraft(id), null) ); return dialogBuilder .addButton(slot, button) .addClickHandler(id, dialog -> chatsettingHandler.handleChatMenu(fPlayer, fTarget, chat, localization, this, id) ); } private Dialog.Builder createDialogFColorMenu(FPlayer fPlayer, FPlayer fTarget, FColor.Type type, Dialog.Builder dialogBuilder, Command.Chatsetting.Menu.Color color, Localization.Command.Chatsetting.Menu.SubMenu subMenu) { int slot = color.getSlot(); if (slot == -1) return dialogBuilder; String[] messages = subMenu.getItem().split("<br>"); String title = messages.length > 0 ? messages[0] : ""; String lore = messages.length > 1 ? String.join("<br>", Arrays.copyOfRange(messages, 1, messages.length)) : ""; Component componentTitle = messagePipeline.builder(fTarget, title).build(); Component componentLore = messagePipeline.builder(fTarget, lore).build(); String id = "fp_fcolor_" + type.ordinal(); ActionButton button = new ActionButton( new CommonButtonData(componentTitle, componentLore, chatsettingModule.config().getModern().getButtonWidth()), new DynamicCustomAction(ResourceLocation.minecraft(id), null) ); return dialogBuilder .addButton(slot, button) .addClickHandler(id, dialog -> chatsettingHandler.handleFColorMenu(fPlayer, fTarget, type, color, subMenu, this, id) ); } @Override public void openSubMenu(FPlayer fPlayer, FPlayer fTarget, Component header, Runnable closeConsumer, List<SubMenuItem> items, Function<SubMenuItem, String> getItemMessage, Consumer<SubMenuItem> onSelect, String id) { DialogBody dialogBody = new PlainMessageDialogBody(new PlainMessage(Component.empty(), 10)); CommonDialogData commonDialogData = new CommonDialogData( header, null, true, false, DialogAction.CLOSE, List.of(dialogBody), List.of() ); Dialog.Builder dialogBuilder = new Dialog.Builder(commonDialogData, chatsettingModule.config().getModern().getColumns()) .addCloseConsumer(dialog -> closeConsumer.run()); for (int i = 0; i < items.size(); i++) { SubMenuItem item = items.get(i); String message = getItemMessage.apply(item); String[] messages = message.split("<br>"); String title = messages.length > 0 ? messages[0] : ""; String lore = messages.length > 1 ? String.join("<br>", Arrays.copyOfRange(messages, 1, messages.length)) : ""; Component componentTitle = messagePipeline.builder(fTarget, title).build(); Component componentLore = messagePipeline.builder(fTarget, lore).build(); String subId = id + "_" + i; ActionButton button = new ActionButton( new CommonButtonData(componentTitle, componentLore, chatsettingModule.config().getModern().getButtonWidth()), new DynamicCustomAction(ResourceLocation.minecraft(subId), null) ); dialogBuilder.addButton(i, button); dialogBuilder.addClickHandler(subId, dialog -> chatsettingHandler.handleSubMenu(fPlayer, item, () -> { onSelect.accept(item); dialogController.close(fPlayer.getUuid()); open(fPlayer, fTarget); })); } // reopen - false because submenu is a new menu dialogController.open(fPlayer, dialogBuilder.build(), false); } }
1
0.927241
1
0.927241
game-dev
MEDIA
0.605575
game-dev,desktop-app
0.96072
1
0.96072
goccy/go-zetasql
3,156
internal/ccall/zetasql/base/enum_utils.h
// // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef THIRD_PARTY_ZETASQL_ZETASQL_BASE_ENUM_UTILS_H_ #define THIRD_PARTY_ZETASQL_ZETASQL_BASE_ENUM_UTILS_H_ // Provides utility functions that help with handling Protocol Buffer enums. // // Examples: // // A function to easily iterate over all defined values of an enum known at // compile-time: // // for (Proto::Enum e : EnumerateEnumValues<Proto::Enum>()) { // ... // } // #include "google/protobuf/descriptor.pb.h" namespace zetasql_base { template <typename E> class ProtoEnumIterator; template <typename E> class EnumeratedProtoEnumView; template <typename E> bool operator==(const ProtoEnumIterator<E>& a, const ProtoEnumIterator<E>& b); template <typename E> bool operator!=(const ProtoEnumIterator<E>& a, const ProtoEnumIterator<E>& b); // Generic Proto enum iterator. template <typename E> class ProtoEnumIterator { public: typedef E value_type; typedef std::input_iterator_tag iterator_category; typedef int difference_type; typedef E* pointer; typedef E& reference; ProtoEnumIterator& operator++() { ++current_; return *this; } E operator*() const { return static_cast<E>( google::protobuf::GetEnumDescriptor<E>()->value(current_)->number()); } private: explicit ProtoEnumIterator(int current) : current_(current) {} int current_; // Only EnumeratedProtoEnumView can instantiate ProtoEnumIterator. friend class EnumeratedProtoEnumView<E>; friend bool operator== <>(const ProtoEnumIterator<E>& a, const ProtoEnumIterator<E>& b); friend bool operator!= <>(const ProtoEnumIterator<E>& a, const ProtoEnumIterator<E>& b); }; template <typename E> bool operator==(const ProtoEnumIterator<E>& a, const ProtoEnumIterator<E>& b) { return a.current_ == b.current_; } template <typename E> bool operator!=(const ProtoEnumIterator<E>& a, const ProtoEnumIterator<E>& b) { return a.current_ != b.current_; } template <typename E> class EnumeratedProtoEnumView { public: typedef E value_type; typedef ProtoEnumIterator<E> iterator; iterator begin() const { return iterator(0); } iterator end() const { return iterator(google::protobuf::GetEnumDescriptor<E>()->value_count()); } }; // Returns an EnumeratedProtoEnumView that can be iterated over: // for (Proto::Enum e : EnumerateEnumValues<Proto::Enum>()) { // ... // } template <typename E> EnumeratedProtoEnumView<E> EnumerateEnumValues() { return EnumeratedProtoEnumView<E>(); } } // namespace zetasql_base #endif // THIRD_PARTY_ZETASQL_ZETASQL_BASE_ENUM_UTILS_H_
1
0.811254
1
0.811254
game-dev
MEDIA
0.388534
game-dev
0.61819
1
0.61819
keijiro/4DViewsTest3
2,252
Assets/Remesher/Disintegration.cs
using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; using Unity.Collections; namespace Remesher { // // Disintegration - Flat shader + per-triangle disintegration effect // [ExecuteInEditMode, RequireComponent(typeof(MeshRenderer))] public sealed class Disintegration : MonoBehaviour, ITimeControl, IPropertyPreview { #region Editable attributes [SerializeField] MeshFilter _source = null; [SerializeField] Transform _effector = null; #endregion #region Private objects NativeArray<DisintegrationEffect.Fragment> _fragments; Mesh _mesh; float _time; float _last; #endregion #region ITimeControl implementation public void OnControlTimeStart() => _time = 0; public void OnControlTimeStop() => _time = -1; public void SetTime(double time) => _time = (float)time; #endregion #region IPropertyPreview implementation public void GatherProperties (PlayableDirector director, IPropertyCollector driver) {} #endregion #region MonoBehaviour implementation void OnDisable() { if (_fragments.IsCreated) _fragments.Dispose(); } void OnDestroy() { ObjectUtil.Destroy(_mesh); _mesh = null; } void LateUpdate() { if (_time < 0) { // Negative time: The module is to be disabled. OnDisable(); OnDestroy(); return; } // Lazy initialization if (!_fragments.IsCreated) { _fragments = DisintegrationEffect.Initialize (_source.sharedMesh, _source.transform); _last = 0; } if (_mesh == null) { _mesh = MeshUtil.SetupWithMeshFilter(gameObject); _mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 10); } // Time update // (We don't support rewinding at the moment.) if (_time > _last) DisintegrationEffect.Update(_fragments, _effector, _time - _last); _last = _time; // Mesh reconstruction using (var vertices = DisintegrationEffect.Build(_fragments)) MeshUtil.UpdateWithVertexArray(_mesh, vertices); } #endregion } }
1
0.865483
1
0.865483
game-dev
MEDIA
0.882996
game-dev,graphics-rendering
0.929569
1
0.929569
PCGen/pcgen
3,783
data/deadlands/pinnacle_entertainment/deadlands/deadlands_d20/deadlands_equip_weap_melee.lst
# CVS $Revision$ $Author$ -- Wed Sep 3 00:18:24 2014 -- reformated by prettylst.pl v1.51 (build 24947) SOURCELONG:Deadlands Core Rulebook SOURCESHORT:Deadlands SOURCEWEB:http://www.peginc.com/index.htm SOURCEDATE:2003-01 # Equipment Name Required Weapon Proficiency Type Cost Weight Crit Mult Crit Range Damage Range Size Source Page Weapon prop. bonus Unarmed Strike PROFICIENCY:WEAPON|Unarmed Strike TYPE:Weapon.Unarmed.Melee.Bludgeoning.Monk.Finesseable.Natural COST:0 WT:0 DAMAGE:1d3 SIZE:T SOURCEPAGE:p.72 Brass Knuckles PROFICIENCY:WEAPON|Unarmed Strike TYPE:Weapon.Simple.Melee.Unarmed.Bludgeoning.Finesseable COST:1 WT:1 DAMAGE:1d4 SOURCEPAGE:p.72 Knife (Flint/Bone) PROFICIENCY:WEAPON|Knife TYPE:Weapon.Simple.Melee.Piercing.Finesseable COST:1 WT:1 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d4 SIZE:T SOURCEPAGE:p.72 Knife (Hunting) PROFICIENCY:WEAPON|Knife TYPE:Weapon.Simple.Melee.Ranged.Piercing.Thrown.Finesseable COST:2 WT:1 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d4 RANGE:10 SIZE:T SOURCEPAGE:p.72 Club (Small) PROFICIENCY:WEAPON|Club TYPE:Weapon.Simple.Melee.Bludgeoning.Finesseable COST:0 WT:2 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d4 SIZE:S SOURCEPAGE:p.72 Hatchet PROFICIENCY:WEAPON|Axe TYPE:Weapon.Simple.Melee.Ranged.Slashing.Finesseable COST:3 WT:4 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d6 SIZE:S SOURCEPAGE:p.72 Knife (Bowie) PROFICIENCY:WEAPON|Knife TYPE:Weapon.Simple.Melee.Ranged.Piercing.Slashing.Finesseable COST:4 WT:2 CRITMULT:x3 CRITRANGE:2 DAMAGE:1d4+1 RANGE:10 SIZE:S SOURCEPAGE:p.72 Tomahawk PROFICIENCY:WEAPON|Tomahawk TYPE:Weapon.Simple.Melee.Ranged.Slashing.Finesseable COST:3 WT:4 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d6 RANGE:10 SIZE:S SOURCEPAGE:p.72 Club PROFICIENCY:WEAPON|Club TYPE:Weapon.Simple.Melee.Ranged.Bludgeoning.Thrown.Finesseable COST:0 WT:3 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d6 RANGE:10 SIZE:M SOURCEPAGE:p.72 Skullcrusher PROFICIENCY:WEAPON|Club TYPE:Weapon.Simple.Melee.Bludgeoning.Finesseable COST:4 WT:4 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d6+1 SIZE:M SOURCEPAGE:p.72 War Club (Bladed) PROFICIENCY:WEAPON|Club TYPE:Weapon.Simple.Melee.Bludgeoning.Slashing.Finesseable COST:4 WT:6 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d8 SIZE:M SOURCEPAGE:p.72 Axe (Wood) PROFICIENCY:WEAPON|Axe TYPE:Weapon.Simple.Melee.Slashing.Finesseable COST:0.5 WT:5 CRITMULT:x3 CRITRANGE:1 DAMAGE:1d8 SIZE:L SOURCEPAGE:p.72 #Martial Melee Weapons Name Cavalry Saber PROFICIENCY:WEAPON|Cavalry Saber TYPE:Weapon.Martial.Melee.Slashing COST:15 WT:4 CRITMULT:x2 CRITRANGE:2 DAMAGE:1d8 SIZE:M SOURCEPAGE:p.72 #Exotic Melee Weapons Pick-axe PROFICIENCY:WEAPON|Pick-axe TYPE:Weapon.Exotic.Melee.Piercing COST:2 WT:12 CRITMULT:x4 CRITRANGE:2 DAMAGE:1d8 SIZE:M SOURCEPAGE:p.73 Rifle Bayonet PROFICIENCY:WEAPON|Rifle Bayonet TYPE:Weapon.Exotic.Melee.Piercing.Bludgeoning COST:3 WT:2 CRITMULT:x3 CRITRANGE:1 DAMAGE:1d6 SIZE:L SOURCEPAGE:p.73 #Specific Bowie's Last Knife PROFICIENCY:WEAPON|Knife TYPE:Magic.Weapon.Simple.Melee.Piercing COST:18154 WT:1 CRITMULT:x2 CRITRANGE:2 DAMAGE:1d4 SIZE:T SOURCEPAGE:p.196 BONUS:WEAPON|DAMAGE,TOHIT|3 Cortez's Sword PROFICIENCY:WEAPON|Longsword TYPE:Magic.Weapon.Martial.Melee.Slashing COST:18165 WT:4 CRITMULT:x2 CRITRANGE:2 DAMAGE:1d8 SIZE:M SOURCEPAGE:p.196 BONUS:WEAPON|DAMAGE,TOHIT|3 Crazy Horse's Coup Stick PROFICIENCY:WEAPON|Club TYPE:Magic.Weapon.Simple.Melee.Bludgeoning COST:2704 WT:4 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d6+1 SIZE:M SOURCEPAGE:p.196 Sacred Tomahawk of the Sun PROFICIENCY:WEAPON|Tomahawk TYPE:Magic.Weapon.Simple.Melee.Ranged.Slashing COST:18153 WT:4 CRITMULT:x2 CRITRANGE:1 DAMAGE:1d6 RANGE:10 SIZE:S SOURCEPAGE:p.198 BONUS:WEAPON|DAMAGE,TOHIT|3
1
0.682202
1
0.682202
game-dev
MEDIA
0.993755
game-dev
0.512103
1
0.512103
facebook/redex
1,324
opt/merge_interface/MergeInterface.h
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include "DexClass.h" #include "Pass.h" /** * Merge Interfaces that have same implementors and interface children. * Move interfaces-to-be-merged's functions and fields into merger interfaces * if there is no conflict, if there is conflict existed then skip moving for * abstract method, rename then move for non-true virtuals. (true virtual * conflict will not occur because we checked and removed interfaces that * can cause true virtual conflict.) * Patch all callsites to merged interfaces (change to merger interfaces.) */ class MergeInterfacePass : public Pass { public: MergeInterfacePass() : Pass("MergeInterfacePass") {} redex_properties::PropertyInteractions get_property_interactions() const override { using namespace redex_properties::interactions; using namespace redex_properties::names; return {}; } bool is_cfg_legacy() override { return true; } void run_pass(DexStoresVector&, ConfigFiles&, PassManager&) override; struct Metric { size_t interfaces_to_merge{0}; size_t interfaces_created{0}; size_t interfaces_in_annotation{0}; } m_metric; };
1
0.940573
1
0.940573
game-dev
MEDIA
0.194066
game-dev
0.649439
1
0.649439
richardlord/Flint
5,180
src/org/flintparticles/threeD/actions/MinimumDistance.as
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2011 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.threeD.actions { import org.flintparticles.common.actions.ActionBase; import org.flintparticles.common.emitters.Emitter; import org.flintparticles.common.particles.Particle; import org.flintparticles.threeD.emitters.Emitter3D; import org.flintparticles.threeD.particles.Particle3D; import flash.geom.Vector3D; /** * The MinimumDistance action applies an acceleration to the particle to maintain a minimum * distance between it and its neighbours. * * <p>This action has a priority of 10, so that it executes * before other actions.</p> */ public class MinimumDistance extends ActionBase { private var _min:Number; private var _acc:Number; private var _minSq:Number; /* * Temporary variables created as class members to avoid creating new objects all the time */ private var d:Vector3D; private var move:Vector3D; /** * The constructor creates a ApproachNeighbours action for use by * an emitter. To add a ApproachNeighbours to all particles created by an emitter, use the * emitter's addAction method. * * @see org.flintparticles.common.emitters.Emitter#addAction() * * @param minimum The minimum distance, in pixels, that this action maintains between * particles. * @param acceleration The acceleration force applied to avoid the other particles. */ public function MinimumDistance( minimum:Number = 0, acceleration:Number = 0 ) { priority = 10; d = new Vector3D(); move = new Vector3D(); this.minimum = minimum; this.acceleration = acceleration; } /** * The minimum distance, in pixels, that this action maintains between * particles. */ public function get minimum():Number { return _min; } public function set minimum( value:Number ):void { _min = value; _minSq = value * value; } /** * The acceleration force applied to avoid the other particles. */ public function get acceleration():Number { return _acc; } public function set acceleration( value:Number ):void { _acc = value; } /** * @inheritDoc */ override public function addedToEmitter( emitter:Emitter ) : void { Emitter3D( emitter ).spaceSort = true; } /** * @inheritDoc */ override public function update( emitter:Emitter, particle:Particle, time:Number ):void { var p:Particle3D = Particle3D( particle ); var e:Emitter3D = Emitter3D( emitter ); var particles:Array = e.particlesArray; var other:Particle3D; var i:int; var len:int = particles.length; var distanceInv:Number; var distanceSq:Number; var factor:Number; move.x = 0; move.y = 0; move.z = 0; for( i = p.sortID - 1; i >= 0; --i ) { other = particles[i]; if( ( d.x = p.position.x - other.position.x ) > _min ) break; d.y = p.position.y - other.position.y; if( d.y > _min || d.y < -_min ) continue; d.z = p.position.z - other.position.z; if( d.z > _min || d.z < -_min ) continue; distanceSq = d.lengthSquared; if( distanceSq <= _minSq && distanceSq > 0 ) { distanceInv = 1 / Math.sqrt( distanceSq ); d.scaleBy( distanceInv ); move.incrementBy( d ); } } for( i = p.sortID + 1; i < len; ++i ) { other = particles[i]; if( ( d.x = p.position.x - other.position.x ) < -_min ) break; d.y = p.position.y - other.position.y; if( d.y > _min || d.y < -_min ) continue; d.z = p.position.z - other.position.z; if( d.z > _min || d.z < -_min ) continue; distanceSq = d.lengthSquared; if( distanceSq <= _minSq && distanceSq > 0 ) { distanceInv = 1 / Math.sqrt( distanceSq ); d.scaleBy( distanceInv ); move.incrementBy( d ); } } if ( move.x != 0 || move.y != 0 || move.z != 0 ) { factor = time * _acc / move.length; move.scaleBy( factor ); p.velocity.incrementBy( move ); } } } }
1
0.817194
1
0.817194
game-dev
MEDIA
0.73193
game-dev
0.81778
1
0.81778
psiroki/gzdoomxxh
9,402
wadsrc/static/zscript/ui/statusbar/hexen_sbar.zs
class HexenStatusBar : BaseStatusBar { DynamicValueInterpolator mHealthInterpolator; DynamicValueInterpolator mHealthInterpolator2; HUDFont mHUDFont; HUDFont mIndexFont; HUDFont mBigFont; InventoryBarState diparms; InventoryBarState diparms_sbar; override void Init() { Super.Init(); SetSize(38, 320, 200); // Create the font used for the fullscreen HUD Font fnt = "HUDFONT_RAVEN"; mHUDFont = HUDFont.Create(fnt, fnt.GetCharWidth("0") + 1, Mono_CellLeft, 1, 1); fnt = "INDEXFONT_RAVEN"; mIndexFont = HUDFont.Create(fnt, fnt.GetCharWidth("0"), Mono_CellLeft); fnt = "BIGFONT"; mBigFont = HUDFont.Create(fnt, fnt.GetCharWidth("0"), Mono_CellLeft, 2, 2); diparms = InventoryBarState.Create(mIndexFont); diparms_sbar = InventoryBarState.CreateNoBox(mIndexFont, boxsize:(31, 31), arrowoffs:(0,-10)); mHealthInterpolator = DynamicValueInterpolator.Create(0, 0.25, 1, 8); mHealthInterpolator2 = DynamicValueInterpolator.Create(0, 0.25, 1, 6); // the chain uses a maximum of 6, not 8. } override void NewGame () { Super.NewGame(); mHealthInterpolator.Reset (0); mHealthInterpolator2.Reset (0); } override int GetProtrusion(double scaleratio) const { return scaleratio > 0.85? 28 : 12; // need to get past the gargoyle's wings } override void Tick() { Super.Tick(); mHealthInterpolator.Update(CPlayer.health); mHealthInterpolator2.Update(CPlayer.health); } override void Draw (int state, double TicFrac) { Super.Draw (state, TicFrac); if (state == HUD_StatusBar) { BeginStatusBar(); DrawMainBar (TicFrac); } else if (state == HUD_Fullscreen) { BeginHUD(); DrawFullScreenStuff (); } } protected void DrawFullScreenStuff () { //health DrawImage("PTN1A0", (60, -3)); DrawString(mBigFont, FormatNumber(mHealthInterpolator.GetValue()), (41, -21), DI_TEXT_ALIGN_RIGHT); //armor DrawImage("AR_1A0", (60, -23)); DrawString(mBigFont, FormatNumber(GetArmorSavePercent() / 5, 2), (41, -41), DI_TEXT_ALIGN_RIGHT); //frags/keys if (deathmatch) { DrawString(mHUDFont, FormatNumber(CPlayer.FragCount, 3), (70, -16)); } if (!isInventoryBarVisible() && !Level.NoInventoryBar && CPlayer.mo.InvSel != null) { // This code was changed to always fit the item into the box, regardless of alignment or sprite size. // Heretic's ARTIBOX is 30x30 pixels. DrawImage("ARTIBOX", (-66, -1), 0, HX_SHADOW); DrawInventoryIcon(CPlayer.mo.InvSel, (-66, -15), DI_ARTIFLASH|DI_ITEM_CENTER|DI_DIMDEPLETED, boxsize:(28, 28)); if (CPlayer.mo.InvSel.Amount > 1) { DrawString(mIndexFont, FormatNumber(CPlayer.mo.InvSel.Amount, 3), (-52, -2 - mIndexFont.mFont.GetHeight()), DI_TEXT_ALIGN_RIGHT); } } Ammo ammo1, ammo2; [ammo1, ammo2] = GetCurrentAmmo(); if ((ammo1 is "Mana1") || (ammo2 is "Mana1")) DrawImage("MANABRT1", (-17, -30), DI_ITEM_OFFSETS); else DrawImage("MANADIM1", (-17, -30), DI_ITEM_OFFSETS); if ((ammo1 is "Mana2") || (ammo2 is "Mana2")) DrawImage("MANABRT2", (-17, -15), DI_ITEM_OFFSETS); else DrawImage("MANADIM2", (-17, -15), DI_ITEM_OFFSETS); DrawString(mHUDFont, FormatNumber(GetAmount("Mana1"), 3), (-21, -30), DI_TEXT_ALIGN_RIGHT); DrawString(mHUDFont, FormatNumber(GetAmount("Mana2"), 3), (-21, -15), DI_TEXT_ALIGN_RIGHT); if (isInventoryBarVisible()) { DrawInventoryBar(diparms, (0, 0), 7, DI_SCREEN_CENTER_BOTTOM, HX_SHADOW); } } protected void DrawMainBar (double TicFrac) { DrawImage("H2BAR", (0, 134), DI_ITEM_OFFSETS); String Gem, Chain; if (CPlayer.mo is "ClericPlayer") { Gem = "LIFEGMC2"; Chain = "CHAIN2"; } else if (CPlayer.mo is "MagePlayer") { Gem = "LIFEGMM2"; Chain = "CHAIN3"; } else { Gem = "LIFEGMF2"; Chain = "CHAIN"; } int inthealth = mHealthInterpolator2.GetValue(); DrawGem(Chain, Gem, inthealth, CPlayer.mo.GetMaxHealth(true), (30, 193), -23, 49, 15, (multiplayer? DI_TRANSLATABLE : 0) | DI_ITEM_LEFT_TOP); DrawImage("LFEDGE", (0, 193), DI_ITEM_OFFSETS); DrawImage("RTEDGE", (277, 193), DI_ITEM_OFFSETS); if (!automapactive) { if (isInventoryBarVisible()) { DrawImage("INVBAR", (38, 162), DI_ITEM_OFFSETS); DrawInventoryBar(diparms_sbar, (52, 163), 7, DI_ITEM_LEFT_TOP, HX_SHADOW); } else { DrawImage("STATBAR", (38, 162), DI_ITEM_OFFSETS); //inventory box if (CPlayer.mo.InvSel != null) { DrawInventoryIcon(CPlayer.mo.InvSel, (159.5, 177), DI_ARTIFLASH|DI_ITEM_CENTER|DI_DIMDEPLETED, boxsize:(28, 28)); if (CPlayer.mo.InvSel.Amount > 1) { DrawString(mIndexFont, FormatNumber(CPlayer.mo.InvSel.Amount, 3), (174, 184), DI_TEXT_ALIGN_RIGHT); } } if (deathmatch || teamplay) { DrawImage("KILLS", (38, 163), DI_ITEM_OFFSETS); DrawString(mHUDFont, FormatNumber(CPlayer.FragCount, 3), (66, 176), DI_TEXT_ALIGN_RIGHT); } else { DrawImage("ARMCLS", (41, 178), DI_ITEM_OFFSETS); // Note that this has been changed to use red only if the REAL health is below 25, not when an interpolated value is below 25! DrawString(mHUDFont, FormatNumber(mHealthInterpolator.GetValue(), 3), (66, 176), DI_TEXT_ALIGN_RIGHT, CPlayer.Health < 25? Font.CR_RED : Font.CR_UNTRANSLATED); } //armor DrawImage("ARMCLS", (255, 178), DI_ITEM_OFFSETS); DrawString(mHUDFont, FormatNumber(GetArmorSavePercent() / 5, 2), (276, 176), DI_TEXT_ALIGN_RIGHT); Ammo ammo1, ammo2; [ammo1, ammo2] = GetCurrentAmmo(); if (ammo1 != null && !(ammo1 is "Mana1") && !(ammo1 is "Mana2")) { DrawImage("HAMOBACK", (77, 164), DI_ITEM_OFFSETS); if (ammo2 != null) { DrawTexture(ammo1.icon, (89, 172), DI_ITEM_CENTER); DrawTexture(ammo2.icon, (113, 172), DI_ITEM_CENTER); DrawString(mIndexFont, FormatNumber(ammo1.amount, 3), ( 98, 182), DI_TEXT_ALIGN_RIGHT); DrawString(mIndexFont, FormatNumber(ammo2.amount, 3), (122, 182), DI_TEXT_ALIGN_RIGHT); } else { DrawTexture(ammo1.icon, (100, 172), DI_ITEM_CENTER); DrawString(mIndexFont, FormatNumber(ammo1.amount, 3), (109, 182), DI_TEXT_ALIGN_RIGHT); } } else { int amt1, maxamt1, amt2, maxamt2; [amt1, maxamt1] = GetAmount("Mana1"); [amt2, maxamt2] = GetAmount("Mana2"); if ((ammo1 is "Mana1") || (ammo2 is "Mana1")) { DrawImage("MANABRT1", (77, 164), DI_ITEM_OFFSETS); DrawBar("MANAVL1", "", amt1, maxamt1, (94, 164), 1, SHADER_VERT, DI_ITEM_OFFSETS); } else { DrawImage("MANADIM1", (77, 164), DI_ITEM_OFFSETS); DrawBar("MANAVL1D", "", amt1, maxamt1, (94, 164), 1, SHADER_VERT, DI_ITEM_OFFSETS); } if ((ammo1 is "Mana2") || (ammo2 is "Mana2")) { DrawImage("MANABRT2", (110, 164), DI_ITEM_OFFSETS); DrawBar("MANAVL2", "", amt2, maxamt2, (102, 164), 1, SHADER_VERT, DI_ITEM_OFFSETS); } else { DrawImage("MANADIM2", (110, 164), DI_ITEM_OFFSETS); DrawBar("MANAVL2D", "", amt2, maxamt2, (102, 164), 1, SHADER_VERT, DI_ITEM_OFFSETS); } DrawString(mIndexFont, FormatNumber(amt1, 3), ( 92, 181), DI_TEXT_ALIGN_RIGHT); DrawString(mIndexFont, FormatNumber(amt2, 3), (124, 181), DI_TEXT_ALIGN_RIGHT); } if (CPlayer.mo is "ClericPlayer") { DrawImage("WPSLOT1", (190, 162), DI_ITEM_OFFSETS); if (CheckInventory("CWeapWraithverge")) DrawImage("WPFULL1", (190, 162), DI_ITEM_OFFSETS); else { int pieces = GetWeaponPieceMask("CWeapWraithverge"); if (pieces & 1) DrawImage("WPIECEC1", (190, 162), DI_ITEM_OFFSETS); if (pieces & 2) DrawImage("WPIECEC2", (212, 162), DI_ITEM_OFFSETS); if (pieces & 4) DrawImage("WPIECEC3", (225, 162), DI_ITEM_OFFSETS); } } else if (CPlayer.mo is "MagePlayer") { DrawImage("WPSLOT2", (190, 162), DI_ITEM_OFFSETS); if (CheckInventory("MWeapBloodscourge")) DrawImage("WPFULL2", (190, 162), DI_ITEM_OFFSETS); else { int pieces = GetWeaponPieceMask("MWeapBloodscourge"); if (pieces & 1) DrawImage("WPIECEM1", (190, 162), DI_ITEM_OFFSETS); if (pieces & 2) DrawImage("WPIECEM2", (205, 162), DI_ITEM_OFFSETS); if (pieces & 4) DrawImage("WPIECEM3", (224, 162), DI_ITEM_OFFSETS); } } else { DrawImage("WPSLOT0", (190, 162), DI_ITEM_OFFSETS); if (CheckInventory("FWeapQuietus")) DrawImage("WPFULL0", (190, 162), DI_ITEM_OFFSETS); else { int pieces = GetWeaponPieceMask("FWeapQuietus"); if (pieces & 1) DrawImage("WPIECEF1", (190, 162), DI_ITEM_OFFSETS); if (pieces & 2) DrawImage("WPIECEF2", (225, 162), DI_ITEM_OFFSETS); if (pieces & 4) DrawImage("WPIECEF3", (234, 162), DI_ITEM_OFFSETS); } } } } else // automap { DrawImage("KEYBAR", (38, 162), DI_ITEM_OFFSETS); int cnt = 0; Vector2 keypos = (46, 164); for(let i = CPlayer.mo.Inv; i != null; i = i.Inv) { if (i is "Key" && i.Icon.IsValid()) { DrawTexture(i.Icon, keypos, DI_ITEM_OFFSETS); keypos.X += 20; if (++cnt >= 5) break; } } DrawHexenArmor(HEXENARMOR_ARMOR, "ARMSLOT1", (150, 164), DI_ITEM_OFFSETS); DrawHexenArmor(HEXENARMOR_SHIELD, "ARMSLOT2", (181, 164), DI_ITEM_OFFSETS); DrawHexenArmor(HEXENARMOR_HELM, "ARMSLOT3", (212, 164), DI_ITEM_OFFSETS); DrawHexenArmor(HEXENARMOR_AMULET, "ARMSLOT4", (243, 164), DI_ITEM_OFFSETS); } } }
1
0.890232
1
0.890232
game-dev
MEDIA
0.873245
game-dev
0.972366
1
0.972366
Tercioo/Details-Damage-Meter
6,179
functions/journal.lua
local Details = _G.Details local DF = _G.DetailsFramework local C_Timer = _G.C_Timer local addonName, Details222 = ... local GetSpellInfo = Details222.GetSpellInfo --get the sectionInfo and try to extract the spellID from it --sectionInfo is always a valid table local parseSectionInfoForSpellID = function(sectionInfo) local spellId = sectionInfo.spellID if (spellId) then spellId = tonumber(spellId) if (spellId) then local spellName = GetSpellInfo(spellId) if (spellName) then return spellId end end end end ---this function is called when the player clicks on a link in the chat window to open a section in the encounter journal ---Details! then will check if that spell linked did damage to the raid and show a small box with the damage done ---@param tag any tag isn't used ---@param journalTypeString string ---@param idString string function Details222.EJCache.OnClickEncounterJournalLink(tag, journalTypeString, idString) --not in use local journalType = tonumber(journalTypeString) local id = tonumber(idString) local instanceId, encounterId, sectionId, tierIndex = EJ_HandleLinkPath(journalType, id) if (sectionId) then local sectionInfo = C_EncounterJournal.GetSectionInfo(sectionId) if (sectionInfo and type(sectionInfo) == "table") then local spellId = parseSectionInfoForSpellID(sectionInfo) --spellId is guaranteed to be a valid spellId or nil if (spellId) then local damageDoneTable = Details222.DamageSpells.GetDamageDoneToPlayersBySpell(spellId) local topDamage = damageDoneTable[1] and damageDoneTable[1][2] if (topDamage and topDamage > 0) then --build a cooltip with the damage done to players by the spellId local gameCooltip = GameCooltip gameCooltip:Preset(2) gameCooltip:SetType("tooltip") gameCooltip:SetOption("LeftPadding", -5) gameCooltip:SetOption("RightPadding", 5) gameCooltip:SetOption("LinePadding", 1) gameCooltip:SetOption("StatusBarTexture", [[Interface\AddOns\Details\images\bar_hyanda]]) for i = 1, #damageDoneTable do local targetName, damageDone = unpack(damageDoneTable[i]) local nameWithoutRealm = DF:RemoveRealmName(targetName) local formattedDamage = Details:ToK2(damageDone) local className = Details222.ClassCache.GetClass(targetName) local classTexture, left, right, top, bottom = Details:GetClassIcon(className) gameCooltip:AddLine(nameWithoutRealm, formattedDamage) gameCooltip:AddIcon(classTexture, 1, 1, 14, 14, left, right, top, bottom) gameCooltip:AddStatusBar(damageDone / topDamage * 100, 1, .5, .5, .5, 1, false, {value = 100, color = {.2, .2, .2, 0.9}, texture = [[Interface\AddOns\Details\images\bar_hyanda]]}) end local abilityString = DF:MakeStringFromSpellId(spellId) if (abilityString) then abilityString = abilityString .. " (damage to)" end local anchor = {"bottom", "top", 0, 0} gameCooltip:SetBannerImage(1, 2, [[Interface\PetBattles\Weather-Blizzard]], 220, 55, anchor, {0.85, 0.189609375, 1, 0}, {0, 0, 0, 1}) gameCooltip:SetBannerText(1, 2, abilityString or "Ability Damage Done", {"bottomleft", "topleft", 0, 2}, "white", 14) gameCooltip:SetOwner(EncounterJournal, "topleft", "topright", 50, -10) gameCooltip:Show() end end end end if (not Details222.EJCache.HasJournalOnHideHooked) then Details222.EJCache.HasJournalOnHideHooked = true EncounterJournal:HookScript("OnHide", function() GameCooltip:Hide() end) end end --search the damage container within the combatObject index[1] for actor that used the spellId passed and inflicted damage to players ---@param spellId number ---@param combatId any ---@return table function Details222.DamageSpells.GetDamageDoneToPlayersBySpell(spellId, combatId) local combatObject = Details:GetCombat(combatId) if (not combatObject) then return {} end local damageContainer = combatObject:GetContainer(DETAILS_ATTRIBUTE_DAMAGE) if (not damageContainer) then return {} end local damageDoneTable = {} for index, actorObject in damageContainer:ListActors() do if (actorObject:IsNeutralOrEnemy()) then local spellTable = actorObject:GetSpell(spellId) if (spellTable) then for targetName, damageDone in pairs(spellTable.targets) do damageDoneTable[targetName] = (damageDoneTable[targetName] or 0) + damageDone end end end end local sortedResult = {} for targetName, damageDone in pairs(damageDoneTable) do local className = Details222.ClassCache.GetClass(targetName) sortedResult[#sortedResult + 1] = {targetName, damageDone, className} end table.sort(sortedResult, function(a, b) return a[2] > b[2] end) return sortedResult end --[=[ ["description"] = "Eranog wreathes several players in flames. Upon expiration a Flamerift forms at each player's location, inflicting 144,550 Fire damage to players within 4 yards. A Flamescale Tarasek spills forth from each Flamerift, leaving behind a Lava Flow. On Mythic difficulty, Eranog also opens a Greater Flamerift that creates a Flamescale Captain.", ["link"] = "[Flamerift]", ["siblingSectionID"] = 26037, ["startsOpen"] = false, ["creatureDisplayID"] = 0, ["headerType"] = 2, ["title"] = "Flamerift", ["firstChildSectionID"] = 26036, ["uiModelSceneID"] = 0, ["filteredByDifficulty"] = false, ["abilityIcon"] = 134153, ["spellID"] = 390715, --]=]
1
0.901361
1
0.901361
game-dev
MEDIA
0.949941
game-dev
0.979308
1
0.979308
pietro-lopes/AllTheLeaks
1,422
src/main/java/dev/uncandango/alltheleaks/mixin/core/main/AreaRenderManagerMixin.java
package dev.uncandango.alltheleaks.mixin.core.main; import com.llamalad7.mixinextras.sugar.Local; import me.desht.pneumaticcraft.client.render.area.AreaRenderManager; import me.desht.pneumaticcraft.client.render.area.AreaRenderer; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.neoforged.neoforge.client.event.ClientTickEvent; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; import java.util.Map; @Mixin(value = AreaRenderManager.class, remap = false) public class AreaRenderManagerMixin { // @Shadow // private Level level; // // @Shadow // private List<AreaRenderer> cachedPositionProviderShowers; // // @Shadow // @Final // private Map<BlockPos, AreaRenderer> showHandlers; // // @Inject(method = "tickEnd", at = @At(value = "TAIL")) // private void atl$cleanUp(ClientTickEvent.Post event, CallbackInfo ci, @Local Player player) { // if (player == null && this.level != null) { // this.level = null; // if (this.cachedPositionProviderShowers != null) { // this.cachedPositionProviderShowers.clear(); // } // showHandlers.clear(); // } // } }
1
0.934729
1
0.934729
game-dev
MEDIA
0.992082
game-dev
0.973233
1
0.973233
maruohon/litematica
11,495
src/main/java/litematica/task/MultiplayerCreateSchematicTask.java
package litematica.task; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.function.BiConsumer; import java.util.function.Consumer; import net.minecraft.block.Block; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.NextTickListEntry; import malilib.mixin.access.NBTTagLongArrayMixin; import malilib.overlay.message.MessageDispatcher; import malilib.util.StringUtils; import malilib.util.game.wrap.NbtWrap; import malilib.util.game.wrap.RegistryUtils; import malilib.util.nbt.NbtUtils; import malilib.util.position.BlockPos; import malilib.util.position.Vec3d; import malilib.util.position.Vec3i; import litematica.network.SchematicSavePacketHandler; import litematica.render.infohud.InfoHud; import litematica.scheduler.tasks.TaskBase; import litematica.schematic.EntityInfo; import litematica.schematic.ISchematic; import litematica.schematic.LitematicaSchematic; import litematica.schematic.SchematicBase; import litematica.schematic.SchematicMetadata; import litematica.schematic.SchematicType; import litematica.schematic.container.LitematicaBlockStateContainerFull; import litematica.schematic.util.SchematicCreationUtils; import litematica.selection.AreaSelection; import litematica.selection.SelectionBox; import litematica.util.PositionUtils; public class MultiplayerCreateSchematicTask extends TaskBase { protected final UUID taskId; protected final Consumer<ISchematic> schematicConsumer; protected final LitematicaSchematic schematic; protected final String selectionName; public MultiplayerCreateSchematicTask(AreaSelection selection, UUID taskId, Consumer<ISchematic> schematicConsumer) { this.taskId = taskId; this.schematicConsumer = schematicConsumer; this.schematic = SchematicType.LITEMATICA.createSchematic(null); this.selectionName = selection.getName(); List<SelectionBox> boxes = selection.getAllSelectionBoxes(); this.schematic.setSubRegions(boxes, selection.getEffectiveOrigin()); SchematicMetadata metadata = this.schematic.getMetadata(); metadata.setRegionCount(boxes.size()); metadata.setTotalVolume(PositionUtils.getTotalVolume(boxes)); metadata.setEnclosingSize(PositionUtils.getEnclosingAreaSize(boxes)); this.name = StringUtils.translate("litematica.hud.task_name.save_schematic.server_side"); this.infoHudLines.add(StringUtils.translate("litematica.hud.save_schematic.server_side.waiting")); InfoHud.getInstance().addInfoHudRenderer(this, true); } @Override public boolean execute() { return this.finished; } @Override public void stop() { if (this.finished == false) { MessageDispatcher.warning("litematica.message.error.schematic_save_interrupted"); } SchematicSavePacketHandler.INSTANCE.removeSaveTask(this.taskId); super.stop(); } public void onReceiveData(NBTTagCompound tag) { if (NbtWrap.containsCompound(tag, "Regions") == false || NbtWrap.containsString(tag, "SaveMethod") == false) { MessageDispatcher.error("litematica.message.error.schematic_save.server_side.invalid_data"); return; } NBTTagCompound regionsTag = NbtWrap.getCompound(tag, "Regions"); String saveMethod = NbtWrap.getString(tag, "SaveMethod"); if (saveMethod.equals("AllAtOnce")) { this.readRegions(regionsTag, this::readEntireRegion); this.onSchematicComplete(); } else if (saveMethod.equals("PerChunk")) { this.readRegions(regionsTag, this::readPerChunkPieceOfRegion); if (NbtWrap.getBoolean(tag, "Finished")) { this.onSchematicComplete(); } } } protected void onSchematicComplete() { SchematicCreationUtils.setSchematicMetadataOnCreation(this.schematic, this.selectionName); this.schematicConsumer.accept(this.schematic); this.finished = true; } protected void readRegions(NBTTagCompound regionsTag, BiConsumer<String, NBTTagCompound> regionReader) { for (String regionName : NbtWrap.getKeys(regionsTag)) { if (NbtWrap.containsCompound(regionsTag, regionName)) { NBTTagCompound regionTag = NbtWrap.getCompound(regionsTag, regionName); regionReader.accept(regionName, regionTag); } } } protected void readEntireRegion(String regionName, NBTTagCompound regionTag) { LitematicaSchematic.LitematicaSubRegion region = this.schematic.getSchematicRegion(regionName); if (region != null) { this.readBlocks(regionTag, region::setBlockStateContainer); this.readBlockEntities(regionTag, region::setBlockEntityMap); this.readEntities(regionTag, region::setEntityList); this.readScheduledTicks(regionTag, "BlockTicks", region::setBlockTickMap); } } protected void readPerChunkPieceOfRegion(String regionName, NBTTagCompound regionTag) { LitematicaSchematic.LitematicaSubRegion region = this.schematic.getSchematicRegion(regionName); if (region != null) { // TODO blocks //this.readBlocks(regionTag, region::setBlockStateContainer); this.readBlockEntities(regionTag, map -> region.getBlockEntityMap().putAll(map)); this.readEntities(regionTag, list -> region.getEntityList().addAll(list)); this.readScheduledTicks(regionTag, "BlockTicks", map -> region.getBlockTickMap().putAll(map)); } } protected void readBlocks(NBTTagCompound regionTag, Consumer<LitematicaBlockStateContainerFull> consumer) { if (NbtWrap.containsCompound(regionTag, "Blocks")) { NBTTagCompound blocksTag = NbtWrap.getCompound(regionTag, "Blocks"); if (NbtWrap.containsList(blocksTag, "BlockStatePalette") && NbtWrap.containsLongArray(blocksTag, "BlockStates") && NbtWrap.containsInt(blocksTag, "sizeX") && NbtWrap.containsInt(blocksTag, "sizeY") && NbtWrap.containsInt(blocksTag, "sizeZ")) { NBTBase nbtBase = NbtWrap.getTag(blocksTag, "BlockStates"); Vec3i size = new Vec3i(NbtWrap.getInt(blocksTag, "sizeX"), NbtWrap.getInt(blocksTag, "sizeY"), NbtWrap.getInt(blocksTag, "sizeZ")); if (size.getX() <= 0 || size.getY() <= 0 || size.getZ() <= 0) { MessageDispatcher.error("litematica.message.error.schematic_save.server_side.invalid_region_size", size); return; } NBTTagList paletteTag = NbtWrap.getListOfCompounds(blocksTag, "BlockStatePalette"); long[] blockStateArr = ((NBTTagLongArrayMixin) nbtBase).getArray(); int paletteSize = NbtWrap.getListSize(paletteTag); LitematicaBlockStateContainerFull container = LitematicaBlockStateContainerFull.createContainer(paletteSize, blockStateArr, size); if (container != null) { SchematicBase.readPaletteFromLitematicaFormatTag(paletteTag, container.getPalette()); consumer.accept(container); long totalBlockCount; if (NbtWrap.containsLong(blocksTag, "TotalBlockCount")) { totalBlockCount = NbtWrap.getLong(blocksTag, "TotalBlockCount"); } else { totalBlockCount = container.getTotalBlockCount(); } this.schematic.getMetadata().setTotalBlocks(totalBlockCount); return; } else { MessageDispatcher.error("litematica.message.error.schematic_save.server_side.failed_to_create_block_container"); } } } MessageDispatcher.error("litematica.message.error.schematic_save.server_side.missing_tags_in_block_data"); } protected void readBlockEntities(NBTTagCompound regionTag, Consumer<HashMap<BlockPos, NBTTagCompound>> consumer) { if (NbtWrap.containsList(regionTag, "BlockEntities")) { NBTTagList listTag = NbtWrap.getListOfCompounds(regionTag, "BlockEntities"); HashMap<BlockPos, NBTTagCompound> map = new HashMap<>(); final int size = NbtWrap.getListSize(listTag); for (int i = 0; i < size; ++i) { NBTTagCompound tag = NbtWrap.getCompoundAt(listTag, i); BlockPos pos = NbtUtils.readBlockPos(tag); if (pos != null) { NbtUtils.removeBlockPosFromTag(tag); map.put(pos, tag); } } consumer.accept(map); } } protected void readEntities(NBTTagCompound regionTag, Consumer<List<EntityInfo>> consumer) { if (NbtWrap.containsList(regionTag, "Entities")) { NBTTagList listTag = NbtWrap.getListOfCompounds(regionTag, "Entities"); ArrayList<EntityInfo> list = new ArrayList<>(); final int size = NbtWrap.getListSize(listTag); for (int i = 0; i < size; ++i) { NBTTagCompound tag = NbtWrap.getCompoundAt(listTag, i); Vec3d pos = NbtUtils.readVec3dFromListTag(tag, "Pos"); if (pos != null) { NbtWrap.remove(tag, "Pos"); list.add(new EntityInfo(pos, tag)); } } consumer.accept(list); } } protected <T> void readScheduledTicks(NBTTagCompound regionTag, String tagName, //Function<String, T> objectFactory, // TODO Consumer<HashMap<BlockPos, NextTickListEntry>> consumer) { if (NbtWrap.containsList(regionTag, tagName)) { NBTTagList listTag = NbtWrap.getListOfCompounds(regionTag, tagName); HashMap<BlockPos, NextTickListEntry> map = new HashMap<>(); final int size = NbtWrap.getListSize(listTag); for (int i = 0; i < size; ++i) { NBTTagCompound tag = NbtWrap.getCompoundAt(listTag, i); BlockPos pos = NbtUtils.readBlockPos(tag); Block block = RegistryUtils.getBlockByIdStr(NbtWrap.getString(tag, "Block")); if (pos != null && block != null) { NbtUtils.removeBlockPosFromTag(tag); NextTickListEntry entry = new NextTickListEntry(pos, block); entry.setPriority(NbtWrap.getInt(tag, "Priority")); entry.setScheduledTime(NbtWrap.getInt(tag, "Time")); map.put(pos, entry); } } consumer.accept(map); } } }
1
0.937428
1
0.937428
game-dev
MEDIA
0.847939
game-dev
0.932864
1
0.932864
mm201/pkmn-classic-framework
1,143
web/src/OnceTemplate.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PkmnFoundations.Web { /// <summary> /// Control which only renders once per unique key on a given page. /// </summary> public class OnceTemplate : System.Web.UI.WebControls.PlaceHolder { public OnceTemplate() : base() { } public String Key { get; set; } private HashSet<String> m_keys = null; private HashSet<String> Keys { get { if (m_keys != null) return m_keys; if (!Page.Items.Contains("pkmncfOnceTemplate")) { m_keys = new HashSet<String>(); Page.Items.Add("pkmncfOnceTemplate", m_keys); } else m_keys = (HashSet<String>)Page.Items["pkmncfOnceTemplate"]; return m_keys; } } protected override void Render(System.Web.UI.HtmlTextWriter writer) { if (Keys.Contains(Key)) return; Keys.Add(Key); base.Render(writer); } } }
1
0.649935
1
0.649935
game-dev
MEDIA
0.309978
game-dev
0.78392
1
0.78392
0everey/ES_Framework_Core_OBSOLUTE
1,277
Assets/FishNet/Runtime/Plugins/GameKit/Dependencies/Utilities/Types/SingletonScriptableObject.cs
using UnityEngine; namespace GameKit.Dependencies.Utilities.Types { /// <summary> /// Creates a singleton instance of a scriptable object. /// </summary> /// <typeparam name="T"></typeparam> public abstract class SingletonScriptableObject<T> : ScriptableObject where T : ScriptableObject { private static T _instance = null; public static T Instance { get { if (_instance == null) { T[] results = UnityEngine.Resources.FindObjectsOfTypeAll<T>(); if (results.Length == 0) { Debug.LogError("SingletonScriptableObject: results length is 0 of " + typeof(T).ToString()); return null; } if (results.Length > 1) { Debug.LogError("SingletonScriptableObject: results length is greater than 1 of " + typeof(T).ToString()); return null; } _instance = results[0]; _instance.hideFlags = HideFlags.DontUnloadUnusedAsset; } return _instance; } } } }
1
0.823934
1
0.823934
game-dev
MEDIA
0.830812
game-dev
0.81115
1
0.81115
thetawavegame/thetawave
4,576
src/audio/mod.rs
//! Exposes a plugin that starts, stops, and modulates in-game audio when events are emitted use bevy::prelude::{ in_state, not, App, EventReader, IntoSystemConfigs, Plugin, Res, Resource, Startup, Update, }; use bevy_kira_audio::prelude::{AudioApp, AudioChannel, AudioControl, AudioEasing, AudioTween}; use thetawave_assets::GameAudioAssets; use thetawave_interface::{ audio::{ChangeBackgroundMusicEvent, PlaySoundEffectEvent}, states::AppStates, }; /// Starts, stops, and modulates in-game audio when we receive a /// `thetawave_interface::audio::PlaySoundEffectEvent` or /// `thetawave_interface::audio::ChangeBackgroundMusicEvent`. pub(super) struct ThetawaveAudioPlugin; impl Plugin for ThetawaveAudioPlugin { fn build(&self, app: &mut App) { app.add_event::<PlaySoundEffectEvent>(); app.add_event::<ChangeBackgroundMusicEvent>(); app.add_audio_channel::<BackgroundMusicAudioChannel>() .add_audio_channel::<MenuAudioChannel>() .add_audio_channel::<SoundEffectsAudioChannel>(); app.add_systems(Startup, set_audio_volume_system); app.add_systems( Update, (play_sound_effect_system, change_bg_music_system) .run_if(not(in_state(AppStates::LoadingAssets))), ); } } // audio channels #[derive(Resource)] pub struct BackgroundMusicAudioChannel; #[derive(Resource)] pub struct MenuAudioChannel; #[derive(Resource)] pub struct SoundEffectsAudioChannel; /// Sets the volume of the audio channels to "sane defaults" fn set_audio_volume_system( background_audio_channel: Res<AudioChannel<BackgroundMusicAudioChannel>>, menu_audio_channel: Res<AudioChannel<MenuAudioChannel>>, effects_audio_channel: Res<AudioChannel<SoundEffectsAudioChannel>>, ) { background_audio_channel.set_volume(0.20); menu_audio_channel.set_volume(0.05); effects_audio_channel.set_volume(0.80); } /// Play sound effects when we receive events. This should be called every frame for snappy audio. fn play_sound_effect_system( mut play_sound_event_reader: EventReader<PlaySoundEffectEvent>, audio_channel: Res<AudioChannel<SoundEffectsAudioChannel>>, audio_assets: Res<GameAudioAssets>, ) { for event in play_sound_event_reader.read() { audio_channel.play(audio_assets.get_sound_effect(&event.sound_effect_type)); } } /// System to handle background music changes based on events. /// /// This system listens for `ChangeBackgroundMusicEvent` events and updates /// the background music accordingly. It can stop the current music, start new /// music, handle looping, and apply fade-in and fade-out effects if specified in the event. /// /// - If an event specifies a fade-out duration, the current track will fade out before stopping. /// - If a new background music type is provided, it will play the corresponding track from the `GameAudioAssets`. /// - The system supports looping the new track from a specified point and applying a fade-in effect if specified. /// /// Parameters: /// - `EventReader<ChangeBackgroundMusicEvent>`: Reads events that dictate when and how to change background music. /// - `AudioChannel<BackgroundMusicAudioChannel>`: Controls the background music audio channel, allowing for stop, play, and fade effects. /// - `GameAudioAssets`: A resource that holds all available audio assets. fn change_bg_music_system( mut change_bg_music_event_reader: EventReader<ChangeBackgroundMusicEvent>, audio_channel: Res<AudioChannel<BackgroundMusicAudioChannel>>, audio_assets: Res<GameAudioAssets>, ) { for event in change_bg_music_event_reader.read() { // stop audio if playing sound if audio_channel.is_playing_sound() { let mut stop_command = audio_channel.stop(); // use fade if specified if let Some(fade_out) = event.fade_out { stop_command.fade_out(AudioTween::new(fade_out, AudioEasing::Linear)); } } // play music if provided a type if let Some(bg_music_type) = event.bg_music_type.clone() { let mut start_command = audio_channel.play(audio_assets.get_bg_music_asset(&bg_music_type)); // loop if true if let Some(loop_from) = event.loop_from { start_command.loop_from(loop_from); } // use fade if specified if let Some(fade_in) = event.fade_in { start_command.fade_in(AudioTween::new(fade_in, AudioEasing::Linear)); } } } }
1
0.796153
1
0.796153
game-dev
MEDIA
0.650538
game-dev
0.959888
1
0.959888
nichodim/PolyTrack
4,704
game/ci_venv/include/site/python3.11/pygame/scrap.h
/* pygame - Python Game Library Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen Originally put in the public domain by Sam Lantinga. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef SCRAP_H #define SCRAP_H /* This is unconditionally defined in Python.h */ #if defined(_POSIX_C_SOURCE) #undef _POSIX_C_SOURCE #endif #include <Python.h> /* Handle clipboard text and data in arbitrary formats */ /** * Predefined supported pygame scrap types. */ #define PYGAME_SCRAP_TEXT "text/plain" #define PYGAME_SCRAP_BMP "image/bmp" #define PYGAME_SCRAP_PPM "image/ppm" #define PYGAME_SCRAP_PBM "image/pbm" /** * The supported scrap clipboard types. * * This is only relevant in a X11 environment, which supports mouse * selections as well. For Win32 and MacOS environments the default * clipboard is used, no matter what value is passed. */ typedef enum { SCRAP_CLIPBOARD, SCRAP_SELECTION /* only supported in X11 environments. */ } ScrapClipType; /** * Macro for initialization checks. */ #define PYGAME_SCRAP_INIT_CHECK() \ if (!pygame_scrap_initialized()) \ return (PyErr_SetString(pgExc_SDLError, "scrap system not initialized."), \ NULL) /** * \brief Checks, whether the pygame scrap module was initialized. * * \return 1 if the modules was initialized, 0 otherwise. */ extern int pygame_scrap_initialized(void); /** * \brief Initializes the pygame scrap module internals. Call this before any * other method. * * \return 1 on successful initialization, 0 otherwise. */ extern int pygame_scrap_init(void); /** * \brief Checks, whether the pygame window lost the clipboard focus or not. * * \return 1 if the window lost the focus, 0 otherwise. */ extern int pygame_scrap_lost(void); /** * \brief Places content of a specific type into the clipboard. * * \note For X11 the following notes are important: The following types * are reserved for internal usage and thus will throw an error on * setting them: "TIMESTAMP", "TARGETS", "SDL_SELECTION". * Setting PYGAME_SCRAP_TEXT ("text/plain") will also automatically * set the X11 types "STRING" (XA_STRING), "TEXT" and "UTF8_STRING". * * For Win32 the following notes are important: Setting * PYGAME_SCRAP_TEXT ("text/plain") will also automatically set * the Win32 type "TEXT" (CF_TEXT). * * For QNX the following notes are important: Setting * PYGAME_SCRAP_TEXT ("text/plain") will also automatically set * the QNX type "TEXT" (Ph_CL_TEXT). * * \param type The type of the content. * \param srclen The length of the content. * \param src The NULL terminated content. * \return 1, if the content could be successfully pasted into the clipboard, * 0 otherwise. */ extern int pygame_scrap_put(char *type, Py_ssize_t srclen, char *src); /** * \brief Gets the current content from the clipboard. * * \note The received content does not need to be the content previously * placed in the clipboard using pygame_put_scrap(). See the * pygame_put_scrap() notes for more details. * * \param type The type of the content to receive. * \param count The size of the returned content. * \return The content or NULL in case of an error or if no content of the * specified type was available. */ extern char * pygame_scrap_get(char *type, size_t *count); /** * \brief Gets the currently available content types from the clipboard. * * \return The different available content types or NULL in case of an * error or if no content type is available. */ extern char ** pygame_scrap_get_types(void); /** * \brief Checks whether content for the specified scrap type is currently * available in the clipboard. * * \param type The type to check for. * \return 1, if there is content and 0 otherwise. */ extern int pygame_scrap_contains(char *type); #endif /* SCRAP_H */
1
0.871823
1
0.871823
game-dev
MEDIA
0.378716
game-dev
0.503298
1
0.503298
kisence-mian/UnityLockStepDemo
5,639
LockStepDemo/Server/LockStepDemo/Service/Game/Box2D/Dynamics/Controllers/Controller.cs
using System; namespace Box2DX.Dynamics.Controllers { /// <summary> /// A controller edge is used to connect bodies and controllers together /// in a bipartite graph. /// </summary> public class ControllerEdge { public Controller controller; // provides quick access to other end of this edge. public Body body; // the body public ControllerEdge prevBody; // the previous controller edge in the controllers's joint list public ControllerEdge nextBody; // the next controller edge in the controllers's joint list public ControllerEdge prevController; // the previous controller edge in the body's joint list public ControllerEdge nextController; // the next controller edge in the body's joint list } /// <summary> /// Base class for controllers. Controllers are a convience for encapsulating common /// per-step functionality. /// </summary> public abstract class Controller : IDisposable { internal Controller _prev; internal Controller _next; internal World _world; protected ControllerEdge _bodyList; protected int _bodyCount; public Controller() { _bodyList = null; _bodyCount = 0; } public Controller(World world) { _bodyList = null; _bodyCount = 0; _world = world; } public void Dispose() { //Remove attached bodies //Previus implementation: //while (_bodyCount > 0) // RemoveBody(_bodyList.body); Clear(); } /// <summary> /// Controllers override this to implement per-step functionality. /// </summary> public abstract void Step(TimeStep step); /// <summary> /// Controllers override this to provide debug drawing. /// </summary> public virtual void Draw(DebugDraw debugDraw) { } /// <summary> /// Adds a body to the controller list. /// </summary> public void AddBody(Body body) { ControllerEdge edge = new ControllerEdge(); edge.body = body; edge.controller = this; //Add edge to controller list edge.nextBody = _bodyList; edge.prevBody = null; if (_bodyList != null) _bodyList.prevBody = edge; _bodyList = edge; ++_bodyCount; //Add edge to body list edge.nextController = body._controllerList; edge.prevController = null; if (body._controllerList != null) body._controllerList.prevController = edge; body._controllerList = edge; } /// <summary> /// Removes a body from the controller list. /// </summary> public void RemoveBody(Body body) { //Assert that the controller is not empty Box2DXDebug.Assert(_bodyCount > 0); //Find the corresponding edge ControllerEdge edge = _bodyList; while (edge != null && edge.body != body) edge = edge.nextBody; //Assert that we are removing a body that is currently attached to the controller Box2DXDebug.Assert(edge != null); //Remove edge from controller list if (edge.prevBody != null) edge.prevBody.nextBody = edge.nextBody; if (edge.nextBody != null) edge.nextBody.prevBody = edge.prevBody; if (edge == _bodyList) _bodyList = edge.nextBody; --_bodyCount; //Remove edge from body list if (edge.prevController != null) edge.prevController.nextController = edge.nextController; if (edge.nextController != null) edge.nextController.prevController = edge.prevController; if (edge == body._controllerList) body._controllerList = edge.nextController; //Free the edge edge = null; } /// <summary> /// Removes all bodies from the controller list. /// </summary> public void Clear() { #warning "Check this" ControllerEdge current = _bodyList; while (current != null) { ControllerEdge edge = current; //Remove edge from controller list _bodyList = edge.nextBody; //Remove edge from body list if (edge.prevController != null) edge.prevController.nextController = edge.nextController; if (edge.nextController != null) edge.nextController.prevController = edge.prevController; if (edge == edge.body._controllerList) edge.body._controllerList = edge.nextController; //Free the edge //m_world->m_blockAllocator.Free(edge, sizeof(b2ControllerEdge)); } _bodyCount = 0; } /// <summary> /// Get the next body in the world's body list. /// </summary> internal Controller GetNext() { return _next; } /// <summary> /// Get the parent world of this body. /// </summary> internal World GetWorld() { return _world; } /// <summary> /// Get the attached body list /// </summary> internal ControllerEdge GetBodyList() { return _bodyList; } } }
1
0.664863
1
0.664863
game-dev
MEDIA
0.900688
game-dev
0.698119
1
0.698119
Snownee/SnowRealMagic
2,060
src/main/java/snownee/snow/mixin/SpreadableSnowyDirtBlockMixin.java
package snownee.snow.mixin; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Local; import net.minecraft.core.BlockPos; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SpreadingSnowyDirtBlock; import net.minecraft.world.level.block.state.BlockState; import snownee.snow.CoreModule; import snownee.snow.Hooks; import snownee.snow.SnowCommonConfig; import snownee.snow.block.SnowVariant; @Mixin(SpreadingSnowyDirtBlock.class) public abstract class SpreadableSnowyDirtBlockMixin { @WrapOperation( method = "randomTick", at = @At( value = "INVOKE", ordinal = 1, target = "Lnet/minecraft/world/level/block/state/BlockState;is(Lnet/minecraft/world/level/block/Block;)Z")) private boolean srm_isSnowySetting(BlockState blockState, Block block, Operation<Boolean> original) { return Hooks.isSnowySetting(blockState); } @Inject( method = "canBeGrass", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;is(Lnet/minecraft/world/level/block/Block;)Z"), cancellable = true) private static void srm_checkSnowFirst( final BlockState blockState, final LevelReader levelReader, final BlockPos blockPos, final CallbackInfoReturnable<Boolean> cir, @Local(ordinal = 1) BlockPos abovePos, @Local(ordinal = 1) BlockState aboveBlock) { if (aboveBlock.is(CoreModule.SNOWY_SETTING)) { if (aboveBlock.getBlock() instanceof SnowVariant snowVariant) { cir.setReturnValue( SnowCommonConfig.sustainGrassIfLayerMoreThanOne || snowVariant.srm$layers(aboveBlock, levelReader, abovePos) <= 1); } cir.setReturnValue(true); } } }
1
0.854477
1
0.854477
game-dev
MEDIA
0.947042
game-dev
0.952713
1
0.952713
Beta8397/virtual_robot
2,185
Controller/src/virtual_robot/game_elements/classes/Barrier.java
package virtual_robot.game_elements.classes; import javafx.scene.Group; import org.dyn4j.collision.CategoryFilter; import org.dyn4j.dynamics.Body; import org.dyn4j.geometry.MassType; import virtual_robot.controller.Filters; import virtual_robot.controller.GameElementConfig; import virtual_robot.controller.VirtualField; import virtual_robot.controller.VirtualGameElement; import virtual_robot.dyn4j.Dyn4jUtil; import virtual_robot.dyn4j.FixtureData; import virtual_robot.games.FreightFrenzy; @GameElementConfig(name = "Barrier", filename = "barrier", forGame = FreightFrenzy.class, numInstances = 1) public class Barrier extends VirtualGameElement { public static Barrier theBarrier = null; Body barrierBody = null; // Category and filter for collisions public static final long BARRIER_CATEGORY = 1024; public static final CategoryFilter BARRIER_FILTER = new CategoryFilter(BARRIER_CATEGORY, Filters.MASK_ALL & ~Filters.CHASSIS & ~Filters.ARM); public void initialize(){ super.initialize(); } /** * The implementation of updateState for Barrier is simple: just obtain (x, y, headingRadians) * from the physics body, and translate x and y from meters to pixels. * @param millis milliseconds since the previous update */ @Override public void updateState(double millis) { x = barrierBody.getTransform().getTranslationX() * VirtualField.PIXELS_PER_METER; y = barrierBody.getTransform().getTranslationY() * VirtualField.PIXELS_PER_METER; headingRadians = barrierBody.getTransform().getRotationAngle(); } @Override public synchronized void updateDisplay() { super.updateDisplay(); } /** * Set up the dyn4j physics body for the barrier. */ @Override public void setUpBody(){ /* * Use Dyn4jUtil.createBody to create a Body. Infinite mass (i.e., the barrier is fixed in position) */ elementBody = Dyn4jUtil.createBody(displayGroup, this, 0, 0, new FixtureData(BARRIER_FILTER, 1, 0, 0)); barrierBody = elementBody; // Alias for elementBody barrierBody.setMass(MassType.INFINITE); } }
1
0.757666
1
0.757666
game-dev
MEDIA
0.482086
game-dev
0.721212
1
0.721212
AAEmu/AAEmu
1,407
AAEmu.Game/Models/Game/Skills/Effects/SpecialEffects/ManaCost.cs
using AAEmu.Game.Models.Game.Char; using AAEmu.Game.Models.Game.Skills.Static; using AAEmu.Game.Models.Game.Units; namespace AAEmu.Game.Models.Game.Skills.Effects.SpecialEffects; public class ManaCost : SpecialEffectAction { protected override SpecialType SpecialEffectActionType => SpecialType.ManaCost; public override void Execute(BaseUnit caster, SkillCaster casterObj, BaseUnit target, SkillCastTarget targetObj, CastAction castObj, Skill skill, SkillObject skillObject, DateTime time, int value1, int value2, int value3, int value4) { // TODO ... if (caster is Character) { Logger.Debug("Special effects: ManaCost value1 {0}, value2 {1}, value3 {2}, value4 {3}", value1, value2, value3, value4); } if (caster is Character character) { // TODO: Value1 is used by Mana Stars, value2 is used by other skills. They are never used both at once. // I think value1 is fixed, and value2 is based on skill level somehow. var manaCost = character.SkillModifiersCache.ApplyModifiers(skill, SkillAttribute.ManaCost, value1 + (value2) / 6.35); character.ReduceCurrentMp(null, (int)manaCost); character.LastCast = DateTime.UtcNow; character.IsInPostCast = true; // TODO / 10 } } }
1
0.670222
1
0.670222
game-dev
MEDIA
0.991504
game-dev
0.813088
1
0.813088
Genbox/VelcroPhysics
6,841
src/VelcroPhysics.MonoGame.Samples.Demo/Demos/Prefabs/JumpySpider.cs
using Genbox.VelcroPhysics.Dynamics; using Genbox.VelcroPhysics.Dynamics.Joints; using Genbox.VelcroPhysics.Factories; using Genbox.VelcroPhysics.MonoGame.Samples.Demo.MediaSystem; using Genbox.VelcroPhysics.MonoGame.Samples.Demo.MediaSystem.Graphics; using Genbox.VelcroPhysics.Utilities; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Genbox.VelcroPhysics.MonoGame.Samples.Demo.Demos.Prefabs { public class JumpySpider { private const float FlexTime = 5000f; private const float RelaxTime = 5000f; private const float ShoulderFlexed = -1.2f; private const float ShoulderRelaxed = -0.2f; private const float KneeFlexed = -1.4f; private const float KneeRelaxed = -0.4f; private const float SpiderBodyRadius = 0.65f; private readonly Body _circle; private readonly AngleJoint _leftKneeAngleJoint; private readonly Body _leftLower; private readonly AngleJoint _leftShoulderAngleJoint; private readonly Body _leftUpper; private readonly Sprite _lowerLeg; private readonly Vector2 _lowerLegSize = new Vector2(1.8f, 0.3f); private readonly AngleJoint _rightKneeAngleJoint; private readonly Body _rightLower; private readonly AngleJoint _rightShoulderAngleJoint; private readonly Body _rightUpper; private readonly Sprite _torso; private readonly Sprite _upperLeg; private readonly Vector2 _upperLegSize = new Vector2(1.8f, 0.3f); private bool _flexed; private float _timer; public JumpySpider(World world, Vector2 position) { // Body _circle = BodyFactory.CreateCircle(world, SpiderBodyRadius, 0.1f, position); _circle.BodyType = BodyType.Dynamic; // Left upper leg _leftUpper = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X / 2f, 0f)); _leftUpper.BodyType = BodyType.Dynamic; // Left lower leg _leftLower = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X, 0f) - new Vector2(_lowerLegSize.X / 2f, 0f)); _leftLower.BodyType = BodyType.Dynamic; // Right upper leg _rightUpper = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X / 2f, 0f)); _rightUpper.BodyType = BodyType.Dynamic; // Right lower leg _rightLower = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X, 0f) + new Vector2(_lowerLegSize.X / 2f, 0f)); _rightLower.BodyType = BodyType.Dynamic; //Create joints JointFactory.CreateRevoluteJoint(world, _circle, _leftUpper, new Vector2(_upperLegSize.X / 2f, 0f)); _leftShoulderAngleJoint = JointFactory.CreateAngleJoint(world, _circle, _leftUpper); _leftShoulderAngleJoint.MaxImpulse = 3f; JointFactory.CreateRevoluteJoint(world, _circle, _rightUpper, new Vector2(-_upperLegSize.X / 2f, 0f)); _rightShoulderAngleJoint = JointFactory.CreateAngleJoint(world, _circle, _rightUpper); _rightShoulderAngleJoint.MaxImpulse = 3f; JointFactory.CreateRevoluteJoint(world, _leftUpper, _leftLower, new Vector2(_lowerLegSize.X / 2f, 0f)); _leftKneeAngleJoint = JointFactory.CreateAngleJoint(world, _leftUpper, _leftLower); _leftKneeAngleJoint.MaxImpulse = 3f; JointFactory.CreateRevoluteJoint(world, _rightUpper, _rightLower, new Vector2(-_lowerLegSize.X / 2f, 0f)); _rightKneeAngleJoint = JointFactory.CreateAngleJoint(world, _rightUpper, _rightLower); _rightKneeAngleJoint.MaxImpulse = 3; //GFX _torso = new Sprite(Managers.TextureManager.CircleTexture(SpiderBodyRadius, "Square", Colors.Grey, Colors.Gold, Colors.Black, 1f)); _upperLeg = new Sprite(Managers.TextureManager.TextureFromShape(_leftUpper.FixtureList[0].Shape, Colors.Grey, Colors.Black)); _lowerLeg = new Sprite(Managers.TextureManager.TextureFromShape(_leftLower.FixtureList[0].Shape, Colors.Gold, Colors.Black)); _flexed = false; _timer = 0f; _leftShoulderAngleJoint.TargetAngle = ShoulderRelaxed; _leftKneeAngleJoint.TargetAngle = KneeRelaxed; _rightShoulderAngleJoint.TargetAngle = -ShoulderRelaxed; _rightKneeAngleJoint.TargetAngle = -KneeRelaxed; } public void Update(GameTime gameTime) { _timer += gameTime.ElapsedGameTime.Milliseconds; if (_flexed) { if (_timer >= FlexTime) { _timer = 0; _flexed = false; _leftShoulderAngleJoint.TargetAngle = ShoulderRelaxed; _leftKneeAngleJoint.TargetAngle = KneeRelaxed; _rightShoulderAngleJoint.TargetAngle = -ShoulderRelaxed; _rightKneeAngleJoint.TargetAngle = -KneeRelaxed; } } else if (_timer >= RelaxTime) { _timer = 0f; _flexed = true; _leftShoulderAngleJoint.TargetAngle = ShoulderFlexed; _leftKneeAngleJoint.TargetAngle = KneeFlexed; _rightShoulderAngleJoint.TargetAngle = -ShoulderFlexed; _rightKneeAngleJoint.TargetAngle = -KneeFlexed; } } public void Draw(SpriteBatch batch) { batch.Draw(_lowerLeg.Image, ConvertUnits.ToDisplayUnits(_leftLower.Position), null, Color.White, _leftLower.Rotation, _lowerLeg.Origin, 1f, SpriteEffects.None, 0f); batch.Draw(_lowerLeg.Image, ConvertUnits.ToDisplayUnits(_rightLower.Position), null, Color.White, _rightLower.Rotation, _lowerLeg.Origin, 1f, SpriteEffects.None, 0f); batch.Draw(_upperLeg.Image, ConvertUnits.ToDisplayUnits(_leftUpper.Position), null, Color.White, _leftUpper.Rotation, _upperLeg.Origin, 1f, SpriteEffects.None, 0f); batch.Draw(_upperLeg.Image, ConvertUnits.ToDisplayUnits(_rightUpper.Position), null, Color.White, _rightUpper.Rotation, _upperLeg.Origin, 1f, SpriteEffects.None, 0f); batch.Draw(_torso.Image, ConvertUnits.ToDisplayUnits(_circle.Position), null, Color.White, _circle.Rotation, _torso.Origin, 1f, SpriteEffects.None, 0f); } } }
1
0.749219
1
0.749219
game-dev
MEDIA
0.913574
game-dev
0.971067
1
0.971067
milvus-io/milvus
1,057
internal/streamingnode/server/wal/interceptors/timetick/builder.go
package timetick import ( "github.com/milvus-io/milvus/internal/streamingnode/server/resource" "github.com/milvus-io/milvus/internal/streamingnode/server/wal/interceptors" ) var _ interceptors.InterceptorBuilder = (*interceptorBuilder)(nil) // NewInterceptorBuilder creates a new interceptor builder. // 1. Add timetick to all message before append to wal. // 2. Collect timetick info, and generate sync-timetick message to wal. func NewInterceptorBuilder() interceptors.InterceptorBuilder { return &interceptorBuilder{} } // interceptorBuilder is a builder to build timeTickAppendInterceptor. type interceptorBuilder struct{} // Build implements Builder. func (b *interceptorBuilder) Build(param *interceptors.InterceptorBuildParam) interceptors.Interceptor { operator := newTimeTickSyncOperator(param) // initialize operation can be async to avoid block the build operation. resource.Resource().TimeTickInspector().RegisterSyncOperator(operator) return &timeTickAppendInterceptor{ operator: operator, txnManager: param.TxnManager, } }
1
0.914871
1
0.914871
game-dev
MEDIA
0.293383
game-dev
0.770625
1
0.770625
Moppu/SecretOfManaRandomizer
2,843
SoMRandomizer/processing/hacks/openworld/AISwap.cs
using SoMRandomizer.config.settings; using SoMRandomizer.logging; using SoMRandomizer.processing.common; using SoMRandomizer.processing.hacks.common.util; using System; using System.Collections.Generic; namespace SoMRandomizer.processing.hacks.openworld { /// <summary> /// Hack that swaps AI of regular enemies. /// </summary> /// /// <remarks>Author: Moppleton</remarks> public class AISwap : RandoProcessor { protected override string getName() { return "Enemy AI swap"; } protected override bool process(byte[] origRom, byte[] outRom, string seed, RandoSettings settings, RandoContext context) { Random r = context.randomFunctional; if(settings.get(OpenWorldSettings.PROPERTYNAME_AI_RANDO) != "swap") { return false; } List<int> enemyIds = new List<int>(); for(int i=0; i < 84; i++) { // shadow xx if(i != 32 && i != 46 && i != 63) { enemyIds.Add(i); } } for(int i=0; i < 84; i++) { // shadow xx if (i != 32 && i != 46 && i != 63) { // swap pointers int sourceEnemy = enemyIds[r.Next() % enemyIds.Count]; enemyIds.Remove(sourceEnemy); outRom[0x100000 + i * 16 + 9] = origRom[0x100000 + sourceEnemy * 16 + 9]; outRom[0x100000 + i * 16 + 10] = origRom[0x100000 + sourceEnemy * 16 + 10]; if(sourceEnemy == 0x08) { // green drop outRom[0x1055ce] = (byte)i; } if (sourceEnemy == 0x26) { // emberman outRom[0x10712e] = (byte)i; } if (sourceEnemy == 0x27) { // red drop outRom[0x1071df] = (byte)i; } if (sourceEnemy == 0x38) { // blue drop outRom[0x108275] = (byte)i; } if (sourceEnemy == 0x44) { // tsunami outRom[0x108e94] = (byte)i; } Logging.log("Setting AI for " + context.namesOfThings.getOriginalName(NamesOfThings.INDEX_ENEMIES_START + i) + " to " + context.namesOfThings.getOriginalName(NamesOfThings.INDEX_ENEMIES_START + sourceEnemy), "spoiler"); } } return true; } } }
1
0.805986
1
0.805986
game-dev
MEDIA
0.835504
game-dev
0.887824
1
0.887824
Proxmark/proxmark3
2,669
client/cmdlfnexwatch.c
//----------------------------------------------------------------------------- // // This code is licensed to you under the terms of the GNU GPL, version 2 or, // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- // Low frequency Honeywell NexWatch tag commands // PSK1 RF/16, RF/2, 128 bits long (known) //----------------------------------------------------------------------------- #include "cmdlfnexwatch.h" #include <stdio.h> #include <string.h> #include <inttypes.h> #include <stdbool.h> #include "comms.h" #include "ui.h" #include "util.h" #include "graph.h" #include "cmdparser.h" #include "cmddata.h" #include "cmdlf.h" #include "lfdemod.h" static int CmdHelp(const char *Cmd); int CmdPSKNexWatch(const char *Cmd) { if (!PSKDemod("", false)) return 0; uint8_t preamble[28] = {0,0,0,0,0,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; size_t startIdx = 0, size = DemodBufferLen; bool invert = false; if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)){ // if didn't find preamble try again inverting if (!PSKDemod("1", false)) return 0; size = DemodBufferLen; if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)) return 0; invert = true; } if (size != 128) return 0; setDemodBuf(DemodBuffer, size, startIdx+4); setClockGrid(g_DemodClock, g_DemodStartIdx + ((startIdx+4)*g_DemodClock)); startIdx = 8+32; // 8 = preamble, 32 = reserved bits (always 0) //get ID uint32_t ID = 0; for (uint8_t wordIdx=0; wordIdx<4; wordIdx++){ for (uint8_t idx=0; idx<8; idx++){ ID = (ID << 1) | DemodBuffer[startIdx+wordIdx+(idx*4)]; } } //parity check (TBD) //checksum check (TBD) //output PrintAndLog("NexWatch ID: %d", ID); if (invert){ PrintAndLog("Had to Invert - probably NexKey"); for (uint8_t idx=0; idx<size; idx++) DemodBuffer[idx] ^= 1; } CmdPrintDemodBuff("x"); return 1; } //by marshmellow //see ASKDemod for what args are accepted int CmdNexWatchRead(const char *Cmd) { // read lf silently lf_read(true, 10000); // demod and output viking ID return CmdPSKNexWatch(Cmd); } static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, {"demod", CmdPSKNexWatch, 1, "Demodulate a NexWatch tag (nexkey, quadrakey) from the GraphBuffer"}, {"read", CmdNexWatchRead, 0, "Attempt to Read and Extract tag data from the antenna"}, {NULL, NULL, 0, NULL} }; int CmdLFNexWatch(const char *Cmd) { CmdsParse(CommandTable, Cmd); return 0; } int CmdHelp(const char *Cmd) { CmdsHelp(CommandTable); return 0; }
1
0.7125
1
0.7125
game-dev
MEDIA
0.532247
game-dev,cli-devtools
0.626131
1
0.626131
bcoin-org/lcoin
1,172
scripts/dump.js
'use strict'; var fs = require('fs'); var heapdump = require('heapdump'); var MempoolEntry = require('../lib/mempool/mempoolentry'); var Coins = require('../lib/coins/coins'); var TX = require('../lib/primitives/tx'); var CoinView = require('../lib/coins/coinview'); var SNAPSHOT = __dirname + '/../dump.heapsnapshot'; var tx = parseTX('../test/data/tx4.hex'); var raw, coins, entry; function parseTX(file) { var data = fs.readFileSync(__dirname + '/' + file, 'utf8'); var parts = data.trim().split(/\n+/); var raw = parts[0]; var tx = TX.fromRaw(raw.trim(), 'hex'); var view = new CoinView(); var i, prev; for (i = 1; i < parts.length; i++) { raw = parts[i]; prev = TX.fromRaw(raw.trim(), 'hex'); view.addTX(prev, -1); } return { tx: tx, view: view }; } raw = Coins.fromTX(tx.tx, 0).toRaw(); coins = Coins.fromRaw(raw, tx.tx.hash('hex')); entry = MempoolEntry.fromTX(tx.tx, tx.view, 1000000); setInterval(function() { console.log(tx.hash('hex')); console.log(coins.hash); console.log(entry.tx); }, 60 * 1000); setImmediate(function() { heapdump.writeSnapshot(SNAPSHOT, function(err) { if (err) throw err; }); });
1
0.773628
1
0.773628
game-dev
MEDIA
0.234366
game-dev
0.867039
1
0.867039
apache/chemistry-opencmis
12,119
chemistry-opencmis-server/chemistry-opencmis-server-support/src/main/java/org/apache/chemistry/opencmis/server/support/query/AbstractPredicateWalker.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * * Contributors: * Florent Guillaume, Nuxeo */ package org.apache.chemistry.opencmis.server.support.query; import java.util.ArrayList; import java.util.List; import org.antlr.runtime.tree.Tree; import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException; /** * Basic implementation walking a predicate in lexical order. * <p> * The {@code walkXYZ} methods can be overridden to change the walking order. */ public abstract class AbstractPredicateWalker implements PredicateWalker { @Override public Boolean walkPredicate(Tree node) { switch (node.getType()) { case CmisQlStrictLexer.NOT: return walkNot(node, node.getChild(0)); case CmisQlStrictLexer.AND: return walkAnd(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.OR: return walkOr(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.EQ: return walkEquals(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.NEQ: return walkNotEquals(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.GT: return walkGreaterThan(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.GTEQ: return walkGreaterOrEquals(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.LT: return walkLessThan(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.LTEQ: return walkLessOrEquals(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.IN: return walkIn(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.NOT_IN: return walkNotIn(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.IN_ANY: return walkInAny(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.NOT_IN_ANY: return walkNotInAny(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.EQ_ANY: return walkEqAny(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.IS_NULL: return walkIsNull(node, node.getChild(0)); case CmisQlStrictLexer.IS_NOT_NULL: return walkIsNotNull(node, node.getChild(0)); case CmisQlStrictLexer.LIKE: return walkLike(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.NOT_LIKE: return walkNotLike(node, node.getChild(0), node.getChild(1)); case CmisQlStrictLexer.CONTAINS: if (node.getChildCount() == 1) { return walkContains(node, null, node.getChild(0)); } else { return walkContains(node, node.getChild(0), node.getChild(1)); } case CmisQlStrictLexer.IN_FOLDER: if (node.getChildCount() == 1) { return walkInFolder(node, null, node.getChild(0)); } else { return walkInFolder(node, node.getChild(0), node.getChild(1)); } case CmisQlStrictLexer.IN_TREE: if (node.getChildCount() == 1) { return walkInTree(node, null, node.getChild(0)); } else { return walkInTree(node, node.getChild(0), node.getChild(1)); } case CmisQlStrictLexer.BOOL_LIT: walkBoolean(node); return false; case CmisQlStrictLexer.NUM_LIT: walkNumber(node); return false; case CmisQlStrictLexer.STRING_LIT: walkString(node); return false; case CmisQlStrictLexer.TIME_LIT: walkTimestamp(node); return false; case CmisQlStrictLexer.IN_LIST: walkList(node); return false; case CmisQlStrictLexer.COL: walkCol(node); return false; case CmisQlStrictLexer.ID: walkId(node); return false; case CmisQlStrictLexer.SCORE: return walkScore(node); default: return walkOtherPredicate(node); } } /** For extensibility. */ protected Boolean walkOtherPredicate(Tree node) { throw new CmisRuntimeException("Unknown node type: " + node.getType() + " (" + node.getText() + ")"); } @Override public Boolean walkNot(Tree opNode, Tree node) { walkPredicate(node); return false; } @Override public Boolean walkAnd(Tree opNode, Tree leftNode, Tree rightNode) { walkPredicate(leftNode); walkPredicate(rightNode); return false; } @Override public Boolean walkOr(Tree opNode, Tree leftNode, Tree rightNode) { walkPredicate(leftNode); walkPredicate(rightNode); return false; } @Override public Object walkExpr(Tree node) { switch (node.getType()) { case CmisQlStrictLexer.BOOL_LIT: return walkBoolean(node); case CmisQlStrictLexer.NUM_LIT: return walkNumber(node); case CmisQlStrictLexer.STRING_LIT: return walkString(node); case CmisQlStrictLexer.TIME_LIT: return walkTimestamp(node); case CmisQlStrictLexer.IN_LIST: return walkList(node); case CmisQlStrictLexer.COL: return walkCol(node); case CmisQlStrictLexer.ID: return walkId(node); default: return walkOtherExpr(node); } } public Boolean walkSearchExpr(Tree node) { switch (node.getType()) { case TextSearchLexer.TEXT_AND: return walkTextAnd(node); case TextSearchLexer.TEXT_OR: return walkTextOr(node); case TextSearchLexer.TEXT_MINUS: return walkTextMinus(node); case TextSearchLexer.TEXT_SEARCH_WORD_LIT: return walkTextWord(node); case TextSearchLexer.TEXT_SEARCH_PHRASE_STRING_LIT: return walkTextPhrase(node); default: walkOtherExpr(node); return null; } } /** For extensibility. */ protected Object walkOtherExpr(Tree node) { throw new CmisRuntimeException("Unknown node type: " + node.getType() + " (" + node.getText() + ")"); } @Override public Boolean walkEquals(Tree opNode, Tree leftNode, Tree rightNode) { walkExpr(leftNode); walkExpr(rightNode); return false; } @Override public Boolean walkNotEquals(Tree opNode, Tree leftNode, Tree rightNode) { walkExpr(leftNode); walkExpr(rightNode); return false; } @Override public Boolean walkGreaterThan(Tree opNode, Tree leftNode, Tree rightNode) { walkExpr(leftNode); walkExpr(rightNode); return false; } @Override public Boolean walkGreaterOrEquals(Tree opNode, Tree leftNode, Tree rightNode) { walkExpr(leftNode); walkExpr(rightNode); return false; } @Override public Boolean walkLessThan(Tree opNode, Tree leftNode, Tree rightNode) { walkExpr(leftNode); walkExpr(rightNode); return false; } @Override public Boolean walkLessOrEquals(Tree opNode, Tree leftNode, Tree rightNode) { walkExpr(leftNode); walkExpr(rightNode); return false; } @Override public Boolean walkIn(Tree opNode, Tree colNode, Tree listNode) { walkExpr(colNode); walkExpr(listNode); return false; } @Override public Boolean walkNotIn(Tree opNode, Tree colNode, Tree listNode) { walkExpr(colNode); walkExpr(listNode); return false; } @Override public Boolean walkInAny(Tree opNode, Tree colNode, Tree listNode) { walkExpr(colNode); walkExpr(listNode); return false; } @Override public Boolean walkNotInAny(Tree opNode, Tree colNode, Tree listNode) { walkExpr(colNode); walkExpr(listNode); return false; } @Override public Boolean walkEqAny(Tree opNode, Tree literalNode, Tree colNode) { walkExpr(literalNode); walkExpr(colNode); return false; } @Override public Boolean walkIsNull(Tree opNode, Tree colNode) { walkExpr(colNode); return false; } @Override public Boolean walkIsNotNull(Tree opNode, Tree colNode) { walkExpr(colNode); return false; } @Override public Boolean walkLike(Tree opNode, Tree colNode, Tree stringNode) { walkExpr(colNode); walkExpr(stringNode); return false; } @Override public Boolean walkNotLike(Tree opNode, Tree colNode, Tree stringNode) { walkExpr(colNode); walkExpr(stringNode); return false; } @Override public Boolean walkContains(Tree opNode, Tree qualNode, Tree queryNode) { if (qualNode != null) { return walkSearchExpr(qualNode); } return walkSearchExpr(queryNode); } @Override public Boolean walkInFolder(Tree opNode, Tree qualNode, Tree paramNode) { if (qualNode != null) { walkExpr(qualNode); } walkExpr(paramNode); return false; } @Override public Boolean walkInTree(Tree opNode, Tree qualNode, Tree paramNode) { if (qualNode != null) { walkExpr(qualNode); } walkExpr(paramNode); return false; } @Override public Object walkList(Tree node) { int n = node.getChildCount(); List<Object> res = new ArrayList<Object>(n); for (int i = 0; i < n; i++) { res.add(walkExpr(node.getChild(i))); } return res; } @Override public Object walkBoolean(Tree node) { String s = node.getText(); return Boolean.valueOf(s); } @Override public Object walkNumber(Tree node) { String s = node.getText(); if (s.contains(".") || s.contains("e") || s.contains("E")) { return Double.valueOf(s); } else { return Long.valueOf(s); } } @Override public Object walkString(Tree node) { String s = node.getText(); s = s.substring(1, s.length() - 1); s = s.replace("''", "'"); // unescape quotes return s; } @Override public Object walkTimestamp(Tree node) { String s = node.getText(); s = s.substring(s.indexOf('\'') + 1, s.length() - 1); return CalendarHelper.fromString(s); } @Override public Object walkCol(Tree node) { return null; } @Override public Object walkId(Tree node) { return null; } protected Boolean walkTextAnd(Tree node) { return null; } protected Boolean walkTextOr(Tree node) { return null; } protected Boolean walkTextMinus(Tree node) { return null; } protected Boolean walkTextWord(Tree node) { return null; } protected Boolean walkTextPhrase(Tree node) { return null; } protected Boolean walkScore(Tree node) { return false; } }
1
0.741163
1
0.741163
game-dev
MEDIA
0.199966
game-dev
0.871297
1
0.871297
stgatilov/darkmod_src
10,404
game/ai/States/ExamineRopeState.cpp
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod 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. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) ******************************************************************************/ #include "precompiled.h" #pragma hdrstop #include "ExamineRopeState.h" //#include "../Memory.h" #include "../Tasks/MoveToPositionTask.h" #include "../Tasks/IdleAnimationTask.h" // grayman #3857 namespace ai { ExamineRopeState::ExamineRopeState() {} ExamineRopeState::ExamineRopeState(idAFEntity_Generic* rope, idVec3 point) { _rope = rope; _point = point; } // Get the name of this state const idStr& ExamineRopeState::GetName() const { static idStr _name(STATE_EXAMINE_ROPE); return _name; } // grayman #3559 - make part of WrapUp() visible to outside world void ExamineRopeState::Cleanup(idAI* owner) { owner->m_ExaminingRope = false; owner->GetMemory().stopExaminingRope = false; owner->GetMemory().latchPickedPocket = false; // grayman #3559 } // Wrap up and end state void ExamineRopeState::Wrapup(idAI* owner) { Cleanup(owner); owner->GetMind()->EndState(); } void ExamineRopeState::Init(idAI* owner) { //Memory& memory = owner->GetMemory(); State::Init(owner); DM_LOG(LC_AI, LT_INFO)LOGSTRING("ExamineRopeState initialized.\r"); assert(owner); idAFEntity_Generic* rope = _rope.GetEntity(); if ( rope == NULL ) // this could happen if the player frobs the rope arrow { Wrapup(owner); return; } // stop if something more important has happened if (owner->GetMemory().stopExaminingRope) { Wrapup(owner); return; } owner->actionSubsystem->ClearTasks(); // grayman #3857 if (owner->m_ReactingToPickedPocket) // grayman #3559 { owner->GetMemory().stopReactingToPickedPocket = true; } idVec3 goalDirection; idVec3 ownerOrg = owner->GetPhysics()->GetOrigin(); int areaNum = owner->PointReachableAreaNum(ownerOrg, 1.0f); idEntity* bindMaster = rope->GetBindMaster(); goalDirection = ownerOrg - _point; // fallback - use a direction from the point to the AI if ( bindMaster != NULL ) // the bindMaster is the stuck rope arrow { goalDirection = rope->GetPhysics()->GetOrigin() - bindMaster->GetPhysics()->GetOrigin(); // preferred direction } goalDirection.z = 0; // ignore vertical component goalDirection.NormalizeFast(); idVec3 size(16, 16, 82); idAAS* aas = owner->GetAAS(); if (aas) { size = aas->GetSettings()->boundingBoxes[0][1]; } // Move away from _point and perform a trace down to detect the ground. float standOff = 4*size.x; // any closer than this makes the "look up" animation look a bit strained (ouch!) idVec3 startPoint = _point + goalDirection * standOff; idVec3 bottomPoint = startPoint; bottomPoint.z -= 1000; idVec3 tp1 = startPoint; trace_t result; bool tp1Found = false; if ( gameLocal.clip.TracePoint(result, startPoint, bottomPoint, MASK_OPAQUE, NULL) ) { // Found the floor. tp1.z = result.endpos.z + 1; // move the target point to just above the floor tp1Found = true; } // Reverse direction and see if the floor is closer in that direction startPoint = _point - goalDirection * standOff; idVec3 tp2 = startPoint; bool tp2Found = false; bottomPoint = startPoint; bottomPoint.z -= 1000; if (gameLocal.clip.TracePoint(result, startPoint, bottomPoint, MASK_OPAQUE, NULL)) { // Found the floor. tp2.z = result.endpos.z + 1; // move the target point to just above the floor tp2Found = true; } bool use1 = false; if ( tp1Found ) { if ( tp2Found ) { float tp1ZDelta = abs(ownerOrg.z - tp1.z); float tp2ZDelta = abs(ownerOrg.z - tp2.z); use1 = ( tp1ZDelta <= tp2ZDelta ); } else { use1 = true; } } _examineSpot = _point; // if no spots are found for the AI to stage an examination, search around _point int targetAreaNum; aasPath_t path; bool pathToGoal = false; // whether there's a path to the target point near the rope if ( use1 ) { // Is there a path to tp1? targetAreaNum = owner->PointReachableAreaNum(tp1, 1.0f); if ( owner->PathToGoal(path, areaNum, ownerOrg, targetAreaNum, tp1, owner) ) { pathToGoal = true; _examineSpot = tp1; } } if ( !pathToGoal ) { if ( tp2Found ) { // Is there a path to tp2? targetAreaNum = owner->PointReachableAreaNum(tp2, 1.0f); if ( owner->PathToGoal(path, areaNum, ownerOrg, targetAreaNum, tp2, owner) ) { pathToGoal = true; _examineSpot = tp2; } } } if ( pathToGoal ) { owner->actionSubsystem->ClearTasks(); owner->movementSubsystem->ClearTasks(); // if AI is sitting, he has to stand before sending him on his way owner->movementSubsystem->PushTask(TaskPtr(new MoveToPositionTask(_examineSpot,idMath::INFINITY,5))); if (owner->GetMoveType() == MOVETYPE_SIT) { _examineRopeState = EStateSitting; } else { _examineRopeState = EStateStarting; } _waitEndTime = gameLocal.time + 1000; // allow time for move to begin return; } // There's no path to the goal. Go straight to searching. _waitEndTime = 0; _examineRopeState = EStateFinal; } // Gets called each time the mind is thinking void ExamineRopeState::Think(idAI* owner) { // It's possible that during the examination of a rope, the player // frobs back the rope arrow. You have to account for that. Memory& memory = owner->GetMemory(); idAFEntity_Generic* rope = _rope.GetEntity(); if ( rope == NULL ) // this could happen if the player frobs the rope arrow { Wrapup(owner); return; } // check if something happened to abort the examination if (owner->GetMemory().stopExaminingRope) { Wrapup(owner); return; } owner->PerformVisualScan(); // Let the AI check its senses if (owner->AI_AlertLevel >= owner->thresh_5) // finished if alert level is too high { Wrapup(owner); return; } if ((owner->m_HandlingDoor) || (owner->m_HandlingElevator)) { return; // we're handling a door or elevator, so delay the examination } switch (_examineRopeState) { case EStateSitting: if (gameLocal.time >= _waitEndTime) { if (owner->AI_MOVE_DONE && (owner->GetMoveType() != MOVETYPE_GET_UP)) // standing yet? { owner->movementSubsystem->PushTask(TaskPtr(new MoveToPositionTask(_examineSpot,idMath::INFINITY,5))); _examineRopeState = EStateStarting; _waitEndTime = gameLocal.time + 1000; // allow time for move to begin } } break; case EStateStarting: if (owner->AI_FORWARD || (gameLocal.time >= _waitEndTime)) { _examineRopeState = EStateApproaching; } break; case EStateApproaching: // Walking toward the rope if (!owner->m_ReactingToPickedPocket) // grayman #3559 { if (owner->AI_MOVE_DONE) { owner->TurnToward(_point); memory.latchPickedPocket = true; // grayman #3559 - delay any picked pocket reaction _examineRopeState = EStateTurningToward; _waitEndTime = gameLocal.time + 750; // allow time for turn to complete } } break; case EStateTurningToward: if (gameLocal.time >= _waitEndTime) { StartExaminingTop(owner); // AI looks at top of rope _examineRopeState = EStateExamineTop; _waitEndTime = gameLocal.time + 3000; } break; case EStateExamineTop: if (gameLocal.time >= _waitEndTime) { StartExaminingBottom(owner); // AI looks at bottom of rope _waitEndTime = gameLocal.time + 3000; _examineRopeState = EStateExamineBottom; } break; case EStateExamineBottom: if (gameLocal.time >= _waitEndTime) { _waitEndTime = gameLocal.time + 1000; _examineRopeState = EStateFinal; } break; case EStateFinal: if (gameLocal.time >= _waitEndTime) { // Set up search if latched if (owner->m_LatchedSearch) { owner->m_LatchedSearch = false; // A rope discovery raises the alert level to a max // of thresh_4-0.1. So if the alert level is still below // thresh_4, set up the search parameters for a new search. // If the alert level is thresh_4 or more, you're in // Agitated Searching, which means something else happened // to put you there, and you already have search parameters. if (owner->AI_AlertLevel < owner->thresh_4) { // grayman #3857 - move alert setup into one method SetUpSearchData(EAlertTypeRope, _examineSpot, rope, false, 0); // grayman #3857 } } Wrapup(owner); return; } break; default: break; } } void ExamineRopeState::StartExaminingTop(idAI* owner) { // Look at the top of the rope owner->movementSubsystem->ClearTasks(); owner->StopMove(MOVE_STATUS_DONE); owner->Event_LookAtPosition(_rope.GetEntity()->GetPhysics()->GetOrigin(), 3.0f); } void ExamineRopeState::StartExaminingBottom(idAI* owner) { // Look at the bottom of the rope // owner->movementSubsystem->ClearTasks(); // owner->StopMove(MOVE_STATUS_DONE); idMat3 axis; idVec3 org; jointHandle_t joint = _rope.GetEntity()->GetAnimator()->GetJointHandle( "bone92" ); _rope.GetEntity()->GetJointWorldTransform( joint, gameLocal.time, org, axis ); owner->Event_LookAtPosition(org, 3.0f); } void ExamineRopeState::Save(idSaveGame* savefile) const { State::Save(savefile); _rope.Save(savefile); savefile->WriteInt(_waitEndTime); savefile->WriteInt(static_cast<int>(_examineRopeState)); savefile->WriteVec3(_examineSpot); savefile->WriteVec3(_point); } void ExamineRopeState::Restore(idRestoreGame* savefile) { State::Restore(savefile); _rope.Restore(savefile); savefile->ReadInt(_waitEndTime); int temp; savefile->ReadInt(temp); _examineRopeState = static_cast<EExamineRopeState>(temp); savefile->ReadVec3(_examineSpot); savefile->ReadVec3(_point); } StatePtr ExamineRopeState::CreateInstance() { return StatePtr(new ExamineRopeState); } // Register this state with the StateLibrary StateLibrary::Registrar examineRopeStateRegistrar( STATE_EXAMINE_ROPE, // Task Name StateLibrary::CreateInstanceFunc(&ExamineRopeState::CreateInstance) // Instance creation callback ); } // namespace ai
1
0.989262
1
0.989262
game-dev
MEDIA
0.975145
game-dev
0.990473
1
0.990473
PaperMC/Paper
5,948
paper-server/src/test/java/org/bukkit/craftbukkit/inventory/YamlSerializationTest.java
package org.bukkit.craftbukkit.inventory; import io.papermc.paper.datacomponent.DataComponentTypes; import io.papermc.paper.datacomponent.item.ItemEnchantments; import io.papermc.paper.datacomponent.item.Tool; import io.papermc.paper.datacomponent.item.WrittenBookContent; import io.papermc.paper.registry.RegistryKey; import io.papermc.paper.registry.keys.BlockTypeKeys; import io.papermc.paper.registry.set.RegistrySet; import net.kyori.adventure.text.Component; import net.kyori.adventure.util.TriState; import net.minecraft.world.level.storage.DataVersion; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.support.environment.AllFeatures; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.spongepowered.configurate.ConfigurateException; import org.spongepowered.configurate.ConfigurationNode; import org.spongepowered.configurate.yaml.YamlConfigurationLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @AllFeatures public class YamlSerializationTest { @Test void testDataComponents() { final ItemStack item = ItemStack.of(Material.WRITTEN_BOOK); item.setData(DataComponentTypes.WRITTEN_BOOK_CONTENT, WrittenBookContent.writtenBookContent("Jon", "The Destroyer").addPage(Component.text("hi")).build()); item.setData(DataComponentTypes.ENCHANTMENTS, ItemEnchantments.itemEnchantments().add(Enchantment.AQUA_AFFINITY, 1).add(Enchantment.DENSITY, 2).build()); item.setData(DataComponentTypes.GLIDER); item.setData(DataComponentTypes.TOOL, Tool.tool().addRule(Tool.rule(RegistrySet.keySet(RegistryKey.BLOCK, BlockTypeKeys.ACACIA_DOOR), 1f, TriState.TRUE))); testYamlRoundTrip(item, """ item: ==: org.bukkit.inventory.ItemStack DataVersion: %s id: minecraft:written_book count: 1 components: minecraft:written_book_content: '{author:"The Destroyer",pages:[{raw:"hi"}],title:{raw:"Jon"}}' minecraft:glider: '{}' minecraft:enchantments: '{"minecraft:aqua_affinity":1,"minecraft:density":2}' minecraft:tool: '{rules:[{blocks:"minecraft:acacia_door",correct_for_drops:1b,speed:1.0f}]}' schema_version: 1 """.formatted(Bukkit.getUnsafe().getDataVersion())); } @Test void testItemMeta() { final ItemStack item = ItemStack.of(Material.WRITTEN_BOOK); item.editMeta(BookMeta.class, (meta) -> { meta.setAuthor("The Destroyer"); meta.setTitle("Jon"); meta.addPages(Component.text("hi")); meta.addEnchant(Enchantment.AQUA_AFFINITY, 1, false); meta.addEnchant(Enchantment.DENSITY, 2, false); }); testYamlRoundTrip(item, """ item: ==: org.bukkit.inventory.ItemStack DataVersion: %s id: minecraft:written_book count: 1 components: minecraft:written_book_content: '{author:"The Destroyer",pages:[{raw:"hi"}],title:{raw:"Jon"}}' minecraft:enchantments: '{"minecraft:aqua_affinity":1,"minecraft:density":2}' schema_version: 1 """.formatted(Bukkit.getUnsafe().getDataVersion())); } @Test void testUpgrading() { // 4189 = 1.21.4 testYamlUpgrade(""" item: ==: org.bukkit.inventory.ItemStack DataVersion: 4189 id: minecraft:diamond_hoe count: 1 components: minecraft:unbreakable: '{show_in_tooltip:false}' minecraft:enchantments: '{levels:{"minecraft:sharpness":2},show_in_tooltip:false}' schema_version: 1 """, """ item: ==: org.bukkit.inventory.ItemStack DataVersion: %s id: minecraft:diamond_hoe count: 1 components: minecraft:unbreakable: '{}' minecraft:tooltip_display: '{hidden_components:["minecraft:enchantments","minecraft:unbreakable"]}' minecraft:enchantments: '{"minecraft:sharpness":2}' schema_version: 1 """.formatted(Bukkit.getUnsafe().getDataVersion())); } private void testYamlRoundTrip(ItemStack itemStack, String expectedYamlString) { final YamlConfiguration out = new YamlConfiguration(); out.set("item", itemStack); final String yamlString = out.saveToString(); assertEquals(expectedYamlString, yamlString); final YamlConfiguration in = new YamlConfiguration(); try { in.loadFromString(yamlString); } catch (final InvalidConfigurationException e) { throw new RuntimeException(e); } assertEquals(itemStack, in.getItemStack("item")); } private void testYamlUpgrade(String oldYamlString, String expectedYamlString) { final YamlConfiguration config = new YamlConfiguration(); try { config.loadFromString(oldYamlString); } catch (final InvalidConfigurationException e) { throw new RuntimeException(e); } try { final ConfigurationNode expectedNode = YamlConfigurationLoader.builder().buildAndLoadString(expectedYamlString); final ConfigurationNode upgradedNode = YamlConfigurationLoader.builder().buildAndLoadString(config.saveToString()); Assertions.assertEquals(expectedNode, upgradedNode); } catch (ConfigurateException e) { Assertions.fail("Failed to read yaml", e); } } }
1
0.856081
1
0.856081
game-dev
MEDIA
0.9939
game-dev
0.840172
1
0.840172
organization/Kookie
1,118
app/src/main/kotlin/be/zvz/kookie/block/BlockIdentifierFlattened.kt
/** * * _ __ _ _ * | |/ /___ ___ | | _(_) ___ * | ' // _ \ / _ \| |/ / |/ _ \ * | . \ (_) | (_) | <| | __/ * |_|\_\___/ \___/|_|\_\_|\___| * * A server software for Minecraft: Bedrock Edition * * Copyright (C) 2021 organization Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. */ package be.zvz.kookie.block class BlockIdentifierFlattened @JvmOverloads constructor( blockId: Int, val additionalIds: List<Int>, variant: Int, itemId: Int? = null, tileClass: String? = null ) : BlockIdentifier(blockId, variant, itemId, tileClass) { init { if (additionalIds.isEmpty()) { throw IllegalArgumentException("Expected at least 1 additional ID") } } fun getSecondId(): Int = additionalIds[0] override fun getAllBlockIds(): List<Int> = mutableListOf(blockId).apply { additionalIds.forEach(this::add) }.toList() }
1
0.677169
1
0.677169
game-dev
MEDIA
0.839374
game-dev
0.622038
1
0.622038
lethal-guitar/RigelEngine
4,445
src/game_logic/interactive/item_container.hpp
/* Copyright (C) 2016, Nikolai Wuttke. All rights reserved. * * 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/>. */ #pragma once #include "base/spatial_types.hpp" #include "base/warnings.hpp" RIGEL_DISABLE_WARNINGS #include <entityx/entityx.h> RIGEL_RESTORE_WARNINGS #include <memory> #include <vector> namespace rigel { struct IGameServiceProvider; } namespace rigel::engine { class CollisionChecker; } namespace rigel::game_logic { struct GlobalState; } namespace rigel::game_logic::events { struct ShootableKilled; } namespace rigel::game_logic { struct GlobalDependencies; /** Provides type erasure for component classes */ class ComponentHolder { public: template <typename T> explicit ComponentHolder(T component_) : mpSelf(std::make_unique<Model<T>>(std::move(component_))) { } ComponentHolder(const ComponentHolder& other) : mpSelf(other.mpSelf->clone()) { } ComponentHolder& operator=(const ComponentHolder& other) { auto copy = other; std::swap(mpSelf, copy.mpSelf); return *this; } ComponentHolder(ComponentHolder&&) = default; ComponentHolder& operator=(ComponentHolder&&) = default; void assignToEntity(entityx::Entity entity) const { mpSelf->assignToEntity(entity); } private: struct Concept { virtual ~Concept() = default; virtual std::unique_ptr<Concept> clone() const = 0; virtual void assignToEntity(entityx::Entity entity) const = 0; }; template <typename T> struct Model : public Concept { explicit Model(T data_) : mData(std::move(data_)) { } std::unique_ptr<Concept> clone() const override { return std::make_unique<Model>(mData); } void assignToEntity(entityx::Entity entity) const override { entity.assign<T>(mData); } T mData; }; std::unique_ptr<Concept> mpSelf; }; namespace components { struct ItemBounceEffect { explicit ItemBounceEffect(const float fallVelocity) : mFallVelocity(fallVelocity) { } int mFramesElapsed = 1; float mFallVelocity = 0.0f; }; struct ItemContainer { enum class ReleaseStyle : std::uint8_t { Default, ItemBox, ItemBoxNoBounce, NuclearWasteBarrel }; std::vector<ComponentHolder> mContainedComponents; ReleaseStyle mStyle = ReleaseStyle::Default; std::int8_t mFramesElapsed = 0; bool mHasBeenShot = false; template <typename TComponent, typename... TArgs> void assign(TArgs&&... components) { mContainedComponents.emplace_back( TComponent{std::forward<TArgs>(components)...}); } }; } // namespace components class ItemContainerSystem : public entityx::Receiver<ItemContainerSystem> { public: ItemContainerSystem( entityx::EntityManager* pEntityManager, const engine::CollisionChecker* pCollisionChecker, entityx::EventManager& events); void update(entityx::EntityManager& es); void updateItemBounce(entityx::EntityManager& es); void receive(const events::ShootableKilled& event); private: entityx::EntityManager* mpEntityManager; const engine::CollisionChecker* mpCollisionChecker; }; namespace behaviors { class NapalmBomb { public: void update( GlobalDependencies& dependencies, GlobalState& state, bool isOnScreen, entityx::Entity entity); void onKilled( GlobalDependencies& dependencies, GlobalState& state, const base::Vec2f& inflictorVelocity, entityx::Entity entity); enum class State { Ticking, SpawningFires }; State mState = State::Ticking; int mFramesElapsed = 0; bool mCanSpawnLeft = true; bool mCanSpawnRight = true; private: void explode(GlobalDependencies& dependencies, entityx::Entity entity); void spawnFires(GlobalDependencies& d, const base::Vec2& bombPosition, int step); }; } // namespace behaviors } // namespace rigel::game_logic
1
0.840564
1
0.840564
game-dev
MEDIA
0.944741
game-dev
0.606612
1
0.606612
gamingdotme/opensource-casino-v10
2,381
casino/app/Games/SweetBonanzaXmas/PragmaticLib/Multiple.php
<?php namespace VanguardLTE\Games\SweetBonanzaXmas\PragmaticLib; class Multiple { public static function getBonanzaMultiple($slotArea, $gameSettings, $currentLog){ $tmp = explode(';', $gameSettings['prm']); $tmp = explode('~', $tmp[0]); $prm = $tmp[0]; // символ множителя $prmMultipliers = explode(',',$tmp[1]); // массив возможных значений множителя // перестроить игровое поле на катушки $reels = 6; $tmpSlotArea = array_chunk($slotArea, $reels); $currentSlotArea = []; $k = 0; while ($k < $reels) { // перестроить со строк на ряды $i = 0; while ($i < $gameSettings['sh']) { $currentSlotArea[$k][] = $tmpSlotArea[$i][$k]; $i++; } $k++; } $prmReady = []; // пройти по всем катушкам с конца, и присвоить множители, в лог писать какой множитель от какой катушки foreach ($currentSlotArea as $reelKey => $reel) { foreach (array_reverse($reel) as $symbolKey => $symbol) { if ($symbol == $prm){ $symbolsCount = $gameSettings['sh'] - 1; // массивы с 0 начинаются. Чтобы узнать сколько должно быть в катушке символов $prmSymbol = $reelKey + ($reels * ($symbolsCount - $symbolKey)); // вычисляем поозицию. Номер катушки, прибавляем к позиции катушке с начала $prmReady[] = [ 'Symbol' => $prm, 'Position' => $prmSymbol, 'Multiplier' => self::getMultiplier($currentLog,$prmMultipliers,$reelKey), 'Reel' => $reelKey ]; } } } if ($prmReady) return $prmReady; else return false; } private static function getMultiplier($currentLog, $prmMultipliers, $reelKey){ if ($currentLog && array_key_exists('Multipliers', $currentLog)){ foreach ($currentLog['Multipliers'] as $logMultiplier) { if ($logMultiplier['Reel'] == $reelKey){ $multiplier = $logMultiplier['Multiplier']; } } } if (isset($multiplier)) return $multiplier; else $multiplier = $prmMultipliers[array_rand($prmMultipliers)]; return $multiplier; } }
1
0.65699
1
0.65699
game-dev
MEDIA
0.529957
game-dev
0.618356
1
0.618356
EXL/NXEngine
1,739
ai/first_cave/first_cave.cpp
#include "../stdai.h" #include "../weed/weed.fdh" // for ai_critter #include "first_cave.fdh" INITFUNC(AIRoutines) { ONTICK(OBJ_BAT_BLUE, ai_bat_up_down); ONTICK(OBJ_CRITTER_HOPPING_BLUE, ai_critter); ONTICK(OBJ_HERMIT_GUNSMITH, ai_hermit_gunsmith); ONTICK(OBJ_DOOR_ENEMY, ai_door_enemy); } /* void c------------------------------() {} */ void ai_bat_up_down(Object *o) { switch(o->state) { case 0: o->ymark = o->y; o->timer = random(0, 50); o->state = 1; case 1: if (!o->timer--) { o->state = 2; o->yinertia = 0x300; } break; case 2: { if (o->y >= o->ymark) o->yinertia -= 0x10; else o->yinertia += 0x10; LIMITY(0x300); } break; } FACEPLAYER; ANIMATE(1, 2, 4); } /* void c------------------------------() {} */ void ai_hermit_gunsmith(Object *o) { if (o->state == 0) { o->SnapToGround(); o->state = 1; } if (o->dir == RIGHT) { ai_zzzz_spawner(o); } else { o->frame = 0; randblink(o, 1, 8); } } void ai_door_enemy(Object *o) { enum { INIT = 0, WAIT, OPENEYE, CLOSEEYE }; switch(o->state) { case 0: o->state = WAIT; case WAIT: { o->frame = 0; if (pdistlx(0x8000) && pdistly(0x8000)) { o->animtimer = 0; o->state = OPENEYE; } } break; case OPENEYE: { if (++o->animtimer > 2) { o->animtimer = 0; o->frame++; } if (o->frame > 2) { o->frame = 2; if (!pdistlx(0x8000) || !pdistly(0x8000)) { o->state = CLOSEEYE; o->animtimer = 0; } } } break; case CLOSEEYE: { if (++o->animtimer > 2) { o->animtimer = 0; if (--o->frame <= 0) { o->frame = 0; o->state = WAIT; } } } break; } }
1
0.849276
1
0.849276
game-dev
MEDIA
0.702267
game-dev
0.882801
1
0.882801
congcoi123/tenio
4,903
examples/src/main/java/com/tenio/examples/example4/configuration/ParamLoader.java
package com.tenio.examples.example4.configuration; import com.tenio.common.utility.MathUtility; import java.io.IOException; /** * Class to configuration. */ public final class ParamLoader extends FileLoaderBase { private static ParamLoader instance = null; static { try { instance = new ParamLoader(); } catch (IOException e) { e.printStackTrace(); } } public int NUM_AGENTS; public int NUM_OBSTACLES; public float MIN_OBSTACLE_RADIUS; public float MAX_OBSTACLE_RADIUS; // number of horizontal cells used for spatial partitioning public int NUM_CELLS_X; // number of vertical cells used for spatial partitioning public int NUM_CELLS_Y; // how many samples the smoother will use to average a value public int NUM_SAMPLES_FOR_SMOOTHING; // used to tweak the combined steering force (simply altering the // MaxSteeringForce // will NOT work! This tweaker affects all the steering force multipliers too) public float STEERING_FORCE_TWEAKER; public float MAX_STEERING_FORCE; public float MAX_SPEED; public float VEHICLE_MASS; public float VEHICLE_SCALE; public float MAX_TURN_RATE_PER_SECOND; public float SEPARATION_WEIGHT; public float ALIGNMENT_WEIGHT; public float COHESION_WEIGHT; public float OBSTACLE_AVOIDANCE_WEIGHT; public float WALL_AVOIDANCE_WEIGHT; public float WANDER_WEIGHT; public float SEEK_WEIGHT; public float FLEE_WEIGHT; public float ARRIVE_WEIGHT; public float PURSUIT_WEIGHT; public float OFFSET_PURSUIT_WEIGHT; public float INTERPOSE_WEIGHT; public float HIDE_WEIGHT; public float EVADE_WEIGHT; public float FOLLOW_PATH_WEIGHT; // how close a neighbor must be before an agent perceives it (considers it // to be within its neighborhood) public float VIEW_DISTANCE; // used in obstacle avoidance public float MIN_DETECTION_BOX_LENGTH; // used in wall avoidance public float WALL_DETECTION_FEELER_LENGTH; // these are the probabilities that a steering behavior will be used // when the prioritized dither calculate method is used public float PR_WALL_AVOIDANCE; public float PR_OBSTACLE_AVOIDANCE; public float PR_SEPARATION; public float PR_ALIGNMENT; public float PR_COHESION; public float PR_WANDER; public float PR_SEEK; public float PR_FLEE; public float PR_EVADE; public float PR_HIDE; public float PR_ARRIVE; private ParamLoader() throws IOException { super("src/main/resources/params.ini"); NUM_AGENTS = getNextParameterInt(); NUM_OBSTACLES = getNextParameterInt(); MIN_OBSTACLE_RADIUS = getNextParameterFloat(); MAX_OBSTACLE_RADIUS = getNextParameterFloat(); NUM_CELLS_X = getNextParameterInt(); NUM_CELLS_Y = getNextParameterInt(); NUM_SAMPLES_FOR_SMOOTHING = getNextParameterInt(); STEERING_FORCE_TWEAKER = getNextParameterFloat(); MAX_STEERING_FORCE = getNextParameterFloat() * STEERING_FORCE_TWEAKER; MAX_SPEED = getNextParameterFloat(); VEHICLE_MASS = getNextParameterFloat(); VEHICLE_SCALE = getNextParameterFloat(); SEPARATION_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; ALIGNMENT_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; COHESION_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; OBSTACLE_AVOIDANCE_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; WALL_AVOIDANCE_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; WANDER_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; SEEK_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; FLEE_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; ARRIVE_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; PURSUIT_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; OFFSET_PURSUIT_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; INTERPOSE_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; HIDE_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; EVADE_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; FOLLOW_PATH_WEIGHT = getNextParameterFloat() * STEERING_FORCE_TWEAKER; VIEW_DISTANCE = getNextParameterFloat(); MIN_DETECTION_BOX_LENGTH = getNextParameterFloat(); WALL_DETECTION_FEELER_LENGTH = getNextParameterFloat(); PR_WALL_AVOIDANCE = getNextParameterFloat(); PR_OBSTACLE_AVOIDANCE = getNextParameterFloat(); PR_SEPARATION = getNextParameterFloat(); PR_ALIGNMENT = getNextParameterFloat(); PR_COHESION = getNextParameterFloat(); PR_WANDER = getNextParameterFloat(); PR_SEEK = getNextParameterFloat(); PR_FLEE = getNextParameterFloat(); PR_EVADE = getNextParameterFloat(); PR_HIDE = getNextParameterFloat(); PR_ARRIVE = getNextParameterFloat(); MAX_TURN_RATE_PER_SECOND = MathUtility.PI; } public static ParamLoader getInstance() { return instance; } }
1
0.514772
1
0.514772
game-dev
MEDIA
0.956193
game-dev
0.870814
1
0.870814
dzoba/gptrpg
1,120
ui-admin/src/App.js
import React, { useEffect, useRef } from "react"; import Phaser from 'phaser'; import './App.css'; import GridEngine from "grid-engine"; import preload from './preload'; import create from './create'; import update from './update'; function App() { const gameRef = useRef(null); useEffect(() => { if (gameRef.current === null) { gameRef.current = new Phaser.Game({ title: "GPTRPG", render: { antialias: false, }, type: Phaser.AUTO, physics: { default: "arcade", }, plugins: { scene: [ { key: "gridEngine", plugin: GridEngine, mapping: "gridEngine", }, ], }, scene: { preload, create, update, }, scale: { width: window.innerWidth, height: window.innerHeight, autoCenter: Phaser.Scale.CENTER_BOTH, }, parent: "game", backgroundColor: "#48C4F8", }); } }, []); return <div id="game"></div>; } export default App;
1
0.831354
1
0.831354
game-dev
MEDIA
0.775791
game-dev
0.951595
1
0.951595
shaovie/gserver
5,040
world/src/monster/spawn_monster.cpp
#include "spawn_monster.h" #include "scene_config.h" #include "monster_template.h" #include "monster_obj.h" #include "monster_cfg.h" #include "scene_monster_cfg.h" #include "sys_log.h" #include "clsid.h" #include "zhuzai_fen_shen_mst.h" #include "ghz_wang_zuo_mst.h" #include "ghz_shou_wei_mst.h" #include "global_param_cfg.h" #include "guild_shen_shou_mst.h" #include "guild_scp_mst.h" #include "tu_teng_mst.h" #include "group_monster.h" static ilog_obj *s_log = sys_log::instance()->get_ilog("mst"); static ilog_obj *e_log = err_log::instance()->get_ilog("mst"); ilist<pair_t<int> > spawn_monster::spawn_mst_list; int spawn_monster::spawn_all_scene_monster() { ilist<int> &slist = scene_config::instance()->scene_list(); ilist_node<int> *itor = slist.head(); for (; itor != NULL; itor = itor->next_) { int scene_cid = itor->value_; if (clsid::is_tui_tu_scp_scene(scene_cid) || clsid::is_scp_scene(scene_cid) || global_param_cfg::ghz_scene_cid == scene_cid) continue; spawn_monster::spawn_scene_monster(scene_cid, scene_cid, 0, NULL, NULL); } return 0; } int spawn_monster::spawn_scene_monster(const int scene_id, const int scene_cid, const int idx, ilist<pair_t<int> > *mst_list, ilist<int> *exclude_mst_list) { if (!scene_monster_cfg::instance()->have_monster(scene_cid)) return 0; short x_len = scene_config::instance()->x_len(scene_cid); short y_len = scene_config::instance()->y_len(scene_cid); for (short y = 0; y < y_len; ++y) { for (short x = 0; x < x_len; ++x) { char cv = scene_config::instance()->coord_value(scene_cid, x, y); if (cv == -1) { e_log->wning("get scene %d coord value = -1 where spawan monster!", scene_cid); continue; } if (cv < 10 || (idx != 0 && idx != cv)) continue; int mst_cid = 0; int dir = DIR_XX; if (scene_monster_cfg::instance()->get_monster_info(scene_cid, cv, mst_cid, dir) == -1) continue; if (exclude_mst_list != NULL && exclude_mst_list->find(mst_cid)) continue; int mst_id = spawn_monster::spawn_one(mst_cid, 0, scene_id, scene_cid, dir, x, y); if (mst_list != NULL && mst_id > 0) mst_list->push_back(pair_t<int>(mst_id, mst_cid)); } } return 0; } int spawn_monster::spawn_one(const int mst_cid, const int delay, const int scene_id, const int scene_cid, const char dir, const short x, const short y) { monster_obj *mst = NULL; const monster_cfg_obj *mco = monster_cfg::instance()->get_monster_cfg_obj(mst_cid); if (mco == NULL) { e_log->wning("not found monster %d in monster cfg when spawn monster in %d", mst_cid, scene_cid); return -1; } if (mco->mst_type_ == MST_COMMON) mst = new fighting_monster_obj(); else if (mco->mst_type_ == MST_ZHU_ZAI_JING_XIANG) mst = new zhuzai_fen_shen_mst(); else if (mco->mst_type_ == MST_GHZ_WANG_ZUO) mst = new ghz_wang_zuo_mst(); else if (mco->mst_type_ == MST_GHZ_SHOU_WEI) mst = new ghz_shou_wei_mst(); else if (mco->mst_type_ == MST_GUILD_SHEN_SHOU) mst = new guild_shen_shou_mst(); else if (mco->mst_type_ == MST_GUILD_SCP_NO_HATE_MST) mst = new guild_scp_no_hate_mst(); else if (mco->mst_type_ == MST_GUILD_SCP_HAD_HATE_MST) mst = new guild_scp_had_hate_mst(); else if (mco->mst_type_ == MST_TU_TENG_TO_PLAYER) mst = new player_tu_teng_mst(); else if (mco->mst_type_ == MST_XSZC_MAIN) mst = new xszc_main_mst(mco->param_); else if (mco->mst_type_ == MST_XSZC_BARRACK) mst = new xszc_barrack_mst(mco->param_); else if (mco->mst_type_ == MST_XSZC_DEFENDER) mst = new xszc_defender_mst(mco->param_); else if (mco->mst_type_ == MST_XSZC_ARM) mst = new xszc_arm_mst(mco->param_); if (mst == NULL) { e_log->error("unsupportable monster type %d!", mco->mst_type_); return -1; } if (mst->init(mst_cid, scene_id, scene_cid, dir, x, y) != 0 || mst->do_activate(delay) != 0) { e_log->error("spawn monster %d failed!", mst_cid); delete mst; return -1; } return mst->id(); }
1
0.791266
1
0.791266
game-dev
MEDIA
0.901729
game-dev
0.852912
1
0.852912
JoeyDeVries/Lucid
4,861
Includes/Box2D/Common/b2BlockAllocator.cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Common/b2BlockAllocator.h> #include <limits.h> #include <string.h> #include <stddef.h> int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = { 16, // 0 32, // 1 64, // 2 96, // 3 128, // 4 160, // 5 192, // 6 224, // 7 256, // 8 320, // 9 384, // 10 448, // 11 512, // 12 640, // 13 }; uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1]; bool b2BlockAllocator::s_blockSizeLookupInitialized; struct b2Chunk { int32 blockSize; b2Block* blocks; }; struct b2Block { b2Block* next; }; b2BlockAllocator::b2BlockAllocator() { b2Assert(b2_blockSizes < UCHAR_MAX); m_chunkSpace = b2_chunkArrayIncrement; m_chunkCount = 0; m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); memset(m_freeLists, 0, sizeof(m_freeLists)); if (s_blockSizeLookupInitialized == false) { int32 j = 0; for (int32 i = 1; i <= b2_maxBlockSize; ++i) { b2Assert(j < b2_blockSizes); if (i <= s_blockSizes[j]) { s_blockSizeLookup[i] = (uint8)j; } else { ++j; s_blockSizeLookup[i] = (uint8)j; } } s_blockSizeLookupInitialized = true; } } b2BlockAllocator::~b2BlockAllocator() { for (int32 i = 0; i < m_chunkCount; ++i) { b2Free(m_chunks[i].blocks); } b2Free(m_chunks); } void* b2BlockAllocator::Allocate(int32 size) { if (size == 0) return NULL; b2Assert(0 < size); if (size > b2_maxBlockSize) { return b2Alloc(size); } int32 index = s_blockSizeLookup[size]; b2Assert(0 <= index && index < b2_blockSizes); if (m_freeLists[index]) { b2Block* block = m_freeLists[index]; m_freeLists[index] = block->next; return block; } else { if (m_chunkCount == m_chunkSpace) { b2Chunk* oldChunks = m_chunks; m_chunkSpace += b2_chunkArrayIncrement; m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); b2Free(oldChunks); } b2Chunk* chunk = m_chunks + m_chunkCount; chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); #if defined(_DEBUG) memset(chunk->blocks, 0xcd, b2_chunkSize); #endif int32 blockSize = s_blockSizes[index]; chunk->blockSize = blockSize; int32 blockCount = b2_chunkSize / blockSize; b2Assert(blockCount * blockSize <= b2_chunkSize); for (int32 i = 0; i < blockCount - 1; ++i) { b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); block->next = next; } b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); last->next = NULL; m_freeLists[index] = chunk->blocks->next; ++m_chunkCount; return chunk->blocks; } } void b2BlockAllocator::Free(void* p, int32 size) { if (size == 0) { return; } b2Assert(0 < size); if (size > b2_maxBlockSize) { b2Free(p); return; } int32 index = s_blockSizeLookup[size]; b2Assert(0 <= index && index < b2_blockSizes); #ifdef _DEBUG // Verify the memory address and size is valid. int32 blockSize = s_blockSizes[index]; bool found = false; for (int32 i = 0; i < m_chunkCount; ++i) { b2Chunk* chunk = m_chunks + i; if (chunk->blockSize != blockSize) { b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); } else { if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) { found = true; } } } b2Assert(found); memset(p, 0xfd, blockSize); #endif b2Block* block = (b2Block*)p; block->next = m_freeLists[index]; m_freeLists[index] = block; } void b2BlockAllocator::Clear() { for (int32 i = 0; i < m_chunkCount; ++i) { b2Free(m_chunks[i].blocks); } m_chunkCount = 0; memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); memset(m_freeLists, 0, sizeof(m_freeLists)); }
1
0.782629
1
0.782629
game-dev
MEDIA
0.310295
game-dev
0.858788
1
0.858788
jakevn/MassiveNet
1,605
Unity3d.Examples/Assets/MassiveNet/Examples/NetSimple/Client/Scripts/ScopeHandler.cs
// MIT License (MIT) - Copyright (c) 2014 jakevn - Please see included LICENSE file using MassiveNet; using UnityEngine; namespace Massive.Examples.NetSimple { public class ScopeHandler : MonoBehaviour { private NetView view; private Renderer[] renderers; private Collider[] colliders; private AudioSource[] audioSources; private MonoBehaviour[] monoBehaviours; void Start() { view = GetComponent<NetView>(); view.Scope.OnOut += DisableAll; view.Scope.OnIn += EnableAll; CacheAllComponents(); } public void CacheAllComponents() { renderers = GetComponentsInChildren<Renderer>(); colliders = GetComponentsInChildren<Collider>(); audioSources = GetComponentsInChildren<AudioSource>(); monoBehaviours = GetComponents<MonoBehaviour>(); } public void DisableAll() { ChangeScope(false); } public void EnableAll() { ChangeScope(true); } private void ChangeScope(bool on) { for (int i = 0; i < renderers.Length; i++) { renderers[i].enabled = on; } for (int i = 0; i < colliders.Length; i++) { colliders[i].enabled = on; } for (int i = 0; i < audioSources.Length; i++) { audioSources[i].enabled = on; } for (int i = 0; i < monoBehaviours.Length; i++) { monoBehaviours[i].enabled = on; } } } }
1
0.643975
1
0.643975
game-dev
MEDIA
0.740162
game-dev
0.902499
1
0.902499
LofizKittyCat/GradleMCPBase
27,245
src/main/resources/assets/minecraft/optifine/lang/zh_TW.lang
# Contributors of Traditional Chinese localization # # Degh_Cilon_ From WAWCraft 2016-02-18 ---- 2017-11-19 # Shujinko_kun From MCHK 2016-02-25 ---- 2016-03-27 # NatsuArashi (crowdin MC_PR) 2016-03-03 ---- 2018-06-18 # pan93412 (crowdin pan93412) 2018-08-23 ---- 2018-08-23 # NatsuArashi (crowdin MC_PR) ---- 2018-10-29 ##-------------- zh_TW --------------- # General of.general.ambiguous=模糊 of.general.custom=自訂 of.general.from=來自 of.general.id=Id of.general.restart=重新啟動 of.general.smart=智慧 # Keys of.key.zoom=縮放 # Message of.message.aa.shaders1=反鋸齒與光影不相容。 of.message.aa.shaders2=請關閉光影來啟用這個選項。 of.message.af.shaders1=各向異性過濾與光影不相容。 of.message.af.shaders2=請關閉光影來啟用這個選項。 of.message.fr.shaders1=快速繪製與光影不相容。 of.message.fr.shaders2=請關閉光影來啟用這個選項。 of.message.an.shaders1=3D 立體與光影不相容。 of.message.an.shaders2=請關閉光影來啟用這個選項。 of.message.shaders.aa1=光影與反鋸齒不相容。 of.message.shaders.aa2=請把 品質 -> 反鋸齒 選項設定為 關閉 並重啟你的遊戲。 of.message.shaders.af1=光影與各向異性過濾不相容。 of.message.shaders.af2=請把 品質 -> 各向異性過濾 選項設定為 關閉。 of.message.shaders.fr1=光影與快速繪製不相容。 of.message.shaders.fr2=請把 效能 -> 快速繪製 選項設定為 關閉。 of.message.shaders.an1=光影與 3D 立體不相容。 of.message.shaders.an2=請把 其他 -> 3D 立體 選項設定為 關閉。 of.message.shaders.nv1=這個光影需要較新的 OptiFine 版本: %s of.message.shaders.nv2=你確定要繼續嗎? of.message.newVersion=新的 §eOptiFine§f 版本已可供使用: §e%s§f of.message.java64Bit=你可以安裝 §e64 位元 Java§f 來提升效能。 of.message.openglError=§eOpenGL 錯誤§f: %s (%s) of.message.shaders.loading=正在載入光影: %s of.message.other.reset=確定要將所有顯示設定重設至預設值嗎? of.message.loadingVisibleChunks=正在載入可見區塊 # Skin customization of.options.skinCustomisation.ofCape=OptiFine 披風... of.options.capeOF.openEditor=開啟披風編輯器 of.options.capeOF.reloadCape=重新載入披風 of.options.capeOF.copyEditorLink=將連結複製至剪貼簿 # Video settings options.graphics.tooltip.1=畫面品質 options.graphics.tooltip.2= 流暢 - 低畫質,較流暢 options.graphics.tooltip.3= 精緻 - 高畫質,較慢 options.graphics.tooltip.4=改變雲、樹葉、水、 options.graphics.tooltip.5=陰影與草地側面的外觀。 of.options.renderDistance.tiny=最近 of.options.renderDistance.short=近 of.options.renderDistance.normal=中等 of.options.renderDistance.far=遠 of.options.renderDistance.extreme=超遠 of.options.renderDistance.insane=病態 of.options.renderDistance.ludicrous=荒唐 options.renderDistance.tooltip.1=顯示距離 options.renderDistance.tooltip.2= 2 最近 - 32m(最快) options.renderDistance.tooltip.3= 8 中等 - 128m(正常) options.renderDistance.tooltip.4= 16 遠 - 256m(較慢) options.renderDistance.tooltip.5= 32 超遠 - 512m(最慢!)非常消耗資源! options.renderDistance.tooltip.6= 48 病態 - 768m,需要分配 2G 的記憶體 options.renderDistance.tooltip.7= 64 荒唐 - 1024m,需要分配 3G 的記憶體 options.renderDistance.tooltip.8=16 以上的視野值只在本機世界有效。 options.ao.tooltip.1=柔和光源 options.ao.tooltip.2= 關閉 - 無柔和光源(較快) options.ao.tooltip.3= 最小 - 簡單柔和光源(較慢) options.ao.tooltip.4= 最大 - 複雜柔和光源(最慢) options.framerateLimit.tooltip.1=最大 FPS options.framerateLimit.tooltip.2= 垂直同步 - 受限於螢幕 FPS (60,30,20) options.framerateLimit.tooltip.3= 5-255 - 可變 options.framerateLimit.tooltip.4= 無限制 - 無限制(最快) options.framerateLimit.tooltip.5=即使未達 FPS 上限 options.framerateLimit.tooltip.6=該限制仍會影響 FPS。 of.options.framerateLimit.vsync=垂直同步 of.options.AO_LEVEL=柔和光源 of.options.AO_LEVEL.tooltip.1=柔和光源 of.options.AO_LEVEL.tooltip.2= 關閉 - 沒有陰影 of.options.AO_LEVEL.tooltip.3= 50%% - 較亮的陰影 of.options.AO_LEVEL.tooltip.4= 100%% - 較暗的陰影 options.viewBobbing.tooltip.1=更加真實的移動。 options.viewBobbing.tooltip.2=當使用多精度材質時,關閉它以取得更佳效果。 options.guiScale.tooltip.1=介面大小 options.guiScale.tooltip.2= 自動 - 最大尺寸 options.guiScale.tooltip.3= 小,中,大 - 1x 到 3x options.guiScale.tooltip.4= 4x-10x - 僅適用於 4K 解析度 options.guiScale.tooltip.5=奇數值的放大倍數(1x, 3x, 5x...等)與 Unicode 不相容。 options.guiScale.tooltip.6=較小的介面或許會更流暢。 options.vbo=使用 VBOs options.vbo.tooltip.1=啟用緩衝區頂點物件(VBOs) options.vbo.tooltip.2=使用一種常見的替代繪製模型 options.vbo.tooltip.3=比預設繪製快 (5-10%%)。 options.gamma.tooltip.1=增加較暗物體的亮度 options.gamma.tooltip.2= 幽暗 - 標準亮度 options.gamma.tooltip.3= 1-99%% - 可變亮度 options.gamma.tooltip.4= 明亮 - 最大亮度 options.gamma.tooltip.5=此選項不會改變 options.gamma.tooltip.6=全黑物體的亮度。 options.anaglyph.tooltip.1=3D 立體 options.anaglyph.tooltip.2=給予兩眼不同的顏色以 options.anaglyph.tooltip.3=達成 3D 立體的效果。 options.anaglyph.tooltip.4=需要使用紅藍眼鏡進行觀看。 options.attackIndicator.tooltip.1=設定攻擊指示計的位置 options.attackIndicator.tooltip.2= 十字準星 - 十字準星下方 options.attackIndicator.tooltip.3= 快捷欄 - 快捷欄旁邊 options.attackIndicator.tooltip.4= 關閉 - 無攻擊指示計 options.attackIndicator.tooltip.5=攻擊指示計顯示當前裝備 options.attackIndicator.tooltip.6=的攻擊威力 of.options.ALTERNATE_BLOCKS=方塊替換 of.options.ALTERNATE_BLOCKS.tooltip.1=方塊替換 of.options.ALTERNATE_BLOCKS.tooltip.2=為一些方塊使用備用的方塊模型。 of.options.ALTERNATE_BLOCKS.tooltip.3=取決於選用的資源包。 of.options.FOG_FANCY=迷霧 of.options.FOG_FANCY.tooltip.1=迷霧類型 of.options.FOG_FANCY.tooltip.2= 流暢 - 較流暢的迷霧 of.options.FOG_FANCY.tooltip.3= 精緻 - 較慢的迷霧,視覺效果較佳 of.options.FOG_FANCY.tooltip.4= 關閉 - 無迷霧,最快 of.options.FOG_FANCY.tooltip.5=精緻的迷霧只有當顯卡 of.options.FOG_FANCY.tooltip.6=支援時才可使用。 of.options.FOG_START=迷霧出現距離 of.options.FOG_START.tooltip.1=迷霧出現距離 of.options.FOG_START.tooltip.2= 0.2 - 迷霧出現於玩家周圍 of.options.FOG_START.tooltip.3= 0.8 - 迷霧出現於離玩家較遠的地方 of.options.FOG_START.tooltip.4=此選項通常不會影響效能。 of.options.CHUNK_LOADING=區塊載入 of.options.CHUNK_LOADING.tooltip.1=區塊載入 of.options.CHUNK_LOADING.tooltip.2= 預設 - 當載入區塊時 FPS 不穩定 of.options.CHUNK_LOADING.tooltip.3= 柔和化 - 穩定 FPS of.options.CHUNK_LOADING.tooltip.4= 多核心 - 穩定 FPS,三倍的世界載入速度 of.options.CHUNK_LOADING.tooltip.5=柔和化和多核心可消除由區塊 of.options.CHUNK_LOADING.tooltip.6=載入引起的延遲和卡頓。 of.options.CHUNK_LOADING.tooltip.7=多核心可以令世界載入速度提升三倍 of.options.CHUNK_LOADING.tooltip.8=並通過使用多個 CPU 核心來提升 FPS。 of.options.chunkLoading.smooth=柔和 of.options.chunkLoading.multiCore=多核心 of.options.shaders=光影... of.options.shadersTitle=光影 of.options.shaders.packNone=關閉 of.options.shaders.packDefault=(內建) of.options.shaders.ANTIALIASING=反鋸齒 of.options.shaders.ANTIALIASING.tooltip.1=反鋸齒 of.options.shaders.ANTIALIASING.tooltip.2= 關閉 - (預設)停用反鋸齒(較快) of.options.shaders.ANTIALIASING.tooltip.3= FXAA 2x, 4x - 對線和邊緣反鋸齒處理(較慢) of.options.shaders.ANTIALIASING.tooltip.4=FXAA 是一種平滑鋸齒線和鮮明的色彩過渡的 of.options.shaders.ANTIALIASING.tooltip.5=後處理特效。 of.options.shaders.ANTIALIASING.tooltip.6=它不僅快於傳統的反鋸齒處理, of.options.shaders.ANTIALIASING.tooltip.7=同時也與光影和快速繪製相容。 of.options.shaders.NORMAL_MAP=法線貼圖 of.options.shaders.NORMAL_MAP.tooltip.1=法線貼圖 of.options.shaders.NORMAL_MAP.tooltip.2= 開啟 - (預設)啟用法線貼圖 of.options.shaders.NORMAL_MAP.tooltip.3= 關閉 - 停用法線貼圖 of.options.shaders.NORMAL_MAP.tooltip.4=光影包可以使用法線貼圖以在 of.options.shaders.NORMAL_MAP.tooltip.5=平面的模型表面模擬立體幾何結構。 of.options.shaders.NORMAL_MAP.tooltip.6=法線貼圖材質一般由 of.options.shaders.NORMAL_MAP.tooltip.7=目前的資源包提供。 of.options.shaders.SPECULAR_MAP=鏡面貼圖 of.options.shaders.SPECULAR_MAP.tooltip.1=鏡面貼圖 of.options.shaders.SPECULAR_MAP.tooltip.2= 開啟 - (預設)啟用鏡面貼圖 of.options.shaders.SPECULAR_MAP.tooltip.3= 關閉 - 停用鏡面貼圖 of.options.shaders.SPECULAR_MAP.tooltip.4=光影包可以使用鏡面貼圖 of.options.shaders.SPECULAR_MAP.tooltip.5=來模擬特殊的反射效果。 of.options.shaders.SPECULAR_MAP.tooltip.6=鏡面貼圖材質一般由 of.options.shaders.SPECULAR_MAP.tooltip.7=目前的資源包提供。 of.options.shaders.RENDER_RES_MUL=繪製品質 of.options.shaders.RENDER_RES_MUL.tooltip.1=繪製品質 of.options.shaders.RENDER_RES_MUL.tooltip.2= 0.5x - 低(最快) of.options.shaders.RENDER_RES_MUL.tooltip.3= 1x - 標準(預設) of.options.shaders.RENDER_RES_MUL.tooltip.4= 2x - 高(最慢) of.options.shaders.RENDER_RES_MUL.tooltip.5=繪製品質控制光影包所 of.options.shaders.RENDER_RES_MUL.tooltip.6=繪製的材質尺寸。 of.options.shaders.RENDER_RES_MUL.tooltip.7=較低的值較有利於 4K 顯示。 of.options.shaders.RENDER_RES_MUL.tooltip.8=較高的值用於反鋸齒過濾採樣。 of.options.shaders.SHADOW_RES_MUL=陰影品質 of.options.shaders.SHADOW_RES_MUL.tooltip.1=陰影品質 of.options.shaders.SHADOW_RES_MUL.tooltip.2= 0.5x - 低(最快) of.options.shaders.SHADOW_RES_MUL.tooltip.3= 1x - 標準(預設) of.options.shaders.SHADOW_RES_MUL.tooltip.4= 2x - 高(最慢) of.options.shaders.SHADOW_RES_MUL.tooltip.5=陰影品質控制光影包使用的 of.options.shaders.SHADOW_RES_MUL.tooltip.6=陰影映射貼圖的大小。 of.options.shaders.SHADOW_RES_MUL.tooltip.7=較低的值 = 不精確的、粗糙的陰影。 of.options.shaders.SHADOW_RES_MUL.tooltip.8=較高的值 = 精緻的、更佳的陰影。 of.options.shaders.HAND_DEPTH_MUL=手部深度 of.options.shaders.HAND_DEPTH_MUL.tooltip.1=手部深度 of.options.shaders.HAND_DEPTH_MUL.tooltip.2= 0.5x - 手與鏡頭相距較近 of.options.shaders.HAND_DEPTH_MUL.tooltip.3= 1x - (預設) of.options.shaders.HAND_DEPTH_MUL.tooltip.4= 2x - 手與鏡頭相距較遠 of.options.shaders.HAND_DEPTH_MUL.tooltip.5=手部深度控制手持的物品與 of.options.shaders.HAND_DEPTH_MUL.tooltip.6=鏡頭的距離。 of.options.shaders.HAND_DEPTH_MUL.tooltip.7=此選項對於使用模糊景深的光影包 of.options.shaders.HAND_DEPTH_MUL.tooltip.8=應該會改變手持物品的模糊程度。 of.options.shaders.CLOUD_SHADOW=雲影 of.options.shaders.OLD_HAND_LIGHT=經典手持光源 of.options.shaders.OLD_HAND_LIGHT.tooltip.1=經典手持光源 of.options.shaders.OLD_HAND_LIGHT.tooltip.2= 預設 - 由光影包控制 of.options.shaders.OLD_HAND_LIGHT.tooltip.3= 開啟 - 使用經典手持光源 of.options.shaders.OLD_HAND_LIGHT.tooltip.4= 關閉 - 使用新式手持光源 of.options.shaders.OLD_HAND_LIGHT.tooltip.5=經典手持光源允許只能辨識主手 of.options.shaders.OLD_HAND_LIGHT.tooltip.6=發光物品的光影包也能夠 of.options.shaders.OLD_HAND_LIGHT.tooltip.7=作用於副手。 of.options.shaders.OLD_LIGHTING=經典光源 of.options.shaders.OLD_LIGHTING.tooltip.1=經典光源 of.options.shaders.OLD_LIGHTING.tooltip.2= 預設 - 由光影包控制 of.options.shaders.OLD_LIGHTING.tooltip.3= 開啟 - 使用經典光源 of.options.shaders.OLD_LIGHTING.tooltip.4= 關閉 - 不使用經典光源 of.options.shaders.OLD_LIGHTING.tooltip.5=使用經典光源時則採用原版的固定照明。 of.options.shaders.OLD_LIGHTING.tooltip.6=在這種情況下,方塊各面的照明會始終如一。 of.options.shaders.OLD_LIGHTING.tooltip.7=使用陰影的光影包通常會提供 of.options.shaders.OLD_LIGHTING.tooltip.8=更好的、取決於太陽位置的光源。 of.options.shaders.DOWNLOAD=光影下載 of.options.shaders.DOWNLOAD.tooltip.1=下載光影 of.options.shaders.DOWNLOAD.tooltip.2= of.options.shaders.DOWNLOAD.tooltip.3=在瀏覽器中打開光影包頁面。 of.options.shaders.DOWNLOAD.tooltip.4=將已下載完成的光影置於「光影資料夾」中, of.options.shaders.DOWNLOAD.tooltip.5=它們將出現在已安裝的光影列表裡。 of.options.shaders.SHADER_PACK=光影包資料夾 of.options.shaders.shadersFolder=光影資料夾 of.options.shaders.shaderOptions=光影設定... of.options.shaderOptionsTitle=光影設定 of.options.quality=品質... of.options.qualityTitle=品質設定 of.options.details=細節... of.options.detailsTitle=細節設定 of.options.performance=效能... of.options.performanceTitle=效能設定 of.options.animations=動畫... of.options.animationsTitle=動畫設定 of.options.other=其他... of.options.otherTitle=其他設定 of.options.other.reset=重設視訊設定... of.shaders.profile=設定檔 # Quality of.options.mipmap.bilinear=雙線性 of.options.mipmap.linear=線性 of.options.mipmap.nearest=最近 of.options.mipmap.trilinear=三線性 options.mipmapLevels.tooltip.1=將材質柔和化以使遠處的物體 options.mipmapLevels.tooltip.2=更好看的視覺效果。 options.mipmapLevels.tooltip.3= 關閉 - 無柔和化 options.mipmapLevels.tooltip.4= 1 - 最小柔和化 options.mipmapLevels.tooltip.5= 4 - 最大柔和化 options.mipmapLevels.tooltip.6=此選項通常不影響效能。 of.options.MIPMAP_TYPE=多精度材質類型 of.options.MIPMAP_TYPE.tooltip.1=將材質柔和化以使遠處的物體 of.options.MIPMAP_TYPE.tooltip.2=更好看的視覺效果。 of.options.MIPMAP_TYPE.tooltip.3= 最近 - 粗糙柔和化(最快) of.options.MIPMAP_TYPE.tooltip.4= 線性 - 正常柔和化 of.options.MIPMAP_TYPE.tooltip.5= 雙線性 - 精細柔和化 of.options.MIPMAP_TYPE.tooltip.6= 三線性 - 最佳柔和化(最慢) of.options.AA_LEVEL=反鋸齒 of.options.AA_LEVEL.tooltip.1=反鋸齒 of.options.AA_LEVEL.tooltip.2= 關閉 - (預設)無反鋸齒(較快) of.options.AA_LEVEL.tooltip.3= 2-16 - 對線與邊緣進行反鋸齒處理(較慢) of.options.AA_LEVEL.tooltip.4=反鋸齒對鋸齒線和鮮明的色彩過渡 of.options.AA_LEVEL.tooltip.5=進行平滑處理。 of.options.AA_LEVEL.tooltip.6=啟用它可能會大幅降低 FPS。 of.options.AA_LEVEL.tooltip.7=並非所有等級都顯卡都支援。 of.options.AA_LEVEL.tooltip.8=重啟後生效! of.options.AF_LEVEL=各向異性過濾 of.options.AF_LEVEL.tooltip.1=各向異性過濾 of.options.AF_LEVEL.tooltip.2= 關閉 - (預設)標準材質細節(較快) of.options.AF_LEVEL.tooltip.3= 2-16 - 為多級材質過濾後的材質提供精細細節(較慢) of.options.AF_LEVEL.tooltip.4=各向異性過濾還原了經多次 of.options.AF_LEVEL.tooltip.5=材質過濾後的材質細節。 of.options.AF_LEVEL.tooltip.6=啟用它可能會大幅降低 FPS。 of.options.CLEAR_WATER=清澈水體 of.options.CLEAR_WATER.tooltip.1=清澈水體 of.options.CLEAR_WATER.tooltip.2= 開啟 - 清澈,透明水體 of.options.CLEAR_WATER.tooltip.3= 關閉 - 預設水體 of.options.RANDOM_ENTITIES=隨機實體材質 of.options.RANDOM_ENTITIES.tooltip.1=隨機實體材質 of.options.RANDOM_ENTITIES.tooltip.2= 關閉 - 關閉隨機實體材質,較快 of.options.RANDOM_ENTITIES.tooltip.3= 開啟 - 隨機實體材質,較慢 of.options.RANDOM_ENTITIES.tooltip.4=遊戲中的實體使用隨機的相應貼圖。 of.options.RANDOM_ENTITIES.tooltip.5=需要資源包內有多個實體貼圖。 of.options.BETTER_GRASS=更好的草地 of.options.BETTER_GRASS.tooltip.1=更好的草地 of.options.BETTER_GRASS.tooltip.2= 關閉 - 預設草地材質,較快 of.options.BETTER_GRASS.tooltip.3= 流暢 - 草方塊側面全部使用草地材質,較慢 of.options.BETTER_GRASS.tooltip.4= 精緻 - 草方塊側面材質動態化,最慢 of.options.BETTER_SNOW=更好的雪地 of.options.BETTER_SNOW.tooltip.1=更好的雪地 of.options.BETTER_SNOW.tooltip.2= 關閉 - 預設的雪地,較快 of.options.BETTER_SNOW.tooltip.3= 開啟 - 更好的雪地,較慢 of.options.BETTER_SNOW.tooltip.4=在透明方塊(如柵欄、草叢)與雪 of.options.BETTER_SNOW.tooltip.5=接壤時在其下方顯示雪。 of.options.CUSTOM_FONTS=自訂字體 of.options.CUSTOM_FONTS.tooltip.1=自訂字體 of.options.CUSTOM_FONTS.tooltip.2= 開啟 - 使用自訂字體(預設),較慢 of.options.CUSTOM_FONTS.tooltip.3= 關閉 - 使用預設字體,較快 of.options.CUSTOM_FONTS.tooltip.4=自訂字體一般由 of.options.CUSTOM_FONTS.tooltip.5=目前的資源包提供。 of.options.CUSTOM_COLORS=自訂色彩 of.options.CUSTOM_COLORS.tooltip.1=自訂色彩 of.options.CUSTOM_COLORS.tooltip.2= 開啟 - 使用自訂色彩(預設),較慢 of.options.CUSTOM_COLORS.tooltip.3= 關閉 - 使用預設色彩,較快 of.options.CUSTOM_COLORS.tooltip.4=自訂色彩一般由 of.options.CUSTOM_COLORS.tooltip.5=目前的資源包提供。 of.options.SWAMP_COLORS=沼澤顏色 of.options.SWAMP_COLORS.tooltip.1=沼澤顏色 of.options.SWAMP_COLORS.tooltip.2= 開啟 - 使用沼澤顏色(預設),較慢 of.options.SWAMP_COLORS.tooltip.3= 關閉 - 不使用沼澤顏色,較快 of.options.SWAMP_COLORS.tooltip.4=沼澤的顏色會影響草、樹葉、籐蔓和水。 of.options.SMOOTH_BIOMES=柔和化生態域 of.options.SMOOTH_BIOMES.tooltip.1=柔和化生態域 of.options.SMOOTH_BIOMES.tooltip.2= 開啟 - 柔和化生態域的邊界(預設),較慢 of.options.SMOOTH_BIOMES.tooltip.3= 關閉 - 不柔和化生態域的邊界,較快 of.options.SMOOTH_BIOMES.tooltip.4=柔和化生態域的邊界平滑取樣於 of.options.SMOOTH_BIOMES.tooltip.5=附近所有方塊顏色的平均值。 of.options.SMOOTH_BIOMES.tooltip.6=草、樹葉、籐蔓和水皆會受影響。 of.options.CONNECTED_TEXTURES=連接材質 of.options.CONNECTED_TEXTURES.tooltip.1=連接材質 of.options.CONNECTED_TEXTURES.tooltip.2= 關閉 - 關閉連接材質(預設) of.options.CONNECTED_TEXTURES.tooltip.3= 流暢 - 快速處理連接材質 of.options.CONNECTED_TEXTURES.tooltip.4= 精緻 - 精細處理連接材質 of.options.CONNECTED_TEXTURES.tooltip.5=連接材質為玻璃、沙石和書架增加了連接材質, of.options.CONNECTED_TEXTURES.tooltip.6=當它們互相放在一起時會將材質接為一體。 of.options.CONNECTED_TEXTURES.tooltip.7=連接材質一般由目前的 of.options.CONNECTED_TEXTURES.tooltip.8=資源包提供。 of.options.NATURAL_TEXTURES=自然材質 of.options.NATURAL_TEXTURES.tooltip.1=自然材質 of.options.NATURAL_TEXTURES.tooltip.2= 關閉 - 關閉自然材質(預設) of.options.NATURAL_TEXTURES.tooltip.3= 開啟 - 使用自然材質 of.options.NATURAL_TEXTURES.tooltip.4=自然材質移除由同一類型的方塊 of.options.NATURAL_TEXTURES.tooltip.5=重複放置所產生的柵格狀圖案。 of.options.NATURAL_TEXTURES.tooltip.6=它通過旋轉和翻轉方塊的基礎材質 of.options.NATURAL_TEXTURES.tooltip.7=來產生材質變體。自然材質的設定 of.options.NATURAL_TEXTURES.tooltip.8=和材質一般由目前的資源包提供。 of.options.EMISSIVE_TEXTURES=鏡面材質 of.options.EMISSIVE_TEXTURES.tooltip.1=鏡面材質 of.options.EMISSIVE_TEXTURES.tooltip.2= 關閉 - 關閉鏡面材質(預設) of.options.EMISSIVE_TEXTURES.tooltip.3= 開啟 - 使用鏡面材質 of.options.EMISSIVE_TEXTURES.tooltip.4=光亮材質被繪製為全亮度 of.options.EMISSIVE_TEXTURES.tooltip.5=的覆蓋層。它們可以用來 of.options.EMISSIVE_TEXTURES.tooltip.6=模擬基本材質的發光部分。 of.options.EMISSIVE_TEXTURES.tooltip.7=鏡面材質一般由目前的 of.options.EMISSIVE_TEXTURES.tooltip.8=資源包提供。 of.options.CUSTOM_SKY=自訂天空 of.options.CUSTOM_SKY.tooltip.1=自訂天空 of.options.CUSTOM_SKY.tooltip.2= 開啟 - 自訂天空材質(預設),較慢 of.options.CUSTOM_SKY.tooltip.3= 關閉 - 預設天空材質,較快 of.options.CUSTOM_SKY.tooltip.4=自訂天空材質一般由 of.options.CUSTOM_SKY.tooltip.5=目前的資源包提供。 of.options.CUSTOM_ITEMS=自訂物品 of.options.CUSTOM_ITEMS.tooltip.1=自訂物品 of.options.CUSTOM_ITEMS.tooltip.2= 開啟 - 自訂物品材質(預設),較慢 of.options.CUSTOM_ITEMS.tooltip.3= 關閉 - 原版物品材質,較快 of.options.CUSTOM_ITEMS.tooltip.4=自訂物品材質一般由 of.options.CUSTOM_ITEMS.tooltip.5=目前的資源包提供。 of.options.CUSTOM_ENTITY_MODELS=自訂實體模型 of.options.CUSTOM_ENTITY_MODELS.tooltip.1=自訂實體模型 of.options.CUSTOM_ENTITY_MODELS.tooltip.2= 開啟 - 自訂實體模型(預設),較慢 of.options.CUSTOM_ENTITY_MODELS.tooltip.3= 關閉 - 原版實體模型,較快 of.options.CUSTOM_ENTITY_MODELS.tooltip.4=自訂實體模型一般由 of.options.CUSTOM_ENTITY_MODELS.tooltip.5=目前的資源包提供。 of.options.CUSTOM_GUIS=自訂介面 of.options.CUSTOM_GUIS.tooltip.1=自訂介面 of.options.CUSTOM_GUIS.tooltip.2= 開啟 - 自訂介面(預設),較慢 of.options.CUSTOM_GUIS.tooltip.3= 關閉 - 原版介面,較快 of.options.CUSTOM_GUIS.tooltip.4=自訂介面一般由目前的資源包提供。 # Details of.options.CLOUDS=雲 of.options.CLOUDS.tooltip.1=雲 of.options.CLOUDS.tooltip.2= 預設 - 以「畫面品質」的設定為準 of.options.CLOUDS.tooltip.3= 流暢 - 低品質,較快 of.options.CLOUDS.tooltip.4= 精緻 - 高品質,較慢 of.options.CLOUDS.tooltip.5= 關閉 - 沒有雲,最快 of.options.CLOUDS.tooltip.6=流暢的雲使用 2D 繪製。 of.options.CLOUDS.tooltip.7=精緻的雲使用 3D 繪製。 of.options.CLOUD_HEIGHT=雲層高度 of.options.CLOUD_HEIGHT.tooltip.1=雲層高度 of.options.CLOUD_HEIGHT.tooltip.2= 關閉 - 預設高度 of.options.CLOUD_HEIGHT.tooltip.3= 100%% - 超過世界限制高度 of.options.TREES=樹 of.options.TREES.tooltip.1=樹 of.options.TREES.tooltip.2= 預設 - 以圖像畫質設定為標準 of.options.TREES.tooltip.3= 流暢 - 低品質,最快 of.options.TREES.tooltip.4= 智慧 - 較高品質,較快 of.options.TREES.tooltip.5= 精緻 - 高品質,較慢 of.options.TREES.tooltip.6=流暢的樹葉不透明。 of.options.TREES.tooltip.7=精緻的樹葉透明。 of.options.RAIN=雨和雪 of.options.RAIN.tooltip.1=雨和雪 of.options.RAIN.tooltip.2= 預設 - 以圖像畫質的設定為準 of.options.RAIN.tooltip.3= 流暢 - 少量的雨/雪,較快 of.options.RAIN.tooltip.4= 精緻 - 大量的雨/雪,較慢 of.options.RAIN.tooltip.5= 關閉 - 沒有雨/雪,最快 of.options.RAIN.tooltip.6=當雨雪選項為 關閉 時, of.options.RAIN.tooltip.7=雨聲仍然存在。 of.options.SKY=天空 of.options.SKY.tooltip.1=天空 of.options.SKY.tooltip.2= 開啟 - 天空可見,較慢 of.options.SKY.tooltip.3= 關閉 - 天空不可見,較快 of.options.SKY.tooltip.4=當天空關閉時,月亮和太陽依然可見。 of.options.STARS=星星 of.options.STARS.tooltip.1=星星 of.options.STARS.tooltip.2= 開啟 - 星星可見,較慢 of.options.STARS.tooltip.3= 關閉 - 星星不可見,較快 of.options.SUN_MOON=太陽和月亮 of.options.SUN_MOON.tooltip.1=太陽和月亮 of.options.SUN_MOON.tooltip.2= 開啟 - 太陽和月亮可見(預設) of.options.SUN_MOON.tooltip.3= 關閉 - 太陽和月亮不可見(較快) of.options.SHOW_CAPES=顯示披風 of.options.SHOW_CAPES.tooltip.1=顯示披風 of.options.SHOW_CAPES.tooltip.2= 開啟 - 顯示玩家披風(預設) of.options.SHOW_CAPES.tooltip.3= 關閉 - 不顯示玩家披風 of.options.TRANSLUCENT_BLOCKS=半透明方塊 of.options.TRANSLUCENT_BLOCKS.tooltip.1=半透明方塊 of.options.TRANSLUCENT_BLOCKS.tooltip.2= 預設 - 取決於圖像設定 of.options.TRANSLUCENT_BLOCKS.tooltip.3= 精緻 - 準確的混合顏色(預設) of.options.TRANSLUCENT_BLOCKS.tooltip.4= 流暢 - 快速的混合顏色(較快) of.options.TRANSLUCENT_BLOCKS.tooltip.5=控制不同顏色的半透明方塊 of.options.TRANSLUCENT_BLOCKS.tooltip.6=(染色玻璃、水、冰)隔著空氣 of.options.TRANSLUCENT_BLOCKS.tooltip.7=放在一起時的顏色混和。 of.options.HELD_ITEM_TOOLTIPS=持有物資訊顯示 of.options.HELD_ITEM_TOOLTIPS.tooltip.1=持有物資訊顯示 of.options.HELD_ITEM_TOOLTIPS.tooltip.2= 開啟 - 顯示持有物資訊(預設) of.options.HELD_ITEM_TOOLTIPS.tooltip.3= 關閉 - 隱藏持有物資訊 of.options.ADVANCED_TOOLTIPS=進階資訊顯示 of.options.ADVANCED_TOOLTIPS.tooltip.1=進階資訊顯示 of.options.ADVANCED_TOOLTIPS.tooltip.2= 開啟 - 顯示進階資訊顯示 of.options.ADVANCED_TOOLTIPS.tooltip.3= 關閉 - 隱藏進階資訊顯示(預設) of.options.ADVANCED_TOOLTIPS.tooltip.4=進階資訊顯示顯示物品 of.options.ADVANCED_TOOLTIPS.tooltip.5=(ID、耐久度)和光影設定資料 of.options.ADVANCED_TOOLTIPS.tooltip.6=(ID、來源、預設值)。 of.options.DROPPED_ITEMS=掉落物品 of.options.DROPPED_ITEMS.tooltip.1=掉落物品 of.options.DROPPED_ITEMS.tooltip.2= 預設 - 以圖像畫質的設定為準 of.options.DROPPED_ITEMS.tooltip.3= 流暢 - 2D 掉落物品,較快 of.options.DROPPED_ITEMS.tooltip.4= 精緻 - 3D 掉落物品,較慢 options.entityShadows.tooltip.1=實體陰影 options.entityShadows.tooltip.2= 開啟 - 顯示實體陰影 options.entityShadows.tooltip.3= 關閉 - 隱藏實體陰影 of.options.VIGNETTE=暈影 of.options.VIGNETTE.tooltip.1=螢幕四角輕微變暗的視覺效果 of.options.VIGNETTE.tooltip.2= 預設 - 以圖像畫質的設定為準(預設) of.options.VIGNETTE.tooltip.3= 流暢 - 暈影關閉(較快) of.options.VIGNETTE.tooltip.4= 精緻 - 暈影開啟(較慢) of.options.VIGNETTE.tooltip.5=暈影可能對 FPS 有明顯影響, of.options.VIGNETTE.tooltip.6=尤其是全螢幕遊戲時 of.options.VIGNETTE.tooltip.7=暈影的效果非常細微 of.options.VIGNETTE.tooltip.8=且可以安全地關閉。 of.options.DYNAMIC_FOV=動態視場 of.options.DYNAMIC_FOV.tooltip.1=動態視場 of.options.DYNAMIC_FOV.tooltip.2= 開啟 - 啟用動態視場(預設) of.options.DYNAMIC_FOV.tooltip.3= 關閉 - 停用動態視場 of.options.DYNAMIC_FOV.tooltip.4=當飛行、疾跑或拉弓 of.options.DYNAMIC_FOV.tooltip.5=時改變視場。 of.options.DYNAMIC_LIGHTS=動態光源 of.options.DYNAMIC_LIGHTS.tooltip.1=動態光源 of.options.DYNAMIC_LIGHTS.tooltip.2= 關閉 - 無動態光源(預設) of.options.DYNAMIC_LIGHTS.tooltip.3= 流暢 - 較流暢的動態光源(每 500 毫秒更新一次) of.options.DYNAMIC_LIGHTS.tooltip.4= 精緻 - 高品質的動態光源(即時更新) of.options.DYNAMIC_LIGHTS.tooltip.5=允許發光的物品(火把、螢石等) of.options.DYNAMIC_LIGHTS.tooltip.6=當被玩家左右手持握、裝備或 of.options.DYNAMIC_LIGHTS.tooltip.7=成爲掉落物時照亮周圍。 # Performance of.options.SMOOTH_FPS=柔和化 FPS of.options.SMOOTH_FPS.tooltip.1=通過清除顯示卡緩衝區來穩定 FPS of.options.SMOOTH_FPS.tooltip.2= 關閉 - 不穩定,FPS 可能波動 of.options.SMOOTH_FPS.tooltip.3= 開啟 - FPS 穩定 of.options.SMOOTH_FPS.tooltip.4=此選項依賴於顯卡驅動 of.options.SMOOTH_FPS.tooltip.5=不一定有明顯效果。 of.options.SMOOTH_WORLD=柔和化世界 of.options.SMOOTH_WORLD.tooltip.1=移除內部伺服器造成的資料延遲。 of.options.SMOOTH_WORLD.tooltip.2= 關閉 - 不穩定,FPS 可能波動 of.options.SMOOTH_WORLD.tooltip.3= 開啟 - FPS 穩定 of.options.SMOOTH_WORLD.tooltip.4=分擔內部伺服器負載來穩定 FPS。 of.options.SMOOTH_WORLD.tooltip.5=只在本機世界(單人遊戲)有效。 of.options.FAST_RENDER=快速繪製 of.options.FAST_RENDER.tooltip.1=快速繪製 of.options.FAST_RENDER.tooltip.2= 關閉 - 標準繪製(預設) of.options.FAST_RENDER.tooltip.3= 開啟 - 最佳化繪製(較快) of.options.FAST_RENDER.tooltip.4=採用最佳化的繪製算法來降低 GPU 的負載 of.options.FAST_RENDER.tooltip.5=並且可能大幅提升 FPS。 of.options.FAST_RENDER.tooltip.6=這個選項可能會與部分模組衝突。 of.options.FAST_MATH=快速運算 of.options.FAST_MATH.tooltip.1=快速運算 of.options.FAST_MATH.tooltip.2= 關閉 - 標準的運算(預設) of.options.FAST_MATH.tooltip.3= 開啟 - 更快的運算 of.options.FAST_MATH.tooltip.4=採用最佳化的 sin() 和 cos() 函數可以更 of.options.FAST_MATH.tooltip.5=妥善地利用 CPU 快取並且提升 FPS。 of.options.FAST_MATH.tooltip.6=這個選項會稍微影響世界生成。 of.options.CHUNK_UPDATES=區塊更新 of.options.CHUNK_UPDATES.tooltip.1=區塊更新 of.options.CHUNK_UPDATES.tooltip.2= 1 - 世界載入速度較慢,FPS 較高(預設) of.options.CHUNK_UPDATES.tooltip.3= 3 - 世界載入速度較快,FPS 較低 of.options.CHUNK_UPDATES.tooltip.4= 5 - 世界載入速度最快,FPS 最低 of.options.CHUNK_UPDATES.tooltip.5=繪製每 FPS 時更新的區塊數, of.options.CHUNK_UPDATES.tooltip.6=愈高的值將會導致 FPS 不穩定。 of.options.CHUNK_UPDATES_DYNAMIC=動態更新 of.options.CHUNK_UPDATES_DYNAMIC.tooltip.1=動態更新 of.options.CHUNK_UPDATES_DYNAMIC.tooltip.2= 關閉 - (預設)每 FPS 標準區塊更新 of.options.CHUNK_UPDATES_DYNAMIC.tooltip.3= 開啟 - 當玩家站立不動時更新更多區塊 of.options.CHUNK_UPDATES_DYNAMIC.tooltip.4=當玩家站定時會更新更多 of.options.CHUNK_UPDATES_DYNAMIC.tooltip.5=區塊以加速世界載入。 of.options.LAZY_CHUNK_LOADING=平緩區塊更新 of.options.LAZY_CHUNK_LOADING.tooltip.1=平緩區塊更新 of.options.LAZY_CHUNK_LOADING.tooltip.2= 關閉 - 預設的伺服器區塊載入 of.options.LAZY_CHUNK_LOADING.tooltip.3= 開啟 - 平緩伺服器區塊載入(更柔和) of.options.LAZY_CHUNK_LOADING.tooltip.4=藉由將區塊分佈在多個「遊戲刻」中讀取 of.options.LAZY_CHUNK_LOADING.tooltip.5=來柔和化伺服器整體區塊載入。 of.options.LAZY_CHUNK_LOADING.tooltip.6=如果世界無法正確的載入,請把它關閉。 of.options.LAZY_CHUNK_LOADING.tooltip.7=僅適用於單玩家的本機世界。 of.options.RENDER_REGIONS=區域繪製 of.options.RENDER_REGIONS.tooltip.1=區域繪製 of.options.RENDER_REGIONS.tooltip.2= 關閉 - (預設)不使用區域繪製 of.options.RENDER_REGIONS.tooltip.3= 開啟 - 使用區域繪製 of.options.RENDER_REGIONS.tooltip.4=區域繪製可使遠處的地形繪製得更快。 of.options.RENDER_REGIONS.tooltip.5=當啟用頂點緩衝區對像(VBOs)時此選項將更有效。 of.options.RENDER_REGIONS.tooltip.6=不建議用於整合式顯示卡(內顯)。 of.options.SMART_ANIMATIONS=智慧型動畫 of.options.SMART_ANIMATIONS.tooltip.1=智慧型動畫 of.options.SMART_ANIMATIONS.tooltip.2= 關閉 - 不使用智慧型動畫(預設) of.options.SMART_ANIMATIONS.tooltip.3= 開啟 - 使用智慧型動畫 of.options.SMART_ANIMATIONS.tooltip.4=利用智慧型動畫,讓遊戲只播放 of.options.SMART_ANIMATIONS.tooltip.5=畫面目前可見的材質動畫效果。 of.options.SMART_ANIMATIONS.tooltip.6=這能降低 tick lag 尖峰並提升 FPS。 of.options.SMART_ANIMATIONS.tooltip.7=在大型模組包與高解析度資源包下很有用。 # Animations of.options.animation.allOn=全部開啟 of.options.animation.allOff=全部關閉 of.options.animation.dynamic=動態 of.options.ANIMATED_WATER=水面動畫 of.options.ANIMATED_LAVA=岩漿動畫 of.options.ANIMATED_FIRE=火焰動畫 of.options.ANIMATED_PORTAL=傳送門動畫 of.options.ANIMATED_REDSTONE=紅石動畫 of.options.ANIMATED_EXPLOSION=爆炸動畫 of.options.ANIMATED_FLAME=燃燒動畫 of.options.ANIMATED_SMOKE=煙霧動畫 of.options.VOID_PARTICLES=虛空粒子 of.options.WATER_PARTICLES=水濺粒子 of.options.RAIN_SPLASH=雨滴飛濺 of.options.PORTAL_PARTICLES=傳送門粒子 of.options.POTION_PARTICLES=藥水粒子 of.options.DRIPPING_WATER_LAVA=流動水/岩漿 of.options.ANIMATED_TERRAIN=地形動畫 of.options.ANIMATED_TEXTURES=材質動畫 of.options.FIREWORK_PARTICLES=煙火粒子 # Other of.options.LAGOMETER=效能資訊 of.options.LAGOMETER.tooltip.1=在除錯畫面 (F3) 中顯示效能資訊。 of.options.LAGOMETER.tooltip.2=* 橙 - 記憶體垃圾回收 of.options.LAGOMETER.tooltip.3=* 青 - Tick of.options.LAGOMETER.tooltip.4=* 藍 - 排定的處理程序 of.options.LAGOMETER.tooltip.5=* 紫 - 區塊上傳 of.options.LAGOMETER.tooltip.6=* 紅 - 區塊更新 of.options.LAGOMETER.tooltip.7=* 黃 - 可見度檢查 of.options.LAGOMETER.tooltip.8=* 綠 - 繪製的地形 of.options.PROFILER=除錯分析器 of.options.PROFILER.tooltip.1=除錯分析器 of.options.PROFILER.tooltip.2= 開啟 - 啟用除錯分析器,較慢 of.options.PROFILER.tooltip.3= 關閉 - 停用除錯分析器,較快 of.options.PROFILER.tooltip.4=除錯分析器在除錯介面 (F3) 開啟時 of.options.PROFILER.tooltip.5=收集並且顯示除錯資訊。 of.options.WEATHER=天氣 of.options.WEATHER.tooltip.1=天氣 of.options.WEATHER.tooltip.2= 開啟 - 開啟天氣,較慢 of.options.WEATHER.tooltip.3= 關閉 - 關閉天氣,較快 of.options.WEATHER.tooltip.4=天氣選項影響雨,雪和雷電。 of.options.WEATHER.tooltip.5=天氣選項僅在本機遊戲中生效。 of.options.time.dayOnly=只有白天 of.options.time.nightOnly=只有夜晚 of.options.TIME=時間 of.options.TIME.tooltip.1=時間 of.options.TIME.tooltip.2= 預設 - 正常的日夜交替 of.options.TIME.tooltip.3= 只有白天 - 只有白天 of.options.TIME.tooltip.4= 只有夜晚 - 只有夜晚 of.options.TIME.tooltip.5=時間設定只在創造模式下 of.options.TIME.tooltip.6=且為本機遊戲時有效。 options.fullscreen.tooltip.1=全螢幕 options.fullscreen.tooltip.2= 開啟 - 使用全螢幕模式 options.fullscreen.tooltip.3= 關閉 - 使用視窗模式 options.fullscreen.tooltip.4=全螢幕模式可能比視窗模式 options.fullscreen.tooltip.5=更快或更慢,取決於顯卡。 of.options.FULLSCREEN_MODE=全螢幕模式 of.options.FULLSCREEN_MODE.tooltip.1=全螢幕模式 of.options.FULLSCREEN_MODE.tooltip.2= 預設 - 使用桌面解析度,較慢 of.options.FULLSCREEN_MODE.tooltip.3= 自訂 - 使用自訂螢幕解析度,可能會較快 of.options.FULLSCREEN_MODE.tooltip.4=此選項只在全螢幕模式下有效 (F11)。 of.options.FULLSCREEN_MODE.tooltip.5=較低的解析度通常會較快。 of.options.SHOW_FPS=顯示 FPS of.options.SHOW_FPS.tooltip.1=顯示精簡的 FPS 和繪製資訊 of.options.SHOW_FPS.tooltip.2= Fps - 平均值/最低值 of.options.SHOW_FPS.tooltip.3= C: - 區塊繪製器 of.options.SHOW_FPS.tooltip.4= E: - 一般實體 + 方塊實體 of.options.SHOW_FPS.tooltip.5= U: - 區塊更新 of.options.SHOW_FPS.tooltip.6=當除錯畫面隱藏時才會 of.options.SHOW_FPS.tooltip.7=顯示精簡的 FPS 資訊。 of.options.save.default=預設(兩秒) of.options.save.20s=20 秒 of.options.save.3min=3 分鐘 of.options.save.30min=30 分鐘 of.options.AUTOSAVE_TICKS=自動儲存 of.options.AUTOSAVE_TICKS.tooltip.1=自動儲存間隔 of.options.AUTOSAVE_TICKS.tooltip.2=不建議使用預設自動儲存間隔(兩秒)。 of.options.AUTOSAVE_TICKS.tooltip.3=自動儲存會導致卡頓。 of.options.SCREENSHOT_SIZE=截圖尺寸 of.options.SCREENSHOT_SIZE.tooltip.1=截圖尺寸 of.options.SCREENSHOT_SIZE.tooltip.2= 預設 - 預設的截圖尺寸 of.options.SCREENSHOT_SIZE.tooltip.3= 2x-4x - 自訂截圖尺寸 of.options.SCREENSHOT_SIZE.tooltip.4=抓取更大的截圖可能需要更多的記憶體。 of.options.SCREENSHOT_SIZE.tooltip.5=與快速繪製及反鋸齒不相容。 of.options.SCREENSHOT_SIZE.tooltip.6=需要顯卡 FPS 緩衝區支持。 of.options.SHOW_GL_ERRORS=顯示 GL 錯誤 of.options.SHOW_GL_ERRORS.tooltip.1=顯示 OpenGL 錯誤 of.options.SHOW_GL_ERRORS.tooltip.2=啟用時,OpenGL 的錯誤會顯示在聊天視窗中。 of.options.SHOW_GL_ERRORS.tooltip.3=只有在已知的衝突或錯誤 of.options.SHOW_GL_ERRORS.tooltip.4=無法修復時才建議停用。 of.options.SHOW_GL_ERRORS.tooltip.5=停用時,錯誤仍然會記在錯誤記錄中, of.options.SHOW_GL_ERRORS.tooltip.6=且依然可能導致 FPS 明顯下降。 # Chat Settings of.options.CHAT_BACKGROUND=聊天欄背景 of.options.CHAT_BACKGROUND.tooltip.1=聊天欄背景 of.options.CHAT_BACKGROUND.tooltip.2= 預設 - 修正寬度 of.options.CHAT_BACKGROUND.tooltip.3= 緊湊 - 符合行寬 of.options.CHAT_BACKGROUND.tooltip.4= 關閉 - 隱藏 of.options.CHAT_SHADOW=聊天欄陰影 of.options.CHAT_SHADOW.tooltip.1=聊天欄陰影 of.options.CHAT_SHADOW.tooltip.2= 開啟 - 使用文字陰影 of.options.CHAT_SHADOW.tooltip.3= 關閉 - 無文字陰影
1
0.788778
1
0.788778
game-dev
MEDIA
0.6476
game-dev,graphics-rendering
0.588177
1
0.588177
Papela/Nitrox-Cracked-Mod
1,097
NitroxClient/GameLogic/Spawning/Abstract/SyncEntitySpawner.cs
using System; using NitroxModel.DataStructures.GameLogic; using NitroxModel.DataStructures.Util; using UnityEngine; namespace NitroxClient.GameLogic.Spawning.Abstract; public abstract class SyncEntitySpawner<T> : EntitySpawner<T>, ISyncEntitySpawner where T : Entity { protected abstract bool SpawnSync(T entity, TaskResult<Optional<GameObject>> result); public bool SpawnSync(Entity entity, TaskResult<Optional<GameObject>> result) { return SpawnSync((T)entity, result); } /// <returns>The result of <see cref="SpawnSync(T,TaskResult{Optional{GameObject}})"/> or true with the caught exception </returns> public bool SpawnSyncSafe(Entity entity, TaskResult<Optional<GameObject>> result, TaskResult<Exception> exception) { try { if (SpawnSync((T)entity, result)) { exception.Set(null); return true; } } catch (Exception e) { exception.Set(e); return true; } exception.Set(null); return false; } }
1
0.728397
1
0.728397
game-dev
MEDIA
0.986173
game-dev
0.720728
1
0.720728
vmangos/core
95,623
src/game/Objects/GameObject.cpp
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero> * Copyright (C) 2011-2016 Nostalrius <https://nostalrius.org> * Copyright (C) 2016-2017 Elysium Project <https://github.com/elysium-project> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "GameObject.h" #include "QuestDef.h" #include "ObjectMgr.h" #include "PoolManager.h" #include "SpellMgr.h" #include "Spell.h" #include "Group.h" #include "Opcodes.h" #include "WorldPacket.h" #include "World.h" #include "Database/DatabaseEnv.h" #include "LootMgr.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" #include "MapManager.h" #include "MapPersistentStateMgr.h" #include "BattleGround.h" #include "BattleGroundAV.h" #include "Util.h" #include "GameObjectAI.h" #include "ScriptMgr.h" #include "ZoneScript.h" #include "DynamicTree.h" #include "vmap/GameObjectModel.h" #include <G3D/Box.h> #include <G3D/CoordinateFrame.h> #include <G3D/Quat.h> #include "Geometry.h" bool QuaternionData::isUnit() const { return fabs(x * x + y * y + z * z + w * w - 1.0f) < 1e-5f; } void QuaternionData::toEulerAnglesZYX(float& Z, float& Y, float& X) const { G3D::Matrix3(G3D::Quat(x, y, z, w)).toEulerAnglesZYX(Z, Y, X); } QuaternionData QuaternionData::fromEulerAnglesZYX(float Z, float Y, float X) { G3D::Quat quat(G3D::Matrix3::fromEulerAnglesZYX(Z, Y, X)); return QuaternionData(quat.x, quat.y, quat.z, quat.w); } GameObject::GameObject() : SpellCaster(), loot(this), m_visible(true), m_goInfo(nullptr) { m_objectType |= TYPEMASK_GAMEOBJECT; m_objectTypeId = TYPEID_GAMEOBJECT; #if SUPPORTED_CLIENT_BUILD > CLIENT_BUILD_1_8_4 m_updateFlag = (UPDATEFLAG_ALL | UPDATEFLAG_HAS_POSITION); #endif m_valuesCount = GAMEOBJECT_END; m_respawnTime = 0; m_respawnDelayTime = 25; m_lootState = GO_NOT_READY; m_spawnedByDefault = true; m_useTimes = 0; m_spellId = 0; m_cooldownTime = 0; m_AI = nullptr; m_model = nullptr; m_rotation = 0; m_playerGroupId = 0; m_summonTarget = ObjectGuid(); } GameObject::~GameObject() { // set current spells as deletable for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) { if (m_currentSpells[i]) { m_currentSpells[i]->SetReferencedFromCurrent(false); m_currentSpells[i] = nullptr; } } delete m_AI; delete m_model; MANGOS_ASSERT(m_spellDynObjects.empty()); } GameObject* GameObject::CreateGameObject(uint32 entry) { GameObjectInfo const* goinfo = sObjectMgr.GetGameObjectTemplate(entry); if (goinfo && goinfo->type == GAMEOBJECT_TYPE_TRANSPORT) return new ElevatorTransport; return new GameObject; } void GameObject::AddToWorld() { // Register the gameobject for guid lookup if (!IsInWorld()) { GetMap()->InsertObject<GameObject>(GetObjectGuid(), this); if (m_zoneScript) m_zoneScript->OnGameObjectCreate(this); if (m_model) GetMap()->InsertGameObjectModel(*m_model); } Object::AddToWorld(); // After Object::AddToWorld so that for initial state the GO is added to the world (and hence handled correctly) UpdateCollisionState(); if (!m_AI) AIM_Initialize(); if (sWorld.getConfig(CONFIG_UINT32_SPELL_PROC_DELAY)) m_procsUpdateTimer = sWorld.getConfig(CONFIG_UINT32_SPELL_PROC_DELAY) - (WorldTimer::getMSTime() % sWorld.getConfig(CONFIG_UINT32_SPELL_PROC_DELAY)); } void GameObject::AIM_Initialize() { delete m_AI; m_AI = sScriptMgr.GetGameObjectAI(this); } void GameObject::RemoveFromWorld() { // Remove the gameobject from the accessor if (IsInWorld()) { if (AI()) AI()->OnRemoveFromWorld(); if (m_zoneScript) m_zoneScript->OnGameObjectRemove(this); RemoveAllDynObjects(); // Remove GO from owner if (ObjectGuid owner_guid = GetOwnerGuid()) { if (Unit* owner = ObjectAccessor::GetUnit(*this, owner_guid)) owner->RemoveGameObject(this, false); else { sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Delete %s with SpellId %u LinkedGO %u that lost references to owner %s GO list. Crash possible later.", GetGuidStr().c_str(), m_spellId, GetGOInfo()->GetLinkedGameObjectEntry(), owner_guid.GetString().c_str()); } } if (m_model && GetMap()->ContainsGameObjectModel(*m_model)) GetMap()->RemoveGameObjectModel(*m_model); GetMap()->EraseObject<GameObject>(GetObjectGuid()); } Object::RemoveFromWorld(); } bool GameObject::Create(uint32 guidlow, uint32 name_id, Map* map, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, GOState go_state) { MANGOS_ASSERT(map); Relocate(x, y, z, ang); SetMap(map); m_stationaryPosition = Position(x, y, z, ang); if (!IsPositionValid()) { sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "Gameobject (GUID: %u Entry: %u ) not created. Suggested coordinates are invalid (X: %f Y: %f)", guidlow, name_id, x, y); return false; } SetZoneScript(); GameObjectInfo const* goinfo = sObjectMgr.GetGameObjectTemplate(name_id); if (!goinfo) { sLog.Out(LOG_DBERROR, LOG_LVL_ERROR, "Gameobject (GUID: %u) not created: Entry %u does not exist in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f) ang: %f rotation0: %f rotation1: %f rotation2: %f rotation3: %f", guidlow, name_id, map->GetId(), x, y, z, ang, rotation0, rotation1, rotation2, rotation3); return false; } Object::_Create(guidlow, goinfo->id, goinfo->type == GAMEOBJECT_TYPE_TRANSPORT ? HIGHGUID_TRANSPORT : HIGHGUID_GAMEOBJECT); m_goInfo = goinfo; if (goinfo->type >= MAX_GAMEOBJECT_TYPE) { sLog.Out(LOG_DBERROR, LOG_LVL_ERROR, "Gameobject (GUID: %u) not created: Entry %u has invalid type %u in `gameobject_template`. It may crash client if created.", guidlow, name_id, goinfo->type); return false; } SetObjectScale(goinfo->size); #if SUPPORTED_CLIENT_BUILD < CLIENT_BUILD_1_12_1 SetUInt32Value(GAMEOBJECT_TIMESTAMP, (uint32)time(nullptr)); #endif SetFloatValue(GAMEOBJECT_POS_X, x); SetFloatValue(GAMEOBJECT_POS_Y, y); SetFloatValue(GAMEOBJECT_POS_Z, z); SetFloatValue(GAMEOBJECT_FACING, ang); SetFloatValue(GAMEOBJECT_ROTATION + 0, rotation0); SetFloatValue(GAMEOBJECT_ROTATION + 1, rotation1); UpdateRotationFields(rotation2, rotation3); // GAMEOBJECT_FACING, GAMEOBJECT_ROTATION+2/3 SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction); SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags); SetEntry(goinfo->id); SetDisplayId(goinfo->displayId); SetGoState(go_state); SetGoType(GameobjectTypes(goinfo->type)); SetGoAnimProgress(animprogress); if (goinfo->type == GAMEOBJECT_TYPE_TRANSPORT) { m_updateFlag |= UPDATEFLAG_TRANSPORT; SetUInt32Value(GAMEOBJECT_LEVEL, goinfo->transport.pause); SetGoState(goinfo->transport.startOpen ? GO_STATE_ACTIVE : GO_STATE_READY); SetFlag(GAMEOBJECT_FLAGS, (GO_FLAG_TRANSPORT | GO_FLAG_NODESPAWN)); } if (GetGOInfo()->IsLargeGameObject()) { SetVisibilityModifier(VISIBILITY_DISTANCE_LARGE); if (sWorld.getConfig(CONFIG_BOOL_VISIBILITY_FORCE_ACTIVE_OBJECTS)) SetActiveObjectState(true); } else if (GetGOInfo()->IsInfiniteGameObject()) { SetVisibilityModifier(MAX_VISIBILITY_DISTANCE); if (sWorld.getConfig(CONFIG_BOOL_VISIBILITY_FORCE_ACTIVE_OBJECTS)) SetActiveObjectState(true); } //Notify the map's instance data. //Only works if you create the object in it, not if it is moves to that map. //Normally non-players do not teleport to other maps. if (m_zoneScript) m_zoneScript->OnObjectCreate(this); return true; } class HunterTrapTargetSelectorCheck { public: HunterTrapTargetSelectorCheck(GameObject const* pTrap, Unit const* pOwner, float range) : i_trap(pTrap), i_trapOwner(pOwner), i_range(range) {} WorldObject const& GetFocusObject() const { return *i_trap; } bool operator()(Unit* pTarget) { if (!i_trap->CanSeeInWorld(pTarget)) return false; // don't trigger on enemy player if our owner is not flagged for pvp if (Player const* pOwnerPlayer = i_trapOwner->ToPlayer()) { if (Player const* pTargetPlayer = pTarget->GetCharmerOrOwnerPlayerOrPlayerItself()) { if (!pOwnerPlayer->IsPvP() && !(pOwnerPlayer->IsFFAPvP() && pTargetPlayer->IsFFAPvP()) && !pOwnerPlayer->IsInDuelWith(pTargetPlayer)) return false; } } bool isTotem = pTarget->IsCreature() && ((Creature*)pTarget)->IsTotem(); if (i_trap->IsWithinDistInMap(pTarget, isTotem ? i_range / 3.0f : i_range) && i_trapOwner->IsValidAttackTarget(pTarget) && (pTarget->IsInCombat() || i_trapOwner->IsHostileTo(pTarget))) { i_range = i_trap->GetDistance(pTarget); return true; } return false; } private: GameObject const* i_trap; Unit const* i_trapOwner; float i_range; }; void GameObject::Update(uint32 update_diff, uint32 /*p_time*/) { WorldObject::Update(update_diff, update_diff); if (GetObjectGuid().IsMOTransport()) { //((ShipTransport*)this)->Update(p_time); return; } UpdateCooldowns(GetMap()->GetCurrentClockTime()); m_Events.Update(update_diff); // remove finished spells from current pointers for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) { if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED) { m_currentSpells[i]->SetReferencedFromCurrent(false); m_currentSpells[i] = nullptr; // remove pointer } } UpdatePendingProcs(update_diff); // UpdateAI if (m_AI) m_AI->UpdateAI(update_diff); switch (m_lootState) { case GO_NOT_READY: { switch (GetGoType()) { case GAMEOBJECT_TYPE_TRAP: { // Arming Time for GAMEOBJECT_TYPE_TRAP (6) /* Ivina < Nostalrius > : toujours appliquer le startDelay. Retirer le delai de la DB si jamais un piege n'en a pas. */ // Unit* owner = GetOwner(); // if (owner && ((Player*)owner)->IsInCombat()) if (GetGOInfo()->trap.startDelay) m_cooldownTime = time(nullptr) + GetGOInfo()->trap.startDelay; m_lootState = GO_READY; break; } case GAMEOBJECT_TYPE_FISHINGNODE: { // fishing code (bobber ready) if (time(nullptr) > m_respawnTime - FISHING_BOBBER_READY_TIME) { // splash bobber (bobber ready now) if (Player* caster = ::ToPlayer(GetOwner())) { SetGoState(GO_STATE_ACTIVE); // SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN); SendForcedObjectUpdate(); // Play splash sound PlayDistanceSound(3355); SendGameObjectCustomAnim(); } m_lootState = GO_READY; // can be successfully open with some chance } return; } case GAMEOBJECT_TYPE_CHEST: { if (m_goInfo->chest.chestRestockTime) { if (m_cooldownTime <= time(nullptr)) { m_cooldownTime = 0; m_lootState = GO_READY; ForceValuesUpdateAtIndex(GAMEOBJECT_DYN_FLAGS); } return; } m_lootState = GO_READY; break; } default: m_lootState = GO_READY; // for other GO is same switched without delay to GO_READY break; } } // NO BREAK for switch (m_lootState) case GO_READY: { if (m_respawnTime > 0) // timer on { if (m_respawnTime <= time(nullptr)) // timer expired { m_respawnTime = 0; ClearAllUsesData(); switch (GetGoType()) { case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now { if (Player* caster = ::ToPlayer(GetOwner())) { caster->FinishSpell(CURRENT_CHANNELED_SPELL); WorldPacket data(SMSG_FISH_NOT_HOOKED, 0); ((Player*)caster)->GetSession()->SendPacket(&data); } // can be deleted m_lootState = GO_JUST_DEACTIVATED; return; } case GAMEOBJECT_TYPE_DOOR: case GAMEOBJECT_TYPE_BUTTON: //we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds) if (GetGoState() != GO_STATE_READY) ResetDoorOrButton(); //flags in AB are type_button and we need to add them here so no break! case GAMEOBJECT_TYPE_CHEST: case GAMEOBJECT_TYPE_SPELL_FOCUS: case GAMEOBJECT_TYPE_GOOBER: // Respawn linked trap if any exists RespawnLinkedGameObject(); default: if (!m_spawnedByDefault) // despawn timer { // can be despawned or destroyed SetLootState(GO_JUST_DEACTIVATED); return; } LockEntry const* lock = sLockStore.LookupEntry(GetGOInfo()->GetLockId()); //workarounds for PvP banners if (lock && lock->Index[1] == LOCKTYPE_SLOW_OPEN) { m_respawnDelayTime = -1; //spawn animation GetMap()->Add(this); m_respawnDelayTime = 0; SendGameObjectReset(); } else GetMap()->Add(this); } } } if (isSpawned()) { // traps can have time and can not have GameObjectInfo const* goInfo = GetGOInfo(); if (goInfo->type == GAMEOBJECT_TYPE_TRAP) { if (m_cooldownTime >= time(nullptr)) return; // traps Unit* owner = GetOwner(); Unit* ok = nullptr; // pointer to appropriate target if found any bool IsBattleGroundTrap = false; //FIXME: this is activation radius (in different casting radius that must be selected from spell data) //TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state float radius = float(goInfo->trap.radius); if (!radius) { if (goInfo->trap.cooldown != 3) // cast in other case (at some triggering/linked go/etc explicit call) return; else { if (m_respawnTime > 0) break; // battlegrounds gameobjects has data2 == 0 && data5 == 3 radius = float(goInfo->trap.cooldown); IsBattleGroundTrap = true; } } // Rayon float et non entier (impose par la DB) pour certains pieges chassoux : switch (goInfo->id) { case 2561: case 164638: case 164639: case 164839: case 164872: case 164873: case 164874: case 164875: case 164876: case 164877: case 164879: case 164880: radius = 2.5f; break; } // Note: this hack with search required until GO casting not implemented // search unfriendly creature if (owner && goInfo->trap.charges > 0) // hunter trap { HunterTrapTargetSelectorCheck u_check(this, owner, radius); MaNGOS::UnitLastSearcher<HunterTrapTargetSelectorCheck> checker(ok, u_check); Cell::VisitWorldObjects(this, checker, radius); // players Cell::VisitGridObjects(this, checker, radius); // units } else // environmental trap { // environmental damage spells already have around enemies targeting but this not help in case nonexistent GO casting support // affect only players Player* p_ok = nullptr; MaNGOS::AnyPlayerInObjectRangeCheck p_check(this, radius); MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck> checker(p_ok, p_check); Cell::VisitWorldObjects(this, checker, radius); ok = p_ok; } if (ok && (!AI() || !AI()->OnUse(ok))) { if (owner) owner->CastSpell(ok, goInfo->trap.spellId, true, nullptr, nullptr, GetObjectGuid()); else CastSpell(ok, goInfo->trap.spellId, true, nullptr, nullptr, GetObjectGuid()); // use template cooldown if provided m_cooldownTime = time(nullptr) + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)); // count charges if (goInfo->trap.charges > 0) AddUse(); if (IsBattleGroundTrap && ok->GetTypeId() == TYPEID_PLAYER) { //BattleGround gameobjects case if (((Player*)ok)->InBattleGround()) if (BattleGround* bg = ((Player*)ok)->GetBattleGround()) bg->HandleTriggerBuff(this); } // TODO: all traps can be activated, also those without spell. // Some may have have animation and/or are expected to despawn. if (HasCustomAnim()) SendGameObjectCustomAnim(); } } if (uint32 max_charges = goInfo->GetCharges()) { if (m_useTimes >= max_charges) { m_useTimes = 0; SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed } } } break; } case GO_ACTIVATED: { switch (GetGoType()) { case GAMEOBJECT_TYPE_DOOR: case GAMEOBJECT_TYPE_BUTTON: if (GetGOInfo()->GetAutoCloseTime() && (m_cooldownTime < time(nullptr))) ResetDoorOrButton(); break; case GAMEOBJECT_TYPE_GOOBER: if (m_cooldownTime < time(nullptr)) { RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); SetLootState(GO_JUST_DEACTIVATED); m_cooldownTime = 0; } break; case GAMEOBJECT_TYPE_CHEST: { if (m_cooldownTime > 0 && m_cooldownTime < time(nullptr)) { SetLootState(GO_JUST_DEACTIVATED); } break; } default: break; } break; } case GO_JUST_DEACTIVATED: { switch (GetGoType()) { // if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed case GAMEOBJECT_TYPE_GOOBER: { uint32 spellId = GetGOInfo()->goober.spellId; if (spellId) { // TODO find out why this is here, because m_UniqueUsers is empty for GAMEOBJECT_TYPE_GOOBER for (const auto& guid : m_UniqueUsers) { if (Player* owner = GetMap()->GetPlayer(guid)) owner->CastSpell(owner, spellId, false, nullptr, nullptr, GetObjectGuid()); } ClearAllUsesData(); } SetGoState(GO_STATE_READY); //any return here in case battleground traps break; } case GAMEOBJECT_TYPE_CHEST: { // consumable confirmed to override chest restock if (!m_goInfo->chest.consumable && m_goInfo->chest.chestRestockTime) { m_cooldownTime = time(nullptr) + m_goInfo->chest.chestRestockTime; SetLootState(GO_NOT_READY); ForceValuesUpdateAtIndex(GAMEOBJECT_DYN_FLAGS); return; } break; } } if (GetOwnerGuid() || (!m_spawnedByDefault && !GetGOData())) { if (Unit* owner = GetOwner()) owner->RemoveGameObject(this, false); SetRespawnTime(0); Delete(); return; } // burning flags in some battlegrounds, if you find better condition, just add it if (GetGOInfo()->IsDespawnAtAction() || GetGoAnimProgress() > 0) { SendObjectDeSpawnAnim(); // reset flags if (GetMap()->Instanceable()) { // In Instances GO_FLAG_LOCKED or GO_FLAG_NO_INTERACT are not changed uint32 currentLockOrInteractFlags = GetUInt32Value(GAMEOBJECT_FLAGS) & (GO_FLAG_LOCKED | GO_FLAG_NO_INTERACT); SetUInt32Value(GAMEOBJECT_FLAGS, (GetGOInfo()->flags & ~(GO_FLAG_LOCKED | GO_FLAG_NO_INTERACT)) | currentLockOrInteractFlags); } else SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags); } loot.clear(); SetLootState(GO_READY); if (!m_respawnDelayTime) return; if (m_spawnedByDefault) { m_respawnTime = time(nullptr) + ComputeRespawnDelay(); } else m_respawnTime = 0; // if option not set then object will be saved at grid unload if (sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY)) SaveRespawnTime(); UpdateObjectVisibility(); JustDespawnedWaitingRespawn(); break; } } } uint32 GameObject::ComputeRespawnDelay() const { if (GameObjectData const* data = GetGOData()) return data->ComputeRespawnDelay(m_respawnDelayTime); return m_respawnDelayTime; } uint32 GameObjectData::ComputeRespawnDelay(uint32 respawnDelay) const { if (spawn_flags & SPAWN_FLAG_RANDOM_RESPAWN_TIME) respawnDelay = uint32(float(respawnDelay * urand(90, 110)) / 100.f); if (spawn_flags & SPAWN_FLAG_DYNAMIC_RESPAWN_TIME && sWorld.GetActiveSessionCount() > BLIZZLIKE_REALM_POPULATION) respawnDelay = uint32(float(respawnDelay * BLIZZLIKE_REALM_POPULATION) / float(sWorld.GetActiveSessionCount())); return respawnDelay; } void GameObject::JustDespawnedWaitingRespawn() { if (uint16 poolid = sPoolMgr.IsPartOfAPool<GameObject>(GetGUIDLow())) { uint32 guidLow = GetGUIDLow(); MapPersistentState& state = *GetMap()->GetPersistentState(); sPoolMgr.GetPoolGameObjects(poolid).DespawnObject(state, guidLow); // Calls 'AddObjectToRemoveList', so the object is deleted. Do not use any class method / attribute! if (!IsDeleted()) { sLog.Out(LOG_BASIC, LOG_LVL_MINIMAL, "[Pool #%u] %s is not deleted but should be", poolid, GetGuidStr().c_str()); AddObjectToRemoveList(); } sPoolMgr.UpdatePool<GameObject>(state, poolid, GetGUIDLow()); return; } } void GameObject::Refresh() { // not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway) if (m_respawnTime > 0 && m_spawnedByDefault) return; if (isSpawned()) GetMap()->Add(this); } void GameObject::AddUniqueUse(Player* player) { std::unique_lock<std::shared_timed_mutex> guard(m_UniqueUsers_lock); AddUse(); if (m_UniqueUsers.find(player->GetObjectGuid()) != m_UniqueUsers.end()) return; if (!m_firstUser) m_firstUser = player->GetObjectGuid(); m_UniqueUsers.insert(player->GetObjectGuid()); guard.unlock(); if (GameObjectInfo const* info = GetGOInfo()) if (info->type == GAMEOBJECT_TYPE_SUMMONING_RITUAL && info->summoningRitual.animSpell && GetOwnerGuid() != player->GetObjectGuid()) { SpellEntry const* spellInfo = sSpellMgr.GetSpellEntry(info->summoningRitual.animSpell); if (!spellInfo) { sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "WORLD: unknown spell id %u at play anim for gameobject (Entry: %u GoType: %u )", info->summoningRitual.animSpell, GetEntry(), GetGoType()); return; } Spell* spell = new Spell(player, spellInfo, true, GetObjectGuid()); spell->SetChannelingVisual(true); SpellCastTargets targets; targets.setGOTarget(this); spell->prepare(std::move(targets)); } } void GameObject::RemoveUniqueUse(Player const* player) { const std::lock_guard<std::shared_timed_mutex> guard(m_UniqueUsers_lock); auto itr = m_UniqueUsers.find(player->GetObjectGuid()); if (itr == m_UniqueUsers.end()) return; m_UniqueUsers.erase(itr); if (GameObjectInfo const* info = GetGOInfo()) // owner cancelled if (player->GetObjectGuid() == GetOwnerGuid() || // too many helpers cancelled while it's activated (GetGoState() == GO_STATE_ACTIVE && m_UniqueUsers.size() < info->summoningRitual.reqParticipants)) { if (!info->summoningRitual.ritualPersistent) { if (GetGoState() != GO_STATE_ACTIVE) SetLootState(GO_JUST_DEACTIVATED); else if (Unit* pOwner = GetOwner()) // if active it'll be destroyed in Spell::update // remove it from owner's list to keep it running pOwner->RemoveGameObject(this, false); } SetGoState(GO_STATE_READY); } } void GameObject::FinishRitual() { std::unique_lock<std::shared_timed_mutex> guard(m_UniqueUsers_lock); if (GameObjectInfo const* info = GetGOInfo()) { // take spell cooldown if (Player* pOwner = ::ToPlayer(GetOwner())) if (SpellEntry const* createBySpell = sSpellMgr.GetSpellEntry(GetSpellId())) pOwner->AddCooldown(*createBySpell); if (!info->summoningRitual.ritualPersistent) SetLootState(GO_JUST_DEACTIVATED); // Only ritual of doom deals a second spell if (uint32 spellid = info->summoningRitual.casterTargetSpell) { // On a random user auto it = m_UniqueUsers.begin(); if (it != m_UniqueUsers.end()) { std::advance(it, urand(0, m_UniqueUsers.size() - 1)); guard.unlock(); if (Player* target = GetMap()->GetPlayer(*it)) target->CastSpell(target, spellid, true); } } } } bool GameObject::HasUniqueUser(Player const* player) { const std::shared_lock<std::shared_timed_mutex> guard(m_UniqueUsers_lock); return m_UniqueUsers.find(player->GetObjectGuid()) != m_UniqueUsers.end(); } uint32 GameObject::GetUniqueUseCount() { const std::shared_lock<std::shared_timed_mutex> guard(m_UniqueUsers_lock); return m_UniqueUsers.size(); } void GameObject::CleanupsBeforeDelete() { if (m_uint32Values) // only for fully created object { InterruptNonMeleeSpells(true); m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList } WorldObject::CleanupsBeforeDelete(); } void GameObject::Delete() { // no despawn animation for not activated rituals if (GetGoType() != GAMEOBJECT_TYPE_SUMMONING_RITUAL || GetGoState() == GO_STATE_ACTIVE) SendObjectDeSpawnAnim(); if (!IsDeleted()) AddObjectToRemoveList(); SetGoState(GO_STATE_READY); SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags); if (uint16 poolid = sPoolMgr.IsPartOfAPool<GameObject>(GetGUIDLow())) sPoolMgr.GetPoolGameObjects(poolid).DespawnObject(*GetMap()->GetPersistentState(), GetGUIDLow()); } void GameObject::getFishLoot(Loot* fishloot, Player* loot_owner) { fishloot->clear(); uint32 zone, subzone; GetZoneAndAreaId(zone, subzone); // Don't allow fishing in hidden wetlands lake if (subzone == 11 && loot_owner->IsWithinDist2d(-4074.74f, -1315.79f, 100.0f)) return; // if subzone loot exist use it if (!fishloot->FillLoot(subzone, LootTemplates_Fishing, loot_owner, true, (subzone != zone)) && subzone != zone) // else use zone loot (if zone diff. from subzone, must exist in like case) fishloot->FillLoot(zone, LootTemplates_Fishing, loot_owner, true); } void GameObject::SaveToDB() { // this should only be used when the gameobject has already been loaded // preferably after adding to map, because mapid may not be valid otherwise GameObjectData const* data = sObjectMgr.GetGOData(GetGUIDLow()); if (!data) { sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "GameObject::SaveToDB failed, cannot get gameobject data!"); return; } SaveToDB(GetMapId()); } void GameObject::SaveToDB(uint32 mapid) { GameObjectInfo const* goI = GetGOInfo(); if (!goI) return; // update in loaded data (changing data only in this place) GameObjectData& data = sObjectMgr.NewGOData(GetGUIDLow()); // data->guid = guid don't must be update at save data.id = GetEntry(); data.position.mapId = mapid; data.position.x = GetFloatValue(GAMEOBJECT_POS_X); data.position.y = GetFloatValue(GAMEOBJECT_POS_Y); data.position.z = GetFloatValue(GAMEOBJECT_POS_Z); data.position.o = GetFloatValue(GAMEOBJECT_FACING); data.rotation0 = GetFloatValue(GAMEOBJECT_ROTATION + 0); data.rotation1 = GetFloatValue(GAMEOBJECT_ROTATION + 1); data.rotation2 = GetFloatValue(GAMEOBJECT_ROTATION + 2); data.rotation3 = GetFloatValue(GAMEOBJECT_ROTATION + 3); data.spawntimesecsmin = m_spawnedByDefault ? (int32)m_respawnDelayTime : -(int32)m_respawnDelayTime; data.spawntimesecsmax = m_spawnedByDefault ? (int32)m_respawnDelayTime : -(int32)m_respawnDelayTime; data.animprogress = GetGoAnimProgress(); data.go_state = GetGoState(); data.spawn_flags = m_isActiveObject ? SPAWN_FLAG_ACTIVE : 0; // updated in DB std::ostringstream ss; ss << "INSERT INTO gameobject VALUES ( " << GetGUIDLow() << ", " << GetEntry() << ", " << mapid << ", " << GetFloatValue(GAMEOBJECT_POS_X) << ", " << GetFloatValue(GAMEOBJECT_POS_Y) << ", " << GetFloatValue(GAMEOBJECT_POS_Z) << ", " << GetFloatValue(GAMEOBJECT_FACING) << ", " << GetFloatValue(GAMEOBJECT_ROTATION) << ", " << GetFloatValue(GAMEOBJECT_ROTATION + 1) << ", " << GetFloatValue(GAMEOBJECT_ROTATION + 2) << ", " << GetFloatValue(GAMEOBJECT_ROTATION + 3) << ", " << data.spawntimesecsmin << ", " // PRESERVE SPAWNED BY DEFAULT << data.spawntimesecsmax << ", " << uint32(GetGoAnimProgress()) << ", " << uint32(GetGoState()) << ", " << m_isActiveObject << ", " << m_visibilityModifier << ", " << 0 << ", " // patch_min << 10 << ")"; // patch_max WorldDatabase.BeginTransaction(); WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", GetGUIDLow()); WorldDatabase.PExecuteLog("%s", ss.str().c_str()); WorldDatabase.CommitTransaction(); } bool GameObject::LoadFromDB(uint32 guid, Map* map, bool force) { GameObjectData const* data = sObjectMgr.GetGOData(guid); if (!data) { sLog.Out(LOG_DBERROR, LOG_LVL_MINIMAL, "Gameobject (GUID: %u) not found in table `gameobject`, can't load. ", guid); return false; } if (!force && (data->spawn_flags & SPAWN_FLAG_DISABLED)) return false; uint32 entry = data->id; //uint32 map_id = data->position.mapId; // already used before call float x = data->position.x; float y = data->position.y; float z = data->position.z; float ang = data->position.o; float rotation0 = data->rotation0; float rotation1 = data->rotation1; float rotation2 = data->rotation2; float rotation3 = data->rotation3; uint32 animprogress = data->animprogress; GOState go_state = data->go_state; if (!Create(guid, entry, map, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state)) return false; if (!GetGOInfo()->GetDespawnPossibility() && !GetGOInfo()->IsDespawnAtAction() && data->spawntimesecsmin >= 0) { SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN); m_spawnedByDefault = true; m_respawnDelayTime = 0; m_respawnTime = 0; } else { if (data->spawntimesecsmin >= 0) { m_spawnedByDefault = true; m_respawnDelayTime = data->GetRandomRespawnTime(); m_respawnTime = map->GetPersistentState()->GetGORespawnTime(GetGUIDLow()); // ready to respawn if (m_respawnTime && m_respawnTime <= time(nullptr)) { m_respawnTime = 0; map->GetPersistentState()->SaveGORespawnTime(GetGUIDLow(), 0); } } else { m_spawnedByDefault = false; m_respawnDelayTime = -data->spawntimesecsmin; m_respawnTime = 0; } } if (data->spawn_flags & SPAWN_FLAG_ACTIVE) m_isActiveObject = true; if (data->visibility_mod) m_visibilityModifier = data->visibility_mod; // custom db change aka hack return true; } struct GameObjectRespawnDeleteWorker { explicit GameObjectRespawnDeleteWorker(uint32 guid) : i_guid(guid) {} void operator()(MapPersistentState* state) const { state->SaveGORespawnTime(i_guid, 0); } uint32 i_guid; }; void GameObject::DeleteFromDB() const { if (!HasStaticDBSpawnData()) { sLog.Out(LOG_BASIC, LOG_LVL_DEBUG, "Trying to delete not saved gameobject!"); return; } GameObjectRespawnDeleteWorker worker(GetGUIDLow()); sMapPersistentStateMgr.DoForAllStatesWithMapId(GetMapId(), GetInstanceId(), worker); sObjectMgr.DeleteGOData(GetGUIDLow()); WorldDatabase.PExecuteLog("DELETE FROM gameobject WHERE guid = '%u'", GetGUIDLow()); WorldDatabase.PExecuteLog("DELETE FROM game_event_gameobject WHERE guid = '%u'", GetGUIDLow()); WorldDatabase.PExecuteLog("DELETE FROM gameobject_battleground WHERE guid = '%u'", GetGUIDLow()); } /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ bool GameObject::HasQuest(uint32 quest_id) const { QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestRelationsMapBounds(GetEntry()); for (QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr) { if (itr->second == quest_id) return true; } return false; } bool GameObject::HasInvolvedQuest(uint32 quest_id) const { QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(GetEntry()); for (QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr) { if (itr->second == quest_id) return true; } return false; } bool GameObject::IsTransport() const { // If something is marked as a transport, don't transmit an out of range packet for it. GameObjectInfo const* gInfo = GetGOInfo(); if (!gInfo) return false; return gInfo->IsTransport(); } bool GameObject::IsMoTransport() const { GameObjectInfo const* gInfo = GetGOInfo(); if (!gInfo) return false; return gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT; } Unit* GameObject::GetOwner() const { if (ObjectGuid ownerid = GetOwnerGuid()) return ObjectAccessor::GetUnit(*this, ownerid); return nullptr; } Player* GameObject::GetAffectingPlayer() const { if (!GetOwnerGuid()) return nullptr; if (Unit* owner = GetOwner()) return owner->GetCharmerOrOwnerPlayerOrPlayerItself(); return nullptr; } void GameObject::SaveRespawnTime() { if (m_respawnTime > time(nullptr) && m_spawnedByDefault) GetMap()->GetPersistentState()->SaveGORespawnTime(GetGUIDLow(), m_respawnTime); } void GameObject::SetVisible(bool b) { if (m_visible == b) return; m_visible = b; UpdateObjectVisibility(); } bool GameObject::IsVisibleForInState(WorldObject const* pDetector, WorldObject const* viewPoint, bool inVisibleList) const { // Not in world if (!IsInWorld() || !pDetector->IsInWorld()) return false; // Transport always visible at this step implementation if (IsMoTransport() && IsInMap(pDetector)) return true; // quick check visibility false cases for non-GM-mode if (!pDetector->IsPlayer() || !static_cast<Player const*>(pDetector)->IsGameMaster()) { if (!IsVisible()) return false; // despawned and then not visible for non-GM in GM-mode if (!isSpawned()) return false; if (GetGOInfo()->IsServerOnly()) return false; if (Unit const* pDetectorUnit = pDetector->ToUnit()) { if (GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed && IsHostileTo(pDetectorUnit)) { if (!(pDetectorUnit->m_detectInvisibilityMask & (1 << 3))) // Detect Trap return false; } } } // check distance return IsWithinDistInMap(viewPoint, std::max(GetMap()->GetVisibilityDistance() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), GetVisibilityModifier()), false); } void GameObject::Respawn() { if (m_spawnedByDefault && m_respawnTime > 0) { m_respawnTime = time(nullptr); GetMap()->GetPersistentState()->SaveGORespawnTime(GetGUIDLow(), 0); } } bool GameObject::ActivateToQuest(Player const* pTarget) const { // if GO is ReqCreatureOrGoN for quest if (pTarget->HasQuestForGO(GetEntry())) return true; if (!sObjectMgr.IsGameObjectForQuests(GetEntry())) return false; switch (GetGoType()) { case GAMEOBJECT_TYPE_QUESTGIVER: { // Not fully clear when GO's can activate/deactivate // For cases where GO has additional (except quest itself), // these conditions are not sufficient/will fail. // Never expect flags|4 for these GO's? (NF-note: It doesn't appear it's expected) QuestRelationsMapBounds bounds = sObjectMgr.GetGOQuestRelationsMapBounds(GetEntry()); for (QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr) if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(itr->second)) if (pTarget->CanTakeQuest(qInfo, false)) return true; bounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(GetEntry()); for (QuestRelationsMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr) { if ((pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_INCOMPLETE || pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_COMPLETE) && !pTarget->GetQuestRewardStatus(itr->second)) return true; } break; } // scan GO chest with loot including quest items case GAMEOBJECT_TYPE_CHEST: { if (pTarget->GetQuestStatus(GetGOInfo()->chest.questId) == QUEST_STATUS_INCOMPLETE) return true; if (LootTemplates_Gameobject.HaveQuestLootForPlayer(GetGOInfo()->GetLootId(), pTarget)) { //look for battlegroundAV for some objects which are only activated after mine gots captured by own team // if (GetEntry() == BG_AV_OBJECTID_MINE_N || GetEntry() == BG_AV_OBJECTID_MINE_S) // if (BattleGround* bg = pTarget->GetBattleGround()) // if (bg->GetTypeID() == BATTLEGROUND_AV && !(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(GetEntry(), pTarget->GetTeam()))) // return false; return true; } break; } case GAMEOBJECT_TYPE_GENERIC: { if (pTarget->GetQuestStatus(GetGOInfo()->_generic.questID) == QUEST_STATUS_INCOMPLETE) return true; break; } case GAMEOBJECT_TYPE_SPELL_FOCUS: { if (pTarget->GetQuestStatus(GetGOInfo()->spellFocus.questID) == QUEST_STATUS_INCOMPLETE) return true; break; } case GAMEOBJECT_TYPE_GOOBER: { if (GetGOInfo()->goober.questId == -1 || pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE) return true; break; } default: break; } return false; } void GameObject::SummonLinkedTrapIfAny() { uint32 linkedEntry = GetGOInfo()->GetLinkedGameObjectEntry(); if (!linkedEntry) return; GameObject* linkedGO = new GameObject; if (!linkedGO->Create(GetMap()->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), linkedEntry, GetMap(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, GO_ANIMPROGRESS_DEFAULT, GO_STATE_READY)) { delete linkedGO; return; } linkedGO->SetRespawnTime(GetRespawnDelay()); linkedGO->SetSpellId(GetSpellId()); if (GetOwnerGuid()) { linkedGO->SetOwnerGuid(GetOwnerGuid()); linkedGO->SetUInt32Value(GAMEOBJECT_LEVEL, GetUInt32Value(GAMEOBJECT_LEVEL)); } GetMap()->Add(linkedGO); } void GameObject::TriggerLinkedGameObject(Unit* target) { uint32 trapEntry = GetGOInfo()->GetLinkedGameObjectEntry(); if (!trapEntry) return; GameObjectInfo const* trapInfo = sObjectMgr.GetGameObjectTemplate(trapEntry); if (!trapInfo || trapInfo->type != GAMEOBJECT_TYPE_TRAP) return; SpellEntry const* trapSpell = sSpellMgr.GetSpellEntry(trapInfo->trap.spellId); // The range to search for linked trap is weird. We set 0.5 as default. Most (all?) // traps are probably expected to be pretty much at the same location as the used GO, // so it appears that using range from spell is obsolete. float range = 0.5f; if (trapSpell) // checked at load already range = Spells::GetSpellMaxRange(sSpellRangeStore.LookupEntry(trapSpell->rangeIndex)); // search nearest linked GO GameObject* trapGO = nullptr; { // search closest with base of used GO, using max range of trap spell as search radius (why? See above) MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*this, trapEntry, range); MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(trapGO, go_check); Cell::VisitGridObjects(this, checker, range); } // found correct GO if (trapGO && trapGO->isSpawned()) trapGO->Use(target); } void GameObject::RespawnLinkedGameObject() { uint32 trapEntry = GetGOInfo()->GetLinkedGameObjectEntry(); if (!trapEntry) return; GameObjectInfo const* trapInfo = sObjectMgr.GetGameObjectTemplate(trapEntry); if (!trapInfo || trapInfo->type != GAMEOBJECT_TYPE_TRAP) return; float range = 0.5f; // search nearest linked GO GameObject* trapGO = nullptr; { // search closest with base of used GO, using max range of trap spell as search radius MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*this, trapEntry, range); MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(trapGO, go_check); Cell::VisitGridObjects(this, checker, range); } // Respawn the trap if (trapGO && !trapGO->isSpawned()) trapGO->Respawn(); } GameObject* GameObject::LookupFishingHoleAround(float range) { GameObject* ok = nullptr; MaNGOS::NearestGameObjectFishingHoleCheck u_check(*this, range); MaNGOS::GameObjectSearcher<MaNGOS::NearestGameObjectFishingHoleCheck> checker(ok, u_check); Cell::VisitGridObjects(this, checker, range); return ok; } void GameObject::ResetDoorOrButton() { if (m_lootState == GO_READY || m_lootState == GO_JUST_DEACTIVATED) return; SwitchDoorOrButton(false); SetLootState(GO_JUST_DEACTIVATED); m_cooldownTime = 0; } void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */) { // GO_NOT_READY: needed in OnGameObjectCreate if (m_lootState != GO_READY && m_lootState != GO_NOT_READY) return; if (!time_to_restore) time_to_restore = GetGOInfo()->GetAutoCloseTime(); SwitchDoorOrButton(true, alternative); SetLootState(GO_ACTIVATED); m_cooldownTime = time(nullptr) + time_to_restore; } void GameObject::SwitchDoorOrButton(bool activate, bool alternative /* = false */) { if (activate) SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); else RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); if (GetGoState() == GO_STATE_READY) //if closed -> open SetGoState(alternative ? GO_STATE_ACTIVE_ALTERNATIVE : GO_STATE_ACTIVE); else //if open -> close SetGoState(GO_STATE_READY); } void GameObject::Use(Unit* user) { // by default spell caster is user WorldObject* spellCaster = this; uint32 spellId = 0; bool triggered = false; // Nostalrius : Compatible avec les Unit comme caster. if (AI() && AI()->OnUse(user)) return; if (user->IsPlayer()) { if (m_goInfo->CannotBeUsedUnderImmunity() && user->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE)) return; if (!m_goInfo->IsUsableMounted() && user->IsMounted()) user->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED); if (sScriptMgr.OnGameObjectUse((Player*)user, this)) return; } // test only for exist cooldown data (cooldown timer used for door/buttons reset that not have use cooldown) if (uint32 cooldown = GetGOInfo()->GetCooldown()) { if (m_cooldownTime > sWorld.GetGameTime()) return; m_cooldownTime = sWorld.GetGameTime() + cooldown; } switch (GetGoType()) { case GAMEOBJECT_TYPE_DOOR: // 0 { //doors never really despawn, only reset to default state/flags UseDoorOrButton(); // activate script GetMap()->ScriptsStart(sGameObjectScripts, GetGUIDLow(), user->GetObjectGuid(), GetObjectGuid()); return; } case GAMEOBJECT_TYPE_BUTTON: // 1 { // add LOS requirement for Lever objects, like the ones inside sm cath/armory entrance if (GetDisplayId() == 295) if (!user->IsWithinLOSInMap(this, false)) return; //buttons never really despawn, only reset to default state/flags UseDoorOrButton(); // activate script GetMap()->ScriptsStart(sGameObjectScripts, GetGUIDLow(), user->GetObjectGuid(), GetObjectGuid()); TriggerLinkedGameObject(user); return; } case GAMEOBJECT_TYPE_QUESTGIVER: // 2 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (!sScriptMgr.OnGossipHello(player, this)) { player->PrepareGossipMenu(this, GetGOInfo()->questgiver.gossipID); player->SendPreparedGossip(this); } return; } case GAMEOBJECT_TYPE_CHEST: // 3 { if (user->GetTypeId() != TYPEID_PLAYER) return; if (GetFactionTemplateId() && !GetGOInfo()->chest.minSuccessOpens && !GetGOInfo()->chest.maxSuccessOpens) { std::list<Unit*> targets; MaNGOS::AnyFriendlyUnitInObjectRangeCheck check(this, 10.0f); MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(targets, check); Cell::VisitAllObjects(this, searcher, 10.0f); for (Unit* attacker : targets) { if (!attacker->IsInCombat() && !attacker->HasUnitState(UNIT_STATE_CAN_NOT_REACT_OR_LOST_CONTROL) && attacker->IsValidAttackTarget(user) && attacker->IsWithinLOSInMap(user) && attacker->AI()) attacker->AI()->AttackStart(user); } } GetMap()->ScriptsStart(sGameObjectScripts, GetGUIDLow(), user->GetObjectGuid(), GetObjectGuid()); TriggerLinkedGameObject(user); return; } case GAMEOBJECT_TYPE_GENERIC: // 5 { // No known way to exclude some - only different approach is to select despawnable GOs by Entry SetLootState(GO_JUST_DEACTIVATED); return; } case GAMEOBJECT_TYPE_TRAP: // 6 { // Currently we do not expect trap code below to be Use() // directly (except from spell effect). Code here will be called by TriggerLinkedGameObject. if (uint32 spellId = GetGOInfo()->trap.spellId) { if (Unit* pOwner = GetOwner()) pOwner->CastSpell(user, spellId, true, nullptr, nullptr, GetObjectGuid()); else CastSpell(user, spellId, true, nullptr, nullptr, GetObjectGuid()); } if (HasCustomAnim()) SendGameObjectCustomAnim(); if (uint32 max_charges = GetGOInfo()->GetCharges()) { AddUse(); if (m_useTimes >= max_charges) { m_useTimes = 0; SetLootState(GO_JUST_DEACTIVATED); } } return; } case GAMEOBJECT_TYPE_CHAIR: //7 Sitting: Wooden bench, chairs { GameObjectInfo const* info = GetGOInfo(); if (!info) return; if (user->GetTypeId() != TYPEID_PLAYER) return; if (!user->IsWithinLOSInMap(this, false)) return; // a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one float slotX, slotY; GetClosestChairSlotPosition(user->GetPositionX(), user->GetPositionY(), slotX, slotY); user->NearTeleportTo(slotX, slotY, GetPositionZ(), GetOrientation(), TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET); user->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR + info->chair.height); return; } case GAMEOBJECT_TYPE_SPELL_FOCUS: // 8 { TriggerLinkedGameObject(user); // some may be activated in addition? Conditions for this? (ex: entry 181616) break; } case GAMEOBJECT_TYPE_GOOBER: //10 { GameObjectInfo const* info = GetGOInfo(); if (user->GetTypeId() == TYPEID_PLAYER) { Player* player = (Player*)user; if (info->goober.pageId) // show page... { WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8); data << ObjectGuid(GetObjectGuid()); player->GetSession()->SendPacket(&data); } else if (info->goober.gossipID) // ...or gossip, if page does not exist { if (!sScriptMgr.OnGossipHello(player, this)) { player->PrepareGossipMenu(this, info->goober.gossipID); player->SendPreparedGossip(this); } } // possible quest objective for active quests if (info->goober.questId > 0 && sObjectMgr.GetQuestTemplate(info->goober.questId)) { //Quest require to be active for GO using if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE) break; } if (info->goober.eventId) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Goober ScriptStart id %u for GO entry %u (GUID %u).", info->goober.eventId, GetEntry(), GetGUIDLow()); if (!sScriptMgr.OnProcessEvent(info->goober.eventId, player, this, true)) GetMap()->ScriptsStart(sEventScripts, info->goober.eventId, player->GetObjectGuid(), GetObjectGuid()); } else GetMap()->ScriptsStart(sGameObjectScripts, GetGUIDLow(), user->GetObjectGuid(), GetObjectGuid()); // possible quest objective for active quests if (info->goober.questId > 0 && sObjectMgr.GetQuestTemplate(info->goober.questId)) { //Quest require to be active for GO using if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE) break; } player->RewardPlayerAndGroupAtCast(this); } TriggerLinkedGameObject(user); SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); SetLootState(GO_ACTIVATED); uint32 time_to_restore = info->GetAutoCloseTime(); // this appear to be ok, however others exist in addition to this that should have custom (ex: 190510, 188692, 187389) if (HasCustomAnim() || time_to_restore && info->goober.customAnim) SendGameObjectCustomAnim(); else SetGoState(GO_STATE_ACTIVE); m_cooldownTime = time(nullptr) + time_to_restore; // cast this spell later if provided spellId = info->goober.spellId; break; } case GAMEOBJECT_TYPE_CAMERA: //13 { GameObjectInfo const* info = GetGOInfo(); if (!info) return; if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (info->camera.cinematicId) player->SendCinematicStart(info->camera.cinematicId); if (info->camera.eventID) { if (!sScriptMgr.OnProcessEvent(info->camera.eventID, player, this, true)) GetMap()->ScriptsStart(sEventScripts, info->camera.eventID, player->GetObjectGuid(), GetObjectGuid()); } return; } case GAMEOBJECT_TYPE_FISHINGNODE: //17 fishing bobber { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (player->GetObjectGuid() != GetOwnerGuid()) return; switch (getLootState()) { case GO_READY: // ready for loot { // 1) skill must be >= base_zone_skill // 2) if skill == base_zone_skill => 5% chance // 3) chance is linear dependence from (base_zone_skill-skill) uint32 zone, subzone; GetZoneAndAreaId(zone, subzone); int32 zone_skill = sObjectMgr.GetFishingBaseSkillLevel(subzone); if (!zone_skill) zone_skill = sObjectMgr.GetFishingBaseSkillLevel(zone); //provide error, no fishable zone or area should be 0 if (!zone_skill) sLog.Out(LOG_DBERROR, LOG_LVL_MINIMAL, "Fishable areaId %u are not properly defined in `skill_fishing_base_level`.", subzone); int32 skill = player->GetSkillValue(SKILL_FISHING); int32 chance = skill - zone_skill + 5; int32 roll = irand(1, 100); sLog.Out(LOG_BASIC, LOG_LVL_DEBUG, "Fishing check (skill: %i zone min skill: %i chance %i roll: %i", skill, zone_skill, chance, roll); // normal chance bool success = skill >= zone_skill && chance >= roll; GameObject* fishingHole = nullptr; // overwrite fail in case fishhole if allowed (after 3.3.0) if (!success) { if (!sWorld.getConfig(CONFIG_BOOL_SKILL_FAIL_POSSIBLE_FISHINGPOOL)) { //TODO: find reasonable value for fishing hole search fishingHole = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE); if (fishingHole) success = true; } } // just search fishhole for success case else //TODO: find reasonable value for fishing hole search fishingHole = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE); if (success || sWorld.getConfig(CONFIG_BOOL_SKILL_FAIL_GAIN_FISHING)) player->UpdateFishingSkill(); // fish catch or fail and junk allowed (after 3.1.0) if (success || sWorld.getConfig(CONFIG_BOOL_SKILL_FAIL_LOOT_FISHING)) { // prevent removing GO at spell cancel player->RemoveGameObject(this, false); SetOwnerGuid(player->GetObjectGuid()); if (fishingHole) // will set at success only { fishingHole->Use(player); SetLootState(GO_JUST_DEACTIVATED); } else player->SendLoot(GetObjectGuid(), success ? LOOT_FISHING : LOOT_FISHING_FAIL); } else { // fish escaped, can be deleted now SetLootState(GO_JUST_DEACTIVATED); WorldPacket data(SMSG_FISH_ESCAPED, 0); player->GetSession()->SendPacket(&data); } break; } case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update break; default: { SetLootState(GO_JUST_DEACTIVATED); WorldPacket data(SMSG_FISH_NOT_HOOKED, 0); player->GetSession()->SendPacket(&data); break; } } player->FinishSpell(CURRENT_CHANNELED_SPELL); return; } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; GameObjectInfo const* info = GetGOInfo(); if (Unit* owner = GetOwner()) { if (owner->GetTypeId() != TYPEID_PLAYER) return; // accept only use by player from same group as owner, excluding owner itself (unique use already added in spell effect) if (player == (Player*)owner || (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(((Player*)owner)))) return; // expect owner to already be channeling, so if not... if (!owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) return; // in case summoning ritual caster is GO creator spellCaster = owner; } else { if (m_firstUser && player->GetObjectGuid() != m_firstUser && info->summoningRitual.castersGrouped) { if (Group* group = player->GetGroup()) { if (!group->IsMember(m_firstUser)) return; } else return; } spellCaster = player; } AddUniqueUse(player); // full amount unique participants including original summoner, need more if (GetUniqueUseCount() < info->summoningRitual.reqParticipants || !info->summoningRitual.spellId || GetGoState() == GO_STATE_ACTIVE) // spell already sent return; // owner is first user for non-wild GO objects, if it offline value already set to current user if (!GetOwnerGuid()) if (Player* firstUser = GetMap()->GetPlayer(m_firstUser)) spellCaster = firstUser; // Some have a visual effect SetGoState(GO_STATE_ACTIVE); spellId = info->summoningRitual.spellId; // spell have reagent and mana cost but it not expected use its // it triggered spell in fact casted at currently channeled GO triggered = true; // go to end function to spell casting break; } case GAMEOBJECT_TYPE_SPELLCASTER: //22 { SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); GameObjectInfo const* info = GetGOInfo(); if (!info) return; if (info->spellcaster.partyOnly) { Unit* caster = GetOwner(); if (!caster) { if (m_playerGroupId == 0) return; Group* group = ((Player*) user)->GetGroup(); if (!group) return; if (group->GetId() != m_playerGroupId) return; } else { if (caster->GetTypeId() != TYPEID_PLAYER) return; if (user->GetTypeId() != TYPEID_PLAYER || !((Player*)user)->IsInSameRaidWith((Player*)caster)) return; } } spellId = info->spellcaster.spellId; AddUse(); break; } case GAMEOBJECT_TYPE_MEETINGSTONE: //23 { // Should never be called for this type of object. // See WorldSession::HandleMeetingStoneJoinOpcode return; } #if SUPPORTED_CLIENT_BUILD > CLIENT_BUILD_1_5_1 case GAMEOBJECT_TYPE_FLAGSTAND: // 24 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (player->CanUseBattleGroundObject()) { // in battleground check BattleGround* bg = player->GetBattleGround(); if (!bg) return; // BG flag click // AB: // 15001 // 15002 // 15003 // 15004 // 15005 player->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); player->RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY); bg->EventPlayerClickedOnFlag(player, this); return; //we don't need to delete flag ... it is despawned! } break; } #endif #if SUPPORTED_CLIENT_BUILD > CLIENT_BUILD_1_6_1 case GAMEOBJECT_TYPE_FISHINGHOLE: // 25 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; player->SendLoot(GetObjectGuid(), LOOT_FISHINGHOLE); return; } #endif #if SUPPORTED_CLIENT_BUILD > CLIENT_BUILD_1_7_1 case GAMEOBJECT_TYPE_FLAGDROP: // 26 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (player->CanUseBattleGroundObject()) { GameObjectInfo const* info = GetGOInfo(); if (info && info->flagdrop.eventID) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "FlagDrop ScriptStart id %u for GO entry %u (GUID %u).", info->flagdrop.eventID, GetEntry(), GetGUIDLow()); if (!sScriptMgr.OnProcessEvent(info->flagdrop.eventID, player, this, true)) GetMap()->ScriptsStart(sEventScripts, info->flagdrop.eventID, player->GetObjectGuid(), GetObjectGuid()); } spellId = info->flagdrop.pickupSpell; } break; } #endif #if SUPPORTED_CLIENT_BUILD > CLIENT_BUILD_1_11_2 case GAMEOBJECT_TYPE_CAPTURE_POINT: // 29 { // Code here is not even halfway complete, and only added for further development. // Computer may very well blow up after stealing your bank accounts and wreck your car. // Use() object at own risk. GameObjectInfo const* info = GetGOInfo(); if (!info) return; // Can we expect that only player object are able to trigger a capture point or // could dummy creatures be involved? //if (user->GetTypeId() != TYPEID_PLAYER) //return; //Player* player = (Player*)user; // ID1 vs ID2 are possibly related to team. The world states should probably // control which event to be used. For this to work, we need a far better system for // sWorldStateMgr (system to store and keep track of states) so that we at all times // know the state of every part of the world. // Call every event, which is obviously wrong, but can help in further development. For // the time being script side can process events and determine which one to use. It // require of course that some object call go->Use() if (info->capturePoint.winEventID1) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.winEventID1, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.winEventID1, user->GetObjectGuid(), GetObjectGuid()); } if (info->capturePoint.winEventID2) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.winEventID2, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.winEventID2, user->GetObjectGuid(), GetObjectGuid()); } if (info->capturePoint.contestedEventID1) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.contestedEventID1, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.contestedEventID1, user->GetObjectGuid(), GetObjectGuid()); } if (info->capturePoint.contestedEventID2) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.contestedEventID2, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.contestedEventID2, user->GetObjectGuid(), GetObjectGuid()); } if (info->capturePoint.progressEventID1) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.progressEventID1, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.progressEventID1, user->GetObjectGuid(), GetObjectGuid()); } if (info->capturePoint.progressEventID2) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.progressEventID2, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.progressEventID2, user->GetObjectGuid(), GetObjectGuid()); } if (info->capturePoint.neutralEventID1) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.neutralEventID1, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.neutralEventID1, user->GetObjectGuid(), GetObjectGuid()); } if (info->capturePoint.neutralEventID2) { if (!sScriptMgr.OnProcessEvent(info->capturePoint.neutralEventID2, user, this, true)) GetMap()->ScriptsStart(sEventScripts, info->capturePoint.neutralEventID2, user->GetObjectGuid(), GetObjectGuid()); } // Some has spell, need to process those further. return; } #endif default: sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "GameObject::Use unhandled GameObject type %u (entry %u).", GetGoType(), GetEntry()); break; } if (!spellId) return; SpellEntry const* spellInfo = sSpellMgr.GetSpellEntry(spellId); if (!spellInfo) { sLog.Out(LOG_BASIC, LOG_LVL_ERROR, "WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u )", spellId, GetEntry(), GetGoType()); return; } // NOTE: Some of the spells used by GOs are considered triggered, but have cast times. // Ensure that the spell you are using, and any event it may trigger, is checking // pointer validity (i.e. instance, GO, etc) since the caster may have moved maps // or the GO might be gone by the time the spell is executed. Spell* spell = nullptr; if (Unit* pUnit = spellCaster->ToUnit()) spell = new Spell(pUnit, spellInfo, triggered, GetObjectGuid()); else if (GameObject* pGo = spellCaster->ToGameObject()) spell = new Spell(pGo, spellInfo, triggered, GetObjectGuid()); else return; SpellCastTargets targets; // If summoning ritual GO use the summon target instead if (GetGoType() == GAMEOBJECT_TYPE_SUMMONING_RITUAL) { Player* summonTarget = nullptr; // Only player summoning requires a target if (GetEntry() == 36727 && getSummonTarget()) { summonTarget = sObjectMgr.GetPlayer(getSummonTarget()); targets.setUnitTarget(summonTarget); } // Object coordinates are needed later targets.setGOTarget(this); } else targets.setUnitTarget(user); spell->prepare(std::move(targets)); } // overwrite WorldObject function for proper name localization char const* GameObject::GetNameForLocaleIdx(int32 loc_idx) const { if (loc_idx >= 0) { GameObjectLocale const* cl = sObjectMgr.GetGameObjectLocale(GetEntry()); if (cl) { if (cl->Name.size() > (size_t)loc_idx && !cl->Name[loc_idx].empty()) return cl->Name[loc_idx].c_str(); } } return GameObject::GetName(); } void GameObject::UpdateRotationFields(float rotation2 /*=0.0f*/, float rotation3 /*=0.0f*/) { static double const atan_pow = atan(pow(2.0f, -20.0f)); double f_rot1 = sin(GetOrientation() / 2.0f); double f_rot2 = cos(GetOrientation() / 2.0f); int64 i_rot1 = int64(f_rot1 / atan_pow * (f_rot2 >= 0 ? 1.0f : -1.0f)); int64 rotation = i_rot1 & 0x00000000001FFFFF; //float f_rot2 = std::sin(0.0f / 2.0f); //int64 i_rot2 = f_rot2 / atan(pow(2.0f, -20.0f)); //rotation |= (((i_rot2 << 22) >> 32) >> 11) & 0x000003FFFFE00000; //float f_rot3 = std::sin(0.0f / 2.0f); //int64 i_rot3 = f_rot3 / atan(pow(2.0f, -21.0f)); //rotation |= (i_rot3 >> 42) & 0x7FFFFC0000000000; m_rotation = rotation; if (rotation2 == 0.0f && rotation3 == 0.0f) { rotation2 = (float)f_rot1; rotation3 = (float)f_rot2; } SetFloatValue(GAMEOBJECT_ROTATION + 2, rotation2); SetFloatValue(GAMEOBJECT_ROTATION + 3, rotation3); } bool GameObject::IsHostileTo(WorldObject const* target) const { // always non-hostile to GM in GM mode if (target->GetTypeId() == TYPEID_PLAYER && ((Player const*)target)->IsGameMaster()) return false; // test owner instead if have if (Unit const* owner = GetOwner()) return owner->IsHostileTo(target); if (Unit const* pUnitTarget = target->ToUnit()) { if (Unit const* targetOwner = pUnitTarget->GetCharmerOrOwner()) return IsHostileTo(targetOwner); } // for not set faction case (wild object) use hostile case if (!GetGOInfo()->faction) return true; // faction base cases FactionTemplateEntry const*tester_faction = GetFactionTemplateEntry(); FactionTemplateEntry const*target_faction = target->GetFactionTemplateEntry(); if (!tester_faction || !target_faction) return false; // GvP forced reaction and reputation case if (target->GetTypeId() == TYPEID_PLAYER) { // forced reaction if (tester_faction->faction) { if (ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction)) return *force <= REP_HOSTILE; // apply reputation state FactionEntry const* raw_tester_faction = sObjectMgr.GetFactionEntry(tester_faction->faction); if (raw_tester_faction && raw_tester_faction->reputationListID >= 0) return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE; } } // common faction based case (GvC,GvP) return tester_faction->IsHostileTo(*target_faction); } bool GameObject::IsFriendlyTo(WorldObject const* target) const { // always friendly to GM in GM mode if (target->GetTypeId() == TYPEID_PLAYER && ((Player const*)target)->IsGameMaster()) return true; // test owner instead if have if (Unit const* owner = GetOwner()) return owner->IsFriendlyTo(target); if (Unit const* pUnitTarget = target->ToUnit()) { if (Unit const* targetOwner = pUnitTarget->GetCharmerOrOwner()) return IsFriendlyTo(targetOwner); } // for not set faction case (wild object) use hostile case if (!GetGOInfo()->faction) return false; // faction base cases FactionTemplateEntry const*tester_faction = GetFactionTemplateEntry(); FactionTemplateEntry const*target_faction = target->GetFactionTemplateEntry(); if (!tester_faction || !target_faction) return false; // GvP forced reaction and reputation case if (target->GetTypeId() == TYPEID_PLAYER) { // forced reaction if (tester_faction->faction) { if (ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction)) return *force >= REP_FRIENDLY; // apply reputation state if (FactionEntry const* raw_tester_faction = sObjectMgr.GetFactionEntry(tester_faction->faction)) if (raw_tester_faction->reputationListID >= 0) return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY; } } // common faction based case (GvC,GvP) return tester_faction->IsFriendlyTo(*target_faction); } bool GameObject::IsUseRequirementMet() const { if (GameObjectUseRequirement const* req = sObjectMgr.GetGameObjectUseRequirement(GetObjectGuid())) { switch (req->reqType) { case GameObjectUseRequirement::GOBJ_REQUIRE_DEAD_CREATURE: if (Creature* crea = GetMap()->GetCreature(req->guid)) if (crea->IsAlive()) return false; break; case GameObjectUseRequirement::GOBJ_REQUIRE_ACTIVE_OBJECT: if (GameObject* gobjRequired = GetMap()->GetGameObject(req->guid)) if (gobjRequired->GetGoState() != GO_STATE_ACTIVE) return false; break; } } return true; } bool GameObject::PlayerCanUse(Player* pPlayer) { if (pPlayer->IsGameMaster()) return true; if (!IsVisible()) return false; GameObjectInfo const* pInfo = GetGOInfo(); if (!pInfo) return false; switch (pInfo->type) { case GAMEOBJECT_TYPE_DOOR: { // Check lockId uint32 lockId = pInfo->GetLockId(); if (lockId != 0) { LockEntry const* lockInfo = sLockStore.LookupEntry(lockId); if (!lockInfo) return false; for (int j = 0; j < 8; ++j) { switch (lockInfo->Type[j]) { // check key item (many fit cases can be) case LOCK_KEY_ITEM: { if (lockInfo->Index[j]) { if (!pPlayer->HasItemCount(lockInfo->Index[j], 1)) return false; } break; } } } } break; } case GAMEOBJECT_TYPE_CHAIR: { float x, y; GetClosestChairSlotPosition(pPlayer->GetPositionX(), pPlayer->GetPositionY(), x, y); if (pPlayer->GetDistance(x, y, GetPositionZ(), SizeFactor::None) > MAX_SITCHAIRUSE_DISTANCE) return false; break; } } return IsUseRequirementMet(); } void GameObject::SetLootState(LootState state) { if (state == GO_JUST_DEACTIVATED && GetGoType() == GAMEOBJECT_TYPE_CHEST) { m_cooldownTime = 0; } m_lootState = state; UpdateCollisionState(); } void GameObject::SetGoState(GOState state) { //SetByteValue(GAMEOBJECT_BYTES_1, 0, state); // 3.3.5 SetUInt32Value(GAMEOBJECT_STATE, state); UpdateCollisionState(); } void GameObject::SetDisplayId(uint32 modelId) { SetUInt32Value(GAMEOBJECT_DISPLAYID, modelId); UpdateModel(); } float GameObject::GetObjectBoundingRadius() const { // 1.12.1 GameObjectDisplayInfo.dbc not have any info related to size return DEFAULT_WORLD_OBJECT_SIZE; } bool GameObject::IsInSkillupList(Player const* player) const { return m_SkillupSet.find(player->GetObjectGuid()) != m_SkillupSet.end(); } void GameObject::AddToSkillupList(Player const* player) { m_SkillupSet.insert(player->GetObjectGuid()); } struct AddGameObjectToRemoveListInMapsWorker { AddGameObjectToRemoveListInMapsWorker(ObjectGuid guid) : i_guid(guid) {} void operator()(Map* map) { if (GameObject* pGameobject = map->GetGameObject(i_guid)) pGameobject->AddObjectToRemoveList(); } ObjectGuid i_guid; }; void GameObject::AddToRemoveListInMaps(uint32 db_guid, GameObjectData const* data) { AddGameObjectToRemoveListInMapsWorker worker(ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, db_guid)); sMapMgr.DoForAllMapsWithMapId(data->position.mapId, worker); } struct SpawnGameObjectInMapsWorker { SpawnGameObjectInMapsWorker(uint32 guid, GameObjectData const* data) : i_guid(guid), i_data(data) {} void operator()(Map* map) { // Spawn if necessary (loaded grids only) if (map->IsLoaded(i_data->position.x, i_data->position.y)) { ObjectGuid guid(HIGHGUID_GAMEOBJECT, i_data->id, i_guid); if (GameObject* go = map->GetGameObject(guid)) { sLog.Out(LOG_BASIC, LOG_LVL_MINIMAL, "[CRASH] Spawning already spawned Gobj ! GUID=%u", i_guid); return; } GameObjectData const* data = sObjectMgr.GetGOData(i_guid); MANGOS_ASSERT(data); GameObject* pGameobject = GameObject::CreateGameObject(data->id); //sLog.Out(LOG_BASIC, LOG_LVL_DEBUG, "Spawning gameobject %u", *itr); if (!pGameobject->LoadFromDB(i_guid, map)) delete pGameobject; else { //if (pGameobject->isSpawnedByDefault()) map->Add(pGameobject); //else // delete pGameobject; } } } uint32 i_guid; GameObjectData const* i_data; }; void GameObject::SpawnInMaps(uint32 db_guid, GameObjectData const* data) { SpawnGameObjectInMapsWorker worker(db_guid, data); sMapMgr.DoForAllMapsWithMapId(data->position.mapId, worker); } bool GameObject::HasStaticDBSpawnData() const { return sObjectMgr.GetGOData(GetGUIDLow()) != nullptr; } void GameObject::UpdateCollisionState() { if (!m_model || !IsInWorld()) return; bool enabled = GetGoType() == GAMEOBJECT_TYPE_CHEST ? getLootState() == GO_READY : GetGoState() == GO_STATE_READY; m_model->enable(enabled); } void GameObject::UpdateModel() { if (m_model) { if (IsInWorld() && GetMap()->ContainsGameObjectModel(*m_model)) GetMap()->RemoveGameObjectModel(*m_model); delete m_model; } m_model = GameObjectModel::construct(this); if (m_model && IsInWorld()) GetMap()->InsertGameObjectModel(*m_model); } void GameObject::UpdateModelPosition() { if (!m_model) return; if (GetMap()->ContainsGameObjectModel(*m_model)) { GetMap()->RemoveGameObjectModel(*m_model); m_model->Relocate(*this); GetMap()->InsertGameObjectModel(*m_model); } } void GameObject::GetLosCheckPosition(float& x, float& y, float& z) const { if (GameObjectDisplayInfoAddon const* displayInfo = sGameObjectDisplayInfoAddonStorage.LookupEntry<GameObjectDisplayInfoAddon>(GetDisplayId())) { if (displayInfo->min_x || displayInfo->min_y || displayInfo->min_z || displayInfo->max_x || displayInfo->max_y || displayInfo->max_z) { float scale = GetObjectScale(); float minX = displayInfo->min_x * scale; float minY = displayInfo->min_y * scale; float minZ = displayInfo->min_z * scale; float maxX = displayInfo->max_x * scale; float maxY = displayInfo->max_y * scale; float maxZ = displayInfo->max_z * scale; QuaternionData worldRotation = GetLocalRotation(); G3D::Quat worldRotationQuat(worldRotation.x, worldRotation.y, worldRotation.z, worldRotation.w); auto pos = G3D::CoordinateFrame{ { worldRotationQuat },{ GetPositionX(), GetPositionY(), GetPositionZ() } } .toWorldSpace(G3D::Box{ { minX, minY, minZ },{ maxX, maxY, maxZ } }).center(); x = pos.x; y = pos.y; z = pos.z; return; } } if (m_model) { auto pos = m_model->getBounds().center(); x = pos.x; y = pos.y; z = pos.z; return; } GetPosition(x, y, z); z += 1.0f; } GameObjectData const* GameObject::GetGOData() const { return sObjectMgr.GetGOData(GetGUIDLow()); } bool GameObject::HasCustomAnim() const { switch (GetDisplayId()) { case 2570: // eternal flame case 3071: // freezing trap case 3072: // explosive trap case 3073: // frost trap, fixed trap case 3074: // immolation trap case 4392: // lava fissure case 4472: // lava fissure case 4491: // mortar in dun morogh case 6785: // plague fissure case 6747: // sapphiron birth case 6871: // Silithyst bring in return true; } return false; } void GameObject::SendGameObjectCustomAnim(uint32 animId /*= 0*/) { WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM, 8 + 4); data << GetObjectGuid(); data << uint32(animId); SendMessageToSet(&data, true); } void GameObject::SendGameObjectReset() { WorldPacket data(SMSG_GAMEOBJECT_RESET_STATE, 8); data << GetObjectGuid(); SendMessageToSet(&data, true); } void GameObject::Despawn() { SendObjectDeSpawnAnim(); if (GameObjectData const* data = GetGOData()) { if (m_spawnedByDefault) { // TODO: Research this more. Some GOBJs don't set a respawn delay time, but call ::Despawn // If this happens, they will respawn instantly which is most likely undesired behaviour uint32 respawnTime = GetRespawnDelay(); if (!respawnTime) respawnTime = data->GetRandomRespawnTime(); SetRespawnTime(respawnTime); } else { m_respawnTime = 0; m_respawnDelayTime = data->spawntimesecsmin < 0 ? -data->spawntimesecsmin : data->spawntimesecsmin; } } else AddObjectToRemoveList(); } uint32 GameObject::GetLevel() const { uint32 level = 0; switch (GetGOInfo()->type) { case GAMEOBJECT_TYPE_CHEST: level = GetGOInfo()->chest.level; break; case GAMEOBJECT_TYPE_TRAP: level = GetGOInfo()->trap.level; break; } if (!level) level = GetUInt32Value(GAMEOBJECT_LEVEL); return level > 0 ? level : PLAYER_MAX_LEVEL; } bool GameObject::IsAtInteractDistance(Player const* player, uint32 maxRange) const { SpellEntry const* spellInfo; if (maxRange || (spellInfo = GetSpellForLock(player))) { if (maxRange == 0.f) { SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex); maxRange = srange ? srange->maxRange : 0; } if (GetGoType() == GAMEOBJECT_TYPE_SPELL_FOCUS) return maxRange >= GetDistance3dToCenter(player); if (sGameObjectDisplayInfoStore.LookupEntry(GetGOInfo()->displayId)) return IsAtInteractDistance(player->GetPosition(), maxRange); } return IsAtInteractDistance(player->GetPosition(), GetGOInfo()->GetInteractionDistance()); } void GameObject::GetClosestChairSlotPosition(float userX, float userY, float& outX, float& outY) const { // check if the db is sane if (GetGOInfo()->chair.slots > 0) { float lowestDist = DEFAULT_VISIBILITY_DISTANCE; float x_lowest = GetPositionX(); float y_lowest = GetPositionY(); // the object orientation + 1/2 pi // every slot will be on that straight line float orthogonalOrientation = GetOrientation() + M_PI_F * 0.5f; // find nearest slot for (uint32 i = 0; i < GetGOInfo()->chair.slots; ++i) { // the distance between this slot and the center of the go - imagine a 1D space float relativeDistance = (GetGOInfo()->size * i) - (GetGOInfo()->size * (GetGOInfo()->chair.slots - 1) / 2.0f); float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation); float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation); // calculate the distance between the user and this slot float thisDistance = Geometry::GetDistance2D(userX, userY, x_i, y_i); /* debug code. It will spawn a npc on each slot to visualize them. Creature* helper = SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000); std::ostringstream output; output << i << ": thisDist: " << thisDistance; helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL); */ if (thisDistance <= lowestDist) { lowestDist = thisDistance; x_lowest = x_i; y_lowest = y_i; } } outX = x_lowest; outY = y_lowest; return; } outX = GetPositionX(); outY = GetPositionY(); } bool GameObject::IsAtInteractDistance(Position const& pos, float radius) const { if (GameObjectDisplayInfoAddon const* displayInfo = sGameObjectDisplayInfoAddonStorage.LookupEntry<GameObjectDisplayInfoAddon>(GetDisplayId())) { float scale = GetObjectScale(); float minX = displayInfo->min_x * scale - radius; float minY = displayInfo->min_y * scale - radius; float minZ = displayInfo->min_z * scale - radius; float maxX = displayInfo->max_x * scale + radius; float maxY = displayInfo->max_y * scale + radius; float maxZ = displayInfo->max_z * scale + radius; QuaternionData worldRotation = GetLocalRotation(); G3D::Quat worldRotationQuat(worldRotation.x, worldRotation.y, worldRotation.z, worldRotation.w); return G3D::CoordinateFrame{ { worldRotationQuat },{ GetPositionX(), GetPositionY(), GetPositionZ() } } .toWorldSpace(G3D::Box{ { minX, minY, minZ },{ maxX, maxY, maxZ } }) .contains({ pos.x, pos.y, pos.z }); } return GetDistance3dToCenter(pos) <= radius; } SpellEntry const* GameObject::GetSpellForLock(Player const* player) const { if (!player) return nullptr; uint32 lockId = GetGOInfo()->GetLockId(); if (!lockId) return nullptr; LockEntry const* lock = sLockStore.LookupEntry(lockId); if (!lock) return nullptr; for (uint8 i = 0; i < MAX_LOCK_CASE; ++i) { if (!lock->Type[i]) continue; if (lock->Type[i] != LOCK_KEY_SKILL) break; for (auto&& playerSpell : player->GetSpellMap()) if (SpellEntry const* spellInfo = sSpellMgr.GetSpellEntry(playerSpell.first)) for (uint8 i = 0; i < MAX_EFFECT_INDEX; ++i) if (spellInfo->Effect[i] == SPELL_EFFECT_OPEN_LOCK && ((uint32)spellInfo->EffectMiscValue[i]) == lock->Index[i]) if (player->CalculateSpellEffectValue(nullptr, spellInfo, SpellEffectIndex(i), nullptr) >= int32(lock->Skill[i])) return spellInfo; } return nullptr; } const QuaternionData GameObject::GetLocalRotation() const { return QuaternionData(GetFloatValue(GAMEOBJECT_ROTATION), GetFloatValue(GAMEOBJECT_ROTATION + 1), GetFloatValue(GAMEOBJECT_ROTATION + 2), GetFloatValue(GAMEOBJECT_ROTATION + 3)); }
1
0.95235
1
0.95235
game-dev
MEDIA
0.984417
game-dev
0.969051
1
0.969051
reinforcement-learning-kr/Unity_ML_Agents_2.0
2,372
unity_project/Drone/Packages/com.unity.ml-agents/Runtime/MLAgentsSettingsManager.cs
using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #else using System.Linq; #endif namespace Unity.MLAgents { #if UNITY_EDITOR [InitializeOnLoad] #endif internal static class MLAgentsSettingsManager { internal static event Action OnSettingsChange; internal const string EditorBuildSettingsConfigKey = "com.unity.ml-agents.settings"; private static MLAgentsSettings s_Settings; // setter will trigger callback for refreshing editor UI if using editor public static MLAgentsSettings Settings { get { if (s_Settings == null) { Initialize(); } return s_Settings; } set { Debug.Assert(value != null); #if UNITY_EDITOR if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(value))) { EditorBuildSettings.AddConfigObject(EditorBuildSettingsConfigKey, value, true); } #endif s_Settings = value; ApplySettings(); } } static MLAgentsSettingsManager() { Initialize(); } static void Initialize() { #if UNITY_EDITOR InitializeInEditor(); #else InitializeInPlayer(); #endif } #if UNITY_EDITOR internal static void InitializeInEditor() { var settings = ScriptableObject.CreateInstance<MLAgentsSettings>(); if (EditorBuildSettings.TryGetConfigObject(EditorBuildSettingsConfigKey, out MLAgentsSettings settingsAsset)) { if (settingsAsset != null) { settings = settingsAsset; } } Settings = settings; } #else internal static void InitializeInPlayer() { Settings = Resources.FindObjectsOfTypeAll<MLAgentsSettings>().FirstOrDefault() ?? ScriptableObject.CreateInstance<MLAgentsSettings>(); } #endif internal static void ApplySettings() { OnSettingsChange?.Invoke(); } internal static void Destroy() { s_Settings = null; OnSettingsChange = null; } } }
1
0.791004
1
0.791004
game-dev
MEDIA
0.698601
game-dev,graphics-rendering
0.763249
1
0.763249
RLBot/RLBot
2,086
src/main/java/rlbot/gamestate/DesiredVector3.java
package rlbot.gamestate; import com.google.flatbuffers.FlatBufferBuilder; import rlbot.flat.Vector3Partial; /** * See https://github.com/RLBot/RLBotJavaExample/wiki/Manipulating-Game-State */ public class DesiredVector3 { private Float x; private Float y; private Float z; public DesiredVector3() { } public DesiredVector3(Float x, Float y, Float z) { this.x = x; this.y = y; this.z = z; } public DesiredVector3(rlbot.flat.Vector3 vector) { this.x = vector.x(); this.y = vector.y(); this.z = vector.z(); } public Float getX() { return x; } /** * @return {@code true} If x is not null. */ public boolean hasX() { return x != null; } public DesiredVector3 withX(Float x) { this.x = x; return this; } public Float getY() { return y; } /** * @return {@code true} If y is not null. */ public boolean hasY() { return y != null; } public DesiredVector3 withY(Float y) { this.y = y; return this; } public Float getZ() { return z; } /** * @return {@code true} If z is not null. */ public boolean hasZ() { return z != null; } public DesiredVector3 withZ(Float z) { this.z = z; return this; } /** * You may wish to override this in order to invert the x value, which would give you a normal * right-handed coordinate system. */ public int toFlatbuffer(FlatBufferBuilder builder) { Vector3Partial.startVector3Partial(builder); if (hasX()) { Vector3Partial.addX(builder, rlbot.flat.Float.createFloat(builder, getX())); } if (hasY()) { Vector3Partial.addY(builder, rlbot.flat.Float.createFloat(builder, getY())); } if (hasZ()) { Vector3Partial.addZ(builder, rlbot.flat.Float.createFloat(builder, getZ())); } return Vector3Partial.endVector3Partial(builder); } }
1
0.674776
1
0.674776
game-dev
MEDIA
0.762291
game-dev,graphics-rendering
0.888505
1
0.888505
Oric-Software-Development-Kit/Oric-Software
4,080
users/twilighte/Wurlde/SSC_Modules/SSCM-OM0S6.S
;SSCM-OM0S6.S FOUTAIN AND STATUE - FOUNTAIN.MEM ON WURLDE.DSK ;1) statue peeing in fountain #include "..\gamecode\WurldeDefines.s" #include "..\gamecode\SSCModuleHeader.s" .zero *=$00 #include "..\gamecode\ZeroPage.s" .text *=$C000 ;************************** ScreenSpecificCodeBlock jmp ScreenInit ;C000 ;Run immediately after SSC(This file) is loaded jmp ScreenRun ;C003 ;Run during a game cycle jmp CollisionDetection ;C006 ;Run during game cycle and parsed Collision Type in A jmp ProcAction ;C009 ;Called when Recognised Key Pressed jmp Spare ;C00C jmp Spare ;C00F jmp Spare ;C012 jmp Spare ;C015 ScreenProseVector .byt <ScreenProse,>ScreenProse ;C018 ScreenNameVector .byt <ScreenName,>ScreenName ;C01A ScreenRules .byt %10001100 ;C01C LocationID .byt 7 ;C01D RecognisedAction .byt %00010000 ;C01E CollisionType .byt 0 ;C01F CollisionTablesVector .byt <ct_CeilingLevel,>ct_CeilingLevel ;C020 ScreenInlayVector .byt <ScreenInlay,>ScreenInlay ;C022 EnteringTextVector ;Enter Boat .byt 0,0 ;C024 InteractionHeaderVector ;This SSC has no meeting place so 0 must be written to high address .byt 0,0 ;C026 CharacterList ; .byt 0,0 ;C028 CharacterInfo .byt 0,0 ;C02A ;************************** ;Collision tables(120) always exist in first page of C000 ct_CeilingLevel .dsb 40,128 ct_FloorLevel .dsb 40,128 ct_BGCollisions .dsb 40,0 ScreenInlay #include "INLAY-OM0S6.s" ; #include "SSC_CommonCode.s" ScreenProse ;Up to 37x7 characters ; *********************************** .byt "The fountain is thought to restore%" .byt "health and beauty, its statue ever%" .byt "cycling the clear water within from%" .byt "an unseen spring deep below. The%" .byt "garden is peaceful and tranquil in%" .byt "stark contrast to lands west of%" .byt "here.]" ScreenName ;Always 13 characters long ; ************* .byt "MONUMENT]" ;Or "Wizards Glen" ScreenInit jsr InitialiseHero Spare rts ;Parsed ;SideApproachFlag Hero Appears on Left(0) or Right(1) InitialiseHero ;For this screen.. lda SideApproachFlag .( bne InitHero4Right ;Set initial hero sprite frame lda #98 sta HeroSprite ;Set Hero X to left ldx #3 stx HeroX ;Set hero y to land contour lda ct_FloorLevel,x sec sbc #9 sta HeroY ;Set other stuff lda #3 sta SpriteWidth lda #9 sta SpriteHeight ;Set initial action to stand right lda #hcStandRight sta HeroAction rts InitHero4Right .) lda #105 sta HeroSprite ;Game start (For Map02) parameters ldx #34 stx HeroX ;Set hero y to land contour lda ct_FloorLevel,x sec sbc #09 sta HeroY ;Set a few defaults lda #3 sta SpriteWidth lda #9 sta SpriteHeight ;Set initial Action lda #hcStandLeft sta HeroAction rts ;Called from DetectFloorAndCollisions in hero.s when the floortable(A) contains ;0,64,128,192 depending on collision(9,10,11,12) ;For M2S5 it is unused ; ;Returned ;Carry Set when move prohibited CollisionDetection ;For this screen we need to store 9(2 places) where the hero may board the boat sta CollisionFound rts CollisionFound .byt 0 ScreenRun jsr ProcDBird jsr GenerateFountain rts ;When the hero performs a recognised action this routine is called ;ProcAction ; ; ProcAction ;Action key pressed (board boat) - check CollisionFound lda CollisionFound ;.( ; beq skip1 ; ;Hero over right place and action pressed so trigger board boat sequence ; ;by disabling hero control.. ; lda ssc_ScreenRules ; ora #%00000001 ; sta ssc_ScreenRules ; ;Freezing Boat Rock ; lda #00 ; sta RockFlag ; ;Triggering Board Animation ; lda #01 ; sta BoardingFlag ; lda #00 ; sta BoardingIndex ;skip1 clc ;.) rts dbird_count .byt 7 ;3 to 15 dbird_MaximumY .byt 38 dbird_LeftStartX .byt 6 dbird_RightStartX .byt 171 dbird_HeightRange .byt 20 dbird_StartY .byt 8 dbird_DefaultLeftBG .byt 127 dbird_DefaultRightBG .byt 64 #include "DistantBirds.s" fountain_count .byt 31 fountain_xorigin .byt 99 fountain_yorigin .byt 45 fountain_ground .byt 51 ;-1 of real ground #include "fountain.s"
1
0.896587
1
0.896587
game-dev
MEDIA
0.976117
game-dev
0.834634
1
0.834634
holycake/mhsj
3,318
daemon/skill/changquan.c
//长拳 changquan.c //menpai skill(can also be used by non-menpai NPCs) inherit SKILL; mapping *action = ({ ([ "action": "只见$N身形一矮,大喝声中一个「冲天炮」对准$n的鼻子呼!地砸了过去", "dodge": 5, "parry": 5, "force": 90, "damage_type": "砸伤" ]), ([ "action": "$N左手一分,右拳运气,一招「拔草寻蛇」便往$n的$l招呼过去", "dodge": 5, "parry": 5, "force": 60, "damage_type": "瘀伤" ]), ([ "action": "$N右拳在$n面门一晃,左掌使了个「叶底偷桃」往$n的$l狠命一抓", "dodge": 5, "parry": 5, "force": 60, "damage_type": "抓伤" ]), ([ "action": "$N步履一沉,左拳拉开,右拳带风,一招「黑虎掏心」势不可挡地击向$n$l", "dodge": 5, "parry": 5, "force": 80, "damage_type": "瘀伤" ]), ([ "action": "只见$N拉开架式,一招「双风贯耳」使得虎虎有风。底下却飞起一脚踢向$n$l", "dodge": 5, "parry": 5, "force": 70, "damage_type": "瘀伤" ]), ([ "action": "$N打得兴起,大喝一声:看我这招「龙虎相交」!\n左手往$n身后一抄,右拳便往$n面门砸了过去", "dodge": 5, "parry": 5, "force": 120, "damage_type": "砸伤" ]), ([ "action": "$N拉开后弓步,双掌使了个「如封似闭」往$n的$l一推", "dodge": 5, "parry": 5, "force": 50, "damage_type": "瘀伤" ]), ([ "action": "只见$N运足气力,一连三拳击向$n$l,力道一拳高过一拳!\n这一招的名字还相当高雅,叫作「阳关三叠」", "dodge": 5, "parry": 5, "force": 80, "damage_type": "瘀伤" ]), ([ "action": "$N往后一纵,就势使了个「老树盘根」,右腿扫向$n的$l", "dodge": 5, "parry": 5, "force": 50, "damage_type": "砸伤" ]), ([ "action": "$N一个转身,左掌护胸,右掌反手使了个「独劈华山」往$n当头一劈", "dodge": 5, "parry": 5, "force": 90, "damage_type": "砸伤" ]), ([ "action": "$N飞身跃起,半空中一脚踢向$n面门,却是个虚招。\n说时迟那时快,只见$N一个倒翻,双掌已到了$n的$l", "dodge": 5, "parry": 5, "force": 100, "damage_type": "瘀伤" ]), }); int valid_learn(object me) { if( me->query_temp("weapon") || me->query_temp("secondary_weapon") ) return notify_fail("练长拳必须空手。\n"); return 1; } int valid_enable(string usage) { return usage=="unarmed"; } mapping query_action(object me, object weapon) { return action[random(sizeof(action))]; } int practice_skill(object me) { if( (int)me->query("sen") < 30) return notify_fail("你的精神无法集中了,休息一下再练吧。\n"); if( (int)me->query("kee") < 30 ) return notify_fail("你现在手足酸软,休息一下再练吧。\n"); if( (int)me->query("force") < 10 ) return notify_fail("你的内力不够了。\n"); me->receive_damage("kee", 30); me->add("force", -10); return 1; } string perform_action_file(string func) { return CLASS_D("fighter") + "/changquan/"+func; }
1
0.852273
1
0.852273
game-dev
MEDIA
0.949813
game-dev
0.521058
1
0.521058
pedrovgs/AndroidGameBoyEmulator
1,721
app/src/main/java/com/github/pedrovgs/androidgameboyemulator/core/processor/isa/RotateLeft8Bit.java
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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.github.pedrovgs.androidgameboyemulator.core.processor.isa; import com.github.pedrovgs.androidgameboyemulator.core.mmu.MMU; import com.github.pedrovgs.androidgameboyemulator.core.processor.GBZ80; abstract class RotateLeft8Bit extends Instruction { RotateLeft8Bit(GBZ80 z80) { super(z80); } RotateLeft8Bit(GBZ80 z80, MMU mmu) { super(z80, mmu); } @Override public void execute() { boolean wasCyEnabled = z80.isFlagCYEnabled(); byte registerValue = loadByte(); byte newRegisterValue = (byte) (registerValue << 1); z80.resetFlagF(); if (wasCyEnabled) { newRegisterValue |= 0x1; } if ((registerValue >> 7 & 0x1) == 0x1) { z80.enableFlagCY(); } if (newRegisterValue == 0) { z80.enableFlagZ(); } storeValue(newRegisterValue); setLastInstructionExecutionTime(); } protected abstract byte loadByte(); protected abstract void storeValue(byte value); protected abstract void setLastInstructionExecutionTime(); }
1
0.637234
1
0.637234
game-dev
MEDIA
0.426149
game-dev
0.708554
1
0.708554
stephengold/Libbulletjme
16,248
src/main/native/bullet3/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btConvexConcaveCollisionAlgorithm.h" #include "LinearMath/btQuickprof.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/CollisionShapes/btMultiSphereShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "BulletCollision/CollisionShapes/btConcaveShape.h" #include "BulletCollision/CollisionDispatch/btManifoldResult.h" #include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h" #include "BulletCollision/CollisionShapes/btTriangleShape.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "LinearMath/btIDebugDraw.h" #include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h" #include "BulletCollision/CollisionShapes/btSdfCollisionShape.h" btConvexConcaveCollisionAlgorithm::btConvexConcaveCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, bool isSwapped) : btActivatingCollisionAlgorithm(ci, body0Wrap, body1Wrap), m_btConvexTriangleCallback(ci.m_dispatcher1, body0Wrap, body1Wrap, isSwapped), m_isSwapped(isSwapped) { } btConvexConcaveCollisionAlgorithm::~btConvexConcaveCollisionAlgorithm() { } void btConvexConcaveCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray) { if (m_btConvexTriangleCallback.m_manifoldPtr) { manifoldArray.push_back(m_btConvexTriangleCallback.m_manifoldPtr); } } btConvexTriangleCallback::btConvexTriangleCallback(btDispatcher* dispatcher, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, bool isSwapped) : m_dispatcher(dispatcher), m_dispatchInfoPtr(0) { m_convexBodyWrap = isSwapped ? body1Wrap : body0Wrap; m_triBodyWrap = isSwapped ? body0Wrap : body1Wrap; // // create the manifold from the dispatcher 'manifold pool' // m_manifoldPtr = m_dispatcher->getNewManifold(m_convexBodyWrap->getCollisionObject(), m_triBodyWrap->getCollisionObject()); clearCache(); } btConvexTriangleCallback::~btConvexTriangleCallback() { clearCache(); m_dispatcher->releaseManifold(m_manifoldPtr); } void btConvexTriangleCallback::clearCache() { m_dispatcher->clearManifold(m_manifoldPtr); } void btConvexTriangleCallback::processTriangle(btVector3* triangle, int partId, int triangleIndex) { BT_PROFILE("btConvexTriangleCallback::processTriangle"); if (!TestTriangleAgainstAabb2(triangle, m_aabbMin, m_aabbMax)) { return; } //just for debugging purposes //printf("triangle %d",m_triangleCount++); btCollisionAlgorithmConstructionInfo ci; ci.m_dispatcher1 = m_dispatcher; #if 0 ///debug drawing of the overlapping triangles if (m_dispatchInfoPtr && m_dispatchInfoPtr->m_debugDraw && (m_dispatchInfoPtr->m_debugDraw->getDebugMode() &btIDebugDraw::DBG_DrawWireframe )) { const btCollisionObject* ob = const_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject()); btVector3 color(1,1,0); btTransform& tr = ob->getWorldTransform(); m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(triangle[1]),color); m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[1]),tr(triangle[2]),color); m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[2]),tr(triangle[0]),color); } #endif if (m_convexBodyWrap->getCollisionShape()->isConvex()) { #ifdef BT_ENABLE_CONVEX_CONCAVE_EARLY_OUT //todo: check this issue https://github.com/bulletphysics/bullet3/issues/4263 //an early out optimisation if the object is separated from the triangle //projected on the triangle normal) { const btVector3 v0 = m_triBodyWrap->getWorldTransform()*triangle[0]; const btVector3 v1 = m_triBodyWrap->getWorldTransform()*triangle[1]; const btVector3 v2 = m_triBodyWrap->getWorldTransform()*triangle[2]; btVector3 triangle_normal_world = ( v1 - v0).cross(v2 - v0); triangle_normal_world.normalize(); btConvexShape* convex = (btConvexShape*)m_convexBodyWrap->getCollisionShape(); btVector3 localPt = convex->localGetSupportingVertex(m_convexBodyWrap->getWorldTransform().getBasis().inverse()*triangle_normal_world); btVector3 worldPt = m_convexBodyWrap->getWorldTransform()*localPt; //now check if this is fully on one side of the triangle btScalar proj_distPt = triangle_normal_world.dot(worldPt); btScalar proj_distTr = triangle_normal_world.dot(v0); btScalar contact_threshold = m_manifoldPtr->getContactBreakingThreshold()+ m_resultOut->m_closestPointDistanceThreshold; btScalar dist = proj_distTr - proj_distPt; if (dist > contact_threshold) return; //also check the other side of the triangle triangle_normal_world*=-1; localPt = convex->localGetSupportingVertex(m_convexBodyWrap->getWorldTransform().getBasis().inverse()*triangle_normal_world); worldPt = m_convexBodyWrap->getWorldTransform()*localPt; //now check if this is fully on one side of the triangle proj_distPt = triangle_normal_world.dot(worldPt); proj_distTr = triangle_normal_world.dot(v0); dist = proj_distTr - proj_distPt; if (dist > contact_threshold) return; } #endif //BT_ENABLE_CONVEX_CONCAVE_EARLY_OUT btTriangleShape tm(triangle[0], triangle[1], triangle[2]); tm.setMargin(m_collisionMarginTriangle); btCollisionObjectWrapper triObWrap(m_triBodyWrap, &tm, m_triBodyWrap->getCollisionObject(), m_triBodyWrap->getWorldTransform(), partId, triangleIndex); //correct transform? btCollisionAlgorithm* colAlgo = 0; if (m_resultOut->m_closestPointDistanceThreshold > 0) { colAlgo = ci.m_dispatcher1->findAlgorithm(m_convexBodyWrap, &triObWrap, 0, BT_CLOSEST_POINT_ALGORITHMS); } else { colAlgo = ci.m_dispatcher1->findAlgorithm(m_convexBodyWrap, &triObWrap, m_manifoldPtr, BT_CONTACT_POINT_ALGORITHMS); } const btCollisionObjectWrapper* tmpWrap = 0; if (m_resultOut->getBody0Internal() == m_triBodyWrap->getCollisionObject()) { tmpWrap = m_resultOut->getBody0Wrap(); m_resultOut->setBody0Wrap(&triObWrap); m_resultOut->setShapeIdentifiersA(partId, triangleIndex); } else { tmpWrap = m_resultOut->getBody1Wrap(); m_resultOut->setBody1Wrap(&triObWrap); m_resultOut->setShapeIdentifiersB(partId, triangleIndex); } { BT_PROFILE("processCollision (GJK?)"); colAlgo->processCollision(m_convexBodyWrap, &triObWrap, *m_dispatchInfoPtr, m_resultOut); } if (m_resultOut->getBody0Internal() == m_triBodyWrap->getCollisionObject()) { m_resultOut->setBody0Wrap(tmpWrap); } else { m_resultOut->setBody1Wrap(tmpWrap); } colAlgo->~btCollisionAlgorithm(); ci.m_dispatcher1->freeCollisionAlgorithm(colAlgo); } } void btConvexTriangleCallback::setTimeStepAndCounters(btScalar collisionMarginTriangle, const btDispatcherInfo& dispatchInfo, const btCollisionObjectWrapper* convexBodyWrap, const btCollisionObjectWrapper* triBodyWrap, btManifoldResult* resultOut) { m_convexBodyWrap = convexBodyWrap; m_triBodyWrap = triBodyWrap; m_dispatchInfoPtr = &dispatchInfo; m_collisionMarginTriangle = collisionMarginTriangle; m_resultOut = resultOut; //recalc aabbs btTransform convexInTriangleSpace; convexInTriangleSpace = m_triBodyWrap->getWorldTransform().inverse() * m_convexBodyWrap->getWorldTransform(); const btCollisionShape* convexShape = static_cast<const btCollisionShape*>(m_convexBodyWrap->getCollisionShape()); //CollisionShape* triangleShape = static_cast<btCollisionShape*>(triBody->m_collisionShape); convexShape->getAabb(convexInTriangleSpace, m_aabbMin, m_aabbMax); btScalar extraMargin = collisionMarginTriangle + resultOut->m_closestPointDistanceThreshold; btVector3 extra(extraMargin, extraMargin, extraMargin); m_aabbMax += extra; m_aabbMin -= extra; } void btConvexConcaveCollisionAlgorithm::clearCache() { m_btConvexTriangleCallback.clearCache(); } void btConvexConcaveCollisionAlgorithm::processCollision(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut) { BT_PROFILE("btConvexConcaveCollisionAlgorithm::processCollision"); const btCollisionObjectWrapper* convexBodyWrap = m_isSwapped ? body1Wrap : body0Wrap; const btCollisionObjectWrapper* triBodyWrap = m_isSwapped ? body0Wrap : body1Wrap; if (triBodyWrap->getCollisionShape()->isConcave()) { if (triBodyWrap->getCollisionShape()->getShapeType() == SDF_SHAPE_PROXYTYPE) { btSdfCollisionShape* sdfShape = (btSdfCollisionShape*)triBodyWrap->getCollisionShape(); if (convexBodyWrap->getCollisionShape()->isConvex()) { btConvexShape* convex = (btConvexShape*)convexBodyWrap->getCollisionShape(); btAlignedObjectArray<btVector3> queryVertices; if (convex->isPolyhedral()) { btPolyhedralConvexShape* poly = (btPolyhedralConvexShape*)convex; for (int v = 0; v < poly->getNumVertices(); v++) { btVector3 vtx; poly->getVertex(v, vtx); queryVertices.push_back(vtx); } } btScalar maxDist = SIMD_EPSILON; if (convex->getShapeType() == SPHERE_SHAPE_PROXYTYPE) { queryVertices.push_back(btVector3(0, 0, 0)); btSphereShape* sphere = (btSphereShape*)convex; maxDist = sphere->getRadius() + SIMD_EPSILON; } if (queryVertices.size()) { resultOut->setPersistentManifold(m_btConvexTriangleCallback.m_manifoldPtr); //m_btConvexTriangleCallback.m_manifoldPtr->clearManifold(); btPolyhedralConvexShape* poly = (btPolyhedralConvexShape*)convex; for (int v = 0; v < queryVertices.size(); v++) { const btVector3& vtx = queryVertices[v]; btVector3 vtxWorldSpace = convexBodyWrap->getWorldTransform() * vtx; btVector3 vtxInSdf = triBodyWrap->getWorldTransform().invXform(vtxWorldSpace); btVector3 normalLocal; btScalar dist; if (sdfShape->queryPoint(vtxInSdf, dist, normalLocal)) { if (dist <= maxDist) { normalLocal.safeNormalize(); btVector3 normal = triBodyWrap->getWorldTransform().getBasis() * normalLocal; if (convex->getShapeType() == SPHERE_SHAPE_PROXYTYPE) { btSphereShape* sphere = (btSphereShape*)convex; dist -= sphere->getRadius(); vtxWorldSpace -= sphere->getRadius() * normal; } resultOut->addContactPoint(normal, vtxWorldSpace - normal * dist, dist); } } } resultOut->refreshContactPoints(); } } } else { const btConcaveShape* concaveShape = static_cast<const btConcaveShape*>(triBodyWrap->getCollisionShape()); if (convexBodyWrap->getCollisionShape()->isConvex()) { btScalar collisionMarginTriangle = concaveShape->getMargin(); resultOut->setPersistentManifold(m_btConvexTriangleCallback.m_manifoldPtr); m_btConvexTriangleCallback.setTimeStepAndCounters(collisionMarginTriangle, dispatchInfo, convexBodyWrap, triBodyWrap, resultOut); m_btConvexTriangleCallback.m_manifoldPtr->setBodies(convexBodyWrap->getCollisionObject(), triBodyWrap->getCollisionObject()); concaveShape->processAllTriangles(&m_btConvexTriangleCallback, m_btConvexTriangleCallback.getAabbMin(), m_btConvexTriangleCallback.getAabbMax()); resultOut->refreshContactPoints(); m_btConvexTriangleCallback.clearWrapperData(); } } } } btScalar btConvexConcaveCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0, btCollisionObject* body1, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut) { (void)resultOut; (void)dispatchInfo; btCollisionObject* convexbody = m_isSwapped ? body1 : body0; btCollisionObject* triBody = m_isSwapped ? body0 : body1; //quick approximation using raycast, todo: hook up to the continuous collision detection (one of the btConvexCast) //only perform CCD above a certain threshold, this prevents blocking on the long run //because object in a blocked ccd state (hitfraction<1) get their linear velocity halved each frame... btScalar squareMot0 = (convexbody->getInterpolationWorldTransform().getOrigin() - convexbody->getWorldTransform().getOrigin()).length2(); if (squareMot0 < convexbody->getCcdSquareMotionThreshold()) { return btScalar(1.); } //const btVector3& from = convexbody->m_worldTransform.getOrigin(); //btVector3 to = convexbody->m_interpolationWorldTransform.getOrigin(); //todo: only do if the motion exceeds the 'radius' btTransform triInv = triBody->getWorldTransform().inverse(); btTransform convexFromLocal = triInv * convexbody->getWorldTransform(); btTransform convexToLocal = triInv * convexbody->getInterpolationWorldTransform(); struct LocalTriangleSphereCastCallback : public btTriangleCallback { btTransform m_ccdSphereFromTrans; btTransform m_ccdSphereToTrans; btTransform m_meshTransform; btScalar m_ccdSphereRadius; btScalar m_hitFraction; LocalTriangleSphereCastCallback(const btTransform& from, const btTransform& to, btScalar ccdSphereRadius, btScalar hitFraction) : m_ccdSphereFromTrans(from), m_ccdSphereToTrans(to), m_ccdSphereRadius(ccdSphereRadius), m_hitFraction(hitFraction) { } virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex) { BT_PROFILE("processTriangle"); (void)partId; (void)triangleIndex; //do a swept sphere for now btTransform ident; ident.setIdentity(); btConvexCast::CastResult castResult; castResult.m_fraction = m_hitFraction; btSphereShape pointShape(m_ccdSphereRadius); btTriangleShape triShape(triangle[0], triangle[1], triangle[2]); btVoronoiSimplexSolver simplexSolver; btSubsimplexConvexCast convexCaster(&pointShape, &triShape, &simplexSolver); //GjkConvexCast convexCaster(&pointShape,convexShape,&simplexSolver); //ContinuousConvexCollision convexCaster(&pointShape,convexShape,&simplexSolver,0); //local space? if (convexCaster.calcTimeOfImpact(m_ccdSphereFromTrans, m_ccdSphereToTrans, ident, ident, castResult)) { if (m_hitFraction > castResult.m_fraction) m_hitFraction = castResult.m_fraction; } } }; if (triBody->getCollisionShape()->isConcave()) { btVector3 rayAabbMin = convexFromLocal.getOrigin(); rayAabbMin.setMin(convexToLocal.getOrigin()); btVector3 rayAabbMax = convexFromLocal.getOrigin(); rayAabbMax.setMax(convexToLocal.getOrigin()); btScalar ccdRadius0 = convexbody->getCcdSweptSphereRadius(); rayAabbMin -= btVector3(ccdRadius0, ccdRadius0, ccdRadius0); rayAabbMax += btVector3(ccdRadius0, ccdRadius0, ccdRadius0); btScalar curHitFraction = btScalar(1.); //is this available? LocalTriangleSphereCastCallback raycastCallback(convexFromLocal, convexToLocal, convexbody->getCcdSweptSphereRadius(), curHitFraction); raycastCallback.m_hitFraction = convexbody->getHitFraction(); btCollisionObject* concavebody = triBody; btConcaveShape* triangleMesh = (btConcaveShape*)concavebody->getCollisionShape(); if (triangleMesh) { triangleMesh->processAllTriangles(&raycastCallback, rayAabbMin, rayAabbMax); } if (raycastCallback.m_hitFraction < convexbody->getHitFraction()) { convexbody->setHitFraction(raycastCallback.m_hitFraction); return raycastCallback.m_hitFraction; } } return btScalar(1.); }
1
0.961819
1
0.961819
game-dev
MEDIA
0.978316
game-dev
0.945542
1
0.945542
Fluorohydride/ygopro-scripts
1,552
c296499.lua
--一族の掟 function c296499.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c296499.target) c:RegisterEffect(e1) --cannot attack local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_CANNOT_ATTACK) e2:SetRange(LOCATION_SZONE) e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e2:SetTarget(c296499.atktarget) c:RegisterEffect(e2) e2:SetLabelObject(e1) --maintain local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e3:SetCode(EVENT_PHASE+PHASE_STANDBY) e3:SetRange(LOCATION_SZONE) e3:SetCountLimit(1) e3:SetCondition(c296499.mtcon) e3:SetOperation(c296499.mtop) c:RegisterEffect(e3) end function c296499.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RACE) local rc=Duel.AnnounceRace(tp,1,RACE_ALL) e:SetLabel(rc) e:GetHandler():SetHint(CHINT_RACE,rc) end function c296499.atktarget(e,c) return c:IsRace(e:GetLabelObject():GetLabel()) end function c296499.mtcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c296499.mtop(e,tp,eg,ep,ev,re,r,rp) if Duel.CheckReleaseGroupEx(tp,nil,1,REASON_MAINTENANCE,false,nil) and Duel.SelectYesNo(tp,aux.Stringid(296499,0)) then local g=Duel.SelectReleaseGroupEx(tp,nil,1,1,REASON_MAINTENANCE,false,nil) Duel.Release(g,REASON_MAINTENANCE) else Duel.Destroy(e:GetHandler(),REASON_COST) end end
1
0.807691
1
0.807691
game-dev
MEDIA
0.994781
game-dev
0.898967
1
0.898967
audulus/rui
4,201
src/views/window.rs
use crate::*; use std::{any::Any, sync::Arc}; /// Struct for the `window_title` modifier. #[derive(Clone)] pub struct TitleView<V> { child: V, title: Arc<str>, } impl<V> TitleView<V> where V: View, { pub fn new(v: V, title: &str) -> Self { Self { child: v, title: title.into(), } } } impl<V> DynView for TitleView<V> where V: View, { fn process( &self, event: &Event, path: &mut IdPath, cx: &mut Context, actions: &mut Vec<Box<dyn Any>>, ) { path.push(0); self.child.process(event, path, cx, actions); path.pop(); } fn draw(&self, path: &mut IdPath, args: &mut DrawArgs) { path.push(0); self.child.draw(path, args); path.pop(); let cx = &mut args.cx; if cx.window_title != self.title { cx.window_title = self.title.clone(); } } fn layout(&self, path: &mut IdPath, args: &mut LayoutArgs) -> LocalSize { path.push(0); let sz = self.child.layout(path, args); path.pop(); sz } fn dirty(&self, path: &mut IdPath, xform: LocalToWorld, cx: &mut Context) { path.push(0); self.child.dirty(path, xform, cx); path.pop(); } fn hittest(&self, path: &mut IdPath, pt: LocalPoint, cx: &mut Context) -> Option<ViewId> { path.push(0); let id = self.child.hittest(path, pt, cx); path.pop(); id } fn commands(&self, path: &mut IdPath, cx: &mut Context, cmds: &mut Vec<CommandInfo>) { path.push(0); self.child.commands(path, cx, cmds); path.pop(); } fn gc(&self, path: &mut IdPath, cx: &mut Context, map: &mut Vec<ViewId>) { path.push(0); self.child.gc(path, cx, map); path.pop(); } fn access( &self, path: &mut IdPath, cx: &mut Context, nodes: &mut Vec<(accesskit::NodeId, accesskit::Node)>, ) -> Option<accesskit::NodeId> { path.push(0); let node_id = self.child.access(path, cx, nodes); path.pop(); node_id } } impl<V> private::Sealed for TitleView<V> {} /// Struct for the `fullscreen` modifier. #[derive(Clone)] pub struct FullscreenView<V> { child: V, } impl<V> FullscreenView<V> where V: View, { pub fn new(v: V) -> Self { Self { child: v } } } impl<V> DynView for FullscreenView<V> where V: View, { fn process( &self, event: &Event, path: &mut IdPath, cx: &mut Context, actions: &mut Vec<Box<dyn Any>>, ) { path.push(0); self.child.process(event, path, cx, actions); path.pop(); } fn draw(&self, path: &mut IdPath, args: &mut DrawArgs) { path.push(0); self.child.draw(path, args); path.pop(); args.cx.fullscreen = true; } fn layout(&self, path: &mut IdPath, args: &mut LayoutArgs) -> LocalSize { path.push(0); let sz = self.child.layout(path, args); path.pop(); sz } fn dirty(&self, path: &mut IdPath, xform: LocalToWorld, cx: &mut Context) { path.push(0); self.child.dirty(path, xform, cx); path.pop(); } fn hittest(&self, path: &mut IdPath, pt: LocalPoint, cx: &mut Context) -> Option<ViewId> { path.push(0); let id = self.child.hittest(path, pt, cx); path.pop(); id } fn commands(&self, path: &mut IdPath, cx: &mut Context, cmds: &mut Vec<CommandInfo>) { path.push(0); self.child.commands(path, cx, cmds); path.pop(); } fn gc(&self, path: &mut IdPath, cx: &mut Context, map: &mut Vec<ViewId>) { path.push(0); self.child.gc(path, cx, map); path.pop(); } fn access( &self, path: &mut IdPath, cx: &mut Context, nodes: &mut Vec<(accesskit::NodeId, accesskit::Node)>, ) -> Option<accesskit::NodeId> { path.push(0); let node_id = self.child.access(path, cx, nodes); path.pop(); node_id } } impl<V> private::Sealed for FullscreenView<V> {}
1
0.805175
1
0.805175
game-dev
MEDIA
0.563911
game-dev
0.95569
1
0.95569