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
CrypticMonkey33/ArchipelagoExplorersOfSky
1,349
worlds/zillion/gen_data.py
from dataclasses import dataclass import json from zilliandomizer.game import Game as ZzGame @dataclass class GenData: """ data passed from generation to patcher """ multi_items: dict[str, tuple[str, str]] """ zz_loc_name to (item_name, player_name) """ zz_game: ZzGame game_id: bytes """ the byte string used to detect the rom """ def to_json(self) -> str: """ serialized data from generation needed to patch rom """ jsonable = { "multi_items": self.multi_items, "zz_game": self.zz_game.to_jsonable(), "game_id": list(self.game_id), } return json.dumps(jsonable) @staticmethod def from_json(gen_data_str: str) -> "GenData": """ the reverse of `to_json` """ from_json = json.loads(gen_data_str) # backwards compatibility for seeds generated before new map_gen options room_gen = from_json["zz_game"]["options"].get("room_gen", None) if room_gen is not None: from_json["zz_game"]["options"]["map_gen"] = {False: "none", True: "rooms"}.get(room_gen, "none") del from_json["zz_game"]["options"]["room_gen"] return GenData( from_json["multi_items"], ZzGame.from_jsonable(from_json["zz_game"]), bytes(from_json["game_id"]), )
0
0.573452
1
0.573452
game-dev
MEDIA
0.39615
game-dev
0.596881
1
0.596881
clover-moe/lilium-voyager
26,922
code/game/g_rankings.c
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // g_rankings.c -- reports for global rankings system #include "g_local.h" #include "g_rankings.h" /* ================ G_RankRunFrame ================ */ void G_RankRunFrame() { gentity_t* ent; gentity_t* ent2; grank_status_t old_status; grank_status_t status; int time; int i; int j; if( !trap_RankCheckInit() ) { trap_RankBegin( GR_GAMEKEY ); } trap_RankPoll(); if( trap_RankActive() ) { for( i = 0; i < level.maxclients; i++ ) { ent = &(g_entities[i]); if ( !ent->inuse ) continue; if ( ent->client == NULL ) continue; if ( ent->r.svFlags & SVF_BOT) { // no bots in ranked games trap_SendConsoleCommand( EXEC_INSERT, va("kick %s\n", ent->client->pers.netname) ); continue; } old_status = ent->client->client_status; status = trap_RankUserStatus( i ); if( ent->client->client_status != status ) { // inform client of current status // not needed for client side log in trap_SendServerCommand( i, va("rank_status %i\n",status) ); if ( i == 0 ) { int j = 0; } ent->client->client_status = status; } switch( status ) { case QGR_STATUS_NEW: case QGR_STATUS_SPECTATOR: if( ent->client->sess.sessionTeam != TEAM_SPECTATOR ) { ent->client->sess.sessionTeam = TEAM_SPECTATOR; ent->client->sess.spectatorState = SPECTATOR_FREE; ClientSpawn( ent ); // make sure by now CS_GRAND rankingsGameID is ready trap_SendServerCommand( i, va("rank_status %i\n",status) ); trap_SendServerCommand( i, "rank_menu\n" ); } break; case QGR_STATUS_NO_USER: case QGR_STATUS_BAD_PASSWORD: case QGR_STATUS_TIMEOUT: case QGR_STATUS_NO_MEMBERSHIP: case QGR_STATUS_INVALIDUSER: case QGR_STATUS_ERROR: if( (ent->r.svFlags & SVF_BOT) == 0 ) { trap_RankUserReset( ent->s.clientNum ); } break; case QGR_STATUS_ACTIVE: if( (ent->client->sess.sessionTeam == TEAM_SPECTATOR) && (g_gametype.integer < GT_TEAM) ) { SetTeam( ent, "free" ); } if( old_status != QGR_STATUS_ACTIVE ) { // player has just become active for( j = 0; j < level.maxclients; j++ ) { ent2 = &(g_entities[j]); if ( !ent2->inuse ) continue; if ( ent2->client == NULL ) continue; if ( ent2->r.svFlags & SVF_BOT) continue; if( (i != j) && (trap_RankUserStatus( j ) == QGR_STATUS_ACTIVE) ) { trap_RankReportInt( i, j, QGR_KEY_PLAYED_WITH, 1, 0 ); } // send current scores so the player's rank will show // up under the crosshair immediately DeathmatchScoreboardMessage( ent2 ); } } break; default: break; } } // don't let ranked games last forever if( ((g_fraglimit.integer == 0) || (g_fraglimit.integer > 100)) && ((g_timelimit.integer == 0) || (g_timelimit.integer > 1000)) ) { trap_Cvar_Set( "timelimit", "1000" ); } } // tell time to clients so they can show current match rating if( level.intermissiontime == 0 ) { for( i = 0; i < level.maxclients; i++ ) { ent = &(g_entities[i]); if( ent->client == NULL ) { continue; } time = (level.time - ent->client->pers.enterTime) / 1000; ent->client->ps.persistant[PERS_MATCH_TIME] = time; } } } /* ================ G_RankFireWeapon ================ */ void G_RankFireWeapon( int self, int weapon ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } if( weapon == WP_GAUNTLET ) { // the gauntlet only "fires" when it actually hits something return; } trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED, 1, 1 ); switch( weapon ) { case WP_MACHINEGUN: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_MACHINEGUN, 1, 1 ); break; case WP_SHOTGUN: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_SHOTGUN, 1, 1 ); break; case WP_GRENADE_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_GRENADE, 1, 1 ); break; case WP_ROCKET_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_ROCKET, 1, 1 ); break; case WP_LIGHTNING: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_LIGHTNING, 1, 1 ); break; case WP_RAILGUN: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_RAILGUN, 1, 1 ); break; case WP_PLASMAGUN: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_PLASMA, 1, 1 ); break; case WP_BFG: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_BFG, 1, 1 ); break; case WP_GRAPPLING_HOOK: trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_GRAPPLE, 1, 1 ); break; default: break; } } /* ================ G_RankDamage ================ */ void G_RankDamage( int self, int attacker, int damage, int means_of_death ) { // state information to avoid counting each shotgun pellet as a hit static int last_framenum = -1; static int last_self = -1; static int last_attacker = -1; static int last_means_of_death = MOD_UNKNOWN; qboolean new_hit; int splash; int key_hit; int key_damage; int key_splash; if( level.warmupTime != 0 ) { // no reports during warmup period return; } new_hit = (level.framenum != last_framenum) || (self != last_self) || (attacker != last_attacker) || (means_of_death != last_means_of_death); // update state information last_framenum = level.framenum; last_self = self; last_attacker = attacker; last_means_of_death = means_of_death; // the gauntlet only "fires" when it actually hits something if( (attacker != ENTITYNUM_WORLD) && (attacker != self) && (means_of_death == MOD_GAUNTLET) && (g_entities[attacker].client) ) { trap_RankReportInt( attacker, -1, QGR_KEY_SHOT_FIRED_GAUNTLET, 1, 1 ); } // don't track hazard damage, just deaths switch( means_of_death ) { case MOD_WATER: case MOD_SLIME: case MOD_LAVA: case MOD_CRUSH: case MOD_TELEFRAG: case MOD_FALLING: case MOD_SUICIDE: case MOD_TRIGGER_HURT: return; default: break; } // get splash damage switch( means_of_death ) { case MOD_GRENADE_SPLASH: case MOD_ROCKET_SPLASH: case MOD_PLASMA_SPLASH: case MOD_BFG_SPLASH: splash = damage; break; default: splash = 0; key_splash = -1; break; } // hit, damage, and splash taken switch( means_of_death ) { case MOD_GAUNTLET: key_hit = QGR_KEY_HIT_TAKEN_GAUNTLET; key_damage = QGR_KEY_DAMAGE_TAKEN_GAUNTLET; break; case MOD_MACHINEGUN: key_hit = QGR_KEY_HIT_TAKEN_MACHINEGUN; key_damage = QGR_KEY_DAMAGE_TAKEN_MACHINEGUN; break; case MOD_SHOTGUN: key_hit = QGR_KEY_HIT_TAKEN_SHOTGUN; key_damage = QGR_KEY_DAMAGE_TAKEN_SHOTGUN; break; case MOD_GRENADE: case MOD_GRENADE_SPLASH: key_hit = QGR_KEY_HIT_TAKEN_GRENADE; key_damage = QGR_KEY_DAMAGE_TAKEN_GRENADE; key_splash = QGR_KEY_SPLASH_TAKEN_GRENADE; break; case MOD_ROCKET: case MOD_ROCKET_SPLASH: key_hit = QGR_KEY_HIT_TAKEN_ROCKET; key_damage = QGR_KEY_DAMAGE_TAKEN_ROCKET; key_splash = QGR_KEY_SPLASH_TAKEN_ROCKET; break; case MOD_PLASMA: case MOD_PLASMA_SPLASH: key_hit = QGR_KEY_HIT_TAKEN_PLASMA; key_damage = QGR_KEY_DAMAGE_TAKEN_PLASMA; key_splash = QGR_KEY_SPLASH_TAKEN_PLASMA; break; case MOD_RAILGUN: key_hit = QGR_KEY_HIT_TAKEN_RAILGUN; key_damage = QGR_KEY_DAMAGE_TAKEN_RAILGUN; break; case MOD_LIGHTNING: key_hit = QGR_KEY_HIT_TAKEN_LIGHTNING; key_damage = QGR_KEY_DAMAGE_TAKEN_LIGHTNING; break; case MOD_BFG: case MOD_BFG_SPLASH: key_hit = QGR_KEY_HIT_TAKEN_BFG; key_damage = QGR_KEY_DAMAGE_TAKEN_BFG; key_splash = QGR_KEY_SPLASH_TAKEN_BFG; break; case MOD_GRAPPLE: key_hit = QGR_KEY_HIT_TAKEN_GRAPPLE; key_damage = QGR_KEY_DAMAGE_TAKEN_GRAPPLE; break; default: key_hit = QGR_KEY_HIT_TAKEN_UNKNOWN; key_damage = QGR_KEY_DAMAGE_TAKEN_UNKNOWN; break; } // report general and specific hit taken if( new_hit ) { trap_RankReportInt( self, -1, QGR_KEY_HIT_TAKEN, 1, 1 ); trap_RankReportInt( self, -1, key_hit, 1, 1 ); } // report general and specific damage taken trap_RankReportInt( self, -1, QGR_KEY_DAMAGE_TAKEN, damage, 1 ); trap_RankReportInt( self, -1, key_damage, damage, 1 ); // report general and specific splash taken if( splash != 0 ) { trap_RankReportInt( self, -1, QGR_KEY_SPLASH_TAKEN, splash, 1 ); trap_RankReportInt( self, -1, key_splash, splash, 1 ); } // hit, damage, and splash given if( (attacker != ENTITYNUM_WORLD) && (attacker != self) ) { switch( means_of_death ) { case MOD_GAUNTLET: key_hit = QGR_KEY_HIT_GIVEN_GAUNTLET; key_damage = QGR_KEY_DAMAGE_GIVEN_GAUNTLET; break; case MOD_MACHINEGUN: key_hit = QGR_KEY_HIT_GIVEN_MACHINEGUN; key_damage = QGR_KEY_DAMAGE_GIVEN_MACHINEGUN; break; case MOD_SHOTGUN: key_hit = QGR_KEY_HIT_GIVEN_SHOTGUN; key_damage = QGR_KEY_DAMAGE_GIVEN_SHOTGUN; break; case MOD_GRENADE: case MOD_GRENADE_SPLASH: key_hit = QGR_KEY_HIT_GIVEN_GRENADE; key_damage = QGR_KEY_DAMAGE_GIVEN_GRENADE; key_splash = QGR_KEY_SPLASH_GIVEN_GRENADE; break; case MOD_ROCKET: case MOD_ROCKET_SPLASH: key_hit = QGR_KEY_HIT_GIVEN_ROCKET; key_damage = QGR_KEY_DAMAGE_GIVEN_ROCKET; key_splash = QGR_KEY_SPLASH_GIVEN_ROCKET; break; case MOD_PLASMA: case MOD_PLASMA_SPLASH: key_hit = QGR_KEY_HIT_GIVEN_PLASMA; key_damage = QGR_KEY_DAMAGE_GIVEN_PLASMA; key_splash = QGR_KEY_SPLASH_GIVEN_PLASMA; break; case MOD_RAILGUN: key_hit = QGR_KEY_HIT_GIVEN_RAILGUN; key_damage = QGR_KEY_DAMAGE_GIVEN_RAILGUN; break; case MOD_LIGHTNING: key_hit = QGR_KEY_HIT_GIVEN_LIGHTNING; key_damage = QGR_KEY_DAMAGE_GIVEN_LIGHTNING; break; case MOD_BFG: case MOD_BFG_SPLASH: key_hit = QGR_KEY_HIT_GIVEN_BFG; key_damage = QGR_KEY_DAMAGE_GIVEN_BFG; key_splash = QGR_KEY_SPLASH_GIVEN_BFG; break; case MOD_GRAPPLE: key_hit = QGR_KEY_HIT_GIVEN_GRAPPLE; key_damage = QGR_KEY_DAMAGE_GIVEN_GRAPPLE; break; default: key_hit = QGR_KEY_HIT_GIVEN_UNKNOWN; key_damage = QGR_KEY_DAMAGE_GIVEN_UNKNOWN; break; } // report general and specific hit given // jwu 8/26/00 // had a case where attacker is 245 which is grnadeshooter attacker is // g_entities index not necessarilly clientnum if (g_entities[attacker].client) { if( new_hit ) { trap_RankReportInt( attacker, -1, QGR_KEY_HIT_GIVEN, 1, 1 ); trap_RankReportInt( attacker, -1, key_hit, 1, 1 ); } // report general and specific damage given trap_RankReportInt( attacker, -1, QGR_KEY_DAMAGE_GIVEN, damage, 1 ); trap_RankReportInt( attacker, -1, key_damage, damage, 1 ); // report general and specific splash given if( splash != 0 ) { trap_RankReportInt( attacker, -1, QGR_KEY_SPLASH_GIVEN, splash, 1 ); trap_RankReportInt( attacker, -1, key_splash, splash, 1 ); } } } // friendly fire if( (attacker != self) && OnSameTeam( &(g_entities[self]), &(g_entities[attacker])) && (g_entities[attacker].client) ) { // report teammate hit if( new_hit ) { trap_RankReportInt( self, -1, QGR_KEY_TEAMMATE_HIT_TAKEN, 1, 1 ); trap_RankReportInt( attacker, -1, QGR_KEY_TEAMMATE_HIT_GIVEN, 1, 1 ); } // report teammate damage trap_RankReportInt( self, -1, QGR_KEY_TEAMMATE_DAMAGE_TAKEN, damage, 1 ); trap_RankReportInt( attacker, -1, QGR_KEY_TEAMMATE_DAMAGE_GIVEN, damage, 1 ); // report teammate splash if( splash != 0 ) { trap_RankReportInt( self, -1, QGR_KEY_TEAMMATE_SPLASH_TAKEN, splash, 1 ); trap_RankReportInt( attacker, -1, QGR_KEY_TEAMMATE_SPLASH_GIVEN, splash, 1 ); } } } /* ================ G_RankPlayerDie ================ */ void G_RankPlayerDie( int self, int attacker, int means_of_death ) { int p1; int p2; if( level.warmupTime != 0 ) { // no reports during warmup period return; } if( attacker == ENTITYNUM_WORLD ) { p1 = self; p2 = -1; trap_RankReportInt( p1, p2, QGR_KEY_HAZARD_DEATH, 1, 1 ); switch( means_of_death ) { case MOD_WATER: trap_RankReportInt( p1, p2, QGR_KEY_WATER, 1, 1 ); break; case MOD_SLIME: trap_RankReportInt( p1, p2, QGR_KEY_SLIME, 1, 1 ); break; case MOD_LAVA: trap_RankReportInt( p1, p2, QGR_KEY_LAVA, 1, 1 ); break; case MOD_CRUSH: trap_RankReportInt( p1, p2, QGR_KEY_CRUSH, 1, 1 ); break; case MOD_TELEFRAG: trap_RankReportInt( p1, p2, QGR_KEY_TELEFRAG, 1, 1 ); break; case MOD_FALLING: trap_RankReportInt( p1, p2, QGR_KEY_FALLING, 1, 1 ); break; case MOD_SUICIDE: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_CMD, 1, 1 ); break; case MOD_TRIGGER_HURT: trap_RankReportInt( p1, p2, QGR_KEY_TRIGGER_HURT, 1, 1 ); break; default: trap_RankReportInt( p1, p2, QGR_KEY_HAZARD_MISC, 1, 1 ); break; } } else if( attacker == self ) { p1 = self; p2 = -1; trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE, 1, 1 ); switch( means_of_death ) { case MOD_GAUNTLET: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_GAUNTLET, 1, 1 ); break; case MOD_MACHINEGUN: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_MACHINEGUN, 1, 1 ); break; case MOD_SHOTGUN: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_SHOTGUN, 1, 1 ); break; case MOD_GRENADE: case MOD_GRENADE_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_GRENADE, 1, 1 ); break; case MOD_ROCKET: case MOD_ROCKET_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_ROCKET, 1, 1 ); break; case MOD_PLASMA: case MOD_PLASMA_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_PLASMA, 1, 1 ); break; case MOD_RAILGUN: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_RAILGUN, 1, 1 ); break; case MOD_LIGHTNING: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_LIGHTNING, 1, 1 ); break; case MOD_BFG: case MOD_BFG_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_BFG, 1, 1 ); break; case MOD_GRAPPLE: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_GRAPPLE, 1, 1 ); break; default: trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_UNKNOWN, 1, 1 ); break; } } else { p1 = attacker; p2 = self; trap_RankReportInt( p1, p2, QGR_KEY_FRAG, 1, 1 ); switch( means_of_death ) { case MOD_GAUNTLET: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_GAUNTLET, 1, 1 ); break; case MOD_MACHINEGUN: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_MACHINEGUN, 1, 1 ); break; case MOD_SHOTGUN: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_SHOTGUN, 1, 1 ); break; case MOD_GRENADE: case MOD_GRENADE_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_GRENADE, 1, 1 ); break; case MOD_ROCKET: case MOD_ROCKET_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_ROCKET, 1, 1 ); break; case MOD_PLASMA: case MOD_PLASMA_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_PLASMA, 1, 1 ); break; case MOD_RAILGUN: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_RAILGUN, 1, 1 ); break; case MOD_LIGHTNING: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_LIGHTNING, 1, 1 ); break; case MOD_BFG: case MOD_BFG_SPLASH: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_BFG, 1, 1 ); break; case MOD_GRAPPLE: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_GRAPPLE, 1, 1 ); break; default: trap_RankReportInt( p1, p2, QGR_KEY_FRAG_UNKNOWN, 1, 1 ); break; } } } /* ================ G_RankWeaponTime ================ */ void G_RankWeaponTime( int self, int weapon ) { gclient_t* client; int time; if( level.warmupTime != 0 ) { // no reports during warmup period return; } client = g_entities[self].client; time = (level.time - client->weapon_change_time) / 1000; client->weapon_change_time = level.time; if( time <= 0 ) { return; } trap_RankReportInt( self, -1, QGR_KEY_TIME, time, 1 ); switch( weapon ) { case WP_GAUNTLET: trap_RankReportInt( self, -1, QGR_KEY_TIME_GAUNTLET, time, 1 ); break; case WP_MACHINEGUN: trap_RankReportInt( self, -1, QGR_KEY_TIME_MACHINEGUN, time, 1 ); break; case WP_SHOTGUN: trap_RankReportInt( self, -1, QGR_KEY_TIME_SHOTGUN, time, 1 ); break; case WP_GRENADE_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_TIME_GRENADE, time, 1 ); break; case WP_ROCKET_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_TIME_ROCKET, time, 1 ); break; case WP_LIGHTNING: trap_RankReportInt( self, -1, QGR_KEY_TIME_LIGHTNING, time, 1 ); break; case WP_RAILGUN: trap_RankReportInt( self, -1, QGR_KEY_TIME_RAILGUN, time, 1 ); break; case WP_PLASMAGUN: trap_RankReportInt( self, -1, QGR_KEY_TIME_PLASMA, time, 1 ); break; case WP_BFG: trap_RankReportInt( self, -1, QGR_KEY_TIME_BFG, time, 1 ); break; case WP_GRAPPLING_HOOK: trap_RankReportInt( self, -1, QGR_KEY_TIME_GRAPPLE, time, 1 ); break; default: break; } } /* ================ G_RankPickupWeapon ================ */ void G_RankPickupWeapon( int self, int weapon ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } trap_RankReportInt( self, -1, QGR_KEY_PICKUP_WEAPON, 1, 1 ); switch( weapon ) { case WP_GAUNTLET: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_GAUNTLET, 1, 1 ); break; case WP_MACHINEGUN: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_MACHINEGUN, 1, 1 ); break; case WP_SHOTGUN: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_SHOTGUN, 1, 1 ); break; case WP_GRENADE_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_GRENADE, 1, 1 ); break; case WP_ROCKET_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_ROCKET, 1, 1 ); break; case WP_LIGHTNING: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_LIGHTNING, 1, 1 ); break; case WP_RAILGUN: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_RAILGUN, 1, 1 ); break; case WP_PLASMAGUN: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_PLASMA, 1, 1 ); break; case WP_BFG: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_BFG, 1, 1 ); break; case WP_GRAPPLING_HOOK: trap_RankReportInt( self, -1, QGR_KEY_PICKUP_GRAPPLE, 1, 1 ); break; default: break; } } /* ================ G_RankPickupAmmo ================ */ void G_RankPickupAmmo( int self, int weapon, int quantity ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } trap_RankReportInt( self, -1, QGR_KEY_BOXES, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS, quantity, 1 ); switch( weapon ) { case WP_MACHINEGUN: trap_RankReportInt( self, -1, QGR_KEY_BOXES_BULLETS, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_BULLETS, quantity, 1 ); break; case WP_SHOTGUN: trap_RankReportInt( self, -1, QGR_KEY_BOXES_SHELLS, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_SHELLS, quantity, 1 ); break; case WP_GRENADE_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_BOXES_GRENADES, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_GRENADES, quantity, 1 ); break; case WP_ROCKET_LAUNCHER: trap_RankReportInt( self, -1, QGR_KEY_BOXES_ROCKETS, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_ROCKETS, quantity, 1 ); break; case WP_LIGHTNING: trap_RankReportInt( self, -1, QGR_KEY_BOXES_LG_AMMO, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_LG_AMMO, quantity, 1 ); break; case WP_RAILGUN: trap_RankReportInt( self, -1, QGR_KEY_BOXES_SLUGS, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_SLUGS, quantity, 1 ); break; case WP_PLASMAGUN: trap_RankReportInt( self, -1, QGR_KEY_BOXES_CELLS, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_CELLS, quantity, 1 ); break; case WP_BFG: trap_RankReportInt( self, -1, QGR_KEY_BOXES_BFG_AMMO, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_BFG_AMMO, quantity, 1 ); break; default: break; } } /* ================ G_RankPickupHealth ================ */ void G_RankPickupHealth( int self, int quantity ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } trap_RankReportInt( self, -1, QGR_KEY_HEALTH, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_HEALTH_TOTAL, quantity, 1 ); switch( quantity ) { case 5: trap_RankReportInt( self, -1, QGR_KEY_HEALTH_5, 1, 1 ); break; case 25: trap_RankReportInt( self, -1, QGR_KEY_HEALTH_25, 1, 1 ); break; case 50: trap_RankReportInt( self, -1, QGR_KEY_HEALTH_50, 1, 1 ); break; case 100: trap_RankReportInt( self, -1, QGR_KEY_HEALTH_MEGA, 1, 1 ); break; default: break; } } /* ================ G_RankPickupArmor ================ */ void G_RankPickupArmor( int self, int quantity ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } trap_RankReportInt( self, -1, QGR_KEY_ARMOR, 1, 1 ); trap_RankReportInt( self, -1, QGR_KEY_ARMOR_TOTAL, quantity, 1 ); switch( quantity ) { case 5: trap_RankReportInt( self, -1, QGR_KEY_ARMOR_SHARD, 1, 1 ); break; case 50: trap_RankReportInt( self, -1, QGR_KEY_ARMOR_YELLOW, 1, 1 ); break; case 100: trap_RankReportInt( self, -1, QGR_KEY_ARMOR_RED, 1, 1 ); break; default: break; } } /* ================ G_RankPickupPowerup ================ */ void G_RankPickupPowerup( int self, int powerup ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } // ctf flags are treated as powerups if( (powerup == PW_REDFLAG) || (powerup == PW_BLUEFLAG) ) { trap_RankReportInt( self, -1, QGR_KEY_FLAG_PICKUP, 1, 1 ); return; } trap_RankReportInt( self, -1, QGR_KEY_POWERUP, 1, 1 ); switch( powerup ) { case PW_QUAD: trap_RankReportInt( self, -1, QGR_KEY_QUAD, 1, 1 ); break; case PW_BATTLESUIT: trap_RankReportInt( self, -1, QGR_KEY_SUIT, 1, 1 ); break; case PW_HASTE: trap_RankReportInt( self, -1, QGR_KEY_HASTE, 1, 1 ); break; case PW_INVIS: trap_RankReportInt( self, -1, QGR_KEY_INVIS, 1, 1 ); break; case PW_REGEN: trap_RankReportInt( self, -1, QGR_KEY_REGEN, 1, 1 ); break; case PW_FLIGHT: trap_RankReportInt( self, -1, QGR_KEY_FLIGHT, 1, 1 ); break; default: break; } } /* ================ G_RankPickupHoldable ================ */ void G_RankPickupHoldable( int self, int holdable ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } switch( holdable ) { case HI_MEDKIT: trap_RankReportInt( self, -1, QGR_KEY_MEDKIT, 1, 1 ); break; case HI_TELEPORTER: trap_RankReportInt( self, -1, QGR_KEY_TELEPORTER, 1, 1 ); break; default: break; } } /* ================ G_RankUseHoldable ================ */ void G_RankUseHoldable( int self, int holdable ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } switch( holdable ) { case HI_MEDKIT: trap_RankReportInt( self, -1, QGR_KEY_MEDKIT_USE, 1, 1 ); break; case HI_TELEPORTER: trap_RankReportInt( self, -1, QGR_KEY_TELEPORTER_USE, 1, 1 ); break; default: break; } } /* ================ G_RankReward ================ */ void G_RankReward( int self, int award ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } switch( award ) { case EF_AWARD_IMPRESSIVE: trap_RankReportInt( self, -1, QGR_KEY_IMPRESSIVE, 1, 1 ); break; case EF_AWARD_EXCELLENT: trap_RankReportInt( self, -1, QGR_KEY_EXCELLENT, 1, 1 ); break; default: break; } } /* ================ G_RankCapture ================ */ void G_RankCapture( int self ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } trap_RankReportInt( self, -1, QGR_KEY_FLAG_CAPTURE, 1, 1 ); } /* ================ G_RankUserTeamName ================ */ void G_RankUserTeamName( int self, char* team_name ) { if( level.warmupTime != 0 ) { // no reports during warmup period return; } trap_RankReportStr( self, -1, QGR_KEY_TEAM_NAME, team_name ); } /* ================ G_RankClientDisconnect ================ */ void G_RankClientDisconnect( int self ) { gclient_t* client; int time; int match_rating; if( level.warmupTime != 0 ) { // no reports during warmup period return; } // match rating client = g_entities[self].client; time = (level.time - client->pers.enterTime) / 1000; if( time < 60 ) { match_rating = 0; } else { match_rating = client->ps.persistant[PERS_MATCH_RATING] / time; } trap_RankReportInt( self, -1, QGR_KEY_MATCH_RATING, match_rating, 0 ); } /* ================ G_RankGameOver ================ */ void G_RankGameOver( void ) { int i; char str[MAX_INFO_VALUE]; int num; if( level.warmupTime != 0 ) { // no reports during warmup period return; } for( i = 0; i < level.maxclients; i++ ) { if( trap_RankUserStatus( i ) == QGR_STATUS_ACTIVE ) { G_RankClientDisconnect( i ); } } // hostname trap_Cvar_VariableStringBuffer( "sv_hostname", str, sizeof(str) ); trap_RankReportStr( -1, -1, QGR_KEY_HOSTNAME, str ); // map trap_Cvar_VariableStringBuffer( "mapname", str, sizeof(str) ); trap_RankReportStr( -1, -1, QGR_KEY_MAP, str ); // mod trap_Cvar_VariableStringBuffer( "fs_game", str, sizeof(str) ); trap_RankReportStr( -1, -1, QGR_KEY_MOD, str ); // gametype num = trap_Cvar_VariableIntegerValue("g_gametype"); trap_RankReportInt( -1, -1, QGR_KEY_GAMETYPE, num, 0 ); // fraglimit num = trap_Cvar_VariableIntegerValue("fraglimit"); trap_RankReportInt( -1, -1, QGR_KEY_FRAGLIMIT, num, 0 ); // timelimit num = trap_Cvar_VariableIntegerValue("timelimit"); trap_RankReportInt( -1, -1, QGR_KEY_TIMELIMIT, num, 0 ); // maxclients num = trap_Cvar_VariableIntegerValue("sv_maxclients"); trap_RankReportInt( -1, -1, QGR_KEY_MAXCLIENTS, num, 0 ); // maxrate num = trap_Cvar_VariableIntegerValue("sv_maxRate"); trap_RankReportInt( -1, -1, QGR_KEY_MAXRATE, num, 0 ); // minping num = trap_Cvar_VariableIntegerValue("sv_minPing"); trap_RankReportInt( -1, -1, QGR_KEY_MINPING, num, 0 ); // maxping num = trap_Cvar_VariableIntegerValue("sv_maxPing"); trap_RankReportInt( -1, -1, QGR_KEY_MAXPING, num, 0 ); // dedicated num = trap_Cvar_VariableIntegerValue("dedicated"); trap_RankReportInt( -1, -1, QGR_KEY_DEDICATED, num, 0 ); // version trap_Cvar_VariableStringBuffer( "version", str, sizeof(str) ); trap_RankReportStr( -1, -1, QGR_KEY_VERSION, str ); }
0
0.996524
1
0.996524
game-dev
MEDIA
0.980568
game-dev
0.96928
1
0.96928
runuo/runuo
2,197
Scripts/Engines/ConPVP/ReadyGump.cs
using System; using System.Collections; using Server.Gumps; using Server.Network; namespace Server.Engines.ConPVP { public class ReadyGump : Gump { private Mobile m_From; private DuelContext m_Context; private int m_Count; public string Center( string text ) { return String.Format( "<CENTER>{0}</CENTER>", text ); } public ReadyGump( Mobile from, DuelContext context, int count ) : base( 50, 50 ) { m_From = from; m_Context = context; m_Count = count; ArrayList parts = context.Participants; int height = 25 + 20; for ( int i = 0; i < parts.Count; ++i ) { Participant p = (Participant)parts[i]; height += 4; if ( p.Players.Length > 1 ) height += 22; height += (p.Players.Length * 22); } height += 25; Closable = false; Dragable = false; AddPage( 0 ); AddBackground( 0, 0, 260, height, 9250 ); AddBackground( 10, 10, 240, height - 20, 0xDAC ); if ( count == -1 ) { AddHtml( 35, 25, 190, 20, Center( "Ready" ), false, false ); } else { AddHtml( 35, 25, 190, 20, Center( "Starting" ), false, false ); AddHtml( 35, 25, 190, 20, "<DIV ALIGN=RIGHT>" + count.ToString(), false, false ); } int y = 25 + 20; for ( int i = 0; i < parts.Count; ++i ) { Participant p = (Participant)parts[i]; y += 4; bool isAllReady = true; int yStore = y; int offset = 0; if ( p.Players.Length > 1 ) { AddHtml( 35 + 14, y, 176, 20, String.Format( "Participant #{0}", i + 1 ), false, false ); y += 22; offset = 10; } for ( int j = 0; j < p.Players.Length; ++j ) { DuelPlayer pl = p.Players[j]; if ( pl != null && pl.Ready ) { AddImage( 35 + offset, y + 4, 0x939 ); } else { AddImage( 35 + offset, y + 4, 0x938 ); isAllReady = false; } string name = ( pl == null ? "(Empty)" : pl.Mobile.Name ); AddHtml( 35 + offset + 14, y, 166, 20, name, false, false ); y += 22; } if ( p.Players.Length > 1 ) AddImage( 35, yStore + 4, isAllReady ? 0x939 : 0x938 ); } } public override void OnResponse( NetState sender, RelayInfo info ) { } } }
0
0.749898
1
0.749898
game-dev
MEDIA
0.195886
game-dev
0.900113
1
0.900113
kniEngine/kni
2,745
src/Xna.Framework.Content.Pipeline/ContentImporter.cs
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; namespace Microsoft.Xna.Framework.Content.Pipeline { /// <summary> /// Implements a file format importer for use with game assets. /// Importers, either provided by the framework or written by a developer, must derive from ContentImporter, as well as being marked with a ContentImporterAttribute. /// An importer should produce results in the standard intermediate object model. If an asset has information not supported by the object model, the importer should output it as opaque data (key/value attributes attached to the relevant object). By following this procedure, a content pipeline can access specialized digital content creation (DCC) tool information, even when that information has not been fully standardized into the official object model. /// You can also design custom importers that accept and import types containing specific third-party extensions to the object model. /// </summary> public abstract class ContentImporter<T> : IContentImporter { /// <summary> /// Initializes a new instance of ContentImporter. /// </summary> protected ContentImporter() { } /// <summary> /// Called by the framework when importing a game asset. This is the method called by XNA when an asset is to be imported into an object that can be recognized by the Content Pipeline. /// </summary> /// <param name="filename">Name of a game asset file.</param> /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param> /// <returns>Resulting game asset.</returns> public abstract T Import(string filename, ContentImporterContext context); /// <summary> /// Called by the framework when importing a game asset. This is the method called by XNA when an asset is to be imported into an object that can be recognized by the Content Pipeline. /// </summary> /// <param name="filename">Name of a game asset file.</param> /// <param name="context">Contains information for importing a game asset, such as a logger interface.</param> /// <returns>Resulting game asset.</returns> Object IContentImporter.Import(string filename, ContentImporterContext context) { if (filename == null) throw new ArgumentNullException("filename"); if (context == null) throw new ArgumentNullException("context"); return Import(filename, context); } } }
0
0.513196
1
0.513196
game-dev
MEDIA
0.64552
game-dev
0.661458
1
0.661458
umuthopeyildirim/DOOM-Mistral
8,810
src/vizdoom/src/teaminfo.cpp
/* ** teaminfo.cpp ** Parses TEAMINFO and manages teams. ** **--------------------------------------------------------------------------- ** Copyright 2007-2009 Christopher Westley ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR 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. **--------------------------------------------------------------------------- ** */ // HEADER FILES ------------------------------------------------------------ #include "c_dispatch.h" #include "gi.h" #include "i_system.h" #include "teaminfo.h" #include "v_font.h" #include "v_video.h" #include "w_wad.h" // MACROS ------------------------------------------------------------------ // TYPES ------------------------------------------------------------------- // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- // PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- // EXTERNAL DATA DECLARATIONS ---------------------------------------------- // PUBLIC DATA DEFINITIONS ------------------------------------------------- FTeam TeamLibrary; TArray<FTeam> Teams; // PRIVATE DATA DEFINITIONS ------------------------------------------------ static const char *TeamInfoOptions[] = { "Game", "PlayerColor", "TextColor", "Logo", "AllowCustomPlayerColor", "RailColor", "FlagItem", "SkullItem", "PlayerStartThingNumber", "SmallFlagHUDIcon", "SmallSkullHUDIcon", "LargeFlagHUDIcon", "LargeSkullHUDIcon", "WinnerPic", "LoserPic", "WinnerTheme", "LoserTheme", }; enum ETeamOptions { TEAMINFO_Game, TEAMINFO_PlayerColor, TEAMINFO_TextColor, TEAMINFO_Logo, TEAMINFO_AllowCustomPlayerColor, TEAMINFO_RailColor, TEAMINFO_FlagItem, TEAMINFO_SkullItem, TEAMINFO_PlayerStartThingNumber, TEAMINFO_SmallFlagHUDIcon, TEAMINFO_SmallSkullHUDIcon, TEAMINFO_LargeFlagHUDIcon, TEAMINFO_LargeSkullHUDIcon, TEAMINFO_WinnerPic, TEAMINFO_LoserPic, TEAMINFO_WinnerTheme, TEAMINFO_LoserTheme, }; // CODE -------------------------------------------------------------------- //========================================================================== // // FTeam :: FTeam // //========================================================================== FTeam::FTeam () { m_iPlayerColor = 0; m_iPlayerCount = 0; m_iScore = 0; m_iPresent = 0; m_iTies = 0; m_bAllowCustomPlayerColor = false; } //========================================================================== // // FTeam :: ParseTeamInfo // //========================================================================== void FTeam::ParseTeamInfo () { int iLump, iLastLump = 0; Teams.Clear(); while ((iLump = Wads.FindLump ("TEAMINFO", &iLastLump)) != -1) { FScanner Scan (iLump); while (Scan.GetString ()) { if (Scan.Compare ("ClearTeams")) ClearTeams (); else if (Scan.Compare ("Team")) ParseTeamDefinition (Scan); else Scan.ScriptError ("ParseTeamInfo: Unknown team command '%s'.\n", Scan.String); } } if (Teams.Size () < 2) I_FatalError ("ParseTeamInfo: At least two teams must be defined in TEAMINFO."); else if (Teams.Size () > (unsigned)TEAM_MAXIMUM) I_FatalError ("ParseTeamInfo: Too many teams defined. (Maximum: %d)", TEAM_MAXIMUM); } //========================================================================== // // FTeam :: ParseTeamDefinition // //========================================================================== void FTeam::ParseTeamDefinition (FScanner &Scan) { FTeam Team; int valid = -1; Scan.MustGetString (); Team.m_Name = Scan.String; Scan.MustGetStringName ("{"); while (!Scan.CheckString ("}")) { Scan.MustGetString (); switch (Scan.MatchString (TeamInfoOptions)) { case TEAMINFO_Game: Scan.MustGetString (); if (Scan.Compare("Any")) valid = 1; else if (CheckGame(Scan.String, false)) valid = 1; else if (valid == -1) valid = 0; break; case TEAMINFO_PlayerColor: Scan.MustGetString (); Team.m_iPlayerColor = V_GetColor (NULL, Scan.String); break; case TEAMINFO_TextColor: Scan.MustGetString (); Team.m_TextColor.AppendFormat ("[%s]", Scan.String); break; case TEAMINFO_Logo: Scan.MustGetString (); Team.m_Logo = Scan.String; break; case TEAMINFO_AllowCustomPlayerColor: Team.m_bAllowCustomPlayerColor = true; break; case TEAMINFO_PlayerStartThingNumber: Scan.MustGetNumber (); break; case TEAMINFO_RailColor: case TEAMINFO_FlagItem: case TEAMINFO_SkullItem: case TEAMINFO_SmallFlagHUDIcon: case TEAMINFO_SmallSkullHUDIcon: case TEAMINFO_LargeFlagHUDIcon: case TEAMINFO_LargeSkullHUDIcon: case TEAMINFO_WinnerPic: case TEAMINFO_LoserPic: case TEAMINFO_WinnerTheme: case TEAMINFO_LoserTheme: Scan.MustGetString (); break; default: Scan.ScriptError ("ParseTeamDefinition: Unknown team option '%s'.\n", Scan.String); break; } } if (valid) Teams.Push (Team); } //========================================================================== // // FTeam :: ClearTeams // //========================================================================== void FTeam::ClearTeams () { Teams.Clear (); } //========================================================================== // // FTeam :: IsValidTeam // //========================================================================== bool FTeam::IsValidTeam (unsigned int uiTeam) { if (uiTeam >= Teams.Size ()) return false; return true; } //========================================================================== // // FTeam :: GetName // //========================================================================== const char *FTeam::GetName () const { return m_Name; } //========================================================================== // // FTeam :: GetPlayerColor // //========================================================================== int FTeam::GetPlayerColor () const { return m_iPlayerColor; } //========================================================================== // // FTeam :: GetTextColor // //========================================================================== int FTeam::GetTextColor () const { if (m_TextColor.IsEmpty ()) return CR_UNTRANSLATED; const BYTE *pColor = (const BYTE *)m_TextColor.GetChars (); int iColor = V_ParseFontColor (pColor, 0, 0); if (iColor == CR_UNDEFINED) { Printf ("GetTextColor: Undefined color '%s' in definition of team '%s'.\n", m_TextColor.GetChars (), m_Name.GetChars ()); return CR_UNTRANSLATED; } return iColor; } //========================================================================== // // FTeam :: GetLogo // //========================================================================== FString FTeam::GetLogo () const { return m_Logo; } //========================================================================== // // FTeam :: GetAllowCustomPlayerColor // //========================================================================== bool FTeam::GetAllowCustomPlayerColor () const { return m_bAllowCustomPlayerColor; } //========================================================================== // // CCMD teamlist // //========================================================================== CCMD (teamlist) { Printf ("Defined teams are as follows:\n"); for (unsigned int uiTeam = 0; uiTeam < Teams.Size (); uiTeam++) Printf ("%d : %s\n", uiTeam, Teams[uiTeam].GetName ()); Printf ("End of team list.\n"); }
0
0.873633
1
0.873633
game-dev
MEDIA
0.707711
game-dev
0.90489
1
0.90489
ashfurrow/NSFetchedResultsController-MVVM
7,540
Pods/ReactiveCocoa/ReactiveCocoaFramework/ReactiveCocoa/extobjc/RACEXTRuntimeExtensions.m
// // EXTRuntimeExtensions.m // extobjc // // Created by Justin Spahr-Summers on 2011-03-05. // Copyright (C) 2012 Justin Spahr-Summers. // Released under the MIT license. // #import "RACEXTRuntimeExtensions.h" #import <ctype.h> #import <libkern/OSAtomic.h> #import <objc/message.h> #import <pthread.h> #import <stdio.h> #import <stdlib.h> #import <string.h> rac_propertyAttributes *rac_copyPropertyAttributes (objc_property_t property) { const char * const attrString = property_getAttributes(property); if (!attrString) { fprintf(stderr, "ERROR: Could not get attribute string from property %s\n", property_getName(property)); return NULL; } if (attrString[0] != 'T') { fprintf(stderr, "ERROR: Expected attribute string \"%s\" for property %s to start with 'T'\n", attrString, property_getName(property)); return NULL; } const char *typeString = attrString + 1; const char *next = NSGetSizeAndAlignment(typeString, NULL, NULL); if (!next) { fprintf(stderr, "ERROR: Could not read past type in attribute string \"%s\" for property %s\n", attrString, property_getName(property)); return NULL; } size_t typeLength = (size_t)(next - typeString); if (!typeLength) { fprintf(stderr, "ERROR: Invalid type in attribute string \"%s\" for property %s\n", attrString, property_getName(property)); return NULL; } // allocate enough space for the structure and the type string (plus a NUL) rac_propertyAttributes *attributes = calloc(1, sizeof(rac_propertyAttributes) + typeLength + 1); if (!attributes) { fprintf(stderr, "ERROR: Could not allocate rac_propertyAttributes structure for attribute string \"%s\" for property %s\n", attrString, property_getName(property)); return NULL; } // copy the type string strncpy(attributes->type, typeString, typeLength); attributes->type[typeLength] = '\0'; // if this is an object type, and immediately followed by a quoted string... if (typeString[0] == *(@encode(id)) && typeString[1] == '"') { // we should be able to extract a class name const char *className = typeString + 2; next = strchr(className, '"'); if (!next) { fprintf(stderr, "ERROR: Could not read class name in attribute string \"%s\" for property %s\n", attrString, property_getName(property)); return NULL; } if (className != next) { size_t classNameLength = (size_t)(next - className); char trimmedName[classNameLength + 1]; strncpy(trimmedName, className, classNameLength); trimmedName[classNameLength] = '\0'; // attempt to look up the class in the runtime attributes->objectClass = objc_getClass(trimmedName); } } if (*next != '\0') { // skip past any junk before the first flag next = strchr(next, ','); } while (next && *next == ',') { char flag = next[1]; next += 2; switch (flag) { case '\0': break; case 'R': attributes->readonly = YES; break; case 'C': attributes->memoryManagementPolicy = rac_propertyMemoryManagementPolicyCopy; break; case '&': attributes->memoryManagementPolicy = rac_propertyMemoryManagementPolicyRetain; break; case 'N': attributes->nonatomic = YES; break; case 'G': case 'S': { const char *nextFlag = strchr(next, ','); SEL name = NULL; if (!nextFlag) { // assume that the rest of the string is the selector const char *selectorString = next; next = ""; name = sel_registerName(selectorString); } else { size_t selectorLength = (size_t)(nextFlag - next); if (!selectorLength) { fprintf(stderr, "ERROR: Found zero length selector name in attribute string \"%s\" for property %s\n", attrString, property_getName(property)); goto errorOut; } char selectorString[selectorLength + 1]; strncpy(selectorString, next, selectorLength); selectorString[selectorLength] = '\0'; name = sel_registerName(selectorString); next = nextFlag; } if (flag == 'G') attributes->getter = name; else attributes->setter = name; } break; case 'D': attributes->dynamic = YES; attributes->ivar = NULL; break; case 'V': // assume that the rest of the string (if present) is the ivar name if (*next == '\0') { // if there's nothing there, let's assume this is dynamic attributes->ivar = NULL; } else { attributes->ivar = next; next = ""; } break; case 'W': attributes->weak = YES; break; case 'P': attributes->canBeCollected = YES; break; case 't': fprintf(stderr, "ERROR: Old-style type encoding is unsupported in attribute string \"%s\" for property %s\n", attrString, property_getName(property)); // skip over this type encoding while (*next != ',' && *next != '\0') ++next; break; default: fprintf(stderr, "ERROR: Unrecognized attribute string flag '%c' in attribute string \"%s\" for property %s\n", flag, attrString, property_getName(property)); } } if (next && *next != '\0') { fprintf(stderr, "Warning: Unparsed data \"%s\" in attribute string \"%s\" for property %s\n", next, attrString, property_getName(property)); } if (!attributes->getter) { // use the property name as the getter by default attributes->getter = sel_registerName(property_getName(property)); } if (!attributes->setter) { const char *propertyName = property_getName(property); size_t propertyNameLength = strlen(propertyName); // we want to transform the name to setProperty: style size_t setterLength = propertyNameLength + 4; char setterName[setterLength + 1]; strncpy(setterName, "set", 3); strncpy(setterName + 3, propertyName, propertyNameLength); // capitalize property name for the setter setterName[3] = (char)toupper(setterName[3]); setterName[setterLength - 1] = ':'; setterName[setterLength] = '\0'; attributes->setter = sel_registerName(setterName); } return attributes; errorOut: free(attributes); return NULL; } Method rac_getImmediateInstanceMethod (Class aClass, SEL aSelector) { unsigned methodCount = 0; Method *methods = class_copyMethodList(aClass, &methodCount); Method foundMethod = NULL; for (unsigned methodIndex = 0;methodIndex < methodCount;++methodIndex) { if (method_getName(methods[methodIndex]) == aSelector) { foundMethod = methods[methodIndex]; break; } } free(methods); return foundMethod; }
0
0.98097
1
0.98097
game-dev
MEDIA
0.512011
game-dev
0.986826
1
0.986826
Pico-Developer/PICO-Unity-Integration-SDK
2,390
Runtime/Scripts/Features/PXR_LateLatching.cs
#if !PICO_OPENXR_SDK using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.XR; namespace Unity.XR.PXR { [Serializable] public class PXR_LateLatching : MonoBehaviour { #if UNITY_2020_3_OR_NEWER private Camera m_LateLatchingCamera; static XRDisplaySubsystem s_DisplaySubsystem = null; static List<XRDisplaySubsystem> s_DisplaySubsystems = new List<XRDisplaySubsystem>(); private void Awake() { m_LateLatchingCamera = GetComponent<Camera>(); } private void OnEnable() { List<XRDisplaySubsystem> displaySubsystems = new List<XRDisplaySubsystem>(); #if UNITY_6000_0_OR_NEWER SubsystemManager.GetSubsystems(displaySubsystems); #else SubsystemManager.GetInstances(displaySubsystems); #endif Debug.Log("PXR_U OnEnable() displaySubsystems.Count = " + displaySubsystems.Count); for (int i = 0; i < displaySubsystems.Count; i++) { s_DisplaySubsystem = displaySubsystems[i]; } } private void OnDisable() { } void Update() { if (s_DisplaySubsystem == null) { List<XRDisplaySubsystem> displaySubsystems = new List<XRDisplaySubsystem>(); #if UNITY_6000_0_OR_NEWER SubsystemManager.GetSubsystems(displaySubsystems); #else SubsystemManager.GetInstances(displaySubsystems); #endif if (displaySubsystems.Count > 0) { s_DisplaySubsystem = displaySubsystems[0]; } } if (null == s_DisplaySubsystem) return; s_DisplaySubsystem.MarkTransformLateLatched(m_LateLatchingCamera.transform, XRDisplaySubsystem.LateLatchNode.Head); } #if !UNITY_EDITOR && UNITY_2021_2_OR_NEWER private void OnPreRender() { s_DisplaySubsystem.BeginRecordingIfLateLatched(m_LateLatchingCamera); } private void OnPostRender() { s_DisplaySubsystem.EndRecordingIfLateLatched(m_LateLatchingCamera); } #endif private void FixedUpdate() { } private void LateUpdate() { } #endif } } #endif
0
0.841867
1
0.841867
game-dev
MEDIA
0.569753
game-dev
0.909946
1
0.909946
TaiyitistMC/Taiyitist
1,602
modules/taiyitist-server/src/main/java/com/taiyitistmc/mixin/world/entity/frog/MixinTadpole.java
package com.taiyitistmc.mixin.world.entity.frog; import com.llamalad7.mixinextras.sugar.Local; import net.minecraft.world.entity.animal.frog.Frog; import net.minecraft.world.entity.animal.frog.Tadpole; import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.event.entity.EntityRemoveEvent; 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; @Mixin(Tadpole.class) public abstract class MixinTadpole { @Shadow protected abstract void setAge(int i); @Inject(method = "ageUp()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/animal/frog/Frog;fudgePositionAfterSizeChange(Lnet/minecraft/world/entity/EntityDimensions;)Z") ) private void taiyitist$transformerEvent(CallbackInfo ci, @Local Frog frog) { // CraftBukkit start if (CraftEventFactory.callEntityTransformEvent(((Tadpole) (Object) this), frog, org.bukkit.event.entity.EntityTransformEvent.TransformReason.METAMORPHOSIS).isCancelled()) { this.setAge(0); // Sets the age to 0 for avoid a loop if the event is canceled } } @Inject(method = "ageUp()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/animal/frog/Tadpole;discard()V")) private void taiyitist$pushRemoveReason(CallbackInfo ci, @Local Frog frog) { frog.pushRemoveCause(EntityRemoveEvent.Cause.TRANSFORMATION); } }
0
0.843634
1
0.843634
game-dev
MEDIA
0.999346
game-dev
0.896663
1
0.896663
hieki-chan/Supermarket-Simulator-Prototype
23,883
Library/PackageCache/com.unity.timeline@1.7.6/Editor/Recording/TimelineRecording.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using UnityEngine; using UnityEngine.Timeline; using UnityEngine.Playables; namespace UnityEditor.Timeline { // Handles Undo animated properties on Monobehaviours to create track clips static partial class TimelineRecording { static readonly List<PropertyModification> s_TempPropertyModifications = new List<PropertyModification>(6); internal static UndoPropertyModification[] ProcessUndoModification(UndoPropertyModification[] modifications, WindowState state) { if (HasAnyPlayableAssetModifications(modifications)) return ProcessPlayableAssetModification(modifications, state, false); return ProcessMonoBehaviourModification(modifications, state); } static UnityEngine.Object GetTarget(UndoPropertyModification undo) { if (undo.currentValue != null) return undo.currentValue.target; if (undo.previousValue != null) return undo.previousValue.target; return null; } // Gets the appropriate track for a given game object static TrackAsset GetTrackForGameObject(GameObject gameObject, WindowState state) { if (gameObject == null) return null; var director = state.editSequence.director; if (director == null) return null; var level = int.MaxValue; TrackAsset result = null; // search the output tracks var outputTracks = state.editSequence.asset.flattenedTracks; foreach (var track in outputTracks) { if (track.GetType() != typeof(AnimationTrack)) continue; if (!state.IsTrackRecordable(track)) continue; var obj = TimelineUtility.GetSceneGameObject(director, track); if (obj != null) { // checks if the effected gameobject is our child var childLevel = GetChildLevel(obj, gameObject); if (childLevel != -1 && childLevel < level) { result = track; level = childLevel; } } } // the resulting track is not armed. checking here avoids accidentally recording objects with their own // tracks if (result && !state.IsTrackRecordable(result)) { result = null; } return result; } // Gets the track this property would record to. // Returns null if there is a track, but it's not currently active for recording public static TrackAsset GetRecordingTrack(SerializedProperty property, WindowState state) { var serializedObject = property.serializedObject; var component = serializedObject.targetObject as Component; if (component == null) return null; var gameObject = component.gameObject; return GetTrackForGameObject(gameObject, state); } // Given a serialized property, gathers all animatable properties static void GatherModifications(SerializedProperty property, List<PropertyModification> modifications) { // handles child properties (Vector3 is 3 recordable properties) if (property.hasChildren) { var iter = property.Copy(); var end = property.GetEndProperty(false); // recurse over all children properties while (iter.Next(true) && !SerializedProperty.EqualContents(iter, end)) { GatherModifications(iter, modifications); } } var isObject = property.propertyType == SerializedPropertyType.ObjectReference; var isFloat = property.propertyType == SerializedPropertyType.Float || property.propertyType == SerializedPropertyType.Boolean || property.propertyType == SerializedPropertyType.Integer; if (isObject || isFloat) { var serializedObject = property.serializedObject; var modification = new PropertyModification(); modification.target = serializedObject.targetObject; modification.propertyPath = property.propertyPath; if (isObject) { modification.value = string.Empty; modification.objectReference = property.objectReferenceValue; } else { modification.value = TimelineUtility.PropertyToString(property); } // Path for monobehaviour based - better to grab the component to get the curvebinding to allow validation if (serializedObject.targetObject is Component) { EditorCurveBinding temp; var go = ((Component)serializedObject.targetObject).gameObject; if (AnimationUtility.PropertyModificationToEditorCurveBinding(modification, go, out temp) != null) { modifications.Add(modification); } } else { modifications.Add(modification); } } } public static void AddKey(SerializedProperty prop, WindowState state) { s_TempPropertyModifications.Clear(); GatherModifications(prop, s_TempPropertyModifications); if (s_TempPropertyModifications.Any()) { AddKey(s_TempPropertyModifications, state); } } public static void AddKey(IEnumerable<PropertyModification> modifications, WindowState state) { var undos = modifications.Select(PropertyModificationToUndoPropertyModification).ToArray(); if (HasAnyPlayableAssetModifications(undos)) ProcessPlayableAssetModification(undos, state, true); ProcessMonoBehaviourModification(undos, state); } static UndoPropertyModification PropertyModificationToUndoPropertyModification(PropertyModification prop) { return new UndoPropertyModification { previousValue = prop, currentValue = new PropertyModification { objectReference = prop.objectReference, propertyPath = prop.propertyPath, target = prop.target, value = prop.value }, keepPrefabOverride = true }; } // Given an animation track, return the clip that we are currently recording to static AnimationClip GetRecordingClip(TrackAsset asset, WindowState state, out double startTime, out double timeScale) { startTime = 0; timeScale = 1; TimelineClip displayBackground = null; asset.FindRecordingClipAtTime(state.editSequence.time, out displayBackground); var animClip = asset.FindRecordingAnimationClipAtTime(state.editSequence.time); if (displayBackground != null) { startTime = displayBackground.start; timeScale = displayBackground.timeScale; } return animClip; } // Helper that finds the animation clip we are recording and the relative time to that clip static bool GetClipAndRelativeTime(UnityEngine.Object target, WindowState state, out AnimationClip outClip, out double keyTime, out bool keyInRange) { const float floatToDoubleError = 0.00001f; outClip = null; keyTime = 0; keyInRange = false; double startTime = 0; double timeScale = 1; AnimationClip clip = null; IPlayableAsset playableAsset = target as IPlayableAsset; Component component = target as Component; // Handle recordable playable assets if (playableAsset != null) { var curvesOwner = AnimatedParameterUtility.ToCurvesOwner(playableAsset, state.editSequence.asset); if (curvesOwner != null) { if (curvesOwner.curves == null) curvesOwner.CreateCurves(curvesOwner.GetUniqueRecordedClipName()); clip = curvesOwner.curves; var timelineClip = curvesOwner as TimelineClip; if (timelineClip != null) { startTime = timelineClip.start; timeScale = timelineClip.timeScale; } } } // Handle recording components, including infinite clip else if (component != null) { var asset = GetTrackForGameObject(component.gameObject, state); if (asset != null) { clip = GetRecordingClip(asset, state, out startTime, out timeScale); } } if (clip == null) return false; keyTime = (state.editSequence.time - startTime) * timeScale; outClip = clip; keyInRange = keyTime >= 0 && keyTime <= (clip.length * timeScale + floatToDoubleError); return true; } public static bool HasCurve(IList<PropertyModification> modifications, UnityEngine.Object target, WindowState state) { return GetKeyTimes(modifications, state).Any(); } public static bool HasKey(IList<PropertyModification> modifications, WindowState state) { AnimationClip clip; double keyTime; bool inRange; if (!GetClipAndRelativeTime(modifications[0].target, state, out clip, out keyTime, out inRange)) return false; return GetKeyTimes(modifications, state).Any(t => (CurveEditUtility.KeyCompare((float)state.editSequence.time, (float)t, clip.frameRate) == 0)); } // Checks if a key already exists for this property static bool HasBinding(UnityEngine.Object target, PropertyModification modification, AnimationClip clip, out EditorCurveBinding binding) { var component = target as Component; var playableAsset = target as IPlayableAsset; if (component != null) { var type = AnimationUtility.PropertyModificationToEditorCurveBinding(modification, component.gameObject, out binding); binding = RotationCurveInterpolation.RemapAnimationBindingForRotationCurves(binding, clip); return type != null; } if (playableAsset != null) { binding = EditorCurveBinding.FloatCurve(string.Empty, target.GetType(), AnimatedParameterUtility.GetAnimatedParameterBindingName(target, modification.propertyPath)); } else { binding = new EditorCurveBinding(); return false; } return true; } public static void RemoveKey(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state) { AnimationClip clip; double keyTime; bool inRange; if (!GetClipAndRelativeTime(target, state, out clip, out keyTime, out inRange) || !inRange) return; var refreshPreview = false; TimelineUndo.PushUndo(clip, L10n.Tr("Remove Key")); foreach (var mod in modifications) { EditorCurveBinding temp; if (HasBinding(target, mod, clip, out temp)) { if (temp.isPPtrCurve) { CurveEditUtility.RemoveObjectKey(clip, temp, keyTime); if (CurveEditUtility.GetObjectKeyCount(clip, temp) == 0) { refreshPreview = true; } } else { AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, temp); if (curve != null) { CurveEditUtility.RemoveKeyFrameFromCurve(curve, (float)keyTime, clip.frameRate); AnimationUtility.SetEditorCurve(clip, temp, curve); if (curve.length == 0) { AnimationUtility.SetEditorCurve(clip, temp, null); refreshPreview = true; } } } } } if (refreshPreview) { state.ResetPreviewMode(); } } static HashSet<double> GetKeyTimes(IList<PropertyModification> modifications, WindowState state) { var keyTimes = new HashSet<double>(); AnimationClip animationClip; double keyTime; bool inRange; var component = modifications[0].target as Component; var target = modifications[0].target; if (component != null) { var track = GetTrackForGameObject(component.gameObject, state); var go = TimelineUtility.GetSceneGameObject(TimelineEditor.inspectedDirector, track); if (go != null) { target = go.transform; } } GetClipAndRelativeTime(target, state, out animationClip, out keyTime, out inRange); if (animationClip == null) return keyTimes; var playableAsset = target as IPlayableAsset; var info = AnimationClipCurveCache.Instance.GetCurveInfo(animationClip); TimelineClip clip = null; if (component != null) { GetTrackForGameObject(component.gameObject, state).FindRecordingClipAtTime(state.editSequence.time, out clip); } else if (playableAsset != null) { clip = FindClipWithAsset(state.editSequence.asset, playableAsset); } foreach (var mod in modifications) { EditorCurveBinding temp; if (HasBinding(target, mod, animationClip, out temp)) { IEnumerable<double> keys = new HashSet<double>(); if (temp.isPPtrCurve) { var curve = info.GetObjectCurveForBinding(temp); if (curve != null) { keys = curve.Select(x => (double)x.time); } } else { var curve = info.GetCurveForBinding(temp); if (curve != null) { keys = curve.keys.Select(x => (double)x.time); } } // Transform the times in to 'global' space using the clip if (clip != null) { foreach (var k in keys) { var time = clip.FromLocalTimeUnbound(k); const double eps = 1e-5; if (time >= clip.start - eps && time <= clip.end + eps) { keyTimes.Add(time); } } } // infinite clip mode, global == local space else { keyTimes.UnionWith(keys); } } } return keyTimes; } public static void NextKey(UnityEngine.Object target, IList<PropertyModification> modifications, WindowState state) { const double eps = 1e-5; var keyTimes = GetKeyTimes(modifications, state); if (keyTimes.Count == 0) return; var nextKeys = keyTimes.Where(x => x > state.editSequence.time + eps); if (nextKeys.Any()) { state.editSequence.time = nextKeys.Min(); } } public static void PrevKey(UnityEngine.Object target, IList<PropertyModification> modifications, WindowState state) { const double eps = 1e-5; var keyTimes = GetKeyTimes(modifications, state); if (keyTimes.Count == 0) return; var prevKeys = keyTimes.Where(x => x < state.editSequence.time - eps); if (prevKeys.Any()) { state.editSequence.time = prevKeys.Max(); } } public static void RemoveCurve(UnityEngine.Object target, IEnumerable<PropertyModification> modifications, WindowState state) { AnimationClip clip = null; double keyTime = 0; var inRange = false; // not used for curves if (!GetClipAndRelativeTime(target, state, out clip, out keyTime, out inRange)) return; TimelineUndo.PushUndo(clip, L10n.Tr("Remove Curve")); foreach (var mod in modifications) { EditorCurveBinding temp; if (HasBinding(target, mod, clip, out temp)) { if (temp.isPPtrCurve) AnimationUtility.SetObjectReferenceCurve(clip, temp, null); else AnimationUtility.SetEditorCurve(clip, temp, null); } } state.ResetPreviewMode(); } public static void KeyAllProperties(Component target, WindowState state) { var go = target is Component component ? component.gameObject : null; GetClipAndRelativeTime(target, state, out var animationClip, out _, out _); var info = AnimationClipCurveCache.Instance.GetCurveInfo(animationClip); if (animationClip != null && info.curves.Length > 0) { KeyProperties(go, state, info.bindings); } } public static void KeyProperties(GameObject go, WindowState state, IList<EditorCurveBinding> bindings) { var allKeyedProperties = new List<PropertyModification>(); var rotationPaths = new HashSet<string>(); for (var i = 0; i < bindings.Count; ++i) { // Skip the euler and key quaternion+hint if (CurveEditUtility.IsRotationKey(bindings[i])) { rotationPaths.Add(bindings[i].path); continue; } AnimationUtility.GetFloatValue(go, bindings[i], out var val); var compo = GetTargetFromEditorBinding(go, bindings[i]); allKeyedProperties.Add(new PropertyModification { target = compo, value = val.ToString(EditorGUI.kFloatFieldFormatString), propertyPath = bindings[i].propertyName }); } foreach (var path in rotationPaths) { foreach (var binding in GetRotationBindings(path)) { var compo = GetTargetFromEditorBinding(go, binding); var readBinding = binding; switch (binding.propertyName) { case kLocalEulerHint + ".x": readBinding = EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalRotation + ".x"); break; case kLocalEulerHint + ".y": readBinding = EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalRotation + ".y"); break; case kLocalEulerHint + ".z": readBinding = EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalRotation + ".z"); break; } AnimationUtility.GetFloatValue(go, readBinding, out var val); allKeyedProperties.Add(new PropertyModification { target = compo, value = val.ToString(EditorGUI.kFloatFieldFormatString), propertyPath = binding.propertyName }); } } AddKey(allKeyedProperties, state); state.Refresh(); } static IEnumerable<EditorCurveBinding> GetRotationBindings(string path) { return new[] { EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalRotation + ".x"), EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalRotation + ".y"), EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalRotation + ".z"), EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalRotation + ".w"), EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalEulerHint + ".x"), EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalEulerHint + ".y"), EditorCurveBinding.FloatCurve(path, typeof(Transform), kLocalEulerHint + ".z"), }; } static Component GetTargetFromEditorBinding(GameObject root, EditorCurveBinding binding) { GameObject go = null; if (string.IsNullOrEmpty(binding.path)) { go = root; } var childTransform = root.transform.Find(binding.path); if (childTransform != null) { go = childTransform.gameObject; } if (go != null) { return go.GetComponent(binding.type); } return null; } public static IEnumerable<GameObject> GetRecordableGameObjects(WindowState state) { if (state == null || state.editSequence.asset == null || state.editSequence.director == null) yield break; var outputTracks = state.editSequence.asset.GetOutputTracks(); foreach (var track in outputTracks) { if (track.GetType() != typeof(AnimationTrack)) continue; if (!state.IsTrackRecordable(track) && !track.GetChildTracks().Any(state.IsTrackRecordable)) continue; var obj = TimelineUtility.GetSceneGameObject(state.editSequence.director, track); if (obj != null) { yield return obj; } } } } }
0
0.943977
1
0.943977
game-dev
MEDIA
0.981599
game-dev
0.869887
1
0.869887
XColorful/BattleRoyale
1,738
core/src/main/java/xiao/battleroyale/config/common/game/zone/zoneshape/CubeEntry.java
package xiao.battleroyale.config.common.game.zone.zoneshape; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import xiao.battleroyale.BattleRoyale; import xiao.battleroyale.api.game.zone.gamezone.ISpatialZone; import xiao.battleroyale.api.game.zone.shape.ZoneShapeTag; import xiao.battleroyale.common.game.zone.spatial.CubeShape; import javax.annotation.Nullable; public class CubeEntry extends AbstractSimpleEntry { public CubeEntry(StartEntry startEntry, EndEntry endEntry, boolean badShape) { super(startEntry, endEntry, badShape); } @Override public @NotNull CubeEntry copy() { return new CubeEntry(startEntry.copy(), endEntry.copy(), badShape); } @Override public String getType() { return ZoneShapeTag.CUBE; } @Override public ZoneShapeType getZoneShapeType() { return ZoneShapeType.CUBE; } @Override public ISpatialZone createSpatialZone() { return new CubeShape(startEntry.copy(), endEntry.copy(), badShape); } @Nullable public static CubeEntry fromJson(JsonObject jsonObject) { StartEntry startEntry = AbstractSimpleEntry.readStartEntry(jsonObject); if (startEntry == null) { BattleRoyale.LOGGER.info("Invalid startEntry for CubeEntry, skipped"); return null; } EndEntry endEntry = AbstractSimpleEntry.readEndEntry(jsonObject); if (endEntry == null) { BattleRoyale.LOGGER.info("Invalid startEntry or endEntry for CubeEntry, skipped"); return null; } boolean badShape = AbstractSimpleEntry.readBadShape(jsonObject); return new CubeEntry(startEntry, endEntry, badShape); } }
0
0.739704
1
0.739704
game-dev
MEDIA
0.782642
game-dev
0.866995
1
0.866995
microsoft/MixedReality-WorldLockingTools-Samples
2,734
Advanced/AlignSubScene/Assets/MRTK/Core/Providers/Hands/HandJointUtils.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Input { public static class HandJointUtils { /// <summary> /// Tries to get the pose of the requested joint for the first controller with the specified handedness. /// </summary> /// <param name="joint">The requested joint</param> /// <param name="handedness">The specific hand of interest. This should be either Handedness.Left or Handedness.Right</param> /// <param name="pose">The output pose data</param> public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) { return TryGetJointPose<IMixedRealityHand>(joint, handedness, out pose); } /// <summary> /// Try to find the first matching hand controller of the given type and return the pose of the requested joint for that hand. /// </summary> public static bool TryGetJointPose<T>(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) where T : class, IMixedRealityHand { T hand = FindHand<T>(handedness); if (hand != null) { return hand.TryGetJoint(joint, out pose); } pose = MixedRealityPose.ZeroIdentity; return false; } /// <summary> /// Find the first detected hand controller with matching handedness. /// </summary> /// <remarks> /// The given handedness should be either Handedness.Left or Handedness.Right. /// </remarks> public static IMixedRealityHand FindHand(Handedness handedness) { return FindHand<IMixedRealityHand>(handedness); } /// <summary> /// Find the first detected hand controller of the given type with matching handedness. /// </summary> public static T FindHand<T>(Handedness handedness) where T : class, IMixedRealityHand { System.Collections.Generic.HashSet<IMixedRealityController> controllers = CoreServices.InputSystem?.DetectedControllers; if (controllers == null) { return null; } foreach (IMixedRealityController detectedController in controllers) { if (detectedController is T hand) { if (detectedController.ControllerHandedness.IsMatch(handedness)) { return hand; } } } return null; } } }
0
0.822395
1
0.822395
game-dev
MEDIA
0.638747
game-dev
0.883115
1
0.883115
stefanhendriks/Dune-II---The-Maker
1,632
src/controls/mousestates/cMouseNormalState.h
#pragma once #include "cMouseState.h" #include "controls/cMouse.h" #include "sMouseEvent.h" #include "controls/cKeyboardEvent.h" class cPlayer; enum eMouseNormalState { SELECT_STATE_NORMAL, // normal state, selecting stuff, etc SELECT_STATE_RALLY, // set rally point for structure }; inline const char *mouseNormalStateString(const eMouseNormalState &state) { switch (state) { case SELECT_STATE_NORMAL: return "SELECT_STATE_NORMAL"; case SELECT_STATE_RALLY: return "SELECT_STATE_RALLY"; default: assert(false); break; } return ""; } /** * A mouse normal state is at the battlefield, and is the default state the mouse is in. It can select units, drag * a border (for multi-select) and drag the viewport * */ class cMouseNormalState : public cMouseState { public: explicit cMouseNormalState(cPlayer *player, cGameControlsContext *context, cMouse *mouse); void onNotifyMouseEvent(const s_MouseEvent &event) override; void onNotifyKeyboardEvent(const cKeyboardEvent &event) override; void onNotifyGameEvent(const s_GameEvent &) override {} void onStateSet() override; void onFocus() override; void onBlur() override; private: eMouseNormalState m_state; void onMouseLeftButtonClicked(); void onMouseRightButtonPressed(); void onMouseRightButtonClicked(); void onMouseMovedTo(); void onKeyDown(const cKeyboardEvent &event); void onKeyPressed(const cKeyboardEvent &event); void setState(eMouseNormalState newState); int getMouseTileForNormalState() const; };
0
0.917209
1
0.917209
game-dev
MEDIA
0.5773
game-dev
0.602462
1
0.602462
IJEMIN/Unity-Programming-Essence-2021
6,784
19/Done/Zombie Multiplayer/Assets/Photon/PhotonUnityNetworking/Code/Views/PhotonTransformView.cs
// ---------------------------------------------------------------------------- // <copyright file="PhotonTransformView.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH // </copyright> // <summary> // Component to synchronize Transforms via PUN PhotonView. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- namespace Photon.Pun { using UnityEngine; [AddComponentMenu("Photon Networking/Photon Transform View")] [HelpURL("https://doc.photonengine.com/en-us/pun/v2/gameplay/synchronization-and-state")] public class PhotonTransformView : MonoBehaviourPun, IPunObservable { private float m_Distance; private float m_Angle; private Vector3 m_Direction; private Vector3 m_NetworkPosition; private Vector3 m_StoredPosition; private Quaternion m_NetworkRotation; public bool m_SynchronizePosition = true; public bool m_SynchronizeRotation = true; public bool m_SynchronizeScale = false; [Tooltip("Indicates if localPosition and localRotation should be used. Scale ignores this setting, and always uses localScale to avoid issues with lossyScale.")] public bool m_UseLocal; bool m_firstTake = false; public void Awake() { m_StoredPosition = transform.localPosition; m_NetworkPosition = Vector3.zero; m_NetworkRotation = Quaternion.identity; } private void Reset() { // Only default to true with new instances. useLocal will remain false for old projects that are updating PUN. m_UseLocal = true; } void OnEnable() { m_firstTake = true; } public void Update() { var tr = transform; if (!this.photonView.IsMine) { if (m_UseLocal) { tr.localPosition = Vector3.MoveTowards(tr.localPosition, this.m_NetworkPosition, this.m_Distance * (1.0f / PhotonNetwork.SerializationRate)); tr.localRotation = Quaternion.RotateTowards(tr.localRotation, this.m_NetworkRotation, this.m_Angle * (1.0f / PhotonNetwork.SerializationRate)); } else { tr.position = Vector3.MoveTowards(tr.position, this.m_NetworkPosition, this.m_Distance * (1.0f / PhotonNetwork.SerializationRate)); tr.rotation = Quaternion.RotateTowards(tr.rotation, this.m_NetworkRotation, this.m_Angle * (1.0f / PhotonNetwork.SerializationRate)); } } } public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { var tr = transform; // Write if (stream.IsWriting) { if (this.m_SynchronizePosition) { if (m_UseLocal) { this.m_Direction = tr.localPosition - this.m_StoredPosition; this.m_StoredPosition = tr.localPosition; stream.SendNext(tr.localPosition); stream.SendNext(this.m_Direction); } else { this.m_Direction = tr.position - this.m_StoredPosition; this.m_StoredPosition = tr.position; stream.SendNext(tr.position); stream.SendNext(this.m_Direction); } } if (this.m_SynchronizeRotation) { if (m_UseLocal) { stream.SendNext(tr.localRotation); } else { stream.SendNext(tr.rotation); } } if (this.m_SynchronizeScale) { stream.SendNext(tr.localScale); } } // Read else { if (this.m_SynchronizePosition) { this.m_NetworkPosition = (Vector3)stream.ReceiveNext(); this.m_Direction = (Vector3)stream.ReceiveNext(); if (m_firstTake) { if (m_UseLocal) tr.localPosition = this.m_NetworkPosition; else tr.position = this.m_NetworkPosition; this.m_Distance = 0f; } else { float lag = Mathf.Abs((float)(PhotonNetwork.Time - info.SentServerTime)); this.m_NetworkPosition += this.m_Direction * lag; if (m_UseLocal) { this.m_Distance = Vector3.Distance(tr.localPosition, this.m_NetworkPosition); } else { this.m_Distance = Vector3.Distance(tr.position, this.m_NetworkPosition); } } } if (this.m_SynchronizeRotation) { this.m_NetworkRotation = (Quaternion)stream.ReceiveNext(); if (m_firstTake) { this.m_Angle = 0f; if (m_UseLocal) { tr.localRotation = this.m_NetworkRotation; } else { tr.rotation = this.m_NetworkRotation; } } else { if (m_UseLocal) { this.m_Angle = Quaternion.Angle(tr.localRotation, this.m_NetworkRotation); } else { this.m_Angle = Quaternion.Angle(tr.rotation, this.m_NetworkRotation); } } } if (this.m_SynchronizeScale) { tr.localScale = (Vector3)stream.ReceiveNext(); } if (m_firstTake) { m_firstTake = false; } } } } }
0
0.885284
1
0.885284
game-dev
MEDIA
0.729032
game-dev
0.984957
1
0.984957
mamontov-cpp/saddy-graphics-engine-2d
1,228
examples/multithreading/game/getpenetrationdepthforitem.cpp
#include "getpenetrationdepthforitem.h" #include <sadvector.h> /*! Struct for storing mapping from item to depth */ struct ItemNameToDepth { sad::String ItemName; //!< Name of item int Depth; //!< Penetration depth }; static sad::Vector<ItemNameToDepth> itemname_to_penetration_depth; void game::clearItemPenetrationDepths() { itemname_to_penetration_depth.clear(); } void game::setItemPenetrationDepth(const sad::String& string, int depth) { sad::String copy = string; copy.toUpper(); for (size_t i = 0; i < itemname_to_penetration_depth.size(); i++) { if (itemname_to_penetration_depth[i].ItemName == copy) { itemname_to_penetration_depth[i].Depth = depth; return; } } itemname_to_penetration_depth.push_back(ItemNameToDepth{copy, depth}); } int game::getPenetrationDepthForItem(const sad::String& string) { sad::String copy = string; copy.toUpper(); for (size_t i = 0; i < itemname_to_penetration_depth.size(); i++) { if (copy.find(itemname_to_penetration_depth[i].ItemName) != std::string::npos) { return itemname_to_penetration_depth[i].Depth; } } return 0; }
0
0.827671
1
0.827671
game-dev
MEDIA
0.803165
game-dev
0.501306
1
0.501306
hieki-chan/Supermarket-Simulator-Prototype
34,926
Library/PackageCache/com.unity.scriptablebuildpipeline@1.21.23/Editor/Utilities/USerialize/Serializer.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq.Expressions; using System.Reflection; using System.Runtime.InteropServices; using UnityEngine; namespace UnityEditor.Build.Pipeline.Utilities.USerialize { /* * Main USerialize serialzation class. Used to write instances of types to a stream * * To Serialize an object to a stream use code such as * * MemoryStream stream = new MemoryStream(); * USerialize.Serializer serializer = new USerialize.Serializer(); * serializer.Serialize(stream, myClassInstance, 1); // '1' is the version of our object, we can read this value back at deserialization time if we want to determine the version of our data */ internal class Serializer { // Data for a single field of a single type we have serialized. We cache information obtained from the reflection API here as the reflection API can be slow to query internal class FieldData { internal FieldInfo m_FieldInfo; internal string m_Name; internal int m_NameIndex; internal Type m_ElementType; internal bool m_ElementTypeIsPrimitive; internal bool m_ElementTypeIsClass; internal bool m_ElementTypeIsValueType; internal DataType m_DataType = DataType.Invalid; internal object m_Getter; } // Data for a type we have serialized. We cache information obtained from the reflection API here as the reflection API can be slow to query internal class TypeData { internal FieldData[] m_Fields; internal string m_AssemblyQualifiedName; internal int m_AssemblyQualifiedNameIndex; } // Simple string table, our serialized data contains two of these, one for the names of the types and fields serialized and one for the values of any string fields or arrays/lists using strings internal class StringTable { List<string> m_Strings = new List<string>(); Dictionary<string, int> m_Index = new Dictionary<string, int>(); /// <summary> /// Clear the data in this stringtable to make it empty /// </summary> internal void Clear() { m_Index.Clear(); m_Strings.Clear(); } /// <summary> /// Write the strings from this stringtable to a binary writer one after another /// </summary> /// <param name="writer">Writer to write the strings to</param> /// <returns>the byte position in the stream being written to where the strings start, this is the current position in the stream when the function was called</returns> internal long Write(BinaryWriter writer) { long stringTableBytePosition = writer.Seek(0, SeekOrigin.Current); writer.Write(m_Strings.Count); m_Strings.ForEach((item) => writer.Write(item)); return stringTableBytePosition; } /// <summary> /// Return the index of a string in the stringtable if it exists, if it does not exist add it then return it's index /// </summary> /// <param name="stringToAddOrFind"></param> /// <returns></returns> internal int GetStringIndex(string stringToAddOrFind) { if (!m_Index.TryGetValue(stringToAddOrFind, out int stringIndex)) { stringIndex = m_Strings.Count; m_Strings.Add(stringToAddOrFind); m_Index.Add(stringToAddOrFind, stringIndex); } return stringIndex; } } // Byte values we store in the stream to signify whether a reference type is null (and thus absent from the stream) or not (and thus it's data comes next) internal const byte IsNull = 0; internal const byte NotNull = 1; // Custom serializers can be provided by the client code to implement serialization for types that cannot be adequately handled by the generic reflection based code // Client code can pass an array of custom serializers and their associated types to the Serializer constructor or can call AddCustomSerializer() to add individual custom serializers at any time prior to serialization taking place Dictionary<Type, ICustomSerializer> m_CustomSerializers = new Dictionary<Type, ICustomSerializer>(); // Cache of TypeData instances for all the types we've been asked to serialize so far. Only type specific data is stored here not instance specific data and this cache *is not* cleared between calls to Serialize() so using the same // Serializer instance to write multiple instances of the same types achieves a significant performance benefit by being able to re-use type information without having to call slow reflection APIs again. Dictionary<Type, TypeData> m_TypeDataCache = new Dictionary<Type, TypeData>(); // Accessing Type.AssemblyQualifiedName can be slow so we keep this cache mapping types to the string table indices in the type/field string table of the assembly qualified name of types being serialized. // Each time Serialize() is called new stringtables are emitted so this is cleared before each call but still provides a measurable speed increase vs. accessing Type.AssemblyQualifiedName each time it's needed Dictionary<Type, int> m_TypeQualifiedNameIndices = new Dictionary<Type, int>(); // String table of strings from field values encountered StringTable m_DataStringTable = new StringTable(); // String table of type and field names encountered StringTable m_TypeStringTable = new StringTable(); // Writer we are writing out serialized data to BinaryWriter m_Writer; // Serialization data format version number. Written to the stream to provide a means for upgrade should it be necessary in the future internal const byte SerializationVersion = 1; internal Serializer() { } internal Serializer(params ICustomSerializer[] customSerializers) { if (customSerializers != null) Array.ForEach(customSerializers, (customSerializer) => AddCustomSerializer(customSerializer)); } internal void AddCustomSerializer(ICustomSerializer customSerializer) { m_CustomSerializers.Add(customSerializer.GetType(), customSerializer); } /// <summary> /// Clear data that we cache about types and object contents that can change between objects. /// </summary> void ClearPerObjectCachedData() { // Reset the type/field name and data string tables to empty for each object. m_DataStringTable.Clear(); m_TypeStringTable.Clear(); // Clear the type and field name indices from the cached type data as each object's type string table is distinct so the indices from any previously written objects will be invalid foreach (KeyValuePair<Type, TypeData> typeDataCacheEntry in m_TypeDataCache) { typeDataCacheEntry.Value.m_AssemblyQualifiedNameIndex = -1; foreach (FieldData fieldData in typeDataCacheEntry.Value.m_Fields) { fieldData.m_NameIndex = -1; } } // Clear the assembly qualified type name cache as the indices of the assembly qualified type names in the type stringtable will likely be different for this object than the previous one serialized m_TypeQualifiedNameIndices.Clear(); } // Main serialization function. Serializes 'objectToSerialize' to the given stream inserting the supplied object version number in the data. The object version number can be obtained by DeSerializer.ObjectVersion when deserializing the data internal void Serialize(Stream stream, object objectToSerialize, int objectVersion) { ClearPerObjectCachedData(); m_Writer = new BinaryWriter(stream); // Version number for the serialization file format itself m_Writer.Write(SerializationVersion); // Client code version number for their own use m_Writer.Write(objectVersion); // Leave space for the offsets to the type and data stringtables data that we write after the serialization data proper long stringTableOffsetPosition = m_Writer.Seek(0, SeekOrigin.Current); m_Writer.Write(0uL); // Space for the offset to the type string table data m_Writer.Write(0uL); // Space for the offset to the data string table data // Write serialization data for the object WriteObject(objectToSerialize); // Write the type and data stringtables then fill in their position offsets at the start of the data we left space for earlier long typeStringTableBytePos = m_TypeStringTable.Write(m_Writer); long dataStringTableBytePos = m_DataStringTable.Write(m_Writer); m_Writer.Seek((int)stringTableOffsetPosition, SeekOrigin.Begin); m_Writer.Write(typeStringTableBytePos); m_Writer.Write(dataStringTableBytePos); m_Writer.Flush(); } // Call to start writing directly to a stream, used primarily for testing USerialize functions in isolation internal void StartWritingToStream(Stream stream) { m_Writer = new BinaryWriter(stream); } // Call when we've finished writing to a stream, used primarily for testing USerialize functions in isolation internal void FinishWritingToStream() { m_Writer.Flush(); } // Return the cached type data for a given type. Will return it from the m_TypeDataCache cache if present otherwise will generate a new TypeData instance from the type and add it to the cache TypeData GetTypeData(Type type) { if (!m_TypeDataCache.TryGetValue(type, out TypeData typeData)) { // Cache data about the fields that is slow to retrieve every time an instance of this type is processed FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); typeData = new TypeData() { m_Fields = new FieldData[fieldInfos.Length] }; typeData.m_AssemblyQualifiedName = type.AssemblyQualifiedName; typeData.m_AssemblyQualifiedNameIndex = m_TypeStringTable.GetStringIndex(typeData.m_AssemblyQualifiedName); for (int fieldNum = 0; fieldNum < fieldInfos.Length; fieldNum++) { FieldInfo field = fieldInfos[fieldNum]; FieldData fieldData = new FieldData(); fieldData.m_FieldInfo = field; fieldData.m_Name = field.Name; fieldData.m_NameIndex = m_TypeStringTable.GetStringIndex(fieldData.m_Name); if (typeof(Array).IsAssignableFrom(field.FieldType)) { fieldData.m_DataType = DataType.Array; fieldData.m_ElementType = field.FieldType.GetElementType(); fieldData.m_ElementTypeIsPrimitive = fieldData.m_ElementType.IsPrimitive; fieldData.m_ElementTypeIsClass = fieldData.m_ElementType.IsClass; fieldData.m_ElementTypeIsValueType = fieldData.m_ElementType.IsValueType; fieldData.m_Getter = CreateObjectGetter(type, field); } else if (field.FieldType.IsGenericType && (field.FieldType.GetGenericTypeDefinition() == typeof(List<>))) { fieldData.m_DataType = DataType.List; fieldData.m_ElementType = field.FieldType.GetGenericArguments()[0]; } else if (field.FieldType == typeof(GUID)) { fieldData.m_DataType = DataType.Guid; fieldData.m_Getter = CreateGetter<GUID>(type, field); } else if (field.FieldType == typeof(Hash128)) { fieldData.m_DataType = DataType.Hash128; fieldData.m_Getter = CreateGetter<Hash128>(type, field); } else if (field.FieldType.IsEnum) { fieldData.m_DataType = DataType.Enum; fieldData.m_Getter = CreateObjectGetter(type, field); } else if (field.FieldType == typeof(String)) { fieldData.m_DataType = DataType.String; fieldData.m_Getter = CreateGetter<string>(type, field); } else if (field.FieldType.IsClass) { fieldData.m_DataType = DataType.Class; fieldData.m_Getter = CreateObjectGetter(type, field); } else if (field.FieldType.IsValueType && (!field.FieldType.IsPrimitive)) { fieldData.m_DataType = DataType.Struct; fieldData.m_Getter = CreateObjectGetter(type, field); } else if (field.FieldType == typeof(byte)) { fieldData.m_DataType = DataType.Byte; fieldData.m_Getter = CreateGetter<byte>(type, field); } else if (field.FieldType == typeof(bool)) { fieldData.m_DataType = DataType.Bool; fieldData.m_Getter = CreateGetter<bool>(type, field); } else if (field.FieldType == typeof(int)) { fieldData.m_DataType = DataType.Int; fieldData.m_Getter = CreateGetter<int>(type, field); } else if (field.FieldType == typeof(uint)) { fieldData.m_DataType = DataType.UInt; fieldData.m_Getter = CreateGetter<uint>(type, field); } else if (field.FieldType == typeof(long)) { fieldData.m_DataType = DataType.Long; fieldData.m_Getter = CreateGetter<long>(type, field); } else if (field.FieldType == typeof(ulong)) { fieldData.m_DataType = DataType.ULong; fieldData.m_Getter = CreateGetter<ulong>(type, field); } else if (field.FieldType == typeof(Type)) { fieldData.m_DataType = DataType.Type; fieldData.m_Getter = CreateGetter<Type>(type, field); } typeData.m_Fields[fieldNum] = fieldData; } m_TypeDataCache.Add(type, typeData); } else if (typeData.m_AssemblyQualifiedNameIndex == -1) { // This type is in our cache but it hasn't been used by the object being serialized yet. Find/add it's type and field names to the type string table so we have a valid index typeData.m_AssemblyQualifiedNameIndex = m_TypeStringTable.GetStringIndex(typeData.m_AssemblyQualifiedName); foreach (FieldData fieldData in typeData.m_Fields) { fieldData.m_NameIndex = m_TypeStringTable.GetStringIndex(fieldData.m_Name); } } return typeData; } // Create a function object to get the value from a field of type 'GetterType'. It is much faster to call this compiled function object than to use the reflection API static Func<object, GetterType> CreateGetter<GetterType>(Type type, FieldInfo field) { ParameterExpression valueExp = Expression.Parameter(typeof(object), "value"); return Expression.Lambda<Func<object, GetterType>>(Expression.Field(Expression.Convert(valueExp, type), field), valueExp).Compile(); } // Create a function object to get the value from a field as a generic object. It is much faster to call this compiled function object than to use the reflection API static Func<object, object> CreateObjectGetter(Type type, FieldInfo field) { ParameterExpression valueExp = Expression.Parameter(typeof(object), "value"); return Expression.Lambda<Func<object, object>>(Expression.Convert(Expression.Field(Expression.Convert(valueExp, type), field), typeof(object)), valueExp).Compile(); } // Write an object to the serialization stream void WriteObject(object objectToWrite) { if (!WriteNullFlag(objectToWrite)) return; // Get information about the objects type then write the type/field stringtable index of it's type name and how many fields it has Type objectType = objectToWrite.GetType(); TypeData typeData = GetTypeData(objectType); WriteStringIndex(typeData.m_AssemblyQualifiedNameIndex); if (typeData.m_Fields.Length > ushort.MaxValue) throw new InvalidDataException($"USerialize cannot serialize objects with more than {ushort.MaxValue} fields"); m_Writer.Write((ushort)typeData.m_Fields.Length); // Process each field in turn foreach (FieldData field in typeData.m_Fields) { switch (field.m_DataType) { case DataType.Array: { WriteFieldInfo(field, DataType.Array); Array array = (Array)((Func<object, object>)field.m_Getter)(objectToWrite); if (WriteNullFlag(array)) { // We only support rank 1 for now m_Writer.Write(array.Rank); m_Writer.Write(array.Length); if (array.Rank != 1) throw new InvalidDataException($"USerialize currently doesn't support arrays with ranks other than one - field {field.m_Name} of type {field.m_FieldInfo.FieldType.Name} has rank {array.Rank}"); Type elementType = field.m_ElementType; if (field.m_ElementTypeIsPrimitive) { // A primitive array, write the bytes as optimally as possible for types we support if (elementType == typeof(byte)) { // byte[] m_Writer.Write((byte)DataType.Byte); m_Writer.Write((byte[])array, 0, array.Length); } // Per customer request else if (elementType == typeof(ulong)) { ulong[] ulongArray = (ulong[])array; m_Writer.Write((byte)DataType.ULong); for (int elementIndex = 0; elementIndex < array.Length; elementIndex++) { m_Writer.Write(ulongArray[elementIndex]); } } else throw new InvalidDataException($"USerialize currently doesn't support primitive arrays of type {elementType.Name} - field {field.m_Name} of type {field.m_FieldInfo.FieldType.Name}"); } else if (elementType == typeof(string)) { // String[] string[] stringArray = (string[])array; m_Writer.Write((byte)DataType.String); for (int elementIndex = 0; elementIndex < array.Length; elementIndex++) { WriteDataString(stringArray[elementIndex]); } } else if (elementType == typeof(Type)) { // Type[] Type[] typeArray = (Type[])array; m_Writer.Write((byte)DataType.Type); for (int elementIndex = 0; elementIndex < array.Length; elementIndex++) { if (typeArray[elementIndex] != null) WriteStringIndex(GetTypeQualifiedNameIndex(typeArray[elementIndex])); else WriteStringIndex(USerialize.InvalidStringIndex); } } else if (field.m_ElementTypeIsClass) { // An array of class instances m_Writer.Write((byte)DataType.Class); WriteStringIndex(GetTypeQualifiedNameIndex(elementType)); for (int elementIndex = 0; elementIndex < array.Length; elementIndex++) { object elementToWrite = array.GetValue(elementIndex); // If the element isn't null see if we have a custom serializer for the type of this instance. // The array type might be a base class for the actual instances which may not all be the same derived type so we use the runtime type of each instance individually to check for custom serializers rather than using the type of the array itself if (elementToWrite != null) { Type elementObjectType = elementToWrite.GetType(); if (m_CustomSerializers.TryGetValue(elementObjectType, out ICustomSerializer customSerializer)) { m_Writer.Write((byte)DataType.Custom); WriteStringIndex(GetTypeQualifiedNameIndex(elementObjectType)); customSerializer.USerializer(this, elementToWrite); } else if (elementObjectType == typeof(string)) { m_Writer.Write((byte)DataType.String); WriteDataString((string)elementToWrite); } else if (elementObjectType == typeof(Int32)) { m_Writer.Write((byte)DataType.Int); m_Writer.Write((int)elementToWrite); } else { if (elementObjectType.IsPrimitive) throw new InvalidDataException($"USerialize cannot handle type '{elementObjectType.Name}' in object[] array '{objectType.Name}.{field.m_Name}'"); m_Writer.Write((byte)DataType.Class); WriteObject(elementToWrite); } } else { m_Writer.Write((byte)DataType.Class); m_Writer.Write(IsNull); } } } else if (field.m_ElementTypeIsValueType) { // An array of struct instances m_Writer.Write((byte)DataType.Struct); WriteStringIndex(GetTypeQualifiedNameIndex(elementType)); for (int elementIndex = 0; elementIndex < array.Length; elementIndex++) { WriteObject(array.GetValue(elementIndex)); } } else throw new InvalidDataException($"USerialize doesn't support serializing array field {field.m_Name} of type {field.m_FieldInfo.FieldType.Name} which is of type {elementType.Name}"); } break; } case DataType.List: { // A List<> WriteFieldInfo(field, DataType.List); System.Collections.IList list = field.m_FieldInfo.GetValue(objectToWrite) as System.Collections.IList; if (WriteNullFlag(list)) { m_Writer.Write(list.Count); WriteStringIndex(GetTypeQualifiedNameIndex(field.m_ElementType)); for (int elementIndex = 0; elementIndex < list.Count; elementIndex++) { WriteObject(list[elementIndex]); } } break; } case DataType.Guid: { // GUID instance WriteFieldInfo(field, DataType.Guid); GUID guid = ((Func<object, GUID>)field.m_Getter)(objectToWrite); unsafe { UInt64* guidPtr = (UInt64*)&guid; m_Writer.Write(guidPtr[0]); m_Writer.Write(guidPtr[1]); } break; } case DataType.Hash128: { // Hash128 instance WriteFieldInfo(field, DataType.Hash128); Hash128 hash = ((Func<object, Hash128>)field.m_Getter)(objectToWrite); unsafe { UInt64* hashPtr = (UInt64*)&hash; m_Writer.Write(hashPtr[0]); m_Writer.Write(hashPtr[1]); } break; } case DataType.Enum: // An enum, we write it's value as an Int32 WriteFieldInfo(field, DataType.Enum); m_Writer.Write((int)((Func<object, object>)field.m_Getter)(objectToWrite)); break; case DataType.String: { // String instance WriteFieldInfo(field, DataType.String); WriteDataString(((Func<object, string>)field.m_Getter)(objectToWrite)); break; } case DataType.Class: { // Is a class instance. If the value isn't null check to see if we have been given a custom serializer for it's type. // If the value is null or there is no custom serializer registered for the value's type write it as normal // Note the type of the actual object is used to locate custom serializers rather than the type of the field in case the object is actually of a derived type object fieldValue = ((Func<object, object>)field.m_Getter)(objectToWrite); if ((fieldValue == null) || (!DoCustomSerialization(field, fieldValue))) { WriteFieldInfo(field, DataType.Class); WriteObject(fieldValue); } break; } case DataType.Struct: { // Is a struct instance. Check to see if we have been given a custom serializer for it's type, if not write it as normal object fieldValue = ((Func<object, object>)field.m_Getter)(objectToWrite); if (!DoCustomSerialization(field, fieldValue)) { WriteFieldInfo(field, DataType.Struct); WriteObject(fieldValue); } break; } case DataType.Byte: WriteFieldInfo(field, DataType.Byte); m_Writer.Write(((Func<object, byte>)field.m_Getter)(objectToWrite)); break; case DataType.Bool: WriteFieldInfo(field, DataType.Bool); m_Writer.Write(((Func<object, bool>)field.m_Getter)(objectToWrite)); break; case DataType.Int: WriteFieldInfo(field, DataType.Int); m_Writer.Write(((Func<object, int>)field.m_Getter)(objectToWrite)); break; case DataType.UInt: WriteFieldInfo(field, DataType.UInt); m_Writer.Write(((Func<object, uint>)field.m_Getter)(objectToWrite)); break; case DataType.Long: WriteFieldInfo(field, DataType.Long); m_Writer.Write(((Func<object, long>)field.m_Getter)(objectToWrite)); break; case DataType.ULong: WriteFieldInfo(field, DataType.ULong); m_Writer.Write(((Func<object, ulong>)field.m_Getter)(objectToWrite)); break; case DataType.Type: WriteFieldInfo(field, DataType.Type); WriteStringIndex(GetTypeQualifiedNameIndex(((Func<object, Type>)field.m_Getter)(objectToWrite))); break; default: throw new InvalidDataException($"USerialize doesn't know how to serialize field {objectType.Name}.{field.m_Name} of type {field.m_FieldInfo.FieldType.Name}"); } } } // Return the index in the type/field stringtable of the AssemblyQualifiedName of the given type. Accessing Type.AssemblyQualifiedName can be slow so we use a cache // to store the string table indices of types we've encountered before int GetTypeQualifiedNameIndex(Type type) { if (type == null) return -1; if (!m_TypeQualifiedNameIndices.TryGetValue(type, out int qualifiedNameIndex)) { qualifiedNameIndex = m_TypeStringTable.GetStringIndex(type.AssemblyQualifiedName); m_TypeQualifiedNameIndices.Add(type, qualifiedNameIndex); } return qualifiedNameIndex; } // Check to see if a custom serializer has been registered for the type of a given object. If so call it and return true, otherwise return false bool DoCustomSerialization(FieldData field, object valueToSerialize) { Type valueType = valueToSerialize.GetType(); if (m_CustomSerializers.TryGetValue(valueType, out ICustomSerializer customSerializer)) { WriteFieldInfo(field, DataType.Custom); WriteStringIndex(GetTypeQualifiedNameIndex(valueType)); customSerializer.USerializer(this, valueToSerialize); return true; } return false; } // Write a byte array to the stream. The actual bytes are preceded by a flag byte indicating whether the array passed in was null or not internal void WriteBytes(byte[] bytes) { if (WriteNullFlag(bytes)) { m_Writer.Write(bytes.Length); m_Writer.Write(bytes, 0, bytes.Length); } } // If the supplied object *is not* null write a byte with value NotNull (1) to the stream and return true // if the supplied object *is* null write a byte with value IsNull (0) to the stream and return false internal bool WriteNullFlag(object value) { if (value != null) { m_Writer.Write(NotNull); return true; } m_Writer.Write(IsNull); return false; } // Write a string table index. There are almost never more than 32,767 strings so we use 15 bits by default for compactness. // If a string has an index more than 32,767 (i.e. 0x8000+) we store 0x8000 as a flag to signify this combined with the bottom 15 bits of the index. Bits 15 to 30 are stored in the following 16 bits of data. internal void WriteStringIndex(int stringIndex) { if (stringIndex < 0x8000) m_Writer.Write((ushort)stringIndex); else { m_Writer.Write((ushort)(0x8000 | (stringIndex & 0x7FFF))); m_Writer.Write((ushort)(stringIndex >> 15)); } } // Write meta-data for a field to the stream. The index of the field's name in the type/field stringtable is written followed by a byte indicating the type of the data in the stream void WriteFieldInfo(FieldData field, DataType dataType) { WriteStringIndex(field.m_NameIndex); m_Writer.Write((byte)dataType); } // Write a field value string to the stream. A IsNull/NotNull byte is written then if the string is not null the index of the string in the data stringtable internal void WriteDataString(string stringToWrite) { if (WriteNullFlag(stringToWrite)) WriteStringIndex(m_DataStringTable.GetStringIndex(stringToWrite)); } } }
0
0.907502
1
0.907502
game-dev
MEDIA
0.251304
game-dev
0.7698
1
0.7698
EasyRPG/Player
2,958
src/window_shopbuy.cpp
/* * This file is part of EasyRPG Player. * * EasyRPG Player 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. * * EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. */ // Headers #include <sstream> #include <string> #include "window_base.h" #include "window_shopbuy.h" #include "game_system.h" #include "game_party.h" #include "bitmap.h" #include "font.h" #include "output.h" #include <lcf/reader_util.h> Window_ShopBuy::Window_ShopBuy(const std::vector<int>& goods, int ix, int iy, int iwidth, int iheight) : Window_Selectable(ix, iy, iwidth, iheight) , data(goods) { index = 0; item_max = data.size(); } int Window_ShopBuy::GetItemId() { if (index < 0 || index >= (int)data.size()) { return 0; } else { return data[index]; } } void Window_ShopBuy::Refresh() { CreateContents(); contents->Clear(); Rect rect(0, 0, contents->GetWidth(), contents->GetHeight()); contents->Clear(); for (size_t i = 0; i < data.size(); ++i) { DrawItem(i); } } void Window_ShopBuy::DrawItem(int index) { int item_id = data[index]; // (Shop) items are guaranteed to be valid const lcf::rpg::Item* item = lcf::ReaderUtil::GetElement(lcf::Data::items, item_id); int price = 0; bool enabled = false; if (!item) { Output::Warning("Window ShopBuy: Invalid item ID {}", item_id); } else { enabled = item->price <= Main_Data::game_party->GetGold() && Main_Data::game_party->GetItemCount(item_id) < Main_Data::game_party->GetMaxItemCount(item_id); price = item->price; } Rect rect = GetItemRect(index); contents->ClearRect(rect); DrawItemName(*item, rect.x, rect.y, enabled); std::string str = std::to_string(price); contents->TextDraw(rect.width, rect.y, enabled ? Font::ColorDefault : Font::ColorDisabled, str, Text::AlignRight); } void Window_ShopBuy::UpdateHelp() { std::string help_text = ""; if (!data.empty()) { const lcf::rpg::Item* item = lcf::ReaderUtil::GetElement(lcf::Data::items, data[index]); if (item) { help_text = ToString(item->description); } else { help_text = "??? BAD ITEM ???"; } } help_window->SetText(std::move(help_text)); } bool Window_ShopBuy::CheckEnable(int item_id) { const lcf::rpg::Item* item = lcf::ReaderUtil::GetElement(lcf::Data::items, item_id); if (!item) { return false; } return (item->price <= Main_Data::game_party->GetGold() && Main_Data::game_party->GetItemCount(item_id) < Main_Data::game_party->GetMaxItemCount(item_id)); }
0
0.87495
1
0.87495
game-dev
MEDIA
0.931324
game-dev
0.943371
1
0.943371
lua9520/source-engine-2018-cstrike15_src
1,991
game/client/vgui_entitypanel.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: This is a panel which is rendered on top of an entity // // $Revision: $ // $NoKeywords: $ //=============================================================================// #ifndef VGUI_ENTITYPANEL_H #define VGUI_ENTITYPANEL_H #ifdef _WIN32 #pragma once #endif #include "C_BaseEntity.h" #include <vgui/MouseCode.h> #include "VGUI_basepanel.h" // forward declarations class KeyValues; //----------------------------------------------------------------------------- // This is a base class for a panel which always is rendered on top of an entity //----------------------------------------------------------------------------- class CEntityPanel : public CBasePanel { public: DECLARE_CLASS( CEntityPanel, CBasePanel ); // constructor CEntityPanel( vgui::Panel *pParent, const char *panelName ); virtual void ComputeParent( void ); virtual void ComputeAndSetSize( void ); // Initialize from key values bool Init( KeyValues* pKeyValues, C_BaseEntity* pEntity ); // Determine where our entity is in screen space. void GetEntityPosition( int& sx, int& sy ); // Base implementation of ShouldDraw bool ShouldDraw(); // called when we're ticked (updates our position)... virtual void OnTick( void ); virtual void OnCursorEntered(); virtual void OnCursorExited(); const char *GetMouseOverText( void ); C_BaseEntity* GetEntity() { return (C_BaseEntity*)m_pBaseEntity; } // Attach to a new entity void SetEntity( C_BaseEntity* pEntity ); public: enum { MAX_ENTITY_MOUSEOVER = 256 }; // Offset from entity that we should draw int m_OffsetX, m_OffsetY; char m_szMouseOverText[ MAX_ENTITY_MOUSEOVER ]; bool m_bShowInNormal; int m_iOrgWidth; int m_iOrgHeight; int m_iOrgOffsetX; int m_iOrgOffsetY; float m_flScale; private: // This is the entity to which we're attached EHANDLE m_pBaseEntity; }; #endif // VGUI_ENTITYPANEL_H
0
0.856483
1
0.856483
game-dev
MEDIA
0.860139
game-dev
0.507208
1
0.507208
p-org/P
7,764
Tst/RegressionTests/Feature4DataTypes/DynamicError/CastInExprs2/CastInExprsDynError.p
//XYZs cast operator in expressions //XYZs dynamic error //Basic types: int, bool, event event E : int; event EI1: int; event EI2: int; event EI3: int; event EI4: int; event EI5: int; event EI6: int; event E1; event E2; event ET1: (a: int, b: bool); event ET2: (a: int, b: bool); event ESEQ1: seq[int]; event ESEQ2: seq[int]; event EMAP1: map[int,int]; event EMAP11: map[int,int]; event EMAP2: map[int,int]; event EMAP3: map[int,int]; machine Main { var t : (a: seq [int], b: map[int, seq[int]]); var t1 : (a: seq [int], b: map[int, seq[int]]); var ts: (a: int, b: int); var ts1: (a: int, b: bool); var tt: (int, int); var tbool: (bool, bool); var te: (int, event); /////////////////////////////////////////////////////////// var b: bool; var y : int; var tmp: int; var tmp1: int; var ev: event; var a: any; var tmp2: (a: seq [any], b: map[int, seq[any]]); var tmp3: map[int, seq[int]]; var s: seq[int]; var s1: seq[any]; var s2: seq[int]; var s3: seq[seq[any]]; var s4, s8: seq[(int,int)]; var s5: seq[bool]; var s6: seq[map[int,any]]; var s7: seq[int]; var s9: seq[event]; ///////////////////////////////////////////////////////// var s10: seq[any]; var s11: seq[int]; var s12: seq[bool]; var i: int; var mac: machine; var m1: map[int,int]; var m4: map[int,int]; var m3: map[int,bool]; //TODO: write asgns for m2 var m5, m6: map[int,any]; var m2: map[int,map[int,any]]; var m7: map[bool,seq[(a: int, b: int)]]; var m8: map[int,event]; ////////////////////////////////////// var m9: map[int,any]; start state S { entry { ////////////////////////// int vs any: a = default(any); //y = a as int; //dynamic error: "value must be a member of type" (other XYZs) a = 1; y = a as int; //OK assert (y == a); //holds ////////////////////////// bool vs any: a = default(any); b = a as bool; //dynamic error: "value must be a member of type" (this XYZ) assert(b == true); raise halt; } } } machine XYZ { var ss: seq[int]; var yt: int; var tts1: (a: int, b: bool); var tts: (a: int, b: int); var ta: any; var s: seq[int]; var s1: seq[any]; var mi: map[int,int]; var ma: map[int,any]; start state init { entry { //ss = payload as seq[int]; //assert(ss[0] == 3); //holds } on EI1 goto XYZEI1; on EI6 goto XYZEI6; on ET1 goto XYZET1; on ET2 goto XYZET2; on ESEQ1 goto XYZESEQ1; on ESEQ2 goto XYZESEQ2; on EMAP1 goto XYZEMAP1; on EMAP11 goto XYZEMAP11; on EMAP2 goto XYZEMAP2; on EMAP3 goto XYZEMAP3; } // int is sent state XYZEI1 { entry (payload: any) { ta = payload as any; assert(ta == 1); //holds //yt = payload as int; //dynamic error: "value must have a concrete type" (TODO: add Sent\XYZ.p) (no error in runtime!) //assert(yt == 1); //holds? goto init; } } // "any as int" is sent state XYZEI6 { entry (payload: int) { yt = payload as int; //OK assert(yt == 1); //holds yt = payload; //OK assert(yt == 1); //holds ta = payload as any; //OK assert(yt == 1); //holds goto init; } } // tuple is sent via a var state XYZET1 { entry (payload: (a: int, b: bool)) { tts1 = payload as (a: int, b: bool); //OK assert (tts1.a == 1 && tts1.b == true); //holds tts1 = payload; //OK assert (tts1.a == 1 && tts1.b == true); //holds goto init; } } // tuple is sent via literal state XYZET2 { entry (payload: (a: int, b: bool)) { tts1 = payload as (a: int, b: bool); //OK assert (tts1.a == 2 && tts1.b == false); //holds goto init; } } // seq[int] sent state XYZESEQ1 { entry (payload: seq[int]) { s = payload as seq[int]; //OK assert (s[0] == 1); //holds s = payload; //OK assert (s[0] == 1); //holds s1 = payload as seq[int]; //OK assert (s1[0] == 1); //holds s1 = payload; //OK assert (s1[0] == 1); //holds s1 = payload as seq[any]; //OK assert (s1[0] == 1); //holds goto init; } } // "seq[any] as seq[int]" is sent state XYZESEQ2 { entry (payload: seq[int]) { s = payload as seq[int]; //OK assert (s[0] == 1); //holds s = payload; //OK assert (s[0] == 1); //holds s1 = payload as seq[int]; //OK assert (s1[0] == 1); //holds s1 = payload; //OK assert (s1[0] == 1); //holds s1 = payload as seq[any]; //OK assert (s1[0] == 1); //holds goto init; } } // default(map[int,int]) is sent state XYZEMAP1 { entry (payload: map[int,int]) { mi = payload; //assert (mi[0] == 0); //dynamic error: "key not found" (other XYZs) mi[0] = 0; mi[3] = 3; assert (mi[0] == 0 && mi[3] == 3); //holds mi = default(map[int,int]); mi = payload as map[int,int]; //assert (mi[0] == 0); //dynamic error: "key not found" (other XYZs) ma = payload as map[int,int]; //assert (ma[0] == 0); //dynamic error: "key not found" (other XYZs) ma = default(map[int,any]); ma = payload; //assert (ma[0] == 0); //dynamic error: "key not found" (other XYZs) ma = default(map[int,any]); ma = payload as map[int,any]; //assert (ma[0] == 0); //dynamic error: "key not found" (other XYZs) goto init; } } // map[int,int] is sent (0,1) (3,3) state XYZEMAP11 { entry (payload: map[int,int]) { mi = default(map[int,int]); mi = payload; assert (mi[0] == 1 && mi[3] == 3); //holds mi = default(map[int,int]); mi = payload as map[int,int]; assert (mi[0] == 1 && mi[3] == 3); //holds ma = payload as map[int,int]; assert (ma[0] == 1 && ma[3] == 3); //holds ma = default(map[int,any]); ma = payload; assert (ma[0] == 1 && ma[3] == 3); //holds ma = default(map[int,any]); ma = payload as map[int,any]; assert (ma[0] == 1 && ma[3] == 3); //holds goto init; } } // default(map[int,any]) is sent as map[int,int] state XYZEMAP2 { entry (payload: map[int,int]) { mi = payload; //OK //assert (mi[0] == 1 && mi[3] == 3); //dynamic error: "key not found" (other XYZs) mi = default(map[int,int]); mi = payload as map[int,int]; //OK //assert (mi[0] == 1 && mi[3] == 3); //dynamic error: "key not found" (other XYZs) ma = payload as map[int,int]; //ok //assert (ma[0] == 1 && ma[3] == 3); //dynamic error: "key not found" (other XYZs) ma = default(map[int,any]); ma = payload; //OK //assert (ma[0] == 1 && ma[3] == 3); //dynamic error: "key not found" (other XYZs) ma = default(map[int,any]); ma = payload as map[int,any]; //OK //assert (ma[0] == 1 && ma[3] == 3); //dynamic error: "key not found" (other XYZs) goto init; } } // map[int,any] assigned a value of map[int,int] type is sent as map[int,int] state XYZEMAP3 { entry (payload: map[int,int]) { mi = payload; //OK assert (mi[0] == 1 && mi[3] == 3); //holds mi = default(map[int,int]); mi = payload as map[int,int]; //OK assert (mi[0] == 1 && mi[3] == 3); //holds ma = payload as map[int,int]; //ok assert (ma[0] == 1 && ma[3] == 3); //holds ma = default(map[int,any]); ma = payload; //OK assert (ma[0] == 1 && ma[3] == 3); //holds ma = default(map[int,any]); ma = payload as map[int,any]; //OK assert (ma[0] == 1 && ma[3] == 3); //holds goto init; } } }
0
0.751526
1
0.751526
game-dev
MEDIA
0.224282
game-dev
0.621194
1
0.621194
gtkd-developers/GtkD
7,767
generated/gtkd/gio/ActionT.d
/* * This file is part of gtkD. * * gtkD 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, with * some exceptions, please read the COPYING file. * * gtkD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with gtkD; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA */ // generated automatically - do not change // find conversion definition on APILookup.txt // implement new conversion functionalities on the wrap.utils pakage module gio.ActionT; public import gio.c.functions; public import gio.c.types; public import glib.ErrorG; public import glib.GException; public import glib.Str; public import glib.Variant; public import glib.VariantType; public import glib.c.functions; public import gtkc.giotypes; /** * #GAction represents a single named action. * * The main interface to an action is that it can be activated with * g_action_activate(). This results in the 'activate' signal being * emitted. An activation has a #GVariant parameter (which may be * %NULL). The correct type for the parameter is determined by a static * parameter type (which is given at construction time). * * An action may optionally have a state, in which case the state may be * set with g_action_change_state(). This call takes a #GVariant. The * correct type for the state is determined by a static state type * (which is given at construction time). * * The state may have a hint associated with it, specifying its valid * range. * * #GAction is merely the interface to the concept of an action, as * described above. Various implementations of actions exist, including * #GSimpleAction. * * In all cases, the implementing class is responsible for storing the * name of the action, the parameter type, the enabled state, the * optional state type and the state and emitting the appropriate * signals when these change. The implementor is responsible for filtering * calls to g_action_activate() and g_action_change_state() for type * safety and for the state being enabled. * * Probably the only useful thing to do with a #GAction is to put it * inside of a #GSimpleActionGroup. */ public template ActionT(TStruct) { /** Get the main Gtk struct */ public GAction* getActionStruct(bool transferOwnership = false) { if (transferOwnership) ownedRef = false; return cast(GAction*)getStruct(); } /** * Activates the action. * * @parameter must be the correct type of parameter for the action (ie: * the parameter type given at construction time). If the parameter * type was %NULL then @parameter must also be %NULL. * * If the @parameter GVariant is floating, it is consumed. * * Params: * parameter = the parameter to the activation * * Since: 2.28 */ public void activate(Variant parameter) { g_action_activate(getActionStruct(), (parameter is null) ? null : parameter.getVariantStruct()); } /** * Request for the state of @action to be changed to @value. * * The action must be stateful and @value must be of the correct type. * See g_action_get_state_type(). * * This call merely requests a change. The action may refuse to change * its state or may change its state to something other than @value. * See g_action_get_state_hint(). * * If the @value GVariant is floating, it is consumed. * * Params: * value = the new state * * Since: 2.30 */ public void changeState(Variant value) { g_action_change_state(getActionStruct(), (value is null) ? null : value.getVariantStruct()); } /** * Checks if @action is currently enabled. * * An action must be enabled in order to be activated or in order to * have its state changed from outside callers. * * Returns: whether the action is enabled * * Since: 2.28 */ public bool getEnabled() { return g_action_get_enabled(getActionStruct()) != 0; } /** * Queries the name of @action. * * Returns: the name of the action * * Since: 2.28 */ public string getName() { return Str.toString(g_action_get_name(getActionStruct())); } /** * Queries the type of the parameter that must be given when activating * @action. * * When activating the action using g_action_activate(), the #GVariant * given to that function must be of the type returned by this function. * * In the case that this function returns %NULL, you must not give any * #GVariant, but %NULL instead. * * Returns: the parameter type * * Since: 2.28 */ public VariantType getParameterType() { auto __p = g_action_get_parameter_type(getActionStruct()); if(__p is null) { return null; } return new VariantType(cast(GVariantType*) __p); } /** * Queries the current state of @action. * * If the action is not stateful then %NULL will be returned. If the * action is stateful then the type of the return value is the type * given by g_action_get_state_type(). * * The return value (if non-%NULL) should be freed with * g_variant_unref() when it is no longer required. * * Returns: the current state of the action * * Since: 2.28 */ public Variant getState() { auto __p = g_action_get_state(getActionStruct()); if(__p is null) { return null; } return new Variant(cast(GVariant*) __p, true); } /** * Requests a hint about the valid range of values for the state of * @action. * * If %NULL is returned it either means that the action is not stateful * or that there is no hint about the valid range of values for the * state of the action. * * If a #GVariant array is returned then each item in the array is a * possible value for the state. If a #GVariant pair (ie: two-tuple) is * returned then the tuple specifies the inclusive lower and upper bound * of valid values for the state. * * In any case, the information is merely a hint. It may be possible to * have a state value outside of the hinted range and setting a value * within the range may fail. * * The return value (if non-%NULL) should be freed with * g_variant_unref() when it is no longer required. * * Returns: the state range hint * * Since: 2.28 */ public Variant getStateHint() { auto __p = g_action_get_state_hint(getActionStruct()); if(__p is null) { return null; } return new Variant(cast(GVariant*) __p, true); } /** * Queries the type of the state of @action. * * If the action is stateful (e.g. created with * g_simple_action_new_stateful()) then this function returns the * #GVariantType of the state. This is the type of the initial value * given as the state. All calls to g_action_change_state() must give a * #GVariant of this type and g_action_get_state() will return a * #GVariant of the same type. * * If the action is not stateful (e.g. created with g_simple_action_new()) * then this function will return %NULL. In that case, g_action_get_state() * will return %NULL and you must not call g_action_change_state(). * * Returns: the state type, if the action is stateful * * Since: 2.28 */ public VariantType getStateType() { auto __p = g_action_get_state_type(getActionStruct()); if(__p is null) { return null; } return new VariantType(cast(GVariantType*) __p); } }
0
0.875511
1
0.875511
game-dev
MEDIA
0.195274
game-dev
0.871402
1
0.871402
Unity-Technologies/UnityCsReference
2,194
Runtime/2D/SpriteAtlas/ScriptBindings/SpriteAtlas.bindings.cs
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine.U2D { [NativeHeader("Runtime/2D/SpriteAtlas/SpriteAtlasManager.h")] [NativeHeader("Runtime/2D/SpriteAtlas/SpriteAtlas.h")] [StaticAccessor("GetSpriteAtlasManager()", StaticAccessorType.Dot)] public class SpriteAtlasManager { public static event Action<string, Action<SpriteAtlas>> atlasRequested = null; [RequiredByNativeCode] private static bool RequestAtlas(string tag) { if (atlasRequested != null) { atlasRequested(tag, Register); return true; } return false; } public static event Action<SpriteAtlas> atlasRegistered = null; [RequiredByNativeCode] private static void PostRegisteredAtlas(SpriteAtlas spriteAtlas) { atlasRegistered?.Invoke(spriteAtlas); } extern internal static void Register(SpriteAtlas spriteAtlas); } [NativeHeader("Runtime/Graphics/SpriteFrame.h")] [NativeType(Header = "Runtime/2D/SpriteAtlas/SpriteAtlas.h")] public class SpriteAtlas : UnityEngine.Object { public SpriteAtlas() { Internal_Create(this); } extern private static void Internal_Create([Writable] SpriteAtlas self); extern public bool isVariant {[NativeMethod("IsVariant")] get; } extern public string tag { get; } extern public int spriteCount { get; } extern public bool CanBindTo([NotNull] Sprite sprite); extern public Sprite GetSprite(string name); public int GetSprites(Sprite[] sprites) { return GetSpritesScripting(sprites); } public int GetSprites(Sprite[] sprites, string name) { return GetSpritesWithNameScripting(sprites, name); } extern private int GetSpritesScripting([Unmarshalled] Sprite[] sprites); extern private int GetSpritesWithNameScripting([Unmarshalled] Sprite[] sprites, string name); } }
0
0.604609
1
0.604609
game-dev
MEDIA
0.933513
game-dev
0.568531
1
0.568531
joewing/maze
1,431
maze.nim
# Maze generator in Nimrod # Joe Wingbermuehle 2013-10-01 import math # Width and height must be odd. const width = 39 const height = 23 type MazeT = array[0 .. height - 1, array[0 .. width - 1, int]] proc showMaze(maze: MazeT) = for y in countup(0, height - 1): for x in countup(0, width - 1): if maze[y][x] == 1: write(stdout, "[]") else: write(stdout, " ") write(stdout, "\n") proc initMaze(maze: ref MazeT) = for y in countup(0, height - 1): for x in countup(0, width - 1): maze[y][x] = 1 for x in countup(0, width - 1): maze[0][x] = 0 maze[height - 1][x] = 0 for y in countup(0, height - 1): maze[y][0] = 0 maze[y][width - 1] = 0 proc carveMaze(maze: ref MazeT, x, y: int) = maze[y][x] = 0 let d = math.random(4) for i in countup(0, 3): var dx, dy: int case (d + i) mod 4 of 0: dx = 1 of 1: dx = -1 of 2: dy = 1 else: dy = -1 let nx = x + dx ny = y + dy nx2 = x + 2 * dx ny2 = y + 2 * dy if maze[ny][nx] == 1 and maze[ny2][nx2] == 1: maze[ny][nx] = 0 carveMaze(maze, nx2, ny2) proc generateMaze(): MazeT = var Presult: ref MazeT new(Presult) initMaze(Presult) carveMaze(Presult, 2, 2) Presult[1][2] = 0 Presult[height - 2][width - 3] = 0 return Presult[] showMaze(generateMaze())
0
0.717128
1
0.717128
game-dev
MEDIA
0.811093
game-dev
0.930878
1
0.930878
swgemu/Core3
2,152
MMOCoreORB/src/server/zone/objects/creature/commands/pet/PetGetPatrolPointCommand.h
#ifndef PETGETPATROLPOINTCOMMAND_H_ #define PETGETPATROLPOINTCOMMAND_H_ #include "server/zone/objects/creature/commands/QueueCommand.h" #include "server/zone/objects/creature/ai/AiAgent.h" #include "server/zone/objects/creature/ai/DroidObject.h" #include "server/zone/managers/creature/PetManager.h" class PetGetPatrolPointCommand : public QueueCommand { public: PetGetPatrolPointCommand(const String& name, ZoneProcessServer* server) : QueueCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const { ManagedReference<PetControlDevice*> controlDevice = creature->getControlDevice().get().castTo<PetControlDevice*>(); if (controlDevice == nullptr) return GENERALERROR; ManagedReference<AiAgent*> pet = cast<AiAgent*>(creature); if (pet == nullptr) return GENERALERROR; if (pet->hasRidingCreature()) return GENERALERROR; // Check if droid has power if (controlDevice->getPetType() == PetManager::DROIDPET) { ManagedReference<DroidObject*> droidPet = cast<DroidObject*>(pet.get()); if (droidPet == nullptr) return GENERALERROR; if (!droidPet->hasPower()) { pet->showFlyText("npc_reaction/flytext", "low_power", 204, 0, 0); // "*Low Power*" return GENERALERROR; } } // ignore if pet is in combat if (pet->isInCombat()) return GENERALERROR; Locker clocker(controlDevice, creature); if (controlDevice->getPatrolPointSize() < 10) { ManagedReference<SceneObject*> targetObject = server->getZoneServer()->getObject(target, true); if (targetObject != nullptr || targetObject->isPlayerCreature()) { CreatureObject* player = targetObject->asCreatureObject(); PatrolPoint point; point.setPositionX(player->getPositionX()); point.setPositionY(player->getPositionY()); point.setPositionZ(player->getPositionZ()); point.setCell(player->getParent().get().castTo<CellObject*>()); controlDevice->addPatrolPoint(point); player->sendSystemMessage("@pet/pet_menu:patrol_added"); // Patrol point acknowledged } } return SUCCESS; } }; #endif /* PETGETPATROLPOINTCOMMAND_H_ */
0
0.970532
1
0.970532
game-dev
MEDIA
0.97487
game-dev
0.948017
1
0.948017
DecartAI/Decart-XR
3,642
DecartAI-Quest-Unity/Assets/metaVoiceSdk/Features/Dictation/source/Lib/Wit.ai/Features/dictation/Scripts/Runtime/Dictation/ServiceReferences/DictationServiceReference.cs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * Licensed under the Oculus SDK License Agreement (the "License"); * you may not use the Oculus SDK except in compliance with the License, * which is provided at the time of installation or download, or which * otherwise accompanies this software in either electronic or hard copy form. * * You may obtain a copy of the License at * * https://developer.oculus.com/licenses/oculussdk/ * * Unless required by applicable law or agreed to in writing, the Oculus SDK * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Meta.WitAi.Dictation; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace Meta.WitAi.Utilities { [Serializable] public struct DictationServiceReference { [SerializeField] internal DictationService dictationService; public DictationService DictationService { get { if (!dictationService) { DictationService[] services = Resources.FindObjectsOfTypeAll<DictationService>(); if (services != null) { // Set as first instance that isn't a prefab dictationService = Array.Find(services, (o) => o.gameObject.scene.rootCount != 0); } } return dictationService; } } } #if UNITY_EDITOR [CustomPropertyDrawer(typeof(DictationServiceReference))] public class DictationServiceReferenceDrawer : PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return EditorGUIUtility.singleLineHeight; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var refProp = property.FindPropertyRelative("DictationService"); var reference = refProp.objectReferenceValue as DictationService; var dictationServices = GameObject.FindObjectsByType<DictationService>(FindObjectsSortMode.None); var dictationServiceNames = new string[dictationServices.Length + 1]; int index = 0; dictationServiceNames[0] = "Autodetect"; if (dictationServices.Length == 1) { dictationServiceNames[0] = $"{dictationServiceNames[0]} - {dictationServices[0].name}"; } for (int i = 0; i < dictationServices.Length; i++) { dictationServiceNames[i + 1] = dictationServices[i].name; if (dictationServices[i] == reference) { index = i + 1; } } EditorGUI.BeginProperty(position, label, property); var updatedIndex = EditorGUI.Popup(position, index, dictationServiceNames); if (index != updatedIndex) { if (updatedIndex > 0) { refProp.objectReferenceValue = dictationServices[updatedIndex - 1]; } else { refProp.objectReferenceValue = null; } property.serializedObject.ApplyModifiedProperties(); } EditorGUI.EndProperty(); } } #endif }
0
0.737282
1
0.737282
game-dev
MEDIA
0.627969
game-dev
0.706139
1
0.706139
mastercomfig/tf2-patches-old
3,205
src/game/client/tf/tf_hud_passtime_reticle.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef TF_HUD_PASSTIME_RETICLE_H #define TF_HUD_PASSTIME_RETICLE_H #ifdef _WIN32 #pragma once #endif #include "utlvector.h" #include "Color.h" #include "fx_quad.h" //----------------------------------------------------------------------------- CFXQuad *CreateReticleSprite( const char *pModelName, float scale, float spinSpeed ); class C_FuncPasstimeGoal; //----------------------------------------------------------------------------- class C_PasstimeReticle { public: virtual ~C_PasstimeReticle(); void OnClientThink(); protected: C_PasstimeReticle() {} virtual bool Update() = 0; void AddSprite( CFXQuad *pEnt ); void SetAllOrigins( const Vector& pos ); void SetAllNormals( const Vector& normal ); void SetAllAlphas( byte a ); void SetAllScales( float s ); void SetOrigin( int i, const Vector& pos ); void SetNormal( int i, const Vector& normal ); void SetAlpha( int i, byte a ); void SetRgba( int i, byte r, byte g, byte b, byte a ); void SetScale( int i, float s ); CUtlVector<CFXQuad*> m_pSprites; private: // noncopyable C_PasstimeReticle( const C_PasstimeReticle& ) = delete; C_PasstimeReticle( C_PasstimeReticle&& ) = delete; C_PasstimeReticle& operator=( const C_PasstimeReticle& ) = delete; C_PasstimeReticle& operator=( C_PasstimeReticle&& ) = delete; }; //----------------------------------------------------------------------------- class C_PasstimeBallReticle : public C_PasstimeReticle { public: C_PasstimeBallReticle(); private: virtual bool Update() OVERRIDE; }; //----------------------------------------------------------------------------- class C_PasstimeGoalReticle : public C_PasstimeReticle { public: C_PasstimeGoalReticle( C_FuncPasstimeGoal *pGoal ); private: virtual bool Update() OVERRIDE; CHandle<C_FuncPasstimeGoal> m_hGoal; }; //----------------------------------------------------------------------------- class C_PasstimePassReticle : public C_PasstimeReticle { public: C_PasstimePassReticle(); private: virtual bool Update() OVERRIDE; void FindPassHintTarget( C_TFPlayer *pLocalPlayer ); float m_flTargetScore; CHandle<C_BaseEntity> m_hTarget; }; //----------------------------------------------------------------------------- class C_PasstimeBounceReticle : public C_PasstimeReticle { public: C_PasstimeBounceReticle(); void Show( const Vector& pos, const Vector& normal ); void Hide(); private: virtual bool Update() OVERRIDE; }; //----------------------------------------------------------------------------- class C_PasstimePlayerReticle : public C_PasstimeReticle { public: C_PasstimePlayerReticle( C_TFPlayer *pPlayer ); private: virtual bool Update() OVERRIDE; CHandle<C_TFPlayer> m_hPlayer; }; //----------------------------------------------------------------------------- class C_PasstimeAskForBallReticle : public C_PasstimeReticle { public: C_PasstimeAskForBallReticle( C_TFPlayer *pPlayer ); private: virtual bool Update() OVERRIDE; CHandle<C_TFPlayer> m_hPlayer; }; #endif // TF_HUD_PASSTIME_RETICLE_H
0
0.92396
1
0.92396
game-dev
MEDIA
0.427696
game-dev
0.685368
1
0.685368
ilpincy/argos3
3,345
src/plugins/simulator/physics_engines/dynamics3d/bullet/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btTriangleIndexVertexArray.h" btTriangleIndexVertexArray::btTriangleIndexVertexArray(int numTriangles, int* triangleIndexBase, int triangleIndexStride, int numVertices, btScalar* vertexBase, int vertexStride) : m_hasAabb(0) { btIndexedMesh mesh; mesh.m_numTriangles = numTriangles; mesh.m_triangleIndexBase = (const unsigned char*)triangleIndexBase; mesh.m_triangleIndexStride = triangleIndexStride; mesh.m_numVertices = numVertices; mesh.m_vertexBase = (const unsigned char*)vertexBase; mesh.m_vertexStride = vertexStride; addIndexedMesh(mesh); } btTriangleIndexVertexArray::~btTriangleIndexVertexArray() { } void btTriangleIndexVertexArray::getLockedVertexIndexBase(unsigned char** vertexbase, int& numverts, PHY_ScalarType& type, int& vertexStride, unsigned char** indexbase, int& indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart) { btAssert(subpart < getNumSubParts()); btIndexedMesh& mesh = m_indexedMeshes[subpart]; numverts = mesh.m_numVertices; (*vertexbase) = (unsigned char*)mesh.m_vertexBase; type = mesh.m_vertexType; vertexStride = mesh.m_vertexStride; numfaces = mesh.m_numTriangles; (*indexbase) = (unsigned char*)mesh.m_triangleIndexBase; indexstride = mesh.m_triangleIndexStride; indicestype = mesh.m_indexType; } void btTriangleIndexVertexArray::getLockedReadOnlyVertexIndexBase(const unsigned char** vertexbase, int& numverts, PHY_ScalarType& type, int& vertexStride, const unsigned char** indexbase, int& indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart) const { const btIndexedMesh& mesh = m_indexedMeshes[subpart]; numverts = mesh.m_numVertices; (*vertexbase) = (const unsigned char*)mesh.m_vertexBase; type = mesh.m_vertexType; vertexStride = mesh.m_vertexStride; numfaces = mesh.m_numTriangles; (*indexbase) = (const unsigned char*)mesh.m_triangleIndexBase; indexstride = mesh.m_triangleIndexStride; indicestype = mesh.m_indexType; } bool btTriangleIndexVertexArray::hasPremadeAabb() const { return (m_hasAabb == 1); } void btTriangleIndexVertexArray::setPremadeAabb(const btVector3& aabbMin, const btVector3& aabbMax) const { m_aabbMin = aabbMin; m_aabbMax = aabbMax; m_hasAabb = 1; // this is intentionally an int see notes in header } void btTriangleIndexVertexArray::getPremadeAabb(btVector3* aabbMin, btVector3* aabbMax) const { *aabbMin = m_aabbMin; *aabbMax = m_aabbMax; }
0
0.881543
1
0.881543
game-dev
MEDIA
0.823055
game-dev
0.874387
1
0.874387
ProjectEQ/projecteqquests
6,736
abysmal/Yitimis_Groglenog.pl
# items: 58211, 58057, 58033, 58164, 58040, 58070, 58133, 58153, 58152, 58144, 58165, 58041, 58213 sub EVENT_SAY { if ($text=~/hail/i) { if (quest::istaskactivityactive(500168,4)) { #Brewing Collect Step 5 quest::say("You've been just a peach helping out! I don't think I need your help any more, you've already done so much. Let me give you the secret I promised and you go out and enjoy the rest of the day."); $client->Message(15, "Yitimis pulls out several ragged-looking pieces of parchment, most with wine stains that make them almost unreadable. She holds one up for you to look at. It only takes you a minute to grasp what needs to be done to prepare the Taelosian Tea Leaves and the Taelosian Mountain Tea Leaves. In fact, you are certain that if you work at it long enough, you can produce more usable tea with practice."); quest::LearnRecipe(7839); #Taelosian Tea quest::LearnRecipe(7838); #Taelosian Mountain Tea } elsif(quest::istaskactivityactive(500158,4)) { #Brewing Freebie Step 5 quest::say("You've been just a peach helping out! I don't think I need your help any more, you've already done so much. Let me give you the secret I promised and you go out and enjoy the rest of the day."); $client->Message(15, "Yitimis pulls out several ragged-looking pieces of parchment, most with wine stains that make them almost unreadable. She holds one up for you to look at. It only takes you a minute to grasp what needs to be done to prepare the Taelosian Tea Leaves and the Taelosian Mountain Tea Leaves. In fact, you are certain that if you work at it long enough, you can produce more usable tea with practice."); quest::LearnRecipe(7839); #Taelosian Tea quest::LearnRecipe(7838); #Taelosian Mountain Tea } else { quest::say("Hail. Brell's blessing on you. Are you, perchance, a brewer or interested in learning the craft? I have a lot of [work] to do here, and I could use some help."); } } if ($text=~/work/i) { quest::say("We're very busy just trying to keep up with demand. With all of the new discoveries on Taelosia, we have a lot of visitors, but I'd really like to have some time to look at the native plants. I've been given some samples of the [tea] that grows locally and it has some very unusual properties. I just have not had enough time to investigate. Perhaps you could [lend a hand] with my daily tasks so that I can free up some time to look into this?"); } if ($text=~/tea/i) { quest::say("It's aromatic and that's the least of its properties. I have a few dozen interesting ideas I want to try. Unfortunately, the tea requires special preparation before it can be used. I've worked out how to do that and I'd be very pleased if you could bring me some of those Taelosian Tea Leaves. I'll prepare them for you and only keep a small amount for myself. That way we can both try it!"); } if ($text=~/lend a hand/i) { if (quest::istaskactivityactive(500158,0)) { #Brewing Freebie Step 1 quest::say("Excellent. The mornings are probably the busiest around here. And a Wayfarer's favorite pick-me-up in the morning is called Spicy Sunrise. Just take the Orange Juice and the Wayfarer Spice and combine it in a brew barrel. It will make a tasty drink! Please bring them to me as soon as you can. If you help me out enough, I may be willing to share the secret of preparing Taelosian Teas with you!"); quest::summonitem(58211,20); #Wayfarer Spice quest::summonitem(58057,20); #Orange Juice } elsif (quest::istaskactivityactive(500158,1)) { #Brewing Freebie Step 2 quest::say("Well hello! I can certainly use your help. We need to brew up some coffee. I think we'll make Vanilla Coffee today. Just take the Coffee Beans, the Vanilla Beans and the Flask of Purified Sea Water and combine them in a brew barrel. Please rush back and give me the coffee, we'd like to serve it hot."); quest::summonitem(58033,20); #Coffee Beans quest::summonitem(58164,20); #Vanilla Beans quest::summonitem(58040,20); #Flask of Purified Sea Water } elsif (quest::istaskactivityactive(500158,2)) { #Brewing Freebie Step 3 quest::say("Hi! I'm glad you can help. One of the things we have trouble with around here is folks that stay on duty for hour after hour and getting bored. They tend to fall asleep. Well, Galidnus designed a tasty beverage that helps folks stay awake. Though he didn't come up with a very good name for it. He calls it Galidnus Glad Juice. To make it, just put Orange Juice, Coffee Beans, and Redberry into a brew barrel and combine. Bring them back to me when you've got them ready. Thank you!"); quest::summonitem(58057,20); #Orange Juice quest::summonitem(58033,20); #Coffee Beans quest::summonitem(58070,20); #Redberry } elsif (quest::istaskactivityactive(500158,3)) { #Brewing Freebie Step 4 quest::say("'You sure are helpful! This one is pretty simple, though the ingredients can be expensive enough, I suppose. We need a good stock of Wayfarer Spiced Wine. Just put the Simple Wine and the Wayfarer Spice in a brew barrel and combine them. Bring me the wine and I'll get them into the store room. Thank you for helping me out."); quest::summonitem(58211,20); #Wayfarer Spice quest::summonitem(58133,20); #Simple Wine } else { quest::taskselector(500158); #Brewing Freebie } } } sub EVENT_ITEM { if (plugin::check_handin(\%itemcount, 58153 => 1)) { #Taelosian Tea Leaves quest::say("Ah, yes. Here is your tea."); quest::summonitem(58152,2); #Taelosian Tea } elsif (plugin::check_handin(\%itemcount, 58144 => 4) || plugin::check_handin(\%itemcount, 58144 => 3) || plugin::check_handin(\%itemcount, 58144 => 2) || plugin::check_handin(\%itemcount, 58144 => 1)) { #Spicy Sunrise quest::say("Ah, yes. Thank you."); } elsif (plugin::check_handin(\%itemcount, 58165 => 4) || plugin::check_handin(\%itemcount, 58165 => 3) || plugin::check_handin(\%itemcount, 58165 => 2) || plugin::check_handin(\%itemcount, 58165 => 1)) { #Vanilla Coffee quest::say("Ah, yes. Thank you."); } elsif (plugin::check_handin(\%itemcount, 58041 => 4) || plugin::check_handin(\%itemcount, 58041 => 3) || plugin::check_handin(\%itemcount, 58041 => 2) || plugin::check_handin(\%itemcount, 58041 => 1)) { #Galidnus' Glad Juice quest::say("Ah, yes. Thank you."); } elsif (plugin::check_handin(\%itemcount, 58213 => 4) || plugin::check_handin(\%itemcount, 58213 => 3) || plugin::check_handin(\%itemcount, 58213 => 2) || plugin::check_handin(\%itemcount, 58213 => 1)) { #Wayfarer Spiced Wine quest::say("Ah, yes. Thank you."); } plugin::return_items(\%itemcount); }
0
0.66421
1
0.66421
game-dev
MEDIA
0.523353
game-dev,testing-qa
0.621955
1
0.621955
KhronosGroup/WebGL
1,654
sdk/tests/conformance/ogles/GL/functions/ivec4_empty_out_ivec4_array_vert.vert
/* Copyright (c) 2019 The Khronos Group Inc. Use of this source code is governed by an MIT-style license that can be found in the LICENSE.txt file. */ attribute vec4 gtf_Vertex; uniform mat4 gtf_ModelViewProjectionMatrix; varying vec4 color; // Function declarations. ivec4 function(out ivec4 par[3]); bool is_all(const in ivec4 par, const in int value); bool is_all(const in ivec4 array[3], const in ivec4 value); void set_all(out ivec4 array[3], const in ivec4 value); void main (void) { ivec4 par[3]; ivec4 ret = ivec4(0, 0, 0, 0); float gray = 0.0; // Initialize the entire array to 1. set_all(par, ivec4(1, 1, 1, 1)); ret = function(par); // The parameter should be changed by the function and the function should return 1. if(is_all(par, ivec4(0, 0, 0, 0)) && is_all(ret, 1)) { gray = 1.0; } color = vec4(gray, gray, gray, 1.0); gl_Position = gtf_ModelViewProjectionMatrix * gtf_Vertex; } // Function definitions. ivec4 function(out ivec4 par[3]) { // Test parameter qualifier (default is "in"). set_all(par, ivec4(0, 0, 0, 0)); return ivec4(1, 1, 1, 1); } bool is_all(const in ivec4 par, const in int value) { bool ret = true; if(par[0] != value) ret = false; if(par[1] != value) ret = false; if(par[2] != value) ret = false; if(par[3] != value) ret = false; return ret; } bool is_all(const in ivec4 array[3], const in ivec4 value) { bool ret = true; if(array[0] != value) ret = false; if(array[1] != value) ret = false; if(array[2] != value) ret = false; return ret; } void set_all(out ivec4 array[3], const in ivec4 value) { array[0] = value; array[1] = value; array[2] = value; }
0
0.804283
1
0.804283
game-dev
MEDIA
0.51004
game-dev
0.86299
1
0.86299
echurchill/CityWorld
1,162
src/me/daddychurchill/CityWorld/Rooms/StorageRoom.java
package me.daddychurchill.CityWorld.Rooms; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.block.data.Bisected.Half; import org.bukkit.block.data.type.Slab.Type; import me.daddychurchill.CityWorld.Support.RealBlocks; abstract class StorageRoom extends FilledRoom { StorageRoom() { // TODO Auto-generated constructor stub } void drawNSEmptyShelve(RealBlocks chunk, int x, int y, int z, int height, int run) { for (int y1 = 0; y1 < height; y1++) { chunk.setBlock(x, y + y1, z, Material.BIRCH_STAIRS, BlockFace.NORTH, Half.TOP); chunk.setBlocks(x, x + 1, y + y1, z + 1, z + run - 1, Material.BIRCH_SLAB, Type.TOP); chunk.setBlock(x, y + y1, z + run - 1, Material.BIRCH_STAIRS, BlockFace.SOUTH, Half.TOP); } } void drawWEEmptyShelve(RealBlocks chunk, int x, int y, int z, int height, int run) { for (int y1 = 0; y1 < height; y1++) { chunk.setBlock(x, y + y1, z, Material.BIRCH_STAIRS, BlockFace.WEST, Half.TOP); chunk.setBlocks(x + 1, x + run - 1, y + y1, z, z + 1, Material.BIRCH_SLAB, Type.TOP); chunk.setBlock(x + run - 1, y + y1, z, Material.BIRCH_STAIRS, BlockFace.EAST, Half.TOP); } } }
0
0.650598
1
0.650598
game-dev
MEDIA
0.759531
game-dev,testing-qa
0.579453
1
0.579453
MATTYOneInc/AionEncomBase_Java8
3,058
AL-Game/data/scripts/system/handlers/ai/worlds/enshar/NegartonAI2.java
/* * This file is part of Encom. * * Encom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Encom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Encom. If not, see <http://www.gnu.org/licenses/>. */ package ai.worlds.enshar; import com.aionemu.gameserver.ai2.AIName; import com.aionemu.gameserver.ai2.NpcAI2; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.utils.ThreadPoolManager; import com.aionemu.gameserver.world.World; import com.aionemu.gameserver.world.knownlist.Visitor; import java.util.List; /****/ /** Author (Encom) /****/ @AIName("negarton") public class NegartonAI2 extends NpcAI2 { @Override protected void handleDialogStart(Player player) { //Cet Territory Village Infiltration Rift Corridor Key. if (player.getInventory().getFirstItemByItemId(185000234) != null) { PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 10)); } else { PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 27)); } } @Override public boolean onDialogSelect(final Player player, int dialogId, int questId, int extendedRewardIndex) { //Cet Territory Village Infiltration Rift Corridor Key. if (dialogId == 10000 && player.getInventory().decreaseByItemId(185000234, 1)) { switch (getNpcId()) { case 804840: //Negarton. announceDarkLegionPortal(); spawn(702721, 1474.6984f, 1796.5096f, 330.69998f, (byte) 103); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { despawnNpc(702721); } }, 300000); //5 Minutes. break; } } PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 0)); return true; } private void announceDarkLegionPortal() { World.getInstance().doOnAllPlayers(new Visitor<Player>() { @Override public void visit(Player player) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_DARK_SIDE_LEGION_DIRECT_PORTAL_OPEN); } }); } private void despawnNpc(int npcId) { if (getPosition().getWorldMapInstance().getNpcs(npcId) != null) { List<Npc> npcs = getPosition().getWorldMapInstance().getNpcs(npcId); for (Npc npc: npcs) { npc.getController().onDelete(); } } } }
0
0.92061
1
0.92061
game-dev
MEDIA
0.939151
game-dev
0.78208
1
0.78208
Stefanuk12/ROBLOX
50,338
Games/Kohls Admin House/Archive/oofkohlsv2/Main.lua
-- // Valiant ENV loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/ValiantENV.lua"))() -- // Main Script if getgenv().KAHHaxLoaded then warn("oofkohls v2 already loaded!") return end warn("Loading oofkohls v2 - Made By Stefanuk12#5820 | Stefanuk12") -- // Initialise if not getgenv()["KAHHax"] then getgenv()["KAHHax"] = {} end if not getgenv()["KAHHax"]["InitialisedModules"] then getgenv()["KAHHax"]["InitialisedModules"] = {} end -- // Vars local Players = game:GetService("Players") local Workspace = game:GetService("Workspace") local LocalPlayer = Players.LocalPlayer local GameFolder = Workspace:WaitForChild("Terrain"):WaitForChild("_Game") local AdminFolder = GameFolder:WaitForChild("Admin") local Pads = AdminFolder:WaitForChild("Pads") local WorkspaceFolder = GameFolder:WaitForChild("Workspace") local HolderFolder = GameFolder:WaitForChild("Folder") local NotificationHandler = loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/Notifications/Script.lua"))() NotificationHandler["StorageLocation"] = game:GetService("CoreGui") KAHHax["vars"] = { PlayerManager = {--[[ PlayerUID = { Lagging = true, SpamList = {}, BlacklistedPhrases = {}, BlacklistConnection = {}, }, ]]}, RainbowColor = Color3.fromRGB(0, 0, 0), WhitelistedUsers = {91318356, 23294806}, MusicAPI = loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/Music%20API/Controller.lua"))(), ChatBypasser = loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/Word%20Bypass/Main.lua"))(), largeText = game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Games/Kohls%20Admin%20House/LongText.txt"), gearList = { PaintBucket = 18474459, Hyperlaser = 130113146, RainbowCarpet = 225921000, Airstrike = 88885539, SuperRLauncher = 190094159, RLauncher = 32356064, SSTripmine = 11999247, ASSentry = 68603151, RPOSword = 159229806, IceStaff = 19704064, Transmorph = 29099749, ShiftingPolarity = 61459706, PortableJustice = 82357101, }, BlacklistedGears = { "82357101", "94794847", }, WhitelistedCMDs = { "play", "give", "smusic", "pmusic", "sallsounds", "pasounds", "tturret", "epilepsy", "paintarea", "regen", }, SpamList = {}, Prefix = ":", NetworkOwner = false, WhileWait = 0.01, } vars = KAHHax.vars vars.ChatBypasser.ChatBypassEnabled = false vars.Alert = function(...) local text = tostring(...) NotificationHandler.newNotification("ALERT", text, "Alert") end vars.Notify = function(...) local text = tostring(...) NotificationHandler.newNotification("SUCCESS", text, "Success") end if sethiddenproperty then game:GetService("RunService"):BindToRenderStep("NetworkRep", 0, function() if vars.NetworkOwner and gethiddenproperty(LocalPlayer, "SimulationRadius") ~= 1/0 then sethiddenproperty(LocalPlayer, "SimulationRadius", 1/0) sethiddenproperty(LocalPlayer, "MaximumSimulationRadius", 1/0) end end) end function KAHHax.vars.getPlayer(String) local Found = {} local Target = string.lower(String) if Target == "all" then for i,v in pairs(game:GetService("Players"):GetPlayers()) do table.insert(Found, v) end elseif Target == "others" then for i,v in pairs(game:GetService("Players"):GetPlayers()) do if v ~= game:GetService("Players").LocalPlayer then table.insert(Found, v) end end elseif Target == "me" then table.insert(Found, game:GetService("Players").LocalPlayer) else for i,v in pairs(game:GetService("Players"):GetPlayers()) do if v.Name:lower():sub(1, #String) == String:lower() then table.insert(Found, v) end end end return Found end function KAHHax.vars.checkWhitelisted(UserId) local PlayerName = Players:GetNameFromUserIdAsync(UserId) if vars.PlayerManager[PlayerName] and vars.PlayerManager[PlayerName]["Whitelisted"] then return true end return false end function KAHHax.vars.checkAllWhitelisted() for _,v in pairs(Players:GetPlayers()) do if KAHHax.vars.checkWhitelisted(v.UserId) then return true end end return false end function KAHHax.vars.addPlayerToManager(Player) if typeof(Player) == 'Instance' and Player.Parent == Players and Player ~= LocalPlayer then vars.PlayerManager[Player.Name] = { ["Lagging"] = false, ["BlacklistedPhrases"] = {}, ["BlacklistConnection"] = {}, ["Whitelisted"] = false, } vars.PlayerManager[Player.Name].BlacklistConnection.A = Player.Chatted:Connect(function(message) local Whitelisted = vars.PlayerManager[Player.Name].Whitelisted -- // Blacklist Phrases for _,v in pairs(vars.PlayerManager[Player.Name].BlacklistedPhrases) do if string.match(message, v.Phrase) then Players:Chat(v.Punishment) end end -- // Blacklist Gears local splitString = string.split(message, " ") if not Whitelisted and string.match(splitString[1], "gear") then for _,v in pairs(vars.BlacklistedGears) do if string.match(message, v) and splitString[2] then if string.lower(splitString[2]) == 'me' then splitString[2] = Player.Name end wait(0.5) Players:Chat(":removetools "..splitString[2]) end end end -- // Whitelist CMDs if Player ~= LocalPlayer and vars.PlayerManager[Player.Name]["Whitelisted"] then for _, v in pairs(vars.WhitelistedCMDs) do local Command = vars.Prefix..v if string.match(message, vars.Prefix..v) and string.sub(message, 1, #Command) == Command then KAHHax.CMDs[v].Function(message) end end end end) print(Player.Name.. " has joined and added to the PlayerManager.") end end function KAHHax.vars.removePlayerFromManager(Player) if typeof(Player) == 'Instance' and Player.Parent == Players and vars.PlayerManager[Player.Name] then for i,v in pairs(vars.PlayerManager) do if i == Player.Name then for a,x in pairs(v.BlacklistConnection) do if typeof(x) == "RBXScriptConnection" then x:Disconnect() end end vars.PlayerManager[i] = nil print(Player.Name.. " has left and been removed from the PlayerManager.") break end end end end wait(0.5) -- // Player Manager for i,v in pairs(Players:GetPlayers()) do vars.addPlayerToManager(v) end Players.PlayerAdded:Connect(function(player) vars.addPlayerToManager(player) end) Players.PlayerRemoving:Connect(function(player) vars.removePlayerFromManager(player) end) -- // Rainbow Color coroutine.wrap(function() while wait() do vars.RainbowColor = Color3.fromHSV(tick() % 5 / 5, 1, 1) end end)() -- // Script KAHHax.CMDs = {--[[ { CommandName = v, ModuleName = w, Example = x, Description = y, Function = z, } ]]} -- // Controller Vars KAHHax.ControllerSettings = { RE = false, PS = false, lagServer = false, EarRape = false, PersistantAdmin = false, Epilepsy = false, LaggerRunning = false, antiPunish = false, antiBlind = false, antiKill = false, antiJail = false, PSCan = game:GetService("MarketplaceService"):UserOwnsGamePassAsync(LocalPlayer.UserId, 35748), } KAHHax.ServerOOFController = {} KAHHax.SoundAbuseController = {} KAHHax.AdminController = {} -- // Script function verifyGameIntegrity() local _Game = game:GetService("Workspace").Terrain["_Game"] local _Workspace = _Game.Workspace local Admin = _Game.Admin local CheckList = { Total = true, AdminPads = true, HouseFloor = true, RegenPad = true, Baseplate = true, } pcall(function() local count = 0 if not _Workspace:FindFirstChild("Baseplate") or _Workspace.Baseplate.Position ~= Vector3.new(-41, 0.0999999, -25.59) then CheckList["Baseplate"] = false CheckList["Total"] = false end if not _Workspace:FindFirstChild("Baseplate") or _Workspace["Basic House"]["SmoothBlockModel112"].Position ~= Vector3.new(-30.065, 4.63, 72.243) then CheckList["HouseFloor"] = false CheckList["Total"] = false end if not Admin:FindFirstChild("Regen") or Admin.Regen.Position ~= Vector3.new(-7.165, 5.42999, 94.743) then CheckList["RegenPad"] = false CheckList["Total"] = false end for i,v in pairs(Admin.Pads:GetChildren()) do count = count + 1 if v.Transparency == 1 then CheckList["AdminPads"] = false CheckList["Total"] = false end end if count < 9 or count < 10 then CheckList["AdminPads"] = false CheckList["Total"] = false end end) return CheckList end function fireCommand(command, message) if KAHHax.CMDs[command] then if not message then message = "" end KAHHax.CMDs[command].Function(vars.Prefix..command.." "..message) end end function checkLagging() local LaggingCount = 0 for i,v in pairs(vars.PlayerManager) do if v.Lagging then LaggingCount = LaggingCount + 1 end end if LaggingCount <= 0 then KAHHax.ControllerSettings.LaggerRunning = false elseif LaggingCount >= 1 then KAHHax.ControllerSettings.LaggerRunning = true end end -- // Anti KAHHax.ControllerSettings.antiPunish = false KAHHax.ControllerSettings.antiBlind = false KAHHax.ControllerSettings.antiKill = false KAHHax.ControllerSettings.antiJail = false game:GetService("Lighting").ChildAdded:Connect(function(child) -- // Anti Punish if KAHHax.ControllerSettings.antiPunish and child.Name == LocalPlayer.Name then Players:Chat(":reset me") end end) LocalPlayer.PlayerGui.ChildAdded:Connect(function(child) -- // Anti Blind if KAHHax.ControllerSettings.antiBlind and child.Name == "EFFECTGUIBLIND" then wait(0.1) child:Destroy() end end) LocalPlayer.Character:WaitForChild("Humanoid").Died:Connect(function() -- // Anti Kill if KAHHax.ControllerSettings.antiKill then Players:Chat(":reset me") end end) LocalPlayer.CharacterAdded:Connect(function(Character) Character:WaitForChild("Humanoid").Died:Connect(function() -- // Anti Kill if KAHHax.ControllerSettings.antiKill then Players:Chat(":reset me") end end) end) HolderFolder.ChildAdded:Connect(function(child) -- // Anti Jail if KAHHax.ControllerSettings.antiJail and child.Name == LocalPlayer.Name.."'s jail" then Players:Chat(":removejails") end end) -- // Identifier ;) local fgpfPHrase = ":m hi gamer" for _,v in pairs(game:GetService("Players"):GetPlayers()) do if table.find(vars.WhitelistedUsers, v.UserId) and LocalPlayer.UserId ~= v.UserId then wait(0.5) game:GetService("ReplicatedStorage").DefaultChatSystemChatEvents.SayMessageRequest:FireServer(fgpfPHrase, "All") Players:Chat(fgpfPHrase) end end game:GetService("Players").PlayerAdded:Connect(function(plr) if vars.checkWhitelisted(plr.UserId) and not table.find(vars.WhitelistedUsers, LocalPlayer.UserId) then wait(0.5) game:GetService("ReplicatedStorage").DefaultChatSystemChatEvents.SayMessageRequest:FireServer(fgpfPHrase, "All") Players:Chat(fgpfPHrase) plr.Chatted:Connect(function(chat) if string.lower(chat) == "hi gamers" and LocalPlayer.UserId ~= plr.UserId then wait(0.5) game:GetService("ReplicatedStorage").DefaultChatSystemChatEvents.SayMessageRequest:FireServer(fgpfPHrase, "All") Players:Chat(fgpfPHrase) end end) end end) for _,v in pairs(vars.WhitelistedUsers) do local Player = Players:GetNameFromUserIdAsync(v) if Players:FindFirstChild(Player) then local Player = Players:FindFirstChild(Player) Player.Chatted:Connect(function(chat) if string.lower(chat) == "hi gamers" and LocalPlayer.UserId ~= Player.UserId then wait(0.5) game:GetService("ReplicatedStorage").DefaultChatSystemChatEvents.SayMessageRequest:FireServer(fgpfPHrase, "All") Players:Chat(fgpfPHrase) end end) end end -- // All of the Coroutines KAHHax.ControllerSettings.RECoroutine = coroutine.wrap(function() -- // Respawn Explode Spam while wait(vars.WhileWait) do if KAHHax.ControllerSettings.RE then for i,v in pairs(vars.getPlayer("others")) do if not vars.checkAllWhitelisted() then Players:Chat(":respawn others") wait(0.1) Players:Chat(":explode others") end end end end end)() KAHHax.ServerOOFController.PartCoroutine = coroutine.wrap(function() -- // Part Spam while wait(vars.WhileWait) do if not KAHHax.ControllerSettings.PSCan then break end if KAHHax.ControllerSettings.PS then Players:Chat(":part/10/10/10") end end end)() if not game:GetService("MarketplaceService"):UserOwnsGamePassAsync(LocalPlayer.UserId, 35748) then vars.Alert("You do not have Person299's Admin, cannot part spam!") end KAHHax.ServerOOFController.EpilepsyCoroutine = coroutine.wrap(function() -- // Epilepsy while wait(vars.WhileWait) do if KAHHax.ControllerSettings.Epilepsy then Players:Chat(":colorshifttop 10000 0 0"); wait() Players:Chat(":colorshiftbottom 10000 0 0"); wait() Players:Chat(":colorshifttop 0 10000 0"); wait() Players:Chat(":colorshiftbottom 0 10000 0"); wait() Players:Chat(":colorshifttop 0 0 10000"); wait() Players:Chat(":colorshiftbottom 0 0 10000"); wait() end end end)() function pmLargeText() for i,v in pairs(vars.PlayerManager) do if v and v.Lagging then Players:Chat(":pm "..i.." "..vars.largeText) end end end KAHHax.ServerOOFController.PMCoroutine = coroutine.wrap(function() -- // PM Lag Spammer while wait(vars.WhileWait) do pmLargeText() end end)() KAHHax.ServerOOFController.SVRLagCoroutine = coroutine.wrap(function() -- // Server Lag while wait(vars.WhileWait) do if KAHHax.ControllerSettings.lagServer and not vars.checkAllWhitelisted() then Players:Chat(":pm others "..vars.largeText) end end end)() KAHHax.SoundAbuseController.mainCoroutine = coroutine.wrap(function() while wait(0.25) do if KAHHax.ControllerSettings.EarRape then for i,v in pairs(game:GetService("Workspace"):GetDescendants()) do if v:IsA("Sound") then v:Play() end end end end end)() SpamListCoroutine = coroutine.wrap(function() while wait(vars.WhileWait) do if vars.SpamList[1] then for _,v in pairs(vars.SpamList) do Players:Chat(v.Phrase) end end end end)() KAHHax.AdminController.PAdminCoroutine = coroutine.wrap(function() fireCommand("regen") wait(math.random()) local Pad = Pads:FindFirstChild("Touch to get admin") while wait() do if KAHHax.ControllerSettings.PersistantAdmin and LocalPlayer.Character:FindFirstChildWhichIsA("BasePart") then Pad.Head.Size = Vector3.new(0.1, 0.1, 0.1) Pad.Head.CanCollide = false Pad.Head.Transparency = 1 Pad.Head.CFrame = LocalPlayer.Character.PrimaryPart.CFrame if not string.match(Pad.Name, LocalPlayer.Name) and Pad.Head.BrickColor == BrickColor.new("Really red") then fireCommand("regen") end end end end)() -- // Anti Lava Blocks for _,v in pairs(WorkspaceFolder.Obby:GetDescendants()) do if v:IsA("TouchTransmitter") then v:Destroy() end end -- // CMD Handler function addCMD(CommandName, ModuleName, Example, Description, Function) if not CommandName or not ModuleName or not Example or not Description or not Function then vars.Alert("addCMDs invalid! ".. CommandName) return end local CMDs = KAHHax.CMDs local Prefix = vars.Prefix CMDs[CommandName] = { ModuleName = ModuleName, Example = Prefix..Example, Description = Description, Function = Function, } end LocalPlayer.Chatted:Connect(function(message) for i,v in pairs(KAHHax.CMDs) do local Command = vars.Prefix..i if not message then message = "" end if v.Function and string.sub(message, 1, #Command) == Command then v.Function(message) end end end) local Prefix = vars.Prefix -- // CMDs: Admin Module addCMD("regen", "Admin", "regen", "Regens the admin.", function(message) local verbrose = string.split(message, " ")[2] local RegenPad = AdminFolder.Regen fireclickdetector(AdminFolder.Regen.ClickDetector, 0) if verbrose then print('Regened Admin.') end end) addCMD("getadmin", "Admin", "getadmin", "Gets admin.", function(message) local verbrose = string.split(message, " ")[2] fireCommand("regen") wait(0.25) if firetouchinterest then firetouchinterest(LocalPlayer.Character.PrimaryPart, Pads:FindFirstChild("Touch to get admin").Head, 0) else local savedPos = LocalPlayer.Character.PrimaryPart.CFrame LocalPlayer.Character.PrimaryPart.CFrame = Pads:FindFirstChild("Touch to get admin").Head.CFrame wait(1) LocalPlayer.Character.PrimaryPart.CFrame = savedPos end if verbrose then print('Got Admin.') end end) addCMD("peradmin", "Admin", "peradmin", "Toggles Persistant Admin.", function(message) KAHHax.ControllerSettings.PersistantAdmin = not KAHHax.ControllerSettings.PersistantAdmin vars.Notify('Persistant Admin Toggle: '.. (not KAHHax.ControllerSettings.PersistantAdmin and "Disabled." or "Enabled.")) end) -- // CMDs: Extra (Anti) Module addCMD("antipunish", "Anti", "antiPunish", "Toggles Anti Punish.", function(message) KAHHax.ControllerSettings.antiPunish = not KAHHax.ControllerSettings.antiPunish vars.Notify('Anti Punish Toggle: '.. (not KAHHax.ControllerSettings.antiPunish and "Disabled." or "Enabled.")) end) addCMD("antiblind", "Anti", "antiBlind", "Toggles Anti Blind.", function(message) KAHHax.ControllerSettings.antiBlind = not KAHHax.ControllerSettings.antiBlind vars.Notify('Anti Blind Toggle: '.. (not KAHHax.ControllerSettings.antiBlind and "Disabled." or "Enabled.")) end) addCMD("antikill", "Anti", "antiKill", "Toggles Anti Kill.", function(message) KAHHax.ControllerSettings.antiKill = not KAHHax.ControllerSettings.antiKill vars.Notify('Anti Kill Toggle: '.. (not KAHHax.ControllerSettings.antiKill and "Disabled." or "Enabled.")) end) addCMD("antijail", "Anti", "antiJail", "Toggles Anti Jail.", function(message) KAHHax.ControllerSettings.antiJail = not KAHHax.ControllerSettings.antiJail vars.Notify('Anti Jail Toggle: '.. (not KAHHax.ControllerSettings.antiJail and "Disabled." or "Enabled.")) end) -- // CMDs: Gear Giver Module addCMD("give", "Gear Giver", "give me SuperRLauncher", "Give yourself and others gears!", function(message) local splitString = string.split(message, " ") if splitString[2] and splitString[3] and vars.gearList[splitString[3]] then Players:Chat(":gear "..splitString[2].." "..vars.gearList[splitString[3]]) elseif not splitString[2] or not splitString[3] then vars.Alert("Invalid Arguments!") end end) addCMD("givehelp", "Gear Giver", "givehelp", "Returns all of the givable gears.", function(message) print('Welcome to Gear Giver - for Kohls Admin House. Prefix is :give - You need admin! All of the available gears will be listed below.') for i,v in pairs(vars.gearList) do local itemName = game:GetService("MarketplaceService"):GetProductInfo(v).Name print("> "..itemName.." = "..i) end print('Example - :give all SSTripmine') end) -- // CMDs: Sound Abuse Module addCMD("pasounds", "Sound Abuse", "pasounds", "Plays all of the sounds in the game.", function(message) for i,v in pairs(game:GetService("Workspace"):GetDescendants()) do if v:IsA("Sound") then v:Play() end end vars.Notify('Played All Sounds.') end) addCMD("sallsounds", "Sound Abuse", "sallsounds", "Stops all of the sounds in the game.", function(message) for i,v in pairs(game:GetService("Workspace"):GetDescendants()) do if v:IsA("Sound") then v:Stop() end end vars.Notify('Stopped All Sounds.') end) addCMD("pmusic", "Sound Abuse", "pmusic", "Plays the 'Music' Sound.", function(message) if HolderFolder:FindFirstChildWhichIsA("Sound") then HolderFolder:FindFirstChildWhichIsA("Sound"):Play() end vars.Notify('Played Music.') end) addCMD("smusic", "Sound Abuse", "smusic", "Stops the 'Music' Sound.", function(message) if HolderFolder:FindFirstChildWhichIsA("Sound") then HolderFolder:FindFirstChildWhichIsA("Sound"):Stop() end vars.Notify('Stopped Music.') end) addCMD("earrape", "Sound Abuse", "earrape", "Toggles EarRape.", function(message) KAHHax.ControllerSettings.EarRape = not KAHHax.ControllerSettings.EarRape vars.Notify('EarRape Toggle: '.. (not KAHHax.ControllerSettings.EarRape and "Disabled." or "Enabled.")) end) -- // CMDs: Server OOF Module addCMD("movebaseplate", "Server OOF", "movebaseplate", "Makes you able to move the baseplate.", function(message) local Spawn = WorkspaceFolder.Spawn3 local Baseplate = WorkspaceFolder.Baseplate local testCFrame = Baseplate.CFrame local testPosition = Spawn.Position local X, Y, Z, R00, R01, R02, R10, R11, R12, R20, R21, R22 = testCFrame:GetComponents() local X, Y, Z = testPosition.X, Y + 1, testPosition.Z local newCFrame = CFrame.new(X, Y, Z, R00, R01, R02, R10, R11, R12, R20, R21, R22) LocalPlayer.Character.HumanoidRootPart.CFrame = newCFrame wait(1.5) Players:Chat(":stun me") vars.Notify("Done!") end) addCMD("partspam", "Server OOF", "partspam", "Toggles Spam Parts (Persons299's Admin Needed!).", function(message) KAHHax.ControllerSettings.PS = not KAHHax.ControllerSettings.PS vars.Notify('Part Spam Toggle: '.. (not KAHHax.ControllerSettings.PS and "Disabled." or "Enabled.")) end) addCMD("respam", "Server OOF", "respam", "Toggles Server Respawn-Explode Spam.", function(message) KAHHax.ControllerSettings.RE = not KAHHax.ControllerSettings.RE vars.Notify('Respawn-Explode Spam Toggle: '.. (not KAHHax.ControllerSettings.RE and "Disabled." or "Enabled.")) end) addCMD("makepbaseplate", "Server OOF", "makepbaseplate", "Makes a 'fake' baseplate.", function(message) local Baseplate = Instance.new("Part", WorkspaceFolder) Baseplate.Name = "PhantomBaseplate" Baseplate.BrickColor = BrickColor.new("Bright green") Baseplate.Size = Vector3.new(1000, 1.2, 1000) Baseplate.TopSurface = "Studs" Baseplate.Anchored = true vars.Notify("Made Fake Baseplate.") end) addCMD("removepbaseplates", "Server OOF", "removepbaseplates", "Removes all 'fake' baseplates.", function(message) for i,v in pairs(WorkspaceFolder:GetChildren()) do if v.Name == "PhantomBaseplate" then v:Destroy() end end vars.Notify("Removed Fake Baseplates.") end) addCMD("paintarea", "Server OOF", "paintarea | 255 0 0 (RGB or 'random') | Obby Box", "Paints the specified section as the specified colour.", function(message) local splitString = string.split(message, " | ") if splitString[1] and splitString[2] and splitString[3] then SelectedColor = Color3.new(0, 0, 0) Color = string.lower(splitString[2]) local Section = string.lower(splitString[3]) vars.Notify("Painting: Section - ".. Section.." ".. "Color - ".. (string.lower(splitString[2]) == "random" and "Random Color" or Color)) if string.gmatch(Color, "[%d%s]+") then R, G, B = 0, 0, 0 local colorSplit = string.split(splitString[2], " ") if colorSplit[1] and tonumber(colorSplit[1]) then R = tonumber(colorSplit[1]) end if colorSplit[2] and tonumber(colorSplit[2]) then G = tonumber(colorSplit[2]) end if colorSplit[3] and tonumber(colorSplit[3]) then B = tonumber(colorSplit[3]) end SelectedColor = Color3.fromRGB(R, G, B) end -- // Check if you already have a Paint Bucket if not (LocalPlayer.Backpack:FindFirstChild("PaintBucket") or LocalPlayer.Character:FindFirstChild("PaintBucket")) then Players:Chat(":gear me 18474459") end LocalPlayer.Backpack:WaitForChild("PaintBucket") LocalPlayer.Character.Humanoid:EquipTool(LocalPlayer.Backpack.PaintBucket) LocalPlayer.Character:WaitForChild("PaintBucket") -- // The Actual Painting Part local Remote = LocalPlayer.Character:WaitForChild("PaintBucket"):WaitForChild("Remotes"):WaitForChild("ServerControls") if Section == "all" then for _, part in pairs(WorkspaceFolder:GetDescendants()) do coroutine.wrap(function() if part:IsA("BasePart") then Remote:InvokeServer("PaintPart", {["Part"] = part, ["Color"] = (Color == "random" and vars.RainbowColor or SelectedColor) }) end end)() end else for i,v in pairs(WorkspaceFolder:GetChildren()) do if string.match(string.lower(v.Name), Section) then for _, part in pairs(v:GetDescendants()) do coroutine.wrap(function() if part:IsA("BasePart") then Remote:InvokeServer("PaintPart", {["Part"] = part, ["Color"] = (Color == "random" and vars.RainbowColor or SelectedColor) }) end end)() end end end end LocalPlayer.Character.PaintBucket.Parent = LocalPlayer.Backpack vars.Notify("Painted: Section - ".. tostring(Section).." ".. "Color -".. (string.lower(splitString[2]) == "random" and "Random Color" or tostring(SelectedColor))) else vars.Alert("Invalid Arguments!") end end) addCMD("tlag", "Server OOF", "tlag EpicGamer69", "Toggles lagging player.", function(message) local splitString = string.split(message, " ") if splitString[1] and splitString[2] then local targetUser = splitString[2] for i,v in pairs(vars.getPlayer(targetUser)) do if not vars.checkWhitelisted(v.UserId) then vars.PlayerManager[v.Name].Lagging = not vars.PlayerManager[v.Name].Lagging vars.Notify(vars.PlayerManager[v.Name].Lagging and v.Name.." is being lagged." or v.Name.." has stopped being lagged.") end end else vars.Alert("Invalid Arguments!") end checkLagging() end) addCMD("svrlag", "Server OOF", "svrlag", "Toggles lagging the whole server.", function(message) KAHHax.ControllerSettings.lagServer = not KAHHax.ControllerSettings.lagServer vars.Notify('Lag Server Toggle: '.. (not KAHHax.ControllerSettings.lagServer and "Disabled." or "Enabled.")) end) addCMD("spam", "Server OOF", "spam kill all", "Spams a message.", function(message) local Str = Prefix.."spam " local givenPhrase = string.sub(message, #Str, -1) if not givenPhrase then vars.Alert("Invalid Arguments!") return end if not vars.SpamList[1] then table.insert(vars.SpamList, {Phrase = givenPhrase}) vars.Notify('Successfully added to Spam List, Message: '.. givenPhrase) else for i,v in pairs(vars.SpamList) do if v.Phrase ~= givenPhrase then table.insert(vars.SpamList, {Phrase = givenPhrase}) vars.Notify('Successfully added to Spam List, Message: '.. givenPhrase) else vars.Alert("Already spamming this message: ".. givenPhrase) end end end end) addCMD("rspam", "Server OOF", "rspam kill all", "Removes a spam message.", function(message) local Str = Prefix.."rspam " local givenPhrase = string.sub(message, #Str, -1) for i,v in pairs(vars.SpamList) do if v.Phrase == givenPhrase then table.remove(vars.SpamList, i) vars.Notify('Successfully removed to Spam List, Message: '.. givenPhrase) end end end) addCMD("blphrase", "Server OOF", "blphrase | EpicGamer69 | kill all | reset all", "When Player says Phrase, Punishment is said.", function(message) local splitString = string.split(message, " | ") if splitString[1] and splitString[2] and splitString[3] and splitString[4] then local targetPlayer = vars.getPlayer(splitString[2]) for _,v in pairs(targetPlayer) do if v and not vars.checkWhitelisted(v.UserId) then local bLTBL = vars.PlayerManager[v.Name].BlacklistedPhrases table.insert(bLTBL, {Phrase = splitString[3], Punishment = splitString[4]}) vars.Notify('Blacklisted Phrase: Player - '.. v.Name.." ".. "Phrase -".. splitString[3].." ".. "Punishment -".. splitString[4]) else vars.Alert(targetPlayer.. " - unable to blacklist phrases") end end else vars.Alert("Invalid Arguments!") end end) addCMD("rblphrase", "Server OOF", "rblphrase | EpicGamer69 | kill all", "Remove Blacklisted Phrase.", function(message) local splitString = string.split(message, " | ") if splitString[1] and splitString[2] and splitString[3]then local targetPlayer = vars.getPlayer(splitString[2]) for _,v in pairs(targetPlayer) do if v and not vars.checkWhitelisted(v.UserId) then for a,x in pairs(vars.PlayerManager[v.Name].BlacklistedPhrases) do if x.Phrase == splitString[3] then table.remove(vars.PlayerManager[v.Name].BlacklistedPhrases, a) vars.Notify('Removed Blacklisted Phrase: Player - '.. v.Name, "Phrase - ".. splitString[3]) end end end end else vars.Alert("Invalid Arguments!") end end) addCMD("crash", "Server OOF", "crash", "Crashes Server.", function(message) Players:Chat(":gear all 94794847") LocalPlayer.Backpack:WaitForChild("VampireVanquisher") LocalPlayer.Character.Humanoid:EquipTool(LocalPlayer.Backpack.VampireVanquisher) LocalPlayer.Character:WaitForChild("VampireVanquisher") wait(1) Players:Chat(":size all .3") wait(1) Players:Chat(":size all .3") wait(1) Players:Chat(":size all .3") end) addCMD("epilepsy", "Server OOF", "epilepsy", "Spams Colours.", function(message) KAHHax.ControllerSettings.Epilepsy = not KAHHax.ControllerSettings.Epilepsy vars.Notify("Toggle - Epilepsy: ".. (KAHHax.ControllerSettings.Epilepsy and "Enabled." or "Disabled.")) end) addCMD("tturret", "Server OOF", "tturret others", "Gives you the Teapot Turret!", function(message) local Str = Prefix.."tturret " if string.sub(message, #Str, -1) then Players:Chat(":hat "..string.sub(message, #Str, -1).." 1055299") else Players:Chat(":hat me 1055299") end vars.Notify("Given Teapot Turret"..(string.sub(message, #Str, -1) and " to "..string.sub(message, #Str, -1).."!" or " self!")) end) -- // CMDs: Music Commands addCMD("getmusic", "Music Commands", "getmusic", "Prints all of the playable music.", function(message) vars.MusicAPI.printMusic() end) addCMD("refreshmusic", "Music Commands", "refreshmusic", "Refreshes the music table.", function(message) vars.MusicAPI.testAllSounds() end) addCMD("play", "Music Commands", "play 53", "Plays the sound indexed at the number.", function(message) local SoundId local splitString = string.split(message, " ") if splitString[1] and splitString[2] and string.gsub(splitString[2], "%D", "") ~= "" then local SoundId = string.gsub(splitString[2], "%D", ""); SoundId = tonumber(SoundId) if not vars.MusicAPI.musicTable[SoundId] then vars.Alert("This sound does not exist!") return end Players:Chat(":music "..vars.MusicAPI.getSound(SoundId)) vars.Notify("Now Playing: "..vars.MusicAPI.getSoundName(SoundId)) else vars.Alert("Invalid Arguments!") end end) -- // CMDs: Control addCMD("whitelist", "Control", "whitelist EpicGamer69", "Whitelists the player to be able to use whitelisted commands.", function(message) local splitString = string.split(message, " ") if splitString[2] then for _, v in pairs(vars.getPlayer(splitString[2])) do if v ~= LocalPlayer and vars.PlayerManager[v.Name] and not vars.PlayerManager[v.Name]["Whitelisted"] then vars.PlayerManager[v.Name]["Whitelisted"] = true vars.Notify("Whitelisted "..v.Name.."!") Players:Chat(":pm " .. v.Name .. " You have been whitelisted to use oof kohls, please follow the link in logs for further info.") Players:Chat(":pm __ bit.ly/wlcmds") end end vars.Notify("Please redirect whitelisted users to: bit.ly/wlcmds. This link redirects to all of the commands they have access to and any extra info they may need.") end end) addCMD("rwhitelist", "Control", "rwhitelist EpicGamer69", "Removes the whitelist from the player.", function(message) local splitString = string.split(message, " ") if splitString[2] then local playerTable = vars.getPlayer(splitString[2]) for _, v in pairs(playerTable) do if v ~= LocalPlayer and not table.find(vars.WhitelistedUsers, v.UserId) and vars.PlayerManager[v.Name] and vars.PlayerManager[v.Name]["Whitelisted"] then vars.PlayerManager[v.Name]["Whitelisted"] = false vars.Notify("Removed "..v.Name.." from the Whitelist!") end end end end) addCMD("blgear", "Control", "blgear 19704064", "Makes it so no one can give others or themselves the blacklisted gear.", function(message) local splitString = string.split(message, " ") if splitString[2] and tonumber(splitString[2]) and not table.find(vars.BlacklistedGears, splitString[2]) then table.insert(vars.BlacklistedGears, splitString[2]) vars.Notify("Blacklisted Gear ("..splitString[2]..")!") end end) addCMD("rblgear", "Control", "rblgear 19704064", "Removes the gear as being Blacklisted.", function(message) local splitString = string.split(message, " ") if splitString[2] and tonumber(splitString[2]) then for i,v in pairs(vars.BlacklistedGears) do if v == splitString[2] then table.remove(vars.BlacklistedGears, i) vars.Notify("Removed Blacklisted Gear ("..splitString[2]..")!") end end end end) -- // CMDs: Misc. Commands addCMD("rj", "Misc", "rj", "Rejoins the game.", function(message) game:GetService('TeleportService'):Teleport(game.PlaceId) end) addCMD("execute", "Misc", "execute print('hi'))", "Executes whatever you want.", function(message) local Str = Prefix.."execute " loadstring(string.sub(message, #Str, -1))() end) addCMD("bypass", "Misc", "bypass whats up my niga", "Auto-bypasses a phrase.", function(message) local Str = Prefix.."bypass " local BypassedText = vars.ChatBypasser.bypassText(string.sub(message, #Str, -1), true) game:GetService("ReplicatedStorage").DefaultChatSystemChatEvents.SayMessageRequest:FireServer(BypassedText, "All") end) addCMD("tbypass", "Misc", "tbypass", "Toggles global bypass on all of your chats.", function(message) vars.ChatBypasser.ChatBypassEnabled = not vars.ChatBypasser.ChatBypassEnabled vars.Notify("Toggle - Chat Bypass: ".. (vars.ChatBypasser.ChatBypassEnabled and "Enabled." or "Disabled.")) end) addCMD("cbtools", "Misc", "cbtools me", "Gears you the BTool gears. (Client-sided)", function(message) local splitString = string.split(message, " ") if not splitString[2] then splitString[2] = "me" end local btoolGears = { "16200204", "16200402", "16969792", "73089190", "21001552", } for _,v in pairs(btoolGears) do Players:Chat(":gear "..splitString[2].." "..v) end vars.Notify("Successfully geared "..splitString[2].." clientsided btools.") end) addCMD("age", "Misc", "age EpicGamer69", "Returns the Account Age of the Player.", function(message) local Str = Prefix.."age " local Target = string.sub(message, #Str, -1) local targetPlayer = vars.getPlayer(Target) if Target and targetPlayer and targetPlayer[1] then for _, plr in pairs(targetPlayer) do local Chat = plr.Name.."'s Account Age is: "..plr.AccountAge --game:GetService("Players"):Chat(":h "..Chat) --game:GetService("ReplicatedStorage").DefaultChatSystemChatEvents.SayMessageRequest:FireServer(Chat, "All") vars.Notify(Chat) wait(2) end else if not targetPlayer[1] then vars.Alert("This Player does not exist!") else vars.Alert("Invalid Arguments!") end end end) addCMD("copycmds", "Misc", "copycmds", "Copies all of the commands to your clipboard.", function(message) local CommandCount = 0 for i,v in pairs(KAHHax.CMDs) do CommandCount = CommandCount + 1 end local Holder = "oofkohls v2 Command List | Total Commands: "..CommandCount.." | Prefix - "..Prefix.."\n" Holder = Holder.."--~~-- Admin Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Admin" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end Holder = Holder.."--~~-- Server OOF Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Server OOF" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end Holder = Holder.."--~~-- Sound Abuse Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Sound Abuse" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end Holder = Holder.."--~~-- Music Commands Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Music Commands" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end Holder = Holder.."--~~-- Gear Giver Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Gear Giver" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end Holder = Holder.."--~~-- Anti Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Anti" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end Holder = Holder.."-~~-- Control Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Control" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end Holder = Holder.."--~~-- Misc Module --~~--\n" for i,v in pairs(KAHHax.CMDs) do if v.ModuleName == "Misc" then Holder = Holder.."> "..i.." - Description: "..v.Description.." - Example: "..v.Example.."\n" end end setclipboard(Holder) vars.Notify("Copied all Commands to clipboard!") end) -- // CMDs: Misc. Commands - CMD GUI addCMD("xcmds", "Misc", "xcmds", "Shows all of the CMDs.", function(message) vars.Notify("Please go to bit.ly/doofkohlsv2 for further info!") local ScriptCMDs = Instance.new("ScreenGui") local Container = Instance.new("Frame") local Header = Instance.new("Frame") local Title = Instance.new("TextButton") local Close = Instance.new("TextButton") local Body = Instance.new("Frame") local CMDFrame = Instance.new("ScrollingFrame") local UIListLayout = Instance.new("UIListLayout") local example = Instance.new("TextButton") local ExamplePrompt = Instance.new("TextButton") ScriptCMDs.Name = "ScriptCMDs" ScriptCMDs.Parent = game.Players.LocalPlayer:WaitForChild("PlayerGui") ScriptCMDs.ZIndexBehavior = Enum.ZIndexBehavior.Sibling Container.Name = "Container" Container.Parent = ScriptCMDs Container.BackgroundColor3 = Color3.fromRGB(25, 25, 25) Container.BackgroundTransparency = 1.000 Container.BorderSizePixel = 0 Container.Position = UDim2.new(0.399999976, 0, 0.200000033, 0) Container.Size = UDim2.new(0, 400, 0, 50) Header.Name = "Header" Header.Parent = Container Header.BackgroundColor3 = Color3.fromRGB(35, 35, 35) Header.BorderSizePixel = 0 Header.Size = UDim2.new(0, 400, 0, 50) Title.Name = "Title" Title.Parent = Header Title.BackgroundColor3 = Color3.fromRGB(35, 35, 35) Title.BackgroundTransparency = 1.000 Title.BorderSizePixel = 0 Title.Size = UDim2.new(0, 0, 0, 50) Title.AutoButtonColor = false Title.Font = Enum.Font.GothamBlack Title.Text = " | Epic Script CMDs" Title.TextColor3 = Color3.fromRGB(255, 255, 255) Title.TextSize = 14.000 Title.TextStrokeColor3 = Color3.fromRGB(200, 200, 200) Title.TextXAlignment = Enum.TextXAlignment.Left Close.Name = "Close" Close.Parent = Header Close.BackgroundColor3 = Color3.fromRGB(25, 25, 25) Close.BorderSizePixel = 0 Close.Position = UDim2.new(0.88500005, 0, 0, 0) Close.Size = UDim2.new(0, 45, 0, 50) Close.AutoButtonColor = false Close.Font = Enum.Font.GothamBold Close.Text = "X" Close.TextColor3 = Color3.fromRGB(255, 105, 97) Close.TextSize = 14.000 Close.TextStrokeColor3 = Color3.fromRGB(200, 200, 200) Body.Name = "Body" Body.Parent = Header Body.BackgroundColor3 = Color3.fromRGB(25, 25, 25) Body.BackgroundTransparency = 1.000 Body.BorderSizePixel = 0 Body.Position = UDim2.new(0, 0, 0.985000014, 0) Body.Size = UDim2.new(0, 400, 0, 350) CMDFrame.Name = "CMDFrame" CMDFrame.Parent = Body CMDFrame.Active = true CMDFrame.BackgroundColor3 = Color3.fromRGB(25, 25, 25) CMDFrame.BorderSizePixel = 0 CMDFrame.Size = UDim2.new(0, 400, 0, 350) CMDFrame.CanvasSize = UDim2.new(0, 0, 5, 0) UIListLayout.Parent = CMDFrame example.Name = ":example" example.Parent = CMDFrame example.BackgroundColor3 = Color3.fromRGB(25, 25, 25) example.BackgroundTransparency = 1.000 example.BorderSizePixel = 0 example.Position = UDim2.new(0, 0, -0.0114285713, 0) example.Size = UDim2.new(0, 400, 0, 50) example.Visible = false example.AutoButtonColor = false example.Font = Enum.Font.Gotham example.Text = " > :example - example description" example.TextColor3 = Color3.fromRGB(255, 255, 255) example.TextSize = 14.000 example.TextStrokeColor3 = Color3.fromRGB(200, 200, 200) example.TextXAlignment = Enum.TextXAlignment.Left ExamplePrompt.Name = "Example Prompt" ExamplePrompt.Parent = Header ExamplePrompt.BackgroundColor3 = Color3.fromRGB(35, 35, 35) ExamplePrompt.BackgroundTransparency = 1.000 ExamplePrompt.BorderSizePixel = 0 ExamplePrompt.Position = UDim2.new(0.38499999, 0, 0, 0) ExamplePrompt.Size = UDim2.new(0, 200, 0, 50) ExamplePrompt.AutoButtonColor = false ExamplePrompt.Font = Enum.Font.Gotham ExamplePrompt.Text = " click cmds 4 example print" ExamplePrompt.TextColor3 = Color3.fromRGB(255, 255, 255) ExamplePrompt.TextSize = 14.000 for i,v in pairs(KAHHax.CMDs) do local Clone = example:Clone() wait() Clone.Name = v.Example Clone.Text = " > "..Prefix..i.." - "..v.Description Clone.Parent = CMDFrame Clone.Visible = true end example = nil -- // Script local Dragger = {}; do local Mouse = game:GetService("Players").LocalPlayer:GetMouse() local UIS = game:GetService("UserInputService") local Heartbeat = game:GetService("RunService").Heartbeat function Dragger.new(Frame) local success, response = pcall(function() return Frame.MouseEnter end) if success then Frame.Active = true response:Connect(function() local Input = Frame.InputBegan:Connect(function(Key) if Key.UserInputType == Enum.UserInputType.MouseButton1 then local objectPosition = Vector2.new(Mouse.X - Frame.AbsolutePosition.X, Mouse.Y - Frame.AbsolutePosition.Y) while Heartbeat:Wait() and UIS:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) do pcall(function() Frame:TweenPosition(UDim2.new(0, Mouse.X - objectPosition.X + (Frame.Size.X.Offset * Frame.AnchorPoint.X), 0, Mouse.Y - objectPosition.Y + (Frame.Size.Y.Offset * Frame.AnchorPoint.Y)), 'Out', 'Linear', 0.1, true) end) end end end) local Leave Leave = Frame.MouseLeave:Connect(function() Input:Disconnect() Leave:Disconnect() end) end) end end end Dragger.new(Container) local Connections = {} function hoverGlow(hoverPart, affectedPart) local TweenService = game:GetService("TweenService") local hPartMouseEnter = hoverPart.MouseEnter:Connect(function() TweenService:Create(affectedPart, TweenInfo.new(0.2), {TextStrokeTransparency = 0.8}):Play() end) local hPartMouseLeave = hoverPart.MouseLeave:Connect(function() TweenService:Create(affectedPart, TweenInfo.new(0.2), {TextStrokeTransparency = 1}):Play() end) local hPartMouseDown = hoverPart.MouseButton1Down:Connect(function() TweenService:Create(affectedPart, TweenInfo.new(0.2), {TextStrokeTransparency = 0.5}):Play() end) local hPartMouseUp = hoverPart.MouseButton1Up:Connect(function() TweenService:Create(affectedPart, TweenInfo.new(0.2), {TextStrokeTransparency = 1}):Play() end) table.insert(Connections, {Connection = hPartMouseEnter}) table.insert(Connections, {Connection = hPartMouseLeave}) table.insert(Connections, {Connection = hPartMouseDown}) table.insert(Connections, {Connection = hPartMouseUp}) end hoverGlow(Close, Close) local CloseConnection = Close.MouseButton1Click:Connect(function() for i,v in pairs(Connections) do v.Connection:Disconnect() end for i,v in pairs(ScriptCMDs:GetDescendants()) do if string.match(v.ClassName, "Frame") then game:GetService("TweenService"):Create(v, TweenInfo.new(1), {BackgroundTransparency = 1}):Play() game:GetService("TweenService"):Create(v, TweenInfo.new(1), {BackgroundTransparency = 1}):Play() end if string.match(v.ClassName, "Text") then game:GetService("TweenService"):Create(v, TweenInfo.new(1), {BackgroundTransparency = 1}):Play() game:GetService("TweenService"):Create(v, TweenInfo.new(1), {TextTransparency = 1}):Play() game:GetService("TweenService"):Create(v, TweenInfo.new(1), {TextTransparency = 1}):Play() v.TextStrokeTransparency = 1 end if string.match(v.ClassName, "ScrollingFrame") then game:GetService("TweenService"):Create(v, TweenInfo.new(1), {ScrollBarImageTransparency = 1}):Play() end end wait(2) ScriptCMDs:Destroy() end) hoverGlow(Title, Title) local TitleClickConnection = Title.MouseButton1Click:Connect(function() print("hi epic scirpt comandsa") end) for i,v in pairs(CMDFrame:GetChildren()) do if v:IsA("TextButton") then hoverGlow(v, v) local ButtonClickConnection = v.MouseButton1Click:Connect(function() print('Command Example - '..v.Name) end) table.insert(Connections, {Connection = ButtonClickConnection}) end end table.insert(Connections, {Connection = CloseConnection}) table.insert(Connections, {Connection = TitleClickConnection}) end) getgenv().KAHHaxLoaded = true vars.Notify('Loaded oofkohls v2 - Made by Stefanuk12#5820 | Stefanuk12') warn("Loaded oofkohls v2 - Made by Stefanuk12#5820 | Stefanuk12")
0
0.936288
1
0.936288
game-dev
MEDIA
0.491841
game-dev,web-backend
0.936496
1
0.936496
raverie-us/raverie-engine
1,891
Code/Systems/Content/ContentLibrary.hpp
// MIT Licensed (see LICENSE.md). #pragma once namespace Raverie { class ResourcePackage; DeclareEnum2(LibraryState, Enumerated, Loaded); /// A Content Library is a collection of content items. Each /// content library is represented by an OS folder on disk. class ContentLibrary : public Object { public: RaverieDeclareType(ContentLibrary, TypeCopyMode::ReferenceType); ContentLibrary(); ~ContentLibrary(); // Name of content library. String Name; // Source path for content library. String SourcePath; // Library listing file name. String LibraryFile; // Unique Id for this content library. ResourceId LibraryId; // Source control type for this content library; String SourceControlType; // Save content library file. // Does not save contained content items meta or data. void Save(); // Save all content files meta files void SaveAllContentItemMeta(); // Load content library file. bool Load(); // Get output path. String GetOutputPath(); // Library Protection bool GetReadOnly() { return mReadOnly; } bool GetWritable() { return !mReadOnly; } // Find a content item by file name (Not the full path). ContentItem* FindContentItemByFileName(StringParam filename); void Serialize(Serializer& stream); void BuildListing(ResourceListing& listing); // Resources in this library hashed by unique file id typedef HashMap<String, ContentItem*> ContentMapType; ContentMapType::valuerange GetContentItems() { return ContentItems.Values(); } private: // Internals // Add a content item to this library. void AddContentItem(ContentItem* contentItem); // Remove a content item from this library. bool RemoveContentItem(ContentItem* contentItem); bool mReadOnly; ContentMapType ContentItems; friend class ContentItem; friend class ContentSystem; }; } // namespace Raverie
0
0.784042
1
0.784042
game-dev
MEDIA
0.423315
game-dev
0.533618
1
0.533618
KelpFramework/kelp
2,259
core/src/main/java/de/pxav/kelp/core/entity/type/ExplosiveMinecart.java
package de.pxav.kelp.core.entity.type; import de.pxav.kelp.core.KelpPlugin; import de.pxav.kelp.core.entity.KelpEntity; import de.pxav.kelp.core.entity.KelpEntityType; import de.pxav.kelp.core.entity.type.general.MinecartEntity; import de.pxav.kelp.core.entity.version.EntityTypeVersionTemplate; import de.pxav.kelp.core.world.KelpLocation; import org.bukkit.entity.Entity; public interface ExplosiveMinecart extends MinecartEntity<ExplosiveMinecart> { /** * Creates a new entity of this type at the given location. * * While this creates a new instance, it won't actually spawn the entity. * You can first do some modifications on it and then call the * {@link KelpEntity#spawn()} method. * * If you don't want to create a new entity, but just a new kelp * entity instance based of an existing bukkit entity, you can use * {@link #from(Entity)} instead. * * @param location The location, where the entity should be spawned later. * @return A new instance of a sheep entity. */ static ExplosiveMinecart create(KelpLocation location) { return (ExplosiveMinecart) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class) .newKelpEntity(getEntityType(), location.getBukkitLocation()); } /** * Takes a bukkit entity and converts it to a kelp entity of the same type. * * This can be used if you are for example handling an event that returns a bukkit entity, * but you want to use a kelp entity for your operations. You can also use * the more general method provided by {@link de.pxav.kelp.core.entity.KelpEntity the * kelp entity base class}: {@link de.pxav.kelp.core.entity.KelpEntity#from(Entity)}, * but this way you don't have to cast your entity to the specific type * manually. * * @param entity The entity you want to convert. * @return The kelp instance of the given bukkit entity. */ static ExplosiveMinecart from(Entity entity) { return (ExplosiveMinecart) KelpPlugin.getInjector().getInstance(EntityTypeVersionTemplate.class) .getKelpEntity(entity); } static KelpEntityType getEntityType() { return KelpEntityType.MINECART_TNT; } @Override default KelpEntityType getType() { return getEntityType(); } }
0
0.530778
1
0.530778
game-dev
MEDIA
0.818903
game-dev
0.673025
1
0.673025
SinlessDevil/TestTaskArmageddonica
1,949
Assets/Code/Infrastructure/StateMachine/Battle/States/CardSelectionBattleState.cs
using Code.Infrastructure.StateMachine.Game.States; using Code.Services.CardSelection; using Code.Services.Factories.UIFactory; using Code.Services.Input.Card; using Code.Services.Input.Card.Select; using Code.UI.Game.Cards.Holder; namespace Code.Infrastructure.StateMachine.Battle.States { public class CardSelectionBattleState : IState, IBattleState { private readonly ICardSelectionWinndowService _cardSelectionWinndowWindowService; private readonly IStateMachine<IBattleState> _stateMachine; private readonly ISelectionCardInputService _selectionCardInputService; private readonly IUIFactory _uiFactory; public CardSelectionBattleState( ICardSelectionWinndowService cardSelectionWinndowWindowService, IStateMachine<IBattleState> stateMachine, ISelectionCardInputService selectionCardInputService, IUIFactory uiFactory) { _cardSelectionWinndowWindowService = cardSelectionWinndowWindowService; _stateMachine = stateMachine; _selectionCardInputService = selectionCardInputService; _uiFactory = uiFactory; } void IState.Enter() { _selectionCardInputService.Enable(); _cardSelectionWinndowWindowService.Open(); _cardSelectionWinndowWindowService.ClosedWindowEvent += OnClosedWinndowWindow; CardHolder.Hide(); } void IExitable.Exit() { _selectionCardInputService.Disable(); _cardSelectionWinndowWindowService.ClosedWindowEvent -= OnClosedWinndowWindow; _cardSelectionWinndowWindowService.Close(); } private void OnClosedWinndowWindow() { _stateMachine.Enter<CardPlacementBattleState>(); } private CardHolder CardHolder => _uiFactory.GameHud.CardHolder; } }
0
0.752318
1
0.752318
game-dev
MEDIA
0.701782
game-dev
0.665428
1
0.665428
randovania/randovania
1,354
randovania/games/samus_returns/db_integrity.py
from collections.abc import Iterator from randovania.game_description.game_description import GameDescription from randovania.game_description.integrity_check import ( check_for_items_to_be_replaced_by_templates, check_for_resources_to_use_together, ) # Short name resource -> recommended template name use_templates_over_items = { "Spring": "Use Spring Ball", "Spider": "Use Spider Ball", "Bomb": "Lay Bomb or Lay Any Bomb", "PBAmmo": "Lay Power Bomb or Lay Any Bomb", } # short name resource -> Tuple(short name resources) combined_resources = { "Spider": ("Morph",), "Spring": ("Morph",), "Bomb": ("Morph",), "PBAmmo": ("Morph",), "IBJ": ("Morph", "Bomb"), "DBJ": ("Morph", "Bomb"), "UBJ": ("Morph", "Bomb"), "FrozenEnemy": ("Ice",), "SpiderClip": ("Morph", "Spider", "OoB"), "IceClip": ("Ice", "OoB"), "PhaseClip": ("Morph", "Phase", "OoB"), "MeleeClip": ("Morph", "OoB"), "UnmorphExtend": ("Morph",), "AirMorph": ("Morph",), "SpiderBoost": ("Morph", "Spider", "PBAmmo"), "Freeze": ("Ice",), "HazardRuns": ("Hazard",), } def find_msr_db_errors(game: GameDescription) -> Iterator[str]: yield from check_for_items_to_be_replaced_by_templates(game, use_templates_over_items) yield from check_for_resources_to_use_together(game, combined_resources)
0
0.637169
1
0.637169
game-dev
MEDIA
0.877488
game-dev
0.872589
1
0.872589
The-Final-Nights/The-Final-Nights
5,846
code/modules/modular_computers/file_system/programs/arcade.dm
/datum/computer_file/program/arcade filename = "dsarcade" filedesc = "Donksoft Micro Arcade" program_icon_state = "arcade" extended_desc = "This port of the classic game 'Outbomb Cuban Pete', redesigned to run on tablets, with thrilling graphics and chilling storytelling." requires_ntnet = FALSE size = 6 tgui_id = "NtosArcade" program_icon = "gamepad" ///Returns TRUE if the game is being played. var/game_active = TRUE ///This disables buttom actions from having any impact if TRUE. Resets to FALSE when the player is allowed to make an action again. var/pause_state = FALSE var/boss_hp = 45 var/boss_mp = 15 var/player_hp = 30 var/player_mp = 10 var/ticket_count = 0 ///Shows what text is shown on the app, usually showing the log of combat actions taken by the player. var/heads_up = "Nanotrasen says, winners make us money." var/boss_name = "Cuban Pete's Minion" ///Determines which boss image to use on the UI. var/boss_id = 1 /datum/computer_file/program/arcade/proc/game_check(mob/user) sleep(5) user?.mind?.adjust_experience(/datum/skill/gaming, 1) if(boss_hp <= 0) heads_up = "You have crushed [boss_name]! Rejoice!" playsound(computer.loc, 'sound/arcade/win.ogg', 50) game_active = FALSE program_icon_state = "arcade_off" if(istype(computer)) computer.update_appearance() ticket_count += 1 user?.mind?.adjust_experience(/datum/skill/gaming, 50) sleep(10) else if(player_hp <= 0 || player_mp <= 0) heads_up = "You have been defeated... how will the station survive?" playsound(computer.loc, 'sound/arcade/lose.ogg', 50) game_active = FALSE program_icon_state = "arcade_off" if(istype(computer)) computer.update_appearance() user?.mind?.adjust_experience(/datum/skill/gaming, 10) sleep(10) /datum/computer_file/program/arcade/proc/enemy_check(mob/user) var/boss_attackamt = 0 //Spam protection from boss attacks as well. var/boss_mpamt = 0 var/bossheal = 0 if(pause_state == TRUE) boss_attackamt = rand(3,6) boss_mpamt = rand (2,4) bossheal = rand (4,6) if(game_active == FALSE) return if (boss_mp <= 5) heads_up = "[boss_mpamt] magic power has been stolen from you!" playsound(computer.loc, 'sound/arcade/steal.ogg', 50, TRUE) player_mp -= boss_mpamt boss_mp += boss_mpamt else if(boss_mp > 5 && boss_hp <12) heads_up = "[boss_name] heals for [bossheal] health!" playsound(computer.loc, 'sound/arcade/heal.ogg', 50, TRUE) boss_hp += bossheal boss_mp -= boss_mpamt else heads_up = "[boss_name] attacks you for [boss_attackamt] damage!" playsound(computer.loc, 'sound/arcade/hit.ogg', 50, TRUE) player_hp -= boss_attackamt pause_state = FALSE game_check() /datum/computer_file/program/arcade/ui_assets(mob/user) return list( get_asset_datum(/datum/asset/simple/arcade), ) /datum/computer_file/program/arcade/ui_data(mob/user) var/list/data = get_header_data() data["Hitpoints"] = boss_hp data["PlayerHitpoints"] = player_hp data["PlayerMP"] = player_mp data["TicketCount"] = ticket_count data["GameActive"] = game_active data["PauseState"] = pause_state data["Status"] = heads_up data["BossID"] = "boss[boss_id].gif" return data /datum/computer_file/program/arcade/ui_act(action, list/params) . = ..() if(.) return var/obj/item/computer_hardware/printer/printer if(computer) printer = computer.all_components[MC_PRINT] var/gamerSkillLevel = 0 var/gamerSkill = 0 if(usr?.mind) gamerSkillLevel = usr.mind.get_skill_level(/datum/skill/gaming) gamerSkill = usr.mind.get_skill_modifier(/datum/skill/gaming, SKILL_RANDS_MODIFIER) switch(action) if("Attack") var/attackamt = 0 //Spam prevention. if(pause_state == FALSE) attackamt = rand(2,6) + rand(0, gamerSkill) pause_state = TRUE heads_up = "You attack for [attackamt] damage." playsound(computer.loc, 'sound/arcade/hit.ogg', 50, TRUE) boss_hp -= attackamt sleep(10) game_check() enemy_check() return TRUE if("Heal") var/healamt = 0 //More Spam Prevention. var/healcost = 0 if(pause_state == FALSE) healamt = rand(6,8) + rand(0, gamerSkill) var/maxPointCost = 3 if(gamerSkillLevel >= SKILL_LEVEL_JOURNEYMAN) maxPointCost = 2 healcost = rand(1, maxPointCost) pause_state = TRUE heads_up = "You heal for [healamt] damage." playsound(computer.loc, 'sound/arcade/heal.ogg', 50, TRUE) player_hp += healamt player_mp -= healcost sleep(10) game_check() enemy_check() return TRUE if("Recharge_Power") var/rechargeamt = 0 //As above. if(pause_state == FALSE) rechargeamt = rand(4,7) + rand(0, gamerSkill) pause_state = TRUE heads_up = "You regain [rechargeamt] magic power." playsound(computer.loc, 'sound/arcade/mana.ogg', 50, TRUE) player_mp += rechargeamt sleep(10) game_check() enemy_check() return TRUE if("Dispense_Tickets") if(!printer) to_chat(usr, "<span class='notice'>Hardware error: A printer is required to redeem tickets.</span>") return if(printer.stored_paper <= 0) to_chat(usr, "<span class='notice'>Hardware error: Printer is out of paper.</span>") return else computer.visible_message("<span class='notice'>\The [computer] prints out paper.</span>") if(ticket_count >= 1) new /obj/item/stack/arcadeticket((get_turf(computer)), 1) to_chat(usr, "<span class='notice'>[computer] dispenses a ticket!</span>") ticket_count -= 1 printer.stored_paper -= 1 else to_chat(usr, "<span class='notice'>You don't have any stored tickets!</span>") return TRUE if("Start_Game") game_active = TRUE boss_hp = 45 player_hp = 30 player_mp = 10 heads_up = "You stand before [boss_name]! Prepare for battle!" program_icon_state = "arcade" boss_id = rand(1,6) pause_state = FALSE if(istype(computer)) computer.update_appearance()
0
0.857567
1
0.857567
game-dev
MEDIA
0.969647
game-dev
0.965737
1
0.965737
danielga/sourcesdk-minimal
1,444
game/server/ai_basehumanoid.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef AI_BASEHUMANOID_H #define AI_BASEHUMANOID_H #include "ai_behavior.h" #include "ai_blended_movement.h" //----------------------------------------------------------------------------- // CLASS: CAI_BaseHumanoid //----------------------------------------------------------------------------- typedef CAI_BlendingHost< CAI_BehaviorHost<CAI_BaseNPC> > CAI_BaseHumanoidBase; class CAI_BaseHumanoid : public CAI_BaseHumanoidBase { DECLARE_CLASS( CAI_BaseHumanoid, CAI_BaseHumanoidBase ); public: bool HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt); // Tasks virtual void StartTask( const Task_t *pTask ); virtual void RunTask( const Task_t *pTask ); virtual void BuildScheduleTestBits( ); // Navigation bool OnMoveBlocked( AIMoveResult_t *pResult ); // Damage void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator ); // Various start tasks virtual void StartTaskRangeAttack1( const Task_t *pTask ); // Various run tasks virtual void RunTaskRangeAttack1( const Task_t *pTask ); // Purpose: check ammo virtual void CheckAmmo( void ); }; //----------------------------------------------------------------------------- #endif
0
0.93312
1
0.93312
game-dev
MEDIA
0.96149
game-dev
0.606481
1
0.606481
ikesnowy/Algorithms-4th-Edition-in-Csharp
3,711
2 Sorting/2.2/Merge/MergeSortKWay.cs
using System; using System.Diagnostics; // ReSharper disable CognitiveComplexity namespace Merge; /// <summary> /// k 路归并排序。 /// </summary> public class MergeSortKWay : BaseSort { /// <summary> /// 同时归并的数组数目。 /// </summary> /// <value>同时归并的数组数目。</value> public int K { get; set; } /// <summary> /// 默认构造函数。 /// </summary> public MergeSortKWay() { K = 2; } /// <summary> /// 用 k 向归并排序对数组 a 进行排序。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="a"></param> /// <exception cref="ArgumentOutOfRangeException">数组长度小于 K 值时抛出异常。</exception> public override void Sort<T>(T[] a) { if (K > a.Length) throw new ArgumentOutOfRangeException(nameof(a), "数组长度不能小于 K 值!"); var aux = new T[a.Length]; Sort(a, aux, 0, a.Length - 1); Debug.Assert(IsSorted(a)); } /// <summary> /// 自顶向下地对数组指定范围内进行 k 向归并排序,需要辅助数组。 /// </summary> /// <typeparam name="T">需要排序的元素类型。</typeparam> /// <param name="a">原数组。</param> /// <param name="aux">辅助数组。</param> /// <param name="lo">排序范围起点。</param> /// <param name="hi">排序范围终点。</param> private void Sort<T>(T[] a, T[] aux, int lo, int hi) where T : IComparable<T> { if (hi <= lo) // 小于或等于一个元素 return; var mids = new int[K - 1]; var steps = (hi - lo) / K; mids[0] = lo + steps; for (var i = 1; i < K - 1; i++) { mids[i] = mids[i - 1] + steps; if (mids[i] > hi) // 防止溢出 mids[i] = hi; } Sort(a, aux, lo, mids[0]); for (var i = 1; i < K - 1; i++) { Sort(a, aux, mids[i - 1] + 1, mids[i]); } Sort(a, aux, mids[K - 2] + 1, hi); Merge(a, aux, lo, mids, hi); } /// <summary> /// 将指定范围内的元素归并。 /// </summary> /// <typeparam name="T">数组元素类型。</typeparam> /// <param name="a">原数组。</param> /// <param name="aux">辅助数组。</param> /// <param name="lo">范围起点。</param> /// <param name="mids">范围中间点。</param> /// <param name="hi">范围终点。</param> private void Merge<T>(T[] a, T[] aux, int lo, int[] mids, int hi) where T : IComparable<T> { for (var l = lo; l <= hi; l++) { aux[l] = a[l]; } var pointers = new int[K]; // 标记每个数组的当前归并位置 pointers[0] = lo; // 开始时归并位置处于每个子数组的起始 for (var i = 1; i < K; i++) { pointers[i] = mids[i - 1] + 1; } // 开始归并 for (var i = lo; i <= hi; i++) { // 找到最小值 T min; var minPointerIndex = 0; var isInit = true; if (pointers[K - 1] > hi) { min = default!; // 初始化以避免编译错误 } else { min = aux[pointers[K - 1]]; minPointerIndex = K - 1; isInit = false; } for (var j = 0; j < K - 1; j++) { if (pointers[j] > mids[j]) // 当前数组已经用完 continue; if (isInit) // 第一次赋值 { isInit = false; min = aux[pointers[j]]; minPointerIndex = j; continue; } if (Less(aux[pointers[j]], min)) { min = aux[pointers[j]]; minPointerIndex = j; } } // 将最小值赋给归并数组,对应子数组的归并位置+1 a[i] = min; pointers[minPointerIndex]++; } } }
0
0.694737
1
0.694737
game-dev
MEDIA
0.298128
game-dev
0.842226
1
0.842226
odamex/odamex
9,583
common/stringtable.cpp
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id: 5e4144c9eef5e9ab934757cc7dd8cc26ccb8c6aa $ // // Copyright (C) 1998-2006 by Randy Heit (ZDoom). // Copyright (C) 2006-2025 by The Odamex Team. // // 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. // // DESCRIPTION: // String Abstraction Layer (StringTable) // //----------------------------------------------------------------------------- #include "odamex.h" #include "stringtable.h" #include "cmdlib.h" #include "i_system.h" #include "oscanner.h" #include "stringenums.h" #include "w_wad.h" /** * @brief Map a ZDoom game name to Odamex's internals and returns true if * the current game is the passed string. * * @param str String to check against. * @return True if the game matches the passed string, otherwise false. */ static bool IfGameZDoom(const std::string& str) { if (!stricmp(str.c_str(), "doom") && ::gamemode != retail_chex && ::gamemode != undetermined) { return true; } if (!stricmp(str.c_str(), "chex") && ::gamemode == retail_chex) { return true; } // We don't support anything else. return false; } bool StringTable::canSetPassString(int pass, const std::string& name) const { StringHash::const_iterator it = _stringHash.find(name); // New string? if (it == _stringHash.end()) return true; // Found an entry, does the string exist? if ((*it).second.string.first == false) return true; // Was the string set with a less exact pass? if ((*it).second.pass >= pass) return true; return false; } void StringTable::clearStrings() { _stringHash.clear(); } // // Loads a language // void StringTable::loadLanguage(const char* code, bool exactMatch, int pass, char* lump, size_t lumpLen) { OScannerConfig config = { "LANGUAGE", // lumpName false, // semiComments true, // cComments }; OScanner os = OScanner::openBuffer(config, lump, lump + lumpLen); while (os.scan()) { // Parse a language section. bool shouldParseSection = false; os.assertTokenIs("["); while (os.scan()) { // Code to check against. char checkCode[4] = {'\0', '\0', '\0', '\0'}; if (os.compareToken("]")) { break; } else if (os.compareToken("default")) { // Default has a speical ID. strncpy(checkCode, "**", 3); } else { // Turn the language into an ID. const std::string& lang = os.getToken(); if (lang.length() == 2 || lang.length() == 3) { strncpy(checkCode, lang.c_str(), lang.length()); } else { os.error("Language identifier must be 2 or 3 characters"); } } if (exactMatch && strncmp(code, checkCode, 3) == 0) { shouldParseSection = true; } else if (!exactMatch && strncmp(code, checkCode, 2) == 0) { shouldParseSection = true; } } if (shouldParseSection) { // Parse all of the strings in this section. while (os.scan()) { if (os.compareToken("[")) { // We reached the end of the section. os.unScan(); break; } // $ifgame() does not appear to be documented in the wiki, // but it causes the next string to only be set it the game // matches up. bool skip = false; if (os.compareToken("$")) { os.scan(); os.assertTokenIs("ifgame"); os.scan(); os.assertTokenIs("("); os.scan(); skip = !IfGameZDoom(os.getToken()); os.scan(); os.assertTokenIs(")"); os.scan(); } // String name const std::string& name = os.getToken(); // If we can find the token, skip past the string if (!canSetPassString(pass, name)) { while (os.scan()) { if (os.compareToken(";")) break; } continue; } os.scan(); os.assertTokenIs("="); // Grab the string value. std::string value; while (os.scan()) { const std::string piece = os.getToken(); if (piece.compare(";") == 0) { // Found the end of the string, next batter up. break; } value += piece; } replaceEscapes(value); if (skip) { continue; } setPassString(pass, name, value); } } else { // Skip past all of the strings in this section. while (os.scan()) { if (os.compareToken("[")) { // Found another section, parse it. os.unScan(); break; } } } } } void StringTable::loadStringsLump(const int lump, const char* lumpname, const bool engOnly) { // Can't use Z_Malloc this early, so we use raw new/delete. size_t len = W_LumpLength(lump); char* languageLump = new char[len + 1]; W_ReadLump(lump, languageLump); languageLump[len] = '\0'; // String replacement pass. Strings in an later pass can be replaced // by a string in an earlier pass from another lump. int pass = 1; if (!engOnly) { // Load language-specific strings. for (size_t i = 0; i < ARRAY_LENGTH(::LanguageIDs); i++) { // Deconstruct code into something less confusing. char code[4]; UNMAKE_ID(code, ::LanguageIDs[i]); // Language codes are up to three letters long. code[3] = '\0'; // Try the full language code (enu). loadLanguage(code, true, pass++, languageLump, len); // Try the partial language code (en). code[2] = '\0'; loadLanguage(code, true, pass++, languageLump, len); // Try an inexact match for all languages in the same family (en_). loadLanguage(code, false, pass++, languageLump, len); } } // Load string defaults. loadLanguage("**", true, pass++, languageLump, len); delete[] languageLump; } void StringTable::prepareIndexes() { // All of the default strings have index numbers that represent their // position in the now-removed enumeration. This function simply sets // them all up. for (size_t i = 0; i < ARRAY_LENGTH(::stringIndexes); i++) { OString name = *(::stringIndexes[i]); StringHash::iterator it = _stringHash.find(name); if (it == _stringHash.end()) { TableEntry entry = {std::make_pair(false, ""), 0xFF, static_cast<int>(i)}; _stringHash.emplace(name, entry); } } } void StringTable::replaceEscapes(std::string& str) { size_t index = 0; for (;;) { // Find the initial slash. index = str.find("\\", index); if (index == std::string::npos || index == str.length() - 1) break; // Substitute the escape string. switch (str.at(index + 1)) { case 'n': str.replace(index, 2, "\n"); break; case '\\': str.replace(index, 2, "\\"); break; } index += 1; } } // // Dump all strings to the console. // // Sometimes a blunt instrument is what is necessary. // void StringTable::dumpStrings() { for (const auto& [first, second] : _stringHash) { PrintFmt(PRINT_HIGH, "{} (pass: {}, index: {}) = {}\n", first, second.pass, second.index, second.string.second); } } // // See if a string exists in the table. // bool StringTable::hasString(const OString& name) const { StringHash::const_iterator it = _stringHash.find(name); if (it == _stringHash.end()) return false; if ((*it).second.string.first == false) return false; return true; } // // Load strings from all LANGUAGE lumps in all loaded WAD files. // void StringTable::loadStrings(const bool engOnly) { clearStrings(); prepareIndexes(); int lump = -1; lump = -1; while ((lump = W_FindLump("LANGUAGE", lump)) != -1) { loadStringsLump(lump, "LANGUAGE", engOnly); } } // // Find a string with the same text. // const OString& StringTable::matchString(const OString& string) const { for (const auto& [first, second] : _stringHash) { if (second.string.first == false) continue; if (second.string.second == string) return first; } static OString empty = ""; return empty; } // // Set a string to something specific by name. // // Overrides the existing string, if it exists. // void StringTable::setString(const OString& name, const OString& string) { StringHash::iterator it = _stringHash.find(name); if (it == _stringHash.end()) { // Stringtable entry does nto exist, insert it. TableEntry entry = {std::make_pair(true, string), 0, -1}; _stringHash.emplace(name, entry); } else { // Stringtable entry exists, update it. (*it).second.string.first = true; (*it).second.string.second = string; } } // // Set a string to something specific by name. // // Does not set the string if it already exists. // void StringTable::setPassString(int pass, const OString& name, const OString& string) { StringHash::iterator it = _stringHash.find(name); if (it == _stringHash.end()) { // Stringtable entry does not exist. TableEntry entry = {std::make_pair(true, string), pass, -1}; _stringHash.emplace(name, entry); } else { // Stringtable entry exists, but has not been set yet. (*it).second.string.first = true; (*it).second.string.second = string; (*it).second.pass = pass; } } // // Number of entries in the stringtable. // size_t StringTable::size() const { return _stringHash.size(); } VERSION_CONTROL(stringtable_cpp, "$Id: 5e4144c9eef5e9ab934757cc7dd8cc26ccb8c6aa $")
0
0.895351
1
0.895351
game-dev
MEDIA
0.224738
game-dev
0.941932
1
0.941932
TelepathicGrunt/Bumblezone
3,862
common/src/main/java/com/telepathicgrunt/the_bumblezone/worldgen/features/HoneyCrystalFeature.java
package com.telepathicgrunt.the_bumblezone.worldgen.features; import com.mojang.serialization.Codec; import com.telepathicgrunt.the_bumblezone.blocks.HoneyCrystal; import com.telepathicgrunt.the_bumblezone.modinit.BzBlocks; import com.telepathicgrunt.the_bumblezone.modinit.BzTags; import com.telepathicgrunt.the_bumblezone.worldgen.features.configs.HoneyCrystalFeatureConfig; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.tags.FluidTags; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; public class HoneyCrystalFeature extends Feature<HoneyCrystalFeatureConfig> { public HoneyCrystalFeature(Codec<HoneyCrystalFeatureConfig> configFactory) { super(configFactory); } /** * Place crystal block attached to a block if it is buried underground or underwater */ @Override public boolean place(FeaturePlaceContext<HoneyCrystalFeatureConfig> context) { BlockPos.MutableBlockPos blockpos$Mutable = new BlockPos.MutableBlockPos().set(context.origin()); BlockState originalBlockstate = context.level().getBlockState(blockpos$Mutable); BlockState blockstate; ChunkPos currentChunkPos = new ChunkPos(blockpos$Mutable); if (originalBlockstate.getBlock() == Blocks.CAVE_AIR || (context.config().exposed && originalBlockstate.isAir() && !originalBlockstate.is(BzTags.AIR_LIKE)) || (originalBlockstate.getFluidState().is(FluidTags.WATER) && originalBlockstate.getCollisionShape(context.level(), blockpos$Mutable).isEmpty())) { for (Direction face : Direction.values()) { blockpos$Mutable.set(context.origin()); blockstate = context.level().getBlockState(blockpos$Mutable.move(face, 7)); if (!context.config().exposed && blockstate.getBlock() == Blocks.AIR) { return false; // too close to the outside. Refuse generation } } BlockState honeyCrystal = BzBlocks.HONEY_CRYSTAL.get().defaultBlockState() .setValue(HoneyCrystal.WATERLOGGED, originalBlockstate.getFluidState().is(FluidTags.WATER)); //loop through all 6 directions blockpos$Mutable.set(context.origin()); for (Direction facing : Direction.values()) { honeyCrystal = honeyCrystal.setValue(HoneyCrystal.FACING, facing); // if the block is solid, place crystal on it if (honeyCrystal.canSurvive(context.level(), blockpos$Mutable)) { //if the spot is invalid, we get air back BlockState result = HoneyCrystal.updateFromNeighbourShapes(honeyCrystal, context.level(), blockpos$Mutable); if (result.getBlock() != Blocks.AIR) { //avoid placing crystal on block in other chunk as the cave hasn't carved it yet. Direction directionProp = result.getValue(HoneyCrystal.FACING); blockpos$Mutable.move(directionProp.getOpposite()); if (blockpos$Mutable.getX() >> 4 != currentChunkPos.x || blockpos$Mutable.getZ() >> 4 != currentChunkPos.z) { return false; // facing side chunk. cancel spawn } blockpos$Mutable.move(directionProp); // move back context.level().setBlock(blockpos$Mutable, result, 3); return true; //crystal was placed } } } } return false; } }
0
0.936633
1
0.936633
game-dev
MEDIA
0.991555
game-dev
0.849383
1
0.849383
StrongPC123/Far-Cry-1-Source-Full
4,674
CryGame/GameCallbacks.cpp
////////////////////////////////////////////////////////////////////// // // Game source code (c) Crytek 2001-2003 // // File: GameCallBacks.cpp // // History: // -October 31,2003: created // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Game.h" #include "XNetwork.h" #include "XServer.h" #include "XClient.h" #include "UIHud.h" #include "XPlayer.h" #include "PlayerSystem.h" #include "XServer.h" #include "WeaponSystemEx.h" #include "ScriptObjectGame.h" #include "ScriptObjectInput.h" #include <IEntitySystem.h> #include "UISystem.h" #include "ScriptObjectUI.h" #include "XVehicleSystem.h" #include "XVehicle.h" /////////////////////////////////////////////////////////////////////////// /////////////////////////// physics callbacks ///////////////////////////// ////////////////////////////////////////////////////////////////////////// int CXGame::CreatePhysicalEntity(void *pForeignData,int iForeignData,int iForeignFlags) { switch (iForeignData&0x0F) { case 0: return ((IEntity*)pForeignData)->CreatePhysicalEntityCallback(iForeignFlags); // CEntity case 1: ((IEntityRender*)pForeignData)->Physicalize(true); return 1; // CBrush case 2: return m_pSystem->GetI3DEngine()->PhysicalizeStaticObject(pForeignData,iForeignData,iForeignFlags); // CStatObjInst } return 0; } ////////////////////////////////////////////////////////////////////////// int CXGame::DestroyPhysicalEntity(IPhysicalEntity *pent) { pe_params_foreign_data pfd; pent->GetParams(&pfd); switch (pfd.iForeignData&0x0F) { case 0: return ((IEntityRender*)pfd.pForeignData)->DestroyPhysicalEntityCallback(pent); // CEntity case 1: ((IEntityRender*)pfd.pForeignData)->DestroyPhysicalEntityCallback(pent); return 1; // CBrush case 2: return 2; // CStatObjInst } return 0; } ////////////////////////////////////////////////////////////////////////// const char *CXGame::GetForeignName(void *pForeignData,int iForeignData,int iForeignFlags) { if (pForeignData) switch (iForeignData) { case 0: return ((IEntity*)pForeignData)->GetName(); case 1: return "Brush/StatObj"; } return "Orphan Entity"; } ////////////////////////////////////////////////////////////////////////// void CXGame::OnBBoxOverlap(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, IPhysicalEntity *pCollider, void *pColliderForeignData,int iColliderForeignData) { if (iForeignData==0 && iColliderForeignData==0) { IEntity *pEntity = (IEntity*)pForeignData; IEntity *pColliderEntity = (IEntity*)pColliderForeignData; pEntity->OnPhysicsBBoxOverlap( pColliderEntity ); } } ////////////////////////////////////////////////////////////////////////// void CXGame::OnCollision(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, coll_history_item *pCollision) { } ////////////////////////////////////////////////////////////////////////// void CXGame::OnStateChange(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, int iOldSimClass,int iNewSimClass) { // If foregin data is entity. if (iForeignData==0) { IEntity *pEntity = ((IEntity*)pForeignData); pEntity->OnPhysicsStateChange( iNewSimClass,iOldSimClass ); } } ////////////////////////////////////////////////////////////////////////// int CXGame::OnImpulse(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, pe_action_impulse *action) { if (iForeignData==0 && IsMultiplayer() && UseFixedStep() && ((IEntity*)pForeignData)->GetNetPresence()) { if (IsServer()) ScheduleEvent(-1,pEntity,action); return 0; } return 1; } ////////////////////////////////////////////////////////////////////////// void CXGame::OnPostStep(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, float fTimeInterval) { IEntityContainer *pCnt; CVehicle *pVehicle; CPlayer *pPlayer; if (iForeignData==0 && pForeignData) { if (((IEntity*)pForeignData)->GetUpdateVisLevel()==eUT_PhysicsPostStep) { SEntityUpdateContext ctx; ctx.nFrameID = m_pSystem->GetIRenderer() ? m_pSystem->GetIRenderer()->GetFrameID() : 0; ctx.pCamera = &m_pSystem->GetViewCamera(); ctx.fCurrTime = m_pSystem->GetITimer()->GetCurrTime(); ctx.fFrameTime = fTimeInterval; ctx.bProfileToLog = false; ctx.numVisibleEntities = 0; ctx.numUpdatedEntities = 0; ((IEntity*)pForeignData)->Update(ctx); } else if (pCnt=((IEntity*)pForeignData)->GetContainer()) { if (pCnt->QueryContainerInterface(CIT_IVEHICLE, (void**)&pVehicle)) pVehicle->UpdatePhysics(fTimeInterval); else if (pCnt->QueryContainerInterface(CIT_IPLAYER, (void**)&pPlayer)) pPlayer->UpdatePhysics(fTimeInterval); } } }
0
0.656838
1
0.656838
game-dev
MEDIA
0.86501
game-dev
0.836412
1
0.836412
dengzibiao/moba
6,461
Assets/Script/UI_Major/UIHero/Breakthrough.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using Tianyu; public class Breakthrough : GUIBase { HeroData hd; public UISprite HeroImg; public UISprite icon; public UIButton RisingStarBtn; public UISlider jingyancao; public UISprite[] StarList; public UILabel ExpLbl; //public UILabel strengthGrowthLabel; //public UILabel intelligenceGrowthLabel; //public UILabel agileGrowthLabel; //public UISprite PowerProgress; //public UISprite IntelligenceProgress; //public UISprite AgilityProgress; private Transform shengXingEffect; public Transform[] xingxingEffect; ItemData soulItem; int currentSoul = 0; int soul_gem = 0; int userGlod = 0; StarUpGradeNode starUpHero; public UILabel Gold; public static Breakthrough instance; public Breakthrough() { instance = this; } public override UIPanleID GetUIKey() { return UIPanleID.none; } /// <summary> /// 初始化 /// </summary> protected override void Init() { //PowerProgress.width = 0; //PowerProgress.pivot = UIWidget.Pivot.Left; //IntelligenceProgress.width = 0; //IntelligenceProgress.pivot = UIWidget.Pivot.Left; //AgilityProgress.width = 0; //AgilityProgress.pivot = UIWidget.Pivot.Left; EventDelegate.Set(RisingStarBtn.onClick, OnRisingStarBtnClick); shengXingEffect = transform.Find("UI_YXShengXing_01"); } protected override void ShowHandler() { //strengthGrowthLabel.text = "" + UI_HeroDetail.hd.node.GetStarGrowUpRate(0, UI_HeroDetail.hd.star); //PowerProgress.width = 60; //intelligenceGrowthLabel.text = "" + UI_HeroDetail.hd.node.GetStarGrowUpRate(1, UI_HeroDetail.hd.star); //IntelligenceProgress.width = HeroDescription.Instance().GetProgressLength(UI_HeroDetail.hd.node.GetStarGrowUpRate(1, UI_HeroDetail.hd.star)); //agileGrowthLabel.text = "" + UI_HeroDetail.hd.node.GetStarGrowUpRate(2, UI_HeroDetail.hd.star); //AgilityProgress.width = HeroDescription.Instance().GetProgressLength(UI_HeroDetail.hd.node.GetStarGrowUpRate(2, UI_HeroDetail.hd.star)); } public void RefreshUI(HeroData hd) { this.hd = hd; soulItem = playerData.GetInstance().GetItemDatatByID(hd.node.soul_gem); HeroImg.spriteName = hd.node.icon_name; icon.spriteName = GoodsDataOperation.GetInstance().GetSmallHeroGrameByHeroGrade(hd.grade); if (null == soulItem) { currentSoul = 0; } else { currentSoul = soulItem.Count; } for (int i = 0; i < StarList.Length; i++) { StarList[i].spriteName = i < hd.star ? "xing" : "xing-hui"; } if (hd.star < 5) { int star = hd.star; RisingStarBtn.gameObject.SetActive(true); Gold.gameObject.SetActive(true); starUpHero = FSDataNodeTable<StarUpGradeNode>.GetSingleton().FindDataByType(++star); //更换英雄魂石图标 Gold 魂石条 Gold.text = "" + starUpHero.evolve_cost; //魂石条赋值 jingyancao.value = currentSoul / (float)starUpHero.evolve_stone_num; jingyancao.transform.Find("Label").GetComponent<UILabel>().text = currentSoul + "/" + starUpHero.evolve_stone_num; } else { Gold.text = ""; jingyancao.value = 1 / 1; //jingyancao.transform.Find("Label").GetComponent<UILabel>().text = currentSoul + " 英雄星级已达到满级"; jingyancao.transform.Find("Label").GetComponent<UILabel>().text = " 英雄星级已达到满级"; RisingStarBtn.gameObject.SetActive(false); Gold.gameObject.SetActive(false); } if (shengXingEffect!=null) { if (shengXingEffect.gameObject.activeSelf) { shengXingEffect.gameObject.SetActive(false); } } for (int i = 0; i < xingxingEffect.Length; i++) { xingxingEffect[i].gameObject.SetActive(false); } } public void PlayerShengXingEffect(int from,int to) { shengXingEffect.gameObject.SetActive(true); if (xingxingEffect.Length >= to) { xingxingEffect[to - 1].gameObject.SetActive(true); } StartCoroutine(HideEffect()); } IEnumerator HideEffect() { yield return new WaitForSeconds(1f); shengXingEffect.gameObject.SetActive(false); for (int i=0;i<xingxingEffect.Length;i++) { xingxingEffect[i].gameObject.SetActive(false); } } private void OnRisingStarBtnClick() { if (hd.star >= 5) { starUpHero = FSDataNodeTable<StarUpGradeNode>.GetSingleton().FindDataByType(hd.star); Gold.text = "" + starUpHero.evolve_cost; //获取物品 //soulItem = playerData.GetInstance().GetItemDatatByID(Globe.selectHero.soul_gem); if (null == soulItem) { currentSoul = 0; } else { currentSoul = soulItem.Count; } jingyancao.value = 1; jingyancao.transform.Find("Label").GetComponent<UILabel>().text = currentSoul + "/" + starUpHero.evolve_stone_num; return; } //金币 if (playerData.GetInstance().baginfo.gold < starUpHero.evolve_cost) { Control.ShowGUI(UIPanleID.UIGoldHand, EnumOpenUIType.DefaultUIOrSecond); return; } if (currentSoul >= starUpHero.evolve_stone_num) { soul_gem = starUpHero.evolve_stone_num; userGlod = starUpHero.evolve_cost; int star = hd.star; HeroAndEquipNodeData.HD = hd; ClientSendDataMgr.GetSingle().GetHeroSend().SendUpgradeHeroStar(Globe.selectHero.hero_id, star+1, Globe.selectHero.soul_gem, starUpHero.evolve_stone_num); } else { //UIGoodsGetWayPanel.Instance.SetID(hd.node.soul_gem); //if (UILevel.instance.GetLevelData()) //{ // Control.ShowGUI(GameLibrary.UIGoodsGetWayPanel); //} Control.ShowGUI(UIPanleID.UIGoodsGetWayPanel, EnumOpenUIType.DefaultUIOrSecond, false, (long)hd.node.soul_gem); return; } } }
0
0.830016
1
0.830016
game-dev
MEDIA
0.960092
game-dev
0.957242
1
0.957242
melsman/mlkit
2,910
src/Common/UnionFindPoly.sml
(* * * File: UnionFindPoly.sml * Author: Lars Birkedal (birkedal@diku.dk) * Created: Wed May 12 15:26:35 MET DST 1993 * Modified: Fri Apr 29 13:37:13 MET DST 1994 * * Contents: Polymorphic Union Find * Tarjan, ``Data Structures and Network Algorithms'', 1983 * *) (* 24 Feb 1996: modified ElementNode type by replacing 'info ref by 'info *) structure UnionFindPoly: UNION_FIND_POLY = struct type rank = int ref datatype 'info ElementNode = EQR of 'info * rank | LINK of 'info Element withtype 'info Element = 'info ElementNode ref fun die s = let val s = "UnionFindPoly." ^ s in print s; raise Fail s end fun find e = (* Path halving *) case !e of LINK e' => (case !e' of LINK e'' => (e := LINK e''; find e'') | EQR _ => e') | EQR _ => e fun find_info e = let val e = find e in case !e of EQR(i,_) => i | _ => die "find_info.impossible" end fun find_rep_and_info e = let val e = find e in case !e of EQR(i,_) => (e,i) | _ => die "find_rep_and_info.impossible" end fun set_info e i = let val e = find e in case !e of EQR(_,r) => e:= EQR(i,r) | _ => die "set_info.impossible" end fun eq_Elements (e1 : 'info Element, e2 : 'info Element) : bool = find e1 = find e2 fun mkElement (info : '_info) = ref (EQR(info, ref 0)) fun union info_combine (e,e') = (* Union by rank *) let val e = find e val e' = find e' in case (!e, !e') of (EQR(i,r),EQR(i',r')) => if !r < !r' then (e' := EQR(info_combine (i,i'),r'); e := LINK e'; e') else if !r' < !r then (e := EQR(info_combine (i,i'),r); (* was (i',i) ; mael 2004-08-21 *) e' := LINK e; e) else (r' := !r' + 1; e' := EQR(info_combine (i,i'),r'); e := LINK e'; e') | _ => die "union.impossible" end (* Pickler *) val pu_intref = Pickle.refOneGen Pickle.int (* Perhaps not really safe as ranks are used * as first-class values *) fun pu (dummy : 'a) (pu_a : 'a Pickle.pu) : 'a Element Pickle.pu = let val dummy : 'a ElementNode = EQR(dummy,ref 0) val pu_Element : 'a ElementNode Pickle.pu -> 'a Element Pickle.pu = Pickle.cache "Element" (fn pu => let val pu = Pickle.refEqGen eq_Elements dummy pu in Pickle.convert (fn a => a, fn a => find a) pu end) fun toInt (EQR _) = 0 | toInt (LINK _) = 1 fun fun_EQR pu = Pickle.con1 EQR (fn EQR a => a | _ => die "pu.fun_EQR") (Pickle.pairGen0(pu_a,pu_intref)) fun fun_LINK pu = Pickle.con1 LINK (fn (* LINK a => a | *) _ => die "pu.fun_LINK") (pu_Element pu) val pu = Pickle.dataGen("UnionFindPoly.ElementNode",toInt,[fun_EQR,fun_LINK]) in pu_Element pu end fun find x = x end
0
0.752753
1
0.752753
game-dev
MEDIA
0.310212
game-dev
0.954148
1
0.954148
Calandiel/SongsOfFOSS
12,659
sote/game/raws/events/_localisation.lua
local ut = require "game.ui-utils" local political_values = require "game.raws.values.political" local text = {} ---Character prepares to explore local province and chooses how he will proceed ---@param self table ---@param character Character ---@param associated_data Province function text.exploration_preparation(self, character, associated_data) return "I plan to explore the province " .. associated_data.name .. ". We have following options:" end ---Character explores local province and reports to himself of exploration progress ---@param self table ---@param character Character ---@param associated_data ExplorationData function text.exploration_progress(self, character, associated_data) return "I am currently exploring the province " .. associated_data.explored_province.name .. "." .. " I estimate that exploration will take roughly " .. tostring(math.floor(associated_data._exploration_days_left / character.leading_warband:size())) .. " days." .. " We have enough supplies for " .. ut.to_fixed_point2(character.leading_warband:days_of_travel()) .. " days of exploration" end ---Character prepares to explore local province and chooses how he will proceed ---@param self table ---@param character Character ---@param associated_data ExplorationData function text.exploration_result(self, character, associated_data) return "My party finished exploration of the local province" end ---Character was asked by explorer about local lands ---@param self table ---@param character Character ---@param associated_data ExplorationData function text.exploration_ask_locals_local(self, character, associated_data) return associated_data.explorer.name .. " asked me about local area." end ---Character receives an answer from a local character and decides his further actions ---@param self table ---@param character Character ---@param associated_data ExplorationData function text.exploration_ask_locals_explorer_payment(self, character, associated_data) local conversation = associated_data.last_conversation if conversation == nil then error("Conversation was not set") end local payment_string = tostring(ut.to_fixed_point2(conversation.payment)) .. MONEY_SYMBOL; return "Local person asked us for a payment: " .. payment_string .. " in exchange for information." end ---Character receives help from a local character in his exploration ---@param self table ---@param character Character ---@param associated_data ExplorationData function text.exploration_ask_locals_explorer_help_received(self, character, associated_data) local conversation = associated_data.last_conversation if conversation == nil then error("Conversation was not set") end return "Local person " .. conversation.partner.name .. " provided me with directions." end function text.option_okay(self, character, associated_data) return "Fine" end function text.tooltip_okay(self, character, associated_data) return "Get back to whatever I was doing" end ---Character was paid for his help in exploration ---@param self table ---@param character Character ---@param associated_data ExplorationData ---@return function function text.exploration_helper_payment_received(self, character, associated_data) return function() return "I got " .. ut.to_fixed_point2(associated_data.last_conversation.payment) .. MONEY_SYMBOL .. " of wealth." end end ---Character was paid for his help in exploration ---@param self table ---@param character Character ---@param associated_data nil ---@return string function text.tax_collection_1(self, character, associated_data) return "I was collecting taxes on behalf of " .. character.realm.leader.name .. ". " .. "I have already collected a sizable amount but I can collect even more taxes and keep them myself." .. " My reputation among our people will suffer even more but as long I am on a good side of " .. character.realm.leader.name .. " it's probably fine." end function text.request_tribute(self, character, associated_data) ---@type Character associated_data = associated_data local name = associated_data.name local temp = "him" if associated_data.female then temp = "her" end local my_warlords, my_power = political_values.military_strength(character) local their_warlords, their_power = political_values.military_strength(associated_data) local strength_estimation_string = "There are " .. my_warlords .. " warlords on my side with total strength of " .. my_power .. " warriors. And on their side there are " .. their_warlords .. " warlords with total strength of " .. their_power .. " warriors." return name .. " requested me to pay tribute to " .. temp .. ". " .. strength_estimation_string .. " What should I do?" end function text.request_tribute_refusal(self, character, associated_data) ---@type Character associated_data = associated_data local name = associated_data.name local my_warlords, my_power = political_values.military_strength(character) local their_warlords, their_power = political_values.military_strength(associated_data) local strength_estimation_string = "There are " .. my_warlords .. " warlords on my side with total strength of " .. my_power .. " warriors. And on their side there are " .. their_warlords .. " warlords with total strength of " .. their_power .. " warriors." return name .. " refused to pay tribute to me. " .. strength_estimation_string .. " What should I do?" end function text.not_a_leader() return "I'm not a leader of the tribe" end function text.negotiation_not_a_tributary() return "We are not the tributary of them" end ---Produces a string which summarizes current negotiation ---@param negotiation NegotiationData function text.negotiation_string(negotiation) local trade_string_initiator = "" if negotiation.negotiations_terms_characters then trade_string_initiator = negotiation.initiator.name .. " will: \n" for good, amount in pairs(negotiation.negotiations_terms_characters.trade.goods_transfer_from_initiator_to_target) do if amount > 0 then trade_string_initiator = trade_string_initiator .. "- Transfer " .. tostring(amount) .. " of " .. good .. "\n" end end if negotiation.negotiations_terms_characters.trade.wealth_transfer_from_initiator_to_target > 0 then trade_string_initiator = trade_string_initiator .. "- Transfer " .. tostring(negotiation.negotiations_terms_characters.trade.wealth_transfer_from_initiator_to_target) .. " of wealth \n" end end local trade_string_target = "" if negotiation.negotiations_terms_characters then trade_string_target = negotiation.target.name .. " will: \n" for good, amount in pairs(negotiation.negotiations_terms_characters.trade.goods_transfer_from_initiator_to_target) do if amount < 0 then trade_string_target = trade_string_target .. "- Transfer " .. tostring(-amount) .. " of " .. good .. "\n" end end if negotiation.negotiations_terms_characters.trade.wealth_transfer_from_initiator_to_target < 0 then trade_string_target = trade_string_target .. "- Transfer " .. tostring(-negotiation.negotiations_terms_characters.trade.wealth_transfer_from_initiator_to_target) .. " of wealth \n" end end local realm_string = "" -- diplomacy for _, item in ipairs(negotiation.negotiations_terms_realms) do if item.free then realm_string = realm_string .. "- ".. item.root.name .. " will set " .. item.target.name .. " free. \n" end if item.subjugate then realm_string = realm_string .. "- ".. item.target.name .. " will recognise " .. item.root.name .. " as an overlord. \n" end realm_string = realm_string .. "These realms will will negotiate a following trade agreement \n" local trade_realm_string_initiator = negotiation.initiator.name .. " will: \n" for good, amount in pairs(item.trade.goods_transfer_from_initiator_to_target) do if amount > 0 then trade_realm_string_initiator = trade_realm_string_initiator .. "- Transfer " .. tostring(amount) .. " of " .. good .. "\n" end end if item.trade.wealth_transfer_from_initiator_to_target > 0 then trade_realm_string_initiator = trade_realm_string_initiator .. "- Transfer " .. tostring(item.trade.wealth_transfer_from_initiator_to_target) .. " of wealth \n" end local trade_realm_string_target = negotiation.target.name .. " will: \n" for good, amount in pairs(item.trade.goods_transfer_from_initiator_to_target) do if amount < 0 then trade_realm_string_target = trade_realm_string_target .. "- Transfer " .. tostring(-amount) .. " of " .. good .. "\n" end end if item.trade.wealth_transfer_from_initiator_to_target < 0 then trade_realm_string_target = trade_realm_string_target .. "- Transfer " .. tostring(-item.trade.wealth_transfer_from_initiator_to_target) .. " of wealth \n" end realm_string = realm_string .. trade_realm_string_initiator .. trade_realm_string_target .. "\n" end local character_realm_string = "Also, \n" for _, item in ipairs(negotiation.negotiations_terms_character_to_realm) do if item.trade_permission then character_realm_string = character_realm_string .. negotiation.initiator.name .. " will be allowed to trade in lands of " .. item.target.name .. "\n" end if item.building_permission then character_realm_string = character_realm_string .. negotiation.initiator.name .. " will be allowed to build in lands of " .. item.target.name .. "\n" end end return trade_string_initiator .. trade_string_target .. realm_string .. character_realm_string -- maybe it could be reused later --[[ if status.goods_transfer then current_status_string = current_status_string .. "Transfer a part of their stockpile to overlord. \n" end if status.wealth_transfer then current_status_string = current_status_string .. "Transfer a part of their wealth to overlord. \n" end if status.warriors_contribution then current_status_string = current_status_string .. "Provide overlord with warriors. \n" end if status.protection then current_status_string = current_status_string .. "Overlord is obliged to protect them. \n" end if status.local_ruler then current_status_string = current_status_string .. "Subject's ruler is decided locally. \n" else current_status_string = current_status_string .. "Subject's ruler is decided by overlord. \n" end ]]-- end function text.negotiate(self, character, associated_data) ---@type Character character = character ---@type NegotiationData associated_data = associated_data local intro = "INITIATOR: " .. associated_data.initiator.name .. " NEGOTIATION PARTNER: " .. associated_data.target.name .. ".\n" return intro .. "Current negotiation draft: \n" .. text.negotiation_string(associated_data) end function text.negotiate_adjustment(self, character, associated_data) ---@type Character character = character ---@type NegotiationData associated_data = associated_data local intro = "We got response from " .. associated_data.target.name .. ".\n" return intro .. "He presented us with a following adjusted negotiation draft: \n" .. text.negotiation_string(associated_data) end function text.negotiation_status_quo() return "Or maybe we don't want any changes after all." end function text.negotiation_agree() return "We agree with the new terms" end function text.negotiation_disagree() return "We disagree with the new terms" end ---@param self table ---@param character Character ---@param negotiation_data NegotiationData ---@return string function text.target_accepts(self, character, negotiation_data) return character.name .. " accepted our offer" end function text.negotiation_back_down(self, character, negotiation_data) return "I decided to back down" end ---@param self table ---@param character Character ---@param negotiation_data NegotiationData ---@return string function text.target_declines(self, character, negotiation_data) return character.name .. " declined our offer" end function text.add_personal_term_option(self, character, negotiation_data) return "Add new personal term" end function text.add_personal_term_option_tooltip(self, character, negotiation_data) return "Personal goods or wealth exchange." end function text.add_realm_term_option(self, character, negotiation_data) return "Add new realm-related term" end function text.add_realm_term_option_tooltip(self, character, negotiation_data) return "Diplomacy" end function text.send_negotiation_terms_tooltip(self, character, negotiation_data) return "Send your terms to your target" end return text
0
0.767973
1
0.767973
game-dev
MEDIA
0.754373
game-dev
0.884771
1
0.884771
AlessioGr/NotQuests
3,119
paper/src/main/java/rocks/gravili/notquests/paper/structs/variables/PermissionVariable.java
/* * NotQuests - A Questing plugin for Minecraft Servers * Copyright (C) 2022 Alessio Gravili * * 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 rocks.gravili.notquests.paper.structs.variables; import cloud.commandframework.arguments.standard.StringArgument; import java.util.ArrayList; import java.util.List; import org.bukkit.command.CommandSender; import rocks.gravili.notquests.paper.NotQuests; import rocks.gravili.notquests.paper.structs.QuestPlayer; public class PermissionVariable extends Variable<Boolean> { public PermissionVariable(NotQuests main) { super(main); if (main.getIntegrationsManager().isLuckpermsEnabled()) { setCanSetValue(true); } addRequiredString( StringArgument.<CommandSender>newBuilder("Permission") .withSuggestionsProvider( (context, lastString) -> { final List<String> allArgs = context.getRawInput(); main.getUtilManager() .sendFancyCommandCompletion( context.getSender(), allArgs.toArray(new String[0]), "[Permission Node]", "[...]"); ArrayList<String> suggestions = new ArrayList<>(); suggestions.add("<Enter Permission node>"); return suggestions; }) .single() .build()); } @Override public Boolean getValueInternally(QuestPlayer questPlayer, Object... objects) { return questPlayer != null && questPlayer.getPlayer().hasPermission(getRequiredStringValue("Permission")); } @Override public boolean setValueInternally(Boolean newValue, QuestPlayer questPlayer, Object... objects) { if (!main.getIntegrationsManager().isLuckpermsEnabled()) { return false; } if (newValue) { main.getIntegrationsManager() .getLuckPermsManager() .givePermission(questPlayer.getUniqueId(), getRequiredStringValue("Permission")); } else { main.getIntegrationsManager() .getLuckPermsManager() .denyPermission(questPlayer.getUniqueId(), getRequiredStringValue("Permission")); } return true; } @Override public List<String> getPossibleValues(QuestPlayer questPlayer, Object... objects) { return null; } @Override public String getPlural() { return "Permissions"; } @Override public String getSingular() { return "Permission"; } }
0
0.883533
1
0.883533
game-dev
MEDIA
0.940776
game-dev
0.885769
1
0.885769
PlayFab/PlayFab-Samples
3,885
Samples/Win32/ThunderRumble/PlayFabCPPSDK/include/playfab/PlayFabPluginManager.h
#pragma once #include <playfab/PlayFabCallRequestContainer.h> #include <playfab/PlayFabError.h> #include <unordered_map> // Intellisense-only includes #include <curl/curl.h> namespace PlayFab { /// <summary> /// The enumeration of supported plugin contracts. /// </summary> enum class PlayFabPluginContract { PlayFab_Serializer, PlayFab_Transport }; /// <summary> /// Interface of any PlayFab SDK plugin. /// </summary> class IPlayFabPlugin { }; /// <summary> /// Interface of any transport SDK plugin. /// All functions execute asynchronously /// </summary> class IPlayFabHttpPlugin : public IPlayFabPlugin { public: /// <summary> /// starts the process of making a post request. /// A user is expected to supply their own CallRequestContainerBase /// </summary> virtual void MakePostRequest(const CallRequestContainerBase&) = 0; }; /// <summary> /// Interface of any data serializer SDK plugin. /// </summary> class IPlayFabSerializerPlugin : public IPlayFabPlugin { }; /// <summary> /// The PlayFab plugin manager. /// It can be used either as an instance or a singleton. /// </summary> class PlayFabPluginManager { public: static PlayFabPluginManager& GetInstance(); // The singleton instance of plugin manager (created on demand) PlayFabPluginManager(); // Prevent copy/move construction PlayFabPluginManager(const PlayFabPluginManager&) = delete; PlayFabPluginManager(PlayFabPluginManager&&) = delete; // Prevent copy/move assignment operations PlayFabPluginManager& operator=(const PlayFabPluginManager&) = delete; PlayFabPluginManager& operator=(PlayFabPluginManager&&) = delete; // Gets a plugin. // If a plugin with specified contract and optional instance name does not exist, it will create a new one. template <typename T> static std::shared_ptr<T> GetPlugin(const PlayFabPluginContract contract, const std::string& instanceName = "") { return std::static_pointer_cast<T>(GetInstance().GetPluginInternal(contract, instanceName)); } // Sets a custom plugin. // If a plugin with specified contract and optional instance name already exists, it will be replaced with specified instance. static void SetPlugin(std::shared_ptr<IPlayFabPlugin> plugin, const PlayFabPluginContract contract, const std::string& instanceName = ""); // Gets a plugin. // If a plugin with specified contract and optional instance name does not exist, it will create a new one. template <typename T> std::shared_ptr<T> GetPluginInstance(const PlayFabPluginContract contract, const std::string& instanceName = "") { return std::static_pointer_cast<T>(GetPluginInternal(contract, instanceName)); } // Sets a custom plugin. // If a plugin with specified contract and optional instance name already exists, it will be replaced with specified instance. void SetPluginInstance(std::shared_ptr<IPlayFabPlugin> plugin, const PlayFabPluginContract contract, const std::string& instanceName = ""); private: std::shared_ptr<IPlayFabPlugin> GetPluginInternal(const PlayFabPluginContract contract, const std::string& instanceName); void SetPluginInternal(std::shared_ptr<IPlayFabPlugin> plugin, const PlayFabPluginContract contract, const std::string& instanceName); std::shared_ptr<IPlayFabPlugin> CreatePlayFabSerializerPlugin(); std::shared_ptr<IPlayFabPlugin> CreatePlayFabTransportPlugin(); private: std::map<const std::pair<const PlayFabPluginContract, const std::string>, std::shared_ptr<IPlayFabPlugin>> plugins; }; }
0
0.814747
1
0.814747
game-dev
MEDIA
0.676068
game-dev
0.773869
1
0.773869
tgstation/tgstation
6,246
code/datums/storage/subtypes/pockets.dm
///Regular pockets /datum/storage/pockets max_slots = 2 max_specific_storage = WEIGHT_CLASS_SMALL max_total_storage = 50 do_rustle = FALSE /datum/storage/pockets/attempt_insert(obj/item/to_insert, mob/user, override, force, messages) . = ..() if(!.) return if(!silent || override) return if(quickdraw) to_chat(user, span_notice("You discreetly slip [to_insert] into [parent]. Right-click to remove it.")) else to_chat(user, span_notice("You discreetly slip [to_insert] into [parent].")) ///Small pockets /datum/storage/pockets/small max_slots = 1 attack_hand_interact = FALSE ///Tiny pockets /datum/storage/pockets/tiny max_slots = 1 max_specific_storage = WEIGHT_CLASS_TINY attack_hand_interact = FALSE ///Fedora pockets /datum/storage/pockets/small/fedora/New( atom/parent, max_slots, max_specific_storage, max_total_storage, ) . = ..() set_holdable(exception_hold_list = list( /obj/item/katana, /obj/item/toy/katana, /obj/item/nullrod/claymore/katana, /obj/item/energy_katana, /obj/item/gun/ballistic/automatic/tommygun, )) ///Fedora detective pockets /datum/storage/pockets/small/fedora/detective attack_hand_interact = TRUE // so the detectives would discover pockets in their hats click_alt_open = FALSE ///Chef hat pocket /datum/storage/pockets/chefhat attack_hand_interact = TRUE max_slots = 1 max_specific_storage = WEIGHT_CLASS_NORMAL /datum/storage/pockets/chefhat/New( atom/parent, max_slots, max_specific_storage, max_total_storage, ) . = ..() set_holdable(list( /obj/item/mob_holder, /obj/item/food/deadmouse )) /datum/storage/pockets/chefhat/can_insert(obj/item/to_insert, mob/user, messages, force) . = ..() if(ispickedupmob(to_insert)) var/obj/item/mob_holder/mausholder = to_insert if(locate(/mob/living/basic/mouse) in mausholder.contents) return return FALSE ///Shoe pockets /datum/storage/pockets/shoes max_slots = 2 attack_hand_interact = FALSE quickdraw = TRUE silent = TRUE /datum/storage/pockets/shoes/New( atom/parent, max_slots, max_specific_storage, max_total_storage, ) . = ..() set_holdable( can_hold_list = list( /obj/item/knife, /obj/item/spess_knife, /obj/item/switchblade, /obj/item/boxcutter, /obj/item/pen, /obj/item/flashlight/pen, //i mean cmon if a pen fits in there this does /obj/item/scalpel, /obj/item/dnainjector, /obj/item/reagent_containers/syringe, /obj/item/reagent_containers/applicator/pill, /obj/item/reagent_containers/hypospray/medipen, /obj/item/reagent_containers/dropper, /obj/item/implanter, /obj/item/screwdriver, /obj/item/weldingtool/mini, /obj/item/firing_pin, /obj/item/suppressor, /obj/item/ammo_box/magazine/m9mm, /obj/item/ammo_box/magazine/m10mm, /obj/item/ammo_box/magazine/m45, /obj/item/ammo_box/magazine/toy/pistol, /obj/item/ammo_casing, /obj/item/lipstick, /obj/item/cigarette, /obj/item/lighter, /obj/item/match, /obj/item/holochip, /obj/item/toy/crayon, /obj/item/reagent_containers/cup/glass/flask, ), cant_hold_list = list( /obj/item/screwdriver/power, /obj/item/ammo_casing/rocket, /obj/item/cigarette/pipe, /obj/item/toy/crayon/spraycan, ) ) ///Clown shoe pockets /datum/storage/pockets/shoes/clown/New( atom/parent, max_slots, max_specific_storage, max_total_storage, ) . = ..() set_holdable( can_hold_list = list( /obj/item/ammo_box/magazine/m10mm, /obj/item/ammo_box/magazine/m45, /obj/item/ammo_box/magazine/m9mm, /obj/item/ammo_casing, /obj/item/bikehorn, /obj/item/cigarette, /obj/item/dnainjector, /obj/item/firing_pin, /obj/item/holochip, /obj/item/implanter, /obj/item/knife, /obj/item/lighter, /obj/item/lipstick, /obj/item/match, /obj/item/pen, /obj/item/flashlight/pen, /obj/item/reagent_containers/cup/glass/flask, /obj/item/reagent_containers/dropper, /obj/item/reagent_containers/hypospray/medipen, /obj/item/reagent_containers/syringe, /obj/item/scalpel, /obj/item/screwdriver, /obj/item/spess_knife, /obj/item/suppressor, /obj/item/switchblade, /obj/item/toy/crayon, /obj/item/weldingtool/mini, ), cant_hold_list = list( /obj/item/ammo_casing/rocket, /obj/item/cigarette/pipe, /obj/item/screwdriver/power, /obj/item/toy/crayon/spraycan, ), ) ///Protector pocket /datum/storage/pockets/pocketprotector max_slots = 3 max_specific_storage = WEIGHT_CLASS_TINY /datum/storage/pockets/pocketprotector/New( atom/parent, max_slots, max_specific_storage, max_total_storage, ) . = ..() set_holdable(list( //Same items as a PDA /obj/item/pen, /obj/item/toy/crayon, /obj/item/lipstick, /obj/item/flashlight/pen, /obj/item/lipstick, )) ///Helmet pockets /datum/storage/pockets/helmet max_slots = 2 quickdraw = TRUE max_total_storage = 6 /datum/storage/pockets/helmet/New( atom/parent, max_slots, max_specific_storage, max_total_storage, ) . = ..() set_holdable(list( /obj/item/reagent_containers/cup/glass/bottle/vodka, /obj/item/reagent_containers/cup/glass/bottle/molotov, /obj/item/reagent_containers/cup/glass/drinkingglass, /obj/item/ammo_box/speedloader/strilka310 )) ///Void cloak pocket /datum/storage/pockets/void_cloak quickdraw = TRUE max_total_storage = 5 // 2 small items + 1 tiny item, or 1 normal item + 1 small item max_slots = 3 /datum/storage/pockets/void_cloak/New( atom/parent, max_slots, max_specific_storage, max_total_storage, ) . = ..() set_holdable( can_hold_list = list( /obj/item/ammo_box/speedloader/strilka310/lionhunter, /obj/item/bodypart, // Bodyparts are often used in rituals. They're also often normal sized, so you can only fit one. /obj/item/clothing/neck/eldritch_amulet, /obj/item/clothing/neck/heretic_focus, /obj/item/codex_cicatrix, /obj/item/eldritch_potion, /obj/item/food/grown/poppy, // Used to regain a Living Heart. /obj/item/melee/rune_carver, /obj/item/melee/sickly_blade, // Normal sized, so you can only fit one. /obj/item/organ, // Organs are also often used in rituals. /obj/item/reagent_containers/cup/beaker/eldritch, ), exception_hold_list = list( /obj/item/bodypart, /obj/item/melee/sickly_blade ) )
0
0.76568
1
0.76568
game-dev
MEDIA
0.997224
game-dev
0.583859
1
0.583859
CorgiTaco-MC/Enhanced-Celestials
4,277
Common/src/main/java/dev/corgitaco/enhancedcelestials/world/level/levelgen/structure/crater/CraterPiece.java
package dev.corgitaco.enhancedcelestials.world.level.levelgen.structure.crater; import dev.corgitaco.enhancedcelestials.util.FastNoise; import dev.corgitaco.enhancedcelestials.world.level.levelgen.structure.ECStructurePieceTypes; import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.util.RandomSource; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.StructureManager; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.StructurePiece; import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext; public class CraterPiece extends StructurePiece { protected static FastNoise fastNoise = Util.make(new FastNoise(20202), (noise) -> { noise.SetNoiseType(FastNoise.NoiseType.Simplex); noise.SetFrequency(0.004F); }); private final CraterStructure.PieceStructureInfo structureInfo; protected CraterPiece(CraterStructure.PieceStructureInfo structureInfo, int genDepth, BoundingBox boundingBox) { super(ECStructurePieceTypes.CRATER_PIECE.get(), genDepth, boundingBox); this.structureInfo = structureInfo; } public CraterPiece(StructurePieceSerializationContext context, CompoundTag tag) { super(ECStructurePieceTypes.CRATER_PIECE.get(), tag); this.structureInfo = CraterStructure.PieceStructureInfo.CODEC.decode(NbtOps.INSTANCE, tag.get("crater_info")).result().orElseThrow().getFirst(); } @Override protected void addAdditionalSaveData(StructurePieceSerializationContext context, CompoundTag compoundTag) { compoundTag.put("crater_info", CraterStructure.PieceStructureInfo.CODEC.encodeStart(NbtOps.INSTANCE, this.structureInfo).result().orElseThrow()); } @Override public void postProcess(WorldGenLevel worldGenLevel, StructureManager structureManager, ChunkGenerator chunkGenerator, RandomSource randomSource, BoundingBox boundingBox, ChunkPos chunkPos, BlockPos blockPos) { double radius = this.structureInfo.baseRadiusX(); double radiusZ = this.structureInfo.baseRadiusZ(); double yRadius = 40; BlockPos origin = this.structureInfo.origin(); int baseHeight = origin.getY(); BlockPos subtract = origin.offset((int) -radius, 0, (int) -radiusZ); int startX = subtract.getX(); int startZ = subtract.getZ(); BlockPos add = origin.offset((int) radius, 0,(int)radiusZ); int endX = add.getX(); int endZ = add.getZ(); BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos(); int minX = Math.max(startX - 10, chunkPos.getMinBlockX()); int maxX = Math.min(endX + 10, chunkPos.getMaxBlockX()); int minZ = Math.max(startZ - 10, chunkPos.getMinBlockZ()); int maxZ = Math.min(endZ + 10, chunkPos.getMaxBlockZ()); double xRadiusSquared = radius * radius; double yRadiusSquared = yRadius * yRadius; double zRadiusSquared = radiusZ * radiusZ; for (int worldX = minX; worldX <= maxX; worldX++) { int localX = worldX - origin.getX(); mutable.set(worldX, 0, 0); for (int worldZ = minZ; worldZ <= maxZ; worldZ++) { int localZ = worldZ - origin.getZ(); mutable.set(worldX, 0, worldZ); for (double y = -yRadius; y <= yRadius; y++) { mutable.set(worldX, baseHeight + y, worldZ); //Credits to Hex_26 for this equation!/ double equationResult = (localX * localX) / xRadiusSquared + (y * y) / yRadiusSquared + (localZ * localZ) / zRadiusSquared; double threshold = 1 + 0.7 * fastNoise.GetNoise(mutable.getX(), mutable.getZ()); if (equationResult >= 1) { continue; } worldGenLevel.setBlock(mutable, Blocks.AIR.defaultBlockState(), 3); } } } } }
0
0.861711
1
0.861711
game-dev
MEDIA
0.961784
game-dev
0.71848
1
0.71848
Planimeter/hl2sb-src
123,679
src/game/server/hl2/npc_playercompanion.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "npc_playercompanion.h" #include "combine_mine.h" #include "fire.h" #include "func_tank.h" #include "globalstate.h" #include "npcevent.h" #include "props.h" #include "BasePropDoor.h" #include "ai_hint.h" #include "ai_localnavigator.h" #include "ai_memory.h" #include "ai_pathfinder.h" #include "ai_route.h" #include "ai_senses.h" #include "ai_squad.h" #include "ai_squadslot.h" #include "ai_tacticalservices.h" #include "ai_interactions.h" #include "filesystem.h" #include "collisionutils.h" #include "grenade_frag.h" #include <KeyValues.h> #include "physics_npc_solver.h" ConVar ai_debug_readiness("ai_debug_readiness", "0" ); ConVar ai_use_readiness("ai_use_readiness", "1" ); // 0 = off, 1 = on, 2 = on for player squad only ConVar ai_readiness_decay( "ai_readiness_decay", "120" );// How many seconds it takes to relax completely ConVar ai_new_aiming( "ai_new_aiming", "1" ); #define GetReadinessUse() ai_use_readiness.GetInt() extern ConVar g_debug_transitions; #define PLAYERCOMPANION_TRANSITION_SEARCH_DISTANCE (100*12) int AE_COMPANION_PRODUCE_FLARE; int AE_COMPANION_LIGHT_FLARE; int AE_COMPANION_RELEASE_FLARE; #define MAX_TIME_BETWEEN_BARRELS_EXPLODING 5.0f #define MAX_TIME_BETWEEN_CONSECUTIVE_PLAYER_KILLS 3.0f //----------------------------------------------------------------------------- // An aimtarget becomes invalid if it gets this close //----------------------------------------------------------------------------- #define COMPANION_AIMTARGET_NEAREST 24.0f #define COMPANION_AIMTARGET_NEAREST_SQR 576.0f //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- BEGIN_DATADESC( CNPC_PlayerCompanion ) DEFINE_FIELD( m_bMovingAwayFromPlayer, FIELD_BOOLEAN ), DEFINE_EMBEDDED( m_SpeechWatch_PlayerLooking ), DEFINE_EMBEDDED( m_FakeOutMortarTimer ), // (recomputed) // m_bWeightPathsInCover // These are auto-saved by AI // DEFINE_FIELD( m_AssaultBehavior, CAI_AssaultBehavior ), // DEFINE_FIELD( m_FollowBehavior, CAI_FollowBehavior ), // DEFINE_FIELD( m_StandoffBehavior, CAI_StandoffBehavior ), // DEFINE_FIELD( m_LeadBehavior, CAI_LeadBehavior ), // DEFINE_FIELD( m_OperatorBehavior, FIELD_EMBEDDED ), // m_ActBusyBehavior // m_PassengerBehavior // m_FearBehavior DEFINE_INPUTFUNC( FIELD_VOID, "OutsideTransition", InputOutsideTransition ), DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessPanic", InputSetReadinessPanic ), DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessStealth", InputSetReadinessStealth ), DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessLow", InputSetReadinessLow ), DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessMedium", InputSetReadinessMedium ), DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessHigh", InputSetReadinessHigh ), DEFINE_INPUTFUNC( FIELD_FLOAT, "LockReadiness", InputLockReadiness ), //------------------------------------------------------------------------------ #ifdef HL2_EPISODIC DEFINE_FIELD( m_hFlare, FIELD_EHANDLE ), DEFINE_INPUTFUNC( FIELD_STRING, "EnterVehicle", InputEnterVehicle ), DEFINE_INPUTFUNC( FIELD_STRING, "EnterVehicleImmediately", InputEnterVehicleImmediately ), DEFINE_INPUTFUNC( FIELD_VOID, "ExitVehicle", InputExitVehicle ), DEFINE_INPUTFUNC( FIELD_VOID, "CancelEnterVehicle", InputCancelEnterVehicle ), #endif // HL2_EPISODIC //------------------------------------------------------------------------------ DEFINE_INPUTFUNC( FIELD_STRING, "GiveWeapon", InputGiveWeapon ), DEFINE_FIELD( m_flReadiness, FIELD_FLOAT ), DEFINE_FIELD( m_flReadinessSensitivity, FIELD_FLOAT ), DEFINE_FIELD( m_bReadinessCapable, FIELD_BOOLEAN ), DEFINE_FIELD( m_flReadinessLockedUntil, FIELD_TIME ), DEFINE_FIELD( m_fLastBarrelExploded, FIELD_TIME ), DEFINE_FIELD( m_iNumConsecutiveBarrelsExploded, FIELD_INTEGER ), DEFINE_FIELD( m_fLastPlayerKill, FIELD_TIME ), DEFINE_FIELD( m_iNumConsecutivePlayerKills, FIELD_INTEGER ), // m_flBoostSpeed (recomputed) DEFINE_EMBEDDED( m_AnnounceAttackTimer ), DEFINE_FIELD( m_hAimTarget, FIELD_EHANDLE ), DEFINE_KEYFIELD( m_bAlwaysTransition, FIELD_BOOLEAN, "AlwaysTransition" ), DEFINE_KEYFIELD( m_bDontPickupWeapons, FIELD_BOOLEAN, "DontPickupWeapons" ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableAlwaysTransition", InputEnableAlwaysTransition ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableAlwaysTransition", InputDisableAlwaysTransition ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableWeaponPickup", InputEnableWeaponPickup ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableWeaponPickup", InputDisableWeaponPickup ), #if HL2_EPISODIC DEFINE_INPUTFUNC( FIELD_VOID, "ClearAllOutputs", InputClearAllOuputs ), #endif DEFINE_OUTPUT( m_OnWeaponPickup, "OnWeaponPickup" ), END_DATADESC() //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CNPC_PlayerCompanion::eCoverType CNPC_PlayerCompanion::gm_fCoverSearchType; bool CNPC_PlayerCompanion::gm_bFindingCoverFromAllEnemies; string_t CNPC_PlayerCompanion::gm_iszMortarClassname; string_t CNPC_PlayerCompanion::gm_iszFloorTurretClassname; string_t CNPC_PlayerCompanion::gm_iszGroundTurretClassname; string_t CNPC_PlayerCompanion::gm_iszShotgunClassname; string_t CNPC_PlayerCompanion::gm_iszRollerMineClassname; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::CreateBehaviors() { #ifdef HL2_EPISODIC AddBehavior( &m_FearBehavior ); AddBehavior( &m_PassengerBehavior ); #endif // HL2_EPISODIC AddBehavior( &m_ActBusyBehavior ); #ifdef HL2_EPISODIC AddBehavior( &m_OperatorBehavior ); AddBehavior( &m_StandoffBehavior ); AddBehavior( &m_AssaultBehavior ); AddBehavior( &m_FollowBehavior ); AddBehavior( &m_LeadBehavior ); #else AddBehavior( &m_AssaultBehavior ); AddBehavior( &m_StandoffBehavior ); AddBehavior( &m_FollowBehavior ); AddBehavior( &m_LeadBehavior ); #endif//HL2_EPISODIC return BaseClass::CreateBehaviors(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::Precache() { gm_iszMortarClassname = AllocPooledString( "func_tankmortar" ); gm_iszFloorTurretClassname = AllocPooledString( "npc_turret_floor" ); gm_iszGroundTurretClassname = AllocPooledString( "npc_turret_ground" ); gm_iszShotgunClassname = AllocPooledString( "weapon_shotgun" ); gm_iszRollerMineClassname = AllocPooledString( "npc_rollermine" ); PrecacheModel( STRING( GetModelName() ) ); #ifdef HL2_EPISODIC // The flare we're able to pull out PrecacheModel( "models/props_junk/flare.mdl" ); #endif // HL2_EPISODIC BaseClass::Precache(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::Spawn() { SelectModel(); Precache(); SetModel( STRING( GetModelName() ) ); SetHullType(HULL_HUMAN); SetHullSizeNormal(); SetSolid( SOLID_BBOX ); AddSolidFlags( FSOLID_NOT_STANDABLE ); SetBloodColor( BLOOD_COLOR_RED ); m_flFieldOfView = 0.02; m_NPCState = NPC_STATE_NONE; CapabilitiesClear(); CapabilitiesAdd( bits_CAP_SQUAD ); if ( !HasSpawnFlags( SF_NPC_START_EFFICIENT ) ) { CapabilitiesAdd( bits_CAP_ANIMATEDFACE | bits_CAP_TURN_HEAD ); CapabilitiesAdd( bits_CAP_USE_WEAPONS | bits_CAP_AIM_GUN | bits_CAP_MOVE_SHOOT ); CapabilitiesAdd( bits_CAP_DUCK | bits_CAP_DOORS_GROUP ); CapabilitiesAdd( bits_CAP_USE_SHOT_REGULATOR ); } CapabilitiesAdd( bits_CAP_NO_HIT_PLAYER | bits_CAP_NO_HIT_SQUADMATES | bits_CAP_FRIENDLY_DMG_IMMUNE ); CapabilitiesAdd( bits_CAP_MOVE_GROUND ); SetMoveType( MOVETYPE_STEP ); m_HackedGunPos = Vector( 0, 0, 55 ); SetAimTarget(NULL); m_bReadinessCapable = IsReadinessCapable(); SetReadinessValue( 0.0f ); SetReadinessSensitivity( random->RandomFloat( 0.7, 1.3 ) ); m_flReadinessLockedUntil = 0.0f; m_AnnounceAttackTimer.Set( 10, 30 ); #if !defined( HL2SB ) && defined( HL2_EPISODIC ) // We strip this flag because it's been made obsolete by the StartScripting behavior if ( HasSpawnFlags( SF_NPC_ALTCOLLISION ) ) { Warning( "NPC %s using alternate collision! -- DISABLED\n", STRING( GetEntityName() ) ); RemoveSpawnFlags( SF_NPC_ALTCOLLISION ); } m_hFlare = NULL; #endif // !HL2SB && HL2_EPISODIC BaseClass::Spawn(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::Restore( IRestore &restore ) { int baseResult = BaseClass::Restore( restore ); if ( gpGlobals->eLoadType == MapLoad_Transition ) { m_StandoffBehavior.SetActive( false ); } #if !defined( HL2SB ) && defined( HL2_EPISODIC ) // We strip this flag because it's been made obsolete by the StartScripting behavior if ( HasSpawnFlags( SF_NPC_ALTCOLLISION ) ) { Warning( "NPC %s using alternate collision! -- DISABLED\n", STRING( GetEntityName() ) ); RemoveSpawnFlags( SF_NPC_ALTCOLLISION ); } #endif // !HL2SB && HL2_EPISODIC return baseResult; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::ObjectCaps() { int caps = UsableNPCObjectCaps( BaseClass::ObjectCaps() ); return caps; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ShouldAlwaysThink() { return ( BaseClass::ShouldAlwaysThink() || ( GetFollowBehavior().GetFollowTarget() && GetFollowBehavior().GetFollowTarget()->IsPlayer() ) ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- Disposition_t CNPC_PlayerCompanion::IRelationType( CBaseEntity *pTarget ) { if ( !pTarget ) return D_NU; Disposition_t baseRelationship = BaseClass::IRelationType( pTarget ); if ( baseRelationship != D_LI ) { if ( IsTurret( pTarget ) ) { // Citizens are afeared of turrets, so long as the turret // is active... that is, not classifying itself as CLASS_NONE if( pTarget->Classify() != CLASS_NONE ) { if( !hl2_episodic.GetBool() && IsSafeFromFloorTurret(GetAbsOrigin(), pTarget) ) { return D_NU; } return D_FR; } } else if ( baseRelationship == D_HT && pTarget->IsNPC() && ((CAI_BaseNPC *)pTarget)->GetActiveWeapon() && ((CAI_BaseNPC *)pTarget)->GetActiveWeapon()->ClassMatches( gm_iszShotgunClassname ) && ( !GetActiveWeapon() || !GetActiveWeapon()->ClassMatches( gm_iszShotgunClassname ) ) ) { if ( (pTarget->GetAbsOrigin() - GetAbsOrigin()).LengthSqr() < Square( 25 * 12 ) ) { // Ignore enemies on the floor above us if ( fabs(pTarget->GetAbsOrigin().z - GetAbsOrigin().z) < 100 ) return D_FR; } } } return baseRelationship; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsSilentSquadMember() const { if ( (const_cast<CNPC_PlayerCompanion *>(this))->Classify() == CLASS_PLAYER_ALLY_VITAL && m_pSquad && MAKE_STRING(m_pSquad->GetName()) == GetPlayerSquadName() ) { return true; } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::GatherConditions() { BaseClass::GatherConditions(); #ifndef HL2SB if ( AI_IsSinglePlayer() ) { #endif #ifdef HL2SB CBasePlayer *pPlayer = UTIL_GetNearestPlayer( GetAbsOrigin() ); #else CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); #endif if ( Classify() == CLASS_PLAYER_ALLY_VITAL ) { bool bInPlayerSquad = ( m_pSquad && MAKE_STRING(m_pSquad->GetName()) == GetPlayerSquadName() ); if ( bInPlayerSquad ) { if ( GetState() == NPC_STATE_SCRIPT || ( !HasCondition( COND_SEE_PLAYER ) && (GetAbsOrigin() - pPlayer->GetAbsOrigin()).LengthSqr() > Square(50 * 12) ) ) { RemoveFromSquad(); } } else if ( GetState() != NPC_STATE_SCRIPT ) { if ( HasCondition( COND_SEE_PLAYER ) && (GetAbsOrigin() - pPlayer->GetAbsOrigin()).LengthSqr() < Square(25 * 12) ) { if ( hl2_episodic.GetBool() ) { // Don't stomp our squad if we're in one if ( GetSquad() == NULL ) { AddToSquad( GetPlayerSquadName() ); } } else { AddToSquad( GetPlayerSquadName() ); } } } } m_flBoostSpeed = 0; if ( m_AnnounceAttackTimer.Expired() && ( GetLastEnemyTime() == 0.0 || gpGlobals->curtime - GetLastEnemyTime() > 20 ) ) { // Always delay when an encounter begins m_AnnounceAttackTimer.Set( 4, 8 ); } if ( GetFollowBehavior().GetFollowTarget() && ( GetFollowBehavior().GetFollowTarget()->IsPlayer() || GetCommandGoal() != vec3_invalid ) && GetFollowBehavior().IsMovingToFollowTarget() && GetFollowBehavior().GetGoalRange() > 0.1 && BaseClass::GetIdealSpeed() > 0.1 ) { Vector vPlayerToFollower = GetAbsOrigin() - pPlayer->GetAbsOrigin(); float dist = vPlayerToFollower.NormalizeInPlace(); bool bDoSpeedBoost = false; if ( !HasCondition( COND_IN_PVS ) ) bDoSpeedBoost = true; else if ( GetFollowBehavior().GetFollowTarget()->IsPlayer() ) { if ( dist > GetFollowBehavior().GetGoalRange() * 2 ) { float dot = vPlayerToFollower.Dot( pPlayer->EyeDirection3D() ); if ( dot < 0 ) { bDoSpeedBoost = true; } } } if ( bDoSpeedBoost ) { float lag = dist / GetFollowBehavior().GetGoalRange(); float mult; if ( lag > 10.0 ) mult = 2.0; else if ( lag > 5.0 ) mult = 1.5; else if ( lag > 3.0 ) mult = 1.25; else mult = 1.1; m_flBoostSpeed = pPlayer->GetSmoothedVelocity().Length(); if ( m_flBoostSpeed < BaseClass::GetIdealSpeed() ) m_flBoostSpeed = BaseClass::GetIdealSpeed(); m_flBoostSpeed *= mult; } } #ifndef HL2SB } #endif // Update our readiness if we're if ( IsReadinessCapable() ) { UpdateReadiness(); } PredictPlayerPush(); // Grovel through memories, don't forget enemies parented to func_tankmortar entities. // !!!LATER - this should really call out and ask if I want to forget the enemy in question. AIEnemiesIter_t iter; for( AI_EnemyInfo_t *pMemory = GetEnemies()->GetFirst(&iter); pMemory != NULL; pMemory = GetEnemies()->GetNext(&iter) ) { if ( IsMortar( pMemory->hEnemy ) || IsSniper( pMemory->hEnemy ) ) { pMemory->bUnforgettable = ( IRelationType( pMemory->hEnemy ) < D_LI ); pMemory->bEludedMe = false; } } if ( GetMotor()->IsDeceleratingToGoal() && IsCurTaskContinuousMove() && HasCondition( COND_PLAYER_PUSHING) && IsCurSchedule( SCHED_MOVE_AWAY ) ) { ClearSchedule( "Being pushed by player" ); } CBaseEntity *pEnemy = GetEnemy(); m_bWeightPathsInCover = false; if ( pEnemy ) { if ( IsMortar( pEnemy ) || IsSniper( pEnemy ) ) { m_bWeightPathsInCover = true; } } ClearCondition( COND_PC_SAFE_FROM_MORTAR ); if ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) ) { CSound *pSound = GetBestSound( SOUND_DANGER ); if ( pSound && (pSound->SoundType() & SOUND_CONTEXT_MORTAR) ) { float flDistSq = (pSound->GetSoundOrigin() - GetAbsOrigin() ).LengthSqr(); if ( flDistSq > Square( MORTAR_BLAST_RADIUS + GetHullWidth() * 2 ) ) SetCondition( COND_PC_SAFE_FROM_MORTAR ); } } // Handle speech AI. Don't do AI speech if we're in scripts unless permitted by the EnableSpeakWhileScripting input. if ( m_NPCState == NPC_STATE_IDLE || m_NPCState == NPC_STATE_ALERT || m_NPCState == NPC_STATE_COMBAT || ( ( m_NPCState == NPC_STATE_SCRIPT ) && CanSpeakWhileScripting() ) ) { DoCustomSpeechAI(); } #ifdef HL2SB if ( hl2_episodic.GetBool() && !GetEnemy() && HasCondition( COND_HEAR_PLAYER ) ) { Vector los = ( UTIL_GetNearestPlayer( GetAbsOrigin() )->EyePosition() - EyePosition() ); #else if ( AI_IsSinglePlayer() && hl2_episodic.GetBool() && !GetEnemy() && HasCondition( COND_HEAR_PLAYER ) ) { Vector los = ( UTIL_GetLocalPlayer()->EyePosition() - EyePosition() ); #endif los.z = 0; VectorNormalize( los ); if ( DotProduct( los, EyeDirection2D() ) > DOT_45DEGREE ) { ClearCondition( COND_HEAR_PLAYER ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::DoCustomSpeechAI( void ) { #ifdef HL2SB CBasePlayer *pPlayer = AI_GetNearestPlayer( GetAbsOrigin() ); #else CBasePlayer *pPlayer = AI_GetSinglePlayer(); #endif // Don't allow this when we're getting in the car #ifdef HL2_EPISODIC bool bPassengerInTransition = ( IsInAVehicle() && ( m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_ENTERING || m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_EXITING ) ); #else bool bPassengerInTransition = false; #endif Vector vecEyePosition = EyePosition(); if ( bPassengerInTransition == false && pPlayer && pPlayer->FInViewCone( vecEyePosition ) && pPlayer->FVisible( vecEyePosition ) ) { if ( m_SpeechWatch_PlayerLooking.Expired() ) { SpeakIfAllowed( TLK_LOOK ); m_SpeechWatch_PlayerLooking.Stop(); } } else { m_SpeechWatch_PlayerLooking.Start( 1.0f ); } // Mention the player is dead if ( HasCondition( COND_TALKER_PLAYER_DEAD ) ) { SpeakIfAllowed( TLK_PLDEAD ); } } //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::PredictPlayerPush() { #ifdef HL2SB CBasePlayer *pPlayer = AI_GetNearestPlayer( GetAbsOrigin() ); #else CBasePlayer *pPlayer = AI_GetSinglePlayer(); #endif if ( pPlayer && pPlayer->GetSmoothedVelocity().LengthSqr() >= Square(140)) { Vector predictedPosition = pPlayer->WorldSpaceCenter() + pPlayer->GetSmoothedVelocity() * .4; Vector delta = WorldSpaceCenter() - predictedPosition; if ( delta.z < GetHullHeight() * .5 && delta.Length2DSqr() < Square(GetHullWidth() * 1.414) ) TestPlayerPushing( pPlayer ); } } //----------------------------------------------------------------------------- // Purpose: Allows for modification of the interrupt mask for the current schedule. // In the most cases the base implementation should be called first. //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::BuildScheduleTestBits() { BaseClass::BuildScheduleTestBits(); // Always interrupt to get into the car SetCustomInterruptCondition( COND_PC_BECOMING_PASSENGER ); if ( IsCurSchedule(SCHED_RANGE_ATTACK1) ) { SetCustomInterruptCondition( COND_PLAYER_PUSHING ); } if ( ( ConditionInterruptsCurSchedule( COND_GIVE_WAY ) || IsCurSchedule(SCHED_HIDE_AND_RELOAD ) || IsCurSchedule(SCHED_RELOAD ) || IsCurSchedule(SCHED_STANDOFF ) || IsCurSchedule(SCHED_TAKE_COVER_FROM_ENEMY ) || IsCurSchedule(SCHED_COMBAT_FACE ) || IsCurSchedule(SCHED_ALERT_FACE ) || IsCurSchedule(SCHED_COMBAT_STAND ) || IsCurSchedule(SCHED_ALERT_FACE_BESTSOUND) || IsCurSchedule(SCHED_ALERT_STAND) ) ) { SetCustomInterruptCondition( COND_HEAR_MOVE_AWAY ); SetCustomInterruptCondition( COND_PLAYER_PUSHING ); SetCustomInterruptCondition( COND_PC_HURTBYFIRE ); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CSound *CNPC_PlayerCompanion::GetBestSound( int validTypes ) { AISoundIter_t iter; CSound *pCurrentSound = GetSenses()->GetFirstHeardSound( &iter ); while ( pCurrentSound ) { // the npc cares about this sound, and it's close enough to hear. if ( pCurrentSound->FIsSound() ) { if( pCurrentSound->SoundContext() & SOUND_CONTEXT_MORTAR ) { return pCurrentSound; } } pCurrentSound = GetSenses()->GetNextHeardSound( &iter ); } return BaseClass::GetBestSound( validTypes ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::QueryHearSound( CSound *pSound ) { if( !BaseClass::QueryHearSound(pSound) ) return false; switch( pSound->SoundTypeNoContext() ) { case SOUND_READINESS_LOW: SetReadinessLevel( AIRL_RELAXED, false, true ); return false; case SOUND_READINESS_MEDIUM: SetReadinessLevel( AIRL_STIMULATED, false, true ); return false; case SOUND_READINESS_HIGH: SetReadinessLevel( AIRL_AGITATED, false, true ); return false; default: return true; } } //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::QuerySeeEntity( CBaseEntity *pEntity, bool bOnlyHateOrFearIfNPC ) { CAI_BaseNPC *pOther = pEntity->MyNPCPointer(); if ( pOther && ( pOther->GetState() == NPC_STATE_ALERT || GetState() == NPC_STATE_ALERT || pOther->GetState() == NPC_STATE_COMBAT || GetState() == NPC_STATE_COMBAT ) && pOther->IsPlayerAlly() ) { return true; } return BaseClass::QuerySeeEntity( pEntity, bOnlyHateOrFearIfNPC ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ShouldIgnoreSound( CSound *pSound ) { if ( !BaseClass::ShouldIgnoreSound( pSound ) ) { if ( pSound->IsSoundType( SOUND_DANGER ) && !SoundIsVisible(pSound) ) return true; #ifdef HL2_EPISODIC // Ignore vehicle sounds when we're driving in them if ( pSound->m_hOwner && pSound->m_hOwner->GetServerVehicle() != NULL ) { if ( m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_INSIDE && m_PassengerBehavior.GetTargetVehicle() == pSound->m_hOwner->GetServerVehicle()->GetVehicleEnt() ) return true; } #endif // HL2_EPISODIC } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::SelectSchedule() { m_bMovingAwayFromPlayer = false; #ifdef HL2_EPISODIC // Always defer to passenger if it's running if ( ShouldDeferToPassengerBehavior() ) { DeferSchedulingToBehavior( &m_PassengerBehavior ); return BaseClass::SelectSchedule(); } #endif // HL2_EPISODIC if ( m_ActBusyBehavior.IsRunning() && m_ActBusyBehavior.NeedsToPlayExitAnim() ) { trace_t tr; Vector vUp = GetAbsOrigin(); vUp.z += .25; AI_TraceHull( GetAbsOrigin(), vUp, GetHullMins(), GetHullMaxs(), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr ); if ( tr.startsolid ) { if ( HasCondition( COND_HEAR_DANGER ) ) { m_ActBusyBehavior.StopBusying(); } DeferSchedulingToBehavior( &m_ActBusyBehavior ); return BaseClass::SelectSchedule(); } } int nSched = SelectFlinchSchedule(); if ( nSched != SCHED_NONE ) return nSched; int schedule = SelectScheduleDanger(); if ( schedule != SCHED_NONE ) return schedule; schedule = SelectSchedulePriorityAction(); if ( schedule != SCHED_NONE ) return schedule; if ( ShouldDeferToFollowBehavior() ) { DeferSchedulingToBehavior( &(GetFollowBehavior()) ); } else if ( !BehaviorSelectSchedule() ) { if ( m_NPCState == NPC_STATE_IDLE || m_NPCState == NPC_STATE_ALERT ) { schedule = SelectScheduleNonCombat(); if ( schedule != SCHED_NONE ) return schedule; } else if ( m_NPCState == NPC_STATE_COMBAT ) { schedule = SelectScheduleCombat(); if ( schedule != SCHED_NONE ) return schedule; } } return BaseClass::SelectSchedule(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::SelectScheduleDanger() { if( HasCondition( COND_HEAR_DANGER ) ) { CSound *pSound; pSound = GetBestSound( SOUND_DANGER ); ASSERT( pSound != NULL ); if ( pSound && (pSound->m_iType & SOUND_DANGER) ) { if ( !(pSound->SoundContext() & (SOUND_CONTEXT_MORTAR|SOUND_CONTEXT_FROM_SNIPER)) || IsOkToCombatSpeak() ) SpeakIfAllowed( TLK_DANGER ); if ( HasCondition( COND_PC_SAFE_FROM_MORTAR ) ) { // Just duck and cover if far away from the explosion, or in cover. return SCHED_COWER; } #if 1 else if( pSound && (pSound->m_iType & SOUND_CONTEXT_FROM_SNIPER) ) { return SCHED_COWER; } #endif return SCHED_TAKE_COVER_FROM_BEST_SOUND; } } if ( GetEnemy() && m_FakeOutMortarTimer.Expired() && GetFollowBehavior().GetFollowTarget() && IsMortar( GetEnemy() ) && assert_cast<CAI_BaseNPC *>(GetEnemy())->GetEnemy() == this && assert_cast<CAI_BaseNPC *>(GetEnemy())->FInViewCone( this ) && assert_cast<CAI_BaseNPC *>(GetEnemy())->FVisible( this ) ) { m_FakeOutMortarTimer.Set( 7 ); return SCHED_PC_FAKEOUT_MORTAR; } if ( HasCondition( COND_HEAR_MOVE_AWAY ) ) return SCHED_MOVE_AWAY; if ( HasCondition( COND_PC_HURTBYFIRE ) ) { ClearCondition( COND_PC_HURTBYFIRE ); return SCHED_MOVE_AWAY; } return SCHED_NONE; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::SelectSchedulePriorityAction() { if ( GetGroundEntity() && !IsInAScript() ) { if ( GetGroundEntity()->IsPlayer() ) { return SCHED_PC_GET_OFF_COMPANION; } if ( GetGroundEntity()->IsNPC() && IRelationType( GetGroundEntity() ) == D_LI && WorldSpaceCenter().z - GetGroundEntity()->WorldSpaceCenter().z > GetHullHeight() * .5 ) { return SCHED_PC_GET_OFF_COMPANION; } } int schedule = SelectSchedulePlayerPush(); if ( schedule != SCHED_NONE ) { if ( GetFollowBehavior().IsRunning() ) KeepRunningBehavior(); return schedule; } return SCHED_NONE; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::SelectSchedulePlayerPush() { if ( HasCondition( COND_PLAYER_PUSHING ) && !IsInAScript() && !IgnorePlayerPushing() ) { // Ignore move away before gordon becomes the man if ( GlobalEntity_GetState("gordon_precriminal") != GLOBAL_ON ) { m_bMovingAwayFromPlayer = true; return SCHED_MOVE_AWAY; } } return SCHED_NONE; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IgnorePlayerPushing( void ) { if ( hl2_episodic.GetBool() ) { // Ignore player pushes if we're leading him if ( m_LeadBehavior.IsRunning() && m_LeadBehavior.HasGoal() ) return true; if ( m_AssaultBehavior.IsRunning() && m_AssaultBehavior.OnStrictAssault() ) return true; } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::SelectScheduleCombat() { if ( CanReload() && (HasCondition ( COND_NO_PRIMARY_AMMO ) || HasCondition(COND_LOW_PRIMARY_AMMO)) ) { return SCHED_HIDE_AND_RELOAD; } return SCHED_NONE; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::CanReload( void ) { if ( IsRunningDynamicInteraction() ) return false; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ShouldDeferToFollowBehavior() { if ( !GetFollowBehavior().CanSelectSchedule() || !GetFollowBehavior().FarFromFollowTarget() ) return false; if ( m_StandoffBehavior.CanSelectSchedule() && !m_StandoffBehavior.IsBehindBattleLines( GetFollowBehavior().GetFollowTarget()->GetAbsOrigin() ) ) return false; if ( HasCondition(COND_BETTER_WEAPON_AVAILABLE) && !GetActiveWeapon() ) { // Unarmed allies should arm themselves as soon as the opportunity presents itself. return false; } // Even though assault and act busy are placed ahead of the follow behavior in precedence, the below // code is necessary because we call ShouldDeferToFollowBehavior BEFORE we call the generic // BehaviorSelectSchedule, which tries the behaviors in priority order. if ( m_AssaultBehavior.CanSelectSchedule() && hl2_episodic.GetBool() ) { return false; } if ( hl2_episodic.GetBool() ) { if ( m_ActBusyBehavior.CanSelectSchedule() && m_ActBusyBehavior.IsCombatActBusy() ) { return false; } } return true; } //----------------------------------------------------------------------------- // CalcReasonableFacing() is asking us if there's any reason why we wouldn't // want to look in this direction. // // Right now this is used to help prevent citizens aiming their guns at each other //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsValidReasonableFacing( const Vector &vecSightDir, float sightDist ) { if( !GetActiveWeapon() ) { // If I'm not armed, it doesn't matter if I'm looking at another citizen. return true; } if( ai_new_aiming.GetBool() ) { Vector vecEyePositionCentered = GetAbsOrigin(); vecEyePositionCentered.z = EyePosition().z; if( IsSquadmateInSpread(vecEyePositionCentered, vecEyePositionCentered + vecSightDir * 240.0f, VECTOR_CONE_15DEGREES.x, 12.0f * 3.0f) ) { return false; } } return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::TranslateSchedule( int scheduleType ) { switch( scheduleType ) { case SCHED_IDLE_STAND: case SCHED_ALERT_STAND: if( GetActiveWeapon() ) { // Everyone with less than half a clip takes turns reloading when not fighting. CBaseCombatWeapon *pWeapon = GetActiveWeapon(); if( CanReload() && pWeapon->UsesClipsForAmmo1() && pWeapon->Clip1() < ( pWeapon->GetMaxClip1() * .5 ) && OccupyStrategySlot( SQUAD_SLOT_EXCLUSIVE_RELOAD ) ) { #ifdef HL2SB CBasePlayer *pPlayer = UTIL_GetNearestPlayer( GetAbsOrigin() ); #else if ( AI_IsSinglePlayer() ) { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); #endif pWeapon = pPlayer->GetActiveWeapon(); if( pWeapon && pWeapon->UsesClipsForAmmo1() && pWeapon->Clip1() < ( pWeapon->GetMaxClip1() * .75 ) && pPlayer->GetAmmoCount( pWeapon->GetPrimaryAmmoType() ) ) { SpeakIfAllowed( TLK_PLRELOAD ); } #ifndef HL2SB } #endif return SCHED_RELOAD; } } break; case SCHED_COWER: return SCHED_PC_COWER; case SCHED_TAKE_COVER_FROM_BEST_SOUND: { CSound *pSound = GetBestSound(SOUND_DANGER); if( pSound && pSound->m_hOwner ) { if( pSound->m_hOwner->IsNPC() && FClassnameIs( pSound->m_hOwner, "npc_zombine" ) ) { // Run fully away from a Zombine with a grenade. return SCHED_PC_TAKE_COVER_FROM_BEST_SOUND; } } return SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND; } case SCHED_FLEE_FROM_BEST_SOUND: return SCHED_PC_FLEE_FROM_BEST_SOUND; case SCHED_ESTABLISH_LINE_OF_FIRE: case SCHED_MOVE_TO_WEAPON_RANGE: if ( IsMortar( GetEnemy() ) ) return SCHED_TAKE_COVER_FROM_ENEMY; break; case SCHED_CHASE_ENEMY: if ( IsMortar( GetEnemy() ) ) return SCHED_TAKE_COVER_FROM_ENEMY; if ( GetEnemy() && FClassnameIs( GetEnemy(), "npc_combinegunship" ) ) return SCHED_ESTABLISH_LINE_OF_FIRE; break; case SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK: // If we're fighting a gunship, try again if ( GetEnemy() && FClassnameIs( GetEnemy(), "npc_combinegunship" ) ) return SCHED_ESTABLISH_LINE_OF_FIRE; break; case SCHED_RANGE_ATTACK1: if ( IsMortar( GetEnemy() ) ) return SCHED_TAKE_COVER_FROM_ENEMY; if ( GetShotRegulator()->IsInRestInterval() ) return SCHED_STANDOFF; if( !OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) ) return SCHED_STANDOFF; break; case SCHED_FAIL_TAKE_COVER: if ( IsEnemyTurret() ) { return SCHED_PC_FAIL_TAKE_COVER_TURRET; } break; case SCHED_RUN_FROM_ENEMY_FALLBACK: { if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) ) { return SCHED_RANGE_ATTACK1; } break; } } return BaseClass::TranslateSchedule( scheduleType ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::StartTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_SOUND_WAKE: LocateEnemySound(); SetWait( 0.5 ); break; case TASK_ANNOUNCE_ATTACK: { if ( GetActiveWeapon() && m_AnnounceAttackTimer.Expired() ) { if ( SpeakIfAllowed( TLK_ATTACKING, UTIL_VarArgs("attacking_with_weapon:%s", GetActiveWeapon()->GetClassname()) ) ) { m_AnnounceAttackTimer.Set( 10, 30 ); } } BaseClass::StartTask( pTask ); break; } case TASK_PC_WAITOUT_MORTAR: if ( HasCondition( COND_NO_HEAR_DANGER ) ) TaskComplete(); break; case TASK_MOVE_AWAY_PATH: { if ( m_bMovingAwayFromPlayer ) SpeakIfAllowed( TLK_PLPUSH ); BaseClass::StartTask( pTask ); } break; case TASK_PC_GET_PATH_OFF_COMPANION: { Assert( ( GetGroundEntity() && ( GetGroundEntity()->IsPlayer() || ( GetGroundEntity()->IsNPC() && IRelationType( GetGroundEntity() ) == D_LI ) ) ) ); GetNavigator()->SetAllowBigStep( GetGroundEntity() ); ChainStartTask( TASK_MOVE_AWAY_PATH, 48 ); /* trace_t tr; UTIL_TraceHull( GetAbsOrigin(), GetAbsOrigin(), GetHullMins(), GetHullMaxs(), MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr ); if ( tr.startsolid && tr.m_pEnt == GetGroundEntity() ) { // Allow us to move through the entity for a short time NPCPhysics_CreateSolver( this, GetGroundEntity(), true, 2.0f ); } */ } break; default: BaseClass::StartTask( pTask ); break; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::RunTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_SOUND_WAKE: if( IsWaitFinished() ) { TaskComplete(); } break; case TASK_PC_WAITOUT_MORTAR: { if ( HasCondition( COND_NO_HEAR_DANGER ) ) TaskComplete(); } break; case TASK_MOVE_AWAY_PATH: { BaseClass::RunTask( pTask ); if ( GetNavigator()->IsGoalActive() && !GetEnemy() ) { AddFacingTarget( EyePosition() + BodyDirection2D() * 240, 1.0, 2.0 ); } } break; case TASK_PC_GET_PATH_OFF_COMPANION: { #ifdef HL2SB GetNavigator()->SetAllowBigStep( UTIL_GetNearestPlayer( GetAbsOrigin() ) ); #else if ( AI_IsSinglePlayer() ) { GetNavigator()->SetAllowBigStep( UTIL_GetLocalPlayer() ); } #endif ChainRunTask( TASK_MOVE_AWAY_PATH, 48 ); } break; default: BaseClass::RunTask( pTask ); break; } } //----------------------------------------------------------------------------- // Parses this NPC's activity remap from the actremap.txt file //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::PrepareReadinessRemap( void ) { CUtlVector< CActivityRemap > entries; UTIL_LoadActivityRemapFile( "scripts/actremap.txt", "npc_playercompanion", entries ); for ( int i = 0; i < entries.Count(); i++ ) { CCompanionActivityRemap ActRemap; Q_memcpy( &ActRemap, &entries[i], sizeof( CActivityRemap ) ); KeyValues *pExtraBlock = ActRemap.GetExtraKeyValueBlock(); if ( pExtraBlock ) { KeyValues *pKey = pExtraBlock->GetFirstSubKey(); while ( pKey ) { const char *pKeyName = pKey->GetName(); const char *pKeyValue = pKey->GetString(); if ( !stricmp( pKeyName, "readiness" ) ) { ActRemap.m_fUsageBits |= bits_REMAP_READINESS; if ( !stricmp( pKeyValue, "AIRL_PANIC" ) ) { ActRemap.m_readiness = AIRL_PANIC; } else if ( !stricmp( pKeyValue, "AIRL_STEALTH" ) ) { ActRemap.m_readiness = AIRL_STEALTH; } else if ( !stricmp( pKeyValue, "AIRL_RELAXED" ) ) { ActRemap.m_readiness = AIRL_RELAXED; } else if ( !stricmp( pKeyValue, "AIRL_STIMULATED" ) ) { ActRemap.m_readiness = AIRL_STIMULATED; } else if ( !stricmp( pKeyValue, "AIRL_AGITATED" ) ) { ActRemap.m_readiness = AIRL_AGITATED; } } else if ( !stricmp( pKeyName, "aiming" ) ) { ActRemap.m_fUsageBits |= bits_REMAP_AIMING; if ( !stricmp( pKeyValue, "TRS_NONE" ) ) { // This is the new way to say that we don't care, the tri-state was abandoned (jdw) ActRemap.m_fUsageBits &= ~bits_REMAP_AIMING; } else if ( !stricmp( pKeyValue, "TRS_FALSE" ) || !stricmp( pKeyValue, "FALSE" ) ) { ActRemap.m_bAiming = false; } else if ( !stricmp( pKeyValue, "TRS_TRUE" ) || !stricmp( pKeyValue, "TRUE" ) ) { ActRemap.m_bAiming = true; } } else if ( !stricmp( pKeyName, "weaponrequired" ) ) { ActRemap.m_fUsageBits |= bits_REMAP_WEAPON_REQUIRED; if ( !stricmp( pKeyValue, "TRUE" ) ) { ActRemap.m_bWeaponRequired = true; } else if ( !stricmp( pKeyValue, "FALSE" ) ) { ActRemap.m_bWeaponRequired = false; } } else if ( !stricmp( pKeyName, "invehicle" ) ) { ActRemap.m_fUsageBits |= bits_REMAP_IN_VEHICLE; if ( !stricmp( pKeyValue, "TRUE" ) ) { ActRemap.m_bInVehicle = true; } else if ( !stricmp( pKeyValue, "FALSE" ) ) { ActRemap.m_bInVehicle = false; } } pKey = pKey->GetNextKey(); } } const char *pActName = ActivityList_NameForIndex( (int)ActRemap.mappedActivity ); if ( GetActivityID( pActName ) == ACT_INVALID ) { AddActivityToSR( pActName, (int)ActRemap.mappedActivity ); } m_activityMappings.AddToTail( ActRemap ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::Activate( void ) { BaseClass::Activate(); PrepareReadinessRemap(); } //----------------------------------------------------------------------------- // Purpose: Translate an activity given a list of criteria //----------------------------------------------------------------------------- Activity CNPC_PlayerCompanion::TranslateActivityReadiness( Activity activity ) { // If we're in an actbusy, we don't want to mess with this if ( m_ActBusyBehavior.IsActive() ) return activity; if ( m_bReadinessCapable && ( GetReadinessUse() == AIRU_ALWAYS || ( GetReadinessUse() == AIRU_ONLY_PLAYER_SQUADMATES && (IsInPlayerSquad()||Classify()==CLASS_PLAYER_ALLY_VITAL) ) ) ) { bool bShouldAim = ShouldBeAiming(); for ( int i = 0; i < m_activityMappings.Count(); i++ ) { // Get our activity remap CCompanionActivityRemap actremap = m_activityMappings[i]; // Activity must match if ( activity != actremap.activity ) continue; // Readiness must match if ( ( actremap.m_fUsageBits & bits_REMAP_READINESS ) && GetReadinessLevel() != actremap.m_readiness ) continue; // Deal with weapon state if ( ( actremap.m_fUsageBits & bits_REMAP_WEAPON_REQUIRED ) && actremap.m_bWeaponRequired ) { // Must have a weapon if ( GetActiveWeapon() == NULL ) continue; // Must either not care about aiming, or agree on aiming if ( actremap.m_fUsageBits & bits_REMAP_AIMING ) { if ( bShouldAim && actremap.m_bAiming == false ) continue; if ( bShouldAim == false && actremap.m_bAiming ) continue; } } // Must care about vehicle status if ( actremap.m_fUsageBits & bits_REMAP_IN_VEHICLE ) { // Deal with the two vehicle states if ( actremap.m_bInVehicle && IsInAVehicle() == false ) continue; if ( actremap.m_bInVehicle == false && IsInAVehicle() ) continue; } // We've successfully passed all criteria for remapping this return actremap.mappedActivity; } } return activity; } //----------------------------------------------------------------------------- // Purpose: Override base class activiites //----------------------------------------------------------------------------- Activity CNPC_PlayerCompanion::NPC_TranslateActivity( Activity activity ) { if ( activity == ACT_COWER ) return ACT_COVER_LOW; if ( activity == ACT_RUN && ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) || IsCurSchedule( SCHED_FLEE_FROM_BEST_SOUND ) ) ) { if ( random->RandomInt( 0, 1 ) && HaveSequenceForActivity( ACT_RUN_PROTECTED ) ) activity = ACT_RUN_PROTECTED; } activity = BaseClass::NPC_TranslateActivity( activity ); if ( activity == ACT_IDLE ) { if ( (m_NPCState == NPC_STATE_COMBAT || m_NPCState == NPC_STATE_ALERT) && gpGlobals->curtime - m_flLastAttackTime < 3) { activity = ACT_IDLE_ANGRY; } } return TranslateActivityReadiness( activity ); } //------------------------------------------------------------------------------ // Purpose: Handle animation events //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::HandleAnimEvent( animevent_t *pEvent ) { #ifdef HL2_EPISODIC // Create a flare and parent to our hand if ( pEvent->event == AE_COMPANION_PRODUCE_FLARE ) { m_hFlare = static_cast<CPhysicsProp *>(CreateEntityByName( "prop_physics" )); if ( m_hFlare != NULL ) { // Set the model m_hFlare->SetModel( "models/props_junk/flare.mdl" ); // Set the parent attachment m_hFlare->SetParent( this ); m_hFlare->SetParentAttachment( "SetParentAttachment", pEvent->options, false ); } return; } // Start the flare up with proper fanfare if ( pEvent->event == AE_COMPANION_LIGHT_FLARE ) { if ( m_hFlare != NULL ) { m_hFlare->CreateFlare( 5*60.0f ); } return; } // Drop the flare to the ground if ( pEvent->event == AE_COMPANION_RELEASE_FLARE ) { // Detach m_hFlare->SetParent( NULL ); m_hFlare->Spawn(); m_hFlare->RemoveInteraction( PROPINTER_PHYSGUN_CREATE_FLARE ); // Disable collisions between the NPC and the flare PhysDisableEntityCollisions( this, m_hFlare ); // TODO: Find the velocity of the attachment point, at this time, in the animation cycle // Construct a toss velocity Vector vecToss; AngleVectors( GetAbsAngles(), &vecToss ); VectorNormalize( vecToss ); vecToss *= random->RandomFloat( 64.0f, 72.0f ); vecToss[2] += 64.0f; // Throw it IPhysicsObject *pObj = m_hFlare->VPhysicsGetObject(); pObj->ApplyForceCenter( vecToss ); // Forget about the flare at this point m_hFlare = NULL; return; } #endif // HL2_EPISODIC switch( pEvent->event ) { case EVENT_WEAPON_RELOAD: if ( GetActiveWeapon() ) { GetActiveWeapon()->WeaponSound( RELOAD_NPC ); GetActiveWeapon()->m_iClip1 = GetActiveWeapon()->GetMaxClip1(); ClearCondition(COND_LOW_PRIMARY_AMMO); ClearCondition(COND_NO_PRIMARY_AMMO); ClearCondition(COND_NO_SECONDARY_AMMO); } break; default: BaseClass::HandleAnimEvent( pEvent ); break; } } //----------------------------------------------------------------------------- // Purpose: This is a generic function (to be implemented by sub-classes) to // handle specific interactions between different types of characters // (For example the barnacle grabbing an NPC) // Input : Constant for the type of interaction // Output : true - if sub-class has a response for the interaction // false - if sub-class has no response //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt) { if (interactionType == g_interactionHitByPlayerThrownPhysObj ) { if ( IsOkToSpeakInResponseToPlayer() ) { Speak( TLK_PLYR_PHYSATK ); } return true; } return BaseClass::HandleInteraction( interactionType, data, sourceEnt ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ int CNPC_PlayerCompanion::GetSoundInterests() { return SOUND_WORLD | SOUND_COMBAT | SOUND_PLAYER | SOUND_DANGER | SOUND_BULLET_IMPACT | SOUND_MOVE_AWAY | SOUND_READINESS_LOW | SOUND_READINESS_MEDIUM | SOUND_READINESS_HIGH; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::Touch( CBaseEntity *pOther ) { BaseClass::Touch( pOther ); // Did the player touch me? if ( pOther->IsPlayer() || ( pOther->VPhysicsGetObject() && (pOther->VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_PLAYER_HELD ) ) ) { // Ignore if pissed at player if ( m_afMemory & bits_MEMORY_PROVOKED ) return; #ifdef HL2SB TestPlayerPushing( ( pOther->IsPlayer() ) ? pOther : AI_GetNearestPlayer( GetAbsOrigin() ) ); #else TestPlayerPushing( ( pOther->IsPlayer() ) ? pOther : AI_GetSinglePlayer() ); #endif } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::ModifyOrAppendCriteria( AI_CriteriaSet& set ) { BaseClass::ModifyOrAppendCriteria( set ); if ( GetEnemy() && IsMortar( GetEnemy() ) ) { set.RemoveCriteria( "enemy" ); set.AppendCriteria( "enemy", STRING(gm_iszMortarClassname) ); } if ( HasCondition( COND_PC_HURTBYFIRE ) ) { set.AppendCriteria( "hurt_by_fire", "1" ); } if ( m_bReadinessCapable ) { switch( GetReadinessLevel() ) { case AIRL_PANIC: set.AppendCriteria( "readiness", "panic" ); break; case AIRL_STEALTH: set.AppendCriteria( "readiness", "stealth" ); break; case AIRL_RELAXED: set.AppendCriteria( "readiness", "relaxed" ); break; case AIRL_STIMULATED: set.AppendCriteria( "readiness", "stimulated" ); break; case AIRL_AGITATED: set.AppendCriteria( "readiness", "agitated" ); break; } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsReadinessCapable() { if ( GlobalEntity_GetState("gordon_precriminal") == GLOBAL_ON ) return false; #ifndef HL2_EPISODIC // Allow episodic companions to use readiness even if unarmed. This allows for the panicked // citizens in ep1_c17_05 (sjb) if( !GetActiveWeapon() ) return false; #endif if( GetActiveWeapon() && LookupActivity("ACT_IDLE_AIM_RIFLE_STIMULATED") == ACT_INVALID ) return false; if( GetActiveWeapon() && FClassnameIs( GetActiveWeapon(), "weapon_rpg" ) ) return false; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::AddReadiness( float flAdd, bool bOverrideLock ) { if( IsReadinessLocked() && !bOverrideLock ) return; SetReadinessValue( GetReadinessValue() + flAdd ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::SubtractReadiness( float flSub, bool bOverrideLock ) { if( IsReadinessLocked() && !bOverrideLock ) return; // Prevent readiness from going below 0 (below 0 is only for scripted states) SetReadinessValue( MAX(GetReadinessValue() - flSub, 0) ); } //----------------------------------------------------------------------------- // This method returns false if the NPC is not allowed to change readiness at this point. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::AllowReadinessValueChange( void ) { if ( GetIdealActivity() == ACT_IDLE || GetIdealActivity() == ACT_WALK || GetIdealActivity() == ACT_RUN ) return true; if ( HasActiveLayer() == true ) return false; return false; } //----------------------------------------------------------------------------- // NOTE: This function ignores the lock. Use the interface functions. //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::SetReadinessValue( float flSet ) { if ( AllowReadinessValueChange() == false ) return; int priorReadiness = GetReadinessLevel(); flSet = MIN( 1.0f, flSet ); flSet = MAX( READINESS_MIN_VALUE, flSet ); m_flReadiness = flSet; if( GetReadinessLevel() != priorReadiness ) { // We've been bumped up into a different readiness level. // Interrupt IDLE schedules (if we're playing one) so that // we can pick the proper animation. SetCondition( COND_IDLE_INTERRUPT ); // Force us to recalculate our animation. If we don't do this, // our translated activity may change, but not our root activity, // and then we won't actually visually change anims. ResetActivity(); //Force the NPC to recalculate it's arrival sequence since it'll most likely be wrong now that we changed readiness level. GetNavigator()->SetArrivalSequence( ACT_INVALID ); ReadinessLevelChanged( priorReadiness ); } } //----------------------------------------------------------------------------- // if bOverrideLock, you'll change the readiness level even if we're within // a time period during which someone else has locked the level. // // if bSlam, you'll allow the readiness level to be set lower than current. //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::SetReadinessLevel( int iLevel, bool bOverrideLock, bool bSlam ) { if( IsReadinessLocked() && !bOverrideLock ) return; switch( iLevel ) { case AIRL_PANIC: if( bSlam ) SetReadinessValue( READINESS_MODE_PANIC ); break; case AIRL_STEALTH: if( bSlam ) SetReadinessValue( READINESS_MODE_STEALTH ); break; case AIRL_RELAXED: if( bSlam || GetReadinessValue() < READINESS_VALUE_RELAXED ) SetReadinessValue( READINESS_VALUE_RELAXED ); break; case AIRL_STIMULATED: if( bSlam || GetReadinessValue() < READINESS_VALUE_STIMULATED ) SetReadinessValue( READINESS_VALUE_STIMULATED ); break; case AIRL_AGITATED: if( bSlam || GetReadinessValue() < READINESS_VALUE_AGITATED ) SetReadinessValue( READINESS_VALUE_AGITATED ); break; default: DevMsg("ERROR: Bad readiness level\n"); break; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::GetReadinessLevel() { if ( m_bReadinessCapable == false ) return AIRL_RELAXED; if( m_flReadiness == READINESS_MODE_PANIC ) { return AIRL_PANIC; } if( m_flReadiness == READINESS_MODE_STEALTH ) { return AIRL_STEALTH; } if( m_flReadiness <= READINESS_VALUE_RELAXED ) { return AIRL_RELAXED; } if( m_flReadiness <= READINESS_VALUE_STIMULATED ) { return AIRL_STIMULATED; } return AIRL_AGITATED; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::UpdateReadiness() { // Only update readiness if it's not in a scripted state if ( !IsInScriptedReadinessState() ) { if( HasCondition(COND_HEAR_COMBAT) || HasCondition(COND_HEAR_BULLET_IMPACT) ) SetReadinessLevel( AIRL_STIMULATED, false, false ); if( HasCondition(COND_HEAR_DANGER) || HasCondition(COND_SEE_ENEMY) ) SetReadinessLevel( AIRL_AGITATED, false, false ); if( m_flReadiness > 0.0f && GetReadinessDecay() > 0 ) { // Decay. SubtractReadiness( ( 0.1 * (1.0f/GetReadinessDecay())) * m_flReadinessSensitivity ); } } if( ai_debug_readiness.GetBool() && AI_IsSinglePlayer() ) { // Draw the readiness-o-meter Vector vecSpot; Vector vecOffset( 0, 0, 12 ); const float BARLENGTH = 12.0f; const float GRADLENGTH = 4.0f; Vector right; UTIL_PlayerByIndex( 1 )->GetVectors( NULL, &right, NULL ); if ( IsInScriptedReadinessState() ) { // Just print the name of the scripted state vecSpot = EyePosition() + vecOffset; if( GetReadinessLevel() == AIRL_STEALTH ) { NDebugOverlay::Text( vecSpot, "Stealth", true, 0.1 ); } else if( GetReadinessLevel() == AIRL_PANIC ) { NDebugOverlay::Text( vecSpot, "Panic", true, 0.1 ); } else { NDebugOverlay::Text( vecSpot, "Unspecified", true, 0.1 ); } } else { vecSpot = EyePosition() + vecOffset; NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 255, 255, 255, false, 0.1 ); vecSpot = EyePosition() + vecOffset + Vector( 0, 0, BARLENGTH * READINESS_VALUE_RELAXED ); NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 0, 255, 0, false, 0.1 ); vecSpot = EyePosition() + vecOffset + Vector( 0, 0, BARLENGTH * READINESS_VALUE_STIMULATED ); NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 255, 255, 0, false, 0.1 ); vecSpot = EyePosition() + vecOffset + Vector( 0, 0, BARLENGTH * READINESS_VALUE_AGITATED ); NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 255, 0, 0, false, 0.1 ); vecSpot = EyePosition() + vecOffset; NDebugOverlay::Line( vecSpot, vecSpot + Vector( 0, 0, BARLENGTH * GetReadinessValue() ), 255, 255, 0, false, 0.1 ); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- float CNPC_PlayerCompanion::GetReadinessDecay() { return ai_readiness_decay.GetFloat(); } //----------------------------------------------------------------------------- // Passing NULL to clear the aim target is acceptible. //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::SetAimTarget( CBaseEntity *pTarget ) { if( pTarget != NULL && IsAllowedToAim() ) { m_hAimTarget = pTarget; } else { m_hAimTarget = NULL; } Activity NewActivity = NPC_TranslateActivity(GetActivity()); //Don't set the ideal activity to an activity that might not be there. if ( SelectWeightedSequence( NewActivity ) == ACT_INVALID ) return; if (NewActivity != GetActivity() ) { SetIdealActivity( NewActivity ); } #if 0 if( m_hAimTarget ) { Msg("New Aim Target: %s\n", m_hAimTarget->GetClassname() ); NDebugOverlay::Line(EyePosition(), m_hAimTarget->WorldSpaceCenter(), 255, 255, 0, false, 0.1 ); } #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::StopAiming( char *pszReason ) { #if 0 if( pszReason ) { Msg("Stopped aiming because %s\n", pszReason ); } #endif SetAimTarget(NULL); Activity NewActivity = NPC_TranslateActivity(GetActivity()); if (NewActivity != GetActivity()) { SetIdealActivity( NewActivity ); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #define COMPANION_MAX_LOOK_TIME 3.0f #define COMPANION_MIN_LOOK_TIME 1.0f #define COMPANION_MAX_TACTICAL_TARGET_DIST 1800.0f // 150 feet bool CNPC_PlayerCompanion::PickTacticalLookTarget( AILookTargetArgs_t *pArgs ) { if( HasCondition( COND_SEE_ENEMY ) ) { // Don't bother. We're dealing with our enemy. return false; } float flMinLookTime; float flMaxLookTime; // Excited companions will look at each target only briefly and then find something else to look at. flMinLookTime = COMPANION_MIN_LOOK_TIME + ((COMPANION_MAX_LOOK_TIME-COMPANION_MIN_LOOK_TIME) * (1.0f - GetReadinessValue()) ); switch( GetReadinessLevel() ) { case AIRL_RELAXED: // Linger on targets, look at them for quite a while. flMinLookTime = COMPANION_MAX_LOOK_TIME + random->RandomFloat( 0.0f, 2.0f ); break; case AIRL_STIMULATED: // Look around a little quicker. flMinLookTime = COMPANION_MIN_LOOK_TIME + random->RandomFloat( 0.0f, COMPANION_MAX_LOOK_TIME - 1.0f ); break; case AIRL_AGITATED: // Look around very quickly flMinLookTime = COMPANION_MIN_LOOK_TIME; break; } flMaxLookTime = flMinLookTime + random->RandomFloat( 0.0f, 0.5f ); pArgs->flDuration = random->RandomFloat( flMinLookTime, flMaxLookTime ); if( HasCondition(COND_SEE_PLAYER) && hl2_episodic.GetBool() ) { // 1/3rd chance to authoritatively look at player if( random->RandomInt( 0, 2 ) == 0 ) { #ifdef HL2SB pArgs->hTarget = AI_GetNearestPlayer( GetAbsOrigin() ); #else pArgs->hTarget = AI_GetSinglePlayer(); #endif return true; } } // Use hint nodes CAI_Hint *pHint; CHintCriteria hintCriteria; hintCriteria.AddHintType( HINT_WORLD_VISUALLY_INTERESTING ); hintCriteria.AddHintType( HINT_WORLD_VISUALLY_INTERESTING_DONT_AIM ); hintCriteria.AddHintType( HINT_WORLD_VISUALLY_INTERESTING_STEALTH ); hintCriteria.SetFlag( bits_HINT_NODE_VISIBLE | bits_HINT_NODE_IN_VIEWCONE | bits_HINT_NPC_IN_NODE_FOV ); hintCriteria.AddIncludePosition( GetAbsOrigin(), COMPANION_MAX_TACTICAL_TARGET_DIST ); { AI_PROFILE_SCOPE( CNPC_PlayerCompanion_FindHint_PickTacticalLookTarget ); pHint = CAI_HintManager::FindHint( this, hintCriteria ); } if( pHint ) { pArgs->hTarget = pHint; // Turn this node off for a few seconds to stop others aiming at the same thing (except for stealth nodes) if ( pHint->HintType() != HINT_WORLD_VISUALLY_INTERESTING_STEALTH ) { pHint->DisableForSeconds( 5.0f ); } return true; } // See what the base class thinks. return BaseClass::PickTacticalLookTarget( pArgs ); } //----------------------------------------------------------------------------- // Returns true if changing target. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::FindNewAimTarget() { if( GetEnemy() ) { // Don't bother. Aim at enemy. return false; } if( !m_bReadinessCapable || GetReadinessLevel() == AIRL_RELAXED ) { // If I'm relaxed (don't want to aim), or physically incapable, // don't run this hint node searching code. return false; } CAI_Hint *pHint; CHintCriteria hintCriteria; CBaseEntity *pPriorAimTarget = GetAimTarget(); hintCriteria.SetHintType( HINT_WORLD_VISUALLY_INTERESTING ); hintCriteria.SetFlag( bits_HINT_NODE_VISIBLE | bits_HINT_NODE_IN_VIEWCONE | bits_HINT_NPC_IN_NODE_FOV ); hintCriteria.AddIncludePosition( GetAbsOrigin(), COMPANION_MAX_TACTICAL_TARGET_DIST ); pHint = CAI_HintManager::FindHint( this, hintCriteria ); if( pHint ) { if( (pHint->GetAbsOrigin() - GetAbsOrigin()).Length2D() < COMPANION_AIMTARGET_NEAREST ) { // Too close! return false; } if( !HasAimLOS(pHint) ) { // No LOS return false; } if( pHint != pPriorAimTarget ) { // Notify of the change. SetAimTarget( pHint ); return true; } } // Didn't find an aim target, or found the same one. return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::OnNewLookTarget() { if( ai_new_aiming.GetBool() ) { if( GetLooktarget() ) { // See if our looktarget is a reasonable aim target. CAI_Hint *pHint = dynamic_cast<CAI_Hint*>( GetLooktarget() ); if( pHint ) { if( pHint->HintType() == HINT_WORLD_VISUALLY_INTERESTING && (pHint->GetAbsOrigin() - GetAbsOrigin()).Length2D() > COMPANION_AIMTARGET_NEAREST && FInAimCone(pHint->GetAbsOrigin()) && HasAimLOS(pHint) ) { SetAimTarget( pHint ); return; } } } // Search for something else. FindNewAimTarget(); } else { if( GetLooktarget() ) { // Have picked a new entity to look at. Should we copy it to the aim target? if( IRelationType( GetLooktarget() ) == D_LI ) { // Don't aim at friends, just keep the old target (if any) return; } if( (GetLooktarget()->GetAbsOrigin() - GetAbsOrigin()).Length2D() < COMPANION_AIMTARGET_NEAREST ) { // Too close! return; } if( !HasAimLOS( GetLooktarget() ) ) { // No LOS return; } SetAimTarget( GetLooktarget() ); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ShouldBeAiming() { if( !IsAllowedToAim() ) { return false; } if( !GetEnemy() && !GetAimTarget() ) { return false; } if( GetEnemy() && !HasCondition(COND_SEE_ENEMY) ) { return false; } return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #define PC_MAX_ALLOWED_AIM 2 bool CNPC_PlayerCompanion::IsAllowedToAim() { if( !m_pSquad ) return true; if( GetReadinessLevel() == AIRL_AGITATED ) { // Agitated companions can always aim. This makes the squad look // more alert as a whole when something very serious/dangerous has happened. return true; } int count = 0; // If I'm in a squad, only a certain number of us can aim. AISquadIter_t iter; for ( CAI_BaseNPC *pSquadmate = m_pSquad->GetFirstMember(&iter); pSquadmate; pSquadmate = m_pSquad->GetNextMember(&iter) ) { CNPC_PlayerCompanion *pCompanion = dynamic_cast<CNPC_PlayerCompanion*>(pSquadmate); if( pCompanion && pCompanion != this && pCompanion->GetAimTarget() != NULL ) { count++; } } if( count < PC_MAX_ALLOWED_AIM ) { return true; } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::HasAimLOS( CBaseEntity *pAimTarget ) { trace_t tr; UTIL_TraceLine( Weapon_ShootPosition(), pAimTarget->WorldSpaceCenter(), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); if( tr.fraction < 0.5 || (tr.m_pEnt && (tr.m_pEnt->IsNPC()||tr.m_pEnt->IsPlayer())) ) { return false; } return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::AimGun() { Vector vecAimDir; if( !GetEnemy() ) { if( GetAimTarget() && FInViewCone(GetAimTarget()) ) { float flDist; Vector vecAimTargetLoc = GetAimTarget()->WorldSpaceCenter(); flDist = (vecAimTargetLoc - GetAbsOrigin()).Length2DSqr(); // Throw away a looktarget if it gets too close. We don't want guys turning around as // they walk through doorways which contain a looktarget. if( flDist < COMPANION_AIMTARGET_NEAREST_SQR ) { StopAiming("Target too near"); return; } // Aim at my target if it's in my cone vecAimDir = vecAimTargetLoc - Weapon_ShootPosition();; VectorNormalize( vecAimDir ); SetAim( vecAimDir); if( !HasAimLOS(GetAimTarget()) ) { // LOS is broken. if( !FindNewAimTarget() ) { // No alternative available right now. Stop aiming. StopAiming("No LOS"); } } return; } else { if( GetAimTarget() ) { // We're aiming at something, but we're about to stop because it's out of viewcone. // Try to find something else. if( FindNewAimTarget() ) { // Found something else to aim at. return; } else { // ditch the aim target, it's gone out of view. StopAiming("Went out of view cone"); } } if( GetReadinessLevel() == AIRL_AGITATED ) { // Aim down! Agitated animations don't have non-aiming versions, so // just point the weapon down. Vector vecSpot = EyePosition(); Vector forward, up; GetVectors( &forward, NULL, &up ); vecSpot += forward * 128 + up * -64; vecAimDir = vecSpot - Weapon_ShootPosition(); VectorNormalize( vecAimDir ); SetAim( vecAimDir); return; } } } BaseClass::AimGun(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CBaseEntity *CNPC_PlayerCompanion::GetAlternateMoveShootTarget() { if( GetAimTarget() && !GetAimTarget()->IsNPC() && GetReadinessLevel() != AIRL_RELAXED ) { return GetAimTarget(); } return BaseClass::GetAlternateMoveShootTarget(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsValidEnemy( CBaseEntity *pEnemy ) { if ( GetFollowBehavior().GetFollowTarget() && GetFollowBehavior().GetFollowTarget()->IsPlayer() && IsSniper( pEnemy ) ) { AI_EnemyInfo_t *pInfo = GetEnemies()->Find( pEnemy ); if ( pInfo ) { if ( gpGlobals->curtime - pInfo->timeLastSeen > 10 ) { if ( !((CAI_BaseNPC*)pEnemy)->HasCondition( COND_IN_PVS ) ) return false; } } } return BaseClass::IsValidEnemy( pEnemy ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsSafeFromFloorTurret( const Vector &vecLocation, CBaseEntity *pTurret ) { float dist = ( vecLocation - pTurret->EyePosition() ).LengthSqr(); if ( dist > Square( 4.0*12.0 ) ) { if ( !pTurret->MyNPCPointer()->FInViewCone( vecLocation ) ) { #if 0 // Draws a green line to turrets I'm safe from NDebugOverlay::Line( vecLocation, pTurret->WorldSpaceCenter(), 0, 255, 0, false, 0.1 ); #endif return true; } } #if 0 // Draws a red lines to ones I'm not safe from. NDebugOverlay::Line( vecLocation, pTurret->WorldSpaceCenter(), 255, 0, 0, false, 0.1 ); #endif return false; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ bool CNPC_PlayerCompanion::ShouldMoveAndShoot( void ) { return BaseClass::ShouldMoveAndShoot(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #define PC_LARGER_BURST_RANGE (12.0f * 10.0f) // If an enemy is this close, player companions fire larger continuous bursts. void CNPC_PlayerCompanion::OnUpdateShotRegulator() { BaseClass::OnUpdateShotRegulator(); if( GetEnemy() && HasCondition(COND_CAN_RANGE_ATTACK1) ) { if( GetAbsOrigin().DistTo( GetEnemy()->GetAbsOrigin() ) <= PC_LARGER_BURST_RANGE ) { if( hl2_episodic.GetBool() ) { // Longer burst int longBurst = random->RandomInt( 10, 15 ); GetShotRegulator()->SetBurstShotsRemaining( longBurst ); GetShotRegulator()->SetRestInterval( 0.1, 0.2 ); } else { // Longer burst GetShotRegulator()->SetBurstShotsRemaining( GetShotRegulator()->GetBurstShotsRemaining() * 2 ); // Shorter Rest interval float flMinInterval, flMaxInterval; GetShotRegulator()->GetRestInterval( &flMinInterval, &flMaxInterval ); GetShotRegulator()->SetRestInterval( flMinInterval * 0.6f, flMaxInterval * 0.6f ); } } } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::DecalTrace( trace_t *pTrace, char const *decalName ) { // Do not decal a player companion's head or face, no matter what. if( pTrace->hitgroup == HITGROUP_HEAD ) return; BaseClass::DecalTrace( pTrace, decalName ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ bool CNPC_PlayerCompanion::FCanCheckAttacks() { if( GetEnemy() && ( IsSniper(GetEnemy()) || IsMortar(GetEnemy()) || IsTurret(GetEnemy()) ) ) { // Don't attack the sniper or the mortar. return false; } return BaseClass::FCanCheckAttacks(); } //----------------------------------------------------------------------------- // Purpose: Return the actual position the NPC wants to fire at when it's trying // to hit it's current enemy. //----------------------------------------------------------------------------- #define CITIZEN_HEADSHOT_FREQUENCY 3 // one in this many shots at a zombie will be aimed at the zombie's head Vector CNPC_PlayerCompanion::GetActualShootPosition( const Vector &shootOrigin ) { if( GetEnemy() && GetEnemy()->Classify() == CLASS_ZOMBIE && random->RandomInt( 1, CITIZEN_HEADSHOT_FREQUENCY ) == 1 ) { return GetEnemy()->HeadTarget( shootOrigin ); } return BaseClass::GetActualShootPosition( shootOrigin ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ WeaponProficiency_t CNPC_PlayerCompanion::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon ) { if( FClassnameIs( pWeapon, "weapon_ar2" ) ) { return WEAPON_PROFICIENCY_VERY_GOOD; } return WEAPON_PROFICIENCY_PERFECT; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::Weapon_CanUse( CBaseCombatWeapon *pWeapon ) { if( BaseClass::Weapon_CanUse( pWeapon ) ) { // If this weapon is a shotgun, take measures to control how many // are being used in this squad. Don't allow a companion to pick up // a shotgun if a squadmate already has one. if( pWeapon->ClassMatches( gm_iszShotgunClassname ) ) { return (NumWeaponsInSquad("weapon_shotgun") < 1 ); } else { return true; } } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ShouldLookForBetterWeapon() { if ( m_bDontPickupWeapons ) return false; return BaseClass::ShouldLookForBetterWeapon(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::Weapon_Equip( CBaseCombatWeapon *pWeapon ) { BaseClass::Weapon_Equip( pWeapon ); m_bReadinessCapable = IsReadinessCapable(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::PickupWeapon( CBaseCombatWeapon *pWeapon ) { BaseClass::PickupWeapon( pWeapon ); SpeakIfAllowed( TLK_NEWWEAPON ); m_OnWeaponPickup.FireOutput( this, this ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- const int MAX_NON_SPECIAL_MULTICOVER = 2; CUtlVector<AI_EnemyInfo_t *> g_MultiCoverSearchEnemies; CNPC_PlayerCompanion * g_pMultiCoverSearcher; //------------------------------------- int __cdecl MultiCoverCompare( AI_EnemyInfo_t * const *ppLeft, AI_EnemyInfo_t * const *ppRight ) { const AI_EnemyInfo_t *pLeft = *ppLeft; const AI_EnemyInfo_t *pRight = *ppRight; if ( !pLeft->hEnemy && !pRight->hEnemy) return 0; if ( !pLeft->hEnemy ) return 1; if ( !pRight->hEnemy ) return -1; if ( pLeft->hEnemy == g_pMultiCoverSearcher->GetEnemy() ) return -1; if ( pRight->hEnemy == g_pMultiCoverSearcher->GetEnemy() ) return 1; bool bLeftIsSpecial = ( CNPC_PlayerCompanion::IsMortar( pLeft->hEnemy ) || CNPC_PlayerCompanion::IsSniper( pLeft->hEnemy ) ); bool bRightIsSpecial = ( CNPC_PlayerCompanion::IsMortar( pLeft->hEnemy ) || CNPC_PlayerCompanion::IsSniper( pLeft->hEnemy ) ); if ( !bLeftIsSpecial && bRightIsSpecial ) return 1; if ( bLeftIsSpecial && !bRightIsSpecial ) return -1; float leftRelevantTime = ( pLeft->timeLastSeen == AI_INVALID_TIME || pLeft->timeLastSeen == 0 ) ? -99999 : pLeft->timeLastSeen; if ( pLeft->timeLastReceivedDamageFrom != AI_INVALID_TIME && pLeft->timeLastReceivedDamageFrom > leftRelevantTime ) leftRelevantTime = pLeft->timeLastReceivedDamageFrom; float rightRelevantTime = ( pRight->timeLastSeen == AI_INVALID_TIME || pRight->timeLastSeen == 0 ) ? -99999 : pRight->timeLastSeen; if ( pRight->timeLastReceivedDamageFrom != AI_INVALID_TIME && pRight->timeLastReceivedDamageFrom > rightRelevantTime ) rightRelevantTime = pRight->timeLastReceivedDamageFrom; if ( leftRelevantTime < rightRelevantTime ) return -1; if ( leftRelevantTime > rightRelevantTime ) return 1; float leftDistSq = g_pMultiCoverSearcher->GetAbsOrigin().DistToSqr( pLeft->hEnemy->GetAbsOrigin() ); float rightDistSq = g_pMultiCoverSearcher->GetAbsOrigin().DistToSqr( pRight->hEnemy->GetAbsOrigin() ); if ( leftDistSq < rightDistSq ) return -1; if ( leftDistSq > rightDistSq ) return 1; return 0; } //------------------------------------- void CNPC_PlayerCompanion::SetupCoverSearch( CBaseEntity *pEntity ) { if ( IsTurret( pEntity ) ) gm_fCoverSearchType = CT_TURRET; gm_bFindingCoverFromAllEnemies = false; g_pMultiCoverSearcher = this; if ( Classify() == CLASS_PLAYER_ALLY_VITAL || IsInPlayerSquad() ) { if ( GetEnemy() ) { if ( !pEntity || GetEnemies()->NumEnemies() > 1 ) { if ( !pEntity ) // if pEntity is NULL, test is against a point in space, so always to search against current enemy too gm_bFindingCoverFromAllEnemies = true; AIEnemiesIter_t iter; for ( AI_EnemyInfo_t *pEnemyInfo = GetEnemies()->GetFirst(&iter); pEnemyInfo != NULL; pEnemyInfo = GetEnemies()->GetNext(&iter) ) { CBaseEntity *pEnemy = pEnemyInfo->hEnemy; if ( pEnemy ) { if ( pEnemy != GetEnemy() ) { if ( pEnemyInfo->timeAtFirstHand == AI_INVALID_TIME || gpGlobals->curtime - pEnemyInfo->timeLastSeen > 10.0 ) continue; gm_bFindingCoverFromAllEnemies = true; } g_MultiCoverSearchEnemies.AddToTail( pEnemyInfo ); } } if ( g_MultiCoverSearchEnemies.Count() == 0 ) { gm_bFindingCoverFromAllEnemies = false; } else if ( gm_bFindingCoverFromAllEnemies ) { g_MultiCoverSearchEnemies.Sort( MultiCoverCompare ); Assert( g_MultiCoverSearchEnemies[0]->hEnemy == GetEnemy() ); } } } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::CleanupCoverSearch() { gm_fCoverSearchType = CT_NORMAL; g_MultiCoverSearchEnemies.RemoveAll(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::FindCoverPos( CBaseEntity *pEntity, Vector *pResult) { AI_PROFILE_SCOPE(CNPC_PlayerCompanion_FindCoverPos); ASSERT_NO_REENTRY(); bool result = false; SetupCoverSearch( pEntity ); if ( gm_bFindingCoverFromAllEnemies ) { result = BaseClass::FindCoverPos( pEntity, pResult ); gm_bFindingCoverFromAllEnemies = false; } if ( !result ) result = BaseClass::FindCoverPos( pEntity, pResult ); CleanupCoverSearch(); return result; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::FindCoverPosInRadius( CBaseEntity *pEntity, const Vector &goalPos, float coverRadius, Vector *pResult ) { AI_PROFILE_SCOPE(CNPC_PlayerCompanion_FindCoverPosInRadius); ASSERT_NO_REENTRY(); bool result = false; SetupCoverSearch( pEntity ); if ( gm_bFindingCoverFromAllEnemies ) { result = BaseClass::FindCoverPosInRadius( pEntity, goalPos, coverRadius, pResult ); gm_bFindingCoverFromAllEnemies = false; } if ( !result ) { result = BaseClass::FindCoverPosInRadius( pEntity, goalPos, coverRadius, pResult ); } CleanupCoverSearch(); return result; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::FindCoverPos( CSound *pSound, Vector *pResult ) { AI_PROFILE_SCOPE(CNPC_PlayerCompanion_FindCoverPos); bool result = false; bool bIsMortar = ( pSound->SoundContext() == SOUND_CONTEXT_MORTAR ); SetupCoverSearch( NULL ); if ( gm_bFindingCoverFromAllEnemies ) { result = ( bIsMortar ) ? FindMortarCoverPos( pSound, pResult ) : BaseClass::FindCoverPos( pSound, pResult ); gm_bFindingCoverFromAllEnemies = false; } if ( !result ) { result = ( bIsMortar ) ? FindMortarCoverPos( pSound, pResult ) : BaseClass::FindCoverPos( pSound, pResult ); } CleanupCoverSearch(); return result; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::FindMortarCoverPos( CSound *pSound, Vector *pResult ) { bool result = false; Assert( pSound->SoundContext() == SOUND_CONTEXT_MORTAR ); gm_fCoverSearchType = CT_MORTAR; result = GetTacticalServices()->FindLateralCover( pSound->GetSoundOrigin(), 0, pResult ); if ( !result ) { result = GetTacticalServices()->FindCoverPos( pSound->GetSoundOrigin(), pSound->GetSoundOrigin(), 0, CoverRadius(), pResult ); } gm_fCoverSearchType = CT_NORMAL; return result; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsCoverPosition( const Vector &vecThreat, const Vector &vecPosition ) { if ( gm_bFindingCoverFromAllEnemies ) { for ( int i = 0; i < g_MultiCoverSearchEnemies.Count(); i++ ) { // @TODO (toml 07-27-04): Should skip checking points near already checked points AI_EnemyInfo_t *pEnemyInfo = g_MultiCoverSearchEnemies[i]; Vector testPos; CBaseEntity *pEnemy = pEnemyInfo->hEnemy; if ( !pEnemy ) continue; if ( pEnemy == GetEnemy() || IsMortar( pEnemy ) || IsSniper( pEnemy ) || i < MAX_NON_SPECIAL_MULTICOVER ) { testPos = pEnemyInfo->vLastKnownLocation + pEnemy->GetViewOffset(); } else break; gm_bFindingCoverFromAllEnemies = false; bool result = IsCoverPosition( testPos, vecPosition ); gm_bFindingCoverFromAllEnemies = true; if ( !result ) return false; } if ( gm_fCoverSearchType != CT_MORTAR && GetEnemy() && vecThreat.DistToSqr( GetEnemy()->EyePosition() ) < 1 ) return true; // else fall through } if ( gm_fCoverSearchType == CT_TURRET && GetEnemy() && IsSafeFromFloorTurret( vecPosition, GetEnemy() ) ) { return true; } if ( gm_fCoverSearchType == CT_MORTAR ) { CSound *pSound = GetBestSound( SOUND_DANGER ); Assert ( pSound && pSound->SoundContext() == SOUND_CONTEXT_MORTAR ); if( pSound ) { // Don't get closer to the shell Vector vecToSound = vecThreat - GetAbsOrigin(); Vector vecToPosition = vecPosition - GetAbsOrigin(); VectorNormalize( vecToPosition ); VectorNormalize( vecToSound ); if ( vecToPosition.AsVector2D().Dot( vecToSound.AsVector2D() ) > 0 ) return false; // Anything outside the radius is okay float flDistSqr = (vecPosition - vecThreat).Length2DSqr(); float radiusSq = Square( pSound->Volume() ); if( flDistSqr > radiusSq ) { return true; } } } return BaseClass::IsCoverPosition( vecThreat, vecPosition ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsMortar( CBaseEntity *pEntity ) { if ( !pEntity ) return false; CBaseEntity *pEntityParent = pEntity->GetParent(); return ( pEntityParent && pEntityParent->GetClassname() == STRING(gm_iszMortarClassname) ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsSniper( CBaseEntity *pEntity ) { if ( !pEntity ) return false; return ( pEntity->Classify() == CLASS_PROTOSNIPER ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsTurret( CBaseEntity *pEntity ) { if ( !pEntity ) return false; const char *pszClassname = pEntity->GetClassname(); return ( pszClassname == STRING(gm_iszFloorTurretClassname) || pszClassname == STRING(gm_iszGroundTurretClassname) ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsGunship( CBaseEntity *pEntity ) { if( !pEntity ) return false; return (pEntity->Classify() == CLASS_COMBINE_GUNSHIP ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CNPC_PlayerCompanion::OnTakeDamage_Alive( const CTakeDamageInfo &info ) { if( info.GetAttacker() ) { bool bIsEnvFire; if( ( bIsEnvFire = FClassnameIs( info.GetAttacker(), "env_fire" ) ) != false || FClassnameIs( info.GetAttacker(), "entityflame" ) || FClassnameIs( info.GetAttacker(), "env_entity_igniter" ) ) { GetMotor()->SetIdealYawToTarget( info.GetAttacker()->GetAbsOrigin() ); SetCondition( COND_PC_HURTBYFIRE ); } // @Note (toml 07-25-04): there isn't a good solution to player companions getting injured by // fires that have huge damage radii that extend outside the rendered // fire. Recovery from being injured by fire will also not be done // before we ship/ Here we trade one bug (guys standing around dying // from flames they appear to not be near), for a lesser one // this guy was standing in a fire and didn't react. Since // the levels are supposed to have the centers of all the fires // npc clipped, this latter case should be rare. if ( bIsEnvFire ) { if ( ( GetAbsOrigin() - info.GetAttacker()->GetAbsOrigin() ).Length2DSqr() > Square(12 + GetHullWidth() * .5 ) ) { return 0; } } } return BaseClass::OnTakeDamage_Alive( info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttackerEnt ) { AI_PROFILE_SCOPE( CNPC_PlayerCompanion_OnFriendDamaged ); BaseClass::OnFriendDamaged( pSquadmate, pAttackerEnt ); CAI_BaseNPC *pAttacker = pAttackerEnt->MyNPCPointer(); if ( pAttacker ) { bool bDirect = ( pSquadmate->FInViewCone(pAttacker) && ( ( pSquadmate->IsPlayer() && HasCondition(COND_SEE_PLAYER) ) || ( pSquadmate->MyNPCPointer() && pSquadmate->MyNPCPointer()->IsPlayerAlly() && GetSenses()->DidSeeEntity( pSquadmate ) ) ) ); if ( bDirect ) { UpdateEnemyMemory( pAttacker, pAttacker->GetAbsOrigin(), pSquadmate ); } else { if ( FVisible( pSquadmate ) ) { AI_EnemyInfo_t *pInfo = GetEnemies()->Find( pAttacker ); if ( !pInfo || ( gpGlobals->curtime - pInfo->timeLastSeen ) > 15.0 ) UpdateEnemyMemory( pAttacker, pSquadmate->GetAbsOrigin(), pSquadmate ); } } #ifdef HL2SB CBasePlayer *pPlayer = AI_GetNearestPlayer( GetAbsOrigin() ); #else CBasePlayer *pPlayer = AI_GetSinglePlayer(); #endif if ( pPlayer && IsInPlayerSquad() && ( pPlayer->GetAbsOrigin().AsVector2D() - GetAbsOrigin().AsVector2D() ).LengthSqr() < Square( 25*12 ) && IsAllowedToSpeak( TLK_WATCHOUT ) ) { if ( !pPlayer->FInViewCone( pAttacker ) ) { Vector2D vPlayerDir = pPlayer->EyeDirection2D().AsVector2D(); Vector2D vEnemyDir = pAttacker->EyePosition().AsVector2D() - pPlayer->EyePosition().AsVector2D(); vEnemyDir.NormalizeInPlace(); float dot = vPlayerDir.Dot( vEnemyDir ); if ( dot < 0 ) Speak( TLK_WATCHOUT, "dangerloc:behind" ); else if ( ( pPlayer->GetAbsOrigin().AsVector2D() - pAttacker->GetAbsOrigin().AsVector2D() ).LengthSqr() > Square( 40*12 ) ) Speak( TLK_WATCHOUT, "dangerloc:far" ); } else if ( pAttacker->GetAbsOrigin().z - pPlayer->GetAbsOrigin().z > 128 ) { Speak( TLK_WATCHOUT, "dangerloc:above" ); } else if ( pAttacker->GetHullType() <= HULL_TINY && ( pPlayer->GetAbsOrigin().AsVector2D() - pAttacker->GetAbsOrigin().AsVector2D() ).LengthSqr() > Square( 100*12 ) ) { Speak( TLK_WATCHOUT, "dangerloc:far" ); } } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsValidMoveAwayDest( const Vector &vecDest ) { // Don't care what the destination is unless I have an enemy and // that enemy is a sniper (for now). if( !GetEnemy() ) { return true; } if( GetEnemy()->Classify() != CLASS_PROTOSNIPER ) { return true; } if( IsCoverPosition( GetEnemy()->EyePosition(), vecDest + GetViewOffset() ) ) { return true; } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::FValidateHintType( CAI_Hint *pHint ) { switch( pHint->HintType() ) { case HINT_PLAYER_SQUAD_TRANSITON_POINT: case HINT_WORLD_VISUALLY_INTERESTING_DONT_AIM: case HINT_PLAYER_ALLY_MOVE_AWAY_DEST: case HINT_PLAYER_ALLY_FEAR_DEST: return true; break; default: break; } return BaseClass::FValidateHintType( pHint ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ValidateNavGoal() { bool result; if ( GetNavigator()->GetGoalType() == GOALTYPE_COVER ) { if ( IsEnemyTurret() ) gm_fCoverSearchType = CT_TURRET; } result = BaseClass::ValidateNavGoal(); gm_fCoverSearchType = CT_NORMAL; return result; } const float AVOID_TEST_DIST = 18.0f*12.0f; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #define COMPANION_EPISODIC_AVOID_ENTITY_FLAME_RADIUS 18.0f bool CNPC_PlayerCompanion::OverrideMove( float flInterval ) { bool overrode = BaseClass::OverrideMove( flInterval ); if ( !overrode && GetNavigator()->GetGoalType() != GOALTYPE_NONE ) { string_t iszEnvFire = AllocPooledString( "env_fire" ); string_t iszBounceBomb = AllocPooledString( "combine_mine" ); #ifdef HL2_EPISODIC string_t iszNPCTurretFloor = AllocPooledString( "npc_turret_floor" ); string_t iszEntityFlame = AllocPooledString( "entityflame" ); #endif // HL2_EPISODIC if ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) ) { CSound *pSound = GetBestSound( SOUND_DANGER ); if( pSound && pSound->SoundContext() == SOUND_CONTEXT_MORTAR ) { // Try not to get any closer to the center GetLocalNavigator()->AddObstacle( pSound->GetSoundOrigin(), (pSound->GetSoundOrigin() - GetAbsOrigin()).Length2D() * 0.5, AIMST_AVOID_DANGER ); } } CBaseEntity *pEntity = NULL; trace_t tr; // For each possible entity, compare our known interesting classnames to its classname, via ID while( ( pEntity = OverrideMoveCache_FindTargetsInRadius( pEntity, GetAbsOrigin(), AVOID_TEST_DIST ) ) != NULL ) { // Handle each type if ( pEntity->m_iClassname == iszEnvFire ) { Vector vMins, vMaxs; if ( FireSystem_GetFireDamageDimensions( pEntity, &vMins, &vMaxs ) ) { UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_FIRE_SOLID, pEntity, COLLISION_GROUP_NONE, &tr ); if (tr.fraction == 1.0 && !tr.startsolid) { GetLocalNavigator()->AddObstacle( pEntity->GetAbsOrigin(), ( ( vMaxs.x - vMins.x ) * 1.414 * 0.5 ) + 6.0, AIMST_AVOID_DANGER ); } } } #ifdef HL2_EPISODIC else if ( pEntity->m_iClassname == iszNPCTurretFloor ) { UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_BLOCKLOS, pEntity, COLLISION_GROUP_NONE, &tr ); if (tr.fraction == 1.0 && !tr.startsolid) { float radius = 1.4 * pEntity->CollisionProp()->BoundingRadius2D(); GetLocalNavigator()->AddObstacle( pEntity->WorldSpaceCenter(), radius, AIMST_AVOID_OBJECT ); } } else if( pEntity->m_iClassname == iszEntityFlame && pEntity->GetParent() && !pEntity->GetParent()->IsNPC() ) { float flDist = pEntity->WorldSpaceCenter().DistTo( WorldSpaceCenter() ); if( flDist > COMPANION_EPISODIC_AVOID_ENTITY_FLAME_RADIUS ) { // If I'm not in the flame, prevent me from getting close to it. // If I AM in the flame, avoid placing an obstacle until the flame frightens me away from itself. UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_BLOCKLOS, pEntity, COLLISION_GROUP_NONE, &tr ); if (tr.fraction == 1.0 && !tr.startsolid) { GetLocalNavigator()->AddObstacle( pEntity->WorldSpaceCenter(), COMPANION_EPISODIC_AVOID_ENTITY_FLAME_RADIUS, AIMST_AVOID_OBJECT ); } } } #endif // HL2_EPISODIC else if ( pEntity->m_iClassname == iszBounceBomb ) { CBounceBomb *pBomb = static_cast<CBounceBomb *>(pEntity); if ( pBomb && !pBomb->IsPlayerPlaced() && pBomb->IsAwake() ) { UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_BLOCKLOS, pEntity, COLLISION_GROUP_NONE, &tr ); if (tr.fraction == 1.0 && !tr.startsolid) { GetLocalNavigator()->AddObstacle( pEntity->GetAbsOrigin(), BOUNCEBOMB_DETONATE_RADIUS * .8, AIMST_AVOID_DANGER ); } } } } } return overrode; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::MovementCost( int moveType, const Vector &vecStart, const Vector &vecEnd, float *pCost ) { bool bResult = BaseClass::MovementCost( moveType, vecStart, vecEnd, pCost ); if ( moveType == bits_CAP_MOVE_GROUND ) { if ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) ) { CSound *pSound = GetBestSound( SOUND_DANGER ); if( pSound && (pSound->SoundContext() & (SOUND_CONTEXT_MORTAR|SOUND_CONTEXT_FROM_SNIPER)) ) { Vector vecToSound = pSound->GetSoundReactOrigin() - GetAbsOrigin(); Vector vecToPosition = vecEnd - GetAbsOrigin(); VectorNormalize( vecToPosition ); VectorNormalize( vecToSound ); if ( vecToPosition.AsVector2D().Dot( vecToSound.AsVector2D() ) > 0 ) { *pCost *= 1.5; bResult = true; } } } if ( m_bWeightPathsInCover && GetEnemy() ) { if ( BaseClass::IsCoverPosition( GetEnemy()->EyePosition(), vecEnd ) ) { *pCost *= 0.1; bResult = true; } } } return bResult; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- float CNPC_PlayerCompanion::GetIdealSpeed() const { float baseSpeed = BaseClass::GetIdealSpeed(); if ( baseSpeed < m_flBoostSpeed ) return m_flBoostSpeed; return baseSpeed; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- float CNPC_PlayerCompanion::GetIdealAccel() const { float multiplier = 1.0; if ( AI_IsSinglePlayer() ) { if ( m_bMovingAwayFromPlayer && (UTIL_PlayerByIndex(1)->GetAbsOrigin() - GetAbsOrigin()).Length2DSqr() < Square(3.0*12.0) ) multiplier = 2.0; } return BaseClass::GetIdealAccel() * multiplier; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::OnObstructionPreSteer( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult ) { if ( pMoveGoal->directTrace.flTotalDist - pMoveGoal->directTrace.flDistObstructed < GetHullWidth() * 1.5 ) { CAI_BaseNPC *pBlocker = pMoveGoal->directTrace.pObstruction->MyNPCPointer(); if ( pBlocker && pBlocker->IsPlayerAlly() && !pBlocker->IsMoving() && !pBlocker->IsInAScript() && ( IsCurSchedule( SCHED_NEW_WEAPON ) || IsCurSchedule( SCHED_GET_HEALTHKIT ) || pBlocker->IsCurSchedule( SCHED_FAIL ) || ( IsInPlayerSquad() && !pBlocker->IsInPlayerSquad() ) || Classify() == CLASS_PLAYER_ALLY_VITAL || IsInAScript() ) ) { if ( pBlocker->ConditionInterruptsCurSchedule( COND_GIVE_WAY ) || pBlocker->ConditionInterruptsCurSchedule( COND_PLAYER_PUSHING ) ) { // HACKHACK pBlocker->GetMotor()->SetIdealYawToTarget( WorldSpaceCenter() ); pBlocker->SetSchedule( SCHED_MOVE_AWAY ); } } } if ( pMoveGoal->directTrace.pObstruction ) { } return BaseClass::OnObstructionPreSteer( pMoveGoal, distClear, pResult ); } //----------------------------------------------------------------------------- // Purpose: Whether or not we should always transition with the player // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ShouldAlwaysTransition( void ) { // No matter what, come through if ( m_bAlwaysTransition ) return true; // Squadmates always come with if ( IsInPlayerSquad() ) return true; // If we're following the player, then come along if ( GetFollowBehavior().GetFollowTarget() && GetFollowBehavior().GetFollowTarget()->IsPlayer() ) return true; return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputOutsideTransition( inputdata_t &inputdata ) { #ifndef HL2SB if ( !AI_IsSinglePlayer() ) return; #endif // Must want to do this if ( ShouldAlwaysTransition() == false ) return; // If we're in a vehicle, that vehicle will transition with us still inside (which is preferable) if ( IsInAVehicle() ) return; #ifdef HL2SB CBaseEntity *pPlayer = UTIL_GetNearestPlayer( GetAbsOrigin() ); #else CBaseEntity *pPlayer = UTIL_GetLocalPlayer(); #endif const Vector &playerPos = pPlayer->GetAbsOrigin(); // Mark us as already having succeeded if we're vital or always meant to come with the player bool bAlwaysTransition = ( ( Classify() == CLASS_PLAYER_ALLY_VITAL ) || m_bAlwaysTransition ); bool bPathToPlayer = bAlwaysTransition; if ( bAlwaysTransition == false ) { AI_Waypoint_t *pPathToPlayer = GetPathfinder()->BuildRoute( GetAbsOrigin(), playerPos, pPlayer, 0 ); if ( pPathToPlayer ) { bPathToPlayer = true; CAI_Path tempPath; tempPath.SetWaypoints( pPathToPlayer ); // path object will delete waypoints GetPathfinder()->UnlockRouteNodes( pPathToPlayer ); } } #ifdef USE_PATHING_LENGTH_REQUIREMENT_FOR_TELEPORT float pathLength = tempPath.GetPathDistanceToGoal( GetAbsOrigin() ); if ( pathLength > 150 * 12 ) return; #endif bool bMadeIt = false; Vector teleportLocation; CAI_Hint *pHint = CAI_HintManager::FindHint( this, HINT_PLAYER_SQUAD_TRANSITON_POINT, bits_HINT_NODE_NEAREST, PLAYERCOMPANION_TRANSITION_SEARCH_DISTANCE, &playerPos ); while ( pHint ) { pHint->Lock(this); pHint->Unlock(0.5); // prevent other squadmates and self from using during transition. pHint->GetPosition( GetHullType(), &teleportLocation ); if ( GetNavigator()->CanFitAtPosition( teleportLocation, MASK_NPCSOLID ) ) { bMadeIt = true; if ( !bPathToPlayer && ( playerPos - GetAbsOrigin() ).LengthSqr() > Square(40*12) ) { AI_Waypoint_t *pPathToTeleport = GetPathfinder()->BuildRoute( GetAbsOrigin(), teleportLocation, pPlayer, 0 ); if ( !pPathToTeleport ) { DevMsg( 2, "NPC \"%s\" failed to teleport to transition a point because there is no path\n", STRING(GetEntityName()) ); bMadeIt = false; } else { CAI_Path tempPath; GetPathfinder()->UnlockRouteNodes( pPathToTeleport ); tempPath.SetWaypoints( pPathToTeleport ); // path object will delete waypoints } } if ( bMadeIt ) { DevMsg( 2, "NPC \"%s\" teleported to transition point %d\n", STRING(GetEntityName()), pHint->GetNodeId() ); break; } } else { if ( g_debug_transitions.GetBool() ) { NDebugOverlay::Box( teleportLocation, GetHullMins(), GetHullMaxs(), 255,0,0, 8, 999 ); } } pHint = CAI_HintManager::FindHint( this, HINT_PLAYER_SQUAD_TRANSITON_POINT, bits_HINT_NODE_NEAREST, PLAYERCOMPANION_TRANSITION_SEARCH_DISTANCE, &playerPos ); } if ( !bMadeIt ) { // Force us if we didn't find a normal route if ( bAlwaysTransition ) { bMadeIt = FindSpotForNPCInRadius( &teleportLocation, pPlayer->GetAbsOrigin(), this, 32.0*1.414, true ); if ( !bMadeIt ) bMadeIt = FindSpotForNPCInRadius( &teleportLocation, pPlayer->GetAbsOrigin(), this, 32.0*1.414, false ); } } if ( bMadeIt ) { Teleport( &teleportLocation, NULL, NULL ); } else { DevMsg( 2, "NPC \"%s\" failed to find a suitable transition a point\n", STRING(GetEntityName()) ); } BaseClass::InputOutsideTransition( inputdata ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputSetReadinessPanic( inputdata_t &inputdata ) { SetReadinessLevel( AIRL_PANIC, true, true ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputSetReadinessStealth( inputdata_t &inputdata ) { SetReadinessLevel( AIRL_STEALTH, true, true ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputSetReadinessLow( inputdata_t &inputdata ) { SetReadinessLevel( AIRL_RELAXED, true, true ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputSetReadinessMedium( inputdata_t &inputdata ) { SetReadinessLevel( AIRL_STIMULATED, true, true ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputSetReadinessHigh( inputdata_t &inputdata ) { SetReadinessLevel( AIRL_AGITATED, true, true ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputLockReadiness( inputdata_t &inputdata ) { float value = inputdata.value.Float(); LockReadiness( value ); } //----------------------------------------------------------------------------- // Purpose: Locks the readiness state of the NCP // Input : time - if -1, the lock is effectively infinite //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::LockReadiness( float duration ) { if ( duration == -1.0f ) { m_flReadinessLockedUntil = FLT_MAX; } else { m_flReadinessLockedUntil = gpGlobals->curtime + duration; } } //----------------------------------------------------------------------------- // Purpose: Unlocks the readiness state //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::UnlockReadiness( void ) { // Set to the past m_flReadinessLockedUntil = gpGlobals->curtime - 0.1f; } //------------------------------------------------------------------------------ #ifdef HL2_EPISODIC //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ShouldDeferToPassengerBehavior( void ) { if ( m_PassengerBehavior.CanSelectSchedule() ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: Determines if this player companion is capable of entering a vehicle // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::CanEnterVehicle( void ) { return true; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::CanExitVehicle( void ) { // See if we can exit our vehicle CPropJeepEpisodic *pVehicle = dynamic_cast<CPropJeepEpisodic *>(m_PassengerBehavior.GetTargetVehicle()); if ( pVehicle != NULL && pVehicle->NPC_CanExitVehicle( this, true ) == false ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: // Input : *lpszVehicleName - //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::EnterVehicle( CBaseEntity *pEntityVehicle, bool bImmediately ) { // Must be allowed to do this if ( CanEnterVehicle() == false ) return; // Find the target vehicle CPropJeepEpisodic *pVehicle = dynamic_cast<CPropJeepEpisodic *>(pEntityVehicle); // Get in the car if it's valid if ( pVehicle != NULL && pVehicle->NPC_CanEnterVehicle( this, true ) ) { // Set her into a "passenger" behavior m_PassengerBehavior.Enable( pVehicle, bImmediately ); m_PassengerBehavior.EnterVehicle(); // Only do this if we're outside the vehicle if ( m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_OUTSIDE ) { SetCondition( COND_PC_BECOMING_PASSENGER ); } } } //----------------------------------------------------------------------------- // Purpose: Get into the requested vehicle // Input : &inputdata - contains the entity name of the vehicle to enter //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputEnterVehicle( inputdata_t &inputdata ) { CBaseEntity *pEntity = FindNamedEntity( inputdata.value.String() ); EnterVehicle( pEntity, false ); } //----------------------------------------------------------------------------- // Purpose: Get into the requested vehicle immediately (no animation, pop) // Input : &inputdata - contains the entity name of the vehicle to enter //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputEnterVehicleImmediately( inputdata_t &inputdata ) { CBaseEntity *pEntity = FindNamedEntity( inputdata.value.String() ); EnterVehicle( pEntity, true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputExitVehicle( inputdata_t &inputdata ) { // See if we're allowed to exit the vehicle if ( CanExitVehicle() == false ) return; m_PassengerBehavior.ExitVehicle(); } //----------------------------------------------------------------------------- // Purpose: // Input : &inputdata - //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputCancelEnterVehicle( inputdata_t &inputdata ) { m_PassengerBehavior.CancelEnterVehicle(); } //----------------------------------------------------------------------------- // Purpose: Forces the NPC out of the vehicle they're riding in // Input : bImmediate - If we need to exit immediately, teleport to any exit location // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::ExitVehicle( void ) { // For now just get out m_PassengerBehavior.ExitVehicle(); return true; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsInAVehicle( void ) const { // Must be active and getting in/out of vehicle if ( m_PassengerBehavior.IsEnabled() && m_PassengerBehavior.GetPassengerState() != PASSENGER_STATE_OUTSIDE ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: // Output : IServerVehicle - //----------------------------------------------------------------------------- IServerVehicle *CNPC_PlayerCompanion::GetVehicle( void ) { if ( IsInAVehicle() ) { CPropVehicleDriveable *pDriveableVehicle = m_PassengerBehavior.GetTargetVehicle(); if ( pDriveableVehicle != NULL ) return pDriveableVehicle->GetServerVehicle(); } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : CBaseEntity //----------------------------------------------------------------------------- CBaseEntity *CNPC_PlayerCompanion::GetVehicleEntity( void ) { if ( IsInAVehicle() ) { CPropVehicleDriveable *pDriveableVehicle = m_PassengerBehavior.GetTargetVehicle(); return pDriveableVehicle; } return NULL; } //----------------------------------------------------------------------------- // Purpose: Override our efficiency so that we don't jitter when we're in the middle // of our enter/exit animations. // Input : bInPVS - Whether we're in the PVS or not //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::UpdateEfficiency( bool bInPVS ) { // If we're transitioning and in the PVS, we override our efficiency if ( IsInAVehicle() && bInPVS ) { PassengerState_e nState = m_PassengerBehavior.GetPassengerState(); if ( nState == PASSENGER_STATE_ENTERING || nState == PASSENGER_STATE_EXITING ) { SetEfficiency( AIE_NORMAL ); return; } } // Do the default behavior BaseClass::UpdateEfficiency( bInPVS ); } //----------------------------------------------------------------------------- // Purpose: Whether or not we can dynamically interact with another NPC //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::CanRunAScriptedNPCInteraction( bool bForced /*= false*/ ) { // TODO: Allow this but only for interactions who stem from being in a vehicle? if ( IsInAVehicle() ) return false; return BaseClass::CanRunAScriptedNPCInteraction( bForced ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsAllowedToDodge( void ) { // TODO: Allow this but only for interactions who stem from being in a vehicle? if ( IsInAVehicle() ) return false; return BaseClass::IsAllowedToDodge(); } #endif //HL2_EPISODIC //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Purpose: Always transition along with the player //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputEnableAlwaysTransition( inputdata_t &inputdata ) { m_bAlwaysTransition = true; } //----------------------------------------------------------------------------- // Purpose: Stop always transitioning along with the player //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputDisableAlwaysTransition( inputdata_t &inputdata ) { m_bAlwaysTransition = false; } //----------------------------------------------------------------------------- // Purpose: Stop picking up weapons from the ground //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputEnableWeaponPickup( inputdata_t &inputdata ) { m_bDontPickupWeapons = false; } //----------------------------------------------------------------------------- // Purpose: Return to default behavior of picking up better weapons on the ground //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::InputDisableWeaponPickup( inputdata_t &inputdata ) { m_bDontPickupWeapons = true; } //------------------------------------------------------------------------------ // Purpose: Give the NPC in question the weapon specified //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputGiveWeapon( inputdata_t &inputdata ) { // Give the NPC the specified weapon string_t iszWeaponName = inputdata.value.StringID(); if ( iszWeaponName != NULL_STRING ) { if( Classify() == CLASS_PLAYER_ALLY_VITAL ) { m_iszPendingWeapon = iszWeaponName; } else { GiveWeapon( iszWeaponName ); } } } #if HL2_EPISODIC //------------------------------------------------------------------------------ // Purpose: Delete all outputs from this NPC. //------------------------------------------------------------------------------ void CNPC_PlayerCompanion::InputClearAllOuputs( inputdata_t &inputdata ) { datamap_t *dmap = GetDataDescMap(); while ( dmap ) { int fields = dmap->dataNumFields; for ( int i = 0; i < fields; i++ ) { typedescription_t *dataDesc = &dmap->dataDesc[i]; if ( ( dataDesc->fieldType == FIELD_CUSTOM ) && ( dataDesc->flags & FTYPEDESC_OUTPUT ) ) { CBaseEntityOutput *pOutput = (CBaseEntityOutput *)((int)this + (int)dataDesc->fieldOffset[0]); pOutput->DeleteAllElements(); /* int nConnections = pOutput->NumberOfElements(); for ( int j = 0; j < nConnections; j++ ) { } */ } } dmap = dmap->baseMap; } } #endif //----------------------------------------------------------------------------- // Purpose: Player in our squad killed something // Input : *pVictim - Who he killed // &info - How they died //----------------------------------------------------------------------------- void CNPC_PlayerCompanion::OnPlayerKilledOther( CBaseEntity *pVictim, const CTakeDamageInfo &info ) { // filter everything that comes in here that isn't an NPC CAI_BaseNPC *pCombatVictim = dynamic_cast<CAI_BaseNPC *>( pVictim ); if ( !pCombatVictim ) { return; } CBaseEntity *pInflictor = info.GetInflictor(); int iNumBarrels = 0; int iConsecutivePlayerKills = 0; bool bPuntedGrenade = false; bool bVictimWasEnemy = false; bool bVictimWasMob = false; bool bVictimWasAttacker = false; bool bHeadshot = false; bool bOneShot = false; if ( dynamic_cast<CBreakableProp *>( pInflictor ) && ( info.GetDamageType() & DMG_BLAST ) ) { // if a barrel explodes that was initiated by the player within a few seconds of the previous one, // increment a counter to keep track of how many have exploded in a row. if ( gpGlobals->curtime - m_fLastBarrelExploded >= MAX_TIME_BETWEEN_BARRELS_EXPLODING ) { m_iNumConsecutiveBarrelsExploded = 0; } m_iNumConsecutiveBarrelsExploded++; m_fLastBarrelExploded = gpGlobals->curtime; iNumBarrels = m_iNumConsecutiveBarrelsExploded; } else { // if player kills an NPC within a few seconds of the previous kill, // increment a counter to keep track of how many he's killed in a row. if ( gpGlobals->curtime - m_fLastPlayerKill >= MAX_TIME_BETWEEN_CONSECUTIVE_PLAYER_KILLS ) { m_iNumConsecutivePlayerKills = 0; } m_iNumConsecutivePlayerKills++; m_fLastPlayerKill = gpGlobals->curtime; iConsecutivePlayerKills = m_iNumConsecutivePlayerKills; } // don't comment on kills when she can't see the victim if ( !FVisible( pVictim ) ) { return; } // check if the player killed an enemy by punting a grenade if ( pInflictor && Fraggrenade_WasPunted( pInflictor ) && Fraggrenade_WasCreatedByCombine( pInflictor ) ) { bPuntedGrenade = true; } // check if the victim was Alyx's enemy if ( GetEnemy() == pVictim ) { bVictimWasEnemy = true; } AI_EnemyInfo_t *pEMemory = GetEnemies()->Find( pVictim ); if ( pEMemory != NULL ) { // was Alyx being mobbed by this enemy? bVictimWasMob = pEMemory->bMobbedMe; // has Alyx recieved damage from this enemy? if ( pEMemory->timeLastReceivedDamageFrom > 0 ) { bVictimWasAttacker = true; } } // Was it a headshot? if ( ( pCombatVictim->LastHitGroup() == HITGROUP_HEAD ) && ( info.GetDamageType() & DMG_BULLET ) ) { bHeadshot = true; } // Did the player kill the enemy with 1 shot? if ( ( pCombatVictim->GetDamageCount() == 1 ) && ( info.GetDamageType() & DMG_BULLET ) ) { bOneShot = true; } // set up the speech modifiers CFmtStrN<512> modifiers( "num_barrels:%d,distancetoplayerenemy:%f,playerAmmo:%s,consecutive_player_kills:%d," "punted_grenade:%d,victim_was_enemy:%d,victim_was_mob:%d,victim_was_attacker:%d,headshot:%d,oneshot:%d", iNumBarrels, EnemyDistance( pVictim ), info.GetAmmoName(), iConsecutivePlayerKills, bPuntedGrenade, bVictimWasEnemy, bVictimWasMob, bVictimWasAttacker, bHeadshot, bOneShot ); SpeakIfAllowed( TLK_PLAYER_KILLED_NPC, modifiers ); BaseClass::OnPlayerKilledOther( pVictim, info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CNPC_PlayerCompanion::IsNavigationUrgent( void ) { bool bBase = BaseClass::IsNavigationUrgent(); // Consider follow & assault behaviour urgent if ( !bBase && (m_FollowBehavior.IsActive() || ( m_AssaultBehavior.IsRunning() && m_AssaultBehavior.IsUrgent() )) && Classify() == CLASS_PLAYER_ALLY_VITAL ) { // But only if the blocker isn't the player, and isn't a physics object that's still moving CBaseEntity *pBlocker = GetNavigator()->GetBlockingEntity(); if ( pBlocker && !pBlocker->IsPlayer() ) { IPhysicsObject *pPhysObject = pBlocker->VPhysicsGetObject(); if ( pPhysObject && !pPhysObject->IsAsleep() ) return false; if ( pBlocker->IsNPC() ) return false; } // If we're within the player's viewcone, then don't teleport. // This test was made more general because previous iterations had cases where characters // could not see the player but the player could in fact see them. Now the NPC's facing is // irrelevant and the player's viewcone is more authorative. -- jdw #ifdef HL2SB CBasePlayer *pLocalPlayer = AI_GetNearestPlayer( GetAbsOrigin() ); #else CBasePlayer *pLocalPlayer = AI_GetSinglePlayer(); #endif if ( pLocalPlayer->FInViewCone( EyePosition() ) ) return false; return true; } return bBase; } //----------------------------------------------------------------------------- // // Schedules // //----------------------------------------------------------------------------- AI_BEGIN_CUSTOM_NPC( player_companion_base, CNPC_PlayerCompanion ) // AI Interaction for being hit by a physics object DECLARE_INTERACTION(g_interactionHitByPlayerThrownPhysObj) DECLARE_INTERACTION(g_interactionPlayerPuntedHeavyObject) DECLARE_CONDITION( COND_PC_HURTBYFIRE ) DECLARE_CONDITION( COND_PC_SAFE_FROM_MORTAR ) DECLARE_CONDITION( COND_PC_BECOMING_PASSENGER ) DECLARE_TASK( TASK_PC_WAITOUT_MORTAR ) DECLARE_TASK( TASK_PC_GET_PATH_OFF_COMPANION ) DECLARE_ANIMEVENT( AE_COMPANION_PRODUCE_FLARE ) DECLARE_ANIMEVENT( AE_COMPANION_LIGHT_FLARE ) DECLARE_ANIMEVENT( AE_COMPANION_RELEASE_FLARE ) //========================================================= // > TakeCoverFromBestSound // // Find cover and move towards it, but only do so for a short // time. This is appropriate when the dangerous item is going // to detonate very soon. This way our NPC doesn't run a great // distance from an object that explodes shortly after the NPC // gets underway. //========================================================= DEFINE_SCHEDULE ( SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FLEE_FROM_BEST_SOUND" " TASK_STOP_MOVING 0" " TASK_SET_TOLERANCE_DISTANCE 24" " TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION 0" " TASK_FIND_COVER_FROM_BEST_SOUND 0" " TASK_RUN_PATH_TIMED 1.0" " TASK_STOP_MOVING 0" " TASK_FACE_SAVEPOSITION 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" // Translated to cover "" " Interrupts" " COND_PC_SAFE_FROM_MORTAR" ) DEFINE_SCHEDULE ( SCHED_PC_TAKE_COVER_FROM_BEST_SOUND, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FLEE_FROM_BEST_SOUND" " TASK_STOP_MOVING 0" " TASK_SET_TOLERANCE_DISTANCE 24" " TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION 0" " TASK_FIND_COVER_FROM_BEST_SOUND 0" " TASK_RUN_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" " TASK_STOP_MOVING 0" " TASK_FACE_SAVEPOSITION 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" // Translated to cover "" " Interrupts" " COND_NEW_ENEMY" " COND_PC_SAFE_FROM_MORTAR" ) DEFINE_SCHEDULE ( SCHED_PC_COWER, " Tasks" " TASK_WAIT_RANDOM 0.1" " TASK_SET_ACTIVITY ACTIVITY:ACT_COWER" " TASK_PC_WAITOUT_MORTAR 0" " TASK_WAIT 0.1" " TASK_WAIT_RANDOM 0.5" "" " Interrupts" " " ) //========================================================= // //========================================================= DEFINE_SCHEDULE ( SCHED_PC_FLEE_FROM_BEST_SOUND, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COWER" " TASK_GET_PATH_AWAY_FROM_BEST_SOUND 600" " TASK_RUN_PATH_TIMED 1.5" " TASK_STOP_MOVING 0" " TASK_TURN_LEFT 179" "" " Interrupts" " COND_NEW_ENEMY" " COND_PC_SAFE_FROM_MORTAR" ) //========================================================= DEFINE_SCHEDULE ( SCHED_PC_FAIL_TAKE_COVER_TURRET, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COWER" " TASK_STOP_MOVING 0" " TASK_MOVE_AWAY_PATH 600" " TASK_RUN_PATH_FLEE 100" " TASK_STOP_MOVING 0" " TASK_TURN_LEFT 179" "" " Interrupts" " COND_NEW_ENEMY" ) //========================================================= DEFINE_SCHEDULE ( SCHED_PC_FAKEOUT_MORTAR, " Tasks" " TASK_MOVE_AWAY_PATH 300" " TASK_RUN_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" "" " Interrupts" " COND_HEAR_DANGER" ) //========================================================= DEFINE_SCHEDULE ( SCHED_PC_GET_OFF_COMPANION, " Tasks" " TASK_PC_GET_PATH_OFF_COMPANION 0" " TASK_RUN_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" "" " Interrupts" "" ) AI_END_CUSTOM_NPC() // // Special movement overrides for player companions // #define NUM_OVERRIDE_MOVE_CLASSNAMES 4 class COverrideMoveCache : public IEntityListener { public: void LevelInitPreEntity( void ) { CacheClassnames(); gEntList.AddListenerEntity( this ); Clear(); } void LevelShutdownPostEntity( void ) { gEntList.RemoveListenerEntity( this ); Clear(); } inline void Clear( void ) { m_Cache.Purge(); } inline bool MatchesCriteria( CBaseEntity *pEntity ) { for ( int i = 0; i < NUM_OVERRIDE_MOVE_CLASSNAMES; i++ ) { if ( pEntity->m_iClassname == m_Classname[i] ) return true; } return false; } virtual void OnEntitySpawned( CBaseEntity *pEntity ) { if ( MatchesCriteria( pEntity ) ) { m_Cache.AddToTail( pEntity ); } }; virtual void OnEntityDeleted( CBaseEntity *pEntity ) { if ( !m_Cache.Count() ) return; if ( MatchesCriteria( pEntity ) ) { m_Cache.FindAndRemove( pEntity ); } }; CBaseEntity *FindTargetsInRadius( CBaseEntity *pFirstEntity, const Vector &vecOrigin, float flRadius ) { if ( !m_Cache.Count() ) return NULL; int nIndex = m_Cache.InvalidIndex(); // If we're starting with an entity, start there and move past it if ( pFirstEntity != NULL ) { nIndex = m_Cache.Find( pFirstEntity ); nIndex = m_Cache.Next( nIndex ); if ( nIndex == m_Cache.InvalidIndex() ) return NULL; } else { nIndex = m_Cache.Head(); } CBaseEntity *pTarget = NULL; const float flRadiusSqr = Square( flRadius ); // Look through each cached target, looking for one in our range while ( nIndex != m_Cache.InvalidIndex() ) { pTarget = m_Cache[nIndex]; if ( pTarget && ( pTarget->GetAbsOrigin() - vecOrigin ).LengthSqr() < flRadiusSqr ) return pTarget; nIndex = m_Cache.Next( nIndex ); } return NULL; } void ForceRepopulateList( void ) { Clear(); CacheClassnames(); CBaseEntity *pEnt = gEntList.FirstEnt(); while( pEnt ) { if( MatchesCriteria( pEnt ) ) { m_Cache.AddToTail( pEnt ); } pEnt = gEntList.NextEnt( pEnt ); } } private: inline void CacheClassnames( void ) { m_Classname[0] = AllocPooledString( "env_fire" ); m_Classname[1] = AllocPooledString( "combine_mine" ); m_Classname[2] = AllocPooledString( "npc_turret_floor" ); m_Classname[3] = AllocPooledString( "entityflame" ); } CUtlLinkedList<EHANDLE> m_Cache; string_t m_Classname[NUM_OVERRIDE_MOVE_CLASSNAMES]; }; // Singleton for access COverrideMoveCache g_OverrideMoveCache; COverrideMoveCache *OverrideMoveCache( void ) { return &g_OverrideMoveCache; } CBaseEntity *OverrideMoveCache_FindTargetsInRadius( CBaseEntity *pFirstEntity, const Vector &vecOrigin, float flRadius ) { return g_OverrideMoveCache.FindTargetsInRadius( pFirstEntity, vecOrigin, flRadius ); } void OverrideMoveCache_ForceRepopulateList( void ) { g_OverrideMoveCache.ForceRepopulateList(); } void OverrideMoveCache_LevelInitPreEntity( void ) { g_OverrideMoveCache.LevelInitPreEntity(); } void OverrideMoveCache_LevelShutdownPostEntity( void ) { g_OverrideMoveCache.LevelShutdownPostEntity(); }
0
0.989449
1
0.989449
game-dev
MEDIA
0.989708
game-dev
0.816937
1
0.816937
GNOME/gnumeric
1,285
src/gnm-marshalers.list
# see glib-genmarshal(1) for a detailed description of the file format, # possible parameter types are: # VOID indicates no return type, or no extra # parameters. if VOID is used as the parameter # list, no additional parameters may be present. # BOOLEAN for boolean types (gboolean) # CHAR for signed char types (gchar) # UCHAR for unsigned char types (guchar) # INT for signed integer types (gint) # UINT for unsigned integer types (guint) # LONG for signed long integer types (glong) # ULONG for unsigned long integer types (gulong) # ENUM for enumeration types (gint) # FLAGS for flag enumeration types (guint) # FLOAT for single-precision float types (gfloat) # DOUBLE for double-precision float types (gdouble) # STRING for string types (gchar*) # BOXED for boxed (anonymous but reference counted) types (GBoxed*) # POINTER for anonymous pointer types (gpointer) # OBJECT for GObject or derived types (GObject*) # NONE deprecated alias for VOID # BOOL deprecated alias for BOOLEAN BOOLEAN:POINTER BOOLEAN:OBJECT,POINTER VOID:BOOLEAN,INT BOOLEAN:VOID INT:POINTER,BOOLEAN BOXED:BOXED,BOXED,BOXED
0
0.912547
1
0.912547
game-dev
MEDIA
0.282276
game-dev
0.626984
1
0.626984
Ragebones/StormCore
109,893
src/server/game/Entities/Object/Object.cpp
/* * Copyright (C) 2014-2017 StormCore * * 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/>. */ #include "Object.h" #include "Common.h" #include "SharedDefines.h" #include "WorldPacket.h" #include "Opcodes.h" #include "Log.h" #include "World.h" #include "Creature.h" #include "Player.h" #include "Vehicle.h" #include "ObjectMgr.h" #include "UpdateData.h" #include "Util.h" #include "ObjectAccessor.h" #include "Transport.h" #include "VMapFactory.h" #include "CellImpl.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "SpellAuraEffects.h" #include "UpdateFieldFlags.h" #include "TemporarySummon.h" #include "Totem.h" #include "MovementPackets.h" #include "OutdoorPvPMgr.h" #include "Unit.h" #include "BattlefieldMgr.h" #include "MiscPackets.h" #include "InstanceScenario.h" #include "AreaTriggerTemplate.h" Object::Object() { m_objectTypeId = TYPEID_OBJECT; m_objectType = TYPEMASK_OBJECT; m_updateFlag = UPDATEFLAG_NONE; m_uint32Values = nullptr; _dynamicValues = nullptr; _dynamicChangesArrayMask = nullptr; m_valuesCount = 0; _dynamicValuesCount = 0; _fieldNotifyFlags = UF_FLAG_DYNAMIC; m_inWorld = false; m_objectUpdated = false; } WorldObject::~WorldObject() { // this may happen because there are many !create/delete if (IsWorldObject() && m_currMap) { if (GetTypeId() == TYPEID_CORPSE) { TC_LOG_FATAL("misc", "WorldObject::~WorldObject Corpse Type: %d (%s) deleted but still in map!!", ToCorpse()->GetType(), GetGUID().ToString().c_str()); ABORT(); } ResetMap(); } } Object::~Object() { if (IsInWorld()) { TC_LOG_FATAL("misc", "Object::~Object %s deleted but still in world!!", GetGUID().ToString().c_str()); if (isType(TYPEMASK_ITEM)) TC_LOG_FATAL("misc", "Item slot %u", ((Item*)this)->GetSlot()); ABORT(); } if (m_objectUpdated) { TC_LOG_FATAL("misc", "Object::~Object %s deleted but still in update list!!", GetGUID().ToString().c_str()); ABORT(); } delete[] m_uint32Values; m_uint32Values = nullptr; delete[] _dynamicValues; _dynamicValues = nullptr; delete[] _dynamicChangesArrayMask; _dynamicChangesArrayMask = nullptr; } void Object::_InitValues() { m_uint32Values = new uint32[m_valuesCount]; memset(m_uint32Values, 0, m_valuesCount * sizeof(uint32)); _changesMask.resize(m_valuesCount); _dynamicChangesMask.resize(_dynamicValuesCount); if (_dynamicValuesCount) { _dynamicValues = new std::vector<uint32>[_dynamicValuesCount]; _dynamicChangesArrayMask = new std::vector<uint8>[_dynamicValuesCount]; } m_objectUpdated = false; } void Object::_Create(ObjectGuid const& guid) { if (!m_uint32Values) _InitValues(); SetGuidValue(OBJECT_FIELD_GUID, guid); SetUInt16Value(OBJECT_FIELD_TYPE, 0, m_objectType); m_PackGUID.Set(guid); } std::string Object::_ConcatFields(uint16 startIndex, uint16 size) const { std::ostringstream ss; for (uint16 index = 0; index < size; ++index) ss << GetUInt32Value(index + startIndex) << ' '; return ss.str(); } void Object::AddToWorld() { if (m_inWorld) return; ASSERT(m_uint32Values); m_inWorld = true; // synchronize values mirror with values array (changes will send in updatecreate opcode any way ASSERT(!m_objectUpdated); ClearUpdateMask(false); } void Object::RemoveFromWorld() { if (!m_inWorld) return; m_inWorld = false; // if we remove from world then sending changes not required ClearUpdateMask(true); } void Object::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const { if (!target) return; uint8 updateType = UPDATETYPE_CREATE_OBJECT; uint32 flags = m_updateFlag; /** lower flag1 **/ if (target == this) // building packet for yourself flags |= UPDATEFLAG_SELF; switch (GetGUID().GetHigh()) { case HighGuid::Player: case HighGuid::Pet: case HighGuid::Corpse: case HighGuid::DynamicObject: case HighGuid::AreaTrigger: updateType = UPDATETYPE_CREATE_OBJECT2; break; case HighGuid::Creature: case HighGuid::Vehicle: { if (TempSummon const* summon = ToUnit()->ToTempSummon()) if (summon->GetSummonerGUID().IsPlayer()) updateType = UPDATETYPE_CREATE_OBJECT2; break; } case HighGuid::GameObject: { if (ToGameObject()->GetOwnerGUID().IsPlayer()) updateType = UPDATETYPE_CREATE_OBJECT2; break; } default: break; } if (WorldObject const* worldObject = dynamic_cast<WorldObject const*>(this)) { if (!(flags & UPDATEFLAG_LIVING)) if (!worldObject->m_movementInfo.transport.guid.IsEmpty()) flags |= UPDATEFLAG_TRANSPORT_POSITION; if (worldObject->GetAIAnimKitId() || worldObject->GetMovementAnimKitId() || worldObject->GetMeleeAnimKitId()) flags |= UPDATEFLAG_ANIMKITS; } if (flags & UPDATEFLAG_STATIONARY_POSITION) { // UPDATETYPE_CREATE_OBJECT2 for some gameobject types... if (isType(TYPEMASK_GAMEOBJECT)) { switch (ToGameObject()->GetGoType()) { case GAMEOBJECT_TYPE_TRAP: case GAMEOBJECT_TYPE_DUEL_ARBITER: case GAMEOBJECT_TYPE_FLAGSTAND: case GAMEOBJECT_TYPE_FLAGDROP: updateType = UPDATETYPE_CREATE_OBJECT2; break; default: break; } } } if (Unit const* unit = ToUnit()) if (unit->GetVictim()) flags |= UPDATEFLAG_HAS_TARGET; ByteBuffer buf(0x400); buf << uint8(updateType); buf << GetPackGUID(); buf << uint8(m_objectTypeId); BuildMovementUpdate(&buf, flags); BuildValuesUpdate(updateType, &buf, target); BuildDynamicValuesUpdate(updateType, &buf, target); data->AddUpdateBlock(buf); } void Object::SendUpdateToPlayer(Player* player) { // send create update to player UpdateData upd(player->GetMapId()); WorldPacket packet; if (player->HaveAtClient(this)) BuildValuesUpdateBlockForPlayer(&upd, player); else BuildCreateUpdateBlockForPlayer(&upd, player); upd.BuildPacket(&packet); player->GetSession()->SendPacket(&packet); } void Object::BuildValuesUpdateBlockForPlayer(UpdateData* data, Player* target) const { ByteBuffer buf(500); buf << uint8(UPDATETYPE_VALUES); buf << GetPackGUID(); BuildValuesUpdate(UPDATETYPE_VALUES, &buf, target); BuildDynamicValuesUpdate(UPDATETYPE_VALUES, &buf, target); data->AddUpdateBlock(buf); } void Object::BuildOutOfRangeUpdateBlock(UpdateData* data) const { data->AddOutOfRangeGUID(GetGUID()); } void Object::DestroyForPlayer(Player* target) const { ASSERT(target); UpdateData updateData(target->GetMapId()); BuildOutOfRangeUpdateBlock(&updateData); WorldPacket packet; updateData.BuildPacket(&packet); target->SendDirectMessage(&packet); } int32 Object::GetInt32Value(uint16 index) const { ASSERT(index < m_valuesCount || PrintIndexError(index, false)); return m_int32Values[index]; } uint32 Object::GetUInt32Value(uint16 index) const { ASSERT(index < m_valuesCount || PrintIndexError(index, false)); return m_uint32Values[index]; } uint64 Object::GetUInt64Value(uint16 index) const { ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, false)); return *((uint64*)&(m_uint32Values[index])); } float Object::GetFloatValue(uint16 index) const { ASSERT(index < m_valuesCount || PrintIndexError(index, false)); return m_floatValues[index]; } uint8 Object::GetByteValue(uint16 index, uint8 offset) const { ASSERT(index < m_valuesCount || PrintIndexError(index, false)); ASSERT(offset < 4); return *(((uint8*)&m_uint32Values[index])+offset); } uint16 Object::GetUInt16Value(uint16 index, uint8 offset) const { ASSERT(index < m_valuesCount || PrintIndexError(index, false)); ASSERT(offset < 2); return *(((uint16*)&m_uint32Values[index])+offset); } ObjectGuid const& Object::GetGuidValue(uint16 index) const { ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, false)); return *((ObjectGuid*)&(m_uint32Values[index])); } void Object::BuildMovementUpdate(ByteBuffer* data, uint32 flags) const { bool NoBirthAnim = false; bool EnablePortals = false; bool PlayHoverAnim = false; bool HasMovementUpdate = (flags & UPDATEFLAG_LIVING) != 0; bool HasMovementTransport = (flags & UPDATEFLAG_TRANSPORT_POSITION) != 0; bool Stationary = (flags & UPDATEFLAG_STATIONARY_POSITION) != 0; bool CombatVictim = (flags & UPDATEFLAG_HAS_TARGET) != 0; bool ServerTime = (flags & UPDATEFLAG_TRANSPORT) != 0; bool VehicleCreate = (flags & UPDATEFLAG_VEHICLE) != 0; bool AnimKitCreate = (flags & UPDATEFLAG_ANIMKITS) != 0; bool Rotation = (flags & UPDATEFLAG_ROTATION) != 0; bool HasAreaTrigger = (flags & UPDATEFLAG_AREATRIGGER) != 0; bool HasGameObject = false; bool ThisIsYou = (flags & UPDATEFLAG_SELF) != 0; bool SmoothPhasing = false; bool SceneObjCreate = false; bool PlayerCreateData = false; uint32 PauseTimesCount = 0; if (GameObject const* go = ToGameObject()) if (go->GetGoType() == GAMEOBJECT_TYPE_TRANSPORT) PauseTimesCount = go->GetGOValue()->Transport.StopFrames->size(); data->WriteBit(NoBirthAnim); data->WriteBit(EnablePortals); data->WriteBit(PlayHoverAnim); data->WriteBit(HasMovementUpdate); data->WriteBit(HasMovementTransport); data->WriteBit(Stationary); data->WriteBit(CombatVictim); data->WriteBit(ServerTime); data->WriteBit(VehicleCreate); data->WriteBit(AnimKitCreate); data->WriteBit(Rotation); data->WriteBit(HasAreaTrigger); data->WriteBit(HasGameObject); data->WriteBit(SmoothPhasing); data->WriteBit(ThisIsYou); data->WriteBit(SceneObjCreate); data->WriteBit(PlayerCreateData); data->FlushBits(); if (HasMovementUpdate) { Unit const* unit = ToUnit(); bool HasFallDirection = unit->HasUnitMovementFlag(MOVEMENTFLAG_FALLING); bool HasFall = HasFallDirection || unit->m_movementInfo.jump.fallTime != 0; bool HasSpline = unit->IsSplineEnabled(); *data << GetPackGUID(); // MoverGUID *data << uint32(unit->m_movementInfo.time); // MoveTime *data << float(unit->GetPositionX()); *data << float(unit->GetPositionY()); *data << float(unit->GetPositionZ()); *data << float(unit->GetOrientation()); *data << float(unit->m_movementInfo.pitch); // Pitch *data << float(unit->m_movementInfo.splineElevation); // StepUpStartElevation *data << uint32(0); // RemoveForcesIDs.size() *data << uint32(0); // MoveIndex //for (std::size_t i = 0; i < RemoveForcesIDs.size(); ++i) // *data << ObjectGuid(RemoveForcesIDs); data->WriteBits(unit->GetUnitMovementFlags(), 30); data->WriteBits(unit->GetExtraUnitMovementFlags(), 18); data->WriteBit(!unit->m_movementInfo.transport.guid.IsEmpty()); // HasTransport data->WriteBit(HasFall); // HasFall data->WriteBit(HasSpline); // HasSpline - marks that the unit uses spline movement data->WriteBit(0); // HeightChangeFailed data->WriteBit(0); // RemoteTimeValid if (!unit->m_movementInfo.transport.guid.IsEmpty()) *data << unit->m_movementInfo.transport; if (HasFall) { *data << uint32(unit->m_movementInfo.jump.fallTime); // Time *data << float(unit->m_movementInfo.jump.zspeed); // JumpVelocity if (data->WriteBit(HasFallDirection)) { *data << float(unit->m_movementInfo.jump.sinAngle); // Direction *data << float(unit->m_movementInfo.jump.cosAngle); *data << float(unit->m_movementInfo.jump.xyspeed); // Speed } } *data << float(unit->GetSpeed(MOVE_WALK)); *data << float(unit->GetSpeed(MOVE_RUN)); *data << float(unit->GetSpeed(MOVE_RUN_BACK)); *data << float(unit->GetSpeed(MOVE_SWIM)); *data << float(unit->GetSpeed(MOVE_SWIM_BACK)); *data << float(unit->GetSpeed(MOVE_FLIGHT)); *data << float(unit->GetSpeed(MOVE_FLIGHT_BACK)); *data << float(unit->GetSpeed(MOVE_TURN_RATE)); *data << float(unit->GetSpeed(MOVE_PITCH_RATE)); *data << uint32(0); // unit->m_movementInfo.forces.size() data->WriteBit(HasSpline); data->FlushBits(); //for (std::size_t i = 0; i < unit->m_movementInfo.forces.size(); ++i) //{ // *data << ObjectGuid(ID); // *data << Vector3(Origin); // *data << Vector3(Direction); // *data << int32(TransportID); // *data << float(Magnitude); // data->WriteBits(Type, 2); //} if (HasSpline) WorldPackets::Movement::CommonMovement::WriteCreateObjectSplineDataBlock(*unit->movespline, *data); } *data << uint32(PauseTimesCount); if (Stationary) { WorldObject const* self = static_cast<WorldObject const*>(this); *data << float(self->GetStationaryX()); *data << float(self->GetStationaryY()); *data << float(self->GetStationaryZ()); *data << float(self->GetStationaryO()); } if (CombatVictim) *data << ToUnit()->GetVictim()->GetGUID(); // CombatVictim if (ServerTime) { GameObject const* go = ToGameObject(); /** @TODO Use IsTransport() to also handle type 11 (TRANSPORT) Currently grid objects are not updated if there are no nearby players, this causes clients to receive different PathProgress resulting in players seeing the object in a different position */ if (go && go->ToTransport()) // ServerTime *data << uint32(go->GetGOValue()->Transport.PathProgress); else *data << uint32(getMSTime()); } if (VehicleCreate) { Unit const* unit = ToUnit(); *data << uint32(unit->GetVehicleKit()->GetVehicleInfo()->ID); // RecID *data << float(unit->GetOrientation()); // InitialRawFacing } if (AnimKitCreate) { WorldObject const* self = static_cast<WorldObject const*>(this); *data << uint16(self->GetAIAnimKitId()); // AiID *data << uint16(self->GetMovementAnimKitId()); // MovementID *data << uint16(self->GetMeleeAnimKitId()); // MeleeID } if (Rotation) *data << uint64(ToGameObject()->GetPackedWorldRotation()); // Rotation if (GameObject const* go = ToGameObject()) for (uint32 i = 0; i < PauseTimesCount; ++i) *data << uint32(go->GetGOValue()->Transport.StopFrames->at(i)); if (HasMovementTransport) { WorldObject const* self = static_cast<WorldObject const*>(this); *data << self->m_movementInfo.transport; } if (HasAreaTrigger) { AreaTrigger const* areaTrigger = ToAreaTrigger(); AreaTriggerMiscTemplate const* areaTriggerMiscTemplate = areaTrigger->GetMiscTemplate(); AreaTriggerTemplate const* areaTriggerTemplate = areaTrigger->GetTemplate(); *data << uint32(areaTrigger->GetTimeSinceCreated()); *data << areaTrigger->GetRollPitchYaw(); bool hasAbsoluteOrientation = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_HAS_ABSOLUTE_ORIENTATION); bool hasDynamicShape = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_HAS_DYNAMIC_SHAPE); bool hasAttached = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_HAS_ATTACHED); bool hasFaceMovementDir = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_HAS_FACE_MOVEMENT_DIR); bool hasFollowsTerrain = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_HAS_FOLLOWS_TERRAIN); bool hasUnk1 = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_UNK1); bool hasTargetRollPitchYaw = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_HAS_TARGET_ROLL_PITCH_YAW); bool hasScaleCurveID = areaTriggerMiscTemplate->ScaleCurveId != 0; bool hasMorphCurveID = areaTriggerMiscTemplate->MorphCurveId != 0; bool hasFacingCurveID = areaTriggerMiscTemplate->FacingCurveId != 0; bool hasMoveCurveID = areaTriggerMiscTemplate->MoveCurveId != 0; bool hasUnk2 = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_UNK2); bool hasUnk3 = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_UNK3); bool hasUnk4 = areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_UNK4); bool hasAreaTriggerSphere = areaTriggerTemplate->IsSphere(); bool hasAreaTriggerBox = areaTriggerTemplate->IsBox(); bool hasAreaTriggerPolygon = areaTriggerTemplate->IsPolygon(); bool hasAreaTriggerCylinder = areaTriggerTemplate->IsCylinder(); bool hasAreaTriggerSpline = areaTrigger->HasSplines(); bool hasAreaTriggerUnkType = false; // areaTriggerTemplate->HasFlag(AREATRIGGER_FLAG_UNK5); data->WriteBit(hasAbsoluteOrientation); data->WriteBit(hasDynamicShape); data->WriteBit(hasAttached); data->WriteBit(hasFaceMovementDir); data->WriteBit(hasFollowsTerrain); data->WriteBit(hasUnk1); data->WriteBit(hasTargetRollPitchYaw); data->WriteBit(hasScaleCurveID); data->WriteBit(hasMorphCurveID); data->WriteBit(hasFacingCurveID); data->WriteBit(hasMoveCurveID); data->WriteBit(hasUnk2); data->WriteBit(hasUnk3); data->WriteBit(hasUnk4); data->WriteBit(hasAreaTriggerSphere); data->WriteBit(hasAreaTriggerBox); data->WriteBit(hasAreaTriggerPolygon); data->WriteBit(hasAreaTriggerCylinder); data->WriteBit(hasAreaTriggerSpline); data->WriteBit(hasAreaTriggerUnkType); if (hasUnk3) data->WriteBit(0); data->FlushBits(); if (hasAreaTriggerSpline) { std::vector<G3D::Vector3> const& splinePoints = areaTrigger->GetSpline().getPoints(); *data << uint32(areaTrigger->GetTimeToTarget()); *data << uint32(areaTrigger->GetElapsedTimeForMovement()); data->WriteBits(splinePoints.size(), 16); for (G3D::Vector3 const& spline : splinePoints) *data << spline; } if (hasTargetRollPitchYaw) *data << areaTrigger->GetTargetRollPitchYaw(); if (hasScaleCurveID) *data << uint32(areaTriggerMiscTemplate->ScaleCurveId); if (hasMorphCurveID) *data << uint32(areaTriggerMiscTemplate->MorphCurveId); if (hasFacingCurveID) *data << uint32(areaTriggerMiscTemplate->FacingCurveId); if (hasMoveCurveID) *data << uint32(areaTriggerMiscTemplate->MoveCurveId); if (hasUnk2) *data << int32(0); if (hasUnk4) *data << uint32(0); if (hasAreaTriggerSphere) { *data << float(areaTriggerTemplate->SphereDatas.Radius); *data << float(areaTriggerTemplate->SphereDatas.RadiusTarget); } if (hasAreaTriggerBox) { *data << float(areaTriggerTemplate->BoxDatas.Extents[0]); *data << float(areaTriggerTemplate->BoxDatas.Extents[1]); *data << float(areaTriggerTemplate->BoxDatas.Extents[2]); *data << float(areaTriggerTemplate->BoxDatas.ExtentsTarget[0]); *data << float(areaTriggerTemplate->BoxDatas.ExtentsTarget[1]); *data << float(areaTriggerTemplate->BoxDatas.ExtentsTarget[2]); } if (hasAreaTriggerPolygon) { *data << int32(areaTriggerTemplate->PolygonVertices.size()); *data << int32(areaTriggerTemplate->PolygonVerticesTarget.size()); *data << float(areaTriggerTemplate->PolygonDatas.Height); *data << float(areaTriggerTemplate->PolygonDatas.HeightTarget); for (G3D::Vector2 const& vertice : areaTriggerTemplate->PolygonVertices) *data << vertice; for (G3D::Vector2 const& vertice : areaTriggerTemplate->PolygonVerticesTarget) *data << vertice; } if (hasAreaTriggerCylinder) { *data << float(areaTriggerTemplate->CylinderDatas.Radius); *data << float(areaTriggerTemplate->CylinderDatas.RadiusTarget); *data << float(areaTriggerTemplate->CylinderDatas.Height); *data << float(areaTriggerTemplate->CylinderDatas.HeightTarget); *data << float(areaTriggerTemplate->CylinderDatas.LocationZOffset); *data << float(areaTriggerTemplate->CylinderDatas.LocationZOffsetTarget); } if (hasAreaTriggerUnkType) { /*packet.ResetBitReader(); var unk1 = packet.ReadBit("AreaTriggerUnk1"); var hasCenter = packet.ReadBit("HasCenter", index); packet.ReadBit("Unk bit 703 1", index); packet.ReadBit("Unk bit 703 2", index); packet.ReadUInt32(); packet.ReadInt32(); packet.ReadUInt32(); packet.ReadSingle("Radius", index); packet.ReadSingle("BlendFromRadius", index); packet.ReadSingle("InitialAngel", index); packet.ReadSingle("ZOffset", index); if (unk1) packet.ReadPackedGuid128("AreaTriggerUnkGUID", index); if (hasCenter) packet.ReadVector3("Center", index);*/ } } //if (GameObject) //{ // *data << uint32(WorldEffectID); // data->WriteBit(bit8); // if (bit8) // *data << uint32(Int1); //} //if (SmoothPhasing) //{ // data->WriteBit(ReplaceActive); // data->WriteBit(HasReplaceObjectt); // if (HasReplaceObject) // *data << ObjectGuid(ReplaceObject); //} //if (SceneObjCreate) //{ // data->WriteBit(HasLocalScriptData); // data->WriteBit(HasPetBattleFullUpdate); // if (HasLocalScriptData) // { // data->WriteBits(Data.length(), 7); // data->WriteString(Data); // } // if (HasPetBattleFullUpdate) // { // for (std::size_t i = 0; i < 2; ++i) // { // *data << ObjectGuid(Players[i].CharacterID); // *data << int32(Players[i].TrapAbilityID); // *data << int32(Players[i].TrapStatus); // *data << uint16(Players[i].RoundTimeSecs); // *data << int8(Players[i].FrontPet); // *data << uint8(Players[i].InputFlags); // data->WriteBits(Players[i].Pets.size(), 2); // for (std::size_t j = 0; j < Players[i].Pets.size(); ++j) // { // *data << ObjectGuid(Players[i].Pets[j].BattlePetGUID); // *data << int32(Players[i].Pets[j].SpeciesID); // *data << int32(Players[i].Pets[j].DisplayID); // *data << int32(Players[i].Pets[j].CollarID); // *data << int16(Players[i].Pets[j].Level); // *data << int16(Players[i].Pets[j].Xp); // *data << int32(Players[i].Pets[j].CurHealth); // *data << int32(Players[i].Pets[j].MaxHealth); // *data << int32(Players[i].Pets[j].Power); // *data << int32(Players[i].Pets[j].Speed); // *data << int32(Players[i].Pets[j].NpcTeamMemberID); // *data << uint16(Players[i].Pets[j].BreedQuality); // *data << uint16(Players[i].Pets[j].StatusFlags); // *data << int8(Players[i].Pets[j].Slot); // *data << uint32(Players[i].Pets[j].Abilities.size()); // *data << uint32(Players[i].Pets[j].Auras.size()); // *data << uint32(Players[i].Pets[j].States.size()); // for (std::size_t k = 0; k < Players[i].Pets[j].Abilities.size(); ++k) // { // *data << int32(Players[i].Pets[j].Abilities[k].AbilityID); // *data << int16(Players[i].Pets[j].Abilities[k].CooldownRemaining); // *data << int16(Players[i].Pets[j].Abilities[k].LockdownRemaining); // *data << int8(Players[i].Pets[j].Abilities[k].AbilityIndex); // *data << uint8(Players[i].Pets[j].Abilities[k].Pboid); // } // for (std::size_t k = 0; k < Players[i].Pets[j].Auras.size(); ++k) // { // *data << int32(Players[i].Pets[j].Auras[k].AbilityID); // *data << uint32(Players[i].Pets[j].Auras[k].InstanceID); // *data << int32(Players[i].Pets[j].Auras[k].RoundsRemaining); // *data << int32(Players[i].Pets[j].Auras[k].CurrentRound); // *data << uint8(Players[i].Pets[j].Auras[k].CasterPBOID); // } // for (std::size_t k = 0; k < Players[i].Pets[j].States.size(); ++k) // { // *data << uint32(Players[i].Pets[j].States[k].StateID); // *data << int32(Players[i].Pets[j].States[k].StateValue); // } // data->WriteBits(Players[i].Pets[j].CustomName.length(), 7); // data->WriteString(Players[i].Pets[j].CustomName); // } // } // for (std::size_t i = 0; i < 3; ++i) // { // *data << uint32(Enviros[j].Auras.size()); // *data << uint32(Enviros[j].States.size()); // for (std::size_t j = 0; j < Enviros[j].Auras.size(); ++j) // { // *data << int32(Enviros[j].Auras[j].AbilityID); // *data << uint32(Enviros[j].Auras[j].InstanceID); // *data << int32(Enviros[j].Auras[j].RoundsRemaining); // *data << int32(Enviros[j].Auras[j].CurrentRound); // *data << uint8(Enviros[j].Auras[j].CasterPBOID); // } // for (std::size_t j = 0; j < Enviros[j].States.size(); ++j) // { // *data << uint32(Enviros[i].States[j].StateID); // *data << int32(Enviros[i].States[j].StateValue); // } // } // *data << uint16(WaitingForFrontPetsMaxSecs); // *data << uint16(PvpMaxRoundTime); // *data << int32(CurRound); // *data << uint32(NpcCreatureID); // *data << uint32(NpcDisplayID); // *data << int8(CurPetBattleState); // *data << uint8(ForfeitPenalty); // *data << ObjectGuid(InitialWildPetGUID); // data->WriteBit(IsPVP); // data->WriteBit(CanAwardXP); // } //} //if (PlayerCreateData) //{ // data->WriteBit(HasSceneInstanceIDs); // data->WriteBit(HasRuneState); // if (HasSceneInstanceIDs) // { // *data << uint32(SceneInstanceIDs.size()); // for (std::size_t i = 0; i < SceneInstanceIDs.size(); ++i) // *data << uint32(SceneInstanceIDs[i]); // } // if (HasRuneState) // { // *data << uint8(RechargingRuneMask); // *data << uint8(UsableRuneMask); // *data << uint32(ToUnit()->GetMaxPower(POWER_RUNES)); // for (uint32 i = 0; i < ToUnit()->GetMaxPower(POWER_RUNES); ++i) // *data << uint8(255 - (ToUnit()->ToPlayer()->GetRuneCooldown(i) * 51)); // } //} } void Object::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* target) const { if (!target) return; std::size_t blockCount = UpdateMask::GetBlockCount(m_valuesCount); uint32* flags = NULL; uint32 visibleFlag = GetUpdateFieldData(target, flags); ASSERT(flags); *data << uint8(blockCount); std::size_t maskPos = data->wpos(); data->resize(data->size() + blockCount * sizeof(UpdateMask::BlockType)); for (uint16 index = 0; index < m_valuesCount; ++index) { if (_fieldNotifyFlags & flags[index] || ((updateType == UPDATETYPE_VALUES ? _changesMask[index] : m_uint32Values[index]) && (flags[index] & visibleFlag))) { UpdateMask::SetUpdateBit(data->contents() + maskPos, index); *data << m_uint32Values[index]; } } } void Object::BuildDynamicValuesUpdate(uint8 updateType, ByteBuffer* data, Player* target) const { if (!target) return; std::size_t blockCount = UpdateMask::GetBlockCount(_dynamicValuesCount); uint32* flags = nullptr; uint32 visibleFlag = GetDynamicUpdateFieldData(target, flags); *data << uint8(blockCount); std::size_t maskPos = data->wpos(); data->resize(data->size() + blockCount * sizeof(UpdateMask::BlockType)); for (uint16 index = 0; index < _dynamicValuesCount; ++index) { std::vector<uint32> const& values = _dynamicValues[index]; if (_fieldNotifyFlags & flags[index] || ((updateType == UPDATETYPE_VALUES ? _dynamicChangesMask[index] != UpdateMask::UNCHANGED : !values.empty()) && (flags[index] & visibleFlag))) { UpdateMask::SetUpdateBit(data->contents() + maskPos, index); std::size_t arrayBlockCount = UpdateMask::GetBlockCount(values.size()); *data << uint16(UpdateMask::EncodeDynamicFieldChangeType(arrayBlockCount, _dynamicChangesMask[index], updateType)); if (_dynamicChangesMask[index] == UpdateMask::VALUE_AND_SIZE_CHANGED && updateType == UPDATETYPE_VALUES) *data << uint32(values.size()); std::size_t arrayMaskPos = data->wpos(); data->resize(data->size() + arrayBlockCount * sizeof(UpdateMask::BlockType)); for (std::size_t v = 0; v < values.size(); ++v) { if (updateType != UPDATETYPE_VALUES || _dynamicChangesArrayMask[index][v]) { UpdateMask::SetUpdateBit(data->contents() + arrayMaskPos, v); *data << uint32(values[v]); } } } } } void Object::AddToObjectUpdateIfNeeded() { if (m_inWorld && !m_objectUpdated) { AddToObjectUpdate(); m_objectUpdated = true; } } void Object::ClearUpdateMask(bool remove) { memset(_changesMask.data(), 0, _changesMask.size()); _dynamicChangesMask.assign(_dynamicChangesMask.size(), UpdateMask::UNCHANGED); for (uint32 i = 0; i < _dynamicValuesCount; ++i) memset(_dynamicChangesArrayMask[i].data(), 0, _dynamicChangesArrayMask[i].size()); if (m_objectUpdated) { if (remove) RemoveFromObjectUpdate(); m_objectUpdated = false; } } void Object::BuildFieldsUpdate(Player* player, UpdateDataMapType& data_map) const { UpdateDataMapType::iterator iter = data_map.find(player); if (iter == data_map.end()) { std::pair<UpdateDataMapType::iterator, bool> p = data_map.emplace(player, UpdateData(player->GetMapId())); ASSERT(p.second); iter = p.first; } BuildValuesUpdateBlockForPlayer(&iter->second, iter->first); } uint32 Object::GetUpdateFieldData(Player const* target, uint32*& flags) const { uint32 visibleFlag = UF_FLAG_PUBLIC; if (target == this) visibleFlag |= UF_FLAG_PRIVATE; switch (GetTypeId()) { case TYPEID_ITEM: case TYPEID_CONTAINER: flags = ItemUpdateFieldFlags; if (((Item const*)this)->GetOwnerGUID() == target->GetGUID()) visibleFlag |= UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER; break; case TYPEID_UNIT: case TYPEID_PLAYER: { Player* plr = ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself(); flags = UnitUpdateFieldFlags; if (ToUnit()->GetOwnerGUID() == target->GetGUID()) visibleFlag |= UF_FLAG_OWNER; if (HasFlag(OBJECT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO)) if (ToUnit()->HasAuraTypeWithCaster(SPELL_AURA_EMPATHY, target->GetGUID())) visibleFlag |= UF_FLAG_SPECIAL_INFO; if (plr && plr->IsInSameRaidWith(target)) visibleFlag |= UF_FLAG_PARTY_MEMBER; break; } case TYPEID_GAMEOBJECT: flags = GameObjectUpdateFieldFlags; if (ToGameObject()->GetOwnerGUID() == target->GetGUID()) visibleFlag |= UF_FLAG_OWNER; break; case TYPEID_DYNAMICOBJECT: flags = DynamicObjectUpdateFieldFlags; if (ToDynObject()->GetCasterGUID() == target->GetGUID()) visibleFlag |= UF_FLAG_OWNER; break; case TYPEID_CORPSE: flags = CorpseUpdateFieldFlags; if (ToCorpse()->GetOwnerGUID() == target->GetGUID()) visibleFlag |= UF_FLAG_OWNER; break; case TYPEID_AREATRIGGER: flags = AreaTriggerUpdateFieldFlags; break; case TYPEID_SCENEOBJECT: flags = SceneObjectUpdateFieldFlags; break; case TYPEID_CONVERSATION: flags = ConversationUpdateFieldFlags; break; case TYPEID_OBJECT: ABORT(); break; } return visibleFlag; } uint32 Object::GetDynamicUpdateFieldData(Player const* target, uint32*& flags) const { uint32 visibleFlag = UF_FLAG_PUBLIC; if (target == this) visibleFlag |= UF_FLAG_PRIVATE; switch (GetTypeId()) { case TYPEID_ITEM: case TYPEID_CONTAINER: flags = ItemDynamicUpdateFieldFlags; if (((Item const*)this)->GetOwnerGUID() == target->GetGUID()) visibleFlag |= UF_FLAG_OWNER | UF_FLAG_ITEM_OWNER; break; case TYPEID_UNIT: case TYPEID_PLAYER: { Player* plr = ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself(); flags = UnitDynamicUpdateFieldFlags; if (ToUnit()->GetOwnerGUID() == target->GetGUID()) visibleFlag |= UF_FLAG_OWNER; if (HasFlag(OBJECT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO)) if (ToUnit()->HasAuraTypeWithCaster(SPELL_AURA_EMPATHY, target->GetGUID())) visibleFlag |= UF_FLAG_SPECIAL_INFO; if (plr && plr->IsInSameRaidWith(target)) visibleFlag |= UF_FLAG_PARTY_MEMBER; break; } case TYPEID_GAMEOBJECT: flags = GameObjectDynamicUpdateFieldFlags; break; case TYPEID_CONVERSATION: flags = ConversationDynamicUpdateFieldFlags; break; default: flags = nullptr; break; } return visibleFlag; } void Object::_LoadIntoDataField(std::string const& data, uint32 startOffset, uint32 count) { if (data.empty()) return; Tokenizer tokens(data, ' ', count); if (tokens.size() != count) return; for (uint32 index = 0; index < count; ++index) { m_uint32Values[startOffset + index] = atoul(tokens[index]); _changesMask[startOffset + index] = 1; } } void Object::SetInt32Value(uint16 index, int32 value) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (m_int32Values[index] != value) { m_int32Values[index] = value; _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::SetUInt32Value(uint16 index, uint32 value) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (m_uint32Values[index] != value) { m_uint32Values[index] = value; _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::UpdateUInt32Value(uint16 index, uint32 value) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); m_uint32Values[index] = value; _changesMask[index] = 1; } void Object::SetUInt64Value(uint16 index, uint64 value) { ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, true)); if (*((uint64*)&(m_uint32Values[index])) != value) { m_uint32Values[index] = PAIR64_LOPART(value); m_uint32Values[index + 1] = PAIR64_HIPART(value); _changesMask[index] = 1; _changesMask[index + 1] = 1; AddToObjectUpdateIfNeeded(); } } bool Object::AddGuidValue(uint16 index, ObjectGuid const& value) { ASSERT(index + 3 < m_valuesCount || PrintIndexError(index, true)); if (!value.IsEmpty() && ((ObjectGuid*)&(m_uint32Values[index]))->IsEmpty()) { *((ObjectGuid*)&(m_uint32Values[index])) = value; _changesMask[index] = 1; _changesMask[index + 1] = 1; _changesMask[index + 2] = 1; _changesMask[index + 3] = 1; AddToObjectUpdateIfNeeded(); return true; } return false; } bool Object::RemoveGuidValue(uint16 index, ObjectGuid const& value) { ASSERT(index + 3 < m_valuesCount || PrintIndexError(index, true)); if (!value.IsEmpty() && *((ObjectGuid*)&(m_uint32Values[index])) == value) { ((ObjectGuid*)&(m_uint32Values[index]))->Clear(); _changesMask[index] = 1; _changesMask[index + 1] = 1; _changesMask[index + 2] = 1; _changesMask[index + 3] = 1; AddToObjectUpdateIfNeeded(); return true; } return false; } void Object::SetFloatValue(uint16 index, float value) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (m_floatValues[index] != value) { m_floatValues[index] = value; _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::SetByteValue(uint16 index, uint8 offset, uint8 value) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 3) { TC_LOG_ERROR("misc", "Object::SetByteValue: wrong offset %u", offset); return; } if (uint8(m_uint32Values[index] >> (offset * 8)) != value) { m_uint32Values[index] &= ~uint32(uint32(0xFF) << (offset * 8)); m_uint32Values[index] |= uint32(uint32(value) << (offset * 8)); _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::SetUInt16Value(uint16 index, uint8 offset, uint16 value) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 1) { TC_LOG_ERROR("misc", "Object::SetUInt16Value: wrong offset %u", offset); return; } if (uint16(m_uint32Values[index] >> (offset * 16)) != value) { m_uint32Values[index] &= ~uint32(uint32(0xFFFF) << (offset * 16)); m_uint32Values[index] |= uint32(uint32(value) << (offset * 16)); _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::SetGuidValue(uint16 index, ObjectGuid const& value) { ASSERT(index + 3 < m_valuesCount || PrintIndexError(index, true)); if (*((ObjectGuid*)&(m_uint32Values[index])) != value) { *((ObjectGuid*)&(m_uint32Values[index])) = value; _changesMask[index] = 1; _changesMask[index + 1] = 1; _changesMask[index + 2] = 1; _changesMask[index + 3] = 1; AddToObjectUpdateIfNeeded(); } } void Object::SetStatFloatValue(uint16 index, float value) { if (value < 0) value = 0.0f; SetFloatValue(index, value); } void Object::SetStatInt32Value(uint16 index, int32 value) { if (value < 0) value = 0; SetUInt32Value(index, uint32(value)); } void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply) { int32 cur = GetUInt32Value(index); cur += (apply ? val : -val); if (cur < 0) cur = 0; SetUInt32Value(index, cur); } void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply) { int32 cur = GetInt32Value(index); cur += (apply ? val : -val); SetInt32Value(index, cur); } void Object::ApplyModUInt16Value(uint16 index, uint8 offset, int16 val, bool apply) { int16 cur = GetUInt16Value(index, offset); cur += (apply ? val : -val); if (cur < 0) cur = 0; SetUInt16Value(index, offset, cur); } void Object::ApplyModSignedFloatValue(uint16 index, float val, bool apply) { float cur = GetFloatValue(index); cur += (apply ? val : -val); SetFloatValue(index, cur); } void Object::ApplyPercentModFloatValue(uint16 index, float val, bool apply) { float value = GetFloatValue(index); ApplyPercentModFloatVar(value, val, apply); SetFloatValue(index, value); } void Object::ApplyModPositiveFloatValue(uint16 index, float val, bool apply) { float cur = GetFloatValue(index); cur += (apply ? val : -val); if (cur < 0) cur = 0; SetFloatValue(index, cur); } void Object::SetFlag(uint16 index, uint32 newFlag) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); uint32 oldval = m_uint32Values[index]; uint32 newval = oldval | newFlag; if (oldval != newval) { m_uint32Values[index] = newval; _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::RemoveFlag(uint16 index, uint32 oldFlag) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); ASSERT(m_uint32Values); uint32 oldval = m_uint32Values[index]; uint32 newval = oldval & ~oldFlag; if (oldval != newval) { m_uint32Values[index] = newval; _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::ToggleFlag(uint16 index, uint32 flag) { if (HasFlag(index, flag)) RemoveFlag(index, flag); else SetFlag(index, flag); } bool Object::HasFlag(uint16 index, uint32 flag) const { if (index >= m_valuesCount && !PrintIndexError(index, false)) return false; return (m_uint32Values[index] & flag) != 0; } void Object::ApplyModFlag(uint16 index, uint32 flag, bool apply) { if (apply) SetFlag(index, flag); else RemoveFlag(index, flag); } void Object::SetByteFlag(uint16 index, uint8 offset, uint8 newFlag) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 3) { TC_LOG_ERROR("misc", "Object::SetByteFlag: wrong offset %u", offset); return; } if (!(uint8(m_uint32Values[index] >> (offset * 8)) & newFlag)) { m_uint32Values[index] |= uint32(uint32(newFlag) << (offset * 8)); _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::RemoveByteFlag(uint16 index, uint8 offset, uint8 oldFlag) { ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 3) { TC_LOG_ERROR("misc", "Object::RemoveByteFlag: wrong offset %u", offset); return; } if (uint8(m_uint32Values[index] >> (offset * 8)) & oldFlag) { m_uint32Values[index] &= ~uint32(uint32(oldFlag) << (offset * 8)); _changesMask[index] = 1; AddToObjectUpdateIfNeeded(); } } void Object::ToggleByteFlag(uint16 index, uint8 offset, uint8 flag) { if (HasByteFlag(index, offset, flag)) RemoveByteFlag(index, offset, flag); else SetByteFlag(index, offset, flag); } bool Object::HasByteFlag(uint16 index, uint8 offset, uint8 flag) const { ASSERT(index < m_valuesCount || PrintIndexError(index, false)); ASSERT(offset < 4); return (((uint8*)&m_uint32Values[index])[offset] & flag) != 0; } void Object::SetFlag64(uint16 index, uint64 newFlag) { uint64 oldval = GetUInt64Value(index); uint64 newval = oldval | newFlag; SetUInt64Value(index, newval); } void Object::RemoveFlag64(uint16 index, uint64 oldFlag) { uint64 oldval = GetUInt64Value(index); uint64 newval = oldval & ~oldFlag; SetUInt64Value(index, newval); } void Object::ToggleFlag64(uint16 index, uint64 flag) { if (HasFlag64(index, flag)) RemoveFlag64(index, flag); else SetFlag64(index, flag); } bool Object::HasFlag64(uint16 index, uint64 flag) const { ASSERT(index < m_valuesCount || PrintIndexError(index, false)); return (GetUInt64Value(index) & flag) != 0; } void Object::ApplyModFlag64(uint16 index, uint64 flag, bool apply) { if (apply) SetFlag64(index, flag); else RemoveFlag64(index, flag); } std::vector<uint32> const& Object::GetDynamicValues(uint16 index) const { ASSERT(index < _dynamicValuesCount || PrintIndexError(index, false)); return _dynamicValues[index]; } uint32 Object::GetDynamicValue(uint16 index, uint16 offset) const { ASSERT(index < _dynamicValuesCount || PrintIndexError(index, false)); if (offset >= _dynamicValues[index].size()) return 0; return _dynamicValues[index][offset]; } void Object::AddDynamicValue(uint16 index, uint32 value) { ASSERT(index < _dynamicValuesCount || PrintIndexError(index, false)); SetDynamicValue(index, _dynamicValues[index].size(), value); } void Object::RemoveDynamicValue(uint16 index, uint32 value) { ASSERT(index < _dynamicValuesCount || PrintIndexError(index, false)); // TODO: Research if this is blizzlike to just set value to 0 std::vector<uint32>& values = _dynamicValues[index]; for (std::size_t i = 0; i < values.size(); ++i) { if (values[i] == value) { values[i] = 0; _dynamicChangesMask[index] = UpdateMask::VALUE_CHANGED; _dynamicChangesArrayMask[index][i] = 1; AddToObjectUpdateIfNeeded(); } } } void Object::ClearDynamicValue(uint16 index) { ASSERT(index < _dynamicValuesCount || PrintIndexError(index, false)); if (!_dynamicValues[index].empty()) { _dynamicValues[index].clear(); _dynamicChangesMask[index] = UpdateMask::VALUE_AND_SIZE_CHANGED; _dynamicChangesArrayMask[index].clear(); AddToObjectUpdateIfNeeded(); } } void Object::SetDynamicValue(uint16 index, uint16 offset, uint32 value) { ASSERT(index < _dynamicValuesCount || PrintIndexError(index, false)); UpdateMask::DynamicFieldChangeType changeType = UpdateMask::VALUE_CHANGED; std::vector<uint32>& values = _dynamicValues[index]; if (values.size() <= offset) { values.resize(offset + 1); changeType = UpdateMask::VALUE_AND_SIZE_CHANGED; } if (_dynamicChangesArrayMask[index].size() <= offset) _dynamicChangesArrayMask[index].resize((offset / 32 + 1) * 32); if (values[offset] != value || changeType == UpdateMask::VALUE_AND_SIZE_CHANGED) { values[offset] = value; _dynamicChangesMask[index] = changeType; _dynamicChangesArrayMask[index][offset] = 1; AddToObjectUpdateIfNeeded(); } } bool Object::PrintIndexError(uint32 index, bool set) const { TC_LOG_ERROR("misc", "Attempt %s non-existed value field: %u (count: %u) for object typeid: %u type mask: %u", (set ? "set value to" : "get value from"), index, m_valuesCount, GetTypeId(), m_objectType); // ASSERT must fail after function call return false; } void MovementInfo::OutDebug() { TC_LOG_DEBUG("misc", "MOVEMENT INFO"); TC_LOG_DEBUG("misc", "%s", guid.ToString().c_str()); TC_LOG_DEBUG("misc", "flags %s (%u)", Movement::MovementFlags_ToString(flags).c_str(), flags); TC_LOG_DEBUG("misc", "flags2 %s (%u)", Movement::MovementFlagsExtra_ToString(flags2).c_str(), flags2); TC_LOG_DEBUG("misc", "time %u current time %u", time, getMSTime()); TC_LOG_DEBUG("misc", "position: `%s`", pos.ToString().c_str()); if (!transport.guid.IsEmpty()) { TC_LOG_DEBUG("misc", "TRANSPORT:"); TC_LOG_DEBUG("misc", "%s", transport.guid.ToString().c_str()); TC_LOG_DEBUG("misc", "position: `%s`", transport.pos.ToString().c_str()); TC_LOG_DEBUG("misc", "seat: %i", transport.seat); TC_LOG_DEBUG("misc", "time: %u", transport.time); if (flags2 & MOVEMENTFLAG2_INTERPOLATED_MOVEMENT) TC_LOG_DEBUG("misc", "prevTime: %u", transport.prevTime); if (transport.vehicleId) TC_LOG_DEBUG("misc", "vehicleId: %u", transport.vehicleId); } if ((flags & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || (flags2 & MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING)) TC_LOG_DEBUG("misc", "pitch: %f", pitch); if (flags & MOVEMENTFLAG_FALLING || jump.fallTime) { TC_LOG_DEBUG("misc", "fallTime: %u j_zspeed: %f", jump.fallTime, jump.zspeed); if (flags & MOVEMENTFLAG_FALLING) TC_LOG_DEBUG("misc", "j_sinAngle: %f j_cosAngle: %f j_xyspeed: %f", jump.sinAngle, jump.cosAngle, jump.xyspeed); } if (flags & MOVEMENTFLAG_SPLINE_ELEVATION) TC_LOG_DEBUG("misc", "splineElevation: %f", splineElevation); } WorldObject::WorldObject(bool isWorldObject) : WorldLocation(), LastUsedScriptID(0), m_name(""), m_isActive(false), m_isWorldObject(isWorldObject), m_zoneScript(NULL), m_transport(NULL), m_currMap(NULL), m_InstanceId(0), m_phaseMask(PHASEMASK_NORMAL), _dbPhase(0), m_notifyflags(0), m_executed_notifies(0) { m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE | GHOST_VISIBILITY_GHOST); m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); } void WorldObject::SetWorldObject(bool on) { if (!IsInWorld()) return; GetMap()->AddObjectToSwitchList(this, on); } bool WorldObject::IsWorldObject() const { if (m_isWorldObject) return true; if (ToCreature() && ToCreature()->m_isTempWorldObject) return true; return false; } void WorldObject::setActive(bool on) { if (m_isActive == on) return; if (GetTypeId() == TYPEID_PLAYER) return; m_isActive = on; if (!IsInWorld()) return; Map* map = FindMap(); if (!map) return; if (on) { if (GetTypeId() == TYPEID_UNIT) map->AddToActive(this->ToCreature()); else if (GetTypeId() == TYPEID_DYNAMICOBJECT) map->AddToActive((DynamicObject*)this); } else { if (GetTypeId() == TYPEID_UNIT) map->RemoveFromActive(this->ToCreature()); else if (GetTypeId() == TYPEID_DYNAMICOBJECT) map->RemoveFromActive((DynamicObject*)this); } } void WorldObject::CleanupsBeforeDelete(bool /*finalCleanup*/) { if (IsInWorld()) RemoveFromWorld(); if (Transport* transport = GetTransport()) transport->RemovePassenger(this); } void WorldObject::RemoveFromWorld() { if (!IsInWorld()) return; DestroyForNearbyPlayers(); Object::RemoveFromWorld(); } uint32 WorldObject::GetZoneId() const { return GetBaseMap()->GetZoneId(m_positionX, m_positionY, m_positionZ); } uint32 WorldObject::GetAreaId() const { return GetBaseMap()->GetAreaId(m_positionX, m_positionY, m_positionZ); } void WorldObject::GetZoneAndAreaId(uint32& zoneid, uint32& areaid) const { GetBaseMap()->GetZoneAndAreaId(zoneid, areaid, m_positionX, m_positionY, m_positionZ); } InstanceScript* WorldObject::GetInstanceScript() { Map* map = GetMap(); return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceScript() : NULL; } float WorldObject::GetDistanceZ(const WorldObject* obj) const { float dz = std::fabs(GetPositionZ() - obj->GetPositionZ()); float sizefactor = GetObjectSize() + obj->GetObjectSize(); float dist = dz - sizefactor; return (dist > 0 ? dist : 0); } bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const { float sizefactor = GetObjectSize() + obj->GetObjectSize(); float maxdist = dist2compare + sizefactor; if (GetTransport() && obj->GetTransport() && obj->GetTransport()->GetGUID() == GetTransport()->GetGUID()) { float dtx = m_movementInfo.transport.pos.m_positionX - obj->m_movementInfo.transport.pos.m_positionX; float dty = m_movementInfo.transport.pos.m_positionY - obj->m_movementInfo.transport.pos.m_positionY; float disttsq = dtx * dtx + dty * dty; if (is3D) { float dtz = m_movementInfo.transport.pos.m_positionZ - obj->m_movementInfo.transport.pos.m_positionZ; disttsq += dtz * dtz; } return disttsq < (maxdist * maxdist); } float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float distsq = dx*dx + dy*dy; if (is3D) { float dz = GetPositionZ() - obj->GetPositionZ(); distsq += dz*dz; } return distsq < maxdist * maxdist; } bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const { if (!IsInMap(obj)) return false; float x, y, z; if (obj->GetTypeId() == TYPEID_PLAYER) obj->GetPosition(x, y, z); else obj->GetHitSpherePointFor(GetPosition(), x, y, z); return IsWithinLOS(x, y, z); } float WorldObject::GetDistance(const WorldObject* obj) const { float d = GetExactDist(obj) - GetObjectSize() - obj->GetObjectSize(); return d > 0.0f ? d : 0.0f; } float WorldObject::GetDistance(const Position &pos) const { float d = GetExactDist(&pos) - GetObjectSize(); return d > 0.0f ? d : 0.0f; } float WorldObject::GetDistance(float x, float y, float z) const { float d = GetExactDist(x, y, z) - GetObjectSize(); return d > 0.0f ? d : 0.0f; } float WorldObject::GetDistance2d(const WorldObject* obj) const { float d = GetExactDist2d(obj) - GetObjectSize() - obj->GetObjectSize(); return d > 0.0f ? d : 0.0f; } float WorldObject::GetDistance2d(float x, float y) const { float d = GetExactDist2d(x, y) - GetObjectSize(); return d > 0.0f ? d : 0.0f; } bool WorldObject::IsSelfOrInSameMap(const WorldObject* obj) const { if (this == obj) return true; return IsInMap(obj); } bool WorldObject::IsInMap(const WorldObject* obj) const { if (obj) return IsInWorld() && obj->IsInWorld() && (GetMap() == obj->GetMap()); return false; } bool WorldObject::IsWithinDist3d(float x, float y, float z, float dist) const { return IsInDist(x, y, z, dist + GetObjectSize()); } bool WorldObject::IsWithinDist3d(const Position* pos, float dist) const { return IsInDist(pos, dist + GetObjectSize()); } bool WorldObject::IsWithinDist2d(float x, float y, float dist) const { return IsInDist2d(x, y, dist + GetObjectSize()); } bool WorldObject::IsWithinDist2d(const Position* pos, float dist) const { return IsInDist2d(pos, dist + GetObjectSize()); } bool WorldObject::IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D /*= true*/) const { return obj && _IsWithinDist(obj, dist2compare, is3D); } bool WorldObject::IsWithinDistInMap(WorldObject const* obj, float dist2compare, bool is3D /*= true*/) const { return obj && IsInMap(obj) && IsInPhase(obj) && _IsWithinDist(obj, dist2compare, is3D); } bool WorldObject::IsWithinLOS(float ox, float oy, float oz) const { /*float x, y, z; GetPosition(x, y, z); VMAP::IVMapManager* vMapManager = VMAP::VMapFactory::createOrGetVMapManager(); return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);*/ if (IsInWorld()) { float x, y, z; if (GetTypeId() == TYPEID_PLAYER) GetPosition(x, y, z); else GetHitSpherePointFor({ ox, oy, oz }, x, y, z); return GetMap()->isInLineOfSight(x, y, z + 2.0f, ox, oy, oz + 2.0f, GetPhaseMask()); } return true; } Position WorldObject::GetHitSpherePointFor(Position const& dest) const { G3D::Vector3 vThis(GetPositionX(), GetPositionY(), GetPositionZ()); G3D::Vector3 vObj(dest.GetPositionX(), dest.GetPositionY(), dest.GetPositionZ()); G3D::Vector3 contactPoint = vThis + (vObj - vThis).directionOrZero() * GetObjectSize(); return Position(contactPoint.x, contactPoint.y, contactPoint.z, GetAngle(contactPoint.x, contactPoint.y)); } void WorldObject::GetHitSpherePointFor(Position const& dest, float& x, float& y, float& z) const { Position pos = GetHitSpherePointFor(dest); x = pos.GetPositionX(); y = pos.GetPositionY(); z = pos.GetPositionZ(); } bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D /* = true */) const { float dx1 = GetPositionX() - obj1->GetPositionX(); float dy1 = GetPositionY() - obj1->GetPositionY(); float distsq1 = dx1*dx1 + dy1*dy1; if (is3D) { float dz1 = GetPositionZ() - obj1->GetPositionZ(); distsq1 += dz1*dz1; } float dx2 = GetPositionX() - obj2->GetPositionX(); float dy2 = GetPositionY() - obj2->GetPositionY(); float distsq2 = dx2*dx2 + dy2*dy2; if (is3D) { float dz2 = GetPositionZ() - obj2->GetPositionZ(); distsq2 += dz2*dz2; } return distsq1 < distsq2; } bool WorldObject::IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D /* = true */) const { float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float distsq = dx*dx + dy*dy; if (is3D) { float dz = GetPositionZ() - obj->GetPositionZ(); distsq += dz*dz; } float sizefactor = GetObjectSize() + obj->GetObjectSize(); // check only for real range if (minRange > 0.0f) { float mindist = minRange + sizefactor; if (distsq < mindist * mindist) return false; } float maxdist = maxRange + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::IsInRange2d(float x, float y, float minRange, float maxRange) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float distsq = dx*dx + dy*dy; float sizefactor = GetObjectSize(); // check only for real range if (minRange > 0.0f) { float mindist = minRange + sizefactor; if (distsq < mindist * mindist) return false; } float maxdist = maxRange + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::IsInRange3d(float x, float y, float z, float minRange, float maxRange) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float dz = GetPositionZ() - z; float distsq = dx*dx + dy*dy + dz*dz; float sizefactor = GetObjectSize(); // check only for real range if (minRange > 0.0f) { float mindist = minRange + sizefactor; if (distsq < mindist * mindist) return false; } float maxdist = maxRange + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::IsInBetween(const WorldObject* obj1, const WorldObject* obj2, float size) const { if (!obj1 || !obj2) return false; float dist = GetExactDist2d(obj1->GetPositionX(), obj1->GetPositionY()); // not using sqrt() for performance if ((dist * dist) >= obj1->GetExactDist2dSq(obj2->GetPositionX(), obj2->GetPositionY())) return false; if (!size) size = GetObjectSize() / 2; float angle = obj1->GetAngle(obj2); // not using sqrt() for performance return (size * size) >= GetExactDist2dSq(obj1->GetPositionX() + std::cos(angle) * dist, obj1->GetPositionY() + std::sin(angle) * dist); } bool WorldObject::isInFront(WorldObject const* target, float arc) const { return HasInArc(arc, target); } bool WorldObject::isInBack(WorldObject const* target, float arc) const { return !HasInArc(2 * float(M_PI) - arc, target); } void WorldObject::GetRandomPoint(const Position &pos, float distance, float &rand_x, float &rand_y, float &rand_z) const { if (!distance) { pos.GetPosition(rand_x, rand_y, rand_z); return; } // angle to face `obj` to `this` float angle = (float)rand_norm()*static_cast<float>(2*M_PI); float new_dist = (float)rand_norm()*static_cast<float>(distance); rand_x = pos.m_positionX + new_dist * std::cos(angle); rand_y = pos.m_positionY + new_dist * std::sin(angle); rand_z = pos.m_positionZ; Trinity::NormalizeMapCoord(rand_x); Trinity::NormalizeMapCoord(rand_y); UpdateGroundPositionZ(rand_x, rand_y, rand_z); // update to LOS height if available } Position WorldObject::GetRandomPoint(const Position &srcPos, float distance) const { float x, y, z; GetRandomPoint(srcPos, distance, x, y, z); return Position(x, y, z, GetOrientation()); } void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const { float new_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z + 2.0f, true); if (new_z > INVALID_HEIGHT) z = new_z + 0.05f; // just to be sure that we are not a few pixel under the surface } void WorldObject::UpdateAllowedPositionZ(float x, float y, float &z) const { // TODO: Allow transports to be part of dynamic vmap tree if (GetTransport()) return; switch (GetTypeId()) { case TYPEID_UNIT: { // non fly unit don't must be in air // non swim unit must be at ground (mostly speedup, because it don't must be in water and water level check less fast if (!ToCreature()->CanFly()) { bool canSwim = ToCreature()->CanSwim(); float ground_z = z; float max_z = canSwim ? GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)) : ((ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true))); if (max_z > INVALID_HEIGHT) { if (z > max_z) z = max_z; else if (z < ground_z) z = ground_z; } } else { float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); if (z < ground_z) z = ground_z; } break; } case TYPEID_PLAYER: { // for server controlled moves playr work same as creature (but it can always swim) if (!ToPlayer()->CanFly()) { float ground_z = z; float max_z = GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)); if (max_z > INVALID_HEIGHT) { if (z > max_z) z = max_z; else if (z < ground_z) z = ground_z; } } else { float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); if (z < ground_z) z = ground_z; } break; } default: { float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); if (ground_z > INVALID_HEIGHT) z = ground_z; break; } } } float WorldObject::GetGridActivationRange() const { if (ToPlayer()) return GetMap()->GetVisibilityRange(); else if (ToCreature()) return ToCreature()->m_SightDistance; else return 0.0f; } float WorldObject::GetVisibilityRange() const { if (isActiveObject() && !ToPlayer()) return MAX_VISIBILITY_DISTANCE; else return GetMap()->GetVisibilityRange(); } float WorldObject::GetSightRange(const WorldObject* target) const { if (ToUnit()) { if (ToPlayer()) { if (target && target->isActiveObject() && !target->ToPlayer()) return MAX_VISIBILITY_DISTANCE; else return GetMap()->GetVisibilityRange(); } else if (ToCreature()) return ToCreature()->m_SightDistance; else return SIGHT_RANGE_UNIT; } return 0.0f; } bool WorldObject::CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth, bool distanceCheck, bool checkAlert) const { if (this == obj) return true; if (obj->IsNeverVisible() || CanNeverSee(obj)) return false; if (obj->IsAlwaysVisibleFor(this) || CanAlwaysSee(obj)) return true; bool corpseVisibility = false; if (distanceCheck) { bool corpseCheck = false; if (Player const* thisPlayer = ToPlayer()) { if (thisPlayer->isDead() && thisPlayer->GetHealth() > 0 && // Cheap way to check for ghost state !(obj->m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GHOST) & m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GHOST) & GHOST_VISIBILITY_GHOST)) { if (Corpse* corpse = thisPlayer->GetCorpse()) { corpseCheck = true; if (corpse->IsWithinDist(thisPlayer, GetSightRange(obj), false)) if (corpse->IsWithinDist(obj, GetSightRange(obj), false)) corpseVisibility = true; } } } WorldObject const* viewpoint = this; if (Player const* player = this->ToPlayer()) viewpoint = player->GetViewpoint(); if (!viewpoint) viewpoint = this; if (!corpseCheck && !viewpoint->IsWithinDist(obj, GetSightRange(obj), false)) return false; } // GM visibility off or hidden NPC if (!obj->m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GM)) { // Stop checking other things for GMs if (m_serverSideVisibilityDetect.GetValue(SERVERSIDE_VISIBILITY_GM)) return true; } else return m_serverSideVisibilityDetect.GetValue(SERVERSIDE_VISIBILITY_GM) >= obj->m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GM); // Ghost players, Spirit Healers, and some other NPCs if (!corpseVisibility && !(obj->m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GHOST) & m_serverSideVisibilityDetect.GetValue(SERVERSIDE_VISIBILITY_GHOST))) { // Alive players can see dead players in some cases, but other objects can't do that if (Player const* thisPlayer = ToPlayer()) { if (Player const* objPlayer = obj->ToPlayer()) { if (thisPlayer->GetTeam() != objPlayer->GetTeam() || !thisPlayer->IsGroupVisibleFor(objPlayer)) return false; } else return false; } else return false; } if (obj->IsInvisibleDueToDespawn()) return false; if (!CanDetect(obj, ignoreStealth, checkAlert)) return false; return true; } bool WorldObject::CanNeverSee(WorldObject const* obj) const { return GetMap() != obj->GetMap() || !IsInPhase(obj); } bool WorldObject::CanDetect(WorldObject const* obj, bool ignoreStealth, bool checkAlert) const { const WorldObject* seer = this; // Pets don't have detection, they use the detection of their masters if (Unit const* thisUnit = ToUnit()) if (Unit* controller = thisUnit->GetCharmerOrOwner()) seer = controller; if (obj->IsAlwaysDetectableFor(seer)) return true; if (!ignoreStealth && !seer->CanDetectInvisibilityOf(obj)) return false; if (!ignoreStealth && !seer->CanDetectStealthOf(obj, checkAlert)) return false; return true; } bool WorldObject::CanDetectInvisibilityOf(WorldObject const* obj) const { uint32 mask = obj->m_invisibility.GetFlags() & m_invisibilityDetect.GetFlags(); // Check for not detected types if (mask != obj->m_invisibility.GetFlags()) return false; for (uint32 i = 0; i < TOTAL_INVISIBILITY_TYPES; ++i) { if (!(mask & (1 << i))) continue; int32 objInvisibilityValue = obj->m_invisibility.GetValue(InvisibilityType(i)); int32 ownInvisibilityDetectValue = m_invisibilityDetect.GetValue(InvisibilityType(i)); // Too low value to detect if (ownInvisibilityDetectValue < objInvisibilityValue) return false; } return true; } bool WorldObject::CanDetectStealthOf(WorldObject const* obj, bool checkAlert) const { // Combat reach is the minimal distance (both in front and behind), // and it is also used in the range calculation. // One stealth point increases the visibility range by 0.3 yard. if (!obj->m_stealth.GetFlags()) return true; float distance = GetExactDist(obj); float combatReach = 0.0f; Unit const* unit = ToUnit(); if (unit) combatReach = unit->GetCombatReach(); if (distance < combatReach) return true; if (!HasInArc(float(M_PI), obj)) return false; GameObject const* go = ToGameObject(); for (uint32 i = 0; i < TOTAL_STEALTH_TYPES; ++i) { if (!(obj->m_stealth.GetFlags() & (1 << i))) continue; if (unit && unit->HasAuraTypeWithMiscvalue(SPELL_AURA_DETECT_STEALTH, i)) return true; // Starting points int32 detectionValue = 30; // Level difference: 5 point / level, starting from level 1. // There may be spells for this and the starting points too, but // not in the DBCs of the client. detectionValue += int32(getLevelForTarget(obj) - 1) * 5; // Apply modifiers detectionValue += m_stealthDetect.GetValue(StealthType(i)); if (go) if (Unit* owner = go->GetOwner()) detectionValue -= int32(owner->getLevelForTarget(this) - 1) * 5; detectionValue -= obj->m_stealth.GetValue(StealthType(i)); // Calculate max distance float visibilityRange = float(detectionValue) * 0.3f + combatReach; // If this unit is an NPC then player detect range doesn't apply if (unit && unit->GetTypeId() == TYPEID_PLAYER && visibilityRange > MAX_PLAYER_STEALTH_DETECT_RANGE) visibilityRange = MAX_PLAYER_STEALTH_DETECT_RANGE; // When checking for alert state, look 8% further, and then 1.5 yards more than that. if (checkAlert) visibilityRange += (visibilityRange * 0.08f) + 1.5f; // If checking for alert, and creature's visibility range is greater than aggro distance, No alert Unit const* tunit = obj->ToUnit(); if (checkAlert && unit && unit->ToCreature() && visibilityRange >= unit->ToCreature()->GetAttackDistance(tunit) + unit->ToCreature()->m_CombatDistance) return false; if (distance > visibilityRange) return false; } return true; } void Object::ForceValuesUpdateAtIndex(uint32 i) { _changesMask[i] = 1; AddToObjectUpdateIfNeeded(); } void WorldObject::SendMessageToSet(WorldPacket const* data, bool self) { if (IsInWorld()) SendMessageToSetInRange(data, GetVisibilityRange(), self); } void WorldObject::SendMessageToSetInRange(WorldPacket const* data, float dist, bool /*self*/) { Trinity::MessageDistDeliverer notifier(this, data, dist); VisitNearbyWorldObject(dist, notifier); } void WorldObject::SendMessageToSet(WorldPacket const* data, Player const* skipped_rcvr) { Trinity::MessageDistDeliverer notifier(this, data, GetVisibilityRange(), false, skipped_rcvr); VisitNearbyWorldObject(GetVisibilityRange(), notifier); } void WorldObject::SetMap(Map* map) { ASSERT(map); ASSERT(!IsInWorld()); if (m_currMap == map) // command add npc: first create, than loadfromdb return; if (m_currMap) { TC_LOG_FATAL("misc", "WorldObject::SetMap: obj %u new map %u %u, old map %u %u", (uint32)GetTypeId(), map->GetId(), map->GetInstanceId(), m_currMap->GetId(), m_currMap->GetInstanceId()); ABORT(); } m_currMap = map; m_mapId = map->GetId(); m_InstanceId = map->GetInstanceId(); if (IsWorldObject()) m_currMap->AddWorldObject(this); } void WorldObject::ResetMap() { ASSERT(m_currMap); ASSERT(!IsInWorld()); if (IsWorldObject()) m_currMap->RemoveWorldObject(this); m_currMap = NULL; //maybe not for corpse //m_mapId = 0; //m_InstanceId = 0; } Map const* WorldObject::GetBaseMap() const { ASSERT(m_currMap); return m_currMap->GetParent(); } void WorldObject::AddObjectToRemoveList() { ASSERT(m_uint32Values); Map* map = FindMap(); if (!map) { TC_LOG_ERROR("misc", "Object (Entry: %u %s) at attempt add to move list not have valid map (Id: %u).", GetEntry(), GetGUID().ToString().c_str(), GetMapId()); return; } map->AddObjectToRemoveList(this); } TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropertiesEntry const* properties /*= NULL*/, uint32 duration /*= 0*/, Unit* summoner /*= NULL*/, uint32 spellId /*= 0*/, uint32 vehId /*= 0*/) { uint32 mask = UNIT_MASK_SUMMON; if (properties) { switch (properties->Category) { case SUMMON_CATEGORY_PET: mask = UNIT_MASK_GUARDIAN; break; case SUMMON_CATEGORY_PUPPET: mask = UNIT_MASK_PUPPET; break; case SUMMON_CATEGORY_VEHICLE: mask = UNIT_MASK_MINION; break; case SUMMON_CATEGORY_WILD: case SUMMON_CATEGORY_ALLY: case SUMMON_CATEGORY_UNK: { switch (properties->Type) { case SUMMON_TYPE_MINION: case SUMMON_TYPE_GUARDIAN: case SUMMON_TYPE_GUARDIAN2: mask = UNIT_MASK_GUARDIAN; break; case SUMMON_TYPE_TOTEM: case SUMMON_TYPE_LIGHTWELL: mask = UNIT_MASK_TOTEM; break; case SUMMON_TYPE_VEHICLE: case SUMMON_TYPE_VEHICLE2: mask = UNIT_MASK_SUMMON; break; case SUMMON_TYPE_MINIPET: mask = UNIT_MASK_MINION; break; default: if (properties->Flags & 512) // Mirror Image, Summon Gargoyle mask = UNIT_MASK_GUARDIAN; break; } break; } default: return NULL; } } TempSummon* summon = NULL; switch (mask) { case UNIT_MASK_SUMMON: summon = new TempSummon(properties, summoner, false); break; case UNIT_MASK_GUARDIAN: summon = new Guardian(properties, summoner, false); break; case UNIT_MASK_PUPPET: summon = new Puppet(properties, summoner); break; case UNIT_MASK_TOTEM: summon = new Totem(properties, summoner); break; case UNIT_MASK_MINION: summon = new Minion(properties, summoner, false); break; } if (!summon->Create(GenerateLowGuid<HighGuid::Creature>(), this, 0, entry, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), nullptr, vehId)) { delete summon; return NULL; } // Set the summon to the summoner's phase summon->CopyPhaseFrom(summoner); summon->SetUInt32Value(UNIT_CREATED_BY_SPELL, spellId); summon->SetHomePosition(pos); summon->InitStats(duration); AddToMap(summon->ToCreature()); summon->InitSummon(); // call MoveInLineOfSight for nearby creatures Trinity::AIRelocationNotifier notifier(*summon); summon->VisitNearbyObject(GetVisibilityRange(), notifier); return summon; } /** * Summons group of creatures. * * @param group Id of group to summon. * @param list List to store pointers to summoned creatures. */ void Map::SummonCreatureGroup(uint8 group, std::list<TempSummon*>* list /*= NULL*/) { std::vector<TempSummonData> const* data = sObjectMgr->GetSummonGroup(GetId(), SUMMONER_TYPE_MAP, group); if (!data) return; for (std::vector<TempSummonData>::const_iterator itr = data->begin(); itr != data->end(); ++itr) if (TempSummon* summon = SummonCreature(itr->entry, itr->pos, NULL, itr->time)) if (list) list->push_back(summon); } void WorldObject::SetZoneScript() { if (Map* map = FindMap()) { if (map->IsDungeon()) m_zoneScript = (ZoneScript*)((InstanceMap*)map)->GetInstanceScript(); else if (!map->IsBattlegroundOrArena()) { if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(GetZoneId())) m_zoneScript = bf; else m_zoneScript = sOutdoorPvPMgr->GetZoneScript(GetZoneId()); } } } Scenario* WorldObject::GetScenario() const { if (IsInWorld()) if (InstanceMap* instanceMap = GetMap()->ToInstanceMap()) return instanceMap->GetInstanceScenario(); return nullptr; } TempSummon* WorldObject::SummonCreature(uint32 entry, Position const& pos, TempSummonType spwtype /*= TEMPSUMMON_MANUAL_DESPAWN*/, uint32 duration /*= 0*/, uint32 /*vehId = 0*/) const { if (Map* map = FindMap()) { if (TempSummon* summon = map->SummonCreature(entry, pos, NULL, duration, isType(TYPEMASK_UNIT) ? (Unit*)this : NULL)) { summon->SetTempSummonType(spwtype); return summon; } } return nullptr; } TempSummon* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang /*= 0*/, TempSummonType spwtype /*= TEMPSUMMON_MANUAL_DESPAWN*/, uint32 despwtime /*= 0*/) const { if (!x && !y && !z) { GetClosePoint(x, y, z, GetObjectSize()); ang = GetOrientation(); } Position pos; pos.Relocate(x, y, z, ang); return SummonCreature(id, pos, spwtype, despwtime, 0); } GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot, uint32 respawnTime) { if (!IsInWorld()) return nullptr; GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(entry); if (!goinfo) { TC_LOG_ERROR("sql.sql", "Gameobject template %u not found in database!", entry); return nullptr; } Map* map = GetMap(); GameObject* go = new GameObject(); if (!go->Create(entry, map, GetPhaseMask(), pos, rot, 255, GO_STATE_READY)) { delete go; return nullptr; } go->CopyPhaseFrom(this); go->SetRespawnTime(respawnTime); if (GetTypeId() == TYPEID_PLAYER || GetTypeId() == TYPEID_UNIT) //not sure how to handle this ToUnit()->AddGameObject(go); else go->SetSpawnedByDefault(false); map->AddToMap(go); return go; } GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float z, float ang, G3D::Quat const& rot, uint32 respawnTime) { if (!x && !y && !z) { GetClosePoint(x, y, z, GetObjectSize()); ang = GetOrientation(); } Position pos(x, y, z, ang); return SummonGameObject(entry, pos, rot, respawnTime); } Creature* WorldObject::SummonTrigger(float x, float y, float z, float ang, uint32 duration, CreatureAI* (*GetAI)(Creature*)) { TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; Creature* summon = SummonCreature(WORLD_TRIGGER, x, y, z, ang, summonType, duration); if (!summon) return NULL; //summon->SetName(GetName()); if (GetTypeId() == TYPEID_PLAYER || GetTypeId() == TYPEID_UNIT) { summon->setFaction(((Unit*)this)->getFaction()); summon->SetLevel(((Unit*)this)->getLevel()); } if (GetAI) summon->AIM_Initialize(GetAI(summon)); return summon; } /** * Summons group of creatures. Should be called only by instances of Creature and GameObject classes. * * @param group Id of group to summon. * @param list List to store pointers to summoned creatures. */ void WorldObject::SummonCreatureGroup(uint8 group, std::list<TempSummon*>* list /*= NULL*/) { ASSERT((GetTypeId() == TYPEID_GAMEOBJECT || GetTypeId() == TYPEID_UNIT) && "Only GOs and creatures can summon npc groups!"); std::vector<TempSummonData> const* data = sObjectMgr->GetSummonGroup(GetEntry(), GetTypeId() == TYPEID_GAMEOBJECT ? SUMMONER_TYPE_GAMEOBJECT : SUMMONER_TYPE_CREATURE, group); if (!data) { TC_LOG_WARN("scripts", "%s (%s) tried to summon non-existing summon group %u.", GetName().c_str(), GetGUID().ToString().c_str(), group); return; } for (std::vector<TempSummonData>::const_iterator itr = data->begin(); itr != data->end(); ++itr) if (TempSummon* summon = SummonCreature(itr->entry, itr->pos, itr->type, itr->time)) if (list) list->push_back(summon); } Creature* WorldObject::FindNearestCreature(uint32 entry, float range, bool alive) const { Creature* creature = NULL; Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck checker(*this, entry, alive, range); Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(this, creature, checker); VisitNearbyObject(range, searcher); return creature; } GameObject* WorldObject::FindNearestGameObject(uint32 entry, float range) const { GameObject* go = NULL; Trinity::NearestGameObjectEntryInObjectRangeCheck checker(*this, entry, range); Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck> searcher(this, go, checker); VisitNearbyGridObject(range, searcher); return go; } GameObject* WorldObject::FindNearestGameObjectOfType(GameobjectTypes type, float range) const { GameObject* go = NULL; Trinity::NearestGameObjectTypeInObjectRangeCheck checker(*this, type, range); Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectTypeInObjectRangeCheck> searcher(this, go, checker); VisitNearbyGridObject(range, searcher); return go; } void WorldObject::GetGameObjectListWithEntryInGrid(std::list<GameObject*>& gameobjectList, uint32 entry, float maxSearchRange) const { CellCoord pair(Trinity::ComputeCellCoord(this->GetPositionX(), this->GetPositionY())); Cell cell(pair); cell.SetNoCreate(); Trinity::AllGameObjectsWithEntryInRange check(this, entry, maxSearchRange); Trinity::GameObjectListSearcher<Trinity::AllGameObjectsWithEntryInRange> searcher(this, gameobjectList, check); TypeContainerVisitor<Trinity::GameObjectListSearcher<Trinity::AllGameObjectsWithEntryInRange>, GridTypeMapContainer> visitor(searcher); cell.Visit(pair, visitor, *(this->GetMap()), *this, maxSearchRange); } void WorldObject::GetCreatureListWithEntryInGrid(std::list<Creature*>& creatureList, uint32 entry, float maxSearchRange) const { CellCoord pair(Trinity::ComputeCellCoord(this->GetPositionX(), this->GetPositionY())); Cell cell(pair); cell.SetNoCreate(); Trinity::AllCreaturesOfEntryInRange check(this, entry, maxSearchRange); Trinity::CreatureListSearcher<Trinity::AllCreaturesOfEntryInRange> searcher(this, creatureList, check); TypeContainerVisitor<Trinity::CreatureListSearcher<Trinity::AllCreaturesOfEntryInRange>, GridTypeMapContainer> visitor(searcher); cell.Visit(pair, visitor, *(this->GetMap()), *this, maxSearchRange); } void WorldObject::GetPlayerListInGrid(std::list<Player*>& playerList, float maxSearchRange) const { Trinity::AnyPlayerInObjectRangeCheck checker(this, maxSearchRange); Trinity::PlayerListSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(this, playerList, checker); this->VisitNearbyWorldObject(maxSearchRange, searcher); } /* namespace Trinity { class NearUsedPosDo { public: NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float angle, ObjectPosSelector& selector) : i_object(obj), i_searcher(searcher), i_angle(angle), i_selector(selector) { } void operator()(Corpse*) const { } void operator()(DynamicObject*) const { } void operator()(Creature* c) const { // skip self or target if (c == i_searcher || c == &i_object) return; float x, y, z; if (!c->IsAlive() || c->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED | UNIT_STATE_DISTRACTED) || !c->GetMotionMaster()->GetDestination(x, y, z)) { x = c->GetPositionX(); y = c->GetPositionY(); } add(c, x, y); } template<class T> void operator()(T* u) const { // skip self or target if (u == i_searcher || u == &i_object) return; float x, y; x = u->GetPositionX(); y = u->GetPositionY(); add(u, x, y); } // we must add used pos that can fill places around center void add(WorldObject* u, float x, float y) const { // u is too nearest/far away to i_object if (!i_object.IsInRange2d(x, y, i_selector.m_dist - i_selector.m_size, i_selector.m_dist + i_selector.m_size)) return; float angle = i_object.GetAngle(u)-i_angle; // move angle to range -pi ... +pi while (angle > M_PI) angle -= 2.0f * M_PI; while (angle < -M_PI) angle += 2.0f * M_PI; // dist include size of u float dist2d = i_object.GetDistance2d(x, y); i_selector.AddUsedPos(u->GetObjectSize(), angle, dist2d + i_object.GetObjectSize()); } private: WorldObject const& i_object; WorldObject const* i_searcher; float i_angle; ObjectPosSelector& i_selector; }; } // namespace Trinity */ //=================================================================================================== void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle) const { x = GetPositionX() + (GetObjectSize() + distance2d) * std::cos(absAngle); y = GetPositionY() + (GetObjectSize() + distance2d) * std::sin(absAngle); Trinity::NormalizeMapCoord(x); Trinity::NormalizeMapCoord(y); } void WorldObject::GetNearPoint(WorldObject const* /*searcher*/, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle) const { GetNearPoint2D(x, y, distance2d+searcher_size, absAngle); z = GetPositionZ(); // Should "searcher" be used instead of "this" when updating z coordinate ? UpdateAllowedPositionZ(x, y, z); // if detection disabled, return first point if (!sWorld->getBoolConfig(CONFIG_DETECT_POS_COLLISION)) return; // return if the point is already in LoS if (IsWithinLOS(x, y, z)) return; // remember first point float first_x = x; float first_y = y; float first_z = z; // loop in a circle to look for a point in LoS using small steps for (float angle = float(M_PI) / 8; angle < float(M_PI) * 2; angle += float(M_PI) / 8) { GetNearPoint2D(x, y, distance2d + searcher_size, absAngle + angle); z = GetPositionZ(); UpdateAllowedPositionZ(x, y, z); if (IsWithinLOS(x, y, z)) return; } // still not in LoS, give up and return first position found x = first_x; y = first_y; z = first_z; } void WorldObject::GetClosePoint(float &x, float &y, float &z, float size, float distance2d /*= 0*/, float angle /*= 0*/) const { // angle calculated from current orientation GetNearPoint(NULL, x, y, z, size, distance2d, GetOrientation() + angle); } Position WorldObject::GetNearPosition(float dist, float angle) { Position pos = GetPosition(); MovePosition(pos, dist, angle); return pos; } Position WorldObject::GetFirstCollisionPosition(float dist, float angle) { Position pos = GetPosition(); MovePositionToFirstCollision(pos, dist, angle); return pos; } Position WorldObject::GetRandomNearPosition(float radius) { Position pos = GetPosition(); MovePosition(pos, radius * (float)rand_norm(), (float)rand_norm() * static_cast<float>(2 * M_PI)); return pos; } void WorldObject::GetContactPoint(const WorldObject* obj, float &x, float &y, float &z, float distance2d /*= CONTACT_DISTANCE*/) const { // angle to face `obj` to `this` using distance includes size of `obj` GetNearPoint(obj, x, y, z, obj->GetObjectSize(), distance2d, GetAngle(obj)); } float WorldObject::GetObjectSize() const { return (m_valuesCount > UNIT_FIELD_COMBATREACH) ? m_floatValues[UNIT_FIELD_COMBATREACH] : DEFAULT_WORLD_OBJECT_SIZE; } void WorldObject::MovePosition(Position &pos, float dist, float angle) { angle += GetOrientation(); float destx, desty, destz, ground, floor; destx = pos.m_positionX + dist * std::cos(angle); desty = pos.m_positionY + dist * std::sin(angle); // Prevent invalid coordinates here, position is unchanged if (!Trinity::IsValidMapCoord(destx, desty, pos.m_positionZ)) { TC_LOG_FATAL("misc", "WorldObject::MovePosition: Object (Entry: %u %s) has invalid coordinates X: %f and Y: %f were passed!", GetEntry(), GetGUID().ToString().c_str(), destx, desty); return; } ground = GetMap()->GetHeight(GetPhaseMask(), destx, desty, MAX_HEIGHT, true); floor = GetMap()->GetHeight(GetPhaseMask(), destx, desty, pos.m_positionZ, true); destz = std::fabs(ground - pos.m_positionZ) <= std::fabs(floor - pos.m_positionZ) ? ground : floor; float step = dist/10.0f; for (uint8 j = 0; j < 10; ++j) { // do not allow too big z changes if (std::fabs(pos.m_positionZ - destz) > 6) { destx -= step * std::cos(angle); desty -= step * std::sin(angle); ground = GetMap()->GetHeight(GetPhaseMask(), destx, desty, MAX_HEIGHT, true); floor = GetMap()->GetHeight(GetPhaseMask(), destx, desty, pos.m_positionZ, true); destz = std::fabs(ground - pos.m_positionZ) <= std::fabs(floor - pos.m_positionZ) ? ground : floor; } // we have correct destz now else { pos.Relocate(destx, desty, destz); break; } } Trinity::NormalizeMapCoord(pos.m_positionX); Trinity::NormalizeMapCoord(pos.m_positionY); UpdateGroundPositionZ(pos.m_positionX, pos.m_positionY, pos.m_positionZ); pos.SetOrientation(GetOrientation()); } // @todo: replace with WorldObject::UpdateAllowedPositionZ float NormalizeZforCollision(WorldObject* obj, float x, float y, float z) { float ground = obj->GetMap()->GetHeight(obj->GetPhaseMask(), x, y, MAX_HEIGHT, true); float floor = obj->GetMap()->GetHeight(obj->GetPhaseMask(), x, y, z + 2.0f, true); float helper = std::fabs(ground - z) <= std::fabs(floor - z) ? ground : floor; if (z > helper) // must be above ground { if (Unit* unit = obj->ToUnit()) { if (unit->CanFly()) return z; } LiquidData liquid_status; ZLiquidStatus res = obj->GetMap()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status); if (res && liquid_status.level > helper) // water must be above ground { if (liquid_status.level > z) // z is underwater return z; else return std::fabs(liquid_status.level - z) <= std::fabs(helper - z) ? liquid_status.level : helper; } } return helper; } void WorldObject::MovePositionToFirstCollision(Position &pos, float dist, float angle) { angle += GetOrientation(); float destx, desty, destz; destx = pos.m_positionX + dist * std::cos(angle); desty = pos.m_positionY + dist * std::sin(angle); // Prevent invalid coordinates here, position is unchanged if (!Trinity::IsValidMapCoord(destx, desty)) { TC_LOG_FATAL("misc", "WorldObject::MovePositionToFirstCollision invalid coordinates X: %f and Y: %f were passed!", destx, desty); return; } destz = NormalizeZforCollision(this, destx, desty, pos.GetPositionZ()); bool col = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), pos.m_positionX, pos.m_positionY, pos.m_positionZ + 0.5f, destx, desty, destz + 0.5f, destx, desty, destz, -0.5f); // collision occured if (col) { // move back a bit destx -= CONTACT_DISTANCE * std::cos(angle); desty -= CONTACT_DISTANCE * std::sin(angle); dist = std::sqrt((pos.m_positionX - destx)*(pos.m_positionX - destx) + (pos.m_positionY - desty)*(pos.m_positionY - desty)); } // check dynamic collision col = GetMap()->getObjectHitPos(GetPhaseMask(), pos.m_positionX, pos.m_positionY, pos.m_positionZ + 0.5f, destx, desty, destz + 0.5f, destx, desty, destz, -0.5f); // Collided with a gameobject if (col) { destx -= CONTACT_DISTANCE * std::cos(angle); desty -= CONTACT_DISTANCE * std::sin(angle); dist = std::sqrt((pos.m_positionX - destx)*(pos.m_positionX - destx) + (pos.m_positionY - desty)*(pos.m_positionY - desty)); } float step = dist / 10.0f; for (uint8 j = 0; j < 10; ++j) { // do not allow too big z changes if (std::fabs(pos.m_positionZ - destz) > 6.0f) { destx -= step * std::cos(angle); desty -= step * std::sin(angle); destz = NormalizeZforCollision(this, destx, desty, pos.GetPositionZ()); } // we have correct destz now else { pos.Relocate(destx, desty, destz); break; } } Trinity::NormalizeMapCoord(pos.m_positionX); Trinity::NormalizeMapCoord(pos.m_positionY); pos.m_positionZ = NormalizeZforCollision(this, destx, desty, pos.GetPositionZ()); pos.SetOrientation(GetOrientation()); } void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update) { m_phaseMask = newPhaseMask; if (update && IsInWorld()) UpdateObjectVisibility(); } bool WorldObject::HasInPhaseList(uint32 phase) { return _phases.find(phase) != _phases.end(); } // Updates Area based phases, does not remove phases from auras // Phases from gm commands are not taken into calculations, they can be lost!! void WorldObject::UpdateAreaAndZonePhase() { bool updateNeeded = false; PhaseInfo const& phases = sObjectMgr->GetAreaAndZonePhases(); for (PhaseInfo::const_iterator itr = phases.begin(); itr != phases.end(); ++itr) { uint32 areaOrZoneId = itr->first; for (PhaseInfoStruct const& phase : itr->second) { if (areaOrZoneId == GetAreaId() || areaOrZoneId == GetZoneId()) { if (sConditionMgr->IsObjectMeetToConditions(this, phase.Conditions)) { // add new phase if condition passed, true if it wasnt added before bool up = SetInPhase(phase.Id, false, true); if (!updateNeeded && up) updateNeeded = true; } else { // condition failed, remove phase, true if there was something removed bool up = SetInPhase(phase.Id, false, false); if (!updateNeeded && up) updateNeeded = true; } } else { // not in area, remove phase, true if there was something removed bool up = SetInPhase(phase.Id, false, false); if (!updateNeeded && up) updateNeeded = true; } } } // do not remove a phase if it would be removed by an area but we have the same phase from an aura if (Unit* unit = ToUnit()) { Unit::AuraEffectList const& auraPhaseList = unit->GetAuraEffectsByType(SPELL_AURA_PHASE); for (Unit::AuraEffectList::const_iterator itr = auraPhaseList.begin(); itr != auraPhaseList.end(); ++itr) { uint32 phase = uint32((*itr)->GetMiscValueB()); bool up = SetInPhase(phase, false, true); if (!updateNeeded && up) updateNeeded = true; } Unit::AuraEffectList const& auraPhaseGroupList = unit->GetAuraEffectsByType(SPELL_AURA_PHASE_GROUP); for (Unit::AuraEffectList::const_iterator itr = auraPhaseGroupList.begin(); itr != auraPhaseGroupList.end(); ++itr) { bool up = false; uint32 phaseGroup = uint32((*itr)->GetMiscValueB()); std::set<uint32> const& phaseIDs = sDB2Manager.GetPhasesForGroup(phaseGroup); for (uint32 phase : phaseIDs) up = SetInPhase(phase, false, true); if (!updateNeeded && up) updateNeeded = true; } } // only update visibility and send packets if there was a change in the phase list if (updateNeeded && GetTypeId() == TYPEID_PLAYER && IsInWorld()) ToPlayer()->GetSession()->SendSetPhaseShift(GetPhases(), GetTerrainSwaps(), GetWorldMapAreaSwaps()); // only update visibilty once, to prevent objects appearing for a moment while adding in multiple phases if (updateNeeded && IsInWorld()) UpdateObjectVisibility(); } bool WorldObject::SetInPhase(uint32 id, bool update, bool apply) { if (id) { if (apply) { if (HasInPhaseList(id)) // do not run the updates if we are already in this phase return false; _phases.insert(id); } else { // if area phase passes the condition we should not remove it (ie: if remove called from aura remove) // this however breaks the .mod phase command, you wont be able to remove any area based phases with it if (std::vector<PhaseInfoStruct> const* phases = sObjectMgr->GetPhasesForArea(GetAreaId())) for (PhaseInfoStruct const& phase : *phases) if (id == phase.Id) if (sConditionMgr->IsObjectMeetToConditions(this, phase.Conditions)) return false; if (!HasInPhaseList(id)) // do not run the updates if we are not in this phase return false; _phases.erase(id); } } RebuildTerrainSwaps(); if (update && IsInWorld()) UpdateObjectVisibility(); return true; } void WorldObject::CopyPhaseFrom(WorldObject* obj, bool update) { if (!obj) return; for (uint32 phase : obj->GetPhases()) SetInPhase(phase, false, true); if (update && IsInWorld()) UpdateObjectVisibility(); } void WorldObject::ClearPhases(bool update) { _phases.clear(); RebuildTerrainSwaps(); if (update && IsInWorld()) UpdateObjectVisibility(); } bool WorldObject::IsInPhase(WorldObject const* obj) const { // PhaseId 169 is the default fallback phase if (_phases.empty() && obj->GetPhases().empty()) return true; if (_phases.empty() && obj->IsInPhase(DEFAULT_PHASE)) return true; if (obj->GetPhases().empty() && IsInPhase(DEFAULT_PHASE)) return true; if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->IsGameMaster()) return true; return Trinity::Containers::Intersects(_phases.begin(), _phases.end(), obj->GetPhases().begin(), obj->GetPhases().end()); } void WorldObject::PlayDistanceSound(uint32 soundId, Player* target /*= nullptr*/) { if (target) target->SendDirectMessage(WorldPackets::Misc::PlaySpeakerbotSound(GetGUID(), soundId).Write()); else SendMessageToSet(WorldPackets::Misc::PlaySpeakerbotSound(GetGUID(), soundId).Write(), true); } void WorldObject::PlayDirectSound(uint32 soundId, Player* target /*= nullptr*/) { if (target) target->SendDirectMessage(WorldPackets::Misc::PlaySound(GetGUID(), soundId).Write()); else SendMessageToSet(WorldPackets::Misc::PlaySound(GetGUID(), soundId).Write(), true); } void WorldObject::DestroyForNearbyPlayers() { if (!IsInWorld()) return; std::list<Player*> targets; Trinity::AnyPlayerInObjectRangeCheck check(this, GetVisibilityRange(), false); Trinity::PlayerListSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(this, targets, check); VisitNearbyWorldObject(GetVisibilityRange(), searcher); for (std::list<Player*>::const_iterator iter = targets.begin(); iter != targets.end(); ++iter) { Player* player = (*iter); if (player == this) continue; if (!player->HaveAtClient(this)) continue; if (isType(TYPEMASK_UNIT) && ToUnit()->GetCharmerGUID() == player->GetGUID()) /// @todo this is for puppet continue; DestroyForPlayer(player); player->m_clientGUIDs.erase(GetGUID()); } } void WorldObject::UpdateObjectVisibility(bool /*forced*/) { //updates object's visibility for nearby players Trinity::VisibleChangesNotifier notifier(*this); VisitNearbyWorldObject(GetVisibilityRange(), notifier); } struct WorldObjectChangeAccumulator { UpdateDataMapType& i_updateDatas; WorldObject& i_object; GuidSet plr_list; WorldObjectChangeAccumulator(WorldObject &obj, UpdateDataMapType &d) : i_updateDatas(d), i_object(obj) { } void Visit(PlayerMapType &m) { Player* source = NULL; for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); BuildPacket(source); if (!source->GetSharedVisionList().empty()) { SharedVisionList::const_iterator it = source->GetSharedVisionList().begin(); for (; it != source->GetSharedVisionList().end(); ++it) BuildPacket(*it); } } } void Visit(CreatureMapType &m) { Creature* source = NULL; for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); if (!source->GetSharedVisionList().empty()) { SharedVisionList::const_iterator it = source->GetSharedVisionList().begin(); for (; it != source->GetSharedVisionList().end(); ++it) BuildPacket(*it); } } } void Visit(DynamicObjectMapType &m) { DynamicObject* source = NULL; for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); ObjectGuid guid = source->GetCasterGUID(); if (guid.IsPlayer()) { //Caster may be NULL if DynObj is in removelist if (Player* caster = ObjectAccessor::FindPlayer(guid)) if (caster->GetGuidValue(PLAYER_FARSIGHT) == source->GetGUID()) BuildPacket(caster); } } } void BuildPacket(Player* player) { // Only send update once to a player if (plr_list.find(player->GetGUID()) == plr_list.end() && player->HaveAtClient(&i_object)) { i_object.BuildFieldsUpdate(player, i_updateDatas); plr_list.insert(player->GetGUID()); } } template<class SKIP> void Visit(GridRefManager<SKIP> &) { } }; void WorldObject::BuildUpdate(UpdateDataMapType& data_map) { CellCoord p = Trinity::ComputeCellCoord(GetPositionX(), GetPositionY()); Cell cell(p); cell.SetNoCreate(); WorldObjectChangeAccumulator notifier(*this, data_map); TypeContainerVisitor<WorldObjectChangeAccumulator, WorldTypeMapContainer > player_notifier(notifier); Map& map = *GetMap(); //we must build packets for all visible players cell.Visit(p, player_notifier, map, *this, GetVisibilityRange()); ClearUpdateMask(false); } void WorldObject::AddToObjectUpdate() { GetMap()->AddUpdateObject(this); } void WorldObject::RemoveFromObjectUpdate() { GetMap()->RemoveUpdateObject(this); } ObjectGuid WorldObject::GetTransGUID() const { if (GetTransport()) return GetTransport()->GetGUID(); return ObjectGuid::Empty; } void WorldObject::RebuildTerrainSwaps() { // Clear all terrain swaps, will be rebuilt below // Reason for this is, multiple phases can have the same terrain swap, we should not remove the swap if another phase still use it _terrainSwaps.clear(); // Check all applied phases for terrain swap and add it only once for (uint32 phaseId : _phases) { if (std::vector<uint32> const* swaps = sObjectMgr->GetPhaseTerrainSwaps(phaseId)) { for (uint32 const& swap : *swaps) { // only add terrain swaps for current map MapEntry const* mapEntry = sMapStore.LookupEntry(swap); if (!mapEntry || mapEntry->ParentMapID != int32(GetMapId())) continue; if (sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_TERRAIN_SWAP, swap, this)) _terrainSwaps.insert(swap); } } } // get default terrain swaps, only for current map always if (std::vector<uint32> const* mapSwaps = sObjectMgr->GetDefaultTerrainSwaps(GetMapId())) for (uint32 const& swap : *mapSwaps) if (sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_TERRAIN_SWAP, swap, this)) _terrainSwaps.insert(swap); // online players have a game client with world map display if (GetTypeId() == TYPEID_PLAYER) RebuildWorldMapAreaSwaps(); } void WorldObject::RebuildWorldMapAreaSwaps() { // Clear all world map area swaps, will be rebuilt below _worldMapAreaSwaps.clear(); // get ALL default terrain swaps, if we are using it (condition is true) // send the worldmaparea for it, to see swapped worldmaparea in client from other maps too, not just from our current TerrainPhaseInfo const& defaults = sObjectMgr->GetDefaultTerrainSwapStore(); for (TerrainPhaseInfo::const_iterator itr = defaults.begin(); itr != defaults.end(); ++itr) for (uint32 const& swap : itr->second) if (std::vector<uint32> const* uiMapSwaps = sObjectMgr->GetTerrainWorldMaps(swap)) if (sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_TERRAIN_SWAP, swap, this)) for (uint32 worldMapAreaId : *uiMapSwaps) _worldMapAreaSwaps.insert(worldMapAreaId); // Check all applied phases for world map area swaps for (uint32 phaseId : _phases) if (std::vector<uint32> const* swaps = sObjectMgr->GetPhaseTerrainSwaps(phaseId)) for (uint32 const& swap : *swaps) if (std::vector<uint32> const* uiMapSwaps = sObjectMgr->GetTerrainWorldMaps(swap)) if (sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_TERRAIN_SWAP, swap, this)) for (uint32 worldMapAreaId : *uiMapSwaps) _worldMapAreaSwaps.insert(worldMapAreaId); }
0
0.947265
1
0.947265
game-dev
MEDIA
0.828699
game-dev
0.956676
1
0.956676
SpongePowered/Sponge
15,492
testplugins/src/main/java/org/spongepowered/test/customdata/CustomDataTest.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.customdata; import com.google.inject.Inject; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.block.entity.BlockEntity; import org.spongepowered.api.command.Command; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.parameter.Parameter; import org.spongepowered.api.data.DataProvider; import org.spongepowered.api.data.DataRegistration; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.persistence.DataBuilder; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataQuery; import org.spongepowered.api.data.persistence.DataSerializable; import org.spongepowered.api.data.persistence.DataStore; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; import org.spongepowered.api.data.persistence.Queries; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityTypes; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.lifecycle.RegisterCommandEvent; import org.spongepowered.api.event.lifecycle.RegisterDataEvent; import org.spongepowered.api.event.network.ServerSideConnectionEvent; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.query.QueryTypes; import org.spongepowered.api.scheduler.Scheduler; import org.spongepowered.api.scheduler.Task; import org.spongepowered.api.util.Ticks; import org.spongepowered.api.world.chunk.WorldChunk; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.storage.ServerWorldProperties; import org.spongepowered.math.vector.Vector3i; import org.spongepowered.plugin.PluginContainer; import org.spongepowered.plugin.builtin.jvm.Plugin; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @Plugin("customdatatest") public final class CustomDataTest { private final PluginContainer plugin; private Key<Value<Integer>> myDataKey; private Key<Value<String>> mySimpleDataKey; private Key<Value<ItemType>> myItemTypeKey; private Key<Value<MyObject>> myObjectKey; @Inject public CustomDataTest(final PluginContainer plugin) { this.plugin = plugin; } private enum Type { ITEMSTACK, ENTITY, BLOCKENTITY, PLAYER, USER, BLOCK, CHUNK, LEVEL } @Listener private void onRegisterSpongeCommand(final RegisterCommandEvent<Command.Parameterized> event) { final Parameter.Value<Integer> numberKey = Parameter.integerNumber().key("number").optional().build(); final Parameter.Value<Type> type = Parameter.enumValue(Type.class).key("type").optional().build(); final Command.Parameterized myCommand = Command.builder() .addParameter(type) .addParameter(numberKey) .executor(context -> { final Integer number = context.one(numberKey).orElse(1); final ServerPlayer player = context.cause().first(ServerPlayer.class).get(); switch (context.one(type).orElse(Type.ITEMSTACK)) { case ITEMSTACK: final ItemStack stack = ItemStack.of(ItemTypes.PAPER); stack.offer(this.myDataKey, number); stack.offer(this.mySimpleDataKey, "It works! " + number); stack.offer(this.myItemTypeKey, ItemTypes.PAPER.get()); stack.offer(this.myObjectKey, new MyObject(MyEnum.FOO, "it works!")); player.inventory().offer(stack); final List<Slot> slots = player.inventory().query(QueryTypes.ITEM_STACK_CUSTOM.get().of(s -> s.get(this.myDataKey).isPresent())).slots(); final int itemSum = slots.stream().map(Slot::peek).mapToInt(item -> item.get(this.myDataKey).get()).sum(); player.sendActionBar(Component.text(itemSum)); slots.stream().map(Slot::peek).map(s -> s.get(this.mySimpleDataKey)).forEach(data -> data.ifPresent(value -> player.sendMessage(Identity.nil(), Component.text(value)))); break; case ENTITY: final Entity entity = player.world().createEntity(EntityTypes.MINECART.get(), player.position().add(0, 3, 0)); entity.offer(this.myDataKey, number); player.world().spawnEntity(entity); final int entitySum = player.nearbyEntities(5).stream().filter(e -> e.get(this.myDataKey).isPresent()).mapToInt(e -> e.get(this.myDataKey).get()).sum(); player.sendActionBar(Component.text(entitySum)); break; case BLOCKENTITY: player.world().setBlock(player.blockPosition(), BlockTypes.DISPENSER.get().defaultState()); final BlockEntity blockEntity = player.world().blockEntity(player.blockPosition()).get(); blockEntity.offer(this.myDataKey, number); final int blockEntitySum = player.world().blockEntities().stream().filter(e -> e.get(this.myDataKey).isPresent()) .mapToInt(e -> e.get(this.myDataKey).get()).sum(); player.sendActionBar(Component.text(blockEntitySum)); break; case PLAYER: final Integer integer = player.get(this.myDataKey).orElse(0); player.sendActionBar(Component.text(integer)); player.offer(this.myDataKey, number); break; case USER: // delegate to player this.customUserData(player.uniqueId(), number).thenAcceptAsync(v -> { player.kick(Component.text("Setting User data...")); final Scheduler scheduler = Sponge.server().scheduler(); scheduler.submit(Task.builder().delay(Ticks.single()).execute(() -> this.customUserData(player.uniqueId(), number).join()).plugin(this.plugin).build()); scheduler.submit(Task.builder().delay(Ticks.of(2)).execute(() -> this.customUserData(player.uniqueId(), number).join()).plugin(this.plugin).build()); }, Sponge.server().scheduler().executor(this.plugin)); break; case BLOCK: // try out custom data-stores final Integer oldNumber = player.world().get(player.blockPosition(), this.myDataKey).orElse(0); player.sendActionBar(Component.text(oldNumber)); player.world().offer(player.blockPosition(), this.myDataKey, oldNumber + number); break; case CHUNK: final Integer oldNumber2 = player.world().chunk(player.location().chunkPosition()).get(this.myDataKey).orElse(0); player.sendActionBar(Component.text(oldNumber2)); player.world().chunk(player.location().chunkPosition()).offer(this.myDataKey, oldNumber2 + number); break; case LEVEL: final Integer oldNumber3 = player.world().properties().get(this.myDataKey).orElse(0); player.sendActionBar(Component.text(oldNumber3)); player.world().properties().offer(this.myDataKey, oldNumber3 + number); break; } return CommandResult.success(); }) .build(); event.register(this.plugin, myCommand, "customdata"); } @Listener private void onRegisterData(final RegisterDataEvent event) { final ResourceKey key = ResourceKey.of(this.plugin, "mydata"); this.myDataKey = Key.builder().key(key).elementType(Integer.class).build(); final DataProvider<Value<Integer>, Integer> blockDataProvider = DataProvider.mutableBuilder() .key(this.myDataKey).dataHolder(ServerLocation.class) .get(this::getData).set(this::setData).delete(this::removeData) .build(); final DataStore dataStore = DataStore.of(this.myDataKey, DataQuery.of("mykey"), ItemStack.class, User.class, ServerPlayer.class, BlockEntity.class, Entity.class, WorldChunk.class, ServerWorldProperties.class); final DataRegistration myRegistration = DataRegistration.builder() .dataKey(this.myDataKey) .store(dataStore) .provider(blockDataProvider) .build(); event.register(myRegistration); // Or if it is super simple data this.mySimpleDataKey = Key.from(this.plugin, "mysimpledata", String.class); event.register(DataRegistration.of(this.mySimpleDataKey, ItemStack.class)); this.myItemTypeKey = Key.from(this.plugin, "myitemtypedata", ItemType.class); event.register(DataRegistration.of(this.myItemTypeKey, ItemStack.class)); // Custom Plugin controlled Object. Must implement DataSerializable to serialize and provider a DataBuilder to deserialize. this.myObjectKey = Key.from(this.plugin, "myobjectdata", MyObject.class); event.register(DataRegistration.of(this.myObjectKey, ItemStack.class)); Sponge.dataManager().registerBuilder(MyObject.class, new MyObjectBuilder()); } private static class MyObject implements DataSerializable { public MyObject(final MyEnum enumValue, final String stringValue) { this.enumValue = enumValue; this.stringValue = stringValue; } public static final DataQuery ENUM_VALUE = DataQuery.of("enum_value"); public static final DataQuery STRING_VALUE = DataQuery.of("string_value"); public MyEnum enumValue; public String stringValue; @Override public int contentVersion() { return 1; } @Override public DataContainer toContainer() { return DataContainer.createNew() .set(Queries.CONTENT_VERSION, this.contentVersion()) .set(ENUM_VALUE, enumValue.name()) .set(STRING_VALUE, stringValue); } } private static class MyObjectBuilder implements DataBuilder<MyObject> { @Override public Optional<MyObject> build(final DataView container) throws InvalidDataException { final Optional<String> enumValue = container.getString(MyObject.ENUM_VALUE); final Optional<String> stringValue = container.getString(MyObject.STRING_VALUE); if (enumValue.isPresent() && stringValue.isPresent()) { return Optional.of(new MyObject(MyEnum.valueOf(enumValue.get()), stringValue.get())); } return Optional.empty(); } } private enum MyEnum { FOO, BAR } // replace with mongoDB - for web-scale private Map<ResourceKey, Map<Vector3i, Integer>> myCustomData = new HashMap<>(); private DataTransactionResult removeData(final ServerLocation serverLocation) { final Integer removed = this.myCustomData.getOrDefault(serverLocation.worldKey(), Collections.emptyMap()).remove(serverLocation.blockPosition()); if (removed == null) { return DataTransactionResult.failNoData(); } return DataTransactionResult.successRemove(Value.immutableOf(this.myDataKey, removed)); } private DataTransactionResult setData(final ServerLocation serverLocation, final Integer value) { final Map<Vector3i, Integer> worldData = this.myCustomData.computeIfAbsent(serverLocation.worldKey(), k -> new HashMap<>()); worldData.put(serverLocation.blockPosition(), value); return DataTransactionResult.successResult(Value.immutableOf(this.myDataKey, value)); } private Integer getData(final ServerLocation serverLocation) { return this.myCustomData.getOrDefault(serverLocation.worldKey(), Collections.emptyMap()).get(serverLocation.blockPosition()); } @Listener private void onJoin(final ServerSideConnectionEvent.Join event) { final Optional<Integer> myValue = event.player().get(this.myDataKey); myValue.ifPresent(integer -> this.plugin.logger().info("CustomData: {}", integer)); } private CompletableFuture<Void> customUserData(final UUID playerUUID, final int number) { return Sponge.server().userManager().load(playerUUID) .thenAcceptAsync(user -> { if (user.isPresent()) { final Integer integer = user.get().get(this.myDataKey).orElse(0); this.plugin.logger().info("Custom data on user {}: {}", user.get().name(), integer); user.get().offer(this.myDataKey, number); } }, Sponge.server().scheduler().executor(this.plugin)); } }
0
0.906374
1
0.906374
game-dev
MEDIA
0.909317
game-dev
0.9753
1
0.9753
MontagueM/Charm
4,097
ThirdParty/fbx/FbxCachedEffect.cs
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace Internal.Fbx { public class FbxCachedEffect : FbxNodeAttribute { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal FbxCachedEffect(global::System.IntPtr cPtr, bool cMemoryOwn) : base(FbxWrapperNativePINVOKE.FbxCachedEffect_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(FbxCachedEffect obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; throw new global::System.MethodAccessException("C++ destructor does not have public access"); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public static FbxClassId ClassId { set { FbxWrapperNativePINVOKE.FbxCachedEffect_ClassId_set(FbxClassId.getCPtr(value)); } get { global::System.IntPtr cPtr = FbxWrapperNativePINVOKE.FbxCachedEffect_ClassId_get(); FbxClassId ret = (cPtr == global::System.IntPtr.Zero) ? null : new FbxClassId(cPtr, false); return ret; } } public override FbxClassId GetClassId() { FbxClassId ret = new FbxClassId(FbxWrapperNativePINVOKE.FbxCachedEffect_GetClassId(swigCPtr), true); return ret; } public new static FbxCachedEffect Create(FbxManager pManager, string pName) { global::System.IntPtr cPtr = FbxWrapperNativePINVOKE.FbxCachedEffect_Create__SWIG_0(FbxManager.getCPtr(pManager), pName); FbxCachedEffect ret = (cPtr == global::System.IntPtr.Zero) ? null : new FbxCachedEffect(cPtr, false); return ret; } public new static FbxCachedEffect Create(FbxObject pContainer, string pName) { global::System.IntPtr cPtr = FbxWrapperNativePINVOKE.FbxCachedEffect_Create__SWIG_1(FbxObject.getCPtr(pContainer), pName); FbxCachedEffect ret = (cPtr == global::System.IntPtr.Zero) ? null : new FbxCachedEffect(cPtr, false); return ret; } public override FbxNodeAttribute.EType GetAttributeType() { FbxNodeAttribute.EType ret = (FbxNodeAttribute.EType)FbxWrapperNativePINVOKE.FbxCachedEffect_GetAttributeType(swigCPtr); return ret; } public FbxCachedEffect.ECategory GetCategory() { FbxCachedEffect.ECategory ret = (FbxCachedEffect.ECategory)FbxWrapperNativePINVOKE.FbxCachedEffect_GetCategory(swigCPtr); return ret; } public void SetCache(FbxCache pCache, FbxCachedEffect.ECategory pCategory) { FbxWrapperNativePINVOKE.FbxCachedEffect_SetCache__SWIG_0(swigCPtr, FbxCache.getCPtr(pCache), (int)pCategory); } public void SetCache(FbxCache pCache) { FbxWrapperNativePINVOKE.FbxCachedEffect_SetCache__SWIG_1(swigCPtr, FbxCache.getCPtr(pCache)); } public FbxCache GetCache() { global::System.IntPtr cPtr = FbxWrapperNativePINVOKE.FbxCachedEffect_GetCache(swigCPtr); FbxCache ret = (cPtr == global::System.IntPtr.Zero) ? null : new FbxCache(cPtr, false); return ret; } public override string GetTypeName() { string ret = FbxWrapperNativePINVOKE.FbxCachedEffect_GetTypeName(swigCPtr); return ret; } public override FbxStringList GetTypeFlags() { FbxStringList ret = new FbxStringList(FbxWrapperNativePINVOKE.FbxCachedEffect_GetTypeFlags(swigCPtr), true); return ret; } public enum ECategory { eParticles, eFluids, eHair, eGeneric } } }
0
0.594443
1
0.594443
game-dev
MEDIA
0.271393
game-dev
0.630831
1
0.630831
TakuanDaikon/DFGUI
32,961
DFGUI/Scripts/Internal/dfDynamicFont.cs
/* Copyright 2013-2014 Daikon Forge */ /**************************************************************************** * PLEASE NOTE: The code in this file is under extremely active development * and is likely to change quite frequently. It is not recommended to modify * the code in this file, as your changes are likely to be overwritten by * the next product update when it is published. * **************************************************************************/ using UnityEngine; using System; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Globalization; using System.Reflection; using System.Collections; using System.Collections.Generic; using UnityMaterial = UnityEngine.Material; using UnityFont = UnityEngine.Font; using UnityShader = UnityEngine.Shader; #region Documentation /// <summary> /// The dfDynamicFont class is used to render TrueType or OpenType fonts /// in your user interface. /// You can create a dfDynamicFont by following this tutorial - http://www.youtube.com/embed/Tx4NIIK5sWo /// </summary> #endregion [ExecuteInEditMode] [Serializable] [AddComponentMenu( "Daikon Forge/User Interface/Dynamic Font" )] public class dfDynamicFont : dfFontBase { #region Static variables private static List<dfDynamicFont> loadedFonts = new List<dfDynamicFont>(); #endregion #region Serialized private fields [SerializeField] private UnityFont baseFont; [SerializeField] private UnityMaterial material; [SerializeField] private UnityShader shader; [SerializeField] private int baseFontSize = -1; [SerializeField] private int baseline = -1; [SerializeField] private int lineHeight = 0; #endregion #region Private runtime variables protected dfList<FontCharacterRequest> requests = new dfList<FontCharacterRequest>(); #endregion #region dfFontBase overrides /// <summary> /// Gets or sets the Material that will be used to render text /// </summary> public override UnityMaterial Material { get { if( this.baseFont != null && this.material != null ) { this.material.mainTexture = this.baseFont.material.mainTexture; this.material.shader = Shader; } return this.material; } set { if( value != this.material ) { this.material = value; dfGUIManager.RefreshAll(); } } } /// <summary> /// Gets or sets a reference to the shader that will be used to render the text /// </summary> public UnityShader Shader { get { if( this.shader == null ) this.shader = Shader.Find( "Daikon Forge/Dynamic Font Shader" ); return this.shader; } set { this.shader = value; dfGUIManager.RefreshAll(); } } /// <summary> /// Returns a reference to the texture which contains the /// glyph images that will be used to render text /// </summary> public override Texture Texture { get { return this.baseFont.material.mainTexture; } } /// <summary> /// Returns a value indicating whether the font configuration is valid /// </summary> public override bool IsValid { get { return this.baseFont != null && this.Material != null && this.Texture != null; } } /// <summary> /// Gets or sets the base font size that the Font is set to. This value /// *must* match the [Font Size] value of the Font, as it is used during /// rendering to calculate the vertical offset of each character. /// </summary> public override int FontSize { get { return this.baseFontSize; } set { if( value != this.baseFontSize ) { this.baseFontSize = value; dfGUIManager.RefreshAll(); } } } /// <summary> /// Gets or sets the default minimum height of each line of rendered text /// </summary> public override int LineHeight { get { return this.lineHeight; } set { if( value != this.lineHeight ) { this.lineHeight = value; dfGUIManager.RefreshAll(); } } } public override dfFontRendererBase ObtainRenderer() { return DynamicFontRenderer.Obtain( this ); } #endregion #region Public properties /// <summary> /// Gets or sets the TrueType or OpenType baseFont that will be used to render /// any text using this dfDynamicFont /// </summary> public UnityFont BaseFont { get { return this.baseFont; } set { if( value != this.baseFont ) { this.baseFont = value; dfGUIManager.RefreshAll(); } } } public int Baseline { get { return this.baseline; } set { if( value != this.baseline ) { this.baseline = value; dfGUIManager.RefreshAll(); } } } public int Descent { get { return this.LineHeight - this.baseline; } } #endregion #region Static methods public static dfDynamicFont FindByName( string name ) { for( int i = 0; i < loadedFonts.Count; i++ ) { if( string.Equals( loadedFonts[ i ].name, name, StringComparison.OrdinalIgnoreCase ) ) return loadedFonts[ i ]; } var asset = Resources.Load( name ) as GameObject; if( asset == null ) { return null; } var newFont = asset.GetComponent<dfDynamicFont>(); if( newFont == null ) { return null; } loadedFonts.Add( newFont ); return newFont; } #endregion #region Public methods /// <summary> /// Returns a Vector2 structure containing the width and height that would be /// required to render a single line of text at the given size and with the given style /// </summary> /// <param name="text">The single line of text to measure</param> /// <param name="size">The desired font size</param> /// <param name="style">The desired text style</param> /// <returns></returns> public Vector2 MeasureText( string text, int size, FontStyle style ) { RequestCharacters( text, size, style ); var multiplier = (float)size / (float)FontSize; var lineHeight = Mathf.CeilToInt( Baseline * multiplier ); var measuredSize = new Vector2( 0, lineHeight ); UnityEngine.CharacterInfo glyph = new UnityEngine.CharacterInfo(); for( int i = 0; i < text.Length; i++ ) { BaseFont.GetCharacterInfo( text[ i ], out glyph, size, style ); var width = Mathf.Ceil( glyph.vert.x + glyph.vert.width ); if( text[ i ] == ' ' ) { width = Mathf.Ceil( glyph.width ); } else if( text[ i ] == '\t' ) { width += size * 4; } measuredSize.x += width; } return measuredSize; } /// <summary> /// Ensures that the requested characters are available in the Unity Font's /// texture atlas at the given size and style. /// </summary> /// <param name="text">The set of characters that will be rendered</param> /// <param name="size">The maximum height, in pixels, of the text to be rendered</param> /// <param name="style">The style of text that will be rendered</param> public void RequestCharacters( string text, int size, FontStyle style ) { if( this.baseFont == null ) throw new NullReferenceException( "Base Font not assigned: " + this.name ); // Ensure that the font manager knows that there is a possibility that this // font's atlas has been changed dfFontManager.Invalidate( this ); // Request the characters and retrieve the glyph data this.baseFont.RequestCharactersInTexture( text, size, style ); } /// <summary> /// Request characters to be added to the font texture in the indicated size and font style /// </summary> public virtual void AddCharacterRequest( string characters, int fontSize, FontStyle style ) { dfFontManager.FlagPendingRequests( this ); var request = FontCharacterRequest.Obtain(); request.Characters = characters; request.FontSize = fontSize; request.FontStyle = style; requests.Add( request ); } /// <summary> /// Issues all pending character requests (added by AddCharacterRequest) /// </summary> public virtual void FlushCharacterRequests() { for( int i = 0; i < requests.Count; i++ ) { var request = requests[ i ]; this.baseFont.RequestCharactersInTexture( request.Characters, request.FontSize, request.FontStyle ); } requests.ReleaseItems(); } #endregion #region Nested classes /// <summary> /// Represents a request for characters in a font /// </summary> protected class FontCharacterRequest : IPoolable { #region Object pooling private static dfList<FontCharacterRequest> pool = new dfList<FontCharacterRequest>(); public static FontCharacterRequest Obtain() { return ( pool.Count > 0 ) ? pool.Pop() : new FontCharacterRequest(); } public void Release() { Characters = null; FontSize = 0; FontStyle = UnityEngine.FontStyle.Normal; pool.Add( this ); } #endregion #region Public fields /// <summary> /// The characters to request /// </summary> public string Characters; /// <summary> /// The font size requested /// </summary> public int FontSize; /// <summary> /// The font style requested /// </summary> public FontStyle FontStyle; #endregion } public class DynamicFontRenderer : dfFontRendererBase, IPoolable { #region Object pooling private static Queue<DynamicFontRenderer> objectPool = new Queue<DynamicFontRenderer>(); #endregion #region Static variables and constants private static Vector2[] OUTLINE_OFFSETS = new Vector2[] { new Vector2( -1, -1 ), new Vector2( -1, 1 ), new Vector2( 1, -1 ), new Vector2( 1, 1 ) }; private static int[] TRIANGLE_INDICES = new int[] { 0, 1, 3, 3, 1, 2 }; private static Stack<Color32> textColors = new Stack<Color32>(); #endregion #region Public properties /// <summary> /// Returns a count of lines of text that were rendered /// </summary> public int LineCount { get { return lines.Count; } } /// <summary> /// Gets or sets a reference to the dfAtlas instance that contains /// any sprites that will be rendered /// </summary> public dfAtlas SpriteAtlas { get; set; } /// <summary> /// Gets or sets a reference to the dfRenderData buffer that will /// hold any sprites which are rendered /// </summary> public dfRenderData SpriteBuffer { get; set; } #endregion #region Private instance fields private dfList<LineRenderInfo> lines = null; private dfList<dfMarkupToken> tokens = null; private bool inUse = false; #endregion #region Constructors internal DynamicFontRenderer() { } #endregion #region Object pooling public static dfFontRendererBase Obtain( dfDynamicFont font ) { var renderer = objectPool.Count > 0 ? objectPool.Dequeue() : new DynamicFontRenderer(); renderer.Reset(); renderer.Font = font; renderer.inUse = true; return renderer; } public override void Release() { if( !inUse ) return; inUse = false; this.Reset(); if( this.tokens != null ) { this.tokens.Release(); this.tokens = null; } if( lines != null ) { lines.ReleaseItems(); lines.Release(); lines = null; } this.BottomColor = (Color32?)null; objectPool.Enqueue( this ); } #endregion #region Public methods /// <summary> /// Returns an array of float values, each one corresponding /// to the width of the character at the same position of the /// source text. NOTE: Does not do any markup processing, and /// must only be used on single-line plaintext. /// </summary> public override float[] GetCharacterWidths( string text ) { var totalWidth = 0f; return GetCharacterWidths( text, 0, text.Length - 1, out totalWidth ); } /// <summary> /// Returns an array of float values, each one corresponding /// to the width of the character at the same position of the /// source text. NOTE: Does not do any markup processing, and /// must only be used on single-line plaintext. /// </summary> public float[] GetCharacterWidths( string text, int startIndex, int endIndex, out float totalWidth ) { totalWidth = 0f; var font = (dfDynamicFont)Font; var fontSize = Mathf.CeilToInt( font.FontSize * TextScale ); var output = new float[ text.Length ]; var last = 0f; var maxWidth = 0f; font.RequestCharacters( text, fontSize, FontStyle.Normal ); UnityEngine.CharacterInfo glyph = new UnityEngine.CharacterInfo(); for( int i = startIndex; i <= endIndex; i++, last = maxWidth ) { if( !font.BaseFont.GetCharacterInfo( text[ i ], out glyph, fontSize, FontStyle.Normal ) ) continue; if( text[ i ] == '\t' ) { maxWidth += TabSize; } else if( text[ i ] == ' ' ) { maxWidth += glyph.width; } else { maxWidth += ( glyph.vert.x + glyph.vert.width ); } output[ i ] = ( maxWidth - last ) * PixelRatio; } return output; } /// <summary> /// Measures the given text and returns the size (in pixels) required /// to render the text. /// </summary> /// <param name="text">The text to be measured</param> /// <returns>The size required to render the text</returns> public override Vector2 MeasureString( string text ) { // Ensure that the required characters can be found in the dynamic font's // character data. var font = (dfDynamicFont)Font; var fontSize = Mathf.CeilToInt( font.FontSize * TextScale ); font.RequestCharacters( text, fontSize, FontStyle.Normal ); tokenize( text ); var lines = calculateLinebreaks(); var totalWidth = 0f; var totalHeight = 0f; for( int i = 0; i < lines.Count; i++ ) { totalWidth = Mathf.Max( lines[ i ].lineWidth, totalWidth ); totalHeight += lines[ i ].lineHeight; } this.tokens.Release(); this.tokens = null; var result = new Vector2( totalWidth, totalHeight ); return result; } /// <summary> /// Render the given text as mesh data to the given destination buffer /// </summary> /// <param name="text">The text to be rendered</param> /// <param name="destination">The dfRenderData buffer that will hold the /// text mesh information</param> public override void Render( string text, dfRenderData destination ) { //@Profiler.BeginSample( "Render dynamic font text" ); textColors.Clear(); textColors.Push( Color.white ); // Ensure that the required characters can be found in the dynamic font's // character data. var font = (dfDynamicFont)Font; var fontSize = Mathf.CeilToInt( font.FontSize * TextScale ); font.RequestCharacters( text, fontSize, FontStyle.Normal ); tokenize( text ); var lines = calculateLinebreaks(); destination.EnsureCapacity( getAnticipatedVertCount( tokens ) ); var maxWidth = 0; var maxHeight = 0; var position = ( VectorOffset / PixelRatio ).CeilToInt(); for( int i = 0; i < lines.Count; i++ ) { var line = lines[ i ]; var lineStartIndex = destination.Vertices.Count; var spriteStartIndex = ( SpriteBuffer != null ) ? SpriteBuffer.Vertices.Count : 0; renderLine( lines[ i ], textColors, position, destination ); position.y -= line.lineHeight; maxWidth = Mathf.Max( (int)line.lineWidth, maxWidth ); maxHeight += Mathf.CeilToInt( line.lineHeight ); if( line.lineWidth > MaxSize.x ) { clipRight( destination, lineStartIndex ); clipRight( SpriteBuffer, spriteStartIndex ); } clipBottom( destination, lineStartIndex ); clipBottom( SpriteBuffer, spriteStartIndex ); } this.RenderedSize = new Vector2( Mathf.Min( MaxSize.x, maxWidth ), Mathf.Min( MaxSize.y, maxHeight ) ) * TextScale; this.tokens.Release(); this.tokens = null; //@Profiler.EndSample(); } #endregion #region Private utility methods private int getAnticipatedVertCount( dfList<dfMarkupToken> tokens ) { var textSize = 4 + ( Shadow ? 4 : 0 ) + ( Outline ? 4 : 0 ); var count = 0; for( int i = 0; i < tokens.Count; i++ ) { var token = tokens[ i ]; if( token.TokenType == dfMarkupTokenType.Text ) { count += textSize * token.Length; } else if( token.TokenType == dfMarkupTokenType.StartTag ) { count += 4; } } return count; } /// <summary> /// Renders a single line of text /// </summary> private void renderLine( LineRenderInfo line, Stack<Color32> colors, Vector3 position, dfRenderData destination ) { position.x += calculateLineAlignment( line ); for( int i = line.startOffset; i <= line.endOffset; i++ ) { var token = tokens[ i ]; var type = token.TokenType; if( type == dfMarkupTokenType.Text ) { renderText( token, colors.Peek(), position, destination ); } else if( type == dfMarkupTokenType.StartTag ) { if( token.Matches( "sprite" ) && SpriteAtlas != null && SpriteBuffer != null ) { renderSprite( token, colors.Peek(), position, SpriteBuffer ); } else if( token.Matches( "color" ) ) { colors.Push( parseColor( token ) ); } } else if( type == dfMarkupTokenType.EndTag ) { if( token.Matches( "color" ) && colors.Count > 1 ) { colors.Pop(); } } position.x += token.Width; } } private void renderText( dfMarkupToken token, Color32 color, Vector3 position, dfRenderData renderData ) { try { //@Profiler.BeginSample( "Render text token" ); var font = (dfDynamicFont)Font; var fontSize = Mathf.CeilToInt( font.FontSize * TextScale ); var fontStyle = FontStyle.Normal; var glyph = new UnityEngine.CharacterInfo(); var descent = font.Descent; var verts = renderData.Vertices; var triangles = renderData.Triangles; var uvs = renderData.UV; var colors = renderData.Colors; var x = position.x; var y = position.y; // Set the render material in the output buffer *after* requesting // glyph data, which may result in CharacterInfo in the dfDynamicFont's // texture atlas being rebuilt. renderData.Material = font.Material; var topColor = applyOpacity( multiplyColors( color, DefaultColor ) ); var bottomColor = topColor; if( BottomColor.HasValue ) { bottomColor = applyOpacity( multiplyColors( color, BottomColor.Value ) ); } for( int i = 0; i < token.Length; i++ ) { if( i > 0 ) x += CharacterSpacing * TextScale; if( !font.baseFont.GetCharacterInfo( token[ i ], out glyph, fontSize, fontStyle ) ) continue; var yadjust = ( font.FontSize + glyph.vert.y ) - fontSize + descent; var quadLeft = ( x + glyph.vert.x ); var quadTop = ( y + yadjust ); var quadRight = ( quadLeft + glyph.vert.width ); var quadBottom = ( quadTop + glyph.vert.height ); var v0 = new Vector3( quadLeft, quadTop ) * PixelRatio; var v1 = new Vector3( quadRight, quadTop ) * PixelRatio; var v2 = new Vector3( quadRight, quadBottom ) * PixelRatio; var v3 = new Vector3( quadLeft, quadBottom ) * PixelRatio; if( Shadow ) { addTriangleIndices( verts, triangles ); var activeShadowOffset = (Vector3)ShadowOffset * PixelRatio; verts.Add( v0 + activeShadowOffset ); verts.Add( v1 + activeShadowOffset ); verts.Add( v2 + activeShadowOffset ); verts.Add( v3 + activeShadowOffset ); var activeShadowColor = applyOpacity( ShadowColor ); colors.Add( activeShadowColor ); colors.Add( activeShadowColor ); colors.Add( activeShadowColor ); colors.Add( activeShadowColor ); addUVCoords( uvs, glyph ); } if( Outline ) { for( int o = 0; o < OUTLINE_OFFSETS.Length; o++ ) { addTriangleIndices( verts, triangles ); var activeOutlineOffset = (Vector3)OUTLINE_OFFSETS[ o ] * OutlineSize * PixelRatio; verts.Add( v0 + activeOutlineOffset ); verts.Add( v1 + activeOutlineOffset ); verts.Add( v2 + activeOutlineOffset ); verts.Add( v3 + activeOutlineOffset ); var activeOutlineColor = applyOpacity( OutlineColor ); colors.Add( activeOutlineColor ); colors.Add( activeOutlineColor ); colors.Add( activeOutlineColor ); colors.Add( activeOutlineColor ); addUVCoords( uvs, glyph ); } } addTriangleIndices( verts, triangles ); verts.Add( v0 ); verts.Add( v1 ); verts.Add( v2 ); verts.Add( v3 ); colors.Add( topColor ); colors.Add( topColor ); colors.Add( bottomColor ); colors.Add( bottomColor ); addUVCoords( uvs, glyph ); x += Mathf.CeilToInt( glyph.vert.x + glyph.vert.width ); } } finally { //@Profiler.EndSample(); } } private static void addUVCoords( dfList<Vector2> uvs, UnityEngine.CharacterInfo glyph ) { var region = glyph.uv; var uvLeft = region.x; var uvTop = region.y + region.height; var uvRight = uvLeft + region.width; var uvBottom = region.y; if( glyph.flipped ) { uvs.Add( new Vector2( uvRight, uvBottom ) ); uvs.Add( new Vector2( uvRight, uvTop ) ); uvs.Add( new Vector2( uvLeft, uvTop ) ); uvs.Add( new Vector2( uvLeft, uvBottom ) ); } else { uvs.Add( new Vector2( uvLeft, uvTop ) ); uvs.Add( new Vector2( uvRight, uvTop ) ); uvs.Add( new Vector2( uvRight, uvBottom ) ); uvs.Add( new Vector2( uvLeft, uvBottom ) ); } } private void renderSprite( dfMarkupToken token, Color32 color, Vector3 position, dfRenderData destination ) { try { //@Profiler.BeginSample( "Render embedded sprite" ); var spriteName = token.GetAttribute( 0 ).Value.Value; var spriteInfo = SpriteAtlas[ spriteName ]; if( spriteInfo == null ) return; var options = new dfSprite.RenderOptions() { atlas = SpriteAtlas, color = color, fillAmount = 1, flip = dfSpriteFlip.None, offset = position, pixelsToUnits = PixelRatio, size = new Vector2( token.Width, token.Height ), spriteInfo = spriteInfo }; dfSprite.renderSprite( SpriteBuffer, options ); } finally { //@Profiler.EndSample(); } } private Color32 parseColor( dfMarkupToken token ) { var color = UnityEngine.Color.white; if( token.AttributeCount == 1 ) { var value = token.GetAttribute( 0 ).Value.Value; if( value.Length == 7 && value[ 0 ] == '#' ) { uint intColor = 0; uint.TryParse( value.Substring( 1 ), NumberStyles.HexNumber, null, out intColor ); color = UIntToColor( intColor | 0xFF000000 ); } else { color = dfMarkupStyle.ParseColor( value, DefaultColor ); } } return applyOpacity( color ); } private Color32 UIntToColor( uint color ) { var a = (byte)( color >> 24 ); var r = (byte)( color >> 16 ); var g = (byte)( color >> 8 ); var b = (byte)( color >> 0 ); return new Color32( r, g, b, a ); } /// <summary> /// Determine where each line of text starts. Assumes that the /// tokens array is already populated and that the render size /// of each token has already been determined. /// </summary> /// <returns></returns> private dfList<LineRenderInfo> calculateLinebreaks() { try { //@Profiler.BeginSample( "Calculate line breaks" ); if( lines != null ) { return lines; } lines = dfList<LineRenderInfo>.Obtain(); var font = (dfDynamicFont)Font; var lastBreak = 0; var startIndex = 0; var index = 0; var lineWidth = 0; var lineHeight = font.Baseline * TextScale; while( index < tokens.Count && lines.Count * lineHeight <= MaxSize.y + lineHeight ) { var token = tokens[ index ]; var type = token.TokenType; if( type == dfMarkupTokenType.Newline ) { lines.Add( LineRenderInfo.Obtain( startIndex, index ) ); startIndex = lastBreak = ++index; lineWidth = 0; continue; } var tokenWidth = Mathf.CeilToInt( token.Width ); var canWrap = WordWrap && lastBreak > startIndex && ( type == dfMarkupTokenType.Text || ( type == dfMarkupTokenType.StartTag && token.Matches( "sprite" ) ) ); if( canWrap && lineWidth + tokenWidth >= MaxSize.x ) { if( lastBreak > startIndex ) { lines.Add( LineRenderInfo.Obtain( startIndex, lastBreak - 1 ) ); startIndex = index = ++lastBreak; lineWidth = 0; } else { lines.Add( LineRenderInfo.Obtain( startIndex, lastBreak - 1 ) ); startIndex = lastBreak = ++index; lineWidth = 0; } continue; } if( type == dfMarkupTokenType.Whitespace ) { lastBreak = index; } lineWidth += tokenWidth; index += 1; } if( startIndex < tokens.Count ) { lines.Add( LineRenderInfo.Obtain( startIndex, tokens.Count - 1 ) ); } for( int i = 0; i < lines.Count; i++ ) { calculateLineSize( lines[ i ] ); } return lines; } finally { //@Profiler.EndSample(); } } private int calculateLineAlignment( LineRenderInfo line ) { var width = line.lineWidth; if( TextAlign == TextAlignment.Left || width < 1 ) return 0; var x = 0f; if( TextAlign == TextAlignment.Right ) { x = MaxSize.x - width; } else { x = ( MaxSize.x - width ) * 0.5f; } return Mathf.CeilToInt( Mathf.Max( 0f, x ) ); } private void calculateLineSize( LineRenderInfo line ) { var font = (dfDynamicFont)Font; line.lineHeight = font.Baseline * TextScale; var width = 0; for( int i = line.startOffset; i <= line.endOffset; i++ ) { width += tokens[ i ].Width; } line.lineWidth = width; } /// <summary> /// Splits the source text into tokens and preprocesses the /// tokens to determine render size required, etc. /// </summary> private void tokenize( string text ) { try { //@Profiler.BeginSample( "Tokenize text" ); if( this.ProcessMarkup ) this.tokens = dfMarkupTokenizer.Tokenize( text ); else this.tokens = dfPlainTextTokenizer.Tokenize( text ); for( int i = 0; i < tokens.Count; i++ ) { calculateTokenRenderSize( tokens[ i ] ); } } finally { //@Profiler.EndSample(); } } /// <summary> /// Calculates the size, in pixels, required to render this /// token on screen. Does not account for scale. /// </summary> /// <param name="token"></param> private void calculateTokenRenderSize( dfMarkupToken token ) { try { //@Profiler.BeginSample( "Calculate token render size" ); var totalWidth = 0f; var ch = '\0'; var font = (dfDynamicFont)Font; var glyph = new UnityEngine.CharacterInfo(); if( token.TokenType == dfMarkupTokenType.Text ) { var fontSize = Mathf.CeilToInt( font.FontSize * TextScale ); for( int i = 0; i < token.Length; i++ ) { // Dereference the original character and obtain character information ch = token[ i ]; font.baseFont.GetCharacterInfo( ch, out glyph, fontSize, FontStyle.Normal ); // TODO: Implement 'tab stops' calculation if( ch == '\t' ) { totalWidth += this.TabSize; continue; } // Add the character width to the total totalWidth += ( ch != ' ' ) ? ( glyph.vert.x + glyph.vert.width ) : ( glyph.width + CharacterSpacing * TextScale ); } if( token.Length > 2 ) { totalWidth += ( token.Length - 2 ) * CharacterSpacing * TextScale; } token.Height = Font.LineHeight; token.Width = Mathf.CeilToInt( totalWidth ); } else if( token.TokenType == dfMarkupTokenType.Whitespace ) { var fontSize = Mathf.CeilToInt( font.FontSize * TextScale ); var spacing = CharacterSpacing * TextScale; for( int i = 0; i < token.Length; i++ ) { // Dereference the original character ch = token[ i ]; // TODO: Implement 'tab stops' calculation if( ch == '\t' ) { totalWidth += this.TabSize; } else if( ch == ' ' ) { font.baseFont.GetCharacterInfo( ch, out glyph, fontSize, FontStyle.Normal ); totalWidth += glyph.width + spacing; } } token.Height = Font.LineHeight; token.Width = Mathf.CeilToInt( totalWidth ); } else if( token.TokenType == dfMarkupTokenType.StartTag ) { if( token.Matches( "sprite" ) && SpriteAtlas != null ) { if( token.AttributeCount == 1 ) { var texture = SpriteAtlas.Texture; var lineHeight = font.Baseline * TextScale; var spriteName = token.GetAttribute( 0 ).Value.Value; var sprite = SpriteAtlas[ spriteName ]; if( sprite != null ) { var aspectRatio = ( sprite.region.width * texture.width ) / ( sprite.region.height * texture.height ); totalWidth = Mathf.CeilToInt( lineHeight * aspectRatio ); } token.Height = Mathf.CeilToInt( lineHeight ); token.Width = Mathf.CeilToInt( totalWidth ); } } } } finally { //@Profiler.EndSample(); } } private float getTabStop( float position ) { var scale = PixelRatio * TextScale; if( TabStops != null && TabStops.Count > 0 ) { for( int i = 0; i < TabStops.Count; i++ ) { if( TabStops[ i ] * scale > position ) return TabStops[ i ] * scale; } } if( TabSize > 0 ) return position + TabSize * scale; return position + ( this.Font.FontSize * 4 * scale ); } private void clipRight( dfRenderData destination, int startIndex ) { if( destination == null ) return; var limit = VectorOffset.x + MaxSize.x * PixelRatio; var verts = destination.Vertices; var uv = destination.UV; for( int i = startIndex; i < verts.Count; i += 4 ) { var ul = verts[ i + 0 ]; var ur = verts[ i + 1 ]; var br = verts[ i + 2 ]; var bl = verts[ i + 3 ]; var w = ur.x - ul.x; if( ur.x > limit ) { var clip = 1f - ( ( limit - ur.x + w ) / w ); verts[ i + 0 ] = ul = new Vector3( Mathf.Min( ul.x, limit ), ul.y, ul.z ); verts[ i + 1 ] = ur = new Vector3( Mathf.Min( ur.x, limit ), ur.y, ur.z ); verts[ i + 2 ] = br = new Vector3( Mathf.Min( br.x, limit ), br.y, br.z ); verts[ i + 3 ] = bl = new Vector3( Mathf.Min( bl.x, limit ), bl.y, bl.z ); var uvx = Mathf.Lerp( uv[ i + 1 ].x, uv[ i ].x, clip ); uv[ i + 1 ] = new Vector2( uvx, uv[ i + 1 ].y ); uv[ i + 2 ] = new Vector2( uvx, uv[ i + 2 ].y ); w = ur.x - ul.x; } } } private void clipBottom( dfRenderData destination, int startIndex ) { if( destination == null ) return; var limit = VectorOffset.y - MaxSize.y * PixelRatio; var verts = destination.Vertices; var uv = destination.UV; var colors = destination.Colors; for( int i = startIndex; i < verts.Count; i += 4 ) { var ul = verts[ i + 0 ]; var ur = verts[ i + 1 ]; var br = verts[ i + 2 ]; var bl = verts[ i + 3 ]; var h = ul.y - bl.y; if( bl.y <= limit ) { var clip = 1f - ( Mathf.Abs( -limit + ul.y ) / h ); verts[ i + 0 ] = ul = new Vector3( ul.x, Mathf.Max( ul.y, limit ), ur.z ); verts[ i + 1 ] = ur = new Vector3( ur.x, Mathf.Max( ur.y, limit ), ur.z ); verts[ i + 2 ] = br = new Vector3( br.x, Mathf.Max( br.y, limit ), br.z ); verts[ i + 3 ] = bl = new Vector3( bl.x, Mathf.Max( bl.y, limit ), bl.z ); uv[ i + 3 ] = Vector2.Lerp( uv[ i + 3 ], uv[ i + 0 ], clip ); uv[ i + 2 ] = Vector2.Lerp( uv[ i + 2 ], uv[ i + 1 ], clip ); var color = Color.Lerp( colors[ i + 3 ], colors[ i ], clip ); colors[ i + 3 ] = color; colors[ i + 2 ] = color; } } } private Color32 applyOpacity( Color32 color ) { color.a = (byte)( Opacity * 255 ); return color; } private static void addTriangleIndices( dfList<Vector3> verts, dfList<int> triangles ) { var vcount = verts.Count; var indices = TRIANGLE_INDICES; for( int ii = 0; ii < indices.Length; ii++ ) { triangles.Add( vcount + indices[ ii ] ); } } private Color multiplyColors( Color lhs, Color rhs ) { return new Color ( lhs.r * rhs.r, lhs.g * rhs.g, lhs.b * rhs.b, lhs.a * rhs.a ); } #endregion } private class LineRenderInfo : IPoolable { #region Public fields and properties public int startOffset; public int endOffset; public float lineWidth; public float lineHeight; public int length { get { return endOffset - startOffset + 1; } } #endregion #region Object Pooling private static dfList<LineRenderInfo> pool = new dfList<LineRenderInfo>(); private LineRenderInfo() { } public static LineRenderInfo Obtain( int start, int end ) { var result = ( pool.Count > 0 ) ? pool.Pop() : new LineRenderInfo(); result.startOffset = start; result.endOffset = end; result.lineHeight = 0; return result; } public void Release() { startOffset = endOffset = 0; lineWidth = lineHeight = 0; pool.Add( this ); } #endregion } #endregion }
0
0.829435
1
0.829435
game-dev
MEDIA
0.734797
game-dev,graphics-rendering
0.986754
1
0.986754
Tencent-RTC/TUIRoomKit
13,844
iOS/TUIRoomKit/Source/Common/Basic/Fluxor/Selector.swift
/* * Fluxor * Copyright (c) Morten Bjerg Gregersen 2020 * MIT license, see LICENSE file for details */ import Foundation // swiftlint:disable function_parameter_count /// Something which selects a `Value` from the specified `State`. public protocol SelectorProtocol { /// The input for the `Selector`. associatedtype State /// The output of the `Selector`, associatedtype Value /** A pure function which takes a `State` and returns a `Value` from it. - Parameter state: The `State` to map - Returns: The `Value` mapped from the `State` */ func map(_ state: State) -> Value } /** A type which takes a `State` and returns a `Value` from it. `Selector`s can be based on other `Selector`s making it possible to select a combined `Value`. */ public class Selector<State, Value>: SelectorProtocol { /// An unique identifier used when overriding the `Selector` on the `MockStore`. public let id = UUID() /// The closue used for the mapping. private let _projector: (State) -> Value /// The latest value for a state hash. internal private(set) var result: (stateHash: UUID, value: Value)? /** Creates a `Selector` from a `keyPath`. - Parameter keyPath: The `keyPath` to create the `Selector` from */ public convenience init(keyPath: KeyPath<State, Value>) { self.init(projector: { $0[keyPath: keyPath] }) } /** Creates a `Selector` from a `projector` closure. - Parameter projector: The `projector` closure to create the `Selector` from */ public init(projector: @escaping (State) -> Value) { _projector = projector } public func map(_ state: State) -> Value { _projector(state) } } /// A `Selector` created from a `Selector`s and a `projector` function. public class Selector1<State, S1, Value>: Selector<State, Value> where S1: SelectorProtocol, S1.State == State { /// A pure function which takes the `Value` from the other `Selector` and returns a new `Value`. public let projector: (S1.Value) -> Value /** Creates a `Selector` from a `Selector` and a `projector` function. - Parameter selector1: The first `Selector` - Parameter projector: The closure to pass the value from the `Selector` to */ public init(_ selector1: S1, _ projector: @escaping (S1.Value) -> Value) { self.projector = projector super.init(projector: { projector(selector1.map($0)) }) } /** Creates a `Selector` from a `Selector` and a `projector` function. - Parameter selector1: The first `Selector` - Parameter projector: The closure to pass the value from the `Selector` to */ public convenience init(_ selector1: S1, keyPath: KeyPath<S1.Value, Value>) { self.init(selector1) { $0[keyPath: keyPath] } } } /// A `Selector` created from two `Selector`s and a `projector` function. public class Selector2<State, S1, S2, Value>: Selector<State, Value> where S1: SelectorProtocol, S1.State == State, S2: SelectorProtocol, S2.State == State { /// A pure function which takes the `Value`s from the other `Selector`s and returns a new `Value`. public let projector: (S1.Value, S2.Value) -> Value /** Creates a `Selector` from two `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter projector: The closure to pass the values from the `Selector`s to */ public init(_ selector1: S1, _ selector2: S2, _ projector: @escaping (S1.Value, S2.Value) -> Value) { self.projector = projector super.init(projector: { projector(selector1.map($0), selector2.map($0)) }) } } /// A `Selector` created from three `Selector`s and a `projector` function. public class Selector3<State, S1, S2, S3, Value>: Selector<State, Value> where S1: SelectorProtocol, S1.State == State, S2: SelectorProtocol, S2.State == State, S3: SelectorProtocol, S3.State == State { /// A pure function which takes the `Value`s from the other `Selector`s and returns a new `Value`. public let projector: (S1.Value, S2.Value, S3.Value) -> Value /** Creates a `Selector` from three `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter selector3: The third `Selector` - Parameter projector: The closure to pass the values from the `Selectors` to */ public init(_ selector1: S1, _ selector2: S2, _ selector3: S3, _ projector: @escaping (S1.Value, S2.Value, S3.Value) -> Value) { self.projector = projector super.init(projector: { projector(selector1.map($0), selector2.map($0), selector3.map($0)) }) } } /// A `Selector` created from four `Selector`s and a `projector` function. public class Selector4<State, S1, S2, S3, S4, Value>: Selector<State, Value> where S1: SelectorProtocol, S1.State == State, S2: SelectorProtocol, S2.State == State, S3: SelectorProtocol, S3.State == State, S4: SelectorProtocol, S4.State == State { /// A pure function which takes the `Value`s from the other `Selector`s and returns a new `Value`. public let projector: (S1.Value, S2.Value, S3.Value, S4.Value) -> Value /** Creates a `Selector` from four `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter selector3: The third `Selector` - Parameter selector4: The fourth `Selector` - Parameter projector: The closure to pass the values from the `Selectors` to */ public init(_ selector1: S1, _ selector2: S2, _ selector3: S3, _ selector4: S4, _ projector: @escaping (S1.Value, S2.Value, S3.Value, S4.Value) -> Value) { self.projector = projector super.init(projector: { projector(selector1.map($0), selector2.map($0), selector3.map($0), selector4.map($0)) }) } } /// A `Selector` created from five `Selector`s and a `projector` function. public class Selector5<State, S1, S2, S3, S4, S5, Value>: Selector<State, Value> where S1: SelectorProtocol, S1.State == State, S2: SelectorProtocol, S2.State == State, S3: SelectorProtocol, S3.State == State, S4: SelectorProtocol, S4.State == State, S5: SelectorProtocol, S5.State == State { /// A pure function which takes the `Value`s from the other `Selector`s and returns a new `Value`. public let projector: (S1.Value, S2.Value, S3.Value, S4.Value, S5.Value) -> Value /** Creates a `Selector` from five `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter selector3: The third `Selector` - Parameter selector4: The fourth `Selector` - Parameter selector5: The fifth `Selector` - Parameter projector: The closure to pass the values from the `Selectors` to */ public init(_ selector1: S1, _ selector2: S2, _ selector3: S3, _ selector4: S4, _ selector5: S5, _ projector: @escaping (S1.Value, S2.Value, S3.Value, S4.Value, S5.Value) -> Value) { self.projector = projector super.init(projector: { projector(selector1.map($0), selector2.map($0), selector3.map($0), selector4.map($0), selector5.map($0)) }) } } /// Creator functions. public extension Selector { /** Creates a `Selector` from a `Selector` and a `projector` function. - Parameter selector1: The first `Selector` - Parameter projector: The closure to pass the value from the `Selector` to - Returns: A `Selector` from the given `Selector` and the `projector` function */ static func with<S1>(_ selector1: S1, projector: @escaping (S1.Value) -> Value) -> Selector1<State, S1, Value> { .init(selector1, projector) } /** Creates a `Selector` from a `Selector` and a `KeyPath`. - Parameter selector1: The first `Selector` - Parameter keyPath: The `keyPath` to create the `Selector` from - Parameter keyPath: The `KeyPath` to subscript in the value from the `Selector` - Returns: A `Selector` from the given `Selector` and the `KeyPath` */ static func with<S1>(_ selector1: S1, keyPath: KeyPath<S1.Value, Value>) -> Selector1<State, S1, Value> { .init(selector1, keyPath: keyPath) } /** Creates a `Selector` from two `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter projector: The closure to pass the values from the `Selector`s to - Returns: A `Selector` from the given `Selector`s and the `projector` function */ static func with<S1, S2>(_ selector1: S1, _ selector2: S2, projector: @escaping (S1.Value, S2.Value) -> Value) -> Selector2<State, S1, S2, Value> { .init(selector1, selector2, projector) } /** Creates a `Selector` from three `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter selector3: The third `Selector` - Parameter projector: The closure to pass the values from the `Selectors` to - Returns: A `Selector` from the given `Selector`s and the `projector` function */ static func with<S1, S2, S3>(_ selector1: S1, _ selector2: S2, _ selector3: S3, projector: @escaping (S1.Value, S2.Value, S3.Value) -> Value) -> Selector3<State, S1, S2, S3, Value> { .init(selector1, selector2, selector3, projector) } /** Creates a `Selector` from four `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter selector3: The third `Selector` - Parameter selector4: The fourth `Selector` - Parameter projector: The closure to pass the values from the `Selectors` to - Returns: A `Selector` from the given `Selector`s and the `projector` function */ static func with<S1, S2, S3, S4>(_ selector1: S1, _ selector2: S2, _ selector3: S3, _ selector4: S4, projector: @escaping (S1.Value, S2.Value, S3.Value, S4.Value) -> Value) -> Selector4<State, S1, S2, S3, S4, Value> { .init(selector1, selector2, selector3, selector4, projector) } /** Creates a `Selector` from five `Selector`s and a `projector` function. - Parameter selector1: The first `Selector` - Parameter selector2: The second `Selector` - Parameter selector3: The third `Selector` - Parameter selector4: The fourth `Selector` - Parameter selector5: The fifth `Selector` - Parameter projector: The closure to pass the values from the `Selectors` to - Returns: A `Selector` from the given `Selector`s and the `projector` function */ static func with<S1, S2, S3, S4, S5>(_ selector1: S1, _ selector2: S2, _ selector3: S3, _ selector4: S4, _ selector5: S5, projector: @escaping (S1.Value, S2.Value, S3.Value, S4.Value, S5.Value) -> Value) -> Selector5<State, S1, S2, S3, S4, S5, Value> { .init(selector1, selector2, selector3, selector4, selector5, projector) } } /// Memoization support, where the `Selector` remembers the last result to speed up mapping. internal extension Selector { /** Sets the value and the corresponding `stateHash`. - Parameter value: The value to save - Parameter stateHash: The hash of the state the value was selected from */ func setResult(value: Value, forStateHash stateHash: UUID) { result = (stateHash: stateHash, value: value) } /** Selects the `Value` from the `State` based on the subclass's `map` function and saves the result. - If a value is already saved and the saved state hash matches the passed, the saved value is returned. - If a value is already saved but the saved state hash doesn't match the passed a new value is selected and saved along with the passed state hash - Parameter state: The `State` to select from - Parameter stateHash: The hash of the `State` to select from - Returns: The `Value` mapped with the `projector` */ func map(_ state: State, stateHash: UUID) -> Value { if let result = result, result.stateHash == stateHash { return result.value } let value = map(state) setResult(value: value, forStateHash: stateHash) return value } }
0
0.762896
1
0.762896
game-dev
MEDIA
0.678465
game-dev
0.593732
1
0.593732
rizonesoft/Notepad3
6,033
grepWinNP3/sktoolslib_mod/AnimationManager.h
// sktoolslib - common files for SK tools // Copyright (C) 2017, 2020-2021 - Stefan Kueng // 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, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // /** * \brief helper class for the Windows Animation Manager. * Provides convenience methods to use the Windows Animation Manager using * timer events. * * Example to animate transparency: * \code * // create the animation variable for the alpha value to animate. * // Note: this variable can be a temp variable, but then subsequent * // animations won't stop previous animations of the variable. * CMyWindow::CMyWindow() * { * // m_AnimVarAlpha is a member variable of type IUIAnimationVariablePtr * m_AnimVarAlpha = Animator::Instance().CreateAnimationVariable(0); * } * void MakeVisible() * { * auto transAlpha = Animator::Instance().CreateLinearTransition(0.3, 255); * auto storyBoard = Animator::Instance().CreateStoryBoard(); * storyBoard->AddTransition(m_AnimVarAlpha, transAlpha); * Animator::Instance().RunStoryBoard(storyBoard, [this]() * { * SetTransparency((BYTE)Animator::GetIntegerValue(m_AnimVarAlpha)); * }); * } * * void MakeInvisible() * { * auto transAlpha = Animator::Instance().CreateLinearTransition(0.5, 0); * auto storyBoard = Animator::Instance().CreateStoryBoard(); * storyBoard->AddTransition(m_AnimVarAlpha, transAlpha); * Animator::Instance().RunStoryBoard(storyBoard, [this]() * { * SetTransparency((BYTE)Animator::GetIntegerValue(m_AnimVarAlpha)); * }); * } */ #pragma once #include <UIAnimation.h> #include <functional> #include <memory> #include <comip.h> _COM_SMARTPTR_TYPEDEF(IUIAnimationStoryboard, __uuidof(IUIAnimationStoryboard)); _COM_SMARTPTR_TYPEDEF(IUIAnimationVariable, __uuidof(IUIAnimationVariable)); _COM_SMARTPTR_TYPEDEF(IUIAnimationManager, __uuidof(IUIAnimationManager)); _COM_SMARTPTR_TYPEDEF(IUIAnimationTransitionLibrary, __uuidof(IUIAnimationTransitionLibrary)); _COM_SMARTPTR_TYPEDEF(IUIAnimationTimer, __uuidof(IUIAnimationTimer)); _COM_SMARTPTR_TYPEDEF(IUIAnimationTimerUpdateHandler, __uuidof(IUIAnimationTimerUpdateHandler)); _COM_SMARTPTR_TYPEDEF(IUIAnimationTransition, __uuidof(IUIAnimationTransition)); class CTimerEventHandler; class AnimationVariable { public: IUIAnimationVariablePtr m_animVar; double m_defaultValue = 0.0; }; class Animator { public: /// the singleton accessor static Animator& Instance(); /// shuts down the animation manager. /// call this *before* COM gets shut down, i.e. before CoUninitialize() or OleUninitialize(). static void ShutDown(); static bool IsInstanceActive(); /// Disable copying Animator(const Animator&) = delete; Animator& operator=(const Animator&) = delete; AnimationVariable CreateAnimationVariable(double start, double defValue) const; static INT32 GetIntegerValue(AnimationVariable& var); static double GetValue(AnimationVariable& var); IUIAnimationTransitionPtr CreateAccelerateDecelerateTransition(AnimationVariable& var, UI_ANIMATION_SECONDS duration, double finalValue, double accelerationRatio = 0.4, double decelerationRatio = 0.4) const; IUIAnimationTransitionPtr CreateSmoothStopTransition(AnimationVariable& var, UI_ANIMATION_SECONDS duration, double finalValue) const; IUIAnimationTransitionPtr CreateParabolicTransitionFromAcceleration(AnimationVariable& var, double finalValue, double finalVelocity, double acceleration) const; IUIAnimationTransitionPtr CreateCubicTransition(AnimationVariable& var, UI_ANIMATION_SECONDS maximumDuration, double finalValue, double finalVelocity) const; IUIAnimationTransitionPtr CreateReversalTransition(UI_ANIMATION_SECONDS duration) const; IUIAnimationTransitionPtr CreateSinusoidalTransitionFromRange(UI_ANIMATION_SECONDS duration, double minimumValue, double maximumValue, UI_ANIMATION_SECONDS period, UI_ANIMATION_SLOPE slope) const; IUIAnimationTransitionPtr CreateSinusoidalTransitionFromVelocity(UI_ANIMATION_SECONDS duration, UI_ANIMATION_SECONDS period) const; IUIAnimationTransitionPtr CreateLinearTransitionFromSpeed(AnimationVariable& var, double speed, double finalValue) const; IUIAnimationTransitionPtr CreateLinearTransition(AnimationVariable& var, UI_ANIMATION_SECONDS duration, double finalValue) const; IUIAnimationTransitionPtr CreateDiscreteTransition(AnimationVariable& var, UI_ANIMATION_SECONDS delay, double finalValue, UI_ANIMATION_SECONDS hold) const; IUIAnimationTransitionPtr CreateConstantTransition(UI_ANIMATION_SECONDS duration) const; IUIAnimationTransitionPtr CreateInstantaneousTransition(AnimationVariable& var, double finalValue) const; IUIAnimationStoryboardPtr CreateStoryBoard() const; HRESULT RunStoryBoard(IUIAnimationStoryboardPtr storyBoard, std::function<void()> callback) const; HRESULT AbandonAllStoryBoards() const; virtual ~Animator(); private: Animator(); static std::unique_ptr<Animator> instance; /// The holder of the UIAnimationManager IUIAnimationManagerPtr pAnimMgr; /// The holder of the UIAnimationTimer IUIAnimationTimerPtr pAnimTmr; /// The holder of the UITransitionLibrary IUIAnimationTransitionLibraryPtr pTransLib; /// the timer callback object CTimerEventHandler * timerEventHandler; };
0
0.765069
1
0.765069
game-dev
MEDIA
0.349985
game-dev
0.514659
1
0.514659
Chris3606/GoRogue
2,823
GoRogue/MapGeneration/GenerationContext.cs
using System; using GoRogue.Components; using JetBrains.Annotations; namespace GoRogue.MapGeneration { /// <summary> /// A context object used for map generation. Map generation steps will require and retrieve components that have /// been added to this context when they need to retrieve data about the map generated by previous steps. /// </summary> [PublicAPI] public class GenerationContext : ComponentCollection { /// <summary> /// Height of the map this context represents. /// </summary> public readonly int Height; /// <summary> /// Width of the map this context represents. /// </summary> public readonly int Width; /// <summary> /// Creates a map context with no components, with the given width/height values. /// </summary> /// <param name="width">The width of the map this context represents.</param> /// <param name="height">The height of the map this context represents.</param> public GenerationContext(int width, int height) { if (width <= 0) throw new ArgumentException("Width for generation context must be greater than 0.", nameof(width)); if (height <= 0) throw new ArgumentException("Height for generation context must be greater than 0.", nameof(height)); Width = width; Height = height; } /// <summary> /// Retrieves a context component (optionally with a given tag), or utilizes the specified function to create a /// new one and adds it if an existing one does not exist. /// </summary> /// <typeparam name="TComponent">Type of component to retrieve.</typeparam> /// <param name="newFunc">Function to use to create a new component, if there is no existing component.</param> /// <param name="tag"> /// An optional tag that must be associated with the retrieved or created component. If null is specified, no /// tag is associated with a new object, and any object meeting the type requirement will be allowed as the /// return value. /// </param> /// <returns> /// An existing component of the appropriate type if one exists, or the newly created/added component if not. /// </returns> public TComponent GetFirstOrNew<TComponent>([InstantHandle] Func<TComponent> newFunc, string? tag = null) where TComponent : class { var contextComponent = GetFirstOrDefault<TComponent>(tag); if (contextComponent != null) return contextComponent; contextComponent = newFunc(); Add(contextComponent, tag); return contextComponent; } } }
0
0.881043
1
0.881043
game-dev
MEDIA
0.757909
game-dev
0.81882
1
0.81882
LubiiiCZ/DevQuickie
1,322
Quickie005-IsometricTilemap/Game1.cs
namespace Quickie005; public class Game1 : Game { private readonly GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; private GameManager _gameManager; public Game1() { _graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; IsMouseVisible = true; } protected override void Initialize() { _graphics.PreferredBackBufferWidth = 1024; _graphics.PreferredBackBufferHeight = 768; _graphics.ApplyChanges(); Globals.Content = Content; _gameManager = new(); base.Initialize(); } protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); Globals.SpriteBatch = _spriteBatch; } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); Globals.Update(gameTime); _gameManager.Update(); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); _spriteBatch.Begin(); _gameManager.Draw(); _spriteBatch.End(); base.Draw(gameTime); } }
0
0.636397
1
0.636397
game-dev
MEDIA
0.832589
game-dev
0.624669
1
0.624669
dguenms/Dawn-of-Civilization
8,010
CvGameCoreDLL/FFreeListArray.h
#pragma once // $Revision: #2 $ $Author: mbreitkreutz $ $DateTime: 2005/06/13 13:35:55 $ //------------------------------------------------------------------------------------------------ // // ***************** FIRAXIS GAME ENGINE ******************** // // FILE: FFreeListArray.h // // AUTHOR: Soren Johnson // // PURPOSE: A dynamic array with a free list... // //------------------------------------------------------------------------------------------------ // Copyright (c) 2004 Firaxis Games, Inc. All rights reserved. //------------------------------------------------------------------------------------------------ #ifndef FFREELISTARRAY_H #define FFREELISTARRAY_H #pragma once #include "FFreeListArrayBase.h" #include "FDataStreamBase.h" template <class T> class FFreeListArray : public FFreeListArrayBase<T> { public: FFreeListArray(); virtual ~FFreeListArray(); virtual void init(int iNumSlots = 8); virtual void uninit(); virtual T* getAt(int iIndex); void insert(T data); void insertAt(T data, int iIndex); void insertFirst(T data); int getIndex(T data); bool remove(T data); bool removeAt(int iIndex); virtual void removeAll(); void Read( FDataStreamBase* pStream ); void Write( FDataStreamBase* pStream ); protected: struct DArrayNode { int iNextFreeIndex; T data; }; DArrayNode* m_pArray; virtual void growArray(); }; // Public Functions... template <class T> FFreeListArray<T>::FFreeListArray() { m_iFreeListHead = FFreeList::FLA_FREE_LIST_INDEX; m_iFreeListCount = 0; m_iLastIndex = FFreeList::INVALID_INDEX; m_iNumSlots = 0; m_pArray = NULL; } template <class T> FFreeListArray<T>::~FFreeListArray() { uninit(); } template <class T> void FFreeListArray<T>::init(int iNumSlots) { int iI; uninit(); m_iFreeListHead = FLA_FREE_LIST_INDEX; m_iFreeListCount = 0; m_iLastIndex = FFreeList::INVALID_INDEX; m_iNumSlots = iNumSlots; if (m_iNumSlots > 0) { m_pArray = new DArrayNode[m_iNumSlots]; for (iI = 0; iI < m_iNumSlots; iI++) { m_pArray[iI].iNextFreeIndex = FFreeList::INVALID_INDEX; } } } template <class T> void FFreeListArray<T>::uninit() { if (m_pArray != NULL) { removeAll(); SAFE_DELETE_ARRAY(m_pArray); } } template <class T> void FFreeListArray<T>::insert(T data) { int iIndex; if (m_pArray == NULL) { init(); } if ((m_iLastIndex == m_iNumSlots - 1) && (m_iFreeListCount == 0)) { growArray(); } if (m_iFreeListCount > 0) { iIndex = m_iFreeListHead; m_iFreeListHead = m_pArray[m_iFreeListHead].iNextFreeIndex; m_iFreeListCount--; } else { m_iLastIndex++; iIndex = m_iLastIndex; } m_pArray[iIndex].data = data; m_pArray[iIndex].iNextFreeIndex = FFreeList::INVALID_INDEX; } template <class T> void FFreeListArray<T>::insertAt(T data, int iIndex) { int iTempIndex; if (m_pArray == NULL) { init(); } if (iIndex <= m_iLastIndex) { if (m_pArray[iIndex].iNextFreeIndex == FFreeList::INVALID_INDEX) { m_pArray[iIndex].data = data; return; } } while (iIndex > m_iNumSlots - 1) { growArray(); } if (iIndex > m_iLastIndex) { while (iIndex != m_iLastIndex + 1) { m_iLastIndex++; m_pArray[m_iLastIndex].iNextFreeIndex = m_iFreeListHead; m_iFreeListHead = m_iLastIndex; m_iFreeListCount++; } m_iLastIndex++; } m_pArray[iIndex].data = data; if (m_iFreeListHead != FLA_FREE_LIST_INDEX) { if (iIndex == m_iFreeListHead) { m_iFreeListHead = m_pArray[iIndex].iNextFreeIndex; m_iFreeListCount--; } else { iTempIndex = m_iFreeListHead; while (iTempIndex != FLA_FREE_LIST_INDEX) { assert(iTempIndex != FFreeList::INVALID_INDEX); if (m_pArray[iTempIndex].iNextFreeIndex == iIndex) { m_pArray[iTempIndex].iNextFreeIndex = m_pArray[iIndex].iNextFreeIndex; m_iFreeListCount--; break; } iTempIndex = m_pArray[iTempIndex].iNextFreeIndex; } } } m_pArray[iIndex].iNextFreeIndex = FFreeList::INVALID_INDEX; } template <class T> void FFreeListArray<T>::insertFirst(T data) { int iI; if (m_pArray == NULL) { init(); } if ((m_iLastIndex == m_iNumSlots - 1) && (m_iFreeListCount == 0)) { growArray(); } for (iI = 0; iI <= m_iLastIndex; iI++) { if (m_pArray[iI].iNextFreeIndex != FFreeList::INVALID_INDEX) { insertAt(data, iI); return; } } insert(data); } template <class T> T* FFreeListArray<T>::getAt(int iIndex) { if ((m_pArray == NULL) || (iIndex == FFreeList::INVALID_INDEX)) { return NULL; } if ((iIndex >= 0) && (iIndex <= m_iLastIndex)) { if (m_pArray[iIndex].iNextFreeIndex == FFreeList::INVALID_INDEX) { return &(m_pArray[iIndex].data); } } return NULL; } template <class T> int FFreeListArray<T>::getIndex(T data) { int iI; if (m_pArray == NULL) { return FFreeList::INVALID_INDEX; } for (iI = 0; iI <= m_iLastIndex; iI++) { if (m_pArray[iI].iNextFreeIndex == FFreeList::INVALID_INDEX) { if (m_pArray[iI].data == data) { return iI; } } } return FFreeList::INVALID_INDEX; } template <class T> bool FFreeListArray<T>::remove(T data) { int iI; assert(m_pArray != NULL); for (iI = 0; iI <= m_iLastIndex; iI++) { if (m_pArray[iI].iNextFreeIndex == FFreeList::INVALID_INDEX) { if (m_pArray[iI].data == data) { return removeAt(iI); } } } return false; } template <class T> bool FFreeListArray<T>::removeAt(int iIndex) { assert(m_pArray != NULL); if ((iIndex >= 0) && (iIndex <= m_iLastIndex)) { if (m_pArray[iIndex].iNextFreeIndex == FFreeList::INVALID_INDEX) { m_pArray[iIndex].iNextFreeIndex = m_iFreeListHead; m_iFreeListHead = iIndex; m_iFreeListCount++; return true; } } return false; } template <class T> void FFreeListArray<T>::removeAll() { int iI; if (m_pArray == NULL) { return; } m_iFreeListHead = FLA_FREE_LIST_INDEX; m_iFreeListCount = 0; m_iLastIndex = FFreeList::INVALID_INDEX; for (iI = 0; iI < m_iNumSlots; iI++) { m_pArray[iI].iNextFreeIndex = FFreeList::INVALID_INDEX; } } // Protected functions... template <class T> void FFreeListArray<T>::growArray() { DArrayNode* pOldArray; int iOldNumSlots; int iI; pOldArray = m_pArray; iOldNumSlots = m_iNumSlots; m_iNumSlots *= 2; m_pArray = new DArrayNode[m_iNumSlots]; for (iI = 0; iI < m_iNumSlots; iI++) { if (iI < iOldNumSlots) { m_pArray[iI] = pOldArray[iI]; } else { m_pArray[iI].iNextFreeIndex = FFreeList::INVALID_INDEX; } } delete [] pOldArray; } // // use when list contains non-streamable types // template < class T > inline void FFreeListArray< T >::Read( FDataStreamBase* pStream ) { int iCount = 0; pStream->Read( &iCount ); init( iCount ); if ( iCount ) { for ( int i = 0; i < iCount; i++ ) { T* pData = new T; pStream->Read( sizeof ( T ), ( byte* )pData ); insert( pData ); } } } template < class T > inline void FFreeListArray< T >::Write( FDataStreamBase* pStream ) { int iCount = getCount(); pStream->Write( iCount ); for ( int i = 0; i < getIndexAfterLast(); i++ ) { if ( getAt( i ) ) { pStream->Write( sizeof ( T ), ( byte* )getAt( i ) ); } } } //------------------------------- // Serialization helper templates: //------------------------------- // // use when list contains streamable types // template < class T > inline void ReadStreamableFFreeListArray( FFreeListArray< T >& flist, FDataStreamBase* pStream ) { int iCount = 0; pStream->Read( &iCount ); flist.init( iCount ); if ( iCount ) { for ( int i = 0; i < iCount; i++ ) { T* pData = new T; pData->read( pStream ); flist.insert( pData ); } } } // // use when list contains streamable types // template < class T > inline void WriteStreamableFFreeListArray( FFreeListArray< T >& flist, FDataStreamBase* pStream ) { int iCount = flist.getCount(); pStream->Write( iCount ); for ( int i = 0; i < flist.getIndexAfterLast(); i++ ) { if ( flist[ i ] ) { flist[ i ]->write( pStream ); } } } #endif //FFREELISTARRAY_H
0
0.987173
1
0.987173
game-dev
MEDIA
0.371179
game-dev
0.987181
1
0.987181
Haruma-K/UnityDebugSheet
2,446
Assets/UnityDebugSheet/Editor/Foundation/Drawer/DrawerEditor.cs
using UnityEditor; using UnityEngine; namespace Drawer.Editor { [CustomEditor(typeof(UnityDebugSheet.Runtime.Foundation.Drawer.Drawer), true)] public class DrawerEditor : UnityEditor.Editor { private bool _debugFoldout; private SerializedProperty _directionProp; private SerializedProperty _moveInsideSafeAreaProp; private SerializedProperty _openOnStartProp; private SerializedProperty _scriptProp; private SerializedProperty _sizeProp; protected virtual void OnEnable() { _scriptProp = serializedObject.FindProperty("m_Script"); _directionProp = serializedObject.FindProperty("_direction"); _sizeProp = serializedObject.FindProperty("_size"); _moveInsideSafeAreaProp = serializedObject.FindProperty("_moveInsideSafeArea"); _openOnStartProp = serializedObject.FindProperty("_openOnStart"); } public override void OnInspectorGUI() { serializedObject.Update(); DrawProperties(); serializedObject.ApplyModifiedProperties(); _debugFoldout = EditorGUILayout.BeginFoldoutHeaderGroup(_debugFoldout, "Debug"); if (_debugFoldout) { EditorGUILayout.BeginVertical(GUI.skin.box); DrawDebugMenu(); EditorGUILayout.EndVertical(); } EditorGUILayout.EndFoldoutHeaderGroup(); } protected virtual void DrawProperties() { GUI.enabled = false; EditorGUILayout.PropertyField(_scriptProp); GUI.enabled = true; EditorGUILayout.PropertyField(_directionProp); EditorGUILayout.PropertyField(_sizeProp); EditorGUILayout.PropertyField(_moveInsideSafeAreaProp); EditorGUILayout.PropertyField(_openOnStartProp); } protected virtual void DrawDebugMenu() { var component = (UnityDebugSheet.Runtime.Foundation.Drawer.Drawer)target; using (var ccs = new EditorGUI.ChangeCheckScope()) { var progress = EditorGUILayout.Slider("Progress", component.Progress, 0.0f, 1.0f); if (ccs.changed) { component.Progress = progress; EditorApplication.QueuePlayerLoopUpdate(); } } } } }
0
0.81689
1
0.81689
game-dev
MEDIA
0.970688
game-dev
0.894582
1
0.894582
microsoft/Forerunner
2,056
crypto/bn256/cloudflare/mul_bmi2_amd64.h
#define mulBMI2(a0,a1,a2,a3, rb) \ MOVQ a0, DX \ MOVQ $0, R13 \ MULXQ 0+rb, R8, R9 \ MULXQ 8+rb, AX, R10 \ ADDQ AX, R9 \ MULXQ 16+rb, AX, R11 \ ADCQ AX, R10 \ MULXQ 24+rb, AX, R12 \ ADCQ AX, R11 \ ADCQ $0, R12 \ ADCQ $0, R13 \ \ MOVQ a1, DX \ MOVQ $0, R14 \ MULXQ 0+rb, AX, BX \ ADDQ AX, R9 \ ADCQ BX, R10 \ MULXQ 16+rb, AX, BX \ ADCQ AX, R11 \ ADCQ BX, R12 \ ADCQ $0, R13 \ MULXQ 8+rb, AX, BX \ ADDQ AX, R10 \ ADCQ BX, R11 \ MULXQ 24+rb, AX, BX \ ADCQ AX, R12 \ ADCQ BX, R13 \ ADCQ $0, R14 \ \ MOVQ a2, DX \ MOVQ $0, R15 \ MULXQ 0+rb, AX, BX \ ADDQ AX, R10 \ ADCQ BX, R11 \ MULXQ 16+rb, AX, BX \ ADCQ AX, R12 \ ADCQ BX, R13 \ ADCQ $0, R14 \ MULXQ 8+rb, AX, BX \ ADDQ AX, R11 \ ADCQ BX, R12 \ MULXQ 24+rb, AX, BX \ ADCQ AX, R13 \ ADCQ BX, R14 \ ADCQ $0, R15 \ \ MOVQ a3, DX \ MULXQ 0+rb, AX, BX \ ADDQ AX, R11 \ ADCQ BX, R12 \ MULXQ 16+rb, AX, BX \ ADCQ AX, R13 \ ADCQ BX, R14 \ ADCQ $0, R15 \ MULXQ 8+rb, AX, BX \ ADDQ AX, R12 \ ADCQ BX, R13 \ MULXQ 24+rb, AX, BX \ ADCQ AX, R14 \ ADCQ BX, R15 #define gfpReduceBMI2() \ \ // m = (T * N') mod R, store m in R8:R9:R10:R11 MOVQ ·np+0(SB), DX \ MULXQ 0(SP), R8, R9 \ MULXQ 8(SP), AX, R10 \ ADDQ AX, R9 \ MULXQ 16(SP), AX, R11 \ ADCQ AX, R10 \ MULXQ 24(SP), AX, BX \ ADCQ AX, R11 \ \ MOVQ ·np+8(SB), DX \ MULXQ 0(SP), AX, BX \ ADDQ AX, R9 \ ADCQ BX, R10 \ MULXQ 16(SP), AX, BX \ ADCQ AX, R11 \ MULXQ 8(SP), AX, BX \ ADDQ AX, R10 \ ADCQ BX, R11 \ \ MOVQ ·np+16(SB), DX \ MULXQ 0(SP), AX, BX \ ADDQ AX, R10 \ ADCQ BX, R11 \ MULXQ 8(SP), AX, BX \ ADDQ AX, R11 \ \ MOVQ ·np+24(SB), DX \ MULXQ 0(SP), AX, BX \ ADDQ AX, R11 \ \ storeBlock(R8,R9,R10,R11, 64(SP)) \ \ \ // m * N mulBMI2(·p2+0(SB),·p2+8(SB),·p2+16(SB),·p2+24(SB), 64(SP)) \ \ \ // Add the 512-bit intermediate to m*N MOVQ $0, AX \ ADDQ 0(SP), R8 \ ADCQ 8(SP), R9 \ ADCQ 16(SP), R10 \ ADCQ 24(SP), R11 \ ADCQ 32(SP), R12 \ ADCQ 40(SP), R13 \ ADCQ 48(SP), R14 \ ADCQ 56(SP), R15 \ ADCQ $0, AX \ \ gfpCarry(R12,R13,R14,R15,AX, R8,R9,R10,R11,BX)
0
0.670791
1
0.670791
game-dev
MEDIA
0.178023
game-dev
0.804239
1
0.804239
magefree/mage
3,743
Mage.Sets/src/mage/cards/j/JetfireIngeniousScientist.java
package mage.cards.j; import mage.MageInt; import mage.Mana; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.VariableCost; import mage.abilities.costs.common.RemoveVariableCountersTargetCost; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.TransformSourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.MoreThanMeetsTheEyeAbility; import mage.abilities.mana.builder.ConditionalManaBuilder; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.SubType; import mage.constants.SuperType; import mage.counters.CounterType; import mage.filter.StaticFilters; import mage.game.Game; import mage.game.permanent.token.PowerstoneToken; import mage.players.Player; import mage.target.TargetPlayer; import mage.util.CardUtil; import java.util.UUID; /** * @author TheElk801 */ public final class JetfireIngeniousScientist extends CardImpl { public JetfireIngeniousScientist(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{4}{U}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.ROBOT); this.power = new MageInt(3); this.toughness = new MageInt(4); this.secondSideCardClazz = mage.cards.j.JetfireAirGuardian.class; // More Than Meets the Eye {3}{U} this.addAbility(new MoreThanMeetsTheEyeAbility(this, "{3}{U}")); // Flying this.addAbility(FlyingAbility.getInstance()); // Remove one or more +1/+1 counters from among artifacts you control: Target player adds that much {C}. This mana can't be spent to cast nonartifact spells. Convert Jetfire. Ability ability = new SimpleActivatedAbility( new JetfireIngeniousScientistEffect(), new RemoveVariableCountersTargetCost( StaticFilters.FILTER_CONTROLLED_PERMANENT_ARTIFACTS, CounterType.P1P1, "one or more", 1 ) ); ability.addEffect(new TransformSourceEffect().setText("convert {this}")); ability.addTarget(new TargetPlayer()); this.addAbility(ability); } private JetfireIngeniousScientist(final JetfireIngeniousScientist card) { super(card); } @Override public JetfireIngeniousScientist copy() { return new JetfireIngeniousScientist(this); } } class JetfireIngeniousScientistEffect extends OneShotEffect { JetfireIngeniousScientistEffect() { super(Outcome.Benefit); staticText = "target player adds that much {C}. This mana can't be spent to cast nonartifact spells"; } private JetfireIngeniousScientistEffect(final JetfireIngeniousScientistEffect effect) { super(effect); } @Override public JetfireIngeniousScientistEffect copy() { return new JetfireIngeniousScientistEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(getTargetPointer().getFirst(game, source)); int countersRemoved = CardUtil.castStream( source.getCosts().stream(), VariableCost.class ).mapToInt(VariableCost::getAmount).sum(); if (player == null || countersRemoved < 1) { return false; } ConditionalManaBuilder manaBuilder = PowerstoneToken.makeBuilder(); Mana mana = manaBuilder.setMana(Mana.ColorlessMana(countersRemoved), source, game).build(); player.getManaPool().addMana(mana, game, source); return true; } }
0
0.930514
1
0.930514
game-dev
MEDIA
0.990376
game-dev
0.997632
1
0.997632
ChengF3ng233/Untitled
3,024
src/main/java/net/minecraft/block/BlockStainedGlassPane.java
package net.minecraft.block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; import java.util.List; public class BlockStainedGlassPane extends BlockPane { public static final PropertyEnum<EnumDyeColor> COLOR = PropertyEnum.create("color", EnumDyeColor.class); public BlockStainedGlassPane() { super(Material.glass, false); this.setDefaultState(this.blockState.getBaseState().withProperty(NORTH, Boolean.FALSE).withProperty(EAST, Boolean.FALSE).withProperty(SOUTH, Boolean.FALSE).withProperty(WEST, Boolean.FALSE).withProperty(COLOR, EnumDyeColor.WHITE)); this.setCreativeTab(CreativeTabs.tabDecorations); } /** * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It * returns the metadata of the dropped item based on the old metadata of the block. */ public int damageDropped(IBlockState state) { return state.getValue(COLOR).getMetadata(); } /** * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) */ public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) { for (int i = 0; i < EnumDyeColor.values().length; ++i) { list.add(new ItemStack(itemIn, 1, i)); } } /** * Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState state) { return state.getValue(COLOR).getMapColor(); } public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.TRANSLUCENT; } /** * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(meta)); } /** * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState state) { return state.getValue(COLOR).getMetadata(); } protected BlockState createBlockState() { return new BlockState(this, NORTH, EAST, WEST, SOUTH, COLOR); } public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { BlockBeacon.updateColorAsync(worldIn, pos); } } public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { BlockBeacon.updateColorAsync(worldIn, pos); } } }
0
0.721927
1
0.721927
game-dev
MEDIA
0.9972
game-dev
0.82945
1
0.82945
GrognardsFromHell/TemplePlus
3,423
tpdatasrc/co8infra/scr/Spell121 - Dictum.py
from toee import * from utilities import * def OnBeginSpellCast( spell ): print "Dictum OnBeginSpellCast" print "spell.target_list=", spell.target_list print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level game.particles( "sp-evocation-conjure", spell.caster ) def OnSpellEffect ( spell ): print "Dictum OnSpellEffect" remove_list = [] # The Will save versus banishment is at a -4 penalty spell.dc = spell.dc + 4 #ff = open('dictum.txt', 'w') #ffs = '' target_list = pyspell_targetarray_copy_to_obj_list(spell) for target_item_obj in target_list: obj_hit_dice = target_item_obj.hit_dice_num # Only works on non-lawful creatures alignment = target_item_obj.critter_get_alignment() if not (alignment & ALIGNMENT_LAWFUL): game.particles( 'sp-Destroy Undead', target_item_obj ) # Anything ten or more levels below the caster's level dies #ffs += '\n' + str(spell.caster_level) + '\n' + str(obj_hit_dice) + '\n' if obj_hit_dice <= (spell.caster_level - 10): # So you'll get awarded XP for the kill if not target_item_obj in game.leader.group_list(): target_item_obj.damage( game.leader , D20DT_UNSPECIFIED, dice_new( "1d1" ) ) target_item_obj.critter_kill() # Anything five or more levels below the caster's level is paralyzed if obj_hit_dice <= (spell.caster_level - 5): spell.duration = game.random_range(1,10) * 10 target_item_obj.condition_add_with_args( 'sp-Hold Monster', spell.id, spell.duration, 0 ) # Anything one or more levels below the caster's level is slowed if obj_hit_dice <= (spell.caster_level - 1): spell.duration = game.random_range(1,4) + game.random_range(1,4) target_item_obj.condition_add_with_args( 'sp-Slow', spell.id, spell.duration, 1 ) # Anything the caster's level or below is deafened if obj_hit_dice <= (spell.caster_level): spell.duration = game.random_range(1,4) target_item_obj.condition_add_with_args( 'sp-Shout', spell.id, spell.duration, 0 ) # Summoned and extraplanar creatures below the caster's level are also banished # if they fail a Will save at -4 if target_item_obj.d20_query_has_spell_condition( sp_Summoned ) or target_item_obj.npc_flags_get() & ONF_EXTRAPLANAR != 0: #ffs += 'Spell condition summoned: ' + str(target_item_obj.d20_query_has_spell_condition( sp_Summoned ) ) + '\nExtraplanar: ' + str(target_item_obj.npc_flags_get( ONF_EXTRAPLANAR )) + '\n' # allow Will saving throw to negate if target_item_obj.saving_throw_spell( spell.dc, D20_Save_Will, D20STD_F_NONE, spell.caster, spell.id ): # saving throw successful target_item_obj.float_mesfile_line( 'mes\\spell.mes', 30001 ) game.particles( 'Fizzle', target_item_obj ) else: # saving throw unsuccessful target_item_obj.float_mesfile_line( 'mes\\spell.mes', 30002 ) # creature is sent back to its own plane # kill for now # So you'll get awarded XP for the kill if not target_item_obj in game.leader.group_list(): target_item_obj.damage( game.leader , D20DT_UNSPECIFIED, dice_new( "1d1" ) ) target_item_obj.critter_kill() remove_list.append( target_item_obj ) #ff.write(ffs) #ff.close() spell.target_list.remove_list( remove_list ) spell.spell_end(spell.id) def OnBeginRound( spell ): print "Dictum OnBeginRound" def OnEndSpellCast( spell ): print "Dictum OnEndSpellCast"
0
0.810829
1
0.810829
game-dev
MEDIA
0.936935
game-dev
0.923858
1
0.923858
MiranCZ/altoclef
1,225
src/main/java/adris/altoclef/tasks/resources/wood/CollectFenceGateTask.java
package adris.altoclef.tasks.resources.wood; import adris.altoclef.TaskCatalogue; import adris.altoclef.tasks.resources.CraftWithMatchingPlanksTask; import adris.altoclef.util.CraftingRecipe; import adris.altoclef.util.ItemTarget; import adris.altoclef.util.helpers.ItemHelper; import net.minecraft.item.Item; public class CollectFenceGateTask extends CraftWithMatchingPlanksTask { public CollectFenceGateTask(Item[] targets, ItemTarget planks, int count) { super(targets, woodItems -> woodItems.fenceGate, createRecipe(planks), new boolean[]{false, true, false, false, true, false, false, false, false}, count); } public CollectFenceGateTask(Item target, String plankCatalogueName, int count) { this(new Item[]{target}, new ItemTarget(plankCatalogueName, 1), count); } public CollectFenceGateTask(int count) { this(ItemHelper.WOOD_FENCE_GATE, TaskCatalogue.getItemTarget("planks", 1), count); } private static CraftingRecipe createRecipe(ItemTarget planks) { ItemTarget p = planks; ItemTarget s = TaskCatalogue.getItemTarget("stick", 1); return CraftingRecipe.newShapedRecipe(new ItemTarget[]{s, p, s, s, p, s, null, null, null}, 1); } }
0
0.851971
1
0.851971
game-dev
MEDIA
0.567457
game-dev,desktop-app
0.901676
1
0.901676
baaron4/GW2-Elite-Insights-Parser
47,222
GW2EIEvtcParser/LogLogic/Raids/RaidWings/W8/Bosses/GreerTheBlightbringer.cs
using System.Numerics; using GW2EIEvtcParser.EIData; using GW2EIEvtcParser.Exceptions; using GW2EIEvtcParser.Extensions; using GW2EIEvtcParser.ParsedData; using GW2EIEvtcParser.ParserHelpers; using static GW2EIEvtcParser.ArcDPSEnums; using static GW2EIEvtcParser.LogLogic.LogLogicUtils; using static GW2EIEvtcParser.LogLogic.LogLogicPhaseUtils; using static GW2EIEvtcParser.LogLogic.LogLogicTimeUtils; using static GW2EIEvtcParser.ParserHelper; using static GW2EIEvtcParser.ParserHelpers.LogImages; using static GW2EIEvtcParser.SkillIDs; using static GW2EIEvtcParser.SpeciesIDs; namespace GW2EIEvtcParser.LogLogic; internal class GreerTheBlightbringer : MountBalrior { private static readonly long[] ReflectableProjectiles = [BlobOfBlight, BlobOfBlight2, ScatteringSporeblast, RainOfSpores]; // Legacy, no longer reflectable. private static readonly long[] Boons = [ Aegis, Alacrity, Fury, Might, Protection, Quickness, Regeneration, Resistance, Resolution, Stability, Swiftness, Vigor ]; internal readonly MechanicGroup Mechanics = new MechanicGroup([ new MechanicGroup([ new PlayerSrcHealthDamageHitMechanic(ReflectableProjectiles, new MechanicPlotlySetting(Symbols.YDown, Colors.Pink), "ProjRefl.Greer.H", "Reflected projectiles have hit Greer", "Reflected Projectile Hit (Greer)", 0) .UsingChecker((hde, log) => hde.To.IsSpecies(TargetID.Greer)).WithBuilds(GW2Builds.November2024MountBalriorRelease, GW2Builds.December2024MountBalriorNerfs), new PlayerSrcHealthDamageHitMechanic(ReflectableProjectiles, new MechanicPlotlySetting(Symbols.YDown, Colors.Purple), "ProjRefl.Reeg.H", "Reflected projectiles have hit Reeg", "Reflected Projectile Hit (Reeg)", 0) .UsingChecker((hde, log) => hde.To.IsSpecies(TargetID.Reeg)).WithBuilds(GW2Builds.November2024MountBalriorRelease, GW2Builds.December2024MountBalriorNerfs), new PlayerSrcHealthDamageHitMechanic(ReflectableProjectiles, new MechanicPlotlySetting(Symbols.YDown, Colors.LightPurple), "ProjRefl.Gree.H", "Reflected projectiles have hit Gree", "Reflected Projectile Hit (Gree)", 0) .UsingChecker((hde, log) => hde.To.IsSpecies(TargetID.Gree)).WithBuilds(GW2Builds.November2024MountBalriorRelease, GW2Builds.December2024MountBalriorNerfs), ]), new MechanicGroup([ new PlayerDstHealthDamageHitMechanic([RotTheWorld, RotTheWorldCM], new MechanicPlotlySetting(Symbols.Star, Colors.Teal), "RotWorld.H", "Hit by Rot the World (Breakbar AoEs)", "Rot the World Hit", 0), new PlayerDstHealthDamageHitMechanic([RakeTheRot, RakeTheRot2, RakeTheRot3], new MechanicPlotlySetting(Symbols.PentagonOpen, Colors.LightBlue), "Rake.H", "Hit by Rake the Rot", "Rake the Rot Hit", 0), new MechanicGroup([ new PlayerDstHealthDamageHitMechanic([EruptionOfRot, EruptionOfRot2, EruptionOfRot3, EruptionOfRot4, EruptionOfRot5, EruptionOfRot6], new MechanicPlotlySetting(Symbols.Hexagram, Colors.GreenishYellow), "ErupRot.H", "Hit by Eruption of Rot", "Eruption of Rot Hit", 0), new PlayerDstHealthDamageHitMechanic([RotEruption, RotEruptionCM], new MechanicPlotlySetting(Symbols.TriangleSEOpen, Colors.DarkBlue), "RotErup", "Hit by Rot Eruption", "Rot Eruption Hit", 0), new PlayerDstBuffApplyMechanic(EruptionOfRotBuff, new MechanicPlotlySetting(Symbols.StarTriangleDown, Colors.LightBrown), "ErupRot.S", "Stood in Eruption of Rot (Green)", "Stood in Eruption of Rot", 0), new PlayerDstBuffApplyMechanic(EruptionOfRotBuff, new MechanicPlotlySetting(Symbols.StarTriangleDownOpen, Colors.LightBrown), "ErupRot.Dwn", "Downed by stacking Eruption of Rot (Green)", "Downed by Eruption of Rot", 0) .UsingChecker((bae, log) => bae.To.IsDowned(log, bae.Time)), new PlayerDstEffectMechanic([EffectGUIDs.GreerEruptionOfRotGreen, EffectGUIDs.GreerEruptionOfRotGreen2, EffectGUIDs.GreerEruptionofRotGreen3], new MechanicPlotlySetting(Symbols.Circle, Colors.Green), "ErupRot.T", "Targeted by Eruption of Rot (Green)", "Eruption of Rot (Green)", 0), ]), new PlayerDstHealthDamageHitMechanic([RipplesOfRot, RipplesOfRot2, RipplesOfRotCM, RipplesOfRotCM2], new MechanicPlotlySetting(Symbols.StarSquareOpenDot, Colors.Chocolate), "RippRot.H", "Hit by Ripples of Rot", "Ripples of Rot Hit", 0), new PlayerDstBuffApplyMechanic(PlagueRot, new MechanicPlotlySetting(Symbols.YDown, Colors.Red), "PlagueRot", "Received Plague Rot", "Plague Rot", 0), new PlayerDstBuffApplyMechanic(PlagueRot, new MechanicPlotlySetting(Symbols.YDown, Colors.Yellow), "Unplagued.Achiv", "Achievement Eligibility: Guaranteed Plague Free", "Achiv Unplagued", 0) .UsingEnable(log => log.LogData.IsCM).UsingAchievementEligibility(), ]), new PlayerDstHealthDamageHitMechanic(WaveOfCorruption, new MechanicPlotlySetting(Symbols.HourglassOpen, Colors.LightRed), "WaveCor.H", "Hit by Wave of Corruption", "Wave of Corruption Hit", 0), new MechanicGroup([ new PlayerDstHealthDamageHitMechanic([SeedsOfDecay, SeedsOfDecay2, SeedsOfDecay3], new MechanicPlotlySetting(Symbols.TriangleLeftOpen, Colors.Sand), "SeedsDec.H", "Hit by Seeds of Decay (Greer's Armor Falling)", "Seeds of Decay Hit", 0), new PlayerDstHealthDamageHitMechanic([CageOfDecay, CageOfDecay2, CageOfDecay3, CageOfDecay4, CageOfDecay5], new MechanicPlotlySetting(Symbols.Hourglass, Colors.LightPurple), "Cage.H", "Hit by Cage of Decay", "Cage of Decay Hit", 0), ]), new EnemyCastStartMechanic(TheWorldEndsInDecay, new MechanicPlotlySetting(Symbols.X, Colors.DarkRed), "Enrage", "The World Ends in Decay (Enrage)", "The World Ends in Decay (Enrage)", 0), new MechanicGroup([ new PlayerDstHealthDamageHitMechanic([RainOfSpores, RainOfSpores2], new MechanicPlotlySetting(Symbols.Hexagon, Colors.Green), "RainSpore.H", "Hit by Rain of Spores", "Rain of Spores Hit", 0), new PlayerDstHealthDamageHitMechanic([ScatteringSporeblast, ScatteringSporeblast2], new MechanicPlotlySetting(Symbols.SquareOpen, Colors.GreenishYellow), "ScatSpore.H", "Hit by Scattering Sporeblast", "Scattering Sporeblast Hit", 0), ]), new MechanicGroup([ new PlayerDstBuffApplyMechanic(InfectiousRotBuff, new MechanicPlotlySetting(Symbols.CircleX, Colors.Red), "InfRot.T", "Targeted by Infectious Rot (Hit by Noxious Blight)", "Infectious Rot Target", 0), new PlayerDstHealthDamageHitMechanic([NoxiousBlight, NoxiousBlight2, NoxiousBlightCM, NoxiousBlightCM2], new MechanicPlotlySetting(Symbols.TriangleNEOpen, Colors.DarkPink), "NoxBlight.H", "Hit by Noxious Blight", "Noxious Blight Hit", 0), ]), new PlayerDstHealthDamageHitMechanic([EnfeeblingMiasma, EnfeeblingMiasma2, EnfeeblingMiasma3, EnfeeblingMiasma4], new MechanicPlotlySetting(Symbols.TriangleDown, Colors.LightPurple), "EnfMiasma.H", "Hit by Enfeebling Miasma", "Enfeebling Miasma Hit", 0), new PlayerDstHealthDamageHitMechanic([AuraOfCorruptionDamage_ReegGreeEreg, AuraOfCorruptionDamage_Greer], new MechanicPlotlySetting(Symbols.CircleOpenDot, Colors.Purple), "AuraCorr.H", "Hit by Aura of Corruption (Hitbox)", "Aura of Corruption Hit", 0), new PlayerDstHealthDamageHitMechanic([SweepTheMold, SweepTheMold2, SweepTheMold3], new MechanicPlotlySetting(Symbols.PentagonOpen, Colors.Blue), "Sweep.H", "Hit by Sweep the Mold", "Sweep the Mold Hit", 0), new MechanicGroup([ new PlayerDstHealthDamageHitMechanic([BlobOfBlight, BlobOfBlight2, BlobOfBlight3], new MechanicPlotlySetting(Symbols.Star, Colors.CobaltBlue), "BlobBlight.H", "Hit by Blob of Blight", "Blob of Blight Hit", 0), new PlayerDstBuffApplyMechanic(TargetBuff, new MechanicPlotlySetting(Symbols.CircleXOpen, Colors.LightBlue), "BlobBlight.T", "Targeted by Blob of Blight", "Blob of Blight Target", 0), ]), new PlayerDstHealthDamageHitMechanic([StompTheGrowth, StompTheGrowth2, StompTheGrowth3], new MechanicPlotlySetting(Symbols.CircleOpen, Colors.LightOrange), "Stomp.H", "Hit by Stomp the Growth", "Stomp the Growth Hit", 0), new PlayerDstBuffRemoveMechanic(Boons, new MechanicPlotlySetting(Symbols.Octagon, Colors.Purple), "BoonCorrupt", "Boons corrupted (any)", "Boons Corrupted", 100) .UsingChecker((brae, log) => brae.By.IsAnySpecies([(int)TargetID.Greer, (int)TargetID.Gree, (int)TargetID.Reeg, (int)TargetID.Ereg])), new EnemyDstBuffApplyMechanic(EmpoweredGreer, new MechanicPlotlySetting(Symbols.YUp, Colors.Red), "Empowered", "Gained Empowered", "Empowered", 0), ]); public GreerTheBlightbringer(int triggerID) : base(triggerID) { MechanicList.Add(Mechanics); Extension = "greer"; Icon = EncounterIconGreer; ChestID = ChestID.GreersChest; LogCategoryInformation.InSubCategoryOrder = 0; LogID |= 0x000001; } internal override CombatReplayMap GetCombatMapInternal(ParsedEvtcLog log, CombatReplayDecorationContainer arenaDecorations) { var crMap = new CombatReplayMap( (1912, 1845), (11300, -10621, 18374, -3794)); AddArenaDecorationsPerEncounter(log, arenaDecorations, LogID, CombatReplayGreerTheBlightbringer, crMap); return crMap; } internal override IReadOnlyList<TargetID> GetTargetsIDs() { return [ TargetID.Greer, TargetID.Gree, TargetID.Reeg, TargetID.Ereg, TargetID.ProtoGreerling, ]; } internal override Dictionary<TargetID, int> GetTargetsSortIDs() { return new Dictionary<TargetID, int>() { { TargetID.Greer, 0 }, { TargetID.Gree, 1 }, { TargetID.Reeg, 1 }, { TargetID.Ereg, 1 }, { TargetID.ProtoGreerling, 2 }, }; } internal override IReadOnlyList<TargetID> GetTrashMobsIDs() { return [ TargetID.EmpoweringBeast, ]; } internal override long GetLogOffset(EvtcVersionEvent evtcVersion, LogData logData, AgentData agentData, List<CombatItem> combatData) { long startToUse = GetGenericLogOffset(logData); CombatItem? logStartNPCUpdate = combatData.FirstOrDefault(x => x.IsStateChange == StateChange.LogNPCUpdate); if (logStartNPCUpdate != null) { startToUse = GetEnterCombatTime(logData, agentData, combatData, logStartNPCUpdate.Time, [(int)TargetID.Greer, (int)TargetID.Gree, (int)TargetID.Reeg], logStartNPCUpdate.DstAgent); } return startToUse; } internal static void RenameProtoGreerlings(IReadOnlyList<SingleActor> targets) { foreach (SingleActor target in targets) { if (target.IsSpecies(TargetID.ProtoGreerling)) { target.OverrideName("Champion " + target.Character); } } } internal override void EIEvtcParse(ulong gw2Build, EvtcVersionEvent evtcVersion, LogData logData, AgentData agentData, List<CombatItem> combatData, IReadOnlyDictionary<uint, ExtensionHandler> extensions) { base.EIEvtcParse(gw2Build, evtcVersion, logData, agentData, combatData, extensions); RenameProtoGreerlings(Targets); } internal override LogData.LogMode GetLogMode(CombatData combatData, AgentData agentData, LogData logData) { SingleActor greer = Targets.FirstOrDefault(x => x.IsSpecies(TargetID.Greer)) ?? throw new MissingKeyActorsException("Greer not found"); SingleActor? ereg = Targets.FirstOrDefault(x => x.IsSpecies(TargetID.Ereg)); if (ereg != null) { greer.OverrideName("Godspoil Greer"); return LogData.LogMode.CMNoName; } return LogData.LogMode.Normal; } private static void SetPhaseNameForHP(PhaseData damageImmunityPhase, double hpPercent) { if (hpPercent > 81) { damageImmunityPhase.Name = "100% - 80%"; } else if (hpPercent > 66) { damageImmunityPhase.Name = "80% - 65%"; } else if (hpPercent > 51) { damageImmunityPhase.Name = "65% - 50%"; } else if (hpPercent > 36) { damageImmunityPhase.Name = "50% - 35%"; } else if (hpPercent > 21 ) { damageImmunityPhase.Name = "35% - 20%"; } else { damageImmunityPhase.Name = "20% - 0%"; } } private static void AddMainTitansToPhase(PhaseData phase, SingleActor? greer, IEnumerable<SingleActor> greeAndReg, SingleActor? ereg, ParsedEvtcLog log) { phase.AddTarget(greer, log); phase.AddTargets(greeAndReg, log, PhaseData.TargetPriority.Blocking); phase.AddTarget(ereg, log, PhaseData.TargetPriority.NonBlocking); } internal static List<PhaseData> ComputePhases(ParsedEvtcLog log, SingleActor greer, IEnumerable<SingleActor> greeAndReeg, SingleActor? ereg, IEnumerable<SingleActor> protoGreerlings, EncounterPhaseData encounterPhase, bool requirePhases) { if (!requirePhases) { return []; } var phases = new List<PhaseData>(encounterPhase.IsCM ? 14 : 11); // In shield bubble phases phases.AddRange(GetPhasesByCast(log, InvulnerableBarrier, greer, true, true, encounterPhase.Start, encounterPhase.End)); var mainPhases = new List<PhaseData>(3); for (int i = 0; i < phases.Count; i++) { var phaseIndex = i + 1; PhaseData phase = phases[i]; if (phaseIndex % 2 == 0) { phase.Name = "Split " + (phaseIndex) / 2; phase.AddParentPhase(encounterPhase); phase.AddTargets(greeAndReeg, log); phase.AddTargets([greer, ereg], log, PhaseData.TargetPriority.NonBlocking); } else { mainPhases.Add(phase); phase.AddParentPhase(encounterPhase); phase.Name = "Phase " + (phaseIndex + 1) / 2; AddMainTitansToPhase(phase, greer, greeAndReeg, ereg, log); } } // Generic in between damage immunity phases handling var damageImmunityPhases = GetPhasesByInvul(log, [DamageImmunity1, DamageImmunity2], greer, false, true, encounterPhase.Start, encounterPhase.End); foreach (var damageImmunityPhase in damageImmunityPhases) { damageImmunityPhase.AddParentPhases(mainPhases); var currentMainPhase = phases.LastOrDefault(x => x.Start <= damageImmunityPhase.Start && x.Name.Contains("Phase")); var hpAtStart = greer.GetCurrentHealthPercent(log, damageImmunityPhase.Start); if (currentMainPhase != null) { if (currentMainPhase.End > damageImmunityPhase.End) { AddMainTitansToPhase(damageImmunityPhase, greer, greeAndReeg, ereg, log); phases.Add(damageImmunityPhase); SetPhaseNameForHP(damageImmunityPhase, hpAtStart); } else { var beforeShieldPhase = new SubPhasePhaseData(damageImmunityPhase.Start, currentMainPhase.End); beforeShieldPhase.AddParentPhases(mainPhases); SetPhaseNameForHP(beforeShieldPhase, hpAtStart); AddMainTitansToPhase(beforeShieldPhase, greer, greeAndReeg, ereg, log); phases.Add(beforeShieldPhase); var nextMainPhase = phases.FirstOrDefault(x => x.Start >= damageImmunityPhase.Start && x.Name.Contains("Phase")); if (nextMainPhase != null) { var afterShieldPhase = new SubPhasePhaseData(nextMainPhase.Start, damageImmunityPhase.End); afterShieldPhase.AddParentPhases(mainPhases); SetPhaseNameForHP(afterShieldPhase, greer.GetCurrentHealthPercent(log, afterShieldPhase.Start)); AddMainTitansToPhase(afterShieldPhase, greer, greeAndReeg, ereg, log); phases.Add(afterShieldPhase); } } } } // Enrage handling, greer gets damage immunity again, remove that var lastPhase = phases.Last(); if (log.CombatData.GetAnimatedCastData(TheWorldEndsInDecay).Any(x => lastPhase.Start >= x.Time && x.Time >= encounterPhase.Start)) { phases.Remove(lastPhase); } // Below 20% CM phases handling if (encounterPhase.IsCM && greer.GetBuffStatus(log, DamageImmunity3).Any(x => x.Value > 0)) { var finalPhases = GetPhasesByInvul(log, DamageImmunity3, greer, true, true, encounterPhase.Start, encounterPhase.End); var finalHPPhase = phases.Last(); if (finalPhases.Count > 0) { var p20Percent10PercentPhase = finalPhases[0]; p20Percent10PercentPhase.AddParentPhase(finalHPPhase); p20Percent10PercentPhase.OverrideStart(finalHPPhase.Start); p20Percent10PercentPhase.Name = "20% - 10%"; AddMainTitansToPhase(p20Percent10PercentPhase, greer, greeAndReeg, ereg, log); phases.Add(finalPhases[0]); var protoPhases = 0; var below10Phases = 0; for (var i = 1; i < finalPhases.Count; i++) { var phase = finalPhases[i]; phase.AddParentPhase(finalHPPhase); if (i % 2 == 1) { phase.Name = "Proto Greer " + (++protoPhases); phase.AddTargets(protoGreerlings, log); phases.Add(phase); } else { phase.Name = "Below 10% " + (++below10Phases); AddMainTitansToPhase(phase, greer, greeAndReeg, ereg, log); phases.Add(phase); } phase.OverrideEnd(Math.Min(phase.End, finalHPPhase.End)); } } } return phases; } internal override List<PhaseData> GetPhases(ParsedEvtcLog log, bool requirePhases) { List<PhaseData> phases = GetInitialPhase(log); SingleActor greer = Targets.FirstOrDefault(x => x.IsSpecies(TargetID.Greer)) ?? throw new MissingKeyActorsException("Greer not found"); var greeAndReegIDs = new List<int> { (int) TargetID.Reeg, (int) TargetID.Gree, }; var greeAndReeg = Targets.Where(x => x.IsAnySpecies(greeAndReegIDs)); // Ereg is present in CM var ereg = Targets.FirstOrDefault(x => x.IsSpecies(TargetID.Ereg)); AddMainTitansToPhase(phases[0], greer, greeAndReeg, ereg, log); // The Proto-Greelings can respawn during 10% var protoGreerlings = Targets.Where(x => x.IsSpecies(TargetID.ProtoGreerling)); phases[0].AddTargets(protoGreerlings, log, PhaseData.TargetPriority.Blocking); phases.AddRange(ComputePhases(log, greer, greeAndReeg, ereg, protoGreerlings, (EncounterPhaseData)phases[0], requirePhases)); return phases; } internal override void ComputeNPCCombatReplayActors(NPC target, ParsedEvtcLog log, CombatReplay replay) { if (!log.LogData.IsInstance) { base.ComputeNPCCombatReplayActors(target, log, replay); } (long start, long end) lifespan; switch (target.ID) { case (int)TargetID.Greer: AddSweepTheMoldRakeTheRot(target, log, replay); AddStompTheGrowth(target, log, replay); AddScatteringSporeblast(target, log, replay); AddEnfeeblingMiasma(target, log, replay); AddRainOfSpores(target, log, replay); AddRipplesOfRot(target, log, replay); AddBlobOfBlight(target, log, replay); AddCageOfDecayOrNoxiousBlight(target, log, replay); // Getting breakbar times to filter some effects of different sizes appearing at the end of it. var breakbars = target.GetBuffStatus(log, [DamageImmunity1, DamageImmunity2, DamageImmunity3]).Where(x => x.Value > 0); foreach (var breakbar in breakbars) { // Rot the World - AoEs if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerRotTheWorld, out var rotTheWorld)) { foreach (EffectEvent effect in rotTheWorld.Where(x => x.Time >= breakbar.Start && x.Time <= breakbar.End)) { lifespan = effect.ComputeLifespan(log, effect.Duration); replay.Decorations.AddWithBorder(new CircleDecoration(240, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)), Colors.LightOrange, 0.2); } } } // Rot the World - Breakbar var breakbarUpdates = target.GetBreakbarPercentUpdates(log); var (breakbarNones, breakbarActives, breakbarImmunes, breakbarRecoverings) = target.GetBreakbarStatus(log); foreach (var segment in breakbarActives) { replay.Decorations.AddActiveBreakbar(segment.TimeSpan, target, breakbarUpdates); } // Invulnerable Barrier if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerInvulnerableBarrier, out var invulnerableBarriers)) { foreach (EffectEvent effect in invulnerableBarriers) { lifespan = effect.ComputeLifespan(log, effect.Duration); replay.Decorations.AddWithBorder(new CircleDecoration(600, lifespan, Colors.GreenishYellow, 0.2, new AgentConnector(target)), Colors.GreenishYellow, 0.4); } } break; case (int)TargetID.Reeg: AddEmpoweringBlast(target, log, replay); AddScatteringSporeblast(target, log, replay); AddRainOfSpores(target, log, replay); AddBlobOfBlight(target, log, replay); AddCageOfDecayOrNoxiousBlight(target, log, replay); break; case (int)TargetID.Gree: AddEmpoweringBlast(target, log, replay); AddSweepTheMoldRakeTheRot(target, log, replay); AddStompTheGrowth(target, log, replay); AddRipplesOfRot(target, log, replay); AddEnfeeblingMiasma(target, log, replay); AddCageOfDecayOrNoxiousBlight(target, log, replay); break; case (int)TargetID.Ereg: AddEmpoweringBlast(target, log, replay); AddScatteringSporeblast(target, log, replay); AddEnfeeblingMiasma(target, log, replay); AddRainOfSpores(target, log, replay); AddBlobOfBlight(target, log, replay); break; case (int)TargetID.ProtoGreerling: AddSweepTheMoldRakeTheRot(target, log, replay); AddStompTheGrowth(target, log, replay); AddScatteringSporeblast(target, log, replay); break; case (int)TargetID.EmpoweringBeast: // Blighting Stab - Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerBlightingStabIndicator, out var blightingStabIndicator)) { foreach (EffectEvent effect in blightingStabIndicator) { // Duration too long by 500ms, use damage effect as end time lifespan = effect.ComputeLifespanWithSecondaryEffectAndPosition(log, EffectGUIDs.GreerBlightingStabDamage); replay.Decorations.Add(new CircleDecoration(300, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position))); } } // Blighting Stab - Damage if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerBlightingStabDamage, out var blightingStabDamage)) { foreach (EffectEvent effect in blightingStabDamage) { lifespan = effect.ComputeLifespan(log, 1000); replay.Decorations.Add(new CircleDecoration(300, lifespan, Colors.GreenishYellow, 0.2, new PositionConnector(effect.Position))); } } break; default: break; } } internal override void ComputePlayerCombatReplayActors(PlayerActor player, ParsedEvtcLog log, CombatReplay replay) { if (!log.LogData.IsInstance) { base.ComputePlayerCombatReplayActors(player, log, replay); } // Eruption of Rot - Green AoE if (log.CombatData.TryGetEffectEventsByDstWithGUIDs(player.AgentItem, [EffectGUIDs.GreerEruptionOfRotGreen, EffectGUIDs.GreerEruptionOfRotGreen2, EffectGUIDs.GreerEruptionofRotGreen3], out var noxiousBlight)) { foreach (EffectEvent effect in noxiousBlight) { long duration = effect.GUIDEvent.ContentGUID == EffectGUIDs.GreerEruptionOfRotGreen ? 10000 : 8000; string icon = effect.GUIDEvent.ContentGUID == EffectGUIDs.GreerEruptionOfRotGreen || effect.GUIDEvent.ContentGUID == EffectGUIDs.GreerEruptionOfRotGreen2 ? ParserIcons.GreenMarkerSize2Overhead : ParserIcons.GreenMarkerSize3Overhead; long growing = effect.Time + duration; (long start, long end) lifespan = effect.ComputeLifespan(log, duration); var circle = new CircleDecoration(240, lifespan, Colors.DarkGreen, 0.2, new AgentConnector(player)); replay.Decorations.AddWithGrowing(circle, growing, true); replay.Decorations.AddOverheadIcon(lifespan, player, icon); } } // Infectious Rot - Failed Green AoE | Plague Rot - Failed Green AoE CM var infectiousRot = player.GetBuffStatus(log, [InfectiousRotBuff, PlagueRot]).Where(x => x.Value > 0); foreach (var segment in infectiousRot) { replay.Decorations.Add(new CircleDecoration(200, segment.TimeSpan, Colors.Red, 0.2, new AgentConnector(player))); } } internal override void ComputeEnvironmentCombatReplayDecorations(ParsedEvtcLog log, CombatReplayDecorationContainer environmentDecorations) { if (!log.LogData.IsInstance) { base.ComputeEnvironmentCombatReplayDecorations(log, environmentDecorations); } // Wave of Corruption if (log.CombatData.TryGetEffectEventsByGUID(EffectGUIDs.GreerWaveOfCorruption1, out var shockwaves)) { foreach (EffectEvent effect in shockwaves) { (long start, long end) lifespan = (effect.Time, effect.Time + 3000); environmentDecorations.AddShockwave(new PositionConnector(effect.Position), lifespan, Colors.Purple, 0.2, 1500); } } } private static void AddScatteringSporeblast(NPC target, ParsedEvtcLog log, CombatReplay replay) { // Scattering Sporeblast - Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerScatteringSporeblastIndicator, out var sporeblasts)) { foreach (EffectEvent effect in sporeblasts) { (long start, long end) lifespan = effect.ComputeLifespan(log, effect.Duration); var indicator = new CircleDecoration(100, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)); replay.Decorations.Add(indicator); } } } private static void AddSweepTheMoldRakeTheRot(NPC target, ParsedEvtcLog log, CombatReplay replay) { // Swepp the Mold / Rake the Rot - Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerSweepTheMoldRakeTheRotIndicator, out var indicators)) { var casts = target.GetAnimatedCastEvents(log).Where(x => x.SkillID == SweepTheMold || x.SkillID == SweepTheMold2 || x.SkillID == SweepTheMold3 || x.SkillID == RakeTheRot || x.SkillID == RakeTheRot2 || x.SkillID == RakeTheRot3); foreach (var cast in casts) { foreach (EffectEvent effect in indicators.Where(x => x.Time >= cast.Time && x.Time < cast.Time + 1000)) // 1 second padding { // Sweep the Mold has a X 20 and Y 40 offset, the X is already covered by the effect rotation. // Adding 40 to the radius matches the in game visual uint radius = 0; switch (cast.SkillID) { case SweepTheMold: radius = 750 + 40; break; case RakeTheRot: radius = 750; break; case SweepTheMold2: radius = 950 + 40; break; case RakeTheRot2: radius = 950; break; case SweepTheMold3: radius = 550 + 40; break; case RakeTheRot3: radius = 550; break; default: break; } (long start, long end) lifespan = effect.ComputeLifespan(log, effect.Duration); var cone = new PieDecoration(radius, 120, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z + 90)); replay.Decorations.Add(cone); } } } } private static void AddEnfeeblingMiasma(NPC target, ParsedEvtcLog log, CombatReplay replay) { (long start, long end) lifespan; // Enfeebling Miasma - Cone Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerEnfeeblingMiasma, out var miasmaIndicator)) { foreach (EffectEvent effect in miasmaIndicator) { lifespan = effect.ComputeLifespan(log, 6000); var cone = new PieDecoration(2000, 60, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z + 90)); replay.Decorations.Add(cone); } } // Enfeebling Miasma - Gas Circles if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerEnfeeblingMiasmaGasMoving, out var miasmaAnimation) && log.CombatData.TryGetEffectEventsBySrcWithGUIDs(target.AgentItem, [EffectGUIDs.GreerEnfeeblingMiasmaGasClouds, EffectGUIDs.GreerEnfeeblingMiasmaGasCloudsNew], out var miasmaClouds)) { foreach (EffectEvent animation in miasmaAnimation) { foreach (EffectEvent cloud in miasmaClouds.Where(x => x.Time > animation.Time && x.Time < animation.Time + 6000)) { long duration = cloud.GUIDEvent.ContentGUID == EffectGUIDs.GreerEnfeeblingMiasmaGasClouds ? 12000 : 13000; lifespan = cloud.ComputeLifespan(log, duration); var circle = new CircleDecoration(150, lifespan, Colors.Purple, 0.2, new PositionConnector(cloud.Position)); replay.Decorations.AddWithBorder(circle, Colors.Red, 0.2); if (!log.CombatData.HasMissileData) { replay.Decorations.AddProjectile(animation.Position, cloud.Position, (animation.Time, cloud.Time), Colors.Purple, 0.2, 150); } } } } // Enfeebling Miasma - Gas Projectiles var enfeeblingMiasmaCloud = log.CombatData.GetMissileEventsBySkillIDs([EnfeeblingMiasma, EnfeeblingMiasma2, EnfeeblingMiasma3, EnfeeblingMiasma4]).Where(x => x.Src.Is(target.AgentItem)); replay.Decorations.AddNonHomingMissiles(log, enfeeblingMiasmaCloud, Colors.Purple, 0.2, 150); } private static void AddCageOfDecayOrNoxiousBlight(NPC target, ParsedEvtcLog log, CombatReplay replay) { (long start, long end) lifespan; // Cage of Decay - Arrow Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerCageOfDecayArrowIndicator, out var cageOfDecayArrows)) { foreach (EffectEvent effect in cageOfDecayArrows) { lifespan = effect.ComputeLifespan(log, 5000); var offset = new Vector3(700, 0, 0); var arrow = new RectangleDecoration(1400, 100, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position).WithOffset(offset, true)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z - 90)); replay.Decorations.Add(arrow); } } // Cage of Decay - Circle Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerCageOfDecayCircleIndicator, out var cageOfDecayCirclesIndicators)) { foreach (EffectEvent effect in cageOfDecayCirclesIndicators) { long duration = 5000; long growing = effect.Time + duration; lifespan = effect.ComputeLifespan(log, duration); var circle = new CircleDecoration(360, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)); replay.Decorations.AddWithGrowing(circle, growing); } } // Cage of Decay + Noxious Blight - Roots if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerCageOfDecayRoots, out var cageOfDecayRoots)) { foreach (EffectEvent effect in cageOfDecayRoots) { lifespan = effect.ComputeLifespan(log, 2000); var roots = (RectangleDecoration)new RectangleDecoration(50, 150, lifespan, Colors.GreenishYellow, 0.3, new PositionConnector(effect.Position)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z)); replay.Decorations.AddWithBorder(roots, Colors.Purple, 0.2); } } // Cage of Decay + Noxious Blight - Circle Damage if (log.CombatData.TryGetEffectEventsBySrcWithGUIDs(target.AgentItem, [EffectGUIDs.GreerCageOfDecayCircleDamage, EffectGUIDs.GreerCageOfDecayCircleDamageNew], out var cageOfDecayCirclesDamage)) { foreach (EffectEvent effect in cageOfDecayCirclesDamage) { // Durations: Cage of Decay - 23000 | Eruption of Rot - 8000 lifespan = effect.ComputeLifespan(log, effect.Duration); var circle = new CircleDecoration(360, lifespan, Colors.LightPurple, 0.3, new PositionConnector(effect.Position)); replay.Decorations.AddWithBorder(circle, Colors.GreenishYellow, 0.3); } } // Cage of Decay - Moving roots walls if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerCageOfDecayMovingWalls, out var cageOfDecayWalls)) { foreach (EffectEvent effect in cageOfDecayWalls) { lifespan = effect.ComputeLifespan(log, 2000); var wall = (RectangleDecoration)new RectangleDecoration(200, 50, lifespan, Colors.GreenishYellow, 0.3, new PositionConnector(effect.Position)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z)); replay.Decorations.AddWithBorder(wall, Colors.Purple, 0.2); } } // Cage of Decay - Roots walls around the circle of damage if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerCageOfDecayCircleWalls, out var cageOfDecayCircleWalls)) { foreach (EffectEvent effect in cageOfDecayCircleWalls) { lifespan = effect.ComputeLifespan(log, 23000); var wall = (RectangleDecoration)new RectangleDecoration(200, 100, lifespan, Colors.GreenishYellow, 0.3, new PositionConnector(effect.Position)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z)); replay.Decorations.AddWithBorder(wall, Colors.Purple, 0.2); } } } private static void AddRainOfSpores(NPC target, ParsedEvtcLog log, CombatReplay replay) { // Rain of Spores - Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerRainOfSporesIndicator, out var rainOfSpores)) { foreach (EffectEvent effect in rainOfSpores) { (long start, long end) lifespan = effect.ComputeLifespan(log, effect.Duration); replay.Decorations.Add(new CircleDecoration(200, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position))); } } } private static void AddStompTheGrowth(NPC target, ParsedEvtcLog log, CombatReplay replay) { // Stomp the Growth - Circle indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerStompTheGrowth, out var stompTheGrowth)) { var casts = target.GetAnimatedCastEvents(log).Where(x => x.SkillID == StompTheGrowth || x.SkillID == StompTheGrowth2 || x.SkillID == StompTheGrowth3); foreach (var cast in casts) { foreach (EffectEvent effect in stompTheGrowth.Where(x => x.Time >= cast.Time && x.Time < cast.Time + 3000)) // 3 seconds padding { uint radius = 0; switch (cast.SkillID) { case StompTheGrowth: radius = 800; break; case StompTheGrowth2: radius = 600; break; case StompTheGrowth3: radius = 1000; break; default: break; } (long start, long end) lifespan = effect.ComputeLifespan(log, effect.Duration); var circle = new CircleDecoration(radius, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)); replay.Decorations.AddWithGrowing(circle, effect.Time + effect.Duration); } } } } private static void AddRipplesOfRot(NPC target, ParsedEvtcLog log, CombatReplay replay) { (long start, long end) lifespan; // Ripples of Rot - Inner Circle if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerRipplesOfRotIndicator1, out var ripplesOfRotIndicator1)) { foreach (EffectEvent effect in ripplesOfRotIndicator1) { lifespan = effect.ComputeLifespan(log, effect.Duration); var innerCircle = new CircleDecoration(240, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)); replay.Decorations.AddWithGrowing(innerCircle, effect.Time + effect.Duration); } } // Ripples of Rot - Outer Circle if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerRipplesOfRotIndicator2, out var ripplesOfRotIndicator2)) { foreach (EffectEvent effect in ripplesOfRotIndicator2) { lifespan = effect.ComputeLifespan(log, effect.Duration); var outerCircle = new CircleDecoration(800, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)); replay.Decorations.AddWithBorder(outerCircle, Colors.LightOrange, 0.2); } } // Ripples of Rot - Moving roots walls if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerRipplesOfRotMovingWalls, out var movingWalls)) { foreach (EffectEvent effect in movingWalls) { lifespan = effect.ComputeLifespan(log, 2000); var wall = (RectangleDecoration)new RectangleDecoration(100, 50, lifespan, Colors.GreenishYellow, 0.3, new PositionConnector(effect.Position)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z)); replay.Decorations.AddWithBorder(wall, Colors.Purple, 0.2); } } // Ripples of Rot - Roots Walls if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerRipplesOfRotWalls, out var walls)) { foreach (EffectEvent effect in walls) { lifespan = effect.ComputeLifespan(log, 23000); var wall = (RectangleDecoration)new RectangleDecoration(200, 100, lifespan, Colors.GreenishYellow, 0.3, new PositionConnector(effect.Position)).UsingRotationConnector(new AngleConnector(effect.Rotation.Z)); replay.Decorations.AddWithBorder(wall, Colors.Purple, 0.2); } } } private static void AddBlobOfBlight(NPC target, ParsedEvtcLog log, CombatReplay replay) { (long start, long end) lifespan; // Blob of Blight - AoE Indicator if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerBlobOfBlightIndicator, out var blobOfBlightIndicator)) { foreach (EffectEvent effect in blobOfBlightIndicator) { // The effect has 0 duration logged lifespan = effect.ComputeLifespan(log, 2315); replay.Decorations.AddWithGrowing(new CircleDecoration(300, lifespan, Colors.LightOrange, 0.2, new PositionConnector(effect.Position)), lifespan.end); } } // Blob of Blight - Stationary Orb if (log.CombatData.TryGetEffectEventsBySrcWithGUID(target.AgentItem, EffectGUIDs.GreerBlobofBlightStationary, out var blobOfBlight)) { foreach (EffectEvent effect in blobOfBlight) { lifespan = effect.ComputeLifespan(log, 7000); replay.Decorations.Add(new CircleDecoration(60, lifespan, Colors.GreenishYellow, 0.3, new PositionConnector(effect.Position))); replay.Decorations.Add(new DoughnutDecoration(60, 80, lifespan, Colors.LightPurple, 0.3, new PositionConnector(effect.Position))); } } // Blob of Blight - Moving Orbs // Using the projectile velocity to distinguish between the main orbs and the mini orbs // Main orbs have 0.3 and mini orbs have 0.5, once the main orb hits a player, the mini orbs have 0.4 var blobOfBlightOrbs = log.CombatData.GetMissileEventsBySrcBySkillIDs(target.AgentItem, [BlobOfBlight, BlobOfBlight2, BlobOfBlight3]); var blobOfBlightMainOrbs = blobOfBlightOrbs.Where(x => x.LaunchEvents.Any(x => x.Speed == 0.3f)); var blobOfBlightMiniOrbs = blobOfBlightOrbs.Where(x => x.LaunchEvents.Any(x => x.Speed == 0.4f || x.Speed == 0.5f)); // Main Orbs foreach (MissileEvent missileEvent in blobOfBlightMainOrbs) { lifespan = (missileEvent.Time, missileEvent.RemoveEvent?.Time ?? log.LogData.LogEnd); for (int i = 0; i < missileEvent.LaunchEvents.Count; i++) { MissileLaunchEvent? launch = missileEvent.LaunchEvents[i]; lifespan = (launch.Time, i != missileEvent.LaunchEvents.Count - 1 ? missileEvent.LaunchEvents[i + 1].Time : lifespan.end); if (!launch.TargetedAgent.IsNonIdentifiedSpecies()) { replay.Decorations.Add(new CircleDecoration(60, lifespan, Colors.GreenishYellow, 0.3, new PositionToAgentConnector(launch.TargetedAgent, launch.LaunchPosition, launch.Time, launch.Speed))); replay.Decorations.Add(new DoughnutDecoration(60, 80, lifespan, Colors.LightPurple, 0.3, new PositionToAgentConnector(launch.TargetedAgent, launch.LaunchPosition, launch.Time, launch.Speed))); } } } // Mini Orbs replay.Decorations.AddNonHomingMissiles(log, blobOfBlightMiniOrbs, Colors.GreenishYellow, 0.3, 25); } private static void AddEmpoweringBlast(NPC target, ParsedEvtcLog log, CombatReplay replay) { // Empowering Blast - Orbs var orbs = log.CombatData.GetMissileEventsBySrcBySkillIDs(target.AgentItem, [EmpoweringBlast1, EmpoweringBlast2]); replay.Decorations.AddHomingMissiles(log, orbs, Colors.Purple, 0.5, 25); } internal override void SetInstanceBuffs(ParsedEvtcLog log, List<InstanceBuff> instanceBuffs) { if (!log.LogData.IsInstance) { base.SetInstanceBuffs(log, instanceBuffs); } var encounterPhases = log.LogData.GetPhases(log).OfType<EncounterPhaseData>().Where(x => x.LogID == LogID); foreach (var encounterPhase in encounterPhases) { if (encounterPhase.Success && encounterPhase.IsCM) { // The buff elegibility remains on players even if Ereg is dead var ereg = encounterPhase.Targets.Keys.FirstOrDefault(x => x.IsSpecies(TargetID.Ereg)); if (ereg != null && !log.CombatData.GetDeadEvents(ereg.AgentItem).Any()) { instanceBuffs.Add(new(log.Buffs.BuffsByIDs[AchievementEligibilitySpareTheEreg], 1, encounterPhase)); } } } } }
0
0.974637
1
0.974637
game-dev
MEDIA
0.693032
game-dev
0.768767
1
0.768767
opentibiabr/otservbr-global
1,026
data/scripts/actions/quests/cults_of_tibia/magnifier.lua
local cultsOfTibiaMagnifier = Action() function cultsOfTibiaMagnifier.onUse(player, item, fromPosition, target, toPosition, isHotkey) local sqm = Position(33296, 32140, 8) local tile = Tile(Position(target:getPosition())) if not player then return true end if not target:isItem() then return false end if target:isCreature() then return false end if (isInArray({2622, 2601, 2596, 2612, 2618}, target:getId())) then player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Nothing special. This picture looks genuine.") target:getPosition():sendMagicEffect(CONST_ME_POFF) elseif target:getPosition() == sqm and target:getId() == 2613 and player:getStorageValue(Storage.CultsOfTibia.MotA.Mission) == 8 then target:getPosition():sendMagicEffect(CONST_ME_POFF) player:setStorageValue(Storage.CultsOfTibia.MotA.Mission, 9) player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "This is it. It looks like it was painted by a child!") end return true end cultsOfTibiaMagnifier:id(25306) cultsOfTibiaMagnifier:register()
0
0.825689
1
0.825689
game-dev
MEDIA
0.937826
game-dev
0.84874
1
0.84874
logicpulse/logicPOS
6,618
LogicPOS.Shared/POSSession.cs
using LogicPOS.Data.XPO.Utility; using LogicPOS.Domain.Entities; using LogicPOS.Domain.Enums; using LogicPOS.Globalization; using LogicPOS.Shared.Orders; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; namespace LogicPOS.Shared { public class POSSession { private readonly log4net.ILog _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private string JsonFileLocation { get; set; } public DateTime SessionStartDate { get; set; } public DateTime SessionUpdatedAt { get; set; } public Dictionary<Guid, DateTime> LoggedUsers { get; set; } public Guid CurrentOrderMainId { get; set; } public Dictionary<Guid, OrderMain> OrderMains { get; set; } public Dictionary<string, object> Tokens { get; set; } private bool IsEmpty => OrderMains.Count == 0 && LoggedUsers.Count == 0; public POSSession(string jsonFileLocation) { JsonFileLocation = jsonFileLocation; CurrentOrderMainId = Guid.Empty; SessionStartDate = XPOUtility.CurrentDateTimeAtomic(); LoggedUsers = new Dictionary<Guid, DateTime>(); OrderMains = new Dictionary<Guid, OrderMain>(); } public string Serialize() { return JsonConvert.SerializeObject(this, Formatting.Indented); } public void WriteToFile() { var contentsToWriteToFile = Serialize(); var writer = new StreamWriter(JsonFileLocation, false); writer.Write(contentsToWriteToFile); writer.Close(); } public void DeleteJsonFile() { if (File.Exists(JsonFileLocation)) File.Delete(JsonFileLocation); } public void Save() { if (HasCurrentSession && CurrentSession.IsEmpty) { DeleteJsonFile(); return; } SessionUpdatedAt = XPOUtility.CurrentDateTimeAtomic(); WriteToFile(); } public void CleanSession() { DeleteLoggedUsers(); DeleteEmptyTickets(); } public void DeleteLoggedUsers() { foreach (Guid id in CurrentSession.LoggedUsers.Keys) { sys_userdetail user = XPOUtility.GetEntityById<sys_userdetail>(id); XPOUtility.Audit("USER_loggerOUT", string.Format(CultureResources.GetResourceByLanguage(Settings.CultureSettings.CurrentCultureName, "audit_message_used_forced_loggerout"), user.Name)); } CurrentSession.LoggedUsers.Clear(); } public void DeleteEmptyTickets() { Guid latestNonEmptyOrder = Guid.Empty; if (OrderMains != null && OrderMains.Count > 0) { //Used to store List of Items to Remove after foreach, we cant remove it inside a foreach List<Guid> removeItems = new List<Guid>(); foreach (Guid orderIndex in OrderMains.Keys) { //Remove if Not Open and if Dont have Lines if (OrderMains[orderIndex].OrderStatus != OrderStatus.Open && OrderMains[orderIndex].OrderTickets[OrderMains[orderIndex].CurrentTicketId].OrderDetails.Lines.Count == 0) { removeItems.Add(orderIndex); } else { latestNonEmptyOrder = orderIndex; } }; foreach (var item in removeItems) { OrderMains.Remove(item); break; } } if (!CurrentSession.OrderMains.ContainsKey(CurrentSession.CurrentOrderMainId)) CurrentSession.CurrentOrderMainId = latestNonEmptyOrder; } public bool SetToken(string pToken, object pValue) { bool result = false; try { //Init Dictionary if (Tokens == null) Tokens = new Dictionary<string, object>(); //Update Token if (Tokens.ContainsKey(pToken)) { Tokens[pToken] = pValue; } //Add Token else { Tokens.Add(pToken, pValue); } result = true; } catch (Exception ex) { _logger.Error(ex.Message, ex); } return result; } public object GetToken(string pToken) { object result = null; try { if (Tokens != null && Tokens.Count > 0 && Tokens.ContainsKey(pToken)) result = Tokens[pToken]; } catch (Exception ex) { _logger.Error(ex.Message, ex); } return result; } #region Static public static POSSession GetSessionFromFile(string jsonFileLocation) { POSSession appSession; if (File.Exists(jsonFileLocation)) { string jsonfileContents = File.ReadAllText(jsonFileLocation); appSession = JsonConvert.DeserializeObject<POSSession>(jsonfileContents); appSession.JsonFileLocation = jsonFileLocation; } else { appSession = new POSSession(jsonFileLocation); appSession.Save(); } return appSession; } public static POSSession CurrentSession { get; set; } public static bool HasCurrentSession => CurrentSession != null; public static decimal GetGlobalDiscount() { decimal result = 0.0m; if (HasCurrentSession && CurrentSession.OrderMains.ContainsKey(CurrentSession.CurrentOrderMainId) ) { OrderMain orderMain = CurrentSession.OrderMains[CurrentSession.CurrentOrderMainId]; pos_configurationplacetable xConfigurationPlaceTable = XPOUtility.GetEntityById<pos_configurationplacetable>(orderMain.Table.Oid); if (xConfigurationPlaceTable != null) { result = xConfigurationPlaceTable.Discount; } } return result; } #endregion } }
0
0.949251
1
0.949251
game-dev
MEDIA
0.474654
game-dev
0.993531
1
0.993531
MiczFlor/RPi-Jukebox-RFID
5,249
components/gpio_control/function_calls.py
import logging import sys from subprocess import Popen as function_call import os import pathlib class phoniebox_function_calls: def __init__(self): self.logger = logging.getLogger(__name__) playout_control_relative_path = "../../scripts/playout_controls.sh" function_calls_absolute_path = str(pathlib.Path(__file__).parent.absolute()) self.playout_control = os.path.abspath(os.path.join(function_calls_absolute_path, playout_control_relative_path)) rfid_trigger_relative_path = "../../scripts/rfid_trigger_play.sh" self.rfid_trigger = os.path.abspath(os.path.join(function_calls_absolute_path, rfid_trigger_relative_path)) def functionCallShutdown(self, *args): function_call("{command} -c=shutdown".format(command=self.playout_control), shell=True) def functionCallVolU(self, steps=None, *args): if steps is None: function_call("{command} -c=volumeup".format(command=self.playout_control), shell=True) else: function_call("{command} -c=volumeup -v={value}".format(value=steps, command=self.playout_control), shell=True) def functionCallVolD(self, steps=None, *args): if steps is None: function_call("{command} -c=volumedown".format(command=self.playout_control), shell=True) else: function_call("{command} -c=volumedown -v={value}".format(value=steps, command=self.playout_control), shell=True) def functionCallVol0(self, *args): function_call("{command} -c=mute".format(command=self.playout_control), shell=True) def functionCallPlayerNext(self, *args): function_call("{command} -c=playernext".format(command=self.playout_control), shell=True) def functionCallPlayerPrev(self, *args): function_call("{command} -c=playerprev".format(command=self.playout_control), shell=True) def functionCallPlayerPauseForce(self, *args): function_call("{command} -c=playerpauseforce".format(command=self.playout_control), shell=True) def functionCallPlayerPause(self, *args): function_call("{command} -c=playerpause".format(command=self.playout_control), shell=True) def functionCallRecordStart(self, *args): function_call("{command} -c=recordstart".format(command=self.playout_control), shell=True) def functionCallRecordStop(self, *args): function_call("{command} -c=recordstop".format(command=self.playout_control), shell=True) def functionCallRecordPlayLatest(self, *args): function_call("{command} -c=recordplaylatest".format(command=self.playout_control), shell=True) def functionCallToggleWifi(self, *args): function_call("{command} -c=togglewifi".format(command=self.playout_control), shell=True) def functionCallPlayerStop(self, *args): function_call("{command} -c=playerstop".format(command=self.playout_control), shell=True) def functionCallPlayerSeekFwd(self, seconds=None, *args): if seconds is None: seconds = 10 function_call("{command} -c=playerseek -v=+{value}".format(command=self.playout_control, value=seconds), shell=True) def functionCallPlayerSeekBack(self, seconds=None, *args): if seconds is None: seconds = 10 function_call("{command} -c=playerseek -v=-{value}".format(command=self.playout_control, value=seconds), shell=True) def functionCallPlayerSeekFarFwd(self, seconds=None, *args): if seconds is None: seconds = 60 function_call("{command} -c=playerseek -v=+{value}".format(command=self.playout_control, value=seconds), shell=True) def functionCallPlayerSeekFarBack(self, seconds=None, *args): if seconds is None: seconds = 60 function_call("{command} -c=playerseek -v=-{value}".format(command=self.playout_control, value=seconds), shell=True) def functionCallPlayerRandomTrack(self, *args): function_call("{command} -c=randomtrack".format(command=self.playout_control), shell=True) def functionCallPlayerRandomCard(self, *args): function_call("{command} -c=randomcard".format(command=self.playout_control), shell=True) def functionCallPlayerRandomFolder(self, *args): function_call("{command} -c=randomfolder".format(command=self.playout_control), shell=True) def functionCallBluetoothToggle(self, mode=None, *args): if mode is None: mode = 'toggle' function_call("{command} -c=bluetoothtoggle -v={value}".format(command=self.playout_control, value=mode), shell=True) def functionCallTriggerPlayCardId(self, cardid, *args): function_call("{command} --cardid={value}".format(command=self.rfid_trigger, value=cardid), shell=True) def functionCallTriggerPlayFolder(self, folder, *args): function_call("{command} --dir={value}".format(command=self.rfid_trigger, value=folder), shell=True) def getFunctionCall(self, functionName): self.logger.error('Get FunctionCall: {} {}'.format(functionName, functionName in locals())) getattr(sys.modules[__name__], str) return locals().get(functionName, None)
0
0.633774
1
0.633774
game-dev
MEDIA
0.665044
game-dev
0.559944
1
0.559944
googlevr/blocks
11,363
Assets/Scripts/guides/GridPlaneAnchor.cs
// Copyright 2020 The Blocks Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; using UnityEngine; using com.google.apps.peltzer.client.model.main; using com.google.apps.peltzer.client.model.controller; using com.google.apps.peltzer.client.tools.utils; using TMPro; /// <summary> /// This class is responsible for managing a world space grid plane that is locked to an axis of moment. /// A grid plane consistes of the visual grid with a child "anchor". A grid plane anchor is the interaction /// point for the grid plane to which the anchor is nested. /// </summary> public class GridPlaneAnchor : MonoBehaviour { /// <summary> /// Axis type to specify to which axis the plane belongs. /// </summary> public enum AxisType { X = 0, Y = 1, Z = 2 } // Immutable marks the object as a source for generating new instances and are not moved themselves. public bool isImmutable = true; public AxisType axisType; /// <summary> /// Holds a lookup of the currently cloned planes, the root GameObject of a "GridPlane" to which the anchor is parented, /// which is used for de-duping along a particular axis type. This dictionary is populated for any source grid planes, i.e. a plane that spawns another plane. /// </summary> public Dictionary<float, GameObject> planeClones; private bool isSetup = false; private bool isHovered = false; private bool isHeld = false; private bool isGrabFrameUpdate = false; private bool isReleaseFrameUpdate = false; private Material planeMaterial; private Material anchorMaterial; private TextMeshPro label; private GridPlaneAnchor rootGridPlaneAnchor; void Start() { Setup(); } private void Setup() { PeltzerMain.Instance.peltzerController.PeltzerControllerActionHandler += ControllerEventHandler; planeMaterial = transform.parent.GetComponent<Renderer>().material; label = transform.parent.Find("Label").gameObject.GetComponent<TextMeshPro>(); if (isImmutable) { planeClones = new Dictionary<float, GameObject>(); } isSetup = true; } void Update() { if (!isSetup) return; isHovered = IsCollidedWithSelector(); if (!isHovered && isImmutable) { isHeld = false; } // Remove the reference. if (isGrabFrameUpdate && !isImmutable) { isGrabFrameUpdate = false; if (rootGridPlaneAnchor.planeClones.ContainsKey(transform.parent.localPosition[(int)axisType])) { rootGridPlaneAnchor.planeClones.Remove(transform.parent.localPosition[(int)axisType]); } } if (isHeld && !isImmutable) { // Set zoomer flag to show world bounds while held. PeltzerMain.Instance.Zoomer.isManipulatingGridPlane = true; // Snap grid plane to grid. Vector3 newLSPos = transform.parent.parent.parent .InverseTransformPoint(PeltzerMain.Instance.worldSpace .ModelToWorld(PeltzerMain.Instance.GetSelector().selectorPosition)); switch (axisType) { case AxisType.X: newLSPos = new Vector3(newLSPos.x, transform.parent.transform.localPosition.y, transform.parent.transform.localPosition.z); break; case AxisType.Y: newLSPos = new Vector3(transform.parent.transform.localPosition.x, newLSPos.y, transform.parent.transform.localPosition.z); break; case AxisType.Z: newLSPos = new Vector3(transform.parent.transform.localPosition.x, transform.parent.transform.localPosition.y, newLSPos.z); break; } // Clamp precision @ .3 newLSPos = new Vector3(Mathf.RoundToInt(newLSPos.x * 1000.000f) / 1000.000f, Mathf.RoundToInt(newLSPos.y * 1000.000f) / 1000.000f, Mathf.RoundToInt(newLSPos.z * 1000.000f) / 1000.000f); transform.parent.localPosition = newLSPos; // Display value. SetLabel(newLSPos[(int)axisType].ToString("F3") + " bu"); } else if (isHovered && !isImmutable) { // Display value. SetLabel(transform.parent.localPosition[(int)axisType].ToString("F3") + " bu"); } else { // Clear label. SetLabel(""); } // Pass material to shader// Get world position of selector position. Vector4 selectorWorldPosition = PeltzerMain.Instance.worldSpace .ModelToWorld(PeltzerMain.Instance.peltzerController.LastPositionModel); selectorWorldPosition.w = PeltzerMain.Instance.peltzerController.isBlockMode ? 0 : 1; planeMaterial.SetVector("_SelectorPosition", selectorWorldPosition); // check if it is overlapping if (isReleaseFrameUpdate && !isImmutable) { isReleaseFrameUpdate = false; if (IsOverlappingPlaneOnSameAxis()) { DestroyGridPlane(); } else { rootGridPlaneAnchor.planeClones.Add(transform.parent.localPosition[(int)axisType], transform.parent.gameObject); } } } /// <summary> /// Set the label text from position information. /// </summary> /// <param name="text">The string to to display in the label.</param> private void SetLabel(string text) { label.gameObject.transform.LookAt(PeltzerMain.Instance.hmd.transform); label.text = text; } /// <summary> /// Creates a new grid plane along a coordinate axis. /// </summary> private void SpawnNewGridPlane() { // Clone and set transform. GameObject planeClone = GameObject.Instantiate(transform.parent).gameObject; planeClone.transform.Find("GridAnchor").GetComponent<GridPlaneAnchor>().rootGridPlaneAnchor = this; GridPlaneAnchor gridPlaneAnchor = planeClone.transform.Find("GridAnchor").GetComponent<GridPlaneAnchor>(); gridPlaneAnchor.isImmutable = false; gridPlaneAnchor.isHeld = true; gridPlaneAnchor.isHovered = true; planeClone.transform.parent = transform.parent.parent; planeClone.transform.localEulerAngles = transform.parent.transform.localEulerAngles; planeClone.transform.position = transform.parent.transform.position; planeClone.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); gridPlaneAnchor.Setup(); // Reset the interactions on this plane. if (isImmutable) { isHeld = false; isHovered = false; } } // Handle mode selection when appropriate. private void ControllerEventHandler(object sender, ControllerEventArgs args) { if (IsGrabbingAnchor(args)) { // Disable multiselection. PeltzerMain.Instance.GetSelector().EndMultiSelection(); // As we use the eraser on spawned clones to provide a "delete" method, we exclude // any delete tool (eraser) from spawning to provide clarity. if (isImmutable && PeltzerMain.Instance.peltzerController.mode != ControllerMode.delete) { SpawnNewGridPlane(); } else if (!isImmutable) { isHeld = true; // if tool is eraser, delete this plane via parent. if (PeltzerMain.Instance.peltzerController.mode == ControllerMode.delete) { DestroyGridPlane(); return; } // Set grab check semaphore for next update. // This semaphore is used to check for duplicate planes at same level. isGrabFrameUpdate = true; } } else if (IsReleasingAnchor(args)) { isHeld = false; PeltzerMain.Instance.Zoomer.isManipulatingGridPlane = false; // If plane is set outside of world space, destroy it. if (!isImmutable && (Mathf.Abs(transform.parent.localPosition[(int)axisType]) >= 0.5f || IsOverlappingPlaneOnSameAxis())) { DestroyGridPlane(); return; } // Set release check semaphore for next update. // This semaphore is used to check for duplicate planes at same level. isReleaseFrameUpdate = true; } } /// <summary> /// Destroys this instance of a grid plane. /// </summary> private void DestroyGridPlane() { isHeld = false; isHovered = false; PeltzerMain.Instance.peltzerController.PeltzerControllerActionHandler -= ControllerEventHandler; DestroyImmediate(transform.parent.gameObject); } /// <summary> /// Determines if a planes position is currently the same as another of the same axis alignment. /// </summary> private bool IsOverlappingPlaneOnSameAxis() { if (rootGridPlaneAnchor.planeClones.ContainsKey(transform.parent.localPosition[(int)axisType])) { return true; } return false; } /// <summary> /// Determines if the selector is colliding with this transform. /// </summary> private bool IsCollidedWithSelector() { float dist = Vector3.Distance(PeltzerMain.Instance.worldSpace .ModelToWorld(PeltzerMain.Instance.GetSelector().selectorPosition), transform.position); return dist <= transform.localScale.x / 2f * PeltzerMain.Instance.worldSpace.scale; } /// <summary> /// Determines if this anchor is being grabbed. /// </summary> /// <param name="args">Controller event information</param> private bool IsGrabbingAnchor(ControllerEventArgs args) { return isHovered && args.ControllerType == ControllerType.PELTZER && args.ButtonId == ButtonId.Trigger && args.Action == ButtonAction.DOWN; } /// <summary> /// Determines if the anchor is being released. /// </summary> /// <param name="args">Controller event informatin</param> private bool IsReleasingAnchor(ControllerEventArgs args) { return isHeld && args.ControllerType == ControllerType.PELTZER && args.ButtonId == ButtonId.Trigger && args.Action == ButtonAction.UP; } }
0
0.947424
1
0.947424
game-dev
MEDIA
0.86844
game-dev
0.978753
1
0.978753
b1inkie/dst-api
8,760
scripts_619045/prefabs/cave_banana_tree.lua
local assets = { Asset("ANIM", "anim/cave_banana_tree.zip"), Asset("MINIMAP_IMAGE", "cave_banana_tree_stump"), Asset("MINIMAP_IMAGE", "cave_banana_tree_burnt"), } local prefabs_tree = { "cave_banana", "log", "twigs", "cave_banana_stump", "cave_banana_burnt", } local prefabs_stump = { "ash", } local prefabs_burnt = { "charcoal", } local function onregenfn(inst) inst.AnimState:PlayAnimation("grow") inst.AnimState:PushAnimation("idle_loop", true) inst.AnimState:Show("BANANA") end local function makefullfn(inst) inst.AnimState:PlayAnimation("grow") inst.AnimState:PlayAnimation("idle_loop", true) inst.AnimState:Show("BANANA") end local function onpickedfn(inst) inst.SoundEmitter:PlaySound("dontstarve/wilson/pickup_reeds") inst.AnimState:PlayAnimation("pick") inst.AnimState:PushAnimation("idle_loop") inst.AnimState:Hide("BANANA") end local function makeemptyfn(inst) inst.AnimState:PlayAnimation("idle_loop") inst.AnimState:Hide("BANANA") end local function setupstump(inst) SpawnPrefab("cave_banana_stump").Transform:SetPosition(inst.Transform:GetWorldPosition()) inst:Remove() end local function tree_chopped(inst, worker) if not (worker ~= nil and worker:HasTag("playerghost")) then inst.SoundEmitter:PlaySound("dontstarve/wilson/use_axe_tree") end inst.SoundEmitter:PlaySound("dontstarve/forest/treefall") inst.components.lootdropper:SpawnLootPrefab("log") inst.components.lootdropper:SpawnLootPrefab("twigs") inst.components.lootdropper:SpawnLootPrefab("twigs") inst.AnimState:Hide("BANANA") if inst.components.pickable ~= nil and inst.components.pickable.canbepicked then inst.components.lootdropper:SpawnLootPrefab("cave_banana") end inst.components.pickable.caninteractwith = false inst.components.workable:SetWorkable(false) inst.AnimState:PlayAnimation("fall") inst:ListenForEvent("animover", setupstump) end local function tree_chop(inst, worker) inst.AnimState:PlayAnimation("chop") inst.AnimState:PushAnimation("idle_loop", true) if not (worker ~= nil and worker:HasTag("playerghost")) then inst.SoundEmitter:PlaySound("dontstarve/wilson/use_axe_tree") end end local function tree_startburn(inst) if inst.components.pickable ~= nil then inst.components.pickable.caninteractwith = false end end local function tree_burnt(inst) local burnt_tree = SpawnPrefab("cave_banana_burnt") burnt_tree.Transform:SetPosition(inst.Transform:GetWorldPosition()) burnt_tree.no_banana = inst.components.pickable == nil or not inst.components.pickable.canbepicked if burnt_tree.no_banana then burnt_tree.AnimState:Hide("BANANA") end inst:Remove() end local function tree_onsave(inst, data) if inst.components.burnable ~= nil and inst.components.burnable:IsBurning() then data.burnt = true data.no_banana = inst.components.pickable == nil or not inst.components.pickable.canbepicked end end local function tree_onload(inst, data) if data ~= nil then if data.burnt then if data.no_banana and inst.components.pickable ~= nil then inst.components.pickable.canbepicked = false end tree_burnt(inst) end end end local function tree_fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.entity:AddMiniMapEntity() inst.entity:AddNetwork() MakeObstaclePhysics(inst, .25) inst.MiniMapEntity:SetIcon("cave_banana_tree.png") inst:AddTag("plant") inst.AnimState:SetBank("cave_banana_tree") inst.AnimState:SetBuild("cave_banana_tree") inst.AnimState:PlayAnimation("idle_loop", true) inst.entity:SetPristine() if not TheWorld.ismastersim then return inst end inst.AnimState:SetFrame(math.random(inst.AnimState:GetCurrentAnimationNumFrames()) - 1) inst:AddComponent("pickable") inst.components.pickable.picksound = "dontstarve/wilson/pickup_reeds" inst.components.pickable:SetUp("cave_banana", TUNING.CAVE_BANANA_GROW_TIME) inst.components.pickable.onregenfn = onregenfn inst.components.pickable.onpickedfn = onpickedfn inst.components.pickable.makeemptyfn = makeemptyfn inst.components.pickable.makefullfn = makefullfn inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.CHOP) inst.components.workable:SetWorkLeft(3) inst.components.workable:SetOnFinishCallback(tree_chopped) inst.components.workable:SetOnWorkCallback(tree_chop) inst:AddComponent("lootdropper") inst:AddComponent("inspectable") --------------------- MakeMediumBurnable(inst) MakeSmallPropagator(inst) MakeNoGrowInWinter(inst) --------------------- inst.components.burnable:SetOnIgniteFn(tree_startburn) inst.components.burnable:SetOnBurntFn(tree_burnt) AddToRegrowthManager(inst) inst.OnSave = tree_onsave inst.OnLoad = tree_onload return inst end local function stump_startburn(inst) --blank fn to override default one since we do not --want to add "tree" tag but we still want to save end local function stump_burnt(inst) SpawnPrefab("ash").Transform:SetPosition(inst.Transform:GetWorldPosition()) inst:Remove() end local function stump_dug(inst) inst.components.lootdropper:SpawnLootPrefab("log") inst:Remove() end local function stump_onsave(inst, data) data.burnt = inst.components.burnable ~= nil and inst.components.burnable:IsBurning() or nil end local function stump_onload(inst, data) if data ~= nil and data.burnt then stump_burnt(inst) end end local function stump_fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.entity:AddMiniMapEntity() inst.entity:AddNetwork() inst.MiniMapEntity:SetIcon("cave_banana_tree_stump.png") inst:AddTag("plant") inst:AddTag("stump") inst.AnimState:SetBank("cave_banana_tree") inst.AnimState:SetBuild("cave_banana_tree") inst.AnimState:PlayAnimation("idle_stump") inst:SetPrefabNameOverride("cave_banana_tree") inst.entity:SetPristine() if not TheWorld.ismastersim then return inst end inst:AddComponent("lootdropper") inst:AddComponent("inspectable") inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.DIG) inst.components.workable:SetWorkLeft(1) inst.components.workable:SetOnWorkCallback(stump_dug) MakeSmallBurnable(inst) MakeSmallPropagator(inst) inst.components.burnable:SetOnIgniteFn(stump_startburn) inst.components.burnable:SetOnBurntFn(stump_burnt) inst.OnSave = stump_onsave inst.OnLoad = stump_onload return inst end local function burnt_chopped(inst) inst.components.workable:SetWorkable(false) inst.SoundEmitter:PlaySound("dontstarve/forest/treeCrumble") inst.AnimState:PlayAnimation("chop_burnt") inst.components.lootdropper:SpawnLootPrefab("charcoal") inst.persists = false inst:DoTaskInTime(50 * FRAMES, inst.Remove) end local function burnt_onsave(inst, data) data.no_banana = inst.no_banana or nil end local function burnt_onload(inst, data) if data ~= nil and data.no_banana then inst.no_banana = data.no_banana inst.AnimState:Hide("BANANA") end end local function burnt_fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.entity:AddMiniMapEntity() inst.entity:AddNetwork() MakeObstaclePhysics(inst, .25) inst.MiniMapEntity:SetIcon("cave_banana_tree_burnt.png") inst:AddTag("plant") inst.AnimState:SetBank("cave_banana_tree") inst.AnimState:SetBuild("cave_banana_tree") inst.AnimState:PlayAnimation("burnt") inst:SetPrefabNameOverride("cave_banana_tree") inst.entity:SetPristine() if not TheWorld.ismastersim then return inst end inst:AddComponent("inspectable") inst:AddComponent("lootdropper") inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.CHOP) inst.components.workable:SetWorkLeft(1) inst.components.workable:SetOnFinishCallback(burnt_chopped) MakeHauntableWorkAndIgnite(inst) inst.OnSave = burnt_onsave inst.OnLoad = burnt_onload return inst end return Prefab("cave_banana_tree", tree_fn, assets, prefabs_tree), Prefab("cave_banana_burnt", burnt_fn, assets, prefabs_burnt), Prefab("cave_banana_stump", stump_fn, assets, prefabs_stump)
0
0.643793
1
0.643793
game-dev
MEDIA
0.988527
game-dev
0.773722
1
0.773722
setuppf/GameBookServer
2,784
11_03_teleport/src/libs/libserver/system_manager.cpp
#include "system_manager.h" #include "create_component.h" #include "message_system.h" #include "entity_system.h" #include "update_system.h" #include "console_thread_component.h" #include "object_pool_collector.h" #include "timer_component.h" #include <thread> SystemManager::SystemManager() { _pEntitySystem = new EntitySystem(this); _pMessageSystem = new MessageSystem(this); _pUpdateSystem = new UpdateSystem(); _systems.emplace_back(_pUpdateSystem); //_systems.emplace_back(new DependenceSystem()); //_systems.emplace_back(new StartSystem()); // gen random seed ߳ID std::stringstream strStream; strStream << std::this_thread::get_id(); std::string idstr = strStream.str(); std::seed_seq seed1(idstr.begin(), idstr.end()); std::minstd_rand0 generator(seed1); _pRandomEngine = new std::default_random_engine(generator()); _pPoolCollector = new DynamicObjectPoolCollector(this); } void SystemManager::InitComponent(ThreadType threadType) { _pEntitySystem->AddComponent<TimerComponent>(); _pEntitySystem->AddComponent<CreateComponentC>(); _pEntitySystem->AddComponent<ConsoleThreadComponent>(threadType); } void SystemManager::Update() { #if LOG_TRACE_COMPONENT_OPEN CheckBegin(); #endif _pPoolCollector->Update(); #if LOG_TRACE_COMPONENT_OPEN CheckPoint("pool"); #endif _pEntitySystem->Update(); #if LOG_TRACE_COMPONENT_OPEN CheckPoint("entity"); #endif _pMessageSystem->Update(_pEntitySystem); #if LOG_TRACE_COMPONENT_OPEN CheckPoint("message"); #endif for (auto iter = _systems.begin(); iter != _systems.end(); ++iter) { auto pSys = (*iter); pSys->Update(_pEntitySystem); #if LOG_TRACE_COMPONENT_OPEN CheckPoint(pSys->GetTypeName()); #endif } } void SystemManager::Dispose() { for (auto one : _systems) { one->Dispose(); delete one; } _systems.clear(); delete _pRandomEngine; _pRandomEngine = nullptr; _pMessageSystem->Dispose(); delete _pMessageSystem; _pMessageSystem = nullptr; _pEntitySystem->Dispose(); delete _pEntitySystem; _pEntitySystem = nullptr; // ֮ǰһUpdateuseеĶصFree _pPoolCollector->Update(); _pPoolCollector->Dispose(); delete _pPoolCollector; _pPoolCollector = nullptr; } std::default_random_engine* SystemManager::GetRandomEngine() const { return _pRandomEngine; } MessageSystem* SystemManager::GetMessageSystem() const { return _pMessageSystem; } EntitySystem* SystemManager::GetEntitySystem() const { return _pEntitySystem; } UpdateSystem* SystemManager::GetUpdateSystem() const { return _pUpdateSystem; } DynamicObjectPoolCollector* SystemManager::GetPoolCollector() const { return _pPoolCollector; }
0
0.973861
1
0.973861
game-dev
MEDIA
0.564514
game-dev
0.969281
1
0.969281
opentomb/OpenTomb
2,354
src/physics/hair.h
#ifndef PHYSICS_HAIR_H #define PHYSICS_HAIR_H #include <stdint.h> /* Hair interface */ #define HAIR_TR1 0 #define HAIR_TR2 1 #define HAIR_TR3 2 #define HAIR_TR4_KID_1 3 #define HAIR_TR4_KID_2 4 #define HAIR_TR4_OLD 5 #define HAIR_TR5_KID_1 6 #define HAIR_TR5_KID_2 7 #define HAIR_TR5_OLD 8 // Maximum amount of joint hair vertices. By default, TR4-5 used four // vertices for each hair (unused TR1 hair mesh even used three). // It's hardly possible if anyone will exceed a limit of 8 vertices, // but if it happens, this should be edited. #define HAIR_VERTEX_MAP_LIMIT 8 // Since we apply TR4 hair scheme to TR2-3 as well, we need to discard // polygons which are unused. These are 0 and 5 in both TR2 and TR3. #define HAIR_DISCARD_ROOT_FACE 0 #define HAIR_DISCARD_TAIL_FACE 5 typedef struct hair_setup_s { uint32_t model_id; // Hair model ID uint32_t link_body; // Lara's head mesh index float root_weight; // Root and tail hair body weight. Intermediate body float tail_weight; // weights are calculated from these two parameters float hair_damping[2]; // Damping affects hair "plasticity" float hair_inertia; // Inertia affects hair "responsiveness" float hair_restitution; // "Bounciness" of the hair float hair_friction; // How much other bodies will affect hair trajectory float joint_overlap; // How much two hair bodies overlap each other float joint_cfm; // Constraint force mixing (joint softness) float joint_erp; // Error reduction parameter (joint "inertia") float head_offset[3]; // Linear offset to place hair to float root_angle[3]; // First constraint set angle (to align hair angle) uint32_t vertex_map_count; // Amount of REAL vertices to link head and hair uint32_t hair_vertex_map[HAIR_VERTEX_MAP_LIMIT]; // Hair vertex indices to link uint32_t head_vertex_map[HAIR_VERTEX_MAP_LIMIT]; // Head vertex indices to link }hair_setup_t, *hair_setup_p; // Gets scripted hair set-up to specified hair set-up structure. hair_setup_p Hair_GetSetup(struct lua_State *lua, int stack_pos); void Hair_DeleteSetup(hair_setup_p setup); #endif /* PHYSICS_HAIR_H */
0
0.837156
1
0.837156
game-dev
MEDIA
0.793357
game-dev
0.564225
1
0.564225
GodotECS/godex
3,687
storage/shared_steady_storage.h
#pragma once #include "core/templates/paged_allocator.h" #include "dense_vector.h" #include "storage.h" /// The `SharedSteadyStorage` is the perfect choice when you want to share the /// same component between entities, and that components memory never changes. /// /// When dealing with physics engines or audio engines, etc... it's usually /// needed to have objects that are shared between some other objects: in /// all those cases, it's possible to use this storage. template <class T> class SharedSteadyStorage : public SharedStorage<T> { PagedAllocator<T, false> allocator; LocalVector<T *> allocated_pointers; DenseVector<godex::SID> storage; public: virtual void configure(const Dictionary &p_config) override { clear(); allocator.configure(p_config.get("page_size", 200)); } virtual String get_type_name() const override { return "SteadyStorage[" + String(typeid(T).name()) + "]"; } virtual bool is_steady() const override { return true; } virtual godex::SID create_shared_component(const T &p_data) override { T *d = allocator.alloc(); *d = p_data; godex::SID id = allocated_pointers.size(); allocated_pointers.push_back(d); return id; } virtual void free_shared_component(godex::SID p_id) override { if (p_id < allocated_pointers.size()) { if (allocated_pointers[p_id] != nullptr) { allocator.free(allocated_pointers[p_id]); allocated_pointers[p_id] = nullptr; } } } virtual bool has_shared_component(godex::SID p_id) const override { if (p_id < allocated_pointers.size()) { return allocated_pointers[p_id] != nullptr; } return false; } virtual void insert(EntityID p_entity, godex::SID p_id) override { if (p_id < allocated_pointers.size()) { if (allocated_pointers[p_id] != nullptr) { storage.insert(p_entity, p_id); StorageBase::notify_changed(p_entity); return; } } ERR_PRINT("The SID is not poiting to any valid object. This is not supposed to happen."); } virtual T *get_shared_component(godex::SID p_id) override { if (p_id < allocated_pointers.size()) { if (allocated_pointers[p_id] != nullptr) { return allocated_pointers[p_id]; } } CRASH_NOW_MSG("This Entity doesn't have anything stored, before get the data you have to use `has()`."); return nullptr; } virtual const T *get_shared_component(godex::SID p_id) const override { if (p_id < allocated_pointers.size()) { if (allocated_pointers[p_id] != nullptr) { return allocated_pointers[p_id]; } } CRASH_NOW_MSG("This Entity doesn't have anything stored, before get the data you have to use `has()`."); return nullptr; } virtual bool has(EntityID p_entity) const override { bool h = storage.has(p_entity); if (h) { const godex::SID id = storage.get(p_entity); if (id < allocated_pointers.size()) { h = allocated_pointers[id] != nullptr; } else { // Doesn't have. h = false; } } return h; } virtual T *get(EntityID p_entity, Space p_mode = Space::LOCAL) override { StorageBase::notify_changed(p_entity); return get_shared_component(storage.get(p_entity)); } virtual const T *get(EntityID p_entity, Space p_mode = Space::LOCAL) const override { return get_shared_component(storage.get(p_entity)); } virtual void remove(EntityID p_entity) override { storage.remove(p_entity); // Make sure to remove as changed. StorageBase::notify_updated(p_entity); } virtual void clear() override { allocator.reset(); allocated_pointers.reset(); storage.clear(); StorageBase::flush_changed(); } virtual EntitiesBuffer get_stored_entities() const { return { storage.get_entities().size(), storage.get_entities().ptr() }; } };
0
0.986321
1
0.986321
game-dev
MEDIA
0.440201
game-dev
0.975462
1
0.975462
hieki-chan/Supermarket-Simulator-Prototype
1,801
Library/PackageCache/com.unity.visualscripting@1.9.4/Runtime/VisualScripting.Core/Profiling/ProfilingUtility.cs
using System.Diagnostics; using System.Threading; using UnityEngine.Profiling; namespace Unity.VisualScripting { public static class ProfilingUtility { static ProfilingUtility() { currentSegment = rootSegment = new ProfiledSegment(null, "Root"); } private static readonly object @lock = new object(); public static ProfiledSegment rootSegment { get; private set; } public static ProfiledSegment currentSegment { get; set; } [Conditional("ENABLE_PROFILER")] public static void Clear() { currentSegment = rootSegment = new ProfiledSegment(null, "Root"); } public static ProfilingScope SampleBlock(string name) { return new ProfilingScope(name); } [Conditional("ENABLE_PROFILER")] public static void BeginSample(string name) { Monitor.Enter(@lock); if (!currentSegment.children.Contains(name)) { currentSegment.children.Add(new ProfiledSegment(currentSegment, name)); } currentSegment = currentSegment.children[name]; currentSegment.calls++; currentSegment.stopwatch.Start(); if (UnityThread.allowsAPI) { Profiler.BeginSample(name); } } [Conditional("ENABLE_PROFILER")] public static void EndSample() { currentSegment.stopwatch.Stop(); if (currentSegment.parent != null) { currentSegment = currentSegment.parent; } if (UnityThread.allowsAPI) { Profiler.EndSample(); } Monitor.Exit(@lock); } } }
0
0.735674
1
0.735674
game-dev
MEDIA
0.719687
game-dev
0.817348
1
0.817348
d3cod3/ofxVisualProgramming
9,057
src/objects/gui/moMultiToggle.cpp
/*============================================================================== ofxVisualProgramming: A visual programming patching environment for OF Copyright (c) 2024 Emanuele Mazza aka n3m3da <emanuelemazza@d3cod3.org> ofxVisualProgramming is distributed under the MIT License. This gives everyone the freedoms to use ofxVisualProgramming in any context: commercial or non-commercial, public or private, open or closed source. 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. See https://github.com/d3cod3/ofxVisualProgramming for documentation ==============================================================================*/ #ifndef OFXVP_BUILD_WITH_MINIMAL_OBJECTS #include "moMultiToggle.h" //-------------------------------------------------------------- moMultiToggle::moMultiToggle() : PatchObject("multitoggle"){ this->numInlets = 1; this->numOutlets = 1; _inletParams[0] = new vector<float>(); // values _outletParams[0] = new vector<float>(); // output this->initInletsState(); numToggles = 6; newNumToggles = numToggles; values = new bool[numToggles]; toggleW = 26.0f; this->width *= 1.54; this->height /= 2.0f; needReset = false; loaded = false; } //-------------------------------------------------------------- void moMultiToggle::newObject(){ PatchObject::setName( this->objectName ); this->addInlet(VP_LINK_ARRAY,"values"); this->addOutlet(VP_LINK_ARRAY,"values"); this->setCustomVar(static_cast<float>(numToggles),"NUM_TOGGLES"); ofxVP_CAST_PIN_PTR<vector<float>>(this->_inletParams[0])->clear(); ofxVP_CAST_PIN_PTR<vector<float>>(this->_inletParams[0])->assign(numToggles,0.0f); ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->clear(); ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->assign(numToggles,0.0f); for(size_t i=0;i<numToggles;i++){ values[i] = false; } for(int i=0;i<numToggles;i++){ this->setCustomVar(static_cast<float>(values[i]),"TOGGLEVALUE_"+ofToString(i+1)); } } //-------------------------------------------------------------- void moMultiToggle::setupObjectContent(shared_ptr<ofAppGLFWWindow> &mainWindow){ unusedArgs(mainWindow); } //-------------------------------------------------------------- void moMultiToggle::updateObjectContent(map<int,shared_ptr<PatchObject>> &patchObjects){ unusedArgs(patchObjects); if(this->inletsConnected[0]){ for(size_t i=0;i<numToggles;i++){ if(ofxVP_CAST_PIN_PTR<vector<float>>(this->_inletParams[0])->at(i) >= 1.0f){ values[i] = true; }else{ values[i] = false; } } } for(size_t i=0;i<numToggles;i++){ if(values[i]){ ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->at(i) = 1.0f; }else{ ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->at(i) = 0.0f; } } if(needReset){ needReset = false; numToggles = newNumToggles; ofxVP_CAST_PIN_PTR<vector<float>>(this->_inletParams[0])->clear(); ofxVP_CAST_PIN_PTR<vector<float>>(this->_inletParams[0])->assign(numToggles,0.0f); ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->clear(); ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->assign(numToggles,0.0f); values = new bool[numToggles]; for(size_t i=0;i<numToggles;i++){ values[i] = false; } for(int i=0;i<numToggles;i++){ if(this->existsCustomVar("TOGGLEVALUE_"+ofToString(i+1))){ values[i] = static_cast<bool>(this->getCustomVar("TOGGLEVALUE_"+ofToString(i+1))); }else{ this->setCustomVar(static_cast<float>(values[i]),"TOGGLEVALUE_"+ofToString(i+1)); } } this->width = 20*scaleFactor + numToggles*(toggleW+8.0f)*scaleFactor + 10*scaleFactor; if(this->width < OBJECT_WIDTH*scaleFactor){ this->width = OBJECT_WIDTH*scaleFactor; } this->saveConfig(false); } if(!loaded){ loaded = true; numToggles = this->getCustomVar("NUM_TOGGLES"); newNumToggles = numToggles; ofxVP_CAST_PIN_PTR<vector<float>>(this->_inletParams[0])->clear(); ofxVP_CAST_PIN_PTR<vector<float>>(this->_inletParams[0])->assign(numToggles,0.0f); ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->clear(); ofxVP_CAST_PIN_PTR<vector<float>>(this->_outletParams[0])->assign(numToggles,0.0f); values = new bool[numToggles]; for(size_t i=0;i<numToggles;i++){ values[i] = false; } for(int i=0;i<numToggles;i++){ if(this->existsCustomVar("TOGGLEVALUE_"+ofToString(i+1))){ values[i] = static_cast<bool>(this->getCustomVar("TOGGLEVALUE_"+ofToString(i+1))); }else{ this->setCustomVar(static_cast<float>(values[i]),"TOGGLEVALUE_"+ofToString(i+1)); } } this->saveConfig(false); } } //-------------------------------------------------------------- void moMultiToggle::drawObjectContent(ofTrueTypeFont *font, shared_ptr<ofBaseGLRenderer>& glRenderer){ unusedArgs(font,glRenderer); } //-------------------------------------------------------------- void moMultiToggle::drawObjectNodeGui( ImGuiEx::NodeCanvas& _nodeCanvas ){ // CONFIG GUI inside Menu if(_nodeCanvas.BeginNodeMenu()){ ImGui::Separator(); ImGui::Separator(); ImGui::Separator(); if (ImGui::BeginMenu("CONFIG")) { drawObjectNodeConfig(); this->configMenuWidth = ImGui::GetWindowWidth(); ImGui::EndMenu(); } _nodeCanvas.EndNodeMenu(); } // Visualize (Object main view) if( _nodeCanvas.BeginNodeContent(ImGuiExNodeView_Visualise) ){ ImGui::SetCursorPos(ImVec2(((this->width*_nodeCanvas.GetCanvasScale())/2.0f)-(((toggleW+8.0)*scaleFactor)*numToggles/2.0f)+(8.0f*scaleFactor),(IMGUI_EX_NODE_HEADER_HEIGHT*scaleFactor)+(this->height*_nodeCanvas.GetCanvasScale()/2.0f)-(toggleW*scaleFactor))); for(int i=0;i<numToggles;i++){ if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32(120,120,120,30)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, IM_COL32(120,120,120,60)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, IM_COL32(120,120,120,60)); ImGui::PushStyleColor(ImGuiCol_SliderGrab, IM_COL32(120,120,120,160)); if(ImGui::Checkbox("##t",&values[i])){ this->setCustomVar(static_cast<float>(values[i]),"TOGGLEVALUE_"+ofToString(i+1)); } ImGui::PopStyleColor(4); ImGui::PopID(); } _nodeCanvas.EndNodeContent(); } } //-------------------------------------------------------------- void moMultiToggle::drawObjectNodeConfig(){ ImGui::Spacing(); if(ImGui::InputInt("Inlets",&newNumToggles)){ if(newNumToggles > MAX_INLETS){ newNumToggles = MAX_INLETS; } if(newNumToggles < 2){ newNumToggles = 2; } } ImGui::SameLine(); ImGuiEx::HelpMarker("You can set 32 inlets max."); ImGui::Spacing(); if(ImGui::Button("APPLY",ImVec2(224*scaleFactor,26*scaleFactor))){ this->setCustomVar(static_cast<float>(numToggles),"NUM_TOGGLES"); needReset = true; } ImGuiEx::ObjectInfo( "Multiple toggles gui object.", "https://mosaic.d3cod3.org/reference.php?r=multitoggle", scaleFactor); } //-------------------------------------------------------------- void moMultiToggle::removeObjectContent(bool removeFileFromData){ unusedArgs(removeFileFromData); } OBJECT_REGISTER( moMultiToggle, "multitoggle", OFXVP_OBJECT_CAT_GUI) #endif
0
0.882702
1
0.882702
game-dev
MEDIA
0.590367
game-dev
0.964141
1
0.964141
openai/atari-py
1,874
atari_py/ale_interface/src/games/supported/SirLancelot.hpp
/* ***************************************************************************** * A.L.E (Arcade Learning Environment) * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and * the Reinforcement Learning and Artificial Intelligence Laboratory * Released under the GNU General Public License; see License.txt for details. * * Based on: Stella -- "An Atari 2600 VCS Emulator" * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team * * ***************************************************************************** */ #ifndef __SIRLANCELOT_HPP__ #define __SIRLANCELOT_HPP__ #include "../RomSettings.hpp" /* RL wrapper for Up N Down */ class SirLancelotSettings : public RomSettings { public: SirLancelotSettings(); // reset void reset(); // is end of game bool isTerminal() const; // get the most recently observed reward reward_t getReward() const; // the rom-name // MD5 7ead257e8b5a44cac538f5f54c7a0023 const char* rom() const { return "sir_lancelot"; } // create a new instance of the rom RomSettings* clone() const; // is an action part of the minimal set? bool isMinimal(const Action& a) const; // process the latest information from ALE void step(const System& system); // saves the state of the rom settings void saveState(Serializer & ser); // loads the state of the rom settings void loadState(Deserializer & ser); // SirLancelot requires the reset+left action to start the game ActionVect getStartingActions(); virtual int lives() { return isTerminal() ? 0 : m_lives; } private: bool m_terminal; reward_t m_reward; reward_t m_score; int m_lives; }; #endif // __SIRLANCELOT_HPP__
0
0.838934
1
0.838934
game-dev
MEDIA
0.88142
game-dev
0.822439
1
0.822439
EluciusFTW/CardGames
1,059
src/Tests/CardGames.Poker.Tests/Hands/OmahaHandTests.cs
using CardGames.Poker.Hands.HandTypes; using CardGames.Core.French.Cards.Extensions; using Xunit; using FluentAssertions; using CardGames.Poker.Hands.CommunityCardHands; namespace CardGames.Poker.Tests.Hands; public class OmahaHandTests { [Theory] [InlineData("2s 5d 6d Qh", "8d Js Kc 5c 5h", HandType.Trips)] [InlineData("2s 5d 5h Qh", "8d Js Kc 7c 6h", HandType.OnePair)] public void Determines_Hand_Type(string holeCards, string boardCards, HandType expectedHandType) { var hand = new OmahaHand(holeCards.ToCards(), boardCards.ToCards()); hand.Type.Should().Be(expectedHandType); } [Theory] [InlineData("2s 5d 6d Qh", "8d Js Kc 5c")] [InlineData("2s 5d Qd As", "8d Qs Kc Ah")] public void Determines_Winner(string holeCardsOne, string holeCardsTwo) { var board = "Ac Ad Jd 6c 3s".ToCards(); var handOne = new OmahaHand(holeCardsOne.ToCards(), board); var handTwo = new OmahaHand(holeCardsTwo.ToCards(), board); (handOne < handTwo).Should().BeTrue(); } }
0
0.800549
1
0.800549
game-dev
MEDIA
0.886301
game-dev
0.618824
1
0.618824
Waikato/moa
8,532
moa/src/main/java/moa/clusterers/outliers/MCOD/ISBIndex.java
/* * ISBIndex.java * Copyright (C) 2013 Aristotle University of Thessaloniki, Greece * @author D. Georgiadis, A. Gounaris, A. Papadopoulos, K. Tsichlas, Y. Manolopoulos * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.clusterers.outliers.MCOD; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Vector; import com.yahoo.labs.samoa.instances.Instance; public class ISBIndex { public static class ISBNode implements Comparable<ISBNode> { public static enum NodeType { OUTLIER, INLIER_MC, INLIER_PD } public Instance inst; public StreamObj obj; public Long id; public MicroCluster mc; public Set<MicroCluster> Rmc; public int count_after; public NodeType nodeType; private ArrayList<ISBNode> nn_before; // statistics public int nOutlier; public int nInlier; public ISBNode(Instance inst, StreamObj obj, Long id) { this.inst = inst; this.obj = obj; this.id = id; // init statistics nOutlier = 0; nInlier = 0; // init other fields InitNode(); } public void InitNode() { this.mc = null; this.Rmc = new TreeSet<MicroCluster>(); this.count_after = 1; this.nodeType = NodeType.INLIER_PD; this.nn_before = new ArrayList<ISBNode>(); } @Override public int compareTo(ISBNode t) { if (this.id > t.id) return +1; else if (this.id < t.id) return -1; return 0; } public void AddPrecNeigh(ISBNode node) { int pos = Collections.binarySearch(nn_before, node); if (pos < 0) { // item does not exist, so add it to the right position nn_before.add(-(pos + 1), node); } } public void RemovePrecNeigh(ISBNode node) { int pos = Collections.binarySearch(nn_before, node); if (pos >= 0) { // item exists nn_before.remove(pos); } } public ISBNode GetMinPrecNeigh(Long sinceId) { if (nn_before.size() > 0) { int startPos; ISBNode dummy = new ISBNode(null, null, sinceId); int pos = Collections.binarySearch(nn_before, dummy); if (pos < 0) { // item does not exist, should insert at position startPos startPos = -(pos + 1); } else { // item exists at startPos startPos = pos; } if (startPos < nn_before.size()) { return nn_before.get(startPos); } } return null; } public int CountPrecNeighs(Long sinceId) { if (nn_before.size() > 0) { // get number of neighs with id >= sinceId int startPos; ISBNode dummy = new ISBNode(null, null, sinceId); int pos = Collections.binarySearch(nn_before, dummy); if (pos < 0) { // item does not exist, should insert at position startPos startPos = -(pos + 1); } else { // item exists at startPos startPos = pos; } if (startPos < nn_before.size()) { return nn_before.size() - startPos; } } return 0; } public List<ISBNode> Get_nn_before() { return nn_before; } } MTreeStreamObjects mtree; Map<Integer, Set<ISBNode>> mapNodes; double m_radius; int m_k; // k nearest neighbors public ISBIndex(double radius, int k) { mtree = new MTreeStreamObjects(); mapNodes = new HashMap<Integer, Set<ISBNode>>(); m_radius = radius; m_k = k; } Vector<ISBNode> GetAllNodes() { Vector<ISBNode> v = new Vector<ISBNode>(); Iterator it = mapNodes.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); Set<ISBNode> setNodes = (Set<ISBNode>) pairs.getValue(); for (ISBNode n : setNodes) { v.add(n); } } return v; } public static class ISBSearchResult { public ISBNode node; public double distance; public ISBSearchResult(ISBNode n, double distance) { this.node = n; this.distance = distance; } } public Vector<ISBSearchResult> RangeSearch(ISBNode node, double radius) { Vector<ISBSearchResult> results = new Vector<ISBSearchResult>(); StreamObj obj; double d; MTreeStreamObjects.Query query = mtree.getNearestByRange(node.obj, radius); for (MTreeStreamObjects.ResultItem q : query) { // get next obj found within range obj = q.data; // get distance of obj from query d = q.distance; // get all nodes referencing obj Vector<ISBNode> nodes = MapGetNodes(obj); for (int i = 0; i < nodes.size(); i++) results.add(new ISBSearchResult(nodes.get(i), d)); } return results; } public void Insert(ISBNode node) { // insert object of node at mtree mtree.add(node.obj); // insert node at map MapInsert(node); } public void Remove(ISBNode node) { // remove from map MapDelete(node); // check if stream object at mtree is still being referenced if (MapCountObjRefs(node.obj) <= 0) { // delete stream object from mtree mtree.remove(node.obj); } } Vector<ISBNode> MapGetNodes(StreamObj obj) { int h = obj.hashCode(); Vector<ISBNode> v = new Vector<ISBNode>(); if (mapNodes.containsKey(h)) { Set<ISBNode> s = mapNodes.get(h); ISBNode node; Iterator<ISBNode> i = s.iterator(); while (i.hasNext()) { node = i.next(); if (node.obj.equals(obj)) v.add(node); } } return v; } int MapCountObjRefs(StreamObj obj) { int h = obj.hashCode(); int iCount = 0; if (mapNodes.containsKey(h)) { Set<ISBNode> s = mapNodes.get(h); ISBNode n; Iterator<ISBNode> i = s.iterator(); while (i.hasNext()) { n = i.next(); if (n.obj.equals(obj)) iCount++; } } return iCount; } void MapInsert(ISBNode node) { int h = node.obj.hashCode(); Set<ISBNode> s; if (mapNodes.containsKey(h)) { s = mapNodes.get(h); s.add(node); } else { s = new HashSet<ISBNode>(); s.add(node); mapNodes.put(h, s); } } void MapDelete(ISBNode node) { int h = node.obj.hashCode(); if (mapNodes.containsKey(h)) { Set<ISBNode> s = mapNodes.get(h); s.remove(node); if (s.isEmpty()) { // ### added mapNodes.remove(h); } } } }
0
0.795355
1
0.795355
game-dev
MEDIA
0.174983
game-dev
0.964779
1
0.964779
igiagkiozis/CrystalAI
7,996
CrystalAI/Source/Actions/GenericActionBase.cs
// GPL v3 License // // Copyright (c) 2016-2017 Bismur Studios Ltd. // Copyright (c) 2016-2017 Ioannis Giagkiozis // // GenericActionBase.cs is part of Crystal AI. // // Crystal AI 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. // // Crystal AI 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 Crystal AI. If not, see <http://www.gnu.org/licenses/>. using System; namespace Crystal { /// <summary> /// Base class for generic <see cref="T:Crystal.IAction"/>s. All actions should derive either from /// this class or its non-generic version <see cref="T:Crystal.ActionBase"/>. /// </summary> /// <typeparam name="TContext">The type of the context.</typeparam> /// <seealso cref="T:Crystal.IAction"/> public class ActionBase<TContext> : IAction where TContext : class, IContext { readonly IActionCollection _collection; float _cooldown; float _startedTime; /// <summary> /// A unique identifier for this action. /// </summary> public string NameId { get; } /// <summary> /// The Time that this action has been running for since it has been started in seconds. /// </summary> public float ElapsedTime { get { if(ActionStatus == ActionStatus.Running) return CrTime.TotalSeconds - _startedTime; return 0f; } } /// <summary> /// The required cool-down time, in seconds, needed before this action executes again. /// </summary> public float Cooldown { get { return _cooldown; } set { _cooldown = value.ClampToLowerBound(0.0f); } } /// <summary> /// This returns true if the cool-down time for this action has not yet elapsed. /// </summary> public bool InCooldown { get { if(ActionStatus == ActionStatus.Running || ActionStatus == ActionStatus.Idle) return false; return CrTime.TotalSeconds - _startedTime < _cooldown; } } /// <summary> /// Gets the action status. /// </summary> public ActionStatus ActionStatus { get; protected set; } = ActionStatus.Idle; /// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public void Execute(TContext context) { if(CanExecute() == false) return; if(TryUpdate(context) == false) { _startedTime = CrTime.TotalSeconds; ActionStatus = ActionStatus.Running; OnExecute(context); } } /// <summary> /// Creates a new instance of the implementing class. Note that the semantics here /// are somewhat vague, however, by convention the "Prototype Pattern" uses a "Clone" /// function. Note that this may have very different semantics when compared with either /// shallow or deep cloning. When implementing this remember to include only the defining /// characteristics of the class and not its state! /// </summary> /// <returns></returns> public virtual IAction Clone() { return new ActionBase<TContext>(this); } /// <summary> /// Ends the action and sets its status to <see cref="F:Crystal.ActionStatus.Success"/>. /// </summary> /// <param name="context">The context.</param> protected void EndInSuccess(IContext context) { EndInSuccess((TContext)context); } /// <summary> /// Ends the action and sets its status to <see cref="F:Crystal.ActionStatus.Failure"/>. /// </summary> /// <param name="context">The context.</param> protected void EndInFailure(IContext context) { EndInFailure((TContext)context); } /// <summary> /// Ends the action and sets its status to <see cref="F:Crystal.ActionStatus.Success"/>. /// </summary> /// <param name="context">The context.</param> protected void EndInSuccess(TContext context) { if(ActionStatus != ActionStatus.Running) return; ActionStatus = ActionStatus.Success; FinalizeAction(context); } /// <summary> /// Ends the action and sets its status to <see cref="F:Crystal.ActionStatus.Failure"/>. /// </summary> /// <param name="context">The context.</param> protected void EndInFailure(TContext context) { if(ActionStatus != ActionStatus.Running) return; ActionStatus = ActionStatus.Failure; FinalizeAction(context); } /// <summary> /// Executes once when the action starts. /// </summary> /// <param name="context">Context.</param> protected virtual void OnExecute(TContext context) { EndInSuccess(context); } /// <summary> /// Executes on every action update, until <see cref="ActionBase.EndInSuccess"/> or /// <see cref="ActionBase.EndInFailure"/> is called. /// </summary> /// <param name="context">Context.</param> protected virtual void OnUpdate(TContext context) { } /// <summary> /// This can be used for cleanup. It executes after <see cref="ActionBase.EndInSuccess"/> or /// <see cref="ActionBase.EndInFailure"/> is called. /// </summary> /// <param name="context">Context.</param> protected virtual void OnStop(TContext context) { } /// <summary> /// Initializes a new instance of the <see cref="ActionBase{TContext}"/> class. /// </summary> public ActionBase() { } /// <summary> /// Initializes a new instance of the <see cref="ActionBase{TContext}"/> class. /// </summary> /// <param name="other">The other.</param> protected ActionBase(ActionBase<TContext> other) { NameId = other.NameId; Cooldown = other.Cooldown; _collection = other._collection; } /// <summary> /// Initializes a new instance of the <see cref="ActionBase{TContext}"/> class. /// </summary> /// <param name="nameId">The name identifier.</param> /// <param name="collection">The collection.</param> /// <exception cref="T:Crystal.ActionBase`1.NameIdEmptyOrNullException"></exception> /// <exception cref="T:Crystal.ActionBase`1.ActionCollectionNullException"></exception> public ActionBase(string nameId, IActionCollection collection) { if(string.IsNullOrEmpty(nameId)) throw new NameIdEmptyOrNullException(); if(collection == null) throw new ActionCollectionNullException(); NameId = nameId; _collection = collection; AddSelfToCollection(); } void IAction.Execute(IContext context) { Execute((TContext)context); } bool CanExecute() { if(InCooldown) { ActionStatus = ActionStatus.Failure; return false; } return true; } bool TryUpdate(TContext context) { if(ActionStatus == ActionStatus.Running) { OnUpdate(context); return true; } return false; } void FinalizeAction(TContext context) { OnStop(context); } void AddSelfToCollection() { if(_collection.Add(this) == false) throw new ActionAlreadyExistsInCollectionException(NameId); } internal class NameIdEmptyOrNullException : Exception { } internal class ActionCollectionNullException : Exception { } internal class ActionAlreadyExistsInCollectionException : Exception { public override string Message { get; } public ActionAlreadyExistsInCollectionException(string nameId) { Message = string.Format("Error: {0} already exists in the actions collection.", nameId); } } } }
0
0.875457
1
0.875457
game-dev
MEDIA
0.327532
game-dev
0.950755
1
0.950755
philkr/pystk
6,610
lib/bullet/src/BulletCollision/CollisionShapes/btCompoundShape.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_COMPOUND_SHAPE_H #define BT_COMPOUND_SHAPE_H #include "btCollisionShape.h" #include "LinearMath/btVector3.h" #include "LinearMath/btTransform.h" #include "LinearMath/btMatrix3x3.h" #include "btCollisionMargin.h" #include "LinearMath/btAlignedObjectArray.h" //class btOptimizedBvh; struct btDbvt; ATTRIBUTE_ALIGNED16(struct) btCompoundShapeChild { BT_DECLARE_ALIGNED_ALLOCATOR(); btTransform m_transform; btCollisionShape* m_childShape; int m_childShapeType; btScalar m_childMargin; struct btDbvtNode* m_node; }; SIMD_FORCE_INLINE bool operator==(const btCompoundShapeChild& c1, const btCompoundShapeChild& c2) { return ( c1.m_transform == c2.m_transform && c1.m_childShape == c2.m_childShape && c1.m_childShapeType == c2.m_childShapeType && c1.m_childMargin == c2.m_childMargin ); } /// The btCompoundShape allows to store multiple other btCollisionShapes /// This allows for moving concave collision objects. This is more general then the static concave btBvhTriangleMeshShape. /// It has an (optional) dynamic aabb tree to accelerate early rejection tests. /// @todo: This aabb tree can also be use to speed up ray tests on btCompoundShape, see http://code.google.com/p/bullet/issues/detail?id=25 /// Currently, removal of child shapes is only supported when disabling the aabb tree (pass 'false' in the constructor of btCompoundShape) ATTRIBUTE_ALIGNED16(class) btCompoundShape : public btCollisionShape { btAlignedObjectArray<btCompoundShapeChild> m_children; btVector3 m_localAabbMin; btVector3 m_localAabbMax; btDbvt* m_dynamicAabbTree; ///increment m_updateRevision when adding/removing/replacing child shapes, so that some caches can be updated int m_updateRevision; btScalar m_collisionMargin; protected: btVector3 m_localScaling; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btCompoundShape(bool enableDynamicAabbTree = true); virtual ~btCompoundShape(); void addChildShape(const btTransform& localTransform,btCollisionShape* shape); /// Remove all children shapes that contain the specified shape virtual void removeChildShape(btCollisionShape* shape); void removeChildShapeByIndex(int childShapeindex); int getNumChildShapes() const { return int (m_children.size()); } btCollisionShape* getChildShape(int index) { return m_children[index].m_childShape; } const btCollisionShape* getChildShape(int index) const { return m_children[index].m_childShape; } btTransform& getChildTransform(int index) { return m_children[index].m_transform; } const btTransform& getChildTransform(int index) const { return m_children[index].m_transform; } ///set a new transform for a child, and update internal data structures (local aabb and dynamic tree) void updateChildTransform(int childIndex, const btTransform& newChildTransform, bool shouldRecalculateLocalAabb = true); btCompoundShapeChild* getChildList() { return &m_children[0]; } ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; /** Re-calculate the local Aabb. Is called at the end of removeChildShapes. Use this yourself if you modify the children or their transforms. */ virtual void recalculateLocalAabb(); virtual void setLocalScaling(const btVector3& scaling); virtual const btVector3& getLocalScaling() const { return m_localScaling; } virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual void setMargin(btScalar margin) { m_collisionMargin = margin; } virtual btScalar getMargin() const { return m_collisionMargin; } virtual const char* getName()const { return "Compound"; } const btDbvt* getDynamicAabbTree() const { return m_dynamicAabbTree; } btDbvt* getDynamicAabbTree() { return m_dynamicAabbTree; } void createAabbTreeFromChildren(); ///computes the exact moment of inertia and the transform from the coordinate system defined by the principal axes of the moment of inertia ///and the center of mass to the current coordinate system. "masses" points to an array of masses of the children. The resulting transform ///"principal" has to be applied inversely to all children transforms in order for the local coordinate system of the compound ///shape to be centered at the center of mass and to coincide with the principal axes. This also necessitates a correction of the world transform ///of the collision object by the principal transform. void calculatePrincipalAxisTransform(btScalar* masses, btTransform& principal, btVector3& inertia) const; int getUpdateRevision() const { return m_updateRevision; } virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btCompoundShapeChildData { btTransformFloatData m_transform; btCollisionShapeData *m_childShape; int m_childShapeType; float m_childMargin; }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btCompoundShapeData { btCollisionShapeData m_collisionShapeData; btCompoundShapeChildData *m_childShapePtr; int m_numChildShapes; float m_collisionMargin; }; SIMD_FORCE_INLINE int btCompoundShape::calculateSerializeBufferSize() const { return sizeof(btCompoundShapeData); } #endif //BT_COMPOUND_SHAPE_H
0
0.977955
1
0.977955
game-dev
MEDIA
0.95518
game-dev
0.989644
1
0.989644
Mindgamesnl/OpenAudioMc
3,161
OpenAudioMc/Plugin/src/main/java/com/craftmend/openaudiomc/spigot/modules/regions/registry/WorldRegionManager.java
package com.craftmend.openaudiomc.spigot.modules.regions.registry; import com.craftmend.openaudiomc.generic.storage.enums.StorageKey; import com.craftmend.openaudiomc.spigot.modules.regions.objects.RegionMedia; import com.craftmend.openaudiomc.spigot.modules.regions.objects.RegionProperties; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class WorldRegionManager { private String world; // map region source -> shared media private final Map<String, RegionMedia> regionMediaMap = new HashMap<>(); // map region name -> region properties / settings private final Map<String, RegionProperties> regionPropertiesMap = new HashMap<>(); public WorldRegionManager(String world) { this.world = world; } public void registerRegion(RegionProperties addedRegion) { // check if we already have this region if (regionPropertiesMap.containsKey(addedRegion.getRegionName())) { // is the one we are adding newer? RegionProperties currentRegion = regionPropertiesMap.get(addedRegion.getRegionName()); if (currentRegion.getId() != null && addedRegion.getId() != null && currentRegion.getId() > addedRegion.getId()) { // nope, we already have a newer one return; } } regionPropertiesMap.put(addedRegion.getRegionName(), addedRegion); // update media if (regionMediaMap.get(addedRegion.getSource()) != null) { regionMediaMap.get(addedRegion.getSource()).setVolume(addedRegion.getVolume()); regionMediaMap.get(addedRegion.getSource()).setFadeTime(addedRegion.getFadeTimeMs()); } if (StorageKey.SETTINGS_HYDRATE_REGIONS_ON_BOOT.getBoolean()) { addedRegion.getMediaForWorld(this); } } public RegionProperties getRegionProperties(String regionName) { return regionPropertiesMap.get(regionName); } public void unregisterRegion(String regionName) { regionPropertiesMap.remove(regionName); } public boolean containsRegion(String regionName) { return regionPropertiesMap.containsKey(regionName); } public RegionMedia getRegionMedia(String source, int volume, int fadeTimeMs, Boolean loop) { if (regionMediaMap.containsKey(source)) return regionMediaMap.get(source); RegionMedia regionMedia = new RegionMedia(source, volume, fadeTimeMs, loop); regionMediaMap.put(source, regionMedia); return regionMedia; } public void dropMediaCache() { regionMediaMap.clear(); } public Collection<RegionProperties> getRegions() { return regionPropertiesMap.values(); } public void unregisterRegionMedia(String source) { regionMediaMap.remove(source); } public void clearMediaCache() { regionMediaMap.clear(); } public int getRegionCount() { return regionPropertiesMap.size(); } public void registerRegions(Set<RegionProperties> regionsWithoutWorld) { regionsWithoutWorld.forEach(this::registerRegion); } }
0
0.593892
1
0.593892
game-dev
MEDIA
0.832905
game-dev
0.851529
1
0.851529
KoffeinFlummi/AGM
2,393
AGM_Logistics/functions/Drag/fn_dragObject.sqf
/* Name: AGM_Drag_fnc_dragObject Author(s): L-H Description: Prepares the passed unit to drag the passed weapon. Parameters: 0: OBJECT - Dragged weapon 1: OBJECT - Unit dragging Returns: Nothing Example: [StaticWeapon3, player] call AGM_Drag_fnc_dragObject; */ #define ANIM_CARRY ["amovpercmstpslowwrfldnon_acinpknlmwlkslowwrfldb_2", "amovpercmstpsraswpstdnon_acinpknlmwlksnonwpstdb_2", "amovpercmstpsnonwnondnon_acinpknlmwlksnonwnondb_2", "acinpknlmstpsraswrfldnon", "acinpknlmstpsnonwpstdnon", "acinpknlmstpsnonwnondnon"]; _this spawn { _draggedObject = _this select 0; _unit = _this select 1; if (_draggedObject getVariable ["AGM_disableDrag", false]) exitWith {}; _ableToDrag = true; if ((typeOf _draggedObject) isKindOf "StaticWeapon") then { _gunner = gunner _draggedObject; if (!isNull _gunner && {alive _gunner}) then { _gunner setPosASL getPosASL _gunner; }; } else { // Crate handling if (_draggedObject getVariable ["AGM_useWeight", true]) then { _ableToDrag = ((_draggedObject call AGM_Drag_fnc_GetWeight) <= AGM_Drag_MaxWeight); }; }; if (!_ableToDrag) exitWith { [localize "STR_AGM_Drag_UnableToDrag"] call AGM_Core_fnc_displayTextStructured;}; if (primaryWeapon _unit == "") then { _unit addWeapon "AGM_FakePrimaryWeapon"; }; _unit selectWeapon (primaryWeapon _unit); [_unit, _draggedObject, true] call AGM_Core_fnc_claim; _unit setVariable ["AGM_isDragging", true]; _unit setVariable ["AGM_carriedItem", _draggedObject, true]; _unit playActionNow "grabDrag"; waitUntil {animationState _unit in ANIM_CARRY}; // exit here if the player releases the jerry can before the animation is finished if !(_unit getVariable ["AGM_isDragging", false]) exitWith { _unit playAction "released"; }; _attachPoint = [0,1.2, ((_draggedObject modelToWorld [0,0,0]) select 2) - ((_unit modelToWorld [0,0,0]) select 2)]; _draggedObject attachTo [_unit, _attachPoint]; _actionID = _unit getVariable ["AGM_Drag_ReleaseActionID", -1]; if (_actionID != -1) then { _unit removeAction _actionID; }; _actionID = _unit addAction [format ["<t color='#FF0000'>%1</t>", localize "STR_AGM_Drag_EndDrag"], "player call AGM_Drag_fnc_releaseObject;", nil, 20, false, true, "","player call AGM_Drag_fnc_isDraggingObject"]; _unit setVariable ["AGM_Drag_ReleaseActionID", _actionID]; AGM_Drag_CurrentHeightChange = 0; };
0
0.77042
1
0.77042
game-dev
MEDIA
0.981051
game-dev
0.901023
1
0.901023
charlesfranciscodev/codingame
3,989
puzzles/kotlin/src/skynet-revolution2/skynet-revolution2.kt
import java.util.Scanner import java.util.ArrayDeque fun main(args : Array<String>) { val graph = Graph() graph.readInitInput() graph.gameLoop() } class Node(val index:Int) { val links = ArrayList<Node>() var isGateway = false var isMarked = false fun nbGatewayLinks() : Int { return links.count { it.isGateway } } fun gatewayLink(): Node? { return links.firstOrNull { it.isGateway } } } class Graph { val input = Scanner(System.`in`) val nodes = ArrayList<Node>() val targetGateways = ArrayList<Node>() fun updateTargets(gateway: Node) { if (gateway.links.isEmpty()) { targetGateways.remove(gateway) } } fun reset() { for (node in nodes) { node.isMarked = false } } /** n1 and n2 are the indices of the nodes you wish to sever the link between */ fun sever(n1: Int, n2: Int) { val builder = StringBuilder() builder.append(n1) builder.append(" ") builder.append(n2) println(builder.toString()) } fun readInitInput() { val nbNodes = input.nextInt() // the total number of nodes in the level, including the gateways val nbLinks = input.nextInt() // the number of links val nbGateways = input.nextInt() // the number of exit gateways (0 until nbNodes).mapTo(nodes) { Node(it) } for (i in 0 until nbLinks) { val n1 = input.nextInt() // n1 and n2 defines a link between these nodes val n2 = input.nextInt() val node1 = nodes[n1] val node2 = nodes[n2] node1.links.add(node2) node2.links.add(node1) } for (i in 0 until nbGateways) { val index = input.nextInt() // the index of a gateway node val gateway = nodes[index] gateway.isGateway = true targetGateways.add(gateway) } } fun gameLoop() { while (true) { val agentIndex = input.nextInt() // The index of the node on which the Skynet agent is positioned this turn if (!blockNearbyAgent(agentIndex)) { if (!blockDoubleGateway(agentIndex)) { blockGateway() } } } } /** If the agent is linked to an exit, sever the link and return True. Otherwise, return False */ fun blockNearbyAgent(agentIndex: Int): Boolean { val agentNode = nodes[agentIndex] for (node in agentNode.links) { if (node.isGateway) { sever(agentIndex, node.index) agentNode.links.remove(node) node.links.remove(agentNode) updateTargets(node) return true } } return false } /** * Slice the last link on the shortest path between the virus and a gateway using BFS. * Only danger nodes are considered in possible paths. * A danger node is a node with 1 or more gateway links. * The link is severed if the node is linked to 2 gateways. * */ fun blockDoubleGateway(agentIndex: Int): Boolean { val agentNode = nodes[agentIndex] val queue = ArrayDeque<Node>() reset() agentNode.isMarked = true queue.add(agentNode) while(!queue.isEmpty()) { val currentNode = queue.pollFirst() for (neighbor in currentNode.links) { val nbGatewayLinks = neighbor.nbGatewayLinks() if (!neighbor.isGateway && nbGatewayLinks >= 1 && !neighbor.isMarked) { neighbor.isMarked = true if (nbGatewayLinks == 2) { val gateway = neighbor.gatewayLink() if (gateway != null) { sever(neighbor.index, gateway.index) neighbor.links.remove(gateway) gateway.links.remove(neighbor) updateTargets(gateway) return true } } else { queue.add(neighbor) } } } } return false } /** Slice a random gateway link. */ fun blockGateway() { val gateway = targetGateways[0] val node = gateway.links[0] sever(gateway.index, node.index) gateway.links.remove(node) node.links.remove(gateway) updateTargets(gateway) } }
0
0.82036
1
0.82036
game-dev
MEDIA
0.650405
game-dev
0.9439
1
0.9439
AliView/AliView
6,138
src/main/java/aliview/importer/ReaderHelper.java
package aliview.importer; import java.io.BufferedReader; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /* * * This method is inspired by Import Helper * * */ public class ReaderHelper { private static final Logger logger = Logger.getLogger(ReaderHelper.class); private BufferedReader reader; private int lastReadInt; private String nextLine; public ReaderHelper(BufferedReader reader){ this.reader = reader; } public String getStringUntilNextSpaceOrTab() throws IOException{ StringBuilder chars = new StringBuilder(); boolean haveHadNonWhiteChars = false; while(true){ char nextChar = readChar(); if(isWhiteSpace(nextChar) && haveHadNonWhiteChars){ break; } else{ chars.append(nextChar); haveHadNonWhiteChars = true; } } return chars.toString(); } public String getStringFromNextPositions(int count) throws IOException { StringBuilder chars = new StringBuilder(); for(int n = 0; n < count; n++){ char nextChar = readChar(); if(isPhylipNameChar(nextChar)){ chars.append(nextChar); }else{ // skip this one } } return chars.toString(); } public String getNonWhiteCharsUntilNextLineOrEOF() throws IOException { StringBuilder chars = new StringBuilder(); try { while(true){ char nextChar = readChar(); if(isNewline(nextChar)){ break; }else if(isWhiteSpaceNotNewline(nextChar)){ // skip }else{ chars.append(nextChar); } } } catch (EOFException e) { // do nothing and return what is in buffer } return chars.toString(); } public byte[] getNonWhiteBytes(int count) throws IOException{ byte[] bytes = new byte[count]; int nextInt; int counter = 0; while(counter < count){ nextInt = read(); if(isWhiteSpace(nextInt)){ // skip } else{ bytes[counter] = (byte)nextInt; counter ++; } } return bytes; } public String getNonWhiteCharsUntilNextOrEOF(char targetChar, int nextSeqSizeEstimate) throws IOException { StringBuilder chars = new StringBuilder(nextSeqSizeEstimate); try { while(true){ char nextChar = readChar(); if(nextChar == targetChar){ break; }else if(isWhiteSpace(nextChar)){ // skip }else{ chars.append(nextChar); } } } catch (EOFException e) { // Do nothing - return what is in buffer } return chars.toString(); } public char readChar() throws IOException{ return (char) read(); } public int read() throws IOException{ lastReadInt = reader.read(); if(lastReadInt == -1){ throw new EOFException(); } return lastReadInt; } public boolean isEOF(){ return lastReadInt == -1; } public void skipPastNextline() throws IOException { while(readChar() != '\n'); } public void skipPastNext(char c) throws IOException { while(readChar() != c); } public void readNextLine() throws IOException{ nextLine = reader.readLine(); } public String getNextLine() throws IOException{ return nextLine; } public boolean isNextLineEOF() throws IOException{ return (nextLine == null); } public boolean isNextLineContainingNonWhitespaceChars() throws IOException{ if(isNextLineEOF()){ return false; } return isStringContainingNonWhitespaceChars(nextLine); } public boolean isNextLineEmptyOrOnlyWhitespaceChars() throws IOException{ if(isNextLineEOF()){ return false; } return !isStringContainingNonWhitespaceChars(nextLine); } public boolean isNextLineStartingWithNonBlankChar(){ if(nextLine != null){ if(nextLine.length() > 0){ if(!isWhiteSpace(nextLine.charAt(0))){ return true; } } } return false; } public void readUntilNextNonBlankLine() throws IOException{ readNextLine(); while(isNextLineEmptyOrOnlyWhitespaceChars()){ readNextLine(); } } public boolean readUntilNextLineContains(String target) throws IOException { readNextLine(); while(!isNextLineEOF()){ if(StringUtils.containsIgnoreCase(nextLine, target)){ return true; } readNextLine(); } return false; } // // Utility methods // private static boolean isPhylipNameChar(char c) { if(c == '\t' || c=='\r' || c=='\n'){ return false; } else{ return true; } } private static boolean isWhiteSpace(int c) { return isWhiteSpace((char)c); } private static boolean isSpaceOrTab(char c) { if(c==' ' || c=='\t'){ return true; } else{ return false; } } private static boolean isWhiteSpace(char c) { if(c==' ' || c == '\t' || c=='\r' || c=='\n'){ return true; } else{ return false; } } private static boolean isWhiteSpaceNotNewline(char c) { if(c==' ' || c == '\t' || c=='\r'){ return true; } else{ return false; } } private static boolean isNewline(char c) { if(c=='\n'){ return true; } else{ return false; } } public static boolean isStringContainingNonWhitespaceChars(String input){ if(input == null){ return false; } for(int n = 0; n < input.length(); n++){ if(! isWhiteSpace(input.charAt(n))){ return true; } } return false; } public static String removeSpace(String text) { if(text.indexOf(' ')>-1){ text = StringUtils.remove(text, ' '); } return text; } public static String removeTab(String text) { if(text.indexOf('\t')>-1){ text = StringUtils.remove(text, '\t'); } return text; } public static String removeSpaceAndTab(String text) { text = removeSpace(text); text = removeTab(text); return text; } public static int indexOfFirstNonWhiteCharAfterWhiteChar(String text) { boolean whiteFound = false; int index = -1; for(int n = 0; n< text.length(); n++){ if(isWhiteSpace(text.charAt(n))){ whiteFound = true; } if(whiteFound && !isWhiteSpace(text.charAt(n))){ index = n; break; } } return index; } public static int indexOfFirstNonWhiteChar(String text) { int index = -1; for(int n = 0; n< text.length(); n++){ if(! isWhiteSpace(text.charAt(n))){ index = n; break; } } return index; } }
0
0.836491
1
0.836491
game-dev
MEDIA
0.121673
game-dev
0.967656
1
0.967656
ducttape/ducttape-engine
1,641
engine/src/Physics/PhysicsManager.cpp
// ---------------------------------------------------------------------------- // This file is part of the Ducttape Project (http://ducttape-dev.org) and is // licensed under the GNU LESSER PUBLIC LICENSE version 3. For the full license // text, please see the LICENSE file in the root of this project or at // http://www.gnu.org/licenses/lgpl.html // ---------------------------------------------------------------------------- #include <Physics/PhysicsManager.hpp> #include <Core/Root.hpp> namespace dt { PhysicsManager::PhysicsManager() {} void PhysicsManager::initialize() { } void PhysicsManager::deinitialize() { for(auto it = mWorlds.begin(); it != mWorlds.end(); ++it) { it->second->deinitialize(); } mWorlds.clear(); } void PhysicsManager::updateFrame(double simulation_frame_time) { // step all worlds for(auto iter = mWorlds.begin(); iter != mWorlds.end(); ++iter) { iter->second->stepSimulation(simulation_frame_time); } } PhysicsManager* PhysicsManager::get() { return Root::getInstance().getPhysicsManager(); } bool PhysicsManager::hasWorld(const QString name) { return mWorlds.count(name) > 0; } PhysicsWorld::PhysicsWorldSP PhysicsManager::addWorld(PhysicsWorld* world) { QString name = world->getName(); PhysicsWorld::PhysicsWorldSP world_sp(world); mWorlds.insert(std::make_pair(name, world_sp)); getWorld(name)->initialize(); return getWorld(name); } PhysicsWorld::PhysicsWorldSP PhysicsManager::getWorld(const QString name) { if(hasWorld(name)) return mWorlds.find(name)->second; return PhysicsWorld::PhysicsWorldSP(); } }
0
0.567925
1
0.567925
game-dev
MEDIA
0.891321
game-dev
0.663315
1
0.663315
XFactHD/FramedBlocks
1,259
src/main/java/io/github/xfacthd/framedblocks/client/model/geometry/cube/FramedPathGeometry.java
package io.github.xfacthd.framedblocks.client.model.geometry.cube; import io.github.xfacthd.framedblocks.api.model.data.QuadMap; import io.github.xfacthd.framedblocks.api.model.geometry.Geometry; import io.github.xfacthd.framedblocks.api.model.quad.Modifiers; import io.github.xfacthd.framedblocks.api.model.quad.QuadModifier; import io.github.xfacthd.framedblocks.api.model.wrapping.GeometryFactory; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.neoforged.neoforge.model.data.ModelData; public class FramedPathGeometry extends Geometry { public FramedPathGeometry(@SuppressWarnings("unused") GeometryFactory.Context ctx) {} @Override public void transformQuad(QuadMap quadMap, BakedQuad quad, ModelData data) { Direction quadDir = quad.direction(); if (quadDir == Direction.UP) { QuadModifier.of(quad) .apply(Modifiers.setPosition(15F/16F)) .export(quadMap.get(null)); } else if (quadDir != Direction.DOWN) { QuadModifier.of(quad) .apply(Modifiers.cut(Direction.UP, 15F/16F)) .export(quadMap.get(quadDir)); } } }
0
0.681422
1
0.681422
game-dev
MEDIA
0.494307
game-dev,graphics-rendering
0.759976
1
0.759976
KimYC1223/UnityPathGenerator
5,472
Packages/com.unity.asset-store-tools/Editor/Exporter/PackageExporter.cs
using AssetStoreTools.Utility; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using UnityEditor; namespace AssetStoreTools.Exporter { internal abstract class PackageExporter { protected const string ProgressBarTitle = "Exporting Package"; protected const string ProgressBarStepSavingAssets = "Saving Assets..."; protected const string ProgressBarStepGatheringFiles = "Gathering files..."; protected const string ProgressBarStepCompressingPackage = "Compressing package..."; public static async Task<ExportResult> ExportPackage(ExporterSettings exportSettings) { if (!IsSettingsValid(exportSettings, out Exception e)) return new ExportResult() { Success = false, Error = ASError.GetGenericError(e) }; switch (exportSettings) { case LegacyExporterSettings legacySettings: return await PackageExporterLegacy.ExportPackage(legacySettings); case DefaultExporterSettings defaultSettings: return PackageExporterDefault.ExportPackage(defaultSettings); default: return new ExportResult() { Success = false, Error = ASError.GetGenericError(new ArgumentException("Unrecognized ExportSettings type was provided")) }; } } private static bool IsSettingsValid(ExporterSettings settings, out Exception e) { e = null; if (settings == null) e = new ArgumentException("Package Exporting failed: ExporterSettings cannot be null"); else if (settings.ExportPaths == null || settings.ExportPaths.Length == 0) e = new ArgumentException("Package Exporting failed: received an invalid export paths array"); else if (string.IsNullOrEmpty(settings.OutputFilename)) e = new ArgumentException("Package Exporting failed: received an invalid output path"); else if (settings.OutputFilename.EndsWith("/") || settings.OutputFilename.EndsWith("\\")) e = new ArgumentException("Package Exporting failed: output path must be a valid filename and not end with a directory separator character"); return e == null; } protected string[] GetAssetPaths(string rootPath) { // To-do: slight optimization is possible in the future by having a list of excluded folders/file extensions List<string> paths = new List<string>(); // Add files within given directory var filePaths = Directory.GetFiles(rootPath).Select(p => p.Replace('\\', '/')).ToArray(); paths.AddRange(filePaths); // Add directories within given directory var directoryPaths = Directory.GetDirectories(rootPath).Select(p => p.Replace('\\', '/')).ToArray(); foreach (var nestedDirectory in directoryPaths) paths.AddRange(GetAssetPaths(nestedDirectory)); // Add the given directory itself if it is not empty if (filePaths.Length > 0 || directoryPaths.Length > 0) paths.Add(rootPath); return paths.ToArray(); } protected string GetAssetGuid(string assetPath, bool hiddenSearch) { // Skip meta files as they do not have guids if (assetPath.EndsWith(".meta")) return string.Empty; // Skip hidden assets. They normally do not have meta files, but // have been observed to retain them in the past due to a Unity bug if (assetPath.EndsWith("~")) return string.Empty; // Skip ProjectVersion.txt file specifically as it may introduce // project compatibility issues when imported if (string.Compare(assetPath, "ProjectSettings/ProjectVersion.txt", StringComparison.OrdinalIgnoreCase) == 0) return string.Empty; // Attempt retrieving guid from the Asset Database first var guid = AssetDatabase.AssetPathToGUID(assetPath); if (guid != string.Empty) return guid; // Files in hidden folders (e.g. Samples~) are not part of the Asset Database, // therefore GUIDs need to be scraped from the .meta file. // Note: only do this for custom exporter since the native exporter // will not be able to retrieve the asset path from a hidden folder if (hiddenSearch) { // To-do: handle hidden folders without meta files var metaPath = $"{assetPath}.meta"; if (!File.Exists(metaPath)) return string.Empty; using (StreamReader reader = new StreamReader(metaPath)) { string line; while ((line = reader.ReadLine()) != string.Empty) { if (!line.StartsWith("guid:")) continue; var metaGuid = line.Substring("guid:".Length).Trim(); return metaGuid; } } } return string.Empty; } protected virtual void PostExportCleanup() { EditorUtility.ClearProgressBar(); } } }
0
0.986694
1
0.986694
game-dev
MEDIA
0.605942
game-dev
0.979326
1
0.979326
GENIE-MC/Generator
2,009
src/Physics/Decay/Decayer.h
//____________________________________________________________________________ /*! \class genie::Decayer \brief Base class for decayer classes. Implements common configuration, allowing users to toggle on/off flags for particles and decay channels. Is a concerete implementation of the EventRecordVisitorI interface. \author Costas Andreopoulos <c.andreopoulos \at cern.ch> University of Liverpool \created November 14, 2018 \cpright Copyright (c) 2003-2025, The GENIE Collaboration For the full text of the license visit http://copyright.genie-mc.org */ //____________________________________________________________________________ #ifndef _DECAYER_H_ #define _DECAYER_H_ class TDecayChannel; #include "Framework/EventGen/EventRecordVisitorI.h" #include "Framework/ParticleData/PDGCodeList.h" #include "Framework/GHEP/GHepStatus.h" namespace genie { class GHepParticle; class Decayer : public EventRecordVisitorI { public: virtual ~Decayer(); // Overload the Algorithm::Configure() methods to load private data // members from configuration options void Configure(const Registry & config); void Configure(string config); protected: Decayer(); Decayer(string name); Decayer(string name, string config); virtual void LoadConfig (void); virtual bool ToBeDecayed (int pdgc, GHepStatus_t ist) const; virtual bool IsUnstable (int pdgc) const; virtual bool IsHandled (int pdgc) const = 0; virtual void InhibitDecay (int pdgc, TDecayChannel * dc=0) const = 0; virtual void UnInhibitDecay(int pdgc, TDecayChannel * dc=0) const = 0; bool fGenerateWeighted; ///< generate weighted or unweighted decays? bool fRunBefHadroTransp; ///< is invoked before or after FSI? PDGCodeList fParticlesToDecay; ///< list of particles to be decayed PDGCodeList fParticlesNotToDecay; ///< list of particles for which decay is inhibited }; } // genie namespace #endif // _DECAYER_H_
0
0.879726
1
0.879726
game-dev
MEDIA
0.89511
game-dev
0.618981
1
0.618981
Antarctics/noname
9,916
condition.md
# 4.5 技能条件 ## 1. 条件判断概述 技能条件判断主要包括: - [filter函数判断](#filter) - [check函数判断](#check) - [mod条件判断](#mod) - [特殊条件判断](#特殊) ## 2. Filter函数判断<a id="filter"></a> ### 2.1 基本用法 ```javascript "condition_skill": { trigger: {player: 'phaseBegin'}, filter(event, player){ // 基础条件 return player.hp < 3; // 体力值小于3 // 手牌条件 return player.countCards('hs').some(card=> card.name == "sha"); // 有【杀】 // 目标条件 return target.isDamaged(); // 目标已受伤 // 场上条件 return game.hasPlayer(function(current){ // 场上存在满足条件的角色 return current.hp < 2; }); } } ``` ### 2.2 复合条件 ```javascript filter(event, player){ // 多个条件同时满足 return player.hp < 3 && player.countCards('h') > 0 && !player.hasSkill('some_skill'); // 多个条件满足其一 return player.hp < 3 || player.countCards('h') == 0 || player.isDamaged(); } ``` ## 3. Check函数判断<a id="check"></a> ### 3.1 AI判断 ```javascript "check_skill": { enable: 'phaseUse', check(event, player){ // 基础判断 if(player.hp < 2) return 1; // 推荐发动 if(player.hp > 3) return 0; // 不推荐发动 // 形势判断 if(player.hasUnknown()) return 0; // 存在未知情况 if(game.hasPlayer(function(current){ return get.attitude(player,current) > 0 && current.hp == 1; })) return 2; // 队友濒死优先度高 } } ``` ### 3.2 选择判断 ```javascript "choice_skill": { chooseButton: { dialog(event, player){ return ui.create.dialog('选择一项', [ ['sha', 'tao'], 'vcard' ]); }, check(button){ // 按钮选择判断 if(button.link[2] == 'sha'){ if(_status.event.player.hp < 2) return 0; return 1; } return 2; // 桃的优先度最高 }, backup(links, player){ // 选择结果处理 } } } ``` ## 4. Mod条件判断<a id="mod"></a> ### 4.1 基本用法 ```javascript "mod_skill": { mod: { // 使用条件 cardEnabled(card, player){ if(player.hp < 2) return false; }, // 目标条件 targetEnabled(card, player, target){ if(target.hp < 2) return false; }, // 数值条件 cardUsable(card, player, num){ if(card.name == 'sha') return num + 1; } } } ``` ### 4.2 复杂条件 ```javascript "complex_mod": { mod: { // 多重条件判断 cardEnabled(card, player){ if(!player.countCards('h')) return false; if(player.hasSkill('some_skill')) return false; if(_status.currentPhase != player) return false; return true; }, // 动态数值判断 maxHandcard(player, num){ if(player.hp < 3) return num - 1; if(player.hasSkill('some_skill')) return num + 1; return num; } } } ``` ## 5. 特殊条件判断<a id="特殊"></a> ### 5.1 时机条件 ```javascript "timing_skill": { enable: 'phaseUse', filter(event, player){ // 判断当前时机 if(_status.currentPhase != player) return false; if(event.parent.name == 'phaseUse') return true; return false; } } ``` ### 5.2 状态条件 ```javascript "state_skill": { trigger: {player: 'damageEnd'}, filter(event, player){ // 判断角色状态 if(player.isTurnedOver()) return false; if(player.isLinked()) return false; if(!player.isAlive()) return false; return true; } } ``` ## 6. 进阶技巧 ### 6.1 条件缓存 ```javascript "cache_skill": { trigger: {player: 'phaseBegin'}, filter(event, player){ // 缓存复杂计算结果 if(player.storage.cache_result === undefined){ player.storage.cache_result = game.countPlayer(function(current){ return current.hp < 2; }); } return player.storage.cache_result > 0; }, content(){ // 使用后清除缓存 delete player.storage.cache_result; } } ``` ### 6.2 动态条件 ```javascript "dynamic_skill": { mod: { cardEnabled(card, player){ // 根据场上形势动态判断 var enemies = game.countPlayer(function(current){ return get.attitude(player, current) < 0; }); if(enemies > 2) return false; return true; } } } ``` ## 7. 注意事项 1. **性能优化** - 避免复杂循环 - 合理使用缓存 - 减少不必要判断 2. **条件设计** - 条件要明确 - 避免矛盾条件 - 考虑边界情况 ## 练习 1. 创建一个多重条件技能: - 包含体力值判断 - 包含手牌数判断 - 包含目标状态判断 <details> <summary>参考答案 | 🟩 Easy</summary> ```javascript "multi_condition": { enable: "phaseUse", filter(event, player){ // 基础条件:体力值小于3且有手牌 if(player.hp >= 3 || !player.countCards('h')) return false; // 场上条件:存在受伤角色 return game.hasPlayer(function(current){ return current.isDamaged(); }); }, filterTarget(card, player, target){ // 目标条件 return target.isDamaged() && // 目标已受伤 target.countCards('h') < target.hp && // 手牌数小于体力值 !target.hasSkill('multi_condition_effect'); // 没有临时效果 }, async content(event, trigger, player){ // 根据条件给予不同效果 if(target.hp <= 2){ await target.recover(); } else { await target.draw(2); } target.addTempSkill('multi_condition_effect'); }, ai: { order: 7, result: { target(player, target){ if(target.hp <= 2) return 2; return 1; } } } } ``` </details> 2. 创建一个动态条件技能: - 根据场上形势变化 - 包含AI判断 - 实现条件缓存 <details> <summary>参考答案 | 🟥 Hard</summary> ```javascript "dynamic_condition": { // 缓存机制 init(player){ player.storage.dynamic_condition = { situation: null, lastUpdate: 0 }; }, // 场势评估(自建函数) getSituation(player){ let situation = 0; // 计算我方状态 situation += player.hp; situation += player.countCards('h'); // 计算敌方状态 game.countPlayer(function(current){ if(get.attitude(player, current) < 0){ situation -= current.hp; situation -= current.countCards('h'); } }); return situation }, enable: "phaseUse", filter(event, player){ // 动态条件判断 let situation = lib.skill.dynamic_condition.getSituation(player); if(situation > 0){ // 优势时需要有手牌 return player.countCards('h') > 0; } else { // 劣势时需要体力值大于1 return player.hp > 1; } }, async content(event, trigger, player){ let situation = lib.skill.dynamic_condition.getSituation(player); if(situation > 0){ // 优势时进攻 let target = await player.chooseTarget('选择一名目标角色').forResult(); if(target.bool){ await target.targets[0].damage(); } } else { // 劣势时防守 await player.draw(2); } }, ai: { order(item, player){ let situation = lib.skill.dynamic_condition.getSituation(player); if(situation > 0) return 8; return 4; }, result: { player(player){ let situation = lib.skill.dynamic_condition.getSituation(player); if(situation > 0) return 1; return 2; } } } } ``` </details> 3. 创建一个复杂mod技能: - 修改多个游戏数值 - 包含多重条件判断 - 实现动态修改 <details> <summary>参考答案 | 🟥 Hard</summary> ```javascript "complex_mod": { // 初始化 init(player){ player.storage.complex_mod = { attackRange: 0, maxHandcard: 0, cardUsable: 0 }; }, // 更新数值(自建函数) updateMod(player){ let storage = player.storage.complex_mod; // 根据体力值修改攻击距离 storage.attackRange = Math.max(0, 3 - player.hp); // 根据手牌数修改手牌上限 storage.maxHandcard = Math.floor(player.countCards('h') / 2); // 根据装备数修改出牌次数 storage.cardUsable = player.countCards('e'); }, // 触发更新 trigger: { player: ["changeHp", "gainAfter", "loseAfter", "equipAfter"] }, forced: true, popup: false, filter(event, player){ return true; }, content(){ lib.skill.complex_mod.updateMod(player); }, // 数值修改 mod: { attackRange(player, num){ return num + player.storage.complex_mod.attackRange; }, maxHandcard(player, num){ return num + player.storage.complex_mod.maxHandcard; }, cardUsable(card, player, num){ if(card.name == 'sha'){ return num + player.storage.complex_mod.cardUsable; } }, globalTo(from, to, distance){ // 特殊条件:被翻面时防御距离+1 if(to.isTurnedOver()) return distance + 1; }, targetEnabled(card, player, target){ // 特殊条件:目标体力值大于自己时不能指定 if(target.hp > player.hp && get.tag(card, 'damage')){ return false; } }, ignoredHandcard(card, player){ // 特殊条件:红色手牌不计入手牌上限 if(get.color(card) == 'red'){ return true; } } }, // 显示提示 mark: true, intro: { content(storage, player){ lib.skill.complex_mod.updateMod(player); let str = '当前效果:n'; str += '攻击距离+' + storage.attackRange + 'n'; str += '手牌上限+' + storage.maxHandcard + 'n'; str += '出杀次数+' + storage.cardUsable; return str; } } } ``` </details> </br> 下一节我们将学习技能动画效果。
0
0.859492
1
0.859492
game-dev
MEDIA
0.994263
game-dev
0.673697
1
0.673697
glKarin/com.n0n3m4.diii4a
5,707
Q3E/src/main/jni/source/tier1/kvpacker.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Contains a branch-neutral binary packer for KeyValues trees. // // $NoKeywords: $ // //=============================================================================// #include <KeyValues.h> #include "kvpacker.h" #include "tier0/dbg.h" #include "utlbuffer.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> #define KEYVALUES_TOKEN_SIZE 1024 // writes KeyValue as binary data to buffer bool KVPacker::WriteAsBinary( KeyValues *pNode, CUtlBuffer &buffer ) { if ( buffer.IsText() ) // must be a binary buffer return false; if ( !buffer.IsValid() ) // must be valid, no overflows etc return false; // Write subkeys: // loop through all our peers for ( KeyValues *dat = pNode; dat != NULL; dat = dat->GetNextKey() ) { // write type switch ( dat->GetDataType() ) { case KeyValues::TYPE_NONE: { buffer.PutUnsignedChar( PACKTYPE_NONE ); break; } case KeyValues::TYPE_STRING: { buffer.PutUnsignedChar( PACKTYPE_STRING ); break; } case KeyValues::TYPE_WSTRING: { buffer.PutUnsignedChar( PACKTYPE_WSTRING ); break; } case KeyValues::TYPE_INT: { buffer.PutUnsignedChar( PACKTYPE_INT ); break; } case KeyValues::TYPE_UINT64: { buffer.PutUnsignedChar( PACKTYPE_UINT64 ); break; } case KeyValues::TYPE_FLOAT: { buffer.PutUnsignedChar( PACKTYPE_FLOAT ); break; } case KeyValues::TYPE_COLOR: { buffer.PutUnsignedChar( PACKTYPE_COLOR ); break; } case KeyValues::TYPE_PTR: { buffer.PutUnsignedChar( PACKTYPE_PTR ); break; } default: break; } // write name buffer.PutString( dat->GetName() ); // write value switch ( dat->GetDataType() ) { case KeyValues::TYPE_NONE: { if( !WriteAsBinary( dat->GetFirstSubKey(), buffer ) ) return false; break; } case KeyValues::TYPE_STRING: { if (dat->GetString() && *(dat->GetString())) { buffer.PutString( dat->GetString() ); } else { buffer.PutString( "" ); } break; } case KeyValues::TYPE_WSTRING: { int nLength = dat->GetWString() ? Q_wcslen( dat->GetWString() ) : 0; buffer.PutShort( nLength ); for( int k = 0; k < nLength; ++ k ) { buffer.PutShort( ( unsigned short ) dat->GetWString()[k] ); } break; } case KeyValues::TYPE_INT: { buffer.PutInt( dat->GetInt() ); break; } case KeyValues::TYPE_UINT64: { buffer.PutInt64( dat->GetUint64() ); break; } case KeyValues::TYPE_FLOAT: { buffer.PutFloat( dat->GetFloat() ); break; } case KeyValues::TYPE_COLOR: { Color color = dat->GetColor(); buffer.PutUnsignedChar( color[0] ); buffer.PutUnsignedChar( color[1] ); buffer.PutUnsignedChar( color[2] ); buffer.PutUnsignedChar( color[3] ); break; } case KeyValues::TYPE_PTR: { buffer.PutUnsignedInt( (uintptr_t)dat->GetPtr() ); break; } default: break; } } // write tail, marks end of peers buffer.PutUnsignedChar( PACKTYPE_NULLMARKER ); return buffer.IsValid(); } // read KeyValues from binary buffer, returns true if parsing was successful bool KVPacker::ReadAsBinary( KeyValues *pNode, CUtlBuffer &buffer ) { if ( buffer.IsText() ) // must be a binary buffer return false; if ( !buffer.IsValid() ) // must be valid, no overflows etc return false; pNode->Clear(); char token[KEYVALUES_TOKEN_SIZE]; KeyValues *dat = pNode; EPackType ePackType = (EPackType)buffer.GetUnsignedChar(); // loop through all our peers while ( true ) { if ( ePackType == PACKTYPE_NULLMARKER ) break; // no more peers buffer.GetString( token ); token[KEYVALUES_TOKEN_SIZE-1] = 0; dat->SetName( token ); switch ( ePackType ) { case PACKTYPE_NONE: { KeyValues *pNewNode = new KeyValues(""); dat->AddSubKey( pNewNode ); if( !ReadAsBinary( pNewNode, buffer ) ) return false; break; } case PACKTYPE_STRING: { buffer.GetString( token ); token[KEYVALUES_TOKEN_SIZE-1] = 0; dat->SetStringValue( token ); break; } case PACKTYPE_WSTRING: { int nLength = buffer.GetShort(); if ( nLength >= 0 && nLength*sizeof( uint16 ) <= (uint)buffer.GetBytesRemaining() ) { if ( nLength > 0 ) { wchar_t *pTemp = (wchar_t *)malloc( sizeof( wchar_t ) * (1 + nLength) ); for ( int k = 0; k < nLength; ++k ) { pTemp[k] = buffer.GetShort(); // ugly, but preserving existing behavior } pTemp[nLength] = 0; dat->SetWString( NULL, pTemp ); free( pTemp ); } else dat->SetWString( NULL, L"" ); } break; } case PACKTYPE_INT: { dat->SetInt( NULL, buffer.GetInt() ); break; } case PACKTYPE_UINT64: { dat->SetUint64( NULL, (uint64)buffer.GetInt64() ); break; } case PACKTYPE_FLOAT: { dat->SetFloat( NULL, buffer.GetFloat() ); break; } case PACKTYPE_COLOR: { Color color( buffer.GetUnsignedChar(), buffer.GetUnsignedChar(), buffer.GetUnsignedChar(), buffer.GetUnsignedChar() ); dat->SetColor( NULL, color ); break; } case PACKTYPE_PTR: { dat->SetPtr( NULL, buffer.GetPtr() ); break; } default: break; } if ( !buffer.IsValid() ) // error occured return false; ePackType = (EPackType)buffer.GetUnsignedChar(); if ( ePackType == PACKTYPE_NULLMARKER ) break; // new peer follows KeyValues *pNewPeer = new KeyValues(""); dat->SetNextKey( pNewPeer ); dat = pNewPeer; } return buffer.IsValid(); }
0
0.935014
1
0.935014
game-dev
MEDIA
0.131661
game-dev
0.98753
1
0.98753
SkyFireArchives/SkyFireEMU_420
4,659
src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> * * 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 "ScriptPCH.h" #include "utgarde_keep.h" uint32 entry_search[3] = { 186609, 186610, 186611 }; class npc_dragonflayer_forge_master : public CreatureScript { public: npc_dragonflayer_forge_master() : CreatureScript("npc_dragonflayer_forge_master") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_dragonflayer_forge_masterAI(pCreature); } struct npc_dragonflayer_forge_masterAI : public ScriptedAI { npc_dragonflayer_forge_masterAI(Creature *c) : ScriptedAI(c) { pInstance = c->GetInstanceScript(); fm_Type = 0; } InstanceScript* pInstance; uint8 fm_Type; void Reset() { if (fm_Type == 0) fm_Type = GetForgeMasterType(); CheckForge(); } void CheckForge() { if (pInstance) { switch(fm_Type) { case 1: pInstance->SetData(EVENT_FORGE_1, me->isAlive() ? NOT_STARTED : DONE); break; case 2: pInstance->SetData(EVENT_FORGE_2, me->isAlive() ? NOT_STARTED : DONE); break; case 3: pInstance->SetData(EVENT_FORGE_3, me->isAlive() ? NOT_STARTED : DONE); break; } } } void JustDied(Unit * /*killer*/) { if (fm_Type == 0) fm_Type = GetForgeMasterType(); if (pInstance) { switch(fm_Type) { case 1: pInstance->SetData(EVENT_FORGE_1, DONE); break; case 2: pInstance->SetData(EVENT_FORGE_2, DONE); break; case 3: pInstance->SetData(EVENT_FORGE_3, DONE); break; } } } void EnterCombat(Unit * /*who*/) { if (fm_Type == 0) fm_Type = GetForgeMasterType(); if (pInstance) { switch(fm_Type) { case 1: pInstance->SetData(EVENT_FORGE_1, IN_PROGRESS); break; case 2: pInstance->SetData(EVENT_FORGE_2, IN_PROGRESS); break; case 3: pInstance->SetData(EVENT_FORGE_3, IN_PROGRESS); break; } } me->SetUInt32Value(UNIT_NPC_EMOTESTATE , EMOTE_ONESHOT_NONE); } uint8 GetForgeMasterType() { float diff = 30.0f; int near_f = 0; for (uint8 i = 0; i < 3 ; ++i) { GameObject* temp; temp = me->FindNearestGameObject(entry_search[i], 30); if (temp) { if (me->IsWithinDist(temp, diff, false)) { near_f = i + 1; diff = me->GetDistance2d(temp); } } } switch (near_f) { case 1: return 1; case 2: return 2; case 3: return 3; default: return 0; } } void UpdateAI(const uint32 /*diff*/) { if (fm_Type == 0) fm_Type = GetForgeMasterType(); if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; }; void AddSC_utgarde_keep() { new npc_dragonflayer_forge_master(); }
0
0.987571
1
0.987571
game-dev
MEDIA
0.976016
game-dev
0.993371
1
0.993371
DaFuqs/Spectrum
1,330
src/main/java/de/dafuqs/spectrum/blocks/decoration/TransientLightBlock.java
package de.dafuqs.spectrum.blocks.decoration; import com.mojang.serialization.*; import net.minecraft.core.*; import net.minecraft.server.level.*; import net.minecraft.util.*; import net.minecraft.world.item.*; import net.minecraft.world.level.*; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.*; public class TransientLightBlock extends PersistentLightBlock { public static final MapCodec<TransientLightBlock> CODEC = simpleCodec(TransientLightBlock::new); public TransientLightBlock(Properties settings) { super(settings); } // @Override // public MapCodec<? extends DecayingLightBlock> getCodec() { // //TODO: Make the codec // return CODEC; // } @Override public ItemStack getCloneItemStack(LevelReader world, BlockPos pos, BlockState state) { return ItemStack.EMPTY; } @Override public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { super.randomTick(state, world, pos, random); int light = state.getValue(LightBlock.LEVEL); if (light < 2) { if (state.getValue(WATERLOGGED)) { world.setBlock(pos, Blocks.WATER.defaultBlockState(), 3); } else { world.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); } } else { world.setBlock(pos, state.setValue(LightBlock.LEVEL, light - 1), 3); } } }
0
0.614075
1
0.614075
game-dev
MEDIA
0.998411
game-dev
0.593575
1
0.593575
Knowledgator/GLiNER.cpp
4,298
src/tokenizer_utils.cpp
#define PCRE2_CODE_UNIT_WIDTH 8 #include <pcre2.h> #include <fstream> #include <iostream> #include <memory> #include "GLiNER/tokenizer_utils.hpp" namespace gliner { // RAII wrapper for PCRE2 resources class PCRE2Resource { private: pcre2_code *pattern_; pcre2_match_data *match_data_; public: PCRE2Resource() : pattern_(nullptr), match_data_(nullptr) {} ~PCRE2Resource() { if (match_data_) pcre2_match_data_free(match_data_); if (pattern_) pcre2_code_free(pattern_); } // Prevent copying PCRE2Resource(const PCRE2Resource &) = delete; PCRE2Resource &operator=(const PCRE2Resource &) = delete; void compilePattern(const char *pattern) { int errorcode; PCRE2_SIZE erroroffset; pattern_ = pcre2_compile( reinterpret_cast<PCRE2_SPTR>(pattern), PCRE2_ZERO_TERMINATED, PCRE2_UTF | PCRE2_UCP, &errorcode, &erroroffset, nullptr); if (!pattern_) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(errorcode, buffer, sizeof(buffer)); throw std::runtime_error("PCRE2 compilation failed at offset " + std::to_string(erroroffset) + ": " + reinterpret_cast<char *>(buffer)); } // Enable JIT compilation for better performance pcre2_jit_compile(pattern_, PCRE2_JIT_COMPLETE); match_data_ = pcre2_match_data_create_from_pattern(pattern_, nullptr); if (!match_data_) { throw std::runtime_error("Failed to create PCRE2 match data"); } } pcre2_code *pattern() const { return pattern_; } pcre2_match_data *match_data() const { return match_data_; } PCRE2_SIZE *getOvectorPointer() const { return pcre2_get_ovector_pointer(match_data_); } }; struct WhitespaceTokenSplitter::Implementation { PCRE2Resource pcre2; }; std::string LoadBytesFromFile(const std::string &path) { std::ifstream fs(path, std::ios::in | std::ios::binary); if (!fs) { throw std::runtime_error("Cannot open file: " + path); } // More efficient file reading using a single allocation fs.seekg(0, std::ios::end); std::string data; data.reserve(fs.tellg()); fs.seekg(0, std::ios::beg); data.assign( std::istreambuf_iterator<char>(fs), std::istreambuf_iterator<char>()); return data; } WhitespaceTokenSplitter::WhitespaceTokenSplitter() : pimpl(std::make_unique<Implementation>()) { pimpl->pcre2.compilePattern("\\w+(?:[-_]\\w+)*|\\S"); } WhitespaceTokenSplitter::~WhitespaceTokenSplitter() = default; std::vector<Token> WhitespaceTokenSplitter::call(const std::string &text) { std::vector<Token> tokens; tokens.reserve(text.length() / 4); // Estimate initial capacity PCRE2_SIZE *ovector = pimpl->pcre2.getOvectorPointer(); const size_t subject_length = text.length(); size_t start_offset = 0; while (true) { int rc = pcre2_match( pimpl->pcre2.pattern(), reinterpret_cast<PCRE2_SPTR>(text.c_str()), subject_length, start_offset, PCRE2_NO_UTF_CHECK, pimpl->pcre2.match_data(), nullptr); if (rc < 0) { if (rc != PCRE2_ERROR_NOMATCH) { throw std::runtime_error("PCRE2 matching error: " + std::to_string(rc)); } break; } const size_t start = ovector[0]; const size_t end = ovector[1]; tokens.push_back({start, end, text.substr(start, end - start)}); start_offset = end; } return tokens; } }
0
0.938371
1
0.938371
game-dev
MEDIA
0.165506
game-dev
0.937645
1
0.937645
i-net-software/JWebAssembly
26,956
test/de/inetsoftware/jwebassembly/runtime/ControlFlowOperators.java
/* * Copyright 2018 - 2022 Volker Berlin (i-net software) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.inetsoftware.jwebassembly.runtime; import java.util.ArrayList; import java.util.Collection; import org.junit.ClassRule; import org.junit.runners.Parameterized.Parameters; import de.inetsoftware.jwebassembly.ScriptEngine; import de.inetsoftware.jwebassembly.WasmRule; import de.inetsoftware.jwebassembly.api.annotation.Export; @SuppressWarnings( { "javadoc", "null", "rawtypes", "cast", "boxing", "unused" } ) public class ControlFlowOperators extends AbstractBaseTest { @ClassRule public static WasmRule rule = new WasmRule( TestClass.class ); public ControlFlowOperators( ScriptEngine script, String method, Object[] params ) { super( rule, script, method, params ); } @Parameters( name = "{0}-{1}" ) public static Collection<Object[]> data() { ArrayList<Object[]> list = new ArrayList<>(); for( ScriptEngine script : ScriptEngine.testEngines() ) { addParam( list, script, "ifeq" ); addParam( list, script, "ifne" ); addParam( list, script, "iflt" ); addParam( list, script, "ifMultiple" ); addParam( list, script, "ifMultipleDouble" ); addParam( list, script, "ifCompare" ); addParam( list, script, "switchDirect" ); addParam( list, script, "switchWithConditionMethodParams" ); addParam( list, script, "switchWithConditionSelect" ); addParam( list, script, "endlessLoop" ); addParam( list, script, "doWhileLoop" ); addParam( list, script, "doWhileLoopTwoConditions" ); addParam( list, script, "doWhileLoopWithBreak" ); addParam( list, script, "whileLoop" ); addParam( list, script, "whileLoopWithContinue" ); addParam( list, script, "whileLoopInElse_3" ); addParam( list, script, "whileLoopInElse_13" ); addParam( list, script, "whileLoopInElseAfterReturn" ); addParam( list, script, "whileLoopAfterIfWithReturn" ); addParam( list, script, "whileLoopInsideLoop" ); addParam( list, script, "whileTrueInsideWhileTrue" ); addParam( list, script, "whileTrueContinueWithSwitch" ); addParam( list, script, "forLoop" ); addParam( list, script, "conditionalOperator" ); addParam( list, script, "conditionalOperator2" ); addParam( list, script, "conditionalOperatorConcated" ); addParam( list, script, "conditionalOperatorConcated2" ); addParam( list, script, "redifineVariable" ); addParam( list, script, "ifAnd_0" ); addParam( list, script, "ifAnd_3" ); addParam( list, script, "ifAnd_6" ); addParam( list, script, "if4And_6" ); addParam( list, script, "if4And_7" ); addParam( list, script, "ifOr0" ); addParam( list, script, "ifOr1" ); addParam( list, script, "ifOr3" ); addParam( list, script, "ifOr5" ); addParam( list, script, "ifOr7" ); addParam( list, script, "ifAndOr0" ); addParam( list, script, "ifAndOr2" ); addParam( list, script, "ifAndOr4" ); addParam( list, script, "ifAndOr6" ); addParam( list, script, "ifAndOr8" ); addParam( list, script, "ifAndOrComplex" ); addParam( list, script, "ifAndOrComplex2" ); addParam( list, script, "ifWithoutElseAndLoop" ); addParam( list, script, "ifOrWithMulti" ); addParam( list, script, "ifMultipleInsideThen" ); addParam( list, script, "ifWithConditionalInsideThen" ); addParam( list, script, "conditionalInsideIf_1" ); addParam( list, script, "conditionalInsideIf_2" ); addParam( list, script, "conditionalInsideIf_3" ); addParam( list, script, "conditionalInsideIf_4" ); addParam( list, script, "ifWithReturn8" ); addParam( list, script, "ifWithReturn17" ); addParam( list, script, "ifWithReturn21" ); addParam( list, script, "ifWithReturn27" ); addParam( list, script, "ifWithReturn28" ); addParam( list, script, "stringSwitchNormalFoo" ); addParam( list, script, "stringSwitchNormalBar" ); addParam( list, script, "stringSwitchNormalDefault" ); addParam( list, script, "stringSwitchReverseFoo" ); addParam( list, script, "stringSwitchReverseBar" ); addParam( list, script, "stringSwitchReverseDefault" ); addParam( list, script, "stringSwitchContinue1" ); addParam( list, script, "stringSwitchContinue2" ); addParam( list, script, "stringSwitchContinueDefault" ); } rule.setTestParameters( list ); return list; } static class TestClass { @Export static int ifeq() { int condition = 0; if( condition != 0 ) { return 13; } else { return 76; } } @Export static int ifne() { int condition = 3; if( condition == 0 ) { return 13; } else { return 76; } } @Export static int iflt() { int condition = 3; if( condition >= 0 ) { condition = 13; } else { condition = 76; } return condition; } @Export static int ifMultiple() { int condition = 3; if( condition <= 0 ) { if( condition < 0 ) { condition = 13; } } else { if( condition > 0 ) { condition++; } else { condition--; } } if( condition > 2 ) { condition++; } else { condition = 0; } if( condition >= 2 ) { condition++; } else { condition = 0; } if( condition <= 123 ) { condition++; } else { condition = 0; } if( condition < 123 ) { condition++; } else { condition = 0; } if( condition != 123 ) { condition++; } else { condition = 0; } return condition; } @Export static int ifMultipleDouble() { double condition = 3; if( condition <= 0 ) { if( condition < 0 ) { condition = 13; } } else { if( condition > 0 ) { condition++; } else { condition--; } } if( condition > 2 ) { condition *= 2; } else { condition = 0; } if( condition >= 2 ) { condition *= 2; } else { condition = 0; } if( condition <= 123 ) { condition *= 2; } else { condition = 0; } if( condition < 123 ) { condition *= 2; } else { condition = 0; } if( condition != 123 ) { condition *= 2; } else { condition = 0; } if( condition == 123 ) { condition = 0; } else { condition *= 2; } int x = (int)(25 / condition); // prevent 0 as value return (int)condition; } @Export static int ifCompare() { double condition = 3.0; int result; if( condition >= 3.5 ) { result = 13; } else { result = 76; } return result; } @Export static int switchDirect() { return tableSwitch(10) + (tableSwitch( 9 ) * 10) + (tableSwitch( -1 ) * 100) + (lookupSwitch(Integer.MAX_VALUE) * 1000) + (lookupSwitch(0) * 10000 ); } private static int tableSwitch( int a ) { int b; switch( 1 + a - 1 ){ case 8: case 9: b = 2; break; case 10: case 11: b = 1; break; default: b = 9; } return b; } private static int lookupSwitch( int a ) { int b; switch(a){ case 1: b = 1; break; case 1000: case 1001: if( a == 1000 ) { b = 2; break; } else { b = 0; } //$FALL-THROUGH$ case Integer.MAX_VALUE: b = 3; break; default: b = 9; } return b; } @Export public static int switchWithConditionMethodParams() { int last = 8; switch( last ) { case -2: last = -13; break; default: last = tableSwitch( (last == 0 ? 0 : last) ); break; } return last; } @Export private static int switchWithConditionSelect() { boolean cond = true; int c1 = 1; int c2 = 2; int b; switch( cond ? c1 : c2 ) { case 1: b = 17; switch( cond ? c1 : c2 ) { case 1: b = 13; break; case 2: b = 14; break; } break; case 2: case 1001: if( c1 == 1000 ) { b = 1000; break; } else { b = 1001; } //$FALL-THROUGH$ case Integer.MAX_VALUE: b = 3; break; default: b = 9; } return b; } @Export static int endlessLoop() { int a = 0; int b = 0; do { if( a < 10 ) { b++; } else { return a; } a++; } while( true ); } @Export static double doWhileLoop() { int a = 0; double d = 1.01; do { d *= 2; a++; } while( a < 10 ); return d; } @Export static int doWhileLoopTwoConditions() { int val = 42; int shift = 1; do { val >>>= shift; } while (val > 7 && shift > 0); return val; } @Export static double doWhileLoopWithBreak() { int a = 0; double d = 1.01; do { a++; if( a == 5 ) { break; } d *= 2; } while( a < 10 ); return a * d; } @Export static int whileLoop() { float a = 0; int b = 1; while( a < 10 ) { b *= 2; a++; } return b; } @Export public static int whileLoopWithContinue() { int i = 0; int value = 0; while( i < 16 ) { i++; if( i > 8 ) { continue; } value |= 1 << i; } return value; } private static int whileLoopInElse( int yIndex ) { int result = 0; if( yIndex == 3 ) { result = 42; } else { while( yIndex > 7 ) { result++; yIndex--; } } return result; } @Export public static int whileLoopInElse_3() { return whileLoopInElse( 3 ); } @Export public static int whileLoopInElse_13() { return whileLoopInElse( 13 ); } @Export public static int whileLoopInElseAfterReturn() { int yIndex = 13; int result = 0; if (yIndex == 3) { return 42; } else { while (yIndex > 7) { result++; yIndex--; } } return result; } @Export public static int whileLoopAfterIfWithReturn() { int yIndex = 13; int result = 0; if (yIndex < 3) { if( yIndex == 3 ) { return 42; } while (yIndex > 7) { result++; yIndex--; } } return result; } @Export public static int whileLoopInsideLoop() { int i = 15; MAIN: while( true ) { while( i >= 9 ) { i--; } int start = i; while( i > start ) { if( true ) { i--; continue MAIN; } } return start; } } @Export static int whileTrueInsideWhileTrue() { int sw = 1; while( true ) { if( sw != 1 ) { sw++; break; } sub: while( true ) { if( sw == 1 ) { sw = 2; break; } else { sw = 17; } } } return sw; } @Export static int whileTrueContinueWithSwitch() { int sw = 1; LOOP: while( true ) { switch(sw) { case 1: sw++; continue LOOP; case 5: return sw; default: sw++; } break; } return sw; } @Export static int forLoop() { int a = 0; for( int i = 0; i < 10; i++ ) { a += i; } return a; } @Export static int conditionalOperator () { int condition = 4; return condition >= 4 ? condition < 4 ? 1 : 2 : condition == 4 ? 3 : 4; } @Export static int conditionalOperator2() { int val = 42; int result = 3 + (val == 1 ? 1 : (val == 2 ? 2 : (val == 3 ? 3 : 4))); return result; } @Export static int conditionalOperatorConcated () { int a = 7; int b = 13; int c = 42; int result = (a < 0 ? false : a == c ) && (b < 0 ? false : b == c ) ? 3 : 4; return result; } @Export static int conditionalOperatorConcated2() { int a = 7; int b = 13; int c = 42; return (a < 0 ? a != b : a != c ) && (b < 0 ? false : b == c ) ? 17 : 18; } @Export static double redifineVariable() { int x = 42; if( x > 0 ) { double a = 1; double b = 2.5; return a + b; } else { int a = 1; int b = 3; return a + b; } } @Export static int ifAnd_0() { return ifAnd( 0 ); } @Export static int ifAnd_3() { return ifAnd( 3 ); } @Export static int ifAnd_6() { return ifAnd( 6 ); } private static int ifAnd( int condition ) { int result; if( condition > 0 && condition < 5 ) { result = 42; } else { result = 76; } return result; } @Export static int if4And_6() { return if4And( 6 ); } @Export static int if4And_7() { return if4And( 7 ); } private static int if4And( int condition ) { int result; if( condition > 1 && condition > 3 && condition > 5 && condition > 7 ) { result = 42; } else { result = 76; } return result; } @Export static int ifOr0() { return ifOr( 0 ); } @Export static int ifOr1() { return ifOr( 1 ); } @Export static int ifOr3() { return ifOr( 3 ); } @Export static int ifOr5() { return ifOr( 5 ); } @Export static int ifOr7() { return ifOr( 7 ); } private static int ifOr( int condition ) { int result; if( condition == 1 || condition == 3 || condition == 5 || condition == 7 ) { result = 42; } else { result = 76; } return result; } @Export static int ifAndOr0() { return ifAndOr( 0 ); } @Export static int ifAndOr2() { return ifAndOr( 2 ); } @Export static int ifAndOr4() { return ifAndOr( 4 ); } @Export static int ifAndOr6() { return ifAndOr( 6 ); } @Export static int ifAndOr8() { return ifAndOr( 8 ); } private static int ifAndOr( int condition ) { int result; if( (condition >= 1 && condition <= 3) || (condition >= 5 && condition <= 7) ) { result = 42; } else { result = 76; } return result; } @Export private static int ifAndOrComplex() { int b1 = 0; int b2 = 0; int result; if( (b1 == 0xf0 && (b2 < 0x90 || b2 > 0xbf)) || (b1 == 0xf4 && (b2 & 0xf0) != 0x80) || (b2 & 0xc0) != 0x80) { result = 13; } else { result = 42; } return result; } @Export private static int ifAndOrComplex2() { int result = ifAndOrComplex2Impl( false, false, false ); result = result * 10 + ifAndOrComplex2Impl( true, false, false ); result = result * 10 + ifAndOrComplex2Impl( true, true, false ); result = result * 10 + ifAndOrComplex2Impl( true, false, true ); return result; } private static int ifAndOrComplex2Impl( boolean a, boolean b, boolean c ) { int result = 13; if( a && (b || c)) { result = 42; } else { result = 17; } return result; } private static int ifWithoutElseAndLoop; @Export static int ifWithoutElseAndLoop() { int n = 1; // because some compiler (Eclipse) move the loop condition to the end of the loop. Then there can be an optimization that the if jump to the end of the loop. if( ifWithoutElseAndLoop != 1 ) { ifWithoutElseAndLoop = 1; } while( n < 10 ) { ifWithoutElseAndLoop *= n++; } return ifWithoutElseAndLoop; } @Export static int ifOrWithMulti() { int len = 4; // the GOTO before the ELSE is not related to the main IF condition if( (len == 4 || len == 9) ) { if( len == 9 ) { len = 13; } else { len = 42; } } return len; } @Export static int ifMultipleInsideThen() { int result = 0; if( (result == 7) || (result == 13) ) { // multiple IF inside the primary IF if( result == -1 ) { result = 1; } else { result = 2; } if( result > result ) { result = 3; } } else { result = 4; } return result; } @Export static int ifWithConditionalInsideThen() { int val = 42; int result = 0; if( val > 20 ) { if( val > 21 ) { result = val == 42 ? 4 : 5; } } else { result = 3; } return result + 13; } @Export static int conditionalInsideIf_1() { return conditionalInsideIf( null, null, null ); } @Export static int conditionalInsideIf_2() { return conditionalInsideIf( null, null, "foo" ); } @Export static int conditionalInsideIf_3() { return conditionalInsideIf( "foo", null, null ); } @Export static int conditionalInsideIf_4() { return conditionalInsideIf( null, "foo", null ); } static int conditionalInsideIf( Object a, Object b, Object c ) { if( (a == null ? b == null : a == b ) ) { return c == null ? 1 : 2; } else { return 3; } } @Export static int ifWithReturn8() { return ifWithReturn( 8, 0 ); } @Export static int ifWithReturn17() { return ifWithReturn( 8, 13 ); } @Export static int ifWithReturn21() { return ifWithReturn( 8, 5 ); } @Export static int ifWithReturn27() { return ifWithReturn( 0, 0 ); } @Export static int ifWithReturn28() { return ifWithReturn( 0, 1 ); } private static int ifWithReturn( int a, int b ) { if( a > 7 ) { if( b > 1 ) { if( b == 13 ) { return 17; } else { return 21; } } } else { if( a == b ) { return 27; } else { return 28; } } return a; } @Export static int stringSwitchNormalFoo() { return stringSwitchNormal( "foo" ); } @Export static int stringSwitchNormalBar() { return stringSwitchNormal( "bar" ); } @Export static int stringSwitchNormalDefault() { return stringSwitchNormal( "default" ); } private static int stringSwitchNormal( String tagName ) { switch( tagName ) { case "foo": return 1; case "bar": return 2; default: return 3; } } @Export static int stringSwitchReverseFoo() { return stringSwitchReverse( "foo" ); } @Export static int stringSwitchReverseBar() { return stringSwitchReverse( "bar" ); } @Export static int stringSwitchReverseDefault() { return stringSwitchReverse( "default" ); } private static int stringSwitchReverse( String tagName ) { switch( tagName ) { default: return 3; case "bar": return 2; case "foo": return 1; } } @Export static int stringSwitchContinue1() { return stringSwitchContinue( "1" ); } @Export static int stringSwitchContinue2() { return stringSwitchContinue( "2" ); } @Export static int stringSwitchContinueDefault() { return stringSwitchContinue( "8" ); } /** * Strings have continue hash codes that a compiler could use a tableswitch. */ private static int stringSwitchContinue( String tagName ) { switch( tagName ) { case "1": return 1; case "2": return 2; case "3": return 3; case "4": return 4; case "5": return 5; case "6": return 7; default: return 8; } } } }
0
0.802965
1
0.802965
game-dev
MEDIA
0.208888
game-dev
0.768601
1
0.768601
SabineWren/wow-api-type-definitions
15,016
Function/Unit.d.lua
---@meta --- Instructs your character to assist the specified unit. ---@param unit UnitId ---@return nil function AssistUnit(unit) end --- Drops an item from the cursor onto a unit. ---@param unit UnitId ---@return nil function DropItemOnUnit(unit) end --- Follow an ally with the specified UnitID ---@param unit UnitId ---@return nil function FollowUnit(unit) end --- Challenge a unit to a duel. ---@param unit UnitId ---@return nil function StartDuelUnit(unit) end --- Determine if the unit is in combat or has aggro. --- - Returns false if the unit being checked for aggro is out of range. --- - Returns false if a unit is proximity-aggroed. It wont return true until it either attacks or is attacked. --- - For hunters, returns true shortly after pet enters combat. ---@param unit UnitId ---@return nil|1 ---@nodiscard function UnitAffectingCombat(unit) end --- Returns the armor statistics relevant to the specified unit. ---@param unit UnitId ---@return number base Base armor without buffs, armor kits or enchantments. ---@return number effective Effective/total armor after modifiers. ---@return number armor Armor after adding armor kits and enchantments but without buffs. ---@return number bonus Amount of armor increase due to positive buffs. ---@return number malus Armor reduction due to negative buffs (a negative number). ---@nodiscard function UnitArmor(unit) end --- Returns information about the unit's melee attacks. ---@param unit UnitId ---@return number mainBase The unit's base main hand attack power. ---@return number mainMod Any modifier to the unit's main hand attack power. ---@return number offBase The unit's base offhand attack power (equal to unarmed weapon skill if unit doesn't dual wield). ---@return number offMod Any modifier to the unit's offhand attack power. ---@nodiscard function UnitAttackBothHands(unit) end --- Returns the unit's melee attack power and modifiers. ---@param unit UnitId ---@return number base The unit's base attack power. ---@return number bonus The total effect of positive buffs to attack power. ---@return number malus The total effect of negative buffs to the attack power (a negative number). ---@nodiscard function UnitAttackPower(unit) end --- Returns the unit's melee attack speed for each hand. ---@param unit UnitId ---@return number mainSpeed The unit's base main hand attack speed (seconds). ---@return nil|number offSpeed The unit's offhand attack speed (seconds) - nil if the unit has no offhand weapon. ---@nodiscard function UnitAttackSpeed(unit) end --- Returns true if the first unit can assist the second, false otherwise. ---@param unit UnitId ---@param otherUnit UnitId ---@return 1|nil ---@nodiscard function UnitCanAssist(unit, otherUnit) end --- Returns true if the first unit can attack the second, false otherwise. ---@param unit UnitId ---@param otherUnit UnitId ---@return 1|nil ---@nodiscard function UnitCanAttack(unit, otherUnit) end --- Returns true if the first unit can cooperate with the second, false otherwise. ---@param unit UnitId ---@param otherUnit UnitId ---@return 1|nil ---@nodiscard function UnitCanCooperate(unit, otherUnit) end --- Returns the number of unspent talent points for the specified unit -- usually 0. ---@param unit UnitId ---@return integer ---@nodiscard function UnitCharacterPoints(unit) end --- Defaults to WARRIOR if unit has no class ---@param unit UnitId ---@return string classLocalized ex. "Mage", "Warrior", "Guerrier" ---@return CharacterClass classEnglish ---@nodiscard function UnitClass(unit) end --- Returns the classification of the specified unit (ex. "elite" or "worldboss"). ---@param unit UnitId ---@return string ---@nodiscard function UnitClassification(unit) end --- Returns the type of creature of the specified unit (ex. "Crab"). --- - TODO this can probably return nil ---@param unit UnitId ---@return CreatureFamily ---@nodiscard function UnitCreatureFamily(unit) end --- Returns the classification type of creature of the specified unit (ex. "Beast"). ---@param unit UnitId ---@return CreatureType ---@nodiscard function UnitCreatureType(unit) end --- Returns the damage statistics relevant to the specified unit. ---@param unit UnitId ---@return number lowDmg The unit's minimum melee damage. ---@return number hiDmg The unit's maximum melee damage. ---@return number offlowDmg The unit's minimum offhand melee damage. ---@return number offhiDmg The unit's maximum offhand melee damage. ---@return number bonus Positive physical Bonus (should be >= 0). ---@return number malus Negative physical Bonus (should be <= 0). ---@return number percentmod Percentage modifier (usually 1). ---@nodiscard function UnitDamage(unit) end --- Returns the base defense skill of the specified unit. ---@param unit UnitId ---@return number baseDefense The unit's defense without armor. Includes the warrior talent Anticipation. ---@return number armorDefense The defense gained from the unit's armor. ---@nodiscard function UnitDefense(unit) end --- Returns true if the specified unit exists, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitExists(unit) end --- Returns the faction group id and name of the specified unit. ---@param unit UnitId ---@return nil|"Alliance"|"Horde"|"Neutral" factionEnglish ---@return nil|string factionLocalized ---@nodiscard function UnitFactionGroup(unit) end --- Returns the current health, in points, of the specified unit. ---@param unit UnitId ---@return integer ---@nodiscard function UnitHealth(unit) end --- Returns the maximum health, in points, of the specified unit. ---@param unit UnitId ---@return integer ---@nodiscard function UnitHealthMax(unit) end --- Returns true if the specified unit is charmed, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsCharmed(unit) end --- Returns true if the unit is a civilian NPC. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsCivilian(unit) end --- Returns 1 if the specified unit is connected or npc, nil if offline or not a valid unit. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsConnected(unit) end --- Returns true if the specified unit is a corpse, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsCorpse(unit) end --- Returns true if the specified unit is dead, nil otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsDead(unit) end --- Returns true if the specified unit is dead or a ghost, nil otherwise. --- - Returns true while Feign Death active. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsDeadOrGhost(unit) end --- Returns true if the specified units are enemies, false otherwise. ---@param unit UnitId ---@param otherUnit UnitId ---@return 1|nil ---@nodiscard function UnitIsEnemy(unit, otherUnit) end --- Returns true if the specified units are friends (PC of same faction or friendly NPC), false otherwise. ---@param unit UnitId ---@param otherUnit UnitId ---@return 1|nil ---@nodiscard function UnitIsFriend(unit, otherUnit) end --- Returns true if the specified unit is a ghost, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsGhost(unit) end --- Returns true if the specified unit is flagged for PVP, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsPVP(unit) end --- Returns true if the specified unit is flagged for free-for-all PVP, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsPVPFreeForAll(unit) end --- Returns true if the specified unit is a player character, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsPlayer(unit) end --- Returns true if the specified unit is a mob, more powerful than its nominal level, false otherwise (ex. "elite" mobs) ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsPlusMob(unit) end --- Returns true if the specified unit is tapped, false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsTapped(unit) end --- Returns true if the specified unit is tapped by the player himself, otherwise false. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsTappedByPlayer(unit) end --- Returns true if the specified unit is trivial (Trivial means the unit is "grey" to the player. false otherwise. ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsTrivial(unit) end --- Determine if two units are the same unit. ---@param unit UnitId ---@param otherUnit UnitId ---@return 1|nil ---@nodiscard function UnitIsUnit(unit, otherUnit) end ---1 if visible, nil if not ---@param unit UnitId ---@return 1|nil ---@nodiscard function UnitIsVisible(unit) end --- Returns the level of a unit. --- - Returns -1 if unknown or boss. --- - When inebriated, the apparent level of hostile units is lowered by up to 5. --- - When calling UnitLevel("player") on PLAYER_LEVEL_UP it might be incorrect; check the payload instead to be sure. ---@param unit UnitId ---@return integer ---@nodiscard function UnitLevel(unit) end --- Returns the current mana (or energy,rage,etc), in points, of the specified unit. --- - TODO what if the target has no mana bar? Is it 0? ---@param unit UnitId ---@return integer ---@nodiscard function UnitMana(unit) end --- Returns the maximum mana (or energy,rage,etc), in points, of the specified unit. --- - TODO what if the target has no mana bar? Is it 0? ---@param unit UnitId ---@return integer ---@nodiscard function UnitManaMax(unit) end --- Returns the name (and realm name) of a unit. ---@param unit UnitId ---@return nil|string name ---@return nil|string realm ---@nodiscard function UnitName(unit) end --- Returns 1 if unit is on a taxi. ---@param unit UnitId ---@return nil|1 ---@nodiscard function UnitOnTaxi(unit) end --- Returns true if the specified unit is controlled by a player, false otherwise. ---@param unit UnitId ---@return nil|1 ---@nodiscard function UnitPlayerControlled(unit) end --- Returns 1 if the specified unit/pet is a member of the player's party, nil otherwise (returns 1 for "player" and "pet"). ---@param unit UnitId ---@return nil|1 ---@nodiscard function UnitPlayerOrPetInParty(unit) end --- Returns 1 if the specified unit/pet is a member of the player's raid, nil otherwise (returns 1 for "player" and "pet"). ---@param unit UnitId ---@return nil|1 ---@nodiscard function UnitPlayerOrPetInRaid(unit) end --- Returns unit's name with PvP rank prefix (ex. "Corporal Allianceguy"). --- - nil if out of range ---@param unit UnitId ---@return nil|string ---@nodiscard function UnitPVPName(unit) end --- Get PvP rank information for requested unit. --- - Starts at 5, not 1. Returns 0 if no rank. ---@param unit UnitId ---@return 0|5|6|7|8|9|10|11|12|13|14|15|16|17|18 ---@nodiscard function UnitPVPRank(unit) end --- Returns a number corresponding to the power type (ex. mana, rage or energy) of the specified unit. --- - TODO what if no power type? Can this return nil? ---@param unit UnitId ---@return PowerType ---@nodiscard function UnitPowerType(unit) end --- Returns the race name of the specified unit (ex. "Human" or "Troll"). --- - TODO can this return nil? --- - "Undead" localized returns "Scourge" English ---@param unit UnitId ---@return string raceLocalized ---@return string raceEnglish ---@nodiscard function UnitRace(unit) end --- Returns the ranged attack number of the unit. ---@param unit UnitId ---@return number base 0 if no ranged weapon equipped. ---@return number modifier Total effect of all modifiers. ---@nodiscard function UnitRangedAttack(unit) end --- Returns the ranged attack power of the unit. ---@param unit UnitId ---@return number base The unit's base ranged attack power (seems to give a positive number even if no ranged weapon equipped). ---@return number bonus The total effect of positive buffs to ranged attack power.. ---@return number malus The total effect of negative buffs to the ranged attack power (a negative number). ---@nodiscard function UnitRangedAttackPower(unit) end --- Returns the ranged attack speed and damage of the unit. ---@param unit UnitId ---@return number speed The unit's ranged weapon speed (0 if no ranged weapon equipped). ---@return number lowDmg The unit's minimum ranged damage. ---@return number hiDmg The unit's maximum ranged damage. ---@return number bonus The unit's positive Bonus on ranged attacks (includes Spelldamage increases). ---@return number malus The unit's negative Bonus on ranged attacks. ---@return number percent percentage modifier (usually 1). ---@nodiscard function UnitRangedDamage(unit) end --- Returns a number corresponding to the reaction (aggressive, neutral or friendly) of the first unit towards the second unit. --- - Values other than 2, 4 or 5 are only returned when the first unit is an NPC in a reputation faction and the second is you or your pet. ---@param unit UnitId ---@param otherUnit UnitId ---@return Reputation reaction The level of the reaction of unit towards otherUnit - this is a number from 1 to 8. ---@nodiscard function UnitReaction(unit, otherUnit) end --- Returns the resistance statistics relevant to the specified unit and resistance type. ---@param unit UnitId ---@param index Resistance ---@return number base Base value excluding gear worn. ---@return number total ---@return number bonus Amount from positive gear and buffs. ---@return number malus Amount from negative gear and debuffs. ---@nodiscard function UnitResistance(unit, index) end --- Returns a code indicating the gender of the specified unit, if known. (1=unknown, 2=male, 3=female) ← changed in 1.11! ---@param unit UnitId ---@return Gender ---@nodiscard function UnitSex(unit) end --- Returns the statistics relevant to the specified unit and basic attribute (ex. strength or intellect). ---@param unit UnitId ---@param stat StatIndex ---@return number base The unit's base stat. ---@return number total The unit's current stat. ---@return number bonus Any positive buffs applied to the stat. ---@return number malus Any negative buffs applied to the stat. ---@nodiscard function UnitStat(unit, stat) end --- Returns the number of experience points the specified unit has in their current level. --- - TODO does this work on pets? ---@param unit "pet"|"player"-- &UnitId ---@return integer ---@nodiscard function UnitXP(unit) end --- Returns the number of experience points the specified unit needs to reach their next level. --- - TODO does this work on pets? ---@param unit "pet"|"player"-- &UnitId ---@return integer ---@nodiscard function UnitXPMax(unit) end --- Paint a Texture object with the specified unit's portrait. ---@param texture Texture ---@param unit UnitId ---@return nil function SetPortraitTexture(texture, unit) end --- Paint a Texture object with the given texture path. ---@param texture Texture ---@param path string ---@return nil function SetPortraitToTexture(texture, path) end
0
0.934986
1
0.934986
game-dev
MEDIA
0.513374
game-dev
0.625554
1
0.625554
dekrom/BepHaxAddon
4,929
src/main/java/bep/hax/mixin/InGameHudMixin.java
package bep.hax.mixin; import net.minecraft.text.Text; import bep.hax.modules.AntiToS; import bep.hax.modules.NoHurtCam; import net.minecraft.item.ItemStack; import net.minecraft.text.MutableText; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import net.minecraft.client.gui.DrawContext; import com.llamalad7.mixinextras.sugar.Local; import net.minecraft.client.gui.hud.InGameHud; import org.spongepowered.asm.mixin.injection.At; import com.llamalad7.mixinextras.sugar.ref.LocalRef; import org.spongepowered.asm.mixin.injection.Inject; import meteordevelopment.meteorclient.systems.modules.Modules; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import bep.hax.modules.ShulkerOverviewModule; import net.minecraft.block.ShulkerBoxBlock; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.RenderTickCounter; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.BlockItem; import net.minecraft.util.Arm; @Mixin(InGameHud.class) public class InGameHudMixin { @Shadow private ItemStack currentStack; // See AntiToS.java @Inject( method = "renderHeldItemTooltip", at = @At(value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;contains(Lnet/minecraft/component/ComponentType;)Z") ) private void censorItemTooltip(DrawContext context, CallbackInfo ci, @Local LocalRef<MutableText> itemName) { if (this.currentStack.isEmpty()) return; Modules modules = Modules.get(); if (modules == null) return; AntiToS antiToS = modules.get(AntiToS.class); if (!antiToS.isActive()) return; if (antiToS.containsBlacklistedText(itemName.get().getString())) { itemName.set(Text.empty().append(antiToS.censorText(itemName.get().getString())).formatted(this.currentStack.getRarity().getFormatting())); } } @Inject(method = "renderHotbar", at = @At("TAIL")) private void onRenderHotbar(DrawContext context, RenderTickCounter tickCounter, CallbackInfo ci) { ShulkerOverviewModule module = Modules.get().get(ShulkerOverviewModule.class); if (module == null || !module.isActive()) return; MinecraftClient mc = MinecraftClient.getInstance(); PlayerEntity player = mc.player; if (player == null) return; int scaledWidth = mc.getWindow().getScaledWidth(); int scaledHeight = mc.getWindow().getScaledHeight(); int center = scaledWidth / 2; // Hotbar slots 0-8 int hotbarY = scaledHeight - 19; for (int i = 0; i < 9; i++) { int posX = center - 90 + i * 20 + 2; ItemStack stack = player.getInventory().getStack(i); if (stack.isEmpty()) continue; if (!(stack.getItem() instanceof BlockItem blockItem) || !(blockItem.getBlock() instanceof ShulkerBoxBlock)) continue; module.renderShulkerOverlay(context, posX, hotbarY, stack); } // Offhand slot ItemStack offhandStack = player.getOffHandStack(); if (!offhandStack.isEmpty() && offhandStack.getItem() instanceof BlockItem blockItem && blockItem.getBlock() instanceof ShulkerBoxBlock) { // Offhand slot position calculation // The offhand slot appears at y = scaledHeight - 23 (3 pixels above hotbar) int offY = scaledHeight - 23; int offX; // The offhand slot is positioned differently based on main hand // Left-handed: offhand appears on the right side // Right-handed: offhand appears on the left side if (player.getMainArm() == Arm.LEFT) { // When left-handed, offhand slot is on the right side offX = center + 91 + 9; // Right side of hotbar + 9 pixel gap } else { // When right-handed, offhand slot is on the left side offX = center - 91 - 29; // Left side of hotbar - 29 pixels (slot width + gap) } // Add 3 pixels to x and y to account for the item position within the slot module.renderShulkerOverlay(context, offX + 3, offY + 3, offhandStack); } } @Inject(method = "renderOverlay", at = @At("HEAD"), cancellable = true) private void onRenderOverlay(DrawContext context, net.minecraft.util.Identifier texture, float opacity, CallbackInfo ci) { // This handles the red hurt overlay Modules modules = Modules.get(); if (modules == null) return; NoHurtCam noHurtCam = modules.get(NoHurtCam.class); if (noHurtCam != null && noHurtCam.shouldDisableRedOverlay()) { // Cancel the red overlay rendering when hurt MinecraftClient mc = MinecraftClient.getInstance(); if (mc.player != null && mc.player.hurtTime > 0) { ci.cancel(); } } } }
0
0.90471
1
0.90471
game-dev
MEDIA
0.977903
game-dev
0.868863
1
0.868863
MaxMraz/yarntown
6,851
data/scripts/fx/lighting_effects.lua
local lighting_effects = {} local effects = { torch = sol.sprite.create"entities/effects/light_l", candle = sol.sprite.create"entities/effects/light_s", explosion = sol.sprite.create"entities/effects/light_xl", hero_aura = sol.sprite.create"entities/effects/light_m", lantern = sol.sprite.create"entities/effects/light_l", } local shadow_surface local light_surface local darkness_color function lighting_effects:initialize() --scale effects to proper size: -- effects.hero_aura:set_scale(2, 2) -- effects.torch:set_scale(2, 2) -- effects.explosion:set_scale(1, 1) --add color to effects effects.torch:set_color_modulation{255, 230, 150} effects.candle:set_color_modulation{255, 230, 130} effects.hero_aura:set_color_modulation{255, 230, 180} effects.lantern:set_color_modulation{230, 210, 240} effects.explosion:set_color_modulation{255, 240, 180} --set blend modes for i=1, #effects do effects[i]:set_blend_mode"blend" end --create surfaces shadow_surface = sol.surface.create() shadow_surface:set_blend_mode"multiply" light_surface = sol.surface.create() light_surface:set_blend_mode"add" --set default darkness level darkness_color = {70,90,100} end function lighting_effects:set_darkness_level(level) if level == 1 then darkness_color = {150,180,200} elseif level == 2 then darkness_color = {100,115,135} elseif level == 3 then darkness_color = {75,85,90} elseif level == 4 then darkness_color = {20,40,55} elseif level == 5 then darkness_color = {5, 15, 25} elseif level == "dusk" then darkness_color = {240,229,210} elseif level == "night" then darkness_color = {100,115,135} else darkness_color = level end end function lighting_effects:fade_to_darkness_level(level) if lighting_effects.color_fade_timer then lighting_effects.color_fade_timer:stop() end if level == 1 then new_darkness_color = {150,180,200} elseif level == 2 then new_darkness_color = {100,115,135} elseif level == 3 then new_darkness_color = {75,85,90} elseif level == 4 then new_darkness_color = {20,40,55} elseif level == 5 then new_darkness_color = {5, 15, 25} elseif level == "dusk" then new_darkness_color = {240,229,210} elseif level == "night" then new_darkness_color = {100,115,135} else new_darkness_color = level end local r1, g1, b1 = darkness_color[1], darkness_color[2], darkness_color[3] local r2, g2, b2 = new_darkness_color[1], new_darkness_color[2], new_darkness_color[3] lighting_effects.color_fade_timer = sol.timer.start(sol.main.get_game(), 10, function() local r_step = 1 local g_step = 1 local b_step = 1 if math.abs(r1-r2) > 10 then r_step = 5 end if math.abs(g1-g2) > 10 then g_step = 5 end if math.abs(b1-b2) > 10 then b_step = 5 end if r1 > r2 then r_step = r_step * -1 elseif r1 == r2 then r_step = 0 end if r1 > r2 then g_step = g_step * -1 elseif g1 == g2 then g_step = 0 end if r1 > r2 then b_step = b_step * -1 elseif b1 == b2 then b_step = 0 end r1 = r1 + r_step g1 = g1 + g_step b1 = b1 + b_step darkness_color = {r1, g1, b1} if r1 == r2 and g1 == g2 and b1 == b2 then else return true end end) end --name for specific entities: --^lighting_effect_torch --^lighting_effect_candle function lighting_effects:on_draw(dst_surface) local game = sol.main.get_game() local map = game:get_map() local hero = map:get_hero() local cam_x, cam_y = map:get_camera():get_position() local hx, hy, hz = hero:get_position() --clear the surfaces light_surface:clear() shadow_surface:clear() --color surfaces shadow_surface:fill_color(darkness_color) --=========================================================================================-- --draw different light effects --hero aura: if hero.torch then effects.hero_aura:draw(light_surface, hx - cam_x, hy - cam_y) end --torches: for e in map:get_entities("^lighting_effect_torch") do if e:is_enabled() and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.torch:draw(light_surface, x - cam_x, y - cam_y) end end --candles: for e in map:get_entities("^lighting_effect_candle") do if e:is_enabled() and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.candle:draw(light_surface, x - cam_x, y - cam_y) end end --Lanterns for e in map:get_entities_by_type("custom_entity") do if e:is_enabled() and e:get_model() == "lantern" and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.lantern:draw(light_surface, x - cam_x, y - cam_y) end end --explosions for e in map:get_entities_by_type("explosion") do if e:is_enabled() and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.explosion:draw(light_surface, x - cam_x, y - cam_y) end end --fire for e in map:get_entities_by_type("fire") do if e:is_enabled() and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.torch:draw(light_surface, x - cam_x, y - cam_y) end end for e in map:get_entities_by_type("custom_entity") do if e:get_model() == "fire" and e:is_enabled() and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.torch:draw(light_surface, x - cam_x, y - cam_y) end end --fire arrows for e in map:get_entities_by_type("custom_entity") do if e:is_enabled() and e:get_model() == "arrow_fire" and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.candle:draw(light_surface, x - cam_x, y - cam_y) end end --iron candles for e in map:get_entities_by_type("custom_entity") do if e:is_enabled() and e:get_name() == "iron_candle_entity" and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.candle:draw(light_surface, x - cam_x, y - cam_y) end end --lightning for e in map:get_entities_by_type("custom_entity") do if e:is_enabled() and e:get_name() == "lightning_attack" and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() effects.torch:draw(light_surface, x - cam_x, y - cam_y) end end --enemies for e in map:get_entities_by_type("enemy") do if e:is_enabled() and e.lighting_effect and e:get_distance(hero) <= 450 then local x,y = e:get_center_position() if e.lighting_effect == 1 then effects.candle:draw(light_surface, x - cam_x, y - cam_y) end if e.lighting_effect == 2 then effects.torch:draw(light_surface, x - cam_x, y - cam_y) end end end light_surface:draw(shadow_surface) shadow_surface:draw(dst_surface) end return lighting_effects
0
0.983185
1
0.983185
game-dev
MEDIA
0.872911
game-dev
0.926344
1
0.926344
jazzyjester/Mario-Game
6,269
MarioObjects/Objects/GameObjects/FireBall.cs
using System; using System.Collections.Generic; using System.Text; using MarioObjects.Objects.BaseObjects; using MarioObjects.Objects.Utils; namespace MarioObjects.Objects.GameObjects { public class FireBall : AnimatedGraphicObject { public enum FireBallType { FT_Mario, FT_Piranah }; public enum FireBallDir { FB_Right, FB_Left }; public double StartVelocity; public double StartPosition; public double TimeCount; public FireBallDir Direction; public int Dirx; public Boolean Started; public FireBallType Type; public Boolean Fire; public double OffX, OffY; public double CntX, CntY; public override void Intersection(Collision c, GraphicObject g) { base.Intersection(c, g); switch (g.OT) { case ObjectType.OT_SolidBlock: goto case ObjectType.OT_PipeUp; case ObjectType.OT_BlockQuestion: goto case ObjectType.OT_Grass; case ObjectType.OT_Brick: goto case ObjectType.OT_Grass; case ObjectType.OT_Grass: { StartFireBall(); break; } case ObjectType.OT_PipeUp: { Started = false; Visible = false; break; } case ObjectType.OT_Goomba: { if (Type == FireBallType.FT_Mario) { ((MonsterGoomba)g).GoombaFallDie(); Started = false; Visible = false; } break; } case ObjectType.OT_Koopa: { if (Type == FireBallType.FT_Mario) { ((MonsterKoopa)g).SetKoopaState(MonsterKoopa.KoopaState.KS_Shield); Started = false; Visible = false; } break; } case ObjectType.OT_Pirana: { if (Type == FireBallType.FT_Mario && ((MonsterPiranah)g).Move != MonsterPiranah.PiranaMove.PM_None) // Only kill pirana if it's out of its pipe { ((MonsterPiranah)g).Visible = false; ((MonsterPiranah)g).Live = false; } break; } // Handle fireball hitting Mario case ObjectType.OT_Mario: { if (Type != FireBallType.FT_Mario) // Make sure it isn't Mario's fireball { Mario m = (Mario)g; if (!m.Blinking) { m.MarioHandleCollision(); } } break; } } } public void RunFireBall(int x, int y, FireBallType T, FireBallDir D) { Type = T; Direction = D; if (Type == FireBallType.FT_Mario) { if (D == FireBallDir.FB_Right) Dirx = 1; else Dirx = -1; } if (Type == FireBallType.FT_Piranah) { } SetFireProperties(); newx = x; newy = y; StartFireBall(); } public void StartFireBall() { Fire = true; Visible = true; StartPosition = newy; if (Started == false) StartVelocity = 0; else StartVelocity = -15; Started = true; TimeCount = 0; } public double CalcFireBallPosition() { return StartPosition + StartVelocity * TimeCount + 4.9 * TimeCount * TimeCount; } public override void Draw() { base.Draw(); } public override void OnAnimate(object sender, EventArgs e) { base.OnAnimate(sender, e); } public void SetOffXY(double x, double y) { OffX = x; OffY = y; CntX = 0; CntY = 0; } public void OnFire(object sender, EventArgs e) { if (Started) { if (Fire) { if (Type == FireBallType.FT_Mario) { TimeCount += (250.0 / 1000.0); newy = (int)CalcFireBallPosition(); newx += 5 * Dirx; } if (Type == FireBallType.FT_Piranah) { //CntX += OffX; //CntY += OffY; newx += (int)OffX; newy += (int)OffY; } if (newy < 0) Started = false; if (newx >= LevelGenerator.CurrentLevel.MarioObject.x + 320) { Started = false; Visible = false; } if (newx < LevelGenerator.CurrentLevel.MarioObject.x - 320) { Started = false; Visible = false; } } } } public void SetFireProperties() { this.x = x; this.y = y; SetWidthHeight(); width = 8; height = 9; } public FireBall(int x, int y) : base(ObjectType.OT_FireBall) { Fire = false; Visible = false; AnimatedCount = 4; TimerGenerator.AddTimerEventHandler(TimerType.TT_100, OnAnimate); TimerGenerator.AddTimerEventHandler(TimerType.TT_50, OnFire); } } }
0
0.89532
1
0.89532
game-dev
MEDIA
0.848716
game-dev
0.857698
1
0.857698
ForestDango/Hollow-Knight-Demo
2,714
Assets/PlayMaker/Actions/Physics2D/SetHingeJoint2dProperties.cs
// (c) Copyright HutongGames, LLC 2010-2016. All rights reserved. using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Physics2D)] [Tooltip("Sets the various properties of a HingeJoint2d component")] public class SetHingeJoint2dProperties : FsmStateAction { [RequiredField] [Tooltip("The HingeJoint2d target")] [CheckForComponent(typeof(HingeJoint2D))] public FsmOwnerDefault gameObject; [ActionSection("Limits")] [Tooltip("Should limits be placed on the range of rotation?")] public FsmBool useLimits; [Tooltip("Lower angular limit of rotation.")] public FsmFloat min; [Tooltip("Upper angular limit of rotation")] public FsmFloat max; [ActionSection("Motor")] [Tooltip("Should a motor force be applied automatically to the Rigidbody2D?")] public FsmBool useMotor; [Tooltip("The desired speed for the Rigidbody2D to reach as it moves with the joint.")] public FsmFloat motorSpeed; [Tooltip("The maximum force that can be applied to the Rigidbody2D at the joint to attain the target speed.")] public FsmFloat maxMotorTorque; [Tooltip("Repeat every frame while the state is active.")] public bool everyFrame; HingeJoint2D _joint; JointMotor2D _motor; JointAngleLimits2D _limits; public override void Reset() { useLimits = new FsmBool() {UseVariable=true}; min = new FsmFloat() {UseVariable=true}; max = new FsmFloat() {UseVariable=true}; useMotor = new FsmBool() {UseVariable=true}; motorSpeed = new FsmFloat() {UseVariable=true}; maxMotorTorque = new FsmFloat() {UseVariable=true}; everyFrame = false; } public override void OnEnter() { var go = Fsm.GetOwnerDefaultTarget(gameObject); if (go != null) { _joint = go.GetComponent<HingeJoint2D>(); if(_joint!=null) { _motor = _joint.motor; _limits = _joint.limits; } } SetProperties(); if(!everyFrame) { Finish(); } } public override void OnUpdate() { SetProperties(); } void SetProperties() { if(_joint==null) { return; } if (!useMotor.IsNone) { _joint.useMotor = useMotor.Value; } if (!motorSpeed.IsNone) { _motor.motorSpeed = motorSpeed.Value; _joint.motor = _motor; } if (!maxMotorTorque.IsNone) { _motor.maxMotorTorque = maxMotorTorque.Value; _joint.motor = _motor; } if (!useLimits.IsNone) { _joint.useLimits = useLimits.Value; } if (!min.IsNone) { _limits.min = min.Value; _joint.limits = _limits; } if (!max.IsNone) { _limits.max = max.Value; _joint.limits = _limits; } } } }
0
0.939973
1
0.939973
game-dev
MEDIA
0.978082
game-dev
0.861346
1
0.861346
v3921358/MapleRoot
2,305
MapleRoot/src/main/java/constants/inventory/EquipType.java
/* This file is part of the HeavenMS MapleStory Server Copyleft (L) 2016 - 2019 RonanLana This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package constants.inventory; import java.util.HashMap; import java.util.Map; /** * @author RonanLana */ public enum EquipType { UNDEFINED(-1), ACCESSORY(0), CAP(100), CAPE(110), COAT(104), FACE(2), GLOVES(108), HAIR(3), LONGCOAT(105), PANTS(106), PET_EQUIP(180), PET_EQUIP_FIELD(181), PET_EQUIP_LABEL(182), PET_EQUIP_QUOTE(183), RING(111), SHIELD(109), SHOES(107), TAMING(190), TAMING_SADDLE(191), SWORD(1302), AXE(1312), MACE(1322), DAGGER(1332), WAND(1372), STAFF(1382), SWORD_2H(1402), AXE_2H(1412), MACE_2H(1422), SPEAR(1432), POLEARM(1442), BOW(1452), CROSSBOW(1462), CLAW(1472), KNUCKLER(1482), PISTOL(1492); private final int i; private static final Map<Integer, EquipType> map = new HashMap(34); EquipType(int val) { this.i = val; } public int getValue() { return i; } static { for (EquipType eqEnum : EquipType.values()) { map.put(eqEnum.i, eqEnum); } } public static EquipType getEquipTypeById(int itemid) { EquipType ret; int val = itemid / 100000; if (val == 13 || val == 14) { ret = map.get(itemid / 1000); } else { ret = map.get(itemid / 10000); } return (ret != null) ? ret : EquipType.UNDEFINED; } }
0
0.865256
1
0.865256
game-dev
MEDIA
0.44914
game-dev
0.61586
1
0.61586