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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sghiassy/Code-Reading-Book | 3,921 | netbsdsrc/games/phantasia/phantstruct.h | /* $NetBSD: phantstruct.h,v 1.2 1995/03/24 04:00:11 cgd Exp $ */
/*
* phantstruct.h - structure definitions for Phantasia
*/
struct player /* player statistics */
{
double p_experience; /* experience */
double p_level; /* level */
double p_strength; /* strength */
double p_sword; /* sword */
double p_might; /* effect strength */
double p_energy; /* energy */
double p_maxenergy; /* maximum energy */
double p_shield; /* shield */
double p_quickness; /* quickness */
double p_quksilver; /* quicksilver */
double p_speed; /* effective quickness */
double p_magiclvl; /* magic level */
double p_mana; /* mana */
double p_brains; /* brains */
double p_poison; /* poison */
double p_gold; /* gold */
double p_gems; /* gems */
double p_sin; /* sin */
double p_x; /* x coord */
double p_y; /* y coord */
double p_1scratch,
p_2scratch; /* variables used for decree, player battle */
struct
{
short ring_type; /* type of ring */
short ring_duration; /* duration of ring */
bool ring_inuse; /* ring in use flag */
} p_ring; /* ring stuff */
long p_age; /* age of player */
int p_degenerated; /* age/3000 last degenerated */
short p_type; /* character type */
short p_specialtype; /* special character type */
short p_lives; /* multiple lives for council, valar */
short p_crowns; /* crowns */
short p_charms; /* charms */
short p_amulets; /* amulets */
short p_holywater; /* holy water */
short p_lastused; /* day of year last used */
short p_status; /* playing, cloaked, etc. */
short p_tampered; /* decree'd, etc. flag */
short p_istat; /* used for inter-terminal battle */
bool p_palantir; /* palantir */
bool p_blessing; /* blessing */
bool p_virgin; /* virgin */
bool p_blindness; /* blindness */
char p_name[SZ_NAME]; /* name */
char p_password[SZ_PASSWORD];/* password */
char p_login[SZ_LOGIN]; /* login */
};
struct monster /* monster stats */
{
double m_strength; /* strength */
double m_brains; /* brains */
double m_speed; /* speed */
double m_energy; /* energy */
double m_experience; /* experience */
double m_flock; /* % chance of flocking */
double m_o_strength; /* original strength */
double m_o_speed; /* original speed */
double m_maxspeed; /* maximum speed */
double m_o_energy; /* original energy */
double m_melee; /* melee damage */
double m_skirmish; /* skirmish damage */
int m_treasuretype; /* treasure type */
int m_type; /* special type */
char m_name[26]; /* name */
};
struct energyvoid /* energy void */
{
double ev_x; /* x coordinate */
double ev_y; /* y coordinate */
bool ev_active; /* active or not */
};
struct scoreboard /* scoreboard entry */
{
double sb_level; /* level of player */
char sb_type[4]; /* character type of player */
char sb_name[SZ_NAME]; /* name of player */
char sb_login[SZ_LOGIN]; /* login of player */
};
struct charstats /* character type statistics */
{
double c_maxbrains; /* max brains per level */
double c_maxmana; /* max mana per level */
double c_weakness; /* how strongly poison affects player */
double c_goldtote; /* how much gold char can carry */
int c_ringduration; /* bad ring duration */
struct
{
double base; /* base for roll */
double interval; /* interval for roll */
double increase; /* increment per level */
} c_quickness, /* quickness */
c_strength, /* strength */
c_mana, /* mana */
c_energy, /* energy level */
c_brains, /* brains */
c_magiclvl; /* magic level */
};
struct menuitem /* menu item for purchase */
{
char *item; /* menu item name */
double cost; /* cost of item */
};
| 412 | 0.796925 | 1 | 0.796925 | game-dev | MEDIA | 0.865966 | game-dev | 0.550551 | 1 | 0.550551 |
eleev/tic-tac-toe | 6,238 | ios-spritekit-tic-tac-toe/ActiveGameState.swift | //
// ActiveGameState.swift
// Crosses'n Ous
//
// Created by Astemir Eleev on 01/07/2017.
// Copyright © 2017 Astemir Eleev. All rights reserved.
//
import GameplayKit
import SpriteKit
class ActiveGameState: GKState {
// MARK: - Propertoes
var scene: GameScene?
var waitingOnPlayer: Bool
// MARK: - Initializers
init(scene: GameScene) {
self.scene = scene
waitingOnPlayer = false
super.init()
}
// MARK: - Methods
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass == EndGameState.self
}
override func didEnter(from previousState: GKState?) {
waitingOnPlayer = false
}
override func update(deltaTime seconds: TimeInterval) {
assert(scene != nil, "Scene must not be nil")
assert(scene?.gameBoard != nil, "Gameboard must not be nil")
if !waitingOnPlayer{
waitingOnPlayer = true
updateGameState()
}
}
func updateGameState() {
assert(scene != nil, "Scene must not be nil")
assert(scene?.gameBoard != nil, "Gameboard must not be nil")
let (state, winner) = self.scene!.gameBoard!.determineIfWinner()
if state == .winner{
let winningLabel = self.scene?.childNode(withName: "winningLabel")
winningLabel?.isHidden = true
let winningPlayer = self.scene!.gameBoard!.isPlayerOne(winner!) ? "1" : "2"
if let winningLabel = winningLabel as? SKLabelNode,
let player1_score = self.scene?.childNode(withName: "//player1_score") as? SKLabelNode,
let player2_score = self.scene?.childNode(withName: "//player2_score") as? SKLabelNode {
winningLabel.text = "Player \(winningPlayer) wins!"
winningLabel.isHidden = false
if winningPlayer == "1" {
player1_score.text = "\(Int(player1_score.text!)! + 1)"
} else {
player2_score.text = "\(Int(player2_score.text!)! + 1)"
}
self.stateMachine?.enter(EndGameState.self)
waitingOnPlayer = false
}
} else if state == .draw {
let winningLabel = self.scene?.childNode(withName: "winningLabel")
winningLabel?.isHidden = true
if let winningLabel = winningLabel as? SKLabelNode {
winningLabel.text = "It's a draw"
winningLabel.isHidden = false
}
self.stateMachine?.enter(EndGameState.self)
waitingOnPlayer = false
} else if self.scene!.gameBoard!.isPlayerTwoTurn() {
// Change the font type for AI agent
let completion = highlightActivePlayer(.machine, with: .blue)
//AI moves
self.scene?.isUserInteractionEnabled = false
assert(scene != nil, "Scene must not be nil")
assert(scene?.gameBoard != nil, "Gameboard must not be nil")
DispatchQueue.global(qos: .default).async {
self.scene!.ai.gameModel = self.scene!.gameBoard!
let move = self.scene!.ai.bestMoveForActivePlayer() as? Move
assert(move != nil, "AI should be able to find a move")
let strategistTime = CFAbsoluteTimeGetCurrent()
let delta = CFAbsoluteTimeGetCurrent() - strategistTime
let aiTimeCeiling: TimeInterval = 1.0
let delay = min(aiTimeCeiling - delta, aiTimeCeiling)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) {
guard let cellNode: SKSpriteNode = self.scene?.childNode(withName: self.scene!.gameBoard!.getElementAtBoardLocation(move!.cell).node) as? SKSpriteNode else{
return
}
let circle = SKSpriteNode(imageNamed: Constants.ouCell)
circle.size = CGSize(width: Constants.cellSize, height: Constants.cellSize)
cellNode.alpha = 0.0
cellNode.addChild(circle)
let reveal = SKAction.fadeAlpha(to: 1.0, duration: 0.5)
cellNode.run(reveal)
self.scene!.gameBoard!.addPlayerValueAtBoardLocation(move!.cell, value: .o)
self.scene!.gameBoard!.togglePlayer()
self.waitingOnPlayer = false
self.scene?.isUserInteractionEnabled = true
// Completes the visual feedback to the human-player
completion()
}
}
} else {
self.waitingOnPlayer = false
self.scene?.isUserInteractionEnabled = true
}
}
}
/*
Extension that adds helper methods for visual feedback for human-player
*/
extension ActiveGameState {
/*
Highlights player's label indicating which turn is which
*/
fileprivate func highlightActivePlayer(_ player: CurrentPlayer, with color: UIColor = .blue) -> () -> ()? {
let labelNodeName = player == .human ? "player1_label_node" : "player2_label_node"
var font: UIColor?
var label: SKLabelNode?
if let playerNode = self.scene?.childNode(withName: labelNodeName) as? SKLabelNode {
label = playerNode
font = playerNode.fontColor
playerNode.fontColor = color
}
let completion = {
label?.fontColor = font
}
return completion
}
}
struct Constants {
static let cellSize = 115
static let ouCell = "O"
static let exCell = "X"
static let reset = "Reset"
static let resetLabel = "reset_label"
static let gridSearchRequest = "//grid*"
static let difficuly = "Difficulty:"
}
| 412 | 0.852784 | 1 | 0.852784 | game-dev | MEDIA | 0.955015 | game-dev | 0.910471 | 1 | 0.910471 |
setuppf/GameBookServer | 1,825 | 08_02_allinone/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 <thread>
SystemManager::SystemManager()
{
_pEntitySystem = new EntitySystem(this);
_pMessageSystem = new MessageSystem(this);
//_systems.emplace_back(new DependenceSystem());
//_systems.emplace_back(new StartSystem());
_systems.emplace_back(new UpdateSystem());
// 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());
}
void SystemManager::InitComponent()
{
_pEntitySystem->AddComponent<CreateComponentC>();
_pEntitySystem->AddComponent<ConsoleThreadComponent>();
}
void SystemManager::Update()
{
_pEntitySystem->Update();
_pMessageSystem->Update(_pEntitySystem);
for (auto iter = _systems.begin(); iter != _systems.end(); ++iter)
{
(*iter)->Update(_pEntitySystem);
}
}
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;
}
std::default_random_engine* SystemManager::GetRandomEngine() const
{
return _pRandomEngine;
}
MessageSystem* SystemManager::GetMessageSystem() const
{
return _pMessageSystem;
}
EntitySystem* SystemManager::GetEntitySystem() const
{
return _pEntitySystem;
}
| 412 | 0.928664 | 1 | 0.928664 | game-dev | MEDIA | 0.723424 | game-dev | 0.779803 | 1 | 0.779803 |
EnigmaticaModpacks/Enigmatica6 | 4,453 | kubejs/server_scripts/enigmatica/kubejs/base/recipetypes/minecraft/stonecutter.js | onEvent('recipes', (event) => {
const id_prefix = 'enigmatica:base/minecraft/stonecutter/';
const recipes = [
{
output: 'masonry:stonechiseledslab',
input: 'minecraft:chiseled_stone_bricks'
},
{
output: 'masonry:stonechiseledwall',
input: 'minecraft:chiseled_stone_bricks'
},
{
output: 'masonry:stonelargebrickscrackedslab',
input: 'minecraft:cracked_stone_bricks'
},
{
output: 'masonry:stonelargebrickscrackedwall',
input: 'minecraft:cracked_stone_bricks'
},
{
output: 'masonry:granitepolishedwall',
input: 'minecraft:polished_granite'
},
{
output: 'masonry:dioritepolishedwall',
input: 'minecraft:polished_diorite'
},
{
output: 'masonry:andesitepolishedwall',
input: 'minecraft:polished_andesite'
},
{
output: 'masonry:darkprismarinepanelswall',
input: 'minecraft:dark_prismarine'
},
{
output: 'masonry:prismarinepaverswall',
input: 'minecraft:prismarine_bricks'
},
{
output: 'betterendforge:endstone_dust',
input: 'byg:end_sand'
},
{
output: 'byg:end_sand',
input: 'betterendforge:endstone_dust'
},
{
output: Item.of('2x occultism:otherstone_slab'),
input: 'occultism:otherstone'
},
{
output: Item.of('8x darkutils:blank_plate'),
input: 'occultism:otherstone'
},
{
output: 'minecraft:terracotta',
input: 'quark:shingles'
}
];
// Color based recipes
colors.forEach((color) => {
recipes.push({
output: `minecraft:${color}_terracotta`,
input: `quark:${color}_shingles`
});
});
// Recipes for stonecuttables constant
stonecuttables.forEach((stoneType) => {
stoneType.stones.forEach((stone) => {
recipes.push({
output: stone,
input: `#enigmatica:stonecuttables/${stoneType.name}`
});
});
stoneType.onlyAsOutput.forEach((stone) => {
recipes.push({
output: stone,
input: `#enigmatica:stonecuttables/${stoneType.name}`
});
});
});
// Recipes for masonry constants
masonryStoneTypes.forEach((stoneType) => {
masonryPatterns.forEach((pattern) => {
let input = stoneType + pattern;
if (!masonryIgnoredInputs.includes(input)) {
recipes.push({
output: `2x masonry:${input}slab`,
input: `masonry:${input}`
});
recipes.push({
output: `masonry:${input}wall`,
input: `masonry:${input}`
});
}
});
});
masonryTiledStoneTypes.forEach((stoneType) => {
recipes.push({
output: Item.of(`2x masonry:${stoneType}tiledslab`),
input: `masonry:${stoneType}tiled`
});
recipes.push({
output: `masonry:${stoneType}tiledwall`,
input: `masonry:${stoneType}tiled`
});
});
// Conversion between different storage_blocks of the same material
let conversionTypes = ['storage_block', 'ore'];
conversionTypes.forEach((type) => {
materialsToUnify.forEach((material) => {
if (!entryIsBlacklisted(material, type)) {
let tag = Ingredient.of(`#forge:${type}s/${material}`);
if (tag.stacks.size() > 1) {
tag.stacks.forEach((block) => {
recipes.push({ output: block.id, input: tag });
});
}
}
});
});
// Tag conversion
conversionTypes = ['#forge:dirt', '#forge:workbenches', '#forge:grass'];
conversionTypes.forEach((tag) => {
let ingredient = Ingredient.of(tag);
ingredient.stacks.forEach((block) => {
recipes.push({ output: block.id, input: ingredient });
});
});
recipes.forEach((recipe) => {
fallback_id(event.stonecutting(recipe.output, recipe.input), id_prefix);
});
});
| 412 | 0.708745 | 1 | 0.708745 | game-dev | MEDIA | 0.944277 | game-dev | 0.683927 | 1 | 0.683927 |
angband/angband | 22,572 | src/ui-map.c | /**
* \file ui-map.c
* \brief Writing level map info to the screen
*
* Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke
*
* This work is free software; you can redistribute it and/or modify it
* under the terms of either:
*
* a) the GNU General Public License as published by the Free Software
* Foundation, version 2, or
*
* b) the "Angband licence":
* This software may be copied and distributed for educational, research,
* and not for profit purposes provided that this copyright and statement
* are included in all such copies. Other copyrights may also apply.
*/
#include "angband.h"
#include "cave.h"
#include "grafmode.h"
#include "init.h"
#include "mon-predicate.h"
#include "mon-util.h"
#include "monster.h"
#include "obj-tval.h"
#include "obj-util.h"
#include "player-timed.h"
#include "trap.h"
#include "ui-input.h"
#include "ui-map.h"
#include "ui-object.h"
#include "ui-output.h"
#include "ui-prefs.h"
#include "ui-term.h"
/**
* Hallucinatory monster
*/
static void hallucinatory_monster(int *a, wchar_t *c)
{
while (1) {
/* Select a random monster */
struct monster_race *race = &r_info[randint0(z_info->r_max)];
/* Skip non-entries */
if (!race->name) continue;
/* Retrieve attr/char */
*a = monster_x_attr[race->ridx];
*c = monster_x_char[race->ridx];
return;
}
}
/**
* Hallucinatory object
*/
static void hallucinatory_object(int *a, wchar_t *c)
{
while (1) {
/* Select a random object */
struct object_kind *kind = &k_info[randint0(z_info->k_max - 1) + 1];
/* Skip non-entries */
if (!kind->name) continue;
/* Retrieve attr/char (HACK - without flavors) */
*a = kind_x_attr[kind->kidx];
*c = kind_x_char[kind->kidx];
/* HACK - Skip empty entries */
if (*a == 0 || *c == 0) continue;
return;
}
}
/**
* Get the graphics of a listed trap.
*
* We should probably have better handling of stacked traps, but that can
* wait until we do, in fact, have stacked traps under normal conditions.
* Return true if it's a web
*/
static bool get_trap_graphics(struct chunk *c, struct grid_data *g, int *a,
wchar_t *w)
{
/* Trap is visible */
if (trf_has(g->trap->flags, TRF_VISIBLE) ||
trf_has(g->trap->flags, TRF_GLYPH) ||
trf_has(g->trap->flags, TRF_WEB)) {
/* Get the graphics */
*a = trap_x_attr[g->lighting][g->trap->kind->tidx];
*w = trap_x_char[g->lighting][g->trap->kind->tidx];
}
return trf_has(g->trap->flags, TRF_WEB);
}
/**
* Apply text lighting effects
*/
static void grid_get_attr(struct grid_data *g, int *a)
{
/* Save the high-bit, since it's used for attr inversion in GCU */
int a0 = *a & 0x80;
/* Remove the high bit so we can add it back again at the end */
*a = (*a & 0x7F);
/* Play with fg colours for terrain affected by torchlight */
if (feat_is_torch(g->f_idx)) {
/* Brighten if torchlit, darken if out of LoS, super dark for UNLIGHT */
switch (g->lighting) {
case LIGHTING_TORCH: *a = get_color(*a, ATTR_LIGHT, 1); break;
case LIGHTING_LIT: *a = get_color(*a, ATTR_DARK, 1); break;
case LIGHTING_DARK: *a = get_color(*a, ATTR_DARK, 2); break;
default: break;
}
}
/* Add the attr inversion back for GCU */
if (a0) {
*a = a0 | *a;
}
/* Hybrid or block walls */
if (use_graphics == GRAPHICS_NONE && feat_is_wall(g->f_idx)) {
if (OPT(player, hybrid_walls))
*a = *a + (MULT_BG * BG_DARK);
else if (OPT(player, solid_walls))
*a = *a + (MULT_BG * BG_SAME);
}
}
/**
* This function takes a pointer to a grid info struct describing the
* contents of a grid location (as obtained through the function map_info)
* and fills in the character and attr pairs for display.
*
* ap and cp are filled with the attr/char pair for the monster, object or
* floor tile that is at the "top" of the grid (monsters covering objects,
* which cover floor, assuming all are present).
*
* tap and tcp are filled with the attr/char pair for the floor, regardless
* of what is on it. This can be used by graphical displays with
* transparency to place an object onto a floor tile, is desired.
*
* Any lighting effects are also applied to these pairs, clear monsters allow
* the underlying colour or feature to show through (ATTR_CLEAR and
* CHAR_CLEAR), multi-hued colour-changing (ATTR_MULTI) is applied, and so on.
* Technically, the flag "CHAR_MULTI" is supposed to indicate that a monster
* looks strange when examined, but this flag is currently ignored.
*
* NOTES:
* This is called pretty frequently, whenever a grid on the map display
* needs updating, so don't overcomplicate it.
*
* The "zero" entry in the feature/object/monster arrays are
* used to provide "special" attr/char codes, with "monster zero" being
* used for the player attr/char, "object zero" being used for the "pile"
* attr/char, and "feature zero" being used for the "darkness" attr/char.
*
* TODO:
* The transformations for tile colors, or brightness for the 16x16
* tiles should be handled differently. One possibility would be to
* extend feature_type with attr/char definitions for the different states.
* This will probably be done outside of the current text->graphics mappings
* though.
*/
void grid_data_as_text(struct grid_data *g, int *ap, wchar_t *cp, int *tap,
wchar_t *tcp)
{
struct feature *feat = &f_info[g->f_idx];
int a = feat_x_attr[g->lighting][feat->fidx];
wchar_t c = feat_x_char[g->lighting][feat->fidx];
bool skip_objects = false;
/* Get the colour for ASCII */
if (use_graphics == GRAPHICS_NONE)
grid_get_attr(g, &a);
/* Save the terrain info for the transparency effects */
(*tap) = a;
(*tcp) = c;
/* There is a trap in this grid, and we are not hallucinating */
if (g->trap && (!g->hallucinate)) {
/* Change graphics to indicate visible traps, skip objects if a web */
skip_objects = get_trap_graphics(cave, g, &a, &c);
}
if (!skip_objects) {
/* If there's an object, deal with that. */
if (g->unseen_money) {
/* $$$ gets an orange star*/
a = object_kind_attr(unknown_gold_kind);
c = object_kind_char(unknown_gold_kind);
} else if (g->unseen_object) {
/* Everything else gets a red star */
a = object_kind_attr(unknown_item_kind);
c = object_kind_char(unknown_item_kind);
} else if (g->first_kind) {
if (g->hallucinate) {
/* Just pick a random object to display. */
hallucinatory_object(&a, &c);
} else if (g->multiple_objects) {
/* Get the "pile" feature instead */
a = object_kind_attr(pile_kind);
c = object_kind_char(pile_kind);
} else {
/* Normal attr and char */
a = object_kind_attr(g->first_kind);
c = object_kind_char(g->first_kind);
}
}
}
/* Handle monsters, the player and trap borders */
if (g->m_idx > 0) {
if (g->hallucinate) {
/* Just pick a random monster to display. */
hallucinatory_monster(&a, &c);
} else if (!monster_is_camouflaged(cave_monster(cave, g->m_idx))) {
struct monster *mon = cave_monster(cave, g->m_idx);
uint8_t da;
wchar_t dc;
/* Desired attr & char */
da = monster_x_attr[mon->race->ridx];
dc = monster_x_char[mon->race->ridx];
/* Special handling of attrs and/or chars */
if (da & 0x80) {
/* Special attr/char codes */
a = da;
c = dc;
} else if (OPT(player, purple_uniques) &&
monster_is_shape_unique(mon)) {
/* Turn uniques purple if desired (violet, actually) */
a = COLOUR_VIOLET;
c = dc;
} else if (rf_has(mon->race->flags, RF_ATTR_MULTI) ||
rf_has(mon->race->flags, RF_ATTR_FLICKER) ||
rf_has(mon->race->flags, RF_ATTR_RAND)) {
/* Multi-hued monster */
a = mon->attr ? mon->attr : da;
c = dc;
} else if (!flags_test(mon->race->flags, RF_SIZE,
RF_ATTR_CLEAR, RF_CHAR_CLEAR, FLAG_END)) {
/* Normal monster (not "clear" in any way) */
a = da;
/* Desired attr & char. da is not used, should a be set to it?*/
/*da = monster_x_attr[mon->race->ridx];*/
dc = monster_x_char[mon->race->ridx];
c = dc;
} else if (a & 0x80) {
/* Bizarre grid under monster */
a = da;
c = dc;
} else if (!rf_has(mon->race->flags, RF_CHAR_CLEAR)) {
/* Normal char, Clear attr, monster */
c = dc;
} else if (!rf_has(mon->race->flags, RF_ATTR_CLEAR)) {
/* Normal attr, Clear char, monster */
a = da;
}
/* Store the drawing attr so we can use it elsewhere */
mon->attr = a;
}
} else if (g->is_player) {
struct monster_race *race = &r_info[0];
/* Get the "player" attr */
a = monster_x_attr[race->ridx];
if ((OPT(player, hp_changes_color)) && !(a & 0x80)) {
switch(player->chp * 10 / player->mhp)
{
case 10:
case 9:
{
a = COLOUR_WHITE;
break;
}
case 8:
case 7:
{
a = COLOUR_YELLOW;
break;
}
case 6:
case 5:
{
a = COLOUR_ORANGE;
break;
}
case 4:
case 3:
{
a = COLOUR_L_RED;
break;
}
case 2:
case 1:
case 0:
{
a = COLOUR_RED;
break;
}
default:
{
a = COLOUR_WHITE;
break;
}
}
}
/* Get the "player" char */
c = monster_x_char[race->ridx];
}
/* Result */
(*ap) = a;
(*cp) = c;
}
/**
* Get dimensions of a small-scale map (i.e. display_map()'s result).
* \param t Is the terminal displaying the map.
* \param c Is the chunk to display.
* \param tw Is the tile width in characters.
* \param th Is the tile height in characters.
* \param mw *mw is set to the width of the small-scale map.
* \param mh *mh is set to the height of the small-scale map.
*/
static void get_minimap_dimensions(term *t, const struct chunk *c,
int tw, int th, int *mw, int *mh)
{
int map_height = t->hgt - 2;
int map_width = t->wid - 2;
int cave_height = c->height;
int cave_width = c->width;
int remainder;
if (th > 1) {
/*
* Round cave height up to a multiple of the tile height
* (ideally want no information truncated).
*/
remainder = cave_height % th;
if (remainder > 0) {
cave_height += th - remainder;
}
/*
* Round map height down to a multiple of the tile height
* (don't want partial tiles overwriting the map borders).
*/
map_height -= map_height % th;
}
if (tw > 1) {
/* As above but for the width. */
remainder = cave_width % tw;
if (remainder > 0) {
cave_width += tw - remainder;
}
map_width -= map_width % tw;
}
*mh = MIN(map_height, cave_height);
*mw = MIN(map_width, cave_width);
}
/**
* Move the cursor to a given map location.
*/
static void move_cursor_relative_map(int y, int x)
{
int ky, kx;
term *old;
int j;
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++) {
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if (!(window_flag[j] & (PW_MAPS))) continue;
if (window_flag[j] & PW_MAP) {
/* Be consistent with display_map(). */
int map_width, map_height;
get_minimap_dimensions(t, cave, tile_width,
tile_height, &map_width, &map_height);
ky = (y * map_height) / cave->height;
if (tile_height > 1) {
ky = ky - (ky % tile_height) + 1;
} else {
++ky;
}
kx = (x * map_width) / cave->width;
if (tile_width > 1) {
kx = kx - (kx % tile_width) + 1;
} else {
++kx;
}
} else {
/* Location relative to panel */
ky = y - t->offset_y;
if (tile_height > 1)
ky = tile_height * ky;
kx = x - t->offset_x;
if (tile_width > 1)
kx = tile_width * kx;
}
/* Verify location */
if ((ky < 0) || (ky >= t->hgt)) continue;
if ((kx < 0) || (kx >= t->wid)) continue;
/* Go there */
old = Term;
Term_activate(t);
(void)Term_gotoxy(kx, ky);
Term_activate(old);
}
}
/**
* Move the cursor to a given map location.
*
* The main screen will always be at least 24x80 in size.
*/
void move_cursor_relative(int y, int x)
{
int ky, kx;
int vy, vx;
/* Move the cursor on map sub-windows */
move_cursor_relative_map(y, x);
/* Location relative to panel */
ky = y - Term->offset_y;
/* Verify location */
if ((ky < 0) || (ky >= SCREEN_HGT)) return;
/* Location relative to panel */
kx = x - Term->offset_x;
/* Verify location */
if ((kx < 0) || (kx >= SCREEN_WID)) return;
/* Location in window */
vy = ky + ROW_MAP;
/* Location in window */
vx = kx + COL_MAP;
if (tile_width > 1)
vx += (tile_width - 1) * kx;
if (tile_height > 1)
vy += (tile_height - 1) * ky;
/* Go there */
(void)Term_gotoxy(vx, vy);
}
/**
* Display an attr/char pair at the given map location
*
* Note the inline use of "panel_contains()" for efficiency.
*
* Note the use of "Term_queue_char()" for efficiency.
*/
static void print_rel_map(wchar_t c, uint8_t a, int y, int x)
{
int ky, kx;
int j;
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++) {
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if (!(window_flag[j] & (PW_MAPS))) continue;
if (window_flag[j] & PW_MAP) {
/* Be consistent with display_map(). */
int map_width, map_height;
get_minimap_dimensions(t, cave, tile_width,
tile_height, &map_width, &map_height);
kx = (x * map_width) / cave->width;
ky = (y * map_height) / cave->height;
if (tile_width > 1) {
kx = kx - (kx % tile_width) + 1;
} else {
++kx;
}
if (tile_height > 1) {
ky = ky - (ky % tile_height) + 1;
} else {
++ky;
}
} else {
/* Location relative to panel */
ky = y - t->offset_y;
if (tile_height > 1) {
ky = tile_height * ky;
if (ky + 1 >= t->hgt) continue;
}
kx = x - t->offset_x;
if (tile_width > 1) {
kx = tile_width * kx;
if (kx + 1 >= t->wid) continue;
}
}
/* Verify location */
if ((ky < 0) || (ky >= t->hgt)) continue;
if ((kx < 0) || (kx >= t->wid)) continue;
/* Queue it */
Term_queue_char(t, kx, ky, a, c, 0, 0);
if ((tile_width > 1) || (tile_height > 1))
/*
* The overhead view can make use of the last row in
* the terminal. Others leave it be.
*/
Term_big_queue_char(t, kx, ky, t->hgt -
((window_flag[j] & PW_OVERHEAD) ? 0 : ROW_BOTTOM_MAP),
a, c, 0, 0);
}
}
/**
* Display an attr/char pair at the given map location
*
* Note the inline use of "panel_contains()" for efficiency.
*
* Note the use of "Term_queue_char()" for efficiency.
*
* The main screen will always be at least 24x80 in size.
*/
void print_rel(wchar_t c, uint8_t a, int y, int x)
{
int ky, kx;
int vy, vx;
/* Print on map sub-windows */
print_rel_map(c, a, y, x);
/* Location relative to panel */
ky = y - Term->offset_y;
/* Verify location */
if ((ky < 0) || (ky >= SCREEN_HGT)) return;
/* Location relative to panel */
kx = x - Term->offset_x;
/* Verify location */
if ((kx < 0) || (kx >= SCREEN_WID)) return;
/* Get right position */
vx = COL_MAP + (tile_width * kx);
vy = ROW_MAP + (tile_height * ky);
/* Queue it */
Term_queue_char(Term, vx, vy, a, c, 0, 0);
if ((tile_width > 1) || (tile_height > 1))
Term_big_queue_char(Term, vx, vy, ROW_MAP + SCREEN_ROWS,
a, c, 0, 0);
}
static void prt_map_aux(void)
{
int a, ta;
wchar_t c, tc;
struct grid_data g;
int y, x;
int vy, vx;
int ty, tx;
int j;
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++) {
term *t = angband_term[j];
int clipy;
/* No window */
if (!t) continue;
/* No relevant flags */
if (!(window_flag[j] & (PW_MAPS))) continue;
if (window_flag[j] & PW_MAP) {
term *old = Term;
Term_activate(t);
display_map(NULL, NULL);
Term_activate(old);
continue;
}
/* Assume screen */
ty = t->offset_y + (t->hgt / tile_height);
tx = t->offset_x + (t->wid / tile_width);
/*
* The overhead view can use the last row of the terminal.
* Others can not.
*/
clipy = t->hgt - ((window_flag[j] & PW_OVERHEAD) ? 0 : ROW_BOTTOM_MAP);
/* Dump the map */
for (y = t->offset_y, vy = 0; y < ty; vy += tile_height, y++) {
for (x = t->offset_x, vx = 0; x < tx; vx += tile_width, x++) {
/* Check bounds */
if (!square_in_bounds(cave, loc(x, y))) {
Term_queue_char(t, vx, vy,
COLOUR_WHITE, ' ',
0, 0);
if (tile_width > 1 || tile_height > 1) {
Term_big_queue_char(t, vx, vy,
clipy, COLOUR_WHITE, ' ', 0, 0);
}
continue;
}
/* Determine what is there */
map_info(loc(x, y), &g);
grid_data_as_text(&g, &a, &c, &ta, &tc);
Term_queue_char(t, vx, vy, a, c, ta, tc);
if ((tile_width > 1) || (tile_height > 1))
Term_big_queue_char(t, vx, vy, clipy,
255, -1, 0, 0);
}
/* Clear partial tile at the end of each line. */
for (; vx < t->wid; ++vx) {
Term_queue_char(t, vx, vy, COLOUR_WHITE,
' ', 0, 0);
}
}
/* Clear row of partial tiles at the bottom. */
for (; vy < t->hgt; ++vy) {
for (vx = 0; vx < t->wid; ++vx) {
Term_queue_char(t, vx, vy, COLOUR_WHITE,
' ', 0, 0);
}
}
}
}
/**
* Redraw (on the screen) the current map panel
*
* Note the inline use of "light_spot()" for efficiency.
*
* The main screen will always be at least 24x80 in size.
*/
void prt_map(void)
{
int a, ta;
wchar_t c, tc;
struct grid_data g;
int y, x;
int vy, vx;
int ty, tx;
int clipy;
/* Redraw map sub-windows */
prt_map_aux();
/* Assume screen */
ty = Term->offset_y + SCREEN_HGT;
tx = Term->offset_x + SCREEN_WID;
/* Avoid overwriting the last row with padding for big tiles. */
clipy = ROW_MAP + SCREEN_ROWS;
/* Dump the map */
for (y = Term->offset_y, vy = ROW_MAP; y < ty; vy += tile_height, y++)
for (x = Term->offset_x, vx = COL_MAP; x < tx; vx += tile_width, x++) {
/* Check bounds */
if (!square_in_bounds(cave, loc(x, y))) continue;
/* Determine what is there */
map_info(loc(x, y), &g);
grid_data_as_text(&g, &a, &c, &ta, &tc);
/* Queue it */
Term_queue_char(Term, vx, vy, a, c, ta, tc);
if ((tile_width > 1) || (tile_height > 1))
Term_big_queue_char(Term, vx, vy, clipy, a, c,
COLOUR_WHITE, L' ');
}
}
/**
* Display a "small-scale" map of the dungeon in the active Term.
*
* Note that this function must "disable" the special lighting effects so
* that the "priority" function will work.
*
* Note the use of a specialized "priority" function to allow this function
* to work with any graphic attr/char mappings, and the attempts to optimize
* this function where possible.
*
* If "cy" and "cx" are not NULL, then returns the screen location at which
* the player was displayed, so the cursor can be moved to that location,
* and restricts the horizontal map size to SCREEN_WID. Otherwise, nothing
* is returned (obviously), and no restrictions are enforced.
*/
void display_map(int *cy, int *cx)
{
int map_hgt, map_wid;
int row, col;
int x, y;
struct grid_data g;
int a, ta;
wchar_t c, tc;
uint8_t tp;
struct monster_race *race = &r_info[0];
/* Priority array */
uint8_t **mp = mem_zalloc(cave->height * sizeof(uint8_t*));
for (y = 0; y < cave->height; y++)
mp[y] = mem_zalloc(cave->width * sizeof(uint8_t));
/* Desired map height */
get_minimap_dimensions(Term, cave, tile_width, tile_height,
&map_wid, &map_hgt);
/* Prevent accidents */
if ((map_wid < 1) || (map_hgt < 1)) {
for (y = 0; y < cave->height; y++)
mem_free(mp[y]);
mem_free(mp);
return;
}
/* Nothing here */
a = COLOUR_WHITE;
c = L' ';
ta = COLOUR_WHITE;
tc = L' ';
/* Draw a box around the edge of the term */
window_make(0, 0, map_wid + 1, map_hgt + 1);
/* Clear outside that boundary. */
if (map_wid + 1 < Term->wid - 1) {
for (y = 0; y < map_hgt + 1; y++) {
Term_erase(map_wid + 2, y, Term->wid - map_wid - 2);
}
}
if (map_hgt + 1 < Term->hgt - 1) {
for (y = map_hgt + 2; y < Term->hgt; y++) {
Term_erase(0, y, Term->wid);
}
}
/* Analyze the actual map */
for (y = 0; y < cave->height; y++) {
row = (y * map_hgt) / cave->height;
if (tile_height > 1) row = row - (row % tile_height);
for (x = 0; x < cave->width; x++) {
col = (x * map_wid) / cave->width;
if (tile_width > 1) col = col - (col % tile_width);
/* Get the attr/char at that map location */
map_info(loc(x, y), &g);
grid_data_as_text(&g, &a, &c, &ta, &tc);
/* Get the priority of that attr/char */
tp = f_info[g.f_idx].priority;
/* Stuff on top of terrain gets higher priority */
if ((a != ta) || (c != tc)) tp = 20;
/* Save "best" */
if (mp[row][col] < tp) {
/* Hack - make every grid on the map lit */
g.lighting = LIGHTING_LIT;
grid_data_as_text(&g, &a, &c, &ta, &tc);
Term_queue_char(Term, col + 1, row + 1, a, c, ta, tc);
if ((tile_width > 1) || (tile_height > 1))
Term_big_queue_char(Term, col + 1,
row + 1, Term->hgt - 1,
255, -1, 0, 0);
/* Save priority */
mp[row][col] = tp;
}
}
}
/*** Display the player ***/
/* Player location */
row = (player->grid.y * map_hgt / cave->height);
col = (player->grid.x * map_wid / cave->width);
if (tile_width > 1)
col = col - (col % tile_width);
if (tile_height > 1)
row = row - (row % tile_height);
/* Get the terrain at the player's spot. */
map_info(player->grid, &g);
g.lighting = LIGHTING_LIT;
grid_data_as_text(&g, &a, &c, &ta, &tc);
/* Get the "player" tile */
a = monster_x_attr[race->ridx];
c = monster_x_char[race->ridx];
/* Draw the player */
Term_queue_char(Term, col + 1, row + 1, a, c, ta, tc);
if ((tile_width > 1) || (tile_height > 1))
Term_big_queue_char(Term, col + 1, row + 1, Term->hgt - 1,
255, -1, 0, 0);
/* Return player location */
if (cy != NULL) (*cy) = row + 1;
if (cx != NULL) (*cx) = col + 1;
for (y = 0; y < cave->height; y++)
mem_free(mp[y]);
mem_free(mp);
}
/*
* Display a "small-scale" map of the dungeon.
*
* Note that the "player" is always displayed on the map.
*/
void do_cmd_view_map(void)
{
int cy, cx;
uint8_t w, h;
const char *prompt = "Hit any key to continue";
if (Term->view_map_hook) {
(*(Term->view_map_hook))(Term);
return;
}
/* Save screen */
screen_save();
/* Note */
prt("Please wait...", 0, 0);
/* Flush */
Term_fresh();
/* Clear the screen */
Term_clear();
/* store the tile multipliers */
w = tile_width;
h = tile_height;
tile_width = 1;
tile_height = 1;
/* Display the map */
display_map(&cy, &cx);
/* Show the prompt */
put_str(prompt, Term->hgt - 1, Term->wid / 2 - strlen(prompt) / 2);
/* Highlight the player */
Term_gotoxy(cx, cy);
/* Get any key */
(void)anykey();
/* Restore the tile multipliers */
tile_width = w;
tile_height = h;
/* Load screen */
screen_load();
}
| 412 | 0.976953 | 1 | 0.976953 | game-dev | MEDIA | 0.924673 | game-dev | 0.987067 | 1 | 0.987067 |
SimulaVR/godot-haskell | 5,176 | examples/top-down-ten-minutes/src/Game/World.hs | {-# LANGUAGE LambdaCase, TypeOperators #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
module Game.World where
import Control.Lens
import Control.Monad
import Control.Monad.Extra
import Godot
import Godot.Core.Node as Node
import qualified Godot.Core.AnimationPlayer as A
import Godot.Core.Input as Input
import Godot.Core.KinematicBody2D
import Godot.Core.Node2D
import Godot.Core.Particles2D
import Godot.Core.Object
import Godot.Core.PathFollow2D
import Godot.Core.RigidBody2D
import Godot.Core.Timer as Timer
import Godot.Core.CanvasItem
import Godot.Core.SceneTree
import Godot.Gdnative
import Linear.V2
import System.Random
import Project.Support
import Project.Scenes.World()
import Project.Scenes.Bullet()
import Project.Scenes.Enemy()
import Project.Scenes.Explosion()
import Data.String
import System.IO.Unsafe
import qualified Data.Text as T
import Data.Coerce
import Data.Maybe
import Data.Typeable
instance IsString GodotString where
fromString = unsafePerformIO . toLowLevel . T.pack
data Player = Player
{ _base :: KinematicBody2D
, _movespeed :: Float
, _bulletspeed :: Float
, _bullet :: MVar (PackedScene' "Bullet")
}
data Enemy = Enemy
{ _ebase :: KinematicBody2D
, _motion :: Vector2
, _explosion :: MVar (PackedScene' "Explosion")
}
data Bullet = Bullet
{ _bbase :: RigidBody2D
}
makeFieldsNoPrefix ''Player
makeFieldsNoPrefix ''Enemy
makeFieldsNoPrefix ''Bullet
-- * Player
instance NodeInit Player where
init b = do
Player b 500 500 <$> newEmptyMVar
instance NodeInit Enemy where
init b = Enemy b <$> godot_vector2_new 0 0 <*> newEmptyMVar
instance NodeInit Bullet where
init b = pure $ Bullet b
instance NodeMethod Player "_ready" '[] (IO ()) where
nodeMethod self = putMVar (self ^. bullet) =<< preloadScene
instance NodeMethod Player "_physics_process" '[Float] (IO ()) where
nodeMethod self _ = do
Just inp <- getSingleton @Input
action <- sum <$> mapM (\(c,v) -> (v *). fromIntegral . fromEnum <$>
(is_action_pressed inp =<< toLowLevel c))
[("left", V2 (-1) 0) ,("right", V2 1 0) ,("up", V2 0 (-1)) ,("down", V2 0 1)]
motion <- godot_vector2_normalized =<< toLowLevel action
motion <- godot_vector2_operator_multiply_scalar motion $ realToFrac (self ^. movespeed)
void $ move_and_slide self motion Nothing Nothing Nothing Nothing Nothing
look_at self =<< get_global_mouse_position self
whenM (is_action_just_pressed inp =<< toLowLevel "LMB") $ fire self
instance NodeMethod Player "_on_Area2D_body_entered" '[Node] (IO ()) where
nodeMethod self body = do
n <- fromLowLevel =<< get_name body
when ("Enemy" `T.isInfixOf` n) $ kill self
fire :: Player -> IO ()
fire self = do
b <- sceneInstance =<< readMVar (self ^. bullet)
set_position b =<< get_global_position self
set_rotation_degrees b =<< get_rotation_degrees self
apply_impulse b <$> toLowLevel (V2 0 0)
<*> (godot_vector2_rotated
<$> toLowLevel (V2 (self^.bulletspeed) 0)
<*> (realToFrac <$> get_rotation self)
& join)
& join
call_deferred <$> (get_root =<< get_tree self)
<*> toLowLevel "add_child"
<*> pure [toVariant b]
& join
-- * Enemy
instance NodeMethod Enemy "_ready" '[] (IO ()) where
nodeMethod self = putMVar (self ^. explosion) =<< preloadScene
instance NodeMethod Enemy "_on_Area2D_body_entered" '[Node] (IO ()) where
nodeMethod self body = do
n <- fromLowLevel =<< get_name body
when ("Bullet" `T.isInfixOf` n) $ do
ex <- sceneInstance =<< readMVar (self ^. explosion)
set_position ex =<< get_position self
set_emitting ex True
call_deferred <$> (get_root =<< get_tree self)
<*> toLowLevel "add_child"
<*> pure [toVariant ex]
& join
queue_free self
kill :: Player -> IO ()
kill self = void . reload_current_scene =<< get_tree self
instance NodeMethod Enemy "_physics_process" '[Float] (IO ()) where
nodeMethod self _ = do
pl <- get_node <$> get_parent self <*> toLowLevel "Player" & join
pp <- get_position =<< tryCast' @Node2D pl
ps <- get_position self
set_position self =<< godot_vector2_operator_add ps
=<< (godot_vector2_operator_divide_scalar <$> godot_vector2_operator_subtract pp ps
<*> pure 50 & join)
look_at self pp
void $ move_and_collide self (self ^. motion) Nothing Nothing Nothing
-- * Bullet
instance NodeMethod Bullet "_on_Bullet_body_entered" '[Node] (IO ()) where
nodeMethod self _ = do
n <- getNode' @"AnimationPlayer" self
A.play n (Just "fadeout") Nothing Nothing Nothing
instance NodeMethod Bullet "_on_AnimationPlayer_animation_finished" '[GodotString] (IO ()) where
nodeMethod self _ = queue_free self
setupNode ''Player "World" "Player"
deriveBase ''Player
setupNode ''Enemy "Enemy" "Enemy"
deriveBase ''Enemy
setupNode ''Bullet "Bullet" "Bullet"
deriveBase ''Bullet
| 412 | 0.801944 | 1 | 0.801944 | game-dev | MEDIA | 0.949228 | game-dev | 0.703234 | 1 | 0.703234 |
hausen/circuit-simulator | 2,053 | src/ProbeElm.java | import java.awt.*;
import java.util.StringTokenizer;
class ProbeElm extends CircuitElm {
static final int FLAG_SHOWVOLTAGE = 1;
public ProbeElm(int xx, int yy) { super(xx, yy); }
public ProbeElm(int xa, int ya, int xb, int yb, int f,
StringTokenizer st) {
super(xa, ya, xb, yb, f);
}
int getDumpType() { return 'p'; }
Point center;
void setPoints() {
super.setPoints();
// swap points so that we subtract higher from lower
if (point2.y < point1.y) {
Point x = point1;
point1 = point2;
point2 = x;
}
center = interpPoint(point1, point2, .5);
}
void draw(Graphics g) {
int hs = 8;
setBbox(point1, point2, hs);
boolean selected = (needsHighlight() || sim.plotYElm == this);
double len = (selected || sim.dragElm == this) ? 16 : dn-32;
calcLeads((int) len);
setVoltageColor(g, volts[0]);
if (selected)
g.setColor(selectColor);
drawThickLine(g, point1, lead1);
setVoltageColor(g, volts[1]);
if (selected)
g.setColor(selectColor);
drawThickLine(g, lead2, point2);
Font f = new Font("SansSerif", Font.BOLD, 14);
g.setFont(f);
if (this == sim.plotXElm)
drawCenteredText(g, "X", center.x, center.y, true);
if (this == sim.plotYElm)
drawCenteredText(g, "Y", center.x, center.y, true);
if (mustShowVoltage()) {
String s = getShortUnitText(volts[0], "V");
drawValues(g, s, 4);
}
drawPosts(g);
}
boolean mustShowVoltage() {
return (flags & FLAG_SHOWVOLTAGE) != 0;
}
void getInfo(String arr[]) {
arr[0] = "scope probe";
arr[1] = "Vd = " + getVoltageText(getVoltageDiff());
}
boolean getConnection(int n1, int n2) { return false; }
public EditInfo getEditInfo(int n) {
if (n == 0) {
EditInfo ei = new EditInfo("", 0, -1, -1);
ei.checkbox = new Checkbox("Show Voltage", mustShowVoltage());
return ei;
}
return null;
}
public void setEditValue(int n, EditInfo ei) {
if (n == 0) {
if (ei.checkbox.getState())
flags = FLAG_SHOWVOLTAGE;
else
flags &= ~FLAG_SHOWVOLTAGE;
}
}
}
| 412 | 0.787248 | 1 | 0.787248 | game-dev | MEDIA | 0.501839 | game-dev | 0.927928 | 1 | 0.927928 |
rachelselinar/DREAMPlaceFPGA | 3,532 | thirdparty/Limbo/limbo/thirdparty/dlx/example/sudoku/SudokuSolver.cpp | #include "SudokuSolver.hpp"
#include <dlx/AlgorithmDLX.hpp>
#include <assert.h>
#include <algorithm>
#include <unordered_map>
#include <vector>
Sudoku SudokuSolver::solve(const Sudoku& sudoku) const {
return solve_impl(sudoku, false);
}
Sudoku SudokuSolver::random_solution(const Sudoku& sudoku) const {
return solve_impl(sudoku, true);
}
Sudoku SudokuSolver::solve_impl(const Sudoku& sudoku, bool randomized) const {
if (!sudoku.is_valid()) {
throw std::runtime_error("solve(): Invalid sudoku");
}
const SudokuType& type = sudoku.type();
unsigned n = type.n();
auto pack = [&](unsigned a, unsigned b) -> unsigned { return a * n + b; };
auto id_cell = [&](unsigned x, unsigned y) -> unsigned { return pack(x, y); };
auto id_col = [&](unsigned x, unsigned d) -> unsigned { return type.size() + pack(x, d); };
auto id_row = [&](unsigned y, unsigned d) -> unsigned { return 2 * type.size() + pack(y, d); };
auto id_region = [&](unsigned i, unsigned d) -> unsigned { return 3 * type.size() + pack(i, d); };
std::vector<unsigned> cell_taken(type.size());
std::vector<unsigned> col_taken(type.size());
std::vector<unsigned> row_taken(type.size());
std::vector<unsigned> region_taken(type.size());
for (unsigned i = 0; i < type.size(); ++i) {
if (sudoku[i] != 0) {
unsigned x = i % n;
unsigned y = i / n;
unsigned d = sudoku[i] - 1;
++cell_taken[pack(x, y)];
++col_taken[pack(x, d)];
++row_taken[pack(y, d)];
++region_taken[pack(type.region(x, y), d)];
}
}
std::vector<std::vector<unsigned>> matrix;
for (unsigned i = 0; i < n; ++i) {
for (unsigned j = 0; j < n; ++j) {
if (cell_taken[pack(i, j)]) matrix.push_back({id_cell(i, j)});
if (col_taken[pack(i, j)]) matrix.push_back({id_col(i, j)});
if (row_taken[pack(i, j)]) matrix.push_back({id_row(i, j)});
if (region_taken[pack(i, j)]) matrix.push_back({id_region(i, j)});
}
}
std::unordered_map<unsigned, unsigned> row_position, row_digit;
for (unsigned y = 0; y < n; ++y) {
for (unsigned x = 0; x < n; ++x) {
for (unsigned d = 0; d < n; ++d) {
if (cell_taken[pack(x, y)]
|| col_taken[pack(x, d)]
|| row_taken[pack(y, d)]
|| region_taken[pack(type.region(x, y), d)])
{
continue;
}
unsigned row_index = matrix.size();
row_position[row_index] = y * n + x;
row_digit[row_index] = d;
matrix.push_back({
id_cell(x, y),
id_col(x, d),
id_row(y, d),
id_region(type.region(x, y), d)
});
}
}
}
AlgorithmDLX dlx(ExactCoverProblem(4 * type.size(), matrix));
auto options = AlgorithmDLX::Options();
if (randomized) {
static std::random_device rd;
static auto engine = std::mt19937(rd());
options.choose_random_column = randomized;
options.random_engine = &engine;
}
options.max_solutions = randomized ? 1 : 2;
auto result = dlx.search(options);
auto solutions = std::vector<Sudoku>();
for (const auto& rows : result.solutions) {
Sudoku solved(sudoku);
for (auto i : rows) {
auto pos = row_position.find(i);
if (pos != row_position.end()) {
solved[pos->second] = row_digit[i] + 1;
}
}
solutions.push_back(std::move(solved));
}
if (solutions.empty()) {
throw std::runtime_error("No solution");
}
if (solutions.size() > 1) {
throw std::runtime_error("Multiple solutions");
}
return solutions[0];
}
| 412 | 0.855919 | 1 | 0.855919 | game-dev | MEDIA | 0.534736 | game-dev,scientific-computing | 0.978486 | 1 | 0.978486 |
ifcquery/ifcplusplus | 2,783 | IfcPlusPlus/src/ifcpp/IFC4X3/include/IfcTShapeProfileDef.h | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#pragma once
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"
#include "IfcParameterizedProfileDef.h"
namespace IFC4X3
{
class IFCQUERY_EXPORT IfcPositiveLengthMeasure;
class IFCQUERY_EXPORT IfcNonNegativeLengthMeasure;
class IFCQUERY_EXPORT IfcPlaneAngleMeasure;
//ENTITY
class IFCQUERY_EXPORT IfcTShapeProfileDef : public IfcParameterizedProfileDef
{
public:
IfcTShapeProfileDef() = default;
IfcTShapeProfileDef( int id );
virtual void getStepLine( std::stringstream& stream, size_t precision ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type, size_t precision ) const;
virtual void readStepArguments( const std::vector<std::string>& args, const BuildingModelMapType<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream, std::unordered_set<int>& entityIdNotFound );
virtual void setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self );
virtual uint8_t getNumAttributes() const { return 12; }
virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const;
virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const;
virtual void unlinkFromInverseCounterparts();
virtual uint32_t classID() const { return 3071757647; }
// IfcProfileDef -----------------------------------------------------------
// attributes:
// shared_ptr<IfcProfileTypeEnum> m_ProfileType;
// shared_ptr<IfcLabel> m_ProfileName; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcExternalReferenceRelationship> > m_HasExternalReference_inverse;
// std::vector<weak_ptr<IfcProfileProperties> > m_HasProperties_inverse;
// IfcParameterizedProfileDef -----------------------------------------------------------
// attributes:
// shared_ptr<IfcAxis2Placement2D> m_Position; //optional
// IfcTShapeProfileDef -----------------------------------------------------------
// attributes:
shared_ptr<IfcPositiveLengthMeasure> m_Depth;
shared_ptr<IfcPositiveLengthMeasure> m_FlangeWidth;
shared_ptr<IfcPositiveLengthMeasure> m_WebThickness;
shared_ptr<IfcPositiveLengthMeasure> m_FlangeThickness;
shared_ptr<IfcNonNegativeLengthMeasure> m_FilletRadius; //optional
shared_ptr<IfcNonNegativeLengthMeasure> m_FlangeEdgeRadius; //optional
shared_ptr<IfcNonNegativeLengthMeasure> m_WebEdgeRadius; //optional
shared_ptr<IfcPlaneAngleMeasure> m_WebSlope; //optional
shared_ptr<IfcPlaneAngleMeasure> m_FlangeSlope; //optional
};
}
| 412 | 0.913573 | 1 | 0.913573 | game-dev | MEDIA | 0.355637 | game-dev | 0.50566 | 1 | 0.50566 |
liyunfan1223/mod-playerbots | 5,952 | src/strategy/actions/GenericBuffUtils.cpp | /*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license, you may redistribute it
* and/or modify it under version 3 of the License, or (at your option), any later version.
*/
#include "GenericBuffUtils.h"
#include "PlayerbotAIConfig.h"
#include <map>
#include "Player.h"
#include "Group.h"
#include "SpellMgr.h"
#include "Chat.h"
#include "PlayerbotAI.h"
#include "ServerFacade.h"
#include "AiObjectContext.h"
#include "Value.h"
#include "Config.h"
#include "PlayerbotTextMgr.h"
namespace ai::buff
{
std::string MakeAuraQualifierForBuff(std::string const& name)
{
// Paladin
if (name == "blessing of kings") return "blessing of kings,greater blessing of kings";
if (name == "blessing of might") return "blessing of might,greater blessing of might";
if (name == "blessing of wisdom") return "blessing of wisdom,greater blessing of wisdom";
if (name == "blessing of sanctuary") return "blessing of sanctuary,greater blessing of sanctuary";
// Druid
if (name == "mark of the wild") return "mark of the wild,gift of the wild";
// Mage
if (name == "arcane intellect") return "arcane intellect,arcane brilliance";
// Priest
if (name == "power word: fortitude") return "power word: fortitude,prayer of fortitude";
return name;
}
std::string GroupVariantFor(std::string const& name)
{
// Paladin
if (name == "blessing of kings") return "greater blessing of kings";
if (name == "blessing of might") return "greater blessing of might";
if (name == "blessing of wisdom") return "greater blessing of wisdom";
if (name == "blessing of sanctuary") return "greater blessing of sanctuary";
// Druid
if (name == "mark of the wild") return "gift of the wild";
// Mage
if (name == "arcane intellect") return "arcane brilliance";
// Priest
if (name == "power word: fortitude") return "prayer of fortitude";
return std::string();
}
bool HasRequiredReagents(Player* bot, uint32 spellId)
{
if (!spellId)
return false;
if (SpellInfo const* info = sSpellMgr->GetSpellInfo(spellId))
{
for (int i = 0; i < MAX_SPELL_REAGENTS; ++i)
{
if (info->Reagent[i] > 0)
{
uint32 const itemId = info->Reagent[i];
int32 const need = info->ReagentCount[i];
if ((int32)bot->GetItemCount(itemId, false) < need)
return false;
}
}
// No reagent required
return true;
}
return false;
}
std::string UpgradeToGroupIfAppropriate(
Player* bot,
PlayerbotAI* botAI,
std::string const& baseName,
bool announceOnMissing,
std::function<void(std::string const&)> announce)
{
std::string castName = baseName;
Group* g = bot->GetGroup();
if (!g || g->GetMembersCount() < static_cast<uint32>(sPlayerbotAIConfig->minBotsForGreaterBuff))
return castName; // Group too small: stay in solo mode
if (std::string const groupName = GroupVariantFor(baseName); !groupName.empty())
{
uint32 const groupVariantSpellId = botAI->GetAiObjectContext()
->GetValue<uint32>("spell id", groupName)->Get();
// We check usefulness on the **basic** buff (not the greater version),
// because "spell cast useful" may return false for the greater variant.
bool const usefulBase = botAI->GetAiObjectContext()
->GetValue<bool>("spell cast useful", baseName)->Get();
if (groupVariantSpellId && HasRequiredReagents(bot, groupVariantSpellId))
{
// Learned + reagents OK -> switch to greater
return groupName;
}
// Missing reagents -> announce if (a) greater is known, (b) base buff is useful,
// (c) announce was requested, (d) a callback is provided.
if (announceOnMissing && groupVariantSpellId && usefulBase && announce)
{
static std::map<std::pair<uint32, std::string>, time_t> s_lastWarn; // par bot & par buff
time_t now = std::time(nullptr);
uint32 botLow = static_cast<uint32>(bot->GetGUID().GetCounter());
time_t& last = s_lastWarn[ std::make_pair(botLow, groupName) ];
if (!last || now - last >= sPlayerbotAIConfig->rpWarningCooldown) // Configurable anti-spam
{
// DB Key choice in regard of the buff
std::string key;
if (groupName.find("greater blessing") != std::string::npos)
key = "rp_missing_reagent_greater_blessing";
else if (groupName == "gift of the wild")
key = "rp_missing_reagent_gift_of_the_wild";
else if (groupName == "arcane brilliance")
key = "rp_missing_reagent_arcane_brilliance";
else
key = "rp_missing_reagent_generic";
// Placeholders
std::map<std::string, std::string> placeholders;
placeholders["%group_spell"] = groupName;
placeholders["%base_spell"] = baseName;
std::string announceText = sPlayerbotTextMgr->GetBotTextOrDefault(key,
"Out of components for %group_spell. Using %base_spell!", placeholders);
announce(announceText);
last = now;
}
}
}
return castName;
}
}
| 412 | 0.939486 | 1 | 0.939486 | game-dev | MEDIA | 0.58154 | game-dev | 0.978106 | 1 | 0.978106 |
GValiente/butano | 13,315 | butano/src/bn_regular_bg_map_ptr.cpp.h | /*
* Copyright (c) 2020-2025 Gustavo Valiente gustavo.valiente@protonmail.com
* zlib License, see LICENSE file.
*/
#include "bn_regular_bg_map_ptr.h"
#include "bn_bg_palette_ptr.h"
#include "bn_regular_bg_item.h"
#include "bn_bg_blocks_manager.h"
#include "bn_regular_bg_tiles_ptr.h"
namespace bn
{
optional<regular_bg_map_ptr> regular_bg_map_ptr::find(
const regular_bg_map_item& map_item, const regular_bg_tiles_ptr& tiles, const bg_palette_ptr& palette)
{
int handle = bg_blocks_manager::find_regular_map(map_item, map_item.cells_ptr(), tiles, palette);
optional<regular_bg_map_ptr> result;
if(handle >= 0)
{
result = regular_bg_map_ptr(handle);
}
return result;
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::find(
const regular_bg_map_item& map_item, const regular_bg_tiles_ptr& tiles, const bg_palette_ptr& palette,
int map_index)
{
int handle = bg_blocks_manager::find_regular_map(map_item, map_item.cells_ptr(map_index), tiles, palette);
optional<regular_bg_map_ptr> result;
if(handle >= 0)
{
result = regular_bg_map_ptr(handle);
}
return result;
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::find(const regular_bg_item& item)
{
optional<regular_bg_tiles_ptr> tiles = regular_bg_tiles_ptr::find(item.tiles_item());
optional<regular_bg_map_ptr> result;
if(regular_bg_tiles_ptr* tiles_ptr = tiles.get())
{
optional<bg_palette_ptr> palette = bg_palette_ptr::find(item.palette_item());
if(bg_palette_ptr* palette_ptr = palette.get())
{
result = find(item.map_item(), *tiles_ptr, *palette_ptr);
}
}
return result;
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::find(const regular_bg_item& item, int map_index)
{
optional<regular_bg_tiles_ptr> tiles = regular_bg_tiles_ptr::find(item.tiles_item());
optional<regular_bg_map_ptr> result;
if(regular_bg_tiles_ptr* tiles_ptr = tiles.get())
{
optional<bg_palette_ptr> palette = bg_palette_ptr::find(item.palette_item());
if(bg_palette_ptr* palette_ptr = palette.get())
{
result = find(item.map_item(), *tiles_ptr, *palette_ptr, map_index);
}
}
return result;
}
regular_bg_map_ptr regular_bg_map_ptr::create(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette)
{
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(), move(tiles), move(palette), false);
return regular_bg_map_ptr(handle);
}
regular_bg_map_ptr regular_bg_map_ptr::create(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette, int map_index)
{
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(map_index), move(tiles), move(palette), false);
return regular_bg_map_ptr(handle);
}
regular_bg_map_ptr regular_bg_map_ptr::create(const regular_bg_item& item)
{
const regular_bg_map_item& map_item = item.map_item();
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(), regular_bg_tiles_ptr::create(item.tiles_item()),
bg_palette_ptr::create(item.palette_item()), false);
return regular_bg_map_ptr(handle);
}
regular_bg_map_ptr regular_bg_map_ptr::create(const regular_bg_item& item, int map_index)
{
const regular_bg_map_item& map_item = item.map_item();
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(map_index), regular_bg_tiles_ptr::create(item.tiles_item()),
bg_palette_ptr::create(item.palette_item()), false);
return regular_bg_map_ptr(handle);
}
regular_bg_map_ptr regular_bg_map_ptr::create_new(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette)
{
return create(map_item, move(tiles), move(palette));
}
regular_bg_map_ptr regular_bg_map_ptr::create_new(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette, int map_index)
{
return create(map_item, move(tiles), move(palette), map_index);
}
regular_bg_map_ptr regular_bg_map_ptr::allocate(
const size& dimensions, regular_bg_tiles_ptr tiles, bg_palette_ptr palette)
{
int handle = bg_blocks_manager::allocate_regular_map(dimensions, move(tiles), move(palette), false);
return regular_bg_map_ptr(handle);
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::create_optional(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette)
{
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(), move(tiles), move(palette), true);
optional<regular_bg_map_ptr> result;
if(handle >= 0)
{
result = regular_bg_map_ptr(handle);
}
return result;
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::create_optional(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette, int map_index)
{
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(map_index), move(tiles), move(palette), true);
optional<regular_bg_map_ptr> result;
if(handle >= 0)
{
result = regular_bg_map_ptr(handle);
}
return result;
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::create_optional(const regular_bg_item& item)
{
optional<regular_bg_tiles_ptr> tiles = regular_bg_tiles_ptr::create_optional(item.tiles_item());
optional<regular_bg_map_ptr> result;
if(regular_bg_tiles_ptr* tiles_ptr = tiles.get())
{
optional<bg_palette_ptr> palette = bg_palette_ptr::create_optional(item.palette_item());
if(bg_palette_ptr* palette_ptr = palette.get())
{
const regular_bg_map_item& map_item = item.map_item();
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(), move(*tiles_ptr), move(*palette_ptr), true);
if(handle >= 0)
{
result = regular_bg_map_ptr(handle);
}
}
}
return result;
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::create_optional(const regular_bg_item& item, int map_index)
{
optional<regular_bg_tiles_ptr> tiles = regular_bg_tiles_ptr::create_optional(item.tiles_item());
optional<regular_bg_map_ptr> result;
if(regular_bg_tiles_ptr* tiles_ptr = tiles.get())
{
optional<bg_palette_ptr> palette = bg_palette_ptr::create_optional(item.palette_item());
if(bg_palette_ptr* palette_ptr = palette.get())
{
const regular_bg_map_item& map_item = item.map_item();
int handle = bg_blocks_manager::create_regular_map(
map_item, map_item.cells_ptr(map_index), move(*tiles_ptr), move(*palette_ptr), true);
if(handle >= 0)
{
result = regular_bg_map_ptr(handle);
}
}
}
return result;
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::create_new_optional(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette)
{
return create_optional(map_item, move(tiles), move(palette));
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::create_new_optional(
const regular_bg_map_item& map_item, regular_bg_tiles_ptr tiles, bg_palette_ptr palette, int map_index)
{
return create_optional(map_item, move(tiles), move(palette), map_index);
}
optional<regular_bg_map_ptr> regular_bg_map_ptr::allocate_optional(
const size& dimensions, regular_bg_tiles_ptr tiles, bg_palette_ptr palette)
{
int handle = bg_blocks_manager::allocate_regular_map(dimensions, move(tiles), move(palette), true);
optional<regular_bg_map_ptr> result;
if(handle >= 0)
{
result = regular_bg_map_ptr(handle);
}
return result;
}
regular_bg_map_ptr::regular_bg_map_ptr(const regular_bg_map_ptr& other) :
regular_bg_map_ptr(other._handle)
{
bg_blocks_manager::increase_usages(_handle);
}
regular_bg_map_ptr& regular_bg_map_ptr::operator=(const regular_bg_map_ptr& other)
{
if(_handle != other._handle)
{
if(_handle >= 0)
{
bg_blocks_manager::decrease_usages(_handle);
}
_handle = other._handle;
bg_blocks_manager::increase_usages(_handle);
}
return *this;
}
regular_bg_map_ptr::~regular_bg_map_ptr()
{
if(_handle >= 0)
{
bg_blocks_manager::decrease_usages(_handle);
}
}
int regular_bg_map_ptr::id() const
{
return bg_blocks_manager::hw_id(_handle);
}
size regular_bg_map_ptr::dimensions() const
{
return bg_blocks_manager::map_dimensions(_handle);
}
bool regular_bg_map_ptr::big() const
{
return bg_blocks_manager::big_map(_handle);
}
bpp_mode regular_bg_map_ptr::bpp() const
{
return palette().bpp();
}
int regular_bg_map_ptr::tiles_offset() const
{
return bg_blocks_manager::regular_tiles_offset(_handle);
}
int regular_bg_map_ptr::palette_banks_offset() const
{
return bg_blocks_manager::palette_offset(_handle);
}
compression_type regular_bg_map_ptr::compression() const
{
return bg_blocks_manager::compression(_handle);
}
optional<span<const regular_bg_map_cell>> regular_bg_map_ptr::cells_ref() const
{
return bg_blocks_manager::regular_map_cells_ref(_handle);
}
void regular_bg_map_ptr::set_cells_ref(const regular_bg_map_item& map_item)
{
bg_blocks_manager::set_regular_map_cells_ref(_handle, map_item, map_item.cells_ptr());
}
void regular_bg_map_ptr::set_cells_ref(const regular_bg_map_item& map_item, int map_index)
{
bg_blocks_manager::set_regular_map_cells_ref(_handle, map_item, map_item.cells_ptr(map_index));
}
void regular_bg_map_ptr::reload_cells_ref()
{
bg_blocks_manager::reload(_handle);
}
const regular_bg_tiles_ptr& regular_bg_map_ptr::tiles() const
{
return bg_blocks_manager::regular_map_tiles(_handle);
}
void regular_bg_map_ptr::set_tiles(const regular_bg_tiles_ptr& tiles)
{
bg_blocks_manager::set_regular_map_tiles(_handle, regular_bg_tiles_ptr(tiles));
}
void regular_bg_map_ptr::set_tiles(regular_bg_tiles_ptr&& tiles)
{
bg_blocks_manager::set_regular_map_tiles(_handle, move(tiles));
}
void regular_bg_map_ptr::set_tiles(const regular_bg_tiles_item& tiles_item)
{
optional<regular_bg_tiles_ptr> tiles = tiles_item.find_tiles();
if(regular_bg_tiles_ptr* tiles_ptr = tiles.get())
{
bg_blocks_manager::set_regular_map_tiles(_handle, move(*tiles_ptr));
}
else
{
bg_blocks_manager::remove_regular_map_tiles(_handle);
bg_blocks_manager::set_regular_map_tiles(_handle, regular_bg_tiles_ptr::create(tiles_item));
}
}
const bg_palette_ptr& regular_bg_map_ptr::palette() const
{
return bg_blocks_manager::map_palette(_handle);
}
void regular_bg_map_ptr::set_palette(const bg_palette_ptr& palette)
{
bg_blocks_manager::set_regular_map_palette(_handle, bg_palette_ptr(palette));
}
void regular_bg_map_ptr::set_palette(bg_palette_ptr&& palette)
{
bg_blocks_manager::set_regular_map_palette(_handle, move(palette));
}
void regular_bg_map_ptr::set_palette(const bg_palette_item& palette_item)
{
if(palette_item.bpp() == bpp_mode::BPP_4 || bpp() == bpp_mode::BPP_4)
{
optional<bg_palette_ptr> palette = palette_item.find_palette();
if(bg_palette_ptr* palette_ptr = palette.get())
{
bg_blocks_manager::set_regular_map_palette(_handle, move(*palette_ptr));
}
else
{
bg_blocks_manager::remove_map_palette(_handle);
bg_blocks_manager::set_regular_map_palette(_handle, bg_palette_ptr::create_new(palette_item));
}
}
else
{
bg_blocks_manager::set_regular_map_palette(_handle, bg_palette_ptr::create(palette_item));
}
}
void regular_bg_map_ptr::set_tiles_and_palette(regular_bg_tiles_ptr tiles, bg_palette_ptr palette)
{
bg_blocks_manager::set_regular_map_tiles_and_palette(_handle, move(tiles), move(palette));
}
void regular_bg_map_ptr::set_tiles_and_palette(const regular_bg_tiles_item& tiles_item,
const bg_palette_item& palette_item)
{
optional<regular_bg_tiles_ptr> tiles = tiles_item.find_tiles();
regular_bg_tiles_ptr* tiles_ptr = tiles.get();
if(! tiles_ptr)
{
bg_blocks_manager::remove_regular_map_tiles(_handle);
tiles = regular_bg_tiles_ptr::create(tiles_item);
tiles_ptr = tiles.get();
}
optional<bg_palette_ptr> palette = palette_item.find_palette();
bg_palette_ptr* palette_ptr = palette.get();
if(! palette_ptr)
{
if(palette_item.bpp() == bpp_mode::BPP_4 || bpp() == bpp_mode::BPP_4)
{
bg_blocks_manager::remove_map_palette(_handle);
}
palette = bg_palette_ptr::create_new(palette_item);
palette_ptr = palette.get();
}
bg_blocks_manager::set_regular_map_tiles_and_palette(_handle, move(*tiles_ptr), move(*palette_ptr));
}
optional<span<regular_bg_map_cell>> regular_bg_map_ptr::vram()
{
return bg_blocks_manager::regular_map_vram(_handle);
}
}
| 412 | 0.979611 | 1 | 0.979611 | game-dev | MEDIA | 0.338296 | game-dev | 0.657434 | 1 | 0.657434 |
amazon-gamelift/amazon-gamelift-plugin-unreal | 1,304 | Scripts/cleanup.sh | #!/bin/bash
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
set -e
SCRIPT_BASE_PATH=$(pwd)
rm -rf "$SCRIPT_BASE_PATH/Out"
rm -rf "$SCRIPT_BASE_PATH/GameLiftServerSDK/Source/GameLiftServerSDK/Private/aws"
[ -d "$SCRIPT_BASE_PATH/Temp" ] && find "$SCRIPT_BASE_PATH/Temp" -mindepth 1 -type d ! -name 'downloads' -exec rm -rf {} + || true
[ -d "$SCRIPT_BASE_PATH/Temp/downloads" ] && find "$SCRIPT_BASE_PATH/Temp/downloads" -mindepth 1 ! -name 'GameLift-Cpp-ServerSDK.zip' -exec rm -rf {} + || true
[ -d "$SCRIPT_BASE_PATH/GameLiftServerSDK/ThirdParty" ] && find "$SCRIPT_BASE_PATH/GameLiftServerSDK/ThirdParty" -mindepth 1 ! -name '.gitkeep' -exec rm -rf {} + || true
[ -d "$SCRIPT_BASE_PATH/GameLiftPlugin/Source/GameLiftServer/ThirdParty" ] && find "$SCRIPT_BASE_PATH/GameLiftPlugin/Source/GameLiftServer/ThirdParty" -mindepth 1 ! -name '.gitkeep' -exec rm -rf {} + || true
[ -d "$SCRIPT_BASE_PATH/GameLiftPlugin/Source/GameLiftServer" ] && find "$SCRIPT_BASE_PATH/GameLiftPlugin/Source/GameLiftServer" -mindepth 1 -type d ! -name 'ThirdParty' -exec rm -rf {} + || true
[ -d "$SCRIPT_BASE_PATH/GameLiftPlugin/Source/GameLiftServer" ] && find "$SCRIPT_BASE_PATH/GameLiftPlugin/Source/GameLiftServer" -maxdepth 1 -type f -exec rm -f {} + || true | 412 | 0.946112 | 1 | 0.946112 | game-dev | MEDIA | 0.592336 | game-dev | 0.63828 | 1 | 0.63828 |
jjbali/Extended-Experienced-PD | 5,995 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/custom/buffs/AttributeModifier.java | package com.shatteredpixel.shatteredpixeldungeon.custom.buffs;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.FlavourBuff;
import com.shatteredpixel.shatteredpixeldungeon.custom.utils.GME;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.ui.BuffIndicator;
import com.watabou.utils.Bundle;
public class AttributeModifier extends FlavourBuff {
{
type = buffType.NEUTRAL;
announced = true;
}
public float atk_m = 1f;
public float def_m = 1f;
public float acc_m = 1f;
public float eva_m = 1f;
public float dmg_m = 1f;
public float hp_m = 1f;
public float atk_l = 0f;
public float def_l = 0f;
public float acc_l = 0f;
public float eva_l = 0f;
public float dmg_l = 0f;
public float hp_l = 0f;
public long orig_HT = -1;
public void merge(AttributeModifier another){
atk_m *= another.atk_m;
def_m *= another.def_m;
acc_m *= another.acc_m;
eva_m *= another.eva_m;
dmg_m *= another.dmg_m;
hp_m *= another.hp_m;
atk_l += another.atk_l;
def_l += another.def_l;
acc_l += another.acc_l;
eva_l += another.eva_l;
dmg_l += another.dmg_l;
hp_l += another.hp_l;
}
public int affectAtk(float attackPower){
return GME.accurateRound(attackPower * atk_m + atk_l);
}
public int affectDef(float defensePower){
return GME.accurateRound(defensePower * def_m + def_l);
}
public float affectAcc(float accuracy){
return accuracy * acc_m + acc_l;
}
public float affectEva(float evasion){
return evasion * eva_m + eva_l;
}
public int affectDmg(float damage){
return GME.accurateRound(damage * dmg_m + dmg_l);
}
public void affectHp(Char ch){
float percent = (float) ch.HP / ch.HT;
//HT of Char is bundled, need to roll back first
if(orig_HT < 0) {
orig_HT = ch.HT;
}else{
ch.HT = orig_HT;
}
ch.HT = (int)(ch.HT * hp_m + hp_l);
if(ch.HT <= 0){
ch.HT = 1;
}
ch.HP = GME.accurateRound(ch.HT * percent);
if(ch.HP <= 0){
ch.HP = 1;
}
}
public void setHPBack(Char ch){
float percent = (float) ch.HP / ch.HT;
ch.HT = orig_HT;
boolean alive = ch.isAlive();
ch.HP = GME.accurateRound(ch.HT * percent);
if(ch.HP <= 0 && alive) ch.HP = 1;
}
public AttributeModifier setAtk(float m, float l){
atk_m = m; atk_l = l;
return this;
}
public AttributeModifier setDef(float m, float l){
def_m = m; def_l = l;
return this;
}
public AttributeModifier setAcc(float m, float l){
acc_m = m; acc_l = l;
return this;
}
public AttributeModifier setEva(float m, float l){
eva_m = m; eva_l = l;
return this;
}
public AttributeModifier setDmg(float m, float l){
dmg_m = m; dmg_l = l;
return this;
}
public AttributeModifier setHP(float m, float l){
hp_m = m; hp_l = l;
if(target != null){
affectHp(target);
}
return this;
}
public AttributeModifier setAll(float[] mul, float[] add){
atk_m = mul[0];
def_m = mul[1];
acc_m = mul[2];
eva_m = mul[3];
dmg_m = mul[4];
hp_m = mul[5];
atk_l = add[0];
def_l = add[1];
acc_l = add[2];
eva_l = add[3];
dmg_l = add[4];
hp_l = add[5];
if(target != null){
affectHp(target);
}
return this;
}
@Override
public boolean attachTo(Char target) {
for(Buff b: target.buffs()){
if(b instanceof AttributeModifier){
merge((AttributeModifier) b);
b.detach();
}
}
boolean ret_val = super.attachTo(target);
if(ret_val){
affectHp(target);
}
return ret_val;
}
@Override
public void detach() {
setHPBack(target);
super.detach();
}
@Override
public int icon() {
return BuffIndicator.COMBO;
}
@Override
public String toString() {
return Messages.get(this, "name");
}
@Override
public String desc() {
return Messages.get(this, "desc", atk_m, atk_l, def_m, def_l, acc_m, acc_l, eva_m, eva_l, dmg_m, dmg_l, hp_m, hp_l, target.HP, target.HT);
}
@Override
public void storeInBundle(Bundle bundle) {
super.storeInBundle(bundle);
bundle.put("atk_mul", atk_m);
bundle.put("def_mul", def_m);
bundle.put("acc_mul", acc_m);
bundle.put("eva_mul", eva_m);
bundle.put("dmg_mul", dmg_m);
bundle.put("hp_mul", hp_m);
bundle.put("atk_lin", atk_l);
bundle.put("def_lin", def_l);
bundle.put("acc_lin", acc_l);
bundle.put("eva_lin", eva_l);
bundle.put("dmg_lin", dmg_l);
bundle.put("hp_lin", hp_l);
bundle.put("orig_hp", orig_HT);
}
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
atk_m = bundle.getFloat("atk_mul");
def_m = bundle.getFloat("def_mul");
acc_m = bundle.getFloat("acc_mul");
eva_m = bundle.getFloat("eva_mul");
dmg_m = bundle.getFloat("dmg_mul");
hp_m = bundle.getFloat("hp_mul");
atk_l = bundle.getFloat("atk_lin");
def_l = bundle.getFloat("def_lin");
acc_l = bundle.getFloat("acc_lin");
eva_l = bundle.getFloat("eva_lin");
dmg_l = bundle.getFloat("dmg_lin");
hp_l = bundle.getFloat("hp_lin");
orig_HT = bundle.getInt("orig_hp");
}
}
| 412 | 0.854603 | 1 | 0.854603 | game-dev | MEDIA | 0.958918 | game-dev | 0.927571 | 1 | 0.927571 |
wxyanxw/Go2-EDU-Mycobot-320-M5-Gazebo-Simulation-with-Navigation-and-MoveIt | 2,901 | go2_mycobot_sim_2.0/unitree_sim/unitree_guide/unitree_guide/src/FSM/State_StepTest.cpp | /**********************************************************************
Copyright (c) 2020-2023, Unitree Robotics.Co.Ltd. All rights reserved.
***********************************************************************/
#include "FSM/State_StepTest.h"
State_StepTest::State_StepTest(CtrlComponents *ctrlComp)
:FSMState(ctrlComp, FSMStateName::STEPTEST, "stepTest"),
_est(ctrlComp->estimator), _robModel(ctrlComp->robotModel),
_balCtrl(ctrlComp->balCtrl), _contact(ctrlComp->contact),
_phase(ctrlComp->phase){
_gaitHeight = 0.05;
_KpSwing = Vec3(600, 600, 200).asDiagonal();
_KdSwing = Vec3(20, 20, 5).asDiagonal();
_Kpp = Vec3(50, 50, 300).asDiagonal();
_Kpw = Vec3(600, 600, 600).asDiagonal();
_Kdp = Vec3(5, 5, 20).asDiagonal();
_Kdw = Vec3(10, 10, 10).asDiagonal();
}
void State_StepTest::enter(){
_pcd = _est->getPosition();
_Rd = _lowState->getRotMat();
_posFeetGlobalInit = _est->getFeetPos();
_posFeetGlobalGoal = _posFeetGlobalInit;
_ctrlComp->setStartWave();
_ctrlComp->ioInter->zeroCmdPanel();
}
void State_StepTest::run(){
_posBody = _est->getPosition();
_velBody = _est->getVelocity();
_B2G_RotMat = _lowState->getRotMat();
_G2B_RotMat = _B2G_RotMat.transpose();
for(int i(0); i<4; ++i){
if((*_contact)(i) == 0){
_posFeetGlobalGoal(2, i) = _posFeetGlobalInit(2, i) + (1-cos((*_phase)(i)*2*M_PI))*_gaitHeight;
_velFeetGlobalGoal(2, i) = sin((*_phase)(i)*2*M_PI)*2*M_PI*_gaitHeight;
}
}
calcTau();
_lowCmd->setZeroGain();
_lowCmd->setTau(_tau);
}
void State_StepTest::exit(){
_ctrlComp->ioInter->zeroCmdPanel();
_ctrlComp->setAllSwing();
}
FSMStateName State_StepTest::checkChange(){
if(_lowState->userCmd == UserCommand::L2_B){
return FSMStateName::PASSIVE;
}
else if(_lowState->userCmd == UserCommand::L2_A){
return FSMStateName::FIXEDSTAND;
}
else{
return FSMStateName::STEPTEST;
}
}
void State_StepTest::calcTau(){
_ddPcd = _Kpp*(_pcd - _posBody) + _Kdp * (Vec3(0, 0, 0) - _velBody);
_dWbd = _Kpw*rotMatToExp(_Rd*_G2B_RotMat) + _Kdw * (Vec3(0, 0, 0) - _lowState->getGyroGlobal());
_posFeet2BGlobal = _est->getPosFeet2BGlobal();
_forceFeetGlobal = - _balCtrl->calF(_ddPcd, _dWbd, _B2G_RotMat, _posFeet2BGlobal, *_contact);
_posFeetGlobal = _est->getFeetPos();
_velFeetGlobal = _est->getFeetVel();
for(int i(0); i<4; ++i){
if((*_contact)(i) == 0){
_forceFeetGlobal.col(i) = _KpSwing*(_posFeetGlobalGoal.col(i) - _posFeetGlobal.col(i)) + _KdSwing*(_velFeetGlobalGoal.col(i)-_velFeetGlobal.col(i));
}
}
_forceFeetBody = _G2B_RotMat * _forceFeetGlobal;
_q = vec34ToVec12(_lowState->getQ());
_tau = _robModel->getTau(_q, _forceFeetBody);
} | 412 | 0.712704 | 1 | 0.712704 | game-dev | MEDIA | 0.484727 | game-dev,testing-qa | 0.914672 | 1 | 0.914672 |
walkline/ToCloud9 | 3,853 | apps/matchmakingserver/service/battleground_service_test.go | package service
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/walkline/ToCloud9/shared/wow/guid"
)
func TestRemoveBattlegroundLinkForPlayer(t *testing.T) {
// Initialize the service
service := &battleGroundService{
playersQueueOrBattleground: make(map[QueuesByRealmAndPlayerKey][]QueueOrBattlegroundLink),
}
// Prepare test data
playerGUID := uint64(12345)
realmID := uint32(1)
bgKeyToRemove := BattlegroundKey{InstanceID: 101, RealmID: 1}
otherBgKey := BattlegroundKey{InstanceID: 102, RealmID: 1}
service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: uint16(realmID),
LowGUID: guid.LowType(playerGUID),
},
}] = []QueueOrBattlegroundLink{
{BattlegroundKey: &bgKeyToRemove, Queue: nil},
{BattlegroundKey: &otherBgKey, Queue: nil},
}
// Call the function to remove the link
service.removeBattlegroundLinkForPlayer(bgKeyToRemove, playerGUID, realmID)
// Validate results
remainingLinks := service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: uint16(realmID),
LowGUID: guid.LowType(playerGUID),
},
}]
assert.Len(t, remainingLinks, 1)
assert.Equal(t, otherBgKey, *remainingLinks[0].BattlegroundKey)
assert.Equal(t, nil, remainingLinks[0].Queue)
}
func TestRemoveQueueForGroupMembers(t *testing.T) {
// Initialize the service
service := &battleGroundService{
playersQueueOrBattleground: make(map[QueuesByRealmAndPlayerKey][]QueueOrBattlegroundLink),
}
// Prepare test data
player1 := uint64(12345)
player2 := uint64(67890)
leader := uint64(11111)
realmID := uint16(1)
queueToRemove := &GenericBattlegroundQueue{}
otherQueue := &GenericBattlegroundQueue{}
group := &QueuedGroup{
Members: []guid.PlayerUnwrapped{{RealmID: realmID, LowGUID: guid.LowType(player1)}, {RealmID: realmID, LowGUID: guid.LowType(player2)}},
LeaderGUID: guid.PlayerUnwrapped{RealmID: realmID, LowGUID: guid.LowType(leader)},
RealmID: uint32(realmID),
}
// Populate the map with links
service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(player1),
},
}] = []QueueOrBattlegroundLink{
{Queue: queueToRemove},
{Queue: otherQueue},
}
service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(player2),
},
}] = []QueueOrBattlegroundLink{
{Queue: queueToRemove},
}
service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(leader),
},
}] = []QueueOrBattlegroundLink{
{Queue: queueToRemove},
{Queue: otherQueue},
}
// Call the function
service.removeQueueForGroupMembers(queueToRemove, group)
// Validate results
// Player 1: QueueToRemove removed, OtherQueue remains
assert.Len(t, service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(player1),
},
}], 1)
assert.Equal(t, otherQueue, service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(player1),
},
}][0].Queue)
// Player 2: All links removed
assert.Len(t, service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(player2),
},
}], 0)
// Leader: QueueToRemove removed, OtherQueue remains
assert.Len(t, service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(leader),
},
}], 1)
assert.Equal(t, otherQueue, service.playersQueueOrBattleground[QueuesByRealmAndPlayerKey{
guid.PlayerUnwrapped{
RealmID: realmID,
LowGUID: guid.LowType(leader),
},
}][0].Queue)
}
| 412 | 0.567719 | 1 | 0.567719 | game-dev | MEDIA | 0.70065 | game-dev | 0.592317 | 1 | 0.592317 |
chen0040/java-reinforcement-learning | 4,194 | src/main/java/com/github/chen0040/rl/models/QModel.java | package com.github.chen0040.rl.models;
import com.github.chen0040.rl.utils.IndexValue;
import com.github.chen0040.rl.utils.Matrix;
import com.github.chen0040.rl.utils.Vec;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
/**
* @author xschen
* 9/27/2015 0027.
* Q is known as the quality of state-action combination, note that it is different from utility of a state
*/
@Getter
@Setter
public class QModel {
/**
* Q value for (state_id, action_id) pair
* Q is known as the quality of state-action combination, note that it is different from utility of a state
*/
private Matrix Q;
/**
* $\alpha[s, a]$ value for learning rate: alpha(state_id, action_id)
*/
private Matrix alphaMatrix;
/**
* discount factor
*/
private double gamma = 0.7;
private int stateCount;
private int actionCount;
public QModel(int stateCount, int actionCount, double initialQ){
this.stateCount = stateCount;
this.actionCount = actionCount;
Q = new Matrix(stateCount,actionCount);
alphaMatrix = new Matrix(stateCount, actionCount);
Q.setAll(initialQ);
alphaMatrix.setAll(0.1);
}
public QModel(int stateCount, int actionCount){
this(stateCount, actionCount, 0.1);
}
public QModel(){
}
@Override
public boolean equals(Object rhs){
if(rhs != null && rhs instanceof QModel){
QModel rhs2 = (QModel)rhs;
if(gamma != rhs2.gamma) return false;
if(stateCount != rhs2.stateCount || actionCount != rhs2.actionCount) return false;
if((Q!=null && rhs2.Q==null) || (Q==null && rhs2.Q !=null)) return false;
if((alphaMatrix !=null && rhs2.alphaMatrix ==null) || (alphaMatrix ==null && rhs2.alphaMatrix !=null)) return false;
return !((Q != null && !Q.equals(rhs2.Q)) || (alphaMatrix != null && !alphaMatrix.equals(rhs2.alphaMatrix)));
}
return false;
}
public QModel makeCopy(){
QModel clone = new QModel();
clone.copy(this);
return clone;
}
public void copy(QModel rhs){
gamma = rhs.gamma;
stateCount = rhs.stateCount;
actionCount = rhs.actionCount;
Q = rhs.Q==null ? null : rhs.Q.makeCopy();
alphaMatrix = rhs.alphaMatrix == null ? null : rhs.alphaMatrix.makeCopy();
}
public double getQ(int stateId, int actionId){
return Q.get(stateId, actionId);
}
public void setQ(int stateId, int actionId, double Qij){
Q.set(stateId, actionId, Qij);
}
public double getAlpha(int stateId, int actionId){
return alphaMatrix.get(stateId, actionId);
}
public void setAlpha(double defaultAlpha) {
this.alphaMatrix.setAll(defaultAlpha);
}
public IndexValue actionWithMaxQAtState(int stateId, Set<Integer> actionsAtState){
Vec rowVector = Q.rowAt(stateId);
return rowVector.indexWithMaxValue(actionsAtState);
}
private void reset(double initialQ){
Q.setAll(initialQ);
}
public IndexValue actionWithSoftMaxQAtState(int stateId,Set<Integer> actionsAtState, Random random) {
Vec rowVector = Q.rowAt(stateId);
double sum = 0;
if(actionsAtState==null){
actionsAtState = new HashSet<>();
for(int i=0; i < actionCount; ++i){
actionsAtState.add(i);
}
}
List<Integer> actions = new ArrayList<>();
for(Integer actionId : actionsAtState){
actions.add(actionId);
}
double[] acc = new double[actions.size()];
for(int i=0; i < actions.size(); ++i){
sum += rowVector.get(actions.get(i));
acc[i] = sum;
}
double r = random.nextDouble() * sum;
IndexValue result = new IndexValue();
for(int i=0; i < actions.size(); ++i){
if(acc[i] >= r){
int actionId = actions.get(i);
result.setIndex(actionId);
result.setValue(rowVector.get(actionId));
break;
}
}
return result;
}
}
| 412 | 0.91476 | 1 | 0.91476 | game-dev | MEDIA | 0.396665 | game-dev | 0.973086 | 1 | 0.973086 |
RS485/LogisticsPipes | 6,064 | src/main/kotlin/network/rs485/logisticspipes/compat/BarrelInventoryHandler.kt | /*
* Copyright (c) 2022 RS485
*
* "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public
* License 1.0.1, or MMPL. Please check the contents of the license located in
* https://github.com/RS485/LogisticsPipes/blob/dev/LICENSE.md
*
* This file can instead be distributed under the license terms of the
* MIT license:
*
* Copyright (c) 2022 RS485
*
* This MIT license was reworded to only match this file. If you use the regular
* MIT license in your project, replace this copyright notice (this line and any
* lines below and NOT the copyright line above) with the lines from the original
* MIT license located here: http://opensource.org/licenses/MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this file and associated documentation files (the "Source Code"), to deal in
* the Source Code without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Source Code, and to permit persons to whom the Source Code 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 Source Code, which also can be
* distributed under the MIT.
*
* 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 network.rs485.logisticspipes.compat
import logisticspipes.proxy.specialinventoryhandler.SpecialInventoryHandler
import logisticspipes.utils.item.ItemIdentifier
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.capabilities.CapabilityInject
import network.rs485.logisticspipes.inventory.ProviderMode
import pl.asie.charset.api.storage.IBarrel
class CharsetImplementationFactory : SpecialInventoryHandler.Factory {
companion object {
@JvmStatic
@CapabilityInject(IBarrel::class)
val barrelCapability: Capability<IBarrel>? = null
}
override fun init(): Boolean = true
override fun isType(tile: TileEntity, dir: EnumFacing?): Boolean = barrelCapability?.let { tile.hasCapability(it, dir) } ?: false
override fun getUtilForTile(
tile: TileEntity,
direction: EnumFacing?,
mode: ProviderMode
): SpecialInventoryHandler = BarrelInventoryHandler(tile.getCapability(barrelCapability!!, direction)!!, mode)
}
class BarrelInventoryHandler(val tile: IBarrel, val mode: ProviderMode) : SpecialInventoryHandler() {
override fun decrStackSize(slot: Int, amount: Int): ItemStack {
if (slot != 0) return ItemStack.EMPTY
return tile.extractItem(amount, false)
}
override fun containsUndamagedItem(item: ItemIdentifier): Boolean =
ItemIdentifier.get(getItem()).undamaged.equals(item)
override fun add(stack: ItemStack, orientation: EnumFacing?, doAdd: Boolean): ItemStack {
if (tile.shouldInsertToSide(orientation) && (isEmpty() || isValidItem(ItemIdentifier.get(stack)))) {
val leftover = tile.insertItem(stack, !doAdd)
return if (leftover.isEmpty) {
stack
} else {
assert(leftover.item == stack.item)
stack.copy().also { it.count -= leftover.count }
}
}
return stack
}
override fun getMultipleItems(itemIdent: ItemIdentifier, count: Int): ItemStack {
if (!isEmpty() && isValidItem(itemIdent)) {
if (itemCount(itemIdent) >= count) {
return tile.extractItem(count, false)
}
}
return ItemStack.EMPTY
}
override fun getSingleItem(itemIdent: ItemIdentifier): ItemStack = getMultipleItems(itemIdent, 1)
override fun getItems(): MutableSet<ItemIdentifier> = mutableSetOf(ItemIdentifier.get(getItem()))
override fun getItemsAndCount(): MutableMap<ItemIdentifier, Int> =
mutableMapOf(getIdentifier() to itemCount(getIdentifier()))
override fun getSizeInventory(): Int = 1
override fun getStackInSlot(slot: Int): ItemStack {
if (slot != 0) return ItemStack.EMPTY
val stack = getItem()
stack.count = itemCount(getIdentifier())
return if (stack.isEmpty) ItemStack.EMPTY
else stack
}
override fun roomForItem(stack: ItemStack): Int {
val identifier = ItemIdentifier.get(stack)
return if (isValidItem(identifier)) {
tile.maxItemCount - itemCount(identifier)
} else 0
}
override fun itemCount(itemIdent: ItemIdentifier): Int {
return if (!isEmpty() && isValidItem(itemIdent)) tile.itemCount.providerMode()
else 0
}
/**
* Correct amount for current provider mode.
*/
private fun Int.providerMode(): Int {
return if (mode.hideOnePerType || mode.hideOnePerStack) (this - 1)
else this
}
/**
* Checks if the barrel is empty.
*/
private fun isEmpty() = getItem().isEmpty
/**
* Checks if the item matches the one inside the barrel.
*/
private fun isValidItem(itemIdent: ItemIdentifier) = itemIdent.equals(ItemIdentifier.get(getItem()))
/**
* Returns an ItemStack with the same item as the one in the barrel.
*/
private fun getItem(): ItemStack = tile.extractItem(1, true)
/**
* Returns the ItemIdentifier from the getItem method.
*/
private fun getIdentifier(): ItemIdentifier = ItemIdentifier.get(getItem())
} | 412 | 0.946365 | 1 | 0.946365 | game-dev | MEDIA | 0.952746 | game-dev | 0.957233 | 1 | 0.957233 |
jmorton06/Lumos | 52,705 | Lumos/External/box2d/include/box2d/box2d.h | // SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "base.h"
#include "collision.h"
#include "id.h"
#include "types.h"
#include <stdbool.h>
/**
* @defgroup world World
* These functions allow you to create a simulation world.
*
* You can add rigid bodies and joint constraints to the world and run the simulation. You can get contact
* information to get contact points and normals as well as events. You can query to world, checking for overlaps and casting rays
* or shapes. There is also debugging information such as debug draw, timing information, and counters. You can find documentation
* here: https://box2d.org/
* @{
*/
/// Create a world for rigid body simulation. A world contains bodies, shapes, and constraints. You make create
/// up to 128 worlds. Each world is completely independent and may be simulated in parallel.
/// @return the world id.
B2_API b2WorldId b2CreateWorld( const b2WorldDef* def );
/// Destroy a world
B2_API void b2DestroyWorld( b2WorldId worldId );
/// World id validation. Provides validation for up to 64K allocations.
B2_API bool b2World_IsValid( b2WorldId id );
/// Simulate a world for one time step. This performs collision detection, integration, and constraint solution.
/// @param worldId The world to simulate
/// @param timeStep The amount of time to simulate, this should be a fixed number. Usually 1/60.
/// @param subStepCount The number of sub-steps, increasing the sub-step count can increase accuracy. Usually 4.
B2_API void b2World_Step( b2WorldId worldId, float timeStep, int subStepCount );
/// Call this to draw shapes and other debug draw data
B2_API void b2World_Draw( b2WorldId worldId, b2DebugDraw* draw );
/// Get the body events for the current time step. The event data is transient. Do not store a reference to this data.
B2_API b2BodyEvents b2World_GetBodyEvents( b2WorldId worldId );
/// Get sensor events for the current time step. The event data is transient. Do not store a reference to this data.
B2_API b2SensorEvents b2World_GetSensorEvents( b2WorldId worldId );
/// Get contact events for this current time step. The event data is transient. Do not store a reference to this data.
B2_API b2ContactEvents b2World_GetContactEvents( b2WorldId worldId );
/// Overlap test for all shapes that *potentially* overlap the provided AABB
B2_API b2TreeStats b2World_OverlapAABB( b2WorldId worldId, b2AABB aabb, b2QueryFilter filter, b2OverlapResultFcn* fcn,
void* context );
/// Overlap test for all shapes that overlap the provided shape proxy.
B2_API b2TreeStats b2World_OverlapShape( b2WorldId worldId, const b2ShapeProxy* proxy, b2QueryFilter filter,
b2OverlapResultFcn* fcn, void* context );
/// Cast a ray into the world to collect shapes in the path of the ray.
/// Your callback function controls whether you get the closest point, any point, or n-points.
/// The ray-cast ignores shapes that contain the starting point.
/// @note The callback function may receive shapes in any order
/// @param worldId The world to cast the ray against
/// @param origin The start point of the ray
/// @param translation The translation of the ray from the start point to the end point
/// @param filter Contains bit flags to filter unwanted shapes from the results
/// @param fcn A user implemented callback function
/// @param context A user context that is passed along to the callback function
/// @return traversal performance counters
B2_API b2TreeStats b2World_CastRay( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter,
b2CastResultFcn* fcn, void* context );
/// Cast a ray into the world to collect the closest hit. This is a convenience function.
/// This is less general than b2World_CastRay() and does not allow for custom filtering.
B2_API b2RayResult b2World_CastRayClosest( b2WorldId worldId, b2Vec2 origin, b2Vec2 translation, b2QueryFilter filter );
/// Cast a shape through the world. Similar to a cast ray except that a shape is cast instead of a point.
/// @see b2World_CastRay
B2_API b2TreeStats b2World_CastShape( b2WorldId worldId, const b2ShapeProxy* proxy, b2Vec2 translation, b2QueryFilter filter,
b2CastResultFcn* fcn, void* context );
/// Cast a capsule mover through the world. This is a special shape cast that handles sliding along other shapes while reducing
/// clipping.
B2_API float b2World_CastMover( b2WorldId worldId, const b2Capsule* mover, b2Vec2 translation, b2QueryFilter filter );
/// Collide a capsule mover with the world, gathering collision planes that can be fed to b2SolvePlanes. Useful for
/// kinematic character movement.
B2_API void b2World_CollideMover( b2WorldId worldId, const b2Capsule* mover, b2QueryFilter filter, b2PlaneResultFcn* fcn,
void* context );
/// Enable/disable sleep. If your application does not need sleeping, you can gain some performance
/// by disabling sleep completely at the world level.
/// @see b2WorldDef
B2_API void b2World_EnableSleeping( b2WorldId worldId, bool flag );
/// Is body sleeping enabled?
B2_API bool b2World_IsSleepingEnabled( b2WorldId worldId );
/// Enable/disable continuous collision between dynamic and static bodies. Generally you should keep continuous
/// collision enabled to prevent fast moving objects from going through static objects. The performance gain from
/// disabling continuous collision is minor.
/// @see b2WorldDef
B2_API void b2World_EnableContinuous( b2WorldId worldId, bool flag );
/// Is continuous collision enabled?
B2_API bool b2World_IsContinuousEnabled( b2WorldId worldId );
/// Adjust the restitution threshold. It is recommended not to make this value very small
/// because it will prevent bodies from sleeping. Usually in meters per second.
/// @see b2WorldDef
B2_API void b2World_SetRestitutionThreshold( b2WorldId worldId, float value );
/// Get the the restitution speed threshold. Usually in meters per second.
B2_API float b2World_GetRestitutionThreshold( b2WorldId worldId );
/// Adjust the hit event threshold. This controls the collision speed needed to generate a b2ContactHitEvent.
/// Usually in meters per second.
/// @see b2WorldDef::hitEventThreshold
B2_API void b2World_SetHitEventThreshold( b2WorldId worldId, float value );
/// Get the the hit event speed threshold. Usually in meters per second.
B2_API float b2World_GetHitEventThreshold( b2WorldId worldId );
/// Register the custom filter callback. This is optional.
B2_API void b2World_SetCustomFilterCallback( b2WorldId worldId, b2CustomFilterFcn* fcn, void* context );
/// Register the pre-solve callback. This is optional.
B2_API void b2World_SetPreSolveCallback( b2WorldId worldId, b2PreSolveFcn* fcn, void* context );
/// Set the gravity vector for the entire world. Box2D has no concept of an up direction and this
/// is left as a decision for the application. Usually in m/s^2.
/// @see b2WorldDef
B2_API void b2World_SetGravity( b2WorldId worldId, b2Vec2 gravity );
/// Get the gravity vector
B2_API b2Vec2 b2World_GetGravity( b2WorldId worldId );
/// Apply a radial explosion
/// @param worldId The world id
/// @param explosionDef The explosion definition
B2_API void b2World_Explode( b2WorldId worldId, const b2ExplosionDef* explosionDef );
/// Adjust contact tuning parameters
/// @param worldId The world id
/// @param hertz The contact stiffness (cycles per second)
/// @param dampingRatio The contact bounciness with 1 being critical damping (non-dimensional)
/// @param pushSpeed The maximum contact constraint push out speed (meters per second)
/// @note Advanced feature
B2_API void b2World_SetContactTuning( b2WorldId worldId, float hertz, float dampingRatio, float pushSpeed );
/// Adjust joint tuning parameters
/// @param worldId The world id
/// @param hertz The contact stiffness (cycles per second)
/// @param dampingRatio The contact bounciness with 1 being critical damping (non-dimensional)
/// @note Advanced feature
B2_API void b2World_SetJointTuning( b2WorldId worldId, float hertz, float dampingRatio );
/// Set the maximum linear speed. Usually in m/s.
B2_API void b2World_SetMaximumLinearSpeed( b2WorldId worldId, float maximumLinearSpeed );
/// Get the maximum linear speed. Usually in m/s.
B2_API float b2World_GetMaximumLinearSpeed( b2WorldId worldId );
/// Enable/disable constraint warm starting. Advanced feature for testing. Disabling
/// warm starting greatly reduces stability and provides no performance gain.
B2_API void b2World_EnableWarmStarting( b2WorldId worldId, bool flag );
/// Is constraint warm starting enabled?
B2_API bool b2World_IsWarmStartingEnabled( b2WorldId worldId );
/// Get the number of awake bodies.
B2_API int b2World_GetAwakeBodyCount( b2WorldId worldId );
/// Get the current world performance profile
B2_API b2Profile b2World_GetProfile( b2WorldId worldId );
/// Get world counters and sizes
B2_API b2Counters b2World_GetCounters( b2WorldId worldId );
/// Set the user data pointer.
B2_API void b2World_SetUserData( b2WorldId worldId, void* userData );
/// Get the user data pointer.
B2_API void* b2World_GetUserData( b2WorldId worldId );
/// Set the friction callback. Passing NULL resets to default.
B2_API void b2World_SetFrictionCallback( b2WorldId worldId, b2FrictionCallback* callback );
/// Set the restitution callback. Passing NULL resets to default.
B2_API void b2World_SetRestitutionCallback( b2WorldId worldId, b2RestitutionCallback* callback );
/// Dump memory stats to box2d_memory.txt
B2_API void b2World_DumpMemoryStats( b2WorldId worldId );
/// This is for internal testing
B2_API void b2World_RebuildStaticTree( b2WorldId worldId );
/// This is for internal testing
B2_API void b2World_EnableSpeculative( b2WorldId worldId, bool flag );
/** @} */
/**
* @defgroup body Body
* This is the body API.
* @{
*/
/// Create a rigid body given a definition. No reference to the definition is retained. So you can create the definition
/// on the stack and pass it as a pointer.
/// @code{.c}
/// b2BodyDef bodyDef = b2DefaultBodyDef();
/// b2BodyId myBodyId = b2CreateBody(myWorldId, &bodyDef);
/// @endcode
/// @warning This function is locked during callbacks.
B2_API b2BodyId b2CreateBody( b2WorldId worldId, const b2BodyDef* def );
/// Destroy a rigid body given an id. This destroys all shapes and joints attached to the body.
/// Do not keep references to the associated shapes and joints.
B2_API void b2DestroyBody( b2BodyId bodyId );
/// Body identifier validation. Can be used to detect orphaned ids. Provides validation for up to 64K allocations.
B2_API bool b2Body_IsValid( b2BodyId id );
/// Get the body type: static, kinematic, or dynamic
B2_API b2BodyType b2Body_GetType( b2BodyId bodyId );
/// Change the body type. This is an expensive operation. This automatically updates the mass
/// properties regardless of the automatic mass setting.
B2_API void b2Body_SetType( b2BodyId bodyId, b2BodyType type );
/// Set the body name. Up to 31 characters excluding 0 termination.
B2_API void b2Body_SetName( b2BodyId bodyId, const char* name );
/// Get the body name. May be null.
B2_API const char* b2Body_GetName( b2BodyId bodyId );
/// Set the user data for a body
B2_API void b2Body_SetUserData( b2BodyId bodyId, void* userData );
/// Get the user data stored in a body
B2_API void* b2Body_GetUserData( b2BodyId bodyId );
/// Get the world position of a body. This is the location of the body origin.
B2_API b2Vec2 b2Body_GetPosition( b2BodyId bodyId );
/// Get the world rotation of a body as a cosine/sine pair (complex number)
B2_API b2Rot b2Body_GetRotation( b2BodyId bodyId );
/// Get the world transform of a body.
B2_API b2Transform b2Body_GetTransform( b2BodyId bodyId );
/// Set the world transform of a body. This acts as a teleport and is fairly expensive.
/// @note Generally you should create a body with then intended transform.
/// @see b2BodyDef::position and b2BodyDef::angle
B2_API void b2Body_SetTransform( b2BodyId bodyId, b2Vec2 position, b2Rot rotation );
/// Get a local point on a body given a world point
B2_API b2Vec2 b2Body_GetLocalPoint( b2BodyId bodyId, b2Vec2 worldPoint );
/// Get a world point on a body given a local point
B2_API b2Vec2 b2Body_GetWorldPoint( b2BodyId bodyId, b2Vec2 localPoint );
/// Get a local vector on a body given a world vector
B2_API b2Vec2 b2Body_GetLocalVector( b2BodyId bodyId, b2Vec2 worldVector );
/// Get a world vector on a body given a local vector
B2_API b2Vec2 b2Body_GetWorldVector( b2BodyId bodyId, b2Vec2 localVector );
/// Get the linear velocity of a body's center of mass. Usually in meters per second.
B2_API b2Vec2 b2Body_GetLinearVelocity( b2BodyId bodyId );
/// Get the angular velocity of a body in radians per second
B2_API float b2Body_GetAngularVelocity( b2BodyId bodyId );
/// Set the linear velocity of a body. Usually in meters per second.
B2_API void b2Body_SetLinearVelocity( b2BodyId bodyId, b2Vec2 linearVelocity );
/// Set the angular velocity of a body in radians per second
B2_API void b2Body_SetAngularVelocity( b2BodyId bodyId, float angularVelocity );
/// Set the velocity to reach the given transform after a given time step.
/// The result will be close but maybe not exact. This is meant for kinematic bodies.
/// This will automatically wake the body if asleep.
B2_API void b2Body_SetTargetTransform( b2BodyId bodyId, b2Transform target, float timeStep );
/// Get the linear velocity of a local point attached to a body. Usually in meters per second.
B2_API b2Vec2 b2Body_GetLocalPointVelocity( b2BodyId bodyId, b2Vec2 localPoint );
/// Get the linear velocity of a world point attached to a body. Usually in meters per second.
B2_API b2Vec2 b2Body_GetWorldPointVelocity( b2BodyId bodyId, b2Vec2 worldPoint );
/// Apply a force at a world point. If the force is not applied at the center of mass,
/// it will generate a torque and affect the angular velocity. This optionally wakes up the body.
/// The force is ignored if the body is not awake.
/// @param bodyId The body id
/// @param force The world force vector, usually in newtons (N)
/// @param point The world position of the point of application
/// @param wake Option to wake up the body
B2_API void b2Body_ApplyForce( b2BodyId bodyId, b2Vec2 force, b2Vec2 point, bool wake );
/// Apply a force to the center of mass. This optionally wakes up the body.
/// The force is ignored if the body is not awake.
/// @param bodyId The body id
/// @param force the world force vector, usually in newtons (N).
/// @param wake also wake up the body
B2_API void b2Body_ApplyForceToCenter( b2BodyId bodyId, b2Vec2 force, bool wake );
/// Apply a torque. This affects the angular velocity without affecting the linear velocity.
/// This optionally wakes the body. The torque is ignored if the body is not awake.
/// @param bodyId The body id
/// @param torque about the z-axis (out of the screen), usually in N*m.
/// @param wake also wake up the body
B2_API void b2Body_ApplyTorque( b2BodyId bodyId, float torque, bool wake );
/// Apply an impulse at a point. This immediately modifies the velocity.
/// It also modifies the angular velocity if the point of application
/// is not at the center of mass. This optionally wakes the body.
/// The impulse is ignored if the body is not awake.
/// @param bodyId The body id
/// @param impulse the world impulse vector, usually in N*s or kg*m/s.
/// @param point the world position of the point of application.
/// @param wake also wake up the body
/// @warning This should be used for one-shot impulses. If you need a steady force,
/// use a force instead, which will work better with the sub-stepping solver.
B2_API void b2Body_ApplyLinearImpulse( b2BodyId bodyId, b2Vec2 impulse, b2Vec2 point, bool wake );
/// Apply an impulse to the center of mass. This immediately modifies the velocity.
/// The impulse is ignored if the body is not awake. This optionally wakes the body.
/// @param bodyId The body id
/// @param impulse the world impulse vector, usually in N*s or kg*m/s.
/// @param wake also wake up the body
/// @warning This should be used for one-shot impulses. If you need a steady force,
/// use a force instead, which will work better with the sub-stepping solver.
B2_API void b2Body_ApplyLinearImpulseToCenter( b2BodyId bodyId, b2Vec2 impulse, bool wake );
/// Apply an angular impulse. The impulse is ignored if the body is not awake.
/// This optionally wakes the body.
/// @param bodyId The body id
/// @param impulse the angular impulse, usually in units of kg*m*m/s
/// @param wake also wake up the body
/// @warning This should be used for one-shot impulses. If you need a steady force,
/// use a force instead, which will work better with the sub-stepping solver.
B2_API void b2Body_ApplyAngularImpulse( b2BodyId bodyId, float impulse, bool wake );
/// Get the mass of the body, usually in kilograms
B2_API float b2Body_GetMass( b2BodyId bodyId );
/// Get the rotational inertia of the body, usually in kg*m^2
B2_API float b2Body_GetRotationalInertia( b2BodyId bodyId );
/// Get the center of mass position of the body in local space
B2_API b2Vec2 b2Body_GetLocalCenterOfMass( b2BodyId bodyId );
/// Get the center of mass position of the body in world space
B2_API b2Vec2 b2Body_GetWorldCenterOfMass( b2BodyId bodyId );
/// Override the body's mass properties. Normally this is computed automatically using the
/// shape geometry and density. This information is lost if a shape is added or removed or if the
/// body type changes.
B2_API void b2Body_SetMassData( b2BodyId bodyId, b2MassData massData );
/// Get the mass data for a body
B2_API b2MassData b2Body_GetMassData( b2BodyId bodyId );
/// This update the mass properties to the sum of the mass properties of the shapes.
/// This normally does not need to be called unless you called SetMassData to override
/// the mass and you later want to reset the mass.
/// You may also use this when automatic mass computation has been disabled.
/// You should call this regardless of body type.
/// Note that sensor shapes may have mass.
B2_API void b2Body_ApplyMassFromShapes( b2BodyId bodyId );
/// Adjust the linear damping. Normally this is set in b2BodyDef before creation.
B2_API void b2Body_SetLinearDamping( b2BodyId bodyId, float linearDamping );
/// Get the current linear damping.
B2_API float b2Body_GetLinearDamping( b2BodyId bodyId );
/// Adjust the angular damping. Normally this is set in b2BodyDef before creation.
B2_API void b2Body_SetAngularDamping( b2BodyId bodyId, float angularDamping );
/// Get the current angular damping.
B2_API float b2Body_GetAngularDamping( b2BodyId bodyId );
/// Adjust the gravity scale. Normally this is set in b2BodyDef before creation.
/// @see b2BodyDef::gravityScale
B2_API void b2Body_SetGravityScale( b2BodyId bodyId, float gravityScale );
/// Get the current gravity scale
B2_API float b2Body_GetGravityScale( b2BodyId bodyId );
/// @return true if this body is awake
B2_API bool b2Body_IsAwake( b2BodyId bodyId );
/// Wake a body from sleep. This wakes the entire island the body is touching.
/// @warning Putting a body to sleep will put the entire island of bodies touching this body to sleep,
/// which can be expensive and possibly unintuitive.
B2_API void b2Body_SetAwake( b2BodyId bodyId, bool awake );
/// Enable or disable sleeping for this body. If sleeping is disabled the body will wake.
B2_API void b2Body_EnableSleep( b2BodyId bodyId, bool enableSleep );
/// Returns true if sleeping is enabled for this body
B2_API bool b2Body_IsSleepEnabled( b2BodyId bodyId );
/// Set the sleep threshold, usually in meters per second
B2_API void b2Body_SetSleepThreshold( b2BodyId bodyId, float sleepThreshold );
/// Get the sleep threshold, usually in meters per second.
B2_API float b2Body_GetSleepThreshold( b2BodyId bodyId );
/// Returns true if this body is enabled
B2_API bool b2Body_IsEnabled( b2BodyId bodyId );
/// Disable a body by removing it completely from the simulation. This is expensive.
B2_API void b2Body_Disable( b2BodyId bodyId );
/// Enable a body by adding it to the simulation. This is expensive.
B2_API void b2Body_Enable( b2BodyId bodyId );
/// Set this body to have fixed rotation. This causes the mass to be reset in all cases.
B2_API void b2Body_SetFixedRotation( b2BodyId bodyId, bool flag );
/// Does this body have fixed rotation?
B2_API bool b2Body_IsFixedRotation( b2BodyId bodyId );
/// Set this body to be a bullet. A bullet does continuous collision detection
/// against dynamic bodies (but not other bullets).
B2_API void b2Body_SetBullet( b2BodyId bodyId, bool flag );
/// Is this body a bullet?
B2_API bool b2Body_IsBullet( b2BodyId bodyId );
/// Enable/disable contact events on all shapes.
/// @see b2ShapeDef::enableContactEvents
/// @warning changing this at runtime may cause mismatched begin/end touch events
B2_API void b2Body_EnableContactEvents( b2BodyId bodyId, bool flag );
/// Enable/disable hit events on all shapes
/// @see b2ShapeDef::enableHitEvents
B2_API void b2Body_EnableHitEvents( b2BodyId bodyId, bool flag );
/// Get the world that owns this body
B2_API b2WorldId b2Body_GetWorld( b2BodyId bodyId );
/// Get the number of shapes on this body
B2_API int b2Body_GetShapeCount( b2BodyId bodyId );
/// Get the shape ids for all shapes on this body, up to the provided capacity.
/// @returns the number of shape ids stored in the user array
B2_API int b2Body_GetShapes( b2BodyId bodyId, b2ShapeId* shapeArray, int capacity );
/// Get the number of joints on this body
B2_API int b2Body_GetJointCount( b2BodyId bodyId );
/// Get the joint ids for all joints on this body, up to the provided capacity
/// @returns the number of joint ids stored in the user array
B2_API int b2Body_GetJoints( b2BodyId bodyId, b2JointId* jointArray, int capacity );
/// Get the maximum capacity required for retrieving all the touching contacts on a body
B2_API int b2Body_GetContactCapacity( b2BodyId bodyId );
/// Get the touching contact data for a body.
/// @note Box2D uses speculative collision so some contact points may be separated.
/// @returns the number of elements filled in the provided array
/// @warning do not ignore the return value, it specifies the valid number of elements
B2_API int b2Body_GetContactData( b2BodyId bodyId, b2ContactData* contactData, int capacity );
/// Get the current world AABB that contains all the attached shapes. Note that this may not encompass the body origin.
/// If there are no shapes attached then the returned AABB is empty and centered on the body origin.
B2_API b2AABB b2Body_ComputeAABB( b2BodyId bodyId );
/** @} */
/**
* @defgroup shape Shape
* Functions to create, destroy, and access.
* Shapes bind raw geometry to bodies and hold material properties including friction and restitution.
* @{
*/
/// Create a circle shape and attach it to a body. The shape definition and geometry are fully cloned.
/// Contacts are not created until the next time step.
/// @return the shape id for accessing the shape
B2_API b2ShapeId b2CreateCircleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Circle* circle );
/// Create a line segment shape and attach it to a body. The shape definition and geometry are fully cloned.
/// Contacts are not created until the next time step.
/// @return the shape id for accessing the shape
B2_API b2ShapeId b2CreateSegmentShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Segment* segment );
/// Create a capsule shape and attach it to a body. The shape definition and geometry are fully cloned.
/// Contacts are not created until the next time step.
/// @return the shape id for accessing the shape
B2_API b2ShapeId b2CreateCapsuleShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Capsule* capsule );
/// Create a polygon shape and attach it to a body. The shape definition and geometry are fully cloned.
/// Contacts are not created until the next time step.
/// @return the shape id for accessing the shape
B2_API b2ShapeId b2CreatePolygonShape( b2BodyId bodyId, const b2ShapeDef* def, const b2Polygon* polygon );
/// Destroy a shape. You may defer the body mass update which can improve performance if several shapes on a
/// body are destroyed at once.
/// @see b2Body_ApplyMassFromShapes
B2_API void b2DestroyShape( b2ShapeId shapeId, bool updateBodyMass );
/// Shape identifier validation. Provides validation for up to 64K allocations.
B2_API bool b2Shape_IsValid( b2ShapeId id );
/// Get the type of a shape
B2_API b2ShapeType b2Shape_GetType( b2ShapeId shapeId );
/// Get the id of the body that a shape is attached to
B2_API b2BodyId b2Shape_GetBody( b2ShapeId shapeId );
/// Get the world that owns this shape
B2_API b2WorldId b2Shape_GetWorld( b2ShapeId shapeId );
/// Returns true if the shape is a sensor. It is not possible to change a shape
/// from sensor to solid dynamically because this breaks the contract for
/// sensor events.
B2_API bool b2Shape_IsSensor( b2ShapeId shapeId );
/// Set the user data for a shape
B2_API void b2Shape_SetUserData( b2ShapeId shapeId, void* userData );
/// Get the user data for a shape. This is useful when you get a shape id
/// from an event or query.
B2_API void* b2Shape_GetUserData( b2ShapeId shapeId );
/// Set the mass density of a shape, usually in kg/m^2.
/// This will optionally update the mass properties on the parent body.
/// @see b2ShapeDef::density, b2Body_ApplyMassFromShapes
B2_API void b2Shape_SetDensity( b2ShapeId shapeId, float density, bool updateBodyMass );
/// Get the density of a shape, usually in kg/m^2
B2_API float b2Shape_GetDensity( b2ShapeId shapeId );
/// Set the friction on a shape
/// @see b2ShapeDef::friction
B2_API void b2Shape_SetFriction( b2ShapeId shapeId, float friction );
/// Get the friction of a shape
B2_API float b2Shape_GetFriction( b2ShapeId shapeId );
/// Set the shape restitution (bounciness)
/// @see b2ShapeDef::restitution
B2_API void b2Shape_SetRestitution( b2ShapeId shapeId, float restitution );
/// Get the shape restitution
B2_API float b2Shape_GetRestitution( b2ShapeId shapeId );
/// Set the shape material identifier
/// @see b2ShapeDef::material
B2_API void b2Shape_SetMaterial( b2ShapeId shapeId, int material );
/// Get the shape material identifier
B2_API int b2Shape_GetMaterial( b2ShapeId shapeId );
/// Get the shape filter
B2_API b2Filter b2Shape_GetFilter( b2ShapeId shapeId );
/// Set the current filter. This is almost as expensive as recreating the shape. This may cause
/// contacts to be immediately destroyed. However contacts are not created until the next world step.
/// Sensor overlap state is also not updated until the next world step.
/// @see b2ShapeDef::filter
B2_API void b2Shape_SetFilter( b2ShapeId shapeId, b2Filter filter );
/// Enable sensor events for this shape.
/// @see b2ShapeDef::enableSensorEvents
B2_API void b2Shape_EnableSensorEvents( b2ShapeId shapeId, bool flag );
/// Returns true if sensor events are enabled.
B2_API bool b2Shape_AreSensorEventsEnabled( b2ShapeId shapeId );
/// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors.
/// @see b2ShapeDef::enableContactEvents
/// @warning changing this at run-time may lead to lost begin/end events
B2_API void b2Shape_EnableContactEvents( b2ShapeId shapeId, bool flag );
/// Returns true if contact events are enabled
B2_API bool b2Shape_AreContactEventsEnabled( b2ShapeId shapeId );
/// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive
/// and must be carefully handled due to multithreading. Ignored for sensors.
/// @see b2PreSolveFcn
B2_API void b2Shape_EnablePreSolveEvents( b2ShapeId shapeId, bool flag );
/// Returns true if pre-solve events are enabled
B2_API bool b2Shape_ArePreSolveEventsEnabled( b2ShapeId shapeId );
/// Enable contact hit events for this shape. Ignored for sensors.
/// @see b2WorldDef.hitEventThreshold
B2_API void b2Shape_EnableHitEvents( b2ShapeId shapeId, bool flag );
/// Returns true if hit events are enabled
B2_API bool b2Shape_AreHitEventsEnabled( b2ShapeId shapeId );
/// Test a point for overlap with a shape
B2_API bool b2Shape_TestPoint( b2ShapeId shapeId, b2Vec2 point );
/// Ray cast a shape directly
B2_API b2CastOutput b2Shape_RayCast( b2ShapeId shapeId, const b2RayCastInput* input );
/// Get a copy of the shape's circle. Asserts the type is correct.
B2_API b2Circle b2Shape_GetCircle( b2ShapeId shapeId );
/// Get a copy of the shape's line segment. Asserts the type is correct.
B2_API b2Segment b2Shape_GetSegment( b2ShapeId shapeId );
/// Get a copy of the shape's chain segment. These come from chain shapes.
/// Asserts the type is correct.
B2_API b2ChainSegment b2Shape_GetChainSegment( b2ShapeId shapeId );
/// Get a copy of the shape's capsule. Asserts the type is correct.
B2_API b2Capsule b2Shape_GetCapsule( b2ShapeId shapeId );
/// Get a copy of the shape's convex polygon. Asserts the type is correct.
B2_API b2Polygon b2Shape_GetPolygon( b2ShapeId shapeId );
/// Allows you to change a shape to be a circle or update the current circle.
/// This does not modify the mass properties.
/// @see b2Body_ApplyMassFromShapes
B2_API void b2Shape_SetCircle( b2ShapeId shapeId, const b2Circle* circle );
/// Allows you to change a shape to be a capsule or update the current capsule.
/// This does not modify the mass properties.
/// @see b2Body_ApplyMassFromShapes
B2_API void b2Shape_SetCapsule( b2ShapeId shapeId, const b2Capsule* capsule );
/// Allows you to change a shape to be a segment or update the current segment.
B2_API void b2Shape_SetSegment( b2ShapeId shapeId, const b2Segment* segment );
/// Allows you to change a shape to be a polygon or update the current polygon.
/// This does not modify the mass properties.
/// @see b2Body_ApplyMassFromShapes
B2_API void b2Shape_SetPolygon( b2ShapeId shapeId, const b2Polygon* polygon );
/// Get the parent chain id if the shape type is a chain segment, otherwise
/// returns b2_nullChainId.
B2_API b2ChainId b2Shape_GetParentChain( b2ShapeId shapeId );
/// Get the maximum capacity required for retrieving all the touching contacts on a shape
B2_API int b2Shape_GetContactCapacity( b2ShapeId shapeId );
/// Get the touching contact data for a shape. The provided shapeId will be either shapeIdA or shapeIdB on the contact data.
/// @note Box2D uses speculative collision so some contact points may be separated.
/// @returns the number of elements filled in the provided array
/// @warning do not ignore the return value, it specifies the valid number of elements
B2_API int b2Shape_GetContactData( b2ShapeId shapeId, b2ContactData* contactData, int capacity );
/// Get the maximum capacity required for retrieving all the overlapped shapes on a sensor shape.
/// This returns 0 if the provided shape is not a sensor.
/// @param shapeId the id of a sensor shape
/// @returns the required capacity to get all the overlaps in b2Shape_GetSensorOverlaps
B2_API int b2Shape_GetSensorCapacity( b2ShapeId shapeId );
/// Get the overlapped shapes for a sensor shape.
/// @param shapeId the id of a sensor shape
/// @param overlaps a user allocated array that is filled with the overlapping shapes
/// @param capacity the capacity of overlappedShapes
/// @returns the number of elements filled in the provided array
/// @warning do not ignore the return value, it specifies the valid number of elements
/// @warning overlaps may contain destroyed shapes so use b2Shape_IsValid to confirm each overlap
B2_API int b2Shape_GetSensorOverlaps( b2ShapeId shapeId, b2ShapeId* overlaps, int capacity );
/// Get the current world AABB
B2_API b2AABB b2Shape_GetAABB( b2ShapeId shapeId );
/// Get the mass data for a shape
B2_API b2MassData b2Shape_GetMassData( b2ShapeId shapeId );
/// Get the closest point on a shape to a target point. Target and result are in world space.
/// todo need sample
B2_API b2Vec2 b2Shape_GetClosestPoint( b2ShapeId shapeId, b2Vec2 target );
/// Chain Shape
/// Create a chain shape
/// @see b2ChainDef for details
B2_API b2ChainId b2CreateChain( b2BodyId bodyId, const b2ChainDef* def );
/// Destroy a chain shape
B2_API void b2DestroyChain( b2ChainId chainId );
/// Get the world that owns this chain shape
B2_API b2WorldId b2Chain_GetWorld( b2ChainId chainId );
/// Get the number of segments on this chain
B2_API int b2Chain_GetSegmentCount( b2ChainId chainId );
/// Fill a user array with chain segment shape ids up to the specified capacity. Returns
/// the actual number of segments returned.
B2_API int b2Chain_GetSegments( b2ChainId chainId, b2ShapeId* segmentArray, int capacity );
/// Set the chain friction
/// @see b2ChainDef::friction
B2_API void b2Chain_SetFriction( b2ChainId chainId, float friction );
/// Get the chain friction
B2_API float b2Chain_GetFriction( b2ChainId chainId );
/// Set the chain restitution (bounciness)
/// @see b2ChainDef::restitution
B2_API void b2Chain_SetRestitution( b2ChainId chainId, float restitution );
/// Get the chain restitution
B2_API float b2Chain_GetRestitution( b2ChainId chainId );
/// Set the chain material
/// @see b2ChainDef::material
B2_API void b2Chain_SetMaterial( b2ChainId chainId, int material );
/// Get the chain material
B2_API int b2Chain_GetMaterial( b2ChainId chainId );
/// Chain identifier validation. Provides validation for up to 64K allocations.
B2_API bool b2Chain_IsValid( b2ChainId id );
/** @} */
/**
* @defgroup joint Joint
* @brief Joints allow you to connect rigid bodies together while allowing various forms of relative motions.
* @{
*/
/// Destroy a joint
B2_API void b2DestroyJoint( b2JointId jointId );
/// Joint identifier validation. Provides validation for up to 64K allocations.
B2_API bool b2Joint_IsValid( b2JointId id );
/// Get the joint type
B2_API b2JointType b2Joint_GetType( b2JointId jointId );
/// Get body A id on a joint
B2_API b2BodyId b2Joint_GetBodyA( b2JointId jointId );
/// Get body B id on a joint
B2_API b2BodyId b2Joint_GetBodyB( b2JointId jointId );
/// Get the world that owns this joint
B2_API b2WorldId b2Joint_GetWorld( b2JointId jointId );
/// Get the local anchor on bodyA
B2_API b2Vec2 b2Joint_GetLocalAnchorA( b2JointId jointId );
/// Get the local anchor on bodyB
B2_API b2Vec2 b2Joint_GetLocalAnchorB( b2JointId jointId );
/// Toggle collision between connected bodies
B2_API void b2Joint_SetCollideConnected( b2JointId jointId, bool shouldCollide );
/// Is collision allowed between connected bodies?
B2_API bool b2Joint_GetCollideConnected( b2JointId jointId );
/// Set the user data on a joint
B2_API void b2Joint_SetUserData( b2JointId jointId, void* userData );
/// Get the user data on a joint
B2_API void* b2Joint_GetUserData( b2JointId jointId );
/// Wake the bodies connect to this joint
B2_API void b2Joint_WakeBodies( b2JointId jointId );
/// Get the current constraint force for this joint. Usually in Newtons.
B2_API b2Vec2 b2Joint_GetConstraintForce( b2JointId jointId );
/// Get the current constraint torque for this joint. Usually in Newton * meters.
B2_API float b2Joint_GetConstraintTorque( b2JointId jointId );
/**
* @defgroup distance_joint Distance Joint
* @brief Functions for the distance joint.
* @{
*/
/// Create a distance joint
/// @see b2DistanceJointDef for details
B2_API b2JointId b2CreateDistanceJoint( b2WorldId worldId, const b2DistanceJointDef* def );
/// Set the rest length of a distance joint
/// @param jointId The id for a distance joint
/// @param length The new distance joint length
B2_API void b2DistanceJoint_SetLength( b2JointId jointId, float length );
/// Get the rest length of a distance joint
B2_API float b2DistanceJoint_GetLength( b2JointId jointId );
/// Enable/disable the distance joint spring. When disabled the distance joint is rigid.
B2_API void b2DistanceJoint_EnableSpring( b2JointId jointId, bool enableSpring );
/// Is the distance joint spring enabled?
B2_API bool b2DistanceJoint_IsSpringEnabled( b2JointId jointId );
/// Set the spring stiffness in Hertz
B2_API void b2DistanceJoint_SetSpringHertz( b2JointId jointId, float hertz );
/// Set the spring damping ratio, non-dimensional
B2_API void b2DistanceJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio );
/// Get the spring Hertz
B2_API float b2DistanceJoint_GetSpringHertz( b2JointId jointId );
/// Get the spring damping ratio
B2_API float b2DistanceJoint_GetSpringDampingRatio( b2JointId jointId );
/// Enable joint limit. The limit only works if the joint spring is enabled. Otherwise the joint is rigid
/// and the limit has no effect.
B2_API void b2DistanceJoint_EnableLimit( b2JointId jointId, bool enableLimit );
/// Is the distance joint limit enabled?
B2_API bool b2DistanceJoint_IsLimitEnabled( b2JointId jointId );
/// Set the minimum and maximum length parameters of a distance joint
B2_API void b2DistanceJoint_SetLengthRange( b2JointId jointId, float minLength, float maxLength );
/// Get the distance joint minimum length
B2_API float b2DistanceJoint_GetMinLength( b2JointId jointId );
/// Get the distance joint maximum length
B2_API float b2DistanceJoint_GetMaxLength( b2JointId jointId );
/// Get the current length of a distance joint
B2_API float b2DistanceJoint_GetCurrentLength( b2JointId jointId );
/// Enable/disable the distance joint motor
B2_API void b2DistanceJoint_EnableMotor( b2JointId jointId, bool enableMotor );
/// Is the distance joint motor enabled?
B2_API bool b2DistanceJoint_IsMotorEnabled( b2JointId jointId );
/// Set the distance joint motor speed, usually in meters per second
B2_API void b2DistanceJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed );
/// Get the distance joint motor speed, usually in meters per second
B2_API float b2DistanceJoint_GetMotorSpeed( b2JointId jointId );
/// Set the distance joint maximum motor force, usually in newtons
B2_API void b2DistanceJoint_SetMaxMotorForce( b2JointId jointId, float force );
/// Get the distance joint maximum motor force, usually in newtons
B2_API float b2DistanceJoint_GetMaxMotorForce( b2JointId jointId );
/// Get the distance joint current motor force, usually in newtons
B2_API float b2DistanceJoint_GetMotorForce( b2JointId jointId );
/** @} */
/**
* @defgroup motor_joint Motor Joint
* @brief Functions for the motor joint.
*
* The motor joint is used to drive the relative transform between two bodies. It takes
* a relative position and rotation and applies the forces and torques needed to achieve
* that relative transform over time.
* @{
*/
/// Create a motor joint
/// @see b2MotorJointDef for details
B2_API b2JointId b2CreateMotorJoint( b2WorldId worldId, const b2MotorJointDef* def );
/// Set the motor joint linear offset target
B2_API void b2MotorJoint_SetLinearOffset( b2JointId jointId, b2Vec2 linearOffset );
/// Get the motor joint linear offset target
B2_API b2Vec2 b2MotorJoint_GetLinearOffset( b2JointId jointId );
/// Set the motor joint angular offset target in radians
B2_API void b2MotorJoint_SetAngularOffset( b2JointId jointId, float angularOffset );
/// Get the motor joint angular offset target in radians
B2_API float b2MotorJoint_GetAngularOffset( b2JointId jointId );
/// Set the motor joint maximum force, usually in newtons
B2_API void b2MotorJoint_SetMaxForce( b2JointId jointId, float maxForce );
/// Get the motor joint maximum force, usually in newtons
B2_API float b2MotorJoint_GetMaxForce( b2JointId jointId );
/// Set the motor joint maximum torque, usually in newton-meters
B2_API void b2MotorJoint_SetMaxTorque( b2JointId jointId, float maxTorque );
/// Get the motor joint maximum torque, usually in newton-meters
B2_API float b2MotorJoint_GetMaxTorque( b2JointId jointId );
/// Set the motor joint correction factor, usually in [0, 1]
B2_API void b2MotorJoint_SetCorrectionFactor( b2JointId jointId, float correctionFactor );
/// Get the motor joint correction factor, usually in [0, 1]
B2_API float b2MotorJoint_GetCorrectionFactor( b2JointId jointId );
/**@}*/
/**
* @defgroup mouse_joint Mouse Joint
* @brief Functions for the mouse joint.
*
* The mouse joint is designed for use in the samples application, but you may find it useful in applications where
* the user moves a rigid body with a cursor.
* @{
*/
/// Create a mouse joint
/// @see b2MouseJointDef for details
B2_API b2JointId b2CreateMouseJoint( b2WorldId worldId, const b2MouseJointDef* def );
/// Set the mouse joint target
B2_API void b2MouseJoint_SetTarget( b2JointId jointId, b2Vec2 target );
/// Get the mouse joint target
B2_API b2Vec2 b2MouseJoint_GetTarget( b2JointId jointId );
/// Set the mouse joint spring stiffness in Hertz
B2_API void b2MouseJoint_SetSpringHertz( b2JointId jointId, float hertz );
/// Get the mouse joint spring stiffness in Hertz
B2_API float b2MouseJoint_GetSpringHertz( b2JointId jointId );
/// Set the mouse joint spring damping ratio, non-dimensional
B2_API void b2MouseJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio );
/// Get the mouse joint damping ratio, non-dimensional
B2_API float b2MouseJoint_GetSpringDampingRatio( b2JointId jointId );
/// Set the mouse joint maximum force, usually in newtons
B2_API void b2MouseJoint_SetMaxForce( b2JointId jointId, float maxForce );
/// Get the mouse joint maximum force, usually in newtons
B2_API float b2MouseJoint_GetMaxForce( b2JointId jointId );
/**@}*/
/**
* @defgroup filter_joint Filter Joint
* @brief Functions for the filter joint.
*
* The filter joint is used to disable collision between two bodies. As a side effect of being a joint, it also
* keeps the two bodies in the same simulation island.
* @{
*/
/// Create a filter joint.
/// @see b2FilterJointDef for details
B2_API b2JointId b2CreateFilterJoint( b2WorldId worldId, const b2FilterJointDef* def );
/**@}*/
/**
* @defgroup prismatic_joint Prismatic Joint
* @brief A prismatic joint allows for translation along a single axis with no rotation.
*
* The prismatic joint is useful for things like pistons and moving platforms, where you want a body to translate
* along an axis and have no rotation. Also called a *slider* joint.
* @{
*/
/// Create a prismatic (slider) joint.
/// @see b2PrismaticJointDef for details
B2_API b2JointId b2CreatePrismaticJoint( b2WorldId worldId, const b2PrismaticJointDef* def );
/// Enable/disable the joint spring.
B2_API void b2PrismaticJoint_EnableSpring( b2JointId jointId, bool enableSpring );
/// Is the prismatic joint spring enabled or not?
B2_API bool b2PrismaticJoint_IsSpringEnabled( b2JointId jointId );
/// Set the prismatic joint stiffness in Hertz.
/// This should usually be less than a quarter of the simulation rate. For example, if the simulation
/// runs at 60Hz then the joint stiffness should be 15Hz or less.
B2_API void b2PrismaticJoint_SetSpringHertz( b2JointId jointId, float hertz );
/// Get the prismatic joint stiffness in Hertz
B2_API float b2PrismaticJoint_GetSpringHertz( b2JointId jointId );
/// Set the prismatic joint damping ratio (non-dimensional)
B2_API void b2PrismaticJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio );
/// Get the prismatic spring damping ratio (non-dimensional)
B2_API float b2PrismaticJoint_GetSpringDampingRatio( b2JointId jointId );
/// Enable/disable a prismatic joint limit
B2_API void b2PrismaticJoint_EnableLimit( b2JointId jointId, bool enableLimit );
/// Is the prismatic joint limit enabled?
B2_API bool b2PrismaticJoint_IsLimitEnabled( b2JointId jointId );
/// Get the prismatic joint lower limit
B2_API float b2PrismaticJoint_GetLowerLimit( b2JointId jointId );
/// Get the prismatic joint upper limit
B2_API float b2PrismaticJoint_GetUpperLimit( b2JointId jointId );
/// Set the prismatic joint limits
B2_API void b2PrismaticJoint_SetLimits( b2JointId jointId, float lower, float upper );
/// Enable/disable a prismatic joint motor
B2_API void b2PrismaticJoint_EnableMotor( b2JointId jointId, bool enableMotor );
/// Is the prismatic joint motor enabled?
B2_API bool b2PrismaticJoint_IsMotorEnabled( b2JointId jointId );
/// Set the prismatic joint motor speed, usually in meters per second
B2_API void b2PrismaticJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed );
/// Get the prismatic joint motor speed, usually in meters per second
B2_API float b2PrismaticJoint_GetMotorSpeed( b2JointId jointId );
/// Set the prismatic joint maximum motor force, usually in newtons
B2_API void b2PrismaticJoint_SetMaxMotorForce( b2JointId jointId, float force );
/// Get the prismatic joint maximum motor force, usually in newtons
B2_API float b2PrismaticJoint_GetMaxMotorForce( b2JointId jointId );
/// Get the prismatic joint current motor force, usually in newtons
B2_API float b2PrismaticJoint_GetMotorForce( b2JointId jointId );
/// Get the current joint translation, usually in meters.
B2_API float b2PrismaticJoint_GetTranslation( b2JointId jointId );
/// Get the current joint translation speed, usually in meters per second.
B2_API float b2PrismaticJoint_GetSpeed( b2JointId jointId );
/** @} */
/**
* @defgroup revolute_joint Revolute Joint
* @brief A revolute joint allows for relative rotation in the 2D plane with no relative translation.
*
* The revolute joint is probably the most common joint. It can be used for ragdolls and chains.
* Also called a *hinge* or *pin* joint.
* @{
*/
/// Create a revolute joint
/// @see b2RevoluteJointDef for details
B2_API b2JointId b2CreateRevoluteJoint( b2WorldId worldId, const b2RevoluteJointDef* def );
/// Enable/disable the revolute joint spring
B2_API void b2RevoluteJoint_EnableSpring( b2JointId jointId, bool enableSpring );
/// It the revolute angular spring enabled?
B2_API bool b2RevoluteJoint_IsSpringEnabled( b2JointId jointId );
/// Set the revolute joint spring stiffness in Hertz
B2_API void b2RevoluteJoint_SetSpringHertz( b2JointId jointId, float hertz );
/// Get the revolute joint spring stiffness in Hertz
B2_API float b2RevoluteJoint_GetSpringHertz( b2JointId jointId );
/// Set the revolute joint spring damping ratio, non-dimensional
B2_API void b2RevoluteJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio );
/// Get the revolute joint spring damping ratio, non-dimensional
B2_API float b2RevoluteJoint_GetSpringDampingRatio( b2JointId jointId );
/// Get the revolute joint current angle in radians relative to the reference angle
/// @see b2RevoluteJointDef::referenceAngle
B2_API float b2RevoluteJoint_GetAngle( b2JointId jointId );
/// Enable/disable the revolute joint limit
B2_API void b2RevoluteJoint_EnableLimit( b2JointId jointId, bool enableLimit );
/// Is the revolute joint limit enabled?
B2_API bool b2RevoluteJoint_IsLimitEnabled( b2JointId jointId );
/// Get the revolute joint lower limit in radians
B2_API float b2RevoluteJoint_GetLowerLimit( b2JointId jointId );
/// Get the revolute joint upper limit in radians
B2_API float b2RevoluteJoint_GetUpperLimit( b2JointId jointId );
/// Set the revolute joint limits in radians. It is expected that lower <= upper
/// and that -0.95 * B2_PI <= lower && upper <= -0.95 * B2_PI.
B2_API void b2RevoluteJoint_SetLimits( b2JointId jointId, float lower, float upper );
/// Enable/disable a revolute joint motor
B2_API void b2RevoluteJoint_EnableMotor( b2JointId jointId, bool enableMotor );
/// Is the revolute joint motor enabled?
B2_API bool b2RevoluteJoint_IsMotorEnabled( b2JointId jointId );
/// Set the revolute joint motor speed in radians per second
B2_API void b2RevoluteJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed );
/// Get the revolute joint motor speed in radians per second
B2_API float b2RevoluteJoint_GetMotorSpeed( b2JointId jointId );
/// Get the revolute joint current motor torque, usually in newton-meters
B2_API float b2RevoluteJoint_GetMotorTorque( b2JointId jointId );
/// Set the revolute joint maximum motor torque, usually in newton-meters
B2_API void b2RevoluteJoint_SetMaxMotorTorque( b2JointId jointId, float torque );
/// Get the revolute joint maximum motor torque, usually in newton-meters
B2_API float b2RevoluteJoint_GetMaxMotorTorque( b2JointId jointId );
/**@}*/
/**
* @defgroup weld_joint Weld Joint
* @brief A weld joint fully constrains the relative transform between two bodies while allowing for springiness
*
* A weld joint constrains the relative rotation and translation between two bodies. Both rotation and translation
* can have damped springs.
*
* @note The accuracy of weld joint is limited by the accuracy of the solver. Long chains of weld joints may flex.
* @{
*/
/// Create a weld joint
/// @see b2WeldJointDef for details
B2_API b2JointId b2CreateWeldJoint( b2WorldId worldId, const b2WeldJointDef* def );
/// Get the weld joint reference angle in radians
B2_API float b2WeldJoint_GetReferenceAngle( b2JointId jointId );
/// Set the weld joint reference angle in radians, must be in [-pi,pi].
B2_API void b2WeldJoint_SetReferenceAngle( b2JointId jointId, float angleInRadians );
/// Set the weld joint linear stiffness in Hertz. 0 is rigid.
B2_API void b2WeldJoint_SetLinearHertz( b2JointId jointId, float hertz );
/// Get the weld joint linear stiffness in Hertz
B2_API float b2WeldJoint_GetLinearHertz( b2JointId jointId );
/// Set the weld joint linear damping ratio (non-dimensional)
B2_API void b2WeldJoint_SetLinearDampingRatio( b2JointId jointId, float dampingRatio );
/// Get the weld joint linear damping ratio (non-dimensional)
B2_API float b2WeldJoint_GetLinearDampingRatio( b2JointId jointId );
/// Set the weld joint angular stiffness in Hertz. 0 is rigid.
B2_API void b2WeldJoint_SetAngularHertz( b2JointId jointId, float hertz );
/// Get the weld joint angular stiffness in Hertz
B2_API float b2WeldJoint_GetAngularHertz( b2JointId jointId );
/// Set weld joint angular damping ratio, non-dimensional
B2_API void b2WeldJoint_SetAngularDampingRatio( b2JointId jointId, float dampingRatio );
/// Get the weld joint angular damping ratio, non-dimensional
B2_API float b2WeldJoint_GetAngularDampingRatio( b2JointId jointId );
/** @} */
/**
* @defgroup wheel_joint Wheel Joint
* The wheel joint can be used to simulate wheels on vehicles.
*
* The wheel joint restricts body B to move along a local axis in body A. Body B is free to
* rotate. Supports a linear spring, linear limits, and a rotational motor.
*
* @{
*/
/// Create a wheel joint
/// @see b2WheelJointDef for details
B2_API b2JointId b2CreateWheelJoint( b2WorldId worldId, const b2WheelJointDef* def );
/// Enable/disable the wheel joint spring
B2_API void b2WheelJoint_EnableSpring( b2JointId jointId, bool enableSpring );
/// Is the wheel joint spring enabled?
B2_API bool b2WheelJoint_IsSpringEnabled( b2JointId jointId );
/// Set the wheel joint stiffness in Hertz
B2_API void b2WheelJoint_SetSpringHertz( b2JointId jointId, float hertz );
/// Get the wheel joint stiffness in Hertz
B2_API float b2WheelJoint_GetSpringHertz( b2JointId jointId );
/// Set the wheel joint damping ratio, non-dimensional
B2_API void b2WheelJoint_SetSpringDampingRatio( b2JointId jointId, float dampingRatio );
/// Get the wheel joint damping ratio, non-dimensional
B2_API float b2WheelJoint_GetSpringDampingRatio( b2JointId jointId );
/// Enable/disable the wheel joint limit
B2_API void b2WheelJoint_EnableLimit( b2JointId jointId, bool enableLimit );
/// Is the wheel joint limit enabled?
B2_API bool b2WheelJoint_IsLimitEnabled( b2JointId jointId );
/// Get the wheel joint lower limit
B2_API float b2WheelJoint_GetLowerLimit( b2JointId jointId );
/// Get the wheel joint upper limit
B2_API float b2WheelJoint_GetUpperLimit( b2JointId jointId );
/// Set the wheel joint limits
B2_API void b2WheelJoint_SetLimits( b2JointId jointId, float lower, float upper );
/// Enable/disable the wheel joint motor
B2_API void b2WheelJoint_EnableMotor( b2JointId jointId, bool enableMotor );
/// Is the wheel joint motor enabled?
B2_API bool b2WheelJoint_IsMotorEnabled( b2JointId jointId );
/// Set the wheel joint motor speed in radians per second
B2_API void b2WheelJoint_SetMotorSpeed( b2JointId jointId, float motorSpeed );
/// Get the wheel joint motor speed in radians per second
B2_API float b2WheelJoint_GetMotorSpeed( b2JointId jointId );
/// Set the wheel joint maximum motor torque, usually in newton-meters
B2_API void b2WheelJoint_SetMaxMotorTorque( b2JointId jointId, float torque );
/// Get the wheel joint maximum motor torque, usually in newton-meters
B2_API float b2WheelJoint_GetMaxMotorTorque( b2JointId jointId );
/// Get the wheel joint current motor torque, usually in newton-meters
B2_API float b2WheelJoint_GetMotorTorque( b2JointId jointId );
/**@}*/
/**@}*/
| 412 | 0.710703 | 1 | 0.710703 | game-dev | MEDIA | 0.809838 | game-dev | 0.639835 | 1 | 0.639835 |
mouahrara/aedenthorn | 7,824 | WeatherTotem/CodePatches.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using StardewValley;
using StardewValley.GameData.LocationContexts;
using Object = StardewValley.Object;
namespace WeatherTotem
{
public partial class ModEntry
{
public class Object_rainTotem_Patch
{
public static bool Prefix(Object __instance, Farmer who)
{
if (!Config.ModEnabled)
return true;
GameLocation currentLocation = who.currentLocation;
string locationContextId = currentLocation.GetLocationContextId();
LocationContextData locationContext = currentLocation.GetLocationContext();
if (!locationContext.AllowRainTotem)
{
return true;
}
if (locationContext.RainTotemAffectsContext is not null)
{
locationContextId = locationContext.RainTotemAffectsContext;
locationContext = LocationContexts.Require(locationContext.RainTotemAffectsContext);
}
who.currentLocation.ShowPagedResponses(SHelper.Translation.Get("menu.prompt"), GetWeathersResponses(locationContext), (string response) => OnResponse(response, __instance, who, currentLocation, locationContextId));
return false;
}
private static List<KeyValuePair<string, string>> GetWeathersResponses(LocationContextData locationContext)
{
List<KeyValuePair<string, string>> responses = new();
Dictionary<string, int> weatherPriority = new()
{
{ Game1.weather_sunny, 0 },
{ Game1.weather_rain, 1 },
{ Game1.weather_green_rain, 2 },
{ Game1.weather_lightning, 3 },
{ Game1.weather_snow, 4 },
{ Game1.weather_debris, 5 }
};
foreach (WeatherCondition weatherCondition in locationContext.WeatherConditions)
{
if (weatherCondition.Weather.Equals(Game1.weather_festival) || weatherCondition.Weather.Equals(Game1.weather_wedding))
continue;
if (!responses.Any(r => r.Key.Equals(weatherCondition.Weather)))
{
bool isConditionFulfilled = weatherCondition.Condition is null;
if (!isConditionFulfilled)
{
string[] array = weatherCondition.Condition.Trim().Split(',', StringSplitOptions.TrimEntries);
for (int i = 0; i < array.Length; i++)
{
if (array[i].Equals("IS_GREEN_RAIN_DAY"))
{
array[i] = "SEASON summer";
}
}
isConditionFulfilled = !array.Any(condition => condition.StartsWith("SEASON") || condition.StartsWith("!SEASON")) || array.Any(condition =>
{
if (condition.StartsWith("SEASON") || condition.StartsWith("!SEASON"))
{
WorldDate worldDate = new(Game1.Date);
worldDate.TotalDays++;
string[] seasons = ArgUtility.SplitBySpace(condition);
bool reverse = condition.StartsWith("!SEASON");
bool anyMatch = seasons.Any(s => s.ToLower() == worldDate.SeasonKey);
return (anyMatch && !reverse) || (reverse && !anyMatch);
}
return false;
});
}
if (isConditionFulfilled)
{
responses.Add(new(weatherCondition.Weather, weatherCondition.Weather switch
{
Game1.weather_sunny => SHelper.Translation.Get("menu.Sun"),
Game1.weather_rain => SHelper.Translation.Get("menu.Rain"),
Game1.weather_green_rain => SHelper.Translation.Get("menu.GreenRain"),
Game1.weather_lightning => SHelper.Translation.Get("menu.Storm"),
Game1.weather_snow => SHelper.Translation.Get("menu.Snow"),
Game1.weather_debris => SHelper.Translation.Get("menu.Wind"),
_ => weatherCondition.Weather
}));
}
}
}
responses.Sort((x, y) =>
{
return (weatherPriority.ContainsKey(x.Key), weatherPriority.ContainsKey(y.Key)) switch
{
(true, true) => weatherPriority[x.Key].CompareTo(weatherPriority[y.Key]),
(true, false) => -1,
(false, true) => 1,
_ => x.Key.CompareTo(y.Key)
};
});
return responses;
}
private static void OnResponse(string response, Object __instance, Farmer who, GameLocation currentLocation, string locationContextId)
{
string sound = response switch
{
Game1.weather_rain => Config.RainSound,
Game1.weather_green_rain => Config.GreenRainSound,
Game1.weather_lightning => Config.StormSound,
Game1.weather_snow => Config.SnowSound,
Game1.weather_debris => Config.WindSound,
_ => Config.SunSound
};
bool flag = false;
if (locationContextId.Equals("Default"))
{
if (!Utility.isFestivalDay(Game1.dayOfMonth + 1, Game1.season))
{
Game1.netWorldState.Value.WeatherForTomorrow = Game1.weatherForTomorrow = response;
flag = true;
}
}
else
{
currentLocation.GetWeather().WeatherForTomorrow = response;
flag = true;
}
if (flag)
{
Game1.pauseThenMessage(2000, SHelper.Translation.GetTranslations().Any(t => t.Key.Equals($"message.{response}")) ? SHelper.Translation.Get($"message.{response}") : SHelper.Translation.Get($"message.Default"));
}
Game1.screenGlow = false;
if (!string.IsNullOrEmpty(Config.InvokeSound))
{
currentLocation.playSound(Config.InvokeSound);
}
who.canMove = false;
Game1.screenGlowOnce(Color.SlateBlue, hold: false);
Game1.player.faceDirection(2);
Game1.player.FarmerSprite.animateOnce(new FarmerSprite.AnimationFrame[1]
{
new(57, 2000, secondaryArm: false, flip: false, Farmer.canMoveNow, behaviorAtEndOfFrame: true)
});
for (int i = 0; i < 6; i++)
{
Game1.Multiplayer.broadcastSprites(currentLocation, new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Rectangle(648, 1045, 52, 33), 9999f, 1, 999, who.Position + new Vector2(0f, -128f), flicker: false, flipped: false, 1f, 0.01f, Color.White * 0.8f, 2f, 0.01f, 0f, 0f)
{
motion = new Vector2(Game1.random.Next(-10, 11) / 10f, -2f),
delayBeforeAnimationStart = i * 200
});
Game1.Multiplayer.broadcastSprites(currentLocation, new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Rectangle(648, 1045, 52, 33), 9999f, 1, 999, who.Position + new Vector2(0f, -128f), flicker: false, flipped: false, 1f, 0.01f, Color.White * 0.8f, 1f, 0.01f, 0f, 0f)
{
motion = new Vector2(Game1.random.Next(-30, -10) / 10f, -1f),
delayBeforeAnimationStart = 100 + i * 200
});
Game1.Multiplayer.broadcastSprites(currentLocation, new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Rectangle(648, 1045, 52, 33), 9999f, 1, 999, who.Position + new Vector2(0f, -128f), flicker: false, flipped: false, 1f, 0.01f, Color.White * 0.8f, 1f, 0.01f, 0f, 0f)
{
motion = new Vector2(Game1.random.Next(10, 30) / 10f, -1f),
delayBeforeAnimationStart = 200 + i * 200
});
}
TemporaryAnimatedSprite temporaryAnimatedSprite = new(0, 9999f, 1, 999, Game1.player.Position + new Vector2(0f, -96f), flicker: false, flipped: false, verticalFlipped: false, 0f)
{
motion = new Vector2(0f, -7f),
acceleration = new Vector2(0f, 0.1f),
scaleChange = 0.015f,
alpha = 1f,
alphaFade = 0.0075f,
shakeIntensity = 1f,
initialPosition = Game1.player.Position + new Vector2(0f, -96f),
xPeriodic = true,
xPeriodicLoopTime = 1000f,
xPeriodicRange = 4f,
layerDepth = 1f
};
temporaryAnimatedSprite.CopyAppearanceFromItemId(__instance.QualifiedItemId);
Game1.Multiplayer.broadcastSprites(currentLocation, temporaryAnimatedSprite);
DelayedAction.playSoundAfterDelay(sound, 2000);
who.reduceActiveItemByOne();
}
}
public class Object_performUseAction_Patch
{
public static void Postfix(Object __instance, ref bool __result)
{
if (__instance.Name is not null && __instance.name.Contains("Totem") && __instance.QualifiedItemId.Equals("(O)681"))
{
__result = false;
}
}
}
}
}
| 412 | 0.914953 | 1 | 0.914953 | game-dev | MEDIA | 0.460849 | game-dev | 0.971832 | 1 | 0.971832 |
googlearchive/tango-examples-unity | 18,432 | TangoWithMultiplayer/Assets/Photon Unity Networking/Demos/DemoPickup/Scripts/PickupController.cs | using UnityEngine;
using System.Collections;
public enum PickupCharacterState
{
Idle = 0,
Walking = 1,
Trotting = 2,
Running = 3,
Jumping = 4,
}
[RequireComponent(typeof(CharacterController))]
public class PickupController : MonoBehaviour, IPunObservable
{
public AnimationClip idleAnimation;
public AnimationClip walkAnimation;
public AnimationClip runAnimation;
public AnimationClip jumpPoseAnimation;
public float walkMaxAnimationSpeed = 0.75f;
public float trotMaxAnimationSpeed = 1.0f;
public float runMaxAnimationSpeed = 1.0f;
public float jumpAnimationSpeed = 1.15f;
public float landAnimationSpeed = 1.0f;
private Animation _animation;
public PickupCharacterState _characterState;
// The speed when walking
public float walkSpeed = 2.0f;
// after trotAfterSeconds of walking we trot with trotSpeed
public float trotSpeed = 4.0f;
// when pressing "Fire3" button (cmd) we start running
public float runSpeed = 6.0f;
public float inAirControlAcceleration = 3.0f;
// How high do we jump when pressing jump and letting go immediately
public float jumpHeight = 0.5f;
// The gravity for the character
public float gravity = 20.0f;
// The gravity in controlled descent mode
public float speedSmoothing = 10.0f;
public float rotateSpeed = 500.0f;
public float trotAfterSeconds = 3.0f;
public bool canJump = false;
private float jumpRepeatTime = 0.05f;
private float jumpTimeout = 0.15f;
private float groundedTimeout = 0.25f;
// The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
private float lockCameraTimer = 0.0f;
// The current move direction in x-z
private Vector3 moveDirection = Vector3.zero;
// The current vertical speed
private float verticalSpeed = 0.0f;
// The current x-z move speed
private float moveSpeed = 0.0f;
// The last collision flags returned from controller.Move
private CollisionFlags collisionFlags;
// Are we jumping? (Initiated with jump button and not grounded yet)
private bool jumping = false;
private bool jumpingReachedApex = false;
// Are we moving backwards (This locks the camera to not do a 180 degree spin)
private bool movingBack = false;
// Is the user pressing any keys?
private bool isMoving = false;
// When did the user start walking (Used for going into trot after a while)
private float walkTimeStart = 0.0f;
// Last time the jump button was clicked down
private float lastJumpButtonTime = -10.0f;
// Last time we performed a jump
private float lastJumpTime = -1.0f;
// the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
//private float lastJumpStartHeight = 0.0f;
private Vector3 inAirVelocity = Vector3.zero;
private float lastGroundedTime = 0.0f;
Vector3 velocity = Vector3.zero;
private Vector3 lastPos;
private Vector3 remotePosition;
public bool isControllable = false;
public bool DoRotate = true;
public float RemoteSmoothing = 5;
public bool AssignAsTagObject = true;
void Awake()
{
// PUN: automatically determine isControllable, if this GO has a PhotonView
PhotonView pv = gameObject.GetComponent<PhotonView>();
if (pv != null)
{
this.isControllable = pv.isMine;
// The pickup demo assigns this GameObject as the PhotonPlayer.TagObject. This way, we can access this character (controller, position, etc) easily
if (this.AssignAsTagObject)
{
pv.owner.TagObject = gameObject;
}
// please note: we change this setting on ANY PickupController if "DoRotate" is off. not only locally when it's "our" GameObject!
if (!this.DoRotate && pv.ObservedComponents != null)
{
for (int i = 0; i < pv.ObservedComponents.Count; ++i)
{
if (pv.ObservedComponents[i] is Transform)
{
pv.onSerializeTransformOption = OnSerializeTransform.OnlyPosition;
break;
}
}
}
}
this.moveDirection = transform.TransformDirection(Vector3.forward);
this._animation = GetComponent<Animation>();
if (!this._animation)
Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
if (!this.idleAnimation)
{
this._animation = null;
Debug.Log("No idle animation found. Turning off animations.");
}
if (!this.walkAnimation)
{
this._animation = null;
Debug.Log("No walk animation found. Turning off animations.");
}
if (!this.runAnimation)
{
this._animation = null;
Debug.Log("No run animation found. Turning off animations.");
}
if (!this.jumpPoseAnimation && this.canJump)
{
this._animation = null;
Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");
}
}
void Update()
{
if (this.isControllable)
{
if (Input.GetButtonDown("Jump"))
{
this.lastJumpButtonTime = Time.time;
}
this.UpdateSmoothedMovementDirection();
// Apply gravity
// - extra power jump modifies gravity
// - controlledDescent mode modifies gravity
this.ApplyGravity();
// Apply jumping logic
this.ApplyJumping();
// Calculate actual motion
Vector3 movement = this.moveDirection *this.moveSpeed + new Vector3(0, this.verticalSpeed, 0) + this.inAirVelocity;
movement *= Time.deltaTime;
//Debug.Log(movement.x.ToString("0.000") + ":" + movement.z.ToString("0.000"));
// Move the controller
CharacterController controller = GetComponent<CharacterController>();
this.collisionFlags = controller.Move(movement);
}
// PUN: if a remote position is known, we smooth-move to it (being late(r) but smoother)
if (this.remotePosition != Vector3.zero)
{
transform.position = Vector3.Lerp(transform.position, this.remotePosition, Time.deltaTime * this.RemoteSmoothing);
}
this.velocity = (transform.position - this.lastPos)*25;
// ANIMATION sector
if (this._animation)
{
if (this._characterState == PickupCharacterState.Jumping)
{
if (!this.jumpingReachedApex)
{
this._animation[this.jumpPoseAnimation.name].speed = this.jumpAnimationSpeed;
this._animation[this.jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
this._animation.CrossFade(this.jumpPoseAnimation.name);
}
else
{
this._animation[this.jumpPoseAnimation.name].speed = -this.landAnimationSpeed;
this._animation[this.jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
this._animation.CrossFade(this.jumpPoseAnimation.name);
}
}
else
{
if (this._characterState == PickupCharacterState.Idle)
{
this._animation.CrossFade(this.idleAnimation.name);
}
else if (this._characterState == PickupCharacterState.Running)
{
this._animation[this.runAnimation.name].speed = this.runMaxAnimationSpeed;
if (this.isControllable)
{
this._animation[this.runAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.runMaxAnimationSpeed);
}
this._animation.CrossFade(this.runAnimation.name);
}
else if (this._characterState == PickupCharacterState.Trotting)
{
this._animation[this.walkAnimation.name].speed = this.trotMaxAnimationSpeed;
if (this.isControllable)
{
this._animation[this.walkAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.trotMaxAnimationSpeed);
}
this._animation.CrossFade(this.walkAnimation.name);
}
else if (this._characterState == PickupCharacterState.Walking)
{
this._animation[this.walkAnimation.name].speed = this.walkMaxAnimationSpeed;
if (this.isControllable)
{
this._animation[this.walkAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.walkMaxAnimationSpeed);
}
this._animation.CrossFade(this.walkAnimation.name);
}
if (this._characterState != PickupCharacterState.Running)
{
this._animation[this.runAnimation.name].time = 0.0f;
}
}
}
// ANIMATION sector
// Set rotation to the move direction
if (this.IsGrounded())
{
// a specialty of this controller: you can disable rotation!
if (this.DoRotate)
{
transform.rotation = Quaternion.LookRotation(this.moveDirection);
}
}
else
{
/* This causes choppy behaviour when colliding with SIDES
* Vector3 xzMove = velocity;
xzMove.y = 0;
if (xzMove.sqrMagnitude > 0.001f)
{
transform.rotation = Quaternion.LookRotation(xzMove);
}*/
}
// We are in jump mode but just became grounded
if (this.IsGrounded())
{
this.lastGroundedTime = Time.time;
this.inAirVelocity = Vector3.zero;
if (this.jumping)
{
this.jumping = false;
SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
}
}
this.lastPos = transform.position;
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
stream.SendNext(transform.position);
stream.SendNext((byte)this._characterState);
}
else
{
bool initialRemotePosition = (this.remotePosition == Vector3.zero);
this.remotePosition = (Vector3)stream.ReceiveNext();
this._characterState = (PickupCharacterState)((byte)stream.ReceiveNext());
if (initialRemotePosition)
{
// avoids lerping the character from "center" to the "current" position when this client joins
transform.position = this.remotePosition;
}
}
}
void UpdateSmoothedMovementDirection()
{
Transform cameraTransform = Camera.main.transform;
bool grounded = this.IsGrounded();
// Forward vector relative to the camera along the x-z plane
Vector3 forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
// Right vector relative to the camera
// Always orthogonal to the forward vector
Vector3 right = new Vector3(forward.z, 0, -forward.x);
float v = Input.GetAxisRaw("Vertical");
float h = Input.GetAxisRaw("Horizontal");
// Are we moving backwards or looking backwards
if (v < -0.2f)
this.movingBack = true;
else
this.movingBack = false;
bool wasMoving = this.isMoving;
this.isMoving = Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f;
// Target direction relative to the camera
Vector3 targetDirection = h * right + v * forward;
// Debug.Log("targetDirection " + targetDirection);
// Grounded controls
if (grounded)
{
// Lock camera for short period when transitioning moving & standing still
this.lockCameraTimer += Time.deltaTime;
if (this.isMoving != wasMoving)
this.lockCameraTimer = 0.0f;
// We store speed and direction seperately,
// so that when the character stands still we still have a valid forward direction
// moveDirection is always normalized, and we only update it if there is user input.
if (targetDirection != Vector3.zero)
{
// If we are really slow, just snap to the target direction
if (this.moveSpeed < this.walkSpeed * 0.9f && grounded)
{
this.moveDirection = targetDirection.normalized;
}
// Otherwise smoothly turn towards it
else
{
this.moveDirection = Vector3.RotateTowards(this.moveDirection, targetDirection, this.rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
this.moveDirection = this.moveDirection.normalized;
}
}
// Smooth the speed based on the current target direction
float curSmooth = this.speedSmoothing * Time.deltaTime;
// Choose target speed
//* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
float targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0f);
this._characterState = PickupCharacterState.Idle;
// Pick speed modifier
if ((Input.GetKey(KeyCode.LeftShift) | Input.GetKey(KeyCode.RightShift)) && this.isMoving)
{
targetSpeed *= this.runSpeed;
this._characterState = PickupCharacterState.Running;
}
else if (Time.time - this.trotAfterSeconds > this.walkTimeStart)
{
targetSpeed *= this.trotSpeed;
this._characterState = PickupCharacterState.Trotting;
}
else if (this.isMoving)
{
targetSpeed *= this.walkSpeed;
this._characterState = PickupCharacterState.Walking;
}
this.moveSpeed = Mathf.Lerp(this.moveSpeed, targetSpeed, curSmooth);
// Reset walk time start when we slow down
if (this.moveSpeed < this.walkSpeed * 0.3f)
this.walkTimeStart = Time.time;
}
// In air controls
else
{
// Lock camera while in air
if (this.jumping)
this.lockCameraTimer = 0.0f;
if (this.isMoving)
this.inAirVelocity += targetDirection.normalized * Time.deltaTime *this.inAirControlAcceleration;
}
}
void ApplyJumping()
{
// Prevent jumping too fast after each other
if (this.lastJumpTime + this.jumpRepeatTime > Time.time)
return;
if (this.IsGrounded())
{
// Jump
// - Only when pressing the button down
// - With a timeout so you can press the button slightly before landing
if (this.canJump && Time.time < this.lastJumpButtonTime + this.jumpTimeout)
{
this.verticalSpeed = this.CalculateJumpVerticalSpeed(this.jumpHeight);
SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}
}
}
void ApplyGravity()
{
if (this.isControllable) // don't move player at all if not controllable.
{
// Apply gravity
//bool jumpButton = Input.GetButton("Jump");
// When we reach the apex of the jump we send out a message
if (this.jumping && !this.jumpingReachedApex && this.verticalSpeed <= 0.0f)
{
this.jumpingReachedApex = true;
SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
}
if (this.IsGrounded())
this.verticalSpeed = 0.0f;
else
this.verticalSpeed -= this.gravity * Time.deltaTime;
}
}
float CalculateJumpVerticalSpeed(float targetJumpHeight)
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * targetJumpHeight *this.gravity);
}
void DidJump()
{
this.jumping = true;
this.jumpingReachedApex = false;
this.lastJumpTime = Time.time;
//lastJumpStartHeight = transform.position.y;
this.lastJumpButtonTime = -10;
this._characterState = PickupCharacterState.Jumping;
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
// Debug.DrawRay(hit.point, hit.normal);
if (hit.moveDirection.y > 0.01f)
return;
}
public float GetSpeed()
{
return this.moveSpeed;
}
public bool IsJumping()
{
return this.jumping;
}
public bool IsGrounded()
{
return (this.collisionFlags & CollisionFlags.CollidedBelow) != 0;
}
public Vector3 GetDirection()
{
return this.moveDirection;
}
public bool IsMovingBackwards()
{
return this.movingBack;
}
public float GetLockCameraTimer()
{
return this.lockCameraTimer;
}
public bool IsMoving()
{
return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5f;
}
public bool HasJumpReachedApex()
{
return this.jumpingReachedApex;
}
public bool IsGroundedWithTimeout()
{
return this.lastGroundedTime + this.groundedTimeout > Time.time;
}
public void Reset()
{
gameObject.tag = "Player";
}
} | 412 | 0.876924 | 1 | 0.876924 | game-dev | MEDIA | 0.954949 | game-dev | 0.925686 | 1 | 0.925686 |
quack/quack | 1,409 | src/cli/Component.php | <?php
/**
* Quack Compiler and toolkit
* Copyright (C) 2015-2017 Quack and CONTRIBUTORS
*
* This file is part of Quack.
*
* Quack 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.
*
* Quack 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 Quack. If not, see <http://www.gnu.org/licenses/>.
*/
namespace QuackCompiler\Cli;
abstract class Component
{
private $state;
public function __construct($state)
{
$this->state = $state;
}
protected function setState($state)
{
foreach ($state as $prop => $value) {
$this->state[$prop] = $value;
}
$this->render();
}
protected function state() {
$props = func_get_args();
$result = [];
foreach ($props as $prop) {
$result[] = $this->state[$prop];
}
return 1 === count($result)
? $result[0]
: $result;
}
abstract public function render();
}
| 412 | 0.517704 | 1 | 0.517704 | game-dev | MEDIA | 0.258624 | game-dev | 0.710486 | 1 | 0.710486 |
SkriptLang/Skript | 7,507 | src/main/java/org/skriptlang/skript/bukkit/itemcomponents/equippable/EquippableWrapper.java | package org.skriptlang.skript.bukkit.itemcomponents.equippable;
import ch.njol.skript.Skript;
import ch.njol.skript.util.ItemSource;
import io.papermc.paper.datacomponent.DataComponentType.Valued;
import io.papermc.paper.datacomponent.DataComponentTypes;
import io.papermc.paper.datacomponent.item.Equippable;
import io.papermc.paper.datacomponent.item.Equippable.Builder;
import io.papermc.paper.registry.RegistryKey;
import io.papermc.paper.registry.set.RegistryKeySet;
import net.kyori.adventure.key.Key;
import org.bukkit.Registry;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
import org.skriptlang.skript.bukkit.itemcomponents.ComponentUtils;
import org.skriptlang.skript.bukkit.itemcomponents.ComponentWrapper;
import java.lang.reflect.Method;
import java.util.Collection;
/**
* A {@link ComponentWrapper} for getting and setting data on an {@link Equippable} component.
*/
@SuppressWarnings("UnstableApiUsage")
public class EquippableWrapper extends ComponentWrapper<Equippable, Builder> {
private static final boolean HAS_MODEL_METHOD = Skript.methodExists(Equippable.class, "model");
private static final @Nullable Method COMPONENT_MODEL_METHOD;
private static final @Nullable Method BUILDER_MODEL_METHOD;
public static final boolean HAS_EQUIP_ON_INTERACT = Skript.methodExists(Equippable.class, "equipOnInteract");
public static final boolean HAS_CAN_BE_SHEARED = Skript.methodExists(Equippable.class, "canBeSheared");
public static final boolean HAS_SHEAR_SOUND = Skript.methodExists(Equippable.class, "shearSound");
static {
// Paper changed '#model' to '#assetId' in 1.21.4
Method componentModelMethod = null;
Method builderModelMethod = null;
if (HAS_MODEL_METHOD) {
try {
componentModelMethod = Equippable.class.getDeclaredMethod("model");
builderModelMethod = Equippable.Builder.class.getDeclaredMethod("model", Key.class);
} catch (NoSuchMethodException ignored) {}
}
COMPONENT_MODEL_METHOD = componentModelMethod;
BUILDER_MODEL_METHOD = builderModelMethod;
}
public EquippableWrapper(ItemStack itemStack) {
super(itemStack);
}
public EquippableWrapper(ItemSource<?> itemSource) {
super(itemSource);
}
public EquippableWrapper(Equippable component) {
super(component);
}
public EquippableWrapper(Builder builder) {
super(builder);
}
@Override
public Valued<Equippable> getDataComponentType() {
return DataComponentTypes.EQUIPPABLE;
}
@Override
protected Equippable getComponent(ItemStack itemStack) {
Equippable equippable = itemStack.getData(DataComponentTypes.EQUIPPABLE);
if (equippable != null)
return equippable;
return Equippable.equippable(EquipmentSlot.HEAD).build();
}
@Override
protected Builder getBuilder(ItemStack itemStack) {
Equippable equippable = itemStack.getData(DataComponentTypes.EQUIPPABLE);
if (equippable != null)
return equippable.toBuilder();
return Equippable.equippable(EquipmentSlot.HEAD);
}
@Override
protected void setComponent(ItemStack itemStack, Equippable component) {
itemStack.setData(DataComponentTypes.EQUIPPABLE, component);
}
@Override
protected Builder getBuilder(Equippable component) {
return component.toBuilder();
}
@Override
public EquippableWrapper clone() {
EquippableWrapper clone = newWrapper();
Equippable base = getComponent();
clone.applyComponent(clone(base.slot()));
return clone;
}
/**
* Returns a cloned {@link Equippable} of this {@link EquippableWrapper} with a new {@link EquipmentSlot}.
*/
public Equippable clone(EquipmentSlot slot) {
Equippable base = getComponent();
Builder builder = Equippable.equippable(slot)
.allowedEntities(base.allowedEntities())
.cameraOverlay(base.cameraOverlay())
.damageOnHurt(base.damageOnHurt())
.dispensable(base.dispensable())
.equipSound(base.equipSound())
.swappable(base.swappable());
setAssetId(builder, getAssetId());
if (HAS_EQUIP_ON_INTERACT) {
builder.equipOnInteract(base.equipOnInteract());
}
if (HAS_CAN_BE_SHEARED) {
builder.canBeSheared(base.canBeSheared());
}
if (HAS_SHEAR_SOUND) {
builder.shearSound(base.shearSound());
}
return builder.build();
}
@Override
public Equippable newComponent() {
return newBuilder().build();
}
@Override
public Builder newBuilder() {
return Equippable.equippable(EquipmentSlot.HEAD);
}
@Override
public EquippableWrapper newWrapper() {
return newInstance();
}
/**
* Returns a {@link Collection} of {@link EntityType}s that are allowed to wear with this {@link EquippableWrapper}.
*/
public Collection<EntityType> getAllowedEntities() {
return getAllowedEntities(getComponent());
}
/**
* Updates the model/assetId of this {@link EquippableWrapper} with {@code key}.
* @param key The {@link Key} to set to.
*/
public void setAssetId(Key key) {
Builder builder = getBuilder();
setAssetId(builder, key);
applyBuilder(builder);
}
/**
* Returns the model/assetId {@link Key} of this {@link EquippableWrapper}.
*/
public Key getAssetId() {
return getAssetId(getComponent());
}
/**
* Get an {@link EquippableWrapper} with a new {@link Equippable} component.
*/
public static EquippableWrapper newInstance() {
return new EquippableWrapper(
Equippable.equippable(EquipmentSlot.HEAD)
);
}
/**
* Returns the model/assetId {@link Key} of {@code component}.
* <p>
* Paper 1.21.2 to 1.21.3 uses #model
* Paper 1.21.4+ uses #assetId
* </p>
* @param component The {@link Equippable} component to retrieve.
* @return The {@link Key}.
*/
public static Key getAssetId(Equippable component) {
if (HAS_MODEL_METHOD) {
assert COMPONENT_MODEL_METHOD != null;
try {
return (Key) COMPONENT_MODEL_METHOD.invoke(component);
} catch (Exception ignored) {}
}
return component.assetId();
}
/**
* Updates the model/assetId of {@code builder} with {@code key}.
* <p>
* Paper 1.21.2 to 1.21.3 uses #model
* Paper 1.21.4+ uses #assetId
* </p>
* @param builder The {@link Builder} to update.
* @param key The {@link Key} to set to.
* @return {@code builder}.
*/
public static Builder setAssetId(Builder builder, Key key) {
if (HAS_MODEL_METHOD) {
assert BUILDER_MODEL_METHOD != null;
try {
BUILDER_MODEL_METHOD.invoke(builder, key);
} catch (Exception ignored) {}
} else {
builder.assetId(key);
}
return builder;
}
/**
* Returns a {@link Collection} of {@link EntityType}s that are allowed to wear with this {@code component}.
* <p>
* Paper originally returns {@link RegistryKeySet} but has no real modification capabilities.
* </p>
* @param component The {@link Equippable} component to get from.
* @return The allowed {@link EntityType}s.
*/
public static Collection<EntityType> getAllowedEntities(Equippable component) {
return ComponentUtils.registryKeySetToCollection(component.allowedEntities(), Registry.ENTITY_TYPE);
}
/**
* Converts {@code entityTypes} into a {@link RegistryKeySet} to update the allowed entities of an {@link Equippable} component.
* @param entityTypes The allowed {@link EntityType}s.
* @return {@link RegistryKeySet} representation of {@code entityTypes}.
*/
public static RegistryKeySet<EntityType> convertAllowedEntities(Collection<EntityType> entityTypes) {
return ComponentUtils.collectionToRegistryKeySet(entityTypes, RegistryKey.ENTITY_TYPE);
}
}
| 412 | 0.900072 | 1 | 0.900072 | game-dev | MEDIA | 0.264518 | game-dev | 0.874403 | 1 | 0.874403 |
sourav-357/DSA-GFG | 1,131 | ProblemOfTheDay/RotateDequesByK.java | package ProblemOfTheDay;
import java.util.Deque;
class RotateDequesByK {
public static void rotateDeque(Deque<Integer> dq, int type, int k) {
// If the deque is empty, no rotation is needed.
if (dq.isEmpty()) {
return;
}
// Get the actual number of rotations needed (k mod size of deque)
int size = dq.size();
k = k % size;
// If the rotation is greater than 0, proceed with the rotation
if (k == 0) {
return; // No need to rotate if k is 0 after modulo operation
}
if (type == 1) {
// Right rotation (Clockwise): Move the last element to the front
for (int i = 0; i < k; i++) {
dq.addFirst(dq.removeLast()); // Remove the last element and add it at the front
}
} else if (type == 2) {
// Left rotation (Anti-clockwise): Move the first element to the back
for (int i = 0; i < k; i++) {
dq.addLast(dq.removeFirst()); // Remove the first element and add it at the back
}
}
}
}
| 412 | 0.823889 | 1 | 0.823889 | game-dev | MEDIA | 0.273248 | game-dev | 0.872517 | 1 | 0.872517 |
gnosygnu/xowa | 1,657 | 400_xowa/src/gplx/xowa/mediawiki/XophpBool_.java | /*
XOWA: the XOWA Offline Wiki Application
Copyright (C) 2012-2017 gnosygnu@gmail.com
XOWA is licensed under the terms of the General Public License (GPL) Version 3,
or alternatively under the terms of the Apache License Version 2.0.
You may use XOWA according to either of these licenses as is most appropriate
for your project on a case-by-case basis.
The terms of each license can be found in the source code repository:
GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt
Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt
*/
package gplx.xowa.mediawiki; import gplx.*; import gplx.xowa.*;
public class XophpBool_ {
public static final boolean Null = false;
public static boolean is_true(byte[] val) {return val != null && is_true(String_.new_u8(val));}
public static boolean is_true(String val) {
// REF: https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
if (String_.Len_eq_0(val)) return false; // the empty String ...
String val_upper = String_.Upper(val);
if (String_.Eq(val_upper, "FALSE")) { // the boolean FALSE itself
return false;
}
double val_double = Double_.parse_or(val, -1); // pick "-1" as marker for invalid doubles; only care about comparing to "0"
// the integers 0 and -0 (zero)
// the floats 0.0 and -0.0 (zero)
// ... and the String "0"
if (val_double == 0) {
return false;
}
// Skip these as they shouldn't render in String serialization
// * an array with zero elements
// * the special type NULL (including unset variables)
// * SimpleXML objects created from empty tags
return true;
}
}
| 412 | 0.664789 | 1 | 0.664789 | game-dev | MEDIA | 0.449046 | game-dev | 0.527062 | 1 | 0.527062 |
CraftJarvis/MineStudio | 4,453 | minestudio/simulator/minerl/Malmo/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/RewardForSendingCommandImplementation.java | // --------------------------------------------------------------------------------------------------
// Copyright (c) 2016 Microsoft Corporation
//
// 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 com.microsoft.Malmo.MissionHandlers;
import com.microsoft.Malmo.MissionHandlerInterfaces.ICommandHandler;
import com.microsoft.Malmo.MissionHandlerInterfaces.IRewardProducer;
import com.microsoft.Malmo.Schemas.MissionInit;
import com.microsoft.Malmo.Schemas.RewardForSendingCommand;
/**
* Simple discrete reward signal, which tests for movement, goal-reaching, and
* lava-swimming.<br>
*/
public class RewardForSendingCommandImplementation extends RewardBase implements IRewardProducer {
protected float rewardPerCommand;
protected Integer commandTally = 0;
private RewardForSendingCommand params;
@Override
public boolean parseParameters(Object params) {
super.parseParameters(params);
if (params == null || !(params instanceof RewardForSendingCommand))
return false;
this.params = (RewardForSendingCommand) params;
this.rewardPerCommand = this.params.getReward().floatValue();
return true;
}
@Override
public void prepare(MissionInit missionInit) {
super.prepare(missionInit);
// We need to see the commands as they come in, so we can calculate the
// reward.
// To do this we create our own command handler and insert it at the
// root of the command chain.
// This is also how the ObservationFromRecentCommands handler works.
// It's slightly dirty behaviour, but it's cleaner than the other
// options!
MissionBehaviour mb = parentBehaviour();
ICommandHandler oldch = mb.commandHandler;
CommandGroup newch = new CommandGroup() {
protected boolean onExecute(String verb, String parameter, MissionInit missionInit) {
// See if this command gets handled by the legitimate handlers:
boolean handled = super.onExecute(verb, parameter, missionInit);
if (handled) // Yes, so record it:
{
synchronized (RewardForSendingCommandImplementation.this.commandTally) {
RewardForSendingCommandImplementation.this.commandTally++;
}
}
return handled;
}
};
newch.setOverriding((oldch != null) ? oldch.isOverriding() : true);
if (oldch != null)
newch.addCommandHandler(oldch);
mb.commandHandler = newch;
}
@Override
public void cleanup() {
super.cleanup();
}
@Override
public void getReward(MissionInit missionInit, MultidimensionalReward reward) {
super.getReward(missionInit, reward);
synchronized (RewardForSendingCommandImplementation.this.commandTally) {
if( this.commandTally > 0) {
float reward_value = this.rewardPerCommand * this.commandTally;
float adjusted_reward = adjustAndDistributeReward(reward_value, this.params.getDimension(), this.params.getDistribution());
reward.add( this.params.getDimension(), adjusted_reward );
this.commandTally = 0;
}
}
}
}
| 412 | 0.930501 | 1 | 0.930501 | game-dev | MEDIA | 0.689465 | game-dev | 0.920979 | 1 | 0.920979 |
Interkarma/daggerfall-unity | 3,604 | Assets/Scripts/Game/UserInterface/HUDFlickerBase.cs | using UnityEngine;
using System.Collections;
using DaggerfallWorkshop.Game;
namespace DaggerfallWorkshop.Game.UserInterface
{
public abstract class HUDFlickerBase
{
public enum AlphaDirection
{
None,
Decreasing,
Increasing
}
protected AlphaDirection alphaDirection;
protected float chanceReverseState = 0;
protected float alphaSpeed;
protected float alphaUpper;
protected float alphaLower;
public float RedValue { get; protected set; }
public float AlphaValue { get; protected set; }
protected int reversalCount = 0;
protected int reversalCountThreshold;
public bool IsTimedOut { get; set; }
public HUDFlickerBase()
{
Init();
}
public abstract void Init();
public virtual void CheckReverseAlphaDirection()
{
// Alpha Direction Reversal Check
if ((alphaDirection == AlphaDirection.Increasing && AlphaValue >= alphaUpper) ||
(alphaDirection == AlphaDirection.Decreasing && AlphaValue <= alphaLower))
ReverseAlphaDirection();
else if (AlphaValue >= alphaLower && AlphaValue <= alphaUpper)
RandomlyReverseAlphaDirection();
}
protected void RandomlyReverseAlphaDirection()
{
const float minChance = -0.01f; // negative so it takes a little while before it can reverse at least.
const float chanceStep = 0.008f;
if (alphaDirection == AlphaDirection.None)
return;
// chance of reversal grows over time.
chanceReverseState += chanceStep * Time.deltaTime;
// randomly reverse alpha
if (Random.Range(0f, 1f) < chanceReverseState)
{
// chance gets reset each time it's randomly reversed.
chanceReverseState = minChance;
ReverseAlphaDirection();
}
}
private void ReverseAlphaDirection()
{
if (alphaDirection == AlphaDirection.Increasing)
alphaDirection = AlphaDirection.Decreasing;
else if (alphaDirection == AlphaDirection.Decreasing)
alphaDirection = AlphaDirection.Increasing;
if (reversalCount != -1)
reversalCount++;
}
protected void SetAlphaValue(float overrideValue = -1)
{
if (overrideValue != -1)
{
AlphaValue = overrideValue;
return;
}
// set alpha depending on State
if ((reversalCount >= reversalCountThreshold && reversalCountThreshold != -1)
|| alphaDirection == AlphaDirection.None)
AlphaValue = 0;
else if (alphaDirection == AlphaDirection.Decreasing)
AlphaValue -= alphaSpeed * Time.deltaTime;
else if (alphaDirection == AlphaDirection.Increasing)
AlphaValue += alphaSpeed * Time.deltaTime;
AlphaValue = Mathf.Clamp(AlphaValue, 0, alphaUpper);
}
public virtual void Cycle()
{
if (!IsTimedOut)
{
if (reversalCount >= reversalCountThreshold && reversalCountThreshold != -1)
{
IsTimedOut = true;
}
CheckReverseAlphaDirection();
SetAlphaValue();
}
else
SetAlphaValue(0);
}
}
} | 412 | 0.926861 | 1 | 0.926861 | game-dev | MEDIA | 0.782629 | game-dev | 0.941361 | 1 | 0.941361 |
MemoriesOfTime/Nukkit-MOT | 2,780 | src/main/java/cn/nukkit/utils/CameraPresetManager.java | package cn.nukkit.utils;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.command.data.CommandEnum;
import cn.nukkit.math.Vector3f;
import cn.nukkit.network.protocol.UpdateSoftEnumPacket;
import cn.nukkit.network.protocol.types.camera.CameraPreset;
import lombok.Getter;
import org.cloudburstmc.protocol.common.DefinitionRegistry;
import org.cloudburstmc.protocol.common.NamedDefinition;
import org.cloudburstmc.protocol.common.SimpleDefinitionRegistry;
import javax.annotation.Nullable;
import java.util.Map;
import java.util.TreeMap;
public class CameraPresetManager {
@Getter
private static DefinitionRegistry<NamedDefinition> cameraPresetDefinitions;
private static final Map<String, CameraPreset> PRESETS = new TreeMap<>();
public static Map<String, CameraPreset> getPresets() {
return PRESETS;
}
@Nullable
public static CameraPreset getPreset(String identifier) {
return getPresets().get(identifier);
}
public static void registerCameraPresets(CameraPreset... presets) {
for (var preset : presets) {
if (PRESETS.containsKey(preset.getIdentifier())) {
throw new IllegalArgumentException("Camera preset " + preset.getIdentifier() + " already exists!");
}
PRESETS.put(preset.getIdentifier(), preset);
CommandEnum.CAMERA_PRESETS.updateSoftEnum(UpdateSoftEnumPacket.Type.ADD, preset.getIdentifier());
}
int id = 0;
//重新分配id
SimpleDefinitionRegistry.Builder<NamedDefinition> builder = SimpleDefinitionRegistry.builder();
for (var preset : presets) {
preset.setRuntimeId(id++);
builder.add(preset);
}
cameraPresetDefinitions = builder.build();
Server.getInstance().getOnlinePlayers().values().forEach(Player::sendCameraPresets);
}
public static final CameraPreset FIRST_PERSON;
public static final CameraPreset FREE;
public static final CameraPreset THIRD_PERSON;
public static final CameraPreset THIRD_PERSON_FRONT;
static {
FIRST_PERSON = CameraPreset.builder()
.identifier("minecraft:first_person")
.build();
FREE = CameraPreset.builder()
.identifier("minecraft:free")
.pos(new Vector3f(0, 0, 0))
.yaw(0F)
.pitch(0F)
.build();
THIRD_PERSON = CameraPreset.builder()
.identifier("minecraft:third_person")
.build();
THIRD_PERSON_FRONT = CameraPreset.builder()
.identifier("minecraft:third_person_front")
.build();
registerCameraPresets(FIRST_PERSON, FREE, THIRD_PERSON, THIRD_PERSON_FRONT);
}
}
| 412 | 0.832423 | 1 | 0.832423 | game-dev | MEDIA | 0.474092 | game-dev | 0.902494 | 1 | 0.902494 |
magefree/mage | 2,673 | Mage.Sets/src/mage/cards/r/RoryWilliams.java | package mage.cards.r;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.CastSourceTriggeredAbility;
import mage.abilities.effects.common.ExileSpellWithTimeCountersEffect;
import mage.abilities.effects.keyword.InvestigateEffect;
import mage.abilities.keyword.*;
import mage.constants.*;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.stack.Spell;
/**
*
* @author Skiwkr
*/
public final class RoryWilliams extends CardImpl {
public RoryWilliams(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{W}{U}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.SOLDIER);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// Partner with Amy Pond
this.addAbility(new PartnerWithAbility("Amy Pond"));
// First strike
this.addAbility(FirstStrikeAbility.getInstance());
// Lifelink
this.addAbility(LifelinkAbility.getInstance());
// The Last Centurion -- When you cast this spell from anywhere other than exile, exile it with three time counters on it. It gains suspend. Then investigate.
Ability ability = new RoryWilliamsTriggeredAbility(new ExileSpellWithTimeCountersEffect(3, true)
.setText("exile it with three time counters on it. It gains suspend"));
ability.addEffect(new InvestigateEffect(1).concatBy("Then"));
ability.withFlavorWord("The Last Centurion");
this.addAbility(ability);
}
private RoryWilliams(final RoryWilliams card) {
super(card);
}
@Override
public RoryWilliams copy() {
return new RoryWilliams(this);
}
}
class RoryWilliamsTriggeredAbility extends CastSourceTriggeredAbility {
RoryWilliamsTriggeredAbility(Effect effect) {
super(effect, false);
setRuleAtTheTop(true);
setTriggerPhrase("When you cast this spell from anywhere other than exile, ");
}
private RoryWilliamsTriggeredAbility(final RoryWilliamsTriggeredAbility ability) {
super(ability);
}
@Override
public RoryWilliamsTriggeredAbility copy() {
return new RoryWilliamsTriggeredAbility(this);
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
return super.checkTrigger(event,game)
&& !((Spell) game.getObject(sourceId)).getFromZone().equals(Zone.EXILED);
}
}
| 412 | 0.925748 | 1 | 0.925748 | game-dev | MEDIA | 0.85635 | game-dev | 0.9846 | 1 | 0.9846 |
RoyTheunissen/Asset-Palette | 1,715 | Editor/Entries/GuidBasedReference.cs | using System;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace RoyTheunissen.AssetPalette
{
/// <summary>
/// There's two reasons why you should be using this class instead of having direct Object references:
///
/// - This way the actual loading of the assets is delayed as much as possible. The palette will not load any of
/// the references until it's necessary, for example for generating a preview or actually using a palette entry.
///
/// - This way the Personal Palette can correctly serialize and deserialize the asset reference. The Personal
/// Palette is not stored in an asset but is stored in the EditorPrefs as JSON instead. By default Unity's
/// JSON utility does not seem to deserialize asset references correctly and they will become corrupt.
/// </summary>
[Serializable]
public class GuidBasedReference<T> where T : Object
{
[SerializeField] private string guid;
public bool HasGuid => !string.IsNullOrEmpty(guid);
private bool didCacheAsset;
private T cachedAsset;
public T Asset
{
get
{
if (!didCacheAsset)
{
cachedAsset = AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(guid));
didCacheAsset = cachedAsset != null;
}
return cachedAsset;
}
}
public GuidBasedReference(T targetObject)
{
guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(targetObject));
cachedAsset = targetObject;
didCacheAsset = true;
}
}
}
| 412 | 0.916975 | 1 | 0.916975 | game-dev | MEDIA | 0.875116 | game-dev | 0.944741 | 1 | 0.944741 |
andrewlock/NetEscapades.EnumGenerators | 5,474 | src/NetEscapades.EnumGenerators.Interceptors/README.md | #  NetEscapades.EnumGenerators.Interceptors
A source generator interceptor for automatically intercepting calls to `ToString()` on enums, and replacing them with calls to `ToStringFast()` generated by [NetEscapades.EnumGenerators](https://www.nuget.org/packages/NetEscapades.EnumGenerators)
> This source generator requires the .NET 8.0.400 SDK. You can target earlier frameworks like .NET Core 3.1 etc, but the _SDK_ must be at least 8.0.400
## Why use this package?
Many methods that operate with enums, such as the `ToString()` or `HasFlag()` method, are surprisingly slow. The [NetEscapades.EnumGenerators](https://www.nuget.org/packages/NetEscapades.EnumGenerators) uses a source generator to provide _fast_ versions of these methods, such as `ToStringFast()` or `HasFlagFast()`.
The main downside to the extension methods generated by [NetEscapades.EnumGenerators](https://www.nuget.org/packages/NetEscapades.EnumGenerators) is that you have to remember to use them. The [NetEscapades.EnumGenerators.Interceptors](https://www.nuget.org/packages/NetEscapades.EnumGenerators.Interceptors) package solves this problem by intercepting calls to `ToString()` and replacing them with calls `ToStringFast()` automatically using the .NET compiler feature called [interceptors](https://github.com/dotnet/roslyn/blob/main/docs/features/interceptors.md).
> Interceptors were introduced as an experimental feature in C#12 with .NET 8, and are stable in .NET 9. They allow a source generator to "intercept" certain method calls, and replace the call with a different one.
For example if you have this code:
```csharp
var choice = Color.Red;
Console.WriteLine("You chose: " + choice.ToString());
public enum Color
{
Red = 0,
Blue = 1,
}
```
When you use the [NetEscapades.EnumGenerators.Interceptors](https://www.nuget.org/packages/NetEscapades.EnumGenerators.Interceptors), the interceptor automatically replaces the call to `choice.ToString()` at compile-time with a call to `ToStringFast()`, as though you wrote the following:
```csharp
// The compiler replaces the call with this 👇
Console.WriteLine("You chose: " + choice.ToStringFast());
```
There are many caveats to this behaviour, as described below, but any explicit calls to `ToString()` or `HasFlag()` on a supported enum are replaced automatically.
## Adding NetEscapades.EnumGenerators.Interceptors to your project
Add the package to your application using:
```bash
dotnet add package NetEscapades.EnumGenerators.Interceptors
```
This adds a `<PackageReference>` to your project. You can additionally mark the package as `PrivateAssets="all"` and `ExcludeAssets="runtime"`.
> Setting `PrivateAssets="all"` means any projects referencing this one won't get a reference to the _NetEscapades.EnumGenerators.Interceptors_ package. Setting `ExcludeAssets="runtime"` ensures the _NetEscapades.EnumGenerators.Interceptors.Attributes.dll_ file is _not_ copied to your build output (it is not required at runtime).
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<!-- Add the package -->
<PackageReference Include="NetEscapades.EnumGenerators.Interceptors" Version="1.0.0-beta14"
PrivateAssets="all" ExcludeAssets="runtime" />
<!-- -->
</Project>
```
## Enabling interception for an enum
By default, adding [NetEscapades.EnumGenerators.Interceptors](https://www.nuget.org/packages/NetEscapades.EnumGenerators.Interceptors) to a project enables interception for all enums _defined in that project_ that use the `[EnumExtensions]` or `[EnumExtensions<T>]` attributes. If you wish to intercept calls made to enums with extensions defined in _other_ projects, you must add the `[Interceptable<T>]` attribute in the project where you want the interception to happen, e.g.
```csharp
[assembly:Interceptable<DateTimeKind>]
[assembly:Interceptable<Color>]
```
If you don't want a specific enum to be intercepted, you can set the `IsInterceptable` property to `false`, e.g.
```csharp
[EnumExtensions(IsInterceptable = false)]
public enum Colour
{
Red = 0,
Blue = 1,
}
```
Interception only works when the target type is unambiguously an interceptable enum, so it won't work
- When `ToString()` is called in other source generated code.
- When `ToString()` is called in already-compiled code.
- If the `ToString()` call is _implicit_ (for example in `string` interpolation)
- If the `ToString()` call is made on a base type, such as `System.Enum` or `object`
- If the `ToString()` call is made on a generic type
For example:
```csharp
// All the examples in this method CAN be intercepted
public void CanIntercept()
{
var ok1 = Color.Red.ToString(); // ✅
var red = Color.Red;
var ok2 = red.ToString(); // ✅
var ok3 = "The colour is " + red.ToString(); // ✅
var ok4 = $"The colour is {red.ToString()}"; // ✅
}
// The examples in this method can NOT be intercepted
public void CantIntercept()
{
var bad1 = ((System.Enum)Color.Red).ToString(); // ❌ Base type
var bad2 = ((object)Color.Red).ToString(); // ❌ Base type
var bad3 = "The colour is " + red; // ❌ implicit
var bad4 = $"The colour is {red}"; // ❌ implicit
string Write<T>(T val)
where T : Enum
{
return val.ToString(); // ❌ generic
}
}
``` | 412 | 0.884887 | 1 | 0.884887 | game-dev | MEDIA | 0.350983 | game-dev | 0.624905 | 1 | 0.624905 |
Fluorohydride/ygopro-scripts | 2,408 | c59069885.lua | --ティスティナの抱擁
local s,id,o=GetID()
function s.initial_effect(c)
--activate
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_ACTIVATE)
e0:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e0)
--change position
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_CHAINING)
e1:SetRange(LOCATION_SZONE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,id)
e1:SetCondition(s.cpcon)
e1:SetTarget(s.cptg)
e1:SetOperation(s.cpop)
c:RegisterEffect(e1)
--control
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_CONTROL)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetRange(LOCATION_SZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,id+o)
e2:SetCondition(s.ctcon)
e2:SetTarget(s.cttg)
e2:SetOperation(s.ctop)
c:RegisterEffect(e2)
end
function s.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x1a4) and c:IsDefenseAbove(3000)
end
function s.cpcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return rp==1-tp and re:GetHandler():IsOnField() and re:GetHandler():IsRelateToEffect(re) and re:IsActiveType(TYPE_MONSTER)
and Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function s.cptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local tc=re:GetHandler()
if chk==0 then return tc:IsCanChangePosition() and tc:IsRelateToEffect(re) and tc:IsCanBeEffectTarget(e) end
Duel.SetTargetCard(tc)
end
function s.cpop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.ChangePosition(tc,POS_FACEDOWN_DEFENSE)
end
end
function s.ctcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function s.filter(c,tp)
return c:IsFacedown() and c:IsControler(1-tp) and c:IsControlerCanBeChanged()
end
function s.cttg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and s.filter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(s.filter,tp,0,LOCATION_MZONE,1,nil,tp) end
local g=Duel.SelectTarget(tp,s.filter,tp,0,LOCATION_MZONE,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_CONTROL,g,1,0,0)
end
function s.ctop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.GetControl(tc,tp)
end
end
| 412 | 0.968391 | 1 | 0.968391 | game-dev | MEDIA | 0.915159 | game-dev | 0.972798 | 1 | 0.972798 |
Monkestation/Monkestation2.0 | 3,351 | code/modules/mob/living/basic/lavaland/legion/legion_ai.dm | /// Keep away and launch skulls at every opportunity, prioritising injured allies
/datum/ai_controller/basic_controller/legion
blackboard = list(
BB_TARGETING_STRATEGY = /datum/targeting_strategy/basic/legion,
BB_TARGET_MINIMUM_STAT = HARD_CRIT,
BB_AGGRO_RANGE = 5, // Unobservant
BB_BASIC_MOB_FLEE_DISTANCE = 6,
)
ai_movement = /datum/ai_movement/basic_avoidance
idle_behavior = /datum/idle_behavior/idle_random_walk
planning_subtrees = list(
/datum/ai_planning_subtree/random_speech/legion,
/datum/ai_planning_subtree/simple_find_target,
/datum/ai_planning_subtree/targeted_mob_ability,
/datum/ai_planning_subtree/flee_target/legion,
)
/// Chase and attack whatever we are targeting, if it's friendly we will heal them
/datum/ai_controller/basic_controller/legion_brood
blackboard = list(
BB_TARGETING_STRATEGY = /datum/targeting_strategy/basic/legion,
BB_TARGET_MINIMUM_STAT = HARD_CRIT,
)
ai_movement = /datum/ai_movement/basic_avoidance
idle_behavior = /datum/idle_behavior/idle_random_walk
planning_subtrees = list(
/datum/ai_planning_subtree/simple_find_target,
/datum/ai_planning_subtree/basic_melee_attack_subtree,
)
/// Target nearby friendlies if they are hurt (and are not themselves Legions)
/datum/targeting_strategy/basic/legion
/datum/targeting_strategy/basic/legion/faction_check(datum/ai_controller/controller, mob/living/living_mob, mob/living/the_target)
if (!living_mob.faction_check_atom(the_target, exact_match = check_factions_exactly))
return FALSE
if (istype(the_target, living_mob.type))
return TRUE
var/atom/created_by = living_mob.ai_controller.blackboard[BB_LEGION_BROOD_CREATOR]
if (!QDELETED(created_by) && istype(the_target, created_by.type))
return TRUE
return the_target.stat == DEAD || the_target.health >= the_target.maxHealth
/// Don't run away from friendlies
/datum/ai_planning_subtree/flee_target/legion
/datum/ai_planning_subtree/flee_target/legion/SelectBehaviors(datum/ai_controller/controller, seconds_per_tick)
var/mob/living/target = controller.blackboard[target_key]
if (QDELETED(target) || target.faction_check_atom(controller.pawn))
return // Only flee if we have a hostile target
return ..()
/// Make spooky sounds, if we have a corpse inside then impersonate them
/datum/ai_planning_subtree/random_speech/legion
speech_chance = 1
speak = list("Come...", "Legion...", "Why...?")
emote_hear = list("groans.", "wails.", "whimpers.")
emote_see = list("twitches.", "shudders.")
/// Stuff to specifically say into a radio
var/list/radio_speech = list("Come...", "Why...?")
/datum/ai_planning_subtree/random_speech/legion/speak(datum/ai_controller/controller)
var/mob/living/carbon/human/victim = controller.blackboard[BB_LEGION_CORPSE]
if (QDELETED(victim) || prob(30))
return ..()
var/list/remembered_speech = controller.blackboard[BB_LEGION_RECENT_LINES] || list()
if (length(remembered_speech) && prob(50)) // Don't spam the radio
controller.queue_behavior(/datum/ai_behavior/perform_speech, pick(remembered_speech))
return
var/obj/item/radio/mob_radio = locate() in victim.contents
if (QDELETED(mob_radio))
return ..() // No radio, just talk funny
controller.queue_behavior(/datum/ai_behavior/perform_speech_radio, pick(radio_speech + remembered_speech), mob_radio, list(RADIO_CHANNEL_SUPPLY, RADIO_CHANNEL_COMMON))
| 412 | 0.899906 | 1 | 0.899906 | game-dev | MEDIA | 0.988114 | game-dev | 0.919933 | 1 | 0.919933 |
SightstoneOfficial/LegendaryClient | 22,022 | LegendaryClient/Windows/FriendList.xaml.cs | using LegendaryClient.Controls;
using LegendaryClient.Logic;
using LegendaryClient.Logic.SQLite;
using LegendaryClient.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using LegendaryClient.Logic.Riot.Platform;
using Timer = System.Timers.Timer;
using LegendaryClient.Logic.Riot;
using System.Threading.Tasks;
using agsXMPP;
using agsXMPP.protocol.client;
namespace LegendaryClient.Windows
{
/// <summary>
/// Interaction logic for ChatPage.xaml
/// </summary>
public partial class FriendList
{
private static Timer UpdateTimer;
private LargeChatPlayer PlayerItem;
private ChatPlayerItem LastPlayerItem;
private SelectionChangedEventArgs selection;
bool loaded = false;
public FriendList()
{
InitializeComponent();
if (Settings.Default.StatusMsg != "Set your status message")
StatusBox.Text = Settings.Default.StatusMsg;
UpdateTimer = new Timer(5000);
UpdateTimer.Elapsed += UpdateChat;
UpdateTimer.Enabled = true;
UpdateTimer.Start();
Client.chatlistview = ChatListView;
}
private void PresenceChanger_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (PresenceChanger.SelectedIndex == -1)
return;
switch ((string)PresenceChanger.SelectedValue)
{
case "Online":
Client.CurrentPresence = PresenceType.available;
Client.presenceStatus = ShowType.chat;
break;
case "Busy":
//TODO: fix away status, for some reason its not doing anything but there is a function depending on presenceStatus being "away" or not so...
Client.CurrentPresence = PresenceType.available;
Client.presenceStatus = ShowType.away;
break;
case "Invisible":
Client.presenceStatus = ShowType.NONE;
Client.CurrentPresence = PresenceType.invisible;
break;
}
}
private void UpdateChat(object sender, ElapsedEventArgs e)
{
Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async () =>
{
if (Client.CurrentStatus != StatusBox.Text && StatusBox.Text != "Set your status message")
Client.CurrentStatus = StatusBox.Text;
else if (StatusBox.Text == "Set your status message")
Client.CurrentStatus = "Online";
Settings.Default.StatusMsg = StatusBox.Text;
Settings.Default.Save();
if (!Client.UpdatePlayers)
return;
Client.UpdatePlayers = false;
ChatListView.Children.Clear();
#region "Groups"
while (!Client.loadedGroups)
{
await Task.Delay(1000);
}
foreach (Group g in Client.Groups)
{
var playersListView = new ListView
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalContentAlignment = VerticalAlignment.Stretch
};
playersListView.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty,
ScrollBarVisibility.Disabled);
playersListView.Foreground = Brushes.White;
playersListView.Background = null;
playersListView.BorderBrush = null;
playersListView.MouseDoubleClick += PlayersListView_MouseDoubleClick;
playersListView.SelectionChanged += ChatListView_SelectionChanged;
playersListView.PreviewMouseWheel += PlayersListView_PreviewMouseWheel;
int players = 0;
foreach (var chatPlayerPair in Client.AllPlayers.ToArray().OrderBy(u => u.Value.Username))
{
var player = new ChatPlayer
{
Tag = chatPlayerPair.Value,
DataContext = chatPlayerPair.Value,
ContextMenu = (ContextMenu)Resources["PlayerChatMenu"],
PlayerName = { Content = chatPlayerPair.Value.Username },
LevelLabel = { Content = chatPlayerPair.Value.Level }
};
var bc = new BrushConverter();
var brush = (Brush)bc.ConvertFrom("#FFFFFFFF");
player.PlayerStatus.Content = chatPlayerPair.Value.Status;
player.PlayerStatus.Foreground = brush;
if (chatPlayerPair.Value.IsOnline && g.GroupName == chatPlayerPair.Value.Group)
{
player.Width = 250;
bc = new BrushConverter();
brush = (Brush)bc.ConvertFrom("#FFFFFFFF");
player.PlayerStatus.Foreground = brush;
string UriSource = Path.Combine(Client.ExecutingDirectory, "Assets", "profileicon",
chatPlayerPair.Value.ProfileIcon + ".png");
player.ProfileImage.Source = Client.GetImage(UriSource);
if (chatPlayerPair.Value.GameStatus != "outOfGame")
{
switch (chatPlayerPair.Value.GameStatus)
{
case "inGame":
champions inGameChamp = champions.GetChampion(chatPlayerPair.Value.Champion);
if (inGameChamp != null)
player.PlayerStatus.Content = "In Game as " + inGameChamp.displayName;
else
player.PlayerStatus.Content = "In Game";
break;
case "hostingPracticeGame":
player.PlayerStatus.Content = "Creating Custom Game";
break;
case "inQueue":
player.PlayerStatus.Content = "In Queue";
break;
case "spectating":
player.PlayerStatus.Content = "Spectating";
break;
case "championSelect":
player.PlayerStatus.Content = "In Champion Select";
break;
case "hostingRankedGame":
player.PlayerStatus.Content = "Creating Ranked Game";
break;
case "teamSelect":
player.PlayerStatus.Content = "In Team Select";
break;
case "hostingNormalGame":
player.PlayerStatus.Content = "Creating Normal Game";
break;
case "hostingCoopVsAIGame":
player.PlayerStatus.Content = "Creating Co-op vs. AI Game";
break;
case "inTeamBuilder":
player.PlayerStatus.Content = "In Team Builder";
break;
case "tutorial":
player.PlayerStatus.Content = "In Tutorial";
break;
}
brush = (Brush)bc.ConvertFrom("#FFFFFF99");
player.PlayerStatus.Foreground = brush;
}
player.MouseRightButtonDown += player_MouseRightButtonDown;
player.MouseMove += ChatPlayerMouseOver;
player.MouseLeave += player_MouseLeave;
playersListView.Items.Add(player);
players++;
}
else if (!chatPlayerPair.Value.IsOnline && g.GroupName == "Offline")
{
player.Width = 250;
player.Height = 30;
player.PlayerName.Margin = new Thickness(5, 2.5, 0, 0);
player.LevelLabel.Visibility = Visibility.Hidden;
player.ProfileImage.Visibility = Visibility.Hidden;
playersListView.Items.Add(player);
players++;
}
}
var groupControl = new ChatGroup
{
Width = 230,
PlayersLabel = { Content = players },
NameLabel = { Content = g.GroupName }
};
groupControl.GroupListView.Children.Add(playersListView);
if (g.IsOpen)
{
groupControl.ExpandLabel.Content = "-";
groupControl.GroupListView.Visibility = Visibility.Visible;
}
if (!string.IsNullOrEmpty(g.GroupName))
ChatListView.Children.Add(groupControl);
else Client.Log("Removed a group");
}
#endregion
if (ChatListView.Children.Count > 0 && ChatListView.Children[0] is ChatGroup && loaded)
{
//Stop droping 100 times
(ChatListView.Children[0] as ChatGroup).GroupGrid_MouseDown(null, null);
loaded = true;
}
}));
}
private void player_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
var item = (ChatPlayer)sender;
var playerItem = (ChatPlayerItem)item.Tag;
LastPlayerItem = playerItem;
}
private void PlayersListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (selection.AddedItems.Count <= 0)
return;
var player = (ChatPlayer)selection.AddedItems[0];
((ListView)e.Source).SelectedIndex = -1;
var playerItem = (ChatPlayerItem)player.Tag;
List<NotificationChatPlayer> items = new List<NotificationChatPlayer>();
foreach (object x in Client.ChatListView.Items)
{
if (x.GetType() == typeof(NotificationChatPlayer))
items.Add((NotificationChatPlayer)x);
}
if (items.Any(x => (string)x.PlayerLabelName.Content == playerItem.Username))
return;
var chatPlayer = new NotificationChatPlayer
{
Tag = playerItem,
PlayerName = playerItem.Username,
Margin = new Thickness(1, 0, 1, 0),
PlayerLabelName = { Content = playerItem.Username }
};
Client.ChatListView.Items.Add(chatPlayer);
}
private void PlayersListView_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Handled)
return;
e.Handled = true;
var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
{
RoutedEvent = MouseWheelEvent,
Source = sender
};
var parent = ((Control)sender).Parent as UIElement;
if (parent != null)
parent.RaiseEvent(eventArg);
}
private void player_MouseLeave(object sender, MouseEventArgs e)
{
if (PlayerItem == null)
return;
Client.MainGrid.Children.Remove(PlayerItem);
PlayerItem = null;
}
private void ChatPlayerMouseOver(object sender, MouseEventArgs e)
{
var item = (ChatPlayer)sender;
var playerItem = (ChatPlayerItem)item.Tag;
if (PlayerItem == null)
{
PlayerItem = new LargeChatPlayer();
Client.MainGrid.Children.Add(PlayerItem);
Panel.SetZIndex(PlayerItem, 5);
PlayerItem.Tag = playerItem;
if (Client.PlayerNote.Any(x => x.Key == playerItem.Username))
{
PlayerItem.Note.Text = Client.PlayerNote[playerItem.Username];
PlayerItem.Note.Foreground = Brushes.Green;
PlayerItem.Note.Visibility = Visibility.Visible;
}
PlayerItem.PlayerName.Content = playerItem.Username;
PlayerItem.PlayerLeague.Content = playerItem.LeagueTier + " " + playerItem.LeagueDivision;
PlayerItem.PlayerStatus.Text = playerItem.Status;
if (playerItem.RankedWins == 0)
PlayerItem.PlayerWins.Content = playerItem.Wins + " Normal Wins";
else
PlayerItem.PlayerWins.Content = playerItem.RankedWins + " Ranked Wins";
PlayerItem.LevelLabel.Content = playerItem.Level;
PlayerItem.UsingLegendary.Visibility = playerItem.UsingLegendary
? Visibility.Visible
: Visibility.Hidden;
//PlayerItem.Dev.Visibility = playerItem.IsLegendaryDev ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
string UriSource = Path.Combine(Client.ExecutingDirectory, "Assets", "profileicon",
playerItem.ProfileIcon + ".png");
PlayerItem.ProfileImage.Source = Client.GetImage(UriSource);
if (playerItem.Status != null)
{
}
else if (playerItem.Status == null)
{
Client.hidelegendaryaddition = true;
}
else
{
PlayerItem.PlayerStatus.Text = "";
}
if (playerItem.GameStatus != "outOfGame")
{
var elapsed = new TimeSpan();
if (playerItem.Timestamp != 0)
elapsed = DateTime.Now.Subtract(Client.JavaTimeStampToDateTime(playerItem.Timestamp));
switch (playerItem.GameStatus)
{
case "inGame":
champions inGameChamp = champions.GetChampion(playerItem.Champion);
if (inGameChamp != null)
PlayerItem.InGameStatus.Text = "In Game" + Environment.NewLine +
"Playing as " + inGameChamp.displayName +
Environment.NewLine +
"For " +
string.Format("{0} Minutes and {1} Seconds",
elapsed.Minutes, elapsed.Seconds);
else
PlayerItem.InGameStatus.Text = "In Game";
break;
case "hostingPracticeGame":
PlayerItem.InGameStatus.Text = "Creating Custom Game";
break;
case "inQueue":
PlayerItem.InGameStatus.Text = "In Queue" + Environment.NewLine +
"For " +
string.Format("{0} Minutes and {1} Seconds", elapsed.Minutes,
elapsed.Seconds);
break;
case "spectating":
PlayerItem.InGameStatus.Text = "Spectating";
break;
case "championSelect":
PlayerItem.InGameStatus.Text = "In Champion Select" + Environment.NewLine +
"For " +
string.Format("{0} Minutes and {1} Seconds", elapsed.Minutes,
elapsed.Seconds);
break;
case "hostingRankedGame":
PlayerItem.InGameStatus.Text = "Creating Ranked Game";
break;
case "teamSelect":
PlayerItem.InGameStatus.Text = "In Team Select";
break;
case "hostingNormalGame":
PlayerItem.InGameStatus.Text = "Creating Normal Game";
break;
case "hostingCoopVsAIGame":
PlayerItem.InGameStatus.Text = "Creating Co-op vs. AI Game";
break;
case "inTeamBuilder":
PlayerItem.InGameStatus.Text = "In Team Builder";
break;
case "tutorial":
PlayerItem.InGameStatus.Text = "In Tutorial";
break;
}
PlayerItem.InGameStatus.Visibility = Visibility.Visible;
}
PlayerItem.Width = 300;
PlayerItem.HorizontalAlignment = HorizontalAlignment.Right;
PlayerItem.VerticalAlignment = VerticalAlignment.Top;
}
Point mouseLocation = e.GetPosition(Client.MainGrid);
double yMargin = mouseLocation.Y;
if (yMargin + 195 > Client.MainGrid.ActualHeight)
yMargin = Client.MainGrid.ActualHeight - 195;
PlayerItem.Margin = new Thickness(0, yMargin, 250, 0);
}
private void ChatListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selection = e;
}
private void ProfileItem_Click(object sender, RoutedEventArgs e)
{
var item = (ChatPlayer)selection.AddedItems[0];
Client.Profile.GetSummonerProfile(item.PlayerName.Content.ToString());
Client.SwitchPage(Client.Profile);
}
private async void Invite_Click(object sender, RoutedEventArgs e)
{
if (Client.isOwnerOfGame)
await RiotCalls.Invite(LastPlayerItem.Id.Replace("sum", ""));
}
private async void AddFriendButton_Click(object sender, RoutedEventArgs e)
{
PublicSummoner user = await RiotCalls.GetSummonerByName(FriendAddBox.Text);
var Jid = new Jid("sum" + user.SummonerId, Client.XmppConnection.Server, "");
Client.PresManager.Subscribe(Jid);
FriendAddBox.Text = "";
}
private async void SpectateGame_Click(object sender, RoutedEventArgs e)
{
switch (LastPlayerItem.GameStatus)
{
case "inGame":
{
PlatformGameLifecycleDTO n =
await RiotCalls.RetrieveInProgressSpectatorGameInfo(LastPlayerItem.Username);
if (n.GameName != null)
Client.LaunchSpectatorGame(Client.Region.SpectatorIpAddress,
n.PlayerCredentials.ObserverEncryptionKey, (int)n.PlayerCredentials.GameId,
Client.Region.InternalName);
}
break;
case "spectating":
break;
}
}
private void RankedStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (Client.Dev)
{
Client.TierName = RankedStatus.SelectedItem.ToString().ToUpper();
Client.SetChatHover();
}
}
private void BlockFriend_Click(object sender, RoutedEventArgs e)
{
}
private async void RemoveFriend_Click(object sender, RoutedEventArgs e)
{
if (LastPlayerItem != null)
{
PublicSummoner sum = await RiotCalls.GetSummonerByName(LastPlayerItem.Username);
var Jid = new Jid("sum" + sum.SummonerId, Client.XmppConnection.Server, "");
Client.PresManager.Unsubscribe(Jid);
//Client.PresManager.Remove(Jid);
Client.AllPlayers.Remove(Jid.User);
Client.UpdatePlayers = true;
UpdateChat(null, null);
}
}
}
} | 412 | 0.95238 | 1 | 0.95238 | game-dev | MEDIA | 0.301969 | game-dev | 0.975997 | 1 | 0.975997 |
Pico-Developer/PICO-Unity-Integration-SDK | 3,914 | Runtime/Debugger/Scripts/Interaction/PXR_DefaultButton.cs | /*******************************************************************************
Copyright © 2015-2022 PICO Technology Co., Ltd.All rights reserved.
NOTICE:All information contained herein is, and remains the property of
PICO Technology Co., Ltd. The intellectual and technical concepts
contained herein are proprietary to PICO Technology Co., Ltd. and may be
covered by patents, patents in process, and are protected by trade secret or
copyright law. Dissemination of this information or reproduction of this
material is strictly forbidden unless prior written permission is obtained from
PICO Technology Co., Ltd.
*******************************************************************************/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
#if UNITY_EDITOR || DEVELOPMENT_BUILD
namespace Unity.XR.PXR.Debugger
{
public class PXR_DefaultButton : MonoBehaviour, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler
{
bool isButtonPress = false;
bool isButtonHover = false;
private float hoverSpeed = 0.8f;
[SerializeField] private Color defaultColor;
[SerializeField] private Color hoverColor;
[SerializeField] private GameObject panelGO;
[SerializeField] private GameObject[] panelList;
[SerializeField] private PXR_DefaultButton[] buttonList;
[SerializeField] private MeshRenderer bg;
[SerializeField] private MeshRenderer border;
[SerializeField] private Sprite sprite;
private float borderAlpha;
private void Start()
{
Reset();
}
private void OnValidate()
{
transform.GetChild(0).GetComponent<Image>().sprite = sprite;
}
// Called when the button is selected
public void OnPointerDown(PointerEventData eventData)
{
if (!isButtonPress)
{
border.material.color = hoverColor;
bg.material.color = defaultColor;
isButtonHover = false;
isButtonPress = true;
OpenPanel();
}
}
private void Update()
{
if (isButtonHover)
{
bg.material.color = Color.Lerp(bg.material.color, hoverColor, hoverSpeed * Time.deltaTime);
var borderColor = Color.Lerp(border.material.color, hoverColor, hoverSpeed * Time.deltaTime);
borderAlpha += hoverSpeed * Time.deltaTime;
borderColor.a = borderAlpha;
border.material.color = borderColor;
}
}
private void OpenPanel(){
for (var i = 0; i < panelList.Length; i++)
{
panelList[i].SetActive(false);
}
for (var i = 0; i<buttonList.Length; i++){
buttonList[i].Reset();
}
panelGO.SetActive(true);
if(panelGO.TryGetComponent(out IPXR_PanelManager manager)){
manager.Init();
}
}
public void OnPointerEnter(PointerEventData eventData)
{
if (!isButtonPress)
{
border.material.color = new Color(0, 0, 0, 0);
borderAlpha = 0f;
isButtonHover = true;
}
}
public void OnPointerExit(PointerEventData eventData)
{
if (!isButtonPress)
{
isButtonHover = false;
border.material.color = new Color(0, 0, 0, 0);
bg.material.color = defaultColor;
}
}
public void Reset()
{
bg.material.color = defaultColor;
border.material.color = new Color(0, 0, 0, 0);
isButtonPress = false;
isButtonHover = false;
panelGO.SetActive(false);
}
}
}
#endif | 412 | 0.834445 | 1 | 0.834445 | game-dev | MEDIA | 0.801198 | game-dev | 0.859227 | 1 | 0.859227 |
roubincode/ETCore | 3,556 | ETClient/Unity/Assets/ETFramework/Editor/ReferenceCollectorEditor/ReferenceCollectorEditor.cs | using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
[CustomEditor(typeof (ReferenceCollector))]
[CanEditMultipleObjects]
public class ReferenceCollectorEditor: Editor
{
private string searchKey
{
get
{
return _searchKey;
}
set
{
if (_searchKey != value)
{
_searchKey = value;
heroPrefab = referenceCollector.Get<Object>(searchKey);
}
}
}
private ReferenceCollector referenceCollector;
private Object heroPrefab;
private string _searchKey = "";
private void DelNullReference()
{
var dataProperty = serializedObject.FindProperty("data");
for (int i = dataProperty.arraySize - 1; i >= 0; i--)
{
var gameObjectProperty = dataProperty.GetArrayElementAtIndex(i).FindPropertyRelative("gameObject");
if (gameObjectProperty.objectReferenceValue == null)
{
dataProperty.DeleteArrayElementAtIndex(i);
}
}
}
private void OnEnable()
{
referenceCollector = (ReferenceCollector) target;
}
public override void OnInspectorGUI()
{
Undo.RecordObject(referenceCollector, "Changed Settings");
var dataProperty = serializedObject.FindProperty("data");
GUILayout.BeginHorizontal();
if (GUILayout.Button("添加引用"))
{
AddReference(dataProperty, Guid.NewGuid().GetHashCode().ToString(), null);
}
if (GUILayout.Button("全部删除"))
{
dataProperty.ClearArray();
}
if (GUILayout.Button("删除空引用"))
{
DelNullReference();
}
if (GUILayout.Button("排序"))
{
referenceCollector.Sort();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
searchKey = EditorGUILayout.TextField(searchKey);
EditorGUILayout.ObjectField(heroPrefab, typeof (Object), false);
if (GUILayout.Button("删除"))
{
referenceCollector.Remove(searchKey);
heroPrefab = null;
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
var delList = new List<int>();
SerializedProperty property;
for (int i = referenceCollector.data.Count - 1; i >= 0; i--)
{
GUILayout.BeginHorizontal();
property = dataProperty.GetArrayElementAtIndex(i).FindPropertyRelative("key");
property.stringValue = EditorGUILayout.TextField(property.stringValue, GUILayout.Width(150));
property = dataProperty.GetArrayElementAtIndex(i).FindPropertyRelative("gameObject");
property.objectReferenceValue = EditorGUILayout.ObjectField(property.objectReferenceValue, typeof(Object), true);
if (GUILayout.Button("X"))
{
delList.Add(i);
}
GUILayout.EndHorizontal();
}
var eventType = Event.current.type;
if (eventType == EventType.DragUpdated || eventType == EventType.DragPerform)
{
// Show a copy icon on the drag
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (eventType == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
foreach (var o in DragAndDrop.objectReferences)
{
AddReference(dataProperty, o.name, o);
}
}
Event.current.Use();
}
foreach (var i in delList)
{
dataProperty.DeleteArrayElementAtIndex(i);
}
serializedObject.ApplyModifiedProperties();
serializedObject.UpdateIfRequiredOrScript();
}
private void AddReference(SerializedProperty dataProperty, string key, Object obj)
{
int index = dataProperty.arraySize;
dataProperty.InsertArrayElementAtIndex(index);
var element = dataProperty.GetArrayElementAtIndex(index);
element.FindPropertyRelative("key").stringValue = key;
element.FindPropertyRelative("gameObject").objectReferenceValue = obj;
}
} | 412 | 0.892526 | 1 | 0.892526 | game-dev | MEDIA | 0.754185 | game-dev,desktop-app | 0.990037 | 1 | 0.990037 |
MCreator-Examples/Tale-of-Biomes | 2,015 | src/main/java/net/nwtg/taleofbiomes/block/PiruffLeavesBlock.java |
package net.nwtg.taleofbiomes.block;
import net.nwtg.taleofbiomes.init.TaleOfBiomesModBlocks;
import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent;
import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.api.distmarker.Dist;
import net.minecraft.world.level.pathfinder.PathType;
import net.minecraft.world.level.material.MapColor;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.LeavesBlock;
import net.minecraft.world.level.FoliageColor;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.entity.Mob;
import net.minecraft.core.Direction;
import net.minecraft.core.BlockPos;
import net.minecraft.client.renderer.BiomeColors;
public class PiruffLeavesBlock extends LeavesBlock {
public PiruffLeavesBlock() {
super(BlockBehaviour.Properties.of().ignitedByLava().mapColor(MapColor.PLANT).sound(SoundType.GRASS).strength(0.2f).noOcclusion());
}
@Override
public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {
return 1;
}
@Override
public int getFlammability(BlockState state, BlockGetter world, BlockPos pos, Direction face) {
return 30;
}
@Override
public PathType getBlockPathType(BlockState state, BlockGetter world, BlockPos pos, Mob entity) {
return PathType.BLOCKED;
}
@OnlyIn(Dist.CLIENT)
public static void blockColorLoad(RegisterColorHandlersEvent.Block event) {
event.getBlockColors().register((bs, world, pos, index) -> {
return world != null && pos != null ? BiomeColors.getAverageFoliageColor(world, pos) : FoliageColor.getDefaultColor();
}, TaleOfBiomesModBlocks.PIRUFF_LEAVES.get());
}
@OnlyIn(Dist.CLIENT)
public static void itemColorLoad(RegisterColorHandlersEvent.Item event) {
event.getItemColors().register((stack, index) -> {
return FoliageColor.getDefaultColor();
}, TaleOfBiomesModBlocks.PIRUFF_LEAVES.get());
}
}
| 412 | 0.700599 | 1 | 0.700599 | game-dev | MEDIA | 0.997333 | game-dev | 0.596594 | 1 | 0.596594 |
NanoAdblocker/NanoCore2 | 8,535 | src/js/nano-1p-filters.js | // ----------------------------------------------------------------------------------------------------------------- //
// Nano Core 2 - An adblocker
// Copyright (C) 2018-2019 Nano Core 2 contributors
//
// 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/>.
// ----------------------------------------------------------------------------------------------------------------- //
// Dashboard my filters tab script
// ----------------------------------------------------------------------------------------------------------------- //
"use strict";
// ----------------------------------------------------------------------------------------------------------------- //
var nano = nano || {};
// ----------------------------------------------------------------------------------------------------------------- //
nano.filters_cache = "";
nano.editor = new nano.Editor("userFilters", true, false);
nano.has_unsaved_changes = false;
// ----------------------------------------------------------------------------------------------------------------- //
window.hasUnsavedData = () => {
return nano.has_unsaved_changes;
};
// ----------------------------------------------------------------------------------------------------------------- //
nano.load_settings = async () => {
const wrap = await vAPI.messaging.send("dashboard", {
what: "userSettings",
name: "nanoEditorSoftWrap",
});
nano.editor.set_line_wrap(wrap === true);
nano.render_filters(true);
};
// ----------------------------------------------------------------------------------------------------------------- //
nano.render_filters = async (first) => {
const details = await vAPI.messaging.send("dashboard", {
what: "readUserFilters",
});
if (details instanceof Object === false || details.error)
return;
let content = details.content.trim();
nano.filters_cache = content;
if (content.length > 0)
content += "\n";
nano.editor.set_value_focus(content);
nano.filters_changed(false);
nano.render_anno();
if (first)
nano.editor.reset_undo();
};
nano.render_anno = async () => {
const data = await vAPI.messaging.send("dashboard", {
what: "nanoGetFilterLinterResult",
});
if (data)
nano.editor.set_anno(data.errors.concat(data.warnings));
};
// ----------------------------------------------------------------------------------------------------------------- //
nano.filters_changed = (changed) => {
if (typeof changed !== "boolean")
changed = nano.editor.get_unix_value().trim() !== nano.filters_cache;
const apply_disable = (id, disabled) => {
const elem = document.getElementById(id);
if (disabled)
elem.setAttribute("disabled", "");
else
elem.removeAttribute("disabled");
};
apply_disable("userFiltersApply", !changed);
apply_disable("userFiltersRevert", !changed);
nano.has_unsaved_changes = changed;
};
nano.filters_saved = () => {
vAPI.messaging.send("dashboard", {
what: "reloadAllFilters",
});
const btn = document.getElementById("userFiltersApply");
btn.setAttribute("disabled", "");
// Wait a bit for filters to finish compiling
setTimeout(nano.render_anno, 1000);
};
nano.filters_apply = async () => {
const details = await vAPI.messaging.send("dashboard", {
what: "writeUserFilters",
content: nano.editor.get_unix_value(),
});
if (details instanceof Object === false || details.error)
return;
nano.filters_cache = details.content.trim();
nano.editor.set_value_focus(details.content);
nano.filters_changed(false);
nano.filters_saved();
// TODO: Set the cursor back to its original position?
// TODO: Clear undo history?
};
nano.filters_revert = () => {
let content = nano.filters_cache;
if (content.length > 0)
content += "\n";
nano.editor.set_value_focus(content);
nano.filters_changed(false);
};
// ----------------------------------------------------------------------------------------------------------------- //
nano.import_picked = function () {
const abp_importer = (s) => {
const re_abp_subscription_extractor =
/\n\[Subscription\]\n+url=~[^\n]+([\x08-\x7E]*?)(?:\[Subscription\]|$)/ig;
const re_abp_filter_extractor = /\[Subscription filters\]([\x08-\x7E]*?)(?:\[Subscription\]|$)/i;
let matches = re_abp_subscription_extractor.exec(s);
if (matches === null)
return s;
const out = [];
do {
if (matches.length === 2) {
let filter_match = re_abp_filter_extractor.exec(matches[1].trim());
if (filter_match !== null && filter_match.length === 2)
out.push(filter_match[1].trim().replace(/\\\[/g, "["));
}
matches = re_abp_subscription_extractor.exec(s);
} while (matches !== null);
return out.join("\n");
};
const on_file_reader_load = function () {
let content = abp_importer(this.result);
content = uBlockDashboard.mergeNewLines(nano.editor.get_unix_value().trim(), content);
nano.editor.set_value_focus(content + "\n");
nano.filters_changed();
};
const file = this.files[0];
if (file === undefined || file.name === "")
return;
if (!file.type.startsWith("text"))
return;
const fr = new FileReader();
fr.onload = on_file_reader_load;
fr.readAsText(file);
};
nano.import_filters = () => {
const input = document.getElementById("importFilePicker");
input.value = "";
input.click();
};
// ----------------------------------------------------------------------------------------------------------------- //
nano.export_filters = () => {
const val = nano.editor.get_platform_value().trim();
if (val === "")
return;
const filename = vAPI.i18n("1pExportFilename")
.replace("{{datetime}}", uBlockDashboard.dateNowToSensibleString())
.replace(/ +/g, "_");
vAPI.download({
"url": "data:text/plain;charset=utf-8," + encodeURIComponent(val + nano.editor.get_platform_line_break()),
"filename": filename,
});
};
// ----------------------------------------------------------------------------------------------------------------- //
nano.init = () => {
let elem = document.getElementById("importUserFiltersFromFile");
elem.addEventListener("click", nano.import_filters);
elem = document.getElementById("importFilePicker");
elem.addEventListener("change", nano.import_picked);
elem = document.getElementById("exportUserFiltersToFile");
elem.addEventListener("click", nano.export_filters);
elem = document.getElementById("userFiltersApply");
elem.addEventListener("click", nano.filters_apply);
elem = document.getElementById("userFiltersRevert");
elem.addEventListener("click", nano.filters_revert);
nano.editor.on("change", nano.filters_changed);
nano.load_settings();
};
// ----------------------------------------------------------------------------------------------------------------- //
cloud.onPush = () => {
return nano.editor.get_unix_value();
};
cloud.onPull = (data, append) => {
if (typeof data !== "string")
return;
if (append)
data = uBlockDashboard.mergeNewLines(nano.editor.get_unix_value(), data);
nano.editor.set_value_focus(data);
nano.filters_changed();
};
// ----------------------------------------------------------------------------------------------------------------- //
nano.init();
nano.editor.on_key("save", "Ctrl-S", () => {
const btn = document.getElementById("userFiltersApply");
btn.click();
});
// ----------------------------------------------------------------------------------------------------------------- //
| 412 | 0.603464 | 1 | 0.603464 | game-dev | MEDIA | 0.260583 | game-dev | 0.924761 | 1 | 0.924761 |
Wurst-Imperium/Wurst7 | 4,781 | src/main/java/net/wurstclient/mixin/GameMenuScreenMixin.java | /*
* Copyright (c) 2014-2025 Wurst-Imperium and contributors.
*
* This source code is subject to the terms of the GNU General Public
* License, version 3. If a copy of the GPL was not distributed with this
* file, You can obtain one at: https://www.gnu.org/licenses/gpl-3.0.txt
*/
package net.wurstclient.mixin;
import java.util.ArrayList;
import java.util.List;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
import net.minecraft.client.gl.RenderPipelines;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.GameMenuScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.wurstclient.WurstClient;
import net.wurstclient.options.WurstOptionsScreen;
@Mixin(GameMenuScreen.class)
public abstract class GameMenuScreenMixin extends Screen
{
@Unique
private static final Identifier WURST_TEXTURE =
Identifier.of("wurst", "wurst_128.png");
@Unique
private ButtonWidget wurstOptionsButton;
private GameMenuScreenMixin(WurstClient wurst, Text title)
{
super(title);
}
@Inject(at = @At("TAIL"), method = "initWidgets()V")
private void onInitWidgets(CallbackInfo ci)
{
if(!WurstClient.INSTANCE.isEnabled())
return;
addWurstOptionsButton();
}
@Inject(at = @At("TAIL"),
method = "render(Lnet/minecraft/client/gui/DrawContext;IIF)V")
private void onRender(DrawContext context, int mouseX, int mouseY,
float partialTicks, CallbackInfo ci)
{
if(!WurstClient.INSTANCE.isEnabled() || wurstOptionsButton == null)
return;
int x = wurstOptionsButton.getX() + 34;
int y = wurstOptionsButton.getY() + 2;
int w = 63;
int h = 16;
int fw = 63;
int fh = 16;
float u = 0;
float v = 0;
context.state.goUpLayer();
context.drawTexture(RenderPipelines.GUI_TEXTURED, WURST_TEXTURE, x, y,
u, v, w, h, fw, fh);
}
@Unique
private void addWurstOptionsButton()
{
List<ClickableWidget> buttons = Screens.getButtons(this);
// Fallback position
int buttonX = width / 2 - 102;
int buttonY = 60;
int buttonWidth = 204;
int buttonHeight = 20;
for(ClickableWidget button : buttons)
{
// If feedback button exists, use its position
if(isTrKey(button, "menu.sendFeedback")
|| isTrKey(button, "menu.feedback"))
{
buttonY = button.getY();
break;
}
// If options button exists, go 24px above it
if(isTrKey(button, "menu.options"))
{
buttonY = button.getY() - 24;
break;
}
}
// Clear required space for Wurst Options
hideFeedbackReportAndServerLinksButtons();
ensureSpaceAvailable(buttonX, buttonY, buttonWidth, buttonHeight);
// Create Wurst Options button
MutableText buttonText = Text.literal(" Options");
wurstOptionsButton = ButtonWidget
.builder(buttonText, b -> openWurstOptions())
.dimensions(buttonX, buttonY, buttonWidth, buttonHeight).build();
buttons.add(wurstOptionsButton);
}
@Unique
private void hideFeedbackReportAndServerLinksButtons()
{
for(ClickableWidget button : Screens.getButtons(this))
if(isTrKey(button, "menu.sendFeedback")
|| isTrKey(button, "menu.reportBugs")
|| isTrKey(button, "menu.feedback")
|| isTrKey(button, "menu.server_links"))
button.visible = false;
}
@Unique
private void ensureSpaceAvailable(int x, int y, int width, int height)
{
// Check if there are any buttons in the way
ArrayList<ClickableWidget> buttonsInTheWay = new ArrayList<>();
for(ClickableWidget button : Screens.getButtons(this))
{
if(button.getRight() < x || button.getX() > x + width
|| button.getBottom() < y || button.getY() > y + height)
continue;
if(!button.visible)
continue;
buttonsInTheWay.add(button);
}
// If not, we're done
if(buttonsInTheWay.isEmpty())
return;
// If yes, clear space below and move the buttons there
ensureSpaceAvailable(x, y + 24, width, height);
for(ClickableWidget button : buttonsInTheWay)
button.setY(button.getY() + 24);
}
@Unique
private void openWurstOptions()
{
client.setScreen(new WurstOptionsScreen(this));
}
@Unique
private boolean isTrKey(ClickableWidget button, String key)
{
String message = button.getMessage().getString();
return message != null && message.equals(I18n.translate(key));
}
}
| 412 | 0.805518 | 1 | 0.805518 | game-dev | MEDIA | 0.937593 | game-dev | 0.896935 | 1 | 0.896935 |
ProjectIgnis/CardScripts | 2,897 | unofficial/c511007024.lua | --ダメージ・ブースト
--Damage Boost
--Scritped by Lyris
local s,id=GetID()
function s.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_CHAINING)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e1:SetCondition(s.condition)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCondition(s.condition2)
c:RegisterEffect(e2)
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
if tp==ep or not Duel.IsChainNegatable(ev) then return false end
if not re:IsActiveType(TYPE_MONSTER) and not re:IsActiveType(TYPE_TRAP) and not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return false end
local tex,ttg,ttc=Duel.GetOperationInfo(ev,CATEGORY_NEGATE)
if not tex or ttg==nil or ttc+ttg:FilterCount(Card.IsControler,nil,tp)-#ttg<=0 then return false end
local ex,cg,ct,cp,cv=Duel.GetOperationInfo(ev-1,CATEGORY_DAMAGE)
if ex and (cp~=tp or cp==PLAYER_ALL) then return true end
ex,cg,ct,cp,cv=Duel.GetOperationInfo(ev-1,CATEGORY_RECOVER)
return ex and (cp~=tp or cp==PLAYER_ALL) and Duel.IsPlayerAffectedByEffect(1-tp,EFFECT_REVERSE_RECOVER)
end
function s.condition2(e,tp,eg,ep,ev,re,r,rp)
if tp==ep or not Duel.IsChainNegatable(ev) then return false end
if not re:IsActiveType(TYPE_MONSTER) and not re:IsActiveType(TYPE_TRAP) and not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return false end
local tex,ttg,ttc=Duel.GetOperationInfo(ev,CATEGORY_DISABLE)
if not tex or ttg==nil or ttc+ttg:FilterCount(Card.IsControler,nil,tp)-#ttg<=0 then return false end
local ex,cg,ct,cp,cv=Duel.GetOperationInfo(ev-1,CATEGORY_DAMAGE)
if ex and (cp~=tp or cp==PLAYER_ALL) then return true end
ex,cg,ct,cp,cv=Duel.GetOperationInfo(ev-1,CATEGORY_RECOVER)
return ex and (cp~=tp or cp==PLAYER_ALL) and Duel.IsPlayerAffectedByEffect(1-tp,EFFECT_REVERSE_RECOVER)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
if re:GetHandler():IsRelateToEffect(re) and re:GetHandler():IsDestructable() then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,re:GetHandler(),1,0,0)
end
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) and Duel.Destroy(re:GetHandler(),REASON_EFFECT)~=0 then
--Duel.BreakEffect()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHANGE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(0,1)
e1:SetValue(s.damop)
e1:SetReset(RESET_CHAIN)
Duel.RegisterEffect(e1,tp)
Duel.RegisterFlagEffect(tp,id,RESET_PHASE|PHASE_END,0,1)
end
end
function s.damop(e,re,val,r,rp,rc)
local tp=e:GetHandlerPlayer()
local cc=Duel.GetCurrentChain()
if cc==0 or rp~=tp or (r&REASON_EFFECT)==0 or Duel.GetFlagEffect(tp,id)==0 then return val end
Duel.ResetFlagEffect(tp,id)
return val*2
end | 412 | 0.970359 | 1 | 0.970359 | game-dev | MEDIA | 0.875022 | game-dev | 0.974056 | 1 | 0.974056 |
Fewnity/Xenity-Engine | 16,014 | Xenity_Engine/include/bullet/BulletCollision/CollisionDispatch/btCompoundCompoundCollisionAlgorithm.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btCompoundCompoundCollisionAlgorithm.h"
#include "LinearMath/btQuickprof.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btCompoundShape.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btAabbUtil2.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
//USE_LOCAL_STACK will avoid most (often all) dynamic memory allocations due to resizing in processCollision and MycollideTT
#define USE_LOCAL_STACK 1
btShapePairCallback gCompoundCompoundChildShapePairCallback = 0;
btCompoundCompoundCollisionAlgorithm::btCompoundCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped)
:btCompoundCollisionAlgorithm(ci,body0Wrap,body1Wrap,isSwapped)
{
void* ptr = btAlignedAlloc(sizeof(btHashedSimplePairCache),16);
m_childCollisionAlgorithmCache= new(ptr) btHashedSimplePairCache();
const btCollisionObjectWrapper* col0ObjWrap = body0Wrap;
btAssert (col0ObjWrap->getCollisionShape()->isCompound());
const btCollisionObjectWrapper* col1ObjWrap = body1Wrap;
btAssert (col1ObjWrap->getCollisionShape()->isCompound());
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape());
m_compoundShapeRevision0 = compoundShape0->getUpdateRevision();
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape());
m_compoundShapeRevision1 = compoundShape1->getUpdateRevision();
}
btCompoundCompoundCollisionAlgorithm::~btCompoundCompoundCollisionAlgorithm()
{
removeChildAlgorithms();
m_childCollisionAlgorithmCache->~btHashedSimplePairCache();
btAlignedFree(m_childCollisionAlgorithmCache);
}
void btCompoundCompoundCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray)
{
int i;
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
((btCollisionAlgorithm*)pairs[i].m_userPointer)->getAllContactManifolds(manifoldArray);
}
}
}
void btCompoundCompoundCollisionAlgorithm::removeChildAlgorithms()
{
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
int numChildren = pairs.size();
int i;
for (i=0;i<numChildren;i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer;
algo->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(algo);
}
}
m_childCollisionAlgorithmCache->removeAllPairs();
}
struct btCompoundCompoundLeafCallback : btDbvt::ICollide
{
int m_numOverlapPairs;
const btCollisionObjectWrapper* m_compound0ColObjWrap;
const btCollisionObjectWrapper* m_compound1ColObjWrap;
btDispatcher* m_dispatcher;
const btDispatcherInfo& m_dispatchInfo;
btManifoldResult* m_resultOut;
class btHashedSimplePairCache* m_childCollisionAlgorithmCache;
btPersistentManifold* m_sharedManifold;
btCompoundCompoundLeafCallback (const btCollisionObjectWrapper* compound1ObjWrap,
const btCollisionObjectWrapper* compound0ObjWrap,
btDispatcher* dispatcher,
const btDispatcherInfo& dispatchInfo,
btManifoldResult* resultOut,
btHashedSimplePairCache* childAlgorithmsCache,
btPersistentManifold* sharedManifold)
:m_numOverlapPairs(0),m_compound0ColObjWrap(compound1ObjWrap),m_compound1ColObjWrap(compound0ObjWrap),m_dispatcher(dispatcher),m_dispatchInfo(dispatchInfo),m_resultOut(resultOut),
m_childCollisionAlgorithmCache(childAlgorithmsCache),
m_sharedManifold(sharedManifold)
{
}
void Process(const btDbvtNode* leaf0,const btDbvtNode* leaf1)
{
BT_PROFILE("btCompoundCompoundLeafCallback::Process");
m_numOverlapPairs++;
int childIndex0 = leaf0->dataAsInt;
int childIndex1 = leaf1->dataAsInt;
btAssert(childIndex0>=0);
btAssert(childIndex1>=0);
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(m_compound0ColObjWrap->getCollisionShape());
btAssert(childIndex0<compoundShape0->getNumChildShapes());
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(m_compound1ColObjWrap->getCollisionShape());
btAssert(childIndex1<compoundShape1->getNumChildShapes());
const btCollisionShape* childShape0 = compoundShape0->getChildShape(childIndex0);
const btCollisionShape* childShape1 = compoundShape1->getChildShape(childIndex1);
//backup
btTransform orgTrans0 = m_compound0ColObjWrap->getWorldTransform();
const btTransform& childTrans0 = compoundShape0->getChildTransform(childIndex0);
btTransform newChildWorldTrans0 = orgTrans0*childTrans0 ;
btTransform orgTrans1 = m_compound1ColObjWrap->getWorldTransform();
const btTransform& childTrans1 = compoundShape1->getChildTransform(childIndex1);
btTransform newChildWorldTrans1 = orgTrans1*childTrans1 ;
//perform an AABB check first
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0);
childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1);
btVector3 thresholdVec(m_resultOut->m_closestPointDistanceThreshold, m_resultOut->m_closestPointDistanceThreshold, m_resultOut->m_closestPointDistanceThreshold);
aabbMin0 -= thresholdVec;
aabbMax0 += thresholdVec;
if (gCompoundCompoundChildShapePairCallback)
{
if (!gCompoundCompoundChildShapePairCallback(childShape0,childShape1))
return;
}
if (TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
btCollisionObjectWrapper compoundWrap0(this->m_compound0ColObjWrap,childShape0, m_compound0ColObjWrap->getCollisionObject(),newChildWorldTrans0,-1,childIndex0);
btCollisionObjectWrapper compoundWrap1(this->m_compound1ColObjWrap,childShape1,m_compound1ColObjWrap->getCollisionObject(),newChildWorldTrans1,-1,childIndex1);
btSimplePair* pair = m_childCollisionAlgorithmCache->findPair(childIndex0,childIndex1);
btCollisionAlgorithm* colAlgo = 0;
if (m_resultOut->m_closestPointDistanceThreshold > 0)
{
colAlgo = m_dispatcher->findAlgorithm(&compoundWrap0, &compoundWrap1, 0, BT_CLOSEST_POINT_ALGORITHMS);
}
else
{
if (pair)
{
colAlgo = (btCollisionAlgorithm*)pair->m_userPointer;
}
else
{
colAlgo = m_dispatcher->findAlgorithm(&compoundWrap0, &compoundWrap1, m_sharedManifold, BT_CONTACT_POINT_ALGORITHMS);
pair = m_childCollisionAlgorithmCache->addOverlappingPair(childIndex0, childIndex1);
btAssert(pair);
pair->m_userPointer = colAlgo;
}
}
btAssert(colAlgo);
const btCollisionObjectWrapper* tmpWrap0 = 0;
const btCollisionObjectWrapper* tmpWrap1 = 0;
tmpWrap0 = m_resultOut->getBody0Wrap();
tmpWrap1 = m_resultOut->getBody1Wrap();
m_resultOut->setBody0Wrap(&compoundWrap0);
m_resultOut->setBody1Wrap(&compoundWrap1);
m_resultOut->setShapeIdentifiersA(-1,childIndex0);
m_resultOut->setShapeIdentifiersB(-1,childIndex1);
colAlgo->processCollision(&compoundWrap0,&compoundWrap1,m_dispatchInfo,m_resultOut);
m_resultOut->setBody0Wrap(tmpWrap0);
m_resultOut->setBody1Wrap(tmpWrap1);
}
}
};
static DBVT_INLINE bool MyIntersect( const btDbvtAabbMm& a,
const btDbvtAabbMm& b, const btTransform& xform, btScalar distanceThreshold)
{
btVector3 newmin,newmax;
btTransformAabb(b.Mins(),b.Maxs(),0.f,xform,newmin,newmax);
newmin -= btVector3(distanceThreshold, distanceThreshold, distanceThreshold);
newmax += btVector3(distanceThreshold, distanceThreshold, distanceThreshold);
btDbvtAabbMm newb = btDbvtAabbMm::FromMM(newmin,newmax);
return Intersect(a,newb);
}
static inline void MycollideTT( const btDbvtNode* root0,
const btDbvtNode* root1,
const btTransform& xform,
btCompoundCompoundLeafCallback* callback, btScalar distanceThreshold)
{
if(root0&&root1)
{
int depth=1;
int treshold=btDbvt::DOUBLE_STACKSIZE-4;
btAlignedObjectArray<btDbvt::sStkNN> stkStack;
#ifdef USE_LOCAL_STACK
ATTRIBUTE_ALIGNED16(btDbvt::sStkNN localStack[btDbvt::DOUBLE_STACKSIZE]);
stkStack.initializeFromBuffer(&localStack,btDbvt::DOUBLE_STACKSIZE,btDbvt::DOUBLE_STACKSIZE);
#else
stkStack.resize(btDbvt::DOUBLE_STACKSIZE);
#endif
stkStack[0]=btDbvt::sStkNN(root0,root1);
do {
btDbvt::sStkNN p=stkStack[--depth];
if(MyIntersect(p.a->volume,p.b->volume,xform, distanceThreshold))
{
if(depth>treshold)
{
stkStack.resize(stkStack.size()*2);
treshold=stkStack.size()-4;
}
if(p.a->isinternal())
{
if(p.b->isinternal())
{
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b->childs[1]);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b->childs[1]);
}
else
{
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[0],p.b);
stkStack[depth++]=btDbvt::sStkNN(p.a->childs[1],p.b);
}
}
else
{
if(p.b->isinternal())
{
stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[0]);
stkStack[depth++]=btDbvt::sStkNN(p.a,p.b->childs[1]);
}
else
{
callback->Process(p.a,p.b);
}
}
}
} while(depth);
}
}
void btCompoundCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
const btCollisionObjectWrapper* col0ObjWrap = body0Wrap;
const btCollisionObjectWrapper* col1ObjWrap= body1Wrap;
btAssert (col0ObjWrap->getCollisionShape()->isCompound());
btAssert (col1ObjWrap->getCollisionShape()->isCompound());
const btCompoundShape* compoundShape0 = static_cast<const btCompoundShape*>(col0ObjWrap->getCollisionShape());
const btCompoundShape* compoundShape1 = static_cast<const btCompoundShape*>(col1ObjWrap->getCollisionShape());
const btDbvt* tree0 = compoundShape0->getDynamicAabbTree();
const btDbvt* tree1 = compoundShape1->getDynamicAabbTree();
if (!tree0 || !tree1)
{
return btCompoundCollisionAlgorithm::processCollision(body0Wrap,body1Wrap,dispatchInfo,resultOut);
}
///btCompoundShape might have changed:
////make sure the internal child collision algorithm caches are still valid
if ((compoundShape0->getUpdateRevision() != m_compoundShapeRevision0) || (compoundShape1->getUpdateRevision() != m_compoundShapeRevision1))
{
///clear all
removeChildAlgorithms();
m_compoundShapeRevision0 = compoundShape0->getUpdateRevision();
m_compoundShapeRevision1 = compoundShape1->getUpdateRevision();
}
///we need to refresh all contact manifolds
///note that we should actually recursively traverse all children, btCompoundShape can nested more then 1 level deep
///so we should add a 'refreshManifolds' in the btCollisionAlgorithm
{
int i;
btManifoldArray manifoldArray;
#ifdef USE_LOCAL_STACK
btPersistentManifold localManifolds[4];
manifoldArray.initializeFromBuffer(&localManifolds,0,4);
#endif
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*) pairs[i].m_userPointer;
algo->getAllContactManifolds(manifoldArray);
for (int m=0;m<manifoldArray.size();m++)
{
if (manifoldArray[m]->getNumContacts())
{
resultOut->setPersistentManifold(manifoldArray[m]);
resultOut->refreshContactPoints();
resultOut->setPersistentManifold(0);
}
}
manifoldArray.resize(0);
}
}
}
btCompoundCompoundLeafCallback callback(col0ObjWrap,col1ObjWrap,this->m_dispatcher,dispatchInfo,resultOut,this->m_childCollisionAlgorithmCache,m_sharedManifold);
const btTransform xform=col0ObjWrap->getWorldTransform().inverse()*col1ObjWrap->getWorldTransform();
MycollideTT(tree0->m_root,tree1->m_root,xform,&callback, resultOut->m_closestPointDistanceThreshold);
//printf("#compound-compound child/leaf overlap =%d \r",callback.m_numOverlapPairs);
//remove non-overlapping child pairs
{
btAssert(m_removePairs.size()==0);
//iterate over all children, perform an AABB check inside ProcessChildShape
btSimplePairArray& pairs = m_childCollisionAlgorithmCache->getOverlappingPairArray();
int i;
btManifoldArray manifoldArray;
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
for (i=0;i<pairs.size();i++)
{
if (pairs[i].m_userPointer)
{
btCollisionAlgorithm* algo = (btCollisionAlgorithm*)pairs[i].m_userPointer;
{
btTransform orgTrans0;
const btCollisionShape* childShape0 = 0;
btTransform newChildWorldTrans0;
btTransform orgInterpolationTrans0;
childShape0 = compoundShape0->getChildShape(pairs[i].m_indexA);
orgTrans0 = col0ObjWrap->getWorldTransform();
orgInterpolationTrans0 = col0ObjWrap->getWorldTransform();
const btTransform& childTrans0 = compoundShape0->getChildTransform(pairs[i].m_indexA);
newChildWorldTrans0 = orgTrans0*childTrans0 ;
childShape0->getAabb(newChildWorldTrans0,aabbMin0,aabbMax0);
}
btVector3 thresholdVec(resultOut->m_closestPointDistanceThreshold, resultOut->m_closestPointDistanceThreshold, resultOut->m_closestPointDistanceThreshold);
aabbMin0 -= thresholdVec;
aabbMax0 += thresholdVec;
{
btTransform orgInterpolationTrans1;
const btCollisionShape* childShape1 = 0;
btTransform orgTrans1;
btTransform newChildWorldTrans1;
childShape1 = compoundShape1->getChildShape(pairs[i].m_indexB);
orgTrans1 = col1ObjWrap->getWorldTransform();
orgInterpolationTrans1 = col1ObjWrap->getWorldTransform();
const btTransform& childTrans1 = compoundShape1->getChildTransform(pairs[i].m_indexB);
newChildWorldTrans1 = orgTrans1*childTrans1 ;
childShape1->getAabb(newChildWorldTrans1,aabbMin1,aabbMax1);
}
aabbMin1 -= thresholdVec;
aabbMax1 += thresholdVec;
if (!TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
algo->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(algo);
m_removePairs.push_back(btSimplePair(pairs[i].m_indexA,pairs[i].m_indexB));
}
}
}
for (int i=0;i<m_removePairs.size();i++)
{
m_childCollisionAlgorithmCache->removeOverlappingPair(m_removePairs[i].m_indexA,m_removePairs[i].m_indexB);
}
m_removePairs.clear();
}
}
btScalar btCompoundCompoundCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
btAssert(0);
return 0.f;
}
| 412 | 0.949717 | 1 | 0.949717 | game-dev | MEDIA | 0.7196 | game-dev | 0.965933 | 1 | 0.965933 |
0xTas/stardust | 9,839 | src/main/java/dev/stardust/modules/StashBrander.java | package dev.stardust.modules;
import java.util.List;
import dev.stardust.Stardust;
import net.minecraft.item.Item;
import dev.stardust.util.MsgUtil;
import net.minecraft.item.ItemStack;
import net.minecraft.sound.SoundEvents;
import meteordevelopment.orbit.EventHandler;
import net.minecraft.screen.AnvilScreenHandler;
import meteordevelopment.meteorclient.settings.*;
import net.minecraft.component.DataComponentTypes;
import dev.stardust.mixin.accessor.AnvilScreenAccessor;
import net.minecraft.client.gui.screen.ingame.AnvilScreen;
import meteordevelopment.meteorclient.utils.player.InvUtils;
import meteordevelopment.meteorclient.events.world.TickEvent;
import meteordevelopment.meteorclient.systems.modules.Module;
import dev.stardust.mixin.accessor.AnvilScreenHandlerAccessor;
import meteordevelopment.meteorclient.systems.modules.Modules;
import meteordevelopment.meteorclient.systems.modules.player.EXPThrower;
/**
* @author Tas [0xTas] <root@0xTas.dev>
**/
public class StashBrander extends Module {
public StashBrander() { super(Stardust.CATEGORY, "StashBrander","Allows you to automatically rename items in bulk when using anvils."); }
private final Setting<List<Item>> itemList = settings.getDefaultGroup().add(
new ItemListSetting.Builder()
.name("items")
.description("Items to automatically rename (or exclude from being renamed, if blacklist mode is enabled.)")
.build()
);
private final Setting<String> itemName = settings.getDefaultGroup().add(
new StringSetting.Builder()
.name("custom-name")
.description("The name you want to give to qualifying items.")
.defaultValue("")
.onChanged(name -> {
if (name.length() > AnvilScreenHandler.MAX_NAME_LENGTH) {
MsgUtil.sendModuleMsg("§4Custom name exceeds max accepted length§8..!", this.name);
}
})
.build()
);
private final Setting<Boolean> blacklistMode = settings.getDefaultGroup().add(
new BoolSetting.Builder()
.name("blacklist-mode")
.description("Rename all items except the ones selected in the Items list.")
.defaultValue(false)
.build()
);
private final Setting<Boolean> renameNamed = settings.getDefaultGroup().add(
new BoolSetting.Builder()
.name("rename-prenamed")
.description("Rename items which already have a different custom name.")
.defaultValue(false)
.build()
);
private final Setting<Boolean> muteAnvils = settings.getDefaultGroup().add(
new BoolSetting.Builder()
.name("mute-anvils")
.defaultValue(true)
.build()
);
private final Setting<Boolean> pingOnDone = settings.getDefaultGroup().add(
new BoolSetting.Builder()
.name("sound-ping")
.description("Play a sound cue when no more items can be renamed.")
.defaultValue(true)
.build()
);
private final Setting<Double> pingVolume = settings.getDefaultGroup().add(
new DoubleSetting.Builder()
.name("ping-volume")
.sliderMin(0.0)
.sliderMax(5.0)
.defaultValue(0.5)
.build()
);
private final Setting<Boolean> disableOnDone = settings.getDefaultGroup().add(
new BoolSetting.Builder()
.name("disable-on-done")
.description("Automatically disable the module when no more items can be renamed.")
.defaultValue(false)
.build()
);
private final Setting<Boolean> enableExpThrower = settings.getDefaultGroup().add(
new BoolSetting.Builder()
.name("enable-exp-thrower")
.description("Automatically enable the Exp Thrower module when no more items can be renamed.")
.defaultValue(false)
.build()
);
private final Setting<Integer> tickRate = settings.getDefaultGroup().add(
new IntSetting.Builder()
.name("tick-rate")
.description("Increase this if the server is kicking you.")
.min(0).max(1000)
.sliderRange(1, 100)
.defaultValue(1)
.build()
);
private int timer = 0;
private boolean notified = false;
private static final int ANVIL_OFFSET = 3;
// See WorldMixin.java
public boolean shouldMute() { return muteAnvils.get(); }
private boolean hasValidItems(AnvilScreenHandler handler) {
if (mc.player == null) return false;
for (int n = 0; n < mc.player.getInventory().main.size() + ANVIL_OFFSET; n++) {
if (n == AnvilScreenHandler.OUTPUT_ID) continue;
ItemStack stack = handler.getSlot(n).getStack();
if ((blacklistMode.get() && !itemList.get().contains(stack.getItem()))
|| (!blacklistMode.get() && itemList.get().contains(stack.getItem())))
{
if (itemName.get().isBlank() && stack.contains(DataComponentTypes.CUSTOM_NAME)) {
return renameNamed.get();
} else if (!stack.getName().getString().equals(itemName.get())) {
return renameNamed.get() || !stack.contains(DataComponentTypes.CUSTOM_NAME);
}
}
}
return false;
}
private void noXP() {
if (mc.player == null) return;
if (!notified) {
MsgUtil.sendModuleMsg("Not enough experience§c..!", this.name);
if (pingOnDone.get()) mc.player.playSound(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, pingVolume.get().floatValue(), 1.0f);
}
notified = true;
mc.player.closeHandledScreen();
if (disableOnDone.get()) this.toggle();
if (enableExpThrower.get() && !Modules.get().isActive(EXPThrower.class)) Modules.get().get(EXPThrower.class).toggle();
}
private void finished() {
if (mc.player == null) return;
if (!notified) {
MsgUtil.sendModuleMsg("No more items to rename§a..!", this.name);
if (pingOnDone.get()) mc.player.playSound(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, pingVolume.get().floatValue(), 1.0f);
}
notified = true;
mc.player.closeHandledScreen();
if (disableOnDone.get()) this.toggle();
}
@Override
public void onDeactivate() {
timer = 0;
notified = false;
}
@EventHandler
private void onTick(TickEvent.Post event) {
if (mc.player == null) return;
if (mc.currentScreen == null) {
notified = false;
return;
}
if (mc.getNetworkHandler() == null) return;
if (!(mc.currentScreen instanceof AnvilScreen anvilScreen)) return;
if (!(mc.player.currentScreenHandler instanceof AnvilScreenHandler anvil)) return;
if (timer < tickRate.get()) {
timer++;
return;
} else {
timer = 0;
}
ItemStack input1 = anvil.getSlot(AnvilScreenHandler.INPUT_1_ID).getStack();
ItemStack input2 = anvil.getSlot(AnvilScreenHandler.INPUT_2_ID).getStack();
ItemStack output = anvil.getSlot(AnvilScreenHandler.OUTPUT_ID).getStack();
if (!hasValidItems(anvil)) finished();
else if (input1.isEmpty() && input2.isEmpty()) {
// fill input 1
for (int n = ANVIL_OFFSET; n < mc.player.getInventory().main.size() + ANVIL_OFFSET; n++) {
ItemStack stack = anvil.getSlot(n).getStack();
if ((blacklistMode.get() && !itemList.get().contains(stack.getItem()))
|| (!blacklistMode.get() && itemList.get().contains(stack.getItem())))
{
if (stack.getName().getString().equals(itemName.get())) continue;
if (stack.contains(DataComponentTypes.CUSTOM_NAME) && !renameNamed.get()) continue;
if (itemName.get().isBlank() && !stack.contains(DataComponentTypes.CUSTOM_NAME)) continue;
InvUtils.shiftClick().slotId(n);
return;
}
}
// no more valid items
finished();
} else if (!output.isEmpty() && itemList.get().contains(output.getItem())) {
// take output
if (output.getName().getString().equals(itemName.get()) || (itemName.get().isBlank() && input1.contains(DataComponentTypes.CUSTOM_NAME))) {
int cost = ((AnvilScreenHandlerAccessor) anvil).getLevelCost().get();
if (mc.player.experienceLevel >= cost) {
InvUtils.shiftClick().slotId(AnvilScreenHandler.OUTPUT_ID);
} else noXP();
}
} else if (!input2.isEmpty()) {
// input 2 shouldn't be filled but correct it if so
InvUtils.shiftClick().slotId(AnvilScreenHandler.INPUT_2_ID);
((AnvilScreenAccessor) anvilScreen).getNameField().setText(itemName.get());
} else if (output.isEmpty()) {
/*
* See AnvilScreenMixin.java
* The server lets you rename multiple stacks from a single RenameItemC2SPacket,
* as long as the AnvilScreen is prevented from sending additional rename packets when moving stacks.
* Occasionally the output slot fails to update, so we refresh the slot manually here and just try again.
**/
if (((AnvilScreenAccessor) anvilScreen).getNameField().getText().equals(itemName.get())) {
InvUtils.shiftClick().slotId(AnvilScreenHandler.INPUT_1_ID);
} else {
((AnvilScreenAccessor) anvilScreen).getNameField().setText(itemName.get());
}
}
}
}
| 412 | 0.964365 | 1 | 0.964365 | game-dev | MEDIA | 0.950183 | game-dev | 0.967508 | 1 | 0.967508 |
UkoeHB/bevy_cobweb_ui | 12,400 | crates/sickle_ui_scaffold/src/attributes/dynamic_style.rs | use bevy::prelude::*;
use bevy::time::Stopwatch;
use bevy::ui::UiSystem;
use crate::*;
pub struct DynamicStylePlugin;
impl Plugin for DynamicStylePlugin
{
fn build(&self, app: &mut App)
{
app.configure_sets(PostUpdate, DynamicStylePostUpdate.before(UiSystem::Prepare))
.add_systems(
PostUpdate,
(
update_dynamic_style_static_attributes,
update_dynamic_style_on_flux_change,
tick_dynamic_style_stopwatch,
update_dynamic_style_on_stopwatch_change,
// Cleanup in a separate step in case of stopwatches that only exist for 1 tick.
cleanup_dynamic_style_stopwatch,
)
.chain()
.in_set(DynamicStylePostUpdate),
);
}
}
#[derive(SystemSet, Clone, Eq, Debug, Hash, PartialEq)]
pub struct DynamicStylePostUpdate;
fn update_dynamic_style_static_attributes(
mut q_styles: Query<(Entity, &mut DynamicStyle), Changed<DynamicStyle>>,
mut commands: Commands,
)
{
for (entity, mut style) in &mut q_styles {
let mut had_static = false;
for context_attribute in &style.attributes {
let DynamicStyleAttribute::Static(style) = &context_attribute.attribute else {
continue;
};
let target = match context_attribute.target {
Some(context) => context,
None => entity,
};
style.apply(&mut commands.style(target));
had_static = true;
}
if had_static {
let style = style.bypass_change_detection();
style.attributes.retain(|csa| !csa.attribute.is_static());
if style.attributes.len() == 0 {
commands.entity(entity).remove::<DynamicStyle>();
}
}
}
}
fn update_dynamic_style_on_flux_change(
mut q_styles: Query<
(
Entity,
Ref<DynamicStyle>,
&FluxInteraction,
Option<&mut DynamicStyleStopwatch>,
),
Or<(Changed<DynamicStyle>, Changed<FluxInteraction>)>,
>,
mut commands: Commands,
)
{
for (entity, style, interaction, stopwatch) in &mut q_styles {
let mut lock_needed = StopwatchLock::None;
let mut keep_stop_watch = false;
for context_attribute in &style.attributes {
match &context_attribute.attribute {
DynamicStyleAttribute::Responsive(style) => {
let target = match context_attribute.target {
Some(context) => context,
None => entity,
};
style.apply(*interaction, &mut commands.style(target));
}
DynamicStyleAttribute::Animated { controller, .. } => {
let animation_lock = if !controller.is_entered() {
keep_stop_watch = true;
controller.animation.lock_duration(&FluxInteraction::None)
+ controller.animation.lock_duration(interaction)
} else {
controller.animation.lock_duration(interaction)
};
if animation_lock > lock_needed {
lock_needed = animation_lock;
}
}
_ => continue,
}
}
if let Some(mut stopwatch) = stopwatch {
if !keep_stop_watch || style.is_changed() {
stopwatch.0.reset();
}
stopwatch.1 = lock_needed;
} else {
commands
.entity(entity)
.insert(DynamicStyleStopwatch(Stopwatch::new(), lock_needed));
}
}
}
fn tick_dynamic_style_stopwatch(time: Res<Time<Real>>, mut q_stopwatches: Query<&mut DynamicStyleStopwatch>)
{
for mut style_stopwatch in &mut q_stopwatches {
style_stopwatch.0.tick(time.delta());
}
}
fn update_dynamic_style_on_stopwatch_change(
mut p: ParamSet<(
&World,
Query<
(
Entity,
&mut DynamicStyle,
&FluxInteraction,
Option<&DynamicStyleStopwatch>,
),
Or<(
Changed<DynamicStyle>,
Changed<FluxInteraction>,
Changed<DynamicStyleStopwatch>,
)>,
>,
)>,
mut commands: Commands,
)
{
let world_ptr: *const World = std::ptr::from_ref(p.p0());
for (entity, mut style, interaction, stopwatch) in p.p1().iter_mut() {
let style_changed = style.is_changed();
let style = style.bypass_change_detection();
let mut enter_completed = true;
let mut filter_entered = false;
for context_attribute in &mut style.attributes {
let DynamicStyleAttribute::Animated { attribute, controller } = &mut context_attribute.attribute
else {
continue;
};
if let Some(stopwatch) = stopwatch {
controller.update(interaction, stopwatch.0.elapsed_secs());
}
if style_changed || controller.dirty() {
let target = match context_attribute.target {
Some(context) => context,
None => entity,
};
// Initialize the attribute's enter_ref value immediately before the first time we apply the
// attribute.
// - We need to do this here so the initialized value gets saved in the DynamicStyle component for
// reuse.
if controller.just_started_entering() {
let mut init_attribute = attribute.clone();
{
// SAFETY:
// - The current system is exclusive because of the &World parameter.
// - The current iterator is not parallel, so there are no concurrent mutable accesses.
// - This world reference is read-only, so it can't invalidate the current iterator.
// - The attribute being mutated is a local variable that's not in the world.
let world = unsafe { &*world_ptr };
init_attribute.initialize_enter(target, world);
}
*attribute = init_attribute;
}
attribute.apply(controller.current_state(), &mut commands.style(target));
}
if !controller.is_entered() {
enter_completed = false;
} else if controller.animation.delete_on_entered {
filter_entered = true;
}
}
if !style.enter_completed && enter_completed {
style.enter_completed = true;
}
if filter_entered {
style.attributes.retain(|csa| {
let DynamicStyleAttribute::Animated { controller, .. } = &csa.attribute else { return true };
!(controller.animation.delete_on_entered && controller.is_entered())
});
if style.attributes.len() == 0 {
commands.entity(entity).remove::<DynamicStyle>();
}
}
}
}
fn cleanup_dynamic_style_stopwatch(
mut q_stopwatches: Query<(Entity, &DynamicStyleStopwatch)>,
mut commands: Commands,
)
{
for (entity, style_stopwatch) in &mut q_stopwatches {
let remove_stopwatch = match style_stopwatch.1 {
StopwatchLock::None => true,
StopwatchLock::Infinite => false,
StopwatchLock::Duration(length) => style_stopwatch.0.elapsed() > length,
};
if remove_stopwatch {
commands.entity(entity).remove::<DynamicStyleStopwatch>();
}
}
}
#[derive(Component, Clone, Debug, Default)]
#[component(storage = "SparseSet")]
pub struct DynamicStyleStopwatch(pub Stopwatch, pub StopwatchLock);
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
pub struct DynamicStyleEnterState
{
completed: bool,
}
impl DynamicStyleEnterState
{
pub fn completed(&self) -> bool
{
self.completed
}
}
#[derive(Clone, Debug)]
pub struct ContextStyleAttribute
{
target: Option<Entity>,
attribute: DynamicStyleAttribute,
}
impl LogicalEq for ContextStyleAttribute
{
fn logical_eq(&self, other: &Self) -> bool
{
self.target == other.target && self.attribute.logical_eq(&other.attribute)
}
}
impl ContextStyleAttribute
{
pub fn new(context: impl Into<Option<Entity>>, attribute: DynamicStyleAttribute) -> Self
{
Self { target: context.into(), attribute }
}
}
// TODO: Consider moving to sparse set. Static styles are removed in
// the same frame they are added, so only interaction animations stay long term.
// Measure impact
//#[component(storage = "SparseSet")]
#[derive(Component, Clone, Debug, Default)]
pub struct DynamicStyle
{
attributes: Vec<ContextStyleAttribute>,
enter_completed: bool,
}
impl DynamicStyle
{
pub fn new(attributes: Vec<DynamicStyleAttribute>) -> Self
{
Self {
attributes: attributes
.iter()
.map(|attribute| ContextStyleAttribute { target: None, attribute: attribute.clone() })
.collect(),
enter_completed: false,
}
}
pub fn enter_completed(&self) -> bool
{
self.enter_completed
}
pub fn copy_from(attributes: Vec<ContextStyleAttribute>) -> Self
{
Self { attributes, enter_completed: false }
}
pub fn merge(mut self, mut other: DynamicStyle) -> Self
{
self.merge_in_place(&mut other);
self
}
pub fn merge_in_place(&mut self, other: &mut DynamicStyle)
{
self.merge_in_place_from_iter(other.attributes.drain(..));
other.enter_completed = false;
}
pub fn merge_in_place_from_iter(&mut self, other_attrs: impl Iterator<Item = ContextStyleAttribute>)
{
for attribute in other_attrs {
if !self.attributes.iter().any(|csa| csa.logical_eq(&attribute)) {
self.attributes.push(attribute);
} else {
// Safe unwrap: checked in if above
let index = self
.attributes
.iter()
.position(|csa| csa.logical_eq(&attribute))
.unwrap();
self.attributes[index] = attribute;
}
}
self.enter_completed = false;
}
pub fn copy_controllers(&mut self, other: &DynamicStyle)
{
for context_attribute in self.attributes.iter_mut() {
if !context_attribute.attribute.is_animated() {
continue;
}
let Some(old_attribute) = other
.attributes
.iter()
.find(|csa| csa.logical_eq(context_attribute))
else {
continue;
};
let DynamicStyleAttribute::Animated { controller: old_controller, attribute: old_attribute } =
&old_attribute.attribute
else {
continue;
};
let ContextStyleAttribute {
attribute: DynamicStyleAttribute::Animated { ref mut controller, attribute },
..
} = context_attribute
else {
continue;
};
if attribute == old_attribute && controller.animation == old_controller.animation {
controller.copy_state_from(old_controller);
}
}
}
pub fn is_interactive(&self) -> bool
{
self.attributes
.iter()
.any(|csa| csa.attribute.is_responsive())
}
pub fn is_animated(&self) -> bool
{
self.attributes
.iter()
.any(|csa| csa.attribute.is_animated())
}
/// Extracts the inner attribute buffer.
///
/// Allows re-using the buffer via [`Self::copy_from`]. See [`StyleBuilder::convert_to_iter_with_buffers`].
pub fn take_inner(self) -> Vec<ContextStyleAttribute>
{
self.attributes
}
}
| 412 | 0.811684 | 1 | 0.811684 | game-dev | MEDIA | 0.66605 | game-dev | 0.90846 | 1 | 0.90846 |
mathsman5133/coc.py | 9,104 | examples/discord_bot.py | # this example assumes you have discord.py > v2.0
# installed via `python -m pip install -U discord.py`
# for more info on using discord.py, see the docs at:
# https://discordpy.readthedocs.io/en/latest
import asyncio
import logging
import os
import traceback
import discord
from discord.ext import commands
import coc
from coc import utils
INFO_CHANNEL_ID = 761848043242127370 # some discord channel ID
clan_tags = ["#20090C9PR", "#202GG92Q", "#20C8G0RPL"]
bot = commands.Bot(command_prefix="?", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Logged in!!")
@coc.ClanEvents.member_join(tags=clan_tags)
async def on_clan_member_join(member, clan):
await bot.get_channel(INFO_CHANNEL_ID).send(
"{0.name} ({0.tag}) just " "joined our clan {1.name} ({1.tag})!".format(
member, clan)
)
@coc.ClanEvents.member_name(tags=clan_tags)
async def member_name_change(old_player, new_player):
await bot.get_channel(INFO_CHANNEL_ID).send(
"Name Change! {0.name} is now called {1.name} (his tag is {1.tag})".format(
old_player, new_player)
)
@coc.ClientEvents.event_error()
async def on_event_error(exception):
if isinstance(exception, coc.PrivateWarLog):
return # lets ignore private war log errors
print(
"Uh oh! Something went wrong in coc.py events... printing traceback for you.")
traceback.print_exc()
@bot.command()
async def player_heroes(ctx, player_tag):
if not utils.is_valid_tag(player_tag):
await ctx.send("You didn't give me a proper tag!")
return
try:
player = await ctx.bot.coc_client.get_player(player_tag)
except coc.NotFound:
await ctx.send("This player doesn't exist!")
return
to_send = ""
for hero in player.heroes:
to_send += "{}: Lv{}/{}\n".format(str(hero),
hero.level, hero.max_level)
await ctx.send(to_send)
@bot.command()
async def parse_army(ctx, army_link: str):
troops, spells = ctx.bot.coc_client.parse_army_link(army_link)
print(troops, spells)
parsed_link_output = ''
if troops or spells: # checking if troops or spells is present in link
for troop, quantity in troops:
parsed_link_output += "The user wants {} {}s. They each have {} DPS.\n".format(
quantity, troop.name, troop.dps)
for spell, quantity in spells:
parsed_link_output += "The user wants {} {}s.\n".format(
quantity, spell.name)
else:
parsed_link_output += "Invalid Link!"
await ctx.send(parsed_link_output)
@bot.command()
async def create_army(ctx):
link = ctx.bot.coc_client.create_army_link(
barbarian=10,
archer=20,
hog_rider=30,
healing_spell=3,
poison_spell=2,
rage_spell=2
)
await ctx.send(link)
@bot.command()
async def member_stat(ctx, player_tag):
if not utils.is_valid_tag(player_tag):
await ctx.send("You didn't give me a proper tag!")
return
try:
player = await ctx.bot.coc_client.get_player(player_tag)
except coc.NotFound:
await ctx.send("This clan doesn't exist!")
return
frame = ''
if player.town_hall > 11:
frame += f"`{'TH Weapon LvL:':<15}` `{player.town_hall_weapon:<15}`\n"
role = player.role if player.role else 'None'
clan = player.clan.name if player.clan else 'None'
frame += (
f"`{'Role:':<15}` `{role:<15}`\n"
f"`{'Player Tag:':<15}` `{player.tag:<15}`\n"
f"`{'Current Clan:':<15}` `{clan:<15.15}`\n"
f"`{'League:':<15}` `{player.league.name:<15.15}`\n"
f"`{'Trophies:':<15}` `{player.trophies:<15}`\n"
f"`{'Best Trophies:':<15}` `{player.best_trophies:<15}`\n"
f"`{'War Stars:':<15}` `{player.war_stars:<15}`\n"
f"`{'Attack Wins:':<15}` `{player.attack_wins:<15}`\n"
f"`{'Defense Wins:':<15}` `{player.defense_wins:<15}`\n"
f"`{'Capital Contrib':<15}` `{player.clan_capital_contributions:<15}`\n"
)
e = discord.Embed(colour=discord.Colour.green(),
description=frame)
e.set_thumbnail(url=player.clan.badge.url)
await ctx.send(embed=e)
@bot.command()
async def clan_info(ctx, clan_tag):
if not utils.is_valid_tag(clan_tag):
await ctx.send("You didn't give me a proper tag!")
return
try:
clan: coc.Clan = await ctx.bot.coc_client.get_clan(clan_tag)
except coc.NotFound:
await ctx.send("This clan doesn't exist!")
return
if clan.public_war_log is False:
log = "Private"
else:
log = "Public"
e = discord.Embed(colour=discord.Colour.green())
e.set_thumbnail(url=clan.badge.url)
e.add_field(name="Clan Name",
value=f"{clan.name}({clan.tag})\n[Open in game]({clan.share_link})",
inline=False)
e.add_field(name="Clan Level", value=clan.level, inline=False)
e.add_field(name="Description", value=clan.description, inline=False)
e.add_field(name="Leader", value=clan.get_member_by(
role=coc.Role.leader), inline=False)
e.add_field(name="Clan Type", value=clan.type, inline=False)
e.add_field(name="Location", value=clan.location, inline=False)
e.add_field(name="Total Clan Trophies", value=clan.points, inline=False)
e.add_field(name="Total Clan Builder Base Trophies",
value=clan.builder_base_points, inline=False)
e.add_field(name="WarLog Type", value=log, inline=False)
e.add_field(name="Required Trophies",
value=clan.required_trophies, inline=False)
e.add_field(name="War Win Streak", value=clan.war_win_streak, inline=False)
e.add_field(name="War Frequency", value=clan.war_frequency, inline=False)
e.add_field(name="Clan War League Rank",
value=clan.war_league, inline=False)
e.add_field(name="Clan Labels", value="\n".join(
label.name for label in clan.labels), inline=False)
e.add_field(name="Member Count",
value=f"{clan.member_count}/50", inline=False)
e.add_field(
name="Clan Record",
value=f"Won - {clan.war_wins}\nLost - {clan.war_losses}\n Draw - {clan.war_ties}",
inline=False
)
frame = ""
for district in clan.capital_districts:
frame += (f"`{f'{district.name}:':<20}` `{district.hall_level:<15}`\n")
e2 = discord.Embed(colour=discord.Colour.green(), description=frame,
title="Capital Distracts")
await ctx.send(embeds=[e, e2])
@bot.command()
async def clan_member(ctx, clan_tag):
if not utils.is_valid_tag(clan_tag):
await ctx.send("You didn't give me a proper tag!")
return
try:
clan = await ctx.bot.coc_client.get_clan(clan_tag)
except coc.NotFound:
await ctx.send("This clan does not exist!")
return
member = ""
for i, a in enumerate(clan.members, start=1):
member += f"`{i}.` {a.name} (th{a.town_hall})\n"
embed = discord.Embed(colour=discord.Colour.red(),
title=f"Members of {clan.name}", description=member)
embed.set_thumbnail(url=clan.badge.url)
embed.set_footer(text=f"Total Members - {clan.member_count}/50")
await ctx.send(embed=embed)
@bot.command()
async def current_war_status(ctx, clan_tag):
if not utils.is_valid_tag(clan_tag):
await ctx.send("You didn't give me a proper tag!")
return
e = discord.Embed(colour=discord.Colour.blue())
try:
war = await ctx.bot.coc_client.get_current_war(clan_tag)
except coc.PrivateWarLog:
return await ctx.send("Clan has a private war log!")
if war is None:
return await ctx.send("Clan is in a strange CWL state!")
e.add_field(name="War State:", value=war.state, inline=False)
if war.end_time: # if state is notInWar we will get errors
hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
minutes, seconds = divmod(remainder, 60)
e.add_field(name=war.clan.name, value=war.clan.tag)
e.add_field(
name="Opponent:",
value=f"{war.opponent.name}\n" f"{war.opponent.tag}", inline=False)
e.add_field(name="War End Time:",
value=f"{hours} hours {minutes} minutes {seconds} seconds",
inline=False)
await ctx.send(embed=e)
async def main():
logging.basicConfig(level=logging.ERROR)
async with coc.Client() as coc_client:
# Attempt to log into CoC API using your credentials.
try:
await coc_client.login(os.environ.get("DEV_SITE_EMAIL"),
os.environ.get("DEV_SITE_PASSWORD"))
except coc.InvalidCredentials as error:
exit(error)
# Add the client session to the bot
bot.coc_client = coc_client
await bot.start(os.environ.get("DISCORD_BOT_TOKEN"))
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
| 412 | 0.611072 | 1 | 0.611072 | game-dev | MEDIA | 0.487037 | game-dev | 0.860828 | 1 | 0.860828 |
falconpl/falcon | 1,038 | modules/native/fmodskel/src/fmodskel_srv.h | /*
@{fmodskel_MAIN_PRJ}@
FILE: @{fmodskel_PROJECT_NAME}@_srv.h
@{fmodskel_DESCRIPTION}@
Interface extension functions
-------------------------------------------------------------------
Author: @{fmodskel_AUTHOR}@
Begin: @{fmodskel_DATE}@
-------------------------------------------------------------------
(C) Copyright @{fmodskel_YEAR}@: @{fmodskel_COPYRIGHT}@
@{fmodskel_LICENSE}@
*/
/** \file
Service publishing - reuse Falcon module logic (mod) in
your applications!
*/
#ifndef @{fmodskel_PROJECT_NAME}@_SRV_H
#define @{fmodskel_PROJECT_NAME}@_SRV_H
#include <falcon/service.h>
namespace Falcon { namespace Srv {
// provide a class that will serve as a service provider.
class Skeleton: public Service
{
public:
// declare the name of the service as it will be published.
Skeleton():
Service( "Skeleton" )
{}
// Provide here methods that needs to be exported.
int skeleton();
};
}} // namespace Falcon::Service
#endif
/* end of @{fmodskel_PROJECT_NAME}@_srv.h */
| 412 | 0.742914 | 1 | 0.742914 | game-dev | MEDIA | 0.627412 | game-dev | 0.673683 | 1 | 0.673683 |
mattgodbolt/reddog | 14,675 | dreamcast/reddog/game/strats/aquabot.dst | //require a network or spline to operate
//if they are on a spline labelled 'entryspline'
//they shall follow this to its end
//If they have a parent, then after the entryspline
//they'll inherit the parent's network data, and use that
PARAMINT WaitAfterSpawn 0 //Amount of time before Aquabot starts to move
PARAMFLOAT NearRange 30.0
LOCALINT fireCount
LOCALINT isGenerated
//GAP BETWEEN EACH SALVO
DEFINE DELAYTWEENFIRE 15
//GAP BETWEEN EACH SET OF SALVOS
DEFINE FIRERATE 120
//USED TO SAY WHETHER TO GO AFTER TARGET OR PLAYER
LOCALINT TARGETVALID
DEFINE LEFTGUN 3
DEFINE RIGHTGUN 6
DEFINE CHEST 9
STATE Init
IF (!(MyFlag2 & OWNIPARAMS))
WaitAfterSpawn = 0
ENDIF
IF (!(MyFlag & OWNFPARAMS))
NearRange = 30.0
ENDIF
IF (NearRange < 10.0)
NearRange = 10.0
ENDIF
MakeMeTheLast()
MyFlag = MyFlag | STRATCOLL | RELVELCALC | ENEMY | HOVERMOVE | TARGETABLE | LOWCOLL
MyFlag2 = MyFlag2 | COLLMOVE
// SetFriction(1.0,0.1,0.05)
SetFriction(0.05,0.05,0.05)
damage = 1.0
health = 50.0
fireCount = 0
InitPath()
//make sure we have a path
IF (!MyPath)
STAT>Kill
ENDIF
//30 DEGS VIS
SEEANG = (TWOPI/360.0) * 16.0
RotationRestriction(1.0, 1.0, 1.0)
AllocStratSoundBlock(1)
TRIGSET>Kill WHENDEAD
IF (GetGlobalParamFloat(0) = 1.0)
isGenerated = 1
ELSE
isGenerated = 0
ENDIF
MyFlag = MyFlag | NODISP
IF (MyParent)
WHILE (MyParentInvalid())
MyFlag = MyFlag
ENDWHILE
ENDIF
OBJECT>ENEMIES\AQUABOT
RegisterCollision()
MyFlag = MyFlag & LNOT(NODISP)
TRIGSET>SpecularMadness EVERY 1
IF (isGenerated)
InheritMyParent()
InitPath()
ENDIF
SetObjectShadowState(1)
//IF JUST ON A SPLINE GO INTO SPLINE MODE
//ELSE NETWORK
IF (!(OnEntrySpline))
MyFlag = MyFlag | GRAVITYON | FLOORCOLL
TRIGSET>DirectMe EVERY 1
TRIGSET>FireCheck EVERY 1
ENDIF
//AM I JUST ON A SIMPLE WAY PATH ?
IF (WaitAfterSpawn > 0)
LOOP (WaitAfterSpawn)
MyFlag = MyFlag
ENDLOOP
ENDIF
IF ((MyPath) AND (!(OnNet)))
//HAVE I GOT AN ENTRY SPLINE ?
IF (!(OnEntrySpline))
//NO, THEN NORMAL WAYPATH BEHAVIOUR
STAT>Defend
ELSE
//ELSE, LET'S SET UP SOME SPLINE ACTION
InitSplineData()
//RUN THE 'COMING FROM WATER' CODE
MODELANIM>ENEMIES\AQUABOT.RDO>Emerge>0
STAT>FollowSpline
ENDIF
ELSE
inrange = 0
TRIGSET>StopGoCheck EVERY 1
IF (MyPath) AND (MyPatrol)
STAT>StartTankNetwork
ELSE
IF (MyPath)
STAT>Network
ELSE
STAT>Wait
ENDIF
ENDIF
ENDIF
ENDSTATE
DEFINE PATHSPEED 0.8
//EMERGE
STATE FollowSpline
MODELANIM>ENEMIES\AQUABOT.RDO>Emerge>0
MyFlag = MyFlag & LNOT(GRAVITYON + FLOORCOLL)
WHILE (MyAnimFlag & RUNNING)
MyFlag = MyFlag
ENDWHILE
MODELANIM>ENEMIES\AQUABOT.RDO>Idle>REPEAT
STAT>FollowSplineMain
ENDSTATE
STATE FollowSplineMain
FaceAlongPath(2)
TiltAlongPath(TWOPI/16.0)
MoveAlongPath(PATHSPEED / 1.5)
IF (LastWay())
MyFlag = MyFlag | FLOORCOLL | GRAVITYON
STAT>Drop
ENDIF
ENDSTATE
STATE Drop
//see if we have been given a parent in MAX
IF (MyParent)
//INHERIT PATH DETAILS
InheritMyParent()
IF (MyPath)
SaveX = x
SaveY = y
SaveZ = z
SetGlobalParamInt(0,100)
InitPath()
ClearGlobalParams()
z = SaveZ
y = SaveY
z = SaveZ
// TRIGSET>Booster EVERY 1
// WHILE (!(IAmOnFloor))
// TowardWay (0.01,0.01)
// IF (absspeedz < -0.08)
// BREAK = 1
// ENDIF
// Flatten(3.0)
// ENDWHILE
TRIGSET>FireCheck EVERY 1
TRIGSET>DirectMe EVERY 1
//DELETE THE DUMMY PARENT
DeleteMyParent()
//PROCESS ACCORDING TO THE PARENT'S PATH TYPE
//AM I JUST ON A SIMPLE WAY PATH ?
IF ((MyPath) AND (!(OnNet)))
STAT>Defend
ELSE
inrange = 0
TRIGSET>StopGoCheck EVERY 1
IF (MyPath) AND (MyPatrol)
STAT>StartTankNetwork
ELSE
IF (MyPath)
STAT>Network
ELSE
STAT>Wait
ENDIF
ENDIF
ENDIF
ENDIF
ENDIF
ENDSTATE
LOCALFLOAT ang
LOCALFLOAT TOANG
LOCALINT BOOSTUP
LOCALINT BREAK
LOCALFLOAT TOPSPEED
LOCALFLOAT velocity
LOCALFLOAT height
LOCALFLOAT dist
LOCALINT firing
//STATE Booster
// TOPSPEED = 0.1
// IF (((BOOSTUP) OR (BREAK)) AND (FABS(absspeedz < TOPSPEED)))
// IF (BREAK)
// velocity = 0.045
// BREAK = 0
// ELSE
// velocity = 0.03
// ENDIF
// MoveZ(velocity)
// ELSE
// velocity = velocity * 0.75
// ENDIF
// TRIGFIN
//ENDSTATE
LOCALFLOAT hang
TRIGGER DirectMe
//inrange set when we are not moving
Flatten(4.0)
IF (absspeedz < -0.08)
BREAK = 1
ENDIF
CheckZ = DogZ + 1.5
height = RandRange(0.03,0.1) * 1.5 * Ssin(hang)
// IF (!inrange)
IF (z < CheckZ)
dist = FABS(z - CheckZ)
IF (dist > (height))
hang = hang + 0.1
BOOSTUP = 1
ENDIF
ELSE
IF (z > CheckZ)
dist = FABS(z - CheckZ)
IF (dist > (height + 3.0))
hang = hang + 0.1
BOOSTUP = 0
//CUT THE VELOCITY
velocity = 0
ENDIF
ENDIF
ENDIF
ELSE
IF (z > CheckZ)
dist = FABS(z - CheckZ)
IF (dist > (height + 3.0))
hang = hang + 0.1
BOOSTUP = 0
//CUT THE VELOCITY
velocity = 0
ENDIF
ENDIF
//ENDIF
TOPSPEED = 0.1
IF (((BOOSTUP) OR (BREAK)) AND (FABS(absspeedz < TOPSPEED)))
IF (BREAK)
velocity = 0.045
BREAK = 0
ELSE
velocity = 0.03
ENDIF
MoveZ(velocity)
ELSE
velocity = velocity * 0.75
ENDIF
IF ((!inrange) AND (!Firing))
SaveX = CheckX
SaveY = CheckY
SaveZ = CheckZ
SetCheckPosMyRotate(0)
IF (CheckX < 0 )
TOANG = -TWOPI/720.0
ELSE
TOANG = TWOPI/720.0
ENDIF
ang = ang + ((TOANG - ang) * 0.03)
RelRotateY(ang)
CheckX = SaveX
CheckY = SaveY
CheckZ = SaveZ
ENDIF
TRIGFIN
ENDTRIGGER
LOCALFLOAT hitdist
STATE Wait
ENDSTATE
LOCALINT FIREAMOUNT
LOCALINT TARGETSEEN
LOCALINT Firing
DEFINE NTSCFIREDELAY 18
LOCALINT FIREDELAY
LOCALFLOAT SEEANG
STATE FireCheck
FIREDELAY = NTSCFIREDELAY
SetPlayerToTarget(TARGETVALID)
TARGETSEEN = NearPlayerXY(NearRange * 3.0)
SetPlayerBack()
IF (TARGETSEEN)
SetPlayerToTarget(TARGETVALID)
IF (PlayerDistXY() > 50.0)
FIREAMOUNT = 300
ELSE
FIREAMOUNT = FIRERATE
ENDIF
ObjectTowardPlayerXZ(CHEST , 0.05, 0.05, TWOPI/8.0, TWOPI/32.0)
SetPlayerBack()
CrntRotToIdleRotX(CHEST, 0.005)
CrntRotToIdleRotZ(CHEST, 0.02)
fireCount = fireCount + 1
//IF I'M NOT BEING HIT AND I'M READY TO FIRE, THEN FIRE
IF ((!HITSET) AND (fireCount > FIREAMOUNT))
Firing = 1
MyFlag2 = MyFlag2 | STOPPED
SetPlayerToTarget(TARGETVALID)
TARGETSEEN = SeePlayerZ(TWOPI/8.0)
SetPlayerBack()
WHILE (!TARGETSEEN)
SetPlayerToTarget(TARGETVALID)
ObjectTowardPlayerXZ(CHEST , 0.05, 0.05, TWOPI/8.0, TWOPI/32.0)
CrntRotToIdleRotX(CHEST, 0.005)
CrntRotToIdleRotZ(CHEST, 0.02)
RelTurnTowardPlayerXY(0.05)
TARGETSEEN = SeePlayerZ(SEEANG)
SetPlayerBack()
ENDWHILE
MODELANIM>ENEMIES\AQUABOT.RDO>LEFTFIRE>0
WHILE (MyAnimFlag & TWEEN)
MyFlag = MyFlag
ENDWHILE
frame = 0
WHILE (frame < FIREDELAY)
frame = frame + 1
ENDWHILE
fireCount = 0
PLAYSOUND>BTANK_GUN4C 0 1.0 0.0 0.0 0.0 0
//CREATE A BLUE EXPLOSION AND THEN THE TRAIL
MyVar = 4.0
CREATE SPAWN_BLASTEXP 0, 4.0, 0, 0, 0, 0, LEFTGUN
SetGlobalParamInt(1,1)
//BULLET FROM HAND WAREZ
CREATE SPAWN_STARFIRE 0.0, 12.0, 0, 0, 0, 0, LEFTGUN
ClearGlobalParams()
LOOP (DELAYTWEENFIRE)
MyFlag = MyFlag
ENDLOOP
MODELANIM>ENEMIES\AQUABOT.RDO>RIGHTFIRE>0
WHILE (MyAnimFlag & TWEEN)
MyFlag = MyFlag
ENDWHILE
frame = 0
WHILE (frame < FIREDELAY)
frame = frame + 1
ENDWHILE
MyVar = 4.0
CREATE SPAWN_BLASTEXP 0, 4.0, 0, 0, 0, 0, RIGHTGUN
SetGlobalParamInt(1,1)
CREATE SPAWN_STARFIRE 0.0, 12.0, 0, 0, 0, 0, RIGHTGUN
ClearGlobalParams()
MyFlag2 = MyFlag2 & LNOT(STOPPED)
MyFlag = MyFlag | GRAVITYON + FLOORCOLL
Firing = 0
MODELANIM>ENEMIES\AQUABOT.RDO>Idle>REPEAT
ENDIF
ELSE
MyFlag2 = MyFlag2 & LNOT(STOPPED)
ENDIF
TRIGFIN
ENDSTATE
STATE Defend
SetPlayerToTarget(TARGETVALID)
lastdist = PlayerDistXY()
endreached = 0
IF (!NearPlayerXY(NearRange / 2.0))
SetPlayerBack()
STAT>Attack
ELSE
SetPlayerBack()
STAT>GetOut
ENDIF
ENDSTATE
STATE GetOut
SetPlayerToTarget(TARGETVALID)
WHILE ((!endreached))
SetPlayerToTarget(TARGETVALID)
endreached = GetFurthestWay(0)
IF (!NearPlayerXY(NearRange + 5.0))
endreached = 1
ENDIF
IF (!NearCheckPosXY(0.0))
IF (AwaySeeWayZ(0.5))
MoveY (-0.02)
ENDIF
AwayWayZ(0.10)
ENDIF
SetPlayerBack()
ENDWHILE
SetPlayerBack()
STAT>DefendWait
ENDSTATE
LOCALFLOAT distnow
STATE DefendWait
SetPlayerToTarget(TARGETVALID)
lastdist = PlayerDistXY()
distnow = lastdist
inrange = 1
WHILE ((distnow < lastdist + 1.0) AND (distnow > lastdist - 1.0))
SetPlayerToTarget(TARGETVALID)
distnow = PlayerDistXY()
SetPlayerBack()
ENDWHILE
inrange = 0
SetPlayerBack()
STAT>Defend
ENDSTATE
STATE Attack
SetPlayerToTarget(TARGETVALID)
IF (NearPlayerXY (NearRange * 0.6) OR endreached)
SetPlayerBack()
STAT>DefendWait
ENDIF
endreached = GetNearestWaySpline(0.0)
IF (!endreached)
IF (SeeWayZ(0.5))
MoveY (0.02)
ENDIF
TowardWay (0.05,0.05)
ENDIF
SetPlayerBack()
ENDSTATE
LOCALFLOAT lastdist
//*** NETWORK CODE ***
LOCALINT inrange
DEFINE LEFT 0
DEFINE RIGHT 1
LOCALINT STRAFEMODE
LOCALFLOAT SaveX
LOCALFLOAT SaveY
LOCALFLOAT SaveZ
LOCALFLOAT LEFTX
LOCALFLOAT LEFTY
LOCALFLOAT LEFTZ
LOCALFLOAT RIGHTX
LOCALFLOAT RIGHTY
LOCALFLOAT RIGHTZ
LOCALFLOAT temp1
LOCALFLOAT temp2
LOCALFLOAT temp3
LOCALFLOAT temp4
LOCALFLOAT temp5
LOCALFLOAT temp6
LOCALFLOAT temp7
LOCALFLOAT temp8
LOCALFLOAT temp9
LOCALINT TIME
STATE StopGoCheck
ObjectTowardPlayerXZ(CHEST , 0.05, 0.05, TWOPI/8.0, TWOPI/32.0)
CrntRotToIdleRotX(CHEST, 0.005)
CrntRotToIdleRotZ(CHEST, 0.02)
SaveX = CheckX
SaveY = CheckY
SaveZ = CheckZ
IF ((inrange) AND (!firing))
IF (STRAFEMODE = LEFT)
CheckX = LEFTX
CheckY = LEFTY
CheckZ = LEFTZ
ELSE
CheckX = RIGHTX
CheckY = RIGHTY
CheckZ = RIGHTZ
ENDIF
//STEPS SET BOOST VAL HIGH
IF (!TIME)
IF (mvelocity < 0.15)
mvelocity = mvelocity + 0.05
ENDIF
ENDIF
MoveTowardXY(CheckX, CheckY, 0.03)
mvelocity = mvelocity * 0.9
IF (!TIME)
IF (NearCheckPosXY(0))
TIME = 1
ENDIF
ELSE
IF (mvelocity < 0.05)
STRAFEMODE = !STRAFEMODE
TIME =0
ENDIF
ENDIF
SetPlayerToTarget(TARGETVALID)
RelTurnTowardPlayerXY(0.05)
IF (!NearPlayerXY(NearRange))
inrange = 0
ENDIF
SetPlayerBack()
ELSE
IF (!firing)
SetPlayerToTarget(TARGETVALID)
TARGETSEEN = NearPlayerXY(NearRange * 0.6)
SetPlayerBack()
IF (TARGETSEEN)
inrange = 1
//save checkp
SaveX = CheckX
SaveY = CheckY
SaveZ = CheckZ
//SAVE MATRIX ROTS
temp1 = StrM00
temp2 = StrM01
temp3 = StrM02
temp4 = StrM10
temp5 = StrM11
temp6 = StrM12
temp7 = StrM20
temp8 = StrM21
temp9 = StrM22
//TEMP FACE THE PLAYER DIRECTLY
SetPlayerToTarget(TARGETVALID)
RelTurnTowardPlayerXY(0.05)
SetPlayerBack()
//setup strafe position left and right
SetCheckPosRel(0,-4.0,0,0)
LEFTX = CheckX
LEFTY = CheckY
LEFTZ = CheckZ
SetCheckPosRel(0,4.0,0,0)
RIGHTX = CheckX
RIGHTY = CheckY
RIGHTZ = CheckZ
//RESTORE MATRIX ROTS
StrM00 = temp1
StrM01 = temp2
StrM02 = temp3
StrM10 = temp4
StrM11 = temp5
StrM12 = temp6
StrM20 = temp7
StrM21 = temp8
StrM22 = temp9
//restore checkp
CheckX = SaveX
CheckY = SaveY
CheckZ = SaveZ
TIME = 0
STRAFEMODE = LEFT
ENDIF
ENDIF
ENDIF
CheckX = SaveX
CheckY = SaveY
CheckZ = SaveZ
TRIGFIN
ENDSTATE
LOCALINT endreached
DEFINE MOVESPEED 0.05
STATE StartTankNetwork
IF (NearCheckPosXY(0.0))
IF (LastWay())
LeaveFixedPath()
endreached = 0
STAT> Network
ELSE
GetNextWay()
ENDIF
ENDIF
IF (SeeWayZ(0.5))
MoveY (MOVESPEED)
ELSE
MoveY (MOVESPEED/2.0)
ENDIF
TowardWay (0.05,0.05)
ENDSTATE
STATE Network
endreached = GetNearestWay(0.0)
STAT>NetworkMain
ENDSTATE
LOCALFLOAT mvelocity
STATE NetworkMain
SetPlayerToTarget(TARGETVALID)
IF (!inrange)
IF (NearCheckPosXY(0.0))
endreached = GetNearestWay(0.0)
ELSE
IF (!endreached)
MoveTowardXY(CheckX, CheckY, 0.03)
SetPlayerToTarget(TARGETVALID)
RelTurnTowardPlayerXY(0.05)
IF (mvelocity < 0.2)
mvelocity = mvelocity + 0.05
ENDIF
SetPlayerBack()
ELSE
IF (!NearCheckPosXY(0.0))
MoveTowardXY(CheckX, CheckY, 0.03)
SetPlayerToTarget(TARGETVALID)
RelTurnTowardPlayerXY(0.05)
IF (mvelocity < 0.2)
mvelocity = mvelocity + 0.05
ENDIF
SetPlayerBack()
ENDIF
ENDIF
ENDIF
ENDIF
mvelocity = mvelocity * 0.75
SetPlayerBack()
ENDSTATE
STATE NetworkMain2
SetPlayerToTarget(TARGETVALID)
IF (!inrange)
IF (NearCheckPosXY(0.0))
endreached = GetNearestWay(0.0)
ELSE
IF (!endreached)
IF (SeeWayZ(0.05))
TowardWay (0.02,0.02)
MoveY(MOVESPEED)
ELSE
MoveY(MOVESPEED/1.5)
TowardWay (0.05,0.05)
ENDIF
ELSE
IF (!NearCheckPosXY(0.0))
IF (SeeWayZ(0.05))
TowardWay (0.02,0.02)
MoveY(MOVESPEED)
ELSE
MoveY(MOVESPEED/1.5)
TowardWay (0.05,0.05)
ENDIF
ENDIF
ENDIF
ENDIF
ENDIF
SetPlayerBack()
ENDSTATE
LOCALFLOAT SPECAMOUNT
LOCALINT HITSET
TRIGGER HitAnim
MODELANIM>ENEMIES\AQUABOT.RDO>GetHit>NOTWEEN
WHILE (MyAnimFlag & RUNNING)
MyFlag = MyFlag
ENDWHILE
MODELANIM>ENEMIES\AQUABOT.RDO>Idle>REPEAT
HITSET = 0
TRIGSTOP
ENDTRIGGER
TRIGGER SpecularMadness
UpdateTrigFlag(TRIG_ALWAYS_RUN)
IF ((MyFlag & HITSTRAT) AND (CollWithFlag & BULLETTYPE))
IF ((!Firing) AND (!HITSET))
HITSET = 1
TRIGSET>HitAnim EVERY 1
ENDIF
SPECAMOUNT = 1.0
ENDIF
IF (SPECAMOUNT > 0)
MyFlag2 = MyFlag2 | SPECULAR
SetSpecularColour(0, SPECAMOUNT,SPECAMOUNT,SPECAMOUNT)
SPECAMOUNT = SPECAMOUNT - 0.1
ELSE
SPECAMOUNT = 0
MyFlag2 = MyFlag2 & LNOT(SPECULAR)
ENDIF
TRIGFIN
ENDTRIGGER
STATE Kill
// adrelanin = adrelanin + 0.2
Score = Score + 1000
MakeFrags (0.1, 24)
MyVar = 0.0
CREATE SPAWN_BLASTEXP 0, 0, 0, 0, 0, 0, 0
IF (isGenerated)
ParentVar = ParentVar + 1.0
ENDIF
//TRIGSTOP
DESTROYME SPAWN_EXPLODINGBITS
ENDSTATE
| 412 | 0.883099 | 1 | 0.883099 | game-dev | MEDIA | 0.976131 | game-dev | 0.980668 | 1 | 0.980668 |
magicskysword/Next | 6,140 | Template/ModABPackTemplate/Assets/Spine/Editor/spine-unity/Editor/Components/SkeletonAnimationInspector.cs | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated July 28, 2023. Replaces all prior versions.
*
* Copyright (c) 2013-2023, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
* otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 THE
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using Spine;
using UnityEditor;
using UnityEngine;
namespace Spine.Unity.Editor {
[CustomEditor(typeof(SkeletonAnimation))]
[CanEditMultipleObjects]
public class SkeletonAnimationInspector : SkeletonRendererInspector {
protected SerializedProperty animationName, loop, timeScale, unscaledTime, autoReset;
protected bool wasAnimationParameterChanged = false;
readonly GUIContent LoopLabel = new GUIContent("Loop", "Whether or not .AnimationName should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected.");
readonly GUIContent TimeScaleLabel = new GUIContent("Time Scale", "The rate at which animations progress over time. 1 means normal speed. 0.5 means 50% speed.");
readonly GUIContent UnscaledTimeLabel = new GUIContent("Unscaled Time",
"If enabled, AnimationState uses unscaled game time (Time.unscaledDeltaTime), " +
"running animations independent of e.g. game pause (Time.timeScale). " +
"Instance SkeletonAnimation.timeScale will still be applied.");
protected override void OnEnable () {
base.OnEnable();
animationName = serializedObject.FindProperty("_animationName");
loop = serializedObject.FindProperty("loop");
timeScale = serializedObject.FindProperty("timeScale");
unscaledTime = serializedObject.FindProperty("unscaledTime");
}
protected override void DrawInspectorGUI (bool multi) {
base.DrawInspectorGUI(multi);
if (!TargetIsValid) return;
bool sameData = SpineInspectorUtility.TargetsUseSameData(serializedObject);
foreach (UnityEngine.Object o in targets)
TrySetAnimation(o as SkeletonAnimation);
EditorGUILayout.Space();
if (!sameData) {
EditorGUILayout.DelayedTextField(animationName);
} else {
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(animationName);
wasAnimationParameterChanged |= EditorGUI.EndChangeCheck(); // Value used in the next update.
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(loop, LoopLabel);
wasAnimationParameterChanged |= EditorGUI.EndChangeCheck(); // Value used in the next update.
EditorGUILayout.PropertyField(timeScale, TimeScaleLabel);
foreach (UnityEngine.Object o in targets) {
SkeletonAnimation component = o as SkeletonAnimation;
component.timeScale = Mathf.Max(component.timeScale, 0);
}
EditorGUILayout.PropertyField(unscaledTime, UnscaledTimeLabel);
EditorGUILayout.Space();
SkeletonRootMotionParameter();
serializedObject.ApplyModifiedProperties();
}
protected void TrySetAnimation (SkeletonAnimation skeletonAnimation) {
if (skeletonAnimation == null) return;
if (!skeletonAnimation.valid || skeletonAnimation.AnimationState == null)
return;
TrackEntry current = skeletonAnimation.AnimationState.GetCurrent(0);
if (!isInspectingPrefab) {
string activeAnimation = (current != null) ? current.Animation.Name : "";
bool activeLoop = (current != null) ? current.Loop : false;
bool animationParameterChanged = this.wasAnimationParameterChanged &&
((activeAnimation != animationName.stringValue) || (activeLoop != loop.boolValue));
if (animationParameterChanged) {
this.wasAnimationParameterChanged = false;
Skeleton skeleton = skeletonAnimation.Skeleton;
AnimationState state = skeletonAnimation.AnimationState;
if (!Application.isPlaying) {
if (state != null) state.ClearTrack(0);
skeleton.SetToSetupPose();
}
Spine.Animation animationToUse = skeleton.Data.FindAnimation(animationName.stringValue);
if (!Application.isPlaying) {
if (animationToUse != null) {
skeletonAnimation.AnimationState.SetAnimation(0, animationToUse, loop.boolValue);
}
skeletonAnimation.Update(0);
skeletonAnimation.LateUpdate();
requireRepaint = true;
} else {
if (animationToUse != null)
state.SetAnimation(0, animationToUse, loop.boolValue);
else
state.ClearTrack(0);
}
}
// Reflect animationName serialized property in the inspector even if SetAnimation API was used.
if (Application.isPlaying) {
if (current != null && current.Animation != null) {
if (skeletonAnimation.AnimationName != animationName.stringValue)
animationName.stringValue = current.Animation.Name;
}
}
}
}
}
}
| 412 | 0.890107 | 1 | 0.890107 | game-dev | MEDIA | 0.764385 | game-dev,graphics-rendering | 0.958049 | 1 | 0.958049 |
liangxiegame/QFramework | 1,034 | QFramework.Unity2018+/Assets/QFramework/Toolkits/_CoreKit/DeclareKit/Editor/DeclareKitMenu.cs | /****************************************************************************
* Copyright (c) 2015 - 2024 liangxiegame UNDER MIT License
*
* https://qframework.cn
* https://github.com/liangxiegame/QFramework
* https://gitee.com/liangxiegame/QFramework
****************************************************************************/
#if UNITY_EDITOR
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace QFramework
{
public class DeclareKitMenu
{
[MenuItem("GameObject/QFramework/DeclareKit/@(Alt+D)Add Declare Component &d", false, 0)]
static void AddView()
{
var gameObject = Selection.objects.First() as GameObject;
if (!gameObject)
{
Debug.LogWarning("需要选择 GameObject");
return;
}
var view = gameObject.GetComponent<DeclareComponent>();
if (!view)
{
gameObject.AddComponent<DeclareComponent>();
}
}
}
}
#endif | 412 | 0.674928 | 1 | 0.674928 | game-dev | MEDIA | 0.948302 | game-dev | 0.545724 | 1 | 0.545724 |
FrogTheFrog/moondeck | 3,778 | src/steam-utils/waitForAppStartNotification.ts | import { LifetimeNotification } from "@decky/ui";
import { SteamClientEx } from "./shared";
import { logger } from "../lib/logger";
export enum AppStartResult {
TimeoutOrError,
Started,
Cancelled
}
// eslint-disable-next-line @typescript-eslint/promise-function-async
function waitForLifetimeNotification(appId: number, lifetimeCallback: (running: boolean) => void): () => void {
try {
const { unregister } = (SteamClient as SteamClientEx).GameSessions.RegisterForAppLifetimeNotifications((data: LifetimeNotification) => {
if (data.unAppID !== appId) {
return;
}
lifetimeCallback(data.bRunning);
});
let unregistered = false;
return () => {
if (!unregistered) {
unregistered = true;
unregister();
}
};
} catch (error) {
logger.critical(error);
// eslint-disable-next-line @typescript-eslint/no-empty-function
return () => { };
}
}
// For handling the case where the user cancels the app launch.
function waitForProcessLaunchAction(gameId: string, processLaunched: (launched: boolean) => void): () => void {
try {
let actionId: number | null = null;
let callbackInvoked = false;
const { unregister: unregisterStart } = (SteamClient as SteamClientEx).Apps.RegisterForGameActionStart((gameActionId, gameIdFromAction, action, _1) => {
if (action === "LaunchApp" && gameIdFromAction === gameId && actionId === null) {
actionId = gameActionId;
}
});
const { unregister: unregisterTaskChange } = (SteamClient as SteamClientEx).Apps.RegisterForGameActionTaskChange((gameActionId, _1, _2, task, _3) => {
if (gameActionId === actionId && task === "CreatingProcess" && !callbackInvoked) {
callbackInvoked = true;
processLaunched(true);
}
});
const { unregister: unregisterEnd } = (SteamClient as SteamClientEx).Apps.RegisterForGameActionEnd((gameActionId) => {
if (gameActionId === actionId && !callbackInvoked) {
callbackInvoked = true;
processLaunched(false);
}
});
let unregistered = false;
return () => {
if (!unregistered) {
unregistered = true;
unregisterStart();
unregisterTaskChange();
unregisterEnd();
}
};
} catch (error) {
logger.critical(error);
// eslint-disable-next-line @typescript-eslint/no-empty-function
return () => { };
}
}
/**
* Convenience function for waiting until app starts.
*/
export async function waitForAppStartNotification(appId: number, gameId: string, timeout: number): Promise<AppStartResult> {
// MUST leave this function async/await (for usage purposes)!
return await new Promise<AppStartResult>((_resolve) => {
let alreadyResolved = false;
let timeoutId: NodeJS.Timeout | undefined;
let unregisterAction: (() => void) | undefined;
let unregisterNotification: (() => void) | undefined;
const resolve = (value: AppStartResult): void => {
if (!alreadyResolved) {
alreadyResolved = true;
clearTimeout(timeoutId);
unregisterAction?.();
unregisterNotification?.();
_resolve(value);
}
};
try {
unregisterAction = waitForProcessLaunchAction(gameId, (launched) => {
if (launched) {
unregisterAction?.();
} else {
resolve(AppStartResult.Cancelled);
}
});
unregisterNotification = waitForLifetimeNotification(appId, (running) => {
resolve(running ? AppStartResult.Started : AppStartResult.TimeoutOrError);
});
timeoutId = setTimeout(() => { resolve(AppStartResult.TimeoutOrError); }, timeout);
} catch (error) {
logger.critical(error);
resolve(AppStartResult.TimeoutOrError);
}
});
}
| 412 | 0.836544 | 1 | 0.836544 | game-dev | MEDIA | 0.45728 | game-dev | 0.948676 | 1 | 0.948676 |
Fabrizio-Caruso/CROSS-LIB | 5,583 | src/games/chase/split_files/item.c | #include "settings.h"
#include "character.h"
#include "item.h"
#include "ghost.h"
#include "game_text.h"
extern uint16_t points;
extern uint8_t guns;
extern uint8_t lives;
extern uint8_t level;
extern uint8_t freezeActive;
extern uint8_t freeze_count_down;
#if defined(FULL_GAME)
extern uint8_t invincibilityActive;
extern uint8_t confuseActive;
extern uint8_t zombieActive;
extern uint8_t invincibility_count_down;
extern uint8_t confuse_count_down;
extern uint8_t zombie_count_down;
extern uint8_t bases_in_completed_levels;
extern uint8_t all_skulls_killed_in_completed_levels;
extern uint8_t extraLife_present_on_level;
extern uint8_t zombie_present_on_level;
#endif
extern Image DEAD_GHOST_IMAGE;
extern Character ghosts[GHOSTS_NUMBER];
extern Character bombs[BOMBS_NUMBER];
extern Character skull;
extern Character player;
extern Item powerUp;
extern Item gun;
extern Item extraPoints;
#if defined(FULL_GAME)
extern Character *chasedEnemyPtr;
extern Character chasingBullet;
extern Item powerUp2;
extern Item freeze;
extern Item invincibility;
extern Item chase;
extern Item super;
extern Item extraLife;
extern Item confuse;
extern Item zombie;
#endif
#if !defined(TINY_GAME)
void itemReached(Character * itemPtr)
{
_XL_ZAP_SOUND();
#if defined(_XL_TURN_BASED)
displayPlayer(&player);
#endif
itemPtr->_status = 0;
displayScore();
}
void relocateItem(Character * itemPtr)
{
itemPtr->_status = 1;
#if defined(FULL_GAME)
do
{
relocateCharacter(itemPtr);
} while(innerWallReached(itemPtr));
#else
relocateCharacter(itemPtr);
#endif
}
#if defined(FULL_GAME)
void _commonPowerUpEffect(void)
{
points+=POWER_UP_BONUS;
decreaseGhostLevel();
freezeActive = 1;
freeze_count_down += FROZEN_COUNT_DOWN;
}
void powerUpEffect(void)
{
_commonPowerUpEffect();
powerUp._coolDown = POWER_UP_COOL_DOWN;
}
void _gunEffect(void)
{
guns = GUNS_NUMBER;
#if !defined(NO_STATS)
printGunsStats();
#endif
points+=GUN_BONUS;
}
void gunEffect(void)
{
_gunEffect();
gun._coolDown = GUN_COOL_DOWN;
}
#else
void powerUpEffect(void)
{
points+=POWER_UP_BONUS;
freezeActive = 1;
freeze_count_down += FROZEN_COUNT_DOWN;
powerUp._coolDown = POWER_UP_COOL_DOWN;
}
void gunEffect(void)
{
guns = GUNS_NUMBER;
#if !defined(NO_STATS)
printGunsStats();
#endif
points+=GUN_BONUS;
gun._coolDown = GUN_COOL_DOWN;
}
#endif
void extraPointsEffect(void)
{
points+=EXTRA_POINTS+level*EXTRA_POINTS_LEVEL_INCREASE;
extraPoints._coolDown = SECOND_EXTRA_POINTS_COOL_DOWN;//(EXTRA_POINTS_COOL_DOWN<<4); // second time is harder
}
void handle_item(register Item *itemPtr)
{
// Manage item
if(itemPtr->_character._status == 1)
{
if(areCharctersAtSamePosition(&player, (Character *) itemPtr))
{
itemPtr->_effect();
itemReached((Character *) itemPtr);
}
else
{
_blink_draw(itemPtr->_character._x, itemPtr->_character._y, itemPtr->_character._imagePtr, &(itemPtr->_blink));
}
}
else if (itemPtr->_coolDown == 0)
{
relocateItem((Character *) itemPtr);
}
else
{
--(itemPtr->_coolDown);
}
}
void handle_count_down(uint8_t * activeItemFlagPtr, uint8_t * countDownPtr)
{
if(*activeItemFlagPtr)
{
if(*countDownPtr<=0)
{
*activeItemFlagPtr=0;
}
else
{
--(*countDownPtr);
}
}
}
#endif // !defined(TINY_GAME)
#if defined(FULL_GAME)
void reducePowerUpsCoolDowns(void)
{
extraPoints._coolDown/=2;
invincibility._coolDown/=2;
freeze._coolDown/=2;
_XL_TICK_SOUND();
}
#elif !defined(TINY_GAME)
void reducePowerUpsCoolDowns(void)
{
extraPoints._coolDown/=2;
_XL_TICK_SOUND();
}
#else
#endif
#if defined(FULL_GAME)
void powerUp2Effect(void)
{
_commonPowerUpEffect();
powerUp2._coolDown = POWER_UP2_COOL_DOWN;
}
void _freezeEffect(void)
{
_commonPowerUpEffect();
_commonPowerUpEffect();
_commonPowerUpEffect();
}
void freezeEffect(void)
{
_freezeEffect();
freeze._coolDown = ((uint16_t) (FREEZE_COOL_DOWN)*2);
}
void extraLifeEffect(void)
{
++lives;
all_skulls_killed_in_completed_levels=1;
extraLife_present_on_level = 0;
printLivesStats();
}
void _invincibilityEffect(void)
{
invincibilityActive = 1;
invincibility_count_down = INVINCIBILITY_COUNT_DOWN;
}
void invincibilityEffect(void)
{
_invincibilityEffect();
invincibility._coolDown = ((uint16_t) (INVINCIBILITY_COOL_DOWN)*4);
}
void superEffect(void)
{
_freezeEffect();
_gunEffect();
_invincibilityEffect();
super._coolDown = ((uint16_t) (SUPER_COOL_DOWN)*8);
}
void confuseEffect(void)
{
confuseActive = 1;
confuse._coolDown = SECOND_CONFUSE_COOL_DOWN;
confuse_count_down = CONFUSE_COUNT_DOWN;
}
void zombieEffect(void)
{
uint8_t i;
zombieActive = 1;
bases_in_completed_levels = 1;
zombie._coolDown = SECOND_ZOMBIE_COOL_DOWN;
zombie_count_down = ZOMBIE_COUNT_DOWN;
for(i=0;i<GHOSTS_NUMBER;++i)
{
if(!(ghosts[i]._status))
{
ghosts[i]._imagePtr = &DEAD_GHOST_IMAGE;
}
}
}
void chaseEffect(void)
{
unsigned firstAliveIndex;
chasingBullet._status = 1;
chasingBullet._x = chase._character._x;
chasingBullet._y = chase._character._y;
chase._coolDown = ((uint16_t)(CHASE_COOL_DOWN)*2);
firstAliveIndex = firstAlive();
if(firstAliveIndex == GHOSTS_NUMBER)
{
chasedEnemyPtr = &skull;
}
else
{
chasedEnemyPtr = &ghosts[firstAliveIndex];
}
}
#endif
| 412 | 0.945011 | 1 | 0.945011 | game-dev | MEDIA | 0.987946 | game-dev | 0.828868 | 1 | 0.828868 |
PavelZinchenko/event_horizon | 7,835 | Starship/Assets/Scripts/Domain/Galaxy/StarData.cs | using System.Collections.Generic;
using System.Linq;
using Economy;
using Galaxy.StarContent;
using Game;
using GameDatabase.DataModel;
using GameModel;
using GameServices;
using GameServices.Quests;
using GameServices.Random;
using Model.Generators;
using Session;
using Session.Content;
using UnityEngine;
using Utils;
using Zenject;
using Random = System.Random;
namespace Galaxy
{
public sealed class StarData : GameServiceBase
{
[Inject] private readonly RegionMap _regionMap;
[Inject] private readonly IRandom _random;
[Inject] private readonly HolidayManager _holidayManager;
[Inject] private readonly IQuestManager _questManager;
[Inject] private StarContentChangedSignal.Trigger _starContentChangedTrigger;
[Inject] private readonly Occupants _occupants;
[Inject] private readonly Boss _boss;
[Inject] private readonly Ruins _ruins;
[Inject] private readonly Challenge _challenge;
[Inject] private readonly LocalEvent _localEvent;
[Inject] private readonly Survival _survival;
[Inject] private readonly Wormhole _wormhole;
[Inject] private readonly StarBase _starBase;
[Inject] private readonly XmasTree _xmas;
[Inject] private readonly Hive _hive;
[Inject]
public StarData(ISessionData session, SessionDataLoadedSignal dataLoadedSignal, SessionCreatedSignal sessionCreatedSignal)
: base(dataLoadedSignal, sessionCreatedSignal)
{
_session = session;
}
public bool IsVisited(int starId) { return _session.StarMap.IsVisited(starId); }
public void SetVisited(int starId) { _session.StarMap.SetVisited(starId); }
public Vector2 GetPosition(int starId) { return StarLayout.GetStarPosition(starId, _random.Seed); }
public int GetLevel(int starId) { return StarLayout.GetStarLevel(starId, _random.Seed); }
public string GetName(int starId) { return NameGenerator.GetStarName(starId); }
public string GetBookmark(int starId) { return _session.StarMap.GetBookmark(starId); }
public void SetBookmark(int starId, string value)
{
_session.StarMap.SetBookmark(starId, value);
_starContentChangedTrigger.Fire(starId);
}
public bool HasBookmark(int starId) { return _session.StarMap.HasBookmark(starId); }
public Region GetRegion(int starId) { return _regionMap.GetStarRegion(starId); }
public bool IsQuestObjective(int starId) { return _questManager.IsQuestObjective(starId); }
public StarObjects GetObjects(int starId)
{
var objects = new StarObjects();
if (HasStarBase(starId))
{
objects.Add(StarObjectType.StarBase);
return objects;
}
if (starId < 24 && _customStarObjects.TryGetValue(starId, out objects))
return objects;
var value = _random.RandomInt(starId, 1000);
var faction = GetRegion(starId).Faction;
if (value >= 100 && value < 125)
objects.Add(StarObjectType.Wormhole);
//if (value >= 150 && value < 175 && Faction > 0)
// pointsOfInterest.Add(PointOfInterest.Laboratory);
if (value >= 200 && value < 300 && faction == Faction.Neutral)
objects.Add(StarObjectType.Event);
if (value >= 300 && value < 325 && faction == Faction.Neutral)
objects.Add(StarObjectType.Survival);
if (value >= 350 && value < 375 && faction != Faction.Neutral)
objects.Add(StarObjectType.Arena);
if (value >= 400 && value < 450 && (faction != Faction.Neutral || value < 420))
objects.Add(StarObjectType.Boss);
if (value >= 450 && value < 475 && faction == Faction.Neutral)
objects.Add(StarObjectType.Ruins);
if (CurrencyExtensions.PremiumCurrencyAllowed)
if (value >= 500 && value < 510)
objects.Add(StarObjectType.Military);
if (value >= 550 && value < 570)
objects.Add(StarObjectType.Challenge);
if (value >= 600 && value < 650 && faction != Faction.Neutral)
objects.Add(StarObjectType.Hive);
if (value >= 700 && value < 720 && faction == Faction.Neutral)
objects.Add(StarObjectType.BlackMarket);
if (value >= 800 && value < 810 && _holidayManager.IsChristmas)
objects.Add(StarObjectType.Xmas);
return objects;
}
public bool HasStarBase(int starId)
{
int x, y;
StarLayout.IdToPosition(starId, out x, out y);
if (!RegionMap.IsHomeStar(x, y))
return false;
return GetRegion(starId).Id != Region.UnoccupiedRegionId;
}
public void CaptureBase(int starId)
{
_starBase.Attack(starId);
}
public Occupants.Facade GetOccupant(int starId) { return new Occupants.Facade(_occupants, starId); }
public Boss.Facade GetBoss(int starId) { return new Boss.Facade(_boss, starId); }
public Ruins.Facade GetRuins(int starId) { return new Ruins.Facade(_ruins, starId); }
public XmasTree.Facade GetXmasTree(int starId) { return new XmasTree.Facade(_xmas, starId); }
public Challenge.Facade GetChallenge(int starId) { return new Challenge.Facade(_challenge, starId); }
public LocalEvent.Facade GetLocalEvent(int starId) { return new LocalEvent.Facade(_localEvent, starId); }
public Survival.Facade GetSurvival(int starId) { return new Survival.Facade(_survival, starId); }
public Wormhole.Facade GetWormhole(int starId) { return new Wormhole.Facade(_wormhole, starId); }
public StarContent.Hive.Facade GetPandemic(int starId) { return new Hive.Facade(_hive, starId); }
protected override void OnSessionDataLoaded()
{
_customStarObjects.Clear();
var random = new Random(_session.Game.Seed);
var stars = new Queue<int>(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 14, 16, 17, 18, 21, 22, 23 }.OrderBy(id => random.Next()));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Ruins));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.BlackMarket));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Challenge));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Boss));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Event));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Event));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Event));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Survival));
_customStarObjects.Add(stars.Dequeue(), StarObjects.Create(StarObjectType.Wormhole));
while (stars.Count > 0)
_customStarObjects.Add(stars.Dequeue(), new StarObjects());
//foreach (var item in _customStarObjects)
// _session.StarMap.SetEnemy(item.Key, StarMapData.Occupant.Empty);
_session.StarMap.SetEnemy(0, StarMapData.Occupant.Empty);
SetVisited(0);
}
protected override void OnSessionCreated()
{
}
private readonly Dictionary<int, StarObjects> _customStarObjects = new Dictionary<int, StarObjects>();
private readonly ISessionData _session;
}
public class StarContentChangedSignal : SmartWeakSignal<int> { public class Trigger : TriggerBase {} }
}
| 412 | 0.741437 | 1 | 0.741437 | game-dev | MEDIA | 0.961929 | game-dev | 0.908498 | 1 | 0.908498 |
MergHQ/CRYENGINE | 1,641 | Code/CryEngine/CryCommon/CryRenderer/RenderElements/CREPostProcess.h | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
/*=============================================================================
CREPostProcess.h : Post processing RenderElement common data
Revision history:
* 23/02/2005: Re-factored/Converted to CryEngine 2.0 by Tiago Sousa
* Created by Tiago Sousa
=============================================================================*/
#ifndef __CREPOSTPROCESS_H__
#define __CREPOSTPROCESS_H__
class CREPostProcess : public CRendElementBase
{
friend class CD3D9Renderer;
public:
CREPostProcess();
virtual ~CREPostProcess();
virtual void mfPrepare(bool bCheckOverflow);
virtual bool mfDraw(CShader* ef, SShaderPass* sfm);
// Use for setting numeric values, vec4 (colors, position, vectors, wtv), strings
virtual int mfSetParameter(const char* pszParam, float fValue, bool bForceValue = false) const;
virtual int mfSetParameterVec4(const char* pszParam, const Vec4& pValue, bool bForceValue = false) const;
virtual int mfSetParameterString(const char* pszParam, const char* pszArg) const;
virtual void mfGetParameter(const char* pszParam, float& fValue) const;
virtual void mfGetParameterVec4(const char* pszParam, Vec4& pValue) const;
virtual void mfGetParameterString(const char* pszParam, const char*& pszArg) const;
virtual int32 mfGetPostEffectID(const char* pPostEffectName) const;
//! Reset all post-processing effects.
virtual void Reset(bool bOnSpecChange = false);
virtual void mfReset()
{
Reset();
}
virtual void GetMemoryUsage(ICrySizer* pSizer) const
{
pSizer->AddObject(this, sizeof(*this));
}
};
#endif
| 412 | 0.921136 | 1 | 0.921136 | game-dev | MEDIA | 0.64129 | game-dev | 0.626276 | 1 | 0.626276 |
Haleth/Aurora | 12,308 | Skin/Retail/AddOns/Blizzard_TradeSkillUI.lua | local _, private = ...
if not private.isRetail then return end
--[[ Lua Globals ]]
-- luacheck: globals pcall ipairs select
--[[ Core ]]
local Aurora = private.Aurora
local Base = Aurora.Base
local Hook, Skin = Aurora.Hook, Aurora.Skin
local Color, Util = Aurora.Color, Aurora.Util
do --[[ AddOns\Blizzard_TradeSkillUI.lua ]]
do --[[ Blizzard_TradeSkillRecipeButton ]]
Hook.TradeSkillRecipeButtonMixin = {}
function Hook.TradeSkillRecipeButtonMixin:SetUp(tradeSkillInfo)
if tradeSkillInfo.type == "header" or tradeSkillInfo.type == "subheader" then
self._minus:Show()
self:SetBackdrop(true)
if tradeSkillInfo.numIndents > 0 then
self:SetBackdropOption("offsets", {
left = 24,
right = 263,
top = 0,
bottom = 3,
})
else
self:SetBackdropOption("offsets", {
left = 4,
right = 283,
top = 0,
bottom = 3,
})
end
-- Blizz doesn't call SetHighlightTexture, so we have to fix it here.
self.Highlight:SetTexture("")
else
self._minus:Hide()
self._plus:Hide()
self:SetBackdrop(false)
end
end
end
do --[[ Blizzard_TradeSkillDetails ]]
Hook.TradeSkillDetailsMixin = {}
function Hook.TradeSkillDetailsMixin:RefreshDisplay()
local recipeInfo = self.selectedRecipeID and _G.C_TradeSkillUI.GetRecipeInfo(self.selectedRecipeID)
if recipeInfo then
local numReagents = _G.C_TradeSkillUI.GetRecipeNumReagents(self.selectedRecipeID)
for reagentIndex = 1, numReagents do
local link = _G.C_TradeSkillUI.GetRecipeReagentItemLink(self.selectedRecipeID, reagentIndex)
Hook.SetItemButtonQuality(self.Contents.Reagents[reagentIndex], _G.C_Item.GetItemQualityByID(link), link)
end
local optionalReagentSlots, _, _, _, playerReagentCount = _G.C_TradeSkillUI.GetOptionalReagentInfo(self.selectedRecipeID)
for optionalReagentIndex = 1, #optionalReagentSlots do
local reagentButton = self.Contents.OptionalReagents[optionalReagentIndex]
local reagentName = self:GetOptionalReagent(optionalReagentIndex)
local hasReagent = reagentName ~= nil;
if playerReagentCount == 0 then
hasReagent = false;
end
if reagentButton:IsLocked() then
reagentButton:SetBackdropBorderColor(Color.gray)
else
if reagentButton.SelectedTexture:IsShown() then
reagentButton:SetBackdropBorderColor(Color.yellow)
elseif hasReagent then
reagentButton:SetBackdropBorderColor(_G.COMMON_GRAY_COLOR)
else
reagentButton:SetBackdropBorderColor(Color.green)
end
end
end
end
end
Hook.TradeSkillGuildListingMixin = {}
function Hook.TradeSkillGuildListingMixin:Refresh()
local offset = _G.HybridScrollFrame_GetOffset(self.Container.ScrollFrame)
for i, craftersButton in ipairs(self.Container.ScrollFrame.buttons) do
if craftersButton:IsShown() then
local dataIndex = offset + i
local displayName, fullName, classFileName, online = _G.GetGuildRecipeMember(dataIndex)
craftersButton:SetText(displayName)
if online then
craftersButton:Enable()
craftersButton.fullName = fullName
local classColor = _G.CUSTOM_CLASS_COLORS[classFileName]
if classColor then
craftersButton.Text:SetTextColor(classColor.r, classColor.g, classColor.b)
end
end
end
end
end
end
end
do --[[ AddOns\Blizzard_TradeSkillUI.xml ]]
do --[[ Blizzard_TradeSkillTemplates ]]
function Skin.OptionalReagentButtonTemplate(Button)
Skin.LargeItemButtonTemplate(Button)
end
end
do --[[ Blizzard_TradeSkillRecipeButton ]]
function Skin.TradeSkillRowButtonTemplate(Button)
Util.Mixin(Button, Hook.TradeSkillRecipeButtonMixin)
Skin.ExpandOrCollapse(Button)
Skin.FrameTypeStatusBar(Button.SubSkillRankBar)
Button.SubSkillRankBar.BorderLeft:Hide()
Button.SubSkillRankBar.BorderRight:Hide()
Button.SubSkillRankBar.BorderMid:Hide()
end
end
do --[[ Blizzard_TradeSkillDetails ]]
function Skin.TradeSkillReagentTemplate(Button)
Skin.LargeItemButtonTemplate(Button)
end
function Skin.TradeSkillOptionalReagentTemplate(Button)
Skin.OptionalReagentButtonTemplate(Button)
Base.CropIcon(Button.SelectedTexture)
Button.SelectedTexture:SetAllPoints(Button.Icon)
end
function Skin.TradeSkillDetailsFrameTemplate(ScrollFrame)
Util.Mixin(ScrollFrame, Hook.TradeSkillDetailsMixin)
ScrollFrame.Background:Hide()
Skin.UIPanelStretchableArtScrollBarTemplate(ScrollFrame.ScrollBar)
Skin.MagicButtonTemplate(ScrollFrame.CreateAllButton)
ScrollFrame.CreateAllButton:SetPoint("TOPLEFT", ScrollFrame, "BOTTOMLEFT", 1, -1)
Skin.MagicButtonTemplate(ScrollFrame.ViewGuildCraftersButton)
ScrollFrame.ViewGuildCraftersButton:SetPoint("TOPLEFT", ScrollFrame, "BOTTOMLEFT", 0, -1)
Skin.MagicButtonTemplate(ScrollFrame.ExitButton)
Skin.MagicButtonTemplate(ScrollFrame.CreateButton)
Util.PositionRelative("TOPRIGHT", ScrollFrame, "BOTTOMRIGHT", 27, -1, 5, "Left", {
ScrollFrame.ExitButton,
ScrollFrame.CreateButton,
})
Skin.NumericInputSpinnerTemplate(ScrollFrame.CreateMultipleInputBox)
ScrollFrame.CreateMultipleInputBox:ClearAllPoints()
ScrollFrame.CreateMultipleInputBox:SetPoint("TOPLEFT", ScrollFrame.CreateAllButton, "TOPRIGHT", 25, -1)
local GuildFrame = ScrollFrame.GuildFrame
GuildFrame:SetPoint("BOTTOMLEFT", ScrollFrame, "BOTTOMRIGHT", 33, 19)
Util.Mixin(GuildFrame, Hook.TradeSkillGuildListingMixin)
Skin.TranslucentFrameTemplate(GuildFrame)
Skin.UIPanelCloseButton(GuildFrame.CloseButton)
GuildFrame.Container:SetBackdrop(nil)
Skin.HybridScrollBarTemplate(GuildFrame.Container.ScrollFrame.scrollBar)
local Contents = ScrollFrame.Contents
do -- ResultIcon
local Button = Contents.ResultIcon
Base.SetBackdrop(Button, Color.black, Color.frame.a)
Button:SetBackdropOption("offsets", {
left = -1,
right = -1,
top = -1,
bottom = -1,
})
Button._auroraIconBorder = Button
Button.ResultBorder:Hide()
Button.Count:SetPoint("BOTTOMRIGHT", -2, 2)
Button:SetNormalTexture([[Interface\GuildFrame\GuildEmblemsLG_01]])
Base.CropIcon(Button:GetNormalTexture())
end
for i = 1, #Contents.Reagents do
Skin.TradeSkillReagentTemplate(Contents.Reagents[i])
end
for i = 1, #Contents.OptionalReagents do
Skin.TradeSkillOptionalReagentTemplate(Contents.OptionalReagents[i])
end
ScrollFrame.GlowClipFrame:SetPoint("TOP", 0, 10)
end
end
do --[[ Blizzard_TradeSkillRecipeList ]]
function Skin.TradeSkillRecipeListTemplate(ScrollFrame)
Skin.TabButtonTemplate(ScrollFrame.LearnedTab)
Skin.TabButtonTemplate(ScrollFrame.UnlearnedTab)
local _, _, _, scrollBar = ScrollFrame:GetChildren()
Skin.HybridScrollBarTemplate(scrollBar)
--Skin.UIDropDownMenuTemplate(ScrollFrame.RecipeOptionsMenu)
end
end
do --[[ Blizzard_TradeSkillOptionalReagentList ]]
function Skin.OptionalReagentListLineTemplate(Frame)
Skin.ScrollListLineTemplate(Frame)
Skin.OptionalReagentButtonTemplate(Frame)
end
function Skin.OptionalReagentListTemplate(Frame)
Skin.SimplePanelTemplate(Frame)
Skin.UICheckButtonTemplate(Frame.HideUnownedButton)
Skin.UIPanelButtonTemplate(Frame.CloseButton)
Skin.ScrollListTemplate(Frame.ScrollList)
end
end
end
function private.AddOns.Blizzard_TradeSkillUI()
----====####$$$$%%%%$$$$####====----
-- Blizzard_TradeSkillUtils --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%$$$$####====----
-- Blizzard_TradeSkillTemplates --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- Blizzard_TradeSkillRecipeButton --
----====####$$$$%%%%%$$$$####====----
----====####$$$$%%%%$$$$####====----
-- Blizzard_TradeSkillDetails --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- Blizzard_TradeSkillRecipeList --
----====####$$$$%%%%%$$$$####====----
----====####$$$$%%%%%%%%%%%%$$$$####====----
-- Blizzard_TradeSkillOptionalReagentList --
----====####$$$$%%%%%%%%%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- Blizzard_TradeSkillUI --
----====####$$$$%%%%%$$$$####====----
local TradeSkillFrame = _G.TradeSkillFrame
Skin.PortraitFrameTemplate(TradeSkillFrame)
TradeSkillFrame.TabardBackground:SetPoint("TOPLEFT", 0, 0)
TradeSkillFrame.TabardBackground:SetTexCoord(0, 1, 0, 1)
TradeSkillFrame.TabardBackground:SetAtlas("communities-guildbanner-background", true)
TradeSkillFrame.TabardEmblem:SetSize(56 * 1.2, 64 * 1.2)
TradeSkillFrame.TabardEmblem:SetPoint("CENTER", TradeSkillFrame.TabardBackground, 0, 8)
TradeSkillFrame.TabardBorder:SetPoint("TOPLEFT", 0, 0)
TradeSkillFrame.TabardBorder:SetTexCoord(0, 1, 0, 1)
TradeSkillFrame.TabardBorder:SetAtlas("communities-guildbanner-border", true)
Skin.InsetFrameTemplate(TradeSkillFrame.RecipeInset)
Skin.InsetFrameTemplate(TradeSkillFrame.DetailsInset)
Skin.TradeSkillRecipeListTemplate(TradeSkillFrame.RecipeList)
Skin.TradeSkillDetailsFrameTemplate(TradeSkillFrame.DetailsFrame)
local RankFrame = TradeSkillFrame.RankFrame
Skin.FrameTypeStatusBar(RankFrame)
RankFrame.BorderLeft:Hide()
RankFrame.BorderRight:Hide()
RankFrame.BorderMid:Hide()
RankFrame.Background:Hide()
Skin.SearchBoxTemplate(TradeSkillFrame.SearchBox)
Skin.UIMenuButtonStretchTemplate(TradeSkillFrame.FilterButton)
TradeSkillFrame.FilterButton.Icon:SetSize(5, 10)
Base.SetTexture(TradeSkillFrame.FilterButton.Icon, "arrowRight")
do -- LinkToButton
local LinkToButton = TradeSkillFrame.LinkToButton
Skin.FrameTypeButton(LinkToButton)
LinkToButton:SetBackdropOption("offsets", {
left = 4,
right = 5,
top = 8,
bottom = 5,
})
local bg = LinkToButton:GetBackdropTexture("bg")
local chatIcon = LinkToButton:CreateTexture(nil, "ARTWORK", nil, 1)
chatIcon:SetAtlas("transmog-icon-chat")
chatIcon:SetPoint("CENTER", bg, -2, -1)
chatIcon:SetSize(11, 11)
local arrow = LinkToButton:CreateTexture(nil, "ARTWORK", nil, 5)
arrow:SetPoint("TOPRIGHT", bg, -2, -4)
arrow:SetSize(5, 10)
Base.SetTexture(arrow, "arrowRight")
end
Skin.OptionalReagentListTemplate(TradeSkillFrame.OptionalReagentList)
end
| 412 | 0.911435 | 1 | 0.911435 | game-dev | MEDIA | 0.708829 | game-dev | 0.928129 | 1 | 0.928129 |
Geant4/geant4 | 3,670 | examples/extended/persistency/P02/exampleP02.cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file persistency/P02/exampleP02.cc
/// \brief Main program of the persistency/P02 example
//
//
//
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "ExP02DetConstrReader.hh"
#include "ExP02DetectorConstruction.hh"
#include "ExP02PrimaryGeneratorAction.hh"
#include "FTFP_BERT.hh"
#include "G4RunManagerFactory.hh"
#include "G4Types.hh"
#include "G4UIExecutive.hh"
#include "G4UImanager.hh"
#include "G4VisExecutive.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
int main(int argc, char** argv)
{
if (argc == 1) {
G4cout << "Please give 'write' or 'read' as argument " << G4endl;
return 0;
}
G4VUserDetectorConstruction* det;
if (std::string(argv[1]) == "read") {
det = new ExP02DetConstrReader;
}
else if (std::string(argv[1]) == "write") {
det = new ExP02DetectorConstruction;
}
else {
G4cout << "Wrong argument!" << G4endl;
return 0;
}
// User interface
G4UIExecutive* ui = new G4UIExecutive(argc, argv);
// Run manager
auto* runManager = G4RunManagerFactory::CreateRunManager(G4RunManagerType::SerialOnly);
// UserInitialization classes (mandatory)
runManager->SetUserInitialization(det);
G4VModularPhysicsList* physicsList = new FTFP_BERT;
runManager->SetUserInitialization(physicsList);
// Visualization
G4VisManager* visManager = new G4VisExecutive;
visManager->Initialize();
// UserAction classes
runManager->SetUserAction(new ExP02PrimaryGeneratorAction());
// Initialize G4 kernel
runManager->Initialize();
// get the pointer to the User Interface manager
G4UImanager* UImanager = G4UImanager::GetUIpointer();
UImanager->ApplyCommand("/control/execute vis.mac");
ui->SessionStart();
delete ui;
delete visManager;
delete runManager;
return 0;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 412 | 0.585209 | 1 | 0.585209 | game-dev | MEDIA | 0.646803 | game-dev | 0.664999 | 1 | 0.664999 |
LiXizhi/NPLRuntime | 1,385 | Client/trunk/ParaEngineClient/VoxelMesh/MetaHeightmap.h | #pragma once
#include "MetaObject.h"
#include "ShapeAABB.h"
namespace ParaEngine
{
/// a meta height map is associated with a region in the global height map based terrain.
class MetaHeightmap : public MetaObject
{
public:
/** a region in global height map based terrain. */
class TerrainRegion
{
public:
/** bounding box in world space */
TerrainRegion(const CShapeAABB& aabb) : m_aabb(aabb) {};
/** in world coordinate. */
float getHeightAt(float x, float z);
Vector3 getCenter() const;
const CShapeAABB& getBoundingBox() const {return m_aabb;};
private:
CShapeAABB m_aabb;
};
/**
* @param wf: world fragment to which this meta object belongs.
*/
MetaHeightmap(MetaWorldFragment *wf, const TerrainRegion& t, float groundThreshold);
/// Adds this meta height map to the data grid.
virtual void updateDataGrid(DataGrid* dataGrid);
/// Returns the fallof range of the MetaHeightmap.
float getFallofRange() const {return mFallofRange; }
/// Sets the fallof range. A fallof range less than the dataGrids grid size
/// will make the algorithm fail.
void setFallofRange(float fallof) {mFallofRange = fallof; }
virtual CShapeAABB getAABB() const;
protected:
// the parent terrain tile to which this meta height map is bound.
TerrainRegion mTerrainTile;
float mFallofRange, mGroundThreshold, mGradient;
};
} | 412 | 0.861006 | 1 | 0.861006 | game-dev | MEDIA | 0.937851 | game-dev | 0.649707 | 1 | 0.649707 |
glinuz/hi3798mv100 | 3,482 | HiSTBLinuxV100R005C00SPC041B020/sample/higo/sample_wm.c | /**
\file
\brief exmaple of GIF decoding and display
\copyright Shenzhen Hisilicon Co., Ltd.
\version draft
\author x57522
\date 2008-9-17
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "hi_go.h"
#include "sample_displayInit.h"
/***************************** Macro Definition ******************************/
/*************************** Structure Definition ****************************/
/********************** Global Variable declaration **************************/
/******************************* API declaration *****************************/
HI_S32 main(HI_S32 argc, HI_CHAR* argv[])
{
HI_S32 ret = HI_SUCCESS;
HI_HANDLE hLayer;
HIGO_WNDINFO_S WinInfo;
HI_HANDLE hWindow;
HI_S32 sWidth = 500, sHeight=400;
HI_HANDLE hWinSurface;
HIGO_LAYER_INFO_S LayerInfo;
HIGO_LAYER_E eLayerID = HIGO_LAYER_HD_0;
/** initial*/
ret = Display_Init();
if (HI_SUCCESS != ret)
{
return ret;
}
ret = HI_GO_Init();
if (HI_SUCCESS != ret)
{
goto ERR1;
}
/** get the HD layer's default parameters*/
ret = HI_GO_GetLayerDefaultParam(eLayerID, &LayerInfo);
if (HI_SUCCESS != ret)
{
goto ERR2;
}
/** create graphic layer */
ret = HI_GO_CreateLayer(&LayerInfo, &hLayer);
if (HI_SUCCESS != ret)
{
goto ERR2;
}
/** set the background color of graphic layer*/
ret = HI_GO_SetLayerBGColor(hLayer,0xffffffff);
if (HI_SUCCESS != ret)
{
goto ERR3;
}
WinInfo.hLayer = hLayer;
WinInfo.rect.x = 50;
WinInfo.rect.y = 50;
WinInfo.rect.w = sWidth;
WinInfo.rect.h = sHeight;
WinInfo.LayerNum = 0;
WinInfo.PixelFormat = HIGO_PF_8888;
WinInfo.BufferType = HIGO_BUFFER_SINGLE;
/** create window*/
ret = HI_GO_CreateWindowEx(&WinInfo, &hWindow);
if (HI_SUCCESS != ret)
{
goto ERR3;
}
/** get surface of the window */
ret = HI_GO_GetWindowSurface(hWindow, &hWinSurface);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
/** fill window*/
ret = HI_GO_FillRect(hWinSurface,NULL,0xFFFF0000,HIGO_COMPOPT_NONE);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
/** set the opacity of the window */
ret = HI_GO_SetWindowOpacity(hWindow,128);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
/** should fresh the window if any changed to the window*/
ret = HI_GO_UpdateWindow(hWindow,NULL);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
//fresh the window to the graphic layer
ret = HI_GO_RefreshLayer(hLayer, NULL);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
Printf("press any key to change pos\n");
getchar();
/** change the position of the window*/
ret = HI_GO_SetWindowPos(hWindow,300,200);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
/** fresh the window */
ret = HI_GO_UpdateWindow(hWindow, NULL);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
//fresh the window to the graphic layer
ret = HI_GO_RefreshLayer(hLayer, NULL);
if (HI_SUCCESS != ret)
{
goto ERR4;
}
printf("press any key to exit\n");
getchar();
ERR4:
HI_GO_DestroyWindow(hWindow);
ERR3:
HI_GO_DestroyLayer(hLayer);
ERR2:
HI_GO_Deinit();
ERR1:
Display_DeInit();
return ret;
}
| 412 | 0.523944 | 1 | 0.523944 | game-dev | MEDIA | 0.48379 | game-dev | 0.963209 | 1 | 0.963209 |
unixpickle/weakai | 6,737 | demos/minimax/scripts/game_state.js | (function() {
function GameState() {
this._playerTurn = 1;
this._specificJumpingPosition = null;
this._board = [];
for (var i = 0; i < GameState.BOARD_SIZE*GameState.BOARD_SIZE; ++i) {
this._board[i] = null;
}
var idStepper = 0;
for (var i = 0; i < GameState.PLAYER_ROWS; ++i) {
for (var j = 0; j < GameState.BOARD_SIZE; ++j) {
if ((j & 1) !== (i & 1)) {
continue;
}
for (var player = 1; player <= 2; ++player) {
var x = (player === 1 ? j : GameState.BOARD_SIZE-1-j);
var y = (player === 1 ? GameState.BOARD_SIZE-1-i : i);
var piece = new PieceState(idStepper++, player, false);
this._board[x + y*GameState.BOARD_SIZE] = piece;
}
}
}
}
GameState.BOARD_SIZE = 8;
GameState.PLAYER_ROWS = 3;
GameState.prototype.playerTurn = function() {
return this._playerTurn;
};
GameState.prototype.pieceAtPosition = function(p) {
return this._board[p.x + p.y*GameState.BOARD_SIZE];
};
GameState.prototype.availableMoves = function() {
if (this._specificJumpingPosition !== null) {
return this._availableJumpsForPosition(this._specificJumpingPosition);
}
var jumps = this._availableJumps();
if (jumps.length > 0) {
return jumps;
}
return this._availableNonJumps();
};
GameState.prototype.stateAfterMove = function(move) {
var state = Object.create(GameState.prototype);
state._playerTurn = this._playerTurn;
state._specificJumpingPosition = null;
state._board = this._board.slice();
state._setPieceAtPosition(move.getSource(), null);
var jumpedPos = move.jumpedPosition();
if (jumpedPos !== null) {
state._setPieceAtPosition(jumpedPos, null);
}
if ((move.getDestination().y === 0 && state._playerTurn === 1) ||
(move.getDestination().y === GameState.BOARD_SIZE-1 && state._playerTurn === 2)) {
var kingPiece = new PieceState(move.getPiece().getId(), move.getPiece().getPlayer(), true);
state._setPieceAtPosition(move.getDestination(), kingPiece);
} else {
state._setPieceAtPosition(move.getDestination(), move.getPiece());
}
if (jumpedPos !== null && state._availableJumpsForPosition(move.getDestination()).length > 0) {
state._specificJumpingPosition = move.getDestination();
} else {
state._playerTurn = (this._playerTurn === 1 ? 2 : 1);
state._specificJumpingPosition = null;
}
return state;
};
GameState.prototype._availableJumps = function() {
var res = [];
for (var x = 0; x < GameState.BOARD_SIZE; ++x) {
for (var y = 0; y < GameState.BOARD_SIZE; ++y) {
var jumps = this._availableJumpsForPosition({x: x, y: y});
for (var i = 0, len = jumps.length; i < len; ++i) {
res.push(jumps[i]);
}
}
}
return res;
};
GameState.prototype._availableJumpsForPosition = function(piecePosition) {
var res = [];
var piece = this.pieceAtPosition(piecePosition);
if (piece === null || piece.getPlayer() !== this._playerTurn) {
return res;
}
for (var dx = -1; dx <= 1; dx += 2) {
if (piecePosition.x+dx*2 < 0 || piecePosition.x+dx*2 > GameState.BOARD_SIZE-1) {
continue;
}
for (var dy = -1; dy <= 1; dy += 2) {
if ((piecePosition.y+dy*2 < 0 || piecePosition.y+dy*2 > GameState.BOARD_SIZE-1) ||
(dy === -1 && !piece.isKing() && piece.getPlayer() === 2) ||
(dy === 1 && !piece.isKing() && piece.getPlayer() === 1)) {
continue;
}
var jumpPiece = this.pieceAtPosition({x: piecePosition.x + dx, y: piecePosition.y + dy});
if (jumpPiece === null || jumpPiece.getPlayer() === this._playerTurn) {
continue;
}
var destinationPoint = {x: piecePosition.x + dx*2, y: piecePosition.y + dy*2};
var destination = this.pieceAtPosition(destinationPoint);
if (destination === null) {
res.push(new Move(piece, piecePosition, destinationPoint));
}
}
}
return res;
};
GameState.prototype._availableNonJumps = function() {
var res = [];
for (var x = 0; x < GameState.BOARD_SIZE; ++x) {
for (var y = 0; y < GameState.BOARD_SIZE; ++y) {
var moves = this._availableNonJumpsForPosition({x: x, y: y});
for (var i = 0, len = moves.length; i < len; ++i) {
res.push(moves[i]);
}
}
}
return res;
};
GameState.prototype._availableNonJumpsForPosition = function(piecePosition) {
var res = [];
var piece = this.pieceAtPosition(piecePosition);
if (piece === null || piece.getPlayer() !== this._playerTurn) {
return res;
}
for (var dx = -1; dx <= 1; dx += 2) {
if (piecePosition.x+dx < 0 || piecePosition.x+dx > GameState.BOARD_SIZE-1) {
continue;
}
for (var dy = -1; dy <= 1; dy += 2) {
if ((piecePosition.y+dy < 0 || piecePosition.y+dy > GameState.BOARD_SIZE-1) ||
(dy === -1 && !piece.isKing() && piece.getPlayer() === 2) ||
(dy === 1 && !piece.isKing() && piece.getPlayer() === 1)) {
continue;
}
var destinationPoint = {x: piecePosition.x + dx, y: piecePosition.y + dy};
var destination = this.pieceAtPosition(destinationPoint);
if (destination === null) {
res.push(new Move(piece, piecePosition, destinationPoint));
}
}
}
return res;
};
GameState.prototype._setPieceAtPosition = function(pos, piece) {
this._board[pos.x + pos.y*GameState.BOARD_SIZE] = piece;
};
function PieceState(id, player, isKing) {
this._id = id;
this._player = player;
this._isKing = isKing;
}
PieceState.prototype.getId = function() {
return this._id;
};
PieceState.prototype.getPlayer = function() {
return this._player;
};
PieceState.prototype.isKing = function() {
return this._isKing;
};
function Move(piece, source, destination) {
this._piece = piece;
this._source = source;
this._destination = destination;
}
Move.prototype.getPiece = function(piece) {
return this._piece;
};
Move.prototype.getSource = function() {
return this._source;
};
Move.prototype.getDestination = function() {
return this._destination;
};
Move.prototype.jumpedPosition = function() {
if (Math.abs(this._destination.x - this._source.x) === 2) {
return {
x: this._source.x + (this._destination.x-this._source.x)/2,
y: this._source.y + (this._destination.y-this._source.y)/2,
};
} else {
return null;
}
};
window.app.GameState = GameState;
window.app.Move = Move;
})();
| 412 | 0.823761 | 1 | 0.823761 | game-dev | MEDIA | 0.760643 | game-dev,web-frontend | 0.929909 | 1 | 0.929909 |
engstk/op8 | 19,183 | arch/x86/crypto/serpent-sse2-x86_64-asm_64.S | /*
* Serpent Cipher 8-way parallel algorithm (x86_64/SSE2)
*
* Copyright (C) 2011 Jussi Kivilinna <jussi.kivilinna@mbnet.fi>
*
* Based on crypto/serpent.c by
* Copyright (C) 2002 Dag Arne Osvik <osvik@ii.uib.no>
* 2003 Herbert Valerio Riedel <hvr@gnu.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 <linux/linkage.h>
.file "serpent-sse2-x86_64-asm_64.S"
.text
#define CTX %rdi
/**********************************************************************
8-way SSE2 serpent
**********************************************************************/
#define RA1 %xmm0
#define RB1 %xmm1
#define RC1 %xmm2
#define RD1 %xmm3
#define RE1 %xmm4
#define RA2 %xmm5
#define RB2 %xmm6
#define RC2 %xmm7
#define RD2 %xmm8
#define RE2 %xmm9
#define RNOT %xmm10
#define RK0 %xmm11
#define RK1 %xmm12
#define RK2 %xmm13
#define RK3 %xmm14
#define S0_1(x0, x1, x2, x3, x4) \
movdqa x3, x4; \
por x0, x3; \
pxor x4, x0; \
pxor x2, x4; \
pxor RNOT, x4; \
pxor x1, x3; \
pand x0, x1; \
pxor x4, x1; \
pxor x0, x2;
#define S0_2(x0, x1, x2, x3, x4) \
pxor x3, x0; \
por x0, x4; \
pxor x2, x0; \
pand x1, x2; \
pxor x2, x3; \
pxor RNOT, x1; \
pxor x4, x2; \
pxor x2, x1;
#define S1_1(x0, x1, x2, x3, x4) \
movdqa x1, x4; \
pxor x0, x1; \
pxor x3, x0; \
pxor RNOT, x3; \
pand x1, x4; \
por x1, x0; \
pxor x2, x3; \
pxor x3, x0; \
pxor x3, x1;
#define S1_2(x0, x1, x2, x3, x4) \
pxor x4, x3; \
por x4, x1; \
pxor x2, x4; \
pand x0, x2; \
pxor x1, x2; \
por x0, x1; \
pxor RNOT, x0; \
pxor x2, x0; \
pxor x1, x4;
#define S2_1(x0, x1, x2, x3, x4) \
pxor RNOT, x3; \
pxor x0, x1; \
movdqa x0, x4; \
pand x2, x0; \
pxor x3, x0; \
por x4, x3; \
pxor x1, x2; \
pxor x1, x3; \
pand x0, x1;
#define S2_2(x0, x1, x2, x3, x4) \
pxor x2, x0; \
pand x3, x2; \
por x1, x3; \
pxor RNOT, x0; \
pxor x0, x3; \
pxor x0, x4; \
pxor x2, x0; \
por x2, x1;
#define S3_1(x0, x1, x2, x3, x4) \
movdqa x1, x4; \
pxor x3, x1; \
por x0, x3; \
pand x0, x4; \
pxor x2, x0; \
pxor x1, x2; \
pand x3, x1; \
pxor x3, x2; \
por x4, x0; \
pxor x3, x4;
#define S3_2(x0, x1, x2, x3, x4) \
pxor x0, x1; \
pand x3, x0; \
pand x4, x3; \
pxor x2, x3; \
por x1, x4; \
pand x1, x2; \
pxor x3, x4; \
pxor x3, x0; \
pxor x2, x3;
#define S4_1(x0, x1, x2, x3, x4) \
movdqa x3, x4; \
pand x0, x3; \
pxor x4, x0; \
pxor x2, x3; \
por x4, x2; \
pxor x1, x0; \
pxor x3, x4; \
por x0, x2; \
pxor x1, x2;
#define S4_2(x0, x1, x2, x3, x4) \
pand x0, x1; \
pxor x4, x1; \
pand x2, x4; \
pxor x3, x2; \
pxor x0, x4; \
por x1, x3; \
pxor RNOT, x1; \
pxor x0, x3;
#define S5_1(x0, x1, x2, x3, x4) \
movdqa x1, x4; \
por x0, x1; \
pxor x1, x2; \
pxor RNOT, x3; \
pxor x0, x4; \
pxor x2, x0; \
pand x4, x1; \
por x3, x4; \
pxor x0, x4;
#define S5_2(x0, x1, x2, x3, x4) \
pand x3, x0; \
pxor x3, x1; \
pxor x2, x3; \
pxor x1, x0; \
pand x4, x2; \
pxor x2, x1; \
pand x0, x2; \
pxor x2, x3;
#define S6_1(x0, x1, x2, x3, x4) \
movdqa x1, x4; \
pxor x0, x3; \
pxor x2, x1; \
pxor x0, x2; \
pand x3, x0; \
por x3, x1; \
pxor RNOT, x4; \
pxor x1, x0; \
pxor x2, x1;
#define S6_2(x0, x1, x2, x3, x4) \
pxor x4, x3; \
pxor x0, x4; \
pand x0, x2; \
pxor x1, x4; \
pxor x3, x2; \
pand x1, x3; \
pxor x0, x3; \
pxor x2, x1;
#define S7_1(x0, x1, x2, x3, x4) \
pxor RNOT, x1; \
movdqa x1, x4; \
pxor RNOT, x0; \
pand x2, x1; \
pxor x3, x1; \
por x4, x3; \
pxor x2, x4; \
pxor x3, x2; \
pxor x0, x3; \
por x1, x0;
#define S7_2(x0, x1, x2, x3, x4) \
pand x0, x2; \
pxor x4, x0; \
pxor x3, x4; \
pand x0, x3; \
pxor x1, x4; \
pxor x4, x2; \
pxor x1, x3; \
por x0, x4; \
pxor x1, x4;
#define SI0_1(x0, x1, x2, x3, x4) \
movdqa x3, x4; \
pxor x0, x1; \
por x1, x3; \
pxor x1, x4; \
pxor RNOT, x0; \
pxor x3, x2; \
pxor x0, x3; \
pand x1, x0; \
pxor x2, x0;
#define SI0_2(x0, x1, x2, x3, x4) \
pand x3, x2; \
pxor x4, x3; \
pxor x3, x2; \
pxor x3, x1; \
pand x0, x3; \
pxor x0, x1; \
pxor x2, x0; \
pxor x3, x4;
#define SI1_1(x0, x1, x2, x3, x4) \
pxor x3, x1; \
movdqa x0, x4; \
pxor x2, x0; \
pxor RNOT, x2; \
por x1, x4; \
pxor x3, x4; \
pand x1, x3; \
pxor x2, x1; \
pand x4, x2;
#define SI1_2(x0, x1, x2, x3, x4) \
pxor x1, x4; \
por x3, x1; \
pxor x0, x3; \
pxor x0, x2; \
por x4, x0; \
pxor x4, x2; \
pxor x0, x1; \
pxor x1, x4;
#define SI2_1(x0, x1, x2, x3, x4) \
pxor x1, x2; \
movdqa x3, x4; \
pxor RNOT, x3; \
por x2, x3; \
pxor x4, x2; \
pxor x0, x4; \
pxor x1, x3; \
por x2, x1; \
pxor x0, x2;
#define SI2_2(x0, x1, x2, x3, x4) \
pxor x4, x1; \
por x3, x4; \
pxor x3, x2; \
pxor x2, x4; \
pand x1, x2; \
pxor x3, x2; \
pxor x4, x3; \
pxor x0, x4;
#define SI3_1(x0, x1, x2, x3, x4) \
pxor x1, x2; \
movdqa x1, x4; \
pand x2, x1; \
pxor x0, x1; \
por x4, x0; \
pxor x3, x4; \
pxor x3, x0; \
por x1, x3; \
pxor x2, x1;
#define SI3_2(x0, x1, x2, x3, x4) \
pxor x3, x1; \
pxor x2, x0; \
pxor x3, x2; \
pand x1, x3; \
pxor x0, x1; \
pand x2, x0; \
pxor x3, x4; \
pxor x0, x3; \
pxor x1, x0;
#define SI4_1(x0, x1, x2, x3, x4) \
pxor x3, x2; \
movdqa x0, x4; \
pand x1, x0; \
pxor x2, x0; \
por x3, x2; \
pxor RNOT, x4; \
pxor x0, x1; \
pxor x2, x0; \
pand x4, x2;
#define SI4_2(x0, x1, x2, x3, x4) \
pxor x0, x2; \
por x4, x0; \
pxor x3, x0; \
pand x2, x3; \
pxor x3, x4; \
pxor x1, x3; \
pand x0, x1; \
pxor x1, x4; \
pxor x3, x0;
#define SI5_1(x0, x1, x2, x3, x4) \
movdqa x1, x4; \
por x2, x1; \
pxor x4, x2; \
pxor x3, x1; \
pand x4, x3; \
pxor x3, x2; \
por x0, x3; \
pxor RNOT, x0; \
pxor x2, x3; \
por x0, x2;
#define SI5_2(x0, x1, x2, x3, x4) \
pxor x1, x4; \
pxor x4, x2; \
pand x0, x4; \
pxor x1, x0; \
pxor x3, x1; \
pand x2, x0; \
pxor x3, x2; \
pxor x2, x0; \
pxor x4, x2; \
pxor x3, x4;
#define SI6_1(x0, x1, x2, x3, x4) \
pxor x2, x0; \
movdqa x0, x4; \
pand x3, x0; \
pxor x3, x2; \
pxor x2, x0; \
pxor x1, x3; \
por x4, x2; \
pxor x3, x2; \
pand x0, x3;
#define SI6_2(x0, x1, x2, x3, x4) \
pxor RNOT, x0; \
pxor x1, x3; \
pand x2, x1; \
pxor x0, x4; \
pxor x4, x3; \
pxor x2, x4; \
pxor x1, x0; \
pxor x0, x2;
#define SI7_1(x0, x1, x2, x3, x4) \
movdqa x3, x4; \
pand x0, x3; \
pxor x2, x0; \
por x4, x2; \
pxor x1, x4; \
pxor RNOT, x0; \
por x3, x1; \
pxor x0, x4; \
pand x2, x0; \
pxor x1, x0;
#define SI7_2(x0, x1, x2, x3, x4) \
pand x2, x1; \
pxor x2, x3; \
pxor x3, x4; \
pand x3, x2; \
por x0, x3; \
pxor x4, x1; \
pxor x4, x3; \
pand x0, x4; \
pxor x2, x4;
#define get_key(i, j, t) \
movd (4*(i)+(j))*4(CTX), t; \
pshufd $0, t, t;
#define K2(x0, x1, x2, x3, x4, i) \
get_key(i, 0, RK0); \
get_key(i, 1, RK1); \
get_key(i, 2, RK2); \
get_key(i, 3, RK3); \
pxor RK0, x0 ## 1; \
pxor RK1, x1 ## 1; \
pxor RK2, x2 ## 1; \
pxor RK3, x3 ## 1; \
pxor RK0, x0 ## 2; \
pxor RK1, x1 ## 2; \
pxor RK2, x2 ## 2; \
pxor RK3, x3 ## 2;
#define LK2(x0, x1, x2, x3, x4, i) \
movdqa x0 ## 1, x4 ## 1; \
pslld $13, x0 ## 1; \
psrld $(32 - 13), x4 ## 1; \
por x4 ## 1, x0 ## 1; \
pxor x0 ## 1, x1 ## 1; \
movdqa x2 ## 1, x4 ## 1; \
pslld $3, x2 ## 1; \
psrld $(32 - 3), x4 ## 1; \
por x4 ## 1, x2 ## 1; \
pxor x2 ## 1, x1 ## 1; \
movdqa x0 ## 2, x4 ## 2; \
pslld $13, x0 ## 2; \
psrld $(32 - 13), x4 ## 2; \
por x4 ## 2, x0 ## 2; \
pxor x0 ## 2, x1 ## 2; \
movdqa x2 ## 2, x4 ## 2; \
pslld $3, x2 ## 2; \
psrld $(32 - 3), x4 ## 2; \
por x4 ## 2, x2 ## 2; \
pxor x2 ## 2, x1 ## 2; \
movdqa x1 ## 1, x4 ## 1; \
pslld $1, x1 ## 1; \
psrld $(32 - 1), x4 ## 1; \
por x4 ## 1, x1 ## 1; \
movdqa x0 ## 1, x4 ## 1; \
pslld $3, x4 ## 1; \
pxor x2 ## 1, x3 ## 1; \
pxor x4 ## 1, x3 ## 1; \
movdqa x3 ## 1, x4 ## 1; \
get_key(i, 1, RK1); \
movdqa x1 ## 2, x4 ## 2; \
pslld $1, x1 ## 2; \
psrld $(32 - 1), x4 ## 2; \
por x4 ## 2, x1 ## 2; \
movdqa x0 ## 2, x4 ## 2; \
pslld $3, x4 ## 2; \
pxor x2 ## 2, x3 ## 2; \
pxor x4 ## 2, x3 ## 2; \
movdqa x3 ## 2, x4 ## 2; \
get_key(i, 3, RK3); \
pslld $7, x3 ## 1; \
psrld $(32 - 7), x4 ## 1; \
por x4 ## 1, x3 ## 1; \
movdqa x1 ## 1, x4 ## 1; \
pslld $7, x4 ## 1; \
pxor x1 ## 1, x0 ## 1; \
pxor x3 ## 1, x0 ## 1; \
pxor x3 ## 1, x2 ## 1; \
pxor x4 ## 1, x2 ## 1; \
get_key(i, 0, RK0); \
pslld $7, x3 ## 2; \
psrld $(32 - 7), x4 ## 2; \
por x4 ## 2, x3 ## 2; \
movdqa x1 ## 2, x4 ## 2; \
pslld $7, x4 ## 2; \
pxor x1 ## 2, x0 ## 2; \
pxor x3 ## 2, x0 ## 2; \
pxor x3 ## 2, x2 ## 2; \
pxor x4 ## 2, x2 ## 2; \
get_key(i, 2, RK2); \
pxor RK1, x1 ## 1; \
pxor RK3, x3 ## 1; \
movdqa x0 ## 1, x4 ## 1; \
pslld $5, x0 ## 1; \
psrld $(32 - 5), x4 ## 1; \
por x4 ## 1, x0 ## 1; \
movdqa x2 ## 1, x4 ## 1; \
pslld $22, x2 ## 1; \
psrld $(32 - 22), x4 ## 1; \
por x4 ## 1, x2 ## 1; \
pxor RK0, x0 ## 1; \
pxor RK2, x2 ## 1; \
pxor RK1, x1 ## 2; \
pxor RK3, x3 ## 2; \
movdqa x0 ## 2, x4 ## 2; \
pslld $5, x0 ## 2; \
psrld $(32 - 5), x4 ## 2; \
por x4 ## 2, x0 ## 2; \
movdqa x2 ## 2, x4 ## 2; \
pslld $22, x2 ## 2; \
psrld $(32 - 22), x4 ## 2; \
por x4 ## 2, x2 ## 2; \
pxor RK0, x0 ## 2; \
pxor RK2, x2 ## 2;
#define KL2(x0, x1, x2, x3, x4, i) \
pxor RK0, x0 ## 1; \
pxor RK2, x2 ## 1; \
movdqa x0 ## 1, x4 ## 1; \
psrld $5, x0 ## 1; \
pslld $(32 - 5), x4 ## 1; \
por x4 ## 1, x0 ## 1; \
pxor RK3, x3 ## 1; \
pxor RK1, x1 ## 1; \
movdqa x2 ## 1, x4 ## 1; \
psrld $22, x2 ## 1; \
pslld $(32 - 22), x4 ## 1; \
por x4 ## 1, x2 ## 1; \
pxor x3 ## 1, x2 ## 1; \
pxor RK0, x0 ## 2; \
pxor RK2, x2 ## 2; \
movdqa x0 ## 2, x4 ## 2; \
psrld $5, x0 ## 2; \
pslld $(32 - 5), x4 ## 2; \
por x4 ## 2, x0 ## 2; \
pxor RK3, x3 ## 2; \
pxor RK1, x1 ## 2; \
movdqa x2 ## 2, x4 ## 2; \
psrld $22, x2 ## 2; \
pslld $(32 - 22), x4 ## 2; \
por x4 ## 2, x2 ## 2; \
pxor x3 ## 2, x2 ## 2; \
pxor x3 ## 1, x0 ## 1; \
movdqa x1 ## 1, x4 ## 1; \
pslld $7, x4 ## 1; \
pxor x1 ## 1, x0 ## 1; \
pxor x4 ## 1, x2 ## 1; \
movdqa x1 ## 1, x4 ## 1; \
psrld $1, x1 ## 1; \
pslld $(32 - 1), x4 ## 1; \
por x4 ## 1, x1 ## 1; \
pxor x3 ## 2, x0 ## 2; \
movdqa x1 ## 2, x4 ## 2; \
pslld $7, x4 ## 2; \
pxor x1 ## 2, x0 ## 2; \
pxor x4 ## 2, x2 ## 2; \
movdqa x1 ## 2, x4 ## 2; \
psrld $1, x1 ## 2; \
pslld $(32 - 1), x4 ## 2; \
por x4 ## 2, x1 ## 2; \
movdqa x3 ## 1, x4 ## 1; \
psrld $7, x3 ## 1; \
pslld $(32 - 7), x4 ## 1; \
por x4 ## 1, x3 ## 1; \
pxor x0 ## 1, x1 ## 1; \
movdqa x0 ## 1, x4 ## 1; \
pslld $3, x4 ## 1; \
pxor x4 ## 1, x3 ## 1; \
movdqa x0 ## 1, x4 ## 1; \
movdqa x3 ## 2, x4 ## 2; \
psrld $7, x3 ## 2; \
pslld $(32 - 7), x4 ## 2; \
por x4 ## 2, x3 ## 2; \
pxor x0 ## 2, x1 ## 2; \
movdqa x0 ## 2, x4 ## 2; \
pslld $3, x4 ## 2; \
pxor x4 ## 2, x3 ## 2; \
movdqa x0 ## 2, x4 ## 2; \
psrld $13, x0 ## 1; \
pslld $(32 - 13), x4 ## 1; \
por x4 ## 1, x0 ## 1; \
pxor x2 ## 1, x1 ## 1; \
pxor x2 ## 1, x3 ## 1; \
movdqa x2 ## 1, x4 ## 1; \
psrld $3, x2 ## 1; \
pslld $(32 - 3), x4 ## 1; \
por x4 ## 1, x2 ## 1; \
psrld $13, x0 ## 2; \
pslld $(32 - 13), x4 ## 2; \
por x4 ## 2, x0 ## 2; \
pxor x2 ## 2, x1 ## 2; \
pxor x2 ## 2, x3 ## 2; \
movdqa x2 ## 2, x4 ## 2; \
psrld $3, x2 ## 2; \
pslld $(32 - 3), x4 ## 2; \
por x4 ## 2, x2 ## 2;
#define S(SBOX, x0, x1, x2, x3, x4) \
SBOX ## _1(x0 ## 1, x1 ## 1, x2 ## 1, x3 ## 1, x4 ## 1); \
SBOX ## _2(x0 ## 1, x1 ## 1, x2 ## 1, x3 ## 1, x4 ## 1); \
SBOX ## _1(x0 ## 2, x1 ## 2, x2 ## 2, x3 ## 2, x4 ## 2); \
SBOX ## _2(x0 ## 2, x1 ## 2, x2 ## 2, x3 ## 2, x4 ## 2);
#define SP(SBOX, x0, x1, x2, x3, x4, i) \
get_key(i, 0, RK0); \
SBOX ## _1(x0 ## 1, x1 ## 1, x2 ## 1, x3 ## 1, x4 ## 1); \
get_key(i, 2, RK2); \
SBOX ## _1(x0 ## 2, x1 ## 2, x2 ## 2, x3 ## 2, x4 ## 2); \
get_key(i, 3, RK3); \
SBOX ## _2(x0 ## 1, x1 ## 1, x2 ## 1, x3 ## 1, x4 ## 1); \
get_key(i, 1, RK1); \
SBOX ## _2(x0 ## 2, x1 ## 2, x2 ## 2, x3 ## 2, x4 ## 2); \
#define transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \
movdqa x0, t2; \
punpckldq x1, x0; \
punpckhdq x1, t2; \
movdqa x2, t1; \
punpckhdq x3, x2; \
punpckldq x3, t1; \
movdqa x0, x1; \
punpcklqdq t1, x0; \
punpckhqdq t1, x1; \
movdqa t2, x3; \
punpcklqdq x2, t2; \
punpckhqdq x2, x3; \
movdqa t2, x2;
#define read_blocks(in, x0, x1, x2, x3, t0, t1, t2) \
movdqu (0*4*4)(in), x0; \
movdqu (1*4*4)(in), x1; \
movdqu (2*4*4)(in), x2; \
movdqu (3*4*4)(in), x3; \
\
transpose_4x4(x0, x1, x2, x3, t0, t1, t2)
#define write_blocks(out, x0, x1, x2, x3, t0, t1, t2) \
transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \
\
movdqu x0, (0*4*4)(out); \
movdqu x1, (1*4*4)(out); \
movdqu x2, (2*4*4)(out); \
movdqu x3, (3*4*4)(out);
#define xor_blocks(out, x0, x1, x2, x3, t0, t1, t2) \
transpose_4x4(x0, x1, x2, x3, t0, t1, t2) \
\
movdqu (0*4*4)(out), t0; \
pxor t0, x0; \
movdqu x0, (0*4*4)(out); \
movdqu (1*4*4)(out), t0; \
pxor t0, x1; \
movdqu x1, (1*4*4)(out); \
movdqu (2*4*4)(out), t0; \
pxor t0, x2; \
movdqu x2, (2*4*4)(out); \
movdqu (3*4*4)(out), t0; \
pxor t0, x3; \
movdqu x3, (3*4*4)(out);
ENTRY(__serpent_enc_blk_8way)
/* input:
* %rdi: ctx, CTX
* %rsi: dst
* %rdx: src
* %rcx: bool, if true: xor output
*/
pcmpeqd RNOT, RNOT;
leaq (4*4*4)(%rdx), %rax;
read_blocks(%rdx, RA1, RB1, RC1, RD1, RK0, RK1, RK2);
read_blocks(%rax, RA2, RB2, RC2, RD2, RK0, RK1, RK2);
K2(RA, RB, RC, RD, RE, 0);
S(S0, RA, RB, RC, RD, RE); LK2(RC, RB, RD, RA, RE, 1);
S(S1, RC, RB, RD, RA, RE); LK2(RE, RD, RA, RC, RB, 2);
S(S2, RE, RD, RA, RC, RB); LK2(RB, RD, RE, RC, RA, 3);
S(S3, RB, RD, RE, RC, RA); LK2(RC, RA, RD, RB, RE, 4);
S(S4, RC, RA, RD, RB, RE); LK2(RA, RD, RB, RE, RC, 5);
S(S5, RA, RD, RB, RE, RC); LK2(RC, RA, RD, RE, RB, 6);
S(S6, RC, RA, RD, RE, RB); LK2(RD, RB, RA, RE, RC, 7);
S(S7, RD, RB, RA, RE, RC); LK2(RC, RA, RE, RD, RB, 8);
S(S0, RC, RA, RE, RD, RB); LK2(RE, RA, RD, RC, RB, 9);
S(S1, RE, RA, RD, RC, RB); LK2(RB, RD, RC, RE, RA, 10);
S(S2, RB, RD, RC, RE, RA); LK2(RA, RD, RB, RE, RC, 11);
S(S3, RA, RD, RB, RE, RC); LK2(RE, RC, RD, RA, RB, 12);
S(S4, RE, RC, RD, RA, RB); LK2(RC, RD, RA, RB, RE, 13);
S(S5, RC, RD, RA, RB, RE); LK2(RE, RC, RD, RB, RA, 14);
S(S6, RE, RC, RD, RB, RA); LK2(RD, RA, RC, RB, RE, 15);
S(S7, RD, RA, RC, RB, RE); LK2(RE, RC, RB, RD, RA, 16);
S(S0, RE, RC, RB, RD, RA); LK2(RB, RC, RD, RE, RA, 17);
S(S1, RB, RC, RD, RE, RA); LK2(RA, RD, RE, RB, RC, 18);
S(S2, RA, RD, RE, RB, RC); LK2(RC, RD, RA, RB, RE, 19);
S(S3, RC, RD, RA, RB, RE); LK2(RB, RE, RD, RC, RA, 20);
S(S4, RB, RE, RD, RC, RA); LK2(RE, RD, RC, RA, RB, 21);
S(S5, RE, RD, RC, RA, RB); LK2(RB, RE, RD, RA, RC, 22);
S(S6, RB, RE, RD, RA, RC); LK2(RD, RC, RE, RA, RB, 23);
S(S7, RD, RC, RE, RA, RB); LK2(RB, RE, RA, RD, RC, 24);
S(S0, RB, RE, RA, RD, RC); LK2(RA, RE, RD, RB, RC, 25);
S(S1, RA, RE, RD, RB, RC); LK2(RC, RD, RB, RA, RE, 26);
S(S2, RC, RD, RB, RA, RE); LK2(RE, RD, RC, RA, RB, 27);
S(S3, RE, RD, RC, RA, RB); LK2(RA, RB, RD, RE, RC, 28);
S(S4, RA, RB, RD, RE, RC); LK2(RB, RD, RE, RC, RA, 29);
S(S5, RB, RD, RE, RC, RA); LK2(RA, RB, RD, RC, RE, 30);
S(S6, RA, RB, RD, RC, RE); LK2(RD, RE, RB, RC, RA, 31);
S(S7, RD, RE, RB, RC, RA); K2(RA, RB, RC, RD, RE, 32);
leaq (4*4*4)(%rsi), %rax;
testb %cl, %cl;
jnz .L__enc_xor8;
write_blocks(%rsi, RA1, RB1, RC1, RD1, RK0, RK1, RK2);
write_blocks(%rax, RA2, RB2, RC2, RD2, RK0, RK1, RK2);
ret;
.L__enc_xor8:
xor_blocks(%rsi, RA1, RB1, RC1, RD1, RK0, RK1, RK2);
xor_blocks(%rax, RA2, RB2, RC2, RD2, RK0, RK1, RK2);
ret;
ENDPROC(__serpent_enc_blk_8way)
ENTRY(serpent_dec_blk_8way)
/* input:
* %rdi: ctx, CTX
* %rsi: dst
* %rdx: src
*/
pcmpeqd RNOT, RNOT;
leaq (4*4*4)(%rdx), %rax;
read_blocks(%rdx, RA1, RB1, RC1, RD1, RK0, RK1, RK2);
read_blocks(%rax, RA2, RB2, RC2, RD2, RK0, RK1, RK2);
K2(RA, RB, RC, RD, RE, 32);
SP(SI7, RA, RB, RC, RD, RE, 31); KL2(RB, RD, RA, RE, RC, 31);
SP(SI6, RB, RD, RA, RE, RC, 30); KL2(RA, RC, RE, RB, RD, 30);
SP(SI5, RA, RC, RE, RB, RD, 29); KL2(RC, RD, RA, RE, RB, 29);
SP(SI4, RC, RD, RA, RE, RB, 28); KL2(RC, RA, RB, RE, RD, 28);
SP(SI3, RC, RA, RB, RE, RD, 27); KL2(RB, RC, RD, RE, RA, 27);
SP(SI2, RB, RC, RD, RE, RA, 26); KL2(RC, RA, RE, RD, RB, 26);
SP(SI1, RC, RA, RE, RD, RB, 25); KL2(RB, RA, RE, RD, RC, 25);
SP(SI0, RB, RA, RE, RD, RC, 24); KL2(RE, RC, RA, RB, RD, 24);
SP(SI7, RE, RC, RA, RB, RD, 23); KL2(RC, RB, RE, RD, RA, 23);
SP(SI6, RC, RB, RE, RD, RA, 22); KL2(RE, RA, RD, RC, RB, 22);
SP(SI5, RE, RA, RD, RC, RB, 21); KL2(RA, RB, RE, RD, RC, 21);
SP(SI4, RA, RB, RE, RD, RC, 20); KL2(RA, RE, RC, RD, RB, 20);
SP(SI3, RA, RE, RC, RD, RB, 19); KL2(RC, RA, RB, RD, RE, 19);
SP(SI2, RC, RA, RB, RD, RE, 18); KL2(RA, RE, RD, RB, RC, 18);
SP(SI1, RA, RE, RD, RB, RC, 17); KL2(RC, RE, RD, RB, RA, 17);
SP(SI0, RC, RE, RD, RB, RA, 16); KL2(RD, RA, RE, RC, RB, 16);
SP(SI7, RD, RA, RE, RC, RB, 15); KL2(RA, RC, RD, RB, RE, 15);
SP(SI6, RA, RC, RD, RB, RE, 14); KL2(RD, RE, RB, RA, RC, 14);
SP(SI5, RD, RE, RB, RA, RC, 13); KL2(RE, RC, RD, RB, RA, 13);
SP(SI4, RE, RC, RD, RB, RA, 12); KL2(RE, RD, RA, RB, RC, 12);
SP(SI3, RE, RD, RA, RB, RC, 11); KL2(RA, RE, RC, RB, RD, 11);
SP(SI2, RA, RE, RC, RB, RD, 10); KL2(RE, RD, RB, RC, RA, 10);
SP(SI1, RE, RD, RB, RC, RA, 9); KL2(RA, RD, RB, RC, RE, 9);
SP(SI0, RA, RD, RB, RC, RE, 8); KL2(RB, RE, RD, RA, RC, 8);
SP(SI7, RB, RE, RD, RA, RC, 7); KL2(RE, RA, RB, RC, RD, 7);
SP(SI6, RE, RA, RB, RC, RD, 6); KL2(RB, RD, RC, RE, RA, 6);
SP(SI5, RB, RD, RC, RE, RA, 5); KL2(RD, RA, RB, RC, RE, 5);
SP(SI4, RD, RA, RB, RC, RE, 4); KL2(RD, RB, RE, RC, RA, 4);
SP(SI3, RD, RB, RE, RC, RA, 3); KL2(RE, RD, RA, RC, RB, 3);
SP(SI2, RE, RD, RA, RC, RB, 2); KL2(RD, RB, RC, RA, RE, 2);
SP(SI1, RD, RB, RC, RA, RE, 1); KL2(RE, RB, RC, RA, RD, 1);
S(SI0, RE, RB, RC, RA, RD); K2(RC, RD, RB, RE, RA, 0);
leaq (4*4*4)(%rsi), %rax;
write_blocks(%rsi, RC1, RD1, RB1, RE1, RK0, RK1, RK2);
write_blocks(%rax, RC2, RD2, RB2, RE2, RK0, RK1, RK2);
ret;
ENDPROC(serpent_dec_blk_8way)
| 412 | 0.879828 | 1 | 0.879828 | game-dev | MEDIA | 0.372202 | game-dev | 0.537917 | 1 | 0.537917 |
AlexGyver/GyverLibs | 1,419 | GyverBus/examples/esp8266 to ardu (softserial)/send/send.ino | // отправляем структуру через SoftwareSerial
// отправляет esp8266 (этот скетч), принимает Ардуина
// Провод подключен к D2 ноды и D10 Ардуины
#include <SoftwareSerial.h>
SoftwareSerial mySerial(5, 4); // RX, TX
// ВНИМАНИЕ! Нужно указывать номера GPIO, а не D-пины
// на Node получается RX-D1, TX-D2
#include "GBUS.h"
// адрес 5, буфер 20 байт
GBUS bus(&mySerial, 5, 20);
// структура для отправки
// БУДЬ ВНИМАТЕЛЕН, ЛЮБИТЕЛЬ ESP8266!!
// Тут данные кодируются хрен пойми как, компилятор "не смог"
// сначала располагай тяжёлые типы данных (float, int, long)
// РАСПОЛАГАЙ БАЙТЫ В КОНЦЕ СТРУКТУРЫ!
// int тут занимает 4 байта, так что на Arduino его нужно принимать как long!!!
// структура структур должна быть одинаковая
struct myStruct {
float val_f;
float val_f2;
int val_i;
long val_l;
byte val_b;
};
void setup() {
// родной сериал открываю для наблюдения за процессом
Serial.begin(9600);
// этот сериал будет принимать данные
// мы указали его как обработчик
mySerial.begin(9600);
}
void loop() {
Serial.println("transmitting");
myStruct data;
// забиваем данные
data.val_f = 12.34;
data.val_f2 = 56.78;
data.val_i = 1234;
data.val_l = 123456;
data.val_b = 12;
// отправляем на адрес 3
bus.sendData(3, data);
delay(2000);
// tick() тут не нужен! Он занимается только приёмом данных
// отправка делается так, как реализовано в используемой либе интерфейса
}
| 412 | 0.673909 | 1 | 0.673909 | game-dev | MEDIA | 0.263408 | game-dev | 0.514961 | 1 | 0.514961 |
SuperMap/vue-iclient | 36,517 | static/libs/Cesium/Workers/upsampleQuantizedTerrainMesh.js | /**
* Cesium - https://github.com/AnalyticalGraphicsInc/cesium
*
* Copyright 2011-2017 Cesium Contributors
*
* 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.
*
* Columbus View (Pat. Pend.)
*
* Portions licensed separately.
* See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
*/
define(['./when-a55a8a4c', './Check-bc1d37d9', './Math-edfe2d1c', './Cartesian2-52d9479f', './BoundingSphere-ab31357a', './RuntimeError-7c184ac0', './WebGLConstants-4c11ee5f', './ComponentDatatype-919a7463', './FeatureDetection-bac17d71', './Transforms-794e44e6', './buildModuleUrl-02e5236f', './AttributeCompression-4a5b893f', './IndexDatatype-18a8cae6', './IntersectionTests-afd4a13d', './Plane-68b37818', './createTaskProcessorWorker', './EllipsoidTangentPlane-7eb9b50e', './OrientedBoundingBox-80ab75fe', './TerrainEncoding-f6db33b5'], function (when, Check, _Math, Cartesian2, BoundingSphere, RuntimeError, WebGLConstants, ComponentDatatype, FeatureDetection, Transforms, buildModuleUrl, AttributeCompression, IndexDatatype, IntersectionTests, Plane, createTaskProcessorWorker, EllipsoidTangentPlane, OrientedBoundingBox, TerrainEncoding) { 'use strict';
/**
* Contains functions for operating on 2D triangles.
*
* @exports Intersections2D
*/
var Intersections2D = {};
/**
* Splits a 2D triangle at given axis-aligned threshold value and returns the resulting
* polygon on a given side of the threshold. The resulting polygon may have 0, 1, 2,
* 3, or 4 vertices.
*
* @param {Number} threshold The threshold coordinate value at which to clip the triangle.
* @param {Boolean} keepAbove true to keep the portion of the triangle above the threshold, or false
* to keep the portion below.
* @param {Number} u0 The coordinate of the first vertex in the triangle, in counter-clockwise order.
* @param {Number} u1 The coordinate of the second vertex in the triangle, in counter-clockwise order.
* @param {Number} u2 The coordinate of the third vertex in the triangle, in counter-clockwise order.
* @param {Number[]} [result] The array into which to copy the result. If this parameter is not supplied,
* a new array is constructed and returned.
* @returns {Number[]} The polygon that results after the clip, specified as a list of
* vertices. The vertices are specified in counter-clockwise order.
* Each vertex is either an index from the existing list (identified as
* a 0, 1, or 2) or -1 indicating a new vertex not in the original triangle.
* For new vertices, the -1 is followed by three additional numbers: the
* index of each of the two original vertices forming the line segment that
* the new vertex lies on, and the fraction of the distance from the first
* vertex to the second one.
*
* @example
* var result = Cesium.Intersections2D.clipTriangleAtAxisAlignedThreshold(0.5, false, 0.2, 0.6, 0.4);
* // result === [2, 0, -1, 1, 0, 0.25, -1, 1, 2, 0.5]
*/
Intersections2D.clipTriangleAtAxisAlignedThreshold = function(threshold, keepAbove, u0, u1, u2, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(threshold)) {
throw new Check.DeveloperError('threshold is required.');
}
if (!when.defined(keepAbove)) {
throw new Check.DeveloperError('keepAbove is required.');
}
if (!when.defined(u0)) {
throw new Check.DeveloperError('u0 is required.');
}
if (!when.defined(u1)) {
throw new Check.DeveloperError('u1 is required.');
}
if (!when.defined(u2)) {
throw new Check.DeveloperError('u2 is required.');
}
//>>includeEnd('debug');
if (!when.defined(result)) {
result = [];
} else {
result.length = 0;
}
var u0Behind;
var u1Behind;
var u2Behind;
if (keepAbove) {
u0Behind = u0 < threshold;
u1Behind = u1 < threshold;
u2Behind = u2 < threshold;
} else {
u0Behind = u0 > threshold;
u1Behind = u1 > threshold;
u2Behind = u2 > threshold;
}
var numBehind = u0Behind + u1Behind + u2Behind;
var u01Ratio;
var u02Ratio;
var u12Ratio;
var u10Ratio;
var u20Ratio;
var u21Ratio;
if (numBehind === 1) {
if (u0Behind) {
u01Ratio = (threshold - u0) / (u1 - u0);
u02Ratio = (threshold - u0) / (u2 - u0);
result.push(1);
result.push(2);
if (u02Ratio !== 1.0) {
result.push(-1);
result.push(0);
result.push(2);
result.push(u02Ratio);
}
if (u01Ratio !== 1.0) {
result.push(-1);
result.push(0);
result.push(1);
result.push(u01Ratio);
}
} else if (u1Behind) {
u12Ratio = (threshold - u1) / (u2 - u1);
u10Ratio = (threshold - u1) / (u0 - u1);
result.push(2);
result.push(0);
if (u10Ratio !== 1.0) {
result.push(-1);
result.push(1);
result.push(0);
result.push(u10Ratio);
}
if (u12Ratio !== 1.0) {
result.push(-1);
result.push(1);
result.push(2);
result.push(u12Ratio);
}
} else if (u2Behind) {
u20Ratio = (threshold - u2) / (u0 - u2);
u21Ratio = (threshold - u2) / (u1 - u2);
result.push(0);
result.push(1);
if (u21Ratio !== 1.0) {
result.push(-1);
result.push(2);
result.push(1);
result.push(u21Ratio);
}
if (u20Ratio !== 1.0) {
result.push(-1);
result.push(2);
result.push(0);
result.push(u20Ratio);
}
}
} else if (numBehind === 2) {
if (!u0Behind && u0 !== threshold) {
u10Ratio = (threshold - u1) / (u0 - u1);
u20Ratio = (threshold - u2) / (u0 - u2);
result.push(0);
result.push(-1);
result.push(1);
result.push(0);
result.push(u10Ratio);
result.push(-1);
result.push(2);
result.push(0);
result.push(u20Ratio);
} else if (!u1Behind && u1 !== threshold) {
u21Ratio = (threshold - u2) / (u1 - u2);
u01Ratio = (threshold - u0) / (u1 - u0);
result.push(1);
result.push(-1);
result.push(2);
result.push(1);
result.push(u21Ratio);
result.push(-1);
result.push(0);
result.push(1);
result.push(u01Ratio);
} else if (!u2Behind && u2 !== threshold) {
u02Ratio = (threshold - u0) / (u2 - u0);
u12Ratio = (threshold - u1) / (u2 - u1);
result.push(2);
result.push(-1);
result.push(0);
result.push(2);
result.push(u02Ratio);
result.push(-1);
result.push(1);
result.push(2);
result.push(u12Ratio);
}
} else if (numBehind !== 3) {
// Completely in front of threshold
result.push(0);
result.push(1);
result.push(2);
}
// else Completely behind threshold
return result;
};
/**
* Compute the barycentric coordinates of a 2D position within a 2D triangle.
*
* @param {Number} x The x coordinate of the position for which to find the barycentric coordinates.
* @param {Number} y The y coordinate of the position for which to find the barycentric coordinates.
* @param {Number} x1 The x coordinate of the triangle's first vertex.
* @param {Number} y1 The y coordinate of the triangle's first vertex.
* @param {Number} x2 The x coordinate of the triangle's second vertex.
* @param {Number} y2 The y coordinate of the triangle's second vertex.
* @param {Number} x3 The x coordinate of the triangle's third vertex.
* @param {Number} y3 The y coordinate of the triangle's third vertex.
* @param {Cartesian3} [result] The instance into to which to copy the result. If this parameter
* is undefined, a new instance is created and returned.
* @returns {Cartesian3} The barycentric coordinates of the position within the triangle.
*
* @example
* var result = Cesium.Intersections2D.computeBarycentricCoordinates(0.0, 0.0, 0.0, 1.0, -1, -0.5, 1, -0.5);
* // result === new Cesium.Cartesian3(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0);
*/
Intersections2D.computeBarycentricCoordinates = function(x, y, x1, y1, x2, y2, x3, y3, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(x)) {
throw new Check.DeveloperError('x is required.');
}
if (!when.defined(y)) {
throw new Check.DeveloperError('y is required.');
}
if (!when.defined(x1)) {
throw new Check.DeveloperError('x1 is required.');
}
if (!when.defined(y1)) {
throw new Check.DeveloperError('y1 is required.');
}
if (!when.defined(x2)) {
throw new Check.DeveloperError('x2 is required.');
}
if (!when.defined(y2)) {
throw new Check.DeveloperError('y2 is required.');
}
if (!when.defined(x3)) {
throw new Check.DeveloperError('x3 is required.');
}
if (!when.defined(y3)) {
throw new Check.DeveloperError('y3 is required.');
}
//>>includeEnd('debug');
var x1mx3 = x1 - x3;
var x3mx2 = x3 - x2;
var y2my3 = y2 - y3;
var y1my3 = y1 - y3;
var inverseDeterminant = 1.0 / (y2my3 * x1mx3 + x3mx2 * y1my3);
var ymy3 = y - y3;
var xmx3 = x - x3;
var l1 = (y2my3 * xmx3 + x3mx2 * ymy3) * inverseDeterminant;
var l2 = (-y1my3 * xmx3 + x1mx3 * ymy3) * inverseDeterminant;
var l3 = 1.0 - l1 - l2;
if (when.defined(result)) {
result.x = l1;
result.y = l2;
result.z = l3;
return result;
}
return new Cartesian2.Cartesian3(l1, l2, l3);
};
/**
* Compute the intersection between 2 line segments
*
* @param {Number} x00 The x coordinate of the first line's first vertex.
* @param {Number} y00 The y coordinate of the first line's first vertex.
* @param {Number} x01 The x coordinate of the first line's second vertex.
* @param {Number} y01 The y coordinate of the first line's second vertex.
* @param {Number} x10 The x coordinate of the second line's first vertex.
* @param {Number} y10 The y coordinate of the second line's first vertex.
* @param {Number} x11 The x coordinate of the second line's second vertex.
* @param {Number} y11 The y coordinate of the second line's second vertex.
* @param {Cartesian2} [result] The instance into to which to copy the result. If this parameter
* is undefined, a new instance is created and returned.
* @returns {Cartesian2} The intersection point, undefined if there is no intersection point or lines are coincident.
*
* @example
* var result = Cesium.Intersections2D.computeLineSegmentLineSegmentIntersection(0.0, 0.0, 0.0, 2.0, -1, 1, 1, 1);
* // result === new Cesium.Cartesian2(0.0, 1.0);
*/
Intersections2D.computeLineSegmentLineSegmentIntersection = function(x00, y00, x01, y01, x10, y10, x11, y11, result) {
//>>includeStart('debug', pragmas.debug);
Check.Check.typeOf.number('x00', x00);
Check.Check.typeOf.number('y00', y00);
Check.Check.typeOf.number('x01', x01);
Check.Check.typeOf.number('y01', y01);
Check.Check.typeOf.number('x10', x10);
Check.Check.typeOf.number('y10', y10);
Check.Check.typeOf.number('x11', x11);
Check.Check.typeOf.number('y11', y11);
//>>includeEnd('debug');
var numerator1A = (x11 - x10) * (y00 - y10) - (y11 - y10) * (x00 - x10);
var numerator1B = (x01 - x00) * (y00 - y10) - (y01 - y00) * (x00 - x10);
var denominator1 = (y11 - y10) * (x01 - x00) - (x11 - x10) * (y01 - y00);
// If denominator = 0, then lines are parallel. If denominator = 0 and both numerators are 0, then coincident
if (denominator1 === 0) {
return;
}
var ua1 = numerator1A / denominator1;
var ub1 = numerator1B / denominator1;
if (ua1 >= 0 && ua1 <= 1 && ub1 >= 0 && ub1 <= 1) {
if (!when.defined(result)) {
result = new Cartesian2.Cartesian2();
}
result.x = x00 + ua1 * (x01 - x00);
result.y = y00 + ua1 * (y01 - y00);
return result;
}
};
var maxShort = 32767;
var halfMaxShort = (maxShort / 2) | 0;
var clipScratch = [];
var clipScratch2 = [];
var verticesScratch = [];
var cartographicScratch = new Cartesian2.Cartographic();
var cartesian3Scratch = new Cartesian2.Cartesian3();
var uScratch = [];
var vScratch = [];
var heightScratch = [];
var indicesScratch = [];
var normalsScratch = [];
var horizonOcclusionPointScratch = new Cartesian2.Cartesian3();
var boundingSphereScratch = new BoundingSphere.BoundingSphere();
var orientedBoundingBoxScratch = new OrientedBoundingBox.OrientedBoundingBox();
var decodeTexCoordsScratch = new Cartesian2.Cartesian2();
var octEncodedNormalScratch = new Cartesian2.Cartesian3();
function upsampleQuantizedTerrainMesh(parameters, transferableObjects) {
var isEastChild = parameters.isEastChild;
var isNorthChild = parameters.isNorthChild;
var minU = isEastChild ? halfMaxShort : 0;
var maxU = isEastChild ? maxShort : halfMaxShort;
var minV = isNorthChild ? halfMaxShort : 0;
var maxV = isNorthChild ? maxShort : halfMaxShort;
var uBuffer = uScratch;
var vBuffer = vScratch;
var heightBuffer = heightScratch;
var normalBuffer = normalsScratch;
uBuffer.length = 0;
vBuffer.length = 0;
heightBuffer.length = 0;
normalBuffer.length = 0;
var indices = indicesScratch;
indices.length = 0;
var vertexMap = {};
var parentVertices = parameters.vertices;
var parentIndices = parameters.indices;
parentIndices = parentIndices.subarray(0, parameters.indexCountWithoutSkirts);
var encoding = TerrainEncoding.TerrainEncoding.clone(parameters.encoding);
var hasVertexNormals = encoding.hasVertexNormals;
var exaggeration = parameters.exaggeration;
var vertexCount = 0;
var quantizedVertexCount = parameters.vertexCountWithoutSkirts;
var parentMinimumHeight = parameters.minimumHeight;
var parentMaximumHeight = parameters.maximumHeight;
var parentUBuffer = new Array(quantizedVertexCount);
var parentVBuffer = new Array(quantizedVertexCount);
var parentHeightBuffer = new Array(quantizedVertexCount);
var parentNormalBuffer = hasVertexNormals ? new Array(quantizedVertexCount * 2) : undefined;
var threshold = 20;
var height;
var i, n;
var u, v;
for (i = 0, n = 0; i < quantizedVertexCount; ++i, n += 2) {
var texCoords = encoding.decodeTextureCoordinates(parentVertices, i, decodeTexCoordsScratch);
height = encoding.decodeHeight(parentVertices, i) / exaggeration;
u = _Math.CesiumMath.clamp((texCoords.x * maxShort) | 0, 0, maxShort);
v = _Math.CesiumMath.clamp((texCoords.y * maxShort) | 0, 0, maxShort);
parentHeightBuffer[i] = _Math.CesiumMath.clamp((((height - parentMinimumHeight) / (parentMaximumHeight - parentMinimumHeight)) * maxShort) | 0, 0, maxShort);
if (u < threshold) {
u = 0;
}
if (v < threshold) {
v = 0;
}
if (maxShort - u < threshold) {
u = maxShort;
}
if (maxShort - v < threshold) {
v = maxShort;
}
parentUBuffer[i] = u;
parentVBuffer[i] = v;
if (hasVertexNormals) {
var encodedNormal = encoding.getOctEncodedNormal(parentVertices, i, octEncodedNormalScratch);
parentNormalBuffer[n] = encodedNormal.x;
parentNormalBuffer[n + 1] = encodedNormal.y;
}
if ((isEastChild && u >= halfMaxShort || !isEastChild && u <= halfMaxShort) &&
(isNorthChild && v >= halfMaxShort || !isNorthChild && v <= halfMaxShort)) {
vertexMap[i] = vertexCount;
uBuffer.push(u);
vBuffer.push(v);
heightBuffer.push(parentHeightBuffer[i]);
if (hasVertexNormals) {
normalBuffer.push(parentNormalBuffer[n]);
normalBuffer.push(parentNormalBuffer[n + 1]);
}
++vertexCount;
}
}
var triangleVertices = [];
triangleVertices.push(new Vertex());
triangleVertices.push(new Vertex());
triangleVertices.push(new Vertex());
var clippedTriangleVertices = [];
clippedTriangleVertices.push(new Vertex());
clippedTriangleVertices.push(new Vertex());
clippedTriangleVertices.push(new Vertex());
var clippedIndex;
var clipped2;
for (i = 0; i < parentIndices.length; i += 3) {
var i0 = parentIndices[i];
var i1 = parentIndices[i + 1];
var i2 = parentIndices[i + 2];
var u0 = parentUBuffer[i0];
var u1 = parentUBuffer[i1];
var u2 = parentUBuffer[i2];
triangleVertices[0].initializeIndexed(parentUBuffer, parentVBuffer, parentHeightBuffer, parentNormalBuffer, i0);
triangleVertices[1].initializeIndexed(parentUBuffer, parentVBuffer, parentHeightBuffer, parentNormalBuffer, i1);
triangleVertices[2].initializeIndexed(parentUBuffer, parentVBuffer, parentHeightBuffer, parentNormalBuffer, i2);
// Clip triangle on the east-west boundary.
var clipped = Intersections2D.clipTriangleAtAxisAlignedThreshold(halfMaxShort, isEastChild, u0, u1, u2, clipScratch);
// Get the first clipped triangle, if any.
clippedIndex = 0;
if (clippedIndex >= clipped.length) {
continue;
}
clippedIndex = clippedTriangleVertices[0].initializeFromClipResult(clipped, clippedIndex, triangleVertices);
if (clippedIndex >= clipped.length) {
continue;
}
clippedIndex = clippedTriangleVertices[1].initializeFromClipResult(clipped, clippedIndex, triangleVertices);
if (clippedIndex >= clipped.length) {
continue;
}
clippedIndex = clippedTriangleVertices[2].initializeFromClipResult(clipped, clippedIndex, triangleVertices);
// Clip the triangle against the North-south boundary.
clipped2 = Intersections2D.clipTriangleAtAxisAlignedThreshold(halfMaxShort, isNorthChild, clippedTriangleVertices[0].getV(), clippedTriangleVertices[1].getV(), clippedTriangleVertices[2].getV(), clipScratch2);
addClippedPolygon(uBuffer, vBuffer, heightBuffer, normalBuffer, indices, vertexMap, clipped2, clippedTriangleVertices, hasVertexNormals);
// If there's another vertex in the original clipped result,
// it forms a second triangle. Clip it as well.
if (clippedIndex < clipped.length) {
clippedTriangleVertices[2].clone(clippedTriangleVertices[1]);
clippedTriangleVertices[2].initializeFromClipResult(clipped, clippedIndex, triangleVertices);
clipped2 = Intersections2D.clipTriangleAtAxisAlignedThreshold(halfMaxShort, isNorthChild, clippedTriangleVertices[0].getV(), clippedTriangleVertices[1].getV(), clippedTriangleVertices[2].getV(), clipScratch2);
addClippedPolygon(uBuffer, vBuffer, heightBuffer, normalBuffer, indices, vertexMap, clipped2, clippedTriangleVertices, hasVertexNormals);
}
}
var uOffset = isEastChild ? -maxShort : 0;
var vOffset = isNorthChild ? -maxShort : 0;
var westIndices = [];
var southIndices = [];
var eastIndices = [];
var northIndices = [];
var minimumHeight = Number.MAX_VALUE;
var maximumHeight = -minimumHeight;
var cartesianVertices = verticesScratch;
cartesianVertices.length = 0;
var ellipsoid = Cartesian2.Ellipsoid.clone(parameters.ellipsoid);
var rectangle = Cartesian2.Rectangle.clone(parameters.childRectangle);
var north = rectangle.north;
var south = rectangle.south;
var east = rectangle.east;
var west = rectangle.west;
if (east < west) {
east += _Math.CesiumMath.TWO_PI;
}
for (i = 0; i < uBuffer.length; ++i) {
u = Math.round(uBuffer[i]);
if (u <= minU) {
westIndices.push(i);
u = 0;
} else if (u >= maxU) {
eastIndices.push(i);
u = maxShort;
} else {
u = u * 2 + uOffset;
}
uBuffer[i] = u;
v = Math.round(vBuffer[i]);
if (v <= minV) {
southIndices.push(i);
v = 0;
} else if (v >= maxV) {
northIndices.push(i);
v = maxShort;
} else {
v = v * 2 + vOffset;
}
vBuffer[i] = v;
height = _Math.CesiumMath.lerp(parentMinimumHeight, parentMaximumHeight, heightBuffer[i] / maxShort);
if (height < minimumHeight) {
minimumHeight = height;
}
if (height > maximumHeight) {
maximumHeight = height;
}
heightBuffer[i] = height;
cartographicScratch.longitude = _Math.CesiumMath.lerp(west, east, u / maxShort);
cartographicScratch.latitude = _Math.CesiumMath.lerp(south, north, v / maxShort);
cartographicScratch.height = height;
ellipsoid.cartographicToCartesian(cartographicScratch, cartesian3Scratch);
cartesianVertices.push(cartesian3Scratch.x);
cartesianVertices.push(cartesian3Scratch.y);
cartesianVertices.push(cartesian3Scratch.z);
}
var boundingSphere = BoundingSphere.BoundingSphere.fromVertices(cartesianVertices, Cartesian2.Cartesian3.ZERO, 3, boundingSphereScratch);
var orientedBoundingBox = OrientedBoundingBox.OrientedBoundingBox.fromRectangle(rectangle, minimumHeight, maximumHeight, ellipsoid, orientedBoundingBoxScratch);
var occluder = new TerrainEncoding.EllipsoidalOccluder(ellipsoid);
var horizonOcclusionPoint = occluder.computeHorizonCullingPointFromVerticesPossiblyUnderEllipsoid(boundingSphere.center, cartesianVertices, 3, boundingSphere.center, minimumHeight, horizonOcclusionPointScratch);
var heightRange = maximumHeight - minimumHeight;
var vertices = new Uint16Array(uBuffer.length + vBuffer.length + heightBuffer.length);
for (i = 0; i < uBuffer.length; ++i) {
vertices[i] = uBuffer[i];
}
var start = uBuffer.length;
for (i = 0; i < vBuffer.length; ++i) {
vertices[start + i] = vBuffer[i];
}
start += vBuffer.length;
for (i = 0; i < heightBuffer.length; ++i) {
vertices[start + i] = maxShort * (heightBuffer[i] - minimumHeight) / heightRange;
}
var indicesTypedArray = IndexDatatype.IndexDatatype.createTypedArray(uBuffer.length, indices);
var encodedNormals;
if (hasVertexNormals) {
var normalArray = new Uint8Array(normalBuffer);
transferableObjects.push(vertices.buffer, indicesTypedArray.buffer, normalArray.buffer);
encodedNormals = normalArray.buffer;
} else {
transferableObjects.push(vertices.buffer, indicesTypedArray.buffer);
}
return {
vertices : vertices.buffer,
encodedNormals : encodedNormals,
indices : indicesTypedArray.buffer,
minimumHeight : minimumHeight,
maximumHeight : maximumHeight,
westIndices : westIndices,
southIndices : southIndices,
eastIndices : eastIndices,
northIndices : northIndices,
boundingSphere : boundingSphere,
orientedBoundingBox : orientedBoundingBox,
horizonOcclusionPoint : horizonOcclusionPoint
};
}
function Vertex() {
this.vertexBuffer = undefined;
this.index = undefined;
this.first = undefined;
this.second = undefined;
this.ratio = undefined;
}
Vertex.prototype.clone = function(result) {
if (!when.defined(result)) {
result = new Vertex();
}
result.uBuffer = this.uBuffer;
result.vBuffer = this.vBuffer;
result.heightBuffer = this.heightBuffer;
result.normalBuffer = this.normalBuffer;
result.index = this.index;
result.first = this.first;
result.second = this.second;
result.ratio = this.ratio;
return result;
};
Vertex.prototype.initializeIndexed = function(uBuffer, vBuffer, heightBuffer, normalBuffer, index) {
this.uBuffer = uBuffer;
this.vBuffer = vBuffer;
this.heightBuffer = heightBuffer;
this.normalBuffer = normalBuffer;
this.index = index;
this.first = undefined;
this.second = undefined;
this.ratio = undefined;
};
Vertex.prototype.initializeFromClipResult = function(clipResult, index, vertices) {
var nextIndex = index + 1;
if (clipResult[index] !== -1) {
vertices[clipResult[index]].clone(this);
} else {
this.vertexBuffer = undefined;
this.index = undefined;
this.first = vertices[clipResult[nextIndex]];
++nextIndex;
this.second = vertices[clipResult[nextIndex]];
++nextIndex;
this.ratio = clipResult[nextIndex];
++nextIndex;
}
return nextIndex;
};
Vertex.prototype.getKey = function() {
if (this.isIndexed()) {
return this.index;
}
return JSON.stringify({
first : this.first.getKey(),
second : this.second.getKey(),
ratio : this.ratio
});
};
Vertex.prototype.isIndexed = function() {
return when.defined(this.index);
};
Vertex.prototype.getH = function() {
if (when.defined(this.index)) {
return this.heightBuffer[this.index];
}
return _Math.CesiumMath.lerp(this.first.getH(), this.second.getH(), this.ratio);
};
Vertex.prototype.getU = function() {
if (when.defined(this.index)) {
return this.uBuffer[this.index];
}
return _Math.CesiumMath.lerp(this.first.getU(), this.second.getU(), this.ratio);
};
Vertex.prototype.getV = function() {
if (when.defined(this.index)) {
return this.vBuffer[this.index];
}
return _Math.CesiumMath.lerp(this.first.getV(), this.second.getV(), this.ratio);
};
var encodedScratch = new Cartesian2.Cartesian2();
// An upsampled triangle may be clipped twice before it is assigned an index
// In this case, we need a buffer to handle the recursion of getNormalX() and getNormalY().
var depth = -1;
var cartesianScratch1 = [new Cartesian2.Cartesian3(), new Cartesian2.Cartesian3()];
var cartesianScratch2 = [new Cartesian2.Cartesian3(), new Cartesian2.Cartesian3()];
function lerpOctEncodedNormal(vertex, result) {
++depth;
var first = cartesianScratch1[depth];
var second = cartesianScratch2[depth];
first = AttributeCompression.AttributeCompression.octDecode(vertex.first.getNormalX(), vertex.first.getNormalY(), first);
second = AttributeCompression.AttributeCompression.octDecode(vertex.second.getNormalX(), vertex.second.getNormalY(), second);
cartesian3Scratch = Cartesian2.Cartesian3.lerp(first, second, vertex.ratio, cartesian3Scratch);
Cartesian2.Cartesian3.normalize(cartesian3Scratch, cartesian3Scratch);
AttributeCompression.AttributeCompression.octEncode(cartesian3Scratch, result);
--depth;
return result;
}
Vertex.prototype.getNormalX = function() {
if (when.defined(this.index)) {
return this.normalBuffer[this.index * 2];
}
encodedScratch = lerpOctEncodedNormal(this, encodedScratch);
return encodedScratch.x;
};
Vertex.prototype.getNormalY = function() {
if (when.defined(this.index)) {
return this.normalBuffer[this.index * 2 + 1];
}
encodedScratch = lerpOctEncodedNormal(this, encodedScratch);
return encodedScratch.y;
};
var polygonVertices = [];
polygonVertices.push(new Vertex());
polygonVertices.push(new Vertex());
polygonVertices.push(new Vertex());
polygonVertices.push(new Vertex());
function addClippedPolygon(uBuffer, vBuffer, heightBuffer, normalBuffer, indices, vertexMap, clipped, triangleVertices, hasVertexNormals) {
if (clipped.length === 0) {
return;
}
var numVertices = 0;
var clippedIndex = 0;
while (clippedIndex < clipped.length) {
clippedIndex = polygonVertices[numVertices++].initializeFromClipResult(clipped, clippedIndex, triangleVertices);
}
for (var i = 0; i < numVertices; ++i) {
var polygonVertex = polygonVertices[i];
if (!polygonVertex.isIndexed()) {
var key = polygonVertex.getKey();
if (when.defined(vertexMap[key])) {
polygonVertex.newIndex = vertexMap[key];
} else {
var newIndex = uBuffer.length;
uBuffer.push(polygonVertex.getU());
vBuffer.push(polygonVertex.getV());
heightBuffer.push(polygonVertex.getH());
if (hasVertexNormals) {
normalBuffer.push(polygonVertex.getNormalX());
normalBuffer.push(polygonVertex.getNormalY());
}
polygonVertex.newIndex = newIndex;
vertexMap[key] = newIndex;
}
} else {
polygonVertex.newIndex = vertexMap[polygonVertex.index];
polygonVertex.uBuffer = uBuffer;
polygonVertex.vBuffer = vBuffer;
polygonVertex.heightBuffer = heightBuffer;
if (hasVertexNormals) {
polygonVertex.normalBuffer = normalBuffer;
}
}
}
if (numVertices === 3) {
// A triangle.
indices.push(polygonVertices[0].newIndex);
indices.push(polygonVertices[1].newIndex);
indices.push(polygonVertices[2].newIndex);
} else if (numVertices === 4) {
// A quad - two triangles.
indices.push(polygonVertices[0].newIndex);
indices.push(polygonVertices[1].newIndex);
indices.push(polygonVertices[2].newIndex);
indices.push(polygonVertices[0].newIndex);
indices.push(polygonVertices[2].newIndex);
indices.push(polygonVertices[3].newIndex);
}
}
var upsampleQuantizedTerrainMesh$1 = createTaskProcessorWorker(upsampleQuantizedTerrainMesh);
return upsampleQuantizedTerrainMesh$1;
});
| 412 | 0.800312 | 1 | 0.800312 | game-dev | MEDIA | 0.153151 | game-dev | 0.504014 | 1 | 0.504014 |
0xgen0/ethernal | 4,361 | contracts/test/balance.js | const {assert} = require('chai');
const {ethers} = require('@nomiclabs/buidler');
const {BigNumber} = require('ethers');
const {
coordinatesToLocation,
bfs,
path,
isLocation,
getRing,
monsterLevel,
generateXp,
generateCoins,
kills,
range,
generateKeys,
share,
} = require('../../backend/src/game/utils');
const {
bossChance,
} = require('../../backend/src/data/utils');
const {
setupContracts,
forceMove,
randomMove,
randomWalk,
expectError,
characterCoordinates,
waitFor,
zeroAddress,
} = require('../lib');
describe('Balance', function () {
const maxLevel = 10;
let pure;
before(async function () {
await setupContracts();
pure = await ethers.getContract('ReadOnlyDungeon');
});
it('ring', async function () {
assert.equal(
Number(await pure.getRing(coordinatesToLocation('0,0'), coordinatesToLocation('100,0'))),
getRing('100,0'),
);
});
it('monster level', async function () {
const level = 3;
const levelWidth = 25;
const coordinates = levelWidth * level + ',0';
const levelRing =
Number(await pure.getRing(coordinatesToLocation('0,0'), coordinatesToLocation(coordinates))) / levelWidth;
assert.equal(levelRing, level);
});
it('big boss spawnrate', async function () {
const levels = {};
for (let i = 0; i < maxLevel; i++) {
levels[i] = bossChance(i);
}
console.table(levels);
});
it('level up requirements', async function () {
const levels = {};
for (let i = 0; i <= maxLevel; i++) {
const {xpRequired, coinsRequired, hpIncrease} = await pure.toLevelUp(i);
levels[i] = {xpRequired, coinsRequired: Number(coinsRequired), hpIncrease};
}
console.table(levels);
assert.equal(levels[8].xpRequired, 1269);
assert.equal(levels[8].coinsRequired, 153);
assert.equal(levels[8].hpIncrease, 10);
});
it('kills', async function () {
const levels = {};
for (let i = 0; i <= maxLevel; i++) {
levels[i] = {
trash: kills(i),
'mini boss': kills(i, 'mini boss'),
'big boss': kills(i, 'big boss'),
};
}
console.table(levels);
assert.equal(levels[8].trash, 32);
assert.equal(levels[8]['mini boss'], 10);
});
it('range', async function () {
const results = [];
for (let i = 0; i < 10000; i++) {
results.push(range(10));
}
const average = Math.round(results.reduce((a, b) => a + b) / results.length);
assert.equal(average, 10);
});
it('generates xp', async function () {
const levels = {};
for (let i = 0; i <= maxLevel - 1; i++) {
levels[i] = {
trash: generateXp(i, 'trash', true),
'mini boss': generateXp(i, 'mini boss', true),
'big boss': generateXp(i, 'big boss', true),
'trash (range)': generateXp(i),
'mini boss (range)': generateXp(i, 'mini boss'),
'big boss (range)': generateXp(i, 'big boss'),
};
}
console.table(levels);
assert.equal(levels[8].trash, 10.3828125);
});
it('generates coins', async function () {
const levels = {};
for (let i = 0; i <= maxLevel - 1; i++) {
levels[i] = {
trash: generateCoins(i, 'trash', true),
'mini boss': generateCoins(i, 'mini boss', true),
'big boss': generateCoins(i, 'big boss', true),
'trash (range)': generateCoins(i),
'mini boss (range)': generateCoins(i, 'mini boss'),
'big boss (range)': generateCoins(i, 'big boss'),
};
}
console.table(levels);
assert.equal(levels[0].trash, 0.82);
assert.equal(levels[8].trash, 4.80625);
});
it('generates keys', async function () {
let keys = 0;
for (let i = 0; i <= 1000 - 1; i++) {
keys += generateKeys();
}
assert.equal(Math.round(keys / 100), 4);
});
it('rewards room discovery', async function () {
const levelWidth = 25;
const levels = {};
for (let i = 0; i <= maxLevel * 5 - 1; i++) {
const coordinates = '0,' + i * levelWidth;
const {numGold, numElements} = await pure.computeRoomDiscoveryReward(
coordinatesToLocation(coordinates),
'0x0000000000000000000000000000000000000000000000000000000000000000',
0,
);
levels[i] = {coordinates, gold: Number(numGold), elements: Number(numElements)};
}
console.table(levels);
});
});
| 412 | 0.709868 | 1 | 0.709868 | game-dev | MEDIA | 0.539456 | game-dev | 0.835943 | 1 | 0.835943 |
TechReborn/TechReborn | 2,482 | src/main/java/techreborn/blockentity/storage/energy/HighVoltageSUBlockEntity.java | /*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 TechReborn
*
* 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 techreborn.blockentity.storage.energy;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos;
import reborncore.common.powerSystem.RcEnergyTier;
import reborncore.common.screen.BuiltScreenHandler;
import reborncore.common.screen.BuiltScreenHandlerProvider;
import reborncore.common.screen.builder.ScreenHandlerBuilder;
import techreborn.init.TRBlockEntities;
import techreborn.init.TRContent;
/**
* Created by modmuss50 on 14/03/2016.
*/
public class HighVoltageSUBlockEntity extends EnergyStorageBlockEntity implements BuiltScreenHandlerProvider {
/**
* MFSU should store 40M Energy with 512 E/t I/O
*/
public HighVoltageSUBlockEntity(BlockPos pos, BlockState state) {
super(TRBlockEntities.HIGH_VOLTAGE_SU, pos, state, "HIGH_VOLTAGE_SU", 2, TRContent.Machine.HIGH_VOLTAGE_SU.block, RcEnergyTier.HIGH, 40_000_000);
}
@Override
public BuiltScreenHandler createScreenHandler(int syncID, final PlayerEntity player) {
return new ScreenHandlerBuilder("mfsu").player(player.getInventory()).inventory().hotbar().armor()
.complete(8, 18).addArmor().addInventory().blockEntity(this).energySlot(0, 62, 45).energySlot(1, 98, 45)
.syncEnergyValue().addInventory().create(this, syncID);
}
}
| 412 | 0.741085 | 1 | 0.741085 | game-dev | MEDIA | 0.985969 | game-dev | 0.737261 | 1 | 0.737261 |
locationtech/geogig | 4,660 | src/storage/temporary-rocksdb/src/main/java/org/locationtech/geogig/tempstorage/rocksdb/RocksdbDAGStorageProvider.java | /* Copyright (c) 2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan - initial implementation
*/
package org.locationtech.geogig.tempstorage.rocksdb;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.eclipse.jdt.annotation.Nullable;
import org.locationtech.geogig.base.Preconditions;
import org.locationtech.geogig.model.Node;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.model.internal.DAG;
import org.locationtech.geogig.model.internal.DAGNode;
import org.locationtech.geogig.model.internal.DAGStorageProvider;
import org.locationtech.geogig.model.internal.NodeId;
import org.locationtech.geogig.model.internal.TreeId;
import org.locationtech.geogig.storage.ObjectStore;
import org.rocksdb.RocksDB;
import com.google.common.base.Throwables;
class RocksdbDAGStorageProvider implements DAGStorageProvider {
private final ObjectStore objectStore;
private Path directory;
private RocksdbHandle dagDb, nodeDb;
private final RocksdbNodeStore nodeStore;
private final RocksdbDAGStore dagStore;
public RocksdbDAGStorageProvider(ObjectStore source) {
this.objectStore = source;
this.dagStore = new RocksdbDAGStore(this::getOrCreateDagDb);
this.nodeStore = new RocksdbNodeStore(this::getOrCreateNodeDb);
}
private RocksDB getOrCreateNodeDb() {
if (nodeDb == null) {
nodeDb = createDb("node");
}
return nodeDb.db;
}
private RocksDB getOrCreateDagDb() {
if (dagDb == null) {
dagDb = createDb("dag");
}
return nodeDb.db;
}
private synchronized RocksdbHandle createDb(String name) {
try {
if (directory == null) {
directory = Files.createTempDirectory("geogig-tmp-tree-store");
}
Path dbdir = directory.resolve(name);
RocksdbHandle db = RocksdbHandle.create(dbdir);
return db;
} catch (Exception e) {
RocksdbHandle.delete(directory.toFile());
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
public @Override void dispose() {
if (nodeStore != null) {
nodeStore.close();
}
if (dagStore != null) {
dagStore.close();
}
close(dagDb);
close(nodeDb);
if (directory != null) {
RocksdbHandle.delete(directory.toFile());
}
}
private void close(RocksdbHandle handle) {
if (handle != null) {
handle.dispose();
}
}
public @Override DAG getTree(TreeId id) throws NoSuchElementException {
return dagStore.getTree(id);
}
public @Override List<DAG> getTrees(List<TreeId> ids) throws NoSuchElementException {
return dagStore.getTrees(ids);
}
public @Override DAG getOrCreateTree(TreeId treeId, ObjectId originalTreeId) {
return dagStore.getOrCreateTree(treeId, originalTreeId);
}
public @Override void save(DAG dag) {
save(Collections.singletonList(dag));
}
public @Override void save(List<DAG> dags) {
dagStore.save(dags);
}
public @Override Node getNode(NodeId nodeId) {
DAGNode dagNode = nodeStore.get(nodeId);
Preconditions.checkState(dagNode != null);
return dagNode.resolve(objectStore);
}
public @Override Map<NodeId, Node> getNodes(final Set<NodeId> nodeIds) {
Map<NodeId, DAGNode> dagNodes = nodeStore.getAll(nodeIds);
Map<NodeId, Node> res = new HashMap<>();
dagNodes.forEach((id, node) -> res.put(id, node.resolve(objectStore)));
return res;
}
public @Override void saveNode(NodeId nodeId, DAGNode node) {
nodeStore.put(nodeId, node);
}
public @Override void saveNode(NodeId nodeId, Node node) {
nodeStore.put(nodeId, DAGNode.of(node));
}
public @Override void saveNodes(Map<NodeId, DAGNode> nodeMappings) {
nodeStore.putAll(nodeMappings);
}
@Nullable
public @Override RevTree getTree(ObjectId originalId) {
return objectStore.getTree(originalId);
}
}
| 412 | 0.93881 | 1 | 0.93881 | game-dev | MEDIA | 0.401963 | game-dev | 0.947757 | 1 | 0.947757 |
MagmaGuy/EliteMobs | 12,674 | src/main/java/com/magmaguy/elitemobs/api/PlayerDamagedByEliteMobEvent.java | package com.magmaguy.elitemobs.api;
import com.magmaguy.elitemobs.adventurersguild.GuildRank;
import com.magmaguy.elitemobs.collateralminecraftchanges.PlayerDeathMessageByEliteMob;
import com.magmaguy.elitemobs.config.MobCombatSettingsConfig;
import com.magmaguy.elitemobs.entitytracker.EntityTracker;
import com.magmaguy.elitemobs.mobconstructor.EliteEntity;
import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity;
import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties;
import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory;
import com.magmaguy.elitemobs.utils.EventCaller;
import com.magmaguy.magmacore.util.AttributeManager;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
public class PlayerDamagedByEliteMobEvent extends EliteDamageEvent {
private static final HandlerList handlers = new HandlerList();
private final Entity entity;
private final EliteEntity eliteEntity;
private final Player player;
private final EntityDamageByEntityEvent entityDamageByEntityEvent;
private final Projectile projectile;
public PlayerDamagedByEliteMobEvent(EliteEntity eliteEntity, Player player, EntityDamageByEntityEvent event, Projectile projectile, double damage) {
super(damage, event);
this.entity = event.getEntity();
this.eliteEntity = eliteEntity;
this.player = player;
this.entityDamageByEntityEvent = event;
this.projectile = projectile;
}
public static HandlerList getHandlerList() {
return handlers;
}
public Entity getEntity() {
return this.entity;
}
public EliteEntity getEliteMobEntity() {
return this.eliteEntity;
}
public Player getPlayer() {
return this.player;
}
public Projectile getProjectile() {
return projectile;
}
public EntityDamageByEntityEvent getEntityDamageByEntityEvent() {
return this.entityDamageByEntityEvent;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
//Thing that launches the event
public static class PlayerDamagedByEliteMobEventFilter implements Listener {
@Getter
@Setter
private static boolean bypass = false;
@Getter
@Setter
private static double specialMultiplier = 1;
private static double eliteToPlayerDamageFormula(Player player, EliteEntity eliteEntity, EntityDamageByEntityEvent event) {
double baseDamage = EliteMobProperties.getBaselineDamage(eliteEntity.getLivingEntity().getType(), eliteEntity);
//Case for creeper and ghast explosions
if (eliteEntity.getLivingEntity() != null && player.isValid() && player.getLocation().getWorld().equals(eliteEntity.getLivingEntity().getWorld()))
if (eliteEntity.getLivingEntity().getType().equals(EntityType.CREEPER)) {
Creeper creeper = (Creeper) eliteEntity.getLivingEntity();
double distance = player.getLocation().distance(eliteEntity.getLivingEntity().getLocation());
double distanceAttenuation = 1 - distance / creeper.getExplosionRadius();
distanceAttenuation = distanceAttenuation < 0 ? 0 : distanceAttenuation;
baseDamage *= distanceAttenuation;
} else if (eliteEntity.getLivingEntity().getType().equals(EntityType.GHAST) &&
event.getDamager().getType().equals(EntityType.FIREBALL)) {
double distance = player.getLocation().distance(eliteEntity.getLivingEntity().getLocation());
double distanceAttenuation = 1 - distance / ((Fireball) event.getDamager()).getYield();
distanceAttenuation = distanceAttenuation < 0 ? 0 : distanceAttenuation;
baseDamage *= distanceAttenuation;
}
double bonusDamage = eliteEntity.getLevel() * .5; //A .5 increase in damage for every level the mob has
ElitePlayerInventory elitePlayerInventory = ElitePlayerInventory.getPlayer(player);
if (elitePlayerInventory == null) return 0;
//Bosses now gain .5 damage per level instead of 1 damage per level to make fight against high level and low level mobs more lenient
double damageReduction = elitePlayerInventory.getEliteDefense(true) * 0.5;
if (event.getDamager() instanceof AbstractArrow)
damageReduction += elitePlayerInventory.getEliteProjectileProtection(true);
if (event.getDamager() instanceof Fireball || event.getDamager() instanceof Creeper) {
damageReduction += elitePlayerInventory.getEliteBlastProtection(true);
}
double customBossDamageMultiplier = eliteEntity.getDamageMultiplier();
double potionEffectDamageReduction = 0;
if (player.hasPotionEffect(PotionEffectType.RESISTANCE))
potionEffectDamageReduction = (player.getPotionEffect(PotionEffectType.RESISTANCE).
getAmplifier() + 1) * MobCombatSettingsConfig.getResistanceDamageMultiplier();
double finalDamage;
if (eliteEntity instanceof CustomBossEntity customBossEntity && customBossEntity.isNormalizedCombat())
finalDamage = Math.max(baseDamage + bonusDamage - damageReduction - potionEffectDamageReduction, 1) *
customBossDamageMultiplier * specialMultiplier * MobCombatSettingsConfig.getNormalizedDamageToPlayerMultiplier();
else
finalDamage = Math.max(baseDamage + bonusDamage - damageReduction - potionEffectDamageReduction, 1) *
customBossDamageMultiplier * specialMultiplier * MobCombatSettingsConfig.getDamageToPlayerMultiplier();
if (specialMultiplier != 1) specialMultiplier = 1;
double playerMaxHealth = AttributeManager.getAttributeBaseValue(player,"generic_max_health");
//Prevent 1-shots
finalDamage = Math.min(finalDamage, playerMaxHealth - 1);
return finalDamage;
}
//Remove potion effects of creepers when they blow up because Minecraft passes those effects to players, and they are infinite
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
private void explosionEvent(EntityExplodeEvent event) {
if (event.getEntity().getType().equals(EntityType.CREEPER) && EntityTracker.isEliteMob(event.getEntity())) {
//by default minecraft spreads potion effects
Set<PotionEffect> potionEffects = new HashSet<>(((Creeper) event.getEntity()).getActivePotionEffects());
potionEffects.forEach(potionEffectType -> ((Creeper) event.getEntity()).removePotionEffect(potionEffectType.getType()));
}
}
@EventHandler
public void onEliteDamagePlayer(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
bypass = false;
if (!(event.getDamager() instanceof Explosive))
return;
}
if (!(event.getEntity() instanceof Player player)) return;
//citizens
if (player.hasMetadata("NPC") || ElitePlayerInventory.getPlayer(player) == null)
return;
Projectile projectile = null;
EliteEntity eliteEntity = null;
if (event.getDamager() instanceof LivingEntity)
eliteEntity = EntityTracker.getEliteMobEntity(event.getDamager());
else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) {
eliteEntity = EntityTracker.getEliteMobEntity((LivingEntity) ((Projectile) event.getDamager()).getShooter());
projectile = (Projectile) event.getDamager();
} else if (event.getDamager().getType().equals(EntityType.EVOKER_FANGS))
if (((EvokerFangs) event.getDamager()).getOwner() != null)
eliteEntity = EntityTracker.getEliteMobEntity(((EvokerFangs) event.getDamager()).getOwner());
if (eliteEntity == null || eliteEntity.getLivingEntity() == null) return;
//By this point, it is guaranteed that this kind of damage should have custom EliteMobs behavior
//dodge chance
if (ThreadLocalRandom.current().nextDouble() < GuildRank.dodgeBonusValue(GuildRank.getGuildPrestigeRank(player), GuildRank.getActiveGuildRank(player)) / 100) {
player.sendTitle(" ", "Dodged!");
event.setCancelled(true);
return;
}
boolean blocking = false;
//Blocking reduces melee damage and nullifies most ranged damage at the cost of shield durability
if (player.isBlocking()) {
blocking = true;
if (player.getInventory().getItemInOffHand().getType().equals(Material.SHIELD)) {
ItemMeta itemMeta = player.getInventory().getItemInOffHand().getItemMeta();
org.bukkit.inventory.meta.Damageable damageable = (Damageable) itemMeta;
if (player.getInventory().getItemInOffHand().getItemMeta().hasEnchant(Enchantment.UNBREAKING) &&
player.getInventory().getItemInOffHand().getItemMeta().getEnchantLevel(Enchantment.UNBREAKING) / 20D > ThreadLocalRandom.current().nextDouble())
damageable.setDamage(damageable.getDamage() + 5);
player.getInventory().getItemInOffHand().setItemMeta(itemMeta);
if (Material.SHIELD.getMaxDurability() < damageable.getDamage())
player.getInventory().setItemInOffHand(null);
}
if (event.getDamager() instanceof Projectile) {
bypass = false;
event.getDamager().remove();
return;
}
}
//Calculate the damage for the event
double newDamage = eliteToPlayerDamageFormula(player, eliteEntity, event);
//Blocking reduces damage by 80%
if (blocking)
newDamage = newDamage - newDamage * MobCombatSettingsConfig.getBlockingDamageReduction();
//nullify vanilla reductions
for (EntityDamageEvent.DamageModifier modifier : EntityDamageByEntityEvent.DamageModifier.values())
if (event.isApplicable(modifier) && modifier != EntityDamageEvent.DamageModifier.ABSORPTION)
event.setDamage(modifier, 0);
//Check if we should be doing raw damage, which some powers have
if (bypass) {
//Use raw damage in case of bypass
newDamage = event.getOriginalDamage(EntityDamageEvent.DamageModifier.BASE);
bypass = false;
}
//Run the event, see if it will get cancelled or suffer further damage modifications
PlayerDamagedByEliteMobEvent playerDamagedByEliteMobEvent = new PlayerDamagedByEliteMobEvent(eliteEntity, player, event, projectile, newDamage);
new EventCaller(playerDamagedByEliteMobEvent);
//In case damage got modified along the way
newDamage = playerDamagedByEliteMobEvent.getDamage();
if (playerDamagedByEliteMobEvent.isCancelled()) {
bypass = false;
return;
}
//Set the final damage value
event.setDamage(EntityDamageEvent.DamageModifier.BASE, newDamage);
//Deal with the player getting killed todo: this is a bit busted, fix
if (player.getHealth() - event.getDamage() <= 0)
PlayerDeathMessageByEliteMob.addDeadPlayer(player, PlayerDeathMessageByEliteMob.initializeDeathMessage(player, eliteEntity));
}
}
}
| 412 | 0.939551 | 1 | 0.939551 | game-dev | MEDIA | 0.944073 | game-dev | 0.960884 | 1 | 0.960884 |
ccnet/CruiseControl.NET | 3,370 | Playground/CruiseControl.Core/Triggers/Schedule.cs | namespace CruiseControl.Core.Triggers
{
using System;
using System.ComponentModel;
using CruiseControl.Core.Interfaces;
using Ninject;
/// <summary>
/// Triggers a build at a set time.
/// </summary>
public class Schedule
: Trigger
{
#region Private fields
private DateTime? nextTime;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Schedule"/> class.
/// </summary>
public Schedule()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Schedule"/> class.
/// </summary>
/// <param name="time">The time.</param>
public Schedule(TimeSpan time)
{
this.Time = time;
}
#endregion
#region Public properties
#region Time
/// <summary>
/// Gets or sets the time.
/// </summary>
/// <value>
/// The time.
/// </value>
public TimeSpan? Time { get; set; }
#endregion
#region NextTime
/// <summary>
/// Gets the time the trigger will next be tripped or checked to see if tripped.
/// </summary>
public override DateTime? NextTime
{
get { return this.nextTime; }
}
#endregion
#region Clock
/// <summary>
/// Gets or sets the clock.
/// </summary>
/// <value>
/// The clock.
/// </value>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Inject]
public IClock Clock { get; set; }
#endregion
#endregion
#region Public methods
#region Validate()
/// <summary>
/// Validates this trigger.
/// </summary>
/// <param name="validationLog">The validation log.</param>
public override void Validate(IValidationLog validationLog)
{
base.Validate(validationLog);
if (!this.Time.HasValue)
{
validationLog.AddError("No time set - trigger will not fire");
}
}
#endregion
#endregion
#region Protected methods
#region OnCheck()
/// <summary>
/// Called when the trigger needs to be checked.
/// </summary>
/// <returns>
/// An <see cref="IntegrationRequest"/> if tripped; <c>null</c> otherwise.
/// </returns>
protected override IntegrationRequest OnCheck()
{
if (this.Clock.Now < this.nextTime.Value)
{
return null;
}
return new IntegrationRequest(this.NameOrType);
}
#endregion
#region OnReset()
/// <summary>
/// Called when a reset needs to be performed.
/// </summary>
protected override void OnReset()
{
base.OnReset();
var timeToCheck = this.Clock.Today.Add(this.Time.Value);
if (timeToCheck <= this.Clock.Now)
{
timeToCheck = timeToCheck.AddDays(1);
}
this.nextTime = timeToCheck;
}
#endregion
#endregion
}
}
| 412 | 0.954673 | 1 | 0.954673 | game-dev | MEDIA | 0.582038 | game-dev | 0.939164 | 1 | 0.939164 |
The-Aether-Team/The-Aether-II | 8,277 | src/main/java/com/aetherteam/aetherii/block/dungeon/FungalCarpetBlock.java | package com.aetherteam.aetherii.block.dungeon;
import com.aetherteam.aetherii.block.AetherIIBlocks;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.mojang.serialization.MapCodec;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.MossyCarpetBlock;
import net.minecraft.world.level.block.MultifaceBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.level.block.state.properties.WallSide;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.BooleanSupplier;
public class FungalCarpetBlock extends MossyCarpetBlock {
public static final MapCodec<FungalCarpetBlock> CODEC = simpleCodec(FungalCarpetBlock::new);
public static final BooleanProperty BASE = BlockStateProperties.BOTTOM;
private static final EnumProperty<WallSide> NORTH = BlockStateProperties.NORTH_WALL;
private static final EnumProperty<WallSide> EAST = BlockStateProperties.EAST_WALL;
private static final EnumProperty<WallSide> SOUTH = BlockStateProperties.SOUTH_WALL;
private static final EnumProperty<WallSide> WEST = BlockStateProperties.WEST_WALL;
private static final ImmutableMap PROPERTY_BY_DIRECTION = ImmutableMap.copyOf(Util.make(Maps.newEnumMap(Direction.class), (map) -> {
map.put(Direction.NORTH, NORTH);
map.put(Direction.EAST, EAST);
map.put(Direction.SOUTH, SOUTH);
map.put(Direction.WEST, WEST);
}));
public FungalCarpetBlock(Properties properties) {
super(properties);
this.registerDefaultState(this.stateDefinition.any().setValue(BASE, true).setValue(NORTH, WallSide.NONE).setValue(EAST, WallSide.NONE).setValue(SOUTH, WallSide.NONE).setValue(WEST, WallSide.NONE));
}
private static BlockState getUpdatedState(BlockState state, BlockGetter blockGetter, BlockPos pos, boolean base) {
BlockState stateAbove = null;
BlockState stateBelow = null;
base |= state.getValue(BASE);
EnumProperty<WallSide> wallProperty;
WallSide wallSide;
for(Iterator<Direction> var6 = Direction.Plane.HORIZONTAL.iterator(); var6.hasNext(); state = state.setValue(wallProperty, wallSide)) {
Direction direction = var6.next();
wallProperty = getPropertyForFace(direction);
wallSide = canSupportAtFace(blockGetter, pos, direction) ? (base ? WallSide.LOW : state.getValue(wallProperty)) : WallSide.NONE;
if (wallSide == WallSide.LOW) {
if (stateAbove == null) {
stateAbove = blockGetter.getBlockState(pos.above());
}
if (stateAbove.is(AetherIIBlocks.FUNGAL_CARPET) && stateAbove.getValue(wallProperty) != WallSide.NONE && !(Boolean)stateAbove.getValue(BASE)) {
wallSide = WallSide.TALL;
}
if (!(Boolean)state.getValue(BASE)) {
if (stateBelow == null) {
stateBelow = blockGetter.getBlockState(pos.below());
}
if (stateBelow.is(AetherIIBlocks.FUNGAL_CARPET) && stateBelow.getValue(wallProperty) == WallSide.NONE) {
wallSide = WallSide.NONE;
}
}
}
}
return state;
}
@Override
@Nullable
public BlockState getStateForPlacement(BlockPlaceContext context) {
return getUpdatedState(this.defaultBlockState(), context.getLevel(), context.getClickedPos(), true);
}
public static void placeAt(LevelAccessor level, BlockPos pos, RandomSource random, int flags) {
BlockState state = AetherIIBlocks.FUNGAL_CARPET.get().defaultBlockState();
BlockState stateUpdated = getUpdatedState(state, level, pos, true);
level.setBlock(pos, stateUpdated, 3);
Objects.requireNonNull(random);
BlockState stateAbove = createTopperWithSideChance(level, pos, random::nextBoolean);
if (!stateAbove.isAir()) {
level.setBlock(pos.above(), stateAbove, flags);
}
}
@Override
public void setPlacedBy(Level level, BlockPos pos, BlockState state, @Nullable LivingEntity entity, ItemStack stack) {
if (!level.isClientSide) {
RandomSource randomsource = level.getRandom();
Objects.requireNonNull(randomsource);
BlockState stateAbove = createTopperWithSideChance(level, pos, randomsource::nextBoolean);
if (!stateAbove.isAir()) {
level.setBlock(pos.above(), stateAbove, 3);
}
}
}
private static BlockState createTopperWithSideChance(BlockGetter blockGetter, BlockPos pos, BooleanSupplier booleanSupplier) {
BlockPos posAbove = pos.above();
BlockState stateAbove = blockGetter.getBlockState(posAbove);
boolean flag = stateAbove.is(AetherIIBlocks.FUNGAL_CARPET.get());
if ((!flag || !(Boolean)stateAbove.getValue(BASE)) && (flag || stateAbove.canBeReplaced())) {
BlockState state = AetherIIBlocks.FUNGAL_CARPET.get().defaultBlockState().setValue(BASE, false);
BlockState stateUpdated = getUpdatedState(state, blockGetter, pos.above(), true);
for (Direction direction : Direction.Plane.HORIZONTAL) {
EnumProperty<WallSide> wallProperty = getPropertyForFace(direction);
if (stateUpdated.getValue(wallProperty) != WallSide.NONE && !booleanSupplier.getAsBoolean()) {
stateUpdated = stateUpdated.setValue(wallProperty, WallSide.NONE);
}
}
return hasFaces(stateUpdated) && stateUpdated != stateAbove ? stateUpdated : Blocks.AIR.defaultBlockState();
} else {
return Blocks.AIR.defaultBlockState();
}
}
@Override
protected BlockState updateShape(BlockState state, LevelReader level, ScheduledTickAccess tickAccess, BlockPos pos, Direction direction, BlockPos neighborPos, BlockState neighborState, RandomSource random) {
if (!state.canSurvive(level, pos)) {
return Blocks.AIR.defaultBlockState();
} else {
BlockState stateUpdated = getUpdatedState(state, level, pos, false);
return !hasFaces(stateUpdated) ? Blocks.AIR.defaultBlockState() : stateUpdated;
}
}
private static boolean hasFaces(BlockState state) {
if (!state.getValue(BASE)) {
Iterator var1 = PROPERTY_BY_DIRECTION.values().iterator();
EnumProperty wallProperty;
do {
if (!var1.hasNext()) {
return false;
}
wallProperty = (EnumProperty) var1.next();
} while (state.getValue(wallProperty) == WallSide.NONE);
}
return true;
}
private static boolean canSupportAtFace(BlockGetter blockGetter, BlockPos pos, Direction direction) {
return direction != Direction.UP && MultifaceBlock.canAttachTo(blockGetter, pos, direction);
}
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(BASE, NORTH, EAST, SOUTH, WEST);
}
@Override
public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) {
BlockState stateTop = createTopperWithSideChance(level, pos, () -> true);
if (!stateTop.isAir()) {
level.setBlock(pos.above(), stateTop, 3);
}
}
} | 412 | 0.860995 | 1 | 0.860995 | game-dev | MEDIA | 0.990377 | game-dev | 0.953229 | 1 | 0.953229 |
Interkarma/daggerfall-unity | 1,799 | Assets/Scripts/Game/MagicAndEffects/Effects/Restoration/HealPersonality.cs | // Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2023 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using DaggerfallConnect;
using DaggerfallConnect.Arena2;
namespace DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects
{
/// <summary>
/// Heal - Personality
/// </summary>
public class HealPersonality : HealEffect
{
public static readonly string EffectKey = "Heal-Personality";
public override void SetProperties()
{
properties.Key = EffectKey;
properties.ClassicKey = MakeClassicKey(10, 5);
properties.SupportMagnitude = true;
properties.AllowedTargets = EntityEffectBroker.TargetFlags_All;
properties.AllowedElements = EntityEffectBroker.ElementFlags_MagicOnly;
properties.AllowedCraftingStations = MagicCraftingStations.SpellMaker;
properties.MagicSkill = DFCareer.MagicSkills.Restoration;
properties.MagnitudeCosts = MakeEffectCosts(40, 28);
healStat = DFCareer.Stats.Personality;
}
public override string GroupName => TextManager.Instance.GetLocalizedText("heal");
public override string SubGroupName => TextManager.Instance.GetLocalizedText("personality");
public override TextFile.Token[] SpellMakerDescription => DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1545);
public override TextFile.Token[] SpellBookDescription => DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1245);
}
}
| 412 | 0.780877 | 1 | 0.780877 | game-dev | MEDIA | 0.821759 | game-dev | 0.876811 | 1 | 0.876811 |
TheMobyCollective/spyro-1 | 14,351 | src/hud.c | #include "hud.h"
#include "42CC4.h"
#include "camera.h"
#include "common.h"
#include "math.h"
#include "memory.h"
#include "overlay_pointers.h"
#include "variables.h"
void HudPrint(int pIdx, int pLen, int pValue, int pArg4) {
char buf[8];
char *end = buf;
int i;
// break the digits apart backwards ...
while (pValue != 0) {
*end = pValue % 10;
pValue = pValue / 10;
++end;
}
if (end == buf) {
buf[0] = 0;
end = buf + 1;
}
// build out the corresponding digit mobys
for (i = 0; i < pLen; ++i) {
if (end != buf) {
--end;
if (pArg4 == 0) {
g_Hud.m_Mobys[pIdx + i].m_Substate = *end;
} else {
g_Hud.m_Mobys[pIdx + i].m_Class = (*end & 0xFF) + MOBYCLASS_NUMBER_0;
g_Hud.m_Mobys[pIdx + i].m_RenderRadius = 0xFF;
}
} else {
if (pArg4 != 0) {
g_Hud.m_Mobys[pIdx + i].m_RenderRadius = 0;
}
}
}
}
void HudMoveMoby(int pIdx, int pLen, int pYOffset) {
int i;
for (i = 0; i < pLen; ++i) {
g_Hud.m_Mobys[pIdx + i].m_Position.y =
g_HudMobyTargetPos[pIdx + i].y + pYOffset;
}
}
void HudMoveEgg(int pIdx, int pLen, int pYOffset) {
int i;
for (i = 0; i < pLen; ++i) {
g_Hud.m_SpriteRect[pIdx + i].y = g_HudEggTargetRect[pIdx + i].y + pYOffset;
}
}
void HudMobyRotate(int pIdx, int pLen, int pZRot) {
int i;
for (i = 0; i < pLen; ++i) {
if (g_Hud.m_Mobys[pIdx + i].m_Rotation.z != 0 ||
g_Hud.m_Mobys[pIdx + i].m_Substate !=
g_Hud.m_Mobys[pIdx + i].m_Class - MOBYCLASS_NUMBER_0) {
g_Hud.m_Mobys[pIdx + i].m_Rotation.z = pZRot;
}
if (g_Hud.m_Mobys[pIdx + i].m_Substate != 0xFF && pZRot == 192) {
g_Hud.m_Mobys[pIdx + i].m_Class =
(g_Hud.m_Mobys[pIdx + i].m_Substate & 0xFF) + MOBYCLASS_NUMBER_0;
g_Hud.m_Mobys[pIdx + i].m_RenderRadius = 0xFF;
}
}
}
void HudGemUpdate(void) {
g_Hud.m_GemCount = g_LevelGemCount[D_80075964];
HudPrint(0, 4, g_Hud.m_GemCount, 1);
if (g_Hud.m_GemDisplayState == HDS_Opening ||
g_Hud.m_GemDisplayState == HDS_Open ||
g_Hud.m_GemDisplayState == HDS_Completed) {
g_Hud.m_GemDisplayState = HDS_Closing;
g_Hud.m_GemProgress = 13;
}
}
void HudReset(int pArg) {
int i;
Memset(g_Hud.m_Mobys, 0, sizeof(g_Hud.m_Mobys));
for (i = 0; i < 12; ++i) {
func_800529CC(&g_Hud.m_Mobys[i]);
VecCopy(&g_Hud.m_Mobys[i].m_Position, &g_HudMobyTargetPos[i]);
g_Hud.m_Mobys[i].m_DepthOffset = 32;
g_Hud.m_Mobys[i].m_RenderRadius = 0xFF;
g_Hud.m_Mobys[i].m_Substate = 0xFF;
g_Hud.m_Mobys[i].m_SpecularMetalType = 11;
}
Memset(g_Hud.m_SpriteRect, 0, sizeof(g_Hud.m_SpriteRect));
for (i = 0; i < 12; ++i) {
g_Hud.m_SpriteRect[i].x = g_HudEggTargetRect[i].x;
g_Hud.m_SpriteRect[i].y = g_HudEggTargetRect[i].y;
g_Hud.m_SpriteRect[i].w = g_HudEggTargetRect[i].w;
g_Hud.m_SpriteRect[i].h = g_HudEggTargetRect[i].h;
}
g_Hud.m_Mobys[4].m_Class = MOBYCLASS_HUD_GEM_CHEST;
g_Hud.m_Mobys[7].m_Class = MOBYCLASS_HUD_DRAGON;
g_Hud.m_Mobys[10].m_Class = MOBYCLASS_HUD_SPYRO_HEAD;
g_Hud.m_Mobys[11].m_Class = MOBYCLASS_HUD_KEY;
g_Hud.m_Mobys[11].m_Rotation.z = 64;
g_Hud.m_GemDisplayState = 1;
g_Hud.m_DragonDisplayState = 1;
g_Hud.m_LifeDisplayState = 1;
g_Hud.m_EggDisplayState = 1;
g_Hud.m_KeyDisplayState = 1;
g_Hud.m_GemProgress = 0;
g_Hud.m_DragonProgress = 0;
g_Hud.m_LifeProgress = 0;
g_Hud.m_EggProgress = 0;
g_Hud.m_KeyProgress = 0;
g_Hud.m_GemSteadyTicks = 0;
g_Hud.m_DragonSteadyTicks = 0;
g_Hud.m_LifeSteadyTicks = 0;
g_Hud.m_EggSteadyTicks = 0;
g_Hud.m_KeySteadyTicks = 0;
g_Hud.m_GemCount = g_LevelGemCount[D_80075964];
g_Hud.m_DragonCount = g_DragonTotal;
g_Hud.m_LifeCount = D_8007582C;
g_Hud.m_EggCount = g_EggTotal;
g_Hud.m_KeyFlag = D_80075830;
g_Hud.m_LifeOrbCount = D_800758E8;
HudPrint(0, 4, g_Hud.m_GemCount, 1);
HudPrint(5, 2, g_Hud.m_DragonCount, 1);
HudPrint(8, 2, g_Hud.m_LifeCount, 1);
if (pArg) {
g_Hud.D_80077FDC = 0;
for (i = 0; i < D_800758E8; ++i) {
g_Hud.m_SpriteRect[12 + i].x =
g_Hud.m_Mobys[10].m_Position.x + g_LifeOrbXYTarget[i].x - 29;
g_Hud.m_SpriteRect[12 + i].y =
g_Hud.m_Mobys[10].m_Position.y + g_LifeOrbXYTarget[i].y - 28;
g_Hud.m_SpriteRect[12 + i].w = 8;
g_Hud.m_SpriteRect[12 + i].h = 8;
}
}
}
inline static uint something_hud(int i) { return (0x6000000 + i * 0x1000000); }
void HudTick(void) {
int i;
int j;
Vector3D vec;
g_Hud.unk_0x3c = (g_Hud.unk_0x3c - g_DeltaTime) & 0xFF;
g_Hud.unk_0x40 = (g_Hud.unk_0x40 + 1) % 9;
g_Hud.m_Mobys[4].m_Rotation.y = COSINE_8(g_Hud.unk_0x3c) >> 9;
g_Hud.m_Mobys[4].m_Rotation.z = (u_char)g_Hud.unk_0x3c;
if (g_Hud.m_GemDisplayState == HDS_Hidden) {
if (g_Hud.m_GemCount != g_LevelGemCount[D_80075964]) {
g_Hud.m_GemDisplayState = HDS_Opening;
g_Hud.m_GemProgress = 0;
}
} else if (g_Hud.m_GemDisplayState == HDS_Opening) {
if (g_Hud.m_GemProgress == 13) {
g_Hud.m_GemDisplayState = HDS_Open;
g_Hud.m_GemProgress = 0;
g_Hud.m_GemSteadyTicks = 0;
if (g_Hud.m_GemCount == g_LevelGemCount[D_80075964]) {
g_Hud.m_GemSteadyTicks = -40;
}
} else {
HudMoveMoby(0, 5, g_HudOpeningOffsets[g_Hud.m_GemProgress++]);
}
} else if (g_Hud.m_GemDisplayState == HDS_Open) {
if (g_Hud.m_GemCount == g_LevelGemCount[D_80075964] &&
g_Hud.m_GemProgress == 0) {
g_Hud.m_GemSteadyTicks++;
if (g_Hud.m_GemSteadyTicks == 20) {
g_Hud.m_GemDisplayState = HDS_Closing;
g_Hud.m_GemProgress = 13;
}
} else {
g_Hud.m_GemSteadyTicks = 0;
if (g_LevelGemCount[D_80075964] - g_Hud.m_GemCount >= 3 &&
(g_Hud.m_GemProgress & 0x1F) == 0) {
g_Hud.m_GemProgress -= 0x20;
} else {
g_Hud.m_GemProgress -= 0x10;
}
HudPrint(0, 4, g_Hud.m_GemCount + 1, 0);
HudMobyRotate(0, 4, g_Hud.m_GemProgress);
if (g_LevelGemCount[D_80075964] - g_Hud.m_GemCount > 200) {
g_Hud.m_GemCount += 8;
} else if (g_LevelGemCount[D_80075964] - g_Hud.m_GemCount > 20 ||
g_Hud.m_GemProgress == 0xC0) {
g_Hud.m_GemCount += 1;
}
if (g_Hud.m_GemCount == g_TargetGemCounts[D_80075964] &&
g_Hud.m_GemProgress == 0) {
g_Hud.m_GemDisplayState = HDS_Completed;
}
}
} else if (g_Hud.m_GemDisplayState == HDS_Closing) {
if (g_Hud.m_GemCount != g_LevelGemCount[D_80075964]) {
g_Hud.m_GemDisplayState = HDS_Opening;
} else if (g_Hud.m_GemProgress == 0) {
g_Hud.m_GemDisplayState = HDS_Hidden;
} else {
HudMoveMoby(0, 5, g_HudClosingOffsets[--g_Hud.m_GemProgress]);
}
} else if (g_Hud.m_GemDisplayState == HDS_Completed) {
g_Hud.m_GemSteadyTicks += g_DeltaTime;
if (g_Hud.m_GemSteadyTicks >= 240) {
g_Hud.m_GemDisplayState = HDS_Closing;
g_Hud.m_GemProgress = 13;
}
}
g_Hud.m_Mobys[7].m_Substate += 8;
g_Hud.m_Mobys[7].m_Rotation.z =
COSINE_8(g_Hud.m_Mobys[7].m_Substate & 0xFF) >> 8;
if (g_Hud.m_DragonDisplayState == HDS_Opening) {
if (g_Hud.m_DragonProgress == 13) {
g_Hud.m_DragonDisplayState = HDS_Open;
g_Hud.m_DragonProgress = 0;
g_Hud.m_DragonSteadyTicks = -40;
} else {
HudMoveMoby(5, 3, g_HudOpeningOffsets[g_Hud.m_DragonProgress++]);
}
} else if (g_Hud.m_DragonDisplayState == HDS_Open) {
g_Hud.m_DragonSteadyTicks++;
if (g_Hud.m_DragonSteadyTicks == 20) {
g_Hud.m_DragonDisplayState = HDS_Closing;
g_Hud.m_DragonProgress = 13;
}
} else if (g_Hud.m_DragonDisplayState == HDS_Closing) {
if (g_Hud.m_DragonProgress == 0) {
g_Hud.m_DragonDisplayState = HDS_Hidden;
} else {
HudMoveMoby(5, 3, g_HudClosingOffsets[--g_Hud.m_DragonProgress]);
}
}
g_Hud.m_Mobys[10].m_Rotation.z = g_Hud.unk_0x3c & 0xFF;
if (g_Hud.m_LifeDisplayState == HDS_Hidden) {
if (g_Hud.m_LifeCount != D_8007582C || g_Hud.m_LifeOrbCount != D_800758E8) {
g_Hud.m_LifeDisplayState = HDS_Opening;
g_Hud.m_LifeProgress = 0;
}
} else if (g_Hud.m_LifeDisplayState == HDS_Opening) {
if (g_Hud.m_LifeProgress == 13) {
g_Hud.m_LifeDisplayState = HDS_Open;
g_Hud.m_LifeProgress = 0;
g_Hud.m_LifeSteadyTicks = 0;
if (g_Hud.m_LifeCount == D_8007582C &&
g_Hud.m_LifeOrbCount == D_800758E8) {
g_Hud.m_LifeSteadyTicks = -40;
}
} else {
HudMoveMoby(8, 3, g_HudOpeningOffsets[g_Hud.m_LifeProgress++]);
}
} else if (g_Hud.m_LifeDisplayState == HDS_Open) {
if (g_Hud.m_LifeCount == D_8007582C && g_Hud.m_LifeProgress == 0) {
if (g_Hud.m_LifeOrbCount == D_800758E8) {
g_Hud.m_LifeSteadyTicks += 1;
if (g_Hud.m_LifeSteadyTicks == 20) {
g_Hud.m_LifeDisplayState = HDS_Closing;
g_Hud.m_LifeProgress = 13;
}
} else {
g_Hud.m_LifeSteadyTicks = 0;
g_Hud.m_LifeOrbCount = D_800758E8;
}
} else {
g_Hud.m_LifeSteadyTicks = 0;
g_Hud.m_LifeProgress = g_Hud.m_LifeProgress - 16;
HudPrint(8, 2, g_Hud.m_LifeCount + 1, 0);
HudMobyRotate(8, 2, g_Hud.m_LifeProgress);
if (g_Hud.m_LifeProgress == 0xC0) {
g_Hud.m_LifeCount += 1;
}
}
} else if (g_Hud.m_LifeDisplayState == HDS_Closing) {
if (g_Hud.m_LifeCount != D_8007582C || g_Hud.m_LifeOrbCount != D_800758E8) {
g_Hud.m_LifeDisplayState = HDS_Opening;
g_Hud.m_LifeOrbCount = D_800758E8;
} else if (g_Hud.m_LifeProgress == 0) {
g_Hud.m_LifeDisplayState = HDS_Hidden;
} else {
HudMoveMoby(8, 3, g_HudClosingOffsets[--g_Hud.m_LifeProgress]);
}
}
for (i = 0; i < g_Hud.m_LifeOrbCount; ++i) {
g_Hud.m_SpriteRect[12 + i].x =
g_Hud.m_Mobys[10].m_Position.x + g_LifeOrbXYTarget[i].x - 29;
g_Hud.m_SpriteRect[12 + i].y =
g_Hud.m_Mobys[10].m_Position.y + g_LifeOrbXYTarget[i].y - 28;
g_Hud.m_SpriteRect[12 + i].w = 8;
g_Hud.m_SpriteRect[12 + i].h = 8;
}
switch (g_Hud.m_EggDisplayState) {
case HDS_Hidden: {
if (g_Hud.m_EggCount != g_EggTotal || g_Hud.D_80077FDC != 0) {
g_Hud.m_EggDisplayState = HDS_Opening;
g_Hud.m_EggProgress = 0;
}
break;
}
case HDS_Opening: {
if (g_Hud.m_EggProgress == 13) {
g_Hud.m_EggDisplayState = HDS_Open;
g_Hud.m_EggSteadyTicks = 0;
if (g_Hud.m_EggCount == g_EggTotal && g_Hud.D_80077FDC == 0) {
g_Hud.m_EggSteadyTicks = -40;
}
} else {
HudMoveEgg(0, 12, -g_HudOpeningOffsets[g_Hud.m_EggProgress++]);
}
break;
}
case HDS_Open: {
if (g_Hud.m_EggCount == g_EggTotal) {
if (g_Hud.D_80077FDC != 0) {
g_Hud.m_EggSteadyTicks = 0;
} else {
if (g_Hud.m_EggSteadyTicks == 20) {
g_Hud.m_EggDisplayState = HDS_Closing;
g_Hud.m_EggProgress = 13;
}
}
} else if (g_Hud.m_EggSteadyTicks == 1) {
vec.x = g_Hud.m_EggCount * 324 - 2500;
vec.y = 1008;
vec.z = 4096;
(*D_800758E4)(16, 77, &vec, nullptr);
} else if (g_Hud.m_EggSteadyTicks > 8) {
g_Hud.m_EggCount += 1;
g_Hud.m_EggSteadyTicks = 0;
}
g_Hud.m_EggSteadyTicks += 1;
break;
}
case HDS_Closing: {
if (g_Hud.m_EggCount != g_EggTotal || g_Hud.D_80077FDC != 0) {
g_Hud.m_EggDisplayState = HDS_Opening;
} else if (g_Hud.m_EggProgress == 0) {
g_Hud.m_EggDisplayState = HDS_Hidden;
} else {
HudMoveEgg(0, 12, -g_HudClosingOffsets[--g_Hud.m_EggProgress]);
}
break;
}
}
if (D_80075830 != 1)
g_Hud.m_KeyFlag = D_80075830;
switch (g_Hud.m_KeyDisplayState) {
case HDS_Hidden: {
if (g_Hud.m_KeyFlag != D_80075830) {
g_Hud.m_KeyDisplayState = HDS_Opening;
g_Hud.m_KeyProgress = 0;
}
break;
}
case HDS_Opening: {
if (g_Hud.m_KeyProgress == 13) {
g_Hud.m_KeyDisplayState = HDS_Open;
g_Hud.m_KeySteadyTicks = 0;
if (g_Hud.m_KeyFlag == D_80075830) {
g_Hud.m_KeySteadyTicks = -40;
}
} else {
HudMoveMoby(11, 1, -g_HudOpeningOffsets[g_Hud.m_KeyProgress++]);
}
break;
}
case HDS_Open: {
if (g_Hud.m_KeyFlag != D_80075830) {
if (g_Hud.m_KeySteadyTicks == 0) {
for (j = 0; j < 6; ++j) {
(*D_800758E4)(1, 12, &g_Hud.m_Mobys[11].m_Props,
(void *)(something_hud(j) + 0x8080));
}
} else if (g_Hud.m_KeySteadyTicks > 11) {
g_Hud.m_Mobys[11].m_Substate = 64;
g_Hud.m_KeySteadyTicks = 0;
g_Hud.m_KeyFlag = D_80075830;
}
} else if (g_Hud.m_KeySteadyTicks == 20) {
g_Hud.m_KeyDisplayState = HDS_Closing;
g_Hud.m_KeyProgress = 13;
}
g_Hud.m_KeySteadyTicks += 1;
break;
}
case HDS_Closing: {
if (g_Hud.m_KeyFlag != D_80075830) {
g_Hud.m_KeyDisplayState = HDS_Opening;
g_Hud.m_KeyProgress = 0;
} else if (g_Hud.m_KeyProgress == 0) {
g_Hud.m_KeyDisplayState = HDS_Hidden;
} else {
HudMoveMoby(11, 1, -g_HudClosingOffsets[--g_Hud.m_KeyProgress]);
}
break;
}
}
g_Hud.m_Mobys[11].m_Substate += 4;
g_Hud.m_Mobys[11].m_Rotation.x = COSINE_8(g_Hud.m_Mobys[11].m_Substate) >> 7;
g_Hud.m_Mobys[11].m_Rotation.y = SINE_8(g_Hud.m_Mobys[11].m_Substate) >> 7;
if (D_800758E8 > 19) {
D_8007582C++;
if (D_8007582C > 99)
D_8007582C = 99;
D_800758E8 -= 20;
}
}
void GenerateGemCollectMobys(int pGemValue, Moby *pGemPos) {
int i = 1;
int moby_x = pGemPos->m_Position.x;
int moby_y = pGemPos->m_Position.y;
Vector3D16 vec;
setXYZ(&vec, Cos(g_Camera.m_Rotation.z - 0x400) >> 8,
Sin(g_Camera.m_Rotation.z - 0x400) >> 8, 128);
for (; pGemValue != 0; pGemValue /= 10, i *= 10) {
MobyNumberProps *props;
int rem = (pGemValue % 10);
Moby *pMoby = (*g_SpawnMoby)(rem + MOBYCLASS_NUMBER_0, nullptr);
setXYZ(&pMoby->m_Position, moby_x, moby_y, pGemPos->m_Position.z);
setXYZ(&pMoby->m_Rotation, 0, 0, g_Camera.m_Rotation.z >> 4);
props = pMoby->m_Props;
setXYZ(&props->unk_0x8, vec.x, vec.y, vec.z);
props->unk_0x4 = rem * i;
// this FIXED_MUL may not be exactly what they are getting at, but it
// matches
moby_x -= FIXED_MUL(SINE_8(pMoby->m_Rotation.z), 256);
moby_y += FIXED_MUL(COSINE_8(pMoby->m_Rotation.z), 256);
vec.z -= 16;
}
}
| 412 | 0.703216 | 1 | 0.703216 | game-dev | MEDIA | 0.878093 | game-dev | 0.803103 | 1 | 0.803103 |
OpenZeppelin/cairo-contracts | 6,632 | docs/modules/ROOT/pages/security.adoc | = Security
The following documentation provides context, reasoning, and examples of modules found under `openzeppelin_security`.
CAUTION: Expect these modules to evolve.
== Initializable
The xref:api/security.adoc#InitializableComponent[Initializable] component provides a simple mechanism that mimics
the functionality of a constructor.
More specifically, it enables logic to be performed once and only once which is useful to set up a contract's initial state when a constructor cannot be used, for example when there are circular dependencies at construction time.
=== Usage
You can use the component in your contracts like this:
[,cairo]
----
#[starknet::contract]
mod MyInitializableContract {
use openzeppelin_security::InitializableComponent;
component!(path: InitializableComponent, storage: initializable, event: InitializableEvent);
impl InternalImpl = InitializableComponent::InternalImpl<ContractState>;
#[storage]
struct Storage {
#[substorage(v0)]
initializable: InitializableComponent::Storage,
param: felt252
}
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
#[flat]
InitializableEvent: InitializableComponent::Event
}
fn initializer(ref self: ContractState, some_param: felt252) {
// Makes the method callable only once
self.initializable.initialize();
// Initialization logic
self.param.write(some_param);
}
}
----
CAUTION: This Initializable pattern should only be used in one function.
=== Interface
The component provides the following external functions as part of the `InitializableImpl` implementation:
[,cairo]
----
#[starknet::interface]
pub trait InitializableABI {
fn is_initialized() -> bool;
}
----
== Pausable
:assert_not_paused: xref:api/security.adoc#PausableComponent-assert_not_paused[assert_not_paused]
:assert_paused: xref:api/security.adoc#PausableComponent-assert_paused[assert_paused]
The xref:api/security.adoc#PausableComponent[Pausable] component allows contracts to implement an emergency stop mechanism.
This can be useful for scenarios such as preventing trades until the end of an evaluation period or having an emergency switch to freeze all transactions in the event of a large bug.
To become pausable, the contract should include `pause` and `unpause` functions (which should be protected).
For methods that should be available only when paused or not, insert calls to `{assert_paused}` and `{assert_not_paused}`
respectively.
=== Usage
For example (using the xref:api/access.adoc#OwnableComponent[Ownable] component for access control):
[,cairo]
----
#[starknet::contract]
mod MyPausableContract {
use openzeppelin_access::ownable::OwnableComponent;
use openzeppelin_security::PausableComponent;
use starknet::ContractAddress;
component!(path: OwnableComponent, storage: ownable, event: OwnableEvent);
component!(path: PausableComponent, storage: pausable, event: PausableEvent);
// Ownable Mixin
#[abi(embed_v0)]
impl OwnableMixinImpl = OwnableComponent::OwnableMixinImpl<ContractState>;
impl OwnableInternalImpl = OwnableComponent::InternalImpl<ContractState>;
// Pausable
#[abi(embed_v0)]
impl PausableImpl = PausableComponent::PausableImpl<ContractState>;
impl PausableInternalImpl = PausableComponent::InternalImpl<ContractState>;
#[storage]
struct Storage {
#[substorage(v0)]
ownable: OwnableComponent::Storage,
#[substorage(v0)]
pausable: PausableComponent::Storage
}
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
#[flat]
OwnableEvent: OwnableComponent::Event,
#[flat]
PausableEvent: PausableComponent::Event
}
#[constructor]
fn constructor(ref self: ContractState, owner: ContractAddress) {
self.ownable.initializer(owner);
}
#[external(v0)]
fn pause(ref self: ContractState) {
self.ownable.assert_only_owner();
self.pausable.pause();
}
#[external(v0)]
fn unpause(ref self: ContractState) {
self.ownable.assert_only_owner();
self.pausable.unpause();
}
#[external(v0)]
fn when_not_paused(ref self: ContractState) {
self.pausable.assert_not_paused();
// Do something
}
#[external(v0)]
fn when_paused(ref self: ContractState) {
self.pausable.assert_paused();
// Do something
}
}
----
=== Interface
The component provides the following external functions as part of the `PausableImpl` implementation:
[,cairo]
----
#[starknet::interface]
pub trait PausableABI {
fn is_paused() -> bool;
}
----
== Reentrancy Guard
:start: xref:api/security.adoc#ReentrancyGuardComponent-start[start]
:end: xref:api/security.adoc#ReentrancyGuardComponent-end[end]
A https://gus-tavo-guim.medium.com/reentrancy-attack-on-smart-contracts-how-to-identify-the-exploitable-and-an-example-of-an-attack-4470a2d8dfe4[reentrancy attack] occurs when the caller is able to obtain more resources than allowed by recursively calling a target's function.
=== Usage
Since Cairo does not support modifiers like Solidity, the xref:api/security.adoc#ReentrancyGuardComponent[ReentrancyGuard]
component exposes two methods `{start}` and `{end}` to protect functions against reentrancy attacks.
The protected function must call `start` before the first function statement, and `end` before the return statement, as shown below:
[,cairo]
----
#[starknet::contract]
mod MyReentrancyContract {
use openzeppelin_security::ReentrancyGuardComponent;
component!(
path: ReentrancyGuardComponent, storage: reentrancy_guard, event: ReentrancyGuardEvent
);
impl InternalImpl = ReentrancyGuardComponent::InternalImpl<ContractState>;
#[storage]
struct Storage {
#[substorage(v0)]
reentrancy_guard: ReentrancyGuardComponent::Storage
}
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
#[flat]
ReentrancyGuardEvent: ReentrancyGuardComponent::Event
}
#[external(v0)]
fn protected_function(ref self: ContractState) {
self.reentrancy_guard.start();
// Do something
self.reentrancy_guard.end();
}
#[external(v0)]
fn another_protected_function(ref self: ContractState) {
self.reentrancy_guard.start();
// Do something
self.reentrancy_guard.end();
}
}
----
NOTE: The guard prevents the execution flow occurring inside `protected_function`
to call itself or `another_protected_function`, and vice versa. | 412 | 0.940555 | 1 | 0.940555 | game-dev | MEDIA | 0.421895 | game-dev,security-crypto | 0.866724 | 1 | 0.866724 |
DeltaV-Station/Delta-v | 3,406 | Content.Client/Fluids/PuddleSystem.cs | using Content.Client.IconSmoothing;
using Content.Shared.Chemistry.Components;
using Content.Shared.Fluids;
using Content.Shared.Fluids.Components;
using Robust.Client.GameObjects;
using Robust.Shared.Map;
namespace Content.Client.Fluids;
public sealed class PuddleSystem : SharedPuddleSystem
{
[Dependency] private readonly IconSmoothSystem _smooth = default!;
[Dependency] private readonly SpriteSystem _sprite = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PuddleComponent, AppearanceChangeEvent>(OnPuddleAppearance);
}
private void OnPuddleAppearance(EntityUid uid, PuddleComponent component, ref AppearanceChangeEvent args)
{
if (args.Sprite == null)
return;
var volume = 1f;
if (args.AppearanceData.TryGetValue(PuddleVisuals.CurrentVolume, out var volumeObj))
{
volume = (float)volumeObj;
}
// Update smoothing and sprite based on volume.
if (TryComp<IconSmoothComponent>(uid, out var smooth))
{
if (volume < LowThreshold)
{
_sprite.LayerSetRsiState((uid, args.Sprite), 0, $"{smooth.StateBase}a");
_smooth.SetEnabled(uid, false, smooth);
}
else if (volume < MediumThreshold)
{
_sprite.LayerSetRsiState((uid, args.Sprite), 0, $"{smooth.StateBase}b");
_smooth.SetEnabled(uid, false, smooth);
}
else
{
if (!smooth.Enabled)
{
_sprite.LayerSetRsiState((uid, args.Sprite), 0, $"{smooth.StateBase}0");
_smooth.SetEnabled(uid, true, smooth);
_smooth.DirtyNeighbours(uid);
}
}
}
var baseColor = Color.White;
if (args.AppearanceData.TryGetValue(PuddleVisuals.SolutionColor, out var colorObj))
{
var color = (Color)colorObj;
_sprite.SetColor((uid, args.Sprite), color * baseColor);
}
else
{
_sprite.SetColor((uid, args.Sprite), args.Sprite.Color * baseColor);
}
}
#region Spill
// Maybe someday we'll have clientside prediction for entity spawning, but not today.
// Until then, these methods do nothing on the client.
/// <inheritdoc/>
public override bool TrySplashSpillAt(EntityUid uid, EntityCoordinates coordinates, Solution solution, out EntityUid puddleUid, bool sound = true, EntityUid? user = null)
{
puddleUid = EntityUid.Invalid;
return false;
}
/// <inheritdoc/>
public override bool TrySpillAt(EntityCoordinates coordinates, Solution solution, out EntityUid puddleUid, bool sound = true)
{
puddleUid = EntityUid.Invalid;
return false;
}
/// <inheritdoc/>
public override bool TrySpillAt(EntityUid uid, Solution solution, out EntityUid puddleUid, bool sound = true, TransformComponent? transformComponent = null)
{
puddleUid = EntityUid.Invalid;
return false;
}
/// <inheritdoc/>
public override bool TrySpillAt(TileRef tileRef, Solution solution, out EntityUid puddleUid, bool sound = true, bool tileReact = true)
{
puddleUid = EntityUid.Invalid;
return false;
}
#endregion Spill
}
| 412 | 0.915438 | 1 | 0.915438 | game-dev | MEDIA | 0.963438 | game-dev | 0.970444 | 1 | 0.970444 |
Team-Pepsi/pepsimod | 19,584 | src/main/java/net/daporkchop/pepsimod/module/impl/misc/HUDMod.java | /*
* Adapted from The MIT License (MIT)
*
* Copyright (c) 2016-2020 DaPorkchop_
*
* 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:
*
* Any persons and/or organizations using this software must include the above copyright notice and this permission notice,
* provide sufficient credit to the original authors of the project (IE: DaPorkchop_), as well as provide a link to the original project.
*
* 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 net.daporkchop.pepsimod.module.impl.misc;
import net.daporkchop.pepsimod.Pepsimod;
import net.daporkchop.pepsimod.misc.TickRate;
import net.daporkchop.pepsimod.module.ModuleCategory;
import net.daporkchop.pepsimod.module.ModuleManager;
import net.daporkchop.pepsimod.module.api.Module;
import net.daporkchop.pepsimod.module.api.ModuleOption;
import net.daporkchop.pepsimod.module.api.OptionCompletions;
import net.daporkchop.pepsimod.module.api.option.ExtensionSlider;
import net.daporkchop.pepsimod.module.api.option.ExtensionType;
import net.daporkchop.pepsimod.util.PepsiUtils;
import net.daporkchop.pepsimod.util.ReflectionStuff;
import net.daporkchop.pepsimod.util.colors.rainbow.RainbowText;
import net.daporkchop.pepsimod.util.config.impl.GeneralTranslator;
import net.daporkchop.pepsimod.util.config.impl.HUDTranslator;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.GuiIngame;
import net.minecraft.item.ItemStack;
import java.awt.Color;
public class HUDMod extends Module {
public static HUDMod INSTANCE;
public String serverBrand = "";
{
INSTANCE = this;
}
public HUDMod(boolean isEnabled, int key) {
super(isEnabled, "HUD", key, true);
}
@Override
public void onEnable() {
}
@Override
public void onDisable() {
}
@Override
public boolean shouldTick() {
return true;
}
@Override
public void tick() {
for (Module module : ModuleManager.ENABLED_MODULES) {
module.updateName();
}
ModuleManager.sortModules(GeneralTranslator.INSTANCE.sortType);
}
@Override
public void init() {
INSTANCE = this;
}
@Override
public ModuleOption[] getDefaultOptions() {
return new ModuleOption[]{
new ModuleOption<>(HUDTranslator.INSTANCE.drawLogo, "draw_logo", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.drawLogo = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.drawLogo;
}, "Watermark"),
new ModuleOption<>(HUDTranslator.INSTANCE.arrayList, "arraylist", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.arrayList = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.arrayList;
}, "ArrayList"),
new ModuleOption<>(HUDTranslator.INSTANCE.TPS, "tps", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.TPS = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.TPS;
}, "TPS"),
new ModuleOption<>(HUDTranslator.INSTANCE.coords, "coords", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.coords = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.coords;
}, "Coords"),
new ModuleOption<>(HUDTranslator.INSTANCE.netherCoords, "nether_coords", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.netherCoords = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.netherCoords;
}, "NetherCoords"),
new ModuleOption<>(HUDTranslator.INSTANCE.arrayListTop, "arraylist_top", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.arrayListTop = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.arrayListTop;
}, "ArrayListOnTop"),
new ModuleOption<>(HUDTranslator.INSTANCE.serverBrand, "server_brand", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.serverBrand = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.serverBrand;
}, "ServerBrand"),
new ModuleOption<>(HUDTranslator.INSTANCE.rainbow, "rainbow", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.rainbow = value;
for (Module module : ModuleManager.AVALIBLE_MODULES) {
module.updateName();
}
return true;
},
() -> {
return HUDTranslator.INSTANCE.rainbow;
}, "Rainbow"),
new ModuleOption<>(HUDTranslator.INSTANCE.direction, "direction", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.direction = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.direction;
}, "Direction"),
new ModuleOption<>(HUDTranslator.INSTANCE.armor, "armor", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.armor = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.armor;
}, "Armor"),
new ModuleOption<>(HUDTranslator.INSTANCE.effects, "effects", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.effects = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.effects;
}, "Effects"),
new ModuleOption<>(HUDTranslator.INSTANCE.fps, "fps", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.fps = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.fps;
}, "FPS"),
new ModuleOption<>(HUDTranslator.INSTANCE.ping, "ping", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.ping = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.ping;
}, "Ping"),
new ModuleOption<>(HUDTranslator.INSTANCE.clampTabList, "clampTabList", OptionCompletions.BOOLEAN,
(value) -> {
HUDTranslator.INSTANCE.clampTabList = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.clampTabList;
}, "Clamp Tab List"),
new ModuleOption<>(HUDTranslator.INSTANCE.maxTabRows, "maxTabRows", OptionCompletions.INTEGER,
(value) -> {
HUDTranslator.INSTANCE.maxTabRows = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.maxTabRows;
}, "Max Tab Rows", new ExtensionSlider(ExtensionType.VALUE_INT, 1, 80, 1)),
/*new ModuleOption<>(HUDTranslator.INSTANCE.maxTabCols, "maxTabCols", OptionCompletions.INTEGER,
(value) -> {
HUDTranslator.INSTANCE.maxTabCols = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.maxTabCols;
}, "Max Tab Cols", new ExtensionSlider(ExtensionType.VALUE_INT, 0, 15, 1)),*/
new ModuleOption<>(HUDTranslator.INSTANCE.r, "r", new String[]{"0", "128", "255"},
(value) -> {
HUDTranslator.INSTANCE.r = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.r;
}, "Red", new ExtensionSlider(ExtensionType.VALUE_INT, 0, 255, 1)),
new ModuleOption<>(HUDTranslator.INSTANCE.g, "g", new String[]{"0", "128", "255"},
(value) -> {
HUDTranslator.INSTANCE.g = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.g;
}, "Green", new ExtensionSlider(ExtensionType.VALUE_INT, 0, 255, 1)),
new ModuleOption<>(HUDTranslator.INSTANCE.b, "b", new String[]{"0", "128", "255"},
(value) -> {
HUDTranslator.INSTANCE.b = value;
return true;
},
() -> {
return HUDTranslator.INSTANCE.b;
}, "Blue", new ExtensionSlider(ExtensionType.VALUE_INT, 0, 255, 1))
};
}
public ModuleCategory getCategory() {
return ModuleCategory.MISC;
}
public void registerKeybind(String name, int key) {
}
@Override
public void onRenderGUI(float partialTicks, int width, int height, GuiIngame gui) {
if (HUDTranslator.INSTANCE.drawLogo) {
if (HUDTranslator.INSTANCE.rainbow) {
PepsiUtils.PEPSI_NAME.drawAtPos(gui, 2, 2, 0);
} else {
HUDTranslator.INSTANCE.bindColor();
mc.fontRenderer.drawString(Pepsimod.NAME_VERSION, 2, 2, HUDTranslator.INSTANCE.getColor(), true);
}
}
if (HUDTranslator.INSTANCE.arrayList) {
if (HUDTranslator.INSTANCE.arrayListTop) {
for (int i = 0, j = 0; i < ModuleManager.ENABLED_MODULES.size(); i++) {
Module module = ModuleManager.ENABLED_MODULES.get(i);
if (module.state.hidden) {
continue;
}
if (HUDTranslator.INSTANCE.rainbow) {
if (module.text instanceof RainbowText) {
((RainbowText) module.text).drawAtPos(gui, width - 2 - module.text.width(), 2 + j * 10, ++j * 10);
} else {
module.text.drawAtPos(gui, width - 2 - module.text.width(), 2 + ++j * 10);
}
} else {
HUDTranslator.INSTANCE.bindColor();
mc.fontRenderer.drawString(module.text.getRawText(), width - 2 - module.text.width(), 2 + j * 10, HUDTranslator.INSTANCE.getColor());
j++;
}
}
} else {
int j = mc.currentScreen instanceof GuiChat ? 14 : 0;
for (int i = 0; i < ModuleManager.ENABLED_MODULES.size(); i++) {
Module module = ModuleManager.ENABLED_MODULES.get(i);
if (module.state.hidden) {
continue;
}
if (HUDTranslator.INSTANCE.rainbow) {
if (module.text instanceof RainbowText) {
((RainbowText) module.text).drawAtPos(gui, width - 2 - module.text.width(), height - (j += 10), j / 10 * 8);
} else {
module.text.drawAtPos(gui, width - 2 - module.text.width(), height - (j += 10));
}
} else {
HUDTranslator.INSTANCE.bindColor();
mc.fontRenderer.drawString(module.text.getRawText(), width - 2 - module.text.width(), height - (j += 10), HUDTranslator.INSTANCE.getColor());
}
}
}
}
int i = 0;
if (HUDTranslator.INSTANCE.arrayListTop) {
i = mc.currentScreen instanceof GuiChat ? 14 : 0;
if (HUDTranslator.INSTANCE.serverBrand) {
String text = PepsiUtils.COLOR_ESCAPE + "7Server brand: " + PepsiUtils.COLOR_ESCAPE + "r" + HUDMod.INSTANCE.serverBrand;
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("Server brand: " + HUDMod.INSTANCE.serverBrand) + 2), height - 2 - (i += 10), Color.white.getRGB());
}
if (HUDTranslator.INSTANCE.ping) {
try {
int ping = mc.getConnection().getPlayerInfo(mc.getConnection().getGameProfile().getId()).getResponseTime();
String text = PepsiUtils.COLOR_ESCAPE + "7Ping: " + PepsiUtils.COLOR_ESCAPE + "r" + ping;
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("Ping: " + ping) + 2), height - 2 - (i += 10), Color.white.getRGB());
} catch (NullPointerException e) {
}
}
if (HUDTranslator.INSTANCE.TPS) {
String text = PepsiUtils.COLOR_ESCAPE + "7TPS: " + PepsiUtils.COLOR_ESCAPE + "r" + TickRate.TPS;
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("TPS: " + TickRate.TPS) + 2), height - 2 - (i += 10), Color.white.getRGB());
}
if (HUDTranslator.INSTANCE.fps) {
String text = PepsiUtils.COLOR_ESCAPE + "7FPS: " + PepsiUtils.COLOR_ESCAPE + "r" + ReflectionStuff.getDebugFps();
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("FPS: " + ReflectionStuff.getDebugFps()) + 2), height - 2 - (i += 10), Color.white.getRGB());
}
} else {
if (HUDTranslator.INSTANCE.serverBrand) {
String text = PepsiUtils.COLOR_ESCAPE + "7Server brand: " + PepsiUtils.COLOR_ESCAPE + "r" + HUDMod.INSTANCE.serverBrand;
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("Server brand: " + HUDMod.INSTANCE.serverBrand) + 2), 2 + i++ * 10, Color.white.getRGB());
}
if (HUDTranslator.INSTANCE.ping) {
try {
int ping = mc.getConnection().getPlayerInfo(mc.getConnection().getGameProfile().getId()).getResponseTime();
String text = PepsiUtils.COLOR_ESCAPE + "7Ping: " + PepsiUtils.COLOR_ESCAPE + "r" + ping;
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("Ping: " + ping) + 2), 2 + i++ * 10, Color.white.getRGB());
} catch (NullPointerException e) {
}
}
if (HUDTranslator.INSTANCE.TPS) {
String text = PepsiUtils.COLOR_ESCAPE + "7TPS: " + PepsiUtils.COLOR_ESCAPE + "r" + TickRate.TPS;
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("TPS: " + TickRate.TPS) + 2), 2 + i++ * 10, Color.white.getRGB());
}
if (HUDTranslator.INSTANCE.fps) {
String text = PepsiUtils.COLOR_ESCAPE + "7FPS: " + PepsiUtils.COLOR_ESCAPE + "r" + ReflectionStuff.getDebugFps();
gui.drawString(mc.fontRenderer, text, width - (mc.fontRenderer.getStringWidth("FPS: " + ReflectionStuff.getDebugFps()) + 2), 2 + i++ * 10, Color.white.getRGB());
}
}
i = mc.currentScreen instanceof GuiChat ? 14 : 0;
if (HUDTranslator.INSTANCE.coords) {
String toRender = PepsiUtils.COLOR_ESCAPE + "7XYZ" + PepsiUtils.COLOR_ESCAPE + "f: " + PepsiUtils.COLOR_ESCAPE + "7" + PepsiUtils.roundCoords(mc.player.posX) + "" + PepsiUtils.COLOR_ESCAPE + "f, " + PepsiUtils.COLOR_ESCAPE + "7" + PepsiUtils.roundCoords(mc.player.posY) + "" + PepsiUtils.COLOR_ESCAPE + "f, " + PepsiUtils.COLOR_ESCAPE + "7" + PepsiUtils.roundCoords(mc.player.posZ);
if (HUDTranslator.INSTANCE.netherCoords && mc.player.dimension != 1) {
toRender += " " + PepsiUtils.COLOR_ESCAPE + "f(" + PepsiUtils.COLOR_ESCAPE + "7" + PepsiUtils.roundCoords(PepsiUtils.getDimensionCoord(mc.player.posX)) + "" + PepsiUtils.COLOR_ESCAPE + "f, " + PepsiUtils.COLOR_ESCAPE + "7" + PepsiUtils.roundCoords(mc.player.posY) + "" + PepsiUtils.COLOR_ESCAPE + "f, " + PepsiUtils.COLOR_ESCAPE + "7" + PepsiUtils.roundCoords(PepsiUtils.getDimensionCoord(mc.player.posZ)) + "" + PepsiUtils.COLOR_ESCAPE + "f)";
}
mc.fontRenderer.drawString(toRender, 2, height - (i += 10), Color.white.getRGB(), true);
}
if (HUDTranslator.INSTANCE.direction) {
mc.fontRenderer.drawString(PepsiUtils.COLOR_ESCAPE + "7[" + PepsiUtils.COLOR_ESCAPE + "f" + PepsiUtils.getFacing() + PepsiUtils.COLOR_ESCAPE + "7]", 2, height - (i += 10), Color.white.getRGB(), true);
}
if (HUDTranslator.INSTANCE.armor) {
i = 0;
int xPos = width / 2;
xPos -= 90;
for (int j = 0; j < 4; j++) {
ItemStack stack = PepsiUtils.getWearingArmor(j);
PepsiUtils.renderItem(xPos + 20 * i++, height - 70, partialTicks, mc.player, stack);
}
}
}
}
| 412 | 0.765526 | 1 | 0.765526 | game-dev | MEDIA | 0.762176 | game-dev | 0.866064 | 1 | 0.866064 |
rfresh2/ZenithProxy | 11,292 | src/main/java/com/zenith/command/impl/SpectatorCommand.java | package com.zenith.command.impl;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.zenith.Proxy;
import com.zenith.command.api.Command;
import com.zenith.command.api.CommandCategory;
import com.zenith.command.api.CommandContext;
import com.zenith.command.api.CommandUsage;
import com.zenith.discord.Embed;
import com.zenith.feature.spectator.SpectatorEntityRegistry;
import com.zenith.feature.spectator.entity.SpectatorEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.mojang.brigadier.arguments.StringArgumentType.*;
import static com.zenith.Globals.CONFIG;
import static com.zenith.Globals.PLAYER_LISTS;
import static com.zenith.command.api.CommandOutputHelper.playerListToString;
import static com.zenith.command.brigadier.ToggleArgumentType.getToggle;
import static com.zenith.command.brigadier.ToggleArgumentType.toggle;
import static com.zenith.discord.DiscordBot.escape;
public class SpectatorCommand extends Command {
@Override
public CommandUsage commandUsage() {
return CommandUsage.builder()
.name("spectator")
.category(CommandCategory.CORE)
.description("""
Configures the Spectator feature.
The spectator whitelist only allows players to join as spectators.
Players who are regular whitelisted (i.e. with the `whitelist` command) can always join as spectators regardless.
Spectator entities control what entity is used to represent spectators in-game.
Full commands allow spectators access to all standard ZenithProxy commands like `connect`, `disconnect`, etc.
If this is disabled, spectators only have access to a limited set of core commands.
""")
.usageLines(
"on/off",
"whitelist add/del <player>",
"whitelist addAll <player 1>,<player 2>...",
"whitelist list",
"whitelist clear",
"entity list",
"entity <entity>",
"chat on/off",
"playerCamOnJoin on/off",
"fullCommands on/off",
"fullCommands slashCommands on/off",
"fullCommands requireRegularWhitelist on/off"
)
.build();
}
@Override
public LiteralArgumentBuilder<CommandContext> register() {
return command("spectator").requires(Command::validateAccountOwner)
.then(argument("toggle", toggle()).executes(c -> {
CONFIG.server.spectator.allowSpectator = getToggle(c, "toggle");
if (!CONFIG.server.spectator.allowSpectator)
Proxy.getInstance().getSpectatorConnections()
.forEach(connection -> connection.disconnect(CONFIG.server.extra.whitelist.kickmsg));
c.getSource().getEmbed()
.title("Spectators " + toggleStrCaps(CONFIG.server.spectator.allowSpectator))
.primaryColor()
.description(spectatorWhitelist());
}))
.then(literal("whitelist")
.then(literal("add").then(argument("player", string()).executes(c -> {
final String playerName = StringArgumentType.getString(c, "player");
PLAYER_LISTS.getSpectatorWhitelist().add(playerName)
.ifPresentOrElse(e ->
c.getSource().getEmbed()
.title("Added user: " + escape(e.getUsername()) + " To Spectator Whitelist")
.primaryColor()
.description(spectatorWhitelist()),
() -> c.getSource().getEmbed()
.title("Failed to add user: " + escape(playerName) + " to whitelist. Unable to lookup profile.")
.errorColor()
.description(spectatorWhitelist()));
})))
.then(literal("addAll").then(argument("playerList", greedyString()).executes(c -> {
String playerList = getString(c, "playerList");
String[] split = playerList.split(",");
if (split.length == 0) {
c.getSource().getEmbed()
.title("Invalid Input")
.description("Each player name must be delimited by `,`");
return ERROR;
}
List<String> addErrors = new ArrayList<>();
for (var player : split) {
if (PLAYER_LISTS.getSpectatorWhitelist().add(player).isEmpty()) {
addErrors.add(player);
}
}
c.getSource().getEmbed()
.title("Added Players")
.addField("Added Player Count", split.length - addErrors.size());
if (!addErrors.isEmpty()) {
c.getSource().getEmbed()
.description("Failed adding " + addErrors.size() + " players: " + String.join(", ", addErrors));
}
return OK;
})))
.then(literal("del").then(argument("player", string()).executes(c -> {
final String playerName = StringArgumentType.getString(c, "player");
PLAYER_LISTS.getSpectatorWhitelist().remove(playerName);
c.getSource().getEmbed()
.title("Removed user: " + escape(playerName) + " From Spectator Whitelist")
.primaryColor()
.description(spectatorWhitelist());
Proxy.getInstance().kickNonWhitelistedPlayers();
})))
.then(literal("clear").executes(c -> {
PLAYER_LISTS.getSpectatorWhitelist().clear();
c.getSource().getEmbed()
.title("Spectator Whitelist Cleared")
.errorColor()
.description(spectatorWhitelist());
Proxy.getInstance().kickNonWhitelistedPlayers();
}))
.then(literal("list").executes(c -> {
c.getSource().getEmbed()
.title("Spectator Whitelist")
.primaryColor()
.description(spectatorWhitelist());
})))
.then(literal("entity")
.then(literal("list").executes(c -> {
c.getSource().getEmbed()
.title("Entity List")
.description(entityList())
.primaryColor();
}))
.then(argument("entityID", enumStrings(SpectatorEntityRegistry.getEntityIdentifiers())).executes(c -> {
final String entityInput = StringArgumentType.getString(c, "entityID");
Optional<SpectatorEntity> spectatorEntity = SpectatorEntityRegistry.getSpectatorEntity(entityInput);
if (spectatorEntity.isPresent()) {
CONFIG.server.spectator.spectatorEntity = entityInput;
c.getSource().getEmbed()
.title("Set Entity")
.primaryColor();
} else {
c.getSource().getEmbed()
.title("Invalid Entity")
.description(entityList())
.errorColor();
}
})))
.then(literal("chat")
.then(argument("toggle", toggle()).executes(c -> {
CONFIG.server.spectator.spectatorPublicChatEnabled = getToggle(c, "toggle");
c.getSource().getEmbed()
.title("Spectator Chat " + toggleStrCaps(CONFIG.server.spectator.spectatorPublicChatEnabled))
.primaryColor()
.description(spectatorWhitelist());
})))
.then(literal("playerCamOnJoin").then(argument("toggle", toggle()).executes(c -> {
CONFIG.server.spectator.playerCamOnJoin = getToggle(c, "toggle");
c.getSource().getEmbed()
.title("Player Cam On Join " + toggleStrCaps(CONFIG.server.spectator.playerCamOnJoin))
.primaryColor();
})))
.then(literal("fullCommands").requires(Command::validateAccountOwner)
.then(argument("toggle", toggle()).executes(c -> {
CONFIG.server.spectator.fullCommandsEnabled = getToggle(c, "toggle");
c.getSource().getEmbed()
.title("Full Spectator Commands " + toggleStrCaps(CONFIG.server.spectator.fullCommandsEnabled))
.primaryColor();
}))
.then(literal("slashCommands").then(argument("toggle", toggle()).executes(c -> {
CONFIG.server.spectator.fullCommandsAcceptSlashCommands = getToggle(c, "toggle");
c.getSource().getEmbed()
.title("Full Spectator Commands Accept Slash Commands " + toggleStrCaps(CONFIG.server.spectator.fullCommandsAcceptSlashCommands))
.primaryColor();
})))
.then(literal("requireRegularWhitelist").then(argument("toggle", toggle()).executes(c -> {
CONFIG.server.spectator.fullCommandsRequireRegularWhitelist = getToggle(c, "toggle");
c.getSource().getEmbed()
.title("Full Spectator Commands Require Regular Whitelist " + toggleStrCaps(CONFIG.server.spectator.fullCommandsRequireRegularWhitelist))
.primaryColor();
}))));
}
private String spectatorWhitelist() {
return "**Spectator Whitelist**\n" + playerListToString(PLAYER_LISTS.getSpectatorWhitelist());
}
private String entityList() {
return "**Entity List**\n" + String.join(", ", SpectatorEntityRegistry.getEntityIdentifiers());
}
@Override
public void defaultEmbed(final Embed builder) {
builder
.addField("Spectators", toggleStr(CONFIG.server.spectator.allowSpectator))
.addField("Chat", toggleStr(CONFIG.server.spectator.spectatorPublicChatEnabled))
.addField("Entity", CONFIG.server.spectator.spectatorEntity)
.addField("PlayerCam On Join", toggleStr(CONFIG.server.spectator.playerCamOnJoin))
.addField("Full Commands", toggleStr(CONFIG.server.spectator.fullCommandsEnabled))
.addField("Full Commands Slash Commands", toggleStr(CONFIG.server.spectator.fullCommandsAcceptSlashCommands))
.addField("Full Commands Require Regular Whitelist", toggleStr(CONFIG.server.spectator.fullCommandsRequireRegularWhitelist));
}
}
| 412 | 0.930874 | 1 | 0.930874 | game-dev | MEDIA | 0.662568 | game-dev,testing-qa | 0.926521 | 1 | 0.926521 |
mcclure/bitbucket-backup | 4,861 | repos/nanogunk/contents/lib/perlin.lua | local ffi = require( "ffi" )
local sqrt, random, floor, band, min, max = math.sqrt, math.random, math.floor, bit.band, math.min, math.max
local function v2normself(v)
local oos = 1 / sqrt( v[0]*v[0] + v[1]*v[1] )
v[0], v[1] = v[0]*oos, v[1]*oos
end
local function v3normself(v)
local oos = 1 / sqrt( v[0]*v[0] + v[1]*v[1] + v[2]*v[2] )
v[0], v[1], v[2] = v[0]*oos, v[1]*oos, v[2]*oos
end
local function perlin_init(B)
local p = ffi.new( "uint8_t[?]", B + B + 2 )
local g1 = ffi.new( "double[?]", B + B + 2 )
local g2 = ffi.new( "double[?]", (B + B + 2)*2 )
local g3 = ffi.new( "double[?][3]", B + B + 2 )
for i = 0, B-1 do
p[i] = i
g1[i] = random()*2-1
local x = random()*2-1
local y = random()*2-1
local n = sqrt(x*x + y*y)
g2[i*2],g2[i*2+1] = x/n, y/n
for j = 0, 2 do
g3[i][j] = random()*2-1
end
v3normself( g3[i] )
end
for i = B-1, 0 do
local j = random(0, B-1)
p[i], p[j] = p[j], p[i]
end
for i = 0, B+1 do
p[B+i] = p[i]
g1[B+i] = g1[i]
for j = 0, 1 do
g2[(B+i)*2+0] = g2[i*2+0]
g2[(B+i)*2+1] = g2[i*2+1]
end
for j = 0, 2 do
g3[B+i][j] = g3[i][j]
end
end
return p, g1, g2, g3
end
local p, g1, g2, g3 = perlin_init(256)
local function s_curve(t)
return t*t*(3 - 2*t)
end
local function setup(t)
local ft = floor( t )
local b0 = band(255, ft)
local r0 = t - ft
local b1 = band(255, b0 + 1)
local r1 = r0 - 1
return b0, b1, r0, r1
end
local function setup2(t)
local ft = floor( t )
local b0 = band(255, ft)
return b0, band(255, b0 + 1), t - ft
end
local function at3(q,rx,ry,rz)
return rx*q[0] + ry*q[1] + rz*q[2]
end
local function noise1( arg )
local bx0, bx1, rx0, rx1 = setup( arg )
local sx = s_curve( rx0 )
local u = rx0 * g1[ p[bx0] ]
local v = rx1 * g1[ p[bx1] ]
return lerp( sx, u, v )
end
local function lerp(t, a, b)
return a + t * (b - a)
end
local function noise2( arg0, arg1 )
local g2 = g2
local bx0, bx1, rx = setup2( arg0 )
local by0, by1, ry = setup2( arg1 )
local i, j = p[ bx0], p[ bx1]
local b00, b10 = p[i + by0]*2, p[j + by0]*2
local b01, b11 = p[i + by1]*2, p[j + by1]*2
local sx = rx*rx*(3-2*rx)
local a = lerp(
sx,
rx *g2[b00] + ry*g2[b00+1],
(rx-1)*g2[b10] + ry*g2[b10+1]
)
local b = lerp(
sx,
rx *g2[b01] + (ry-1)*g2[b01+1],
(rx-1)*g2[b11] + (ry-1)*g2[b11+1]
)
return lerp( ry*ry*(3-2*ry), a, b )
end
local function noise3( arg0, arg1, arg2 )
local bx0, bx1, rx0, rx1 = setup( arg0 )
local by0, by1, ry0, ry1 = setup( arg1 )
local bz0, bz1, rz0, rz1 = setup( arg2 )
local i, j = p[ bx0 ], p[ bx1 ]
local b00, b10 = p[ i + by0 ], p[ j + by0 ]
local b01, b11 = p[ i + by1 ], p[ j + by1 ]
local t, sy, sz = s_curve( rx0 ), s_curve( ry0 ), s_curve( rz0 )
local u = at3( g3[b00 + bz0], rx0, ry0, rz0 )
local v = at3( g3[b10 + bz0], rx1, ry0, rz0 )
local a = lerp( t, u, v )
local u = at3( g3[b01 + bz0], rx0, ry1, rz0 )
local v = at3( g3[b11 + bz0], rx1, ry1, rz0 )
local b = lerp( t, u, v )
local c = lerp( sy, a, b )
local u = at3( g3[b00 + bz1], rx0, ry0, rz1 )
local v = at3( g3[b10 + bz1], rx1, ry0, rz1 )
local a = lerp( t, u, v )
local u = at3( g3[b01 + bz1], rx0, ry1, rz1 )
local v = at3( g3[b11 + bz1], rx1, ry1, rz1 )
local b = lerp( t, u, v )
local d = lerp( sy, a, b )
return lerp( sz, c, d )
end
-- --- My harmonic summing functions - PDB --------------------------*/
-- In what follows "alpha" is the weight when the sum is formed.
-- Typically it is 2, As this approaches 1 the function is noisier.
-- "beta" is the harmonic scaling/spacing, typically 2.
local function perlin1( x, alpha, beta, n )
local sum, scale = 0, 1
for i = 0, n - 1 do
sum = sum + noise1( x ) / scale
scale = scale * alpha
x = x * beta
end
return sum
end
local function perlin2( x, y, alpha, beta, n )
local sum, ooscale = 0, 1
local ooalpha = 0.5 -- 1 / alpha
for i = 0, n - 1 do
sum = sum + noise2( x, y ) * ooscale
x,y,ooscale = x*beta, y*beta, ooscale*ooalpha
end
return sum
end
local function perlin3( x, y, z, alpha, beta, n )
local sum, scale = 0, 1
for i = 0, n - 1 do
sum = sum + noise3( x, y, z ) / scale
scale = scale * alpha
x, y, z = x*beta, y*beta, z*beta
end
return sum
end
if false then
for x = 0, 100 do
for y = 0, 100 do
local v = floor(perlin2(random(),random(),1,1,100))
v = max(0,min(v, 100-32))+32
io.write(string.format("%c",v))
end
io.write('\n')
end
end
return {
noise1 = noise1,
noise2 = noise2,
noise3 = noise3,
perlin1 = perlin1,
perlin2 = perlin2,
perlin3 = perlin3,
}
| 412 | 0.714242 | 1 | 0.714242 | game-dev | MEDIA | 0.346847 | game-dev | 0.98416 | 1 | 0.98416 |
jwvhewitt/gearhead-2 | 20,377 | description.pp | unit description;
{ This unit provides the descriptions for gears. Its purpose is to }
{ explain to the player exactly what a given item does, and how it }
{ differs from other items. }
{
GearHead2, a roguelike mecha CRPG
Copyright (C) 2005 Joseph Hewitt
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
The full text of the LGPL can be found in license.txt.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
{$LONGSTRINGS ON}
interface
uses texutil,ui4gh,gears,gearutil,movement,locale;
Function WeaponDescription( GB: GameBoardPtr; Weapon: GearPtr ): String;
Function ExtendedDescription( GB: GameBoardPtr; Part: GearPtr ): String;
Function MechaDescription( Mek: GearPtr ): String;
Function TimeString( ComTime: LongInt ): String;
Function JobAgeGenderDesc( NPC: GearPtr ): String;
Function SkillDescription( N: Integer ): String;
Function MechaPilotName( Mek: GearPtr ): String;
Function TeamMateName( M: GearPtr ): String;
Function RenownDesc( Renown: Integer ): String;
implementation
uses ghmodule,ghweapon,ghsensor,ghsupport,ghmovers,ghguard,ghswag,ghholder,ghchars,
ability,ghintrinsic,interact,ghmecha;
Function BasicWeaponDesc( Weapon: GearPtr ): String;
{Supply a default name for this particular weapon.}
begin
{Convert the size of the weapon to a string.}
if Weapon^.G = GG_Weapon then begin
BasicWeaponDesc := DCName( WeaponDC( Weapon ) , Weapon^.Scale ) + ' ' + MsgString( 'WEAPONNAME_' + BStr( Weapon^.S ) );
end else begin
BasicWeaponDesc := DCName( WeaponDC( Weapon ) , Weapon^.Scale );
end;
end;
Function WeaponDescription( GB: GameBoardPtr; Weapon: GearPtr ): String;
{ Create a description for this weapon. }
var
Master,Ammo: GearPtr;
desc,AA: String;
S,M,L: Integer;
begin
{ Take the default name for the weapon from the WeaponName }
{ function in ghweapon. }
desc := BasicWeaponDesc( Weapon ) + ' (' + MsgSTring( 'STATABRV_' + BStr( Weapon^.Stat[ STAT_AttackStat ] ) ) + ')';
if Weapon^.G = GG_Weapon then begin
Master := FindMaster( Weapon );
Ammo := LocateGoodAmmo( Weapon );
if ( Weapon^.S = GS_Missile ) and ( Ammo <> Nil ) then begin
desc := BasicWeaponDesc( Ammo );
end;
if Master <> Nil then begin
if Master^.Scale <> Weapon^.Scale then begin
desc := desc + ' SF:' + BStr( Weapon^.Scale );
end;
end else if Weapon^.Scale > 0 then begin
desc := desc + ' SF:' + BStr( Weapon^.Scale );
end;
AA := WeaponAttackAttributes( Weapon );
if (Weapon^.S = GS_Ballistic) or (Weapon^.S = GS_BeamGun) or ( Weapon^.S = GS_Missile ) then begin
S := ScaleRange( WeaponRange( Nil , Weapon , RANGE_Short ) , Weapon^.Scale );
M := ScaleRange( WeaponRange( Nil , Weapon , RANGE_Medium ) , Weapon^.Scale );
L := ScaleRange( WeaponRange( Nil , Weapon , RANGE_Long ) , Weapon^.Scale );
if HasAttackAttribute( AA , AA_LineAttack ) then begin
desc := desc + ' RNG:' + BStr( S ) + '-' + BStr( L );
end else begin
desc := desc + ' RNG:' + BStr( S ) + '-' + BStr( M ) + '-' + BStr( L );
end;
end else if HasAttackAttribute( AA , AA_Extended ) then begin
desc := desc + ' RNG:' + BStr( ScaleRange( 2 , Weapon^.Scale ) );
end;
if Weapon^.S <> GS_Missile then begin
desc := desc + ' ACC:' + SgnStr( Weapon^.Stat[STAT_Accuracy] );
end else if Ammo <> Nil then begin
desc := desc + ' ACC:' + SgnStr( Ammo^.Stat[STAT_Accuracy] );
end;
desc := desc + ' SPD:' + BStr( Weapon^.Stat[STAT_Recharge] );
if (Weapon^.S = GS_Ballistic) or (Weapon^.S = GS_BeamGun) then begin
if Weapon^.Stat[ STAT_BurstValue ] > 0 then desc := desc + ' BV:' + BStr( Weapon^.Stat[ STAT_BurstValue ] + 1 );
end;
if (Weapon^.S = GS_Ballistic) or (Weapon^.S = GS_Missile) then begin
if Ammo <> Nil then begin
desc := desc + ' ' + BStr( AmmoRemaining( Weapon ) ) + '/' + BStr( Ammo^.Stat[ STAT_AmmoPresent] ) + 'a';
end else begin
desc := desc + MsgString( 'AMMO-EMPTY' );
end;
end else if ( Weapon^.S = GS_BeamGun ) or ( Weapon^.S = GS_EMelee ) then begin
desc := desc + ' EP:' + BStr( EnergyCost( Weapon ) ) + '/' + BStr( EnergyPoints( FindMasterOrRoot( Weapon ) ) );
end;
if HasAttackAttribute( AA , AA_Mystery ) then begin
desc := desc + ' ???';
end else begin
if AA <> '' then begin
desc := desc + ' ' + UpCase( AA );
end;
end;
if SAttValue( Weapon^.SA , 'CALIBER' ) <> '' then desc := desc + ' ' + SAttValue( Weapon^.SA , 'CALIBER' );
end else if Weapon^.G = GG_Ammo then begin
AA := WeaponAttackAttributes( Weapon );
if Weapon^.S = GS_Grenade then begin
desc := desc + ' RNG:T';
if Weapon^.Stat[ STAT_BurstValue ] > 0 then desc := desc + ' BV:' + BStr( Weapon^.Stat[ STAT_BurstValue ] + 1 );
end;
desc := desc + ' ' + BStr( Weapon^.Stat[STAT_AmmoPresent] - NAttValue( Weapon^.NA , NAG_WeaponModifier , NAS_AmmoSpent ) ) + '/' + BStr( Weapon^.Stat[ STAT_AmmoPresent] ) + 'a';
if HasAttackAttribute( AA , AA_Mystery ) then begin
desc := desc + ' ???';
end else begin
if AA <> '' then begin
desc := desc + ' ' + UpCase( AA );
end;
end;
end;
desc := desc + ' ARC:' + MsgString( 'WEAPONINFO_ARC' + BStr( WeaponArc( Weapon ) ) );
WeaponDescription := desc;
end;
Function WAODescription( Weapon: GearPtr ): String;
{ Create a description for this weapon. }
var
desc,AA: String;
begin
{ Take the default name for the weapon from the WeaponName }
{ function in ghweapon. }
desc := MsgString( 'WAO_' + BStr( Weapon^.S ) );
if Weapon^.V <> 0 then desc := desc + ' DC:' + SgnStr( Weapon^.V );
if Weapon^.Stat[ STAT_Range ] <> 0 then desc := desc + ' RNG:' + SgnStr( Weapon^.Stat[ STAT_Range ] );
if Weapon^.Stat[ STAT_Accuracy ] <> 0 then desc := desc + ' ACC:' + SgnStr( Weapon^.Stat[ STAT_Accuracy ] );
if Weapon^.Stat[ STAT_Recharge ] <> 0 then desc := desc + ' SPD:' + SgnStr( Weapon^.Stat[ STAT_Recharge ] );
AA := WeaponAttackAttributes( Weapon );
if HasAttackAttribute( AA , AA_Mystery ) then begin
desc := desc + ' ???';
end else if AA <> '' then begin
desc := desc + ' ' + UpCase( AA );
end;
WAODescription := desc;
end;
Function MoveSysDescription( Part: GearPtr ): String;
{ Return a description of the size/type of this movement }
{ system. }
begin
MoveSysDescription := MsgString( 'MoveSys_Class' ) + ' ' + BStr( Part^.V ) + ' ' + MoveSysName( Part );
end;
Function ModifierDescription( Part: GearPtr ): String;
{ Return a description for this modifier gear. }
var
it: String;
T: Integer;
begin
if Part^.S = GS_StatModifier then begin
it := '';
for t := 1 to NumGearStats do begin
if Part^.Stat[ T ] <> 0 then begin
if it <> '' then it := it + ', ';
it := it + SgnStr( Part^.Stat[ T ] ) + ' ' + MsgString( 'STATNAME_' + BStr( T ) );
end;
end;
end else if Part^.S = GS_SkillModifier then begin
it := MsgString( 'SKILLNAME_' + Bstr( Part^.Stat[ STAT_SkillToModify ] ) );
it := it + ' ' + SgnStr( Part^.Stat[ STAT_SkillModBonus ] );
end;
if it <> '' then it := it + '.';
ModifierDescription := it;
end;
Function ShieldDescription( Part: GearPtr ): String;
{ Return a description of the size/type of this movement }
{ system. }
begin
ShieldDescription := MsgString( 'Shield_Desc' ) + SgnStr( Part^.Stat[ STAT_ShieldBonus ] );
end;
Function ToolDescription( Part: GearPtr ): String;
{ Return a description of the size/type of this movement }
{ system. }
var
msg: String;
begin
if Part^.S > 0 then begin
msg := SgnStr( Part^.V ) + ' ' + MsgString( 'SKILLNAME_' + Bstr( Part^.S ) );
end else begin
msg := SgnStr( Part^.V ) + ' ' + MsgString( 'TALENT' + Bstr( Abs( Part^.S ) ) );
end;
ToolDescription := msg;
end;
Function IntrinsicsDescription( Part: GearPtr ): String;
{ Return a list of all the intrinsics associated with this part. }
var
T: Integer;
it: String;
begin
it := '';
{ Start by adding the armor type, if appropriate. }
T := NAttValue( Part^.NA , NAG_GearOps , NAS_ArmorType );
if T <> 0 then it := MsgString( 'ARMORTYPE_' + BStr( T ) );
{ We're only interested if the intrinsics are attached directly }
{ to this part. }
for t := 1 to NumIntrinsic do begin
if NAttValue( Part^.NA , NAG_Intrinsic , T ) <> 0 then begin
if it = '' then begin
it := MsgString( 'INTRINSIC_' + BStr( T ) );
end else begin
it := it + ', ' + MsgString( 'INTRINSIC_' + BStr( T ) );
end;
end;
end;
IntrinsicsDescription := it;
end;
Function ArmorDescription( Part: GearPtr ): String;
{ Return a description of this armor's stat modifiers, if any. }
var
it: String;
T: Integer;
begin
it := ArmorName( Part );
for t := 1 to NumGearStats do begin
if Part^.Stat[t] <> 0 then begin
it := it + ', +' + BStr( Part^.Stat[t] div 10 ) + '.' + BStr( Part^.Stat[t] mod 10 ) + ' ' + MsgString( 'STATNAME_' + BStr( T ) );
end;
end;
ArmorDescription := it;
end;
Function RepairFuelDescription( Part: GearPtr ): String;
{ Return a description for this repair fuel. }
begin
RepairFuelDescription := MsgString( 'REPAIRTYPE_' + BStr( Part^.S ) ) + ' ' + BStr( Part^.V ) + ' DP';
end;
Function PowerSourceDescription( Part: GearPtr ): String;
{ Return a description of the size of this power source. }
var
msg: String;
begin
msg := ReplaceHash( MsgString( 'PowerSource_Desc' ) , BStr( Part^.V ) );
PowerSourceDescription := msg;
end;
Function ComputerDescription( Part: GearPtr ): String;
{ Return a description of this computer. }
var
msg: String;
ZG,SWZG: Integer;
SW: GearPtr;
begin
msg := ReplaceHash( MsgString( 'Computer_Desc' ) , BStr( Part^.V ) );
ZG := ZetaGigs( Part );
SWZG := 0;
SW := Part^.SubCom;
while SW <> Nil do begin
SWZG := SWZG + ZetaGigs( SW );
SW := SW^.Next;
end;
msg := ReplaceHash( msg , BStr( ZG - SWZG ) );
msg := ReplaceHash( msg , BStr( ZG ) );
ComputerDescription := Msg;
end;
Function SoftwareDescription( Part: GearPtr ): String;
{ Return a description of this software's function. }
var
msg: String;
begin
msg := SgnStr( Part^.V ) + ' ';
case Part^.Stat[ STAT_SW_Type ] of
S_MVBoost: msg := msg + ReplaceHash( MsgString( 'SOFTWARE_MVBOOST_DESC' ) , Bstr( Part^.Stat[ STAT_SW_Param ] ) );
S_TRBoost: msg := msg + ReplaceHash( MsgString( 'SOFTWARE_TRBOOST_DESC' ) , Bstr( Part^.Stat[ STAT_SW_Param ] ) );
S_SpeedComp: msg := msg + ReplaceHash( MsgString( 'SOFTWARE_SPEEDCOMP_DESC' ) , Bstr( Part^.Stat[ STAT_SW_Param ] ) );
S_Information: msg := MsgSTring( 'SOFTWARE_INFORMATION_' + Bstr( Part^.Stat[ STAT_SW_Param ] ) );
else msg := msg + MsgString( 'SOFTWARE_MISC_DESC' );
end;
msg := msg + '; ' + BStr( ZetaGigs( Part ) ) + ' ZeG';
SoftwareDescription := msg;
end;
Function UsableDescription( Part: GearPtr ): String;
{ Return a description for this usable gear. }
begin
if Part^.S = GS_Transformation then begin
UsableDescription := MsgString( 'USABLENAME_1' ) + ': ' + MsgString( 'FORMNAME_' + BStr( Part^.V ) );
end else begin
UsableDescription := MsgString( 'USABLE_CLASS' ) + ' ' + BStr( Part^.V ) + ' ' + MsgString( 'USABLENAME_' + BStr( Part^.S ) );
end;
end;
Function CharaDescription( PC: GearPtr ): String;
{ Return a description of this character. For now, the description will }
{ just be a list of the character's talents. }
var
T: Integer;
msg: String;
begin
msg := '';
for t := 1 to NumTalent do begin
if NAttValue( PC^.NA , NAG_Talent , T ) <> 0 then begin
if msg = '' then msg := MsgSTring( 'TALENT' + BStr( T ) )
else msg := msg + ', ' + MsgSTring( 'TALENT' + BStr( T ) );
end;
end;
CharaDescription := msg;
end;
Function ExtendedDescription( GB: GameBoardPtr; Part: GearPtr ): String;
{ Provide an extended description telling all about the }
{ attributes of this particular item. }
var
it,IntDesc: String;
SC: GearPtr;
begin
{ Error check first. }
if Part = Nil then Exit( '' );
{ Start examining the part. }
it := '';
if ( Part^.G = GG_Weapon ) then begin
it := WeaponDescription( GB , Part );
end else if Part^.G = GG_Mecha then begin
it := MechaDescription( Part );
end else if Part^.G = GG_RepairFuel then begin
it := RepairFuelDescription( Part );
end else if ( Part^.G = GG_Ammo ) then begin
it := WeaponDescription( GB , Part );
end else if Part^.G = GG_MoveSys then begin
it := MoveSysDescription( Part );
end else if Part^.G = GG_Modifier then begin
it := ModifierDescription( Part );
end else if Part^.G = GG_Character then begin
it := CharaDescription( Part );
end else if Part^.G = GG_Tool then begin
it := ToolDescription( Part );
SC := Part^.SubCom;
while ( SC <> Nil ) do begin
it := it + '; ' + ExtendedDescription( GB , SC );
SC := SC^.Next;
end;
end else if Part^.G = GG_PowerSource then begin
it := PowerSourceDescription( Part );
end else if Part^.G = GG_COmputer then begin
it := ComputerDescription( Part );
end else if Part^.G = GG_Software then begin
it := SoftwareDescription( Part );
end else if Part^.G = GG_ExArmor then begin
it := ArmorDescription( Part );
SC := Part^.SubCom;
while ( SC <> Nil ) do begin
it := it + '; ' + ExtendedDescription( GB , SC );
SC := SC^.Next;
end;
end else if Part^.G = GG_Shield then begin
it := ShieldDescription( Part );
SC := Part^.SubCom;
while ( SC <> Nil ) do begin
it := it + '; ' + ExtendedDescription( GB , SC );
SC := SC^.Next;
end;
end else if Part^.G = GG_WeaponAddOn then begin
it := WAODescription( Part );
SC := Part^.SubCom;
while ( SC <> Nil ) do begin
it := it + '; ' + ExtendedDescription( GB , SC );
SC := SC^.Next;
end;
end else if Part^.G = GG_Support then begin
it := ReplaceHash( MsgString( 'SupportDesc' ) , BStr( Part^.V ) );
end else if Part^.G = GG_Usable then begin
it := UsableDescription( Part );
end else if Part^.G <> GG_Module then begin
SC := Part^.SubCom;
while ( SC <> Nil ) do begin
if it = '' then it := ExtendedDescription( GB , SC )
else it := it + '; ' + ExtendedDescription( GB , SC );
SC := SC^.Next;
end;
end else begin
{ This is a module, as determined by the above clause. }
if Part^.Stat[ STAT_VariableModuleForm ] <> 0 then it := MsgString( 'VariableModule' ) + ' ' + MsgString( 'MODULENAME_' + BStr( Part^.Stat[ STAT_PrimaryModuleForm ] ) ) + '/' + MsgString( 'MODULENAME_' + BStr( Part^.Stat[ STAT_VariableModuleForm ] ) );
end;
IntDesc := IntrinsicsDescription( Part );
if IntDesc <> '' then begin
if it = '' then it := IntDesc
else it := it + ', ' + IntDesc;
end;
ExtendedDescription := it;
end;
Function MechaDescription( Mek: GearPtr ): String;
{ Return a text description of this mecha's technical points. }
var
it,i2: String;
MM,MMS,MaxSpeed,FullSpeed: Integer;
CanMove: Boolean;
Engine: GearPtr;
begin
it := MassString( Mek ) + ' ' + MsgString( 'FORMNAME_' + BStr( Mek^.S ) );
it := it + ' ' + 'MV:' + SgnStr(MechaManeuver(Mek));
it := it + ' ' + 'TR:' + SgnStr(MechaTargeting(Mek));
it := it + ' ' + 'SE:' + SgnStr(MechaSensorRating(Mek));
MM := CountActiveParts( Mek , GG_Holder , GS_Hand );
if MM > 0 then begin
it := it + ' ' + MsgString( 'MEKDESC_Hands' ) + ':' + BStr( MM );
end;
MM := CountActiveParts( Mek , GG_Holder , GS_Mount );
if MM > 0 then begin
it := it + ' ' + MsgString( 'MEKDESC_Mounts' ) + ':' + BStr( MM );
end;
CanMove := False;
MaxSpeed := 0;
for MM := 1 to NumMoveMode do begin
MMS := BaseMoveRate( Nil , Mek , MM );
FullSpeed := AdjustedMoveRate( Nil , Mek , MM , NAV_FullSpeed );
if FullSpeed > MaxSpeed then MaxSpeed := FullSpeed;
if MMS > 0 then begin
CanMove := True;
{ Add a description for this movemode. }
if MM = MM_Fly then begin
{ Check to see whether the mecha can }
{ fly or just jump. }
if JumpTime( Nil , Mek ) = 0 then begin
it := it + ' ' + MsgString( 'MoveModeName_' + BStr( MM ) ) + ':' + BStr( MMS );
end else begin
it := it + ' ' + MsgString( 'MEKDESC_Jump' ) + ':' + BStr( JumpTime( Nil , Mek ) ) + 's';
end;
end else begin
it := it + ' ' + MsgString( 'MoveModeName_' + BStr( MM ) ) + ':' + BStr( MMS );
end;
end;
end;
if MaxSpeed > 0 then it := it + ' Max:' + BStr( MaxSpeed );
if Mek^.Stat[ STAT_MechaTrait ] <> 0 then begin
it := it + ' ' + MsgString( 'MECHATRAIT_' + BStr( Mek^.Stat[ STAT_MechaTrait ] ) );
end;
Engine := SeekGear( Mek , GG_Support , GS_Engine );
if Engine <> Nil then begin
i2 := MsgString( 'MEKDESC_ENGINE' + Bstr( Engine^.Stat[ STAT_EngineSubtype ] ) );
if i2 <> '' then it := it + ' ' + i2;
end;
{ Add warnings for different conditions. }
if not CanMove then begin
it := it + ' ' + MsgString( 'MEKDESC_Immobile' );
end;
if Destroyed( Mek ) then begin
it := it + ' ' + MsgString( 'MEKDESC_Destroyed' );
end;
if SeekGear(mek,GG_CockPit,0) = Nil then begin
it := it + ' ' + MsgString( 'MEKDESC_NoCockpit' );
end;
MechaDescription := it;
end;
Function TimeString( ComTime: LongInt ): String;
{ Create a string to express the time listed in COMTIME. }
var
msg: String;
S,M,H,D: LongInt; { Seconds, Minutes, Hours, Days }
begin
S := ComTime mod 60;
M := ( ComTime div 60 ) mod 60;
H := ( ComTime div AP_Hour ) mod 24;
D := ComTime div AP_Day;
msg := Bstr( H ) + ':' + WideStr( M , 2 ) + ':' + WideStr( S , 2 ) + MsgString( 'CLOCK_days' ) + BStr( D );
TimeString := msg;
end;
Function JobAgeGenderDesc( NPC: GearPtr ): String;
{ Return the Job, Age, and Gender of the provided character in }
{ a nicely formatted string. }
var
msg,job: String;
R: Integer;
begin
R := NAttValue( NPC^.NA , NAG_CharDescription , NAS_DAge ) + 20;
if R > 0 then msg := BStr( R )
else msg := '???';
msg := msg + ' year old';
if NAttValue( NPC^.NA, NAG_CharDescription, NAS_Gender) <> NAV_Undefined then begin
msg := msg + ' ' + LowerCase( MsgString( 'GenderName_' + BStr( NAttValue( NPC^.NA , NAG_CharDescription , NAS_Gender ) ) ) );
end;
job := SAttValue( NPC^.SA , 'JOB' );
if job <> '' then msg := msg + ' ' + LowerCase( job );
{ Check the NPC's relationship with the PC. }
r := NAttValue( NPC^.NA , NAG_Relationship , 0 );
if R > 0 then begin
job := MsgString( 'RELATIONSHIP_' + BStr( R ) );
if job <> '' then msg := msg + ', ' + job;
end;
msg := msg + '.';
JobAgeGenderDesc := msg;
end;
Function SkillDescription( N: Integer ): String;
{ Return a description for this skill. The main text is taken }
{ from the messages.txt file, plus the name of the stat which }
{ governs this skill. }
var
msg: String;
begin
msg := '';
{ Error check- only provide description for a legal skill }
{ number. Otherwise just return an empty string. }
if ( N >= 1 ) and ( N <= NumSkill ) then begin
msg := MsgString( 'SKILLDESC_' + BStr( N ) );
end;
SkillDescription := msg;
end;
Function MechaPilotName( Mek: GearPtr ): String;
{ Return the name of the mecha and the pilot, together. }
var
Msg,PName: String;
begin
msg := GearName( Mek );
if Mek^.G = GG_Mecha then begin
PName := PilotName( Mek );
if PName <> msg then msg := msg + ' (' + PName + ')';
end;
MechaPilotName := msg;
end;
Function TeamMateName( M: GearPtr ): String;
{ Return the name of this team-mate. If the team-mate is a mecha, }
{ also return the name of its pilot if appropriate. }
var
msg,pname: String;
begin
msg := FullGearName( M );
if M^.G = GG_Mecha then begin
pname := SAttValue( M^.SA , 'pilot' );
if pname <> '' then msg := msg + ' (' + pname + ')';
end;
TeamMateName := msg;
end;
Function RenownDesc( Renown: Integer ): String;
{ Return a description for the provided renown. }
begin
if Renown > 80 then begin
RenownDesc := MsgString( 'AHQRANK_5' );
end else if Renown > 60 then begin
RenownDesc := MsgString( 'AHQRANK_4' );
end else if Renown > 40 then begin
RenownDesc := MsgString( 'AHQRANK_3' );
end else if Renown > 20 then begin
RenownDesc := MsgString( 'AHQRANK_2' );
end else begin
RenownDesc := MsgString( 'AHQRANK_1' );
end;
end;
end.
| 412 | 0.930576 | 1 | 0.930576 | game-dev | MEDIA | 0.915201 | game-dev | 0.845216 | 1 | 0.845216 |
lua9520/source-engine-2018-hl2_src | 7,313 | game/server/NextBot/Player/NextBotPlayerBody.h | // NextBotPlayerBody.h
// Control and information about the bot's body state (posture, animation state, etc)
// Author: Michael Booth, October 2006
//========= Copyright Valve Corporation, All rights reserved. ============//
#ifndef _NEXT_BOT_PLAYER_BODY_H_
#define _NEXT_BOT_PLAYER_BODY_H_
#include "NextBotBodyInterface.h"
//----------------------------------------------------------------------------------------------------------------
/**
* A useful reply for IBody::AimHeadTowards. When the
* head is aiming on target, press the fire button.
*/
class PressFireButtonReply : public INextBotReply
{
public:
virtual void OnSuccess( INextBot *bot ); // invoked when process completed successfully
};
//----------------------------------------------------------------------------------------------------------------
/**
* A useful reply for IBody::AimHeadTowards. When the
* head is aiming on target, press the alt-fire button.
*/
class PressAltFireButtonReply : public INextBotReply
{
public:
virtual void OnSuccess( INextBot *bot ); // invoked when process completed successfully
};
//----------------------------------------------------------------------------------------------------------------
/**
* A useful reply for IBody::AimHeadTowards. When the
* head is aiming on target, press the jump button.
*/
class PressJumpButtonReply : public INextBotReply
{
public:
virtual void OnSuccess( INextBot *bot ); // invoked when process completed successfully
};
//----------------------------------------------------------------------------------------------------------------
/**
* The interface for control and information about the bot's body state (posture, animation state, etc)
*/
class PlayerBody : public IBody
{
public:
PlayerBody( INextBot *bot );
virtual ~PlayerBody();
virtual void Reset( void ); // reset to initial state
virtual void Upkeep( void ); // lightweight update guaranteed to occur every server tick
virtual bool SetPosition( const Vector &pos );
virtual const Vector &GetEyePosition( void ) const; // return the eye position of the bot in world coordinates
virtual const Vector &GetViewVector( void ) const; // return the view unit direction vector in world coordinates
virtual void AimHeadTowards( const Vector &lookAtPos,
LookAtPriorityType priority = BORING,
float duration = 0.0f,
INextBotReply *replyWhenAimed = NULL,
const char *reason = NULL ); // aim the bot's head towards the given goal
virtual void AimHeadTowards( CBaseEntity *subject,
LookAtPriorityType priority = BORING,
float duration = 0.0f,
INextBotReply *replyWhenAimed = NULL,
const char *reason = NULL ); // continually aim the bot's head towards the given subject
virtual bool IsHeadAimingOnTarget( void ) const; // return true if the bot's head has achieved its most recent lookat target
virtual bool IsHeadSteady( void ) const; // return true if head is not rapidly turning to look somewhere else
virtual float GetHeadSteadyDuration( void ) const; // return the duration that the bot's head has been on-target
virtual void ClearPendingAimReply( void ); // clear out currently pending replyWhenAimed callback
virtual float GetMaxHeadAngularVelocity( void ) const; // return max turn rate of head in degrees/second
virtual bool StartActivity( Activity act, unsigned int flags );
virtual Activity GetActivity( void ) const; // return currently animating activity
virtual bool IsActivity( Activity act ) const; // return true if currently animating activity matches the given one
virtual bool HasActivityType( unsigned int flags ) const; // return true if currently animating activity has any of the given flags
virtual void SetDesiredPosture( PostureType posture ); // request a posture change
virtual PostureType GetDesiredPosture( void ) const; // get posture body is trying to assume
virtual bool IsDesiredPosture( PostureType posture ) const; // return true if body is trying to assume this posture
virtual bool IsInDesiredPosture( void ) const; // return true if body's actual posture matches its desired posture
virtual PostureType GetActualPosture( void ) const; // return body's current actual posture
virtual bool IsActualPosture( PostureType posture ) const; // return true if body is actually in the given posture
virtual bool IsPostureMobile( void ) const; // return true if body's current posture allows it to move around the world
virtual bool IsPostureChanging( void ) const; // return true if body's posture is in the process of changing to new posture
virtual void SetArousal( ArousalType arousal ); // arousal level change
virtual ArousalType GetArousal( void ) const; // get arousal level
virtual bool IsArousal( ArousalType arousal ) const; // return true if body is at this arousal level
virtual float GetHullWidth( void ) const; // width of bot's collision hull in XY plane
virtual float GetHullHeight( void ) const; // height of bot's current collision hull based on posture
virtual float GetStandHullHeight( void ) const; // height of bot's collision hull when standing
virtual float GetCrouchHullHeight( void ) const; // height of bot's collision hull when crouched
virtual const Vector &GetHullMins( void ) const; // return current collision hull minimums based on actual body posture
virtual const Vector &GetHullMaxs( void ) const; // return current collision hull maximums based on actual body posture
virtual unsigned int GetSolidMask( void ) const; // return the bot's collision mask (hack until we get a general hull trace abstraction here or in the locomotion interface)
virtual CBaseEntity *GetEntity( void ); // get the entity
private:
CBasePlayer *m_player;
PostureType m_posture;
ArousalType m_arousal;
mutable Vector m_eyePos; // for use with GetEyePosition() ONLY
mutable Vector m_viewVector; // for use with GetViewVector() ONLY
mutable Vector m_hullMins; // for use with GetHullMins() ONLY
mutable Vector m_hullMaxs; // for use with GetHullMaxs() ONLY
Vector m_lookAtPos; // if m_lookAtSubject is non-NULL, it continually overwrites this position with its own
EHANDLE m_lookAtSubject;
Vector m_lookAtVelocity; // world velocity of lookat point, for tracking moving subjects
CountdownTimer m_lookAtTrackingTimer;
LookAtPriorityType m_lookAtPriority;
CountdownTimer m_lookAtExpireTimer; // how long until this lookat expired
IntervalTimer m_lookAtDurationTimer; // how long have we been looking at this target
INextBotReply *m_lookAtReplyWhenAimed;
bool m_isSightedIn; // true if we are looking at our last lookat target
bool m_hasBeenSightedIn; // true if we have hit the current lookat target
IntervalTimer m_headSteadyTimer;
QAngle m_priorAngles; // last update's head angles
QAngle m_desiredAngles;
CountdownTimer m_anchorRepositionTimer; // the time is takes us to recenter our virtual mouse
Vector m_anchorForward;
};
inline bool PlayerBody::IsHeadAimingOnTarget( void ) const
{
// TODO: Calling this immediately after AimHeadTowards will always return false until next Upkeep() (MSB)
return m_isSightedIn;
}
#endif // _NEXT_BOT_PLAYER_BODY_H_
| 412 | 0.893833 | 1 | 0.893833 | game-dev | MEDIA | 0.827307 | game-dev | 0.566868 | 1 | 0.566868 |
tatsuya-koyama/Alto-tascal-Unity-Lib | 12,692 | Assets/00_Altotascal/AltoEditor/Editor/EditorWindow/FavoritesWindow.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using Object = UnityEngine.Object;
namespace AltoEditor
{
public class FavoritesWindow : AltoEditorWindow
{
[MenuItem(AltoMenuPath.EditorWindow + "Favorites Window")]
static void ShowWindow()
{
GetWindow<FavoritesWindow>("★ Favorites");
}
Vector2 _scrollView;
bool _highlightRecent;
const string DefaultColor = "292929";
//----------------------------------------------------------------------
// Data structure
//----------------------------------------------------------------------
[System.Serializable]
class AssetInfo
{
public string guid;
public string path;
public string name;
public string type;
public string color;
public long time; // last opened unixtime [sec]
[NonSerialized] public int newestRank;
}
[System.Serializable]
class AssetInfoList
{
public List<AssetInfo> infoList = new();
}
[SerializeField] static AssetInfoList _assetsCache = null;
AssetInfoList _assets
{
get { return _assetsCache ??= LoadPrefs(); }
}
AssetInfo GetAssetInfo(string guid)
{
return _assets.infoList.FirstOrDefault(_ => _.guid == guid);
}
//----------------------------------------------------------------------
// Save and Load
//----------------------------------------------------------------------
void SavePrefs()
{
SaveSettings(_assetsCache);
}
AssetInfoList LoadPrefs()
{
return LoadSettings<AssetInfoList>() ?? new();
}
//----------------------------------------------------------------------
// Draw GUI
//----------------------------------------------------------------------
void OnGUI()
{
using (new GUILayout.HorizontalScope())
{
if (Button("★ Fav", 100f, 40f, "Bookmark selecting asset"))
{
BookmarkAsset();
}
DrawSortButtons();
}
AssignNewestRank(_assets.infoList);
_scrollView = GUILayout.BeginScrollView(_scrollView);
{
bool isCanceled;
foreach (var info in _assets.infoList)
{
using (new GUILayout.HorizontalScope())
{
isCanceled = DrawAssetRow(info);
}
if (isCanceled) { break; }
}
using (new GUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
_highlightRecent = GUILayout.Toggle(_highlightRecent, "Highlight recent");
}
}
GUILayout.EndScrollView();
}
void DrawSortButtons()
{
var sortFuncs = new(string, Action)[]
{
("▼ Type", SortByType),
("▲ Type", SortByTypeDesc),
("▼ Name", SortByName),
("▲ Name", SortByNameDesc),
("▼ Color", SortByColor),
("▲ Color", SortByColorDesc),
("▼ Time", SortByLastOpenedAt),
("▲ Time", SortByLastOpenedAtDesc),
};
for (int i = 0; i < 4; ++i)
{
using (new GUILayout.VerticalScope())
{
for (int j = 0; j < 2; ++j)
{
var funcInfo = sortFuncs[i * 2 + j];
string buttonLabel = funcInfo.Item1;
Action sortFunc = funcInfo.Item2;
if (Button(buttonLabel, 100f, 20f, color: LightGray))
{
sortFunc();
SavePrefs();
}
}
}
}
GUILayout.FlexibleSpace();
}
bool DrawAssetRow(AssetInfo info)
{
bool isCanceled = false;
{
var content = new GUIContent("◎", "Highlight asset");
if (GUILayout.Button(content, GUILayout.ExpandWidth(false)))
{
HighlightAsset(info);
}
}
{
SelectColorButton(info);
DrawAssetItemButton(info);
}
{
var content = new GUIContent("X", "Remove from Favs");
if (GUILayout.Button(content, GUILayout.ExpandWidth(false)))
{
RemoveAsset(info);
isCanceled = true;
}
}
return isCanceled;
}
void SelectColorButton(AssetInfo info)
{
Rect buttonRect = GUILayoutUtility.GetRect(
new GUIContent(""), GUI.skin.button, GUILayout.Width(14f)
);
if (GUI.Button(buttonRect, "", EditorStyles.boldLabel))
{
Vector2 screenPos = GUIUtility.GUIToScreenPoint(new Vector2(buttonRect.x, buttonRect.y));
buttonRect = new Rect(screenPos, buttonRect.size);
CustomColorPicker.ShowWindow(buttonRect, color => OnSelectColor(info, color));
}
buttonRect.y += 1f;
buttonRect.height -= 3f;
string colorCode = !string.IsNullOrEmpty(info.color) ? info.color : DefaultColor;
ColorUtility.TryParseHtmlString($"#{colorCode}", out var color);
EditorGUI.DrawRect(buttonRect, color);
}
void OnSelectColor(AssetInfo info, Color color)
{
var targetInfo = GetAssetInfo(info.guid);
targetInfo.color = ColorUtility.ToHtmlStringRGB(color);
SavePrefs();
}
void DrawAssetItemButton(AssetInfo info)
{
var content = new GUIContent($" {info.name}", AssetDatabase.GetCachedIcon(info.path));
var style = GUI.skin.button;
var originalAlignment = style.alignment;
var originalFontStyle = style.fontStyle;
var originalTextColor = style.normal.textColor;
style.alignment = TextAnchor.MiddleLeft;
SetRowStyle(info, style);
float width = position.width - 90f;
if (GUILayout.Button(content, style, GUILayout.MaxWidth(width), GUILayout.Height(18)))
{
OpenAsset(info);
}
style.alignment = originalAlignment;
style.fontStyle = originalFontStyle;
style.normal.textColor = originalTextColor;
}
//----------------------------------------------------------------------
// Highlight newer rows
//----------------------------------------------------------------------
void AssignNewestRank(List<AssetInfo> infoList)
{
var ordered = infoList.OrderByDescending(_ => _.time);
int rank = 1;
foreach (var info in ordered)
{
if (info.time == 0) { continue; }
info.newestRank = rank;
++rank;
}
}
void SetRowStyle(AssetInfo info, GUIStyle style)
{
if (!_highlightRecent) { return; }
int rank = info.newestRank;
if (rank == 1)
{
style.fontStyle = FontStyle.Bold;
style.normal.textColor = new Color(1f, 1f, 0f);
}
if (2 <= rank && rank <= 5)
{
style.fontStyle = FontStyle.Bold;
float b1 = 0.85f + (5 - rank) * 0.05f;
float b2 = 0.70f + (5 - rank) * 0.10f;
style.normal.textColor = new Color(b1, b2 * 0.85f, 0.5f);
}
}
//----------------------------------------------------------------------
// Control bookmarked assets
//----------------------------------------------------------------------
void BookmarkAsset()
{
foreach (string assetGuid in Selection.assetGUIDs)
{
if (_assets.infoList.Exists(x => x.guid == assetGuid)) { continue; }
var info = new AssetInfo
{
guid = assetGuid,
path = AssetDatabase.GUIDToAssetPath(assetGuid),
color = DefaultColor,
time = 0,
};
Object asset = AssetDatabase.LoadAssetAtPath<Object>(info.path);
info.name = asset.name;
info.type = asset.GetType().ToString();
_assets.infoList.Add(info);
}
SavePrefs();
}
void RemoveAsset(AssetInfo info)
{
_assets.infoList.Remove(info);
SavePrefs();
}
void HighlightAsset(AssetInfo info)
{
var asset = AssetDatabase.LoadAssetAtPath<Object>(info.path);
EditorGUIUtility.PingObject(asset);
}
void OpenAsset(AssetInfo info)
{
// Record last opened time
info.time = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
SavePrefs();
// Open scene asset
if (Path.GetExtension(info.path).Equals(".unity"))
{
if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
EditorSceneManager.OpenScene(info.path, OpenSceneMode.Single);
}
return;
}
// Open other type asset
var asset = AssetDatabase.LoadAssetAtPath<Object>(info.path);
AssetDatabase.OpenAsset(asset);
}
//----------------------------------------------------------------------
// Sort
//----------------------------------------------------------------------
void SortByType()
{
_assets.infoList.Sort((a, b) => {
int cmp1 = a.type.CompareTo(b.type);
if (cmp1 != 0) { return cmp1; }
return a.name.CompareTo(b.name);
});
}
void SortByTypeDesc()
{
_assets.infoList.Sort((a, b) => {
int cmp1 = b.type.CompareTo(a.type);
if (cmp1 != 0) { return cmp1; }
return a.name.CompareTo(b.name);
});
}
void SortByName()
{
_assets.infoList.Sort((a, b) => {
return a.name.CompareTo(b.name);
});
}
void SortByNameDesc()
{
_assets.infoList.Sort((a, b) => {
return b.name.CompareTo(a.name);
});
}
void SortByColor()
{
_assets.infoList.Sort((a, b) => {
int cmp1 = a.color.CompareTo(b.color);
if (cmp1 != 0) { return cmp1; }
int cmp2 = a.type.CompareTo(b.type);
if (cmp2 != 0) { return cmp2; }
return a.name.CompareTo(b.name);
});
}
void SortByColorDesc()
{
_assets.infoList.Sort((a, b) => {
int cmp1 = b.color.CompareTo(a.color);
if (cmp1 != 0) { return cmp1; }
int cmp2 = a.type.CompareTo(b.type);
if (cmp2 != 0) { return cmp2; }
return a.name.CompareTo(b.name);
});
}
void SortByLastOpenedAt()
{
_assets.infoList.Sort((a, b) => {
int cmp1 = b.time.CompareTo(a.time);
if (cmp1 != 0) { return cmp1; }
int cmp2 = a.type.CompareTo(b.type);
if (cmp2 != 0) { return cmp2; }
return a.name.CompareTo(b.name);
});
}
void SortByLastOpenedAtDesc()
{
_assets.infoList.Sort((a, b) => {
int cmp1 = a.time.CompareTo(b.time);
if (cmp1 != 0) { return cmp1; }
int cmp2 = a.type.CompareTo(b.type);
if (cmp2 != 0) { return cmp2; }
return a.name.CompareTo(b.name);
});
}
}
}
| 412 | 0.878218 | 1 | 0.878218 | game-dev | MEDIA | 0.628218 | game-dev,desktop-app | 0.996274 | 1 | 0.996274 |
awgil/ffxiv_bossmod | 4,420 | BossMod/Modules/Global/MaskedCarnivale/Stage26PapaMia/Stage26Act2.cs | namespace BossMod.Global.MaskedCarnivale.Stage26.Act2;
public enum OID : uint
{
Boss = 0x2C58, //R=3.6
Thunderhead = 0x2C59, //R=1.0
Helper = 0x233C,
}
public enum AID : uint
{
AutoAttack = 6499, // 2C58->player, no cast, single-target
RawInstinct = 18604, // 2C58->self, 3.0s cast, single-target
BodyBlow = 18601, // 2C58->player, 4.0s cast, single-target
VoidThunderII = 18602, // 2C58->location, 3.0s cast, range 4 circle
LightningBolt = 18606, // 2C59->self, no cast, range 8 circle
DadJoke = 18605, // 2C58->self, no cast, range 25+R 120-degree cone, knockback 15, dir forward
VoidThunderIII = 18603, // 2C58->player, 4.0s cast, range 20 circle
}
public enum SID : uint
{
CriticalStrikes = 1797, // Boss->Boss, extra=0x0
Electrocution = 271, // Boss/2C59->player, extra=0x0
}
public enum IconID : uint
{
BaitKnockback = 23, // player
}
class Thunderhead(BossModule module) : Components.PersistentVoidzone(module, 8, m => m.Enemies(OID.Thunderhead));
class DadJoke(BossModule module) : Components.Knockback(module)
{
private DateTime _activation;
public override IEnumerable<Source> Sources(int slot, Actor actor)
{
if (_activation != default)
yield return new(Module.PrimaryActor.Position, 15, _activation, Direction: Angle.FromDirection(actor.Position - Module.PrimaryActor.Position), Kind: Kind.DirForward);
}
public override void OnEventIcon(Actor actor, uint iconID, ulong targetID)
{
if (iconID == (uint)IconID.BaitKnockback)
_activation = WorldState.FutureTime(5);
}
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
if ((AID)spell.Action.ID == AID.DadJoke)
_activation = default;
}
public override bool DestinationUnsafe(int slot, Actor actor, WPos pos)
{
if (Module.FindComponent<Thunderhead>()?.ActiveAOEs(slot, actor).Any(z => z.Shape.Check(pos, z.Origin, z.Rotation)) ?? false)
return true;
if (!Module.InBounds(pos))
return true;
else
return false;
}
}
class VoidThunderII(BossModule module) : Components.StandardAOEs(module, AID.VoidThunderII, 4);
class RawInstinct(BossModule module) : Components.CastHint(module, AID.RawInstinct, "Prepare to dispel buff");
class VoidThunderIII(BossModule module) : Components.RaidwideCast(module, AID.VoidThunderIII, "Raidwide + Electrocution");
class BodyBlow(BossModule module) : Components.SingleTargetCast(module, AID.BodyBlow, "Soft Tankbuster");
class Hints(BossModule module) : BossComponent(module)
{
public override void AddGlobalHints(GlobalHints hints)
{
hints.Add($"{Module.PrimaryActor.Name} will cast Raw Instinct, which causes all his hits to crit.\nUse Eerie Soundwave to dispel it.\n{Module.PrimaryActor.Name} is weak against earth and strong against lightning attacks.");
}
}
class Hints2(BossModule module) : BossComponent(module)
{
public override void AddGlobalHints(GlobalHints hints)
{
var critbuff = Module.Enemies(OID.Boss).FirstOrDefault(x => x.FindStatus(SID.CriticalStrikes) != null);
if (critbuff != null)
hints.Add($"Dispel {Module.PrimaryActor.Name} with Eerie Soundwave!");
}
public override void AddHints(int slot, Actor actor, TextHints hints)
{
var electrocution = actor.FindStatus(SID.Electrocution);
if (electrocution != null)
hints.Add("Electrocution on you! Cleanse it with Exuviation.");
}
}
class Stage26Act2States : StateMachineBuilder
{
public Stage26Act2States(BossModule module) : base(module)
{
TrivialPhase()
.ActivateOnEnter<RawInstinct>()
.ActivateOnEnter<VoidThunderII>()
.ActivateOnEnter<VoidThunderIII>()
.ActivateOnEnter<BodyBlow>()
.ActivateOnEnter<DadJoke>()
.ActivateOnEnter<Thunderhead>()
.ActivateOnEnter<Hints2>()
.DeactivateOnEnter<Hints>();
}
}
[ModuleInfo(BossModuleInfo.Maturity.Contributed, Contributors = "Malediktus", GroupType = BossModuleInfo.GroupType.MaskedCarnivale, GroupID = 695, NameID = 9231, SortOrder = 2)]
public class Stage26Act2 : BossModule
{
public Stage26Act2(WorldState ws, Actor primary) : base(ws, primary, new(100, 100), new ArenaBoundsCircle(16))
{
ActivateComponent<Hints>();
}
}
| 412 | 0.901336 | 1 | 0.901336 | game-dev | MEDIA | 0.981871 | game-dev | 0.872617 | 1 | 0.872617 |
AionGermany/aion-germany | 9,417 | AL-Game/src/com/aionemu/gameserver/services/territory/TerritoryService.java | /**
*
*/
package com.aionemu.gameserver.services.territory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;
import com.aionemu.commons.database.dao.DAOManager;
import com.aionemu.gameserver.GameServer;
import com.aionemu.gameserver.dao.LegionDAO;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.team.legion.Legion;
import com.aionemu.gameserver.model.team.legion.LegionTerritory;
import com.aionemu.gameserver.network.aion.serverpackets.SM_CONQUEROR_PROTECTOR;
import com.aionemu.gameserver.network.aion.serverpackets.SM_LEGION_INFO;
import com.aionemu.gameserver.network.aion.serverpackets.SM_STONESPEAR_SIEGE;
import com.aionemu.gameserver.network.aion.serverpackets.SM_TERRITORY_LIST;
import com.aionemu.gameserver.network.aion.serverpackets.SM_UNK_12B;
import com.aionemu.gameserver.services.LegionService;
import com.aionemu.gameserver.services.teleport.TeleportService2;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.world.World;
import com.aionemu.gameserver.world.WorldPosition;
import javolution.util.FastMap;
/**
* @author CoolyT
*/
public class TerritoryService {
private TerritoryBuff territoryBuff;
private FastMap<Integer, TerritoryBuff> buffs = new FastMap<Integer, TerritoryBuff>();
private TreeMap<Integer, LegionTerritory> territories = new TreeMap<Integer, LegionTerritory>();
private TreeMap<Integer, TreeMap<Integer, WorldPosition>> teleporters = new TreeMap<Integer, TreeMap<Integer, WorldPosition>>();
public void init() {
LegionService ls = LegionService.getInstance();
Collection<Legion> legions = new ArrayList<Legion>();
int counter = 0;
// Fill Map with dummies, because client wants 6 entries ..
for (int i = 1; i <= 6; i++) {
territories.put(i, new LegionTerritory(i));
}
// Fill the LegionList
for (Integer legionId : DAOManager.getDAO(LegionDAO.class).getLegionIdswithTerritories()) {
legions.add(ls.getLegion(legionId));
}
// replace the dummies with realdata, if a legion owns an territory
for (Legion legion : legions) {
LegionTerritory territory = legion.getTerritory();
// Because .replace is only supported @ java 1.8 or higher, we use the old variant :)
territories.remove(territory.getId());
territories.put(territory.getId(), territory);
counter++;
}
GameServer.log.info("[TerritoryService] " + counter + " Legions owns a Territory..");
/*
* Teleporters Asmos
*/
// Mura
TreeMap<Integer, WorldPosition> mura = new TreeMap<Integer, WorldPosition>();
mura.put(805174, new WorldPosition(220080000, 1767.4069F, 2589.9512F, 299.21448F, (byte) 25));
mura.put(805175, new WorldPosition(220080000, 1767.9563F, 2586.478F, 298.71466F, (byte) 86));
mura.put(805176, new WorldPosition(220080000, 1803.5879F, 2557.8096F, 299.47995F, (byte) 6));
mura.put(805177, new WorldPosition(220080000, 1800.6494F, 2554.5647F, 298.75F, (byte) 72));
teleporters.put(1, mura);
// Satyr
TreeMap<Integer, WorldPosition> satyr = new TreeMap<Integer, WorldPosition>();
satyr.put(805178, new WorldPosition(220080000, 1442.7272F, 1739.9116F, 329.77304F, (byte) 60));
satyr.put(805179, new WorldPosition(220080000, 1446.1732F, 1741.3677F, 328.875F, (byte) 116));
satyr.put(805180, new WorldPosition(220080000, 1469.9454F, 1781.2479F, 330.02618F, (byte) 45));
satyr.put(805181, new WorldPosition(220080000, 1472.8165F, 1777.6108F, 328.82397F, (byte) 101));
teleporters.put(2, satyr);
// Velias
TreeMap<Integer, WorldPosition> velias = new TreeMap<Integer, WorldPosition>();
velias.put(805182, new WorldPosition(220080000, 764.80646F, 1310.1145F, 252.27219F, (byte) 26));
velias.put(805183, new WorldPosition(220080000, 765.20404F, 1304.71F, 251.5F, (byte) 86));
velias.put(805184, new WorldPosition(220080000, 796.8811F, 1272.6748F, 252.29373F, (byte) 3));
velias.put(805185, new WorldPosition(220080000, 792.2996F, 1270.9819F, 251.5F, (byte) 63));
teleporters.put(3, velias);
/*
* Teleporters Elyos
*/
// Kenoa
TreeMap<Integer, WorldPosition> kenoa = new TreeMap<Integer, WorldPosition>();
kenoa.put(805164, new WorldPosition(210070000, 1375.895F, 647.5174F, 581.81555F, (byte) 29));
kenoa.put(805165, new WorldPosition(210070000, 1376.3457F, 643.75977F, 581.61F, (byte) 88));
kenoa.put(805162, new WorldPosition(210070000, 1330.3495F, 634.5133F, 582.0176F, (byte) 45));
kenoa.put(805163, new WorldPosition(210070000, 1333.2931F, 631.8545F, 581.4909F, (byte) 110));
teleporters.put(4, kenoa);
// Deluan
TreeMap<Integer, WorldPosition> deluan = new TreeMap<Integer, WorldPosition>();
deluan.put(805168, new WorldPosition(210070000, 1211.4873F, 1580.0035F, 467.79865F, (byte) 107));
deluan.put(805169, new WorldPosition(210070000, 1208.5676F, 1582.7205F, 467.20496F, (byte) 50));
deluan.put(805167, new WorldPosition(210070000, 1217.7823F, 1626.8406F, 467.2364F, (byte) 75));
deluan.put(805166, new WorldPosition(210070000, 1220.8087F, 1628.8281F, 467.61154F, (byte) 9));
teleporters.put(5, deluan);
// Attika
TreeMap<Integer, WorldPosition> attika = new TreeMap<Integer, WorldPosition>();
attika.put(805172, new WorldPosition(210070000, 2381.85F, 1542.4397F, 438.40796F, (byte) 31));
attika.put(805173, new WorldPosition(210070000, 2378.4214F, 1538.7888F, 437.67432F, (byte) 79));
attika.put(805171, new WorldPosition(210070000, 2334.0369F, 1525.9147F, 438.49768F, (byte) 112));
attika.put(805170, new WorldPosition(210070000, 2332.486F, 1529.6007F, 438.5F, (byte) 45));
teleporters.put(6, attika);
}
public void onTeleport(Player player, int npcid) {
if (player.getLegion() == null || player.getLegion().getTerritory().getId() == 0)
return;
int territoryId = player.getLegion().getTerritory().getId();
TreeMap<Integer, WorldPosition> teleportMap = teleporters.get(territoryId);
WorldPosition pos = null;
if (teleportMap.containsKey(npcid))
pos = teleportMap.get(npcid);
if (pos != null)
TeleportService2.teleportTo(player, pos.getMapId(), pos.getX(), pos.getY(), pos.getZ(), pos.getHeading());
}
public void onEnterWorld(Player player) {
PacketSendUtility.sendPacket(player, new SM_TERRITORY_LIST(territories.values()));
PacketSendUtility.sendPacket(player, new SM_UNK_12B());
}
public void sendStoneSpearPacket(Player player) {
// PacketSendUtility.sendPacket(player, new SM_STONESPEAR_SIEGE(player.getLegion(),0));
}
public void onEnterTerritory(Player player) {
if (player.getLegion() == null || player.getLegion().getTerritory().getId() == 0)
return;
territoryBuff = new TerritoryBuff();
territoryBuff.applyEffect(player);
buffs.put(player.getObjectId(), territoryBuff);
}
public void onLeaveTerritory(Player player) {
if (player.getLegion() == null || player.getLegion().getTerritory().getId() == 0)
return;
if (buffs.containsKey(player.getObjectId())) {
buffs.get(player.getObjectId()).endEffect(player);
buffs.remove(player.getObjectId());
}
}
public void scanForIntruders(Player player) {
Collection<Player> players = new ArrayList<Player>();
Iterator<Player> playerIt = World.getInstance().getPlayersIterator();
while (playerIt.hasNext()) {
Player enemy = playerIt.next();
if (player.getWorldId() == enemy.getWorldId() && player.getRace() != enemy.getRace())
players.add(enemy);
}
PacketSendUtility.sendPacket(player, new SM_CONQUEROR_PROTECTOR(players, false));
}
public void onConquerTerritory(Legion legion, int id) {
if (legion.ownsTerretory()) {
onLooseTerritory(legion);
}
LegionTerritory territory = new LegionTerritory(id);
territory.setLegionId(legion.getLegionId());
territory.setLegionName(legion.getLegionName());
legion.setTerritory(territory);
territories.remove(id);
territories.put(id, territory);
broadcastTerritoryList(territories);
broadcastToLegion(legion);
}
private void broadcastToLegion(Legion legion) {
PacketSendUtility.broadcastPacketToLegion(legion, new SM_LEGION_INFO(legion));
PacketSendUtility.broadcastPacketToLegion(legion, new SM_STONESPEAR_SIEGE(legion, 0));
}
public void onLooseTerritory(Legion legion) {
int oldTerritoryId = legion.getTerritory().getId();
legion.clearTerritory();
if (oldTerritoryId == 0)
GameServer.log.info("[TerritoryService] Error TerritoryId is 0 !!! - Legion : " + legion.getLegionName());
LegionTerritory fakeTerritory = new LegionTerritory(oldTerritoryId);
territories.remove(oldTerritoryId);
territories.put(oldTerritoryId, fakeTerritory);
TreeMap<Integer, LegionTerritory> lostTerr = new TreeMap<Integer, LegionTerritory>();
lostTerr.put(oldTerritoryId, fakeTerritory);
broadcastTerritoryList(lostTerr);
broadcastToLegion(legion);
}
public void broadcastTerritoryList(TreeMap<Integer, LegionTerritory> terr) {
Collection<Player> players = World.getInstance().getAllPlayers();
for (Player player : players) {
if (!player.isOnline())
return;
PacketSendUtility.sendPacket(player, new SM_TERRITORY_LIST(terr.values()));
}
}
public Collection<LegionTerritory> getTerritories() {
return territories.values();
}
public static TerritoryService getInstance() {
return TerritoryService.SingletonHolder.instance;
}
private static class SingletonHolder {
protected static final TerritoryService instance = new TerritoryService();
}
}
| 412 | 0.786334 | 1 | 0.786334 | game-dev | MEDIA | 0.99237 | game-dev | 0.944232 | 1 | 0.944232 |
ant-design/ant-design-mini | 3,378 | demo/pages/Grid/index.axml | <!-- #if ALIPAY || WECHAT -->
<view class="navigation-bar"/>
<!-- #endif -->
<ant-container title="3列">
<ant-grid
items="{{ items3 }}"
onTap="handleTapItem"
iconSize="{{ 36 }}"
columns="{{ 3 }}" />
</ant-container>
<ant-container title="4列">
<ant-grid
items="{{ items4 }}"
onTap="handleTapItem"
columns="{{ 4 }}" />
</ant-container>
<ant-container title="5列">
<ant-grid
items="{{ items5 }}"
onTap="handleTapItem"
columns="{{ 5 }}" />
</ant-container>
<ant-container title="换行">
<ant-grid
items="{{ items5More }}"
onTap="handleTapItem"
columns="{{ 5 }}" />
</ant-container>
<ant-container title="5列-展示分割线">
<ant-grid
items="{{ items5 }}"
onTap="handleTapItem"
columns="{{ 5 }}"
showDivider />
</ant-container>
<ant-container title="2列-带描述">
<ant-grid
items="{{ items2withDesc }}"
onTap="handleTapItem"
iconSize="{{ 36 }}"
columns="{{ 2 }}" />
</ant-container>
<ant-container title="3列-带描述">
<ant-grid
items="{{ items3withDesc }}"
iconSize="{{ 36 }}"
onTap="handleTapItem"
columns="{{ 3 }}" />
</ant-container>
<ant-container title="2列-元素横向布局">
<ant-grid
items="{{ items2 }}"
onTap="handleTapItem"
columns="{{ 2 }}"
gridItemLayout="horizontal" />
</ant-container>
<ant-container title="2行-元素横向布局">
<ant-grid
items="{{ items4 }}"
gridItemLayout="horizontal"
onTap="handleTapItem"
columns="{{ 2 }}" />
</ant-container>
<ant-container title="3列-元素横向布局">
<ant-grid
items="{{ items3 }}"
onTap="handleTapItem"
columns="{{ 3 }}"
gridItemLayout="horizontal" />
</ant-container>
<ant-container title="2列-带描述">
<ant-grid
items="{{ items2withDesc }}"
onTap="handleTapItem"
iconSize="{{ 36 }}"
gridItemLayout="horizontal"
columns="{{ 2 }}" />
</ant-container>
<ant-container title="可滑动">
<ant-grid
items="{{ scrollItems }}"
onTap="handleTapItem"
mode="scroll" />
</ant-container>
<ant-container title="滑块可滑动">
<swiper
indicator-dots="{{ true }}"
autoplay="{{ true }}"
vertical="{{ false }}"
interval="{{ 1000 }}"
circular="{{ false }}"
duration="{{ 1500 }}"
>
<swiper-item key="swiper-item-{{index}}" a:for="{{[1,2,3,4]}}">
<ant-grid
items="{{ items5More }}"
onTap="handleTapItem"
columns="{{ 5 }}"
/>
</swiper-item>
</swiper>
</ant-container>
<ant-container title="自定义图标大小">
<ant-grid
items="{{ itemsCustom }}"
onTap="handleTapItem"
columns="{{ 5 }}"
iconSize="{{ 44 }}" />
</ant-container>
<!-- #if ALIPAY -->
<ant-container title="自定义">
<ant-grid
items="{{ itemsCustom }}"
onTap="handleTapItem"
columns="{{ 5 }}">
<view
slot="icon"
slot-scope="props">
<ant-badge
a:if="{{ props.value.tag }}"
offsetX="-10px"
type="text"
text="{{ props.value.tag }}">
<image
src="{{ props.value.icon }}"
style="width: 44px; height: 44px" />
</ant-badge>
<image
a:else
src="{{ props.value.icon }}"
style="width: 44px; height: 44px" />
</view>
<view
slot="title"
slot-scope="props">
第{{ props.index + 1 }}项
</view>
<view
slot="description"
slot-scope="props">
描述{{ props.index + 1 }}
</view>
</ant-grid>
</ant-container>
<!-- #endif -->
| 412 | 0.839178 | 1 | 0.839178 | game-dev | MEDIA | 0.643247 | game-dev | 0.608286 | 1 | 0.608286 |
ScreepsQuorum/screeps-quorum | 5,794 | src/programs/city/defense.js | 'use strict'
/**
* Provide Room-level Security
*/
class CityDefense extends kernel.process {
constructor (...args) {
super(...args)
this.priority = PRIORITIES_DEFENSE
// Pre-load all effect values.
if (!global.TOWER_DAMAGE_EFFECT || !global.TOWER_REPAIR_EFFECT || !global.TOWER_HEAL_EFFECT) {
global.TOWER_DAMAGE_EFFECT = []
global.TOWER_REPAIR_EFFECT = []
global.TOWER_HEAL_EFFECT = []
for (let i = 0; i < 50; i++) {
global.TOWER_DAMAGE_EFFECT[i] = this.calculateWithFallOff(TOWER_POWER_ATTACK, i)
global.TOWER_REPAIR_EFFECT[i] = this.calculateWithFallOff(TOWER_POWER_REPAIR, i)
global.TOWER_HEAL_EFFECT[i] = this.calculateWithFallOff(TOWER_POWER_HEAL, i)
}
}
}
getDescriptor () {
return this.data.room
}
main () {
if (!Game.rooms[this.data.room]) {
return this.suicide()
}
this.room = Game.rooms[this.data.room]
const towers = this.room.structures[STRUCTURE_TOWER]
const hostiles = this.room.find(FIND_HOSTILE_CREEPS)
if (towers && towers.length > 0) {
this.fireTowers(towers, hostiles)
}
if (towers && _.some(towers, tower => tower.energy < tower.energyCapacity)) {
this.launchCreepProcess('loader', 'replenisher', this.data.room, 1)
}
const playerHostiles = this.room.getHostilesByPlayer()
if (playerHostiles.length > 0) {
let aggression = AGGRESSION_INVADE
if (!this.room.controller.my || !this.room.structures[STRUCTURE_SPAWN]) {
aggression = AGGRESSION_RAZE
} else if (this.room.controller.safemode) {
aggression = AGGRESSION_TRIGGER_SAFEMODE
} else if (this.room.controller.upgradeBlocked) {
aggression = AGGRESSION_BLOCK_UPGRADE
}
for (const user in playerHostiles) {
Logger.log(`Hostile creep owned by ${user} detected in room ${this.data.room}.`, LOG_WARN)
qlib.notify.send(`Hostile creep owned by ${user} detected in room ${this.data.room}.`, TICKS_BETWEEN_ALERTS)
Empire.dossier.recordAggression(user, this.data.room, aggression)
}
this.safeMode()
}
}
fireTowers (towers, hostiles) {
const attackFunc = (attackTarget) => {
for (const tower of towers) {
if (tower.energy < TOWER_ENERGY_COST) {
continue
}
tower.attack(attackTarget)
}
}
const healFunc = (healTarget) => {
let damage = healTarget.hitsMax - healTarget.hits
for (const tower of towers) {
if (damage <= 0) {
break
}
const distance = tower.pos.getRangeTo(healTarget.pos)
damage -= global.TOWER_HEAL_EFFECT[distance]
tower.heal(healTarget)
}
}
if (hostiles.length > 0) {
const closestHostile = _.min(hostiles, c => c.pos.getRangeTo(towers[0].pos))
attackFunc(closestHostile)
return
}
if (this.data.healTarget !== undefined) {
const healTarget = Game.getObjectById(this.data.healTarget)
if (healTarget &&
(healTarget.pos.roomName === this.data.room) &&
(healTarget.hits < healTarget.hitsMax)) {
healFunc(healTarget)
return
}
// heal target no longer valid
delete this.data.healTarget
}
// look for a heal target every healFrequency ticks
const healFrequency = 5
if (this.period(healFrequency, 'healTargetSelection')) {
const room = Game.rooms[this.data.room]
const myCreeps = room.find(FIND_MY_CREEPS)
const lowestCreep = _.min(myCreeps, c => c.hits / c.hitsMax)
if (!_.isNumber(lowestCreep) &&
(lowestCreep.hits < lowestCreep.hitsMax)) {
this.data.healTarget = lowestCreep.id
healFunc(lowestCreep)
}
}
}
safeMode () {
const hostiles = this.room.getPlayerHostiles()
const room = Game.rooms[this.data.room]
if (room.controller.safeMode && room.controller.safeMode > 0) {
return true
}
if (!room.controller.canSafemode()) {
return false
}
const safeStructures = room.find(FIND_MY_SPAWNS)
// If there are no spawns this room isn't worth protecting with a safemode.
if (safeStructures.length <= 0) {
return false
}
// If other rooms are more important than this one save the safemode
if (!room.getRoomSetting('ALWAYS_SAFEMODE')) {
const cities = Room.getCities()
let highestLevel = 0
for (const cityName of cities) {
if (!Game.rooms[cityName]) {
continue
}
const city = Game.rooms[cityName]
if (!city.controller.canSafemode()) {
continue
}
if (city.getRoomSetting('ALWAYS_SAFEMODE')) {
return false
}
const level = city.getPracticalRoomLevel()
if (highestLevel < level) {
highestLevel = level
}
}
if (room.getPracticalRoomLevel() < highestLevel) {
return false
}
}
safeStructures.push(room.controller)
let structure
for (structure of safeStructures) {
const closest = structure.pos.findClosestByRange(hostiles)
if (structure.pos.getRangeTo(closest) < 5) {
// Trigger safemode
if (room.controller.activateSafeMode() === OK) {
Logger.log(`Activating safemode in ${this.data.room}`, LOG_ERROR)
}
return true
}
}
return false
}
calculateWithFallOff (optimalValue, distance) {
let effect = optimalValue
if (distance > TOWER_OPTIMAL_RANGE) {
if (distance > TOWER_FALLOFF_RANGE) {
distance = TOWER_FALLOFF_RANGE
}
effect -= effect * TOWER_FALLOFF * (distance - TOWER_OPTIMAL_RANGE) / (TOWER_FALLOFF_RANGE - TOWER_OPTIMAL_RANGE)
}
return Math.floor(effect)
}
}
module.exports = CityDefense
| 412 | 0.895802 | 1 | 0.895802 | game-dev | MEDIA | 0.995263 | game-dev | 0.820076 | 1 | 0.820076 |
magkopian/keepassxc-debian | 1,993 | keepassxc-2.3.4.orig/src/gui/CloneDialog.cpp | /*
* Copyright (C) 2017 KeePassXC Team <team@keepassxc.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 or (at your option)
* version 3 of the 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 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 "CloneDialog.h"
#include "ui_CloneDialog.h"
#include "config-keepassx.h"
#include "version.h"
#include "core/Database.h"
#include "core/Entry.h"
#include "core/FilePath.h"
#include "crypto/Crypto.h"
#include "gui/DatabaseWidget.h"
CloneDialog::CloneDialog(DatabaseWidget* parent, Database* db, Entry* entry)
: QDialog(parent)
, m_ui(new Ui::CloneDialog())
{
m_db = db;
m_entry = entry;
m_parent = parent;
m_ui->setupUi(this);
this->setFixedSize(this->sizeHint());
setAttribute(Qt::WA_DeleteOnClose);
connect(m_ui->buttonBox, SIGNAL(rejected()), SLOT(close()));
connect(m_ui->buttonBox, SIGNAL(accepted()), SLOT(cloneEntry()));
}
void CloneDialog::cloneEntry()
{
Entry::CloneFlags flags = Entry::CloneNewUuid | Entry::CloneResetTimeInfo;
if (m_ui->titleClone->isChecked()) {
flags |= Entry::CloneRenameTitle;
}
if (m_ui->referencesClone->isChecked()) {
flags |= Entry::CloneUserAsRef;
flags |= Entry::ClonePassAsRef;
}
if (m_ui->historyClone->isChecked()) {
flags |= Entry::CloneIncludeHistory;
}
Entry* entry = m_entry->clone(flags);
entry->setGroup(m_entry->group());
m_parent->refreshSearch();
close();
}
CloneDialog::~CloneDialog()
{
}
| 412 | 0.67744 | 1 | 0.67744 | game-dev | MEDIA | 0.707397 | game-dev | 0.626248 | 1 | 0.626248 |
aysihuniks/NClaim | 2,241 | src/main/java/nesoi/aysihuniks/nclaim/service/ClaimSettingsManager.java | package nesoi.aysihuniks.nclaim.service;
import lombok.RequiredArgsConstructor;
import nesoi.aysihuniks.nclaim.NClaim;
import nesoi.aysihuniks.nclaim.api.events.ClaimSettingChangeEvent;
import nesoi.aysihuniks.nclaim.enums.Setting;
import nesoi.aysihuniks.nclaim.model.Claim;
import nesoi.aysihuniks.nclaim.model.SettingCfg;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.nandayo.dapi.message.ChannelType;
@RequiredArgsConstructor
public class ClaimSettingsManager {
private final NClaim plugin;
public void toggleSetting(Claim claim, Player player, Setting setting) {
SettingCfg settingCfg = plugin.getGuiLangManager().getSettingConfig(setting);
if (!settingCfg.isChangeable()) {
ChannelType.CHAT.send(player, plugin.getLangManager().getString("command.change.setting_cannot_be_changed"));
return;
}
if (settingCfg.getPermission() != null && !player.hasPermission(settingCfg.getPermission())) {
ChannelType.CHAT.send(player, plugin.getLangManager().getString("command.permission_denied"));
return;
}
if (!isAuthorized(claim, player)) {
ChannelType.CHAT.send(player, plugin.getLangManager().getString("command.permission_denied"));
return;
}
boolean newState = !claim.getSettings().isEnabled(setting);
ClaimSettingChangeEvent changeEvent = new ClaimSettingChangeEvent(claim, claim.getSettings(), player, newState);
Bukkit.getPluginManager().callEvent(changeEvent);
if (changeEvent.isCancelled()) {
ChannelType.CHAT.send(player, plugin.getLangManager().getString("claim.setting_change_cancelled"));
return;
}
claim.getSettings().set(setting, newState);
if (plugin.getNconfig().isDatabaseEnabled()) {
plugin.getDatabaseManager().saveClaim(claim);
}
}
public boolean isSettingEnabled(Claim claim, Setting setting) {
return claim.getSettings().isEnabled(setting);
}
private boolean isAuthorized(Claim claim, Player player) {
return claim.getOwner().equals(player.getUniqueId()) ||
player.hasPermission("nclaim.admin");
}
} | 412 | 0.953319 | 1 | 0.953319 | game-dev | MEDIA | 0.822286 | game-dev | 0.986264 | 1 | 0.986264 |
Mi-Walkie-Talkie-by-Darkhorse/Mi-Walkie-Talkie-Plus | 4,192 | app/smali_classes2/com/ifengyu/intercom/update/dolphin/k$c.smali | .class Lcom/ifengyu/intercom/update/dolphin/k$c;
.super Ljava/lang/Thread;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/ifengyu/intercom/update/dolphin/k;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x2
name = "c"
.end annotation
# instance fields
.field private volatile a:Z
.field final synthetic b:Lcom/ifengyu/intercom/update/dolphin/k;
# direct methods
.method private constructor <init>(Lcom/ifengyu/intercom/update/dolphin/k;)V
.locals 0
iput-object p1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->b:Lcom/ifengyu/intercom/update/dolphin/k;
invoke-direct {p0}, Ljava/lang/Thread;-><init>()V
return-void
.end method
.method synthetic constructor <init>(Lcom/ifengyu/intercom/update/dolphin/k;Lcom/ifengyu/intercom/update/dolphin/k$a;)V
.locals 0
invoke-direct {p0, p1}, Lcom/ifengyu/intercom/update/dolphin/k$c;-><init>(Lcom/ifengyu/intercom/update/dolphin/k;)V
return-void
.end method
# virtual methods
.method a()V
.locals 1
const/4 v0, 0x1
iput-boolean v0, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->a:Z
return-void
.end method
.method public run()V
.locals 3
const/4 v0, 0x0
iput-boolean v0, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->a:Z
:goto_0
iget-boolean v1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->a:Z
if-nez v1, :cond_4
iget-object v1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->b:Lcom/ifengyu/intercom/update/dolphin/k;
invoke-static {v1}, Lcom/ifengyu/intercom/update/dolphin/k;->a(Lcom/ifengyu/intercom/update/dolphin/k;)Lcom/ifengyu/intercom/update/dolphin/g;
move-result-object v1
invoke-interface {v1}, Lcom/ifengyu/intercom/update/dolphin/g;->hasNext()Z
move-result v1
if-eqz v1, :cond_0
iget-object v1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->b:Lcom/ifengyu/intercom/update/dolphin/k;
invoke-static {v1}, Lcom/ifengyu/intercom/update/dolphin/k;->a(Lcom/ifengyu/intercom/update/dolphin/k;)Lcom/ifengyu/intercom/update/dolphin/g;
move-result-object v1
invoke-interface {v1}, Lcom/ifengyu/intercom/update/dolphin/g;->f()I
move-result v1
const/4 v2, 0x2
if-le v1, v2, :cond_1
:cond_0
iget-object v1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->b:Lcom/ifengyu/intercom/update/dolphin/k;
invoke-static {v1}, Lcom/ifengyu/intercom/update/dolphin/k;->a(Lcom/ifengyu/intercom/update/dolphin/k;)Lcom/ifengyu/intercom/update/dolphin/g;
move-result-object v1
invoke-interface {v1}, Lcom/ifengyu/intercom/update/dolphin/g;->d()Z
move-result v1
if-eqz v1, :cond_2
:cond_1
iget-object v1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->b:Lcom/ifengyu/intercom/update/dolphin/k;
invoke-static {v1}, Lcom/ifengyu/intercom/update/dolphin/k;->a(Lcom/ifengyu/intercom/update/dolphin/k;)Lcom/ifengyu/intercom/update/dolphin/g;
move-result-object v1
invoke-interface {v1}, Lcom/ifengyu/intercom/update/dolphin/g;->e()Z
goto :goto_1
:cond_2
invoke-static {}, Lcom/ifengyu/intercom/node/j;->b()Lcom/ifengyu/intercom/node/j;
move-result-object v1
invoke-virtual {v1}, Lcom/ifengyu/intercom/node/j;->a()Z
move-result v1
if-nez v1, :cond_3
iget-object v1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->b:Lcom/ifengyu/intercom/update/dolphin/k;
invoke-static {v1, v0}, Lcom/ifengyu/intercom/update/dolphin/k;->a(Lcom/ifengyu/intercom/update/dolphin/k;Z)V
goto :goto_2
:cond_3
:goto_1
:try_start_0
iget-object v1, p0, Lcom/ifengyu/intercom/update/dolphin/k$c;->b:Lcom/ifengyu/intercom/update/dolphin/k;
invoke-static {v1}, Lcom/ifengyu/intercom/update/dolphin/k;->b(Lcom/ifengyu/intercom/update/dolphin/k;)V
:try_end_0
.catch Ljava/lang/InterruptedException; {:try_start_0 .. :try_end_0} :catch_0
goto :goto_0
:catch_0
const-string v1, "UpdateHelper"
const-string v2, "SendDataThread interrupted."
invoke-static {v1, v2}, Lcom/ifengyu/intercom/i/z;->d(Ljava/lang/String;Ljava/lang/String;)I
goto :goto_0
:cond_4
:goto_2
return-void
.end method
| 412 | 0.778238 | 1 | 0.778238 | game-dev | MEDIA | 0.393549 | game-dev | 0.5361 | 1 | 0.5361 |
qhdwight/voxelfield | 1,484 | Packages/Swihoni.Sessions/Runtime/Entities/ItemEntityModifierBehavior.cs | using Swihoni.Components;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Swihoni.Sessions.Entities
{
[RequireComponent(typeof(Rigidbody))]
public class ItemEntityModifierBehavior : EntityModifierBehavior
{
public Rigidbody Rigidbody { get; private set; }
private void Awake() => Rigidbody = GetComponent<Rigidbody>();
public override void SetActive(Scene scene, bool isActive, int index)
{
base.SetActive(scene, isActive, index);
Rigidbody.velocity = Vector3.zero;
Rigidbody.angularVelocity = Vector3.zero;
Rigidbody.constraints = isActive ? RigidbodyConstraints.None : RigidbodyConstraints.FreezeAll;
}
public override void Modify(in SessionContext context)
{
base.Modify(context);
var throwable = context.entity.Require<ThrowableComponent>();
throwable.thrownElapsedUs.Add(context.durationUs);
if (throwable.flags.IsFloating)
{
Rigidbody.constraints = RigidbodyConstraints.FreezeAll;
transform.rotation = Quaternion.AngleAxis(Mathf.Repeat(context.timeUs / 10_000f, 360.0f), Vector3.up);
}
else Rigidbody.constraints = RigidbodyConstraints.None;
if (!throwable.flags.IsPersistent && throwable.thrownElapsedUs > context.Mode.GetItemEntityLifespanUs(context))
context.entity.Clear();
}
}
} | 412 | 0.561981 | 1 | 0.561981 | game-dev | MEDIA | 0.96561 | game-dev | 0.73474 | 1 | 0.73474 |
dynatrace-oss/hash4j | 3,659 | src/main/java/com/dynatrace/hash4j/similarity/DistinctElementHashProvider.java | /*
* Copyright 2022-2025 Dynatrace LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dynatrace.hash4j.similarity;
import static com.dynatrace.hash4j.internal.EmptyArray.EMPTY_LONG_ARRAY;
import static com.dynatrace.hash4j.internal.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.dynatrace.hash4j.random.PseudoRandomGenerator;
import com.dynatrace.hash4j.random.PseudoRandomGeneratorProvider;
import java.util.Arrays;
final class DistinctElementHashProvider implements ElementHashProvider {
private static final double EXTENSION_FACTOR = 1.5;
private static final long INITIAL_SEED = 0xfbf04e77450e9094L;
private final PseudoRandomGenerator pseudoRandomGenerator;
private long nullConstant;
private long[] work;
private int distinctCount = 0;
public DistinctElementHashProvider(PseudoRandomGeneratorProvider pseudoRandomGeneratorProvider) {
requireNonNull(pseudoRandomGeneratorProvider);
this.pseudoRandomGenerator = pseudoRandomGeneratorProvider.create();
this.pseudoRandomGenerator.reset(INITIAL_SEED);
this.work = EMPTY_LONG_ARRAY;
this.nullConstant = pseudoRandomGenerator.nextLong();
}
private static int computeWorkArrayLength(int numElements) {
return Integer.highestOneBit((int) (numElements * EXTENSION_FACTOR)) << 1;
}
private static boolean contains(long[] array, int len, long key) {
for (int i = 0; i < len; ++i) {
if (array[i] == key) return true;
}
return false;
}
private void changeNullConstant(int workLen) {
long newNullConstant;
do {
newNullConstant = pseudoRandomGenerator.nextLong();
} while (nullConstant == newNullConstant || contains(work, workLen, newNullConstant));
for (int i = 0; i < workLen; ++i) {
if (work[i] == nullConstant) {
work[i] = newNullConstant;
}
}
nullConstant = newNullConstant;
}
public void reset(ElementHashProvider elementHashProvider) {
int numElements = elementHashProvider.getNumberOfElements();
checkArgument(numElements <= 0x40000000L);
int workLen = computeWorkArrayLength(numElements);
if (work.length < workLen) {
work = new long[workLen];
}
Arrays.fill(work, 0, workLen, nullConstant);
int workLenMinus1 = workLen - 1;
for (int elementIdx = 0; elementIdx < numElements; ++elementIdx) {
long hash = elementHashProvider.getElementHash(elementIdx);
if (hash == nullConstant) {
// very unlikely case, if this happens find a new null constant
changeNullConstant(workLen);
}
int pos = (int) hash & workLenMinus1;
while (work[pos] != nullConstant && work[pos] != hash) {
pos = (pos + 1) & workLenMinus1;
}
work[pos] = hash;
}
distinctCount = 0;
for (int pos = 0; pos < workLen; ++pos) {
if (work[pos] != nullConstant) {
work[distinctCount] = work[pos];
distinctCount += 1;
}
}
}
@Override
public int getNumberOfElements() {
return distinctCount;
}
@Override
public long getElementHash(int elementIndex) {
return work[elementIndex];
}
}
| 412 | 0.946818 | 1 | 0.946818 | game-dev | MEDIA | 0.465014 | game-dev | 0.979236 | 1 | 0.979236 |
Boat-H2CO3/H2CO3Launcher | 4,239 | H2CO3Library/src/main/java/org/koishi/launcher/h2co3core/mod/modinfo/LiteModMetadata.java | /*
* Hello Minecraft! Launcher
* Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.koishi.launcher.h2co3core.mod.modinfo;
import com.google.gson.JsonParseException;
import org.koishi.launcher.h2co3core.mod.LocalModFile;
import org.koishi.launcher.h2co3core.mod.ModLoaderType;
import org.koishi.launcher.h2co3core.mod.ModManager;
import org.koishi.launcher.h2co3core.util.gson.JsonUtils;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public final class LiteModMetadata {
private final String name;
private final String version;
private final String mcversion;
private final String revision;
private final String author;
private final String[] classTransformerClasses;
private final String description;
private final String modpackName;
private final String modpackVersion;
private final String checkUpdateUrl;
private final String updateURI;
public LiteModMetadata() {
this("", "", "", "", "", new String[]{""}, "", "", "", "", "");
}
public LiteModMetadata(String name, String version, String mcversion, String revision, String author, String[] classTransformerClasses, String description, String modpackName, String modpackVersion, String checkUpdateUrl, String updateURI) {
this.name = name;
this.version = version;
this.mcversion = mcversion;
this.revision = revision;
this.author = author;
this.classTransformerClasses = classTransformerClasses;
this.description = description;
this.modpackName = modpackName;
this.modpackVersion = modpackVersion;
this.checkUpdateUrl = checkUpdateUrl;
this.updateURI = updateURI;
}
public static LocalModFile fromFile(ModManager modManager, Path modFile, FileSystem fs) throws IOException, JsonParseException {
try (ZipFile zipFile = new ZipFile(modFile.toFile())) {
ZipEntry entry = zipFile.getEntry("litemod.json");
if (entry == null)
throw new IOException("File " + modFile + "is not a LiteLoader mod.");
LiteModMetadata metadata = JsonUtils.fromJsonFully(zipFile.getInputStream(entry), LiteModMetadata.class);
if (metadata == null)
throw new IOException("Mod " + modFile + " `litemod.json` is malformed.");
return new LocalModFile(modManager, modManager.getLocalMod(metadata.getName(), ModLoaderType.LITE_LOADER), modFile, metadata.getName(), new LocalModFile.Description(metadata.getDescription()), metadata.getAuthor(),
metadata.getVersion(), metadata.getGameVersion(), metadata.getUpdateURI(), "");
}
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getGameVersion() {
return mcversion;
}
public String getRevision() {
return revision;
}
public String getAuthor() {
return author;
}
public String[] getClassTransformerClasses() {
return classTransformerClasses;
}
public String getDescription() {
return description;
}
public String getModpackName() {
return modpackName;
}
public String getModpackVersion() {
return modpackVersion;
}
public String getCheckUpdateUrl() {
return checkUpdateUrl;
}
public String getUpdateURI() {
return updateURI;
}
}
| 412 | 0.758543 | 1 | 0.758543 | game-dev | MEDIA | 0.557225 | game-dev | 0.787905 | 1 | 0.787905 |
dotCMS/core | 4,055 | dotCMS/src/main/webapp/html/js/dojo/custom-build/dojox/charting/Theme.js | define("dojox/charting/Theme", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/Color", "./SimpleTheme",
"dojox/color/_base", "dojox/color/Palette", "dojox/gfx/gradutils"],
function(lang, declare, Color, SimpleTheme, colorX, Palette){
var Theme = declare("dojox.charting.Theme", SimpleTheme, {
// summary:
// A Theme is a pre-defined object, primarily JSON-based, that makes up the definitions to
// style a chart. It extends SimpleTheme with additional features like color definition by
// palettes and gradients definition.
});
/*=====
var __DefineColorArgs = {
// summary:
// The arguments object that can be passed to define colors for a theme.
// num: Number?
// The number of colors to generate. Defaults to 5.
// colors: String[]|dojo/_base/Color[]?
// A pre-defined set of colors; this is passed through to the Theme directly.
// hue: Number?
// A hue to base the generated colors from (a number from 0 - 359).
// saturation: Number?
// If a hue is passed, this is used for the saturation value (0 - 100).
// low: Number?
// An optional value to determine the lowest value used to generate a color (HSV model)
// high: Number?
// An optional value to determine the highest value used to generate a color (HSV model)
// base: String|dojo/_base/Color?
// A base color to use if we are defining colors using dojox.color.Palette
// generator: String?
// The generator function name from dojox/color/Palette.
};
=====*/
lang.mixin(Theme, {
defineColors: function(kwArgs){
// summary:
// Generate a set of colors for the theme based on keyword
// arguments.
// kwArgs: __DefineColorArgs
// The arguments object used to define colors.
// returns: dojo/_base/Color[]
// An array of colors for use in a theme.
//
// example:
// | var colors = Theme.defineColors({
// | base: "#369",
// | generator: "compound"
// | });
//
// example:
// | var colors = Theme.defineColors({
// | hue: 60,
// | saturation: 90,
// | low: 30,
// | high: 80
// | });
kwArgs = kwArgs || {};
var l, c = [], n = kwArgs.num || 5; // the number of colors to generate
if(kwArgs.colors){
// we have an array of colors predefined, so fix for the number of series.
l = kwArgs.colors.length;
for(var i = 0; i < n; i++){
c.push(kwArgs.colors[i % l]);
}
return c; // dojo.Color[]
}
if(kwArgs.hue){
// single hue, generate a set based on brightness
var s = kwArgs.saturation || 100, // saturation
st = kwArgs.low || 30,
end = kwArgs.high || 90;
// we'd like it to be a little on the darker side.
l = (end + st) / 2;
// alternately, use "shades"
return Palette.generate(
colorX.fromHsv(kwArgs.hue, s, l), "monochromatic"
).colors;
}
if(kwArgs.generator){
// pass a base color and the name of a generator
return colorX.Palette.generate(kwArgs.base, kwArgs.generator).colors;
}
return c; // dojo.Color[]
},
generateGradient: function(fillPattern, colorFrom, colorTo){
var fill = lang.delegate(fillPattern);
fill.colors = [
{offset: 0, color: colorFrom},
{offset: 1, color: colorTo}
];
return fill;
},
generateHslColor: function(color, luminance){
color = new Color(color);
var hsl = color.toHsl(),
result = colorX.fromHsl(hsl.h, hsl.s, luminance);
result.a = color.a; // add missing opacity
return result;
},
generateHslGradient: function(color, fillPattern, lumFrom, lumTo){
color = new Color(color);
var hsl = color.toHsl(),
colorFrom = colorX.fromHsl(hsl.h, hsl.s, lumFrom),
colorTo = colorX.fromHsl(hsl.h, hsl.s, lumTo);
colorFrom.a = colorTo.a = color.a; // add missing opacity
return Theme.generateGradient(fillPattern, colorFrom, colorTo); // Object
}
});
// for compatibility
Theme.defaultMarkers = SimpleTheme.defaultMarkers;
Theme.defaultColors = SimpleTheme.defaultColors;
Theme.defaultTheme = SimpleTheme.defaultTheme;
return Theme;
});
| 412 | 0.710312 | 1 | 0.710312 | game-dev | MEDIA | 0.217985 | game-dev | 0.716492 | 1 | 0.716492 |
MikeShah/SDL2_Tutorials | 2,337 | 26_ColliderComponent/src/GameEntity.cpp | #include "GameEntity.hpp"
#include "Collider2D.hpp"
GameEntity::GameEntity(){
m_sprite = nullptr;
}
GameEntity::GameEntity(SDL_Renderer* renderer){
m_renderer = renderer;
m_sprite = nullptr;
}
GameEntity::~GameEntity(){
if(nullptr != m_sprite){
delete m_sprite;
}
for(int i=0; i<m_colliders.size(); i++){
delete m_colliders[i];
}
}
void GameEntity::Update(){
// Update the position of our collider,
// to be the same as the position of our Sprite component
//if(nullptr != m_sprite){
// int x = m_sprite->GetPositionX();
// int y = m_sprite->GetPositionY();
// int w = m_sprite->GetWidth();
// int h = m_sprite->GetHeight();
//}
}
void GameEntity::Render(){
if(nullptr != m_sprite){
m_sprite->Render(m_renderer);
}
for(int i=0; i < m_colliders.size();i++){
if(nullptr != m_colliders[i]){
SDL_SetRenderDrawColor(m_renderer,255,0,255,SDL_ALPHA_OPAQUE);
SDL_RenderDrawRect(m_renderer,&m_colliders[i]->GetColliderBoundingBox());
}
}
}
void GameEntity::AddTexturedRectangleComponent(std::string spritepath){
m_sprite = new TexturedRectangle(m_renderer,spritepath);
}
void GameEntity::AddTexturedRectangleComponent(std::string spritepath, int redcolorkey, int greencolorkey, int bluecolorkey){
m_sprite = new TexturedRectangle(m_renderer,spritepath, redcolorkey, greencolorkey, bluecolorkey);
}
void GameEntity::AddBoxCollider2D(){
m_colliders.push_back(new BoxCollider2D());
}
TexturedRectangle& GameEntity::GetTexturedRectangle(){
return *m_sprite;
}
BoxCollider2D& GameEntity::GetBoxCollider2D(size_t index){
return *m_colliders[index];
}
void GameEntity::SetPosition(int x, int y){
// Set the texture position
if(nullptr!=m_sprite){
m_sprite->SetPosition(x,y);
}
for(int i=0; i < m_colliders.size();i++){
if(nullptr != m_colliders[i]){
m_colliders[i]->SetAbsolutePosition(x,y);
}
}
}
void GameEntity::SetDimensions(int w, int h){
// Set the texture position
if(nullptr!=m_sprite){
m_sprite->SetDimensions(w,h);
}
for(int i=0; i < m_colliders.size();i++){
if(nullptr != m_colliders[i]){
m_colliders[i]->SetDimensions(w,h);
}
}
}
| 412 | 0.812169 | 1 | 0.812169 | game-dev | MEDIA | 0.739354 | game-dev,graphics-rendering | 0.682489 | 1 | 0.682489 |
Hoto-Mocha/Re-ARranged-Pixel-Dungeon | 2,748 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/particles/LightParticle.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2024 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.effects.particles;
import com.watabou.noosa.particles.Emitter;
import com.watabou.noosa.particles.Emitter.Factory;
import com.watabou.noosa.particles.PixelParticle;
import com.watabou.utils.ColorMath;
import com.watabou.utils.PointF;
import com.watabou.utils.Random;
public class LightParticle extends PixelParticle.Shrinking { //this is from ShadowParticle
public static final Factory MISSILE = new Factory() {
@Override
public void emit( Emitter emitter, int index, float x, float y ) {
((LightParticle)emitter.recycle( LightParticle.class )).reset( x, y );
}
};
public static final Factory CURSE = new Factory() {
@Override
public void emit( Emitter emitter, int index, float x, float y ) {
((LightParticle)emitter.recycle( LightParticle.class )).resetCurse( x, y );
}
};
public static final Factory UP = new Factory() {
@Override
public void emit( Emitter emitter, int index, float x, float y ) {
((LightParticle)emitter.recycle( LightParticle.class )).resetUp( x, y );
}
};
public void reset( float x, float y ) {
revive();
this.x = x;
this.y = y;
speed.set( Random.Float( -5, +5 ), Random.Float( -5, +5 ) );
size = 6;
left = lifespan = 0.5f;
}
public void resetCurse( float x, float y ) {
revive();
size = 8;
left = lifespan = 0.5f;
speed.polar( Random.Float( PointF.PI2 ), Random.Float( 16, 32 ) );
this.x = x - speed.x * lifespan;
this.y = y - speed.y * lifespan;
}
public void resetUp( float x, float y ) {
revive();
speed.set( Random.Float( -8, +8 ), Random.Float( -32, -48 ) );
this.x = x;
this.y = y;
size = 6;
left = lifespan = 1f;
}
@Override
public void update() {
super.update();
float p = left / lifespan;
// alpha: 0 -> 1 -> 0; size: 6 -> 0; color: 0x660044 -> 0x000000
color( ColorMath.interpolate( 0xFFFFFF, 0x444444, p ) );
am = p < 0.5f ? p * p * 4 : (1 - p) * 2;
}
} | 412 | 0.901457 | 1 | 0.901457 | game-dev | MEDIA | 0.907969 | game-dev,graphics-rendering | 0.961012 | 1 | 0.961012 |
mc-zhonghuang/Urticaria-Public | 21,299 | src/main/java/net/minecraft/init/Bootstrap.java | package net.minecraft.init;
import com.mojang.authlib.GameProfile;
import net.minecraft.block.*;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.dispenser.*;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.item.EntityBoat;
import net.minecraft.entity.item.EntityExpBottle;
import net.minecraft.entity.item.EntityFireworkRocket;
import net.minecraft.entity.item.EntityTNTPrimed;
import net.minecraft.entity.projectile.*;
import net.minecraft.item.*;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.stats.StatList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityDispenser;
import net.minecraft.tileentity.TileEntitySkull;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.LoggingPrintStream;
import net.minecraft.util.StringUtils;
import net.minecraft.world.World;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.PrintStream;
import java.util.Random;
public class Bootstrap {
private static final PrintStream SYSOUT = System.out;
/**
* Whether the blocks, items, etc have already been registered
*/
private static boolean alreadyRegistered = false;
private static final Logger LOGGER = LogManager.getLogger();
/**
* Is Bootstrap registration already done?
*/
public static boolean isRegistered() {
return alreadyRegistered;
}
static void registerDispenserBehaviors() {
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.arrow, new BehaviorProjectileDispense() {
protected IProjectile getProjectileEntity(final World worldIn, final IPosition position) {
final EntityArrow entityarrow = new EntityArrow(worldIn, position.getX(), position.getY(), position.getZ());
entityarrow.canBePickedUp = 1;
return entityarrow;
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.egg, new BehaviorProjectileDispense() {
protected IProjectile getProjectileEntity(final World worldIn, final IPosition position) {
return new EntityEgg(worldIn, position.getX(), position.getY(), position.getZ());
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.snowball, new BehaviorProjectileDispense() {
protected IProjectile getProjectileEntity(final World worldIn, final IPosition position) {
return new EntitySnowball(worldIn, position.getX(), position.getY(), position.getZ());
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.experience_bottle, new BehaviorProjectileDispense() {
protected IProjectile getProjectileEntity(final World worldIn, final IPosition position) {
return new EntityExpBottle(worldIn, position.getX(), position.getY(), position.getZ());
}
protected float func_82498_a() {
return super.func_82498_a() * 0.5F;
}
protected float func_82500_b() {
return super.func_82500_b() * 1.25F;
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.potionitem, new IBehaviorDispenseItem() {
private final BehaviorDefaultDispenseItem field_150843_b = new BehaviorDefaultDispenseItem();
public ItemStack dispense(final IBlockSource source, final ItemStack stack) {
return ItemPotion.isSplash(stack.getMetadata()) ? (new BehaviorProjectileDispense() {
protected IProjectile getProjectileEntity(final World worldIn, final IPosition position) {
return new EntityPotion(worldIn, position.getX(), position.getY(), position.getZ(), stack.copy());
}
protected float func_82498_a() {
return super.func_82498_a() * 0.5F;
}
protected float func_82500_b() {
return super.func_82500_b() * 1.25F;
}
}).dispense(source, stack) : this.field_150843_b.dispense(source, stack);
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.spawn_egg, new BehaviorDefaultDispenseItem() {
public ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata());
final double d0 = source.getX() + (double) enumfacing.getFrontOffsetX();
final double d1 = (float) source.getBlockPos().getY() + 0.2F;
final double d2 = source.getZ() + (double) enumfacing.getFrontOffsetZ();
final Entity entity = ItemMonsterPlacer.spawnCreature(source.getWorld(), stack.getMetadata(), d0, d1, d2);
if (entity instanceof EntityLivingBase && stack.hasDisplayName()) {
entity.setCustomNameTag(stack.getDisplayName());
}
stack.splitStack(1);
return stack;
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.fireworks, new BehaviorDefaultDispenseItem() {
public ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata());
final double d0 = source.getX() + (double) enumfacing.getFrontOffsetX();
final double d1 = (float) source.getBlockPos().getY() + 0.2F;
final double d2 = source.getZ() + (double) enumfacing.getFrontOffsetZ();
final EntityFireworkRocket entityfireworkrocket = new EntityFireworkRocket(source.getWorld(), d0, d1, d2, stack);
source.getWorld().spawnEntityInWorld(entityfireworkrocket);
stack.splitStack(1);
return stack;
}
protected void playDispenseSound(final IBlockSource source) {
source.getWorld().playAuxSFX(1002, source.getBlockPos(), 0);
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.fire_charge, new BehaviorDefaultDispenseItem() {
public ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata());
final IPosition iposition = BlockDispenser.getDispensePosition(source);
final double d0 = iposition.getX() + (double) ((float) enumfacing.getFrontOffsetX() * 0.3F);
final double d1 = iposition.getY() + (double) ((float) enumfacing.getFrontOffsetY() * 0.3F);
final double d2 = iposition.getZ() + (double) ((float) enumfacing.getFrontOffsetZ() * 0.3F);
final World world = source.getWorld();
final Random random = world.rand;
final double d3 = random.nextGaussian() * 0.05D + (double) enumfacing.getFrontOffsetX();
final double d4 = random.nextGaussian() * 0.05D + (double) enumfacing.getFrontOffsetY();
final double d5 = random.nextGaussian() * 0.05D + (double) enumfacing.getFrontOffsetZ();
world.spawnEntityInWorld(new EntitySmallFireball(world, d0, d1, d2, d3, d4, d5));
stack.splitStack(1);
return stack;
}
protected void playDispenseSound(final IBlockSource source) {
source.getWorld().playAuxSFX(1009, source.getBlockPos(), 0);
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.boat, new BehaviorDefaultDispenseItem() {
private final BehaviorDefaultDispenseItem field_150842_b = new BehaviorDefaultDispenseItem();
public ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata());
final World world = source.getWorld();
final double d0 = source.getX() + (double) ((float) enumfacing.getFrontOffsetX() * 1.125F);
final double d1 = source.getY() + (double) ((float) enumfacing.getFrontOffsetY() * 1.125F);
final double d2 = source.getZ() + (double) ((float) enumfacing.getFrontOffsetZ() * 1.125F);
final BlockPos blockpos = source.getBlockPos().offset(enumfacing);
final Material material = world.getBlockState(blockpos).getBlock().getMaterial();
final double d3;
if (Material.water.equals(material)) {
d3 = 1.0D;
} else {
if (!Material.air.equals(material) || !Material.water.equals(world.getBlockState(blockpos.down()).getBlock().getMaterial())) {
return this.field_150842_b.dispense(source, stack);
}
d3 = 0.0D;
}
final EntityBoat entityboat = new EntityBoat(world, d0, d1 + d3, d2);
world.spawnEntityInWorld(entityboat);
stack.splitStack(1);
return stack;
}
protected void playDispenseSound(final IBlockSource source) {
source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0);
}
});
final IBehaviorDispenseItem ibehaviordispenseitem = new BehaviorDefaultDispenseItem() {
private final BehaviorDefaultDispenseItem field_150841_b = new BehaviorDefaultDispenseItem();
public ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final ItemBucket itembucket = (ItemBucket) stack.getItem();
final BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata()));
if (itembucket.tryPlaceContainedLiquid(source.getWorld(), blockpos)) {
stack.setItem(Items.bucket);
stack.stackSize = 1;
return stack;
} else {
return this.field_150841_b.dispense(source, stack);
}
}
};
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.lava_bucket, ibehaviordispenseitem);
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.water_bucket, ibehaviordispenseitem);
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.bucket, new BehaviorDefaultDispenseItem() {
private final BehaviorDefaultDispenseItem field_150840_b = new BehaviorDefaultDispenseItem();
public ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final World world = source.getWorld();
final BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata()));
final IBlockState iblockstate = world.getBlockState(blockpos);
final Block block = iblockstate.getBlock();
final Material material = block.getMaterial();
final Item item;
if (Material.water.equals(material) && block instanceof BlockLiquid && iblockstate.getValue(BlockLiquid.LEVEL).intValue() == 0) {
item = Items.water_bucket;
} else {
if (!Material.lava.equals(material) || !(block instanceof BlockLiquid) || iblockstate.getValue(BlockLiquid.LEVEL).intValue() != 0) {
return super.dispenseStack(source, stack);
}
item = Items.lava_bucket;
}
world.setBlockToAir(blockpos);
if (--stack.stackSize == 0) {
stack.setItem(item);
stack.stackSize = 1;
} else if (((TileEntityDispenser) source.getBlockTileEntity()).addItemStack(new ItemStack(item)) < 0) {
this.field_150840_b.dispense(source, new ItemStack(item));
}
return stack;
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.flint_and_steel, new BehaviorDefaultDispenseItem() {
private boolean field_150839_b = true;
protected ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final World world = source.getWorld();
final BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata()));
if (world.isAirBlock(blockpos)) {
world.setBlockState(blockpos, Blocks.fire.getDefaultState());
if (stack.attemptDamageItem(1, world.rand)) {
stack.stackSize = 0;
}
} else if (world.getBlockState(blockpos).getBlock() == Blocks.tnt) {
Blocks.tnt.onBlockDestroyedByPlayer(world, blockpos, Blocks.tnt.getDefaultState().withProperty(BlockTNT.EXPLODE, Boolean.valueOf(true)));
world.setBlockToAir(blockpos);
} else {
this.field_150839_b = false;
}
return stack;
}
protected void playDispenseSound(final IBlockSource source) {
if (this.field_150839_b) {
source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0);
} else {
source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0);
}
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.dye, new BehaviorDefaultDispenseItem() {
private boolean field_150838_b = true;
protected ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
if (EnumDyeColor.WHITE == EnumDyeColor.byDyeDamage(stack.getMetadata())) {
final World world = source.getWorld();
final BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata()));
if (ItemDye.applyBonemeal(stack, world, blockpos)) {
if (!world.isRemote) {
world.playAuxSFX(2005, blockpos, 0);
}
} else {
this.field_150838_b = false;
}
return stack;
} else {
return super.dispenseStack(source, stack);
}
}
protected void playDispenseSound(final IBlockSource source) {
if (this.field_150838_b) {
source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0);
} else {
source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0);
}
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Item.getItemFromBlock(Blocks.tnt), new BehaviorDefaultDispenseItem() {
protected ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final World world = source.getWorld();
final BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata()));
final EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(world, (double) blockpos.getX() + 0.5D, blockpos.getY(), (double) blockpos.getZ() + 0.5D, null);
world.spawnEntityInWorld(entitytntprimed);
world.playSoundAtEntity(entitytntprimed, "game.tnt.primed", 1.0F, 1.0F);
--stack.stackSize;
return stack;
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Items.skull, new BehaviorDefaultDispenseItem() {
private boolean field_179240_b = true;
protected ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final World world = source.getWorld();
final EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata());
final BlockPos blockpos = source.getBlockPos().offset(enumfacing);
final BlockSkull blockskull = Blocks.skull;
if (world.isAirBlock(blockpos) && blockskull.canDispenserPlace(world, blockpos, stack)) {
if (!world.isRemote) {
world.setBlockState(blockpos, blockskull.getDefaultState().withProperty(BlockSkull.FACING, EnumFacing.UP), 3);
final TileEntity tileentity = world.getTileEntity(blockpos);
if (tileentity instanceof TileEntitySkull) {
if (stack.getMetadata() == 3) {
GameProfile gameprofile = null;
if (stack.hasTagCompound()) {
final NBTTagCompound nbttagcompound = stack.getTagCompound();
if (nbttagcompound.hasKey("SkullOwner", 10)) {
gameprofile = NBTUtil.readGameProfileFromNBT(nbttagcompound.getCompoundTag("SkullOwner"));
} else if (nbttagcompound.hasKey("SkullOwner", 8)) {
final String s = nbttagcompound.getString("SkullOwner");
if (!StringUtils.isNullOrEmpty(s)) {
gameprofile = new GameProfile(null, s);
}
}
}
((TileEntitySkull) tileentity).setPlayerProfile(gameprofile);
} else {
((TileEntitySkull) tileentity).setType(stack.getMetadata());
}
((TileEntitySkull) tileentity).setSkullRotation(enumfacing.getOpposite().getHorizontalIndex() * 4);
Blocks.skull.checkWitherSpawn(world, blockpos, (TileEntitySkull) tileentity);
}
--stack.stackSize;
}
} else {
this.field_179240_b = false;
}
return stack;
}
protected void playDispenseSound(final IBlockSource source) {
if (this.field_179240_b) {
source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0);
} else {
source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0);
}
}
});
BlockDispenser.dispenseBehaviorRegistry.putObject(Item.getItemFromBlock(Blocks.pumpkin), new BehaviorDefaultDispenseItem() {
private boolean field_179241_b = true;
protected ItemStack dispenseStack(final IBlockSource source, final ItemStack stack) {
final World world = source.getWorld();
final BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata()));
final BlockPumpkin blockpumpkin = (BlockPumpkin) Blocks.pumpkin;
if (world.isAirBlock(blockpos) && blockpumpkin.canDispenserPlace(world, blockpos)) {
if (!world.isRemote) {
world.setBlockState(blockpos, blockpumpkin.getDefaultState(), 3);
}
--stack.stackSize;
} else {
this.field_179241_b = false;
}
return stack;
}
protected void playDispenseSound(final IBlockSource source) {
if (this.field_179241_b) {
source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0);
} else {
source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0);
}
}
});
}
/**
* Registers blocks, items, stats, etc.
*/
public static void register() {
if (!alreadyRegistered) {
alreadyRegistered = true;
if (LOGGER.isDebugEnabled()) {
redirectOutputToLog();
}
Block.registerBlocks();
BlockFire.init();
Item.registerItems();
StatList.init();
registerDispenserBehaviors();
}
}
/**
* redirect standard streams to logger
*/
private static void redirectOutputToLog() {
System.setErr(new LoggingPrintStream("STDERR", System.err));
System.setOut(new LoggingPrintStream("STDOUT", SYSOUT));
}
public static void printToSYSOUT(final String p_179870_0_) {
SYSOUT.println(p_179870_0_);
}
}
| 412 | 0.950459 | 1 | 0.950459 | game-dev | MEDIA | 0.986122 | game-dev | 0.898103 | 1 | 0.898103 |
citizenfx/fivem | 8,256 | code/components/gta-core-ny/src/GameInit.cpp | #include "StdInc.h"
#include "GameInit.h"
#include "Text.h"
#include "Hooking.h"
#include "CrossLibraryInterfaces.h"
#include <ICoreGameInit.h>
static bool* g_preventSaveLoading;
bool GameInit::GetGameLoaded()
{
auto ptr = *hook::get_pattern<BYTE*>("8B 4C 24 04 33 C0 85 C9 0F 94 C0", 13);
return !*ptr;
//return !(*(uint8_t*)0xF22B3C);
}
void GameInit::LoadGameFirstLaunch(bool (*callBeforeLoad)())
{
assert(!GameInit::GetGameLoaded());
static auto skipLoadscreenFrame = *hook::get_pattern<BYTE*>("55 8B EC 83 E4 F8 83 EC 20 80 3D ? ? ? ? 00 53 55", 0x1F);
static auto loadscreenState = *hook::get_pattern<DWORD*>("83 f8 31 74 ? 83 f8 3e 75 1a", 25);
*(DWORD*)loadscreenState = 6;
if (callBeforeLoad)
{
static bool(*preLoadCB)();
preLoadCB = callBeforeLoad;
OnPreGameLoad.Connect([]()
{
while (!preLoadCB())
{
*(BYTE*)skipLoadscreenFrame = 0;
MSG msg;
while (PeekMessage(&msg, 0, 0, 0, TRUE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
});
}
OnGameRequestLoad();
}
#if we_do_want_loading_tune
struct LoadingTune
{
void StartLoadingTune();
};
void WRAPPER LoadingTune::StartLoadingTune()
{
EAXJMP(0x7B9980);
}
static LoadingTune& loadingTune = *(LoadingTune*)0x10F85B0;
#endif
GameInit::GameInit()
{
}
static hook::cdecl_stub<void* (int, int, int)> _initLoadingScreens([]()
{
return hook::get_pattern("83 EC 10 80 3D ? ? ? ? 00 53 56 8A FA");
});
static bool* dontProcessTheGame;
void GameInit::SetLoadScreens()
{
static auto loadScreensEnabled = *hook::get_pattern<uint8_t*>("75 11 85 F6 6A 00", -5);
// disable load screens if they're already ongoing
hook::put<uint8_t>(loadScreensEnabled, 0);
_initLoadingScreens(0, 0, 0);
if (Instance<ICoreGameInit>::Get()->GetGameLoaded())
{
*dontProcessTheGame = true;
*g_preventSaveLoading = true;
}
hook::put<uint8_t>(loadScreensEnabled, 1);
#if we_do_want_loading_tune
loadingTune.StartLoadingTune();
#endif
}
static bool g_shouldSwitchToCustomLoad;
static rage::grcTexture* g_customLoad;
rage::grcTexture* GameInit::GetLastCustomLoadTexture()
{
return g_customLoad;
}
void GameInit::PrepareSwitchToCustomLoad(rage::grcTexture* texture)
{
// set our local flag too
g_shouldSwitchToCustomLoad = true;
g_customLoad = texture;
}
bool GameInit::ShouldSwitchToCustomLoad()
{
if (g_shouldSwitchToCustomLoad)
{
g_shouldSwitchToCustomLoad = false;
return true;
}
return false;
}
static hook::cdecl_stub<void(const char*, bool, bool, int)> _setTextForLoadscreen([]()
{
return hook::get_pattern("CC 0F B6 ? ? ? ? ? FF 74 24 04 33 C9 38", 1);
});
bool* stopNetwork;
static hook::cdecl_stub<void()> _leaveGame([]()
{
return hook::get_pattern("A1 ? ? ? ? 83 F8 0C 74 34");
});
static bool g_ignoreNextGracefulDeath;
void GameInit::KillNetwork(const wchar_t* reason)
{
// no overkill please
if (*stopNetwork)
{
return;
}
// #TODOLIBERTY: ?
//g_hooksDLL->SetDisconnectSafeguard(false);
// special case for graceful kill
if (reason == (wchar_t*)1)
{
if (g_ignoreNextGracefulDeath)
{
g_ignoreNextGracefulDeath = false;
return;
}
_leaveGame();
return;
}
if (reason != nullptr)
{
TheText->SetCustom("CIT_NET_KILL_REASON", reason);
_setTextForLoadscreen("CIT_NET_KILL_REASON", true, false, -1);
static char smallReason[8192];
wcstombs(smallReason, reason, _countof(smallReason));
g_ignoreNextGracefulDeath = true;
OnKillNetwork(smallReason);
}
*stopNetwork = true;
}
bool* reloadGameNextFrame;
void GameInit::ReloadGame()
{
//((void(*)())0x40ACE0)();
//((void(*)())0x40B180)();
*reloadGameNextFrame = true;
tryDisconnectFlag = 2;
}
void GameInit::SetPreventSavePointer(bool* preventSaveValue)
{
g_preventSaveLoading = preventSaveValue;
}
static void ToggleBackGameProcess()
{
dontProcessTheGame = false;
g_preventSaveLoading = false;
}
static uintptr_t origToggleBack;
static void __declspec(naked) ToggleBackGameProcessStub()
{
__asm
{
// preserve ecx and call
push ecx
call ToggleBackGameProcess
pop ecx
// jump back to original
push origToggleBack
retn
}
}
static hook::cdecl_stub<void* ()> _unloadStreamedFonts([]()
{
return hook::get_pattern("83 3D ? ? ? ? FF 74 ? 6A FF");
});
void GameInit::MurderGame()
{
// unload streamed fonts
_unloadStreamedFonts();
//((void(*)())0x7F9260)();
}
#include <NetLibrary.h>
#include <GameFlags.h>
#include <nutsnbolts.h>
NetLibrary* g_netLibrary;
GameInit* g_gameInit;
static InitFunction initFunction([]()
{
g_gameInit = new GameInit();
// create ICoreGameInit instance
Instance<ICoreGameInit>::Set(g_gameInit);
NetLibrary::OnNetLibraryCreate.Connect([](NetLibrary* netLibrary)
{
g_netLibrary = netLibrary;
g_netLibrary->OnBuildMessage.Connect([](const std::function<void(uint32_t, const char*, int)>& writeReliable)
{
//if (*(BYTE*)0x18A82FD) // is server running
if (*(BYTE*)hook::get_pattern<char>("0F 86 ? ? ? ? 6A FF 6A 00 6A 01", -33))
{
auto base = g_netLibrary->GetServerBase();
writeReliable(0xB3EA30DE, (char*)&base, sizeof(base));
}
});
g_netLibrary->OnInitReceived.Connect([](NetAddress server)
{
GameFlags::ResetFlags();
/*nui::SetMainUI(false);
nui::DestroyFrame("mpMenu");*/
//m_connectionState = CS_DOWNLOADING;
if (!g_gameInit->GetGameLoaded())
{
g_gameInit->SetLoadScreens();
}
else
{
g_gameInit->SetLoadScreens();
// unlock the mutex as we'll reenter here
//g_netFrameMutex.unlock();
g_netLibrary->Death();
//g_netFrameMutex.lock();
g_netLibrary->Resurrection();
g_gameInit->ReloadGame();
}
});
g_netLibrary->OnAttemptDisconnect.Connect([](const char*)
{
g_gameInit->KillNetwork((const wchar_t*)1);
});
g_netLibrary->OnFinalizeDisconnect.Connect([](NetAddress address)
{
GameFlags::ResetFlags();
GameInit::MurderGame();
});
OnGameFrame.Connect([]()
{
g_netLibrary->RunFrame();
});
});
});
static HookFunction hookFunction([]()
{
reloadGameNextFrame = *(bool**)(hook::get_call(hook::get_pattern<char>("6a 00 6a 20 6a 01 50 6a 00", 50)) + 0x16);
stopNetwork = *hook::get_pattern<bool*>("83 f8 0e 74 34", -9);
dontProcessTheGame = *hook::get_pattern<bool*>("EB 26 6A 01 6A 00 6A 00 B9", 19);
// weird jump because of weird random floats? probably for fading anyway...
hook::nop(hook::pattern("F6 C4 44 0F 8A ? ? ? ? 80 3D ? ? ? ? 00").count(2).get(1).get<void*>(3), 6);
// some function that resets to/undoes weird loading text state rather than continuing on our nice loading screens (during the 'faux game process' state)
hook::nop(hook::get_pattern("83 3D ? ? ? ? 01 C6 05 ? ? ? ? 00", -71), 5);
// hook to reset processing the game after our load caller finishes
//hook::jump(0x420FA2, ToggleBackGameProcess);
{
auto location = hook::get_pattern("6A 00 68 FF 00 00 00 68 E8 03 00 00 B9", 17);
hook::set_call(&origToggleBack, location);
hook::call(location, ToggleBackGameProcessStub);
}
// unused byte which is set to 0 during loading
hook::put<uint8_t>(*hook::get_pattern<BYTE*>("8B 4C 24 04 33 C0 85 C9 0F 94 C0", 13), 1);
// LoadGameNow argument 'reload game fully, even if episodes didn't change' in one caller, to be specific the one we actually use indirectly above as the script flag uses it
/*hook::put<uint8_t>(0x420F91, true);
// other callers for this stuff
hook::put<uint8_t>(0x420FD9, 1);
hook::put<uint8_t>(0x420EAB, 1);
hook::put<uint8_t>(0x420F33, 1);*/
// don't load loadscreens at the start
hook::nop(hook::get_pattern("6A 00 32 D2 B1 01", 6), 5);
// don't wait for loadscreens at the start
hook::put<uint8_t>(hook::get_pattern("80 3D ? ? ? ? 00 B9 01 00 00 00 0F 45 C1 80 3D", -23), 0xEB);
// always redo game object variables
//hook::nop(0x4205C5, 2);
// silly people doing silly things (related to loadGameNow call types)
{
auto location = hook::get_pattern<char>("6A 00 68 FF 00 00 00 68 E8 03 00 00 B9");
hook::nop(location - 0x45, 2);
hook::nop(location - 0x3B, 2);
}
hook::nop(hook::get_pattern("6A 00 6A 00 0F 84 ? ? ? ? 8B", 20), 6);
hook::nop(hook::get_pattern("6A 00 6A 00 68 C8 00 00 00 E8 ? ? ? ? 5E 5B", 24), 2);
});
fwEvent<const char*> OnKillNetwork;
fwEvent<> OnPreGameLoad;
fwEvent<> OnKillNetworkDone;
| 412 | 0.869814 | 1 | 0.869814 | game-dev | MEDIA | 0.683009 | game-dev | 0.961619 | 1 | 0.961619 |
rust-gamedev/rust-game-ports | 2,324 | bunner-macroquad/src/car.rs | use crate::{actor::Actor, mover::Mover, position::Position, resources::Resources};
use macroquad::{
audio::play_sound_once,
prelude::{collections::storage, draw_texture, WHITE},
rand::{self, ChooseRandom},
};
use std::collections::HashSet;
#[derive(Clone)]
pub struct Car {
dx: i32,
position: Position,
image_index: usize,
played_sounds: HashSet<CarSound>,
}
impl Mover for Car {
fn dx(&self) -> i32 {
self.dx
}
}
impl Actor for Car {
fn update(&mut self) {
self.position.x += self.dx;
}
fn draw(&self, offset_x: i32, offset_y: i32) {
let image = *storage::get::<Resources>()
.car_textures
.get(self.image_index)
.unwrap();
draw_texture(
image,
(self.position.x + offset_x) as f32 - image.width() / 2.,
(self.position.y + offset_y) as f32 - image.height(),
WHITE,
);
}
fn x(&self) -> i32 {
self.position.x
}
fn y(&self) -> i32 {
self.position.y
}
fn width(&self) -> i32 {
90
}
}
impl Car {
pub fn new(dx: i32, position: Position) -> Self {
let image_index = if dx < 0 {
*vec![0, 2, 4].choose().unwrap()
} else {
*vec![1, 3, 5].choose().unwrap()
};
Self {
dx,
position,
image_index,
played_sounds: HashSet::new(),
}
}
pub fn play_sound(&mut self, sound: CarSound) {
if self.played_sounds.insert(sound.clone()) {
match sound {
CarSound::Zoom => {
let rnd = rand::gen_range::<usize>(0, 6);
play_sound_once(storage::get::<Resources>().zoom_sounds[rnd]);
}
CarSound::Honk => {
let rnd = rand::gen_range::<usize>(0, 4);
play_sound_once(storage::get::<Resources>().honk_sounds[rnd]);
}
}
}
}
}
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
pub enum CarSound {
Zoom,
Honk,
}
pub struct TrafficSound {
pub y_offset: i32,
pub sound: CarSound,
}
impl TrafficSound {
pub fn new(y_offset: i32, sound: CarSound) -> Self {
TrafficSound { y_offset, sound }
}
}
| 412 | 0.627147 | 1 | 0.627147 | game-dev | MEDIA | 0.718927 | game-dev,audio-video-media | 0.974887 | 1 | 0.974887 |
alistairrutherford/libgdx-demos | 5,054 | simple-shooter/core/src/com/netthreads/gdx/app/layer/PulseLayer.java | /*
* -----------------------------------------------------------------------
* Copyright 2012 - Alistair Rutherford - www.netthreads.co.uk
* -----------------------------------------------------------------------
*
* 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 com.netthreads.gdx.app.layer;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Pool;
import com.netthreads.gdx.app.definition.AppEvents;
import com.netthreads.gdx.app.definition.AppTextureDefinitions;
import com.netthreads.gdx.app.sprite.PulseSprite;
import com.netthreads.libgdx.director.AppInjector;
import com.netthreads.libgdx.director.Director;
import com.netthreads.libgdx.event.ActorEvent;
import com.netthreads.libgdx.event.ActorEventObserver;
import com.netthreads.libgdx.scene.Layer;
import com.netthreads.libgdx.texture.TextureCache;
import com.netthreads.libgdx.texture.TextureDefinition;
/**
* Scene layer.
*
*/
public class PulseLayer extends Layer implements ActorEventObserver
{
private static final int INITIAL_SPRITE_CAPACITY = 20;
public static final float FRAME_DURATION = 0.2f;
// -------------------------------------------------------------------
// Sprite pool.
// -------------------------------------------------------------------
private Pool<PulseSprite> pool = new Pool<PulseSprite>(INITIAL_SPRITE_CAPACITY)
{
@Override
protected PulseSprite newObject()
{
TextureDefinition definition = textureCache.getDefinition(AppTextureDefinitions.TEXTURE_PULSE);
TextureRegion textureRegion = textureCache.getTexture(definition);
PulseSprite sprite = new PulseSprite(textureRegion, definition.getRows(), definition.getCols(), FRAME_DURATION);
return sprite;
}
};
/**
* The one and only director.
*/
private Director director;
/**
* Singletons.
*/
private TextureCache textureCache;
/**
* Create pulse group layer.
*
* @param stage
*/
public PulseLayer(float width, float height)
{
setWidth(width);
setHeight(height);
director = AppInjector.getInjector().getInstance(Director.class);
textureCache = AppInjector.getInjector().getInstance(TextureCache.class);
}
/**
* Called when layer is part of visible view but not yet displayed.
*
*/
@Override
public void enter()
{
// Add this as an event observer.
director.registerEventHandler(this);
}
/**
* Called when layer is no longer part of visible view.
*
*/
@Override
public void exit()
{
cleanup();
// Remove this as an event observer.
director.deregisterEventHandler(this);
}
/**
* Pooled layers need cleanup view elements.
*
*/
private void cleanup()
{
int size = getChildren().size;
while (size > 0)
{
Actor actor = getChildren().get(--size);
removeActor(actor);
}
}
/**
* Event handler will listen for pulse fire event and kick off pulse when one is received.
*
* Event handler will listen for signal that pulse is finished and remove it from view.
*
*/
@Override
public boolean handleEvent(ActorEvent event)
{
boolean handled = false;
switch (event.getId())
{
case AppEvents.EVENT_START_PULSE:
handleStartPulse(event.getActor());
handled = true;
break;
case AppEvents.EVENT_END_PULSE:
handleEndPulse(event.getActor());
handled = true;
break;
default:
break;
}
return handled;
}
/**
* Launch a sprite from pool (if one available).
*
* @param source
* The source actor.
*/
private void handleStartPulse(Actor source)
{
// Get free sprite from pool.
PulseSprite sprite = pool.obtain();
// The starting position of pulse is source of 'fire pulse' i.e. our
// ship.
float x = source.getX() + source.getWidth() / 2 - sprite.getWidth() / 2;
float y = source.getY() + source.getHeight() / 2;
// if valid then add it else re-pool.
if ((x > 0 && y > 0) && (x < this.getWidth() && y < this.getHeight()))
{
// Add to view.
addActor(sprite);
// DO THIS AFTER ADDING TO VIEW.
sprite.run(x, y);
}
else
{
pool.free(sprite);
}
}
/**
* Handles pulse action complete.
*
* @param source
* The source actor.
*/
public void handleEndPulse(Actor source)
{
removeActor(source);
}
/**
* We override the removeActor to ensure we clear actions and re-pool item.
*
*/
@Override
public boolean removeActor(Actor actor)
{
super.removeActor(actor);
actor.clearActions();
pool.free((PulseSprite) actor);
return true;
}
}
| 412 | 0.582843 | 1 | 0.582843 | game-dev | MEDIA | 0.885828 | game-dev | 0.890763 | 1 | 0.890763 |
ReikaKalseki/RotaryCraft | 5,039 | TileEntities/World/TileEntityLamp.java | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.RotaryCraft.TileEntities.World;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import Reika.DragonAPI.Base.OneSlotMachine;
import Reika.DragonAPI.Instantiable.Data.BlockStruct.BlockArray;
import Reika.DragonAPI.Instantiable.Data.Immutable.Coordinate;
import Reika.DragonAPI.Interfaces.TileEntity.BreakAction;
import Reika.DragonAPI.Interfaces.TileEntity.InertIInv;
import Reika.RotaryCraft.Auxiliary.Interfaces.RangedEffect;
import Reika.RotaryCraft.Base.TileEntity.TileEntitySpringPowered;
import Reika.RotaryCraft.Registry.BlockRegistry;
import Reika.RotaryCraft.Registry.MachineRegistry;
public class TileEntityLamp extends TileEntitySpringPowered implements InertIInv, RangedEffect, OneSlotMachine, BreakAction {
private BlockArray light = new BlockArray();
private boolean canlight;
public static final int MAXRANGE = 12;
@Override
protected void animateWithTick(World world, int x, int y, int z) {
}
@Override
public MachineRegistry getTile() {
return MachineRegistry.LAMP;
}
@Override
public boolean hasModelTransparency() {
return false;
}
@Override
public int getRedstoneOverride() {
return 0;
}
@Override
public void updateEntity(World world, int x, int y, int z, int meta) {
boolean red = this.hasRedstoneSignal();
if (!red)
this.updateCoil();
if (world.isRemote)
return;
if (red)
canlight = false;
if (!canlight) {
this.goDark();
return;
}
if (light.isEmpty()) {
for (int i = 1; i <= this.getRange(); i++) {
if (this.canEditAt(world, x+i, y, z))
light.addBlockCoordinate(x+i, y, z);
if (this.canEditAt(world, x, y+i, z))
light.addBlockCoordinate(x, y+i, z);
if (this.canEditAt(world, x, y, z+i))
light.addBlockCoordinate(x, y, z+i);
if (this.canEditAt(world, x-i, y, z))
light.addBlockCoordinate(x-i, y, z);
if (this.canEditAt(world, x, y-i, z))
light.addBlockCoordinate(x, y-i, z);
if (this.canEditAt(world, x, y, z-i))
light.addBlockCoordinate(x, y, z-i);
}
for (int r = 2; r <= this.getRange()*0.8; r += 2) {
if (this.canEditAt(world, x+r, y, z+r))
light.addBlockCoordinate(x+r, y, z+r);
if (this.canEditAt(world, x-r, y, z+r))
light.addBlockCoordinate(x-r, y, z+r);
if (this.canEditAt(world, x+r, y, z-r))
light.addBlockCoordinate(x+r, y, z-r);
if (this.canEditAt(world, x-r, y, z-r))
light.addBlockCoordinate(x-r, y, z-r);
if (this.canEditAt(world, x+r, y+r, z+r))
light.addBlockCoordinate(x+r, y+r, z+r);
if (this.canEditAt(world, x-r, y+r, z+r))
light.addBlockCoordinate(x-r, y+r, z+r);
if (this.canEditAt(world, x+r, y+r, z-r))
light.addBlockCoordinate(x+r, y+r, z-r);
if (this.canEditAt(world, x-r, y+r, z-r))
light.addBlockCoordinate(x-r, y+r, z-r);
if (this.canEditAt(world, x+r, y-r, z+r))
light.addBlockCoordinate(x+r, y-r, z+r);
if (this.canEditAt(world, x-r, y-r, z+r))
light.addBlockCoordinate(x-r, y-r, z+r);
if (this.canEditAt(world, x+r, y-r, z-r))
light.addBlockCoordinate(x+r, y-r, z-r);
if (this.canEditAt(world, x-r, y-r, z-r))
light.addBlockCoordinate(x-r, y-r, z-r);
}
return;
}
//int[] xyz = light.getNextAndMoveOn();
for (int n = 0; n < light.getSize(); n++) {
Coordinate c = light.getNthBlock(n);
if (c.getBlock(world) == Blocks.air)
c.setBlock(world, BlockRegistry.LIGHT.getBlockInstance(), 15);
worldObj.func_147451_t(c.xCoord, c.yCoord, c.zCoord);
}
}
public boolean canEditAt(World world, int x, int y, int z) {
Block id = world.getBlock(x, y, z);
return id == Blocks.air || id.isAir(world, x, y, z);
}
private void goDark() {
for (int n = 0; n < light.getSize(); n++) {
Coordinate c = light.getNthBlock(n);
if (c.getBlock(worldObj) == BlockRegistry.LIGHT.getBlockInstance())
c.setBlock(worldObj, Blocks.air);
worldObj.func_147451_t(c.xCoord, c.yCoord, c.zCoord);
}
}
private void updateCoil() {
if (!this.hasCoil()) {
canlight = false;
return;
}
tickcount++;
if (tickcount > this.getUnwindTime()) {
ItemStack is = this.getDecrementedCharged();
inv[0] = is;
tickcount = 0;
}
canlight = true;
}
@Override
public int getRange() {
return this.getMaxRange();
}
@Override
public int getMaxRange() {
return MAXRANGE;
}
private void clearAll() {
for (int k = 0; k < light.getSize(); k++) {
Coordinate c = light.getNthBlock(k);
c.setBlock(worldObj, Blocks.air);
}
}
@Override
public int getBaseDischargeTime() {
return 120;
}
@Override
public void breakBlock() {
this.clearAll();
}
}
| 412 | 0.85348 | 1 | 0.85348 | game-dev | MEDIA | 0.85224 | game-dev | 0.911096 | 1 | 0.911096 |
fulpstation/fulpstation | 9,204 | code/modules/mob/living/basic/cult/constructs/harvester.dm | /mob/living/basic/construct/harvester
name = "Harvester"
real_name = "Harvester"
desc = "A long, thin construct built to herald Nar'Sie's rise. It'll be all over soon."
icon_state = "harvester"
icon_living = "harvester"
maxHealth = 40
health = 40
sight = SEE_MOBS
melee_damage_lower = 15
melee_damage_upper = 20
attack_verb_continuous = "butchers"
attack_verb_simple = "butcher"
attack_sound = 'sound/items/weapons/bladeslice.ogg'
attack_vis_effect = ATTACK_EFFECT_SLASH
construct_spells = list(
/datum/action/cooldown/spell/aoe/area_conversion,
/datum/action/cooldown/spell/forcewall/cult,
)
playstyle_string = "<B>You are a Harvester. You are incapable of directly killing humans, \
but your attacks will remove their limbs: Bring those who still cling to this world \
of illusion back to the Geometer so they may know Truth. Your form and any you are \
pulling can pass through runed walls effortlessly.</B>"
can_repair = TRUE
slowed_by_drag = FALSE
/mob/living/basic/construct/harvester/Initialize(mapload)
. = ..()
grant_abilities()
/mob/living/basic/construct/harvester/proc/grant_abilities()
AddElement(/datum/element/wall_walker, /turf/closed/wall/mineral/cult)
AddComponent(\
/datum/component/amputating_limbs,\
surgery_time = 0,\
surgery_verb = "slicing",\
minimum_stat = CONSCIOUS,\
)
var/datum/action/innate/seek_prey/seek = new(src)
seek.Grant(src)
seek.Activate()
/// If the attack is a limbless carbon, abort the attack, paralyze them, and get a special message from Nar'Sie.
/mob/living/basic/construct/harvester/resolve_unarmed_attack(atom/attack_target, list/modifiers)
if(!iscarbon(attack_target))
return ..()
var/mob/living/carbon/carbon_target = attack_target
for(var/obj/item/bodypart/limb as anything in carbon_target.bodyparts)
if(limb.body_part == HEAD || limb.body_part == CHEST)
continue
return ..() //if any arms or legs exist, attack
carbon_target.Paralyze(6 SECONDS)
visible_message(span_danger("[src] knocks [carbon_target] down!"))
if(theme == THEME_CULT)
to_chat(src, span_cult_large("\"Bring [carbon_target.p_them()] to me.\""))
/datum/action/innate/seek_master
name = "Seek your Master"
desc = "You and your master share a soul-link that informs you of their location"
background_icon_state = "bg_demon"
overlay_icon_state = "bg_demon_border"
buttontooltipstyle = "cult"
button_icon = 'icons/mob/actions/actions_cult.dmi'
button_icon_state = "cult_mark"
/// Where is nar nar? Are we even looking?
var/tracking = FALSE
/// The construct we're attached to
var/mob/living/basic/construct/the_construct
/datum/action/innate/seek_master/Grant(mob/living/player)
the_construct = player
..()
/datum/action/innate/seek_master/Activate()
var/datum/antagonist/cult/cult_status = owner.mind.has_antag_datum(/datum/antagonist/cult)
if(!cult_status)
return
var/datum/objective/eldergod/summon_objective = locate() in cult_status.cult_team.objectives
if(summon_objective.check_completion())
the_construct.construct_master = cult_status.cult_team.blood_target
if(!the_construct.construct_master)
to_chat(the_construct, span_cult_italic("You have no master to seek!"))
the_construct.seeking = FALSE
return
if(tracking)
tracking = FALSE
the_construct.seeking = FALSE
to_chat(the_construct, span_cult_italic("You are no longer tracking your master."))
return
else
tracking = TRUE
the_construct.seeking = TRUE
to_chat(the_construct, span_cult_italic("You are now tracking your master."))
/datum/action/innate/seek_prey
name = "Seek the Harvest"
desc = "None can hide from Nar'Sie, activate to track a survivor attempting to flee the red harvest!"
button_icon = 'icons/mob/actions/actions_cult.dmi'
background_icon_state = "bg_demon"
overlay_icon_state = "bg_demon_border"
buttontooltipstyle = "cult"
button_icon_state = "cult_mark"
/datum/action/innate/seek_prey/Activate()
if(GLOB.cult_narsie == null)
return
var/mob/living/basic/construct/harvester/the_construct = owner
if(the_construct.seeking)
desc = "None can hide from Nar'Sie, activate to track a survivor attempting to flee the red harvest!"
button_icon_state = "cult_mark"
the_construct.seeking = FALSE
to_chat(the_construct, span_cult_italic("You are now tracking Nar'Sie, return to reap the harvest!"))
return
if(!LAZYLEN(GLOB.cult_narsie.souls_needed))
to_chat(the_construct, span_cult_italic("Nar'Sie has completed her harvest!"))
return
the_construct.construct_master = pick(GLOB.cult_narsie.souls_needed)
var/mob/living/real_target = the_construct.construct_master //We can typecast this way because Narsie only allows /mob/living into the souls list
to_chat(the_construct, span_cult_italic("You are now tracking your prey, [real_target.real_name] - harvest [real_target.p_them()]!"))
desc = "Activate to track Nar'Sie!"
button_icon_state = "sintouch"
the_construct.seeking = TRUE
/mob/living/basic/construct/harvester/heretic
name = "Rusted Harvester"
real_name = "Rusted Harvester"
desc = "A long, thin, decrepit construct originally built to herald Nar'Sie's rise, corrupted and rusted by the forces of the Mansus to spread its will instead."
icon_state = "harvester"
icon_living = "harvester"
construct_spells = list(
/datum/action/cooldown/spell/aoe/rust_conversion,
/datum/action/cooldown/spell/pointed/rust_construction,
)
can_repair = FALSE
slowed_by_drag = FALSE
faction = list(FACTION_HERETIC)
maxHealth = 45
health = 45
melee_damage_lower = 20
melee_damage_upper = 25
// Dim green
lighting_cutoff_red = 10
lighting_cutoff_green = 20
lighting_cutoff_blue = 5
playstyle_string = span_bold("You are a Rusted Harvester, built to serve the Sanguine Apostate, twisted to work the will of the Mansus. You are fragile and weak, but you rend cultists (only) apart on each attack. Follow your Master's orders!")
theme = THEME_HERETIC
/mob/living/basic/construct/harvester/heretic/Initialize(mapload)
. = ..()
ADD_TRAIT(src, TRAIT_MANSUS_TOUCHED, REF(src))
add_filter("rusted_harvester", 3, list("type" = "outline", "color" = COLOR_GREEN, "size" = 2, "alpha" = 40))
RegisterSignal(src, COMSIG_MIND_TRANSFERRED, TYPE_PROC_REF(/datum/mind, enslave_mind_to_creator))
RegisterSignal(src, COMSIG_MOB_ENSLAVED_TO, PROC_REF(link_master))
/mob/living/basic/construct/harvester/heretic/proc/link_master(mob/self, mob/master)
src.construct_master = master
RegisterSignal(construct_master, COMSIG_LIVING_DEATH, PROC_REF(on_master_death))
SIGNAL_HANDLER
/mob/living/basic/construct/harvester/heretic/proc/on_master_death(mob/self, mob/master)
SIGNAL_HANDLER
to_chat(src, span_userdanger("Your link to the mansus suddenly snaps as your master [construct_master] perishes! Without [construct_master.p_their()] support, your body crumbles..."))
visible_message(span_alert("[src] suddenly crumbles to dust!"))
death()
/mob/living/basic/construct/harvester/heretic/attack_animal(mob/living/simple_animal/user, list/modifiers)
// They're pretty fragile so this is probably necessary to prevent bullshit deaths.
if(user == src)
return
return ..()
/mob/living/basic/construct/harvester/heretic/grant_abilities()
AddElement(/datum/element/wall_walker, or_trait = TRAIT_RUSTY)
AddElement(/datum/element/leeching_walk)
AddComponent(\
/datum/component/amputating_limbs,\
surgery_time = 1.5 SECONDS,\
surgery_verb = "slicing",\
minimum_stat = CONSCIOUS,\
pre_hit_callback = CALLBACK(src, PROC_REF(is_cultist_handler)),\
)
AddComponent(/datum/component/damage_aura,\
range = 3,\
brute_damage = 0.5,\
burn_damage = 0.5,\
toxin_damage = 0.5,\
stamina_damage = 4,\
simple_damage = 1.5,\
immune_factions = list(FACTION_HERETIC),\
damage_message = span_boldwarning("Your body wilts and withers as it comes near [src]'s aura."),\
message_probability = 7,\
current_owner = src,\
)
var/datum/action/innate/seek_master/heretic/seek = new(src)
seek.Grant(src)
seek.Activate()
// These aren't friends they're assholes
// Don't let them be near you!
/mob/living/basic/construct/harvester/heretic/Life(seconds_per_tick, times_fired)
. = ..()
if(!.) //dead or deleted
return
if(!SPT_PROB(7, seconds_per_tick))
return
var/turf/adjacent = get_step(src, pick(GLOB.alldirs))
// 90% chance to be directional, otherwise what we're on top of
var/turf/open/land = (isopenturf(adjacent) && prob(90)) ? adjacent : get_turf(src)
do_rust_heretic_act(land)
if(prob(7))
to_chat(src, span_notice("Eldritch energies emanate from your body."))
/mob/living/basic/construct/harvester/heretic/proc/is_cultist_handler(mob/victim)
return IS_CULTIST(victim)
/datum/action/innate/seek_master/heretic
name = "Seek your Master"
desc = "Use your direct link to the Mansus to sense where your master is located via the arrow on the top-right of your HUD."
button_icon = 'icons/mob/actions/actions_cult.dmi'
background_icon_state = "bg_heretic"
overlay_icon_state = "bg_heretic_border"
tracking = TRUE
/datum/action/innate/seek_master/heretic/New(Target)
. = ..()
the_construct = Target
the_construct.seeking = TRUE
// no real reason for most of this weird oldcode
/datum/action/innate/seek_master/Activate()
return
| 412 | 0.849224 | 1 | 0.849224 | game-dev | MEDIA | 0.986275 | game-dev | 0.95088 | 1 | 0.95088 |
Rexcrazy804/Zaphkiel | 1,668 | users/dots/quickshell/kurukurubar/Data/Config.qml | pragma ComponentBehavior: Bound
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import qs.Data as Dat
Singleton {
id: root
property alias data: jsonData
property alias fgGenProc: generateFg
property string wallFg: ""
FileView {
path: Dat.Paths.config + "/config.json"
watchChanges: true
onAdapterUpdated: writeAdapter()
onFileChanged: reload()
JsonAdapter {
id: jsonData
property bool mousePsystem: false
property bool reservedShell: false
property bool setWallpaper: true
property bool wallFgLayer: false
property string wallSrc: Quickshell.env("HOME") + "/.config/background"
}
}
IpcHandler {
function setWallpaper(path: string) {
path = Qt.resolvedUrl(path);
jsonData.wallSrc = path;
}
target: "config"
}
Process {
id: generateFg
property string script: Dat.Paths.urlToPath(Qt.resolvedUrl("../scripts/extractFg.sh"))
command: ["bash", script, Dat.Paths.urlToPath(jsonData.wallSrc), Dat.Paths.urlToPath(Dat.Paths.cache)]
stdout: SplitParser {
onRead: data => {
if (/\[.*\]/.test(data)) {
console.log(data);
} else if (/FOREGROUND/.test(data)) {
root.wallFg = data.split(" ")[1];
} else {
console.log("[EXT] " + data);
}
}
}
}
Connections {
function onWallFgLayerChanged() {
onWallSrcChanged();
}
function onWallSrcChanged() {
if (jsonData.wallSrc != "" && jsonData.wallFgLayer) {
if (!generateFg.running) {
generateFg.running = true;
}
}
}
target: jsonData
}
}
| 412 | 0.765906 | 1 | 0.765906 | game-dev | MEDIA | 0.394666 | game-dev | 0.909498 | 1 | 0.909498 |
cH1yoi/L4D2-Rinka-Coop-Server | 8,421 | addons/sourcemod/scripting/funcommands/timebomb.sp | /**
* vim: set ts=4 :
* =============================================================================
* SourceMod Basefuncommands Plugin
* Provides TimeBomb functionality
*
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
int g_TimeBombSerial[MAXPLAYERS+1] = { 0, ... };
int g_TimeBombTime[MAXPLAYERS+1] = { 0, ... };
ConVar g_Cvar_TimeBombTicks;
ConVar g_Cvar_TimeBombRadius;
ConVar g_Cvar_TimeBombMode;
void CreateTimeBomb(int client)
{
g_TimeBombSerial[client] = ++g_Serial_Gen;
CreateTimer(1.0, Timer_TimeBomb, client | (g_Serial_Gen << 7), DEFAULT_TIMER_FLAGS);
g_TimeBombTime[client] = g_Cvar_TimeBombTicks.IntValue;
}
void KillTimeBomb(int client)
{
g_TimeBombSerial[client] = 0;
if (IsClientInGame(client))
{
SetEntityRenderColor(client, 255, 255, 255, 255);
}
}
void KillAllTimeBombs()
{
for (int i = 1; i <= MaxClients; i++)
{
KillTimeBomb(i);
}
}
void PerformTimeBomb(int client, int target)
{
if (g_TimeBombSerial[target] == 0)
{
CreateTimeBomb(target);
LogAction(client, target, "\"%L\" set a TimeBomb on \"%L\"", client, target);
}
else
{
KillTimeBomb(target);
SetEntityRenderColor(client, 255, 255, 255, 255);
LogAction(client, target, "\"%L\" removed a TimeBomb on \"%L\"", client, target);
}
}
public Action Timer_TimeBomb(Handle timer, any value)
{
int client = value & 0x7f;
int serial = value >> 7;
if (!IsClientInGame(client)
|| !IsPlayerAlive(client)
|| serial != g_TimeBombSerial[client])
{
KillTimeBomb(client);
return Plugin_Stop;
}
g_TimeBombTime[client]--;
float vec[3];
GetClientEyePosition(client, vec);
if (g_TimeBombTime[client] > 0)
{
int color;
if (g_TimeBombTime[client] > 1)
{
color = RoundToFloor(g_TimeBombTime[client] * (128.0 / g_Cvar_TimeBombTicks.FloatValue));
if (g_BeepSound[0])
{
EmitAmbientSound(g_BeepSound, vec, client, SNDLEVEL_RAIDSIREN);
}
}
else
{
color = 0;
if (g_FinalSound[0])
{
EmitAmbientSound(g_FinalSound, vec, client, SNDLEVEL_RAIDSIREN);
}
}
SetEntityRenderColor(client, 255, 128, color, 255);
char name[MAX_NAME_LENGTH];
GetClientName(client, name, sizeof(name));
PrintCenterTextAll("%t", "Till Explodes", name, g_TimeBombTime[client]);
if (g_BeamSprite > -1 && g_HaloSprite > -1)
{
GetClientAbsOrigin(client, vec);
vec[2] += 10;
TE_SetupBeamRingPoint(vec, 10.0, g_Cvar_TimeBombRadius.FloatValue / 3.0, g_BeamSprite, g_HaloSprite, 0, 15, 0.5, 5.0, 0.0, greyColor, 10, 0);
TE_SendToAll();
TE_SetupBeamRingPoint(vec, 10.0, g_Cvar_TimeBombRadius.FloatValue / 3.0, g_BeamSprite, g_HaloSprite, 0, 10, 0.6, 10.0, 0.5, whiteColor, 10, 0);
TE_SendToAll();
}
return Plugin_Continue;
}
else
{
if (g_ExplosionSprite > -1)
{
TE_SetupExplosion(vec, g_ExplosionSprite, 5.0, 1, 0, g_Cvar_TimeBombRadius.IntValue, 5000);
TE_SendToAll();
}
if (g_BoomSound[0])
{
EmitAmbientSound(g_BoomSound, vec, client, SNDLEVEL_RAIDSIREN);
}
ForcePlayerSuicide(client);
KillTimeBomb(client);
SetEntityRenderColor(client, 255, 255, 255, 255);
if (g_Cvar_TimeBombMode.IntValue > 0)
{
int teamOnly = ((g_Cvar_TimeBombMode.IntValue == 1) ? true : false);
for (int i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i) || !IsPlayerAlive(i) || i == client)
{
continue;
}
if (teamOnly && GetClientTeam(i) != GetClientTeam(client))
{
continue;
}
float pos[3];
GetClientEyePosition(i, pos);
float distance = GetVectorDistance(vec, pos);
if (distance > g_Cvar_TimeBombRadius.FloatValue)
{
continue;
}
int damage = 220;
damage = RoundToFloor(damage * ((g_Cvar_TimeBombRadius.FloatValue - distance) / g_Cvar_TimeBombRadius.FloatValue));
SlapPlayer(i, damage, false);
if (g_ExplosionSprite > -1)
{
TE_SetupExplosion(pos, g_ExplosionSprite, 0.05, 1, 0, 1, 1);
TE_SendToAll();
}
/* ToDo
float dir[3];
SubtractVectors(vec, pos, dir);
TR_TraceRayFilter(vec, dir, MASK_SOLID, RayType_Infinite, TR_Filter_Client);
if (i == TR_GetEntityIndex())
{
int damage = 100;
int radius = g_Cvar_TimeBombRadius.IntValue / 2;
if (distance > radius)
{
distance -= radius;
damage = RoundToFloor(damage * ((radius - distance) / radius));
}
SlapPlayer(i, damage, false);
}
*/
}
}
return Plugin_Stop;
}
}
public void AdminMenu_TimeBomb(TopMenu topmenu,
TopMenuAction action,
TopMenuObject object_id,
int param,
char[] buffer,
int maxlength)
{
if (action == TopMenuAction_DisplayOption)
{
Format(buffer, maxlength, "%T", "TimeBomb player", param);
}
else if (action == TopMenuAction_SelectOption)
{
DisplayTimeBombMenu(param);
}
}
void DisplayTimeBombMenu(int client)
{
Menu menu = new Menu(MenuHandler_TimeBomb);
char title[100];
Format(title, sizeof(title), "%T:", "TimeBomb player", client);
menu.SetTitle(title);
menu.ExitBackButton = true;
AddTargetsToMenu(menu, client, true, true);
menu.Display(client, MENU_TIME_FOREVER);
}
public int MenuHandler_TimeBomb(Menu menu, MenuAction action, int param1, int param2)
{
if (action == MenuAction_End)
{
delete menu;
}
else if (action == MenuAction_Cancel)
{
if (param2 == MenuCancel_ExitBack && hTopMenu)
{
hTopMenu.Display(param1, TopMenuPosition_LastCategory);
}
}
else if (action == MenuAction_Select)
{
char info[32];
int userid, target;
menu.GetItem(param2, info, sizeof(info));
userid = StringToInt(info);
if ((target = GetClientOfUserId(userid)) == 0)
{
PrintToChat(param1, "[SM] %t", "Player no longer available");
}
else if (!CanUserTarget(param1, target))
{
PrintToChat(param1, "[SM] %t", "Unable to target");
}
else
{
char name[MAX_NAME_LENGTH];
GetClientName(target, name, sizeof(name));
PerformTimeBomb(param1, target);
ShowActivity2(param1, "[SM] ", "%t", "Toggled TimeBomb on target", "_s", name);
}
/* Re-draw the menu if they're still valid */
if (IsClientInGame(param1) && !IsClientInKickQueue(param1))
{
DisplayTimeBombMenu(param1);
}
}
return 0;
}
public Action Command_TimeBomb(int client, int args)
{
if (args < 1)
{
ReplyToCommand(client, "[SM] Usage: sm_timebomb <#userid|name>");
return Plugin_Handled;
}
char arg[65];
GetCmdArg(1, arg, sizeof(arg));
char target_name[MAX_TARGET_LENGTH];
int target_list[MAXPLAYERS], target_count;
bool tn_is_ml;
if ((target_count = ProcessTargetString(
arg,
client,
target_list,
MAXPLAYERS,
COMMAND_FILTER_ALIVE,
target_name,
sizeof(target_name),
tn_is_ml)) <= 0)
{
ReplyToTargetError(client, target_count);
return Plugin_Handled;
}
for (int i = 0; i < target_count; i++)
{
PerformTimeBomb(client, target_list[i]);
}
if (tn_is_ml)
{
ShowActivity2(client, "[SM] ", "%t", "Toggled TimeBomb on target", target_name);
}
else
{
ShowActivity2(client, "[SM] ", "%t", "Toggled TimeBomb on target", "_s", target_name);
}
return Plugin_Handled;
}
| 412 | 0.954435 | 1 | 0.954435 | game-dev | MEDIA | 0.825916 | game-dev | 0.938736 | 1 | 0.938736 |
elsong823/HalfSLG | 2,167 | S9/HalfSLG/Assets/HalfSLG/Scripts/Battle/BattleBehaviourSystem/BattleBehaviourChip/BattleStrategyChip.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ELGame.BattleBehaviourSystem
{
public abstract class BattleStrategyChip
:ScriptableObject, IBattleBehaviourChip
{
public abstract string ChipName { get; }
public abstract bool NeedRecordSkillResult { get; }
public abstract BattleBehaviourType BehaviourType { get; }
public List<ScriptableObject> adjustorTransfer;
protected List<IBattleBehaviourChipAdjustor> adjustors;
protected BattleBaseData baseData;
protected BattleBehaviourSystem behaviourSystem;
protected List<BattleBehaviourItem> battleBehaviourItems;
public virtual void Init(BattleBehaviourSystem behaviourSystem, BattleBaseData baseData)
{
this.baseData = baseData;
this.behaviourSystem = behaviourSystem;
battleBehaviourItems = new List<BattleBehaviourItem>(baseData.enemyBattleTeam.battleUnits.Count);
if (adjustorTransfer != null && adjustorTransfer.Count > 0)
{
adjustors = new List<IBattleBehaviourChipAdjustor>();
for (int i = 0; i < adjustorTransfer.Count; i++)
{
if (adjustorTransfer[i] is IBattleBehaviourChipAdjustor)
adjustors.Add(adjustorTransfer[i] as IBattleBehaviourChipAdjustor);
}
}
}
public abstract void CalculateBehaviourItem(List<BattleBehaviourItem> behaviourItems, float weight);
public abstract void RecordSkillResult(BattleUnit from, BattleUnitSkillResult battleUnitSkillResult);
public abstract void ResetChip();
protected void AddToTargetList(List<BattleBehaviourItem> targetList)
{
if (adjustors != null && adjustors.Count > 0)
{
for (int i = 0; i < adjustors.Count; ++i)
{
adjustors[i].AdjustBehaviourItem(battleBehaviourItems);
}
}
targetList.AddRange(battleBehaviourItems);
battleBehaviourItems.Clear();
}
}
} | 412 | 0.824276 | 1 | 0.824276 | game-dev | MEDIA | 0.734494 | game-dev | 0.978984 | 1 | 0.978984 |
harrison314/BouncyHsm | 1,946 | src/Test/Pkcs11Interop.Ext/HighLevelAPI41/MechanismParams/CkSalsa20ChaCha20Polly1305Params.cs | using Pkcs11Interop.Ext.HighLevelAPI.MechanismParams;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pkcs11Interop.Ext.HighLevelAPI41.MechanismParams;
internal class CkSalsa20ChaCha20Polly1305Params : ICkSalsa20ChaCha20Polly1305Params
{
private bool disposedValue;
private CK_SALSA20_CHACHA20_POLY1305_PARAMS lowLevelStruct = new CK_SALSA20_CHACHA20_POLY1305_PARAMS();
public CkSalsa20ChaCha20Polly1305Params(byte[] nonce, byte[]? aadData)
{
this.lowLevelStruct.pNonce = MemoryUtils.MemDup(nonce);
this.lowLevelStruct.ulNonceLen = (uint)nonce.Length;
this.lowLevelStruct.pAAD = IntPtr.Zero;
this.lowLevelStruct.ulAADLen = 0;
if (aadData != null)
{
this.lowLevelStruct.pAAD = MemoryUtils.MemDup(aadData);
this.lowLevelStruct.ulAADLen = (uint)aadData.Length;
}
}
public object ToMarshalableStructure()
{
if (this.disposedValue)
throw new ObjectDisposedException(this.GetType().FullName);
return this.lowLevelStruct;
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
MemoryUtils.MemFreeReset(ref this.lowLevelStruct.pNonce);
MemoryUtils.MemFreeReset(ref this.lowLevelStruct.pAAD);
this.disposedValue = true;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
this.Dispose(disposing: true);
GC.SuppressFinalize(this);
}
~CkSalsa20ChaCha20Polly1305Params()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
this.Dispose(disposing: false);
}
}
| 412 | 0.849994 | 1 | 0.849994 | game-dev | MEDIA | 0.62947 | game-dev | 0.757333 | 1 | 0.757333 |
shxzu/Simp | 3,896 | src/main/java/net/minecraft/network/play/server/S20PacketEntityProperties.java | package net.minecraft.network.play.server;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
public class S20PacketEntityProperties implements Packet<INetHandlerPlayClient>
{
private int entityId;
private final List<S20PacketEntityProperties.Snapshot> field_149444_b = Lists.newArrayList();
public S20PacketEntityProperties()
{
}
public S20PacketEntityProperties(int entityIdIn, Collection<IAttributeInstance> p_i45236_2_)
{
this.entityId = entityIdIn;
for (IAttributeInstance iattributeinstance : p_i45236_2_)
{
this.field_149444_b.add(new S20PacketEntityProperties.Snapshot(iattributeinstance.getAttribute().getAttributeUnlocalizedName(), iattributeinstance.getBaseValue(), iattributeinstance.func_111122_c()));
}
}
public void readPacketData(PacketBuffer buf) throws IOException
{
this.entityId = buf.readVarIntFromBuffer();
int i = buf.readInt();
for (int j = 0; j < i; ++j)
{
String s = buf.readStringFromBuffer(64);
double d0 = buf.readDouble();
List<AttributeModifier> list = Lists.newArrayList();
int k = buf.readVarIntFromBuffer();
for (int l = 0; l < k; ++l)
{
UUID uuid = buf.readUuid();
list.add(new AttributeModifier(uuid, "Unknown synced attribute modifier", buf.readDouble(), buf.readByte()));
}
this.field_149444_b.add(new S20PacketEntityProperties.Snapshot(s, d0, list));
}
}
public void writePacketData(PacketBuffer buf) throws IOException
{
buf.writeVarIntToBuffer(this.entityId);
buf.writeInt(this.field_149444_b.size());
for (S20PacketEntityProperties.Snapshot s20packetentityproperties$snapshot : this.field_149444_b)
{
buf.writeString(s20packetentityproperties$snapshot.func_151409_a());
buf.writeDouble(s20packetentityproperties$snapshot.func_151410_b());
buf.writeVarIntToBuffer(s20packetentityproperties$snapshot.func_151408_c().size());
for (AttributeModifier attributemodifier : s20packetentityproperties$snapshot.func_151408_c())
{
buf.writeUuid(attributemodifier.getID());
buf.writeDouble(attributemodifier.getAmount());
buf.writeByte(attributemodifier.getOperation());
}
}
}
public void processPacket(INetHandlerPlayClient handler)
{
handler.handleEntityProperties(this);
}
public int getEntityId()
{
return this.entityId;
}
public List<S20PacketEntityProperties.Snapshot> func_149441_d()
{
return this.field_149444_b;
}
public class Snapshot
{
private final String field_151412_b;
private final double field_151413_c;
private final Collection<AttributeModifier> field_151411_d;
public Snapshot(String p_i45235_2_, double p_i45235_3_, Collection<AttributeModifier> p_i45235_5_)
{
this.field_151412_b = p_i45235_2_;
this.field_151413_c = p_i45235_3_;
this.field_151411_d = p_i45235_5_;
}
public String func_151409_a()
{
return this.field_151412_b;
}
public double func_151410_b()
{
return this.field_151413_c;
}
public Collection<AttributeModifier> func_151408_c()
{
return this.field_151411_d;
}
}
}
| 412 | 0.799101 | 1 | 0.799101 | game-dev | MEDIA | 0.65554 | game-dev,networking | 0.866995 | 1 | 0.866995 |
mattmatterson111/IS12-Warfare-Two | 2,367 | code/modules/lorepaper/ERT/transport/teleport_turfs.dm | /obj/effect/darkout_teleporter
name = ""
desc = ""
icon = 'icons/hammer/source.dmi'
icon_state = "tools/black"
allowtooltip = FALSE
density = TRUE
invisibility = 101
var/delay = 20
var/id
var/enabled = TRUE
var/list/valid = list() // List of other valid teleporters with the same ID
var/entrance
var/twoway
/obj/effect/darkout_teleporter/CanPass(atom/movable/mover, turf/target, height, air_group)
return TRUE
GLOBAL_LIST_EMPTY(teleports)
/obj/effect/darkout_teleporter/Initialize()
. = ..()
if (!id)
return
if (!GLOB.teleports[id])
GLOB.teleports[id] = list()
GLOB.teleports[id] += src
pop_valid_list()
/obj/effect/darkout_teleporter/proc/pop_valid_list()
if(!islist(valid))
valid = list()
if(length(valid))
valid.Cut()
var/list/group = GLOB.teleports[id]
if (!group)
return
for (var/obj/effect/darkout_teleporter/t in group)
if (t == src)
continue
// Skip if same type (entrance-to-entrance or exit-to-exit)
if (t.entrance == src.entrance)
continue
// Skip if target is not two-way and you're trying to go back
if (!t.twoway && src.entrance == t.entrance)
continue
valid += t
/obj/effect/darkout_teleporter/Crossed(mob/living/user)
if (!enabled || user.doing_something)
return
if (!length(valid))
pop_valid_list()
if(!length(valid))
return // No valid destinations
user.doing_something = TRUE
if (do_after(user, delay, stay_still = TRUE))
var/turf/exit = get_turf(pick(valid))
if (!exit)
user.doing_something = FALSE
return
if (user.pulling)
user.pulling.forceMove(exit)
user.forceMove(exit)
playsound(src, 'sound/effects/ladder.ogg', 75, 1)
playsound(exit, 'sound/effects/ladder.ogg', 75, 1)
user.doing_something = FALSE
/proc/update_teleports(id)
for (var/obj/effect/darkout_teleporter/t in GLOB.teleports[id])
t.pop_valid_list()
/obj/effect/darkout_teleporter/proc/change_id(var/new_id)
// Remove from old group
if (GLOB.teleports[id])
GLOB.teleports[id] -= src
// Force old group to recalculate their valid lists
// Update ID
id = new_id
// Add to new group
if (!GLOB.teleports[id])
GLOB.teleports[id] = list()
GLOB.teleports[id] += src
// Recalculate your list
pop_valid_list()
// If you're twoway, notify others
if (twoway)
for (var/obj/effect/darkout_teleporter/t in GLOB.teleports[id])
if (t != src)
t.pop_valid_list() | 412 | 0.904205 | 1 | 0.904205 | game-dev | MEDIA | 0.869836 | game-dev | 0.990956 | 1 | 0.990956 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.