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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
heavy3/programming-abstractions | 6,005 | 19-inheritance/readerEx.19.06/Nim.cpp | //
// Nim.cpp
//
// This file implements the game-specific methods required to play a game
// of nim.
//
// Most of the code here amounts to elaborations of abstract methods in the
// game engine superclass.
//
// --------------------------------------------------------------------------
// Attribution: "Programming Abstractions in C++" by Eric Roberts
// Chapter 19, Exercise 06 (See also Chapter 9, Exercise 12)
// Stanford University, Autumn Quarter 2012
// http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf
//
// This code relies significantly upon code from Figures 9-5 and 9-6.
// --------------------------------------------------------------------------
//
// Created by Glenn Streiff on 4/7/16 and 3/25/17
// Copyright © 2017 Glenn Streiff. All rights reserved. (derivative work)
//
#include "Nim.h"
using namespace std;
//
// Constructors: Nim
// Usage: Nim game;
// Nim game(depth); // specify resursive depth
// ---------------------------------------------------
// Instantiates the Nim game object.
//
// The second form allows you to override the default recusion
// depth limit when the algorithm is evaluating the game tree
// solution space relative to a given position.
//
// For a game as simple as nim, this is not a practical consideration.
// However if we subclassed the game engine for something like Chess,
// it might be a parameter we want to control.
//
Nim::Nim() {
initGame();
}
Nim::Nim(int recursiveDepth): TwoPlayerGame<NimMove>(recursiveDepth) {
initGame();
}
//
// Method: printInstructions
// Usage: game.printInstructions();
// --------------------------------
// This method explains the rules of the game to the user.
//
void Nim::printInstructions() {
cout << "Welcome to the game of (better) Nim!" << endl << endl;
cout << "In this game, we will start with a pile of" << endl;
cout << N_COINS << " coins on the table. On each turn, you" << endl;
cout << "and I will alternately take between 1 and" << endl;
cout << MAX_MOVE << " coins from the table. The player who" << endl;
cout << "takes the last coin loses." << endl << endl;
}
//
// Method: initGame
// Usage: game.initGame()
// ----------------------
// This is typically invoked by the game engine itself to restore the
// state of play to some initial condition.
//
void Nim::initGame() {
nCoins = N_COINS;
whoseTurn = STARTING_PLAYER;
}
//
// Method: displayGame
// Usage: displayGame();
// ---------------------
// Displays the current state of the game on the output stream.
//
void Nim::displayGame() const {
cout << "There are " << nCoins << " coins in the pile." << endl;
}
//
// Method: displayMove
// Usage: displayMove(move);
// -------------------------
// Updates the display with the results of a player's move.
//
void Nim::displayMove(NimMove move) const {
if (getCurrentPlayer() == COMPUTER) {
cout << "I'll take " << move.nTaken << "." << endl;
}
}
//
// Method: makeMove
// Usage: makeMove(move);
// ----------------------
// Updates the game state by making the given move.
//
void Nim::makeMove(NimMove move) {
nCoins -= move.nTaken;
}
//
// Method: evaluateStaticPosition
// Usage: int rating = evaluateStaticPosition();
// ----------------------------------------------
// Evaluates a particular state in the game without making any further
// recursive calls.
//
// The insight here is that you really don't need fancy recursion to
// discern if the current position is good or not.
//
// If it's your turn and the number of coins on the table is 1 plus some
// multiple of 4, you're pretty much hosed. :-/
//
// Your opponent just needs to keep removing enough coins:
//
// 4 - (# of coins you removed in your last turn)
//
// to maintain the the 1-plus-a-multiple-of-4 condition to win.
//
int Nim::evaluateStaticPosition() {
int r; // rating
r = (nCoins % (MAX_MOVE + 1) == 1) ? LOSING_POSITION : WINNING_POSITION;
return r;
}
//
// Method: retractMove
// Usage: retractMove(move);
// -------------------------
// Retracts a move.
//
void Nim::retractMove(NimMove move) {
nCoins += move.nTaken;
}
//
// Method: generateMoveList
// Usage: generateMoveList(moveList);
// ----------------------------------
// Fills the moveList vector with the legal moves available in the current
// state.
void Nim::generateMoveList(Vector<NimMove> & moveList) const {
if (nCoins < 1) return;
int limit = (nCoins < MAX_MOVE) ? nCoins : MAX_MOVE;
for (int n = 1; n <= limit; n++) {
NimMove move = { .nTaken = n };
moveList += move;
}
}
//
// Method: gameIsOver
// Usage: if (gameIsOver()) . . .
// ------------------------------
// Returns true if the game is over.
bool Nim::gameIsOver() {
return (nCoins <= 1);
}
//
// Method: getUserMove
// Usage: NimMove move = getUserMove();
// ----------------------------------
// Asks the user to enter a move and returns the number of coins taken.
// If the move is not legal, the user is asked to reenter a valid move.
NimMove Nim::getUserMove() {
NimMove move;
while (true) {
move.nTaken = getInteger("How many would you like? ");
int limit = (nCoins < MAX_MOVE) ? nCoins : MAX_MOVE;
if (move.nTaken > 0 && move.nTaken <= limit) return move;
cout << "That's cheating! Please choose a number";
cout << " between 1 and " << limit << "." << endl;
cout << "There are " << nCoins << " coins in the pile." << endl;
}
}
//
// Method: announceResult
// Usage: announceResult();
// ------------------------
// This method announces the final result of the game.
void Nim::announceResult() const {
if (nCoins == 0) {
cout << "You took the last coin. You lose." << endl;
} else {
cout << "There is only one coin left." << endl;
if (whoseTurn == HUMAN) {
cout << "I win." << endl;
} else {
cout << "I lose." << endl;
}
}
}
| 0 | 0.730844 | 1 | 0.730844 | game-dev | MEDIA | 0.759574 | game-dev | 0.737738 | 1 | 0.737738 |
Electrical-Age/ElectricalAge | 1,504 | src/main/java/mods/eln/transparentnode/powerinductor/PowerInductorRender.java | package mods.eln.transparentnode.powerinductor;
import mods.eln.cable.CableRenderType;
import mods.eln.misc.Direction;
import mods.eln.node.transparent.TransparentNodeDescriptor;
import mods.eln.node.transparent.TransparentNodeElementInventory;
import mods.eln.node.transparent.TransparentNodeElementRender;
import mods.eln.node.transparent.TransparentNodeEntity;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import java.io.DataInputStream;
public class PowerInductorRender extends TransparentNodeElementRender {
public PowerInductorDescriptor descriptor;
private CableRenderType renderPreProcess;
public PowerInductorRender(TransparentNodeEntity tileEntity,
TransparentNodeDescriptor descriptor) {
super(tileEntity, descriptor);
this.descriptor = (PowerInductorDescriptor) descriptor;
}
@Override
public void draw() {
descriptor.draw();
}
@Override
public void refresh(float deltaT) {
}
@Override
public void networkUnserialize(DataInputStream stream) {
super.networkUnserialize(stream);
/* try {
} catch (IOException e) {
e.printStackTrace();
}*/
}
TransparentNodeElementInventory inventory = new TransparentNodeElementInventory(2, 64, this);
@Override
public GuiScreen newGuiDraw(Direction side, EntityPlayer player) {
return new PowerInductorGui(player, inventory, this);
}
}
| 0 | 0.805692 | 1 | 0.805692 | game-dev | MEDIA | 0.926476 | game-dev | 0.747807 | 1 | 0.747807 |
Rolisteam/rolisteam | 4,326 | src/libraries/core/include/model/playermodel.h | /*************************************************************************
* Copyright (C) 2011 by Joseph Boudou *
* Copyright (C) 2014 by Renaud Guezennec *
* *
* https://rolisteam.org/ *
* *
* Rolisteam 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. *
*************************************************************************/
#ifndef PLAYERS_LIST_H
#define PLAYERS_LIST_H
//#include "data/player.h"
#include <QAbstractItemModel>
#include <QPointer>
#include <core_global.h>
#include <memory>
class Character;
class Player;
class Person;
/**
* @brief PlayersList is a model of players and character. List of connected players and theyr characters
* @note This class is NOT thread-safe.
*/
class CORE_EXPORT PlayerModel : public QAbstractItemModel
{
Q_OBJECT
Q_PROPERTY(QString gameMasterId READ gameMasterId NOTIFY gameMasterIdChanged)
Q_PROPERTY(QString localPlayerId READ localPlayerId WRITE setLocalPlayerId NOTIFY localPlayerIdChanged)
public:
enum ItemDataRole
{
IdentifierRole= Qt::UserRole + 1,
PersonPtrRole,
NameRole,
ColorRole,
LocalRole,
GmRole,
CharacterRole,
CharacterStateIdRole,
NpcRole,
AvatarRole
};
PlayerModel(QObject* parent= nullptr);
virtual ~PlayerModel() override;
////////////////////////////////////
// implements QAbstractItemModel
///////////////////////////////////
QVariant data(const QModelIndex& index, int role) const override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role= Qt::DisplayRole) const override;
QModelIndex index(int row, int column, const QModelIndex& parent= QModelIndex()) const override;
QModelIndex parent(const QModelIndex& index) const override;
int rowCount(const QModelIndex& parent= QModelIndex()) const override;
int columnCount(const QModelIndex& parent= QModelIndex()) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
Player* playerById(const QString& id) const;
Person* personById(const QString& id) const;
Character* characterById(const QString& id)const;
QModelIndex personToIndex(Person* person) const;
QString gameMasterId() const;
QString localPlayerId() const;
QHash<int, QByteArray> roleNames() const override;
public slots:
void clear();
void addPlayer(Player* player);
void removePlayer(Player* player);
void addCharacter(const QModelIndex& parent, Character *character, int pos= -1);
void removeCharacter(Character* character);
void setLocalPlayerId(const QString& uuid);
signals:
void playerJoin(Player* player);
void playerLeft(Player* player);
void gameMasterIdChanged(const QString& gameMasterId);
void localPlayerIdChanged(const QString& localId);
private:
void setGameMasterId(const QString& id);
private:
std::vector<std::unique_ptr<Player>> m_players;
QString m_gameMasterId;
QString m_localPlayerId;
};
#endif
| 0 | 0.887646 | 1 | 0.887646 | game-dev | MEDIA | 0.712715 | game-dev,desktop-app | 0.610557 | 1 | 0.610557 |
ChengF3ng233/Untitled | 3,220 | src/main/java/net/minecraft/item/crafting/RecipeBookCloning.java | package net.minecraft.item.crafting;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemEditableBook;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
public class RecipeBookCloning implements IRecipe {
/**
* Used to check if a recipe matches current crafting inventory
*/
public boolean matches(InventoryCrafting inv, World worldIn) {
int i = 0;
ItemStack itemstack = null;
for (int j = 0; j < inv.getSizeInventory(); ++j) {
ItemStack itemstack1 = inv.getStackInSlot(j);
if (itemstack1 != null) {
if (itemstack1.getItem() == Items.written_book) {
if (itemstack != null) {
return false;
}
itemstack = itemstack1;
} else {
if (itemstack1.getItem() != Items.writable_book) {
return false;
}
++i;
}
}
}
return itemstack != null && i > 0;
}
/**
* Returns an Item that is the result of this recipe
*/
public ItemStack getCraftingResult(InventoryCrafting inv) {
int i = 0;
ItemStack itemstack = null;
for (int j = 0; j < inv.getSizeInventory(); ++j) {
ItemStack itemstack1 = inv.getStackInSlot(j);
if (itemstack1 != null) {
if (itemstack1.getItem() == Items.written_book) {
if (itemstack != null) {
return null;
}
itemstack = itemstack1;
} else {
if (itemstack1.getItem() != Items.writable_book) {
return null;
}
++i;
}
}
}
if (itemstack != null && i >= 1 && ItemEditableBook.getGeneration(itemstack) < 2) {
ItemStack itemstack2 = new ItemStack(Items.written_book, i);
itemstack2.setTagCompound((NBTTagCompound) itemstack.getTagCompound().copy());
itemstack2.getTagCompound().setInteger("generation", ItemEditableBook.getGeneration(itemstack) + 1);
if (itemstack.hasDisplayName()) {
itemstack2.setStackDisplayName(itemstack.getDisplayName());
}
return itemstack2;
} else {
return null;
}
}
/**
* Returns the size of the recipe area
*/
public int getRecipeSize() {
return 9;
}
public ItemStack getRecipeOutput() {
return null;
}
public ItemStack[] getRemainingItems(InventoryCrafting inv) {
ItemStack[] aitemstack = new ItemStack[inv.getSizeInventory()];
for (int i = 0; i < aitemstack.length; ++i) {
ItemStack itemstack = inv.getStackInSlot(i);
if (itemstack != null && itemstack.getItem() instanceof ItemEditableBook) {
aitemstack[i] = itemstack;
break;
}
}
return aitemstack;
}
}
| 0 | 0.739826 | 1 | 0.739826 | game-dev | MEDIA | 0.997633 | game-dev | 0.861041 | 1 | 0.861041 |
AllenDang/cimgui-go | 2,790 | thirdparty/SDL/src/video/haiku/SDL_bclipboard.cc | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_HAIKU
/* BWindow based clipboard implementation */
#include <unistd.h>
#include <TypeConstants.h>
#include "SDL_BWin.h"
#include "SDL_timer.h"
#include "../SDL_sysvideo.h"
#ifdef __cplusplus
extern "C" {
#endif
int HAIKU_SetClipboardText(_THIS, const char *text) {
BMessage *clip = NULL;
if (be_clipboard->Lock()) {
be_clipboard->Clear();
if ((clip = be_clipboard->Data())) {
/* Presumably the string of characters is ascii-format */
ssize_t asciiLength = 0;
for (; text[asciiLength] != 0; ++asciiLength) {}
clip->AddData("text/plain", B_MIME_TYPE, text, asciiLength);
be_clipboard->Commit();
}
be_clipboard->Unlock();
}
return 0;
}
char *HAIKU_GetClipboardText(_THIS) {
BMessage *clip = NULL;
const char *text = NULL;
ssize_t length;
char *result;
if (be_clipboard->Lock()) {
if ((clip = be_clipboard->Data())) {
/* Presumably the string of characters is ascii-format */
clip->FindData("text/plain", B_MIME_TYPE, (const void**)&text,
&length);
}
be_clipboard->Unlock();
}
if (text == NULL) {
result = SDL_strdup("");
} else {
/* Copy the data and pass on to SDL */
result = (char *)SDL_malloc((length + 1) * sizeof(char));
SDL_strlcpy(result, text, length + 1);
}
return result;
}
SDL_bool HAIKU_HasClipboardText(_THIS) {
SDL_bool result = SDL_FALSE;
char *text = HAIKU_GetClipboardText(_this);
if (text) {
result = text[0] != '\0' ? SDL_TRUE : SDL_FALSE;
SDL_free(text);
}
return result;
}
#ifdef __cplusplus
}
#endif
#endif /* SDL_VIDEO_DRIVER_HAIKU */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.749861 | 1 | 0.749861 | game-dev | MEDIA | 0.448314 | game-dev | 0.638972 | 1 | 0.638972 |
Rosewood-Development/RoseStacker | 1,090 | Plugin/src/main/java/dev/rosewood/rosestacker/stack/settings/conditions/spawner/tags/BelowYAxisConditionTag.java | package dev.rosewood.rosestacker.stack.settings.conditions.spawner.tags;
import dev.rosewood.rosestacker.manager.LocaleManager;
import dev.rosewood.rosestacker.stack.StackedSpawner;
import dev.rosewood.rosestacker.stack.settings.conditions.spawner.ConditionTag;
import java.util.List;
import org.bukkit.block.Block;
public class BelowYAxisConditionTag extends ConditionTag {
private int yValue;
public BelowYAxisConditionTag(String tag) {
super(tag, true);
}
@Override
public boolean check(StackedSpawner stackedSpawner, Block spawnBlock) {
return spawnBlock.getY() <= this.yValue;
}
@Override
public boolean parseValues(String[] values) {
if (values.length != 1)
return false;
try {
this.yValue = Integer.parseInt(values[0]);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
@Override
protected List<String> getInfoMessageValues(LocaleManager localeManager) {
return List.of(String.valueOf(this.yValue));
}
}
| 0 | 0.509976 | 1 | 0.509976 | game-dev | MEDIA | 0.630711 | game-dev | 0.7595 | 1 | 0.7595 |
danmaq/touhou-ctc-danmakufu | 13,995 | th_dnh/script/thC/STAGE/1d.dnh | //////////////////////////////////////////////////////////////////////
//====================================================================
//
// I ` Concealed the Conclusion
// STAGE 1d
//
// Xe[WCu玩IɃCN[h܂
//
//====================================================================
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// 萔
//////////////////////////////////////////////////////////////////////
/** ǂݍރXe[WŗL̔wiOtBbNłB
* wi͖܂B
*/
let STAGE_1D_LOAD_LIST_GRAPHIC_BG = [
imgMapStoneTile2,
imgMapGround,
imgMapBamboo,
] ~ LOADBGLIST_MIMA;
let STAGE_1D_LOAD_LIST_GRAPHIC = [
IMAGE_THC_STAGE_LOGO[ 3 ],
] ~ IMAGE_LIST_MIMA;
let STAGE_1D_LOAD_LIST_ENEMY = [
z_s_12,
z_m_01,
z_s_01,
z_j_01,
] ~ bossMimaAList ~ bossMimaBList;
let STAGE_1D_LOAD_LIST_SOUND = [
];
//////////////////////////////////////////////////////////////////////
// oϐ
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------
// ŗL
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
//
function Stage1DInitialize(){
AllZakoEnemyKill( true );
LoadProgress(
STAGE_DEFAULT_LOAD_GRAPHIC ~ STAGE_1D_LOAD_LIST_GRAPHIC ~ GetBGRealLoadList( STAGE_1D_LOAD_LIST_GRAPHIC_BG ),
STAGE_DEFAULT_LOAD_ENEMY ~ STAGE_1D_LOAD_LIST_ENEMY,
STAGE_DEFAULT_LOAD_SE ~ STAGE_1D_LOAD_LIST_SOUND
);
PlayMusicEx( 20 );
}
// ɃXe[W̒g
task Stage1D(){
SetShotAutoDeleteClip( 32, 64, 32, 32 );
__Wait( 20 );
StageLogo();
__Wait( 300 );
//---------------------------------------------------------------
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 10, 14 ] );
loop( 7 ){
CreateEnemyFromFile( z_s_12, GetCenterX() - 50+RandBlur( 30 ), GetClipMinY() - 20, 0, 135, 1 );
CreateEnemyFromFile( z_s_12, GetCenterX() - 50+RandBlur( 30 ), GetClipMinY() - 20, 0, 45, 0 );
__Wait( 14 );
}
__Wait( 120 );
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 9, 14 ] );
loop( 7 ){
CreateEnemyFromFile( z_s_12, GetCenterX() + 50+RandBlur( 30 ), GetClipMinY() - 20, 0, 135, 1 );
CreateEnemyFromFile( z_s_12, GetCenterX() + 50+RandBlur( 30 ), GetClipMinY() - 20, 0, 45, 0 );
__Wait( 14 );
}
__Wait( 70 );
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 8, 12 ] );
loop( 6 ){
CreateEnemyFromFile( z_s_12, GetCenterX() - 50+RandBlur( 30 ), GetClipMinY() - 20, 0, 135, 1 );
CreateEnemyFromFile( z_s_12, GetCenterX() - 50+RandBlur( 30 ), GetClipMinY() - 20, 0, 45, 0 );
__Wait( 15 );
}
__Wait( 50 );
//---------------------------------------------------------------
CreateEnemyFromFile( z_m_01, GetCenterX(), GetClipMinY() - 20, 5, 90, 0 );
__Wait( 100 );
//---------------------------------------------------------------
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 4, 6 ] );
ascent( i in 0..6 ){
CreateEnemyFromFile( z_s_01, GetClipMinX() - 20, rand( GetClipMinY() - 20, GetCenterY() / 2 ), rand( 5, 9 ), Smooth( 60, 10, i, 6 ), 0 );
__Wait( 11 );
}
__Wait( 30 );
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 4, 6 ] );
ascent( i in 0..6 ){
CreateEnemyFromFile( z_s_01, GetClipMaxX() + 20, rand( GetClipMinY() - 20, GetCenterY() / 2 ), rand( 5, 9 ), Smooth( 120, 170, i, 6 ), 0 );
__Wait( 11 );
}
__Wait( 30 );
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 4, 6 ] );
ascent( i in 0..6 ){
CreateEnemyFromFile( z_s_01, GetClipMaxX() + 20, rand( GetClipMinY() - 20, GetCenterY() / 2 ), rand( 5, 9 ), Smooth( 120, 170, i, 6 ), 0 );
__Wait( 11 );
}
__Wait( 50 );
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 4, 6 ] );
ascent( i in 0..6 ){
CreateEnemyFromFile( z_s_01, GetClipMinX() - 20, rand( GetClipMinY() - 20, GetCenterY() / 2 ), rand( 5, 9 ), Smooth( 60, 10, i, 6 ), 0 );
CreateEnemyFromFile( z_s_01, GetClipMaxX() + 20, rand( GetClipMinY() - 20, GetCenterY() / 2 ), rand( 5, 9 ), Smooth( 120, 170, i, 6 ), 0 );
__Wait( 11 );
}
__Wait( 120 );
//---------------------------------------------------------------
CreateEnemyFromFile( z_m_01, GetCenterX() / 2, GetClipMinY() - 20, 5, 90, 0 );
CreateEnemyFromFile( z_m_01, GetCenterX() * 1.5, GetClipMinY() - 20, 5, 90, 0 );
__Wait( 250 );
AllZakoEnemyKill( true );
let BossCount_1D=0;
///////////////////////////////////////////////////////////////////////
NextPhase();
if( m_nFlanLevel < 2 ){ CreateEnemyBossFromFile( bossMimaAE, GetCenterX(), 0, 0, 0, 0 ); }
if( m_nFlanLevel > 1 ){ CreateEnemyBossFromFile( bossMimaAH, GetCenterX(), 0, 0, 0, 0 ); }
while( GetEnemyNum() != 0 ){
yield;
BossCount_1D++;
}
CreateEnemyFromFile( bossMimaA99, GetCenterX(), 0, 0, 0, 0 );
WaitZeroEnemy();//G܂Œ~
///////////////////////////////////////////////////////////////////////
SetShotAutoDeleteClip( 32, 64, 32, 32 );
__Wait( 100 );
let BaceTime=[ 800, 1600 ][ m_nFlanLevel>1 ];
//---------------------------------------------------------------
loop( [ 0, [ 1, [ 2, 3 ][ BossCount_1D < BaceTime ] ][ BossCount_1D < BaceTime + 250 ] ][ BossCount_1D < BaceTime + 500 ] ){
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 14, 20 ] );
loop( 20 ){
CreateEnemyFromFile( z_s_12, GetCenterX() + rand( -80, 80 ), GetClipMinY() - 20, 0, rand( 45, 135 ), [ 1, 0 ][ rand( 0, 100 ) > 50 ] );
__Wait( 8 );
}
__Wait( 50 );
}
//---------------------------------------------------------------
if( BossCount_1D<BaceTime+550 ){
CreateEnemyFromFile( z_m_01, GetCenterX(), GetClipMinY() - 20, 5, 90, 0 );
__Wait( 30 );
CreateEnemyFromFile( z_m_01, GetCenterX() * 1.5, GetClipMinY() - 20, 5, 90, 0 );
__Wait( 30 );
CreateEnemyFromFile( z_m_01, GetCenterX() / 2, GetClipMinY() - 20, 5, 90, 0 );
__Wait( 30 );
}
if( BossCount_1D < BaceTime + 650 ){
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 20, 30 ] );
loop( 15 ){
CreateEnemyFromFile( z_s_01, GetClipMaxX() + 20, GetCenterY() + RandBlur( 20 ), rand( 3, 5 ), 225 + rand( -10, 10 ), 1 );
__Wait( rand( 11, 17 ) );
CreateEnemyFromFile( z_s_01, GetClipMinX() - 20, GetCenterY() + RandBlur( 20 ), rand( 3, 5 ), -45 + rand( -10, 10 ), 1 );
__Wait( rand( 11, 17 ) );
}
}
//---------------------------------------------------------------
CreateEnemyFromFile( z_m_01, GetCenterX() / 2, GetClipMinY() - 20, 4, 90, 0 );
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 2, 3 ] );
ascent( i in 0..3 ){
CreateEnemyFromFile( z_s_01, Smooth( GetCenterX() + 20, GetClipMaxX() - 20, i, 3 ), GetClipMinY() - 20, 4, 90, 0 );
__Wait( 13 );
}
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 2, 3 ] );
ascent( i in 0..3 ){
CreateEnemyFromFile( z_s_01, Smooth( GetClipMaxX() - 50, GetCenterX() + 20, i, 3 ), GetClipMinY() - 20, 4, 90, 0 );
__Wait( 13 );
}
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 2, 3 ] );
ascent( i in 0..3 ){
CreateEnemyFromFile( z_s_01, Smooth( GetCenterX() - 20, GetClipMinX() + 20, i, 3 ), GetClipMinY() - 20, 4, 90, 0 );
__Wait( 13 );
}
CreateEnemyFromFile( z_m_01, GetCenterX() * 1.5, GetClipMinY() - 20, 4, 90, 0 );
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 2, 3 ] );
ascent( i in 0..3 ){
CreateEnemyFromFile( z_s_01, Smooth( GetClipMinX() + 50, GetCenterX() - 20, i, 3 ), GetClipMinY() - 20, 4, 90, 0 );
__Wait( 13 );
}
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 2, 3 ] );
ascent( i in 0..3 ){
CreateEnemyFromFile( z_s_01, Smooth( GetCenterX() + 20, GetClipMaxX() - 20, i, 3 ), GetClipMinY() - 20, 4, 90, 0 );
__Wait( 13 );
}
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_ITEM, [ 2, 3 ] );
ascent( i in 0..3 ){
CreateEnemyFromFile( z_s_01, Smooth( GetClipMinX() - 50, GetCenterX() + 20, i, 3 ), GetClipMinY() - 20, 4, 90, 0 );
__Wait( 13 );
}
__Wait( 250 );
//w-------------------------------------
CreateEnemyFromFile( z_j_01, rand( GetClipMinX() + 30, GetClipMaxX() - 30 ), rand( GetClipMinY() + 30, GetCenterY() * [ 0.8, 1, 1.2, 1.5 ][ m_nFlanLevel ] ), 0, rand( 0, 360 ), 0 );
__Wait( 250 / [ 3, 6, 10, 15 ][ m_nFlanLevel ] );
loop( [ 5, 8, 10, 12 ][ m_nFlanLevel ] ){
CreateEnemyFromFile( z_j_01, rand( GetClipMinX() + 30, GetClipMaxX() - 30 ), rand( GetClipMinY() + 30, GetCenterY() * [ 0.8, 1, 1.2, 1.5 ][ m_nFlanLevel ] ), 0, rand( 0, 360 ), 0 );
__Wait( 200 / [ 3, 6, 10, 15 ][ m_nFlanLevel ] );
}
__Wait( 20 );
ascent( i in 0..5 ){
CreateEnemyFromFile( z_j_01, Smooth( GetClipMaxX() - 30, GetClipMinX() + 30, i, 4 ), GetCenterY() / 2, 0, rand( 0, 360 ), 0 );
}
__Wait( 350 );
AllZakoEnemyKill( true );
yield;
//83`88b
///////////////////////////////////////////////////////////////////////
CreateEnemyBossFromFile( bossMimaB, GetCenterX(), 0, 0, 0, 0 );
WaitZeroEnemy(); //G܂Œ~
if( IsTryLastSpell() ){
CreateEnemyBossFromFile( bossMimaBL, GetCenterX(), GetCenterY() / 2, 0, 0, 0 );
WaitZeroEnemy(); //G܂Œ~
}
SetCommonDataEx( FLAN_CDNS, FLAN_CD_PLAYER_SHOT_ENABLE, false );
ForbidShot( true );
CreateEnemyFromFile( bossMimaB99, GetCenterX(), 0, 0, 0, 0 );
WaitZeroEnemy(); //G܂Œ~
//I
///////////////////////////////////////////////////////////////////////
//̃Xe[W////////////////
FadeOutMusic( bgmList[ 21 ], 100 );
SetClearHistory( 1 );
if( !m_bStagePractice ){
DeleteResource( STAGE_1D_LOAD_LIST_GRAPHIC ~ STAGE_1D_LOAD_LIST_GRAPHIC_BG, STAGE_1D_LOAD_LIST_SOUND );
Stage2();
}
else{ Clear(); }
////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------
// ʏ
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
/**
* t[ƂɌĂ܂B
*
* @param nStage ݂̃Xe[W
* @param nStageCount ݂̃Xe[WJE^l
* @param nLevel x(0`3)
* @param nCount ݂̃JE^l
* @param nPhase ݂̃tF[Y
* @param nPhaseCount ݂̃tF[YJE^l
* @param nPrevPhase 1ȌԂ̃tF[Y
*/
function Stage1DMainLoop( let nStage, let nStageCount, let nLevel, let nCount, let nPhase, let nPhaseCount, let nPrevPhase ){
if( !GetCommonDataDefaultEx( CL_CDNS_CONFIG, CL_CD_CONFIG_BGG, true ) ){ return; }
let nSpeedTable = [ 0.4, 0.2, 0.5 ];
let anBGParam = GetCommonDataDefaultEx( CL_CDNS_TEMP, CL_CD_STAGE_BG_PARAMETER, [ 0, 90, 80, 0, 200, 0 ] );
anBGParam[ BG_TO_Z ] = anBGParam[ BG_TO_Z ] - Smooth( nSpeedTable[ Max( nPhase - 1, 0 ) ], nSpeedTable[ nPhase ], nPhaseCount, 300 );
if( !OnEnemySpell() && IsRenderFrame() && nPhase == 0 && nPhaseCount <= 1000 ){
anBGParam[ BG_FROM_DISTANCE ] = SlowDown( 1000, 700, nPhaseCount, 1000 );
}
SetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_BG_PARAMETER, anBGParam );
}
/**
* wiG掞ɌĂ܂B
*
* @param nStage ݂̃Xe[W
* @param nStageCount ݂̃Xe[WJE^l
* @param nLevel x(0`3)
* @param nCount ݂̃JE^l
* @param nPhase ݂̃tF[Y
* @param nPhaseCount ݂̃tF[YJE^l
* @param nPrevPhase 1ȌԂ̃tF[Y
*/
function Stage1DDrawBackGround( let nStage, let nStageCount, let nLevel, let nCount, let nPhase, let nPhaseCount, let nPrevPhase ){
let anBGParam = GetCommonDataEx( CL_CDNS_TEMP, CL_CD_STAGE_BG_PARAMETER );
if( nStageCount > 2000 ){ SetFogEx( 700, 1200, 255, 160, 160 ); }
else{
SetFogEx(
Smooth( 50, 700, nStageCount, 600 ),
Smooth( 200, 1200, nStageCount, 800 ),
255,
Smooth( 255, 160, nStageCount, 2000 ),
Smooth( 240, 160, nStageCount, 1000 )
);
}
SetViewFrom( anBGParam[ BG_FROM_DISTANCE ], anBGParam[ BG_FROM_YAW ], anBGParam[ BG_FROM_PITCH ] );
let nViewToX = anBGParam[ BG_TO_X ] + GetCommonDataDefaultEx( CL_CDNS_TEMP, CL_CD_STAGE_GAP_X, 0 );
let nViewToY = anBGParam[ BG_TO_Y ] + GetCommonDataDefaultEx( CL_CDNS_TEMP, CL_CD_STAGE_GAP_Y, 0 );
let nViewToZ = anBGParam[ BG_TO_Z ] + GetCommonDataDefaultEx( CL_CDNS_TEMP, CL_CD_STAGE_GAP_Z, 0 );
SetViewTo( nViewToX, nViewToY, nViewToZ );
SetTexture( imgMapGround );
SetGraphicAngle( 90, 0, 0 );
SetGraphicRect( 0, 0, 512, 512 );
SetGraphicScale( 2, 2 );
local{
let nZ = truncEx( anBGParam[ BG_TO_Z ], 1024 ) - 1792;
loop( 3 ){
DrawGraphic3D( 0, -100, nZ );
nZ += 1024;
}
}
SetTexture( imgMapStoneTile2 );
SetGraphicScale( 1, 1 );
local{
let nZ = truncEx( anBGParam[ BG_TO_Z ], 1024 ) - 1792;
SetGraphicRect( 0, 0, 256, 256 );
loop( 12 ){
DrawGraphic3D( 0, -90, nZ );
nZ += 256;
}
}
SetTexture( imgMapBamboo );
SetGraphicRect( 0, 0, 214, 512 );
let nSpace = 256;
let nZ = truncEx( anBGParam[ BG_TO_Z ], nSpace ) - 590;
loop( trunc( 1024 / nSpace ) ){
let nUniqueNum = trunc( absolute( nZ ) / nSpace );
ascent( let x in 0..2 ){
let nDir = [ 1, -1 ][ x ];
let nDstX = ( 144 + m_anFlanRandomTable[ ( nUniqueNum + 17 ) % FLAN_RANDTABLE_LENGTH ] / 2 ) * nDir;
let nDstZ = nZ + m_anFlanRandomTable[ nUniqueNum % FLAN_RANDTABLE_LENGTH ] / 5 + x * nSpace / 3;
let nBranch = [ 4, 3 ][ nZ < -1000 ];
ascent( let i in 0..nBranch ){
SetGraphicAngle( 0, Smooth( 0, 180, i, nBranch ) + m_anFlanRandomTable[ nUniqueNum % FLAN_RANDTABLE_LENGTH ], 180 );
DrawGraphic3D(
nDstX,
100 + m_anFlanRandomTable[ ( nUniqueNum + i ) % FLAN_RANDTABLE_LENGTH ] / 8,
nDstZ
);
}
}
nZ += nSpace;
}
SetColor( 255, 255, 255 );
SetAlpha( 255 );
SetGraphicAngle( 0, 0, 0 );
}
/**
* ʃCG掞ɌĂ܂B
*
* @param nStage ݂̃Xe[W
* @param nStageCount ݂̃Xe[WJE^l
* @param nLevel x(0`3)
* @param nCount ݂̃JE^l
* @param nPhase ݂̃tF[Y
* @param nPhaseCount ݂̃tF[YJE^l
* @param nPrevPhase 1ȌԂ̃tF[Y
*/
function Stage1DDrawBottomObject( let nStage, let nStageCount, let nLevel, let nCount, let nPhase, let nPhaseCount, let nPrevPhase ){
}
/**
* ʃCG掞ɌĂ܂B
*
* @param nStage ݂̃Xe[W
* @param nStageCount ݂̃Xe[WJE^l
* @param nLevel x(0`3)
* @param nCount ݂̃JE^l
* @param nPhase ݂̃tF[Y
* @param nPhaseCount ݂̃tF[YJE^l
* @param nPrevPhase 1ȌԂ̃tF[Y
*/
function Stage1DDrawTopObject( let nStage, let nStageCount, let nLevel, let nCount, let nPhase, let nPhaseCount, let nPrevPhase ){
}
| 0 | 0.752385 | 1 | 0.752385 | game-dev | MEDIA | 0.852608 | game-dev | 0.951767 | 1 | 0.951767 |
X11Libre/xserver | 6,166 | Xi/xiwarppointer.c | /*
* Copyright 2007-2008 Peter Hutterer
*
* 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 (including the next
* paragraph) 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.
*
* Author: Peter Hutterer, University of South Australia, NICTA
*/
/***********************************************************************
*
* Request to Warp the pointer location of an extension input device.
*
*/
#include <dix-config.h>
#include <X11/X.h> /* for inputstr.h */
#include <X11/Xproto.h> /* Request macro */
#include <X11/extensions/XI.h>
#include <X11/extensions/XI2proto.h>
#include "dix/cursor_priv.h"
#include "dix/dix_priv.h"
#include "dix/input_priv.h"
#include "mi/mipointer_priv.h"
#include "Xi/handlers.h"
#include "inputstr.h" /* DeviceIntPtr */
#include "windowstr.h" /* window structure */
#include "scrnintstr.h" /* screen structure */
#include "extnsionst.h"
#include "exevents.h"
#include "exglobals.h"
#include "mipointer.h" /* for miPointerUpdateSprite */
/***********************************************************************
*
* This procedure allows a client to warp the pointer of a device.
*
*/
int _X_COLD
SProcXIWarpPointer(ClientPtr client)
{
REQUEST(xXIWarpPointerReq);
REQUEST_SIZE_MATCH(xXIWarpPointerReq);
swapl(&stuff->src_win);
swapl(&stuff->dst_win);
swapl(&stuff->src_x);
swapl(&stuff->src_y);
swaps(&stuff->src_width);
swaps(&stuff->src_height);
swapl(&stuff->dst_x);
swapl(&stuff->dst_y);
swaps(&stuff->deviceid);
return (ProcXIWarpPointer(client));
}
int
ProcXIWarpPointer(ClientPtr client)
{
int rc;
int x, y;
WindowPtr dest = NULL;
DeviceIntPtr pDev;
SpritePtr pSprite;
ScreenPtr newScreen;
int src_x, src_y;
int dst_x, dst_y;
REQUEST(xXIWarpPointerReq);
REQUEST_SIZE_MATCH(xXIWarpPointerReq);
/* FIXME: panoramix stuff is missing, look at ProcWarpPointer */
rc = dixLookupDevice(&pDev, stuff->deviceid, client, DixWriteAccess);
if (rc != Success) {
client->errorValue = stuff->deviceid;
return rc;
}
if ((!InputDevIsMaster(pDev) && !InputDevIsFloating(pDev)) ||
(InputDevIsMaster(pDev) && !IsPointerDevice(pDev))) {
client->errorValue = stuff->deviceid;
return BadDevice;
}
if (stuff->dst_win != None) {
rc = dixLookupWindow(&dest, stuff->dst_win, client, DixGetAttrAccess);
if (rc != Success) {
client->errorValue = stuff->dst_win;
return rc;
}
}
pSprite = pDev->spriteInfo->sprite;
x = pSprite->hotPhys.x;
y = pSprite->hotPhys.y;
src_x = stuff->src_x / (double) (1 << 16);
src_y = stuff->src_y / (double) (1 << 16);
dst_x = stuff->dst_x / (double) (1 << 16);
dst_y = stuff->dst_y / (double) (1 << 16);
if (stuff->src_win != None) {
int winX, winY;
WindowPtr src;
rc = dixLookupWindow(&src, stuff->src_win, client, DixGetAttrAccess);
if (rc != Success) {
client->errorValue = stuff->src_win;
return rc;
}
winX = src->drawable.x;
winY = src->drawable.y;
if (src->drawable.pScreen != pSprite->hotPhys.pScreen ||
x < winX + src_x ||
y < winY + src_y ||
(stuff->src_width != 0 &&
winX + src_x + (int) stuff->src_width < 0) ||
(stuff->src_height != 0 &&
winY + src_y + (int) stuff->src_height < y) ||
!PointInWindowIsVisible(src, x, y))
return Success;
}
if (dest) {
x = dest->drawable.x;
y = dest->drawable.y;
newScreen = dest->drawable.pScreen;
}
else
newScreen = pSprite->hotPhys.pScreen;
x += dst_x;
y += dst_y;
if (x < 0)
x = 0;
else if (x > newScreen->width)
x = newScreen->width - 1;
if (y < 0)
y = 0;
else if (y > newScreen->height)
y = newScreen->height - 1;
if (newScreen == pSprite->hotPhys.pScreen) {
if (x < pSprite->physLimits.x1)
x = pSprite->physLimits.x1;
else if (x >= pSprite->physLimits.x2)
x = pSprite->physLimits.x2 - 1;
if (y < pSprite->physLimits.y1)
y = pSprite->physLimits.y1;
else if (y >= pSprite->physLimits.y2)
y = pSprite->physLimits.y2 - 1;
if (pSprite->hotShape)
ConfineToShape(pSprite->hotShape, &x, &y);
if (newScreen->SetCursorPosition)
newScreen->SetCursorPosition(pDev, newScreen, x, y, TRUE);
}
else if (!PointerConfinedToScreen(pDev)) {
NewCurrentScreen(pDev, newScreen, x, y);
}
/* if we don't update the device, we get a jump next time it moves */
pDev->last.valuators[0] = x;
pDev->last.valuators[1] = y;
miPointerUpdateSprite(pDev);
if (*newScreen->CursorWarpedTo)
(*newScreen->CursorWarpedTo) (pDev, newScreen, client,
dest, pSprite, x, y);
/* FIXME: XWarpPointer is supposed to generate an event. It doesn't do it
here though. */
return Success;
}
| 0 | 0.980301 | 1 | 0.980301 | game-dev | MEDIA | 0.379229 | game-dev | 0.991657 | 1 | 0.991657 |
TechnoVisual/Pygame-Zero | 1,290 | pacman2/gamemaps.py | # gamemaps module
from pygame import image, surface, Color
moveimage = image.load('images/pacmanmovemap.png')
dotimage = image.load('images/pacmandotmap.png')
def checkMovePoint(p):
global moveimage
if p.x+p.movex < 0: p.x = p.x+600
if p.x+p.movex > 600: p.x = p.x-600
if moveimage.get_at((int(p.x+p.movex), int(p.y+p.movey-80))) != Color('black'):
p.movex = p.movey = 0
def checkDotPoint(x,y):
global dotimage
if dotimage.get_at((int(x), int(y))) == Color('black'):
return 1
if dotimage.get_at((int(x), int(y))) == Color('red'):
return 2
return False
def getPossibleDirection(g):
global moveimage
if g.x-20 < 0:
g.x = g.x+600
if g.x+20 > 600:
g.x = g.x-600
directions = [0,0,0,0]
if g.x+20 < 600:
if moveimage.get_at((int(g.x+20), int(g.y-80))) == Color('black'): directions[0] = 1
if g.x < 600 and g.x >= 0:
if moveimage.get_at((int(g.x), int(g.y-60))) == Color('black'): directions[1] = 1
if g.x-20 >= 0:
if moveimage.get_at((int(g.x-20), int(g.y-80))) == Color('black'): directions[2] = 1
if g.x < 600 and g.x >= 0:
if moveimage.get_at((int(g.x), int(g.y-100))) == Color('black'): directions[3] = 1
return directions
| 0 | 0.64677 | 1 | 0.64677 | game-dev | MEDIA | 0.699333 | game-dev,graphics-rendering | 0.790999 | 1 | 0.790999 |
leavesnight/VIEO_SLAM | 5,023 | optimizer/g2o/g2o/stuff/property.h | // g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef G2O_PROPERTY_H_
#define G2O_PROPERTY_H_
#include <string>
#include <map>
#include <sstream>
#include "string_tools.h"
namespace g2o {
class BaseProperty {
public:
BaseProperty(const std::string name_);
virtual ~BaseProperty();
const std::string& name() {return _name;}
virtual std::string toString() const = 0;
virtual bool fromString(const std::string& s) = 0;
protected:
std::string _name;
};
template <typename T>
class Property: public BaseProperty {
public:
typedef T ValueType;
Property(const std::string& name_): BaseProperty(name_){}
Property(const std::string& name_, const T& v): BaseProperty(name_), _value(v){}
void setValue(const T& v) {_value = v; }
const T& value() const {return _value;}
virtual std::string toString() const
{
std::stringstream sstr;
sstr << _value;
return sstr.str();
}
virtual bool fromString(const std::string& s)
{
bool status = convertString(s, _value);
return status;
}
protected:
T _value;
};
/**
* \brief a collection of properties mapping from name to the property itself
*/
class PropertyMap : protected std::map<std::string, BaseProperty*>
{
public:
typedef std::map<std::string, BaseProperty*> BaseClass;
typedef BaseClass::iterator PropertyMapIterator;
typedef BaseClass::const_iterator PropertyMapConstIterator;
~PropertyMap();
/**
* add a property to the map
*/
bool addProperty(BaseProperty* p);
/**
* remove a property from the map
*/
bool eraseProperty(const std::string& name_);
/**
* return a property by its name
*/
template <typename P>
P* getProperty(const std::string& name_)
{
PropertyMapIterator it=find(name_);
if (it==end())
return 0;
return dynamic_cast<P*>(it->second);
}
template <typename P>
const P* getProperty(const std::string& name_) const
{
PropertyMapConstIterator it=find(name_);
if (it==end())
return 0;
return dynamic_cast<P*>(it->second);
}
/**
* create a property and insert it
*/
template <typename P>
P* makeProperty(const std::string& name_, const typename P::ValueType& v)
{
PropertyMapIterator it=find(name_);
if (it==end()){
P* p=new P(name_, v);
addProperty(p);
return p;
} else
return dynamic_cast<P*>(it->second);
}
/**
* update a specfic property with a new value
* @return true if the params is stored and update was carried out
*/
bool updatePropertyFromString(const std::string& name, const std::string& value);
/**
* update the map based on a name=value string, e.g., name1=val1,name2=val2
* @return true, if it was possible to update all parameters
*/
bool updateMapFromString(const std::string& values);
void writeToCSV(std::ostream& os) const;
using BaseClass::size;
using BaseClass::begin;
using BaseClass::end;
using BaseClass::iterator;
using BaseClass::const_iterator;
};
typedef Property<int> IntProperty;
typedef Property<bool> BoolProperty;
typedef Property<float> FloatProperty;
typedef Property<double> DoubleProperty;
typedef Property<std::string> StringProperty;
} // end namespace
#endif
| 0 | 0.927652 | 1 | 0.927652 | game-dev | MEDIA | 0.17155 | game-dev | 0.78128 | 1 | 0.78128 |
fredakilla/GPlayEngine | 19,767 | samples/racer/src/RacerGame.cpp | #include "RacerGame.h"
// Render queue indexes (in order of drawing).
enum RenderQueue
{
QUEUE_OPAQUE = 0,
QUEUE_TRANSPARENT,
QUEUE_COUNT
};
bool __viewFrustumCulling = true;
bool __flythruCamera = false;
bool __drawDebug = false;
bool __useAccelerometer = false;
bool __showMenu = false;
bool __menuFlag = false;
// Declare our game instance
RacerGame game;
// Input bit-flags (powers of 2)
#define ACCELERATOR (1 << 0)
#define BRAKE (1 << 1)
#define REVERSE (1 << 2)
#define UPRIGHT (1 << 3)
#define STEER_LEFT (1 << 4)
#define STEER_RIGHT (1 << 5)
#define ACCELERATOR_MOUSE (1 << 6)
#define BRAKE_MOUSE (1 << 7)
#define STEERING_RESPONSE (7.0f)
RacerGame::RacerGame()
: _scene(NULL), _font(NULL), _menu(NULL), _overlay(NULL), _keyFlags(0), _mouseFlags(0), _steering(0),
_gamepad(NULL), _physicalGamepad(NULL), _virtualGamepad(NULL), _virtualGamepadClip(NULL),
_carVehicle(NULL), _upsetTimer(0),
_backgroundMusic(NULL), _engineSound(NULL), _brakingSound(NULL)
{
}
void RacerGame::initialize()
{
setMultiTouch(true);
_font = Font::create("res/core/ui/arial.gpb");
// Display the gameplay splash screen during loading, for at least 1 second.
displayScreen(this, &RacerGame::drawSplash, NULL, 1000L);
// Create the menu and start listening to its controls.
_menu = Form::create("res/data/samples/racer/common/menu.form");
_menu->setEnabled(false);
static_cast<Button*>(_menu->getControl("newGameButton"))->addListener(this, Listener::CLICK);
static_cast<Button*>(_menu->getControl("quitGameButton"))->addListener(this, Listener::CLICK);
static_cast<RadioButton*>(_menu->getControl("useGamepad"))->addListener(this, Listener::VALUE_CHANGED);
static_cast<RadioButton*>(_menu->getControl("useTilt"))->addListener(this, Listener::VALUE_CHANGED);
if (!canExit())
{
// Prevent a programmatic exit on platforms that don't allow it.
_menu->removeControl("quitGameButton");
}
// Create a pause button to display the menu
_overlay = Form::create("res/data/samples/racer/common/overlay.form");
static_cast<Button*>(_overlay->getControl("menuButton"))->addListener(this, Listener::CLICK);
// Load the scene
_scene = Scene::load("res/data/samples/racer/common/racer.scene");
// Set the aspect ratio for the scene's camera to match the current resolution
_scene->getActiveCamera()->setAspectRatio(getAspectRatio());
// Initialize scene
_scene->visit(this, &RacerGame::initializeScene);
// Load and initialize game script
getScriptController()->loadScript("res/data/samples/racer/common/racer.lua");
getScriptController()->executeFunction<void>("setScene", "<Scene>", NULL, _scene);
Node* carNode = _scene->findNode("carbody");
if (carNode && carNode->getCollisionObject()->getType() == PhysicsCollisionObject::VEHICLE)
{
_carVehicle = static_cast<PhysicsVehicle*>(carNode->getCollisionObject());
resetToStart();
}
// Create audio tracks
_backgroundMusic = AudioSource::create("res/data/samples/racer/common/background_track.ogg", true);
if (_backgroundMusic)
{
_backgroundMusic->setLooped(true);
_backgroundMusic->play();
_backgroundMusic->setGain(0.3f);
}
_engineSound = AudioSource::create("res/data/samples/racer/common/engine_loop.ogg");
if (_engineSound)
{
_engineSound->setLooped(true);
_engineSound->play();
_engineSound->setGain(0.7f);
}
_brakingSound = AudioSource::create("res/data/samples/racer/common/braking.wav", true);
_brakingSound->setLooped(false);
_brakingSound->setGain(0.5f);
_gamepad = getGamepad(0);
}
bool RacerGame::initializeScene(Node* node)
{
static Node* lightNode = _scene->findNode("directionalLight1");
Model* model = dynamic_cast<Model*>(node->getDrawable());
if (model)
{
Material* material = model->getMaterial();
if (material && material->getTechnique()->getPassByIndex(0)->getEffect()->getUniform("u_directionalLightDirection"))
{
material->getParameter("u_ambientColor")->setValue(_scene->getAmbientColor());
material->getParameter("u_directionalLightColor[0]")->setValue(lightNode->getLight()->getColor());
material->getParameter("u_directionalLightDirection[0]")->setValue(lightNode->getForwardVectorView());
}
}
return true;
}
void RacerGame::finalize()
{
SAFE_RELEASE(_backgroundMusic);
SAFE_RELEASE(_engineSound);
SAFE_RELEASE(_brakingSound);
SAFE_RELEASE(_scene);
SAFE_RELEASE(_font);
SAFE_RELEASE(_menu);
SAFE_RELEASE(_overlay);
}
void RacerGame::update(float elapsedTime)
{
// The "Start" button is mapped to MENU2.
if (!__showMenu && !__menuFlag && _gamepad->isButtonDown(Gamepad::BUTTON_MENU2))
{
__menuFlag = true;
menuEvent();
}
if (__menuFlag && !_gamepad->isButtonDown(Gamepad::BUTTON_MENU2))
{
__menuFlag = false;
}
if (__showMenu && !__menuFlag && _gamepad->isButtonDown(Gamepad::BUTTON_MENU2))
{
__menuFlag = true;
menuEvent();
}
Node* cameraNode;
if (_scene->getActiveCamera() && (cameraNode = _scene->getActiveCamera()->getNode()))
{
float dt = elapsedTime / 1000.0f;
float braking = 0;
float driving = 0;
if (_carVehicle)
{
float v = _carVehicle->getSpeedKph();
bool isVirt = _gamepad->isVirtual();
if (!__flythruCamera)
{
// Vehicle Control (Normal Mode)
Vector2 direction;
if (_gamepad->getJoystickCount())
{
_gamepad->getJoystickValues(0, &direction);
}
if (_gamepad->isButtonDown(Gamepad::BUTTON_LEFT))
{
direction.set(-1.0f, 0.0f);
}
else if (_gamepad->isButtonDown(Gamepad::BUTTON_RIGHT))
{
direction.set(1.0f, 0.0f);
}
// Allow keys to control steering
if (_keyFlags & STEER_LEFT)
{
_steering += STEERING_RESPONSE * dt;
}
else if (_keyFlags & STEER_RIGHT)
{
_steering -= STEERING_RESPONSE * dt;
}
else if (__useAccelerometer)
{
float pitch, roll;
Game::getAccelerometerValues(&pitch, &roll);
_steering = -0.16 * roll;
}
else
{
_steering = -direction.x;
}
_steering = std::max(-1.0f, std::min(_steering, 1.0f));
if (_gamepad->getTriggerCount() > 1)
{
driving = _gamepad->getTriggerValue(1);
_engineSound->setGain(0.8f + (driving * 0.2f));
}
if (!driving && ((_keyFlags & ACCELERATOR) || (_keyFlags & ACCELERATOR_MOUSE) || _gamepad->isButtonDown(Gamepad::BUTTON_A)))
{
driving = 1;
_engineSound->setGain(1.0f);
}
else
{
_engineSound->setGain(0.8f);
}
float s = _carVehicle->getSpeedSmoothKph() / 100.0f;
_engineSound->setPitch(std::max(0.2f, std::min(s, 2.0f)));
// Reverse only below a reasonable speed
bool isReverseCommanded = (_keyFlags & REVERSE) ||
(!isVirt && _gamepad->isButtonDown(Gamepad::BUTTON_X)) ||
(direction.y < -0.1 && _gamepad->isButtonDown(Gamepad::BUTTON_A));
if (isReverseCommanded && v < 30.0f)
{
driving = -0.6f;
}
if ((_keyFlags & BRAKE) || (_keyFlags & BRAKE_MOUSE) || _gamepad->isButtonDown(Gamepad::BUTTON_B) || (_gamepad->getTriggerCount() > 0 && _gamepad->getTriggerValue(0) > 0.5f))
{
braking = 1;
if (_brakingSound && (_brakingSound->getState() != AudioSource::PLAYING) && (v > 30.0f))
_brakingSound->play();
}
else
{
_brakingSound->stop();
}
// Make the camera follow the car
Node* carNode = _carVehicle->getNode();
Vector3 carPosition(carNode->getTranslation());
Vector3 commandedPosition(carPosition + Vector3::unitY()*4.0f - carNode->getBackVector()*10.0f);
cameraNode->translateSmooth(commandedPosition, dt, 0.2f);
Matrix m;
Matrix::createLookAt(cameraNode->getTranslation(), carPosition, Vector3::unitY(), &m);
m.transpose();
Quaternion q;
m.getRotation(&q);
cameraNode->setRotation(q);
}
// Slightly different steering gain based on gamepad type.
_carVehicle->setSteerdown( (isVirt ? 94.0f : 87.0f), (isVirt ? 0.15f : 0.22f) );
_carVehicle->update(elapsedTime, _steering, braking, driving);
// Auto-detect an upset car
if (fabs(v) < 10.0f && isUpset())
{
_upsetTimer += dt;
}
else
{
_upsetTimer = 0;
}
if (_upsetTimer > 3.0f)
{
_upsetTimer = 0;
resetInPlace();
}
else if ( (_keyFlags & UPRIGHT) ||
(!isVirt && _gamepad->isButtonDown(Gamepad::BUTTON_Y)) ||
(_carVehicle->getNode()->getTranslationY() < -300.0f) )
{
resetToStart();
}
}
}
}
bool RacerGame::isUpset() const
{
GP_ASSERT(_carVehicle);
return _carVehicle->getNode()->getUpVector().y < 0.4f;
}
void RacerGame::render(float elapsedTime)
{
// Clear the color and depth buffers
clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0);
// Visit all the nodes in the scene to build our render queues
for (unsigned int i = 0; i < QUEUE_COUNT; ++i)
_renderQueues[i].clear();
_scene->visit(this, &RacerGame::buildRenderQueues);
// Draw the scene from our render queues
drawScene();
if (__drawDebug)
{
Game::getInstance()->getPhysicsController()->drawDebug(_scene->getActiveCamera()->getViewProjectionMatrix());
}
// Draw the gamepad
if (_gamepad && _gamepad->isVirtual())
_gamepad->draw();
// Draw the menu
if (__showMenu)
{
_menu->draw();
}
_overlay->draw();
// Draw FPS and speed
int carSpeed = _carVehicle ? (int)_carVehicle->getSpeedKph() : 0;
_font->start();
char fps[32];
sprintf(fps, "%d", getFrameRate());
_font->drawText(fps, 5, 5, Vector4(0,0.5f,1,1), 20);
char kph[32];
sprintf(kph, "%d [km/h]", carSpeed);
_font->drawText(kph, getWidth() / 2 - 50, getHeight() - 60, Vector4(1,1,1,1), 40);
_font->finish();
}
bool RacerGame::buildRenderQueues(Node* node)
{
Model* model = dynamic_cast<Model*>(node->getDrawable());
if (model)
{
// Perform view-frustum culling for this node
if (__viewFrustumCulling && !node->getBoundingSphere().intersects(_scene->getActiveCamera()->getFrustum()))
return true;
// Determine which render queue to insert the node into
std::vector<Node*>* queue;
if (node->hasTag("transparent"))
queue = &_renderQueues[QUEUE_TRANSPARENT];
else
queue = &_renderQueues[QUEUE_OPAQUE];
queue->push_back(node);
}
return true;
}
void RacerGame::drawScene()
{
// Iterate through each render queue and draw the nodes in them
for (unsigned int i = 0; i < QUEUE_COUNT; ++i)
{
std::vector<Node*>& queue = _renderQueues[i];
for (size_t j = 0, ncount = queue.size(); j < ncount; ++j)
{
queue[j]->getDrawable()->draw();
}
}
}
void RacerGame::drawSplash(void* param)
{
clear(CLEAR_COLOR_DEPTH, Vector4(0, 0, 0, 1), 1.0f, 0);
SpriteBatch* batch = SpriteBatch::create("res/core/logo_powered_white.png");
batch->start();
batch->draw(this->getWidth() * 0.5f, this->getHeight() * 0.5f, 0.0f, 512.0f, 512.0f, 0.0f, 1.0f, 1.0f, 0.0f, Vector4::one(), true);
batch->finish();
SAFE_DELETE(batch);
}
void RacerGame::keyEvent(Keyboard::KeyEvent evt, int key)
{
if (evt == Keyboard::KEY_PRESS)
{
switch (key)
{
case Keyboard::KEY_ESCAPE:
menuEvent();
break;
case Keyboard::KEY_A:
case Keyboard::KEY_CAPITAL_A:
case Keyboard::KEY_LEFT_ARROW:
_keyFlags |= STEER_LEFT;
break;
case Keyboard::KEY_D:
case Keyboard::KEY_CAPITAL_D:
case Keyboard::KEY_RIGHT_ARROW:
_keyFlags |= STEER_RIGHT;
break;
case Keyboard::KEY_W:
case Keyboard::KEY_CAPITAL_W:
case Keyboard::KEY_UP_ARROW:
_keyFlags |= ACCELERATOR;
break;
case Keyboard::KEY_S:
case Keyboard::KEY_CAPITAL_S:
case Keyboard::KEY_DOWN_ARROW:
_keyFlags |= REVERSE;
break;
case Keyboard::KEY_SPACE:
_keyFlags |= BRAKE;
break;
case Keyboard::KEY_Y:
case Keyboard::KEY_CAPITAL_Y:
_keyFlags |= UPRIGHT;
break;
case Keyboard::KEY_V:
__viewFrustumCulling = !__viewFrustumCulling;
break;
case Keyboard::KEY_F:
__flythruCamera = !__flythruCamera;
getScriptController()->executeFunction<void>("toggleCamera", NULL);
break;
case Keyboard::KEY_B:
__drawDebug = !__drawDebug;
break;
case Keyboard::KEY_J:
__useAccelerometer = !__useAccelerometer;
break;
}
}
else if (evt == Keyboard::KEY_RELEASE)
{
switch (key)
{
case Keyboard::KEY_A:
case Keyboard::KEY_CAPITAL_A:
case Keyboard::KEY_LEFT_ARROW:
_keyFlags &= ~STEER_LEFT;
break;
case Keyboard::KEY_D:
case Keyboard::KEY_CAPITAL_D:
case Keyboard::KEY_RIGHT_ARROW:
_keyFlags &= ~STEER_RIGHT;
break;
case Keyboard::KEY_W:
case Keyboard::KEY_CAPITAL_W:
case Keyboard::KEY_UP_ARROW:
_keyFlags &= ~ACCELERATOR;
break;
case Keyboard::KEY_S:
case Keyboard::KEY_CAPITAL_S:
case Keyboard::KEY_DOWN_ARROW:
_keyFlags &= ~REVERSE;
break;
case Keyboard::KEY_SPACE:
_keyFlags &= ~BRAKE;
break;
case Keyboard::KEY_Y:
case Keyboard::KEY_CAPITAL_Y:
_keyFlags &= ~UPRIGHT;
break;
}
}
}
void RacerGame::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
switch (evt)
{
case Touch::TOUCH_PRESS:
break;
case Touch::TOUCH_RELEASE:
break;
case Touch::TOUCH_MOVE:
break;
};
}
bool RacerGame::mouseEvent(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
{
bool consumed = false;
switch (evt)
{
case Mouse::MOUSE_PRESS_LEFT_BUTTON:
_keyFlags |= ACCELERATOR_MOUSE;
break;
case Mouse::MOUSE_PRESS_RIGHT_BUTTON:
_keyFlags |= BRAKE_MOUSE;
break;
case Mouse::MOUSE_RELEASE_LEFT_BUTTON:
_keyFlags &= ~ACCELERATOR_MOUSE;
break;
case Mouse::MOUSE_RELEASE_RIGHT_BUTTON:
_keyFlags &= ~BRAKE_MOUSE;
break;
}
return consumed;
}
void RacerGame::gamepadEvent(Gamepad::GamepadEvent evt, Gamepad* gamepad)
{
// Prioritise physical gamepads over the virtual one.
switch(evt)
{
case Gamepad::CONNECTED_EVENT:
if (gamepad->isVirtual())
{
float from = 0.0f;
float to = getHeight();
Animation* virtualGamepadAnimation = gamepad->getForm()->createAnimationFromTo("gamepad_transition", Form::ANIMATE_POSITION_Y, &from, &to, Curve::LINEAR, 2000L);
_virtualGamepadClip = virtualGamepadAnimation->getClip();
_virtualGamepad = gamepad;
}
else
{
if (!_physicalGamepad)
_physicalGamepad = gamepad;
}
if (_physicalGamepad)
{
if (_virtualGamepadClip && _gamepad == _virtualGamepad)
{
_virtualGamepadClip->setSpeed(1.0f);
_virtualGamepadClip->play();
}
_gamepad = _physicalGamepad;
if (_virtualGamepad)
{
_virtualGamepad->getForm()->setEnabled(false);
}
}
else if (_virtualGamepad)
{
if (_gamepad == _physicalGamepad)
{
_virtualGamepadClip->setSpeed(-1.0f);
_virtualGamepadClip->play();
}
_gamepad = _virtualGamepad;
_virtualGamepad->getForm()->setEnabled(true);
}
break;
case Gamepad::DISCONNECTED_EVENT:
if (gamepad == _physicalGamepad)
{
_gamepad = _virtualGamepad;
_physicalGamepad = NULL;
_virtualGamepadClip->setSpeed(-1.0f);
_virtualGamepadClip->play();
_virtualGamepad->getForm()->setEnabled(true);
}
break;
}
}
void RacerGame::menuEvent()
{
__showMenu = !__showMenu;
if (__showMenu)
{
static_cast<Button*>(_overlay->getControl("menuButton"))->setText("Resume");
pause();
_menu->setEnabled(true);
//_menu->setState(Control::FOCUS);
}
else
{
static_cast<Button*>(_overlay->getControl("menuButton"))->setText("Menu");
resume();
_menu->setEnabled(false);
}
}
void RacerGame::resetToStart()
{
Vector3 pos(-258, 1, 278);
Quaternion rot(Vector3::unitY(), MATH_DEG_TO_RAD(143.201f));
reset(pos, rot);
}
void RacerGame::resetInPlace()
{
Node* carNode = _carVehicle->getNode();
Vector3 pos;
carNode->getTranslation(&pos);
pos.y += 3.0f;
float angle = 0;
Vector3 v;
carNode->getForwardVector(&v);
if (v.x*v.x + v.z*v.z > 0)
{
angle += atan2(-v.x, -v.z);
}
Quaternion rot(Vector3::unitY(), angle);
reset(pos, rot);
}
void RacerGame::reset(const Vector3& pos, const Quaternion& rot)
{
Node* carNode = _carVehicle->getNode();
_carVehicle->setEnabled(false);
carNode->setTranslation(pos);
carNode->setRotation(rot);
_carVehicle->reset();
_carVehicle->setEnabled(true);
}
void RacerGame::controlEvent(Control* control, EventType evt)
{
if (strcmp(control->getId(), "newGameButton") == 0)
{
resetToStart();
// Close the menu and resume the game.
menuEvent();
}
else if (strcmp(control->getId(), "quitGameButton") == 0)
{
exit();
}
else if (strcmp(control->getId(), "useGamepad") == 0)
{
__useAccelerometer = false;
}
else if (strcmp(control->getId(), "useTilt") == 0)
{
__useAccelerometer = true;
}
else if (strcmp(control->getId(), "menuButton") == 0)
{
menuEvent();
}
}
| 0 | 0.963791 | 1 | 0.963791 | game-dev | MEDIA | 0.852277 | game-dev | 0.980212 | 1 | 0.980212 |
kactus2/kactus2dev | 1,552 | KactusAPI/include/MemoryMapExpressionsGatherer.h | //-----------------------------------------------------------------------------
// File: MemoryMapExpressionsGatherer.h
//-----------------------------------------------------------------------------
// Project: Kactus2
// Author: Mikko Teuho
// Date: 29.04.2015
//
// Description:
// Gathers expressions from a memory map and its memory remaps.
//-----------------------------------------------------------------------------
#ifndef MEMORYMAPEXPRESSIONGATHERER_H
#define MEMORYMAPEXPRESSIONGATHERER_H
#include <QSharedPointer>
#include <QStringList>
class MemoryMap;
//-----------------------------------------------------------------------------
//! Gathers expressions from a memory map and its memory remaps.
//-----------------------------------------------------------------------------
class MemoryMapExpressionGatherer
{
public:
/*!
* The constructor.
*/
MemoryMapExpressionGatherer();
/*!
* The destructor.
*/
virtual ~MemoryMapExpressionGatherer();
/*!
* Get the expressions from a given memory map.
*
* @param [in] memoryMap The given memory map.
*
* @return A list containing all the expressions used in a memory map.
*/
QStringList getExpressions(QSharedPointer<MemoryMap> memoryMap) const;
private:
//! No copying.
MemoryMapExpressionGatherer(const MemoryMapExpressionGatherer& other);
//! No assignment.
MemoryMapExpressionGatherer& operator=(const MemoryMapExpressionGatherer& other);
};
#endif // MEMORYMAPEXPRESSIONGATHERER_H
| 0 | 0.569514 | 1 | 0.569514 | game-dev | MEDIA | 0.208635 | game-dev | 0.561405 | 1 | 0.561405 |
OpenDungeons/OpenDungeons | 5,877 | source/sound/SoundEffectsManager.h | /*
* Copyright (C) 2011-2016 OpenDungeons Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*/
#ifndef SOUNDEFFECTSMANAGER_H_
#define SOUNDEFFECTSMANAGER_H_
#include <OgreSingleton.h>
#include <OgreVector3.h>
#include <SFML/Audio.hpp>
#include <vector>
#include <map>
// Forward declarations
class CreatureDefinition;
class ODPacket;
namespace Ogre
{
class Quaternion;
}
//! \brief Special Relative sounds
namespace SoundRelativeInterface
{
const std::string Click = "Interface/Click";
const std::string PickSelector = "Interface/PickSelector";
}
namespace SoundRelativeKeeperStatements
{
const std::string AllyDefeated = "Keeper/AllyDefeated";
const std::string Defeat = "Keeper/Defeat";
const std::string Lost = "Keeper/Lost";
const std::string Victory = "Keeper/Victory";
const std::string GoalFailed = "Keeper/GoalFailed";
const std::string GoalMet = "Keeper/GoalMet";
const std::string CreatureNew = "Keeper/CreatureNew";
const std::string CreatureNoFood = "Keeper/CreatureNoFood";
const std::string CreatureNoBed = "Keeper/CreatureNoBed";
const std::string WeAreUnderAttack = "Keeper/WeAreUnderAttack";
}
// The Z value to use for tile positioned sounds.
// Tiles are from -0.25 to 3.0 in z value, the floor is at 0,
// and we're using an pseudo-average value.
const float TILE_ZPOS = 2.5;
//! \brief A small object used to contain both the sound and its buffer,
//! as both must have the same life-cycle.
class GameSound
{
public:
//! \brief Game sound constructor
//! \param filename The sound filename used to load the sound.
//! \param spatialSound tells whether the sound should be prepared to be a spatial sound.
//! with a position, strength and attenuation relative to the camera position.
GameSound(const std::string& filename, bool spatialSound);
~GameSound();
bool isInitialized() const
{ return !(mSoundBuffer == nullptr); }
bool isPlaying() const
{ return mSound->getStatus() == sf::SoundSource::Status::Playing; }
//! \brief Play at the given spatial position
void play(float x, float y, float z);
void play()
{ mSound->play(); }
void stop()
{ mSound->stop(); }
const std::string& getFilename() const
{ return mFilename; }
private:
//! \brief The Main sound object
sf::Sound* mSound;
//! \brief The corresponding sound buffer, must not be destroyed
//! before the sound object itself is deleted.
sf::SoundBuffer* mSoundBuffer;
//! \brief The sound filename
std::string mFilename;
};
//! \brief Helper class to manage sound effects.
class SoundEffectsManager: public Ogre::Singleton<SoundEffectsManager>
{
public:
static const std::string DEFAULT_KEEPER_VOICE;
//! \brief Loads every available interface sounds
SoundEffectsManager();
//! \brief Deletes both sound caches.
virtual ~SoundEffectsManager();
void updateListener(float timeSinceLastFrame,
const Ogre::Vector3& position, const Ogre::Quaternion& orientation);
//! \brief Plays a spatial sound at the given tile position.
void playSpatialSound(const std::string& family,
float XPos, float YPos, float height = TILE_ZPOS);
//! \brief Proxy used for sounds that aren't spatial and can be heard everywhere.
void playRelativeSound(const std::string& family);
private:
//! \brief Every spatial game sounds (spells, traps, creatures...). The sounds are read when launching the
//! game by browsing the sound directory
//! \note the GameSound here are handled by the game sound cache.
std::map<std::string, std::vector<GameSound*>> mSpatialSounds;
//! \brief Every relative (ie not spatial) game sounds (interface, keeper statements, ...). The sounds
//! are read when launching the game by browsing the sound directory
//! \note the GameSound here are handled by the game sound cache.
std::map<std::string, std::vector<GameSound*>> mRelativeSounds;
//! \brief The sound cache, containing the sound references, used by game entities.
//! \brief The GameSounds here must be deleted at destruction.
std::map<std::string, GameSound*> mGameSoundCache;
//! \brief Stores the relative sounds to play. Once a sound has stopped playing, the next one will start
std::vector<GameSound*> mRelativeSoundQueue;
//! \brief Returns a game sounds from the cache.
//! \param filename The sound filename.
//! \param spatialSound Whether the sound is a spatial sound.
//! If an unexisting file is given, a new cache instance is returned.
//! \note Use this function only to create new game sounds as it is the only way to make sure
//! the GameSound* instance is correclty cleared up when quitting.
//! \warning Returns nullptr if the filename is an invalid/unreadable sound.
GameSound* getGameSound(const std::string& filename, bool spatialSound = false);
//! \brief Recursive function that fills the sound map with sound files found and reads
//! child directories
void readSounds(std::map<std::string, std::vector<GameSound*>>& soundsFamily,
const std::string& parentPath, const std::string& parentFamily, bool spatialSound);
};
#endif // SOUNDEFFECTSMANAGER_H_
| 0 | 0.732052 | 1 | 0.732052 | game-dev | MEDIA | 0.816047 | game-dev,audio-video-media | 0.507885 | 1 | 0.507885 |
FlameskyDexive/Legends-Of-Heroes | 1,464 | Unity/Assets/Scripts/ModelView/Client/Plugins/EUI/Tools/UIFindHelper.cs | using System;
using UnityEngine;
namespace ET.Client
{
[EnableClass]
public class UIFindHelper
{
/// <summary>
/// 查找子节点
/// </summary>
/// <OtherParam name="_target"></OtherParam>
/// <OtherParam name="_childName"></OtherParam>
/// <returns></returns>
public static Transform FindDeepChild(GameObject _target, string _childName)
{
Transform resultTrs = null;
resultTrs = _target.transform.Find(_childName);
if (resultTrs == null)
{
foreach (Transform trs in _target.transform)
{
resultTrs = UIFindHelper.FindDeepChild(trs.gameObject, _childName);
if (resultTrs != null)
return resultTrs;
}
}
return resultTrs;
}
/// <summary>
/// 根据泛型查找子节点
/// </summary>
/// <param name="_target"></param>
/// <param name="_childName"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T FindDeepChild<T>(GameObject _target, string _childName) where T : Component
{
Transform resultTrs = UIFindHelper.FindDeepChild(_target, _childName);
if (resultTrs != null)
return resultTrs.gameObject.GetComponent<T>();
return (T)((object)null);
}
}
} | 0 | 0.859623 | 1 | 0.859623 | game-dev | MEDIA | 0.828006 | game-dev | 0.880724 | 1 | 0.880724 |
slavidodo/OpenTibia-Unity | 17,577 | OpenTibia/Assets/Scripts/Modules/Skills/SkillsWindow.cs | using System;
using OpenTibiaUnity.Core.Components.Base;
using OpenTibiaUnity.Core.Creatures;
using UnityEngine;
using UnityEngine.UI;
namespace OpenTibiaUnity.Modules.Skills
{
public class SkillsWindow : MiniWindow
{
private static Color RedColor = new Color(1, 0, 0);
private static Color GreenColor = new Color(0, 1, 0);
[SerializeField] private SkillRawPanel _skillRawPanelPrefab = null;
[SerializeField] private SkillProgressPanel _skillProgressPanelPrefab = null;
[SerializeField] private SkillProgressIconPanel _skillProgressIconPanelPrefab = null;
[SerializeField] private Sprite _magicIcon = null;
[SerializeField] private Sprite _fistIcon = null;
[SerializeField] private Sprite _clubIcon = null;
[SerializeField] private Sprite _swordIcon = null;
[SerializeField] private Sprite _axeIcon = null;
[SerializeField] private Sprite _distIcon = null;
[SerializeField] private Sprite _shieldingIcon = null;
[SerializeField] private Sprite _fishingIcon = null;
private SkillPanel _expPanel = null;
private SkillPanel _levelPanel = null;
private SkillPanel _expGainRatePanel = null;
private SkillPanel _hitPointsPanel = null;
private SkillPanel _manaPanel = null;
private SkillPanel _soulPointsPanel = null;
private SkillPanel _capacityPanel = null;
private SkillPanel _speedPanel = null;
private SkillPanel _regenerationPanel = null;
private SkillPanel _staminaPanel = null;
private SkillPanel _offlineTrainingPanel = null;
// known skills
private SkillPanel _magicPanel = null;
private SkillPanel _fistPanel = null;
private SkillPanel _clubPanel = null;
private SkillPanel _swordPanel = null;
private SkillPanel _axePanel = null;
private SkillPanel _distancePanel = null;
private SkillPanel _shieldingPanel = null;
private SkillPanel _fishingPanel = null;
private SkillPanel _criticalChancePanel = null;
private SkillPanel _criticalExtraDamagePanel = null;
private SkillPanel _lifeLeechChancePanel = null;
private SkillPanel _lifeLeechAmountPanel = null;
private SkillPanel _manaLeechChancePanel = null;
private SkillPanel _manaLeechAmountPanel = null;
protected override void Awake() {
base.Awake();
Creature.onSkillChange.AddListener(OnCreatureSkillChange);
}
protected override void Start() {
base.Start();
if (OpenTibiaUnity.GameManager.IsGameRunning) {
var player = OpenTibiaUnity.Player;
for (SkillType skillType = SkillType.First; skillType < SkillType.Last; skillType++)
OnCreatureSkillChange(player, skillType, player.GetSkill(skillType));
OnCreatureSkillChange(player, SkillType.Experience, player.GetSkill(SkillType.Experience));
}
}
private void OnCreatureSkillChange(Creature creature, SkillType skillType, Skill skill) {
if (creature != OpenTibiaUnity.Player)
return;
var skillPanel = GetSkillPanelForSkillType(skillType);
if (!skillPanel)
return;
switch (skillType) {
case SkillType.Stamina:
case SkillType.Food:
case SkillType.OfflineTraining: {
int value = (int)Mathf.Round(Mathf.Max(0, skill.Level - skill.BaseLevel) / 60000f);
float percentage = 0;
if (skillType == SkillType.Stamina) {
int happyHour = 1;
int totalHours = 56;
if (OpenTibiaUnity.GameManager.ClientVersion >= 841) {
happyHour = 2;
totalHours = 42;
}
percentage = value / (totalHours * 60f);
if ((totalHours * 60) - value > happyHour * 60)
skillPanel.SetProgressColor(RedColor);
else
skillPanel.SetProgressColor(GreenColor);
} else if (skillType == SkillType.OfflineTraining) {
percentage = value / (12 * 60f);
}
skillPanel.SetValue(string.Format("{0:D2}:{1:D2}", value / 60, value % 60), percentage * 100);
break;
}
default: {
long skillLevel = skill.Level;
if (skillType == SkillType.Capacity)
skillLevel /= 100;
skillPanel.SetValue(skillLevel, skill.Percentage);
break;
}
}
}
protected override void OnClientVersionChange(int _, int newVersion) {
base.OnClientVersionChange(_, newVersion);
var gameManager = OpenTibiaUnity.GameManager;
DestroyOldComponents();
if (newVersion > 1000) {
_levelPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_LEVEL);
_expPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_EXPERIENCE_MINIMAL);
// exp panel is yellow if experienceBonus > 0 (10.54+ and was removed at some point)
} else {
_expPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_LEVEL);
_levelPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_EXPERIENCE);
}
if (OpenTibiaUnity.GameManager.GetFeature(GameFeature.GameExperienceGain))
_expGainRatePanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_XPGAIN);
_hitPointsPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_HITPOINTS);
_manaPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_MANA);
_soulPointsPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_SOULPOINTS);
_capacityPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_CAPACITY);
if (gameManager.GetFeature(GameFeature.GameSkillsBase))
_speedPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_SPEED);
if (gameManager.GetFeature(GameFeature.GamePlayerRegenerationTime))
_regenerationPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_REGENERATION);
if (gameManager.GetFeature(GameFeature.GamePlayerStamina))
_staminaPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_STAMINA);
if (gameManager.GetFeature(GameFeature.GameOfflineTrainingTime))
_offlineTrainingPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_OFFLINETRAINING);
if (newVersion > 1150) {
CreateSeparator();
_magicPanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_MAGIC, 0, 0, GreenColor, _magicIcon);
_fistPanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_FIST, 0, 0, GreenColor, _fistIcon);
_clubPanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_CLUB, 0, 0, GreenColor, _clubIcon);
_swordPanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_SWORD, 0, 0, GreenColor, _swordIcon);
_axePanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_AXE, 0, 0, GreenColor, _axeIcon);
_distancePanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_DISTANCE, 0, 0, GreenColor, _distIcon);
_shieldingPanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_SHIELDING, 0, 0, GreenColor, _shieldingIcon);
_fishingPanel = CreateSkillPanel(_skillProgressIconPanelPrefab, TextResources.SKILLS_FISHING, 0, 0, GreenColor, _fishingIcon);
} else {
_magicPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_MAGIC, 0, 0, RedColor);
CreateSeparator();
_fistPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_FIST_LEGACY, 0, 0, GreenColor);
_clubPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_CLUB_LEGACY, 0, 0, GreenColor);
_swordPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_SWORD_LEGACY, 0, 0, GreenColor);
_axePanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_AXE_LEGACY, 0, 0, GreenColor);
_distancePanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_DISTANCE_LEGACY, 0, 0, GreenColor);
_shieldingPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_SHIELDING, 0, 0, GreenColor);
_shieldingPanel = CreateSkillPanel(_skillProgressPanelPrefab, TextResources.SKILLS_FISHING, 0, 0, GreenColor);
}
if (gameManager.GetFeature(GameFeature.GameAdditionalSkills)) {
CreateSeparator();
CreateSkillLabel(TextResources.SKILLS_CRITICALHIT);
_criticalChancePanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_CRITICALHIT_CHANCE);
_criticalExtraDamagePanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_CRITICALHIT_EXTRADMG);
CreateSkillLabel(TextResources.SKILLS_LIFELEECH);
_lifeLeechChancePanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_LIFELEECH_CHANCE);
_lifeLeechAmountPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_LIFELEECH_AMOUNT);
CreateSkillLabel(TextResources.SKILLS_MANALEECH);
_manaLeechChancePanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_MANALEECH_CHANCE);
_manaLeechAmountPanel = CreateSkillPanel(_skillRawPanelPrefab, TextResources.SKILLS_MANALEECH_AMOUNT);
var skillPanels = new SkillPanel[] {
_criticalChancePanel, _criticalExtraDamagePanel,
_lifeLeechChancePanel, _lifeLeechAmountPanel,
_manaLeechChancePanel, _manaLeechAmountPanel
};
foreach (var skillPanel in skillPanels) {
var rt = skillPanel.labelText.rectTransform;
rt.offsetMin = new Vector2(5, rt.offsetMin.y);
}
}
UpdateMaxHeight();
}
protected void DestroyOldComponents() {
if (_expPanel) { Destroy(_expPanel.gameObject); _expPanel = null; }
if (_levelPanel) { Destroy(_levelPanel.gameObject); _levelPanel = null; }
if (_expGainRatePanel) { Destroy(_expGainRatePanel.gameObject); _expGainRatePanel = null; }
if (_hitPointsPanel) { Destroy(_hitPointsPanel.gameObject); _hitPointsPanel = null; }
if (_manaPanel) { Destroy(_manaPanel.gameObject); _manaPanel = null; }
if (_soulPointsPanel) { Destroy(_soulPointsPanel.gameObject); _soulPointsPanel = null; }
if (_capacityPanel) { Destroy(_capacityPanel.gameObject); _capacityPanel = null; }
if (_speedPanel) { Destroy(_speedPanel.gameObject); _speedPanel = null; }
if (_regenerationPanel) { Destroy(_regenerationPanel.gameObject); _regenerationPanel = null; }
if (_staminaPanel) { Destroy(_staminaPanel.gameObject); _staminaPanel = null; }
if (_offlineTrainingPanel) { Destroy(_offlineTrainingPanel.gameObject); _offlineTrainingPanel = null; }
if (_magicPanel) { Destroy(_magicPanel.gameObject); _magicPanel = null; }
if (_fistPanel) { Destroy(_fistPanel.gameObject); _fistPanel = null; }
if (_clubPanel) { Destroy(_clubPanel.gameObject); _clubPanel = null; }
if (_swordPanel) { Destroy(_swordPanel.gameObject); _swordPanel = null; }
if (_axePanel) { Destroy(_axePanel.gameObject); _axePanel = null; }
if (_distancePanel) { Destroy(_distancePanel.gameObject); _distancePanel = null; }
if (_shieldingPanel) { Destroy(_shieldingPanel.gameObject); _shieldingPanel = null; }
if (_criticalChancePanel) { Destroy(_criticalChancePanel.gameObject); _criticalChancePanel = null; }
if (_criticalExtraDamagePanel) { Destroy(_criticalExtraDamagePanel.gameObject); _criticalExtraDamagePanel = null; }
if (_lifeLeechChancePanel) { Destroy(_lifeLeechChancePanel.gameObject); _lifeLeechChancePanel = null; }
if (_lifeLeechAmountPanel) { Destroy(_lifeLeechAmountPanel.gameObject); _lifeLeechAmountPanel = null; }
if (_manaLeechChancePanel) { Destroy(_manaLeechChancePanel.gameObject); _manaLeechChancePanel = null; }
if (_manaLeechAmountPanel) { Destroy(_manaLeechAmountPanel.gameObject); _manaLeechAmountPanel = null; }
foreach (Transform child in _panelContent)
Destroy(child.gameObject);
}
private SkillPanel CreateSkillPanel(SkillPanel prefab, string name, long value = 0, float percent = 0, Color? color = null, Sprite icon = null) {
var skillPanel = Instantiate(prefab, _panelContent);
skillPanel.SetText(name);
skillPanel.SetValue(value, percent);
skillPanel.SetIcon(icon);
if (color != null)
skillPanel.SetProgressColor(color.Value);
skillPanel.name = string.Format("Skill_{0}", name);
return skillPanel;
}
private GameObject CreateSeparator() {
var newGameObject = new GameObject();
var newRectTransform = newGameObject.AddComponent<RectTransform>();
var horizontalSeparator = Instantiate(OpenTibiaUnity.GameManager.HorizontalSeparator, newRectTransform);
var hrRectTransform = horizontalSeparator.transform as RectTransform;
hrRectTransform.anchorMin = new Vector2(0, 0.5f);
hrRectTransform.anchorMax = new Vector2(1, 0.5f);
hrRectTransform.pivot = new Vector2(0.5f, 0.5f);
hrRectTransform.anchoredPosition = Vector2.zero;
newGameObject.AddComponent<LayoutElement>().minHeight = 10;
newGameObject.transform.SetParent(_panelContent);
newGameObject.name = "Separator_" + newGameObject.transform.GetSiblingIndex();
return newGameObject;
}
private TMPro.TextMeshProUGUI CreateSkillLabel(string text) {
var label = Instantiate(OpenTibiaUnity.GameManager.DefaultLabel, _panelContent);
label.SetText(string.Format("{0}:", text));
return label;
}
private void UpdateMaxHeight() {
var conetntVerticalLayoutGroup = _panelContent.GetComponent<VerticalLayoutGroup>();
if (!conetntVerticalLayoutGroup)
return;
float maxComtentHeight = (_panelContent.childCount - 1) * conetntVerticalLayoutGroup.spacing + 2;
foreach (Transform child in _panelContent) {
var childLayoutElement = child.GetComponent<LayoutElement>();
if (childLayoutElement)
maxComtentHeight += childLayoutElement.minHeight;
}
_maxContentHeight = maxComtentHeight;
}
private SkillPanel GetSkillPanelForSkillType(SkillType skillType) {
switch (skillType) {
case SkillType.Level: return _levelPanel;
case SkillType.Experience: return _expPanel;
case SkillType.ExperienceGain: return _expGainRatePanel;
case SkillType.Health: return _hitPointsPanel;
case SkillType.Mana: return _manaPanel;
case SkillType.SoulPoints: return _soulPointsPanel;
case SkillType.Capacity: return _capacityPanel;
case SkillType.Speed: return _speedPanel;
case SkillType.Food: return _regenerationPanel;
case SkillType.Stamina: return _staminaPanel;
case SkillType.OfflineTraining: return _offlineTrainingPanel;
case SkillType.MagLevel: return _magicPanel;
case SkillType.Fist: return _fistPanel;
case SkillType.Club: return _clubPanel;
case SkillType.Sword: return _swordPanel;
case SkillType.Axe: return _axePanel;
case SkillType.Distance: return _distancePanel;
case SkillType.Shield: return _shieldingPanel;
case SkillType.CriticalHitChance: return _criticalChancePanel;
case SkillType.CriticalHitDamage: return _criticalExtraDamagePanel;
case SkillType.LifeLeechChance: return _lifeLeechChancePanel;
case SkillType.LifeLeechAmount: return _lifeLeechAmountPanel;
case SkillType.ManaLeechChance: return _manaLeechChancePanel;
case SkillType.ManaLeechAmount: return _manaLeechAmountPanel;
}
return null;
}
}
}
| 0 | 0.766271 | 1 | 0.766271 | game-dev | MEDIA | 0.973593 | game-dev | 0.738967 | 1 | 0.738967 |
Minestom/Minestom | 2,388 | src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java | package net.minestom.server.adventure.bossbar;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.text.Component;
import net.minestom.server.Viewable;
import net.minestom.server.adventure.AdventurePacketConvertor;
import net.minestom.server.entity.Player;
import net.minestom.server.network.packet.server.play.BossBarPacket;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* A holder of a boss bar. This class is not intended for public use, instead you should
* use {@link BossBarManager} to manage boss bars for players.
*/
final class BossBarHolder implements Viewable {
final UUID uuid = UUID.randomUUID();
final Set<Player> players = new CopyOnWriteArraySet<>();
final BossBar bar;
BossBarHolder(BossBar bar) {
this.bar = bar;
}
BossBarPacket createRemovePacket() {
return new BossBarPacket(uuid, new BossBarPacket.RemoveAction());
}
BossBarPacket createAddPacket() {
return new BossBarPacket(uuid, new BossBarPacket.AddAction(bar));
}
BossBarPacket createPercentUpdate(float newPercent) {
return new BossBarPacket(uuid, new BossBarPacket.UpdateHealthAction(newPercent));
}
BossBarPacket createColorUpdate(BossBar.Color color) {
return new BossBarPacket(uuid, new BossBarPacket.UpdateStyleAction(color, bar.overlay()));
}
BossBarPacket createTitleUpdate(Component title) {
return new BossBarPacket(uuid, new BossBarPacket.UpdateTitleAction(title));
}
BossBarPacket createFlagsUpdate() {
return createFlagsUpdate(bar.flags());
}
BossBarPacket createFlagsUpdate(Set<BossBar.Flag> newFlags) {
return new BossBarPacket(uuid, new BossBarPacket.UpdateFlagsAction(AdventurePacketConvertor.getBossBarFlagValue(newFlags)));
}
BossBarPacket createOverlayUpdate(BossBar.Overlay overlay) {
return new BossBarPacket(uuid, new BossBarPacket.UpdateStyleAction(bar.color(), overlay));
}
@Override
public boolean addViewer(Player player) {
return this.players.add(player);
}
@Override
public boolean removeViewer(Player player) {
return this.players.remove(player);
}
@Override
public Set<Player> getViewers() {
return Collections.unmodifiableSet(this.players);
}
}
| 0 | 0.686267 | 1 | 0.686267 | game-dev | MEDIA | 0.964161 | game-dev | 0.565354 | 1 | 0.565354 |
amethyst/rustrogueliketutorial | 1,213 | chapter-61-townportal/src/random_table.rs | use rltk::RandomNumberGenerator;
pub struct RandomEntry {
name : String,
weight : i32
}
impl RandomEntry {
pub fn new<S:ToString>(name: S, weight: i32) -> RandomEntry {
RandomEntry{ name: name.to_string(), weight }
}
}
#[derive(Default)]
pub struct RandomTable {
entries : Vec<RandomEntry>,
total_weight : i32
}
impl RandomTable {
pub fn new() -> RandomTable {
RandomTable{ entries: Vec::new(), total_weight: 0 }
}
pub fn add<S:ToString>(mut self, name : S, weight: i32) -> RandomTable {
if weight > 0 {
self.total_weight += weight;
self.entries.push(RandomEntry::new(name.to_string(), weight));
}
self
}
pub fn roll(&self, rng : &mut RandomNumberGenerator) -> String {
if self.total_weight == 0 { return "None".to_string(); }
let mut roll = rng.roll_dice(1, self.total_weight)-1;
let mut index : usize = 0;
while roll > 0 {
if roll < self.entries[index].weight {
return self.entries[index].name.clone();
}
roll -= self.entries[index].weight;
index += 1;
}
"None".to_string()
}
}
| 0 | 0.548138 | 1 | 0.548138 | game-dev | MEDIA | 0.774732 | game-dev | 0.82213 | 1 | 0.82213 |
beyond-all-reason/RecoilEngine | 28,870 | rts/Map/ReadMap.cpp | /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include <cstdlib>
#include <cstring> // memcpy
#include "xsimd/xsimd.hpp"
#include "ReadMap.h"
#include "MapDamage.h"
#include "MapInfo.h"
#include "MetalMap.h"
#include "Rendering/Env/MapRendering.h"
#include "SMF/SMFReadMap.h"
#include "Game/LoadScreen.h"
#include "System/EventHandler.h"
#include "System/Exceptions.h"
#include "System/SpringMath.h"
#include "System/Threading/ThreadPool.h"
#include "System/FileSystem/ArchiveScanner.h"
#include "System/FileSystem/FileHandler.h"
#include "System/FileSystem/FileSystem.h"
#include "System/Log/ILog.h"
#include "System/SpringHash.h"
#include "System/SafeUtil.h"
#include "System/TimeProfiler.h"
#include "System/XSimdOps.hpp"
#include "Game/GlobalUnsynced.h"
#include "Sim/Misc/LosHandler.h"
#include "System/Misc/TracyDefs.h"
static constexpr size_t MAX_UHM_RECTS_PER_FRAME = 128;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CR_BIND(MapDimensions, ())
CR_REG_METADATA(MapDimensions, (
CR_MEMBER(mapx),
CR_MEMBER(mapxm1),
CR_MEMBER(mapxp1),
CR_MEMBER(mapy),
CR_MEMBER(mapym1),
CR_MEMBER(mapyp1),
CR_MEMBER(mapSquares),
CR_MEMBER(hmapx),
CR_MEMBER(hmapy),
CR_MEMBER(pwr2mapx),
CR_MEMBER(pwr2mapy)
))
CR_BIND_INTERFACE(CReadMap)
CR_REG_METADATA(CReadMap, (
CR_IGNORED(hmUpdated),
CR_IGNORED(processingHeightBounds),
CR_IGNORED(initHeightBounds),
CR_IGNORED(tempHeightBounds),
CR_IGNORED(currHeightBounds),
CR_IGNORED(unsyncedHeightInfo),
CR_IGNORED(boundingRadius),
CR_IGNORED(mapChecksum),
CR_IGNORED(heightMapSyncedPtr),
CR_IGNORED(heightMapUnsyncedPtr),
CR_IGNORED(originalHeightMapPtr),
/*
CR_IGNORED(originalHeightMap),
CR_IGNORED(centerHeightMap),
CR_IGNORED(mipCenterHeightMaps),
*/
CR_IGNORED(mipPointerHeightMaps),
/*
CR_IGNORED(visVertexNormals),
CR_IGNORED(faceNormalsSynced),
CR_IGNORED(faceNormalsUnsynced),
CR_IGNORED(centerNormalsSynced),
CR_IGNORED(centerNormalsUnsynced),
CR_IGNORED(centerNormals2D),
CR_IGNORED(slopeMap),
CR_IGNORED(typeMap),
*/
CR_IGNORED(sharedCornerHeightMaps),
CR_IGNORED(sharedCenterHeightMaps),
CR_IGNORED(sharedFaceNormals),
CR_IGNORED(sharedCenterNormals),
CR_IGNORED(sharedSlopeMaps),
CR_IGNORED(unsyncedHeightMapUpdates),
/*
CR_IGNORED( syncedHeightMapDigests),
CR_IGNORED(unsyncedHeightMapDigests),
*/
CR_POSTLOAD(PostLoad),
CR_SERIALIZER(Serialize)
))
// initialized in CGame::LoadMap
CReadMap* readMap = nullptr;
MapDimensions mapDims;
std::vector<float> CReadMap::mapFileHeightMap;
std::vector<float> CReadMap::originalHeightMap;
std::vector<float> CReadMap::centerHeightMap;
std::vector<float> CReadMap::maxHeightMap;
std::array<std::vector<float>, CReadMap::numHeightMipMaps - 1> CReadMap::mipCenterHeightMaps;
std::vector<float3> CReadMap::faceNormalsSynced;
std::vector<float3> CReadMap::faceNormalsUnsynced;
std::vector<float3> CReadMap::centerNormalsSynced;
std::vector<float3> CReadMap::centerNormalsUnsynced;
std::vector<float> CReadMap::slopeMap;
std::vector<uint8_t> CReadMap::typeMap;
std::vector<float3> CReadMap::centerNormals2D;
std::vector<uint8_t> CReadMap:: syncedHeightMapDigests;
std::vector<uint8_t> CReadMap::unsyncedHeightMapDigests;
MapTexture::~MapTexture() {
// do NOT delete a Lua-set texture here!
glDeleteTextures(1, &texIDs[RAW_TEX_IDX]);
texIDs[RAW_TEX_IDX] = 0;
texIDs[LUA_TEX_IDX] = 0;
}
CReadMap* CReadMap::LoadMap(const std::string& mapName)
{
RECOIL_DETAILED_TRACY_ZONE;
CReadMap* rm = nullptr;
if (FileSystem::GetExtension(mapName) == "sm3") {
throw content_error("[CReadMap::LoadMap] SM3 maps are no longer supported as of Spring 95.0");
} else {
// assume SMF format by default; calls ::Initialize
rm = new CSMFReadMap(mapName);
}
if (rm == nullptr)
return nullptr;
// read metal- and type-map
MapBitmapInfo mbi;
MapBitmapInfo tbi;
unsigned char* metalmapPtr = rm->GetInfoMap("metal", &mbi);
unsigned char* typemapPtr = rm->GetInfoMap("type", &tbi);
assert(mbi.width == mapDims.hmapx);
assert(mbi.height == mapDims.hmapy);
metalMap.Init(metalmapPtr, mbi.width, mbi.height, mapInfo->map.maxMetal);
if (metalmapPtr != nullptr)
rm->FreeInfoMap("metal", metalmapPtr);
if (typemapPtr != nullptr && tbi.width == mapDims.hmapx && tbi.height == mapDims.hmapy) {
assert(!typeMap.empty());
memcpy(typeMap.data(), typemapPtr, typeMap.size());
} else {
LOG_L(L_WARNING, "[CReadMap::%s] missing or illegal typemap for \"%s\" (dims=<%d,%d>)", __func__, mapName.c_str(), tbi.width, tbi.height);
}
if (typemapPtr != nullptr)
rm->FreeInfoMap("type", typemapPtr);
return rm;
}
#ifdef USING_CREG
void CReadMap::Serialize(creg::ISerializer* s)
{
RECOIL_DETAILED_TRACY_ZONE;
SerializeMapChangesBeforeMatch(s);
SerializeMapChangesDuringMatch(s);
SerializeTypeMap(s);
s->SerializeObjectInstance(&metalMap, metalMap.GetClass());
}
void CReadMap::SerializeMapChangesBeforeMatch(creg::ISerializer* s)
{
RECOIL_DETAILED_TRACY_ZONE;
SerializeMapChanges(s, GetMapFileHeightMapSynced(), const_cast<float*>(GetOriginalHeightMapSynced()));
}
void CReadMap::SerializeMapChangesDuringMatch(creg::ISerializer* s)
{
RECOIL_DETAILED_TRACY_ZONE;
SerializeMapChanges(s, GetOriginalHeightMapSynced(), const_cast<float*>(GetCornerHeightMapSynced()));
}
void CReadMap::SerializeMapChanges(creg::ISerializer* s, const float* refHeightMap, float* modifiedHeightMap) {
RECOIL_DETAILED_TRACY_ZONE;
// using integers so we can xor the original heightmap with the
// current one (affected by Lua, explosions, etc) - long runs of
// zeros for unchanged squares should compress significantly better.
int32_t* ichms = reinterpret_cast< int32_t*>(modifiedHeightMap);
const int32_t* iochms = reinterpret_cast<const int32_t*>(refHeightMap);
int32_t height;
if (s->IsWriting()) {
for (uint32_t i = 0; i < (mapDims.mapxp1 * mapDims.mapyp1); i++) {
height = ichms[i] ^ iochms[i];
s->Serialize(&height, sizeof(int32_t));
}
} else {
for (uint32_t i = 0; i < (mapDims.mapxp1 * mapDims.mapyp1); i++) {
s->Serialize(&height, sizeof(int32_t));
ichms[i] = height ^ iochms[i];
}
}
}
void CReadMap::SerializeTypeMap(creg::ISerializer* s)
{
RECOIL_DETAILED_TRACY_ZONE;
// LuaSynced can also touch the typemap, serialize it (manually)
MapBitmapInfo tbi;
uint8_t* itm = typeMap.data();
uint8_t* iotm = GetInfoMap("type", &tbi);
assert(!typeMap.empty());
assert(typeMap.size() == (tbi.width * tbi.height));
if (iotm == nullptr)
return;
uint8_t type;
if (s->IsWriting()) {
for (uint32_t i = 0; i < (mapDims.hmapx * mapDims.hmapy); i++) {
type = itm[i] ^ iotm[i];
s->Serialize(&type, sizeof(uint8_t));
}
} else {
for (uint32_t i = 0; i < (mapDims.hmapx * mapDims.hmapy); i++) {
s->Serialize(&type, sizeof(uint8_t));
itm[i] = type ^ iotm[i];
}
}
FreeInfoMap("type", iotm);
}
void CReadMap::PostLoad()
{
RECOIL_DETAILED_TRACY_ZONE;
sharedCornerHeightMaps[0] = &(*heightMapUnsyncedPtr)[0];
sharedCornerHeightMaps[1] = &(*heightMapSyncedPtr)[0];
sharedCenterHeightMaps[0] = ¢erHeightMap[0]; // NO UNSYNCED VARIANT
sharedCenterHeightMaps[1] = ¢erHeightMap[0];
sharedFaceNormals[0] = &faceNormalsUnsynced[0];
sharedFaceNormals[1] = &faceNormalsSynced[0];
sharedCenterNormals[0] = ¢erNormalsUnsynced[0];
sharedCenterNormals[1] = ¢erNormalsSynced[0];
sharedSlopeMaps[0] = &slopeMap[0]; // NO UNSYNCED VARIANT
sharedSlopeMaps[1] = &slopeMap[0];
mipPointerHeightMaps.fill(nullptr);
mipPointerHeightMaps[0] = ¢erHeightMap[0];
for (int i = 1; i < numHeightMipMaps; i++) {
mipCenterHeightMaps[i - 1].clear();
mipCenterHeightMaps[i - 1].resize((mapDims.mapx >> i) * (mapDims.mapy >> i));
mipPointerHeightMaps[i] = &mipCenterHeightMaps[i - 1][0];
}
hmUpdated = true;
mapDamage->RecalcArea(0, mapDims.mapx, 0, mapDims.mapy);
}
#endif //USING_CREG
CReadMap::~CReadMap()
{
RECOIL_DETAILED_TRACY_ZONE;
metalMap.Kill();
}
void CReadMap::Initialize()
{
RECOIL_DETAILED_TRACY_ZONE;
// set global map info
mapDims.Initialize();
float3::maxxpos = mapDims.mapx * SQUARE_SIZE - 1;
float3::maxzpos = mapDims.mapy * SQUARE_SIZE - 1;
boundingRadius = math::sqrt(Square(mapDims.mapx * SQUARE_SIZE) + Square(mapDims.mapy * SQUARE_SIZE)) * 0.5f;
{
char loadMsg[512];
const char* fmtString = "Loading Map (%u MB)";
uint32_t reqMemFootPrintKB =
((( mapDims.mapxp1) * mapDims.mapyp1 * 2 * sizeof(float)) / 1024) + // cornerHeightMap{Synced, Unsynced}
((( mapDims.mapxp1) * mapDims.mapyp1 * sizeof(float)) / 1024) + // originalHeightMap
(( mapDims.mapx * mapDims.mapy * 2 * 2 * sizeof(float3)) / 1024) + // faceNormals{Synced, Unsynced}
(( mapDims.mapx * mapDims.mapy * 2 * sizeof(float3)) / 1024) + // centerNormals{Synced, Unsynced}
((( mapDims.mapxp1) * mapDims.mapyp1 * sizeof(float3)) / 1024) + // VisVertexNormals
(( mapDims.mapx * mapDims.mapy * sizeof(float)) / 1024) + // centerHeightMap
(( mapDims.mapx * mapDims.mapy * sizeof(float)) / 1024) + // maxHeightMap
(( mapDims.hmapx * mapDims.hmapy * sizeof(float)) / 1024) + // slopeMap
(( mapDims.hmapx * mapDims.hmapy * sizeof(uint8_t)) / 1024) + // typeMap
(( mapDims.hmapx * mapDims.hmapy * sizeof(float)) / 1024) + // MetalMap::extractionMap
(( mapDims.hmapx * mapDims.hmapy * sizeof(unsigned char)) / 1024); // MetalMap::metalMap
// mipCenterHeightMaps[i]
for (int i = 1; i < numHeightMipMaps; i++) {
reqMemFootPrintKB += ((((mapDims.mapx >> i) * (mapDims.mapy >> i)) * sizeof(float)) / 1024);
}
sprintf(loadMsg, fmtString, reqMemFootPrintKB / 1024);
loadscreen->SetLoadMessage(loadMsg);
}
mapFileHeightMap.clear();
mapFileHeightMap.resize(mapDims.mapxp1 * mapDims.mapyp1);
originalHeightMap.clear();
originalHeightMap.resize(mapDims.mapxp1 * mapDims.mapyp1);
faceNormalsSynced.clear();
faceNormalsSynced.resize(mapDims.mapx * mapDims.mapy * 2);
faceNormalsUnsynced.clear();
faceNormalsUnsynced.resize(mapDims.mapx * mapDims.mapy * 2);
centerNormalsSynced.clear();
centerNormalsSynced.resize(mapDims.mapx * mapDims.mapy);
centerNormalsUnsynced.clear();
centerNormalsUnsynced.resize(mapDims.mapx * mapDims.mapy);
centerNormals2D.clear();
centerNormals2D.resize(mapDims.mapx * mapDims.mapy);
centerHeightMap.clear();
centerHeightMap.resize(mapDims.mapx * mapDims.mapy);
maxHeightMap.clear();
maxHeightMap.resize(mapDims.mapx * mapDims.mapy);
mipPointerHeightMaps.fill(nullptr);
mipPointerHeightMaps[0] = ¢erHeightMap[0];
originalHeightMapPtr = &originalHeightMap;
for (int i = 1; i < numHeightMipMaps; i++) {
mipCenterHeightMaps[i - 1].clear();
mipCenterHeightMaps[i - 1].resize((mapDims.mapx >> i) * (mapDims.mapy >> i));
mipPointerHeightMaps[i] = &mipCenterHeightMaps[i - 1][0];
}
slopeMap.clear();
slopeMap.resize(mapDims.hmapx * mapDims.hmapy);
// by default, all squares are set to terrain-type 0
typeMap.clear();
typeMap.resize(mapDims.hmapx * mapDims.hmapy, 0);
assert(heightMapSyncedPtr != nullptr);
assert(heightMapUnsyncedPtr != nullptr);
assert(originalHeightMapPtr != nullptr);
{
sharedCornerHeightMaps[0] = &(*heightMapUnsyncedPtr)[0];
sharedCornerHeightMaps[1] = &(*heightMapSyncedPtr)[0];
sharedCenterHeightMaps[0] = ¢erHeightMap[0]; // NO UNSYNCED VARIANT
sharedCenterHeightMaps[1] = ¢erHeightMap[0];
sharedFaceNormals[0] = &faceNormalsUnsynced[0];
sharedFaceNormals[1] = &faceNormalsSynced[0];
sharedCenterNormals[0] = ¢erNormalsUnsynced[0];
sharedCenterNormals[1] = ¢erNormalsSynced[0];
sharedSlopeMaps[0] = &slopeMap[0]; // NO UNSYNCED VARIANT
sharedSlopeMaps[1] = &slopeMap[0];
}
InitHeightBounds();
syncedHeightMapDigests.clear();
unsyncedHeightMapDigests.clear();
// not callable here because losHandler is still uninitialized, deferred to Game::PostLoadSim
// InitHeightMapDigestVectors();
UpdateHeightMapSynced({0, 0, mapDims.mapx, mapDims.mapy});
unsyncedHeightInfo.resize(
(mapDims.mapx / PATCH_SIZE) * (mapDims.mapy / PATCH_SIZE),
float3{
initHeightBounds.x,
initHeightBounds.y,
(initHeightBounds.y + initHeightBounds.x) * 0.5f
}
);
// FIXME: sky & skyLight aren't created yet (crashes in SMFReadMap.cpp)
// UpdateDraw(true);
}
void CReadMap::InitHeightBounds()
{
RECOIL_DETAILED_TRACY_ZONE;
const float* heightmap = GetCornerHeightMapSynced();
for (int i = 0; i < (mapDims.mapxp1 * mapDims.mapyp1); ++i) {
mapFileHeightMap[i] = heightmap[i];
}
LoadOriginalHeightMapAndChecksum();
}
void CReadMap::LoadOriginalHeightMapAndChecksum()
{
RECOIL_DETAILED_TRACY_ZONE;
const float* heightmap = GetCornerHeightMapSynced();
initHeightBounds.x = std::numeric_limits<float>::max();
initHeightBounds.y = std::numeric_limits<float>::lowest();
tempHeightBounds = initHeightBounds;
uint32_t checksum = 0;
for (int i = 0; i < (mapDims.mapxp1 * mapDims.mapyp1); ++i) {
originalHeightMap[i] = heightmap[i];
initHeightBounds.x = std::min(initHeightBounds.x, heightmap[i]);
initHeightBounds.y = std::max(initHeightBounds.y, heightmap[i]);
checksum = spring::LiteHash(&heightmap[i], sizeof(heightmap[i]), checksum);
}
mapChecksum = spring::LiteHash(mapInfo->map.name.c_str(), mapInfo->map.name.size(), checksum);
currHeightBounds.x = initHeightBounds.x;
currHeightBounds.y = initHeightBounds.y;
}
uint32_t CReadMap::CalcHeightmapChecksum()
{
RECOIL_DETAILED_TRACY_ZONE;
const float* heightmap = GetCornerHeightMapSynced();
uint32_t checksum = 0;
for (int i = 0; i < (mapDims.mapxp1 * mapDims.mapyp1); ++i) {
checksum = spring::LiteHash(&heightmap[i], sizeof(heightmap[i]), checksum);
}
return spring::LiteHash(mapInfo->map.name.c_str(), mapInfo->map.name.size(), checksum);
}
uint32_t CReadMap::CalcTypemapChecksum()
{
RECOIL_DETAILED_TRACY_ZONE;
uint32_t checksum = spring::LiteHash(&typeMap[0], typeMap.size() * sizeof(typeMap[0]), 0);
for (const CMapInfo::TerrainType& tt : mapInfo->terrainTypes) {
checksum = spring::LiteHash(tt.name.c_str(), tt.name.size(), checksum);
checksum = spring::LiteHash(&tt.hardness, offsetof(CMapInfo::TerrainType, receiveTracks) - offsetof(CMapInfo::TerrainType, hardness), checksum);
}
return checksum;
}
void CReadMap::UpdateDraw(bool firstCall)
{
SCOPED_TIMER("Update::ReadMap::UHM");
if (unsyncedHeightMapUpdates.empty())
return;
//optimize layout
unsyncedHeightMapUpdates.Process(firstCall);
const int N = static_cast<int>(std::min(MAX_UHM_RECTS_PER_FRAME, unsyncedHeightMapUpdates.size()));
for (int i = 0; i < N; i++) {
UpdateHeightMapUnsynced(*(unsyncedHeightMapUpdates.begin() + i));
};
UpdateHeightMapUnsyncedPost();
for (int i = 0; i < N; i++) {
eventHandler.UnsyncedHeightMapUpdate(*(unsyncedHeightMapUpdates.begin() + i));
}
for (int i = 0; i < N; i++) {
unsyncedHeightMapUpdates.pop_front();
}
}
void CReadMap::UpdateHeightMapSynced(const SRectangle& hgtMapRect)
{
RECOIL_DETAILED_TRACY_ZONE;
const bool initialize = (hgtMapRect == SRectangle{ 0, 0, mapDims.mapx, mapDims.mapy });
const int2 mins = {hgtMapRect.x1 - 1, hgtMapRect.z1 - 1};
const int2 maxs = {hgtMapRect.x2 + 1, hgtMapRect.z2 + 1};
// NOTE:
// rectangles are clamped to map{x,y}m1 which are the proper inclusive bounds for center heightmaps
// parts of UpdateHeightMapUnsynced() (vertex normals, normal texture) however inclusively clamp to
// map{x,y} since they index corner heightmaps, while UnsyncedHeightMapUpdate() EventClients should
// already expect {x,z}2 <= map{x,y} and do internal clamping as well
const SRectangle centerRect = {std::max(mins.x, 0), std::max(mins.y, 0), std::min(maxs.x, mapDims.mapxm1), std::min(maxs.y, mapDims.mapym1)};
const SRectangle cornerRect = {std::max(mins.x, 0), std::max(mins.y, 0), std::min(maxs.x, mapDims.mapx ), std::min(maxs.y, mapDims.mapy )};
UpdateCenterHeightmap(centerRect, initialize);
UpdateMipHeightmaps(centerRect, initialize);
UpdateFaceNormals(centerRect, initialize);
UpdateSlopemap(centerRect, initialize); // must happen after UpdateFaceNormals()!
// push the unsynced update; initial one without LOS check
if (initialize) {
unsyncedHeightMapUpdates.push_back(cornerRect);
} else {
#ifdef USE_HEIGHTMAP_DIGESTS
// convert heightmap rectangle to LOS-map space
const int2 losMapSize = losHandler->los.size;
const SRectangle losMapRect = centerRect * (SQUARE_SIZE * losHandler->los.invDiv);
// heightmap updated, increment digests (byte-overflow is intentional!)
for (int lmz = losMapRect.z1; lmz <= losMapRect.z2; ++lmz) {
for (int lmx = losMapRect.x1; lmx <= losMapRect.x2; ++lmx) {
const int losMapIdx = lmx + lmz * (losMapSize.x + 1);
assert(losMapIdx < syncedHeightMapDigests.size());
syncedHeightMapDigests[losMapIdx]++;
}
}
#endif
HeightMapUpdateLOSCheck(cornerRect);
}
}
void CReadMap::UpdateHeightBounds(int syncFrame)
{
RECOIL_DETAILED_TRACY_ZONE;
constexpr int PACING_PERIOD = GAME_SPEED; //tune if needed
int dataChunk = syncFrame % PACING_PERIOD;
if (dataChunk == 0) {
if (processingHeightBounds)
currHeightBounds = tempHeightBounds;
processingHeightBounds = hmUpdated;
hmUpdated = false;
}
if (!processingHeightBounds)
return;
if (dataChunk == 0) {
tempHeightBounds.x = std::numeric_limits<float>::max();
tempHeightBounds.y = std::numeric_limits<float>::lowest();
}
const int idxBeg = (dataChunk + 0) * mapDims.mapxp1 * mapDims.mapyp1 / PACING_PERIOD;
const int idxEnd = (dataChunk + 1) * mapDims.mapxp1 * mapDims.mapyp1 / PACING_PERIOD;
UpdateTempHeightBoundsSIMD(idxBeg, idxEnd);
}
void CReadMap::UpdateTempHeightBoundsSIMD(size_t idxBeg, size_t idxEnd)
{
RECOIL_DETAILED_TRACY_ZONE;
tempHeightBounds.xy = xsimd::reduce(
heightMapSyncedPtr->begin() + idxBeg,
heightMapSyncedPtr->begin() + idxEnd,
tempHeightBounds.xy,
MinOp{}, MaxOp{}
);
}
void CReadMap::UpdateHeightBounds()
{
RECOIL_DETAILED_TRACY_ZONE;
tempHeightBounds.x = std::numeric_limits<float>::max();
tempHeightBounds.y = std::numeric_limits<float>::lowest();
UpdateTempHeightBoundsSIMD(0, mapDims.mapxp1 * mapDims.mapyp1);
currHeightBounds.x = tempHeightBounds.x;
currHeightBounds.y = tempHeightBounds.y;
}
void CReadMap::UpdateCenterHeightmap(const SRectangle& rect, bool initialize) const
{
RECOIL_DETAILED_TRACY_ZONE;
const float* heightmapSynced = GetCornerHeightMapSynced();
for_mt_chunk(rect.z1, rect.z2 + 1, [heightmapSynced, &rect](const int y) {
for (int x = rect.x1; x <= rect.x2; x++) {
const int idxTL = (y + 0) * mapDims.mapxp1 + x + 0;
const int idxTR = (y + 0) * mapDims.mapxp1 + x + 1;
const int idxBL = (y + 1) * mapDims.mapxp1 + x + 0;
const int idxBR = (y + 1) * mapDims.mapxp1 + x + 1;
const int index = y * mapDims.mapx + x;
const float height =
heightmapSynced[idxTL] +
heightmapSynced[idxTR] +
heightmapSynced[idxBL] +
heightmapSynced[idxBR];
centerHeightMap[index] = height * 0.25f;
maxHeightMap[index] = std::max
( std::max(heightmapSynced[idxTL], heightmapSynced[idxTR])
, std::max(heightmapSynced[idxBL], heightmapSynced[idxBR])
);
}
}, 256);
}
void CReadMap::UpdateMipHeightmaps(const SRectangle& rect, bool initialize)
{
RECOIL_DETAILED_TRACY_ZONE;
for (int i = 0; i < numHeightMipMaps - 1; i++) {
const int hmapx = mapDims.mapx >> i;
const int sx = (rect.x1 >> i) & (~1);
const int ex = (rect.x2 >> i);
const int sy = (rect.z1 >> i) & (~1);
const int ey = (rect.z2 >> i);
float* topMipMap = mipPointerHeightMaps[i ];
float* subMipMap = mipPointerHeightMaps[i + 1];
for (int y = sy; y < ey; y += 2) {
for (int x = sx; x < ex; x += 2) {
const float height =
topMipMap[(x ) + (y ) * hmapx] +
topMipMap[(x ) + (y + 1) * hmapx] +
topMipMap[(x + 1) + (y ) * hmapx] +
topMipMap[(x + 1) + (y + 1) * hmapx];
subMipMap[(x / 2) + (y / 2) * hmapx / 2] = height * 0.25f;
}
}
}
}
void CReadMap::UpdateFaceNormals(const SRectangle& rect, bool initialize)
{
RECOIL_DETAILED_TRACY_ZONE;
const float* heightmapSynced = GetCornerHeightMapSynced();
const int z1 = std::max( 0, rect.z1 - 1);
const int x1 = std::max( 0, rect.x1 - 1);
const int z2 = std::min(mapDims.mapym1, rect.z2 + 1);
const int x2 = std::min(mapDims.mapxm1, rect.x2 + 1);
for_mt_chunk(z1, z2 + 1, [&](const int y) {
float3 fnTL;
float3 fnBR;
for (int x = x1; x <= x2; x++) {
const int idxTL = (y ) * mapDims.mapxp1 + x; // TL
const int idxBL = (y + 1) * mapDims.mapxp1 + x; // BL
const float& hTL = heightmapSynced[idxTL ];
const float& hTR = heightmapSynced[idxTL + 1];
const float& hBL = heightmapSynced[idxBL ];
const float& hBR = heightmapSynced[idxBL + 1];
// normal of top-left triangle (face) in square
//
// *---> e1
// |
// |
// v
// e2
//const float3 e1( SQUARE_SIZE, hTR - hTL, 0);
//const float3 e2( 0, hBL - hTL, SQUARE_SIZE);
//const float3 fnTL = (e2.cross(e1)).Normalize();
fnTL.y = SQUARE_SIZE;
fnTL.x = - (hTR - hTL);
fnTL.z = - (hBL - hTL);
fnTL.Normalize();
// normal of bottom-right triangle (face) in square
//
// e3
// ^
// |
// |
// e4 <---*
//const float3 e3(-SQUARE_SIZE, hBL - hBR, 0);
//const float3 e4( 0, hTR - hBR,-SQUARE_SIZE);
//const float3 fnBR = (e4.cross(e3)).Normalize();
fnBR.y = SQUARE_SIZE;
fnBR.x = (hBL - hBR);
fnBR.z = (hTR - hBR);
fnBR.Normalize();
faceNormalsSynced[(y * mapDims.mapx + x) * 2 ] = fnTL;
faceNormalsSynced[(y * mapDims.mapx + x) * 2 + 1] = fnBR;
// square-normal
centerNormalsSynced[y * mapDims.mapx + x] = (fnTL + fnBR).Normalize();
centerNormals2D[y * mapDims.mapx + x] = (fnTL + fnBR).Normalize2D();
if (initialize) {
faceNormalsUnsynced[(y * mapDims.mapx + x) * 2 ] = faceNormalsSynced[(y * mapDims.mapx + x) * 2 ];
faceNormalsUnsynced[(y * mapDims.mapx + x) * 2 + 1] = faceNormalsSynced[(y * mapDims.mapx + x) * 2 + 1];
centerNormalsUnsynced[y * mapDims.mapx + x] = centerNormalsSynced[y * mapDims.mapx + x];
}
}
}, 64);
}
void CReadMap::UpdateSlopemap(const SRectangle& rect, bool initialize)
{
RECOIL_DETAILED_TRACY_ZONE;
const int sx = std::max(0, (rect.x1 / 2) - 1);
const int ex = std::min(mapDims.hmapx - 1, (rect.x2 / 2) + 1);
const int sy = std::max(0, (rect.z1 / 2) - 1);
const int ey = std::min(mapDims.hmapy - 1, (rect.z2 / 2) + 1);
for_mt_chunk(sy, ey + 1, [sx, ex](const int y) {
for (int x = sx; x <= ex; x++) {
const int idx0 = (y*2 ) * (mapDims.mapx) + x*2;
const int idx1 = (y*2 + 1) * (mapDims.mapx) + x*2;
float avgslope = 0.0f;
avgslope += faceNormalsSynced[(idx0 ) * 2 ].y;
avgslope += faceNormalsSynced[(idx0 ) * 2 + 1].y;
avgslope += faceNormalsSynced[(idx0 + 1) * 2 ].y;
avgslope += faceNormalsSynced[(idx0 + 1) * 2 + 1].y;
avgslope += faceNormalsSynced[(idx1 ) * 2 ].y;
avgslope += faceNormalsSynced[(idx1 ) * 2 + 1].y;
avgslope += faceNormalsSynced[(idx1 + 1) * 2 ].y;
avgslope += faceNormalsSynced[(idx1 + 1) * 2 + 1].y;
avgslope *= 0.125f;
float maxslope = faceNormalsSynced[(idx0 ) * 2 ].y;
maxslope = std::min(maxslope, faceNormalsSynced[(idx0 ) * 2 + 1].y);
maxslope = std::min(maxslope, faceNormalsSynced[(idx0 + 1) * 2 ].y);
maxslope = std::min(maxslope, faceNormalsSynced[(idx0 + 1) * 2 + 1].y);
maxslope = std::min(maxslope, faceNormalsSynced[(idx1 ) * 2 ].y);
maxslope = std::min(maxslope, faceNormalsSynced[(idx1 ) * 2 + 1].y);
maxslope = std::min(maxslope, faceNormalsSynced[(idx1 + 1) * 2 ].y);
maxslope = std::min(maxslope, faceNormalsSynced[(idx1 + 1) * 2 + 1].y);
// smooth it a bit, so small holes don't block huge tanks
const float lerp = maxslope / avgslope;
const float slope = mix(maxslope, avgslope, lerp);
slopeMap[y * mapDims.hmapx + x] = 1.0f - slope;
}
}, 128);
}
/// split the update into multiple invididual (los-square) chunks
void CReadMap::HeightMapUpdateLOSCheck(const SRectangle& hgtMapRect)
{
RECOIL_DETAILED_TRACY_ZONE;
// size of LOS square in heightmap coords; divisor is SQUARE_SIZE * 2^mipLevel
const int losSqrSize = losHandler->los.mipDiv / SQUARE_SIZE;
const SRectangle losMapRect = hgtMapRect * (SQUARE_SIZE * losHandler->los.invDiv); // LOS space
const float* ctrHgtMap = readMap->GetCenterHeightMapSynced();
const auto PushRect = [&](SRectangle& subRect, int hmx, int hmz) {
if (subRect.GetArea() > 0) {
subRect.ClampIn(hgtMapRect);
unsyncedHeightMapUpdates.push_back(subRect);
subRect = {hmx + losSqrSize, hmz, hmx + losSqrSize, hmz + losSqrSize};
} else {
subRect.x1 = hmx + losSqrSize;
subRect.x2 = hmx + losSqrSize;
}
};
for (int lmz = losMapRect.z1; lmz <= losMapRect.z2; ++lmz) {
const int hmz = lmz * losSqrSize;
int hmx = losMapRect.x1 * losSqrSize;
SRectangle subRect = {hmx, hmz, hmx, hmz + losSqrSize};
for (int lmx = losMapRect.x1; lmx <= losMapRect.x2; ++lmx) {
hmx = lmx * losSqrSize;
// NB:
// LosHandler expects positions in center-heightmap bounds, but hgtMapRect is a corner-rectangle
// as such hmx and hmz have to be clamped by CenterSqrToPos before the center-height is accessed
if (!(gu->spectatingFullView || losHandler->InLos(CenterSqrToPos(ctrHgtMap, hmx, hmz), gu->myAllyTeam))) {
PushRect(subRect, hmx, hmz);
continue;
}
if (!HasHeightMapViewChanged({lmx, lmz})) {
PushRect(subRect, hmx, hmz);
continue;
}
// update rectangle size
subRect.x2 = hmx + losSqrSize;
}
PushRect(subRect, hmx, hmz);
}
}
void CReadMap::InitHeightMapDigestVectors(const int2 losMapSize)
{
RECOIL_DETAILED_TRACY_ZONE;
#if defined(USE_HEIGHTMAP_DIGESTS)
assert(losHandler != nullptr);
assert(syncedHeightMapDigests.empty());
const int xsize = losMapSize.x + 1;
const int ysize = losMapSize.y + 1;
syncedHeightMapDigests.clear();
syncedHeightMapDigests.resize(xsize * ysize, 0);
unsyncedHeightMapDigests.clear();
unsyncedHeightMapDigests.resize(xsize * ysize, 0);
#endif
}
bool CReadMap::HasHeightMapViewChanged(const int2 losMapPos)
{
RECOIL_DETAILED_TRACY_ZONE;
#if defined(USE_HEIGHTMAP_DIGESTS)
const int2 losMapSize = losHandler->los.size;
const int losMapIdx = losMapPos.x + losMapPos.y * (losMapSize.x + 1);
assert(losMapIdx < syncedHeightMapDigests.size() && losMapIdx >= 0);
if (unsyncedHeightMapDigests[losMapIdx] != syncedHeightMapDigests[losMapIdx]) {
unsyncedHeightMapDigests[losMapIdx] = syncedHeightMapDigests[losMapIdx];
return true;
}
return false;
#else
return true;
#endif
}
void CReadMap::UpdateLOS(const SRectangle& hgtMapRect)
{
RECOIL_DETAILED_TRACY_ZONE;
if (gu->spectatingFullView)
return;
// currently we use the LOS for view updates (alternatives are AirLOS and/or radar)
// the other maps use different resolutions, must check size here for safety
// (if another source is used, change the res. of syncedHeightMapDigests etc)
assert(hgtMapRect.GetWidth() <= (losHandler->los.mipDiv / SQUARE_SIZE));
assert(losHandler != nullptr);
SRectangle hgtMapPoint = hgtMapRect;
//HACK: UpdateLOS() is called for single LOS squares, but we use <= in HeightMapUpdateLOSCheck().
// This would make our update area 4x as large, so we need to make the rectangle a point. Better
// would be to use < instead of <= everywhere.
//FIXME: this actually causes spikes in the UHM
// hgtMapPoint.x2 = hgtMapPoint.x1;
// hgtMapPoint.z2 = hgtMapPoint.z1;
HeightMapUpdateLOSCheck(hgtMapPoint);
}
void CReadMap::BecomeSpectator()
{
RECOIL_DETAILED_TRACY_ZONE;
HeightMapUpdateLOSCheck({0, 0, mapDims.mapx, mapDims.mapy});
}
namespace {
template<typename T>
void CopySyncedToUnsyncedImpl(const std::vector<T>& src, std::vector<T>& dst) {
std::copy(src.begin(), src.end(), dst.begin());
};
}
void CReadMap::CopySyncedToUnsynced()
{
RECOIL_DETAILED_TRACY_ZONE;
CopySyncedToUnsyncedImpl(*heightMapSyncedPtr, *heightMapUnsyncedPtr);
CopySyncedToUnsyncedImpl(faceNormalsSynced, faceNormalsUnsynced);
CopySyncedToUnsyncedImpl(centerNormalsSynced, centerNormalsUnsynced);
eventHandler.UnsyncedHeightMapUpdate(SRectangle{ 0, 0, mapDims.mapx, mapDims.mapy });
}
bool CReadMap::HasVisibleWater() const { return (!mapRendering->voidWater && !IsAboveWater()); }
bool CReadMap::HasOnlyVoidWater() const { return ( mapRendering->voidWater && IsUnderWater()); }
| 0 | 0.943179 | 1 | 0.943179 | game-dev | MEDIA | 0.85563 | game-dev | 0.81388 | 1 | 0.81388 |
Grasscutters/Grasscutter | 1,360 | src/main/java/emu/grasscutter/data/excels/EquipAffixData.java | package emu.grasscutter.data.excels;
import emu.grasscutter.data.*;
import emu.grasscutter.data.common.FightPropData;
import java.util.ArrayList;
@ResourceType(name = "EquipAffixExcelConfigData.json")
public class EquipAffixData extends GameResource {
private int affixId;
private int id;
private int level;
private long nameTextMapHash;
private String openConfig;
private FightPropData[] addProps;
private float[] paramList;
@Override
public int getId() {
return affixId;
}
public int getMainId() {
return id;
}
public int getLevel() {
return level;
}
public long getNameTextMapHash() {
return nameTextMapHash;
}
public String getOpenConfig() {
return openConfig;
}
public FightPropData[] getAddProps() {
return addProps;
}
public float[] getParamList() {
return paramList;
}
@Override
public void onLoad() {
ArrayList<FightPropData> parsed = new ArrayList<FightPropData>(getAddProps().length);
for (FightPropData prop : getAddProps()) {
if (prop.getPropType() != null && prop.getValue() != 0f) {
prop.onLoad();
parsed.add(prop);
}
}
this.addProps = parsed.toArray(new FightPropData[parsed.size()]);
}
}
| 0 | 0.863247 | 1 | 0.863247 | game-dev | MEDIA | 0.816486 | game-dev | 0.940992 | 1 | 0.940992 |
BetonQuest/BetonQuest | 3,893 | src/main/java/org/betonquest/betonquest/compatibility/protocollib/conversation/MenuConvIOSettings.java | package org.betonquest.betonquest.compatibility.protocollib.conversation;
import net.kyori.adventure.text.Component;
import org.betonquest.betonquest.api.common.component.VariableComponent;
import org.betonquest.betonquest.api.quest.QuestException;
import org.betonquest.betonquest.api.text.TextParser;
import org.bukkit.configuration.ConfigurationSection;
/**
* Menu conversation settings.
*/
public record MenuConvIOSettings(int lineLength, int lineCount, int lineFillBefore, int refreshDelay, int rateLimit,
String npcNameType, String npcNameAlign,
boolean npcNameSeparator, boolean optionsSeparator,
String controlSelect, String controlMove, String controlCancel,
VariableComponent npcName, VariableComponent npcText, Component npcTextWrap,
VariableComponent optionText, Component optionTextWrap,
VariableComponent optionSelectedText, Component optionSelectedTextWrap,
Component scrollUp, Component scrollDown) {
/**
* Creates a new instance of MenuConvIOSettings from a configuration section.
*
* @param textParser the text parser to use to parse components
* @param config the configuration section to read settings from
* @return a new instance of MenuConvIOSettings
* @throws QuestException if the text parser could not parse a text
*/
public static MenuConvIOSettings fromConfigurationSection(final TextParser textParser, final ConfigurationSection config) throws QuestException {
final int lineLength = config.getInt("line_length");
final int lineCount = config.getInt("line_count");
final int lineFillBefore = config.getInt("line_fill_before");
final int refreshDelay = config.getInt("refresh_delay");
final int rateLimit = config.getInt("rate_limit");
final String npcNameType = config.getString("npc_name_type", "");
final String npcNameAlign = config.getString("npc_name_align", "");
final boolean npcNameSeparator = config.getBoolean("npc_name_separator");
final boolean optionsSeparator = config.getBoolean("options_separator");
final String controlSelect = config.getString("control_select", "");
final String controlMove = config.getString("control_move", "");
final String controlCancel = config.getString("control_cancel", "");
final String npcName = config.getString("npc_name", "");
final String npcText = config.getString("npc_text", "");
final String npcTextWrap = config.getString("npc_text_wrap", "");
final String optionText = config.getString("option_text", "");
final String optionTextWrap = config.getString("option_text_wrap", "");
final String optionSelectedText = config.getString("option_selected_text", "");
final String optionSelectedTextWrap = config.getString("option_selected_text_wrap", "");
final String scrollUp = config.getString("scroll_up", "");
final String scrollDown = config.getString("scroll_down", "");
return new MenuConvIOSettings(lineLength, lineCount, lineFillBefore, refreshDelay, rateLimit,
npcNameType, npcNameAlign, npcNameSeparator, optionsSeparator, controlSelect, controlMove, controlCancel,
new VariableComponent(textParser.parse(npcName)), new VariableComponent(textParser.parse(npcText)),
textParser.parse(npcTextWrap), new VariableComponent(textParser.parse(optionText)),
textParser.parse(optionTextWrap), new VariableComponent(textParser.parse(optionSelectedText)),
textParser.parse(optionSelectedTextWrap), textParser.parse(scrollUp), textParser.parse(scrollDown)
);
}
}
| 0 | 0.883265 | 1 | 0.883265 | game-dev | MEDIA | 0.295941 | game-dev | 0.892674 | 1 | 0.892674 |
Auviotre/Enigmatic-Addons | 5,867 | src/main/java/auviotre/enigmatic/addon/contents/items/NightScroll.java | package auviotre.enigmatic.addon.contents.items;
import auviotre.enigmatic.addon.api.items.IBetrayed;
import auviotre.enigmatic.addon.handlers.SuperAddonHandler;
import com.aizistral.enigmaticlegacy.api.generic.SubscribeConfig;
import com.aizistral.enigmaticlegacy.helpers.ItemLoreHelper;
import com.aizistral.enigmaticlegacy.items.generic.ItemBaseCurio;
import com.aizistral.omniconfig.wrappers.Omniconfig;
import com.aizistral.omniconfig.wrappers.OmniconfigWrapper;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Rarity;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.lighting.LevelLightEngine;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.jetbrains.annotations.NotNull;
import top.theillusivec4.curios.api.SlotContext;
import javax.annotation.Nullable;
import java.util.List;
import java.util.UUID;
public class NightScroll extends ItemBaseCurio implements IBetrayed {
public static Omniconfig.PerhapsParameter averageDamageBoost;
public static Omniconfig.PerhapsParameter averageDamageResistance;
public static Omniconfig.PerhapsParameter averageLifeSteal;
public NightScroll() {
super(ItemBaseCurio.getDefaultProperties().rarity(Rarity.EPIC));
}
@SubscribeConfig
public static void onConfig(@NotNull OmniconfigWrapper builder) {
builder.pushPrefix("PactofDarkNight");
averageDamageBoost = builder.comment("The average damage boost modifier provided by Pact of Dark Night.").max(100).getPerhaps("AverageDamageBoost", 20);
averageDamageResistance = builder.comment("The average damage resistance modifier provided by Pact of Dark Night.").max(100).getPerhaps("AverageDamageResistance", 16);
averageLifeSteal = builder.comment("The average life stealing modifier provided by Pact of Dark Night.").max(100).getPerhaps("AverageLifeSteal", 8);
builder.popPrefix();
}
public static boolean isDark(Player player) {
if (!SuperAddonHandler.isOKOne(player)) return false;
if (player.hasEffect(MobEffects.DARKNESS)) return true;
LevelLightEngine lightEngine = player.level().getLightEngine();
BlockPos blockPos = player.blockPosition();
return true;
}
public static float getDarkModifier(Player player) {
if (player == null || !SuperAddonHandler.isOKOne(player)) return 0.4F;
if (player.hasEffect(MobEffects.DARKNESS)) return 2.0F;
LevelLightEngine lightEngine = player.level().getLightEngine();
BlockPos blockPos = player.blockPosition();
int i = 16 - lightEngine.getRawBrightness(blockPos, 8);
return 0.4F + 0.1F * i;
}
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> list, TooltipFlag flagIn) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
if (Screen.hasShiftDown()) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticaddons.nightScroll1");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticaddons.nightScroll2");
float darkModifier = getDarkModifier(Minecraft.getInstance().player);
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticaddons.nightScroll3", ChatFormatting.GOLD, (int) (darkModifier * averageDamageBoost.getValue().asPercentage()) + "%");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticaddons.nightScroll4", ChatFormatting.GOLD, (int) (darkModifier * averageDamageResistance.getValue().asPercentage()) + "%");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticaddons.nightScroll5", ChatFormatting.GOLD, (int) (darkModifier * averageLifeSteal.getValue().asPercentage()) + "%");
} else {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.holdShift");
}
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.indicateCursedOnesOnly(list);
}
public void curioTick(SlotContext context, ItemStack stack) {
if (context.entity() instanceof Player player) {
if (!SuperAddonHandler.isOKOne(player) && !(player.isCreative() || player.isSpectator())) {
player.addEffect(new MobEffectInstance(MobEffects.DARKNESS, 20));
}
}
}
public Multimap<Attribute, AttributeModifier> getAttributeModifiers(SlotContext slotContext, UUID uuid, ItemStack stack) {
Multimap<Attribute, AttributeModifier> attributes = HashMultimap.create();
LivingEntity entity = slotContext.entity();
if (entity instanceof Player player && isDark(player)) {
attributes.put(Attributes.ATTACK_DAMAGE, new AttributeModifier(UUID.fromString("6F27C266-9DCD-22DC-E491-4AF7B6A8CCF9"), "Dark Bonus", averageDamageBoost.getValue().asModifier(false) * getDarkModifier(player), AttributeModifier.Operation.MULTIPLY_TOTAL));
}
return attributes;
}
}
| 0 | 0.913672 | 1 | 0.913672 | game-dev | MEDIA | 0.991561 | game-dev | 0.985144 | 1 | 0.985144 |
asteroide-development/Asteroide | 1,625 | src/main/java/spigey/asteroide/commands/BypassCommand.java | package spigey.asteroide.commands;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import meteordevelopment.meteorclient.commands.Command;
import meteordevelopment.meteorclient.utils.player.ChatUtils;
import net.minecraft.command.CommandSource;
import net.minecraft.text.Text;
import spigey.asteroide.util;
public class BypassCommand extends Command {
public BypassCommand() {
super("bypass", "Lets you bypass most chat filters");
}
@Override
public void build(LiteralArgumentBuilder<CommandSource> builder) {
builder.executes(context -> {
error("You have to specify a message!");
return SINGLE_SUCCESS;
});
builder.then(argument("text", StringArgumentType.greedyString()).executes(context -> {
String copy = StringArgumentType.getString(context, "text")
.replaceAll("a", "а")
.replaceAll("c", "с")
.replaceAll("e", "е")
.replaceAll("h", "һ")
.replaceAll("i", "і")
.replaceAll("j", "ј")
.replaceAll("n", "ո")
.replaceAll("o", "о")
.replaceAll("p", "р")
.replaceAll("u", "ս")
.replaceAll("v", "ν")
.replaceAll("x", "х")
.replaceAll("y", "у");
ChatUtils.sendMsg(Text.of("Done creating the bypassed message!"));
ChatUtils.sendMsg(util.getSendButton(util.getCopyButton(copy), copy));
return SINGLE_SUCCESS;
}));
}
}
| 0 | 0.789924 | 1 | 0.789924 | game-dev | MEDIA | 0.390932 | game-dev,web-backend | 0.78688 | 1 | 0.78688 |
assaultcube/AC | 51,992 | source/src/menus.cpp | // menus.cpp: ingame menu system (also used for scores and serverlist)
#include "cube.h"
hashtable<const char *, gmenu> menus;
gmenu *curmenu = NULL, *lastmenu = NULL;
color *menuselbgcolor, *menuseldescbgcolor = NULL;
static int menurighttabwidth = 888; // width of sliders and text input fields (is adapted to font and screen size later)
vector<gmenu *> menustack;
COMMANDF(curmenu, "", () {result(curmenu ? curmenu->name : "");} );
inline gmenu *setcurmenu(gmenu *newcurmenu) // only change curmenu through here!
{
curmenu = newcurmenu;
keyrepeat(curmenu && curmenu->allowinput && !curmenu->hotkeys, KR_MENU);
return curmenu;
}
void menuset(void *m, bool save)
{
if(curmenu==m) return;
if(curmenu)
{
if(save && curmenu->allowinput) menustack.add(curmenu);
else curmenu->close();
}
if(setcurmenu((gmenu *)m)) curmenu->open();
}
void showmenu(const char *name, bool top)
{
menurighttabwidth = max(VIRTW/4, 15 * text_width("w")); // adapt to screen and font size every time a menu opens
if(!name)
{
setcurmenu(NULL);
return;
}
gmenu *m = menus.access(name);
if(!m) return;
if(!top && curmenu)
{
if(curmenu==m) return;
loopv(menustack) if(menustack[i]==m) return;
menustack.insert(0, m);
return;
}
menuset(m);
}
void closemenu(const char *name)
{
gmenu *m;
if(!name)
{
if(curmenu) curmenu->close();
while(!menustack.empty())
{
m = menustack.pop();
if(m) m->close();
}
setcurmenu(NULL);
return;
}
m = menus.access(name);
if(!m) return;
if(curmenu==m) menuset(menustack.empty() ? NULL : menustack.pop(), false);
else loopv(menustack)
{
if(menustack[i]==m)
{
menustack.remove(i);
return;
}
}
}
COMMAND(closemenu, "s");
void showmenu_(const char *name)
{
showmenu(name, true);
}
COMMANDN(showmenu, showmenu_, "s");
const char *persistentmenuselectionalias(const char *name)
{
static defformatstring(al)("__lastmenusel_%s", name);
filtertext(al, al, FTXT__ALIAS);
return al;
}
int normalizemenuselection(int sel, int length)
{
if (sel < 0) sel = length > 0 ? length - 1 : 0;
else if (sel >= length) sel = 0;
return sel;
}
void menuselect(void *menu, int sel)
{
gmenu &m = *(gmenu *)menu;
sel = normalizemenuselection(sel, m.items.length());
if(m.items.inrange(sel))
{
int oldsel = m.menusel;
m.menusel = sel;
if(m.allowinput)
{
if(sel!=oldsel)
{
if(m.items.inrange(oldsel)) m.items[oldsel]->focus(false);
if(!m.items[sel]->greyedout) m.items[sel]->focus(true);
audiomgr.playsound(S_MENUSELECT, SP_HIGHEST);
if(m.persistentselection)
{
defformatstring(val)("%d", sel);
alias(persistentmenuselectionalias(m.name), val);
}
}
}
}
}
void drawarrow(int dir, int x, int y, int size, float r = 1.0f, float g = 1.0f, float b = 1.0f)
{
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glColor3f(r, g, b);
glBegin(GL_TRIANGLES);
glVertex2f(x, dir ? y+size : y);
glVertex2f(x+size/2, dir ? y : y+size);
glVertex2f(x+size, dir ? y+size : y);
glEnd();
xtraverts += 3;
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
}
#define MAXMENU 34
bool menuvisible()
{
if(!curmenu) return false;
return true;
}
extern void *scoremenu;
void rendermenu()
{
if(curmenu != scoremenu) setscope(false);
gmenu &m = *curmenu;
m.refresh();
m.render();
}
void mitem::render(int x, int y, int w)
{
if(isselection()) renderbg(x, y, w, menuselbgcolor);
else if(bgcolor) renderbg(x, y, w, bgcolor);
}
void mitem::renderbg(int x, int y, int w, color *c)
{
if(isselection()) blendbox(x-FONTH/4, y-FONTH/6, x+w+FONTH/4, y+FONTH+FONTH/6, false, -1, c);
else blendbox(x, y, x+w, y+FONTH, false, -1, c);
}
int mitem::execaction(const char *arg1)
{
int result = 0;
if(getaction())
{
if(curmenu) setcontext("menu", curmenu->name);
push("arg1", arg1);
result = execute(getaction());
pop("arg1");
resetcontext();
}
return result;
}
bool mitem::isselection() { return parent->allowinput && !parent->hotkeys && parent->items.inrange(parent->menusel) && parent->items[parent->menusel]==this; }
color mitem::gray(0.2f, 0.2f, 0.2f);
color mitem::white(1.0f, 1.0f, 1.0f);
color mitem::whitepulse(1.0f, 1.0f, 1.0f);
bool mitem::menugreyedout = false;
// text item
struct mitemmanual : mitem
{
const char *text, *action, *hoveraction, *desc;
mitemmanual(gmenu *parent, char *text, char *action, char *hoveraction, color *bgcolor, const char *desc) : mitem(parent, bgcolor, mitem::TYPE_MANUAL), text(text), action(action), hoveraction(hoveraction), desc(desc) {}
virtual int width() { return text_width(text) + (strchr(text, '\n') ? menurighttabwidth : 0); }
virtual void render(int x, int y, int w)
{
int c = greyedout ? 128 : 255;
mitem::render(x, y, w);
const char *nl = strchr(text, '\n');
if(nl)
{
string l;
copystring(l, text, min(MAXSTRLEN, (int)strcspn(text, "\n") + 1));
draw_text(l, x, y, c, c, c);
draw_text(nl + 1, x + w - max(menurighttabwidth, text_width(nl + 1)), y, c, c, c);
}
else draw_text(text, x, y, c, c, c);
}
virtual void focus(bool on)
{
if(on && hoveraction) execute(hoveraction);
}
virtual int select()
{
int result = 0;
if(action && action[0])
{
gmenu *oldmenu = curmenu;
result = execaction(text);
if(result >= 0 && oldmenu == curmenu)
{
menuset(NULL, false);
menustack.shrink(0);
}
}
return result;
}
virtual const char *getdesc() { return desc; }
virtual const char *gettext() { return text; }
virtual const char *getaction() { return action; }
};
struct mitemtext : mitemmanual
{
mitemtext(gmenu *parent, char *text, char *action, char *hoveraction, color *bgcolor, const char *desc = NULL) : mitemmanual(parent, text, action, hoveraction, bgcolor, desc) {}
virtual ~mitemtext()
{
DELETEA(text);
DELETEA(action);
DELETEA(hoveraction);
DELETEA(desc);
}
};
VARP(hidebigmenuimages, 0, 0, 1);
struct mitemimagemanual : mitemmanual
{
Texture *image;
font *altfont;
mitemimagemanual(gmenu *parent, const char *filename, const char *altfontname, char *text, char *action, char *hoveraction, color *bgcolor, const char *desc = NULL) : mitemmanual(parent, text, action, hoveraction, bgcolor, desc)
{
image = filename ? textureload(filename, 3) : NULL;
altfont = altfontname ? getfont(altfontname) : NULL;
}
virtual ~mitemimagemanual() {}
virtual int width()
{
if(image && *text != '\t') return (FONTH*image->xs)/image->ys + FONTH/2 + mitemmanual::width();
return mitemmanual::width();
}
virtual void render(int x, int y, int w)
{
mitem::render(x, y, w);
if(image || altfont)
{
int xs = 0, c = greyedout ? 128 : 255;
if(image)
{
xs = (FONTH*image->xs)/image->ys;
framedquadtexture(image->id, x, y, xs, FONTH, 0, 255, true);
}
draw_text(text, !image || *text == '\t' ? x : x+xs + FONTH/2, y, c, c, c);
if(altfont && strchr(text, '\a'))
{
char *r = newstring(text), *re, *l = r;
while((re = strchr(l, '\a')) && re[1])
{
*re = '\0';
x += text_width(l);
l = re + 2;
pushfont(altfont->name);
draw_textf("%s%c", x, y, greyedout ? "\f4" : "", re[1]);
popfont();
}
delete[] r;
}
if(image && isselection() && !hidebigmenuimages && image->ys > FONTH)
{
w += FONTH;
int xs = (2 * VIRTW - w) / 5, ys = (xs * image->ys) / image->xs;
x = (6 * VIRTW + w - 2 * xs) / 4; y = VIRTH - ys / 2;
framedquadtexture(image->id, x, y, xs, ys, FONTH);
}
}
else mitemmanual::render(x, y, w);
}
};
struct mitemimage : mitemimagemanual
{
mitemimage(gmenu *parent, const char *filename, char *text, char *action, char *hoveraction, color *bgcolor, const char *desc = NULL, const char *altfont = NULL) : mitemimagemanual(parent, filename, altfont, text, action, hoveraction, bgcolor, desc) {}
virtual ~mitemimage()
{
DELETEA(text);
DELETEA(action);
DELETEA(hoveraction);
DELETEA(desc);
}
};
VARP(browsefiledesc, 0, 1, 1);
struct mitemmapload : mitemmanual
{
const char *filename, *mapmessage;
Texture *image;
mitemmapload(gmenu *parent, const char *filename, char *text, char *action, char *hoveraction, const char *desc) : mitemmanual(parent, text, action, hoveraction, NULL, desc), filename(filename), mapmessage(NULL), image(NULL) {}
virtual ~mitemmapload()
{
delstring(filename);
DELETEA(mapmessage);
DELETEA(text);
DELETEA(action);
DELETEA(hoveraction);
DELETEA(desc);
}
virtual void key(int code, bool isdown)
{
if(code == SDLK_LEFT && parent->xoffs > -50) parent->xoffs -= 2;
else if(code == SDLK_RIGHT && parent->xoffs < 50) parent->xoffs += 2;
}
virtual void render(int x, int y, int w)
{
int c = greyedout ? 128 : 255;
mitem::render(x, y, w);
draw_text(text, x, y, c, c, c);
if(isselection())
{
if(!image && !mapmessage)
{ // load map description and preview picture
silent_texture_load = true;
const char *cgzpath = "packages" PATHDIVS "maps";
if(browsefiledesc)
{ // checking map messages is slow and may be disabled
mapmessage = getfiledesc(cgzpath, behindpath(filename), "cgz"); // check for regular map
if(!mapmessage) mapmessage = getfiledesc((cgzpath = "packages" PATHDIVS "maps" PATHDIVS "official"), behindpath(filename), "cgz"); // check for official map
}
defformatstring(p2p)("%s/preview/%s.jpg", cgzpath, filename);
if(!hidebigmenuimages) image = textureload(p2p, 3);
if(!image || image == notexture) image = textureload("packages/misc/nopreview.jpg", 3);
silent_texture_load = false;
}
w += FONTH;
int xs = (2 * VIRTW - w - x) / 2, xp = x + w + xs / 2, ym = VIRTH - FONTH/2;
if(image && !hidebigmenuimages && image->ys > FONTH)
{
int ys = (xs * image->ys) / image->xs, yp = VIRTH - ys / 2;
ym = yp + ys + 2 * FONTH;
framedquadtexture(image->id, xp, yp, xs, ys, FONTH);
draw_text(text, xp + xs/2 - text_width(text)/2, yp + ys);
}
if(mapmessage && *mapmessage) draw_text(mapmessage, xp - FONTH, ym, 0xFF, 0xFF, 0xFF, 0xFF, -1, 2 * VIRTW - (xp - FONTH) - FONTH/2);
}
}
};
// text input item
struct mitemtextinput : mitemtext
{
textinputbuffer input;
char *defaultvalueexp;
bool modified, hideinput;
mitemtextinput(gmenu *parent, char *text, char *value, char *action, char *hoveraction, color *bgcolor, int maxchars, int maskinput) : mitemtext(parent, text, action, hoveraction, bgcolor), defaultvalueexp(value), modified(false), hideinput(false)
{
mitemtype = TYPE_TEXTINPUT;
copystring(input.buf, value);
input.max = maxchars > 0 ? min(maxchars, MAXSTRLEN - 1) : 15;
hideinput = (maskinput != 0);
}
virtual int width()
{
return text_width(text) + menurighttabwidth;
}
virtual void render(int x, int y, int w)
{
int c = greyedout ? 128 : 255;
bool sel = isselection();
if(sel)
{
renderbg(x+w-menurighttabwidth, y-FONTH/6, menurighttabwidth, menuselbgcolor);
renderbg(x, y-FONTH/6, w-menurighttabwidth-FONTH/2, menuseldescbgcolor);
}
draw_text(text, x, y, c, c, c);
int cibl = (int)strlen(input.buf); // current input-buffer length
int iboff = input.pos > 14 ? (input.pos < cibl ? input.pos - 14 : cibl - 14) : (input.pos == -1 ? (cibl > 14 ? cibl - 14 : 0) : 0); // input-buffer offset
string showinput, tempinputbuf; int sc = 14;
copystring(tempinputbuf, input.buf);
if(hideinput && !(SDL_GetModState() & MOD_KEYS_CTRL))
{ // "mask" user input with asterisks, use for menuitemtextinputs that take passwords
for(char *c = tempinputbuf; *c; c++)
*c = '*';
}
while(iboff > 0)
{
copystring(showinput, tempinputbuf + iboff - 1, sc + 2);
if(text_width(showinput) > menurighttabwidth) break;
iboff--; sc++;
}
while(iboff + sc < cibl)
{
copystring(showinput, tempinputbuf + iboff, sc + 2);
if(text_width(showinput) > menurighttabwidth) break;
sc++;
}
copystring(showinput, tempinputbuf + iboff, sc + 1);
draw_text(showinput, x+w-menurighttabwidth, y, c, c, c, 255, sel && !greyedout ? (input.pos>=0 ? (input.pos > sc ? sc : input.pos) : cibl) : -1);
}
virtual void focus(bool on)
{
if(on && hoveraction) execute(hoveraction);
textinput(on, TI_MENU);
if(action && !on && modified && parent->items.find(this) != parent->items.length() - 1)
{
modified = false;
execaction(input.buf);
}
}
virtual void key(int code, bool isdown)
{
if(input.key(code)) modified = true;
if(action && code == SDLK_RETURN && modified && parent->items.find(this) != parent->items.length() - 1)
{
modified = false;
execaction(input.buf);
}
}
void say(const char *text)
{
if(input.say(text)) modified = true;
}
virtual void init()
{
setdefaultvalue();
modified = false;
}
virtual int select()
{
int result = 0;
if(parent->menusel == parent->items.length() - 1)
{
const char *tmp = text;
text = input.buf;
result = mitemmanual::select();
text = tmp;
textinput(result, TI_MENU);
}
return result;
}
void setdefaultvalue()
{
const char *p = defaultvalueexp;
char *r = executeret(p);
copystring(input.buf, r ? r : "");
if(r) delete[] r;
}
};
// slider item
VARP(wrapslider, 0, 0, 1);
struct mitemslider : mitem
{
int min_, max_, step, value, maxvaluewidth;
char *text, *valueexp, *action;
string curval;
vector<char *> opts;
bool wrap, isradio;
mitemslider(gmenu *parent, char *text, int _min, int _max, char *value, char *display, char *action, color *bgcolor, bool wrap, bool isradio) : mitem(parent, bgcolor, mitem::TYPE_SLIDER),
min_(_min), max_(_max), value(_min), maxvaluewidth(0), text(text), valueexp(value), action(action), wrap(wrap), isradio(isradio)
{
char *enddigits;
step = (int) strtol(display, &enddigits, 10);
if(!*display || *enddigits)
{
step = 1;
explodelist(display, opts);
if(max_ - min_ + 1 != opts.length())
{
if(max_ != -1) clientlogf("menuitemslider: display string length (%d) doesn't match max-min (%d) \"%s\" [%s]", opts.length(), max_ - min_ + 1, text, display);
max_ = min_ + opts.length() - 1;
}
}
getmaxvaluewidth();
}
virtual ~mitemslider()
{
opts.deletearrays();
DELETEA(text);
DELETEA(valueexp);
DELETEA(action);
}
virtual int width() { return text_width(text) + (isradio ? 0 : menurighttabwidth) + maxvaluewidth + 2*FONTH; }
virtual void render(int x, int y, int w)
{
bool sel = isselection();
int range = max_-min_;
int cval = value-min_;
int tw = text_width(text), ow = isradio ? text_width(curval) : menurighttabwidth, pos = !isradio || ow < menurighttabwidth ? menurighttabwidth : ow;
if(sel)
{
renderbg(x + w - pos, y, ow, menuselbgcolor);
renderbg(x, y, w - pos - FONTH/2, menuseldescbgcolor);
if(pos - ow > FONTH/2) renderbg(x + w - pos + ow + FONTH/2, y, pos - ow - FONTH/2, menuseldescbgcolor);
}
int c = greyedout ? 128 : 255;
draw_text(text, x, y, c, c, c);
draw_text(curval, x + (isradio ? w - pos : tw), y, c, c, c);
if(!isradio)
{
blendbox(x+w-menurighttabwidth, y+FONTH/3, x+w, y+FONTH*2/3, false, -1, &gray);
int offset = (int)(cval/((float)range)*menurighttabwidth);
blendbox(x+w-menurighttabwidth+offset-FONTH/6, y, x+w-menurighttabwidth+offset+FONTH/6, y+FONTH, false, -1, greyedout ? &gray : (sel ? &whitepulse : &white));
}
}
virtual void key(int code, bool isdown)
{
if(code == SDLK_LEFT) slide(false);
else if(code == SDLK_RIGHT) slide(true);
}
virtual void init()
{
const char *p = valueexp;
char *v = executeret(p);
if(v)
{
value = clamp(int(ATOI(v)), min_, max_);
delete[] v;
}
displaycurvalue();
}
void slide(bool right)
{
value += right ? step : -step;
if (wrapslider || wrap)
{
if (value > max_) value = min_;
if (value < min_) value = max_;
}
else value = min(max_, max(min_, value));
displaycurvalue();
if(action)
{
string v;
itoa(v, value);
execaction(v);
}
}
void displaycurvalue()
{
if(isradio)
{
*curval = '\0';
loopv(opts) concatformatstring(curval, "%s\1%c %s", i ? " " : "", (i + min_ == value) ? '\11' : '\10', opts[i]);
}
else if(opts.length()) // extract display name from list
{
int idx = value - min_;
copystring(curval, opts.inrange(idx) ? opts[idx] : "");
}
else itoa(curval, value); // display number only
}
void getmaxvaluewidth()
{
int oldvalue = value;
maxvaluewidth = 0;
for(int v = min_; v <= max_; v++)
{
value = v;
displaycurvalue();
maxvaluewidth = max(text_width(curval), maxvaluewidth);
}
value = oldvalue;
displaycurvalue();
}
virtual const char *gettext() { return text; }
virtual const char *getaction() { return action; }
};
// key input item
struct mitemkeyinput : mitem
{
char *text, *bindcmd;
const char *keyname;
vector<int> newkeys;
int isup, bindtype;
string keynames;
static const char *unknown, *empty;
bool capture;
mitemkeyinput(gmenu *parent, char *text, char *bindcmd, color *bgcolor, int bindtype) : mitem(parent, bgcolor, mitem::TYPE_KEYINPUT), text(text), bindcmd(bindcmd),
keyname(NULL), isup(0), bindtype(bindtype), capture(false) {};
~mitemkeyinput()
{
DELETEA(text);
DELETEA(bindcmd);
}
virtual int width() { return text_width(text)+text_width(keyname ? keyname : " "); }
virtual void render(int x, int y, int w)
{
int tw = text_width(keyname ? keyname : " "), c = greyedout ? 128 : 255;
static color capturec(0.4f, 0, 0);
if(isselection())
{
blendbox(x+w-tw-FONTH, y-FONTH/6, x+w+FONTH, y+FONTH+FONTH/6, false, -1, capture ? &capturec : NULL);
blendbox(x, y-FONTH/6, x+w-tw-FONTH, y+FONTH+FONTH/6, false, -1, menuseldescbgcolor);
}
draw_text(text, x, y, c, c, c);
draw_text(keyname, x+w-tw, y, c, c, c);
}
virtual void init()
{
keynames[0] = 0;
for(keym **km = findbinda(bindcmd, bindtype); *km; km++) concatformatstring(keynames, " or %s", (*km)->name);
keyname = *keynames ? keynames + 4 : unknown;
capture = false;
menuheader(parent, NULL, NULL);
}
virtual int select()
{
capture = true;
isup = 0;
keyname = empty;
newkeys.setsize(0);
keynames[0] = '\0';
return 0;
}
virtual void key(int code, bool isdown)
{
keym *km;
if(!capture || !((km = findbindc(code)))) return;
if(code == SDLK_ESCAPE)
{
capture = false;
parent->init();
return;
}
bool known = newkeys.find(code) >= 0;
if(isdown)
{
if(!known)
{
if(km->actions[bindtype][0] && strcmp(km->actions[bindtype], bindcmd))
{
static defformatstring(keybound)("\f3Warning: \"%s\" key is already in use. You can press ESC to cancel.", km->name);
menuheader(parent, NULL, keybound);
}
newkeys.add(code);
concatformatstring(keynames, "%s or ", km->name);
keyname = keynames;
}
}
else
{
if(known && ++isup == newkeys.length())
{
for(keym **km = findbinda(bindcmd, bindtype); *km; km++) bindkey(*km, "", bindtype); // clear existing binds to this cmd
bool bindfailed = false;
loopv(newkeys) bindfailed = !bindc(newkeys[i], bindcmd, bindtype) || bindfailed;
if(bindfailed) conoutf("\f3could not bind key");
else parent->init(); // show new keys
}
}
}
virtual const char* gettext() { return text; }
};
const char *mitemkeyinput::unknown = "?";
const char *mitemkeyinput::empty = " ";
// checkbox menu item
struct mitemcheckbox : mitem
{
char *text, *valueexp, *action;
int pos;
bool checked;
mitemcheckbox(gmenu *parent, char *text, char *value, char *action, int pos, color *bgcolor) : mitem(parent, bgcolor, mitem::TYPE_CHECKBOX), text(text), valueexp(value), action(action), pos(pos), checked(false) {}
~mitemcheckbox()
{
DELETEA(text);
DELETEA(valueexp);
DELETEA(action);
}
virtual int width() { return text_width(text) + (pos ? menurighttabwidth : FONTH + FONTH/3); }
virtual int select()
{
checked = !checked;
return execaction(checked ? "1" : "0");
}
virtual void init()
{
const char *p = valueexp;
char *r = executeret(p);
checked = (r && atoi(r) > 0);
if(r) delete[] r;
}
virtual void render(int x, int y, int w)
{
bool sel = isselection();
const static int boxsize = FONTH;
int offs = ((menurighttabwidth - FONTH) * ((msctrl % 41) ? pos : (50 + 50 * sinf(totalmillis / 300.0f + y)))) / 100;
int c = greyedout ? 128 : 255;
if(sel)
{
renderbg(x, y, w-boxsize-offs-FONTH/2, menuseldescbgcolor);
renderbg(x+w-boxsize-offs, y, boxsize, menuselbgcolor);
if(offs > FONTH/2) renderbg(x+w-offs+FONTH/2, y, offs-FONTH/2, menuseldescbgcolor);
}
draw_text(text, x, y, c, c, c);
x -= offs;
blendbox(x+w-boxsize, y, x+w, y+boxsize, false, -1, &gray);
color *col = greyedout ? &gray : (sel ? &whitepulse : &white);
if(checked)
{
int x1 = x+w-boxsize-FONTH/6, x2 = x+w+FONTH/6, y1 = y-FONTH/6, y2 = y+boxsize+FONTH/6;
line(x1, y1, x2, y2, col);
line(x2, y1, x1, y2, col);
}
}
virtual const char* gettext() { return text; }
virtual const char *getaction() { return action; }
};
// console iface
void *addmenu(const char *name, const char *title, bool allowinput, void (__cdecl *refreshfunc)(void *, bool), bool (__cdecl *keyfunc)(void *, int, bool), bool hotkeys, bool forwardkeys)
{
gmenu *m = menus.access(name);
if(!m)
{
name = newstring(name);
m = &menus[name];
m->name = name;
m->initaction = NULL;
m->header = m->footer = NULL;
m->menusel = 0;
}
m->title = title;
DELSTRING(m->mdl);
m->allowinput = allowinput;
m->inited = false;
m->hotkeys = hotkeys;
m->refreshfunc = refreshfunc;
m->keyfunc = keyfunc;
DELSTRING(m->usefont);
m->allowblink = false;
m->forwardkeys = forwardkeys;
lastmenu = m;
mitem::menugreyedout = false;
return m;
}
void newmenu(char *name, int *hotkeys, int *forwardkeys)
{
addmenu(name, NULL, true, NULL, NULL, *hotkeys > 0, *forwardkeys > 0);
}
COMMAND(newmenu, "sii");
void menureset(void *menu)
{
gmenu &m = *(gmenu *)menu;
m.items.deletecontents();
}
void delmenu(const char *name)
{
if (!name) return;
gmenu *m = menus.access(name);
if (!m) return;
else menureset(m);
}
COMMAND(delmenu, "s");
void menuitemmanual(void *menu, char *text, char *action, color *bgcolor, const char *desc)
{
gmenu &m = *(gmenu *)menu;
m.items.add(new mitemmanual(&m, text, action, NULL, bgcolor, desc));
}
void menuimagemanual(void *menu, const char *filename, const char *altfontname, char *text, char *action, color *bgcolor, const char *desc)
{
gmenu &m = *(gmenu *)menu;
m.items.add(new mitemimagemanual(&m, filename, altfontname, text, action, NULL, bgcolor, desc));
}
void menutitlemanual(void *menu, const char *title)
{
gmenu &m = *(gmenu *)menu;
m.title = title;
}
void menuheader(void *menu, char *header, char *footer, bool heap)
{
gmenu &m = *(gmenu *)menu;
if(m.headfootheap) { DELSTRING(m.header); DELSTRING(m.footer); }
m.header = (header && *header) || heap ? header : NULL;
m.footer = (footer && *footer) || heap ? footer : NULL;
m.headfootheap = heap; // false: "manual"
}
COMMANDF(menuheader, "ss", (char *header, char *footer) { if(lastmenu) menuheader(lastmenu, *header ? newstring(header) : NULL, *footer ? newstring(footer) : NULL, true); });
void menufont(char *menu, const char *usefont)
{
gmenu *m = *menu ? menus.access(menu) : lastmenu;
if(m)
{
DELSTRING(m->usefont);
m->usefont = usefont && *usefont ? newstring(usefont) : NULL;
}
}
COMMAND(menufont, "ss");
void setmenublink(int *truth)
{
if(!lastmenu) return;
gmenu *m = lastmenu;
m->allowblink = *truth != 0;
}
COMMANDN(menucanblink, setmenublink, "i");
void menutitle(char *title)
{
if(!lastmenu) return;
gmenu *m = lastmenu;
DELSTRING(m->title);
m->title = newstring(title);
}
COMMAND(menutitle, "s");
void menuinit(char *initaction)
{
if(!lastmenu) return;
DELSTRING(lastmenu->initaction);
lastmenu->initaction = newstring(initaction);
}
COMMAND(menuinit, "s");
void menuinitselection(int *line)
{
if(!lastmenu) return;
if(lastmenu->items.inrange(*line)) lastmenu->menusel = *line;
else lastmenu->menuselinit = *line;
}
COMMAND(menuinitselection, "i");
void menuselectionpersistent()
{
if(!curmenu) return;
curmenu->persistentselection = true;
const char *val = getalias(persistentmenuselectionalias(curmenu->name));
if(val) menuselect(curmenu, ATOI(val));
}
COMMAND(menuselectionpersistent, "");
void menusynctabstops(int *onoff)
{
if(curmenu) curmenu->synctabstops = *onoff != 0;
}
COMMAND(menusynctabstops, "i");
void menurenderoffset(int *xoff, int *yoff)
{
if(!lastmenu) return;
lastmenu->xoffs = *xoff;
lastmenu->yoffs = *yoff;
}
COMMAND(menurenderoffset, "ii");
void menuselection(char *menu, int *line)
{
if(!menu || !menus.access(menu)) return;
gmenu &m = menus[menu];
menuselect(&m, *line);
}
COMMAND(menuselection, "si");
void menuitemgreyedout(int *onoff)
{
mitem::menugreyedout = *onoff != 0;
}
COMMAND(menuitemgreyedout, "i");
void menuitem(char *text, char *action, char *hoveraction, char *desc)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemtext(lastmenu, newstring(text), (action[0] && !strcmp(action,"-1")) ? NULL : newstring(action[0] ? action : text), hoveraction[0] ? newstring(hoveraction) : NULL, NULL, *desc ? newstring(desc) : NULL));
}
COMMAND(menuitem, "ssss");
void menuitemimage(char *name, char *text, char *action, char *hoveraction)
{
if(!lastmenu) return;
if(fileexists(name, "r") || findfile(name, "r") != name)
lastmenu->items.add(new mitemimage(lastmenu, name, newstring(text), action[0] ? newstring(action) : NULL, hoveraction[0] ? newstring(hoveraction) : NULL, NULL));
else
lastmenu->items.add(new mitemtext(lastmenu, newstring(text), newstring(action[0] ? action : text), hoveraction[0] ? newstring(hoveraction) : NULL, NULL));
}
COMMAND(menuitemimage, "ssss");
void menuitemaltfont(char *altfont, char *text, char *action, char *hoveraction, char *desc)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemimage(lastmenu, NULL, newstring(text), action[0] ? newstring(action) : NULL, hoveraction[0] ? newstring(hoveraction) : NULL, NULL, desc[0] ? newstring(desc) : NULL, altfont));
}
COMMAND(menuitemaltfont, "sssss");
void menuitemmapload(char *name, char *action, char *hoveraction, char *desc)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemmapload(lastmenu, newstring(name), newstring(name), *action ? newstring(action) : NULL, *hoveraction ? newstring(hoveraction) : NULL, *desc ? newstring(desc) : NULL));
}
COMMAND(menuitemmapload, "ssss");
void menuitemtextinput(char *text, char *value, char *action, char *hoveraction, int *maxchars, int *maskinput)
{
if(!lastmenu || !text || !value) return;
lastmenu->items.add(new mitemtextinput(lastmenu, newstring(text), newstring(value), action[0] ? newstring(action) : NULL, hoveraction[0] ? newstring(hoveraction) : NULL, NULL, *maxchars, *maskinput));
}
COMMAND(menuitemtextinput, "ssssii");
void menuitemslider(char *text, int *min_, int *max_, char *value, char *display, char *action, int *wrap)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemslider(lastmenu, newstring(text), *min_, *max_, newstring(value), display, action[0] ? newstring(action) : NULL, NULL, *wrap != 0, false));
}
COMMAND(menuitemslider, "siisssi");
void menuitemradio(char *text, int *min_, int *max_, char *value, char *display, char *action)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemslider(lastmenu, newstring(text), *min_, *max_, newstring(value), display, action[0] ? newstring(action) : NULL, NULL, true, true));
}
COMMAND(menuitemradio, "siisss");
void menuitemcheckbox(char *text, char *value, char *action, int *pos)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemcheckbox(lastmenu, newstring(text), newstring(value), action[0] ? newstring(action) : NULL, clamp(*pos, 0, 100), NULL));
}
COMMAND(menuitemcheckbox, "sssi");
void menuitemkeyinput(char *text, char *bindcmd)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemkeyinput(lastmenu, newstring(text), newstring(bindcmd), NULL, keym::ACTION_DEFAULT));
}
COMMAND(menuitemkeyinput, "ss");
void menuitemeditkeyinput(char *text, char *bindcmd)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemkeyinput(lastmenu, newstring(text), newstring(bindcmd), NULL, keym::ACTION_EDITING));
}
COMMAND(menuitemeditkeyinput, "ss");
void menuitemspectkeyinput(char *text, char *bindcmd)
{
if(!lastmenu) return;
lastmenu->items.add(new mitemkeyinput(lastmenu, newstring(text), newstring(bindcmd), NULL, keym::ACTION_SPECTATOR));
}
COMMAND(menuitemspectkeyinput, "ss");
void menumdl(char *menu, char *mdl, char *anim, int *rotspeed, int *scale)
{
gmenu *m = *menu ? menus.access(menu) : lastmenu;
if(!m) return;
DELETEA(m->mdl);
if(!*mdl) return;
m->mdl = newstring(mdl);
m->anim = findanim(anim)|ANIM_LOOP;
m->rotspeed = clamp(*rotspeed, 0, 100);
m->scale = clamp(*scale, 0, 100);
}
COMMAND(menumdl, "sssii");
void menudirlist(char *dir, char *ext, char *action, int *image, char *searchfile)
{
if(!lastmenu || !*action) return;
if(lastmenu->dirlist) delete lastmenu->dirlist;
mdirlist *d = lastmenu->dirlist = new mdirlist;
d->dir = newstring(dir);
d->ext = ext[0] ? newstring(ext): NULL;
d->action = action[0] ? newstring(action) : NULL;
d->image = *image!=0;
d->searchfile = searchfile[0] ? newstring(searchfile) : NULL;
d->subdiraction = NULL;
d->subdirdots = false;
}
COMMAND(menudirlist, "sssis");
void menudirlistsub(char *action, int *dots)
{
if(!lastmenu || !lastmenu->dirlist || !*action) return;
mdirlist *d = lastmenu->dirlist;
d->subdirdots = *dots != 0;
DELETEA(d->subdiraction);
d->subdiraction = *action ? newstring(action) : NULL;
}
COMMAND(menudirlistsub, "si");
void chmenutexture(char *menu, char *texname, char *title)
{
gmenu *m = *menu ? menus.access(menu) : NULL;
if(!m) return;
DELETEA(m->previewtexture);
if(*texname) m->previewtexture = newstring(texname);
DELETEA(m->previewtexturetitle);
if(*title) m->previewtexturetitle = newstring(title);
}
COMMAND(chmenutexture, "sss");
bool parsecolor(color *col, const char *r, const char *g, const char *b, const char *a)
{
if(!r[0] || !col) return false; // four possible parameter schemes:
if(!g[0]) g = b = r; // grey
if(!b[0]) { a = g; g = b = r; } // grey alpha
col->r = ((float) atoi(r)) / 100; // red green blue
col->g = ((float) atoi(g)) / 100; // red green blue alpha
col->b = ((float) atoi(b)) / 100;
col->alpha = a[0] ? ((float) atoi(a)) / 100 : 1.0;
return true;
}
void menuselectionbgcolor(char *r, char *g, char *b, char *a)
{
if(!menuselbgcolor) menuselbgcolor = new color;
if(!r[0]) { DELETEP(menuselbgcolor); return; }
parsecolor(menuselbgcolor, r, g, b, a);
}
COMMAND(menuselectionbgcolor, "ssss");
void menuselectiondescbgcolor(char *r, char *g, char *b, char *a)
{
if(!menuseldescbgcolor) menuseldescbgcolor = new color;
if(!r[0]) { DELETEP(menuseldescbgcolor); return; }
parsecolor(menuseldescbgcolor, r, g, b, a);
}
COMMAND(menuselectiondescbgcolor, "ssss");
static bool iskeypressed(int key)
{
int numkeys = 0;
Uint8 const* state = SDL_GetKeyboardState(&numkeys);
return key < numkeys && state[key] != 0;
}
void menusay(const char *text)
{
if(curmenu && curmenu->allowinput && curmenu->items.inrange(curmenu->menusel)) curmenu->items[curmenu->menusel]->say(text);
}
// move menu selection forward or backward and skip empty items that are not selectable
int movemenuselection(int currentmenusel, int direction)
{
direction = clamp(direction, -1, 1);
int newmenusel = currentmenusel;
bool selectable = false;
for(int i = 0; i < curmenu->items.length(); i++)
{
newmenusel += direction;
newmenusel = normalizemenuselection(newmenusel, curmenu->items.length());
if(curmenu->items.inrange(newmenusel))
{
mitem *newitem = curmenu->items[newmenusel];
selectable = !newitem->greyedout && newitem->gettext() && newitem->gettext()[0] != '\0' && (newitem->mitemtype!=mitem::TYPE_MANUAL||newitem->getaction());
}
if(selectable) break;
}
if(selectable) return newmenusel;
else return currentmenusel;
}
bool menukey(int code, bool isdown, SDL_Keymod mod)
{
if(!curmenu) return false;
int n = curmenu->items.length(), menusel = curmenu->menusel;
if(curmenu->items.inrange(menusel) && !curmenu->items[menusel]->greyedout)
{
mitem *m = curmenu->items[menusel];
if(m->mitemtype == mitem::TYPE_KEYINPUT && ((mitemkeyinput *)m)->capture)
{
m->key(code, isdown);
return true;
}
}
if(isdown)
{
int pagesize = MAXMENU - curmenu->headeritems();
switch(code)
{
case SDLK_PAGEUP: menusel -= pagesize; break;
case SDLK_PAGEDOWN:
if(menusel+pagesize>=n && menusel/pagesize!=(n-1)/pagesize) menusel = n-1;
else menusel += pagesize;
break;
case SDLK_ESCAPE:
case SDL_AC_BUTTON_RIGHT:
if(!curmenu->allowinput) return false;
menuset(menustack.empty() ? NULL : menustack.pop(), false);
return true;
break;
case SDLK_UP:
case SDL_AC_BUTTON_WHEELUP:
if(iskeypressed(SDL_SCANCODE_LCTRL)) return menukey(SDLK_LEFT);
if(iskeypressed(SDL_SCANCODE_LALT)) return menukey(SDLK_RIGHTBRACKET);
if(!curmenu->allowinput) return false;
menusel = movemenuselection(menusel, -1);
break;
case SDLK_DOWN:
case SDL_AC_BUTTON_WHEELDOWN:
if(iskeypressed(SDL_SCANCODE_LCTRL)) return menukey(SDLK_RIGHT);
if(iskeypressed(SDL_SCANCODE_LALT)) return menukey(SDLK_LEFTBRACKET);
if(!curmenu->allowinput) return false;
menusel = movemenuselection(menusel, 1);
break;
case SDLK_TAB:
if(!curmenu->allowinput) return false;
if(mod & KMOD_LSHIFT) menusel = movemenuselection(menusel, -1);
else menusel = movemenuselection(menusel, 1);
break;
case SDLK_1:
case SDLK_2:
case SDLK_3:
case SDLK_4:
case SDLK_5:
case SDLK_6:
case SDLK_7:
case SDLK_8:
case SDLK_9:
if(curmenu->allowinput && curmenu->hotkeys)
{
int idx = code-SDLK_1;
if(curmenu->items.inrange(idx) && !curmenu->items[idx]->greyedout)
{
menuselect(curmenu, idx);
mitem &m = *curmenu->items[idx];
m.select();
}
return true;
}
default:
{
if(!curmenu->allowinput) return false;
if(curmenu->keyfunc && (*curmenu->keyfunc)(curmenu, code, isdown)) return true;
if(!curmenu->items.inrange(menusel)) return false;
mitem &m = *curmenu->items[menusel];
if(!m.greyedout) m.key(code, isdown);
if(code == SDLK_HOME && m.mitemtype != mitem::TYPE_TEXTINPUT) menuselect(curmenu, (menusel = 0));
return !curmenu->forwardkeys;
}
}
if(!curmenu->hotkeys) menuselect(curmenu, menusel);
return true;
}
else
{
switch(code) // action on keyup to avoid repeats
{
case SDLK_PRINTSCREEN:
curmenu->conprintmenu();
return true;
case SDLK_F12:
if(curmenu->allowinput)
{
extern void screenshot(const char *filename);
screenshot(NULL);
}
break;
}
if(!curmenu->allowinput || !curmenu->items.inrange(menusel)) return false;
mitem &m = *curmenu->items[menusel];
if(code==SDLK_RETURN || code==SDLK_KP_ENTER || code==SDLK_SPACE || code==SDL_AC_BUTTON_LEFT || code==SDL_AC_BUTTON_MIDDLE)
{
if(!m.greyedout && m.select() != -1) audiomgr.playsound(S_MENUENTER, SP_HIGHEST);
return true;
}
return false;
}
}
void rendermenumdl()
{
if(!curmenu) return;
gmenu &m = *curmenu;
if(!m.mdl) return;
glPushMatrix();
glLoadIdentity();
glRotatef(90+180, 0, -1, 0);
glRotatef(90, -1, 0, 0);
glScalef(1, -1, 1);
bool isplayermodel = !strncmp(m.mdl, "playermodels", strlen("playermodels"));
bool isweapon = !strncmp(m.mdl, "weapons", strlen("weapons"));
vec pos;
if(!isweapon) pos = vec(0.5f, 0.3f, -0.1f);
else pos = vec(0.50f, 0, 0.425f);
float yaw = 1.0f, pitch = isplayermodel || isweapon ? 0.0f : camera1->pitch;
if(m.rotspeed) yaw += lastmillis/5.0f/100.0f*m.rotspeed;
if(fabs(pitch) < 10.0f) pitch = 0.0f;
else pitch += 10.0f * (pitch < 0 ? 1 : -1);
int tex = 0;
if(isplayermodel)
{
defformatstring(skin)("packages/models/%s.jpg", m.mdl);
tex = -(int)textureload(skin)->id;
}
modelattach a[2];
if(isplayermodel)
{
a[0].name = "weapons/subgun/world";
a[0].tag = "tag_weapon";
}
float scale = (m.scale ? m.scale * 0.04f: 1.0f) * 0.25f;
rendermodel(isplayermodel ? "playermodels" : m.mdl, m.anim|ANIM_DYNALLOC, tex, -1, pos, 0, yaw, pitch, 0, 0, NULL, a, scale);
glPopMatrix();
dimeditinfopanel = 0;
}
void gmenu::refresh()
{
if(refreshfunc)
{
(*refreshfunc)(this, !inited);
inited = true;
}
if(menusel>=items.length()) menusel = max(items.length()-1, 0);
}
void gmenu::open()
{
inited = false;
if(!allowinput) menusel = 0;
if(!forwardkeys) player1->stopmoving();
setcontext("menu", name);
if(initaction)
{
gmenu *oldlastmenu = lastmenu;
lastmenu = this;
execute(initaction);
lastmenu = oldlastmenu;
}
if(items.inrange(menuselinit)) { menusel = menuselinit; menuselinit = -1; }
if(items.inrange(menusel) && !items[menusel]->greyedout) items[menusel]->focus(true);
init();
resetcontext();
}
void gmenu::close()
{
if(items.inrange(menusel)) items[menusel]->focus(false);
}
void gmenu::conprintmenu()
{
if(title) conoutf( "[:: %s ::]", title);//if(items.length()) conoutf( " %03d items", items.length());
loopv(items) { conoutf("%03d: %s%s%s", 1+i, items[i]->gettext(), items[i]->getaction()?"|\t|":"", items[i]->getaction()?items[i]->getaction():""); }
}
const char *menufilesortorders[] = { "normal", "reverse", "ignorecase", "ignorecase_reverse", "" };
int (*menufilesortcmp[])(const char **, const char **) = { stringsort, stringsortrev, stringsortignorecase, stringsortignorecaserev };
void gmenu::init()
{
if(!menuseldescbgcolor) menuseldescbgcolor = new color(0.2f, 0.2f, 0.2f, 0.2f);
if(dirlist && dirlist->dir && dirlist->ext)
{
items.deletecontents();
if(dirlist->subdiraction)
{
vector<char *> subdirs;
if(dirlist->subdirdots) subdirs.add(newstring(".."));
listsubdirs(dirlist->dir, subdirs, stringsort);
loopv(subdirs)
{
defformatstring(cdir)("\fs\f1[%s]\fr", subdirs[i]);
defformatstring(act)("%s %s", dirlist->subdiraction, escapestring(subdirs[i]));
items.add(new mitemtext(this, newstring(cdir), newstring(act), NULL, NULL, NULL));
}
}
defformatstring(sortorderalias)("menufilesort_%s", dirlist->ext);
int sortorderindex = 0;
const char *customsortorder = getalias(sortorderalias);
if(customsortorder) sortorderindex = getlistindex(customsortorder, menufilesortorders, true, 0);
vector<char *> files;
listfiles(dirlist->dir, dirlist->ext, files, menufilesortcmp[sortorderindex]);
string searchfileuc;
if(dirlist->searchfile)
{
const char *searchfilealias = getalias(dirlist->searchfile);
copystring(searchfileuc, searchfilealias ? searchfilealias : dirlist->searchfile);
strtoupper(searchfileuc);
}
loopv(files)
{
char *f = files[i], *d = (strcmp(dirlist->ext, "cgz") || dirlist->searchfile) && browsefiledesc ? getfiledesc(dirlist->dir, f, dirlist->ext) : NULL;
bool filefound = false;
if(dirlist->searchfile)
{
string fuc, duc;
copystring(fuc, f);
strtoupper(fuc);
copystring(duc, d ? d : "");
strtoupper(duc);
if(strstr(fuc, searchfileuc) || strstr(duc, searchfileuc)) filefound = true;
}
if(dirlist->image)
{
string fullname = "";
if(dirlist->dir[0]) formatstring(fullname)("%s/%s", dirlist->dir, f);
else copystring(fullname, f);
if(dirlist->ext)
{
concatstring(fullname, ".");
concatstring(fullname, dirlist->ext);
}
items.add(new mitemimage(this, newstring(fullname), f, newstring(dirlist->action), NULL, NULL, d));
}
else if(!strcmp(dirlist->ext, "cgz"))
{
if(!dirlist->searchfile || filefound)
{
items.add(new mitemmapload(this, newstring(f), newstring(f), newstring(dirlist->action), NULL, NULL));
}
DELSTRING(d);
}
else if(!strcmp(dirlist->ext, "dmo"))
{
if(!dirlist->searchfile || filefound) items.add(new mitemtext(this, f, newstring(dirlist->action), NULL, NULL, d));
}
else items.add(new mitemtext(this, f, newstring(dirlist->action), NULL, NULL, d));
}
}
loopv(items) items[i]->init();
}
int gmenu::headeritems() // returns number of header and footer lines (and also recalculates hasdesc)
{
hasdesc = false;
loopv(items) if(items[i]->getdesc()) { hasdesc = true; break; }
return (header ? 2 : 0) + (footer || hasdesc ? (footlen ? (footlen + 1) : 2) : 0);
}
FVAR(menutexturesize, 0.1f, 1.0f, 5.0f);
FVAR(menupicturesize, 0.1f, 1.6f, 5.0f);
void rendermenutexturepreview(char *previewtexture, int w, const char *title)
{
static Texture *pt = NULL;
static uint last_pt = 0;
bool ispicture = title != NULL;
uint cur_pt = hthash(previewtexture);
if(cur_pt != last_pt)
{
silent_texture_load = ispicture;
defformatstring(texpath)("packages/textures/%s", previewtexture);
pt = textureload(texpath, ispicture ? 3 : 0);
last_pt = cur_pt;
silent_texture_load = false;
}
if(pt && pt != notexture && pt->xs && pt->ys)
{
int xs = (VIRTW * (ispicture ? menupicturesize : menutexturesize)) / 4, ys = (xs * pt->ys) / pt->xs, ysmax = (3 * VIRTH) / 2;
if(ys > ysmax) ys = ysmax, xs = (ys * pt->xs) / pt->ys;
int x = (6 * VIRTW + w - 2 * xs) / 4, y = VIRTH - ys / 2 - 2 * FONTH;
extern int fullbrightlevel;
framedquadtexture(pt->id, x, y, xs, ys, FONTH / 2, fullbrightlevel);
defformatstring(res)("%dx%d", pt->xs, pt->ys);
draw_text(title ? title : res, x, y + ys + 2 * FONTH);
}
}
void gmenu::render()
{
if(usefont) pushfont(usefont);
if(!allowblink) ignoreblinkingbit = true;
bool synctabs = title != NULL || synctabstops;
const char *t = title;
if(!t)
{
static string buf;
if(hotkeys) formatstring(buf)("%s hotkeys", name);
else formatstring(buf)("[ %s menu ]", name);
t = buf;
}
int w = 0, footermaxw = 2 * VIRTW - 6 * FONTH, hitems = headeritems(), footwidth, footheight, maxfootheight = 0;
if(hasdesc) loopv(items) if(items[i]->getdesc())
{
text_bounds(items[i]->getdesc(), footwidth, footheight, footermaxw);
w = max(w, footwidth);
maxfootheight = max(maxfootheight, footheight);
}
if(synctabs) text_startcolumns();
loopv(items) w = max(w, items[i]->width());
int pagesize = MAXMENU - hitems,
offset = menusel - (menusel%pagesize),
mdisp = min(items.length(), pagesize),
cdisp = min(items.length()-offset, pagesize),
pages = (items.length() - 1) / pagesize;
mitem::whitepulse.alpha = (sinf(lastmillis/200.0f)+1.0f)/2.0f;
defformatstring(menupages)("%d/%d", (offset / pagesize) + 1, pages + 1);
int menupageswidth = pages ? text_width(menupages) : 0; // adds to topmost line, either menu title or header
w = max(w, text_width(t) + (header ? 0 : menupageswidth));
if(header) w = max(w, text_width(header) + menupageswidth);
int step = (FONTH*5)/4;
int h = (mdisp+hitems+2)*step;
int y = (2*VIRTH-h)/2;
int x = hotkeys ? (2*VIRTW-w)/6 : (2*VIRTW-w)/2;
x = clamp(x + (VIRTW * xoffs) / 100, 3 * FONTH, 2 * VIRTW - w - 3 * FONTH);
y = clamp(y + (VIRTH * yoffs) / 100, 3 * FONTH, 2 * VIRTH - h - 3 * FONTH);
if(!hotkeys) renderbg(x - FONTH*3/2, y - FONTH, x + w + FONTH*3/2, y + h + FONTH, true);
if(pages)
{
if(offset > 0) drawarrow(1, x + w + FONTH*3/2 - FONTH*5/6, y - FONTH*5/6, FONTH*2/3);
if(offset + pagesize < items.length()) drawarrow(0, x + w + FONTH*3/2 - FONTH*5/6, y + h + FONTH/6, FONTH*2/3);
draw_text(menupages, x + w + FONTH*3/2 - FONTH*5/6 - menupageswidth, y);
}
if(header)
{
draw_text(header, x, y);
y += step*2;
}
draw_text(t, x, y);
y += step*2;
loopj(cdisp)
{
items[offset+j]->render(x, y, w);
y += step;
}
if(synctabs) text_endcolumns();
if(footer || hasdesc)
{
y += ((mdisp-cdisp)+1)*step;
const char *usefoot = hasdesc && items.inrange(menusel) ? items[menusel]->getdesc() : footer;
if(!hasdesc) text_bounds(footer, footwidth, maxfootheight, w);
if(maxfootheight) footlen = min(MAXMENU / 4, (maxfootheight + step / 2) / step);
if(usefoot) draw_text(usefoot, x, y, 0xFF, 0xFF, 0xFF, 0xFF, -1, w);
}
if(previewtexture && *previewtexture) rendermenutexturepreview(previewtexture, w, previewtexturetitle);
if(usefont) popfont(); // setfont("default");
ignoreblinkingbit = false;
}
void gmenu::renderbg(int x1, int y1, int x2, int y2, bool border)
{
static Texture *tex = NULL;
if(!tex) tex = textureload("packages/misc/menu.jpg");
static color transparent(1, 1, 1, 0.75f);
blendbox(x1, y1, x2, y2, border, tex->id, allowinput ? NULL : &transparent);
}
// apply changes menu
void *applymenu = NULL;
static vector<const char *> needsapply;
VARP(applydialog, 0, 1, 1);
void addchange(const char *desc, int type)
{
if(!applydialog) return;
if(type!=CHANGE_GFX)
{
conoutf("..restart AssaultCube for this setting to take effect");
return;
}
bool changed = false;
loopv(needsapply) if(!strcmp(needsapply[i], desc)) { changed = true; break; }
if(!changed) needsapply.add(desc);
showmenu("apply", false);
}
void clearchanges(int type)
{
if(type!=CHANGE_GFX) return;
needsapply.shrink(0);
closemenu("apply");
}
void refreshapplymenu(void *menu, bool init)
{
gmenu *m = (gmenu *) menu;
if(!m || (!init && needsapply.length() != m->items.length()-3)) return;
m->items.deletecontents();
loopv(needsapply) m->items.add(new mitemtext(m, newstring(needsapply[i]), NULL, NULL, NULL));
m->items.add(new mitemtext(m, newstring(""), NULL, NULL, NULL));
m->items.add(new mitemtext(m, newstring("Yes"), newstring("resetgl"), NULL, NULL));
m->items.add(new mitemtext(m, newstring("No"), newstring("echo [..restart AssaultCube to apply the new settings]"), NULL, NULL));
if(init) m->menusel = m->items.length()-2; // select OK
}
| 0 | 0.949561 | 1 | 0.949561 | game-dev | MEDIA | 0.571338 | game-dev | 0.940073 | 1 | 0.940073 |
petrroll/PowerSwitcher | 4,983 | PowerSwitcher/PowerManager.cs | using Petrroll.Helpers;
using PowerSwitcher.Wrappers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
namespace PowerSwitcher
{
public interface IPowerManager : INotifyPropertyChanged, IDisposable
{
ObservableCollection<IPowerSchema> Schemas { get; }
IPowerSchema CurrentSchema { get; }
PowerPlugStatus CurrentPowerStatus { get; }
void UpdateSchemas();
void SetPowerSchema(IPowerSchema schema);
void SetPowerSchema(Guid guid);
}
public class PowerManager : ObservableObject, IPowerManager
{
Win32PowSchemasWrapper powerWraper;
BatteryInfoWrapper batteryWrapper;
public ObservableCollection<IPowerSchema> Schemas{ get; private set; }
public IPowerSchema CurrentSchema { get; private set; }
public PowerPlugStatus CurrentPowerStatus { get; private set; }
public PowerManager()
{
powerWraper = new Win32PowSchemasWrapper();
batteryWrapper = new BatteryInfoWrapper(powerChangedEvent);
Schemas = new ObservableCollection<IPowerSchema>();
powerChangedEvent(batteryWrapper.GetCurrentChargingStatus());
UpdateSchemas();
}
public void UpdateSchemas()
{
var currSchemaGuid = powerWraper.GetActiveGuid();
var newSchemas = powerWraper.GetCurrentSchemas();
//Add and update new / changed schemas
foreach (var newSchema in newSchemas)
{
var originalSchema = Schemas.FirstOrDefault(sch => sch.Guid == newSchema.Guid);
if (originalSchema == null) { insertNewSchema(newSchemas, newSchema); originalSchema = newSchema; }
if (newSchema.Guid == currSchemaGuid && originalSchema?.IsActive != true)
{ setNewCurrSchema(originalSchema); }
if (originalSchema?.Name != newSchema.Name)
{ ((PowerSchema)originalSchema).Name = newSchema.Name; }
}
if(!Schemas.Any(sch => currSchemaGuid == sch.Guid))
{
noSchemaIsActive();
}
//remove old schemas
var schemasToBeRemoved = new List<IPowerSchema>();
foreach (var oldSchema in Schemas)
{
if (newSchemas.FirstOrDefault(sch => sch.Guid == oldSchema.Guid) == null)
{ schemasToBeRemoved.Add(oldSchema); }
}
schemasToBeRemoved.ForEach(sch => Schemas.Remove(sch));
}
private void noSchemaIsActive()
{
var oldActive = Schemas.FirstOrDefault(sch => sch.IsActive);
if (oldActive != null)
{
((PowerSchema)oldActive).IsActive = false;
CurrentSchema = null;
RaisePropertyChangedEvent(nameof(CurrentSchema));
}
}
private void insertNewSchema(List<PowerSchema> newSchemas, PowerSchema newSchema)
{
var insertToIndex = Math.Min(newSchemas.IndexOf(newSchema), Schemas.Count);
Schemas.Insert(insertToIndex, newSchema);
}
private void setNewCurrSchema(IPowerSchema newActiveSchema)
{
var oldActiveSchema = Schemas.FirstOrDefault(sch => sch.IsActive);
((PowerSchema)newActiveSchema).IsActive = true;
CurrentSchema = newActiveSchema;
RaisePropertyChangedEvent(nameof(CurrentSchema));
//can cause change change of curr power schema: http://stackoverflow.com/questions/42703092/remove-selection-when-selected-item-gets-deleted-from-listbox
if (oldActiveSchema != null) { ((PowerSchema)oldActiveSchema).IsActive = false; }
}
public void SetPowerSchema(IPowerSchema schema)
{
SetPowerSchema(schema.Guid);
}
public void SetPowerSchema(Guid guid)
{
try { powerWraper.SetActiveGuid(guid); } catch (PowerSwitcherWrappersException) { }
UpdateSchemas();
}
private void powerChangedEvent(PowerPlugStatus newStatus)
{
if(newStatus == CurrentPowerStatus) { return; }
CurrentPowerStatus = newStatus;
RaisePropertyChangedEvent(nameof(CurrentPowerStatus));
}
#region IDisposable Support
private bool disposedValue = false;
protected virtual void Dispose(bool disposing)
{
if (disposedValue) { return; }
if (disposing)
{
batteryWrapper.Dispose();
}
disposedValue = true;
}
public void Dispose()
{
Dispose(true);
//No destructor so isn't required (yet)
// GC.SuppressFinalize(this);
}
#endregion
}
}
| 0 | 0.885792 | 1 | 0.885792 | game-dev | MEDIA | 0.49773 | game-dev | 0.95478 | 1 | 0.95478 |
SimonGaufreteau/ZygorGuidesViewer | 6,575 | Libs/AceGUI-3.0/widgets/AceGUIWidget-Keybinding.lua | --[[-----------------------------------------------------------------------------
Keybinding Widget
Set Keybindings in the Config UI.
-------------------------------------------------------------------------------]]
local Type, Version = 'Keybinding', 21
local AceGUI = LibStub and LibStub('AceGUI-3.0', true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then
return
end
-- Lua APIs
local pairs = pairs
-- WoW APIs
local IsShiftKeyDown, IsControlKeyDown, IsAltKeyDown =
IsShiftKeyDown, IsControlKeyDown, IsAltKeyDown
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: NOT_BOUND
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire('OnEnter')
end
local function Control_OnLeave(frame)
frame.obj:Fire('OnLeave')
end
local function Keybinding_OnClick(frame, button)
if button == 'LeftButton' or button == 'RightButton' then
local self = frame.obj
if self.waitingForKey then
frame:EnableKeyboard(false)
self.msgframe:Hide()
frame:UnlockHighlight()
self.waitingForKey = nil
else
frame:EnableKeyboard(true)
self.msgframe:Show()
frame:LockHighlight()
self.waitingForKey = true
end
end
AceGUI:ClearFocus()
end
local ignoreKeys = {
['BUTTON1'] = true,
['BUTTON2'] = true,
['UNKNOWN'] = true,
['LSHIFT'] = true,
['LCTRL'] = true,
['LALT'] = true,
['RSHIFT'] = true,
['RCTRL'] = true,
['RALT'] = true,
}
local function Keybinding_OnKeyDown(frame, key)
local self = frame.obj
if self.waitingForKey then
local keyPressed = key
if keyPressed == 'ESCAPE' then
keyPressed = ''
else
if ignoreKeys[keyPressed] then
return
end
if IsShiftKeyDown() then
keyPressed = 'SHIFT-' .. keyPressed
end
if IsControlKeyDown() then
keyPressed = 'CTRL-' .. keyPressed
end
if IsAltKeyDown() then
keyPressed = 'ALT-' .. keyPressed
end
end
frame:EnableKeyboard(false)
self.msgframe:Hide()
frame:UnlockHighlight()
self.waitingForKey = nil
if not self.disabled then
self:SetKey(keyPressed)
self:Fire('OnKeyChanged', keyPressed)
end
end
end
local function Keybinding_OnMouseDown(frame, button)
if button == 'LeftButton' or button == 'RightButton' then
return
elseif button == 'MiddleButton' then
button = 'BUTTON3'
elseif button == 'Button4' then
button = 'BUTTON4'
elseif button == 'Button5' then
button = 'BUTTON5'
end
Keybinding_OnKeyDown(frame, button)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
['OnAcquire'] = function(self)
self:SetWidth(200)
self:SetLabel('')
self:SetKey('')
self.waitingForKey = nil
self.msgframe:Hide()
self:SetDisabled(false)
end,
-- ["OnRelease"] = nil,
['SetDisabled'] = function(self, disabled)
self.disabled = disabled
if disabled then
self.button:Disable()
self.label:SetTextColor(0.5, 0.5, 0.5)
else
self.button:Enable()
self.label:SetTextColor(1, 1, 1)
end
end,
['SetKey'] = function(self, key)
if (key or '') == '' then
self.button:SetText(NOT_BOUND)
self.button:SetNormalFontObject('GameFontNormal')
else
self.button:SetText(key)
self.button:SetNormalFontObject('GameFontHighlight')
end
end,
['GetKey'] = function(self)
local key = self.button:GetText()
if key == NOT_BOUND then
key = nil
end
return key
end,
['SetLabel'] = function(self, label)
self.label:SetText(label or '')
if (label or '') == '' then
self.alignoffset = nil
self:SetHeight(24)
else
self.alignoffset = 30
self:SetHeight(44)
end
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local ControlBackdrop = {
bgFile = 'Interface\\Tooltips\\UI-Tooltip-Background',
edgeFile = 'Interface\\Tooltips\\UI-Tooltip-Border',
tile = true,
tileSize = 16,
edgeSize = 16,
insets = { left = 3, right = 3, top = 3, bottom = 3 },
}
local function keybindingMsgFixWidth(frame)
frame:SetWidth(frame.msg:GetWidth() + 10)
frame:SetScript('OnUpdate', nil)
end
local function Constructor()
local name = 'AceGUI30KeybindingButton' .. AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame('Frame', nil, UIParent)
local button = CreateFrame('Button', name, frame, 'UIPanelButtonTemplate2')
button:EnableMouse(true)
button:RegisterForClicks('AnyDown')
button:SetScript('OnEnter', Control_OnEnter)
button:SetScript('OnLeave', Control_OnLeave)
button:SetScript('OnClick', Keybinding_OnClick)
button:SetScript('OnKeyDown', Keybinding_OnKeyDown)
button:SetScript('OnMouseDown', Keybinding_OnMouseDown)
button:SetPoint('BOTTOMLEFT')
button:SetPoint('BOTTOMRIGHT')
button:SetHeight(24)
local text = button:GetFontString()
text:SetPoint('LEFT', 7, 0)
text:SetPoint('RIGHT', -7, 0)
local label = frame:CreateFontString(nil, 'OVERLAY', 'GameFontHighlight')
label:SetPoint('TOPLEFT')
label:SetPoint('TOPRIGHT')
label:SetJustifyH('CENTER')
label:SetHeight(18)
local msgframe = CreateFrame('Frame', nil, UIParent)
msgframe:SetHeight(30)
msgframe:SetBackdrop(ControlBackdrop)
msgframe:SetBackdropColor(0, 0, 0)
msgframe:SetFrameStrata('FULLSCREEN_DIALOG')
msgframe:SetFrameLevel(1000)
local msg = msgframe:CreateFontString(nil, 'OVERLAY', 'GameFontNormal')
msg:SetText('Press a key to bind, ESC to clear the binding or click the button again to cancel.')
msgframe.msg = msg
msg:SetPoint('TOPLEFT', 5, -5)
msgframe:SetScript('OnUpdate', keybindingMsgFixWidth)
msgframe:SetPoint('BOTTOM', button, 'TOP')
msgframe:Hide()
local widget = {
button = button,
label = label,
msgframe = msgframe,
frame = frame,
alignoffset = 30,
type = Type,
}
for method, func in pairs(methods) do
widget[method] = func
end
button.obj = widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| 0 | 0.824611 | 1 | 0.824611 | game-dev | MEDIA | 0.741178 | game-dev | 0.879648 | 1 | 0.879648 |
595554963github/AssetStudio-Neptune | 8,008 | Assetstudio/Classes/Sprite.cs | using System;
using System.Collections.Generic;
using System.IO;
namespace AssetStudio
{
public class SecondarySpriteTexture
{
public PPtr<Texture2D> texture;
public string name;
public SecondarySpriteTexture(ObjectReader reader)
{
texture = new PPtr<Texture2D>(reader);
name = reader.ReadStringToNull();
}
}
public enum SpritePackingRotation
{
None = 0,
FlipHorizontal = 1,
FlipVertical = 2,
Rotate180 = 3,
Rotate90 = 4
};
public enum SpritePackingMode
{
Tight = 0,
Rectangle
};
public enum SpriteMeshType
{
FullRect,
Tight
};
public class SpriteSettings
{
public uint settingsRaw;
public uint packed;
public SpritePackingMode packingMode;
public SpritePackingRotation packingRotation;
public SpriteMeshType meshType;
public SpriteSettings(BinaryReader reader)
{
settingsRaw = reader.ReadUInt32();
packed = settingsRaw & 1; //1
packingMode = (SpritePackingMode)((settingsRaw >> 1) & 1); //1
packingRotation = (SpritePackingRotation)((settingsRaw >> 2) & 0xf); //4
meshType = (SpriteMeshType)((settingsRaw >> 6) & 1); //1
//reserved
}
}
public class SpriteVertex
{
public Vector3 pos;
public Vector2 uv;
public SpriteVertex(ObjectReader reader)
{
var version = reader.version;
pos = reader.ReadVector3();
if (version[0] < 4 || (version[0] == 4 && version[1] <= 3)) //4.3 and down
{
uv = reader.ReadVector2();
}
}
}
public class SpriteRenderData
{
public PPtr<Texture2D> texture;
public PPtr<Texture2D> alphaTexture;
public List<SecondarySpriteTexture> secondaryTextures;
public List<SubMesh> m_SubMeshes;
public byte[] m_IndexBuffer;
public VertexData m_VertexData;
public List<SpriteVertex> vertices;
public ushort[] indices;
public Matrix4x4[] m_Bindpose;
public List<BoneWeights4> m_SourceSkin;
public Rectf textureRect;
public Vector2 textureRectOffset;
public Vector2 atlasRectOffset;
public SpriteSettings settingsRaw;
public Vector4 uvTransform;
public float downscaleMultiplier;
public SpriteRenderData(ObjectReader reader)
{
var version = reader.version;
texture = new PPtr<Texture2D>(reader);
if (version[0] > 5 || (version[0] == 5 && version[1] >= 2)) //5.2 and up
{
alphaTexture = new PPtr<Texture2D>(reader);
}
if (version[0] >= 2019) //2019 and up
{
var secondaryTexturesSize = reader.ReadInt32();
secondaryTextures = new List<SecondarySpriteTexture>();
for (int i = 0; i < secondaryTexturesSize; i++)
{
secondaryTextures.Add(new SecondarySpriteTexture(reader));
}
}
if (version[0] > 5 || (version[0] == 5 && version[1] >= 6)) //5.6 and up
{
var m_SubMeshesSize = reader.ReadInt32();
m_SubMeshes = new List<SubMesh>();
for (int i = 0; i < m_SubMeshesSize; i++)
{
m_SubMeshes.Add(new SubMesh(reader));
}
m_IndexBuffer = reader.ReadUInt8Array();
reader.AlignStream();
m_VertexData = new VertexData(reader);
}
else
{
var verticesSize = reader.ReadInt32();
vertices = new List<SpriteVertex>();
for (int i = 0; i < verticesSize; i++)
{
vertices.Add(new SpriteVertex(reader));
}
indices = reader.ReadUInt16Array();
reader.AlignStream();
}
if (version[0] >= 2018) //2018 and up
{
m_Bindpose = reader.ReadMatrixArray();
if (version[0] == 2018 && version[1] < 2) //2018.2 down
{
var m_SourceSkinSize = reader.ReadInt32();
for (int i = 0; i < m_SourceSkinSize; i++)
{
m_SourceSkin[i] = new BoneWeights4(reader);
}
}
}
textureRect = new Rectf(reader);
textureRectOffset = reader.ReadVector2();
if (version[0] > 5 || (version[0] == 5 && version[1] >= 6)) //5.6 and up
{
atlasRectOffset = reader.ReadVector2();
}
settingsRaw = new SpriteSettings(reader);
if (version[0] > 4 || (version[0] == 4 && version[1] >= 5)) //4.5 and up
{
uvTransform = reader.ReadVector4();
}
if (version[0] >= 2017) //2017 and up
{
downscaleMultiplier = reader.ReadSingle();
}
}
}
public class Rectf
{
public float x;
public float y;
public float width;
public float height;
public Rectf(BinaryReader reader)
{
x = reader.ReadSingle();
y = reader.ReadSingle();
width = reader.ReadSingle();
height = reader.ReadSingle();
}
}
public sealed class Sprite : NamedObject
{
public Rectf m_Rect;
public Vector2 m_Offset;
public Vector4 m_Border;
public float m_PixelsToUnits;
public Vector2 m_Pivot = new Vector2(0.5f, 0.5f);
public uint m_Extrude;
public bool m_IsPolygon;
public KeyValuePair<Guid, long> m_RenderDataKey;
public string[] m_AtlasTags;
public PPtr<SpriteAtlas> m_SpriteAtlas;
public SpriteRenderData m_RD;
public List<Vector2[]> m_PhysicsShape;
public Sprite(ObjectReader reader) : base(reader)
{
m_Rect = new Rectf(reader);
m_Offset = reader.ReadVector2();
if (version[0] > 4 || (version[0] == 4 && version[1] >= 5)) //4.5 and up
{
m_Border = reader.ReadVector4();
}
m_PixelsToUnits = reader.ReadSingle();
if (version[0] > 5
|| (version[0] == 5 && version[1] > 4)
|| (version[0] == 5 && version[1] == 4 && version[2] >= 2)
|| (version[0] == 5 && version[1] == 4 && version[2] == 1 && buildType.IsPatch && version[3] >= 3)) //5.4.1p3 and up
{
m_Pivot = reader.ReadVector2();
}
m_Extrude = reader.ReadUInt32();
if (version[0] > 5 || (version[0] == 5 && version[1] >= 3)) //5.3 and up
{
m_IsPolygon = reader.ReadBoolean();
reader.AlignStream();
}
if (version[0] >= 2017) //2017 and up
{
var first = new Guid(reader.ReadBytes(16));
var second = reader.ReadInt64();
m_RenderDataKey = new KeyValuePair<Guid, long>(first, second);
m_AtlasTags = reader.ReadStringArray();
m_SpriteAtlas = new PPtr<SpriteAtlas>(reader);
}
m_RD = new SpriteRenderData(reader);
if (version[0] >= 2017) //2017 and up
{
var m_PhysicsShapeSize = reader.ReadInt32();
m_PhysicsShape = new List<Vector2[]>();
for (int i = 0; i < m_PhysicsShapeSize; i++)
{
m_PhysicsShape.Add(reader.ReadVector2Array());
}
}
//vector m_Bones 2018 and up
}
}
}
| 0 | 0.897721 | 1 | 0.897721 | game-dev | MEDIA | 0.759121 | game-dev,graphics-rendering | 0.937834 | 1 | 0.937834 |
Monkestation/Monkestation2.0 | 10,476 | monkestation/code/modules/virology/disease/base_disease_folder/_base.dm | GLOBAL_LIST_INIT(infected_contact_mobs, list())
GLOBAL_LIST_INIT(virusDB, list())
/datum/disease
//the disease's antigens, that the body's immune_system will read to produce corresponding antibodies. Without antigens, a disease cannot be cured.
var/list/antigen = list()
//alters a pathogen's propensity to mutate. Set to FALSE to forbid a pathogen from ever mutating.
var/mutation_modifier = TRUE
//the antibody concentration at which the disease will fully exit the body
var/strength = 100
//the percentage of the strength at which effects will start getting disabled by antibodies.
var/robustness = 100
//chance to cure the disease at every proc when the body is getting cooked alive.
var/max_bodytemperature = T0C+100
//very low temperatures will stop the disease from activating/progressing
var/min_bodytemperature = 120
///split category used for predefined diseases atm
var/category = DISEASE_NORMAL
//logging
var/log = ""
var/origin = "Unknown"
var/logged_virusfood = FALSE
var/fever_warning = FALSE
//cosmetic
var/color
var/pattern = 1
var/pattern_color
///pathogenic warfare - If you have a second disease of a form name in the list they will start fighting.
var/list/can_kill = list("Bacteria")
//When an opportunity for the disease to spread_flags to a mob arrives, runs this percentage through prob()
//Ignored if infected materials are ingested (injected with infected blood, eating infected meat)
var/infectionchance = 20
var/infectionchance_base = 20
//ticks increases by [speed] every time the disease activates. Drinking Virus Food also accelerates the process by 10.
var/ticks = 0
var/speed = 1
var/stageprob = 25
//when spreading to another mob, that new carrier has the disease's stage reduced by stage_variance
var/stage_variance = -1
var/uniqueID = 0// 0000 to 9999, set when the pathogen gets initially created
var/subID = 0// 000 to 9999, set if the pathogen underwent effect or antigen mutation
var/childID = 0// 01 to 99, incremented as the pathogen gets analyzed after a mutation
//bitflag showing which transmission types are allowed for this disease
var/allowed_transmission = DISEASE_SPREAD_BLOOD | DISEASE_SPREAD_CONTACT_SKIN | DISEASE_SPREAD_CONTACT_FLUIDS | DISEASE_SPREAD_AIRBORNE
/datum/disease/proc/roll_antigen(list/factors = list())
if (factors.len <= 0)
antigen = list(pick(GLOB.all_antigens))
antigen |= pick(GLOB.all_antigens)
else
var/selected_first_antigen = pick(
factors[ANTIGEN_BLOOD];ANTIGEN_BLOOD,
factors[ANTIGEN_COMMON];ANTIGEN_COMMON,
factors[ANTIGEN_RARE];ANTIGEN_RARE,
factors[ANTIGEN_ALIEN];ANTIGEN_ALIEN,
)
antigen = list(pick(antigen_family(selected_first_antigen)))
var/selected_second_antigen = pick(
factors[ANTIGEN_BLOOD];ANTIGEN_BLOOD,
factors[ANTIGEN_COMMON];ANTIGEN_COMMON,
factors[ANTIGEN_RARE];ANTIGEN_RARE,
factors[ANTIGEN_ALIEN];ANTIGEN_ALIEN,
)
antigen |= pick(antigen_family(selected_second_antigen))
/datum/disease/proc/get_effect(index)
if(!index)
return pick(symptoms)
return symptoms[clamp(index,0,symptoms.len)]
/datum/disease/proc/GetImmuneData(mob/living/mob)
var/lowest_stage = stage
var/highest_concentration = 0
if (mob.immune_system)
var/immune_system = mob.immune_system.GetImmunity()
var/list/antibodies = immune_system[2]
var/subdivision = (strength - ((robustness * strength) / 100)) / max_stages
//for each antigen, we measure the corresponding antibody concentration in the carrier's immune system
//the less robust the pathogen, the more likely that further stages' effects won't activate at a given concentration
for (var/A in antigen)
var/concentration = antibodies[A]
highest_concentration = max(highest_concentration,concentration)
var/i = lowest_stage
while (i > 0)
if (concentration > (strength - i * subdivision))
lowest_stage = i-1
i--
return list(lowest_stage,highest_concentration)
/datum/disease/acute/cure(add_resistance = TRUE, mob/living/carbon/target)
target = target || affected_mob || usr
if(!istype(affected_mob) || QDELING(affected_mob))
return
for(var/datum/symptom/symptom in symptoms)
symptom.disable_effect(target, src)
target.diseases -= src
logger.Log(LOG_CATEGORY_VIRUS, "[affected_mob.name] was cured of virus [real_name()] at [loc_name(affected_mob.loc)]", list("disease_data" = admin_details(), "location" = loc_name(affected_mob.loc)))
//--Plague Stuff--
/*
var/datum/faction/plague_mice/plague = find_active_faction_by_type(/datum/faction/plague_mice)
if (plague && ("[uniqueID]-[subID]" == plague.diseaseID))
plague.update_hud_icons()
*/
//----------------
var/list/pathogen_info = filter_disease_by_spread(affected_mob.diseases, required = DISEASE_SPREAD_CONTACT_SKIN)
if(!length(pathogen_info))
GLOB.infected_contact_mobs -= affected_mob
if(affected_mob.pathogen)
for(var/mob/living/goggle_wearer in GLOB.virus_viewers)
goggle_wearer.client?.images -= affected_mob.pathogen
// Add resistance by boosting whichever antigen is needed
if(add_resistance && target.immune_system)
var/boosted_antigen
var/boosted_antigen_level
for(var/antigen in src.antigen)
var/level = target.immune_system.antibodies[antigen]
if(level >= strength)
return
else if(!boosted_antigen || (boosted_antigen_level > level))
boosted_antigen = antigen
boosted_antigen_level = level
if(boosted_antigen)
target.immune_system.antibodies[boosted_antigen] = max(strength + 10, boosted_antigen_level)
/datum/disease/proc/activate(mob/living/mob, starved = FALSE, seconds_per_tick)
if(!affected_mob)
return_parent()
if((mob.stat == DEAD) && !process_dead)
return
//Searing body temperatures cure diseases, on top of killing you.
if(mob.bodytemperature > max_bodytemperature)
cure(target = mob)
return
if(disease_flags & DISEASE_DORMANT)
return
if(!(infectable_biotypes & mob.mob_biotypes))
return
if(mob.immune_system)
if(prob(10 - (robustness * 0.01))) //100 robustness don't auto cure
mob.immune_system.NaturalImmune()
if(!mob.immune_system.CanInfect(src))
cure(target = mob)
return
//Freezing body temperatures halt diseases completely
if(mob.bodytemperature < min_bodytemperature)
return
//Virus food speeds up disease progress
if(!ismouse(mob))
if(mob.reagents?.has_reagent(/datum/reagent/consumable/virus_food))
mob.reagents.remove_reagent(/datum/reagent/consumable/virus_food, 0.1)
if(!logged_virusfood)
log += "<br />[ROUND_TIME()] Virus Fed ([mob.reagents.get_reagent_amount(/datum/reagent/consumable/virus_food)]U)"
logged_virusfood=1
ticks += 10
else
logged_virusfood=0
if(prob(strength * 0.1))
incubate(mob, 1)
//Moving to the next stage
if(ticks > stage*100 && prob(stageprob))
incubate(mob, 1)
if(stage < max_stages)
log += "<br />[ROUND_TIME()] NEXT STAGE ([stage])"
stage++
ticks = 0
//Pathogen killing each others
for (var/datum/disease/acute/enemy_pathogen as anything in mob.diseases)
if(enemy_pathogen == src)
continue
if ((enemy_pathogen.form in can_kill) && strength > enemy_pathogen.strength)
log += "<br />[ROUND_TIME()] destroyed enemy [enemy_pathogen.form] #[enemy_pathogen.uniqueID]-[enemy_pathogen.subID] ([strength] > [enemy_pathogen.strength])"
enemy_pathogen.cure(target = mob)
// This makes it so that <mob> only ever gets affected by the equivalent of one virus so antags don't just stack a bunch
if(starved)
return
var/list/immune_data = GetImmuneData(mob)
if(!istype(mob, /mob/living/basic/mouse/plague)) //plague mice don't trigger effects to not kill em
for(var/datum/symptom/e in symptoms)
if (e.can_run_effect(immune_data[1], seconds_per_tick))
e.run_effect(mob, src)
//fever is a reaction of the body's immune system to the infection. The higher the antibody concentration (and the disease still not cured), the higher the fever
if (mob.bodytemperature < mob.bodytemp_heat_damage_limit - 15)//but we won't go all the way to burning up just because of a fever, probably
var/fever = round((robustness / 100) * (immune_data[2] / 10) * (stage / max_stages))
switch (mob.mob_size)
if (MOB_SIZE_TINY)
mob.bodytemperature += fever*0.2
if (MOB_SIZE_SMALL)
mob.bodytemperature += fever*0.5
if (MOB_SIZE_HUMAN)
mob.bodytemperature += fever
if (MOB_SIZE_LARGE)
mob.bodytemperature += fever*1.5
if (MOB_SIZE_HUGE)
mob.bodytemperature += fever*2
if (fever > 0 && prob(3))
switch (fever_warning)
if (0)
to_chat(mob, span_warning("You feel a fever coming on, your body warms up and your head hurts a bit."))
fever_warning++
if (1)
if (mob.bodytemperature > 320)
to_chat(mob, span_warning("Your palms are sweaty."))
fever_warning++
if (2)
if (mob.bodytemperature > 335)
to_chat(mob, span_warning("Your knees are weak."))
fever_warning++
if (3)
if (mob.bodytemperature > 350)
to_chat(mob, span_warning("Your arms are heavy."))
fever_warning++
ticks += speed
//horrible, awful, stolen code from disease/advance. But it WORKS
/datum/disease/acute
var/list/properties = list()
/// Calls on GenerateProperties and AssignProperties to set a disease severity. From `disease/advance`
/datum/disease/acute/proc/Refresh_Acute(new_name = FALSE)
GenerateProperties_Acute()
assign_properties_Acute()
/// Generates the list for the severity with severity defined at 0, then calls on symtomps severity for final.
/datum/disease/acute/proc/GenerateProperties_Acute()
properties = list("severity" = 0)
for(var/datum/symptom/S in symptoms)
if(!S.neutered)
properties["severity"] = max(properties["severity"], S.severity) // severity is based on the highest severity non-neutered symptom
/datum/disease/acute/proc/assign_properties_Acute()
if(length(properties))
set_severity_Acute(properties["severity"])
else
CRASH("Our properties were empty or null!")
///sets a serverity level based on the properties["severity"] value of the disease
/datum/disease/acute/proc/set_severity_Acute(level_sev)
switch(level_sev)
if(-INFINITY to 0)
severity = DISEASE_SEVERITY_POSITIVE
if(1)
severity = DISEASE_SEVERITY_NONTHREAT
if(2)
severity = DISEASE_SEVERITY_MINOR
if(3)
severity = DISEASE_SEVERITY_MEDIUM
if(4)
severity = DISEASE_SEVERITY_HARMFUL
if(5)
severity = DISEASE_SEVERITY_DANGEROUS
if(6 to INFINITY)
severity = DISEASE_SEVERITY_BIOHAZARD
else
severity = "Unknown"
| 0 | 0.752008 | 1 | 0.752008 | game-dev | MEDIA | 0.954074 | game-dev | 0.733557 | 1 | 0.733557 |
magefree/mage | 2,166 | Mage.Sets/src/mage/cards/c/ConsignToDream.java |
package mage.cards.c;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.TargetPermanent;
/**
*
* @author jeffwadsworth
*
*/
public final class ConsignToDream extends CardImpl {
public ConsignToDream(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{U}");
// Return target permanent to its owner's hand. If that permanent is red or green, put it on top of its owner's library instead.
this.getSpellAbility().addEffect(new ConsignToDreamEffect());
this.getSpellAbility().addTarget(new TargetPermanent());
}
private ConsignToDream(final ConsignToDream card) {
super(card);
}
@Override
public ConsignToDream copy() {
return new ConsignToDream(this);
}
}
class ConsignToDreamEffect extends OneShotEffect {
ConsignToDreamEffect() {
super(Outcome.ReturnToHand);
this.staticText = "Return target permanent to its owner's hand. If that permanent is red or green, put it on top of its owner's library instead";
}
private ConsignToDreamEffect(final ConsignToDreamEffect effect) {
super(effect);
}
@Override
public ConsignToDreamEffect copy() {
return new ConsignToDreamEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent target = game.getPermanent(source.getFirstTarget());
Player controller = game.getPlayer(source.getControllerId());
if (target != null && controller != null) {
if (target.getColor(game).isRed() || target.getColor(game).isGreen()) {
return controller.putCardsOnTopOfLibrary(target, game, source, true);
} else {
return controller.moveCards(target, Zone.HAND, source, game);
}
}
return false;
}
}
| 0 | 0.988867 | 1 | 0.988867 | game-dev | MEDIA | 0.98459 | game-dev | 0.989569 | 1 | 0.989569 |
TheAnswer/Core3 | 6,357 | MMOCoreORB/src/server/zone/objects/tangible/eventperk/FlagGameImplementation.cpp | #include "server/zone/objects/tangible/eventperk/FlagGame.h"
#include "server/zone/Zone.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "templates/params/creature/ObjectFlag.h"
#include "server/zone/objects/tangible/TangibleObject.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/tangible/components/FlagGameDataComponent.h"
#include "server/zone/objects/tangible/tasks/FlagGamePulseTask.h"
void FlagGameImplementation::initializeTransientMembers() {
TangibleObjectImplementation::initializeTransientMembers();
}
void FlagGameImplementation::notifyInsertToZone(Zone* zone) {
if (rebScore > impScore)
changeFlag(Factions::FACTIONREBEL);
else if (impScore > rebScore)
changeFlag(Factions::FACTIONIMPERIAL);
else
changeFlag(0);
}
uint32 FlagGameImplementation::getFlagTemplate(uint32 faction) {
switch (faction) {
case Factions::FACTIONREBEL:
return 0x1C517D16; // STRING_HASHCODE("object/tangible/furniture/all/event_flag_game_reb_banner.iff")
case Factions::FACTIONIMPERIAL:
return 0xA5EBEFBE; // STRING_HASHCODE("object/tangible/furniture/all/event_flag_game_imp_banner.iff")
case 0:
default:
return 0x21C1197C; // STRING_HASHCODE("object/tangible/furniture/all/event_flag_game_neut_banner.iff")
}
}
void FlagGameImplementation::changeFlag(uint32 faction) {
removeCurFlag();
ManagedReference<ZoneServer*> zoneServer = getZoneServer();
if (zoneServer == nullptr)
return;
ManagedReference<TangibleObject*> flag = zoneServer->createObject(getFlagTemplate(faction), "playerstructures", 1).castTo<TangibleObject*>();
if (flag == nullptr)
return;
Locker locker(flag);
FlagGameDataComponent* data = cast<FlagGameDataComponent*>(flag->getDataObjectComponent()->get());
if (data == nullptr) {
error("No dataObjectComponent.");
flag->destroyObjectFromDatabase(true);
return;
}
data->setFlagGame(_this.getReferenceUnsafeStaticCast());
flag->initializePosition(getPositionX(), getPositionZ(), getPositionY());
flag->setDirection(Math::deg2rad(getDirectionAngle()));
zone->transferObject(flag, -1, true);
curFlag = flag;
factionControl = faction;
lastFlagChange.updateToCurrentTime();
}
void FlagGameImplementation::removeCurFlag() {
ManagedReference<TangibleObject*> flag = curFlag.get();
if (flag != nullptr) {
Locker locker(flag);
flag->destroyObjectFromWorld(true);
flag->destroyObjectFromDatabase();
}
}
void FlagGameImplementation::tryFlagChange(CreatureObject* player) {
Time currentTime;
int timeDiff = currentTime.getMiliTime() - lastFlagChange.getMiliTime();
if (timeDiff < 15000) {
player->sendSystemMessage("@event_perk:flag_game_cannot_switch_yet");
return;
}
if (player->getFaction() == 0 || player->getFaction() == factionControl || gameStatus == 0 || gameStatus == 2) {
return;
}
if (player->getFaction() == Factions::FACTIONREBEL) {
announceToPlayers("flag_game_rebel_capture");
} else if (player->getFaction() == Factions::FACTIONIMPERIAL) {
announceToPlayers("flag_game_imperial_capture");
} else {
return;
}
changeFlag(player->getFaction());
}
bool FlagGameImplementation::canUseFlag(CreatureObject* player) {
if ((player->getPvpStatusBitmask() & ObjectFlag::OVERT) && player->getFaction() != factionControl)
return true;
return false;
}
void FlagGameImplementation::startGame() {
if (timeLimit == 0)
timeLimit = 10 * 60 * 1000; // 10 minute default
gameStatus = 1;
impScore = 0;
rebScore = 0;
gameStartTime.updateToCurrentTime();
lastFlagChange.updateToCurrentTime();
announceToPlayers("flag_game_game_starting");
activateGamePulse();
}
void FlagGameImplementation::endGame() {
if (rebScore > impScore) {
changeFlag(Factions::FACTIONREBEL);
doVictoryEffects(Factions::FACTIONREBEL);
announceToPlayers("flag_game_over_reb_win");
} else if (impScore > rebScore) {
changeFlag(Factions::FACTIONIMPERIAL);
doVictoryEffects(Factions::FACTIONIMPERIAL);
announceToPlayers("flag_game_over_imp_win");
} else {
changeFlag(0);
announceToPlayers("flag_game_over_tie");
}
gameStatus = 2;
}
void FlagGameImplementation::activateGamePulse() {
if (gamePulse == nullptr) {
gamePulse = new FlagGamePulseTask(_this.getReferenceUnsafeStaticCast());
gamePulse->reschedule(15 * 1000); // 15 second pulse
} else {
gamePulse->reschedule(15 * 1000);
}
}
void FlagGameImplementation::announceToPlayers(const String& message) {
SortedVector<ManagedReference<TreeEntry*> > closeObjects;
zone->getInRangeObjects(getPositionX(), getPositionZ(), getPositionY(), 256, &closeObjects, true);
for (int i = 0; i < closeObjects.size(); i++) {
SceneObject* targetObject = cast<SceneObject*>(closeObjects.get(i).get());
if (targetObject != nullptr && targetObject->isPlayerCreature()) {
ManagedReference<CreatureObject*> player = cast<CreatureObject*>(targetObject);
if (player != nullptr)
player->sendSystemMessage("@event_perk:" + message);
}
}
}
void FlagGameImplementation::showScores(CreatureObject* player) {
if (gameStatus != 2)
return;
StringIdChatParameter msg;
msg.setStringId("@event_perk:flag_game_score_1");
msg.setDI(impScore);
player->sendSystemMessage(msg);
msg.setStringId("@event_perk:flag_game_score_2");
msg.setDI(rebScore);
player->sendSystemMessage(msg);
}
void FlagGameImplementation::doVictoryEffects(uint32 faction) {
SortedVector<ManagedReference<TreeEntry*> > closeObjects;
zone->getInRangeObjects(getPositionX(), 0, getPositionY(), 256, &closeObjects, true);
for (int i = 0; i < closeObjects.size(); i++) {
SceneObject* targetObject = cast<SceneObject*>(closeObjects.get(i).get());
if (targetObject != nullptr && targetObject->isPlayerCreature()) {
ManagedReference<CreatureObject*> player = cast<CreatureObject*>(targetObject);
if (player != nullptr && player->getFaction() == faction && (player->getPvpStatusBitmask() & ObjectFlag::OVERT)) {
if (player->getFaction() == Factions::FACTIONREBEL) {
player->playEffect("clienteffect/holoemote_rebel.cef", "head");
} else if (player->getFaction() == Factions::FACTIONIMPERIAL) {
player->playEffect("clienteffect/holoemote_imperial.cef", "head");
}
}
}
}
}
void FlagGameImplementation::destroyObjectFromWorld(bool sendSelfDestroy) {
removeCurFlag();
TangibleObjectImplementation::destroyObjectFromWorld(sendSelfDestroy);
}
| 0 | 0.82293 | 1 | 0.82293 | game-dev | MEDIA | 0.977726 | game-dev | 0.960576 | 1 | 0.960576 |
lambda-plugins/HighwayTools | 2,144 | src/main/kotlin/trombone/handler/Liquid.kt | package trombone.handler
import HighwayTools.debugLevel
import HighwayTools.fillerMat
import HighwayTools.illegalPlacements
import HighwayTools.maxReach
import HighwayTools.placementSearch
import com.lambda.client.LambdaMod
import com.lambda.client.event.SafeClientEvent
import com.lambda.client.util.math.CoordinateConverter.asString
import com.lambda.client.util.math.VectorUtils.distanceTo
import com.lambda.client.util.world.getNeighbourSequence
import net.minecraft.block.BlockLiquid
import net.minecraft.util.EnumFacing
import trombone.IO
import trombone.blueprint.BlueprintTask
import trombone.task.BlockTask
import trombone.task.TaskManager.addTask
import trombone.task.TaskManager.tasks
import trombone.task.TaskState
object Liquid {
fun SafeClientEvent.handleLiquid(blockTask: BlockTask): Boolean {
var foundLiquid = false
for (side in EnumFacing.values()) {
if (side == EnumFacing.DOWN) continue
val neighbourPos = blockTask.blockPos.offset(side)
if (world.getBlockState(neighbourPos).block !is BlockLiquid) continue
if (player.distanceTo(neighbourPos) > maxReach
|| getNeighbourSequence(neighbourPos, placementSearch, maxReach, !illegalPlacements).isEmpty()
) {
if (debugLevel == IO.DebugLevel.VERBOSE) {
LambdaMod.LOG.info("[Trombone] Skipping liquid block at ${neighbourPos.asString()} due to distance")
}
blockTask.updateState(TaskState.DONE)
return true
}
foundLiquid = true
tasks[neighbourPos]?.let {
updateLiquidTask(it)
} ?: run {
val newTask = BlockTask(neighbourPos, TaskState.LIQUID, fillerMat)
val blueprintTask = BlueprintTask(fillerMat, isFiller = true, isSupport = false)
addTask(newTask, blueprintTask)
}
}
return foundLiquid
}
fun SafeClientEvent.updateLiquidTask(blockTask: BlockTask) {
blockTask.updateState(TaskState.LIQUID)
blockTask.updateTask(this)
}
} | 0 | 0.930318 | 1 | 0.930318 | game-dev | MEDIA | 0.561979 | game-dev | 0.918958 | 1 | 0.918958 |
LLNL/GridDyn | 2,913 | gridDyn/relays/zonalRelay.h | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; eval: (c-set-offset 'innamespace 0); -*- */
/*
* LLNS Copyright Start
* Copyright (c) 2016, Lawrence Livermore National Security
* This work was performed under the auspices of the U.S. Department
* of Energy by Lawrence Livermore National Laboratory in part under
* Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* LLNS Copyright End
*/
#ifndef ZONAL_RELAY_H_
#define ZONAL_RELAY_H_
#include "gridRelay.h"
/** class building off of gridRelay to define a zonal relays
the number of zones is arbritrary and it works by checking the impedences of the associated link and comparing to specific thresholds.
This zonal relays runs off a single impededence number
*/
class zonalRelay : public gridRelay
{
public:
enum zonalrelay_flags
{
nondirectional_flag = object_flag10,
};
protected:
count_t m_zones = 2; //!< the number of zones for the relay
index_t m_terminal = 1; //!< the side of the line to connect 1=from side 2=to side, 3+ for multiterminal devices
double m_resetMargin = 0.01; //!<! the reset margin for clearing a fault
std::vector<double> m_zoneLevels; //!< the level of impedence to trigger
std::vector<double> m_zoneDelays; //!< the delay upon which to act for the relay
count_t m_condition_level = kInvalidCount; //!< the level of condition that has been triggered
int autoName = -1; //!< storage for indicator of the type of autoname to use
public:
zonalRelay (const std::string &objName = "zonalRelay_$");
virtual gridCoreObject * clone (gridCoreObject *obj = nullptr) const override;
virtual int setFlag (const std::string &flag, bool val = true) override;
virtual int set (const std::string ¶m, const std::string &val) override;
virtual int set (const std::string ¶m, double val, gridUnits::units_t unitType = gridUnits::defUnit) override;
virtual double get (const std::string ¶m, gridUnits::units_t unitType = gridUnits::defUnit) const override;
virtual void dynObjectInitializeA (double time0, unsigned long flags) override;
protected:
virtual void actionTaken (index_t ActionNum, index_t conditionNum, change_code actionReturn, double actionTime) override;
virtual void conditionTriggered (index_t conditionNum, double triggerTime) override;
virtual void conditionCleared (index_t conditionNum, double triggerTime) override;
virtual void receiveMessage (std::uint64_t sourceID, std::shared_ptr<commMessage> message) override;
/** function to automatically generate the comm system names
@param[in] code a code value representing the method of generating the name
@return the generated name
*/
std::string generateAutoName (int code);
};
#endif | 0 | 0.899423 | 1 | 0.899423 | game-dev | MEDIA | 0.438362 | game-dev | 0.765297 | 1 | 0.765297 |
bukkbeek/GodotPixelRenderer | 22,887 | PixelRenderer/data/scripts/PixelRenderer.gd | extends Node3D
signal single_export_finished
@onready var export_dir_path: Label = %ExportDirPath
@onready var select_folder_button: Button = %SelectFolderButton
@onready var export_button: Button = %ExportButton
@onready var file_dialog: FileDialog = %FileDialog
@onready var texture_rect: TextureRect = %PixelCanvas
@onready var fps_spin_box: SpinBox = %FpsSpin
@onready var left_renderer: Control = %LeftRenderer
@onready var renderer: PanelContainer = %Renderer
@onready var right_renderer: Control = %RightRenderer
@onready var renderer_container: BoxContainer = %RendererContainer
@onready var models_spawner: Node3D = %ModelsSpawner
@onready var prefix_text: LineEdit = %PrefixText
@onready var sub_viewport: SubViewport = $SubViewport
@onready var bg_color_rect: ColorRect = %BgColorRect
@onready var bg_color_check_box: CheckButton = %BgColorCheckBox
@onready var bg_color_picker: ColorPickerButton = %BgColorPicker
@onready var progress_bar: ProgressBar = %ProgressBar
@onready var console: HBoxContainer = %ConsoleContainer
@onready var viewport_background: ColorRect = %ViewportBackgroundColorRect
@export var start_frame: int = 0
@export var end_frame: int = 30
@export var fps: int = 12
@onready var resolution_x: SpinBox = %ResolutionX
@onready var resolution_y: SpinBox = %ResolutionY
@onready var preview_image_check_box: CheckButton = %PreviewImageCheckBox
@onready var view_mode_dropdown : OptionButton = %ViewModeDropDown
@onready var canvas_size_label: Label = %CanvasSizeLabel
@onready var pixel_material_script: Node = $PixelMaterial
var export_directory: String = ""
var is_exporting: bool = false
var current_export_frame: int = 0
var total_frames: int = 0
# Timer for canvas updates
var canvas_update_timer: Timer
# Cached texture for FPS-controlled display
var cached_texture: ImageTexture
# Base canvas size - always 800x800
var BASE_CANVAS_SIZE: Vector2 = Vector2(800, 800)
# Animation export variables
var animation_player: AnimationPlayer = null
var was_playing_before_export: bool = false
var original_animation_position: float = 0.0
var export_frame_list: Array = []
var export_frame_index: int = 0
var capture_viewport: SubViewport = null
var renderer_clone: Node = null
func _ready():
# Initialize console
console._update("EffectBlocks PixelRenderer")
console._update("Visit https://bukkbeek.itch.io/effectblocks")
console._update("PixelRenderer initialized successfully")
console._update("Canvas update timer set to " + str(fps) + " FPS")
console._update("Base canvas size: " + str(BASE_CANVAS_SIZE) + "x" + str(BASE_CANVAS_SIZE))
console._update("Default minion skeleton by KayKit: kaylousberg.itch.io/kaykit-skeletons")
texture_rect.texture = sub_viewport.get_texture()
sub_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
# Keep SubViewport updating continuously so models run at normal speed
sub_viewport.render_target_update_mode = SubViewport.UPDATE_ALWAYS
# Initialize cached texture
cached_texture = ImageTexture.new()
# Create and configure the canvas update timer for visual feed updates
canvas_update_timer = Timer.new()
canvas_update_timer.wait_time = 1.0 / fps
canvas_update_timer.timeout.connect(_on_canvas_timer_timeout)
add_child(canvas_update_timer)
canvas_update_timer.start()
# Connect signals
export_button.pressed.connect(_on_export_button_pressed)
select_folder_button.pressed.connect(_on_select_folder_button_pressed)
fps_spin_box.value_changed.connect(_on_fps_changed)
resolution_x.value_changed.connect(_on_resolution_changed)
resolution_y.value_changed.connect(_on_resolution_changed)
file_dialog.dir_selected.connect(_on_directory_selected)
bg_color_check_box.toggled.connect(_on_bg_color_toggled)
bg_color_picker.color_changed.connect(_on_bg_color_changed)
# Setup View Modes
_setup_view_mode_dropdown()
view_mode_dropdown.item_selected.connect(_view_mode_item_selected)
# Connect to ViewMaterials signal for automatic color remap toggle
get_node("ViewMaterials").technical_mode_selected.connect(_on_technical_mode_selected)
# Set up file dialog
file_dialog.file_mode = FileDialog.FILE_MODE_OPEN_DIR
file_dialog.access = FileDialog.ACCESS_FILESYSTEM
# Initialize FPS spin box
fps_spin_box.value = fps
fps_spin_box.min_value = 1
fps_spin_box.max_value = 120
fps_spin_box.step = 1
# Initialize resolution spin box
resolution_x.value = 512
resolution_x.min_value = 1
resolution_x.step = 1
resolution_y.value = 512
resolution_y.min_value = 1
resolution_y.step = 1
# Initialize background color controls
_update_bg_color_visibility()
# Initialize export directory label
_update_export_path_label()
# Initialize canvas size label
_update_canvas_size_label()
# Initialize progress bar
progress_bar.min_value = 0
progress_bar.max_value = 100
func _on_fps_changed(value: float):
fps = int(value)
if fps > 0:
canvas_update_timer.wait_time = 1.0 / fps
canvas_update_timer.start()
else:
canvas_update_timer.stop()
console._update("Preview FPS changed to " + str(fps))
func _on_canvas_timer_timeout():
# Вместо копирования данных, мы просто просим вьюпорт
# отрендерить один новый кадр.
# TextureRect, который уже смотрит на него, обновится автоматически.
sub_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
func _on_resolution_changed(value: float):
var res_x = resolution_x.value
var res_y = resolution_y.value
if res_x > res_y:
BASE_CANVAS_SIZE = Vector2(800, 800*(float(res_y) / float(res_x)))
else:
BASE_CANVAS_SIZE = Vector2(800*(float(res_x) / float(res_y)), 800)
print_debug(BASE_CANVAS_SIZE)
print_debug(res_x)
print_debug(res_y)
if BASE_CANVAS_SIZE.x > BASE_CANVAS_SIZE.y:
renderer_container.vertical = true
texture_rect.custom_minimum_size = BASE_CANVAS_SIZE
var offset_y = (800-BASE_CANVAS_SIZE.y)/2
left_renderer.custom_minimum_size = Vector2(800, int(offset_y))
right_renderer.custom_minimum_size = Vector2(800, int(offset_y))
viewport_background.position =Vector2(555, int(offset_y))
else:
renderer_container.vertical = false
texture_rect.custom_minimum_size = BASE_CANVAS_SIZE
var offset_x = (800-BASE_CANVAS_SIZE.x)/2
left_renderer.custom_minimum_size = Vector2(int(offset_x), 800 )
right_renderer.custom_minimum_size = Vector2(int(offset_x), 800)
viewport_background.position =Vector2(555+int(offset_x), 0)
print_debug(texture_rect.custom_minimum_size)
sub_viewport.size = BASE_CANVAS_SIZE
viewport_background.custom_minimum_size = BASE_CANVAS_SIZE
viewport_background.size = BASE_CANVAS_SIZE
_update_canvas_size_label()
console._update("Export resolution changed to " + str(int(res_x)) + "x" + str(int(res_y)))
func start_export() -> void:
_on_export_button_pressed()
func _on_export_button_pressed():
if is_exporting:
return
if export_directory == "":
console._update("No export directory selected, opening folder dialog...")
_on_select_folder_button_pressed()
return
# Start the export process
_start_export()
func _on_select_folder_button_pressed():
# Open file dialog to select export directory
file_dialog.popup_centered(Vector2i(800, 600))
func _on_directory_selected(dir: String):
export_directory = dir
console._update("Export directory set to: " + export_directory)
# Update the label to show the selected path
_update_export_path_label()
func _find_animation_player(node: Node) -> AnimationPlayer:
# Check if current node is an AnimationPlayer
if node is AnimationPlayer:
return node as AnimationPlayer
# Recursively search children
for child in node.get_children():
var result = _find_animation_player(child)
if result != null:
return result
return null
func _start_export():
if export_directory == "":
console._update("No export directory selected")
return
if console.console_container_expanded:
console._on_expand_log_button_pressed()
# Get frame range from models_spawner UI instead of hardcoded values
var actual_start_frame = start_frame
var actual_end_frame = end_frame
if models_spawner:
# Try to get the frame values from models_spawner directly (it has start_spin and end_spin as @onready vars)
if models_spawner.has_method("get") and models_spawner.get("start_spin") != null and models_spawner.get("end_spin") != null:
actual_start_frame = int(models_spawner.start_spin.value)
actual_end_frame = int(models_spawner.end_spin.value)
console._update("Using frame range from UI: " + str(actual_start_frame) + " to " + str(actual_end_frame))
else:
console._update("Could not access frame range UI controls, using default values")
if actual_start_frame >= actual_end_frame:
console._update("Invalid frame range: start_frame must be less than end_frame")
return
# Calculate frame skip based on FPS (baseline 30 FPS)
var frame_skip = int(30.0 / float(fps))
if frame_skip < 1:
frame_skip = 1
console._update("Export FPS: " + str(fps) + " (will render every " + str(frame_skip) + " frame(s) from 30 FPS baseline)")
# Find the animation player in the loaded model
if models_spawner:
var loaded_model = models_spawner.get_loaded_model()
if loaded_model:
animation_player = _find_animation_player(loaded_model)
if animation_player:
console._update("Found AnimationPlayer - animation will play during export")
# Store current state
was_playing_before_export = animation_player.is_playing()
original_animation_position = animation_player.current_animation_position
# Ensure animation is playing
if not animation_player.is_playing():
animation_player.play()
console._update("Started animation playback for export")
animation_player.speed_scale = 0.0
else:
console._update("No AnimationPlayer found - exporting static frames")
else:
console._update("No model loaded - exporting static frames")
is_exporting = true
current_export_frame = actual_start_frame
start_frame = actual_start_frame # Update the instance variables
end_frame = actual_end_frame
# Calculate total frames that will actually be exported (considering frame skipping)
var frames_to_export = []
for frame_num in range(start_frame, end_frame + 1):
if (frame_num - start_frame) % frame_skip == 0:
frames_to_export.append(frame_num)
total_frames = frames_to_export.size()
export_button.text = "Exporting..."
export_button.disabled = true
# Initialize progress bar
progress_bar.value = 0
console._update("Starting export from frame " + str(start_frame) + " to " + str(end_frame))
console._update("Total frames to export: " + str(total_frames) + " at " + str(fps) + " FPS (skipping " + str(frame_skip - 1) + " frames between renders)")
console._update("Frames to render: " + str(frames_to_export))
# Store the frames list and start with the first frame
export_frame_list = frames_to_export
export_frame_index = 0
# Start the export process
_export_next_frame()
func _export_next_frame():
if export_frame_index >= export_frame_list.size():
_finish_export()
return
# Get the actual frame number to render
var frame_to_render = export_frame_list[export_frame_index]
# Update progress bar
var progress_percent = float(export_frame_index) / float(total_frames) * 100.0
progress_bar.value = progress_percent
console._update("Processing frame " + str(frame_to_render) + " (" + str(export_frame_index + 1) + "/" + str(total_frames) + ")")
# If we have an animation player, seek to the correct frame position
if animation_player and animation_player.current_animation != "":
# Animation timing always uses 30 FPS baseline
var target_time = float(frame_to_render) / 30.0
# Make sure we don't exceed animation length
var animation_length = animation_player.current_animation_length
if target_time > animation_length:
target_time = animation_length
# Seek to the exact frame position
animation_player.seek(target_time, true)
console._update("Animation seeked to time: " + str(target_time) + "s (frame " + str(frame_to_render) + " at 30 FPS baseline)")
# Wait for multiple frames to ensure proper rendering and animation update
#var s = renderer_container.size
#print_debug(s)
#await get_tree().process_frame
#await get_tree().process_frame
#await get_tree().process_frame
# Capture the entire Renderer control node and its contents
var image = await _capture_control_node()
if image:
var res_x = resolution_x.value
var res_y = resolution_y.value
# Apply resolution scaling if not in preview mode
if not preview_image_check_box.button_pressed:
var target_size_x = int(res_x)
var target_size_y = int(res_y)
if image.get_width() != target_size_x or image.get_height() != target_size_y:
console._update("Scaling image to " + str(target_size_x) + "x" + str(target_size_y))
image.resize(target_size_x, target_size_y, Image.INTERPOLATE_NEAREST)
#image = _scale_image_nearest_neighbor(image, int(resolution.value))
# Get prefix from UI, default to "frame" if empty
var prefix = prefix_text.text.strip_edges()
if prefix.is_empty():
prefix = "frame"
# Use actual frame numbers for exported files (Blender style)
var filename = "%s_%04d.png" % [prefix, frame_to_render]
var filepath = export_directory.path_join(filename)
console._update("Saving frame to: " + filepath)
# Save the image
var error = image.save_png(filepath)
if error != OK:
console._update("ERROR: Failed to save frame " + str(frame_to_render) + " - Error code: " + str(error))
else:
var size_info = ""
if preview_image_check_box.button_pressed:
size_info = " (preview size: " + str(image.get_width()) + "x" + str(image.get_height()) + ")"
else:
size_info = " (scaled to: " + str(image.get_width()) + "x" + str(image.get_height()) + ")"
console._update("✓ Exported frame " + str(frame_to_render) + " as " + filename + " (" + str(export_frame_index + 1) + "/" + str(total_frames) + ")" + size_info)
else:
console._update("ERROR: Failed to capture frame " + str(frame_to_render))
export_frame_index += 1
# Continue with next frame
_export_next_frame()
func _capture_control_node() -> Image:
if not renderer:
console._update("ERROR: Renderer control node is null")
return null
# Get the size of the control node
var size = renderer.size
if size.x <= 0 or size.y <= 0:
console._update("ERROR: Renderer control node has invalid size: " + str(size))
return null
console._update("Capturing frame at size: " + str(size))
# Create a SubViewport to render the control
capture_viewport = SubViewport.new()
capture_viewport.size = Vector2i(size)
capture_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
# Enable transparency in the SubViewport
capture_viewport.transparent_bg = true
if not is_instance_valid(capture_viewport):
return null
# Temporarily add the SubViewport to the scene
add_child(capture_viewport)
# Clone the renderer node and its children
renderer_clone = renderer.duplicate(DUPLICATE_USE_INSTANTIATION)
capture_viewport.add_child(renderer_clone)
# Force the viewport to render
capture_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
await get_tree().process_frame
await get_tree().process_frame # Wait an extra frame for safety
# Get the rendered image with proper alpha channel
var viewport_texture = capture_viewport.get_texture()
if not viewport_texture:
console._update("ERROR: Could not get texture from SubViewport")
# Clean up before returning
capture_viewport.remove_child(renderer_clone)
renderer_clone.queue_free()
remove_child(capture_viewport)
capture_viewport.queue_free()
capture_viewport = null
renderer_clone = null
return null
var image = viewport_texture.get_image()
# Clean up
capture_viewport.remove_child(renderer_clone)
renderer_clone.queue_free()
remove_child(capture_viewport)
capture_viewport.queue_free()
capture_viewport = null
renderer_clone = null
if not image:
console._update("ERROR: Could not capture image from SubViewport")
return null
# Ensure the image has an alpha channel for transparency
if image.get_format() != Image.FORMAT_RGBA8:
image.convert(Image.FORMAT_RGBA8)
console._update("Image converted to RGBA8 format")
console._update("Frame captured successfully")
# The image should now preserve the alpha channel from the SubViewport
return image
func _scale_image_nearest_neighbor(source_image: Image, target_size: int) -> Image:
"""
Scale an image to target_size x target_size using nearest neighbor filtering
to preserve pixel art aesthetics
"""
if not source_image:
console._update("ERROR: Source image is null for scaling")
return null
var source_width = source_image.get_width()
var source_height = source_image.get_height()
# If already the target size, return as-is
if source_width == target_size and source_height == target_size:
console._update("Image already at target size (" + str(target_size) + "x" + str(target_size) + ")")
return source_image
console._update("Scaling image from " + str(source_width) + "x" + str(source_height) + " to " + str(target_size) + "x" + str(target_size))
# Create a new image with the target size
var scaled_image = Image.create(target_size, target_size, false, Image.FORMAT_RGBA8)
# Calculate scaling factors
var scale_x = float(source_width) / float(target_size)
var scale_y = float(source_height) / float(target_size)
# Apply nearest neighbor scaling
for y in range(target_size):
for x in range(target_size):
# Find the nearest source pixel
var source_x = int(x * scale_x)
var source_y = int(y * scale_y)
# Clamp to source image bounds
source_x = clamp(source_x, 0, source_width - 1)
source_y = clamp(source_y, 0, source_height - 1)
# Get the pixel from source and set it in the scaled image
var pixel_color = source_image.get_pixel(source_x, source_y)
scaled_image.set_pixel(x, y, pixel_color)
console._update("Image scaling completed")
return scaled_image
func _finish_export():
is_exporting = false
export_button.text = "Export"
export_button.disabled = false
# Restore animation player state
if animation_player:
if was_playing_before_export:
# Restore to original position and continue playing
animation_player.seek(original_animation_position)
if not animation_player.is_playing():
animation_player.play()
animation_player.speed_scale = 1.0
console._update("Animation restored to original state")
else:
# Stop animation if it wasn't playing before
animation_player.speed_scale = 1.0
animation_player.stop()
animation_player.seek(original_animation_position)
console._update("Animation stopped and restored to original position")
# Complete the progress bar
progress_bar.value = 100
console._update("------------------------------")
console._update("EXPORT COMPLETED!")
console._update("Total frames exported: " + str(total_frames))
console._update("Export location: " + export_directory)
console._update("Frame rate: " + str(fps) + " FPS")
if animation_player:
console._update("Animation was synchronized during export")
console._update("------------------------------")
# Optional: Show a completion message
_show_completion_message(total_frames)
func _show_completion_message(frame_count: int):
# You can implement a popup or notification here
console._update("Animation export finished: " + str(frame_count) + " frames at " + str(fps) + " FPS")
console._update("You can now create animations or GIFs from the exported frames")
single_export_finished.emit()
# Example: OS.shell_open(export_directory) # Opens the export folder
# Optional: Method to set frame range programmatically
func set_frame_range(start: int, end: int):
start_frame = start
end_frame = end
console._update("Frame range set to: " + str(start) + " - " + str(end) + " (total: " + str(end - start + 1) + " frames)")
func _update_canvas():
# Capture the current frame from the SubViewport
var viewport_texture = sub_viewport.get_texture()
if viewport_texture:
var image = viewport_texture.get_image()
if image:
# Update the cached texture with the current frame
cached_texture.set_image(image)
# Apply the cached texture to the display
texture_rect.texture = cached_texture
else:
console._update("WARNING: Could not get image from SubViewport for canvas update")
else:
console._update("WARNING: Could not get texture from SubViewport for canvas update")
func _update_export_path_label():
if export_directory == "":
export_dir_path.text = "No directory selected"
else:
export_dir_path.text = export_directory
func _update_canvas_size_label():
#var export_resolution_x = float(resolution_x.value)
#var export_resolution_y = float(resolution_y.value)
#var base_size_x = float(BASE_CANVAS_SIZE.x)
#var base_size_y = float(BASE_CANVAS_SIZE.y)
#var scale_factor_x = export_resolution_x / base_size_x
#var scale_factor_y = export_resolution_y / base_size_y
#var scale_factor = Vector2(scale_factor_x, scale_factor_y)
#var scale_text = " | *" + str(scale_factor) + " upscaled"
canvas_size_label.text = "Canvas " + str(BASE_CANVAS_SIZE) + "px | Export Res. " + str(resolution_x.value) + "px :"+ str(resolution_y.value) + "px"
func _on_bg_color_toggled(button_pressed: bool):
_update_bg_color_visibility()
if button_pressed:
console._update("Background color enabled")
else:
console._update("Background color disabled")
func _on_bg_color_changed(color: Color):
bg_color_rect.color = color
console._update("Background color changed to: " + str(color))
func _update_bg_color_visibility():
var should_be_visible = bg_color_check_box.button_pressed
bg_color_rect.visible = should_be_visible
func _view_mode_item_selected(index : int):
get_node("ViewMaterials").item_selected(index)
var selection : String = view_mode_dropdown.get_item_text(index)
console._update("Switching View Mode To " + selection)
func _on_technical_mode_selected(mode_name: String):
# Automatically turn off color remap when technical modes are selected
_turn_off_color_remap_if_enabled()
console._update("Technical mode '" + mode_name + "' selected - color remap automatically disabled")
func _turn_off_color_remap_if_enabled():
# Check if color remap is currently enabled and turn it off
if pixel_material_script and pixel_material_script.use_palette_check_box.button_pressed:
pixel_material_script.use_palette_check_box.button_pressed = false
# Trigger the toggled signal to update the shader parameter
pixel_material_script._on_use_palette_toggled(false)
console._update("Color remap automatically turned off for technical view mode")
func _setup_view_mode_dropdown():
view_mode_dropdown.clear()
view_mode_dropdown.add_item("Albedo")
view_mode_dropdown.add_item("Normal")
view_mode_dropdown.add_item("Specular")
| 0 | 0.689619 | 1 | 0.689619 | game-dev | MEDIA | 0.424326 | game-dev,graphics-rendering | 0.767548 | 1 | 0.767548 |
PotRooms/AzurPromiliaData | 2,104 | Lua/src/ui/store/battle/battleState.lua | local this = {}
function this:init()
this.super.init(self)
self.data = {
battleId = nil,
battleItems = {},
battleServerData = nil,
rewardList = nil,
catchRewardList = nil,
createBattleType = nil,
tagDic = {},
heroCache = nil,
oneKeyChangeType = C_PlayerPrefsUtility.GetInt(L_Const.SaveKey_OneKeyBattleChangeType, L_Const.OneKeyBattleChangeType.loop),
objBattleInfo = {}
}
self:setFightOver()
end
function this:getObjBattleInfo(uuid)
return self.data.objBattleInfo[uuid] or {}
end
function this:getBattleTagByItemId(itemId)
return self.data.tagDic[itemId]
end
function this:getBattleId()
return self.data.battleId
end
function this:getBattleServerData()
return self.data.battleServerData
end
function this:getBattleIsBackstab()
if not self:getBattleServerData() then
return false
end
return self.data.battleServerData.backstab == 1
end
function this:getIsInBattle()
return L_BattleDataManager:checkPlayerBattle()
end
function this:getBattleItems()
return self.data.battleItems
end
function this:getBattleReward()
return self.data.rewardList or {}
end
function this:getCatchReward()
return self.data.catchRewardList or {}
end
function this:getParseBattleReward(sType)
local data = self:getBattleReward()
if sType and sType == L_Const.FightRewardReason.FRR_Catch then
data = self:getCatchReward()
end
local res = {}
for i, v in pairs(data) do
local item = v
if not res[item.itemtype] then
res[item.itemtype] = {}
end
if not math.isEmpty(item.guid) then
res[item.itemtype][item.guid] = v
else
res[item.itemtype][item.itemid] = v
end
end
return res
end
function this:getCreateBattleType()
return self.data.createBattleType
end
function this:getHeroCacheData()
return self.data.heroCache
end
function this:getBattleEntry()
if self.data.battleServerData == nil then
return L_Const.BattleEntryType.BET_INTERIMER
end
return self.data.battleServerData.entry
end
function this:getOneKeyChangeType()
return self.data.oneKeyChangeType
end
return this
| 0 | 0.719027 | 1 | 0.719027 | game-dev | MEDIA | 0.811739 | game-dev | 0.962109 | 1 | 0.962109 |
locationtech/geowave | 4,418 | core/store/src/main/java/org/locationtech/geowave/core/store/data/field/ArrayWriter.java | /**
* Copyright (c) 2013-2022 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.core.store.data.field;
import java.nio.ByteBuffer;
import org.locationtech.geowave.core.index.VarintUtils;
/** This class contains the basic object array writer field types */
public abstract class ArrayWriter<FieldType> implements FieldWriter<FieldType[]> {
public static enum Encoding {
FIXED_SIZE_ENCODING((byte) 0), VARIABLE_SIZE_ENCODING((byte) 1);
private final byte encoding;
Encoding(final byte encoding) {
this.encoding = encoding;
}
public byte getByteEncoding() {
return encoding;
}
}
private final FieldWriter<FieldType> writer;
public ArrayWriter(final FieldWriter<FieldType> writer) {
this.writer = writer;
}
protected byte[] writeFixedSizeField(final FieldType[] fieldValue) {
if (fieldValue == null) {
return new byte[] {};
}
final byte[][] byteData = getBytes(fieldValue);
int bytesPerEntry = 0;
for (final byte[] bytes : byteData) {
if (bytes.length > 0) {
bytesPerEntry = bytes.length;
}
}
final ByteBuffer buf =
ByteBuffer.allocate(
1
+ VarintUtils.unsignedIntByteLength(bytesPerEntry)
+ (int) Math.ceil(fieldValue.length / 8.0)
+ getLength(byteData));
// this is a header value to indicate how data should be read/written
buf.put(Encoding.FIXED_SIZE_ENCODING.getByteEncoding());
// this is a header value to indicate the size of each entry
VarintUtils.writeUnsignedInt(bytesPerEntry, buf);
for (int i = 0; i < fieldValue.length; i += 8) {
int header = 255;
final int headerIdx = buf.position();
buf.position(headerIdx + 1);
for (int j = 0; ((i + j) < fieldValue.length) && (j < 8); j++) {
final int mask = ~((int) Math.pow(2.0, j));
if (fieldValue[i + j] == null) {
header = header & mask;
} else {
buf.put(byteData[i + j]);
}
}
buf.put(headerIdx, (byte) header);
}
return buf.array();
}
protected byte[] writeVariableSizeField(final FieldType[] fieldValue) {
if (fieldValue == null) {
return new byte[] {};
}
final byte[][] bytes = getBytes(fieldValue);
int sizeBytes = 0;
for (final byte[] entry : bytes) {
sizeBytes += VarintUtils.unsignedIntByteLength(entry.length);
}
final ByteBuffer buf = ByteBuffer.allocate(1 + sizeBytes + getLength(bytes));
// this is a header value to indicate how data should be read/written
buf.put(Encoding.VARIABLE_SIZE_ENCODING.getByteEncoding());
for (final byte[] entry : bytes) {
VarintUtils.writeUnsignedInt(entry.length, buf);
if (entry.length > 0) {
buf.put(entry);
}
}
return buf.array();
}
private byte[][] getBytes(final FieldType[] fieldData) {
final byte[][] bytes = new byte[fieldData.length][];
for (int i = 0; i < fieldData.length; i++) {
if (fieldData[i] == null) {
bytes[i] = new byte[] {};
} else {
bytes[i] = writer.writeField(fieldData[i]);
}
}
return bytes;
}
private int getLength(final byte[][] bytes) {
int length = 0;
for (final byte[] entry : bytes) {
length += entry.length;
}
return length;
}
public static class FixedSizeObjectArrayWriter<FieldType> extends ArrayWriter<FieldType> {
public FixedSizeObjectArrayWriter(final FieldWriter<FieldType> writer) {
super(writer);
}
@Override
public byte[] writeField(final FieldType[] fieldValue) {
return super.writeFixedSizeField(fieldValue);
}
}
public static class VariableSizeObjectArrayWriter<FieldType> extends ArrayWriter<FieldType> {
public VariableSizeObjectArrayWriter(final FieldWriter<FieldType> writer) {
super(writer);
}
@Override
public byte[] writeField(final FieldType[] fieldValue) {
return super.writeVariableSizeField(fieldValue);
}
}
}
| 0 | 0.887626 | 1 | 0.887626 | game-dev | MEDIA | 0.256807 | game-dev | 0.91032 | 1 | 0.91032 |
GalaxyCr8r/solarance-beginnings | 8,614 | client/src/gameplay/gui/faction_window.rs | use egui::{Color32, Context, RichText};
use spacetimedb_sdk::*;
use crate::{module_bindings::*, stdb::utils::get_faction_shortname};
#[derive(PartialEq)]
enum CurrentTab {
Player,
Faction,
Members,
Relations,
}
pub struct State {
current_tab: CurrentTab,
}
impl State {
pub fn new() -> Self {
State {
current_tab: CurrentTab::Player,
}
}
}
pub fn draw(
egui_ctx: &Context,
ctx: &DbConnection,
state: &mut State,
open: &mut bool,
) -> Option<egui::InnerResponse<Option<()>>> {
egui::Window::new("Faction Information")
.open(open)
.title_bar(true)
.resizable(true)
.collapsible(true)
.movable(true)
.vscroll(true)
.default_width(400.0)
.default_height(500.0)
.show(egui_ctx, |ui| {
// Tab selection
ui.horizontal(|ui| {
ui.selectable_value(&mut state.current_tab, CurrentTab::Player, "Player");
ui.selectable_value(&mut state.current_tab, CurrentTab::Faction, "Faction");
ui.selectable_value(&mut state.current_tab, CurrentTab::Members, "Members");
ui.selectable_value(&mut state.current_tab, CurrentTab::Relations, "Relations");
});
ui.separator();
match state.current_tab {
CurrentTab::Player => draw_player_tab(ui, ctx),
CurrentTab::Faction => draw_faction_tab(ui, ctx),
CurrentTab::Members => draw_members_tab(ui, ctx),
CurrentTab::Relations => draw_relations_tab(ui, ctx),
}
})
}
fn draw_player_tab(ui: &mut egui::Ui, ctx: &DbConnection) {
ui.heading("Player Information");
ui.separator();
if let Some(player) = ctx.db().player().id().find(&ctx.identity()) {
ui.label(format!("Username: {}", player.username));
ui.label(format!("Credits: {}", player.credits));
ui.label(format!(
"Status: {}",
if player.logged_in {
"Online"
} else {
"Offline"
}
));
ui.separator();
if let Some(faction) = ctx.db().faction().id().find(&player.faction_id.value) {
ui.label(format!("Current Faction: {}", faction.name));
ui.label(format!("Faction Tier: {:?}", faction.tier));
} else {
ui.label("Current Faction: Unknown");
}
} else {
ui.label("Player information not available");
}
}
fn draw_faction_tab(ui: &mut egui::Ui, ctx: &DbConnection) {
ui.heading("Faction Hierarchy");
ui.separator();
// Show player's current faction first if they have one
if let Some(player) = ctx.db().player().id().find(&ctx.identity()) {
if let Some(faction) = ctx.db().faction().id().find(&player.faction_id.value) {
ui.label(
RichText::new(format!(
"Your Faction: {} ({})",
faction.name, faction.short_name
))
.size(16.0)
.strong()
.color(Color32::LIGHT_BLUE),
);
ui.separator();
}
}
ui.label("All Factions:");
ui.separator();
// Get all factions and organize them by parent-child relationships
let all_factions: Vec<_> = ctx.db().faction().iter().collect();
// Find root factions (those without parents)
let root_factions: Vec<_> = all_factions
.iter()
.filter(|f| f.parent_id.is_none())
.collect();
// Draw the faction tree
for root_faction in root_factions {
draw_faction_tree_node(ui, ctx, root_faction, &all_factions, 0);
}
}
fn draw_faction_tree_node(
ui: &mut egui::Ui,
ctx: &DbConnection,
faction: &Faction,
all_factions: &[Faction],
depth: usize,
) {
let indent = " ".repeat(depth);
// Find child factions
let children: Vec<_> = all_factions
.iter()
.filter(|f| f.parent_id.as_ref().map(|p| p.value) == Some(faction.id))
.collect();
// Create collapsing header for factions with children, or simple label for leaf factions
if !children.is_empty() {
let header_text = format!(
"{}{} ({}) - {:?}",
indent, faction.name, faction.short_name, faction.tier
);
ui.collapsing(header_text, |ui| {
// Show faction details
draw_faction_details(ui, ctx, faction);
ui.separator();
ui.label("Sub-factions:");
// Draw children
for child in children {
draw_faction_tree_node(ui, ctx, child, all_factions, depth + 1);
}
});
} else {
// Leaf faction - show as expandable for details
let header_text = format!(
"{}{} ({}) - {:?}",
indent, faction.name, faction.short_name, faction.tier
);
ui.collapsing(header_text, |ui| {
draw_faction_details(ui, ctx, faction);
});
}
}
fn draw_faction_details(ui: &mut egui::Ui, ctx: &DbConnection, faction: &Faction) {
ui.label(format!("Short Name: {}", faction.short_name));
ui.label(format!("Tier: {:?}", faction.tier));
ui.label(format!(
"Joinable: {}",
if faction.joinable { "Yes" } else { "No" }
));
if let Some(parent_id) = &faction.parent_id {
if let Some(parent) = ctx.db().faction().id().find(&parent_id.value) {
ui.label(format!("Parent: {} ({})", parent.name, parent.short_name));
}
}
if let Some(capital_id) = faction.capital_station_id {
ui.label(format!("Capital Station ID: {}", capital_id));
}
ui.separator();
ui.label("Description:");
ui.label(&faction.description);
// Show member count
let member_count = ctx
.db()
.player()
.iter()
.filter(|p| p.faction_id.value == faction.id)
.count();
ui.label(format!("Members: {}", member_count));
}
fn draw_members_tab(ui: &mut egui::Ui, ctx: &DbConnection) {
ui.heading("Faction Members");
ui.separator();
if let Some(player) = ctx.db().player().id().find(&ctx.identity()) {
let members: Vec<_> = ctx
.db()
.player()
.iter()
.filter(|p| p.faction_id.value == player.faction_id.value)
.collect();
ui.label(format!("Total Members: {}", members.len()));
ui.separator();
for member in members {
ui.horizontal(|ui| {
let status_color = if member.logged_in {
Color32::GREEN
} else {
Color32::GRAY
};
ui.colored_label(status_color, "●");
ui.label(&member.username);
ui.label(format!("Credits: {}", member.credits));
});
}
}
}
fn draw_relations_tab(ui: &mut egui::Ui, ctx: &DbConnection) {
ui.heading("Faction Relations");
ui.separator();
if let Some(player) = ctx.db().player().id().find(&ctx.identity()) {
ui.label(format!(
"{}'s relations with other factions:",
get_faction_shortname(ctx, &player.faction_id.value)
));
ui.separator();
for faction in ctx.db().faction().iter() {
if faction.id != player.faction_id.value {
ui.horizontal(|ui| {
ui.label(&faction.name);
// Find standing between current faction and this faction
if let Some(standing) = ctx.db().faction_standing().iter().find(|s| {
s.faction_one_id == player.faction_id.value
&& s.faction_two_id == faction.id
}) {
let (color, status) = get_reputation_display(standing.reputation_score);
ui.colored_label(color, status);
ui.label(format!("({})", standing.reputation_score));
} else {
ui.colored_label(Color32::GRAY, "Unknown");
}
});
}
}
}
}
fn get_reputation_display(reputation: i32) -> (Color32, &'static str) {
match reputation {
r if r >= 75 => (Color32::LIGHT_BLUE, "Allied"),
r if r >= 25 => (Color32::GREEN, "Friendly"),
r if r >= -25 => (Color32::YELLOW, "Neutral"),
r if r >= -75 => (Color32::ORANGE, "Disliked"),
_ => (Color32::RED, "Hostile"),
}
}
| 0 | 0.541402 | 1 | 0.541402 | game-dev | MEDIA | 0.96773 | game-dev | 0.886613 | 1 | 0.886613 |
Redot-Engine/redot-engine | 33,314 | scene/3d/physics/area_3d.cpp | /**************************************************************************/
/* area_3d.cpp */
/**************************************************************************/
/* This file is part of: */
/* REDOT ENGINE */
/* https://redotengine.org */
/**************************************************************************/
/* Copyright (c) 2024-present Redot Engine contributors */
/* (see REDOT_AUTHORS.md) */
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "area_3d.h"
#include "servers/audio_server.h"
void Area3D::set_gravity_space_override_mode(SpaceOverride p_mode) {
gravity_space_override = p_mode;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_OVERRIDE_MODE, p_mode);
}
Area3D::SpaceOverride Area3D::get_gravity_space_override_mode() const {
return gravity_space_override;
}
void Area3D::set_gravity_is_point(bool p_enabled) {
gravity_is_point = p_enabled;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT, p_enabled);
}
bool Area3D::is_gravity_a_point() const {
return gravity_is_point;
}
void Area3D::set_gravity_point_unit_distance(real_t p_scale) {
gravity_point_unit_distance = p_scale;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_UNIT_DISTANCE, p_scale);
}
real_t Area3D::get_gravity_point_unit_distance() const {
return gravity_point_unit_distance;
}
void Area3D::set_gravity_point_center(const Vector3 &p_center) {
gravity_vec = p_center;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, p_center);
}
const Vector3 &Area3D::get_gravity_point_center() const {
return gravity_vec;
}
void Area3D::set_gravity_direction(const Vector3 &p_direction) {
gravity_vec = p_direction;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, p_direction);
}
const Vector3 &Area3D::get_gravity_direction() const {
return gravity_vec;
}
void Area3D::set_gravity(real_t p_gravity) {
gravity = p_gravity;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY, p_gravity);
}
real_t Area3D::get_gravity() const {
return gravity;
}
void Area3D::set_linear_damp_space_override_mode(SpaceOverride p_mode) {
linear_damp_space_override = p_mode;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_LINEAR_DAMP_OVERRIDE_MODE, p_mode);
}
Area3D::SpaceOverride Area3D::get_linear_damp_space_override_mode() const {
return linear_damp_space_override;
}
void Area3D::set_angular_damp_space_override_mode(SpaceOverride p_mode) {
angular_damp_space_override = p_mode;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP_OVERRIDE_MODE, p_mode);
}
Area3D::SpaceOverride Area3D::get_angular_damp_space_override_mode() const {
return angular_damp_space_override;
}
void Area3D::set_linear_damp(real_t p_linear_damp) {
linear_damp = p_linear_damp;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_LINEAR_DAMP, p_linear_damp);
}
real_t Area3D::get_linear_damp() const {
return linear_damp;
}
void Area3D::set_angular_damp(real_t p_angular_damp) {
angular_damp = p_angular_damp;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP, p_angular_damp);
}
real_t Area3D::get_angular_damp() const {
return angular_damp;
}
void Area3D::set_priority(int p_priority) {
priority = p_priority;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_PRIORITY, p_priority);
}
int Area3D::get_priority() const {
return priority;
}
void Area3D::set_wind_force_magnitude(real_t p_wind_force_magnitude) {
wind_force_magnitude = p_wind_force_magnitude;
if (is_inside_tree()) {
_initialize_wind();
}
}
real_t Area3D::get_wind_force_magnitude() const {
return wind_force_magnitude;
}
void Area3D::set_wind_attenuation_factor(real_t p_wind_force_attenuation_factor) {
wind_attenuation_factor = p_wind_force_attenuation_factor;
if (is_inside_tree()) {
_initialize_wind();
}
}
real_t Area3D::get_wind_attenuation_factor() const {
return wind_attenuation_factor;
}
void Area3D::set_wind_source_path(const NodePath &p_wind_source_path) {
wind_source_path = p_wind_source_path;
if (is_inside_tree()) {
_initialize_wind();
}
}
const NodePath &Area3D::get_wind_source_path() const {
return wind_source_path;
}
void Area3D::_initialize_wind() {
real_t temp_magnitude = 0.0;
Vector3 wind_direction(0., 0., 0.);
Vector3 wind_source(0., 0., 0.);
// Overwrite with area-specified info if available
if (!wind_source_path.is_empty()) {
Node *wind_source_node = get_node_or_null(wind_source_path);
ERR_FAIL_NULL_MSG(wind_source_node, "Path to wind source is invalid: '" + String(wind_source_path) + "'.");
Node3D *wind_source_node3d = Object::cast_to<Node3D>(wind_source_node);
ERR_FAIL_NULL_MSG(wind_source_node3d, "Path to wind source does not point to a Node3D: '" + String(wind_source_path) + "'.");
Transform3D global_transform = wind_source_node3d->get_transform();
wind_direction = -global_transform.basis.get_column(Vector3::AXIS_Z).normalized();
wind_source = global_transform.origin;
temp_magnitude = wind_force_magnitude;
}
// Set force, source and direction in the physics server.
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_ATTENUATION_FACTOR, wind_attenuation_factor);
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_SOURCE, wind_source);
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_DIRECTION, wind_direction);
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_FORCE_MAGNITUDE, temp_magnitude);
}
void Area3D::_body_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = Object::cast_to<Node>(obj);
ERR_FAIL_NULL(node);
HashMap<ObjectID, BodyState>::Iterator E = body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->value.in_tree);
E->value.in_tree = true;
emit_signal(SceneStringName(body_entered), node);
for (int i = 0; i < E->value.shapes.size(); i++) {
emit_signal(SceneStringName(body_shape_entered), E->value.rid, node, E->value.shapes[i].body_shape, E->value.shapes[i].area_shape);
}
}
void Area3D::_body_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = Object::cast_to<Node>(obj);
ERR_FAIL_NULL(node);
HashMap<ObjectID, BodyState>::Iterator E = body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->value.in_tree);
E->value.in_tree = false;
emit_signal(SceneStringName(body_exited), node);
for (int i = 0; i < E->value.shapes.size(); i++) {
emit_signal(SceneStringName(body_shape_exited), E->value.rid, node, E->value.shapes[i].body_shape, E->value.shapes[i].area_shape);
}
}
void Area3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, int p_body_shape, int p_area_shape) {
bool body_in = p_status == PhysicsServer3D::AREA_BODY_ADDED;
ObjectID objid = p_instance;
// Exit early if instance is invalid.
if (objid.is_null()) {
lock_callback();
locked = true;
// Emit the appropriate signals.
if (body_in) {
emit_signal(SceneStringName(body_shape_entered), p_body, (Node *)nullptr, p_body_shape, p_area_shape);
} else {
emit_signal(SceneStringName(body_shape_exited), p_body, (Node *)nullptr, p_body_shape, p_area_shape);
}
locked = false;
unlock_callback();
return;
}
Object *obj = ObjectDB::get_instance(objid);
Node *node = Object::cast_to<Node>(obj);
HashMap<ObjectID, BodyState>::Iterator E = body_map.find(objid);
if (!body_in && !E) {
return; //likely removed from the tree
}
lock_callback();
locked = true;
if (body_in) {
if (!E) {
E = body_map.insert(objid, BodyState());
E->value.rid = p_body;
E->value.rc = 0;
E->value.in_tree = node && node->is_inside_tree();
if (node) {
node->connect(SceneStringName(tree_entered), callable_mp(this, &Area3D::_body_enter_tree).bind(objid));
node->connect(SceneStringName(tree_exiting), callable_mp(this, &Area3D::_body_exit_tree).bind(objid));
if (E->value.in_tree) {
emit_signal(SceneStringName(body_entered), node);
}
}
}
E->value.rc++;
if (node) {
E->value.shapes.insert(ShapePair(p_body_shape, p_area_shape));
}
if (!node || E->value.in_tree) {
emit_signal(SceneStringName(body_shape_entered), p_body, node, p_body_shape, p_area_shape);
}
} else {
E->value.rc--;
if (node) {
E->value.shapes.erase(ShapePair(p_body_shape, p_area_shape));
}
bool in_tree = E->value.in_tree;
if (E->value.rc == 0) {
body_map.remove(E);
if (node) {
node->disconnect(SceneStringName(tree_entered), callable_mp(this, &Area3D::_body_enter_tree));
node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &Area3D::_body_exit_tree));
if (in_tree) {
emit_signal(SceneStringName(body_exited), obj);
}
}
}
if (!node || in_tree) {
emit_signal(SceneStringName(body_shape_exited), p_body, obj, p_body_shape, p_area_shape);
}
}
locked = false;
unlock_callback();
}
void Area3D::_clear_monitoring() {
ERR_FAIL_COND_MSG(locked, "This function can't be used during the in/out signal.");
{
HashMap<ObjectID, BodyState> bmcopy = body_map;
body_map.clear();
//disconnect all monitored stuff
for (const KeyValue<ObjectID, BodyState> &E : bmcopy) {
Object *obj = ObjectDB::get_instance(E.key);
Node *node = Object::cast_to<Node>(obj);
if (!node) { //node may have been deleted in previous frame or at other legitimate point
continue;
}
//ERR_CONTINUE(!node);
node->disconnect(SceneStringName(tree_entered), callable_mp(this, &Area3D::_body_enter_tree));
node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &Area3D::_body_exit_tree));
if (!E.value.in_tree) {
continue;
}
for (int i = 0; i < E.value.shapes.size(); i++) {
emit_signal(SceneStringName(body_shape_exited), E.value.rid, node, E.value.shapes[i].body_shape, E.value.shapes[i].area_shape);
}
emit_signal(SceneStringName(body_exited), node);
}
}
{
HashMap<ObjectID, AreaState> bmcopy = area_map;
area_map.clear();
//disconnect all monitored stuff
for (const KeyValue<ObjectID, AreaState> &E : bmcopy) {
Object *obj = ObjectDB::get_instance(E.key);
Node *node = Object::cast_to<Node>(obj);
if (!node) { //node may have been deleted in previous frame or at other legitimate point
continue;
}
//ERR_CONTINUE(!node);
node->disconnect(SceneStringName(tree_entered), callable_mp(this, &Area3D::_area_enter_tree));
node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &Area3D::_area_exit_tree));
if (!E.value.in_tree) {
continue;
}
for (int i = 0; i < E.value.shapes.size(); i++) {
emit_signal(SceneStringName(area_shape_exited), E.value.rid, node, E.value.shapes[i].area_shape, E.value.shapes[i].self_shape);
}
emit_signal(SceneStringName(area_exited), obj);
}
}
}
void Area3D::_space_changed(const RID &p_new_space) {
if (p_new_space.is_null()) {
_clear_monitoring();
}
}
void Area3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
_initialize_wind();
} break;
}
}
void Area3D::set_monitoring(bool p_enable) {
ERR_FAIL_COND_MSG(locked, "Function blocked during in/out signal. Use set_deferred(\"monitoring\", true/false).");
if (p_enable == monitoring) {
return;
}
monitoring = p_enable;
if (monitoring) {
PhysicsServer3D::get_singleton()->area_set_monitor_callback(get_rid(), callable_mp(this, &Area3D::_body_inout));
PhysicsServer3D::get_singleton()->area_set_area_monitor_callback(get_rid(), callable_mp(this, &Area3D::_area_inout));
} else {
PhysicsServer3D::get_singleton()->area_set_monitor_callback(get_rid(), Callable());
PhysicsServer3D::get_singleton()->area_set_area_monitor_callback(get_rid(), Callable());
_clear_monitoring();
}
}
void Area3D::_area_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = Object::cast_to<Node>(obj);
ERR_FAIL_NULL(node);
HashMap<ObjectID, AreaState>::Iterator E = area_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->value.in_tree);
E->value.in_tree = true;
emit_signal(SceneStringName(area_entered), node);
for (int i = 0; i < E->value.shapes.size(); i++) {
emit_signal(SceneStringName(area_shape_entered), E->value.rid, node, E->value.shapes[i].area_shape, E->value.shapes[i].self_shape);
}
}
void Area3D::_area_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = Object::cast_to<Node>(obj);
ERR_FAIL_NULL(node);
HashMap<ObjectID, AreaState>::Iterator E = area_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->value.in_tree);
E->value.in_tree = false;
emit_signal(SceneStringName(area_exited), node);
for (int i = 0; i < E->value.shapes.size(); i++) {
emit_signal(SceneStringName(area_shape_exited), E->value.rid, node, E->value.shapes[i].area_shape, E->value.shapes[i].self_shape);
}
}
void Area3D::_area_inout(int p_status, const RID &p_area, ObjectID p_instance, int p_area_shape, int p_self_shape) {
bool area_in = p_status == PhysicsServer3D::AREA_BODY_ADDED;
ObjectID objid = p_instance;
// Exit if instance is invalid.
if (objid.is_null()) {
lock_callback();
locked = true;
// Emit the appropriate signals.
if (area_in) {
emit_signal(SceneStringName(area_shape_entered), p_area, (Node *)nullptr, p_area_shape, p_self_shape);
} else {
emit_signal(SceneStringName(area_shape_exited), p_area, (Node *)nullptr, p_area_shape, p_self_shape);
}
locked = false;
unlock_callback();
return;
}
Object *obj = ObjectDB::get_instance(objid);
Node *node = Object::cast_to<Node>(obj);
HashMap<ObjectID, AreaState>::Iterator E = area_map.find(objid);
if (!area_in && !E) {
return; //likely removed from the tree
}
lock_callback();
locked = true;
if (area_in) {
if (!E) {
E = area_map.insert(objid, AreaState());
E->value.rid = p_area;
E->value.rc = 0;
E->value.in_tree = node && node->is_inside_tree();
if (node) {
node->connect(SceneStringName(tree_entered), callable_mp(this, &Area3D::_area_enter_tree).bind(objid));
node->connect(SceneStringName(tree_exiting), callable_mp(this, &Area3D::_area_exit_tree).bind(objid));
if (E->value.in_tree) {
emit_signal(SceneStringName(area_entered), node);
}
}
}
E->value.rc++;
if (node) {
E->value.shapes.insert(AreaShapePair(p_area_shape, p_self_shape));
}
if (!node || E->value.in_tree) {
emit_signal(SceneStringName(area_shape_entered), p_area, node, p_area_shape, p_self_shape);
}
} else {
E->value.rc--;
if (node) {
E->value.shapes.erase(AreaShapePair(p_area_shape, p_self_shape));
}
bool in_tree = E->value.in_tree;
if (E->value.rc == 0) {
area_map.remove(E);
if (node) {
node->disconnect(SceneStringName(tree_entered), callable_mp(this, &Area3D::_area_enter_tree));
node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &Area3D::_area_exit_tree));
if (in_tree) {
emit_signal(SceneStringName(area_exited), obj);
}
}
}
if (!node || in_tree) {
emit_signal(SceneStringName(area_shape_exited), p_area, obj, p_area_shape, p_self_shape);
}
}
locked = false;
unlock_callback();
}
bool Area3D::is_monitoring() const {
return monitoring;
}
TypedArray<Node3D> Area3D::get_overlapping_bodies() const {
TypedArray<Node3D> ret;
ERR_FAIL_COND_V_MSG(!monitoring, ret, "Can't find overlapping bodies when monitoring is off.");
ret.resize(body_map.size());
int idx = 0;
for (const KeyValue<ObjectID, BodyState> &E : body_map) {
Object *obj = ObjectDB::get_instance(E.key);
if (obj) {
ret[idx] = obj;
idx++;
}
}
ret.resize(idx);
return ret;
}
bool Area3D::has_overlapping_bodies() const {
ERR_FAIL_COND_V_MSG(!monitoring, false, "Can't find overlapping bodies when monitoring is off.");
return !body_map.is_empty();
}
void Area3D::set_monitorable(bool p_enable) {
ERR_FAIL_COND_MSG(locked || (is_inside_tree() && PhysicsServer3D::get_singleton()->is_flushing_queries()), "Function blocked during in/out signal. Use set_deferred(\"monitorable\", true/false).");
if (p_enable == monitorable) {
return;
}
monitorable = p_enable;
PhysicsServer3D::get_singleton()->area_set_monitorable(get_rid(), monitorable);
}
bool Area3D::is_monitorable() const {
return monitorable;
}
TypedArray<Area3D> Area3D::get_overlapping_areas() const {
TypedArray<Area3D> ret;
ERR_FAIL_COND_V_MSG(!monitoring, ret, "Can't find overlapping areas when monitoring is off.");
ret.resize(area_map.size());
int idx = 0;
for (const KeyValue<ObjectID, AreaState> &E : area_map) {
Object *obj = ObjectDB::get_instance(E.key);
if (obj) {
ret[idx] = obj;
idx++;
}
}
ret.resize(idx);
return ret;
}
bool Area3D::has_overlapping_areas() const {
ERR_FAIL_COND_V_MSG(!monitoring, false, "Can't find overlapping areas when monitoring is off.");
return !area_map.is_empty();
}
bool Area3D::overlaps_area(Node *p_area) const {
ERR_FAIL_NULL_V(p_area, false);
HashMap<ObjectID, AreaState>::ConstIterator E = area_map.find(p_area->get_instance_id());
if (!E) {
return false;
}
return E->value.in_tree;
}
bool Area3D::overlaps_body(Node *p_body) const {
ERR_FAIL_NULL_V(p_body, false);
HashMap<ObjectID, BodyState>::ConstIterator E = body_map.find(p_body->get_instance_id());
if (!E) {
return false;
}
return E->value.in_tree;
}
void Area3D::set_audio_bus_override(bool p_override) {
audio_bus_override = p_override;
}
bool Area3D::is_overriding_audio_bus() const {
return audio_bus_override;
}
void Area3D::set_audio_bus_name(const StringName &p_audio_bus) {
audio_bus = p_audio_bus;
}
StringName Area3D::get_audio_bus_name() const {
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (AudioServer::get_singleton()->get_bus_name(i) == audio_bus) {
return audio_bus;
}
}
return SceneStringName(Master);
}
void Area3D::set_use_reverb_bus(bool p_enable) {
use_reverb_bus = p_enable;
}
bool Area3D::is_using_reverb_bus() const {
return use_reverb_bus;
}
void Area3D::set_reverb_bus_name(const StringName &p_audio_bus) {
reverb_bus = p_audio_bus;
}
StringName Area3D::get_reverb_bus_name() const {
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (AudioServer::get_singleton()->get_bus_name(i) == reverb_bus) {
return reverb_bus;
}
}
return SceneStringName(Master);
}
void Area3D::set_reverb_amount(float p_amount) {
reverb_amount = p_amount;
}
float Area3D::get_reverb_amount() const {
return reverb_amount;
}
void Area3D::set_reverb_uniformity(float p_uniformity) {
reverb_uniformity = p_uniformity;
}
float Area3D::get_reverb_uniformity() const {
return reverb_uniformity;
}
void Area3D::_validate_property(PropertyInfo &p_property) const {
if (!Engine::get_singleton()->is_editor_hint()) {
return;
}
if (p_property.name == "audio_bus_name" || p_property.name == "reverb_bus_name") {
String options;
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (i > 0) {
options += ",";
}
String name = AudioServer::get_singleton()->get_bus_name(i);
options += name;
}
p_property.hint_string = options;
} else if (p_property.name.begins_with("gravity") && p_property.name != "gravity_space_override") {
if (gravity_space_override == SPACE_OVERRIDE_DISABLED) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
} else {
if (gravity_is_point) {
if (p_property.name == "gravity_direction") {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
} else {
if (p_property.name.begins_with("gravity_point_")) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
} else if (p_property.name.begins_with("linear_damp") && p_property.name != "linear_damp_space_override") {
if (linear_damp_space_override == SPACE_OVERRIDE_DISABLED) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
} else if (p_property.name.begins_with("angular_damp") && p_property.name != "angular_damp_space_override") {
if (angular_damp_space_override == SPACE_OVERRIDE_DISABLED) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
}
void Area3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_gravity_space_override_mode", "space_override_mode"), &Area3D::set_gravity_space_override_mode);
ClassDB::bind_method(D_METHOD("get_gravity_space_override_mode"), &Area3D::get_gravity_space_override_mode);
ClassDB::bind_method(D_METHOD("set_gravity_is_point", "enable"), &Area3D::set_gravity_is_point);
ClassDB::bind_method(D_METHOD("is_gravity_a_point"), &Area3D::is_gravity_a_point);
ClassDB::bind_method(D_METHOD("set_gravity_point_unit_distance", "distance_scale"), &Area3D::set_gravity_point_unit_distance);
ClassDB::bind_method(D_METHOD("get_gravity_point_unit_distance"), &Area3D::get_gravity_point_unit_distance);
ClassDB::bind_method(D_METHOD("set_gravity_point_center", "center"), &Area3D::set_gravity_point_center);
ClassDB::bind_method(D_METHOD("get_gravity_point_center"), &Area3D::get_gravity_point_center);
ClassDB::bind_method(D_METHOD("set_gravity_direction", "direction"), &Area3D::set_gravity_direction);
ClassDB::bind_method(D_METHOD("get_gravity_direction"), &Area3D::get_gravity_direction);
ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &Area3D::set_gravity);
ClassDB::bind_method(D_METHOD("get_gravity"), &Area3D::get_gravity);
ClassDB::bind_method(D_METHOD("set_linear_damp_space_override_mode", "space_override_mode"), &Area3D::set_linear_damp_space_override_mode);
ClassDB::bind_method(D_METHOD("get_linear_damp_space_override_mode"), &Area3D::get_linear_damp_space_override_mode);
ClassDB::bind_method(D_METHOD("set_angular_damp_space_override_mode", "space_override_mode"), &Area3D::set_angular_damp_space_override_mode);
ClassDB::bind_method(D_METHOD("get_angular_damp_space_override_mode"), &Area3D::get_angular_damp_space_override_mode);
ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &Area3D::set_angular_damp);
ClassDB::bind_method(D_METHOD("get_angular_damp"), &Area3D::get_angular_damp);
ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &Area3D::set_linear_damp);
ClassDB::bind_method(D_METHOD("get_linear_damp"), &Area3D::get_linear_damp);
ClassDB::bind_method(D_METHOD("set_priority", "priority"), &Area3D::set_priority);
ClassDB::bind_method(D_METHOD("get_priority"), &Area3D::get_priority);
ClassDB::bind_method(D_METHOD("set_wind_force_magnitude", "wind_force_magnitude"), &Area3D::set_wind_force_magnitude);
ClassDB::bind_method(D_METHOD("get_wind_force_magnitude"), &Area3D::get_wind_force_magnitude);
ClassDB::bind_method(D_METHOD("set_wind_attenuation_factor", "wind_attenuation_factor"), &Area3D::set_wind_attenuation_factor);
ClassDB::bind_method(D_METHOD("get_wind_attenuation_factor"), &Area3D::get_wind_attenuation_factor);
ClassDB::bind_method(D_METHOD("set_wind_source_path", "wind_source_path"), &Area3D::set_wind_source_path);
ClassDB::bind_method(D_METHOD("get_wind_source_path"), &Area3D::get_wind_source_path);
ClassDB::bind_method(D_METHOD("set_monitorable", "enable"), &Area3D::set_monitorable);
ClassDB::bind_method(D_METHOD("is_monitorable"), &Area3D::is_monitorable);
ClassDB::bind_method(D_METHOD("set_monitoring", "enable"), &Area3D::set_monitoring);
ClassDB::bind_method(D_METHOD("is_monitoring"), &Area3D::is_monitoring);
ClassDB::bind_method(D_METHOD("get_overlapping_bodies"), &Area3D::get_overlapping_bodies);
ClassDB::bind_method(D_METHOD("get_overlapping_areas"), &Area3D::get_overlapping_areas);
ClassDB::bind_method(D_METHOD("has_overlapping_bodies"), &Area3D::has_overlapping_bodies);
ClassDB::bind_method(D_METHOD("has_overlapping_areas"), &Area3D::has_overlapping_areas);
ClassDB::bind_method(D_METHOD("overlaps_body", "body"), &Area3D::overlaps_body);
ClassDB::bind_method(D_METHOD("overlaps_area", "area"), &Area3D::overlaps_area);
ClassDB::bind_method(D_METHOD("set_audio_bus_override", "enable"), &Area3D::set_audio_bus_override);
ClassDB::bind_method(D_METHOD("is_overriding_audio_bus"), &Area3D::is_overriding_audio_bus);
ClassDB::bind_method(D_METHOD("set_audio_bus_name", "name"), &Area3D::set_audio_bus_name);
ClassDB::bind_method(D_METHOD("get_audio_bus_name"), &Area3D::get_audio_bus_name);
ClassDB::bind_method(D_METHOD("set_use_reverb_bus", "enable"), &Area3D::set_use_reverb_bus);
ClassDB::bind_method(D_METHOD("is_using_reverb_bus"), &Area3D::is_using_reverb_bus);
ClassDB::bind_method(D_METHOD("set_reverb_bus_name", "name"), &Area3D::set_reverb_bus_name);
ClassDB::bind_method(D_METHOD("get_reverb_bus_name"), &Area3D::get_reverb_bus_name);
ClassDB::bind_method(D_METHOD("set_reverb_amount", "amount"), &Area3D::set_reverb_amount);
ClassDB::bind_method(D_METHOD("get_reverb_amount"), &Area3D::get_reverb_amount);
ClassDB::bind_method(D_METHOD("set_reverb_uniformity", "amount"), &Area3D::set_reverb_uniformity);
ClassDB::bind_method(D_METHOD("get_reverb_uniformity"), &Area3D::get_reverb_uniformity);
ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D")));
ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D")));
ADD_SIGNAL(MethodInfo("area_shape_entered", PropertyInfo(Variant::RID, "area_rid"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D"), PropertyInfo(Variant::INT, "area_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
ADD_SIGNAL(MethodInfo("area_shape_exited", PropertyInfo(Variant::RID, "area_rid"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D"), PropertyInfo(Variant::INT, "area_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
ADD_SIGNAL(MethodInfo("area_entered", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D")));
ADD_SIGNAL(MethodInfo("area_exited", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D")));
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "monitoring"), "set_monitoring", "is_monitoring");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "monitorable"), "set_monitorable", "is_monitorable");
ADD_PROPERTY(PropertyInfo(Variant::INT, "priority", PROPERTY_HINT_RANGE, "0,100000,1,or_greater,or_less"), "set_priority", "get_priority");
ADD_GROUP("Gravity", "gravity_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "gravity_space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_gravity_space_override_mode", "get_gravity_space_override_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gravity_point", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_gravity_is_point", "is_gravity_a_point");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_point_unit_distance", PROPERTY_HINT_RANGE, "0,1024,0.001,or_greater,exp,suffix:m"), "set_gravity_point_unit_distance", "get_gravity_point_unit_distance");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity_point_center", PROPERTY_HINT_NONE, "suffix:m"), "set_gravity_point_center", "get_gravity_point_center");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity_direction"), "set_gravity_direction", "get_gravity_direction");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity", PROPERTY_HINT_RANGE, U"-32,32,0.001,or_less,or_greater,suffix:m/s\u00B2"), "set_gravity", "get_gravity");
ADD_GROUP("Linear Damp", "linear_damp_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "linear_damp_space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_linear_damp_space_override_mode", "get_linear_damp_space_override_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "linear_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_linear_damp", "get_linear_damp");
ADD_GROUP("Angular Damp", "angular_damp_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "angular_damp_space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_angular_damp_space_override_mode", "get_angular_damp_space_override_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_angular_damp", "get_angular_damp");
ADD_GROUP("Wind", "wind_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wind_force_magnitude", PROPERTY_HINT_RANGE, "0,10,0.001,or_greater"), "set_wind_force_magnitude", "get_wind_force_magnitude");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wind_attenuation_factor", PROPERTY_HINT_RANGE, "0.0,3.0,0.001,or_greater"), "set_wind_attenuation_factor", "get_wind_attenuation_factor");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "wind_source_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_wind_source_path", "get_wind_source_path");
ADD_GROUP("Audio Bus", "audio_bus_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "audio_bus_override"), "set_audio_bus_override", "is_overriding_audio_bus");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "audio_bus_name", PROPERTY_HINT_ENUM, ""), "set_audio_bus_name", "get_audio_bus_name");
ADD_GROUP("Reverb Bus", "reverb_bus_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reverb_bus_enabled"), "set_use_reverb_bus", "is_using_reverb_bus");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "reverb_bus_name", PROPERTY_HINT_ENUM, ""), "set_reverb_bus_name", "get_reverb_bus_name");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "reverb_bus_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_reverb_amount", "get_reverb_amount");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "reverb_bus_uniformity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_reverb_uniformity", "get_reverb_uniformity");
BIND_ENUM_CONSTANT(SPACE_OVERRIDE_DISABLED);
BIND_ENUM_CONSTANT(SPACE_OVERRIDE_COMBINE);
BIND_ENUM_CONSTANT(SPACE_OVERRIDE_COMBINE_REPLACE);
BIND_ENUM_CONSTANT(SPACE_OVERRIDE_REPLACE);
BIND_ENUM_CONSTANT(SPACE_OVERRIDE_REPLACE_COMBINE);
}
Area3D::Area3D() :
CollisionObject3D(PhysicsServer3D::get_singleton()->area_create(), true) {
audio_bus = SceneStringName(Master);
reverb_bus = SceneStringName(Master);
set_gravity(9.8);
set_gravity_direction(Vector3(0, -1, 0));
set_monitoring(true);
set_monitorable(true);
}
Area3D::~Area3D() {
}
| 0 | 0.953837 | 1 | 0.953837 | game-dev | MEDIA | 0.894317 | game-dev | 0.716054 | 1 | 0.716054 |
FlaxEngine/FlaxEngine | 31,759 | Source/Editor/Surface/NodeElementArchetype.cs | // Copyright (c) Wojciech Figat. All rights reserved.
using System;
using System.Collections.Generic;
using System.Reflection;
using FlaxEditor.CustomEditors;
using FlaxEditor.Scripting;
using FlaxEngine;
namespace FlaxEditor.Surface
{
/// <summary>
/// Surface node element archetype description.
/// </summary>
[HideInEditor]
public sealed class NodeElementArchetype
{
/// <summary>
/// The element type.
/// </summary>
public NodeElementType Type;
/// <summary>
/// Default element position in node that has default size.
/// </summary>
public Float2 Position;
/// <summary>
/// The element size for some types.
/// </summary>
public Float2 Size;
/// <summary>
/// Custom text value.
/// </summary>
public string Text;
/// <summary>
/// Control tooltip text.
/// </summary>
public string Tooltip;
/// <summary>
/// True if use single connections (for Input element).
/// </summary>
public bool Single;
/// <summary>
/// Index of the node value that is connected with that element.
/// </summary>
public int ValueIndex;
/// <summary>
/// The minimum value.
/// </summary>
public float ValueMin;
/// <summary>
/// The maximum value.
/// </summary>
public float ValueMax;
/// <summary>
/// Unique ID of the box in the graph data to link it to this element (Output/Input elements).
/// </summary>
public int BoxID;
/// <summary>
/// Default connections type for that element (can be set of types).
/// </summary>
public ScriptType ConnectionsType;
/// <summary>
/// Gets the actual element position on the x axis.
/// </summary>
public float ActualPositionX => Position.X + Constants.NodeMarginX;
/// <summary>
/// Gets the actual element position on the y axis.
/// </summary>
public float ActualPositionY => Position.Y + Constants.NodeMarginY + Constants.NodeHeaderSize;
/// <summary>
/// Gets the actual element position.
/// </summary>
public Float2 ActualPosition => new Float2(Position.X + Constants.NodeMarginX, Position.Y + Constants.NodeMarginY + Constants.NodeHeaderSize);
/// <summary>
/// Node element archetypes factory object. Helps to build surface nodes archetypes.
/// </summary>
public static class Factory
{
/// <summary>
/// Creates new Input box element description.
/// </summary>
/// <param name="yLevel">The y level.</param>
/// <param name="text">The text.</param>
/// <param name="single">If true then box can have only one connection, otherwise multiple connections are allowed.</param>
/// <param name="type">The type.</param>
/// <param name="id">The unique box identifier.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Input(float yLevel, string text, bool single, ScriptType type, int id, int valueIndex = -1)
{
return new NodeElementArchetype
{
Type = NodeElementType.Input,
Position = new Float2(
Constants.NodeMarginX - Constants.BoxOffsetX,
Constants.NodeMarginY + Constants.NodeHeaderSize + yLevel * Constants.LayoutOffsetY),
Text = text,
Single = single,
ValueIndex = valueIndex,
BoxID = id,
ConnectionsType = type
};
}
/// <summary>
/// Creates new Input box element description.
/// </summary>
/// <param name="yLevel">The y level.</param>
/// <param name="text">The text.</param>
/// <param name="single">If true then box can have only one connection, otherwise multiple connections are allowed.</param>
/// <param name="type">The type.</param>
/// <param name="id">The unique box identifier.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Input(float yLevel, string text, bool single, Type type, int id, int valueIndex = -1)
{
return new NodeElementArchetype
{
Type = NodeElementType.Input,
Position = new Float2(
Constants.NodeMarginX - Constants.BoxOffsetX,
Constants.NodeMarginY + Constants.NodeHeaderSize + yLevel * Constants.LayoutOffsetY),
Text = text,
Single = single,
ValueIndex = valueIndex,
BoxID = id,
ConnectionsType = new ScriptType(type)
};
}
/// <summary>
/// Creates new Output box element description.
/// </summary>
/// <param name="yLevel">The y level.</param>
/// <param name="text">The text.</param>
/// <param name="type">The type.</param>
/// <param name="id">The unique box identifier.</param>
/// <param name="single">If true then box can have only one connection, otherwise multiple connections are allowed.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Output(float yLevel, string text, ScriptType type, int id, bool single = false)
{
return new NodeElementArchetype
{
Type = NodeElementType.Output,
Position = new Float2(
Constants.NodeMarginX - Constants.BoxSize + Constants.BoxOffsetX,
Constants.NodeMarginY + Constants.NodeHeaderSize + yLevel * Constants.LayoutOffsetY),
Text = text,
Single = single,
ValueIndex = -1,
BoxID = id,
ConnectionsType = type
};
}
/// <summary>
/// Creates new Output box element description.
/// </summary>
/// <param name="yLevel">The y level.</param>
/// <param name="text">The text.</param>
/// <param name="type">The type.</param>
/// <param name="id">The unique box identifier.</param>
/// <param name="single">If true then box can have only one connection, otherwise multiple connections are allowed.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Output(float yLevel, string text, Type type, int id, bool single = false)
{
return new NodeElementArchetype
{
Type = NodeElementType.Output,
Position = new Float2(
Constants.NodeMarginX - Constants.BoxSize + Constants.BoxOffsetX,
Constants.NodeMarginY + Constants.NodeHeaderSize + yLevel * Constants.LayoutOffsetY),
Text = text,
Single = single,
ValueIndex = -1,
BoxID = id,
ConnectionsType = new ScriptType(type)
};
}
/// <summary>
/// Creates new Bool value element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Bool(float x, float y, int valueIndex = -1)
{
return new NodeElementArchetype
{
Type = NodeElementType.BoolValue,
Position = new Float2(x, y),
Text = null,
Single = false,
ValueIndex = valueIndex,
BoxID = -1,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Integer value element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="component">The index of the component to edit. For vectors this can be set to modify only single component of it. Eg. for vec2 value component set to 1 will edit only Y component. Default value -1 will be used to edit whole value.</param>
/// <param name="valueMin">The minimum value range.</param>
/// <param name="valueMax">The maximum value range.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Integer(float x, float y, int valueIndex = -1, int component = -1, int valueMin = -1000000, int valueMax = 1000000)
{
return new NodeElementArchetype
{
Type = NodeElementType.IntegerValue,
Position = new Float2(Constants.NodeMarginX + x, Constants.NodeMarginY + Constants.NodeHeaderSize + y),
Text = null,
Single = false,
ValueIndex = valueIndex,
ValueMin = valueMin,
ValueMax = valueMax,
BoxID = -1,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Unsigned Integer value element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="component">The index of the component to edit. For vectors this can be set to modify only single component of it. Eg. for vec2 value component set to 1 will edit only Y component. Default value -1 will be used to edit whole value.</param>
/// <param name="valueMin">The minimum value range.</param>
/// <param name="valueMax">The maximum value range.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype UnsignedInteger(float x, float y, int valueIndex = -1, int component = -1, uint valueMin = 0, uint valueMax = 1000000)
{
return new NodeElementArchetype
{
Type = NodeElementType.UnsignedIntegerValue,
Position = new Float2(Constants.NodeMarginX + x, Constants.NodeMarginY + Constants.NodeHeaderSize + y),
Text = null,
Single = false,
ValueIndex = valueIndex,
ValueMin = valueMin,
ValueMax = valueMax,
BoxID = -1,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Float value element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="component">The index of the component to edit. For vectors this can be set to modify only single component of it. Eg. for vec2 value component set to 1 will edit only Y component. Default value -1 will be used to edit whole value.</param>
/// <param name="valueMin">The minimum value range.</param>
/// <param name="valueMax">The maximum value range.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Float(float x, float y, int valueIndex = -1, int component = -1, float valueMin = -1000000, float valueMax = 1000000)
{
return new NodeElementArchetype
{
Type = NodeElementType.FloatValue,
Position = new Float2(Constants.NodeMarginX + x, Constants.NodeMarginY + Constants.NodeHeaderSize + y),
Text = null,
Single = false,
ValueIndex = valueIndex,
ValueMin = valueMin,
ValueMax = valueMax,
BoxID = component,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Float2 value element description to edit X component.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="valueMin">The minimum value range.</param>
/// <param name="valueMax">The maximum value range.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Vector_X(float x, float y, int valueIndex = -1, float valueMin = -1000000, float valueMax = 1000000)
{
return Float(x, y, valueIndex, 0, valueMin, valueMax);
}
/// <summary>
/// Creates new Vector value element description to edit Y component.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space). The actual position is offset by 1 times <see cref="Constants.LayoutOffsetY"/> to make it easier to arrange.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="valueMin">The minimum value range.</param>
/// <param name="valueMax">The maximum value range.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Vector_Y(float x, float y, int valueIndex = -1, float valueMin = -1000000, float valueMax = 1000000)
{
return Float(x, y, valueIndex, 1, valueMin, valueMax);
}
/// <summary>
/// Creates new Vector value element description to edit Z component.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space). The actual position is offset by 2 times <see cref="Constants.LayoutOffsetY"/> to make it easier to arrange.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="valueMin">The minimum value range.</param>
/// <param name="valueMax">The maximum value range.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Vector_Z(float x, float y, int valueIndex = -1, float valueMin = -1000000, float valueMax = 1000000)
{
return Float(x, y, valueIndex, 2, valueMin, valueMax);
}
/// <summary>
/// Creates new Vector value element description to edit W component.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space). The actual position is offset by 3 times <see cref="Constants.LayoutOffsetY"/> to make it easier to arrange.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="valueMin">The minimum value range.</param>
/// <param name="valueMax">The maximum value range.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Vector_W(float x, float y, int valueIndex = -1, float valueMin = -1000000, float valueMax = 1000000)
{
return Float(x, y, valueIndex, 3, valueMin, valueMax);
}
/// <summary>
/// Creates new Color value element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Color(float x, float y, int valueIndex = -1)
{
return new NodeElementArchetype
{
Type = NodeElementType.ColorValue,
Position = new Float2(Constants.NodeMarginX + x, Constants.NodeMarginY + Constants.NodeHeaderSize + y),
Text = null,
Single = false,
ValueIndex = valueIndex,
BoxID = -1,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Asset picker element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="type">The allowed assets type to use (including inherited types).</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Asset(float x, float y, int valueIndex, Type type)
{
return new NodeElementArchetype
{
Type = NodeElementType.Asset,
Position = new Float2(x, y),
Text = type.FullName,
Single = false,
ValueIndex = valueIndex,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Actor picker element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="type">The allowed actor type to use (including inherited types).</param>
/// <param name="width">The element width.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Actor(float x, float y, int valueIndex, Type type, float width = 70)
{
return new NodeElementArchetype
{
Type = NodeElementType.Actor,
Position = new Float2(x, y),
Size = new Float2(width, 16),
Text = type.FullName,
Single = false,
ValueIndex = valueIndex,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Combo Box element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="width">The width of the element.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="values">The set of combo box items to present. May be nul if provided at runtime.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype ComboBox(float x, float y, float width, int valueIndex = -1, string[] values = null)
{
return new NodeElementArchetype
{
Type = NodeElementType.ComboBox,
Position = new Float2(x, y),
Size = new Float2(width, 0),
Text = values != null ? string.Join("\n", values) : null, // Pack all values to string separated with new line characters
Single = false,
ValueIndex = valueIndex,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Combo Box element description for enum editing.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="width">The width of the element.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="enumType">The enum type to present all it's values. Important: first value should be 0 and so on.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype ComboBox(float x, float y, int width, int valueIndex, Type enumType)
{
if (enumType == null || !enumType.IsEnum)
throw new ArgumentException();
FieldInfo[] fields = enumType.GetFields();
List<string> values = new List<string>(fields.Length);
for (int i = 0; i < fields.Length; i++)
{
var field = fields[i];
if (field.Name.Equals("value__"))
continue;
var name = Utilities.Utils.GetPropertyNameUI(field.Name);
values.Add(name);
}
return ComboBox(x, y, width, valueIndex, values.ToArray());
}
/// <summary>
/// Creates new Combo Box element description for enum editing.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="width">The width of the element.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="enumType">The enum type to present all it's values.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Enum(float x, float y, int width, int valueIndex, Type enumType)
{
if (enumType == null || !enumType.IsEnum)
throw new ArgumentException();
return new NodeElementArchetype
{
Type = NodeElementType.EnumValue,
Position = new Float2(x, y),
Size = new Float2(width, 0),
Text = enumType.FullName,
Single = false,
ValueIndex = valueIndex,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Text element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="text">The text to show.</param>
/// <param name="width">The control width.</param>
/// <param name="height">The control height.</param>
/// <param name="tooltip">The control tooltip text.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Text(float x, float y, string text, float width = 100.0f, float height = 16.0f, string tooltip = null)
{
return new NodeElementArchetype
{
Type = NodeElementType.Text,
Position = new Float2(x, y),
Size = new Float2(width, height),
Text = text,
Tooltip = tooltip,
Single = false,
ValueIndex = -1,
BoxID = 0,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new TextBox element description.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <param name="isMultiline">Enable/disable multiline text input support</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype TextBox(float x, float y, float width, float height, int valueIndex, bool isMultiline = true)
{
return new NodeElementArchetype
{
Type = NodeElementType.TextBox,
Position = new Float2(Constants.NodeMarginX + x, Constants.NodeMarginY + Constants.NodeHeaderSize + y),
Size = new Float2(width, height),
Single = false,
ValueIndex = valueIndex,
BoxID = isMultiline ? 1 : 0,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Skeleton Bone Index Select element description for enum editing.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="width">The width of the element.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype SkeletonBoneIndexSelect(float x, float y, int width, int valueIndex)
{
return new NodeElementArchetype
{
Type = NodeElementType.SkeletonBoneIndexSelect,
Position = new Float2(x, y),
Size = new Float2(width, 0),
Text = null,
Single = false,
ValueIndex = valueIndex,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new Skeleton Node Name Select element description for enum editing.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="width">The width of the element.</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype SkeletonNodeNameSelect(float x, float y, int width, int valueIndex)
{
return new NodeElementArchetype
{
Type = NodeElementType.SkeletonNodeNameSelect,
Position = new Float2(x, y),
Size = new Float2(width, 0),
Text = null,
Single = false,
ValueIndex = valueIndex,
ConnectionsType = ScriptType.Null
};
}
/// <summary>
/// Creates new element description for Bounding Box editing.
/// </summary>
/// <param name="x">The x location (in node area space).</param>
/// <param name="y">The y location (in node area space).</param>
/// <param name="valueIndex">The index of the node variable linked as the input. Useful to make a physical connection between input box and default value for it.</param>
/// <returns>The archetype.</returns>
public static NodeElementArchetype Box(float x, float y, int valueIndex)
{
return new NodeElementArchetype
{
Type = NodeElementType.BoxValue,
Position = new Float2(Constants.NodeMarginX + x, Constants.NodeMarginY + Constants.NodeHeaderSize + y),
Text = null,
Single = false,
ValueIndex = valueIndex,
ConnectionsType = ScriptType.Null
};
}
}
}
}
| 0 | 0.957613 | 1 | 0.957613 | game-dev | MEDIA | 0.372467 | game-dev | 0.750995 | 1 | 0.750995 |
prolog/shadow-of-the-wyrm | 1,336 | scripts/items/clay_pot.lua | require('constants')
require('fn')
require('items')
-- When a clay pot smashes and this script runs, an item is created.
-- Either an ivory piece, or in much rarer cases, something more useful.
local function pot_smash(item_original_id, props, creature_original_id, row, col)
-- Add a message about the pot smashing.
add_message_for_creature(creature_original_id, "AMMUNITION_DESTRUCTION_SMASH")
local props_t = fn.props_to_table(props)
local suppress_val = props_t[ITEM_PROPERTIES_SUPPRESS_ITEM_GENERATION_ON_DESTRUCTION]
log(CLOG_ERROR, "props: " .. props)
log(CLOG_ERROR, "size: " .. tostring(props_t))
for key,val in pairs(props_t) do
log(CLOG_ERROR, key .. val)
end
if suppress_val ~= "1" then
-- Create the item on the tile.
local base_id = ""
local quantity = 1
if RNG_percent_chance(1) then
base_id = "_ether_potion"
elseif RNG_percent_chance(2) then
base_id = "_healing_potion"
elseif RNG_percent_chance(2) then
base_id = "_unstoning_potion"
else
base_id = CURRENCY_ID
quantity = RNG_range(2,3)
end
log(CLOG_ERROR, "Adding item: " .. base_id)
add_object_to_tile(base_id, row, col, quantity)
end
end
-- Set up the clay pot functions.
local pot_fn = pot_smash
items.set_item_fn("_clay_pot", "ITEM_EVENT_AMMO_DESTRUCT", pot_fn)
| 0 | 0.79887 | 1 | 0.79887 | game-dev | MEDIA | 0.997472 | game-dev | 0.918504 | 1 | 0.918504 |
CCBlueX/LiquidBounce | 2,541 | src/main/java/net/ccbluex/liquidbounce/injection/mixins/minecraft/render/MixinItemRender.java | /*
* This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
*
* Copyright (c) 2015 - 2025 CCBlueX
*
* LiquidBounce 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.
*
* LiquidBounce 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 LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
*/
package net.ccbluex.liquidbounce.injection.mixins.minecraft.render;
import net.ccbluex.liquidbounce.features.module.modules.combat.ModuleSwordBlock;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ModelTransformationMode;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static net.minecraft.item.ModelTransformationMode.THIRD_PERSON_LEFT_HAND;
import static net.minecraft.item.ModelTransformationMode.THIRD_PERSON_RIGHT_HAND;
@Mixin(ItemRenderer.class)
public class MixinItemRender {
@Inject(method = "renderItem(Lnet/minecraft/entity/LivingEntity;Lnet/minecraft/item/ItemStack;Lnet/minecraft/item/ModelTransformationMode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/world/World;III)V", at = @At("HEAD"), cancellable = true)
private void hookRenderItem(LivingEntity entity, ItemStack item, ModelTransformationMode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, World world, int light, int overlay, int seed, CallbackInfo ci) {
if (renderMode == (leftHanded ? THIRD_PERSON_LEFT_HAND : THIRD_PERSON_RIGHT_HAND) && entity instanceof PlayerEntity player && ModuleSwordBlock.INSTANCE.shouldHideOffhand(player, item)) {
ci.cancel();
}
}
}
| 0 | 0.811222 | 1 | 0.811222 | game-dev | MEDIA | 0.981677 | game-dev | 0.761122 | 1 | 0.761122 |
chris81605/DOL-BJXExtende_for_ML_Project | 5,393 | DATA/原版 0.4.5.3/DoLModExportData_20240117_021134/passage/Widgets Actions Possessed.twee | :: Widgets Actions Possessed [widget]
<<widget "actionspossessed">>
<<if !$leftactiondefault>>
<<set $leftactiondefault to "leftacceptW">>
<</if>>
<<if !$rightactiondefault>>
<<set $rightactiondefault to "rightacceptW">>
<</if>>
<<if !$feetactiondefault>>
<<set $feetactiondefault to "feetacceptW">>
<</if>>
<<if !$mouthactiondefault>>
<<set $mouthactiondefault to "mouthacceptW">>
<</if>>
<<if $leftarm is 0>>
你的左臂自由了,<span class="pink">但无法控制自如。</span>
<br>
<<if $leftactiondefault is "leftacceptW">>
| <label><span class="wraith">接受</span> <<radiobutton "$leftaction" "leftacceptW" checked>></label>
<<else>>
| <label><span class="wraith">接受</span> <<radiobutton "$leftaction" "leftacceptW">></label>
<</if>>
<<if $leftactiondefault is "leftresistW">>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$leftaction" "leftresistW" checked>></label>
<<else>>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$leftaction" "leftresistW">></label>
<</if>>
<br>
<<elseif $leftarm is "grappled">>
你的左臂在他们的控制下不由自主地扭动。
<br>
<<set $leftactiondefault to ["leftacceptW","leftstruggleW"].includes($leftactiondefault) ? "leftstruggleW" : "leftstillW">>
<<if $leftactiondefault is "leftstruggleW">>
| <label><span class="wraith">挣扎</span> <<radiobutton "$leftaction" "leftstruggleW" checked>></label>
<<else>>
| <label><span class="wraith">挣扎</span> <<radiobutton "$leftaction" "leftstruggleW">></label>
<</if>>
<<if $leftactiondefault is "leftstillW">>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$leftaction" "leftstillW" checked>></label>
<<else>>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$leftaction" "leftstillW">></label>
<</if>>
<br>
<<elseif $leftarm is "bound">>
你的右臂在他们的掌握下,不由自主地扭动着。
<br>
<</if>>
<<if $rightarm is 0>>
<br>
你的右臂是自由的,<span class="pink">但无法控制自如。</span>
<br>
<<if $rightactiondefault is "rightacceptW">>
| <label><span class="wraith">接受</span> <<radiobutton "$rightaction" "rightacceptW" checked>></label>
<<else>>
| <label><span class="wraith">接受</span> <<radiobutton "$rightaction" "rightacceptW">></label>
<</if>>
<<if $rightactiondefault is "rightresistW">>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$rightaction" "rightresistW" checked>></label>
<<else>>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$rightaction" "rightresistW">></label>
<</if>>
<br>
<<elseif $rightarm is "grappled">>
<br>
你的右臂在他们的掌握下,不由自主地扭动着。
<br>
<<set $rightactiondefault to ["rightacceptW","rightstruggleW"].includes($rightactiondefault) ? "rightstruggleW" : "rightstillW">>
<<if $rightactiondefault is "rightstruggleW">>
| <label><span class="wraith">挣扎</span> <<radiobutton "$rightaction" "rightstruggleW" checked>></label>
<<else>>
| <label><span class="wraith">挣扎</span> <<radiobutton "$rightaction" "rightstruggleW">></label>
<</if>>
<<if $rightactiondefault is "rightstillW">>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$rightaction" "rightstillW" checked>></label>
<<else>>
| <label><span class="brat">将其固定不动</span> <<radiobutton "$rightaction" "rightstillW">></label>
<</if>>
<br>
<<elseif $rightarm is "bound">>
<br>
你的右臂不由自主地在其范围内扭动。
<br>
<</if>>
<<if $feetuse is 0>>
<br>
你的腿自由了,<span class="pink">但是你没有知觉</span>。
<br>
<<if $feetactiondefault is "feetacceptW">>
| <label><span class="wraith">接受</span> <<radiobutton "$feetaction" "feetacceptW" checked>></label>
<<else>>
| <label><span class="wraith">接受</span> <<radiobutton "$feetaction" "feetacceptW">></label>
<</if>>
<<if $feetactiondefault is "feetresistW">>
| <label><span class="brat">让他们保持不动</span> <<radiobutton "$feetaction" "feetresistW" checked>></label>
<<else>>
| <label><span class="brat">让他们保持不动</span> <<radiobutton "$feetaction" "feetresistW">></label>
<</if>>
<br>
<<elseif $feetuse is "bound">>
<br>
你的脚在他们的掌握下,不由自主地扭动着。
<br>
<</if>>
<<if $mouthuse is 0>>
<br>
你的嘴自由了,<span class="pink">但是不熟悉的话从你的嘴里说出来</span>。
<br>
<<if $mouthactiondefault is "mouthacceptW">>
| <label><span class="wraith">接受</span> <<radiobutton "$mouthaction" "mouthacceptW" checked>></label>
<<else>>
| <label><span class="wraith">接受</span> <<radiobutton "$mouthaction" "mouthacceptW">></label>
<</if>>
<<if $mouthactiondefault is "mouthresistW">>
| <label><span class="brat">闭上你的嘴</span> <<radiobutton "$mouthaction" "mouthresistW" checked>></label>
<<else>>
| <label><span class="brat">闭上你的嘴</span> <<radiobutton "$mouthaction" "mouthresistW">></label>
<</if>>
<<elseif $mouthuse is "lefthand" or $mouthuse is "righthand">>
<br>
你的嘴被堵住了,堵住了你心中涌出的话语。
<br>
<<set $mouthactiondefault to ["mouthacceptW","handbiteW"].includes($mouthactiondefault) ? "handbiteW" : "handcloseW">>
<<if $mouthactiondefault is "handbiteW">>
| <label><span class="wraith">咬</span> <<radiobutton "$mouthaction" "handbiteW" checked>></label>
<<else>>
| <label><span class="wraith">咬</span> <<radiobutton "$mouthaction" "handbiteW">></label>
<</if>>
<<if $mouthactiondefault is "handcloseW">>
| <label><span class="brat">闭上你的嘴</span> <<radiobutton "$mouthaction" "handcloseW" checked>></label>
<<else>>
| <label><span class="brat">闭上你的嘴</span> <<radiobutton "$mouthaction" "handcloseW">></label>
<</if>>
<</if>>
<</widget>> | 0 | 0.866662 | 1 | 0.866662 | game-dev | MEDIA | 0.467615 | game-dev | 0.750195 | 1 | 0.750195 |
p1xel8ted/UltrawideFixes | 8,214 | src/MegaManDiveOffline/MegaManDiveOffline/Plugin.cs | namespace MegaManDiveOffline;
[Harmony]
[BepInPlugin(PluginGuid, PluginName, PluginVersion)]
public class Plugin : BasePlugin
{
private const string PluginGuid = "p1xel8ted.megamandiveoffline.ultrawide";
private const string PluginName = "MEGA MAN X DiVE Offline Ultra-Wide";
private const string PluginVersion = "0.1.1";
internal static int SimplifiedWidth => Helpers.GetGcd(SelectedWidth, SelectedHeight).simplifiedWidth;
internal static int SimplifiedHeight => Helpers.GetGcd(SelectedWidth, SelectedHeight).simplifiedHeight;
private static ConfigEntry<string> Resolution { get; set; }
internal static ConfigEntry<FullScreenMode> FullScreenModeConfig { get; private set; }
internal static Resolution SelectedResolution { get; private set; }
internal static int SelectedRefresh => SelectedResolution.refreshRate;
internal static int SelectedWidth => SelectedResolution.width;
internal static int SelectedHeight => SelectedResolution.height;
private static ConfigEntry<bool> RunInBackground { get; set; }
private static ConfigEntry<bool> MuteInBackground { get; set; }
internal static ConfigEntry<int> FieldOfView { get; private set; }
private static ManualLogSource Logger { get; set; }
internal static ConfigEntry<float> CustomScale { get; private set; }
private static ConfigEntry<bool> CorrectFixedUpdateRate { get; set; }
private static ConfigEntry<bool> UseRefreshRateForFixedUpdateRate { get; set; }
private static int MaxRefreshRate => Screen.resolutions.Max(a => a.refreshRate);
public override void Load()
{
var maxRes = $"{Display.main.systemWidth}x{Display.main.systemHeight}@{MaxRefreshRate}Hz";
Logger = Log;
var acceptedResolutions = Screen.resolutions
.GroupBy(a => $"{a.width}x{a.height}")
.Select(a => a.MaxBy(b => b.refreshRate))
.Select(a => $"{a.width}x{a.height}@{a.refreshRate}Hz")
.ToArray();
Resolution = Config.Bind("02. Display", "Resolution", maxRes, new ConfigDescription("Set the resolution of the game", new AcceptableValueList<string>(acceptedResolutions), new ConfigurationManagerAttributes {Order = 100}));
Resolution.SettingChanged += (_, _) =>
{
ApplySettings();
};
FullScreenModeConfig = Config.Bind("02. Display", "Full Screen Mode", FullScreenMode.FullScreenWindow, new ConfigDescription("Set the full screen mode", null, new ConfigurationManagerAttributes {Order = 99}));
FullScreenModeConfig.SettingChanged += (_, _) =>
{
ApplySettings();
};
CustomScale = Config.Bind("03. UI", "Custom UI Scale", 1f, new ConfigDescription("Custom scale for the game's UI.", new AcceptableValueRange<float>(0.5f, 2f), new ConfigurationManagerAttributes {Order = 98}));
FieldOfView = Config.Bind("04. Camera", "Field of View", 50, new ConfigDescription("Increase or decrease the field of view of the camera. Default is 50% increases", new AcceptableValueRange<int>(0, 300), new ConfigurationManagerAttributes {Order = 97}));
FieldOfView.SettingChanged += (_, _) =>
{
ApplyFieldOfView();
};
CorrectFixedUpdateRate = Config.Bind("05. Performance", "Correct Physics Update Rate", true,
new ConfigDescription("Adjusts the physics update rate to minimum amount to reduce camera judder based on your refresh rate. Not all games like this setting being adjusted.", null, new ConfigurationManagerAttributes {Order = 96}));
CorrectFixedUpdateRate.SettingChanged += (_, _) =>
{
UpdateFixedRate();
};
UseRefreshRateForFixedUpdateRate = Config.Bind("05. Performance", "Use Refresh Rate For Physics Update Rate", true,
new ConfigDescription("Sets the physics update rate based on the monitor's refresh rate for smoother gameplay. If you're playing on a potato, this may have performance impacts.", null, new ConfigurationManagerAttributes {Order = 95}));
UseRefreshRateForFixedUpdateRate.SettingChanged += (_, _) =>
{
UpdateFixedRate();
};
RunInBackground = Config.Bind("06. Misc", "Run In Background", true, new ConfigDescription("Allows the game to run even when not in focus.", null, new ConfigurationManagerAttributes {Order = 94}));
RunInBackground.SettingChanged += (_, _) =>
{
Application.runInBackground = RunInBackground.Value;
};
MuteInBackground = Config.Bind("06. Misc", "Mute In Background", false, new ConfigDescription("Mutes the game's audio when it is not in focus.", null, new ConfigurationManagerAttributes {Order = 93}));
MuteInBackground.SettingChanged += (_, _) =>
{
AudioListener.pause = !Application.isFocused && MuteInBackground.Value;
};
Application.focusChanged += (Il2CppSystem.Action<bool>) FocusChanged;
SceneManager.sceneLoaded += (UnityAction<Scene, LoadSceneMode>) SceneManagerOnSceneLoaded;
Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), PluginGuid);
Log.LogInfo($"Plugin {PluginName} is loaded!");
}
private static void FocusChanged(bool focus)
{
AudioListener.pause = !focus && MuteInBackground.Value;
}
private static void SceneManagerOnSceneLoaded(Scene a, LoadSceneMode l)
{
ApplySettings();
UpdateBackgrounds();
}
private static int FindLowestFrameRateMultipleAboveFifty(int originalRate)
{
for (var rate = originalRate / 2; rate > 50; rate--)
{
if (originalRate % rate == 0)
{
return rate;
}
}
return originalRate;
}
private static void UpdateFixedRate()
{
if (SelectedRefresh <= 60)
{
Logger.LogInfo("Refresh rate is 60Hz or lower. Skipping physics update rate adjustment.");
return;
}
if (CorrectFixedUpdateRate.Value)
{
if (UseRefreshRateForFixedUpdateRate.Value)
{
Time.fixedDeltaTime = 1f / SelectedRefresh;
}
else
{
var denominator = FindLowestFrameRateMultipleAboveFifty(SelectedRefresh);
Time.fixedDeltaTime = 1f / denominator;
}
}
else
{
Time.fixedDeltaTime = 1f / 60f; //Game default
}
}
private static void ApplySettings()
{
var res = Resolution.Value.Split('@');
var resSplit = res[0].Split('x');
var width = int.Parse(resSplit[0]);
var height = int.Parse(resSplit[1]);
var refreshRate = int.Parse(res[1].Replace("Hz", ""));
SelectedResolution = new Resolution
{
width = width,
height = height,
refreshRate = refreshRate
};
Application.runInBackground = RunInBackground.Value;
Screen.SetResolution(SelectedWidth, SelectedHeight, FullScreenModeConfig.Value, SelectedRefresh);
Application.targetFrameRate = SelectedRefresh;
UpdateFixedRate();
ApplyFieldOfView();
}
private static void ApplyFieldOfView()
{
var ct = Resources.FindObjectsOfTypeAll(Il2CppType.Of<CameraControl>());
foreach (var c in ct)
{
var cameraControl = c.TryCast<CameraControl>();
if (cameraControl)
{
cameraControl.UpdateCameraFov(cameraControl._defaultFov + cameraControl._defaultFov * (FieldOfView.Value / 100f));
}
}
}
private static void UpdateBackgrounds()
{
var backgroundImages = Resources.FindObjectsOfTypeAll(Il2CppType.Of<Image>());
foreach (var image in backgroundImages)
{
var i = image.TryCast<Image>();
if (!i) continue;
var rect = i.GetComponent<RectTransform>();
if (!rect) continue;
if (Mathf.Approximately(rect.sizeDelta.x, 3000))
{
rect.sizeDelta = new Vector2(SelectedWidth, SelectedHeight);
}
}
}
} | 0 | 0.962456 | 1 | 0.962456 | game-dev | MEDIA | 0.445789 | game-dev | 0.975036 | 1 | 0.975036 |
microsoft/MixedReality-WorldLockingTools-Samples | 6,022 | Advanced/AlignSubScene/Assets/MRTK/SDK/Experimental/Elastic/Scripts/QuaternionElasticSystem.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Runtime.CompilerServices;
using UnityEngine;
[assembly: InternalsVisibleTo("Microsoft.MixedReality.Toolkit.Tests.PlayModeTests")]
namespace Microsoft.MixedReality.Toolkit.Experimental.Physics
{
public class QuaternionElasticSystem : IElasticSystem<Quaternion>
{
private Quaternion currentValue;
private Quaternion currentVelocity;
private QuaternionElasticExtent extent;
private ElasticProperties elasticProperties;
/// <summary>
/// Default constructor; initializes the elastic system with the specified
/// initial value, velocity, extent, and elastic properties.
/// </summary>
public QuaternionElasticSystem(Quaternion initialValue,
Quaternion initialVelocity,
QuaternionElasticExtent extentInfo,
ElasticProperties elasticProperties)
{
currentValue = initialValue;
currentVelocity = initialVelocity;
this.extent = extentInfo;
this.elasticProperties = elasticProperties;
}
/// <inheritdoc/>
public Quaternion ComputeIteration(Quaternion forcingValue, float deltaTime)
{
// If the dot product is negative, we need to negate the forcing
// quaternion so that the force is coherent/wraps correctly.
if (Quaternion.Dot(forcingValue, currentValue) < 0)
{
forcingValue = new Quaternion(-forcingValue.x, -forcingValue.y, -forcingValue.z, -forcingValue.w);
}
// Displacement of the forcing value compared to the current state's value.
Quaternion displacement = Quaternion.Inverse(currentValue) * forcingValue;
// The force applied is an approximation of F=(kx - vd) in 4-space
Quaternion force = Add(Scale(displacement, elasticProperties.HandK), Scale(currentVelocity, -elasticProperties.Drag));
// Euler representation of the current elastic quaternion state.
Vector3 eulers = currentValue.eulerAngles;
foreach (var snapPoint in extent.SnapPoints)
{
// If we are set to repeat the snap points (i.e., tiling them across the sphere),
// we use the nearest integer multiple of the snap point. If it is not repeated,
// we use the snap point directly.
Vector3 nearest = extent.RepeatSnapPoints ? GetNearest(eulers, snapPoint) : snapPoint;
// Convert the nearest point to a quaternion representation.
Quaternion nearestQuat = Quaternion.Euler(nearest.x, nearest.y, nearest.z);
// If the dot product is negative, we need to negate the snap
// quaternion so that the snap force is coherent/wraps correctly.
if (Quaternion.Dot(nearestQuat, currentValue) < 0)
{
nearestQuat = Scale(nearestQuat, -1.0f);
}
// Displacement from the current value to the snap quaternion.
Quaternion snapDisplacement = Quaternion.Inverse(currentValue) * nearestQuat;
// Angle of the snapping displacement, used to calculate the snapping magnitude.
float snapAngle = Quaternion.Angle(currentValue, nearestQuat);
// Strength of the snapping force, function of the snap angle and the configured
// snapping radius.
float snapFactor = ComputeSnapFactor(snapAngle, extent.SnapRadius);
// Accumulate the force from every snap point.
force = Add(force, Scale(snapDisplacement, elasticProperties.SnapK * snapFactor));
}
// Performing Euler integration in 4-space.
// Acceleration = F/m
Quaternion accel = Scale(force, (1 / elasticProperties.Mass));
// v' = v + a * deltaT
currentVelocity = Add(currentVelocity, Scale(accel, deltaTime));
// x' = x + v' * deltaT
currentValue *= Scale(currentVelocity, deltaTime).normalized;
// As the current value is a quaternion, we must renormalize the quaternion
// before using it as a representation of a rotation.
currentValue = currentValue.normalized;
return currentValue;
}
/// <inheritdoc/>
public Quaternion GetCurrentValue() => currentValue;
/// <inheritdoc/>
public Quaternion GetCurrentVelocity() => currentVelocity;
// Find the nearest integer multiple of the specified interval
private Vector3 GetNearest(Vector3 target, Vector3 interval)
{
return new Vector3(GetNearest(target.x, interval.x), GetNearest(target.y, interval.y), GetNearest(target.z, interval.z));
}
// Find the nearest integer multiple of the specified interval
private float GetNearest(float target, float interval)
{
return Mathf.Round(target / interval) * interval;
}
private float ComputeSnapFactor(float angleFromPoint, float radius)
{
// Snap force is calculated by multiplying the "-kx" factor by
// a clamped distance factor. This results in an overall
// hyperbolic profile to the force imparted by the snap point.
return (1.0f - Mathf.Clamp01(Mathf.Abs(angleFromPoint / radius)));
}
// Elementwise quaternion addition.
private Quaternion Add(Quaternion p, Quaternion q)
{
return new Quaternion(p.x + q.x, p.y + q.y, p.z + q.z, p.w + q.w);
}
// Elementwise quaternion scale.
private Quaternion Scale(Quaternion p, float t)
{
return new Quaternion(p.x * t, p.y * t, p.z * t, p.w * t);
}
}
}
| 0 | 0.90624 | 1 | 0.90624 | game-dev | MEDIA | 0.819989 | game-dev,graphics-rendering | 0.908111 | 1 | 0.908111 |
OreCruncher/DynamicSurroundings | 3,539 | src/main/java/org/orecruncher/dsurround/client/handlers/fog/HazeFogRangeCalculator.java | /*
* This file is part of Dynamic Surroundings, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.orecruncher.dsurround.client.handlers.fog;
import javax.annotation.Nonnull;
import org.orecruncher.dsurround.capabilities.dimension.IDimensionInfo;
import org.orecruncher.dsurround.client.handlers.EnvironStateHandler.EnvironState;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Calculates the fog ranges based on player elevation as compared to the
* dimensions cloud height.
*/
@SideOnly(Side.CLIENT)
public class HazeFogRangeCalculator extends VanillaFogRangeCalculator {
protected static final int BAND_OFFSETS = 15;
protected static final int BAND_CORE_SIZE = 10;
protected static final float IMPACT_FAR = 0.6F;
protected static final float IMPACT_NEAR = 0.95F;
protected final FogResult cached = new FogResult();
public HazeFogRangeCalculator() {
}
@Override
@Nonnull
public String getName() {
return "HazeFogRangeCalculator";
}
@Override
@Nonnull
public FogResult calculate(@Nonnull final EntityViewRenderEvent.RenderFogEvent event) {
final IDimensionInfo di = EnvironState.getDimensionInfo();
if (di.hasHaze()) {
final float lowY = di.getCloudHeight() - BAND_OFFSETS;
final float highY = di.getCloudHeight() + BAND_OFFSETS + BAND_CORE_SIZE;
// Calculate the players Y. If it's in the band range calculate the fog
// parameters
final Vec3d eyes = EnvironState.getPlayer().getPositionEyes((float) event.getRenderPartialTicks());
if (eyes.y > lowY && eyes.y < highY) {
final float coreLowY = lowY + BAND_OFFSETS;
final float coreHighY = coreLowY + BAND_CORE_SIZE;
float scaleFar = IMPACT_FAR;
float scaleNear = IMPACT_NEAR;
if (eyes.y < coreLowY) {
final float factor = (float) ((eyes.y - lowY) / BAND_OFFSETS);
scaleFar *= factor;
scaleNear *= factor;
} else if (eyes.y > coreHighY) {
final float factor = (float) ((highY - eyes.y) / BAND_OFFSETS);
scaleFar *= factor;
scaleNear *= factor;
}
final float end = event.getFarPlaneDistance() * (1F - scaleFar);
final float start = event.getFarPlaneDistance() * (1F - scaleNear);
this.cached.set(start, end);
return this.cached;
}
}
this.cached.set(event);
return this.cached;
}
}
| 0 | 0.902465 | 1 | 0.902465 | game-dev | MEDIA | 0.5287 | game-dev,graphics-rendering | 0.940516 | 1 | 0.940516 |
Starlink/starjava | 1,989 | datanode/src/main/uk/ac/starlink/datanode/factory/SimpleDataNodeBuilder.java | package uk.ac.starlink.datanode.factory;
import uk.ac.starlink.datanode.nodes.DataNode;
import uk.ac.starlink.datanode.nodes.NoSuchDataException;
/**
* An abstract DataNodeBuilder providing a template for builders which
* build nodes from instances of a given class. This class doesn't
* do anything clever, it's just a convenience for subclasses.
*/
public abstract class SimpleDataNodeBuilder extends DataNodeBuilder {
private Class argClass;
private String name;
private Class nodeClass;
/**
* Construct a new builder which will turn out DataNodes from
* objects of a given class (or its subclasses).
*
* @param name the name of this builder - this should normally be
* the classname of the DataNodes it will produce
* @param argClass the class on which this node builder will operate
*/
protected SimpleDataNodeBuilder( String name, Class argClass ) {
this.name = name;
this.argClass = argClass;
this.nodeClass = DataNode.class;
}
/**
* Construct a new builder which will turn out DataNode of a given
* class from objects of a given class.
* Just invokes
* <code>SimpleDataNodeBuilder(nodeClass.getName(),argClass)</code>.
*
* @param nodeClass the class of DataNode objects which this builder
* will be building
* @param argClass the class on which this node bulider will operate
*/
protected SimpleDataNodeBuilder( Class nodeClass, Class argClass ) {
this( nodeClass.getName(), argClass );
this.nodeClass = nodeClass;
}
abstract public DataNode buildNode( Object obj ) throws NoSuchDataException;
public Class getNodeClass() {
return nodeClass;
}
public boolean suitable( Class objClass ) {
return argClass.isAssignableFrom( objClass );
}
public String toString() {
return name + "(" + argClass.getName() + ")";
}
}
| 0 | 0.608953 | 1 | 0.608953 | game-dev | MEDIA | 0.246341 | game-dev | 0.604072 | 1 | 0.604072 |
Bigjoos/U-232-V5 | 28,518 | include/geshi/geshi/lsl2.php | <?php
/*************************************************************************************
* lsl2.php
* --------
* Author: William Fry (william.fry@nyu.edu)
* Copyright: (c) 2009 William Fry
* Release Version: 1.0.8.3
* Date Started: 2009/02/04
*
* Linden Scripting Language (LSL2) language file for GeSHi.
*
* Data derived and validated against the following:
* http://wiki.secondlife.com/wiki/LSL_Portal
* http://www.lslwiki.net/lslwiki/wakka.php?wakka=HomePage
* http://rpgstats.com/wiki/index.php?title=Main_Page
*
* CHANGES
* -------
* 2009/02/05 (1.0.0)
* - First Release
*
* TODO (updated 2009/02/05)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi 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.
*
* GeSHi 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 GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array (
'LANG_NAME' => 'LSL2',
'COMMENT_SINGLE' => array(1 => '//'),
'COMMENT_MULTI' => array(),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array('"'),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array( // flow control
'do',
'else',
'for',
'if',
'jump',
'return',
'state',
'while',
),
2 => array( // manifest constants
'ACTIVE',
'AGENT',
'AGENT_ALWAYS_RUN',
'AGENT_ATTACHMENTS',
'AGENT_AWAY',
'AGENT_BUSY',
'AGENT_CROUCHING',
'AGENT_FLYING',
'AGENT_IN_AIR',
'AGENT_MOUSELOOK',
'AGENT_ON_OBJECT',
'AGENT_SCRIPTED',
'AGENT_SITTING',
'AGENT_TYPING',
'AGENT_WALKING',
'ALL_SIDES',
'ANIM_ON',
'ATTACH_BACK',
'ATTACH_BELLY',
'ATTACH_CHEST',
'ATTACH_CHIN',
'ATTACH_HEAD',
'ATTACH_HUD_BOTTOM',
'ATTACH_HUD_BOTTOM_LEFT',
'ATTACH_HUD_BOTTOM_RIGHT',
'ATTACH_HUD_CENTER_1',
'ATTACH_HUD_CENTER_2',
'ATTACH_HUD_TOP_CENTER',
'ATTACH_HUD_TOP_LEFT',
'ATTACH_HUD_TOP_RIGHT',
'ATTACH_LEAR',
'ATTACH_LEYE',
'ATTACH_LFOOT',
'ATTACH_LHAND',
'ATTACH_LHIP',
'ATTACH_LLARM',
'ATTACH_LLLEG',
'ATTACH_LPEC',
'ATTACH_LSHOULDER',
'ATTACH_LUARM',
'ATTACH_LULEG',
'ATTACH_MOUTH',
'ATTACH_NOSE',
'ATTACH_PELVIS',
'ATTACH_REAR',
'ATTACH_REYE',
'ATTACH_RFOOT',
'ATTACH_RHAND',
'ATTACH_RHIP',
'ATTACH_RLARM',
'ATTACH_RLLEG',
'ATTACH_RPEC',
'ATTACH_RSHOULDER',
'ATTACH_RUARM',
'ATTACH_RULEG',
'CAMERA_ACTIVE',
'CAMERA_BEHINDNESS_ANGLE',
'CAMERA_BEHINDNESS_LAG',
'CAMERA_DISTANCE',
'CAMERA_FOCUS',
'CAMERA_FOCUS_LAG',
'CAMERA_FOCUS_LOCKED',
'CAMERA_FOCUS_OFFSET',
'CAMERA_FOCUS_THRESHOLD',
'CAMERA_PITCH',
'CAMERA_POSITION',
'CAMERA_POSITION_LAG',
'CAMERA_POSITION_LOCKED',
'CAMERA_POSITION_THRESHOLD',
'CHANGED_ALLOWED_DROP',
'CHANGED_COLOR',
'CHANGED_INVENTORY',
'CHANGED_LINK',
'CHANGED_OWNER',
'CHANGED_REGION',
'CHANGED_SCALE',
'CHANGED_SHAPE',
'CHANGED_TELEPORT',
'CHANGED_TEXTURE',
'CLICK_ACTION_NONE',
'CLICK_ACTION_OPEN',
'CLICK_ACTION_OPEN_MEDIA',
'CLICK_ACTION_PAY',
'CLICK_ACTION_SIT',
'CLICK_ACTION_TOUCH',
'CONTROL_BACK',
'CONTROL_DOWN',
'CONTROL_FWD',
'CONTROL_LBUTTON',
'CONTROL_LEFT',
'CONTROL_ML_LBUTTON',
'CONTROL_RIGHT',
'CONTROL_ROT_LEFT',
'CONTROL_ROT_RIGHT',
'CONTROL_UP',
'DATA_BORN',
'DATA_NAME',
'DATA_ONLINE',
'DATA_PAYINFO',
'DATA_RATING',
'DATA_SIM_POS',
'DATA_SIM_RATING',
'DATA_SIM_STATUS',
'DEBUG_CHANNEL',
'DEG_TO_RAD',
'EOF',
'FALSE',
'HTTP_BODY_MAXLENGTH',
'HTTP_BODY_TRUNCATED',
'HTTP_METHOD',
'HTTP_MIMETYPE',
'HTTP_VERIFY_CERT',
'INVENTORY_ALL',
'INVENTORY_ANIMATION',
'INVENTORY_BODYPART',
'INVENTORY_CLOTHING',
'INVENTORY_GESTURE',
'INVENTORY_LANDMARK',
'INVENTORY_NONE',
'INVENTORY_NOTECARD',
'INVENTORY_OBJECT',
'INVENTORY_SCRIPT',
'INVENTORY_SOUND',
'INVENTORY_TEXTURE',
'LAND_LEVEL',
'LAND_LOWER',
'LAND_NOISE',
'LAND_RAISE',
'LAND_REVERT',
'LAND_SMOOTH',
'LINK_ALL_CHILDREN',
'LINK_ALL_OTHERS',
'LINK_ROOT',
'LINK_SET',
'LINK_THIS',
'LIST_STAT_GEOMETRIC_MEAN',
'LIST_STAT_MAX',
'LIST_STAT_MEAN',
'LIST_STAT_MEDIAN',
'LIST_STAT_MIN',
'LIST_STAT_NUM_COUNT',
'LIST_STAT_RANGE',
'LIST_STAT_STD_DEV',
'LIST_STAT_SUM',
'LIST_STAT_SUM_SQUARES',
'LOOP',
'MASK_BASE',
'MASK_EVERYONE',
'MASK_GROUP',
'MASK_NEXT',
'MASK_OWNER',
'NULL_KEY',
'OBJECT_CREATOR',
'OBJECT_DESC',
'OBJECT_GROUP',
'OBJECT_NAME',
'OBJECT_OWNER',
'OBJECT_POS',
'OBJECT_ROT',
'OBJECT_UNKNOWN_DETAIL',
'OBJECT_VELOCITY',
'PARCEL_DETAILS_AREA',
'PARCEL_DETAILS_DESC',
'PARCEL_DETAILS_GROUP',
'PARCEL_DETAILS_NAME',
'PARCEL_DETAILS_OWNER',
'PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY',
'PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS',
'PARCEL_FLAG_ALLOW_CREATE_OBJECTS',
'PARCEL_FLAG_ALLOW_DAMAGE',
'PARCEL_FLAG_ALLOW_FLY',
'PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY',
'PARCEL_FLAG_ALLOW_GROUP_SCRIPTS',
'PARCEL_FLAG_ALLOW_LANDMARK',
'PARCEL_FLAG_ALLOW_SCRIPTS',
'PARCEL_FLAG_ALLOW_TERRAFORM',
'PARCEL_FLAG_LOCAL_SOUND_ONLY',
'PARCEL_FLAG_RESTRICT_PUSHOBJECT',
'PARCEL_FLAG_USE_ACCESS_GROUP',
'PARCEL_FLAG_USE_ACCESS_LIST',
'PARCEL_FLAG_USE_BAN_LIST',
'PARCEL_FLAG_USE_LAND_PASS_LIST',
'PARCEL_MEDIA_COMMAND_AGENT',
'PARCEL_MEDIA_COMMAND_AUTO_ALIGN',
'PARCEL_MEDIA_COMMAND_DESC',
'PARCEL_MEDIA_COMMAND_LOOP_SET',
'PARCEL_MEDIA_COMMAND_PAUSE',
'PARCEL_MEDIA_COMMAND_PLAY',
'PARCEL_MEDIA_COMMAND_SIZE',
'PARCEL_MEDIA_COMMAND_STOP',
'PARCEL_MEDIA_COMMAND_TEXTURE',
'PARCEL_MEDIA_COMMAND_TIME',
'PARCEL_MEDIA_COMMAND_TYPE',
'PARCEL_MEDIA_COMMAND_URL',
'PASSIVE',
'PAYMENT_INFO_ON_FILE',
'PAYMENT_INFO_USED',
'PAY_DEFAULT',
'PAY_HIDE',
'PERMISSION_ATTACH',
'PERMISSION_CHANGE_LINKS',
'PERMISSION_CONTROL_CAMERA',
'PERMISSION_DEBIT',
'PERMISSION_TAKE_CONTROLS',
'PERMISSION_TRACK_CAMERA',
'PERMISSION_TRIGGER_ANIMATION',
'PERM_ALL',
'PERM_COPY',
'PERM_MODIFY',
'PERM_MOVE',
'PERM_TRANSFER',
'PI',
'PI_BY_TWO',
'PRIM_BUMP_BARK',
'PRIM_BUMP_BLOBS',
'PRIM_BUMP_BRICKS',
'PRIM_BUMP_BRIGHT',
'PRIM_BUMP_CHECKER',
'PRIM_BUMP_CONCRETE',
'PRIM_BUMP_DARK',
'PRIM_BUMP_DISKS',
'PRIM_BUMP_GRAVEL',
'PRIM_BUMP_LARGETILE',
'PRIM_BUMP_NONE',
'PRIM_BUMP_SHINY',
'PRIM_BUMP_SIDING',
'PRIM_BUMP_STONE',
'PRIM_BUMP_STUCCO',
'PRIM_BUMP_SUCTION',
'PRIM_BUMP_TILE',
'PRIM_BUMP_WEAVE',
'PRIM_BUMP_WOOD',
'PRIM_COLOR',
'PRIM_FULLBRIGHT',
'PRIM_HOLE_CIRCLE',
'PRIM_HOLE_DEFAULT',
'PRIM_HOLE_SQUARE',
'PRIM_HOLE_TRIANGLE',
'PRIM_MATERIAL',
'PRIM_MATERIAL_FLESH',
'PRIM_MATERIAL_GLASS',
'PRIM_MATERIAL_LIGHT',
'PRIM_MATERIAL_METAL',
'PRIM_MATERIAL_PLASTIC',
'PRIM_MATERIAL_RUBBER',
'PRIM_MATERIAL_STONE',
'PRIM_MATERIAL_WOOD',
'PRIM_PHANTOM',
'PRIM_PHYSICS',
'PRIM_POSITION',
'PRIM_ROTATION',
'PRIM_SHINY_HIGH',
'PRIM_SHINY_LOW',
'PRIM_SHINY_MEDIUM',
'PRIM_SHINY_NONE',
'PRIM_SIZE',
'PRIM_TEMP_ON_REZ',
'PRIM_TEXTURE',
'PRIM_TYPE',
'PRIM_TYPE_BOX',
'PRIM_TYPE_CYLINDER',
'PRIM_TYPE_PRISM',
'PRIM_TYPE_RING',
'PRIM_TYPE_SPHERE',
'PRIM_TYPE_TORUS',
'PRIM_TYPE_TUBE',
'PSYS_PART_BOUNCE_MASK',
'PSYS_PART_EMISSIVE_MASK',
'PSYS_PART_END_ALPHA',
'PSYS_PART_END_COLOR',
'PSYS_PART_END_SCALE',
'PSYS_PART_FLAGS',
'PSYS_PART_FOLLOW_SRC_MASK',
'PSYS_PART_FOLLOW_VELOCITY_MASK',
'PSYS_PART_INTERP_COLOR_MASK',
'PSYS_PART_INTERP_SCALE_MASK',
'PSYS_PART_MAX_AGE',
'PSYS_PART_START_ALPHA',
'PSYS_PART_START_COLOR',
'PSYS_PART_START_SCALE',
'PSYS_PART_TARGET_LINEAR_MASK',
'PSYS_PART_TARGET_POS_MASK',
'PSYS_PART_WIND_MASK',
'PSYS_SRC_ACCEL',
'PSYS_SRC_ANGLE_BEGIN',
'PSYS_SRC_ANGLE_END',
'PSYS_SRC_BURST_PART_COUNT',
'PSYS_SRC_BURST_RADIUS',
'PSYS_SRC_BURST_RATE',
'PSYS_SRC_BURST_SPEED_MAX',
'PSYS_SRC_BURST_SPEED_MIN',
'PSYS_SRC_INNERANGLE',
'PSYS_SRC_MAX_AGE',
'PSYS_SRC_OMEGA',
'PSYS_SRC_OUTERANGLE',
'PSYS_SRC_PATTERN',
'PSYS_SRC_PATTERN_ANGLE',
'PSYS_SRC_PATTERN_ANGLE_CONE',
'PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY',
'PSYS_SRC_PATTERN_DROP',
'PSYS_SRC_PATTERN_EXPLODE',
'PSYS_SRC_TARGET_KEY',
'PSYS_SRC_TEXTURE',
'RAD_TO_DEG',
'REMOTE_DATA_CHANNEL',
'REMOTE_DATA_REQUEST',
'SCRIPTED',
'SQRT2',
'STATUS_BLOCK_GRAB',
'STATUS_DIE_AT_EDGE',
'STATUS_PHANTOM',
'STATUS_PHYSICS',
'STATUS_RETURN_AT_EDGE',
'STATUS_ROTATE_X',
'STATUS_ROTATE_Y',
'STATUS_ROTATE_Z',
'STATUS_SANDBOX',
'TRUE',
'TWO_PI',
'VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY',
'VEHICLE_ANGULAR_DEFLECTION_TIMESCALE',
'VEHICLE_ANGULAR_FRICTION_TIMESCALE',
'VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE',
'VEHICLE_ANGULAR_MOTOR_DIRECTION',
'VEHICLE_ANGULAR_MOTOR_TIMESCALE',
'VEHICLE_BANKING_EFFICIENCY',
'VEHICLE_BANKING_MIX',
'VEHICLE_BANKING_TIMESCALE',
'VEHICLE_BUOYANCY',
'VEHICLE_FLAG_CAMERA_DECOUPLED',
'VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT',
'VEHICLE_FLAG_HOVER_TERRAIN_ONLY',
'VEHICLE_FLAG_HOVER_UP_ONLY',
'VEHICLE_FLAG_HOVER_WATER_ONLY',
'VEHICLE_FLAG_LIMIT_MOTOR_UP',
'VEHICLE_FLAG_LIMIT_ROLL_ONLY',
'VEHICLE_FLAG_MOUSELOOK_BANK',
'VEHICLE_FLAG_MOUSELOOK_STEER',
'VEHICLE_FLAG_NO_DEFLECTION_UP',
'VEHICLE_HOVER_EFFICIENCY',
'VEHICLE_HOVER_HEIGHT',
'VEHICLE_HOVER_TIMESCALE',
'VEHICLE_LINEAR_DEFLECTION_EFFICIENCY',
'VEHICLE_LINEAR_DEFLECTION_TIMESCALE',
'VEHICLE_LINEAR_FRICTION_TIMESCALE',
'VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE',
'VEHICLE_LINEAR_MOTOR_DIRECTION',
'VEHICLE_LINEAR_MOTOR_OFFSET',
'VEHICLE_LINEAR_MOTOR_TIMESCALE',
'VEHICLE_REFERENCE_FRAME',
'VEHICLE_TYPE_AIRPLANE',
'VEHICLE_TYPE_BALLOON',
'VEHICLE_TYPE_BOAT',
'VEHICLE_TYPE_CAR',
'VEHICLE_TYPE_NONE',
'VEHICLE_TYPE_SLED',
'VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY',
'VEHICLE_VERTICAL_ATTRACTION_TIMESCALE',
'ZERO_ROTATION',
'ZERO_VECTOR',
),
3 => array( // handlers
'at_rot_target',
'at_target',
'attached',
'changed',
'collision',
'collision_end',
'collision_start',
'control',
'dataserver',
'email',
'http_response',
'land_collision',
'land_collision_end',
'land_collision_start',
'link_message',
'listen',
'money',
'moving_end',
'moving_start',
'no_sensor',
'not_at_rot_target',
'not_at_target',
'object_rez',
'on_rez',
'remote_data',
'run_time_permissions',
'sensor',
'state_entry',
'state_exit',
'timer',
'touch',
'touch_end',
'touch_start',
),
4 => array( // data types
'float',
'integer',
'key',
'list',
'rotation',
'string',
'vector',
),
5 => array( // library
'default',
'llAbs',
'llAcos',
'llAddToLandBanList',
'llAddToLandPassList',
'llAdjustSoundVolume',
'llAllowInventoryDrop',
'llAngleBetween',
'llApplyImpulse',
'llApplyRotationalImpulse',
'llAsin',
'llAtan2',
'llAttachToAvatar',
'llAvatarOnSitTarget',
'llAxes2Rot',
'llAxisAngle2Rot',
'llBase64ToInteger',
'llBase64ToString',
'llBreakAllLinks',
'llBreakLink',
'llCeil',
'llClearCameraParams',
'llCloseRemoteDataChannel',
'llCloud',
'llCollisionFilter',
'llCollisionSound',
'llCollisionSprite',
'llCos',
'llCreateLink',
'llCSV2List',
'llDeleteSubList',
'llDeleteSubString',
'llDetachFromAvatar',
'llDetectedGrab',
'llDetectedGroup',
'llDetectedKey',
'llDetectedLinkNumber',
'llDetectedName',
'llDetectedOwner',
'llDetectedPos',
'llDetectedRot',
'llDetectedTouchBinormal',
'llDetectedTouchFace',
'llDetectedTouchNormal',
'llDetectedTouchPos',
'llDetectedTouchST',
'llDetectedTouchUV',
'llDetectedType',
'llDetectedVel',
'llDialog',
'llDie',
'llDumpList2String',
'llEdgeOfWorld',
'llEjectFromLand',
'llEmail',
'llEscapeURL',
'llEuler2Rot',
'llFabs',
'llFloor',
'llForceMouselook',
'llFrand',
'llGetAccel',
'llGetAgentInfo',
'llGetAgentLanguage',
'llGetAgentSize',
'llGetAlpha',
'llGetAndResetTime',
'llGetAnimation',
'llGetAnimationList',
'llGetAttached',
'llGetBoundingBox',
'llGetCameraPos',
'llGetCameraRot',
'llGetCenterOfMass',
'llGetColor',
'llGetCreator',
'llGetDate',
'llGetEnergy',
'llGetForce',
'llGetFreeMemory',
'llGetGeometricCenter',
'llGetGMTclock',
'llGetInventoryCreator',
'llGetInventoryKey',
'llGetInventoryName',
'llGetInventoryNumber',
'llGetInventoryPermMask',
'llGetInventoryType',
'llGetKey',
'llGetLandOwnerAt',
'llGetLinkKey',
'llGetLinkName',
'llGetLinkNumber',
'llGetListEntryType',
'llGetListLength',
'llGetLocalPos',
'llGetLocalRot',
'llGetMass',
'llGetNextEmail',
'llGetNotecardLine',
'llGetNumberOfNotecardLines',
'llGetNumberOfPrims',
'llGetNumberOfSides',
'llGetObjectDesc',
'llGetObjectDetails',
'llGetObjectMass',
'llGetObjectName',
'llGetObjectPermMask',
'llGetObjectPrimCount',
'llGetOmega',
'llGetOwner',
'llGetOwnerKey',
'llGetParcelDetails',
'llGetParcelFlags',
'llGetParcelMaxPrims',
'llGetParcelPrimCount',
'llGetParcelPrimOwners',
'llGetPermissions',
'llGetPermissionsKey',
'llGetPos',
'llGetPrimitiveParams',
'llGetRegionAgentCount',
'llGetRegionCorner',
'llGetRegionFlags',
'llGetRegionFPS',
'llGetRegionName',
'llGetRegionTimeDilation',
'llGetRootPosition',
'llGetRootRotation',
'llGetRot',
'llGetScale',
'llGetScriptName',
'llGetScriptState',
'llGetSimulatorHostname',
'llGetStartParameter',
'llGetStatus',
'llGetSubString',
'llGetSunDirection',
'llGetTexture',
'llGetTextureOffset',
'llGetTextureRot',
'llGetTextureScale',
'llGetTime',
'llGetTimeOfDay',
'llGetTimestamp',
'llGetTorque',
'llGetUnixTime',
'llGetVel',
'llGetWallclock',
'llGiveInventory',
'llGiveInventoryList',
'llGiveMoney',
'llGround',
'llGroundContour',
'llGroundNormal',
'llGroundRepel',
'llGroundSlope',
'llHTTPRequest',
'llInsertString',
'llInstantMessage',
'llIntegerToBase64',
'llKey2Name',
'llList2CSV',
'llList2Float',
'llList2Integer',
'llList2Key',
'llList2List',
'llList2ListStrided',
'llList2Rot',
'llList2String',
'llList2Vector',
'llListen',
'llListenControl',
'llListenRemove',
'llListFindList',
'llListInsertList',
'llListRandomize',
'llListReplaceList',
'llListSort',
'llListStatistics',
'llLoadURL',
'llLog',
'llLog10',
'llLookAt',
'llLoopSound',
'llLoopSoundMaster',
'llLoopSoundSlave',
'llMapDestination',
'llMD5String',
'llMessageLinked',
'llMinEventDelay',
'llModifyLand',
'llModPow',
'llMoveToTarget',
'llOffsetTexture',
'llOpenRemoteDataChannel',
'llOverMyLand',
'llOwnerSay',
'llParcelMediaCommandList',
'llParcelMediaQuery',
'llParseString2List',
'llParseStringKeepNulls',
'llParticleSystem',
'llPassCollisions',
'llPassTouches',
'llPlaySound',
'llPlaySoundSlave',
'llPow',
'llPreloadSound',
'llPushObject',
'llRegionSay',
'llReleaseControls',
'llRemoteDataReply',
'llRemoteDataSetRegion',
'llRemoteLoadScriptPin',
'llRemoveFromLandBanList',
'llRemoveFromLandPassList',
'llRemoveInventory',
'llRemoveVehicleFlags',
'llRequestAgentData',
'llRequestInventoryData',
'llRequestPermissions',
'llRequestSimulatorData',
'llResetLandBanList',
'llResetLandPassList',
'llResetOtherScript',
'llResetScript',
'llResetTime',
'llRezAtRoot',
'llRezObject',
'llRot2Angle',
'llRot2Axis',
'llRot2Euler',
'llRot2Fwd',
'llRot2Left',
'llRot2Up',
'llRotateTexture',
'llRotBetween',
'llRotLookAt',
'llRotTarget',
'llRotTargetRemove',
'llRound',
'llSameGroup',
'llSay',
'llScaleTexture',
'llScriptDanger',
'llSendRemoteData',
'llSensor',
'llSensorRemove',
'llSensorRepeat',
'llSetAlpha',
'llSetBuoyancy',
'llSetCameraAtOffset',
'llSetCameraEyeOffset',
'llSetCameraParams',
'llSetClickAction',
'llSetColor',
'llSetDamage',
'llSetForce',
'llSetForceAndTorque',
'llSetHoverHeight',
'llSetLinkAlpha',
'llSetLinkColor',
'llSetLinkPrimitiveParams',
'llSetLinkTexture',
'llSetLocalRot',
'llSetObjectDesc',
'llSetObjectName',
'llSetParcelMusicURL',
'llSetPayPrice',
'llSetPos',
'llSetPrimitiveParams',
'llSetRemoteScriptAccessPin',
'llSetRot',
'llSetScale',
'llSetScriptState',
'llSetSitText',
'llSetSoundQueueing',
'llSetSoundRadius',
'llSetStatus',
'llSetText',
'llSetTexture',
'llSetTextureAnim',
'llSetTimerEvent',
'llSetTorque',
'llSetTouchText',
'llSetVehicleFlags',
'llSetVehicleFloatParam',
'llSetVehicleRotationParam',
'llSetVehicleType',
'llSetVehicleVectorParam',
'llSHA1String',
'llShout',
'llSin',
'llSitTarget',
'llSleep',
'llSqrt',
'llStartAnimation',
'llStopAnimation',
'llStopHover',
'llStopLookAt',
'llStopMoveToTarget',
'llStopSound',
'llStringLength',
'llStringToBase64',
'llStringTrim',
'llSubStringIndex',
'llTakeControls',
'llTan',
'llTarget',
'llTargetOmega',
'llTargetRemove',
'llTeleportAgentHome',
'llToLower',
'llToUpper',
'llTriggerSound',
'llTriggerSoundLimited',
'llUnescapeURL',
'llUnSit',
'llVecDist',
'llVecMag',
'llVecNorm',
'llVolumeDetect',
'llWater',
'llWhisper',
'llWind',
'llXorBase64StringsCorrect',
),
6 => array( // deprecated
'llMakeExplosion',
'llMakeFire',
'llMakeFountain',
'llMakeSmoke',
'llSound',
'llSoundPreload',
'llXorBase64Strings',
),
7 => array( // unimplemented
'llPointAt',
'llRefreshPrimURL',
'llReleaseCamera',
'llRemoteLoadScript',
'llSetPrimURL',
'llStopPointAt',
'llTakeCamera',
'llTextBox',
),
8 => array( // God mode
'llGodLikeRezObject',
'llSetInventoryPermMask',
'llSetObjectPermMask',
),
),
'SYMBOLS' => array(
'{', '}', '(', ')', '[', ']',
'=', '+', '-', '*', '/',
'+=', '-=', '*=', '/=', '++', '--',
'!', '%', '&', '|', '&&', '||',
'==', '!=', '<', '>', '<=', '>=',
'~', '<<', '>>', '^', ':',
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => true,
1 => true,
2 => true,
3 => true,
4 => true,
5 => true,
6 => true,
7 => true,
8 => true,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #0000ff;',
2 => 'color: #000080;',
3 => 'color: #008080;',
4 => 'color: #228b22;',
5 => 'color: #b22222;',
6 => 'color: #8b0000; background-color: #ffff00;',
7 => 'color: #8b0000; background-color: #fa8072;',
8 => 'color: #000000; background-color: #ba55d3;',
),
'COMMENTS' => array(
1 => 'color: #ff7f50; font-style: italic;',
),
'ESCAPE_CHAR' => array(
0 => 'color: #000099;'
),
'BRACKETS' => array(
0 => 'color: #000000;'
),
'STRINGS' => array(
0 => 'color: #006400;'
),
'NUMBERS' => array(
0 => 'color: #000000;'
),
'METHODS' => array(
),
'SYMBOLS' => array(
0 => 'color: #000000;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
)
),
'URLS' => array(
1 => '',
2 => '',
3 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
4 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
5 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
6 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
7 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
8 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
),
'OOLANG' => false,
'OBJECT_SPLITTERS' => array(),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
)
);
?> | 0 | 0.778585 | 1 | 0.778585 | game-dev | MEDIA | 0.213734 | game-dev | 0.715332 | 1 | 0.715332 |
ChanceSD/PvPManager | 10,015 | pvpmanager/src/main/java/me/chancesd/pvpmanager/utils/CombatUtils.java | package me.chancesd.pvpmanager.utils;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.CommandException;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.entity.EntityCombustByEntityEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import org.bukkit.projectiles.ProjectileSource;
import org.jetbrains.annotations.NotNull;
import me.chancesd.pvpmanager.setting.Conf;
import me.chancesd.pvpmanager.PvPManager;
import me.chancesd.pvpmanager.integration.hook.placeholderapi.PlaceholderProcessor;
import me.chancesd.sdutils.scheduler.ScheduleUtils;
import me.chancesd.sdutils.utils.Log;
import me.chancesd.sdutils.utils.MCVersion;
import me.chancesd.sdutils.utils.ReflectionUtil;
import me.chancesd.sdutils.utils.ChatUtils;
public final class CombatUtils {
private static final DecimalFormat decimalFormat = new DecimalFormat();
private static PlaceholderProcessor cachedPlaceholderProcessor;
private CombatUtils() {
}
static {
decimalFormat.setMaximumFractionDigits(2);
}
public static String formatTo2Digits(final double value) {
return decimalFormat.format(value);
}
public static boolean hasTimePassed(final long toggleTime, final int cooldown) {
return hasTimePassedMs(toggleTime, cooldown * 1000L);
}
public static boolean hasTimePassedMs(final long toggleTime, final long cooldown) {
return System.currentTimeMillis() - toggleTime >= cooldown;
}
public static int getTimeLeft(final long startTime, final int time) {
return (int) (getTimeLeftMs(startTime, time * 1000L) / 1000);
}
public static long getTimeLeftMs(final long startTime, final long time) {
return startTime + time - System.currentTimeMillis();
}
public static void executeCommands(final List<String> commands, final Player player, final String playerName, final String victim) {
if (commands.isEmpty())
return;
for (final String command : commands) {
try {
@SuppressWarnings("deprecation")
final String preparedCommand = command.replace("{player}", playerName).replace("{victim}", victim)
.replace("{item}", getItemDisplay(player.getItemInHand()));
if (preparedCommand.toLowerCase().startsWith("!console")) {
ScheduleUtils.executeConsoleCommand(preparedCommand.substring(9));
} else if (preparedCommand.toLowerCase().startsWith("!player")) {
player.performCommand(preparedCommand.substring(8));
} else {
ScheduleUtils.executeConsoleCommand(preparedCommand);
}
} catch (final CommandException e) {
Log.warning("Error executing command: \"" + command + "\" for player: " + playerName);
Log.warning("This error comes from the command and it's respective plugin below:");
Log.warning(e.getMessage(), e);
}
}
}
public static void executeCommands(final List<String> commands, final Player player, final String playerName) {
executeCommands(commands, player, playerName, "");
}
@SuppressWarnings("null")
private static String getItemDisplay(final ItemStack item) {
if (item.hasItemMeta()) {
final ItemMeta itemMeta = item.getItemMeta();
if (itemMeta.hasDisplayName())
return itemMeta.getDisplayName();
if (MCVersion.isAtLeast(MCVersion.V1_20_5) && itemMeta.hasItemName())
return itemMeta.getItemName();
}
return item.getType().name();
}
public static final boolean isPvP(final EntityDamageByEntityEvent event) {
final Entity attacker = event.getDamager();
final Entity defender = event.getEntity();
if (!(defender instanceof Player))
return false;
if (attacker instanceof Player)
return isValidPvPAttack(attacker, defender);
if (attacker instanceof Projectile || MCVersion.isAtLeast(MCVersion.V1_9) && attacker instanceof AreaEffectCloud) {
final ProjectileSource projSource = getSource(attacker);
if (projSource instanceof Player) {
final Entity shooter = (Entity) projSource;
if (isValidPvPAttack(shooter, defender))
return shouldCountDamage(event);
}
}
if (attacker instanceof final TNTPrimed tnt) {
final Entity tntAttacker = tnt.getSource();
if (tntAttacker instanceof Player && isValidPvPAttack(tntAttacker, defender)) {
return true;
}
}
return false;
}
private static boolean isValidPvPAttack(final Entity attacker, final Entity defender) {
return Conf.SELF_TAG.asBool() || !defender.equals(attacker);
}
private static boolean shouldCountDamage(final EntityDamageByEntityEvent event) {
return !Conf.IGNORE_NO_DMG_HITS.asBool() || event.getDamage() != 0;
}
public static final boolean isPvP(final EntityCombustByEntityEvent event) {
final Entity attacker = event.getCombuster();
final Entity defender = event.getEntity();
if (!(defender instanceof Player))
return false;
if (attacker instanceof Player)
return true;
if (attacker instanceof final Projectile projectile) {
final ProjectileSource projSource = projectile.getShooter();
if (projSource instanceof Player) {
final Entity shooter = (Entity) projSource;
return isValidPvPAttack(shooter, defender);
}
}
return false;
}
public static final boolean isNPC(final Entity entity) {
return entity.hasMetadata("NPC");
}
public static boolean canFly(final Player p) {
return p.isFlying() || p.getAllowFlight();
}
@SuppressWarnings("null")
public static void checkGlide(final Player p) {
if (!p.isGliding())
return;
final Location playerLocation = p.getLocation();
p.setGliding(false);
ScheduleUtils.teleport(p, playerLocation);
p.setFallDistance(-200);
if (!Conf.PUSHBACK_REMOVE_ELYTRA.asBool())
return;
final ItemStack chestplate = p.getInventory().getChestplate();
if (chestplate == null || chestplate.getType() != Material.ELYTRA)
return;
p.getInventory().setChestplate(null);
final Map<Integer, ItemStack> item = p.getInventory().addItem(chestplate);
if (!item.isEmpty())
p.getWorld().dropItemNaturally(playerLocation, item.values().stream().findFirst().orElse(chestplate));
}
@SuppressWarnings("null")
public static void fakeItemStackDrop(final Player player, final ItemStack[] inventory) {
final Location playerLocation = player.getLocation();
final World playerWorld = player.getWorld();
for (final ItemStack itemstack : inventory) {
if (itemstack != null && !itemstack.getType().equals(Material.AIR)) {
playerWorld.dropItemNaturally(playerLocation, itemstack);
}
}
}
public static boolean isOnline(@NotNull final String name) {
return Bukkit.getPlayer(name) != null;
}
public static boolean isOnline(@NotNull final UUID uuid) {
return Bukkit.getPlayer(uuid) != null;
}
public static boolean isReal(@NotNull final UUID id) {
return Bukkit.getPlayer(id) != null;
}
public static boolean isWorldExcluded(final String worldName) {
return Conf.WORLD_EXCLUSIONS.asSet().contains(worldName);
}
public static boolean hasHarmfulPotion(final AreaEffectCloud areaCloud) {
if (MCVersion.isAtLeast(MCVersion.V1_20_2)) {
final PotionType basePotionType = areaCloud.getBasePotionType();
if (basePotionType == null)
return false;
final List<PotionEffect> potionTypes = basePotionType.getPotionEffects();
return !potionTypes.isEmpty() && potionTypes.stream().anyMatch(p -> isHarmfulPotion(p.getType()));
}
PotionEffectType potionEffectType = null;
try {
potionEffectType = (PotionEffectType) ReflectionUtil.invokeMethods(areaCloud, "getBasePotionData", "getType", "getEffectType");
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
Log.severe("Error getting potion type of lingering potion", e);
}
return potionEffectType != null && isHarmfulPotion(potionEffectType);
}
@SuppressWarnings("deprecation")
public static boolean isHarmfulPotion(final PotionEffectType type) {
return Conf.HARMFUL_POTIONS.asSet().contains(type.getName());
}
public static boolean recursiveContainsCommand(final String[] givenCommand, final List<String> list) {
boolean contains = false;
for (int i = 0; i < givenCommand.length; i++) {
final StringBuilder args = new StringBuilder(givenCommand[0]);
for (int j = 1; j <= i; j++) {
args.append(" ").append(givenCommand[j]);
}
if (list.contains(args.toString().toLowerCase())) {
contains = true;
break;
}
}
return contains;
}
public static String truncateString(final String text, final int size) {
return text.substring(0, Math.min(text.length(), size));
}
/**
* Process placeholders in a message, combining PlaceholderAPI support with PvPManager fallback
*
* @param player The player to get placeholder values for
* @param message The message containing placeholders
* @return The message with placeholders replaced
*/
public static String processPlaceholders(final Player player, final String message) {
if (message == null) {
return message;
}
// Use ChatUtils with PvPManager fallback for when PlaceholderAPI is disabled
return ChatUtils.setPlaceholders(player, message, (p, msg) -> {
if (cachedPlaceholderProcessor == null) {
cachedPlaceholderProcessor = new PlaceholderProcessor(PvPManager.getInstance());
}
return cachedPlaceholderProcessor.replacePlaceholders(p, msg);
});
}
private static ProjectileSource getSource(final Entity entity) {
if (entity instanceof final Projectile projectile)
return projectile.getShooter();
else
return ((AreaEffectCloud) entity).getSource();
}
}
| 0 | 0.948528 | 1 | 0.948528 | game-dev | MEDIA | 0.985488 | game-dev | 0.992883 | 1 | 0.992883 |
mangosthree/server | 5,613 | src/game/OutdoorPvP/OutdoorPvPMgr.cpp | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu>
*
* 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "OutdoorPvPMgr.h"
#include "Policies/Singleton.h"
#include "OutdoorPvP.h"
#include "World.h"
#include "Log.h"
#include "OutdoorPvPEP.h"
#include "OutdoorPvPGH.h"
#include "OutdoorPvPHP.h"
#include "OutdoorPvPNA.h"
#include "OutdoorPvPSI.h"
#include "OutdoorPvPTF.h"
#include "OutdoorPvPZM.h"
#include "DisableMgr.h"
INSTANTIATE_SINGLETON_1(OutdoorPvPMgr);
OutdoorPvPMgr::OutdoorPvPMgr()
{
m_updateTimer.SetInterval(TIMER_OPVP_MGR_UPDATE);
memset(&m_scripts, 0, sizeof(m_scripts));
}
OutdoorPvPMgr::~OutdoorPvPMgr()
{
for (uint8 i = 0; i < MAX_OPVP_ID; ++i)
{
delete m_scripts[i];
}
}
#define LOAD_OPVP_ZONE(a) \
if (sWorld.getConfig(CONFIG_BOOL_OUTDOORPVP_##a##_ENABLED) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_OUTDOORPVP, OPVP_ID_##a)) \
{ \
m_scripts[OPVP_ID_##a] = new OutdoorPvP##a(); \
++counter; \
}
/**
Function which loads all outdoor pvp scripts
*/
void OutdoorPvPMgr::InitOutdoorPvP()
{
uint8 counter = 0;
LOAD_OPVP_ZONE(SI);
LOAD_OPVP_ZONE(EP);
LOAD_OPVP_ZONE(HP);
LOAD_OPVP_ZONE(ZM);
LOAD_OPVP_ZONE(TF);
LOAD_OPVP_ZONE(NA);
LOAD_OPVP_ZONE(GH);
sLog.outString();
sLog.outString(">> Loaded %u Outdoor PvP zones", counter);
}
OutdoorPvP* OutdoorPvPMgr::GetScript(uint32 zoneId)
{
switch (zoneId)
{
case ZONE_ID_SILITHUS:
return m_scripts[OPVP_ID_SI];
case ZONE_ID_EASTERN_PLAGUELANDS:
return m_scripts[OPVP_ID_EP];
case ZONE_ID_HELLFIRE_PENINSULA:
return m_scripts[OPVP_ID_HP];
case ZONE_ID_ZANGARMARSH:
return m_scripts[OPVP_ID_ZM];
case ZONE_ID_TEROKKAR_FOREST:
return m_scripts[OPVP_ID_TF];
case ZONE_ID_NAGRAND:
return m_scripts[OPVP_ID_NA];
case ZONE_ID_GRIZZLY_HILLS:
return m_scripts[OPVP_ID_GH];
default:
return NULL;
}
}
OutdoorPvP* OutdoorPvPMgr::GetScriptOfAffectedZone(uint32 zoneId)
{
switch (zoneId)
{
case ZONE_ID_TEMPLE_OF_AQ:
case ZONE_ID_RUINS_OF_AQ:
case ZONE_ID_GATES_OF_AQ:
return m_scripts[OPVP_ID_SI];
case ZONE_ID_STRATHOLME:
case ZONE_ID_SCHOLOMANCE:
return m_scripts[OPVP_ID_EP];
case ZONE_ID_HELLFIRE_RAMPARTS:
case ZONE_ID_HELLFIRE_CITADEL:
case ZONE_ID_BLOOD_FURNACE:
case ZONE_ID_SHATTERED_HALLS:
case ZONE_ID_MAGTHERIDON_LAIR:
return m_scripts[OPVP_ID_HP];
case ZONE_ID_SERPENTSHRINE_CAVERN:
case ZONE_ID_STREAMVAULT:
case ZONE_ID_UNDERBOG:
case ZONE_ID_SLAVE_PENS:
return m_scripts[OPVP_ID_ZM];
case ZONE_ID_SHADOW_LABYRINTH:
case ZONE_ID_AUCHENAI_CRYPTS:
case ZONE_ID_SETHEKK_HALLS:
case ZONE_ID_MANA_TOMBS:
return m_scripts[OPVP_ID_TF];
default:
return NULL;
}
}
/**
Function that handles the players which enters a specific zone
@param player to be handled in the event
@param zone id used for the current outdoor pvp script
*/
void OutdoorPvPMgr::HandlePlayerEnterZone(Player* player, uint32 zoneId)
{
if (OutdoorPvP* script = GetScript(zoneId))
{
script->HandlePlayerEnterZone(player, true);
}
else if (OutdoorPvP* affectedScript = GetScriptOfAffectedZone(zoneId))
{
affectedScript->HandlePlayerEnterZone(player, false);
}
}
/**
Function that handles the player who leaves a specific zone
@param player to be handled in the event
@param zone id used for the current outdoor pvp script
*/
void OutdoorPvPMgr::HandlePlayerLeaveZone(Player* player, uint32 zoneId)
{
// teleport: called once from Player::CleanupsBeforeDelete, once from Player::UpdateZone
if (OutdoorPvP* script = GetScript(zoneId))
{
script->HandlePlayerLeaveZone(player, true);
}
else if (OutdoorPvP* affectedScript = GetScriptOfAffectedZone(zoneId))
{
affectedScript->HandlePlayerLeaveZone(player, false);
}
}
void OutdoorPvPMgr::Update(uint32 diff)
{
m_updateTimer.Update(diff);
if (!m_updateTimer.Passed())
{
return;
}
for (uint8 i = 0; i < MAX_OPVP_ID; ++i)
if (m_scripts[i])
{
m_scripts[i]->Update(m_updateTimer.GetCurrent());
}
m_updateTimer.Reset();
}
| 0 | 0.997914 | 1 | 0.997914 | game-dev | MEDIA | 0.934558 | game-dev | 0.984304 | 1 | 0.984304 |
sinkillerj/ProjectE | 1,238 | src/api/java/moze_intel/projecte/api/world_transmutation/IWorldTransmutation.java | package moze_intel.projecte.api.world_transmutation;
import net.minecraft.core.Holder;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public sealed interface IWorldTransmutation extends IWorldTransmutationFunction permits SimpleWorldTransmutation, WorldTransmutation {
/**
* Gets the holder for the block that the origin is for. Used for grouping transmutations in order to prioritize state specific ones.
*/
Holder<Block> origin();
/**
* {@return whether this world transmutation has an alternate output when sneaking}
*/
boolean hasAlternate();
/**
* {@inheritDoc}
*
* @return The resulting state, or {@code null} if {@link #canTransmute(BlockState)} returns {@code false} for the input state.
*/
@Nullable
@Override
BlockState result(@NotNull BlockState state, boolean isSneaking);
/**
* Checks whether this world transmutation can be applied to a given block state.
*
* @param state Input state to try and match.
*
* @return {@code true} if this world transmutation is valid for the given state.
*/
boolean canTransmute(@NotNull BlockState state);
} | 0 | 0.820632 | 1 | 0.820632 | game-dev | MEDIA | 0.906686 | game-dev | 0.804457 | 1 | 0.804457 |
Athlaeos/ValhallaMMO | 18,817 | v1_19_R1/src/main/java/me/athlaeos/valhallammo/nms/NMS_v1_19_R1.java | package me.athlaeos.valhallammo.nms;
import io.netty.channel.Channel;
import me.athlaeos.valhallammo.block.DigPacketInfo;
import me.athlaeos.valhallammo.dom.EquippableWrapper;
import me.athlaeos.valhallammo.dom.Pair;
import me.athlaeos.valhallammo.dom.Structures;
import me.athlaeos.valhallammo.item.ItemBuilder;
import me.athlaeos.valhallammo.version.AttributeMappings;
import me.athlaeos.valhallammo.version.EnchantmentMappings;
import me.athlaeos.valhallammo.utility.ItemUtils;
import me.athlaeos.valhallammo.utility.Utils;
import me.athlaeos.valhallammo.version.PotionEffectMappings;
import net.md_5.bungee.api.chat.BaseComponent;
import net.minecraft.core.BlockPos;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.protocol.game.ClientboundBlockDestructionPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.craftbukkit.v1_19_R1.CraftServer;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R1.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_19_R1.generator.strucutre.CraftStructure;
import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import java.lang.reflect.Field;
import java.util.*;
public final class NMS_v1_19_R1 implements NMS {
@Override
public void forceAttack(Player player, LivingEntity victim) {
((CraftPlayer) player).getHandle().attack(((CraftEntity) victim).getHandle());
}
@Override
public Channel channel(Player p) {
return ((CraftPlayer) p).getHandle().connection.connection.channel;
}
@Override
public Pair<Location, Structures> getNearestStructure(World world, Location location, Map<Structures, Integer> structuresToFind){
Collection<Pair<Integer, Integer>> chunksToScan = new HashSet<>();
int cX = location.getChunk().getX();
int cZ = location.getChunk().getZ();
int maxRadius = Collections.max(structuresToFind.values());
for (int x = cX - maxRadius; x <= cX + maxRadius; x++){
for (int z = cZ - maxRadius; z <= cZ + maxRadius; z++){
chunksToScan.add(new Pair<>(x, z));
}
}
Pair<Location, Structures> found = null;
int closest = Integer.MAX_VALUE;
CraftServer server = (CraftServer) Bukkit.getServer();
RegistryAccess.Frozen access = server.getServer().registryAccess();
for (Pair<Integer, Integer> chunk : chunksToScan){
Map<Structure, StructureStart> structures = ((CraftWorld) world).getHandle()
.getChunk(chunk.getOne(), chunk.getTwo(), ChunkStatus.STRUCTURE_REFERENCES).getAllStarts();
for (Structure s : structures.keySet()){
Structures structure = Structures.fromStructure(CraftStructure.minecraftToBukkit(s, access));
if (structure == null) continue;
StructureStart start = structures.get(s);
int distance = Utils.getManhattanDistance(location.getChunk().getX(), location.getChunk().getZ(), chunk.getOne(), chunk.getTwo());
if (!structuresToFind.containsKey(structure)) continue;
int maxDistance = structuresToFind.get(structure);
if (distance > maxDistance || distance > closest) continue;
closest = distance;
BlockPos pos = start.getBoundingBox().getCenter();
Location loc = new Location(location.getWorld(), pos.getX(), pos.getY(), pos.getZ());
found = new Pair<>(loc, structure);
}
}
return found;
}
@Override
public DigPacketInfo readDiggingPacket(Player p, Object packet) {
if (!(packet instanceof ServerboundPlayerActionPacket digPacket)) return null;
BlockPos pos = digPacket.getPos();
return new DigPacketInfo(p, pos.getX(), pos.getY(), pos.getZ(), DigPacketInfo.fromName(digPacket.getAction().name()));
}
@Override
public void blockBreakAnimation(Player p, org.bukkit.block.Block b, int id, int stage) {
ServerPlayer entityPlayer = ((CraftPlayer) p).getHandle();
ServerGamePacketListenerImpl playerConnection = entityPlayer.connection;
BlockPos blockPosition = new BlockPos(b.getX(), b.getY(), b.getZ());
playerConnection.send(new ClientboundBlockDestructionPacket(id, blockPosition, stage));
}
@Override
public void blockParticleAnimation(org.bukkit.block.Block b) {
b.getWorld().spawnParticle(org.bukkit.Particle.BLOCK_CRACK, b.getLocation().add(0.5, 0, 0.5),
10, b.getBlockData());
}
@Override
public float toolPower(org.bukkit.inventory.ItemStack tool, org.bukkit.block.Block b) {
if (!ItemUtils.isEmpty(tool)) {
ItemStack craftItemStack = CraftItemStack.asNMSCopy(tool);
Level nmsWorld = ((CraftWorld) b.getWorld()).getHandle();
Block nmsBlock = nmsWorld.getBlockState(new BlockPos(b.getX(), b.getY(), b.getZ())).getBlock();
return craftItemStack.getDestroySpeed(nmsBlock.defaultBlockState());
}
return 1;
}
@Override
public float toolPower(org.bukkit.inventory.ItemStack tool, Material b) {
if (!ItemUtils.isEmpty(tool)) {
ItemStack craftItemStack = CraftItemStack.asNMSCopy(tool);
CraftBlockData data = (CraftBlockData) b.createBlockData();
return craftItemStack.getDestroySpeed(data.getState());
}
return 1;
}
@Override
public void breakBlock(Player p, org.bukkit.block.Block b) {
b.getWorld().spawnParticle(Particle.BLOCK_CRACK, b.getLocation().add(0.5, 0.5, 0.5), 100, 0.1, 0.1, 0.1, 4, b.getBlockData());
b.getWorld().playSound(b.getLocation(), b.getBlockData().getSoundGroup().getBreakSound(), 1.0f, 1.0f);
((CraftPlayer) p).getHandle().gameMode.destroyBlock(new BlockPos(b.getX(), b.getY(), b.getZ()));
}
@Override
public Sound blockSound(org.bukkit.block.Block b) {
try {
Level nmsWorld = ((CraftWorld) b.getWorld()).getHandle();
Block nmsBlock = nmsWorld.getBlockState(new BlockPos(b.getX(), b.getY(), b.getZ())).getBlock();
SoundType soundEffectType = nmsBlock.getSoundType(nmsBlock.defaultBlockState());
Field soundEffectField = soundEffectType.getClass().getDeclaredField("fallSound");
soundEffectField.setAccessible(true);
SoundEvent soundEffect = (SoundEvent) soundEffectField.get(soundEffectType);
Field keyField = SoundEvent.class.getDeclaredField("CODEC");
keyField.setAccessible(true);
ResourceLocation minecraftKey = (ResourceLocation) keyField.get(soundEffect);
return Sound.valueOf(minecraftKey.getPath().toUpperCase(java.util.Locale.US)
.replace(".", "_")
.replace("_FALL", "_HIT"));
} catch (NoSuchFieldException | IllegalAccessException ignored) {
}
return Sound.BLOCK_STONE_HIT;
}
@Override
public void resetAttackCooldown(Player p){
ServerPlayer entityPlayer = ((CraftPlayer) p).getHandle();
entityPlayer.resetAttackStrengthTicker();
}
@Override
public void setEdible(ItemBuilder meta, boolean edible, boolean canAlwaysEat, float eatTimeSeconds) {
// do nothing, incompatible
}
@Override
public void setGlint(ItemMeta meta, boolean glint) {
// do nothing, incompatible
}
@Override
public void setMaxStackSize(ItemMeta meta, int stackSize) {
// do nothing, incompatible
}
@Override
public int getMaxStackSize(ItemMeta meta, Material baseMaterial) {
return baseMaterial.getMaxStackSize();
}
@Override
public void setFireResistant(ItemMeta meta, boolean fireResistant) {
// do nothing, incompatible
}
@Override
public void setHideTooltip(ItemMeta meta, boolean hideToolTip) {
// do nothing, incompatible
}
@Override
public void setBookContents(org.bukkit.inventory.ItemStack book, List<BaseComponent[]> pages) {
}
@Override
public Enchantment getEnchantment(EnchantmentMappings mappedTo) {
return oldMappings(mappedTo);
}
@Override
public PotionType getPotionType(PotionMeta meta) {
return meta.getBasePotionData().getType();
}
@Override
public PotionEffectType getPotionEffectType(PotionEffectMappings mappedTo) {
return oldMappings(mappedTo);
}
@Override
public Attribute getAttribute(AttributeMappings mappedTo) {
return getMappedAttribute(mappedTo);
}
public static Attribute getMappedAttribute(AttributeMappings mappedTo){
return switch (mappedTo){
case LUCK -> Attribute.GENERIC_LUCK;
case ARMOR -> Attribute.GENERIC_ARMOR;
case MAX_HEALTH -> Attribute.GENERIC_MAX_HEALTH;
case ATTACK_SPEED -> Attribute.GENERIC_ATTACK_SPEED;
case FLYING_SPEED -> Attribute.GENERIC_FLYING_SPEED;
case ATTACK_DAMAGE -> Attribute.GENERIC_ATTACK_DAMAGE;
case MOVEMENT_SPEED -> Attribute.GENERIC_MOVEMENT_SPEED;
case ARMOR_TOUGHNESS -> Attribute.GENERIC_ARMOR_TOUGHNESS;
case ATTACK_KNOCKBACK -> Attribute.GENERIC_ATTACK_KNOCKBACK;
case HORSE_JUMP_STRENGTH -> Attribute.HORSE_JUMP_STRENGTH;
case KNOCKBACK_RESISTANCE -> Attribute.GENERIC_KNOCKBACK_RESISTANCE;
case SPAWN_REINFORCEMENTS -> Attribute.ZOMBIE_SPAWN_REINFORCEMENTS;
default -> null;
};
}
@Override
public boolean isUpgraded(PotionMeta meta) {
return meta.getBasePotionData().isUpgraded();
}
@Override
public boolean isExtended(PotionMeta meta) {
return meta.getBasePotionData().isExtended();
}
@Override
public void setPotionType(PotionMeta meta, PotionType type) {
meta.setBasePotionData(new PotionData(type, false, false));
}
@Override
public void addUniqueAttribute(LivingEntity e, UUID uuid, String identifier, Attribute type, double amount, AttributeModifier.Operation operation) {
addAttribute(e, uuid, identifier, type, amount, operation);
}
@Override
public boolean hasUniqueAttribute(LivingEntity e, UUID uuid, String identifier, Attribute type) {
return hasAttribute(e, uuid, identifier, type);
}
@Override
public double getUniqueAttributeValue(LivingEntity e, UUID uuid, String identifier, Attribute type) {
return getAttributeValue(e, uuid, identifier, type);
}
@Override
public void removeUniqueAttribute(LivingEntity e, String identifier, Attribute type) {
removeAttribute(e, identifier, type);
}
public static Enchantment oldMappings(EnchantmentMappings mapping){
return switch (mapping){
case FLAME -> Enchantment.ARROW_FIRE;
case POWER -> Enchantment.ARROW_DAMAGE;
case INFINITY -> Enchantment.ARROW_INFINITE;
case PUNCH -> Enchantment.ARROW_KNOCKBACK;
case CURSE_OF_BINDING -> Enchantment.BINDING_CURSE;
case CHANNELING -> Enchantment.CHANNELING;
case SHARPNESS -> Enchantment.DAMAGE_ALL;
case BANE_OF_ARTHROPODS -> Enchantment.DAMAGE_ARTHROPODS;
case SMITE -> Enchantment.DAMAGE_UNDEAD;
case DEPTH_STRIDER -> Enchantment.DEPTH_STRIDER;
case EFFICIENCY -> Enchantment.DIG_SPEED;
case UNBREAKING -> Enchantment.DURABILITY;
case FIRE_ASPECT -> Enchantment.FIRE_ASPECT;
case FROST_WALKER -> Enchantment.FROST_WALKER;
case IMPALING -> Enchantment.IMPALING;
case KNOCKBACK -> Enchantment.KNOCKBACK;
case FORTUNE -> Enchantment.LOOT_BONUS_BLOCKS;
case LOOTING -> Enchantment.LOOT_BONUS_MOBS;
case LOYALTY -> Enchantment.LOYALTY;
case LUCK_OF_THE_SEA -> Enchantment.LUCK;
case LURE -> Enchantment.LURE;
case MENDING -> Enchantment.MENDING;
case MULTISHOT -> Enchantment.MULTISHOT;
case RESPIRATION -> Enchantment.OXYGEN;
case PIERCING -> Enchantment.PIERCING;
case PROTECTION -> Enchantment.PROTECTION_ENVIRONMENTAL;
case BLAST_PROTECTION -> Enchantment.PROTECTION_EXPLOSIONS;
case FEATHER_FALLING -> Enchantment.PROTECTION_FALL;
case FIRE_PROTECTION -> Enchantment.PROTECTION_FIRE;
case PROJECTILE_PROTECTION -> Enchantment.PROTECTION_PROJECTILE;
case QUICK_CHARGE -> Enchantment.QUICK_CHARGE;
case RIPTIDE -> Enchantment.RIPTIDE;
case SILK_TOUCH -> Enchantment.SILK_TOUCH;
case SOUL_SPEED -> Enchantment.SOUL_SPEED;
case SWEEPING_EDGE -> Enchantment.SWEEPING_EDGE;
case THORNS -> Enchantment.THORNS;
case CURSE_OF_VANISHING -> Enchantment.VANISHING_CURSE;
case AQUA_AFFINITY -> Enchantment.WATER_WORKER;
default -> null;
};
}
public static PotionEffectType oldMappings(PotionEffectMappings mapping){
return switch (mapping){
case LUCK -> PotionEffectType.LUCK;
case HASTE -> PotionEffectType.FAST_DIGGING;
case SPEED -> PotionEffectType.SPEED;
case HUNGER -> PotionEffectType.HUNGER;
case NAUSEA -> PotionEffectType.CONFUSION;
case POISON -> PotionEffectType.POISON;
case WITHER -> PotionEffectType.WITHER;
case GLOWING -> PotionEffectType.GLOWING;
case BAD_LUCK -> PotionEffectType.UNLUCK;
case DARKNESS -> PotionEffectType.DARKNESS;
case BAD_OMEN -> PotionEffectType.BAD_OMEN;
case SLOWNESS -> PotionEffectType.SLOW;
case STRENGTH -> PotionEffectType.INCREASE_DAMAGE;
case WEAKNESS -> PotionEffectType.WEAKNESS;
case BLINDNESS -> PotionEffectType.BLINDNESS;
case ABSORPTION -> PotionEffectType.ABSORPTION;
case LEVITATION -> PotionEffectType.LEVITATION;
case JUMP_BOOST -> PotionEffectType.JUMP;
case RESISTANCE -> PotionEffectType.DAMAGE_RESISTANCE;
case SATURATION -> PotionEffectType.SATURATION;
case HEALTH_BOOST -> PotionEffectType.HEALTH_BOOST;
case INVISIBILITY -> PotionEffectType.INVISIBILITY;
case REGENERATION -> PotionEffectType.REGENERATION;
case NIGHT_VISION -> PotionEffectType.NIGHT_VISION;
case SLOW_FALLING -> PotionEffectType.SLOW_FALLING;
case CONDUIT_POWER -> PotionEffectType.CONDUIT_POWER;
case DOLPHINS_GRACE -> PotionEffectType.DOLPHINS_GRACE;
case INSTANT_DAMAGE -> PotionEffectType.HARM;
case INSTANT_HEALTH -> PotionEffectType.HEAL;
case MINING_FATIGUE -> PotionEffectType.SLOW_DIGGING;
case FIRE_RESISTANCE -> PotionEffectType.FIRE_RESISTANCE;
case WATER_BREATHING -> PotionEffectType.WATER_BREATHING;
case HERO_OF_THE_VILLAGE -> PotionEffectType.HERO_OF_THE_VILLAGE;
default -> null;
};
}
public static void addAttribute(LivingEntity e, UUID uuid, String identifier, Attribute type, double amount, AttributeModifier.Operation operation){
AttributeInstance instance = e.getAttribute(type);
if (instance != null){
instance.getModifiers().stream().filter(m -> m != null && m.getName().equals(identifier)).forEach(instance::removeModifier);
if (amount != 0) instance.addModifier(new AttributeModifier(uuid, identifier, amount, operation));
}
}
public static boolean hasAttribute(LivingEntity e, UUID uuid, String identifier, Attribute type){
AttributeInstance instance = e.getAttribute(type);
return instance != null && instance.getModifiers().stream().anyMatch(m -> m != null && m.getName().equals(identifier));
}
public static double getAttributeValue(LivingEntity e, UUID uuid, String identifier, Attribute type){
AttributeInstance instance = e.getAttribute(type);
if (instance != null) return instance.getModifiers().stream().filter(m -> m != null && m.getName().equals(identifier) && m.getUniqueId().equals(uuid)).map(AttributeModifier::getAmount).findFirst().orElse(0D);
return 0;
}
public static void removeAttribute(LivingEntity e, String identifier, Attribute type){
AttributeInstance instance = e.getAttribute(type);
if (instance != null) instance.getModifiers().stream().filter(m -> m != null && m.getName().equals(identifier)).forEach(instance::removeModifier);
}
@Override
public void setItemModel(ItemMeta meta, String model){
// not compatible
}
@Override
public void setEquippable(ItemMeta meta, String modelKey, EquipmentSlot slot, String cameraOverlayKey, Sound equipSound, List<EntityType> allowedTypes){
// not compatible
}
@Override
public void setToolTipStyle(ItemMeta meta, String namespacedKey){
// not compatible
}
@Override
public String getItemModel(ItemMeta meta) {
// not compatible
return null;
}
@Override
public EquippableWrapper getEquippable(ItemMeta meta) {
// not compatible
return null;
}
@Override
public String getToolTipStyle(ItemMeta meta) {
// not compatible
return null;
}
}
| 0 | 0.955897 | 1 | 0.955897 | game-dev | MEDIA | 0.999 | game-dev | 0.971947 | 1 | 0.971947 |
ProjectIgnis/CardScripts | 1,252 | unofficial/c100000343.lua | --森の聖騎士 ワンコ
--Wonko, Noble Knight of the Forest
local s,id=GetID()
function s.initial_effect(c)
--target
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e1:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET)
e1:SetCondition(s.tgcon)
e1:SetTarget(s.tglimit)
e1:SetValue(1)
c:RegisterEffect(e1)
--destroyed
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,0))
e2:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_BATTLE_DESTROYED)
e2:SetOperation(s.desop)
c:RegisterEffect(e2)
end
function s.tgcon(e,c)
return Duel.IsExistingMatchingCard(Card.IsFaceup,0,LOCATION_FZONE,LOCATION_FZONE,1,nil)
end
function s.tglimit(e,c)
return c~=e:GetHandler()
end
function s.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
if not bc:IsRelateToBattle() or bc:IsFacedown() then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(-500)
bc:RegisterEffect(e1)
end | 0 | 0.845303 | 1 | 0.845303 | game-dev | MEDIA | 0.971474 | game-dev | 0.626916 | 1 | 0.626916 |
SavageLabs/SavageFactions | 2,138 | src/main/java/com/massivecraft/factions/ConfigVersion.java | package com.massivecraft.factions;
import java.io.IOException;
public class ConfigVersion {
/**
* Config Version Tool:
*
* Changes to the config need to be added to the default config
* but also need to be coded into the version number slot of the update.
*
* This allows default configs to be updated to the latest version on load, but older
* config version to be updated without needing to reset the config or transfer old config stats.
*/
public static class Checker {
private final int currentVersion = 1;
private int version = 0;
public Checker checkLevel() {
if (!SavageFactions.plugin.getConfig().isSet("Config-Version")) version = 0;
else version = SavageFactions.plugin.getConfig().getInt("Config-Version");
return this;
}
public Checker TakeActionIfRequired() {
switch (version) {
case 0:
// The only change in v0 - v1 is config version
SavageFactions.plugin.getConfig().addDefault("Config-Version", 1);
SavageFactions.plugin.log("Config Version " + version + " found! Updated config to " + (version + 1));
break;
case currentVersion:
SavageFactions.plugin.log("Config.yml was found to be up-to-date!");
break;
default:
// Unknown number found, log it.
SavageFactions.plugin.log("Unsupported config version found!");
SavageFactions.plugin.log("Please reset your config to default!");
break;
}
return this;
}
public boolean save() {
try {
SavageFactions.plugin.getConfig().save("config.yml");
} catch (IOException er) {
SavageFactions.plugin.log("There was an error saving the updates to config.yml! Aborting!");
er.printStackTrace();
return false;
}
return true;
}
}
}
| 0 | 0.803025 | 1 | 0.803025 | game-dev | MEDIA | 0.740651 | game-dev | 0.678422 | 1 | 0.678422 |
oculus-samples/Unity-Decommissioned | 2,982 | Assets/Decommissioned/Scripts/Interactables/PumpTransformer.cs | // Copyright (c) Meta Platforms, Inc. and affiliates.
// Use of the material below is subject to the terms of the MIT License
// https://github.com/oculus-samples/Unity-Decommissioned/tree/main/Assets/Decommissioned/LICENSE
using System;
using Meta.XR.Samples;
using Oculus.Interaction;
using UnityEngine;
namespace Meta.Decommissioned.Interactables
{
/// <summary>
/// Special <see cref="ITransformer"/> object specifically for interaction with the handle of a pump. Configures
/// and manages multiple grab points and handle movement.
///
/// <p>This component is one of two used to create a pump object; for implementation of a constrained rod, see
/// the <see cref="PumpControl"/> script.</p>
/// </summary>
[MetaCodeSample("Decommissioned")]
public class PumpTransformer : MonoBehaviour, ITransformer
{
[SerializeField] private float m_maxPushDistance = 0.5f;
private Vector3 m_initialPosition;
private Vector3 m_grabOffsetInLocalSpace;
private IGrabbable m_grabbable;
private Vector3 GrabPoint
{
get
{
var grabPoints = m_grabbable.GrabPoints;
var point0 = grabPoints[0].position;
if (grabPoints.Count == 1)
{
return point0;
}
var point1 = grabPoints[1].position;
return Vector3.LerpUnclamped(point0, point1, 0.5f);
}
}
public void Initialize(IGrabbable grabbable)
{
m_grabbable = grabbable;
m_initialPosition = m_grabbable.Transform.localPosition;
}
public void BeginTransform()
{
var targetTransform = m_grabbable.Transform;
m_grabOffsetInLocalSpace = targetTransform.InverseTransformVector(GrabPoint - targetTransform.position);
}
public void UpdateTransform()
{
var targetTransform = m_grabbable.Transform;
var constrainedPosition = GrabPoint - targetTransform.TransformVector(m_grabOffsetInLocalSpace);
// the translation constraints occur in parent space
if (targetTransform.parent != null)
{
constrainedPosition = targetTransform.parent.InverseTransformPoint(constrainedPosition);
}
constrainedPosition.x = m_initialPosition.x;
constrainedPosition.y = Math.Clamp(constrainedPosition.y, m_initialPosition.y - m_maxPushDistance, m_initialPosition.y);
constrainedPosition.z = m_initialPosition.z;
// Convert the constrained position back to world space
if (targetTransform.parent != null)
{
constrainedPosition = targetTransform.parent.TransformPoint(constrainedPosition);
}
targetTransform.position = constrainedPosition;
}
public void EndTransform() { }
}
}
| 0 | 0.917924 | 1 | 0.917924 | game-dev | MEDIA | 0.889713 | game-dev | 0.970383 | 1 | 0.970383 |
glKarin/com.n0n3m4.diii4a | 2,242 | Q3E/src/main/jni/source/engine/replay_internal.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
//----------------------------------------------------------------------------------------
#ifndef REPLAY_INTERNAL_H
#define REPLAY_INTERNAL_H
#ifdef _WIN32
#pragma once
#endif
//----------------------------------------------------------------------------------------
#include "replay/ireplaysystem.h"
#include "replay/iserverreplaycontext.h"
#if !defined( DEDICATED )
#include "replay/iclientreplaycontext.h"
#include "replay/ireplayperformancemanager.h"
#include "replay/ireplayperformancecontroller.h"
#include "replay/ireplaymoviemanager.h"
#include "replay/ireplaymovierenderer.h"
#endif
//----------------------------------------------------------------------------------------
extern IReplaySystem *g_pReplay;
extern IServerReplayContext *g_pServerReplayContext;
extern CreateInterfaceFn g_fnReplayFactory;
#if !defined( DEDICATED )
extern IClientReplayContext *g_pClientReplayContext;
extern IReplayManager *g_pReplayManager;
extern IReplayMovieManager *g_pReplayMovieManager;
extern IReplayPerformanceManager *g_pReplayPerformanceManager;
extern IReplayPerformanceController *g_pReplayPerformanceController;
extern IReplayMovieRenderer *g_pReplayMovieRenderer;
#endif
//----------------------------------------------------------------------------------------
#define SETUP_CVAR_REF( _cvar ) ConVarRef _cvar( #_cvar ); Assert( _cvar.IsValid() );
#define GET_REPLAY_DBG_REF() SETUP_CVAR_REF( replay_debug )
//----------------------------------------------------------------------------------------
// Purpose: Init/shutdown the replay system
//----------------------------------------------------------------------------------------
void ReplaySystem_Init( bool bDedicated );
void ReplaySystem_Shutdown();
//----------------------------------------------------------------------------------------
// Purpose: Check to see if replay is supported on the running game/platform
//----------------------------------------------------------------------------------------
bool Replay_IsSupportedModAndPlatform();
//----------------------------------------------------------------------------------------
#endif // REPLAY_INTERNAL_H
| 0 | 0.677711 | 1 | 0.677711 | game-dev | MEDIA | 0.410739 | game-dev | 0.632005 | 1 | 0.632005 |
Dimbreath/AzurLaneData | 3,269 | ja-JP/support/network/ipaddress.lua | pg = pg or {}
slot0 = pg
slot0.IPAddress = class("IPAddress")
slot1 = slot0.IPAddress
slot2 = "https://www.azurlane.tw/getip"
slot3 = {
{
"202.39.128.0",
"202.39.255.255"
},
{
"203.66.0.0",
"203.66.255.255"
},
{
"203.69.0.0",
"203.69.255.255"
},
{
"203.75.0.0",
"203.75.255.255"
},
{
"203.74.0.0",
"203.74.255.255"
},
{
"210.65.0.0",
"210.65.255.255"
},
{
"210.71.128.0",
"210.71.255.255"
},
{
"210.61.0.0",
"210.61.255.255"
},
{
"210.62.248.0",
"210.62.255.255"
},
{
"210.59.128.0",
"210.59.255.255"
},
{
"210.242.0.0",
"210.242.127.255"
},
{
"210.242.128.0",
"210.242.255.255"
},
{
"210.241.224.0",
"210.241.255.255"
},
{
"211.72.0.0",
"211.72.127.255"
},
{
"211.72.128.0",
"211.72.255.255"
},
{
"211.75.0.0",
" 211.75.127.255"
},
{
"211.75.128.0",
"211.75.255.255"
},
{
"211.20.0.0",
"211.20.255.255"
},
{
"211.21.0.0",
"211.21.255.255"
},
{
"211.22.0.0",
"211.22.255.255"
},
{
"211.23.0.0",
"211.23.255.255"
},
{
"61.216.0.0",
"61.219.255.255"
},
{
"61.220.0.0",
"61.227.255.255"
},
{
"61.228.0.0",
"61.231.255.255"
},
{
"218.160.0.0",
"218.165.255.255"
}
}
function slot1.Ctor(slot0)
slot0:ConvertIPRange()
slot0.requestUrl = uv0
if not Application.isEditor then
VersionMgr.Inst:WebRequest(slot0.requestUrl, function (slot0, slot1)
uv0.exportIP = slot1
uv0.isSpecialIP = uv0:CheckExportIP()
end)
end
end
function slot1.IsIPString(slot0, slot1)
if type(slot1) ~= "string" then
return false
end
if string.len(slot1) < 7 or slot2 > 15 then
return false
end
slot3 = string.find(slot1, "%p", 1)
slot4 = 0
while slot3 ~= nil do
if string.sub(slot1, slot3, slot3) ~= "." then
return false
end
slot3 = string.find(slot1, "%p", slot3 + 1)
if slot4 + 1 > 3 then
return false
end
end
if slot4 ~= 3 then
return false
end
slot5 = {}
for slot9 in string.gmatch(slot1, "%d+") do
slot5[#slot5 + 1] = slot9
if tonumber(slot9) == nil or slot10 > 255 then
return false
end
end
if #slot5 ~= 4 then
return false
end
return true
end
function slot1.IP2Int(slot0, slot1)
slot2 = 0
slot3, slot4, slot5, slot6 = slot1:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")
return 16777216 * slot3 + 65536 * slot4 + 256 * slot5 + slot6
end
function slot1.ConvertIPRange(slot0)
slot0.IPRangeIntList = {}
for slot4, slot5 in ipairs(uv0) do
slot6 = {}
table.insert(slot6, slot0:IP2Int(slot5[1]))
table.insert(slot6, slot0:IP2Int(slot5[2]))
table.insert(slot0.IPRangeIntList, slot6)
end
end
function slot1.CheckExportIP(slot0)
if not slot0.exportIP or not slot0:IsIPString(slot0.exportIP) then
return false
end
slot1 = slot0:IP2Int(slot0.exportIP)
for slot5, slot6 in ipairs(slot0.IPRangeIntList) do
if slot6[1] <= slot1 and slot1 <= slot6[2] then
return true
end
end
return false
end
function slot1.GetExportIPString(slot0)
return slot0.exportIP
end
function slot1.GetLocalIP(slot0)
slot0.localIP = ReflectionHelp.RefGetProperty(typeof("UnityEngine.NetworkPlayer"), "ipAddress", ReflectionHelp.RefGetProperty(typeof("UnityEngine.Network"), "player"))
return slot0.localIP
end
function slot1.IsSpecialIP(slot0)
return slot0.isSpecialIP
end
| 0 | 0.566915 | 1 | 0.566915 | game-dev | MEDIA | 0.653684 | game-dev | 0.771813 | 1 | 0.771813 |
rebuild-123/Python-Head-First-Design-Patterns | 1,068 | command/party/CeilingFanOffCommand.py | import re
import sys
from CeilingFan import CeilingFan
from Command import Command
class CeilingFanOffCommand(Command):
ceilingFan: CeilingFan
prevSpeed: int = 0
def __init__(self, ceilingFan: CeilingFan):
self.ceilingFan = ceilingFan
def execute(self) -> None:
self.prevSpeed = self.ceilingFan.getSpeed()
self.ceilingFan.off()
def undo(self) -> None:
if re.match(r'3\.[1-9][0-9]\.', sys.version[:5]):
# Only for python 3.10 and later
match self.prevSpeed:
case CeilingFan.HIGH: self.ceilingFan.high()
case CeilingFan.MEDIUM: self.ceilingFan.medium()
case CeilingFan.LOW: self.ceilingFan.low()
case _: self.ceilingFan.off()
else:
if self.prevSpeed == CeilingFan.HIGH: self.ceilingFan.high()
elif self.prevSpeed == CeilingFan.MEDIUM: self.ceilingFan.medium()
elif self.prevSpeed == CeilingFan.LOW: self.ceilingFan.low()
else: self.ceilingFan.off() | 0 | 0.521943 | 1 | 0.521943 | game-dev | MEDIA | 0.320666 | game-dev | 0.60954 | 1 | 0.60954 |
aerys/minko | 5,809 | plugin/bullet/lib/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btContactConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "LinearMath/btVector3.h"
#include "btJacobianEntry.h"
#include "btContactSolverInfo.h"
#include "LinearMath/btMinMax.h"
#include "BulletCollision/NarrowPhaseCollision/btManifoldPoint.h"
btContactConstraint::btContactConstraint(btPersistentManifold* contactManifold,btRigidBody& rbA,btRigidBody& rbB)
:btTypedConstraint(CONTACT_CONSTRAINT_TYPE,rbA,rbB),
m_contactManifold(*contactManifold)
{
}
btContactConstraint::~btContactConstraint()
{
}
void btContactConstraint::setContactManifold(btPersistentManifold* contactManifold)
{
m_contactManifold = *contactManifold;
}
void btContactConstraint::getInfo1 (btConstraintInfo1* info)
{
}
void btContactConstraint::getInfo2 (btConstraintInfo2* info)
{
}
void btContactConstraint::buildJacobian()
{
}
#include "btContactConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "LinearMath/btVector3.h"
#include "btJacobianEntry.h"
#include "btContactSolverInfo.h"
#include "LinearMath/btMinMax.h"
#include "BulletCollision/NarrowPhaseCollision/btManifoldPoint.h"
//response between two dynamic objects without friction and no restitution, assuming 0 penetration depth
btScalar resolveSingleCollision(
btRigidBody* body1,
btCollisionObject* colObj2,
const btVector3& contactPositionWorld,
const btVector3& contactNormalOnB,
const btContactSolverInfo& solverInfo,
btScalar distance)
{
btRigidBody* body2 = btRigidBody::upcast(colObj2);
const btVector3& normal = contactNormalOnB;
btVector3 rel_pos1 = contactPositionWorld - body1->getWorldTransform().getOrigin();
btVector3 rel_pos2 = contactPositionWorld - colObj2->getWorldTransform().getOrigin();
btVector3 vel1 = body1->getVelocityInLocalPoint(rel_pos1);
btVector3 vel2 = body2? body2->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0);
btVector3 vel = vel1 - vel2;
btScalar rel_vel;
rel_vel = normal.dot(vel);
btScalar combinedRestitution = 0.f;
btScalar restitution = combinedRestitution* -rel_vel;
btScalar positionalError = solverInfo.m_erp *-distance /solverInfo.m_timeStep ;
btScalar velocityError = -(1.0f + restitution) * rel_vel;// * damping;
btScalar denom0 = body1->computeImpulseDenominator(contactPositionWorld,normal);
btScalar denom1 = body2? body2->computeImpulseDenominator(contactPositionWorld,normal) : 0.f;
btScalar relaxation = 1.f;
btScalar jacDiagABInv = relaxation/(denom0+denom1);
btScalar penetrationImpulse = positionalError * jacDiagABInv;
btScalar velocityImpulse = velocityError * jacDiagABInv;
btScalar normalImpulse = penetrationImpulse+velocityImpulse;
normalImpulse = 0.f > normalImpulse ? 0.f: normalImpulse;
body1->applyImpulse(normal*(normalImpulse), rel_pos1);
if (body2)
body2->applyImpulse(-normal*(normalImpulse), rel_pos2);
return normalImpulse;
}
//bilateral constraint between two dynamic objects
void resolveSingleBilateral(btRigidBody& body1, const btVector3& pos1,
btRigidBody& body2, const btVector3& pos2,
btScalar distance, const btVector3& normal,btScalar& impulse ,btScalar timeStep)
{
(void)timeStep;
(void)distance;
btScalar normalLenSqr = normal.length2();
btAssert(btFabs(normalLenSqr) < btScalar(1.1));
if (normalLenSqr > btScalar(1.1))
{
impulse = btScalar(0.);
return;
}
btVector3 rel_pos1 = pos1 - body1.getCenterOfMassPosition();
btVector3 rel_pos2 = pos2 - body2.getCenterOfMassPosition();
//this jacobian entry could be re-used for all iterations
btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
btVector3 vel = vel1 - vel2;
btJacobianEntry jac(body1.getCenterOfMassTransform().getBasis().transpose(),
body2.getCenterOfMassTransform().getBasis().transpose(),
rel_pos1,rel_pos2,normal,body1.getInvInertiaDiagLocal(),body1.getInvMass(),
body2.getInvInertiaDiagLocal(),body2.getInvMass());
btScalar jacDiagAB = jac.getDiagonal();
btScalar jacDiagABInv = btScalar(1.) / jacDiagAB;
btScalar rel_vel = jac.getRelativeVelocity(
body1.getLinearVelocity(),
body1.getCenterOfMassTransform().getBasis().transpose() * body1.getAngularVelocity(),
body2.getLinearVelocity(),
body2.getCenterOfMassTransform().getBasis().transpose() * body2.getAngularVelocity());
btScalar a;
a=jacDiagABInv;
rel_vel = normal.dot(vel);
//todo: move this into proper structure
btScalar contactDamping = btScalar(0.2);
#ifdef ONLY_USE_LINEAR_MASS
btScalar massTerm = btScalar(1.) / (body1.getInvMass() + body2.getInvMass());
impulse = - contactDamping * rel_vel * massTerm;
#else
btScalar velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
impulse = velocityImpulse;
#endif
}
| 0 | 0.858131 | 1 | 0.858131 | game-dev | MEDIA | 0.99271 | game-dev | 0.977126 | 1 | 0.977126 |
LodestarMC/Lodestone | 2,660 | src/main/java/team/lodestar/lodestone/recipe/builder/NBTCarryRecipeBuilder.java | package team.lodestar.lodestone.recipe.builder;
import net.minecraft.advancements.*;
import net.minecraft.advancements.critereon.*;
import net.minecraft.core.registries.*;
import net.minecraft.data.recipes.*;
import net.minecraft.resources.*;
import net.minecraft.tags.*;
import net.minecraft.world.item.*;
import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.*;
import org.jetbrains.annotations.*;
import team.lodestar.lodestone.recipe.*;
import java.util.*;
public class NBTCarryRecipeBuilder extends ShapedRecipeBuilder implements LodestoneRecipeBuilder<NBTCarryRecipe> {
public final Ingredient copyFrom;
public NBTCarryRecipeBuilder(RecipeCategory category, ItemStack result, Ingredient copyFrom) {
super(category, result);
this.copyFrom = copyFrom;
}
@Override
public NBTCarryRecipe buildRecipe(ResourceLocation id) {
var recipe = new ShapedRecipe(
Objects.requireNonNullElse(group, ""),
RecipeBuilder.determineBookCategory(category),
ensureValid(id),
resultStack,
showNotification
);
return new NBTCarryRecipe(recipe, this.copyFrom);
}
@Override
public void save(RecipeOutput recipeOutput) {
save(recipeOutput, BuiltInRegistries.ITEM.getKey(getResult()));
}
@Override
public void save(RecipeOutput recipeOutput, String id) {
save(recipeOutput, ResourceLocation.parse(id));
}
@Override
public NBTCarryRecipeBuilder define(Character symbol, TagKey<Item> tag) {
return (NBTCarryRecipeBuilder) super.define(symbol, tag);
}
@Override
public NBTCarryRecipeBuilder define(Character symbol, ItemLike item) {
return (NBTCarryRecipeBuilder) super.define(symbol, item);
}
@Override
public NBTCarryRecipeBuilder define(Character symbol, Ingredient ingredient) {
return (NBTCarryRecipeBuilder) super.define(symbol, ingredient);
}
@Override
public NBTCarryRecipeBuilder pattern(String pattern) {
return (NBTCarryRecipeBuilder) super.pattern(pattern);
}
@Override
public NBTCarryRecipeBuilder unlockedBy(String name, Criterion<?> criterion) {
return (NBTCarryRecipeBuilder) super.unlockedBy(name, criterion);
}
@Override
public NBTCarryRecipeBuilder group(@Nullable String groupName) {
return (NBTCarryRecipeBuilder) super.group(groupName);
}
@Override
public NBTCarryRecipeBuilder showNotification(boolean showNotification) {
return (NBTCarryRecipeBuilder) super.showNotification(showNotification);
}
}
| 0 | 0.838709 | 1 | 0.838709 | game-dev | MEDIA | 0.954914 | game-dev | 0.94281 | 1 | 0.94281 |
Soapwood/VXMusic | 2,049 | VXMusicOverlay/Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Editor/DropdownOptionListDrawer.cs | using UnityEditorInternal;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(TMP_Dropdown.OptionDataList), true)]
class DropdownOptionListDrawer : PropertyDrawer
{
private ReorderableList m_ReorderableList;
private void Init(SerializedProperty property)
{
if (m_ReorderableList != null)
return;
SerializedProperty array = property.FindPropertyRelative("m_Options");
m_ReorderableList = new ReorderableList(property.serializedObject, array);
m_ReorderableList.drawElementCallback = DrawOptionData;
m_ReorderableList.drawHeaderCallback = DrawHeader;
m_ReorderableList.elementHeight += 16;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Init(property);
m_ReorderableList.DoList(position);
}
private void DrawHeader(Rect rect)
{
GUI.Label(rect, "Options");
}
private void DrawOptionData(Rect rect, int index, bool isActive, bool isFocused)
{
SerializedProperty itemData = m_ReorderableList.serializedProperty.GetArrayElementAtIndex(index);
SerializedProperty itemText = itemData.FindPropertyRelative("m_Text");
SerializedProperty itemImage = itemData.FindPropertyRelative("m_Image");
RectOffset offset = new RectOffset(0, 0, -1, -3);
rect = offset.Add(rect);
rect.height = EditorGUIUtility.singleLineHeight;
EditorGUI.PropertyField(rect, itemText, GUIContent.none);
rect.y += EditorGUIUtility.singleLineHeight;
EditorGUI.PropertyField(rect, itemImage, GUIContent.none);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
Init(property);
return m_ReorderableList.GetHeight();
}
}
}
| 0 | 0.954915 | 1 | 0.954915 | game-dev | MEDIA | 0.902643 | game-dev | 0.974437 | 1 | 0.974437 |
CafeFPS/r5_flowstate | 49,953 | vscripts/mp/sh_loot_marvin.nut | global function ShLootMarvin_Init
#if CLIENT
global function ServerCallback_PromptPingLootMarvin
#endif
#if SERVER
global function LootMarvin_OnDispenseLootAnimEvent
global function ClientCallback_PromptPingLootMarvin
#endif
#if SERVER && DEV
global function CreateMarvin_Loot
global function CreateMarvin_Story
global function SeeMarvinSpawnLocations
#endif
global const string STORY_MARVIN_SCRIPTNAME = "story_marvin"
global const string LOOT_MARVIN_SCRIPTNAME = "loot_marvin"
const string ITEM_MARVIN_ARM_REF = "loot_marvin_arm"
const int MAX_NUM_MARVINS = 24
const int MAX_NUM_ARM_MARVINS = 5
const int MARVIN_DIST_BUFFER = 5000
const int MAX_LOOT_ITEMS_FROM_MARVIN = 3
const float DURATION_COOLDOWN = 90.0
const float DURATION_WAIT_FOR_PLAYERS_NEARBY = 30.0
const string WAYPOINTTYPE_COOLDOWN = "waypointType_MarvinCooldown"
const string WAYPOINTTYPE_SCREEN = "waypointType_MarvinScreen"
const float SLOT_MACHINE_CYCLE_LENGTH = 0.3
const asset STORY_MARVIN_CSV_DIALOGUE = $"datatable/dialogue/story_marvin_dialogue.rpak"
const asset VFX_LOT_MARVIN_DISPERSE = $"P_marvin_loot_CP"
const asset VFX_LOT_MARVIN_SPARK_ARM = $"P_sparks_marvin_arm"
#if SERVER
const int LOOT_MARVIN_TRIGGER_RADIUS = 384
const string ANIM_LOOT_MARVIN_POWERDOWN_IDLE = "mrvn_powerdown_idle"
const string ANIM_LOOT_MARVIN_POWERUP = "mrvn_loot_activate"
const string ANIM_LOOT_MARVIN_ACTIVE_LOOP = "mrvn_loot_slotmachine_idle"
const string ANIM_LOOT_MARVIN_POWERDOWN = "mrvn_loot_powerdown"
const string ANIM_LOOT_MARVIN_SLOT_CRANK = "mrvn_loot_slotmachine_handle"
const string ANIM_LOOT_MARVIN_DISPENSE_SAD = "mrvn_giveloot_shrug"
const string ANIM_LOOT_MARVIN_DISPENSE_NEUTRAL = "mrvn_giveloot_gesture"
const string ANIM_LOOT_MARVIN_DISPENSE_PLEASED = "mrvn_giveloot_wave"
const string ANIM_LOOT_MARVIN_DISPENSE_VERY_HAPPY = "mrvn_giveloot_newhand"
const string ANIM_STORY_MARVIN_IDLE = "mrvn_storyteller_idle"
const string SFX_STORY_MARVIN_LOG = "diag_mp_amelie_audioLog_01_3p"
const string SFX_LOOT_MARVIN_SLOT_LOOP = "LootMarvin_Tumbler_Start_Loop"
const string SFX_LOOT_MARVIN_SLOT_INTERACT_SAD = "LootMarvin_Result_Grey"
const string SFX_LOOT_MARVIN_SLOT_INTERACT_NEUTRAL = "LootMarvin_Result_Blue"
const string SFX_LOOT_MARVIN_SLOT_INTERACT_PLEASED = "LootMarvin_Result_Purple"
const string SFX_LOOT_MARVIN_SLOT_INTERACT_VERY_HAPPY = "LootMarvin_Result_Gold"
const string SFX_LOOT_MARVIN_DISPERSE = "LootMarvin_DispenseLoot"
const string SFX_MARVIN_DENY = "Olympus_Horizon_Screen_Deny"
const string SFX_MARVIN_SPARKS = "LootMarvin_Arm_Sparks"
const string SIGNAL_PLAYER_ENTERED_MARVIN_TRIGGER = "OnEnterMarvinTrigger"
const string SIGNAL_MARVIN_ON_ACTIVATED = "OnMarvinActivated"
const string SIGNAL_MARVIN_ON_POWERDOWN = "OnMarvinPowerdown"
const string BODYGROUP_RIGHT_ARM = "removableRightForearm"
const int BODYGROUP_RIGHT_ARM_INDEX_ATTACHED_SPECIAL = 3
const int BODYGROUP_RIGHT_ARM_INDEX_DETACHED = 1
const string BODYGROUP_LEFT_ARM = "removableLeftForearm"
const int BODYGROUP_LEFT_ARM_INDEX_DETACHED = 1
#endif // SERVER
#if SERVER
enum eMarvinEmoticon
{
SAD,
NEUTRAL,
PLEASED,
VERY_HAPPY,
}
#endif
#if SERVER || CLIENT
global enum eMarvinState
{
DISABLED,
READY_FOR_POWERUP,
POWERING_UP,
ACTIVE,
DISPENSING,
POWERING_DOWN,
PERMANENTLY_DISABLED,
}
#endif
#if SERVER
struct MarvinData
{
Point startPoint
int marvinState
bool hasDetachableArm = false
bool isStoryMarvin = false
bool hasMissingArmBeenAttached = false
int lootTypeState
entity trigger
entity chestWaypoint
int currentEmoticonIdx = eMarvinEmoticon.SAD
bool hasSlotMachineSettled = false
entity armSparkFx
}
#endif //SERVER
struct
{
#if SERVER
table< entity, MarvinData > spawnedMarvinData
array<entity> marvinNodes
#else // SERVER
var chestScreenTopo
var chestScreenRui
var cooldownRui
entity topPriorityLootMarvin
#endif // CLIENT
}file
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// #### ## ## #### ########
// ## ### ## ## ##
// ## #### ## ## ##
// ## ## ## ## ## ##
// ## ## #### ## ##
// ## ## ### ## ##
// #### ## ## #### ##
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
void function ShLootMarvin_Init()
{
/*if( !GameMode_IsActive( eGameModes.SURVIVAL ) )
{
#if SERVER
// enable this callback so we can delete the dummy props already in the map
AddSpawnCallbackEditorClass( "prop_dynamic", "script_loot_marvin", LootMarvin_OnScriptTargetSpawned )
#endif
return
}*/
//PrecacheScriptString( STORY_MARVIN_SCRIPTNAME )
//"PrecacheScriptString( LOOT_MARVIN_SCRIPTNAME )
//RegisterCSVDialogue( STORY_MARVIN_CSV_DIALOGUE )
return // TODO: ENABLE THIS WHEN WE GET ANIMATIONS FOR MARVINS - LorryLeKral
PrecacheParticleSystem( VFX_LOT_MARVIN_DISPERSE )
PrecacheParticleSystem( VFX_LOT_MARVIN_SPARK_ARM )
#if SERVER
RegisterSignal( SIGNAL_PLAYER_ENTERED_MARVIN_TRIGGER )
RegisterSignal( SIGNAL_MARVIN_ON_ACTIVATED )
RegisterSignal( SIGNAL_MARVIN_ON_POWERDOWN )
AddSpawnCallbackEditorClass( "prop_dynamic", "script_loot_marvin", LootMarvin_OnScriptTargetSpawned )
//RegisterCustomItemPickupAction( ITEM_MARVIN_ARM_REF, LootMarvinArm_OnPickup )
#endif
#if CLIENT
AddCallback_OnPlayerLifeStateChanged( OnPlayerLifeStateChanged )
Waypoints_RegisterCustomType( WAYPOINTTYPE_COOLDOWN, InstanceMarvinCooldownCreatedWP )
Waypoints_RegisterCustomType( WAYPOINTTYPE_SCREEN, InstanceMarvinScreenCreatedWP )
AddCreateCallback( "npc_marvin", ClOnMarvinSpawned )
#endif
AddCallback_EntitiesDidLoad( EntitiesDidLoad )
}
void function EntitiesDidLoad()
{
/*if( !GameMode_IsActive( eGameModes.SURVIVAL ) )
return*/
int maxNumMarvins = GetCurrentPlaylistVarInt( "marvins_max_num", MAX_NUM_MARVINS )
int maxNumArmedMarvins = GetCurrentPlaylistVarInt( "marvins_max_num_armed", MAX_NUM_ARM_MARVINS )
bool lootMarvinsEnabled = GetCurrentPlaylistVarBool( "loot_marvins_enabled", true )
float marvinDistanceBuffer = GetCurrentPlaylistVarFloat( "marvins_distance_buffer", MARVIN_DIST_BUFFER )
#if SERVER
file.marvinNodes.randomize()
array<entity> usedNodes
if ( lootMarvinsEnabled )
{
int numSpawnedMarvins = 0
int numArmedMarvinsSpawned = 0
foreach ( int idx, entity node in file.marvinNodes )
{
// don't spawn more than the max
if ( numSpawnedMarvins >= maxNumMarvins )
break
// don't spawn if we're too close to another marvin that already spawned
bool isTooCloseToAnotherNode = false
foreach ( entity occupiedNode in usedNodes )
{
if ( Distance( occupiedNode.GetOrigin(), node.GetOrigin() ) <= marvinDistanceBuffer )
{
isTooCloseToAnotherNode = true
break
}
}
if ( isTooCloseToAnotherNode )
continue
// spawn the marvin
usedNodes.append( node )
bool hasDetachableArm = numArmedMarvinsSpawned < maxNumArmedMarvins
ProcessLevelEdMarvinNode( node, false, hasDetachableArm )
numSpawnedMarvins++
numArmedMarvinsSpawned++
}
}
foreach ( entity node in file.marvinNodes )
node.Destroy()
file.marvinNodes.clear()
printf( "Total num story and loot marvins: %i", file.spawnedMarvinData.len() )
#endif //SERVER
}
#if SERVER
void function LootMarvin_OnScriptTargetSpawned( entity ent )
{
/*if( !GameMode_IsActive( eGameModes.SURVIVAL ) )
{
ent.Destroy()
return
}*/
bool storyMarvinsEnabled = GetCurrentPlaylistVarBool( "story_marvins_enabled", false )
if ( ent.HasKey( "is_story_marvin" ) && ent.kv.is_story_marvin == "1" )
{
if ( storyMarvinsEnabled )
ProcessLevelEdMarvinNode( ent, true )
ent.Destroy()
}
else
{
file.marvinNodes.append( ent )
}
}
#endif // SERVER
#if SERVER
void function ProcessLevelEdMarvinNode( entity node, bool isStoryMarvin, bool hasDetachableArm = false )
{
vector origin = node.GetOrigin()
vector angles = node.GetAngles()
entity entityParent = node.GetParent()
CreateMarvin( origin, angles, entityParent, isStoryMarvin, hasDetachableArm )
}
#endif //SERVER
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// ## ## ######## #### ##
// ## ## ## ## ##
// ## ## ## ## ##
// ## ## ## ## ##
// ## ## ## ## ##
// ## ## ## ## ##
// ####### ## #### ########
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
#if SERVER && DEV
void function CreateMarvin_Loot( bool hasDetachableArm = false )
{
entity player = gp()[0]
TraceResults traceResults = PlayerViewTrace( player, 90000 )
if ( traceResults.fraction >= 1.0 )
return
CreateMarvin( traceResults.endPos, <0, 0, 0>, null, false, hasDetachableArm )
}
#endif // SERVER && DEV
#if SERVER && DEV
void function CreateMarvin_Story()
{
entity player = gp()[0]
TraceResults traceResults = PlayerViewTrace( player, 90000 )
if ( traceResults.fraction >= 1.0 )
return
CreateMarvin( traceResults.endPos, <0, RandomFloat( 360.0 ), 0>, null, true, false )
}
#endif // SERVER && DEV
#if SERVER && DEV
void function SeeMarvinSpawnLocations()
{
bool storyMarvinExists = false
foreach ( entity marvin, MarvinData data in file.spawnedMarvinData )
{
if ( IsAlive( marvin ) )
{
if ( data.hasDetachableArm )
{
DebugDrawSphere( marvin.GetOrigin(), 256, COLOR_BLUE, true, 45.0 )
}
else if ( data.isStoryMarvin )
{
DebugDrawSphere( marvin.GetOrigin(), 256, COLOR_GREEN, true, 45.0 )
storyMarvinExists = true
}
else
{
DebugDrawSphere( marvin.GetOrigin(), 256, COLOR_YELLOW, true, 45.0 )
}
}
}
int numAliveMarvins = storyMarvinExists ? file.spawnedMarvinData.len() - 1 : file.spawnedMarvinData.len()
printf( "Number of alive loot marvins: %i", numAliveMarvins )
}
#endif // SERVER && DEV
#if SERVER
void function PlayAnimLootMarvin( entity marvin, Point startPoint, string animation )
{
EndSignal( marvin, "OnDeath" )
Assert( IsAlive( marvin ), "Marvin tried to play an anim, but it is not alive." )
// TODO: support playing anims when the marvin is parented, which doesn't occur in olympus...for now at least.
marvin.SetNextThinkNow()
marvin.Anim_ScriptedPlayWithRefPoint( animation, startPoint.origin, startPoint.angles, DEFAULT_SCRIPTED_ANIMATION_BLEND_TIME )
WaittillAnimDone( marvin )
}
#endif
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// ###### ######## ### ## ## ## ## #### ## ## ######
// ## ## ## ## ## ## ## ## ## ### ## ## ### ## ## ##
// ## ## ## ## ## ## ## ## #### ## ## #### ## ##
// ###### ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ####
// ## ## ######### ## ## ## ## #### ## ## #### ## ##
// ## ## ## ## ## ## ## ## ## ### ## ## ### ## ##
// ###### ## ## ## ### ### ## ## #### ## ## ######
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
#if SERVER
void function CreateMarvin( vector origin, vector angles, entity lootMarvinParent, bool isStoryMarvin, bool hasDetachableArm )
{
if ( isStoryMarvin )
{
origin += (AnglesToRight( angles ) * -48.0) + (AnglesToForward( angles ) * 4.0)
}
string marvinScriptName = isStoryMarvin ? STORY_MARVIN_SCRIPTNAME : LOOT_MARVIN_SCRIPTNAME
entity marvin = CreateNPCFromAISettings( "npc_marvin_olympus", TEAM_UNASSIGNED, origin, angles )
marvin.SetScriptName( marvinScriptName )
DispatchSpawn( marvin )
//marvin.SetIgnorePredictedTriggerTypes( TT_JUMP_PAD | TT_GRAVITY_LIFT | TT_BLACKHOLE )
//marvin.SetNetworkDistanceCullEnabled( false )
// link it all to greater parent if there is one
if ( IsValid( lootMarvinParent ) )
marvin.SetParent( lootMarvinParent )
// state data
MarvinData data
data.startPoint.origin = origin
data.startPoint.angles = angles
file.spawnedMarvinData[ marvin ] <- data
// callbacks
AddEntityCallback_OnDamaged( marvin, LootAndStoryMarvin_OnDamaged )
AddEntityCallback_OnKilled( marvin, LootAndStoryMarvin_OnKilled )
// setup
if ( isStoryMarvin )
{
data.isStoryMarvin = true
thread PlayAnim( marvin, ANIM_STORY_MARVIN_IDLE )
marvin.SetUsable()
marvin.SetUsePrompts( "#STORY_MARVIN_PROMPT_USE", "#STORY_MARVIN_PROMPT_USE" )
marvin.AddUsableValue( USABLE_CUSTOM_HINTS | USABLE_BY_OWNER | USABLE_BY_PILOTS | USABLE_BY_ENEMIES )
marvin.SetUsablePriority( USABLE_PRIORITY_LOW )
AddCallback_OnUseEntity_ServerOnly( marvin, OnUseStoryMarvin )
}
else
{
//marvin.SetBodygroupModelByIndex( marvin.FindBodygroup( BODYGROUP_RIGHT_ARM ), BODYGROUP_RIGHT_ARM_INDEX_DETACHED )
if ( hasDetachableArm )
{
marvin.SetSkin( 1 )
data.hasDetachableArm = true
}
marvin.SetUsable()
marvin.SetUsePrompts( "#LOOT_MARVIN_PROMPT_USE", "#LOOT_MARVIN_PROMPT_USE" )
marvin.AddUsableValue( USABLE_CUSTOM_HINTS | USABLE_BY_OWNER | USABLE_BY_PILOTS | USABLE_BY_ENEMIES )
marvin.SetUsablePriority( USABLE_PRIORITY_LOW )
AddCallback_OnUseEntity_ServerOnly( marvin, CreateOnUseLootMarvinFunc( data ) )
data.marvinState = eMarvinState.READY_FOR_POWERUP
//marvin.SetThinkDuringAnimation( false )
thread PlayAnimLootMarvin( marvin, data.startPoint, ANIM_LOOT_MARVIN_POWERDOWN_IDLE )
//marvin.SetActivityModifier( ACT_MODIFIER_POWERED_DOWN, true )
/*data.trigger = CreateTriggerCylinder( marvin.GetOrigin(), LOOT_MARVIN_TRIGGER_RADIUS, 72, 16 )
data.trigger.SetEnterCallback( CreateOnEnterLootMarvinTriggerFunc( marvin, data ) )
data.trigger.SetLeaveCallback( CreateOnLeaveLootMarvinTriggerFunc( marvin, data ) )*/
}
}
#endif //SERVER
#if CLIENT
void function ClOnMarvinSpawned( entity marvin )
{
if ( marvin.GetScriptName() != LOOT_MARVIN_SCRIPTNAME )
return
AddEntityCallback_GetUseEntOverrideText( marvin, LootMarvinHintTextFunc )
}
#endif
#if CLIENT
string function LootMarvinHintTextFunc( entity marvin )
{
entity player = GetLocalViewPlayer()
if ( GradeFlagsHas( marvin, eGradeFlags.IS_OPEN ) )
{
return "#LOOT_MARVIN_PROMPT_COOLDOWN"
}
else if ( GradeFlagsHas( marvin, eGradeFlags.IS_BUSY ) )
{
return "#LOOT_MARVIN_PROMPT_BUSY"
}
else if ( GradeFlagsHas( marvin, eGradeFlags.IS_LOCKED ) )
{
return "#LOOT_MARVIN_PROMPT_DISABLED"
}
else if ( DoesPlayerHaveMarvinArmInInventory( player ) )
{
return "#LOOT_MARVIN_PROMPT_USE_HAS_ARM"
}
return "#LOOT_MARVIN_PROMPT_USE"
}
#endif // CLIENT
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// ###### ######## ####### ######## ## ## ## ## ### ######## ## ## #### ## ##
// ## ## ## ## ## ## ## ## ## ### ### ## ## ## ## ## ## ## ### ##
// ## ## ## ## ## ## #### #### #### ## ## ## ## ## ## ## #### ##
// ###### ## ## ## ######## ## ## ### ## ## ## ######## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ## ## ######### ## ## ## ## ## ## ####
// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###
// ###### ## ####### ## ## ## ## ## ## ## ## ## ### #### ## ##
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
#if SERVER
void function OnUseStoryMarvin( entity marvin, entity playerUser, int useFlags )
{
thread OnUseStoryMarvin_Thread( marvin, playerUser )
}
#endif //SERVER
#if SERVER
void function OnUseStoryMarvin_Thread( entity marvin, entity playerUser )
{
const float AUDIO_LOG_LENGTH = 34.0
const float PATH_DIST_FOR_REACTION_LINE = 1080.0
EndSignal( marvin, "OnDeath" )
marvin.UnsetUsable()
EmitSoundOnEntity( marvin, SFX_STORY_MARVIN_LOG )
wait AUDIO_LOG_LENGTH + 2.0
marvin.SetUsable()
if ( IsAlive( playerUser ) && IsPlayerPathfinder( playerUser ) )
{
/*if ( PlayerDeliveryShouldBeUrgent( playerUser, playerUser.GetOrigin() ) )
return*/
if ( Distance( playerUser.GetOrigin(), marvin.GetOrigin() ) <= PATH_DIST_FOR_REACTION_LINE )
PlayBattleChatterLineToSpeakerAndTeam( playerUser, "path_story_marvin_reaction" )
}
}
#endif
#if SERVER || CLIENT
bool function IsPlayerPathfinder( entity player )
{
/*ItemFlavor character = LoadoutSlot_GetItemFlavor( ToEHI( player ), Loadout_Character() )
string characterRef = ItemFlavor_GetCharacterRef( character ).tolower()
if ( characterRef != "character_pathfinder" )
return false
*/
return true
}
#endif
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// ######## ######## #### ###### ###### ######## ######## ######
// ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ## ## ##
// ## ######## ## ## #### ## #### ###### ######## ######
// ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## ## ## ## ## ## ## ## ## ## ##
// ## ## ## #### ###### ###### ######## ## ## ######
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
#if SERVER
void functionref( entity trigger, entity ent ) function CreateOnEnterLootMarvinTriggerFunc( entity marvin, MarvinData data )
{
return void function( entity trigger, entity ent ) : ( marvin, data )
{
OnEnterLootMarvinTrigger( trigger, ent, marvin, data )
}
}
#endif //SERVER
#if SERVER
void functionref( entity trigger, entity ent ) function CreateOnLeaveLootMarvinTriggerFunc( entity marvin, MarvinData data )
{
return void function( entity trigger, entity ent ) : ( marvin, data )
{
thread OnLeaveLootMarvinTrigger( trigger, ent, marvin, data )
}
}
#endif //SERVER
#if SERVER
void function OnEnterLootMarvinTrigger( entity trigger, entity ent, entity marvin, MarvinData data )
{
if ( !IsValid( ent ) || !ent.IsPlayer() )
return
if ( !IsAlive( marvin ) )
return
//marvin.SetThinkDuringAnimation( true )
Signal( marvin, SIGNAL_PLAYER_ENTERED_MARVIN_TRIGGER )
if ( data.marvinState != eMarvinState.READY_FOR_POWERUP )
return
PIN_Interact ( ent, "loot_marvin_power_up" ) //have checked that ent is a player above
thread TryMarvinPowerUp( marvin, data )
}
#endif //SERVER
#if SERVER
void function OnLeaveLootMarvinTrigger( entity trigger, entity ent, entity marvin, MarvinData data )
{
if ( !IsValid( ent ) || !ent.IsPlayer() )
return
if ( !IsAlive( marvin ) )
return
array<entity> touchingPlayers
foreach ( entity touchEnt in trigger.GetTouchingEntities() )
{
if ( touchEnt.IsPlayer() )
touchingPlayers.append( touchEnt )
}
if ( touchingPlayers.len() > 0 )
return
EndSignal( marvin, "OnDeath" )
EndSignal( marvin, SIGNAL_MARVIN_ON_POWERDOWN )
EndSignal( marvin, SIGNAL_PLAYER_ENTERED_MARVIN_TRIGGER )
//marvin.SetThinkDuringAnimation( false )
if ( data.marvinState != eMarvinState.ACTIVE )
{
if ( data.marvinState == eMarvinState.POWERING_UP )
{
WaitSignal( marvin, SIGNAL_MARVIN_ON_ACTIVATED )
}
else
{
return
}
}
wait GetCurrentPlaylistVarFloat( "loot_marvin_wait_nearby_players_duration", DURATION_WAIT_FOR_PLAYERS_NEARBY )
PIN_Interact ( ent, "loot_marvin_power_down" ) //have checked that ent is a player above
thread TryPowerDownMarvin( marvin, data, false )
}
#endif //SERVER
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// ## ## ### #### ## ##
// ### ### ## ## ## ### ##
// #### #### ## ## ## #### ##
// ## ### ## ## ## ## ## ## ##
// ## ## ######### ## ## ####
// ## ## ## ## ## ## ###
// ## ## ## ## #### ## ##
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
#if SERVER
void function TryMarvinPowerUp( entity marvin, MarvinData data )
{
if ( !IsAlive( marvin ) )
return
EndSignal( marvin, "OnDeath" )
if ( data.marvinState == eMarvinState.POWERING_UP )
return
data.marvinState = eMarvinState.POWERING_UP
GradeFlagsClear( marvin, eGradeFlags.IS_OPEN ) // clear the recharging use prompt
GradeFlagsSet( marvin, eGradeFlags.IS_BUSY ) // busy use prompt
if ( data.hasDetachableArm )
{
int particleIdx = GetParticleSystemIndex( VFX_LOT_MARVIN_SPARK_ARM )
int vfxAttachIdx = marvin.LookupAttachment( "FX_L_FOREARM" )
data.armSparkFx = StartParticleEffectOnEntity_ReturnEntity( marvin, particleIdx, FX_PATTACH_POINT_FOLLOW, vfxAttachIdx )
EmitSoundOnEntity( marvin, SFX_MARVIN_SPARKS )
}
waitthread PlayAnimLootMarvin( marvin, data.startPoint, ANIM_LOOT_MARVIN_POWERUP )
data.marvinState = eMarvinState.ACTIVE
Signal( marvin, SIGNAL_MARVIN_ON_ACTIVATED )
thread PlayAnimLootMarvin( marvin, data.startPoint, ANIM_LOOT_MARVIN_ACTIVE_LOOP )
thread SlotMachineCycleThink( marvin, data )
//marvin.SetActivityModifier( ACT_MODIFIER_POWERED_DOWN, false )
GradeFlagsClear( marvin, eGradeFlags.IS_BUSY )
}
#endif //SERVER
#if SERVER
void function TryPowerDownMarvin( entity marvin, MarvinData data, bool shouldCooldown, bool playTransitionAnimToIdle = true )
{
if ( !IsAlive( marvin ) )
return
EndSignal( marvin, "OnDeath" )
if ( data.marvinState == eMarvinState.POWERING_DOWN )
return
data.marvinState = eMarvinState.POWERING_DOWN
Signal( marvin, SIGNAL_MARVIN_ON_POWERDOWN )
GradeFlagsSet( marvin, eGradeFlags.IS_BUSY ) // busy use prompt
if ( playTransitionAnimToIdle )
waitthread PlayAnimLootMarvin( marvin, data.startPoint, ANIM_LOOT_MARVIN_POWERDOWN )
thread PlayAnimLootMarvin( marvin, data.startPoint, ANIM_LOOT_MARVIN_POWERDOWN_IDLE )
if ( data.hasDetachableArm )
{
if ( IsValid( data.armSparkFx ) )
data.armSparkFx.Destroy()
StopSoundOnEntity( marvin, SFX_MARVIN_SPARKS )
}
if ( shouldCooldown )
{
data.marvinState = eMarvinState.DISABLED
GradeFlagsSet( marvin, eGradeFlags.IS_OPEN ) // cooldown use prompt
float cooldownDuration = GetCurrentPlaylistVarFloat( "loot_marvin_cooldown_duration", DURATION_COOLDOWN )
entity wp = CreateWaypoint_Custom( WAYPOINTTYPE_COOLDOWN )
wp.SetWaypointEntity( 0, marvin )
wp.SetOrigin( marvin.GetOrigin() + <0, 0, 66> )
wp.SetAngles( marvin.GetAngles() )
wp.SetWaypointGametime( 0, Time() )
wp.SetWaypointGametime( 1, Time() + cooldownDuration )
OnThreadEnd(
function() : ( wp )
{
if ( IsValid( wp ) )
wp.Destroy()
}
)
wait cooldownDuration
wp.Destroy()
}
else if ( data.hasMissingArmBeenAttached )
{
if ( IsValid( data.trigger ) )
data.trigger.Destroy()
data.marvinState = eMarvinState.PERMANENTLY_DISABLED
GradeFlagsSet( marvin, eGradeFlags.IS_LOCKED ) // permanently disabled
GradeFlagsClear( marvin, eGradeFlags.IS_BUSY ) // clear busy use prompt
return
}
data.marvinState = eMarvinState.READY_FOR_POWERUP
foreach ( entity touchEnt in data.trigger.GetTouchingEntities() )
{
if ( touchEnt.IsPlayer() )
thread TryMarvinPowerUp( marvin, data )
}
}
#endif
#if CLIENT
void function InstanceMarvinCooldownCreatedWP( entity wp )
{
entity marvin = wp.GetWaypointEntity( 0 )
//marvin.ai.secondaryWaypoint = wp
}
#endif
#if SERVER
void function LootAndStoryMarvin_OnDamaged( entity marvin, var damageInfo )
{
//marvin.SetThinkDuringAnimation( true )
// prevent an arc star impact from killing a MRVN
int damageSourceId = DamageInfo_GetDamageSourceIdentifier( damageInfo )
float damageAmount = DamageInfo_GetDamage( damageInfo )
int damageType = DamageInfo_GetDamageType( damageInfo )
if ( damageSourceId == eDamageSourceId.mp_weapon_grenade_emp && damageType != DMG_BLAST )
{
if ( marvin.GetHealth() - damageAmount <= 0.0 )
DamageInfo_ScaleDamage( damageInfo, 0.1 )
}
}
#endif //SERVER
#if SERVER
void function LootAndStoryMarvin_OnKilled( entity marvin, var damageInfo )
{
if ( marvin in file.spawnedMarvinData )
{
MarvinData data = file.spawnedMarvinData[marvin]
if ( data.hasDetachableArm )
{
int attachId = marvin.LookupAttachment( "FX_L_FOREARM" )
vector armOrigin = marvin.GetAttachmentOrigin( attachId )
vector armAngles = marvin.GetAttachmentAngles( attachId )
vector direction = AnglesToForward( armAngles )
if ( IsValid( data.armSparkFx ) )
data.armSparkFx.Destroy()
StopSoundOnEntity( marvin, SFX_MARVIN_SPARKS )
//marvin.SetBodygroupModelByIndex( marvin.FindBodygroup( BODYGROUP_LEFT_ARM ), BODYGROUP_LEFT_ARM_INDEX_DETACHED )
ThrowLootParams params
params.dropOrg = armOrigin
params.fwd = direction
params.ref = ITEM_MARVIN_ARM_REF
params.count = 1
params.player = null
params.deathBox = null
params.throwVelocityRange[0] = 25.0
params.throwVelocityRange[1] = 50.0
//entity loot = SURVIVAL_ThrowLootFromPointEx( params )
}
if ( IsValid( data.trigger ) )
data.trigger.Destroy()
if ( IsValid( data.chestWaypoint ) )
data.chestWaypoint.Destroy()
//PIN_PlayerItemDestruction( DamageInfo_GetAttacker( damageInfo ), ITEM_DESTRUCTION_TYPES.LOOT_MARVIN, { dropped_arm = data.hasDetachableArm } )
delete file.spawnedMarvinData[marvin]
}
}
#endif //SERVER
#if SERVER
bool function LootMarvinArm_OnPickup( entity marvinArm, entity playerUser, int pickupFlags, entity deathBox, int ornull desiredCount, LootData lootData )
{
/*bool result = PickupBackpackItem( marvinArm, playerUser, pickupFlags, deathBox, desiredCount )
if ( result )
Remote_CallFunction_NonReplay(playerUser, "ServerCallback_PromptPingLootMarvin", playerUser)*/
return false//result
}
#endif //SERVER
#if CLIENT
void function ServerCallback_PromptPingLootMarvin ( entity player )
{
/*AddOnscreenPromptFunction( "quickchat", void function( entity player ) {
Remote_ServerCallFunction("ClientCallback_PromptPingLootMarvin")
}, 6.0, "#PING_LOOT_MARVIN")*/
}
#endif
#if SERVER
void function ClientCallback_PromptPingLootMarvin ( entity player )
{
AttemptPingNearestValidMarvinForPlayer(player)
}
#endif
#if SERVER
void function AttemptPingNearestValidMarvinForPlayer( entity player )
{
// get all valid marvins who are available to have an arm attached
array<entity> validMarvins
foreach ( entity marvin, MarvinData data in file.spawnedMarvinData )
{
if ( !IsAlive( marvin ) || data.hasMissingArmBeenAttached || data.isStoryMarvin )
continue
validMarvins.append( marvin )
}
if ( validMarvins.len() == 0 )
return
array<ArrayDistanceEntry> allResults = ArrayDistanceResults( validMarvins, player.GetOrigin() )
allResults.sort( DistanceCompareClosest )
// get the nearest valid marvin in a safe area to ping
entity nearestMarvin
for ( int i = 0; i < allResults.len(); i++ )
{
entity marvin = allResults[i].ent
/*if ( !SURVIVAL_DeathFieldIsValid( Survival_GetPlayerRealm( player ) ) )
{
nearestMarvin = marvin
break
}
if ( SURVIVAL_PosInSafeZone( Survival_GetPlayerRealm( player ), marvin.GetOrigin() ) )
{
nearestMarvin = marvin
break
}*/
}
if ( !IsValid( nearestMarvin ) )
return
// ping the nearest valid marvin, only visible to the player who picked up the arm
entity wp = CreateWaypoint_Ping_Location( player, ePingType.LOOT_MARVIN, nearestMarvin, nearestMarvin.GetOrigin(), -1, false )
if ( IsValid( wp ) )
wp.SetAbsOrigin( nearestMarvin.GetOrigin() + <0, 0, 138> )
}
#endif
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// ###### ## ####### ######## ## ## ### ###### ## ## #### ## ## ########
// ## ## ## ## ## ## ### ### ## ## ## ## ## ## ## ### ## ##
// ## ## ## ## ## #### #### ## ## ## ## ## ## #### ## ##
// ###### ## ## ## ## ## ### ## ## ## ## ######### ## ## ## ## ######
// ## ## ## ## ## ## ## ######### ## ## ## ## ## #### ##
// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ##
// ###### ######## ####### ## ## ## ## ## ###### ## ## #### ## ## ########
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
const int WAYPOINT_IDX_STARTTIME = 0
const int WAYPOINT_IDX_EMOTICON = 0
const int WAYPOINT_IDX_HAS_SETTLED = 1
#if SERVER || CLIENT
bool function DoesPlayerHaveMarvinArmInInventory( entity player )
{
array<ConsumableInventoryItem> playerInventory = SURVIVAL_GetPlayerInventory( player )
foreach ( invItem in playerInventory )
{
LootData lootData = SURVIVAL_Loot_GetLootDataByIndex( invItem.type )
if ( lootData.ref == ITEM_MARVIN_ARM_REF )
return true
}
return false
}
#endif
#if SERVER
void functionref( entity marvin, entity player, int useFlags ) function CreateOnUseLootMarvinFunc( MarvinData data )
{
return void function( entity marvin, entity player, int useFlags ) : ( data )
{
thread DispenseLootFromMarvin( marvin, player, data )
}
}
#endif //SERVER
#if SERVER
void function DispenseLootFromMarvin( entity marvin, entity player, MarvinData data )
{
EndSignal( marvin, "OnDeath" )
if ( GradeFlagsHas( marvin, eGradeFlags.IS_OPEN ) || GradeFlagsHas( marvin, eGradeFlags.IS_BUSY ) || GradeFlagsHas( marvin, eGradeFlags.IS_LOCKED ) )
{
EmitSoundOnEntityOnlyToPlayer( marvin, player, SFX_MARVIN_DENY )
return
}
GradeFlagsSet( marvin, eGradeFlags.IS_BUSY ) // busy use prompt
// check if player has marvin arm
bool shouldAttachArm = false
if ( !data.hasMissingArmBeenAttached ) // defensive, technically should never get this far if arm has been attached.
shouldAttachArm = DoesPlayerHaveMarvinArmInInventory( player )
if ( shouldAttachArm )
{
//marvin.SetBodygroupModelByIndex( marvin.FindBodygroup( BODYGROUP_RIGHT_ARM ), BODYGROUP_RIGHT_ARM_INDEX_ATTACHED_SPECIAL )
data.hasMissingArmBeenAttached = true
SURVIVAL_RemoveFromPlayerInventory( player, ITEM_MARVIN_ARM_REF, 1 )
}
data.marvinState = eMarvinState.DISPENSING
// play appropriate loot emoticon sound
int lootEmoticonIdx = GetDesiredEmoticonIndex( data )
switch ( lootEmoticonIdx )
{
case eMarvinEmoticon.SAD:
EmitSoundOnEntity( marvin, SFX_LOOT_MARVIN_SLOT_INTERACT_SAD )
break
case eMarvinEmoticon.NEUTRAL:
EmitSoundOnEntity( marvin, SFX_LOOT_MARVIN_SLOT_INTERACT_NEUTRAL )
break
case eMarvinEmoticon.PLEASED:
EmitSoundOnEntity( marvin, SFX_LOOT_MARVIN_SLOT_INTERACT_PLEASED )
break
case eMarvinEmoticon.VERY_HAPPY:
EmitSoundOnEntity( marvin, SFX_LOOT_MARVIN_SLOT_INTERACT_VERY_HAPPY )
break
}
// show marvin/slot machine hand crank
if ( !shouldAttachArm )
{
waitthread PlayAnimLootMarvin( marvin, data.startPoint, ANIM_LOOT_MARVIN_SLOT_CRANK )
thread PlayAnimLootMarvin( marvin, data.startPoint, ANIM_LOOT_MARVIN_ACTIVE_LOOP )
//marvin.SetActivityModifier( ACT_MODIFIER_POWERED_DOWN, false )
}
while( !data.hasSlotMachineSettled )
WaitFrame()
data.hasSlotMachineSettled = false
string dispenseAnim
switch ( data.currentEmoticonIdx )
{
case eMarvinEmoticon.NEUTRAL:
dispenseAnim = ANIM_LOOT_MARVIN_DISPENSE_NEUTRAL
break
case eMarvinEmoticon.PLEASED:
dispenseAnim = ANIM_LOOT_MARVIN_DISPENSE_PLEASED
break
case eMarvinEmoticon.VERY_HAPPY:
dispenseAnim = ANIM_LOOT_MARVIN_DISPENSE_VERY_HAPPY
break
default:
dispenseAnim = ANIM_LOOT_MARVIN_DISPENSE_SAD
break
}
//marvin.SetActivityModifier( ACT_MODIFIER_POWERED_DOWN, true )
waitthread PlayAnimLootMarvin( marvin, data.startPoint, dispenseAnim )
string pinActionName = data.hasMissingArmBeenAttached ? "loot_marvin_dispense_arm" : "loot_marvin_dispense"
PIN_Interact (player, pinActionName)
bool shouldPowerDown = !data.hasMissingArmBeenAttached
thread TryPowerDownMarvin( marvin, data, shouldPowerDown, false )
}
#endif //SERVER
#if SERVER
void function LootMarvin_OnDispenseLootAnimEvent( entity marvin )
{
if ( !IsAlive( marvin ) )
return
if ( !(marvin in file.spawnedMarvinData) )
return
MarvinData data = file.spawnedMarvinData[ marvin ]
string lootGroup
switch ( data.currentEmoticonIdx )
{
case eMarvinEmoticon.NEUTRAL:
lootGroup = "loot_roller_contents_rare"
break
case eMarvinEmoticon.PLEASED:
lootGroup = "marvin_contents_epic"
break
case eMarvinEmoticon.VERY_HAPPY:
lootGroup = "loot_roller_contents_legendary"
break
default:
lootGroup = "loot_roller_contents_common"
break
}
EmitSoundOnEntity( marvin, SFX_LOOT_MARVIN_DISPERSE )
thread PlayLootDisperseFx_Thread ( marvin, data.currentEmoticonIdx )
vector chestOrigin = marvin.GetAttachmentOrigin( marvin.LookupAttachment( "SCREEN_CENTER" ) )
int lootThrowVecIdx = 0
array<vector> lootThrowVectors
lootThrowVectors.append( FlattenVec( RotateVector( marvin.GetForwardVector(), <0, -45, 0> ) ) )
lootThrowVectors.append( marvin.GetForwardVector() )
lootThrowVectors.append( FlattenVec( RotateVector( marvin.GetForwardVector(), <0, 45, 0> ) ) )
array<string> marvinLootRefs = SURVIVAL_GetMultipleWeightedItemsFromGroup( lootGroup, MAX_LOOT_ITEMS_FROM_MARVIN )
if ( lootGroup == "loot_roller_contents_legendary" )
{
marvinLootRefs.pop()
marvinLootRefs.append( SURVIVAL_GetWeightedItemFromGroup( "gold_any" ) )
}
foreach ( int lootIdx, string itemRef in marvinLootRefs )
{
vector direction = lootThrowVectors[ lootThrowVecIdx ]
ThrowLootParams params
params.dropOrg = chestOrigin
params.fwd = direction
params.ref = itemRef
params.count = 1
params.player = null
params.deathBox = null
params.throwVelocityRange[0] = 25.0
params.throwVelocityRange[1] = 150.0
//entity loot = SURVIVAL_ThrowLootFromPointEx( params )
lootThrowVecIdx++
if ( lootThrowVecIdx > lootThrowVectors.len() - 1 )
lootThrowVecIdx = 0
}
}
#endif
#if SERVER
void function PlayLootDisperseFx_Thread ( entity marvin, int currentEmoticonIdx )
{
int lootRarity = currentEmoticonIdx + 1
int particleIdx = GetParticleSystemIndex( VFX_LOT_MARVIN_DISPERSE )
int vfxAttachIdx = marvin.LookupAttachment( "SCREEN_CENTER" )
//Given ( entity, particleSystemIndex, FX_PATTACH_ attachType, attachmentIndex ),
entity fxHandle = StartParticleEffectOnEntity_ReturnEntity( marvin, particleIdx, FX_PATTACH_POINT_FOLLOW, vfxAttachIdx )
vector rarityColor = GetFXRarityColorForTier( lootRarity )
EffectSetControlPointVector( fxHandle, 1, rarityColor )
wait 1
if ( IsValid (fxHandle) )
fxHandle.Destroy()
}
void function SlotMachineCycleThink( entity marvin, MarvinData data )
{
EndSignal( marvin, "OnDeath" )
EndSignal( marvin, SIGNAL_MARVIN_ON_POWERDOWN )
EmitSoundOnEntity( marvin, SFX_LOOT_MARVIN_SLOT_LOOP )
OnThreadEnd(
function() : ( marvin, data )
{
if ( IsValid( data.chestWaypoint ) )
data.chestWaypoint.Destroy()
StopSoundOnEntity( marvin, SFX_LOOT_MARVIN_SLOT_LOOP )
}
)
Assert( !IsValid( data.chestWaypoint ), "Marvin already has a valid waypoint entity for his chest screen at: " + marvin.GetOrigin() )
// this number should be divisible by 0.1 so it plays nice between server and client
float cycleLength = GetCurrentPlaylistVarFloat( "marvin_slot_cycle_length", SLOT_MACHINE_CYCLE_LENGTH )
float cycleLengthServerSafe = cycleLength - 0.01 //extra safe way to keep server aligned with client. Sometimes waiting in clean tenths gets rounded up.
data.currentEmoticonIdx = eMarvinEmoticon.SAD
data.chestWaypoint = CreateWaypoint_Custom( WAYPOINTTYPE_SCREEN )
data.chestWaypoint.SetOrigin( marvin.GetOrigin() )
data.chestWaypoint.SetWaypointEntity( 0, marvin )
data.chestWaypoint.SetWaypointInt( WAYPOINT_IDX_EMOTICON, data.currentEmoticonIdx )
data.chestWaypoint.SetWaypointInt( WAYPOINT_IDX_HAS_SETTLED, 0 )
while( true )
{
data.chestWaypoint.SetWaypointGametime( WAYPOINT_IDX_STARTTIME, Time() )
wait cycleLengthServerSafe
int desiredEmoticonIdx = GetDesiredEmoticonIndex( data )
data.chestWaypoint.SetWaypointInt( WAYPOINT_IDX_EMOTICON, desiredEmoticonIdx )
data.currentEmoticonIdx = desiredEmoticonIdx
if ( data.marvinState == eMarvinState.DISPENSING )
break
}
data.chestWaypoint.SetWaypointInt( WAYPOINT_IDX_HAS_SETTLED, 1 )
data.hasSlotMachineSettled = true
StopSoundOnEntity( marvin, SFX_LOOT_MARVIN_SLOT_LOOP )
WaitForever()
}
#endif // SERVER
#if CLIENT
void function InstanceMarvinScreenCreatedWP( entity wp )
{
/*entity marvin = wp.GetWaypointEntity( 0 )
/*if( !IsValid( marvin ) )
{
thread Thread_HandleMarvinInvalid ( wp )
return
}
marvin.ai.primaryWaypoint = wp*/
}
/*void function Thread_HandleMarvinInvalid( entity wp )
{
entity marvin = wp.GetWaypointEntity( 0 )
while( !IsValid( marvin ) )
{
#if DEV
printf( "Loot Marvin has not yet replicated" )
#endif
marvin = wp.GetWaypointEntity( 0 )
WaitFrame()
}
marvin.ai.primaryWaypoint = wp
}*/
#endif
#if SERVER
int function GetDesiredEmoticonIndex( MarvinData data )
{
int desiredEmoticonIdx = 0
if ( data.hasMissingArmBeenAttached )
return eMarvinEmoticon.VERY_HAPPY
switch ( data.currentEmoticonIdx )
{
case eMarvinEmoticon.SAD:
desiredEmoticonIdx = eMarvinEmoticon.NEUTRAL
break
case eMarvinEmoticon.NEUTRAL:
desiredEmoticonIdx = eMarvinEmoticon.PLEASED
break
case eMarvinEmoticon.PLEASED:
desiredEmoticonIdx = eMarvinEmoticon.SAD
break
}
return desiredEmoticonIdx
}
#endif //SERVER
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
//
// ######## ## ## ####
// ## ## ## ## ##
// ## ## ## ## ##
// ######## ## ## ##
// ## ## ## ## ##
// ## ## ## ## ##
// ## ## ####### ####
//
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
// =================================================================================================================================
#if CLIENT
void function OnPlayerLifeStateChanged( entity player, int oldState, int newState )
{
if ( player == GetLocalViewPlayer() )
{
if ( newState != LIFE_ALIVE )
{
}
else if ( IsValid( player ) )
{
thread SetTopPriorityLootMarvin( player )
thread TrackNearestChestScreen( player )
thread TrackNearestCooldownIndicator( player )
}
}
}
#endif
#if CLIENT
void function TrackNearestChestScreen( entity player )
{
const float MAYA_SCREEN_WIDTH = 5.686
const float MAYA_SCREEN_HEIGHT = 4.512
//const asset SCREEN_RUI_ASSET = $"ui/marvin_chest_slot_machine.rpak"
EndSignal( player, "OnDeath" )
if ( file.chestScreenTopo == null )
file.chestScreenTopo = CreateRUITopology_Worldspace( <0, 0, 0>, <0, 0, 0>, MAYA_SCREEN_WIDTH, MAYA_SCREEN_HEIGHT )
//if ( file.chestScreenRui == null )
//file.chestScreenRui = RuiCreate( SCREEN_RUI_ASSET, file.chestScreenTopo, RUI_DRAW_WORLD, 0 )
float cycleLength = GetCurrentPlaylistVarFloat( "marvin_slot_cycle_length", SLOT_MACHINE_CYCLE_LENGTH )
//RuiSetFloat( file.chestScreenRui, "cycleLength", cycleLength )
//RuiSetBool( file.chestScreenRui, "isVisible", false )
OnThreadEnd(
function () : ()
{
//RuiSetBool( file.chestScreenRui, "isVisible", false )
}
)
while( true )
{
/*if ( IsValid( file.topPriorityLootMarvin ) && IsValid( file.topPriorityLootMarvin.ai.primaryWaypoint ) )
{
entity wp = file.topPriorityLootMarvin.ai.primaryWaypoint
RuiTopology_SetParent( file.chestScreenTopo, file.topPriorityLootMarvin, "SCREEN_CENTER" )
RuiSetGameTime( file.chestScreenRui, "startCycleTime", wp.GetWaypointGametime( WAYPOINT_IDX_STARTTIME ) )
RuiSetBool( file.chestScreenRui, "isVisible", true )
RuiSetInt( file.chestScreenRui, "emotionIdx", wp.GetWaypointInt( WAYPOINT_IDX_EMOTICON ) )
if ( wp.GetWaypointInt( WAYPOINT_IDX_HAS_SETTLED ) > 0 )
{
RuiSetBool( file.chestScreenRui, "shouldStop", true )
}
else
{
RuiSetBool( file.chestScreenRui, "shouldStop", false )
}
RuiSetGameTime( file.chestScreenRui, "startCycleTime", wp.GetWaypointGametime( WAYPOINT_IDX_STARTTIME ) )
}
else*/
{
//RuiSetBool( file.chestScreenRui, "isVisible", false )
}
WaitFrame()
}
}
#endif
#if CLIENT
void function TrackNearestCooldownIndicator( entity player )
{
EndSignal( player, "OnDeath" )
/*if ( file.cooldownRui == null )
{
file.cooldownRui = CreateCockpitRui( $"ui/wattson_ult_cooldown_timer_world.rpak", 1 )
RuiSetFloat3( file.cooldownRui, "worldPosOffset", <0, 0, 0> )
RuiSetBool( file.cooldownRui, "shouldDesaturate", true )
}
OnThreadEnd(
function () : ()
{
RuiSetBool( file.cooldownRui, "isVisible", false )
}
)*/
while( true )
{
//if ( IsValid( file.topPriorityLootMarvin ) && IsValid( file.topPriorityLootMarvin.ai.secondaryWaypoint ) )
{
/*entity wp = file.topPriorityLootMarvin.ai.secondaryWaypoint
RuiTrackFloat3( file.cooldownRui, "worldPos", wp, RUI_TRACK_ABSORIGIN_FOLLOW )
RuiSetGameTime( file.cooldownRui, "startTime", wp.GetWaypointGametime( 0 ) )
RuiSetGameTime( file.cooldownRui, "endTime", wp.GetWaypointGametime( 1 ) )
bool canTrace = false
bool isFar = Distance( player.EyePosition(), wp.GetOrigin() ) > 700.0
if ( !isFar )
{
TraceResults results = TraceLine( player.EyePosition(), wp.GetOrigin(), [player], TRACE_MASK_VISIBLE, TRACE_COLLISION_GROUP_NONE )
canTrace = results.fraction > 0.95
}
if ( isFar || !canTrace )
{
RuiSetBool( file.cooldownRui, "isVisible", false )
}
else
{
RuiSetBool( file.cooldownRui, "isVisible", true )
}*/
}
//else
{
//RuiSetBool( file.cooldownRui, "isVisible", false )
}
WaitFrame()
}
}
#endif
#if CLIENT
void function SetTopPriorityLootMarvin( entity player )
{
EndSignal( player, "OnDeath" )
EndSignal( player, "OnDestroy" )
while( true )
{
array<entity> allMarvins = GetEntArrayByScriptName( LOOT_MARVIN_SCRIPTNAME )
array<entity> validMarvins
foreach ( entity marvin in allMarvins )
{
if ( !IsAlive( marvin ) )
continue
// is the marvin within the view player's viewcone
float dot = DotProduct( AnglesToForward( player.CameraAngles() ), Normalize( marvin.GetOrigin() - player.CameraPosition() ) )
/*float scalar = GetFovScalar( player )
float minDot = cos( DEG_TO_RAD * DEFAULT_FOV * 1.3 * scalar )
bool isInView = dot > minDot
if ( isInView )
validMarvins.append( marvin )*/
}
array<ArrayDistanceEntry> allResults = ArrayDistanceResults( validMarvins, player.GetOrigin() )
allResults.sort( DistanceCompareClosest )
if ( allResults.len() > 0 )
file.topPriorityLootMarvin = allResults[ 0 ].ent
wait 0.2
}
}
#endif | 0 | 0.812422 | 1 | 0.812422 | game-dev | MEDIA | 0.960511 | game-dev | 0.800528 | 1 | 0.800528 |
xiaoye97/xiaoye97-BepInEx-Plugins | 1,377 | Craftopia/UndergroundPicker/UndergroundPicker.cs | using Oc;
using BepInEx;
using HarmonyLib;
using UnityEngine;
using BepInEx.Configuration;
namespace UndergroundPicker
{
[BepInPlugin("me.xiaoye97.plugin.Craftopia.UndergroundPicker", "UndergroundPicker", "1.0")]
public class UndergroundPicker : BaseUnityPlugin
{
public static OcInstallObjMng Inst;
private ConfigEntry<float> checkTime;
private float cd;
void Start()
{
checkTime = Config.Bind<float>("Setting", "CheckTime", 2, "每隔多长时间触发一次检测(秒)");
cd = checkTime.Value;
}
void Update()
{
if (cd > 0) cd -= Time.deltaTime;
else
{
cd = checkTime.Value;
TryPickup();
}
}
void TryPickup()
{
if(Inst == null)
{
if (SingletonMonoBehaviour<OcInstallObjMng>.Inst == null) return;
else Inst = SingletonMonoBehaviour<OcInstallObjMng>.Inst;
}
var pickers = Inst.transform.GetComponentsInChildren<OcPicker>();
foreach (var picker in pickers)
{
if (picker.transform.position.y < -1)
{
Traverse.Create(picker).Field("_PickupEventCmp").GetValue<OcPickupEvent>().PickupHold();
}
}
}
}
}
| 0 | 0.974103 | 1 | 0.974103 | game-dev | MEDIA | 0.769926 | game-dev | 0.975847 | 1 | 0.975847 |
ElunaLuaEngine/ElunaTrinityWotlk | 7,662 | src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ruby_sanctum.h"
#include "ScriptedCreature.h"
enum ZarithrianTexts
{
SAY_AGGRO = 0, // Alexstrasza has chosen capable allies.... A pity that I must END YOU!
SAY_KILL = 1, // You thought you stood a chance? - It's for the best.
SAY_ADDS = 2, // Turn them to ash, minions!
SAY_DEATH = 3, // HALION! I...
};
enum ZarithrianSpells
{
// General Zarithrian
SPELL_INTIMIDATING_ROAR = 74384,
SPELL_CLEAVE_ARMOR = 74367,
// Zarithrian Spawn Stalker
SPELL_SUMMON_FLAMECALLER = 74398,
// Onyx Flamecaller
SPELL_BLAST_NOVA = 74392,
SPELL_LAVA_GOUT = 74394
};
enum ZarithrianEvents
{
// General Zarithrian
EVENT_CLEAVE = 1,
EVENT_INTIDMDATING_ROAR,
EVENT_SUMMON_ADDS,
EVENT_SUMMON_ADDS2,
// Onyx Flamecaller
EVENT_BLAST_NOVA,
EVENT_LAVA_GOUT
};
enum ZarithrianMisc
{
SPLINE_GENERAL_EAST = 1,
SPLINE_GENERAL_WEST = 2,
POINT_GENERAL_ROOM = 3
};
// 39746 - General Zarithrian
struct boss_general_zarithrian : public BossAI
{
boss_general_zarithrian(Creature* creature) : BossAI(creature, DATA_GENERAL_ZARITHRIAN) { }
void Reset() override
{
_Reset();
if (instance->GetBossState(DATA_SAVIANA_RAGEFIRE) == DONE && instance->GetBossState(DATA_BALTHARUS_THE_WARBORN) == DONE)
{
me->RemoveUnitFlag(UNIT_FLAG_UNINTERACTIBLE);
me->SetImmuneToPC(false);
}
}
bool CanAIAttack(Unit const* target) const override
{
return (instance->GetBossState(DATA_SAVIANA_RAGEFIRE) == DONE && instance->GetBossState(DATA_BALTHARUS_THE_WARBORN) == DONE && BossAI::CanAIAttack(target));
}
void JustEngagedWith(Unit* who) override
{
BossAI::JustEngagedWith(who);
Talk(SAY_AGGRO);
events.ScheduleEvent(EVENT_CLEAVE, 8s);
events.ScheduleEvent(EVENT_INTIDMDATING_ROAR, 14s);
events.ScheduleEvent(EVENT_SUMMON_ADDS, 15s);
if (Is25ManRaid())
events.ScheduleEvent(EVENT_SUMMON_ADDS2, 16s);
}
// Override to not set adds in combat yet.
void JustSummoned(Creature* summon) override
{
summons.Summon(summon);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_DEATH);
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
summons.DespawnAll();
_DespawnAtEvade();
}
void KilledUnit(Unit* victim) override
{
if (victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SUMMON_ADDS:
Talk(SAY_ADDS);
[[fallthrough]];
case EVENT_SUMMON_ADDS2:
{
if (Creature* stalker1 = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_ZARITHRIAN_SPAWN_STALKER_1)))
stalker1->CastSpell(stalker1, SPELL_SUMMON_FLAMECALLER, true);
if (Creature* stalker2 = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_ZARITHRIAN_SPAWN_STALKER_2)))
stalker2->CastSpell(stalker2, SPELL_SUMMON_FLAMECALLER, true);
events.Repeat(45s);
break;
}
case EVENT_INTIDMDATING_ROAR:
DoCastSelf(SPELL_INTIMIDATING_ROAR);
events.Repeat(35s, 40s);
break;
case EVENT_CLEAVE:
DoCastVictim(SPELL_CLEAVE_ARMOR);
events.ScheduleEvent(EVENT_CLEAVE, 15s);
break;
default:
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
};
// 39814 - Onyx Flamecaller
struct npc_onyx_flamecaller : public ScriptedAI
{
npc_onyx_flamecaller(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), _lavaGoutCount(0) { }
void Reset() override
{
_events.Reset();
_lavaGoutCount = 0;
me->SetReactState(REACT_DEFENSIVE);
MoveToGeneral();
}
void JustEngagedWith(Unit* /*who*/) override
{
_events.ScheduleEvent(EVENT_BLAST_NOVA, 17s);
_events.ScheduleEvent(EVENT_LAVA_GOUT, 3s);
}
void EnterEvadeMode(EvadeReason /*why*/) override { }
void IsSummonedBy(WorldObject* /*summoner*/) override
{
// Let Zarithrian count as summoner.
if (Creature* zarithrian = _instance->GetCreature(DATA_GENERAL_ZARITHRIAN))
zarithrian->AI()->JustSummoned(me);
}
void MovementInform(uint32 type, uint32 pointId) override
{
if (type != SPLINE_CHAIN_MOTION_TYPE && pointId != POINT_GENERAL_ROOM)
return;
DoZoneInCombat();
}
void MoveToGeneral()
{
if (me->GetPositionY() < 500.0f)
me->GetMotionMaster()->MoveAlongSplineChain(POINT_GENERAL_ROOM, SPLINE_GENERAL_WEST, false);
else
me->GetMotionMaster()->MoveAlongSplineChain(POINT_GENERAL_ROOM, SPLINE_GENERAL_EAST, false);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BLAST_NOVA:
DoCastAOE(SPELL_BLAST_NOVA);
_events.Repeat(15s, 20s);
break;
case EVENT_LAVA_GOUT:
if (_lavaGoutCount >= 3)
{
_lavaGoutCount = 0;
_events.Repeat(8s);
break;
}
DoCastVictim(SPELL_LAVA_GOUT);
_lavaGoutCount++;
_events.Repeat(1s);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap _events;
InstanceScript* _instance;
uint8 _lavaGoutCount;
};
void AddSC_boss_general_zarithrian()
{
RegisterRubySanctumCreatureAI(boss_general_zarithrian);
RegisterRubySanctumCreatureAI(npc_onyx_flamecaller);
}
| 0 | 0.91294 | 1 | 0.91294 | game-dev | MEDIA | 0.992188 | game-dev | 0.941439 | 1 | 0.941439 |
vercidium-patreon/meshing | 2,369 | ChunkHeightmap.cs | namespace meshing;
public unsafe partial struct Chunk
{
public void OnVoxelAdded(int i, int j, int k)
{
int access = GetHeightmapAccess(i, k);
if (j < *(minAltitude + access))
*(minAltitude + access) = (byte)j;
var max = maxAltitude + access;
if (j >= *max)
*max = (byte)j;
}
public void OnVoxelRemoved(int i, int j, int k)
{
// Precalculate 1D array accesses
var hAccess = GetHeightmapAccess(i, k);
var xzAccess = i * Constants.ChunkSize + k * Constants.ChunkSizeSquared;
var access = xzAccess + j;
// Update the min
UpdateMinHeightmap(j, hAccess, access, xzAccess);
// Update the max
UpdateMaxHeightmap(j, hAccess, access, xzAccess);
}
void UpdateMinHeightmap(int j, int hAccess, int access, int xzAccess)
{
var min = minAltitude + hAccess;
// Bail if we didn't remove the lowest voxel
if (*min != j && *min != (byte)Constants.ChunkSize)
return;
// Calculate how far up to search
var chunkTop = xzAccess + Constants.ChunkSize;
var amount = chunkTop - access;
var ptr = voxels + access;
// Search up until we find a voxel
for (; amount > 0; amount--)
{
if (ptr++->index == 0)
continue;
// Store the Y part of the access in the heightmap
*min = (byte)(access & Constants.ChunkMask);
return;
}
// If no voxel was found
*min = (byte)Constants.ChunkSize;
}
void UpdateMaxHeightmap(int j, int hAccess, int access, int xzAccess)
{
var max = maxAltitude + hAccess;
// Bail if we didn't remove the highest voxel
if (*max != j && *max != 0)
return;
// Calculate how far down to search
var chunkBottom = xzAccess;
var amount = access - chunkBottom;
var ptr = voxels + access;
// Search down until we find a voxel
for (; amount > 0; amount--)
{
if (ptr--->index == 0)
continue;
// Store the Y part of the access in the heightmap
*max = (byte)(access & Constants.ChunkMask);
return;
}
// If no voxel was found
*max = 0;
}
}
| 0 | 0.906544 | 1 | 0.906544 | game-dev | MEDIA | 0.322574 | game-dev | 0.939905 | 1 | 0.939905 |
channeldorg/channeld-ue-plugin | 1,055 | Source/ChanneldUE/View/PlayerStartLocator.cpp | #include "PlayerStartLocator.h"
#include "EngineUtils.h"
#include "GameFramework/PlayerStart.h"
UPlayerStartLocatorBase::UPlayerStartLocatorBase(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
FVector UPlayerStartLocatorBase::GetPlayerStartPosition_Implementation(int64 ConnId, AActor*& StartSpot) const
{
if (auto Itr = TActorIterator<APlayerStart>(GetWorld()))
{
StartSpot = *Itr;
return StartSpot->GetActorLocation();
}
return FVector::ZeroVector;
}
UPlayerStartLocator_ModByConnId::UPlayerStartLocator_ModByConnId(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
FVector UPlayerStartLocator_ModByConnId::GetPlayerStartPosition_Implementation(int64 ConnId, AActor*& StartSpot) const
{
TArray<AActor*> PlayerStarts;
for (auto Itr = TActorIterator<APlayerStart>(GetWorld()); Itr; ++Itr)
{
PlayerStarts.Add(*Itr);
}
if (PlayerStarts.Num() > 0)
{
StartSpot = PlayerStarts[ConnId % PlayerStarts.Num()];
return StartSpot->GetActorLocation();
}
return FVector::ZeroVector;
}
| 0 | 0.84631 | 1 | 0.84631 | game-dev | MEDIA | 0.963357 | game-dev | 0.943445 | 1 | 0.943445 |
andyfischer/circa | 3,681 | src/symbols.cpp | // Copyright (c) Andrew Fischer. See LICENSE file for license terms.
#include "common_headers.h"
#include "hashtable.h"
#include "list.h"
#include "names_builtin.h"
#include "string_type.h"
#include "symbols.h"
#include "tagged_value.h"
#include "term.h"
#include "type.h"
namespace circa {
Value* g_runtimeSymbolMap; // Maps strings to Symbol values.
Value* g_runtimeSymbolTable; // List, associating Symbol values with strings.
int g_nextRuntimeSymbol = s_LastBuiltinName + 1;
Symbol string_to_symbol(const char* str)
{
// Find this name as an existing builtin symbol.
int foundBuiltin = builtin_symbol_from_string(str);
if (foundBuiltin != -1)
return foundBuiltin;
// Find this name as an existing runtime symbol.
Value strVal;
set_string(&strVal, str);
Value* foundRuntime = hashtable_get(g_runtimeSymbolMap, &strVal);
if (foundRuntime != NULL)
return as_symbol(foundRuntime);
// Create a new runtime symbol.
Value* newRuntime = hashtable_insert(g_runtimeSymbolMap, &strVal);
int index = g_nextRuntimeSymbol++;
set_int(newRuntime, index);
list_resize(g_runtimeSymbolTable, index+1);
set_value(list_get(g_runtimeSymbolTable, index), &strVal);
return index;
}
void set_symbol_from_string(Value* val, Value* str)
{
if (val == str) {
Value temp;
move(str, &temp);
return set_symbol_from_string(val, &temp);
}
set_symbol(val, string_to_symbol(as_cstring(str)));
}
void set_symbol_from_string(Value* val, const char* str)
{
set_symbol(val, string_to_symbol(str));
}
const char* symbol_as_string(Symbol symbol)
{
const char* builtinName = builtin_symbol_to_string(symbol);
if (builtinName != NULL)
return builtinName;
Value* tableVal = list_get(g_runtimeSymbolTable, symbol);
if (tableVal != NULL)
return as_cstring(tableVal);
return NULL;
}
const char* symbol_as_string(Value* symbol)
{
return symbol_as_string(as_symbol(symbol));
}
void symbol_to_string(Value* symbol, Value* str)
{
ca_assert(symbol != str);
const char* builtinName = builtin_symbol_to_string(as_symbol(symbol));
if (builtinName != NULL) {
set_string(str, builtinName);
return;
}
Value* tableVal = list_get(g_runtimeSymbolTable, as_symbol(symbol));
if (tableVal != NULL) {
ca_assert(is_string(tableVal));
copy(tableVal, str);
return;
}
set_string(str, "");
}
static void symbol_to_source_string(Value* value, Value* out)
{
string_append(out, ":");
string_append(out, symbol_as_string(value));
}
static int hash_func(Value* value)
{
return as_symbol(value);
}
bool symbol_eq(Value* val, Symbol s)
{
return is_symbol(val) && as_symbol(val) == s;
}
void symbol_initialize_global_table()
{
g_runtimeSymbolMap = new Value();
set_hashtable(g_runtimeSymbolMap);
g_runtimeSymbolTable = new Value();
set_list(g_runtimeSymbolTable, 0);
}
void symbol_deinitialize_global_table()
{
set_null(g_runtimeSymbolMap);
delete g_runtimeSymbolMap;
g_runtimeSymbolMap = NULL;
set_null(g_runtimeSymbolTable);
delete g_runtimeSymbolTable;
g_runtimeSymbolTable = NULL;
}
void symbol_setup_type(Type* type)
{
reset_type(type);
set_string(&type->name, "Symbol");
type->storageType = s_StorageTypeInt;
type->toString = symbol_to_source_string;
type->hashFunc = hash_func;
}
CIRCA_EXPORT const char* circa_symbol_text(Value* symbol)
{
return symbol_as_string(symbol);
}
CIRCA_EXPORT bool circa_symbol_equals(Value* symbol, const char* text)
{
return strcmp(symbol_as_string(symbol), text) == 0;
}
}
| 0 | 0.768257 | 1 | 0.768257 | game-dev | MEDIA | 0.314997 | game-dev | 0.79781 | 1 | 0.79781 |
Unity-Technologies/arfoundation-demos | 1,655 | Assets/UX/Scripts/DisableTrackedVisuals.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
public class DisableTrackedVisuals : MonoBehaviour
{
[SerializeField]
[Tooltip("Disables spawned feature points and the ARPointCloudManager")]
bool m_DisableFeaturePoints;
public bool disableFeaturePoints
{
get => m_DisableFeaturePoints;
set => m_DisableFeaturePoints = value;
}
[SerializeField]
[Tooltip("Disables spawned planes and ARPlaneManager")]
bool m_DisablePlaneRendering;
public bool disablePlaneRendering
{
get => m_DisablePlaneRendering;
set => m_DisablePlaneRendering = value;
}
[SerializeField]
ARPointCloudManager m_PointCloudManager;
public ARPointCloudManager pointCloudManager
{
get => m_PointCloudManager;
set => m_PointCloudManager = value;
}
[SerializeField]
ARPlaneManager m_PlaneManager;
public ARPlaneManager planeManager
{
get => m_PlaneManager;
set => m_PlaneManager = value;
}
void OnEnable()
{
PlaceObjectsOnPlane.onPlacedObject += OnPlacedObject;
}
void OnDisable()
{
PlaceObjectsOnPlane.onPlacedObject -= OnPlacedObject;
}
void OnPlacedObject()
{
if (m_DisableFeaturePoints)
{
m_PointCloudManager.SetTrackablesActive(false);
m_PointCloudManager.enabled = false;
}
if (m_DisablePlaneRendering)
{
m_PlaneManager.SetTrackablesActive(false);
m_PlaneManager.enabled = false;
}
}
}
| 0 | 0.655449 | 1 | 0.655449 | game-dev | MEDIA | 0.627165 | game-dev | 0.822451 | 1 | 0.822451 |
TheAssemblyArmada/Vanilla-Conquer | 9,984 | redalert/teamtype.h | //
// Copyright 2020 Electronic Arts Inc.
//
// TiberianDawn.DLL and RedAlert.dll and corresponding source code is free
// software: you can redistribute it and/or modify it under the terms of
// the GNU General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
// TiberianDawn.DLL and RedAlert.dll and corresponding source code is distributed
// in the hope that it will be useful, but with permitted additional restrictions
// under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT
// distributed with this program. You should have received a copy of the
// GNU General Public License along with permitted additional restrictions
// with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection
/* $Header: /CounterStrike/TEAMTYPE.H 1 3/03/97 10:25a Joe_bostic $ */
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
***********************************************************************************************
* *
* Project Name : Command & Conquer *
* *
* File Name : TEAMTYPE.H *
* *
* Programmer : Joe L. Bostic *
* *
* Start Date : 07/02/96 *
* *
* Last Update : July 2, 1996 [JLB] *
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#ifndef TEAMTYPE_H
#define TEAMTYPE_H
#include "endianness.h"
/*
** TeamMissionType: the various missions that a team can have.
*/
typedef enum TeamMissionType : char
{
TMISSION_NONE = -1,
TMISSION_ATTACK, // Attack specified quarry type.
TMISSION_ATT_WAYPT, // Attack specified waypoint
TMISSION_FORMATION, // Change formation of team.
TMISSION_MOVE, // moves to waypoint specified.
TMISSION_MOVECELL, // moves to cell # specified.
TMISSION_GUARD, // works like an infantry's guard mission
TMISSION_LOOP, // loop back to start of mission list
TMISSION_ATTACKTARCOM, // attack tarcom
TMISSION_UNLOAD, // Unload at current location.
TMISSION_DEPLOY, // Deploy mobile building type.
TMISSION_HOUND_DOG, // Follow nearest friendly unit.
TMISSION_DO, // Do guard, sticky, area guard (mission sticks on this).
TMISSION_SET_GLOBAL, // Set global variable.
TMISSION_INVULNERABLE, // Magical invulnerability.
TMISSION_LOAD, // Load onto transport member of team.
TMISSION_SPY, // Spy enter the building at specified waypoint
TMISSION_PATROL, // Move but look for enemies as well.
TMISSION_COUNT,
TMISSION_FIRST = 0
} TeamMissionType;
/*
** Forward declarations.
*/
class TechnoTypeClass;
/*
** This structure contains one team mission value & its argument.
*/
class TeamMissionClass
{
public:
#if defined(CHEAT_KEYS) || defined(SCENARIO_EDITOR)
char const* Description(int index) const;
operator const char*() const
{
return (Description(0));
};
#endif
void Draw_It(int index, int x, int y, int width, int height, bool selected, TextPrintType flags);
TeamMissionType Mission; // Mission type.
union
{
struct
{
#ifdef __BIG_ENDIAN__
unsigned char __padding_1[3];
#endif
union
{
FormationType Formation; // Formation to use.
QuarryType Quarry; // Combat quarry type.
MissionType Mission; // General mission orders.
};
};
int Value; // Usually a waypoint number.
} Data;
};
/*
** This class specifies the quantity and type of members desired for the
** team.
*/
class TeamMemberClass
{
public:
int Quantity; // Number of objects desired for this type.
TechnoTypeClass const* Class; // The type of object desired.
};
/*
** TeamTypeClass declaration
*/
class TeamTypeClass : public AbstractTypeClass
{
public:
enum TeamTypeClassEnums
{
MAX_TEAM_CLASSCOUNT = 5,
MAX_TEAM_MISSIONS = 20
};
/*
** Constructor/Destructor
*/
TeamTypeClass(void);
TeamTypeClass(NoInitClass const& x)
: AbstractTypeClass(x)
, Trigger(x){};
virtual ~TeamTypeClass(void){};
static void* operator new(size_t) noexcept;
static void* operator new(size_t, void* ptr)
{
return (ptr);
};
static void operator delete(void* ptr);
static void operator delete(void*, void*)
{
}
/*
** Initialization: clears all team types in preparation for new scenario
*/
static void Init(void);
/*
** File I/O routines
*/
void Build_INI_Entry(char* buffer);
static void Read_INI(CCINIClass& ini);
void Fill_In(char* name, char* entry);
static void Write_INI(CCINIClass& ini);
static const char* INI_Name(void)
{
return "TeamTypes";
};
void Code_Pointers(void);
void Decode_Pointers(void);
/*
** As_Pointer gets a pointer to the trigger object give its name
*/
static TeamTypeClass* As_Pointer(char const* name);
/*
** Processing routines
*/
TeamClass* Create_One_Of(void) const;
void Destroy_All_Of(void) const;
void Detach(TARGET target, bool all = true);
/*
** Utility routines
*/
void Draw_It(int index, int x, int y, int width, int height, bool selected, TextPrintType flags) const;
static char const* Name_From_Mission(TeamMissionType order);
static TeamMissionType Mission_From_Name(char const* name);
static TeamTypeClass const*
Suggested_New_Team(HouseClass* house, int atypes, int utypes, int itypes, int vtypes, bool alerted);
static TeamTypeClass* From_Name(char const* name);
bool Edit(void);
#if defined(CHEAT_KEYS) || defined(SCENARIO_EDITOR)
char const* Member_Description(void) const;
char const* Description(void) const;
operator const char*(void) const
{
return (Description());
};
#endif
/*
** If this teamtype object is active, then this flag will be true.
** TeamType objects that are not active are either not yet created or have
** been deleted after fulfilling their action.
*/
unsigned IsActive : 1;
/*
** If RoundAbout, the team avoids high-threat areas
*/
unsigned IsRoundAbout : 1;
/*
** If Suicide, the team won't stop until it achieves its mission or it's
** dead
*/
unsigned IsSuicide : 1;
/*
** Is this team type allowed to be created automatically by the computer
** when the appropriate trigger indicates?
*/
unsigned IsAutocreate : 1;
/*
** This flag tells the computer that it should build members to fill
** a team of this type regardless of whether there actually is a team
** of this type active.
*/
unsigned IsPrebuilt : 1;
/*
** If this team should allow recruitment of new members, then this flag
** will be true. A false value results in a team that fights until it
** is dead. This is similar to IsSuicide, but they will defend themselves.
*/
unsigned IsReinforcable : 1;
/*
** A transient team type was created exclusively to bring on reinforcements
** as a result of some special event. As soon as there are no teams
** existing of this type, then this team type should be deleted.
*/
unsigned IsTransient : 1;
/*
** Priority given the team for recruiting purposes; higher priority means
** it can steal members from other teams (scale: 0 - 15)
*/
int RecruitPriority;
/*
** Initial # of this type of team
*/
unsigned char InitNum;
/*
** Max # of this type of team allowed at one time
*/
unsigned char MaxAllowed;
/*
** Fear level of this team
*/
unsigned char Fear;
/*
** House the team belongs to
*/
HousesType House;
/*
** Trigger to assign to each object as it joins this team.
*/
CCPtr<TriggerTypeClass> Trigger;
/*
** This is the waypoint origin to use when creating this team or
** when bringing the team on as a reinforcement.
*/
WAYPOINT Origin;
/*
** This records the number of teams of this type that are currently
** active.
*/
int Number;
/*
** Number and list of missions that this team will follow.
*/
int MissionCount;
TeamMissionClass MissionList[MAX_TEAM_MISSIONS];
/*
** Number and type of members desired for this team.
*/
int ClassCount;
TeamMemberClass Members[MAX_TEAM_CLASSCOUNT];
/*
** Some additional padding in case we need to add data to the class and maintain backwards compatibility for
*save/load
*/
static char const* TMissions[TMISSION_COUNT];
};
#endif
| 0 | 0.95054 | 1 | 0.95054 | game-dev | MEDIA | 0.927082 | game-dev | 0.853083 | 1 | 0.853083 |
PocketMine/PocketMine-MP | 1,165 | src/pocketmine/item/SpiderEye.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\item;
use pocketmine\entity\Effect;
class SpiderEye extends Food{
public function __construct($meta = 0, $count = 1){
parent::__construct(self::SPIDER_EYE, $meta, $count, "Spider Eye");
}
public function getFoodRestore() : int{
return 2;
}
public function getSaturationRestore() : float{
return 3.2;
}
public function getAdditionalEffects() : array{
return [Effect::getEffect(Effect::POISON)->setDuration(80)];
}
}
| 0 | 0.577511 | 1 | 0.577511 | game-dev | MEDIA | 0.927335 | game-dev | 0.780552 | 1 | 0.780552 |
shatteredmoon/open-rum | 4,227 | ultima/scripts/client/broadcasts/abyss_altar_test.nut | // Received from the server after looking at an Abyss altar
class Abyss_Altar_Test_Broadcast extends rumBroadcast
{
var1 = 0; // Test phase
var2 = 0; // Response
constructor( ... )
{
base.constructor();
if( vargv.len() > 0 )
{
var1 = vargv[0];
if( vargv.len() > 1 )
{
var2 = vargv[1];
}
}
}
function OnRecv()
{
local ePhase = var1;
if( U4_AbyssAltarPhaseType.Virtue == ePhase )
{
ShowString( "" );
local ciPlayer = ::rumGetMainPlayer();
local ciMap = ciPlayer.GetMap();
local iLevel = ciMap.GetProperty( Map_Level_PropertyID, 0 );
if( iLevel > 0 )
{
local strQuestion = format( "u4_command_look_abyss_altar_question_%d_client_StringID", iLevel );
local strPrompt = format( "%s \"%s\"", ::rumGetString( u4_command_look_abyss_altar_client_StringID ),
::rumGetStringByName( strQuestion ) );
ShowString( strPrompt, g_strColorTagArray.Cyan );
g_ciUI.m_ciGameInputTextBox.Clear();
g_ciUI.m_ciGameInputTextBox.ShowPrompt( false );
g_ciUI.m_ciGameInputTextBox.SetInputMode( InputMode.Text_Response, QuestionCallback );
}
}
else if( U4_AbyssAltarPhaseType.Stone == ePhase )
{
ShowString( "" );
ShowString( ::rumGetString( u4_command_look_abyss_altar_prompt_client_StringID ), g_strColorTagArray.Cyan );
local ciPlayer = ::rumGetMainPlayer();
local iFlags = ciPlayer.GetProperty( U4_Item_Stones_PropertyID, 0 );
if( iFlags )
{
g_ciUI.m_ciGameListView.Clear();
g_ciUI.m_ciGameListView.DisableMultiSelect();
g_ciUI.m_ciGameListView.SetFormat( "0.05" );
local strEntry;
for( local eVirtue = 0; eVirtue < VirtueType.NumVirtues; ++eVirtue )
{
if( ::rumBitOn( iFlags, eVirtue ) )
{
strEntry = ::rumGetString( g_eU4StoneStringArray[eVirtue] );
g_ciUI.m_ciGameListView.SetEntry( eVirtue, strEntry );
}
}
CalculateListViewSize( g_ciUI.m_ciGameListView, "default", 6 );
g_ciUI.m_ciGameListView.m_funcAccept = StoneCallback;
g_ciUI.m_ciGameListView.m_funcCancel = Ultima_ListSelectionEnd;
g_ciUI.m_ciGameListView.SetActive( true );
g_ciUI.m_ciGameListView.Focus();
}
}
else if( U4_AbyssAltarPhaseType.Codex == ePhase )
{
ShowString( "" );
ShowString( ::rumGetString( u4_codex_chamber_client_StringID ), g_strColorTagArray.Yellow );
}
}
function StoneCallback()
{
// The player selected a stone
local eStoneType = g_ciUI.m_ciGameListView.GetSelectedKey();
local strDesc = g_ciUI.m_ciGameListView.GetCurrentEntry();
ShowString( strDesc );
local ciBroadcast = ::rumCreate( Abyss_Altar_Test_BroadcastID, U4_AbyssAltarPhaseType.Stone, eStoneType );
::rumSendBroadcast( ciBroadcast );
Ultima_ListSelectionEnd();
}
function QuestionCallback( ... )
{
g_ciUI.m_ciGameInputTextBox.Clear();
if( vargv.len() > 0 )
{
// The player provided an answer, send it to the server for handling
local strAnswer = vargv[0];
ShowString( strAnswer );
local strVirtue = strAnswer.tolower();
// Rebuild the localized virtue table
VirtueLoc.resize( VirtueType.NumVirtues );
for( local eVirtue = 0; eVirtue < VirtueType.NumVirtues; ++eVirtue )
{
VirtueLoc[eVirtue] = ::rumGetString( g_eU4VirtueStringArray[eVirtue] ).tolower();
}
// See if the provided answer matches anything in the localized virtue table
local eVirtue = -1;
for( local i = 0; -1 == eVirtue, i < VirtueLoc.len(); ++i )
{
// Does the typed keyword match any virtues in the localized virtue table?
if( strVirtue == VirtueLoc[i] )
{
// The index of the virtue in the table
eVirtue = i;
}
}
local ciBroadcast = ::rumCreate( Abyss_Altar_Test_BroadcastID, U4_AbyssAltarPhaseType.Virtue, eVirtue );
::rumSendBroadcast( ciBroadcast );
}
else
{
// The player did not respond with an answer
ShowString( "" );
}
}
}
| 0 | 0.911445 | 1 | 0.911445 | game-dev | MEDIA | 0.706186 | game-dev | 0.956931 | 1 | 0.956931 |
OsBelief/Cocos2d-JS-Game | 31,451 | FindYourSister/frameworks/cocos2d-html5/extensions/ccui/uiwidgets/UIButton.js | /****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* Base class for ccui.Button
* @class
* @extends ccui.Widget
*
* @property {String} titleText - The content string of the button title
* @property {String} titleFont - The content string font of the button title
* @property {Number} titleFontSize - The content string font size of the button title
* @property {String} titleFontName - The content string font name of the button title
* @property {cc.Color} titleFontColor - The content string font color of the button title
* @property {Boolean} pressedActionEnabled - Indicate whether button has zoom effect when clicked
*/
ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
_buttonNormalRenderer: null,
_buttonClickedRenderer: null,
_buttonDisableRenderer: null,
_titleRenderer: null,
_normalFileName: "",
_clickedFileName: "",
_disabledFileName: "",
_prevIgnoreSize: true,
_scale9Enabled: false,
_capInsetsNormal: null,
_capInsetsPressed: null,
_capInsetsDisabled: null,
_normalTexType: ccui.Widget.LOCAL_TEXTURE,
_pressedTexType: ccui.Widget.LOCAL_TEXTURE,
_disabledTexType: ccui.Widget.LOCAL_TEXTURE,
_normalTextureSize: null,
_pressedTextureSize: null,
_disabledTextureSize: null,
pressedActionEnabled: false,
_titleColor: null,
_normalTextureScaleXInSize: 1,
_normalTextureScaleYInSize: 1,
_pressedTextureScaleXInSize: 1,
_pressedTextureScaleYInSize: 1,
_normalTextureLoaded: false,
_pressedTextureLoaded: false,
_disabledTextureLoaded: false,
_className: "Button",
_normalTextureAdaptDirty: true,
_pressedTextureAdaptDirty: true,
_disabledTextureAdaptDirty: true,
_fontName: "Thonburi",
_fontSize: 12,
_type: 0,
/**
* allocates and initializes a UIButton.
* Constructor of ccui.Button
* @constructor
* @example
* // example
* var uiButton = new ccui.Button();
*/
ctor: function (normalImage, selectedImage, disableImage, texType) {
this._capInsetsNormal = cc.rect(0, 0, 0, 0);
this._capInsetsPressed = cc.rect(0, 0, 0, 0);
this._capInsetsDisabled = cc.rect(0, 0, 0, 0);
this._normalTextureSize = cc.size(0, 0);
this._pressedTextureSize = cc.size(0, 0);
this._disabledTextureSize = cc.size(0, 0);
this._titleColor = cc.color.WHITE;
ccui.Widget.prototype.ctor.call(this);
this.setTouchEnabled(true);
texType && this.init(normalImage, selectedImage, disableImage, texType);
},
init: function (normalImage, selectedImage,disableImage, texType) {
if (ccui.Widget.prototype.init.call(this)) {
if(normalImage === undefined)
return true;
this.loadTextures(normalImage, selectedImage,disableImage, texType);
}
return false;
},
_initRenderer: function () {
this._buttonNormalRenderer = cc.Sprite.create();
this._buttonClickedRenderer = cc.Sprite.create();
this._buttonDisableRenderer = cc.Sprite.create();
this._titleRenderer = cc.LabelTTF.create("");
this._titleRenderer.setAnchorPoint(0.5, 0.5);
this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1);
this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1);
this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1);
this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1);
},
/**
* Sets if button is using scale9 renderer.
* @param {Boolean} able true that using scale9 renderer, false otherwise.
*/
setScale9Enabled: function (able) {
if (this._scale9Enabled == able)
return;
this._brightStyle = ccui.Widget.BRIGHT_STYLE_NONE;
this._scale9Enabled = able;
this.removeProtectedChild(this._buttonNormalRenderer);
this.removeProtectedChild(this._buttonClickedRenderer);
this.removeProtectedChild(this._buttonDisableRenderer);
if (this._scale9Enabled) {
this._buttonNormalRenderer = cc.Scale9Sprite.create();
this._buttonClickedRenderer = cc.Scale9Sprite.create();
this._buttonDisableRenderer = cc.Scale9Sprite.create();
} else {
this._buttonNormalRenderer = cc.Sprite.create();
this._buttonClickedRenderer = cc.Sprite.create();
this._buttonDisableRenderer = cc.Sprite.create();
}
this.loadTextureNormal(this._normalFileName, this._normalTexType);
this.loadTexturePressed(this._clickedFileName, this._pressedTexType);
this.loadTextureDisabled(this._disabledFileName, this._disabledTexType);
this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1);
this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1);
this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1);
if (this._scale9Enabled) {
var ignoreBefore = this._ignoreSize;
this.ignoreContentAdaptWithSize(false);
this._prevIgnoreSize = ignoreBefore;
} else {
this.ignoreContentAdaptWithSize(this._prevIgnoreSize);
}
this.setCapInsetsNormalRenderer(this._capInsetsNormal);
this.setCapInsetsPressedRenderer(this._capInsetsPressed);
this.setCapInsetsDisabledRenderer(this._capInsetsDisabled);
this.setBright(this._bright);
},
/**
* Get button is using scale9 renderer or not.
* @returns {Boolean}
*/
isScale9Enabled: function () {
return this._scale9Enabled;
},
ignoreContentAdaptWithSize: function (ignore) {
if (!this._scale9Enabled || (this._scale9Enabled && !ignore)) {
ccui.Widget.prototype.ignoreContentAdaptWithSize.call(this, ignore);
this._prevIgnoreSize = ignore;
}
},
getVirtualRendererSize: function(){
return cc.size(this._normalTextureSize);
},
/**
* Load textures for button.
* @param {String} normal
* @param {String} selected
* @param {String} disabled
* @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
*/
loadTextures: function (normal, selected, disabled, texType) {
this.loadTextureNormal(normal, texType);
this.loadTexturePressed(selected, texType);
this.loadTextureDisabled(disabled, texType);
},
/**
* Load normal state texture for button.
* @param {String} normal
* @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
*/
loadTextureNormal: function (normal, texType) {
if (!normal)
return;
texType = texType || ccui.Widget.LOCAL_TEXTURE;
this._normalFileName = normal;
this._normalTexType = texType;
var self = this;
if(!this._buttonNormalRenderer.texture || !this._buttonNormalRenderer.texture.isLoaded()){
this._buttonNormalRenderer.addLoadedEventListener(function(){
self._findLayout();
self._normalTextureSize = self._buttonNormalRenderer.getContentSize();
self._updateFlippedX();
self._updateFlippedY();
self._updateChildrenDisplayedRGBA();
self._buttonNormalRenderer.setColor(self.getColor());
self._buttonNormalRenderer.setOpacity(self.getOpacity());
self._updateContentSizeWithTextureSize(self._normalTextureSize);
self._normalTextureLoaded = true;
self._normalTextureAdaptDirty = true;
});
}
if (this._scale9Enabled) {
var normalRendererScale9 = this._buttonNormalRenderer;
switch (this._normalTexType){
case ccui.Widget.LOCAL_TEXTURE:
normalRendererScale9.initWithFile(normal);
break;
case ccui.Widget.PLIST_TEXTURE:
normalRendererScale9.initWithSpriteFrameName(normal);
break;
default:
break;
}
normalRendererScale9.setCapInsets(this._capInsetsNormal);
} else {
var normalRenderer = this._buttonNormalRenderer;
switch (this._normalTexType){
case ccui.Widget.LOCAL_TEXTURE:
//SetTexture cannot load resource
normalRenderer.initWithFile(normal);
break;
case ccui.Widget.PLIST_TEXTURE:
//SetTexture cannot load resource
normalRenderer.initWithSpriteFrameName(normal);
break;
default:
break;
}
}
this._normalTextureSize = this._buttonNormalRenderer.getContentSize();
this._updateFlippedX();
this._updateFlippedY();
this._updateChildrenDisplayedRGBA();
this._updateContentSizeWithTextureSize(this._normalTextureSize);
this._normalTextureLoaded = true;
this._normalTextureAdaptDirty = true;
},
/**
* Load selected state texture for button.
* @param {String} selected
* @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
*/
loadTexturePressed: function (selected, texType) {
if (!selected)
return;
texType = texType || ccui.Widget.LOCAL_TEXTURE;
this._clickedFileName = selected;
this._pressedTexType = texType;
var self = this;
if(!this._buttonClickedRenderer.texture || !this._buttonClickedRenderer.texture.isLoaded()){
this._buttonClickedRenderer.addLoadedEventListener(function(){
self._findLayout();
self._pressedTextureSize = self._buttonClickedRenderer.getContentSize();
self._updateFlippedX();
self._updateFlippedY();
self._updateChildrenDisplayedRGBA();
self._pressedTextureLoaded = true;
self._pressedTextureAdaptDirty = true;
});
}
if (this._scale9Enabled) {
var clickedRendererScale9 = this._buttonClickedRenderer;
switch (this._pressedTexType) {
case ccui.Widget.LOCAL_TEXTURE:
clickedRendererScale9.initWithFile(selected);
break;
case ccui.Widget.PLIST_TEXTURE:
clickedRendererScale9.initWithSpriteFrameName(selected);
break;
default:
break;
}
clickedRendererScale9.setCapInsets(this._capInsetsPressed);
} else {
var clickedRenderer = this._buttonClickedRenderer;
switch (this._pressedTexType) {
case ccui.Widget.LOCAL_TEXTURE:
//SetTexture cannot load resource
clickedRenderer.initWithFile(selected);
break;
case ccui.Widget.PLIST_TEXTURE:
//SetTexture cannot load resource
clickedRenderer.initWithSpriteFrameName(selected);
break;
default:
break;
}
}
this._pressedTextureSize = this._buttonClickedRenderer.getContentSize();
this._updateFlippedX();
this._updateFlippedY();
this._updateChildrenDisplayedRGBA();
this._pressedTextureLoaded = true;
this._pressedTextureAdaptDirty = true;
},
/**
* Load dark state texture for button.
* @param {String} disabled
* @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
*/
loadTextureDisabled: function (disabled, texType) {
if (!disabled)
return;
texType = texType || ccui.Widget.LOCAL_TEXTURE;
this._disabledFileName = disabled;
this._disabledTexType = texType;
var self = this;
if(!this._buttonDisableRenderer.texture || !this._buttonDisableRenderer.texture.isLoaded()){
this._buttonDisableRenderer.addLoadedEventListener(function() {
self._findLayout();
self._disabledTextureSize = self._buttonDisableRenderer.getContentSize();
self._updateFlippedX();
self._updateFlippedY();
self._updateChildrenDisplayedRGBA();
self._disabledTextureLoaded = true;
self._disabledTextureAdaptDirty = true;
});
}
if (this._scale9Enabled) {
var disabledScale9 = this._buttonDisableRenderer;
switch (this._disabledTexType) {
case ccui.Widget.LOCAL_TEXTURE:
disabledScale9.initWithFile(disabled);
break;
case ccui.Widget.PLIST_TEXTURE:
disabledScale9.initWithSpriteFrameName(disabled);
break;
default:
break;
}
disabledScale9.setCapInsets(this._capInsetsDisabled);
} else {
var disabledRenderer = this._buttonDisableRenderer;
switch (this._disabledTexType) {
case ccui.Widget.LOCAL_TEXTURE:
//SetTexture cannot load resource
disabledRenderer.initWithFile(disabled);
break;
case ccui.Widget.PLIST_TEXTURE:
//SetTexture cannot load resource
disabledRenderer.initWithSpriteFrameName(disabled);
break;
default:
break;
}
}
this._disabledTextureSize = this._buttonDisableRenderer.getContentSize();
this._updateFlippedX();
this._updateFlippedY();
this._updateChildrenDisplayedRGBA();
this._disabledTextureLoaded = true;
this._disabledTextureAdaptDirty = true;
},
/**
* Sets capinsets for button, if button is using scale9 renderer.
* @param {cc.Rect} capInsets
*/
setCapInsets: function (capInsets) {
this.setCapInsetsNormalRenderer(capInsets);
this.setCapInsetsPressedRenderer(capInsets);
this.setCapInsetsDisabledRenderer(capInsets);
},
/**
* Sets capinsets for button, if button is using scale9 renderer.
* @param {cc.Rect} capInsets
*/
setCapInsetsNormalRenderer: function (capInsets) {
this._capInsetsNormal = capInsets;
if (!this._scale9Enabled)
return;
this._buttonNormalRenderer.setCapInsets(capInsets);
},
/**
* Get normal renderer cap insets .
* @returns {cc.Rect}
*/
getCapInsetsNormalRenderer:function(){
return this._capInsetsNormal;
},
/**
* Sets capinsets for button, if button is using scale9 renderer.
* @param {cc.Rect} capInsets
*/
setCapInsetsPressedRenderer: function (capInsets) {
this._capInsetsPressed = capInsets;
if (!this._scale9Enabled)
return;
this._buttonClickedRenderer.setCapInsets(capInsets);
},
/**
* Get pressed renderer cap insets .
* @returns {cc.Rect}
*/
getCapInsetsPressedRenderer: function () {
return this._capInsetsPressed;
},
/**
* Sets capinsets for button, if button is using scale9 renderer.
* @param {cc.Rect} capInsets
*/
setCapInsetsDisabledRenderer: function (capInsets) {
this._capInsetsDisabled = capInsets;
if (!this._scale9Enabled)
return;
this._buttonDisableRenderer.setCapInsets(capInsets);
},
/**
* Get disable renderer cap insets .
* @returns {cc.Rect}
*/
getCapInsetsDisabledRenderer: function () {
return this._capInsetsDisabled;
},
onPressStateChangedToNormal: function () {
this._buttonNormalRenderer.setVisible(true);
this._buttonClickedRenderer.setVisible(false);
this._buttonDisableRenderer.setVisible(false);
if (this._pressedTextureLoaded) {
if (this.pressedActionEnabled){
this._buttonNormalRenderer.stopAllActions();
this._buttonClickedRenderer.stopAllActions();
var zoomAction = cc.ScaleTo.create(0.05, this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
this._buttonNormalRenderer.runAction(zoomAction);
this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
}
} else {
if (this._scale9Enabled)
this._updateTexturesRGBA();
else {
this._buttonNormalRenderer.stopAllActions();
this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
}
}
},
onPressStateChangedToPressed: function () {
var locNormalRenderer = this._buttonNormalRenderer;
if (this._pressedTextureLoaded) {
locNormalRenderer.setVisible(false);
this._buttonClickedRenderer.setVisible(true);
this._buttonDisableRenderer.setVisible(false);
if (this.pressedActionEnabled) {
locNormalRenderer.stopAllActions();
this._buttonClickedRenderer.stopAllActions();
var zoomAction = cc.ScaleTo.create(0.05, this._pressedTextureScaleXInSize + 0.1,this._pressedTextureScaleYInSize + 0.1);
this._buttonClickedRenderer.runAction(zoomAction);
locNormalRenderer.setScale(this._pressedTextureScaleXInSize + 0.1, this._pressedTextureScaleYInSize + 0.1);
}
} else {
locNormalRenderer.setVisible(true);
this._buttonClickedRenderer.setVisible(true);
this._buttonDisableRenderer.setVisible(false);
if (this._scale9Enabled)
locNormalRenderer.setColor(cc.Color.GRAY);
else {
locNormalRenderer.stopAllActions();
locNormalRenderer.setScale(this._normalTextureScaleXInSize + 0.1, this._normalTextureScaleYInSize + 0.1);
}
}
},
onPressStateChangedToDisabled: function () {
this._buttonNormalRenderer.setVisible(false);
this._buttonClickedRenderer.setVisible(false);
this._buttonDisableRenderer.setVisible(true);
this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
},
_updateFlippedX: function () {
var flip = this._flippedX ? -1.0 : 1.0;
this._titleRenderer.setScaleX(flip);
if (this._scale9Enabled) {
this._buttonNormalRenderer.setScaleX(flip);
this._buttonClickedRenderer.setScaleX(flip);
this._buttonDisableRenderer.setScaleX(flip);
} else {
this._buttonNormalRenderer.setFlippedX(this._flippedX);
this._buttonClickedRenderer.setFlippedX(this._flippedX);
this._buttonDisableRenderer.setFlippedX(this._flippedX);
}
},
_updateFlippedY: function () {
var flip = this._flippedY ? -1.0 : 1.0;
this._titleRenderer.setScaleY(flip);
if (this._scale9Enabled) {
this._buttonNormalRenderer.setScaleY(flip);
this._buttonClickedRenderer.setScaleY(flip);
this._buttonDisableRenderer.setScaleY(flip);
} else {
this._buttonNormalRenderer.setFlippedY(this._flippedY);
this._buttonClickedRenderer.setFlippedY(this._flippedY);
this._buttonDisableRenderer.setFlippedY(this._flippedY);
}
},
_updateTexturesRGBA: function(){
this._buttonNormalRenderer.setColor(this.getColor());
this._buttonClickedRenderer.setColor(this.getColor());
this._buttonDisableRenderer.setColor(this.getColor());
this._buttonNormalRenderer.setOpacity(this.getOpacity());
this._buttonClickedRenderer.setOpacity(this.getOpacity());
this._buttonDisableRenderer.setOpacity(this.getOpacity());
},
_onSizeChanged: function () {
ccui.Widget.prototype._onSizeChanged.call(this);
this._updateTitleLocation();
this._normalTextureAdaptDirty = true;
this._pressedTextureAdaptDirty = true;
this._disabledTextureAdaptDirty = true;
},
/**
* Gets the Virtual Renderer of widget.
* @returns {cc.Node}
*/
getVirtualRenderer: function () {
if (this._bright) {
switch (this._brightStyle) {
case ccui.Widget.BRIGHT_STYLE_NORMAL:
return this._buttonNormalRenderer;
case ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT:
return this._buttonClickedRenderer;
default:
return null;
}
} else
return this._buttonDisableRenderer;
},
_normalTextureScaleChangedWithSize: function () {
if (this._ignoreSize) {
if (!this._scale9Enabled) {
this._buttonNormalRenderer.setScale(1.0);
this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1;
}
} else {
if (this._scale9Enabled) {
this._buttonNormalRenderer.setPreferredSize(this._contentSize);
this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1;
} else {
var textureSize = this._normalTextureSize;
if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
this._buttonNormalRenderer.setScale(1.0);
return;
}
var scaleX = this._contentSize.width / textureSize.width;
var scaleY = this._contentSize.height / textureSize.height;
this._buttonNormalRenderer.setScaleX(scaleX);
this._buttonNormalRenderer.setScaleY(scaleY);
this._normalTextureScaleXInSize = scaleX;
this._normalTextureScaleYInSize = scaleY;
}
}
this._buttonNormalRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
},
_pressedTextureScaleChangedWithSize: function () {
if (this._ignoreSize) {
if (!this._scale9Enabled) {
this._buttonClickedRenderer.setScale(1.0);
this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1;
}
} else {
if (this._scale9Enabled) {
this._buttonClickedRenderer.setPreferredSize(this._contentSize);
this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1;
} else {
var textureSize = this._pressedTextureSize;
if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
this._buttonClickedRenderer.setScale(1.0);
return;
}
var scaleX = this._contentSize.width / textureSize.width;
var scaleY = this._contentSize.height / textureSize.height;
this._buttonClickedRenderer.setScaleX(scaleX);
this._buttonClickedRenderer.setScaleY(scaleY);
this._pressedTextureScaleXInSize = scaleX;
this._pressedTextureScaleYInSize = scaleY;
}
}
this._buttonClickedRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
},
_disabledTextureScaleChangedWithSize: function () {
if (this._ignoreSize) {
if (!this._scale9Enabled)
this._buttonDisableRenderer.setScale(1.0);
} else {
if (this._scale9Enabled)
this._buttonDisableRenderer.setPreferredSize(this._contentSize);
else {
var textureSize = this._disabledTextureSize;
if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
this._buttonDisableRenderer.setScale(1.0);
return;
}
var scaleX = this._contentSize.width / textureSize.width;
var scaleY = this._contentSize.height / textureSize.height;
this._buttonDisableRenderer.setScaleX(scaleX);
this._buttonDisableRenderer.setScaleY(scaleY);
}
}
this._buttonDisableRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
},
_adaptRenderers: function(){
if (this._normalTextureAdaptDirty) {
this._normalTextureScaleChangedWithSize();
this._normalTextureAdaptDirty = false;
}
if (this._pressedTextureAdaptDirty) {
this._pressedTextureScaleChangedWithSize();
this._pressedTextureAdaptDirty = false;
}
if (this._disabledTextureAdaptDirty) {
this._disabledTextureScaleChangedWithSize();
this._disabledTextureAdaptDirty = false;
}
},
_updateTitleLocation: function(){
this._titleRenderer.setPosition(this._contentSize.width * 0.5, this._contentSize.height * 0.5);
},
/**
* Changes if button can be clicked zoom effect.
* @param {Boolean} enabled
*/
setPressedActionEnabled: function (enabled) {
this.pressedActionEnabled = enabled;
},
/**
* set title text
* @param {String} text
*/
setTitleText: function (text) {
this._titleRenderer.setString(text);
},
/**
* get title text
* @returns {String} text
*/
getTitleText: function () {
return this._titleRenderer.getString();
},
/**
* set title color
* @param {cc.Color} color
*/
setTitleColor: function (color) {
this._titleColor.r = color.r;
this._titleColor.g = color.g;
this._titleColor.b = color.b;
this._titleRenderer.updateDisplayedColor(color);
},
/**
* get title color
* @returns {cc.Color}
*/
getTitleColor: function () {
return this._titleRenderer.getColor();
},
/**
* set title fontSize
* @param {cc.Size} size
*/
setTitleFontSize: function (size) {
this._titleRenderer.setFontSize(size);
},
/**
* get title fontSize
* @returns {cc.Size}
*/
getTitleFontSize: function () {
return this._titleRenderer.getFontSize();
},
/**
* set title fontName
* @param {String} fontName
*/
setTitleFontName: function (fontName) {
this._titleRenderer.setFontName(fontName);
this._fontName = fontName;
},
/**
* get title fontName
* @returns {String}
*/
getTitleFontName: function () {
return this._titleRenderer.getFontName();
},
_setTitleFont: function (font) {
this._titleRenderer.font = font;
},
_getTitleFont: function () {
return this._titleRenderer.font;
},
/**
* Returns the "class name" of widget.
* @returns {string}
*/
getDescription: function () {
return "Button";
},
_createCloneInstance: function () {
return ccui.Button.create();
},
_copySpecialProperties: function (uiButton) {
this._prevIgnoreSize = uiButton._prevIgnoreSize;
this.setScale9Enabled(uiButton._scale9Enabled);
this.loadTextureNormal(uiButton._normalFileName, uiButton._normalTexType);
this.loadTexturePressed(uiButton._clickedFileName, uiButton._pressedTexType);
this.loadTextureDisabled(uiButton._disabledFileName, uiButton._disabledTexType);
this.setCapInsetsNormalRenderer(uiButton._capInsetsNormal);
this.setCapInsetsPressedRenderer(uiButton._capInsetsPressed);
this.setCapInsetsDisabledRenderer(uiButton._capInsetsDisabled);
this.setTitleText(uiButton.getTitleText());
this.setTitleFontName(uiButton.getTitleFontName());
this.setTitleFontSize(uiButton.getTitleFontSize());
this.setTitleColor(uiButton.getTitleColor());
this.setPressedActionEnabled(uiButton.pressedActionEnabled);
}
});
var _p = ccui.Button.prototype;
// Extended properties
/** @expose */
_p.titleText;
cc.defineGetterSetter(_p, "titleText", _p.getTitleText, _p.setTitleText);
/** @expose */
_p.titleFont;
cc.defineGetterSetter(_p, "titleFont", _p._getTitleFont, _p._setTitleFont);
/** @expose */
_p.titleFontSize;
cc.defineGetterSetter(_p, "titleFontSize", _p.getTitleFontSize, _p.setTitleFontSize);
/** @expose */
_p.titleFontName;
cc.defineGetterSetter(_p, "titleFontName", _p.getTitleFontName, _p.setTitleFontName);
/** @expose */
_p.titleColor;
cc.defineGetterSetter(_p, "titleColor", _p.getTitleColor, _p.setTitleColor);
_p = null;
/**
* allocates and initializes a UIButton.
* @deprecated
* @param {string} [normalImage] normal state texture name
* @param {string} [selectedImage] selected state texture name
* @param {string} [disableImage] disabled state texture name
* @param {string} [texType]
* @return {ccui.Button}
* @example
* // example
* var uiButton = ccui.Button.create();
*/
ccui.Button.create = function (normalImage, selectedImage, disableImage, texType) {
return new ccui.Button(normalImage, selectedImage, disableImage, texType);
};
// Constants
ccui.Button.NORMAL_RENDERER_ZORDER = -2;
ccui.Button.PRESSED_RENDERER_ZORDER = -2;
ccui.Button.DISABLED_RENDERER_ZORDER = -2;
ccui.Button.TITLE_RENDERER_ZORDER = -1;
ccui.Button.SYSTEM = 0;
ccui.Button.TTF = 1;
| 0 | 0.945237 | 1 | 0.945237 | game-dev | MEDIA | 0.43616 | game-dev | 0.952748 | 1 | 0.952748 |
pd-l2ork/pd-l2ork | 4,439 | externals/iem/iemguts/src/savebangs.c |
/******************************************************
*
* propertybang - implementation file
*
* copyleft (c) IOhannes m zmölnig
*
* 2007:forum::für::umläute:2007
*
* institute of electronic music and acoustics (iem)
*
******************************************************
*
* license: GNU General Public License v.2 (or later)
*
******************************************************/
/*
* this object outputs a bang when the savfn of the parent abstraction is called
*/
/*
* LATER sketch:
* monkey-patching the parent canvas so that stores a local function table
* then modify this function-table so that the savefn points to us
* on call: we call the parents savefunction and output bangs
*/
/*
* TODO: how does this behave in sub-patches?
* -> BUG: the depth should _really_ refer to the abstraction-depth
* else we get weird duplicates (most likely due to the "$0" trick
*/
#include "iemguts-objlist.h"
#include "g_canvas.h"
/* ------------------------- helper methods for savefunctions ---------------------------- */
typedef struct _savefuns {
t_class*class;
t_savefn savefn;
struct _savefuns *next;
} t_savefuns;
static t_savefuns*s_savefuns=0;
static t_savefn find_savefn(const t_class*class)
{
t_savefuns*fun=s_savefuns;
if(0==s_savefuns || 0==class)
return 0;
for(fun=s_savefuns; fun; fun=fun->next) {
if(class == fun->class) {
return fun->savefn;
}
}
return 0;
}
static void add_savefn(t_class*class)
{
if(0!=find_savefn(class)) {
return;
} else {
t_savefuns*sfun=getbytes(sizeof(*sfun));
sfun->class=class;
sfun->savefn=class_getsavefn(class);
sfun->next=0;
if(0==s_savefuns) {
s_savefuns=sfun;
} else {
t_savefuns*sfp=s_savefuns;
while(sfp->next)
sfp=sfp->next;
sfp->next = sfun;
}
}
}
/* ------------------------- savefunctions ---------------------------- */
static void orig_savefn(t_gobj*z, t_binbuf*b)
{
t_class*class=z->g_pd;
t_savefn savefn=find_savefn(class);
if(savefn) {
savefn(z, b);
}
}
static void savebangs_bangem(t_iemguts_objlist*objs, int pst);
static void savebangs_savefn(t_gobj*z, t_binbuf*b) {
/* z is the parent abstraction;
* we maintain a list of all [savebangs] within a parent, in order to call all of them
*/
t_iemguts_objlist*obj=objectsInCanvas((t_pd*)z);
savebangs_bangem(obj, 0);
orig_savefn(z, b);
savebangs_bangem(obj, 1);
}
/* ------------------------- savebangs ---------------------------- */
static t_class *savebangs_class;
typedef struct _savebangs
{
t_object x_obj;
t_outlet *x_pre, *x_post;
t_canvas *x_parent;
} t_savebangs;
static void savebangs_bangs(t_savebangs*x, int pst)
{
if(!pst)
outlet_bang(x->x_pre);
else
outlet_bang(x->x_post);
}
static void savebangs_bangem(t_iemguts_objlist*objs, int pst) {
while(objs) {
t_savebangs*x=(t_savebangs*)objs->obj;
savebangs_bangs(x, pst);
objs=objs->next;
}
}
static void savebangs_mysavefn(t_gobj*z, t_binbuf*b) {
t_savebangs*x=(t_savebangs*)z;
int doit=(!x->x_parent);
if(doit)savebangs_bangs(x, 0);
orig_savefn(z, b);
if(doit)savebangs_bangs(x, 1);
}
static void *savebangs_new(t_floatarg f)
{
t_savebangs *x = (t_savebangs *)pd_new(savebangs_class);
t_glist *glist=(t_glist *)canvas_getcurrent();
t_canvas *canvas=(t_canvas*)glist_getcanvas(glist);
t_class *class = 0;
int depth=(int)f;
if(depth<0)depth=0;
if(depth) {
depth--;
while(depth && canvas) {
canvas=canvas->gl_owner;
depth--;
}
if(canvas) {
class=((t_gobj*)canvas)->g_pd;
add_savefn(class);
class_setsavefn(class, savebangs_savefn);
x->x_parent=canvas;
} else {
x->x_parent=0;
}
addObjectToCanvas((t_pd*)canvas, (t_pd*)x);
}
x->x_post=outlet_new(&x->x_obj, &s_bang);
x->x_pre=outlet_new(&x->x_obj, &s_bang);
return (x);
}
static void savebangs_free(t_savebangs *x)
{
/* unpatch the parent canvas */
removeObjectFromCanvases((t_pd*)x);
}
void savebangs_setup(void)
{
iemguts_boilerplate("[savebangs]", 0);
savebangs_class = class_new(gensym("savebangs"), (t_newmethod)savebangs_new,
(t_method)savebangs_free, sizeof(t_savebangs), CLASS_NOINLET, A_DEFFLOAT, 0);
add_savefn(savebangs_class);
class_setsavefn(savebangs_class, savebangs_mysavefn);
}
| 0 | 0.63805 | 1 | 0.63805 | game-dev | MEDIA | 0.494909 | game-dev,graphics-rendering | 0.708754 | 1 | 0.708754 |
advancedfx/advancedfx | 3,722 | AfxHookGoldSrc/hooks/client/cstrike/CrossHairFix.cpp | #include "stdafx.h"
// See also: /doc/notes_goldsrc/debug_cstrike_crosshair.txt
#include "CrossHairFix.h"
#include <windows.h>
#include <shared/AfxDetours.h>
#include <hlsdk.h>
#include "../../../hl_addresses.h"
#include "../../HookHw.h"
#include "../../hw/Host_Frame.h"
#include <gl/gl.h>
#include <Windows.h>
#include <deps/release/Detours/src/detours.h>
typedef void (__fastcall *UnkCstrikeCrosshairFn_t)( void * This, void * edx, float dwUnk1, DWORD dwUnk2);
bool g_Cstrike_CrossHair_Block = false;
UnkCstrikeCrosshairFn_t g_pfnCrosshairFix_Hooked_Func = NULL;
double *g_f_ch_mul_fac = NULL;
double *g_f_ch_add_fac = NULL;
double g_cstrike_ch_frameT = 1.0/100.0;
void __fastcall CrosshairFix_Hooking_Func(void * This, void * edx, float fUnkTime, DWORD dwUnkWeaponCode )
{
static float oldClientTime = 0;
static double deltaT = 0;
bool freezeCh = g_Cstrike_CrossHair_Block;
bool fix = !freezeCh && 0.0 < g_cstrike_ch_frameT;
if(fix)
{
double frameTime = pEngfuncs->pfnGetCvarFloat("host_framerate");
if(0 >= frameTime) frameTime = *g_phost_frametime;
deltaT += frameTime;
bool coolDown = g_cstrike_ch_frameT <= deltaT;
if(coolDown)
{
// apply cooldown:
bool doLoop;
GLboolean oldMasks[5];
do
{
deltaT -= g_cstrike_ch_frameT;
doLoop = g_cstrike_ch_frameT <= deltaT;
if(doLoop)
{
glGetBooleanv(GL_COLOR_WRITEMASK, oldMasks);
glGetBooleanv(GL_DEPTH_WRITEMASK, &(oldMasks[4]));
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glDepthMask(GL_FALSE);
}
g_pfnCrosshairFix_Hooked_Func( This, edx, fUnkTime, dwUnkWeaponCode );
if(doLoop)
{
glColorMask(oldMasks[0], oldMasks[1], oldMasks[2], oldMasks[3]);
glDepthMask(oldMasks[4]);
}
}
while(doLoop);
return; // done.
}
else
// keep it frozen:
freezeCh = true;
}
if(freezeCh)
{
// do not apply any cool down, just make it drawn:
MdtMemBlockInfos mbisMul, mbisAdd;
double fOldMulFac, fOldAddFac;
MdtMemAccessBegin(g_f_ch_mul_fac, sizeof(double), &mbisMul);
MdtMemAccessBegin(g_f_ch_add_fac, sizeof(double), &mbisAdd);
fOldMulFac = *g_f_ch_mul_fac;
fOldAddFac = *g_f_ch_add_fac;
*g_f_ch_mul_fac = 0.0f;
*g_f_ch_add_fac = 0.0f;
g_pfnCrosshairFix_Hooked_Func( This, edx, fUnkTime, dwUnkWeaponCode );
*g_f_ch_mul_fac = fOldMulFac;
*g_f_ch_add_fac = fOldAddFac;
MdtMemAccessEnd(&mbisAdd);
MdtMemAccessEnd(&mbisMul);
}
else
// Normal (unfixed) operation.
g_pfnCrosshairFix_Hooked_Func( This, edx, fUnkTime, dwUnkWeaponCode );
}
double Cstrike_CrossHair_Fps_get()
{
return 0.0 != g_cstrike_ch_frameT ? 1.0 / g_cstrike_ch_frameT : 0.0;
}
void Cstrike_CrossHair_Fps_set(double value)
{
g_cstrike_ch_frameT = 0.0 != value ? 1.0 / value : 0.0;
}
bool Hook_Cstrike_CrossHair_Fix()
{
static bool firstRun = true;
static bool firstResult = true;
if (!firstRun) return firstResult;
firstRun = false;
double * addrMul = (double *)HL_ADDR_GET(cstrike_UnkCrosshairFn_mul_fac);
double * addrAdd = (double *)HL_ADDR_GET(cstrike_UnkCrosshairFn_add_fac);
BYTE * addrFn = (BYTE *)HL_ADDR_GET(cstrike_UnkCrosshairFn);
if (!(
addrMul && addrAdd && addrFn
))
{
firstResult = false;
}
else
{
LONG error = NO_ERROR;
g_f_ch_mul_fac = addrMul;
g_f_ch_add_fac = addrAdd;
g_pfnCrosshairFix_Hooked_Func = (UnkCstrikeCrosshairFn_t)addrFn;
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)g_pfnCrosshairFix_Hooked_Func, CrosshairFix_Hooking_Func);
error = DetourTransactionCommit();
if (NO_ERROR != error)
{
firstResult = false;
ErrorBox("Interception failed:\nHook_Cstrike_CrossHair_Fix()");
}
}
return firstResult;
}
| 0 | 0.879092 | 1 | 0.879092 | game-dev | MEDIA | 0.775704 | game-dev | 0.629069 | 1 | 0.629069 |
bozimmerman/CoffeeMud | 4,146 | com/planet_ink/coffee_mud/Abilities/Druid/Chant_SummonFood.java | package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2002-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Chant_SummonFood extends Chant
{
@Override
public String ID()
{
return "Chant_SummonFood";
}
private final static String localizedName = CMLib.lang().L("Summon Food");
@Override
public String name()
{
return localizedName;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
@Override
protected int canAffectCode()
{
return 0;
}
@Override
protected int canTargetCode()
{
return 0;
}
@Override
public int classificationCode()
{
return Ability.ACODE_CHANT | Ability.DOMAIN_PLANTGROWTH;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if(((mob.location().domainType()&Room.INDOORS)>0)&&(!auto))
{
mob.tell(L("You must be outdoors to try this."));
return false;
}
if((CMLib.flags().isACityRoom(mob.location()))
||(mob.location().domainType()==Room.DOMAIN_OUTDOORS_AIR)
||(CMLib.flags().isWateryRoom(mob.location())))
{
mob.tell(L("This magic will not work here."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> chant(s) to the ground.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
Food newItem=null;
final int berryType=RawMaterial.CODES.BERRIES()[CMLib.dice().roll(1,RawMaterial.CODES.BERRIES().length,-1)];
for(int i=0;i<((adjustedLevel(mob,asLevel)/4)+1);i++)
{
newItem=(Food)CMClass.getBasicItem("GenFoodResource");
newItem.setName(L("some @x1",RawMaterial.CODES.NAME(berryType).toLowerCase()));
newItem.setDisplayText(L("@x1 are growing here.",CMStrings.capitalizeAndLower(newItem.name())));
newItem.setDescription(L("These little berries look juicy and good."));
newItem.setMaterial(berryType);
newItem.setNourishment(150+(10*super.getX1Level(mob)));
newItem.setBaseValue(1);
CMLib.materials().addEffectsToResource(newItem);
newItem.setMiscText(newItem.text());
mob.location().addItem(newItem,ItemPossessor.Expire.Resource);
}
if(newItem!=null)
mob.location().showHappens(CMMsg.MSG_OK_ACTION,L("@x1 quickly begin to grow here.",CMStrings.capitalizeAndLower(newItem.name())));
mob.location().recoverPhyStats();
}
}
else
return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s) to the ground, but nothing happens."));
// return whether it worked
return success;
}
}
| 0 | 0.652822 | 1 | 0.652822 | game-dev | MEDIA | 0.970023 | game-dev | 0.597252 | 1 | 0.597252 |
Arkania/ArkCORE-NG | 30,253 | dep/recastnavigation/Recast/RecastContour.cpp | //
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.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.
//
#define _USE_MATH_DEFINES
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Recast.h"
#include "RecastAlloc.h"
#include "RecastAssert.h"
static int getCornerHeight(int x, int y, int i, int dir,
const rcCompactHeightfield& chf,
bool& isBorderVertex)
{
const rcCompactSpan& s = chf.spans[i];
int ch = (int)s.y;
int dirp = (dir+1) & 0x3;
unsigned int regs[4] = {0,0,0,0};
// Combine region and area codes in order to prevent
// border vertices which are in between two areas to be removed.
regs[0] = chf.spans[i].reg | (chf.areas[i] << 16);
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dir);
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
const rcCompactSpan& as = chf.spans[ai];
ch = rcMax(ch, (int)as.y);
regs[1] = chf.spans[ai].reg | (chf.areas[ai] << 16);
if (rcGetCon(as, dirp) != RC_NOT_CONNECTED)
{
const int ax2 = ax + rcGetDirOffsetX(dirp);
const int ay2 = ay + rcGetDirOffsetY(dirp);
const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dirp);
const rcCompactSpan& as2 = chf.spans[ai2];
ch = rcMax(ch, (int)as2.y);
regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
}
}
if (rcGetCon(s, dirp) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dirp);
const int ay = y + rcGetDirOffsetY(dirp);
const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dirp);
const rcCompactSpan& as = chf.spans[ai];
ch = rcMax(ch, (int)as.y);
regs[3] = chf.spans[ai].reg | (chf.areas[ai] << 16);
if (rcGetCon(as, dir) != RC_NOT_CONNECTED)
{
const int ax2 = ax + rcGetDirOffsetX(dir);
const int ay2 = ay + rcGetDirOffsetY(dir);
const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dir);
const rcCompactSpan& as2 = chf.spans[ai2];
ch = rcMax(ch, (int)as2.y);
regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
}
}
// Check if the vertex is special edge vertex, these vertices will be removed later.
for (int j = 0; j < 4; ++j)
{
const int a = j;
const int b = (j+1) & 0x3;
const int c = (j+2) & 0x3;
const int d = (j+3) & 0x3;
// The vertex is a border vertex there are two same exterior cells in a row,
// followed by two interior cells and none of the regions are out of bounds.
const bool twoSameExts = (regs[a] & regs[b] & RC_BORDER_REG) != 0 && regs[a] == regs[b];
const bool twoInts = ((regs[c] | regs[d]) & RC_BORDER_REG) == 0;
const bool intsSameArea = (regs[c]>>16) == (regs[d]>>16);
const bool noZeros = regs[a] != 0 && regs[b] != 0 && regs[c] != 0 && regs[d] != 0;
if (twoSameExts && twoInts && intsSameArea && noZeros)
{
isBorderVertex = true;
break;
}
}
return ch;
}
static void walkContour(int x, int y, int i,
rcCompactHeightfield& chf,
unsigned char* flags, rcIntArray& points)
{
// Choose the first non-connected edge
unsigned char dir = 0;
while ((flags[i] & (1 << dir)) == 0)
dir++;
unsigned char startDir = dir;
int starti = i;
const unsigned char area = chf.areas[i];
int iter = 0;
while (++iter < 40000)
{
if (flags[i] & (1 << dir))
{
// Choose the edge corner
bool isBorderVertex = false;
bool isAreaBorder = false;
int px = x;
int py = getCornerHeight(x, y, i, dir, chf, isBorderVertex);
int pz = y;
switch(dir)
{
case 0: pz++; break;
case 1: px++; pz++; break;
case 2: px++; break;
}
int r = 0;
const rcCompactSpan& s = chf.spans[i];
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dir);
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
r = (int)chf.spans[ai].reg;
if (area != chf.areas[ai])
isAreaBorder = true;
}
if (isBorderVertex)
r |= RC_BORDER_VERTEX;
if (isAreaBorder)
r |= RC_AREA_BORDER;
points.push(px);
points.push(py);
points.push(pz);
points.push(r);
flags[i] &= ~(1 << dir); // Remove visited edges
dir = (dir+1) & 0x3; // Rotate CW
}
else
{
int ni = -1;
const int nx = x + rcGetDirOffsetX(dir);
const int ny = y + rcGetDirOffsetY(dir);
const rcCompactSpan& s = chf.spans[i];
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const rcCompactCell& nc = chf.cells[nx+ny*chf.width];
ni = (int)nc.index + rcGetCon(s, dir);
}
if (ni == -1)
{
// Should not happen.
return;
}
x = nx;
y = ny;
i = ni;
dir = (dir+3) & 0x3; // Rotate CCW
}
if (starti == i && startDir == dir)
{
break;
}
}
}
static float distancePtSeg(const int x, const int z,
const int px, const int pz,
const int qx, const int qz)
{
float pqx = (float)(qx - px);
float pqz = (float)(qz - pz);
float dx = (float)(x - px);
float dz = (float)(z - pz);
float d = pqx*pqx + pqz*pqz;
float t = pqx*dx + pqz*dz;
if (d > 0)
t /= d;
if (t < 0)
t = 0;
else if (t > 1)
t = 1;
dx = px + t*pqx - x;
dz = pz + t*pqz - z;
return dx*dx + dz*dz;
}
static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
const float maxError, const int maxEdgeLen, const int buildFlags)
{
// Add initial points.
bool hasConnections = false;
for (int i = 0; i < points.size(); i += 4)
{
if ((points[i+3] & RC_CONTOUR_REG_MASK) != 0)
{
hasConnections = true;
break;
}
}
if (hasConnections)
{
// The contour has some portals to other regions.
// Add a new point to every location where the region changes.
for (int i = 0, ni = points.size()/4; i < ni; ++i)
{
int ii = (i+1) % ni;
const bool differentRegs = (points[i*4+3] & RC_CONTOUR_REG_MASK) != (points[ii*4+3] & RC_CONTOUR_REG_MASK);
const bool areaBorders = (points[i*4+3] & RC_AREA_BORDER) != (points[ii*4+3] & RC_AREA_BORDER);
if (differentRegs || areaBorders)
{
simplified.push(points[i*4+0]);
simplified.push(points[i*4+1]);
simplified.push(points[i*4+2]);
simplified.push(i);
}
}
}
if (simplified.size() == 0)
{
// If there is no connections at all,
// create some initial points for the simplification process.
// Find lower-left and upper-right vertices of the contour.
int llx = points[0];
int lly = points[1];
int llz = points[2];
int lli = 0;
int urx = points[0];
int ury = points[1];
int urz = points[2];
int uri = 0;
for (int i = 0; i < points.size(); i += 4)
{
int x = points[i+0];
int y = points[i+1];
int z = points[i+2];
if (x < llx || (x == llx && z < llz))
{
llx = x;
lly = y;
llz = z;
lli = i/4;
}
if (x > urx || (x == urx && z > urz))
{
urx = x;
ury = y;
urz = z;
uri = i/4;
}
}
simplified.push(llx);
simplified.push(lly);
simplified.push(llz);
simplified.push(lli);
simplified.push(urx);
simplified.push(ury);
simplified.push(urz);
simplified.push(uri);
}
// Add points until all raw points are within
// error tolerance to the simplified shape.
const int pn = points.size()/4;
for (int i = 0; i < simplified.size()/4; )
{
int ii = (i+1) % (simplified.size()/4);
int ax = simplified[i*4+0];
int az = simplified[i*4+2];
int ai = simplified[i*4+3];
int bx = simplified[ii*4+0];
int bz = simplified[ii*4+2];
int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
float maxd = 0;
int maxi = -1;
int ci, cinc, endi;
// Traverse the segment in lexilogical order so that the
// max deviation is calculated similarly when traversing
// opposite segments.
if (bx > ax || (bx == ax && bz > az))
{
cinc = 1;
ci = (ai+cinc) % pn;
endi = bi;
}
else
{
cinc = pn-1;
ci = (bi+cinc) % pn;
endi = ai;
rcSwap(ax, bx);
rcSwap(az, bz);
}
// Tessellate only outer edges or edges between areas.
if ((points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0 ||
(points[ci*4+3] & RC_AREA_BORDER))
{
while (ci != endi)
{
float d = distancePtSeg(points[ci*4+0], points[ci*4+2], ax, az, bx, bz);
if (d > maxd)
{
maxd = d;
maxi = ci;
}
ci = (ci+cinc) % pn;
}
}
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (maxi != -1 && maxd > (maxError*maxError))
{
// Add space for the new point.
simplified.resize(simplified.size()+4);
const int n = simplified.size()/4;
for (int j = n-1; j > i; --j)
{
simplified[j*4+0] = simplified[(j-1)*4+0];
simplified[j*4+1] = simplified[(j-1)*4+1];
simplified[j*4+2] = simplified[(j-1)*4+2];
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = points[maxi*4+0];
simplified[(i+1)*4+1] = points[maxi*4+1];
simplified[(i+1)*4+2] = points[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
}
else
{
++i;
}
}
// Split too long edges.
if (maxEdgeLen > 0 && (buildFlags & (RC_CONTOUR_TESS_WALL_EDGES|RC_CONTOUR_TESS_AREA_EDGES)) != 0)
{
for (int i = 0; i < simplified.size()/4; )
{
const int ii = (i+1) % (simplified.size()/4);
const int ax = simplified[i*4+0];
const int az = simplified[i*4+2];
const int ai = simplified[i*4+3];
const int bx = simplified[ii*4+0];
const int bz = simplified[ii*4+2];
const int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
int maxi = -1;
int ci = (ai+1) % pn;
// Tessellate only outer edges or edges between areas.
bool tess = false;
// Wall edges.
if ((buildFlags & RC_CONTOUR_TESS_WALL_EDGES) && (points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0)
tess = true;
// Edges between areas.
if ((buildFlags & RC_CONTOUR_TESS_AREA_EDGES) && (points[ci*4+3] & RC_AREA_BORDER))
tess = true;
if (tess)
{
int dx = bx - ax;
int dz = bz - az;
if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen)
{
// Round based on the segments in lexilogical order so that the
// max tesselation is consistent regardles in which direction
// segments are traversed.
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
if (n > 1)
{
if (bx > ax || (bx == ax && bz > az))
maxi = (ai + n/2) % pn;
else
maxi = (ai + (n+1)/2) % pn;
}
}
}
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (maxi != -1)
{
// Add space for the new point.
simplified.resize(simplified.size()+4);
const int n = simplified.size()/4;
for (int j = n-1; j > i; --j)
{
simplified[j*4+0] = simplified[(j-1)*4+0];
simplified[j*4+1] = simplified[(j-1)*4+1];
simplified[j*4+2] = simplified[(j-1)*4+2];
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = points[maxi*4+0];
simplified[(i+1)*4+1] = points[maxi*4+1];
simplified[(i+1)*4+2] = points[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
}
else
{
++i;
}
}
}
for (int i = 0; i < simplified.size()/4; ++i)
{
// The edge vertex flag is take from the current raw point,
// and the neighbour region is take from the next raw point.
const int ai = (simplified[i*4+3]+1) % pn;
const int bi = simplified[i*4+3];
simplified[i*4+3] = (points[ai*4+3] & (RC_CONTOUR_REG_MASK|RC_AREA_BORDER)) | (points[bi*4+3] & RC_BORDER_VERTEX);
}
}
static int calcAreaOfPolygon2D(const int* verts, const int nverts)
{
int area = 0;
for (int i = 0, j = nverts-1; i < nverts; j=i++)
{
const int* vi = &verts[i*4];
const int* vj = &verts[j*4];
area += vi[0] * vj[2] - vj[0] * vi[2];
}
return (area+1) / 2;
}
// TODO: these are the same as in RecastMesh.cpp, consider using the same.
inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
inline int area2(const int* a, const int* b, const int* c)
{
return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
}
// Exclusive or: true iff exactly one argument is true.
// The arguments are negated to ensure that they are 0/1
// values. Then the bitwise Xor operator may apply.
// (This idea is due to Michael Baldwin.)
inline bool xorb(bool x, bool y)
{
return !x ^ !y;
}
// Returns true iff c is strictly to the left of the directed
// line through a to b.
inline bool left(const int* a, const int* b, const int* c)
{
return area2(a, b, c) < 0;
}
inline bool leftOn(const int* a, const int* b, const int* c)
{
return area2(a, b, c) <= 0;
}
inline bool collinear(const int* a, const int* b, const int* c)
{
return area2(a, b, c) == 0;
}
// Returns true iff ab properly intersects cd: they share
// a point interior to both segments. The properness of the
// intersection is ensured by using strict leftness.
static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
{
// Eliminate improper cases.
if (collinear(a,b,c) || collinear(a,b,d) ||
collinear(c,d,a) || collinear(c,d,b))
return false;
return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
}
// Returns T iff (a,b,c) are collinear and point c lies
// on the closed segement ab.
static bool between(const int* a, const int* b, const int* c)
{
if (!collinear(a, b, c))
return false;
// If ab not vertical, check betweenness on x; else on y.
if (a[0] != b[0])
return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
else
return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
}
// Returns true iff segments ab and cd intersect, properly or improperly.
static bool intersect(const int* a, const int* b, const int* c, const int* d)
{
if (intersectProp(a, b, c, d))
return true;
else if (between(a, b, c) || between(a, b, d) ||
between(c, d, a) || between(c, d, b))
return true;
else
return false;
}
static bool vequal(const int* a, const int* b)
{
return a[0] == b[0] && a[2] == b[2];
}
static bool intersectSegCountour(const int* d0, const int* d1, int i, int n, const int* verts)
{
// For each edge (k,k+1) of P
for (int k = 0; k < n; k++)
{
int k1 = next(k, n);
// Skip edges incident to i.
if (i == k || i == k1)
continue;
const int* p0 = &verts[k * 4];
const int* p1 = &verts[k1 * 4];
if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
continue;
if (intersect(d0, d1, p0, p1))
return true;
}
return false;
}
static bool inCone(int i, int n, const int* verts, const int* pj)
{
const int* pi = &verts[i * 4];
const int* pi1 = &verts[next(i, n) * 4];
const int* pin1 = &verts[prev(i, n) * 4];
// If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
if (leftOn(pin1, pi, pi1))
return left(pi, pj, pin1) && left(pj, pi, pi1);
// Assume (i-1,i,i+1) not collinear.
// else P[i] is reflex.
return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
}
static void removeDegenerateSegments(rcIntArray& simplified)
{
// Remove adjacent vertices which are equal on xz-plane,
// or else the triangulator will get confused.
int npts = simplified.size()/4;
for (int i = 0; i < npts; ++i)
{
int ni = next(i, npts);
if (vequal(&simplified[i*4], &simplified[ni*4]))
{
// Degenerate segment, remove.
for (int j = i; j < simplified.size()/4-1; ++j)
{
simplified[j*4+0] = simplified[(j+1)*4+0];
simplified[j*4+1] = simplified[(j+1)*4+1];
simplified[j*4+2] = simplified[(j+1)*4+2];
simplified[j*4+3] = simplified[(j+1)*4+3];
}
simplified.resize(simplified.size()-4);
npts--;
}
}
}
static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
{
const int maxVerts = ca.nverts + cb.nverts + 2;
int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM);
if (!verts)
return false;
int nv = 0;
// Copy contour A.
for (int i = 0; i <= ca.nverts; ++i)
{
int* dst = &verts[nv*4];
const int* src = &ca.verts[((ia+i)%ca.nverts)*4];
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
nv++;
}
// Copy contour B
for (int i = 0; i <= cb.nverts; ++i)
{
int* dst = &verts[nv*4];
const int* src = &cb.verts[((ib+i)%cb.nverts)*4];
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
nv++;
}
rcFree(ca.verts);
ca.verts = verts;
ca.nverts = nv;
rcFree(cb.verts);
cb.verts = 0;
cb.nverts = 0;
return true;
}
struct rcContourHole
{
rcContour* contour;
int minx, minz, leftmost;
};
struct rcContourRegion
{
rcContour* outline;
rcContourHole* holes;
int nholes;
};
struct rcPotentialDiagonal
{
int vert;
int dist;
};
// Finds the lowest leftmost vertex of a contour.
static void findLeftMostVertex(rcContour* contour, int* minx, int* minz, int* leftmost)
{
*minx = contour->verts[0];
*minz = contour->verts[2];
*leftmost = 0;
for (int i = 1; i < contour->nverts; i++)
{
const int x = contour->verts[i*4+0];
const int z = contour->verts[i*4+2];
if (x < *minx || (x == *minx && z < *minz))
{
*minx = x;
*minz = z;
*leftmost = i;
}
}
}
static int compareHoles(const void* va, const void* vb)
{
const rcContourHole* a = (const rcContourHole*)va;
const rcContourHole* b = (const rcContourHole*)vb;
if (a->minx == b->minx)
{
if (a->minz < b->minz)
return -1;
if (a->minz > b->minz)
return 1;
}
else
{
if (a->minx < b->minx)
return -1;
if (a->minx > b->minx)
return 1;
}
return 0;
}
static int compareDiagDist(const void* va, const void* vb)
{
const rcPotentialDiagonal* a = (const rcPotentialDiagonal*)va;
const rcPotentialDiagonal* b = (const rcPotentialDiagonal*)vb;
if (a->dist < b->dist)
return -1;
if (a->dist > b->dist)
return 1;
return 0;
}
static void mergeRegionHoles(rcContext* ctx, rcContourRegion& region)
{
// Sort holes from left to right.
for (int i = 0; i < region.nholes; i++)
findLeftMostVertex(region.holes[i].contour, ®ion.holes[i].minx, ®ion.holes[i].minz, ®ion.holes[i].leftmost);
qsort(region.holes, region.nholes, sizeof(rcContourHole), compareHoles);
int maxVerts = region.outline->nverts;
for (int i = 0; i < region.nholes; i++)
maxVerts += region.holes[i].contour->nverts;
rcScopedDelete<rcPotentialDiagonal> diags = (rcPotentialDiagonal*)rcAlloc(sizeof(rcPotentialDiagonal)*maxVerts, RC_ALLOC_TEMP);
if (!diags)
{
ctx->log(RC_LOG_WARNING, "mergeRegionHoles: Failed to allocated diags %d.", maxVerts);
return;
}
rcContour* outline = region.outline;
// Merge holes into the outline one by one.
for (int i = 0; i < region.nholes; i++)
{
rcContour* hole = region.holes[i].contour;
int index = -1;
int bestVertex = region.holes[i].leftmost;
for (int iter = 0; iter < hole->nverts; iter++)
{
// Find potential diagonals.
// The 'best' vertex must be in the cone described by 3 cosequtive vertices of the outline.
// ..o j-1
// |
// | * best
// |
// j o-----o j+1
// :
int ndiags = 0;
const int* corner = &hole->verts[bestVertex*4];
for (int j = 0; j < outline->nverts; j++)
{
if (inCone(j, outline->nverts, outline->verts, corner))
{
int dx = outline->verts[j*4+0] - corner[0];
int dz = outline->verts[j*4+2] - corner[2];
diags[ndiags].vert = j;
diags[ndiags].dist = dx*dx + dz*dz;
ndiags++;
}
}
// Sort potential diagonals by distance, we want to make the connection as short as possible.
qsort(diags, ndiags, sizeof(rcPotentialDiagonal), compareDiagDist);
// Find a diagonal that is not intersecting the outline not the remaining holes.
index = -1;
for (int j = 0; j < ndiags; j++)
{
const int* pt = &outline->verts[diags[j].vert*4];
bool intersect = intersectSegCountour(pt, corner, diags[i].vert, outline->nverts, outline->verts);
for (int k = i; k < region.nholes && !intersect; k++)
intersect |= intersectSegCountour(pt, corner, -1, region.holes[k].contour->nverts, region.holes[k].contour->verts);
if (!intersect)
{
index = diags[j].vert;
break;
}
}
// If found non-intersecting diagonal, stop looking.
if (index != -1)
break;
// All the potential diagonals for the current vertex were intersecting, try next vertex.
bestVertex = (bestVertex + 1) % hole->nverts;
}
if (index == -1)
{
ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to find merge points for %p and %p.", region.outline, hole);
continue;
}
if (!mergeContours(*region.outline, *hole, index, bestVertex))
{
ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to merge contours %p and %p.", region.outline, hole);
continue;
}
}
}
/// @par
///
/// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen
/// parameters control how closely the simplified contours will match the raw contours.
///
/// Simplified contours are generated such that the vertices for portals between areas match up.
/// (They are considered mandatory vertices.)
///
/// Setting @p maxEdgeLength to zero will disabled the edge length feature.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig
bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
const float maxError, const int maxEdgeLen,
rcContourSet& cset, const int buildFlags)
{
rcAssert(ctx);
const int w = chf.width;
const int h = chf.height;
const int borderSize = chf.borderSize;
ctx->startTimer(RC_TIMER_BUILD_CONTOURS);
rcVcopy(cset.bmin, chf.bmin);
rcVcopy(cset.bmax, chf.bmax);
if (borderSize > 0)
{
// If the heightfield was build with bordersize, remove the offset.
const float pad = borderSize*chf.cs;
cset.bmin[0] += pad;
cset.bmin[2] += pad;
cset.bmax[0] -= pad;
cset.bmax[2] -= pad;
}
cset.cs = chf.cs;
cset.ch = chf.ch;
cset.width = chf.width - chf.borderSize*2;
cset.height = chf.height - chf.borderSize*2;
cset.borderSize = chf.borderSize;
int maxContours = rcMax((int)chf.maxRegions, 8);
cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
if (!cset.conts)
return false;
cset.nconts = 0;
rcScopedDelete<unsigned char> flags = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!flags)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount);
return false;
}
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
// Mark boundaries.
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
unsigned char res = 0;
const rcCompactSpan& s = chf.spans[i];
if (!chf.spans[i].reg || (chf.spans[i].reg & RC_BORDER_REG))
{
flags[i] = 0;
continue;
}
for (int dir = 0; dir < 4; ++dir)
{
unsigned short r = 0;
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dir);
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
r = chf.spans[ai].reg;
}
if (r == chf.spans[i].reg)
res |= (1 << dir);
}
flags[i] = res ^ 0xf; // Inverse, mark non connected edges.
}
}
}
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
rcIntArray verts(256);
rcIntArray simplified(64);
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (flags[i] == 0 || flags[i] == 0xf)
{
flags[i] = 0;
continue;
}
const unsigned short reg = chf.spans[i].reg;
if (!reg || (reg & RC_BORDER_REG))
continue;
const unsigned char area = chf.areas[i];
verts.resize(0);
simplified.resize(0);
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
walkContour(x, y, i, chf, flags, verts);
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags);
removeDegenerateSegments(simplified);
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
// Store region->contour remap info.
// Create contour.
if (simplified.size()/4 >= 3)
{
if (cset.nconts >= maxContours)
{
// Allocate more contours.
// This happens when a region has holes.
const int oldMax = maxContours;
maxContours *= 2;
rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
for (int j = 0; j < cset.nconts; ++j)
{
newConts[j] = cset.conts[j];
// Reset source pointers to prevent data deletion.
cset.conts[j].verts = 0;
cset.conts[j].rverts = 0;
}
rcFree(cset.conts);
cset.conts = newConts;
ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours);
}
rcContour* cont = &cset.conts[cset.nconts++];
cont->nverts = simplified.size()/4;
cont->verts = (int*)rcAlloc(sizeof(int)*cont->nverts*4, RC_ALLOC_PERM);
if (!cont->verts)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'verts' (%d).", cont->nverts);
return false;
}
memcpy(cont->verts, &simplified[0], sizeof(int)*cont->nverts*4);
if (borderSize > 0)
{
// If the heightfield was build with bordersize, remove the offset.
for (int j = 0; j < cont->nverts; ++j)
{
int* v = &cont->verts[j*4];
v[0] -= borderSize;
v[2] -= borderSize;
}
}
cont->nrverts = verts.size()/4;
cont->rverts = (int*)rcAlloc(sizeof(int)*cont->nrverts*4, RC_ALLOC_PERM);
if (!cont->rverts)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'rverts' (%d).", cont->nrverts);
return false;
}
memcpy(cont->rverts, &verts[0], sizeof(int)*cont->nrverts*4);
if (borderSize > 0)
{
// If the heightfield was build with bordersize, remove the offset.
for (int j = 0; j < cont->nrverts; ++j)
{
int* v = &cont->rverts[j*4];
v[0] -= borderSize;
v[2] -= borderSize;
}
}
cont->reg = reg;
cont->area = area;
}
}
}
}
// Merge holes if needed.
if (cset.nconts > 0)
{
// Calculate winding of all polygons.
rcScopedDelete<char> winding = (char*)rcAlloc(sizeof(char)*cset.nconts, RC_ALLOC_TEMP);
if (!winding)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'hole' (%d).", cset.nconts);
return false;
}
int nholes = 0;
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
// If the contour is wound backwards, it is a hole.
winding[i] = calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0 ? -1 : 1;
if (winding[i] < 0)
nholes++;
}
if (nholes > 0)
{
// Collect outline contour and holes contours per region.
// We assume that there is one outline and multiple holes.
const int nregions = chf.maxRegions+1;
rcScopedDelete<rcContourRegion> regions = (rcContourRegion*)rcAlloc(sizeof(rcContourRegion)*nregions, RC_ALLOC_TEMP);
if (!regions)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'regions' (%d).", nregions);
return false;
}
memset(regions, 0, sizeof(rcContourRegion)*nregions);
rcScopedDelete<rcContourHole> holes = (rcContourHole*)rcAlloc(sizeof(rcContourHole)*cset.nconts, RC_ALLOC_TEMP);
if (!holes)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'holes' (%d).", cset.nconts);
return false;
}
memset(holes, 0, sizeof(rcContourHole)*cset.nconts);
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
// Positively would contours are outlines, negative holes.
if (winding[i] > 0)
{
if (regions[cont.reg].outline)
ctx->log(RC_LOG_ERROR, "rcBuildContours: Multiple outlines for region %d.", cont.reg);
regions[cont.reg].outline = &cont;
}
else
{
regions[cont.reg].nholes++;
}
}
int index = 0;
for (int i = 0; i < nregions; i++)
{
if (regions[i].nholes > 0)
{
regions[i].holes = &holes[index];
index += regions[i].nholes;
regions[i].nholes = 0;
}
}
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
rcContourRegion& reg = regions[cont.reg];
if (winding[i] < 0)
reg.holes[reg.nholes++].contour = &cont;
}
// Finally merge each regions holes into the outline.
for (int i = 0; i < nregions; i++)
{
rcContourRegion& reg = regions[i];
if (!reg.nholes) continue;
if (reg.outline)
{
mergeRegionHoles(ctx, reg);
}
else
{
// The region does not have an outline.
// This can happen if the contour becaomes selfoverlapping because of
// too aggressive simplification settings.
ctx->log(RC_LOG_ERROR, "rcBuildContours: Bad outline for region %d, contour simplification is likely too aggressive.", i);
}
}
}
}
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS);
return true;
}
| 0 | 0.991178 | 1 | 0.991178 | game-dev | MEDIA | 0.342404 | game-dev | 0.992422 | 1 | 0.992422 |
seed4j/seed4j | 2,191 | src/main/java/com/seed4j/generator/server/javatool/modernizer/domain/ModernizerModuleFactory.java | package com.seed4j.generator.server.javatool.modernizer.domain;
import static com.seed4j.module.domain.Seed4JModule.gradleCommunityPlugin;
import static com.seed4j.module.domain.Seed4JModule.mavenPlugin;
import static com.seed4j.module.domain.Seed4JModule.moduleBuilder;
import static com.seed4j.module.domain.Seed4JModule.pluginExecution;
import static com.seed4j.module.domain.mavenplugin.MavenBuildPhase.VERIFY;
import com.seed4j.module.domain.Seed4JModule;
import com.seed4j.module.domain.gradleplugin.GradleMainBuildPlugin;
import com.seed4j.module.domain.mavenplugin.MavenPlugin;
import com.seed4j.module.domain.properties.Seed4JModuleProperties;
import com.seed4j.shared.error.domain.Assert;
public class ModernizerModuleFactory {
private static final String MODERNIZER = "modernizer";
public Seed4JModule buildModule(Seed4JModuleProperties properties) {
Assert.notNull("properties", properties);
// @formatter:off
return moduleBuilder(properties)
.mavenPlugins()
.pluginManagement(modernizerMavenPluginManagement())
.plugin(modernizerMavenPlugin().build())
.and()
.gradlePlugins()
.plugin(modernizerGradlePlugin())
.and()
.build();
// @formatter:on
}
private MavenPlugin.MavenPluginOptionalBuilder modernizerMavenPlugin() {
return mavenPlugin().groupId("org.gaul").artifactId("modernizer-maven-plugin");
}
private MavenPlugin modernizerMavenPluginManagement() {
return modernizerMavenPlugin()
.versionSlug("modernizer-maven-plugin")
.configuration(
"""
<javaVersion>${java.version}</javaVersion>
<failOnViolations>true</failOnViolations>
"""
)
.addExecution(pluginExecution().goals(MODERNIZER).id(MODERNIZER).phase(VERIFY))
.build();
}
private GradleMainBuildPlugin modernizerGradlePlugin() {
return gradleCommunityPlugin()
.id("com.github.andygoossens.modernizer")
.pluginSlug(MODERNIZER)
.versionSlug(MODERNIZER)
.configuration(
"""
modernizer {
failOnViolations = true
includeTestClasses = true
}
"""
)
.build();
}
}
| 0 | 0.77484 | 1 | 0.77484 | game-dev | MEDIA | 0.343271 | game-dev | 0.682286 | 1 | 0.682286 |
ww-rm/SpineViewer | 14,431 | SpineRuntimes/SpineRuntime34/ExposedList.cs | //
// System.Collections.Generic.List
//
// Authors:
// Ben Maurer (bmaurer@ximian.com)
// Martin Baulig (martin@ximian.com)
// Carlos Alberto Cortez (calberto.cortez@gmail.com)
// David Waite (mass@akuma.org)
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2005 David Waite
//
// 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.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace SpineRuntime34 {
[Serializable]
[DebuggerDisplay("Count={Count}")]
public class ExposedList<T> : IEnumerable<T> {
public T[] Items;
public int Count;
private const int DefaultCapacity = 4;
private static readonly T[] EmptyArray = new T[0];
private int version;
public ExposedList () {
Items = EmptyArray;
}
public ExposedList (IEnumerable<T> collection) {
CheckCollection(collection);
// initialize to needed size (if determinable)
ICollection<T> c = collection as ICollection<T>;
if (c == null) {
Items = EmptyArray;
AddEnumerable(collection);
} else {
Items = new T[c.Count];
AddCollection(c);
}
}
public ExposedList (int capacity) {
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity");
Items = new T[capacity];
}
internal ExposedList (T[] data, int size) {
Items = data;
Count = size;
}
public void Add (T item) {
// If we check to see if we need to grow before trying to grow
// we can speed things up by 25%
if (Count == Items.Length)
GrowIfNeeded(1);
Items[Count++] = item;
version++;
}
public void GrowIfNeeded (int newCount) {
int minimumSize = Count + newCount;
if (minimumSize > Items.Length)
Capacity = Math.Max(Math.Max(Capacity * 2, DefaultCapacity), minimumSize);
}
public ExposedList<T> Resize (int newSize) {
if (newSize > Items.Length) Array.Resize(ref Items, newSize);
Count = newSize;
return this;
}
private void CheckRange (int idx, int count) {
if (idx < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if ((uint)idx + (uint)count > (uint)Count)
throw new ArgumentException("index and count exceed length of list");
}
private void AddCollection (ICollection<T> collection) {
int collectionCount = collection.Count;
if (collectionCount == 0)
return;
GrowIfNeeded(collectionCount);
collection.CopyTo(Items, Count);
Count += collectionCount;
}
private void AddEnumerable (IEnumerable<T> enumerable) {
foreach (T t in enumerable) {
Add(t);
}
}
public void AddRange (IEnumerable<T> collection) {
CheckCollection(collection);
ICollection<T> c = collection as ICollection<T>;
if (c != null)
AddCollection(c);
else
AddEnumerable(collection);
version++;
}
public int BinarySearch (T item) {
return Array.BinarySearch<T>(Items, 0, Count, item);
}
public int BinarySearch (T item, IComparer<T> comparer) {
return Array.BinarySearch<T>(Items, 0, Count, item, comparer);
}
public int BinarySearch (int index, int count, T item, IComparer<T> comparer) {
CheckRange(index, count);
return Array.BinarySearch<T>(Items, index, count, item, comparer);
}
public void Clear (bool clearArray = true) {
if (clearArray)
Array.Clear(Items, 0, Items.Length);
Count = 0;
version++;
}
public bool Contains (T item) {
return Array.IndexOf<T>(Items, item, 0, Count) != -1;
}
public ExposedList<TOutput> ConvertAll<TOutput> (Converter<T, TOutput> converter) {
if (converter == null)
throw new ArgumentNullException("converter");
ExposedList<TOutput> u = new ExposedList<TOutput>(Count);
for (int i = 0; i < Count; i++)
u.Items[i] = converter(Items[i]);
u.Count = Count;
return u;
}
public void CopyTo (T[] array) {
Array.Copy(Items, 0, array, 0, Count);
}
public void CopyTo (T[] array, int arrayIndex) {
Array.Copy(Items, 0, array, arrayIndex, Count);
}
public void CopyTo (int index, T[] array, int arrayIndex, int count) {
CheckRange(index, count);
Array.Copy(Items, index, array, arrayIndex, count);
}
public bool Exists (Predicate<T> match) {
CheckMatch(match);
return GetIndex(0, Count, match) != -1;
}
public T Find (Predicate<T> match) {
CheckMatch(match);
int i = GetIndex(0, Count, match);
return (i != -1) ? Items[i] : default(T);
}
private static void CheckMatch (Predicate<T> match) {
if (match == null)
throw new ArgumentNullException("match");
}
public ExposedList<T> FindAll (Predicate<T> match) {
CheckMatch(match);
return FindAllList(match);
}
private ExposedList<T> FindAllList (Predicate<T> match) {
ExposedList<T> results = new ExposedList<T>();
for (int i = 0; i < Count; i++)
if (match(Items[i]))
results.Add(Items[i]);
return results;
}
public int FindIndex (Predicate<T> match) {
CheckMatch(match);
return GetIndex(0, Count, match);
}
public int FindIndex (int startIndex, Predicate<T> match) {
CheckMatch(match);
CheckIndex(startIndex);
return GetIndex(startIndex, Count - startIndex, match);
}
public int FindIndex (int startIndex, int count, Predicate<T> match) {
CheckMatch(match);
CheckRange(startIndex, count);
return GetIndex(startIndex, count, match);
}
private int GetIndex (int startIndex, int count, Predicate<T> match) {
int end = startIndex + count;
for (int i = startIndex; i < end; i++)
if (match(Items[i]))
return i;
return -1;
}
public T FindLast (Predicate<T> match) {
CheckMatch(match);
int i = GetLastIndex(0, Count, match);
return i == -1 ? default(T) : Items[i];
}
public int FindLastIndex (Predicate<T> match) {
CheckMatch(match);
return GetLastIndex(0, Count, match);
}
public int FindLastIndex (int startIndex, Predicate<T> match) {
CheckMatch(match);
CheckIndex(startIndex);
return GetLastIndex(0, startIndex + 1, match);
}
public int FindLastIndex (int startIndex, int count, Predicate<T> match) {
CheckMatch(match);
int start = startIndex - count + 1;
CheckRange(start, count);
return GetLastIndex(start, count, match);
}
private int GetLastIndex (int startIndex, int count, Predicate<T> match) {
// unlike FindLastIndex, takes regular params for search range
for (int i = startIndex + count; i != startIndex; )
if (match(Items[--i]))
return i;
return -1;
}
public void ForEach (Action<T> action) {
if (action == null)
throw new ArgumentNullException("action");
for (int i = 0; i < Count; i++)
action(Items[i]);
}
public Enumerator GetEnumerator () {
return new Enumerator(this);
}
public ExposedList<T> GetRange (int index, int count) {
CheckRange(index, count);
T[] tmpArray = new T[count];
Array.Copy(Items, index, tmpArray, 0, count);
return new ExposedList<T>(tmpArray, count);
}
public int IndexOf (T item) {
return Array.IndexOf<T>(Items, item, 0, Count);
}
public int IndexOf (T item, int index) {
CheckIndex(index);
return Array.IndexOf<T>(Items, item, index, Count - index);
}
public int IndexOf (T item, int index, int count) {
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if ((uint)index + (uint)count > (uint)Count)
throw new ArgumentOutOfRangeException("index and count exceed length of list");
return Array.IndexOf<T>(Items, item, index, count);
}
private void Shift (int start, int delta) {
if (delta < 0)
start -= delta;
if (start < Count)
Array.Copy(Items, start, Items, start + delta, Count - start);
Count += delta;
if (delta < 0)
Array.Clear(Items, Count, -delta);
}
private void CheckIndex (int index) {
if (index < 0 || (uint)index > (uint)Count)
throw new ArgumentOutOfRangeException("index");
}
public void Insert (int index, T item) {
CheckIndex(index);
if (Count == Items.Length)
GrowIfNeeded(1);
Shift(index, 1);
Items[index] = item;
version++;
}
private void CheckCollection (IEnumerable<T> collection) {
if (collection == null)
throw new ArgumentNullException("collection");
}
public void InsertRange (int index, IEnumerable<T> collection) {
CheckCollection(collection);
CheckIndex(index);
if (collection == this) {
T[] buffer = new T[Count];
CopyTo(buffer, 0);
GrowIfNeeded(Count);
Shift(index, buffer.Length);
Array.Copy(buffer, 0, Items, index, buffer.Length);
} else {
ICollection<T> c = collection as ICollection<T>;
if (c != null)
InsertCollection(index, c);
else
InsertEnumeration(index, collection);
}
version++;
}
private void InsertCollection (int index, ICollection<T> collection) {
int collectionCount = collection.Count;
GrowIfNeeded(collectionCount);
Shift(index, collectionCount);
collection.CopyTo(Items, index);
}
private void InsertEnumeration (int index, IEnumerable<T> enumerable) {
foreach (T t in enumerable)
Insert(index++, t);
}
public int LastIndexOf (T item) {
return Array.LastIndexOf<T>(Items, item, Count - 1, Count);
}
public int LastIndexOf (T item, int index) {
CheckIndex(index);
return Array.LastIndexOf<T>(Items, item, index, index + 1);
}
public int LastIndexOf (T item, int index, int count) {
if (index < 0)
throw new ArgumentOutOfRangeException("index", index, "index is negative");
if (count < 0)
throw new ArgumentOutOfRangeException("count", count, "count is negative");
if (index - count + 1 < 0)
throw new ArgumentOutOfRangeException("count", count, "count is too large");
return Array.LastIndexOf<T>(Items, item, index, count);
}
public bool Remove (T item) {
int loc = IndexOf(item);
if (loc != -1)
RemoveAt(loc);
return loc != -1;
}
public int RemoveAll (Predicate<T> match) {
CheckMatch(match);
int i = 0;
int j = 0;
// Find the first item to remove
for (i = 0; i < Count; i++)
if (match(Items[i]))
break;
if (i == Count)
return 0;
version++;
// Remove any additional items
for (j = i + 1; j < Count; j++) {
if (!match(Items[j]))
Items[i++] = Items[j];
}
if (j - i > 0)
Array.Clear(Items, i, j - i);
Count = i;
return (j - i);
}
public void RemoveAt (int index) {
if (index < 0 || (uint)index >= (uint)Count)
throw new ArgumentOutOfRangeException("index");
Shift(index, -1);
Array.Clear(Items, Count, 1);
version++;
}
public void RemoveRange (int index, int count) {
CheckRange(index, count);
if (count > 0) {
Shift(index, -count);
Array.Clear(Items, Count, count);
version++;
}
}
public void Reverse () {
Array.Reverse(Items, 0, Count);
version++;
}
public void Reverse (int index, int count) {
CheckRange(index, count);
Array.Reverse(Items, index, count);
version++;
}
public void Sort () {
Array.Sort<T>(Items, 0, Count, Comparer<T>.Default);
version++;
}
public void Sort (IComparer<T> comparer) {
Array.Sort<T>(Items, 0, Count, comparer);
version++;
}
public void Sort (Comparison<T> comparison) {
Array.Sort<T>(Items, comparison);
version++;
}
public void Sort (int index, int count, IComparer<T> comparer) {
CheckRange(index, count);
Array.Sort<T>(Items, index, count, comparer);
version++;
}
public T[] ToArray () {
T[] t = new T[Count];
Array.Copy(Items, t, Count);
return t;
}
public void TrimExcess () {
Capacity = Count;
}
public bool TrueForAll (Predicate<T> match) {
CheckMatch(match);
for (int i = 0; i < Count; i++)
if (!match(Items[i]))
return false;
return true;
}
public int Capacity {
get {
return Items.Length;
}
set {
if ((uint)value < (uint)Count)
throw new ArgumentOutOfRangeException();
Array.Resize(ref Items, value);
}
}
#region Interface implementations.
IEnumerator<T> IEnumerable<T>.GetEnumerator () {
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator () {
return GetEnumerator();
}
#endregion
[Serializable]
public struct Enumerator : IEnumerator<T>, IDisposable {
private ExposedList<T> l;
private int next;
private int ver;
private T current;
internal Enumerator (ExposedList<T> l)
: this() {
this.l = l;
ver = l.version;
}
public void Dispose () {
l = null;
}
private void VerifyState () {
if (l == null)
throw new ObjectDisposedException(GetType().FullName);
if (ver != l.version)
throw new InvalidOperationException(
"Collection was modified; enumeration operation may not execute.");
}
public bool MoveNext () {
VerifyState();
if (next < 0)
return false;
if (next < l.Count) {
current = l.Items[next++];
return true;
}
next = -1;
return false;
}
public T Current {
get {
return current;
}
}
void IEnumerator.Reset () {
VerifyState();
next = 0;
}
object IEnumerator.Current {
get {
VerifyState();
if (next <= 0)
throw new InvalidOperationException();
return current;
}
}
}
}
}
| 0 | 0.851209 | 1 | 0.851209 | game-dev | MEDIA | 0.328955 | game-dev | 0.955123 | 1 | 0.955123 |
AndroidCSOfficial/android-code-studio | 11,504 | event/eventbus/src/main/java/org/greenrobot/eventbus/SubscriberMethodFinder.java | /*
* Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.greenrobot.eventbus;
import org.greenrobot.eventbus.meta.SubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
class SubscriberMethodFinder {
/*
* In newer class files, compilers may add methods. Those are called bridge or synthetic methods.
* EventBus must ignore both. There modifiers are not public but defined in the Java class file format:
* http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.6-200-A.1
*/
private static final int BRIDGE = 0x40;
private static final int SYNTHETIC = 0x1000;
private static final int MODIFIERS_IGNORE =
Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE =
new ConcurrentHashMap<>();
private List<SubscriberInfoIndex> subscriberInfoIndexes;
private final boolean strictMethodVerification;
private final boolean ignoreGeneratedIndex;
private static final int POOL_SIZE = 4;
private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
SubscriberMethodFinder(
List<SubscriberInfoIndex> subscriberInfoIndexes,
boolean strictMethodVerification,
boolean ignoreGeneratedIndex) {
this.subscriberInfoIndexes = subscriberInfoIndexes;
this.strictMethodVerification = strictMethodVerification;
this.ignoreGeneratedIndex = ignoreGeneratedIndex;
}
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException(
"Subscriber "
+ subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
findState.recycle();
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
private FindState prepareFindState() {
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
FindState state = FIND_STATE_POOL[i];
if (state != null) {
FIND_STATE_POOL[i] = null;
return state;
}
}
}
return new FindState();
}
private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null
&& findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see
// https://github.com/greenrobot/EventBus/issues/149
try {
methods = findState.clazz.getMethods();
} catch (
LinkageError error) { // super class of NoClassDefFoundError to be a bit more broad...
String msg = "Could not inspect methods of " + findState.clazz.getName();
if (ignoreGeneratedIndex) {
msg += ". Please consider using EventBus annotation processor to avoid reflection.";
} else {
msg +=
". Please make this class visible to EventBus annotation processor to avoid reflection.";
}
throw new EventBusException(msg, error);
}
findState.skipSuperClasses = true;
}
for (Method method : methods) {
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(
new SubscriberMethod(
method,
eventType,
threadMode,
subscribeAnnotation.priority(),
subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(
"@Subscribe method "
+ methodName
+ "must have exactly 1 parameter but has "
+ parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(
methodName
+ " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}
static void clearCaches() {
METHOD_CACHE.clear();
}
static class FindState {
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
final StringBuilder methodKeyBuilder = new StringBuilder(128);
Class<?> subscriberClass;
Class<?> clazz;
boolean skipSuperClasses;
SubscriberInfo subscriberInfo;
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
void recycle() {
subscriberMethods.clear();
anyMethodByEventType.clear();
subscriberClassByMethodKey.clear();
methodKeyBuilder.setLength(0);
subscriberClass = null;
clazz = null;
skipSuperClasses = false;
subscriberInfo = null;
}
boolean checkAdd(Method method, Class<?> eventType) {
// 2 level check: 1st level with event type only (fast), 2nd level with complete signature
// when required.
// Usually a subscriber doesn't have methods listening to the same event type.
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;
} else {
if (existing instanceof Method) {
if (!checkAddWithMethodSignature((Method) existing, eventType)) {
// Paranoia check
throw new IllegalStateException();
}
// Put any non-Method object to "consume" the existing Method
anyMethodByEventType.put(eventType, this);
}
return checkAddWithMethodSignature(method, eventType);
}
}
private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());
String methodKey = methodKeyBuilder.toString();
Class<?> methodClass = method.getDeclaringClass();
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
// Only add if not already found in a sub class
return true;
} else {
// Revert the put, old class is further down the class hierarchy
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}
}
void moveToSuperclass() {
if (skipSuperClasses) {
clazz = null;
} else {
clazz = clazz.getSuperclass();
String clazzName = clazz.getName();
// Skip system classes, this degrades performance.
// Also we might avoid some ClassNotFoundException (see FAQ for background).
if (clazzName.startsWith("java.")
|| clazzName.startsWith("javax.")
|| clazzName.startsWith("android.")
|| clazzName.startsWith("androidx.")
|| clazzName.startsWith("jdkx.")
|| clazzName.startsWith("openjdk.")) {
clazz = null;
}
}
}
}
}
| 0 | 0.943819 | 1 | 0.943819 | game-dev | MEDIA | 0.227731 | game-dev | 0.991199 | 1 | 0.991199 |
smartgrass/XCSkillEditor_Unity | 2,170 | Assets/_3rd/Flux/Runtime/Events/Script/FCallFunctionEvent.cs | using UnityEngine;
using System;
using System.Reflection;
namespace Flux
{
//[FEvent("Script/Call Function")]
public class FCallFunctionEvent : FEvent {
public const BindingFlags METHOD_FLAGS = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
[SerializeField]
[Tooltip("If false, it gets called every tick")]
private bool _callOnlyOnTrigger = true;
public bool CallOnlyOnTrigger { get { return _callOnlyOnTrigger; } set { _callOnlyOnTrigger = value; } }
[SerializeField]
[HideInInspector]
private string _className = null;
public string ClassName { get { return _className; } set { _className = value; } }
[SerializeField]
[HideInInspector]
private string _methodName = null;
public string MethodName { get { return _methodName; } set { _methodName = value; } }
private Type _classType = null;
private object _scriptReference = null;
private MethodInfo _methodInfo = null;
protected override void OnInit()
{
_classType = GetType(_className);
if (_classType != null)
{
_scriptReference = Owner.GetComponent(_classType);
if (_scriptReference != null)
{
#if NETFX_CORE
_methodInfo = TypeExtensions.GetMethod( _classType, _methodName, METHOD_FLAGS );
#else
_methodInfo = _classType.GetMethod(_methodName, METHOD_FLAGS);
#endif
}
}
}
protected override void OnTrigger( float timeSinceTrigger )
{
CallFunction();
}
protected override void OnUpdateEvent( float timeSinceTrigger )
{
if( _callOnlyOnTrigger )
return;
CallFunction();
}
private Type GetType(string className)
{
Type type = Type.GetType(className);
if( type == null )
{
Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
for(int i = 0; i != assemblies.Length; ++i )
{
type = assemblies[i].GetType(className);
if( type != null )
break;
}
}
return type;
}
private void CallFunction()
{
if( _methodInfo != null )
{
if( _methodInfo.IsStatic )
_methodInfo.Invoke( null, null );
else
_methodInfo.Invoke( _scriptReference, null );
}
}
}
}
| 0 | 0.961365 | 1 | 0.961365 | game-dev | MEDIA | 0.754974 | game-dev | 0.951963 | 1 | 0.951963 |
stephengold/Libbulletjme | 4,801 | src/main/native/bullet3/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_CONVEX_CONVEX_ALGORITHM_H
#define BT_CONVEX_CONVEX_ALGORITHM_H
#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "btCollisionCreateFunc.h"
#include "btCollisionDispatcher.h"
#include "LinearMath/btTransformUtil.h" //for btConvexSeparatingDistanceUtil
#include "BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.h"
class btConvexPenetrationDepthSolver;
///Enabling USE_SEPDISTANCE_UTIL2 requires 100% reliable distance computation. However, when using large size ratios GJK can be imprecise
///so the distance is not conservative. In that case, enabling this USE_SEPDISTANCE_UTIL2 would result in failing/missing collisions.
///Either improve GJK for large size ratios (testing a 100 units versus a 0.1 unit object) or only enable the util
///for certain pairs that have a small size ratio
//#define USE_SEPDISTANCE_UTIL2 1
///The convexConvexAlgorithm collision algorithm implements time of impact, convex closest points and penetration depth calculations between two convex objects.
///Multiple contact points are calculated by perturbing the orientation of the smallest object orthogonal to the separating normal.
///This idea was described by Gino van den Bergen in this forum topic http://www.bulletphysics.com/Bullet/phpBB3/viewtopic.php?f=4&t=288&p=888#p888
class btConvexConvexAlgorithm : public btActivatingCollisionAlgorithm
{
#ifdef USE_SEPDISTANCE_UTIL2
btConvexSeparatingDistanceUtil m_sepDistance;
#endif
btConvexPenetrationDepthSolver* m_pdSolver;
btVertexArray worldVertsB1;
btVertexArray worldVertsB2;
bool m_ownManifold;
btPersistentManifold* m_manifoldPtr;
bool m_lowLevelOfDetail;
int m_numPerturbationIterations;
int m_minimumPointsPerturbationThreshold;
///cache separating vector to speedup collision detection
public:
btConvexConvexAlgorithm(btPersistentManifold* mf, const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, btConvexPenetrationDepthSolver* pdSolver, int numPerturbationIterations, int minimumPointsPerturbationThreshold);
virtual ~btConvexConvexAlgorithm();
virtual void processCollision(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut);
virtual btScalar calculateTimeOfImpact(btCollisionObject* body0, btCollisionObject* body1, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut);
virtual void getAllContactManifolds(btManifoldArray& manifoldArray)
{
///should we use m_ownManifold to avoid adding duplicates?
if (m_manifoldPtr && m_ownManifold)
manifoldArray.push_back(m_manifoldPtr);
}
void setLowLevelOfDetail(bool useLowLevel);
const btPersistentManifold* getManifold()
{
return m_manifoldPtr;
}
struct CreateFunc : public btCollisionAlgorithmCreateFunc
{
btConvexPenetrationDepthSolver* m_pdSolver;
int m_numPerturbationIterations;
int m_minimumPointsPerturbationThreshold;
CreateFunc(btConvexPenetrationDepthSolver* pdSolver);
virtual ~CreateFunc();
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap)
{
void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexConvexAlgorithm));
return new (mem) btConvexConvexAlgorithm(ci.m_manifold, ci, body0Wrap, body1Wrap, m_pdSolver, m_numPerturbationIterations, m_minimumPointsPerturbationThreshold);
}
};
};
#endif //BT_CONVEX_CONVEX_ALGORITHM_H
| 0 | 0.941023 | 1 | 0.941023 | game-dev | MEDIA | 0.991278 | game-dev | 0.88315 | 1 | 0.88315 |
CrazyVince/Hacking | 15,442 | Library/PackageCache/com.unity.timeline@1.6.4/Editor/Trackhead.cs | using System;
using System.Linq;
using UnityEditor.Timeline.Actions;
using UnityEngine;
using UnityEngine.Timeline;
namespace UnityEditor.Timeline
{
static class Gaps
{
static readonly string kInsertTime = L10n.Tr("Insert Time");
public static void Insert(TimelineAsset asset, double at, double amount, double tolerance)
{
var tracks = asset.flattenedTracks.Where(x => x.lockedInHierarchy == false).ToList();
// gather all clips
var clips = tracks.SelectMany(x => x.clips).Where(x => (x.start - at) >= -tolerance).ToList();
var markers = tracks.SelectMany(x => x.GetMarkers()).Where(x => (x.time - at) >= -tolerance).ToList();
// push undo on the tracks for the clips that are being modified
UndoExtensions.RegisterClips(clips, kInsertTime);
// push the clips
foreach (var clip in clips)
{
clip.start += amount;
}
// push undos and move the markers
UndoExtensions.RegisterMarkers(markers, kInsertTime);
foreach (var marker in markers)
{
marker.time += amount;
}
TimelineEditor.Refresh(RefreshReason.ContentsModified);
}
}
class PlayheadContextMenu : Manipulator
{
readonly TimeAreaItem m_TimeAreaItem;
static readonly int[] kFrameInsertionValues = { 5, 10, 25, 100 };
static readonly GUIContent[] kFrameInsertionValuesGuiContents =
{
L10n.TextContent("Insert/Frame/5 Frames"),
L10n.TextContent("Insert/Frame/10 Frames"),
L10n.TextContent("Insert/Frame/25 Frames"),
L10n.TextContent("Insert/Frame/100 Frames")
};
static readonly GUIContent kSingleFrameGuiContents = L10n.TextContent("Insert/Frame/Single");
static readonly GUIContent kSelectedTimeGuiContents = L10n.TextContent("Insert/Selected Time");
public PlayheadContextMenu(TimeAreaItem timeAreaItem)
{
m_TimeAreaItem = timeAreaItem;
}
protected override bool ContextClick(Event evt, WindowState state)
{
if (!m_TimeAreaItem.bounds.Contains(evt.mousePosition))
return false;
var tolerance = TimeUtility.GetEpsilon(state.editSequence.time, state.referenceSequence.frameRate);
var menu = new GenericMenu();
if (!TimelineWindow.instance.state.editSequence.isReadOnly)
{
menu.AddItem(kSingleFrameGuiContents, false, () =>
Gaps.Insert(state.editSequence.asset, state.editSequence.time,
1.0 / state.referenceSequence.frameRate, tolerance)
);
for (var i = 0; i != kFrameInsertionValues.Length; ++i)
{
double f = kFrameInsertionValues[i];
menu.AddItem(
kFrameInsertionValuesGuiContents[i],
false, () =>
Gaps.Insert(state.editSequence.asset, state.editSequence.time,
f / state.referenceSequence.frameRate, tolerance)
);
}
var playRangeTime = state.playRange;
if (playRangeTime.y > playRangeTime.x)
{
menu.AddItem(kSelectedTimeGuiContents, false, () =>
Gaps.Insert(state.editSequence.asset, playRangeTime.x, playRangeTime.y - playRangeTime.x,
TimeUtility.GetEpsilon(playRangeTime.x, state.referenceSequence.frameRate))
);
}
}
menu.AddItem(L10n.TextContent("Select/Clips Ending Before"), false, () => SelectClipsEndingBefore(state));
menu.AddItem(L10n.TextContent("Select/Clips Starting Before"), false, () => SelectClipsStartingBefore(state));
menu.AddItem(L10n.TextContent("Select/Clips Ending After"), false, () => SelectClipsEndingAfter(state));
menu.AddItem(L10n.TextContent("Select/Clips Starting After"), false, () => SelectClipsStartingAfter(state));
menu.AddItem(L10n.TextContent("Select/Clips Intersecting"), false, () => SelectClipsIntersecting(state));
menu.AddItem(L10n.TextContent("Select/Blends Intersecting"), false, () => SelectBlendsIntersecting(state));
menu.ShowAsContext();
return true;
}
internal static void SelectClipsEndingBefore(WindowState state)
{
var tolerance = TimeUtility.GetEpsilon(state.editSequence.time, state.referenceSequence.frameRate);
SelectMenuCallback(x => x.end < state.editSequence.time + tolerance, state);
}
internal static void SelectClipsStartingBefore(WindowState state)
{
var tolerance = TimeUtility.GetEpsilon(state.editSequence.time, state.referenceSequence.frameRate);
SelectMenuCallback(x => x.start < state.editSequence.time + tolerance, state);
}
internal static void SelectClipsEndingAfter(WindowState state)
{
var tolerance = TimeUtility.GetEpsilon(state.editSequence.time, state.referenceSequence.frameRate);
SelectMenuCallback(x => x.end - state.editSequence.time >= -tolerance, state);
}
internal static void SelectClipsStartingAfter(WindowState state)
{
var tolerance = TimeUtility.GetEpsilon(state.editSequence.time, state.referenceSequence.frameRate);
SelectMenuCallback(x => x.start - state.editSequence.time >= -tolerance, state);
}
internal static void SelectClipsIntersecting(WindowState state)
{
SelectMenuCallback(x => x.start <= state.editSequence.time && state.editSequence.time <= x.end, state);
}
internal static void SelectBlendsIntersecting(WindowState state)
{
SelectMenuCallback(x => SelectBlendingIntersecting(x, state.editSequence.time), state);
}
static bool SelectBlendingIntersecting(TimelineClip clip, double time)
{
return clip.start <= time && time <= clip.end && (
(time <= clip.start + clip.blendInDuration) ||
(time >= clip.end - clip.blendOutDuration)
);
}
static void SelectMenuCallback(Func<TimelineClip, bool> selector, WindowState state)
{
var allClips = state.GetWindow().treeView.allClipGuis;
if (allClips == null)
return;
SelectionManager.Clear();
for (var i = 0; i != allClips.Count; ++i)
{
var c = allClips[i];
if (c != null && c.clip != null && c.clip.GetParentTrack().lockedInHierarchy == false && selector(c.clip))
{
SelectionManager.Add(c.clip);
}
}
}
}
class TimeAreaContextMenu : Manipulator
{
protected override bool ContextClick(Event evt, WindowState state)
{
if (state.timeAreaRect.Contains(Event.current.mousePosition))
{
var menu = new GenericMenu();
AddTimeAreaMenuItems(menu, state);
menu.ShowAsContext();
return true;
}
return false;
}
internal static void AddTimeAreaMenuItems(GenericMenu menu, WindowState state)
{
foreach (var value in Enum.GetValues(typeof(TimelineAsset.DurationMode)))
{
var mode = (TimelineAsset.DurationMode)value;
var item = EditorGUIUtility.TextContent(string.Format(TimelineWindow.Styles.DurationModeText, L10n.Tr(ObjectNames.NicifyVariableName(mode.ToString()))));
if (state.recording || state.IsEditingASubTimeline() || state.editSequence.asset == null
|| state.editSequence.isReadOnly)
menu.AddDisabledItem(item);
else
menu.AddItem(item, state.editSequence.asset.durationMode == mode, () => SelectDurationCallback(state, mode));
menu.AddItem(DirectorStyles.showMarkersOnTimeline, state.showMarkerHeader, () => state.showMarkerHeader = !state.showMarkerHeader);
}
}
static void SelectDurationCallback(WindowState state, TimelineAsset.DurationMode mode)
{
if (mode == state.editSequence.asset.durationMode)
return;
UndoExtensions.RegisterTimeline(state.editSequence.asset, "Duration Mode");
// if we switched from Auto to Fixed, use the auto duration as the new fixed duration so the end marker stay in the same position.
if (state.editSequence.asset.durationMode == TimelineAsset.DurationMode.BasedOnClips && mode == TimelineAsset.DurationMode.FixedLength)
{
state.editSequence.asset.UpdateFixedDurationWithItemsDuration();
}
state.editSequence.asset.durationMode = mode;
state.UpdateRootPlayableDuration(state.editSequence.duration);
}
}
class Scrub : Manipulator
{
readonly Func<Event, WindowState, bool> m_OnMouseDown;
readonly Action<double> m_OnMouseDrag;
readonly System.Action m_OnMouseUp;
bool m_IsCaptured;
public Scrub(Func<Event, WindowState, bool> onMouseDown, Action<double> onMouseDrag, System.Action onMouseUp)
{
m_OnMouseDown = onMouseDown;
m_OnMouseDrag = onMouseDrag;
m_OnMouseUp = onMouseUp;
}
protected override bool MouseDown(Event evt, WindowState state)
{
if (evt.button != 0)
return false;
if (!m_OnMouseDown(evt, state))
return false;
state.AddCaptured(this);
m_IsCaptured = true;
return true;
}
protected override bool MouseUp(Event evt, WindowState state)
{
if (!m_IsCaptured)
return false;
m_IsCaptured = false;
state.RemoveCaptured(this);
m_OnMouseUp();
return true;
}
protected override bool MouseDrag(Event evt, WindowState state)
{
if (!m_IsCaptured)
return false;
m_OnMouseDrag(state.GetSnappedTimeAtMousePosition(evt.mousePosition));
return true;
}
}
class TimeAreaItem : Control
{
public Color headColor { get; set; }
public Color lineColor { get; set; }
public bool drawLine { get; set; }
public bool drawHead { get; set; }
public bool canMoveHead { get; set; }
public string tooltip { get; set; }
public Vector2 boundOffset { get; set; }
readonly GUIContent m_HeaderContent = new GUIContent();
readonly GUIStyle m_Style;
readonly Tooltip m_Tooltip;
Rect m_BoundingRect;
float widgetHeight { get { return m_Style.fixedHeight; } }
float widgetWidth { get { return m_Style.fixedWidth; } }
public Rect bounds
{
get
{
Rect r = m_BoundingRect;
r.y = TimelineWindow.instance.state.timeAreaRect.yMax - widgetHeight;
r.position += boundOffset;
return r;
}
}
public GUIStyle style
{
get { return m_Style; }
}
public bool showTooltip { get; set; }
// is this the first frame the drag callback is being invoked
public bool firstDrag { get; private set; }
public TimeAreaItem(GUIStyle style, Action<double> onDrag)
{
m_Style = style;
headColor = Color.white;
var scrub = new Scrub(
(evt, state) =>
{
firstDrag = true;
return state.timeAreaRect.Contains(evt.mousePosition) && bounds.Contains(evt.mousePosition);
},
(d) =>
{
if (onDrag != null)
onDrag(d);
firstDrag = false;
},
() =>
{
showTooltip = false;
firstDrag = false;
}
);
AddManipulator(scrub);
lineColor = m_Style.normal.textColor;
drawLine = true;
drawHead = true;
canMoveHead = false;
tooltip = string.Empty;
boundOffset = Vector2.zero;
m_Tooltip = new Tooltip(DirectorStyles.Instance.displayBackground, DirectorStyles.Instance.tinyFont);
}
public void Draw(Rect rect, WindowState state, double time)
{
var clipRect = new Rect(0.0f, 0.0f, TimelineWindow.instance.position.width, TimelineWindow.instance.position.height);
clipRect.xMin += state.sequencerHeaderWidth;
using (new GUIViewportScope(clipRect))
{
Vector2 windowCoordinate = rect.min;
windowCoordinate.y += 4.0f;
windowCoordinate.x = state.TimeToPixel(time);
m_BoundingRect = new Rect((windowCoordinate.x - widgetWidth / 2.0f), windowCoordinate.y, widgetWidth, widgetHeight);
// Do not paint if the time cursor goes outside the timeline bounds...
if (Event.current.type == EventType.Repaint)
{
if (m_BoundingRect.xMax < state.timeAreaRect.xMin)
return;
if (m_BoundingRect.xMin > state.timeAreaRect.xMax)
return;
}
var top = new Vector3(windowCoordinate.x, rect.y - DirectorStyles.kDurationGuiThickness);
var bottom = new Vector3(windowCoordinate.x, rect.yMax);
if (drawLine)
{
Rect lineRect = Rect.MinMaxRect(top.x - 0.5f, top.y, bottom.x + 0.5f, bottom.y);
EditorGUI.DrawRect(lineRect, lineColor);
}
if (drawHead && Event.current.type == EventType.Repaint)
{
Color c = GUI.color;
GUI.color = headColor;
style.Draw(bounds, m_HeaderContent, false, false, false, false);
GUI.color = c;
if (canMoveHead)
EditorGUIUtility.AddCursorRect(bounds, MouseCursor.MoveArrow);
}
if (showTooltip)
{
m_Tooltip.text = TimeReferenceUtility.ToTimeString(time);
Vector2 position = bounds.position;
position.y = state.timeAreaRect.y;
position.y -= m_Tooltip.bounds.height;
position.x -= Mathf.Abs(m_Tooltip.bounds.width - bounds.width) / 2.0f;
Rect tooltipBounds = bounds;
tooltipBounds.position = position;
m_Tooltip.bounds = tooltipBounds;
m_Tooltip.Draw();
}
}
}
}
}
| 0 | 0.957524 | 1 | 0.957524 | game-dev | MEDIA | 0.841736 | game-dev | 0.986724 | 1 | 0.986724 |
createthis/createthis_vr_ui | 1,191 | Assets/CreateThis/Scripts/VR/UI/Container/Editor/PanelContainerEditor.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace CreateThis.VR.UI.Container {
[CustomEditor(typeof(PanelContainer))]
[CanEditMultipleObjects]
public class PanelContainerEditor : Editor {
SerializedProperty minWidth;
SerializedProperty minHeight;
SerializedProperty bounds;
void OnEnable() {
minWidth = serializedObject.FindProperty("minWidth");
minHeight = serializedObject.FindProperty("minHeight");
bounds = serializedObject.FindProperty("bounds");
}
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUILayout.PropertyField(minWidth);
EditorGUILayout.PropertyField(minHeight);
EditorGUILayout.PropertyField(bounds);
serializedObject.ApplyModifiedProperties();
if (GUILayout.Button("Resize")) {
if (target.GetType() == typeof(PanelContainer)) {
PanelContainer panelContainer = (PanelContainer)target;
panelContainer.Resize();
}
}
}
}
} | 0 | 0.844252 | 1 | 0.844252 | game-dev | MEDIA | 0.889107 | game-dev | 0.730665 | 1 | 0.730665 |
originn0/dynamic_social_democracy | 17,208 | source/scenes/events/lvp_party_congress_curtius.scene.dry | title: <span style="color: #FFCC00;">**LVP**</span> Party Vote
subtitle: Julius Curtius has resigned!
view-if: curtius_explosion_timer == time and lvp_leader == "Curtius" and lvp_formed
on-arrival: {!
Q.curtius_resign_lvp = 1;
Q.heuss_points = 0;
Q.dietrich_points = 0;
Q.dingeldey_points = 1;
if (Q.in_grand_coalition || Q.in_weimar_coalition) {
Q.lvp_relation += 4;
Q.lvp_left += 1;
} else if (Q.in_popular_front || Q.in_left_front) {
Q.lvp_right += 4;
Q.lvp_relation -= 10;
}
if (Q.agriculture_minister_party == "LVP" || Q.economic_minister_party == "LVP" || (Q.chancellor == "Brüning" && !Q.spd_in_government)) {
Q.dietrich_points += 1;
}
if (Q.spd_votes >= 30) {
Q.dingeldey_points += 2;
}
if (Q.chancellor == "Brüning" && Q.spd_toleration) {
Q.dietrich_points += 1;
Q.dingeldey_points += 2;
Q.lvp_right += 3;
}
if (Q.lvp_relation >= 50) {
Q.lvp_left += 3;
Q.heuss_points += 2;
Q.dingeldey_points -= 2;
} else if (Q.lvp_relation < 40) {
Q.lvp_right += 3;
Q.dingeldey_points += 2;
Q.heuss_points -= 1;
}
if (Q.nationalism >= 50) {
Q.lvp_right += 2;
}
if (Q.pro_republic >= 60) {
Q.heuss_points += 2;
Q.lvp_left += 2;
} else if (Q.pro_republic < 50) {
Q.dingeldey_points += 1;
Q.lvp_right += 1;
}
if (Q.lvp_votes >= 8) {
if (Q.lvp_ideology == "Right") {
Q.lvp_left += 3;
} else if (Q.lvp_ideology == "Left") {
Q.lvp_right += 3;
}
} else if (Q.lvp_votes < 8 && Q.nsdap_votes >= (Q.lvp_votes + 5)) {
Q.lvp_right += 5;
Q.dingeldey_points += 2;
}
if (Q.lvp_right > (Q.lvp_left*1.5) || (Q.lvp_right > (Q.lvp_left + 5))) {
Q.lvp_ideology = "Right"
} else if (Q.lvp_left > (Q.lvp_right*1.5) || (Q.lvp_left > (Q.lvp_right + 5))) {
Q.lvp_ideology = "Left"
} else {
Q.lvp_ideology = "Moderate"
}
if (Q.lvp_ideology == "Right") {
Q.dingeldey_points += 2;
}
if (Q.lvp_ideology == "Moderate") {
Q.dietrich_points += 2;
}
if (Q.lvp_ideology == "Left") {
Q.heuss_points += 2;
}
if ((Q.heuss_points - 2) >= Q.dietrich_points && (Q.heuss_points - 2) >= Q.dingeldey_points) {
Q.heuss_lead = 1;
} else {
Q.heuss_lead = 0;
}
if ((Q.dietrich_points - 2) >= Q.heuss_points && (Q.dietrich_points - 2) >= Q.dingeldey_points) {
Q.dietrich_lead = 1;
} else {
Q.dietrich_lead = 0;
}
if ((Q.dingeldey_points - 2) >= Q.heuss_points && (Q.dingeldey_points - 2) >= Q.dietrich_points) {
Q.dingeldey_lead = 1;
} else {
Q.dingeldey_lead = 0;
}
if (!Q.dietrich_lead && !Q.heuss_lead && !Q.dingeldey_lead) {
Q.lvp_deadlock = 1;
} else {
Q.lvp_deadlock = 0;
}
!}
max-visits: 1
tags: event
face-image: img/weimar_coalition_3.jpg
new-page: true
= <span style="color: #FFCC00;">**LVP**</span> Party Vote
Following the disastrous Austrian customs union project, which he was the architect of, he has tendered his resignation from both the Foreign Ministry and the leadership of the <span style="color: #FFCC00;">**LVP**</span>. This debacle has significantly discredited him and his allies, leading to a rightward shift within the <span style="color: #FFCC00;">**LVP**</span>.
An internal election must now be held to determine Curtius’s successor. Many candidates who have previously lost to him in the last party congress have once again stepped up to replace him, significantly crowding the field. Newer candidates have also thrown their hats in the ring. The right wing of the <span style="color: #FFCC00;">**LVP**</span> will rally behind Dingeldey, the left <span style="color: #c00000;">Social</span> <span style="color: #000000;">Repu</span><span style="color: #DD0000;">bli</span><span style="color: #FFCC00;">cans</span> will support Heuss, and the pragmatic center prefers Dietrich. While the new candidates have a low chance of winning, they may emerge as a compromise if no candidate secures a majority.
- @heuss
- @dietrich
- @dingeldey
- @deadlock
@heuss
title: Theodor Heuss is elected!
subtitle: Heuss is a <span style="color: #c00000;">Social</span> <span style="color: #000000;">Rep</span><span style="color: #DD0000;">ubl</span><span style="color: #FFCC00;">ican</span>, and a member of the former <span style="color: #D3C24D;">**[+ ddp_name +]**</span>.
unavailable-subtitle: The wider <span style="color: #FFCC00;">LVP</span> perceive him as too left-wing, despite his previous affiliation with the <span style="color: #D3C24D;">[+ ddp_name +]</span>'s business wing.
choose-if: heuss_lead
on-arrival: lvp_relation += 12; lvp_left += 7; lvp_leader = "Heuss"; pro_republic += (lvp_votes / 2); workers_lvp += 2; workers_spd -= 2; new_middle_lvp += 6; old_middle_lvp -= 3; old_middle_other += 5 if (dnvp_ideology == "Radical"); old_middle_dnvp += 5 if dnvp_ideology == "Moderate"; old_middle_kvp += 5; rural_lvp -= 5; rural_other += 5 if (dnvp_ideology == "Radical" and not kvp_formed); rural_dnvp += 5 if dnvp_ideology == "Moderate"; rural_kvp += 5; catholics_lvp += 3; catholics_spd -= 3; coalition_dissent -= 1; heuss_explode_time = time + 8; heuss_election_time = time
face-image: img/portraits/heuss.jpg
Theodor Heuss, a rising star and former member of the <span style="color: #D3C24D;">**[+ ddp_name +]**</span>, has been elected chairman of the <span style="color: #FFCC00;">Liberal People's Party</span>. Backed primarily by the 'Social Republican Circle,' composed of former <span style="color: #D3C24D;">**[+ ddp_name +]**</span> members and liberal intellectuals and newspapers, Heuss has also garnered support from the broader party due to his decently conservative stances on economic and national issues.
Heuss's victory empowers the '<span style="color: #c00000;">Social</span> <span style="color: #000000;">Rep</span><span style="color: #DD0000;">ubl</span><span style="color: #FFCC00;">ican</span>' wing, strengthening our cooperation. Despite his personal leanings toward the right, Heuss remains one of the most committed and genuine supporters for <span style="color: #FFCC00;">liberal</span> <span style="color: #586593;">democracy</span> within the <span style="color: #FFCC00;">**LVP**</span>.
@dietrich
title: Hermann Dietrich is elected!
subtitle: Dietrich was the former leader of the <span style="color: #D3C24D;">**[+ ddp_name +]**</span>'s business wing, and is somewhat skeptical of cooperation with us.
unavailable-subtitle: [? if not heuss_lead: The wider <span style="color: #FFCC00;">LVP</span> perceive him as too left-wing, despite his previous affiliation with the <span style="color: #D3C24D;">[+ ddp_name +]</span>'s business wing. ?][? if heuss_lead: His lack of energy and the burden of his governmental roles have led the party to favor Heuss instead. ?]
choose-if: dietrich_lead
on-arrival: lvp_relation += 5; lvp_left += 2; lvp_leader = "Dietrich"; pro_republic += 5; old_middle_lvp += 4; rural_lvp += 4; new_middle_lvp -= 4; dietrich_lvp_explode_time = time + 8; dietrich_election_time = time
face-image: img/portraits/dietrich.jpg
Hermann Dietrich, formerly affiliated with the business wing of the <span style="color: #D3C24D;">**[+ ddp_name +]**</span>, has been elected chairman of the <span style="color: #FFCC00;">**LVP**</span>. Dietrich is mainly supported by smaller businesses and ruralites, and [? if chancellor == "Brüning" and not spd_in_government: is known for formulating Brüning's emergency decrees during his tenure as Finance Minister.?][? if not (chancellor == "Brüning" and not spd_in_government): is known for his fiscal conservatism.?]
Despite this, Dietrich is not as extreme as the industrialists on the right of the party and remains open to cooperation with us if there is no other majority. However, his leadership has been quite uninspiring, to say the least. [? if agriculture_minister_party == "LVP" or economic_minister_party == "LVP": The responsibilities of his ministry prevent him from being involved in the day-to-day running of his party, which is now delegated to a group of his associates in the business wing. ?]
@dingeldey
title: Eduard Dingeldey is elected.
subtitle: Dingeldey was a member of the former <span style="color: #C0A054;">**DVP**</span>, and commonly associated with the industrial-right of the party.
unavailable-subtitle: The right-industrial faction of the <span style="color: #FFCC00;">LVP</span> lack the power necessary to install their candidate.
choose-if: dingeldey_lead
on-arrival: lvp_relation -= 8; lvp_right += 5; lvp_leader = "Dingeldey"; new_middle_lvp -= 4; workers_lvp -= 2; old_middle_lvp += 3; coalition_dissent += 1; dingeldey_explode_time = time + 8; dingeldey_election_time = time
face-image: img/portraits/dingeldey.jpg
Eduard Dingeldey, previously part of the movement for bourgeois unity, has now been elected chairman of the <span style="color: #FFCC00;">**LVP**</span>. Dingeldey is backed by the industrial forces on the right of the party, alongside former <span style="color: #C0A054;">**DVP**</span> members. He appears to be focused on fostering closer cooperation with the array of parties between the <span style="color: #FFCC00;">**LVP**</span> and the <span style="color: #3E88B3;">**DNVP**</span>.
However, Dingeldey has thus far proven to be an ineffectual leader, often capitulating to the right wing of the <span style="color: #FFCC00;">**LVP**</span>. Recently, we’ve observed a deterioration in relations with his party, alongside a noticeable rightward shift in the <span style="color: #FFCC00;">**LVP**</span>'s internal politics.
@deadlock
title: The vote has been deadlocked!
subtitle: No candidate is able to gather a sufficient amount of votes.
view-if: lvp_deadlock
on-arrival: {!
if (((Q.workers_spd_normalized < 40 || Q.unions_independent) || Q.new_middle_lvp_normalized >= 50 || Q.nationalism >= 55) && Q.dnvp_leader != "Lambach") Q.glatzel_lvp_unlock = 1;
if ((Q.nationalism >= 60) && Q.womens_rights >= 4) Q.baumer_lvp_unlock = 1;
if (((Q.lvp_ideology == "Left" || Q.lvp_relation >= 50) || (Q.new_middle_lvp_normalized + Q.old_middle_lvp_normalized >= 65)) && Q.confronting_antisemitism >= 1 && Q.stolper_program_adopted) Q.stolper_lvp_unlock = 1;
if (Q.baumer_lvp_unlock) {
Q.glatzel_lvp_unlock = 0;
Q.stolper_lvp_unlock = 0;
} else if (Q.glatzel_lvp_unlock) {
Q.baumer_lvp_unlock = 0;
Q.stolper_lvp_unlock = 0;
} else if (Q.stolper_lvp_unlock) {
Q.glatzel_lvp_unlock = 0;
Q.baumer_lvp_unlock = 0;
}
if (!Q.stolper_lvp_unlock && !Q.baumer_lvp_unlock && !Q.glatzel_lvp_unlock) Q.kardorff_lvp_unlock = 1;
!}
The vote has been deadlocked, with no candidate ahead by enough to constitute a majority. New compromise candidates have stepped forth.
- @stolper
- @glatzel
- @kardorff
- @baumer
@glatzel
title: Frank Glatzel is elected!
subtitle: Glatzel, a former member of the <span style="color: #3E88B3;">**DNVP**</span> and <span style="color: #C0A054;">**DVP**</span>, advocates the idea of broadening the party's appeal to workers.
unavailable-subtitle: His trade union membership has made him a non-option in the eyes of the <span style="color: #FFCC00;">LVP</span>, and his supporters lack meaningful influence.
choose-if: glatzel_lvp_unlock
on-arrival: lvp_leader = "Glatzel"; bourgeois_cooperation -= 3; workers_lvp += 12; workers_dnvp -= 4; workers_dnf -= 4; workers_other -= 4; workers_nsdap -= 4; workers_spd -= 4; workers_z -= 2; new_middle_lvp += 8; new_middle_nsdap -= 4; new_middle_other -= 2; new_middle_spd -= 2; catholics_lvp += 6; catholics_other -= 2; catholics_dnvp -= 2; catholics_z -= 2; old_middle_lvp += 4; old_middle_dnvp -= 4; rural_lvp -= 6; rural_dnvp += 4; rural_other += 2; rural_dnvp += 2 if dnvp_ideology == "Moderate"; rural_kvp += 2 if kvp_formed
face-image: img/portraits/glatzel.jpg
achievement: neuer_nationalismus
Frank Glatzel, a trade unionist affiliated with the conservative white-collar union, the DHV, has been elected the new leader of the <span style="color: #FFCC00;">**LVP**</span>. He advocates for a "New Nationalism," emphasizing solidarity among all classes to defend the country's "<span class="tooltip-text" title="Lebensraum">living space</span>" and to foster freedom for the people. In his push for *Volksgemeinschaft*, aimed at reducing class conflict, he has incorporated more nationalistic and corporatist elements into the party platform. This vision gained him the support of nationalists and Stresemannites within the <span style="color: #FFCC00;">**LVP**</span>, with the paramilitary group "Young German Order" even backing his leadership bid.
As expected, this shift has caused concern among the remaining industrialists in the <span style="color: #FFCC00;">**LVP**</span>, as the party moves away from its traditional sole focus on middle-class interests. This has resulted in a significant change in the party’s financial backing, with funding from big business dwindling and being replaced by donations and newly established dues. His <span class="tooltip-text" title="good mod">dynamic</span> leadership should be closely watched.
@kardorff
title: Siegfried von Kardorff is elected!
subtitle: Kardorff is able to secure the continuation of Curtius's leadership.
unavailable-subtitle: His closeness to Curtius has undermined his position.
choose-if: kardorff_lvp_unlock
on-arrival: lvp_leader = "Kardorff"; dvp_left += 3 if in_grand_coalition; bourgeois_cooperation += 1; dvp_relation += 5 if in_grand_coalition; new_middle_lvp += 4; catholics_lvp += 2; rural_lvp += 2; old_middle_lvp += 2; pro_republic += 3
face-image: img/portraits/kardorff.jpg
Kardorff is elected to succeed Curtius as the leader of the <span style="color: #FFCC00;">**LVP**</span>. He is expected to be a continuation of Curtius's leadership, being another Stresemann follower and supporter of constructive cooperation with the <span style="color: #c00000;">**SPD**</span>. [? if ui0_seen: He even rallied his parliamentary faction to save our Grand Coalition back in 1929.?]
[? if bruning_time: He is also one of the strongest supporters of the Brüning government, frequently coming into conflict with the right of the party over support for it. ?]
@stolper
title: Gustav Stolper is elected!
subtitle: Creator of the famed Stolper Program, and a <span style="color: #005EB8;">Jew</span>.
unavailable-subtitle: The <span style="color: #FFCC00;">LVP</span> prefers not to exacerbate their reputation as the party for <span style="color: #005EB8;">Jews</span>.
choose-if: stolper_lvp_unlock
on-arrival: lvp_leader = "Stolper"; lvp_relation += 6; lvp_left += 3; rural_lvp *= 0.6; rural_nsdap += 4; new_middle_lvp *= 1.5; old_middle_lvp *= 1.2; pro_republic += 5
face-image: img/portraits/stolper.jpg
Gustav Stolper, a German-Austrian economist and the son of <span style="color: #005EB8;">Jewish</span> immigrants from Poland, has been elected chairman of the <span style="color: #FFCC00;">**LVP**</span>, reinforcing a stereotype the party has long struggled to dispel. Despite this, Stolper—renowned for the economic program bearing his name—could be exactly what the <span style="color: #FFCC00;">**LVP**</span> needs to revitalize its middle-class support.
Relations have improved compared to Curtius's tenure, as Stolper's strained ties with parties to the right of the <span style="color: #FFCC00;">**LVP**</span>—due to anti-Semitism—have made cooperation with us easier.
@baumer
title: Gertrud Bäumer is elected!
subtitle: Leader of the <span style="color: #FFCC00;">**LVP**</span>'s women's wing, and a moderate feminist. Has questionable views on the "national questions".
unavailable-subtitle: The <span style="color: #FFCC00;">LVP</span> will never accept a woman as their leader.
choose-if: baumer_lvp_unlock
on-arrival: lvp_leader = "Bäumer"; lvp_relation += 5; nationalism += lvp_votes; workers_lvp += 6; workers_other -= 2; workers_spd -= 4; new_middle_lvp += 20; new_middle_spd -= 15; new_middle_kpd -= 5; old_middle_lvp -= 20; old_middle_dnvp += 5; old_middle_dnvp += 10 if dnvp_ideology == "Moderate"; old_middle_nsdap += 5; old_middle_kvp += 10; old_middle_other += 5; rural_lvp *= 0.5; rural_nsdap += 5; rural_dnvp += 5 if not kvp_formed; rural_kvp += 5; pro_republic -= 5
face-image: img/portraits/baumer.jpg
Somehow, Gertrud Bäumer, long-time deputy leader of the <span style="color: #D3C24D;">**[+ ddp_name +]**</span> and now the leader of the <span style="color: #FFCC00;">**LVP**</span>'s women's wing, has been elected to the leadership of the <span style="color: #FFCC00;">**LVP**</span>. This is quite a bizarre development, but her victory can be attributed to her passionate nationalism and romanticism, as well as her questionable views on <span style="color: #005EB8;">Jews</span> and race, which have garnered the support of nationalists within the party. Additionally, some within the party cynically believe that by electing a woman, they can appeal to a broader female electorate.
For us, Bäumer's background as a former <span style="color: #D3C24D;">**[+ ddp_name +]**</span> member may work in our favor, improving our relationship with the <span style="color: #FFCC00;">**LVP**</span>. However, it remains to be seen whether she will gain more votes than she loses due to her moderate feminist stance, as many refuse to support her purely out of misogyny. | 0 | 0.521127 | 1 | 0.521127 | game-dev | MEDIA | 0.638631 | game-dev,ml-ai | 0.790044 | 1 | 0.790044 |
planet-x3/px3_ose | 4,786 | src/video/hercules.s | ; Engine of Planet X3, a real-time strategy game originally for MS-DOS.
; Copyright (C) 2018-2023 8-Bit Productions LLC 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 2 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <https://www.gnu.org/licenses/>.
;
; -----
;
; AUTHORS of this file (in chronological order)
;
; - Benedikt Freisen
;
; *) Of or for 8-Bit Productions LLC
; **) Partly for 8-Bit Productions LLC
; Hercules Graphics Card routines
; data for CRTC registers 0-11, index port 3b4h, data port 3b5h
; CRTC table for 720x348, 4 fields
; hercules_crtc_tab db 35h,2dh,2eh,07h,5bh,02h,57h,57h,02h,03h,00h,00h
; CRTC table for 640x348, 4 fields
; hercules_crtc_tab db 35h,28h,2ch,07h,5bh,02h,57h,57h,02h,03h,00h,00h
; CRTC table for 640x300, 3 fields
hercules_crtc_tab db 35h,28h,2ch,07h,79h,03h,64h,6ch,02h,02h,00h,00h
; switch to 640x300x2 Hercules mode
set_hercules_640x300x2:
push ax
push dx
; switch to mode 7
mov ax,7
int 10h
; disable video (graphics mode with page 0)
mov dx,3b8h
mov al,02h
out dx,al
; set CRTC registers
push si
mov si,hercules_crtc_tab
xor ax,ax
cli ; disable interrupts
cld
sh_crtc_loop:
mov dl,0b4h ; dx=3b4h
out dx,al
inc ax
push ax
lodsb
inc dx
out dx,al
pop ax
cmp al,12
jb sh_crtc_loop
sti ; enable interrupts
pop si
; allow graphics mode, upper page disabled
mov dl,0bfh ; dx=3bfh
mov al,1 ; 3 if upper page enabled
out dx,al
; clear screen
push es ; save es
mov ax,0b000h
mov es,ax ; es=0a000h
push di ; save di
xor di,di ; di=0
xor ax,ax ; ax=0
push cx ; save cx
mov cx,16384
rep stosw ; clear the entire 32KiB page
pop cx ; restore cx
pop di ; restore di
pop es ; restore es
; enable video (graphics mode with page 0)
mov dl,0b8h ; dx = 3b8h
mov al,0ah
out dx,al
pop dx ; restore dx
pop ax ; restore ax
ret
restore_old_mode_hercules:
; switch to old video mode saved at program start
mov ah,0
mov al,[cs:old_mode]
int 10h
; re-enable port 3b8 protection
mov dx,3bfh
mov al,0
out dx,al
ret
emulate_movsb_to_cga_on_hgc:
push ax,dx
lodsb ; load group of pixels
mov dl,al
mov dh,al
and dx,0101010110101010b
shl dh,1
or al,dh
and dh,dl
cmp di,1fffh ; cf = (di <= 8191)
jnc emtcoh01
stosb
mov al,[es:di+1fffh]
and al,01010101b
or al,dh
mov [es:di+1fffh],al
jmp emtcoh02
emtcoh01:
mov [es:di+2000h],al
mov al,[es:di]
and al,10101010b
shr dh,1
or al,dh
stosb
emtcoh02:
pop dx,ax
ret
; ds:si input: 1st & 2nd field
; es:di output: 1st, 2nd, 3rd & empty 4th field
convert_cga_to_3_field_hgc:
mov si,3fffh
mov di,7fffh-32
mov bh,0
.tileloop:
mov cx,32
.byteloop:
mov al,[si]
mov dl,al
mov dh,al
and dx,0101010110101010b
shl dh,1
or al,dh
and dh,dl
mov [es:di],al
shr dh,1
mov ah,dh
mov al,[si-32]
mov dl,al
mov dh,al
and dx,0101010110101010b
shl dh,1
or al,dh
and dh,dl
mov [es:di-64],al
or ah,dh
mov [es:di-32],ah
dec si
dec di
loop .byteloop
sub si,32
sub di,96
dec bh
jnz .tileloop
ret
| 0 | 0.916133 | 1 | 0.916133 | game-dev | MEDIA | 0.53584 | game-dev | 0.992936 | 1 | 0.992936 |
AAEmu/AAEmu | 1,755 | AAEmu.Game/Models/Game/Char/ICharacter.cs | using System.Drawing;
using AAEmu.Game.Models.Game.Chat;
using AAEmu.Game.Models.Game.Items;
using AAEmu.Game.Models.Game.Items.Actions;
using AAEmu.Game.Models.Game.Units;
using AAEmu.Game.Models.StaticValues;
namespace AAEmu.Game.Models.Game.Char;
public interface ICharacter : IUnit
{
CharacterQuests Quests { get; set; }
Inventory Inventory { get; set; }
long Money { get; set; }
long Money2 { get; set; }
int HonorPoint { get; set; }
int VocationPoint { get; set; }
short CrimePoint { get; set; }
CharacterMates Mates { get; set; }
CharacterAppellations Appellations { get; set; }
CharacterAbilities Abilities { get; set; }
byte NumInventorySlots { get; set; }
short NumBankSlots { get; set; }
public UnitEvents Events { get; }
void SendMessage(ChatType type, string message, Color? color = null);
void SendMessage(string message);
void SendDebugMessage(string message);
void SendErrorMessage(ErrorMessageType errorMsgType, uint type = 0, bool isNotify = true);
void ChangeLabor(short change, int actabilityId);
void AddExp(int expDelta, bool shouldAddAbilityExp);
public bool ChangeMoney(SlotType typeFrom, SlotType typeTo, int amount, ItemTaskType itemTaskType = ItemTaskType.DepositMoney);
public void ChangeGamePoints(GamePointKind kind, int change);
public void SetGrowthRate(float value);
public void SetLootRate(float value);
public void SetVocationRate(float value);
public void SetHonorRate(float value);
public void SetExpRate(float value);
public void SetAutoSaveInterval(float value);
public void SetLogoutMessage(string value);
public void SetMotdMessage(string value);
public void SetGeoDataMode(bool value);
}
| 0 | 0.814326 | 1 | 0.814326 | game-dev | MEDIA | 0.901605 | game-dev | 0.53553 | 1 | 0.53553 |
ill-inc/biomes-game | 3,591 | src/server/map/tiles/fog.ts | import { resolveRange } from "@/cayley/numerics/ranges";
import type { MapResourceDeps } from "@/server/map/resources";
import type { Colors } from "@/server/map/tiles/colors";
import type { Materials } from "@/server/map/tiles/materials";
import type { Surface } from "@/server/map/tiles/surface";
import { TEXTURE_SHAPE } from "@/server/map/tiles/textures";
import {
ImageBox,
downsample,
lerp,
patch3,
tileChildren,
} from "@/server/map/tiles/utils";
import { getTerrainID } from "@/shared/asset_defs/terrain";
import { SHARD_DIM } from "@/shared/game/shard";
import { clamp } from "@/shared/math/math";
import type { Vec2 } from "@/shared/math/types";
import { createGauge } from "@/shared/metrics/metrics";
import { Timer } from "@/shared/metrics/timer";
import { awaitSequential } from "@/shared/util/async";
import assert from "assert";
const mapGenFogTime = createGauge({
name: "map_gen_fog_time_ms",
help: "The time to generate an image tile in millis.",
labelNames: ["level"],
});
const mapRenderFogTime = createGauge({
name: "map_render_fog_time_ms",
help: "The time to render a base image tile in millis.",
});
export async function genFog(
deps: MapResourceDeps,
level: number,
u: number,
v: number
) {
assert.ok(level >= 0);
// Return this tile from the preload cache if it exists.
const preload = await deps.get("/tiles/preload", "fog", level, u, v);
if (preload) {
return preload;
}
// If the tile wasn't preloaded, then generate it recursively.
const timer = new Timer();
try {
if (level === 0) {
const shard: Vec2 = [SHARD_DIM * u, SHARD_DIM * v];
return renderFog(
await deps.get("/tiles/materials", ...shard),
await deps.get("/tiles/colors", ...shard),
await deps.get("/tiles/surface", 0, u, v)
);
} else {
// Recursively generate the children tiles.
// NOTE: We await sequentially here to avoid blowing up the event loop.
const [c00, c01, c10, c11] = await awaitSequential(
() => deps.get("/tiles/fog", level - 1, ...tileChildren([u, v])[0]),
() => deps.get("/tiles/fog", level - 1, ...tileChildren([u, v])[1]),
() => deps.get("/tiles/fog", level - 1, ...tileChildren([u, v])[2]),
() => deps.get("/tiles/fog", level - 1, ...tileChildren([u, v])[3])
);
// Create a 2x2 image from the children tiles and then downsample them.
return ImageBox.fromArray(
downsample(patch3(c00.array(), c01.array(), c10.array(), c11.array()))
);
}
} finally {
mapGenFogTime.set({ level }, timer.elapsed);
}
}
const MAX_MUCK = 15;
function renderFog(materials: Materials, colors: Colors, surface: Surface) {
const timer = new Timer();
try {
const ret = surface.array();
const muck = colors.muck.array();
for (let z = 0; z < SHARD_DIM; z += 1) {
for (let x = 0; x < SHARD_DIM; x += 1) {
const [h, w] = TEXTURE_SHAPE;
const [i, j] = [h * z, w * x];
const range = resolveRange(ret.shape, `${i}:${i + h},${j}:${j + w},:`);
// Check if the surface is road.
const isRoad = materials.block.get([z, x]) == getTerrainID("gravel");
// Blend muck on top based on the depth.
const muckAmount = materials.muck.get([z, x]);
if (muckAmount > 0) {
const t = clamp(muckAmount / MAX_MUCK, 0, isRoad ? 14 / 15 : 1);
ret.assign(range, lerp(ret.slice(range), muck.slice(range), t));
}
}
}
return ImageBox.fromArray(ret);
} finally {
mapRenderFogTime.set(timer.elapsed);
}
}
| 0 | 0.891093 | 1 | 0.891093 | game-dev | MEDIA | 0.643089 | game-dev | 0.960661 | 1 | 0.960661 |
EphemeralSpace/ephemeral-space | 1,797 | Content.Server/Arcade/SpaceVillainGame/SpaceVillainGame.Fighter.cs | namespace Content.Server.Arcade.SpaceVillain;
public sealed partial class SpaceVillainGame
{
/// <summary>
/// A state holder for the fighters in the SpaceVillain game.
/// </summary>
public sealed class Fighter
{
/// <summary>
/// The current hit point total of the fighter.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public int Hp
{
get => _hp;
set => _hp = MathHelper.Clamp(value, 0, HpMax);
}
private int _hp;
/// <summary>
/// The maximum hit point total of the fighter.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public int HpMax
{
get => _hpMax;
set
{
_hpMax = Math.Max(value, 0);
Hp = MathHelper.Clamp(Hp, 0, HpMax);
}
}
private int _hpMax;
/// <summary>
/// The current mana total of the fighter.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public int Mp
{
get => _mp;
set => _mp = MathHelper.Clamp(value, 0, MpMax);
}
private int _mp;
/// <summary>
/// The maximum mana total of the fighter.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public int MpMax
{
get => _mpMax;
set
{
_mpMax = Math.Max(value, 0);
Mp = MathHelper.Clamp(Mp, 0, MpMax);
}
}
private int _mpMax;
/// <summary>
/// Whether the given fighter can take damage/lose mana.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public bool Invincible = false;
}
}
| 0 | 0.73472 | 1 | 0.73472 | game-dev | MEDIA | 0.926975 | game-dev | 0.898666 | 1 | 0.898666 |
Eukaryot/sonic3air | 9,817 | Oxygen/sonic3air/source/sonic3air/menu/TimeAttackMenu.cpp | /*
* Part of the Oxygen Engine / Sonic 3 A.I.R. software distribution.
* Copyright (C) 2017-2025 by Eukaryot
*
* Published under the GNU GPLv3 open source software license, see license.txt
* or https://www.gnu.org/licenses/gpl-3.0.en.html
*/
#include "sonic3air/pch.h"
#include "sonic3air/menu/TimeAttackMenu.h"
#include "sonic3air/menu/GameApp.h"
#include "sonic3air/menu/MenuBackground.h"
#include "sonic3air/menu/SharedResources.h"
#include "sonic3air/Game.h"
#include "sonic3air/audio/AudioOut.h"
#include "sonic3air/data/SharedDatabase.h"
#include "sonic3air/data/TimeAttackData.h"
#include "oxygen/application/Application.h"
#include "oxygen/application/EngineMain.h"
#include "oxygen/application/gameview/GameView.h"
#include "oxygen/application/input/InputManager.h"
#include "oxygen/simulation/Simulation.h"
namespace
{
enum class CharacterOption
{
// Do not make changes here
SONIC_CLASSIC = 0x10,
SONIC_MAXCONTROL = 0x11,
TAILS = 0x20,
KNUCKLES = 0x30
};
}
TimeAttackMenu::TimeAttackMenu(MenuBackground& menuBackground) :
mMenuBackground(&menuBackground)
{
// Build up menu structure
{
mMenuEntries.reserve(4);
mZoneEntry = &mMenuEntries.addEntry();
mActEntry = &mMenuEntries.addEntry();
const auto& zones = SharedDatabase::getAllZones();
for (size_t zoneIndex = 0; zoneIndex < zones.size(); ++zoneIndex)
{
const SharedDatabase::Zone& zone = zones[zoneIndex];
const int acts = zone.mActsTimeAttack;
if (acts > 0)
{
uint16 zoneId = zone.mInternalIndex << 8;
mZoneEntry->addOption(zone.mDisplayName, zoneId);
if (acts == 2)
{
mActEntry->addOption("Act 1", zoneId);
mActEntry->addOption("Act 2", zoneId + 1);
}
else
{
mActEntry->addOption("Single Act", zoneId);
}
}
}
mCharacterEntry = &mMenuEntries.addEntry();
mCharacterEntry->addOption("Sonic", (uint32)CharacterOption::SONIC_CLASSIC);
mCharacterEntry->addOption("Sonic - Max Control", (uint32)CharacterOption::SONIC_MAXCONTROL);
mCharacterEntry->addOption("Tails", (uint32)CharacterOption::TAILS);
mCharacterEntry->addOption("Knuckles", (uint32)CharacterOption::KNUCKLES);
mMenuEntries.addEntry("Back", 0x10);
}
// Set defaults
mMenuEntries.mSelectedEntryIndex = 0;
mZoneEntry->mSelectedIndex = 0;
mCharacterEntry->mSelectedIndex = 0;
}
TimeAttackMenu::~TimeAttackMenu()
{
}
GameMenuBase::BaseState TimeAttackMenu::getBaseState() const
{
switch (mState)
{
case State::APPEAR: return BaseState::FADE_IN;
case State::SHOW: return BaseState::SHOW;
case State::FADE_TO_MENU: return BaseState::FADE_OUT;
case State::FADE_TO_GAME: return BaseState::FADE_OUT;
default: return BaseState::INACTIVE;
}
}
void TimeAttackMenu::setBaseState(BaseState baseState)
{
switch (baseState)
{
case BaseState::INACTIVE: mState = State::INACTIVE; break;
case BaseState::FADE_IN: mState = State::APPEAR; break;
case BaseState::SHOW: mState = State::SHOW; break;
case BaseState::FADE_OUT: mState = State::FADE_TO_MENU; break;
}
}
void TimeAttackMenu::onFadeIn()
{
mState = State::APPEAR;
mMenuBackground->showPreview(true);
mMenuBackground->startTransition(MenuBackground::Target::LIGHT);
// Reset this
mBestTimesForCharacters = 0xff;
mBestTimesForZoneAct = 0xffff;
AudioOut::instance().stopSoundContext(AudioOut::CONTEXT_INGAME + AudioOut::CONTEXT_MUSIC);
// Play "Data Select" music inside this menu
AudioOut::instance().setMenuMusic(0x2f);
}
bool TimeAttackMenu::canBeRemoved()
{
return (mState == State::INACTIVE && mVisibility <= 0.0f);
}
void TimeAttackMenu::initialize()
{
// Update Max Control unlocking
GameMenuEntry::Option* option = mCharacterEntry->getOptionByValue((uint32)CharacterOption::SONIC_MAXCONTROL);
RMX_CHECK(nullptr != option, "Option for Max Control not found", );
if (nullptr != option)
{
option->mVisible = PlayerProgress::instance().mUnlocks.isSecretUnlocked(SharedDatabase::Secret::SECRET_SUPER_PEELOUT);
}
}
void TimeAttackMenu::deinitialize()
{
}
void TimeAttackMenu::keyboard(const rmx::KeyboardEvent& ev)
{
}
void TimeAttackMenu::update(float timeElapsed)
{
GameMenuBase::update(timeElapsed);
// Don't react to input during transitions
if (mState == State::SHOW)
{
// Update menu entries
const GameMenuEntries::UpdateResult result = mMenuEntries.update();
if (result != GameMenuEntries::UpdateResult::NONE)
{
playMenuSound(0x5b);
if (result == GameMenuEntries::UpdateResult::OPTION_CHANGED)
{
if (mMenuEntries.mSelectedEntryIndex == 1) // Act entry was changed
{
mPreferredAct = mActEntry->selected().mValue % 2;
mZoneEntry->setSelectedIndexByValue(mActEntry->selected().mValue & 0xff00);
}
else // Zone entry was changed
{
mActEntry->setSelectedIndexByValue(mZoneEntry->selected().mValue + mPreferredAct);
}
}
}
if (!FTX::keyState(SDLK_LALT) && !FTX::keyState(SDLK_RALT))
{
const InputManager::ControllerScheme& keys = InputManager::instance().getController(0);
const uint32 selectedData = mMenuEntries.selected().mData;
if (keys.Start.justPressed() || keys.A.justPressed() || keys.X.justPressed())
{
if (selectedData == 0x10)
{
backToMainMenu();
}
else
{
triggerStartGame();
}
}
else if (keys.B.justPressed())
{
backToMainMenu();
}
}
}
const uint16 zoneAndAct = (uint16)mActEntry->selected().mValue;
mMenuBackground->setPreviewZoneAndAct(zoneAndAct >> 8, zoneAndAct % 2);
if (mBestTimesForZoneAct != mActEntry->selected().mValue || mBestTimesForCharacters != mCharacterEntry->selected().mValue)
{
mBestTimesForZoneAct = mActEntry->selected().mValue;
mBestTimesForCharacters = mCharacterEntry->selected().mValue;
// Get entries from the time attack table
TimeAttackData::Table* timeAttackTable = TimeAttackData::getTable(mBestTimesForZoneAct, mBestTimesForCharacters);
if (nullptr == timeAttackTable)
{
std::wstring recBaseFilename;
const std::wstring recordingsDir = TimeAttackData::getSavePath(mBestTimesForZoneAct, mBestTimesForCharacters, &recBaseFilename);
if (!recordingsDir.empty())
{
timeAttackTable = &TimeAttackData::loadTable(mBestTimesForZoneAct, mBestTimesForCharacters, recordingsDir + L"/records.json");
}
}
mBestTimes.clear();
if (nullptr != timeAttackTable)
{
mBestTimes.reserve(timeAttackTable->mEntries.size());
for (auto& entry : timeAttackTable->mEntries)
{
mBestTimes.emplace_back(TimeAttackData::getTimeString(entry.mTime, 1));
}
}
}
if (mState == State::APPEAR)
{
if (updateFadeIn(timeElapsed * 6.0f))
{
mState = State::SHOW;
}
}
else if (mState > State::SHOW)
{
if (updateFadeOut(timeElapsed * 6.0f))
{
if (mState == State::FADE_TO_GAME)
{
startGame();
}
mState = State::INACTIVE;
}
}
}
void TimeAttackMenu::render()
{
GuiBase::render();
Drawer& drawer = EngineMain::instance().getDrawer();
int anchorX = 200;
float alpha = 1.0f;
if (mState != State::SHOW && mState != State::FADE_TO_GAME)
{
anchorX += roundToInt((1.0f - mVisibility) * 200.0f);
alpha = mVisibility;
}
// Title text
drawer.printText(global::mSonicFontC, Recti(anchorX, 4, 0, 18), "TIME ATTACK", 5, Color(1.0f, 1.0f, 1.0f, alpha));
// Menu entries
const int positionY[] = { 116, 138, 160, 198 };
for (size_t line = 0; line < mMenuEntries.size(); ++line)
{
const auto& entry = mMenuEntries[line];
const std::string& text = entry.mOptions.empty() ? entry.mText : entry.mOptions[entry.mSelectedIndex].mText;
const bool canGoLeft = entry.mOptions.empty() ? false : (entry.mSelectedIndex > 0);
const bool canGoRight = entry.mOptions.empty() ? false : (entry.mSelectedIndex < entry.mOptions.size() - 1);
const int py = positionY[line];
const bool isSelected = ((int)line == mMenuEntries.mSelectedEntryIndex);
const Color color = (isSelected) ? Color(1.0f, 1.0f, 0.0f, alpha) : Color(1.0f, 1.0f, 1.0f, alpha * 0.9f);
int arrowAnimOffset = 0;
if (isSelected)
{
arrowAnimOffset = (int)std::fmod(FTX::getTime() * 6.0f, 6.0f);
arrowAnimOffset = (arrowAnimOffset > 3) ? (6 - arrowAnimOffset) : arrowAnimOffset;
}
int px = 200;
if (mState != State::SHOW && mState != State::FADE_TO_GAME)
{
const int lineOffset = (mState < State::SHOW) ? (int)(mMenuEntries.size() - 1 - line) : (int)line;
px = 200 + roundToInt(saturate(1.0f - alpha - lineOffset * 0.15f) * 200.0f);
}
if (canGoLeft)
drawer.printText(global::mOxyfontRegular, Recti(px - 145 - arrowAnimOffset, py, 10, 10), "<", 5, color);
if (canGoRight)
drawer.printText(global::mOxyfontRegular, Recti(px + 15 + arrowAnimOffset, py, 10, 10), ">", 5, color);
drawer.printText(global::mOxyfontRegular, Recti(px - 160, py, 200, 10), text, 5, color);
}
for (int i = 0; i < 5; ++i)
{
Recti rect(anchorX + 90, 118 + i * 18, 80, 18);
if (i < (int)mBestTimes.size())
drawer.printText(global::mOxyfontRegular, rect, mBestTimes[i], 5, Color(1.0f, 1.0f, 1.0f, alpha));
else
drawer.printText(global::mOxyfontRegular, rect, "-' --\" --", 5, Color(0.9f, 0.9f, 0.9f, alpha));
}
drawer.performRendering();
}
void TimeAttackMenu::triggerStartGame()
{
playMenuSound(0xaf);
GameApp::instance().getGameView().startFadingOut();
mState = State::FADE_TO_GAME;
}
void TimeAttackMenu::startGame()
{
// Init simulation
const uint8 characters = clamp(mCharacterEntry->selected().mValue >> 4, 1, 3);
Game::instance().startIntoLevel(Game::Mode::TIME_ATTACK, mCharacterEntry->selected().mValue, mActEntry->selected().mValue, characters);
GameApp::instance().onStartGame();
mMenuBackground->setGameStartedMenu();
mMenuEntries.mSelectedEntryIndex = 0;
}
void TimeAttackMenu::backToMainMenu()
{
playMenuSound(0xad);
mMenuBackground->openMainMenu();
mState = State::FADE_TO_MENU;
}
| 0 | 0.918036 | 1 | 0.918036 | game-dev | MEDIA | 0.712644 | game-dev,desktop-app | 0.978952 | 1 | 0.978952 |
ChuanqiXu9/clangd-for-modules | 2,640 | clang-tools-extra/docs/clang-tidy/checks/bugprone/compare-pointer-to-member-virtual-function.rst | .. title:: clang-tidy - bugprone-compare-pointer-to-member-virtual-function
bugprone-compare-pointer-to-member-virtual-function
===================================================
Detects unspecified behavior about equality comparison between pointer to member
virtual function and anything other than null-pointer-constant.
.. code-block:: c++
struct A {
void f1();
void f2();
virtual void f3();
virtual void f4();
void g1(int);
};
void fn() {
bool r1 = (&A::f1 == &A::f2); // ok
bool r2 = (&A::f1 == &A::f3); // bugprone
bool r3 = (&A::f1 != &A::f3); // bugprone
bool r4 = (&A::f3 == nullptr); // ok
bool r5 = (&A::f3 == &A::f4); // bugprone
void (A::*v1)() = &A::f3;
bool r6 = (v1 == &A::f1); // bugprone
bool r6 = (v1 == nullptr); // ok
void (A::*v2)() = &A::f2;
bool r7 = (v2 == &A::f1); // false positive, but potential risk if assigning other value to v2.
void (A::*v3)(int) = &A::g1;
bool r8 = (v3 == &A::g1); // ok, no virtual function match void(A::*)(int) signature.
}
Provide warnings on equality comparisons involve pointers to member virtual
function or variables which is potential pointer to member virtual function and
any entity other than a null-pointer constant.
In certain compilers, virtual function addresses are not conventional pointers
but instead consist of offsets and indexes within a virtual function table
(vtable). Consequently, these pointers may vary between base and derived
classes, leading to unpredictable behavior when compared directly. This issue
becomes particularly challenging when dealing with pointers to pure virtual
functions, as they may not even have a valid address, further complicating
comparisons.
Instead, it is recommended to utilize the ``typeid`` operator or other appropriate
mechanisms for comparing objects to ensure robust and predictable behavior in
your codebase. By heeding this detection and adopting a more reliable comparison
method, you can mitigate potential issues related to unspecified behavior,
especially when dealing with pointers to member virtual functions or pure
virtual functions, thereby improving the overall stability and maintainability
of your code. In scenarios involving pointers to member virtual functions, it's
only advisable to employ ``nullptr`` for comparisons.
Limitations
-----------
Does not analyze values stored in a variable. For variable, only analyze all virtual
methods in the same ``class`` or ``struct`` and diagnose when assigning a pointer
to member virtual function to this variable is possible.
| 0 | 0.828854 | 1 | 0.828854 | game-dev | MEDIA | 0.476761 | game-dev | 0.676225 | 1 | 0.676225 |
bespoke-silicon-group/bsg_manycore | 1,498 | software/spmd/deprecated/go_viral/main.c | // MBT 5-15-2016
// supports "viral booting"
// where code spreads across the tiles, rather
// than having the SPMD loader individually load them.
//
// Usage: put go_viral() as the first thing
// in main.
//
#include "bsg_manycore.h"
// these are private variables
// we do not make them volatile
// so that they may be cached
int bsg_x = -1;
int bsg_y = -1;
int bsg_id = 0;
int bsg_current_size = 1;
#define bsg_memory_words 8192
int go_viral() {
bsg_x = bsg_id_to_x(bsg_id);
bsg_y = bsg_id_to_y(bsg_id);
while (1)
{
int target_id = bsg_current_size+bsg_id;
if (target_id >= bsg_num_tiles)
break;
int target_x = bsg_id_to_x(target_id);
int target_y = bsg_id_to_y(target_id);
bsg_remote_int_ptr ptr
= bsg_remote_ptr(target_x, target_y,0);
int *local_mem = (int *) (0);
// update current size so it gets propagated
bsg_current_size = (bsg_current_size << 1);
for (int i = 0; i < bsg_memory_words; i+=4)
{
int a = local_mem[i];
int b = local_mem[i+1];
int c = local_mem[i+2];
int d = local_mem[i+3];
ptr[i+0] = a;
ptr[i+1] = b;
ptr[i+2] = c;
ptr[i+3] = d;
}
// update remote node with its ID
bsg_remote_store(target_x,target_y,&bsg_id,target_id);
// then, wake up the remote tile!
bsg_remote_unfreeze(target_x,target_y);
}
}
int main()
{
go_viral();
bsg_print_time();
if (bsg_id == (bsg_num_tiles-1))
bsg_finish();
bsg_wait_while(1);
}
| 0 | 0.688664 | 1 | 0.688664 | game-dev | MEDIA | 0.922959 | game-dev | 0.744066 | 1 | 0.744066 |
Gaby-Station/Gaby-Station | 6,593 | Content.Server/NPC/Systems/NPCCombatSystem.Melee.cs | // SPDX-FileCopyrightText: 2022 metalgearsloth <metalgearsloth@gmail.com>
// SPDX-FileCopyrightText: 2023 DrSmugleaf <DrSmugleaf@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 Morb <14136326+Morb0@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 Vordenburg <114301317+Vordenburg@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 metalgearsloth <comedian_vs_clown@hotmail.com>
// SPDX-FileCopyrightText: 2024 0x6273 <0x40@keemail.me>
// SPDX-FileCopyrightText: 2024 Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aidenkrz <aiden@djkraz.com>
// SPDX-FileCopyrightText: 2025 Aineias1 <dmitri.s.kiselev@gmail.com>
// SPDX-FileCopyrightText: 2025 FaDeOkno <143940725+FaDeOkno@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 GoobBot <uristmchands@proton.me>
// SPDX-FileCopyrightText: 2025 McBosserson <148172569+McBosserson@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Milon <plmilonpl@gmail.com>
// SPDX-FileCopyrightText: 2025 Piras314 <p1r4s@proton.me>
// SPDX-FileCopyrightText: 2025 Rouden <149893554+Roudenn@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 TheBorzoiMustConsume <197824988+TheBorzoiMustConsume@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Unlumination <144041835+Unlumy@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 deltanedas <39013340+deltanedas@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 deltanedas <@deltanedas:kde.org>
// SPDX-FileCopyrightText: 2025 gluesniffler <159397573+gluesniffler@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 gluesniffler <linebarrelerenthusiast@gmail.com>
// SPDX-FileCopyrightText: 2025 username <113782077+whateverusername0@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 whateverusername0 <whateveremail>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using System.Numerics;
using Content.Server.NPC.Components;
using Content.Shared.CombatMode;
using Content.Shared.NPC;
using Robust.Shared.Map;
using Robust.Shared.Physics.Components;
using Robust.Shared.Random;
namespace Content.Server.NPC.Systems;
public sealed partial class NPCCombatSystem
{
private const float TargetMeleeLostRange = 14f;
private void InitializeMelee()
{
SubscribeLocalEvent<NPCMeleeCombatComponent, ComponentStartup>(OnMeleeStartup);
SubscribeLocalEvent<NPCMeleeCombatComponent, ComponentShutdown>(OnMeleeShutdown);
}
private void OnMeleeShutdown(EntityUid uid, NPCMeleeCombatComponent component, ComponentShutdown args)
{
if (TryComp<CombatModeComponent>(uid, out var combatMode))
{
_combat.SetInCombatMode(uid, false, combatMode);
}
_steering.Unregister(uid);
}
private void OnMeleeStartup(EntityUid uid, NPCMeleeCombatComponent component, ComponentStartup args)
{
if (TryComp<CombatModeComponent>(uid, out var combatMode))
{
_combat.SetInCombatMode(uid, true, combatMode);
}
}
private void UpdateMelee(float frameTime)
{
var combatQuery = GetEntityQuery<CombatModeComponent>();
var xformQuery = GetEntityQuery<TransformComponent>();
var physicsQuery = GetEntityQuery<PhysicsComponent>();
var curTime = _timing.CurTime;
var query = EntityQueryEnumerator<NPCMeleeCombatComponent, ActiveNPCComponent>();
while (query.MoveNext(out var uid, out var comp, out _))
{
if (!combatQuery.TryGetComponent(uid, out var combat) || !combat.IsInCombatMode)
{
RemComp<NPCMeleeCombatComponent>(uid);
continue;
}
Attack(uid, comp, curTime, frameTime, physicsQuery, xformQuery); // Lavaland Change - added frameTime
}
}
// Lavaland Change - added frameTime
private void Attack(EntityUid uid, NPCMeleeCombatComponent component, TimeSpan curTime, float frameTime, EntityQuery<PhysicsComponent> physicsQuery, EntityQuery<TransformComponent> xformQuery)
{
component.Status = CombatStatus.Normal;
if (!_melee.TryGetWeapon(uid, out var weaponUid, out var weapon))
{
component.Status = CombatStatus.NoWeapon;
return;
}
if (!xformQuery.TryGetComponent(uid, out var xform) ||
!xformQuery.TryGetComponent(component.Target, out var targetXform))
{
component.Status = CombatStatus.TargetUnreachable;
return;
}
if (!xform.Coordinates.TryDistance(EntityManager, targetXform.Coordinates, out var distance))
{
component.Status = CombatStatus.TargetUnreachable;
return;
}
if (distance > TargetMeleeLostRange)
{
component.Status = CombatStatus.TargetUnreachable;
return;
}
if (TryComp<NPCSteeringComponent>(uid, out var steering) &&
steering.Status == SteeringStatus.NoPath)
{
component.Status = CombatStatus.TargetUnreachable;
return;
}
// TODO: When I get parallel operators move this as NPC combat shouldn't be handling this.
_steering.Register(uid, new EntityCoordinates(component.Target, Vector2.Zero), steering);
if (distance > weapon.Range)
{
component.Status = CombatStatus.TargetOutOfRange;
return;
}
if (weapon.NextAttack > curTime || !Enabled)
return;
// Lavaland Change Start
if (component.ChargeupTimer < component.ChargeupDelay)
{
component.ChargeupTimer += frameTime;
return;
}
component.ChargeupTimer = 0f;
// Lavaland Change End
if (_random.Prob(component.MissChance) &&
physicsQuery.TryGetComponent(component.Target, out var targetPhysics) &&
targetPhysics.LinearVelocity.LengthSquared() != 0f)
{
_melee.AttemptLightAttackMiss(uid, weaponUid, weapon, targetXform.Coordinates.Offset(_random.NextVector2(0.5f)));
}
else
{
_melee.AttemptLightAttack(uid, weaponUid, weapon, component.Target);
}
}
} | 0 | 0.919773 | 1 | 0.919773 | game-dev | MEDIA | 0.961368 | game-dev | 0.940884 | 1 | 0.940884 |
PacktPublishing/Mastering-Cpp-Game-Development | 5,385 | Chapter07/Include/bullet/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_MULTI_SAP_BROADPHASE
#define BT_MULTI_SAP_BROADPHASE
#include "btBroadphaseInterface.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btOverlappingPairCache.h"
class btBroadphaseInterface;
class btSimpleBroadphase;
typedef btAlignedObjectArray<btBroadphaseInterface*> btSapBroadphaseArray;
///The btMultiSapBroadphase is a research project, not recommended to use in production. Use btAxisSweep3 or btDbvtBroadphase instead.
///The btMultiSapBroadphase is a broadphase that contains multiple SAP broadphases.
///The user can add SAP broadphases that cover the world. A btBroadphaseProxy can be in multiple child broadphases at the same time.
///A btQuantizedBvh acceleration structures finds overlapping SAPs for each btBroadphaseProxy.
///See http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=328
///and http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=1329
class btMultiSapBroadphase :public btBroadphaseInterface
{
btSapBroadphaseArray m_sapBroadphases;
btSimpleBroadphase* m_simpleBroadphase;
btOverlappingPairCache* m_overlappingPairs;
class btQuantizedBvh* m_optimizedAabbTree;
bool m_ownsPairCache;
btOverlapFilterCallback* m_filterCallback;
int m_invalidPair;
struct btBridgeProxy
{
btBroadphaseProxy* m_childProxy;
btBroadphaseInterface* m_childBroadphase;
};
public:
struct btMultiSapProxy : public btBroadphaseProxy
{
///array with all the entries that this proxy belongs to
btAlignedObjectArray<btBridgeProxy*> m_bridgeProxies;
btVector3 m_aabbMin;
btVector3 m_aabbMax;
int m_shapeType;
/* void* m_userPtr;
short int m_collisionFilterGroup;
short int m_collisionFilterMask;
*/
btMultiSapProxy(const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask)
:btBroadphaseProxy(aabbMin,aabbMax,userPtr,collisionFilterGroup,collisionFilterMask),
m_aabbMin(aabbMin),
m_aabbMax(aabbMax),
m_shapeType(shapeType)
{
m_multiSapParentProxy =this;
}
};
protected:
btAlignedObjectArray<btMultiSapProxy*> m_multiSapProxies;
public:
btMultiSapBroadphase(int maxProxies = 16384,btOverlappingPairCache* pairCache=0);
btSapBroadphaseArray& getBroadphaseArray()
{
return m_sapBroadphases;
}
const btSapBroadphaseArray& getBroadphaseArray() const
{
return m_sapBroadphases;
}
virtual ~btMultiSapBroadphase();
virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* multiSapProxy);
virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher);
virtual void getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const;
virtual void rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback,const btVector3& aabbMin=btVector3(0,0,0),const btVector3& aabbMax=btVector3(0,0,0));
void addToChildBroadphase(btMultiSapProxy* parentMultiSapProxy, btBroadphaseProxy* childProxy, btBroadphaseInterface* childBroadphase);
///calculateOverlappingPairs is optional: incremental algorithms (sweep and prune) might do it during the set aabb
virtual void calculateOverlappingPairs(btDispatcher* dispatcher);
bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
virtual btOverlappingPairCache* getOverlappingPairCache()
{
return m_overlappingPairs;
}
virtual const btOverlappingPairCache* getOverlappingPairCache() const
{
return m_overlappingPairs;
}
///getAabb returns the axis aligned bounding box in the 'global' coordinate frame
///will add some transform later
virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const
{
aabbMin.setValue(-BT_LARGE_FLOAT,-BT_LARGE_FLOAT,-BT_LARGE_FLOAT);
aabbMax.setValue(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
}
void buildTree(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax);
virtual void printStats();
void quicksort (btBroadphasePairArray& a, int lo, int hi);
///reset broadphase internal structures, to ensure determinism/reproducability
virtual void resetPool(btDispatcher* dispatcher);
};
#endif //BT_MULTI_SAP_BROADPHASE
| 0 | 0.945582 | 1 | 0.945582 | game-dev | MEDIA | 0.950388 | game-dev | 0.979515 | 1 | 0.979515 |
mokkkk/MhdpColiseumDatapacksComponents | 2,893 | mhdp_core_dummy_monsters/data/mhdp_monster_tutorial_01/function/core/tick/12_battle.mcfunction | #> mhdp_monster_tutorial_01:core/tick/11_item
#
# tick処理
#
# @within function mhdp_monsters:core/switch/macro/m.damage
# モンスターの状態をデフォルトにする
execute if score @s Mns.General.DummyTimer matches 150 run tag @n[tag=Mns.Root.Ranposu] remove Mns.State.IsNotMove
execute if score @s Mns.General.DummyTimer matches 150 run tag @n[tag=Mns.Root.Ranposu] remove Mns.State.IsDisablePartDamage
execute if score @s Mns.General.DummyTimer matches 150 run tag @n[tag=Mns.Root.Ranposu] remove Mns.State.IsDisableDamage
# メッセージ
execute if score @s Mns.General.DummyTimer matches 60 as @a[tag=Ply.State.PlayingQuest] at @s run playsound ui.button.click master @s ~ ~ ~ 2 1
execute if score @s Mns.General.DummyTimer matches 60 run tellraw @a[tag=Ply.State.PlayingQuest] [\
{"text":"","color": "#FFFFFF","bold": false},\
{"text":"\n【 チュートリアル:狩猟 ","color":"#00FFC3","bold": true},{"text":"1/1","color":"#00FFC3","bold": false},{"text":" 】\n\n","color":"#00FFC3","bold": true},\
{"text":" それでは、これまでの知識を活かして、\n"},\
{"text":" 実際にモンスターと戦ってみましょう。\n"}\
]
# 初期スコア表示
execute if score @s Mns.General.DummyTimer matches 2 run scoreboard players display name $mhdp_temp_tutorial_value Mns.Tutorial.Text {"text":"青鳥竜を討伐する:残り","color":"green"}
execute if score @s Mns.General.DummyTimer matches 2 run scoreboard players display numberformat $mhdp_temp_tutorial_value Mns.Tutorial.Text styled {"color":"green"}
execute if score @s Mns.General.DummyTimer matches 2 run scoreboard players reset $mhdp_temp_tutorial_value_2 Mns.Tutorial.Text
execute if score @s Mns.General.DummyTimer matches 2 run scoreboard players reset $mhdp_temp_tutorial_value_3 Mns.Tutorial.Text
# スコア設定
execute if score @s Mns.General.DummyTimer matches 2 run scoreboard players set $mhdp_temp_tutorial_value Mns.Tutorial.Text 1
# チュートリアル完了:攻撃
execute if score @s Mns.General.DummyTimer matches 3.. if score $mhdp_temp_tutorial_value Mns.Tutorial.Text matches 0.. if entity @n[tag=Mns.Root.Ranposu,tag=Mns.State.Death] run scoreboard players remove $mhdp_temp_tutorial_value Mns.Tutorial.Text 1
execute if score @s Mns.General.DummyTimer matches 3.. if score $mhdp_temp_tutorial_value Mns.Tutorial.Text matches 0 run scoreboard players display name $mhdp_temp_tutorial_value Mns.Tutorial.Text {"text":"青鳥竜を討伐する:","color":"green"}
execute if score @s Mns.General.DummyTimer matches 3.. if score $mhdp_temp_tutorial_value Mns.Tutorial.Text matches 0 run scoreboard players display numberformat $mhdp_temp_tutorial_value Mns.Tutorial.Text fixed {"text":"OK!","color":"green"}
tag @n[tag=Mns.Root.Ranposu] add Mns.State.Tutorial.IsDamage
# 遷移:討伐後
execute if score $mhdp_temp_tutorial_value Mns.Tutorial.Text matches ..0 \
if score @s Mns.General.DummyTimer matches 60.. run function mhdp_monster_tutorial_01:core/tick/change_phase
| 0 | 0.82717 | 1 | 0.82717 | game-dev | MEDIA | 0.733243 | game-dev | 0.898463 | 1 | 0.898463 |
cdcsgit/lognote | 5,196 | src/com/blogspot/cdcsutils/lognote/LogColumnTableModel.kt | package com.blogspot.cdcsutils.lognote
import java.util.regex.Pattern
data class LogColumnItem(val mName: String, val mNth: Int, val mWidth: Int )
class LogColumnTableModel(mainUI: MainUI, baseModel: LogTableModel?) : LogTableModel(mainUI, baseModel) {
private val mCurrFormat = FormatManager.getInstance().mCurrFormat
private val mLogNth = FormatManager.getInstance().mCurrFormat.mLogPosition
companion object {
}
val mColumnItems = arrayOfNulls<LogColumnItem>(mTokenCount + COLUMN_LOG_START)
init {
var idx = 0
mColumnItems[idx] = LogColumnItem("Line", -1, 0)
idx++
mColumnItems[idx] = LogColumnItem("Process", -1, 0)
idx++
val nameArr = mCurrFormat.mColumnNames.split("|")
if (nameArr.isNotEmpty()) {
nameArr.forEach {
val nameSplit = it.split(",")
if (nameSplit.size == 3) {
mColumnItems[idx] = LogColumnItem(nameSplit[0], nameSplit[1].toInt(), nameSplit[2].toInt())
idx++
}
}
}
}
override fun getColumnName(column: Int): String {
return mColumnItems[column]?.mName ?: ""
}
override fun getColumnCount(): Int {
return mColumnItems.size
}
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any {
try {
if (rowIndex >= 0 && mLogItems.size > rowIndex) {
val logItem = mLogItems[rowIndex]
if (columnIndex == COLUMN_NUM) {
return logItem.mNum + " "
} else if (columnIndex == COLUMN_PROCESS_NAME) {
if (TypeShowProcessName != SHOW_PROCESS_NONE) {
if (logItem.mProcessName == null) {
if (mSortedPidTokIdx >= 0 && logItem.mTokenFilterLogs.size > mSortedPidTokIdx) {
return if (logItem.mTokenFilterLogs[mSortedPidTokIdx] == "0") {
"0"
} else {
ProcessList.getInstance().getProcessName(logItem.mTokenFilterLogs[mSortedPidTokIdx])
?: ""
}
}
} else {
return logItem.mProcessName
}
}
else {
return ""
}
} else {
logItem.mTokenLogs?.let {
val tokenIdx = mColumnItems[columnIndex]?.mNth ?: 0
if (tokenIdx < (it.size)) {
return it[tokenIdx]
}
}
if (logItem.mTokenLogs == null && ((mColumnItems[columnIndex]?.mNth ?: -1) == mLogNth)) {
return logItem.mLogLine
}
}
}
} catch (e:ArrayIndexOutOfBoundsException) {
e.printStackTrace()
}
return if (columnIndex == COLUMN_NUM) {
-1
} else {
""
}
}
override fun makeLogItem(num: Int, logLine: String): LogItem {
val level: Int
val tokenFilterLogs: Array<String>
val tokenLogs: List<String>?
val log: String
val textSplited = FormatManager.splitLog(logLine, mTokenCount, mSeparator, mSeparatorList)
if (textSplited.size == mTokenCount) {
level = if (mFilterLevel == LEVEL_NONE) {
LEVEL_NONE
} else {
mLevelMap[textSplited[mLevelIdx]] ?: LEVEL_NONE
}
tokenFilterLogs = Array(mSortedTokenFilters.size) {
if (mSortedTokenFilters[it].mPosition >= 0) {
textSplited[mSortedTokenFilters[it].mPosition]
} else {
""
}
}
log = textSplited[mLogNth]
tokenLogs = textSplited
} else {
level = LEVEL_NONE
tokenFilterLogs = mEmptyTokenFilters
log = logLine
tokenLogs = null
}
val processName = if (TypeShowProcessName != SHOW_PROCESS_NONE && mSortedPidTokIdx >= 0 && tokenFilterLogs.size > mSortedPidTokIdx) {
ProcessList.getInstance().getProcessName(tokenFilterLogs[mSortedPidTokIdx])
} else {
null
}
return LogItem(num.toString(), log, level, tokenFilterLogs, tokenLogs, processName)
}
override fun getPatternPrintFilter(col: Int): Pattern? {
var pattern: Pattern? = null
if ((mColumnItems[col]?.mNth ?: -1) == mLogNth) {
pattern = mPatternPrintFilter
}
else {
val tokenNth = mColumnItems[col]?.mNth ?: -1
for (idx in 0 until FormatManager.MAX_TOKEN_FILTER_COUNT) {
if (tokenNth == mTokenFilters[idx].mPosition) {
pattern = mPatternShowTokens[idx]
break
}
}
}
return pattern
}
}
| 0 | 0.917389 | 1 | 0.917389 | game-dev | MEDIA | 0.312453 | game-dev | 0.947151 | 1 | 0.947151 |
concourse/concourse | 1,333 | fly/commands/targets.go | package commands
import (
"os"
"sort"
"time"
"github.com/concourse/concourse/fly/rc"
"github.com/concourse/concourse/fly/ui"
"github.com/concourse/concourse/skymarshal/token"
"github.com/fatih/color"
)
type TargetsCommand struct{}
func (command *TargetsCommand) Execute([]string) error {
targets, err := rc.LoadTargets()
if err != nil {
return err
}
table := ui.Table{
Headers: ui.TableRow{
{Contents: "name", Color: color.New(color.Bold)},
{Contents: "url", Color: color.New(color.Bold)},
{Contents: "team", Color: color.New(color.Bold)},
{Contents: "expiry", Color: color.New(color.Bold)},
},
}
for targetName, targetValues := range targets {
expirationTime := getExpirationFromString(targetValues.Token)
row := ui.TableRow{
{Contents: string(targetName)},
{Contents: targetValues.API},
{Contents: targetValues.TeamName},
{Contents: expirationTime},
}
table.Data = append(table.Data, row)
}
sort.Sort(table.Data)
return table.Render(os.Stdout, Fly.PrintTableHeaders)
}
func getExpirationFromString(ttoken *rc.TargetToken) string {
if ttoken == nil || ttoken.Type == "" || ttoken.Value == "" {
return "n/a"
}
expiry, err := token.Factory{}.ParseExpiry(ttoken.Value)
if err != nil {
return "n/a: invalid token"
}
return expiry.UTC().Format(time.RFC1123)
}
| 0 | 0.811974 | 1 | 0.811974 | game-dev | MEDIA | 0.409946 | game-dev | 0.889642 | 1 | 0.889642 |
suhang12332/Swift-Craft-Launcher | 5,594 | SwiftCraftLauncher/Services/QuiltLoaderService.swift | import Foundation
enum QuiltLoaderService {
/// 获取所有 Loader 版本(静默版本)
/// - Parameter minecraftVersion: Minecraft 版本
/// - Returns: 加载器版本列表,失败时返回空数组
static func fetchAllQuiltLoaders(for minecraftVersion: String) async -> [QuiltLoaderResponse] {
do {
return try await fetchAllQuiltLoadersThrowing(for: minecraftVersion)
} catch {
let globalError = GlobalError.from(error)
Logger.shared.error("获取 Fabric 加载器版本失败: \(globalError.chineseMessage)")
GlobalErrorHandler.shared.handle(globalError)
return []
}
}
/// 获取所有可用 Quilt Loader 版本
static func fetchAllQuiltLoadersThrowing(for minecraftVersion: String) async throws -> [QuiltLoaderResponse] {
let url = URLConfig.API.Quilt.loaderBase.appendingPathComponent(minecraftVersion)
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw GlobalError.download(
chineseMessage: "获取 Quilt 加载器列表失败: HTTP \(response)",
i18nKey: "error.download.quilt_loaders_fetch_failed",
level: .notification
)
}
let decoder = JSONDecoder()
let allLoaders = try decoder.decode([QuiltLoaderResponse].self, from: data)
return allLoaders.filter { !$0.loader.version.lowercased().contains("beta") && !$0.loader.version.lowercased().contains("pre") }
}
/// 获取指定版本的 Quilt Loader
/// - Parameters:
/// - minecraftVersion: Minecraft 版本
/// - loaderVersion: 指定的加载器版本
/// - Returns: 指定版本的加载器
/// - Throws: GlobalError 当操作失败时
static func fetchSpecificLoaderVersion(for minecraftVersion: String, loaderVersion: String) async throws -> ModrinthLoader {
let cacheKey = "\(minecraftVersion)-\(loaderVersion)"
// 1. 查全局缓存
if let cached = AppCacheManager.shared.get(namespace: "quilt", key: cacheKey, as: ModrinthLoader.self) {
return cached
}
// 2. 直接下载指定版本的 version.json
let (data, response) = try await URLSession.shared.data(from: URLConfig.API.Modrinth.loaderProfile(loader: "quilt", version: loaderVersion))
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw GlobalError.download(
chineseMessage: "获取 Quilt profile 失败: HTTP \(response)",
i18nKey: "error.download.quilt_profile_fetch_failed",
level: .notification
)
}
var result = try JSONDecoder().decode(ModrinthLoader.self, from: data)
result.version = loaderVersion
result = CommonService.processGameVersionPlaceholders(loader: result, gameVersion: minecraftVersion)
// 3. 存入缓存
AppCacheManager.shared.setSilently(namespace: "quilt", key: cacheKey, value: result)
return result
}
/// 设置指定版本的 Quilt 加载器(静默版本)
/// - Parameters:
/// - gameVersion: 游戏版本
/// - loaderVersion: 指定的加载器版本
/// - gameInfo: 游戏信息
/// - onProgressUpdate: 进度更新回调
/// - Returns: 设置结果,失败时返回 nil
static func setupWithSpecificVersion(
for gameVersion: String,
loaderVersion: String,
gameInfo: GameVersionInfo,
onProgressUpdate: @escaping (String, Int, Int) -> Void
) async -> (loaderVersion: String, classpath: String, mainClass: String)? {
do {
return try await setupWithSpecificVersionThrowing(
for: gameVersion,
loaderVersion: loaderVersion,
gameInfo: gameInfo,
onProgressUpdate: onProgressUpdate
)
} catch {
let globalError = GlobalError.from(error)
Logger.shared.error("Quilt 指定版本设置失败: \(globalError.chineseMessage)")
GlobalErrorHandler.shared.handle(globalError)
return nil
}
}
/// 设置指定版本的 Quilt 加载器(抛出异常版本)
/// - Parameters:
/// - gameVersion: 游戏版本
/// - loaderVersion: 指定的加载器版本
/// - gameInfo: 游戏信息
/// - onProgressUpdate: 进度更新回调
/// - Returns: 设置结果
/// - Throws: GlobalError 当操作失败时
static func setupWithSpecificVersionThrowing(
for gameVersion: String,
loaderVersion: String,
gameInfo: GameVersionInfo,
onProgressUpdate: @escaping (String, Int, Int) -> Void
) async throws -> (loaderVersion: String, classpath: String, mainClass: String) {
Logger.shared.info("开始设置指定版本的 Quilt 加载器: \(loaderVersion)")
let quiltProfile = try await fetchSpecificLoaderVersion(for: gameVersion, loaderVersion: loaderVersion)
let librariesDirectory = AppPaths.librariesDirectory
let fileManager = CommonFileManager(librariesDir: librariesDirectory)
fileManager.onProgressUpdate = onProgressUpdate
await fileManager.downloadFabricJars(libraries: quiltProfile.libraries)
let classpathString = CommonService.generateFabricClasspath(from: quiltProfile, librariesDir: librariesDirectory)
let mainClass = quiltProfile.mainClass
guard let version = quiltProfile.version else {
throw GlobalError.resource(
chineseMessage: "Quilt profile 缺少版本信息",
i18nKey: "error.resource.quilt_missing_version",
level: .notification
)
}
return (loaderVersion: version, classpath: classpathString, mainClass: mainClass)
}
}
extension QuiltLoaderService: ModLoaderHandler {}
| 0 | 0.742595 | 1 | 0.742595 | game-dev | MEDIA | 0.617783 | game-dev,mobile | 0.930913 | 1 | 0.930913 |
ldtteam/minecolonies | 1,888 | src/main/java/com/minecolonies/core/event/capabilityproviders/MinecoloniesWorldColonyManagerCapabilityProvider.java | package com.minecolonies.core.event.capabilityproviders;
import com.minecolonies.core.colony.IColonyManagerCapability;
import net.minecraft.nbt.Tag;
import net.minecraft.core.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import javax.annotation.Nonnull;
import static com.minecolonies.core.MineColonies.COLONY_MANAGER_CAP;
/**
* Capability provider for the world capability of Minecolonies.
*/
public class MinecoloniesWorldColonyManagerCapabilityProvider implements ICapabilitySerializable<Tag>
{
/**
* The chunk map capability optional.
*/
private final LazyOptional<IColonyManagerCapability> colonyManagerOptional;
/**
* The chunk map capability.
*/
private final IColonyManagerCapability colonyManager;
/**
* Is this the main overworld cap?
*/
private final boolean overworld;
/**
* Constructor of the provider.
*/
public MinecoloniesWorldColonyManagerCapabilityProvider(final boolean overworld)
{
this.colonyManager = new IColonyManagerCapability.Impl();
this.colonyManagerOptional = LazyOptional.of(() -> colonyManager);
this.overworld = overworld;
}
@Override
public Tag serializeNBT()
{
return IColonyManagerCapability.Storage.writeNBT(COLONY_MANAGER_CAP, colonyManager, overworld);
}
@Override
public void deserializeNBT(final Tag nbt)
{
IColonyManagerCapability.Storage.readNBT(COLONY_MANAGER_CAP, colonyManager, overworld, nbt);
}
@Nonnull
@Override
public <T> LazyOptional<T> getCapability(@Nonnull final Capability<T> cap, final Direction dir)
{
return cap == COLONY_MANAGER_CAP ? colonyManagerOptional.cast() : LazyOptional.empty();
}
} | 0 | 0.681232 | 1 | 0.681232 | game-dev | MEDIA | 0.893454 | game-dev | 0.626075 | 1 | 0.626075 |
ReactVision/virocore | 14,303 | wasm/libs/bullet/src/BulletDynamics/Featherstone/btMultiBody.h | /*
* PURPOSE:
* Class representing an articulated rigid body. Stores the body's
* current state, allows forces and torques to be set, handles
* timestepping and implements Featherstone's algorithm.
*
* COPYRIGHT:
* Copyright (C) Stephen Thompson, <stephen@solarflare.org.uk>, 2011-2013
* Portions written By Erwin Coumans: replacing Eigen math library by Bullet LinearMath and a dedicated 6x6 matrix inverse (solveImatrix)
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_MULTIBODY_H
#define BT_MULTIBODY_H
#include "LinearMath/btScalar.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btQuaternion.h"
#include "LinearMath/btMatrix3x3.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btMultiBodyLink.h"
class btMultiBodyLinkCollider;
class btMultiBody
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
//
// initialization
//
btMultiBody(int n_links, // NOT including the base
btScalar mass, // mass of base
const btVector3 &inertia, // inertia of base, in base frame; assumed diagonal
bool fixed_base_, // whether the base is fixed (true) or can move (false)
bool can_sleep_);
~btMultiBody();
void setupPrismatic(int i, // 0 to num_links-1
btScalar mass,
const btVector3 &inertia, // in my frame; assumed diagonal
int parent,
const btQuaternion &rot_parent_to_this, // rotate points in parent frame to my frame.
const btVector3 &joint_axis, // in my frame
const btVector3 &r_vector_when_q_zero, // vector from parent COM to my COM, in my frame, when q = 0.
bool disableParentCollision=false
);
void setupRevolute(int i, // 0 to num_links-1
btScalar mass,
const btVector3 &inertia,
int parent,
const btQuaternion &zero_rot_parent_to_this, // rotate points in parent frame to this frame, when q = 0
const btVector3 &joint_axis, // in my frame
const btVector3 &parent_axis_position, // vector from parent COM to joint axis, in PARENT frame
const btVector3 &my_axis_position, // vector from joint axis to my COM, in MY frame
bool disableParentCollision=false);
const btMultibodyLink& getLink(int index) const
{
return links[index];
}
btMultibodyLink& getLink(int index)
{
return links[index];
}
void setBaseCollider(btMultiBodyLinkCollider* collider)//collider can be NULL to disable collision for the base
{
m_baseCollider = collider;
}
const btMultiBodyLinkCollider* getBaseCollider() const
{
return m_baseCollider;
}
btMultiBodyLinkCollider* getBaseCollider()
{
return m_baseCollider;
}
//
// get parent
// input: link num from 0 to num_links-1
// output: link num from 0 to num_links-1, OR -1 to mean the base.
//
int getParent(int link_num) const;
//
// get number of links, masses, moments of inertia
//
int getNumLinks() const { return links.size(); }
btScalar getBaseMass() const { return base_mass; }
const btVector3 & getBaseInertia() const { return base_inertia; }
btScalar getLinkMass(int i) const;
const btVector3 & getLinkInertia(int i) const;
//
// change mass (incomplete: can only change base mass and inertia at present)
//
void setBaseMass(btScalar mass) { base_mass = mass; }
void setBaseInertia(const btVector3 &inertia) { base_inertia = inertia; }
//
// get/set pos/vel/rot/omega for the base link
//
const btVector3 & getBasePos() const { return base_pos; } // in world frame
const btVector3 getBaseVel() const
{
return btVector3(m_real_buf[3],m_real_buf[4],m_real_buf[5]);
} // in world frame
const btQuaternion & getWorldToBaseRot() const
{
return base_quat;
} // rotates world vectors into base frame
btVector3 getBaseOmega() const { return btVector3(m_real_buf[0],m_real_buf[1],m_real_buf[2]); } // in world frame
void setBasePos(const btVector3 &pos)
{
base_pos = pos;
}
void setBaseVel(const btVector3 &vel)
{
m_real_buf[3]=vel[0]; m_real_buf[4]=vel[1]; m_real_buf[5]=vel[2];
}
void setWorldToBaseRot(const btQuaternion &rot)
{
base_quat = rot;
}
void setBaseOmega(const btVector3 &omega)
{
m_real_buf[0]=omega[0];
m_real_buf[1]=omega[1];
m_real_buf[2]=omega[2];
}
//
// get/set pos/vel for child links (i = 0 to num_links-1)
//
btScalar getJointPos(int i) const;
btScalar getJointVel(int i) const;
void setJointPos(int i, btScalar q);
void setJointVel(int i, btScalar qdot);
//
// direct access to velocities as a vector of 6 + num_links elements.
// (omega first, then v, then joint velocities.)
//
const btScalar * getVelocityVector() const
{
return &m_real_buf[0];
}
/* btScalar * getVelocityVector()
{
return &real_buf[0];
}
*/
//
// get the frames of reference (positions and orientations) of the child links
// (i = 0 to num_links-1)
//
const btVector3 & getRVector(int i) const; // vector from COM(parent(i)) to COM(i), in frame i's coords
const btQuaternion & getParentToLocalRot(int i) const; // rotates vectors in frame parent(i) to vectors in frame i.
//
// transform vectors in local frame of link i to world frame (or vice versa)
//
btVector3 localPosToWorld(int i, const btVector3 &vec) const;
btVector3 localDirToWorld(int i, const btVector3 &vec) const;
btVector3 worldPosToLocal(int i, const btVector3 &vec) const;
btVector3 worldDirToLocal(int i, const btVector3 &vec) const;
//
// calculate kinetic energy and angular momentum
// useful for debugging.
//
btScalar getKineticEnergy() const;
btVector3 getAngularMomentum() const;
//
// set external forces and torques. Note all external forces/torques are given in the WORLD frame.
//
void clearForcesAndTorques();
void clearVelocities();
void addBaseForce(const btVector3 &f)
{
base_force += f;
}
void addBaseTorque(const btVector3 &t) { base_torque += t; }
void addLinkForce(int i, const btVector3 &f);
void addLinkTorque(int i, const btVector3 &t);
void addJointTorque(int i, btScalar Q);
const btVector3 & getBaseForce() const { return base_force; }
const btVector3 & getBaseTorque() const { return base_torque; }
const btVector3 & getLinkForce(int i) const;
const btVector3 & getLinkTorque(int i) const;
btScalar getJointTorque(int i) const;
//
// dynamics routines.
//
// timestep the velocities (given the external forces/torques set using addBaseForce etc).
// also sets up caches for calcAccelerationDeltas.
//
// Note: the caller must provide three vectors which are used as
// temporary scratch space. The idea here is to reduce dynamic
// memory allocation: the same scratch vectors can be re-used
// again and again for different Multibodies, instead of each
// btMultiBody allocating (and then deallocating) their own
// individual scratch buffers. This gives a considerable speed
// improvement, at least on Windows (where dynamic memory
// allocation appears to be fairly slow).
//
void stepVelocities(btScalar dt,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v,
btAlignedObjectArray<btMatrix3x3> &scratch_m);
// calcAccelerationDeltas
// input: force vector (in same format as jacobian, i.e.:
// 3 torque values, 3 force values, num_links joint torque values)
// output: 3 omegadot values, 3 vdot values, num_links q_double_dot values
// (existing contents of output array are replaced)
// stepVelocities must have been called first.
void calcAccelerationDeltas(const btScalar *force, btScalar *output,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v) const;
// apply a delta-vee directly. used in sequential impulses code.
void applyDeltaVee(const btScalar * delta_vee)
{
for (int i = 0; i < 6 + getNumLinks(); ++i)
{
m_real_buf[i] += delta_vee[i];
}
}
void applyDeltaVee(const btScalar * delta_vee, btScalar multiplier)
{
btScalar sum = 0;
for (int i = 0; i < 6 + getNumLinks(); ++i)
{
sum += delta_vee[i]*multiplier*delta_vee[i]*multiplier;
}
btScalar l = btSqrt(sum);
/*
static btScalar maxl = -1e30f;
if (l>maxl)
{
maxl=l;
// printf("maxl=%f\n",maxl);
}
*/
if (l>m_maxAppliedImpulse)
{
// printf("exceeds 100: l=%f\n",maxl);
multiplier *= m_maxAppliedImpulse/l;
}
for (int i = 0; i < 6 + getNumLinks(); ++i)
{
sum += delta_vee[i]*multiplier*delta_vee[i]*multiplier;
m_real_buf[i] += delta_vee[i] * multiplier;
}
}
// timestep the positions (given current velocities).
void stepPositions(btScalar dt);
//
// contacts
//
// This routine fills out a contact constraint jacobian for this body.
// the 'normal' supplied must be -n for body1 or +n for body2 of the contact.
// 'normal' & 'contact_point' are both given in world coordinates.
void fillContactJacobian(int link,
const btVector3 &contact_point,
const btVector3 &normal,
btScalar *jac,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v,
btAlignedObjectArray<btMatrix3x3> &scratch_m) const;
//
// sleeping
//
void setCanSleep(bool canSleep)
{
can_sleep = canSleep;
}
bool isAwake() const { return awake; }
void wakeUp();
void goToSleep();
void checkMotionAndSleepIfRequired(btScalar timestep);
bool hasFixedBase() const
{
return fixed_base;
}
int getCompanionId() const
{
return m_companionId;
}
void setCompanionId(int id)
{
//printf("for %p setCompanionId(%d)\n",this, id);
m_companionId = id;
}
void setNumLinks(int numLinks)//careful: when changing the number of links, make sure to re-initialize or update existing links
{
links.resize(numLinks);
}
btScalar getLinearDamping() const
{
return m_linearDamping;
}
void setLinearDamping( btScalar damp)
{
m_linearDamping = damp;
}
btScalar getAngularDamping() const
{
return m_angularDamping;
}
bool getUseGyroTerm() const
{
return m_useGyroTerm;
}
void setUseGyroTerm(bool useGyro)
{
m_useGyroTerm = useGyro;
}
btScalar getMaxAppliedImpulse() const
{
return m_maxAppliedImpulse;
}
void setMaxAppliedImpulse(btScalar maxImp)
{
m_maxAppliedImpulse = maxImp;
}
void setHasSelfCollision(bool hasSelfCollision)
{
m_hasSelfCollision = hasSelfCollision;
}
bool hasSelfCollision() const
{
return m_hasSelfCollision;
}
private:
btMultiBody(const btMultiBody &); // not implemented
void operator=(const btMultiBody &); // not implemented
void compTreeLinkVelocities(btVector3 *omega, btVector3 *vel) const;
void solveImatrix(const btVector3& rhs_top, const btVector3& rhs_bot, float result[6]) const;
private:
btMultiBodyLinkCollider* m_baseCollider;//can be NULL
btVector3 base_pos; // position of COM of base (world frame)
btQuaternion base_quat; // rotates world points into base frame
btScalar base_mass; // mass of the base
btVector3 base_inertia; // inertia of the base (in local frame; diagonal)
btVector3 base_force; // external force applied to base. World frame.
btVector3 base_torque; // external torque applied to base. World frame.
btAlignedObjectArray<btMultibodyLink> links; // array of links, excluding the base. index from 0 to num_links-1.
btAlignedObjectArray<btMultiBodyLinkCollider*> m_colliders;
//
// real_buf:
// offset size array
// 0 6 + num_links v (base_omega; base_vel; joint_vels)
// 6+num_links num_links D
//
// vector_buf:
// offset size array
// 0 num_links h_top
// num_links num_links h_bottom
//
// matrix_buf:
// offset size array
// 0 num_links+1 rot_from_parent
//
btAlignedObjectArray<btScalar> m_real_buf;
btAlignedObjectArray<btVector3> vector_buf;
btAlignedObjectArray<btMatrix3x3> matrix_buf;
//std::auto_ptr<Eigen::LU<Eigen::Matrix<btScalar, 6, 6> > > cached_imatrix_lu;
btMatrix3x3 cached_inertia_top_left;
btMatrix3x3 cached_inertia_top_right;
btMatrix3x3 cached_inertia_lower_left;
btMatrix3x3 cached_inertia_lower_right;
bool fixed_base;
// Sleep parameters.
bool awake;
bool can_sleep;
btScalar sleep_timer;
int m_companionId;
btScalar m_linearDamping;
btScalar m_angularDamping;
bool m_useGyroTerm;
btScalar m_maxAppliedImpulse;
bool m_hasSelfCollision;
};
#endif
| 0 | 0.979796 | 1 | 0.979796 | game-dev | MEDIA | 0.958948 | game-dev | 0.985189 | 1 | 0.985189 |
Cibiv/IQ-TREE | 2,951 | ncl/nxsreader.h | // Copyright (C) 1999-2003 Paul O. Lewis
//
// This file is part of NCL (Nexus Class Library) version 2.0.
//
// NCL 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.
//
// NCL 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 NCL; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifndef NCL_NXSREADER_H
#define NCL_NXSREADER_H
/*----------------------------------------------------------------------------------------------------------------------
| This is the class that orchestrates the reading of a NEXUS data file. An object of this class should be created,
| and objects of any block classes that are expected to be needed should be added to `blockList' using the Add
| member function. The Execute member function is then called, which reads the data file until encountering a block
| name, at which point the correct block is looked up in `blockList' and that object's Read method called.
*/
class NxsReader
{
public:
enum NxsTolerateFlags /* Flags used with data member tolerate used to allow some flexibility with respect to the NEXUS format */
{
allowMissingInEquate = 0x0001, /* if set, equate symbols are allowed for missing data symbol */
allowPunctuationInNames = 0x0002 /* if set, some punctuation is allowed within tokens representing labels for taxa, characters, and sets */
};
NxsReader();
virtual ~NxsReader();
bool BlockListEmpty();
unsigned PositionInBlockList(NxsBlock *b);
void Add(NxsBlock *newBlock);
void Detach(NxsBlock *newBlock);
void Reassign(NxsBlock *oldb, NxsBlock *newb);
void Execute(NxsToken& token, bool notifyStartStop = true);
virtual void DebugReportBlock(NxsBlock &nexusBlock);
const char *NCLNameAndVersion();
const char *NCLCopyrightNotice();
const char *NCLHomePageURL();
virtual void ExecuteStarting();
virtual void ExecuteStopping();
virtual bool EnteringBlock(NxsString blockName);
virtual void ExitingBlock(NxsString blockName);
virtual void OutputComment(const NxsString &comment);
virtual void NexusError(NxsString msg, file_pos pos, long line, long col);
virtual void SkippingDisabledBlock(NxsString blockName);
virtual void SkippingBlock(NxsString blockName);
protected:
NxsBlock *blockList; /* pointer to first block in list of blocks */
NxsBlock *currBlock; /* pointer to current block in list of blocks */
};
typedef NxsBlock NexusBlock;
typedef NxsReader Nexus;
#endif
| 0 | 0.899082 | 1 | 0.899082 | game-dev | MEDIA | 0.199381 | game-dev | 0.869344 | 1 | 0.869344 |
UnioGame/leoecs.lite.features | 4,353 | Ability/SubFeatures/AbilityAnimation/Systems/UpdateAttackAnimationSpeedSystem.cs | namespace Ability.SubFeatures.AbilityAnimation.Systems
{
using System;
using System.Collections.Generic;
using Animations.Animator.Data;
using Animations.Animatror.Components;
using Game.Ecs.Ability.Aspects;
using Game.Ecs.Ability.Common.Components;
using Game.Ecs.Ability.SubFeatures.AbilityAnimation.Aspects;
using Game.Ecs.Ability.SubFeatures.AbilityAnimation.Components;
using Game.Ecs.Ability.SubFeatures.AbilityAnimation.Data;
using Game.Ecs.Ability.Tools;
using Game.Ecs.AbilityInventory.Components;
using Game.Ecs.Characteristics.AttackSpeed.Components;
using Game.Ecs.Core.Components;
using Leopotam.EcsLite;
using UniCore.Runtime.ProfilerTools;
using UnityEngine;
using UniGame.LeoEcs.Bootstrap.Runtime.Attributes;
using UniGame.LeoEcs.Shared.Components;
using UniGame.LeoEcs.Shared.Extensions;
using UniGame.LeoEcs.Timer.Components;
/// <summary>
/// Ускоряем анимацию атаки в зависимости от скорости атаки
/// </summary>
#if ENABLE_IL2CPP
using Unity.IL2CPP.CompilerServices;
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
#endif
[Serializable]
[ECSDI]
public class UpdateAttackAnimationSpeedSystem : IEcsInitSystem, IEcsRunSystem
{
private readonly AnimatorParametersMap _parametersMap;
private EcsWorld _world;
private EcsFilter _filter;
private EcsFilter _abilityFilter;
private AbilityAspect _abilityAspect;
private AbilityAnimationAspect _animationAspect;
private AbilityTools _abilityTool;
private AnimationsIdsMap _animatorGlobalMap;
private Stack<EcsPackedEntity> _stack = new Stack<EcsPackedEntity>();
public UpdateAttackAnimationSpeedSystem(AnimatorParametersMap parametersMap)
{
_parametersMap = parametersMap;
}
public void Init(IEcsSystems systems)
{
_world = systems.GetWorld();
_filter = _world.Filter<AnimatorComponent>()
.Inc<RecalculateAnimationAttackSpeedSelfRequest>()
.Inc<AbilityInHandLinkComponent>()
.Inc<AttackAbilityIdComponent>()
.Inc<AnimationsLengthMapComponent>()
.End();
_abilityFilter = _world.Filter<AbilityIdComponent>()
.Inc<AbilityInventoryCompleteComponent>()
.Inc<CooldownComponent>()
.Inc<OwnerComponent>()
.End();
_abilityTool = _world.GetGlobal<AbilityTools>();
_animatorGlobalMap = _world.GetGlobal<AnimationsIdsMap>();
}
public void Run(IEcsSystems systems)
{
foreach (var ownerEntity in _filter)
{
ref var attackAbilityIdComponent = ref _world.GetComponent<AttackAbilityIdComponent>(ownerEntity);
var abilityEntity = _abilityTool.GetAbilityBySlot(ownerEntity, attackAbilityIdComponent.Value);
if(abilityEntity == -1) continue;
ref var cooldownComponent = ref _abilityAspect.Cooldown.Get(abilityEntity);
ref var abilityAnimationIDComponent = ref _animationAspect.ClipId.Get(abilityEntity);
var animationId = abilityAnimationIDComponent.animationId;
ref var animationsLengthMap = ref _animationAspect.AnimationsLengthMap.Get(ownerEntity);
if (!animationsLengthMap.value.TryGetValue((AnimationClipId)animationId, out var animationLength))
{
continue;
}
if(animationLength < cooldownComponent.Value)
{
_animationAspect.RecalculateAttackSpeed.Del(ownerEntity);
continue;
}
ref var animatorComponent = ref _animationAspect.Animator.Get(ownerEntity);
var ratio = Math.Clamp(animationLength / cooldownComponent.Value,0,100) ;
animatorComponent.Value.SetFloat(_parametersMap.attackSpeed, ratio);
_animationAspect.RecalculateAttackSpeed.Del(ownerEntity);
}
}
}
} | 0 | 0.800699 | 1 | 0.800699 | game-dev | MEDIA | 0.986218 | game-dev | 0.838623 | 1 | 0.838623 |
ConstellationLanguage/Constellation | 1,126 | Constellation/Assets/Constellation/Plugins/ConstellationUnity/Scripts/Nodes/UI/Button.cs | using UnityEngine;
namespace Constellation.UI {
public class Button : INode, IReceiver, IRequireGameObject, IDestroy {
UnityEngine.UI.Button button;
public const string NAME = "Button";
private ISender output;
public void Setup (INodeParameters _nodeParameters) {
_nodeParameters.AddInput (this, false, "Object", "Button object");
output = _nodeParameters.GetSender ();
_nodeParameters.AddOutput (true, "Mouse Click");
}
public string NodeName () {
return NAME;
}
public string NodeNamespace () {
return NameSpace.NAME;
}
public void Set (GameObject _gameObject) {
var button = _gameObject.GetComponent<UnityEngine.UI.Button> ();
if (button != null) {
this.button = button;
this.button.onClick.AddListener(ButtonClicked);
}
}
private void ButtonClicked()
{
output.Send(new Ray(button.gameObject.name), 0);
}
public void OnDestroy()
{
this.button.onClick.RemoveAllListeners();
}
public void Receive (Ray value, Input _input) {
if (_input.InputId == 0)
Set (UnityObjectsConvertions.ConvertToGameObject (value.GetObject ()));
}
}
} | 0 | 0.832653 | 1 | 0.832653 | game-dev | MEDIA | 0.972186 | game-dev | 0.66209 | 1 | 0.66209 |
MergHQ/CRYENGINE | 8,227 | Code/GameTemplates/cs/Sydewinder/Assets/Scripts/Entities/Particle/ParticleEffect.lua | ParticleEffect = {
Properties = {
soclasses_SmartObjectClass = "",
ParticleEffect="",
Comment="",
bActive=1, -- Activate on startup
bPrime=1, -- Starts in equilibrium state, as if activated in past
Scale=1, -- Scale entire effect size.
SpeedScale=1, -- Scale particle emission speed
TimeScale=1, -- Scale emitter time evolution
CountScale=1, -- Scale particle counts.
bCountPerUnit=0, -- Multiply count by attachment extent
Strength=-1, -- Custom param control
esAttachType="", -- BoundingBox, Physics, Render
esAttachForm="", -- Vertices, Edges, Surface, Volume
PulsePeriod=0, -- Restart continually at this period.
NetworkSync=0, -- Do I want to be bound to the network?
bRegisterByBBox=0, -- Register In VisArea by BoundingBox, not by Position
Audio =
{
bEnableAudio=0, -- Toggles update of audio data.
audioRTPCRtpc="particlefx", -- The default audio RTPC name used.
esSoundObstructionType = "Ignore",
}
},
Editor = {
Model="Editor/Objects/Particles.cgf",
Icon="Particles.bmp",
},
States = { "Active","Idle" },
Client = {},
Server = {},
};
Net.Expose {
Class = ParticleEffect,
ClientMethods = {
ClEvent_Spawn = { RELIABLE_ORDERED, POST_ATTACH },
ClEvent_Enable = { RELIABLE_ORDERED, POST_ATTACH },
ClEvent_Disable = { RELIABLE_ORDERED, POST_ATTACH },
ClEvent_Restart = { RELIABLE_ORDERED, POST_ATTACH },
ClEvent_Kill = { RELIABLE_ORDERED, POST_ATTACH },
},
ServerMethods = {
},
ServerProperties = {
},
};
-------------------------------------------------------
function ParticleEffect:OnSpawn()
if (not table.NetworkSync) then
self:SetFlags(ENTITY_FLAG_CLIENT_ONLY, 0);
end
end
-------------------------------------------------------
function ParticleEffect:OnLoad(table)
self:GotoState(""); -- forces execution of either "Idle" or "Active" state constructor
if (not table.nParticleSlot) then
if (self.nParticleSlot) then
self:DeleteParticleEmitter( self.nParticleSlot );
end
self:GotoState("Idle");
elseif (not self.nParticleSlot or self.nParticleSlot ~= table.nParticleSlot) then
if (self.nParticleSlot) then
self:DeleteParticleEmitter( self.nParticleSlot );
end
self:GotoState("Idle");
self.nParticleSlot = self:LoadParticleEffect( table.nParticleSlot, self.Properties.ParticleEffect, self.Properties );
self:GotoState("Active");
end
end
-------------------------------------------------------
function ParticleEffect:OnSave(table)
table.nParticleSlot = self.nParticleSlot;
end
-------------------------------------------------------
function ParticleEffect:OnPropertyChange()
if self.Properties.bActive ~= 0 then
self:GotoState( "" );
self:GotoState( "Active" );
else
self:GotoState( "Idle" );
end
end
-------------------------------------------------------
function ParticleEffect:OnReset()
self:GotoState( "Idle" );
if self.Properties.bActive ~= 0 then
self:GotoState( "Active" );
end
end
------------------------------------------------------------------------------------------------------
function ParticleEffect:Event_Enable()
self:GotoState( "Active" );
self:ActivateOutput( "Enable", true );
if CryAction.IsServer() and self.allClients then
self.allClients:ClEvent_Enable();
end
end
function ParticleEffect:Event_Disable()
self:GotoState( "Idle" );
self:ActivateOutput( "Disable", true );
if CryAction.IsServer() and self.allClients then
self.allClients:ClEvent_Disable();
end
end
function ParticleEffect:Event_Restart()
self:GotoState( "Idle" );
self:GotoState( "Active" );
self:ActivateOutput( "Restart", true );
if CryAction.IsServer() and self.allClients then
self.allClients:ClEvent_Restart();
end
end
function ParticleEffect:Event_Spawn()
self:GetDirectionVector(1, g_Vectors.temp_v2); -- 1=forward vector
Particle.SpawnEffect( self.Properties.ParticleEffect, self:GetPos(g_Vectors.temp_v1), g_Vectors.temp_v2, self.Properties.Scale );
self:ActivateOutput( "Spawn", true );
if CryAction.IsServer() and self.allClients then
self.allClients:ClEvent_Spawn();
end
end
function ParticleEffect:Event_Kill()
if (self.nParticleSlot) then
self:DeleteParticleEmitter(self.nParticleSlot);
end;
self:GotoState( "Idle" );
if CryAction.IsServer() and self.allClients then
self.allClients:ClEvent_Kill();
end
end
function ParticleEffect:Enable()
self:GotoState("Active");
if CryAction.IsServer() and self.allClients then
self.allClients:ClEvent_Enable();
end
end
function ParticleEffect:Disable()
self:GotoState("Idle");
if CryAction.IsServer() and self.allClients then
self.allClients:ClEvent_Disable();
end
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Active State
-------------------------------------------------------------------------------
ParticleEffect.Active =
{
OnBeginState = function( self )
if not self.nParticleSlot then
self.nParticleSlot = -1;
end
self.nParticleSlot = self:LoadParticleEffect( self.nParticleSlot, self.Properties.ParticleEffect, self.Properties );
end,
OnLeaveArea = function( self,entity,areaId )
self:GotoState( "Idle" );
end,
}
-------------------------------------------------------------------------------
-- Idle State
-------------------------------------------------------------------------------
ParticleEffect.Idle =
{
OnBeginState = function( self )
if self.nParticleSlot then
self:FreeSlot(self.nParticleSlot);
self.nParticleSlot = nil;
end
end,
OnEnterArea = function( self,entity,areaId )
self:GotoState( "Active" );
end,
}
-- !!! net and states stuff
function ParticleEffect:DefaultState(cs, state)
local default = self[state];
self[cs][state] = {
OnBeginState = default.OnBeginState,
OnEndState = default.OnEndState,
OnLeaveArea = default.OnLeaveArea,
OnEnterArea = default.OnEnterArea,
}
end
-------------------------------------------------------
ParticleEffect:DefaultState("Server", "Idle");
ParticleEffect:DefaultState("Server", "Active");
ParticleEffect:DefaultState("Client", "Idle");
ParticleEffect:DefaultState("Client", "Active");
-------------------------------------------------------
ParticleEffect.FlowEvents =
{
Inputs =
{
Disable = { ParticleEffect.Event_Disable, "bool" },
Enable = { ParticleEffect.Event_Enable, "bool" },
Restart = { ParticleEffect.Event_Restart, "bool" },
Spawn = { ParticleEffect.Event_Spawn, "bool" },
Kill = { ParticleEffect.Event_Kill, "bool" },
},
Outputs =
{
Disable = "bool",
Enable = "bool",
Restart = "bool",
Spawn = "bool",
},
}
-------------------------------------------------------
-- client functions
-------------------------------------------------------
-------------------------------------------------------
function ParticleEffect.Client:OnInit()
self:SetRegisterInSectors(1);
self.Properties.ParticleEffect = self:PreLoadParticleEffect( self.Properties.ParticleEffect );
self:SetUpdatePolicy(ENTITY_UPDATE_POT_VISIBLE);
--self:SetFlags(ENTITY_FLAG_CLIENT_ONLY, 0);
if (self.Properties.bActive ~= 0) then
self:GotoState( "Active" );
else
self:GotoState( "Idle" );
end
--self:NetPresent(nil);
end
-------------------------------------------------------
function ParticleEffect.Client:ClEvent_Spawn()
if( not CryAction.IsServer() ) then
self:Event_Spawn();
end
end
-------------------------------------------------------
function ParticleEffect.Client:ClEvent_Enable()
if( not CryAction.IsServer() ) then
self:Event_Enable();
end
end
-------------------------------------------------------
function ParticleEffect.Client:ClEvent_Disable()
if( not CryAction.IsServer() ) then
self:Event_Disable();
end
end
-------------------------------------------------------
function ParticleEffect.Client:ClEvent_Restart()
if( not CryAction.IsServer() ) then
self:Event_Restart();
end
end
-------------------------------------------------------
function ParticleEffect.Client:ClEvent_Kill()
if( not CryAction.IsServer() ) then
self:Event_Kill();
end
end
| 0 | 0.814702 | 1 | 0.814702 | game-dev | MEDIA | 0.967728 | game-dev | 0.888599 | 1 | 0.888599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.