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
lorddusk/HQM
1,689
common/src/main/java/hardcorequesting/common/quests/task/item/BlockRequirementTask.java
package hardcorequesting.common.quests.task.item; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import hardcorequesting.common.io.adapter.Adapter; import hardcorequesting.common.io.adapter.QuestTaskAdapter; import hardcorequesting.common.quests.Quest; import hardcorequesting.common.quests.task.TaskType; import net.minecraft.core.NonNullList; import net.minecraft.util.GsonHelper; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; import java.lang.reflect.Method; public abstract class BlockRequirementTask extends ItemRequirementTask { public static Method getSilkTouchDrop = null; public static final String NULL_NAME = "item.null.name"; private static final String BLOCKS = "blocks"; public BlockRequirementTask(TaskType<? extends BlockRequirementTask> type, Quest parent) { super(type, parent); } @Override public void onUpdate(Player player) { } public void checkProgress(BlockState state, Player player) { ItemStack drop = new ItemStack(state.getBlock()); NonNullList<ItemStack> consume = NonNullList.withSize(1, drop); increaseItems(consume, player.getUUID()); } @Override public void write(Adapter.JsonObjectBuilder builder) { builder.add(BLOCKS, parts.write(QuestTaskAdapter.ITEM_REQUIREMENT_ADAPTER)); } @SuppressWarnings("ConstantConditions") @Override public void read(JsonObject object) { parts.read(GsonHelper.getAsJsonArray(object, BLOCKS, new JsonArray()), QuestTaskAdapter.ITEM_REQUIREMENT_ADAPTER); } }
0
0.820435
1
0.820435
game-dev
MEDIA
0.993948
game-dev
0.875762
1
0.875762
mojontwins/MK1
9,889
examples/old/D'Veel'Ng/dev - orig/mainloop.h
// mainloop.h // Churrera copyleft 2011 by The Mojon Twins. void do_game () { int j; unsigned char *allpurposepuntero; unsigned char i; unsigned char playing; unsigned char n_pant; unsigned char maincounter; unsigned char objs_old, keys_old, life_old, killed_old; int key_m; #ifdef RANDOM_RESPAWN int x, y; #else unsigned char x, y; #endif unsigned char success; // Kepmston detection #asm halt in a, (31) inc a ld (_kempston_is_attached), a di #endasm // splib2 initialization sp_Initialize (7, 0); sp_Border (BLACK); sp_AddMemory(0, 56, 14, AD_FREE); // Define keys and default controls keys.up = sp_LookupKey('q'); keys.down = sp_LookupKey('a'); keys.left = sp_LookupKey('o'); keys.right = sp_LookupKey('p'); keys.fire = sp_LookupKey(' '); key_m = sp_LookupKey ('m'); joyfunc = sp_JoyKeyboard; // Load tileset allpurposepuntero = tileset; for (j = 0; j < 256; j++) { sp_TileArray (j, allpurposepuntero); allpurposepuntero += 8; } // Clipping rectangle spritesClipValues.row_coord = VIEWPORT_Y; spritesClipValues.col_coord = VIEWPORT_X; spritesClipValues.height = 20; spritesClipValues.width = 30; spritesClip = &spritesClipValues; // Sprite creation #ifdef NO_MASKS sp_player = sp_CreateSpr (sp_OR_SPRITE, 3, sprite_2_a, 1, TRANSPARENT); sp_AddColSpr (sp_player, sprite_2_b, TRANSPARENT); sp_AddColSpr (sp_player, sprite_2_c, TRANSPARENT); player.current_frame = player.next_frame = sprite_2_a; for (i = 0; i < 3; i ++) { sp_moviles [i] = sp_CreateSpr(sp_OR_SPRITE, 3, sprite_9_a, 1, TRANSPARENT); sp_AddColSpr (sp_moviles [i], sprite_9_b, TRANSPARENT); sp_AddColSpr (sp_moviles [i], sprite_9_c, TRANSPARENT); en_an [i].current_frame = sprite_9_a; } #else sp_player = sp_CreateSpr (sp_MASK_SPRITE, 3, sprite_2_a, 1, TRANSPARENT); sp_AddColSpr (sp_player, sprite_2_b, TRANSPARENT); sp_AddColSpr (sp_player, sprite_2_c, TRANSPARENT); player.current_frame = player.next_frame = sprite_2_a; for (i = 0; i < 3; i ++) { sp_moviles [i] = sp_CreateSpr(sp_MASK_SPRITE, 3, sprite_9_a, 2, TRANSPARENT); sp_AddColSpr (sp_moviles [i], sprite_9_b, TRANSPARENT); sp_AddColSpr (sp_moviles [i], sprite_9_c, TRANSPARENT); en_an [i].current_frame = sprite_9_a; } #endif #ifdef PLAYER_CAN_FIRE for (i = 0; i < MAX_BULLETS; i ++) { sp_bullets [i] = sp_CreateSpr (sp_OR_SPRITE, 2, sprite_19_a, 1, TRANSPARENT); sp_AddColSpr (sp_bullets [i], sprite_19_b, TRANSPARENT); } #endif while (1) { // Here the title screen sp_UpdateNow(); unpack ((unsigned int) (s_title)); select_joyfunc (); #ifndef DIRECT_TO_PLAY // Clear screen and show game frame cortina (); sp_UpdateNow(); unpack ((unsigned int) (s_marco)); #endif // Let's do it. playing = 1; init_player (); init_hotspots (); #ifndef DEACTIVATE_KEYS init_cerrojos (); #endif #if defined(PLAYER_KILLS_ENEMIES) || defined (PLAYER_CAN_FIRE) init_malotes (); #endif #ifdef PLAYER_CAN_FIRE init_bullets (); #endif n_pant = SCR_INICIO; maincounter = 0; #ifdef ACTIVATE_SCRIPTING script_result = 0; msc_init_all (); #endif draw_scr (n_pant); draw_life (); #ifndef DEACTIVATE_OBJECTS draw_objs (); #endif #ifndef DEACTIVATE_KEYS draw_keys (); #endif #if defined(PLAYER_KILLS_ENEMIES) || defined(PLAYER_CAN_FIRE) draw_killed (); #endif #ifdef PLAYER_KILLS_ENEMIES #ifdef SHOW_TOTAL // Show total of enemies next to the killed amount. sp_PrintAtInv (KILLED_Y, 2 + KILLED_X, 71, 15); sp_PrintAtInv (KILLED_Y, 3 + KILLED_X, 71, 16 + BADDIES_COUNT / 10); sp_PrintAtInv (KILLED_Y, 4 + KILLED_X, 71, 16 + BADDIES_COUNT % 10); #endif #endif half_life = 0; // Entering game #ifdef ACTIVATE_SCRIPTING script = e_scripts [MAP_W * MAP_H]; run_script (); #endif while (playing) { if (player.objs != objs_old) { draw_objs (); objs_old = player.objs; } if (player.life != life_old) { draw_life (); life_old = player.life; } if (player.keys != keys_old) { draw_keys (); keys_old = player.keys; } #if defined(PLAYER_KILLS_ENEMIES) || defined(PLAYER_CAN_FIRE) if (player.killed != killed_old) { draw_killed (); killed_old = player.killed; } #endif maincounter ++; half_life = !half_life; // Move player if ( !(player.estado & EST_MUR) ) move (n_pant); else { // WTF? } // Move enemies mueve_bicharracos (n_pant); #ifdef PLAYER_CAN_FIRE // Move bullets mueve_bullets (); #endif // Render for (i = 0; i < 3; i ++) { if (malotes [enoffs + i].t != 0) { // Only neccesary if there's rooms with less than 3 enemies. Remove otherwise to gain some bytes! #ifdef RANDOM_RESPAWN if (en_an [i].fanty_activo) { x = en_an [i].x >> 6; y = en_an [i].y >> 6; } else { #endif x = malotes [enoffs + i].x; y = malotes [enoffs + i].y; #ifdef RANDOM_RESPAWN } #endif sp_MoveSprAbs (sp_moviles [i], spritesClip, en_an [i].next_frame - en_an [i].current_frame, VIEWPORT_Y + (y >> 3), VIEWPORT_X + (x >> 3),x & 7, y & 7); en_an [i].current_frame = en_an [i].next_frame; } } // Precalc this, comes handy: x = player.x >> 6; y = player.y >> 6; if ( !(player.estado & EST_PARP) || !(half_life) ) sp_MoveSprAbs (sp_player, spritesClip, player.next_frame - player.current_frame, VIEWPORT_Y + (y >> 3), VIEWPORT_X + (x >> 3), x & 7, y & 7); else sp_MoveSprAbs (sp_player, spritesClip, player.next_frame - player.current_frame, -2, -2, 0, 0); player.current_frame = player.next_frame; #ifdef PLAYER_CAN_FIRE for (i = 0; i < MAX_BULLETS; i ++) { if (bullets [i].estado == 1) { sp_MoveSprAbs (sp_bullets [i], spritesClip, 0, VIEWPORT_Y + (bullets [i].y >> 3), VIEWPORT_X + (bullets [i].x >> 3), bullets [i].x & 7, bullets [i].y & 7); } else { sp_MoveSprAbs (sp_bullets [i], spritesClip, 0, -2, -2, 0, 0); } } #endif // Update to screen sp_UpdateNow(); #ifdef PLAYER_CAN_FIRE for (i = 0; i < 3; i ++) if (en_an [i].morido == 1) { peta_el_beeper (1); en_an [i].morido = 0; } #endif #ifdef PLAYER_FLICKERS // Flickering if (player.estado == EST_PARP) { player.ct_estado --; if (player.ct_estado == 0) player.estado = EST_NORMAL; } #endif // Hotspot interaction. if (x >= hotspot_x - 15 && x <= hotspot_x + 15 && y >= hotspot_y - 15 && y <= hotspot_y + 15) { // Deactivate hotspot draw_coloured_tile (VIEWPORT_X + (hotspot_x >> 3), VIEWPORT_Y + (hotspot_y >> 3), orig_tile); // Was it an object, key or life boost? if (hotspots [n_pant].act == 0) { player.life += PLAYER_REFILL; if (player.life > PLAYER_LIFE) player.life = PLAYER_LIFE; hotspots [n_pant].act = 2; peta_el_beeper (8); #ifndef DEACTIVATE_OBJECTS } else if (hotspots [n_pant].tipo == 1) { #ifdef ONLY_ONE_OBJECT if (player.objs == 0) { i = 1; player.objs ++; hotspots [n_pant].act = 0; peta_el_beeper (9); } else { i = 0; peta_el_beeper (4); draw_coloured_tile (VIEWPORT_X + (hotspot_x >> 3), VIEWPORT_Y + (hotspot_y >> 3), 17); } #else player.objs ++; hotspots [n_pant].act = 0; peta_el_beeper (9); #endif #endif #ifndef DEACTIVATE_KEYS } else if (hotspots [n_pant].tipo == 2) { player.keys ++; hotspots [n_pant].act = 0; peta_el_beeper (7); #endif } // PLOP!! hotspot_x = hotspot_y = 240; } // Flick screen checks and scripting related stuff i = (joyfunc) (&keys); #ifdef ACTIVATE_SCRIPTING #ifdef SCRIPTING_KEY_M if (sp_KeyPressed (key_m)) { #endif #ifdef SCRIPTING_DOWN if ((i & sp_DOWN) == 0) { #endif // Any scripts to run in this screen? script = f_scripts [n_pant]; run_script (); } #endif #ifdef PLAYER_AUTO_CHANGE_SCREEN if (player.x == 0 && player.vx < 0) { n_pant --; draw_scr (n_pant); player.x = 14336; } if (player.x == 14336 && player.vx > 0) { n_pant ++; draw_scr (n_pant); player.x = 0; } #else if (player.x == 0 && ((i & sp_LEFT) == 0)) { n_pant --; draw_scr (n_pant); player.x = 14336; } if (player.x == 14336 && ((i & sp_RIGHT) == 0)) { // 14336 = 224 * 64 n_pant ++; draw_scr (n_pant); player.x = 0; } #endif if (player.y == 0 && player.vy < 0 && n_pant >= MAP_W) { n_pant -= MAP_W; draw_scr (n_pant); player.y = 9216; } if (player.y == 9216 && player.vy > 0) { // 9216 = 144 * 64 if (n_pant < MAP_W * MAP_H - MAP_W) { n_pant += MAP_W; draw_scr (n_pant); player.y = 0; if (player.vy > 256) player.vy = 256; } else { player.vy = -PLAYER_MAX_VY_CAYENDO; if (player.life > 0) { peta_el_beeper (4); player.life --; } } } // Win game condition #ifdef ACTIVATE_SCRIPTING if (player.objs == PLAYER_NUM_OBJETOS || script_result == 1) { #else if (player.objs == PLAYER_NUM_OBJETOS) { #endif success = 0; if (n_pant == pant_final) { if ((player.x >> 10) == PLAYER_FIN_X && (player.y >> 10) == PLAYER_FIN_Y) success = 1; } else if (pant_final == 99) { success = 1; } if (success) { cortina (); game_ending (); playing = 0; cortina (); } } // Game over condition #ifdef ACTIVATE_SCRIPTING if (player.life == 0 || script_result == 2) { #else if (player.life == 0) { #endif // Saca a todo el mundo de aqu! sp_MoveSprAbs (sp_player, spritesClip, 0, VIEWPORT_Y + 30, VIEWPORT_X + 20, 0, 0); for (i = 0; i < 3; i ++) { if (malotes [enoffs + i].t != 0) sp_MoveSprAbs (sp_moviles [i], spritesClip, 0, VIEWPORT_Y + 30, VIEWPORT_X + 20, 0, 0); } game_over (); playing = 0; cortina (); } } } }
0
0.724501
1
0.724501
game-dev
MEDIA
0.977873
game-dev
0.94826
1
0.94826
ProjectIgnis/CardScripts
2,861
official/c43202238.lua
--邪竜星-ガイザー --Yazi, Evil of the Yang Zing local s,id=GetID() function s.initial_effect(c) --synchro summon Synchro.AddProcedure(c,nil,1,1,Synchro.NonTuner(nil),1,99) c:EnableReviveLimit() --cannot target local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e1:SetValue(aux.tgoval) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,0)) e2:SetCategory(CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCountLimit(1,id) e2:SetTarget(s.destg) e2:SetOperation(s.desop) c:RegisterEffect(e2) --spsummon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,1)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_TO_GRAVE) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e3:SetCountLimit(1,{id,1}) e3:SetCondition(s.spcon) e3:SetTarget(s.sptg) e3:SetOperation(s.spop) c:RegisterEffect(e3) end s.listed_series={SET_YANG_ZING} function s.desfilter(c) return c:IsFaceup() and c:IsSetCard(SET_YANG_ZING) end function s.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return false end if chk==0 then return Duel.IsExistingTarget(s.desfilter,tp,LOCATION_MZONE,0,1,nil) and Duel.IsExistingTarget(aux.TRUE,tp,0,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g1=Duel.SelectTarget(tp,s.desfilter,tp,LOCATION_MZONE,0,1,1,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g2=Duel.SelectTarget(tp,aux.TRUE,tp,0,LOCATION_ONFIELD,1,1,nil) g1:Merge(g2) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g1,2,0,0) end function s.desop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local tg=g:Filter(Card.IsRelateToEffect,nil,e) if #tg>0 then Duel.Destroy(tg,REASON_EFFECT) end end function s.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsReason(REASON_DESTROY) and c:IsPreviousControler(tp) and c:IsPreviousLocation(LOCATION_ONFIELD) end function s.spfilter(c,e,tp) return c:IsRace(RACE_WYRM) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function s.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if #g>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end end
0
0.90817
1
0.90817
game-dev
MEDIA
0.988236
game-dev
0.951336
1
0.951336
Genius-x/genius-x
5,522
cocos2d/cocos/editor-support/cocostudio/CCTween.h
/**************************************************************************** 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. ****************************************************************************/ #ifndef __CCTWEEN_H__ #define __CCTWEEN_H__ #include "cocostudio/CCProcessBase.h" #include "2d/CCTweenFunction.h" namespace cocostudio { class Bone; class ArmatureAnimation; using cocos2d::tweenfunc::TweenType; /** * @js NA * @lua NA */ class Tween : public ProcessBase { public: /** * Create with a Bone * @param bone the Bone Tween will bind to */ static Tween *create(Bone *bone); public: Tween(void); virtual ~Tween(void); /** * Init with a Bone * @param bone the Bone Tween will bind to */ virtual bool init(Bone *bone); using ProcessBase::play; /** * Start the Process * * @param movementBoneData the MovementBoneData include all FrameData * @param durationTo the number of frames changing to this animation needs. * @param durationTween the number of frames this animation actual last. * * @param loop whether the animation is loop * * loop < 0 : use the value from MovementData get from Action Editor * loop = 0 : this animation is not loop * loop > 0 : this animation is loop * * @param tweenEasing tween easing is used for calculate easing effect * * TWEEN_EASING_MAX : use the value from MovementData get from Action Editor * -1 : fade out * 0 : line * 1 : fade in * 2 : fade in and out * */ virtual void play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing); inline void setAnimation(ArmatureAnimation *animation) { _animation = animation; } inline ArmatureAnimation *getAnimation() const { return _animation; } virtual void gotoAndPlay(int frameIndex); virtual void gotoAndPause(int frameIndex); virtual void setMovementBoneData(MovementBoneData *data) { _movementBoneData = data; } virtual const MovementBoneData *getMovementBoneData() const { return _movementBoneData; } protected: /** * Update(float dt) will call this handler, you can handle your logic here */ virtual void updateHandler(); /** * Calculate which frame arrived, and if current frame have event, then call the event listener */ virtual float updateFrameData(float currentPercent); /** * Calculate the between value of _from and _to, and give it to between frame data */ virtual void setBetween(FrameData *from, FrameData *to, bool limit = true); /** * According to the percent to calculate current FrameData with tween effect */ virtual FrameData *tweenNodeTo(float percent, FrameData *node = nullptr); /** * According to the percent to calculate current color with tween effect */ virtual void tweenColorTo(float percent, FrameData *node); /** * Update display index and process the key frame event when arrived a key frame */ virtual void arriveKeyFrame(FrameData *keyFrameData); protected: //! A weak reference to the current MovementBoneData. The data is in the data pool MovementBoneData *_movementBoneData; FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData FrameData *_from; //! From frame data, used for calculate between value FrameData *_to; //! To frame data, used for calculate between value FrameData *_between; //! Between frame data, used for calculate current FrameData(m_pNode) value Bone *_bone; //! A weak reference to the Bone TweenType _frameTweenEasing; //! Dedermine which tween effect current frame use int _betweenDuration; //! Current key frame will last _betweenDuration frames int _totalDuration; int _fromIndex; //! The current frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex int _toIndex; //! The next frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex ArmatureAnimation *_animation; bool _passLastFrame; //! If current frame index is more than the last frame's index }; } #endif /*__CCTWEEN_H__*/
0
0.924777
1
0.924777
game-dev
MEDIA
0.740281
game-dev
0.713676
1
0.713676
tbamud/tbamud
6,791
src/mud_event.c
/************************************************************************** * File: mud_event.c Part of tbaMUD * * Usage: Handling of the mud event system * * * * By Vatiken. Copyright 2012 by Joseph Arnusch * **************************************************************************/ #include "conf.h" #include "sysdep.h" #include "structs.h" #include "utils.h" #include "db.h" #include "dg_event.h" #include "constants.h" #include "comm.h" /* For access to the game pulse */ #include "mud_event.h" /* Global List */ struct list_data * world_events = NULL; /* The mud_event_index[] is merely a tool for organizing events, and giving * them a "const char *" name to help in potential debugging */ struct mud_event_list mud_event_index[] = { { "Null" , NULL , -1 }, /* eNULL */ { "Protocol" , get_protocols , EVENT_DESC }, /* ePROTOCOLS */ { "Whirlwind" , event_whirlwind, EVENT_CHAR }, /* eWHIRLWIND */ { "Spell:Darkness",event_countdown, EVENT_ROOM } /* eSPL_DARKNESS */ }; /* init_events() is the ideal function for starting global events. This * might be the case if you were to move the contents of heartbeat() into * the event system */ void init_events(void) { /* Allocate Event List */ world_events = create_list(); } /* event_countdown() is used for events which are to be used as a countdown... * go figure eh? This could be useful for skills which have an extended cooldown, * like "lay on hands" once every 24 hours. Simply add an event to the * mud_event_index[] such as: * { "Lay on hands" , event_countdown, EVENT_CHAR } * and then add the event after a successful skill call: * NEW_EVENT(eLAYONHANDS, ch, NULL, 24 * SECS_PER_MUD_HOUR) * and then add something like this is your skill function: * if (char_has_mud_event(ch, eLAYONHANDS)) { * send_to_char(ch, "You must wait a full 24 hours before re-using this skill.\r\n"); * return; * } * The bottom switch() is for any post-event actions, like telling the character they can * now access their skill again. */ EVENTFUNC(event_countdown) { struct mud_event_data * pMudEvent; struct room_data * room = NULL; room_rnum rnum = NOWHERE; pMudEvent = (struct mud_event_data * ) event_obj; switch (mud_event_index[pMudEvent->iId].iEvent_Type) { case EVENT_CHAR: break; case EVENT_ROOM: room = (struct room_data * ) pMudEvent->pStruct; rnum = real_room(room->number); break; default: break; } switch (pMudEvent->iId) { case eSPL_DARKNESS: REMOVE_BIT_AR(ROOM_FLAGS(rnum), ROOM_DARK); send_to_room(rnum, "The dark shroud disappates.\r\n"); break; case ePROTOCOLS: break; case eWHIRLWIND: break; case eNULL: break; } return 0; } /* As of 3.63, there are only global, descriptor, and character events. This * is due to the potential scope of the necessary debugging if events were * included with rooms, objects, spells or any other structure type. Adding * events to these other systems should be just as easy as adding the current * library was, and should be available in a future release. - Vat */ void attach_mud_event(struct mud_event_data *pMudEvent, long time) { struct event * pEvent; struct descriptor_data * d; struct char_data * ch; struct room_data * room; pEvent = event_create(mud_event_index[pMudEvent->iId].func, pMudEvent, time); pEvent->isMudEvent = TRUE; pMudEvent->pEvent = pEvent; switch (mud_event_index[pMudEvent->iId].iEvent_Type) { case EVENT_WORLD: add_to_list(pEvent, world_events); break; case EVENT_DESC: d = (struct descriptor_data *) pMudEvent->pStruct; add_to_list(pEvent, d->events); break; case EVENT_CHAR: ch = (struct char_data *) pMudEvent->pStruct; if (ch->events == NULL) ch->events = create_list(); add_to_list(pEvent, ch->events); break; case EVENT_ROOM: room = (struct room_data *) pMudEvent->pStruct; if (room->events == NULL) room->events = create_list(); add_to_list(pEvent, room->events); break; } } struct mud_event_data *new_mud_event(event_id iId, void *pStruct, char *sVariables) { struct mud_event_data *pMudEvent; char *varString; CREATE(pMudEvent, struct mud_event_data, 1); varString = (sVariables != NULL) ? strdup(sVariables) : NULL; pMudEvent->iId = iId; pMudEvent->pStruct = pStruct; pMudEvent->sVariables = varString; pMudEvent->pEvent = NULL; return (pMudEvent); } void free_mud_event(struct mud_event_data *pMudEvent) { struct descriptor_data * d; struct char_data * ch; struct room_data * room; switch (mud_event_index[pMudEvent->iId].iEvent_Type) { case EVENT_WORLD: remove_from_list(pMudEvent->pEvent, world_events); break; case EVENT_DESC: d = (struct descriptor_data *) pMudEvent->pStruct; remove_from_list(pMudEvent->pEvent, d->events); break; case EVENT_CHAR: ch = (struct char_data *) pMudEvent->pStruct; remove_from_list(pMudEvent->pEvent, ch->events); if (ch->events->iSize == 0) { free_list(ch->events); ch->events = NULL; } break; case EVENT_ROOM: room = (struct room_data *) pMudEvent->pStruct; remove_from_list(pMudEvent->pEvent, room->events); if (room->events && (room->events->iSize == 0)) { free_list(room->events); room->events = NULL; } break; } if (pMudEvent->sVariables != NULL) free(pMudEvent->sVariables); pMudEvent->pEvent->event_obj = NULL; free(pMudEvent); } struct mud_event_data * char_has_mud_event(struct char_data * ch, event_id iId) { struct event * pEvent; struct mud_event_data * pMudEvent = NULL; bool found = FALSE; if (ch->events == NULL) return NULL; if (ch->events->iSize == 0) return NULL; clear_simple_list(); while ((pEvent = (struct event *) simple_list(ch->events)) != NULL) { if (!pEvent->isMudEvent) continue; pMudEvent = (struct mud_event_data * ) pEvent->event_obj; if (pMudEvent->iId == iId) { found = TRUE; break; } } if (found) return (pMudEvent); return NULL; } void clear_char_event_list(struct char_data * ch) { struct event * pEvent; if (ch->events == NULL) return; if (ch->events->iSize == 0) return; clear_simple_list(); while ((pEvent = (struct event *) simple_list(ch->events)) != NULL) { event_cancel(pEvent); } }
0
0.959038
1
0.959038
game-dev
MEDIA
0.594415
game-dev
0.836043
1
0.836043
Team-RTG/Realistic-Terrain-Generation
5,611
src/main/java/rtg/world/biome/realistic/vanilla/RealisticBiomeVanillaTaigaHills.java
package rtg.world.biome.realistic.vanilla; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockDirt.DirtType; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import rtg.api.config.BiomeConfig; import rtg.api.util.BlockUtil; import rtg.api.util.noise.SimplexNoise; import rtg.api.world.RTGWorld; import rtg.api.world.deco.collection.DecoCollectionTaiga; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; import rtg.api.world.biome.RealisticBiomeBase; public class RealisticBiomeVanillaTaigaHills extends RealisticBiomeBase { public static Biome biome = Biomes.TAIGA_HILLS; public static Biome river = Biomes.RIVER; public RealisticBiomeVanillaTaigaHills() { super(biome, BeachType.STONE); } @Override public void initConfig() { this.getConfig().ALLOW_SCENIC_LAKES.set(false); this.getConfig().addProperty(this.getConfig().ALLOW_LOGS).set(true); this.getConfig().addProperty(this.getConfig().FALLEN_LOG_DENSITY_MULTIPLIER); this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK).set(""); } @Override public TerrainBase initTerrain() { return new TerrainVanillaTaigaHills(); } @Override public SurfaceBase initSurface() { return new SurfaceVanillaTaigaHills(getConfig(), biome.topBlock, biome.fillerBlock); } @Override public void initDecos() { this.addDecoCollection(new DecoCollectionTaiga(this.getConfig(), 10f)); } public boolean allowVanillaTrees() {return false;} public static class TerrainVanillaTaigaHills extends TerrainBase { private float hillStrength = 30f; public TerrainVanillaTaigaHills() { this(72f, 30f); } public TerrainVanillaTaigaHills(float bh, float hs) { base = bh; hillStrength = hs; } @Override public float generateNoise(RTGWorld rtgWorld, int x, int y, float border, float river) { return terrainHighland(x, y, rtgWorld, river, 10f, 68f, hillStrength, base - 62f); } } public static class SurfaceVanillaTaigaHills extends SurfaceBase { private IBlockState mixBlock; public SurfaceVanillaTaigaHills(BiomeConfig config, IBlockState top, IBlockState fill) { super(config, top, fill); mixBlock = this.getConfigBlock(config.SURFACE_MIX_BLOCK.get(), BlockUtil.getStateDirt(DirtType.PODZOL)); } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, RTGWorld rtgWorld, float[] noise, float river, Biome[] base) { Random rand = rtgWorld.rand(); SimplexNoise simplex = rtgWorld.simplexInstance(0); float p = simplex.noise2f(i / 8f, j / 8f) * 0.5f; float c = TerrainBase.calcCliff(x, z, noise, river); int cliff = 0; Block b; for (int k = 255; k > -1; k--) { b = primer.getBlockState(x, k, z).getBlock(); if (b == Blocks.AIR) { depth = -1; } else if (b == Blocks.STONE) { depth++; if (depth == 0) { if (c > 0.45f && c > 1.5f - ((k - 60f) / 65f) + p) { cliff = 1; } if (c > 1.5f) { cliff = 2; } if (k > 110 + (p * 4) && c < 0.3f + ((k - 100f) / 50f) + p) { cliff = 3; } if (cliff == 1) { if (rand.nextInt(3) == 0) { primer.setBlockState(x, k, z, hcCobble()); } else { primer.setBlockState(x, k, z, hcStone()); } } else if (cliff == 2) { primer.setBlockState(x, k, z, getShadowStoneBlock()); } else if (cliff == 3) { primer.setBlockState(x, k, z, Blocks.SNOW.getDefaultState()); } else if (simplex.noise2f(i / 50f, j / 50f) + p * 0.6f > 0.24f) { primer.setBlockState(x, k, z, mixBlock); } else { primer.setBlockState(x, k, z, Blocks.GRASS.getDefaultState()); } } else if (depth < 6) { if (cliff == 1) { primer.setBlockState(x, k, z, hcStone()); } else if (cliff == 2) { primer.setBlockState(x, k, z, getShadowStoneBlock()); } else if (cliff == 3) { primer.setBlockState(x, k, z, Blocks.SNOW.getDefaultState()); } else { primer.setBlockState(x, k, z, Blocks.DIRT.getDefaultState()); } } } } } } }
0
0.933572
1
0.933572
game-dev
MEDIA
0.921528
game-dev
0.978539
1
0.978539
alexhagiopol/cracking-the-coding-interview
1,929
cpp_solutions/chapter_16_moderate/problem_16_04_ticTacWin.h
/* PROBLEM: * Design an algorithm to figure out if someone has won a game of tic-tac-toe. * * SOLUTION: * 1. An algorithm to check if a TTT board is a winning board. Check all rows, all cols, and both diagonals for equality. * 2. An algorithm to store the wiining-ness of all possible TTT boards in a hash map. Generate every possible TTT board * using a recursion tree that assigns one of three possible cell states (blank, X, or O) to one of 9 cells at each level * of the recursion. * 3. A class that populates the hash map in (2) upon construction and only queries the hash map when * asked to determine if a TTT board is a winning board. * * SPACE / TIME: * If we assume that there will be N calls to determine if a TTT board is a winning board, each call will require O(1) * time and O(1) space will be required to store the hash table. * */ #pragma once #include <unordered_map> namespace chapter_16 { class TTTDatabase { private: /* * A TTT board has 9 positions with 3 possible values at each position: * blank, X, or O. Thus, all possible TTT boards can be represented by * 3^9 = 19683 hash values. Thus we only need to store true or false * for 19683 different numbers which fits in a uint16_t whose max value is * 2^16 - 1 = 65536 - 1 = 65535. The range of the key integers is 0 - 19682. */ std::unordered_map<uint16_t, bool> database; const uint16_t boardLength = 9; uint16_t board2Hash(const char* board) const; bool winsLookup(const char* board) const; uint8_t linearIndex(uint8_t R, uint8_t C) const; bool wins(const char* board) const; void updateDB(const char* board); void permuteAndCheckBoard(char* board, uint8_t index); void buildDB(); public: TTTDatabase(); bool ticTacWin(const char* board); }; } // namespace chapter_16
0
0.772323
1
0.772323
game-dev
MEDIA
0.499806
game-dev
0.675572
1
0.675572
google/google-ctf
6,171
2022/hackceler8/game/menus/menu.py
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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. from arcade import gui from typing import Iterable, Optional from pyglet.event import EventDispatcher class BorderedMenu(gui.UIBoxLayout): """A widget that surrounds another widget in an aesthetic box.""" def __init__(self, game, child: Optional[gui.widgets.UIWidget] = None, tileset=None, tileset_start=0, x: float = 0, y: float = 0, **kwargs): super().__init__(x=x, y=y, vertical=False, align='center', children=(), **kwargs) tileset = tileset or game.find_tileset("window-border") topleft = game.make_texture(tileset.tiles[tileset_start]) top = game.make_texture(tileset.tiles[tileset_start + 1]) topright = game.make_texture(tileset.tiles[tileset_start + 2]) left = game.make_texture(tileset.tiles[tileset_start + 3]) center = game.make_texture(tileset.tiles[tileset_start + 4]) right = game.make_texture(tileset.tiles[tileset_start + 5]) bottomleft = game.make_texture(tileset.tiles[tileset_start + 6]) bottom = game.make_texture(tileset.tiles[tileset_start + 7]) bottomright = game.make_texture(tileset.tiles[tileset_start + 8]) self._bgwrapper = gui.UITexturePane(child=child or gui.UIWidget(width=32, height=32, tex=center), tex=center) self.child = self._bgwrapper.child leftcol = gui.UIBoxLayout(align="left") leftcol.add(gui.UITexturePane(child=gui.UIWidget(width=32, height=32), tex=topleft)) self.left_widget = gui.UIWidget(width=32, height=self._bgwrapper.height) leftcol.add(gui.UITexturePane(child=self.left_widget, tex=left)) leftcol.add(gui.UITexturePane(child=gui.UIWidget(width=32, height=32), tex=bottomleft)) centercol = gui.UIBoxLayout(align="center") self.top_widget = gui.UIWidget(width=self._bgwrapper.width, height=32) centercol.add(gui.UITexturePane(child=self.top_widget, tex=top)) centercol.add(self._bgwrapper) self.bottom_widget = gui.UIWidget(width=self._bgwrapper.width, height=32) centercol.add(gui.UITexturePane(child=self.bottom_widget, tex=bottom)) rightcol = gui.UIBoxLayout(align="right") rightcol.add(gui.UITexturePane(child=gui.UIWidget(width=32, height=32), tex=topright)) self.right_widget = gui.UIWidget(width=32, height=self._bgwrapper.height) rightcol.add(gui.UITexturePane(child=self.right_widget, tex=right)) rightcol.add(gui.UITexturePane(child=gui.UIWidget(width=32, height=32), tex=bottomright)) self.add(leftcol) self.add(centercol) self.add(rightcol) @property def child(self): return self._bgwrapper.child @child.setter def child(self, value): self._bgwrapper.child = value def do_layout(self): if self._bgwrapper.height != self.left_widget.height: self.left_widget.rect = self.left_widget.rect.resize(height=self._bgwrapper.height) self.right_widget.rect = self.right_widget.rect.resize(height=self._bgwrapper.height) if self._bgwrapper.width != self.top_widget.width: self.top_widget.rect = self.top_widget.rect.resize(width=self._bgwrapper.width) self.bottom_widget.rect = self.bottom_widget.rect.resize(width=self._bgwrapper.width) super().do_layout() class TextBox(gui.UIInputText): """A text entry box with a white background that offers an on_submit event (enter pressed).""" def __init__(self, game, x: float = 0, y: float = 0, width: float = 100, height: float = 50, text: str = "", font_name=('Arial',), font_size: float = 12, text_color = (0, 0, 0, 255), multiline=False, size_hint=None, size_hint_min=None, size_hint_max=None, style=None, **kwargs): super().__init__(x=x, y=y, width=width, height=height, text=text, font_name=font_name, font_size=font_size, text_color=text_color, multiline=multiline, size_hint=None, size_hint_min=None, size_hint_max=None, style=None, **kwargs) self._active = True self._old_insert_text = self.doc.insert_text self.doc.insert_text = self._insert_text self._tex = game.make_texture(game.find_tileset("white_square").tiles[0]) def _insert_text(self, start, text: str, attributes=None): submit = False if '\n' in text: submit = True text = text.replace("\n", "") if text: self._old_insert_text(start, text, attributes) if submit: self.dispatch_event("on_submit", self.text) def do_render(self, surface): self.prepare_render(surface) surface.draw_texture(0, 0, self.width, self.height, tex=self._tex) super().do_render(surface) TextBox.register_event_type("on_submit") def spinner(game, background=True, *args, **kwargs): if background: name = "spinner_bg" else: name = "spinner" return gui.UISpriteWidget(sprite = game.make_sprite(game.find_frameset(name)), *args, **kwargs) def wrap_menu_background(game, child, tileset=None, tileset_start=0): tileset = tileset or game.find_tileset("window-border") center = game.make_texture(tileset.tiles[tileset_start + 4]) return gui.UITexturePane(child=child, tex=center, width=child.width, height=child.height)
0
0.525833
1
0.525833
game-dev
MEDIA
0.941018
game-dev
0.816172
1
0.816172
quasilyte/roboden-game
5,387
src/scenes/staging/lava_puddle_node.go
package staging import ( "github.com/hajimehoshi/ebiten/v2" resource "github.com/quasilyte/ebitengine-resource" "github.com/quasilyte/ge" "github.com/quasilyte/gmath" "github.com/quasilyte/roboden-game/assets" "github.com/quasilyte/roboden-game/gamedata" ) type lavaPuddleNode struct { rect gmath.Rect centerPos gmath.Vec sprite *ge.Sprite fireDelay float64 attacker magmaDummyAttacker shaderTime float64 shaderTimeSpeed float64 numResourceSpawns int maxResourceSpawns int world *worldState } type magmaDummyAttacker struct { pos gmath.Vec } func (a *magmaDummyAttacker) IsDisposed() bool { return false } func (a *magmaDummyAttacker) GetHitboxRadius() float64 { return 0 } func (a *magmaDummyAttacker) GetPos() *gmath.Vec { return &a.pos } func (a *magmaDummyAttacker) GetVelocity() gmath.Vec { return gmath.Vec{} } func (a *magmaDummyAttacker) IsFlying() bool { return false } func (a *magmaDummyAttacker) OnDamage(gamedata.DamageValue, targetable) {} func (a *magmaDummyAttacker) GetTargetInfo() targetInfo { return targetInfo{} } func newLavaPuddleNode(world *worldState, rect gmath.Rect) *lavaPuddleNode { return &lavaPuddleNode{ rect: rect, world: world, centerPos: rect.Min.Add(gmath.Vec{X: rect.Width() * 0.5, Y: rect.Height() * 0.5}), } } func (lava *lavaPuddleNode) Init(scene *ge.Scene) { lava.sprite = ge.NewSprite(scene.Context()) lava.sprite.Centered = false lava.sprite.Pos.Base = &lava.rect.Min lava.fireDelay = lava.world.rand.FloatRange(30, 200) lava.maxResourceSpawns = lava.world.rand.IntRange(0, 3) if lava.world.graphicsSettings.AllShadersEnabled { lava.sprite.Shader = scene.NewShader(assets.ShaderLavaPuddle) lava.shaderTimeSpeed = 2.5 * lava.world.localRand.FloatRange(0.95, 1.1) lava.shaderTime = lava.world.localRand.FloatRange(545.7, 964.70) lava.sprite.Shader.SetFloatValue("Time", lava.shaderTime) lava.sprite.Shader.SetIntValue("Seed", lava.world.localRand.IntRange(0, 999)) } texture := ebiten.NewImage(int(lava.rect.Width()), int(lava.rect.Height())) lava.sprite.SetImage(resource.Image{Data: texture}) layerPicker := gmath.NewRandPicker[resource.ImageID](lava.world.localRand) for _, l := range lavaAtlas { layerPicker.AddOption(l.texture, l.weight) } for y := 0.0; y < lava.rect.Height(); y += 32.0 { for x := 0.0; x < lava.rect.Width(); x += 32.0 { tileImages := scene.LoadImage(layerPicker.Pick()) lava.drawTile(texture, tileImages, x, y) } } lava.world.stage.AddSpriteBelow(lava.sprite) } func (lava *lavaPuddleNode) drawTile(dst *ebiten.Image, texture resource.Image, x, y float64) { drawDirectionalTile(lava.world.localRand, dst, texture, lava.rect, x, y) } func (lava *lavaPuddleNode) IsDisposed() bool { return false } func (lava *lavaPuddleNode) Update(delta float64) { if !lava.sprite.Shader.IsNil() { lava.shaderTime += delta * lava.shaderTimeSpeed if lava.shaderTime > 999999999 { lava.shaderTime = lava.world.localRand.FloatRange(0, 9) } lava.sprite.Shader.SetFloatValue("Time", lava.shaderTime) } lava.fireDelay = gmath.ClampMin(lava.fireDelay-delta, 0) if lava.fireDelay != 0 { return } lava.fireDelay = lava.world.rand.FloatRange(10, 30) spawnPad := gmath.Vec{X: 20, Y: 20} spawnRect := gmath.Rect{ Min: lava.rect.Min.Add(spawnPad), Max: lava.rect.Max.Sub(spawnPad), } spawnPos := randomSectorPos(lava.world.rand, spawnRect) weapon := gamedata.MagmaHazardWeapon var target targetable var attackPos gmath.Vec if lava.world.rand.Chance(0.3) { lava.world.FindTargetableAgents(spawnPos, true, weapon.AttackRange, func(a *colonyAgentNode) bool { target = a attackPos = snipePos(weapon.ProjectileSpeed, spawnPos, a.pos, a.GetVelocity()) return true }) if target == nil { lava.world.WalkCreeps(spawnPos, weapon.AttackRange, func(creep *creepNode) bool { if creep.stats.Kind != gamedata.CreepCrawler { return false } if creep.pos.DistanceSquaredTo(spawnPos) > weapon.AttackRangeSqr { return false } target = creep attackPos = snipePos(weapon.ProjectileSpeed, spawnPos, creep.pos, creep.GetVelocity()) return true }) } } if target == nil { dist := lava.world.rand.FloatRange(80, weapon.AttackRange) attackPos = gmath.RadToVec(lava.world.rand.Rad()).Mulf(dist).Add(spawnPos) } lava.attacker.pos = spawnPos p := lava.world.newProjectileNode(projectileConfig{ World: lava.world, Weapon: weapon, Attacker: &lava.attacker, ToPos: attackPos, Target: target, }) p.trailCounter = 0.1 lava.world.nodeRunner.AddProjectile(p) createEffect(p.world, effectConfig{Pos: spawnPos, Image: assets.ImageFireBurst}) if target == nil && lava.numResourceSpawns < lava.maxResourceSpawns && lava.world.rand.Chance(0.3) { p.EventDetonated.Connect(nil, func(pos gmath.Vec) { if !posIsFree(lava.world, nil, attackPos, 20) { return } res := lava.world.NewEssenceSourceNode(magmaRockSource, pos) lava.world.nodeRunner.AddObject(res) lava.numResourceSpawns++ res.EventDestroyed.Connect(nil, func(*essenceSourceNode) { lava.numResourceSpawns-- }) }) } } func (lava *lavaPuddleNode) CollidesWith(pos gmath.Vec, r float64) bool { offset := gmath.Vec{X: r*0.5 + 12, Y: r*0.5 + 12} objectRect := gmath.Rect{ Min: pos.Sub(offset), Max: pos.Add(offset), } return lava.rect.Overlaps(objectRect) }
0
0.807013
1
0.807013
game-dev
MEDIA
0.984489
game-dev
0.856645
1
0.856645
newhoryzon/farmers-delight-fabric
9,710
src/main/java/com/nhoryzon/mc/farmersdelight/entity/block/SkilletBlockEntity.java
package com.nhoryzon.mc.farmersdelight.entity.block; import com.nhoryzon.mc.farmersdelight.FarmersDelightMod; import com.nhoryzon.mc.farmersdelight.block.SkilletBlock; import com.nhoryzon.mc.farmersdelight.entity.block.inventory.ItemStackInventory; import com.nhoryzon.mc.farmersdelight.mixin.accessors.RecipeManagerAccessorMixin; import com.nhoryzon.mc.farmersdelight.registry.BlockEntityTypesRegistry; import com.nhoryzon.mc.farmersdelight.registry.ParticleTypesRegistry; import com.nhoryzon.mc.farmersdelight.registry.SoundsRegistry; import com.nhoryzon.mc.farmersdelight.util.CompoundTagUtils; import net.minecraft.block.BlockState; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.Inventory; import net.minecraft.inventory.SimpleInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.listener.ClientPlayPacketListener; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket; import net.minecraft.particle.ParticleTypes; import net.minecraft.recipe.CampfireCookingRecipe; import net.minecraft.recipe.Recipe; import net.minecraft.recipe.RecipeType; import net.minecraft.sound.SoundCategory; import net.minecraft.util.Identifier; import net.minecraft.util.collection.DefaultedList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.random.Random; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; import java.util.Objects; import java.util.Optional; public class SkilletBlockEntity extends SyncedBlockEntity implements ItemStackInventory, HeatableBlockEntity { public static final String TAG_KEY_SKILLET_STACK = "Skillet"; private int cookTime; private int cookTimeTotal; private final DefaultedList<ItemStack> inventory; private Identifier lastRecipeID; private ItemStack skilletStack; private int fireAspectLevel; public SkilletBlockEntity(BlockPos blockPos, BlockState blockState) { super(BlockEntityTypesRegistry.SKILLET.get(), blockPos, blockState); skilletStack = ItemStack.EMPTY; inventory = DefaultedList.ofSize(1, ItemStack.EMPTY); } public static void cookingTick(World world, BlockPos pos, BlockState state, SkilletBlockEntity skillet) { boolean isHeated = skillet.isHeated(world, pos); if (isHeated) { ItemStack cookingStack = skillet.getStoredStack(); if (cookingStack.isEmpty()) { skillet.cookTime = 0; } else { skillet.cookAndOutputItems(cookingStack); } } else if (skillet.cookTime > 0 ) { skillet.cookTime = MathHelper.clamp(skillet.cookTime - 2, 0, skillet.cookTimeTotal); } } public static void animationTick(World world, BlockPos pos, BlockState state, SkilletBlockEntity skillet) { if (skillet.isHeated(world, pos) && skillet.hasStoredStack()) { Random random = world.getRandom(); if (random.nextFloat() < .2f) { double x = (double) pos.getX() + .5d + (random.nextDouble() * .4d - .2d); double y = (double) pos.getY() + .1d; double z = (double) pos.getZ() + .5d + (random.nextDouble() * .4d - .2d); double motionY = random.nextBoolean() ? .015d : .005d; world.addParticle(ParticleTypesRegistry.STEAM.get(), x, y, z, .0d, motionY, .0d); } if (skillet.fireAspectLevel > 0 && random.nextFloat() < skillet.fireAspectLevel * .05f) { double x = (double) pos.getX() + .5d + (random.nextDouble() * .4d - 0.2d); double y = (double) pos.getY() + .1d; double z = (double) pos.getZ() + .5d + (random.nextDouble() * .4d - 0.2d); double motionX = world.random.nextFloat() - .5f; double motionY = world.random.nextFloat() * .5f + .2f; double motionZ = world.random.nextFloat() - .5f; world.addParticle(ParticleTypes.ENCHANTED_HIT, x, y, z, motionX, motionY, motionZ); } } } private void cookAndOutputItems(ItemStack cookingStack) { if (world == null) { return; } ++cookTime; if (cookTime >= cookTimeTotal) { SimpleInventory wrapper = new SimpleInventory(cookingStack); Optional<CampfireCookingRecipe> recipe = getMatchingRecipe(wrapper); if (recipe.isPresent()) { ItemStack resultStack = recipe.get().craft(wrapper, world.getRegistryManager()); Direction direction = getCachedState().get(SkilletBlock.FACING).rotateYClockwise(); ItemEntity entity = new ItemEntity(world, pos.getX() + .5, pos.getY() + .3, pos.getZ() + .5, resultStack.copy()); entity.setVelocity(direction.getOffsetX() *.08f, .25f, direction.getOffsetZ() * .08f); world.spawnEntity(entity); cookTime = 0; removeStack(0, 1); } } } public boolean isCooking() { return isHeated() && hasStoredStack(); } public boolean isHeated() { if (world != null) { return isHeated(world, pos); } return false; } private Optional<CampfireCookingRecipe> getMatchingRecipe(Inventory inventory) { if (world == null) { return Optional.empty(); } if (lastRecipeID != null) { Recipe<Inventory> recipe = ((RecipeManagerAccessorMixin) world.getRecipeManager()) .getAllForType(RecipeType.CAMPFIRE_COOKING) .get(lastRecipeID); if (recipe instanceof CampfireCookingRecipe campfireRecipe && recipe.matches(inventory, world)) { return Optional.of(campfireRecipe); } } Optional<CampfireCookingRecipe> recipe = world.getRecipeManager().getFirstMatch(RecipeType.CAMPFIRE_COOKING, inventory, world); if (recipe.isPresent()) { lastRecipeID = recipe.get().getId(); return recipe; } return Optional.empty(); } @Override public DefaultedList<ItemStack> getItems() { return inventory; } @Override public void readNbt(NbtCompound nbt) { super.readNbt(nbt); fromTag(nbt); } private void fromTag(NbtCompound nbt) { readInventoryNbt(nbt); cookTime = nbt.getInt(CompoundTagUtils.TAG_KEY_COOK_TIME); cookTimeTotal = nbt.getInt(CompoundTagUtils.TAG_KEY_COOK_TIME_TOTAL); skilletStack = ItemStack.fromNbt(nbt.getCompound(TAG_KEY_SKILLET_STACK)); fireAspectLevel = EnchantmentHelper.getLevel(Enchantments.FIRE_ASPECT, skilletStack); } @Override protected void writeNbt(NbtCompound nbt) { super.writeNbt(nbt); writeInventoryNbt(nbt); nbt.putInt(CompoundTagUtils.TAG_KEY_COOK_TIME, cookTime); nbt.putInt(CompoundTagUtils.TAG_KEY_COOK_TIME_TOTAL, cookTimeTotal); nbt.put(TAG_KEY_SKILLET_STACK, skilletStack.writeNbt(new NbtCompound())); } @Nullable @Override public Packet<ClientPlayPacketListener> toUpdatePacket() { return BlockEntityUpdateS2CPacket.create(this); } @Override public NbtCompound toInitialChunkDataNbt() { NbtCompound nbtCompound = new NbtCompound(); writeNbt(nbtCompound); return nbtCompound; } public NbtCompound writeSkilletItem(NbtCompound nbt) { nbt.put(TAG_KEY_SKILLET_STACK, skilletStack.writeNbt(new NbtCompound())); return nbt; } public void setSkilletItem(ItemStack stack) { skilletStack = stack.copy(); fireAspectLevel = EnchantmentHelper.getLevel(Enchantments.FIRE_ASPECT, stack); inventoryChanged(); } public ItemStack addItemToCook(ItemStack addedStack, PlayerEntity player) { Optional<CampfireCookingRecipe> recipe = getMatchingRecipe(new SimpleInventory(addedStack)); if (recipe.isPresent()) { cookTimeTotal = SkilletBlock.getSkilletCookingTime(recipe.get().getCookTime(), fireAspectLevel); boolean wasEmpty = getStoredStack().isEmpty(); ItemStack remainderStack = insertStack(0, addedStack.copy(), false); if (!ItemStack.areEqual(remainderStack, addedStack)) { lastRecipeID = recipe.get().getId(); cookTime = 0; if (wasEmpty && world != null && isHeated(world, pos)) { world.playSound(null, pos.getX() + .5f, pos.getY() + .5f, pos.getZ() + .5f, SoundsRegistry.BLOCK_SKILLET_ADD_FOOD.get(), SoundCategory.BLOCKS, .8f, 1.f); } return remainderStack; } } else if (player != null) { player.sendMessage(FarmersDelightMod.i18n("block.skillet.invalid_item"), true); } return addedStack; } public ItemStack removeItem() { return removeStack(0, getStoredStack().getMaxCount()); } public ItemStack getStoredStack() { return getStack(0); } public boolean hasStoredStack() { return !getStoredStack().isEmpty(); } @Override public void inventoryChanged() { markDirty(); Objects.requireNonNull(world).updateListeners(getPos(), getCachedState(), getCachedState(), 3); } }
0
0.838571
1
0.838571
game-dev
MEDIA
0.998121
game-dev
0.968597
1
0.968597
garkimasera/rusted-ruins
5,314
common/src/saveload.rs
use crate::basic::SAVE_EXTENSION; use crate::gamedata::*; use crate::impl_filebox::MapLoadError; use crate::utils::to_writer_with_mode; use anyhow::Error; use serde_cbor::from_reader; use std::fs::{self, create_dir_all, File}; use std::io::{BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; #[cfg(feature = "global_state_obj")] impl GameData { /// Save game data to the specified directory pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { if cfg!(debug_assertions) { print_save_data_size(self); // Debug code for save file size optimization } let save_dir = path.as_ref(); // Create directory create_dir_all(save_dir)?; // Write id table file let mut file = BufWriter::new(File::create(save_dir.join("idtable"))?); writeln!(file, "{:016x}", *crate::gobj::OBJ_HOLDER_HASH)?; crate::gobj::get_objholder().write_table(&mut file)?; // Write metadata file let mut file = BufWriter::new(File::create(save_dir.join("metadata"))?); serde_json::to_writer_pretty(&mut file, &self.meta)?; // Write GameData let mut file = BufWriter::new(File::create(save_dir.join("gamedata"))?); to_writer_with_mode(&mut file, &self)?; // Write maps let map_dir = save_dir.join("maps"); create_dir_all(&map_dir)?; let mut error_occured = false; self.region.visit_all_maps(|mid, map| { trace!("Saving map {:?}", mid); match BoxedMap::write(map, &map_dir) { Ok(_) => (), Err(e) => { error!("{}", e); error_occured = true; } } }); if error_occured { anyhow::bail!("Map loading failed"); } Ok(()) } /// Load game data from specified directory pub fn load<P: AsRef<Path>>(path: P) -> Result<GameData, Error> { let save_dir = path.as_ref(); // Read metadata file let mut file = BufReader::new(File::open(save_dir.join("metadata"))?); let meta: MetaData = serde_json::from_reader(&mut file)?; // Read index conversion table let mut file = BufReader::new(File::open(save_dir.join("idtable"))?); let idx_conv_table = crate::idx_conv::IdxConvTable::read(&mut file, *crate::gobj::OBJ_HOLDER_HASH)?; let is_table_changed = idx_conv_table.is_some(); if is_table_changed { info!("Detected changes in the id table. Conversion table is created."); } crate::idx_conv::set_idx_conv_table(idx_conv_table); // Read GameData let mut file = BufReader::new(File::open(save_dir.join("gamedata"))?); let mut gamedata: GameData = from_reader(&mut file)?; gamedata.meta = meta; let map_dir = save_dir.join("maps"); if is_table_changed { // Preload is needed if id table is changed let mut mid_vec = Vec::new(); gamedata.region.visit_all_maps(|mid, map| { mid_vec.push(mid); }); for mid in &mid_vec { gamedata.region.preload_map_with_opts(*mid, &map_dir, true); } } else { // Preload current map let mid = gamedata.get_current_mapid(); gamedata.region.preload_map(mid, &map_dir); } Ok(gamedata) } pub fn clean_map_dir<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { let map_dir = path.as_ref().join("maps"); let mut map_files: Vec<PathBuf> = Vec::new(); for entry in fs::read_dir(&map_dir)? { let entry = entry?; let path = entry.path(); if path.is_file() { map_files.push(path); } } let mut map_file_path: Vec<PathBuf> = Vec::new(); self.region.visit_all_maps(|_mid, map| { map_file_path.push(map.path(map_dir.clone())); }); let n_exist_file = map_files.len(); map_files.retain(|p| !map_file_path.iter().any(|a| a == p)); if n_exist_file == map_files.len() { return Ok(()); } for p in &map_files { trace!("Remove unused map file {}", p.to_string_lossy()); fs::remove_file(p)?; } Ok(()) } pub fn save_dir<P: AsRef<Path>>(&self, path: P) -> PathBuf { path.as_ref() .join(format!("{}.{}", self.meta.save_name(), SAVE_EXTENSION)) } } /// Print save data size #[cfg(debug_assertions)] fn print_save_data_size(gd: &GameData) { use serde_cbor::ser::to_vec_packed; let v = to_vec_packed(&gd).unwrap(); println!("Total size = {}", v.len()); let v = to_vec_packed(&gd.region.0).unwrap(); println!("Regions size = {}", v.len()); let v = to_vec_packed(&gd.region.get(RegionId::default())).unwrap(); println!("Region size = {}", v.len()); let map = gd.get_current_map(); let v = to_vec_packed(&map).unwrap(); println!("Current map size = {}", v.len()); let v = to_vec_packed(&map.tile).unwrap(); println!("Current map tiles size = {}", v.len()); } #[cfg(not(debug_assertions))] fn print_save_data_size(_gd: &GameData) {}
0
0.950199
1
0.950199
game-dev
MEDIA
0.891399
game-dev
0.843059
1
0.843059
stride3d/stride-community-toolkit
2,070
examples/code-only/Example01_Basic3DScene_MeshLine/Program.cs
using Stride.CommunityToolkit.Bepu; using Stride.CommunityToolkit.Engine; using Stride.CommunityToolkit.Rendering.Gizmos; using Stride.CommunityToolkit.Rendering.ProceduralModels; using Stride.CommunityToolkit.Skyboxes; using Stride.Core.Mathematics; using Stride.Engine; using Stride.Graphics; using Stride.Rendering; using Buffer = Stride.Graphics.Buffer; using var game = new Game(); game.Run(start: Start); void Start(Scene rootScene) { game.SetupBase3DScene(); game.AddSkybox(); var lineEntity = CreateLineEntity(game); var entity1 = CreateSphereEntity(game); entity1.Transform.Position = new Vector3(0, 8, 0); entity1.AddChild(lineEntity); var entity2 = CreateSphereEntity(game); entity2.Transform.Position = new Vector3(-0.01f, 9, -0.01f); entity1.Scene = rootScene; entity2.Scene = rootScene; } static Entity CreateSphereEntity(Game game) => game.Create3DPrimitive(PrimitiveModelType.Sphere); static Entity CreateLineEntity(Game game) { // Create vertex buffer with start and end points var vertices = new Vector3[] { new(0, 0, 0), new(1, 1, -1) }; var vertexBuffer = Buffer.New(game.GraphicsDevice, vertices, BufferFlags.VertexBuffer); // Create index buffer var indices = new short[] { 0, 1 }; var indexBuffer = Buffer.New(game.GraphicsDevice, indices, BufferFlags.IndexBuffer); var material = GizmoEmissiveColorMaterial.Create(game.GraphicsDevice, Color.DarkMagenta); // Or use this for a specific color //var material = game.CreateMaterial(Color.DarkMagenta); var meshDraw = new MeshDraw { PrimitiveType = PrimitiveType.LineList, VertexBuffers = [new VertexBufferBinding(vertexBuffer, new VertexDeclaration(VertexElement.Position<Vector3>()), vertices.Length)], IndexBuffer = new IndexBufferBinding(indexBuffer, is32Bit: false, indices.Length), DrawCount = indices.Length }; var mesh = new Mesh { Draw = meshDraw }; var model = new Model { mesh, material }; return new Entity { new ModelComponent(model) }; }
0
0.736854
1
0.736854
game-dev
MEDIA
0.746716
game-dev,graphics-rendering
0.916316
1
0.916316
quiverteam/Engine
1,400
src/engine/iengine.h
//===== Copyright 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // // $Workfile: $ // $Date: $ // $NoKeywords: $ //===========================================================================// #if !defined( IENGINE_H ) #define IENGINE_H #ifdef _WIN32 #pragma once #endif #include "interface.h" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- abstract_class IEngine { public: enum { QUIT_NOTQUITTING = 0, QUIT_TODESKTOP, QUIT_RESTART }; // Engine State Flags enum EngineState_t { DLL_INACTIVE = 0, // no dll DLL_ACTIVE, // engine is focused DLL_CLOSE, // closing down dll DLL_RESTART, // engine is shutting down but will restart right away DLL_PAUSED, // engine is paused, can become active from this state }; virtual ~IEngine( void ) { } virtual bool Load( bool dedicated, const char *rootdir ) = 0; virtual void Unload( void ) = 0; virtual void SetNextState( EngineState_t iNextState ) = 0; virtual EngineState_t GetState( void ) = 0; virtual void Frame( void ) = 0; virtual float GetFrameTime( void ) = 0; virtual float GetCurTime( void ) = 0; virtual int GetQuitting( void ) = 0; virtual void SetQuitting( int quittype ) = 0; }; extern IEngine *eng; #endif // IENGINE_H
0
0.720358
1
0.720358
game-dev
MEDIA
0.922581
game-dev
0.605816
1
0.605816
mindustry-antigrief/mindustry-client
3,624
tests/src/test/java/power/PowerTestFixture.java
package power; import arc.*; import arc.mock.*; import arc.util.*; import mindustry.*; import mindustry.content.*; import mindustry.core.*; import mindustry.ctype.*; import mindustry.game.*; import mindustry.gen.*; import mindustry.world.*; import mindustry.world.blocks.power.*; import org.junit.jupiter.api.*; import static mindustry.Vars.*; /** * This class provides objects commonly used by power related unit tests. * For now, this is a helper with static methods, but this might change. * <p> * Note: All tests which subclass this will run with a fixed delta of 0.5! */ public class PowerTestFixture{ @BeforeAll static void initializeDependencies(){ headless = true; Core.files = new MockFiles(); Groups.init(); boolean make = content == null; if(make){ Vars.content = new ContentLoader(){ @Override public void handleMappableContent(MappableContent content){ } }; } Vars.state = new GameState(); Vars.tree = new FileTree(); if(make){ content.createBaseContent(); } Log.useColors = false; Time.setDeltaProvider(() -> 0.5f); } protected static PowerGenerator createFakeProducerBlock(float producedPower){ return new PowerGenerator("fakegen" + System.nanoTime()){{ buildType = () -> new GeneratorBuild(); powerProduction = producedPower; }}; } protected static Battery createFakeBattery(float capacity){ return new Battery("fakebattery" + System.nanoTime()){{ buildType = () -> new BatteryBuild(); consumePowerBuffered(capacity); }}; } protected static Block createFakeDirectConsumer(float powerPerTick){ return new PowerBlock("fakedirectconsumer" + System.nanoTime()){{ buildType = Building::create; consumePower(powerPerTick); }}; } /** * Creates a fake tile on the given location using the given block. * @param x The X coordinate. * @param y The y coordinate. * @param block The block on the tile. * @return The created tile or null in case of exceptions. */ protected static Tile createFakeTile(int x, int y, Block block){ try{ Tile tile = new Tile(x, y); //workaround since init() is not called for custom blocks if(block.consumers.length == 0){ block.init(); } // Using the Tile(int, int, byte, byte) constructor would require us to register any fake block or tile we create // Since this part shall not be part of the test and would require more work anyway, we manually set the block and floor // through reflections and then simulate part of what the changed() method does. Reflect.set(Tile.class, tile, "block", block); Reflect.set(Tile.class, tile, "floor", Blocks.sand); // Simulate the "changed" method. Calling it through reflections would require half the game to be initialized. tile.build = block.newBuilding().init(tile, Team.sharded, false, 0); if(block.hasPower){ new PowerGraph().add(tile.build); } // Assign incredibly high health so the block does not get destroyed on e.g. burning Blast Compound block.health = 100000; tile.build.health = 100000.0f; return tile; }catch(Exception ex){ throw new RuntimeException(ex); } } }
0
0.82034
1
0.82034
game-dev
MEDIA
0.944053
game-dev,testing-qa
0.917724
1
0.917724
3arthqu4ke/3arthh4ck
1,279
src/main/java/me/earth/earthhack/impl/modules/combat/legswitch/ListenerSound.java
package me.earth.earthhack.impl.modules.combat.legswitch; import me.earth.earthhack.api.util.interfaces.Globals; import me.earth.earthhack.impl.managers.minecraft.combat.util.SoundObserver; import me.earth.earthhack.impl.modules.combat.autocrystal.modes.ACRotate; import me.earth.earthhack.impl.modules.combat.legswitch.modes.LegAutoSwitch; import me.earth.earthhack.impl.util.minecraft.InventoryUtil; import net.minecraft.init.Items; import net.minecraft.network.play.server.SPacketSoundEffect; final class ListenerSound extends SoundObserver implements Globals { private final LegSwitch module; public ListenerSound(LegSwitch module) { super(module.soundRemove::getValue); this.module = module; } @Override public void onChange(SPacketSoundEffect value) { if (module.soundStart.getValue() && (InventoryUtil.isHolding(Items.END_CRYSTAL) || module.autoSwitch.getValue() != LegAutoSwitch.None) && (module.rotate.getValue() == ACRotate.None || module.rotate.getValue() == ACRotate.Break)) { module.startCalculation(); } } public boolean shouldBeNotified() { return module.soundStart.getValue(); } }
0
0.683054
1
0.683054
game-dev
MEDIA
0.897044
game-dev
0.521995
1
0.521995
anatawa12/AvatarOptimizer
13,917
Editor/Processors/TraceAndOptimize/FindUnusedObjectsProcessor.cs
using System; using System.Collections.Generic; using System.Linq; using nadena.dev.ndmf; using UnityEngine; namespace Anatawa12.AvatarOptimizer.Processors.TraceAndOptimizes { internal class FindUnusedObjects : TraceAndOptimizePass<FindUnusedObjects> { public override string DisplayName => "T&O: FindUnusedObjects"; protected override void Execute(BuildContext context, TraceAndOptimizeState state) { if (!state.RemoveUnusedObjects) return; var processor = new FindUnusedObjectsProcessor(context, state); processor.ProcessNew(); } } internal readonly struct FindUnusedObjectsProcessor { private readonly BuildContext _context; private readonly bool _noSweepComponents; private readonly bool _noConfigureMergeBone; private readonly bool _noActivenessAnimation; private readonly bool _skipRemoveUnusedSubMesh; public FindUnusedObjectsProcessor(BuildContext context, TraceAndOptimizeState state) { _context = context; _noSweepComponents = state.NoSweepComponents; _noConfigureMergeBone = state.NoConfigureMergeBone; _noActivenessAnimation = state.NoActivenessAnimation; _skipRemoveUnusedSubMesh = state.SkipRemoveUnusedSubMesh; } public void ProcessNew() { var componentInfos = _context.Extension<GCComponentInfoContext>(); var entrypointMap = DependantMap.CreateEntrypointsMap(_context); if (!_noSweepComponents) Sweep(componentInfos, entrypointMap); if (!_noConfigureMergeBone) MergeBone(componentInfos, entrypointMap); var behaviorMap = DependantMap.CreateDependantsMap(_context); if (!_noActivenessAnimation) ActivenessAnimation(componentInfos, behaviorMap); } private void ActivenessAnimation(GCComponentInfoContext componentInfos, DependantMap behaviorMap) { // entrypoint -> affected activeness animated components / GameObjects Dictionary<Component, HashSet<Component>> entryPointActiveness = new Dictionary<Component, HashSet<Component>>(); foreach (var componentInfo in componentInfos.AllInformation) { if (!componentInfo.Component) continue; // swept if (componentInfo.IsEntrypoint) continue; if (!componentInfo.HeavyBehaviourComponent) continue; if (_context.GetAnimationComponent(componentInfo.Component).ContainsAnimationForFloat(Props.EnabledFor(componentInfo.Component))) continue; // enabled is animated so we will not generate activeness animation HashSet<Component> resultSet; using (var enumerator = behaviorMap[componentInfo].Keys.GetEnumerator()) { Utils.Assert(enumerator.MoveNext()); resultSet = GetEntrypointActiveness(enumerator.Current!, _context); // resultSet.Count == 0 => no longer meaning if (enumerator.MoveNext() && resultSet.Count != 0) { resultSet = new HashSet<Component>(resultSet); do { var component = enumerator.Current; if (component == null) continue; if (component == componentInfo.Component) continue; var current = GetEntrypointActiveness(component, _context); resultSet.IntersectWith(current); } while (enumerator.MoveNext() && resultSet.Count != 0); } } if (resultSet.Count == 0) continue; // there are no common activeness animation resultSet.Remove(componentInfo.Component.transform); resultSet.ExceptWith(componentInfo.Component.transform.ParentEnumerable()); Component? commonActiveness; // TODO: we may use all activeness with nested identity transform // if activeness animation is not changed if (resultSet.Count == 0) { // the only activeness is parent of this component so adding animation is not required continue; } if (resultSet.Count == 1) { commonActiveness = resultSet.First(); } else { // TODO: currently this is using most-child component but I don't know is this the best. var nonTransform = resultSet.FirstOrDefault(x => !(x is Transform)); if (nonTransform != null) { // unlikely: deepest common activeness is the entrypoint component. commonActiveness = nonTransform; } else { // likely: deepest common activeness is parent commonActiveness = null; foreach (var component in resultSet) { var transform = (Transform)component; if (commonActiveness == null) commonActiveness = transform; else { // if commonActiveness is parent of transform, transform is children of commonActiveness if (transform.ParentEnumerable().Contains(commonActiveness)) commonActiveness = transform; } } Utils.Assert(commonActiveness != null); } } if (commonActiveness is Transform) { _context.Extension<ObjectMappingContext>().MappingBuilder! .RecordCopyProperty(commonActiveness.gameObject, Props.IsActive, componentInfo.Component, Props.EnabledFor(componentInfo.Component)); } else { _context.Extension<ObjectMappingContext>().MappingBuilder! .RecordCopyProperty(commonActiveness, Props.EnabledFor(commonActiveness), componentInfo.Component, Props.EnabledFor(componentInfo.Component)); } } return; HashSet<Component> GetEntrypointActiveness(Component entryPoint, BuildContext context) { if (entryPointActiveness.TryGetValue(entryPoint, out var found)) return found; var set = new HashSet<Component>(); if (context.GetAnimationComponent(entryPoint).ContainsAnimationForFloat(Props.EnabledFor(entryPoint))) set.Add(entryPoint); for (var transform = entryPoint.transform; transform != context.AvatarRootTransform; transform = transform.parent) if (context.GetAnimationComponent(transform.gameObject).ContainsAnimationForFloat(Props.IsActive)) set.Add(transform); entryPointActiveness.Add(entryPoint, set); return set; } } private void Sweep(GCComponentInfoContext componentInfos, DependantMap entrypointMap) { foreach (var componentInfo in componentInfos.AllInformation) { // null values are ignored if (!componentInfo.Component) continue; if (entrypointMap[componentInfo].Count == 0) { if (componentInfo.Component is Transform) { // Treat Transform Component as GameObject because they are two sides of the same coin DestroyTracker.DestroyImmediate(componentInfo.Component.gameObject); } else { DestroyWithDependencies(componentInfo.Component); } } } } private static void DestroyWithDependencies(Component component) { if (component == null) return; foreach (var dependantType in RequireComponentCache.GetDependantComponents(component.GetType())) foreach (var child in component.GetComponents(dependantType)) DestroyWithDependencies(child); DestroyTracker.DestroyImmediate(component); } private void MergeBone(GCComponentInfoContext componentInfos, DependantMap entrypointMap) { ConfigureRecursive(_context.AvatarRootTransform, _context); // returns (original mergedChildren, list of merged children if merged, and null if not merged) (bool, List<Transform>?) ConfigureRecursive(Transform transform, BuildContext context) { var mergedChildren = true; var afterChildren = new List<Transform>(); foreach (var child in transform.DirectChildrenEnumerable()) { var (newMergedChildren, newChildren) = ConfigureRecursive(child, context); if (newChildren == null) { mergedChildren = false; afterChildren.Add(child); } else { mergedChildren &= newMergedChildren; afterChildren.AddRange(newChildren); } } const GCComponentInfo.DependencyType AllowedUsages = GCComponentInfo.DependencyType.Bone | GCComponentInfo.DependencyType.Parent | GCComponentInfo.DependencyType.ComponentToTransform; // functions for make it easier to know meaning of result (bool, List<Transform>?) YesMerge() => (mergedChildren, afterChildren); (bool, List<Transform>?) NotMerged() => (mergedChildren, null); // Already Merged if (transform.TryGetComponent<MergeBone>(out _)) return YesMerge(); // Components must be Transform Only if (transform.GetComponents<Component>().Length != 1) return NotMerged(); // The bone cannot be used generally if ((entrypointMap.MergedUsages(componentInfos.GetInfo(transform)) & ~AllowedUsages) != 0) return NotMerged(); // must not be animated if (TransformAnimated(transform, context)) return NotMerged(); if (!mergedChildren) { if (GameObjectAnimated(transform, context)) return NotMerged(); var localScale = transform.localScale; var identityTransform = localScale == Vector3.one && transform.localPosition == Vector3.zero && transform.localRotation == Quaternion.identity; if (!identityTransform) { var childrenTransformAnimated = afterChildren.Any(x => TransformAnimated(x, context)); if (childrenTransformAnimated) // if this is not identity transform, animating children is not good return NotMerged(); if (!Utils.ScaledEvenly(localScale)) // non even scaling is not possible to reproduce in children return NotMerged(); } } if (!transform.gameObject.GetComponent<MergeBone>()) transform.gameObject.AddComponent<MergeBone>().avoidNameConflict = true; return YesMerge(); } bool TransformAnimated(Transform transform, BuildContext context) { var transformProperties = context.GetAnimationComponent(transform); // TODO: constant animation detection foreach (var transformProperty in TransformProperties) if (transformProperties.IsAnimatedFloat(transformProperty)) return true; return false; } bool GameObjectAnimated(Transform transform, BuildContext context) { var objectProperties = context.GetAnimationComponent(transform.gameObject); if (objectProperties.IsAnimatedFloat(Props.IsActive)) return true; return false; } } private static readonly string[] TransformProperties = { "m_LocalRotation.x", "m_LocalRotation.y", "m_LocalRotation.z", "m_LocalRotation.w", "m_LocalPosition.x", "m_LocalPosition.y", "m_LocalPosition.z", "m_LocalScale.x", "m_LocalScale.y", "m_LocalScale.z", // Animator Window won't create the following properties, but generated by some scripts and works in runtime "localRotation.x", "localRotation.y", "localRotation.z", "localRotation.w", "localPosition.x", "localPosition.y", "localPosition.z", "localScale.x", "localScale.y", "localScale.z", "localEulerAnglesRaw.x", "localEulerAnglesRaw.y", "localEulerAnglesRaw.z" }; } }
0
0.971627
1
0.971627
game-dev
MEDIA
0.948615
game-dev
0.975767
1
0.975767
KristalTeam/Kristal
10,465
data/actors/ralsei.lua
local actor, super = Class(Actor, "ralsei") function actor:init(style) super.init(self) local ralsei_style = style or Game:getConfig("ralseiStyle") if ralsei_style == 1 then self:initChapter1() else self:initChapter2() end end function actor:initChapter1() -- Display name (optional) self.name = "Ralsei" -- Width and height for this actor, used to determine its center self.width = 23 self.height = 43 -- Hitbox for this actor in the overworld (optional, uses width and height by default) self.hitbox = {2, 31, 19, 14} -- Color for this actor used in outline areas (optional, defaults to red) self.color = {0, 1, 0} -- Path to this actor's sprites (defaults to "") self.path = "party/ralsei/dark_ch1" -- This actor's default sprite or animation, relative to the path (defaults to "") self.default = "walk" -- Sound to play when this actor speaks (optional) self.voice = "ralsei" -- Path to this actor's portrait for dialogue (optional) self.portrait_path = "face/ralsei_hat" -- Offset position for this actor's portrait (optional) self.portrait_offset = {-15, -10} -- Whether this actor as a follower will blush when close to the player self.can_blush = true -- Table of sprite animations self.animations = { -- Battle animations ["battle/idle"] = {"battle/idle", 1/6, true}, ["battle/attack"] = {"battle/attack", 1/15, false}, ["battle/act"] = {"battle/act", 1/15, false}, ["battle/spell"] = {"battle/spell", 1/15, false, next="battle/idle"}, ["battle/item"] = {"battle/item", 1/12, false, next="battle/idle"}, ["battle/spare"] = {"battle/spell", 1/15, false, next="battle/idle"}, ["battle/attack_ready"] = {"battle/attackready", 0.2, true}, ["battle/act_ready"] = {"battle/actready", 0.2, true}, ["battle/spell_ready"] = {"battle/spellready", 0.2, true}, ["battle/item_ready"] = {"battle/itemready", 0.2, true}, ["battle/defend_ready"] = {"battle/defend", 1/15, false}, ["battle/act_end"] = {"battle/actend", 1/15, false, next="battle/idle"}, ["battle/hurt"] = {"battle/hurt", 1/15, false, temp=true, duration=0.5}, ["battle/defeat"] = {"battle/defeat", 1/15, false}, ["battle/swooned"] = {"battle/defeat", 1/15, false}, ["battle/transition"] = {"walk/right_1", 1/15, false}, ["battle/intro"] = {"battle/intro", 1/15, false}, ["battle/victory"] = {"battle/victory", 1/10, false}, -- Cutscene animations ["hood"] = {"hood", 0.25, true}, ["pullhat"] = {"pullhat", 0.25, true}, ["removehood"] = {"removehood", 0.25, false, next="walk/down"}, ["reveal"] = {"reveal", 0.3, false}, ["sing"] = {"sing", 0.4, true}, ["sit"] = {"sit", 0.1, false}, } -- Tables of sprites to change into in mirrors self.mirror_sprites = { ["walk/down"] = "walk/up", ["walk/up"] = "walk/down", ["walk/left"] = "walk/left", ["walk/right"] = "walk/right", ["walk_blush/down"] = "walk_blush/up", ["walk_blush/up"] = "walk_blush/down", ["walk_blush/left"] = "walk_blush/left", ["walk_blush/right"] = "walk_blush/right", ["walk_unhappy/down"] = "walk_unhappy/up", ["walk_unhappy/up"] = "walk_unhappy/down", ["walk_unhappy/left"] = "walk_unhappy/left", ["walk_unhappy/right"] = "walk_unhappy/right", } -- Table of sprite offsets (indexed by sprite name) self.offsets = { -- Movement offsets ["walk/down"] = {0, 0}, ["walk/left"] = {0, 0}, ["walk/right"] = {0, 0}, ["walk/up"] = {0, 0}, ["walk_blush/down"] = {0, 0}, ["walk_blush/left"] = {0, 0}, ["walk_blush/right"] = {0, 0}, ["walk_blush/up"] = {0, 0}, -- Battle offsets ["battle/idle"] = {-7, -2}, ["battle/attack"] = {-11, -3}, ["battle/attackready"] = {-11, -3}, ["battle/act"] = {-3, -2}, ["battle/actend"] = {-3, -2}, ["battle/actready"] = {-3, -2}, ["battle/spell"] = {-12, -2}, ["battle/spellready"] = {-12, -2}, ["battle/item"] = {-8, -10}, ["battle/itemready"] = {-8, -10}, ["battle/defend"] = {-3, -2}, ["battle/defeat"] = {-3, -2}, ["battle/hurt"] = {-13, -2}, -- does this exist? Bor's answer: yes, it does. ["battle/intro"] = {-3, -2}, ["battle/victory"] = {-3, -2}, -- Cutscene offsets ["hood"] = {-2, -1}, ["pullhat"] = {-1, -2}, ["removehood"] = {-2, -1}, ["reveal"] = {-2, -2}, ["sing"] = {-10, -2}, ["sit"] = {0, 0}, ["shock"] = {-17, -4}, ["fallen"] = {-8, 20} } end function actor:initChapter2() -- Display name (optional) self.name = "Ralsei" -- Width and height for this actor, used to determine its center self.width = 21 self.height = 40 -- Hitbox for this actor in the overworld (optional, uses width and height by default) self.hitbox = {1, 28, 19, 14} -- A table that defines where the Soul should be placed on this actor if they are a player. -- First value is x, second value is y. self.soul_offset = {10.5, 24} -- Color for this actor used in outline areas (optional, defaults to red) self.color = {0, 1, 0} -- Path to this actor's sprites (defaults to "") self.path = "party/ralsei/dark" -- This actor's default sprite or animation, relative to the path (defaults to "") self.default = "walk" -- Sound to play when this actor speaks (optional) self.voice = "ralsei" -- Path to this actor's portrait for dialogue (optional) self.portrait_path = "face/ralsei" -- Offset position for this actor's portrait (optional) self.portrait_offset = {-15, -10} -- Whether this actor as a follower will blush when close to the player self.can_blush = true -- Table of sprite animations self.animations = { -- Movement animations ["slide"] = {"slide", 4/30, true}, -- Battle animations ["battle/idle"] = {"battle/idle", 1/6, true}, ["battle/attack"] = {"battle/attack", 1/15, false}, ["battle/act"] = {"battle/act", 1/15, false}, ["battle/spell"] = {"battle/spell", 1/15, false, next="battle/idle"}, ["battle/item"] = {"battle/item", 1/12, false, next="battle/idle"}, ["battle/spare"] = {"battle/spell", 1/15, false, next="battle/idle"}, ["battle/attack_ready"] = {"battle/attackready", 0.2, true}, ["battle/act_ready"] = {"battle/actready", 0.2, true}, ["battle/spell_ready"] = {"battle/spellready", 0.2, true}, ["battle/item_ready"] = {"battle/itemready", 0.2, true}, ["battle/defend_ready"] = {"battle/defend", 1/15, false}, ["battle/act_end"] = {"battle/actend", 1/15, false, next="battle/idle"}, ["battle/hurt"] = {"battle/hurt", 1/15, false, temp=true, duration=0.5}, ["battle/defeat"] = {"battle/defeat", 1/15, false}, ["battle/swooned"] = {"battle/defeat", 1/15, false}, ["battle/transition"] = {"walk/right_1", 1/15, false}, ["battle/intro"] = {"battle/intro", 1/15, false}, ["battle/victory"] = {"battle/victory", 1/10, false}, -- Cutscene animations ["jump_fall"] = {"fall", 1/5, true}, ["jump_ball"] = {"ball", 1/15, true}, ["laugh"] = {"laugh", 4/30, true}, ["hug"] = {"hug", 2/9, false}, ["hug_stop"] = {"hug_stop", 2/9, false}, ["wave_start"] = {"wave_start", 5/30, false, next="wave_down"}, ["wave_down"] = {"wave_down", 5/30, true} } -- Tables of sprites to change into in mirrors self.mirror_sprites = { ["walk/down"] = "walk/up", ["walk/up"] = "walk/down", ["walk/left"] = "walk/left", ["walk/right"] = "walk/right", ["walk_unhappy/down"] = "walk_unhappy/up", ["walk_unhappy/up"] = "walk_unhappy/down", ["walk_unhappy/left"] = "walk_unhappy/left", ["walk_unhappy/right"] = "walk_unhappy/right", ["walk_blush/down"] = "walk_blush/up", ["walk_blush/up"] = "walk_blush/down", ["walk_blush/left"] = "walk_blush/left", ["walk_blush/right"] = "walk_blush/right", } -- Table of sprite offsets (indexed by sprite name) self.offsets = { -- Movement offsets ["walk/down"] = {0, 0}, ["walk/left"] = {0, 0}, ["walk/right"] = {0, 0}, ["walk/up"] = {0, 0}, ["walk_blush/down"] = {0, 0}, ["walk_blush/left"] = {0, 0}, ["walk_blush/right"] = {0, 0}, ["walk_blush/up"] = {0, 0}, ["walk_unhappy/down"] = {0, 0}, ["walk_unhappy/left"] = {0, 0}, ["walk_unhappy/right"] = {0, 0}, ["walk_unhappy/up"] = {0, 0}, ["slide"] = {-2, 2}, -- Battle offsets ["battle/idle"] = {-2, -6}, ["battle/attack"] = {-10, -6}, ["battle/attackready"] = {-10, -6}, ["battle/act"] = {-2, -6}, ["battle/actend"] = {-2, -6}, ["battle/actready"] = {-2, -6}, ["battle/spell"] = {-11, -6}, ["battle/spellready"] = {-11, -6}, ["battle/item"] = {-7, -14}, ["battle/itemready"] = {-7, -14}, ["battle/defend"] = {-2, -6}, ["battle/defeat"] = {-2, -6}, ["battle/hurt"] = {-13, -2}, ["battle/intro"] = {-2, -6}, ["battle/victory"] = {0, -6}, -- Cutscene offsets ["pose"] = {-1, -1}, ["fall"] = {-10, 0}, ["ball"] = {0, 9}, ["landed"] = {-2, 0}, ["hug"] = {0, 0}, ["hug_stop"] = {0, 0}, ["laugh"] = {-1, 0}, ["shocked_behind"] = {-9, 3}, ["surprised_down"] = {-5, -1}, ["wave_start"] = {0, 0}, ["wave_down"] = {2, 1}, ["splat"] = {-15, 21}, ["stool"] = {-11, 18} } end return actor
0
0.888545
1
0.888545
game-dev
MEDIA
0.880384
game-dev
0.977138
1
0.977138
MINIONBOTS/FFXIVMinion
272,582
ffxivminion/languages.lua
ffxiv_strings = { -- bk: EN ["en"] = { startStop = "StartStop", doPulse = "Pulse(Debug)", pulseTime = "Pulse Time (ms)", enableLog = "Enable Log", task = "Task", state = "State", effect = "Effect", autoStartBot = "AutoStartBot", combatMovement = "CombatMovement", enableRepair = "AutoRepair", ignoreMarkerLevels = "IgnoreMarkerLevels", ["Bot Status"] = "BotStatus", settings = "Settings", status = "Status", advancedSettings = "Advanced Settings", vendorSettings = "VendorSettings", gatherSettings = "GatherSettings", skipcutscene = "Skip Cutscenes", depositItems = "Deposit Items", checkChat = "Chat Alert", randomfarmspot = "Use Random Farmspots", disabledrawing = "Disable Rendering", killaggrononfateenemies = "Kill attacking None-Fate Enemies", avoidAOE = "Avoid AOE", -- mesher.lua meshManager = "MeshManager", activated = "Activated", noMeshLoad = "No Mesh Load", mapName = "Map", navmesh = "Navmesh", waypoint = "Waypoint", ["General"] = "General", ["Auto-Equip"] = "Auto-Equip", getWaypoint = "GetMeshWP", useInSwitcher = "UseInSwitcher", enableSwitcher = "EnableSwitcher", minSwitchTime = "MinSwitchTime", maxSwitchTime = "MaxSwitchTime", switchTimer = "TimeUntilSwitch", switcherSettings = "SwitcherSettings", showMesh = "Show Triangles ", showrealMesh = "Show NavMesh", newMeshName = "New Meshfile Name", newMesh = "Clear Navmesh", saveMesh = "Save NavMesh", buildNAVMesh = "Build NavMesh", editor = "Edit Mesh", recoder = "Record Mesh", connections = "Connections", enablePSwitch = "EnableParanoiaSwitch", pSwitchCount = "ParanoiaPlayerCount", maMarkerID = "ID", maMarkerName = "Name", -- skillmanager.lua skillbook = "SkillBook", skillManager = "SkillManager", skillEditor = "SkillEditor", skillEditor_craft = "SkillEditor_Crafting", skillEditor_gather = "SkillEditor_Gathering", saveProfile = "Save Profile", newProfileName = "New Profile", skillProfile = "Skill Profile", newProfile = "Create New Profile", clearProfile = "Clear Profile", skillbookrefresh = "Refresh Skills", targetType = "Target", stepmin = "Step >=", stepmax = "Step <", durabmin = "Durability >=", durabmax = "Durability <", progrmin = "Progress >=", progrmax = "Progress <", qualitymin = "Quality >=", qualitymax = "Quality <", condition = "Condition =", cpmin = "CP >=", cpmax = "CP <", gpmin = "GP >=", gpmax = "GP <", iqstack = "InnerQuiet Stack >=", notused = "NotUsed", excellent = "Excellent", good = "Good", normal = "Normal", poor = "Poor", centered = "Centered", sturdy = "Sturdy", pliant = "Pliant", primed = "Primed", malleable = "Malleable", nodeHas = "Has Item: ", gatherAttemptsMin = "Attempts Remaining >", gatherAttemptsMax = "Attempts Remaining <=", profile = "Profile", sMmode = "Attack Mode", sMtargetmode = "Target Mode", refreshProfiles = "Refresh Profile List", deleteProfile = "Delete Current Profile", autoetectSkills = "Autodetect Skills", refreshSkillList = "Clear & Refresh SkillList", skillEditor = "Skill Editor", enabled = "Enabled", appliesBuff = "Applies (De-)Buff", priority = "Priority", los = "Needs LineOfSight", instacast = "Instant Skill", channeled = "Channel Skill", cooldown = "Cooldown", minRange = "MinRange", maxRange = "MaxRange", isGroundTargeted = "Is GroundTargeted", useOutOfCombat = "Use out of Combat", playerMoving = "Player Moving", playerHPGT = "Player HP% >", playerHPLT = "Player HP% <", playerPowerGT = "Player MP >", playerPowerLT = "Player MP <", playerHas = "Player has Buff: like 13,4152,521", orPlayerHas = "or Player has ", playerHasNot = "Player has NOT Buff: like 13,4152,521", orPlayerCond = "Player has #Conditions >", orPlayerHasNot = "or Player has NOT ", targetMoving = "Target Moving", targetHPGT = "Target HP% >", targetHPLT = "Target HP% <", targetDistanceGT = "Target Distance >", targetDistanceLT = "Target Distance <", enemiesNearCount = "Enemies Near Target(Count) >=", enemiesNearRange = "Enemies Near Target(MaxRange) =", alliesNearCount = "Allies Near Target(Count) >=", alliesNearRange = "Allies Near Target(MaxRange) =", targetHas = "Target has Buff : like 13,4152,521", orTargetHas = "or Target has ", targetHasNot = "Target has NOT Buff : like 13,4152,521", orTargetHasNot = "or Target has NOT ", prevSkillID = "Previous Skill ID", AdvancedSettings = "Advanced Settings", Fightstyle = "Fightstyle", --new SKM stuff alias = "Alias", cdIsReady = "CD Is Ready", cdNotReady = "CD Not Ready", cdTimeLT = "CD Time <=", cdTimeGT = "CD Time >=", nextSkillPrio = "Next Skill Prio", skmTYPE = "Action Type", skmSTYPE = "Skill Type", skmCombat = "Combat Status", skmCHARGE = "Charge Skill", skmLevelMin = "Level >=", skmLevelMax = "Level <=", checkSkill = "Skill ID", isReady = "Is Ready", isNotReady = "Is Not Ready", cooldownRemainingLTE = "Cooldown Remaining <=", cooldownRemainingGTE = "Cooldown Remaining >=", skmNSkillID = "Next Skill ID", skmCBreak = "Combo Breaker", skmTRG = "Skill Target", skmTRGTYPE = "Target Role", skmNPC = "Include NPC", skmPTRG = "Player Target", skmPGTRG = "Ground Target", skmPPos = "Position", skmTHPCL = "Target HP >", skmTHPCB = "Target HP <", skmTCONTIDS = "Content ID(s)", skmTNCONTIDS = "Not Content ID(s)", skmTCASTID = "Cast ID(s)", skmTCASTTM = "Cast @ Me", skmTCASTTIME = "Cast Time >", skmPTPL = "Player TP >", skmPTPB = "Player TP <", skmPMPPL = "Player MP% >", skmPMPPB = "Player MP% <", skmPAGL = "Player Aggro % >", skmPAGB = "Player Aggro % <", skmMPLock = "Causes MP Lockout", skmMPLocked = "Lockout Affected", skmMPLockPer = "MP Lockout %", skmPTCount = "Member Count >=", skmPTHPL = "Party HP% >", skmPTHPB = "Party HP% <", skmPTMPL = "Party MP% >", skmPTMPB = "Party MP% <", skmPTTPL = "Party TP >", skmPTTPB = "Party TP <", skmHPRIOHP = "Priority HP % <", skmHPRIO1 = "Heal Priority 1", skmHPRIO2 = "Heal Priority 2", skmHPRIO3 = "Heal Priority 3", skmHPRIO4 = "Heal Priority 4", skmTECount = "Enemies >=", skmTECount2 = "Enemies <=", skmTERange = "Enemy Range", skmTELevel = "Level Difference", skmTACount = "Allies >=", skmTARange = "Ally Range", skmTBuffOwner = "Buff Owner", skmHasBuffs = "Has Buffs (1+2,3)", skmMissBuffs = "Missing Buffs (1+2,3)", skmOrBuffDura = "Or Buff Dura <=", skmAndBuffDura = "And Buff Dura >", skmUnspoiled = "Unspoiled Node", up = "UP", down = "DOWN", delete = "DELETE", copy = "COPY", paste = "PASTE", --sections skillDetails = "Skill Details", skillChecks = "Other Skill Checks", basicDetails = "Basic Details", playerHPMPTP = "Player HP/MP/TP", party = "Party", target = "Target", casting = "Casting", healPriority = "Heal Priority", aoe = "AOE", playerBuffs = "Player Buffs", targetBuffs = "Target Buffs", --ffxiv stuff specific stuff botMode = "Bot Mode", addGrindSpot = "Add Grind Marker", addFishingSpot = "Add Fishing Marker", addMiningSpot = "Add Mining Marker", addBotanySpot = "Add Botany Marker", addNavSpot = "Add Nav Marker", deleteSpot = "Delete Nearest Marker", markers = "Markers", markerLevel = "Marker Level", markerMinLevel = "Marker Min Level", markerMaxLevel = "Marker Max Level", selectedMarker = "Selected Marker", noMarker = "No Marker", mining = "Mining", fishing = "Fishing", botany = "Botany", gatherTime = "Marker Timer (s)", deleteMarker = "Delete Current Marker", recmesh = "Record Mesh", recAreaType = "Record Type", recAreaSize = "Record Size", changeMesh = "Change Mesh", changeAreaType = "Change Type", changeAreaSize = "Change Size", biDirOffMesh = "Bidirectional Offmeshconnection", addOffMeshSpot = "Add OffMeshConnection", delOffMeshSpot = "Del OffMeshConnection", typeOffMeshSpot = "Type OffMeshConnection", showPath = "Show Path", selectItem1 = "Item Priority 1", selectItem2 = "Item Priority 2", selectItem3 = "Item Priority 3", selectBait = "Select Bait", baitName = "Bait Name", markerName = "Marker Name", markerPos = "Marker Position", selectClosestMarker = "Select Closest Marker", moveToMarker = "Move To Marker", gatherManager = "GatherManager", selectMarker = "Select Marker", logCNE = "Log CNE Results", useMount = "Use Mount", useSprint = "Use Sprint", gatherGardening = "Gather Gardening", gatherChocoFood = "Gather Choco Food", nodeType = "Node Type", throttle = "Throttle", --********************************************** repair = "Repair", questHelpers = "Quest Helpers", mount = "Mount", companion = "Companion", stance = "Stance", stFollow = "Follow", stFree = "Free Stance", stDefender = "Defender Stance", stAttacker = "Attacker Stance", stHealer = "Healer Stance", --********************************************** mountDist = "Mount Distance: ", sprintDist = "Sprint Distance: ", randomPaths = "Randomize Paths", botEnabled = "Bot Enabled", grindMode = "Grind", huntMode = "Hunt", huntlogMode = "Hunting Log", fishMode = "Fish", gatherMode = "Gather", assistMode = "Assist", partyMode = "Party-Grind", craftMode = "Crafting", useStealth = "Use Stealth", randomizeMarkers = "Randomize Markers", teleport = "Teleport", permaSprint = "PermaSprint", avoidHP = "Avoid HP% ", restHP = "Rest HP%: ", restMP = "Rest MP%: ", fleeHP = "Flee HP%: ", fleeMP = "Flee MP%: ", doFates = "Do Fates", fatesOnly = "Fates Only", setEvacPoint = "SetEvacPoint", restInFates = "Rest In Fates", maxFateLevel = "MaxFateLvl: +", minFateLevel = "MinFateLvl: -", waitForComplete = "WaitForComplete%: ", blacklistTimer = "BlacklistTimer (s)", fateIndex = "FateIndex", fateName = "FateName", blacklistAdd = "BlacklistAdd", blacklistRem = "BlacklistRem", enableRadar = "Enable Radar", enable2DRadar = "Enable 2D Radar", enable3DRadar = "Enable 3D Radar", fullscreenRadar = "Fullscreen (2D)", showNodes = "Show Nodes", showPlayers = "Show Players", showBattleNPCs = "Show Battle NPCs", showEventNPCs = "Show Event NPCs", showEventObjects = "Show Event Objects", showAetherytes = "Show Aetherytes", xPos = "X Position", yPos = "Y Position", assist = "Targeting Assist", assistPriority = "Priority", -- new stuff (since last translation) useMooch = "Use Mooch", markerManager = "MarkerManager", prevSkillIDNot = "Previous Skill ID NOT", secsSinceLastCast = "Secs Since Last Cast", combatRangePercent = "Combat Range %: ", blacklistManager = "BlacklistManager", createMarker = "Create Marker", editMarkers = "Edit Markers", markerType = "Marker Type", editMarkerList = "Setup List", addMarker = "Add To List", editMarker = "Edit Marker", newMarker = "New Marker", markerList = "Marker List", markerTeam = "Marker Team", setupList = "Setup List", blacklistName = "Blacklist Name", blacklistEntry = "Blacklist Entry", entryTime = "Entry Time", deleteEntry = "Delete Entry", qualityminper = "Quality % >=", qualitymaxper = "Quality % <", blacklistTarget = "Blacklist Target", addEntry = "Add Entry", blacklistFate = "Blacklist Fate", notAttackable = "Invalid Target", targetName = "Target Name", monsters = "Monsters", fates = "Fates", --************************************************* toggleOnOff = "Toggle On/Off", multiManager = "Multibot Manager", multiChannel = "Channel", multiServer = "Server IP", multiPort = "Port #", multiPass = "Password", serverInfo = "Server Information", --************************************************* huntMonsters = "Hunted Monsters", hunt = "Hunt", doAtma = "Do Atma", prioritizeClaims = "Prioritize Claims", claimRange = "Claim Range", attackClaimed = "Attack Claimed", alwaysKillAggro = "Always Kill Aggro", fateTeleportPercent = "Teleport %", --*************************************************** startCombat = "Start Combat", onlySolo = "Only solo", onlyParty = "Only in party", alliesNearHPLT = "Allies HP% <", --new pvpMode = "PVP", pve = "PVE", both = "Both", pvpTargetType = "PVP Target Type", healer = "Healer", dps = "DPS", tank = "Tank", any = "Any", none = "None", meleeDPS = "Melee DPS", caster = "Caster", ranged = "Ranged", nearDead = "Near Dead", sleeper = "Sleeper", unattendedHealer = "Unattended Healer", prioritizeRanged = "Prioritize Ranged", combatType = "Combat Type", nearest = "Nearest", lowestHealth = "Lowest Health", highestHealth = "Highest Health", tankAssist = "Tank Assist", pvpTargetOne = "Priority 1", pvpTargetTwo = "Priority 2", pvpTargetThree = "Priority 3", pvpTargetFour = "Priority 4", pvpTargetFive = "Priority 5", pvpAvoid = "Avoidance", pvpSpeedMatchPartner = "Speed Match Partner", pvpArena = "PVP Arena", gatherMaps = "Gather Maps", markerFields = "Marker Fields", confirmDuty = "Auto-Confirm Duty", antiAFKMove = "Anti-AFK Move", pvpFlee = "Ranged Flee", skipCutscene = "Skip Cutscenes", skipDialogue = "Skip Dialogues", doUnstuck = "Enable Unstuck", delayLeave = "Delay Leave", defaultProfile = "Default Profile", useHQMats = "Craft HQ Mats", enterDutyTimer = "Enter Timer: ", leaveDutyTimer = "Leave Timer: ", dutyMode = "Duty", dutyLeader = "Duty Leader: ", clickToTeleport = "Click To Teleport", clickToTravel = "Click To Travel", questRunProfile = "RunQuests", questManager = "QuestManager", quests = "Quests", questEditor = "Quest Editor", questDone = "Quest Done", questInfo = "Quest Information", questSteps = "Steps", questDo = "Do Quest Now", questAddQuest = "Add New Quest", questAddStep = "Add New Step", questAddTurnover = "Add New Turn-In", questAddPreReq = "Add New Pre-Req", questID = "Quest ID", questPullID = "Pull Quest ID", questPullValues = "Pull Current Values", questJob = "Quest Job", questLevel = "Quest Level", questSave = "Save Quest", questDelete = "Delete Quest", questUp = "Higher Priority", questDown = "Lower Priority", questStepEditor = "Step Editor", questStep = "Step", questStepInfo = "Step Information", questStepDetails = "Script Details", questAddItem = "Add Item", questClearItems = "Clear Items", questItemEditor = "Item Editor", newItem = "New Item", stepItemAmount = "Amount", items = "Items", convoIndex = "Conversation #", dutyEncounters = "Encounters", dutyEncounterEditor = "Edit Duty Encounter", questStepScript = "Task-Script", questStepDelete = "Delete Step", questStepSave = "Save Step", questTurnoverEditor = "Turn-In Editor", questPreReqEditor = "Prerequisite Editor", questName = "Name", questMinLevel = "Min Level", questMaxLevel = "Max Level", questPreQuest = "Needs Previous Quest", questMap = "Map", questRepeat = "Repeatable", questStepDone = "Step Done", questReset = "Reset Questprogress", markerMode = "Marker Mode", markerList = "Marker List", markerTeam = "Marker Team", singleMarker = "Single Marker", randomMarker = "Random Marker", questMode = "Quest", removeMarker = "Remove Marker", deleteMarker = "Delete Marker", PartyGrind = "Party Grind", PartyLeader = "Leader", GetPartyLeader = "Target->Leader", UseGamePartyLeader = "Use Party Leader", TargetIsCasting = "Target Casting", TargetCastingOnMe = "Casting On Me", TargetCastingTime = "Casting Time >", botanyMarker = "Botany Marker", miningMarker = "Mining Marker", grindMarker = "Grind Marker", huntMarker = "Hunt Marker", pvpMarker = "PVP Marker", unspoiledMarker = "Unspoiled Marker", contentIDEquals = "ContentID=", NOTcontentIDEquals = "NOT ContentID=", fishingMarker = "Fishing Marker", time = "Time (s)", name = "Name", minLevel = "Min Level", maxLevel = "Max Level", markerTime = "Marker Time (s)", useAetherytes = "Use Aetherytes", resetDutyTimer = "Reset Timer: ", createProfile = "Create Profile", existingProfile = "Existing Profile:", profileType = "Profile Type:", customTask = "Custom Task", addEncounter = "Add Encounter", details = "Details", newEncounter = "New Encounter", newQuest = "New Quest", editQuestStep = "Edit Quest Step", newQuestStep = "New Step", newQuestTurnover = "New Turn-In", newQuestPreReq = "New Pre-Req", questEditSteps = "Edit Steps", questEditPreReqs = "Edit Pre-Reqs", questEditTurnovers = "Edit Turn-Ins", stepCurrent = "Current Step", stepTask = "Step Task", stepItemSelector = "Select Item", stepItemID = "Item ID", stepQuestID = "Quest ID", stepTaskCustom = "Step Task Custom", stepMap = "Map ID", stepMesh = "Mesh Name", stepTarget = "Step Target", stepAction = "Action ID", stepCommandString = "Command String", stepKillCount = "Kill Count", stepDelay = "Delay", stepReward = "Reward Slot", stepClear = "Clear All Steps", prereqJob = "PreReq Job", prereqStep = "PreReq Step", prereqID = "PreReq ID", prereqClear = "Clear All PreReqs", turnoverStep = "Step #:", turnoverID = "Turn-In ID", turnoverSlot = "Item Slot", turnoverClear = "Clear All Turn-Ins", profileManager = "Profile Manager", advancedSettings = "Advanced Settings", hacks = "Hacks", newLocation = "New Location", startLocation = "Start Location", addLocation = "Add Location", saveLocation = "Save Location", moveLocation = "Move Location", removeLocation = "Remove Location", minimumGP = "Minimum GP", locationEditor = "Location Editor", locationName = "Location Name", useCordials = "Use Cordials", gatherUnspoiled = "Gather Unspoiled", minerGearset = "Miner Gearset", botanistGearset = "Botanist Gearset", refreshMap = "Refresh Map", hour = "Hour", class = "Class", isIdle = "Is Idle", objectiveIndex = "Objective Index", stepIndex = "Step Index", killCount = "Kill Count", autoEquip = "Auto-Equip", idlePulseCount = "Idle Count", taskDelay = "Task Delay (ms)", eorzeaTime = "Eorzea Time", potionHP = "Potion HP", potionMP = "Potion MP", teleporter = "Teleporter", waypoint = "Waypoint", newWaypoint = "New Waypoint", editWaypoint = "Edit Waypoint", newName = "New Name", deleteWaypoint = "Delete Waypoint", renameWaypoint = "Rename Waypoint", getTargetName = "Get Target Name", saveAsTargetPos = "Save @ Target POS", saveAsPlayerPos = "Save @ Player POS", save = "Save", move = "Move", distance = "Distance", importExport = "Import / Export", autoExport = "Auto Export", fileName = "File Name", gatherLocations = "Gather Locations", huntLocations = "Hunt Locations", basicExport = "Basic Export", basicImport = "Basic Import", markerImport = "Marker Import", overwriteExisting = "Overwrite Existing", allMarkers = "All Markers", exportSettings = "Export Settings", importSettings = "Import Settings", exportGlobal = "Export Global", importGlobal = "Import Global", minimumCP = "Minimum CP", craftAmount = "Craft Amount", --===== Added 1/21/15 - Ace paranoid = "Paranoid", permaSwiftcast = "PermaSwiftCast", castPrevention = "Cast Prevention", shortcutManager = "Shortcut Manager", food = "Food", foodHQ = "Food HQ", curielRoot = "Curiel Root", --====== Added 1/22/15 - Ace whitelistTarget = "Whitelist Target", validSlots = "Valid Slots", --====== Added 2/15/15 - Ace quickStartMode = "QuickStart", --====== Added 2/18/15 - Ace totMin = "ToT >=", totMax = "ToT <", htSucceedMax = "Hasty Touch Success <", shStackMin = "Steady Hand Stack >=", manipMax = "Manipulation Uses <", --====== Added 3/13/15 - Ace doHuntingLog = "Do Hunting Log", --====== Added 4/2/15 - Ace frontlines = "Frontlines", confirm = "Confirm", yes = "Yes", no = "No", debugging = "Debugging", debugItems = "Debug Items", prevComboSkill = "Previous Combo Skill", prevComboSkillNot = "Previous Combo Skill NOT", currentActionNot = "Current Action NOT", filter1 = "Filter 1", filter2 = "Filter 2", filter3 = "Filter 3", filter4 = "Filter 4", filter5 = "Filter 5", underAttack = "Under Attack", hpAdvantage = "HP Advantage >=", targetTPLE = "Target TP <=", targetMPLE = "Target MP <=", performance = "Performance", loot = "Loot", telecast = "Telecast", need = "Need", greed = "Greed", pass = "Pass", extreme = "Extreme", fast = "Fast", --normal = "Normal", slow = "Slow", shortcut = "Shortcut", modifierKey = "Modifier Key", shortcutKey = "Shortcut Key", waitNearEvac = "Wait Near Evac", randomMovement = "Randomize Movement", --====== Added 6/26/15 - Ace underAttackMelee = "Under Attack (Melee)", chain = "Chain", chainStart = "Chain Start", chainEnd = "Chain End", enmityAOE = "Enmity AOE", frontalCone = "Frontal Cone", tankedTargetsOnly = "Tanked Targets Only", aoeCenter = "AOE Center", comboSkill = "Combo Skill", offGCDSkill = "Off GCD Skill", removesBuff = "Removes Buff", --======= Added 7/6/15 - Ace minContentLevel = "Min Content Level", maxContentLevel = "Max Content Level", maxRadius = "Max Radius", dangerousArea = "Dangerous Area", --======= Added 7/19/15 - Ace useChum = "Use Chum", usePatience = "Use Patience", usePatience2 = "Use Patience II", moochableFish = "Moochable Fish", whitelistFish = "Whitelist Fish", whitelistFishHQ = "Whitelist Fish (HQ)", blacklistFish = "Blacklist Fish", blacklistFishHQ = "Blacklist Fish (HQ)", singleUse = "Single Use", --===== Added 9/20/15 - Sebbs maxdurabmin = "Max Durability >=", maxdurabmax = "Max Durability <", maxprogrmin = "Max Progress >=", maxprogrmax = "Max Progress <", --===== Added 9/23/15 - Sebbs -- Help assisthelp = "Assist Mode will... \ \ You Steer, we Shoot. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", grindhelp = "Grind Mode will... \ \ Do Fates, Huntlogs and Grind Mobs. \ \ Only for COMBAT Classes. \ \ While we endevour to Automate Settings, \ Settings can be changed if Advanced Settings is enabled. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", gatherhelp = "Gather Mode will... \ \ Use Markers, Profiles or Quickstart. \ Only for Miner or Botanist. \ \ Skills use are set by Skill Profile", fishhelp = "Fish Mode will... \ \ Use Markers, Profiles or Quickstart. \ \ Only for Fisher. \ \ Skills are NOT set via Skill Profile. \ Set Skills Via Marker or Profiles.", -- Faq assistfaq = "My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job. \ Is Start combat Checked?", grindfaq = "My Bot Doesnt move? \ \ Are any valid Fates Available? \ Are Max Fate settings to low? \ \ My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job.", gatherhfaq = "Bot Doesnt move? \ \ Profile has no valid tasks? \ Markers have radius to small? \ Heavensward or Stormblood may need Marker list.", fishfaq = "Bot Doesnt Fish? \ \ Profile has no valid tasks? \ Current location has Lockout out due to fishing Limit?", -- Missing GUI strings 09/27/17 HusbandoMax -- Shared debugLevel = "Debug Level", addCollectable = "Add Collectable", itemName = "Item Name", minValue = "Min Value", noProfileSelected = "Please select/create a valid profile.", markerMode = "Marker Mode", markerType = "Marker Type", useCordials = "Use Cordials.", collectablePresets = "Use Known Defaults", expManuals = "Use Experience Manuals", -- Assist followTarget = "Follow Target", faceTarget = "Face Target", clientAutoface = "Using Client Autoface", -- Craft forSingleCraftsOnly = "For Single Crafts Only", craftDebug = "Craft Debug", useHQMats = "Use HQ Mats", onlyIfNecesssary = "Only If Necesssary", -- Fish fishMarkerProfileMode = "Fish Mode", baitType = "Bait Type", -- Fish Actions mooch = "Mooch", mooch2 = "Mooch II", patience = "Patience", patience2 = "Patience II", snagging = "Snagging", fishEyes = "Fish Eyes", chum = "Chum", doubleHook = "Double Hook", fishDebug = "Fish Debug", -- Gather gatherDebug = "Gather Debug", gatherMarkerProfileMode = "Gather Mode", minGPHighCordial = "Min GP - High Cordial", minGPCordial = "Min GP - Cordial", minGPWateredCordial = "Min GP - Watered Cordial", stealthDetectRange = "Stealth - Detect Range", stealthRemoveRange = "Stealth - Remove Range", smartStealth = "Smart Stealth", gatherSlotQuickstart = "Gather Slot", mapsQuickstart = "Maps", gardeningQuickstart = "Gardening", raresQuickstart = "Rares", superRaresQuickstart = "Super Rares", chocoboFoodQuickstart = "Chocobo Food", -- Grind AutoLevelMode = "Auto-Level Mode", ModifyAutoGrind = "Modify Auto-Grind", DoOnlyFates = "Do Only Fates", KillNonFateAggro = "Kill Non-Fate Aggro", AdvancedSettings = "Advanced Settings", DoLuminous = "Do Luminous", FateType = "Fate Type", Enable = "Enable", Startat = "Start at %%", Chain = "Chain", Battle = "Battle", Boss = "Boss", Grind = "Grind", Defense = "Defense", Escort = "Escort", MinFateLv = "Min Fate Lv.", SetNoMinFateLevel = "No Min Fate Level", MaxFateLv = "Max Fate Lv.", SetNoMaxFateLevel = "No Max Fate Level", GrindDebug = "Grind Debug", -- Mini Games CuffaCur = "Cuff-a-Cur", MonsterToss = "Monster Toss", TowerStriker = "Tower Striker", RandomizeGame = "Randomize Game", RandomTimeMin = "Random Time Min (m)", RandomTimeMax = "Random Time Max (m)", PlayTime = "Play Time (m)", RestTime = "Rest Time (m)", PostGameDelay = "Post-Game Delay (ms)", -- Party Grind SynctoFates = "Sync to Fates", -- Tooltips :D 09/27/17 HusbandoMax -- Shared debugLevelTooltip = "Change the Debug message level. (The higher the number the more detailed the messages)", addCollectableTooltip = "Add a new Collectable to the list below.", itemNameCollectableTooltip = "Case-sensitive item name for the item to become a collectable.", itemRaitingCollectableTooltip = "Minimum collectable value at which the item will be accepted as a collectable.", profileTooltip = "The profile to be used in the current mode. (Crafting Orders, Gathering, Fishing)", markerModeTooltip = "Select Single,Random or List.", markerTypeTooltip = "Marker type to show in the list below.", useCordialsTooltip = "Allow use of Cordials for GP.", collectablePresetsTooltip = "Add Known Collectables to the list below.", -- Assist assistTooltip = "None: Use manual targetting.\ Lowest Health: Targets the lowest health target within range.\ Highest Health: Targets the highest health target within range.\ Nearest: Targets the closest target within range.\ Tank Assist: Targets whatever your tank is targetting.", assistPriorityTooltip = "Prioritize Damage or Healing.", followTargetTooltip = "Attempts to continually follow the target (useful in PvP).", faceTargetTooltip = "Attempts to continually face the target.\nWarning: Dangerous if using Standard movement mode.", clientAutofaceTooltip = "This option should be turned on if you are using the game client's [Face Target on Attack] options.", startCombatTooltip = "If this option is off, the bot will not attack a mob that is not in combat already.", confirmDutyTooltip = "Auto accepts Duty Queue.", -- Craft craftingOrderEditTooltip = "Opens the Crafting Order Editor.", craftingOrderCreateTooltip = "Creates a New Crafting Order profile.", expManualsTooltip = "Allow use of Experience boost manuals.", craftDebugTooltip = "Enable Debug messages in console.", forSingleCraftsOnlyTooltip = "These settings are for Single Craft (When no profile is selected)", craftAmountTooltip = "Haw many crafts to complete before stopping.", minimumCPTooltip = "CP required before starting the craft. (Useful for CP food)", useHQMatsTooltip = "Allow the use of HQ materials while crafting.", onlyIfNecesssaryTooltip = "Only use HQ materials if there are no NQ materials left.", -- Fish fishMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", baitTypeTooltip = "Bait to be used in Quick Start mode.", -- Fish Actions moochTooltip = "Allow fish mooching.", mooch2Tooltip = "Allow fish mooching (Mooch 2).", patienceTooltip = "Use Patience while fishing.", patience2Tooltip = "Use Patience 2 while fishing.", snaggingTooltip = "Apply the Snagging buff when fishing.", fishEyesTooltip = "Apply the Fish Eyes buff when fishing.", chumTooltip = "Use Chum while fishing.", doubleHookTooltip = "Use Double Hook.", fishDebugTooltip = "Enable Debug messages in console.", -- Gather gatherDebugTooltip = "Enable Debug messages in console.", gatherMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", minGPHighCordialTooltip = "Min GP required before using a High Cordial.", minGPCordialTooltip = "Min GP required before using a Cordial.", minGPWateredCordialTooltip = "Min GP required before using a Watered Cordial.", stealthDetectRangeTooltip = "Enemy range before applying Stealth.", stealthRemoveRangeTooltip = "Enemy range before removing Stealth.", smartStealthTooltip = "Smarter Stealth based on players direction and mob.", gatherSlotQuickstartTooltip = "Set the item slot to gather.", mapsQuickstartTooltip = "Gather Maps when avalible.", gardeningQuickstartTooltip = "Gather Gardening when avalible.", raresQuickstartTooltip = "Gather Rares when avalible.", superRaresQuickstartTooltip = "Gather Super Rares when avalible.", chocoboFoodQuickstartTooltip = "Gather Chocobo Food when avalible.", -- Grind AutoLevelModeTooltip = "Automatically switch maps to continue leveling in an optimal area.", ModifyAutoGrindTooltip = "Opens a GUI to edit the Auto-Level code", doFatesTooltip = "When enabled, the bot will complete FATEs in addition to mob-grinding.", DoOnlyFatesTooltip = "When enabled, the bot will idle between FATEs, and will not perform mob-grinding.", KillNonFateAggroTooltip = "Kills any Non-Fate Aggro", AdvancedSettingsTooltip = "Enable use of Advanced Settings", DoAtmaTooltip = "Grind Atma crystals and moves to the next zones. (Relic)", DoLuminousTooltip = "Grind Luminous crystals and moves to the next zones. (Relic)", MinFateLvTooltip = "Number of levels below current Player level.", SetNoMinFateLevelTooltip = "Number of levels below current Player level.", MaxFateLvTooltip = "Number of levels above current Player level.", SetNoMaxFateLevelTooltip = "Number of levels above current Player level.", fateTeleportPercentTooltip = "Fate percentage required before teleporting to it. (Hacks)", restInFatesTooltip = "Allow resting while in fate when low HP.", waitNearEvacTooltip = "Allow wating near evac postions instead of standing where you are waiting.", GrindDebugTooltip = "Enable Debug messages in console.", prioritizeClaimsTooltip = "Will claim all mobs withing set range on you for optimal drops.", claimRangeTooltip = "Range to claim when using Prioritize Claims.", attackClaimedTooltip = "Attack already clamied mobs.", doHuntingLogTooltip = "When enabled, FFXIVMinion will complete your class hunting log while grinding.", -- Mini Games CuffaCurTooltip = "Play the Cuff-a-Cur mingame.", MonsterTossTooltip = "Play the Monster Toss mingame.", TowerStrikerTooltip = "Play the Tower Striker mingame.", RandomizeGameTooltip = "Changed to a random minigame. (Time set with Random Time Min/Max)", RandomTimeMinTooltip = "Min time used when randomly changing minigames.", RandomTimeMaxTooltip = "Max time used when randomly changing minigames.", PlayTimeTooltip = "Time to play before resting.", RestTimeTooltip = "Time to rest after playing before starting again.", PostGameDelayTooltip = "Delay between starting each minigame.", -- Party Grind UseGamePartyLeaderTooltip = "Use your current party leader as the person to follow/assist.", SynctoFatesTooltip = "Will automatically Sync to Fates when withing a fate zone.", PartyLeaderTooltip = "Enter a players name to follow/assist them.", GetPartyLeaderTooltip = "Gets your current targets name and inserts it above.", --us end }, -- bk: CN ["cn"] = { -- gw2.lua startStop = "开始/停止", doPulse = "暂停(调试)", pulseTime = "暂停时间 (ms)", enableLog = "日志", task = "任务", state = "状态", effect = "效果", autoStartBot = "自动开始", combatMovement = "拟人战斗移动", enableRepair = "自动修理", ignoreMarkerLevels = "忽略地图等级", ["Bot Status"] = "状态", settings = "设置", status = "状态", advancedSettings = "高级设置", vendorSettings = "售卖设置", gatherSettings = "采集设置", skipcutscene = "跳过过场动画", depositItems = "存仓", checkChat = "聊天报警", randomfarmspot = "随机挂机", disabledrawing = "关闭优化", killaggrononfateenemies = "杀死攻击非危命的敌人", avoidAOE = "避免群攻", -- mesher.lua meshManager = "网格脚本管理器", activated = "激活", noMeshLoad = "不加载网格脚本", mapName = "地图", navmesh = "网格脚本", waypoint = "坐标", ["General"] = "普通设置", ["Auto-Equip"] = "Auto-Equip", getWaypoint = "获取网格坐标", useInSwitcher = "使用切换", enableSwitcher = "开启切换", minSwitchTime = "最小切换时间", maxSwitchTime = "最大切换时间", switchTimer = "切换的时间", switcherSettings = "切换设置", showMesh = "显示三角网格", showrealMesh = "显示实际网格", newMeshName = "新网格文件名字", newMesh = "创建新的网格文件", saveMesh = "保存网格到文件", buildNAVMesh = "建一个导航网格", editor = "编辑", recoder = "录制网格", connections = "连接", enablePSwitch = "启用四周检测", pSwitchCount = "四周人数数量", maMarkerID = "ID", maMarkerName = "名字", -- skillmanager.lua skillbook = "技能书", skillManager = "技能管理器", skillEditor = "技能编辑器", skillEditor_craft = "技能编辑器_手艺(匠人)", skillEditor_gather = "技能编辑器_采集", saveProfile = "保存当前配置", newProfileName = "新配置文件名字", skillProfile = "技能配置文件", newProfile = "创建新配置文件", clearProfile = "新配置文件", skillbookrefresh = "舒心技能", targetType = "目标类型", stepmin = "步 >=", stepmax = "步 <", durabmin = "持久 >=", durabmax = "持久 <", progrmin = "进度 >=", progrmax = "进度 <", qualitymin = "质量 >=", qualitymax = "质量 <", condition = "条件 =", cpmin = "CP >=", cpmax = "CP <", gpmin = "GP >=", gpmax = "GP <", iqstack = "内部静态堆叠 >=", notused = "没有使用", excellent = "最高品质", good = "高品质", normal = "通常", poor = "低品质", centered = "安定", sturdy = "结实", pliant = "高效", primed = "长持续", malleable = "大进展", nodeHas = "有物品: ", gatherAttemptsMin = "采集尝试剩余 >", gatherAttemptsMax = "采集尝试剩余 <=", profile = "配置文件", sMmode = "攻击模式", sMtargetmode = "目标模式", refreshProfiles = "刷新配置文件列表", deleteProfile = "删除当前配置", autoetectSkills = "自动检测技能", refreshSkillList = "清除 & 刷新技能列表", skillEditor = "技能编辑器", enabled = "开启", appliesBuff = "应用 (De-)状态", priority = "优先权", los = "需要视线", instacast = "瞬间技能", channeled = "普通技能", cooldown = "冷却", minRange = "最小范围", maxRange = "最大范围", isGroundTargeted = "地面目标", useOutOfCombat = "战斗外使用", playerMoving = "角色移动", playerHPGT = "角色 HP% >", playerHPLT = "角色 HP% <", playerPowerGT = "角色 力量% >", playerPowerLT = "角色 力量% <", playerHas = "角色有 ", orPlayerHas = "或者角色有 ", playerHasNot = "角色没有 ", orPlayerCond = "角色有 #条件 >", orPlayerHasNot = "或者角色没有 ", targetMoving = "目标移动", targetHPGT = "目标 HP% >", targetHPLT = "目标 HP% <", targetDistanceGT = "目标距离 >", targetDistanceLT = "目标距离 <", enemiesNearCount = "目标周围的敌人(数量) >=", enemiesNearRange = "目标周围的敌人(最大范围) =", alliesNearCount = "盟军附近的目标(数量) >=", alliesNearRange = "盟军附近的目标(最大范围) =", targetHas = "目标有 ", orTargetHas = "或者目标有 ", targetHasNot = "目标没有 ", orTargetHasNot = "或者目标没有 ", prevSkillID = "先前的技能 ID", AdvancedSettings = "高级设置", SwapA = "切换武器", SwapR = "随机切换", SwapCD = "切换当技能2-5在冷却(CD)", SwapRange = "切换当目标超出范围", PriorizeKit = "优先套件", PriorizeAttunement1 = "元素优先级 1", PriorizeAttunement2 = "元素优先级 2", PriorizeAttunement3 = "元素优先级 3", PriorizeAttunement4 = "元素优先级 4", AutoStomp = "复活敌方", AutoRezz = "复活敌方", Fightstyle = "战斗风格", alias = "队友", cdIsReady = "CD 准备", cdNotReady = "CD 没准备", cdTimeLT = "CD 时间 <=", cdTimeGT = "CD 时间 >=", nextSkillPrio = "下一个技能优先", skmTYPE = "动作类型", skmSTYPE = "技能类型", skmCombat = "战斗状态", skmCHARGE = "Charge Skill", skmLevelMin = "等级 >=", skmLevelMax = "等级 <=", checkSkill = "技能 ID", isReady = "准备", isNotReady = "没准备", cooldownRemainingLTE = "冷却保留 <=", cooldownRemainingGTE = "冷却保留 >=", skmNSkillID = "下一个技能 ID", skmCBreak = "组合打断", skmTRG = "技能目标", skmTRGTYPE = "目标角色(类型)", skmNPC = "涵盖npc", skmPTRG = "玩家目标", skmPGTRG = "地面目标", skmPPos = "位置", skmTHPCL = "目标 HP >", skmTHPCB = "目标 HP <", skmTCONTIDS = "具体 ID(s)", skmTNCONTIDS = "非具体 ID(s)", skmTCASTID = "释放 ID(s)", skmTCASTTM = "对自己释放 @ Me", skmTCASTTIME = "释放时间 >", skmPTPL = "玩家 TP >", skmPTPB = "玩家 TP <", skmPMPPL = "玩家 MP% >", skmPMPPB = "玩家 MP% <", skmPAGL = "玩家仇恨值% >", skmPAGB = "玩家仇恨值 % <", skmMPLock = "引起 MP 锁定", skmMPLocked = "锁定受影响", skmMPLockPer = "MP 锁定 %", skmPTCount = "队员计数 >=", skmPTHPL = "队伍 HP% >", skmPTHPB = "队伍 HP% <", skmPTMPL = "队伍 MP% >", skmPTMPB = "队伍 MP% <", skmPTTPL = "队伍 TP >", skmPTTPB = "队伍 TP <", skmHPRIOHP = "优先的 HP % <", skmHPRIO1 = "为优先权 1加血", skmHPRIO2 = "为优先权 2加血", skmHPRIO3 = "为优先权 3加血", skmHPRIO4 = "为优先权 4加血", skmTECount = "敌人 >=", skmTECount2 = "敌人 <=", skmTERange = "敌人范围", skmTELevel = "等级区别", skmTACount = "队友 >=", skmTARange = "队友范围", skmTBuffOwner = "状态拥有者", skmHasBuffs = "有状态 (1+2,3)", skmMissBuffs = "没有状态 (1+2,3)", skmOrBuffDura = "或者状态持续时间 <=", skmAndBuffDura = "和状态持续时间 >", skmUnspoiled = "未受破坏的节点", up = "上", down = "下", delete = "删除", copy = "复制", paste = "粘贴", --sections skillDetails = "技能详情", skillChecks = "其他技能检查", basicDetails = "基本细节", playerHPMPTP = "玩家 HP/MP/TP", party = "队伍", target = "目标", casting = "释放", healPriority = "加血优先权", aoe = "群攻", playerBuffs = "玩家状态BF)", targetBuffs = "目标状态(BF)", --ffxiv botMode = "挂机模式", addGrindSpot = "添加普通地面挂机标识", addFishingSpot = "添加钓鱼标识", addMiningSpot = "添加挖矿标识", addBotanySpot = "添加采集标识", addNavSpot = "添加导航标识", deleteSpot = "删掉最近的标识", markers = "标识", markerLevel = "标识等级", markerMinLevel = "标识最低等级", markerMaxLevel = "标识最高等级", selectedMarker = "选择标识", noMarker = "无标记", mining = "挖矿", fishing = "钓鱼", botany = "采集", gatherTime = "标识(采集)计时器 (s)", deleteMarker = "删掉现有标识", recmesh = "录制网格", recAreaType = "录制类型", recAreaSize = "录制大小", changeMesh = "改变网格", changeAreaType = "改变类型", changeAreaSize = "改变大小", biDirOffMesh = "双向 连接点(跳跃)", addOffMeshSpot = "添加 连接点(跳跃)", delOffMeshSpot = "删除 连接点(跳跃)", typeOffMeshSpot = "类型 连接点(跳跃)", showPath = "显示路径", selectItem1 = "物品优先级 1", selectItem2 = "物品优先级 2", selectItem3 = "物品优先级 3", selectBait = "选择 饵", baitName = "饵名", markerName = "标识名字", markerPos = "标识位置", selectClosestMarker = "选择最近的标识", moveToMarker = "移动到标示", gatherManager = "采集管理器", selectMarker = "选择标识", logCNE = "记录结果", useMount = "使用坐骑", useSprint = "使用精灵", gatherGardening = "采集 Gardening", gatherChocoFood = "采集 Choco Food", nodeType = "节点类型", throttle = "阙值", repair = "修理", questHelpers = "任务帮助", mount = "坐骑", companion = "宠物", stance = "姿态", stFollow = "跟随", stFree = "自由姿态", stDefender = "防卫姿态", stAttacker = "攻击姿态", stHealer = "治疗姿态", mountDist = "坐骑距离: ", sprintDist = "精灵距离: ", randomPaths = "随机路径", botEnabled = "开启外挂", grindMode = "普通地面", huntMode = "狩猎", huntlogMode = "狩猎日志", fishMode = "钓鱼", gatherMode = "采集", assistMode = "战斗辅助", craftMode = "手艺(匠人)", partyMode = "组队-普通地面", useStealth = "使用隐身", randomizeMarkers = "随机标记", teleport = "瞬移", permaSprint = "无限疾跑", avoidHP = "Avoid HP% ", restHP = "休息 HP%: ", restMP = "休息 MP%: ", fleeHP = "逃跑 HP%: ", fleeMP = "逃跑 MP%: ", doFates = "打危命", fatesOnly = "只打危命", setEvacPoint = "设置规避点", restInFates = "在危命中休息", maxFateLevel = "最高危命等级: +", minFateLevel = "最低危命等级: -", waitForComplete = "等待完成%: ", blacklistTimer = "黑名单计时器 (s)", fateIndex = "危命索引", fateName = "危命名字", blacklistAdd = "添加进黑名单", blacklistRem = "移出黑名单", enableRadar = "开启雷达", enable2DRadar = "开启2D雷达", enable3DRadar = "开启3D雷达", fullscreenRadar = "全屏 (2D)", showNodes = "显示节点", showPlayers = "显示玩家", showBattleNPCs = "显示战斗NPC", showEventNPCs = "显示事件NPC", showEventObjects = "显示事件目标", showAetherytes = "显示 Aetherytes", xPos = "X 坐标", yPos = "Y 坐标", assist = "战斗辅助", assistPriority = "优先级", -- new stuff (since last translation) useMooch = "使用 Mooch", markerManager = "标识管理器", prevSkillIDNot = "先前的技能 ID 不是", secsSinceLastCast = "从上一次释放剩余秒", combatRangePercent = "战斗范围 %: ", blacklistManager = "黑名单管理器", createMarker = "创建标识", editMarkers = "编辑标识", markerType = "标识类型", editMarkerList = "设置清单", addMarker = "添加到清单", editMarker = "编辑标识", newMarker = "新的标识", markerList = "标识清单", markerTeam = "Marker Team", setupList = "设置清单", blacklistName = "黑名单名字", blacklistEntry = "黑名单值", entryTime = "值时间", deleteEntry = "删除值", qualityminper = "质量 % >=", qualitymaxper = "质量 % <", blacklistTarget = "黑名单目标", addEntry = "添加值", blacklistFate = "危命黑名单", notAttackable = "无效目标", targetName = "目标名字", monsters = "怪物", fates = "危命", --************************************************* toggleOnOff = "切换 开/关", multiManager = "组队管理器", multiChannel = "频道", multiServer = "服务器 IP", multiPort = "端口 #", multiPass = "密码", serverInfo = "服务器信息", huntMonsters = "狩猎怪兽", hunt = "狩猎", doAtma = "Do Atma", prioritizeClaims = "Prioritize Claims", claimRange = "Claim Range", attackClaimed = "Attack Claimed", alwaysKillAggro = "总是击杀主动怪", fateTeleportPercent = "瞬移 %", startCombat = "开始战斗", onlySolo = "只是单人", onlyParty = "只在队伍", alliesNearHPLT = "队友 HP% <", pvpMode = "PVP", pve = "PVE", both = "两个都是", pvpTargetType = "PVP 目标类型", healer = "治疗", dps = "DPS", tank = "坦克", any = "任意", none = "无", caster = "释放者", meleeDPS = "近战 DPS", ranged = "远程", nearDead = "即将死", sleeper = "休眠者", unattendedHealer = "无人值守治疗", prioritizeRanged = "远程优先", combatType = "战斗类型", nearest = "最近", lowestHealth = "最低血", highestHealth = "Highest Health", tankAssist = "Tank Assist", pvpTargetOne = "优先权 1", pvpTargetTwo = "优先权 2", pvpTargetThree = "优先权 3", pvpTargetFour = "优先权 4", pvpTargetFive = "优先权 5", pvpAvoid = "躲避", pvpSpeedMatchPartner = "速度匹配的合作伙伴", gatherMaps = "采集地图", markerFields = "标识区域", confirmDuty = "自动确认副本", antiAFKMove = "防卡移动", pvpFlee = "远程回避率", skipCutscene = "跳过场景动画", skipDialogue = "跳过对话", doUnstuck = "开启防卡", delayLeave = "延迟离开", defaultProfile = "默认配置文件", useHQMats = "加工 HQ 材料", enterDutyTimer = "进入计时器: ", leaveDutyTimer = "离开计时器: ", dutyMode = "副本", dutyLeader = "副本队长: ", clickToTeleport = "点击瞬移", clickToTravel = "点击移动", questRunProfile = "运行任务", questManager = "任务管理器", quests = "任务", questEditor = "任务编辑器", questDone = "任务完成", questInfo = "任务信息", questSteps = "步骤", questDo = "开始做任务", questAddQuest = "添加新的任务", questAddStep = "添加新的步骤", questAddTurnover = "添加新的提交任务", questAddPreReq = "添加新的提前任务", questID = "任务 ID", questPullID = "Pull Quest ID", questPullValues = "Pull Current Values", questJob = "任务工作", questLevel = "任务等级", questSave = "保存任务", questDelete = "删除任务", questUp = "高优先权", questDown = "低优先权", questStepEditor = "步骤编辑器", questStep = "步骤", questStepInfo = "步骤信息", questStepDetails = "脚本细节", questAddItem = "添加物品", questClearItems = "清除物品", questItemEditor = "物品编辑器", newItem = "新物品", stepItemAmount = "数量", items = "物品", convoIndex = "对话 #", dutyEncounters = "副本计数器", dutyEncounterEditor = "编辑副本计数器", questStepScript = "任务脚本", questStepDelete = "删除步骤", questStepSave = "保存步骤", questTurnoverEditor = "提交任务编辑器", questPreReqEditor = "前提条件编辑器", questName = "名字", questMinLevel = "最低等级", questMaxLevel = "最高等级", questPreQuest = "需要前提任务", questMap = "地图", questRepeat = "反复", questStepDone = "步骤完成", questReset = "重置任务进程", markerMode = "标记模式", markerList = "标记清单", markerTeam = "Marker Team", singleMarker = "单个标记", randomMarker = "随机标记", questMode = "任务", removeMarker = "移除标记", deleteMarker = "删除标记", PartyGrind = "组队挂机", PartyLeader = "队长", GetPartyLeader = "目标->队长", UseGamePartyLeader = "使用队长", TargetIsCasting = "对目标释放", TargetCastingOnMe = "释放 开", TargetCastingTime = "释放时间 >", botanyMarker = "采集标记 ", miningMarker = "挖矿标记 ", grindMarker = "普通地面挂机标记", huntMarker = "打猎标记", pvpMarker = "PVP 标记", unspoiledMarker = "未破坏的标记", contentIDEquals = "内容ID=", NOTcontentIDEquals = "不是内容ID=", fishingMarker = "钓鱼标记", time = "时间 (s)", name = "名字", minLevel = "最低等级", maxLevel = "最高等级", markerTime = "标记时间 (s)", useAetherytes = "Use Aetherytes", resetDutyTimer = "重置计时器: ", createProfile = "创建新的配置文件", existingProfile = "现有的配置文件:", profileType = "配置文件类型:", customTask = "自定义任务", addEncounter = "添加计数器", details = "细节", newEncounter = "新的计数器", newQuest = "新的任务", editQuestStep = "编辑任务步骤", newQuestStep = "新的步骤", newQuestTurnover = "新的提交任务", newQuestPreReq = "新的前提任务", questEditSteps = "编辑步骤", questEditPreReqs = "编辑前提任务", questEditTurnovers = "编辑提交的任务", stepCurrent = "现有步骤", stepTask = "步骤任务", stepItemSelector = "选择物品", stepItemID = "物品 ID", stepQuestID = "任务 ID", stepTaskCustom = "自定义步骤任务", stepMap = "地图 ID", stepMesh = "网格名字", stepTarget = "步骤目标", stepAction = "行动 ID", stepCommandString = "命令字符", stepKillCount = "击杀统计", stepDelay = "延迟", stepReward = "奖励槽", stepClear = "清除所有步骤", prereqJob = "前提任务 工作", prereqStep = "前提任务 步骤", prereqID = "前提任务 ID", prereqClear = "清除所有前提任务", turnoverStep = "步骤 #:", turnoverID = "提交任务的ID", turnoverSlot = "物品槽", turnoverClear = "清除所有要交的任务", profileManager = "配置文件管理", advancedSettings = "高级设置", hacks = "黑客", teleport = "瞬移", newLocation = "新的位置", startLocation = "开始位置", addLocation = "添加位置", saveLocation = "保存位置", moveLocation = "移动位置", removeLocation = "移除位置", minimumGP = "最少 GP", locationEditor = "位置编辑", locationName = "位置名字", useCordials = "使用 Cordials", gatherUnspoiled = "采集未破坏", minerGearset = "采矿 Gearset", botanistGearset = "采集(割草+伐木) Gearset", refreshMap = "刷新地图", hour = "小时", class = "职业", isIdle = "空闲", objectiveIndex = "目标次序", stepIndex = "步骤次序", killCount = "击杀统计", autoEquip = "自动换装", idlePulseCount = "闲置(暂停)计数", taskDelay = "任务延迟 (ms)", eorzeaTime = "冷冻时间", potionHP = "药瓶 HP", potionMP = "药瓶 MP", importExport = "导入/输出", autoExport = "自动导出", fileName = "文件名字", gatherLocations = "采集位置", huntLocations = "狩猎位置", basicExport = "基本导出", basicImport = "基本导入", markerImport = "标识导入", overwriteExisting = "覆盖现有", allMarkers = "所有标识", exportSettings = "导出设置", importSettings = "导入设置", exportGlobal = "导出全局", importGlobal = "导入全局", minimumCP = "最少 CP", craftAmount = "手艺(匠人)量", paranoid = "Paranoid", permaSwiftcast = "疾速", castPrevention = "释放 Prevention", shortcutManager = "快捷管理器", food = "食物", foodHQ = "食物 HQ", curielRoot = "Curiel Root", whitelistTarget = "白名单目标", validSlots = "有效的插槽", quickStartMode = "快速开始", totMin = "ToT >=", totMax = "ToT <", htSucceedMax = "Hasty Touch 成功(烹饪15级) <", shStackMin = "稳手堆叠 >=", manipMax = "操作使用<", doHuntingLog = "做打猎日志", frontlines = "前线战场", confirm = "确认", yes = "是", no = "不", debugging = "正在调试", debugItems = "调试物品", prevComboSkill = "先前的组合及恩那个", prevComboSkillNot = "先前的组合技能不是", currentActionNot = "当前的动作不是", filter1 = "过滤器 1", filter2 = "过滤器 2", filter3 = "过滤器 3", filter4 = "过滤器 4", filter5 = "过滤器 5", underAttack = "被攻击", hpAdvantage = "HP 优点 >=", targetTPLE = "目标 TP <=", targetMPLE = "目标 MP <=", performance = "性能", loot = "拾取", telecast = "瞬移释放", need = "需要", greed = "贪婪", pass = "放弃", extreme = "最快", fast = "快", --normal = "一般", slow = "慢", shortcut = "快捷", modifierKey = "修改器热键", shortcutKey = "快捷键", waitNearEvac = "Wait Near Evac", randomMovement = "Randomize Movement", underAttackMelee = "Under Attack (Melee)", chain = "Chain", chainStart = "Chain Start", chainEnd = "Chain End", enmityAOE = "Enmity AOE", frontalCone = "Frontal Cone", tankedTargetsOnly = "Tanked Targets Only", aoeCenter = "AOE Center", comboSkill = "Combo Skill", offGCDSkill = "Off GCD Skill", removesBuff = "Removes Buff", minContentLevel = "Min Content Level", maxContentLevel = "Max Content Level", maxRadius = "Max Radius", dangerousArea = "Dangerous Area", usePatience = "Use Patience", usePatience2 = "Use Patience II", useChum = "Use Chum", moochableFish = "Moochable Fish", whitelistFish = "Whitelist Fish", whitelistFishHQ = "Whitelist Fish (HQ)", blacklistFish = "Blacklist Fish", blacklistFishHQ = "Blacklist Fish (HQ)", singleUse = "Single Use", --===== Added 9/20/15 - Sebbs maxdurabmin = "Max 持久 >=", maxdurabmax = "Max 持久 <", maxprogrmin = "Max 进度 >=", maxprogrmax = "Max 进度 <", --===== Added 9/23/15 - Sebbs -- Help assisthelp = "輔助模式會... \ \ 你指導,我們拍. \ \ 戰鬥程序來自技能檔案或ACR. \ 戰鬥只與使用的配置文件一樣好.", grindhelp = "研磨模式會... \ \ 做命運,狩獵和研磨暴徒. \ \ 只適用於戰鬥班. \ \ 雖然我們努力自動設置, \ 如果啟用高級設置,則可以更改設置. \ \ 戰鬥程序來自技能檔案或ACR. \ 戰鬥只與使用的配置文件一樣好.", gatherhelp = "收集模式會... \ \ 使用標記,配置文件或快速入門. \ 只適用於礦工或植物學家. \ \ 技能使用由技能資料設定.", fishhelp = "魚模式會... \ \ 使用標記,配置文件或快速入門. \ \ 只有費雪. \ \ 技能不是通過技能資料設置的. \ 通過標記或配置文件設置技能.", -- Faq assistfaq = "我的殭屍不會攻擊? \ \ 檢查你的技能資料設置為正確的班級/工作. \ 開始戰鬥檢查?", grindfaq = "我的機器不動? \ \ 有任何有效的命運可用? \ 最大命運設置為低? \ \ 我的殭屍不會攻擊? \ \ 檢查你的技能資料設置為正確的班級/工作.", gatherhfaq = "玩家不動? \ \ 配置文件沒有有效的任務? \ 標記半徑很小? \ 天氣或風暴可能需要標記列表.", fishfaq = "玩家不魚? \ \ 配置文件沒有有效的任務? \ 當前位置由於釣魚而被鎖定限制?", -- Missing GUI strings 09/27/17 HusbandoMax -- Shared debugLevel = "Debug Level", addCollectable = "Add Collectable", itemName = "Item Name", minValue = "Min Value", noProfileSelected = "Please select/create a valid profile.", markerMode = "Marker Mode", markerType = "Marker Type", useCordials = "Use Cordials.", collectablePresets = "Use Known Defaults", expManuals = "Use Experience Manuals", -- Assist followTarget = "Follow Target", faceTarget = "Face Target", clientAutoface = "Using Client Autoface", -- Craft forSingleCraftsOnly = "For Single Crafts Only", craftDebug = "Craft Debug", useHQMats = "Use HQ Mats", onlyIfNecesssary = "Only If Necesssary", -- Fish fishMarkerProfileMode = "Fish Mode", baitType = "Bait Type", -- Fish Actions mooch = "Mooch", mooch2 = "Mooch II", patience = "Patience", patience2 = "Patience II", snagging = "Snagging", fishEyes = "Fish Eyes", chum = "Chum", doubleHook = "Double Hook", fishDebug = "Fish Debug", -- Gather gatherDebug = "Gather Debug", gatherMarkerProfileMode = "Gather Mode", minGPHighCordial = "Min GP - High Cordial", minGPCordial = "Min GP - Cordial", minGPWateredCordial = "Min GP - Watered Cordial", stealthDetectRange = "Stealth - Detect Range", stealthRemoveRange = "Stealth - Remove Range", smartStealth = "Smart Stealth", gatherSlotQuickstart = "Gather Slot", mapsQuickstart = "Maps", gardeningQuickstart = "Gardening", raresQuickstart = "Rares", superRaresQuickstart = "Super Rares", chocoboFoodQuickstart = "Chocobo Food", -- Grind AutoLevelMode = "Auto-Level Mode", ModifyAutoGrind = "Modify Auto-Grind", DoOnlyFates = "Do Only Fates", KillNonFateAggro = "Kill Non-Fate Aggro", AdvancedSettings = "Advanced Settings", DoLuminous = "Do Luminous", FateType = "Fate Type", Enable = "Enable", Startat = "Start at %%", Chain = "Chain", Battle = "Battle", Boss = "Boss", Grind = "Grind", Defense = "Defense", Escort = "Escort", MinFateLv = "Min Fate Lv.", SetNoMinFateLevel = "No Min Fate Level", MaxFateLv = "Max Fate Lv.", SetNoMaxFateLevel = "No Max Fate Level", GrindDebug = "Grind Debug", -- Mini Games CuffaCur = "Cuff-a-Cur", MonsterToss = "Monster Toss", TowerStriker = "Tower Striker", RandomizeGame = "Randomize Game", RandomTimeMin = "Random Time Min (m)", RandomTimeMax = "Random Time Max (m)", PlayTime = "Play Time (m)", RestTime = "Rest Time (m)", PostGameDelay = "Post-Game Delay (ms)", -- Party Grind SynctoFates = "Sync to Fates", -- Tooltips :D 09/27/17 HusbandoMax -- Shared debugLevelTooltip = "Change the Debug message level. (The higher the number the more detailed the messages)", addCollectableTooltip = "Add a new Collectable to the list below.", itemNameCollectableTooltip = "Case-sensitive item name for the item to become a collectable.", itemRaitingCollectableTooltip = "Minimum collectable value at which the item will be accepted as a collectable.", profileTooltip = "The profile to be used in the current mode. (Crafting Orders, Gathering, Fishing)", markerModeTooltip = "Select Single,Random or List.", markerTypeTooltip = "Marker type to show in the list below.", useCordialsTooltip = "Allow use of Cordials for GP.", collectablePresetsTooltip = "Add Known Collectables to the list below.", -- Assist assistTooltip = "None: Use manual targetting.\ Lowest Health: Targets the lowest health target within range.\ Highest Health: Targets the highest health target within range.\ Nearest: Targets the closest target within range.\ Tank Assist: Targets whatever your tank is targetting.", assistPriorityTooltip = "Prioritize Damage or Healing.", followTargetTooltip = "Attempts to continually follow the target (useful in PvP).", faceTargetTooltip = "Attempts to continually face the target.\nWarning: Dangerous if using Standard movement mode.", clientAutofaceTooltip = "This option should be turned on if you are using the game client's [Face Target on Attack] options.", startCombatTooltip = "If this option is off, the bot will not attack a mob that is not in combat already.", confirmDutyTooltip = "Auto accepts Duty Queue.", -- Craft craftingOrderEditTooltip = "Opens the Crafting Order Editor.", craftingOrderCreateTooltip = "Creates a New Crafting Order profile.", expManualsTooltip = "Allow use of Experience boost manuals.", craftDebugTooltip = "Enable Debug messages in console.", forSingleCraftsOnlyTooltip = "These settings are for Single Craft (When no profile is selected)", craftAmountTooltip = "Haw many crafts to complete before stopping.", minimumCPTooltip = "CP required before starting the craft. (Useful for CP food)", useHQMatsTooltip = "Allow the use of HQ materials while crafting.", onlyIfNecesssaryTooltip = "Only use HQ materials if there are no NQ materials left.", -- Fish fishMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", baitTypeTooltip = "Bait to be used in Quick Start mode.", -- Fish Actions moochTooltip = "Allow fish mooching.", mooch2Tooltip = "Allow fish mooching (Mooch 2).", patienceTooltip = "Use Patience while fishing.", patience2Tooltip = "Use Patience 2 while fishing.", snaggingTooltip = "Apply the Snagging buff when fishing.", fishEyesTooltip = "Apply the Fish Eyes buff when fishing.", chumTooltip = "Use Chum while fishing.", doubleHookTooltip = "Use Double Hook.", fishDebugTooltip = "Enable Debug messages in console.", -- Gather gatherDebugTooltip = "Enable Debug messages in console.", gatherMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", minGPHighCordialTooltip = "Min GP required before using a High Cordial.", minGPCordialTooltip = "Min GP required before using a Cordial.", minGPWateredCordialTooltip = "Min GP required before using a Watered Cordial.", stealthDetectRangeTooltip = "Enemy range before applying Stealth.", stealthRemoveRangeTooltip = "Enemy range before removing Stealth.", smartStealthTooltip = "Smarter Stealth based on players direction and mob.", gatherSlotQuickstartTooltip = "Set the item slot to gather.", mapsQuickstartTooltip = "Gather Maps when avalible.", gardeningQuickstartTooltip = "Gather Gardening when avalible.", raresQuickstartTooltip = "Gather Rares when avalible.", superRaresQuickstartTooltip = "Gather Super Rares when avalible.", chocoboFoodQuickstartTooltip = "Gather Chocobo Food when avalible.", -- Grind AutoLevelModeTooltip = "Automatically switch maps to continue leveling in an optimal area.", ModifyAutoGrindTooltip = "Opens a GUI to edit the Auto-Level code", doFatesTooltip = "When enabled, the bot will complete FATEs in addition to mob-grinding.", DoOnlyFatesTooltip = "When enabled, the bot will idle between FATEs, and will not perform mob-grinding.", KillNonFateAggroTooltip = "Kills any Non-Fate Aggro", AdvancedSettingsTooltip = "Enable use of Advanced Settings", DoAtmaTooltip = "Grind Atma crystals and moves to the next zones. (Relic)", DoLuminousTooltip = "Grind Luminous crystals and moves to the next zones. (Relic)", MinFateLvTooltip = "Number of levels below current Player level.", SetNoMinFateLevelTooltip = "Number of levels below current Player level.", MaxFateLvTooltip = "Number of levels above current Player level.", SetNoMaxFateLevelTooltip = "Number of levels above current Player level.", fateTeleportPercentTooltip = "Fate percentage required before teleporting to it. (Hacks)", restInFatesTooltip = "Allow resting while in fate when low HP.", waitNearEvacTooltip = "Allow wating near evac postions instead of standing where you are waiting.", GrindDebugTooltip = "Enable Debug messages in console.", prioritizeClaimsTooltip = "Will claim all mobs withing set range on you for optimal drops.", claimRangeTooltip = "Range to claim when using Prioritize Claims.", attackClaimedTooltip = "Attack already clamied mobs.", doHuntingLogTooltip = "When enabled, FFXIVMinion will complete your class hunting log while grinding.", -- Mini Games CuffaCurTooltip = "Play the Cuff-a-Cur mingame.", MonsterTossTooltip = "Play the Monster Toss mingame.", TowerStrikerTooltip = "Play the Tower Striker mingame.", RandomizeGameTooltip = "Changed to a random minigame. (Time set with Random Time Min/Max)", RandomTimeMinTooltip = "Min time used when randomly changing minigames.", RandomTimeMaxTooltip = "Max time used when randomly changing minigames.", PlayTimeTooltip = "Time to play before resting.", RestTimeTooltip = "Time to rest after playing before starting again.", PostGameDelayTooltip = "Delay between starting each minigame.", -- Party Grind UseGamePartyLeaderTooltip = "Use your current party leader as the person to follow/assist.", SynctoFatesTooltip = "Will automatically Sync to Fates when withing a fate zone.", PartyLeaderTooltip = "Enter a players name to follow/assist them.", GetPartyLeaderTooltip = "Gets your current targets name and inserts it above.", --cn end }, -- bk: JP ["jp"] = { startStop = "スタート/ストップ", doPulse = "パルス(デバッグ)", pulseTime = "パルス間隔(ms)", enableLog = "ログ有効化", task = "タスク", state = "状態", effect = "効果", autoStartBot = "起動時にスタート", combatMovement = "戦闘移動", enableRepair = "自動修理*", ignoreMarkerLevels = "レベル差無視", ["Bot Status"] = "ステータス", settings = "詳細設定", status = "ステータス", advancedSettings = "詳細設定", vendorSettings = "売店設定", gatherSettings = "採集設定", skipcutscene = "カットシーンスキップ*", depositItems = "アイテム預金", checkChat = "チャット警告", randomfarmspot = "ランダム採集", disabledrawing = "レンダリング無効", killaggrononfateenemies = "FATEMOB以外に反撃", avoidAOE = "AOE回避", -- mesher.lua meshManager = "メッシュ", activated = "有効化", noMeshLoad = "メッシュを読み込まない", mapName = "マップ名", navmesh = "メッシュ", waypoint = "中間地点", ["General"] = "一般設定", ["Auto-Equip"] = "Auto-Equip", getWaypoint = "中間地点確保", useInSwitcher = "メッシュ変換使用", enableSwitcher = "メッシュ変換起動", minSwitchTime = "メッシュ変換最小時間", maxSwitchTime = "メッシュ変換最長時間", switchTimer = "メッシュ変換次タイマー", switcherSettings = "メッシュ変換設定", showMesh = "Trianglesを表示", showrealMesh = "メッシュを表示", newMeshName = "新規メッシュファイル名", newMesh = "新規メッシュファイル", saveMesh = "メッシュを保存", buildNAVMesh = "メッシュをビルド", editor = "編集", recoder = "メッシュ記録", connections = "コネクション", enablePSwitch = "パラノイアスイッチ起動", pSwitchCount = "パラノイアプレイヤー数", maMarkerID = "ID", maMarkerName = "名前", -- skillmanager.lua skillbook = "スキルブック", skillManager = "スキル管理", skillEditor = "スキル編集", skillEditor_craft = "スキル編集_生産", skillEditor_gather = "スキル編集_採集", saveProfile = "プロファイルを保存する", newProfileName = "新規プロファイル名", skillProfile = "スキルプロファイル", newProfile = "新規作成", clearProfile = "プロファイルをクリアする", skillbookrefresh = "更新", targetType = "標的", stepmin = "ターン >=", stepmax = "ターン <", durabmin = "耐久 >=", durabmax = "耐久 <", progrmin = "工数 >=", progrmax = "工数 <", qualitymin = "品質 >=", qualitymax = "品質 <", condition = "状態", cpmin = "CP >=", cpmax = "CP >=", gpmin = "GP <", gpmax = "GP >", iqstack = "インナースタック数 >=", notused = "チェックしない", excellent = "最高品質", good = "高品質", normal = "通常", poor = "低品質", centered = "安定", sturdy = "頑丈", pliant = "高能率", primed = "長持続", malleable = "高進捗", nodeHas = "アイテムあり: ", gatherAttemptsMin = "残り採集数 >", gatherAttemptsMax = "残り採集数 <=", profile = "プロファイル", sMmode = "攻撃モード", sMtargetmode = "標的モード", refreshProfiles = "プロファイル表リフレッシュ", deleteProfile = "現プロファイル削除", autoetectSkills = "スキル自動検索", refreshSkillList = "スキル表 新規&リフレッシュ", skillEditor = "スキル編集", enabled = "有効", appliesBuff = "Applies (De-)Buff", priority = "優先順位", los = "視線必須", instacast = "インスタントスキル", channeled = "チャネリングスキル", cooldown = "再使用時間", minRange = "最小範囲", maxRange = "最大範囲", isGroundTargeted = "は、地上標的だった", useOutOfCombat = "戦闘中は使用不可能", playerMoving = "プレイヤー移動中", playerHPGT = "プレイヤーHP% >", playerHPLT = "プレイヤーHP% <", playerPowerGT = "プレイヤーMP >", playerPowerLT = "プレイヤーMP <", playerHas = "存在するバフID (13,4152,521)", orPlayerHas = "or Player has ", playerHasNot = "存在しないバフID (13,4152,521)", orPlayerCond = "Player has #Conditions >", orPlayerHasNot = "or Player has NOT ", targetMoving = "ターゲット移動中", targetHPGT = "ターゲットHP% >", targetHPLT = "ターゲットHP% <", targetDistanceGT = "ターゲット距離 >", targetDistanceLT = "ターゲット距離 <", enemiesNearCount = "ターゲットに近い敵(数) >=", enemiesNearRange = "ターゲットに近い敵(最大範囲) =", alliesNearCount = "味方に近い敵(数) >=", alliesNearRange = "味方に近い敵(最大範囲) =", targetHas = "存在するバフID (13,4152,521)", orTargetHas = "or Target has ", targetHasNot = "存在しないバフID (13,4152,521)", orTargetHasNot = "or Target has NOT ", prevSkillID = "直前のスキルID", AdvancedSettings = "詳細設定", Fightstyle = "戦闘スタイル", alias = "エイリアス", cdIsReady = "CD Is Ready", cdNotReady = "CD Not Ready", cdTimeLT = "CD Time <=", cdTimeGT = "CD Time >=", nextSkillPrio = "Next Skill Prio", skmTYPE = "アクションタイプ", skmSTYPE = "スキルタイプ", skmCombat = "戦闘状態", skmCHARGE = "Charge Skill", skmLevelMin = "Level >=", skmLevelMax = "Level <=", checkSkill = "スキルID", isReady = "Is Ready", isNotReady = "Is Not Ready", cooldownRemainingLTE = "クールダウン残り <=", cooldownRemainingGTE = "クールダウン残り >=", skmNSkillID = "次のスキルID", skmCBreak = "コンボブレーカー", skmTRG = "スキルターゲット", skmTRGTYPE = "ターゲットのロール", skmNPC = "NPCを含める", skmPTRG = "プレイヤーをターゲット", skmPGTRG = "地面をターゲット", skmPPos = "Position", skmTHPCL = "ターゲットHP >", skmTHPCB = "ターゲットHP <", skmTCONTIDS = "Content ID(s)", skmTNCONTIDS = "Not Content ID(s)", skmTCASTID = "キャストID(s)", skmTCASTTM = "自分に対してキャストしているか", skmTCASTTIME = "詠唱時間 >", skmPTPL = "プレイヤーTP >", skmPTPB = "プレイヤーTP <", skmPMPPL = "プレイヤーMP% >", skmPMPPB = "プレイヤーMP% <", skmPAGL = "プレイヤーAggro % >", skmPAGB = "プレイヤーAggro % <", skmMPLock = "Causes MP Lockout", skmMPLocked = "Lockout Affected", skmMPLockPer = "MP Lockout %", skmPTCount = "Member Count >=", skmPTHPL = "パーティHP% >", skmPTHPB = "パーティHP% <", skmPTMPL = "パーティMP% >", skmPTMPB = "パーティMP% <", skmPTTPL = "パーティTP >", skmPTTPB = "パーティTP <", skmHPRIOHP = "優先度HP % <", skmHPRIO1 = "ヒール優先度 1", skmHPRIO2 = "ヒール優先度 2", skmHPRIO3 = "ヒール優先度 3", skmHPRIO4 = "ヒール優先度 4", skmTECount = "敵の数 >=", skmTECount2 = "敵の数 <=", skmTERange = "敵視の距離", skmTELevel = "Level Difference", skmTACount = "Allies >=", skmTARange = "Ally Range", skmTBuffOwner = "バフを与えた人", skmHasBuffs = "存在するバフID (1+2,3)", skmMissBuffs = "存在しないバフID (1+2,3)", skmOrBuffDura = "残り時間 <=", skmAndBuffDura = "残り時間 >", skmUnspoiled = "Unspoiled Node", up = "↑に移動", down = "↓に移動", delete = "削除", copy = "コピー", paste = "ペースト", --sections skillDetails = "スキル詳細", skillChecks = "他スキルチェック", basicDetails = "基本設定", playerHPMPTP = "プレイヤーHP/MP/TP", party = "パーティ", target = "ターゲット", casting = "キャスティング", healPriority = "ヒール優先度", aoe = "AOE", playerBuffs = "プレイヤーのバフ", targetBuffs = "ターゲットのバフ", --ffxiv stuff specific stuff botMode = "モード", addGrindSpot = "レベリングマーカー追加", addFishingSpot = "漁師マーカー追加", addMiningSpot = "採掘師マーカー追加", addBotanySpot = "園芸師マーカー追加", addNavSpot = "ナビマーカー追加", deleteSpot = "最寄りのマーカーを削除する", markers = "マーカー", markerLevel = "マーカーレベル", markerMinLevel = "マーカー最小レベル", markerMaxLevel = "マーカー最大レベル", selectedMarker = "マーカー選択肢", noMarker = "マーカー無効", mining = "採掘師", fishing = "漁師", botany = "園芸師", gatherTime = "マーカータイマー(s)", deleteMarker = "マーカーを削除する", recmesh = "3Dメッシュ記録", recAreaType = "種類", recAreaSize = "範囲", changeMesh = "メッシュ編集", changeAreaType = "種類", changeAreaSize = "範囲", biDirOffMesh = "双方向オフメッシュ接続", addOffMeshSpot = "オフメッシュ接続を追加", delOffMeshSpot = "オフメッシュ接続を削除", typeOffMeshSpot = "Type Offメッシュ接続", showPath = "道路標示", selectItem1 = "アイテム優先度 1", selectItem2 = "アイテム優先度 2", selectItem3 = "アイテム優先度 3", selectBait = "エサ選択", baitName = "エサ名", markerName = "マーカー名", markerPos = "マーカー地点", selectClosestMarker = "近距離マーカーを選択", moveToMarker = "マーカーに移動", gatherManager = "採集管理", selectMarker = "マーカー選択肢", logCNE = "CNEログ結果", useMount = "マウント", useSprint = "スプリント", gatherGardening = "ガーデニングアイテムを集める", gatherChocoFood = "チョコボのエサを集める", nodeType = "Node Type", throttle = "Throttle", repair = "自動修理", questHelpers = "クエスト補助", mount = "マウント", companion = "バディチョコボ", stance = "バディスタンス", stFollow = "フォロー", stFree = "フリー", stDefender = "ディフェンダー", stAttacker = "アタッカー", stHealer = "ヒーラー", mountDist = "マウント距離", sprintDist = "スプリント距離", randomPaths = "移動ルートをランダムにする", botEnabled = "スタート", grindMode = "レべリング", huntMode = "モブハント", huntlogMode = "討伐手帳", fishMode = "釣り", gatherMode = "集まる", craftMode = "クラフト", assistMode = "アシスト", partyMode = "パーティレベリング", useStealth = "ステルス", randomizeMarkers = "マーカーランダム化", teleport = "常にテレポート*", permaSprint = "常にスプリント*", avoidHP = "回避 HP% ", restHP = "一時退避 HP%: ", restMP = "一時退避 MP%: ", fleeHP = "逃げる HP%: ", fleeMP = "逃げる MP%: ", doFates = "FATE参加", fatesOnly = "FATEのみ", setEvacPoint = "退避地点登録", restInFates = "Rest In FATE", maxFateLevel = "最大FATEレベル: +", minFateLevel = "最小FATEレベル: -", waitForComplete = "完了待ち%: ", blacklistTimer = "ブラックリストタイマー(s)", fateIndex = "FATE Index", fateName = "FATE名", blacklistAdd = "ブラックリストAdd", blacklistRem = "ブラックリストRem", enableRadar = "レーダー起動", enable2DRadar = "2Dレーダー起動", enable3DRadar = "3Dレーダー起動", fullscreenRadar = "フルスクリーン (2D)", showNodes = "採集ポイント表示", showPlayers = "プレイヤー表示", showBattleNPCs = "バトルNPC表示", showEventNPCs = "イベントNPC表示", showEventObjects = "イベント物体表示", showAetherytes = "エーテライト表示", xPos = "X 地点", yPos = "Y 地点", assist = "ターゲットアシスト", assistPriority = "優先度", -- new stuff (since last translation) useMooch = "泳がせ釣り", markerManager = "マーカー", prevSkillIDNot = "直前スキルID NOT", secsSinceLastCast = "Secs Since Last Cast", combatRangePercent = "戦闘範囲 %: ", blacklistManager = "ブラックリスト", createMarker = "新規マーカー", editMarkers = "マーカー編集", markerType = "マーカータイプ", editMarkerList = "Setup List", addMarker = "リストに追加する", editMarker = "マーカー編集", newMarker = "新規マーカー", markerList = "マーカーリスト", markerTeam = "マーカーチーム", setupList = "Setup List", blacklistName = "種類", blacklistEntry = "エントリー", entryTime = "時間", deleteEntry = "エントリーを削除", qualityminper = "品質 % >=", qualitymaxper = "品質 % <", blacklistTarget = "Blacklist Target", addEntry = "エントリーを追加", blacklistFate = "ブラックリストに追加", notAttackable = "Invalid Target", targetName = "Target Name", monsters = "Monsters", fates = "Fates", --************************************************* toggleOnOff = "ON / OFF", multiManager = "マルチBot連携", multiChannel = "チャンネル", multiServer = "サーバーIP", multiPort = "ポート#", multiPass = "パスワード", serverInfo = "サーバー情報", huntMonsters = "Hunted Monsters", hunt = "モブハント", doAtma = "アートマ収集", prioritizeClaims = "まとめ狩り", claimRange = "まとめ狩り距離", attackClaimed = "横殴りする", alwaysKillAggro = "Always Kill Aggro", fateTeleportPercent = "テレポート %", startCombat = "自動で殴る", onlySolo = "ソロ時のみ", onlyParty = "パーティ時のみ", alliesNearHPLT = "Allies HP% <", pvpMode = "PVP", pve = "PVE", both = "Both", pvpTargetType = "PVP Target Type", healer = "Healer", dps = "DPS", tank = "Tank", any = "Any", none = "None", caster = "Caster", meleeDPS = "Melee DPS", ranged = "Ranged", nearDead = "Near Dead", sleeper = "Sleeper", unattendedHealer = "Unattended Healer", prioritizeRanged = "Prioritize Ranged", combatType = "Combat Type", nearest = "Nearest", lowestHealth = "Lowest Health", highestHealth = "Highest Health", tankAssist = "Tank Assist", pvpTargetOne = "優先度1", pvpTargetTwo = "優先度2", pvpTargetThree = "優先度3", pvpTargetFour = "優先度4", pvpTargetFive = "優先度5", pvpAvoid = "Avoidance", pvpSpeedMatchPartner = "Speed Match Partner", gatherMaps = "地図を採集する", markerFields = "Marker Fields", confirmDuty = "ID突入時に自動で同意する", antiAFKMove = "Anti-AFK Move", pvpFlee = "Ranged Flee", skipCutscene = "カットシーンスキップ", skipDialogue = "ダイアログスキップ", doUnstuck = "スタック回避", delayLeave = "Delay Leave", defaultProfile = "Default Profile", useHQMats = "HQ素材を使う", enterDutyTimer = "Enter Timer: ", leaveDutyTimer = "Leave Timer: ", dutyMode = "DUTY", dutyLeader = "Duty Leader: ", clickToTeleport = "クリックでテレポート*", clickToTravel = "クリックで移動", questRunProfile = "RunQuests", questManager = "QuestManager", quests = "Quests", questEditor = "Quest Editor", questDone = "Quest Done", questInfo = "Quest Information", questSteps = "Steps", questDo = "Do Quest Now", questAddQuest = "Add New Quest", questAddStep = "Add New Step", questAddTurnover = "Add New Turn-In", questAddPreReq = "Add New Pre-Req", questID = "クエストID", questPullID = "Pull Quest ID", questPullValues = "Pull Current Values", questJob = "Quest Job", questLevel = "Quest Level", questSave = "クエストを保存", questDelete = "クエストを削除", questUp = "↑に移動", questDown = "↓に移動", questStepEditor = "Step Editor", questStep = "Step", questStepInfo = "Step Information", questStepDetails = "Script Details", questAddItem = "Add Item", questClearItems = "Clear Items", questItemEditor = "Item Editor", newItem = "New Item", stepItemAmount = "Amount", items = "Items", convoIndex = "Conversation #", dutyEncounters = "Duty Encounters", dutyEncounterEditor = "Edit Duty Encounter", questStepScript = "Task-Script", questStepDelete = "Delete Step", questStepSave = "Save Step", questTurnoverEditor = "Turn-In Editor", questPreReqEditor = "Prerequisite Editor", questName = "クエスト名", questMinLevel = "下限レベル", questMaxLevel = "上限レベル", questPreQuest = "Needs Previous Quest", questMap = "クエストマップ", questRepeat = "繰り返し", questStepDone = "Step Done", questReset = "Reset Questprogress", markerMode = "マーカーモード", markerList = "マーカーリスト", markerTeam = "マーカーチーム", singleMarker = "シングルマーカー", randomMarker = "ランダムマーカー", questMode = "クエスト", removeMarker = "マーカーをリストから消す", deleteMarker = "マーカーを削除する", PartyGrind = "パーティレベリング", PartyLeader = "リーダー", GetPartyLeader = "ターゲット中を追加", UseGamePartyLeader = "現在のリーダーを指定", TargetIsCasting = "Target Casting", TargetCastingOnMe = "Casting On", TargetCastingTime = "Casting Time >", botanyMarker = "園芸マーカー", miningMarker = "採掘マーカー", grindMarker = "レベリングマーカー", huntMarker = "モブハントマーカー", pvpMarker = "PVPマーカー", unspoiledMarker = "未知採集マーカー", contentIDEquals = "対象ID", NOTcontentIDEquals = "非対象ID", fishingMarker = "釣りマーカー", time = "時間(s)", name = "名前", minLevel = "下限レベル", maxLevel = "上限レベル", markerTime = "マーカー時間(s)", useAetherytes = "エーテライト", resetDutyTimer = "Reset Timer: ", createProfile = "プロファイルを作成", existingProfile = "プロファイル", profileType = "種類", customTask = "Custom Task", addEncounter = "Encounterを追加", details = "詳細", newEncounter = "新しいEncounter", newQuest = "新しいクエスト", editQuestStep = "Quest Stepを編集", newQuestStep = "新しいStep", newQuestTurnover = "新しいTurn-In", newQuestPreReq = "新しいPre-Req", questEditSteps = "Stepを編集", questEditPreReqs = "Pre-Reqsを編集", questEditTurnovers = "Turn-Insを編集", stepCurrent = "Current Step", stepTask = "Step Task", stepItemSelector = "Select Item", stepItemID = "アイテムID", stepQuestID = "クエストID", stepTaskCustom = "Step Task Custom", stepMap = "マップID", stepMesh = "メッシュ名", stepTarget = "Step Target", stepAction = "アクションID", stepCommandString = "Command String", stepKillCount = "倒した数", stepDelay = "ディレイ", stepReward = "Reward Slot", stepClear = "Clear All Steps", prereqJob = "PreReq Job", prereqStep = "PreReq Step", prereqID = "PreReq ID", prereqClear = "全てのPreReqsをクリア", turnoverStep = "Step #:", turnoverID = "Turn-In ID", turnoverSlot = "Item Slot", turnoverClear = "全てのTurn-Insをクリア", profileManager = "プロファイル", advancedSettings = "詳細設定", hacks = "チート機能 *注意!", newLocation = "ロケーションを追加", startLocation = "ここから始める", addLocation = "ロケーションを追加", saveLocation = "ロケーションを保存", moveLocation = "ロケーションをしまう", removeLocation = "ロケーションを削除", minimumGP = "最小GP", locationEditor = "ロケーションエディタ", locationName = "ロケーション名", useCordials = "コーディアルを使う", gatherUnspoiled = "未知採集を有効にする", minerGearset = "採掘師ギアセット#", botanistGearset = "園芸師ギアセット#", refreshMap = "マップを更新", hour = "時刻", class = "クラス", isIdle = "待機地点", objectiveIndex = "目的", stepIndex = "段階", killCount = "倒した数", autoEquip = "自動装備", idlePulseCount = "待ち時間カウント", taskDelay = "タスクディレイ(ms)", eorzeaTime = "エオルゼア時間", potionHP = "ポーションHP", potionMP = "ポーションMP", importExport = "Import / Export", autoExport = "自動エクスポート", fileName = "ファイル名", gatherLocations = "ギャザラーのロケーション", huntLocations = "モブハントのロケーション", basicExport = "基本設定のエクスポート", basicImport = "基本設定のインポート", markerImport = "マーカーのインポート", overwriteExisting = "今の設定を上書きする", allMarkers = "全てのマーカー", exportSettings = "エクスポートの設定", importSettings = "インポートの設定", exportGlobal = "Export Global", importGlobal = "Import Global", minimumCP = "最低CP", craftAmount = "作成個数", paranoid = "テレポート制限(ON推奨)", permaSwiftcast = "常時迅速魔*", castPrevention = "キャスト制限", shortcutManager = "ショートカットキー", food = "食事", foodHQ = "食事 HQ", curielRoot = "クリーエの野菜を使用", whitelistTarget = "ターゲット中のIDを追加", validSlots = "Valid Slots", quickStartMode = "クイックスタート", totMin = "秘訣 >=", totMax = "秘訣 <", htSucceedMax = "ヘイスティタッチ成功回数 <", shStackMin = "ステディハンドスタック数 >=", manipMax = "マニピュレーション使用回数 <", doHuntingLog = "討伐手帳", frontlines = "外縁遺跡群", confirm = "確認", yes = "YES", no = "NO", debugging = "デバギング", debugItems = "デバッグアイテム", prevComboSkill = "直前のコンボスキル", prevComboSkillNot = "直前のコンボスキルではない", currentActionNot = "Current Action NOT", filter1 = "フィルター1", filter2 = "フィルター2", filter3 = "フィルター3", filter4 = "フィルター4", filter5 = "フィルター5", underAttack = "Under Attack", hpAdvantage = "HP Advantage >=", targetTPLE = "ターゲットTP <=", targetMPLE = "ターゲットMP <=", performance = "パフォーマンス", loot = "ロットイン", telecast = "ワープアクション", need = "NEED", greed = "GREED", pass = "PASS", extreme = "Extreme", fast = "Fast", --normal = "通常", slow = "Slow", shortcut = "種類", modifierKey = "装飾キー", shortcutKey = "キー", waitNearEvac = "退避地点で待つ", randomMovement = "ランダム動作", underAttackMelee = "Under Attack (Melee)", chain = "Chain", chainStart = "Chain Start", chainEnd = "Chain End", enmityAOE = "Enmity AOE", frontalCone = "Frontal Cone", tankedTargetsOnly = "Tanked Targets Only", aoeCenter = "AOE Center", comboSkill = "コンボスキル", offGCDSkill = "GCD外スキル", removesBuff = "Removes Buff", minContentLevel = "最小コンテンツレベル", maxContentLevel = "最大コンテンツレベル", maxRadius = "最大範囲(m)", dangerousArea = "危険地帯", usePatience = "ペーシェンス", usePatience2 = "ペーシェンスII", useChum = "撒き餌", moochableFish = "泳がせ可能な魚", whitelistFish = "ホワイトリスト", whitelistFishHQ = "ホワイトリスト(HQ)", blacklistFish = "ブラックリスト", blacklistFishHQ = "ブラックリスト(HQ)", singleUse = "Single Use", --===== Added 9/20/15 - Sebbs maxdurabmin = "Max 耐久 >=", maxdurabmax = "Max 耐久 <", maxprogrmin = "Max 工数 >=", maxprogrmax = "Max 工数 <", --===== Added 9/23/15 - Sebbs -- Help assisthelp = "アシストモード... \ \ あなたは私たちを狙う. \ \ 戦闘ルーチンはスキルプロファイルまたはACRから来る. \ 戦闘は使用されたプロファイルと同じくらい良いです.", grindhelp = "グラインドモード... \ \ フェイト、ハントログ、グラインドモーブ. \ \ バトルクラスのみ. \ \ 私たちは自動設定に努めていますが, \ [詳細設定]を有効にすると設定を変更できます. \ \ 戦闘ルーチンはスキルプロファイルまたはACRから来る. \ 戦闘は使用されたプロファイルと同じくらい良いです.", gatherhelp = "収集モード... \ \ マーカー、プロファイル、クイックスタートを使用する. \ 鉱夫または植物学者のみ. \ \ スキルの使用はスキルプロファイルによって設定されます.", fishhelp = "フィッシュモード... \ \ マーカー、プロファイル、クイックスタートを使用する. \ \ フィッシャーのみ. \ \ スキルはスキルプロファイルでは設定されません. \ マーカーまたはプロファイルによるスキルの設定.", -- Faq assistfaq = "私のボットは攻撃しない? \ \ スキルプロファイルが正しいクラス/ジョブに設定されていることを確認してください. \ スタート戦闘はチェックされていますか?", grindfaq = "私のボットは動かない? \ \ 有効な運命はありますか? \ 最大運命の設定は低いですか? \ \ 私のボットは攻撃しない? \ \ スキルプロファイルが正しいクラス/ジョブに設定されていることを確認してください.", gatherhfaq = "ボットが動かない? \ \ プロファイルに有効なタスクがありません? \ マーカーの半径は小さい? \ 天国や嵐の血痕マーカーリストが必要な場合があります.", fishfaq = "ボット・イットン・フィッシュ? \ \ プロファイルに有効なタスクがありません? \ 現在の位置は釣りの限界によりロックアウトされています?", -- Missing GUI strings 09/27/17 HusbandoMax -- Shared debugLevel = "Debug Level", addCollectable = "Add Collectable", itemName = "Item Name", minValue = "Min Value", noProfileSelected = "Please select/create a valid profile.", markerMode = "Marker Mode", markerType = "Marker Type", useCordials = "Use Cordials.", collectablePresets = "Use Known Defaults", expManuals = "Use Experience Manuals", -- Assist followTarget = "Follow Target", faceTarget = "Face Target", clientAutoface = "Using Client Autoface", -- Craft forSingleCraftsOnly = "For Single Crafts Only", craftDebug = "Craft Debug", useHQMats = "Use HQ Mats", onlyIfNecesssary = "Only If Necesssary", -- Fish fishMarkerProfileMode = "Fish Mode", baitType = "Bait Type", -- Fish Actions mooch = "Mooch", mooch2 = "Mooch II", patience = "Patience", patience2 = "Patience II", snagging = "Snagging", fishEyes = "Fish Eyes", chum = "Chum", doubleHook = "Double Hook", fishDebug = "Fish Debug", -- Gather gatherDebug = "Gather Debug", gatherMarkerProfileMode = "Gather Mode", minGPHighCordial = "Min GP - High Cordial", minGPCordial = "Min GP - Cordial", minGPWateredCordial = "Min GP - Watered Cordial", stealthDetectRange = "Stealth - Detect Range", stealthRemoveRange = "Stealth - Remove Range", smartStealth = "Smart Stealth", gatherSlotQuickstart = "Gather Slot", mapsQuickstart = "Maps", gardeningQuickstart = "Gardening", raresQuickstart = "Rares", superRaresQuickstart = "Super Rares", chocoboFoodQuickstart = "Chocobo Food", -- Grind AutoLevelMode = "Auto-Level Mode", ModifyAutoGrind = "Modify Auto-Grind", DoOnlyFates = "Do Only Fates", KillNonFateAggro = "Kill Non-Fate Aggro", AdvancedSettings = "Advanced Settings", DoLuminous = "Do Luminous", FateType = "Fate Type", Enable = "Enable", Startat = "Start at %%", Chain = "Chain", Battle = "Battle", Boss = "Boss", Grind = "Grind", Defense = "Defense", Escort = "Escort", MinFateLv = "Min Fate Lv.", SetNoMinFateLevel = "No Min Fate Level", MaxFateLv = "Max Fate Lv.", SetNoMaxFateLevel = "No Max Fate Level", GrindDebug = "Grind Debug", -- Mini Games CuffaCur = "Cuff-a-Cur", MonsterToss = "Monster Toss", TowerStriker = "Tower Striker", RandomizeGame = "Randomize Game", RandomTimeMin = "Random Time Min (m)", RandomTimeMax = "Random Time Max (m)", PlayTime = "Play Time (m)", RestTime = "Rest Time (m)", PostGameDelay = "Post-Game Delay (ms)", -- Party Grind SynctoFates = "Sync to Fates", -- Tooltips :D 09/27/17 HusbandoMax -- Shared debugLevelTooltip = "Change the Debug message level. (The higher the number the more detailed the messages)", addCollectableTooltip = "Add a new Collectable to the list below.", itemNameCollectableTooltip = "Case-sensitive item name for the item to become a collectable.", itemRaitingCollectableTooltip = "Minimum collectable value at which the item will be accepted as a collectable.", profileTooltip = "The profile to be used in the current mode. (Crafting Orders, Gathering, Fishing)", markerModeTooltip = "Select Single,Random or List.", markerTypeTooltip = "Marker type to show in the list below.", useCordialsTooltip = "Allow use of Cordials for GP.", collectablePresetsTooltip = "Add Known Collectables to the list below.", -- Assist assistTooltip = "None: Use manual targetting.\ Lowest Health: Targets the lowest health target within range.\ Highest Health: Targets the highest health target within range.\ Nearest: Targets the closest target within range.\ Tank Assist: Targets whatever your tank is targetting.", assistPriorityTooltip = "Prioritize Damage or Healing.", followTargetTooltip = "Attempts to continually follow the target (useful in PvP).", faceTargetTooltip = "Attempts to continually face the target.\nWarning: Dangerous if using Standard movement mode.", clientAutofaceTooltip = "This option should be turned on if you are using the game client's [Face Target on Attack] options.", startCombatTooltip = "If this option is off, the bot will not attack a mob that is not in combat already.", confirmDutyTooltip = "Auto accepts Duty Queue.", -- Craft craftingOrderEditTooltip = "Opens the Crafting Order Editor.", craftingOrderCreateTooltip = "Creates a New Crafting Order profile.", expManualsTooltip = "Allow use of Experience boost manuals.", craftDebugTooltip = "Enable Debug messages in console.", forSingleCraftsOnlyTooltip = "These settings are for Single Craft (When no profile is selected)", craftAmountTooltip = "Haw many crafts to complete before stopping.", minimumCPTooltip = "CP required before starting the craft. (Useful for CP food)", useHQMatsTooltip = "Allow the use of HQ materials while crafting.", onlyIfNecesssaryTooltip = "Only use HQ materials if there are no NQ materials left.", -- Fish fishMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", baitTypeTooltip = "Bait to be used in Quick Start mode.", -- Fish Actions moochTooltip = "Allow fish mooching.", mooch2Tooltip = "Allow fish mooching (Mooch 2).", patienceTooltip = "Use Patience while fishing.", patience2Tooltip = "Use Patience 2 while fishing.", snaggingTooltip = "Apply the Snagging buff when fishing.", fishEyesTooltip = "Apply the Fish Eyes buff when fishing.", chumTooltip = "Use Chum while fishing.", doubleHookTooltip = "Use Double Hook.", fishDebugTooltip = "Enable Debug messages in console.", -- Gather gatherDebugTooltip = "Enable Debug messages in console.", gatherMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", minGPHighCordialTooltip = "Min GP required before using a High Cordial.", minGPCordialTooltip = "Min GP required before using a Cordial.", minGPWateredCordialTooltip = "Min GP required before using a Watered Cordial.", stealthDetectRangeTooltip = "Enemy range before applying Stealth.", stealthRemoveRangeTooltip = "Enemy range before removing Stealth.", smartStealthTooltip = "Smarter Stealth based on players direction and mob.", gatherSlotQuickstartTooltip = "Set the item slot to gather.", mapsQuickstartTooltip = "Gather Maps when avalible.", gardeningQuickstartTooltip = "Gather Gardening when avalible.", raresQuickstartTooltip = "Gather Rares when avalible.", superRaresQuickstartTooltip = "Gather Super Rares when avalible.", chocoboFoodQuickstartTooltip = "Gather Chocobo Food when avalible.", -- Grind AutoLevelModeTooltip = "Automatically switch maps to continue leveling in an optimal area.", ModifyAutoGrindTooltip = "Opens a GUI to edit the Auto-Level code", doFatesTooltip = "When enabled, the bot will complete FATEs in addition to mob-grinding.", DoOnlyFatesTooltip = "When enabled, the bot will idle between FATEs, and will not perform mob-grinding.", KillNonFateAggroTooltip = "Kills any Non-Fate Aggro", AdvancedSettingsTooltip = "Enable use of Advanced Settings", DoAtmaTooltip = "Grind Atma crystals and moves to the next zones. (Relic)", DoLuminousTooltip = "Grind Luminous crystals and moves to the next zones. (Relic)", MinFateLvTooltip = "Number of levels below current Player level.", SetNoMinFateLevelTooltip = "Number of levels below current Player level.", MaxFateLvTooltip = "Number of levels above current Player level.", SetNoMaxFateLevelTooltip = "Number of levels above current Player level.", fateTeleportPercentTooltip = "Fate percentage required before teleporting to it. (Hacks)", restInFatesTooltip = "Allow resting while in fate when low HP.", waitNearEvacTooltip = "Allow wating near evac postions instead of standing where you are waiting.", GrindDebugTooltip = "Enable Debug messages in console.", prioritizeClaimsTooltip = "Will claim all mobs withing set range on you for optimal drops.", claimRangeTooltip = "Range to claim when using Prioritize Claims.", attackClaimedTooltip = "Attack already clamied mobs.", doHuntingLogTooltip = "When enabled, FFXIVMinion will complete your class hunting log while grinding.", -- Mini Games CuffaCurTooltip = "Play the Cuff-a-Cur mingame.", MonsterTossTooltip = "Play the Monster Toss mingame.", TowerStrikerTooltip = "Play the Tower Striker mingame.", RandomizeGameTooltip = "Changed to a random minigame. (Time set with Random Time Min/Max)", RandomTimeMinTooltip = "Min time used when randomly changing minigames.", RandomTimeMaxTooltip = "Max time used when randomly changing minigames.", PlayTimeTooltip = "Time to play before resting.", RestTimeTooltip = "Time to rest after playing before starting again.", PostGameDelayTooltip = "Delay between starting each minigame.", -- Party Grind UseGamePartyLeaderTooltip = "Use your current party leader as the person to follow/assist.", SynctoFatesTooltip = "Will automatically Sync to Fates when withing a fate zone.", PartyLeaderTooltip = "Enter a players name to follow/assist them.", GetPartyLeaderTooltip = "Gets your current targets name and inserts it above.", --jp end }, -- bk: DE ["de"] = { startStop = "StartStop", doPulse = "Pulse(Debug)", pulseTime = "Pulse Time (ms)", enableLog = "Enable Log", task = "Task", state = "State", effect = "Effect", autoStartBot = "AutoStartBot", combatMovement = "CombatMovement", enableRepair = "AutoRepair", ignoreMarkerLevels = "IgnoreMarkerLevels", ["Bot Status"] = "BotStatus", settings = "Settings", status = "Status", advancedSettings = "Advanced Settings", vendorSettings = "VendorSettings", gatherSettings = "GatherSettings", skipcutscene = "Skip Cutscenes", depositItems = "Deposit Items", checkChat = "Chat Alert", randomfarmspot = "Use Random Farmspots", disabledrawing = "Disable Rendering", killaggrononfateenemies = "Kill attacking None-Fate Enemies", avoidAOE = "Avoid AOE", -- mesher.lua meshManager = "MeshManager", activated = "Activated", noMeshLoad = "No Mesh Load", mapName = "Map", navmesh = "Navmesh", waypoint = "Waypoint", ["General"] = "General", ["Auto-Equip"] = "Auto-Equip", getWaypoint = "GetMeshWP", useInSwitcher = "UseInSwitcher", enableSwitcher = "EnableSwitcher", minSwitchTime = "MinSwitchTime", maxSwitchTime = "MaxSwitchTime", switchTimer = "TimeUntilSwitch", switcherSettings = "SwitcherSettings", showMesh = "Show Triangles ", showrealMesh = "Show NavMesh", newMeshName = "New Meshfile Name", newMesh = "Clear Navmesh", saveMesh = "Save NavMesh", buildNAVMesh = "Build NavMesh", recoder = "Record Mesh", connections = "Connections", editor = "Editor", enablePSwitch = "EnableParanoiaSwitch", pSwitchCount = "ParanoiaPlayerCount", maMarkerID = "ID", maMarkerName = "Name", -- skillmanager.lua skillbook = "SkillBook", skillManager = "SkillManager", skillEditor = "SkillEditor", skillEditor_craft = "SkillEditor_Crafting", skillEditor_gather = "SkillEditor_Gathering", saveProfile = "Save Profile", newProfileName = "New Profile", skillProfile = "Skill Profile", newProfile = "Create New Profile", clearProfile = "Clear Profile", skillbookrefresh = "Refresh Skills", targetType = "Target", stepmin = "Step >=", stepmax = "Step <", durabmin = "Durability >=", durabmax = "Durability <", progrmin = "Progress >=", progrmax = "Progress <", qualitymin = "Quality >=", qualitymax = "Quality <", condition = "Zustand =", cpmin = "CP >=", cpmax = "CP <", gpmin = "GP >=", gpmax = "GP <", iqstack = "InnerQuiet Stack >=", notused = "NotUsed", excellent = "Exzellent", good = "Gut", normal = "Ausreichend", poor = "Minderwertig", centered = "Stabil", sturdy = "Robust", pliant = "Ergiebig", primed = "Präpariert", malleable = "Formbar", nodeHas = "Has Item: ", gatherAttemptsMin = "Attempts Remaining >", gatherAttemptsMax = "Attempts Remaining <=", profile = "Profile", sMmode = "Attack Mode", sMtargetmode = "Target Mode", refreshProfiles = "Refresh Profile List", deleteProfile = "Delete Current Profile", autoetectSkills = "Autodetect Skills", refreshSkillList = "Clear & Refresh SkillList", skillEditor = "Skill Editor", enabled = "Enabled", appliesBuff = "Applies (De-)Buff", priority = "Priority", los = "Needs LineOfSight", instacast = "Instant Skill", channeled = "Channel Skill", cooldown = "Cooldown", minRange = "MinRange", maxRange = "MaxRange", isGroundTargeted = "Is GroundTargeted", useOutOfCombat = "Use out of Combat", playerMoving = "Player Moving", playerHPGT = "Player HP% >", playerHPLT = "Player HP% <", playerPowerGT = "Player MP >", playerPowerLT = "Player MP <", playerHas = "Player has Buff: like 13,4152,521", orPlayerHas = "or Player has ", playerHasNot = "Player has NOT Buff: like 13,4152,521", orPlayerCond = "Player has #Conditions >", orPlayerHasNot = "or Player has NOT ", targetMoving = "Target Moving", targetHPGT = "Target HP% >", targetHPLT = "Target HP% <", targetDistanceGT = "Target Distance >", targetDistanceLT = "Target Distance <", enemiesNearCount = "Enemies Near Target(Count) >=", enemiesNearRange = "Enemies Near Target(MaxRange) =", alliesNearCount = "Allies Near Target(Count) >=", alliesNearRange = "Allies Near Target(MaxRange) =", targetHas = "Target has Buff : like 13,4152,521", orTargetHas = "or Target has ", targetHasNot = "Target has NOT Buff : like 13,4152,521", orTargetHasNot = "or Target has NOT ", prevSkillID = "Previous Skill ID", AdvancedSettings = "Advanced Settings", Fightstyle = "Fightstyle", alias = "Alias", cdIsReady = "CD Is Ready", cdNotReady = "CD Not Ready", cdTimeLT = "CD Time <=", cdTimeGT = "CD Time >=", nextSkillPrio = "Next Skill Prio", skmTYPE = "Action Type", skmSTYPE = "Skill Type", skmCombat = "Combat Status", skmCHARGE = "Charge Skill", skmLevelMin = "Level >=", skmLevelMax = "Level <=", checkSkill = "Skill ID", isReady = "Is Ready", isNotReady = "Is Not Ready", cooldownRemainingLTE = "Cooldown Remaining <=", cooldownRemainingGTE = "Cooldown Remaining >=", skmNSkillID = "Next Skill ID", skmCBreak = "Combo Breaker", skmTRG = "Skill Target", skmTRGTYPE = "Target Role", skmNPC = "Include NPC", skmPTRG = "Player Target", skmPGTRG = "Ground Target", skmPPos = "Position", skmTHPCL = "Target HP >", skmTHPCB = "Target HP <", skmTCONTIDS = "Content ID(s)", skmTNCONTIDS = "Not Content ID(s)", skmTCASTID = "Cast ID(s)", skmTCASTTM = "Cast @ Me", skmTCASTTIME = "Cast Time >", skmPTPL = "Player TP >", skmPTPB = "Player TP <", skmPMPPL = "Player MP% >", skmPMPPB = "Player MP% <", skmPAGL = "Player Aggro % >", skmPAGB = "Player Aggro % <", skmMPLock = "Causes MP Lockout", skmMPLocked = "Lockout Affected", skmMPLockPer = "MP Lockout %", skmPTCount = "Member Count >=", skmPTHPL = "Party HP% >", skmPTHPB = "Party HP% <", skmPTMPL = "Party MP% >", skmPTMPB = "Party MP% <", skmPTTPL = "Party TP >", skmPTTPB = "Party TP <", skmHPRIOHP = "Priority HP % <", skmHPRIO1 = "Heal Priority 1", skmHPRIO2 = "Heal Priority 2", skmHPRIO3 = "Heal Priority 3", skmHPRIO4 = "Heal Priority 4", skmTECount = "Enemies >=", skmTECount2 = "Enemies <=", skmTERange = "Enemy Range", skmTELevel = "Level Difference", skmTACount = "Allies >=", skmTARange = "Ally Range", skmTBuffOwner = "Buff Owner", skmHasBuffs = "Has Buffs (1+2,3)", skmMissBuffs = "Missing Buffs (1+2,3)", skmOrBuffDura = "Or Buff Dura <=", skmAndBuffDura = "And Buff Dura >", skmUnspoiled = "Unspoiled Node", up = "UP", down = "DOWN", delete = "DELETE", copy = "COPY", paste = "PASTE", --sections skillDetails = "Skill Details", skillChecks = "Other Skill Checks", basicDetails = "Basic Details", playerHPMPTP = "Player HP/MP/TP", party = "Party", target = "Target", casting = "Casting", healPriority = "Heal Priority", aoe = "AOE", playerBuffs = "Player Buffs", targetBuffs = "Target Buffs", --ffxiv stuff specific stuff botMode = "Bot Mode", addGrindSpot = "Add Grind Marker", addFishingSpot = "Add Fishing Marker", addMiningSpot = "Add Mining Marker", addBotanySpot = "Add Botany Marker", addNavSpot = "Add Nav Marker", deleteSpot = "Delete Nearest Marker", markers = "Markers", markerLevel = "Marker Level", markerMinLevel = "Marker Min Level", markerMaxLevel = "Marker Max Level", selectedMarker = "Selected Marker", noMarker = "No Marker", mining = "Mining", fishing = "Fishing", botany = "Botany", gatherTime = "Marker Timer (s)", deleteMarker = "Delete Current Marker", recmesh = "Record Mesh", recAreaType = "Record Type", recAreaSize = "Record Size", changeMesh = "Change Mesh", changeAreaType = "Change Type", changeAreaSize = "Change Size", biDirOffMesh = "Bidirectional Offmeshconnection", addOffMeshSpot = "Add OffMeshConnection", delOffMeshSpot = "Del OffMeshConnection", typeOffMeshSpot = "Type OffMeshConnection", showPath = "Show Path", selectItem1 = "Item Priority 1", selectItem2 = "Item Priority 2", selectItem3 = "Item Priority 3", selectBait = "Select Bait", baitName = "Bait Name", markerName = "Marker Name", markerPos = "Marker Position", selectClosestMarker = "Select Closest Marker", moveToMarker = "Move To Marker", gatherManager = "GatherManager", selectMarker = "Select Marker", logCNE = "Log CNE Results", useMount = "Use Mount", useSprint = "Use Sprint", gatherGardening = "Gather Gardening", gatherChocoFood = "Gather Choco Food", nodeType = "Node Type", throttle = "Throttle", repair = "Repair", questHelpers = "Quest Helpers", mount = "Mount", companion = "Companion", stance = "Stance", stFollow = "Follow", stFree = "Free Stance", stDefender = "Defender Stance", stAttacker = "Attacker Stance", stHealer = "Healer Stance", mountDist = "Mount Distance: ", sprintDist = "Sprint Distance: ", randomPaths = "Randomize Paths", botEnabled = "Bot Enabled", grindMode = "Grind", huntMode = "Hunt", huntlogMode = "Hunting Log", fishMode = "Fish", craftMode = "Crafting", gatherMode = "Gather", assistMode = "Assist", partyMode = "Party-Grind", useStealth = "Use Stealth", randomizeMarkers = "Randomize Markers", teleport = "Teleport", permaSprint = "PermaSprint", avoidHP = "Avoid HP% ", restHP = "Rest HP%: ", restMP = "Rest MP%: ", fleeHP = "Flee HP%: ", fleeMP = "Flee MP%: ", doFates = "Do Fates", fatesOnly = "Fates Only", setEvacPoint = "SetEvacPoint", restInFates = "Rest In Fates", maxFateLevel = "MaxFateLvl: +", minFateLevel = "MinFateLvl: -", waitForComplete = "WaitForComplete%: ", blacklistTimer = "BlacklistTimer (s)", fateIndex = "FateIndex", fateName = "FateName", blacklistAdd = "BlacklistAdd", blacklistRem = "BlacklistRem", enableRadar = "Enable Radar", enable2DRadar = "Enable 2D Radar", enable3DRadar = "Enable 3D Radar", fullscreenRadar = "Fullscreen (2D)", showNodes = "Show Nodes", showPlayers = "Show Players", showBattleNPCs = "Show Battle NPCs", showEventNPCs = "Show Event NPCs", showEventObjects = "Show Event Objects", showAetherytes = "Show Aetherytes", xPos = "X Position", yPos = "Y Position", assist = "Targeting Assist", assistPriority = "Priority", -- new stuff (since last translation) useMooch = "Use Mooch", markerManager = "MarkerManager", prevSkillIDNot = "Previous Skill ID NOT", secsSinceLastCast = "Secs Since Last Cast", combatRangePercent = "Combat Range %: ", blacklistManager = "BlacklistManager", createMarker = "Create Marker", editMarkers = "Edit Markers", markerType = "Marker Type", editMarkerList = "Setup List", addMarker = "Add To List", editMarker = "Edit Marker", newMarker = "New Marker", markerList = "Marker List", markerTeam = "Marker Team", setupList = "Setup List", blacklistName = "Blacklist Name", blacklistEntry = "Blacklist Entry", entryTime = "Entry Time", deleteEntry = "Delete Entry", qualityminper = "Quality % >=", qualitymaxper = "Quality % <", blacklistTarget = "Blacklist Target", addEntry = "Add Entry", blacklistFate = "Blacklist Fate", notAttackable = "Invalid Target", targetName = "Target Name", monsters = "Monsters", fates = "Fates", --************************************************* toggleOnOff = "Toggle On/Off", multiManager = "Multibot Manager", multiChannel = "Channel", multiServer = "Server IP", multiPort = "Port #", multiPass = "Password", serverInfo = "Server Information", huntMonsters = "Hunted Monsters", hunt = "Hunt", doAtma = "Do Atma", prioritizeClaims = "Prioritize Claims", claimRange = "Claim Range", attackClaimed = "Attack Claimed", alwaysKillAggro = "Always Kill Aggro", fateTeleportPercent = "Teleport %", startCombat = "Start Combat", onlySolo = "Only solo", onlyParty = "Only in party", alliesNearHPLT = "Allies HP% <", pvpMode = "PVP", pve = "PVE", both = "Both", pvpTargetType = "PVP Target Type", healer = "Healer", dps = "DPS", tank = "Tank", any = "Any", none = "None", caster = "Caster", meleeDPS = "Melee DPS", ranged = "Ranged", nearDead = "Near Dead", sleeper = "Sleeper", unattendedHealer = "Unattended Healer", prioritizeRanged = "Prioritize Ranged", combatType = "Combat Type", nearest = "Nearest", lowestHealth = "Lowest Health", highestHealth = "Highest Health", tankAssist = "Tank Assist", pvpTargetOne = "Priority 1", pvpTargetTwo = "Priority 2", pvpTargetThree = "Priority 3", pvpTargetFour = "Priority 4", pvpTargetFive = "Priority 5", pvpAvoid = "Avoidance", pvpSpeedMatchPartner = "Speed Match Partner", gatherMaps = "Gather Maps", markerFields = "Marker Fields", confirmDuty = "Auto-Confirm Duty", antiAFKMove = "Anti-AFK Move", pvpFlee = "Ranged Flee", skipCutscene = "Skip Cutscenes", skipDialogue = "Skip Dialogues", doUnstuck = "Enable Unstuck", delayLeave = "Delay Leave", defaultProfile = "Default Profile", useHQMats = "Craft HQ Mats", enterDutyTimer = "Enter Timer: ", leaveDutyTimer = "Leave Timer: ", dutyMode = "Duty", dutyLeader = "Duty Leader: ", clickToTeleport = "Click To Teleport", clickToTravel = "Click To Travel", questRunProfile = "RunQuests", questManager = "QuestManager", quests = "Quests", questEditor = "Quest Editor", questDone = "Quest Done", questInfo = "Quest Information", questSteps = "Steps", questDo = "Do Quest Now", questAddQuest = "Add New Quest", questAddStep = "Add New Step", questAddTurnover = "Add New Turn-In", questAddPreReq = "Add New Pre-Req", questID = "Quest ID", questPullID = "Pull Quest ID", questPullValues = "Pull Current Values", questJob = "Quest Job", questLevel = "Quest Level", questSave = "Save Quest", questDelete = "Delete Quest", questUp = "Higher Priority", questDown = "Lower Priority", questStepEditor = "Step Editor", questStep = "Step", questStepInfo = "Step Information", questStepDetails = "Script Details", questAddItem = "Add Item", questClearItems = "Clear Items", questItemEditor = "Item Editor", newItem = "New Item", stepItemAmount = "Amount", items = "Items", convoIndex = "Conversation #", dutyEncounters = "Duty Encounters", dutyEncounterEditor = "Edit Duty Encounter", questStepScript = "Task-Script", questStepDelete = "Delete Step", questStepSave = "Save Step", questTurnoverEditor = "Turn-In Editor", questPreReqEditor = "Prerequisite Editor", questName = "Name", questMinLevel = "Min Level", questMaxLevel = "Max Level", questPreQuest = "Needs Previous Quest", questMap = "Map", questRepeat = "Repeatable", questStepDone = "Step Done", questReset = "Reset Questprogress", markerMode = "Marker Mode", markerList = "Marker List", markerTeam = "Marker Team", singleMarker = "Single Marker", randomMarker = "Random Marker", questMode = "Quest", removeMarker = "Remove Marker", deleteMarker = "Delete Marker", PartyGrind = "Party Grind", PartyLeader = "Leader", GetPartyLeader = "Target->Leader", UseGamePartyLeader = "Use Party Leader", TargetIsCasting = "Target Casting", TargetCastingOnMe = "Casting On", TargetCastingTime = "Casting Time >", botanyMarker = "Botany Marker", miningMarker = "Mining Marker", grindMarker = "Grind Marker", huntMarker = "Hunt Marker", pvpMarker = "PVP Marker", unspoiledMarker = "Unspoiled Marker", contentIDEquals = "ContentID=", NOTcontentIDEquals = "NOT ContentID=", fishingMarker = "Fishing Marker", time = "Time (s)", name = "Name", minLevel = "Min Level", maxLevel = "Max Level", markerTime = "Marker Time (s)", useAetherytes = "Use Aetherytes", resetDutyTimer = "Reset Timer: ", createProfile = "Create Profile", existingProfile = "Existing Profile:", profileType = "Profile Type:", customTask = "Custom Task", addEncounter = "Add Encounter", details = "Details", newEncounter = "New Encounter", newQuest = "New Quest", editQuestStep = "Edit Quest Step", newQuestStep = "New Step", newQuestTurnover = "New Turn-In", newQuestPreReq = "New Pre-Req", questEditSteps = "Edit Steps", questEditPreReqs = "Edit Pre-Reqs", questEditTurnovers = "Edit Turn-Ins", stepCurrent = "Current Step", stepTask = "Step Task", stepItemSelector = "Select Item", stepItemID = "Item ID", stepQuestID = "Quest ID", stepTaskCustom = "Step Task Custom", stepMap = "Map ID", stepMesh = "Mesh Name", stepTarget = "Step Target", stepAction = "Action ID", stepCommandString = "Command String", stepKillCount = "Kill Count", stepDelay = "Delay", stepReward = "Reward Slot", stepClear = "Clear All Steps", prereqJob = "PreReq Job", prereqStep = "PreReq Step", prereqID = "PreReq ID", prereqClear = "Clear All PreReqs", turnoverStep = "Step #:", turnoverID = "Turn-In ID", turnoverSlot = "Item Slot", turnoverClear = "Clear All Turn-Ins", profileManager = "Profile Manager", advancedSettings = "Advanced Settings", hacks = "Hacks", teleport = "Teleport", newLocation = "New Location", startLocation = "Start Location", addLocation = "Add Location", saveLocation = "Save Location", moveLocation = "Move Location", removeLocation = "Remove Location", minimumGP = "Minimum GP", locationEditor = "Location Editor", locationName = "Location Name", useCordials = "Use Cordials", gatherUnspoiled = "Gather Unspoiled", minerGearset = "Miner Gearset", botanistGearset = "Botanist Gearset", refreshMap = "Refresh Map", hour = "Hour", class = "Class", isIdle = "Is Idle", objectiveIndex = "Objective Index", stepIndex = "Step Index", killCount = "Kill Count", autoEquip = "Auto-Equip", idlePulseCount = "Idle Count", taskDelay = "Task Delay (ms)", eorzeaTime = "Eorzea Time", potionHP = "Potion HP", potionMP = "Potion MP", importExport = "Import / Export", autoExport = "Auto Export", fileName = "File Name", gatherLocations = "Gather Locations", huntLocations = "Hunt Locations", basicExport = "Basic Export", basicImport = "Basic Import", markerImport = "Marker Import", overwriteExisting = "Overwrite Existing", allMarkers = "All Markers", exportSettings = "Export Settings", importSettings = "Import Settings", exportGlobal = "Export Global", importGlobal = "Import Global", minimumCP = "Minimum CP", craftAmount = "Craft Amount", paranoid = "Paranoid", permaSwiftcast = "PermaSwiftCast", castPrevention = "Cast Prevention", shortcutManager = "Shortcut Manager", food = "Food", foodHQ = "Food HQ", curielRoot = "Curiel Root", whitelistTarget = "Whitelist Target", validSlots = "Valid Slots", quickStartMode = "QuickStart", totMin = "ToT >=", totMax = "ToT <", htSucceedMax = "Hasty Touch Success <", shStackMin = "Steady Hand Stack >=", manipMax = "Manipulation Uses <", doHuntingLog = "Do Hunting Log", frontlines = "Äußere Ruinen", confirm = "Confirm", yes = "Yes", no = "No", debugging = "Debugging", debugItems = "Debug Items", prevComboSkill = "Previous Combo Skill", prevComboSkillNot = "Previous Combo Skill NOT", currentActionNot = "Current Action NOT", filter1 = "Filter 1", filter2 = "Filter 2", filter3 = "Filter 3", filter4 = "Filter 4", filter5 = "Filter 5", underAttack = "Under Attack", hpAdvantage = "HP Advantage >=", targetTPLE = "Target TP <=", targetMPLE = "Target MP <=", performance = "Performance", loot = "Loot", telecast = "Telecast", need = "Need", greed = "Greed", pass = "Pass", extreme = "Extreme", fast = "Fast", --normal = "Normal", slow = "Slow", shortcut = "Shortcut", modifierKey = "Modifier Key", shortcutKey = "Shortcut Key", waitNearEvac = "Wait Near Evac", randomMovement = "Randomize Movement", underAttackMelee = "Under Attack (Melee)", chain = "Chain", chainStart = "Chain Start", chainEnd = "Chain End", enmityAOE = "Enmity AOE", frontalCone = "Frontal Cone", tankedTargetsOnly = "Tanked Targets Only", aoeCenter = "AOE Center", comboSkill = "Combo Skill", offGCDSkill = "Off GCD Skill", removesBuff = "Removes Buff", minContentLevel = "Min Content Level", maxContentLevel = "Max Content Level", maxRadius = "Max Radius", dangerousArea = "Dangerous Area", usePatience = "Use Patience", usePatience2 = "Use Patience II", useChum = "Use Chum", moochableFish = "Moochable Fish", whitelistFish = "Whitelist Fish", whitelistFishHQ = "Whitelist Fish (HQ)", blacklistFish = "Blacklist Fish", blacklistFishHQ = "Blacklist Fish (HQ)", singleUse = "Single Use", --===== Added 9/20/15 - Sebbs maxdurabmin = "Max Durability >=", maxdurabmax = "Max Durability <", maxprogrmin = "Max Progress >=", maxprogrmax = "Max Progress <", --===== Added 9/23/15 - Sebbs -- Help assisthelp = "Assist Mode will... \ \ You Steer, we Shoot. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", grindhelp = "Grind Mode will... \ \ Do Fates, Huntlogs and Grind Mobs. \ \ Only for COMBAT Classes. \ \ While we endevour to Automate Settings, \ Settings can be changed if Advanced Settings is enabled. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", gatherhelp = "Gather Mode will... \ \ Use Markers, Profiles or Quickstart. \ Only for Miner or Botanist. \ \ Skills use are set by Skill Profile", fishhelp = "Fish Mode will... \ \ Use Markers, Profiles or Quickstart. \ \ Only for Fisher. \ \ Skills are NOT set via Skill Profile. \ Set Skills Via Marker or Profiles.", -- Faq assistfaq = "My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job. \ Is Start combat Checked?", grindfaq = "My Bot Doesnt move? \ \ Are any valid Fates Available? \ Are Max Fate settings to low? \ \ My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job.", gatherhfaq = "Bot Doesnt move? \ \ Profile has no valid tasks? \ Markers have radius to small? \ Heavensward or Stormblood may need Marker list.", fishfaq = "Bot Doesnt Fish? \ \ Profile has no valid tasks? \ Current location has Lockout out due to fishing Limit?", -- Missing GUI strings 09/27/17 HusbandoMax -- Shared debugLevel = "Debug Level", addCollectable = "Add Collectable", itemName = "Item Name", minValue = "Min Value", noProfileSelected = "Please select/create a valid profile.", markerMode = "Marker Mode", markerType = "Marker Type", useCordials = "Use Cordials.", collectablePresets = "Use Known Defaults", expManuals = "Use Experience Manuals", -- Assist followTarget = "Follow Target", faceTarget = "Face Target", clientAutoface = "Using Client Autoface", -- Craft forSingleCraftsOnly = "For Single Crafts Only", craftDebug = "Craft Debug", useHQMats = "Use HQ Mats", onlyIfNecesssary = "Only If Necesssary", -- Fish fishMarkerProfileMode = "Fish Mode", baitType = "Bait Type", -- Fish Actions mooch = "Mooch", mooch2 = "Mooch II", patience = "Patience", patience2 = "Patience II", snagging = "Snagging", fishEyes = "Fish Eyes", chum = "Chum", doubleHook = "Double Hook", fishDebug = "Fish Debug", -- Gather gatherDebug = "Gather Debug", gatherMarkerProfileMode = "Gather Mode", minGPHighCordial = "Min GP - High Cordial", minGPCordial = "Min GP - Cordial", minGPWateredCordial = "Min GP - Watered Cordial", stealthDetectRange = "Stealth - Detect Range", stealthRemoveRange = "Stealth - Remove Range", smartStealth = "Smart Stealth", gatherSlotQuickstart = "Gather Slot", mapsQuickstart = "Maps", gardeningQuickstart = "Gardening", raresQuickstart = "Rares", superRaresQuickstart = "Super Rares", chocoboFoodQuickstart = "Chocobo Food", -- Grind AutoLevelMode = "Auto-Level Mode", ModifyAutoGrind = "Modify Auto-Grind", DoOnlyFates = "Do Only Fates", KillNonFateAggro = "Kill Non-Fate Aggro", AdvancedSettings = "Advanced Settings", DoLuminous = "Do Luminous", FateType = "Fate Type", Enable = "Enable", Startat = "Start at %%", Chain = "Chain", Battle = "Battle", Boss = "Boss", Grind = "Grind", Defense = "Defense", Escort = "Escort", MinFateLv = "Min Fate Lv.", SetNoMinFateLevel = "No Min Fate Level", MaxFateLv = "Max Fate Lv.", SetNoMaxFateLevel = "No Max Fate Level", GrindDebug = "Grind Debug", -- Mini Games CuffaCur = "Cuff-a-Cur", MonsterToss = "Monster Toss", TowerStriker = "Tower Striker", RandomizeGame = "Randomize Game", RandomTimeMin = "Random Time Min (m)", RandomTimeMax = "Random Time Max (m)", PlayTime = "Play Time (m)", RestTime = "Rest Time (m)", PostGameDelay = "Post-Game Delay (ms)", -- Party Grind SynctoFates = "Sync to Fates", -- Tooltips :D 09/27/17 HusbandoMax -- Shared debugLevelTooltip = "Change the Debug message level. (The higher the number the more detailed the messages)", addCollectableTooltip = "Add a new Collectable to the list below.", itemNameCollectableTooltip = "Case-sensitive item name for the item to become a collectable.", itemRaitingCollectableTooltip = "Minimum collectable value at which the item will be accepted as a collectable.", profileTooltip = "The profile to be used in the current mode. (Crafting Orders, Gathering, Fishing)", markerModeTooltip = "Select Single,Random or List.", markerTypeTooltip = "Marker type to show in the list below.", useCordialsTooltip = "Allow use of Cordials for GP.", collectablePresetsTooltip = "Add Known Collectables to the list below.", -- Assist assistTooltip = "None: Use manual targetting.\ Lowest Health: Targets the lowest health target within range.\ Highest Health: Targets the highest health target within range.\ Nearest: Targets the closest target within range.\ Tank Assist: Targets whatever your tank is targetting.", assistPriorityTooltip = "Prioritize Damage or Healing.", followTargetTooltip = "Attempts to continually follow the target (useful in PvP).", faceTargetTooltip = "Attempts to continually face the target.\nWarning: Dangerous if using Standard movement mode.", clientAutofaceTooltip = "This option should be turned on if you are using the game client's [Face Target on Attack] options.", startCombatTooltip = "If this option is off, the bot will not attack a mob that is not in combat already.", confirmDutyTooltip = "Auto accepts Duty Queue.", -- Craft craftingOrderEditTooltip = "Opens the Crafting Order Editor.", craftingOrderCreateTooltip = "Creates a New Crafting Order profile.", expManualsTooltip = "Allow use of Experience boost manuals.", craftDebugTooltip = "Enable Debug messages in console.", forSingleCraftsOnlyTooltip = "These settings are for Single Craft (When no profile is selected)", craftAmountTooltip = "Haw many crafts to complete before stopping.", minimumCPTooltip = "CP required before starting the craft. (Useful for CP food)", useHQMatsTooltip = "Allow the use of HQ materials while crafting.", onlyIfNecesssaryTooltip = "Only use HQ materials if there are no NQ materials left.", -- Fish fishMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", baitTypeTooltip = "Bait to be used in Quick Start mode.", -- Fish Actions moochTooltip = "Allow fish mooching.", mooch2Tooltip = "Allow fish mooching (Mooch 2).", patienceTooltip = "Use Patience while fishing.", patience2Tooltip = "Use Patience 2 while fishing.", snaggingTooltip = "Apply the Snagging buff when fishing.", fishEyesTooltip = "Apply the Fish Eyes buff when fishing.", chumTooltip = "Use Chum while fishing.", doubleHookTooltip = "Use Double Hook.", fishDebugTooltip = "Enable Debug messages in console.", -- Gather gatherDebugTooltip = "Enable Debug messages in console.", gatherMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", minGPHighCordialTooltip = "Min GP required before using a High Cordial.", minGPCordialTooltip = "Min GP required before using a Cordial.", minGPWateredCordialTooltip = "Min GP required before using a Watered Cordial.", stealthDetectRangeTooltip = "Enemy range before applying Stealth.", stealthRemoveRangeTooltip = "Enemy range before removing Stealth.", smartStealthTooltip = "Smarter Stealth based on players direction and mob.", gatherSlotQuickstartTooltip = "Set the item slot to gather.", mapsQuickstartTooltip = "Gather Maps when avalible.", gardeningQuickstartTooltip = "Gather Gardening when avalible.", raresQuickstartTooltip = "Gather Rares when avalible.", superRaresQuickstartTooltip = "Gather Super Rares when avalible.", chocoboFoodQuickstartTooltip = "Gather Chocobo Food when avalible.", -- Grind AutoLevelModeTooltip = "Automatically switch maps to continue leveling in an optimal area.", ModifyAutoGrindTooltip = "Opens a GUI to edit the Auto-Level code", doFatesTooltip = "When enabled, the bot will complete FATEs in addition to mob-grinding.", DoOnlyFatesTooltip = "When enabled, the bot will idle between FATEs, and will not perform mob-grinding.", KillNonFateAggroTooltip = "Kills any Non-Fate Aggro", AdvancedSettingsTooltip = "Enable use of Advanced Settings", DoAtmaTooltip = "Grind Atma crystals and moves to the next zones. (Relic)", DoLuminousTooltip = "Grind Luminous crystals and moves to the next zones. (Relic)", MinFateLvTooltip = "Number of levels below current Player level.", SetNoMinFateLevelTooltip = "Number of levels below current Player level.", MaxFateLvTooltip = "Number of levels above current Player level.", SetNoMaxFateLevelTooltip = "Number of levels above current Player level.", fateTeleportPercentTooltip = "Fate percentage required before teleporting to it. (Hacks)", restInFatesTooltip = "Allow resting while in fate when low HP.", waitNearEvacTooltip = "Allow wating near evac postions instead of standing where you are waiting.", GrindDebugTooltip = "Enable Debug messages in console.", prioritizeClaimsTooltip = "Will claim all mobs withing set range on you for optimal drops.", claimRangeTooltip = "Range to claim when using Prioritize Claims.", attackClaimedTooltip = "Attack already clamied mobs.", doHuntingLogTooltip = "When enabled, FFXIVMinion will complete your class hunting log while grinding.", -- Mini Games CuffaCurTooltip = "Play the Cuff-a-Cur mingame.", MonsterTossTooltip = "Play the Monster Toss mingame.", TowerStrikerTooltip = "Play the Tower Striker mingame.", RandomizeGameTooltip = "Changed to a random minigame. (Time set with Random Time Min/Max)", RandomTimeMinTooltip = "Min time used when randomly changing minigames.", RandomTimeMaxTooltip = "Max time used when randomly changing minigames.", PlayTimeTooltip = "Time to play before resting.", RestTimeTooltip = "Time to rest after playing before starting again.", PostGameDelayTooltip = "Delay between starting each minigame.", -- Party Grind UseGamePartyLeaderTooltip = "Use your current party leader as the person to follow/assist.", SynctoFatesTooltip = "Will automatically Sync to Fates when withing a fate zone.", PartyLeaderTooltip = "Enter a players name to follow/assist them.", GetPartyLeaderTooltip = "Gets your current targets name and inserts it above.", --de end }, -- bk: FR ["fr"] = { startStop = "DémarrerArrêter", doPulse = "Pulse(Debug)", pulseTime = "Temps de pulse (ms)", enableLog = "Activer Log", task = "Tâche", state = "État", effect = "Effet", autoStartBot = "AutoDémarrageBot", combatMovement = "CombatMouvement", enableRepair = "AutoReparation", ignoreMarkerLevels = "IgnorerNiveauxMarqueurs", ["Bot Status"] = "StatutBot", status = "Status", settings = "Réglages", advancedSettings = "ConfigurationAvancé", vendorSettings = "ConfigurationVendeur", gatherSettings = "ConfigurationGather", skipcutscene = "Skip Cutscenes", depositItems = "Deposer Objets", checkChat = "Alerte Chat", randomfarmspot = "Utiliser FarmSpot Aléatoire", disabledrawing = "Désactiver Rendering", killaggrononfateenemies = "Tuer aggros non présent dans les fates", avoidAOE = "Avoid AOE", -- mesher.lua meshManager = "MeshManager", activated = "Activer", noMeshLoad = "No Mesh Load", mapName = "Carte", navmesh = "Navmesh", waypoint = "Waypoint", ["General"] = "Géneral", ["Auto-Equip"] = "Auto-Equip", getWaypoint = "AvoirWPMesh", useInSwitcher = "UtiliserChangeurNavMesh", enableSwitcher = "ActiverChangeur", minSwitchTime = "MinTempsChangement", maxSwitchTime = "MaxTempsChangement", switchTimer = "TempsAvantChangement", switcherSettings = "RéglagesChangeur", showMesh = "Voir Triangles ", showrealMesh = "Voir NavMesh", newMeshName = "Nom Nouvelle Navmesh", newMesh = "Effacer Navmesh", saveMesh = "Sauvegarder NavMesh", buildNAVMesh = "Construire NavMesh", recoder = "Record Mesh", connections = "Connections", editor = "Éditeur", enablePSwitch = "ActiverChangeurParanoia", pSwitchCount = "NombreJoueurParanoia", maMarkerID = "ID", maMarkerName = "Nom", -- skillmanager.lua skillbook = "Livre des Compétences", skillManager = "ManagerCompétences", skillEditor = "ÉditeurCompétences", skillEditor_craft = "ÉditeurCompétences_Craft", skillEditor_gather = "ÉditeurCompétences_Gather", saveProfile = "Savegarder Profil Courrent", newProfileName = "Nom Nouveau Profil", skillProfile = "Skill Profile", newProfile = "Create New Profile", clearProfile = "Clear Profile", skillbookrefresh = "Rafraîchir Compétences", targetType = "Cible", stepmin = "Étape >=", stepmax = "Étape <", durabmin = "Durabilité >=", durabmax = "Durabilité <", progrmin = "Progrès >=", progrmax = "Progrès <", qualitymin = "Qualité >=", qualitymax = "Qualité <", condition = "Condition =", cpmin = "CP >=", cpmax = "CP <", gpmin = "GP >=", gpmax = "GP <", iqstack = "InnerQuiet Stack >=", notused = "NotUsed", excellent = "Excellent", good = "Bon", normal = "Normal", poor = "Mauvais", centered = "Stable", sturdy = "Robuste", pliant = "Modulable", primed = "Apprêté", malleable = "Malléable", nodeHas = "As l'objet: ", gatherAttemptsMin = "Nombre d'essai de gather restant >", gatherAttemptsMax = "Nombre d'essai de gather restant <=", profile = "Profil", sMmode = "Mode Attaque", sMtargetmode = "Mode Cible", refreshProfiles = "Rafraîchir Liste Profil", deleteProfile = "Supprimer Profil Courrent", autoetectSkills = "Autodetecter Compétences", refreshSkillList = "Effacer & rafraîchir Liste de Compétences", skillEditor = "Éditeur Compétences", enabled = "Activé", appliesBuff = "Appliquer (De-)Buff", priority = "Priorité", los = "Besoin LineOfSight", instacast = "Compétence Instantannée", channeled = "Compétence de Channel", cooldown = "Cooldown", minRange = "MinRange", maxRange = "MaxRange", isGroundTargeted = "Is GroundTargeted", useOutOfCombat = "Use out of Combat", playerMoving = "Player Moving", playerHPGT = "Player HP% >", playerHPLT = "Player HP% <", playerPowerGT = "Player MP >", playerPowerLT = "Player MP <", playerHas = "Player has Buff: like 13,4152,521", orPlayerHas = "or Player has ", playerHasNot = "Player has NOT Buff: like 13,4152,521", orPlayerCond = "Player has #Conditions >", orPlayerHasNot = "or Player has NOT ", targetMoving = "Target Moving", targetHPGT = "Target HP% >", targetHPLT = "Target HP% <", targetDistanceGT = "Cible Distance >", targetDistanceLT = "Cible Distance <", enemiesNearCount = "Ennemis Proche de la cible(Count) >=", enemiesNearRange = "Ennemis Proche de la cible(MaxRange) =", alliesNearCount = "Alliés Proche de la cible(Count) >=", alliesNearRange = "Alliés Proche de la cible(MaxRange) =", targetHas = "Cible a le BuffID", orTargetHas = "ou Cible a ", targetHasNot = "Cible n'a as le BuffID", orTargetHasNot = "or Cible n'a pas ", prevSkillID = "ID compétence Précédente", AdvancedSettings = "Configuration Avancé", Fightstyle = "Fightstyle", alias = "Alias", cdIsReady = "CD Is Ready", cdNotReady = "CD Not Ready", cdTimeLT = "CD Time <=", cdTimeGT = "CD Time >=", nextSkillPrio = "Next Skill Prio", skmTYPE = "Action Type", skmSTYPE = "Skill Type", skmCombat = "Combat Status", skmCHARGE = "Charge Skill", skmLevelMin = "Level >=", skmLevelMax = "Level <=", checkSkill = "Skill ID", isReady = "Is Ready", isNotReady = "Is Not Ready", cooldownRemainingLTE = "Cooldown Remaining <=", cooldownRemainingGTE = "Cooldown Remaining >=", skmNSkillID = "Next Skill ID", skmCBreak = "Combo Breaker", skmTRG = "Skill Target", skmTRGTYPE = "Target Role", skmNPC = "Include NPC", skmPTRG = "Player Target", skmPGTRG = "Ground Target", skmPPos = "Position", skmTHPCL = "Target HP >", skmTHPCB = "Target HP <", skmTCONTIDS = "Content ID(s)", skmTNCONTIDS = "Not Content ID(s)", skmTCASTID = "Cast ID(s)", skmTCASTTM = "Cast @ Me", skmTCASTTIME = "Cast Time >", skmPTPL = "Player TP >", skmPTPB = "Player TP <", skmPMPPL = "Player MP% >", skmPMPPB = "Player MP% <", skmPAGL = "Player Aggro % >", skmPAGB = "Player Aggro % <", skmMPLock = "Causes MP Lockout", skmMPLocked = "Lockout Affected", skmMPLockPer = "MP Lockout %", skmPTCount = "Member Count >=", skmPTHPL = "Party HP% >", skmPTHPB = "Party HP% <", skmPTMPL = "Party MP% >", skmPTMPB = "Party MP% <", skmPTTPL = "Party TP >", skmPTTPB = "Party TP <", skmHPRIOHP = "Priority HP % <", skmHPRIO1 = "Heal Priority 1", skmHPRIO2 = "Heal Priority 2", skmHPRIO3 = "Heal Priority 3", skmHPRIO4 = "Heal Priority 4", skmTECount = "Enemies >=", skmTECount2 = "Enemies <=", skmTERange = "Enemy Range", skmTELevel = "Level Difference", skmTACount = "Allies >=", skmTARange = "Ally Range", skmTBuffOwner = "Buff Owner", skmHasBuffs = "Has Buffs (1+2,3)", skmMissBuffs = "Missing Buffs (1+2,3)", skmOrBuffDura = "Or Buff Dura <=", skmAndBuffDura = "And Buff Dura >", skmUnspoiled = "Unspoiled Node", up = "UP", down = "DOWN", delete = "DELETE", copy = "COPY", paste = "PASTE", --sections skillDetails = "Skill Details", skillChecks = "Other Skill Checks", basicDetails = "Basic Details", playerHPMPTP = "Player HP/MP/TP", party = "Party", target = "Target", casting = "Casting", healPriority = "Heal Priority", aoe = "AOE", playerBuffs = "Player Buffs", targetBuffs = "Target Buffs", --ffxiv stuff specific stuff botMode = "Bot Mode", addGrindSpot = "Add Grind Marker", addFishingSpot = "Add Fishing Marker", addMiningSpot = "Add Mining Marker", addBotanySpot = "Add Botany Marker", addNavSpot = "Add Nav Marker", deleteSpot = "Delete Nearest Marker", markers = "Markers", markerLevel = "Marker Level", markerMinLevel = "Marker Min Level", markerMaxLevel = "Marker Max Level", selectedMarker = "Selected Marker", noMarker = "No Marker", mining = "Mining", fishing = "Fishing", botany = "Botany", gatherTime = "Marker Timer (s)", deleteMarker = "Delete Current Marker", recmesh = "Record Mesh", recAreaType = "Record Type", recAreaSize = "Record Size", changeMesh = "Change Mesh", changeAreaType = "Change Type", changeAreaSize = "Change Size", biDirOffMesh = "Bidirectional Offmeshconnection", addOffMeshSpot = "Add OffMeshConnection", delOffMeshSpot = "Del OffMeshConnection", typeOffMeshSpot = "Type OffMeshConnection", showPath = "Show Path", selectItem1 = "Item Priority 1", selectItem2 = "Item Priority 2", selectItem3 = "Item Priority 3", selectBait = "Select Bait", baitName = "Bait Name", markerName = "Marker Name", markerPos = "Marker Position", selectClosestMarker = "Select Closest Marker", moveToMarker = "Move To Marker", gatherManager = "GatherManager", selectMarker = "Select Marker", logCNE = "Log CNE Results", useMount = "Use Mount", useSprint = "Use Sprint", gatherGardening = "Gather Gardening", gatherChocoFood = "Gather Choco Food", nodeType = "Node Type", throttle = "Throttle", repair = "Repair", questHelpers = "Quest Helpers", mount = "Mount", companion = "Companion", stance = "Stance", stFollow = "Follow", stFree = "Free Stance", stDefender = "Defender Stance", stAttacker = "Attacker Stance", stHealer = "Healer Stance", mountDist = "Mount Distance: ", sprintDist = "Sprint Distance: ", randomPaths = "Randomize Paths", botEnabled = "Bot Enabled", grindMode = "Grind", huntMode = "Hunt", huntlogMode = "Hunting Log", fishMode = "Fish", gatherMode = "Gather", assistMode = "Assist", craftMode = "Crafting", partyMode = "Party-Grind", useStealth = "Use Stealth", randomizeMarkers = "Randomize Markers", teleport = "Teleport", permaSprint = "PermaSprint", avoidHP = "Avoid HP% ", restHP = "Rest HP%: ", restMP = "Rest MP%: ", fleeHP = "Flee HP%: ", fleeMP = "Flee MP%: ", doFates = "Do Fates", fatesOnly = "Fates Only", setEvacPoint = "SetEvacPoint", restInFates = "Rest In Fates", maxFateLevel = "MaxFateLvl: +", minFateLevel = "MinFateLvl: -", waitForComplete = "WaitForComplete%: ", blacklistTimer = "BlacklistTimer (s)", fateIndex = "FateIndex", fateName = "FateName", blacklistAdd = "BlacklistAdd", blacklistRem = "BlacklistRem", enableRadar = "Enable Radar", enable2DRadar = "Enable 2D Radar", enable3DRadar = "Enable 3D Radar", fullscreenRadar = "Fullscreen (2D)", showNodes = "Show Nodes", showPlayers = "Show Players", showBattleNPCs = "Show Battle NPCs", showEventNPCs = "Show Event NPCs", showEventObjects = "Show Event Objects", showAetherytes = "Show Aetherytes", xPos = "X Position", yPos = "Y Position", assist = "Targeting Assist", assistPriority = "Priority", -- new stuff (since last translation) useMooch = "Use Mooch", markerManager = "MarkerManager", prevSkillIDNot = "Previous Skill ID NOT", secsSinceLastCast = "Secs Since Last Cast", combatRangePercent = "Combat Range %: ", blacklistManager = "BlacklistManager", createMarker = "Create Marker", editMarkers = "Edit Markers", markerType = "Marker Type", editMarkerList = "Setup List", addMarker = "Add To List", editMarker = "Edit Marker", newMarker = "New Marker", markerList = "Marker List", markerTeam = "Marker Team", setupList = "Setup List", blacklistName = "Blacklist Name", blacklistEntry = "Blacklist Entry", entryTime = "Entry Time", deleteEntry = "Delete Entry", qualityminper = "Quality % >=", qualitymaxper = "Quality % <", blacklistTarget = "Blacklist Target", addEntry = "Add Entry", blacklistFate = "Blacklist Fate", notAttackable = "Invalid Target", targetName = "Target Name", monsters = "Monsters", fates = "Fates", --************************************************* toggleOnOff = "Toggle On/Off", multiManager = "Multibot Manager", multiChannel = "Channel", multiServer = "Server IP", multiPort = "Port #", multiPass = "Password", serverInfo = "Server Information", huntMonsters = "Hunted Monsters", hunt = "Hunt", doAtma = "Do Atma", prioritizeClaims = "Prioritize Claims", claimRange = "Claim Range", attackClaimed = "Attack Claimed", alwaysKillAggro = "Always Kill Aggro", fateTeleportPercent = "Teleport %", startCombat = "Start Combat", onlySolo = "Only solo", onlyParty = "Only in party", alliesNearHPLT = "Allies HP% <", pvpMode = "PVP", pve = "PVE", both = "Both", pvpTargetType = "PVP Target Type", healer = "Healer", dps = "DPS", tank = "Tank", any = "Any", none = "None", caster = "Caster", meleeDPS = "Melee DPS", ranged = "Ranged", nearDead = "Near Dead", sleeper = "Sleeper", unattendedHealer = "Unattended Healer", prioritizeRanged = "Prioritize Ranged", combatType = "Combat Type", nearest = "Nearest", lowestHealth = "Lowest Health", highestHealth = "Highest Health", tankAssist = "Tank Assist", pvpTargetOne = "Priority 1", pvpTargetTwo = "Priority 2", pvpTargetThree = "Priority 3", pvpTargetFour = "Priority 4", pvpTargetFive = "Priority 5", pvpAvoid = "Avoidance", pvpSpeedMatchPartner = "Speed Match Partner", gatherMaps = "Gather Maps", markerFields = "Marker Fields", confirmDuty = "Auto-Confirm Duty", antiAFKMove = "Anti-AFK Move", pvpFlee = "Ranged Flee", skipCutscene = "Skip Cutscenes", skipDialogue = "Skip Dialogues", doUnstuck = "Enable Unstuck", delayLeave = "Delay Leave", defaultProfile = "Default Profile", useHQMats = "Craft HQ Mats", enterDutyTimer = "Enter Timer: ", leaveDutyTimer = "Leave Timer: ", dutyMode = "Duty", dutyLeader = "Duty Leader: ", clickToTeleport = "Click To Teleport", clickToTravel = "Click To Travel", questRunProfile = "RunQuests", questManager = "QuestManager", quests = "Quests", questEditor = "Quest Editor", questDone = "Quest Done", questInfo = "Quest Information", questSteps = "Steps", questDo = "Do Quest Now", questAddQuest = "Add New Quest", questAddStep = "Add New Step", questAddTurnover = "Add New Turn-In", questAddPreReq = "Add New Pre-Req", questID = "Quest ID", questPullID = "Pull Quest ID", questPullValues = "Pull Current Values", questJob = "Quest Job", questLevel = "Quest Level", questSave = "Save Quest", questDelete = "Delete Quest", questUp = "Higher Priority", questDown = "Lower Priority", questStepEditor = "Step Editor", questStep = "Step", questStepInfo = "Step Information", questStepDetails = "Script Details", questAddItem = "Add Item", questClearItems = "Clear Items", questItemEditor = "Item Editor", newItem = "New Item", stepItemAmount = "Amount", items = "Items", convoIndex = "Conversation #", dutyEncounters = "Duty Encounters", dutyEncounterEditor = "Edit Duty Encounter", questStepScript = "Task-Script", questStepDelete = "Delete Step", questStepSave = "Save Step", questTurnoverEditor = "Turn-In Editor", questPreReqEditor = "Prerequisite Editor", questName = "Name", questMinLevel = "Min Level", questMaxLevel = "Max Level", questPreQuest = "Needs Previous Quest", questMap = "Map", questRepeat = "Repeatable", questStepDone = "Step Done", questReset = "Reset Questprogress", markerMode = "Marker Mode", markerList = "Marker List", markerTeam = "Marker Team", singleMarker = "Single Marker", randomMarker = "Random Marker", questMode = "Quest", removeMarker = "Remove Marker", deleteMarker = "Delete Marker", PartyGrind = "Party Grind", PartyLeader = "Leader", GetPartyLeader = "Target->Leader", UseGamePartyLeader = "Use Party Leader", TargetIsCasting = "Target Casting", TargetCastingOnMe = "Casting On", TargetCastingTime = "Casting Time >", botanyMarker = "Botany Marker", miningMarker = "Mining Marker", grindMarker = "Grind Marker", huntMarker = "Hunt Marker", pvpMarker = "PVP Marker", unspoiledMarker = "Unspoiled Marker", contentIDEquals = "ContentID=", NOTcontentIDEquals = "NOT ContentID=", fishingMarker = "Fishing Marker", time = "Time (s)", name = "Name", minLevel = "Min Level", maxLevel = "Max Level", markerTime = "Marker Time (s)", useAetherytes = "Use Aetherytes", resetDutyTimer = "Reset Timer: ", createProfile = "Create Profile", existingProfile = "Existing Profile:", profileType = "Profile Type:", customTask = "Custom Task", addEncounter = "Add Encounter", details = "Details", newEncounter = "New Encounter", newQuest = "New Quest", editQuestStep = "Edit Quest Step", newQuestStep = "New Step", newQuestTurnover = "New Turn-In", newQuestPreReq = "New Pre-Req", questEditSteps = "Edit Steps", questEditPreReqs = "Edit Pre-Reqs", questEditTurnovers = "Edit Turn-Ins", stepCurrent = "Current Step", stepTask = "Step Task", stepItemSelector = "Select Item", stepItemID = "Item ID", stepQuestID = "Quest ID", stepTaskCustom = "Step Task Custom", stepMap = "Map ID", stepMesh = "Mesh Name", stepTarget = "Step Target", stepAction = "Action ID", stepCommandString = "Command String", stepKillCount = "Kill Count", stepDelay = "Delay", stepReward = "Reward Slot", stepClear = "Clear All Steps", prereqJob = "PreReq Job", prereqStep = "PreReq Step", prereqID = "PreReq ID", prereqClear = "Clear All PreReqs", turnoverStep = "Step #:", turnoverID = "Turn-In ID", turnoverSlot = "Item Slot", turnoverClear = "Clear All Turn-Ins", profileManager = "Profile Manager", advancedSettings = "Advanced Settings", hacks = "Hacks", newLocation = "New Location", startLocation = "Start Location", addLocation = "Add Location", saveLocation = "Save Location", moveLocation = "Move Location", removeLocation = "Remove Location", minimumGP = "Minimum GP", locationEditor = "Location Editor", locationName = "Location Name", useCordials = "Use Cordials", gatherUnspoiled = "Gather Unspoiled", minerGearset = "Miner Gearset", botanistGearset = "Botanist Gearset", refreshMap = "Refresh Map", hour = "Hour", class = "Class", isIdle = "Is Idle", objectiveIndex = "Objective Index", stepIndex = "Step Index", killCount = "Kill Count", autoEquip = "Auto-Equip", idlePulseCount = "Idle Count", taskDelay = "Task Delay (ms)", eorzeaTime = "Eorzea Time", potionHP = "Potion HP", potionMP = "Potion MP", importExport = "Import / Export", autoExport = "Auto Export", fileName = "File Name", gatherLocations = "Gather Locations", huntLocations = "Hunt Locations", basicExport = "Basic Export", basicImport = "Basic Import", markerImport = "Marker Import", overwriteExisting = "Overwrite Existing", allMarkers = "All Markers", exportSettings = "Export Settings", importSettings = "Import Settings", exportGlobal = "Export Global", importGlobal = "Import Global", minimumCP = "Minimum CP", craftAmount = "Craft Amount", paranoid = "Paranoid", permaSwiftcast = "PermaSwiftCast", castPrevention = "Cast Prevention", shortcutManager = "Shortcut Manager", food = "Food", foodHQ = "Food HQ", curielRoot = "Curiel Root", whitelistTarget = "Whitelist Target", validSlots = "Valid Slots", quickStartMode = "QuickStart", totMin = "ToT >=", totMax = "ToT <", htSucceedMax = "Hasty Touch Success <", shStackMin = "Steady Hand Stack >=", manipMax = "Manipulation Uses <", doHuntingLog = "Do Hunting Log", frontlines = "Les Ruines frontalières", confirm = "Confirm", yes = "Yes", no = "No", debugging = "Debugging", debugItems = "Debug Items", prevComboSkill = "Previous Combo Skill", prevComboSkillNot = "Previous Combo Skill NOT", currentActionNot = "Current Action NOT", filter1 = "Filter 1", filter2 = "Filter 2", filter3 = "Filter 3", filter4 = "Filter 4", filter5 = "Filter 5", underAttack = "Under Attack", hpAdvantage = "HP Advantage >=", targetTPLE = "Target TP <=", targetMPLE = "Target MP <=", performance = "Performance", loot = "Loot", telecast = "Telecast", need = "Need", greed = "Greed", pass = "Pass", extreme = "Extreme", fast = "Fast", --normal = "Normal", slow = "Slow", shortcut = "Shortcut", modifierKey = "Modifier Key", shortcutKey = "Shortcut Key", waitNearEvac = "Wait Near Evac", randomMovement = "Randomize Movement", underAttackMelee = "Under Attack (Melee)", chain = "Chain", chainStart = "Chain Start", chainEnd = "Chain End", enmityAOE = "Enmity AOE", frontalCone = "Frontal Cone", tankedTargetsOnly = "Tanked Targets Only", aoeCenter = "AOE Center", comboSkill = "Combo Skill", offGCDSkill = "Off GCD Skill", removesBuff = "Removes Buff", minContentLevel = "Min Content Level", maxContentLevel = "Max Content Level", maxRadius = "Max Radius", dangerousArea = "Dangerous Area", usePatience = "Use Patience", usePatience2 = "Use Patience II", useChum = "Use Chum", moochableFish = "Moochable Fish", whitelistFish = "Whitelist Fish", whitelistFishHQ = "Whitelist Fish (HQ)", blacklistFish = "Blacklist Fish", blacklistFishHQ = "Blacklist Fish (HQ)", singleUse = "Single Use", --===== Added 9/20/15 - Sebbs maxdurabmin = "Max Durabilité >=", maxdurabmax = "Max Durabilité <", maxprogrmin = "Max Progrès >=", maxprogrmax = "Max Progrès <", --===== Added 9/23/15 - Sebbs -- Help assisthelp = "Assist Mode will... \ \ You Steer, we Shoot. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", grindhelp = "Grind Mode will... \ \ Do Fates, Huntlogs and Grind Mobs. \ \ Only for COMBAT Classes. \ \ While we endevour to Automate Settings, \ Settings can be changed if Advanced Settings is enabled. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", gatherhelp = "Gather Mode will... \ \ Use Markers, Profiles or Quickstart. \ Only for Miner or Botanist. \ \ Skills use are set by Skill Profile", fishhelp = "Fish Mode will... \ \ Use Markers, Profiles or Quickstart. \ \ Only for Fisher. \ \ Skills are NOT set via Skill Profile. \ Set Skills Via Marker or Profiles.", -- Faq assistfaq = "My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job. \ Is Start combat Checked?", grindfaq = "My Bot Doesnt move? \ \ Are any valid Fates Available? \ Are Max Fate settings to low? \ \ My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job.", gatherhfaq = "Bot Doesnt move? \ \ Profile has no valid tasks? \ Markers have radius to small? \ Heavensward or Stormblood may need Marker list.", fishfaq = "Bot Doesnt Fish? \ \ Profile has no valid tasks? \ Current location has Lockout out due to fishing Limit?", -- Missing GUI strings 09/27/17 HusbandoMax -- Shared debugLevel = "Debug Level", addCollectable = "Add Collectable", itemName = "Item Name", minValue = "Min Value", noProfileSelected = "Please select/create a valid profile.", markerMode = "Marker Mode", markerType = "Marker Type", useCordials = "Use Cordials.", collectablePresets = "Use Known Defaults", expManuals = "Use Experience Manuals", -- Assist followTarget = "Follow Target", faceTarget = "Face Target", clientAutoface = "Using Client Autoface", -- Craft forSingleCraftsOnly = "For Single Crafts Only", craftDebug = "Craft Debug", useHQMats = "Use HQ Mats", onlyIfNecesssary = "Only If Necesssary", -- Fish fishMarkerProfileMode = "Fish Mode", baitType = "Bait Type", -- Fish Actions mooch = "Mooch", mooch2 = "Mooch II", patience = "Patience", patience2 = "Patience II", snagging = "Snagging", fishEyes = "Fish Eyes", chum = "Chum", doubleHook = "Double Hook", fishDebug = "Fish Debug", -- Gather gatherDebug = "Gather Debug", gatherMarkerProfileMode = "Gather Mode", minGPHighCordial = "Min GP - High Cordial", minGPCordial = "Min GP - Cordial", minGPWateredCordial = "Min GP - Watered Cordial", stealthDetectRange = "Stealth - Detect Range", stealthRemoveRange = "Stealth - Remove Range", smartStealth = "Smart Stealth", gatherSlotQuickstart = "Gather Slot", mapsQuickstart = "Maps", gardeningQuickstart = "Gardening", raresQuickstart = "Rares", superRaresQuickstart = "Super Rares", chocoboFoodQuickstart = "Chocobo Food", -- Grind AutoLevelMode = "Auto-Level Mode", ModifyAutoGrind = "Modify Auto-Grind", DoOnlyFates = "Do Only Fates", KillNonFateAggro = "Kill Non-Fate Aggro", AdvancedSettings = "Advanced Settings", DoLuminous = "Do Luminous", FateType = "Fate Type", Enable = "Enable", Startat = "Start at %%", Chain = "Chain", Battle = "Battle", Boss = "Boss", Grind = "Grind", Defense = "Defense", Escort = "Escort", MinFateLv = "Min Fate Lv.", SetNoMinFateLevel = "No Min Fate Level", MaxFateLv = "Max Fate Lv.", SetNoMaxFateLevel = "No Max Fate Level", GrindDebug = "Grind Debug", -- Mini Games CuffaCur = "Cuff-a-Cur", MonsterToss = "Monster Toss", TowerStriker = "Tower Striker", RandomizeGame = "Randomize Game", RandomTimeMin = "Random Time Min (m)", RandomTimeMax = "Random Time Max (m)", PlayTime = "Play Time (m)", RestTime = "Rest Time (m)", PostGameDelay = "Post-Game Delay (ms)", -- Party Grind SynctoFates = "Sync to Fates", -- Tooltips :D 09/27/17 HusbandoMax -- Shared debugLevelTooltip = "Change the Debug message level. (The higher the number the more detailed the messages)", addCollectableTooltip = "Add a new Collectable to the list below.", itemNameCollectableTooltip = "Case-sensitive item name for the item to become a collectable.", itemRaitingCollectableTooltip = "Minimum collectable value at which the item will be accepted as a collectable.", profileTooltip = "The profile to be used in the current mode. (Crafting Orders, Gathering, Fishing)", markerModeTooltip = "Select Single,Random or List.", markerTypeTooltip = "Marker type to show in the list below.", useCordialsTooltip = "Allow use of Cordials for GP.", collectablePresetsTooltip = "Add Known Collectables to the list below.", -- Assist assistTooltip = "None: Use manual targetting.\ Lowest Health: Targets the lowest health target within range.\ Highest Health: Targets the highest health target within range.\ Nearest: Targets the closest target within range.\ Tank Assist: Targets whatever your tank is targetting.", assistPriorityTooltip = "Prioritize Damage or Healing.", followTargetTooltip = "Attempts to continually follow the target (useful in PvP).", faceTargetTooltip = "Attempts to continually face the target.\nWarning: Dangerous if using Standard movement mode.", clientAutofaceTooltip = "This option should be turned on if you are using the game client's [Face Target on Attack] options.", startCombatTooltip = "If this option is off, the bot will not attack a mob that is not in combat already.", confirmDutyTooltip = "Auto accepts Duty Queue.", -- Craft craftingOrderEditTooltip = "Opens the Crafting Order Editor.", craftingOrderCreateTooltip = "Creates a New Crafting Order profile.", expManualsTooltip = "Allow use of Experience boost manuals.", craftDebugTooltip = "Enable Debug messages in console.", forSingleCraftsOnlyTooltip = "These settings are for Single Craft (When no profile is selected)", craftAmountTooltip = "Haw many crafts to complete before stopping.", minimumCPTooltip = "CP required before starting the craft. (Useful for CP food)", useHQMatsTooltip = "Allow the use of HQ materials while crafting.", onlyIfNecesssaryTooltip = "Only use HQ materials if there are no NQ materials left.", -- Fish fishMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", baitTypeTooltip = "Bait to be used in Quick Start mode.", -- Fish Actions moochTooltip = "Allow fish mooching.", mooch2Tooltip = "Allow fish mooching (Mooch 2).", patienceTooltip = "Use Patience while fishing.", patience2Tooltip = "Use Patience 2 while fishing.", snaggingTooltip = "Apply the Snagging buff when fishing.", fishEyesTooltip = "Apply the Fish Eyes buff when fishing.", chumTooltip = "Use Chum while fishing.", doubleHookTooltip = "Use Double Hook.", fishDebugTooltip = "Enable Debug messages in console.", -- Gather gatherDebugTooltip = "Enable Debug messages in console.", gatherMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", minGPHighCordialTooltip = "Min GP required before using a High Cordial.", minGPCordialTooltip = "Min GP required before using a Cordial.", minGPWateredCordialTooltip = "Min GP required before using a Watered Cordial.", stealthDetectRangeTooltip = "Enemy range before applying Stealth.", stealthRemoveRangeTooltip = "Enemy range before removing Stealth.", smartStealthTooltip = "Smarter Stealth based on players direction and mob.", gatherSlotQuickstartTooltip = "Set the item slot to gather.", mapsQuickstartTooltip = "Gather Maps when avalible.", gardeningQuickstartTooltip = "Gather Gardening when avalible.", raresQuickstartTooltip = "Gather Rares when avalible.", superRaresQuickstartTooltip = "Gather Super Rares when avalible.", chocoboFoodQuickstartTooltip = "Gather Chocobo Food when avalible.", -- Grind AutoLevelModeTooltip = "Automatically switch maps to continue leveling in an optimal area.", ModifyAutoGrindTooltip = "Opens a GUI to edit the Auto-Level code", doFatesTooltip = "When enabled, the bot will complete FATEs in addition to mob-grinding.", DoOnlyFatesTooltip = "When enabled, the bot will idle between FATEs, and will not perform mob-grinding.", KillNonFateAggroTooltip = "Kills any Non-Fate Aggro", AdvancedSettingsTooltip = "Enable use of Advanced Settings", DoAtmaTooltip = "Grind Atma crystals and moves to the next zones. (Relic)", DoLuminousTooltip = "Grind Luminous crystals and moves to the next zones. (Relic)", MinFateLvTooltip = "Number of levels below current Player level.", SetNoMinFateLevelTooltip = "Number of levels below current Player level.", MaxFateLvTooltip = "Number of levels above current Player level.", SetNoMaxFateLevelTooltip = "Number of levels above current Player level.", fateTeleportPercentTooltip = "Fate percentage required before teleporting to it. (Hacks)", restInFatesTooltip = "Allow resting while in fate when low HP.", waitNearEvacTooltip = "Allow wating near evac postions instead of standing where you are waiting.", GrindDebugTooltip = "Enable Debug messages in console.", prioritizeClaimsTooltip = "Will claim all mobs withing set range on you for optimal drops.", claimRangeTooltip = "Range to claim when using Prioritize Claims.", attackClaimedTooltip = "Attack already clamied mobs.", doHuntingLogTooltip = "When enabled, FFXIVMinion will complete your class hunting log while grinding.", -- Mini Games CuffaCurTooltip = "Play the Cuff-a-Cur mingame.", MonsterTossTooltip = "Play the Monster Toss mingame.", TowerStrikerTooltip = "Play the Tower Striker mingame.", RandomizeGameTooltip = "Changed to a random minigame. (Time set with Random Time Min/Max)", RandomTimeMinTooltip = "Min time used when randomly changing minigames.", RandomTimeMaxTooltip = "Max time used when randomly changing minigames.", PlayTimeTooltip = "Time to play before resting.", RestTimeTooltip = "Time to rest after playing before starting again.", PostGameDelayTooltip = "Delay between starting each minigame.", -- Party Grind UseGamePartyLeaderTooltip = "Use your current party leader as the person to follow/assist.", SynctoFatesTooltip = "Will automatically Sync to Fates when withing a fate zone.", PartyLeaderTooltip = "Enter a players name to follow/assist them.", GetPartyLeaderTooltip = "Gets your current targets name and inserts it above.", --FR end }, -- bk: RU ["ru"] = { startStop = "StartStop", doPulse = "Pulse(Debug)", pulseTime = "Pulse Time (ms)", enableLog = "Enable Log", task = "Task", state = "State", effect = "Effect", autoStartBot = "AutoStartBot", combatMovement = "CombatMovement", enableRepair = "AutoRepair", ignoreMarkerLevels = "IgnoreMarkerLevels", ["Bot Status"] = "BotStatus", settings = "Settings", status = "Status", advancedSettings = "Advanced Settings", vendorSettings = "VendorSettings", gatherSettings = "GatherSettings", skipcutscene = "Skip Cutscenes", depositItems = "Deposit Items", checkChat = "Chat Alert", randomfarmspot = "Use Random Farmspots", disabledrawing = "Disable Rendering", killaggrononfateenemies = "Kill attacking None-Fate Enemies", avoidAOE = "Avoid AOE", -- mesher.lua meshManager = "MeshManager", activated = "Activated", noMeshLoad = "No Mesh Load", mapName = "Map", navmesh = "Navmesh", waypoint = "Waypoint", ["General"] = "General", ["Auto-Equip"] = "Auto-Equip", getWaypoint = "GetMeshWP", useInSwitcher = "UseInSwitcher", enableSwitcher = "EnableSwitcher", minSwitchTime = "MinSwitchTime", maxSwitchTime = "MaxSwitchTime", switchTimer = "TimeUntilSwitch", switcherSettings = "SwitcherSettings", showMesh = "Show Triangles ", showrealMesh = "Show NavMesh", newMeshName = "New Meshfile Name", newMesh = "Clear Navmesh", saveMesh = "Save NavMesh", buildNAVMesh = "Build NavMesh", editor = "Editor", recoder = "Record Mesh", connections = "Connections", enablePSwitch = "EnableParanoiaSwitch", pSwitchCount = "ParanoiaPlayerCount", maMarkerID = "ID", maMarkerName = "Name", -- skillmanager.lua skillbook = "SkillBook", skillManager = "SkillManager", skillEditor = "SkillEditor", skillEditor_craft = "SkillEditor_Crafting", skillEditor_gather = "SkillEditor_Gathering", saveProfile = "Save Profile", newProfileName = "New Profile", skillProfile = "Skill Profile", newProfile = "Create New Profile", clearProfile = "Clear Profile", skillbookrefresh = "Refresh Skills", targetType = "Target", stepmin = "Step >=", stepmax = "Step <", durabmin = "Durability >=", durabmax = "Durability <", progrmin = "Progress >=", progrmax = "Progress <", qualitymin = "Quality >=", qualitymax = "Quality <", condition = "Condition =", cpmin = "CP >=", cpmax = "CP <", gpmin = "GP >=", gpmax = "GP <", iqstack = "InnerQuiet Stack >=", notused = "NotUsed", excellent = "Excellent", good = "Good", normal = "Normal", poor = "Poor", centered = "Centered", sturdy = "Sturdy", pliant = "Pliant", nodeHas = "Has Item: ", gatherAttemptsMin = "Attempts Remaining >", gatherAttemptsMax = "Attempts Remaining <=", profile = "Profile", sMmode = "Attack Mode", sMtargetmode = "Target Mode", refreshProfiles = "Refresh Profile List", deleteProfile = "Delete Current Profile", autoetectSkills = "Autodetect Skills", refreshSkillList = "Clear & Refresh SkillList", skillEditor = "Skill Editor", enabled = "Enabled", appliesBuff = "Applies (De-)Buff", priority = "Priority", los = "Needs LineOfSight", instacast = "Instant Skill", channeled = "Channel Skill", cooldown = "Cooldown", minRange = "Min Range", maxRange = "Max Range", isGroundTargeted = "Is GroundTargeted", useOutOfCombat = "Use out of Combat", playerMoving = "Player Moving", playerHPGT = "Player HP% >", playerHPLT = "Player HP% <", playerPowerGT = "Player MP >", playerPowerLT = "Player MP <", playerHas = "Player has Buff: like 13,4152,521", orPlayerHas = "or Player has ", playerHasNot = "Player has NOT Buff: like 13,4152,521", orPlayerCond = "Player has #Conditions >", orPlayerHasNot = "or Player has NOT ", targetMoving = "Target Moving", targetHPGT = "Target HP% >", targetHPLT = "Target HP% <", targetDistanceGT = "Target Distance >", targetDistanceLT = "Target Distance <", enemiesNearCount = "Enemies Near Target(Count) >=", enemiesNearRange = "Enemies Near Target(MaxRange) =", alliesNearCount = "Allies Near Target(Count) >=", alliesNearRange = "Allies Near Target(MaxRange) =", targetHas = "Target has Buff : like 13,4152,521", orTargetHas = "or Target has ", targetHasNot = "Target has NOT Buff : like 13,4152,521", orTargetHasNot = "or Target has NOT ", prevSkillID = "Previous Skill ID", AdvancedSettings = "Advanced Settings", Fightstyle = "Fightstyle", alias = "Alias", cdIsReady = "CD Is Ready", cdNotReady = "CD Not Ready", cdTimeLT = "CD Time <=", cdTimeGT = "CD Time >=", nextSkillPrio = "Next Skill Prio", skmTYPE = "Action Type", skmSTYPE = "Skill Type", skmCombat = "Combat Status", skmCHARGE = "Charge Skill", skmLevelMin = "Level >=", skmLevelMax = "Level <=", checkSkill = "Skill ID", isReady = "Is Ready", isNotReady = "Is Not Ready", cooldownRemainingLTE = "Cooldown Remaining <=", cooldownRemainingGTE = "Cooldown Remaining >=", skmNSkillID = "Next Skill ID", skmCBreak = "Combo Breaker", skmTRG = "Skill Target", skmTRGTYPE = "Target Role", skmNPC = "Include NPC", skmPTRG = "Player Target", skmPGTRG = "Ground Target", skmPPos = "Position", skmTHPCL = "Target HP >", skmTHPCB = "Target HP <", skmTCONTIDS = "Content ID(s)", skmTNCONTIDS = "Not Content ID(s)", skmTCASTID = "Cast ID(s)", skmTCASTTM = "Cast @ Me", skmTCASTTIME = "Cast Time >", skmPTPL = "Player TP >", skmPTPB = "Player TP <", skmPMPPL = "Player MP% >", skmPMPPB = "Player MP% <", skmPAGL = "Player Aggro % >", skmPAGB = "Player Aggro % <", skmMPLock = "Causes MP Lockout", skmMPLocked = "Lockout Affected", skmMPLockPer = "MP Lockout %", skmPTCount = "Member Count >=", skmPTHPL = "Party HP% >", skmPTHPB = "Party HP% <", skmPTMPL = "Party MP% >", skmPTMPB = "Party MP% <", skmPTTPL = "Party TP >", skmPTTPB = "Party TP <", skmHPRIOHP = "Priority HP % <", skmHPRIO1 = "Heal Priority 1", skmHPRIO2 = "Heal Priority 2", skmHPRIO3 = "Heal Priority 3", skmHPRIO4 = "Heal Priority 4", skmTECount = "Enemies >=", skmTECount2 = "Enemies <=", skmTERange = "Enemy Range", skmTELevel = "Level Difference", skmTACount = "Allies >=", skmTARange = "Ally Range", skmTBuffOwner = "Buff Owner", skmHasBuffs = "Has Buffs (1+2,3)", skmMissBuffs = "Missing Buffs (1+2,3)", skmOrBuffDura = "Or Buff Dura <=", skmAndBuffDura = "And Buff Dura >", skmUnspoiled = "Unspoiled Node", up = "UP", down = "DOWN", delete = "DELETE", copy = "COPY", paste = "PASTE", --sections skillDetails = "Skill Details", skillChecks = "Other Skill Checks", basicDetails = "Basic Details", playerHPMPTP = "Player HP/MP/TP", party = "Party", target = "Target", casting = "Casting", healPriority = "Heal Priority", aoe = "AOE", playerBuffs = "Player Buffs", targetBuffs = "Target Buffs", --ffxiv stuff specific stuff botMode = "Bot Mode", addGrindSpot = "Add Grind Marker", addFishingSpot = "Add Fishing Marker", addMiningSpot = "Add Mining Marker", addBotanySpot = "Add Botany Marker", addNavSpot = "Add Nav Marker", deleteSpot = "Delete Nearest Marker", markers = "Markers", markerLevel = "Marker Level", markerMinLevel = "Marker Min Level", markerMaxLevel = "Marker Max Level", selectedMarker = "Selected Marker", noMarker = "No Marker", mining = "Mining", fishing = "Fishing", botany = "Botany", gatherTime = "Marker Timer (s)", deleteMarker = "Delete Current Marker", recmesh = "Record Mesh", recAreaType = "Record Type", recAreaSize = "Record Size", changeMesh = "Change Mesh", changeAreaType = "Change Type", changeAreaSize = "Change Size", biDirOffMesh = "Bidirectional Offmeshconnection", addOffMeshSpot = "Add OffMeshConnection", delOffMeshSpot = "Del OffMeshConnection", typeOffMeshSpot = "Type OffMeshConnection", showPath = "Show Path", selectItem1 = "Item Priority 1", selectItem2 = "Item Priority 2", selectItem3 = "Item Priority 3", selectBait = "Select Bait", baitName = "Bait Name", markerName = "Marker Name", markerPos = "Marker Position", selectClosestMarker = "Select Closest Marker", moveToMarker = "Move To Marker", gatherManager = "GatherManager", selectMarker = "Select Marker", logCNE = "Log CNE Results", useMount = "Use Mount", useSprint = "Use Sprint", gatherGardening = "Gather Gardening", gatherChocoFood = "Gather Choco Food", nodeType = "Node Type", throttle = "Throttle", repair = "Repair", questHelpers = "Quest Helpers", mount = "Mount", companion = "Companion", stance = "Stance", stFollow = "Follow", stFree = "Free Stance", stDefender = "Defender Stance", stAttacker = "Attacker Stance", stHealer = "Healer Stance", mountDist = "Mount Distance: ", sprintDist = "Sprint Distance: ", randomPaths = "Randomize Paths", botEnabled = "Bot Enabled", grindMode = "Grind", huntMode = "Hunt", huntlogMode = "Hunting Log", fishMode = "Fish", gatherMode = "Gather", assistMode = "Assist", craftMode = "Crafting", partyMode = "Party-Grind", useStealth = "Use Stealth", randomizeMarkers = "Randomize Markers", teleport = "Teleport", permaSprint = "PermaSprint", avoidHP = "Avoid HP% ", restHP = "Rest HP%: ", restMP = "Rest MP%: ", fleeHP = "Flee HP%: ", fleeMP = "Flee MP%: ", doFates = "Do Fates", fatesOnly = "Fates Only", setEvacPoint = "SetEvacPoint", restInFates = "Rest In Fates", maxFateLevel = "MaxFateLvl: +", minFateLevel = "MinFateLvl: -", waitForComplete = "WaitForComplete%: ", blacklistTimer = "BlacklistTimer (s)", fateIndex = "FateIndex", fateName = "FateName", blacklistAdd = "BlacklistAdd", blacklistRem = "BlacklistRem", enableRadar = "Enable Radar", enable2DRadar = "Enable 2D Radar", enable3DRadar = "Enable 3D Radar", fullscreenRadar = "Fullscreen (2D)", showNodes = "Show Nodes", showPlayers = "Show Players", showBattleNPCs = "Show Battle NPCs", showEventNPCs = "Show Event NPCs", showEventObjects = "Show Event Objects", showAetherytes = "Show Aetherytes", xPos = "X Position", yPos = "Y Position", assist = "Targeting Assist", assistPriority = "Priority", -- new stuff (since last translation) useMooch = "Use Mooch", markerManager = "MarkerManager", prevSkillIDNot = "Previous Skill ID NOT", secsSinceLastCast = "Secs Since Last Cast", combatRangePercent = "Combat Range %: ", blacklistManager = "BlacklistManager", createMarker = "Create Marker", editMarkers = "Edit Markers", markerType = "Marker Type", editMarkerList = "Setup List", addMarker = "Add To List", editMarker = "Edit Marker", newMarker = "New Marker", markerList = "Marker List", setupList = "Setup List", blacklistName = "Blacklist Name", blacklistEntry = "Blacklist Entry", entryTime = "Entry Time", deleteEntry = "Delete Entry", qualityminper = "Quality % >=", qualitymaxper = "Quality % <", blacklistTarget = "Blacklist Target", addEntry = "Add Entry", blacklistFate = "Blacklist Fate", notAttackable = "Invalid Target", targetName = "Target Name", monsters = "Monsters", fates = "Fates", --************************************************* toggleOnOff = "Toggle On/Off", multiManager = "Multibot Manager", multiChannel = "Channel", multiServer = "Server IP", multiPort = "Port #", multiPass = "Password", serverInfo = "Server Information", huntMonsters = "Hunted Monsters", hunt = "Hunt", doAtma = "Do Atma", prioritizeClaims = "Prioritize Claims", claimRange = "Claim Range", attackClaimed = "Attack Claimed", alwaysKillAggro = "Always Kill Aggro", fateTeleportPercent = "Teleport %", startCombat = "Start Combat", onlySolo = "Only solo", onlyParty = "Only in party", alliesNearHPLT = "Allies HP% <", pvpMode = "PVP", pve = "PVE", both = "Both", pvpTargetType = "PVP Target Type", healer = "Healer", dps = "DPS", tank = "Tank", any = "Any", none = "None", caster = "Caster", meleeDPS = "Melee DPS", ranged = "Ranged", nearDead = "Near Dead", sleeper = "Sleeper", unattendedHealer = "Unattended Healer", prioritizeRanged = "Prioritize Ranged", combatType = "Combat Type", nearest = "Nearest", lowestHealth = "Lowest Health", highestHealth = "Highest Health", tankAssist = "Tank Assist", pvpTargetOne = "Priority 1", pvpTargetTwo = "Priority 2", pvpTargetThree = "Priority 3", pvpTargetFour = "Priority 4", pvpTargetFive = "Priority 5", pvpAvoid = "Avoidance", pvpSpeedMatchPartner = "Speed Match Partner", gatherMaps = "Gather Maps", markerFields = "Marker Fields", confirmDuty = "Auto-Confirm Duty", antiAFKMove = "Anti-AFK Move", pvpFlee = "Ranged Flee", skipCutscene = "Skip Cutscenes", skipDialogue = "Skip Dialogues", doUnstuck = "Enable Unstuck", delayLeave = "Delay Leave", defaultProfile = "Default Profile", useHQMats = "Craft HQ Mats", enterDutyTimer = "Enter Timer: ", leaveDutyTimer = "Leave Timer: ", dutyMode = "Duty", dutyLeader = "Duty Leader: ", clickToTeleport = "Click To Teleport", clickToTravel = "Click To Travel", questRunProfile = "RunQuests", questManager = "QuestManager", quests = "Quests", questEditor = "Quest Editor", questDone = "Quest Done", questInfo = "Quest Information", questSteps = "Steps", questDo = "Do Quest Now", questAddQuest = "Add New Quest", questAddStep = "Add New Step", questAddTurnover = "Add New Turn-In", questAddPreReq = "Add New Pre-Req", questID = "Quest ID", questPullID = "Pull Quest ID", questPullValues = "Pull Current Values", questJob = "Quest Job", questLevel = "Quest Level", questSave = "Save Quest", questDelete = "Delete Quest", questUp = "Higher Priority", questDown = "Lower Priority", questStepEditor = "Step Editor", questStep = "Step", questStepInfo = "Step Information", questStepDetails = "Script Details", questAddItem = "Add Item", questClearItems = "Clear Items", questItemEditor = "Item Editor", newItem = "New Item", stepItemAmount = "Amount", items = "Items", convoIndex = "Conversation #", dutyEncounters = "Duty Encounters", dutyEncounterEditor = "Edit Duty Encounter", questStepScript = "Task-Script", questStepDelete = "Delete Step", questStepSave = "Save Step", questTurnoverEditor = "Turn-In Editor", questPreReqEditor = "Prerequisite Editor", questName = "Name", questMinLevel = "Min Level", questMaxLevel = "Max Level", questPreQuest = "Needs Previous Quest", questMap = "Map", questRepeat = "Repeatable", questStepDone = "Step Done", questReset = "Reset Questprogress", markerMode = "Marker Mode", markerList = "Marker List", markerTeam = "Marker Team", singleMarker = "Single Marker", randomMarker = "Random Marker", questMode = "Quest", removeMarker = "Remove Marker", deleteMarker = "Delete Marker", PartyGrind = "Party Grind", PartyLeader = "Leader", GetPartyLeader = "Target->Leader", UseGamePartyLeader = "Use Party Leader", TargetIsCasting = "Target Casting", TargetCastingOnMe = "Casting On", TargetCastingTime = "Casting Time >", botanyMarker = "Botany Marker", miningMarker = "Mining Marker", grindMarker = "Grind Marker", huntMarker = "Hunt Marker", pvpMarker = "PVP Marker", unspoiledMarker = "Unspoiled Marker", contentIDEquals = "ContentID=", NOTcontentIDEquals = "NOT ContentID=", fishingMarker = "Fishing Marker", time = "Time (s)", name = "Name", minLevel = "Min Level", maxLevel = "Max Level", markerTime = "Marker Time (s)", useAetherytes = "Use Aetherytes", resetDutyTimer = "Reset Timer: ", createProfile = "Create Profile", existingProfile = "Existing Profile:", profileType = "Profile Type:", customTask = "Custom Task", addEncounter = "Add Encounter", details = "Details", newEncounter = "New Encounter", newQuest = "New Quest", editQuestStep = "Edit Quest Step", newQuestStep = "New Step", newQuestTurnover = "New Turn-In", newQuestPreReq = "New Pre-Req", questEditSteps = "Edit Steps", questEditPreReqs = "Edit Pre-Reqs", questEditTurnovers = "Edit Turn-Ins", stepCurrent = "Current Step", stepTask = "Step Task", stepItemSelector = "Select Item", stepItemID = "Item ID", stepQuestID = "Quest ID", stepTaskCustom = "Step Task Custom", stepMap = "Map ID", stepMesh = "Mesh Name", stepTarget = "Step Target", stepAction = "Action ID", stepCommandString = "Command String", stepKillCount = "Kill Count", stepDelay = "Delay", stepReward = "Reward Slot", stepClear = "Clear All Steps", prereqJob = "PreReq Job", prereqStep = "PreReq Step", prereqID = "PreReq ID", prereqClear = "Clear All PreReqs", turnoverStep = "Step #:", turnoverID = "Turn-In ID", turnoverSlot = "Item Slot", turnoverClear = "Clear All Turn-Ins", profileManager = "Profile Manager", advancedSettings = "Advanced Settings", hacks = "Hacks", newLocation = "New Location", startLocation = "Start Location", addLocation = "Add Location", saveLocation = "Save Location", moveLocation = "Move Location", removeLocation = "Remove Location", minimumGP = "Minimum GP", locationEditor = "Location Editor", locationName = "Location Name", useCordials = "Use Cordials", gatherUnspoiled = "Gather Unspoiled", minerGearset = "Miner Gearset", botanistGearset = "Botanist Gearset", refreshMap = "Refresh Map", hour = "Hour", class = "Class", isIdle = "Is Idle", objectiveIndex = "Objective Index", stepIndex = "Step Index", killCount = "Kill Count", autoEquip = "Auto-Equip", idlePulseCount = "Idle Count", taskDelay = "Task Delay (ms)", eorzeaTime = "Eorzea Time", potionHP = "Potion HP", potionMP = "Potion MP", importExport = "Import / Export", autoExport = "Auto Export", fileName = "File Name", gatherLocations = "Gather Locations", huntLocations = "Hunt Locations", basicExport = "Basic Export", basicImport = "Basic Import", markerImport = "Marker Import", overwriteExisting = "Overwrite Existing", allMarkers = "All Markers", exportSettings = "Export Settings", importSettings = "Import Settings", exportGlobal = "Export Global", importGlobal = "Import Global", minimumCP = "Minimum CP", craftAmount = "Craft Amount", paranoid = "Paranoid", permaSwiftcast = "PermaSwiftCast", castPrevention = "Cast Prevention", shortcutManager = "Shortcut Manager", food = "Food", foodHQ = "Food HQ", curielRoot = "Curiel Root", whitelistTarget = "Whitelist Target", validSlots = "Valid Slots", quickStartMode = "QuickStart", totMin = "ToT >=", totMax = "ToT <", htSucceedMax = "Hasty Touch Success <", shStackMin = "Steady Hand Stack >=", manipMax = "Manipulation Uses <", doHuntingLog = "Do Hunting Log", frontlines = "Frontlines", confirm = "Confirm", yes = "Yes", no = "No", debugging = "Debugging", debugItems = "Debug Items", prevComboSkill = "Previous Combo Skill", prevComboSkillNot = "Previous Combo Skill NOT", currentActionNot = "Current Action NOT", filter1 = "Filter 1", filter2 = "Filter 2", filter3 = "Filter 3", filter4 = "Filter 4", filter5 = "Filter 5", underAttack = "Under Attack", hpAdvantage = "HP Advantage >=", targetTPLE = "Target TP <=", targetMPLE = "Target MP <=", performance = "Performance", loot = "Loot", telecast = "Telecast", need = "Need", greed = "Greed", pass = "Pass", extreme = "Extreme", fast = "Fast", --normal = "Normal", slow = "Slow", shortcut = "Shortcut", modifierKey = "Modifier Key", shortcutKey = "Shortcut Key", waitNearEvac = "Wait Near Evac", randomMovement = "Randomize Movement", underAttackMelee = "Under Attack (Melee)", chain = "Chain", chainStart = "Chain Start", chainEnd = "Chain End", enmityAOE = "Enmity AOE", frontalCone = "Frontal Cone", tankedTargetsOnly = "Tanked Targets Only", aoeCenter = "AOE Center", comboSkill = "Combo Skill", offGCDSkill = "Off GCD Skill", removesBuff = "Removes Buff", minContentLevel = "Min Content Level", maxContentLevel = "Max Content Level", maxRadius = "Max Radius", dangerousArea = "Dangerous Area", usePatience = "Use Patience", usePatience2 = "Use Patience II", useChum = "Use Chum", moochableFish = "Moochable Fish", whitelistFish = "Whitelist Fish", whitelistFishHQ = "Whitelist Fish (HQ)", blacklistFish = "Blacklist Fish", blacklistFishHQ = "Blacklist Fish (HQ)", singleUse = "Single Use", --===== Added 9/20/15 - Sebbs maxdurabmin = "Max Durability >=", maxdurabmax = "Max Durability <", maxprogrmin = "Max Progress >=", maxprogrmax = "Max Progress <", --===== Added 9/23/15 - Sebbs -- Help assisthelp = "Assist Mode will... \ \ You Steer, we Shoot. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", grindhelp = "Grind Mode will... \ \ Do Fates, Huntlogs and Grind Mobs. \ \ Only for COMBAT Classes. \ \ While we endevour to Automate Settings, \ Settings can be changed if Advanced Settings is enabled. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", gatherhelp = "Gather Mode will... \ \ Use Markers, Profiles or Quickstart. \ Only for Miner or Botanist. \ \ Skills use are set by Skill Profile", fishhelp = "Fish Mode will... \ \ Use Markers, Profiles or Quickstart. \ \ Only for Fisher. \ \ Skills are NOT set via Skill Profile. \ Set Skills Via Marker or Profiles.", -- Faq assistfaq = "My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job. \ Is Start combat Checked?", grindfaq = "My Bot Doesnt move? \ \ Are any valid Fates Available? \ Are Max Fate settings to low? \ \ My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job.", gatherhfaq = "Bot Doesnt move? \ \ Profile has no valid tasks? \ Markers have radius to small? \ Heavensward or Stormblood may need Marker list.", fishfaq = "Bot Doesnt Fish? \ \ Profile has no valid tasks? \ Current location has Lockout out due to fishing Limit?", -- Missing GUI strings 09/27/17 HusbandoMax -- Shared debugLevel = "Debug Level", addCollectable = "Add Collectable", itemName = "Item Name", minValue = "Min Value", noProfileSelected = "Please select/create a valid profile.", markerMode = "Marker Mode", markerType = "Marker Type", useCordials = "Use Cordials.", collectablePresets = "Use Known Defaults", expManuals = "Use Experience Manuals", -- Assist followTarget = "Follow Target", faceTarget = "Face Target", clientAutoface = "Using Client Autoface", -- Craft forSingleCraftsOnly = "For Single Crafts Only", craftDebug = "Craft Debug", useHQMats = "Use HQ Mats", onlyIfNecesssary = "Only If Necesssary", -- Fish fishMarkerProfileMode = "Fish Mode", baitType = "Bait Type", -- Fish Actions mooch = "Mooch", mooch2 = "Mooch II", patience = "Patience", patience2 = "Patience II", snagging = "Snagging", fishEyes = "Fish Eyes", chum = "Chum", doubleHook = "Double Hook", fishDebug = "Fish Debug", -- Gather gatherDebug = "Gather Debug", gatherMarkerProfileMode = "Gather Mode", minGPHighCordial = "Min GP - High Cordial", minGPCordial = "Min GP - Cordial", minGPWateredCordial = "Min GP - Watered Cordial", stealthDetectRange = "Stealth - Detect Range", stealthRemoveRange = "Stealth - Remove Range", smartStealth = "Smart Stealth", gatherSlotQuickstart = "Gather Slot", mapsQuickstart = "Maps", gardeningQuickstart = "Gardening", raresQuickstart = "Rares", superRaresQuickstart = "Super Rares", chocoboFoodQuickstart = "Chocobo Food", -- Grind AutoLevelMode = "Auto-Level Mode", ModifyAutoGrind = "Modify Auto-Grind", DoOnlyFates = "Do Only Fates", KillNonFateAggro = "Kill Non-Fate Aggro", AdvancedSettings = "Advanced Settings", DoLuminous = "Do Luminous", FateType = "Fate Type", Enable = "Enable", Startat = "Start at %%", Chain = "Chain", Battle = "Battle", Boss = "Boss", Grind = "Grind", Defense = "Defense", Escort = "Escort", MinFateLv = "Min Fate Lv.", SetNoMinFateLevel = "No Min Fate Level", MaxFateLv = "Max Fate Lv.", SetNoMaxFateLevel = "No Max Fate Level", GrindDebug = "Grind Debug", -- Mini Games CuffaCur = "Cuff-a-Cur", MonsterToss = "Monster Toss", TowerStriker = "Tower Striker", RandomizeGame = "Randomize Game", RandomTimeMin = "Random Time Min (m)", RandomTimeMax = "Random Time Max (m)", PlayTime = "Play Time (m)", RestTime = "Rest Time (m)", PostGameDelay = "Post-Game Delay (ms)", -- Party Grind SynctoFates = "Sync to Fates", -- Tooltips :D 09/27/17 HusbandoMax -- Shared debugLevelTooltip = "Change the Debug message level. (The higher the number the more detailed the messages)", addCollectableTooltip = "Add a new Collectable to the list below.", itemNameCollectableTooltip = "Case-sensitive item name for the item to become a collectable.", itemRaitingCollectableTooltip = "Minimum collectable value at which the item will be accepted as a collectable.", profileTooltip = "The profile to be used in the current mode. (Crafting Orders, Gathering, Fishing)", markerModeTooltip = "Select Single,Random or List.", markerTypeTooltip = "Marker type to show in the list below.", useCordialsTooltip = "Allow use of Cordials for GP.", collectablePresetsTooltip = "Add Known Collectables to the list below.", -- Assist assistTooltip = "None: Use manual targetting.\ Lowest Health: Targets the lowest health target within range.\ Highest Health: Targets the highest health target within range.\ Nearest: Targets the closest target within range.\ Tank Assist: Targets whatever your tank is targetting.", assistPriorityTooltip = "Prioritize Damage or Healing.", followTargetTooltip = "Attempts to continually follow the target (useful in PvP).", faceTargetTooltip = "Attempts to continually face the target.\nWarning: Dangerous if using Standard movement mode.", clientAutofaceTooltip = "This option should be turned on if you are using the game client's [Face Target on Attack] options.", startCombatTooltip = "If this option is off, the bot will not attack a mob that is not in combat already.", confirmDutyTooltip = "Auto accepts Duty Queue.", -- Craft craftingOrderEditTooltip = "Opens the Crafting Order Editor.", craftingOrderCreateTooltip = "Creates a New Crafting Order profile.", expManualsTooltip = "Allow use of Experience boost manuals.", craftDebugTooltip = "Enable Debug messages in console.", forSingleCraftsOnlyTooltip = "These settings are for Single Craft (When no profile is selected)", craftAmountTooltip = "Haw many crafts to complete before stopping.", minimumCPTooltip = "CP required before starting the craft. (Useful for CP food)", useHQMatsTooltip = "Allow the use of HQ materials while crafting.", onlyIfNecesssaryTooltip = "Only use HQ materials if there are no NQ materials left.", -- Fish fishMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", baitTypeTooltip = "Bait to be used in Quick Start mode.", -- Fish Actions moochTooltip = "Allow fish mooching.", mooch2Tooltip = "Allow fish mooching (Mooch 2).", patienceTooltip = "Use Patience while fishing.", patience2Tooltip = "Use Patience 2 while fishing.", snaggingTooltip = "Apply the Snagging buff when fishing.", fishEyesTooltip = "Apply the Fish Eyes buff when fishing.", chumTooltip = "Use Chum while fishing.", doubleHookTooltip = "Use Double Hook.", fishDebugTooltip = "Enable Debug messages in console.", -- Gather gatherDebugTooltip = "Enable Debug messages in console.", gatherMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", minGPHighCordialTooltip = "Min GP required before using a High Cordial.", minGPCordialTooltip = "Min GP required before using a Cordial.", minGPWateredCordialTooltip = "Min GP required before using a Watered Cordial.", stealthDetectRangeTooltip = "Enemy range before applying Stealth.", stealthRemoveRangeTooltip = "Enemy range before removing Stealth.", smartStealthTooltip = "Smarter Stealth based on players direction and mob.", gatherSlotQuickstartTooltip = "Set the item slot to gather.", mapsQuickstartTooltip = "Gather Maps when avalible.", gardeningQuickstartTooltip = "Gather Gardening when avalible.", raresQuickstartTooltip = "Gather Rares when avalible.", superRaresQuickstartTooltip = "Gather Super Rares when avalible.", chocoboFoodQuickstartTooltip = "Gather Chocobo Food when avalible.", -- Grind AutoLevelModeTooltip = "Automatically switch maps to continue leveling in an optimal area.", ModifyAutoGrindTooltip = "Opens a GUI to edit the Auto-Level code", doFatesTooltip = "When enabled, the bot will complete FATEs in addition to mob-grinding.", DoOnlyFatesTooltip = "When enabled, the bot will idle between FATEs, and will not perform mob-grinding.", KillNonFateAggroTooltip = "Kills any Non-Fate Aggro", AdvancedSettingsTooltip = "Enable use of Advanced Settings", DoAtmaTooltip = "Grind Atma crystals and moves to the next zones. (Relic)", DoLuminousTooltip = "Grind Luminous crystals and moves to the next zones. (Relic)", MinFateLvTooltip = "Number of levels below current Player level.", SetNoMinFateLevelTooltip = "Number of levels below current Player level.", MaxFateLvTooltip = "Number of levels above current Player level.", SetNoMaxFateLevelTooltip = "Number of levels above current Player level.", fateTeleportPercentTooltip = "Fate percentage required before teleporting to it. (Hacks)", restInFatesTooltip = "Allow resting while in fate when low HP.", waitNearEvacTooltip = "Allow wating near evac postions instead of standing where you are waiting.", GrindDebugTooltip = "Enable Debug messages in console.", prioritizeClaimsTooltip = "Will claim all mobs withing set range on you for optimal drops.", claimRangeTooltip = "Range to claim when using Prioritize Claims.", attackClaimedTooltip = "Attack already clamied mobs.", doHuntingLogTooltip = "When enabled, FFXIVMinion will complete your class hunting log while grinding.", -- Mini Games CuffaCurTooltip = "Play the Cuff-a-Cur mingame.", MonsterTossTooltip = "Play the Monster Toss mingame.", TowerStrikerTooltip = "Play the Tower Striker mingame.", RandomizeGameTooltip = "Changed to a random minigame. (Time set with Random Time Min/Max)", RandomTimeMinTooltip = "Min time used when randomly changing minigames.", RandomTimeMaxTooltip = "Max time used when randomly changing minigames.", PlayTimeTooltip = "Time to play before resting.", RestTimeTooltip = "Time to rest after playing before starting again.", PostGameDelayTooltip = "Delay between starting each minigame.", -- Party Grind UseGamePartyLeaderTooltip = "Use your current party leader as the person to follow/assist.", SynctoFatesTooltip = "Will automatically Sync to Fates when withing a fate zone.", PartyLeaderTooltip = "Enter a players name to follow/assist them.", GetPartyLeaderTooltip = "Gets your current targets name and inserts it above.", --ru end }, -- bk: KR ["kr"] = { startStop = "시작중지", doPulse = "중지(디버그)", pulseTime = "펄스시간(밀리초)", enableLog = "로그사용", task = "작업", state = "상태", effect = "효과", autoStartBot = "봇자동시작", combatMovement = "전투이동", enableRepair = "자동수리", ignoreMarkerLevels = "마커레벨무시", ["Bot Status"] = "봇상태", settings = "설정", status = "상황", advancedSettings = "고급 설정", vendorSettings = "노점상 설정", gatherSettings = "채집 설정", skipcutscene = "컷씬 넘기기", depositItems = "아이템 보관", checkChat = "채팅 알림", randomfarmspot = "임의의 파밍장소 사용", disabledrawing = "렌더링 해제", killaggrononfateenemies = "페이트 없는 적을 공격", avoidAOE = "교전 피하기", -- mesher.lua meshManager = "그물맵매니저", activated = "활성화된", noMeshLoad = "그물맵로드되지않았다", mapName = "맵", navmesh = "그물맵이름", waypoint = "위치", ["General"] = "일반 설정", ["Auto-Equip"] = "Auto-Equip", getWaypoint = "그물맵얻기", useInSwitcher = "스위치에서사용", enableSwitcher = "스위치사용", minSwitchTime = "최소스위치시간", maxSwitchTime = "최대스위치시간", switchTimer = "스위치까지시간", switcherSettings = "스위치설정", showMesh = "삼각형 보이기 ", showrealMesh = "그물맵 보이기", newMeshName = "새로운 그물맵 이름", newMesh = "그물맵 클리어", saveMesh = "그물맵 저장", buildNAVMesh = "그물맵 생성", editor = "그물맵 수정", recoder = "그물맵 기록", connections = "연결", enablePSwitch = "피해망상스위치실행", pSwitchCount = "피해망상플레이어카운트", maMarkerID = "아이디", maMarkerName = "이름", -- skillmanager.lua skillbook = "스킬북", skillManager = "스킬매니저", skillEditor = "스킬에디터", skillEditor_craft = "스킬에디터_제작", skillEditor_gather = "스킬에디터_채집", saveProfile = "프로필 저장", newProfileName = "새로운 프로필", skillProfile = "스킬 프로필", newProfile = "새로운 프로필 생성", clearProfile = "프로필 클리어", skillbookrefresh = "스킬들 복원", targetType = "타겟", stepmin = "스텝 >=", stepmax = "스텝 <", durabmin = "내구도 >=", durabmax = "내구도 <", progrmin = "진행 >=", progrmax = "진행 <", qualitymin = "품질 >=", qualitymax = "품질 <", condition = "상태 =", cpmin = "CP >=", cpmax = "CP <", gpmin = "GP >=", gpmax = "GP <", iqstack = "내부 스택 >=", notused = "사용안함", excellent = "최고품질", good = "고품질", normal = "보통", poor = "저품질", centered = "안정", sturdy = "튼튼", pliant = "고능률", primed = "장지속", malleable = "고진척", nodeHas = "가진 아이템: ", gatherAttemptsMin = "남은 시도 >", gatherAttemptsMax = "남은 시도 <=", profile = "프로필", sMmode = "공격 모드", sMtargetmode = "타겟 모드", refreshProfiles = "프로필 목록 새로고침", deleteProfile = "현재 프로필 삭제", autoetectSkills = "스킬 자동검색", refreshSkillList = "클리어 & 새로고침 스킬목록", skillEditor = "스킬 에디터", enabled = "사용", appliesBuff = "디버프 적용", priority = "우선순위", los = "시선 필요", instacast = "즉시시전 스킬", channeled = "채널 스킬", cooldown = "재사용대기시간", minRange = "최소사거리", maxRange = "최대사거리", isGroundTargeted = "그라운드 타겟", useOutOfCombat = "전투에서 사용", playerMoving = "플레이어 무빙", playerHPGT = "플레이어 체력% >", playerHPLT = "플레이어 체력% <", playerPowerGT = "플레이어 마나 >", playerPowerLT = "플레이어 마나 <", playerHas = "플레이어가 소유한 버프 : 예 13,4152,521", orPlayerHas = "또는 플레이어가 가진 ", playerHasNot = "플레이어가 소유하지않은 버프 : 예 13,4152,521", orPlayerCond = "플레이어 #상태 >", orPlayerHasNot = "또는 플레이어가 소유하지않은", targetMoving = "타겟 무빙", targetHPGT = "타겟 체력% >", targetHPLT = "타겟 체력% <", targetDistanceGT = "타겟 거리 >", targetDistanceLT = "타겟 거리 <", enemiesNearCount = "적들 가까운 타겟(카운트) >=", enemiesNearRange = "적군 가까운 타겟(최대사거리) =", alliesNearCount = "아군 가까운 타겟(카운트) >=", alliesNearRange = "아군 가까운 타겟(최대사거리) =", targetHas = "타겟이 가진 버프 : 예 13,4152,521", orTargetHas = "또는 타겟이 가진 ", targetHasNot = "타겟이 버프를 소유하지않은 : 예 13,4152,521", orTargetHasNot = "또는 타겟이 소유하지않은", prevSkillID = "이전 스킬 아이디", AdvancedSettings = "고급 설정", Fightstyle = "전투스타일", --new SKM stuff alias = "별명", cdIsReady = "CD 준비됨", cdNotReady = "CD 준비가안됨", cdTimeLT = "CD 시간 <=", cdTimeGT = "CD 시간 >=", nextSkillPrio = "다음 스킬 순서", skmTYPE = "행동 유형", skmSTYPE = "스킬 유형", skmCombat = "전투 상태", skmCHARGE = "차징 스킬", skmLevelMin = "레벨 >=", skmLevelMax = "레벨 <=", checkSkill = "스킬 아이디", isReady = "준비됨", isNotReady = "준비가안됨", cooldownRemainingLTE = "남은 쿨타임 <=", cooldownRemainingGTE = "남은 쿨타임 >=", skmNSkillID = "다음 스킬 아이디", skmCBreak = "콤보 차단기", skmTRG = "스킬 타겟", skmTRGTYPE = "타겟 규칙", skmNPC = "NPC 포함", skmPTRG = "플레이어 타겟", skmPGTRG = "그라운드 타겟", skmPPos = "물약", skmTHPCL = "타겟 체력 >", skmTHPCB = "타겟 체력 <", skmTCONTIDS = "만족한 아이디", skmTNCONTIDS = "만족하지않는 아이디", skmTCASTID = "시전 아이디", skmTCASTTM = "시전 @ 나에게", skmTCASTTIME = "시전 시간 >", skmPTPL = "플레이어 TP >", skmPTPB = "플레이어 TP <", skmPMPPL = "플레이어 마나% >", skmPMPPB = "플레이어 마나% <", skmPAGL = "플레이어 어그로 % >", skmPAGB = "플레이어 어그로 % <", skmMPLock = "마나 잠금 원인", skmMPLocked = "영향 잠금", skmMPLockPer = "마나 잠금 %", skmPTCount = "멤버 카운트 >=", skmPTHPL = "파티 체력% >", skmPTHPB = "파티 체력% <", skmPTMPL = "파티 마나% >", skmPTMPB = "파티 마나% <", skmPTTPL = "파티 TP >", skmPTTPB = "파티 TP <", skmHPRIOHP = "우선순위 체력 % <", skmHPRIO1 = "힐 우선순위 1", skmHPRIO2 = "힐 우선순위 2", skmHPRIO3 = "힐 우선순위 3", skmHPRIO4 = "힐 우선순위 4", skmTECount = "적군 >=", skmTECount2 = "적군 <=", skmTERange = "적 범위", skmTELevel = "레벨 차이", skmTACount = "아군 >=", skmTARange = "아군 범위", skmTBuffOwner = "버프 소유자", skmHasBuffs = "버프 소유 (1+2,3)", skmMissBuffs = "버프 사라짐 (1+2,3)", skmOrBuffDura = "또는 버프 지속 <=", skmAndBuffDura = "그리고 버프 지속 >", skmUnspoiled = "깨끗한 연결점", up = "위", down = "아래", delete = "삭제", copy = "복사", paste = "붙여넣기", --sections skillDetails = "스킬 세부사항", skillChecks = "다른 스킬 체크", basicDetails = "기본 세부사항", playerHPMPTP = "플레이어 체력/마나/TP", party = "파티", target = "타겟", casting = "캐스팅", healPriority = "힐 우선순위", aoe = "교전", playerBuffs = "플레이어 버프", targetBuffs = "타겟 버프", --ffxiv stuff specific stuff botMode = "봇 모드", addGrindSpot = "추가 돌발임무 마커", addFishingSpot = "추가 낚시 마커", addMiningSpot = "추가 광부 마커", addBotanySpot = "추가 원예 마커", addNavSpot = "추가 네비 마커", deleteSpot = "삭제 가까운 마커", markers = "마커", markerLevel = "마커 레벨", markerMinLevel = "최소 레벨 마커", markerMaxLevel = "최대 레벨 마커", selectedMarker = "선택된 마커", noMarker = "마커 없음", mining = "채광", fishing = "낚시", botany = "원예", gatherTime = "마커 시간 (초)", deleteMarker = "현재 마커 삭제", recmesh = "그물망 기록", recAreaType = "기록 유형", recAreaSize = "기록 크기", changeMesh = "그물망 변경", changeAreaType = "유형 변경", changeAreaSize = "크기 변경", biDirOffMesh = "양방향 그물맵연결해제", addOffMeshSpot = "추가 그물맵연결해제", delOffMeshSpot = "삭제 그물맵연결해제", typeOffMeshSpot = "유형 그물맵연결해제", showPath = "경로 보기", selectItem1 = "아이템 우선순위 1", selectItem2 = "아이템 우선순위 2", selectItem3 = "아이템 우선순위 3", selectBait = "미끼 선택", baitName = "미끼 이름", markerName = "마커 이름", markerPos = "마커 위치", selectClosestMarker = "가까운 마커 선택", moveToMarker = "마커로 이동", gatherManager = "채집매니저", selectMarker = "마커 선택", logCNE = "원인과 결과", useMount = "탈것 사용", useSprint = "전력질주 사용", gatherGardening = "채집 원예", gatherChocoFood = "채집 초코 음식", nodeType = "노드 타입", throttle = "조절판", --********************************************** repair = "수리", questHelpers = "퀘스트 도우미", mount = "탈것", companion = "버디", stance = "스탠스", stFollow = "따라가기", stFree = "프리 스탠스", stDefender = "방어 스탠스", stAttacker = "공격 스탠스", stHealer = "힐러 스탠스", --********************************************** mountDist = "탈것 거리: ", sprintDist = "전력질주 거리: ", randomPaths = "무작위 길", botEnabled = "봇 사용", grindMode = "그라인드", huntMode = "토벌", huntlogMode = "토벌수첩", fishMode = "낚시", gatherMode = "채집", assistMode = "어시스트", partyMode = "파티-그라인드", craftMode = "제작", useStealth = "은신 사용", randomizeMarkers = "임의 마커", teleport = "텔레포트", permaSprint = "무한 전력질주", avoidHP = "피탐 HP% ", restHP = "휴식 HP%: ", restMP = "휴식 MP%: ", fleeHP = "도망 HP%: ", fleeMP = "도망 MP%: ", doFates = "돌발임무 실행", fatesOnly = "오직 돌발임무만", setEvacPoint = "SetEvacPoint", restInFates = "나머지 돌발임무", maxFateLevel = "최대돌발임무레벨: +", minFateLevel = "최소돌발임무레벨: -", waitForComplete = "완료대기%: ", blacklistTimer = "블랙리스트시간 (초)", fateIndex = "돌발임무인덱스", fateName = "돌발임무이름", blacklistAdd = "블랙리스트추가", blacklistRem = "블랙리스트렘", enableRadar = "레이더 사용", enable2DRadar = "2D 레이더 사용", enable3DRadar = "3D 레이더 사용", fullscreenRadar = "풀스크린 (2D)", showNodes = "노드 보여줌", showPlayers = "플레이어 보여줌", showBattleNPCs = "전투 엔피씨 보여줌", showEventNPCs = "이벤트 엔피씨 보여줌", showEventObjects = "이벤트 오브젝트 보여줌", showAetherytes = "Aetherytes 보여줌", xPos = "X 위치", yPos = "Y 위치", assist = "어시스트", assistPriority = "우선순위", -- new stuff (since last translation) useMooch = "구걸 사용", markerManager = "마커매니저", prevSkillIDNot = "이전 스킬 아이디 NOT", secsSinceLastCast = "마지막 캐스팅 이후 몇초", combatRangePercent = "전투 범위 %: ", blacklistManager = "블랙리스트매니저", createMarker = "마커 생성", editMarkers = "마커 수정", markerType = "마커 유형", editMarkerList = "설정 목록", addMarker = "리스트 추가", editMarker = "마커 수정", newMarker = "새로운 마커", markerList = "마커 목록", markerTeam = "마커 팀", setupList = "설정 목록", blacklistName = "블랙리스트 이름", blacklistEntry = "블랙리스트 명단", entryTime = "명단 시간", deleteEntry = "명단 삭제", qualityminper = "품질 % >=", qualitymaxper = "품질 % <", blacklistTarget = "블랙리스트 타겟", addEntry = "추가 명단", blacklistFate = "블랙리스트 돌발목표", notAttackable = "잘못된 타겟", targetName = "타겟 이름", monsters = "몬스터", fates = "돌발임무", --************************************************* toggleOnOff = "항상 온/오프", multiManager = "멀티봇 매니저", multiChannel = "채널", multiServer = "서버 아이피", multiPort = "포트 #", multiPass = "비밀번호", serverInfo = "서버 정보", --************************************************* huntMonsters = "몬스터 사냥", hunt = "사냥", doAtma = "Atma 실행", prioritizeClaims = "우선순위 Claims", claimRange = "Claim 사거리", attackClaimed = "공격 Claimed", alwaysKillAggro = "항상 킬 어그로", fateTeleportPercent = "텔레포 %", --*************************************************** startCombat = "전투 시작", onlySolo = "혼자만", onlyParty = "파티만", alliesNearHPLT = "아군 체력% <", --new pvpMode = "PVP", pve = "PVE", both = "둘다", pvpTargetType = "PVP 타겟 유형", healer = "힐러", dps = "딜러", tank = "탱커", any = "아무나", none = "없음", meleeDPS = "근접딜러", caster = "캐스터", ranged = "원거리", nearDead = "죽은 근처", sleeper = "CC걸린", unattendedHealer = "무인 힐러", prioritizeRanged = "우선순위 범위", combatType = "전투 유형", nearest = "가까운", lowestHealth = "적은 체력", highestHealth = "Highest Health", tankAssist = "Tank Assist", pvpTargetOne = "우선순위 1", pvpTargetTwo = "우선순위 2", pvpTargetThree = "우선순위 3", pvpTargetFour = "우선순위 4", pvpTargetFive = "우선순위 5", pvpAvoid = "회피", pvpSpeedMatchPartner = "경기 파트너 속도", pvpArena = "PVP 지역", gatherMaps = "지도 수집", markerFields = "마커 필드", confirmDuty = "던전 자동수락", antiAFKMove = "안티-AFK 이동", pvpFlee = "원거리 도주", skipCutscene = "컷씬 스킵", skipDialogue = "대화 스킵", doUnstuck = "떨어져도 활성화", delayLeave = "딜레이 Leave", defaultProfile = "기본 프로필", useHQMats = "제작 수은 매트", enterDutyTimer = "타이머 입력: ", leaveDutyTimer = "타이머 남기기: ", dutyMode = "던전", dutyLeader = "던전 리더: ", clickToTeleport = "텔레포 클릭", clickToTravel = "여행 클릭", questRunProfile = "퀘스트 실행", questManager = "퀘스트 도우미", quests = "퀘스트", questEditor = "퀘스트 에디터", questDone = "퀘스트 완료", questInfo = "퀘스트 정보", questSteps = "단계", questDo = "지금 퀘스트 실행", questAddQuest = "추가 새로운 퀘스트", questAddStep = "추가 새로운 단계", questAddTurnover = "추가 새로운 Turn-in", questAddPreReq = "추가 새로운 사전필수", questID = "퀘스트 아이디", questPullID = "풀 퀘스트 아이디", questPullValues = "풀 현재 값", questJob = "퀘스트 잡", questLevel = "퀘스트 레벨", questSave = "퀘스트 저장", questDelete = "퀘스트 삭제", questUp = "높은 우선순위", questDown = "낮은 우선순위", questStepEditor = "단계 에디터", questStep = "단계", questStepInfo = "단계 정보", questStepDetails = "단계 세부설정", questAddItem = "아이템 추가", questClearItems = "아이템 클리어", questItemEditor = "아이템 에디터", newItem = "새로운 아이템", stepItemAmount = "총액", items = "아이템", convoIndex = "대화 #", dutyEncounters = "상대", dutyEncounterEditor = "던전 상대 에디터", questStepScript = "작업-스크립트", questStepDelete = "단계 삭제", questStepSave = "단계 저장", questTurnoverEditor = "Turn-in 에디터", questPreReqEditor = "필요조건 에디터", questName = "이름", questMinLevel = "최소 레벨", questMaxLevel = "최대 레벨", questPreQuest = "이전 퀘스트 필요", questMap = "맵", questRepeat = "반복", questStepDone = "단계 완료", questReset = "퀘스트 진행을 재설정", markerMode = "마커 모드", markerList = "마커 목록", markerTeam = "마커 팀", singleMarker = "싱글 마커", randomMarker = "무작위 마커", questMode = "퀘스트", removeMarker = "마커 제거", deleteMarker = "마커 삭제", PartyGrind = "파티 그린드", PartyLeader = "리더", GetPartyLeader = "타겟->리더", UseGamePartyLeader = "파티 리더 사용", TargetIsCasting = "타겟 캐스팅", TargetCastingOnMe = "나에게 캐스팅", TargetCastingTime = "캐스팅 시간 >", botanyMarker = "원예 마커", miningMarker = "채광 마커", grindMarker = "그린드 마커", huntMarker = "사냥 마커", pvpMarker = "PVP 마커", unspoiledMarker = "Unspoiled 마커", contentIDEquals = "포함된아이디=", NOTcontentIDEquals = "포함되지않은 아이디=", fishingMarker = "낚시 마커", time = "시간 (초)", name = "이름", minLevel = "최소 레벨", maxLevel = "최대 레벨", markerTime = "마커 시간 (초)", useAetherytes = "사용 A", resetDutyTimer = "재설정 타이머: ", createProfile = "프로필 생성", existingProfile = "현존하는 프로필:", profileType = "프로필 유형:", customTask = "커스텀 작업", addEncounter = "추가 Encounter", details = "Details", newEncounter = "New Encounter", newQuest = "새로운 퀘스트", editQuestStep = "퀘스트 단계 수정", newQuestStep = "새로운 단계", newQuestTurnover = "새로운 Turn-In", newQuestPreReq = "새로운 Pre-Req", questEditSteps = "단계 수정", questEditPreReqs = "Pre-Reqs 수정", questEditTurnovers = "Turn-인스 수정", stepCurrent = "현재 단계", stepTask = "단계 작업", stepItemSelector = "아이템 선택", stepItemID = "아이템 아이디", stepQuestID = "퀘스트 아이디", stepTaskCustom = "단계 작업 커스텀", stepMap = "맵 아이디", stepMesh = "그물맵 이름", stepTarget = "단계 타겟", stepAction = "액션 아이디", stepCommandString = "명령 줄", stepKillCount = "킬 카운트", stepDelay = "딜레이", stepReward = "Reward Slot", stepClear = "모든 스텝 클리어", prereqJob = "PreReq 잡", prereqStep = "PreReq 단계", prereqID = "PreReq 아이디", prereqClear = "모든 PreReqs 클리어", turnoverStep = "단계 #:", turnoverID = "Turn-In 아이디", turnoverSlot = "아이템 슬롯", turnoverClear = "모든 Turn-인스 클리어", profileManager = "프로필 매니저", advancedSettings = "고급 설정", hacks = "핵", newLocation = "새 위치", startLocation = "시작 위치", addLocation = "새로운 위치", saveLocation = "위치 저장", moveLocation = "위치 이동", removeLocation = "위치 제거", minimumGP = "최소한의 GP", locationEditor = "위치 에디터", locationName = "위치 이름", useCordials = "Cordials 사용", gatherUnspoiled = "Unspoiled 수집", minerGearset = "광부 기어세트", botanistGearset = "식물학자 기어세트", refreshMap = "지도 새로고침", hour = "시", class = "클래스", isIdle = "게으른", objectiveIndex = "오브젝트 인덱스", stepIndex = "단계 인덱스", killCount = "킬 카운트", autoEquip = "자동 장비", idlePulseCount = "게으른 카운트", taskDelay = "작업 딜레이 (ms)", eorzeaTime = "에오르제아 시간", potionHP = "물약 체력", potionMP = "물약 마나", teleporter = "텔레포", waypoint = "웨이포인트", newWaypoint = "새로운 웨이포인트", editWaypoint = "웨이포인트 수정", newName = "새로운 이름", deleteWaypoint = "웨이포인트 삭제", renameWaypoint = "웨이포인트 이름재설정", getTargetName = "타겟 이름 얻기", saveAsTargetPos = "@ 타겟 위치 저장", saveAsPlayerPos = "@ 플레이어 위치 저장", save = "저장", move = "이동", distance = "거리", importExport = "가져오기 / 내보내기", autoExport = "자동 내보내기", fileName = "파일 이름", gatherLocations = "채집 위치", huntLocations = "사냥 위치", basicExport = "기본 내보내기", basicImport = "기본 가져오기", markerImport = "마커 가져오기", overwriteExisting = "기존 덮어쓰기", allMarkers = "모든 마커", exportSettings = "내보내기 설정", importSettings = "가져오기 설정", exportGlobal = "글로벌 수출", importGlobal = "글로벌 수입", minimumCP = "최저의 CP", craftAmount = "공예 총액", --===== Added 1/21/15 - Ace paranoid = "편집증", permaSwiftcast = "무한전력질주", castPrevention = "캐스팅 시전삭제", shortcutManager = "바로가기 매니저", food = "음식", foodHQ = "음식 HQ", curielRoot = "동물 룻", --====== Added 1/22/15 - Ace whitelistTarget = "Whitelist Target", validSlots = "유효한 슬롯", --====== Added 2/15/15 - Ace quickStartMode = "빠른 시작", --====== Added 2/18/15 - Ace totMin = "ToT >=", totMax = "ToT <", htSucceedMax = "성급한 터치 성공 <", shStackMin = "꾸준한 손 스택 >=", manipMax = "조작 용도 <", --====== Added 3/13/15 - Ace doHuntingLog = "토벌 수첩 실행", --====== Added 4/2/15 - Ace frontlines = "최전선", confirm = "확인", yes = "예", no = "아니오", debugging = "Debugging", debugItems = "Debug Items", prevComboSkill = "Previous Combo Skill", prevComboSkillNot = "Previous Combo Skill NOT", currentActionNot = "Current Action NOT", filter1 = "필터 1", filter2 = "필터 2", filter3 = "필터 3", filter4 = "필터 4", filter5 = "필터 5", underAttack = "공격", hpAdvantage = "체력 이득 >=", targetTPLE = "타겟 TP <=", targetMPLE = "타겟 마나 <=", performance = "퍼포먼스", loot = "룻", telecast = "텔레캐스튼", need = "선입찰", greed = "입찰", pass = "포기", extreme = "극도로빠른", fast = "빠른", --normal = "보통", slow = "느린", shortcut = "바로가기", modifierKey = "수정 키", shortcutKey = "바로가기 키", waitNearEvac = "Wait Near Evac", randomMovement = "무작위 이동", --====== Added 6/26/15 - Ace underAttackMelee = "공격 (근접)", chain = "체인", chainStart = "체인 시작", chainEnd = "체인 끝", enmityAOE = "증오 AOE", frontalCone = "정면 Cone", tankedTargetsOnly = "오직 탱커만 타겟", aoeCenter = "광역 센터", comboSkill = "콤보 스킬", offGCDSkill = "GCD 스킬 오프", removesBuff = "버프 삭제", --======= Added 7/6/15 - Ace minContentLevel = "최소 인내 레벨", maxContentLevel = "최대 인내 레벨", maxRadius = "최대 반지름", dangerousArea = "위험 지역", --======= Added 7/19/15 - Ace usePatience = "인내 사용", usePatience2 = "인내 사용 II", useChum = "Use Chum", moochableFish = "구걸 가능 낚시", whitelistFish = "화이트리스트 낚시", whitelistFishHQ = "화이트리스트 낚시 (HQ)", blacklistFish = "블랙리스트 낚시", blacklistFishHQ = "블랙리스트 낚시 (HQ)", singleUse = "Single Use", --===== Added 9/20/15 - Sebbs maxdurabmin = "Max 내구도 >=", maxdurabmax = "Max 내구도 <", maxprogrmin = "Max 진행 >=", maxprogrmax = "Max 진행 <", --===== Added 9/23/15 - Sebbs -- Help assisthelp = "Assist Mode will... \ \ You Steer, we Shoot. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", grindhelp = "Grind Mode will... \ \ Do Fates, Huntlogs and Grind Mobs. \ \ Only for COMBAT Classes. \ \ While we endevour to Automate Settings, \ Settings can be changed if Advanced Settings is enabled. \ \ Combat routines come from Skill Profile or ACR. \ Combat is only as good as the Profile used.", gatherhelp = "Gather Mode will... \ \ Use Markers, Profiles or Quickstart. \ Only for Miner or Botanist. \ \ Skills use are set by Skill Profile", fishhelp = "Fish Mode will... \ \ Use Markers, Profiles or Quickstart. \ \ Only for Fisher. \ \ Skills are NOT set via Skill Profile. \ Set Skills Via Marker or Profiles.", -- Faq assistfaq = "My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job. \ Is Start combat Checked?", grindfaq = "My Bot Doesnt move? \ \ Are any valid Fates Available? \ Are Max Fate settings to low? \ \ My Bot Wont attack? \ \ Check your skill profile is set to the right Class/Job.", gatherhfaq = "Bot Doesnt move? \ \ Profile has no valid tasks? \ Markers have radius to small? \ Heavensward or Stormblood may need Marker list.", fishfaq = "Bot Doesnt Fish? \ \ Profile has no valid tasks? \ Current location has Lockout out due to fishing Limit?", -- Missing GUI strings 09/27/17 HusbandoMax -- Shared debugLevel = "Debug Level", addCollectable = "Add Collectable", itemName = "Item Name", minValue = "Min Value", noProfileSelected = "Please select/create a valid profile.", markerMode = "Marker Mode", markerType = "Marker Type", useCordials = "Use Cordials.", collectablePresets = "Use Known Defaults", expManuals = "Use Experience Manuals", -- Assist followTarget = "Follow Target", faceTarget = "Face Target", clientAutoface = "Using Client Autoface", -- Craft forSingleCraftsOnly = "For Single Crafts Only", craftDebug = "Craft Debug", useHQMats = "Use HQ Mats", onlyIfNecesssary = "Only If Necesssary", -- Fish fishMarkerProfileMode = "Fish Mode", baitType = "Bait Type", -- Fish Actions mooch = "Mooch", mooch2 = "Mooch II", patience = "Patience", patience2 = "Patience II", snagging = "Snagging", fishEyes = "Fish Eyes", chum = "Chum", doubleHook = "Double Hook", fishDebug = "Fish Debug", -- Gather gatherDebug = "Gather Debug", gatherMarkerProfileMode = "Gather Mode", minGPHighCordial = "Min GP - High Cordial", minGPCordial = "Min GP - Cordial", minGPWateredCordial = "Min GP - Watered Cordial", stealthDetectRange = "Stealth - Detect Range", stealthRemoveRange = "Stealth - Remove Range", smartStealth = "Smart Stealth", gatherSlotQuickstart = "Gather Slot", mapsQuickstart = "Maps", gardeningQuickstart = "Gardening", raresQuickstart = "Rares", superRaresQuickstart = "Super Rares", chocoboFoodQuickstart = "Chocobo Food", -- Grind AutoLevelMode = "Auto-Level Mode", ModifyAutoGrind = "Modify Auto-Grind", DoOnlyFates = "Do Only Fates", KillNonFateAggro = "Kill Non-Fate Aggro", AdvancedSettings = "Advanced Settings", DoLuminous = "Do Luminous", FateType = "Fate Type", Enable = "Enable", Startat = "Start at %%", Chain = "Chain", Battle = "Battle", Boss = "Boss", Grind = "Grind", Defense = "Defense", Escort = "Escort", MinFateLv = "Min Fate Lv.", SetNoMinFateLevel = "No Min Fate Level", MaxFateLv = "Max Fate Lv.", SetNoMaxFateLevel = "No Max Fate Level", GrindDebug = "Grind Debug", -- Mini Games CuffaCur = "Cuff-a-Cur", MonsterToss = "Monster Toss", TowerStriker = "Tower Striker", RandomizeGame = "Randomize Game", RandomTimeMin = "Random Time Min (m)", RandomTimeMax = "Random Time Max (m)", PlayTime = "Play Time (m)", RestTime = "Rest Time (m)", PostGameDelay = "Post-Game Delay (ms)", -- Party Grind SynctoFates = "Sync to Fates", -- Tooltips :D 09/27/17 HusbandoMax -- Shared debugLevelTooltip = "Change the Debug message level. (The higher the number the more detailed the messages)", addCollectableTooltip = "Add a new Collectable to the list below.", itemNameCollectableTooltip = "Case-sensitive item name for the item to become a collectable.", itemRaitingCollectableTooltip = "Minimum collectable value at which the item will be accepted as a collectable.", profileTooltip = "The profile to be used in the current mode. (Crafting Orders, Gathering, Fishing)", markerModeTooltip = "Select Single,Random or List.", markerTypeTooltip = "Marker type to show in the list below.", useCordialsTooltip = "Allow use of Cordials for GP.", collectablePresetsTooltip = "Add Known Collectables to the list below.", -- Assist assistTooltip = "None: Use manual targetting.\ Lowest Health: Targets the lowest health target within range.\ Highest Health: Targets the highest health target within range.\ Nearest: Targets the closest target within range.\ Tank Assist: Targets whatever your tank is targetting.", assistPriorityTooltip = "Prioritize Damage or Healing.", followTargetTooltip = "Attempts to continually follow the target (useful in PvP).", faceTargetTooltip = "Attempts to continually face the target.\nWarning: Dangerous if using Standard movement mode.", clientAutofaceTooltip = "This option should be turned on if you are using the game client's [Face Target on Attack] options.", startCombatTooltip = "If this option is off, the bot will not attack a mob that is not in combat already.", confirmDutyTooltip = "Auto accepts Duty Queue.", -- Craft craftingOrderEditTooltip = "Opens the Crafting Order Editor.", craftingOrderCreateTooltip = "Creates a New Crafting Order profile.", expManualsTooltip = "Allow use of Experience boost manuals.", craftDebugTooltip = "Enable Debug messages in console.", forSingleCraftsOnlyTooltip = "These settings are for Single Craft (When no profile is selected)", craftAmountTooltip = "Haw many crafts to complete before stopping.", minimumCPTooltip = "CP required before starting the craft. (Useful for CP food)", useHQMatsTooltip = "Allow the use of HQ materials while crafting.", onlyIfNecesssaryTooltip = "Only use HQ materials if there are no NQ materials left.", -- Fish fishMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", baitTypeTooltip = "Bait to be used in Quick Start mode.", -- Fish Actions moochTooltip = "Allow fish mooching.", mooch2Tooltip = "Allow fish mooching (Mooch 2).", patienceTooltip = "Use Patience while fishing.", patience2Tooltip = "Use Patience 2 while fishing.", snaggingTooltip = "Apply the Snagging buff when fishing.", fishEyesTooltip = "Apply the Fish Eyes buff when fishing.", chumTooltip = "Use Chum while fishing.", doubleHookTooltip = "Use Double Hook.", fishDebugTooltip = "Enable Debug messages in console.", -- Gather gatherDebugTooltip = "Enable Debug messages in console.", gatherMarkerProfileModeTooltip = "Select between Markers, Profile or Quickstart.", minGPHighCordialTooltip = "Min GP required before using a High Cordial.", minGPCordialTooltip = "Min GP required before using a Cordial.", minGPWateredCordialTooltip = "Min GP required before using a Watered Cordial.", stealthDetectRangeTooltip = "Enemy range before applying Stealth.", stealthRemoveRangeTooltip = "Enemy range before removing Stealth.", smartStealthTooltip = "Smarter Stealth based on players direction and mob.", gatherSlotQuickstartTooltip = "Set the item slot to gather.", mapsQuickstartTooltip = "Gather Maps when avalible.", gardeningQuickstartTooltip = "Gather Gardening when avalible.", raresQuickstartTooltip = "Gather Rares when avalible.", superRaresQuickstartTooltip = "Gather Super Rares when avalible.", chocoboFoodQuickstartTooltip = "Gather Chocobo Food when avalible.", -- Grind AutoLevelModeTooltip = "Automatically switch maps to continue leveling in an optimal area.", ModifyAutoGrindTooltip = "Opens a GUI to edit the Auto-Level code", doFatesTooltip = "When enabled, the bot will complete FATEs in addition to mob-grinding.", DoOnlyFatesTooltip = "When enabled, the bot will idle between FATEs, and will not perform mob-grinding.", KillNonFateAggroTooltip = "Kills any Non-Fate Aggro", AdvancedSettingsTooltip = "Enable use of Advanced Settings", DoAtmaTooltip = "Grind Atma crystals and moves to the next zones. (Relic)", DoLuminousTooltip = "Grind Luminous crystals and moves to the next zones. (Relic)", MinFateLvTooltip = "Number of levels below current Player level.", SetNoMinFateLevelTooltip = "Number of levels below current Player level.", MaxFateLvTooltip = "Number of levels above current Player level.", SetNoMaxFateLevelTooltip = "Number of levels above current Player level.", fateTeleportPercentTooltip = "Fate percentage required before teleporting to it. (Hacks)", restInFatesTooltip = "Allow resting while in fate when low HP.", waitNearEvacTooltip = "Allow wating near evac postions instead of standing where you are waiting.", GrindDebugTooltip = "Enable Debug messages in console.", prioritizeClaimsTooltip = "Will claim all mobs withing set range on you for optimal drops.", claimRangeTooltip = "Range to claim when using Prioritize Claims.", attackClaimedTooltip = "Attack already clamied mobs.", doHuntingLogTooltip = "When enabled, FFXIVMinion will complete your class hunting log while grinding.", -- Mini Games CuffaCurTooltip = "Play the Cuff-a-Cur mingame.", MonsterTossTooltip = "Play the Monster Toss mingame.", TowerStrikerTooltip = "Play the Tower Striker mingame.", RandomizeGameTooltip = "Changed to a random minigame. (Time set with Random Time Min/Max)", RandomTimeMinTooltip = "Min time used when randomly changing minigames.", RandomTimeMaxTooltip = "Max time used when randomly changing minigames.", PlayTimeTooltip = "Time to play before resting.", RestTimeTooltip = "Time to rest after playing before starting again.", PostGameDelayTooltip = "Delay between starting each minigame.", -- Party Grind UseGamePartyLeaderTooltip = "Use your current party leader as the person to follow/assist.", SynctoFatesTooltip = "Will automatically Sync to Fates when withing a fate zone.", PartyLeaderTooltip = "Enter a players name to follow/assist them.", GetPartyLeaderTooltip = "Gets your current targets name and inserts it above.", --kr end }, } -- merge the ml_strings into the miniondbstrings, so they get all translated for language,data in pairs(ml_strings) do for skey,str in pairs(data) do if ( ml_miniondbstrings[skey] == nil ) then ml_miniondbstrings[skey] = { [language] = str } else if ( ml_miniondbstrings[skey][language] == nil ) then ml_miniondbstrings[skey][language] = str end end end end -- merge the minionlib strings with our ffxiv strings for language,data in pairs(ffxiv_strings) do if ( ml_strings[language] ) then for skey,str in pairs(data) do if ( ml_strings[language][skey] == nil ) then ml_strings[language][skey] = str else --d("Not adding dupliocate string :"..skey) end end end -- add them to the new ml_miniondbstrings as well for skey,str in pairs(data) do if ( ml_miniondbstrings[skey] == nil ) then ml_miniondbstrings[skey] = { [language] = str } else if ( ml_miniondbstrings[skey][language] == nil ) then ml_miniondbstrings[skey][language] = str end end end end function GetUSString(stringName) return GetStringByLang(stringName,"en") end
0
0.902319
1
0.902319
game-dev
MEDIA
0.919526
game-dev
0.502157
1
0.502157
DruidMech/UE4-CPP-Shooter-Series
16,087
Source Code Per Lesson/Section 11 - Multiple Weapon Types/203 Disable FABRIK When Reloading/Item.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Item.h" #include "Components/BoxComponent.h" #include "Components/WidgetComponent.h" #include "Components/SphereComponent.h" #include "ShooterCharacter.h" #include "Camera/CameraComponent.h" #include "Kismet/GameplayStatics.h" #include "Sound/SoundCue.h" #include "Curves/CurveVector.h" // Sets default values AItem::AItem() : ItemName(FString("Default")), ItemCount(0), ItemRarity(EItemRarity::EIR_Common), ItemState(EItemState::EIS_Pickup), // Item interp variables ZCurveTime(0.7f), ItemInterpStartLocation(FVector(0.f)), CameraTargetLocation(FVector(0.f)), bInterping(false), ItemInterpX(0.f), ItemInterpY(0.f), InterpInitialYawOffset(0.f), ItemType(EItemType::EIT_MAX), InterpLocIndex(0), MaterialIndex(0), bCanChangeCustomDepth(true), // Dynamic Material Parameters GlowAmount(150.f), FresnelExponent(3.f), FresnelReflectFraction(4.f), PulseCurveTime(5.f), SlotIndex(0), bCharacterInventoryFull(false) { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; ItemMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("ItemMesh")); SetRootComponent(ItemMesh); CollisionBox = CreateDefaultSubobject<UBoxComponent>(TEXT("CollisionBox")); CollisionBox->SetupAttachment(ItemMesh); CollisionBox->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); CollisionBox->SetCollisionResponseToChannel( ECollisionChannel::ECC_Visibility, ECollisionResponse::ECR_Block); PickupWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("PickupWidget")); PickupWidget->SetupAttachment(GetRootComponent()); AreaSphere = CreateDefaultSubobject<USphereComponent>(TEXT("AreaSphere")); AreaSphere->SetupAttachment(GetRootComponent()); } // Called when the game starts or when spawned void AItem::BeginPlay() { Super::BeginPlay(); // Hide Pickup Widget if (PickupWidget) { PickupWidget->SetVisibility(false); } // Sets ActiveStars array based on Item Rarity SetActiveStars(); // Setup overlap for AreaSphere AreaSphere->OnComponentBeginOverlap.AddDynamic(this, &AItem::OnSphereOverlap); AreaSphere->OnComponentEndOverlap.AddDynamic(this, &AItem::OnSphereEndOverlap); // Set Item properties based on ItemState SetItemProperties(ItemState); // Set custom depth to disabled InitializeCustomDepth(); StartPulseTimer(); } void AItem::OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (OtherActor) { AShooterCharacter* ShooterCharacter = Cast<AShooterCharacter>(OtherActor); if (ShooterCharacter) { ShooterCharacter->IncrementOverlappedItemCount(1); } } } void AItem::OnSphereEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { if (OtherActor) { AShooterCharacter* ShooterCharacter = Cast<AShooterCharacter>(OtherActor); if (ShooterCharacter) { ShooterCharacter->IncrementOverlappedItemCount(-1); } } } void AItem::SetActiveStars() { // The 0 element isn't used for (int32 i = 0; i <= 5; i++) { ActiveStars.Add(false); } switch (ItemRarity) { case EItemRarity::EIR_Damaged: ActiveStars[1] = true; break; case EItemRarity::EIR_Common: ActiveStars[1] = true; ActiveStars[2] = true; break; case EItemRarity::EIR_Uncommon: ActiveStars[1] = true; ActiveStars[2] = true; ActiveStars[3] = true; break; case EItemRarity::EIR_Rare: ActiveStars[1] = true; ActiveStars[2] = true; ActiveStars[3] = true; ActiveStars[4] = true; break; case EItemRarity::EIR_Legendary: ActiveStars[1] = true; ActiveStars[2] = true; ActiveStars[3] = true; ActiveStars[4] = true; ActiveStars[5] = true; break; } } void AItem::SetItemProperties(EItemState State) { switch (State) { case EItemState::EIS_Pickup: // Set mesh properties ItemMesh->SetSimulatePhysics(false); ItemMesh->SetEnableGravity(false); ItemMesh->SetVisibility(true); ItemMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ItemMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set AreaSphere properties AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Overlap); AreaSphere->SetCollisionEnabled(ECollisionEnabled::QueryOnly); // Set CollisionBox properties CollisionBox->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); CollisionBox->SetCollisionResponseToChannel( ECollisionChannel::ECC_Visibility, ECollisionResponse::ECR_Block); CollisionBox->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); break; case EItemState::EIS_Equipped: PickupWidget->SetVisibility(false); // Set mesh properties ItemMesh->SetSimulatePhysics(false); ItemMesh->SetEnableGravity(false); ItemMesh->SetVisibility(true); ItemMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ItemMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set AreaSphere properties AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set CollisionBox properties CollisionBox->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); CollisionBox->SetCollisionEnabled(ECollisionEnabled::NoCollision); break; case EItemState::EIS_Falling: // Set mesh properties ItemMesh->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); ItemMesh->SetSimulatePhysics(true); ItemMesh->SetEnableGravity(true); ItemMesh->SetVisibility(true); ItemMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ItemMesh->SetCollisionResponseToChannel( ECollisionChannel::ECC_WorldStatic, ECollisionResponse::ECR_Block); // Set AreaSphere properties AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set CollisionBox properties CollisionBox->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); CollisionBox->SetCollisionEnabled(ECollisionEnabled::NoCollision); break; case EItemState::EIS_EquipInterping: PickupWidget->SetVisibility(false); // Set mesh properties ItemMesh->SetSimulatePhysics(false); ItemMesh->SetEnableGravity(false); ItemMesh->SetVisibility(true); ItemMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ItemMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set AreaSphere properties AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set CollisionBox properties CollisionBox->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); CollisionBox->SetCollisionEnabled(ECollisionEnabled::NoCollision); break; case EItemState::EIS_PickedUp: PickupWidget->SetVisibility(false); // Set mesh properties ItemMesh->SetSimulatePhysics(false); ItemMesh->SetEnableGravity(false); ItemMesh->SetVisibility(false); ItemMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); ItemMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set AreaSphere properties AreaSphere->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); AreaSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision); // Set CollisionBox properties CollisionBox->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); CollisionBox->SetCollisionEnabled(ECollisionEnabled::NoCollision); break; } } void AItem::FinishInterping() { bInterping = false; if (Character) { // Subtract 1 from the Item Count of the interp location struct Character->IncrementInterpLocItemCount(InterpLocIndex, -1); Character->GetPickupItem(this); Character->UnHighlightInventorySlot(); } // Set scale back to normal SetActorScale3D(FVector(1.f)); DisableGlowMaterial(); bCanChangeCustomDepth = true; DisableCustomDepth(); } void AItem::ItemInterp(float DeltaTime) { if (!bInterping) return; if (Character && ItemZCurve) { // Elapsed time since we started ItemInterpTimer const float ElapsedTime = GetWorldTimerManager().GetTimerElapsed(ItemInterpTimer); // Get curve value corresponding to ElapsedTime const float CurveValue = ItemZCurve->GetFloatValue(ElapsedTime); UE_LOG(LogTemp, Warning, TEXT("CurveValue: %f"), CurveValue); // Get the item's initial location when the curve started FVector ItemLocation = ItemInterpStartLocation; // Get location in front of the camera const FVector CameraInterpLocation{ GetInterpLocation() }; // Vector from Item to Camera Interp Location, X and Y are zeroed out const FVector ItemToCamera{ FVector(0.f, 0.f, (CameraInterpLocation - ItemLocation).Z) }; // Scale factor to multiply with CurveValue const float DeltaZ = ItemToCamera.Size(); const FVector CurrentLocation{ GetActorLocation() }; // Interpolated X value const float InterpXValue = FMath::FInterpTo( CurrentLocation.X, CameraInterpLocation.X, DeltaTime, 30.0f); // Interpolated Y value const float InterpYValue = FMath::FInterpTo( CurrentLocation.Y, CameraInterpLocation.Y, DeltaTime, 30.f); // Set X and Y of ItemLocation to Interped values ItemLocation.X = InterpXValue; ItemLocation.Y = InterpYValue; // Adding curve value to the Z component of the Initial Location (scaled by DeltaZ) ItemLocation.Z += CurveValue * DeltaZ; SetActorLocation(ItemLocation, true, nullptr, ETeleportType::TeleportPhysics); // Camera rotation this frame const FRotator CameraRotation{ Character->GetFollowCamera()->GetComponentRotation() }; // Camera rotation plus inital Yaw Offset FRotator ItemRotation{ 0.f, CameraRotation.Yaw + InterpInitialYawOffset, 0.f }; SetActorRotation(ItemRotation, ETeleportType::TeleportPhysics); if (ItemScaleCurve) { const float ScaleCurveValue = ItemScaleCurve->GetFloatValue(ElapsedTime); SetActorScale3D(FVector(ScaleCurveValue, ScaleCurveValue, ScaleCurveValue)); } } } FVector AItem::GetInterpLocation() { if (Character == nullptr) return FVector(0.f); switch (ItemType) { case EItemType::EIT_Ammo: return Character->GetInterpLocation(InterpLocIndex).SceneComponent->GetComponentLocation(); break; case EItemType::EIT_Weapon: return Character->GetInterpLocation(0).SceneComponent->GetComponentLocation(); break; } return FVector(); } void AItem::PlayPickupSound(bool bForcePlaySound) { if (Character) { if (bForcePlaySound) { if (PickupSound) { UGameplayStatics::PlaySound2D(this, PickupSound); } } else if (Character->ShouldPlayPickupSound()) { Character->StartPickupSoundTimer(); if (PickupSound) { UGameplayStatics::PlaySound2D(this, PickupSound); } } } } void AItem::EnableCustomDepth() { if (bCanChangeCustomDepth) { ItemMesh->SetRenderCustomDepth(true); } } void AItem::DisableCustomDepth() { if (bCanChangeCustomDepth) { ItemMesh->SetRenderCustomDepth(false); } } void AItem::InitializeCustomDepth() { DisableCustomDepth(); } void AItem::OnConstruction(const FTransform& Transform) { if (MaterialInstance) { DynamicMaterialInstance = UMaterialInstanceDynamic::Create(MaterialInstance, this); ItemMesh->SetMaterial(MaterialIndex, DynamicMaterialInstance); } EnableGlowMaterial(); // Load the data in the Item Rarity Data Table // Path to the Item Rarity Data Table FString RarityTablePath(TEXT("DataTable'/Game/_Game/DataTable/ItemRarityDataTable.ItemRarityDataTable'")); UDataTable* RarityTableObject = Cast<UDataTable>(StaticLoadObject(UDataTable::StaticClass(), nullptr, *RarityTablePath)); if (RarityTableObject) { FItemRarityTable* RarityRow = nullptr; switch (ItemRarity) { case EItemRarity::EIR_Damaged: RarityRow = RarityTableObject->FindRow<FItemRarityTable>(FName("Damaged"), TEXT("")); break; case EItemRarity::EIR_Common: RarityRow = RarityTableObject->FindRow<FItemRarityTable>(FName("Common"), TEXT("")); break; case EItemRarity::EIR_Uncommon: RarityRow = RarityTableObject->FindRow<FItemRarityTable>(FName("Uncommon"), TEXT("")); break; case EItemRarity::EIR_Rare: RarityRow = RarityTableObject->FindRow<FItemRarityTable>(FName("Rare"), TEXT("")); break; case EItemRarity::EIR_Legendary: RarityRow = RarityTableObject->FindRow<FItemRarityTable>(FName("Legendary"), TEXT("")); break; } if (RarityRow) { GlowColor = RarityRow->GlowColor; LightColor = RarityRow->LightColor; DarkColor = RarityRow->DarkColor; NumberOfStars = RarityRow->NumberOfStars; IconBackground = RarityRow->IconBackground; } } } void AItem::EnableGlowMaterial() { if (DynamicMaterialInstance) { DynamicMaterialInstance->SetScalarParameterValue(TEXT("GlowBlendAlpha"), 0); } } void AItem::UpdatePulse() { float ElapsedTime{}; FVector CurveValue{}; switch (ItemState) { case EItemState::EIS_Pickup: if (PulseCurve) { ElapsedTime = GetWorldTimerManager().GetTimerElapsed(PulseTimer); CurveValue = PulseCurve->GetVectorValue(ElapsedTime); } break; case EItemState::EIS_EquipInterping: if (InterpPulseCurve) { ElapsedTime = GetWorldTimerManager().GetTimerElapsed(ItemInterpTimer); CurveValue = InterpPulseCurve->GetVectorValue(ElapsedTime); } break; } if (DynamicMaterialInstance) { DynamicMaterialInstance->SetScalarParameterValue(TEXT("GlowAmount"), CurveValue.X * GlowAmount); DynamicMaterialInstance->SetScalarParameterValue(TEXT("FresnelExponent"), CurveValue.Y * FresnelExponent); DynamicMaterialInstance->SetScalarParameterValue(TEXT("FresnelReflectFraction"), CurveValue.Z * FresnelReflectFraction); } } void AItem::DisableGlowMaterial() { if (DynamicMaterialInstance) { DynamicMaterialInstance->SetScalarParameterValue(TEXT("GlowBlendAlpha"), 1); } } void AItem::PlayEquipSound(bool bForcePlaySound) { if (Character) { if (bForcePlaySound) { if (EquipSound) { UGameplayStatics::PlaySound2D(this, EquipSound); } } else if (Character->ShouldPlayEquipSound()) { Character->StartEquipSoundTimer(); if (EquipSound) { UGameplayStatics::PlaySound2D(this, EquipSound); } } } } // Called every frame void AItem::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Handle Item Interping when in the EquipInterping state ItemInterp(DeltaTime); // Get curve values from PulseCurve and set dynamic material parameters UpdatePulse(); } void AItem::ResetPulseTimer() { StartPulseTimer(); } void AItem::StartPulseTimer() { if (ItemState == EItemState::EIS_Pickup) { GetWorldTimerManager().SetTimer(PulseTimer, this, &AItem::ResetPulseTimer, PulseCurveTime); } } void AItem::SetItemState(EItemState State) { ItemState = State; SetItemProperties(State); } void AItem::StartItemCurve(AShooterCharacter* Char, bool bForcePlaySound) { // Store a handle to the Character Character = Char; // Get array index in InterpLocations with the lowest item count InterpLocIndex = Character->GetInterpLocationIndex(); // Add 1 to the Item Count for this interp location struct Character->IncrementInterpLocItemCount(InterpLocIndex, 1); PlayPickupSound(bForcePlaySound); // Store initial location of the Item ItemInterpStartLocation = GetActorLocation(); bInterping = true; SetItemState(EItemState::EIS_EquipInterping); GetWorldTimerManager().ClearTimer(PulseTimer); GetWorldTimerManager().SetTimer( ItemInterpTimer, this, &AItem::FinishInterping, ZCurveTime); // Get initial Yaw of the Camera const float CameraRotationYaw{ Character->GetFollowCamera()->GetComponentRotation().Yaw }; // Get initial Yaw of the Item const float ItemRotationYaw{ GetActorRotation().Yaw }; // Initial Yaw offset between Camera and Item InterpInitialYawOffset = ItemRotationYaw - CameraRotationYaw; bCanChangeCustomDepth = false; }
0
0.955189
1
0.955189
game-dev
MEDIA
0.953605
game-dev
0.952305
1
0.952305
tswow/tswow
3,090
tswow-scripts/wotlk/std/Spell/SpellCastTime.ts
/* * This file is part of tswow (https://github.com/tswow) * * Copyright (C) 2020 tswow <https://github.com/tswow/> * 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, version 3. * * 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/>. */ import { Cell } from "../../../data/cell/cells/Cell"; import { Table } from "../../../data/table/Table"; import { SpellCastTimesQuery, SpellCastTimesRow } from "../../dbc/SpellCastTimes"; import { DBC } from "../../DBCFiles"; import { MainEntity } from "../Misc/Entity"; import { DynamicIDGenerator, Ids } from "../Misc/Ids"; import { RefDynamic } from "../Refs/Ref"; import { RegistryDynamic } from "../Refs/Registry"; export class SpellCastTime extends MainEntity<SpellCastTimesRow> { clear(): this { this.Base.set(0) this.PerLevel.set(0) this.Minimum.set(0) return this; } get Base() { return this.wrap(this.row.Base); } get PerLevel() { return this.wrap(this.row.PerLevel); } get Minimum() { return this.wrap(this.row.Minimum); } set(base: number, perLevel: number, minimum: number) { this.Base.set(base); this.PerLevel.set(perLevel); this.Minimum.set(minimum) return this.owner; } get ID() { return this.row.ID.get(); } } export class SpellCastTimeRef<T> extends RefDynamic<T,SpellCastTime> { setSimple(base: number, perLevel: number = 0, minimum: number = 0) { this.getRefCopy() .Base.set(base) .PerLevel.set(perLevel) .Minimum.set(minimum) return this.owner; } } export class SpellCastTimeRegistryClass extends RegistryDynamic< SpellCastTime , SpellCastTimesRow , SpellCastTimesQuery > { ref<T>(owner: T, cell: Cell<number,any>) { return new SpellCastTimeRef(owner, cell, this); } protected Table(): Table<any, SpellCastTimesQuery, SpellCastTimesRow> & { add: (id: number) => SpellCastTimesRow; } { return DBC.SpellCastTimes } protected ids(): DynamicIDGenerator { return Ids.SpellCastTimes } Clear(entity: SpellCastTime): void { entity.Base.set(0) .Minimum.set(0) .PerLevel.set(0) } protected FindByID(id: number): SpellCastTimesRow { return DBC.SpellCastTimes.findById(id) } protected EmptyQuery(): SpellCastTimesQuery { return {} } ID(e: SpellCastTime): number { return e.ID } protected Entity(r: SpellCastTimesRow): SpellCastTime { return new SpellCastTime(r); } } export const SpellCastTimeRegistry = new SpellCastTimeRegistryClass();
0
0.80363
1
0.80363
game-dev
MEDIA
0.361951
game-dev
0.884939
1
0.884939
CodeSmile-0000011110110111/de.codesmile.luny
3,237
Runtime/Assets/LunyLuaContext.cs
// Copyright (C) 2021-2025 Steffen Itterheim // Refer to included LICENSE file for terms and conditions. using Lua; using System; using System.Linq; using UnityEditor; using UnityEngine; namespace Luny { /// <summary> /// Contains settings for a Lua context and instantiates an instance of Lua. /// </summary> [CreateAssetMenu(fileName = "New LuaContext", menuName = "Luny/Lua Context", order = 100)] [Icon("Packages/de.codesmile.luny/Editor/Resources/LunyLuaContextIcon.png")] public sealed class LunyLuaContext : ScriptableObject { [Tooltip("When enabled, access to potentially harmful methods and libraries is restricted or disallowed. " + "All paths are relative to the search paths below, absolute paths will not work. " + "Contexts that may run user scripts (eg modding, even if unintential) should enable this!")] [SerializeField] private Boolean m_IsSandbox; /// <summary> /// Directories where functions like dofile() will search for files. /// </summary> [Tooltip("Scripts with relative paths will be searched for in these folders, from top to bottom. Search stops for " + "the first script found.")] [SerializeField] private String[] m_ScriptSearchPaths = { "%PersistentDataPath%", "Assets/StreamingAssets", "Assets/Scripts", "Assets", }; [SerializeField] private LuaLibraryFlags m_Libraries = (LuaLibraryFlags)(-1); // default: Everything /// <summary> /// Which modules (C# bindings) will be available in this Lua state. /// </summary> [SerializeField] private LunyLuaModule[] m_Modules = new LunyLuaModule[0]; [SerializeField] [HideInInspector] private String m_Path; [SerializeField] [HideInInspector] private Boolean m_IsModdingContext; public Boolean IsSandbox => m_IsSandbox; public LuaSearchPaths SearchPaths => new(this, m_ScriptSearchPaths); public String Path => m_Path; public LuaLibraryFlags Libraries => m_Libraries; /// <summary> /// Which modules (C# bindings) will be available in this Lua state. /// </summary> public LunyLuaModule[] Modules => m_Modules; private void OnEnable() => m_IsModdingContext = IsModdingContext; #if UNITY_EDITOR private void OnValidate() => UpdateAssetPath(); private void UpdateAssetPath() { var path = AssetDatabase.GetAssetPath(this); if (path != m_Path) { m_Path = path; EditorUtility.SetDirty(this); } } public Boolean IsEditorContext => AssetDatabase.GetLabels(this).Contains(LunyAssetLabel.EditorLuaContext); public Boolean IsRuntimeContext => AssetDatabase.GetLabels(this).Contains(LunyAssetLabel.RuntimeLuaContext); public Boolean IsModdingContext => m_IsModdingContext = AssetDatabase.GetLabels(this).Contains(LunyAssetLabel.ModdingLuaContext); #else public Boolean IsEditorContext => false; public Boolean IsRuntimeContext => true; public Boolean IsModdingContext => m_IsModdingContext; #endif public LuaValue CreateContextTable() { var context = new LuaTable(0, 6); context["name"] = name; context["path"] = Path; context["sandbox"] = IsSandbox; context["editor"] = IsEditorContext; context["runtime"] = IsRuntimeContext; context["modding"] = IsModdingContext; return context; } } }
0
0.916312
1
0.916312
game-dev
MEDIA
0.508281
game-dev
0.711546
1
0.711546
Soft-Sprint-Studios/Tectonic-Engine
5,110
bullet/include/BulletDynamics/ConstraintSolver/btGeneric6DofSpringConstraint.h
/* Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. 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_GENERIC_6DOF_SPRING_CONSTRAINT_H #define BT_GENERIC_6DOF_SPRING_CONSTRAINT_H #include "LinearMath/btVector3.h" #include "btTypedConstraint.h" #include "btGeneric6DofConstraint.h" #ifdef BT_USE_DOUBLE_PRECISION #define btGeneric6DofSpringConstraintData2 btGeneric6DofSpringConstraintDoubleData2 #define btGeneric6DofSpringConstraintDataName "btGeneric6DofSpringConstraintDoubleData2" #else #define btGeneric6DofSpringConstraintData2 btGeneric6DofSpringConstraintData #define btGeneric6DofSpringConstraintDataName "btGeneric6DofSpringConstraintData" #endif //BT_USE_DOUBLE_PRECISION /// Generic 6 DOF constraint that allows to set spring motors to any translational and rotational DOF /// DOF index used in enableSpring() and setStiffness() means: /// 0 : translation X /// 1 : translation Y /// 2 : translation Z /// 3 : rotation X (3rd Euler rotational around new position of X axis, range [-PI+epsilon, PI-epsilon] ) /// 4 : rotation Y (2nd Euler rotational around new position of Y axis, range [-PI/2+epsilon, PI/2-epsilon] ) /// 5 : rotation Z (1st Euler rotational around Z axis, range [-PI+epsilon, PI-epsilon] ) ATTRIBUTE_ALIGNED16(class) btGeneric6DofSpringConstraint : public btGeneric6DofConstraint { protected: bool m_springEnabled[6]; btScalar m_equilibriumPoint[6]; btScalar m_springStiffness[6]; btScalar m_springDamping[6]; // between 0 and 1 (1 == no damping) void init(); void internalUpdateSprings(btConstraintInfo2 * info); public: BT_DECLARE_ALIGNED_ALLOCATOR(); btGeneric6DofSpringConstraint(btRigidBody & rbA, btRigidBody & rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA); btGeneric6DofSpringConstraint(btRigidBody & rbB, const btTransform& frameInB, bool useLinearReferenceFrameB); void enableSpring(int index, bool onOff); void setStiffness(int index, btScalar stiffness); void setDamping(int index, btScalar damping); void setEquilibriumPoint(); // set the current constraint position/orientation as an equilibrium point for all DOF void setEquilibriumPoint(int index); // set the current constraint position/orientation as an equilibrium point for given DOF void setEquilibriumPoint(int index, btScalar val); bool isSpringEnabled(int index) const { return m_springEnabled[index]; } btScalar getStiffness(int index) const { return m_springStiffness[index]; } btScalar getDamping(int index) const { return m_springDamping[index]; } btScalar getEquilibriumPoint(int index) const { return m_equilibriumPoint[index]; } virtual void setAxis(const btVector3& axis1, const btVector3& axis2); virtual void getInfo2(btConstraintInfo2 * info); virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; }; struct btGeneric6DofSpringConstraintData { btGeneric6DofConstraintData m_6dofData; int m_springEnabled[6]; float m_equilibriumPoint[6]; float m_springStiffness[6]; float m_springDamping[6]; }; struct btGeneric6DofSpringConstraintDoubleData2 { btGeneric6DofConstraintDoubleData2 m_6dofData; int m_springEnabled[6]; double m_equilibriumPoint[6]; double m_springStiffness[6]; double m_springDamping[6]; }; SIMD_FORCE_INLINE int btGeneric6DofSpringConstraint::calculateSerializeBufferSize() const { return sizeof(btGeneric6DofSpringConstraintData2); } ///fills the dataBuffer and returns the struct name (and 0 on failure) SIMD_FORCE_INLINE const char* btGeneric6DofSpringConstraint::serialize(void* dataBuffer, btSerializer* serializer) const { btGeneric6DofSpringConstraintData2* dof = (btGeneric6DofSpringConstraintData2*)dataBuffer; btGeneric6DofConstraint::serialize(&dof->m_6dofData, serializer); int i; for (i = 0; i < 6; i++) { dof->m_equilibriumPoint[i] = m_equilibriumPoint[i]; dof->m_springDamping[i] = m_springDamping[i]; dof->m_springEnabled[i] = m_springEnabled[i] ? 1 : 0; dof->m_springStiffness[i] = m_springStiffness[i]; } return btGeneric6DofSpringConstraintDataName; } #endif // BT_GENERIC_6DOF_SPRING_CONSTRAINT_H
0
0.867209
1
0.867209
game-dev
MEDIA
0.885211
game-dev
0.890716
1
0.890716
blackbone/other-ecs-benchmarks
1,454
Benchmark/Benchmarks/Entities/AddComponent/Add2ComponentsRandomOrder.cs
using System; using Benchmark.Context; using Benchmark.Utils; using BenchmarkDotNet.Attributes; namespace Benchmark.Benchmarks.Entities.AddComponent; [ArtifactsPath(".benchmark_results/" + nameof(Add2ComponentsRandomOrder<T, TE>))] [MemoryDiagnoser] #if CHECK_CACHE_MISSES [HardwareCounters(BenchmarkDotNet.Diagnosers.HardwareCounter.CacheMisses)] #endif public abstract class Add2ComponentsRandomOrder<T, TE> : IBenchmark<T, TE> where T : IBenchmarkContext<TE> { [Params(Constants.EntityCount)] public int EntityCount { get; set; } public T Context { get; set; } private TE[] _entitySet; [GlobalSetup] public void GlobalSetup() { Context = BenchmarkContext.Create<T>(EntityCount); Context.Setup(); _entitySet = Context.PrepareSet(EntityCount); Context.Warmup<Component1, Component2>(0); Context.FinishSetup(); } [IterationSetup] public void IterationSetup() { Context.CreateEntities(_entitySet); _entitySet.Shuffle(); } [Benchmark] public void Run() { Context.AddComponent<Component1, Component2>(_entitySet, 0, default(Component1), default(Component2)); } [IterationCleanup] public void IterationCleanup() { Context.DeleteEntities(_entitySet); } [GlobalCleanup] public void GlobalCleanup() { Context.Cleanup(); Context.Dispose(); Context = default; } }
0
0.885498
1
0.885498
game-dev
MEDIA
0.854679
game-dev
0.828318
1
0.828318
microsoft/typescript-go
9,600
testdata/baselines/reference/submodule/compiler/findLast(target=es2022).types
//// [tests/cases/compiler/findLast.ts] //// === findLast.ts === const itemNumber: number | undefined = [0].findLast((item) => item === 0); >itemNumber : number >[0].findLast((item) => item === 0) : any >[0].findLast : any >[0] : number[] >0 : 0 >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 const itemString: string | undefined = ["string"].findLast((item) => item === "string"); >itemString : string >["string"].findLast((item) => item === "string") : any >["string"].findLast : any >["string"] : string[] >"string" : "string" >findLast : any >(item) => item === "string" : (item: any) => boolean >item : any >item === "string" : boolean >item : any >"string" : "string" new Int8Array().findLast((item) => item === 0); >new Int8Array().findLast((item) => item === 0) : any >new Int8Array().findLast : any >new Int8Array() : Int8Array<ArrayBuffer> >Int8Array : Int8ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint8Array().findLast((item) => item === 0); >new Uint8Array().findLast((item) => item === 0) : any >new Uint8Array().findLast : any >new Uint8Array() : Uint8Array<ArrayBuffer> >Uint8Array : Uint8ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint8ClampedArray().findLast((item) => item === 0); >new Uint8ClampedArray().findLast((item) => item === 0) : any >new Uint8ClampedArray().findLast : any >new Uint8ClampedArray() : Uint8ClampedArray<ArrayBuffer> >Uint8ClampedArray : Uint8ClampedArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Int16Array().findLast((item) => item === 0); >new Int16Array().findLast((item) => item === 0) : any >new Int16Array().findLast : any >new Int16Array() : Int16Array<ArrayBuffer> >Int16Array : Int16ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint16Array().findLast((item) => item === 0); >new Uint16Array().findLast((item) => item === 0) : any >new Uint16Array().findLast : any >new Uint16Array() : Uint16Array<ArrayBuffer> >Uint16Array : Uint16ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Int32Array().findLast((item) => item === 0); >new Int32Array().findLast((item) => item === 0) : any >new Int32Array().findLast : any >new Int32Array() : Int32Array<ArrayBuffer> >Int32Array : Int32ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint32Array().findLast((item) => item === 0); >new Uint32Array().findLast((item) => item === 0) : any >new Uint32Array().findLast : any >new Uint32Array() : Uint32Array<ArrayBuffer> >Uint32Array : Uint32ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Float32Array().findLast((item) => item === 0); >new Float32Array().findLast((item) => item === 0) : any >new Float32Array().findLast : any >new Float32Array() : Float32Array<ArrayBuffer> >Float32Array : Float32ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Float64Array().findLast((item) => item === 0); >new Float64Array().findLast((item) => item === 0) : any >new Float64Array().findLast : any >new Float64Array() : Float64Array<ArrayBuffer> >Float64Array : Float64ArrayConstructor >findLast : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new BigInt64Array().findLast((item) => item === BigInt(0)); >new BigInt64Array().findLast((item) => item === BigInt(0)) : any >new BigInt64Array().findLast : any >new BigInt64Array() : BigInt64Array<ArrayBuffer> >BigInt64Array : BigInt64ArrayConstructor >findLast : any >(item) => item === BigInt(0) : (item: any) => boolean >item : any >item === BigInt(0) : boolean >item : any >BigInt(0) : bigint >BigInt : BigIntConstructor >0 : 0 new BigUint64Array().findLast((item) => item === BigInt(0)); >new BigUint64Array().findLast((item) => item === BigInt(0)) : any >new BigUint64Array().findLast : any >new BigUint64Array() : BigUint64Array<ArrayBuffer> >BigUint64Array : BigUint64ArrayConstructor >findLast : any >(item) => item === BigInt(0) : (item: any) => boolean >item : any >item === BigInt(0) : boolean >item : any >BigInt(0) : bigint >BigInt : BigIntConstructor >0 : 0 const indexNumber: number = [0].findLastIndex((item) => item === 0); >indexNumber : number >[0].findLastIndex((item) => item === 0) : any >[0].findLastIndex : any >[0] : number[] >0 : 0 >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 const indexString: number = ["string"].findLastIndex((item) => item === "string"); >indexString : number >["string"].findLastIndex((item) => item === "string") : any >["string"].findLastIndex : any >["string"] : string[] >"string" : "string" >findLastIndex : any >(item) => item === "string" : (item: any) => boolean >item : any >item === "string" : boolean >item : any >"string" : "string" new Int8Array().findLastIndex((item) => item === 0); >new Int8Array().findLastIndex((item) => item === 0) : any >new Int8Array().findLastIndex : any >new Int8Array() : Int8Array<ArrayBuffer> >Int8Array : Int8ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint8Array().findLastIndex((item) => item === 0); >new Uint8Array().findLastIndex((item) => item === 0) : any >new Uint8Array().findLastIndex : any >new Uint8Array() : Uint8Array<ArrayBuffer> >Uint8Array : Uint8ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint8ClampedArray().findLastIndex((item) => item === 0); >new Uint8ClampedArray().findLastIndex((item) => item === 0) : any >new Uint8ClampedArray().findLastIndex : any >new Uint8ClampedArray() : Uint8ClampedArray<ArrayBuffer> >Uint8ClampedArray : Uint8ClampedArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Int16Array().findLastIndex((item) => item === 0); >new Int16Array().findLastIndex((item) => item === 0) : any >new Int16Array().findLastIndex : any >new Int16Array() : Int16Array<ArrayBuffer> >Int16Array : Int16ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint16Array().findLastIndex((item) => item === 0); >new Uint16Array().findLastIndex((item) => item === 0) : any >new Uint16Array().findLastIndex : any >new Uint16Array() : Uint16Array<ArrayBuffer> >Uint16Array : Uint16ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Int32Array().findLastIndex((item) => item === 0); >new Int32Array().findLastIndex((item) => item === 0) : any >new Int32Array().findLastIndex : any >new Int32Array() : Int32Array<ArrayBuffer> >Int32Array : Int32ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Uint32Array().findLastIndex((item) => item === 0); >new Uint32Array().findLastIndex((item) => item === 0) : any >new Uint32Array().findLastIndex : any >new Uint32Array() : Uint32Array<ArrayBuffer> >Uint32Array : Uint32ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Float32Array().findLastIndex((item) => item === 0); >new Float32Array().findLastIndex((item) => item === 0) : any >new Float32Array().findLastIndex : any >new Float32Array() : Float32Array<ArrayBuffer> >Float32Array : Float32ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new Float64Array().findLastIndex((item) => item === 0); >new Float64Array().findLastIndex((item) => item === 0) : any >new Float64Array().findLastIndex : any >new Float64Array() : Float64Array<ArrayBuffer> >Float64Array : Float64ArrayConstructor >findLastIndex : any >(item) => item === 0 : (item: any) => boolean >item : any >item === 0 : boolean >item : any >0 : 0 new BigInt64Array().findLastIndex((item) => item === BigInt(0)); >new BigInt64Array().findLastIndex((item) => item === BigInt(0)) : any >new BigInt64Array().findLastIndex : any >new BigInt64Array() : BigInt64Array<ArrayBuffer> >BigInt64Array : BigInt64ArrayConstructor >findLastIndex : any >(item) => item === BigInt(0) : (item: any) => boolean >item : any >item === BigInt(0) : boolean >item : any >BigInt(0) : bigint >BigInt : BigIntConstructor >0 : 0 new BigUint64Array().findLastIndex((item) => item === BigInt(0)); >new BigUint64Array().findLastIndex((item) => item === BigInt(0)) : any >new BigUint64Array().findLastIndex : any >new BigUint64Array() : BigUint64Array<ArrayBuffer> >BigUint64Array : BigUint64ArrayConstructor >findLastIndex : any >(item) => item === BigInt(0) : (item: any) => boolean >item : any >item === BigInt(0) : boolean >item : any >BigInt(0) : bigint >BigInt : BigIntConstructor >0 : 0
0
0.676277
1
0.676277
game-dev
MEDIA
0.642767
game-dev
0.85015
1
0.85015
DeltaEngine/DeltaEngine
4,589
VisualStudioTemplates/Delta Engine/Asteroids/Game.cs
using System.Globalization; using DeltaEngine.Core; using DeltaEngine.Extensions; using DeltaEngine.Scenes; namespace $safeprojectname$ { /// <summary> /// Game Logic and initialization for Asteroids /// </summary> public class Game : Scene { public Game(Window window) { highScores = new int[10]; TryLoadingHighscores(); SetUpBackground(); mainMenu = new Menu(); mainMenu.InitGame += StartGame; mainMenu.QuitGame += window.CloseAfterFrame; InteractionLogic = new InteractionLogic(); mainMenu.UpdateHighscoreDisplay(highScores); } private int[] highScores; private readonly Menu mainMenu; private void TryLoadingHighscores() { /*currently unused var highscorePath = GetHighscorePath(); if (!File.Exists(highscorePath)) return; //ncrunch: no coverage, can't use files in mocks using (var stream = File.OpenRead(highscorePath)) { var reader = new StreamReader(stream); GetHighscoresFromString(reader.ReadToEnd()); } */ } /*unused private static string GetHighscorePath() { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "DeltaEngine", "Asteroids", "Highscores"); } */ public void GetHighscoresFromString(string highscoreString) { if (string.IsNullOrEmpty(highscoreString)) return; var partitions = highscoreString.SplitAndTrim(new[] { ',', ' ' }); highScores = new int[10]; for (int i = 0; i < highScores.Length; i++) try { highScores[i] = int.Parse(partitions[i]); } catch { highScores[i] = 0; } } public void StartGame() { mainMenu.Hide(); Show(); controls = new Controls(this); score = 0; GameState = GameState.Playing; InteractionLogic.BeginGame(); SetUpEvents(); controls.SetControlsToState(GameState); HudInterface = new HudInterface(); } private void SetUpEvents() { InteractionLogic.GameOver += GameOver; InteractionLogic.IncreaseScore += increase => { score += increase; HudInterface.SetScoreText(score); }; } private Controls controls; private int score; public InteractionLogic InteractionLogic { get; private set; } public GameState GameState; public HudInterface HudInterface { get; private set; } private void SetUpBackground() { SetQuadraticBackground("AsteroidsBackground"); } public void GameOver() { if (GameState == GameState.GameOver) return; RefreshHighScores(); InteractionLogic.PauseUpdate(); InteractionLogic.Player.Dispose(); GameState = GameState.GameOver; controls.SetControlsToState(GameState); HudInterface.SetGameOverText(); } public void RestartGame() { InteractionLogic.Restart(); score = 0; HudInterface.SetScoreText(score); HudInterface.SetInGameMode(); GameState = GameState.Playing; controls.SetControlsToState(GameState); } private void RefreshHighScores() { AddLastScoreToHighscoreIfQualified(); mainMenu.UpdateHighscoreDisplay(highScores); SaveHighScore(); } private void SaveHighScore() { /*currently unused var highscoreFilePath = GetHighscorePath(); PathExtensions.CreateDirectoryIfNotExists(Path.GetDirectoryName(highscoreFilePath)); using (FileStream highscoreFile = File.Create(highscoreFilePath)) { var writer = new StreamWriter(highscoreFile); writer.Write(CreateHighscoreString()); writer.Flush(); } */ } //ncrunch: no coverage start private string CreateHighscoreString() { var stringOfScores = highScores[0].ToString(CultureInfo.InvariantCulture); for (int i = 1; i < highScores.Length; i++) stringOfScores += ", " + highScores[i].ToString(CultureInfo.InvariantCulture); return stringOfScores; } public void BackToMenu() { Hide(); InteractionLogic.Dispose(); controls.SetControlsToState(GameState.MainMenu); HudInterface.Dispose(); mainMenu.Show(); } private void AddLastScoreToHighscoreIfQualified() { if (score <= highScores[highScores.Length - 1]) return; if (score > highScores[0]) { highScores[0] = score; return; } for (int i = 0; i < highScores.Length - 2; i++) if (highScores[i] > score && score > highScores[i + 1]) InsertNewScoreAt(i + 1); } private void InsertNewScoreAt(int index) { var scoreBuffer = highScores; highScores = new int[10]; for (int i = 0; i < 10; i++) if (i == index) highScores[i] = score; else if (i > index) highScores[i] = scoreBuffer[i - 1]; else highScores[i] = scoreBuffer[i]; } } }
0
0.729684
1
0.729684
game-dev
MEDIA
0.887113
game-dev
0.945625
1
0.945625
SinlessDevil/TestTaskArmageddonica
4,679
Assets/Plugins/UniTask/Runtime/TimeoutController.cs
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System; using System.Threading; namespace Cysharp.Threading.Tasks { // CancellationTokenSource itself can not reuse but CancelAfter(Timeout.InfiniteTimeSpan) allows reuse if did not reach timeout. // Similar discussion: // https://github.com/dotnet/runtime/issues/4694 // https://github.com/dotnet/runtime/issues/48492 // This TimeoutController emulate similar implementation, using CancelAfterSlim; to achieve zero allocation timeout. public sealed class TimeoutController : IDisposable { readonly static Action<object> CancelCancellationTokenSourceStateDelegate = new Action<object>(CancelCancellationTokenSourceState); static void CancelCancellationTokenSourceState(object state) { var cts = (CancellationTokenSource)state; cts.Cancel(); } CancellationTokenSource timeoutSource; CancellationTokenSource linkedSource; PlayerLoopTimer timer; bool isDisposed; readonly DelayType delayType; readonly PlayerLoopTiming delayTiming; readonly CancellationTokenSource originalLinkCancellationTokenSource; public TimeoutController(DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) { this.timeoutSource = new CancellationTokenSource(); this.originalLinkCancellationTokenSource = null; this.linkedSource = null; this.delayType = delayType; this.delayTiming = delayTiming; } public TimeoutController(CancellationTokenSource linkCancellationTokenSource, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) { this.timeoutSource = new CancellationTokenSource(); this.originalLinkCancellationTokenSource = linkCancellationTokenSource; this.linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, linkCancellationTokenSource.Token); this.delayType = delayType; this.delayTiming = delayTiming; } public CancellationToken Timeout(int millisecondsTimeout) { return Timeout(TimeSpan.FromMilliseconds(millisecondsTimeout)); } public CancellationToken Timeout(TimeSpan timeout) { if (originalLinkCancellationTokenSource != null && originalLinkCancellationTokenSource.IsCancellationRequested) { return originalLinkCancellationTokenSource.Token; } // Timeouted, create new source and timer. if (timeoutSource.IsCancellationRequested) { timeoutSource.Dispose(); timeoutSource = new CancellationTokenSource(); if (linkedSource != null) { this.linkedSource.Cancel(); this.linkedSource.Dispose(); this.linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, originalLinkCancellationTokenSource.Token); } timer?.Dispose(); timer = null; } var useSource = (linkedSource != null) ? linkedSource : timeoutSource; var token = useSource.Token; if (timer == null) { // Timer complete => timeoutSource.Cancel() -> linkedSource will be canceled. // (linked)token is canceled => stop timer timer = PlayerLoopTimer.StartNew(timeout, false, delayType, delayTiming, token, CancelCancellationTokenSourceStateDelegate, timeoutSource); } else { timer.Restart(timeout); } return token; } public bool IsTimeout() { return timeoutSource.IsCancellationRequested; } public void Reset() { timer?.Stop(); } public void Dispose() { if (isDisposed) return; try { // stop timer. timer?.Dispose(); // cancel and dispose. timeoutSource.Cancel(); timeoutSource.Dispose(); if (linkedSource != null) { linkedSource.Cancel(); linkedSource.Dispose(); } } finally { isDisposed = true; } } } }
0
0.730685
1
0.730685
game-dev
MEDIA
0.702257
game-dev
0.858611
1
0.858611
I3oris/ic
29,788
share/crystal-ic/src/compiler/crystal/semantic/literal_expander.cr
module Crystal class LiteralExpander def initialize(@program : Program) @regexes = [] of {String, Regex::CompileOptions} end # Converts an array literal to creating an Array and storing the values: # # From: # # [] of T # # To: # # Array(T).new # # From: # # [1, 2, 3] # # To: # # ary = ::Array(typeof(1, 2, 3)).unsafe_build(3) # buf = ary.to_unsafe # buf[0] = 1 # buf[1] = 2 # buf[2] = 3 # ary # # From: # # [1, *exp2, *exp3, 4] # # To: # # temp1 = exp2 # temp2 = exp3 # ary = ::Array(typeof(1, ::Enumerable.element_type(temp1), ::Enumerable.element_type(temp2), 4)).new(2) # ary << 1 # ary.concat(temp1) # ary.concat(temp2) # ary << 4 # ary def expand(node : ArrayLiteral) elem_temp_vars, elem_temp_var_count = complex_elem_temp_vars(node.elements) if node_of = node.of type_var = node_of else type_var = typeof_exp(node, elem_temp_vars) end capacity = node.elements.count { |elem| !elem.is_a?(Splat) } generic = Generic.new(Path.global("Array"), type_var).at(node) if node.elements.any?(Splat) ary_var = new_temp_var.at(node) ary_instance = Call.new(generic, "new", NumberLiteral.new(capacity).at(node)).at(node) exps = Array(ASTNode).new(node.elements.size + elem_temp_var_count + 2) elem_temp_vars.try &.each_with_index do |elem_temp_var, i| next unless elem_temp_var elem_exp = node.elements[i] elem_exp = elem_exp.exp if elem_exp.is_a?(Splat) exps << Assign.new(elem_temp_var, elem_exp.clone).at(elem_temp_var) end exps << Assign.new(ary_var.clone, ary_instance).at(node) node.elements.each_with_index do |elem, i| temp_var = elem_temp_vars.try &.[i] if elem.is_a?(Splat) exps << Call.new(ary_var.clone, "concat", (temp_var || elem.exp).clone).at(node) else exps << Call.new(ary_var.clone, "<<", (temp_var || elem).clone).at(node) end end exps << ary_var Expressions.new(exps).at(node) elsif capacity.zero? Call.new(generic, "new").at(node) else ary_var = new_temp_var.at(node) ary_instance = Call.new(generic, "unsafe_build", NumberLiteral.new(capacity).at(node)).at(node) buffer = Call.new(ary_var, "to_unsafe").at(node) buffer_var = new_temp_var.at(node) exps = Array(ASTNode).new(node.elements.size + elem_temp_var_count + 3) elem_temp_vars.try &.each_with_index do |elem_temp_var, i| next unless elem_temp_var elem_exp = node.elements[i] exps << Assign.new(elem_temp_var, elem_exp.clone).at(elem_temp_var) end exps << Assign.new(ary_var.clone, ary_instance).at(node) exps << Assign.new(buffer_var, buffer).at(node) node.elements.each_with_index do |elem, i| temp_var = elem_temp_vars.try &.[i] exps << Call.new(buffer_var.clone, "[]=", NumberLiteral.new(i).at(node), (temp_var || elem).clone).at(node) end exps << ary_var.clone Expressions.new(exps).at(node) end end def complex_elem_temp_vars(elems : Array, &) temp_vars = nil count = 0 elems.each_with_index do |elem, i| elem = yield elem elem = elem.exp if elem.is_a?(Splat) next if elem.is_a?(Var) || elem.is_a?(InstanceVar) || elem.is_a?(ClassVar) || elem.simple_literal? temp_vars ||= Array(Var?).new(elems.size, nil) temp_vars[i] = new_temp_var.at(elem) count += 1 end {temp_vars, count} end def complex_elem_temp_vars(elems : Array(ASTNode)) complex_elem_temp_vars(elems, &.itself) end def typeof_exp(node : ArrayLiteral, temp_vars : Array(Var?)? = nil) type_exps = node.elements.map_with_index do |elem, i| temp_var = temp_vars.try &.[i] if elem.is_a?(Splat) Call.new(Path.global("Enumerable").at(node), "element_type", (temp_var || elem.exp).clone).at(node) else (temp_var || elem).clone end end TypeOf.new(type_exps).at(node) end # Converts an array-like literal to creating a container and storing the values: # # From: # # T{1, 2, 3} # # To: # # ary = T.new # ary << 1 # ary << 2 # ary << 3 # ary # # From: # # T{1, *exp2, *exp3, 4} # # To: # # ary = T.new # ary << 1 # exp2.each { |v| ary << v } # exp3.each { |v| ary << v } # ary << 4 # ary # # If `T` is an uninstantiated generic type, injects a `typeof` with the # element types. def expand_named(node : ArrayLiteral, generic_type : ASTNode?) elem_temp_vars, elem_temp_var_count = complex_elem_temp_vars(node.elements) if generic_type type_of = typeof_exp(node, elem_temp_vars) node_name = Generic.new(generic_type, type_of).at(node) else node_name = node.name end constructor = Call.new(node_name, "new").at(node) if node.elements.empty? return constructor end ary_var = new_temp_var.at(node) exps = Array(ASTNode).new(node.elements.size + elem_temp_var_count + 2) elem_temp_vars.try &.each_with_index do |elem_temp_var, i| next unless elem_temp_var elem_exp = node.elements[i] elem_exp = elem_exp.exp if elem_exp.is_a?(Splat) exps << Assign.new(elem_temp_var, elem_exp.clone).at(elem_temp_var) end exps << Assign.new(ary_var.clone, constructor).at(node) node.elements.each_with_index do |elem, i| temp_var = elem_temp_vars.try &.[i] if elem.is_a?(Splat) yield_var = new_temp_var each_body = Call.new(ary_var.clone, "<<", yield_var.clone).at(node) each_block = Block.new(args: [yield_var], body: each_body).at(node) exps << Call.new((temp_var || elem.exp).clone, "each", block: each_block).at(node) else exps << Call.new(ary_var.clone, "<<", (temp_var || elem).clone).at(node) end end exps << ary_var Expressions.new(exps).at(node) end # Converts a hash literal into creating a Hash and assigning keys and values. # # Equivalent to a hash-like literal using `::Hash`. def expand(node : HashLiteral) expand_named(node, Path.global("Hash")) end # Converts a hash-like literal into creating a Hash and assigning keys and values: # # From: # # T{} # # To: # # T.new # # From: # # {} of K => V # # To: # # ::Hash(K, V).new # # From: # # T{a => b, c => d} # # To: # # hash = T.new # hash[a] = b # hash[c] = d # hash # # Or if `T` is an uninstantiated generic type: # # hash = T(typeof(a, c), typeof(b, d)).new # hash[a] = b # hash[c] = d # hash def expand_named(node : HashLiteral, generic_type : ASTNode?) key_temp_vars, key_temp_var_count = complex_elem_temp_vars(node.entries, &.key) value_temp_vars, value_temp_var_count = complex_elem_temp_vars(node.entries, &.value) if of = node.of # `generic_type` is nil here type_vars = [of.key, of.value] of ASTNode generic = Generic.new(Path.global("Hash"), type_vars).at(node) elsif generic_type # `node.entries` is non-empty here typeof_key = TypeOf.new(node.entries.map_with_index { |x, i| (key_temp_vars.try(&.[i]) || x.key).clone.as(ASTNode) }).at(node) typeof_value = TypeOf.new(node.entries.map_with_index { |x, i| (value_temp_vars.try(&.[i]) || x.value).clone.as(ASTNode) }).at(node) generic = Generic.new(generic_type, [typeof_key, typeof_value] of ASTNode).at(node) else generic = node.name end constructor = Call.new(generic, "new").at(node) return constructor if node.entries.empty? hash_var = new_temp_var exps = Array(ASTNode).new(node.entries.size + key_temp_var_count + value_temp_var_count + 2) key_temp_vars.try &.each_with_index do |key_temp_var, i| next unless key_temp_var key_exp = node.entries[i].key exps << Assign.new(key_temp_var, key_exp.clone).at(key_temp_var) end value_temp_vars.try &.each_with_index do |value_temp_var, i| next unless value_temp_var value_exp = node.entries[i].value exps << Assign.new(value_temp_var, value_exp.clone).at(value_temp_var) end exps << Assign.new(hash_var.clone, constructor).at(node) node.entries.each_with_index do |entry, i| key_exp = key_temp_vars.try(&.[i]) || entry.key value_exp = value_temp_vars.try(&.[i]) || entry.value exps << Call.new(hash_var.clone, "[]=", key_exp.clone, value_exp.clone).at(node) end exps << hash_var Expressions.new(exps).at(node) end # From: # # /regex/flags # # To declaring a constant with this value (if not already declared): # # ``` # Regex.new("regex", Regex::Options.new(flags)) # ``` # # and then reading from that constant. # That is, we cache regex literals to avoid recompiling them all of the time. # # Only do this for regex literals that don't contain interpolation. # If there's an interpolation, expand to: Regex.new(interpolation, flags) def expand(node : RegexLiteral) node_value = node.value case node_value when StringLiteral string = node_value.value key = {string, node.options} index = @regexes.index(key) || @regexes.size const_name = "$Regex:#{index}" if index == @regexes.size @regexes << key const_value = regex_new_call(node, StringLiteral.new(string).at(node)) const = Const.new(@program, @program, const_name, const_value) @program.types[const_name] = const else const = @program.types[const_name].as(Const) end Path.new(const_name).at(const.value) else regex_new_call(node, node_value) end end private def regex_new_call(node, value) Call.new(Path.global("Regex").at(node), "new", value, regex_options(node)).at(node) end private def regex_options(node) Call.new(Path.global(["Regex", "Options"]).at(node), "new", NumberLiteral.new(node.options.value.to_s).at(node)).at(node) end # Convert and to if: # # From: # # a && b # # To: # # if temp = a # b # else # temp # end def expand(node : And) left = node.left.single_expression new_node = if left.is_a?(Var) || (left.is_a?(IsA) && left.obj.is_a?(Var)) If.new(left, node.right, left.clone).at(node) elsif left.is_a?(Assign) && left.target.is_a?(Var) If.new(left, node.right, left.target.clone).at(node) elsif left.is_a?(Not) && left.exp.is_a?(Var) If.new(left, node.right, left.clone).at(node) elsif left.is_a?(Not) && ((left_exp = left.exp).is_a?(IsA) && left_exp.obj.is_a?(Var)) If.new(left, node.right, left.clone).at(node) else temp_var = new_temp_var If.new(Assign.new(temp_var.clone, left).at(node), node.right, temp_var.clone).at(node) end new_node.and = true new_node.location = node.location new_node end # Convert or to if # # From: # # a || b # # To: # # if temp = a # temp # else # b # end def expand(node : Or) left = node.left.single_expression new_node = if left.is_a?(Var) || (left.is_a?(IsA) && left.obj.is_a?(Var)) If.new(left, left.clone, node.right).at(node) elsif left.is_a?(Assign) && left.target.is_a?(Var) If.new(left, left.target.clone, node.right).at(node) elsif left.is_a?(Not) && left.exp.is_a?(Var) If.new(left, left.clone, node.right).at(node) elsif left.is_a?(Not) && ((left_exp = left.exp).is_a?(IsA) && left_exp.obj.is_a?(Var)) If.new(left, left.clone, node.right).at(node) else temp_var = new_temp_var If.new(Assign.new(temp_var.clone, left).at(node), temp_var.clone, node.right).at(node) end new_node.or = true new_node.location = node.location new_node end # Transform a range literal into creating a Range object. # # From: # # 1 .. 3 # # To: # # Range.new(1, 3, true) # # From: # # 1 ... 3 # # To: # # Range.new(1, 3, false) def expand(node : RangeLiteral) path = Path.global("Range").at(node) bool = BoolLiteral.new(node.exclusive?).at(node) Call.new(path, "new", node.from, node.to, bool).at(node) end # Convert an interpolation to a call to `String.interpolation` # # From: # # "foo#{bar}baz#{qux}" # # To: # # String.interpolation("foo", bar, "baz", qux) def expand(node : StringInterpolation) # We could do `node.expressions.dup` for more purity, # but the string interpolation isn't used later on so this is fine, # and having pieces in a different representation but same end # result is just fine. pieces = node.expressions combine_contiguous_string_literals(pieces) Call.new(Path.global("String").at(node), "interpolation", pieces).at(node) end private def combine_contiguous_string_literals(pieces) i = 0 pieces.reject! do |piece| delete = if i < pieces.size - 1 next_piece = pieces[i + 1] if piece.is_a?(StringLiteral) && next_piece.is_a?(StringLiteral) pieces[i + 1] = StringLiteral.new(piece.value + next_piece.value) true else false end else false end i += 1 delete end end # Convert a Case into a series of if ... elseif ... end: # # From: # # case foo # when bar, baz # 1 # when bun # 2 # else # 3 # end # # To: # # temp = foo # if bar === temp || baz === temp # 1 # elsif bun === temp # 2 # else # 3 # end # # But, when the "when" has a constant name, it's transformed to is_a?: # # From: # # case foo # when Bar # 1 # end # # To: # # temp = foo # if temp.is_a?(Bar) # 1 # end # # We also take care to expand multiple conds # # From: # # case {x, y} # when {1, 2}, {3, 4} # 3 # end # # To: # # if (1 === x && y === 2) || (3 === x && 4 === y) # 3 # end def expand(node : Case) node_cond = node.cond if node.whens.empty? expressions = [] of ASTNode node_else = node.else if node_cond expressions << node_cond expressions << NilLiteral.new unless node_else end if node_else expressions << node_else end return Expressions.new(expressions).at(node) end if node_cond if node_cond.is_a?(TupleLiteral) conds = node_cond.elements else conds = [node_cond] end assigns = [] of ASTNode temp_vars = conds.map do |cond| case cond = cond.single_expression when Var, InstanceVar temp_var = cond when Assign temp_var = cond.target assigns << cond else temp_var = new_temp_var assigns << Assign.new(temp_var.clone, cond).at(node_cond) end temp_var end end a_if = nil final_if = nil node.whens.each do |wh| final_comp = nil wh.conds.each do |cond| next if cond.is_a?(Underscore) if node_cond.is_a?(TupleLiteral) if cond.is_a?(TupleLiteral) comp = nil cond.elements.zip(temp_vars.not_nil!) do |lh, rh| next if lh.is_a?(Underscore) sub_comp = case_when_comparison(rh, lh).at(cond) if comp comp = And.new(comp, sub_comp).at(comp) else comp = sub_comp end end else comp = case_when_comparison(TupleLiteral.new(temp_vars.not_nil!.clone), cond).at(cond) end else temp_var = temp_vars.try &.first comp = case_when_comparison(temp_var, cond).at(cond) end next unless comp if final_comp final_comp = Or.new(final_comp, comp).at(final_comp) else final_comp = comp end end final_comp ||= BoolLiteral.new(true) wh_if = If.new(final_comp, wh.body).at(final_comp) if a_if a_if.else = wh_if else final_if = wh_if end a_if = wh_if end if node.exhaustive? a_if.not_nil!.else = node.else || Unreachable.new elsif node_else = node.else a_if.not_nil!.else = node_else end final_if = final_if.not_nil! final_exp = if assigns && !assigns.empty? assigns << final_if Expressions.new(assigns).at(node) else final_if end final_exp.location = node.location final_exp end # Convert a `select` statement into a `case` statement based on `Channel.select` # # From: # # select # when foo then body # when x = bar then x.baz # end # # To: # # %index, %value = ::Channel.select({foo_select_action, bar_select_action}) # case %index # when 0 # body # when 1 # x = value.as(typeof(foo)) # x.baz # else # ::raise("BUG: invalid select index") # end # # # If there's an `else` branch, use `Channel.non_blocking_select`. # # From: # # select # when foo then body # else qux # end # # To: # # %index, %value = ::Channel.non_blocking_select({foo_select_action}) # case %index # when 0 # body # else # qux # end # def expand(node : Select) index_name = @program.new_temp_var_name value_name = @program.new_temp_var_name targets = [Var.new(index_name).at(node), Var.new(value_name).at(node)] of ASTNode channel = Path.global("Channel").at(node) tuple_values = [] of ASTNode case_whens = [] of When node.whens.each_with_index do |a_when, index| condition = a_when.conds.first case condition when Call cloned_call = condition.clone cloned_call.name = select_action_name(cloned_call.name) tuple_values << cloned_call case_whens << When.new([NumberLiteral.new(index).at(node)] of ASTNode, a_when.body.clone) when Assign cloned_call = condition.value.as(Call).clone cloned_call.name = select_action_name(cloned_call.name) tuple_values << cloned_call typeof_node = TypeOf.new([condition.value.clone] of ASTNode).at(node) cast = Cast.new(Var.new(value_name).at(node), typeof_node).at(node) new_assign = Assign.new(condition.target.clone, cast).at(node) new_body = Expressions.new([new_assign, a_when.body.clone] of ASTNode) case_whens << When.new([NumberLiteral.new(index).at(node)] of ASTNode, new_body) else node.raise "BUG: expected select when expression to be Assign or Call, not #{condition}" end end if node_else = node.else case_else = node_else.clone else case_else = Call.new("raise", StringLiteral.new("BUG: invalid select index"), global: true).at(node) end call = Call.new( channel, node.else ? "non_blocking_select" : "select", TupleLiteral.new(tuple_values).at(node), ).at(node) multi = MultiAssign.new(targets, [call] of ASTNode) case_cond = Var.new(index_name).at(node) a_case = Case.new(case_cond, case_whens, case_else, exhaustive: false).at(node) Expressions.from([multi, a_case] of ASTNode).at(node) end def select_action_name(name) case name when .ends_with? "!" name[0...-1] + "_select_action!" when .ends_with? "?" name[0...-1] + "_select_action?" else name + "_select_action" end end # Transform a multi assign into many assigns. def expand(node : MultiAssign) splat_index = nil splat_underscore = false node.targets.each_with_index do |target, i| if target.is_a?(Splat) raise "BUG: splat assignment already specified" if splat_index splat_index = i splat_underscore = true if target.exp.is_a?(Underscore) end end # From: # # a, b = [1, 2] # # # To: # # temp = [1, 2] # a = temp[0] # b = temp[1] # # If the flag "strict_multi_assign" is present, requires `temp`'s size to # match the number of assign targets exactly: (it must respond to `#size`) # # temp = [1, 2] # raise ... if temp.size != 2 # a = temp[0] # b = temp[1] # # From: # # a, *b, c, d = [1, 2] # # To: # # temp = [1, 2] # raise ... if temp.size < 3 # a = temp[0] # b = temp[1..-3] # c = temp[-2] # d = temp[-1] # # Except any assignments to *_, including the indexing call, are omitted # altogether. if node.values.size == 1 value = node.values[0] middle_splat = splat_index && (0 < splat_index < node.targets.size - 1) raise_on_count_mismatch = @program.has_flag?("strict_multi_assign") || middle_splat temp_var = new_temp_var # temp = ... assigns = Array(ASTNode).new(node.targets.size + (splat_underscore ? 0 : 1) + (raise_on_count_mismatch ? 1 : 0)) assigns << Assign.new(temp_var.clone, value).at(value) # raise ... if temp.size < ... if raise_on_count_mismatch size_call = Call.new(temp_var.clone, "size").at(value) if middle_splat size_comp = Call.new(size_call, "<", NumberLiteral.new(node.targets.size - 1)).at(value) else size_comp = Call.new(size_call, "!=", NumberLiteral.new(node.targets.size)).at(value) end index_error = Call.new(Path.global("IndexError"), "new", StringLiteral.new("Multiple assignment count mismatch")).at(value) raise_call = Call.global("raise", index_error).at(value) assigns << If.new(size_comp, raise_call).at(value) end # ... = temp[...] node.targets.each_with_index do |target, i| if i == splat_index next if splat_underscore indexer = RangeLiteral.new( NumberLiteral.new(i), NumberLiteral.new(i - node.targets.size), false, ).at(value) else indexer = NumberLiteral.new(splat_index && i > splat_index ? i - node.targets.size : i) end call = Call.new(temp_var.clone, "[]", indexer).at(value) assigns << transform_multi_assign_target(target, call) end exps = Expressions.new(assigns) # From: # # a, b = c, d # # To: # # temp1 = c # temp2 = d # a = temp1 # b = temp2 # # From: # # a, *b, c = d, e, f, g # # To: # # temp1 = d # temp2 = ::Tuple.new(e, f) # temp3 = g # a = temp1 # b = temp2 # c = temp3 # # Except values assigned to `*_` are evaluated directly where the # `Tuple` would normally be constructed, and no assignments to `_` would # actually take place. else if splat_index raise "BUG: multiple assignment count mismatch" if node.targets.size - 1 > node.values.size else raise "BUG: multiple assignment count mismatch" if node.targets.size != node.values.size end assign_to_count = splat_underscore ? node.values.size : node.targets.size assign_from_count = node.targets.size - (splat_underscore ? 1 : 0) assign_to_temps = Array(ASTNode).new(assign_to_count) assign_from_temps = Array(ASTNode).new(assign_from_count) node.targets.each_with_index do |target, i| if i == splat_index if splat_underscore node.values.each(within: i..i - node.targets.size) do |value| assign_to_temps << value end next end value = Call.new(Path.global("Tuple").at(node), "new", node.values[i..i - node.targets.size]) else value = node.values[splat_index && i > splat_index ? i - node.targets.size : i] end temp_var = new_temp_var assign_to_temps << Assign.new(temp_var.clone, value).at(node) assign_from_temps << transform_multi_assign_target(target, temp_var.clone) end exps = Expressions.new(assign_to_temps.concat(assign_from_temps)) end exps.location = node.location exps end def transform_multi_assign_target(target, value) if target.is_a?(Splat) target = target.exp end if target.is_a?(Call) target.name = "#{target.name}=" target.args << value target else Assign.new(target, value).at(target) end end private def case_when_comparison(temp_var, cond) return cond unless temp_var right_side = temp_var.clone check_implicit_obj Call check_implicit_obj RespondsTo check_implicit_obj IsA check_implicit_obj Cast check_implicit_obj NilableCast check_implicit_obj Not case cond when NilLiteral return IsA.new(right_side, Path.global("Nil")) when Path, Generic return IsA.new(right_side, cond) when Call obj = cond.obj case obj when Path if cond.name == "class" return IsA.new(right_side, Metaclass.new(obj).at(obj)) end when Generic if cond.name == "class" return IsA.new(right_side, Metaclass.new(obj).at(obj)) end else # no special treatment end else # no special treatment end Call.new(cond, "===", right_side) end macro check_implicit_obj(type) if cond.is_a?({{type}}) cond_obj = cond.is_a?(Not) ? cond.exp : cond.obj if cond_obj.is_a?(ImplicitObj) implicit_call = cond.clone.as({{type}}) if implicit_call.is_a?(Not) implicit_call.exp = temp_var.clone else implicit_call.obj = temp_var.clone end return implicit_call end end end # Expand this: # # ``` # ->foo.bar(X, Y) # ``` # # To this: # # ``` # tmp = foo # ->(x : X, y : Y) { tmp.bar(x, y) } # ``` # # Expand this: # # ``` # ->Foo.bar(X, Y) # ``` # # To this: # # ``` # ->(x : X, y : Y) { Foo.bar(x, y) } # ``` # # Expand this: # # ``` # ->bar(X, Y) # ``` # # To this: # # ``` # ->(x : X, y : Y) { bar(x, y) } # ``` # # in case the implicit `self` is a class or a virtual class. def expand(node : ProcPointer) obj = node.obj if obj && !obj.is_a?(Path) temp_var = new_temp_var.at(obj) assign = Assign.new(temp_var, obj) obj = temp_var end def_args = node.args.map do |arg| Arg.new(@program.new_temp_var_name, restriction: arg).at(arg) end call_args = def_args.map do |def_arg| Var.new(def_arg.name).at(def_arg).as(ASTNode) end body = Call.new(obj, node.name, call_args, global: node.global?).at(node) proc_literal = ProcLiteral.new(Def.new("->", def_args, body).at(node)).at(node) proc_literal.proc_pointer = node if assign Expressions.new([assign, proc_literal]) else proc_literal end end def expand(node) raise "#{node} (#{node.class}) can't be expanded" end def new_temp_var @program.new_temp_var end end end
0
0.79519
1
0.79519
game-dev
MEDIA
0.272658
game-dev
0.913886
1
0.913886
rwengine/openrw
2,979
rwcore/fonts/Unicode.cpp
#include "Unicode.hpp" #include <istream> size_t unicode_to_utf8(unicode_t unicode, char c[4]) { if (unicode < 0x80) { // 7 bits c[0] = static_cast<char>(unicode); return 1; } else if (unicode < 0x800) { // 11 bits c[0] = static_cast<char>(0xc0 | (unicode >> 6)); c[1] = static_cast<char>(0x80 | (unicode & 0x3f)); return 2; } else if (unicode < 0x10000) { // 16 bits c[0] = static_cast<char>(0xe0 | (unicode >> 12)); c[1] = static_cast<char>(0x80 | ((unicode >> 6) & 0x3f)); c[2] = static_cast<char>(0x80 | (unicode & 0x3f)); return 3; } else if (unicode < 0x110000) { // 21 bits c[0] = static_cast<char>(0xf0 | (unicode >> 18)); c[1] = static_cast<char>(0x80 | ((unicode >> 12) & 0x3f)); c[2] = static_cast<char>(0x80 | ((unicode >> 6) & 0x3f)); c[3] = static_cast<char>(0x80 | (unicode & 0x3f)); return 4; } else { return unicode_to_utf8(UnicodeValue::UNICODE_REPLACEMENT_CHARACTER, c); } } Utf8UnicodeIterator::Utf8UnicodeIterator(std::istream &is) : m_is(&is), m_finished(false) { next_unicode(); } void Utf8UnicodeIterator::next_unicode() { int c = m_is->get(); if (c == EOF) { m_finished = true; return; } char cc = static_cast<char>(c); unicode_t unicode; unsigned nb_bytes; if ((cc & 0x80) == 0x00) { unicode = cc; nb_bytes = 0; } else if ((c & 0xe0) == 0xc0) { unicode = c & 0x1f; nb_bytes = 1; } else if ((c & 0xf0) == 0xe0) { unicode = c & 0x0f; nb_bytes = 2; } else if ((c & 0xf8) == 0xf0) { unicode = c & 0x07; nb_bytes = 3; } else { unicode = UnicodeValue::UNICODE_REPLACEMENT_CHARACTER; nb_bytes = 0; } while (nb_bytes != 0) { c = m_is->get(); if (c == EOF) { unicode = UnicodeValue::UNICODE_REPLACEMENT_CHARACTER; m_finished = true; break; } cc = static_cast<char>(c); if ((c & 0xc0) != 0x80) { unicode = UnicodeValue::UNICODE_REPLACEMENT_CHARACTER; break; } unicode = (unicode << 6) | (c & 0x3f); --nb_bytes; } m_unicode = unicode; } Utf8UnicodeIterator &Utf8UnicodeIterator::operator ++() { next_unicode(); return *this; } unicode_t Utf8UnicodeIterator::unicode() const { return m_unicode; } unicode_t Utf8UnicodeIterator::operator *() const { return m_unicode; } bool Utf8UnicodeIterator::good() const { return !m_finished; } Utf8UnicodeIteratorWrapper::Utf8UnicodeIteratorWrapper(const std::string &s) : iss(s) { } Utf8UnicodeIterator Utf8UnicodeIteratorWrapper::begin() { return Utf8UnicodeIterator(iss); } Utf8UnicodeIterator Utf8UnicodeIteratorWrapper::end() { return Utf8UnicodeIterator(); } bool Utf8UnicodeIterator::operator !=(const Utf8UnicodeIterator &) { return good(); }
0
0.73732
1
0.73732
game-dev
MEDIA
0.207704
game-dev
0.854269
1
0.854269
manticoresoftware/manticoresearch
9,099
src/tokenizer/exceptions_trie.cpp
// // Copyright (c) 2017-2025, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #include "exceptions_trie.h" #include "sphinxstd.h" #include "fileio.h" #include "sphinxutils.h" #include "sphinxjson.h" #include "tok_internals.h" ///////////////////////////////////////////////////////////////////////////// // TOKENIZING EXCEPTIONS ///////////////////////////////////////////////////////////////////////////// using WriterTrie_fn = std::function<void (const char*)>; struct WriterTrie_t { WriterTrie_t ( const VecTraits_T<BYTE> & dData, int iMappings, WriterTrie_fn && fnWrite ) : m_dData ( dData ) , m_iMappings ( iMappings ) , m_fnWrite ( std::move ( fnWrite ) ) { } const VecTraits_T<BYTE> & m_dData; int m_iMappings; GtEscapedBuilder m_sLine; int m_iCount = 0; CSphVector<BYTE> m_dPrefix; WriterTrie_fn m_fnWrite; bool m_bAddNL = false; void Write ( int iNode ); }; /// exceptions trie, stored in a tidy simple blob /// we serialize each trie node as follows: /// /// int result_offset, 0 if no output mapping /// BYTE num_bytes, 0 if no further valid bytes can be accepted /// BYTE values[num_bytes], known accepted byte values /// BYTE offsets[num_bytes], and the respective next node offsets /// /// output mappings themselves are serialized just after the nodes, /// as plain old ASCIIZ strings void WriterTrie_t::Write ( int iNode ) { assert ( iNode>=0 && iNode<m_iMappings ); const BYTE * p = m_dData.Begin() + iNode; int iTo = *(int*)const_cast<BYTE*> ( p ); if ( iTo>0 ) { m_sLine.Clear(); const char * sTo = (const char *)m_dData.Begin() + iTo; m_sLine.AppendEscapedWithCommaNoQuotes ( (char*)m_dPrefix.Begin(), m_dPrefix.GetLength() ); m_sLine.Appendf ( " => %s", sTo ); if ( m_bAddNL ) m_sLine.Appendf ( "\n" ); m_fnWrite ( m_sLine.cstr() ); m_iCount++; } int n = p[4]; if ( n==0 ) return; p += 5; for ( int i=0; i<n; i++ ) { m_dPrefix.Add ( p[i] ); int iChild = *(int*)&p[n + 4 * i]; Write ( iChild ); m_dPrefix.Pop(); } } void ExceptionsTrie_c::Export ( Writer_i & tWr ) const { WriterTrie_t tDataWriter ( m_dData, m_iMappings, [&tWr] ( const char * szLine ) { tWr.PutString ( szLine ); } ); tDataWriter.m_bAddNL = true; tWr.PutDword ( m_iCount ); tDataWriter.Write ( 0 ); assert ( tDataWriter.m_iCount==m_iCount ); } void ExceptionsTrie_c::Export ( JsonEscapedBuilder & tOut ) const { WriterTrie_t tDataWriter ( m_dData, m_iMappings, [&tOut] (const char* szLine) { tOut.FixupSpacedAndAppendEscaped ( szLine ); } ); tDataWriter.Write ( 0 ); assert ( tDataWriter.m_iCount==m_iCount ); } /// intermediate exceptions trie node /// only used by ExceptionsTrieGen_c, while building a blob class ExceptionsTrieNode_c { friend class ExceptionsTrieGen_c; struct Entry_t { BYTE m_uValue; ExceptionsTrieNode_c* m_pKid; }; CSphString m_sTo; ///< output mapping for current prefix, if any CSphVector<Entry_t> m_dKids; ///< known and accepted incoming byte values public: ~ExceptionsTrieNode_c() { for ( auto& dKid: m_dKids ) SafeDelete ( dKid.m_pKid ); } /// returns false on a duplicate "from" part, or true on success bool AddMapping ( const BYTE* sFrom, const BYTE* sTo ) { // no more bytes to consume? this is our output mapping then if ( !*sFrom ) { if ( !m_sTo.IsEmpty() ) return false; m_sTo = (const char*)sTo; return true; } int i; for ( i = 0; i < m_dKids.GetLength(); i++ ) if ( m_dKids[i].m_uValue == *sFrom ) break; if ( i == m_dKids.GetLength() ) { Entry_t& t = m_dKids.Add(); t.m_uValue = *sFrom; t.m_pKid = new ExceptionsTrieNode_c(); } return m_dKids[i].m_pKid->AddMapping ( sFrom + 1, sTo ); } }; /// exceptions trie builder /// plain old text mappings in, nice useful trie out class ExceptionsTrieGen_c::Impl_c { ExceptionsTrieNode_c* m_pRoot; int m_iCount; public: Impl_c() { m_pRoot = new ExceptionsTrieNode_c(); m_iCount = 0; } ~Impl_c() { SafeDelete ( m_pRoot ); } /// trims left/right whitespace, folds inner whitespace void FoldSpace ( char* s ) const { // skip leading spaces char* d = s; while ( *s && ( sphIsSpace ( *s ) || *s=='\\' ) ) s++; // handle degenerate (empty string) case if ( !*s ) { *d = '\0'; return; } while ( *s ) { // copy another token, add exactly 1 space after it, and skip whitespace while ( *s && !sphIsSpace ( *s ) ) { if ( *s=='\\' ) s++; else *d++ = *s++; } *d++ = ' '; while ( sphIsSpace ( *s ) || *s=='\\' ) s++; } // replace that last space that we added d[-1] = '\0'; } bool ParseLine ( char* sBuffer, CSphString& sError ) { #define LOC_ERR( _arg ) { sError = _arg; return false; } assert ( m_pRoot ); // extract map-from and map-to parts char* sSplit = strstr ( sBuffer, "=>" ); if ( !sSplit ) LOC_ERR ( "mapping token (=>) not found" ); char* sFrom = sBuffer; char* sTo = sSplit + 2; // skip "=>" *sSplit = '\0'; // trim map-from, map-to FoldSpace ( sFrom ); FoldSpace ( sTo ); if ( !*sFrom ) LOC_ERR ( "empty map-from part" ); if ( !*sTo ) LOC_ERR ( "empty map-to part" ); if ( (int)strlen ( sFrom ) > MAX_KEYWORD_BYTES ) LOC_ERR ( "map-from part too long" ); if ( (int)strlen ( sTo ) > MAX_KEYWORD_BYTES ) LOC_ERR ( "map-from part too long" ); // all parsed ok; add it! if ( m_pRoot->AddMapping ( (BYTE*)sFrom, (BYTE*)sTo ) ) m_iCount++; else LOC_ERR ( "duplicate map-from part" ); return true; #undef LOC_ERR } ExceptionsTrie_c* Build() { if ( !m_pRoot || !m_pRoot->m_sTo.IsEmpty() || m_pRoot->m_dKids.GetLength() == 0 ) return nullptr; auto* pRes = new ExceptionsTrie_c(); pRes->m_iCount = m_iCount; // save the nodes themselves CSphVector<BYTE> dMappings; SaveNode ( pRes, m_pRoot, dMappings ); // append and fixup output mappings CSphVector<BYTE>& d = pRes->m_dData; pRes->m_iMappings = d.GetLength(); d.Append ( dMappings ); BYTE* p = d.Begin(); BYTE* pMax = p + pRes->m_iMappings; while ( p < pMax ) { // fixup offset in the current node, if needed int* pOff = (int*)p; // FIXME? unaligned if ( ( *pOff ) < 0 ) *pOff = 0; // convert -1 to 0 for non-outputs else ( *pOff ) += pRes->m_iMappings; // fixup offsets for outputs // proceed to the next node int n = p[4]; p += 5 + 5 * n; } assert ( p == pMax ); // build the speedup table for the very 1st byte for (int & i : pRes->m_dFirst) i = -1; int n = d[4]; for ( int i = 0; i < n; i++ ) pRes->m_dFirst[d[5 + i]] = *(int*)&pRes->m_dData[5 + n + 4 * i]; SafeDelete ( m_pRoot ); m_pRoot = new ExceptionsTrieNode_c(); m_iCount = 0; return pRes; } private: void SaveInt ( CSphVector<BYTE>& v, int p, int x ) { #if USE_LITTLE_ENDIAN v[p] = x & 0xff; v[p + 1] = ( x >> 8 ) & 0xff; v[p + 2] = ( x >> 16 ) & 0xff; v[p + 3] = ( x >> 24 ) & 0xff; #else v[p] = ( x >> 24 ) & 0xff; v[p + 1] = ( x >> 16 ) & 0xff; v[p + 2] = ( x >> 8 ) & 0xff; v[p + 3] = x & 0xff; #endif } int SaveNode ( ExceptionsTrie_c* pRes, ExceptionsTrieNode_c* pNode, CSphVector<BYTE>& dMappings ) { CSphVector<BYTE>& d = pRes->m_dData; // shortcut // remember the start node offset int iRes = d.GetLength(); int n = pNode->m_dKids.GetLength(); assert ( !( pNode->m_sTo.IsEmpty() && n == 0 ) ); // save offset into dMappings, or temporary (!) save -1 if there is no output mapping // note that we will fixup those -1's to 0's afterwards int iOff = -1; if ( !pNode->m_sTo.IsEmpty() ) { iOff = dMappings.GetLength(); int iLen = pNode->m_sTo.Length(); memcpy ( dMappings.AddN ( iLen + 1 ), pNode->m_sTo.cstr(), iLen + 1 ); } d.AddN ( 4 ); SaveInt ( d, d.GetLength() - 4, iOff ); // sort children nodes by value pNode->m_dKids.Sort ( bind ( &ExceptionsTrieNode_c::Entry_t::m_uValue ) ); // save num_values, and values[] d.Add ( (BYTE)n ); ARRAY_FOREACH ( i, pNode->m_dKids ) d.Add ( pNode->m_dKids[i].m_uValue ); // save offsets[], and the respective child nodes int p = d.GetLength(); d.AddN ( 4 * n ); for ( int i = 0; i < n; i++, p += 4 ) SaveInt ( d, p, SaveNode ( pRes, pNode->m_dKids[i].m_pKid, dMappings ) ); assert ( p == iRes + 5 + 5 * n ); // done! return iRes; } }; ExceptionsTrieGen_c::ExceptionsTrieGen_c() { m_pImpl = new Impl_c; } ExceptionsTrieGen_c::~ExceptionsTrieGen_c() { delete m_pImpl; } void ExceptionsTrieGen_c::FoldSpace ( char* s ) const { m_pImpl->FoldSpace ( s ); } bool ExceptionsTrieGen_c::ParseLine ( char* sBuffer, CSphString& sError ) { return m_pImpl->ParseLine ( sBuffer, sError ); } ExceptionsTrie_c* ExceptionsTrieGen_c::Build() { return m_pImpl->Build(); }
0
0.971199
1
0.971199
game-dev
MEDIA
0.553669
game-dev
0.994669
1
0.994669
codice/ddf
3,765
catalog/core/catalog-core-api-impl/src/test/java/ddf/catalog/content/impl/MockMemoryStorageProvider.java
/** * Copyright (c) Codice Foundation * * <p>This 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 any later version. * * <p>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 Lesser General Public License for more details. A copy of the GNU Lesser General Public * License is distributed along with this program and can be found at * <http://www.gnu.org/licenses/lgpl.html>. */ package ddf.catalog.content.impl; import ddf.catalog.content.StorageException; import ddf.catalog.content.StorageProvider; import ddf.catalog.content.data.ContentItem; import ddf.catalog.content.operation.CreateStorageRequest; import ddf.catalog.content.operation.CreateStorageResponse; import ddf.catalog.content.operation.DeleteStorageRequest; import ddf.catalog.content.operation.DeleteStorageResponse; import ddf.catalog.content.operation.ReadStorageRequest; import ddf.catalog.content.operation.ReadStorageResponse; import ddf.catalog.content.operation.StorageRequest; import ddf.catalog.content.operation.UpdateStorageRequest; import ddf.catalog.content.operation.UpdateStorageResponse; import ddf.catalog.content.operation.impl.CreateStorageResponseImpl; import ddf.catalog.content.operation.impl.DeleteStorageResponseImpl; import ddf.catalog.content.operation.impl.ReadStorageResponseImpl; import ddf.catalog.content.operation.impl.UpdateStorageResponseImpl; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class MockMemoryStorageProvider implements StorageProvider { Map<String, ContentItem> itemMap = new HashMap<>(); Map<String, ContentItem> tempItemMap = new HashMap<>(); @Override public CreateStorageResponse create(CreateStorageRequest createStorageRequest) throws StorageException { for (ContentItem contentItem : createStorageRequest.getContentItems()) { tempItemMap.put(contentItem.getId(), contentItem); } return new CreateStorageResponseImpl( createStorageRequest, createStorageRequest.getContentItems()); } @Override public ReadStorageResponse read(ReadStorageRequest readRequest) throws StorageException { return new ReadStorageResponseImpl( readRequest, itemMap.get(readRequest.getResourceUri().getSchemeSpecificPart())); } @Override public UpdateStorageResponse update(UpdateStorageRequest updateStorageRequest) throws StorageException { for (ContentItem contentItem : updateStorageRequest.getContentItems()) { tempItemMap.put(contentItem.getId(), contentItem); } return new UpdateStorageResponseImpl( updateStorageRequest, updateStorageRequest.getContentItems()); } @Override public DeleteStorageResponse delete(DeleteStorageRequest deleteRequest) throws StorageException { List<ContentItem> contentItems = deleteRequest.getMetacards().stream() .map(metacard -> tempItemMap.remove(metacard.getId())) .collect(Collectors.toList()); return new DeleteStorageResponseImpl(deleteRequest, contentItems); } @Override public void commit(StorageRequest request) throws StorageException { itemMap.putAll(tempItemMap); new HashSet<>(tempItemMap.keySet()).forEach(tempItemMap::remove); } @Override public void rollback(StorageRequest request) throws StorageException { new HashSet<>(tempItemMap.keySet()).forEach(tempItemMap::remove); } public int size() { return itemMap.size(); } }
0
0.822666
1
0.822666
game-dev
MEDIA
0.538594
game-dev
0.547596
1
0.547596
oot-pc-port/oot-pc-port
5,307
asm/non_matchings/overlays/actors/ovl_En_Ani/EnAni_Init.s
glabel EnAni_Init /* 00008 809B0378 27BDFFC0 */ addiu $sp, $sp, 0xFFC0 ## $sp = FFFFFFC0 /* 0000C 809B037C AFA50044 */ sw $a1, 0x0044($sp) /* 00010 809B0380 AFBF002C */ sw $ra, 0x002C($sp) /* 00014 809B0384 AFB00028 */ sw $s0, 0x0028($sp) /* 00018 809B0388 3C05809B */ lui $a1, %hi(D_809B0F6C) ## $a1 = 809B0000 /* 0001C 809B038C 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 00020 809B0390 0C01E037 */ jal Actor_ProcessInitChain /* 00024 809B0394 24A50F6C */ addiu $a1, $a1, %lo(D_809B0F6C) ## $a1 = 809B0F6C /* 00028 809B0398 3C068003 */ lui $a2, 0x8003 ## $a2 = 80030000 /* 0002C 809B039C 24C6B5EC */ addiu $a2, $a2, 0xB5EC ## $a2 = 8002B5EC /* 00030 809B03A0 260400B4 */ addiu $a0, $s0, 0x00B4 ## $a0 = 000000B4 /* 00034 809B03A4 3C05C52F */ lui $a1, 0xC52F ## $a1 = C52F0000 /* 00038 809B03A8 0C00AC78 */ jal ActorShape_Init /* 0003C 809B03AC 3C074210 */ lui $a3, 0x4210 ## $a3 = 42100000 /* 00040 809B03B0 26050198 */ addiu $a1, $s0, 0x0198 ## $a1 = 00000198 /* 00044 809B03B4 3C060600 */ lui $a2, 0x0600 ## $a2 = 06000000 /* 00048 809B03B8 3C070600 */ lui $a3, 0x0600 ## $a3 = 06000000 /* 0004C 809B03BC 260E01DC */ addiu $t6, $s0, 0x01DC ## $t6 = 000001DC /* 00050 809B03C0 260F023C */ addiu $t7, $s0, 0x023C ## $t7 = 0000023C /* 00054 809B03C4 24180010 */ addiu $t8, $zero, 0x0010 ## $t8 = 00000010 /* 00058 809B03C8 AFB80018 */ sw $t8, 0x0018($sp) /* 0005C 809B03CC AFAF0014 */ sw $t7, 0x0014($sp) /* 00060 809B03D0 AFAE0010 */ sw $t6, 0x0010($sp) /* 00064 809B03D4 24E776EC */ addiu $a3, $a3, 0x76EC ## $a3 = 060076EC /* 00068 809B03D8 24C600F0 */ addiu $a2, $a2, 0x00F0 ## $a2 = 060000F0 /* 0006C 809B03DC AFA50034 */ sw $a1, 0x0034($sp) /* 00070 809B03E0 0C0291BE */ jal func_800A46F8 /* 00074 809B03E4 8FA40044 */ lw $a0, 0x0044($sp) /* 00078 809B03E8 3C050600 */ lui $a1, 0x0600 ## $a1 = 06000000 /* 0007C 809B03EC 24A576EC */ addiu $a1, $a1, 0x76EC ## $a1 = 060076EC /* 00080 809B03F0 0C02947A */ jal func_800A51E8 /* 00084 809B03F4 8FA40034 */ lw $a0, 0x0034($sp) /* 00088 809B03F8 2605014C */ addiu $a1, $s0, 0x014C ## $a1 = 0000014C /* 0008C 809B03FC AFA50034 */ sw $a1, 0x0034($sp) /* 00090 809B0400 0C0170D9 */ jal ActorCollider_AllocCylinder /* 00094 809B0404 8FA40044 */ lw $a0, 0x0044($sp) /* 00098 809B0408 3C07809B */ lui $a3, %hi(D_809B0F40) ## $a3 = 809B0000 /* 0009C 809B040C 8FA50034 */ lw $a1, 0x0034($sp) /* 000A0 809B0410 24E70F40 */ addiu $a3, $a3, %lo(D_809B0F40) ## $a3 = 809B0F40 /* 000A4 809B0414 8FA40044 */ lw $a0, 0x0044($sp) /* 000A8 809B0418 0C01712B */ jal ActorCollider_InitCylinder /* 000AC 809B041C 02003025 */ or $a2, $s0, $zero ## $a2 = 00000000 /* 000B0 809B0420 241900FF */ addiu $t9, $zero, 0x00FF ## $t9 = 000000FF /* 000B4 809B0424 A21900AE */ sb $t9, 0x00AE($s0) ## 000000AE /* 000B8 809B0428 3C088016 */ lui $t0, 0x8016 ## $t0 = 80160000 /* 000BC 809B042C 8D08E664 */ lw $t0, -0x199C($t0) ## 8015E664 /* 000C0 809B0430 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 000C4 809B0434 3C05809B */ lui $a1, %hi(func_809B07F8) ## $a1 = 809B0000 /* 000C8 809B0438 11000007 */ beq $t0, $zero, .L809B0458 /* 000CC 809B043C 00000000 */ nop /* 000D0 809B0440 3C05809B */ lui $a1, %hi(func_809B064C) ## $a1 = 809B0000 /* 000D4 809B0444 24A5064C */ addiu $a1, $a1, %lo(func_809B064C) ## $a1 = 809B064C /* 000D8 809B0448 0C26C0DC */ jal func_809B0370 /* 000DC 809B044C 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 000E0 809B0450 10000004 */ beq $zero, $zero, .L809B0464 /* 000E4 809B0454 3C01BF80 */ lui $at, 0xBF80 ## $at = BF800000 .L809B0458: /* 000E8 809B0458 0C26C0DC */ jal func_809B0370 /* 000EC 809B045C 24A507F8 */ addiu $a1, $a1, %lo(func_809B07F8) ## $a1 = 000007F8 /* 000F0 809B0460 3C01BF80 */ lui $at, 0xBF80 ## $at = BF800000 .L809B0464: /* 000F4 809B0464 44810000 */ mtc1 $at, $f0 ## $f0 = -1.00 /* 000F8 809B0468 A60002AA */ sh $zero, 0x02AA($s0) ## 000002AA /* 000FC 809B046C A60002A8 */ sh $zero, 0x02A8($s0) ## 000002A8 /* 00100 809B0470 E6000070 */ swc1 $f0, 0x0070($s0) ## 00000070 /* 00104 809B0474 E6000060 */ swc1 $f0, 0x0060($s0) ## 00000060 /* 00108 809B0478 8FBF002C */ lw $ra, 0x002C($sp) /* 0010C 809B047C 8FB00028 */ lw $s0, 0x0028($sp) /* 00110 809B0480 27BD0040 */ addiu $sp, $sp, 0x0040 ## $sp = 00000000 /* 00114 809B0484 03E00008 */ jr $ra /* 00118 809B0488 00000000 */ nop
0
0.677969
1
0.677969
game-dev
MEDIA
0.971299
game-dev
0.676204
1
0.676204
DukeofCambridge/Road2Technical_Artist
4,469
Assets/Plugins/PostProcessing/Runtime/PostProcessEffectSettings.cs
using System; using System.Collections.ObjectModel; using System.Reflection; using System.Linq; namespace UnityEngine.Rendering.PostProcessing { /// <summary> /// The base class for all post-processing effect settings. Any <see cref="ParameterOverride"/> /// members found in this class will be automatically handled and interpolated by the volume /// framework. /// </summary> /// <example> /// <code> /// [Serializable] /// [PostProcess(typeof(ExampleRenderer), "Custom/ExampleEffect")] /// public sealed class ExampleEffect : PostProcessEffectSettings /// { /// [Range(0f, 1f), Tooltip("Effect intensity.")] /// public FloatParameter intensity = new FloatParameter { value = 0f }; /// /// public override bool IsEnabledAndSupported(PostProcessRenderContext context) /// { /// return enabled.value /// &amp;&amp; intensity.value > 0f; // Only render the effect if intensity is greater than 0 /// } /// } /// </code> /// </example> [Serializable] public class PostProcessEffectSettings : ScriptableObject { /// <summary> /// The active state of the set of parameter defined in this class. /// </summary> /// <seealso cref="enabled"/> public bool active = true; /// <summary> /// The true state of the effect override in the stack. Setting this to <c>false</c> will /// disable rendering for this effect assuming a volume with a higher priority doesn't /// override it to <c>true</c>. /// </summary> public BoolParameter enabled = new BoolParameter { overrideState = true, value = false }; internal ReadOnlyCollection<ParameterOverride> parameters; void OnEnable() { // Automatically grab all fields of type ParameterOverride for this instance parameters = GetType() .GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(t => t.FieldType.IsSubclassOf(typeof(ParameterOverride))) .OrderBy(t => t.MetadataToken) // Guaranteed order .Select(t => (ParameterOverride)t.GetValue(this)) .ToList() .AsReadOnly(); foreach (var parameter in parameters) parameter.OnEnable(); } void OnDisable() { if (parameters == null) return; foreach (var parameter in parameters) parameter.OnDisable(); } /// <summary> /// Sets all the overrides for this effect to a given value. /// </summary> /// <param name="state">The value to set the override states to</param> /// <param name="excludeEnabled">If <c>false</c>, the <see cref="enabled"/> field will also /// be set to the given <see cref="state"/> value.</param> public void SetAllOverridesTo(bool state, bool excludeEnabled = true) { foreach (var prop in parameters) { if (excludeEnabled && prop == enabled) continue; prop.overrideState = state; } } /// <summary> /// Returns <c>true</c> if the effect is currently enabled and supported. /// </summary> /// <param name="context">The current post-processing render context</param> /// <returns><c>true</c> if the effect is currently enabled and supported</returns> public virtual bool IsEnabledAndSupported(PostProcessRenderContext context) { return enabled.value; } /// <summary> /// Returns the computed hash code for this parameter. /// </summary> /// <returns>A computed hash code</returns> public int GetHash() { // Custom hashing function used to compare the state of settings (it's not meant to be // unique but to be a quick way to check if two setting sets have the same state or not). // Hash collision rate should be pretty low. unchecked { //return parameters.Aggregate(17, (i, p) => i * 23 + p.GetHash()); int hash = 17; foreach (var p in parameters) hash = hash * 23 + p.GetHash(); return hash; } } } }
0
0.863641
1
0.863641
game-dev
MEDIA
0.297276
game-dev
0.834399
1
0.834399
TheXTech/TheXTech
8,327
src/control/joystick.h
/* * TheXTech - A platform game engine ported from old source code for VB6 * * Copyright (c) 2009-2011 Andrew Spinks, original VB6 code * Copyright (c) 2020-2025 Vitaly Novichkov <admin@wohlnet.ru> * * 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 * 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 JOYSTICK_H #define JOYSTICK_H #include "../controls.h" #include <string> #include <set> #include <unordered_map> #include <SDL2/SDL_timer.h> typedef struct _SDL_Joystick SDL_Joystick; typedef struct _SDL_GameController SDL_GameController; typedef struct _SDL_Haptic SDL_Haptic; namespace Controls { struct JoystickDevices { SDL_Joystick *joy = nullptr; SDL_GameController *ctrl = nullptr; SDL_Haptic *haptic = nullptr; bool can_poll = false; std::string guid; }; struct KM_Key { enum CtrlTypes { NoControl = -1, JoyAxis = 0, JoyBallX, JoyBallY, JoyHat, JoyButton, CtrlButton, CtrlAxis }; // SDL_Joystick control or SDL_GameController control, depending on context int val = -1; int id = -1; int type = -1; inline bool operator==(const KM_Key &o) { return o.id == id && o.val == val && o.type == type; } inline void assign(int i_type, int i_id, int i_val) { this->type = i_type; this->id = i_id; this->val = i_val; } }; class InputMethod_Joystick : public InputMethod { private: uint32_t m_last_power_check = -10000; StatusInfo m_recent_status; public: JoystickDevices *m_devices; using InputMethod::Type; using InputMethod::Profile; ~InputMethod_Joystick(); // Update functions that set player controls (and editor controls) // based on current device input. Return false if device lost. bool Update(int player, Controls_t &c, CursorControls_t &m, EditorControls_t &e, HotkeysPressed_t &h); void Rumble(int ms, float strength); StatusInfo GetStatus(); }; class InputMethodProfile_Joystick : public InputMethodProfile { private: bool m_canPoll = false; public: using InputMethodProfile::Name; using InputMethodProfile::Type; bool m_controllerProfile = false; // current settings bool m_simple_editor = true; // primary keys (also controller keys in legacy mode) KM_Key m_keys[PlayerControls::n_buttons]; // secondary keys (also joystick keys in legacy mode) KM_Key m_keys2[PlayerControls::n_buttons]; // cursor keys KM_Key m_cursor_keys[CursorControls::n_buttons]; KM_Key m_cursor_keys2[CursorControls::n_buttons]; // editor keys KM_Key m_editor_keys[EditorControls::n_buttons]; KM_Key m_editor_keys2[EditorControls::n_buttons]; // hotkeys KM_Key m_hotkeys[Hotkeys::n_buttons]; KM_Key m_hotkeys2[Hotkeys::n_buttons]; InputMethodProfile_Joystick(); enum InitAs { INIT_AS_DEFAULT = 0, INIT_AS_ALT, INIT_AS_WII_REMOTE, INIT_AS_WII_REMOTE_WITH_NUNCHACK, }; void InitAsJoystick(); void InitAsController(InitAs init_as); void SaveConfig_Legacy(IniProcessing *ctl); void LoadConfig_Legacy(IniProcessing *ctl); // Polls a new (secondary) device button for the i'th player button // Returns true on success and false if no button pressed // Never allows two player buttons to bind to the same device button bool PollPrimaryButton(ControlsClass c, size_t i); bool PollSecondaryButton(ControlsClass c, size_t i); // Deletes a primary button for the i'th button of class c (only called for non-Player buttons) bool DeletePrimaryButton(ControlsClass c, size_t i); // Deletes a secondary device button for the i'th button of class c bool DeleteSecondaryButton(ControlsClass c, size_t i); // Gets strings for the device buttons currently used for the i'th button of class c const char *NamePrimaryButton(ControlsClass c, size_t i); const char *NameSecondaryButton(ControlsClass c, size_t i); // one can assume that the IniProcessing* is already in the correct group void SaveConfig(IniProcessing *ctl); void LoadConfig(IniProcessing *ctl); public: // How many per-type special options are there? size_t GetOptionCount_Custom(); // Methods to manage per-profile options // It is guaranteed that none of these will be called if // GetOptionCount_Custom() returns 0. // get a char* describing the option const char *GetOptionName_Custom(size_t i); // get a char* describing the current option value // must be allocated in static or instance memory // WILL NOT be freed const char *GetOptionValue_Custom(size_t i); // called when A is pressed; allowed to interrupt main game loop bool OptionChange_Custom(size_t i); // called when left is pressed bool OptionRotateLeft_Custom(size_t i); // called when right is pressed bool OptionRotateRight_Custom(size_t i); }; class InputMethodType_Joystick : public InputMethodType { private: std::unordered_map<int, JoystickDevices *> m_availableJoysticks; std::unordered_map<std::string, InputMethodProfile *> m_lastProfileByGUID; InputMethodProfile *AllocateProfile() noexcept override; /*-----------------------*\ || CUSTOM METHODS || \*-----------------------*/ bool OpenJoystick(int joystick_index); bool CloseJoystick(int instance_id); public: using InputMethodType::Name; using InputMethodType::m_profiles; InputMethodType_Joystick(); ~InputMethodType_Joystick(); const std::string& LocalName() const override; bool TestProfileType(InputMethodProfile *profile) override; bool RumbleSupported() override; bool PowerStatusSupported() override; void UpdateControlsPre() override; void UpdateControlsPost() override; // null if no input method is ready // allocates the new InputMethod on the heap InputMethod *Poll(const std::vector<InputMethod *> &active_methods) noexcept override; /*-----------------------*\ || CUSTOM METHODS || \*-----------------------*/ KM_Key PollJoystickKeyAll(); KM_Key PollControllerKeyAll(); InputMethodProfile *AddOldJoystickProfile(); /*-----------------------*\ || OPTIONAL METHODS || \*-----------------------*/ protected: // optional function allowing developer to associate device information with profile, etc // if developer wants to forbid assignment, return false bool SetProfile_Custom(InputMethod *method, int player_no, InputMethodProfile *profile, const std::vector<InputMethod *> &active_methods) override; // unregisters any references to the profile before final deallocation // returns false to prevent deletion if this is impossible bool DeleteProfile_Custom(InputMethodProfile *profile, const std::vector<InputMethod *> &active_methods) override; public: bool ConsumeEvent(const SDL_Event *ev) override; public: // How many per-type special options are there? size_t GetOptionCount() override; // Methods to manage per-profile options // It is guaranteed that none of these will be called if // GetOptionCount() returns 0. // get a char* describing the option const char *GetOptionName(size_t i) override; // get a char* describing the current option value // must be allocated in static or instance memory // WILL NOT be freed const char *GetOptionValue(size_t i) override; // called when A is pressed; allowed to interrupt main game loop bool OptionChange(size_t i) override; protected: void SaveConfig_Custom(IniProcessing *ctl) override; void LoadConfig_Custom(IniProcessing *ctl) override; }; } // namespace Controls #endif // #ifndef JOYSTICK_H
0
0.918349
1
0.918349
game-dev
MEDIA
0.631658
game-dev,desktop-app
0.626868
1
0.626868
KoshakMineDEV/Lumi
15,848
src/main/java/cn/nukkit/level/generator/Normal.java
package cn.nukkit.level.generator; import cn.nukkit.Server; import cn.nukkit.block.Block; import cn.nukkit.block.BlockID; import cn.nukkit.block.BlockStone; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.biome.Biome; import cn.nukkit.level.biome.BiomeSelector; import cn.nukkit.level.biome.EnumBiome; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.generator.noise.vanilla.f.NoiseGeneratorOctavesF; import cn.nukkit.level.generator.object.ore.OreType; import cn.nukkit.level.generator.populator.impl.*; import cn.nukkit.level.generator.populator.overworld.*; import cn.nukkit.level.generator.populator.type.Populator; import cn.nukkit.level.generator.task.ChunkPopulationTask; import cn.nukkit.math.MathHelper; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.SplittableRandom; /** * Nukkit's terrain generator * Originally adapted from the PocketMine-MP generator by NycuRO and CreeperFace * Mostly rewritten by DaPorkchop_ * <p> * The generator classes, and others related to terrain generation are theirs and are intended for NUKKIT USAGE and should not be copied/translated to other server software * such as BukkitPE, ClearSky, Genisys, PocketMine-MP, or others */ public class Normal extends Generator { public static final int BEDROCK_LAYER = -64; private static final float[] biomeWeights = new float[25]; static { for (int i = -2; i <= 2; ++i) { for (int j = -2; j <= 2; ++j) { biomeWeights[i + 2 + (j + 2) * 5] = (float) (10.0F / Math.sqrt((float) (i * i + j * j) + 0.2F)); } } } private List<Populator> generationPopulators = ImmutableList.of( new PopulatorDeepslate(BEDROCK_LAYER), new PopulatorGroundCover() ); private List<Populator> populators = ImmutableList.of( new PopulatorOre(STONE, new OreType[]{ new OreType(Block.get(BlockID.COAL_ORE), 20, 17, 0, 128), new OreType(Block.get(BlockID.COPPER_ORE), 17, 9, 0, 64), new OreType(Block.get(BlockID.IRON_ORE), 20, 9, 0, 64), new OreType(Block.get(BlockID.REDSTONE_ORE), 8, 8, 0, 16), new OreType(Block.get(BlockID.LAPIS_ORE), 1, 7, 0, 30), new OreType(Block.get(BlockID.GOLD_ORE), 2, 9, 0, 32), new OreType(Block.get(BlockID.DIAMOND_ORE), 1, 8, 0, 16), new OreType(Block.get(BlockID.DIRT), 10, 33, 0, 128), new OreType(Block.get(BlockID.GRAVEL), 8, 33, 0, 128), new OreType(Block.get(BlockID.STONE, BlockStone.GRANITE), 10, 33, 0, 80), new OreType(Block.get(BlockID.STONE, BlockStone.DIORITE), 10, 33, 0, 80), new OreType(Block.get(BlockID.STONE, BlockStone.ANDESITE), 10, 33, 0, 80), new OreType(Block.get(BlockID.DEEPSLATE), 20, 33, 0, 8) }), new PopulatorOre(BlockID.DEEPSLATE, new OreType[]{ new OreType(Block.get(BlockID.DEEPSLATE_COAL_ORE), 1, 13, -4, 8, BlockID.DEEPSLATE), new OreType(Block.get(BlockID.DEEPSLATE_COPPER_ORE), 5, 9, -64, 8, BlockID.DEEPSLATE), new OreType(Block.get(BlockID.DEEPSLATE_IRON_ORE), 5, 9, -64, 8, BlockID.DEEPSLATE), new OreType(Block.get(BlockID.DEEPSLATE_REDSTONE_ORE), 8, 8, -64, 8, BlockID.DEEPSLATE), new OreType(Block.get(BlockID.DEEPSLATE_LAPIS_ORE), 6, 6, -64, 8, BlockID.DEEPSLATE), new OreType(Block.get(BlockID.DEEPSLATE_GOLD_ORE), 2, 9, -64, 8, BlockID.DEEPSLATE), new OreType(Block.get(BlockID.DEEPSLATE_DIAMOND_ORE), 4, 5, -64, 8, BlockID.DEEPSLATE) }), new PopulatorCaves(BEDROCK_LAYER), new PopulatorSpring(BlockID.WATER, BlockID.STONE, 15, 8, 255), new PopulatorSpring(BlockID.LAVA, BlockID.STONE, 10, 16, 255), new PopulatorBedrock(BEDROCK_LAYER) ); private List<Populator> structurePopulators = ImmutableList.of( new PopulatorFossil(), new PopulatorShipwreck(), new PopulatorSwampHut(), new PopulatorDesertPyramid(), new PopulatorJungleTemple(), new PopulatorIgloo(), new PopulatorPillagerOutpost(), new PopulatorOceanRuin(), new PopulatorStronghold(), new PopulatorMineshaft(), new PopulatorDesertWell(), new PopulatorDungeon() ); public static final int seaHeight = 64; // should be 62 public NoiseGeneratorOctavesF scaleNoise; public NoiseGeneratorOctavesF depthNoise; private ChunkManager level; private NukkitRandom nukkitRandom; private long localSeed1; private long localSeed2; private BiomeSelector selector; private ThreadLocal<float[]> depthRegion = ThreadLocal.withInitial(() -> null); private ThreadLocal<float[]> mainNoiseRegion = ThreadLocal.withInitial(() -> null); private ThreadLocal<float[]> minLimitRegion = ThreadLocal.withInitial(() -> null); private ThreadLocal<float[]> maxLimitRegion = ThreadLocal.withInitial(() -> null); private ThreadLocal<float[]> heightMap = ThreadLocal.withInitial(() -> new float[825]); private NoiseGeneratorOctavesF minLimitPerlinNoise; private NoiseGeneratorOctavesF maxLimitPerlinNoise; private NoiseGeneratorOctavesF mainPerlinNoise; public Normal() { this(Collections.emptyMap()); } public Normal(Map<String, Object> options) { } @Override public int getId() { return TYPE_INFINITE; } @Override public ChunkManager getChunkManager() { return level; } @Override public String getName() { return "normal"; } @Override public Map<String, Object> getSettings() { return Collections.emptyMap(); } public Biome pickBiome(int x, int z) { return this.selector.pickBiome(x, z); } @Override public void init(ChunkManager level, NukkitRandom random) { this.level = level; this.nukkitRandom = random; SplittableRandom random1 = new SplittableRandom(); this.nukkitRandom.setSeed(this.level.getSeed()); this.localSeed1 = random1.nextLong(); this.localSeed2 = random1.nextLong(); this.nukkitRandom.setSeed(this.level.getSeed()); this.selector = new BiomeSelector(this.nukkitRandom); this.minLimitPerlinNoise = new NoiseGeneratorOctavesF(random, 16); this.maxLimitPerlinNoise = new NoiseGeneratorOctavesF(random, 16); this.mainPerlinNoise = new NoiseGeneratorOctavesF(random, 8); this.scaleNoise = new NoiseGeneratorOctavesF(random, 10); this.depthNoise = new NoiseGeneratorOctavesF(random, 16); } @Override public void populateStructure(final int chunkX, final int chunkZ) { final BaseFullChunk chunk = level.getChunk(chunkX, chunkZ); for (final Populator populator : structurePopulators) { Server.getInstance().computeThreadPool.submit(new ChunkPopulationTask(level, chunk, populator)); } } @Override public void generateChunk(final int chunkX, final int chunkZ) { int baseX = chunkX << 4; int baseZ = chunkZ << 4; this.nukkitRandom.setSeed(chunkX * localSeed1 ^ chunkZ * localSeed2 ^ this.level.getSeed()); BaseFullChunk chunk = level.getChunk(chunkX, chunkZ); //generate base noise values float[] depthRegion = this.depthNoise.generateNoiseOctaves(this.depthRegion.get(), chunkX << 2, chunkZ << 2, 5, 5, 200f, 200f, 0.5f); this.depthRegion.set(depthRegion); float[] mainNoiseRegion = this.mainPerlinNoise.generateNoiseOctaves(this.mainNoiseRegion.get(), chunkX << 2, 0, chunkZ << 2, 5, 33, 5, 11.406866f, 4.277575f, 11.406866f); this.mainNoiseRegion.set(mainNoiseRegion); float[] minLimitRegion = this.minLimitPerlinNoise.generateNoiseOctaves(this.minLimitRegion.get(), chunkX << 2, 0, chunkZ << 2, 5, 33, 5, 684.412f, 684.412f, 684.412f); this.minLimitRegion.set(minLimitRegion); float[] maxLimitRegion = this.maxLimitPerlinNoise.generateNoiseOctaves(this.maxLimitRegion.get(), chunkX << 2, 0, chunkZ << 2, 5, 33, 5, 684.412f, 684.412f, 684.412f); this.maxLimitRegion.set(maxLimitRegion); float[] heightMap = this.heightMap.get(); //generate heightmap and smooth biome heights int horizCounter = 0; int vertCounter = 0; for (int xSeg = 0; xSeg < 5; ++xSeg) { for (int zSeg = 0; zSeg < 5; ++zSeg) { float heightVariationSum = 0.0F; float baseHeightSum = 0.0F; float biomeWeightSum = 0.0F; Biome biome = pickBiome(baseX + (xSeg << 2), baseZ + (zSeg << 2)); for (int xSmooth = -2; xSmooth <= 2; ++xSmooth) { for (int zSmooth = -2; zSmooth <= 2; ++zSmooth) { Biome biome1 = pickBiome(baseX + (xSeg << 2) + xSmooth, baseZ + (zSeg << 2) + zSmooth); float baseHeight = biome1.getBaseHeight(); float heightVariation = biome1.getHeightVariation(); float scaledWeight = biomeWeights[xSmooth + 2 + (zSmooth + 2) * 5] / (baseHeight + 2.0F); if (biome1.getBaseHeight() > biome.getBaseHeight()) { scaledWeight /= 2.0F; } heightVariationSum += heightVariation * scaledWeight; baseHeightSum += baseHeight * scaledWeight; biomeWeightSum += scaledWeight; } } heightVariationSum = heightVariationSum / biomeWeightSum; baseHeightSum = baseHeightSum / biomeWeightSum; heightVariationSum = heightVariationSum * 0.9F + 0.1F; baseHeightSum = (baseHeightSum * 4.0F - 1.0F) / 8.0F; float depthNoise = depthRegion[vertCounter] / 8000.0f; if (depthNoise < 0.0f) { depthNoise = -depthNoise * 0.3f; } depthNoise = depthNoise * 3.0f - 2.0f; if (depthNoise < 0.0f) { depthNoise = depthNoise / 2.0f; if (depthNoise < -1.0f) { depthNoise = -1.0f; } depthNoise = depthNoise / 1.4f; depthNoise = depthNoise / 2.0f; } else { if (depthNoise > 1.0f) { depthNoise = 1.0f; } depthNoise = depthNoise / 8.0f; } ++vertCounter; float baseHeightClone = baseHeightSum; float heightVariationClone = heightVariationSum; baseHeightClone = baseHeightClone + depthNoise * 0.2f; baseHeightClone = baseHeightClone * 8.5f / 8.0f; float baseHeightFactor = 8.5f + baseHeightClone * 4.0f; for (int ySeg = 0; ySeg < 33; ++ySeg) { float baseScale = ((float) ySeg - baseHeightFactor) * 12f * 128.0f / 256.0f / heightVariationClone; if (baseScale < 0.0f) { baseScale *= 4.0f; } float minScaled = minLimitRegion[horizCounter] / 512f; float maxScaled = maxLimitRegion[horizCounter] / 512f; float noiseScaled = (mainNoiseRegion[horizCounter] / 10.0f + 1.0f) / 2.0f; float clamp = MathHelper.denormalizeClamp(minScaled, maxScaled, noiseScaled) - baseScale; if (ySeg > 29) { float yScaled = ((float) (ySeg - 29) / 3.0F); clamp = clamp * (1.0f - yScaled) + -10.0f * yScaled; } heightMap[horizCounter] = clamp; ++horizCounter; } } } //place blocks for (int xSeg = 0; xSeg < 4; ++xSeg) { int xScale = xSeg * 5; int xScaleEnd = (xSeg + 1) * 5; for (int zSeg = 0; zSeg < 4; ++zSeg) { int zScale1 = (xScale + zSeg) * 33; int zScaleEnd1 = (xScale + zSeg + 1) * 33; int zScale2 = (xScaleEnd + zSeg) * 33; int zScaleEnd2 = (xScaleEnd + zSeg + 1) * 33; for (int ySeg = 0; ySeg < 32; ++ySeg) { double height1 = heightMap[zScale1 + ySeg]; double height2 = heightMap[zScaleEnd1 + ySeg]; double height3 = heightMap[zScale2 + ySeg]; double height4 = heightMap[zScaleEnd2 + ySeg]; double height5 = (heightMap[zScale1 + ySeg + 1] - height1) * 0.125f; double height6 = (heightMap[zScaleEnd1 + ySeg + 1] - height2) * 0.125f; double height7 = (heightMap[zScale2 + ySeg + 1] - height3) * 0.125f; double height8 = (heightMap[zScaleEnd2 + ySeg + 1] - height4) * 0.125f; for (int yIn = 0; yIn < 8; ++yIn) { double baseIncr = height1; double baseIncr2 = height2; double scaleY = (height3 - height1) * 0.25f; double scaleY2 = (height4 - height2) * 0.25f; for (int zIn = 0; zIn < 4; ++zIn) { double scaleZ = (baseIncr2 - baseIncr) * 0.25f; double scaleZ2 = baseIncr - scaleZ; for (int xIn = 0; xIn < 4; ++xIn) { if ((scaleZ2 += scaleZ) > 0.0f) { chunk.setBlockId((xSeg << 2) + zIn, (ySeg << 3) + yIn, (zSeg << 2) + xIn, STONE); } else if ((ySeg << 3) + yIn <= seaHeight) { chunk.setBlockId((xSeg << 2) + zIn, (ySeg << 3) + yIn, (zSeg << 2) + xIn, STILL_WATER); } } baseIncr += scaleY; baseIncr2 += scaleY2; } height1 += height5; height2 += height6; height3 += height7; height4 += height8; } } } } for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { chunk.setBiome(x, z, selector.pickBiome(baseX | x, baseZ | z)); } } //populate chunk for (Populator populator : this.generationPopulators) { populator.populate(this.level, chunkX, chunkZ, this.nukkitRandom, chunk); } } @Override public void populateChunk(int chunkX, int chunkZ) { this.nukkitRandom.setSeed(0xdeadbeef ^ (chunkX << 8) ^ chunkZ ^ this.level.getSeed()); for (Populator populator : this.populators) { populator.populate(this.level, chunkX, chunkZ, this.nukkitRandom, level.getChunk(chunkX, chunkZ)); } Biome biome = EnumBiome.getBiome(level.getChunk(chunkX, chunkZ).getBiomeId(7, 7)); biome.populateChunk(this.level, chunkX, chunkZ, this.nukkitRandom); } @Override public Vector3 getSpawn() { return new Vector3(0.5, 256, 0.5); } }
0
0.775038
1
0.775038
game-dev
MEDIA
0.970863
game-dev
0.977127
1
0.977127
Fallen-Breath/tweakermore
2,172
versions/1.21.8/src/main/java/me/fallenbreath/tweakermore/mixins/tweaks/mc_tweaks/disableDarknessEffect/BackgroundRendererStatusEffectFogModifierMixin.java
/* * This file is part of the TweakerMore project, licensed under the * GNU Lesser General Public License v3.0 * * Copyright (C) 2025 Fallen_Breath and contributors * * TweakerMore 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. * * TweakerMore is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with TweakerMore. If not, see <https://www.gnu.org/licenses/>. */ package me.fallenbreath.tweakermore.mixins.tweaks.mc_tweaks.disableDarknessEffect; import com.llamalad7.mixinextras.injector.ModifyReturnValue; import me.fallenbreath.conditionalmixin.api.annotation.Condition; import me.fallenbreath.conditionalmixin.api.annotation.Restriction; import me.fallenbreath.tweakermore.config.TweakerMoreConfigs; import me.fallenbreath.tweakermore.util.ModIds; import net.minecraft.client.render.fog.DarknessEffectFogModifier; import net.minecraft.client.render.fog.StatusEffectFogModifier; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; /** * mc1.14.4 ~ mc1.19.4: subproject 1.15.2 (main project) * mc1.19.4 ~ mc1.21.5: subproject 1.19.4 * mc1.21.6+ : subproject 1.21.8 <-------- */ @Restriction(require = @Condition(value = ModIds.minecraft, versionPredicates = ">=1.19")) @Mixin(StatusEffectFogModifier.class) public abstract class BackgroundRendererStatusEffectFogModifierMixin { @ModifyReturnValue(method = "shouldApply", at = @At("TAIL")) private boolean disableDarknessEffect_doNotApplyIfItIsDarknessEffect(boolean shouldApply) { if (TweakerMoreConfigs.DISABLE_DARKNESS_EFFECT.getBooleanValue()) { if ((Object)this instanceof DarknessEffectFogModifier) { shouldApply = false; } } return shouldApply; } }
0
0.813426
1
0.813426
game-dev
MEDIA
0.779412
game-dev
0.563232
1
0.563232
BattletechModders/ModTek
3,116
ModTek.Preloader/Loader/LegacyChecker.cs
using System.Collections.Generic; using System.Linq; using ModTek.Common.Utils; using Mono.Cecil; using Mono.Cecil.Cil; namespace ModTek.Preloader.Loader; internal static class LegacyChecker { internal static bool IsInjected(string path) { using var game = ModuleDefinition.ReadModule(path); var injected = false; if (IsModTekInjected(game)) { Logger.Main.Log($"Assembly `{FileUtils.GetRelativePath(path)}` was modified by ModTek."); injected = true; } if (IsBTMLInjected(game)) { Logger.Main.Log($"Assembly `{FileUtils.GetRelativePath(path)}` was modified by BTML."); injected = true; } if (IsRogueTechPerfFixInjected(game)) { Logger.Main.Log($"Assembly `{FileUtils.GetRelativePath(path)}` was modified by RogueTechPerfFix."); injected = true; } if (!injected) { Logger.Main.Log($"Assembly `{FileUtils.GetRelativePath(path)}` contains no known injections."); } return injected; } private static bool IsModTekInjected(ModuleDefinition game) { return game.GetType("BattleTech.Main").Methods.Any(x => x.Name == "LoadModTek"); } private static bool IsBTMLInjected(ModuleDefinition game) { var searchTypes = new List<TypeDefinition> { game.GetType("BattleTech.Main"), game.GetType("BattleTech.GameInstance") }; foreach (var type in searchTypes) { // check if btml is attached to any method foreach (var methodDefinition in type.Methods) { if (IsMethodCalledInMethod(methodDefinition, "System.Void BattleTechModLoader.BTModLoader::Init()")) { return true; } } // also have to check in places like IEnumerator generated methods (Nested) foreach (var nestedType in type.NestedTypes) { foreach (var methodDefinition in nestedType.Methods) { if (IsMethodCalledInMethod(methodDefinition, "System.Void BattleTechModLoader.BTModLoader::Init()")) { return true; } } } } return false; } private static bool IsRogueTechPerfFixInjected(ModuleDefinition game) { return game.GetType("BattleTech.UnityGameInstance").Fields.Any(f => f.Name.StartsWith("RTPFVersion")); } private static bool IsMethodCalledInMethod(MethodDefinition methodDefinition, string methodSignature) { if (methodDefinition.Body == null) { return false; } foreach (var instruction in methodDefinition.Body.Instructions) { if (instruction.OpCode.Equals(OpCodes.Call) && instruction.Operand.ToString().Equals(methodSignature)) { return true; } } return false; } }
0
0.944369
1
0.944369
game-dev
MEDIA
0.952904
game-dev
0.874378
1
0.874378
AirFoundation/Naven-NoAuth
16,344
src/main/java/net/minecraft/enchantment/EnchantmentHelper.java
package net.minecraft.enchantment; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureAttribute; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.DamageSource; import net.minecraft.util.WeightedRandom; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; public class EnchantmentHelper { private static final Random enchantmentRand = new Random(); private static final EnchantmentHelper.ModifierDamage enchantmentModifierDamage = new EnchantmentHelper.ModifierDamage(); private static final EnchantmentHelper.ModifierLiving enchantmentModifierLiving = new EnchantmentHelper.ModifierLiving(); private static final EnchantmentHelper.HurtIterator ENCHANTMENT_ITERATOR_HURT = new EnchantmentHelper.HurtIterator(); private static final EnchantmentHelper.DamageIterator ENCHANTMENT_ITERATOR_DAMAGE = new EnchantmentHelper.DamageIterator(); public static int getEnchantmentLevel(int enchID, ItemStack stack) { if (stack == null) { return 0; } else { NBTTagList nbttaglist = stack.getEnchantmentTagList(); if (nbttaglist == null) { return 0; } else { for (int i = 0; i < nbttaglist.tagCount(); ++i) { int j = nbttaglist.getCompoundTagAt(i).getShort("id"); int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); if (j == enchID) { return k; } } return 0; } } } public static Map<Integer, Integer> getEnchantments(ItemStack stack) { Map<Integer, Integer> map = Maps.newLinkedHashMap(); NBTTagList nbttaglist = stack.getItem() == Items.enchanted_book ? Items.enchanted_book.getEnchantments(stack) : stack.getEnchantmentTagList(); if (nbttaglist != null) { for (int i = 0; i < nbttaglist.tagCount(); ++i) { int j = nbttaglist.getCompoundTagAt(i).getShort("id"); int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); map.put(Integer.valueOf(j), Integer.valueOf(k)); } } return map; } public static void setEnchantments(Map<Integer, Integer> enchMap, ItemStack stack) { NBTTagList nbttaglist = new NBTTagList(); Iterator iterator = enchMap.keySet().iterator(); while (iterator.hasNext()) { int i = ((Integer) iterator.next()).intValue(); Enchantment enchantment = Enchantment.getEnchantmentById(i); if (enchantment != null) { NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setShort("id", (short) i); nbttagcompound.setShort("lvl", (short) enchMap.get(Integer.valueOf(i)).intValue()); nbttaglist.appendTag(nbttagcompound); if (stack.getItem() == Items.enchanted_book) { Items.enchanted_book.addEnchantment(stack, new EnchantmentData(enchantment, enchMap.get(Integer.valueOf(i)).intValue())); } } } if (nbttaglist.tagCount() > 0) { if (stack.getItem() != Items.enchanted_book) { stack.setTagInfo("ench", nbttaglist); } } else if (stack.hasTagCompound()) { stack.getTagCompound().removeTag("ench"); } } public static int getMaxEnchantmentLevel(int enchID, ItemStack[] stacks) { if (stacks == null) { return 0; } else { int i = 0; for (ItemStack itemstack : stacks) { int j = getEnchantmentLevel(enchID, itemstack); if (j > i) { i = j; } } return i; } } private static void applyEnchantmentModifier(EnchantmentHelper.IModifier modifier, ItemStack stack) { if (stack != null) { NBTTagList nbttaglist = stack.getEnchantmentTagList(); if (nbttaglist != null) { for (int i = 0; i < nbttaglist.tagCount(); ++i) { int j = nbttaglist.getCompoundTagAt(i).getShort("id"); int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); if (Enchantment.getEnchantmentById(j) != null) { modifier.calculateModifier(Enchantment.getEnchantmentById(j), k); } } } } } private static void applyEnchantmentModifierArray(EnchantmentHelper.IModifier modifier, ItemStack[] stacks) { for (ItemStack itemstack : stacks) { applyEnchantmentModifier(modifier, itemstack); } } public static int getEnchantmentModifierDamage(ItemStack[] stacks, DamageSource source) { enchantmentModifierDamage.damageModifier = 0; enchantmentModifierDamage.source = source; applyEnchantmentModifierArray(enchantmentModifierDamage, stacks); if (enchantmentModifierDamage.damageModifier > 25) { enchantmentModifierDamage.damageModifier = 25; } else if (enchantmentModifierDamage.damageModifier < 0) { enchantmentModifierDamage.damageModifier = 0; } return (enchantmentModifierDamage.damageModifier + 1 >> 1) + enchantmentRand.nextInt((enchantmentModifierDamage.damageModifier >> 1) + 1); } public static float getModifierForCreature(ItemStack p_152377_0_, EnumCreatureAttribute p_152377_1_) { enchantmentModifierLiving.livingModifier = 0.0F; enchantmentModifierLiving.entityLiving = p_152377_1_; applyEnchantmentModifier(enchantmentModifierLiving, p_152377_0_); return enchantmentModifierLiving.livingModifier; } public static void applyThornEnchantments(EntityLivingBase p_151384_0_, Entity p_151384_1_) { ENCHANTMENT_ITERATOR_HURT.attacker = p_151384_1_; ENCHANTMENT_ITERATOR_HURT.user = p_151384_0_; if (p_151384_0_ != null) { applyEnchantmentModifierArray(ENCHANTMENT_ITERATOR_HURT, p_151384_0_.getInventory()); } if (p_151384_1_ instanceof EntityPlayer) { applyEnchantmentModifier(ENCHANTMENT_ITERATOR_HURT, p_151384_0_.getHeldItem()); } } public static void applyArthropodEnchantments(EntityLivingBase p_151385_0_, Entity p_151385_1_) { ENCHANTMENT_ITERATOR_DAMAGE.user = p_151385_0_; ENCHANTMENT_ITERATOR_DAMAGE.target = p_151385_1_; if (p_151385_0_ != null) { applyEnchantmentModifierArray(ENCHANTMENT_ITERATOR_DAMAGE, p_151385_0_.getInventory()); } if (p_151385_0_ instanceof EntityPlayer) { applyEnchantmentModifier(ENCHANTMENT_ITERATOR_DAMAGE, p_151385_0_.getHeldItem()); } } public static int getKnockbackModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.knockback.effectId, player.getHeldItem()); } public static int getFireAspectModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.fireAspect.effectId, player.getHeldItem()); } public static int getRespiration(Entity player) { return getMaxEnchantmentLevel(Enchantment.respiration.effectId, player.getInventory()); } public static int getDepthStriderModifier(Entity player) { return getMaxEnchantmentLevel(Enchantment.depthStrider.effectId, player.getInventory()); } public static int getEfficiencyModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.efficiency.effectId, player.getHeldItem()); } public static boolean getSilkTouchModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.silkTouch.effectId, player.getHeldItem()) > 0; } public static int getFortuneModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.fortune.effectId, player.getHeldItem()); } public static int getLuckOfSeaModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.luckOfTheSea.effectId, player.getHeldItem()); } public static int getLureModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.lure.effectId, player.getHeldItem()); } public static int getLootingModifier(EntityLivingBase player) { return getEnchantmentLevel(Enchantment.looting.effectId, player.getHeldItem()); } public static boolean getAquaAffinityModifier(EntityLivingBase player) { return getMaxEnchantmentLevel(Enchantment.aquaAffinity.effectId, player.getInventory()) > 0; } public static ItemStack getEnchantedItem(Enchantment p_92099_0_, EntityLivingBase p_92099_1_) { for (ItemStack itemstack : p_92099_1_.getInventory()) { if (itemstack != null && getEnchantmentLevel(p_92099_0_.effectId, itemstack) > 0) { return itemstack; } } return null; } public static int calcItemStackEnchantability(Random rand, int enchantNum, int power, ItemStack stack) { Item item = stack.getItem(); int i = item.getItemEnchantability(); if (i <= 0) { return 0; } else { if (power > 15) { power = 15; } int j = rand.nextInt(8) + 1 + (power >> 1) + rand.nextInt(power + 1); return enchantNum == 0 ? Math.max(j / 3, 1) : (enchantNum == 1 ? j * 2 / 3 + 1 : Math.max(j, power * 2)); } } public static ItemStack addRandomEnchantment(Random p_77504_0_, ItemStack p_77504_1_, int p_77504_2_) { List<EnchantmentData> list = buildEnchantmentList(p_77504_0_, p_77504_1_, p_77504_2_); boolean flag = p_77504_1_.getItem() == Items.book; if (flag) { p_77504_1_.setItem(Items.enchanted_book); } if (list != null) { for (EnchantmentData enchantmentdata : list) { if (flag) { Items.enchanted_book.addEnchantment(p_77504_1_, enchantmentdata); } else { p_77504_1_.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); } } } return p_77504_1_; } public static List<EnchantmentData> buildEnchantmentList(Random randomIn, ItemStack itemStackIn, int p_77513_2_) { Item item = itemStackIn.getItem(); int i = item.getItemEnchantability(); if (i <= 0) { return null; } else { i = i / 2; i = 1 + randomIn.nextInt((i >> 1) + 1) + randomIn.nextInt((i >> 1) + 1); int j = i + p_77513_2_; float f = (randomIn.nextFloat() + randomIn.nextFloat() - 1.0F) * 0.15F; int k = (int) ((float) j * (1.0F + f) + 0.5F); if (k < 1) { k = 1; } List<EnchantmentData> list = null; Map<Integer, EnchantmentData> map = mapEnchantmentData(k, itemStackIn); if (map != null && !map.isEmpty()) { EnchantmentData enchantmentdata = WeightedRandom.getRandomItem(randomIn, map.values()); if (enchantmentdata != null) { list = Lists.newArrayList(); list.add(enchantmentdata); for (int l = k; randomIn.nextInt(50) <= l; l >>= 1) { Iterator<Integer> iterator = map.keySet().iterator(); while (iterator.hasNext()) { Integer integer = iterator.next(); boolean flag = true; for (EnchantmentData enchantmentdata1 : list) { if (!enchantmentdata1.enchantmentobj.canApplyTogether(Enchantment.getEnchantmentById(integer.intValue()))) { flag = false; break; } } if (!flag) { iterator.remove(); } } if (!map.isEmpty()) { EnchantmentData enchantmentdata2 = WeightedRandom.getRandomItem(randomIn, map.values()); list.add(enchantmentdata2); } } } } return list; } } public static Map<Integer, EnchantmentData> mapEnchantmentData(int p_77505_0_, ItemStack p_77505_1_) { Item item = p_77505_1_.getItem(); Map<Integer, EnchantmentData> map = null; boolean flag = p_77505_1_.getItem() == Items.book; for (Enchantment enchantment : Enchantment.enchantmentsBookList) { if (enchantment != null && (enchantment.type.canEnchantItem(item) || flag)) { for (int i = enchantment.getMinLevel(); i <= enchantment.getMaxLevel(); ++i) { if (p_77505_0_ >= enchantment.getMinEnchantability(i) && p_77505_0_ <= enchantment.getMaxEnchantability(i)) { if (map == null) { map = Maps.newHashMap(); } map.put(Integer.valueOf(enchantment.effectId), new EnchantmentData(enchantment, i)); } } } } return map; } public static int getEnchantment(ItemStack itemStack, Enchantment enchantment) { if (itemStack == null || itemStack.getEnchantmentTagList() == null || itemStack.getEnchantmentTagList().hasNoTags()) return 0; for (int i = 0; i < itemStack.getEnchantmentTagList().tagCount(); i++) { final NBTTagCompound tagCompound = itemStack.getEnchantmentTagList().getCompoundTagAt(i); if ((tagCompound.hasKey("ench") && tagCompound.getShort("ench") == enchantment.effectId) || (tagCompound.hasKey("id") && tagCompound.getShort("id") == enchantment.effectId)) return tagCompound.getShort("lvl"); } return 0; } static final class DamageIterator implements EnchantmentHelper.IModifier { public EntityLivingBase user; public Entity target; private DamageIterator() { } public void calculateModifier(Enchantment enchantmentIn, int enchantmentLevel) { enchantmentIn.onEntityDamaged(this.user, this.target, enchantmentLevel); } } static final class HurtIterator implements EnchantmentHelper.IModifier { public EntityLivingBase user; public Entity attacker; private HurtIterator() { } public void calculateModifier(Enchantment enchantmentIn, int enchantmentLevel) { enchantmentIn.onUserHurt(this.user, this.attacker, enchantmentLevel); } } interface IModifier { void calculateModifier(Enchantment enchantmentIn, int enchantmentLevel); } static final class ModifierDamage implements EnchantmentHelper.IModifier { public int damageModifier; public DamageSource source; private ModifierDamage() { } public void calculateModifier(Enchantment enchantmentIn, int enchantmentLevel) { this.damageModifier += enchantmentIn.calcModifierDamage(enchantmentLevel, this.source); } } static final class ModifierLiving implements EnchantmentHelper.IModifier { public float livingModifier; public EnumCreatureAttribute entityLiving; private ModifierLiving() { } public void calculateModifier(Enchantment enchantmentIn, int enchantmentLevel) { this.livingModifier += enchantmentIn.calcDamageByCreature(enchantmentLevel, this.entityLiving); } } }
0
0.952396
1
0.952396
game-dev
MEDIA
0.985942
game-dev
0.994163
1
0.994163
latte-soft/datamodelpatch
1,448
src/PatchRoot/DataModelInstances/CorePackages/Workspace/Packages/_Workspace/ExpChat/ExpChat/installReducer/BubbleChat/LegacyChatReducer.luau
local l_script_FirstAncestor_0 = script:FindFirstAncestor("ExpChat"); local l_Parent_0 = l_script_FirstAncestor_0.Parent; local v2 = require(l_Parent_0.Rodux); local l_Dictionary_0 = require(l_Parent_0.llama).Dictionary; local l_Actions_0 = l_script_FirstAncestor_0.Actions; local v5 = require(l_Actions_0.LegacyBubbleChatEnabledChanged); local v6 = require(l_Actions_0.LegacyBubbleChatSettingsChanged); local v7 = require(script.Parent.LegacyDefaultSettings); return v2.createReducer(v7, { [v5.name] = function(v8, v9) return l_Dictionary_0.join(v8, { Enabled = v9.value }); end, [v6.name] = function(_, v11) local l_chatSettings_0 = v11.chatSettings; if l_chatSettings_0.Transparency then l_chatSettings_0.BackgroundTransparency = l_chatSettings_0.Transparency; end; local v13 = l_Dictionary_0.join(v7, l_chatSettings_0); if not (not l_chatSettings_0 or not l_chatSettings_0.UserSpecificSettings) then for v14, v15 in pairs(l_chatSettings_0.UserSpecificSettings) do local v16 = l_Dictionary_0.copyDeep(v7); if v15.Transparency then v15.BackgroundTransparency = v15.Transparency; end; v16.UserSpecificSettings = nil; v13.UserSpecificSettings[v14] = l_Dictionary_0.join(v16, v15); end; end; return v13; end });
0
0.672735
1
0.672735
game-dev
MEDIA
0.752968
game-dev
0.633638
1
0.633638
openfl/openfl
3,071
src/openfl/events/ActivityEvent.hx
package openfl.events; #if !flash // import openfl.utils.ObjectPool; /** A Camera or Microphone object dispatches an ActivityEvent object whenever a camera or microphone reports that it has become active or inactive. There is only one type of activity event: `ActivityEvent.ACTIVITY`. **/ #if !openfl_debug @:fileXml('tags="haxe,release"') @:noDebug #end class ActivityEvent extends Event { /** The `ActivityEvent.ACTIVITY` constant defines the value of the `type` property of an `activity` event object. This event has the following properties: | Property | Value | | --- | --- | | `activating` | `true` if the device is activating or `false` if it is deactivating. | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The object beginning or ending a session, such as a Camera or Microphone object. | **/ public static inline var ACTIVITY:EventType<ActivityEvent> = "activity"; /** Indicates whether the device is activating (`true`) or deactivating (`false`). **/ public var activating:Bool; // @:noCompletion private static var __pool:ObjectPool<ActivityEvent> = new ObjectPool<ActivityEvent>(function() return new ActivityEvent(null), // function(event) event.__init()); /** Creates an event object that contains information about activity events. Event objects are passed as parameters to Event listeners. @param type The type of the event. Event listeners can access this information through the inherited `type` property. There is only one type of activity event: `ActivityEvent.ACTIVITY`. @param bubbles Determines whether the Event object participates in the bubbling phase of the event flow. Event listeners can access this information through the inherited `bubbles` property. @param cancelable Determines whether the Event object can be canceled. Event listeners can access this information through the inherited `cancelable` property. @param activating Indicates whether the device is activating (`true`) or deactivating (`false`). Event listeners can access this information through the `activating` property. **/ public function new(type:String, bubbles:Bool = false, cancelable:Bool = false, activating:Bool = false) { super(type, bubbles, cancelable); this.activating = activating; } public override function clone():ActivityEvent { var event = new ActivityEvent(type, bubbles, cancelable, activating); event.target = target; event.currentTarget = currentTarget; event.eventPhase = eventPhase; return event; } public override function toString():String { return __formatToString("ActivityEvent", ["type", "bubbles", "cancelable", "activating"]); } @:noCompletion private override function __init():Void { super.__init(); activating = false; } } #else typedef ActivityEvent = flash.events.ActivityEvent; #end
0
0.708115
1
0.708115
game-dev
MEDIA
0.717372
game-dev
0.861085
1
0.861085
bates64/papermario-dx
100,638
src/battle/dmg_player.c
#include "common.h" #include "effects.h" #include "battle/battle.h" #include "script_api/battle.h" #include "sprite/player.h" b32 dispatch_damage_event_player(s32 damageAmount, s32 event, b32 noHitSound); b32 dispatch_hazard_event_player(s32 damageAmount, s32 event); API_CALLABLE(PlaySleepHitFX) { fx_debuff(0, script->varTable[0], script->varTable[1], script->varTable[2]); return ApiStatus_DONE2; } API_CALLABLE(PlayDizzyHitFX) { fx_debuff(1, script->varTable[0], script->varTable[1], script->varTable[2]); return ApiStatus_DONE2; } API_CALLABLE(PlayParalyzeHitFX) { EffectInstance* debuffEffect = fx_debuff(2, script->varTable[0], script->varTable[1], script->varTable[2]); debuffEffect->data.debuff->primCol.r = 200; debuffEffect->data.debuff->primCol.g = 120; debuffEffect->data.debuff->primCol.b = 0; debuffEffect->data.debuff->envCol.r = 234; debuffEffect->data.debuff->envCol.g = 193; debuffEffect->data.debuff->envCol.b = 0; return ApiStatus_DONE2; } API_CALLABLE(PlayPoisonHitFX) { EffectInstance* debuffEffect = fx_debuff(2, script->varTable[0], script->varTable[1], script->varTable[2]); debuffEffect->data.debuff->primCol.r = 60; debuffEffect->data.debuff->primCol.g = 160; debuffEffect->data.debuff->primCol.b = 0; debuffEffect->data.debuff->envCol.r = 90; debuffEffect->data.debuff->envCol.g = 240; debuffEffect->data.debuff->envCol.b = 0; return ApiStatus_DONE2; } API_CALLABLE(PlayStopHitFX) { EffectInstance* debuffEffect = fx_debuff(2, script->varTable[0], script->varTable[1], script->varTable[2]); debuffEffect->data.debuff->primCol.r = 205; debuffEffect->data.debuff->primCol.g = 0; debuffEffect->data.debuff->primCol.b = 40; debuffEffect->data.debuff->envCol.r = 205; debuffEffect->data.debuff->envCol.g = 32; debuffEffect->data.debuff->envCol.b = 242; return ApiStatus_DONE2; } API_CALLABLE(PlayFreezeHitSnowflakeFX) { fx_big_snowflakes(0, script->varTable[0], script->varTable[1], script->varTable[2]); return ApiStatus_DONE2; } API_CALLABLE(PlayFreezeHitParticleFX) { Actor* actor = (Actor*)script->varTable[3]; f32 temp1 = actor->size.y; f32 temp2 = actor->size.x / 2; fx_misc_particles(0, script->varTable[0], script->varTable[1], script->varTable[2], temp1, temp2, 1.0f, 10, 30); fx_misc_particles(1, script->varTable[0], script->varTable[1], script->varTable[2], temp1, temp2, 1.0f, 10, 30); return ApiStatus_DONE2; } API_CALLABLE(PlayShrinkHitFX) { s32 i; for (i = 0; i < 20; i++) { fx_floating_cloud_puff(0, script->varTable[0] + rand_int(30) - 15, script->varTable[1] + rand_int(20) - 15, script->varTable[2] + 5, 1.0f, 25); } return ApiStatus_DONE2; } EvtScript EVS_PlaySleepHitFX = { Call(PlaySleepHitFX) Return End }; EvtScript EVS_PlayDizzyHitFX = { Call(PlayDizzyHitFX) Return End }; EvtScript EVS_PlayParalyzeHitFX = { Call(PlayParalyzeHitFX) Return End }; EvtScript EVS_PlayPoisonHitFX = { Call(PlayPoisonHitFX) Return End }; EvtScript EVS_PlayStopHitFX = { Call(PlayStopHitFX) Return End }; EvtScript EVS_PlayFreezeHitFX = { Call(PlayFreezeHitSnowflakeFX) Wait(8) Call(PlayFreezeHitSnowflakeFX) Wait(15) Call(PlayFreezeHitParticleFX) Return End }; EvtScript EVS_PlayShrinkHitFX = { Call(PlayShrinkHitFX) Return End }; void dispatch_event_player(s32 eventType) { Actor* player = gBattleStatus.playerActor; Evt* oldOnHitScript; s32 oldOnHitID; Evt* eventScript; player->lastEventType = eventType; oldOnHitScript = player->handleEventScript; oldOnHitID = player->handleEventScriptID; eventScript = start_script(&EVS_Player_HandleEvent, EVT_PRIORITY_A, EVT_FLAG_RUN_IMMEDIATELY); player->handleEventScript = eventScript; player->handleEventScriptID = eventScript->id; eventScript->owner1.actor = NULL; if (player->takeTurnScript != NULL) { kill_script_by_ID(player->takeTurnScriptID); player->takeTurnScript = NULL; } if (oldOnHitScript != NULL) { kill_script_by_ID(oldOnHitID); } } void dispatch_event_player_continue_turn(s32 eventType) { Actor* player = gBattleStatus.playerActor; Evt* oldOnHitScript; s32 oldOnHitID; Evt* eventScript; player->lastEventType = eventType; oldOnHitScript = player->handleEventScript; oldOnHitID = player->handleEventScriptID; eventScript = start_script(&EVS_Player_HandleEvent, EVT_PRIORITY_A, EVT_FLAG_RUN_IMMEDIATELY); player->handleEventScript = eventScript; player->handleEventScriptID = eventScript->id; eventScript->owner1.actor = NULL; if (oldOnHitScript != NULL) { kill_script_by_ID(oldOnHitID); } } // Determines whether an attack from the player will hit an enemy or HitResult calc_player_test_enemy(void) { BattleStatus* battleStatus = &gBattleStatus; Actor* player = battleStatus->playerActor; ActorState* state = &player->state; s32 targetActorID = battleStatus->curTargetID; s32 targetPartIdx = battleStatus->curTargetPart; Actor* target; ActorPart* targetPart; battleStatus->curTargetID2 = battleStatus->curTargetID; battleStatus->curTargetPart2 = battleStatus->curTargetPart; target = get_actor(targetActorID); if (target == NULL) { return HIT_RESULT_HIT; } targetPart = get_actor_part(target, targetPartIdx); ASSERT(targetPart != NULL); if (targetPart->eventFlags & ACTOR_EVENT_FLAG_ILLUSORY) { return HIT_RESULT_MISS; } if (target->transparentStatus == STATUS_KEY_TRANSPARENT || (targetPart->eventFlags & ACTOR_EVENT_FLAG_BURIED && !(battleStatus->curAttackElement & DAMAGE_TYPE_QUAKE)) ) { return HIT_RESULT_MISS; } if (target->stoneStatus == STATUS_KEY_STONE) { sfx_play_sound_at_position(SOUND_IMMUNE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); return HIT_RESULT_IMMUNE; } if ((battleStatus->curAttackElement & DAMAGE_TYPE_JUMP) && (targetPart->eventFlags & ACTOR_EVENT_FLAG_SPIKY_TOP) && !player_team_is_ability_active(player, ABILITY_SPIKE_SHIELD)) { sfx_play_sound_at_position(SOUND_HIT_SPIKE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); return HIT_RESULT_LANDED_ON_SPIKE; } if (!(battleStatus->curAttackElement & (DAMAGE_TYPE_NO_CONTACT | DAMAGE_TYPE_JUMP)) && (targetPart->eventFlags & ACTOR_EVENT_FLAG_SPIKY_FRONT) && (!(battleStatus->curAttackEventSuppression & SUPPRESS_EVENT_SPIKY_FRONT) && !player_team_is_ability_active(player, ABILITY_SPIKE_SHIELD))) { sfx_play_sound_at_position(SOUND_HIT_SPIKE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); dispatch_hazard_event_player(1, EVENT_SPIKE_CONTACT); dispatch_event_actor(target, EVENT_SPIKE_TAUNT); return HIT_RESULT_BACKFIRE; } if (player->staticStatus != STATUS_KEY_STATIC && target->staticStatus == STATUS_KEY_STATIC) { return HIT_RESULT_HIT_STATIC; } return HIT_RESULT_HIT; } HitResult calc_player_damage_enemy(void) { BattleStatus* battleStatus = &gBattleStatus; Actor* player = battleStatus->playerActor; s32 currentTargetID = battleStatus->curTargetID; s32 currentTargetPartID = battleStatus->curTargetPart; ActorState* state; Evt* evt; Actor* target; ActorPart* targetPart; s32 hitResult; s32 currentAttackDamage; s32 targetDefense; s32 dispatchEvent; s32 partImmuneToElement; s32 canBeShocked; s32 missedAllOrNothing; s32 isFireDamage; s32 isShockDamage; s32 isWaterDamage; s32 isIceDamage; s32 wasSpecialHit; s32 wasStatusInflicted; s32 attackFxType; canBeShocked = FALSE; isFireDamage = FALSE; isWaterDamage = FALSE; isShockDamage = FALSE; isIceDamage = FALSE; wasSpecialHit = FALSE; partImmuneToElement = FALSE; wasStatusInflicted = FALSE; missedAllOrNothing = FALSE; battleStatus->wasStatusInflicted = FALSE; battleStatus->lastAttackDamage = 0; battleStatus->attackerActorID = player->actorID; battleStatus->curTargetID2 = battleStatus->curTargetID; battleStatus->curTargetPart2 = battleStatus->curTargetPart; target = get_actor(currentTargetID); state = &player->state; if (target == NULL) { return HIT_RESULT_HIT; } targetPart = get_actor_part(target, currentTargetPartID); ASSERT(targetPart != NULL); target->lastDamageTaken = 0; if (gBattleStatus.flags1 & BS_FLAGS1_FORCE_IMMUNE_HIT) { hitResult = HIT_RESULT_NO_DAMAGE; dispatchEvent = EVENT_ZERO_DAMAGE; } else { if (player_team_is_ability_active(player, ABILITY_ICE_POWER)) { if (!(battleStatus->curAttackElement & DAMAGE_TYPE_NO_CONTACT)) { battleStatus->curAttackElement |= DAMAGE_TYPE_ICE; } } if (targetPart->eventFlags & ACTOR_EVENT_FLAG_ILLUSORY || target->transparentStatus == STATUS_KEY_TRANSPARENT || (targetPart->eventFlags & ACTOR_EVENT_FLAG_BURIED && !(battleStatus->curAttackElement & DAMAGE_TYPE_QUAKE)) ) { return HIT_RESULT_MISS; } if (target->stoneStatus == STATUS_KEY_STONE) { sfx_play_sound_at_position(SOUND_IMMUNE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); show_immune_bonk(state->goalPos.x, state->goalPos.y, state->goalPos.z, 0, 1, 1); show_next_damage_popup(state->goalPos.x, state->goalPos.y, state->goalPos.z, 0, 0); if (gBattleStatus.flags1 & (BS_FLAGS1_NICE_HIT | BS_FLAGS1_SUPER_HIT)) { return HIT_RESULT_NICE; } else { return HIT_RESULT_HIT; } } if (targetPart->elementalImmunities & battleStatus->curAttackElement) { partImmuneToElement = TRUE; } // check jumping on spiky enemy if ((battleStatus->curAttackElement & DAMAGE_TYPE_JUMP) && (targetPart->eventFlags & ACTOR_EVENT_FLAG_SPIKY_TOP) && !player_team_is_ability_active(player, ABILITY_SPIKE_SHIELD)) { sfx_play_sound_at_position(SOUND_HIT_SPIKE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); dispatch_hazard_event_player(1, EVENT_SPIKE_CONTACT); dispatch_event_actor(target, EVENT_SPIKE_TAUNT); return HIT_RESULT_BACKFIRE; } // check touching fiery enemy and explode on contact if (!(battleStatus->curAttackElement & (DAMAGE_TYPE_NO_CONTACT | DAMAGE_TYPE_SMASH))) { if (targetPart->eventFlags & ACTOR_EVENT_FLAG_EXPLODE_ON_CONTACT) { sfx_play_sound_at_position(SOUND_HIT_PLAYER_FIRE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); dispatch_hazard_event_player(1, EVENT_BURN_CONTACT); dispatch_event_actor(target, EVENT_EXPLODE_TRIGGER); return HIT_RESULT_BACKFIRE; } if (targetPart->eventFlags & ACTOR_EVENT_FLAG_FIREY && !(battleStatus->curAttackEventSuppression & SUPPRESS_EVENT_BURN_CONTACT) && !(player_team_is_ability_active(player, ABILITY_FIRE_SHIELD)) && !(player_team_is_ability_active(player, ABILITY_ICE_POWER)) ) { sfx_play_sound_at_position(SOUND_HIT_PLAYER_FIRE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); dispatch_hazard_event_player(1, EVENT_BURN_CONTACT); dispatch_event_actor(target, EVENT_BURN_TAUNT); return HIT_RESULT_BACKFIRE; } } // check explode on ignition if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && battleStatus->curAttackElement & DAMAGE_TYPE_FIRE && targetPart->eventFlags & (ACTOR_EVENT_FLAG_FIRE_EXPLODE | ACTOR_EVENT_FLAG_EXPLODE_ON_IGNITION) ) { sfx_play_sound_at_position(SOUND_HIT_PLAYER_FIRE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); dispatch_event_actor(target, EVENT_EXPLODE_TRIGGER); if (gBattleStatus.flags1 & (BS_FLAGS1_NICE_HIT | BS_FLAGS1_SUPER_HIT)) { return HIT_RESULT_NICE; } else { return HIT_RESULT_HIT; } } // unknown alternate spiky #1 if (!(battleStatus->curAttackElement & (DAMAGE_TYPE_NO_CONTACT | DAMAGE_TYPE_SMASH)) && targetPart->eventFlags & ACTOR_EVENT_FLAG_ALT_SPIKY && !(battleStatus->curAttackEventSuppression & SUPPRESS_EVENT_ALT_SPIKY) && !player_team_is_ability_active(player, ABILITY_SPIKE_SHIELD) ) { sfx_play_sound_at_position(SOUND_HIT_SPIKE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); dispatch_hazard_event_player(1, EVENT_SPIKE_CONTACT); dispatch_event_actor(target, EVENT_SPIKE_TAUNT); return HIT_RESULT_BACKFIRE; } if (battleStatus->curAttackElement & DAMAGE_TYPE_FIRE) { fx_ring_blast(0, state->goalPos.x, state->goalPos.y, state->goalPos.z * 5.0f, 1.0f, 24); isFireDamage = TRUE; } if (battleStatus->curAttackElement & DAMAGE_TYPE_SHOCK) { apply_shock_effect(target); isShockDamage = TRUE; } if (battleStatus->curAttackElement & DAMAGE_TYPE_WATER) { fx_water_splash(0, state->goalPos.x, state->goalPos.y, state->goalPos.z + 5.0f, 1.0f, 24); isWaterDamage = TRUE; } if (battleStatus->curAttackElement & DAMAGE_TYPE_ICE) { fx_big_snowflakes(0, state->goalPos.x, state->goalPos.y, state->goalPos.z + 5.0f); isIceDamage = TRUE; } attackFxType = player_team_is_ability_active(player, ABILITY_ATTACK_FX); if (attackFxType) { fx_breaking_junk(0, state->goalPos.x, state->goalPos.y, state->goalPos.z + 5.0f, 1.0f, 30); switch (attackFxType) { case 1: sfx_play_sound_at_position(SOUND_LIFE_SHROOM_CHIME, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); break; case 2: sfx_play_sound_at_position(SOUND_PLANTS_BELL, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); break; case 3: sfx_play_sound_at_position(SOUND_SLIDE_WHISTLE_OUT, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); break; case 4: sfx_play_sound_at_position(SOUND_YOSHI, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); break; case 5: sfx_play_sound_at_position(SOUND_HIT_WHACKA, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); break; case 6: sfx_play_sound_at_position(SOUND_FLOWERS_LAUGH, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); break; } } if (!is_ability_active(ABILITY_ZAP_TAP) && player->staticStatus != STATUS_KEY_STATIC && (target->staticStatus == STATUS_KEY_STATIC || targetPart->eventFlags & ACTOR_EVENT_FLAG_ELECTRIFIED) && !(battleStatus->curAttackElement & (DAMAGE_TYPE_NO_CONTACT | DAMAGE_TYPE_SHOCK)) && !(battleStatus->curAttackEventSuppression & SUPPRESS_EVENT_SHOCK_CONTACT) ) { gBattleStatus.flags1 |= BS_FLAGS1_TRIGGER_EVENTS; canBeShocked = TRUE; } if (targetPart->eventFlags & (ACTOR_EVENT_FLAG_STAR_ROD_ENCHANTED | ACTOR_EVENT_FLAG_ENCHANTED)) { battleStatus->curAttackElement &= ~DAMAGE_TYPE_IGNORE_DEFENSE; } targetDefense = get_defense(target, targetPart->defenseTable, battleStatus->curAttackElement); if (!(battleStatus->curAttackElement & DAMAGE_TYPE_IGNORE_DEFENSE)) { targetDefense += target->defenseBoost; } if (targetPart->eventFlags & ACTOR_EVENT_FLAG_EXTREME_DEFENSE) { targetDefense += 127; } currentAttackDamage = battleStatus->curAttackDamage; currentAttackDamage += count_power_plus(battleStatus->curAttackElement); if (battleStatus->merleeAttackBoost > 0 && (gBattleStatus.flags1 & BS_FLAGS1_INCLUDE_POWER_UPS || battleStatus->curAttackElement & DAMAGE_TYPE_JUMP) ) { currentAttackDamage += battleStatus->merleeAttackBoost; } if (battleStatus->jumpCharge && battleStatus->curAttackElement & DAMAGE_TYPE_JUMP) { currentAttackDamage += battleStatus->jumpCharge; gBattleStatus.flags1 &= ~BS_FLAGS1_JUMP_CHARGED; } if (battleStatus->hammerCharge && battleStatus->curAttackElement & (DAMAGE_TYPE_QUAKE_HAMMER | DAMAGE_TYPE_THROW | DAMAGE_TYPE_SMASH)) { currentAttackDamage += battleStatus->hammerCharge; gBattleStatus.flags1 &= ~BS_FLAGS1_HAMMER_CHARGED; } if (battleStatus->unk_98 != 0) { currentAttackDamage += 2; } if (player_team_is_ability_active(player, ABILITY_BERSERKER)) { currentAttackDamage += 2; } if (player_team_is_ability_active(player, ABILITY_P_UP_D_DOWN)) { currentAttackDamage++; } if (player_team_is_ability_active(player, ABILITY_P_DOWN_D_UP)) { currentAttackDamage--; } if (battleStatus->turboChargeTurnsLeft != 0) { currentAttackDamage++; } currentAttackDamage += player->attackBoost; if (player_team_is_ability_active(player, ABILITY_HP_DRAIN)) { battleStatus->hpDrainCount++; currentAttackDamage--; if (currentAttackDamage < 0) { battleStatus->hpDrainCount += currentAttackDamage; } gBattleStatus.flags2 |= BS_FLAGS2_HAS_DRAINED_HP; if (battleStatus->hpDrainCount > 5) { battleStatus->hpDrainCount = 5; } } if (player_team_is_ability_active(player, ABILITY_MEGA_HP_DRAIN)) { battleStatus->hpDrainCount += 2; currentAttackDamage -= 2; if (currentAttackDamage < 0) { battleStatus->hpDrainCount += currentAttackDamage; } gBattleStatus.flags2 |= BS_FLAGS2_HAS_DRAINED_HP; if (battleStatus->hpDrainCount > 5) { battleStatus->hpDrainCount = 5; } } if (gBattleStatus.flags2 & BS_FLAGS2_HAS_RUSH && (gBattleStatus.flags1 & BS_FLAGS1_INCLUDE_POWER_UPS || battleStatus->curAttackElement & DAMAGE_TYPE_JUMP) ) { if (battleStatus->rushFlags & RUSH_FLAG_POWER) { currentAttackDamage += 2; } if (battleStatus->rushFlags & RUSH_FLAG_MEGA) { currentAttackDamage += 4; } fx_radial_shimmer(9, state->goalPos.x, state->goalPos.y, state->goalPos.z, 0.5f, 20); } if (!(gBattleStatus.flags2 & BS_FLAGS2_IS_FIRST_STRIKE) && player_team_is_ability_active(player, ABILITY_ALL_OR_NOTHING) ) { currentAttackDamage++; if (!(gBattleStatus.flags1 & (BS_FLAGS1_NICE_HIT | BS_FLAGS1_SUPER_HIT))) { missedAllOrNothing = TRUE; currentAttackDamage = 0; #if !VERSION_JP targetDefense = 0; #endif gBattleStatus.flags1 &= ~BS_FLAGS1_NICE_HIT; gBattleStatus.flags1 &= ~BS_FLAGS1_SUPER_HIT; gBattleStatus.flags1 &= ~BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 |= BS_FLAGS1_TRIGGER_EVENTS; } } if (player->debuff == STATUS_KEY_SHRINK) { if (currentAttackDamage > 0) { currentAttackDamage /= 2; if (currentAttackDamage == 0) { currentAttackDamage = 1; } } } if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && battleStatus->curAttackElement & DAMAGE_TYPE_BLAST && targetPart->eventFlags & ACTOR_EVENT_FLAG_EXPLODE_ON_IGNITION ) { targetDefense = 0; currentAttackDamage = target->curHP; } if (battleStatus->curAttackElement & DAMAGE_TYPE_STATUS_ALWAYS_HITS) { targetDefense = 0; currentAttackDamage = 0; } if (currentAttackDamage > 99) { currentAttackDamage = 99; } if (currentAttackDamage < 0) { targetDefense = 0; } target->hpChangeCounter = 0; currentAttackDamage -= targetDefense; if (currentAttackDamage < 0) { currentAttackDamage = 0; } if (battleStatus->curAttackElement & DAMAGE_TYPE_POWER_BOUNCE && currentAttackDamage > 0) { currentAttackDamage += battleStatus->powerBounceCounter; if (currentAttackDamage < 1) { currentAttackDamage = 1; } } battleStatus->lastAttackDamage = 0; if (currentAttackDamage < 1) { target->hpChangeCounter = 0; hitResult = HIT_RESULT_NO_DAMAGE; if (!(battleStatus->curAttackElement & DAMAGE_TYPE_STATUS_ALWAYS_HITS)) { dispatchEvent = EVENT_ZERO_DAMAGE; sfx_play_sound_at_position(SOUND_IMMUNE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } else { if (target->curHP < 1) { dispatchEvent = EVENT_DEATH; } else { dispatchEvent = EVENT_ZERO_DAMAGE; } } battleStatus->lastAttackDamage = 0; } else { target->damageCounter += currentAttackDamage; dispatchEvent = EVENT_HIT_COMBO; hitResult = HIT_RESULT_HIT; target->hpChangeCounter -= currentAttackDamage; if (!(targetPart->flags & ACTOR_PART_FLAG_DAMAGE_IMMUNE) && !(gBattleStatus.flags1 & BS_FLAGS1_TUTORIAL_BATTLE) && !partImmuneToElement && !(targetPart->targetFlags & ACTOR_PART_TARGET_NO_DAMAGE) ) { target->curHP -= currentAttackDamage; if (target->curHP < 1) { target->curHP = 0; dispatchEvent = EVENT_DEATH; } } battleStatus->lastAttackDamage += currentAttackDamage; target->lastDamageTaken = battleStatus->lastAttackDamage; target->hpChangeCounter = 0; } if (targetPart->flags & ACTOR_PART_FLAG_DAMAGE_IMMUNE) { if (!is_ability_active(ABILITY_ZAP_TAP) && player->staticStatus != STATUS_KEY_STATIC && (target->staticStatus == STATUS_KEY_STATIC || (targetPart->eventFlags & ACTOR_EVENT_FLAG_ELECTRIFIED)) && !(battleStatus->curAttackElement & DAMAGE_TYPE_NO_CONTACT) && !(battleStatus->curAttackEventSuppression & SUPPRESS_EVENT_SHOCK_CONTACT) && !(battleStatus->curAttackElement & DAMAGE_TYPE_SHOCK) ) { sfx_play_sound_at_position(SOUND_HIT_PLAYER_SHOCK, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); apply_shock_effect(player); dispatch_hazard_event_player(1, EVENT_SHOCK_HIT); return HIT_RESULT_BACKFIRE; } else { if (!(gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS)) { dispatchEvent = EVENT_ZERO_DAMAGE; } else { dispatchEvent = EVENT_IMMUNE; } sfx_play_sound_at_position(SOUND_IMMUNE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); dispatch_event_actor(target, dispatchEvent); show_immune_bonk(state->goalPos.x, state->goalPos.y, state->goalPos.z, 0, 1, 3); if (gBattleStatus.flags1 & (BS_FLAGS1_NICE_HIT | BS_FLAGS1_SUPER_HIT)) { return HIT_RESULT_NICE; } else { return HIT_RESULT_HIT; } } } if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS) { if (battleStatus->curAttackElement & DAMAGE_TYPE_FEAR && rand_int(99) < (target->actorBlueprint->escapeChance * battleStatus->statusChance) / 100 && (target->debuff != STATUS_KEY_FEAR && target->debuff != STATUS_KEY_DIZZY && target->debuff != STATUS_KEY_PARALYZE && target->debuff != STATUS_KEY_SLEEP && target->debuff != STATUS_KEY_FROZEN && target->debuff != STATUS_KEY_STOP) && !(target->flags & ACTOR_FLAG_FLIPPED) ) { dispatch_event_actor(target, EVENT_SCARE_AWAY); if (gBattleStatus.flags1 & (BS_FLAGS1_NICE_HIT | BS_FLAGS1_SUPER_HIT)) { return HIT_RESULT_NICE; } else { return HIT_RESULT_HIT; } } } } if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS) { if (dispatchEvent == EVENT_HIT_COMBO) { dispatchEvent = EVENT_HIT; } if (dispatchEvent == EVENT_ZERO_DAMAGE) { dispatchEvent = EVENT_IMMUNE; } if (target->curHP < 1) { if (dispatchEvent == EVENT_IMMUNE) { dispatchEvent = EVENT_DEATH; } } } else if (dispatchEvent == EVENT_DEATH) { dispatchEvent = EVENT_HIT_COMBO; } if (!(gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS)) { clear_part_pal_adjustment(targetPart); } // check for special case damage events if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS) { // if damage is from Spin Smash, convert generic events to Spin Smash specific events if (battleStatus->curAttackElement & DAMAGE_TYPE_SPIN_SMASH) { PlayerData* playerData = &gPlayerData; if (target->actorBlueprint->spinSmashReq != 255 && playerData->hammerLevel + 1 >= target->actorBlueprint->spinSmashReq && battleStatus->lastAttackDamage > 0 && gBattleStatus.flags1 & BS_FLAGS1_NICE_HIT ) { if (dispatchEvent == EVENT_HIT_COMBO) { dispatchEvent = EVENT_SPIN_SMASH_HIT; } if (dispatchEvent == EVENT_HIT) { dispatchEvent = EVENT_SPIN_SMASH_HIT; } if (dispatchEvent == EVENT_ZERO_DAMAGE) { dispatchEvent = EVENT_SPIN_SMASH_HIT; } if (dispatchEvent == EVENT_IMMUNE) { dispatchEvent = EVENT_SPIN_SMASH_HIT; } if (dispatchEvent == EVENT_DEATH) { dispatchEvent = EVENT_SPIN_SMASH_DEATH; } } } // if damage is from Power Bounce, convert generic events to Power Bounce specific events if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && !(battleStatus->curAttackElement & DAMAGE_TYPE_NO_CONTACT) && targetPart->eventFlags & ACTOR_EVENT_FLAG_POWER_BOUNCE ) { if (dispatchEvent == EVENT_HIT_COMBO) { dispatchEvent = EVENT_POWER_BOUNCE_HIT; } if (dispatchEvent == EVENT_HIT) { dispatchEvent = EVENT_POWER_BOUNCE_HIT; } if (dispatchEvent == EVENT_ZERO_DAMAGE) { dispatchEvent = EVENT_POWER_BOUNCE_HIT; } if (dispatchEvent == EVENT_IMMUNE) { dispatchEvent = EVENT_POWER_BOUNCE_HIT; } if (dispatchEvent == EVENT_DEATH) { dispatchEvent = EVENT_POWER_BOUNCE_DEATH; } } // try generating fall trigger events if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && (battleStatus->curAttackElement & (DAMAGE_TYPE_POW | DAMAGE_TYPE_JUMP)) && targetPart->eventFlags & ACTOR_EVENT_FLAG_GROUNDABLE ) { if (dispatchEvent == EVENT_HIT) { dispatchEvent = EVENT_FALL_TRIGGER; } if (dispatchEvent == EVENT_IMMUNE) { dispatchEvent = EVENT_FALL_TRIGGER; } wasSpecialHit = TRUE; } // try generating flip trigger events if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && (battleStatus->curAttackElement & (DAMAGE_TYPE_QUAKE | DAMAGE_TYPE_POW | DAMAGE_TYPE_JUMP)) && targetPart->eventFlags & ACTOR_EVENT_FLAG_FLIPABLE ) { if (dispatchEvent == EVENT_HIT) { dispatchEvent = EVENT_FLIP_TRIGGER; } if (dispatchEvent == EVENT_IMMUNE) { dispatchEvent = EVENT_FLIP_TRIGGER; } if (!(target->flags & ACTOR_FLAG_FLIPPED)) { wasSpecialHit = TRUE; } } } // try generating flip trigger events if (!(gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS) && battleStatus->curAttackElement & (DAMAGE_TYPE_QUAKE | DAMAGE_TYPE_POW | DAMAGE_TYPE_JUMP) && targetPart->eventFlags & ACTOR_EVENT_FLAG_FLIPABLE ) { if (dispatchEvent == EVENT_HIT_COMBO) { dispatchEvent = EVENT_FLIP_TRIGGER; } if (dispatchEvent == EVENT_ZERO_DAMAGE) { dispatchEvent = EVENT_FLIP_TRIGGER; } if (!(target->flags & ACTOR_FLAG_FLIPPED)) { wasSpecialHit = TRUE; } } // try generating shell crack events if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && battleStatus->curAttackElement & DAMAGE_TYPE_SHELL_CRACK && targetPart->eventFlags & ACTOR_EVENT_FLAG_FLIPABLE ) { if (dispatchEvent == EVENT_HIT) { dispatchEvent = EVENT_SHELL_CRACK_HIT; } if (dispatchEvent == EVENT_IMMUNE) { dispatchEvent = EVENT_SHELL_CRACK_HIT; } wasSpecialHit = TRUE; } // try generating burn events if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && (battleStatus->curAttackElement & (DAMAGE_TYPE_BLAST | DAMAGE_TYPE_FIRE)) ) { if (dispatchEvent == EVENT_HIT) { dispatchEvent = EVENT_BURN_HIT; } if (dispatchEvent == EVENT_DEATH) { dispatchEvent = EVENT_BURN_DEATH; } isFireDamage = TRUE; } // try inflicting status effects if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS && battleStatus->lastAttackDamage >= 0 && dispatchEvent != EVENT_DEATH && dispatchEvent != EVENT_SPIN_SMASH_DEATH && dispatchEvent != EVENT_EXPLODE_TRIGGER && !(targetPart->targetFlags & ACTOR_PART_TARGET_NO_DAMAGE) ) { #define INFLICT_STATUS(STATUS_TYPE) \ if ((battleStatus->curAttackStatus & STATUS_FLAG_##STATUS_TYPE) && \ try_inflict_status(target, STATUS_KEY_##STATUS_TYPE, STATUS_TURN_MOD_##STATUS_TYPE)) { \ wasSpecialHit = TRUE; \ wasStatusInflicted = TRUE; \ } \ INFLICT_STATUS(SHRINK); INFLICT_STATUS(POISON); INFLICT_STATUS(STONE); INFLICT_STATUS(SLEEP); INFLICT_STATUS(STOP); INFLICT_STATUS(STATIC); INFLICT_STATUS(FEAR); INFLICT_STATUS(PARALYZE); INFLICT_STATUS(DIZZY); #undef INFLICT_STATUS if (wasStatusInflicted) { if (dispatchEvent == EVENT_ZERO_DAMAGE) { dispatchEvent = EVENT_HIT_COMBO; } if (dispatchEvent == EVENT_IMMUNE) { dispatchEvent = EVENT_HIT; } } } battleStatus->wasStatusInflicted = wasStatusInflicted; dispatch_event_actor(target, dispatchEvent); if (!(target->flags & ACTOR_FLAG_NO_DMG_POPUP)) { if (battleStatus->lastAttackDamage == 0) { if (!wasSpecialHit && !wasStatusInflicted) { show_immune_bonk(state->goalPos.x, state->goalPos.y, state->goalPos.z, 0, 1, 3); } } else if (!partImmuneToElement) { if (battleStatus->curAttackElement & (DAMAGE_TYPE_MULTIPLE_POPUPS | DAMAGE_TYPE_SMASH)) { show_next_damage_popup(state->goalPos.x, state->goalPos.y, state->goalPos.z, battleStatus->lastAttackDamage, 0); } else { show_primary_damage_popup(state->goalPos.x, state->goalPos.y, state->goalPos.z, battleStatus->lastAttackDamage, 0); } if (!(targetPart->targetFlags & ACTOR_PART_TARGET_NO_DAMAGE)) { show_damage_fx(target, state->goalPos.x, state->goalPos.y, state->goalPos.z, battleStatus->lastAttackDamage); } } } if ((wasSpecialHit && gBattleStatus.flags1 & BS_FLAGS1_NICE_HIT) || gBattleStatus.flags1 & BS_FLAGS1_NICE_HIT) { if (!(gBattleStatus.flags1 & BS_FLAGS1_NO_RATING)) { if (player->actorTypeData1[5]) { sfx_play_sound_at_position(player->actorTypeData1[5], SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->lastAttackDamage > 0) { sfx_play_sound(SOUND_DAMAGE_STARS); } if (battleStatus->lastAttackDamage > 0 || ((battleStatus->curAttackElement & DAMAGE_TYPE_STATUS_ALWAYS_HITS) && wasSpecialHit)) { if (!(battleStatus->curAttackElement & DAMAGE_TYPE_MULTI_BOUNCE)) { show_action_rating(ACTION_RATING_NICE, target, state->goalPos.x, state->goalPos.y, state->goalPos.z); } else { show_action_rating(ACTION_RATING_NICE_SUPER_COMBO, target, state->goalPos.x, state->goalPos.y, state->goalPos.z); } } } } if (missedAllOrNothing) { show_action_rating(ACTION_RATING_MISS, target, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (gBattleStatus.flags1 & BS_FLAGS1_TRIGGER_EVENTS) { func_80266970(target); } if ((battleStatus->lastAttackDamage > 0 || wasSpecialHit) && !partImmuneToElement) { set_actor_flash_mode(target, 1); if (isFireDamage) { sfx_play_sound_at_position(SOUND_HIT_FIRE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } else if (isShockDamage) { sfx_play_sound_at_position(SOUND_HIT_SHOCK, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } else if (isIceDamage) { sfx_play_sound_at_position(SOUND_HIT_ICE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } else { sfx_play_sound_at_position(SOUND_HIT_NORMAL, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } } if (battleStatus->lastAttackDamage < 1 && !wasSpecialHit && !canBeShocked || targetPart->flags & ACTOR_PART_FLAG_DAMAGE_IMMUNE) { sfx_play_sound_at_position(SOUND_IMMUNE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackStatus & STATUS_FLAG_SLEEP && wasStatusInflicted) { evt = start_script(&EVS_PlaySleepHitFX, EVT_PRIORITY_A, 0); evt->varTable[0] = state->goalPos.x; evt->varTable[1] = state->goalPos.y; evt->varTable[2] = state->goalPos.z; sfx_play_sound_at_position(SOUND_INFLICT_SLEEP, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackStatus & STATUS_FLAG_DIZZY && wasStatusInflicted) { evt = start_script(&EVS_PlayDizzyHitFX, EVT_PRIORITY_A, 0); evt->varTable[0] = state->goalPos.x; evt->varTable[1] = state->goalPos.y; evt->varTable[2] = state->goalPos.z; sfx_play_sound_at_position(SOUND_INFLICT_STATUS, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackStatus & STATUS_FLAG_PARALYZE && wasStatusInflicted) { evt = start_script(&EVS_PlayParalyzeHitFX, EVT_PRIORITY_A, 0); evt->varTable[0] = state->goalPos.x; evt->varTable[1] = state->goalPos.y; evt->varTable[2] = state->goalPos.z; sfx_play_sound_at_position(SOUND_INFLICT_STATUS, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackStatus & STATUS_FLAG_POISON && wasStatusInflicted) { evt = start_script(&EVS_PlayPoisonHitFX, EVT_PRIORITY_A, 0); evt->varTable[0] = state->goalPos.x; evt->varTable[1] = state->goalPos.y; evt->varTable[2] = state->goalPos.z; sfx_play_sound_at_position(SOUND_INFLICT_STATUS, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackStatus & STATUS_FLAG_STOP && wasStatusInflicted) { evt = start_script(&EVS_PlayStopHitFX, EVT_PRIORITY_A, 0); evt->varTable[0] = state->goalPos.x; evt->varTable[1] = state->goalPos.y; evt->varTable[2] = state->goalPos.z; sfx_play_sound_at_position(SOUND_INFLICT_STATUS, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackStatus & STATUS_FLAG_FROZEN && wasStatusInflicted) { evt = start_script(&EVS_PlayFreezeHitFX, EVT_PRIORITY_A, 0); evt->varTable[0] = state->goalPos.x; evt->varTable[1] = state->goalPos.y; evt->varTable[2] = state->goalPos.z; evt->varTablePtr[3] = target; sfx_play_sound_at_position(SOUND_HIT_PLAYER_ICE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackStatus & STATUS_FLAG_SHRINK && wasStatusInflicted) { evt = start_script(&EVS_PlayShrinkHitFX, EVT_PRIORITY_A, 0); evt->varTable[0] = state->goalPos.x; evt->varTable[1] = state->goalPos.y; evt->varTable[2] = state->goalPos.z; evt->varTablePtr[3] = target; sfx_play_sound_at_position(SOUND_INFLICT_STATUS, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } if (battleStatus->curAttackElement & DAMAGE_TYPE_SMASH && target->actorType == ACTOR_TYPE_GOOMNUT_TREE) { sfx_play_sound_at_position(SOUND_SMACK_TREE, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } show_actor_health_bar(target); if (gBattleStatus.flags1 & (BS_FLAGS1_NICE_HIT | BS_FLAGS1_SUPER_HIT)) { if (hitResult == HIT_RESULT_HIT) { hitResult = HIT_RESULT_NICE; } if (hitResult == HIT_RESULT_NO_DAMAGE) { hitResult = HIT_RESULT_NICE_NO_DAMAGE; } } if (!is_ability_active(ABILITY_ZAP_TAP) && (player->staticStatus != STATUS_KEY_STATIC) && (target->staticStatus == STATUS_KEY_STATIC || targetPart->eventFlags & ACTOR_EVENT_FLAG_ELECTRIFIED) && !(battleStatus->curAttackElement & (DAMAGE_TYPE_NO_CONTACT | DAMAGE_TYPE_SHOCK)) && !(battleStatus->curAttackEventSuppression & SUPPRESS_EVENT_SHOCK_CONTACT) ) { sfx_play_sound_at_position(SOUND_HIT_PLAYER_SHOCK, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); apply_shock_effect(player); dispatch_hazard_event_player(1, EVENT_SHOCK_HIT); return HIT_RESULT_BACKFIRE; } return hitResult; } b32 dispatch_damage_event_player(s32 damageAmount, s32 event, b32 noHitSound) { BattleStatus* battleStatus = &gBattleStatus; PlayerData* playerData = &gPlayerData; Actor* player = battleStatus->playerActor; ActorState* state = &player->state; s32 oldHPChangeCounter; s32 flags; s32 dispatchEvent; s32 oldPlayerHP; s32 temp; battleStatus->curAttackDamage = damageAmount; temp = (s16)damageAmount; //TODO usage of temp here required to match player->hpChangeCounter += temp; temp = player->hpChangeCounter; player->curHP = playerData->curHP; player->damageCounter += temp; player->hpChangeCounter -= temp; battleStatus->lastAttackDamage = 0; player->curHP -= temp; battleStatus->damageTaken += temp; oldPlayerHP = player->curHP; dispatchEvent = event; if (player->curHP < 1) { battleStatus->lastAttackDamage += oldPlayerHP; player->curHP = 0; dispatchEvent = EVENT_DEATH; } battleStatus->lastAttackDamage += temp; playerData->curHP = player->curHP; if (dispatchEvent == EVENT_HIT_COMBO) { dispatchEvent = EVENT_HIT; } if (dispatchEvent == EVENT_ZERO_DAMAGE) { dispatchEvent = EVENT_IMMUNE; } if (dispatchEvent == EVENT_DEATH) { if (event == EVENT_SPIKE_CONTACT) { dispatchEvent = EVENT_SPIKE_DEATH; } if (event == EVENT_BURN_CONTACT) { dispatchEvent = EVENT_BURN_DEATH; } if (event == EVENT_SHOCK_HIT) { dispatchEvent = EVENT_SHOCK_DEATH; } } if (!noHitSound) { set_goal_pos_to_part(state, ACTOR_PLAYER, 0); sfx_play_sound_at_position(SOUND_HIT_NORMAL, SOUND_SPACE_DEFAULT, state->goalPos.x, state->goalPos.y, state->goalPos.z); } show_next_damage_popup(state->goalPos.x, state->goalPos.y, state->goalPos.z, battleStatus->lastAttackDamage, 1); show_damage_fx(player, state->goalPos.x, state->goalPos.y, state->goalPos.z, battleStatus->lastAttackDamage); if (battleStatus->lastAttackDamage > 0) { set_actor_flash_mode(player, 1); } flags = (gBattleStatus.flags1 & (BS_FLAGS1_NICE_HIT | BS_FLAGS1_SUPER_HIT)) != 0; dispatch_event_player(dispatchEvent); return flags; } // damage received from "damage over time" effects (only used for poison) b32 dispatch_damage_tick_event_player(s32 damageAmount, s32 event) { BattleStatus* battleStatus = &gBattleStatus; battleStatus->curAttackElement = ELEMENT_END; battleStatus->curDamageSource = DMG_SRC_DEFAULT; return dispatch_damage_event_player(damageAmount, event, FALSE); } // damage received from contact hazards b32 dispatch_hazard_event_player(s32 damageAmount, s32 event) { return dispatch_damage_event_player(damageAmount, event, TRUE); } API_CALLABLE(GetMenuSelection) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; s32 outVar1 = *args++; s32 outVar2 = *args++; s32 outVar3 = *args++; evt_set_variable(script, outVar1, battleStatus->moveCategory); evt_set_variable(script, outVar2, battleStatus->moveArgument); evt_set_variable(script, outVar3, battleStatus->selectedMoveID); return ApiStatus_DONE2; } API_CALLABLE(PlayerHopToGoal) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; Actor* player = battleStatus->playerActor; ActorState* playerState = &player->state; f32 playerVel; f32 x, y, z; f32 goalX, goalY, goalZ; if (isInitialCall) { script->functionTemp[0] = FALSE; } if (script->functionTemp[0] == 0) { playerState->moveTime = evt_get_variable(script, *args++); playerState->moveArcAmplitude = evt_get_variable(script, *args++); script->functionTemp[1] = evt_get_variable(script, *args++); playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; x = playerState->curPos.x; y = playerState->curPos.y; z = playerState->curPos.z; goalX = playerState->goalPos.x; goalY = playerState->goalPos.y; goalZ = playerState->goalPos.z; playerState->angle = atan2(x, z, goalX, goalZ); playerState->dist = dist2D(x, z, goalX, goalZ); if (playerState->moveTime == 0) { playerState->moveTime = playerState->dist / playerState->speed; } else { playerState->speed = playerState->dist / playerState->moveTime; } playerState->speed = playerState->dist / playerState->moveTime; playerState->vel = (playerState->acceleration * playerState->moveTime * 0.5f) + ((goalY - y) / playerState->moveTime); set_actor_anim(0, 0, playerState->animJumpRise); playerState->unk_24 = 90.0f; playerState->unk_28 = 180 / playerState->moveTime; playerState->unk_2C = playerState->goalPos.y; if (script->functionTemp[1] != 2) { sfx_play_sound_at_position(SOUND_LONG_PLAYER_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); } script->functionTemp[0] = TRUE; } if (playerState->vel < 0.0f) { set_actor_anim(0, 0, playerState->animJumpFall); } playerVel = playerState->vel; switch (playerState->moveArcAmplitude) { case 0: break; case 1: if (playerState->curPos.y - playerState->unk_2C > 45.0f) { playerVel *= 0.25f; } break; case 2: if (playerState->curPos.y - playerState->unk_2C > 54.9) { playerVel *= 0.25f; } break; } playerState->curPos.y += playerVel; playerState->vel -= playerState->acceleration; add_xz_vec3f(&playerState->curPos, playerState->speed + sin_rad(DEG_TO_RAD(playerState->unk_24)), playerState->angle); playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y; player->curPos.z = playerState->curPos.z; playerState->moveTime--; if (playerState->moveTime >= 0) { return ApiStatus_BLOCK; } player->curPos.y = playerState->goalPos.y; if (script->functionTemp[1] != 1) { play_movement_dust_effects(2, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); } if (script->functionTemp[1] != 2) { sfx_play_sound_at_position(SOUND_LAND_SOFTLY, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); } return ApiStatus_DONE1; } API_CALLABLE(PlayerFallToGoal) { Bytecode* args = script->ptrReadPos; Actor* player = gBattleStatus.playerActor; ActorState* state = &player->state; f32 x, y, z; f32 goalX, goalY, goalZ; if (isInitialCall) { script->functionTemp[0] = FALSE; } if (!script->functionTemp[0]) { s32 moveTime = evt_get_variable(script, *args++); player->state.curPos.x = player->curPos.x; player->state.curPos.y = player->curPos.y; player->state.curPos.z = player->curPos.z; x = player->state.curPos.x; y = player->state.curPos.y; z = player->state.curPos.z; goalX = player->state.goalPos.x; goalY = player->state.goalPos.y; goalZ = player->state.goalPos.z; state->moveTime = moveTime; player->state.angle = atan2(x, z, goalX, goalZ); player->state.dist = dist2D(x, z, goalX, goalZ); y = goalY - y; if (state->moveTime == 0) { state->moveTime = state->dist / state->speed; } else { state->speed = state->dist / state->moveTime; } state->vel = 0.0f; state->acceleration = ((y / state->moveTime) - state->vel) / (-state->moveTime * 0.5); set_actor_anim(ACTOR_PLAYER, 0, state->animJumpRise); script->functionTemp[0] = TRUE; } if (state->vel < 0.0f) { set_actor_anim(ACTOR_PLAYER, 0, state->animJumpFall); } state->curPos.y += state->vel; state->vel -= state->acceleration; add_xz_vec3f(&state->curPos, state->speed, state->angle); player->curPos.x = state->curPos.x; player->curPos.y = state->curPos.y; player->curPos.z = state->curPos.z; state->moveTime--; if (state->moveTime < 0) { player->curPos.x = state->goalPos.x; player->curPos.y = state->goalPos.y; player->curPos.z = state->goalPos.z; play_movement_dust_effects(2, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); sfx_play_sound_at_position(SOUND_LAND_SOFTLY, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); return ApiStatus_DONE1; } return ApiStatus_BLOCK; } API_CALLABLE(PlayerLandJump) { Actor* player = gBattleStatus.playerActor; ActorState* walkMovement = &player->state; if (isInitialCall) { script->functionTemp[0] = 0; } if (script->functionTemp[0] == 0) { walkMovement->curPos.x = player->curPos.x; walkMovement->curPos.y = player->curPos.y; walkMovement->curPos.z = player->curPos.z; script->functionTemp[0] = 1; } if (walkMovement->vel > 0.0f) { if (walkMovement->animJumpRise != 0) { set_actor_anim(0, 0, walkMovement->animJumpRise); } } if (walkMovement->vel < 0.0f) { if (walkMovement->animJumpFall != 0) { set_actor_anim(0, 0, walkMovement->animJumpFall); } } walkMovement->curPos.y += walkMovement->vel; walkMovement->vel -= walkMovement->acceleration; add_xz_vec3f(&walkMovement->curPos, walkMovement->speed, walkMovement->angle); player->curPos.x = walkMovement->curPos.x; player->curPos.y = walkMovement->curPos.y; player->curPos.z = walkMovement->curPos.z; if (player->curPos.y < 0.0f) { player->curPos.y = 0.0f; play_movement_dust_effects(2, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); sfx_play_sound_at_position(SOUND_LAND_SOFTLY, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); return ApiStatus_DONE1; } return ApiStatus_BLOCK; } API_CALLABLE(PlayerRunToGoal) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; Actor* player = battleStatus->playerActor; ActorState* playerState = &player->state; f32 currentX, currentZ, goalX, goalZ; if (isInitialCall) { script->functionTemp[0] = FALSE; } if (!script->functionTemp[0]) { player->state.moveTime = evt_get_variable(script, *args++); player->state.curPos.x = player->curPos.x; player->state.curPos.y = player->curPos.y; player->state.curPos.z = player->curPos.z; goalX = player->state.goalPos.x; goalZ = player->state.goalPos.z; currentX = player->state.curPos.x; currentZ = player->state.curPos.z; player->state.angle = atan2(currentX, currentZ, goalX, goalZ); player->state.dist = dist2D(currentX, currentZ, goalX, goalZ); if (player->state.moveTime == 0) { player->state.moveTime = player->state.dist / player->state.speed; if (player->state.moveTime == 0) { player->state.moveTime = 1; } player->state.speed += (player->state.dist - (player->state.moveTime * player->state.speed)) / player->state.moveTime; } else { player->state.speed = player->state.dist / player->state.moveTime; } playerState->dist = player->actorTypeData1b[0] + 1; script->functionTemp[0] = TRUE; } add_xz_vec3f(&playerState->curPos, playerState->speed, playerState->angle); player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y; player->curPos.z = playerState->curPos.z; if (playerState->speed < 4.0f) { play_movement_dust_effects(0, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); } else { play_movement_dust_effects(1, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); } playerState->dist += playerState->speed; if (playerState->dist > player->actorTypeData1b[0]) { player->footStepCounter++; playerState->dist = 0.0f; if ((player->footStepCounter % 2) != 0) { sfx_play_sound_at_position(SOUND_STEP_NORMAL1, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); } else { sfx_play_sound_at_position(SOUND_STEP_NORMAL2, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); } } playerState->moveTime--; if (playerState->moveTime <= 0) { player->curPos.x = playerState->goalPos.x; player->curPos.z = playerState->goalPos.z; return ApiStatus_DONE2; } return ApiStatus_BLOCK; } API_CALLABLE(CancelablePlayerRunToGoal) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; Actor* player = battleStatus->playerActor; ActorState* playerState = &player->state; f32 currentX, currentZ, goalX, goalZ; if (isInitialCall) { script->functionTemp[0] = FALSE; } if (!script->functionTemp[0]) { player->state.moveTime = evt_get_variable(script, *args++); script->functionTemp[1] = *args++; player->state.curPos.x = player->curPos.x; player->state.curPos.y = player->curPos.y; player->state.curPos.z = player->curPos.z; goalX = player->state.goalPos.x; goalZ = player->state.goalPos.z; currentX = player->state.curPos.x; currentZ = player->state.curPos.z; player->state.angle = atan2(currentX, currentZ, goalX, goalZ); player->state.dist = dist2D(currentX, currentZ, goalX, goalZ); if (player->state.moveTime == 0) { player->state.moveTime = player->state.dist / player->state.speed; player->state.speed += (player->state.dist - (player->state.moveTime * player->state.speed)) / player->state.moveTime; } else { player->state.speed = player->state.dist / player->state.moveTime; } playerState->dist = player->actorTypeData1b[0] + 1; if (playerState->moveTime == 0) { return ApiStatus_DONE2; } script->functionTemp[2] = FALSE; script->functionTemp[3] = 0; script->functionTemp[0] = TRUE; } add_xz_vec3f(&playerState->curPos, playerState->speed, playerState->angle); player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y; player->curPos.z = playerState->curPos.z; if (playerState->speed < 4.0f) { play_movement_dust_effects(0, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); } else { play_movement_dust_effects(1, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); } playerState->dist += playerState->speed; if (playerState->dist > player->actorTypeData1b[0]) { player->footStepCounter++; playerState->dist = 0.0f; if ((player->footStepCounter % 2) != 0) { sfx_play_sound_at_position(SOUND_STEP_NORMAL1, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); } else { sfx_play_sound_at_position(SOUND_STEP_NORMAL2, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); } } if (script->functionTemp[3] > 12) { if (!script->functionTemp[2]) { if (!(battleStatus->curButtonsDown & BUTTON_A)) { script->functionTemp[2] = TRUE; } } if (script->functionTemp[2]) { if (battleStatus->curButtonsPressed & BUTTON_A) { evt_set_variable(script, script->functionTemp[1], 1); return ApiStatus_DONE2; } } } script->functionTemp[3]++; playerState->moveTime--; if (playerState->moveTime > 0) { return ApiStatus_BLOCK; } player->curPos.x = playerState->goalPos.x; player->curPos.z = playerState->goalPos.z; evt_set_variable(script, script->functionTemp[1], 0); return ApiStatus_DONE2; } API_CALLABLE(GetPlayerHP) { evt_set_variable(script, *script->ptrReadPos, gPlayerData.curHP); return ApiStatus_DONE2; } API_CALLABLE(PlayerDamageEnemy) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; s32 hitResultOutVar = *args++; s32 flags; Actor* target; HitResult hitResult; battleStatus->curAttackElement = *args++; battleStatus->curAttackEventSuppression = *args++; battleStatus->curAttackStatus = *args++; battleStatus->curAttackDamage = evt_get_variable(script, *args++); battleStatus->powerBounceCounter = 0; flags = *args++; #if DX_DEBUG_MENU if (dx_debug_is_cheat_enabled(DEBUG_CHEAT_GOD_MODE)) { battleStatus->curAttackDamage = 99; } #endif if ((flags & BS_FLAGS1_INCLUDE_POWER_UPS) && (flags & BS_FLAGS1_TRIGGER_EVENTS)) { gBattleStatus.flags1 |= BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 |= BS_FLAGS1_TRIGGER_EVENTS; } else if (flags & BS_FLAGS1_INCLUDE_POWER_UPS) { gBattleStatus.flags1 |= BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 &= ~BS_FLAGS1_TRIGGER_EVENTS; } else if (flags & BS_FLAGS1_TRIGGER_EVENTS) { gBattleStatus.flags1 &= ~BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 |= BS_FLAGS1_TRIGGER_EVENTS; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 &= ~BS_FLAGS1_TRIGGER_EVENTS; } if (flags & BS_FLAGS1_NICE_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_NICE_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_NICE_HIT; } if (flags & BS_FLAGS1_SUPER_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_SUPER_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_SUPER_HIT; } if (flags & BS_FLAGS1_NO_RATING) { gBattleStatus.flags1 |= BS_FLAGS1_NO_RATING; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_NO_RATING; } if (flags & BS_FLAGS1_FORCE_IMMUNE_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_FORCE_IMMUNE_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_FORCE_IMMUNE_HIT; } target = get_actor(script->owner1.actorID); battleStatus->curTargetID = target->targetActorID; battleStatus->curTargetPart = target->targetPartID; battleStatus->statusChance = battleStatus->curAttackStatus; if (battleStatus->statusChance == STATUS_KEY_NEVER) { battleStatus->statusChance = 0; } battleStatus->statusDuration = (battleStatus->curAttackStatus & 0xF00) >> 8; hitResult = calc_player_damage_enemy(); if (hitResult < 0) { return ApiStatus_FINISH; } evt_set_variable(script, hitResultOutVar, hitResult); if (!does_script_exist_by_ref(script)) { return ApiStatus_FINISH; } return ApiStatus_DONE2; } API_CALLABLE(PlayerPowerBounceEnemy) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; s32 hitResultOutVar = *args++; s32 flags; Actor* target; HitResult hitResult; battleStatus->curAttackElement = *args++; battleStatus->curAttackEventSuppression = *args++; battleStatus->curAttackStatus = *args++; battleStatus->curAttackDamage = evt_get_variable(script, *args++); battleStatus->powerBounceCounter = evt_get_variable(script, *args++); flags = *args++; if ((flags & BS_FLAGS1_INCLUDE_POWER_UPS) && (flags & BS_FLAGS1_TRIGGER_EVENTS)) { gBattleStatus.flags1 |= BS_FLAGS1_INCLUDE_POWER_UPS | BS_FLAGS1_TRIGGER_EVENTS; } else if (flags & BS_FLAGS1_INCLUDE_POWER_UPS) { gBattleStatus.flags1 |= BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 &= ~BS_FLAGS1_TRIGGER_EVENTS; } else if (flags & BS_FLAGS1_TRIGGER_EVENTS) { gBattleStatus.flags1 &= ~BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 |= BS_FLAGS1_TRIGGER_EVENTS; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 &= ~BS_FLAGS1_TRIGGER_EVENTS; } if (flags & BS_FLAGS1_NICE_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_NICE_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_NICE_HIT; } if (flags & BS_FLAGS1_SUPER_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_SUPER_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_SUPER_HIT; } if (flags & BS_FLAGS1_NO_RATING) { gBattleStatus.flags1 |= BS_FLAGS1_NO_RATING; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_NO_RATING; } if (flags & BS_FLAGS1_FORCE_IMMUNE_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_FORCE_IMMUNE_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_FORCE_IMMUNE_HIT; } target = get_actor(script->owner1.actorID); battleStatus->curTargetID = target->targetActorID; battleStatus->curTargetPart = target->targetPartID; battleStatus->statusChance = battleStatus->curAttackStatus; if (battleStatus->statusChance == STATUS_KEY_NEVER) { battleStatus->statusChance = 0; } battleStatus->statusDuration = (battleStatus->curAttackStatus & 0xF00) >> 8; hitResult = calc_player_damage_enemy(); if (hitResult < 0) { return ApiStatus_FINISH; } evt_set_variable(script, hitResultOutVar, hitResult); if (!does_script_exist_by_ref(script)) { return ApiStatus_FINISH; } return ApiStatus_DONE2; } API_CALLABLE(PlayerTestEnemy) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; s32 hitResultOutVar = *args++; s32 flags; Actor* target; HitResult hitResult; battleStatus->curAttackElement = *args++; battleStatus->curAttackEventSuppression = *args++; battleStatus->curAttackStatus = *args++; battleStatus->curAttackDamage = evt_get_variable(script, *args++); battleStatus->powerBounceCounter = 0; flags = *args++; if ((flags & BS_FLAGS1_INCLUDE_POWER_UPS) && (flags & BS_FLAGS1_TRIGGER_EVENTS)) { gBattleStatus.flags1 |= BS_FLAGS1_INCLUDE_POWER_UPS | BS_FLAGS1_TRIGGER_EVENTS; } else if (flags & BS_FLAGS1_INCLUDE_POWER_UPS) { gBattleStatus.flags1 |= BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 &= ~BS_FLAGS1_TRIGGER_EVENTS; } else if (flags & BS_FLAGS1_TRIGGER_EVENTS) { gBattleStatus.flags1 &= ~BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 |= BS_FLAGS1_TRIGGER_EVENTS; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_INCLUDE_POWER_UPS; gBattleStatus.flags1 &= ~BS_FLAGS1_TRIGGER_EVENTS; } if (flags & BS_FLAGS1_NICE_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_NICE_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_NICE_HIT; } if (flags & BS_FLAGS1_SUPER_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_SUPER_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_SUPER_HIT; } if (flags & BS_FLAGS1_NO_RATING) { gBattleStatus.flags1 |= BS_FLAGS1_NO_RATING; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_NO_RATING; } if (flags & BS_FLAGS1_FORCE_IMMUNE_HIT) { gBattleStatus.flags1 |= BS_FLAGS1_FORCE_IMMUNE_HIT; } else { gBattleStatus.flags1 &= ~BS_FLAGS1_FORCE_IMMUNE_HIT; } target = get_actor(script->owner1.actorID); battleStatus->curTargetID = target->targetActorID; battleStatus->curTargetPart = target->targetPartID; battleStatus->statusChance = battleStatus->curAttackStatus; if (battleStatus->statusChance == STATUS_KEY_NEVER) { battleStatus->statusChance = 0; } battleStatus->statusDuration = (battleStatus->curAttackStatus & 0xF00) >> 8; hitResult = calc_player_test_enemy(); if (hitResult < 0) { return ApiStatus_FINISH; } evt_set_variable(script, hitResultOutVar, hitResult); return ApiStatus_DONE2; } API_CALLABLE(DispatchDamagePlayerEvent) { Bytecode* args = script->ptrReadPos; s32 damageAmount = evt_get_variable(script, *args++); if (dispatch_damage_tick_event_player(damageAmount, *args++) < 0) { return ApiStatus_BLOCK; } if (does_script_exist_by_ref(script)) { return ApiStatus_DONE2; } return ApiStatus_BLOCK; } API_CALLABLE(EnablePlayerBlur) { s32 setting = evt_get_variable(script, *script->ptrReadPos); if (setting == ACTOR_BLUR_DISABLE) { disable_player_blur(); } else if (setting == ACTOR_BLUR_ENABLE) { enable_player_blur(); } else { reset_player_blur(); } return ApiStatus_DONE2; } API_CALLABLE(ForceDisablePlayerBlur) { force_disable_player_blur(); return ApiStatus_DONE2; } API_CALLABLE(ForceDisablePlayerBlurImmediately) { force_disable_player_blur_immediately(); return ApiStatus_DONE2; } API_CALLABLE(PlayerBasicJumpToGoal) { BattleStatus* battleStatus = &gBattleStatus; Bytecode* args = script->ptrReadPos; Actor* player = battleStatus->playerActor; ActorState* playerState = &player->state; f32 posX, posY, posZ; f32 goalX, goalZ; f64 accel; enum { BASIC_STATE_00 = 0, BASIC_STATE_01 = 1, BASIC_STATE_02 = 2, BASIC_STATE_03 = 3, }; if (isInitialCall) { player->state.moveTime = evt_get_variable(script, *args++); player->state.moveArcAmplitude = evt_get_variable(script, *args++); switch(player->state.moveArcAmplitude) { default: script->functionTemp[0] = BASIC_STATE_00; break; case PLAYER_BASIC_JUMP_1: script->functionTemp[0] = BASIC_STATE_02; break; } script->functionTemp[1] = 0; } if (script->functionTemp[0] == BASIC_STATE_00) { playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; goalX = playerState->goalPos.x; goalZ = playerState->goalPos.z; posX = playerState->curPos.x; posY = playerState->curPos.y; posZ = playerState->curPos.z; playerState->angle = atan2(posX, posZ, goalX, goalZ); playerState->dist = dist2D(posX, posZ, goalX, goalZ); if (playerState->moveTime == 0) { playerState->moveTime = playerState->dist / playerState->speed; } else { playerState->speed = playerState->dist / playerState->moveTime; } if (playerState->moveTime == 0) { return ApiStatus_DONE2; } playerState->speed = playerState->dist / playerState->moveTime; playerState->velStep.x = (playerState->goalPos.x - playerState->curPos.x) / playerState->moveTime; playerState->velStep.y = (playerState->goalPos.y - playerState->curPos.y) / playerState->moveTime; playerState->velStep.z = (playerState->goalPos.z - playerState->curPos.z) / playerState->moveTime; playerState->acceleration = PI_S / playerState->moveTime; playerState->vel = 0.0f; if (playerState->moveArcAmplitude < PLAYER_BASIC_JUMP_3) { playerState->bounceDivisor = 47.0 + (playerState->dist - 20.0) / 6.0; if (playerState->moveArcAmplitude == PLAYER_BASIC_JUMP_2) { playerState->bounceDivisor *= 1.12; } playerState->unk_24 = 90.0f; playerState->unk_28 = 360 / playerState->moveTime; playerState->unk_18.x = 0.0f; playerState->unk_18.y = 0.0f; accel = playerState->acceleration; playerState->vel += accel + (sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * accel); } else { playerState->bounceDivisor = 47.0 + (playerState->dist - 20.0) / 6.0; if (playerState->moveArcAmplitude == PLAYER_BASIC_JUMP_4) { playerState->bounceDivisor *= 1.25; } playerState->unk_24 = 90.0f; playerState->unk_28 = 360 / playerState->moveTime; playerState->unk_18.x = 0.0f; playerState->unk_18.y = 0.0f; accel = playerState->acceleration; playerState->vel += accel + (sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.8 * accel); } set_actor_anim(0, 0, playerState->animJumpRise); sfx_play_sound_at_position(SOUND_LONG_PLAYER_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); script->functionTemp[0] = BASIC_STATE_01; } switch (script->functionTemp[0]) { case BASIC_STATE_01: if (playerState->vel > PI_S / 2) { set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpFall); } playerState->curPos.x += playerState->velStep.x; playerState->curPos.y += playerState->velStep.y; playerState->curPos.z += playerState->velStep.z; playerState->unk_18.x = player->curPos.y; player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y + (playerState->bounceDivisor * sin_rad(playerState->vel)); player->curPos.z = playerState->curPos.z; if (playerState->goalPos.y > player->curPos.y && playerState->moveTime < 3) { player->curPos.y = playerState->goalPos.y; } playerState->unk_18.y = player->curPos.y; if (playerState->moveArcAmplitude < PLAYER_BASIC_JUMP_3) { accel = playerState->acceleration; playerState->vel += accel + (sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * accel); } else { accel = playerState->acceleration; playerState->vel += accel + (sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.8 * accel); } playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); playerState->moveTime--; if (playerState->moveTime == 0) { player->curPos.y = playerState->goalPos.y; playerState->acceleration = 1.8f; playerState->vel = -(playerState->unk_18.x - playerState->unk_18.y); set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpLand); return ApiStatus_DONE1; } break; case BASIC_STATE_02: if (battleStatus->actionCommandMode == AC_MODE_NOT_LEARNED) { return ApiStatus_DONE2; } playerState->moveTime = 1; playerState->acceleration = 1.8f; playerState->unk_24 = 90.0f; playerState->vel = -(playerState->unk_18.x - playerState->unk_18.y); playerState->bounceDivisor = fabsf(playerState->unk_18.x - playerState->unk_18.y) / 16.5; playerState->unk_28 = 360 / playerState->moveTime; playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; script->functionTemp[0] = BASIC_STATE_03; // fallthrough case BASIC_STATE_03: playerState->curPos.x += (playerState->bounceDivisor * sin_rad(DEG_TO_RAD(playerState->unk_24))) / 33.0; playerState->curPos.y -= (playerState->bounceDivisor * sin_rad(DEG_TO_RAD(playerState->unk_24))); playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y; player->curPos.z = playerState->curPos.z; if (gBattleStatus.flags1 & BS_FLAGS1_2000) { return ApiStatus_DONE2; } playerState->moveTime--; if (playerState->moveTime == 0) { return ApiStatus_DONE1; } break; } return ApiStatus_BLOCK; } API_CALLABLE(PlayerSuperJumpToGoal) { Bytecode* args = script->ptrReadPos; Actor* player = gBattleStatus.playerActor; ActorState* playerState = &player->state; f32 posX, posY, posZ; f32 goalX, goalZ; f32 temp; f64 temp_f20; f64 vel1, vel2; f64 vel3, vel4; f64 vel5, vel6; f64 vel7, vel8; f64 acc1, acc2; f64 acc3, acc4; f64 acc5, acc6; f64 acc7, acc8; enum { SUPER_STATE_00 = 0, SUPER_STATE_01 = 1, SUPER_STATE_02 = 2, SUPER_STATE_10 = 10, SUPER_STATE_11 = 11, SUPER_STATE_20 = 20, SUPER_STATE_21 = 21, }; if (isInitialCall) { player->state.moveTime = evt_get_variable(script, *args++); player->state.moveArcAmplitude = evt_get_variable(script, *args++); switch(player->state.moveArcAmplitude) { default: script->functionTemp[0] = SUPER_STATE_00; break; case PLAYER_SUPER_JUMP_1: case PLAYER_SUPER_JUMP_5: case PLAYER_SUPER_JUMP_6: script->functionTemp[0] = SUPER_STATE_10; break; case PLAYER_SUPER_JUMP_2: script->functionTemp[0] = SUPER_STATE_20; break; } } switch (script->functionTemp[0]) { case SUPER_STATE_00: playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; goalX = playerState->goalPos.x; goalZ = playerState->goalPos.z; posX = playerState->curPos.x; posY = playerState->curPos.y; posZ = playerState->curPos.z; playerState->angle = atan2(posX, posZ, goalX, goalZ); playerState->dist = dist2D(posX, posZ, goalX, goalZ); if (playerState->moveTime == 0) { playerState->moveTime = playerState->dist / playerState->speed; temp = playerState->dist - (playerState->moveTime * playerState->speed); } else { playerState->speed = playerState->dist / playerState->moveTime; temp = playerState->dist - (playerState->moveTime * playerState->speed); } if (playerState->moveTime == 0) { return ApiStatus_DONE2; } playerState->velStep.x = (playerState->goalPos.x - playerState->curPos.x) / playerState->moveTime; playerState->velStep.y = (playerState->goalPos.y - playerState->curPos.y) / playerState->moveTime; playerState->velStep.z = (playerState->goalPos.z - playerState->curPos.z) / playerState->moveTime; playerState->acceleration = (PI_S / 2) / playerState->moveTime; playerState->vel = 0.0f; playerState->speed += temp / playerState->moveTime; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpRise); sfx_play_sound_at_position(SOUND_LONG_PLAYER_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); playerState->unk_24 = 90.0f; playerState->bounceDivisor = 45.0f; playerState->unk_28 = 360 / playerState->moveTime; if (playerState->moveArcAmplitude == PLAYER_SUPER_JUMP_4) { playerState->bounceDivisor = 56.25f; } playerState->unk_18.x = 0.0f; playerState->unk_18.y = 0.0f; if (playerState->moveArcAmplitude == PLAYER_SUPER_JUMP_0) { vel1 = playerState->vel; acc1 = playerState->acceleration; playerState->vel = (vel1 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * acc1) + acc1)); } else { vel2 = playerState->vel; acc2 = playerState->acceleration; playerState->vel = (vel2 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.01 * acc2) + acc2)); } script->functionTemp[0] = SUPER_STATE_01; break; case SUPER_STATE_10: playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; goalX = playerState->goalPos.x; goalZ = playerState->goalPos.z; posX = playerState->curPos.x; posY = playerState->curPos.y; posZ = playerState->curPos.z; playerState->angle = atan2(posX, posZ, goalX, goalZ); playerState->dist = dist2D(posX, posZ, goalX, goalZ); if (playerState->moveTime == 0) { playerState->moveTime = playerState->dist / playerState->speed; temp = playerState->dist - (playerState->moveTime * playerState->speed); } else { playerState->speed = playerState->dist / playerState->moveTime; temp = playerState->dist - (playerState->moveTime * playerState->speed); } if (playerState->moveTime == 0) { return ApiStatus_DONE2; } playerState->velStep.x = (playerState->goalPos.x - playerState->curPos.x) / playerState->moveTime; playerState->velStep.y = (playerState->goalPos.y - playerState->curPos.y) / playerState->moveTime; playerState->velStep.z = (playerState->goalPos.z - playerState->curPos.z) / playerState->moveTime; playerState->vel = (PI_S / 2); playerState->acceleration = (PI_S / 4) / (playerState->moveTime + 1); playerState->speed += temp / playerState->moveTime; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpLand); playerState->unk_24 = 90.0f; playerState->bounceDivisor = 45.0f; playerState->unk_28 = (360 / playerState->moveTime); if (playerState->moveArcAmplitude == PLAYER_SUPER_JUMP_5) { playerState->bounceDivisor = 56.25f; } playerState->unk_18.x = 0.0f; playerState->unk_18.y = 0.0f; if (playerState->moveArcAmplitude == PLAYER_SUPER_JUMP_1) { vel3 = playerState->vel; acc3 = playerState->acceleration; playerState->vel = (vel3 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * acc3) + acc3)); } else { vel4 = playerState->vel; acc4 = playerState->acceleration; playerState->vel = (vel4 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.01 * acc4) + acc4)); } playerState->curPos.y = player->curPos.y - playerState->bounceDivisor; script->functionTemp[0] = SUPER_STATE_11; break; case SUPER_STATE_20: playerState->moveTime = 1; playerState->unk_24 = 90.0f; playerState->bounceDivisor = (fabsf(playerState->unk_18.x - playerState->unk_18.y) / 16.5); playerState->unk_28 = (360 / playerState->moveTime); playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; script->functionTemp[0] = SUPER_STATE_21; break; } switch (script->functionTemp[0]) { case SUPER_STATE_01: if (playerState->moveArcAmplitude == PLAYER_SUPER_JUMP_0) { vel5 = playerState->vel; acc5 = playerState->acceleration; playerState->vel = (vel5 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * acc5) + acc5)); } else { vel6 = playerState->vel; acc6 = playerState->acceleration; playerState->vel = (vel6 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.01 * acc6) + acc6)); } playerState->curPos.x += playerState->velStep.x; playerState->curPos.y += playerState->velStep.y; playerState->curPos.z += playerState->velStep.z; playerState->unk_18.x = player->curPos.y; player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y + (playerState->bounceDivisor * sin_rad(sin_rad(sin_rad(playerState->vel) * (PI_S / 2)) * (PI_S / 2))); player->curPos.z = playerState->curPos.z; playerState->unk_18.y = player->curPos.y; playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); playerState->moveTime--; if (playerState->moveTime == 0) { sfx_play_sound_at_position(SOUND_LONG_PLAYER_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpFall); player->rotPivotOffset.y = 14; player->rot.z -= 66.0f; playerState->moveTime = 7; script->functionTemp[0] = SUPER_STATE_02; } break; case SUPER_STATE_02: player->rotPivotOffset.y = 14; player->rot.z -= 66.0f; playerState->moveTime--; if (playerState->moveTime == 0) { player->rot.z = 0.0f; player->rotPivotOffset.y = 0; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpLand); return ApiStatus_DONE1; } break; case SUPER_STATE_11: playerState->curPos.x += playerState->velStep.x; playerState->curPos.y += playerState->velStep.y; playerState->curPos.z += playerState->velStep.z; playerState->unk_18.x = player->curPos.y; player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y + (playerState->bounceDivisor * sin_rad(playerState->vel)); player->curPos.z = playerState->curPos.z; if (playerState->goalPos.y > player->curPos.y) { player->curPos.y = playerState->goalPos.y; } playerState->unk_18.y = player->curPos.y; if (playerState->moveArcAmplitude == PLAYER_SUPER_JUMP_1) { vel7 = playerState->vel; acc7 = playerState->acceleration; playerState->vel = (vel7 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * acc7) + acc7)); } else { vel8 = playerState->vel; acc8 = playerState->acceleration; playerState->vel = (vel8 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.01 * acc8) + acc8)); } playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); playerState->moveTime--; if (playerState->moveTime == 0) { player->curPos.y = playerState->goalPos.y; set_actor_anim(ACTOR_PLAYER, 0, ANIM_Mario1_SpinFall); return ApiStatus_DONE1; } break; case SUPER_STATE_21: temp_f20 = playerState->curPos.x; temp_f20 += (playerState->bounceDivisor * sin_rad(DEG_TO_RAD(playerState->unk_24))) / 33.0; playerState->curPos.x = temp_f20; playerState->curPos.y -= playerState->bounceDivisor * sin_rad(DEG_TO_RAD(playerState->unk_24)); playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y; player->curPos.z = playerState->curPos.z; if (gBattleStatus.flags1 & BS_FLAGS1_2000) { return ApiStatus_DONE2; } playerState->moveTime--; if (playerState->moveTime == 0) { return ApiStatus_DONE1; } break; } return ApiStatus_BLOCK; } API_CALLABLE(PlayerUltraJumpToGoal) { Bytecode* args = script->ptrReadPos; Actor* player = gBattleStatus.playerActor; ActorState* playerState = &player->state; f32 posX, posY, posZ; f32 goalX, goalZ; f32 speed; f32 temp; f64 temp_f20; f64 temp_f20_2; f64 temp_f20_4; f64 temp_f20_5; f64 temp_f20_6; f64 temp_f20_7; f64 temp_f22; f64 temp_f22_2; f64 temp_f22_3; f64 temp_f22_4; f64 temp_f22_5; f64 temp_f22_6; enum { ULTRA_STATE_00 = 0, ULTRA_STATE_01 = 1, ULTRA_STATE_10 = 10, ULTRA_STATE_11 = 11, ULTRA_STATE_20 = 20, ULTRA_STATE_21 = 21, ULTRA_STATE_30 = 30, ULTRA_STATE_31 = 31, }; if (isInitialCall) { player->state.moveTime = evt_get_variable(script, *args++); player->state.moveArcAmplitude = evt_get_variable(script, *args++); switch(player->state.moveArcAmplitude) { default: case PLAYER_ULTRA_JUMP_0: script->functionTemp[0] = ULTRA_STATE_00; break; case PLAYER_ULTRA_JUMP_1: script->functionTemp[0] = ULTRA_STATE_11; break; case PLAYER_ULTRA_JUMP_2: script->functionTemp[0] = ULTRA_STATE_30; break; case PLAYER_ULTRA_JUMP_3: script->functionTemp[0] = ULTRA_STATE_20; break; case PLAYER_ULTRA_JUMP_4: script->functionTemp[0] = ULTRA_STATE_30; break; } script->functionTemp[1] = 0; } switch (script->functionTemp[0]) { case ULTRA_STATE_00: playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; goalX = playerState->goalPos.x; goalZ = playerState->goalPos.z; posX = playerState->curPos.x; posY = playerState->curPos.y; posZ = playerState->curPos.z; playerState->angle = atan2(posX, posZ, goalX, goalZ); playerState->dist = dist2D(posX, posZ, goalX, goalZ); if (playerState->moveTime == 0) { playerState->moveTime = playerState->dist / playerState->speed; } else { playerState->speed = playerState->dist / playerState->moveTime; } playerState->acceleration = PI_S / playerState->moveTime; playerState->vel = 0.0f; playerState->velStep.x = (playerState->goalPos.x - playerState->curPos.x) / playerState->moveTime; playerState->velStep.y = (playerState->goalPos.y - playerState->curPos.y) / playerState->moveTime; playerState->velStep.z = (playerState->goalPos.z - playerState->curPos.z) / playerState->moveTime; playerState->speed = playerState->dist / playerState->moveTime; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpFall); sfx_play_sound_at_position(SOUND_LONG_PLAYER_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); sfx_play_sound_at_position(SOUND_TORNADO_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); playerState->unk_18.x = 0.0f; playerState->unk_18.y = 0.0f; playerState->unk_24 = 90.0f; temp = playerState->dist; temp -= 20.0; temp /= 6.0; temp += 47.0; playerState->bounceDivisor = temp; temp_f20 = playerState->vel; temp_f22 = playerState->acceleration; playerState->unk_28 = 360 / playerState->moveTime; playerState->vel = temp_f20 + (((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53) * temp_f22) + temp_f22); script->functionTemp[0] = ULTRA_STATE_01; break; case ULTRA_STATE_10: playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; goalX = playerState->goalPos.x; goalZ = playerState->goalPos.z; posX = playerState->curPos.x; posY = playerState->curPos.y; posZ = playerState->curPos.z; playerState->angle = atan2(posX, posZ, goalX, goalZ); playerState->dist = dist2D(posX, posZ, goalX, goalZ); if (playerState->moveTime == 0) { playerState->moveTime = playerState->dist / playerState->speed; temp = playerState->dist - (playerState->moveTime * playerState->speed); } else { speed = playerState->dist / playerState->moveTime; playerState->speed = speed; temp = playerState->dist - (playerState->moveTime * speed); } playerState->acceleration = PI_S / playerState->moveTime; playerState->vel = 0.0f; playerState->velStep.x = (playerState->goalPos.x - playerState->curPos.x) / playerState->moveTime; playerState->velStep.y = (playerState->goalPos.y - playerState->curPos.y) / playerState->moveTime; playerState->velStep.z = (playerState->goalPos.z - playerState->curPos.z) / playerState->moveTime; playerState->speed += temp / playerState->moveTime; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpRise); sfx_play_sound_at_position(SOUND_LONG_PLAYER_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); sfx_play_sound_at_position(SOUND_TORNADO_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); playerState->unk_18.x = 0.0f; playerState->unk_18.y = 0.0f; playerState->unk_24 = 90.0f; temp_f20_2 = playerState->vel; temp_f22_2 = playerState->acceleration; temp = playerState->dist; temp -= 20.0; temp /= 6.0; temp += 47.0; playerState->bounceDivisor = temp; playerState->unk_28 = 360 / playerState->moveTime; playerState->vel = temp_f20_2 + (((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53) * temp_f22_2) + temp_f22_2); script->functionTemp[0] = ULTRA_STATE_11; break; case ULTRA_STATE_20: playerState->moveTime = 1; set_actor_anim(ACTOR_PLAYER, 1, ANIM_Mario1_SpinFall); player->rot.y = 0.0f; playerState->unk_24 = 90.0f; playerState->bounceDivisor = fabsf(playerState->unk_18.x - playerState->unk_18.y) / 16.5; playerState->unk_28 = 360 / playerState->moveTime; playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; script->functionTemp[0] = ULTRA_STATE_21; break; case ULTRA_STATE_30: playerState->curPos.x = player->curPos.x; playerState->curPos.y = player->curPos.y; playerState->curPos.z = player->curPos.z; goalX = playerState->goalPos.x; goalZ = playerState->goalPos.z; posX = playerState->curPos.x; posY = playerState->curPos.y; posZ = playerState->curPos.z; playerState->angle = atan2(posX, posZ, goalX, goalZ); playerState->dist = dist2D(posX, posZ, goalX, goalZ); if (playerState->moveTime == 0) { playerState->moveTime = playerState->dist / playerState->speed; temp = playerState->dist - (playerState->moveTime * playerState->speed); } else { playerState->speed = playerState->dist / playerState->moveTime; temp = playerState->dist - (playerState->moveTime * playerState->speed); } playerState->acceleration = PI_S / (playerState->moveTime + 1); playerState->vel = 0.0f; playerState->velStep.x = (playerState->goalPos.x - playerState->curPos.x) / playerState->moveTime; playerState->velStep.y = (playerState->goalPos.y - playerState->curPos.y) / playerState->moveTime; playerState->velStep.z = (playerState->goalPos.z - playerState->curPos.z) / playerState->moveTime; playerState->speed += temp / playerState->moveTime; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpRise); sfx_play_sound_at_position(SOUND_LONG_PLAYER_JUMP, SOUND_SPACE_DEFAULT, player->curPos.x, player->curPos.y, player->curPos.z); playerState->unk_24 = 90.0f; playerState->unk_28 = 360 / playerState->moveTime; if (playerState->moveArcAmplitude == PLAYER_ULTRA_JUMP_4) { playerState->bounceDivisor = 56.25f; } else { playerState->bounceDivisor = 45.0f; } playerState->unk_18.x = 0.0f; playerState->unk_18.y = 0.0f; temp_f22_3 = playerState->acceleration; playerState->vel += ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * temp_f22_3) + temp_f22_3); script->functionTemp[0] = ULTRA_STATE_31; break; } switch (script->functionTemp[0]) { case ULTRA_STATE_01: temp_f22_4 = playerState->vel; temp_f20_4 = playerState->acceleration; playerState->vel = temp_f22_4 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * temp_f20_4) + temp_f20_4); playerState->curPos.x += playerState->velStep.x; playerState->curPos.y += playerState->velStep.y; playerState->curPos.z += playerState->velStep.z; playerState->unk_18.x = player->curPos.y; player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y + (playerState->bounceDivisor * sin_rad(playerState->vel)); player->curPos.z = playerState->curPos.z; playerState->unk_18.y = player->curPos.y; playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); player->rot.y += 133.0f; player->rot.y = clamp_angle(player->rot.y); if (gBattleStatus.flags1 & BS_FLAGS1_2000) { return ApiStatus_DONE2; } playerState->moveTime--; if (playerState->moveTime == 4) { return ApiStatus_DONE1; } break; case ULTRA_STATE_11: temp_f22_6 = playerState->vel; temp_f20_7 = playerState->acceleration; playerState->vel = temp_f22_6 + ((sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * temp_f20_7) + temp_f20_7); playerState->curPos.x += playerState->velStep.x; playerState->curPos.y += playerState->velStep.y; playerState->curPos.z += playerState->velStep.z; playerState->unk_18.x = player->curPos.y; player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y + (playerState->bounceDivisor * sin_rad(playerState->vel)); player->curPos.z = playerState->curPos.z; if (playerState->goalPos.y > player->curPos.y && playerState->moveTime < 3) { player->curPos.y = playerState->goalPos.y; } playerState->unk_18.y = player->curPos.y; playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpFall); player->rot.y += 133.0f; player->rot.y = clamp_angle(player->rot.y); playerState->moveTime--; if (playerState->moveTime == 0) { playerState->acceleration = 1.8f; playerState->vel = -(playerState->unk_18.x - playerState->unk_18.y); player->curPos.y = playerState->goalPos.y; player->rot.y = 0.0f; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpLand); play_movement_dust_effects(2, player->curPos.x, player->curPos.y, player->curPos.z, player->yaw); return ApiStatus_DONE1; } break; case ULTRA_STATE_21: playerState->curPos.x += (playerState->bounceDivisor * sin_rad(DEG_TO_RAD(playerState->unk_24))) / 33.0; playerState->curPos.y -= playerState->bounceDivisor * sin_rad(DEG_TO_RAD(playerState->unk_24)); playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y; player->curPos.z = playerState->curPos.z; if (gBattleStatus.flags1 & BS_FLAGS1_2000) { return ApiStatus_DONE2; } playerState->moveTime--; if (playerState->moveTime == 0) { return ApiStatus_DONE1; } break; case ULTRA_STATE_31: temp_f20_6 = playerState->acceleration; playerState->vel += (sin_rad(DEG_TO_RAD(playerState->unk_24)) * 0.53 * temp_f20_6) + temp_f20_6; playerState->curPos.x += playerState->velStep.x; playerState->curPos.y += playerState->velStep.y; playerState->curPos.z += playerState->velStep.z; playerState->unk_18.x = player->curPos.y; player->curPos.x = playerState->curPos.x; player->curPos.y = playerState->curPos.y + (playerState->bounceDivisor * sin_rad(playerState->vel)); player->curPos.z = playerState->curPos.z; if (playerState->goalPos.y > player->curPos.y && playerState->moveTime < 3) { player->curPos.y = playerState->goalPos.y; } playerState->unk_18.y = player->curPos.y; playerState->unk_24 += playerState->unk_28; playerState->unk_24 = clamp_angle(playerState->unk_24); set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpFall); player->rot.y += 133.0f; player->rot.y = clamp_angle(player->rot.y); playerState->moveTime--; if (playerState->moveTime == 0) { player->curPos.y = playerState->goalPos.y; player->rot.y = 0.0f; set_actor_anim(ACTOR_PLAYER, 0, playerState->animJumpLand); playerState->acceleration = 1.8f; playerState->vel = -(playerState->unk_18.x - playerState->unk_18.y); return ApiStatus_DONE1; } break; } return ApiStatus_BLOCK; } API_CALLABLE(GetPlayerActionQuality) { Bytecode* args = script->ptrReadPos; s32 outVar = *args++; s32 actionQuality = gBattleStatus.actionQuality; s32 quality = 0; if (actionQuality < 0) { actionQuality = 0; } if (quality < actionQuality) { quality = actionQuality; } evt_set_variable(script, outVar, quality); return ApiStatus_DONE2; } API_CALLABLE(PlayerYieldTurn) { gBattleStatus.flags1 |= BS_FLAGS1_YIELD_TURN; return ApiStatus_DONE2; } API_CALLABLE(DispatchEventPlayer) { dispatch_event_player(evt_get_variable(script, *script->ptrReadPos)); return ApiStatus_DONE2; }
0
0.96351
1
0.96351
game-dev
MEDIA
0.991467
game-dev
0.850182
1
0.850182
DimensionalDevelopment/DimDoors
3,029
common/src/main/java/org/dimdev/dimdoors/rift/targets/PrivatePocketExitTarget.java
package org.dimdev.dimdoors.rift.targets; import net.minecraft.core.Rotations; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; import org.dimdev.dimdoors.api.rift.target.EntityTarget; import org.dimdev.dimdoors.api.util.EntityUtils; import org.dimdev.dimdoors.api.util.Location; import org.dimdev.dimdoors.api.util.RGBA; import org.dimdev.dimdoors.block.entity.RiftBlockEntity; import org.dimdev.dimdoors.world.ModDimensions; import org.dimdev.dimdoors.world.level.registry.DimensionalRegistry; import org.dimdev.dimdoors.world.pocket.PocketDirectory; import org.dimdev.dimdoors.world.pocket.type.Pocket; import java.util.UUID; public class PrivatePocketExitTarget extends VirtualTarget implements EntityTarget { public static final PrivatePocketExitTarget INSTANCE = new PrivatePocketExitTarget(); public static final RGBA COLOR = new RGBA(0, 1, 0, 1); private PrivatePocketExitTarget() { } @Override public boolean receiveEntity(Entity entity, Vec3 relativePos, Rotations relativeAngle, Vec3 relativeVelocity, Location location) { Location destLoc; // TODO: make this recursive UUID uuid = EntityUtils.getOwner(entity).getUUID(); if (uuid != null) { destLoc = DimensionalRegistry.getRiftRegistry().getPrivatePocketExit(uuid); Pocket pocket = DimensionalRegistry.getPrivateRegistry().getPrivatePocket(uuid); if (ModDimensions.isPrivatePocketDimension(this.location.getWorld()) && pocket != null && DimensionalRegistry.getPocketDirectory(pocket.getWorld()).getPocketAt(this.location.pos).equals(pocket)) { DimensionalRegistry.getRiftRegistry().setLastPrivatePocketEntrance(uuid, this.location); // Remember which exit was used for next time the pocket is entered } if (destLoc == null || !(destLoc.getBlockEntity() instanceof RiftBlockEntity)) { if (destLoc == null) { EntityUtils.chat(entity, Component.translatable("rifts.destinations.private_pocket_exit.did_not_use_rift")); } else { EntityUtils.chat(entity, Component.translatable("rifts.destinations.private_pocket_exit.rift_has_closed")); } LimboTarget.INSTANCE.receiveEntity(entity, relativePos, relativeAngle, relativeVelocity, location); return false; } else { ((EntityTarget) destLoc.getBlockEntity()).receiveEntity(entity, relativePos, relativeAngle, relativeVelocity, location); return true; } } else { return false; // Non-player/owned entity tried to escape/leave private pocket } } @Override public void register() { super.register(); PocketDirectory privatePocketRegistry = DimensionalRegistry.getPocketDirectory(this.location.world); Pocket pocket = privatePocketRegistry.getPocketAt(this.location.pos); DimensionalRegistry.getRiftRegistry().addPocketEntrance(pocket, this.location); } @Override public VirtualTargetType<? extends VirtualTarget> getType() { return VirtualTargetType.PRIVATE_POCKET_EXIT.get(); } @Override public VirtualTarget copy() { return this; } }
0
0.923623
1
0.923623
game-dev
MEDIA
0.873261
game-dev
0.891828
1
0.891828
epicweb-dev/data-modeling
1,512
exercises/08.sql/01.solution.sql/epicshop/post-set-playground.js
import os from 'node:os' import path from 'node:path' import { $ } from 'execa' import fsExtra from 'fs-extra' const { EPICSHOP_PLAYGROUND_TIMESTAMP, EPICSHOP_PLAYGROUND_DEST_DIR } = process.env const tempDir = path.join( os.tmpdir(), 'epicshop', 'playground-storage', EPICSHOP_PLAYGROUND_TIMESTAMP, ) const savedDbPath = path.join(tempDir, 'data.db') const savedDbExists = await fsExtra.exists(savedDbPath) if (savedDbExists) { await fsExtra.copy( savedDbPath, path.join(EPICSHOP_PLAYGROUND_DEST_DIR, 'prisma', 'data.db'), ) } const playgroundPrismaSchema = path.join( EPICSHOP_PLAYGROUND_DEST_DIR, 'prisma', 'schema.prisma', ) const savedPrismaClientPath = path.join(tempDir, 'node_modules/.prisma') const savedPrismaClientExists = await fsExtra.exists(savedPrismaClientPath) if (savedPrismaClientExists) { await fsExtra.copy( savedPrismaClientPath, path.join(EPICSHOP_PLAYGROUND_DEST_DIR, 'node_modules/.prisma'), ) } else if (await isFile(playgroundPrismaSchema)) { try { await $({ all: true, cwd: EPICSHOP_PLAYGROUND_DEST_DIR })`prisma generate` console.log('🏗 prisma client generated') } catch (prismaGenerateResult) { console.log(prismaGenerateResult.all) throw new Error(`❌ prisma generate failed when setting playground`) } } await fsExtra.remove(tempDir) await fsExtra.remove(path.join(EPICSHOP_PLAYGROUND_DEST_DIR, 'epicshop')) async function isFile(p) { try { const stat = await fsExtra.stat(p) return stat.isFile() } catch (error) { return false } }
0
0.953115
1
0.953115
game-dev
MEDIA
0.19659
game-dev
0.919456
1
0.919456
nasfadev/store-simulator-game
2,127
Assets/BOXOPHOBIC/Utils/Editor/StyledInspector/StyledRangeOptionsDrawer.cs
// Cristian Pop - https://boxophobic.com/ using UnityEngine; using UnityEditor; namespace Boxophobic.StyledGUI { [CustomPropertyDrawer(typeof(StyledRangeOptions))] public class StyledRangeOptionsAttributeDrawer : PropertyDrawer { StyledRangeOptions a; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { a = (StyledRangeOptions)attribute; GUIStyle styleMid = new GUIStyle(); styleMid.alignment = TextAnchor.MiddleCenter; styleMid.normal.textColor = Color.gray; styleMid.fontSize = 7; if (a.display.Length > 0) { EditorGUI.PropertyField(position, property, label, true); GUILayout.Space(5); } GUILayout.BeginHorizontal(); GUILayout.Space(8); property.floatValue = GUILayout.HorizontalSlider(property.floatValue, a.min, a.max); property.floatValue = Mathf.Clamp(property.floatValue, a.min, a.max); property.floatValue = Mathf.Round(property.floatValue * 1000f) / 1000f; GUILayout.Space(8); GUILayout.EndHorizontal(); #if UNITY_2019_3_OR_NEWER GUILayout.Space(15); #endif GUILayout.BeginHorizontal(); int maxWidth = 20; #if UNITY_2019_3_OR_NEWER maxWidth = 28; #endif for (int i = 0; i < a.options.Length - 1; i++) { GUILayout.Label(a.options[i], styleMid, GUILayout.Width(maxWidth)); GUILayout.Label("", styleMid); } GUILayout.Label(a.options[a.options.Length - 1], styleMid, GUILayout.Width(maxWidth)); GUILayout.EndHorizontal(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { a = (StyledRangeOptions)attribute; if (a.display.Length > 0) { return 18; } else { return -2; } } } }
0
0.908035
1
0.908035
game-dev
MEDIA
0.740161
game-dev
0.923454
1
0.923454
CLB-S/itoc
6,476
itoc.core/Registry/RegistryManager.cs
using ITOC.Core.Item; using ITOC.Core.Registry; namespace ITOC.Core; /// <summary> /// Central manager for all registries in the game. /// Handles registry creation, lookup, and lifecycle management. /// </summary> public class RegistryManager { private static readonly Lazy<RegistryManager> _instance = new(CreateInstance); private readonly Dictionary<Identifier, object> _registries = new(); private readonly ReaderWriterLockSlim _lock = new(); private bool _isRegistryCreationFrozen; /// <summary> /// The singleton instance of the registry manager /// </summary> public static RegistryManager Instance => _instance.Value; /// <summary> /// Whether new registries can be created /// </summary> public bool IsRegistryCreationFrozen => _isRegistryCreationFrozen; /// <summary> /// Built-in registry keys /// </summary> public static class Keys { public static readonly Identifier Blocks = new(Identifier.ItocNamespace, "blocks"); public static readonly Identifier Items = new(Identifier.ItocNamespace, "items"); public static readonly Identifier Biomes = new(Identifier.ItocNamespace, "biomes"); } private RegistryManager() { } private static RegistryManager CreateInstance() { var instance = new RegistryManager(); // Create built-in registries instance.CreateRegistry<Block>(Keys.Blocks); instance.CreateRegistry<IItem>(Keys.Items); instance.CreateRegistry<Biome>(Keys.Biomes); return instance; } /// <summary> /// Creates a new registry with the specified key and type /// </summary> /// <typeparam name="T">The type of content managed by the registry</typeparam> /// <param name="key">The key for the registry</param> /// <returns>The created registry</returns> /// <exception cref="InvalidOperationException">Thrown when registry creation is frozen</exception> /// <exception cref="ArgumentException">Thrown when a registry with the same key already exists</exception> public Registry<T> CreateRegistry<T>(Identifier key) where T : class { if (_isRegistryCreationFrozen) throw new InvalidOperationException("Registry creation is frozen"); _lock.EnterWriteLock(); try { if (_registries.ContainsKey(key)) throw new ArgumentException($"Registry with key {key} already exists"); var registry = new Registry<T>(key); _registries.Add(key, registry); return registry; } finally { _lock.ExitWriteLock(); } } /// <summary> /// Gets a registry by its key /// </summary> /// <typeparam name="T">The type of content managed by the registry</typeparam> /// <param name="key">The key of the registry</param> /// <returns>The registry</returns> /// <exception cref="KeyNotFoundException">Thrown when no registry with the specified key exists</exception> /// <exception cref="InvalidCastException">Thrown when the registry is of a different type</exception> public Registry<T> GetRegistry<T>(Identifier key) where T : class { _lock.EnterReadLock(); try { if (!_registries.TryGetValue(key, out var registry)) throw new KeyNotFoundException($"No registry found with key {key}"); if (registry is Registry<T> typedRegistry) return typedRegistry; throw new InvalidCastException( $"Registry with key {key} is not of type Registry<{typeof(T).Name}>" ); } finally { _lock.ExitReadLock(); } } /// <summary> /// Tries to get a registry by its key /// </summary> /// <typeparam name="T">The type of content managed by the registry</typeparam> /// <param name="key">The key of the registry</param> /// <param name="registry">The registry, if found</param> /// <returns>True if the registry was found, false otherwise</returns> public bool TryGetRegistry<T>(Identifier key, out Registry<T> registry) where T : class { _lock.EnterReadLock(); try { if (_registries.TryGetValue(key, out var obj) && obj is Registry<T> typedRegistry) { registry = typedRegistry; return true; } registry = null; return false; } finally { _lock.ExitReadLock(); } } /// <summary> /// Checks if a registry with the specified key exists /// </summary> /// <param name="key">The key of the registry</param> /// <returns>True if the registry exists, false otherwise</returns> public bool HasRegistry(Identifier key) { _lock.EnterReadLock(); try { return _registries.ContainsKey(key); } finally { _lock.ExitReadLock(); } } /// <summary> /// Gets all registries /// </summary> /// <returns>All registries</returns> public IEnumerable<object> GetAllRegistries() { _lock.EnterReadLock(); try { return _registries.Values.ToList(); } finally { _lock.ExitReadLock(); } } /// <summary> /// Gets all registry keys /// </summary> /// <returns>All registry keys</returns> public IEnumerable<Identifier> GetAllRegistryKeys() { _lock.EnterReadLock(); try { return _registries.Keys.ToList(); } finally { _lock.ExitReadLock(); } } /// <summary> /// Freezes registry creation, preventing new registries from being created /// </summary> public void FreezeRegistryCreation() => _isRegistryCreationFrozen = true; /// <summary> /// Freezes all registries, preventing new entries from being registered /// </summary> public void FreezeAllRegistries() { _lock.EnterReadLock(); try { foreach (var registry in _registries.Values) { if (registry is IFreezable freezable) freezable.Freeze(); } } finally { _lock.ExitReadLock(); } } }
0
0.834059
1
0.834059
game-dev
MEDIA
0.544374
game-dev
0.915501
1
0.915501
dewxin/PlatformGame01
10,149
Assets/_ThirdParty/com.unity.textmeshpro@3.0.6/Scripts/Editor/TMP_SpriteAssetImporter.cs
using System; using UnityEngine; using UnityEngine.TextCore; using UnityEditor; using System.IO; using System.Collections.Generic; using TMPro.EditorUtilities; using TMPro.SpriteAssetUtilities; namespace TMPro { public class TMP_SpriteAssetImporter : EditorWindow { // Create Sprite Asset Editor Window [MenuItem("Window/TextMeshPro/Sprite Importer", false, 2026)] public static void ShowFontAtlasCreatorWindow() { var window = GetWindow<TMP_SpriteAssetImporter>(); window.titleContent = new GUIContent("Sprite Importer"); window.Focus(); } Texture2D m_SpriteAtlas; SpriteAssetImportFormats m_SpriteDataFormat = SpriteAssetImportFormats.TexturePackerJsonArray; TextAsset m_JsonFile; string m_CreationFeedback; TMP_SpriteAsset m_SpriteAsset; /// <summary> /// /// </summary> void OnEnable() { // Set Editor Window Size SetEditorWindowSize(); } /// <summary> /// /// </summary> public void OnGUI() { DrawEditorPanel(); } /// <summary> /// /// </summary> private void OnDisable() { // Clean up sprite asset object that may have been created and not saved. if (m_SpriteAsset != null && !EditorUtility.IsPersistent(m_SpriteAsset)) DestroyImmediate(m_SpriteAsset); } /// <summary> /// /// </summary> void DrawEditorPanel() { // label GUILayout.Label("Import Settings", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); // Sprite Texture Selection m_JsonFile = EditorGUILayout.ObjectField("Sprite Data Source", m_JsonFile, typeof(TextAsset), false) as TextAsset; m_SpriteDataFormat = (SpriteAssetImportFormats)EditorGUILayout.EnumPopup("Import Format", m_SpriteDataFormat); // Sprite Texture Selection m_SpriteAtlas = EditorGUILayout.ObjectField("Sprite Texture Atlas", m_SpriteAtlas, typeof(Texture2D), false) as Texture2D; if (EditorGUI.EndChangeCheck()) { m_CreationFeedback = string.Empty; } GUILayout.Space(10); GUI.enabled = m_JsonFile != null && m_SpriteAtlas != null && m_SpriteDataFormat != SpriteAssetImportFormats.None; // Create Sprite Asset if (GUILayout.Button("Create Sprite Asset")) { m_CreationFeedback = string.Empty; // Clean up sprite asset object that may have been previously created. if (m_SpriteAsset != null && !EditorUtility.IsPersistent(m_SpriteAsset)) DestroyImmediate(m_SpriteAsset); // Read json data file if (m_JsonFile != null) { switch (m_SpriteDataFormat) { case SpriteAssetImportFormats.TexturePackerJsonArray: TexturePacker_JsonArray.SpriteDataObject jsonData = null; try { jsonData = JsonUtility.FromJson<TexturePacker_JsonArray.SpriteDataObject>(m_JsonFile.text); } catch { m_CreationFeedback = "The Sprite Data Source file [" + m_JsonFile.name + "] appears to be invalid or incorrectly formatted."; } if (jsonData != null && jsonData.frames != null && jsonData.frames.Count > 0) { int spriteCount = jsonData.frames.Count; // Update import results m_CreationFeedback = "<b>Import Results</b>\n--------------------\n"; m_CreationFeedback += "<color=#C0ffff><b>" + spriteCount + "</b></color> Sprites were imported from file."; // Create new Sprite Asset m_SpriteAsset = CreateInstance<TMP_SpriteAsset>(); // Assign sprite sheet / atlas texture to sprite asset m_SpriteAsset.spriteSheet = m_SpriteAtlas; List<TMP_SpriteGlyph> spriteGlyphTable = new List<TMP_SpriteGlyph>(); List<TMP_SpriteCharacter> spriteCharacterTable = new List<TMP_SpriteCharacter>(); PopulateSpriteTables(jsonData, spriteCharacterTable, spriteGlyphTable); m_SpriteAsset.spriteCharacterTable = spriteCharacterTable; m_SpriteAsset.spriteGlyphTable = spriteGlyphTable; } break; } } } GUI.enabled = true; // Creation Feedback GUILayout.Space(5); GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(60)); { EditorGUILayout.TextArea(m_CreationFeedback, TMP_UIStyleManager.label); } GUILayout.EndVertical(); GUILayout.Space(5); GUI.enabled = m_JsonFile != null && m_SpriteAtlas && m_SpriteAsset != null; if (GUILayout.Button("Save Sprite Asset") && m_JsonFile != null) { string filePath = EditorUtility.SaveFilePanel("Save Sprite Asset File", new FileInfo(AssetDatabase.GetAssetPath(m_JsonFile)).DirectoryName, m_JsonFile.name, "asset"); if (filePath.Length == 0) return; SaveSpriteAsset(filePath); } GUI.enabled = true; } /// <summary> /// /// </summary> /// <param name="spriteDataObject"></param> /// <param name="spriteCharacterTable"></param> /// <param name="spriteGlyphTable"></param> private static void PopulateSpriteTables(TexturePacker_JsonArray.SpriteDataObject spriteDataObject, List<TMP_SpriteCharacter> spriteCharacterTable, List<TMP_SpriteGlyph> spriteGlyphTable) { List<TexturePacker_JsonArray.Frame> importedSprites = spriteDataObject.frames; float atlasHeight = spriteDataObject.meta.size.h; for (int i = 0; i < importedSprites.Count; i++) { TexturePacker_JsonArray.Frame spriteData = importedSprites[i]; TMP_SpriteGlyph spriteGlyph = new TMP_SpriteGlyph(); spriteGlyph.index = (uint)i; spriteGlyph.metrics = new GlyphMetrics((int)spriteData.frame.w, (int)spriteData.frame.h, -spriteData.frame.w * spriteData.pivot.x, spriteData.frame.h * spriteData.pivot.y, (int)spriteData.frame.w); spriteGlyph.glyphRect = new GlyphRect((int)spriteData.frame.x, (int)(atlasHeight - spriteData.frame.h - spriteData.frame.y), (int)spriteData.frame.w, (int)spriteData.frame.h); spriteGlyph.scale = 1.0f; spriteGlyphTable.Add(spriteGlyph); TMP_SpriteCharacter spriteCharacter = new TMP_SpriteCharacter(0, spriteGlyph); spriteCharacter.name = spriteData.filename.Split('.')[0]; spriteCharacter.unicode = 0xFFFE; spriteCharacter.scale = 1.0f; spriteCharacterTable.Add(spriteCharacter); } } /// <summary> /// /// </summary> /// <param name="filePath"></param> void SaveSpriteAsset(string filePath) { filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath. string dataPath = Application.dataPath; if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1) { Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\""); return; } string relativeAssetPath = filePath.Substring(dataPath.Length - 6); string dirName = Path.GetDirectoryName(relativeAssetPath); string fileName = Path.GetFileNameWithoutExtension(relativeAssetPath); string pathNoExt = dirName + "/" + fileName; // Save Sprite Asset AssetDatabase.CreateAsset(m_SpriteAsset, pathNoExt + ".asset"); // Set version number m_SpriteAsset.version = "1.1.0"; // Compute the hash code for the sprite asset. m_SpriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(m_SpriteAsset.name); // Add new default material for sprite asset. AddDefaultMaterial(m_SpriteAsset); } /// <summary> /// Create and add new default material to sprite asset. /// </summary> /// <param name="spriteAsset"></param> static void AddDefaultMaterial(TMP_SpriteAsset spriteAsset) { Shader shader = Shader.Find("TextMeshPro/Sprite"); Material material = new Material(shader); material.SetTexture(ShaderUtilities.ID_MainTex, spriteAsset.spriteSheet); spriteAsset.material = material; material.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(material, spriteAsset); } /// <summary> /// Limits the minimum size of the editor window. /// </summary> void SetEditorWindowSize() { EditorWindow editorWindow = this; Vector2 currentWindowSize = editorWindow.minSize; editorWindow.minSize = new Vector2(Mathf.Max(230, currentWindowSize.x), Mathf.Max(300, currentWindowSize.y)); } } }
0
0.860582
1
0.860582
game-dev
MEDIA
0.800524
game-dev,graphics-rendering
0.950836
1
0.950836
long-war-2/lwotc
9,476
LongWarOfTheChosen/Src/LW_Overhaul/Classes/UISquadListItem.uc
//--------------------------------------------------------------------------------------- // FILE: UISquadListItem.uc // AUTHOR: Amineri / Pavonis Interactive // // PURPOSE: An individual item within the squad list //--------------------------------------------------------------------------------------- class UISquadListItem extends UIPanel config(LW_Overhaul); // the list that owns this item var UIList List; // BG is created as this panel //var UIBGBox BG; var UIButton ButtonBG; var name ButtonBGLibID; var UIBGBox ButtonFill; // used to handle click-and-drag weirdness with UIButton var UIImage SquadImage; var UIScrollingTextField SquadNameText; var UIScrollingTextField SquadCovertnessText; var UIScrollingTextField SquadStatusText; var UIList ClassIconList; var string SquadName; var StateObjectReference SquadRef; // reference to a XComGameState_LWPersistentSquad var localized string sSquadOnMission, sSquadAvailable, sCovertness; simulated function UISquadListItem InitSquadListItem(StateObjectReference initSquadRef) { SquadRef = initSquadRef; InitPanel(); List = UIList(GetParent(class'UIList')); // list items must be owned by UIList.ItemContainer if(List == none) { ScriptTrace(); `warn("UI list items must be owned by UIList.ItemContainer"); } SetWidth(List.width); //Spawn in the init, so that set up functions have access to its data. ButtonBG = Spawn(class'UIButton', self); ButtonBG.bAnimateOnInit = false; ButtonBG.bIsNavigable = false; ButtonBG.InitButton(ButtonBGLibID); ButtonBG.SetSize(width, height); //Spawn a filler box to prevent button from being messed up on click/drag ButtonFill = Spawn(class'UIBGBox', self); ButtonFill.bAnimateOnInit = false; ButtonFill.InitBG('DarkEventFill', 0, 0, width, height, eUIState_Normal); SquadImage = Spawn(class'UIImage', self); SquadImage.bAnimateOnInit = false; SquadImage.InitImage().SetSize(60, 60).SetPosition(12, 10); SquadNameText = Spawn(class'UIScrollingTextField', self); SquadNameText.bAnimateOnInit = false; SquadNameText.InitScrollingText(, "Squad Name", 400, 80, 1, true); SquadStatusText = Spawn(class'UIScrollingTextField', self); SquadStatusText.bAnimateOnInit = false; SquadStatusText.InitScrollingText(, "STATUS", 130, 510, 10, false); SquadCovertnessText = Spawn(class'UIScrollingTextField', self); SquadCovertnessText.bAnimateOnInit = false; SquadCovertnessText.InitScrollingText(, "", 130, 510, 44, false); ClassIconList = Spawn(class'UIList', self); ClassIconList.bAnimateOnInit = false; ClassIconList.ItemPadding = -3; ClassIconList.InitList(, 80, 38, 460, 40, true /*horizontal*/, false /*AddBG*/); return self; } simulated function Update() { local XComGameState_LWPersistentSquad SquadState; local array<XComGameState_Unit> arrUnitStates; local XComGameState_Unit UnitState; //local XGParamTag ParamTag; //local string CovertnessString; local int idx, StartIndex; local UISquadClassItem ClassItem; //local UIImage ClassIcon; SquadState = XComGameState_LWPersistentSquad(`XCOMHISTORY.GetGameStateForObjectID(SquadRef.ObjectID)); SquadImage.LoadImage(SquadState.GetSquadImagePath()); SquadName = SquadState.sSquadName; SquadNameText.SetTitle(SquadName, bIsFocused, true); if(SquadState.IsDeployedOnMission()) SquadStatusText.SetHTMLText(class'UIUtilities_Text'.static.GetColoredText(sSquadOnMission, eUIState_Warning,,"RIGHT")); else SquadStatusText.SetHTMLText(class'UIUtilities_Text'.static.GetColoredText(sSquadAvailable, eUIState_Good,,"RIGHT")); // JL removed 10/27 because this is often bugged and not providing useful information //ParamTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam")); //ParamTag.IntValue0 = Max(0, SquadState.GetSquadCovertness(SquadState.SquadSoldiers)); //CovertnessString = `XEXPAND.ExpandString(sCovertness); //SquadCovertnessText.SetHTMLText(class'UIUtilities_Text'.static.AlignRight(CovertnessString)); arrUnitStates = SquadState.GetSoldiers(); for(idx = 0; idx < arrUnitStates.Length; idx ++) // add icons for permanent soldiers { UnitState = arrUnitStates[idx]; ClassItem = UISquadClassItem(ClassIconList.GetItem(idx)); if(ClassItem == none) { ClassItem = UISquadClassItem(ClassIconList.CreateItem(class'UISquadClassItem')); ClassItem.bAnimateOnInit = false; ClassItem.InitSquadClassItem(); ClassItem.SetSize(38, 38); } ClassItem.LoadClassImage(UnitState.GetSoldierClassTemplate().IconImage); ClassItem.SetAlpha(GetClassIconAlphaStatus(UnitState, SquadState)); // add dimming effect for unavailable soldiers ClassItem.ShowTempIcon(false); ClassItem.Show(); //TODO : set up tooltips with soldier name on each class icon } StartIndex = idx; arrUnitStates = SquadState.GetTempSoldiers(); for(idx = StartIndex; idx < StartIndex + arrUnitStates.Length; idx ++) // add icons for temporary soldiers { UnitState = arrUnitStates[idx-StartIndex]; ClassItem = UISquadClassItem(ClassIconList.GetItem(idx)); if(ClassItem == none) { ClassItem = UISquadClassItem(ClassIconList.CreateItem(class'UISquadClassItem')); ClassItem.bAnimateOnInit = false; ClassItem.InitSquadClassItem(); ClassItem.SetSize(38, 38); } ClassItem.LoadClassImage(UnitState.GetSoldierClassTemplate().IconImage); ClassItem.SetAlpha(GetClassIconAlphaStatus(UnitState, SquadState)); // add dimming effect for unavailable soldiers ClassItem.ShowTempIcon(true); ClassItem.Show(); //TODO : set up tooltips with soldier name on each class icon } StartIndex = idx; // hide any additional icons if(ClassIconList.GetItemCount() > StartIndex) { for(idx = StartIndex; idx < ClassIconList.GetItemCount(); idx++) { ClassItem = UISquadClassItem(ClassIconList.GetItem(idx)); ClassItem.Hide(); } } if (ClassIconList.GetItemCount() > 13) { ClassIconList.ProcessMouseEvents(ClassIconList.OnChildMouseEvent); } if (bIsFocused) ButtonFill.Hide(); //SetBGColor("cyan_highlight"); else { ButtonFill.SetBGColor("cyan"); ButtonFill.Show(); } } simulated function int GetClassIconAlphaStatus(XComGameState_Unit UnitState, XComGameState_LWPersistentSquad SquadState) { // Dim the icon if the squad is on-mission and this soldier isn't on the mission, regardless of their actual status. if (SquadState.IsDeployedOnMission() && !SquadState.IsSoldierOnMission(UnitState.GetReference())) return 30; // Otherwise set the status by unit status. switch(UnitState.GetStatus()) { case eStatus_Active: if (SquadState.bOnMission && SquadState.IsSoldierTemporary(UnitState.GetReference())) return 50; else return 100; case eStatus_CovertAction: // Ensure Liaisons dimmed when viewing a squad so they appear unavailable return `LWOUTPOSTMGR.IsUnitAHavenLiaison(UnitState.GetReference()) ? 50 : 100; case eStatus_PsiTraining: case eStatus_PsiTesting: case eStatus_Training: case eStatus_Healing: case eStatus_Dead: default: return 50; } } simulated function OnReceiveFocus() { //ButtonFill.SetBGColor("cyan_highlight"); ButtonFill.Hide(); SquadNameText.SetTitle(SquadName, true, true); SquadStatusText.ShowShadow(); SquadCovertnessText.ShowShadow(); super.OnReceiveFocus(); } simulated function OnLoseFocus() { ButtonFill.SetBGColor("cyan"); ButtonFill.Show(); SquadNameText.SetTitle(SquadName, false, true); SquadStatusText.HideShadow(); SquadCovertnessText.HideShadow(); super.OnLoseFocus(); } //override the UIPanel OnMouseEvent to enable sticky highlighting of selected squad simulated function OnMouseEvent(int cmd, array<string> args) { switch( cmd ) { case class'UIUtilities_Input'.const.FXS_L_MOUSE_UP: `SOUNDMGR.PlaySoundEvent("Generic_Mouse_Click"); if( List.HasItem(self) ) { List.SetSelectedIndex(List.GetItemIndex(self)); if(List.OnItemClicked != none) List.OnItemClicked(List, List.SelectedIndex); } break; case class'UIUtilities_Input'.const.FXS_L_MOUSE_UP_DELAYED: if( `XENGINE.m_SteamControllerManager.IsSteamControllerActive() ) { if( List.HasItem(self) ) { List.SetSelectedIndex(List.GetItemIndex(self)); if(List.OnItemClicked != none) List.OnItemClicked(List, List.SelectedIndex); } } break; case class'UIUtilities_Input'.const.FXS_L_MOUSE_DOUBLE_UP: `SOUNDMGR.PlaySoundEvent("Generic_Mouse_Click"); if( List.HasItem(self) ) { List.SetSelectedIndex(List.GetItemIndex(self)); if(List.OnItemDoubleClicked != none) List.OnItemDoubleClicked(List, List.SelectedIndex); } break; case class'UIUtilities_Input'.const.FXS_L_MOUSE_IN: case class'UIUtilities_Input'.const.FXS_L_MOUSE_OVER: case class'UIUtilities_Input'.const.FXS_L_MOUSE_DRAG_OVER: `SOUNDMGR.PlaySoundEvent("Play_Mouseover"); //OnReceiveFocus(); break; case class'UIUtilities_Input'.const.FXS_L_MOUSE_OUT: case class'UIUtilities_Input'.const.FXS_L_MOUSE_DRAG_OUT: case class'UIUtilities_Input'.const.FXS_L_MOUSE_RELEASE_OUTSIDE: //OnLoseFocus(); break; case class'UIUtilities_Input'.const.FXS_MOUSE_SCROLL_DOWN: if( List.Scrollbar != none ) List.Scrollbar.OnMouseScrollEvent(1); break; case class'UIUtilities_Input'.const.FXS_MOUSE_SCROLL_UP: if( List.Scrollbar != none ) List.Scrollbar.OnMouseScrollEvent(-1); break; } if( OnMouseEventDelegate != none ) OnMouseEventDelegate(self, cmd); } defaultproperties { ButtonBGLibID = "theButton"; // in flash //width = 667; height = 81; bProcessesMouseEvents = true; //bIsNavigable = true; bAnimateOnInit = false; }
0
0.825633
1
0.825633
game-dev
MEDIA
0.927821
game-dev
0.947345
1
0.947345
lucasctnh/nodebook
3,536
Assets/NaughtyAttributes/Scripts/Editor/PropertyDrawers/SortingLayerPropertyDrawer.cs
using UnityEngine; using UnityEditor; using System; using System.Reflection; namespace NaughtyAttributes.Editor { [CustomPropertyDrawer(typeof(SortingLayerAttribute))] public class SortingLayerPropertyDrawer : PropertyDrawerBase { private const string TypeWarningMessage = "{0} must be an int or a string"; protected override float GetPropertyHeight_Internal(SerializedProperty property, GUIContent label) { bool validPropertyType = property.propertyType == SerializedPropertyType.String || property.propertyType == SerializedPropertyType.Integer; return validPropertyType ? GetPropertyHeight(property) : GetPropertyHeight(property) + GetHelpBoxHeight(); } protected override void OnGUI_Internal(Rect rect, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(rect, label, property); switch (property.propertyType) { case SerializedPropertyType.String: DrawPropertyForString(rect, property, label, GetLayers()); break; case SerializedPropertyType.Integer: DrawPropertyForInt(rect, property, label, GetLayers()); break; default: string message = string.Format(TypeWarningMessage, property.name); DrawDefaultPropertyAndHelpBox(rect, property, message, MessageType.Warning); break; } EditorGUI.EndProperty(); } private string[] GetLayers() { Type internalEditorUtilityType = typeof(UnityEditorInternal.InternalEditorUtility); PropertyInfo sortingLayersProperty = internalEditorUtilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic); return (string[])sortingLayersProperty.GetValue(null, new object[0]); } private static void DrawPropertyForString(Rect rect, SerializedProperty property, GUIContent label, string[] layers) { int index = IndexOf(layers, property.stringValue); int newIndex = EditorGUI.Popup(rect, label.text, index, layers); string newLayer = layers[newIndex]; if (!property.stringValue.Equals(newLayer, StringComparison.Ordinal)) { property.stringValue = layers[newIndex]; } } private static void DrawPropertyForInt(Rect rect, SerializedProperty property, GUIContent label, string[] layers) { int index = 0; string layerName = SortingLayer.IDToName(property.intValue); for (int i = 0; i < layers.Length; i++) { if (layerName.Equals(layers[i], StringComparison.Ordinal)) { index = i; break; } } int newIndex = EditorGUI.Popup(rect, label.text, index, layers); string newLayerName = layers[newIndex]; int newLayerNumber = SortingLayer.NameToID(newLayerName); if (property.intValue != newLayerNumber) { property.intValue = newLayerNumber; } } private static int IndexOf(string[] layers, string layer) { var index = Array.IndexOf(layers, layer); return Mathf.Clamp(index, 0, layers.Length - 1); } } }
0
0.900127
1
0.900127
game-dev
MEDIA
0.765197
game-dev
0.981548
1
0.981548
tx00100xt/SeriousSamClassic-VK
6,089
SamTSE/Sources/Engine/Ska/smcScan.l
%option prefix="engine_ska_yy" %{ /* Copyright (c) 2002-2012 Croteam Ltd. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <Engine/Base/CTString.h> #include <Engine/Base/CTString.inl> #include <Engine/Base/FileName.h> #include <Engine/Base/ErrorReporting.h> #include <Engine/Templates/DynamicStackArray.cpp> #include "ParsingSmbs.h" #include "smcPars.h" extern CTFileName _fnmApplicationPath; YYSTYPE engine_ska_yylval; #ifdef __cplusplus extern "C" { int engine_ska_yywrap(void); } #endif int engine_ska_yywrap(void) { // no more buffers return 1; }; // declarations for recursive SMC script parsing struct BufferStackEntry { YY_BUFFER_STATE bse_bs; const char *bse_strName; const char *bse_strContents; int bse_iLineCt; BOOL bse_bParserEnd; }; static BufferStackEntry _abseBufferStack[SMC_MAX_INCLUDE_LEVEL]; static int _ibsBufferStackTop = -1; void SMCPushBuffer(const char *strName, const char *strBuffer, BOOL bParserEnd) { _ibsBufferStackTop++; _abseBufferStack[_ibsBufferStackTop].bse_strContents = strdup(strBuffer); _abseBufferStack[_ibsBufferStackTop].bse_strName = strdup(strName); _abseBufferStack[_ibsBufferStackTop].bse_iLineCt = 1; _abseBufferStack[_ibsBufferStackTop].bse_bParserEnd = bParserEnd; _abseBufferStack[_ibsBufferStackTop].bse_bs = engine_ska_yy_scan_string((char*)(const char*)strBuffer); engine_ska_yy_switch_to_buffer(_abseBufferStack[_ibsBufferStackTop].bse_bs); } BOOL SMCPopBuffer(void) { engine_ska_yy_delete_buffer( _abseBufferStack[_ibsBufferStackTop].bse_bs); free((void*)_abseBufferStack[_ibsBufferStackTop].bse_strName); free((void*)_abseBufferStack[_ibsBufferStackTop].bse_strContents); BOOL bParserEnd = _abseBufferStack[_ibsBufferStackTop].bse_bParserEnd; _ibsBufferStackTop--; if (_ibsBufferStackTop>=0) { engine_ska_yy_switch_to_buffer(_abseBufferStack[_ibsBufferStackTop].bse_bs); } return bParserEnd; } const char *SMCGetBufferName(void) { return _abseBufferStack[_ibsBufferStackTop].bse_strName; } int SMCGetBufferLineNumber(void) { return _abseBufferStack[_ibsBufferStackTop].bse_iLineCt; } int SMCGetBufferStackDepth(void) { return _ibsBufferStackTop; } const char *SMCGetBufferContents(void) { return _abseBufferStack[_ibsBufferStackTop].bse_strContents; } void SMCCountOneLine(void) { _abseBufferStack[_ibsBufferStackTop].bse_iLineCt++; } %} %x COMMENT %x INCLUDE DIGIT [0-9] HEXDIGIT [0-9A-Fa-f] DOUBLEQUOTE \" STRINGCONTENT ([^\"]|(\\\")) NONEXP_FLT ({DIGIT}+"."{DIGIT}*) EXP_FLT (({DIGIT}+("."({DIGIT}*)?)?)("E"|"e")("+"|"-")?{DIGIT}+) %% "#INCLUDE" BEGIN(INCLUDE); "SE_SMC" { return(k_SE_SMC); } "SE_END" { return(k_SE_END); } "TFNM" { return(k_TFNM); } "NAME" { return(k_NAME); } "MESH" { return(k_MESH); } "SKELETON" { return(k_SKELETON);} "ANIMSET" { return(k_ANIMSET);} "ANIMATION" { return(K_ANIMATION);} "TEXTURES" { return(k_TEXTURES);} "PARENTBONE" { return(k_PARENTBONE);} "OFFSET" { return(k_OFFSET);} "COLISION" { return(k_COLISION);} "ANIMSPEED" { return(k_ANIMSPEED);} "COLOR" { return(k_COLOR);} "ALLFRAMESBBOX" { return(k_ALLFRAMESBBOX);} <INCLUDE>[ \t]*"\"" /* eat the whitespace */ <INCLUDE>[^"\""]*"\"" { /* got the include file name */ if (SMCGetBufferStackDepth() >= SMC_MAX_INCLUDE_LEVEL) { ThrowF_t("File '%s' line %d\nIncludes nested too deeply '%s'",SMCGetBufferName(), SMCGetBufferLineNumber(),yytext); } char strFileName[256]; strcpy(strFileName, yytext); strFileName[strlen(strFileName)-1] = 0; CTString strIncludeFile; try { strIncludeFile.Load_t(CTString(strFileName)); SMCPushBuffer(strFileName, strIncludeFile, FALSE); } catch (const char *strError) { (void)strError; ThrowF_t("File '%s'\n Could not open '%s' (line %d)",SMCGetBufferName(), strFileName, SMCGetBufferLineNumber()); } BEGIN(INITIAL); } <INCLUDE>. { /* something unrecognized inside include statement */ BEGIN(INITIAL); ThrowF_t("File '%s'\n Wrong syntax for include statement",SMCGetBufferName()); } <<EOF>> { if (SMCPopBuffer()) { yyterminate(); } } /* single character operators and punctuations */ ";"|","|"{"|"}" { return(yytext[0]);} /* constants */ "-"?{DIGIT}+ { engine_ska_yylval.i = atoi(yytext); return(c_int); } "0x"{HEXDIGIT}+ { engine_ska_yylval.i = strtoul(yytext+2, NULL, 16); return(c_int);} "-"?{NONEXP_FLT}("f"|"F")? { engine_ska_yylval.f = (float) atof(yytext); return(c_float); } "-"?{EXP_FLT}("f"|"F")? { engine_ska_yylval.f = (float) atof(yytext); return(c_float); } "\""{STRINGCONTENT}*"\"" { char *strNew; // remove double-quotes yytext[strlen(yytext)-1] = 0; strNew = yytext+1; engine_ska_yylval.str = (const char*)strNew; return(c_string); } /* eat up comments */ "/*" { BEGIN(COMMENT); } <COMMENT>"* /" { BEGIN(INITIAL); } <COMMENT>. {} "//"[^\n]*\n { SMCCountOneLine(); } /* eat up whitespace */ [ \t]+ { } /* eat up linefeeds and count lines in all conditions */ <*>\n { SMCCountOneLine();; } /* for all unrecognized characters */ . { // report an error ThrowF_t("File '%s'\n Unrecognized character '%c' (line %d)", SMCGetBufferName(), yytext[0], SMCGetBufferLineNumber()); //ThrowF_t("Unrecognized character '%c' in line %d)", yytext[0], _yy_iLine ); } %%
0
0.919878
1
0.919878
game-dev
MEDIA
0.154919
game-dev
0.918736
1
0.918736
magefree/mage
3,463
Mage.Tests/src/test/java/org/mage/test/cards/single/mat/NahiriForgedInFuryTest.java
package org.mage.test.cards.single.mat; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author correl */ public class NahiriForgedInFuryTest extends CardTestPlayerBase { /** * {@link mage.cards.n.NahiriForgedInFury} {4}{R}{W} * Legendary Creature - Kor Artificer * * Affinity for Equipment * * Whenever an equipped creature you control attacks, exile the top card of * your library. You may play that card this turn. You may cast Equipment * spells this way without paying their mana costs. */ private static final String nahiri = "Nahiri, Forged in Fury"; private final String boots = "Swiftfoot Boots"; private final String cleaver = "The Reaver Cleaver"; private final String giant = "Hill Giant"; private final String greaves = "Lightning Greaves"; private final String lions = "Savannah Lions"; private final String sword = "Sword of Feast and Famine"; @Test public void test_CostReducedByEquipment() { // Nahiri in hand, four equipment in play, and enough to pay RW addCard(Zone.HAND, playerA, nahiri); addCard(Zone.BATTLEFIELD, playerA, "Mountain", 1); addCard(Zone.BATTLEFIELD, playerA, "Plains", 1); addCard(Zone.BATTLEFIELD, playerA, boots); addCard(Zone.BATTLEFIELD, playerA, cleaver); addCard(Zone.BATTLEFIELD, playerA, greaves); addCard(Zone.BATTLEFIELD, playerA, sword); // Cast for RW (Reduced by 4) castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, nahiri); setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); } @Test public void test_EquippedAttackTriggers() { addCard(Zone.BATTLEFIELD, playerA, "Mountain", 1); addCard(Zone.BATTLEFIELD, playerA, nahiri); addCard(Zone.BATTLEFIELD, playerA, lions); addCard(Zone.BATTLEFIELD, playerA, giant); addCard(Zone.BATTLEFIELD, playerA, boots); addCard(Zone.BATTLEFIELD, playerA, greaves); activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Equip {0}", lions); waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN); activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Equip {1}", giant); // Attack with three creatures, two of which are equipped attack(1, playerA, nahiri); attack(1, playerA, lions); attack(1, playerA, giant); // Order the 2 Nahiri triggers setChoice(playerA, "Whenever an equipped creature you control attacks"); setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); // Triggered twice, exiling two cards assertExileCount(playerA, 2); } @Test public void test_CanCastExiledEquipmentForFree() { addCard(Zone.BATTLEFIELD, playerA, nahiri); addCard(Zone.BATTLEFIELD, playerA, greaves); skipInitShuffling(); addCard(Zone.LIBRARY, playerA, sword); activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Equip {0}", nahiri); // Attack with one equipped creature, exiling the sword attack(1, playerA, nahiri); // Cast sword for free castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, sword); setStrictChooseMode(true); setStopAt(2, PhaseStep.END_TURN); execute(); } }
0
0.939609
1
0.939609
game-dev
MEDIA
0.82718
game-dev,testing-qa
0.959627
1
0.959627
steves-underwater-paradise/blinkload
1,998
common/src/main/java/io/github/steveplays28/blinkload/util/ModUtil.java
package io.github.steveplays28.blinkload.util; import dev.architectury.injectables.annotations.ExpectPlatform; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import static io.github.steveplays28.blinkload.BlinkLoad.MOD_ID; @SuppressWarnings("unused") public abstract class ModUtil { private static final Logger LOGGER = LoggerFactory.getLogger(String.format("%s/mod_util", MOD_ID)); /** * Checks if a mod is present during loading. */ @ExpectPlatform public static boolean isModPresent(String id) { throw new AssertionError("Platform implementation expected."); } /** * Gets the game directory. */ @ExpectPlatform public static @NotNull Path getGameDirectory() { throw new AssertionError("Platform implementation expected."); } @ExpectPlatform public static @NotNull List<String> getModListNames() { throw new AssertionError("Platform implementation expected."); } public static @NotNull List<String> getEnabledResourcePackNames() { @NotNull List<String> enabledResourcePackNames = new ArrayList<>(); try (@NotNull var bufferedFileReader = new BufferedReader(new FileReader(getGameDirectory().resolve("options.txt").toFile()))) { bufferedFileReader.lines().forEach(line -> { if (!line.contains("resourcePacks")) { return; } @NotNull var rawEnabledResourcePackNamesOption = line.split("\\["); if (rawEnabledResourcePackNamesOption.length < 2) { return; } @NotNull var rawEnabledResourcePackNames = rawEnabledResourcePackNamesOption[1].replace("]", ""); enabledResourcePackNames.addAll(List.of(rawEnabledResourcePackNames.split(","))); }); } catch (IOException e) { LOGGER.error("Exception occurred while getting enabled resource pack names: ", e); } return enabledResourcePackNames; } }
0
0.948129
1
0.948129
game-dev
MEDIA
0.549505
game-dev
0.975703
1
0.975703
MagForceSeven/Starfire
5,789
StarfireSaveData/Source/StarfireSaveData/Private/SaveData/SaveDataAsyncManager.cpp
#include "SaveData/SaveDataAsyncManager.h" // Core #include "Logging/StructuredLog.h" #include UE_INLINE_GENERATED_CPP_BY_NAME(SaveDataAsyncManager) FSaveDataAccessStarted USaveDataUtilities::OnSaveDataAccessStarted; FSaveDataAccessEnded USaveDataUtilities::OnSaveDataAccessEnded; void USaveDataAsyncManager::AddNewTask( USaveDataUtilities::FSaveDataAsyncTask *NewTask ) { check( IsInGameThread( ) ); UE_LOGFMT( LogStarfireSaveData, Log, "AsyncManager - Starting Task - {0}", NewTask->TaskName ); AsyncTasks.Push( NewTask ); AsyncTasks.Last( )->Start( this ); // if it's 1, it must have been empty before // unless we're adding while in the middle of ticking due to a Complete call if ((AsyncTasks.Num( ) == 1) && !bIsTicking) USaveDataUtilities::OnSaveDataAccessStarted.Broadcast( ); } void USaveDataAsyncManager::Tick( float DeltaTime ) { ensure( !IsTemplate( ) ); bIsTicking = true; for (int idx = AsyncTasks.Num( ) - 1; idx >= 0; --idx) { const auto AsyncTask = AsyncTasks[ idx ]; if (AsyncTask->IsDone( )) { UE_LOGFMT( LogStarfireSaveData, Log, "AsyncManager - Task Complete - {0}", AsyncTask->TaskName ); AsyncTask->Complete( this ); delete AsyncTask; AsyncTasks.RemoveAt( idx ); } } bIsTicking = false; if (AsyncTasks.IsEmpty( )) USaveDataUtilities::OnSaveDataAccessEnded.Broadcast( ); } void USaveDataAsyncManager::Flush( USaveDataUtilities::FSaveDataAsyncTask::EComplete Mode ) { UE_LOGFMT( LogStarfireSaveData, Log, "SaveDataAsyncManager::Flush (Mode {0})", static_cast<int>(Mode) ); const bool bHadTasks = !AsyncTasks.IsEmpty( ); while (AsyncTasks.Num( )) { const auto Task = AsyncTasks.Pop( ); UE_LOGFMT( LogStarfireSaveData, Warning, "AsyncManager - Flushing Task - {0}", Task->TaskName ); Task->EnsureCompletion( this, Mode ); Task->Complete( this ); delete Task; } if (bHadTasks) USaveDataUtilities::OnSaveDataAccessEnded.Broadcast( ); } ETickableTickType USaveDataAsyncManager::GetTickableTickType() const { if (IsTemplate( )) return ETickableTickType::Never; return ETickableTickType::Conditional; } bool USaveDataAsyncManager::IsTickable( void ) const { ensure( !IsTemplate( ) ); return AsyncTasks.Num( ) > 0; } void USaveDataAsyncManager::Deinitialize( void ) { UE_LOGFMT( LogStarfireSaveData, Log, "SaveDataAsyncManager::Deinitialize" ); const bool bHadTasks = !AsyncTasks.IsEmpty( ); // Make sure that any pending async work is completed at least enough to release the task // The completion callbacks won't happen so no further async tasks should get started // This is meant as a last ditch cleanup operation, not a guarantee that requested tasks // are fully completed (if that task involved multiple async operations) while (AsyncTasks.Num( ) > 0) { const auto Task = AsyncTasks.Pop( ); UE_LOGFMT( LogStarfireSaveData, Warning, "AsyncManager - Force Completing Task - {0}", Task->TaskName ); Task->EnsureCompletion( this, USaveDataUtilities::FSaveDataAsyncTask::EComplete::WithJoin ); delete Task; } if (bHadTasks) USaveDataUtilities::OnSaveDataAccessEnded.Broadcast( ); } void USaveDataUtilities::FlushAsyncSaveTasks( const UObject *WorldContext ) { if (!ensureAlways( SaveOperationsAreAllowed( ) )) return; const UWorld *World = GEngine->GetWorldFromContextObject( WorldContext, EGetWorldErrorMode::LogAndReturnNull ); if (!ensureAlways( World != nullptr )) return; const auto AsyncManager = World->GetSubsystem< USaveDataAsyncManager >( ); AsyncManager->Flush( USaveDataUtilities::FSaveDataAsyncTask::EComplete::WithoutJoin ); } void USaveDataUtilities::WaitOnAsyncSaveTasks( const UObject *WorldContext ) { if (!ensureAlways( SaveOperationsAreAllowed( ) )) return; const UWorld *World = GEngine->GetWorldFromContextObject( WorldContext, EGetWorldErrorMode::LogAndReturnNull ); if (!ensureAlways( World != nullptr )) return; const auto AsyncManager = World->GetSubsystem< USaveDataAsyncManager >( ); AsyncManager->Flush( USaveDataUtilities::FSaveDataAsyncTask::EComplete::WithJoin ); } bool USaveDataUtilities::AnyAsyncSaveTasksPending( const UObject *WorldContext ) { const UWorld *World = GEngine->GetWorldFromContextObject( WorldContext, EGetWorldErrorMode::LogAndReturnNull ); if (!ensureAlways( World != nullptr )) return false; const auto AsyncManager = World->GetSubsystem< USaveDataAsyncManager >( ); return AsyncManager->IsTickable( ); } bool USaveDataUtilities::StartAsyncSaveTask_Internal( const UObject *WorldContext, FSaveDataAsyncTask *Task ) { const UWorld *World = GEngine->GetWorldFromContextObject( WorldContext, EGetWorldErrorMode::LogAndReturnNull ); if (!ensureAlways( World != nullptr )) { delete Task; return false; } const auto AsyncManager = World->GetSubsystem< USaveDataAsyncManager >( ); AsyncManager->AddNewTask( Task ); return true; } UWaitOnSaveAsync_AsyncAction* UWaitOnSaveAsync_AsyncAction::WaitOnSaveGameAsyncActions( UObject *WorldContext ) { const auto World = GEngine->GetWorldFromContextObject( WorldContext, EGetWorldErrorMode::LogAndReturnNull ); if (!ensureAlways( World != nullptr )) return nullptr; const auto AsyncManager = World->GetSubsystem< USaveDataAsyncManager >( ); const auto AsyncAction = NewObject< UWaitOnSaveAsync_AsyncAction >( AsyncManager ); return AsyncAction; } void UWaitOnSaveAsync_AsyncAction::Activate( void ) { const auto AsyncManager = Cast< USaveDataAsyncManager >( GetOuter( ) ); if (AsyncManager->IsTickable( )) StartAction( this, true ); else OnComplete.Broadcast( ); } void UWaitOnSaveAsync_AsyncAction::Tick( float fDeltaT ) { const auto AsyncManager = Cast< USaveDataAsyncManager >( GetOuter( ) ); if (AsyncManager->IsTickable( )) return; OnComplete.Broadcast( ); EndAction( ); }
0
0.898936
1
0.898936
game-dev
MEDIA
0.281831
game-dev
0.927671
1
0.927671
HyperMC-Team/OpenRoxy
18,114
src/main/java/net/minecraft/client/gui/GuiTextField.java
package net.minecraft.client.gui; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiPageButtonList; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.MathHelper; public class GuiTextField extends Gui { private final int id; protected final FontRenderer fontRendererInstance; public int xPosition; public int yPosition; public int width; public int height; protected String text = ""; private int maxStringLength = 32; protected int cursorCounter; protected boolean enableBackgroundDrawing = true; protected boolean canLoseFocus = true; protected boolean isFocused; protected boolean isEnabled = true; protected int lineScrollOffset; private int cursorPosition; protected int selectionEnd; protected int enabledColor = 0xE0E0E0; protected int disabledColor = 0x707070; private boolean visible = true; private GuiPageButtonList.GuiResponder field_175210_x; private Predicate<String> validator = Predicates.alwaysTrue(); public GuiTextField(int componentId, FontRenderer fontrendererObj, int x, int y, int par5Width, int par6Height) { this.id = componentId; this.fontRendererInstance = fontrendererObj; this.xPosition = x; this.yPosition = y; this.width = par5Width; this.height = par6Height; } public void func_175207_a(GuiPageButtonList.GuiResponder p_175207_1_) { this.field_175210_x = p_175207_1_; } public void updateCursorCounter() { ++this.cursorCounter; } public void setText(String p_146180_1_) { if (this.validator.apply(p_146180_1_)) { this.text = p_146180_1_.length() > this.maxStringLength ? p_146180_1_.substring(0, this.maxStringLength) : p_146180_1_; this.setCursorPositionEnd(); } } public String getText() { return this.text; } public String getSelectedText() { int i = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; int j = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; return this.text.substring(i, j); } public void setValidator(Predicate<String> theValidator) { this.validator = theValidator; } public void writeText(String p_146191_1_) { String s = ""; String s1 = ChatAllowedCharacters.filterAllowedCharacters(p_146191_1_); int i = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; int j = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; int k = this.maxStringLength - this.text.length() - (i - j); int l = 0; if (this.text.length() > 0) { s = (String)s + this.text.substring(0, i); } if (k < s1.length()) { s = (String)s + s1.substring(0, k); l = k; } else { s = (String)s + s1; l = s1.length(); } if (this.text.length() > 0 && j < this.text.length()) { s = (String)s + this.text.substring(j); } if (this.validator.apply(s)) { this.text = s; this.moveCursorBy(i - this.selectionEnd + l); if (this.field_175210_x != null) { this.field_175210_x.func_175319_a(this.id, this.text); } } } public void deleteWords(int p_146177_1_) { if (this.text.length() != 0) { if (this.selectionEnd != this.cursorPosition) { this.writeText(""); } else { this.deleteFromCursor(this.getNthWordFromCursor(p_146177_1_) - this.cursorPosition); } } } public void deleteFromCursor(int p_146175_1_) { if (this.text.length() != 0) { if (this.selectionEnd != this.cursorPosition) { this.writeText(""); } else { boolean flag = p_146175_1_ < 0; int i = flag ? this.cursorPosition + p_146175_1_ : this.cursorPosition; int j = flag ? this.cursorPosition : this.cursorPosition + p_146175_1_; String s = ""; if (i >= 0) { s = this.text.substring(0, i); } if (j < this.text.length()) { s = (String)s + this.text.substring(j); } if (this.validator.apply(s)) { this.text = s; if (flag) { this.moveCursorBy(p_146175_1_); } if (this.field_175210_x != null) { this.field_175210_x.func_175319_a(this.id, this.text); } } } } } public int getId() { return this.id; } public int getNthWordFromCursor(int p_146187_1_) { return this.getNthWordFromPos(p_146187_1_, this.getCursorPosition()); } public int getNthWordFromPos(int p_146183_1_, int p_146183_2_) { return this.func_146197_a(p_146183_1_, p_146183_2_, true); } public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_) { int i = p_146197_2_; boolean flag = p_146197_1_ < 0; int j = Math.abs(p_146197_1_); for (int k = 0; k < j; ++k) { if (!flag) { int l = this.text.length(); if ((i = this.text.indexOf(32, i)) == -1) { i = l; continue; } while (p_146197_3_ && i < l && this.text.charAt(i) == ' ') { ++i; } continue; } while (p_146197_3_ && i > 0 && this.text.charAt(i - 1) == ' ') { --i; } while (i > 0 && this.text.charAt(i - 1) != ' ') { --i; } } return i; } public void moveCursorBy(int p_146182_1_) { this.setCursorPosition(this.selectionEnd + p_146182_1_); } public void setCursorPosition(int p_146190_1_) { this.cursorPosition = p_146190_1_; int i = this.text.length(); this.cursorPosition = MathHelper.clamp_int(this.cursorPosition, 0, i); this.setSelectionPos(this.cursorPosition); } public void setCursorPositionZero() { this.setCursorPosition(0); } public void setCursorPositionEnd() { this.setCursorPosition(this.text.length()); } public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_) { if (!this.isFocused) { return false; } if (GuiScreen.isKeyComboCtrlA(p_146201_2_)) { this.setCursorPositionEnd(); this.setSelectionPos(0); return true; } if (GuiScreen.isKeyComboCtrlC(p_146201_2_)) { GuiScreen.setClipboardString(this.getSelectedText()); return true; } if (GuiScreen.isKeyComboCtrlV(p_146201_2_)) { if (this.isEnabled) { this.writeText(GuiScreen.getClipboardString()); } return true; } if (GuiScreen.isKeyComboCtrlX(p_146201_2_)) { GuiScreen.setClipboardString(this.getSelectedText()); if (this.isEnabled) { this.writeText(""); } return true; } switch (p_146201_2_) { case 14: { if (GuiScreen.isCtrlKeyDown()) { if (this.isEnabled) { this.deleteWords(-1); } } else if (this.isEnabled) { this.deleteFromCursor(-1); } return true; } case 199: { if (GuiScreen.isShiftKeyDown()) { this.setSelectionPos(0); } else { this.setCursorPositionZero(); } return true; } case 203: { if (GuiScreen.isShiftKeyDown()) { if (GuiScreen.isCtrlKeyDown()) { this.setSelectionPos(this.getNthWordFromPos(-1, this.getSelectionEnd())); } else { this.setSelectionPos(this.getSelectionEnd() - 1); } } else if (GuiScreen.isCtrlKeyDown()) { this.setCursorPosition(this.getNthWordFromCursor(-1)); } else { this.moveCursorBy(-1); } return true; } case 205: { if (GuiScreen.isShiftKeyDown()) { if (GuiScreen.isCtrlKeyDown()) { this.setSelectionPos(this.getNthWordFromPos(1, this.getSelectionEnd())); } else { this.setSelectionPos(this.getSelectionEnd() + 1); } } else if (GuiScreen.isCtrlKeyDown()) { this.setCursorPosition(this.getNthWordFromCursor(1)); } else { this.moveCursorBy(1); } return true; } case 207: { if (GuiScreen.isShiftKeyDown()) { this.setSelectionPos(this.text.length()); } else { this.setCursorPositionEnd(); } return true; } case 211: { if (GuiScreen.isCtrlKeyDown()) { if (this.isEnabled) { this.deleteWords(1); } } else if (this.isEnabled) { this.deleteFromCursor(1); } return true; } } if (ChatAllowedCharacters.isAllowedCharacter(p_146201_1_)) { if (this.isEnabled) { this.writeText(Character.toString(p_146201_1_)); } return true; } return false; } public void mouseClicked(int p_146192_1_, int p_146192_2_, int p_146192_3_) { boolean flag; boolean bl = flag = p_146192_1_ >= this.xPosition && p_146192_1_ < this.xPosition + this.width && p_146192_2_ >= this.yPosition && p_146192_2_ < this.yPosition + this.height; if (this.canLoseFocus) { this.setFocused(flag); } if (this.isFocused && flag && p_146192_3_ == 0) { int i = p_146192_1_ - this.xPosition; if (this.enableBackgroundDrawing) { i -= 4; } String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), this.getWidth()); this.setCursorPosition(this.fontRendererInstance.trimStringToWidth(s, i).length() + this.lineScrollOffset); } } public void drawTextBox() { if (this.getVisible()) { if (this.getEnableBackgroundDrawing()) { GuiTextField.drawRect(this.xPosition - 1, this.yPosition - 1, this.xPosition + this.width + 1, this.yPosition + this.height + 1, -6250336); GuiTextField.drawRect(this.xPosition, this.yPosition, this.xPosition + this.width, this.yPosition + this.height, -16777216); } int i = this.isEnabled ? this.enabledColor : this.disabledColor; int j = this.cursorPosition - this.lineScrollOffset; int k = this.selectionEnd - this.lineScrollOffset; String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), this.getWidth()); boolean flag = j >= 0 && j <= s.length(); boolean flag1 = this.isFocused && this.cursorCounter / 6 % 2 == 0 && flag; int l = this.enableBackgroundDrawing ? this.xPosition + 4 : this.xPosition; int i1 = this.enableBackgroundDrawing ? this.yPosition + (this.height - 8) / 2 : this.yPosition; int j1 = l; if (k > s.length()) { k = s.length(); } if (s.length() > 0) { String s1 = flag ? s.substring(0, j) : s; j1 = this.fontRendererInstance.drawStringWithShadow(s1, l, i1, i); } boolean flag2 = this.cursorPosition < this.text.length() || this.text.length() >= this.getMaxStringLength(); int k1 = j1; if (!flag) { k1 = j > 0 ? l + this.width : l; } else if (flag2) { k1 = j1 - 1; --j1; } if (s.length() > 0 && flag && j < s.length()) { j1 = this.fontRendererInstance.drawStringWithShadow(s.substring(j), j1, i1, i); } if (flag1) { if (flag2) { Gui.drawRect(k1, i1 - 1, k1 + 1, i1 + 1 + this.fontRendererInstance.FONT_HEIGHT, -3092272); } else { this.fontRendererInstance.drawStringWithShadow("_", k1, i1, i); } } if (k != j) { int l1 = l + this.fontRendererInstance.getStringWidth(s.substring(0, k)); this.drawCursorVertical(k1, i1 - 1, l1 - 1, i1 + 1 + this.fontRendererInstance.FONT_HEIGHT); } } } protected void drawCursorVertical(int p_146188_1_, int p_146188_2_, int p_146188_3_, int p_146188_4_) { if (p_146188_1_ < p_146188_3_) { int i = p_146188_1_; p_146188_1_ = p_146188_3_; p_146188_3_ = i; } if (p_146188_2_ < p_146188_4_) { int j = p_146188_2_; p_146188_2_ = p_146188_4_; p_146188_4_ = j; } if (p_146188_3_ > this.xPosition + this.width) { p_146188_3_ = this.xPosition + this.width; } if (p_146188_1_ > this.xPosition + this.width) { p_146188_1_ = this.xPosition + this.width; } Tessellator tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = tessellator.getWorldRenderer(); GlStateManager.color(0.0f, 0.0f, 255.0f, 255.0f); GlStateManager.disableTexture2D(); GlStateManager.enableColorLogic(); GlStateManager.colorLogicOp(5387); worldrenderer.begin(7, DefaultVertexFormats.POSITION); worldrenderer.pos(p_146188_1_, p_146188_4_, 0.0).endVertex(); worldrenderer.pos(p_146188_3_, p_146188_4_, 0.0).endVertex(); worldrenderer.pos(p_146188_3_, p_146188_2_, 0.0).endVertex(); worldrenderer.pos(p_146188_1_, p_146188_2_, 0.0).endVertex(); tessellator.draw(); GlStateManager.disableColorLogic(); GlStateManager.enableTexture2D(); } public void setMaxStringLength(int p_146203_1_) { this.maxStringLength = p_146203_1_; if (this.text.length() > p_146203_1_) { this.text = this.text.substring(0, p_146203_1_); } } public int getMaxStringLength() { return this.maxStringLength; } public int getCursorPosition() { return this.cursorPosition; } public boolean getEnableBackgroundDrawing() { return this.enableBackgroundDrawing; } public void setEnableBackgroundDrawing(boolean p_146185_1_) { this.enableBackgroundDrawing = p_146185_1_; } public void setTextColor(int p_146193_1_) { this.enabledColor = p_146193_1_; } public void setDisabledTextColour(int p_146204_1_) { this.disabledColor = p_146204_1_; } public void setFocused(boolean p_146195_1_) { if (p_146195_1_ && !this.isFocused) { this.cursorCounter = 0; } this.isFocused = p_146195_1_; } public boolean isFocused() { return this.isFocused; } public void setEnabled(boolean p_146184_1_) { this.isEnabled = p_146184_1_; } public int getSelectionEnd() { return this.selectionEnd; } public int getWidth() { return this.getEnableBackgroundDrawing() ? this.width - 8 : this.width; } public void setSelectionPos(int p_146199_1_) { int i = this.text.length(); if (p_146199_1_ > i) { p_146199_1_ = i; } if (p_146199_1_ < 0) { p_146199_1_ = 0; } this.selectionEnd = p_146199_1_; if (this.fontRendererInstance != null) { if (this.lineScrollOffset > i) { this.lineScrollOffset = i; } int j = this.getWidth(); String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), j); int k = s.length() + this.lineScrollOffset; if (p_146199_1_ == this.lineScrollOffset) { this.lineScrollOffset -= this.fontRendererInstance.trimStringToWidth(this.text, j, true).length(); } if (p_146199_1_ > k) { this.lineScrollOffset += p_146199_1_ - k; } else if (p_146199_1_ <= this.lineScrollOffset) { this.lineScrollOffset -= this.lineScrollOffset - p_146199_1_; } this.lineScrollOffset = MathHelper.clamp_int(this.lineScrollOffset, 0, i); } } public void setCanLoseFocus(boolean p_146205_1_) { this.canLoseFocus = p_146205_1_; } public boolean getVisible() { return this.visible; } public void setVisible(boolean p_146189_1_) { this.visible = p_146189_1_; } }
0
0.913447
1
0.913447
game-dev
MEDIA
0.709197
game-dev
0.926329
1
0.926329
orts/server
12,806
data/npc/scripts/Gregor.lua
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local voices = { {text = 'Gather around me, young knights! I\'m going to teach you some spells!'} } npcHandler:addModule(VoiceModule:new(voices)) local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) local addonProgress = player:getStorageValue(Storage.OutfitQuest.Knight.AddonHelmet) if msgcontains(msg, 'task') then if not player:isPremium() then npcHandler:say('Sorry, but our tasks are only for premium warriors.', cid) return true end if addonProgress < 1 then npcHandler:say('You mean you would like to prove that you deserve to wear such a helmet?', cid) npcHandler.topic[cid] = 1 elseif addonProgress == 1 then npcHandler:say('Your current task is to bring me 100 perfect behemoth fangs, |PLAYERNAME|.', cid) elseif addonProgress == 2 then npcHandler:say('Your current task is to retrieve the helmet of Ramsay the Reckless from Banuta, |PLAYERNAME|.', cid) elseif addonProgress == 3 then npcHandler:say('Your current task is to obtain a flask of warrior\'s sweat, |PLAYERNAME|.', cid) elseif addonProgress == 4 then npcHandler:say('Your current task is to bring me royal steel, |PLAYERNAME|.', cid) elseif addonProgress == 5 then npcHandler:say('Please talk to Sam and tell him I sent you. I\'m sure he will be glad to refine your helmet, |PLAYERNAME|.', cid) else npcHandler:say('You\'ve already completed the task and can consider yourself a mighty warrior, |PLAYERNAME|.', cid) end elseif msgcontains(msg, 'behemoth fang') then if addonProgress == 1 then npcHandler:say('Have you really managed to fulfil the task and brought me 100 perfect behemoth fangs?', cid) npcHandler.topic[cid] = 3 else npcHandler:say('You\'re not serious asking that, are you? They come from behemoths, of course. Unless there are behemoth rabbits. Duh.', cid) end elseif msgcontains(msg, 'ramsay') then if addonProgress == 2 then npcHandler:say('Did you recover the helmet of Ramsay the Reckless?', cid) npcHandler.topic[cid] = 4 else npcHandler:say('These pesky apes steal everything they can get their dirty hands on.', cid) end elseif msgcontains(msg, 'sweat') then if addonProgress == 3 then npcHandler:say('Were you able to get hold of a flask with pure warrior\'s sweat?', cid) npcHandler.topic[cid] = 5 else npcHandler:say('Warrior\'s sweat can be magically extracted from headgear worn by a true warrior, but only in small amounts. Djinns are said to be good at magical extractions.', cid) end elseif msgcontains(msg, 'royal steel') then if addonProgress == 4 then npcHandler:say('Ah, have you brought the royal steel?', cid) npcHandler.topic[cid] = 6 else npcHandler:say('Royal steel can only be refined by very skilled smiths.', cid) end elseif npcHandler.topic[cid] == 1 then if msgcontains(msg, 'yes') then npcHandler:say({ 'Well then, listen closely. First, you will have to prove that you are a fierce and restless warrior by bringing me 100 perfect behemoth fangs. ...', 'Secondly, please retrieve a helmet for us which has been lost a long time ago. The famous Ramsay the Reckless wore it when exploring an ape settlement. ...', 'Third, we need a new flask of warrior\'s sweat. We\'ve run out of it recently, but we need a small amount for the show battles in our arena. ...', 'Lastly, I will have our smith refine your helmet if you bring me royal steel, an especially noble metal. ...', 'Did you understand everything I told you and are willing to handle this task?' }, cid) npcHandler.topic[cid] = 2 elseif msgcontains(msg, 'no') then npcHandler:say('Bah. Then you will have to wait for the day these helmets are sold in shops, but that will not happen before hell freezes over.', cid) npcHandler.topic[cid] = 0 end elseif npcHandler.topic[cid] == 2 then if msgcontains(msg, 'yes') then player:setStorageValue(Storage.OutfitQuest.Ref, math.max(0, player:getStorageValue(Storage.OutfitQuest.Ref)) + 1) player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 1) player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 1) npcHandler:say('Alright then. Come back to me once you have collected 100 perfect behemoth fangs.', cid) npcHandler.topic[cid] = 0 elseif msgcontains(msg, 'no') then npcHandler:say('Would you like me to repeat the task requirements then?', cid) npcHandler.topic[cid] = 1 end elseif npcHandler.topic[cid] == 3 then if msgcontains(msg, 'yes') then if not player:removeItem(5893, 100) then npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid) return true end player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 2) player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 2) player:setStorageValue(Storage.OutfitQuest.Knight.RamsaysHelmetDoor, 1) npcHandler:say('I\'m deeply impressed, brave Knight |PLAYERNAME|. I expected nothing less from you. Now, please retrieve Ramsay\'s helmet.', cid) elseif msgcontains(msg, 'no') then npcHandler:say('There is no need to rush anyway.', cid) end npcHandler.topic[cid] = 0 elseif npcHandler.topic[cid] == 4 then if msgcontains(msg, 'yes') then if not player:removeItem(5924, 1) then npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid) return true end player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 3) player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 3) npcHandler:say('Good work, brave Knight |PLAYERNAME|! Even though it is damaged, it has a lot of sentimental value. Now, please bring me warrior\'s sweat.', cid) elseif msgcontains(msg, 'no') then npcHandler:say('There is no need to rush anyway.', cid) end npcHandler.topic[cid] = 0 elseif npcHandler.topic[cid] == 5 then if msgcontains(msg, 'yes') then if not player:removeItem(5885, 1) then npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid) return true end player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 4) player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 4) npcHandler:say('Now that is a pleasant surprise, brave Knight |PLAYERNAME|! There is only one task left now: Obtain royal steel to have your helmet refined.', cid) elseif msgcontains(msg, 'no') then npcHandler:say('There is no need to rush anyway.', cid) end npcHandler.topic[cid] = 0 elseif npcHandler.topic[cid] == 6 then if msgcontains(msg, 'yes') then if not player:removeItem(5887, 1) then npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid) return true end player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 5) player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 5) npcHandler:say('You truly deserve to wear an adorned helmet, brave Knight |PLAYERNAME|. Please talk to Sam and tell him I sent you. I\'m sure he will be glad to refine your helmet.', cid) elseif msgcontains(msg, 'no') then npcHandler:say('There is no need to rush anyway.', cid) end npcHandler.topic[cid] = 0 end return true end keywordHandler:addSpellKeyword({'find', 'person'}, {npcHandler = npcHandler, spellName = 'Find Person', price = 80, level = 8, vocation = 4}) keywordHandler:addSpellKeyword({'light'}, {npcHandler = npcHandler, spellName = 'Light', price = 0, level = 8, vocation = 4}) keywordHandler:addSpellKeyword({'cure', 'poison'}, {npcHandler = npcHandler, spellName = 'Cure Poison', price = 150, level = 10, vocation = 4}) keywordHandler:addSpellKeyword({'wound', 'cleansing'}, {npcHandler = npcHandler, spellName = 'Wound Cleansing', price = 0, level = 8, vocation = 4}) keywordHandler:addSpellKeyword({'great', 'light'}, {npcHandler = npcHandler, spellName = 'Great Light', price = 500, level = 13, vocation = 4}) keywordHandler:addKeyword({'healing', 'spells'}, StdModule.say, {npcHandler = npcHandler, text = "In this category I have '{Wound Cleansing}' and '{Cure Poison}'."}) keywordHandler:addKeyword({'support', 'spells'}, StdModule.say, {npcHandler = npcHandler, text = "In this category I have '{Light}', '{Find Person}' and '{Great Light}'."}) keywordHandler:addKeyword({'spells'}, StdModule.say, {npcHandler = npcHandler, text = 'I can teach you {healing spells} and {support spells}. What kind of spell do you wish to learn? You can also tell me for which level you would like to learn a spell, if you prefer that.'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = "I am the first knight. I trained some of the greatest heroes of Tibia."}) keywordHandler:addKeyword({'heroes'}, StdModule.say, {npcHandler = npcHandler, text = "Of course, you heard of them. Knights are the best fighters in Tibia."}) keywordHandler:addKeyword({'king'}, StdModule.say, {npcHandler = npcHandler, text = "Hail to our King!"}) keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = "You are joking, eh? Of course, you know me. I am Gregor, the first knight."}) keywordHandler:addKeyword({'gregor'}, StdModule.say, {npcHandler = npcHandler, text = "A great name, isn't it?"}) keywordHandler:addKeyword({'tibia'}, StdModule.say, {npcHandler = npcHandler, text = "Beautiful Tibia. And with our help everyone is save."}) keywordHandler:addKeyword({'time'}, StdModule.say, {npcHandler = npcHandler, text = "It is time to join the Knights!"}) keywordHandler:addKeyword({'knights'}, StdModule.say, {npcHandler = npcHandler, text = "Knights are the warriors of Tibia. Without us, no one would be safe. Every brave and strong man or woman can join us."}) keywordHandler:addKeyword({'bozo'}, StdModule.say, {npcHandler = npcHandler, text = "Some day someone will make something happen to him..."}) keywordHandler:addKeyword({'elane'}, StdModule.say, {npcHandler = npcHandler, text = "A bow might be a fine weapon for someone not strong enough to wield a REAL weapon."}) keywordHandler:addKeyword({'frodo'}, StdModule.say, {npcHandler = npcHandler, text = "I and my students often share a cask of beer or wine at Frodo's hut."}) keywordHandler:addKeyword({'gorn'}, StdModule.say, {npcHandler = npcHandler, text = "Always concerned with his profit. What a loss! He was adventuring with baxter in the old days."}) keywordHandler:addKeyword({'baxter'}, StdModule.say, {npcHandler = npcHandler, text = "He was an adventurer once."}) keywordHandler:addKeyword({'lynda'}, StdModule.say, {npcHandler = npcHandler, text = "Before she became a priest she won the Miss Tibia contest three times in a row."}) keywordHandler:addKeyword({'mcronald'}, StdModule.say, {npcHandler = npcHandler, text = "Peaceful farmers."}) keywordHandler:addKeyword({'ferumbras'}, StdModule.say, {npcHandler = npcHandler, text = "A fine game to hunt. But be careful, he cheats!"}) keywordHandler:addKeyword({'muriel'}, StdModule.say, {npcHandler = npcHandler, text = "Bah, go away with these sorcerer tricks. Only cowards use tricks."}) keywordHandler:addKeyword({'oswald'}, StdModule.say, {npcHandler = npcHandler, text = "What an idiot."}) keywordHandler:addKeyword({'quentin'}, StdModule.say, {npcHandler = npcHandler, text = "I will never understand this peaceful monks and priests."}) keywordHandler:addKeyword({'sam'}, StdModule.say, {npcHandler = npcHandler, text = "He has the muscles, but lacks the guts."}) keywordHandler:addKeyword({'tibianus'}, StdModule.say, {npcHandler = npcHandler, text = "Hail to our King!"}) keywordHandler:addKeyword({'outfit'}, StdModule.say, {npcHandler = npcHandler, text = "Only the bravest warriors may wear adorned helmets. They are traditionally awarded after having completed a difficult task for our guild."}) keywordHandler:addKeyword({'helmet'}, StdModule.say, {npcHandler = npcHandler, text = "Only the bravest warriors may wear adorned helmets. They are traditionally awarded after having completed a difficult task for our guild."}) npcHandler:setMessage(MESSAGE_GREET, "Greetings, |PLAYERNAME|. What do you want?") npcHandler:setMessage(MESSAGE_FAREWELL, "Be careful on your journeys.") npcHandler:setMessage(MESSAGE_WALKAWAY, "Be careful on your journeys.") npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
0
0.922264
1
0.922264
game-dev
MEDIA
0.975323
game-dev
0.986345
1
0.986345
Tuinity/Moonrise
3,217
src/main/java/ca/spottedleaf/moonrise/mixin/chunk_system/ServerPlayerMixin.java
package ca.spottedleaf.moonrise.mixin.chunk_system; import ca.spottedleaf.moonrise.patches.chunk_system.player.ChunkSystemServerPlayer; import ca.spottedleaf.moonrise.patches.chunk_system.player.RegionizedPlayerChunkLoader; import com.llamalad7.mixinextras.sugar.Local; import com.mojang.authlib.GameProfile; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.function.BooleanSupplier; @Mixin(ServerPlayer.class) abstract class ServerPlayerMixin extends Player implements ChunkSystemServerPlayer { public ServerPlayerMixin(final Level p_250508_, final GameProfile p_252153_) { super(p_250508_, p_252153_); } @Unique private boolean isRealPlayer; @Unique private RegionizedPlayerChunkLoader.PlayerChunkLoaderData chunkLoader; @Unique private RegionizedPlayerChunkLoader.ViewDistanceHolder viewDistanceHolder = new RegionizedPlayerChunkLoader.ViewDistanceHolder(); @Override public final boolean moonrise$isRealPlayer() { return this.isRealPlayer; } @Override public final void moonrise$setRealPlayer(final boolean real) { this.isRealPlayer = real; } @Override public final RegionizedPlayerChunkLoader.PlayerChunkLoaderData moonrise$getChunkLoader() { return this.chunkLoader; } @Override public final void moonrise$setChunkLoader(final RegionizedPlayerChunkLoader.PlayerChunkLoaderData loader) { this.chunkLoader = loader; } @Override public final RegionizedPlayerChunkLoader.ViewDistanceHolder moonrise$getViewDistanceHolder() { return this.viewDistanceHolder; } /** * @reason Do not process packets while waiting for spawn location * @author Spottedleaf */ @Redirect( method = "adjustSpawnLocation", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;managedBlock(Ljava/util/function/BooleanSupplier;)V" ) ) private void blockOnCorrectQueue(final MinecraftServer instance, final BooleanSupplier isDone, final @Local(ordinal = 0, argsOnly = true) ServerLevel world) { world.getChunkSource().mainThreadProcessor.managedBlock(isDone); } /** * @reason Copy player state when respawning * @author Spottedleaf */ @Inject( method = "restoreFrom", at = @At( value = "HEAD" ) ) private void copyRealPlayer(ServerPlayer from, boolean bl, CallbackInfo ci) { this.isRealPlayer = ((ServerPlayerMixin)(Object)from).isRealPlayer; this.viewDistanceHolder = ((ServerPlayerMixin)(Object)from).viewDistanceHolder; } }
0
0.917413
1
0.917413
game-dev
MEDIA
0.95636
game-dev
0.982486
1
0.982486
google/filament
11,682
third_party/dawn/src/dawn/native/CommandAllocator.h
// Copyright 2017 The Dawn & Tint Authors // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 SRC_DAWN_NATIVE_COMMANDALLOCATOR_H_ #define SRC_DAWN_NATIVE_COMMANDALLOCATOR_H_ #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <string_view> #include <vector> #include "dawn/common/Assert.h" #include "dawn/common/Math.h" #include "dawn/common/NonCopyable.h" #include "partition_alloc/pointers/raw_ptr_exclusion.h" namespace dawn::native { // Allocation for command buffers should be fast. To avoid doing an allocation per command // or to avoid copying commands when reallocing, we use a linear allocator in a growing set // of large memory blocks. We also use this to have the format to be (u32 commandId, command), // so that iteration over the commands is easy. // Usage of the allocator and iterator: // CommandAllocator allocator; // DrawCommand* cmd = allocator.Allocate<DrawCommand>(CommandType::Draw); // // Fill command // // Repeat allocation and filling commands // // CommandIterator commands(allocator); // CommandType type; // while(commands.NextCommandId(&type)) { // switch(type) { // case CommandType::Draw: // DrawCommand* draw = commands.NextCommand<DrawCommand>(); // // Do the draw // break; // // other cases // } // } // Note that you need to extract the commands from the CommandAllocator before destroying it // and must tell the CommandIterator when the allocated commands have been processed for // deletion. // These are the lists of blocks, should not be used directly, only through CommandAllocator // and CommandIterator struct BlockDef { size_t size; std::unique_ptr<char[]> block; }; using CommandBlocks = std::vector<BlockDef>; namespace detail { constexpr uint32_t kEndOfBlock = std::numeric_limits<uint32_t>::max(); constexpr uint32_t kAdditionalData = std::numeric_limits<uint32_t>::max() - 1; } // namespace detail class CommandAllocator; class CommandIterator : public NonCopyable { public: CommandIterator(); ~CommandIterator(); CommandIterator(CommandIterator&& other); CommandIterator& operator=(CommandIterator&& other); // Shorthand constructor for acquiring CommandBlocks from a single CommandAllocator. explicit CommandIterator(CommandAllocator allocator); void AcquireCommandBlocks(std::vector<CommandAllocator> allocators); template <typename E> bool NextCommandId(E* commandId) { return NextCommandId(reinterpret_cast<uint32_t*>(commandId)); } template <typename T> T* NextCommand() { return static_cast<T*>(NextCommand(sizeof(T), alignof(T))); } template <typename T> T* NextData(size_t count) { return static_cast<T*>(NextData(sizeof(T) * count, alignof(T))); } // Sets iterator to the beginning of the commands without emptying the list. This method can // be used if iteration was stopped early and the iterator needs to be restarted. void Reset(); // This method must to be called after commands have been deleted. This indicates that the // commands have been submitted and they are no longer valid. void MakeEmptyAsDataWasDestroyed(); private: bool IsEmpty() const; DAWN_FORCE_INLINE bool NextCommandId(uint32_t* commandId) { char* idPtr = AlignPtr(mCurrentPtr, alignof(uint32_t)); DAWN_ASSERT(idPtr == reinterpret_cast<char*>(&mEndOfBlock) || idPtr + sizeof(uint32_t) <= mBlocks[mCurrentBlock].block.get() + mBlocks[mCurrentBlock].size); uint32_t id = *reinterpret_cast<uint32_t*>(idPtr); if (id != detail::kEndOfBlock) { mCurrentPtr = idPtr + sizeof(uint32_t); *commandId = id; return true; } return NextCommandIdInNewBlock(commandId); } bool NextCommandIdInNewBlock(uint32_t* commandId); DAWN_FORCE_INLINE void* NextCommand(size_t commandSize, size_t commandAlignment) { char* commandPtr = AlignPtr(mCurrentPtr, commandAlignment); DAWN_ASSERT(commandPtr + sizeof(commandSize) <= mBlocks[mCurrentBlock].block.get() + mBlocks[mCurrentBlock].size); mCurrentPtr = commandPtr + commandSize; return commandPtr; } DAWN_FORCE_INLINE void* NextData(size_t dataSize, size_t dataAlignment) { uint32_t id; bool hasId = NextCommandId(&id); DAWN_ASSERT(hasId); DAWN_ASSERT(id == detail::kAdditionalData); return NextCommand(dataSize, dataAlignment); } CommandBlocks mBlocks; // RAW_PTR_EXCLUSION: This is an extremely hot pointer during command iteration, but always // points to at least a valid uint32_t, either inside a block, or at mEndOfBlock. RAW_PTR_EXCLUSION char* mCurrentPtr = nullptr; size_t mCurrentBlock = 0; // Used to avoid a special case for empty iterators. uint32_t mEndOfBlock = detail::kEndOfBlock; }; class CommandAllocator : public NonCopyable { public: CommandAllocator(); ~CommandAllocator(); // NOTE: A moved-from CommandAllocator is reset to its initial empty state. CommandAllocator(CommandAllocator&&); CommandAllocator& operator=(CommandAllocator&&); // Frees all blocks held by the allocator and restores it to its initial empty state. void Reset(); bool IsEmpty() const; template <typename T, typename E> T* Allocate(E commandId) { static_assert(sizeof(E) == sizeof(uint32_t)); static_assert(alignof(E) == alignof(uint32_t)); static_assert(alignof(T) <= kMaxSupportedAlignment); T* result = reinterpret_cast<T*>(Allocate(static_cast<uint32_t>(commandId), sizeof(T), alignof(T))); if (!result) { return nullptr; } new (result) T; return result; } template <typename T> T* AllocateData(size_t count) { static_assert(alignof(T) <= kMaxSupportedAlignment); T* result = reinterpret_cast<T*>(AllocateData(sizeof(T) * count, alignof(T))); if (!result) { return nullptr; } for (size_t i = 0; i < count; i++) { new (result + i) T; } return result; } size_t GetCommandBlocksCount() const; private: // This is used for some internal computations and can be any power of two as long as code // using the CommandAllocator passes the static_asserts. static constexpr size_t kMaxSupportedAlignment = 8; // To avoid checking for overflows at every step of the computations we compute an upper // bound of the space that will be needed in addition to the command data. static constexpr size_t kWorstCaseAdditionalSize = sizeof(uint32_t) + kMaxSupportedAlignment + alignof(uint32_t) + sizeof(uint32_t); // The default value of mLastAllocationSize. static constexpr size_t kDefaultBaseAllocationSize = 2048; friend CommandIterator; CommandBlocks&& AcquireBlocks(); DAWN_FORCE_INLINE char* Allocate(uint32_t commandId, size_t commandSize, size_t commandAlignment) { DAWN_ASSERT(mCurrentPtr != nullptr); DAWN_ASSERT(mEndPtr != nullptr); DAWN_ASSERT(commandId != detail::kEndOfBlock); // It should always be possible to allocate one id, for kEndOfBlock tagging, DAWN_ASSERT(IsPtrAligned(mCurrentPtr, alignof(uint32_t))); DAWN_ASSERT(mEndPtr >= mCurrentPtr); DAWN_ASSERT(static_cast<size_t>(mEndPtr - mCurrentPtr) >= sizeof(uint32_t)); // The memory after the ID will contain the following: // - the current ID // - padding to align the command, maximum kMaxSupportedAlignment // - the command of size commandSize // - padding to align the next ID, maximum alignof(uint32_t) // - the next ID of size sizeof(uint32_t) // This can't overflow because by construction mCurrentPtr always has space for the next // ID. size_t remainingSize = static_cast<size_t>(mEndPtr - mCurrentPtr); // The good case were we have enough space for the command data and upper bound of the // extra required space. if ((remainingSize >= kWorstCaseAdditionalSize) && (remainingSize - kWorstCaseAdditionalSize >= commandSize)) { uint32_t* idAlloc = reinterpret_cast<uint32_t*>(mCurrentPtr); *idAlloc = commandId; char* commandAlloc = AlignPtr(mCurrentPtr + sizeof(uint32_t), commandAlignment); mCurrentPtr = AlignPtr(commandAlloc + commandSize, alignof(uint32_t)); return commandAlloc; } return AllocateInNewBlock(commandId, commandSize, commandAlignment); } char* AllocateInNewBlock(uint32_t commandId, size_t commandSize, size_t commandAlignment); DAWN_FORCE_INLINE char* AllocateData(size_t commandSize, size_t commandAlignment) { return Allocate(detail::kAdditionalData, commandSize, commandAlignment); } bool GetNewBlock(size_t minimumSize); void ResetPointers(); CommandBlocks mBlocks; size_t mLastAllocationSize = kDefaultBaseAllocationSize; // Data used for the block range at initialization so that the first call to Allocate sees // there is not enough space and calls GetNewBlock. This avoids having to special case the // initialization in Allocate. uint32_t mPlaceholderSpace[1] = {0}; // Pointers to the current range of allocation in the block. Guaranteed to allow for at // least one uint32_t if not nullptr, so that the special kEndOfBlock command id can always // be written. Nullptr iff the blocks were moved out. // RAW_PTR_EXCLUSION: These are extremely hot pointers during command allocation, but always // set to a valid slice (either the placeholder space, or a real allocated block). RAW_PTR_EXCLUSION char* mCurrentPtr = nullptr; RAW_PTR_EXCLUSION char* mEndPtr = nullptr; }; } // namespace dawn::native #endif // SRC_DAWN_NATIVE_COMMANDALLOCATOR_H_
0
0.972405
1
0.972405
game-dev
MEDIA
0.313121
game-dev
0.954489
1
0.954489
CompactMods/CompactMachines
3,223
neoforge-main/src/main/java/dev/compactmods/machines/compat/jei/CompactMachinesJeiPlugin.java
package dev.compactmods.machines.compat.jei; import dev.compactmods.machines.CompactMachinesCommon; import dev.compactmods.machines.api.CompactMachines; import dev.compactmods.machines.api.component.CMDataComponents; import dev.compactmods.machines.api.machine.MachineConstants; import dev.compactmods.machines.api.room.template.RoomTemplateHelper; import dev.compactmods.machines.machine.Machines; import dev.compactmods.machines.shrinking.Shrinking; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.ingredients.IIngredientType; import mezz.jei.api.ingredients.subtypes.ISubtypeInterpreter; import mezz.jei.api.ingredients.subtypes.UidContext; import mezz.jei.api.registration.IRecipeRegistration; import mezz.jei.api.registration.ISubtypeRegistration; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.neoforged.neoforge.server.ServerLifecycleHooks; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import javax.annotation.ParametersAreNullableByDefault; @JeiPlugin public class CompactMachinesJeiPlugin implements IModPlugin { @Override public ResourceLocation getPluginUid() { return CompactMachines.modRL("main"); } @Override public void registerRecipes(IRecipeRegistration registration) { registration.addIngredientInfo( Machines.Items.unboundColored(CompactMachinesCommon.BRAND_MACHINE_COLOR), VanillaTypes.ITEM_STACK, Component.translatable("jei.compactmachines.machines")); // Add all known template JEI infos RoomTemplateHelper.getTemplateHolders(ServerLifecycleHooks.getCurrentServer().registryAccess()) .map(Machines.Items::forNewRoom) .forEach(t -> registration.addIngredientInfo(t, VanillaTypes.ITEM_STACK, Component.translatable("jei.compactmachines.machines"))); registration.addIngredientInfo( new ItemStack(Shrinking.PERSONAL_SHRINKING_DEVICE.get()), VanillaTypes.ITEM_STACK, Component.translatable("jei.compactmachines.shrinking_device")); } @Override @ParametersAreNonnullByDefault public void registerItemSubtypes(ISubtypeRegistration registration) { registration.registerSubtypeInterpreter(VanillaTypes.ITEM_STACK, Machines.Items.UNBOUND_MACHINE.get(), new ISubtypeInterpreter<>() { @Override public @Nullable Object getSubtypeData(ItemStack ingredient, UidContext context) { return ingredient.get(CMDataComponents.ROOM_TEMPLATE_ID); } @Override public @NotNull String getLegacyStringSubtypeInfo(ItemStack ingredient, UidContext context) { return ""; } }); } }
0
0.77758
1
0.77758
game-dev
MEDIA
0.957613
game-dev
0.504788
1
0.504788
DarrenTsung/DTValidator
4,406
Validation/Editor/ValidationErrors/IValidationErrorExtensions.cs
#if UNITY_EDITOR using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.Events; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; using UnityEditor; namespace DTValidator.Internal { public static class IValidationErrorExtensions { // PRAGMA MARK - Public Interface public static Texture2D GetContextIcon(this IValidationError validationError) { if (validationError.ContextObject is GameObject) { return DTValidatorIcons.PrefabIcon; } else if (validationError.ContextObject is SceneAsset) { return DTValidatorIcons.SceneIcon; } else if (validationError.ContextObject is ScriptableObject) { return DTValidatorIcons.ScriptableObjectIcon; } else { Debug.LogWarning("Failed to get image because context object is not recognized type: " + validationError.ContextObject + "!"); return Texture2DUtil.ClearTexture; } } public static string GetContextObjectName(this IValidationError validationError) { object context = validationError.ContextObject; if (context == null) { Debug.LogWarning("Cannot get name for null context! Error: " + validationError); return null; } UnityEngine.Object contextObject = context as UnityEngine.Object; if (contextObject == null) { Debug.LogWarning("Cannot get name of null UnityEngine.Object context: " + contextObject); return null; } string path = AssetDatabase.GetAssetPath(contextObject); return Path.GetFileName(path); } public static void SelectInEditor(this IValidationError validationError) { bool selected = SelectObjectInEditor(validationError); if (!selected) { SelectContextInEditor(validationError); } } // PRAGMA MARK - Internal private static bool SelectObjectInEditor(IValidationError validationError) { if (!typeof(UnityEngine.Component).IsAssignableFrom(validationError.ObjectType) && !typeof(GameObject).IsAssignableFrom(validationError.ObjectType)) { return false; } SceneAsset sceneAsset = validationError.ContextObject as SceneAsset; if (sceneAsset == null) { return false; } string contextScenePath = AssetDatabase.GetAssetPath(sceneAsset); Scene loadedScene = default(Scene); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { var scene = EditorSceneManager.GetSceneAt(i); if (scene.path == contextScenePath) { loadedScene = scene; } } if (!loadedScene.IsValid()) { return false; } HashSet<GameObject> rootGameObjects = new HashSet<GameObject>(loadedScene.GetRootGameObjects()); UnityEngine.Object[] objects = UnityEngine.Object.FindObjectsOfType(validationError.ObjectType); if (objects.Length <= 0) { return false; } IEnumerable<UnityEngine.Object> objectsInScene; if (validationError.ObjectType.Equals(typeof(UnityEngine.GameObject))) { objectsInScene = objects.Where(o => rootGameObjects.Contains((o as UnityEngine.GameObject).GetRoot())); } else { objectsInScene = objects.Where(o => rootGameObjects.Contains((o as UnityEngine.Component).gameObject.GetRoot())); } UnityEngine.Object obj = objectsInScene.FirstOrDefault(o => o.GetLocalId() == validationError.ObjectLocalId); Transform targetTransform = null; UnityEngine.Component objectAsComponent = obj as UnityEngine.Component; if (objectAsComponent != null) { targetTransform = objectAsComponent.transform; } GameObject objectAsGameObject = obj as GameObject; if (objectAsGameObject != null) { targetTransform = objectAsGameObject.transform; } if (targetTransform == null) { return false; } Selection.activeTransform = targetTransform; EditorGUIUtility.PingObject(targetTransform); return true; } private static void SelectContextInEditor(IValidationError validationError) { object context = validationError.ContextObject; if (context == null) { Debug.LogWarning("Cannot select context for null context! Error: " + validationError); return; } UnityEngine.Object contextObject = context as UnityEngine.Object; if (contextObject == null) { Debug.LogWarning("Cannot select null UnityEngine.Object context: " + contextObject); return; } Selection.activeObject = contextObject; EditorGUIUtility.PingObject(contextObject); } } } #endif
0
0.815029
1
0.815029
game-dev
MEDIA
0.838605
game-dev
0.610857
1
0.610857
rovertronic/Mario-Builder-64
19,629
src/game/behaviors/mushroom_1up.inc.c
// mushroom_1up.inc.c // void bhv_1up_interact(void) { // if (obj_check_if_collided_with_object(o, gMarioObject)) { // play_sound(SOUND_GENERAL_COLLECT_1UP, gGlobalSoundSource); // #ifdef MUSHROOMS_HEAL // gMarioState->healCounter = 31; // #ifdef BREATH_METER // gMarioState->breathCounter = 31; // #endif // #endif // #ifdef ENABLE_LIVES // gMarioState->numLives++; // #endif // o->activeFlags = ACTIVE_FLAG_DEACTIVATED; // #if ENABLE_RUMBLE // queue_rumble_data(5, 80); // #endif // } // } // void bhv_1up_common_init(void) { // o->oMoveAnglePitch = -0x4000; // o->oGravity = 3.0f; // o->oFriction = 1.0f; // o->oBuoyancy = 1.0f; // } // //gMarioState->powerup // void bhv_1up_init(void) { // bhv_1up_common_init(); // #ifndef UNLOCK_ALL // if (o->oBehParams2ndByte == MUSHROOM_BP_REQUIRES_BOWSER_1) { // if (!(save_file_get_flags() & (SAVE_FLAG_HAVE_KEY_1 | SAVE_FLAG_UNLOCKED_BASEMENT_DOOR))) { // o->activeFlags = ACTIVE_FLAG_DEACTIVATED; // } // } else if (o->oBehParams2ndByte == MUSHROOM_BP_REQUIRES_BOWSER_2) { // if (!(save_file_get_flags() & (SAVE_FLAG_HAVE_KEY_2 | SAVE_FLAG_UNLOCKED_UPSTAIRS_DOOR))) { // o->activeFlags = ACTIVE_FLAG_DEACTIVATED; // } // } // #endif // } // void one_up_loop_in_air(void) { // if (o->oTimer < 5) { // o->oVelY = 40.0f; // } else { // o->oAngleVelPitch = -0x1000; // o->oMoveAnglePitch += o->oAngleVelPitch; // o->oVelY = coss(o->oMoveAnglePitch) * 30.0f + 2.0f; // o->oForwardVel = -sins(o->oMoveAnglePitch) * 30.0f; // } // } // void pole_1up_move_towards_mario(void) { // f32 dx = gMarioObject->header.gfx.pos[0] - o->oPosX; // f32 dy = gMarioObject->header.gfx.pos[1] - o->oPosY + 120.0f; // f32 dz = gMarioObject->header.gfx.pos[2] - o->oPosZ; // s16 targetPitch = atan2s(sqrtf(sqr(dx) + sqr(dz)), dy); // obj_turn_toward_object(o, gMarioObject, O_MOVE_ANGLE_YAW_INDEX, 0x1000); // o->oMoveAnglePitch = approach_s16_symmetric(o->oMoveAnglePitch, targetPitch, 0x1000); // o->oVelY = sins(o->oMoveAnglePitch) * 30.0f; // o->oForwardVel = coss(o->oMoveAnglePitch) * 30.0f; // bhv_1up_interact(); // } // void one_up_move_away_from_mario(s16 collisionFlags) { // o->oForwardVel = 8.0f; // o->oMoveAngleYaw = o->oAngleToMario + 0x8000; // bhv_1up_interact(); // if (collisionFlags & OBJ_COL_FLAG_HIT_WALL) { // o->oAction = MUSHROOM_ACT_DISAPPEARING; // } // if (!is_point_within_radius_of_mario(o->oPosX, o->oPosY, o->oPosZ, 3000)) { // o->oAction = MUSHROOM_ACT_DISAPPEARING; // } // } // void bhv_1up_walking_loop(void) { // object_step();// // switch (o->oAction) { // case MUSHROOM_ACT_INIT: // if (o->oTimer > 17) { // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // } // if (o->oTimer == 0) { // play_sound(SOUND_GENERAL2_1UP_APPEAR, gGlobalSoundSource); // } // one_up_loop_in_air(); // if (o->oTimer == 37) { // cur_obj_become_tangible(); // o->oAction = MUSHROOM_ACT_MOVING; // o->oForwardVel = 2.0f; // } // break; // case MUSHROOM_ACT_MOVING: // if (o->oTimer > 300) { // o->oAction = MUSHROOM_ACT_DISAPPEARING; // } // bhv_1up_interact(); // break; // case MUSHROOM_ACT_DISAPPEARING: // obj_flicker_and_disappear(o, 30); // bhv_1up_interact(); // break; // } // set_object_visibility(o, 3000); // } // void bhv_1up_running_away_loop(void) { // s16 collisionFlags = object_step(); // switch (o->oAction) { // case MUSHROOM_ACT_INIT: // if (o->oTimer > 17) { // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // } // if (o->oTimer == 0) { // play_sound(SOUND_GENERAL2_1UP_APPEAR, gGlobalSoundSource); // } // one_up_loop_in_air(); // if (o->oTimer == 37) { // cur_obj_become_tangible(); // o->oAction = MUSHROOM_ACT_MOVING; // o->oForwardVel = 8.0f; // } // break; // case MUSHROOM_ACT_MOVING: // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // one_up_move_away_from_mario(collisionFlags); // break; // case MUSHROOM_ACT_DISAPPEARING: // obj_flicker_and_disappear(o, 30); // bhv_1up_interact(); // break; // } // set_object_visibility(o, 3000); // } // void sliding_1up_move(void) { // s16 collisionFlags = object_step(); // if (collisionFlags & OBJ_COL_FLAG_GROUNDED) { // o->oForwardVel += 25.0f; // o->oVelY = 0.0f; // } else { // o->oForwardVel *= 0.98f; // } // if (o->oForwardVel > 40.0) { // o->oForwardVel = 40.0f; // } // if (!is_point_within_radius_of_mario(o->oPosX, o->oPosY, o->oPosZ, 5000)) { // o->oAction = MUSHROOM_ACT_DISAPPEARING; // } // } // void bhv_1up_sliding_loop(void) { // switch (o->oAction) { // case MUSHROOM_ACT_INIT: // set_object_visibility(o, 3000); // if (is_point_within_radius_of_mario(o->oPosX, o->oPosY, o->oPosZ, 1000)) { // o->oAction = MUSHROOM_ACT_MOVING; // } // break; // case MUSHROOM_ACT_MOVING: // sliding_1up_move(); // break; // case MUSHROOM_ACT_DISAPPEARING: // obj_flicker_and_disappear(o, 30); // bhv_1up_interact(); // break; // } // bhv_1up_interact(); // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // } // void bhv_1up_loop(void) { // bhv_1up_interact(); // set_object_visibility(o, 3000); // } // void bhv_1up_jump_on_approach_loop(void) { // s16 collisionFlags; // switch (o->oAction) { // case MUSHROOM_ACT_INIT: // if (is_point_within_radius_of_mario(o->oPosX, o->oPosY, o->oPosZ, 1000)) { // o->oVelY = 40.0f; // o->oAction = MUSHROOM_ACT_MOVING; // } // break; // case MUSHROOM_ACT_MOVING: // collisionFlags = object_step(); // one_up_move_away_from_mario(collisionFlags); // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // break; // case MUSHROOM_ACT_DISAPPEARING: // collisionFlags = object_step(); // bhv_1up_interact(); // obj_flicker_and_disappear(o, 30); // break; // } // set_object_visibility(o, 3000); // } // void bhv_1up_hidden_loop(void) { // s16 collisionFlags; // switch (o->oAction) { // case MUSHROOM_ACT_INIT: // o->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE; // if (o->o1UpHiddenTimesTriggered == o->oBehParams2ndByte) { // o->oVelY = 40.0f; // o->oAction = MUSHROOM_ACT_LOOP_IN_AIR; // o->header.gfx.node.flags &= ~GRAPH_RENDER_INVISIBLE; // play_sound(SOUND_GENERAL2_1UP_APPEAR, gGlobalSoundSource); // } // break; // case MUSHROOM_ACT_MOVING: // collisionFlags = object_step(); // one_up_move_away_from_mario(collisionFlags); // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // break; // case MUSHROOM_ACT_DISAPPEARING: // collisionFlags = object_step(); // bhv_1up_interact(); // obj_flicker_and_disappear(o, 30); // break; // case MUSHROOM_ACT_LOOP_IN_AIR: // collisionFlags = object_step(); // if (o->oTimer > 17) { // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // } // one_up_loop_in_air(); // if (o->oTimer == 37) { // cur_obj_become_tangible(); // o->oAction = MUSHROOM_ACT_MOVING; // o->oForwardVel = 8.0f; // } // break; // } // } // void bhv_1up_hidden_trigger_loop(void) { // if (obj_check_if_collided_with_object(o, gMarioObject)) { // struct Object *nearestHidden1up = cur_obj_nearest_object_with_behavior(bhvHidden1up); // if (nearestHidden1up != NULL) { // nearestHidden1up->o1UpHiddenTimesTriggered++; // } // o->activeFlags = ACTIVE_FLAG_DEACTIVATED; // } // } // void bhv_1up_hidden_in_pole_loop(void) { // switch (o->oAction) { // case MUSHROOM_ACT_INIT: // o->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE; // if (o->o1UpHiddenTimesTriggered == o->oBehParams2ndByte) { // o->oVelY = 40.0f; // o->oAction = MUSHROOM_ACT_LOOP_IN_AIR; // o->header.gfx.node.flags &= ~GRAPH_RENDER_INVISIBLE; // play_sound(SOUND_GENERAL2_1UP_APPEAR, gGlobalSoundSource); // } // break; // case MUSHROOM_ACT_MOVING: // pole_1up_move_towards_mario(); // object_step(); // break; // case MUSHROOM_ACT_LOOP_IN_AIR: // object_step(); // if (o->oTimer > 17) { // spawn_object(o, MODEL_NONE, bhvSparkleSpawn); // } // one_up_loop_in_air(); // if (o->oTimer == 37) { // cur_obj_become_tangible(); // o->oAction = MUSHROOM_ACT_MOVING; // o->oForwardVel = 10.0f; // } // break; // } // } // void bhv_1up_hidden_in_pole_trigger_loop(void) { // if (obj_check_if_collided_with_object(o, gMarioObject)) { // struct Object *nearestHidden1upInPole = cur_obj_nearest_object_with_behavior(bhvHidden1upInPole); // if (nearestHidden1upInPole != NULL) { // nearestHidden1upInPole->o1UpHiddenTimesTriggered++; // } // o->activeFlags = ACTIVE_FLAG_DEACTIVATED; // } // } // void bhv_1up_hidden_in_pole_spawner_loop(void) { // if (is_point_within_radius_of_mario(o->oPosX, o->oPosY, o->oPosZ, 700)) { // s8 i; // spawn_object_relative(2, 0, 50, 0, o, MODEL_1UP, bhvHidden1upInPole); // for (i = 0; i < 2; i++) { // spawn_object_relative(0, 0, i * -200, 0, o, MODEL_NONE, bhvHidden1upInPoleTrigger); // } // o->activeFlags = ACTIVE_FLAG_DEACTIVATED; // } // } extern u8 bullet_fuel; void bhv_crowbar_power_loop() { u8 power = (1 << o->oBehParams2ndByte); if (o->oAction == 0) { if ((o->oDistanceToMario < MB64_DRAWDIST_LOW) && !(gGlobalTimer & 3)) spawn_object(o, MODEL_NONE, bhvSparkleSpawn); o->oFaceAngleYaw += 0x400; o->oFaceAnglePitch = 0x1A00; if (obj_check_if_collided_with_object(o, gMarioObject)) { play_sound(SOUND_MENU_EXIT_PIPE, gGlobalSoundSource); gMarioState->powerup |= power; // Crowbar and rocket boots incompatible if (power == 1) { gMarioState->flags &= ~MARIO_WING_CAP; gMarioState->RFuel = 0; } else { bullet_fuel = 60; } o->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE; o->oAction = 1; } } else if (o->oAction == 1) { if (o->oTimer > 30 * 5) { o->oAction = 0; o->header.gfx.node.flags &= ~GRAPH_RENDER_INVISIBLE; } } } void bhv_crowbar_attack_loop() { o->oWallHitboxRadius = 80.f; s16 sp1E = object_step_without_floor_orient(); struct Object *sp1C; //sp1C = cur_obj_nearest_object_with_behavior(bhvMetalCrate); o->oFaceAngleYaw += 8000; if (o->oFaceAngleYaw > 0x10000) { cur_obj_play_sound_2(SOUND_ACTION_SIDE_FLIP_UNK); o->oFaceAngleYaw = 0; } if (o->oInteractStatus & INT_STATUS_INTERACTED) { cur_obj_play_sound_2(SOUND_ACTION_METAL_STEP); } obj_attack_collided_from_other_object(o, ATTACK_FAST_ATTACK); obj_coin_collected_by_other_object(o); if (o->oAction == 0) { if (o->oTimer > 5) { cur_obj_become_tangible(); } if (sp1E & 2) { cur_obj_play_sound_2(SOUND_ACTION_METAL_STEP); } o->oForwardVel --; if (o->oTimer > 40) { o->oAction = 1; o->oTimer = 0; o->oMoveAngleYaw += 0x8000; } } if (o->oAction == 1) { f32 sp34 = gMarioObject->header.gfx.pos[0] - o->oPosX; f32 sp30 = gMarioObject->header.gfx.pos[1] + 120.0f - o->oPosY; f32 sp2C = gMarioObject->header.gfx.pos[2] - o->oPosZ; s16 sp2A = atan2s(sqrtf(sqr(sp34) + sqr(sp2C)), sp30); obj_turn_toward_object(o, gMarioObject, 16, 0x1000); o->oMoveAnglePitch = approach_s16_symmetric(o->oMoveAnglePitch, sp2A, 0x1000); o->oVelY = sins(o->oMoveAnglePitch) * 80.0f; o->oForwardVel = coss(o->oMoveAnglePitch) * 80.0f; //DIE if (o->oDistanceToMario < 200.0f) { gMarioState->powerup |= 1; mark_obj_for_deletion(o); } } } //>forwardVel mario // void bhv_zipline_loop() { // if (o->oAction == 0) { // if ((o->oDistanceToMario < 200.0f)&&(gMarioState->powerup == 1)) { // gMarioState->faceAngle[0] = o->oFaceAngleYaw; // gMarioObject->header.gfx.angle[1] = o->oFaceAngleYaw; // set_mario_action(gMarioState, ACT_ZIPLINE, 0); // o->oAction = 1; // o->oForwardVel = 20; // o->oHomeY = gMarioState->forwardVel; // } // } // if (o->oAction == 1) { // o->oForwardVel += o->oHomeY; // if (o->oHomeY < 40.0f) { // o->oHomeY += 1.0f; // } // gMarioState->pos[0] = o->oPosX + o->oForwardVel * sins(o->oFaceAngleYaw); // gMarioState->pos[1] = o->oPosY + o->oForwardVel * -sins(o->oFaceAnglePitch); // gMarioState->pos[2] = o->oPosZ + o->oForwardVel * coss(o->oFaceAngleYaw); // gMarioState->faceAngle[0] = o->oFaceAngleYaw; // gMarioObject->header.gfx.angle[1] = o->oFaceAngleYaw; // if (o->oForwardVel > o->oBehParams2ndByte*100.0f) { // o->oAction = 0; // gMarioState->forwardVel = o->oHomeY; // set_mario_action(gMarioState, ACT_FREEFALL, 0); // } // } // } void bhv_item_bubble_loop() { s32 behparam1 = (gCurrentObject->oBehParams >> 24) & 0xFF; struct Object *bubble; f32 BubDist; BubDist = 999.0f; bubble = cur_obj_nearest_object_with_behavior(bhvItemBubble); if (bubble != NULL) { BubDist = lateral_dist_between_objects(o,bubble); } switch (o->oAction) { case 0: o->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE; if (o->oDistanceToMario < 3000) { o->header.gfx.node.flags &= ~GRAPH_RENDER_INVISIBLE; o->oAction = 1; switch(o->oBehParams2ndByte) { case 0: o->prevObj = spawn_object(o, MODEL_YELLOW_COIN, bhvMovingYellowCoin); break; case 1: o->prevObj = spawn_object(o, MODEL_1UP, bhv1upSliding); break; case 2: o->prevObj = spawn_object(o, 0xEF, bhvMovingGreenCoin); break; case 3: o->prevObj = spawn_object(o, MODEL_GOOMBA, bhvGoomba); break; case 4: o->prevObj = spawn_object(o, MODEL_THWOMP, bhvThwomp); break; } } break; case 1: //set object o->prevObj->oTimer = 0; o->prevObj->oVelY = 0; o->prevObj->oPosX = o->oPosX; o->prevObj->oPosZ = o->oPosZ; o->prevObj->oAction = 0; o->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE; o->prevObj->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE; if (o->oDistanceToMario < 3000) { o->prevObj->header.gfx.node.flags &= ~GRAPH_RENDER_INVISIBLE; o->header.gfx.node.flags &= ~GRAPH_RENDER_INVISIBLE; if (o->oBehParams2ndByte > 2) { o->prevObj->oFaceAngleRoll = 0x7FFF; o->prevObj->oPosY = o->oPosY+140; } else { o->prevObj->oPosY = o->oPosY+70; } //Move o->oPosY = o->oHomeY + (55.0f * sins(o->oTimer*500)); if (o->oBehParams2ndByte > 2) { //CHASE MARIO CUZ UR EVIL if (cur_obj_lateral_dist_from_mario_to_home() > 2000.0f) { o->oAngleToMario = cur_obj_angle_to_home(); o->oForwardVel = 5.0f; } else { o->oAngleToMario = obj_angle_to_object(o, gMarioObject); o->oForwardVel = 20.0f; } cur_obj_rotate_yaw_toward(o->oAngleToMario, 0x400); cur_obj_move_using_vel_and_gravity(); } } //collision if ((o->oDistanceToMario < 200)||(BubDist < 200)) { cur_obj_play_sound_2(SOUND_OBJ2_PIRANHA_PLANT_BITE); spawn_object(o,MODEL_BUBBLE,bhvKoopaShellFlame); spawn_object(o,MODEL_BUBBLE,bhvKoopaShellFlame); spawn_object(o,MODEL_BUBBLE,bhvKoopaShellFlame); o->prevObj->oFaceAngleRoll = 0; o->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE; o->oAction = 5; o->oTimer = 0; } break; case 5: if (o->oTimer > 30) { o->activeFlags = ACTIVE_FLAG_DEACTIVATED; } break; } } //2024 rovert here, if you're reviewing my resume and stumble upon this code, no you didn't : ) // u8 shitcum_animstate_table[] = {0,0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,2,2,1,1}; // //im eating fucking doritos right now // // im such a sfucking labzy slob // //shut the fuck up bruh ^^^ // void bhv_dragon_coin_loop() { // //change B pressed to not B pressed // if (gMarioState->IsYoshi) { // o->oAnimState = shitcum_animstate_table[o->oTimer]; // if (o->oTimer == 19) { // o->oTimer = 0; // } // if (o->oDistanceToMario < 100.0f) { // gMarioState->numCoins += 2; // gMarioState->YoshiCoins ++; // spawn_object(o, MODEL_SPARKLES, bhvCoinSparklesSpawner); // mark_obj_for_deletion(o); // } // } // else // { // o->oAnimState = 4; // o->oTimer = 0; // } // }
0
0.79506
1
0.79506
game-dev
MEDIA
0.961901
game-dev
0.760969
1
0.760969
MewoLab/AquaMai
19,821
AquaMai.Config/Migration/ConfigMigration_V1_0_V2_0.cs
using System; using System.Collections.Generic; using AquaMai.Config.Interfaces; using AquaMai.Config.Types; namespace AquaMai.Config.Migration; public class ConfigMigration_V1_0_V2_0 : IConfigMigration { public string FromVersion => "1.0"; public string ToVersion => "2.0"; public ConfigView Migrate(ConfigView src) { var dst = new ConfigView(); dst.SetValue("Version", ToVersion); // UX (legacy) MapBooleanTrueToSectionEnable(src, dst, "UX.TestProof", "GameSystem.TestProof"); if (src.GetValueOrDefault<bool>("UX.QuickSkip")) { // NOTE: UX.QuickSkip was a 4-in-1 large patch in earlier V1, then split since ModKeyMap was introduced. dst.SetValue("UX.OneKeyEntryEnd.Key", "Service"); dst.SetValue("UX.OneKeyEntryEnd.LongPress", true); dst.SetValue("UX.OneKeyRetrySkip.RetryKey", "Service"); dst.SetValue("UX.OneKeyRetrySkip.RetryLongPress", false); dst.SetValue("UX.OneKeyRetrySkip.SkipKey", "Select1P"); dst.SetValue("UX.OneKeyRetrySkip.SkipLongPress", false); dst.EnsureDictionary("GameSystem.QuickRetry"); } if (src.GetValueOrDefault<bool>("UX.HideSelfMadeCharts")) { dst.SetValue("UX.HideSelfMadeCharts.Key", "Service"); dst.SetValue("UX.HideSelfMadeCharts.LongPress", false); } MapBooleanTrueToSectionEnable(src, dst, "UX.LoadJacketPng", "GameSystem.Assets.LoadLocalImages"); MapBooleanTrueToSectionEnable(src, dst, "UX.SkipWarningScreen", "Tweaks.TimeSaving.SkipStartupWarning"); MapBooleanTrueToSectionEnable(src, dst, "UX.SkipToMusicSelection", "Tweaks.TimeSaving.EntryToMusicSelection"); MapBooleanTrueToSectionEnable(src, dst, "UX.SkipEventInfo", "Tweaks.TimeSaving.SkipEventInfo"); MapBooleanTrueToSectionEnable(src, dst, "UX.SelectionDetail", "UX.SelectionDetail"); if (src.GetValueOrDefault<bool>("UX.CustomNoteSkin") || src.GetValueOrDefault<bool>("UX.CustomSkins")) { dst.SetValue("Fancy.CustomSkins.SkinsDir", "LocalAssets/Skins"); } MapBooleanTrueToSectionEnable(src, dst, "UX.JudgeDisplay4B", "Fancy.GamePlay.JudgeDisplay4B"); MapBooleanTrueToSectionEnable(src, dst, "UX.CustomTrackStartDiff", "Fancy.CustomTrackStartDiff"); MapBooleanTrueToSectionEnable(src, dst, "UX.TrackStartProcessTweak", "Fancy.GamePlay.TrackStartProcessTweak"); MapBooleanTrueToSectionEnable(src, dst, "UX.DisableTrackStartTabs", "Fancy.GamePlay.DisableTrackStartTabs"); MapBooleanTrueToSectionEnable(src, dst, "UX.RealisticRandomJudge", "Fancy.GamePlay.RealisticRandomJudge"); // Utils (legacy) if (src.GetValueOrDefault<bool>("Utils.Windowed") || src.GetValueOrDefault<int>("Utils.Width") != 0 || src.GetValueOrDefault<int>("Utils.Height") != 0) { // NOTE: the default "false, 0, 0" was effective earlier in V1, but won't be migrated as enabled in V2. MapValueOrDefaultToEntryValue(src, dst, "Utils.Windowed", "GameSystem.Window.Windowed", false); MapValueOrDefaultToEntryValue(src, dst, "Utils.Width", "GameSystem.Window.Width", 0); MapValueOrDefaultToEntryValue(src, dst, "Utils.Height", "GameSystem.Window.Height", 0); } if (src.GetValueOrDefault<bool>("Utils.PracticeMode") || src.GetValueOrDefault<bool>("Utils.PractiseMode")) // Typo of typo is the correct word { dst.SetValue("UX.PracticeMode.Key", "Test"); dst.SetValue("UX.PracticeMode.LongPress", false); } // Fix (legacy) MapBooleanTrueToSectionEnable(src, dst, "Fix.SlideJudgeTweak", "Fancy.GamePlay.BreakSlideJudgeBlink"); MapBooleanTrueToSectionEnable(src, dst, "Fix.BreakSlideJudgeBlink", "Fancy.GamePlay.BreakSlideJudgeBlink"); MapBooleanTrueToSectionEnable(src, dst, "Fix.SlideJudgeTweak", "Fancy.GamePlay.FanJudgeFlip"); MapBooleanTrueToSectionEnable(src, dst, "Fix.FanJudgeFlip", "Fancy.GamePlay.FanJudgeFlip"); // NOTE: This (FixCircleSlideJudge) was enabled by default in V1, but non-default in V2 since it has visual changes MapBooleanTrueToSectionEnable(src, dst, "Fix.SlideJudgeTweak", "Fancy.GamePlay.AlignCircleSlideJudgeDisplay"); MapBooleanTrueToSectionEnable(src, dst, "Fix.FixCircleSlideJudge", "Fancy.GamePlay.AlignCircleSlideJudgeDisplay"); // Performance (legacy) MapBooleanTrueToSectionEnable(src, dst, "Performance.ImproveLoadSpeed", "Tweaks.TimeSaving.SkipStartupDelays"); // TimeSaving (legacy) MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.ShowNetErrorDetail", "Utils.ShowNetErrorDetail"); // UX MapValueToEntryValueIfNonNullOrDefault(src, dst, "UX.Locale", "General.Locale", ""); MapBooleanTrueToSectionEnable(src, dst, "UX.SinglePlayer", "GameSystem.SinglePlayer"); MapBooleanTrueToSectionEnable(src, dst, "UX.HideMask", "Fancy.HideMask"); MapBooleanTrueToSectionEnable(src, dst, "UX.LoadAssetsPng", "GameSystem.Assets.LoadLocalImages"); MapBooleanTrueToSectionEnable(src, dst, "UX.LoadAssetBundleWithoutManifest", "GameSystem.Assets.LoadAssetBundleWithoutManifest"); MapBooleanTrueToSectionEnable(src, dst, "UX.RandomBgm", "Fancy.RandomBgm"); MapBooleanTrueToSectionEnable(src, dst, "UX.DemoMaster", "Fancy.DemoMaster"); MapBooleanTrueToSectionEnable(src, dst, "UX.ExtendTimer", "GameSystem.DisableTimeout"); MapBooleanTrueToSectionEnable(src, dst, "UX.ImmediateSave", "UX.ImmediateSave"); MapBooleanTrueToSectionEnable(src, dst, "UX.LoadLocalBga", "GameSystem.Assets.UseJacketAsDummyMovie"); if (src.GetValueOrDefault<bool>("UX.CustomFont")) { dst.SetValue("GameSystem.Assets.Fonts.Paths", "LocalAssets/font.ttf"); dst.SetValue("GameSystem.Assets.Fonts.AddAsFallback", false); } MapBooleanTrueToSectionEnable(src, dst, "UX.TouchToButtonInput", "GameSystem.TouchToButtonInput"); MapBooleanTrueToSectionEnable(src, dst, "UX.HideHanabi", "Fancy.GamePlay.HideHanabi"); MapBooleanTrueToSectionEnable(src, dst, "UX.SlideFadeInTweak", "Fancy.GamePlay.SlideFadeInTweak"); MapBooleanTrueToSectionEnable(src, dst, "UX.JudgeAccuracyInfo", "UX.JudgeAccuracyInfo"); MapValueToEntryValueIfNonNullOrDefault(src, dst, "UX.CustomVersionString", "Fancy.CustomVersionString.VersionString", ""); MapValueToEntryValueIfNonNullOrDefault(src, dst, "UX.CustomPlaceName", "Fancy.CustomPlaceName.PlaceName", ""); MapValueToEntryValueIfNonNullOrDefault(src, dst, "UX.ExecOnIdle", "Fancy.Triggers.ExecOnIdle", ""); MapValueToEntryValueIfNonNullOrDefault(src, dst, "UX.ExecOnEntry", "Fancy.Triggers.ExecOnEntry", ""); // Cheat var unlockTickets = src.GetValueOrDefault<bool>("Cheat.TicketUnlock"); var unlockMaps = src.GetValueOrDefault<bool>("Cheat.MapUnlock"); var unlockUtage = src.GetValueOrDefault<bool>("Cheat.UnlockUtage"); if (unlockTickets || unlockMaps || unlockUtage) { dst.SetValue("GameSystem.Unlock.Tickets", unlockTickets); dst.SetValue("GameSystem.Unlock.Maps", unlockMaps); dst.SetValue("GameSystem.Unlock.Utage", unlockUtage); } // Fix MapBooleanTrueToSectionEnable(src, dst, "Fix.SkipVersionCheck", "Tweaks.SkipUserVersionCheck"); if (!src.GetValueOrDefault<bool>("Fix.RemoveEncryption")) { dst.SetValue("GameSystem.RemoveEncryption.Disabled", true); // Enabled by default in V2 } if (!src.GetValueOrDefault<bool>("Fix.ForceAsServer", true)) { dst.SetValue("GameSettings.ForceAsServer.Disabled", true); // Enabled by default in V2 } if (src.GetValueOrDefault<bool>("Fix.ForceFreePlay")) { dst.SetValue("GameSettings.CreditConfig.IsFreePlay", true); } if (src.GetValueOrDefault<bool>("Fix.ForcePaidPlay")) { dst.SetValue("GameSettings.CreditConfig.IsFreePlay", false); dst.SetValue("GameSettings.CreditConfig.LockCredits", 24u); } MapValueToEntryValueIfNonNullOrDefault(src, dst, "Fix.ExtendNotesPool", "Fancy.GamePlay.ExtendNotesPool.Count", 0); MapBooleanTrueToSectionEnable(src, dst, "Fix.FrameRateLock", "Tweaks.LockFrameRate"); if (src.GetValueOrDefault<bool>("Font.FontFix") && !src.GetValueOrDefault<bool>("UX.CustomFont")) { dst.SetValue("GameSystem.Assets.Fonts.Paths", "%SYSTEMROOT%/Fonts/msyhbd.ttc"); dst.SetValue("GameSystem.Assets.Fonts.AddAsFallback", true); } MapBooleanTrueToSectionEnable(src, dst, "Fix.RealisticRandomJudge", "Fancy.GamePlay.RealisticRandomJudge"); if (src.GetValueOrDefault<bool>("UX.SinglePlayer")) { if (src.TryGetValue("Fix.HanabiFix", out bool hanabiFix)) { // If it's enabled or disabled explicitly, use the value, otherwise left empty use the default V2 value (enabled). dst.SetValue("GameSystem.SinglePlayer.FixHanabi", hanabiFix); } } MapBooleanTrueToSectionEnable(src, dst, "Fix.IgnoreAimeServerError", "Tweaks.IgnoreAimeServerError"); MapBooleanTrueToSectionEnable(src, dst, "Fix.TouchResetAfterTrack", "Tweaks.ResetTouchAfterTrack"); // Utils MapBooleanTrueToSectionEnable(src, dst, "Utils.LogUserId", "Utils.LogUserId"); MapValueToEntryValueIfNonNullOrDefault<double>(src, dst, "Utils.JudgeAdjustA", "GameSettings.JudgeAdjust.A", 0); MapValueToEntryValueIfNonNullOrDefault<double>(src, dst, "Utils.JudgeAdjustB", "GameSettings.JudgeAdjust.B", 0); MapValueToEntryValueIfNonNullOrDefault(src, dst, "Utils.TouchDelay", "GameSettings.JudgeAdjust.TouchDelay", 0u); MapBooleanTrueToSectionEnable(src, dst, "Utils.SelectionDetail", "UX.SelectionDetail"); MapBooleanTrueToSectionEnable(src, dst, "Utils.ShowNetErrorDetail", "Utils.ShowNetErrorDetail"); MapBooleanTrueToSectionEnable(src, dst, "Utils.ShowErrorLog", "Utils.ShowErrorLog"); MapBooleanTrueToSectionEnable(src, dst, "Utils.FrameRateDisplay", "Utils.DisplayFrameRate"); MapValueToEntryValueIfNonNullOrDefault(src, dst, "Utils.TouchPanelBaudRate", "GameSystem.TouchPanelBaudRate.BaudRate", 0); // TimeSaving MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.SkipWarningScreen", "Tweaks.TimeSaving.SkipStartupWarning"); MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.ImproveLoadSpeed", "Tweaks.TimeSaving.SkipStartupDelays"); MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.SkipToMusicSelection", "Tweaks.TimeSaving.EntryToMusicSelection"); MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.SkipEventInfo", "Tweaks.TimeSaving.SkipEventInfo"); MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.IWontTapOrSlideVigorously", "Tweaks.TimeSaving.IWontTapOrSlideVigorously"); MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.SkipGameOverScreen", "Tweaks.TimeSaving.SkipGoodbyeScreen"); MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.SkipTrackStart", "Tweaks.TimeSaving.SkipTrackStart"); MapBooleanTrueToSectionEnable(src, dst, "TimeSaving.ShowQuickEndPlay", "UX.QuickEndPlay"); // Visual if (src.GetValueOrDefault<bool>("Visual.CustomSkins")) { dst.SetValue("Fancy.CustomSkins.SkinsDir", "LocalAssets/Skins"); } MapBooleanTrueToSectionEnable(src, dst, "Visual.JudgeDisplay4B", "Fancy.GamePlay.JudgeDisplay4B"); MapBooleanTrueToSectionEnable(src, dst, "Visual.CustomTrackStartDiff", "Fancy.CustomTrackStartDiff"); MapBooleanTrueToSectionEnable(src, dst, "Visual.TrackStartProcessTweak", "Fancy.GamePlay.TrackStartProcessTweak"); MapBooleanTrueToSectionEnable(src, dst, "Visual.DisableTrackStartTabs", "Fancy.GamePlay.DisableTrackStartTabs"); MapBooleanTrueToSectionEnable(src, dst, "Visual.FanJudgeFlip", "Fancy.GamePlay.FanJudgeFlip"); MapBooleanTrueToSectionEnable(src, dst, "Visual.BreakSlideJudgeBlink", "Fancy.GamePlay.BreakSlideJudgeBlink"); MapBooleanTrueToSectionEnable(src, dst, "Visual.SlideArrowAnimation", "Fancy.GamePlay.SlideArrowAnimation"); MapBooleanTrueToSectionEnable(src, dst, "Visual.SlideLayerReverse", "Fancy.GamePlay.SlideLayerReverse"); // ModKeyMap var keyQuickSkip = src.GetValueOrDefault("ModKeyMap.QuickSkip", "None"); var keyInGameRetry = src.GetValueOrDefault("ModKeyMap.InGameRetry", "None"); var keyInGameSkip = src.GetValueOrDefault("ModKeyMap.InGameSkip", "None"); var keyPractiseMode = src.GetValueOrDefault("ModKeyMap.PractiseMode", "None"); var keyHideSelfMadeCharts = src.GetValueOrDefault("ModKeyMap.HideSelfMadeCharts", "None"); if (keyQuickSkip != "None") { dst.SetValue("UX.OneKeyEntryEnd.Key", keyQuickSkip); MapValueToEntryValueIfNonNull<bool>(src, dst, "ModKeyMap.QuickSkipLongPress", "UX.OneKeyEntryEnd.LongPress"); } if (keyInGameRetry != "None" || keyInGameSkip != "None") { dst.SetValue("UX.OneKeyRetrySkip.RetryKey", keyInGameRetry); if (keyInGameRetry != "None") { MapValueToEntryValueIfNonNull<bool>(src, dst, "ModKeyMap.InGameRetryLongPress", "UX.OneKeyRetrySkip.RetryLongPress"); } dst.SetValue("UX.OneKeyRetrySkip.SkipKey", keyInGameSkip); if (keyInGameSkip != "None") { MapValueToEntryValueIfNonNull<bool>(src, dst, "ModKeyMap.InGameSkipLongPress", "UX.OneKeyRetrySkip.SkipLongPress"); } } if (keyPractiseMode != "None") { dst.SetValue("UX.PracticeMode.Key", keyPractiseMode); MapValueToEntryValueIfNonNull<bool>(src, dst, "ModKeyMap.PractiseModeLongPress", "UX.PracticeMode.LongPress"); } if (keyHideSelfMadeCharts != "None") { dst.SetValue("UX.HideSelfMadeCharts.Key", keyHideSelfMadeCharts); MapValueToEntryValueIfNonNull<bool>(src, dst, "ModKeyMap.HideSelfMadeChartsLongPress", "UX.HideSelfMadeCharts.LongPress"); } MapBooleanTrueToSectionEnable(src, dst, "ModKeyMap.EnableNativeQuickRetry", "GameSystem.QuickRetry"); if (src.TryGetValue<string>("ModKeyMap.TestMode", out var testMode) && testMode != "" && testMode != "Test") { dst.SetValue("DeprecationWarning.v1_0_ModKeyMap_TestMode", true); } MapBooleanTrueToSectionEnable(src, dst, "ModKeyMap.TestModeLongPress", "GameSystem.TestProof"); // WindowState if (src.GetValueOrDefault<bool>("WindowState.Enable")) { MapValueOrDefaultToEntryValue(src, dst, "WindowState.Windowed", "GameSystem.Window.Windowed", false); MapValueOrDefaultToEntryValue(src, dst, "WindowState.Width", "GameSystem.Window.Width", 0); MapValueOrDefaultToEntryValue(src, dst, "WindowState.Height", "GameSystem.Window.Height", 0); } // CustomCameraId if (src.GetValueOrDefault<bool>("CustomCameraId.Enable")) { dst.EnsureDictionary("GameSystem.CustomCameraId"); MapValueToEntryValueIfNonNullOrDefault(src, dst, "CustomCameraId.PrintCameraList", "GameSystem.CustomCameraId.PrintCameraList", false); MapValueToEntryValueIfNonNullOrDefault(src, dst, "CustomCameraId.LeftQrCamera", "GameSystem.CustomCameraId.LeftQrCamera", 0); MapValueToEntryValueIfNonNullOrDefault(src, dst, "CustomCameraId.RightQrCamera", "GameSystem.CustomCameraId.RightQrCamera", 0); MapValueToEntryValueIfNonNullOrDefault(src, dst, "CustomCameraId.PhotoCamera", "GameSystem.CustomCameraId.PhotoCamera", 0); MapValueToEntryValueIfNonNullOrDefault(src, dst, "CustomCameraId.ChimeCamera", "GameSystem.CustomCameraId.ChimeCamera", 0); } // TouchSensitivity if (src.GetValueOrDefault<bool>("TouchSensitivity.Enable")) { dst.EnsureDictionary("GameSettings.TouchSensitivity"); var areas = new[] { "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "C1", "C2", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", }; foreach (var area in areas) { MapValueToEntryValueIfNonNull<int>(src, dst, $"TouchSensitivity.{area}", $"GameSettings.TouchSensitivity.{area}"); } } // CustomKeyMap if (src.GetValueOrDefault<bool>("CustomKeyMap.Enable")) { dst.EnsureDictionary("GameSystem.KeyMap"); var keys = new[] { "Test", "Service", "Button1_1P", "Button3_1P", "Button4_1P", "Button2_1P", "Button5_1P", "Button6_1P", "Button7_1P", "Button8_1P", "Select_1P", "Button1_2P", "Button2_2P", "Button3_2P", "Button4_2P", "Button5_2P", "Button6_2P", "Button7_2P", "Button8_2P", "Select_2P" }; foreach (var key in keys) { if (src.TryGetValue<string>($"CustomKeyMap.{key}", out var value) && Enum.TryParse<KeyCodeID>(value, out var keyCode)) { dst.SetValue($"GameSystem.KeyMap.{key}", keyCode.ToString()); } } } // MaimaiDX2077 (WTF is the name?) MapBooleanTrueToSectionEnable(src, dst, "MaimaiDX2077.CustomNoteTypePatch", "Fancy.GamePlay.CustomNoteTypes"); // Default enabled in V2 dst.EnsureDictionary("GameSystem.RemoveEncryption"); dst.EnsureDictionary("GameSettings.ForceAsServer"); return dst; } // An value in the old config maps to an entry value in the new config. // Any existing value, including zero, is valid. private void MapValueToEntryValueIfNonNull<T>(IConfigView src, ConfigView dst, string srcKey, string dstKey) { if (src.TryGetValue<T>(srcKey, out var value)) { dst.SetValue(dstKey, value); } } // An value in the old config maps to an entry value in the new config. // Null or default value is ignored. private void MapValueToEntryValueIfNonNullOrDefault<T>(IConfigView src, ConfigView dst, string srcKey, string dstKey, T defaultValue) { if (src.TryGetValue<T>(srcKey, out var value) && !EqualityComparer<T>.Default.Equals(value, defaultValue)) { dst.SetValue(dstKey, value); } } // An value in the old config maps to an entry value in the new config. // Null value is replaced with a default value. private void MapValueOrDefaultToEntryValue<T>(IConfigView src, ConfigView dst, string srcKey, string dstKey, T defaultValue) { if (src.TryGetValue<T>(srcKey, out var value)) { dst.SetValue(dstKey, value); } else { dst.SetValue(dstKey, defaultValue); } } // An boolean value in the old config maps to a default-off section's enable in the new config. private void MapBooleanTrueToSectionEnable(IConfigView src, ConfigView dst, string srcKey, string dstKey) { if (src.GetValueOrDefault<bool>(srcKey)) { dst.EnsureDictionary(dstKey); } } }
0
0.803066
1
0.803066
game-dev
MEDIA
0.603552
game-dev
0.867859
1
0.867859
mordentral/VRExpansionPlugin
8,515
VRExpansionPlugin/Source/VRExpansionPlugin/Public/Interactibles/VRButtonComponent.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "VRInteractibleFunctionLibrary.h" #include "VRButtonComponent.generated.h" /** * */ // VR Button Types UENUM(Blueprintable) enum class EVRButtonType : uint8 { Btn_Press, Btn_Toggle_Return, Btn_Toggle_Stay }; // VR Button SyncOptions UENUM(Blueprintable) enum class EVRStateChangeAuthorityType : uint8 { /* Button state can be changed on all connections */ CanChangeState_All, /* Button state can be changed only on the server */ CanChangeState_Server, /* Button state can be changed only on the owner of the interacting primitive */ CanChangeState_Owner }; /** Delegate for notification when the button state changes. */ DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FVRButtonStateChangedSignature, bool, ButtonState, AActor *, InteractingActor, UPrimitiveComponent *, InteractingComponent); /** Delegate for notification when the begins a new interaction. */ DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FVRButtonStartedInteractionSignature, AActor *, InteractingActor, UPrimitiveComponent *, InteractingComponent); UCLASS(Blueprintable, meta = (BlueprintSpawnableComponent), ClassGroup = (VRExpansionPlugin)) class VREXPANSIONPLUGIN_API UVRButtonComponent : public UStaticMeshComponent { GENERATED_BODY() public: UVRButtonComponent(const FObjectInitializer& ObjectInitializer); ~UVRButtonComponent(); UFUNCTION() void OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); UFUNCTION() void OnOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex); virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override; virtual void BeginPlay() override; UFUNCTION(BlueprintPure, Category = "VRButtonComponent") bool IsButtonInUse(); // Should be called after the button is moved post begin play UFUNCTION(BlueprintCallable, Category = "VRButtonComponent") void ResetInitialButtonLocation(); // Sets the button state outside of interaction, bSnapIntoPosition is for Toggle_Stay mode, it will lerp into the new position if this is false UFUNCTION(BlueprintCallable, Category = "VRButtonComponent") void SetButtonState(bool bNewButtonState, bool bCallButtonChangedEvent = true, bool bSnapIntoPosition = false); // Resets the button to its resting location (mostly for Toggle_Stay) UFUNCTION(BlueprintCallable, Category = "VRButtonComponent") void SetButtonToRestingPosition(bool bLerpToPosition = false); // On the button state changing, keep in mind that InteractingActor can be invalid if manually setting the state UPROPERTY(BlueprintAssignable, Category = "VRButtonComponent") FVRButtonStateChangedSignature OnButtonStateChanged; // On the button state changing, keep in mind that InteractingActor can be invalid if manually setting the state UFUNCTION(BlueprintImplementableEvent, meta = (DisplayName = "Button State Changed")) void ReceiveButtonStateChanged(bool bCurButtonState, AActor * LastInteractingActor, UPrimitiveComponent * InteractingComponent); // On Button beginning interaction (may spam a bit depending on if overlap is jittering) UPROPERTY(BlueprintAssignable, Category = "VRButtonComponent") FVRButtonStartedInteractionSignature OnButtonBeginInteraction; // On Button ending interaction (may spam a bit depending on if overlap is jittering) UPROPERTY(BlueprintAssignable, Category = "VRButtonComponent") FVRButtonStartedInteractionSignature OnButtonEndInteraction; // On Button beginning interaction (may spam a bit depending on if overlap is jittering) UFUNCTION(BlueprintImplementableEvent, meta = (DisplayName = "Button Started Interaction")) void ReceiveButtonBeginInteraction(AActor * InteractingActor, UPrimitiveComponent * InteractingComponent); // On Button ending interaction (may spam a bit depending on if overlap is jittering) UFUNCTION(BlueprintImplementableEvent, meta = (DisplayName = "Button Ended Interaction")) void ReceiveButtonEndInteraction(AActor * LastInteractingActor, UPrimitiveComponent * LastInteractingComponent); // On the button state changing, keep in mind that InteractingActor can be invalid if manually setting the state UPROPERTY(BlueprintReadOnly, Category = "VRButtonComponent") TObjectPtr<UPrimitiveComponent> LocalInteractingComponent; UPROPERTY(BlueprintReadOnly, Category = "VRButtonComponent") TObjectPtr<AActor> LocalLastInteractingActor; UPROPERTY(BlueprintReadOnly, Category = "VRButtonComponent") TObjectPtr<UPrimitiveComponent> LocalLastInteractingComponent; // Whether the button is enabled or not (can be interacted with) UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") bool bIsEnabled; protected: // Current state of the button, writable to set initial value UPROPERTY(EditAnywhere,BlueprintReadWrite, Replicated, Category = "VRButtonComponent") bool bButtonState; // Who is allowed to change the button state UPROPERTY(EditAnywhere, BlueprintReadWrite, Replicated, Category = "VRButtonComponent|Replication") EVRStateChangeAuthorityType StateChangeAuthorityType; public: bool GetButtonState() { return bButtonState; } void SetButtonState(bool bNewButtonState); EVRStateChangeAuthorityType GetStateChangeAuthorityType() { return StateChangeAuthorityType; } void SetStateChangeAuthorityType(EVRStateChangeAuthorityType NewStateChangeAuthorityType); // Speed that the button de-presses when no longer interacted with UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") float DepressSpeed; // Distance that the button depresses UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") float DepressDistance; // Type of button this is UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") EVRButtonType ButtonType; // Negative on this axis is the depress direction UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") EVRInteractibleAxis ButtonAxis; // Depth at which the button engages (switches) UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") float ButtonEngageDepth; // Minimum time before the button can be switched again UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") float MinTimeBetweenEngaging; // Skips filtering overlaps on the button and lets you manage it yourself, this is the alternative to overriding IsValidOverlap UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRButtonComponent") bool bSkipOverlapFiltering; UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "VRButtonComponent") bool IsValidOverlap(UPrimitiveComponent * OverlapComponent); // Sets the Last interacting actor variable void SetLastInteractingActor(); virtual FVector GetTargetRelativeLocation(); protected: // Overrides the default of : true and allows for controlling it like in an actor, should be default of off normally with grippable components UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = "VRGripInterface|Replication") bool bReplicateMovement; public: bool GetReplicateMovement() { return bReplicateMovement; } void SetReplicateMovement(bool bNewReplicateMovement); virtual void PreReplication(IRepChangedPropertyTracker & ChangedPropertyTracker) override; // Resetting the initial transform here so that it comes in prior to BeginPlay and save loading. virtual void OnRegister() override; protected: // Now replicating this so that it works correctly over the network UPROPERTY(BlueprintReadOnly, ReplicatedUsing = OnRep_InitialRelativeTransform, Category = "VRButtonComponent") FTransform_NetQuantize InitialRelativeTransform; public: // Gets the initial relative transform, if you want to set it you should be using ResetInitialButtonLocation FTransform GetInitialRelativeTransform() { return InitialRelativeTransform; } UFUNCTION() virtual void OnRep_InitialRelativeTransform() { SetButtonToRestingPosition(); } protected: // Control variables FVector InitialLocation; bool bToggledThisTouch; FVector InitialComponentLoc; float LastToggleTime; float GetAxisValue(FVector CheckLocation); FVector SetAxisValue(float SetValue); };
0
0.936671
1
0.936671
game-dev
MEDIA
0.92129
game-dev
0.592976
1
0.592976
beyond-all-reason/RecoilEngine
3,066
rts/Game/Camera/CameraController.cpp
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ #include "CameraController.h" #include "Game/Camera.h" #include "Map/Ground.h" #include "Map/ReadMap.h" #include "Sim/Misc/GlobalConstants.h" #include "System/Config/ConfigHandler.h" #include "System/Misc/TracyDefs.h" CONFIG(float, UseDistToGroundForIcons).defaultValue(0.95f); CCameraController::CCameraController() { RECOIL_DETAILED_TRACY_ZONE; // switchVal: // * 1.0 = 0 degree = overview // * 0.0 = 90 degree = first person switchVal = configHandler->GetFloat("UseDistToGroundForIcons"); scrollSpeed = 1.0f; fov = 45.0f; pixelSize = 1.0f; enabled = true; pos = float3(mapDims.mapx * 0.5f * SQUARE_SIZE, 1000.0f, mapDims.mapy * 0.5f * SQUARE_SIZE); // center map dir = FwdVector; } float3 CCameraController::GetRot() const { return CCamera::GetRotFromDir(GetDir()); } void CCameraController::SetRot(const float3& newRot) { dir = CCamera::GetFwdFromRot(newRot); } bool CCameraController::SetStateBool(const StateMap& sm, const std::string& name, bool& var) { RECOIL_DETAILED_TRACY_ZONE; const StateMap::const_iterator it = sm.find(name); if (it != sm.cend()) { var = (it->second > 0.0f); return true; } return false; } bool CCameraController::SetStateFloat(const StateMap& sm, const std::string& name, float& var) { RECOIL_DETAILED_TRACY_ZONE; const StateMap::const_iterator it = sm.find(name); if (it != sm.cend()) { var = it->second; return true; } return false; } // Uses distance to ground for large angles (near 90 degree), // and distance to unit for flat angles (near 0 degree), // when comparing the camera direction to the map surface, // assuming the map is flat. bool CCameraController::GetUseDistToGroundForIcons() { // dir should already be normalized const float rawDot = UpVector.dot(GetDir()); const float absDot = std::clamp(math::fabs(rawDot), 0.0f, 1.0f); // dot< switch: flat angle (typical for first person camera) // dot>=switch: steep angle (typical for overhead camera) return (absDot >= switchVal); } bool CCameraController::SetState(const StateMap& sm) { RECOIL_DETAILED_TRACY_ZONE; SetStateFloat(sm, "fov", fov); SetStateFloat(sm, "px", pos.x); SetStateFloat(sm, "py", pos.y); SetStateFloat(sm, "pz", pos.z); SetStateFloat(sm, "dx", dir.x); SetStateFloat(sm, "dy", dir.y); SetStateFloat(sm, "dz", dir.z); return true; } void CCameraController::GetState(StateMap& sm) const { RECOIL_DETAILED_TRACY_ZONE; sm["fov"] = fov; sm["px"] = pos.x; sm["py"] = pos.y; sm["pz"] = pos.z; sm["dx"] = dir.x; sm["dy"] = dir.y; sm["dz"] = dir.z; } float CCameraController::DistanceToGround(float3 from, float3 dir, float fallbackPlaneHeight) { RECOIL_DETAILED_TRACY_ZONE; float newGroundDist = CGround::LineGroundCol(from, from + dir * 150000.0f, false); // if the direction is not pointing towards the map we use provided xz plane as heuristic if (newGroundDist <= 0.0f) { newGroundDist = CGround::LinePlaneCol(from, dir, 150000.0f, fallbackPlaneHeight); } return newGroundDist; }
0
0.943909
1
0.943909
game-dev
MEDIA
0.702193
game-dev,graphics-rendering
0.947564
1
0.947564
Faboslav/friends-and-foes
7,612
common/src/main/java/com/faboslav/friendsandfoes/common/entity/ai/brain/CrabBrain.java
package com.faboslav.friendsandfoes.common.entity.ai.brain; import com.faboslav.friendsandfoes.common.entity.CrabEntity; import com.faboslav.friendsandfoes.common.entity.ai.brain.task.crab.*; import com.faboslav.friendsandfoes.common.init.FriendsAndFoesActivities; import com.faboslav.friendsandfoes.common.init.FriendsAndFoesEntityTypes; import com.faboslav.friendsandfoes.common.init.FriendsAndFoesMemoryModuleTypes; import com.faboslav.friendsandfoes.common.init.FriendsAndFoesSensorTypes; import com.faboslav.friendsandfoes.common.tag.FriendsAndFoesTags; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Dynamic; import net.minecraft.tags.ItemTags; import net.minecraft.util.TimeUtil; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.entity.ai.Brain; import net.minecraft.world.entity.ai.behavior.*; import net.minecraft.world.entity.ai.memory.MemoryModuleType; import net.minecraft.world.entity.ai.memory.MemoryStatus; import net.minecraft.world.entity.ai.sensing.Sensor; import net.minecraft.world.entity.ai.sensing.SensorType; import net.minecraft.world.entity.schedule.Activity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import java.util.List; import java.util.function.Predicate; public final class CrabBrain { public static final List<MemoryModuleType<?>> MEMORY_MODULES; public static final List<SensorType<? extends Sensor<? super CrabEntity>>> SENSORS; private static final UniformInt WAVE_COOLDOWN_PROVIDER; public static Brain<?> create(Dynamic<?> dynamic) { Brain.Provider<CrabEntity> profile = Brain.provider(MEMORY_MODULES, SENSORS); Brain<CrabEntity> brain = profile.makeBrain(dynamic); addCoreActivities(brain); addIdleActivities(brain); addLayEggActivities(brain); addDanceActivities(brain); addWaveActivities(brain); brain.setCoreActivities(ImmutableSet.of(Activity.CORE)); brain.setDefaultActivity(Activity.IDLE); brain.useDefaultActivity(); return brain; } private static void addCoreActivities(Brain<CrabEntity> brain) { brain.addActivity( Activity.CORE, 0, ImmutableList.of( new AnimalPanic<>(2.0f), new LookAtTargetSink(45, 90), new MoveToTargetSink(), new CountDownCooldownTicks(MemoryModuleType.TEMPTATION_COOLDOWN_TICKS), new CountDownCooldownTicks(FriendsAndFoesMemoryModuleTypes.CRAB_WAVE_COOLDOWN.get()) ) ); } private static void addLayEggActivities(Brain<CrabEntity> brain) { brain.addActivityWithConditions( FriendsAndFoesActivities.CRAB_LAY_EGG.get(), ImmutableList.of( Pair.of(0, new CrabGoToHomePositionTask()), Pair.of(1, new CrabLocateBurrowSpotTask()), Pair.of(2, new CrabTravelToBurrowSpotTask()), Pair.of(3, new CrabLayEggTask()) ), ImmutableSet.of( Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_HAS_EGG.get(), MemoryStatus.VALUE_PRESENT) ) ); } private static void addDanceActivities(Brain<CrabEntity> brain) { brain.addActivityWithConditions( FriendsAndFoesActivities.CRAB_DANCE.get(), ImmutableList.of( Pair.of(0, new CrabDanceTask()) ), ImmutableSet.of( Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_IS_DANCING.get(), MemoryStatus.VALUE_PRESENT), Pair.of(MemoryModuleType.BREED_TARGET, MemoryStatus.VALUE_ABSENT), Pair.of(MemoryModuleType.TEMPTING_PLAYER, MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_HAS_EGG.get(), MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_BURROW_POS.get(), MemoryStatus.VALUE_ABSENT) ) ); } private static void addWaveActivities(Brain<CrabEntity> brain) { brain.addActivityWithConditions( FriendsAndFoesActivities.CRAB_WAVE.get(), ImmutableList.of( Pair.of(0, new CrabWaveTask()) ), ImmutableSet.of( Pair.of(MemoryModuleType.NEAREST_VISIBLE_PLAYER, MemoryStatus.VALUE_PRESENT), Pair.of(MemoryModuleType.BREED_TARGET, MemoryStatus.VALUE_ABSENT), Pair.of(MemoryModuleType.TEMPTING_PLAYER, MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_WAVE_COOLDOWN.get(), MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_HAS_EGG.get(), MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_IS_DANCING.get(), MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_BURROW_POS.get(), MemoryStatus.VALUE_ABSENT) ) ); } private static void addIdleActivities(Brain<CrabEntity> brain) { brain.addActivityWithConditions( Activity.IDLE, ImmutableList.of( Pair.of(0, new FollowTemptation(crab -> 1.25f)), Pair.of(1, new CrabBreedTask(FriendsAndFoesEntityTypes.CRAB.get())), Pair.of(2, BabyFollowAdult.create(UniformInt.of(5, 16), 1.25f)), Pair.of(3, new RunOne( ImmutableList.of( Pair.of(RandomStroll.stroll(1.0f), 2), Pair.of(SetWalkTargetFromLookTarget.create(1.0f, 3), 2), Pair.of(new DoNothing(30, 60), 1))) ) ), ImmutableSet.of( Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_WAVE_COOLDOWN.get(), MemoryStatus.VALUE_PRESENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_HAS_EGG.get(), MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_IS_DANCING.get(), MemoryStatus.VALUE_ABSENT), Pair.of(FriendsAndFoesMemoryModuleTypes.CRAB_BURROW_POS.get(), MemoryStatus.VALUE_ABSENT) )); } public static void updateActivities(CrabEntity crab) { crab.getBrain().setActiveActivityToFirstValid( ImmutableList.of( FriendsAndFoesActivities.CRAB_LAY_EGG.get(), FriendsAndFoesActivities.CRAB_DANCE.get(), FriendsAndFoesActivities.CRAB_WAVE.get(), Activity.IDLE ) ); } public static void updateMemories(CrabEntity crab) { if (crab.hasEgg()) { crab.getBrain().setMemory(FriendsAndFoesMemoryModuleTypes.CRAB_HAS_EGG.get(), true); } else { crab.getBrain().eraseMemory(FriendsAndFoesMemoryModuleTypes.CRAB_HAS_EGG.get()); } if (crab.isDancing() && !crab.onClimbable()) { crab.getBrain().setMemory(FriendsAndFoesMemoryModuleTypes.CRAB_IS_DANCING.get(), true); } else { crab.getBrain().eraseMemory(FriendsAndFoesMemoryModuleTypes.CRAB_IS_DANCING.get()); } } public static void setWaveCooldown(CrabEntity crab) { crab.getBrain().setMemory(FriendsAndFoesMemoryModuleTypes.CRAB_WAVE_COOLDOWN.get(), WAVE_COOLDOWN_PROVIDER.sample(crab.getRandom())); } public static Predicate<ItemStack> getTemptations() { return itemStack -> itemStack.is(FriendsAndFoesTags.CRAB_TEMPT_ITEMS); } static { SENSORS = List.of( SensorType.NEAREST_LIVING_ENTITIES, SensorType.NEAREST_PLAYERS, SensorType.NEAREST_ADULT, FriendsAndFoesSensorTypes.CRAB_TEMPTATIONS.get() ); MEMORY_MODULES = List.of( MemoryModuleType.TEMPTING_PLAYER, MemoryModuleType.TEMPTATION_COOLDOWN_TICKS, MemoryModuleType.IS_TEMPTED, MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES, MemoryModuleType.PATH, MemoryModuleType.LOOK_TARGET, MemoryModuleType.WALK_TARGET, MemoryModuleType.BREED_TARGET, MemoryModuleType.IS_PANICKING, MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE, MemoryModuleType.NEAREST_VISIBLE_PLAYER, MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM, FriendsAndFoesMemoryModuleTypes.CRAB_HAS_EGG.get(), FriendsAndFoesMemoryModuleTypes.CRAB_IS_DANCING.get(), FriendsAndFoesMemoryModuleTypes.CRAB_BURROW_POS.get(), FriendsAndFoesMemoryModuleTypes.CRAB_WAVE_COOLDOWN.get() ); WAVE_COOLDOWN_PROVIDER = TimeUtil.rangeOfSeconds(20, 40); } }
0
0.524527
1
0.524527
game-dev
MEDIA
0.953969
game-dev
0.900939
1
0.900939
Lorenzooone/PokemonGB_Online_Trades
12,154
utilities/gsc_trading_menu.py
import threading from random import Random from .trading_version import TradingVersion from .gsc_trading_strings import GSCTradingStrings from argparse import ArgumentParser class GSCTradingMenu: """ Class used to handle the various possible menus. """ default_server = ["pokemon-gb-online-trades.herokuapp.com", None] default_emulator = ["localhost", 8765] default_max_level = 100 def __init__(self, kill_function, is_emulator=False): try: args = self.handle_args(is_emulator) except SystemExit as e: kill_function() # Initialize the menu self.server = [args.server_host, args.server_port] self.buffered = args.buffered self.japanese = args.japanese self.max_level = args.max_level self.egg = args.egg self.is_emulator = is_emulator self.multiboot = False if is_emulator: self.emulator = [args.emulator_host, args.emulator_port] self.do_sanity_checks = args.do_sanity_checks self.kill_on_byte_drops = args.kill_on_byte_drops self.verbose = args.verbose self.gen = args.gen_number self.trade_type = args.trade_type self.room = args.room self.toppest_menu_handlers = { "1": self.start_gen1_trading, "2": self.start_gen2_trading, "3": self.start_gen1_trading, "4": self.start_gen3_trading, "m": self.start_multiboot_gen3 } self.top_menu_handlers = { "0": self.start_2p_trading, "1": self.start_2p_trading, "2": self.start_pool_trading, "3": self.handle_options } self.options_menu_handlers = { "0": self.handle_exit_option, "1": self.handle_server_option, "2": self.handle_port_option, "3": self.handle_japanese_option, "4": self.handle_sanity_option, "5": self.handle_verbose_option, "6": self.handle_buffered_option, "7": self.handle_kill_on_byte_drop_option, "8": self.handle_max_level_option, "9": self.handle_eggs_option } if is_emulator: self.options_menu_handlers["10"] = self.handle_emulator_host_option self.options_menu_handlers["11"] = self.handle_emulator_port_option def get_int(self, default_value): x = input() try: ret_val = int(x) except ValueError: ret_val = default_value return ret_val def handle_buffered_change_offer(self, buffered): decided = False while not decided: GSCTradingStrings.buffered_negotiation_print(buffered) x = input().lower() if x == "y" or x == "yes": buffered = not buffered decided = True elif x == "n" or x == "no": decided = True return buffered def handle_game_selector(self): if self.gen is None or ((self.gen != 1) and (self.gen != 2) and (self.gen != 3)): ret_val = None while ret_val is None: GSCTradingStrings.game_selector_menu_print() GSCTradingStrings.choice_print() ret_val = self.toppest_menu_handlers.get(input(), None) if ret_val is not None: ret_val = ret_val() def handle_menu(self): GSCTradingStrings.version_print(TradingVersion.version_major, TradingVersion.version_minor, TradingVersion.version_build) if self.multiboot: self.start_pool_trading() elif self.trade_type is None or ((self.trade_type != GSCTradingStrings.two_player_trade_str) and (self.trade_type != GSCTradingStrings.pool_trade_str)): self.handle_game_selector() if not self.multiboot: ret_val = False while not ret_val: GSCTradingStrings.top_menu_print() GSCTradingStrings.choice_print() ret_val = self.top_menu_handlers.get(input(), self.top_menu_handlers["0"])() else: if self.trade_type == GSCTradingStrings.two_player_trade_str: self.start_2p_trading() elif self.trade_type == GSCTradingStrings.pool_trade_str: self.start_pool_trading() def get_default_room(self): r = Random() return r.randint(0,99999) def start_2p_trading(self): self.trade_type = GSCTradingStrings.two_player_trade_str if self.room is None: self.room = self.get_default_room() GSCTradingStrings.change_room_print(self.room) self.room = self.get_int(self.room) return True def start_pool_trading(self): self.trade_type = GSCTradingStrings.pool_trade_str return True def start_gen1_trading(self): self.gen = 1 return True def start_gen2_trading(self): self.gen = 2 return True def start_gen3_trading(self): self.gen = 3 return True def start_multiboot_gen3(self): self.gen = 3 self.multiboot = True return True def handle_options(self): ret_val = False while not ret_val: GSCTradingStrings.options_menu_print(self) GSCTradingStrings.choice_print() ret_val = self.options_menu_handlers.get(input(), self.options_menu_handlers["0"])() return False def handle_exit_option(self): return True def handle_server_option(self): GSCTradingStrings.change_server_print() self.server[0] = input() return False def handle_port_option(self): GSCTradingStrings.change_port_print() self.server[1] = self.get_int(self.server[1]) return False def handle_emulator_host_option(self): GSCTradingStrings.change_emu_server_print() self.emulator[0] = input() return False def handle_emulator_port_option(self): GSCTradingStrings.change_emu_port_print() self.emulator[1] = self.get_int(self.emulator[1]) return False def handle_buffered_option(self): self.buffered = not self.buffered return False def handle_max_level_option(self): GSCTradingStrings.change_max_level_print(self.max_level) self.max_level = self.get_int(self.max_level) if self.max_level < 2: self.max_level = 2 if self.max_level > 100: self.max_level = 100 return False def handle_eggs_option(self): self.egg = not self.egg return False def handle_japanese_option(self): self.japanese = not self.japanese return False def handle_sanity_option(self): self.do_sanity_checks = not self.do_sanity_checks return False def handle_kill_on_byte_drop_option(self): self.kill_on_byte_drops = not self.kill_on_byte_drops return False def handle_verbose_option(self): self.verbose = not self.verbose return False def handle_args(self, is_emulator): # Parse program's arguments parser = ArgumentParser() parser.add_argument("-g", "--generation", dest="gen_number", default = None, help="generation (1 = RBY/Timecapsule, 2 = GSC, 3 = RSE Special)", type=int) parser.add_argument("-t", "--trade_type", dest="trade_type", default = None, help="trade type (" + GSCTradingStrings.two_player_trade_str + " = 2-Player Trade, " + GSCTradingStrings.pool_trade_str + " = Pool Trade)") parser.add_argument("-r", "--room", dest="room", default = None, help="2-Player Trade's room", type=int) parser.add_argument("-b", "--buffered", action="store_true", dest="buffered", default=False, help="default to buffered trading instead of synchronous") parser.add_argument("-j", "--japanese", action="store_true", dest="japanese", default=False, help="use it if your game is Japanese") parser.add_argument("-dsc", "--disable_sanity_checks", action="store_false", dest="do_sanity_checks", default=True, help="don't perform sanity checks for data sent to the device") parser.add_argument("-dkb", "--disable_kill_drops", action="store_false", dest="kill_on_byte_drops", default=True, help="don't kill the process for dropped bytes") parser.add_argument("-mlp", "--max_level_pool", dest="max_level", default = self.default_max_level, help="Pool's max level", type=int) parser.add_argument("-egp", "--eggify_pool", action="store_true", dest="egg", default=False, help="turns Pool Pokémon into ready-to-hatch eggs") parser.add_argument("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_argument("-sh", "--server_host", dest="server_host", default = self.default_server[0], help="server's host") parser.add_argument("-sp", "--server_port", dest="server_port", default = self.default_server[1], help="server's port", type=int) if is_emulator: parser.add_argument("-eh", "--emulator_host", dest="emulator_host", default = self.default_emulator[0], help="emulator's local host") parser.add_argument("-ep", "--emulator_port", dest="emulator_port", default = self.default_emulator[1], help="emulator's local port", type=int) return parser.parse_args() class GSCBufferedNegotiator(threading.Thread): """ Class used to handle the negotiation when the two clients' buffered variable doesn't match up """ def __init__(self, menu, comms, buffered, sleep_func): threading.Thread.__init__(self) self.daemon=True self.comms = comms self.menu = menu self.final_buffered = None self.buffered = buffered self.sleep_func = sleep_func def force_receive(self, fun): received = None while received is None: self.sleep_func() received = fun() return received def choose_if_buffered(self): buffered = self.buffered self.comms.send_buffered_data(buffered) other_buffered = self.force_receive(self.comms.get_buffered_data) if buffered == other_buffered: return buffered change_buffered = None while change_buffered is None: own_val = self.comms.send_negotiation_data() other_val = self.force_receive(self.comms.get_negotiation_data) if other_val > own_val: change_buffered = True elif other_val < own_val: change_buffered = False while buffered != other_buffered: if not change_buffered: GSCTradingStrings.buffered_other_negotiation_print(buffered) other_buffered = self.force_receive(self.comms.get_buffered_data) else: buffered = self.menu.handle_buffered_change_offer(buffered) self.comms.send_buffered_data(buffered) change_buffered = not change_buffered return buffered def get_chosen_buffered(self): return self.final_buffered def run(self): self.final_buffered = self.choose_if_buffered() if self.menu.verbose: GSCTradingStrings.chosen_buffered_print(self.final_buffered)
0
0.755633
1
0.755633
game-dev
MEDIA
0.444058
game-dev
0.800223
1
0.800223
vlad250906/Create-UfoPort
3,619
modules/porting_lib_ufo/src/main/java/io/github/fabricators_of_create/porting_lib_ufo/entity/ITeleporter.java
package io.github.fabricators_of_create.porting_lib_ufo.entity; import java.util.Objects; import java.util.function.Function; import org.jetbrains.annotations.Nullable; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.portal.PortalForcer; import net.minecraft.world.phys.Vec3; /** * Interface for handling the placement of entities during dimension change. * <p> * An implementation of this interface can be used to place the entity * in a safe location, or generate a return portal, for instance. * <p> * See the {@link PortalForcer} class, which has * been patched to implement this interface, for a vanilla example. */ public interface ITeleporter { /** * Called to handle placing the entity in the new world. * <p> * The initial position of the entity will be its * position in the origin world, multiplied horizontally * by the computed cross-dimensional movement factor. * <p> * Note that the supplied entity has not yet been spawned * in the destination world at the time. * * @param entity the entity to be placed * @param currentWorld the entity's origin * @param destWorld the entity's destination * @param yaw the suggested yaw value to apply * @param repositionEntity a function to reposition the entity, which returns the new entity in the new dimension. This is the vanilla implementation of the dimension travel logic. If the supplied boolean is true, it is attempted to spawn a new portal. * * @return the entity in the new World. Vanilla creates for most {@link Entity}s a new instance and copy the data. But <b>you are not allowed</b> to create a new instance for {@link Player}s! Move the player and update its state, see {@link ServerPlayer#changeDimension(ServerLevel, ITeleporter)} */ default Entity placeEntity(Entity entity, ServerLevel currentWorld, ServerLevel destWorld, float yaw, Function<Boolean, Entity> repositionEntity) { return repositionEntity.apply(true); } /** * Gets the PortalInfo. defaultPortalInfo references the * vanilla code and should not be used for your purposes. * Override this method to handle your own logic. * <p> * Return {@code null} to prevent teleporting. * * @param entity The entity teleporting before the teleport * @param destWorld The world the entity is teleporting to * @param defaultPortalInfo A reference to the vanilla method for getting portal info. You should implement your own logic instead of using this * * @return The location, rotation, and motion of the entity in the destWorld after the teleport */ // @Nullable // default PortalInfo getPortalInfo(Entity entity, ServerLevel destWorld, Function<ServerLevel, PortalInfo> defaultPortalInfo) { // return this.isVanilla() ? defaultPortalInfo.apply(destWorld) : new PortalInfo(entity.position(), Vec3.ZERO, entity.getYRot(), entity.getXRot()); // } /** * Is this teleporter the vanilla instance. */ default boolean isVanilla() { // Ignore the warning, this is fine at runtime return Objects.equals(this.getClass(), PortalForcer.class); } /** * Called when vanilla wants to play the portal sound after teleporting. Return true to play the vanilla sound. * @param player the player * @param sourceWorld the source world * @param destWorld the target world * @return true to play the vanilla sound */ default boolean playTeleportSound(ServerPlayer player, ServerLevel sourceWorld, ServerLevel destWorld) { return true; } }
0
0.84604
1
0.84604
game-dev
MEDIA
0.894513
game-dev
0.62877
1
0.62877
Autodesk/maya-usd
2,929
lib/usdUfe/ufe/trf/UsdRotateUndoableCommand.cpp
// // Copyright 2020 Autodesk // // 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. // #include "UsdRotateUndoableCommand.h" #include "Utils.h" namespace USDUFE_NS_DEF { // Ensure that UsdRotateUndoableCommand is properly setup. USDUFE_VERIFY_CLASS_SETUP(UsdTRSUndoableCommandBase<PXR_NS::GfVec3f>, UsdRotateUndoableCommand); USDUFE_VERIFY_CLASS_BASE(Ufe::RotateUndoableCommand, UsdRotateUndoableCommand); PXR_NS::TfToken UsdRotateUndoableCommand::rotXYZ("xformOp:rotateXYZ"); UsdRotateUndoableCommand::UsdRotateUndoableCommand( const Ufe::Path& path, double x, double y, double z) : Ufe::RotateUndoableCommand(path) , UsdTRSUndoableCommandBase(x, y, z) { // Since we want to change xformOp:rotateXYZ, and we need to store the // prevRotate for undo purposes, we need to make sure we convert it to // common API xformOps (In case we have rotateX, rotateY or rotateZ ops) try { if (!PXR_NS::UsdGeomXformCommonAPI(prim())) UsdUfe::convertToCompatibleCommonAPI(prim()); } catch (...) { // Since DCC cannot catch this error at this moment, store it until we // actually rotate. _failedInit = std::current_exception(); // capture } } UsdRotateUndoableCommand::Ptr UsdRotateUndoableCommand::create(const Ufe::Path& path, double x, double y, double z) { auto cmd = std::make_shared<MakeSharedEnabler<UsdRotateUndoableCommand>>(path, x, y, z); cmd->initialize(); return cmd; } void UsdRotateUndoableCommand::undo() { // Check if initialization went ok. if (!_failedInit) { UsdTRSUndoableCommandBase::undoImp(); } } void UsdRotateUndoableCommand::redo() { redoImp(); } void UsdRotateUndoableCommand::addEmptyAttribute() { performImp(0, 0, 0); // Add an empty rotate } void UsdRotateUndoableCommand::performImp(double x, double y, double z) { UsdUfe::rotateOp(prim(), path(), x, y, z); } //------------------------------------------------------------------------------ // Ufe::RotateUndoableCommand overrides //------------------------------------------------------------------------------ bool UsdRotateUndoableCommand::set(double x, double y, double z) { // Fail early - Initialization did not go as expected. if (_failedInit) { std::rethrow_exception(_failedInit); } perform(x, y, z); return true; } } // namespace USDUFE_NS_DEF
0
0.823308
1
0.823308
game-dev
MEDIA
0.522554
game-dev
0.900275
1
0.900275
TakafumiSakagami/cpiaengine
2,386
demos/Kanon/README.md
# GBA NVL engine - SepiaNVL A basic NVL engine for making Visual Novels, Sound Novels, etc... for the Gameboy Advance. Requires minimal coding knowledge! Made for an article in [C-pia! Magazine](https://c-pia.github.io/). ## Kanon Demo https://github.com/TakafumiSakagami/cpiaengine/assets/12238323/7f335445-6b92-4eb3-99d1-fb1748ab0315 This recreation of Kanon's introduction is used to demonstrate the textbox layout, custom sentence ending symbols, fading to/from white, CG implementation, voices and sound effects, music, and animation sequences. ### Changes made to the template for this demo include: Uses an older version of the template project. This means that... Variables such as `bgpos` and `frames` are not global, and have to be mentioned constantly. It's a bit messier looking as a result. There is no pause menu implemented, and certain scripts look a bit different without `menu.h`'s presence. Notably, `void presets` from `texter.h` is stored in `main.cpp` instead. The textbox, rather than being the singular `bn::regular_bg_ptr textbox` that switches between `textbox.bmp` and `kuro.bmp` on demand, is split into `bn::regular_bg_ptr textbox` and `bn::regular_bg_ptr kuro`. As a result, many commands that demanded a mention of `textbox` in the template will (here, in the Kanon demo) also require mention of `kuro`. ...I don't think there's any functional difference, so go with whichever you prefer aesthetically. That's the outdated stuff out of the way! New things are: There is no namebox, and the textbox can hold an extra line of text. Added white fades to `transitions.h`. Added code to `main.cpp`'s loop for white fade handling. Default fade color changed to white. `sp01` is now a blank image. `sp02` and `bg02` removed. `sp01_fade` images removed from `spriter.h`. `cgny01_fade` images added to `spriter.h`. `logo` added to `spriter.h`. `textbox`, `textbox2`, and `kuro` redesigned. `ctc` and `fastforward` redesigned. `bgpos == 1` in presets (`main.cpp`) has been changed to allow for a full-screen background frame. Repositioned `start_x` and `click to continue` icon in `texter.h`. Repositioned `external_window` default boundaries. Added `bn::sound_items` for voice playback. Added `bn::sound::stop_all();` for voice cancelling. Added `op_anim.h` for the opening animation. Added slower versions of pans in `panner.h`.
0
0.847588
1
0.847588
game-dev
MEDIA
0.769012
game-dev,desktop-app
0.544167
1
0.544167
hammy275/immersive-mc
11,927
common/src/main/java/com/hammy275/immersivemc/server/storage/world/ImmersiveMCLevelStorage.java
package com.hammy275.immersivemc.server.storage.world; import com.hammy275.immersivemc.ImmersiveMC; import com.hammy275.immersivemc.api.common.immersive.ImmersiveHandler; import com.hammy275.immersivemc.common.immersive.handler.WorldStorageHandler; import com.hammy275.immersivemc.common.immersive.handler.ImmersiveHandlers; import com.hammy275.immersivemc.common.immersive.storage.dual.impl.AnvilStorage; import com.hammy275.immersivemc.common.immersive.storage.dual.impl.ItemStorage; import com.hammy275.immersivemc.common.immersive.storage.dual.impl.SmithingTableStorage; import com.hammy275.immersivemc.common.util.Util; import com.hammy275.immersivemc.server.ServerUtil; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; import net.minecraft.SharedConstants; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.ItemTags; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.saveddata.SavedData; import net.minecraft.world.level.saveddata.SavedDataType; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; /** * Holds ALL the save data for ImmersiveMC for a given world/dimension. */ public class ImmersiveMCLevelStorage extends SavedData { private static final int LEVEL_STORAGE_VERSION = 2; private static final SavedDataType<ImmersiveMCLevelStorage> savedDataType = new SavedDataType<>( "immersivemc_data", ImmersiveMCLevelStorage::create, ctx -> new Codec<>() { @Override public <T> DataResult<Pair<ImmersiveMCLevelStorage, T>> decode(DynamicOps<T> ops, T input) { return DataResult.success(new Pair<>(ImmersiveMCLevelStorage.load(CompoundTag.CODEC.parse(ops, input).getOrThrow(), ctx.levelOrThrow().registryAccess()), input)); } @Override public <T> DataResult<T> encode(ImmersiveMCLevelStorage input, DynamicOps<T> ops, T prefix) { return CompoundTag.CODEC.encode(input.save(new CompoundTag(), ctx.levelOrThrow().registryAccess()), ops, prefix); } }, null ); protected Map<BlockPos, WorldStorage> storageMap = new HashMap<>(); private static ImmersiveMCLevelStorage create(Context context) { return new ImmersiveMCLevelStorage(); } public static ImmersiveMCLevelStorage getLevelStorage(ServerLevel level) { return level.getDataStorage().computeIfAbsent(savedDataType); } @Nullable public WorldStorage remove(BlockPos pos) { return storageMap.remove(pos); } @Nullable public WorldStorage get(BlockPos pos, Level level) { WorldStorage storage = storageMap.get(pos); for (ImmersiveHandler<?> handlerMaybeWS : ImmersiveHandlers.HANDLERS) { if (handlerMaybeWS instanceof WorldStorageHandler<?> handler) { if (handler.getWorldStorageClass().isInstance(storage) && Util.isValidBlocks(handler, pos, level)) { return storage; } } } return null; } @Nullable public WorldStorage getWithoutVerification(BlockPos pos, Level level) { return storageMap.get(pos); } @Nullable public WorldStorage getOrCreate(BlockPos pos, Level level) { WorldStorage storage = get(pos, level); if (storage != null) { return storage; } // At this point, we either didn't find a storage or the storage we found doesn't match with any handler. // Either way, attempt to make a new one. for (ImmersiveHandler<?> handlerMaybeWS : ImmersiveHandlers.HANDLERS) { if (handlerMaybeWS instanceof WorldStorageHandler<?> handler) { if (Util.isValidBlocks(handler, pos, level)) { storage = handler.getEmptyWorldStorage(); storageMap.put(pos, storage); return storage; } } } // At this point, we handle the potential circumstance that someone is upgrading from an old version of // ImmersiveMC from a pre-1.20 world, which leads to the extremely rare circumstance that we have an anvil // storage that needs to be converted into a smithing table one. This case is handled here, and is okay // to hardcode, since ImmersiveMC now effectively mandates each immersive has its own, unique ID, which // should prevent something like this from ever happening again. // // Note that we know this must be from a pre-1.20 world, as otherwise, the conversion would be detected // in ImmersiveMCLevelStorage#maybeUpgradeNBT storage = storageMap.get(pos); if (storage instanceof AnvilStorage as && ImmersiveHandlers.smithingTableHandler.isValidBlock(pos, level)) { SmithingTableStorage sts = new SmithingTableStorage(); sts.copyFromOld(as); sts.convertFrom119(); storageMap.put(pos, sts); this.setDirty(); return sts; } // Storage wasn't in-memory, and we couldn't make a new one. Return null. return null; } public static void unmarkAllItemStoragesDirty(MinecraftServer server) { for (ServerLevel level : server.getAllLevels()) { ImmersiveMCLevelStorage storage = getLevelStorage(level); if (storage != null) { storage.storageMap.forEach((pos, ws) -> { if (ws instanceof ItemStorage is) { is.setNoLongerDirtyForClientSync(); } }); } } } public static ImmersiveMCLevelStorage load(CompoundTag nbt, HolderLookup.Provider provider) { ImmersiveMCLevelStorage levelStorage = new ImmersiveMCLevelStorage(); // Use 3700 for 1.20.4 (most recent Minecraft version with ImmersiveMC before this was added) or the current Minecraft data version, whichever is lower. int lastVanillaDataVersion = nbt.contains("lastVanillaDataVersion") ? nbt.getInt("lastVanillaDataVersion").get() : Math.min(3700, SharedConstants.getCurrentVersion().getDataVersion().getVersion()); nbt = maybeUpgradeNBT(nbt, provider, lastVanillaDataVersion); Map<BlockPos, WorldStorage> storageMap = levelStorage.storageMap; storageMap.clear(); int numOfStorages = nbt.getInt("numOfStorages").get(); CompoundTag storages = nbt.getCompound("storages").get(); for (int i = 0; i < numOfStorages; i++) { CompoundTag storageInfo = storages.getCompound(String.valueOf(i)).get(); BlockPos pos = new BlockPos(storageInfo.getInt("posX").get(), storageInfo.getInt("posY").get(), storageInfo.getInt("posZ").get()); ResourceLocation id = Util.getResourceLocation(storageInfo, "id"); WorldStorage storage = null; for (ImmersiveHandler<?> handlerMaybeWS : ImmersiveHandlers.HANDLERS) { if (handlerMaybeWS.getID().equals(id) && handlerMaybeWS instanceof WorldStorageHandler<?> handler) { storage = handler.getEmptyWorldStorage(); storage.load(storageInfo.getCompound("data").get(), provider, lastVanillaDataVersion); break; } } if (storage != null) { storageMap.put(pos, storage); } } return levelStorage; } public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) { nbt.putInt("lastVanillaDataVersion", SharedConstants.getCurrentVersion().getDataVersion().getVersion()); nbt.putInt("version", LEVEL_STORAGE_VERSION); nbt.putInt("numOfStorages", storageMap.size()); CompoundTag storages = new CompoundTag(); int i = 0; for (Map.Entry<BlockPos, WorldStorage> entry : this.storageMap.entrySet()) { CompoundTag storageInfo = new CompoundTag(); storageInfo.putInt("posX", entry.getKey().getX()); storageInfo.putInt("posY", entry.getKey().getY()); storageInfo.putInt("posZ", entry.getKey().getZ()); storageInfo.put("data", entry.getValue().save(new CompoundTag(), provider)); Util.putResourceLocation(storageInfo, "id", entry.getValue().getHandler().getID()); storages.put(String.valueOf(i), storageInfo); i++; } nbt.put("storages", storages); return nbt; } /** * Upgrades NBT tag to something this version of ImmersiveMC can understand. * @param nbtIn NBT to upgrade. This may be modified in any way. * @param provider Provider for registry access. * @param lastVanillaDataVersion The last vanilla data version this saved data was loaded in. * @return A converted NBT, that isn't necessarily the same object as the nbt going into this function. */ private static CompoundTag maybeUpgradeNBT(CompoundTag nbtIn, HolderLookup.Provider provider, int lastVanillaDataVersion) { int version = 1; if (nbtIn.contains("version")) { // Version 1 didn't store a version int version = nbtIn.getInt("version").get(); } while (version < LEVEL_STORAGE_VERSION) { if (version == 1) { int numOfStorages = nbtIn.getInt("numOfStorages").get(); CompoundTag storages = nbtIn.getCompound("storages").get(); for (int i = 0; i < numOfStorages; i++) { CompoundTag storage = storages.getCompound(String.valueOf(i)).get(); String oldDataType = storage.getString("dataType").get(); storage.remove("dataType"); CompoundTag itemsData = storage.getCompound("data").get(); String oldIdentifier = itemsData.getString("identifier").get(); itemsData.remove("identifier"); int numItems = itemsData.getInt("numOfItems").get(); ResourceLocation id; if (numItems == 10) { id = ResourceLocation.fromNamespaceAndPath(ImmersiveMC.MOD_ID, "crafting_table"); } else if (numItems == 4 || (numItems == 3 && oldDataType.equals("basic_item_store"))) { id = ResourceLocation.fromNamespaceAndPath(ImmersiveMC.MOD_ID, "smithing_table"); } else if (numItems == 3) { id = ResourceLocation.fromNamespaceAndPath(ImmersiveMC.MOD_ID, "anvil"); } else if (numItems == 1) { // Need to decode the item to figure out if this is an enchanting table or a beacon. ItemStack item = ServerUtil.parseItem(provider, itemsData.getCompound("item0").get(), lastVanillaDataVersion); if (item.is(ItemTags.BEACON_PAYMENT_ITEMS)) { id = ResourceLocation.fromNamespaceAndPath(ImmersiveMC.MOD_ID, "beacon"); } else { id = ResourceLocation.fromNamespaceAndPath(ImmersiveMC.MOD_ID, "enchanting_table"); } } else { continue; } Util.putResourceLocation(storage, "id", id); } } version++; } return nbtIn; } }
0
0.904217
1
0.904217
game-dev
MEDIA
0.961143
game-dev
0.943237
1
0.943237
AidanHockey5/STM32_VGM_Player_YM2612_SN76489
8,582
lib/SdFat/src/FatLib/istream.cpp
/* FatLib Library * Copyright (C) 2013 by William Greiman * * This file is part of the FatLib Library * * This Library 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 Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the FatLib Library. If not, see * <http://www.gnu.org/licenses/>. */ // #include <ctype.h> #include <float.h> #include <ctype.h> #include "istream.h" //------------------------------------------------------------------------------ int istream::get() { int c; m_gcount = 0; c = getch(); if (c < 0) { setstate(failbit); } else { m_gcount = 1; } return c; } //------------------------------------------------------------------------------ istream& istream::get(char& c) { int tmp = get(); if (tmp >= 0) { c = tmp; } return *this; } //------------------------------------------------------------------------------ istream& istream::get(char *str, streamsize n, char delim) { int c; FatPos_t pos; m_gcount = 0; while ((m_gcount + 1) < n) { c = getch(&pos); if (c < 0) { break; } if (c == delim) { setpos(&pos); break; } str[m_gcount++] = c; } if (n > 0) { str[m_gcount] = '\0'; } if (m_gcount == 0) { setstate(failbit); } return *this; } //------------------------------------------------------------------------------ void istream::getBool(bool *b) { if ((flags() & boolalpha) == 0) { getNumber(b); return; } #ifdef __AVR__ PGM_P truePtr = PSTR("true"); PGM_P falsePtr = PSTR("false"); #else // __AVR__ const char* truePtr = "true"; const char* falsePtr = "false"; #endif // __AVR const uint8_t true_len = 4; const uint8_t false_len = 5; bool trueOk = true; bool falseOk = true; uint8_t i = 0; int c = readSkip(); while (1) { #ifdef __AVR__ falseOk = falseOk && c == pgm_read_byte(falsePtr + i); trueOk = trueOk && c == pgm_read_byte(truePtr + i); #else // __AVR__ falseOk = falseOk && c == falsePtr[i]; trueOk = trueOk && c == truePtr[i]; #endif // __AVR__ if (trueOk == false && falseOk == false) { break; } i++; if (trueOk && i == true_len) { *b = true; return; } if (falseOk && i == false_len) { *b = false; return; } c = getch(); } setstate(failbit); } //------------------------------------------------------------------------------ void istream::getChar(char* ch) { int16_t c = readSkip(); if (c < 0) { setstate(failbit); } else { *ch = c; } } //------------------------------------------------------------------------------ // // http://www.exploringbinary.com/category/numbers-in-computers/ // int16_t const EXP_LIMIT = 100; static const uint32_t uint32_max = (uint32_t)-1; bool istream::getDouble(double* value) { bool got_digit = false; bool got_dot = false; bool neg; int16_t c; bool expNeg = false; int16_t exp = 0; int16_t fracExp = 0; uint32_t frac = 0; FatPos_t endPos; double pow10; double v; getpos(&endPos); c = readSkip(); neg = c == '-'; if (c == '-' || c == '+') { c = getch(); } while (1) { if (isdigit(c)) { got_digit = true; if (frac < uint32_max/10) { frac = frac * 10 + (c - '0'); if (got_dot) { fracExp--; } } else { if (!got_dot) { fracExp++; } } } else if (!got_dot && c == '.') { got_dot = true; } else { break; } if (fracExp < -EXP_LIMIT || fracExp > EXP_LIMIT) { goto fail; } c = getch(&endPos); } if (!got_digit) { goto fail; } if (c == 'e' || c == 'E') { c = getch(); expNeg = c == '-'; if (c == '-' || c == '+') { c = getch(); } while (isdigit(c)) { if (exp > EXP_LIMIT) { goto fail; } exp = exp * 10 + (c - '0'); c = getch(&endPos); } } v = static_cast<double>(frac); exp = expNeg ? fracExp - exp : fracExp + exp; expNeg = exp < 0; if (expNeg) { exp = -exp; } pow10 = 10.0; while (exp) { if (exp & 1) { if (expNeg) { // check for underflow if (v < FLT_MIN * pow10 && frac != 0) { goto fail; } v /= pow10; } else { // check for overflow if (v > FLT_MAX / pow10) { goto fail; } v *= pow10; } } pow10 *= pow10; exp >>= 1; } setpos(&endPos); *value = neg ? -v : v; return true; fail: // error restore position to last good place setpos(&endPos); setstate(failbit); return false; } //------------------------------------------------------------------------------ istream& istream::getline(char *str, streamsize n, char delim) { FatPos_t pos; int c; m_gcount = 0; if (n > 0) { str[0] = '\0'; } while (1) { c = getch(&pos); if (c < 0) { break; } if (c == delim) { m_gcount++; break; } if ((m_gcount + 1) >= n) { setpos(&pos); setstate(failbit); break; } str[m_gcount++] = c; str[m_gcount] = '\0'; } if (m_gcount == 0) { setstate(failbit); } return *this; } //------------------------------------------------------------------------------ bool istream::getNumber(uint32_t posMax, uint32_t negMax, uint32_t* num) { int16_t c; int8_t any = 0; int8_t have_zero = 0; uint8_t neg; uint32_t val = 0; uint32_t cutoff; uint8_t cutlim; FatPos_t endPos; uint8_t f = flags() & basefield; uint8_t base = f == oct ? 8 : f != hex ? 10 : 16; getpos(&endPos); c = readSkip(); neg = c == '-' ? 1 : 0; if (c == '-' || c == '+') { c = getch(); } if (base == 16 && c == '0') { // TESTSUITE c = getch(&endPos); if (c == 'X' || c == 'x') { c = getch(); // remember zero in case no hex digits follow x/X have_zero = 1; } else { any = 1; } } // set values for overflow test cutoff = neg ? negMax : posMax; cutlim = cutoff % base; cutoff /= base; while (1) { if (isdigit(c)) { c -= '0'; } else if (isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; } else { break; } if (c >= base) { break; } if (val > cutoff || (val == cutoff && c > cutlim)) { // indicate overflow error any = -1; break; } val = val * base + c; c = getch(&endPos); any = 1; } setpos(&endPos); if (any > 0 || (have_zero && any >= 0)) { *num = neg ? -val : val; return true; } setstate(failbit); return false; } //------------------------------------------------------------------------------ void istream::getStr(char *str) { FatPos_t pos; uint16_t i = 0; uint16_t m = width() ? width() - 1 : 0XFFFE; if (m != 0) { getpos(&pos); int c = readSkip(); while (i < m) { if (c < 0) { break; } if (isspace(c)) { setpos(&pos); break; } str[i++] = c; c = getch(&pos); } } str[i] = '\0'; if (i == 0) { setstate(failbit); } width(0); } //------------------------------------------------------------------------------ istream& istream::ignore(streamsize n, int delim) { int c; m_gcount = 0; while (m_gcount < n) { c = getch(); if (c < 0) { break; } m_gcount++; if (c == delim) { break; } } return *this; } //------------------------------------------------------------------------------ int istream::peek() { int16_t c; FatPos_t pos; m_gcount = 0; getpos(&pos); c = getch(); if (c < 0) { if (!bad()) { setstate(eofbit); } } else { setpos(&pos); } return c; } //------------------------------------------------------------------------------ int16_t istream::readSkip() { int16_t c; do { c = getch(); } while (isspace(c) && (flags() & skipws)); return c; } //------------------------------------------------------------------------------ /** used to implement ws() */ void istream::skipWhite() { int c; FatPos_t pos; do { c = getch(&pos); } while (isspace(c)); setpos(&pos); }
0
0.77964
1
0.77964
game-dev
MEDIA
0.532329
game-dev
0.984447
1
0.984447
defeatedcrow/HeatAndClimateMod
1,049
src/main/java/defeatedcrow/hac/food/material/entity/PlatePumpkinItem.java
package defeatedcrow.hac.food.material.entity; import defeatedcrow.hac.api.material.EntityRenderData; import defeatedcrow.hac.food.material.FoodInit; import defeatedcrow.hac.food.material.item.ItemEntityFood; import net.minecraft.tags.TagKey; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Item; public class PlatePumpkinItem extends ItemEntityFood { public PlatePumpkinItem(String s, int nut, float sat, TagKey<Item> pair) { super(s, nut, sat, true, pair); } @Override public EntityType<?> getType() { return FoodInit.PLATE_PUMPKIN.get(); } @Override public EntityRenderData getRenderData(Item item) { if (item == FoodInit.PLATE_PUMPKIN_RAW.get()) return PUMPKIN_RAW; if (item == FoodInit.PLATE_PUMPKIN_COOKED.get()) return PUMPKIN_COOKED; return PUMPKIN_RAW; } public static final EntityRenderData PUMPKIN_RAW = new EntityRenderData("food/plate_pumpkin_raw", 1F, 0F); public static final EntityRenderData PUMPKIN_COOKED = new EntityRenderData("food/plate_pumpkin_cooked", 1F, 0F); }
0
0.598446
1
0.598446
game-dev
MEDIA
0.996934
game-dev
0.69725
1
0.69725
MergHQ/CRYENGINE
2,920
Code/CryEngine/CryAction/VehicleSystem/VehicleUsableActionEnter.cpp
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Implements a usable action to enter a vehicle seat ------------------------------------------------------------------------- History: - 19:01:2006: Created by Mathieu Pinard *************************************************************************/ #include "StdAfx.h" #include "CryAction.h" #include "GameObjects/GameObject.h" #include "IActorSystem.h" #include "IGameObject.h" #include "IItem.h" #include "IItemSystem.h" #include "IVehicleSystem.h" #include "Vehicle.h" #include "VehicleSeat.h" #include "VehicleSeatGroup.h" #include "VehicleUsableActionEnter.h" //------------------------------------------------------------------------ bool CVehicleUsableActionEnter::Init(IVehicle* pVehicle, const CVehicleParams& table) { CVehicleParams enterTable = table.findChild("Enter"); if (!enterTable) return false; m_pVehicle = static_cast<CVehicle*>(pVehicle); if (CVehicleParams seatsTables = enterTable.findChild("Seats")) { int c = seatsTables.getChildCount(); int i = 0; m_seatIds.reserve(c); for (; i < c; i++) { CVehicleParams seatRef = seatsTables.getChild(i); if (const char* pSeatName = seatRef.getAttr("value")) { if (TVehicleSeatId seatId = m_pVehicle->GetSeatId(pSeatName)) m_seatIds.push_back(seatId); } } } return !m_seatIds.empty(); } //------------------------------------------------------------------------ int CVehicleUsableActionEnter::OnEvent(int eventType, SVehicleEventParams& eventParams) { if (eventType == eVAE_IsUsable) { EntityId& userId = eventParams.entityId; for (TVehicleSeatIdVector::iterator ite = m_seatIds.begin(), end = m_seatIds.end(); ite != end; ++ite) { TVehicleSeatId seatId = *ite; IVehicleSeat* pSeat = m_pVehicle->GetSeatById(seatId); if (IsSeatAvailable(pSeat, userId)) { eventParams.iParam = seatId; return 1; } } return 0; } else if (eventType == eVAE_OnUsed) { EntityId& userId = eventParams.entityId; IVehicleSeat* pSeat = m_pVehicle->GetSeatById(eventParams.iParam); if (IsSeatAvailable(pSeat, userId)) return pSeat->Enter(userId); return -1; } return 0; } //------------------------------------------------------------------------ bool CVehicleUsableActionEnter::IsSeatAvailable(IVehicleSeat* pSeat, EntityId userId) { if (!pSeat) return false; IActor* pActor = CCryAction::GetCryAction()->GetIActorSystem()->GetActor(userId); if (!static_cast<CVehicleSeat*>(pSeat)->IsFree(pActor)) return false; return true; } void CVehicleUsableActionEnter::GetMemoryStatistics(ICrySizer* s) { s->Add(*this); s->AddContainer(m_seatIds); } DEFINE_VEHICLEOBJECT(CVehicleUsableActionEnter);
0
0.745038
1
0.745038
game-dev
MEDIA
0.920455
game-dev
0.890977
1
0.890977
ElspethThePict/S2Absolute
1,429
SonLVLObjDefs/ARZ/OneWayDoor.cs
using SonicRetro.SonLVL.API; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; namespace S2ObjectDefinitions.ARZ { class OneWayDoor : ObjectDefinition { private Sprite sprite; private PropertySpec[] properties = new PropertySpec[1]; public override void Init(ObjectData data) { sprite = new Sprite(LevelData.GetSpriteSheet("ARZ/Objects.gif").GetSection(1, 78, 16, 64), -8, -32); properties[0] = new PropertySpec("Open From", typeof(int), "Extended", "Which direction this Door should be opened from.", null, new Dictionary<string, int> { { "Left", 0 }, { "Right", 1 } }, (obj) => (obj.PropertyValue == 0) ? 0 : 1, (obj, value) => obj.PropertyValue = (byte)((int)value)); } public override ReadOnlyCollection<byte> Subtypes { get { return new ReadOnlyCollection<byte>(new byte[] {0, 1}); } } public override PropertySpec[] CustomProperties { get { return properties; } } public override string SubtypeName(byte subtype) { switch (subtype) { case 0: return "Open From Left"; case 1: return "Open From Right"; default: return "Unknown"; } } public override Sprite Image { get { return sprite; } } public override Sprite SubtypeImage(byte subtype) { return sprite; } public override Sprite GetSprite(ObjectEntry obj) { return sprite; } } }
0
0.814565
1
0.814565
game-dev
MEDIA
0.666281
game-dev
0.950941
1
0.950941
badkangaroo/UnityProjects
1,086
Bool/Assets/Example.cs
using UnityEngine; using System.Collections; public class Example : MonoBehaviour { public int Gold; public bool SomeBool; // Use this for initialization void Start () { SomeBool = (1 == 1); int a = 1; int b = 3; SomeBool = (a == b); if (SomeBool) { transform.Rotate (new Vector3 (45f, 0f, 0f)); } } public int change; // Update is called once per frame public GameObject A_Cube; public GameObject B_Cube; void Update () { /*if (change >= 10) { transform.position = new Vector3 (3f, 0f, 0f); } else if (change <= -10) { transform.position = new Vector3 (-3f, 0f, 0f); } else { transform.position = new Vector3 (0f, 0f, 0f); }*/ Color col = Color.red; float Ax = A_Cube.transform.position.x; float Ay = A_Cube.transform.position.y; float Bx = B_Cube.transform.position.x; float By = B_Cube.transform.position.y; if (Ax > Bx) { col = Color.black; } else if (Ax <= Bx) { col = Color.blue; } GetComponent<Renderer>().material.color = col; } }
0
0.850335
1
0.850335
game-dev
MEDIA
0.844528
game-dev,graphics-rendering
0.854791
1
0.854791
BG-Software-LLC/WildStacker
5,389
NMS/v1_21_3/src/main/java/com/bgsoftware/wildstacker/nms/v1_21_3/NMSWorldImpl.java
package com.bgsoftware.wildstacker.nms.v1_21_3; import com.bgsoftware.common.reflection.ReflectMethod; import com.bgsoftware.wildstacker.nms.NMSWorld; import com.bgsoftware.wildstacker.utils.chunks.ChunkPosition; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.entity.raid.Raid; import net.minecraft.world.entity.raid.Raider; import net.minecraft.world.level.block.RotatedPillarBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.data.type.TurtleEgg; import org.bukkit.craftbukkit.CraftParticle; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.block.CraftBlock; import org.bukkit.craftbukkit.block.data.CraftBlockData; import org.bukkit.craftbukkit.entity.CraftEntity; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.entity.CraftRaider; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.function.Predicate; public class NMSWorldImpl implements NMSWorld { private static final ReflectMethod<Boolean> RAIDER_HAS_ACTIVE_RAID = new ReflectMethod<>(Raider.class, boolean.class, "gE"); private static final ReflectMethod<Raid> RAIDER_GET_CURRENT_RAID = new ReflectMethod<>(Raider.class, Raid.class, "gB"); @Override public boolean canSpawnOn(org.bukkit.entity.Entity bukkitEntity, Location location) { if (location.getWorld() == null) return false; ServerLevel serverLevel = ((CraftWorld) location.getWorld()).getHandle(); Entity entity = ((CraftEntity) bukkitEntity).getHandle(); BlockPos blockPos = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()); return SpawnPlacements.checkSpawnRules(entity.getType(), serverLevel, EntitySpawnReason.SPAWNER, blockPos, serverLevel.getRandom()); } @Override public Collection<org.bukkit.entity.Entity> getEntitiesAtChunk(ChunkPosition chunkPosition) { return new ArrayList<>(); } @Override public Collection<org.bukkit.entity.Entity> getNearbyEntities(Location location, int range, Predicate<org.bukkit.entity.Entity> filter) { if (location.getWorld() == null) return Collections.emptyList(); ServerLevel serverLevel = ((CraftWorld) location.getWorld()).getHandle(); List<org.bukkit.entity.Entity> entities = new LinkedList<>(); AABB searchArea = new AABB( location.getBlockX() - range, location.getBlockY() - range, location.getBlockZ() - range, location.getBlockX() + range, location.getBlockY() + range, location.getBlockZ() + range ); serverLevel.getEntities().get(searchArea, entity -> { if (filter == null || filter.test(entity.getBukkitEntity())) entities.add(entity.getBukkitEntity()); }); return entities; } @Override public void playParticle(String particle, Location location, int count, int offsetX, int offsetY, int offsetZ, double extra) { World world = location.getWorld(); if (world != null) { ServerLevel serverLevel = ((CraftWorld) world).getHandle(); serverLevel.sendParticles(null, CraftParticle.createParticleParam(Particle.valueOf(particle), null), location.getBlockX(), location.getBlockY(), location.getBlockZ(), count, offsetX, offsetY, offsetZ, extra, false); } } @Override public void attemptJoinRaid(org.bukkit.entity.Player player, org.bukkit.entity.Entity bukkitRaider) { Raider raider = ((CraftRaider) bukkitRaider).getHandle(); boolean hasActiveRaid; Raid raid; try { hasActiveRaid = raider.hasActiveRaid(); raid = raider.getCurrentRaid(); } catch (Throwable error) { hasActiveRaid = RAIDER_HAS_ACTIVE_RAID.invoke(raider); raid = RAIDER_GET_CURRENT_RAID.invoke(raider); } if (hasActiveRaid) raid.addHeroOfTheVillage(((CraftPlayer) player).getHandle()); } @Override public void startEntityListen(World world) { // Do nothing. } @Override public Object getBlockData(Material type, short data) { return CraftBlockData.fromData(CraftMagicNumbers.getBlock(type, (byte) data)); } @Override public boolean isRotatable(Block block) { BlockState blockState = ((CraftBlock) block).getNMS(); return blockState.getBlock() instanceof RotatedPillarBlock; } @Override public void setTurtleEggsAmount(Block turtleEggBlock, int amount) { TurtleEgg turtleEgg = (TurtleEgg) turtleEggBlock.getBlockData(); turtleEgg.setEggs(amount); turtleEggBlock.setBlockData(turtleEgg, true); } }
0
0.82995
1
0.82995
game-dev
MEDIA
0.999192
game-dev
0.942634
1
0.942634
scripthookvdotnet/scripthookvdotnet
8,178
source/scripting_v3/GTA/ScriptSound.cs
// // Copyright (C) 2023 kagikn & contributors // License: https://github.com/scripthookvdotnet/scripthookvdotnet#license // using GTA.Math; using GTA.Native; using System; namespace GTA { /// <summary> /// Represents a script sound, which is for <c>audScriptSound</c>. It is used for script audio sounds processed /// via the static <c>audScriptAudioEntity</c> instance. /// </summary> public class ScriptSound : IEquatable<ScriptSound> { internal ScriptSound(int id) { Id = id; } /// <summary> /// Gets the script sound id/index. /// </summary> public int Id { get; } /// <summary> /// Returns <see langword="true"/> if the sound <see cref="Id"/> is negative, /// which indicates this <see cref="ScriptSound"/> is not valid. /// </summary> public bool IsNull => Id < 0; /// <summary> /// Plays back a sound with the name <paramref name="soundName"/>. /// If this is used to play a sound for which no pan or speakermask is set by the sound designer, then the sound will play from the map's origin - /// therefore this should only be used to play frontend sounds like menu bleeps or other artificially panned effects. /// </summary> /// <param name="soundName">The sound name to play.</param> /// <param name="setName">The optional sound set name that contains the sound.</param> /// <param name="enableOnReplay"><inheritdoc cref="PlaySoundFrontend(string, string, bool)" path="/param[@name='enableOnReplay']"/></param>. public void PlaySound(string soundName, string setName, bool enableOnReplay = true) { Function.Call(Hash.PLAY_SOUND, Id, soundName, setName, enableOnReplay); } /// <summary> /// Plays back a sound "frontend" - at full volume, panned centrally. /// </summary> /// <param name="soundName">The sound name to play.</param> /// <param name="setName">The optional sound set name that contains the sound.</param> /// <param name="enableOnReplay"> /// <para> /// The name is taken from the official definition, but the effect is unknown. /// </para> /// <para> /// Will be internally disabled if the hash calculated from <paramref name="soundName"/> (with <see cref="Game.GenerateHash(string)"/>) is one of the values /// <c>[0x5A23F3D5, 0xDF84A53C, 0xFD4C28, 0x832CAA0F, 0x17BD10F1, 0xFA4A5AA0, 0x2B8F97E3, 0x1D46A6A2, 0xF5E3A26A, 0xF35C567B, /// 0x71F56AB4, 0xC55C68A0, 0x54C522AD, 0xD382DF7C, 0x2A508F9C, 0xE8F24AFD, 0x8DDBFC96, 0x28C8633, 0x596B8EBB, 0x8A73028A, /// 0x578FE4D7, 0xE52306DE, 0x10109BEB]</c>. /// </para> /// </param> /// <remarks> /// If the sound has a Pan or a SpeakerMask set by the sound designer then it will play using these settings, /// otherwise it will play from dead ahead (0°). /// </remarks> public void PlaySoundFrontend(string soundName, string setName, bool enableOnReplay = true) { Function.Call(Hash.PLAY_SOUND_FRONTEND, Id, soundName, setName, enableOnReplay); } /// <summary> /// Plays back a sound from an <see cref="Entity"/>'s location. /// The sound's position will track the <see cref="Entity"/>'s position as it moves. /// </summary> /// <param name="entity">The <see cref="Entity"/> to play the sound from.</param> /// <param name="soundName">The sound name to play.</param> /// <param name="setName">The optional sound set name that contains the sound.</param> public void PlaySoundFromEntity(Entity entity, string soundName, string setName = null) => Function.Call(Hash.PLAY_SOUND_FROM_ENTITY, Id, soundName, entity.Handle, setName, false, 0); /// <summary> /// Plays back a sound from an absolute position. /// </summary> /// <param name="position">The world coordinates to play the sound from.</param> /// <param name="soundName">The sound name to play.</param> /// <param name="setName">The optional sound set name that contains the sound.</param> /// <param name="isExteriorLoc"> /// If <see langword="true"/>, the sound will use a portal occlusion environmentGroup. /// Only use this if the sound is playing outside and needs occlusion. /// </param> public void PlaySoundFromPosition(Vector3 position, string soundName, string setName = null, bool isExteriorLoc = false) => Function.Call(Hash.PLAY_SOUND_FROM_COORD, Id, soundName, position.X, position.Y, position.Z, setName, false, 0, isExteriorLoc); /// <summary> /// <para> /// Sets a variable on a sound. /// </para> /// <para> /// This method allows to communicate with the sound engine in complex ways, /// by passing a floating point value to a specific sound object. This allows some nice effects such as adjusting the pitch of a sample being to be played back, /// or varying a lowpass cutoff. The VariableName parameter must be set up in RAVE (the audio scripting tool) as well as instruction on its usage on a case-by-case /// basis therefore a sound designer must be consulted with before using this command. /// </para> /// </summary> public void UpdatePosition(string variableName, float variableValue) => Function.Call(Hash.SET_VARIABLE_ON_SOUND, Id, variableName, variableValue); /// <summary> /// Updates a playing sounds absolute position. /// Currently not available in v1.0.617.1 or earlier game versions. /// </summary> /// <param name="position">The new position.</param> public void UpdatePosition(Vector3 position) { if (Game.FileVersion < VersionConstsForGameVersion.v1_0_678_1) { GameVersionNotSupportedException.ThrowIfNotSupported((VersionConstsForGameVersion.v1_0_678_1), nameof(ScriptSound), nameof(UpdatePosition)); } Function.Call(Hash.UPDATE_SOUND_COORD, Id, position.X, position.Y, position.Z); } /// <summary> /// Gets a boolean indicating whether the specified sound instance has completed playing. /// </summary> public bool HasFinished() { return Function.Call<bool>(Hash.HAS_SOUND_FINISHED, Id); } /// <summary> /// Stops a playing sound. /// Calling this method on this <see cref="ScriptSound"/> that has finished playing will have no ill effects in any case /// as long as the <see cref="ScriptSound"/> has not been released. /// </summary> public void Stop() { Function.Call(Hash.STOP_SOUND, Id); } /// <summary> /// Releases this <see cref="ScriptSound"/>. /// This should be called once a sound has finished being manipulated by the script so that its <see cref="ScriptSound"/> /// can be released and re-used. /// </summary> public void Release() { Function.Call(Hash.RELEASE_SOUND_ID, Id); } public bool Equals(ScriptSound other) { return Id == other.Id; } public override bool Equals(object obj) { if (obj is ScriptSound model) { return Equals(model); } return false; } public static bool operator ==(ScriptSound left, ScriptSound right) { return left.Equals(right); } public static bool operator !=(ScriptSound left, ScriptSound right) { return !left.Equals(right); } public static implicit operator InputArgument(ScriptSound value) { return new InputArgument((ulong)value.Id); } public override int GetHashCode() { return Id.GetHashCode(); } } }
0
0.82816
1
0.82816
game-dev
MEDIA
0.783291
game-dev,audio-video-media
0.822895
1
0.822895
Black-Tek/BlackTek-Server
8,546
data/npc/scripts/runes.lua
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local voices = { {text = "Runes, wands, rods, health and mana potions! Have a look!"} } npcHandler:addModule(VoiceModule:new(voices)) local shopModule = ShopModule:new() npcHandler:addModule(shopModule) keywordHandler:addKeyword({'stuff'}, StdModule.say, {npcHandler = npcHandler, text = 'Just ask me for a {trade} to see my offers.'}) keywordHandler:addAliasKeyword({'wares'}) keywordHandler:addAliasKeyword({'offer'}) shopModule:addBuyableItem({'spellbook'}, 2175, 150, 'spellbook') shopModule:addBuyableItem({'magic lightwand'}, 2162, 400, 'magic lightwand') shopModule:addBuyableItem({'small health'}, 8704, 20, 1, 'small health potion') shopModule:addBuyableItem({'health potion'}, 7618, 45, 1, 'health potion') shopModule:addBuyableItem({'mana potion'}, 7620, 50, 1, 'mana potion') shopModule:addBuyableItem({'strong health'}, 7588, 100, 1, 'strong health potion') shopModule:addBuyableItem({'strong mana'}, 7589, 80, 1, 'strong mana potion') shopModule:addBuyableItem({'great health'}, 7591, 190, 1, 'great health potion') shopModule:addBuyableItem({'great mana'}, 7590, 120, 1, 'great mana potion') shopModule:addBuyableItem({'great spirit'}, 8472, 190, 1, 'great spirit potion') shopModule:addBuyableItem({'ultimate health'}, 8473, 310, 1, 'ultimate health potion') shopModule:addBuyableItem({'antidote potion'}, 8474, 50, 1, 'antidote potion') shopModule:addSellableItem({'empty potion flask', 'empty flask'}, 7636, 5, 'empty small potion flask') shopModule:addSellableItem({'strong potion flask', 'strong flask'}, 7634, 10, 'empty strong potion flask') shopModule:addSellableItem({'great potion flask', 'great flask'}, 7635, 15, 'empty great potion flask') shopModule:addBuyableItem({'intense healing'}, 2265, 95, 1, 'intense healing rune') shopModule:addBuyableItem({'ultimate healing'}, 2273, 175, 1, 'ultimate healing rune') shopModule:addBuyableItem({'magic wall'}, 2293, 350, 3, 'magic wall rune') shopModule:addBuyableItem({'destroy field'}, 2261, 45, 3, 'destroy field rune') shopModule:addBuyableItem({'light magic missile'}, 2287, 40, 10, 'light magic missile rune') shopModule:addBuyableItem({'heavy magic missile'}, 2311, 120, 10, 'heavy magic missile rune') shopModule:addBuyableItem({'great fireball'}, 2304, 180, 4, 'great fireball rune') shopModule:addBuyableItem({'explosion'}, 2313, 250, 6, 'explosion rune') shopModule:addBuyableItem({'sudden death'}, 2268, 350, 3, 'sudden death rune') shopModule:addBuyableItem({'paralyze'}, 2278, 700, 1, 'paralyze rune') shopModule:addBuyableItem({'animate dead'}, 2316, 375, 1, 'animate dead rune') shopModule:addBuyableItem({'convince creature'}, 2290, 80, 1, 'convince creature rune') shopModule:addBuyableItem({'chameleon'}, 2291, 210, 1, 'chameleon rune') shopModule:addBuyableItem({'disintegrate'}, 2310, 80, 3, 'disintegrate rune') shopModule:addBuyableItemContainer({'bp ap'}, 2002, 8474, 2000, 1, 'backpack of antidote potions') shopModule:addBuyableItemContainer({'bp slhp'}, 2000, 8704, 400, 1, 'backpack of small health potions') shopModule:addBuyableItemContainer({'bp hp'}, 2000, 7618, 900, 1, 'backpack of health potions') shopModule:addBuyableItemContainer({'bp mp'}, 2001, 7620, 1000, 1, 'backpack of mana potions') shopModule:addBuyableItemContainer({'bp shp'}, 2000, 7588, 2000, 1, 'backpack of strong health potions') shopModule:addBuyableItemContainer({'bp smp'}, 2001, 7589, 1600, 1, 'backpack of strong mana potions') shopModule:addBuyableItemContainer({'bp ghp'}, 2000, 7591, 3800, 1, 'backpack of great health potions') shopModule:addBuyableItemContainer({'bp gmp'}, 2001, 7590, 2400, 1, 'backpack of great mana potions') shopModule:addBuyableItemContainer({'bp gsp'}, 1999, 8472, 3800, 1, 'backpack of great spirit potions') shopModule:addBuyableItemContainer({'bp uhp'}, 2000, 8473, 6200, 1, 'backpack of ultimate health potions') shopModule:addBuyableItem({'wand of vortex', 'vortex'}, 2190, 500, 'wand of vortex') shopModule:addBuyableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 1000, 'wand of dragonbreath') shopModule:addBuyableItem({'wand of decay', 'decay'}, 2188, 5000, 'wand of decay') shopModule:addBuyableItem({'wand of draconia', 'draconia'}, 8921, 7500, 'wand of draconia') shopModule:addBuyableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 10000, 'wand of cosmic energy') shopModule:addBuyableItem({'wand of inferno', 'inferno'}, 2187, 15000, 'wand of inferno') shopModule:addBuyableItem({'wand of starstorm', 'starstorm'}, 8920, 18000, 'wand of starstorm') shopModule:addBuyableItem({'wand of voodoo', 'voodoo'}, 8922, 22000, 'wand of voodoo') shopModule:addBuyableItem({'snakebite rod', 'snakebite'}, 2182, 500, 'snakebite rod') shopModule:addBuyableItem({'moonlight rod', 'moonlight'}, 2186, 1000, 'moonlight rod') shopModule:addBuyableItem({'necrotic rod', 'necrotic'}, 2185, 5000, 'necrotic rod') shopModule:addBuyableItem({'northwind rod', 'northwind'}, 8911, 7500, 'northwind rod') shopModule:addBuyableItem({'terra rod', 'terra'}, 2181, 10000, 'terra rod') shopModule:addBuyableItem({'hailstorm rod', 'hailstorm'}, 2183, 15000, 'hailstorm rod') shopModule:addBuyableItem({'springsprout rod', 'springsprout'}, 8912, 18000, 'springsprout rod') shopModule:addBuyableItem({'underworld rod', 'underworld'}, 8910, 22000, 'underworld rod') shopModule:addSellableItem({'wand of vortex', 'vortex'}, 2190, 250, 'wand of vortex') shopModule:addSellableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 500, 'wand of dragonbreath') shopModule:addSellableItem({'wand of decay', 'decay'}, 2188, 2500, 'wand of decay') shopModule:addSellableItem({'wand of draconia', 'draconia'}, 8921, 3750, 'wand of draconia') shopModule:addSellableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 5000, 'wand of cosmic energy') shopModule:addSellableItem({'wand of inferno', 'inferno'}, 2187, 7500, 'wand of inferno') shopModule:addSellableItem({'wand of starstorm', 'starstorm'}, 8920, 9000, 'wand of starstorm') shopModule:addSellableItem({'wand of voodoo', 'voodoo'}, 8922, 11000, 'wand of voodoo') shopModule:addSellableItem({'snakebite rod', 'snakebite'}, 2182, 250,'snakebite rod') shopModule:addSellableItem({'moonlight rod', 'moonlight'}, 2186, 500, 'moonlight rod') shopModule:addSellableItem({'necrotic rod', 'necrotic'}, 2185, 2500, 'necrotic rod') shopModule:addSellableItem({'northwind rod', 'northwind'}, 8911, 3750, 'northwind rod') shopModule:addSellableItem({'terra rod', 'terra'}, 2181, 5000, 'terra rod') shopModule:addSellableItem({'hailstorm rod', 'hailstorm'}, 2183, 7500, 'hailstorm rod') shopModule:addSellableItem({'springsprout rod', 'springsprout'}, 8912, 9000, 'springsprout rod') shopModule:addSellableItem({'underworld rod', 'underworld'}, 8910, 11000, 'underworld rod') function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) local vocationId = player:getVocation():getId() local items = { [1] = 2190, [2] = 2182, [5] = 2190, [6] = 2182 } if msgcontains(msg, 'first rod') or msgcontains(msg, 'first wand') then if table.contains({1, 2, 5, 6}, vocationId) then if player:getStorageValue(PlayerStorageKeys.firstRod) == -1 then selfSay('So you ask me for a {' .. ItemType(items[vocationId]):getName() .. '} to begin your adventure?', cid) npcHandler.topic[cid] = 1 else selfSay('What? I have already gave you one {' .. ItemType(items[vocationId]):getName() .. '}!', cid) end else selfSay('Sorry, you aren\'t a druid either a sorcerer.', cid) end elseif msgcontains(msg, 'yes') then if npcHandler.topic[cid] == 1 then player:addItem(items[vocationId], 1) selfSay('Here you are young adept, take care yourself.', cid) player:setStorageValue(PlayerStorageKeys.firstRod, 1) end npcHandler.topic[cid] = 0 elseif msgcontains(msg, 'no') and npcHandler.topic[cid] == 1 then selfSay('Ok then.', cid) npcHandler.topic[cid] = 0 end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
0
0.814076
1
0.814076
game-dev
MEDIA
0.956683
game-dev
0.693667
1
0.693667
tgstation/tgstation
20,471
code/modules/mod/mod_link.dm
/proc/make_link_visual_generic(datum/mod_link/mod_link, proc_path) var/mob/living/user = mod_link.get_user_callback.Invoke() var/obj/effect/overlay/link_visual = new() link_visual.name = "holocall ([mod_link.id])" link_visual.mouse_opacity = MOUSE_OPACITY_TRANSPARENT LAZYADD(mod_link.holder.update_on_z, link_visual) link_visual.appearance_flags |= KEEP_TOGETHER link_visual.makeHologram(0.75) mod_link.visual_overlays = user.overlays - user.active_thinking_indicator link_visual.add_overlay(mod_link.visual_overlays) mod_link.visual = link_visual mod_link.holder.become_hearing_sensitive(REF(mod_link)) mod_link.holder.RegisterSignals(user, list(COMSIG_CARBON_APPLY_OVERLAY, COMSIG_CARBON_REMOVE_OVERLAY), proc_path) return link_visual /proc/get_link_visual_generic(datum/mod_link/mod_link, atom/movable/visuals, proc_path) var/mob/living/user = mod_link.get_user_callback.Invoke() playsound(mod_link.holder, 'sound/machines/terminal/terminal_processing.ogg', 50, vary = TRUE) visuals.add_overlay(mutable_appearance('icons/effects/effects.dmi', "static_base", ABOVE_NORMAL_TURF_LAYER)) visuals.add_overlay(mutable_appearance('icons/effects/effects.dmi', "modlink", ABOVE_ALL_MOB_LAYER)) visuals.add_filter("crop_square", 1, alpha_mask_filter(icon = icon('icons/effects/effects.dmi', "modlink_filter"))) visuals.maptext_height = 6 visuals.alpha = 0 user.vis_contents += visuals visuals.forceMove(user) animate(visuals, 0.5 SECONDS, alpha = 255) var/datum/callback/setdir_callback = CALLBACK(mod_link.holder, proc_path) setdir_callback.Invoke(user, user.dir, user.dir) mod_link.holder.RegisterSignal(mod_link.holder.loc, COMSIG_ATOM_DIR_CHANGE, proc_path) /proc/delete_link_visual_generic(datum/mod_link/mod_link, mob/living/old_user) playsound(mod_link.get_other().holder, 'sound/machines/terminal/terminal_processing.ogg', 50, vary = TRUE, frequency = -1) LAZYREMOVE(mod_link.holder.update_on_z, mod_link.visual) mod_link.holder.lose_hearing_sensitivity(REF(mod_link)) mod_link.holder.UnregisterSignal(old_user, list(COMSIG_CARBON_APPLY_OVERLAY, COMSIG_CARBON_REMOVE_OVERLAY, COMSIG_ATOM_DIR_CHANGE)) QDEL_NULL(mod_link.visual) /proc/on_user_set_dir_generic(datum/mod_link/mod_link, newdir) var/atom/other_visual = mod_link.get_other().visual if(!newdir) //can sometimes be null or 0 return other_visual.setDir(SOUTH) other_visual.pixel_x = 0 other_visual.pixel_y = 0 var/matrix/new_transform = matrix() if(newdir & NORTH) other_visual.pixel_y = 13 other_visual.layer = BELOW_MOB_LAYER if(newdir & SOUTH) other_visual.pixel_y = -24 other_visual.layer = ABOVE_ALL_MOB_LAYER new_transform.Scale(-1, 1) new_transform.Translate(-1, 0) if(newdir & EAST) other_visual.pixel_x = 14 other_visual.layer = BELOW_MOB_LAYER new_transform.Shear(0.5, 0) new_transform.Scale(0.65, 1) if(newdir & WEST) other_visual.pixel_x = -14 other_visual.layer = BELOW_MOB_LAYER new_transform.Shear(-0.5, 0) new_transform.Scale(0.65, 1) other_visual.transform = new_transform /obj/item/mod/control/Initialize(mapload, datum/mod_theme/new_theme, new_skin, obj/item/mod/core/new_core) . = ..() mod_link = new( src, starting_frequency, CALLBACK(src, PROC_REF(get_wearer)), CALLBACK(src, PROC_REF(can_call)), CALLBACK(src, PROC_REF(make_link_visual)), CALLBACK(src, PROC_REF(get_link_visual)), CALLBACK(src, PROC_REF(delete_link_visual)) ) /obj/item/mod/control/multitool_act_secondary(mob/living/user, obj/item/multitool/tool) . = NONE var/tool_frequency = null if(istype(tool.buffer, /datum/mod_link)) var/datum/mod_link/buffer_link = tool.buffer tool_frequency = buffer_link.frequency balloon_alert(user, "frequency set") . = ITEM_INTERACT_SUCCESS if(!tool_frequency && mod_link.frequency) tool.set_buffer(mod_link) balloon_alert(user, "frequency copied") . = ITEM_INTERACT_SUCCESS else if(tool_frequency && !mod_link.frequency) mod_link.frequency = tool_frequency . = ITEM_INTERACT_SUCCESS else if(tool_frequency && mod_link.frequency) var/response = tgui_alert(user, "Would you like to copy or imprint the frequency?", "MODlink Frequency", list("Copy", "Imprint")) if(!user.is_holding(tool)) return ITEM_INTERACT_BLOCKING switch(response) if("Copy") tool.set_buffer(mod_link) balloon_alert(user, "frequency copied") . = ITEM_INTERACT_SUCCESS if("Imprint") mod_link.frequency = tool_frequency balloon_alert(user, "frequency set") . = ITEM_INTERACT_SUCCESS /obj/item/mod/control/proc/can_call() return get_charge() && wearer && wearer.stat < DEAD /obj/item/mod/control/proc/make_link_visual() return make_link_visual_generic(mod_link, PROC_REF(on_overlay_change)) /obj/item/mod/control/proc/get_link_visual(atom/movable/visuals) return get_link_visual_generic(mod_link, visuals, PROC_REF(on_wearer_set_dir)) /obj/item/mod/control/proc/delete_link_visual(mob/living/old_user) return delete_link_visual_generic(mod_link, old_user) /obj/item/mod/control/Hear(atom/movable/speaker, message_language, raw_message, radio_freq, radio_freq_name, radio_freq_color, list/spans, list/message_mods, message_range) . = ..() if(speaker != wearer && speaker != ai_assistant) return mod_link.visual.say(raw_message, spans = spans, sanitize = FALSE, language = message_language, message_range = 2, message_mods = message_mods) /obj/item/mod/control/proc/on_overlay_change(atom/source, cache_index, overlay) SIGNAL_HANDLER addtimer(CALLBACK(src, PROC_REF(update_link_visual)), 1 TICKS, TIMER_UNIQUE) /obj/item/mod/control/proc/update_link_visual() if(QDELETED(mod_link.link_call)) return mod_link.visual.cut_overlay(mod_link.visual_overlays) mod_link.visual_overlays = wearer.overlays - wearer.active_thinking_indicator mod_link.visual.add_overlay(mod_link.visual_overlays) /obj/item/mod/control/proc/on_wearer_set_dir(atom/source, dir, newdir) SIGNAL_HANDLER on_user_set_dir_generic(mod_link, newdir || SOUTH) /obj/item/clothing/neck/link_scryer name = "\improper MODlink scryer" desc = "An intricate piece of machinery that creates a holographic video call with another MODlink-compatible device. Essentially a video necklace." icon_state = "modlink" actions_types = list(/datum/action/item_action/call_link) /// The installed power cell. var/obj/item/stock_parts/power_store/cell /// The MODlink datum we operate. var/datum/mod_link/mod_link /// Initial frequency of the MODlink. var/starting_frequency /// An additional name tag for the scryer, seen as "MODlink scryer - [label]" var/label /obj/item/clothing/neck/link_scryer/Initialize(mapload) . = ..() mod_link = new( src, starting_frequency, CALLBACK(src, PROC_REF(get_user)), CALLBACK(src, PROC_REF(can_call)), CALLBACK(src, PROC_REF(make_link_visual)), CALLBACK(src, PROC_REF(get_link_visual)), CALLBACK(src, PROC_REF(delete_link_visual)) ) START_PROCESSING(SSobj, src) /obj/item/clothing/neck/link_scryer/Destroy() QDEL_NULL(cell) QDEL_NULL(mod_link) STOP_PROCESSING(SSobj, src) return ..() /obj/item/clothing/neck/link_scryer/examine(mob/user) . = ..() if(cell) . += span_notice("The battery charge reads [cell.percent()]%. <b>Right-click</b> with an empty hand to remove it.") else . += span_notice("It is missing a battery, one can be installed by clicking with a power cell on it.") . += span_notice("The MODlink ID is [mod_link.id], frequency is [mod_link.frequency || "unset"]. <b>Right-click</b> with multitool to copy/imprint frequency.") . += span_notice("Use in hand to set name.") /obj/item/clothing/neck/link_scryer/equipped(mob/living/user, slot) . = ..() if(slot != ITEM_SLOT_NECK) mod_link?.end_call() /obj/item/clothing/neck/link_scryer/dropped(mob/living/user) . = ..() mod_link?.end_call() /obj/item/clothing/neck/link_scryer/attack_self(mob/user, modifiers) var/new_label = reject_bad_text(tgui_input_text(user, "Change the visible name", "Set Name", label, MAX_NAME_LEN)) if(!user.is_holding(src)) return if(!new_label) balloon_alert(user, "invalid name!") return label = new_label balloon_alert(user, "name set") update_name() /obj/item/clothing/neck/link_scryer/process(seconds_per_tick) if(!mod_link.link_call) return cell.use(0.02 * STANDARD_CELL_RATE * seconds_per_tick, force = TRUE) /obj/item/clothing/neck/link_scryer/attackby(obj/item/attacked_by, mob/user, list/modifiers, list/attack_modifiers) . = ..() if(cell || !istype(attacked_by, /obj/item/stock_parts/power_store/cell)) return if(!user.transferItemToLoc(attacked_by, src)) return cell = attacked_by balloon_alert(user, "cell installed") /obj/item/clothing/neck/link_scryer/update_name(updates) . = ..() name = "[initial(name)][label ? " - [label]" : ""]" /obj/item/clothing/neck/link_scryer/Exited(atom/movable/gone, direction) . = ..() if(gone == cell) cell = null /obj/item/clothing/neck/link_scryer/attack_hand_secondary(mob/user, list/modifiers) if(!cell) return SECONDARY_ATTACK_CONTINUE_CHAIN balloon_alert(user, "cell removed") user.put_in_hands(cell) return SECONDARY_ATTACK_CANCEL_ATTACK_CHAIN /obj/item/clothing/neck/link_scryer/multitool_act_secondary(mob/living/user, obj/item/multitool/tool) . = NONE var/tool_frequency = null if(istype(tool.buffer, /datum/mod_link)) var/datum/mod_link/buffer_link = tool.buffer tool_frequency = buffer_link.frequency balloon_alert(user, "frequency set") . = ITEM_INTERACT_SUCCESS if(!tool_frequency && mod_link.frequency) tool.set_buffer(mod_link) balloon_alert(user, "frequency copied") . = ITEM_INTERACT_SUCCESS else if(tool_frequency && !mod_link.frequency) mod_link.frequency = tool_frequency . = ITEM_INTERACT_SUCCESS else if(tool_frequency && mod_link.frequency) var/response = tgui_alert(user, "Would you like to copy or imprint the frequency?", "MODlink Frequency", list("Copy", "Imprint")) if(!user.is_holding(tool)) return ITEM_INTERACT_BLOCKING switch(response) if("Copy") tool.set_buffer(mod_link) balloon_alert(user, "frequency copied") . = ITEM_INTERACT_SUCCESS if("Imprint") mod_link.frequency = tool_frequency balloon_alert(user, "frequency set") . = ITEM_INTERACT_SUCCESS /obj/item/clothing/neck/link_scryer/worn_overlays(mutable_appearance/standing, isinhands) . = ..() if(!QDELETED(mod_link.link_call)) . += mutable_appearance('icons/mob/clothing/neck.dmi', "modlink_active") /obj/item/clothing/neck/link_scryer/ui_action_click(mob/user) if(mod_link.link_call) mod_link.end_call() else if(QDELETED(cell)) user.balloon_alert(user, "no cell installed!") else if(!cell.charge) user.balloon_alert(user, "no charge!") else call_link(user, mod_link) /obj/item/clothing/neck/link_scryer/proc/get_user() var/mob/living/carbon/user = loc return istype(user) && user.wear_neck == src ? user : null /obj/item/clothing/neck/link_scryer/proc/can_call() var/mob/living/user = loc return istype(user) && cell?.charge && user.stat < DEAD /obj/item/clothing/neck/link_scryer/proc/make_link_visual() var/mob/living/user = mod_link.get_user_callback.Invoke() user.update_worn_neck() return make_link_visual_generic(mod_link, PROC_REF(on_overlay_change)) /obj/item/clothing/neck/link_scryer/proc/get_link_visual(atom/movable/visuals) return get_link_visual_generic(mod_link, visuals, PROC_REF(on_user_set_dir)) /obj/item/clothing/neck/link_scryer/proc/delete_link_visual(mob/living/old_user) if(!QDELETED(old_user)) old_user.update_worn_neck() return delete_link_visual_generic(mod_link, old_user) /obj/item/clothing/neck/link_scryer/Hear(atom/movable/speaker, message_language, raw_message, radio_freq, radio_freq_name, radio_freq_color, list/spans, list/message_mods, message_range) . = ..() if(speaker != loc) return mod_link.visual.say(raw_message, spans = spans, sanitize = FALSE, language = message_language, message_range = 3, message_mods = message_mods) /obj/item/clothing/neck/link_scryer/proc/on_overlay_change(atom/source, cache_index, overlay) SIGNAL_HANDLER addtimer(CALLBACK(src, PROC_REF(update_link_visual)), 1 TICKS, TIMER_UNIQUE) /obj/item/clothing/neck/link_scryer/proc/update_link_visual() if(QDELETED(mod_link.link_call)) return var/mob/living/user = loc mod_link.visual.cut_overlay(mod_link.visual_overlays) mod_link.visual_overlays = user.overlays - user.active_thinking_indicator mod_link.visual.add_overlay(mod_link.visual_overlays) /obj/item/clothing/neck/link_scryer/proc/on_user_set_dir(atom/source, dir, newdir) SIGNAL_HANDLER on_user_set_dir_generic(mod_link, newdir || SOUTH) /obj/item/clothing/neck/link_scryer/loaded starting_frequency = MODLINK_FREQ_NANOTRASEN /obj/item/clothing/neck/link_scryer/loaded/Initialize(mapload) . = ..() cell = new /obj/item/stock_parts/power_store/cell/high(src) /obj/item/clothing/neck/link_scryer/loaded/charlie starting_frequency = MODLINK_FREQ_CHARLIE /// A MODlink datum, used to handle unique functions that will be used in the MODlink call. /datum/mod_link /// Generic name for multitool buffers. var/name = "MODlink" /// The frequency of the MODlink. You can only call other MODlinks on the same frequency. var/frequency /// The unique ID of the MODlink. var/id = "" /// The atom that holds the MODlink. var/atom/movable/holder /// A reference to the visuals generated by the MODlink. var/atom/movable/visual /// A list of all overlays of the user, copied everytime they have an overlay change. var/list/visual_overlays = list() /// A reference to the call between two MODlinks. var/datum/mod_link_call/link_call /// Weakref to the user that is involved in our current call, for cleaning up after ourselves. var/datum/weakref/user_in_call_ref /// A callback that returns the user of the MODlink. var/datum/callback/get_user_callback /// A callback that returns whether the MODlink can currently call. var/datum/callback/can_call_callback /// A callback that returns the visuals of the MODlink. var/datum/callback/make_visual_callback /// A callback that receives the visuals of the other MODlink. var/datum/callback/get_visual_callback /// A callback that deletes the visuals of the MODlink. var/datum/callback/delete_visual_callback /datum/mod_link/New( atom/holder, frequency, datum/callback/get_user_callback, datum/callback/can_call_callback, datum/callback/make_visual_callback, datum/callback/get_visual_callback, datum/callback/delete_visual_callback ) var/attempts = 0 var/digits_to_make = 3 do if(attempts == 10) attempts = 0 digits_to_make++ id = "" for(var/i in 1 to digits_to_make) id += num2text(rand(0,9)) attempts++ while(GLOB.mod_link_ids[id]) GLOB.mod_link_ids[id] = src src.frequency = frequency src.holder = holder src.get_user_callback = get_user_callback src.can_call_callback = can_call_callback src.make_visual_callback = make_visual_callback src.get_visual_callback = get_visual_callback src.delete_visual_callback = delete_visual_callback RegisterSignal(holder, COMSIG_QDELETING, PROC_REF(on_holder_delete)) /datum/mod_link/Destroy() GLOB.mod_link_ids -= id if(link_call) end_call() get_user_callback = null make_visual_callback = null get_visual_callback = null delete_visual_callback = null return ..() /datum/mod_link/proc/get_other() RETURN_TYPE(/datum/mod_link) if(!link_call) return return link_call.link_caller == src ? link_call.link_receiver : link_call.link_caller /datum/mod_link/proc/call_link(datum/mod_link/called, mob/user) if(!frequency) return if(!istype(called)) holder.balloon_alert(user, "invalid target!") return var/mob/living/link_user = get_user_callback.Invoke() if(!link_user) return if(HAS_TRAIT(link_user, TRAIT_IN_CALL)) holder.balloon_alert(user, "already calling!") return var/mob/living/link_target = called.get_user_callback.Invoke() if(!link_target) holder.balloon_alert(user, "invalid target!") return if(HAS_TRAIT(link_target, TRAIT_IN_CALL)) holder.balloon_alert(user, "target already in call!") return if(!can_call_callback.Invoke() || !called.can_call_callback.Invoke()) holder.balloon_alert(user, "can't call!") return link_target.playsound_local(get_turf(called.holder), 'sound/items/weapons/ring.ogg', 15, vary = TRUE) var/atom/movable/screen/alert/modlink_call/alert = link_target.throw_alert("[REF(src)]_modlink", /atom/movable/screen/alert/modlink_call) alert.desc = "[holder] ([id]) is calling you! Left-click this to accept the call. Right-click to deny it." alert.link_caller_ref = WEAKREF(src) alert.link_receiver_ref = WEAKREF(called) alert.user_ref = WEAKREF(user) /datum/mod_link/proc/end_call() QDEL_NULL(link_call) /datum/mod_link/proc/entered_call(datum/mod_link/other_link) var/mob/living/user = get_user_callback.Invoke() user_in_call_ref = WEAKREF(user) ADD_TRAIT(user, TRAIT_IN_CALL, REF(src)) var/other_visual = other_link.make_visual_callback.Invoke() get_visual_callback.Invoke(other_visual) /datum/mod_link/proc/exiting_call() var/mob/living/old_user = user_in_call_ref?.resolve() user_in_call_ref = null if(old_user) REMOVE_TRAIT(old_user, TRAIT_IN_CALL, REF(src)) delete_visual_callback.Invoke(old_user) /datum/mod_link/proc/on_holder_delete(atom/source) SIGNAL_HANDLER qdel(src) /// A MODlink call datum, used to handle the call between two MODlinks. /datum/mod_link_call /// The MODlink that is calling. var/datum/mod_link/link_caller /// The MODlink that is being called. var/datum/mod_link/link_receiver /datum/mod_link_call/New(datum/mod_link/link_caller, datum/mod_link/link_receiver) src.link_caller = link_caller src.link_receiver = link_receiver link_caller.link_call = src link_receiver.link_call = src link_caller.entered_call(link_receiver) link_receiver.entered_call(link_caller) START_PROCESSING(SSprocessing, src) /datum/mod_link_call/Destroy() link_caller.exiting_call() link_receiver.exiting_call() link_caller.link_call = null link_receiver.link_call = null STOP_PROCESSING(SSprocessing, src) return ..() /datum/mod_link_call/process(seconds_per_tick) if(can_continue_call()) return qdel(src) /datum/mod_link_call/proc/can_continue_call() return link_caller.frequency == link_receiver.frequency && link_caller.can_call_callback.Invoke() && link_receiver.can_call_callback.Invoke() /proc/call_link(mob/user, datum/mod_link/calling_link) if(!calling_link.frequency) return var/list/callers = list() for(var/id in GLOB.mod_link_ids) var/datum/mod_link/link = GLOB.mod_link_ids[id] if(link.frequency != calling_link.frequency) continue if(link == calling_link) continue if(!link.can_call_callback.Invoke()) continue callers["[link.holder] ([id])"] = id if(!length(callers)) calling_link.holder.balloon_alert(user, "no targets on freq [calling_link.frequency]!") return var/chosen_link = tgui_input_list(user, "Choose ID to call from [calling_link.frequency] frequency", "MODlink", callers) if(!chosen_link) return calling_link.call_link(GLOB.mod_link_ids[callers[chosen_link]], user) /atom/movable/screen/alert/modlink_call name = "MODlink Call Incoming" desc = "Someone is calling you! Left-click this to accept the call. Right-click to deny it." icon_state = "called" timeout = 10 SECONDS clickable_glow = TRUE var/end_message = "call timed out!" /// A weak reference to the MODlink that is calling. var/datum/weakref/link_caller_ref /// A weak reference to the MODlink that is being called. var/datum/weakref/link_receiver_ref /// A weak reference to the mob that is calling. var/datum/weakref/user_ref /atom/movable/screen/alert/modlink_call/Click(location, control, params) . = ..() if(usr != owner) return var/datum/mod_link/link_caller = link_caller_ref.resolve() var/datum/mod_link/link_receiver = link_receiver_ref.resolve() if(!link_caller || !link_receiver) return if(link_caller.link_call || link_receiver.link_call) return var/list/modifiers = params2list(params) if(LAZYACCESS(modifiers, RIGHT_CLICK)) end_message = "call denied!" owner.clear_alert("[REF(link_caller)]_modlink") return end_message = "call accepted" new /datum/mod_link_call(link_caller, link_receiver) owner.clear_alert("[REF(link_caller)]_modlink") /atom/movable/screen/alert/modlink_call/Destroy() var/mob/living/user = user_ref?.resolve() var/datum/mod_link/link_caller = link_caller_ref?.resolve() if(!user || !link_caller) return ..() link_caller.holder.balloon_alert(user, end_message) return ..()
0
0.906291
1
0.906291
game-dev
MEDIA
0.273489
game-dev
0.83616
1
0.83616
OnClick9927/IFramework-Unity
3,928
Assets/Project/Examples/UI/PanelOneView.cs
/********************************************************************************* *Author: OnClick *Version: 1.0 *UnityVersion: 2021.3.33f1c1 *Date: 2024-10-24 *********************************************************************************/ using IFramework.UI; using System.Collections.Generic; using UnityEngine; using static IFramework.UI.UnityEventHelper; namespace IFramework { class AddArg : IEventArgs { public float time; } public class PanelOneView : TestViewBase, IEventHandler<AddArg> { class View { //FieldsStart public UnityEngine.UI.Button Close; public UnityEngine.UI.Button add; public UnityEngine.UI.Button remove; public UnityEngine.Transform items; public UnityEngine.UI.Button OpenOne; public UnityEngine.GameObject Prefab_PanelOneItem; //FieldsEnd public View(IFramework.UI.GameObjectView context) { //InitComponentsStart Close = context.GetComponent<UnityEngine.UI.Button>("Close@sm"); add = context.GetComponent<UnityEngine.UI.Button>("add@sm"); remove = context.GetComponent<UnityEngine.UI.Button>("remove@sm"); items = context.GetTransform("items@sm"); OpenOne = context.GetComponent<UnityEngine.UI.Button>("OpenOne@sm"); Prefab_PanelOneItem = context.FindPrefab("PanelOneItem"); //InitComponentsEnd } } private View view; const string eve_key_remove = "eve_key_remove"; protected override void InitComponents() { view = new View(this); } protected override void OnLoad() { this.BindButton(this.view.remove, () => { Events.Publish(eve_key_remove, null); }); this.BindButton(view.OpenOne, async () => { Log.L("BeginShow"); await (Game.Current as UIGame).ui.Show(PanelNames_UIGame.PanelTwo); Log.L("EndShow"); }); CreateWidgetPool<PanelOneItemWidget>(view.Prefab_PanelOneItem, view.items); //collection = new UIItemViewCollection((Launcher.Instance.game as UIGame).ui); this.BindButton(this.view.Close, (Game.Current as UIGame).CloseView); this.BindButton(this.view.add, () => { //Events.Publish(new AddArg() { time = Time.deltaTime }); Events.Publish(nameof(AddArg), new AddArg() { time = Time.deltaTime }); }); this.SubscribeEvent<AddArg>(this); this.SubscribeEvent(eve_key_remove, (e) => { Remove(); }); this.SubscribeEvent(nameof(AddArg), (e) => { Debug.Log("add"); }); } private Stack<PanelOneItemWidget> queue = new Stack<PanelOneItemWidget>(); private void Remove() { if (queue.Count == 0) return; var pool = this.FindWidgetPool<PanelOneItemWidget>(view.Prefab_PanelOneItem); pool.Set(queue.Pop()); } private void Add() { var pool = this.FindWidgetPool<PanelOneItemWidget>(view.Prefab_PanelOneItem); var result = pool.Get(); result.SetColor(new Color(Random.Range(0, 1f), Random.Range(0, 1f), Random.Range(0, 1f), 1)); queue.Push(result); } void IEventHandler<AddArg>.OnEvent(AddArg msg) { Add(); } protected override void OnShow() { } protected override void OnHide() { } protected override void OnClose() { } } }
0
0.725573
1
0.725573
game-dev
MEDIA
0.972272
game-dev
0.819465
1
0.819465
luakit/luakit
7,824
common/luaobject.h
/* * common/luaobject.h - useful functions for handling Lua objects * * Copyright © 2010 Mason Larobina <mason.larobina@gmail.com> * Copyright © 2009 Julien Danjou <julien@danjou.info> * * 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 LUAKIT_COMMON_LUAOBJECT_H #define LUAKIT_COMMON_LUAOBJECT_H #include <glib-object.h> #include "common/luaclass.h" #include "common/lualib.h" #include "common/signal.h" #include "common/common.h" /** Registry key for the Lua registry API to store a private reference counting * table. This table prevents garbage collection of objects (userdata or * tables) while in use by C functions or objects. * \see http://www.lua.org/manual/5.1/manual.html#3.5 */ #define LUAKIT_OBJECT_REGISTRY_KEY "luakit.object.registry" gint luaH_settype(lua_State *L, lua_class_t *lua_class); void luaH_object_setup(lua_State *L); gpointer luaH_object_incref(lua_State *L, gint tud, gint oud); void luaH_object_decref(lua_State *L, gint tud, gpointer oud); /* Store an item in the environment table of an object. * Removes the stored object from the stack. * `ud` is the index of the object on the stack. * `iud` is the index of the item on the stack. * Return the item reference. */ static inline gpointer luaH_object_ref_item(lua_State *L, gint ud, gint iud) { /* Get the env table from the object */ lua_getfenv(L, ud); gpointer p = luaH_object_incref(L, -1, iud < 0 ? iud - 1 : iud); /* Remove env table */ lua_pop(L, 1); return p; } /* Unref an item from the environment table of an object. * `ud` is the index of the object on the stack. * `p` is the item. */ static inline void luaH_object_unref_item(lua_State *L, gint ud, gpointer p) { /* Get the env table from the object */ lua_getfenv(L, ud); /* Decrement */ luaH_object_decref(L, -1, p); /* Remove env table */ lua_pop(L, 1); } /* Push an object item on the stack. * `ud` is the object index on the stack. * `p` is the item pointer. * Returns the number of element pushed on stack. */ static inline gint luaH_object_push_item(lua_State *L, gint ud, gpointer p) { /* Get env table of the object */ lua_getfenv(L, ud); /* Push key */ lua_pushlightuserdata(L, p); /* Get env.pointer */ lua_rawget(L, -2); /* Remove env table */ lua_remove(L, -2); return 1; } static inline void luaH_object_registry_push(lua_State *L) { lua_pushliteral(L, LUAKIT_OBJECT_REGISTRY_KEY); lua_rawget(L, LUA_REGISTRYINDEX); } /* Reference an object and return a pointer to it. That only works with * userdata, table, thread or function. * Removes the referenced object from the stack. * `oud` is the object index on the stack. * Returns the object reference, or NULL if not referenceable. */ static inline gpointer luaH_object_ref(lua_State *L, gint oud) { luaH_object_registry_push(L); gpointer p = luaH_object_incref(L, -1, oud < 0 ? oud - 1 : oud); lua_pop(L, 1); return p; } /* Reference an object and return a pointer to it checking its type. That only * works with userdata. * `oud` is the object index on the stack. * `class` is the class of object expected * Return the object reference, or NULL if not referenceable. */ static inline gpointer luaH_object_ref_class(lua_State *L, gint oud, lua_class_t *class) { luaH_checkudata(L, oud, class); return luaH_object_ref(L, oud); } /* Unreference an object and return a pointer to it. That only works with * userdata, table, thread or function. * `oud` is the object index on the stack. */ static inline void luaH_object_unref(lua_State *L, gpointer p) { luaH_object_registry_push(L); luaH_object_decref(L, -1, p); lua_pop(L, 1); } /* Push a referenced object onto the stack. * `p` is the object to push. * Returns is the number of element pushed on stack. */ static inline gint luaH_object_push(lua_State *L, gpointer p) { luaH_object_registry_push(L); lua_pushlightuserdata(L, p); lua_rawget(L, -2); lua_remove(L, -2); return 1; } static inline void luaH_gobject_destroy_cb(gpointer ref) { luaH_object_unref(common.L, ref); } static inline void luaH_bind_gobject_ref(lua_State *L, gpointer gobject, int idx) { lua_pushvalue(L, idx); gpointer ref = luaH_object_ref(L, -1); g_object_set_data_full(G_OBJECT(gobject), "dummy-destroy-notify", ref, (GDestroyNotify)luaH_gobject_destroy_cb); } gint signal_array_emit(lua_State *L, signal_t *signals, const gchar *array_name, const gchar *name, gint nargs, gint nret); gint signal_object_emit(lua_State *, signal_t *signals, const gchar *name, gint nargs, gint nret); void luaH_object_add_signal(lua_State *L, gint oud, const gchar *name, gint ud); void luaH_object_remove_signal(lua_State *L, gint oud, const gchar *name , gint ud); gint luaH_object_emit_signal(lua_State *L, gint oud, const gchar *name, gint nargs, gint nret); gint luaH_object_add_signal_simple(lua_State *L); gint luaH_object_remove_signal_simple(lua_State *L); gint luaH_object_remove_signals_simple(lua_State *L); gint luaH_object_emit_signal_simple(lua_State *L); gint luaH_object_property_signal(lua_State *, gint, luakit_token_t); #define LUA_OBJECT_FUNCS(lua_class, type, prefix) \ LUA_CLASS_FUNCS(prefix, lua_class) \ static inline type * \ prefix##_new(lua_State *L) { \ type *p = lua_newuserdata(L, sizeof(type)); \ p_clear(p, 1); \ p->signals = signal_new(); \ luaH_settype(L, &(lua_class)); \ lua_newtable(L); \ lua_newtable(L); \ lua_setmetatable(L, -2); \ lua_setfenv(L, -2); \ lua_pushvalue(L, -1); \ luaH_class_emit_signal(L, &(lua_class), "new", 1, 0); \ return p; \ } #define OBJECT_EXPORT_PROPERTY(pfx, type, field) \ fieldtypeof(type, field) \ pfx##_get_##field(type *object) { \ return object->field; \ } #define LUA_OBJECT_EXPORT_PROPERTY(pfx, type, field, pusher) \ static gint \ luaH_##pfx##_get_##field(lua_State *L, type *object) { \ pusher(L, object->field); \ return 1; \ } gint luaH_object_tostring(lua_State *); gint luaH_object_gc(lua_State *); #define LUA_OBJECT_META(prefix) \ { "__tostring", luaH_object_tostring }, \ { "add_signal", luaH_object_add_signal_simple }, \ { "remove_signal", luaH_object_remove_signal_simple }, \ { "remove_signals", luaH_object_remove_signals_simple }, \ { "emit_signal", luaH_object_emit_signal_simple }, #endif // vim: ft=c:et:sw=4:ts=8:sts=4:tw=80
0
0.866593
1
0.866593
game-dev
MEDIA
0.732927
game-dev
0.658465
1
0.658465
blurite/rsprot
1,236
protocol/osrs-223/osrs-223-model/src/main/kotlin/net/rsprot/protocol/game/incoming/clan/ClanSettingsFullRequest.kt
package net.rsprot.protocol.game.incoming.clan import net.rsprot.protocol.ClientProtCategory import net.rsprot.protocol.game.incoming.GameClientProtCategory import net.rsprot.protocol.message.IncomingGameMessage /** * Clan settings requests are made whenever the server sends a clansettings * delta update, but the update counter in the clan settings message * is greater than that of the clan itself. In order to avoid problems, * the client requests for a full clan settings update from the server, * to re-synchronize all the values. * @property clanId the id of the clan to request, ranging from 0 to 3 (inclusive), * or a negative value if the request is for a guest-clan */ public class ClanSettingsFullRequest( public val clanId: Int, ) : IncomingGameMessage { override val category: ClientProtCategory get() = GameClientProtCategory.USER_EVENT override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ClanSettingsFullRequest return clanId == other.clanId } override fun hashCode(): Int = clanId override fun toString(): String = "ClanSettingsFullRequest(clanId=$clanId)" }
0
0.649364
1
0.649364
game-dev
MEDIA
0.837337
game-dev
0.805761
1
0.805761
BodbDearg/PsyDoom
27,493
game/PsyDoom/MapPatcher/MapPatches_GEC_ME_Beta4.cpp
//------------------------------------------------------------------------------------------------------------------------------------------ // A module containing map patches to apply to the 'GEC Master Edition' (Beta 4) //------------------------------------------------------------------------------------------------------------------------------------------ #include "MapPatches.h" #include "Doom/Game/p_change.h" #include "Doom/Renderer/r_data.h" #include "MapPatcherUtils.h" using namespace MapPatcherUtils; BEGIN_NAMESPACE(MapPatches) //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP04: Hell Keep //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_HellKeep() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix door tracks that shouldn't move for the start door addFlagsToLines(ML_DONTPEGBOTTOM, // First door (in the start area) 19, 22 ); removeFlagsFromLines(ML_DONTPEGBOTTOM, // Door on the way to the courtyard with the big tree 95, 104, // Door beside the exit 136, 144 ); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP11: Sheol //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Sheol() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix parts of the exit room which should not be mapped (like the original version) hideLines(181, 182, 183, 593, 830, 897, 981); // Fix a lift inside the skin building in the outdoor area looking weird when moving removeFlagsFromLines(ML_DONTPEGBOTTOM, 1030); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP13: Paths of Wretchedness //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_PathsOfWretchedness() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix lines which should be mapped in outside lava area past the red, blue and yellow key barrier unhideLines(65, 189, 198, 263, 879, 1371); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP14: Abaddons Void //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_AbaddonsVoid() noexcept { if (shouldApplyMapPatches_GamePlay()) { // Fix a jump from one ledge to the other (near the start area) being almost impossible with 30 Hz physics. // Raise the ledge being jumped from to make it possible. gpSectors[51].floorheight += 16 * FRACUNIT; gpSides[gpLines[401].sidenum[1]].bottomtexture = R_TextureNumForName("WOOD07"); for (mobj_t* pMobj = gpSectors[51].thinglist; pMobj; pMobj = pMobj->snext) { // Make sure the health bonuses in the sector we just raised get moved too... P_ThingHeightClip(*pMobj); } } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP15: Unspeakable Persecution //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_UnspeakablePersecution() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix missing textures for a floor which raises to block off a pathway (near the start area) modifyLines( [](line_t& line) noexcept { gpSides[line.sidenum[0]].bottomtexture = R_TextureNumForName("REDROKX1"); }, 33, 34, 859 ); // Fix a map line which should not show near the start (hell symbol) hideLines(733); } if (shouldApplyMapPatches_GamePlay()) { // Fix a line which the player should be able to cross to use the teleport it bounds modifyLines( [](line_t& line) noexcept { line.special = 97; // WR Teleport line.tag = 41; }, 385 ); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP16: Nightmare Underworld //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_NightmareUnderworld() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a map line in the secret area with the soulsphere (near a lava pit) from being mapped hideLines(165); // Fix a door which looks weird as it opens (should not be upper unpegged). // This door is near the big hellish crack in the wood + skin room. removeFlagsFromLines(ML_DONTPEGTOP, 1494); gpSides[gpLines[1494].sidenum[0]].rowoffset = 8 * FRACUNIT; } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP18: Downtown //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Downtown() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix lines which should be mapped in the building with the rocket launcher unhideLines(268, 320); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP19: Industrial Zone //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_IndustrialZone() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a line which should be mapped in the building with the red key unhideLines(110); // Fix lines which should be mapped outside, near the start area unhideLines(397, 422, 424, 832); } if (shouldApplyMapPatches_GamePlay()) { // Fix the switch past the gate leading up a secret section of the castle wall being usable through the metal bars. // Seal up the bar gate completely (to make it block line activations) and adjust the texture coords to make it look prettier. // This is a bug introduced by PsyDoom's improved 'use line' logic; the switch should have been technically usable through the bars // previously (according to the game rules) but wasn't due to bugs in how the line activation logic worked (a happy coincidence). modifySectors( [](sector_t& sector) noexcept { sector.floorheight = sector.ceilingheight; }, 260 ); modifyLines( [](line_t& line) noexcept { gpSides[line.sidenum[0]].rowoffset = 0; line.flags |= ML_VOID; }, 1113, 737 ); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP20: Betray //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Betray() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a map line on the teleporter beside the exit room which should show unhideLines(559); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP30: Vivisection //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Vivisection() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix monster closet map lines which should be hidden after getting the map powerup hideLines(121, 163, 424, 443, 869, 897, 974); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP31: Inferno of Blood //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_InfernoOfBlood() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix door track textures that shouldn't move for the first door at the start of the map addFlagsToLines(ML_DONTPEGBOTTOM, 1014, 1015); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP33: Tomb Of Malevolence //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_TombOfMalevolence() noexcept { if (shouldApplyMapPatches_GamePlay()) { // Adjust the height of the stairs in the middle of the main area, to allow room for the co-op only cyberdemon to teleport. // This stairs is the one that has a Soulsphere on it. gpSectors[146].floorheight -= 16 * FRACUNIT; gpSectors[149].floorheight -= 32 * FRACUNIT; gpSectors[148].floorheight -= 48 * FRACUNIT; }; } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP45: The Farside Of Titan //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_TheFarsideOfTitan() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a map line which should show near the Soulsphere on a pedestal unhideLines(562); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP46: Dantes Gate //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_DantesGate() noexcept { if (shouldApplyMapPatches_GamePlay()) { // Fix a line which should not be marked as a door line beside the room with the blue key. // Activating this door line messes up the the adjacent sector. removeLineActions(645); } if (shouldApplyMapPatches_Visual()) { // Fix 2 door lines in a monster closet (which is not intended to be mapped) from appearing. // This small room is joined to the large circular room, at the south west corner. hideLines(852, 853); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP48: Bloodflood //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Bloodflood() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a hidden map line in the monster closet in the sewers, beside the green armor unhideLines(400); // Fix a map line for the exit portal not showing addFlagsToLines(ML_SECRET, 527); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP49: Derelict Station //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_DerelictStation() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix some map lines showing inside a hidden monster closet attached to the room with the blue key hideLines(38, 649, 717, 718); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP54: The Image of Evil //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_TheImageOfEvil() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a missing door side texture near the exit portal gpSides[gpLines[925].sidenum[0]].midtexture = R_TextureNumForName("BROWN12"); // Fix a missing map line in the intenstine maze (attached to an unmapped room) addFlagsToLines(ML_SECRET, 920); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP55: Black Tower //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_BlackTower() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a missing step texture in the room with the yellow key gpSides[gpLines[951].sidenum[1]].bottomtexture = R_TextureNumForName("MARBLE04"); // Fix a map line which should not be hidden (in the small room attached to the Megasphere) unhideLines(760); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP57: The Express Elevator to Hell //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_TheExpressElevatorToHell() noexcept { if (shouldApplyMapPatches_Visual()) { // Hide a monster closet automap line that should be hidden (in the south room with 'plus' shaped pillbox in the middle) hideLines(495); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP59: Hanger //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Hanger() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix map lines in the room with the Soulsphere and large pillars not showing unhideLines(215, 1101, 1504, 1507, 1508, 1510, 1532, 1536); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP65: Storage Facility //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_StorageFacility() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix map lines in a hidden monster closet room sometimes showing (the room is intended to be hidden) hideLines(539, 479); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP67: Dead Zone //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_DeadZone() noexcept { if (shouldApplyMapPatches_GamePlay()) { // Fix a sector containing deaf monsters (outside the outer wall) never raising, making 100% kills impossible. // Fix by making it raise with another similar sector containing monsters outside the wall. gpSectors[32].tag = 36; } if (shouldApplyMapPatches_Visual()) { // Fix a line inside the secret exit room which should not show hideLines(649); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP69: Shipping Respawning //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_ShippingRespawning() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a map line in the area with the crates not showing unhideLines(1625); // Fix a map line inside a monster closet which should not show, near the teleporter pads by the crates hideLines(500); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP70: Central Processing //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_CentralProcessing() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a map line in a slime pit to the west of the map not showing unhideLines(1034); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP71: Administration Center //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_AdministrationCenter() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a map line showing at the east of the building which is part of a hidden room hideLines(1213); // Fix a map line not showing in the room with the teleport leading towards the outside unhideLines(834); // Fix a map line not showing in the outdoor area (inside the big building) unhideLines(600); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP74: Mount Pain //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_MountPain() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a map line which should show in the terraced room past the brimstone maze unhideLines(349); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP76: Well Of Souls //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_WellOfSouls() noexcept { if (shouldApplyMapPatches_GamePlay()) { // Fix not being able to reach the exit again if backtracking after raising the final lift to the exit. // This line special would lower the lift permanently, preventing the player from reaching the exit. // It's not needed for anything so just remove the special: removeLineActions(590); } if (shouldApplyMapPatches_Visual()) { // Fix a map line not showing by the yellow key pedestal unhideLines(196); // Fix map lines not showing for the cliff face by the bridge unhideLines(403, 405); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP82: Speed //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Speed() noexcept { if (shouldApplyMapPatches_GamePlay()) { // Fix the player being able to see past the end of the sky in various places: raise outer walls bordering the sky modifySectors( [](sector_t& sector) noexcept { sector.floorheight += 16 * FRACUNIT; sector.ceilingheight += 16 * FRACUNIT; }, 130 ); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP88: Neurosphere //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Neurosphere() noexcept { if (shouldApplyMapPatches_GamePlay()) { // Fix being able to get stuck in the blood in the southernmost room. // The player can bypass a line which raises elevators/platforms (containing chaingunners) which allow escape from the blood area. // This bypass can be achieved by hopping up onto a half wall and bypassing the trigger line near the Super Shotgun. modifyLines( [](line_t& line) noexcept { // Fix by adding an additional 'W1 Floor Raise To Next Higher Floor' trigger which cannot be bypassed! line.special = 119; line.tag = 7; }, 599 ); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP90: Slayer //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Slayer() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix map lines showing in a part of a monster closet which should be hidden (to the west of the map) hideLines(219, 220); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP99: Warrens //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Warrens() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix a missing map line near the Soulsphere by the red key unhideLines(456); } } //------------------------------------------------------------------------------------------------------------------------------------------ // Fix issues for MAP109: Go 2 It //------------------------------------------------------------------------------------------------------------------------------------------ static void patchMap_Go2It() noexcept { if (shouldApplyMapPatches_Visual()) { // Fix missing map lines in the room with the grass and pillars unhideLines(248, 249, 250, 251); } } //------------------------------------------------------------------------------------------------------------------------------------------ // All of the map patches for this game type //------------------------------------------------------------------------------------------------------------------------------------------ static const PatchDef gPatchArray_GEC_ME_Beta4[] = { { 20001, 0x51BD8C31DAE5DC9C, 0x0160232923A6BA2D, patchMap_HellKeep }, // MAP04 { 160332, 0x013F3B27435F706B, 0xA99F122A12E2E3EE, patchMap_Sheol }, // MAP11 { 173712, 0x93D4D689C51DEF47, 0x9F26A30E8101CF37, patchMap_PathsOfWretchedness }, // MAP13 { 105207, 0xA2B8A7F0CFA83D6B, 0xF88EAB0FDCE3667A, patchMap_AbaddonsVoid }, // MAP14 { 132114, 0x4DDD1E65175AF8F7, 0x01668444BCDDBBC1, patchMap_UnspeakablePersecution }, // MAP15 { 171138, 0xC908305550FCEAF7, 0x640FD1210269AB9D, patchMap_NightmareUnderworld }, // MAP16 { 103102, 0x9C898E35FBD2E7F7, 0x5069635F626857D8, patchMap_Downtown }, // MAP18 { 162499, 0x05C85D345D4523AE, 0x77C081B1536F0B82, patchMap_IndustrialZone }, // MAP19 { 87382, 0x85CC150D7341AD22, 0x01555EF45756FF8E, patchMap_Betray }, // MAP20 { 122661, 0xD43A809445B5907E, 0x4AD280F7598BE3D5, patchMap_Vivisection }, // MAP30 { 140784, 0xDB5A27E8FEE6CB5B, 0x85D2D986F5E07304, patchMap_InfernoOfBlood }, // MAP31 { 73904, 0xD1D176845E2CA3D1, 0xBEE5A14C51434B80, patchMap_TombOfMalevolence }, // MAP33 { 151044, 0xE49FB277051FDB5B, 0xD95431833051308A, patchMap_TheFarsideOfTitan }, // MAP45 { 122098, 0xDF2507C85472FB25, 0xEFAED249AFE4CCD2, patchMap_DantesGate }, // MAP46 { 59287, 0x29A485887DAE27C3, 0x534228B651D4DFDE, patchMap_Bloodflood }, // MAP48 { 68720, 0xAC099662761778F7, 0xD2F689E6EC430246, patchMap_DerelictStation }, // MAP49 { 120364, 0xA17F95563CCAE891, 0xC7BC7B007C0E9C2E, patchMap_TheImageOfEvil }, // MAP54 { 143954, 0x457AA5F01F5592E0, 0xAD3A9AC1BF42EF93, patchMap_BlackTower }, // MAP55 { 123320, 0xA97F2699096BE16E, 0x81447F745D75DD8B, patchMap_TheExpressElevatorToHell }, // MAP57 { 140344, 0xF926DB363CE3A90A, 0x2944E39AE9A969A1, patchMap_Hanger }, // MAP59 { 157892, 0x007C1D52778AB863, 0x3AD9589FE0B4F2C9, patchMap_StorageFacility }, // MAP65 { 123951, 0x441FA8942AE1EF39, 0xCB7E8B72E7B50B06, patchMap_DeadZone }, // MAP67 { 179291, 0x2F8C304B18C2E917, 0xCC356F976B15958B, patchMap_ShippingRespawning }, // MAP69 { 149154, 0x8973A4B380C2AC19, 0x9CCE3CB032CF6186, patchMap_CentralProcessing }, // MAP70 { 174087, 0xE298170F408CF590, 0xE04DC9FFE6162B53, patchMap_AdministrationCenter }, // MAP71 { 186331, 0x23518DCF7456882D, 0xC47FB9150E9413A6, patchMap_MountPain }, // MAP74 { 91382, 0x9E5DDD89794B172C, 0x3A73D5AEBF5566A5, patchMap_WellOfSouls }, // MAP76 { 115075, 0x229AB3F282BAF6B0, 0x008C9CF373E2ECD4, patchMap_Speed }, // MAP82 { 142221, 0x93EB99DA2D4BF37E, 0xE2A66BA48B17B268, patchMap_Neurosphere }, // MAP88 { 46378, 0x90476B1E1C3EF4CA, 0x3AB1827AEEE4D881, patchMap_Slayer }, // MAP90 { 46366, 0x39399FE7670D2BDC, 0x988E14C60AA40392, patchMap_Warrens }, // MAP99 { 95297, 0x7933332EEC490012, 0x31A3577166916A83, patchMap_Go2It }, // MAP109 }; const PatchList gPatches_GEC_ME_Beta4 = { gPatchArray_GEC_ME_Beta4, C_ARRAY_SIZE(gPatchArray_GEC_ME_Beta4) }; END_NAMESPACE(MapPatches)
0
0.682726
1
0.682726
game-dev
MEDIA
0.798203
game-dev
0.633322
1
0.633322
Crazy-Crew/CrazyEnchantments
1,615
paper/src/main/java/com/badbones69/crazyenchantments/paper/commands/features/admin/CommandBottle.java
package com.badbones69.crazyenchantments.paper.commands.features.admin; import com.badbones69.crazyenchantments.paper.api.builders.types.tinkerer.TinkererManager; import com.badbones69.crazyenchantments.paper.api.enums.v2.FileKeys; import com.badbones69.crazyenchantments.paper.api.enums.v2.Messages; import com.badbones69.crazyenchantments.paper.commands.features.BaseCommand; import dev.triumphteam.cmd.bukkit.annotation.Permission; import dev.triumphteam.cmd.core.annotations.Command; import dev.triumphteam.cmd.core.annotations.Optional; import dev.triumphteam.cmd.core.annotations.Syntax; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.permissions.PermissionDefault; public class CommandBottle extends BaseCommand { @Command("bottle") @Permission(value = "crazyenchantments.bottle", def = PermissionDefault.OP) @Syntax("/crazyenchantments bottle <player> <xp> <amount>") public void bottle(final CommandSender sender, final int xp, final int amount, @Optional final Player target) { Player safePlayer = target == null ? sender instanceof Player player ? player : null : target; if (safePlayer == null) { Messages.NOT_ONLINE.sendMessage(sender); return; } final ItemStack itemStack = TinkererManager.getXPBottle(xp, FileKeys.tinker.getYamlConfiguration()); if (itemStack == null) { return; } itemStack.setAmount(amount <= 0 ? 1 : amount); this.methods.addItemToInventory(safePlayer, itemStack); } }
0
0.791023
1
0.791023
game-dev
MEDIA
0.982675
game-dev
0.940588
1
0.940588
HanSan2024/psd2unity
2,966
Packages/com.unity.2d.psdimporter@9.0.3/Editor/SpriteData.cs
using System; using System.Collections.Generic; using System.Linq; using UnityEditor.U2D.Sprites; using UnityEngine; using UnityEngine.U2D; namespace UnityEditor.U2D.PSD { [Serializable] internal class SpriteMetaData : SpriteRect { public List<SpriteBone> spriteBone; public List<SpriteOutline> spriteOutline; public List<Vertex2DMetaData> vertices; public List<SpriteOutline> spritePhysicsOutline; public int[] indices; public Vector2Int[] edges; public float tessellationDetail; public Vector2Int uvTransform = Vector2Int.zero; public Vector2 spritePosition; public SpriteMetaData() {} public SpriteMetaData(SpriteRect sr) { alignment = sr.alignment; border = sr.border; name = sr.name; pivot = GetPivotValue(sr.alignment, sr.pivot); rect = sr.rect; spriteID = sr.spriteID; } public static Vector2 GetPivotValue(SpriteAlignment alignment, Vector2 customOffset) { switch (alignment) { case SpriteAlignment.BottomLeft: return new Vector2(0f, 0f); case SpriteAlignment.BottomCenter: return new Vector2(0.5f, 0f); case SpriteAlignment.BottomRight: return new Vector2(1f, 0f); case SpriteAlignment.LeftCenter: return new Vector2(0f, 0.5f); case SpriteAlignment.Center: return new Vector2(0.5f, 0.5f); case SpriteAlignment.RightCenter: return new Vector2(1f, 0.5f); case SpriteAlignment.TopLeft: return new Vector2(0f, 1f); case SpriteAlignment.TopCenter: return new Vector2(0.5f, 1f); case SpriteAlignment.TopRight: return new Vector2(1f, 1f); case SpriteAlignment.Custom: return customOffset; } return Vector2.zero; } public static implicit operator UnityEditor.AssetImporters.SpriteImportData(SpriteMetaData value) { var output = new UnityEditor.AssetImporters.SpriteImportData(); output.name = value.name; output.alignment = value.alignment; output.rect = value.rect; output.border = value.border; output.pivot = value.pivot; output.tessellationDetail = value.tessellationDetail; output.spriteID = value.spriteID.ToString(); if (value.spriteOutline != null) output.outline = value.spriteOutline.Select(x => x.outline).ToList(); return output; } } [Serializable] internal class SpriteOutline { [SerializeField] public Vector2[] outline; } }
0
0.786085
1
0.786085
game-dev
MEDIA
0.670928
game-dev,graphics-rendering
0.955515
1
0.955515
Kamal-Sadek/Liberal-Crime-Squad
5,074
src/common/translateid.cpp
/* Copyright (c) 2002,2003,2004 by Tarn Adams // // This file is part of Liberal Crime Squad. // // Liberal Crime Squad 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. // // Liberal Crime Squad 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 Liberal Crime Squad; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ /* This file was created by Chris Johnson (grundee@users.sourceforge.net) by copying code from game.cpp. To see descriptions of files and functions, see the list at the bottom of includes.h in the top src folder. */ #include <externs.h> /* transforms a squad id number into the index of that squad in the global vector */ int getsquad(int id) { for(int i=0;i<len(squad);i++) if(squad[i]->id==id) return i; return -1; } /* transforms a car id number into the index of that car in the global vector */ int id_getcar(int id) { for(int i=0;i<len(vehicle);i++) if(vehicle[i]->id()==id) return i; return -1; } /* transforms a creature id number into the index of that person in the pool */ int getpoolcreature(int id) { for(int i=0;i<len(pool);i++) if(pool[i]->id==id) return i; return -1; } /* transforms a vehicle type id into the index of that vehicle type in the global vector */ int getvehicletype(int id) { for(int i=0;i<len(vehicletype);i++) if(vehicletype[i]->id()==id) return i; return -1; } /* transforms a vehicle type idname into the index of that vehicle type in the global vector */ int getvehicletype(const string &idname) { for(int i=0;i<len(vehicletype);i++) if(vehicletype[i]->idname()==idname) return i; return -1; } /* transforms a clip type id into the index of that clip type in the global vector */ int getcliptype(int id) { for(int i=0;i<len(cliptype);i++) if(cliptype[i]->get_id()==id) return i; return -1; } /* transforms a clip type name into the index of that clip type in the global vector */ int getcliptype(const string &idname) { for(int i=0;i<len(cliptype);i++) if(cliptype[i]->get_idname()==idname) return i; return -1; } /* transforms a weapon type id into the index of that weapon type in the global vector */ int getweapontype(int id) { for(int i=0;i<len(weapontype);i++) if(weapontype[i]->get_id()==id) return i; return -1; } /* transforms a weapon type name into the index of that weapon type in the global vector */ int getweapontype(const string &idname) { for(int i=0;i<len(weapontype);i++) if(weapontype[i]->get_idname()==idname) return i; return -1; } /* transforms a armor type id into the index of that armor type in the global vector */ int getarmortype(int id) { for(int i=0;i<len(armortype);i++) if(armortype[i]->get_id()==id) return i; return -1; } /* transforms a armor type name into the index of that armor type in the global vector */ int getarmortype(const string &idname) { for(int i=0;i<len(armortype);i++) if(armortype[i]->get_idname()==idname) return i; return -1; } /* transforms a loot type id into the index of that loot type in the global vector */ int getloottype(int id) { for(int i=0;i<len(loottype);i++) if(loottype[i]->get_id()==id) return i; return -1; } /* transforms a loot type name into the index of that loot type in the global vector */ int getloottype(const string &idname) { for(int i=0;i<len(loottype);i++) if(loottype[i]->get_idname()==idname) return i; return -1; } /* transforms a CreatureTypes value into a pointer to that creature type */ const CreatureType* getcreaturetype(short crtype) { for(int i=0;i<len(creaturetype);i++) if(crtype==creaturetype[i]->get_type()) return creaturetype[i]; return NULL; } /* transforms a creature type name into a pointer to that creature type */ const CreatureType* getcreaturetype(const std::string& crtype) { for(int i=0;i<len(creaturetype);i++) if(crtype==creaturetype[i]->get_idname()) return creaturetype[i]; return NULL; }
0
0.570627
1
0.570627
game-dev
MEDIA
0.363761
game-dev
0.880614
1
0.880614
ericraio/vanilla-wow-addons
43,941
p/PowerAuras/PowerAuras.lua
-- ------------------------------------------- -- << Power Auras >> -- Par -Sinsthar- -- [Ziya/Tiven - serveur Fr - Kirin Tor] -- -- Effets visuels autour du personnage -- en cas de buff ou de debuff. -- ------------------------------------------- PowaVersion = "v2.01" CurrentAura = 1; CurrentSecondeAura = 0; MaxAuras = 20; SecondeAura = MaxAuras + 1; CurrentTestAura = MaxAuras + 2; PowaEnabled = 0; PowaModTest = false; -- on test les effets Powa_FramesVisibleTime = {}; -- visible ou pas PowaMisc = { quickhide = false, disabled = false, BTimerX = 0, BTimerY = 0, BTimerA = 1.00, BTimerScale = 1.00, BCents = true, DTimerX = 0, DTimerY = 0, DTimerA = 1.00, DTimerScale = 1.00, DCents = true }; PowaGlobal = {maxeffects = 20, maxtextures = 15} PowaSet = {}; for i = 1, SecondeAura do PowaSet[i] = { texture = 1, anim1 = 1, anim2 = 0, speed = 1.00, begin = 0, duration = 0, alpha = 0.75, size = 0.75, torsion = 1, symetrie = 0, x = 0, y = -30, buffname = "", isdebuff = false, isdebufftype = false, timer = false, inverse = false, r = 1.0, g = 1.0, b = 1.0 }; end TabBuff = {}; -- liste des buffs en cours TabDebuff = {}; -- debuffs TabDebuffType = {}; -- debuff types -- --------------------------------------------------------------------------------------------- function Powa_OnLoad() -- Registering Events -- this:RegisterEvent("PLAYER_AURAS_CHANGED"); this:RegisterEvent("PLAYER_ENTERING_WORLD"); this:RegisterEvent("VARIABLES_LOADED"); Powa_Frames = {}; Powa_textures = {}; -- options init SlashCmdList["POWA"] = Powa_SlashHandler; SLASH_POWA1 = "/powa"; end -- ---------------------------------------------------------------------------------------------- function Powa_InitTabs() for i = 1, CurrentTestAura do if (PowaSet[i]) then -- gere les rajout de variables suivant les versions if (PowaSet[i].timer == nil) then PowaSet[i].timer = false; end if (PowaSet[i].inverse == nil) then PowaSet[i].inverse = false; end if (PowaSet[i].speed == nil) then PowaSet[i].speed = 1.0; end if (PowaSet[i].begin == nil) then PowaSet[i].begin = 0; end if (PowaSet[i].duration == nil) then PowaSet[i].duration = 0; end else -- pas init PowaSet[i] = { texture = 1, anim1 = 1, anim2 = 0, speed = 1.00, begin = 0, duration = 0, alpha = 0.75, size = 0.75, torsion = 1, symetrie = 0, x = 0, y = -30, buffname = "", isdebuff = false, isdebufftype = false, timer = false, inverse = false, r = 1.0, g = 1.0, b = 1.0 } Powa_FramesVisibleTime[i] = 0; end end if (PowaMisc) then if (PowaMisc.BTimerX == nil) then PowaMisc.BTimerX = 0; end if (PowaMisc.BTimerY == nil) then PowaMisc.BTimerY = 0; end if (PowaMisc.BTimerA == nil) then PowaMisc.BTimerA = 1.00; end if (PowaMisc.BTimerScale == nil) then PowaMisc.BTimerScale = 1.00; end if (PowaMisc.DTimerX == nil) then PowaMisc.DTimerX = 0; end if (PowaMisc.DTimerY == nil) then PowaMisc.DTimerY = 0; end if (PowaMisc.DTimerA == nil) then PowaMisc.DTimerA = 1.00; end if (PowaMisc.DTimerScale == nil) then PowaMisc.DTimerScale = 1.00; end if (PowaMisc.BCents == nil) then PowaMisc.BCents = true; end if (PowaMisc.DCents == nil) then PowaMisc.DCents = true; end else PowaMisc.quickhide = false; PowaMisc.disabled = false; PowaMisc.BTimerX = 0; PowaMisc.BTimerY = 0; PowaMisc.BTimerA = 1.00; PowaMisc.BTimerScale = 1.00; PowaMisc.DTimerX = 0; PowaMisc.DTimerY = 0; PowaMisc.DTimerA = 1.00; PowaMisc.DTimerScale = 1.00; PowaMisc.BCents = true; PowaMisc.DCents = true; end end -- ----------------------------------------------------------------------------------------------- function Powa_CreateFrames() for i = 1, CurrentTestAura do if (Powa_Frames[i]) then -- deja cree, ne fait rien else -- Frame -- Powa_Frames[i] = CreateFrame("Frame","Frame"..i); Powa_Frames[i]:Hide(); -- Texture -- Powa_textures[i] = Powa_Frames[i]:CreateTexture(nil,"BACKGROUND"); Powa_textures[i]:SetBlendMode("ADD"); Powa_textures[i]:SetAllPoints(Powa_Frames[i]); -- attache la texture a la frame Powa_Frames[i].texture = Powa_textures[i]; Powa_Frames[i].baseL = 256; Powa_Frames[i].baseH = 256; Powa_FramesVisibleTime[i] = 0; end end end Powa_Timer = {}; Powa_timertex = {}; Tstep = 0.09765625; function Powa_CreateTimer() for i = 1, 4 do if (Powa_Timer[i]) then else Powa_Timer[i] = CreateFrame("Frame","Timer"..i); Powa_Timer[i]:Hide(); Powa_timertex[i] = Powa_Timer[i]:CreateTexture(nil,"BACKGROUND"); Powa_timertex[i]:SetBlendMode("ADD"); Powa_timertex[i]:SetAllPoints(Powa_Timer[i]); -- attache la texture a la frame Powa_Timer[i].texture = Powa_timertex[i]; Powa_timertex[i]:SetTexture("Interface\\Addons\\PowerAuras\\timers.tga"); end end Powa_UpdateOptionsTimer(); Powa_UpdateOptionsTimer2(); end -- ------------------------------------------------------------------------------------ BUFF CHECKS function Powa_MemorizeBuffs() -- cree un string contenant tous les noms des buffs en cours local buffIndex, untilCancelled; for i = 1, 24 do TabBuff[i] = "xXx"; buffIndex, untilCancelled = GetPlayerBuff(i-1, "HELPFUL"); if (buffIndex >= 0) then Powa_Tooltip:SetPlayerBuff(buffIndex); if (Powa_TooltipTextLeft1:IsShown()) then TabBuff[i] = string.upper(Powa_TooltipTextLeft1:GetText()); else Powa_Tooltip:SetOwner(UIParent, "ANCHOR_NONE"); -- ERROR !! Ca ne doit jamais arriver ca end end end for i = 1, 16 do TabDebuff[i] = "xXx"; TabDebuffType[i] = "xXx"; buffIndex, untilCancelled = GetPlayerBuff(i-1, "HARMFUL"); if (buffIndex >= 0) then Powa_Tooltip:SetPlayerBuff(buffIndex); if (Powa_TooltipTextLeft1:IsShown()) then TabDebuff[i] = string.upper(Powa_TooltipTextLeft1:GetText()); if (Powa_TooltipTextRight1:IsShown()) then TabDebuffType[i] = string.upper(Powa_TooltipTextRight1:GetText()); else TabDebuffType[i] = string.upper(PowaText.aucun); end else Powa_Tooltip:SetOwner(UIParent, "ANCHOR_NONE"); -- ERROR !! Ca ne doit jamais arriver ca end end end end function PowaCompareBuffDebuff(xnum) if (PowaMisc.disabled == true) then return false; end if (PowaSet[xnum].isdebuff) then -- un debuff for i = 1, 16 do Powa_Frames[xnum].buffindex = 0; for pword in string.gfind(PowaSet[xnum].buffname, "[%w%s%-%'\195\130-\195\190]+") do if (string.find(TabDebuff[i], string.upper(pword), 1, true)) then Powa_Frames[xnum].buffindex = i-1; -- point vers le debuff qui a le timer return true; end end end elseif (PowaSet[xnum].isdebufftype) then -- type de debuff (cherche a l'inverse) for i = 1, 16 do if (string.find(string.upper(PowaSet[xnum].buffname), TabDebuffType[i], 1, true)) then Powa_Frames[xnum].buffindex = i-1; -- point vers le debuff type qui a le timer return true; end end else -- un buff for i = 1, 24 do Powa_Frames[xnum].buffindex = 0; for pword in string.gfind(PowaSet[xnum].buffname, "[%w%s%-%'\195\130-\195\190]+") do if (string.find(TabBuff[i], string.upper(pword), 1, true)) then Powa_Frames[xnum].buffindex = i-1; -- point vers le buff qui a le timer return true; end end end end return false; end function Powa_NewCheckBuffs() -- compare chaque nom de buff d'activation avec l'ensemble des buffs memorises local LastAura; Powa_MemorizeBuffs(); LastAura = 0; for j = 1, MaxAuras do if (PowaSet[j].buffname == "" or PowaSet[j].buffname == " ") then -- ne fait rien si vide PowaSet[j].buffname = ""; elseif (PowaCompareBuffDebuff(j)) then -- buff actif if (PowaSet[j].inverse == true) then if (Powa_Frames[j]:IsVisible() ) then Powa_FramesVisibleTime[j] = 0; if (j == CurrentSecondeAura) then Powa_FramesVisibleTime[SecondeAura] = 0; if (LastAura > 0) then -- cet effet n'est plus actif mais on affiche l'aura 2 sur le dernier effet CurrentSecondeAura = LastAura; Powa_DisplayAura(LastAura); end end end else Powa_DisplayAura(j); LastAura = j; end else -- -- perte d'aura, s'il est visible on le cache if (PowaSet[j].inverse == false) then if (Powa_Frames[j]:IsVisible() ) then Powa_FramesVisibleTime[j] = 0; if (j == CurrentSecondeAura) then Powa_FramesVisibleTime[SecondeAura] = 0; if (LastAura > 0) then -- cet effet n'est plus actif mais on affiche l'aura 2 sur le dernier effet CurrentSecondeAura = LastAura; Powa_DisplayAura(LastAura); end end end else Powa_DisplayAura(j); LastAura = j; end end end -- end for end -- ----------------------------------------------------------------------------------------- EVENT function Powa_OnEvent() if event == "PLAYER_ENTERING_WORLD" then Powa_Tooltip:SetOwner(UIParent, "ANCHOR_NONE"); elseif event == "VARIABLES_LOADED" then DEFAULT_CHAT_FRAME:AddMessage("|cffB0A0ff<Power Auras>|r |cffffff00"..PowaVersion.."|r - "..PowaText.welcome); -- defini le nombre max d'effets MaxAuras = PowaGlobal.maxeffects; SecondeAura = MaxAuras + 1; CurrentTestAura = MaxAuras + 2; -- verifie en cas de rajout d'effets que tous sont initialises (sinon ca bug :P) Powa_InitTabs(); Powa_CreateFrames(); -- defini le nombre max de textures if (PowaGlobal.maxtextures > 50) then PowaGlobal.maxtextures = 50; elseif (PowaGlobal.maxtextures < 20) then PowaGlobal.maxtextures = 20; end getglobal("PowaBarAuraTextureSlider"):SetMinMaxValues(1,PowaGlobal.maxtextures); getglobal("PowaBarAuraTextureSliderHigh"):SetText(PowaGlobal.maxtextures); PowaEnabled = 1; Powa_CreateTimer(); elseif event == "PLAYER_AURAS_CHANGED" then -- passe les buffs en revue if (PowaModTest == false) then Powa_NewCheckBuffs(); end end end -- ----------------------------------------------------------------------------------------------- function Powa_DisplayAura(FNum) if (PowaEnabled == 0) then return; end -- desactived if (Powa_FramesVisibleTime[FNum] == 0) then -- si pas en cours Powa_textures[FNum]:SetTexture("Interface\\Addons\\PowerAuras\\aura"..PowaSet[FNum].texture..".tga"); Powa_textures[FNum]:SetVertexColor(PowaSet[FNum].r,PowaSet[FNum].g,PowaSet[FNum].b); if (PowaSet[FNum].symetrie == 1) then Powa_textures[FNum]:SetTexCoord(1, 0, 0, 1); -- inverse X elseif (PowaSet[FNum].symetrie == 2) then Powa_textures[FNum]:SetTexCoord(0, 1, 1, 0); -- inverse Y elseif (PowaSet[FNum].symetrie == 3) then Powa_textures[FNum]:SetTexCoord(1, 0, 1, 0); -- inverse XY else Powa_textures[FNum]:SetTexCoord(0, 1, 0, 1); end if (PowaSet[FNum].begin > 0) then Powa_Frames[FNum].beginAnim = 1; else Powa_Frames[FNum].beginAnim = 0; end Powa_Frames[FNum].baseL = 256 * PowaSet[FNum].size * PowaSet[FNum].torsion; Powa_Frames[FNum].baseH = 256 * PowaSet[FNum].size * (2-PowaSet[FNum].torsion); Powa_Frames[FNum]:SetAlpha(PowaSet[FNum].alpha); Powa_Frames[FNum]:SetPoint("Center",PowaSet[FNum].x, PowaSet[FNum].y); Powa_Frames[FNum]:SetWidth(Powa_Frames[FNum].baseL); Powa_Frames[FNum]:SetHeight(Powa_Frames[FNum].baseH); Powa_Frames[FNum].statut = 0; Powa_Frames[FNum].duree = 0; Powa_Frames[FNum]:Show(); Powa_FramesVisibleTime[FNum] = 1; -- affiche anim1 Powa_FramesVisibleTime[SecondeAura] = 0; -- init anim2 end if (Powa_FramesVisibleTime[SecondeAura] == 0) then -- si pas en cours (Anim 2) CurrentSecondeAura = FNum; -- 2eme aura en cours if (PowaSet[FNum].anim2 == 0) then -- pas d'anim Powa_Frames[SecondeAura]:Hide(); return; end if (PowaSet[FNum].begin > 0) then Powa_Frames[FNum].beginAnim = 2; else Powa_Frames[FNum].beginAnim = 0; end PowaSet[SecondeAura].size = PowaSet[FNum].size; PowaSet[SecondeAura].torsion = PowaSet[FNum].torsion; PowaSet[SecondeAura].alpha = PowaSet[FNum].alpha * 0.5; PowaSet[SecondeAura].anim1 = PowaSet[FNum].anim2; PowaSet[SecondeAura].speed = PowaSet[FNum].speed; PowaSet[SecondeAura].duration = PowaSet[FNum].duration; PowaSet[SecondeAura].x = PowaSet[FNum].x; PowaSet[SecondeAura].y = PowaSet[FNum].y; Powa_textures[SecondeAura]:SetTexture("Interface\\Addons\\PowerAuras\\aura"..PowaSet[FNum].texture..".tga"); Powa_textures[SecondeAura]:SetVertexColor(PowaSet[FNum].r,PowaSet[FNum].g,PowaSet[FNum].b); if (PowaSet[FNum].symetrie == 1) then Powa_textures[SecondeAura]:SetTexCoord(1, 0, 0, 1); -- inverse X elseif (PowaSet[FNum].symetrie == 2) then Powa_textures[SecondeAura]:SetTexCoord(0, 1, 1, 0); -- inverse Y elseif (PowaSet[FNum].symetrie == 3) then Powa_textures[SecondeAura]:SetTexCoord(1, 0, 1, 0); -- inverse XY else Powa_textures[SecondeAura]:SetTexCoord(0, 1, 0, 1); end Powa_Frames[SecondeAura].baseL = Powa_Frames[FNum].baseL; Powa_Frames[SecondeAura].baseH = Powa_Frames[FNum].baseH; Powa_Frames[SecondeAura]:SetAlpha(PowaSet[SecondeAura].alpha); Powa_Frames[SecondeAura]:SetPoint("Center",PowaSet[FNum].x, PowaSet[FNum].y); Powa_Frames[SecondeAura]:SetWidth(Powa_Frames[SecondeAura].baseL); Powa_Frames[SecondeAura]:SetHeight(Powa_Frames[SecondeAura].baseH); Powa_Frames[SecondeAura].statut = 1; Powa_Frames[SecondeAura].duree = Powa_Frames[FNum].duree; Powa_Frames[SecondeAura]:Show(); Powa_FramesVisibleTime[SecondeAura] = 1; end end -- -------------------------------------------------------------------------------------- TIMERS PowaActiveTimer = 0; -- le timer en cours PowaActiveTimerValue = 0; PowaActiveTimerSup = 0; -- le 2eme timer en cours PowaActiveTimerSupValue = 0; PowaActiveTimer2 = 0; -- le timer en cours (debuffs) PowaActiveTimer2Value = 0; PowaActiveTimer2Sup = 0; -- le 2eme timer en cours PowaActiveTimer2SupValue = 0; function Powa_UpdateTimer(numi) local newvalue; if (numi > MaxAuras) then -- fin du cycle on arrete return; elseif (PowaSet[numi].timer == false) then -- cet effet n'affiche pas de timer return; end -- prend le timer if (getglobal("PowaBarConfigFrameOptions"):IsVisible()) then -- options des timers, affiche PowaActiveTimer2 = numi; PowaActiveTimer2Value = random(1,9) + (random(1, 99) / 100); PowaActiveTimer = numi; PowaActiveTimerValue = random(1,9) + (random(1, 99) / 100); elseif (PowaSet[numi].isdebuff or PowaSet[numi].isdebufftype) then if (PowaModTest) then newvalue = random(1,9) + (random(1, 99) / 100); else newvalue = GetPlayerBuffTimeLeft( GetPlayerBuff(Powa_Frames[numi].buffindex, "HARMFUL") ); end if (newvalue > 0) then -- ok on a un timer a afficher... if ((PowaActiveTimer2Value > 0) and (newvalue > PowaActiveTimer2Value)) then -- y'a deja un timer dont le nombre est plus petit, domage return; end PowaActiveTimer2 = numi; -- lien vers l'effet PowaActiveTimer2Value = newvalue; -- retiens la valeur end else if (PowaModTest) then newvalue = random(1,9) + (random(1, 99) / 100); else newvalue = GetPlayerBuffTimeLeft( GetPlayerBuff(Powa_Frames[numi].buffindex, "HELPFUL") ); end if (newvalue > 0) then -- ok on a un timer a afficher... if ((PowaActiveTimerValue > 0) and (newvalue > PowaActiveTimerValue)) then -- y'a deja un timer dont le nombre est plus petit, domage return; end PowaActiveTimer = numi; -- lien vers l'effet PowaActiveTimerValue = newvalue; -- retiens la valeur end end end function Powa_ResetTimers() local deci, uni, newvalue; if (PowaActiveTimer > 0) then -- timer a un lien if (Powa_Frames[PowaActiveTimer]:IsVisible()) then -- l'effet est visible, affiche -- timer 1, le gros (secondes) Powa_timertex[1]:SetVertexColor(PowaSet[PowaActiveTimer].r,PowaSet[PowaActiveTimer].g,PowaSet[PowaActiveTimer].b); -- si le timer est > 60, le transforme en minutes newvalue = PowaActiveTimerValue; if (newvalue > 60.00) then newvalue = newvalue / 60; end newvalue = math.min (99.00, newvalue); deci = math.floor(newvalue / 10); uni = math.floor(newvalue - (deci*10)); Powa_timertex[1]:SetTexCoord(Tstep * uni, Tstep * (uni+1), Tstep * deci, Tstep * (deci+1)); Powa_Timer[1]:Show(); -- timer 2, le petit (centieme de secondes) Powa_timertex[2]:SetVertexColor(PowaSet[PowaActiveTimer].r,PowaSet[PowaActiveTimer].g,PowaSet[PowaActiveTimer].b); newvalue = PowaActiveTimerValue; if (newvalue > 60.00) then newvalue = math.mod(newvalue,60); else newvalue = (newvalue - math.floor(newvalue)) * 100; end deci = math.floor(newvalue / 10); uni = math.floor(newvalue - (deci*10)); Powa_timertex[2]:SetTexCoord(Tstep * uni, Tstep * (uni+1), Tstep * deci, Tstep * (deci+1)); if (PowaMisc.BCents == true) then Powa_Timer[2]:Show(); else Powa_Timer[2]:Hide(); end else Powa_Timer[1]:Hide(); -- cache les timer Powa_Timer[2]:Hide(); -- cache les timer end else Powa_Timer[1]:Hide(); Powa_Timer[2]:Hide(); -- cache les timer end PowaActiveTimer = 0; PowaActiveTimerValue = 0; -- idem pour les debuffs if (PowaActiveTimer2 > 0) then -- timer a un lien if (Powa_Frames[PowaActiveTimer2]:IsVisible()) then -- l'effet est visible, affiche -- timer 1, le gros (secondes) Powa_timertex[3]:SetVertexColor(PowaSet[PowaActiveTimer2].r,PowaSet[PowaActiveTimer2].g,PowaSet[PowaActiveTimer2].b); -- si le timer est > 60, le transforme en minutes newvalue = PowaActiveTimer2Value; if (newvalue > 60.00) then newvalue = newvalue / 60; end newvalue = math.min (99.00, newvalue); deci = math.floor(newvalue / 10); uni = math.floor(newvalue - (deci*10)); Powa_timertex[3]:SetTexCoord(Tstep * uni, Tstep * (uni+1), Tstep * deci, Tstep * (deci+1)); Powa_Timer[3]:Show(); -- timer 2, le petit (centieme de secondes) Powa_timertex[4]:SetVertexColor(PowaSet[PowaActiveTimer2].r,PowaSet[PowaActiveTimer2].g,PowaSet[PowaActiveTimer2].b); newvalue = PowaActiveTimer2Value; if (newvalue > 60.00) then newvalue = math.mod(newvalue,60); else newvalue = (newvalue - math.floor(newvalue)) * 100; end deci = math.floor(newvalue / 10); uni = math.floor(newvalue - (deci*10)); Powa_timertex[4]:SetTexCoord(Tstep * uni, Tstep * (uni+1), Tstep * deci, Tstep * (deci+1)); if (PowaMisc.DCents == true) then Powa_Timer[4]:Show(); else Powa_Timer[4]:Hide(); end else Powa_Timer[3]:Hide(); -- cache les timer Powa_Timer[4]:Hide(); -- cache les timer end else Powa_Timer[3]:Hide(); Powa_Timer[4]:Hide(); -- cache les timer end PowaActiveTimer2 = 0; PowaActiveTimer2Value = 0; end -- -------------------------------------------------------------------------------------- ON UPDATE minScale = {a=0, w=0, h=0}; maxScale = {a=0, w=0, h=0}; curScale = {a=0, w=0, h=0}; speedScale = 0; function Powa_OnUpdate(elapsed) for i = 1, CurrentTestAura do if (PowaEnabled == 0) then return; end -- desactived if (Powa_FramesVisibleTime[i] > 0) then -- si visible seulement Powa_UpdateTimer(i); -- met a jour les Timers curScale.w = Powa_Frames[i].baseL; -- regle la taille de l'image en pixel curScale.h = Powa_Frames[i].baseH; -- pas d'anim si l'effet va disparaitre avec duree if ((PowaSet[i].duration > 0) and (Powa_Frames[i].duree > PowaSet[i].duration)) then -- si visible, baisse l'alpha if (Powa_Frames[i]:GetAlpha() > 0) then curScale.a = Powa_Frames[i]:GetAlpha() - (elapsed / 2); -- si alpha 0, cache if (curScale.a <= 0) then Powa_Frames[i]:SetAlpha(0); else Powa_Frames[i]:SetAlpha(curScale.a); end end -- Animation 1 : aucune elseif (PowaSet[i].anim1 == 1) then -- Animation 2 : max alpha <-> mi-alpha elseif (PowaSet[i].anim1 == 2) then minScale.a = PowaSet[i].alpha * 0.5 * PowaSet[i].speed; maxScale.a = PowaSet[i].alpha; if (Powa_Frames[i].statut == 0) then curScale.a = Powa_Frames[i]:GetAlpha() - (elapsed / 2); Powa_Frames[i]:SetAlpha( curScale.a ) if (Powa_Frames[i]:GetAlpha() < minScale.a) then Powa_Frames[i]:SetAlpha(minScale.a); Powa_Frames[i].statut = 1; end else curScale.a = Powa_Frames[i]:GetAlpha() + (elapsed / 2); if (curScale.a > 1.0) then curScale.a = 1.0; end -- pas trop haut non plus Powa_Frames[i]:SetAlpha( curScale.a ) if (Powa_Frames[i]:GetAlpha() >= maxScale.a) then Powa_Frames[i]:SetAlpha(maxScale.a); Powa_Frames[i].statut = 0; end end -- Animation 3 : mini-zoom in repetitif + fading elseif (PowaSet[i].anim1 == 3) then minScale.w = curScale.w * 0.90; minScale.h = curScale.h * 0.90; maxScale.w = curScale.w * 1.20; maxScale.h = curScale.h * 1.20; speedScale = (25 * PowaSet[i].speed) * PowaSet[i].size; if (Powa_Frames[i].statut == 1) then -- decale anim 2 Powa_Frames[i]:SetWidth(curScale.w * 1.15); Powa_Frames[i]:SetHeight(curScale.h * 1.15); Powa_Frames[i].statut = 0; end Powa_Frames[i]:SetWidth( Powa_Frames[i]:GetWidth() + (elapsed * speedScale) ) Powa_Frames[i]:SetHeight( Powa_Frames[i]:GetHeight() + (elapsed * speedScale) ) Powa_Frames[i]:SetAlpha( ((maxScale.w - Powa_Frames[i]:GetWidth()) / (maxScale.w - minScale.w)) * PowaSet[i].alpha ); if (Powa_Frames[i]:GetWidth() > maxScale.w) then Powa_Frames[i]:SetWidth(minScale.w); Powa_Frames[i]:SetHeight(minScale.h); end -- Animation 4 : mini-zoom in/out elseif (PowaSet[i].anim1 == 4) then minScale.w = curScale.w * 0.95; minScale.h = curScale.h * 0.95; maxScale.w = curScale.w * 1.05; maxScale.h = curScale.h * 1.05; speedScale = (50 * PowaSet[i].speed) * PowaSet[i].size; if (Powa_Frames[i].statut == 0) then Powa_Frames[i]:SetWidth( Powa_Frames[i]:GetWidth() + (elapsed * speedScale * PowaSet[i].torsion) ) Powa_Frames[i]:SetHeight( Powa_Frames[i]:GetHeight() + (elapsed * speedScale * (2-PowaSet[i].torsion) ) ) if (Powa_Frames[i]:GetWidth() > maxScale.w) then Powa_Frames[i]:SetWidth(maxScale.w); Powa_Frames[i]:SetHeight(maxScale.h); Powa_Frames[i].statut = 1; end else Powa_Frames[i]:SetWidth( Powa_Frames[i]:GetWidth() - (elapsed * speedScale * PowaSet[i].torsion) ) Powa_Frames[i]:SetHeight( Powa_Frames[i]:GetHeight() - (elapsed * speedScale * (2-PowaSet[i].torsion) ) ) if (Powa_Frames[i]:GetWidth() < minScale.w) then Powa_Frames[i]:SetWidth(minScale.w); Powa_Frames[i]:SetHeight(minScale.h); Powa_Frames[i].statut = 0; end end -- Animation 5 : effet bulle elseif (PowaSet[i].anim1 == 5) then minScale.w = curScale.w * 0.95; minScale.h = curScale.h * 0.95; maxScale.w = curScale.w * 1.05; maxScale.h = curScale.h * 1.05; speedScale = (50 * PowaSet[i].speed) * PowaSet[i].size; if (Powa_Frames[i].statut == 0) then Powa_Frames[i]:SetWidth( Powa_Frames[i]:GetWidth() + (elapsed * speedScale * PowaSet[i].torsion) ) Powa_Frames[i]:SetHeight( Powa_Frames[i]:GetHeight() - (elapsed * speedScale * (2-PowaSet[i].torsion) ) ) if (Powa_Frames[i]:GetWidth() > maxScale.w) then Powa_Frames[i]:SetWidth(maxScale.w); Powa_Frames[i]:SetHeight(minScale.h); Powa_Frames[i].statut = 1; end else Powa_Frames[i]:SetWidth( Powa_Frames[i]:GetWidth() - (elapsed * speedScale * PowaSet[i].torsion) ) Powa_Frames[i]:SetHeight( Powa_Frames[i]:GetHeight() + (elapsed * speedScale * (2-PowaSet[i].torsion) ) ) if (Powa_Frames[i]:GetHeight() > maxScale.h) then Powa_Frames[i]:SetWidth(minScale.w); Powa_Frames[i]:SetHeight(maxScale.h); Powa_Frames[i].statut = 0; end end -- position au hasard + zoom in + fade elseif (PowaSet[i].anim1 == 6) then if (Powa_Frames[i]:GetAlpha() > 0) then curScale.a = Powa_Frames[i]:GetAlpha() - (elapsed * PowaSet[i].alpha * 0.5); if (curScale.a < 0) then Powa_Frames[i]:SetAlpha(0.0); else Powa_Frames[i]:SetAlpha(curScale.a); end maxScale.w = Powa_Frames[i]:GetWidth() + (elapsed * 100 * PowaSet[i].speed * PowaSet[i].size); maxScale.h = Powa_Frames[i]:GetHeight() + (elapsed * 100 * PowaSet[i].speed * PowaSet[i].size); if ( (maxScale.w * 1.5) > Powa_Frames[i]:GetWidth()) then -- evite les lags Powa_Frames[i]:SetWidth(maxScale.w) Powa_Frames[i]:SetHeight(maxScale.h) end else maxScale.w = random(0,10) - 5; maxScale.h = random(0,10) - 5; Powa_Frames[i]:SetAlpha(PowaSet[i].alpha); Powa_Frames[i]:SetWidth(curScale.w * 0.85); Powa_Frames[i]:SetHeight(curScale.h * 0.85); Powa_Frames[i]:SetPoint("Center",PowaSet[i].x + maxScale.w, PowaSet[i].y + maxScale.h); end -- static sauf parfois ou la texture est decalee + opaque (type electrique) elseif (PowaSet[i].anim1 == 7) then if (Powa_Frames[i].statut < 2) then Powa_Frames[i]:SetAlpha(PowaSet[i].alpha / 2); -- mi-alpha if (random( 210-(PowaSet[i].speed*100) ) == 1) then Powa_Frames[i].statut = 2; maxScale.w = random(0,10) - 5; maxScale.h = random(0,10) - 5; Powa_Frames[i]:SetPoint("Center",PowaSet[i].x + maxScale.w, PowaSet[i].y + maxScale.h); Powa_Frames[i]:SetAlpha(PowaSet[i].alpha); end else Powa_Frames[i]:SetPoint("Center",PowaSet[i].x, PowaSet[i].y); Powa_Frames[i].statut = 0; end -- zoom out + stop + fade elseif (PowaSet[i].anim1 == 8) then minScale.w = curScale.w; minScale.h = curScale.h; maxScale.w = curScale.w * 1.30; maxScale.h = curScale.h * 1.30; speedScale = (50 * PowaSet[i].speed) * PowaSet[i].size; if (Powa_Frames[i].statut == 0) then -- demarre le zoom out (max size) Powa_Frames[i]:SetWidth(maxScale.w); Powa_Frames[i]:SetHeight(maxScale.h); Powa_Frames[i]:SetAlpha(0.0); Powa_Frames[i].statut = 2; elseif (Powa_Frames[i].statut == 2) then -- zoom out + fade in Powa_Frames[i]:SetWidth( Powa_Frames[i]:GetWidth() - (elapsed * speedScale * PowaSet[i].torsion) ) Powa_Frames[i]:SetHeight( Powa_Frames[i]:GetHeight() - (elapsed * speedScale * (2-PowaSet[i].torsion) ) ) Powa_Frames[i]:SetAlpha( ((maxScale.w - Powa_Frames[i]:GetWidth()) / (maxScale.w - minScale.w)) * PowaSet[i].alpha ); if (Powa_Frames[i]:GetWidth() < curScale.w) then Powa_Frames[i]:SetWidth(curScale.w); Powa_Frames[i]:SetHeight(curScale.h); Powa_Frames[i].statut = 1; end elseif (Powa_Frames[i].statut == 1) then -- demarre le fade-out Powa_Frames[i]:SetWidth(curScale.w); Powa_Frames[i]:SetHeight(curScale.h); Powa_Frames[i]:SetAlpha(PowaSet[i].alpha); Powa_Frames[i].statut = 3; elseif (Powa_Frames[i].statut == 3) then -- fade-out curScale.a = Powa_Frames[i]:GetAlpha() - (elapsed / random(1,2)); if (curScale.a < 0.0) then Powa_Frames[i]:SetAlpha(0.0); Powa_Frames[i].statut = 0; else Powa_Frames[i]:SetAlpha(curScale.a); end end -- deplacement vers le haut + fade-out + reduction elseif (PowaSet[i].anim1 == 9) then speedScale = (50 * PowaSet[i].speed) * PowaSet[i].size; if (Powa_Frames[i].statut < 2) then -- debut Powa_Frames[i]:SetWidth(curScale.w); Powa_Frames[i]:SetHeight(curScale.h); Powa_Frames[i]:SetPoint("Center",PowaSet[i].x, PowaSet[i].y); Powa_Frames[i]:SetAlpha(PowaSet[i].alpha); Powa_Frames[i].statut = 2; else _,_,_,xOfs,yOfs = Powa_Frames[i]:GetPoint(); Powa_Frames[i]:SetPoint("Center",xOfs + (random(1,3)-2), yOfs + (elapsed * random(10,20))); curScale.a = Powa_Frames[i]:GetAlpha() - ( (elapsed / random(2,4)) * PowaSet[i].alpha); Powa_Frames[i]:SetWidth( Powa_Frames[i]:GetWidth() - (elapsed * speedScale * PowaSet[i].torsion) ) Powa_Frames[i]:SetHeight( Powa_Frames[i]:GetHeight() - (elapsed * speedScale * (2-PowaSet[i].torsion) ) ) if (curScale.a < 0.0) then Powa_Frames[i]:SetAlpha(0.0); Powa_Frames[i].statut = 1; else Powa_Frames[i]:SetAlpha(curScale.a); end end end -- si duration if (PowaSet[i].duration > 0) then -- ajoute le temps passe Powa_Frames[i].duree = Powa_Frames[i].duree + elapsed; end -- FADE OUT elseif Powa_Frames[i]:IsVisible() then if (PowaMisc.quickhide == false) then curScale.a = Powa_Frames[i]:GetAlpha() - (elapsed * 2); if (curScale.a <= 0) then Powa_Frames[i]:Hide(); else Powa_Frames[i]:SetAlpha(curScale.a); Powa_Frames[i]:SetWidth(Powa_Frames[i]:GetWidth() + (elapsed * 200) ); Powa_Frames[i]:SetHeight(Powa_Frames[i]:GetHeight() + (elapsed * 200) ); end else Powa_Frames[i]:Hide(); end end end Powa_ResetTimers(); -- reset Timers end -- ----------------------------------------------------------------------------- LIGNE DE COMMANDE function Powa_SlashHandler(msg) msgNumber = 0; if (msg == "") then -- aucun parametre, on ouvre/ferme les options if (PowaBarConfigFrame:IsVisible()) then Powa_OptionClose(); else Powa_OptionHideAll(); Powa_InitPage(); PowaModTest = true; PowaBarConfigFrame:Show(); end else -- y'a des parametres, on y travaille for a in string.gfind( msg, "maxtex (%d+)" ) do msgNumber = tonumber(a); if (msgNumber > 50) then msgNumber = 50; elseif (msgNumber < 20) then msgNumber = 2; end PowaGlobal.maxtextures = msgNumber; getglobal("PowaBarAuraTextureSlider"):SetMinMaxValues(1,msgNumber); getglobal("PowaBarAuraTextureSliderHigh"):SetText(msgNumber); DEFAULT_CHAT_FRAME:AddMessage("|cffB0A0ff<Power Auras>|r "..PowaText.aideCommande2a.." "..a); return; end for a in string.gfind( msg, "maxeffect (%d+)" ) do msgNumber = tonumber(a); if (msgNumber > 100) then msgNumber = 100; elseif (msgNumber < 10) then msgNumber = 10; end PowaEnabled = 0; -- desactive temporairement les effets Powa_OptionHideAll(); -- cache tout les effets en cours MaxAuras = msgNumber; -- definie le max d'aura SecondeAura = MaxAuras + 1; -- definie la derniere aura CurrentTestAura = MaxAuras + 2; PowaGlobal.maxeffects = MaxAuras; -- sauve le nombre max d'effet Powa_InitTabs(); -- initialise les pages d'effets en plus Powa_CreateFrames(); -- cree les textures des effets en plus PowaEnabled = 1; -- reactive les effets CurrentAura = 1; -- defini l'effet en cours 1 Powa_InitPage(); -- initalise les pages des options DEFAULT_CHAT_FRAME:AddMessage("|cffB0A0ff<Power Auras>|r "..PowaText.aideCommande3a.." "..a); return; end DEFAULT_CHAT_FRAME:AddMessage("|cffB0A0ff<Power Auras>|r "..PowaText.aideCommande1); DEFAULT_CHAT_FRAME:AddMessage("|cffffff50 /powa maxtex ##|r : "..PowaText.aideCommande2); DEFAULT_CHAT_FRAME:AddMessage("|cffffff50 /powa maxeffect ##|r : "..PowaText.aideCommande3); end end -- --------------------------------------------------------------------------- GESTION DES OPTIONS function Powa_InitPage() getglobal("PowaBarAuraTextureSlider"):SetValue(PowaSet[CurrentAura].texture); getglobal("PowaBarAuraAlphaSlider"):SetValue(PowaSet[CurrentAura].alpha); getglobal("PowaBarAuraSizeSlider"):SetValue(PowaSet[CurrentAura].size); getglobal("PowaBarAuraCoordSlider"):SetValue(PowaSet[CurrentAura].y); getglobal("PowaBarAuraCoordXSlider"):SetValue(PowaSet[CurrentAura].x); getglobal("PowaBarAuraAnim2Slider"):SetValue(PowaSet[CurrentAura].anim2); getglobal("PowaBarAuraAnim1Slider"):SetValue(PowaSet[CurrentAura].anim1); getglobal("PowaBarAuraAnimSpeedSlider"):SetValue(PowaSet[CurrentAura].speed); getglobal("PowaBarAuraDurationSlider"):SetValue(PowaSet[CurrentAura].duration); getglobal("PowaBarAuraSymSlider"):SetValue(PowaSet[CurrentAura].symetrie); getglobal("PowaBarAuraDeformSlider"):SetValue(PowaSet[CurrentAura].torsion); getglobal("PowaBarBuffName"):SetText(PowaSet[CurrentAura].buffname); getglobal("AuraTexture"):SetTexture("Interface\\Addons\\PowerAuras\\Aura"..PowaSet[CurrentAura].texture..".tga"); getglobal("PowaColorNormalTexture"):SetVertexColor(PowaSet[CurrentAura].r,PowaSet[CurrentAura].g,PowaSet[CurrentAura].b); getglobal("AuraTexture"):SetVertexColor(PowaSet[CurrentAura].r,PowaSet[CurrentAura].g,PowaSet[CurrentAura].b); getglobal("PowaColor_SwatchBg").r = PowaSet[CurrentAura].r; getglobal("PowaColor_SwatchBg").g = PowaSet[CurrentAura].g; getglobal("PowaColor_SwatchBg").b = PowaSet[CurrentAura].b; getglobal("PowaHeader"):SetText("POWER AURAS "..PowaVersion); getglobal("powa_Text"):SetText(PowaText.nomTitre.." "..CurrentAura.."/"..MaxAuras); getglobal("PowaHideAllButton"):SetText(PowaText.nomHide); getglobal("PowaTestButton"):SetText(PowaText.nomTest); getglobal("PowaCloseButton"):SetText(PowaText.nomClose); getglobal("PowaListButton"):SetText(PowaText.nomListe); if (PowaSet[CurrentAura].isdebuff) then getglobal("PowaDebuffButton"):SetChecked(true); getglobal("PowaDebuffTypeButton"):SetChecked(false); getglobal("PowaBarBuffNameText"):SetText(PowaText.nomDebuff); getglobal("PowaBarBuffName").aide = PowaText.aideBuff2; elseif (PowaSet[CurrentAura].isdebufftype) then getglobal("PowaDebuffTypeButton"):SetChecked(true); getglobal("PowaDebuffButton"):SetChecked(false); getglobal("PowaBarBuffNameText"):SetText(PowaText.nomDebuffType); getglobal("PowaBarBuffName").aide = PowaText.aideBuff3; else getglobal("PowaDebuffButton"):SetChecked(false); getglobal("PowaDebuffTypeButton"):SetChecked(false); getglobal("PowaBarBuffNameText"):SetText(PowaText.nomBuff); getglobal("PowaBarBuffName").aide = PowaText.aideBuff; end getglobal("PowaShowTimerButton"):SetChecked(PowaSet[CurrentAura].timer); getglobal("PowaInverseButton"):SetChecked(PowaSet[CurrentAura].inverse); if (PowaSet[CurrentAura].inverse) then PowaSet[CurrentAura].timer = false; getglobal("PowaShowTimerButton"):SetChecked(PowaSet[CurrentAura].timer); Powa_DisableCheckBox("PowaShowTimerButton"); else Powa_EnableCheckBox("PowaShowTimerButton"); end end function Powa_ChangePagePrev() -- page precedente if (CurrentAura == 1) then CurrentAura = MaxAuras; else CurrentAura = CurrentAura - 1; end Powa_InitPage(); end function Powa_ChangePageNext() -- page suivante if (CurrentAura == MaxAuras) then CurrentAura = 1; else CurrentAura = CurrentAura + 1; end Powa_InitPage(); end function Powa_UpdateAura() -- met a jour l'effet apres modification d'options if (PowaEnabled == 0) then return; end -- desactived Powa_FramesVisibleTime[CurrentAura] = 0; Powa_FramesVisibleTime[SecondeAura] = 0; if (Powa_Frames[CurrentAura]:IsVisible()) then -- sinon on affiche seulement si deja visible Powa_DisplayAura(CurrentAura); end end function Powa_OptionClose() -- ferme la fenetre d'option PowaModTest = false; getglobal("PowaBarConfigFrame"):Hide(); getglobal("PowaListFrame"):Hide(); -- cache tous les effets en test for i = 1, MaxAuras+2 do if (PowaSet[i].duration > 0) then Powa_Frames[i].duree = 31; -- force affiche et mode transparent Powa_Frames[i]:Show(); Powa_Frames[i]:SetAlpha(0.0); Powa_FramesVisibleTime[i] = 1; else Powa_FramesVisibleTime[i] = 0; end end Powa_NewCheckBuffs(); -- detect les effets en cours end function Powa_OptionTest() -- teste ou masque l'effet choisi if (Powa_Frames[CurrentAura]:IsVisible()) then -- deja visible, on la cache Powa_FramesVisibleTime[CurrentAura] = 0; Powa_FramesVisibleTime[SecondeAura] = 0; else -- pas visible alors on affiche Powa_DisplayAura(CurrentAura); end end function Powa_OptionHideAll() -- cache tous les effets -- cache tous les effets en test for i = 1, MaxAuras+2 do Powa_FramesVisibleTime[i] = 0; end end -- ---------------------------------------------------------------------------------- FENETRE D'OPTION function PowaBarAuraTextureSliderChanged() local SliderValue = getglobal("PowaBarAuraTextureSlider"):GetValue(); getglobal("PowaBarAuraTextureSliderText"):SetText(PowaText.nomTexture.." : "..SliderValue); getglobal("AuraTexture"):SetTexture("Interface\\Addons\\PowerAuras\\Aura"..SliderValue..".tga"); PowaSet[CurrentAura].texture = SliderValue; Powa_UpdateAura(); end function PowaBarAuraAlphaSliderChanged() local SliderValue = getglobal("PowaBarAuraAlphaSlider"):GetValue(); getglobal("PowaBarAuraAlphaSliderText"):SetText(PowaText.nomAlpha.." : "..format("%.2f", SliderValue) ); PowaSet[CurrentAura].alpha = SliderValue; Powa_UpdateAura(); end function PowaBarAuraSizeSliderChanged() local SliderValue = getglobal("PowaBarAuraSizeSlider"):GetValue(); getglobal("PowaBarAuraSizeSliderText"):SetText(PowaText.nomTaille.." : "..format("%.2f", SliderValue) ); PowaSet[CurrentAura].size = SliderValue; Powa_UpdateAura(); end function PowaBarAuraCoordSliderChanged() local SliderValue = getglobal("PowaBarAuraCoordSlider"):GetValue(); getglobal("PowaBarAuraCoordSliderText"):SetText(PowaText.nomPos.." Y : "..SliderValue); PowaSet[CurrentAura].y = SliderValue; Powa_UpdateAura(); end function PowaBarAuraCoordXSliderChanged() local SliderValue = getglobal("PowaBarAuraCoordXSlider"):GetValue(); getglobal("PowaBarAuraCoordXSliderText"):SetText(PowaText.nomPos.." X : "..SliderValue); PowaSet[CurrentAura].x = SliderValue; Powa_UpdateAura(); end function PowaBarAuraAnim2SliderChanged() local SliderValue = getglobal("PowaBarAuraAnim2Slider"):GetValue(); getglobal("PowaBarAuraAnim2SliderText"):SetText(PowaText.nomAnim2.." : "..SliderValue); PowaSet[CurrentAura].anim2 = SliderValue; Powa_UpdateAura(); end function PowaBarAuraAnim1SliderChanged() local SliderValue = getglobal("PowaBarAuraAnim1Slider"):GetValue(); getglobal("PowaBarAuraAnim1SliderText"):SetText(PowaText.nomAnim1.." : "..SliderValue); PowaSet[CurrentAura].anim1 = SliderValue; Powa_UpdateAura(); end function PowaBarAuraAnimSpeedSliderChanged() local SliderValue = getglobal("PowaBarAuraAnimSpeedSlider"):GetValue(); getglobal("PowaBarAuraAnimSpeedSliderText"):SetText(PowaText.nomSpeed.." : "..format("%.0f",SliderValue*100).."%"); PowaSet[CurrentAura].speed = SliderValue; Powa_UpdateAura(); end function PowaBarAuraAnimDurationSliderChanged() local SliderValue = getglobal("PowaBarAuraDurationSlider"):GetValue(); getglobal("PowaBarAuraDurationSliderText"):SetText(PowaText.nomDuration.." : "..SliderValue.." sec"); PowaSet[CurrentAura].duration = SliderValue; Powa_UpdateAura(); end function PowaBarAuraSymSliderChanged() local SliderValue = getglobal("PowaBarAuraSymSlider"):GetValue(); if (SliderValue == 0) then getglobal("PowaBarAuraSymSliderText"):SetText(PowaText.nomSymetrie.." : "..PowaText.aucune); elseif (SliderValue == 1) then getglobal("PowaBarAuraSymSliderText"):SetText(PowaText.nomSymetrie.." : X"); elseif (SliderValue == 2) then getglobal("PowaBarAuraSymSliderText"):SetText(PowaText.nomSymetrie.." : Y"); elseif (SliderValue == 3) then getglobal("PowaBarAuraSymSliderText"):SetText(PowaText.nomSymetrie.." : XY"); end PowaSet[CurrentAura].symetrie = SliderValue; Powa_UpdateAura(); end function PowaBarAuraDeformSliderChanged() local SliderValue = getglobal("PowaBarAuraDeformSlider"):GetValue(); getglobal("PowaBarAuraDeformSliderText"):SetText(PowaText.nomDeform.." : "..format("%.2f", SliderValue)); PowaSet[CurrentAura].torsion = SliderValue; Powa_UpdateAura(); end function PowaMaxTexSliderChanged() local SliderValue = getglobal("PowaMaxTexSlider"):GetValue(); getglobal("PowaMaxTexSliderText"):SetText(PowaText.nomMaxTex.." : "..SliderValue); getglobal("PowaBarAuraTextureSlider"):SetMinMaxValues(1,SliderValue); getglobal("PowaBarAuraTextureSliderHigh"):SetText(SliderValue); PowaGlobal.maxtextures = SliderValue; end function PowaTextChanged() PowaSet[CurrentAura].buffname = getglobal("PowaBarBuffName"):GetText(); end function PowaDebuffChecked() if (getglobal("PowaDebuffButton"):GetChecked()) then PowaSet[CurrentAura].isdebuff = true; PowaSet[CurrentAura].isdebufftype = false; getglobal("PowaDebuffTypeButton"):SetChecked(false); getglobal("PowaBarBuffNameText"):SetText(PowaText.nomDebuff); getglobal("PowaBarBuffName").aide = PowaText.aideBuff2; else PowaSet[CurrentAura].isdebuff = false; getglobal("PowaBarBuffNameText"):SetText(PowaText.nomBuff); getglobal("PowaBarBuffName").aide = PowaText.aideBuff; end Powa_UpdateList(); end function PowaDebuffTypeChecked() if (getglobal("PowaDebuffTypeButton"):GetChecked()) then PowaSet[CurrentAura].isdebufftype = true; PowaSet[CurrentAura].isdebuff = false; getglobal("PowaDebuffButton"):SetChecked(false); getglobal("PowaBarBuffNameText"):SetText(PowaText.nomDebuffType); getglobal("PowaBarBuffName").aide = PowaText.aideBuff3; else PowaSet[CurrentAura].isdebufftype = false; getglobal("PowaBarBuffNameText"):SetText(PowaText.nomBuff); getglobal("PowaBarBuffName").aide = PowaText.aideBuff; end Powa_UpdateList(); end function PowaQuickHideChecked() if (getglobal("PowaQuickHideButton"):GetChecked()) then PowaMisc.quickhide = true; else PowaMisc.quickhide = false; end end function PowaShowTimerChecked() if (getglobal("PowaShowTimerButton"):GetChecked()) then PowaSet[CurrentAura].timer = true; else PowaSet[CurrentAura].timer = false; end end function PowaInverseChecked() if (getglobal("PowaInverseButton"):GetChecked()) then PowaSet[CurrentAura].inverse = true; PowaSet[CurrentAura].timer = false; getglobal("PowaShowTimerButton"):SetChecked(false); Powa_DisableCheckBox("PowaShowTimerButton"); else PowaSet[CurrentAura].inverse = false; Powa_EnableCheckBox("PowaShowTimerButton"); end end function Powa_DisableCheckBox(checkBox) getglobal(checkBox):Disable(); getglobal(checkBox.."Text"):SetTextColor(GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b); end function Powa_EnableCheckBox(checkBox, checked) getglobal(checkBox):Enable(); getglobal(checkBox.."Text"):SetTextColor(NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b); end -- ---------------------------------------------------------------------------- OPTIONS DEPLACEMENT function PowaBar_MouseDown( strButton, frmFrame) if( strButton == "LeftButton") then getglobal( frmFrame ):StartMoving( ); end end function PowaBar_MouseUp( strButton, frmFrame) getglobal( frmFrame ):StopMovingOrSizing( ); end -- ----------------------------------------------------------------------------------- COLOR PICKER function PowaOptionsFrame_SetColor() local r,g,b = ColorPickerFrame:GetColorRGB(); local swatch,frame; swatch = getglobal("PowaColorNormalTexture"); -- juste le visuel frame = getglobal("PowaColor_SwatchBg"); -- enregistre la couleur swatch:SetVertexColor(r,g,b); frame.r = r; frame.g = g; frame.b = b; PowaSet[CurrentAura].r = r; PowaSet[CurrentAura].g = g; PowaSet[CurrentAura].b = b; getglobal("AuraTexture"):SetVertexColor(r,g,b); Powa_UpdateAura(); end function PowaOptionsFrame_CancelColor() local r = ColorPickerFrame.previousValues.r; local g = ColorPickerFrame.previousValues.g; local b = ColorPickerFrame.previousValues.b; local swatch,frame; swatch = getglobal("PowaColorNormalTexture"); -- juste le visuel frame = getglobal("PowaColor_SwatchBg"); -- enregistre la couleur swatch:SetVertexColor(r,g,b); frame.r = r; frame.g = g; frame.b = b; getglobal("AuraTexture"):SetVertexColor(r,g,b); end function Powa_OpenColorPicker() CloseMenus(); button = getglobal("PowaColor_SwatchBg"); ColorPickerFrame.func = PowaOptionsFrame_SetColor -- button.swatchFunc; ColorPickerFrame:SetColorRGB(button.r, button.g, button.b); ColorPickerFrame.previousValues = {r = button.r, g = button.g, b = button.b, opacity = button.opacity}; ColorPickerFrame.cancelFunc = PowaOptionsFrame_CancelColor ColorPickerFrame:SetPoint("TOPLEFT", "PowaBarConfigFrame", "TOPRIGHT", 0, 0) ColorPickerFrame:Show(); end
0
0.804539
1
0.804539
game-dev
MEDIA
0.89321
game-dev
0.96027
1
0.96027
H4PM/Elywing
3,974
src/pocketmine/block/WoodenButton.php
<?php /* * * _____ _____ __ _ _ _____ __ __ _____ * / ___| | ____| | \ | | | | / ___/ \ \ / / / ___/ * | | | |__ | \| | | | | |___ \ \/ / | |___ * | | _ | __| | |\ | | | \___ \ \ / \___ \ * | |_| | | |___ | | \ | | | ___| | / / ___| | * \_____/ |_____| |_| \_| |_| /_____/ /_/ /_____/ * * 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. * * @author iTX Technologies * @link https://itxtech.org * */ namespace pocketmine\block; use pocketmine\item\Item; use pocketmine\level\Level; use pocketmine\level\sound\ButtonClickSound; use pocketmine\math\Vector3; use pocketmine\Player; class WoodenButton extends RedstoneSource{ protected $id = self::WOODEN_BUTTON; public function __construct($meta = 0){ $this->meta = $meta; } public function onUpdate($type){ if($type == Level::BLOCK_UPDATE_SCHEDULED){ if($this->isActivated()) { $this->meta ^= 0x08; $this->getLevel()->setBlock($this, $this, true, false); $this->getLevel()->addSound(new ButtonClickSound($this)); $this->deactivate(); } return Level::BLOCK_UPDATE_SCHEDULED; } if($type === Level::BLOCK_UPDATE_NORMAL){ $side = $this->getDamage(); if($this->isActivated()) $side ^= 0x08; $faces = [ 0 => 1, 1 => 0, 2 => 3, 3 => 2, 4 => 5, 5 => 4, ]; if($this->getSide($faces[$side]) instanceof Transparent){ $this->getLevel()->useBreakOn($this); return Level::BLOCK_UPDATE_NORMAL; } } return false; } public function deactivate(array $ignore = []){ parent::deactivate($ignore = []); $faces = [ 0 => 1, 1 => 0, 2 => 3, 3 => 2, 4 => 5, 5 => 4, ]; $side = $this->meta; if($this->isActivated()) $side ^= 0x08; $block = $this->getSide($faces[$side])->getSide(Vector3::SIDE_UP); if(!$this->equals($block)){ $this->deactivateBlock($block); } if($side != 1){ $this->deactivateBlock($this->getSide($faces[$side], 2)); } $this->checkTorchOff($this->getSide($faces[$side]),[$this->getOppositeSide($faces[$side])]); } public function activate(array $ignore = []){ parent::activate($ignore = []); $faces = [ 0 => 1, 1 => 0, 2 => 3, 3 => 2, 4 => 5, 5 => 4, ]; $side = $this->meta; if($this->isActivated()) $side ^= 0x08; $block = $this->getSide($faces[$side])->getSide(Vector3::SIDE_UP); if(!$this->equals($block)){ $this->activateBlock($block); } if($side != 1){ $block = $this->getSide($faces[$side], 2); $this->activateBlock($block); } $this->checkTorchOn($this->getSide($faces[$side]),[$this->getOppositeSide($faces[$side])]); } public function getName(){ return "Wooden Button"; } public function getHardness() { return 0.5; } public function onBreak(Item $item){ if($this->isActivated()){ $this->meta ^= 0x08; $this->getLevel()->setBlock($this, $this, true, false); $this->deactivate(); } $this->getLevel()->setBlock($this, new Air(), true, false); } public function place(Item $item, Block $block, Block $target, $face, $fx, $fy, $fz, Player $player = null){ if($target->isTransparent() === false){ $this->meta = $face; $this->getLevel()->setBlock($block, $this, true, false); return true; } return false; } public function canBeActivated() : bool { return true; } public function isActivated(Block $from = null){ return (($this->meta & 0x08) === 0x08); } public function onActivate(Item $item, Player $player = null){ if(!$this->isActivated()){ $this->meta ^= 0x08; $this->getLevel()->setBlock($this, $this, true, false); $this->getLevel()->addSound(new ButtonClickSound($this)); $this->activate(); $this->getLevel()->scheduleUpdate($this, 30); } return true; } }
0
0.991742
1
0.991742
game-dev
MEDIA
0.878939
game-dev
0.984124
1
0.984124
Cairath/ONI-Mods
2,675
src/PalmeraTree/PalmeraTreePatches.cs
using HarmonyLib; using static CaiLib.Utils.CarePackagesUtils; using static CaiLib.Utils.PlantUtils; using static CaiLib.Utils.RecipeUtils; using static CaiLib.Utils.StringUtils; namespace PalmeraTree { public class PalmeraTreePatches { [HarmonyPatch(typeof(EntityConfigManager))] [HarmonyPatch(nameof(EntityConfigManager.LoadGeneratedEntities))] public class EntityConfigManager_LoadGeneratedEntities_Patch { public static void Prefix() { AddPlantStrings(PalmeraTreeConfig.Id, PalmeraTreeConfig.Name, PalmeraTreeConfig.Description, PalmeraTreeConfig.DomesticatedDescription); AddPlantSeedStrings(PalmeraTreeConfig.Id, PalmeraTreeConfig.SeedName, PalmeraTreeConfig.SeedDescription); AddFoodStrings(SteamedPalmeraBerryConfig.Id, SteamedPalmeraBerryConfig.Name, SteamedPalmeraBerryConfig.Description, SteamedPalmeraBerryConfig.RecipeDescription); AddFoodStrings(PalmeraBerryConfig.Id, PalmeraBerryConfig.Name, PalmeraBerryConfig.Description); AddCropType(PalmeraBerryConfig.Id, 20, 10); } } [HarmonyPatch(typeof(Immigration))] [HarmonyPatch("ConfigureCarePackages")] public static class Immigration_ConfigureCarePackages_Patch { public static void Postfix(ref Immigration __instance) { AddCarePackage(ref __instance, PalmeraTreeConfig.SeedId, 1f, () => CycleCondition(48)); } } [HarmonyPatch(typeof(SupermaterialRefineryConfig))] [HarmonyPatch("ConfigureBuildingTemplate")] public class SupermaterialRefineryConfig_ConfigureBuildingTemplate_Patch { public static void Postfix() { AddComplexRecipe( input: new[] { new ComplexRecipe.RecipeElement(BasicSingleHarvestPlantConfig.SEED_ID.ToTag(), 10f), new ComplexRecipe.RecipeElement(BasicFabricConfig.ID.ToTag(), 10f) }, output: new[] { new ComplexRecipe.RecipeElement(TagManager.Create(PalmeraTreeConfig.SeedId), 1f) }, fabricatorId: SupermaterialRefineryConfig.ID, productionTime: 50f, recipeDescription: "What will happen if you mash some organic mass together?", nameDisplayType: ComplexRecipe.RecipeNameDisplay.Result, sortOrder: 1000 ); } } // seems not needed anymore? // [HarmonyPatch(typeof(KSerialization.Manager))] // [HarmonyPatch("GetType")] // [HarmonyPatch(new[] { typeof(string) })] // public static class KSerializationManager_GetType_Patch // { // public static void Postfix(string type_name, ref Type __result) // { // if (type_name == "PalmeraTree.PalmeraTree") // { // __result = typeof(PalmeraTree); // } // } // } } }
0
0.71139
1
0.71139
game-dev
MEDIA
0.348873
game-dev
0.845283
1
0.845283
AionGermany/aion-germany
2,869
AL-Game-5.8/data/scripts/system/handlers/quest/eltnen/_1470HannetsVengeance.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package quest.eltnen; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /** * @author Atomics */ public class _1470HannetsVengeance extends QuestHandler { private final static int questId = 1470; public _1470HannetsVengeance() { super(questId); } @Override public void register() { qe.registerQuestNpc(790004).addOnQuestStart(questId); // Hannet qe.registerQuestNpc(790004).addOnTalkEvent(questId); // Hannet qe.registerQuestNpc(212846).addOnKillEvent(questId); // Kromede } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); int targetId = 0; if (env.getVisibleObject() instanceof Npc) { targetId = ((Npc) env.getVisibleObject()).getNpcId(); } QuestState qs = player.getQuestStateList().getQuestState(questId); if (targetId == 790004) { if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (env.getDialog() == DialogAction.QUEST_SELECT) { return sendQuestDialog(env, 1011); } else { return sendQuestStartDialog(env); } } else if (qs.getStatus() == QuestStatus.REWARD) { return sendQuestEndDialog(env); } } return false; } @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() != QuestStatus.START) { return false; } int var = qs.getQuestVarById(0); int targetId = 0; if (env.getVisibleObject() instanceof Npc) { targetId = ((Npc) env.getVisibleObject()).getNpcId(); } switch (targetId) { case 212846: qs.setQuestVarById(0, var + 1); updateQuestStatus(env); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return true; } return false; } }
0
0.930383
1
0.930383
game-dev
MEDIA
0.972901
game-dev
0.976658
1
0.976658
DBloodworth95/packet-updater
5,317
nonfree/gamepacks/225/aq.java
import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class aq implements ag { static final String ae = "SHA-256"; final MessageDigest ac = this.ax(); static int ab(byte var0) { int var1 = 0; if (var0 == 0) { var1 = 8; } else { for(int var2 = var0 & 255; (var2 & 128) == 0; var2 <<= 1) { ++var1; } } return var1; } boolean ac(int var1, String var2, long var3) { byte[] var5 = this.am(var2, var3); return ae(var5) >= var1; } static int ae(byte[] var0) { int var1 = 0; byte[] var2 = var0; for(int var3 = 0; var3 < var2.length; ++var3) { byte var4 = var2[var3]; int var5 = ag(var4); var1 += var5; if (var5 != 8) { break; } } return var1; } static int ag(byte var0) { int var1 = 0; if (var0 == 0) { var1 = 8; } else { for(int var2 = var0 & 255; (var2 & 128) == 0; var2 <<= 1) { ++var1; } } return var1; } byte[] aa(String var1, long var2) { StringBuilder var4 = new StringBuilder(); var4.append(var1).append(Long.toHexString(var2)); this.ac.reset(); try { this.ac.update(var4.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException var6) { var6.printStackTrace(); } return this.ac.digest(); } MessageDigest ax() { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException var2) { var2.printStackTrace(); return null; } } boolean aq(int var1, String var2, long var3) { byte[] var5 = this.am(var2, var3); return ae(var5) >= var1; } boolean af(int var1, String var2, long var3) { byte[] var5 = this.am(var2, var3); return ae(var5) >= var1; } byte[] am(String var1, long var2) { StringBuilder var4 = new StringBuilder(); var4.append(var1).append(Long.toHexString(var2)); this.ac.reset(); try { this.ac.update(var4.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException var6) { var6.printStackTrace(); } return this.ac.digest(); } byte[] ai(String var1, long var2) { StringBuilder var4 = new StringBuilder(); var4.append(var1).append(Long.toHexString(var2)); this.ac.reset(); try { this.ac.update(var4.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException var6) { var6.printStackTrace(); } return this.ac.digest(); } static int ar(byte[] var0) { int var1 = 0; byte[] var2 = var0; for(int var3 = 0; var3 < var2.length; ++var3) { byte var4 = var2[var3]; int var5 = ag(var4); var1 += var5; if (var5 != 8) { break; } } return var1; } static int al(byte var0) { int var1 = 0; if (var0 == 0) { var1 = 8; } else { for(int var2 = var0 & 255; (var2 & 128) == 0; var2 <<= 1) { ++var1; } } return var1; } static int ad(byte var0) { int var1 = 0; if (var0 == 0) { var1 = 8; } else { for(int var2 = var0 & 1696672263; (var2 & -1262082899) == 0; var2 <<= 1) { ++var1; } } return var1; } static int ah(byte var0) { int var1 = 0; if (var0 == 0) { var1 = 8; } else { for(int var2 = var0 & 255; (var2 & 128) == 0; var2 <<= 1) { ++var1; } } return var1; } static int ap(byte var0) { int var1 = 0; if (var0 == 0) { var1 = 8; } else { for(int var2 = var0 & 255; (var2 & 128) == 0; var2 <<= 1) { ++var1; } } return var1; } aq(au var1) { } static int au(byte[] var0) { int var1 = 0; byte[] var2 = var0; for(int var3 = 0; var3 < var2.length; ++var3) { byte var4 = var2[var3]; int var5 = ag(var4); var1 += var5; if (var5 != 8) { break; } } return var1; } static int at(byte[] var0) { int var1 = 0; byte[] var2 = var0; for(int var3 = 0; var3 < var2.length; ++var3) { byte var4 = var2[var3]; int var5 = ag(var4); var1 += var5; if (var5 != 8) { break; } } return var1; } static int az(byte var0) { int var1 = 0; if (var0 == 0) { var1 = 8; } else { for(int var2 = var0 & 255; (var2 & 128) == 0; var2 <<= 1) { ++var1; } } return var1; } MessageDigest ao() { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException var2) { var2.printStackTrace(); return null; } } MessageDigest as() { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException var2) { var2.printStackTrace(); return null; } } }
0
0.508358
1
0.508358
game-dev
MEDIA
0.464399
game-dev
0.659896
1
0.659896
mozart/mozart2
1,750
platform-test/fd/houses.oz
% From Hentenryck page 132 % In 5 houses live people from different nations with different professions... functor import FD Search export Return define Houses = proc {$ Vars} local N1 N2 N3 N4 N5 C1 C2 C3 C4 C5 P1 P2 P3 P4 P5 A1 A2 A3 A4 A5 D1 D2 D3 D4 D5 in Vars = [N1 N2 N3 N4 N5 C1 C2 C3 C4 C5 P1 P2 P3 P4 P5 A1 A2 A3 A4 A5 D1 D2 D3 D4 D5] Vars = {FD.dom 1#5} {FD.distinct [N1 N2 N3 N4 N5]} {FD.distinct [C1 C2 C3 C4 C5]} {FD.distinct [P1 P2 P3 P4 P5]} {FD.distinct [A1 A2 A3 A4 A5]} {FD.distinct [D1 D2 D3 D4 D5]} N1=C2 N2=A1 N3=P1 N4=D3 N5=1 D5=3 P3=D1 C1=D4 P5=A4 P2=C3 % observe that eqpc is domain version! C1 =: C5 + 1 thread or N5 =: C4-1 [] N5 =: C4+1 end end thread or A3 =: P4-1 [] A3 =: P4+1 end end thread or A4 =: P2-1 [] A4 =: P2+1 end end {FD.distribute ff Vars} end end HousesSol = [[5 3 4 2 1 4 5 1 2 3 4 1 5 3 2 3 1 4 2 5 5 1 2 4 3] [5 3 4 2 1 4 5 1 2 3 4 1 5 3 2 3 5 4 2 1 5 1 2 4 3] [5 4 3 2 1 4 5 1 2 3 3 1 5 4 2 4 1 3 2 5 5 1 2 4 3] [5 4 3 2 1 4 5 1 2 3 3 1 5 4 2 4 1 5 2 3 5 1 2 4 3] [5 4 3 2 1 4 5 1 2 3 3 1 5 4 2 4 3 5 2 1 5 1 2 4 3] [5 4 3 2 1 4 5 1 2 3 3 1 5 4 2 4 5 3 2 1 5 1 2 4 3]] Return= fd([houses([ all(equal(fun {$} {Search.base.all Houses} end HousesSol) keys: [fd]) all_entailed(entailed(proc {$} {Search.base.all Houses _} end) keys: [fd entailed]) ]) ]) end
0
0.704745
1
0.704745
game-dev
MEDIA
0.197323
game-dev
0.830795
1
0.830795
luciensadi/AwakeMUD
8,732
src/ritualcast.cpp
#include "awake.hpp" #include "structs.hpp" #include "constants.hpp" #include "utils.hpp" #include "comm.hpp" #include "handler.hpp" #include "db.hpp" #include "newmagic.hpp" #include "newhouse.hpp" extern void raw_cast_detection_spell(struct char_data *ch, struct char_data *vict, int spell, int force, struct char_data *mob, int successes); extern void raw_cast_health_spell(struct char_data *ch, struct char_data *vict, int spell, int sub, int force, struct char_data *mob, int ritual_successes); extern void raw_cast_illusion_spell(struct char_data *ch, struct char_data *vict, int spell, int force, struct char_data *mob, int ritual_successes); extern void raw_cast_manipulation_spell(struct char_data *ch, struct char_data *vict, int spell, int force, struct char_data *mob, int ritual_successes, int basedamage); bool spell_is_valid_ritual_spell(int spell) { switch (spell) { case SPELL_COMBATSENSE: case SPELL_NIGHTVISION: case SPELL_INFRAVISION: case SPELL_DETOX: case SPELL_STABILIZE: case SPELL_RESISTPAIN: case SPELL_HEALTHYGLOW: case SPELL_TREAT: case SPELL_HEAL: case SPELL_INCREF1: case SPELL_INCREF2: case SPELL_INCREF3: case SPELL_INCREA: case SPELL_DECATTR: case SPELL_DECCYATTR: case SPELL_INCATTR: case SPELL_INCCYATTR: case SPELL_INVIS: case SPELL_IMP_INVIS: case SPELL_STEALTH: case SPELL_ARMOR: case SPELL_FLAME_AURA: case SPELL_LEVITATE: // You may ritual-cast these spells. return TRUE; } return FALSE; } // Helper function for ritual spells. Returns TRUE if you can have this spell cast on you, FALSE otherwise. bool vict_meets_spell_preconditions(struct char_data *vict, int spell, int subtype) { // Check for spell duplication. for (struct sustain_data *sus = GET_SUSTAINED(vict); sus; sus = sus->next) { if (!sus->is_caster_record && sus->spell == spell && sus->subtype == subtype) { // Already affected. return FALSE; } } return TRUE; } void set_up_ritualcast(struct char_data *ch, struct room_data *in_room, struct spell_data *spell, int force) { FAILURE_CASE(!in_room, "You can't quite figure out where to put things...\r\n"); FAILURE_CASE(IS_WORKING(ch), "You're too busy to cast a ritual spell.\r\n"); FAILURE_CASE(CH_IN_COMBAT(ch), "Ritual cast while fighting?? You ARE mad!\r\n"); FAILURE_CASE(IS_PROJECT(ch), "You can't manipulate physical objects in this form, so setting up a ritual space will be hard.\r\n"); FAILURE_CASE(!GET_APARTMENT(in_room), "Ritual casting requires an undisturbed place with room to move around-- you'll need to be in an apartment.\r\n"); FAILURE_CASE(GET_ROOM_VNUM(in_room) >= 6900 && GET_ROOM_VNUM(in_room) <= 6999, "You can't do that in NERPcorpolis."); FAILURE_CASE(ch->in_veh, "Ritual casting requires more space to move around-- you'll need to leave your vehicle.\r\n"); FAILURE_CASE(!spell_is_valid_ritual_spell(spell->type), "That spell isn't eligible for ritual casting. You can only ritual-cast buffs.\r\n"); // Only one ritual at a time. for (struct obj_data *obj = in_room->contents; obj; obj = obj->next_content) { FAILURE_CASE(GET_OBJ_VNUM(obj) == OBJ_RITUAL_SPELL_COMPONENTS, "There's already a ritual in progress here. Either wait for it to finish, or ##^WDESTROY^n the components so you can begin your own.\r\n"); } // Find the target. struct char_data *vict = get_char_room_vis(ch, buf1); if (!check_spell_victim(ch, vict, spell->type, buf1)) { return; } FAILURE_CASE(IS_NPC(vict), "You can only cast ritual spells on player characters."); FAILURE_CASE(ch != vict, "You can only cast ritual spells on yourself."); FAILURE_CASE(!vict_meets_spell_preconditions(vict, spell->type, spell->subtype), "You can't cast that spell on them right now."); // Charge them. int cost = RITUAL_SPELL_COMPONENT_COST * force * MAX(1, spells[spell->type].drainpower); int time_in_ticks = (RITUAL_SPELL_BASE_TIME * force * MAX(1, spells[spell->type].drainpower)) / (GET_SKILL(ch, SKILL_SORCERY) + MIN(GET_SKILL(ch, SKILL_SORCERY), GET_CASTING(ch))); if (GET_NUYEN(ch) < cost) { send_to_char(ch, "You need at least %d nuyen on hand to pay for the ritual components.\r\n", cost); return; } lose_nuyen(ch, cost, NUYEN_OUTFLOW_RITUAL_CASTING); // Load the ritual casting tracking object. AFF_FLAGS(ch).SetBit(AFF_RITUALCAST); struct obj_data *components = read_object(OBJ_RITUAL_SPELL_COMPONENTS, VIRTUAL, OBJ_LOAD_REASON_MAGIC_BUILD); GET_RITUAL_COMPONENT_CASTER(components) = GET_IDNUM(ch); GET_RITUAL_COMPONENT_SPELL(components) = spell->type; GET_RITUAL_COMPONENT_SUBTYPE(components) = spell->subtype; GET_RITUAL_COMPONENT_FORCE(components) = force; GET_RITUAL_COMPONENT_TARGET(components) = GET_IDNUM(vict); GET_RITUAL_COMPONENT_SPENT_NUYEN(components) = cost; GET_RITUAL_TICKS_AT_START(components) = GET_RITUAL_TICKS_LEFT(components) = time_in_ticks; char restring_buf[500]; snprintf(restring_buf, sizeof(restring_buf), "a ritual invocation of %s", get_spell_name(spell->type, spell->subtype)); components->restring = str_dup(restring_buf); GET_BUILDING(ch) = components; obj_to_room(components, ch->in_room); send_to_char(ch, "You set up candles, incense, and other ritual components, then settle in to cast %s.\r\n", get_spell_name(spell->type, spell->subtype)); act("$n sets up candles, incense, and other ritual components, then settles in to cast a spell.", FALSE, ch, 0, 0, TO_ROOM); } bool handle_ritualcast_tick(struct char_data *ch, struct obj_data *components) { if (--GET_RITUAL_TICKS_LEFT(components) <= 0) { struct char_data *vict = NULL; // Require that the target is present. for (vict = ch->in_room->people; vict; vict = vict->next_in_room) { if (GET_IDNUM(vict) == GET_RITUAL_COMPONENT_TARGET(components)) break; } if (!vict) { send_to_char(ch, "Unable to find their target, the spiraling energies of your ritual scatter away.\r\n"); act("$n's ritual spell flares, then dissipates into motes of ineffectual light.", FALSE, ch, 0, 0, TO_ROOM); // Don't return-- we have cleanup work to do below. } else if (!vict_meets_spell_preconditions(vict, GET_RITUAL_COMPONENT_SPELL(components), GET_RITUAL_COMPONENT_SUBTYPE(components))) { send_to_char(ch, "There's a vibrant clash of energies as your ritual fails to take hold.\r\n"); act("$n's ritual spell rebounds off of $N in a vibrant clash of energies.", FALSE, ch, 0, vict, TO_ROOM); // Don't return-- we have cleanup work to do below. } else { // Message completion. send_to_char(ch, "A rush of magic runs through you with the completion of your ritual.\r\n"); // cast_x_spell() w/ predetermined successes int spell = GET_RITUAL_COMPONENT_SPELL(components); int force = GET_RITUAL_COMPONENT_FORCE(components); int subtype = GET_RITUAL_COMPONENT_SUBTYPE(components); int cost = GET_RITUAL_COMPONENT_SPENT_NUYEN(components); int successes = MAX(1, get_max_usable_spell_successes(spell, force) * RITUAL_SPELL_MAX_SUCCESS_MULTIPLIER); switch (spells[spell].category) { case COMBAT: mudlog_vfprintf(ch, LOG_SYSLOG, "SYSERR: Got COMBAT spell %d while ritualcasting!", spell); break; case DETECTION: raw_cast_detection_spell(ch, vict, spell, force, NULL, successes); break; case HEALTH: raw_cast_health_spell(ch, vict, spell, subtype, force, NULL, successes); break; case ILLUSION: raw_cast_illusion_spell(ch, vict, spell, force, NULL, successes); break; case MANIPULATION: raw_cast_manipulation_spell(ch, vict, spell, force, NULL, successes, 0); break; } // Iterate over their spells to find the new one and apply the cost to the record. for (struct sustain_data *sust = GET_SUSTAINED(ch); sust; sust = sust->next) { if (sust->is_caster_record && sust->spell == spell && sust->force == force && sust->subtype == subtype && sust->success == successes && !sust->ritual_cast_cost) { sust->ritual_cast_cost = cost; break; } } mudlog_vfprintf(ch, LOG_GRIDLOG, "%s ritualcast %s (force %d) for %d nuyen.", GET_CHAR_NAME(ch), spells[spell].name, force, cost); } // Destroy the components. extract_obj(components); components = NULL; ch->char_specials.timer = 0; STOP_WORKING(ch); return TRUE; } return FALSE; }
0
0.887873
1
0.887873
game-dev
MEDIA
0.896624
game-dev
0.956943
1
0.956943
Robosturm/Commander_Wars
3,040
menue/wikimenu.cpp
#include "menue/wikimenu.h" #include "menue/mainwindow.h" #include "resource_management/backgroundmanager.h" #include "resource_management/objectmanager.h" #include "coreengine/mainapp.h" #include "coreengine/gameconsole.h" #include "coreengine/audiomanager.h" #include "3rd_party/oxygine-framework/oxygine/actor/Stage.h" Wikimenu::Wikimenu() : Basemenu() { #ifdef GRAPHICSUPPORT setObjectName("Wikimenu"); #endif Mainapp* pApp = Mainapp::getInstance(); pApp->pauseRendering(); Interpreter::setCppOwnerShip(this); CONSOLE_PRINT("Entering Wiki Menue", GameConsole::eDEBUG); BackgroundManager* pBackgroundManager = BackgroundManager::getInstance(); // load background oxygine::spSprite sprite = MemoryManagement::create<oxygine::Sprite>(); addChild(sprite); oxygine::ResAnim* pBackground = pBackgroundManager->getResAnim("wikimenu"); if (pBackground != nullptr && pBackground->getWidth() > 0 && pBackground->getHeight() > 0) { sprite->setResAnim(pBackground); // background should be last to draw sprite->setPriority(static_cast<qint32>(Mainapp::ZOrder::Background)); sprite->setScaleX(static_cast<float>(oxygine::Stage::getStage()->getWidth()) / static_cast<float>(pBackground->getWidth())); sprite->setScaleY(static_cast<float>(oxygine::Stage::getStage()->getHeight()) / static_cast<float>(pBackground->getHeight())); } pApp->getAudioManager()->clearPlayList(); pApp->getAudioManager()->loadFolder("resources/music/hauptmenue"); pApp->getAudioManager()->playRandom(); oxygine::spButton pButtonExit = ObjectManager::createButton(tr("Exit")); addChild(pButtonExit); pButtonExit->setPosition(oxygine::Stage::getStage()->getWidth() / 2.0f - pButtonExit->getScaledWidth() / 2.0f, oxygine::Stage::getStage()->getHeight() - pButtonExit->getScaledHeight() - 10); pButtonExit->addEventListener(oxygine::TouchEvent::CLICK, [this](oxygine::Event * )->void { emit sigExitMenue(); }); m_pWikiView = MemoryManagement::create<WikiView>(oxygine::Stage::getStage()->getWidth(), oxygine::Stage::getStage()->getHeight()); addChild(m_pWikiView); connect(this, &Wikimenu::sigExitMenue, this, &Wikimenu::exitMenue, Qt::QueuedConnection); pApp->continueRendering(); } void Wikimenu::onEnter() { Interpreter* pInterpreter = Interpreter::getInstance(); QString object = "Init"; QString func = "wikiMenu"; if (pInterpreter->exists(object, func)) { CONSOLE_PRINT("Executing:" + object + "." + func, GameConsole::eDEBUG); QJSValueList args({pInterpreter->newQObject(this)}); pInterpreter->doFunction(object, func, args); } } void Wikimenu::exitMenue() { CONSOLE_PRINT("Leaving Wiki Menue", GameConsole::eDEBUG); m_onEnterTimer.stop(); auto window = MemoryManagement::create<Mainwindow>("ui/menu/mainmenu.xml"); oxygine::Stage::getStage()->addChild(window); oxygine::Actor::detach(); }
0
0.929967
1
0.929967
game-dev
MEDIA
0.96764
game-dev
0.918845
1
0.918845
grinnellidesigns/f-22a
30,902
Cockpit/Scripts/MFD_CENTER/fuel_page.lua
--[[ Grinnelli Designs F-22A Raptor Copyright (C) 2024, Joseph Grinnelli This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses. --]] dofile(LockOn_Options.script_path.."MFD_CENTER/definitions.lua") dofile(LockOn_Options.script_path.."fonts.lua") dofile(LockOn_Options.script_path.."materials.lua") SetScale(FOV) local function vertices(object, height, half_or_double) local width = height if half_or_double == true then -- width = 0.98 end if half_or_double == false then width = 0.12 --change this end local half_width = width / 2 local half_height = height / 2 local x_positive = half_width local x_negative = half_width * -1.0 local y_positive = half_height local y_negative = half_height * -1.0 object.vertices = { {x_negative, y_positive}, {x_positive, y_positive}, {x_positive, y_negative}, {x_negative, y_negative} } object.indices = {0, 1, 2, 2, 3, 0} object.tex_coords = { {0, 0}, {1, 0}, {1, 1}, {0, 1} } end local IndicationTexturesPath = LockOn_Options.script_path.."../IndicationTextures/"--I dont think this is correct might have to add scripts. local BlackColor = {0, 0, 0, 255}--RGBA local WhiteColor = {255, 255, 255, 255}--RGBA local MainColor = {255, 255, 255, 255}--RGBA local GreenColor = {0, 255, 0, 255}--RGBA local YellowColor = {255, 255, 0, 255}--RGBA local OrangeColor = {255, 102, 0, 255}--RGBA local RedColor = {255, 0, 0, 255}--RGBA local TealColor = {0, 255, 255, 255}--RGBA local ScreenColor = {3, 3, 12, 255}--RGBA DO NOT TOUCH 3-3-12-255 is good for on screen -------------------------------------------------------------------------------------------------------------------------------------------- local FUEL_MASK = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_mask.dds", BlackColor)--SYSTEM TEST local FUEL_BOX = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_box.dds", BlackColor)--SYSTEM TEST local FUEL_IND = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_ind.dds", WhiteColor)--SYSTEM TEST local FUEL_PAGE = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_frame.dds", GreenColor)--SYSTEM TEST local FUEL_BOX_BL = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_box.dds", ScreenColor)--SYSTEM TEST local FUEL_MASK_BL = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_mask.dds", ScreenColor)--SYSTEM TEST local MASK_BOX = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/mask_box.dds", ScreenColor)--SYSTEM TEST --local TOP_MASK = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_mask_top.dds", ScreenColor)--SYSTEM TEST local TEAL = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/mask_box.dds", TealColor)--SYSTEM TEST local FUEL_IQT = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_iqt.dds", TealColor)--SYSTEM TEST local FUEL_TQT = MakeMaterial(LockOn_Options.script_path.."../Scripts/IndicationTextures/fuel_tqt.dds", TealColor)--SYSTEM TEST -------------------------------------------------------------------------------------------------------------------------------------------- local ClippingPlaneSize = 1.1 --Clipping Masks local ClippingWidth = 1.1 --Clipping Masks local PFD_MASK_BASE1 = MakeMaterial(nil,{255,0,0,255})--Clipping Masks local PFD_MASK_BASE2 = MakeMaterial(nil,{0,255,0,255})--Clipping Masks --Clipping Masks local total_field_of_view = CreateElement "ceMeshPoly" total_field_of_view.name = "total_field_of_view" total_field_of_view.primitivetype = "triangles" total_field_of_view.vertices = { {-1 * ClippingWidth,-1 * ClippingPlaneSize}, {1 * ClippingWidth,-1 * ClippingPlaneSize}, {1 * ClippingWidth,1 * ClippingPlaneSize}, {-1 * ClippingWidth,1 * ClippingPlaneSize}, } total_field_of_view.material = PFD_MASK_BASE1 total_field_of_view.indices = {0,1,2,2,3,0} total_field_of_view.init_pos = {0, 0, 0} total_field_of_view.init_rot = { 0, 0, 0} -- degree NOT rad total_field_of_view.h_clip_relation = h_clip_relations.REWRITE_LEVEL total_field_of_view.level = 1 total_field_of_view.collimated = false total_field_of_view.isvisible = false Add(total_field_of_view) --Clipping Masks local clipPoly = CreateElement "ceMeshPoly" clipPoly.name = "clipPoly-1" clipPoly.primitivetype = "triangles" clipPoly.init_pos = {0, 0, 0} clipPoly.init_rot = { 0, 0 , 0} -- degree NOT rad clipPoly.vertices = { {-1 * ClippingWidth,-1 * ClippingPlaneSize}, {1 * ClippingWidth,-1 * ClippingPlaneSize}, {1 * ClippingWidth,1 * ClippingPlaneSize}, {-1 * ClippingWidth,1 * ClippingPlaneSize}, } clipPoly.indices = {0,1,2,2,3,0} clipPoly.material = PFD_MASK_BASE2 clipPoly.h_clip_relation = h_clip_relations.INCREASE_IF_LEVEL clipPoly.level = 1 clipPoly.collimated = false clipPoly.isvisible = false Add(clipPoly) ------------------------------------------------------------------------------------------------CLIPPING-END---------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------BASE BACKLIGHT BGROUND = CreateElement "ceTexPoly" BGROUND.name = "BG" BGROUND.material = MASK_BOX BGROUND.change_opacity = false BGROUND.collimated = false BGROUND.isvisible = true BGROUND.init_pos = {0, 0, 0} --L-R,U-D,F-B BGROUND.init_rot = {0, 0, 0} BGROUND.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs BGROUND.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1}}--MENU PAGE = 1 BGROUND.level = 2 BGROUND.h_clip_relation = h_clip_relations.COMPARE vertices(BGROUND,2) Add(BGROUND) -----------------------------------------------------------------------------------------------TEAL FUEL QUANT------------------------------------------------------------------------------------------------ FUELQTY = CreateElement "ceTexPoly" FUELQTY.name = "BG" FUELQTY.material = FUEL_IQT FUELQTY.change_opacity = false FUELQTY.collimated = false FUELQTY.isvisible = true FUELQTY.init_pos = {0, -1.359, 0} --L-R,U-D,F-B FUELQTY.init_rot = {0, 0, 0} --FUELQTY.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUELQTY.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE","FUEL"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUELQTY.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1}, {"move_up_down_using_parameter",2,0.00000780,0} --{"move_up_down_using_parameter",2,0.00000601,0} } FUELQTY.level = 2 FUELQTY.h_clip_relation = h_clip_relations.COMPARE vertices(FUELQTY,2) Add(FUELQTY) -----------------------------------------------------------------------------------------------TEAL FUEL QUANT2------------------------------------------------------------------------------------------------ FUELQTY2 = CreateElement "ceTexPoly" FUELQTY2.name = "BG" FUELQTY2.material = FUEL_IQT FUELQTY2.change_opacity = false FUELQTY2.collimated = false FUELQTY2.isvisible = true FUELQTY2.init_pos = {0, -2.715, 0} --L-R,U-D,F-B {0, -2.7166, 0} --L-R,U-D,F-B FUELQTY2.init_rot = {0, 0, 0} --FUELQTY.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUELQTY2.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE","FUEL"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUELQTY2.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1}, {"move_up_down_using_parameter",2,0.00000780,0} } FUELQTY2.level = 2 FUELQTY2.h_clip_relation = h_clip_relations.COMPARE vertices(FUELQTY2,2) Add(FUELQTY2) -----------------------------------------------------------------------------------------------TEAL-FUEL-TANK-QUANT------------------------------------------------------------------------------------------------ FUELQTY_TANK = CreateElement "ceTexPoly" FUELQTY_TANK.name = "BG" FUELQTY_TANK.material = FUEL_TQT FUELQTY_TANK.change_opacity = false FUELQTY_TANK.collimated = false FUELQTY_TANK.isvisible = true FUELQTY_TANK.init_pos = {0, -0.475, 0} --L-R,U-D,F-B FUELQTY_TANK.init_rot = {0, 0, 0} --FUELQTY_TANK.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUELQTY_TANK.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE","FUELT"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUELQTY_TANK.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1}, {"move_up_down_using_parameter",2,0.00000445,0}--{"move_up_down_using_parameter",2,0.00000445,0} was 870 } FUELQTY_TANK.level = 2 FUELQTY_TANK.h_clip_relation = h_clip_relations.COMPARE vertices(FUELQTY_TANK,2) Add(FUELQTY_TANK) --------------------------------------------------------------------------------------------------ALL-BLACK-MASK-NO-OPACITY----------------------- FUEL_BLK = CreateElement "ceTexPoly" FUEL_BLK.name = "BG" FUEL_BLK.material = FUEL_MASK FUEL_BLK.change_opacity = false FUEL_BLK.collimated = false FUEL_BLK.isvisible = true FUEL_BLK.init_pos = {0, 0, 0} --L-R,U-D,F-B FUEL_BLK.init_rot = {0, 0, 0} FUEL_BLK.element_params = {"CMFD_FUEL_PAGE","MAIN_POWER"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUEL_BLK.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1}}--MENU PAGE = 1 FUEL_BLK.level = 2 FUEL_BLK.h_clip_relation = h_clip_relations.COMPARE vertices(FUEL_BLK,2) Add(FUEL_BLK) --------------------------------------------------------------------------------------ALL-BLACK-MASK-WITH-BACKLIGHT-MATERIAL BGROUND1 = CreateElement "ceTexPoly" BGROUND1.name = "BG" BGROUND1.material = FUEL_MASK_BL BGROUND1.change_opacity = false BGROUND1.collimated = false BGROUND1.isvisible = true BGROUND1.init_pos = {0, 0, 0} --L-R,U-D,F-B BGROUND1.init_rot = {0, 0, 0} BGROUND1.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} BGROUND1.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1}}--MENU PAGE = 1 BGROUND1.level = 2 BGROUND1.h_clip_relation = h_clip_relations.COMPARE vertices(BGROUND1,2) Add(BGROUND1) -------------------------------------------------------------------------FUEL PAGE GREEN LINES FUELFRAME = CreateElement "ceTexPoly" FUELFRAME.name = "BG" FUELFRAME.material = FUEL_PAGE FUELFRAME.change_opacity = false FUELFRAME.collimated = false FUELFRAME.isvisible = true FUELFRAME.init_pos = {0, 0, 0} --L-R,U-D,F-B FUELFRAME.init_rot = {0, 0, 0} FUELFRAME.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUELFRAME.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1}}--MENU PAGE = 1 FUELFRAME.level = 2 FUELFRAME.h_clip_relation = h_clip_relations.COMPARE vertices(FUELFRAME,2) Add(FUELFRAME) --------------------------------------------------------------------------------------------------ALL-BLACK-MASK-NO-OPACITY----------------------- FUEL_BX = CreateElement "ceTexPoly" FUEL_BX.name = "BG" FUEL_BX.material = FUEL_BOX FUEL_BX.change_opacity = false FUEL_BX.collimated = false FUEL_BX.isvisible = true FUEL_BX.init_pos = {0, 0, 0} --L-R,U-D,F-B FUEL_BX.init_rot = {0, 0, 0} FUEL_BX.element_params = {"CMFD_FUEL_PAGE","MAIN_POWER"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs FUEL_BX.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1}}--MENU PAGE = 1 FUEL_BX.level = 2 FUEL_BX.h_clip_relation = h_clip_relations.COMPARE vertices(FUEL_BX,2) Add(FUEL_BX) --------------------------------------------------------------------------------------------------ALL-BLACK-MASK-NO-OPACITY----------------------- FUEL_BX_BL = CreateElement "ceTexPoly" FUEL_BX_BL.name = "BG" FUEL_BX_BL.material = FUEL_BOX_BL FUEL_BX_BL.change_opacity = false FUEL_BX_BL.collimated = false FUEL_BX_BL.isvisible = true FUEL_BX_BL.init_pos = {0, 0, 0} --L-R,U-D,F-B FUEL_BX_BL.init_rot = {0, 0, 0} FUEL_BX_BL.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} FUEL_BX_BL.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1}}--MENU PAGE = 1 FUEL_BX_BL.level = 2 FUEL_BX_BL.h_clip_relation = h_clip_relations.COMPARE vertices(FUEL_BX_BL,2) Add(FUEL_BX_BL) --------------------------------------------------------------------------------------------------FUEL-PAGE-TINY-NUMBERS TINYSHIT = CreateElement "ceTexPoly" TINYSHIT.name = "BG" TINYSHIT.material = FUEL_IND TINYSHIT.change_opacity = false TINYSHIT.collimated = false TINYSHIT.isvisible = true TINYSHIT.init_pos = {0, 0, 0} --L-R,U-D,F-B TINYSHIT.init_rot = {0, 0, 0} TINYSHIT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"}--this may not be bneeded check when more pages done for backlight on page 7 RWR fc3 bs TINYSHIT.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1}}--MENU PAGE = 1 TINYSHIT.level = 2 TINYSHIT.h_clip_relation = h_clip_relations.COMPARE vertices(TINYSHIT,2) Add(TINYSHIT) --------------------------------------------------------------------------------------------------------------------INTERNAL TEXT --INT TEXT INTERNAL_TEXT = CreateElement "ceStringPoly" INTERNAL_TEXT.name = "menu" INTERNAL_TEXT.material = UFD_GRN INTERNAL_TEXT.value = "TOTAL:" INTERNAL_TEXT.stringdefs = {0.004, 0.004, 0.0004, 0.001} INTERNAL_TEXT.alignment = "LeftCenter" INTERNAL_TEXT.formats = {"%s"} INTERNAL_TEXT.h_clip_relation = h_clip_relations.COMPARE INTERNAL_TEXT.level = 2 INTERNAL_TEXT.init_pos = {0.40, 0.65, 0} INTERNAL_TEXT.init_rot = {0, 0, 0} INTERNAL_TEXT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} INTERNAL_TEXT.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1},--ENGINE PAGE = 0 } Add(INTERNAL_TEXT) --------------------------------------------------------------------------------------------------------------------INTERNAL NUMBER INTERNAL_NUMBER = CreateElement "ceStringPoly" INTERNAL_NUMBER.name = "INT NUM" INTERNAL_NUMBER.material = UFD_GRN INTERNAL_NUMBER.init_pos = {0.80, 0.65, 0} --L-R,U-D,F-B INTERNAL_NUMBER.alignment = "RightCenter" INTERNAL_NUMBER.stringdefs = {0.004, 0.004, 0, 0.0} --either 004 or 005 INTERNAL_NUMBER.additive_alpha = true INTERNAL_NUMBER.collimated = false INTERNAL_NUMBER.isdraw = true INTERNAL_NUMBER.use_mipfilter = true INTERNAL_NUMBER.h_clip_relation = h_clip_relations.COMPARE INTERNAL_NUMBER.level = 2 INTERNAL_NUMBER.element_params = {"MFD_OPACITY","FUEL","CMFD_FUEL_PAGE"} INTERNAL_NUMBER.formats = {"%.0f"}--= {"%02.0f"} INTERNAL_NUMBER.controllers = {{"opacity_using_parameter",0},{"text_using_parameter",1,0},{"parameter_in_range",2,0.9,1.1}} Add(INTERNAL_NUMBER) --------------------------------------------------------------------------------------------------------------------TANK TEXT --TANK TEXT TANK_TEXT = CreateElement "ceStringPoly" TANK_TEXT.name = "menu" TANK_TEXT.material = UFD_FONT TANK_TEXT.value = "TANKS:" TANK_TEXT.stringdefs = {0.004, 0.004, 0.0004, 0.001} TANK_TEXT.alignment = "LeftCenter" TANK_TEXT.formats = {"%s"} TANK_TEXT.h_clip_relation = h_clip_relations.COMPARE TANK_TEXT.level = 2 TANK_TEXT.init_pos = {0.40, 0.58, 0} TANK_TEXT.init_rot = {0, 0, 0} TANK_TEXT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} TANK_TEXT.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1},--ENGINE PAGE = 0 } Add(TANK_TEXT) --------------------------------------------------------------------------------------------------------------------TANK NUMBER TANK_NUMBER = CreateElement "ceStringPoly" TANK_NUMBER.name = "INT NUM" TANK_NUMBER.material = UFD_FONT TANK_NUMBER.init_pos = {0.80, 0.58, 0} --L-R,U-D,F-B TANK_NUMBER.alignment = "RightCenter" TANK_NUMBER.stringdefs = {0.004, 0.004, 0, 0.0} --either 004 or 005 TANK_NUMBER.additive_alpha = true TANK_NUMBER.collimated = false TANK_NUMBER.isdraw = true TANK_NUMBER.use_mipfilter = true TANK_NUMBER.h_clip_relation = h_clip_relations.COMPARE TANK_NUMBER.level = 2 TANK_NUMBER.element_params = {"MFD_OPACITY","FUELTANK","CMFD_FUEL_PAGE"} TANK_NUMBER.formats = {"%.0f"}--= {"%02.0f"} TANK_NUMBER.controllers = {{"opacity_using_parameter",0},{"text_using_parameter",1,0},{"parameter_in_range",2,0.9,1.1}} Add(TANK_NUMBER) --------------------------------------------------------------------------------------------------------------------LEFT FF TEXT L_EFF_TEXT = CreateElement "ceStringPoly" L_EFF_TEXT.name = "menu" L_EFF_TEXT.material = UFD_GRN L_EFF_TEXT.value = "L EFF:" L_EFF_TEXT.stringdefs = {0.004, 0.004, 0.0004, 0.001} L_EFF_TEXT.alignment = "LeftCenter" L_EFF_TEXT.formats = {"%s"} L_EFF_TEXT.h_clip_relation = h_clip_relations.COMPARE L_EFF_TEXT.level = 2 L_EFF_TEXT.init_pos = {-0.85, -0.75, 0} L_EFF_TEXT.init_rot = {0, 0, 0} L_EFF_TEXT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} L_EFF_TEXT.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1},--ENGINE PAGE = 0 } Add(L_EFF_TEXT) --------------------------------------------------------------------------------------------------------------------LEFT EGT TEXT L_EGT_TEXT = CreateElement "ceStringPoly" L_EGT_TEXT.name = "menu" L_EGT_TEXT.material = UFD_GRN L_EGT_TEXT.value = "L EGT:" L_EGT_TEXT.stringdefs = {0.004, 0.004, 0.0004, 0.001} L_EGT_TEXT.alignment = "LeftCenter" L_EGT_TEXT.formats = {"%s"} L_EGT_TEXT.h_clip_relation = h_clip_relations.COMPARE L_EGT_TEXT.level = 2 L_EGT_TEXT.init_pos = {-0.85, -0.82, 0} L_EGT_TEXT.init_rot = {0, 0, 0} L_EGT_TEXT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} L_EGT_TEXT.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1},--ENGINE PAGE = 0 } Add(L_EGT_TEXT) --------------------------------------------------------------------------------------------------------------------LEFT FF NUMBER L_EFF_NUMBER = CreateElement "ceStringPoly" L_EFF_NUMBER.name = "INT NUM" L_EFF_NUMBER.material = UFD_GRN L_EFF_NUMBER.init_pos = {-0.45, -0.75, 0} --L-R,U-D,F-B L_EFF_NUMBER.alignment = "RightCenter" L_EFF_NUMBER.stringdefs = {0.004, 0.004, 0, 0.0} --either 004 or 005 L_EFF_NUMBER.additive_alpha = true L_EFF_NUMBER.collimated = false L_EFF_NUMBER.isdraw = true L_EFF_NUMBER.use_mipfilter = true L_EFF_NUMBER.h_clip_relation = h_clip_relations.COMPARE L_EFF_NUMBER.level = 2 L_EFF_NUMBER.element_params = {"MFD_OPACITY","L_FF_VALUE","CMFD_FUEL_PAGE"} L_EFF_NUMBER.formats = {"%.0f"}--= {"%02.0f"} L_EFF_NUMBER.controllers = {{"opacity_using_parameter",0},{"text_using_parameter",1,0},{"parameter_in_range",2,0.9,1.1}} Add(L_EFF_NUMBER) --------------------------------------------------------------------------------------------------------------------LEFT FF NUMBER L_EGT_NUMBER = CreateElement "ceStringPoly" L_EGT_NUMBER.name = "INT NUM" L_EGT_NUMBER.material = UFD_GRN L_EGT_NUMBER.init_pos = {-0.45, -0.82, 0} --L-R,U-D,F-B L_EGT_NUMBER.alignment = "RightCenter" L_EGT_NUMBER.stringdefs = {0.004, 0.004, 0, 0.0} --either 004 or 005 L_EGT_NUMBER.additive_alpha = true L_EGT_NUMBER.collimated = false L_EGT_NUMBER.isdraw = true L_EGT_NUMBER.use_mipfilter = true L_EGT_NUMBER.h_clip_relation = h_clip_relations.COMPARE L_EGT_NUMBER.level = 2 L_EGT_NUMBER.element_params = {"MFD_OPACITY","EGT_L","CMFD_FUEL_PAGE"} L_EGT_NUMBER.formats = {"%.0f"}--= {"%02.0f"} L_EGT_NUMBER.controllers = {{"opacity_using_parameter",0},{"text_using_parameter",1,0},{"parameter_in_range",2,0.9,1.1}} Add(L_EGT_NUMBER) --------------------------------------------------------------------------------------------------------------------LEFT FF TEXT R_EFF_TEXT = CreateElement "ceStringPoly" R_EFF_TEXT.name = "menu" R_EFF_TEXT.material = UFD_GRN R_EFF_TEXT.value = ":R EFF" R_EFF_TEXT.stringdefs = {0.004, 0.004, 0.0004, 0.001} R_EFF_TEXT.alignment = "RightCenter" R_EFF_TEXT.formats = {"%s"} R_EFF_TEXT.h_clip_relation = h_clip_relations.COMPARE R_EFF_TEXT.level = 2 R_EFF_TEXT.init_pos = {0.85, -0.75, 0} R_EFF_TEXT.init_rot = {0, 0, 0} R_EFF_TEXT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} R_EFF_TEXT.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1},--ENGINE PAGE = 0 } Add(R_EFF_TEXT) --------------------------------------------------------------------------------------------------------------------LEFT EGT TEXT R_EGT_TEXT = CreateElement "ceStringPoly" R_EGT_TEXT.name = "menu" R_EGT_TEXT.material = UFD_GRN R_EGT_TEXT.value = ":R EGT" R_EGT_TEXT.stringdefs = {0.004, 0.004, 0.0004, 0.001} R_EGT_TEXT.alignment = "RightCenter" R_EGT_TEXT.formats = {"%s"} R_EGT_TEXT.h_clip_relation = h_clip_relations.COMPARE R_EGT_TEXT.level = 2 R_EGT_TEXT.init_pos = {0.85, -0.82, 0} R_EGT_TEXT.init_rot = {0, 0, 0} R_EGT_TEXT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} R_EGT_TEXT.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1},--ENGINE PAGE = 0 } Add(R_EGT_TEXT) --------------------------------------------------------------------------------------------------------------------LEFT FF NUMBER R_EFF_NUMBER = CreateElement "ceStringPoly" R_EFF_NUMBER.name = "INT NUM" R_EFF_NUMBER.material = UFD_GRN R_EFF_NUMBER.init_pos = {0.45, -0.75, 0} --L-R,U-D,F-B R_EFF_NUMBER.alignment = "LeftCenter" R_EFF_NUMBER.stringdefs = {0.004, 0.004, 0, 0.0} --either 004 or 005 R_EFF_NUMBER.additive_alpha = true R_EFF_NUMBER.collimated = false R_EFF_NUMBER.isdraw = true R_EFF_NUMBER.use_mipfilter = true R_EFF_NUMBER.h_clip_relation = h_clip_relations.COMPARE R_EFF_NUMBER.level = 2 R_EFF_NUMBER.element_params = {"MFD_OPACITY","R_FF_VALUE","CMFD_FUEL_PAGE"} R_EFF_NUMBER.formats = {"%.0f"}--= {"%02.0f"} R_EFF_NUMBER.controllers = {{"opacity_using_parameter",0},{"text_using_parameter",1,0},{"parameter_in_range",2,0.9,1.1}} Add(R_EFF_NUMBER) --------------------------------------------------------------------------------------------------------------------LEFT FF NUMBER R_EGT_NUMBER = CreateElement "ceStringPoly" R_EGT_NUMBER.name = "INT NUM" R_EGT_NUMBER.material = UFD_GRN R_EGT_NUMBER.init_pos = {0.45, -0.82, 0} --L-R,U-D,F-B R_EGT_NUMBER.alignment = "LeftCenter" R_EGT_NUMBER.stringdefs = {0.004, 0.004, 0, 0.0} --either 004 or 005 R_EGT_NUMBER.additive_alpha = true R_EGT_NUMBER.collimated = false R_EGT_NUMBER.isdraw = true R_EGT_NUMBER.use_mipfilter = true R_EGT_NUMBER.h_clip_relation = h_clip_relations.COMPARE R_EGT_NUMBER.level = 2 R_EGT_NUMBER.element_params = {"MFD_OPACITY","EGT_R","CMFD_FUEL_PAGE"} R_EGT_NUMBER.formats = {"%.0f"}--= {"%02.0f"} R_EGT_NUMBER.controllers = {{"opacity_using_parameter",0},{"text_using_parameter",1,0},{"parameter_in_range",2,0.9,1.1}} Add(R_EGT_NUMBER) --------------------------------------------------------------------------------------------------------------------MENU-BUTTON --MENU TEXT MENU_CHK_TEXT = CreateElement "ceStringPoly" MENU_CHK_TEXT.name = "menu" MENU_CHK_TEXT.material = UFD_FONT MENU_CHK_TEXT.value = "MENU" MENU_CHK_TEXT.stringdefs = {0.0050, 0.0050, 0.0004, 0.001} MENU_CHK_TEXT.alignment = "CenterCenter" MENU_CHK_TEXT.formats = {"%s"} MENU_CHK_TEXT.h_clip_relation = h_clip_relations.COMPARE MENU_CHK_TEXT.level = 2 MENU_CHK_TEXT.init_pos = {-0.565,0.92, 0} MENU_CHK_TEXT.init_rot = {0, 0, 0} MENU_CHK_TEXT.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} MENU_CHK_TEXT.controllers = { {"opacity_using_parameter",0}, {"parameter_in_range",1,0.9,1.1},--ENGINE PAGE = 0 } Add(MENU_CHK_TEXT) --------------------------------------------------------------------------------------------------- NAV MENU_TEXT1 = CreateElement "ceStringPoly" MENU_TEXT1.name = "menu" MENU_TEXT1.material = UFD_GRN MENU_TEXT1.value = "RWR" MENU_TEXT1.stringdefs = {0.0050, 0.0050, 0.0004, 0.001} MENU_TEXT1.alignment = "CenterCenter" MENU_TEXT1.formats = {"%s"} MENU_TEXT1.h_clip_relation = h_clip_relations.COMPARE MENU_TEXT1.level = 2 MENU_TEXT1.init_pos = {-0.265, 0.92, 0} MENU_TEXT1.init_rot = {0, 0, 0} MENU_TEXT1.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} MENU_TEXT1.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1},} Add(MENU_TEXT1) --------------------------------------------------------------------------------------------------- NAV MENU_TEXT2 = CreateElement "ceStringPoly" MENU_TEXT2.name = "menu" MENU_TEXT2.material = UFD_GRN MENU_TEXT2.value = "BAY" MENU_TEXT2.stringdefs = {0.0050, 0.0050, 0.0004, 0.001} MENU_TEXT2.alignment = "CenterCenter" MENU_TEXT2.formats = {"%s"} MENU_TEXT2.h_clip_relation = h_clip_relations.COMPARE MENU_TEXT2.level = 2 MENU_TEXT2.init_pos = {0.265, 0.92, 0} MENU_TEXT2.init_rot = {0, 0, 0} MENU_TEXT2.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} MENU_TEXT2.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1},} Add(MENU_TEXT2) --------------------------------------------------------------------------------------------------- NAV MENU_TEXT3 = CreateElement "ceStringPoly" MENU_TEXT3.name = "menu" MENU_TEXT3.material = UFD_GRN MENU_TEXT3.value = "ENG" MENU_TEXT3.stringdefs = {0.0050, 0.0050, 0.0004, 0.001} MENU_TEXT3.alignment = "CenterCenter" MENU_TEXT3.formats = {"%s"} MENU_TEXT3.h_clip_relation = h_clip_relations.COMPARE MENU_TEXT3.level = 2 MENU_TEXT3.init_pos = {0, 0.92, 0} MENU_TEXT3.init_rot = {0, 0, 0} MENU_TEXT3.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} MENU_TEXT3.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1},} Add(MENU_TEXT3) --------------------------------------------------------------------------------------------------- NAV MENU_TEXT3 = CreateElement "ceStringPoly" MENU_TEXT3.name = "menu" MENU_TEXT3.material = UFD_GRN MENU_TEXT3.value = "FCS" MENU_TEXT3.stringdefs = {0.0050, 0.0050, 0.0004, 0.001} MENU_TEXT3.alignment = "CenterCenter" MENU_TEXT3.formats = {"%s"} MENU_TEXT3.h_clip_relation = h_clip_relations.COMPARE MENU_TEXT3.level = 2 MENU_TEXT3.init_pos = {0.565, 0.92, 0} MENU_TEXT3.init_rot = {0, 0, 0} MENU_TEXT3.element_params = {"MFD_OPACITY","CMFD_FUEL_PAGE"} MENU_TEXT3.controllers = {{"opacity_using_parameter",0},{"parameter_in_range",1,0.9,1.1},} Add(MENU_TEXT3) -----------------------------------------------------------------------------------------------------------------------
0
0.889976
1
0.889976
game-dev
MEDIA
0.609826
game-dev
0.811952
1
0.811952
CharsetMC/Charset
16,355
src/main/java/pl/asie/charset/lib/block/BlockBase.java
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020 Adrian Siekierka * * This file is part of Charset. * * Charset 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. * * Charset is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Charset. If not, see <http://www.gnu.org/licenses/>. */ package pl.asie.charset.lib.block; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.Particle; import net.minecraft.client.particle.ParticleManager; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Enchantments; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.*; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import pl.asie.charset.ModCharset; import pl.asie.charset.lib.CharsetLib; import pl.asie.charset.lib.Properties; import pl.asie.charset.lib.item.ISubItemProvider; import pl.asie.charset.lib.render.ParticleDiggingCharset; import pl.asie.charset.lib.render.model.IStateParticleBakedModel; import pl.asie.charset.lib.utils.MethodHandleHelper; import pl.asie.charset.lib.utils.UtilProxyCommon; import pl.asie.charset.lib.utils.Utils; import javax.annotation.Nullable; import java.lang.reflect.Method; import java.util.List; public abstract class BlockBase extends Block implements ISubItemProvider.Container { private final boolean isTileProvider; private final ISubItemProvider subItemProvider; private boolean fullCube = true, opaqueCube = true, comparatorInputOverride = false; // I am very forgetful. private boolean calledSetHardness = false; @Override public Block setHardness(float val) { calledSetHardness = true; return super.setHardness(val); } public void verifyPreGameLaunch() { if (ModCharset.INDEV) { if (!calledSetHardness) { ModCharset.logger.warn("[INDEV] Modder did not call setHardness on " + getRegistryName() + "!"); } } } public BlockBase(Material materialIn) { super(materialIn); isTileProvider = this instanceof ITileEntityProvider; subItemProvider = createSubItemProvider(); } public BlockBase(Material materialIn, MapColor color) { super(materialIn, color); isTileProvider = this instanceof ITileEntityProvider; subItemProvider = createSubItemProvider(); } @Override public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { super.breakBlock(worldIn, pos, state); if (hasComparatorInputOverride(state)) { worldIn.updateComparatorOutputLevel(pos, this); } } @Override public final ISubItemProvider getSubItemProvider() { return subItemProvider; } protected BlockBase setComparatorInputOverride(boolean value) { comparatorInputOverride = value; return this; } protected BlockBase setFullCube(boolean value) { fullCube = value; return this; } protected BlockBase setOpaqueCube(boolean value) { opaqueCube = value; // update affected variables this.fullBlock = this.getDefaultState().isOpaqueCube(); this.lightOpacity = this.fullBlock ? 255 : 0; return this; } protected ISubItemProvider createSubItemProvider() { return null; } @Override public boolean hasComparatorInputOverride(IBlockState state) { return comparatorInputOverride; } @Override public BlockFaceShape getBlockFaceShape(IBlockAccess access, IBlockState state, BlockPos pos, EnumFacing facing) { return isNormalCube(state, access, pos) ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED; } @Override public boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side) { return getBlockFaceShape(world, base_state, pos, side) == BlockFaceShape.SOLID; } @Override public boolean isFullCube(IBlockState state) { return fullCube; } @Override public boolean isOpaqueCube(IBlockState state) { return opaqueCube; } public int getParticleTintIndex() { return -1; } @Override public ItemStack getItem(World world, BlockPos pos, IBlockState state) { if (isTileProvider) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileBase) { return ((TileBase) tile).getPickedBlock(null, null, state); } } return new ItemStack(this); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { if (isTileProvider) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileBase) { return ((TileBase) tile).getPickedBlock(player, target, state); } } return new ItemStack(this); } @Override public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> itemList) { if (subItemProvider != null) { itemList.addAll(subItemProvider.getItems()); } else { super.getSubBlocks(tab, itemList); } } @Override public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos) { if (isTileProvider) { TileEntity tile = worldIn.getTileEntity(pos); if (tile instanceof TileBase) { return ((TileBase) tile).getComparatorValue(15); } } return 0; } @Override public final void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { super.onBlockPlacedBy(world, pos, state, placer, stack); onBlockPlacedBy(world, pos, state, placer, stack, null, 0.5f, 0.5f, 0.5f); } public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack, @Nullable EnumFacing face, float hitX, float hitY, float hitZ) { if (isTileProvider) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileBase) { ((TileBase) tile).onPlacedBy(placer, face, stack, hitX, hitY, hitZ); } } } protected boolean isProtectedDroppable(ItemStack stack) { return false; } @Override public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, ItemStack stack) { player.addStat(StatList.getBlockStats(this)); player.addExhaustion(0.005F); int fortuneLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, stack); boolean silkTouch = EnchantmentHelper.getEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0; NonNullList<ItemStack> items = NonNullList.create(); getDrops(items, worldIn, pos, state, te, fortuneLevel, silkTouch); float chance = net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(items, worldIn, pos, state, fortuneLevel, 1.0f, silkTouch, player); harvesters.set(player); if (!worldIn.isRemote && !worldIn.restoringBlockSnapshots) { for (ItemStack item : items) { if (chance >= 1.0f || worldIn.rand.nextFloat() <= chance || (isProtectedDroppable(item) && !CharsetLib.dropHardMode)) { spawnAsEntity(worldIn, pos, item); } } } harvesters.set(null); } @Override public boolean canDropFromExplosion(Explosion explosionIn) { return false; // custom handling to preserve TE } @Override public void onBlockExploded(World world, BlockPos pos, Explosion explosion) { IBlockState stateOld = world.getBlockState(pos); onExplosionDestroy(world, pos, explosion); IBlockState state = world.getBlockState(pos); TileEntity tile = world.getTileEntity(pos); if (stateOld == state) { world.setBlockToAir(pos); NonNullList<ItemStack> items = NonNullList.create(); getDrops(items, world, pos, state, tile, 0, false); float chance = net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(items, world, pos, state, 0, 1.0f / Utils.getExplosionSize(explosion), true, null); for (ItemStack item : items) { if (world.rand.nextFloat() <= chance || (isProtectedDroppable(item) && !CharsetLib.dropHardMode)) { spawnAsEntity(world, pos, item); } } } else { // The block seems to have been replaced with something. // Don't do anything. } } @Override public final void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { getDrops(drops, world, pos, state, world.getTileEntity(pos), fortune, false); } public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, @Nullable TileEntity te, int fortune, boolean silkTouch) { if (te instanceof TileBase) { ((TileBase) te).getDrops(drops, state, fortune, silkTouch); } else { super.getDrops(drops, world, pos, state, fortune); } } @Override public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { if (!worldIn.isRemote && !worldIn.restoringBlockSnapshots) { NonNullList<ItemStack> drops = NonNullList.create(); getDrops(drops, worldIn, pos, state, worldIn.getTileEntity(pos), fortune, false); chance = net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(drops, worldIn, pos, state, fortune, chance, false, harvesters.get()); for (ItemStack drop : drops) { if (worldIn.rand.nextFloat() <= chance || (isProtectedDroppable(drop) && !CharsetLib.dropHardMode)) { spawnAsEntity(worldIn, pos, drop); } } } } @Override @SideOnly(Side.CLIENT) public boolean addDestroyEffects(World world, BlockPos pos, ParticleManager manager) { IBlockState state = world.getBlockState(pos); IBakedModel model = Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState(state); if (model instanceof IStateParticleBakedModel) { state = getExtendedState(state.getActualState(world, pos), world, pos); TextureAtlasSprite sprite = ((IStateParticleBakedModel) model).getParticleTexture(state, null); if (sprite != null) { for (int j = 0; j < 4; ++j) { for (int k = 0; k < 4; ++k) { for (int l = 0; l < 4; ++l) { double d0 = ((double)j + 0.5D) / 4.0D; double d1 = ((double)k + 0.5D) / 4.0D; double d2 = ((double)l + 0.5D) / 4.0D; manager.addEffect(new ParticleDiggingCharset(world, (double)pos.getX() + d0, (double)pos.getY() + d1, (double)pos.getZ() + d2, d0 - 0.5D, d1 - 0.5D, d2 - 0.5D, state, pos, sprite, getParticleTintIndex())); } } } return true; } } return false; } @Override @SideOnly(Side.CLIENT) public boolean addHitEffects(IBlockState state, World world, RayTraceResult target, ParticleManager manager) { IBakedModel model = Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState(state); if (model instanceof IStateParticleBakedModel) { BlockPos pos = target.getBlockPos(); EnumFacing side = target.sideHit; state = getExtendedState(state.getActualState(world, pos), world, pos); TextureAtlasSprite sprite = ((IStateParticleBakedModel) model).getParticleTexture(state, side); if (sprite != null) { int i = pos.getX(); int j = pos.getY(); int k = pos.getZ(); AxisAlignedBB axisalignedbb = state.getBoundingBox(world, pos); double d0 = (double)i + RANDOM.nextDouble() * (axisalignedbb.maxX - axisalignedbb.minX - 0.20000000298023224D) + 0.10000000149011612D + axisalignedbb.minX; double d1 = (double)j + RANDOM.nextDouble() * (axisalignedbb.maxY - axisalignedbb.minY - 0.20000000298023224D) + 0.10000000149011612D + axisalignedbb.minY; double d2 = (double)k + RANDOM.nextDouble() * (axisalignedbb.maxZ - axisalignedbb.minZ - 0.20000000298023224D) + 0.10000000149011612D + axisalignedbb.minZ; if (side == EnumFacing.DOWN) { d1 = (double)j + axisalignedbb.minY - 0.10000000149011612D; } if (side == EnumFacing.UP) { d1 = (double)j + axisalignedbb.maxY + 0.10000000149011612D; } if (side == EnumFacing.NORTH) { d2 = (double)k + axisalignedbb.minZ - 0.10000000149011612D; } if (side == EnumFacing.SOUTH) { d2 = (double)k + axisalignedbb.maxZ + 0.10000000149011612D; } if (side == EnumFacing.WEST) { d0 = (double)i + axisalignedbb.minX - 0.10000000149011612D; } if (side == EnumFacing.EAST) { d0 = (double)i + axisalignedbb.maxX + 0.10000000149011612D; } Particle particle = new ParticleDiggingCharset(world, d0, d1, d2, 0.0D, 0.0D, 0.0D, state, pos, sprite, getParticleTintIndex()) .multiplyVelocity(0.2F) .multipleParticleScaleBy(0.6F); manager.addEffect(particle); return true; } } return false; } @Override public boolean addLandingEffects(IBlockState state, WorldServer world, BlockPos pos, IBlockState stateAgain, EntityLivingBase entity, int numberOfParticles) { PacketCustomBlockDust packet = new PacketCustomBlockDust(world, pos, entity.posX, entity.posY, entity.posZ, numberOfParticles, 0.15f); CharsetLib.packet.sendToDimension(packet, world.provider.getDimension()); return true; } @Override public boolean addRunningEffects(IBlockState state, World world, BlockPos pos, Entity entity) { return UtilProxyCommon.proxy.addRunningParticles(state, world, pos, entity); } @Override public boolean rotateBlock(World world, BlockPos pos, EnumFacing axis) { if (axis != null) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof ITileWrenchRotatable) { return ((ITileWrenchRotatable) tile).rotateWrench(axis); } else { return super.rotateBlock(world, pos, axis); } } else { return super.rotateBlock(world, pos, axis); } } @Override public IBlockState withRotation(IBlockState state, Rotation rot) { if (state.getPropertyKeys().contains(Properties.FACING)) { return state.withProperty(Properties.FACING, rot.rotate(state.getValue(Properties.FACING))); } else if (state.getPropertyKeys().contains(Properties.FACING4)) { return state.withProperty(Properties.FACING4, rot.rotate(state.getValue(Properties.FACING4))); } else if (state.getPropertyKeys().contains(Properties.AXIS) && (rot == Rotation.CLOCKWISE_90 || rot == Rotation.COUNTERCLOCKWISE_90)) { EnumFacing.Axis axis = state.getValue(Properties.AXIS); if (axis == EnumFacing.Axis.X) { return state.withProperty(Properties.AXIS, EnumFacing.Axis.Z); } else if (axis == EnumFacing.Axis.Z) { return state.withProperty(Properties.AXIS, EnumFacing.Axis.X); } else { return state; } } else { return state; } } @Override public IBlockState withMirror(IBlockState state, Mirror mirror) { if (state.getPropertyKeys().contains(Properties.FACING)) { return state.withProperty(Properties.FACING, mirror.mirror(state.getValue(Properties.FACING))); } else if (state.getPropertyKeys().contains(Properties.FACING4)) { return state.withProperty(Properties.FACING4, mirror.mirror(state.getValue(Properties.FACING4))); } else { return state; } } @Override public boolean eventReceived(IBlockState state, World worldIn, BlockPos pos, int id, int type) { if (super.eventReceived(state, worldIn, pos, id, type)) { return true; } TileEntity tile = worldIn.getTileEntity(pos); if (tile != null) { return tile.receiveClientEvent(id, type); } return false; } }
0
0.958727
1
0.958727
game-dev
MEDIA
0.999218
game-dev
0.986686
1
0.986686
folgerwang/UnrealEngine
2,554
Engine/Plugins/Runtime/GameplayAbilities/Source/GameplayAbilities/Private/Abilities/Tasks/AbilityTask_SpawnActor.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "Abilities/Tasks/AbilityTask_SpawnActor.h" #include "EngineGlobals.h" #include "Engine/Engine.h" #include "AbilitySystemComponent.h" UAbilityTask_SpawnActor::UAbilityTask_SpawnActor(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } UAbilityTask_SpawnActor* UAbilityTask_SpawnActor::SpawnActor(UGameplayAbility* OwningAbility, FGameplayAbilityTargetDataHandle TargetData, TSubclassOf<AActor> InClass) { UAbilityTask_SpawnActor* MyObj = NewAbilityTask<UAbilityTask_SpawnActor>(OwningAbility); MyObj->CachedTargetDataHandle = MoveTemp(TargetData); return MyObj; } // --------------------------------------------------------------------------------------- bool UAbilityTask_SpawnActor::BeginSpawningActor(UGameplayAbility* OwningAbility, FGameplayAbilityTargetDataHandle TargetData, TSubclassOf<AActor> InClass, AActor*& SpawnedActor) { if (Ability && Ability->GetCurrentActorInfo()->IsNetAuthority() && ShouldBroadcastAbilityTaskDelegates()) { UWorld* const World = GEngine->GetWorldFromContextObject(OwningAbility, EGetWorldErrorMode::LogAndReturnNull); if (World) { SpawnedActor = World->SpawnActorDeferred<AActor>(InClass, FTransform::Identity, NULL, NULL, ESpawnActorCollisionHandlingMethod::AlwaysSpawn); } } if (SpawnedActor == nullptr) { if (ShouldBroadcastAbilityTaskDelegates()) { DidNotSpawn.Broadcast(nullptr); } return false; } return true; } void UAbilityTask_SpawnActor::FinishSpawningActor(UGameplayAbility* OwningAbility, FGameplayAbilityTargetDataHandle TargetData, AActor* SpawnedActor) { if (SpawnedActor) { bool bTransformSet = false; FTransform SpawnTransform; if (FGameplayAbilityTargetData* LocationData = CachedTargetDataHandle.Get(0)) //Hardcode to use data 0. It's OK if data isn't useful/valid. { //Set location. Rotation is unaffected. if (LocationData->HasHitResult()) { SpawnTransform.SetLocation(LocationData->GetHitResult()->Location); bTransformSet = true; } else if (LocationData->HasEndPoint()) { SpawnTransform = LocationData->GetEndPointTransform(); bTransformSet = true; } } if (!bTransformSet) { SpawnTransform = AbilitySystemComponent->GetOwner()->GetTransform(); } SpawnedActor->FinishSpawning(SpawnTransform); if (ShouldBroadcastAbilityTaskDelegates()) { Success.Broadcast(SpawnedActor); } } EndTask(); } // ---------------------------------------------------------------------------------------
0
0.826141
1
0.826141
game-dev
MEDIA
0.995772
game-dev
0.734604
1
0.734604
phillipchain/LoLServer
2,376
Content/LeagueSandbox-Scripts/Buffs/LeeSin/BlindMonkQOneChaos.cs
using GameServerCore.Enums; using static LeagueSandbox.GameServer.API.ApiFunctionManager; using GameServerCore.Scripting.CSharp; using LeagueSandbox.GameServer.Scripting.CSharp; using LeagueSandbox.GameServer.GameObjects; using LeagueSandbox.GameServer.GameObjects.AttackableUnits; using LeagueSandbox.GameServer.GameObjects.SpellNS; using LeagueSandbox.GameServer.GameObjects.StatsNS; namespace Buffs { internal class BlindMonkQOneChaos : IBuffGameScript { public BuffScriptMetaData BuffMetaData { get; set; } = new BuffScriptMetaData { BuffType = BuffType.COMBAT_DEHANCER, BuffAddType = BuffAddType.REPLACE_EXISTING }; public StatsModifier StatsModifier { get; private set; } Spell originSpell; Buff thisBuff; Region bubble1; Region bubble2; Particle slow; public void OnActivate(AttackableUnit unit, Buff buff, Spell ownerSpell) { originSpell = ownerSpell; thisBuff = buff; bubble1 = AddUnitPerceptionBubble(unit, 400.0f, 20.0f, buff.SourceUnit.Team); bubble2 = AddUnitPerceptionBubble(unit, 50.0f, 20.0f, buff.SourceUnit.Team, true); // ApplyAssistMarker(buff.SourceUnit, unit, 10.0f); AddParticleTarget(buff.SourceUnit, unit, "blindMonk_Q_resonatingStrike_tar", unit, buff.Duration, bone: "C_BuffBone_Glb_Center_Loc", flags: 0); AddParticleTarget(buff.SourceUnit, unit, "blindMonk_Q_resonatingStrike_tar_blood", unit, buff.Duration, bone: "C_BuffBone_Glb_Center_Loc", flags: 0); slow = AddParticleTarget(buff.SourceUnit, unit, "blindMonk_Q_tar_indicator", unit, buff.Duration, flags: 0); if (buff.SourceUnit.SkinID == 5) { AddParticleTarget(buff.SourceUnit, unit, "leesin_skin05_q_tar_sound", unit, buff.Duration, bone: "C_BuffBone_Glb_Center_Loc", flags: 0); } } public void OnDeactivate(AttackableUnit unit, Buff buff, Spell ownerSpell) { bubble1.SetToRemove(); bubble2.SetToRemove(); slow.SetToRemove(); var manager = unit.GetBuffWithName("BlindMonkQManager"); if (manager != null && manager.SourceUnit == buff.SourceUnit) { RemoveBuff(manager); } } } }
0
0.751213
1
0.751213
game-dev
MEDIA
0.880305
game-dev,testing-qa
0.853707
1
0.853707
ThePaperLuigi/The-Stars-Above
3,668
Projectiles/Melee/BurningDesire/ChainsawFollowUp.cs
using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; using static Terraria.ModLoader.ModContent; namespace StarsAbove.Projectiles.Melee.BurningDesire { public class ChainsawFollowUp : ModProjectile { public override void SetStaticDefaults() { // DisplayName.SetDefault("Burning Desire"); //The English name of the projectile ProjectileID.Sets.TrailCacheLength[Projectile.type] = 5; //The length of old position to be recorded ProjectileID.Sets.TrailingMode[Projectile.type] = 0; //The recording mode } public override void SetDefaults() { Projectile.width = 100; //The width of projectile hitbox Projectile.height = 100; //The height of projectile hitbox Projectile.aiStyle = -1; //The ai style of the projectile, please reference the source code of Terraria Projectile.friendly = false; //Can the projectile deal damage to enemies? Projectile.hostile = false; //Can the projectile deal damage to the player? Projectile.penetrate = -1; //How many monsters the projectile can penetrate. (OnTileCollide below also decrements penetrate for bounces as well) Projectile.timeLeft = 60; //The live time for the projectile (60 = 1 second, so 600 is 10 seconds) Projectile.alpha = 100; //The transparency of the projectile, 255 for completely transparent. (aiStyle 1 quickly fades the projectile in) Make sure to delete this if you aren't using an aiStyle that fades in. You'll wonder why your projectile is invisible. Projectile.light = 0.5f; //How much light emit around the projectile Projectile.ignoreWater = true; //Does the projectile's speed be influenced by water? Projectile.tileCollide = false; //Can the projectile collide with tiles? Projectile.extraUpdates = 0; //Set to above 0 if you want the projectile to update multiple time in a frame //AIType = ProjectileID.Bullet; //Act exactly like default Bullet } bool firstSpawn = true; Vector2 savedVelocity; public override void AI() { if (firstSpawn) { savedVelocity = Projectile.velocity; firstSpawn = false; } if (Projectile.ai[0] > 30) { Projectile.velocity = savedVelocity; Projectile.friendly = true; } else { Projectile.velocity = new Vector2(savedVelocity.X / 10, savedVelocity.Y / 10); } if (Projectile.timeLeft < 10) { Projectile.alpha += 10; } Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.ToRadians(90f); Projectile.ai[0]++; base.AI(); } public override bool OnTileCollide(Vector2 oldVelocity) { return false; } public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { Projectile.NewProjectile(Projectile.GetSource_FromThis(), target.Center.X, target.Center.Y, 0, 0, ProjectileType<ChainsawFollowUpExplosion>(), damageDone / 4, 0f, Main.player[Projectile.owner].whoAmI, 0); Projectile.Kill(); } public override void OnKill(int timeLeft) { } } }
0
0.811766
1
0.811766
game-dev
MEDIA
0.99267
game-dev
0.811631
1
0.811631
Arakne/Araknemu
2,809
src/main/java/fr/quatrevieux/araknemu/game/admin/player/Kick.java
/* * This file is part of Araknemu. * * Araknemu 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. * * Araknemu is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Araknemu. If not, see <https://www.gnu.org/licenses/>. * * Copyright (c) 2017-2021 Vincent Quatrevieux */ package fr.quatrevieux.araknemu.game.admin.player; import fr.quatrevieux.araknemu.common.account.Permission; import fr.quatrevieux.araknemu.game.account.GameAccount; import fr.quatrevieux.araknemu.game.admin.AbstractCommand; import fr.quatrevieux.araknemu.game.admin.AdminPerformer; import fr.quatrevieux.araknemu.game.admin.exception.AdminException; import fr.quatrevieux.araknemu.game.admin.exception.CommandException; import fr.quatrevieux.araknemu.game.player.GamePlayer; import fr.quatrevieux.araknemu.network.out.ServerMessage; import java.util.List; /** * Command for kick a player */ public final class Kick extends AbstractCommand<List<String>> { private final GamePlayer player; public Kick(GamePlayer player) { this.player = player; } @Override protected void build(Builder builder) { builder .help(help -> help .description("Kick the player of the server") .synopsis("@[player] kick [MESSAGE]") .option("MESSAGE", "Optional. The kick reason") .example("@John kick Last warning", "Kick John with message 'Last warning'") .seeAlso("ban", "For ban the player") ) .requires(Permission.MANAGE_PLAYER) ; } @Override public String name() { return "kick"; } @Override public void execute(AdminPerformer performer, List<String> arguments) throws AdminException { checkNotSelf(performer); final String message = arguments.isEmpty() ? "" : "\n" + String.join(" ", arguments); player.account().kick(ServerMessage.kick( performer.account().map(GameAccount::pseudo).orElse("system"), message )); } /** * Check to ensure that the admin do not kick himself */ private void checkNotSelf(AdminPerformer performer) throws CommandException { if (performer.account().filter(player.account()::equals).isPresent()) { error("Cannot kick yourself"); } } }
0
0.877143
1
0.877143
game-dev
MEDIA
0.816299
game-dev
0.827403
1
0.827403
HoolockLinux/m1n1_old
24,262
proxyclient/m1n1/adt.py
# SPDX-License-Identifier: MIT import itertools, fnmatch, sys from construct import * import sys from .utils import AddrLookup, FourCC, SafeGreedyRange __all__ = ["load_adt"] ADTPropertyStruct = Struct( "name" / PaddedString(32, "ascii"), "size" / Int32ul, "value" / Bytes(this.size & 0x7fffffff) ) ADTNodeStruct = Struct( "property_count" / Int32ul, "child_count" / Int32ul, "properties" / Array(this.property_count, Aligned(4, ADTPropertyStruct)), "children" / Array(this.child_count, LazyBound(lambda: ADTNodeStruct)) ) ADTStringList = SafeGreedyRange(CString("ascii")) ADT2Tuple = Array(2, Hex(Int64ul)) ADT3Tuple = Array(3, Hex(Int64ul)) Function = Struct( "phandle" / Int32ul, "name" / FourCC, "args" / SafeGreedyRange(Int32ul), ) STD_PROPERTIES = { "cpu-impl-reg": ADT2Tuple, "name": CString("ascii"), "compatible": ADTStringList, "model": CString("ascii"), "#size-cells": Int32ul, "#address-cells": Int32ul, "clock-ids": SafeGreedyRange(Int32ul), "clock-gates": SafeGreedyRange(Int32ul), "power-gates": SafeGreedyRange(Int32ul), } PMAPIORanges = SafeGreedyRange(Struct( "addr" / Hex(Int64ul), "size" / Hex(Int64ul), "flags" / Hex(Int32ul), "name" / FourCC, )) PMGRPSRegs = SafeGreedyRange(Struct( "reg" / Int32ul, "offset" / Hex(Int32ul), "mask" / Hex(Int32ul), )) PMGRPerfRegs = SafeGreedyRange(Struct( "reg" / Int32ul, "offset" / Hex(Int32ul), "size" / Hex(Int32ul), "unk" / Int32ul, )) PMGRPWRGateRegs = SafeGreedyRange(Struct( "reg" / Int32ul, "offset" / Hex(Int32ul), "mask" / Hex(Int32ul), "unk" / Hex(Int32ul), )) PMGRDeviceFlags = BitStruct( "b7" / Flag, "b6" / Flag, "perf" / Flag, "no_ps" / Flag, "critical" / Flag, "b2" / Flag, "notify_pmp" / Flag, "on" / Flag, ) PMGRDevices = SafeGreedyRange(Struct( "flags" / PMGRDeviceFlags, "unk1_0" / Int8ul, "unk1_1" / Int8ul, "id1" / Int8ul, "parents_un" / Union (0, "u8id" / Struct( "parents" / Array(2, Int8ul), "unk_u8id" / Array(2, Int8ul), ), "u16id" / Struct ( "parents" / Array(2, Int16ul), ), ), "perf_idx" / Int8ul, "perf_block" / Int8ul, "psidx" / Int8ul, "psreg" / Int8ul, "unk2_0" / Int16ul, "pd" / Int8ul, "ps_cfg16" / Int8ul, "unk2_1" / Int32ul, "unk2_2" / Int32ul, "unk2_3" / Int16ul, "id2" / Int16ul, "unk3" / Int32ul, "name" / PaddedString(16, "ascii") )) PMGRClocks = SafeGreedyRange(Struct( "perf_idx" / Int8ul, "perf_block" / Int8ul, "unk" / Int8ul, "id" / Int8ul, Const(0, Int32ul), "name" / PaddedString(16, "ascii"), )) PMGRPowerDomains = SafeGreedyRange(Struct( "unk" / Int8ul, "perf_idx" / Int8ul, "perf_block" / Int8ul, "id" / Int8ul, "flags" / Int32ul, "name" / PaddedString(16, "ascii"), )) PMGRDeviceBridges = SafeGreedyRange(Struct( "idx" / Int32ub, "subdevs" / HexDump(Bytes(0x48)), )) PMGREvents = SafeGreedyRange(Struct( "unk1" / Int8ul, "unk2" / Int8ul, "unk3" / Int8ul, "id" / Int8ul, "perf2_idx" / Int8ul, "perf2_block" / Int8ul, "perf_idx" / Int8ul, "perf_block" / Int8ul, "name" / PaddedString(16, "ascii"), )) GPUPerfState = Struct( "freq" / Int32ul, "volt" / Int32ul, ) GPUPerfState64 = Struct( "volt" / Int64ul, "freq" / Int64ul, ) GPUPerfStates64 = Struct( "dies" / Int64ul, "count" / Int64ul, "states" / Array(this.dies, Array(this.count, GPUPerfState64)), "min_sram_volt" / Array(this.dies, Int64ul), ) SpeakerConfig = Struct( "rx_slot" / Int8ul, "amp_gain" / Int8ul, "vsense_slot" / Int8ul, "isense_slot" / Int8ul, ) DCBlockerConfig = Struct( "dc_blk0" / Hex(Int8ul), "dc_blk1" / Hex(Int8ul), "pad" / Hex(Int16ul), ) Coef = ExprAdapter(Int32ul, lambda x, ctx: (x - ((x & 0x1000000) << 1)) / 65536, lambda x, ctx: int(round(x * 65536)) & 0x1ffffff) MTRPolynomFuseAGX = GreedyRange(Struct( "id" / Int32ul, "data" / Prefixed(Int32ul, GreedyRange(Coef)), )) SpeakerThieleSmall = Struct( "unk0" / Int16ul, "unk1" / Int16ul, "speakers" / GreedyRange(Struct( "pad0" / Hex(Int32ul), "r_mohm" / Int16ul, "temp" / Int16ul, "pad1" / Hex(Int32ul), "pad2" / Hex(Int32ul), "pad3" / Hex(Int16ul), "name" / FourCC, )), "checksum" / Hex(Int16ul), ) TunableGlobal = Struct( "reg_idx" / Hex(Int32ul), "offset" / Hex(Int32ul), "mask" / Hex(Int32ul), "value" / Hex(Int32ul), ) TunableLocal = Struct( "offset" / Hex(Int32ul), "size" / Hex(Int32ul), "mask" / Hex(Int64ul), "value" / Hex(Int64ul), ) DAPFT8110 = Struct( "start" / Hex(Int64ul), "end" / Hex(Int64ul), "r20" / Hex(Int32ul), "unk1" / Hex(Int32ul), "r4" / Hex(Int32ul), "unk2" / Array(5, Hex(Int32ul)), "unk3" / Hex(Int8ul), "r0h" / Hex(Int8ul), "r0l" / Hex(Int8ul), "unk4" / Hex(Int8ul), ) DAPFT8110B = Struct( "start" / Hex(Int64ul), "end" / Hex(Int64ul), "r20" / Hex(Int32ul), "unk1" / Hex(Int32ul), "r4" / Hex(Int32ul), "unk2" / Array(5, Hex(Int32ul)), "unk3" / Hex(Int8ul), "r0h" / Hex(Int8ul), "r0l" / Hex(Int8ul), "unk4" / Hex(Int8ul), "pad" / Hex(Int32ul), ) DAPFT8110C = Struct( "start" / Hex(Int64ul), "end" / Hex(Int64ul), "r20" / Hex(Int32ul), "unk1" / Hex(Int32ul), "r4" / Hex(Int32ul), "unk2" / Array(5, Hex(Int32ul)), "unk3" / Hex(Int8ul), "r0h" / Hex(Int8ul), "r0l" / Hex(Int8ul), "unk4" / Hex(Int8ul), "pad" / Array(3, Hex(Int8ul)), ) AOPRatios = Struct( "r0" / Int8ul, "r1" / Int8ul, "r2" / Int8ul, Const(0, Int8ul), ) DEV_PROPERTIES = { "pmgr": { "*": { "clusters": SafeGreedyRange(Int32ul), "devices": PMGRDevices, "ps-regs": PMGRPSRegs, "perf-regs": PMGRPerfRegs, "pwrgate-regs": PMGRPWRGateRegs, "power-domains": PMGRPowerDomains, "clocks": PMGRClocks, "device-bridges": PMGRDeviceBridges, "voltage-states*": SafeGreedyRange(Int32ul), "events": PMGREvents, "mtr-polynom-fuse-agx": MTRPolynomFuseAGX, } }, "clpc": { "*": { "events": SafeGreedyRange(Int32ul), "devices": SafeGreedyRange(Int32ul), } }, "soc-tuner": { "*": { "device-set-*": SafeGreedyRange(Int32ul), "mcc-configs": SafeGreedyRange(Int32ul), } }, "mcc": { "*": { "dramcfg-data": SafeGreedyRange(Int32ul), "config-data": SafeGreedyRange(Int32ul), } }, "*pmu*": { "*": { "info-*name*": CString("ascii"), "info-*": SafeGreedyRange(Hex(Int32ul)), }, }, "stockholm-spmi": { "*": { "required-functions": ADTStringList, }, }, "sgx": { "*": { "perf-states*": SafeGreedyRange(GPUPerfState), "afr-perf-states": GPUPerfStates64, "cs-perf-states": GPUPerfStates64, "*-kp": Float32l, "*-kp-1": Float32l, "*-ki": Float32l, "*-ki-*": Float32l, "*-gain*": Float32l, "*-scale*": Float32l, } }, "arm-io": { "*": { "clock-frequencies": SafeGreedyRange(Int32ul), "clock-frequencies-regs": SafeGreedyRange(Hex(Int64ul)), "clock-frequencies-nclk": SafeGreedyRange(Int32ul), }, }, "defaults": { "*": { "pmap-io-ranges": PMAPIORanges, } }, "audio-*": { "*": { "speaker-config": SafeGreedyRange(SpeakerConfig), "amp-dcblocker-config": DCBlockerConfig, }, }, "*aop-audio*": { "*": { "clockSource": FourCC, "identifier": FourCC, "ratios": AOPRatios, "filterLengths": Hex(Int32ul), }, }, "*alc?/audio-leap-mic*": { "*": { "audio-stream-formatter": FourCC, } }, "audio": { "*": { "speaker-thiele-small": SpeakerThieleSmall, }, }, # "apcie*": { # "*": { # "apcie-*-tunables": GreedyRange(TunableLocal), # } # }, } def parse_prop(node, path, node_name, name, v, is_template=False): t = None if is_template: t = CString("ascii") v = Sequence(t, Terminated).parse(v)[0] return t, v dev_props = None for k, pt in DEV_PROPERTIES.items(): if fnmatch.fnmatch(path, k): dev_props = pt break if not dev_props: for k, pt in DEV_PROPERTIES.items(): if fnmatch.fnmatch(node_name, k): dev_props = pt break possible_match = False if dev_props: for compat_match, cprops in dev_props.items(): for k, pt in cprops.items(): if fnmatch.fnmatch(name, k): possible_match = True break if possible_match: try: compat = node.compatible[0] except AttributeError: compat = "" for compat_match, cprops in dev_props.items(): if fnmatch.fnmatch(compat, compat_match): for k, pt in cprops.items(): if fnmatch.fnmatch(name, k): t = pt break else: continue break if v == b'' or v is None: return None, None if name.startswith("function-"): if len(v) == 4: t = FourCC else: t = Function if name == "reg" and path != "/device-tree/memory": n = node._parent while n is not None and n._parent is not None: if "ranges" not in n._properties: break n = n._parent else: rs = node._reg_struct if len(v) % rs.sizeof() == 0: t = SafeGreedyRange(rs) elif name == "ranges": try: ac, sc = node.address_cells, node.size_cells except AttributeError: return None, v pac, _ = node._parent.address_cells, node._parent.size_cells at = Hex(Int64ul) if ac == 2 else Array(ac, Hex(Int32ul)) pat = Hex(Int64ul) if pac == 2 else Array(pac, Hex(Int32ul)) st = Hex(Int64ul) if sc == 2 else Array(sc, Hex(Int32ul)) t = SafeGreedyRange(Struct("bus_addr" / at, "parent_addr" / pat, "size" / st)) elif name.startswith("dapf-instance-"): try: flags = node.dart_options except AttributeError: return None, v if flags & 0x40: if len(v) % DAPFT8110B.sizeof() == 0: if len(v) % DAPFT8110C.sizeof() != 0: t = GreedyRange(DAPFT8110B) else: t = GreedyRange(DAPFT8110C) else: t = GreedyRange(DAPFT8110) elif name == "interrupts": # parse "interrupts" as Array of Int32ul, wrong for nodes whose # "interrupt-parent" has "interrupt-cells" = 2 # parsing this correctly would require a second pass t = Array(len(v) // 4, Int32ul) if t is not None: v = Sequence(t, Terminated).parse(v)[0] return t, v if name in STD_PROPERTIES: t = STD_PROPERTIES[name] elif v and v[-1] == 0 and all(0x20 <= i <= 0x7e for i in v[:-1]): t = CString("ascii") elif len(v) == 4: t = Int32ul elif len(v) == 8: t = Int64ul elif len(v) == 16 and all(v[i] == 0 for i in (6, 7, 14, 15)): t = ADT2Tuple if t is not None: try: v = Sequence(t, Terminated).parse(v)[0] except: print("Failed to parse:", path, name, v.hex()) raise return t, v def build_prop(path, name, v, t=None): if v is None: return b'' if t is not None: return t.build(v) if isinstance(v, bytes): return v if name in STD_PROPERTIES: t = STD_PROPERTIES[name] elif isinstance(v, str): t = CString("ascii") elif isinstance(v, int): if v > 0xffffffff: t = Int64ul else: t = Int32ul elif isinstance(v, float): t = Float32l elif isinstance(v, tuple) and all(isinstance(i, int) for i in v): t = Array(len(v), Int32ul) return t.build(v) class ADTNode: def __init__(self, val=None, path="/", parent=None): self._children = [] self._properties = {} self._types = {} self._parent_path = path self._parent = parent if val is not None: for p in val.properties: if p.name == "name": _name = p.value.decode("ascii").rstrip("\0") break else: raise ValueError(f"Node in {path} has no name!") path = self._parent_path + _name raw = {} for p in val.properties: raw[p.name] = p.value is_template = bool(p.size & 0x80000000) try: t, v = parse_prop(self, path, _name, p.name, p.value, is_template) self._types[p.name] = t, is_template self._properties[p.name] = v except Exception as e: print(f"Exception parsing {path}.{p.name} value {p.value.hex()}:", file=sys.stderr) raise # Second pass for k, (t, is_template) in self._types.items(): if t is None: t, v = parse_prop(self, path, _name, k, self._properties[k], is_template) self._types[k] = t, is_template self._properties[k] = v assert build_prop(self._path, k, v, t=t) == raw[k] for c in val.children: node = ADTNode(c, f"{self._path}/", parent=self) self._children.append(node) @property def _path(self): return self._parent_path + self.name def __getitem__(self, item): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) return self[a][b] for i in self._children: if i.name == item: return i raise KeyError(f"Child node '{item}' not found") return self._children[item] def __setitem__(self, item, value): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) self[a][b] = value return for i, c in enumerate(self._children): if c.name == item: self._children[i] = value break else: self._children.append(value) else: self._children[item] = value def __delitem__(self, item): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) del self[a][b] return for i, c in enumerate(self._children): if c.name == item: del self._children[i] return raise KeyError(f"Child node '{item}' not found") del self._children[item] def __contains__(self, item): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) return b in self[a] for c in self._children: if c.name == item: return True return False return item in self._children def __getattr__(self, attr): attr = attr.replace("_", "-") attr = attr.replace("--", "_") if attr in self._properties: return self._properties[attr] raise AttributeError(attr) def __setattr__(self, attr, value): if attr[0] == "_": self.__dict__[attr] = value return attr = attr.replace("_", "-") attr = attr.replace("--", "_") self._properties[attr] = value def __delattr__(self, attr): if attr[0] == "_": del self.__dict__[attr] return attr = attr.replace("_", "-") attr = attr.replace("--", "_") del self._properties[attr] def getprop(self, name, default=None): return self._properties.get(name, default) @property def address_cells(self): try: return self._properties["#address-cells"] except KeyError: raise AttributeError("#address-cells") @property def size_cells(self): try: return self._properties["#size-cells"] except KeyError: raise AttributeError("#size-cells") @property def interrupt_cells(self): try: return self._properties["#interrupt-cells"] except KeyError: raise AttributeError("#interrupt-cells") def _fmt_prop(self, k, v): t, is_template = self._types.get(k, (None, False)) if is_template: return f"<< {v} >>" elif isinstance(v, ListContainer): return f"[{', '.join(self._fmt_prop(k, i) for i in v)}]" elif isinstance(v, bytes): if all(i == 0 for i in v): return f"zeroes({len(v):#x})" else: return v.hex() elif k.startswith("function-"): if isinstance(v, str): return f"{v}()" elif v is None: return f"None" else: args = [] for arg in v.args: b = arg.to_bytes(4, "big") is_ascii = all(0x20 <= c <= 0x7e for c in b) args.append(f"{arg:#x}" if not is_ascii else f"'{b.decode('ascii')}'") return f"{v.phandle}:{v.name}({', '.join(args)})" name.startswith("function-") else: return str(v) def __str__(self, t=""): return "\n".join([ t + f"{self.name} {{", *(t + f" {k} = {self._fmt_prop(k, v)}" for k, v in self._properties.items() if k != "name"), "", *(i.__str__(t + " ") for i in self._children), t + "}" ]) def __repr__(self): return f"<ADTNode {self.name}>" def __iter__(self): return iter(self._children) @property def _reg_struct(self): ac, sc = self._parent.address_cells, self._parent.size_cells return Struct( "addr" / Hex(Int64ul) if ac == 2 else Array(ac, Hex(Int32ul)), "size" / Hex(Int64ul) if sc == 2 else Array(sc, Hex(Int32ul)) ) def get_reg(self, idx): reg = self.reg[idx] addr = reg.addr size = reg.size return self._parent.translate(addr), size def translate(self, addr): node = self while node is not None: if "ranges" not in node._properties: break for r in node.ranges: ba = r.bus_addr # PCIe special case, because Apple really broke # the spec here with their little endian antics if isinstance(ba, list) and len(ba) == 3: ba = (ba[0] << 64) | (ba[2] << 32) | ba[1] if ba <= addr < (ba + r.size): addr = addr - ba + r.parent_addr break node = node._parent return addr def to_bus_addr(self, addr): node = self._parent descend = [] while node is not None: if "ranges" not in node._properties: break descend.append(node) node = node._parent for node in reversed(descend): for r in node.ranges: if r.parent_addr <= addr < (r.parent_addr + r.size): addr = addr - r.parent_addr + r.bus_addr break return addr def tostruct(self): properties = [] for k,v in itertools.chain(self._properties.items()): t, is_template = self._types.get(k, (None, False)) value = build_prop(self._path, k, v, t=t) properties.append({ "name": k, "size": len(value) | (0x80000000 if is_template else 0), "value": value }) data = { "property_count": len(self._properties), "child_count": len(self._children), "properties": properties, "children": [c.tostruct() for c in self._children] } return data def build(self): return ADTNodeStruct.build(self.tostruct()) def walk_tree(self): yield self for child in self: yield from child def build_addr_lookup(self): lookup = AddrLookup() for node in self.walk_tree(): reg = getattr(node, 'reg', None) if not isinstance(reg, list): continue for index in range(len(reg)): try: addr, size = node.get_reg(index) except AttributeError: continue if size == 0: continue lookup.add(range(addr, addr + size), node.name + f"[{index}]") return lookup def create_node(self, name): while name.startswith("/"): name = name[1:] if "/" in name: a, b = name.split("/", 1) return self[a].create_node(b) node = ADTNode(path=self._path + "/", parent=self) node.name = name node._types["reg"] = (SafeGreedyRange(node._reg_struct), False) self[name] = node return node def pmgr_init(self): self.pmgr_u8id = (self["/arm-io/pmgr"].devices[0].id1 != self["/arm-io/pmgr"].devices[1].id1) def pmgr_dev_get_id(self, dev): if self.pmgr_u8id: return dev.id1 else: return dev.id2 def pmgr_dev_get_parents(self, dev): if self.pmgr_u8id: return dev.parents_un.u8id.parents else: return dev.parents_un.u16id.parents def load_adt(data): node = ADTNode(ADTNodeStruct.parse(data)) node.pmgr_init() return node if __name__ == "__main__": import sys, argparse, pathlib parser = argparse.ArgumentParser(description='ADT test for m1n1') parser.add_argument('input', type=pathlib.Path) parser.add_argument('output', nargs='?', type=pathlib.Path) parser.add_argument('-r', '--retrieve', help='retrieve and store the adt from m1n1', action='store_true') parser.add_argument('-a', '--dump-addr', help='dump address lookup table', action='store_true') args = parser.parse_args() if args.retrieve: if args.input.exists(): print('Error "{}" exists!'.format(args.input)) sys.exit() from .setup import * adt_data = u.get_adt() args.input.write_bytes(adt_data) else: adt_data = args.input.read_bytes() adt = load_adt(adt_data) print(adt) new_data = adt.build() if args.output is not None: args.output.write_bytes(new_data) assert new_data == adt_data[:len(new_data)] assert adt_data[len(new_data):] == bytes(len(adt_data) - len(new_data)) if args.dump_addr: print("Address lookup table:") print(adt.build_addr_lookup())
0
0.924643
1
0.924643
game-dev
MEDIA
0.383498
game-dev
0.672285
1
0.672285
floe-audio/Floe
20,336
src/plugin/gui/gui_envelope.cpp
// Copyright 2018-2024 Sam Windell // SPDX-License-Identifier: GPL-3.0-or-later #include "gui_envelope.hpp" #include "gui.hpp" #include "gui_drawing_helpers.hpp" #include "gui_framework/colours.hpp" #include "gui_framework/gui_live_edit.hpp" #include "gui_widget_helpers.hpp" void GUIDoEnvelope(Gui* g, LayerProcessor* layer, Rect r, bool greyed_out, Array<LayerParamIndex, 4> adsr_layer_params, GuiEnvelopeType type) { ASSERT_EQ(adsr_layer_params.size, 4u); auto& imgui = g->imgui; auto& engine = g->engine; auto const max_attack_percent = 0.31f; auto const max_decay_percent = 0.31f; auto const max_release_percent = 0.31f; auto const sustain_point_percent = (max_attack_percent + max_decay_percent) + (1 - (max_attack_percent + max_decay_percent + max_release_percent)); auto const handle_size = r.w * 0.15f; auto const att_rel_slider_sensitivity = 170.0f; auto settings = imgui::DefWindow(); settings.pad_bottom_right = {}; settings.pad_top_left = {}; settings.draw_routine_window_background = [&handle_size](IMGUI_DRAW_WINDOW_BG_ARGS) { auto const& r = window->bounds.Reduced(handle_size / 2); auto const rounding = LiveSize(imgui, UiSizeId::CornerRounding); imgui.graphics->AddRectFilled(r.Min(), r.Max(), LiveCol(imgui, UiColMap::Envelope_Back), rounding); }; imgui.PushID(layer->index); DEFER { imgui.PopID(); }; imgui.BeginWindow(settings, imgui.GetID("envelope container"), r); DEFER { imgui.EndWindow(); }; auto const padded_x = handle_size / 2; auto const padded_y = handle_size / 2; auto const padded_height = imgui.Height() - handle_size; auto const padded_width = imgui.Width() - handle_size; auto const padded_bottom = imgui.Height() - (handle_size / 2); auto const attack_imgui_id = imgui.GetID("attack"); auto const dec_sus_imgui_id = imgui.GetID("dec-sus"); auto const release_imgui_id = imgui.GetID("release"); f32x2 attack_point; f32x2 decay_point; f32x2 sustain_point; f32x2 release_point; struct Range { f32 min; f32 max; }; Range attack_x_range; Range decay_x_range; Range release_x_range; { auto attack_param_id = ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[0]); auto attack_param = engine.processor.main_params.DescribedValue(attack_param_id); auto norm_attack_val = attack_param.LinearValue(); auto const get_x_coord_at_percent = [&](f32 percent) { auto const min_x = padded_x; auto const max_x = min_x + (max_attack_percent * padded_width); return MapFrom01(percent, min_x, max_x); }; attack_point = {get_x_coord_at_percent(norm_attack_val), padded_y}; attack_x_range.min = get_x_coord_at_percent(0); attack_x_range.max = get_x_coord_at_percent(1); Rect grabber = {.xywh {0, 0, attack_point.x + (handle_size / 2), imgui.Height()}}; auto const grabber_unregistered = grabber; MidiLearnMenu(g, attack_param_id, grabber_unregistered); imgui.RegisterAndConvertRect(&grabber); f32 new_value = norm_attack_val; bool changed = false; if (imgui.SliderBehavior(grabber, attack_imgui_id, new_value, attack_param.DefaultLinearValue(), att_rel_slider_sensitivity, {.slower_with_shift = true, .default_on_modifer = true})) { changed = true; } if (imgui.IsHotOrActive(attack_imgui_id)) { imgui.frame_output.cursor_type = CursorType::HorizontalArrows; if (imgui::ClickCheck( { .left_mouse = true, .double_click = true, .triggers_on_mouse_down = true, }, imgui.frame_input)) g->param_text_editor_to_open = attack_param_id; } if (imgui.WasJustActivated(attack_imgui_id)) ParameterJustStartedMoving(engine.processor, attack_param_id); if (changed) SetParameterValue(engine.processor, attack_param_id, new_value, {}); if (imgui.WasJustDeactivated(attack_imgui_id)) ParameterJustStoppedMoving(engine.processor, attack_param_id); ParameterValuePopup(g, attack_param, attack_imgui_id, grabber_unregistered); DoParameterTooltipIfNeeded(g, attack_param, attack_imgui_id, grabber_unregistered); MacroAddDestinationRegion(g, grabber_unregistered, attack_param_id); } { auto decay_id = ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[1]); auto sustain_id = ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[2]); auto decay_param = engine.processor.main_params.DescribedValue(decay_id); auto sustain_param = engine.processor.main_params.DescribedValue(sustain_id); ParamIndex params[] = {decay_id, sustain_id}; DescribedParamValue const* param_ptrs[] = {&decay_param, &sustain_param}; auto const decay_norm_value = decay_param.LinearValue(); auto const sustain_norm_value = sustain_param.LinearValue(); auto const get_x_coord_at_percent = [&](f32 percent) { auto const min_x = attack_point.x; auto const max_x = min_x + (max_decay_percent * padded_width); return MapFrom01(percent, min_x, max_x); }; auto const get_y_coord_at_percent = [&](f32 percent) { auto const min_x = padded_x; auto const max_x = min_x + padded_height; return MapFrom01(percent, min_x, max_x); }; decay_point = {get_x_coord_at_percent(decay_norm_value), get_y_coord_at_percent(1 - sustain_norm_value)}; sustain_point = {padded_x + (sustain_point_percent * padded_width), decay_point.y}; decay_x_range.min = get_x_coord_at_percent(0); decay_x_range.max = get_x_coord_at_percent(1); auto const grabber_y = decay_point.y - (handle_size / 2); f32x2 const grabber_min {Min(decay_point.x - (handle_size / 2), attack_point.x + (handle_size / 2)), grabber_y}; f32x2 const grabber_max {sustain_point.x, imgui.Height()}; auto grabber = Rect::FromMinMax(grabber_min, grabber_max); auto const grabber_unregistered = grabber; MidiLearnMenu(g, params, grabber); imgui.RegisterAndConvertRect(&grabber); static f32x2 rel_click_pos; if (imgui.ButtonBehavior(grabber, dec_sus_imgui_id, {.left_mouse = true, .triggers_on_mouse_down = true})) { rel_click_pos = imgui.frame_input.cursor_pos - imgui.WindowPosToScreenPos(decay_point); } if (imgui.IsHotOrActive(dec_sus_imgui_id)) { imgui.frame_output.cursor_type = CursorType::AllArrows; if (imgui::ClickCheck( { .left_mouse = true, .double_click = true, .triggers_on_mouse_down = true, }, imgui.frame_input)) g->param_text_editor_to_open = decay_id; } if (imgui.WasJustActivated(dec_sus_imgui_id)) { ParameterJustStartedMoving(engine.processor, decay_id); ParameterJustStartedMoving(engine.processor, sustain_id); } if (imgui.IsActive(dec_sus_imgui_id)) { { auto const min_pixels_pos = imgui.WindowPosToScreenPos({get_x_coord_at_percent(0), 0}).x; auto const max_pixels_pos = imgui.WindowPosToScreenPos({get_x_coord_at_percent(1), 0}).x; auto curr_pos = imgui.frame_input.cursor_pos.x - rel_click_pos.x; curr_pos = Clamp(curr_pos, min_pixels_pos, max_pixels_pos); auto const curr_pos_percent = MapTo01(curr_pos, min_pixels_pos, max_pixels_pos); SetParameterValue(engine.processor, decay_id, curr_pos_percent, {}); } { auto const min_pixels_pos = imgui.WindowPosToScreenPos({0, get_y_coord_at_percent(0)}).y; auto const max_pixels_pos = imgui.WindowPosToScreenPos({0, get_y_coord_at_percent(1)}).y; auto curr_pos = imgui.frame_input.cursor_pos.y - rel_click_pos.y; curr_pos = Clamp(curr_pos, min_pixels_pos, max_pixels_pos); auto const curr_pos_percent = MapTo01(curr_pos, min_pixels_pos, max_pixels_pos); SetParameterValue(engine.processor, sustain_id, 1 - curr_pos_percent, {}); } } if (imgui.WasJustDeactivated(dec_sus_imgui_id)) { ParameterJustStoppedMoving(engine.processor, decay_id); ParameterJustStoppedMoving(engine.processor, sustain_id); } ParameterValuePopup(g, param_ptrs, dec_sus_imgui_id, grabber_unregistered); DoParameterTooltipIfNeeded(g, param_ptrs, dec_sus_imgui_id, grabber_unregistered); { auto const h = grabber_unregistered.h / 2; auto macro_r = grabber_unregistered; MacroAddDestinationRegion(g, rect_cut::CutTop(macro_r, h), decay_id); MacroAddDestinationRegion(g, rect_cut::CutTop(macro_r, h), sustain_id); } } { auto release_param_id = ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[3]); auto release_param = engine.processor.main_params.DescribedValue(release_param_id); auto const release_norm_value = release_param.LinearValue(); auto const get_x_coord_at_percent = [&](f32 percent) { auto const min_x = sustain_point.x; auto const max_x = min_x + (max_release_percent * padded_width); return MapFrom01(percent, min_x, max_x); }; release_point = {get_x_coord_at_percent(release_norm_value), padded_bottom}; release_x_range.min = get_x_coord_at_percent(0); release_x_range.max = get_x_coord_at_percent(1); Rect grabber {.xywh {sustain_point.x, 0, (max_release_percent * padded_width) + (handle_size / 2), imgui.Height()}}; auto const grabber_unregistered = grabber; MidiLearnMenu(g, release_param_id, grabber_unregistered); imgui.RegisterAndConvertRect(&grabber); f32 new_value = release_norm_value; bool changed = false; if (imgui.SliderBehavior(grabber, release_imgui_id, new_value, release_param.DefaultLinearValue(), att_rel_slider_sensitivity, {.slower_with_shift = true, .default_on_modifer = true})) { changed = true; } if (imgui.IsHotOrActive(release_imgui_id)) { imgui.frame_output.cursor_type = CursorType::HorizontalArrows; if (imgui::ClickCheck( { .left_mouse = true, .double_click = true, .triggers_on_mouse_down = true, }, imgui.frame_input)) g->param_text_editor_to_open = release_param_id; } if (imgui.WasJustActivated(release_imgui_id)) ParameterJustStartedMoving(engine.processor, release_param_id); if (changed) SetParameterValue(engine.processor, release_param_id, new_value, {}); if (imgui.WasJustDeactivated(release_imgui_id)) ParameterJustStoppedMoving(engine.processor, release_param_id); ParameterValuePopup(g, release_param, release_imgui_id, grabber_unregistered); DoParameterTooltipIfNeeded(g, release_param, release_imgui_id, grabber_unregistered); MacroAddDestinationRegion(g, grabber_unregistered, release_param_id); } { auto const attack_point_screen = imgui.WindowPosToScreenPos(attack_point); auto const decay_point_screen = imgui.WindowPosToScreenPos(decay_point); auto const sustain_point_screen = imgui.WindowPosToScreenPos(sustain_point); auto const release_point_screen = imgui.WindowPosToScreenPos(release_point); auto const bottom_left = imgui.WindowPosToScreenPos({padded_x, padded_bottom}); f32x2 const point_below_decay = {decay_point_screen.x, bottom_left.y}; auto const area_col = LiveCol(imgui, UiColMap::Envelope_Area); auto const range_lines_col = LiveCol(imgui, UiColMap::Envelope_RangeLines); auto const hover_col = LiveCol(imgui, UiColMap::Envelope_HandleHover); auto const greyed_out_line_col = LiveCol(imgui, UiColMap::Envelope_LineGreyedOut); auto const greyed_out_handle_col = LiveCol(imgui, UiColMap::Envelope_HandleGreyedOut); auto line_col = LiveCol(imgui, UiColMap::Envelope_Line); auto handle_col = LiveCol(imgui, UiColMap::Envelope_Handle); auto const handle_visible_size = handle_size / 10; // range lines auto const do_range_lines = [&](Range range, imgui::Id id) { if (imgui.IsActive(id)) { imgui.graphics->AddLine(imgui.WindowPosToScreenPos({range.min, padded_x}), imgui.WindowPosToScreenPos({range.min, padded_bottom}), range_lines_col); imgui.graphics->AddLine(imgui.WindowPosToScreenPos({range.max, padded_x}), imgui.WindowPosToScreenPos({range.max, padded_bottom}), range_lines_col); } }; do_range_lines(attack_x_range, attack_imgui_id); do_range_lines(decay_x_range, dec_sus_imgui_id); do_range_lines(release_x_range, release_imgui_id); // Area under line, done with poly fill instead of a series of triangles/rects because it gives // better results f32x2 area_points_a[4] = {bottom_left, attack_point_screen, decay_point_screen, point_below_decay}; f32x2 area_points_b[4] = {decay_point_screen, sustain_point_screen, release_point_screen, point_below_decay}; imgui.graphics->AddConvexPolyFilled(area_points_a, (int)ArraySize(area_points_a), area_col, false); imgui.graphics->AddConvexPolyFilled(area_points_b, (int)ArraySize(area_points_b), area_col, false); if (!greyed_out) { auto& voice_markers = type == GuiEnvelopeType::Volume ? engine.processor.voice_pool.voice_vol_env_markers_for_gui.Consume().data : engine.processor.voice_pool.voice_fil_env_markers_for_gui.Consume().data; for (auto const voice_index : ::Range(k_num_voices)) { auto const envelope_marker = voice_markers[voice_index]; if (envelope_marker.on && envelope_marker.layer_index == layer->index) { f32 target_pos = 0; f32 const env_pos = envelope_marker.pos / (f32)(UINT16_MAX); ASSERT(env_pos >= 0 && env_pos <= 1); switch (envelope_marker.state) { case adsr::State::Attack: { target_pos = bottom_left.x + env_pos * (attack_point_screen.x - bottom_left.x); break; } case adsr::State::Decay: { auto const sustain_level = envelope_marker.sustain_level / (f32)UINT16_MAX; ASSERT(sustain_level >= 0 && sustain_level <= 1); auto const pos = 1.0f - MapTo01(env_pos, sustain_level, 1.0f); target_pos = attack_point_screen.x + pos * (decay_point_screen.x - attack_point_screen.x); break; } case adsr::State::Sustain: { target_pos = decay_point_screen.x; break; } case adsr::State::Release: { auto const pos = 1.0f - env_pos; target_pos = sustain_point_screen.x + pos * (release_point_screen.x - sustain_point_screen.x); break; } default: PanicIfReached(); } auto& cursor = g->envelope_voice_cursors[(int)type][voice_index]; if (cursor.marker_id != envelope_marker.id) { cursor.cursor = bottom_left.x; cursor.cursor_smoother.Reset(); } cursor.marker_id = envelope_marker.id; cursor.cursor = target_pos; f32 const cursor_x = cursor.cursor_smoother.LowPass(cursor.cursor, 0.5f); Line line {}; if (cursor_x > sustain_point_screen.x) line = {sustain_point_screen, release_point_screen}; else if (cursor_x > decay_point_screen.x) line = {decay_point_screen, sustain_point_screen}; else if (cursor_x > attack_point_screen.x) line = {attack_point_screen, decay_point_screen}; else line = {bottom_left, attack_point_screen}; f32 cursor_y = attack_point_screen.y; if (auto p = line.IntersectionWithVerticalLine(cursor_x)) cursor_y = p->y; draw::VoiceMarkerLine(imgui, {cursor_x, cursor_y}, bottom_left.y - cursor_y, bottom_left.x, line); } } } // lines f32x2 line_points[5] = {bottom_left, attack_point_screen, decay_point_screen, sustain_point_screen, release_point_screen}; imgui.graphics ->AddPolyline(line_points, 5, greyed_out ? greyed_out_line_col : line_col, false, 1, true); // handles auto do_handle = [&](f32x2 point, u32 id) { auto col = greyed_out ? greyed_out_handle_col : handle_col; if (imgui.IsHot(id)) { auto background_col = colours::FromU32(col); background_col.a /= 2; imgui.graphics->AddCircleFilled(point, handle_size / 5, colours::ToU32(background_col)); col = hover_col; } if (imgui.IsActive(id)) col = hover_col; imgui.graphics->AddCircleFilled(point, handle_visible_size, col); }; do_handle(attack_point_screen, attack_imgui_id); do_handle(decay_point_screen, dec_sus_imgui_id); do_handle(release_point_screen, release_imgui_id); } if (g->param_text_editor_to_open) { ParamIndex const params[] = { ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[0]), ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[1]), ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[2]), ParamIndexFromLayerParamIndex(layer->index, adsr_layer_params[3]), }; auto const cut = imgui.Width() / 3; Rect const edit_r {.xywh {cut, 0, imgui.Width() - (cut * 2), imgui.Height()}}; HandleShowingTextEditorForParams(g, edit_r, params); } }
0
0.970841
1
0.970841
game-dev
MEDIA
0.38426
game-dev
0.865091
1
0.865091
CrypticMonkey33/ArchipelagoExplorersOfSky
3,765
worlds/saving_princess/Regions.py
from typing import List, Dict from BaseClasses import MultiWorld, Region, Entrance from . import Locations from .Constants import * region_dict: Dict[str, List[str]] = { REGION_MENU: [], REGION_CAVE: [ LOCATION_CAVE_AMMO, LOCATION_CAVE_RELOAD, LOCATION_CAVE_HEALTH, LOCATION_CAVE_WEAPON, EP_LOCATION_CAVE_MINIBOSS, EP_LOCATION_CAVE_BOSS, EVENT_LOCATION_GUARD_GONE, ], REGION_VOLCANIC: [ LOCATION_VOLCANIC_RELOAD, LOCATION_VOLCANIC_HEALTH, LOCATION_VOLCANIC_AMMO, LOCATION_VOLCANIC_WEAPON, EP_LOCATION_VOLCANIC_BOSS, EVENT_LOCATION_CLIFF_GONE, ], REGION_ARCTIC: [ LOCATION_ARCTIC_AMMO, LOCATION_ARCTIC_RELOAD, LOCATION_ARCTIC_HEALTH, LOCATION_ARCTIC_WEAPON, LOCATION_JACKET, EP_LOCATION_ARCTIC_BOSS, EVENT_LOCATION_ACE_GONE, ], REGION_HUB: [ LOCATION_HUB_AMMO, LOCATION_HUB_HEALTH, LOCATION_HUB_RELOAD, EP_LOCATION_HUB_CONSOLE, EP_LOCATION_HUB_NINJA_SCARE, ], REGION_SWAMP: [ LOCATION_SWAMP_AMMO, LOCATION_SWAMP_HEALTH, LOCATION_SWAMP_RELOAD, LOCATION_SWAMP_SPECIAL, EP_LOCATION_SWAMP_BOSS, EVENT_LOCATION_SNAKE_GONE, ], REGION_ELECTRICAL: [ EP_LOCATION_ELEVATOR_NINJA_FIGHT, LOCATION_ELECTRICAL_WEAPON, EP_LOCATION_ELECTRICAL_MINIBOSS, EP_LOCATION_ELECTRICAL_EXTRA, EVENT_LOCATION_POWER_ON, ], REGION_ELECTRICAL_POWERED: [ LOCATION_ELECTRICAL_RELOAD, LOCATION_ELECTRICAL_HEALTH, LOCATION_ELECTRICAL_AMMO, EP_LOCATION_ELECTRICAL_BOSS, EP_LOCATION_ELECTRICAL_FINAL_BOSS, EVENT_LOCATION_VICTORY, ], } def set_region_locations(region: Region, location_names: List[str], is_pool_expanded: bool): location_pool = {**Locations.location_dict_base, **Locations.location_dict_events} if is_pool_expanded: location_pool = {**Locations.location_dict_expanded, **Locations.location_dict_event_expanded} region.locations = [ Locations.SavingPrincessLocation( region.player, name, Locations.location_dict[name].code, region ) for name in location_names if name in location_pool.keys() ] def create_regions(multiworld: MultiWorld, player: int, is_pool_expanded: bool): for region_name, location_names in region_dict.items(): region = Region(region_name, player, multiworld) set_region_locations(region, location_names, is_pool_expanded) multiworld.regions.append(region) connect_regions(multiworld, player) def connect_regions(multiworld: MultiWorld, player: int): # and add a connection from the menu to the hub region menu = multiworld.get_region(REGION_MENU, player) hub = multiworld.get_region(REGION_HUB, player) connection = Entrance(player, f"{REGION_HUB} entrance", menu) menu.exits.append(connection) connection.connect(hub) # now add an entrance from every other region to hub for region_name in [REGION_CAVE, REGION_VOLCANIC, REGION_ARCTIC, REGION_SWAMP, REGION_ELECTRICAL]: connection = Entrance(player, f"{region_name} entrance", hub) hub.exits.append(connection) connection.connect(multiworld.get_region(region_name, player)) # and finally, the connection between the final region and its powered version electrical = multiworld.get_region(REGION_ELECTRICAL, player) connection = Entrance(player, f"{REGION_ELECTRICAL_POWERED} entrance", electrical) electrical.exits.append(connection) connection.connect(multiworld.get_region(REGION_ELECTRICAL_POWERED, player))
0
0.601918
1
0.601918
game-dev
MEDIA
0.902904
game-dev
0.670333
1
0.670333