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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
EclipseMenu/EclipseMenu | 2,134 | src/hacks/Level/LegacyReversePhysics.cpp | #include <modules/config/config.hpp>
#include <modules/gui/gui.hpp>
#include <modules/gui/components/toggle.hpp>
#include <modules/hack/hack.hpp>
#include <Geode/modify/LevelSettingsObject.hpp>
#include <Geode/modify/PlayLayer.hpp>
namespace eclipse::hacks::Level {
class $modify(LegacyPhysicsPlayLayer, PlayLayer) {
struct Fields {
bool originalFixGravityVal = false;
};
void toggleFixGravityBugState(bool newState) {
m_levelSettings->m_fixGravityBug = newState ? false : m_fields->originalFixGravityVal;
}
bool init(GJGameLevel* level, bool useReplay, bool dontCreateObjects) {
if (!PlayLayer::init(level, useReplay, dontCreateObjects)) return false;
m_fields->originalFixGravityVal = m_levelSettings->m_fixGravityBug;
if (config::get<bool>("level.legacyreversephysics", false))
m_levelSettings->m_fixGravityBug = false;
return true;
}
};
class $hack(LegacyReversePhysics) {
void init() override {
auto tab = gui::MenuTab::find("tab.level");
tab->addToggle("level.legacyreversephysics")->handleKeybinds()->setDescription()
->callback([](bool newState) {
if (auto pl = utils::get<PlayLayer>()) {
static_cast<LegacyPhysicsPlayLayer*>(pl)->toggleFixGravityBugState(newState);
}
});
}
//player would be cheating only if level is new physics and legacy physics is active
//otherwise the hack being on doesn't matter
[[nodiscard]] bool isCheating() const override {
auto legacyPhysics = config::get<"level.legacyreversephysics", bool>();
if (!legacyPhysics) return false;
auto pl = utils::get<PlayLayer>();
if (!pl) return false;
return static_cast<LegacyPhysicsPlayLayer*>(pl)->m_fields->originalFixGravityVal;
}
[[nodiscard]] const char* getId() const override { return "Legacy Reverse Physics"; }
};
REGISTER_HACK(LegacyReversePhysics)
}
| 0 | 0.84681 | 1 | 0.84681 | game-dev | MEDIA | 0.960655 | game-dev | 0.872645 | 1 | 0.872645 |
teeworldsmods2/Teeworlds-Example | 24,402 | src/game/client/components/menus_demo.cpp | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <base/math.h>
#include <engine/demo.h>
#include <engine/keys.h>
#include <engine/graphics.h>
#include <engine/textrender.h>
#include <engine/storage.h>
#include <game/client/render.h>
#include <game/client/gameclient.h>
#include <game/localization.h>
#include <game/client/ui.h>
#include <game/generated/client_data.h>
#include "maplayers.h"
#include "menus.h"
int CMenus::DoButton_DemoPlayer(const void *pID, const char *pText, int Checked, const CUIRect *pRect)
{
RenderTools()->DrawUIRect(pRect, vec4(1,1,1, Checked ? 0.10f : 0.5f)*ButtonColorMul(pID), CUI::CORNER_ALL, 5.0f);
UI()->DoLabel(pRect, pText, 14.0f, 0);
return UI()->DoButtonLogic(pID, pText, Checked, pRect);
}
int CMenus::DoButton_Sprite(const void *pID, int ImageID, int SpriteID, int Checked, const CUIRect *pRect, int Corners)
{
RenderTools()->DrawUIRect(pRect, Checked ? vec4(1.0f, 1.0f, 1.0f, 0.10f) : vec4(1.0f, 1.0f, 1.0f, 0.5f)*ButtonColorMul(pID), Corners, 5.0f);
Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id);
Graphics()->QuadsBegin();
if(!Checked)
Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f);
RenderTools()->SelectSprite(SpriteID);
IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
return UI()->DoButtonLogic(pID, "", Checked, pRect);
}
void CMenus::RenderDemoPlayer(CUIRect MainView)
{
const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
const float SeekBarHeight = 15.0f;
const float ButtonbarHeight = 20.0f;
const float NameBarHeight = 20.0f;
const float Margins = 5.0f;
float TotalHeight;
if(m_MenuActive)
TotalHeight = SeekBarHeight+ButtonbarHeight+NameBarHeight+Margins*3;
else
TotalHeight = SeekBarHeight+Margins*2;
MainView.HSplitBottom(TotalHeight, 0, &MainView);
MainView.VSplitLeft(50.0f, 0, &MainView);
MainView.VSplitRight(450.0f, &MainView, 0);
RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_T, 10.0f);
MainView.Margin(5.0f, &MainView);
CUIRect SeekBar, ButtonBar, NameBar;
int CurrentTick = pInfo->m_CurrentTick - pInfo->m_FirstTick;
int TotalTicks = pInfo->m_LastTick - pInfo->m_FirstTick;
if(m_MenuActive)
{
MainView.HSplitTop(SeekBarHeight, &SeekBar, &ButtonBar);
ButtonBar.HSplitTop(Margins, 0, &ButtonBar);
ButtonBar.HSplitBottom(NameBarHeight, &ButtonBar, &NameBar);
NameBar.HSplitTop(4.0f, 0, &NameBar);
}
else
SeekBar = MainView;
// do seekbar
{
static int s_SeekBarID = 0;
void *id = &s_SeekBarID;
char aBuffer[128];
// draw seek bar
RenderTools()->DrawUIRect(&SeekBar, vec4(0,0,0,0.5f), CUI::CORNER_ALL, 5.0f);
// draw filled bar
float Amount = CurrentTick/(float)TotalTicks;
CUIRect FilledBar = SeekBar;
FilledBar.w = 10.0f + (FilledBar.w-10.0f)*Amount;
RenderTools()->DrawUIRect(&FilledBar, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f);
// draw markers
for(int i = 0; i < pInfo->m_NumTimelineMarkers; i++)
{
float Ratio = (pInfo->m_aTimelineMarkers[i]-pInfo->m_FirstTick) / (float)TotalTicks;
Graphics()->TextureSet(-1);
Graphics()->QuadsBegin();
Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
IGraphics::CQuadItem QuadItem(SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
}
// draw time
str_format(aBuffer, sizeof(aBuffer), "%d:%02d / %d:%02d",
CurrentTick/SERVER_TICK_SPEED/60, (CurrentTick/SERVER_TICK_SPEED)%60,
TotalTicks/SERVER_TICK_SPEED/60, (TotalTicks/SERVER_TICK_SPEED)%60);
UI()->DoLabel(&SeekBar, aBuffer, SeekBar.h*0.70f, 0);
// do the logic
int Inside = UI()->MouseInside(&SeekBar);
if(UI()->ActiveItem() == id)
{
if(!UI()->MouseButton(0))
UI()->SetActiveItem(0);
else
{
static float PrevAmount = 0.0f;
float Amount = (UI()->MouseX()-SeekBar.x)/(float)SeekBar.w;
if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount-Amount) >= 0.01f)
{
PrevAmount = Amount;
m_pClient->OnReset();
m_pClient->m_SuppressEvents = true;
DemoPlayer()->SetPos(Amount);
m_pClient->m_SuppressEvents = false;
m_pClient->m_pMapLayersBackGround->EnvelopeUpdate();
m_pClient->m_pMapLayersForeGround->EnvelopeUpdate();
}
}
}
else if(UI()->HotItem() == id)
{
if(UI()->MouseButton(0))
UI()->SetActiveItem(id);
}
if(Inside)
UI()->SetHotItem(id);
}
if(CurrentTick == TotalTicks)
{
m_pClient->OnReset();
DemoPlayer()->Pause();
DemoPlayer()->SetPos(0);
}
bool IncreaseDemoSpeed = false, DecreaseDemoSpeed = false;
if(m_MenuActive)
{
// do buttons
CUIRect Button;
// combined play and pause button
ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);
static int s_PlayPauseButton = 0;
if(!pInfo->m_Paused)
{
if(DoButton_Sprite(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PAUSE, false, &Button, CUI::CORNER_ALL))
DemoPlayer()->Pause();
}
else
{
if(DoButton_Sprite(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PLAY, false, &Button, CUI::CORNER_ALL))
DemoPlayer()->Unpause();
}
// stop button
ButtonBar.VSplitLeft(Margins, 0, &ButtonBar);
ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);
static int s_ResetButton = 0;
if(DoButton_Sprite(&s_ResetButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_STOP, false, &Button, CUI::CORNER_ALL))
{
m_pClient->OnReset();
DemoPlayer()->Pause();
DemoPlayer()->SetPos(0);
}
// slowdown
ButtonBar.VSplitLeft(Margins, 0, &ButtonBar);
ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);
static int s_SlowDownButton = 0;
if(DoButton_Sprite(&s_SlowDownButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_SLOWER, 0, &Button, CUI::CORNER_ALL) || Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))
DecreaseDemoSpeed = true;
// fastforward
ButtonBar.VSplitLeft(Margins, 0, &ButtonBar);
ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);
static int s_FastForwardButton = 0;
if(DoButton_Sprite(&s_FastForwardButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_FASTER, 0, &Button, CUI::CORNER_ALL))
IncreaseDemoSpeed = true;
// speed meter
ButtonBar.VSplitLeft(Margins*3, 0, &ButtonBar);
char aBuffer[64];
if(pInfo->m_Speed >= 1.0f)
str_format(aBuffer, sizeof(aBuffer), "x%.0f", pInfo->m_Speed);
else
str_format(aBuffer, sizeof(aBuffer), "x%.2f", pInfo->m_Speed);
UI()->DoLabel(&ButtonBar, aBuffer, Button.h*0.7f, -1);
// close button
ButtonBar.VSplitRight(ButtonbarHeight*3, &ButtonBar, &Button);
static int s_ExitButton = 0;
if(DoButton_DemoPlayer(&s_ExitButton, Localize("Close"), 0, &Button))
Client()->Disconnect();
// demo name
char aDemoName[64] = {0};
DemoPlayer()->GetDemoName(aDemoName, sizeof(aDemoName));
char aBuf[128];
str_format(aBuf, sizeof(aBuf), Localize("Demofile: %s"), aDemoName);
CTextCursor Cursor;
TextRender()->SetCursor(&Cursor, NameBar.x, NameBar.y, Button.h*0.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
Cursor.m_LineWidth = MainView.w;
TextRender()->TextEx(&Cursor, aBuf, -1);
}
if(IncreaseDemoSpeed || Input()->KeyPresses(KEY_MOUSE_WHEEL_UP))
{
if(pInfo->m_Speed < 0.1f) DemoPlayer()->SetSpeed(0.1f);
else if(pInfo->m_Speed < 0.25f) DemoPlayer()->SetSpeed(0.25f);
else if(pInfo->m_Speed < 0.5f) DemoPlayer()->SetSpeed(0.5f);
else if(pInfo->m_Speed < 0.75f) DemoPlayer()->SetSpeed(0.75f);
else if(pInfo->m_Speed < 1.0f) DemoPlayer()->SetSpeed(1.0f);
else if(pInfo->m_Speed < 2.0f) DemoPlayer()->SetSpeed(2.0f);
else if(pInfo->m_Speed < 4.0f) DemoPlayer()->SetSpeed(4.0f);
else DemoPlayer()->SetSpeed(8.0f);
}
else if(DecreaseDemoSpeed || Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))
{
if(pInfo->m_Speed > 4.0f) DemoPlayer()->SetSpeed(4.0f);
else if(pInfo->m_Speed > 2.0f) DemoPlayer()->SetSpeed(2.0f);
else if(pInfo->m_Speed > 1.0f) DemoPlayer()->SetSpeed(1.0f);
else if(pInfo->m_Speed > 0.75f) DemoPlayer()->SetSpeed(0.75f);
else if(pInfo->m_Speed > 0.5f) DemoPlayer()->SetSpeed(0.5f);
else if(pInfo->m_Speed > 0.25f) DemoPlayer()->SetSpeed(0.25f);
else if(pInfo->m_Speed > 0.1f) DemoPlayer()->SetSpeed(0.1f);
else DemoPlayer()->SetSpeed(0.05f);
}
}
static CUIRect gs_ListBoxOriginalView;
static CUIRect gs_ListBoxView;
static float gs_ListBoxRowHeight;
static int gs_ListBoxItemIndex;
static int gs_ListBoxSelectedIndex;
static int gs_ListBoxNewSelected;
static int gs_ListBoxDoneEvents;
static int gs_ListBoxNumItems;
static int gs_ListBoxItemsPerRow;
static float gs_ListBoxScrollValue;
static bool gs_ListBoxItemActivated;
void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHeight, const char *pTitle, const char *pBottomText, int NumItems,
int ItemsPerRow, int SelectedIndex, float ScrollValue)
{
CUIRect Scroll, Row;
CUIRect View = *pRect;
CUIRect Header, Footer;
// draw header
View.HSplitTop(ms_ListheaderHeight, &Header, &View);
RenderTools()->DrawUIRect(&Header, vec4(1,1,1,0.25f), CUI::CORNER_T, 5.0f);
UI()->DoLabel(&Header, pTitle, Header.h*ms_FontmodHeight, 0);
// draw footers
View.HSplitBottom(ms_ListheaderHeight, &View, &Footer);
RenderTools()->DrawUIRect(&Footer, vec4(1,1,1,0.25f), CUI::CORNER_B, 5.0f);
Footer.VSplitLeft(10.0f, 0, &Footer);
UI()->DoLabel(&Footer, pBottomText, Header.h*ms_FontmodHeight, 0);
// background
RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.15f), 0, 0);
// prepare the scroll
View.VSplitRight(15, &View, &Scroll);
// setup the variables
gs_ListBoxOriginalView = View;
gs_ListBoxSelectedIndex = SelectedIndex;
gs_ListBoxNewSelected = SelectedIndex;
gs_ListBoxItemIndex = 0;
gs_ListBoxRowHeight = RowHeight;
gs_ListBoxNumItems = NumItems;
gs_ListBoxItemsPerRow = ItemsPerRow;
gs_ListBoxDoneEvents = 0;
gs_ListBoxScrollValue = ScrollValue;
gs_ListBoxItemActivated = false;
// do the scrollbar
View.HSplitTop(gs_ListBoxRowHeight, &Row, 0);
int NumViewable = (int)(gs_ListBoxOriginalView.h/Row.h) + 1;
int Num = (NumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1;
if(Num < 0)
Num = 0;
if(Num > 0)
{
if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View))
gs_ListBoxScrollValue -= 3.0f/Num;
if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View))
gs_ListBoxScrollValue += 3.0f/Num;
if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f;
if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f;
}
Scroll.HMargin(5.0f, &Scroll);
gs_ListBoxScrollValue = DoScrollbarV(pID, &Scroll, gs_ListBoxScrollValue);
// the list
gs_ListBoxView = gs_ListBoxOriginalView;
gs_ListBoxView.VMargin(5.0f, &gs_ListBoxView);
UI()->ClipEnable(&gs_ListBoxView);
gs_ListBoxView.y -= gs_ListBoxScrollValue*Num*Row.h;
}
CMenus::CListboxItem CMenus::UiDoListboxNextRow()
{
static CUIRect s_RowView;
CListboxItem Item = {0};
if(gs_ListBoxItemIndex%gs_ListBoxItemsPerRow == 0)
gs_ListBoxView.HSplitTop(gs_ListBoxRowHeight /*-2.0f*/, &s_RowView, &gs_ListBoxView);
s_RowView.VSplitLeft(s_RowView.w/(gs_ListBoxItemsPerRow-gs_ListBoxItemIndex%gs_ListBoxItemsPerRow)/(UI()->Scale()), &Item.m_Rect, &s_RowView);
Item.m_Visible = 1;
//item.rect = row;
Item.m_HitRect = Item.m_Rect;
//CUIRect select_hit_box = item.rect;
if(gs_ListBoxSelectedIndex == gs_ListBoxItemIndex)
Item.m_Selected = 1;
// make sure that only those in view can be selected
if(Item.m_Rect.y+Item.m_Rect.h > gs_ListBoxOriginalView.y)
{
if(Item.m_HitRect.y < gs_ListBoxOriginalView.y) // clip the selection
{
Item.m_HitRect.h -= gs_ListBoxOriginalView.y-Item.m_HitRect.y;
Item.m_HitRect.y = gs_ListBoxOriginalView.y;
}
}
else
Item.m_Visible = 0;
// check if we need to do more
if(Item.m_Rect.y > gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h)
Item.m_Visible = 0;
gs_ListBoxItemIndex++;
return Item;
}
CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected)
{
int ThisItemIndex = gs_ListBoxItemIndex;
if(Selected)
{
if(gs_ListBoxSelectedIndex == gs_ListBoxNewSelected)
gs_ListBoxNewSelected = ThisItemIndex;
gs_ListBoxSelectedIndex = ThisItemIndex;
}
CListboxItem Item = UiDoListboxNextRow();
if(Item.m_Visible && UI()->DoButtonLogic(pId, "", gs_ListBoxSelectedIndex == gs_ListBoxItemIndex, &Item.m_HitRect))
gs_ListBoxNewSelected = ThisItemIndex;
// process input, regard selected index
if(gs_ListBoxSelectedIndex == ThisItemIndex)
{
if(!gs_ListBoxDoneEvents)
{
gs_ListBoxDoneEvents = 1;
if(m_EnterPressed || (UI()->ActiveItem() == pId && Input()->MouseDoubleClick()))
{
gs_ListBoxItemActivated = true;
UI()->SetActiveItem(0);
}
else
{
for(int i = 0; i < m_NumInputEvents; i++)
{
int NewIndex = -1;
if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS)
{
if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = gs_ListBoxNewSelected + 1;
if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = gs_ListBoxNewSelected - 1;
}
if(NewIndex > -1 && NewIndex < gs_ListBoxNumItems)
{
// scroll
float Offset = (NewIndex/gs_ListBoxItemsPerRow-gs_ListBoxNewSelected/gs_ListBoxItemsPerRow)*gs_ListBoxRowHeight;
int Scroll = gs_ListBoxOriginalView.y > Item.m_Rect.y+Offset ? -1 :
gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h < Item.m_Rect.y+Item.m_Rect.h+Offset ? 1 : 0;
if(Scroll)
{
int NumViewable = (int)(gs_ListBoxOriginalView.h/gs_ListBoxRowHeight) + 1;
int ScrollNum = (gs_ListBoxNumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1;
if(Scroll < 0)
{
int Num = (gs_ListBoxOriginalView.y-Item.m_Rect.y-Offset+gs_ListBoxRowHeight-1.0f)/gs_ListBoxRowHeight;
gs_ListBoxScrollValue -= (1.0f/ScrollNum)*Num;
}
else
{
int Num = (Item.m_Rect.y+Item.m_Rect.h+Offset-(gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h)+gs_ListBoxRowHeight-1.0f)/
gs_ListBoxRowHeight;
gs_ListBoxScrollValue += (1.0f/ScrollNum)*Num;
}
if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f;
if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f;
}
gs_ListBoxNewSelected = NewIndex;
}
}
}
}
//selected_index = i;
CUIRect r = Item.m_Rect;
r.Margin(1.5f, &r);
RenderTools()->DrawUIRect(&r, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f);
}
return Item;
}
int CMenus::UiDoListboxEnd(float *pScrollValue, bool *pItemActivated)
{
UI()->ClipDisable();
if(pScrollValue)
*pScrollValue = gs_ListBoxScrollValue;
if(pItemActivated)
*pItemActivated = gs_ListBoxItemActivated;
return gs_ListBoxNewSelected;
}
int CMenus::DemolistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser)
{
CMenus *pSelf = (CMenus *)pUser;
int Length = str_length(pName);
if((pName[0] == '.' && (pName[1] == 0 ||
(pName[1] == '.' && pName[2] == 0 && !str_comp(pSelf->m_aCurrentDemoFolder, "demos")))) ||
(!IsDir && (Length < 5 || str_comp(pName+Length-5, ".demo"))))
return 0;
CDemoItem Item;
str_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename));
if(IsDir)
{
str_format(Item.m_aName, sizeof(Item.m_aName), "%s/", pName);
Item.m_Valid = false;
}
else
{
str_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-4));
Item.m_InfosLoaded = false;
}
Item.m_IsDir = IsDir != 0;
Item.m_StorageType = StorageType;
pSelf->m_lDemos.add_unsorted(Item);
return 0;
}
void CMenus::DemolistPopulate()
{
m_lDemos.clear();
if(!str_comp(m_aCurrentDemoFolder, "demos"))
m_DemolistStorageType = IStorage::TYPE_ALL;
Storage()->ListDirectory(m_DemolistStorageType, m_aCurrentDemoFolder, DemolistFetchCallback, this);
m_lDemos.sort_range();
}
void CMenus::DemolistOnUpdate(bool Reset)
{
m_DemolistSelectedIndex = Reset ? m_lDemos.size() > 0 ? 0 : -1 :
m_DemolistSelectedIndex >= m_lDemos.size() ? m_lDemos.size()-1 : m_DemolistSelectedIndex;
m_DemolistSelectedIsDir = m_DemolistSelectedIndex < 0 ? false : m_lDemos[m_DemolistSelectedIndex].m_IsDir;
}
void CMenus::RenderDemoList(CUIRect MainView)
{
static int s_Inited = 0;
if(!s_Inited)
{
DemolistPopulate();
DemolistOnUpdate(true);
s_Inited = 1;
}
char aFooterLabel[128] = {0};
if(m_DemolistSelectedIndex >= 0)
{
CDemoItem *Item = &m_lDemos[m_DemolistSelectedIndex];
if(str_comp(Item->m_aFilename, "..") == 0)
str_copy(aFooterLabel, Localize("Parent Folder"), sizeof(aFooterLabel));
else if(m_DemolistSelectedIsDir)
str_copy(aFooterLabel, Localize("Folder"), sizeof(aFooterLabel));
else
{
if(!Item->m_InfosLoaded)
{
char aBuffer[512];
str_format(aBuffer, sizeof(aBuffer), "%s/%s", m_aCurrentDemoFolder, Item->m_aFilename);
Item->m_Valid = DemoPlayer()->GetDemoInfo(Storage(), aBuffer, Item->m_StorageType, &Item->m_Info);
Item->m_InfosLoaded = true;
}
if(!Item->m_Valid)
str_copy(aFooterLabel, Localize("Invalid Demo"), sizeof(aFooterLabel));
else
str_copy(aFooterLabel, Localize("Demo details"), sizeof(aFooterLabel));
}
}
// render background
RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f);
MainView.Margin(10.0f, &MainView);
CUIRect ButtonBar, RefreshRect, PlayRect, DeleteRect, RenameRect, FileIcon, ListBox;
MainView.HSplitBottom(ms_ButtonHeight+5.0f, &MainView, &ButtonBar);
ButtonBar.HSplitTop(5.0f, 0, &ButtonBar);
ButtonBar.VSplitRight(130.0f, &ButtonBar, &PlayRect);
ButtonBar.VSplitLeft(130.0f, &RefreshRect, &ButtonBar);
ButtonBar.VSplitLeft(10.0f, 0, &ButtonBar);
ButtonBar.VSplitLeft(120.0f, &DeleteRect, &ButtonBar);
ButtonBar.VSplitLeft(10.0f, 0, &ButtonBar);
ButtonBar.VSplitLeft(120.0f, &RenameRect, &ButtonBar);
MainView.HSplitBottom(140.0f, &ListBox, &MainView);
// render demo info
MainView.VMargin(5.0f, &MainView);
MainView.HSplitBottom(5.0f, &MainView, 0);
RenderTools()->DrawUIRect(&MainView, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f);
if(!m_DemolistSelectedIsDir && m_DemolistSelectedIndex >= 0 && m_lDemos[m_DemolistSelectedIndex].m_Valid)
{
CUIRect Left, Right, Labels;
MainView.Margin(20.0f, &MainView);
MainView.VSplitMid(&Labels, &MainView);
// left side
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(150.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Created:"), 14.0f, -1);
UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aTimestamp, 14.0f, -1);
Labels.HSplitTop(5.0f, 0, &Labels);
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(150.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Type:"), 14.0f, -1);
UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aType, 14.0f, -1);
Labels.HSplitTop(5.0f, 0, &Labels);
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(150.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Length:"), 14.0f, -1);
int Length = ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[0]<<24)&0xFF000000) | ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[1]<<16)&0xFF0000) |
((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[2]<<8)&0xFF00) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[3]&0xFF);
char aBuf[64];
str_format(aBuf, sizeof(aBuf), "%d:%02d", Length/60, Length%60);
UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1);
Labels.HSplitTop(5.0f, 0, &Labels);
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(150.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Version:"), 14.0f, -1);
str_format(aBuf, sizeof(aBuf), "%d", m_lDemos[m_DemolistSelectedIndex].m_Info.m_Version);
UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1);
// right side
Labels = MainView;
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(150.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Map:"), 14.0f, -1);
UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapName, 14.0f, -1);
Labels.HSplitTop(5.0f, 0, &Labels);
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(20.0f, 0, &Left);
Left.VSplitLeft(130.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Size:"), 14.0f, -1);
unsigned Size = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[1]<<16) |
(m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[3]);
str_format(aBuf, sizeof(aBuf), Localize("%d Bytes"), Size);
UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1);
Labels.HSplitTop(5.0f, 0, &Labels);
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(20.0f, 0, &Left);
Left.VSplitLeft(130.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Crc:"), 14.0f, -1);
unsigned Crc = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[1]<<16) |
(m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[3]);
str_format(aBuf, sizeof(aBuf), "%08x", Crc);
UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1);
Labels.HSplitTop(5.0f, 0, &Labels);
Labels.HSplitTop(20.0f, &Left, &Labels);
Left.VSplitLeft(150.0f, &Left, &Right);
UI()->DoLabelScaled(&Left, Localize("Netversion:"), 14.0f, -1);
UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aNetversion, 14.0f, -1);
}
static int s_DemoListId = 0;
static float s_ScrollValue = 0;
UiDoListboxStart(&s_DemoListId, &ListBox, 17.0f, Localize("Demos"), aFooterLabel, m_lDemos.size(), 1, m_DemolistSelectedIndex, s_ScrollValue);
for(sorted_array<CDemoItem>::range r = m_lDemos.all(); !r.empty(); r.pop_front())
{
CListboxItem Item = UiDoListboxNextItem((void*)(&r.front()));
if(Item.m_Visible)
{
Item.m_Rect.VSplitLeft(Item.m_Rect.h, &FileIcon, &Item.m_Rect);
Item.m_Rect.VSplitLeft(5.0f, 0, &Item.m_Rect);
DoButton_Icon(IMAGE_FILEICONS, r.front().m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_DEMO1, &FileIcon);
UI()->DoLabel(&Item.m_Rect, r.front().m_aName, Item.m_Rect.h*ms_FontmodHeight, -1);
}
}
bool Activated = false;
m_DemolistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, &Activated);
DemolistOnUpdate(false);
static int s_RefreshButton = 0;
if(DoButton_Menu(&s_RefreshButton, Localize("Refresh"), 0, &RefreshRect))
{
DemolistPopulate();
DemolistOnUpdate(false);
}
static int s_PlayButton = 0;
if(DoButton_Menu(&s_PlayButton, m_DemolistSelectedIsDir?Localize("Open"):Localize("Play"), 0, &PlayRect) || Activated)
{
if(m_DemolistSelectedIndex >= 0)
{
if(m_DemolistSelectedIsDir) // folder
{
if(str_comp(m_lDemos[m_DemolistSelectedIndex].m_aFilename, "..") == 0) // parent folder
fs_parent_dir(m_aCurrentDemoFolder);
else // sub folder
{
char aTemp[256];
str_copy(aTemp, m_aCurrentDemoFolder, sizeof(aTemp));
str_format(m_aCurrentDemoFolder, sizeof(m_aCurrentDemoFolder), "%s/%s", aTemp, m_lDemos[m_DemolistSelectedIndex].m_aFilename);
m_DemolistStorageType = m_lDemos[m_DemolistSelectedIndex].m_StorageType;
}
DemolistPopulate();
DemolistOnUpdate(true);
}
else // file
{
char aBuf[512];
str_format(aBuf, sizeof(aBuf), "%s/%s", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename);
const char *pError = Client()->DemoPlayer_Play(aBuf, m_lDemos[m_DemolistSelectedIndex].m_StorageType);
if(pError)
PopupMessage(Localize("Error"), str_comp(pError, "error loading demo") ? pError : Localize("Error loading demo"), Localize("Ok"));
else
{
UI()->SetActiveItem(0);
return;
}
}
}
}
if(!m_DemolistSelectedIsDir)
{
static int s_DeleteButton = 0;
if(DoButton_Menu(&s_DeleteButton, Localize("Delete"), 0, &DeleteRect) || m_DeletePressed)
{
if(m_DemolistSelectedIndex >= 0)
{
UI()->SetActiveItem(0);
m_Popup = POPUP_DELETE_DEMO;
return;
}
}
static int s_RenameButton = 0;
if(DoButton_Menu(&s_RenameButton, Localize("Rename"), 0, &RenameRect))
{
if(m_DemolistSelectedIndex >= 0)
{
UI()->SetActiveItem(0);
m_Popup = POPUP_RENAME_DEMO;
str_copy(m_aCurrentDemoFile, m_lDemos[m_DemolistSelectedIndex].m_aFilename, sizeof(m_aCurrentDemoFile));
return;
}
}
}
}
| 0 | 0.974009 | 1 | 0.974009 | game-dev | MEDIA | 0.672058 | game-dev | 0.952791 | 1 | 0.952791 |
Fast-64/fast64 | 27,146 | fast64_internal/z64/scene/properties.py | import bpy
from bpy.types import PropertyGroup, Object, Light, UILayout, Scene, Context
from bpy.props import (
EnumProperty,
IntProperty,
StringProperty,
CollectionProperty,
PointerProperty,
BoolProperty,
FloatVectorProperty,
)
from bpy.utils import register_class, unregister_class
from ...game_data import game_data
from ...render_settings import on_update_oot_render_settings
from ...utility import prop_split, customExportWarning
from ..cutscene.constants import ootEnumCSWriteType
from ..collection_utility import drawCollectionOps, drawAddButton
from ..utility import onMenuTabChange, onHeaderMenuTabChange, drawEnumWithCustom
from ..constants import (
ootEnumMusicSeq,
ootEnumSceneID,
ootEnumGlobalObject,
ootEnumNaviHints,
ootEnumSkyboxLighting,
ootEnumMapLocation,
ootEnumCameraMode,
ootEnumAudioSessionPreset,
ootEnumHeaderMenu,
ootEnumDrawConfig,
ootEnumHeaderMenuComplete,
)
ootEnumSceneMenuAlternate = [
("General", "General", "General"),
("Lighting", "Lighting", "Lighting"),
("Cutscene", "Cutscene", "Cutscene"),
("Exits", "Exits", "Exits"),
]
ootEnumSceneMenu = ootEnumSceneMenuAlternate + [
("Alternate", "Alternate", "Alternate"),
]
ootEnumLightGroupMenu = [
("Dawn", "Dawn", "Dawn"),
("Day", "Day", "Day"),
("Dusk", "Dusk", "Dusk"),
("Night", "Night", "Night"),
]
ootEnumTransitionAnims = [
("Custom", "Custom", "Custom"),
("0x00", "Spiky", "Spiky"),
("0x01", "Triforce", "Triforce"),
("0x02", "Slow Black Fade", "Slow Black Fade"),
("0x03", "Slow Day/White, Slow Night/Black Fade", "Slow Day/White, Slow Night/Black Fade"),
("0x04", "Fast Day/Black, Slow Night/Black Fade", "Fast Day/Black, Slow Night/Black Fade"),
("0x05", "Fast Day/White, Slow Night/Black Fade", "Fast Day/White, Slow Night/Black Fade"),
("0x06", "Very Slow Day/White, Slow Night/Black Fade", "Very Slow Day/White, Slow Night/Black Fade"),
("0x07", "Very Slow Day/White, Slow Night/Black Fade", "Very Slow Day/White, Slow Night/Black Fade"),
("0x0E", "Slow Sandstorm Fade", "Slow Sandstorm Fade"),
("0x0F", "Fast Sandstorm Fade", "Fast Sandstorm Fade"),
("0x20", "Iris Fade", "Iris Fade"),
("0x2C", "Shortcut Transition", "Shortcut Transition"),
]
ootEnumExitIndex = [
("Custom", "Custom", "Custom"),
("Default", "Default", "Default"),
]
class OOTSceneCommon:
ootEnumBootMode = [
("Play", "Play", "Play"),
("Map Select", "Map Select", "Map Select"),
("File Select", "File Select", "File Select"),
]
def isSceneObj(self, obj):
return obj.type == "EMPTY" and obj.ootEmptyType == "Scene"
class OOTSceneProperties(PropertyGroup):
write_dummy_room_list: BoolProperty(
name="Dummy Room List",
default=False,
description=(
"When exporting the scene to C, use NULL for the pointers to room "
"start/end offsets, instead of the appropriate symbols"
),
)
class OOTExitProperty(PropertyGroup):
expandTab: BoolProperty(name="Expand Tab")
exitIndex: EnumProperty(items=ootEnumExitIndex, default="Default")
exitIndexCustom: StringProperty(default="0x0000")
# These are used when adding an entry to gEntranceTable
scene: EnumProperty(items=ootEnumSceneID, default="SCENE_DEKU_TREE")
sceneCustom: StringProperty(default="SCENE_DEKU_TREE")
# These are used when adding an entry to gEntranceTable
continueBGM: BoolProperty(default=False)
displayTitleCard: BoolProperty(default=True)
fadeInAnim: EnumProperty(items=ootEnumTransitionAnims, default="0x02")
fadeInAnimCustom: StringProperty(default="0x02")
fadeOutAnim: EnumProperty(items=ootEnumTransitionAnims, default="0x02")
fadeOutAnimCustom: StringProperty(default="0x02")
def draw_props(self, layout: UILayout, index: int, headerIndex: int, objName: str):
box = layout.box()
box.prop(self, "expandTab", text="Exit " + str(index + 1), icon="TRIA_DOWN" if self.expandTab else "TRIA_RIGHT")
if self.expandTab:
drawCollectionOps(box, index, "Exit", headerIndex, objName)
drawEnumWithCustom(box, self, "exitIndex", "Exit Index", "")
if self.exitIndex != "Custom":
box.label(text='This is unfinished, use "Custom".')
exitGroup = box.column()
exitGroup.enabled = False
drawEnumWithCustom(exitGroup, self, "scene", "Scene", "")
exitGroup.prop(self, "continueBGM", text="Continue BGM")
exitGroup.prop(self, "displayTitleCard", text="Display Title Card")
drawEnumWithCustom(exitGroup, self, "fadeInAnim", "Fade In Animation", "")
drawEnumWithCustom(exitGroup, self, "fadeOutAnim", "Fade Out Animation", "")
class OOTLightProperty(PropertyGroup):
ambient: FloatVectorProperty(
name="Ambient Color",
size=4,
min=0,
max=1,
default=(70 / 255, 40 / 255, 57 / 255, 1),
subtype="COLOR",
update=on_update_oot_render_settings,
)
useCustomDiffuse0: BoolProperty(name="Use Custom Diffuse 0 Light Object", update=on_update_oot_render_settings)
useCustomDiffuse1: BoolProperty(name="Use Custom Diffuse 1 Light Object", update=on_update_oot_render_settings)
diffuse0: FloatVectorProperty(
name="",
size=4,
min=0,
max=1,
default=(180 / 255, 154 / 255, 138 / 255, 1),
subtype="COLOR",
update=on_update_oot_render_settings,
)
diffuse1: FloatVectorProperty(
name="",
size=4,
min=0,
max=1,
default=(20 / 255, 20 / 255, 60 / 255, 1),
subtype="COLOR",
update=on_update_oot_render_settings,
)
diffuse0Custom: PointerProperty(name="Diffuse 0", type=Light, update=on_update_oot_render_settings)
diffuse1Custom: PointerProperty(name="Diffuse 1", type=Light, update=on_update_oot_render_settings)
fogColor: FloatVectorProperty(
name="",
size=4,
min=0,
max=1,
default=(140 / 255, 120 / 255, 110 / 255, 1),
subtype="COLOR",
update=on_update_oot_render_settings,
)
fogNear: IntProperty(name="", default=993, min=0, max=2**10 - 1, update=on_update_oot_render_settings)
transitionSpeed: IntProperty(name="", default=1, min=0, max=63, update=on_update_oot_render_settings)
z_far: IntProperty(name="", default=0x3200, min=0, max=2**15 - 1, update=on_update_oot_render_settings)
expandTab: BoolProperty(name="Expand Tab")
def draw_props(
self, layout: UILayout, name: str, showExpandTab: bool, index: int, sceneHeaderIndex: int, objName: str
):
if showExpandTab:
box = layout.box().column()
box.prop(self, "expandTab", text=name, icon="TRIA_DOWN" if self.expandTab else "TRIA_RIGHT")
expandTab = self.expandTab
else:
box = layout
expandTab = True
if expandTab:
if index is not None:
drawCollectionOps(box, index, "Light", sceneHeaderIndex, objName)
prop_split(box, self, "ambient", "Ambient Color")
if self.useCustomDiffuse0:
prop_split(box, self, "diffuse0Custom", "Diffuse 0")
box.label(text="Make sure light is not part of scene hierarchy.", icon="FILE_PARENT")
else:
prop_split(box, self, "diffuse0", "Diffuse 0")
box.prop(self, "useCustomDiffuse0")
if self.useCustomDiffuse1:
prop_split(box, self, "diffuse1Custom", "Diffuse 1")
box.label(text="Make sure light is not part of scene hierarchy.", icon="FILE_PARENT")
else:
prop_split(box, self, "diffuse1", "Diffuse 1")
box.prop(self, "useCustomDiffuse1")
prop_split(box, self, "fogColor", "Fog Color")
prop_split(box, self, "fogNear", "Fog Near (Fog Far=1000)")
prop_split(box, self, "z_far", "Z Far (Draw Distance)")
prop_split(box, self, "transitionSpeed", "Transition Speed")
class OOTLightGroupProperty(PropertyGroup):
expandTab: BoolProperty()
menuTab: EnumProperty(items=ootEnumLightGroupMenu)
dawn: PointerProperty(type=OOTLightProperty)
day: PointerProperty(type=OOTLightProperty)
dusk: PointerProperty(type=OOTLightProperty)
night: PointerProperty(type=OOTLightProperty)
defaultsSet: BoolProperty()
def draw_props(self, layout: UILayout):
box = layout.column()
box.row().prop(self, "menuTab", expand=True)
if self.menuTab == "Dawn":
self.dawn.draw_props(box, "Dawn", False, None, None, None)
if self.menuTab == "Day":
self.day.draw_props(box, "Day", False, None, None, None)
if self.menuTab == "Dusk":
self.dusk.draw_props(box, "Dusk", False, None, None, None)
if self.menuTab == "Night":
self.night.draw_props(box, "Night", False, None, None, None)
class OOTSceneTableEntryProperty(PropertyGroup):
drawConfig: EnumProperty(items=ootEnumDrawConfig, name="Scene Draw Config", default="SDC_DEFAULT")
drawConfigCustom: StringProperty(name="Scene Draw Config Custom")
hasTitle: BoolProperty(default=True)
def draw_props(self, layout: UILayout):
drawEnumWithCustom(layout, self, "drawConfig", "Draw Config", "")
class OOTExtraCutsceneProperty(PropertyGroup):
csObject: PointerProperty(
name="Cutscene Object",
type=Object,
poll=lambda self, object: object.type == "EMPTY" and object.ootEmptyType == "Cutscene",
)
class OOTSceneHeaderProperty(PropertyGroup):
expandTab: BoolProperty(name="Expand Tab")
usePreviousHeader: BoolProperty(name="Use Previous Header", default=True)
globalObject: EnumProperty(name="Global Object", default="OBJECT_GAMEPLAY_DANGEON_KEEP", items=ootEnumGlobalObject)
globalObjectCustom: StringProperty(name="Global Object Custom", default="0x00")
naviCup: EnumProperty(name="Navi Hints", default="0x00", items=ootEnumNaviHints)
naviCupCustom: StringProperty(name="Navi Hints Custom", default="0x00")
skyboxID: EnumProperty(name="Skybox", items=lambda self, context: game_data.z64.get_enum("skybox"), default=2)
skyboxIDCustom: StringProperty(name="Skybox ID", default="0")
skyboxCloudiness: EnumProperty(
name="Cloudiness", items=lambda self, context: game_data.z64.get_enum("skybox_config"), default=1
)
skyboxCloudinessCustom: StringProperty(name="Cloudiness ID", default="0x00")
skyboxLighting: EnumProperty(
name="Skybox Lighting",
items=ootEnumSkyboxLighting,
default="LIGHT_MODE_TIME",
update=on_update_oot_render_settings,
)
skyboxLightingCustom: StringProperty(
name="Skybox Lighting Custom", default="0x00", update=on_update_oot_render_settings
)
mapLocation: EnumProperty(name="Map Location", items=ootEnumMapLocation, default="0x00")
mapLocationCustom: StringProperty(name="Skybox Lighting Custom", default="0x00")
cameraMode: EnumProperty(name="Camera Mode", items=ootEnumCameraMode, default="0x00")
cameraModeCustom: StringProperty(name="Camera Mode Custom", default="0x00")
musicSeq: EnumProperty(name="Music Sequence", items=ootEnumMusicSeq, default="NA_BGM_FIELD_LOGIC")
musicSeqCustom: StringProperty(name="Music Sequence ID", default="0x00")
nightSeq: EnumProperty(
name="Nighttime SFX", items=lambda self, context: game_data.z64.get_enum("nature_id"), default=1
)
nightSeqCustom: StringProperty(name="Nighttime SFX ID", default="0x00")
audioSessionPreset: EnumProperty(name="Audio Session Preset", items=ootEnumAudioSessionPreset, default="0x00")
audioSessionPresetCustom: StringProperty(name="Audio Session Preset", default="0x00")
timeOfDayLights: PointerProperty(type=OOTLightGroupProperty, name="Time Of Day Lighting")
lightList: CollectionProperty(type=OOTLightProperty, name="Lighting List")
exitList: CollectionProperty(type=OOTExitProperty, name="Exit List")
writeCutscene: BoolProperty(name="Write Cutscene")
csWriteType: EnumProperty(name="Cutscene Data Type", items=ootEnumCSWriteType, default="Object")
csWriteCustom: StringProperty(name="CS hdr var:", default="")
csWriteObject: PointerProperty(
name="Cutscene Object",
type=Object,
poll=lambda self, object: object.type == "EMPTY" and object.ootEmptyType == "Cutscene",
)
extraCutscenes: CollectionProperty(type=OOTExtraCutsceneProperty, name="Extra Cutscenes")
sceneTableEntry: PointerProperty(type=OOTSceneTableEntryProperty)
menuTab: EnumProperty(name="Menu", items=ootEnumSceneMenu, update=onMenuTabChange)
altMenuTab: EnumProperty(name="Menu", items=ootEnumSceneMenuAlternate)
appendNullEntrance: BoolProperty(
name="Append Null Entrance",
description="Add an additional {0, 0} to the end of the EntranceEntry list.",
default=False,
)
title_card_name: StringProperty(
name="Title Card", default="none", description="Segment name of the title card to use"
)
def draw_props(self, layout: UILayout, dropdownLabel: str, headerIndex: int, objName: str):
from .operators import OOT_SearchMusicSeqEnumOperator # temp circular import fix
if dropdownLabel is not None:
layout.prop(self, "expandTab", text=dropdownLabel, icon="TRIA_DOWN" if self.expandTab else "TRIA_RIGHT")
if not self.expandTab:
return
if headerIndex is not None and headerIndex > 3:
drawCollectionOps(layout, headerIndex - game_data.z64.cs_index_start, "Scene", None, objName)
if headerIndex is not None and headerIndex > 0 and headerIndex < game_data.z64.cs_index_start:
layout.prop(self, "usePreviousHeader", text="Use Previous Header")
if self.usePreviousHeader:
return
if headerIndex is None or headerIndex == 0:
layout.row().prop(self, "menuTab", expand=True)
menuTab = self.menuTab
else:
layout.row().prop(self, "altMenuTab", expand=True)
menuTab = self.altMenuTab
if menuTab == "General":
general = layout.column()
general.box().label(text="General")
drawEnumWithCustom(general, self, "globalObject", "Global Object", "")
drawEnumWithCustom(general, self, "naviCup", "Navi Hints", "")
if headerIndex is None or headerIndex == 0:
self.sceneTableEntry.draw_props(general)
prop_split(general, self, "title_card_name", "Title Card")
if bpy.context.scene.ootSceneExportSettings.customExport:
general.label(text="Custom Export Path enabled, title card will be ignored.", icon="INFO")
general.prop(self, "appendNullEntrance")
skyboxAndSound = layout.column()
skyboxAndSound.box().label(text="Skybox And Sound")
drawEnumWithCustom(skyboxAndSound, self, "skyboxID", "Skybox", "")
drawEnumWithCustom(skyboxAndSound, self, "skyboxCloudiness", "Cloudiness", "")
drawEnumWithCustom(skyboxAndSound, self, "musicSeq", "Music Sequence", "")
musicSearch = skyboxAndSound.operator(OOT_SearchMusicSeqEnumOperator.bl_idname, icon="VIEWZOOM")
musicSearch.objName = objName
musicSearch.headerIndex = headerIndex if headerIndex is not None else 0
drawEnumWithCustom(skyboxAndSound, self, "nightSeq", "Nighttime SFX", "")
drawEnumWithCustom(skyboxAndSound, self, "audioSessionPreset", "Audio Session Preset", "")
cameraAndWorldMap = layout.column()
cameraAndWorldMap.box().label(text="Camera And World Map")
drawEnumWithCustom(cameraAndWorldMap, self, "mapLocation", "Map Location", "")
drawEnumWithCustom(cameraAndWorldMap, self, "cameraMode", "Camera Mode", "")
elif menuTab == "Lighting":
lighting = layout.column()
lighting.box().label(text="Lighting List")
drawEnumWithCustom(lighting, self, "skyboxLighting", "Lighting Mode", "")
if self.skyboxLighting == "LIGHT_MODE_TIME": # Time of Day
self.timeOfDayLights.draw_props(lighting)
else:
for i in range(len(self.lightList)):
self.lightList[i].draw_props(lighting, "Lighting " + str(i), True, i, headerIndex, objName)
drawAddButton(lighting, len(self.lightList), "Light", headerIndex, objName)
elif menuTab == "Cutscene":
cutscene = layout.column()
r = cutscene.row()
r.prop(self, "writeCutscene", text="Write Cutscene")
if self.writeCutscene:
r.prop(self, "csWriteType", text="Data")
if self.csWriteType == "Custom":
cutscene.prop(self, "csWriteCustom")
else:
cutscene.prop(self, "csWriteObject")
if headerIndex is None or headerIndex == 0:
cutscene.label(text="Extra cutscenes (not in any header):")
for i in range(len(self.extraCutscenes)):
box = cutscene.box().column()
drawCollectionOps(box, i, "extraCutscenes", None, objName, True)
box.prop(self.extraCutscenes[i], "csObject", text="CS obj")
if len(self.extraCutscenes) == 0:
drawAddButton(cutscene, 0, "extraCutscenes", 0, objName)
elif menuTab == "Exits":
exitBox = layout.column()
exitBox.box().label(text="Exit List")
for i in range(len(self.exitList)):
self.exitList[i].draw_props(exitBox, i, headerIndex, objName)
drawAddButton(exitBox, len(self.exitList), "Exit", headerIndex, objName)
def update_cutscene_index(self: "OOTAlternateSceneHeaderProperty", context: Context):
if self.currentCutsceneIndex < game_data.z64.cs_index_start:
self.currentCutsceneIndex = game_data.z64.cs_index_start
onHeaderMenuTabChange(self, context)
class OOTAlternateSceneHeaderProperty(PropertyGroup):
childNightHeader: PointerProperty(name="Child Night Header", type=OOTSceneHeaderProperty)
adultDayHeader: PointerProperty(name="Adult Day Header", type=OOTSceneHeaderProperty)
adultNightHeader: PointerProperty(name="Adult Night Header", type=OOTSceneHeaderProperty)
cutsceneHeaders: CollectionProperty(type=OOTSceneHeaderProperty)
headerMenuTab: EnumProperty(name="Header Menu", items=ootEnumHeaderMenu, update=onHeaderMenuTabChange)
currentCutsceneIndex: IntProperty(default=1, update=update_cutscene_index)
def draw_props(self, layout: UILayout, objName: str):
headerSetup = layout.column()
# headerSetup.box().label(text = "Alternate Headers")
headerSetupBox = headerSetup.column()
headerSetupBox.row().prop(self, "headerMenuTab", expand=True)
if self.headerMenuTab == "Child Night":
self.childNightHeader.draw_props(headerSetupBox, None, 1, objName)
elif self.headerMenuTab == "Adult Day":
self.adultDayHeader.draw_props(headerSetupBox, None, 2, objName)
elif self.headerMenuTab == "Adult Night":
self.adultNightHeader.draw_props(headerSetupBox, None, 3, objName)
elif self.headerMenuTab == "Cutscene":
prop_split(headerSetup, self, "currentCutsceneIndex", "Cutscene Index")
drawAddButton(headerSetup, len(self.cutsceneHeaders), "Scene", None, objName)
index = self.currentCutsceneIndex
if index - game_data.z64.cs_index_start < len(self.cutsceneHeaders):
self.cutsceneHeaders[index - game_data.z64.cs_index_start].draw_props(headerSetup, None, index, objName)
else:
headerSetup.label(text="No cutscene header for this index.", icon="QUESTION")
class OOTBootupSceneOptions(PropertyGroup):
bootToScene: BoolProperty(default=False, name="Boot To Scene")
overrideHeader: BoolProperty(default=False, name="Override Header")
headerOption: EnumProperty(items=ootEnumHeaderMenuComplete, name="Header", default="Child Day")
spawnIndex: IntProperty(name="Spawn", min=0)
newGameOnly: BoolProperty(
default=False,
name="Override Scene On New Game Only",
description="Only use this starting scene after loading a new save file",
)
newGameName: StringProperty(default="Link", name="New Game Name")
bootMode: EnumProperty(default="Play", name="Boot Mode", items=OOTSceneCommon.ootEnumBootMode)
# see src/code/z_play.c:Play_Init() - can't access more than 16 cutscenes?
cutsceneIndex: IntProperty(min=4, max=19, default=4, name="Cutscene Index")
def draw_props(self, layout: UILayout):
layout.prop(self, "bootToScene", text="Boot To Scene (HackerOOT)")
if self.bootToScene:
layout.prop(self, "newGameOnly")
prop_split(layout, self, "bootMode", "Boot Mode")
if self.bootMode == "Play":
prop_split(layout, self, "newGameName", "New Game Name")
if self.bootMode != "Map Select":
prop_split(layout, self, "spawnIndex", "Spawn")
layout.prop(self, "overrideHeader")
if self.overrideHeader:
prop_split(layout, self, "headerOption", "Header Option")
if self.headerOption == "Cutscene":
prop_split(layout, self, "cutsceneIndex", "Cutscene Index")
class OOTRemoveSceneSettingsProperty(PropertyGroup):
name: StringProperty(name="Name", default="spot03")
subFolder: StringProperty(name="Subfolder", default="overworld")
customExport: BoolProperty(name="Custom Export Path")
option: EnumProperty(items=ootEnumSceneID, default="SCENE_DEKU_TREE")
def draw_props(self, layout: UILayout):
if self.option == "Custom":
prop_split(layout, self, "subFolder", "Subfolder")
prop_split(layout, self, "name", "Name")
class OOTExportSceneSettingsProperty(PropertyGroup):
name: StringProperty(name="Name", default="spot03")
subFolder: StringProperty(name="Subfolder", default="overworld")
exportPath: StringProperty(name="Directory", subtype="FILE_PATH")
customExport: BoolProperty(name="Custom Export Path")
singleFile: BoolProperty(
name="Export as Single File",
default=False,
description="Does not split the scene and rooms into multiple files.",
)
option: EnumProperty(items=ootEnumSceneID, default="SCENE_DEKU_TREE")
# keeping this on purpose, will be removed once old code is cleaned-up
useNewExporter: BoolProperty(name="Use New Exporter", default=True)
def draw_props(self, layout: UILayout):
if self.customExport:
prop_split(layout, self, "exportPath", "Directory")
prop_split(layout, self, "name", "Name")
customExportWarning(layout)
else:
if self.option == "Custom":
prop_split(layout, self, "subFolder", "Subfolder")
prop_split(layout, self, "name", "Name")
prop_split(layout, bpy.context.scene, "ootSceneExportObj", "Scene Object")
layout.prop(self, "singleFile")
layout.prop(self, "customExport")
# layout.prop(self, "useNewExporter")
class OOTImportSceneSettingsProperty(PropertyGroup):
name: StringProperty(name="Name", default="spot03")
subFolder: StringProperty(name="Subfolder", default="overworld")
destPath: StringProperty(name="Directory", subtype="FILE_PATH")
isCustomDest: BoolProperty(name="Custom Path")
includeMesh: BoolProperty(name="Mesh", default=True)
includeCollision: BoolProperty(name="Collision", default=True)
includeActors: BoolProperty(name="Actors", default=True)
includeCullGroups: BoolProperty(name="Cull Groups", default=True)
includeLights: BoolProperty(name="Lights", default=True)
includeCameras: BoolProperty(name="Cameras", default=True)
includePaths: BoolProperty(name="Paths", default=True)
includeWaterBoxes: BoolProperty(name="Water Boxes", default=True)
includeCutscenes: BoolProperty(name="Cutscenes", default=False)
option: EnumProperty(items=ootEnumSceneID, default="SCENE_DEKU_TREE")
def draw_props(self, layout: UILayout, sceneOption: str):
col = layout.column()
includeButtons1 = col.row(align=True)
includeButtons1.prop(self, "includeMesh", toggle=1)
includeButtons1.prop(self, "includeCollision", toggle=1)
includeButtons1.prop(self, "includeActors", toggle=1)
includeButtons2 = col.row(align=True)
includeButtons2.prop(self, "includeCullGroups", toggle=1)
includeButtons2.prop(self, "includeLights", toggle=1)
includeButtons2.prop(self, "includeCameras", toggle=1)
includeButtons3 = col.row(align=True)
includeButtons3.prop(self, "includePaths", toggle=1)
includeButtons3.prop(self, "includeWaterBoxes", toggle=1)
includeButtons3.prop(self, "includeCutscenes", toggle=1)
col.prop(self, "isCustomDest")
if self.isCustomDest:
prop_split(col, self, "destPath", "Directory")
prop_split(col, self, "name", "Name")
else:
if self.option == "Custom":
prop_split(col, self, "subFolder", "Subfolder")
prop_split(col, self, "name", "Name")
if "SCENE_JABU_JABU" in sceneOption:
col.label(text="Pulsing wall effect won't be imported.", icon="ERROR")
classes = (
OOTExitProperty,
OOTLightProperty,
OOTLightGroupProperty,
OOTSceneTableEntryProperty,
OOTExtraCutsceneProperty,
OOTSceneHeaderProperty,
OOTAlternateSceneHeaderProperty,
OOTBootupSceneOptions,
OOTRemoveSceneSettingsProperty,
OOTExportSceneSettingsProperty,
OOTImportSceneSettingsProperty,
)
def scene_props_register():
for cls in classes:
register_class(cls)
Object.ootSceneHeader = PointerProperty(type=OOTSceneHeaderProperty)
Object.ootAlternateSceneHeaders = PointerProperty(type=OOTAlternateSceneHeaderProperty)
Scene.ootSceneExportObj = PointerProperty(type=Object, poll=OOTSceneCommon.isSceneObj)
Scene.ootSceneExportSettings = PointerProperty(type=OOTExportSceneSettingsProperty)
Scene.ootSceneImportSettings = PointerProperty(type=OOTImportSceneSettingsProperty)
Scene.ootSceneRemoveSettings = PointerProperty(type=OOTRemoveSceneSettingsProperty)
def scene_props_unregister():
del Object.ootSceneHeader
del Object.ootAlternateSceneHeaders
del Scene.ootSceneExportObj
del Scene.ootSceneExportSettings
del Scene.ootSceneImportSettings
del Scene.ootSceneRemoveSettings
for cls in reversed(classes):
unregister_class(cls)
| 0 | 0.932248 | 1 | 0.932248 | game-dev | MEDIA | 0.348338 | game-dev | 0.977928 | 1 | 0.977928 |
GPUOpen-Archive/CodeXL | 6,511 | CodeXL/Components/GpuDebugging/AMDTOpenCLServer/src/csOpenCLHandleMonitor.cpp | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file csOpenCLHandleMonitor.cpp
///
//==================================================================================
//------------------------------ csOpenCLHandleMonitor.cpp ------------------------------
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTOSWrappers/Include/osDebugLog.h>
#include <AMDTOSWrappers/Include/osCriticalSectionLocker.h>
// Local:
#include <src/csOpenCLHandleMonitor.h>
// ---------------------------------------------------------------------------
// Name: csOpenCLHandleMonitor::csOpenCLHandleMonitor
// Description: Constructor.
// Arguments:
// Author: Sigal Algranaty
// Date: 8/12/2009
// ---------------------------------------------------------------------------
csOpenCLHandleMonitor::csOpenCLHandleMonitor()
{
}
// ---------------------------------------------------------------------------
// Name: csOpenCLHandleMonitor::~csOpenCLHandleMonitor
// Description: Destructor.
// Author: Sigal Algranaty
// Date: 8/12/2009
// ---------------------------------------------------------------------------
csOpenCLHandleMonitor::~csOpenCLHandleMonitor()
{
osCriticalSectionLocker mapCSLocker(m_clHandleObjectsMapAccessCS);
// Clear the object IDs:
gtMap<oaCLHandle, apCLObjectID*>::iterator iter = _clHandleObjectsMap.begin();
gtMap<oaCLHandle, apCLObjectID*>::iterator endIter = _clHandleObjectsMap.end();
for (; endIter != iter; iter++)
{
delete(*iter).second;
}
// Clear the map:
_clHandleObjectsMap.clear();
}
// ---------------------------------------------------------------------------
// Name: csOpenCLHandleMonitor::getCLHandleObjectDetails
// Description: Return an OpenCL object by its handle
// Arguments: void* ptr
// Return Val: apCLObjectID*
// Author: Sigal Algranaty
// Date: 8/12/2009
// ---------------------------------------------------------------------------
apCLObjectID* csOpenCLHandleMonitor::getCLHandleObjectDetails(oaCLHandle ptr) const
{
apCLObjectID* pRetVal = NULL;
// Do not attempt this if the critical section is locked:
if (((osCriticalSection&)m_clHandleObjectsMapAccessCS).tryEntering())
{
// Find the handle within the map:
gtMap<oaCLHandle, apCLObjectID*>::const_iterator iterFind = _clHandleObjectsMap.find(ptr);
if (iterFind != _clHandleObjectsMap.end())
{
pRetVal = (*iterFind).second;
}
((osCriticalSection&)m_clHandleObjectsMapAccessCS).leave();
}
return pRetVal;
}
// ---------------------------------------------------------------------------
// Name: csOpenCLHandleMonitor::registerOpenCLHandle
// Description: Adds an openCL handle mapping
// Arguments: void* ptr
// int contextId
// int objectId
// osTransferableObjectType objectType
// int ownerObjectId - represent the object that owns the object -
// for example - program for kernels. This parameter is optional
// int objectDisplayId - when the object name is different then it's index (object that
// are released), use this parameter for the object 'real' display name
// Return Val: void
// Author: Sigal Algranaty
// Date: 8/12/2009
// ---------------------------------------------------------------------------
void csOpenCLHandleMonitor::registerOpenCLHandle(oaCLHandle ptr, int contextId, int objectId, osTransferableObjectType objectType, int ownerObjectId, int objectDisplayId)
{
osCriticalSectionLocker mapCSLocker(m_clHandleObjectsMapAccessCS);
apCLObjectID* pNewObj = getCLHandleObjectDetails(ptr);
if (pNewObj == NULL)
{
pNewObj = new apCLObjectID;
// Insert the new object to the map:
_clHandleObjectsMap[ptr] = pNewObj;
}
// Set the object details:
pNewObj->_contextId = contextId;
pNewObj->_objectId = objectId;
pNewObj->_objectType = objectType;
pNewObj->_ownerObjectId = ownerObjectId;
pNewObj->_objectDisplayName = objectDisplayId;
}
// ---------------------------------------------------------------------------
// Name: csOpenCLHandleMonitor::nameHandledObject
// Description: Sets the name of a handled object, to match a call to a
// clNameXxxxGREMEDY() function.
// Author: Uri Shomroni
// Date: 22/7/2010
// ---------------------------------------------------------------------------
void csOpenCLHandleMonitor::nameHandledObject(oaCLHandle handle, const gtString& objectName)
{
osCriticalSectionLocker mapCSLocker(m_clHandleObjectsMapAccessCS);
gtMap<oaCLHandle, apCLObjectID*>::iterator findIter = _clHandleObjectsMap.find(handle);
if (findIter != _clHandleObjectsMap.end())
{
apCLObjectID* pObjectId = (*findIter).second;
GT_IF_WITH_ASSERT(pObjectId != NULL)
{
pObjectId->_objectName = objectName;
}
}
}
// ---------------------------------------------------------------------------
// Name: csOpenCLHandleMonitor::validateLivingHandle
// Description: Returns true iff the handle is registered as a living object of the given type.
// Author: Uri Shomroni
// Date: 28/7/2015
// ---------------------------------------------------------------------------
bool csOpenCLHandleMonitor::validateLivingHandle(oaCLHandle handle, osTransferableObjectType type) const
{
bool retVal = false;
if (OA_CL_NULL_HANDLE != handle)
{
// HERE BE DRAGONS!
// Do not attempt to update an object we "know" is dead (that is to say, its handle has been released, but it is not yet reused).
apCLObjectID* pObj = getCLHandleObjectDetails(handle);
retVal = (nullptr != pObj);
if (retVal)
{
retVal = (-1 < pObj->_objectId);
// Devices are not context-bound:
if (OS_TOBJ_ID_CL_DEVICE != type)
{
retVal = retVal && (0 < pObj->_contextId);
}
else // OS_TOBJ_ID_CL_DEVICE == type
{
retVal = retVal && (0 == pObj->_contextId);
}
retVal = retVal && (type == pObj->_objectType);
}
}
return retVal;
}
| 0 | 0.922914 | 1 | 0.922914 | game-dev | MEDIA | 0.413892 | game-dev | 0.916358 | 1 | 0.916358 |
followingthefasciaplane/source-engine-diff-check | 4,224 | misc/game/server/tf/passtime_ballcontroller.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "tf_passtime_ball.h"
#include "passtime_ballcontroller.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
namespace
{
int SortDescendingPriority( CPasstimeBallController *const *ppA, CPasstimeBallController *const *ppB )
{
return static_cast< CPasstimeBallController* >( *ppB )->GetPriority()
- static_cast< CPasstimeBallController* >( *ppA )->GetPriority();
}
}
//-----------------------------------------------------------------------------
// static
int CPasstimeBallController::ApplyTo( CPasstimeBall *pBall )
{
// Sort controllers by iPriority, then call Apply until one returns true.
// From then on, skip controllers with a lower iPriority.
// This sorts the autolist, but that should be OK.
auto &controllers = GetAutoList();
controllers.Sort( &SortDescendingPriority );
int iMinPriority = INT_MIN;
int iNumControllers = 0;
for ( auto controller : controllers )
{
if ( !controller->IsEnabled() || !controller->IsActive() )
{
continue;
}
if ( controller->GetPriority() < iMinPriority )
{
break;
}
if ( controller->Apply( pBall ) )
{
iMinPriority = controller->GetPriority();
++iNumControllers;
}
}
return iNumControllers;
}
//-----------------------------------------------------------------------------
// static
int CPasstimeBallController::DisableOn( const CPasstimeBall *pBall )
{
auto &controllers = GetAutoList();
int iCount = 0;
for ( auto pController : controllers )
{
if ( pController->IsEnabled() )
{
pController->SetIsEnabled( false );
++iCount;
}
}
return iCount;
}
//-----------------------------------------------------------------------------
// static
void CPasstimeBallController::BallCollision( CPasstimeBall *pBall,
int iCollisionIndex, gamevcollisionevent_t *pEvent )
{
auto &controllers = GetAutoList();
for ( auto pController : controllers )
{
if ( pController->IsEnabled() && pController->IsActive() )
{
pController->OnBallCollision( pBall, iCollisionIndex, pEvent );
}
}
}
//-----------------------------------------------------------------------------
// static
void CPasstimeBallController::BallPickedUp( CPasstimeBall *pBall,
CTFPlayer *pCatcher )
{
auto &controllers = GetAutoList();
for ( auto pController : controllers )
{
if ( pController->IsEnabled() && pController->IsActive() )
{
pController->OnBallPickedUp( pBall, pCatcher );
}
}
}
//-----------------------------------------------------------------------------
// static
void CPasstimeBallController::BallDamaged( CPasstimeBall *pBall )
{
auto &controllers = GetAutoList();
for ( auto pController : controllers )
{
if ( pController->IsEnabled() && pController->IsActive() )
{
pController->OnBallDamaged( pBall );
}
}
}
//-----------------------------------------------------------------------------
// static
void CPasstimeBallController::BallSpawned( CPasstimeBall *pBall )
{
auto &controllers = GetAutoList();
for ( auto pController : controllers )
{
if ( pController->IsEnabled() && pController->IsActive() )
{
pController->OnBallSpawned( pBall );
}
}
}
//-----------------------------------------------------------------------------
CPasstimeBallController::CPasstimeBallController( int iPriority )
: m_bEnabled( false )
, m_iPriority( iPriority ) {}
//-----------------------------------------------------------------------------
void CPasstimeBallController::SetIsEnabled( bool bEnabled )
{
if ( m_bEnabled == bEnabled )
{
return;
}
m_bEnabled = bEnabled;
if ( bEnabled )
{
OnEnabled();
}
else
{
OnDisabled();
}
}
//-----------------------------------------------------------------------------
bool CPasstimeBallController::IsEnabled() const
{
return m_bEnabled;
}
//-----------------------------------------------------------------------------
int CPasstimeBallController::GetPriority() const
{
return m_iPriority;
}
| 0 | 0.727667 | 1 | 0.727667 | game-dev | MEDIA | 0.800779 | game-dev | 0.699794 | 1 | 0.699794 |
4coder-archive/4coder | 2,414 | 4ed_app_models.cpp | /*
* Mr. 4th Dimention - Allen Webster
*
* 01.05.2020
*
* Implementation of the root models features.
*
*/
// TOP
function void
models_push_view_command_function(Models *models, View_ID view_id, Custom_Command_Function *custom_func){
Model_View_Command_Function *node = models->free_view_cmd_funcs;
if (node == 0){
node = push_array(models->arena, Model_View_Command_Function, 1);
}
else{
sll_stack_pop(models->free_view_cmd_funcs);
}
sll_queue_push(models->first_view_cmd_func, models->last_view_cmd_func, node);
node->view_id = view_id;
node->custom_func = custom_func;
}
function Model_View_Command_Function
models_pop_view_command_function(Models *models){
Model_View_Command_Function result = {};
if (models->first_view_cmd_func != 0){
Model_View_Command_Function *node = models->first_view_cmd_func;
result.custom_func = node->custom_func;
result.view_id = node->view_id;
sll_queue_pop(models->first_view_cmd_func, models->last_view_cmd_func);
sll_stack_push(models->free_view_cmd_funcs, node);
}
return(result);
}
function void
models_push_virtual_event(Models *models, Input_Event *event){
Model_Input_Event_Node *node = models->free_virtual_event;
if (node == 0){
node = push_array(&models->virtual_event_arena, Model_Input_Event_Node, 1);
}
else{
sll_stack_pop(models->free_virtual_event);
}
sll_queue_push(models->first_virtual_event, models->last_virtual_event, node);
node->event = copy_input_event(&models->virtual_event_arena, event);
}
function Input_Event
models_pop_virtual_event(Arena *arena, Models *models){
Input_Event result = {};
if (models->first_virtual_event != 0){
Model_Input_Event_Node *node = models->first_virtual_event;
result = copy_input_event(arena, &node->event);
sll_queue_pop(models->first_virtual_event, models->last_virtual_event);
sll_stack_push(models->free_virtual_event, node);
}
return(result);
}
function void
models_push_wind_down(Models *models, Coroutine *co){
Model_Wind_Down_Co *node = models->free_wind_downs;
if (node != 0){
sll_stack_pop(models->free_wind_downs);
}
else{
node = push_array(models->arena, Model_Wind_Down_Co, 1);
}
sll_stack_push(models->wind_down_stack, node);
node->co = co;
}
// BOTTOM
| 0 | 0.77133 | 1 | 0.77133 | game-dev | MEDIA | 0.576384 | game-dev | 0.78182 | 1 | 0.78182 |
MATTYOneInc/AionEncomBase_Java8 | 2,202 | AL-Game/data/scripts/system/handlers/ai/instance/beshmundirTemple/SacrificialSoulAI2.java | /*
* This file is part of Encom.
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.instance.beshmundirTemple;
import ai.AggressiveNpcAI2;
import com.aionemu.gameserver.ai2.AI2Actions;
import com.aionemu.gameserver.ai2.AIName;
import com.aionemu.gameserver.ai2.AIState;
import com.aionemu.gameserver.model.actions.NpcActions;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.skillengine.SkillEngine;
/****/
/** Author (Encom)
/****/
@AIName("templeSoul")
public class SacrificialSoulAI2 extends AggressiveNpcAI2
{
private Npc boss;
@Override
protected void handleSpawned() {
super.handleSpawned();
AI2Actions.useSkill(this, 18901); //Time Wrinkle.
this.setStateIfNot(AIState.FOLLOWING);
boss = getPosition().getWorldMapInstance().getNpc(216263); //Isbariya The Resolute.
if (boss != null && !NpcActions.isAlreadyDead(boss)) {
AI2Actions.targetCreature(this, boss);
getMoveController().moveToTargetObject();
}
}
@Override
protected void handleAttack(Creature creature) {
super.handleAttack(creature);
if (creature.getEffectController().hasAbnormalEffect(18959)) { //Sixth Sense.
getMoveController().abortMove();
AI2Actions.deleteOwner(this);
}
}
@Override
protected void handleMoveArrived() {
if (boss != null && !NpcActions.isAlreadyDead(boss)) {
SkillEngine.getInstance().getSkill(getOwner(), 18960, 55, boss).useNoAnimationSkill(); //Call Of The Grave.
AI2Actions.deleteOwner(this);
}
}
@Override
public boolean canThink() {
return false;
}
} | 0 | 0.837304 | 1 | 0.837304 | game-dev | MEDIA | 0.97446 | game-dev | 0.869782 | 1 | 0.869782 |
kierstone/Buff-In-TopDownShooter | 22,647 | Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_SpriteAsset.cs | using UnityEngine;
using UnityEngine.TextCore;
using System.Collections.Generic;
using System.Linq;
namespace TMPro
{
[ExcludeFromPresetAttribute]
public class TMP_SpriteAsset : TMP_Asset
{
internal Dictionary<int, int> m_NameLookup;
internal Dictionary<uint, int> m_GlyphIndexLookup;
/// <summary>
/// The version of the sprite asset class.
/// Version 1.1.0 updates the asset data structure to be compatible with new font asset structure.
/// </summary>
public string version
{
get { return m_Version; }
internal set { m_Version = value; }
}
[SerializeField]
private string m_Version;
/// <summary>
/// Information about the sprite asset's face.
/// </summary>
public FaceInfo faceInfo
{
get { return m_FaceInfo; }
internal set { m_FaceInfo = value; }
}
[SerializeField]
internal FaceInfo m_FaceInfo;
// The texture which contains the sprites.
public Texture spriteSheet;
/// <summary>
///
/// </summary>
public List<TMP_SpriteCharacter> spriteCharacterTable
{
get
{
if (m_GlyphIndexLookup == null)
UpdateLookupTables();
return m_SpriteCharacterTable;
}
internal set { m_SpriteCharacterTable = value; }
}
[SerializeField]
private List<TMP_SpriteCharacter> m_SpriteCharacterTable = new List<TMP_SpriteCharacter>();
/// <summary>
/// Dictionary used to lookup sprite characters by their unicode value.
/// </summary>
public Dictionary<uint, TMP_SpriteCharacter> spriteCharacterLookupTable
{
get
{
if (m_SpriteCharacterLookup == null)
UpdateLookupTables();
return m_SpriteCharacterLookup;
}
internal set { m_SpriteCharacterLookup = value; }
}
internal Dictionary<uint, TMP_SpriteCharacter> m_SpriteCharacterLookup;
public List<TMP_SpriteGlyph> spriteGlyphTable
{
get { return m_SpriteGlyphTable; }
internal set { m_SpriteGlyphTable = value; }
}
[SerializeField]
private List<TMP_SpriteGlyph> m_SpriteGlyphTable = new List<TMP_SpriteGlyph>();
internal Dictionary<uint, TMP_SpriteGlyph> m_SpriteGlyphLookup;
// List which contains the SpriteInfo for the sprites contained in the sprite sheet.
public List<TMP_Sprite> spriteInfoList;
/// <summary>
/// List which contains the Fallback font assets for this font.
/// </summary>
[SerializeField]
public List<TMP_SpriteAsset> fallbackSpriteAssets;
internal bool m_IsSpriteAssetLookupTablesDirty = false;
void Awake()
{
// Check version number of sprite asset to see if it needs to be upgraded.
if (this.material != null && string.IsNullOrEmpty(m_Version))
UpgradeSpriteAsset();
}
/// <summary>
/// Create a material for the sprite asset.
/// </summary>
/// <returns></returns>
Material GetDefaultSpriteMaterial()
{
//isEditingAsset = true;
ShaderUtilities.GetShaderPropertyIDs();
// Add a new material
Shader shader = Shader.Find("TextMeshPro/Sprite");
Material tempMaterial = new Material(shader);
tempMaterial.SetTexture(ShaderUtilities.ID_MainTex, spriteSheet);
tempMaterial.hideFlags = HideFlags.HideInHierarchy;
#if UNITY_EDITOR
UnityEditor.AssetDatabase.AddObjectToAsset(tempMaterial, this);
UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(this));
#endif
//isEditingAsset = false;
return tempMaterial;
}
/// <summary>
/// Function to update the sprite name and unicode lookup tables.
/// This function should be called when a sprite's name or unicode value changes or when a new sprite is added.
/// </summary>
public void UpdateLookupTables()
{
//Debug.Log("Updating [" + this.name + "] Lookup tables.");
// Check version number of sprite asset to see if it needs to be upgraded.
if (this.material != null && string.IsNullOrEmpty(m_Version))
UpgradeSpriteAsset();
// Initialize / Clear glyph index lookup dictionary.
if (m_GlyphIndexLookup == null)
m_GlyphIndexLookup = new Dictionary<uint, int>();
else
m_GlyphIndexLookup.Clear();
//
if (m_SpriteGlyphLookup == null)
m_SpriteGlyphLookup = new Dictionary<uint, TMP_SpriteGlyph>();
else
m_SpriteGlyphLookup.Clear();
// Initialize SpriteGlyphLookup
for (int i = 0; i < m_SpriteGlyphTable.Count; i++)
{
TMP_SpriteGlyph spriteGlyph = m_SpriteGlyphTable[i];
uint glyphIndex = spriteGlyph.index;
if (m_GlyphIndexLookup.ContainsKey(glyphIndex) == false)
m_GlyphIndexLookup.Add(glyphIndex, i);
if (m_SpriteGlyphLookup.ContainsKey(glyphIndex) == false)
m_SpriteGlyphLookup.Add(glyphIndex, spriteGlyph);
}
// Initialize name lookup
if (m_NameLookup == null)
m_NameLookup = new Dictionary<int, int>();
else
m_NameLookup.Clear();
// Initialize character lookup
if (m_SpriteCharacterLookup == null)
m_SpriteCharacterLookup = new Dictionary<uint, TMP_SpriteCharacter>();
else
m_SpriteCharacterLookup.Clear();
// Populate Sprite Character lookup tables
for (int i = 0; i < m_SpriteCharacterTable.Count; i++)
{
TMP_SpriteCharacter spriteCharacter = m_SpriteCharacterTable[i];
// Make sure sprite character is valid
if (spriteCharacter == null)
continue;
uint glyphIndex = spriteCharacter.glyphIndex;
// Lookup the glyph for this character
if (m_SpriteGlyphLookup.ContainsKey(glyphIndex) == false)
continue;
// Assign glyph and text asset to this character
spriteCharacter.glyph = m_SpriteGlyphLookup[glyphIndex];
spriteCharacter.textAsset = this;
int nameHashCode = m_SpriteCharacterTable[i].hashCode;
if (m_NameLookup.ContainsKey(nameHashCode) == false)
m_NameLookup.Add(nameHashCode, i);
uint unicode = m_SpriteCharacterTable[i].unicode;
if (unicode != 0xFFFE && m_SpriteCharacterLookup.ContainsKey(unicode) == false)
m_SpriteCharacterLookup.Add(unicode, spriteCharacter);
}
m_IsSpriteAssetLookupTablesDirty = false;
}
/// <summary>
/// Function which returns the sprite index using the hashcode of the name
/// </summary>
/// <param name="hashCode"></param>
/// <returns></returns>
public int GetSpriteIndexFromHashcode(int hashCode)
{
if (m_NameLookup == null)
UpdateLookupTables();
int index;
if (m_NameLookup.TryGetValue(hashCode, out index))
return index;
return -1;
}
/// <summary>
/// Returns the index of the sprite for the given unicode value.
/// </summary>
/// <param name="unicode"></param>
/// <returns></returns>
public int GetSpriteIndexFromUnicode (uint unicode)
{
if (m_SpriteCharacterLookup == null)
UpdateLookupTables();
TMP_SpriteCharacter spriteCharacter;
if (m_SpriteCharacterLookup.TryGetValue(unicode, out spriteCharacter))
return (int)spriteCharacter.glyphIndex;
return -1;
}
/// <summary>
/// Returns the index of the sprite for the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public int GetSpriteIndexFromName (string name)
{
if (m_NameLookup == null)
UpdateLookupTables();
int hashCode = TMP_TextUtilities.GetSimpleHashCode(name);
return GetSpriteIndexFromHashcode(hashCode);
}
/// <summary>
/// Used to keep track of which Sprite Assets have been searched.
/// </summary>
private static HashSet<int> k_searchedSpriteAssets;
/// <summary>
/// Search through the given sprite asset and its fallbacks for the specified sprite matching the given unicode character.
/// </summary>
/// <param name="spriteAsset">The font asset to search for the given character.</param>
/// <param name="unicode">The character to find.</param>
/// <param name="glyph">out parameter containing the glyph for the specified character (if found).</param>
/// <returns></returns>
public static TMP_SpriteAsset SearchForSpriteByUnicode(TMP_SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex)
{
// Check to make sure sprite asset is not null
if (spriteAsset == null) { spriteIndex = -1; return null; }
// Get sprite index for the given unicode
spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode);
if (spriteIndex != -1)
return spriteAsset;
// Initialize list to track instance of Sprite Assets that have already been searched.
if (k_searchedSpriteAssets == null)
k_searchedSpriteAssets = new HashSet<int>();
else
k_searchedSpriteAssets.Clear();
// Get instance ID of sprite asset and add to list.
int id = spriteAsset.GetInstanceID();
k_searchedSpriteAssets.Add(id);
// Search potential fallback sprite assets if includeFallbacks is true.
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, true, out spriteIndex);
// Search default sprite asset potentially assigned in the TMP Settings.
if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null)
return SearchForSpriteByUnicodeInternal(TMP_Settings.defaultSpriteAsset, unicode, true, out spriteIndex);
spriteIndex = -1;
return null;
}
/// <summary>
/// Search through the given list of sprite assets and fallbacks for a sprite whose unicode value matches the target unicode.
/// </summary>
/// <param name="spriteAssets"></param>
/// <param name="unicode"></param>
/// <param name="includeFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByUnicodeInternal(List<TMP_SpriteAsset> spriteAssets, uint unicode, bool includeFallbacks, out int spriteIndex)
{
for (int i = 0; i < spriteAssets.Count; i++)
{
TMP_SpriteAsset temp = spriteAssets[i];
if (temp == null) continue;
int id = temp.GetInstanceID();
// Skip sprite asset if it has already been searched.
if (k_searchedSpriteAssets.Add(id) == false)
continue;
temp = SearchForSpriteByUnicodeInternal(temp, unicode, includeFallbacks, out spriteIndex);
if (temp != null)
return temp;
}
spriteIndex = -1;
return null;
}
/// <summary>
/// Search the given sprite asset and fallbacks for a sprite whose unicode value matches the target unicode.
/// </summary>
/// <param name="spriteAsset"></param>
/// <param name="unicode"></param>
/// <param name="includeFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByUnicodeInternal(TMP_SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex)
{
// Get sprite index for the given unicode
spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode);
if (spriteIndex != -1)
return spriteAsset;
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, true, out spriteIndex);
spriteIndex = -1;
return null;
}
/// <summary>
/// Search the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code.
/// </summary>
/// <param name="spriteAsset">The Sprite Asset to search for the given sprite whose name matches the hashcode value</param>
/// <param name="hashCode">The hash code value matching the name of the sprite</param>
/// <param name="includeFallbacks">Include fallback sprite assets in the search</param>
/// <param name="spriteIndex">The index of the sprite matching the provided hash code</param>
/// <returns>The Sprite Asset that contains the sprite</returns>
public static TMP_SpriteAsset SearchForSpriteByHashCode(TMP_SpriteAsset spriteAsset, int hashCode, bool includeFallbacks, out int spriteIndex)
{
// Make sure sprite asset is not null
if (spriteAsset == null) { spriteIndex = -1; return null; }
spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode);
if (spriteIndex != -1)
return spriteAsset;
// Initialize or clear list to Sprite Assets that have already been searched.
if (k_searchedSpriteAssets == null)
k_searchedSpriteAssets = new HashSet<int>();
else
k_searchedSpriteAssets.Clear();
int id = spriteAsset.instanceID;
// Add to list of font assets already searched.
k_searchedSpriteAssets.Add(id);
TMP_SpriteAsset tempSpriteAsset;
// Search potential fallbacks assigned to local sprite asset.
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
{
tempSpriteAsset = SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
// Search default sprite asset potentially assigned in the TMP Settings.
if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null)
{
tempSpriteAsset = SearchForSpriteByHashCodeInternal(TMP_Settings.defaultSpriteAsset, hashCode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
// Clear search list since we are now looking for the missing sprite character.
k_searchedSpriteAssets.Clear();
uint missingSpriteCharacterUnicode = TMP_Settings.missingCharacterSpriteUnicode;
// Get sprite index for the given unicode
spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(missingSpriteCharacterUnicode);
if (spriteIndex != -1)
return spriteAsset;
// Add current sprite asset to list of assets already searched.
k_searchedSpriteAssets.Add(id);
// Search for the missing sprite character in the local sprite asset and potential fallbacks.
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
{
tempSpriteAsset = SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, missingSpriteCharacterUnicode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
// Search for the missing sprite character in the default sprite asset and potential fallbacks.
if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null)
{
tempSpriteAsset = SearchForSpriteByUnicodeInternal(TMP_Settings.defaultSpriteAsset, missingSpriteCharacterUnicode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
spriteIndex = -1;
return null;
}
/// <summary>
/// Search through the given list of sprite assets and fallbacks for a sprite whose hash code value of its name matches the target hash code.
/// </summary>
/// <param name="spriteAssets"></param>
/// <param name="hashCode"></param>
/// <param name="searchFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByHashCodeInternal(List<TMP_SpriteAsset> spriteAssets, int hashCode, bool searchFallbacks, out int spriteIndex)
{
// Search through the list of sprite assets
for (int i = 0; i < spriteAssets.Count; i++)
{
TMP_SpriteAsset temp = spriteAssets[i];
if (temp == null) continue;
int id = temp.instanceID;
// Skip sprite asset if it has already been searched.
if (k_searchedSpriteAssets.Add(id) == false)
continue;
temp = SearchForSpriteByHashCodeInternal(temp, hashCode, searchFallbacks, out spriteIndex);
if (temp != null)
return temp;
}
spriteIndex = -1;
return null;
}
/// <summary>
/// Search through the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code.
/// </summary>
/// <param name="spriteAsset"></param>
/// <param name="hashCode"></param>
/// <param name="searchFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByHashCodeInternal(TMP_SpriteAsset spriteAsset, int hashCode, bool searchFallbacks, out int spriteIndex)
{
// Get the sprite for the given hash code.
spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode);
if (spriteIndex != -1)
return spriteAsset;
if (searchFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
return SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, true, out spriteIndex);
spriteIndex = -1;
return null;
}
/// <summary>
/// Sort the sprite glyph table by glyph index.
/// </summary>
public void SortGlyphTable()
{
if (m_SpriteGlyphTable == null || m_SpriteGlyphTable.Count == 0) return;
m_SpriteGlyphTable = m_SpriteGlyphTable.OrderBy(item => item.index).ToList();
}
/// <summary>
/// Sort the sprite character table by Unicode values.
/// </summary>
internal void SortCharacterTable()
{
if (m_SpriteCharacterTable != null && m_SpriteCharacterTable.Count > 0)
m_SpriteCharacterTable = m_SpriteCharacterTable.OrderBy(c => c.unicode).ToList();
}
/// <summary>
/// Sort both sprite glyph and character tables.
/// </summary>
internal void SortGlyphAndCharacterTables()
{
SortGlyphTable();
SortCharacterTable();
}
/// <summary>
/// Internal method used to upgrade sprite asset.
/// </summary>
private void UpgradeSpriteAsset()
{
m_Version = "1.1.0";
Debug.Log("Upgrading sprite asset [" + this.name + "] to version " + m_Version + ".", this);
// Convert legacy glyph and character tables to new format
m_SpriteCharacterTable.Clear();
m_SpriteGlyphTable.Clear();
for (int i = 0; i < spriteInfoList.Count; i++)
{
TMP_Sprite oldSprite = spriteInfoList[i];
TMP_SpriteGlyph spriteGlyph = new TMP_SpriteGlyph();
spriteGlyph.index = (uint)i;
spriteGlyph.sprite = oldSprite.sprite;
spriteGlyph.metrics = new GlyphMetrics(oldSprite.width, oldSprite.height, oldSprite.xOffset, oldSprite.yOffset, oldSprite.xAdvance);
spriteGlyph.glyphRect = new GlyphRect((int)oldSprite.x, (int)oldSprite.y, (int)oldSprite.width, (int)oldSprite.height);
spriteGlyph.scale = 1.0f;
spriteGlyph.atlasIndex = 0;
m_SpriteGlyphTable.Add(spriteGlyph);
TMP_SpriteCharacter spriteCharacter = new TMP_SpriteCharacter();
spriteCharacter.glyph = spriteGlyph;
spriteCharacter.unicode = oldSprite.unicode == 0x0 ? 0xFFFE : (uint)oldSprite.unicode;
spriteCharacter.name = oldSprite.name;
spriteCharacter.scale = oldSprite.scale;
m_SpriteCharacterTable.Add(spriteCharacter);
}
// Clear legacy glyph info list.
//spriteInfoList.Clear();
UpdateLookupTables();
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
UnityEditor.AssetDatabase.SaveAssets();
#endif
}
}
}
| 0 | 0.860971 | 1 | 0.860971 | game-dev | MEDIA | 0.847028 | game-dev | 0.871564 | 1 | 0.871564 |
ss14Starlight/space-station-14 | 8,878 | Content.MapRenderer/Painters/MapPainter.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.IO;
using System.Threading.Tasks;
using Content.Client.Markers;
using Content.IntegrationTests;
using Content.IntegrationTests.Pair;
using Content.Server.GameTicking;
using Robust.Client.GameObjects;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.ContentPack;
using Robust.Shared.EntitySerialization;
using Robust.Shared.EntitySerialization.Systems;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Maths;
using Robust.Shared.Timing;
using Robust.UnitTesting.Pool;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace Content.MapRenderer.Painters
{
public sealed class MapPainter : IAsyncDisposable
{
private readonly RenderMap _map;
private readonly ITestContextLike _testContextLike;
private TestPair? _pair;
private Entity<MapGridComponent>[] _grids = [];
public MapPainter(RenderMap map, ITestContextLike testContextLike)
{
_map = map;
_testContextLike = testContextLike;
}
public async Task Initialize()
{
var stopwatch = RStopwatch.StartNew();
var poolSettings = new PoolSettings
{
DummyTicker = false,
Connected = true,
Destructive = true,
Fresh = true,
// Seriously whoever made MapPainter use GameMapPrototype I wish you step on a lego one time.
Map = _map is RenderMapPrototype prototype ? prototype.Prototype : PoolManager.TestMap,
};
_pair = await PoolManager.GetServerClient(poolSettings, _testContextLike);
Console.WriteLine($"Loaded client and server in {(int)stopwatch.Elapsed.TotalMilliseconds} ms");
if (_map is RenderMapFile mapFile)
{
using var stream = File.OpenRead(mapFile.FileName);
await _pair.Server.WaitPost(() =>
{
var loadOptions = new MapLoadOptions
{
// Accept loading both maps and grids without caring about what the input file truly is.
DeserializationOptions =
{
LogOrphanedGrids = false,
},
};
if (!_pair.Server.System<MapLoaderSystem>().TryLoadGeneric(stream, mapFile.FileName, out var loadResult, loadOptions))
throw new IOException($"File {mapFile.FileName} could not be read");
_grids = loadResult.Grids.ToArray();
});
}
}
public async Task SetupView(bool showMarkers)
{
if (_pair == null)
throw new InvalidOperationException("Instance not initialized!");
await _pair.Client.WaitPost(() =>
{
if (_pair.Client.EntMan.TryGetComponent(_pair.Client.PlayerMan.LocalEntity, out SpriteComponent? sprite))
{
_pair.Client.System<SpriteSystem>()
.SetVisible((_pair.Client.PlayerMan.LocalEntity.Value, sprite), false);
}
});
if (showMarkers)
{
await _pair.Client.WaitPost(() =>
{
_pair.Client.System<MarkerSystem>().MarkersVisible = true;
});
}
}
public async Task<MapViewerData> GenerateMapViewerData(ParallaxOutput? parallaxOutput)
{
if (_pair == null)
throw new InvalidOperationException("Instance not initialized!");
var mapShort = _map.ShortName;
string fullName;
if (_map is RenderMapPrototype prototype)
{
fullName = _pair.Server.ProtoMan.Index(prototype.Prototype).MapName;
}
else
{
fullName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(mapShort);
}
var mapViewerData = new MapViewerData
{
Id = mapShort,
Name = fullName,
};
if (parallaxOutput != null)
{
await _pair.Client.WaitPost(() =>
{
var res = _pair.Client.InstanceDependencyCollection.Resolve<IResourceManager>();
mapViewerData.ParallaxLayers.Add(LayerGroup.DefaultParallax(res, parallaxOutput));
});
}
return mapViewerData;
}
public async IAsyncEnumerable<RenderedGridImage<Rgba32>> Paint()
{
if (_pair == null)
throw new InvalidOperationException("Instance not initialized!");
var client = _pair.Client;
var server = _pair.Server;
var sEntityManager = server.ResolveDependency<IServerEntityManager>();
var sPlayerManager = server.ResolveDependency<IPlayerManager>();
var entityManager = server.ResolveDependency<IEntityManager>();
var mapSys = entityManager.System<SharedMapSystem>();
await _pair.RunTicksSync(10);
await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());
var sMapManager = server.ResolveDependency<IMapManager>();
var tilePainter = new TilePainter(client, server);
var entityPainter = new GridPainter(client, server);
var xformQuery = sEntityManager.GetEntityQuery<TransformComponent>();
var xformSystem = sEntityManager.System<SharedTransformSystem>();
await server.WaitPost(() =>
{
var playerEntity = sPlayerManager.Sessions.Single().AttachedEntity;
if (playerEntity.HasValue)
{
sEntityManager.DeleteEntity(playerEntity.Value);
}
if (_map is RenderMapPrototype)
{
var mapId = sEntityManager.System<GameTicker>().DefaultMap;
_grids = sMapManager.GetAllGrids(mapId).ToArray();
}
foreach (var (uid, _) in _grids)
{
var gridXform = xformQuery.GetComponent(uid);
xformSystem.SetWorldRotation(gridXform, Angle.Zero);
}
});
await _pair.RunTicksSync(10);
await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());
foreach (var (uid, grid) in _grids)
{
var tiles = mapSys.GetAllTiles(uid, grid).ToList();
if (tiles.Count == 0)
{
Console.WriteLine($"Warning: Grid {uid} was empty. Skipping image rendering.");
continue;
}
var tileXSize = grid.TileSize * TilePainter.TileImageSize;
var tileYSize = grid.TileSize * TilePainter.TileImageSize;
var minX = tiles.Min(t => t.X);
var minY = tiles.Min(t => t.Y);
var maxX = tiles.Max(t => t.X);
var maxY = tiles.Max(t => t.Y);
var w = (maxX - minX + 1) * tileXSize;
var h = (maxY - minY + 1) * tileYSize;
var customOffset = new Vector2();
//MapGrids don't have LocalAABB, so we offset them to align the bottom left corner with 0,0 coordinates
if (grid.LocalAABB.IsEmpty())
customOffset = new Vector2(-minX, -minY);
var gridCanvas = new Image<Rgba32>(w, h);
await server.WaitPost(() =>
{
tilePainter.Run(gridCanvas, uid, grid, customOffset);
entityPainter.Run(gridCanvas, uid, grid, customOffset);
gridCanvas.Mutate(e => e.Flip(FlipMode.Vertical));
});
var renderedImage = new RenderedGridImage<Rgba32>(gridCanvas)
{
GridUid = uid,
Offset = xformSystem.GetWorldPosition(uid),
};
yield return renderedImage;
}
}
public async Task CleanReturnAsync()
{
if (_pair == null)
throw new InvalidOperationException("Instance not initialized!");
await _pair.CleanReturnAsync();
}
public async ValueTask DisposeAsync()
{
if (_pair != null)
await _pair.DisposeAsync();
}
}
}
| 0 | 0.935007 | 1 | 0.935007 | game-dev | MEDIA | 0.235835 | game-dev | 0.959928 | 1 | 0.959928 |
crawl/crawl | 8,298 | crawl-ref/source/map-cell.h | #pragma once
#include <libutil.h>
#include "enum.h"
#include "mon-info.h"
#include "tag-version.h"
#include "trap-type.h"
#define MAP_MAGIC_MAPPED_FLAG 0x01
#define MAP_SEEN_FLAG 0x02
#define MAP_CHANGED_FLAG 0x04 // FIXME: this doesn't belong here
#define MAP_DETECTED_MONSTER 0x08
#define MAP_INVISIBLE_MONSTER 0x10
#define MAP_DETECTED_ITEM 0x20
#define MAP_VISIBLE_FLAG 0x40
#define MAP_GRID_KNOWN 0xFF
#define MAP_EMPHASIZE 0x100
#define MAP_MORE_ITEMS 0x200
#define MAP_HALOED 0x400
#define MAP_SILENCED 0x800
#define MAP_BLOODY 0x1000
#define MAP_CORRODING 0x2000
#define MAP_ICY 0x8000
/* these flags require more space to serialize: put infrequently used ones there */
#define MAP_EXCLUDED_STAIRS 0x10000
#define MAP_SANCTUARY_1 0x80000
#define MAP_SANCTUARY_2 0x100000
#define MAP_WITHHELD 0x200000
#define MAP_LIQUEFIED 0x400000
#define MAP_ORB_HALOED 0x800000
#define MAP_UMBRAED 0x1000000
#define MAP_QUAD_HALOED 0X4000000
#define MAP_DISJUNCT 0X8000000
#define MAP_BLASPHEMY 0X10000000
#define MAP_BFB_CORPSE 0X20000000
struct cloud_info
{
cloud_info() : type(CLOUD_NONE), colour(0), duration(3), tile(0), pos(0, 0),
killer(KILL_NONE)
{ }
cloud_info(cloud_type t, colour_t c,
uint8_t dur, unsigned short til, coord_def gc,
killer_type kill)
: type(t), colour(c), duration(dur), tile(til), pos(gc), killer(kill)
{ }
friend bool operator==(const cloud_info &lhs, const cloud_info &rhs) {
return lhs.type == rhs.type
&& lhs.colour == rhs.colour
&& lhs.duration == rhs.duration
&& lhs.tile == rhs.tile
&& lhs.pos == rhs.pos
&& lhs.killer == rhs.killer;
}
friend bool operator!=(const cloud_info &lhs, const cloud_info &rhs) {
return !(lhs == rhs);
}
cloud_type type:8;
colour_t colour;
uint8_t duration; // decay/20, clamped to 0-3
// TODO: should this be tileidx_t?
unsigned short tile;
coord_def pos;
killer_type killer;
};
/*
* A map_cell stores what the player knows about a cell.
* These go in env.map_knowledge.
* TODO: this can shrink to 32 bytes by shrinking enums
*/
struct map_cell
{
// TODO: in C++20 we can give these a default member initializer
map_cell() : _feat(DNGN_UNSEEN),
_trap(TRAP_UNASSIGNED)
{
}
~map_cell() = default;
// copy constructor
map_cell(const map_cell& o)
{
*this = o;
}
// copy assignment
map_cell& operator=(const map_cell& o)
{
if (this == &o)
return *this;
flags = o.flags;
_feat = o._feat;
_feat_colour = o._feat_colour;
_trap = o._trap;
_cloud = o._cloud ? make_unique<cloud_info>(*o._cloud) : nullptr;
_item = o._item ? make_unique<item_def>(*o._item) : nullptr;
_mons = o._mons ? make_unique<monster_info>(*o._mons) : nullptr;
return *this;
}
// move constructor
map_cell(map_cell&& o) noexcept = default;
// move assignment
// XXX: Using the default implementation causes a compiler error on gcc
// 4.7, so we specify the implementation for now.
map_cell& operator=(map_cell&& o) noexcept
{
flags = o.flags;
_feat = o._feat;
_feat_colour = o._feat_colour;
_trap = o._trap;
_cloud = std::move(o._cloud);
_item = std::move(o._item);
_mons = std::move(o._mons);
return *this;
}
friend bool operator==(const map_cell &lhs, const map_cell &rhs) {
// TODO: consider providing a proper equality operator
// item_def and monster_info currently lack such operators
// Which makes it impossible for map_cell to provide one
// As far as I can tell, packed_cell is the only user of this
// And packed_cell operator== doesn't *seem* to be used
return &lhs == &rhs;
}
friend bool operator!=(const map_cell &lhs, const map_cell &rhs) {
return !(lhs == rhs);
}
void clear()
{
*this = map_cell();
}
// Clear prior to show update. Need to retain at least "seen" flag.
void clear_data()
{
const uint32_t f = flags & (MAP_SEEN_FLAG | MAP_CHANGED_FLAG);
clear();
flags = f;
}
dungeon_feature_type feat() const
{
// Ugh; MSVC makes the bit field signed even though that means it can't
// actually hold all the enum values. That seems to be in contradiction
// of the standard (§9.6 [class.bit] paragraph 4) but what can you do?
return static_cast<dungeon_feature_type>(static_cast<uint8_t>(_feat));
}
unsigned feat_colour() const
{
return _feat_colour;
}
void set_feature(dungeon_feature_type nfeat, unsigned colour = 0,
trap_type tr = TRAP_UNASSIGNED)
{
_feat = nfeat;
_feat_colour = colour;
_trap = tr;
}
item_def* item() const
{
return _item.get();
}
bool detected_item() const
{
const bool ret = !!(flags & MAP_DETECTED_ITEM);
// TODO: change to an ASSERT when the underlying crash goes away
if (ret && !_item)
{
//clear_item();
return false;
}
return ret;
}
void set_item(const item_def& ii, bool more_items)
{
clear_item();
_item = make_unique<item_def>(ii);
if (more_items)
flags |= MAP_MORE_ITEMS;
}
void set_detected_item();
void clear_item()
{
// TODO: internal callers are doing a bit of duplicate work here
_item.reset();
flags &= ~(MAP_DETECTED_ITEM | MAP_MORE_ITEMS);
}
monster_type monster() const
{
return _mons ? _mons->type : MONS_NO_MONSTER;
}
monster_info* monsterinfo() const
{
return _mons.get();
}
void set_monster(const monster_info& mi)
{
clear_monster();
_mons = make_unique<monster_info>(mi);
}
bool detected_monster() const
{
return !!(flags & MAP_DETECTED_MONSTER);
}
bool invisible_monster() const
{
return !!(flags & MAP_INVISIBLE_MONSTER);
}
void set_detected_monster(monster_type mons)
{
clear_monster();
_mons = make_unique<monster_info>(MONS_SENSED);
_mons->base_type = mons;
flags |= MAP_DETECTED_MONSTER;
}
void set_invisible_monster()
{
clear_monster();
flags |= MAP_INVISIBLE_MONSTER;
}
void clear_monster()
{
// TODO: internal callers are doing a bit of duplicate work here
_mons.reset();
flags &= ~(MAP_DETECTED_MONSTER | MAP_INVISIBLE_MONSTER);
}
cloud_type cloud() const
{
return _cloud ? _cloud->type : CLOUD_NONE;
}
// TODO: should this be colour_t?
unsigned cloud_colour() const
{
return _cloud ? _cloud->colour : static_cast<colour_t>(0);
}
cloud_info* cloudinfo() const
{
return _cloud.get();
}
void set_cloud(const cloud_info& ci)
{
_cloud = make_unique<cloud_info>(ci);
}
void clear_cloud()
{
_cloud.reset();
}
bool update_cloud_state();
bool known() const
{
return !!(flags & MAP_GRID_KNOWN);
}
bool seen() const
{
return !!(flags & MAP_SEEN_FLAG);
}
bool visible() const
{
return !!(flags & MAP_VISIBLE_FLAG);
}
bool changed() const
{
return !!(flags & MAP_CHANGED_FLAG);
}
bool mapped() const
{
return !!(flags & MAP_MAGIC_MAPPED_FLAG);
}
trap_type trap() const
{
return _trap;
}
public:
uint32_t flags = 0; // Flags describing the mappedness of this square.
private:
// TODO: shrink enums, shrink/re-order cloud_info and inline it
dungeon_feature_type _feat:8;
colour_t _feat_colour = 0;
trap_type _trap:8;
unique_ptr<cloud_info> _cloud;
unique_ptr<item_def> _item;
unique_ptr<monster_info> _mons;
};
| 0 | 0.959714 | 1 | 0.959714 | game-dev | MEDIA | 0.868727 | game-dev | 0.966314 | 1 | 0.966314 |
evereux/pycatia | 4,228 | pycatia/dnb_human_sim_interfaces/human_task.py | #! usr/bin/python3.9
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-09-25 14:34:21.593357
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript functions work
and thus help debugging in pycatia.
"""
from pycatia.dmaps_interfaces.activity import Activity
from pycatia.dnb_human_modeling_interfaces.swk_manikin import SWKManikin
class HumanTask(Activity):
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-09-25 14:34:21.593357)
| System.IUnknown
| System.IDispatch
| System.CATBaseUnknown
| System.CATBaseDispatch
| System.AnyObject
| DMAPSInterfaces.Activity
| HumanTask
"""
def __init__(self, com_object):
super().__init__(com_object)
self.human_task = com_object
@property
def specified_cycle_time(self) -> float:
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-09-25 14:34:21.593357)
| o Property SpecifiedCycleTime() As double (Read Only)
|
| returns the time set by the user by set_SpecifiedCycleTime
:rtype: float
"""
return self.human_task.SpecifiedCycleTime
@property
def specified_joint_speed(self) -> float:
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-09-25 14:34:21.593357)
| o Property SpecifiedJointSpeed() As double (Read Only)
|
| returns the speed set by the user by set_SpecifiedJointSpeed
:rtype: float
"""
return self.human_task.SpecifiedJointSpeed
@property
def worker_resource(self) -> SWKManikin:
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-09-25 14:34:21.593357)
| o Property WorkerResource() As SWKManikin (Read Only)
|
| Returns the Worker-Resource associated with this
| worker-activity.
|
| Returns:
| oManikin
:rtype: SWKManikin
"""
return SWKManikin(self.human_task.WorkerResource)
def set_specified_cycle_time(self, time: float, i_override_child_act_simulation_time: int) -> None:
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-09-25 14:34:21.593357))
| o Sub set_SpecifiedCycleTime(double time,
| long iOverrideChildActSimulationTime)
|
| sets the time on the specified task iOverrideChildActSimulationTime: this
| should be set equal to zero when no child act overriding is required
:param float time:
:param int i_override_child_act_simulation_time:
:rtype: None
"""
return self.human_task.set_SpecifiedCycleTime(time, i_override_child_act_simulation_time)
def set_specified_joint_speed(self, speed: float, i_override_child_joint_speed: int) -> None:
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-09-25 14:34:21.593357))
| o Sub set_SpecifiedJointSpeed(double speed,
| long iOverrideChildJointSpeed)
|
| sets the joint speed on the specified task(speed should be between 0.0 to
| 1.0) iOverrideChildJointSpeed: this should be set equal to zero when no child
| act overriding is required
:param float speed:
:param int i_override_child_joint_speed:
:rtype: None
"""
return self.human_task.set_SpecifiedJointSpeed(speed, i_override_child_joint_speed)
def __repr__(self):
return f'HumanTask(name="{self.name}")'
| 0 | 0.918718 | 1 | 0.918718 | game-dev | MEDIA | 0.298749 | game-dev | 0.844366 | 1 | 0.844366 |
MATTYOneInc/AionEncomBase_Java8 | 3,506 | AL-Game/data/scripts/system/handlers/ai/instance/abyssalSplinter/Artifact_Of_ProtectionAI2.java | /*
* This file is part of Encom.
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.instance.abyssalSplinter;
import com.aionemu.gameserver.ai2.AI2Actions;
import com.aionemu.gameserver.ai2.AIName;
import com.aionemu.gameserver.ai2.NpcAI2;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.world.World;
import com.aionemu.gameserver.world.knownlist.Visitor;
/****/
/** Author (Encom)
/****/
@AIName("Artifact_Of_Protection")
public class Artifact_Of_ProtectionAI2 extends NpcAI2
{
@Override
protected void handleDialogStart(Player player) {
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getOwner().getObjectId(), 1011));
}
@Override
public boolean onDialogSelect(final Player player, int dialogId, int questId, int extendedRewardIndex) {
if (dialogId == 10000) {
switch (getNpcId()) {
case 700856: //Artifact Of Protection.
switch (player.getWorldId()) {
case 300220000: //Abyssal Splinter.
announceArtifactProtector();
spawn(216952, 329.61923f, 733.8852f, 197.60815f, (byte) 80); //Yamennes Blindsight.
break;
case 300600000: //Unstable Abyssal Splinter.
announceArtifactProtector();
spawn(219555, 329.61923f, 733.8852f, 197.60815f, (byte) 80); //Durable Yamennes Blindsight.
break;
}
break;
}
} else if (dialogId == 10001) {
switch (getNpcId()) {
case 700856: //Artifact Of Protection.
switch (player.getWorldId()) {
case 300220000: //Abyssal Splinter.
announceFerociousProtector();
spawn(216960, 329.61923f, 733.8852f, 197.60815f, (byte) 80); //Yamennes Painflare.
break;
case 300600000: //Unstable Abyssal Splinter.
announceFerociousProtector();
spawn(219563, 329.61923f, 733.8852f, 197.60815f, (byte) 80); //Unstable Yamennes Painflare.
break;
}
break;
}
}
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 0));
AI2Actions.deleteOwner(this);
return true;
}
private void announceArtifactProtector() {
getPosition().getWorldMapInstance().doOnAllPlayers(new Visitor<Player>() {
@Override
public void visit(Player player) {
//An Artifact Protector has appeared!
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_IDAbRe_Core_NmdD_Wakeup);
}
});
}
private void announceFerociousProtector() {
getPosition().getWorldMapInstance().doOnAllPlayers(new Visitor<Player>() {
@Override
public void visit(Player player) {
//A Ferocious Artifact Protector has appeared!
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_IDAbRe_Core_NmdDH_Wakeup);
}
});
}
} | 0 | 0.927281 | 1 | 0.927281 | game-dev | MEDIA | 0.9559 | game-dev | 0.749513 | 1 | 0.749513 |
golangpoland/meetup_golang_warsaw | 44,807 | 2018/2018_19_Meetup/Intro/plugin/css/reveal.scss | /*!
* reveal.js
* http://revealjs.com
* MIT licensed
*
* Copyright (C) 2018 Hakim El Hattab, http://hakim.se
*/
/*********************************************
* RESET STYLES
*********************************************/
html, body, .reveal div, .reveal span, .reveal applet, .reveal object, .reveal iframe,
.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6, .reveal p, .reveal blockquote, .reveal pre,
.reveal a, .reveal abbr, .reveal acronym, .reveal address, .reveal big, .reveal cite, .reveal code,
.reveal del, .reveal dfn, .reveal em, .reveal img, .reveal ins, .reveal kbd, .reveal q, .reveal s, .reveal samp,
.reveal small, .reveal strike, .reveal strong, .reveal sub, .reveal sup, .reveal tt, .reveal var,
.reveal b, .reveal u, .reveal center,
.reveal dl, .reveal dt, .reveal dd, .reveal ol, .reveal ul, .reveal li,
.reveal fieldset, .reveal form, .reveal label, .reveal legend,
.reveal table, .reveal caption, .reveal tbody, .reveal tfoot, .reveal thead, .reveal tr, .reveal th, .reveal td,
.reveal article, .reveal aside, .reveal canvas, .reveal details, .reveal embed,
.reveal figure, .reveal figcaption, .reveal footer, .reveal header, .reveal hgroup,
.reveal menu, .reveal nav, .reveal output, .reveal ruby, .reveal section, .reveal summary,
.reveal time, .reveal mark, .reveal audio, .reveal video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
.reveal article, .reveal aside, .reveal details, .reveal figcaption, .reveal figure,
.reveal footer, .reveal header, .reveal hgroup, .reveal menu, .reveal nav, .reveal section {
display: block;
}
/*********************************************
* GLOBAL STYLES
*********************************************/
html,
body {
width: 100%;
height: 100%;
overflow: hidden;
}
body {
position: relative;
line-height: 1;
background-color: #fff;
color: #000;
}
/*********************************************
* VIEW FRAGMENTS
*********************************************/
.reveal .slides section .fragment {
opacity: 0;
visibility: hidden;
transition: all .2s ease;
&.visible {
opacity: 1;
visibility: inherit;
}
}
.reveal .slides section .fragment.grow {
opacity: 1;
visibility: inherit;
&.visible {
transform: scale( 1.3 );
}
}
.reveal .slides section .fragment.shrink {
opacity: 1;
visibility: inherit;
&.visible {
transform: scale( 0.7 );
}
}
.reveal .slides section .fragment.zoom-in {
transform: scale( 0.1 );
&.visible {
transform: none;
}
}
.reveal .slides section .fragment.fade-out {
opacity: 1;
visibility: inherit;
&.visible {
opacity: 0;
visibility: hidden;
}
}
.reveal .slides section .fragment.semi-fade-out {
opacity: 1;
visibility: inherit;
&.visible {
opacity: 0.5;
visibility: inherit;
}
}
.reveal .slides section .fragment.strike {
opacity: 1;
visibility: inherit;
&.visible {
text-decoration: line-through;
}
}
.reveal .slides section .fragment.fade-up {
transform: translate(0, 20%);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-down {
transform: translate(0, -20%);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-right {
transform: translate(-20%, 0);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-left {
transform: translate(20%, 0);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-in-then-out,
.reveal .slides section .fragment.current-visible {
opacity: 0;
visibility: hidden;
&.current-fragment {
opacity: 1;
visibility: inherit;
}
}
.reveal .slides section .fragment.fade-in-then-semi-out {
opacity: 0;
visibility: hidden;
&.visible {
opacity: 0.5;
visibility: inherit;
}
&.current-fragment {
opacity: 1;
visibility: inherit;
}
}
.reveal .slides section .fragment.highlight-red,
.reveal .slides section .fragment.highlight-current-red,
.reveal .slides section .fragment.highlight-green,
.reveal .slides section .fragment.highlight-current-green,
.reveal .slides section .fragment.highlight-blue,
.reveal .slides section .fragment.highlight-current-blue {
opacity: 1;
visibility: inherit;
}
.reveal .slides section .fragment.highlight-red.visible {
color: #ff2c2d
}
.reveal .slides section .fragment.highlight-green.visible {
color: #17ff2e;
}
.reveal .slides section .fragment.highlight-blue.visible {
color: #1b91ff;
}
.reveal .slides section .fragment.highlight-current-red.current-fragment {
color: #ff2c2d
}
.reveal .slides section .fragment.highlight-current-green.current-fragment {
color: #17ff2e;
}
.reveal .slides section .fragment.highlight-current-blue.current-fragment {
color: #1b91ff;
}
/*********************************************
* DEFAULT ELEMENT STYLES
*********************************************/
/* Fixes issue in Chrome where italic fonts did not appear when printing to PDF */
.reveal:after {
content: '';
font-style: italic;
}
.reveal iframe {
z-index: 1;
}
/** Prevents layering issues in certain browser/transition combinations */
.reveal a {
position: relative;
}
.reveal .stretch {
max-width: none;
max-height: none;
}
.reveal pre.stretch code {
height: 100%;
max-height: 100%;
box-sizing: border-box;
}
/*********************************************
* CONTROLS
*********************************************/
@keyframes bounce-right {
0%, 10%, 25%, 40%, 50% {transform: translateX(0);}
20% {transform: translateX(10px);}
30% {transform: translateX(-5px);}
}
@keyframes bounce-down {
0%, 10%, 25%, 40%, 50% {transform: translateY(0);}
20% {transform: translateY(10px);}
30% {transform: translateY(-5px);}
}
$controlArrowSize: 3.6em;
$controlArrowSpacing: 1.4em;
$controlArrowLength: 2.6em;
$controlArrowThickness: 0.5em;
$controlsArrowAngle: 45deg;
$controlsArrowAngleHover: 40deg;
$controlsArrowAngleActive: 36deg;
@mixin controlsArrowTransform( $angle ) {
&:before {
transform: translateX(($controlArrowSize - $controlArrowLength)/2) translateY(($controlArrowSize - $controlArrowThickness)/2) rotate( $angle );
}
&:after {
transform: translateX(($controlArrowSize - $controlArrowLength)/2) translateY(($controlArrowSize - $controlArrowThickness)/2) rotate( -$angle );
}
}
.reveal .controls {
$spacing: 12px;
display: none;
position: absolute;
top: auto;
bottom: $spacing;
right: $spacing;
left: auto;
z-index: 1;
color: #000;
pointer-events: none;
font-size: 10px;
button {
position: absolute;
padding: 0;
background-color: transparent;
border: 0;
outline: 0;
cursor: pointer;
color: currentColor;
transform: scale(.9999);
transition: color 0.2s ease,
opacity 0.2s ease,
transform 0.2s ease;
z-index: 2; // above slides
pointer-events: auto;
font-size: inherit;
visibility: hidden;
opacity: 0;
-webkit-appearance: none;
-webkit-tap-highlight-color: rgba( 0, 0, 0, 0 );
}
.controls-arrow:before,
.controls-arrow:after {
content: '';
position: absolute;
top: 0;
left: 0;
width: $controlArrowLength;
height: $controlArrowThickness;
border-radius: $controlArrowThickness/2;
background-color: currentColor;
transition: all 0.15s ease, background-color 0.8s ease;
transform-origin: floor(($controlArrowThickness/2)*10)/10 50%;
will-change: transform;
}
.controls-arrow {
position: relative;
width: $controlArrowSize;
height: $controlArrowSize;
@include controlsArrowTransform( $controlsArrowAngle );
&:hover {
@include controlsArrowTransform( $controlsArrowAngleHover );
}
&:active {
@include controlsArrowTransform( $controlsArrowAngleActive );
}
}
.navigate-left {
right: $controlArrowSize + $controlArrowSpacing*2;
bottom: $controlArrowSpacing + $controlArrowSize/2;
transform: translateX( -10px );
}
.navigate-right {
right: 0;
bottom: $controlArrowSpacing + $controlArrowSize/2;
transform: translateX( 10px );
.controls-arrow {
transform: rotate( 180deg );
}
&.highlight {
animation: bounce-right 2s 50 both ease-out;
}
}
.navigate-up {
right: $controlArrowSpacing + $controlArrowSize/2;
bottom: $controlArrowSpacing*2 + $controlArrowSize;
transform: translateY( -10px );
.controls-arrow {
transform: rotate( 90deg );
}
}
.navigate-down {
right: $controlArrowSpacing + $controlArrowSize/2;
bottom: 0;
transform: translateY( 10px );
.controls-arrow {
transform: rotate( -90deg );
}
&.highlight {
animation: bounce-down 2s 50 both ease-out;
}
}
// Back arrow style: "faded":
// Deemphasize backwards navigation arrows in favor of drawing
// attention to forwards navigation
&[data-controls-back-arrows="faded"] .navigate-left.enabled,
&[data-controls-back-arrows="faded"] .navigate-up.enabled {
opacity: 0.3;
&:hover {
opacity: 1;
}
}
// Back arrow style: "hidden":
// Never show arrows for backwards navigation
&[data-controls-back-arrows="hidden"] .navigate-left.enabled,
&[data-controls-back-arrows="hidden"] .navigate-up.enabled {
opacity: 0;
visibility: hidden;
}
// Any control button that can be clicked is "enabled"
.enabled {
visibility: visible;
opacity: 0.9;
cursor: pointer;
transform: none;
}
// Any control button that leads to showing or hiding
// a fragment
.enabled.fragmented {
opacity: 0.5;
}
.enabled:hover,
.enabled.fragmented:hover {
opacity: 1;
}
}
// Adjust the layout when there are no vertical slides
.reveal:not(.has-vertical-slides) .controls .navigate-left {
bottom: $controlArrowSpacing;
right: 0.5em + $controlArrowSpacing + $controlArrowSize;
}
.reveal:not(.has-vertical-slides) .controls .navigate-right {
bottom: $controlArrowSpacing;
right: 0.5em;
}
// Adjust the layout when there are no horizontal slides
.reveal:not(.has-horizontal-slides) .controls .navigate-up {
right: $controlArrowSpacing;
bottom: $controlArrowSpacing + $controlArrowSize;
}
.reveal:not(.has-horizontal-slides) .controls .navigate-down {
right: $controlArrowSpacing;
bottom: 0.5em;
}
// Invert arrows based on background color
.reveal.has-dark-background .controls {
color: #fff;
}
.reveal.has-light-background .controls {
color: #000;
}
// Disable active states on touch devices
.reveal.no-hover .controls .controls-arrow:hover,
.reveal.no-hover .controls .controls-arrow:active {
@include controlsArrowTransform( $controlsArrowAngle );
}
// Edge aligned controls layout
@media screen and (min-width: 500px) {
$spacing: 8px;
.reveal .controls[data-controls-layout="edges"] {
& {
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.navigate-left,
.navigate-right,
.navigate-up,
.navigate-down {
bottom: auto;
right: auto;
}
.navigate-left {
top: 50%;
left: $spacing;
margin-top: -$controlArrowSize/2;
}
.navigate-right {
top: 50%;
right: $spacing;
margin-top: -$controlArrowSize/2;
}
.navigate-up {
top: $spacing;
left: 50%;
margin-left: -$controlArrowSize/2;
}
.navigate-down {
bottom: $spacing;
left: 50%;
margin-left: -$controlArrowSize/2;
}
}
}
/*********************************************
* PROGRESS BAR
*********************************************/
.reveal .progress {
position: absolute;
display: none;
height: 3px;
width: 100%;
bottom: 0;
left: 0;
z-index: 10;
background-color: rgba( 0, 0, 0, 0.2 );
color: #fff;
}
.reveal .progress:after {
content: '';
display: block;
position: absolute;
height: 10px;
width: 100%;
top: -10px;
}
.reveal .progress span {
display: block;
height: 100%;
width: 0px;
background-color: currentColor;
transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
/*********************************************
* SLIDE NUMBER
*********************************************/
.reveal .slide-number {
position: absolute;
display: block;
right: 8px;
bottom: 8px;
z-index: 31;
font-family: Helvetica, sans-serif;
font-size: 12px;
line-height: 1;
color: #fff;
background-color: rgba( 0, 0, 0, 0.4 );
padding: 5px;
}
.reveal .slide-number a {
color: currentColor;
}
.reveal .slide-number-delimiter {
margin: 0 3px;
}
/*********************************************
* SLIDES
*********************************************/
.reveal {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
touch-action: none;
}
// Mobile Safari sometimes overlays a header at the top
// of the page when in landscape mode. Using fixed
// positioning ensures that reveal.js reduces its height
// when this header is visible.
@media only screen and (orientation : landscape) {
.reveal.ua-iphone {
position: fixed;
}
}
.reveal .slides {
position: absolute;
width: 100%;
height: 100%;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
pointer-events: none;
overflow: visible;
z-index: 1;
text-align: center;
perspective: 600px;
perspective-origin: 50% 40%;
}
.reveal .slides>section {
-ms-perspective: 600px;
}
.reveal .slides>section,
.reveal .slides>section>section {
display: none;
position: absolute;
width: 100%;
padding: 20px 0px;
pointer-events: auto;
z-index: 10;
transform-style: flat;
transition: transform-origin 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985),
transform 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985),
visibility 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985),
opacity 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
/* Global transition speed settings */
.reveal[data-transition-speed="fast"] .slides section {
transition-duration: 400ms;
}
.reveal[data-transition-speed="slow"] .slides section {
transition-duration: 1200ms;
}
/* Slide-specific transition speed overrides */
.reveal .slides section[data-transition-speed="fast"] {
transition-duration: 400ms;
}
.reveal .slides section[data-transition-speed="slow"] {
transition-duration: 1200ms;
}
.reveal .slides>section.stack {
padding-top: 0;
padding-bottom: 0;
pointer-events: none;
}
.reveal .slides>section.present,
.reveal .slides>section>section.present {
display: block;
z-index: 11;
opacity: 1;
}
.reveal .slides>section:empty,
.reveal .slides>section>section:empty,
.reveal .slides>section[data-background-interactive],
.reveal .slides>section>section[data-background-interactive] {
pointer-events: none;
}
.reveal.center,
.reveal.center .slides,
.reveal.center .slides section {
min-height: 0 !important;
}
/* Don't allow interaction with invisible slides */
.reveal .slides>section.future,
.reveal .slides>section>section.future,
.reveal .slides>section.past,
.reveal .slides>section>section.past {
pointer-events: none;
}
.reveal.overview .slides>section,
.reveal.overview .slides>section>section {
pointer-events: auto;
}
.reveal .slides>section.past,
.reveal .slides>section.future,
.reveal .slides>section>section.past,
.reveal .slides>section>section.future {
opacity: 0;
}
/*********************************************
* Mixins for readability of transitions
*********************************************/
@mixin transition-global($style) {
.reveal .slides section[data-transition=#{$style}],
.reveal.#{$style} .slides section:not([data-transition]) {
@content;
}
}
@mixin transition-stack($style) {
.reveal .slides section[data-transition=#{$style}].stack,
.reveal.#{$style} .slides section.stack {
@content;
}
}
@mixin transition-horizontal-past($style) {
.reveal .slides>section[data-transition=#{$style}].past,
.reveal .slides>section[data-transition~=#{$style}-out].past,
.reveal.#{$style} .slides>section:not([data-transition]).past {
@content;
}
}
@mixin transition-horizontal-future($style) {
.reveal .slides>section[data-transition=#{$style}].future,
.reveal .slides>section[data-transition~=#{$style}-in].future,
.reveal.#{$style} .slides>section:not([data-transition]).future {
@content;
}
}
@mixin transition-vertical-past($style) {
.reveal .slides>section>section[data-transition=#{$style}].past,
.reveal .slides>section>section[data-transition~=#{$style}-out].past,
.reveal.#{$style} .slides>section>section:not([data-transition]).past {
@content;
}
}
@mixin transition-vertical-future($style) {
.reveal .slides>section>section[data-transition=#{$style}].future,
.reveal .slides>section>section[data-transition~=#{$style}-in].future,
.reveal.#{$style} .slides>section>section:not([data-transition]).future {
@content;
}
}
/*********************************************
* SLIDE TRANSITION
* Aliased 'linear' for backwards compatibility
*********************************************/
@each $stylename in slide, linear {
.reveal.#{$stylename} section {
backface-visibility: hidden;
}
@include transition-horizontal-past(#{$stylename}) {
transform: translate(-150%, 0);
}
@include transition-horizontal-future(#{$stylename}) {
transform: translate(150%, 0);
}
@include transition-vertical-past(#{$stylename}) {
transform: translate(0, -150%);
}
@include transition-vertical-future(#{$stylename}) {
transform: translate(0, 150%);
}
}
/*********************************************
* CONVEX TRANSITION
* Aliased 'default' for backwards compatibility
*********************************************/
@each $stylename in default, convex {
@include transition-stack(#{$stylename}) {
transform-style: preserve-3d;
}
@include transition-horizontal-past(#{$stylename}) {
transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
}
@include transition-horizontal-future(#{$stylename}) {
transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
}
@include transition-vertical-past(#{$stylename}) {
transform: translate3d(0, -300px, 0) rotateX(70deg) translate3d(0, -300px, 0);
}
@include transition-vertical-future(#{$stylename}) {
transform: translate3d(0, 300px, 0) rotateX(-70deg) translate3d(0, 300px, 0);
}
}
/*********************************************
* CONCAVE TRANSITION
*********************************************/
@include transition-stack(concave) {
transform-style: preserve-3d;
}
@include transition-horizontal-past(concave) {
transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
}
@include transition-horizontal-future(concave) {
transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
}
@include transition-vertical-past(concave) {
transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0);
}
@include transition-vertical-future(concave) {
transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0);
}
/*********************************************
* ZOOM TRANSITION
*********************************************/
@include transition-global(zoom) {
transition-timing-function: ease;
}
@include transition-horizontal-past(zoom) {
visibility: hidden;
transform: scale(16);
}
@include transition-horizontal-future(zoom) {
visibility: hidden;
transform: scale(0.2);
}
@include transition-vertical-past(zoom) {
transform: translate(0, -150%);
}
@include transition-vertical-future(zoom) {
transform: translate(0, 150%);
}
/*********************************************
* CUBE TRANSITION
*
* WARNING:
* this is deprecated and will be removed in a
* future version.
*********************************************/
.reveal.cube .slides {
perspective: 1300px;
}
.reveal.cube .slides section {
padding: 30px;
min-height: 700px;
backface-visibility: hidden;
box-sizing: border-box;
transform-style: preserve-3d;
}
.reveal.center.cube .slides section {
min-height: 0;
}
.reveal.cube .slides section:not(.stack):before {
content: '';
position: absolute;
display: block;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: rgba(0,0,0,0.1);
border-radius: 4px;
transform: translateZ( -20px );
}
.reveal.cube .slides section:not(.stack):after {
content: '';
position: absolute;
display: block;
width: 90%;
height: 30px;
left: 5%;
bottom: 0;
background: none;
z-index: 1;
border-radius: 4px;
box-shadow: 0px 95px 25px rgba(0,0,0,0.2);
transform: translateZ(-90px) rotateX( 65deg );
}
.reveal.cube .slides>section.stack {
padding: 0;
background: none;
}
.reveal.cube .slides>section.past {
transform-origin: 100% 0%;
transform: translate3d(-100%, 0, 0) rotateY(-90deg);
}
.reveal.cube .slides>section.future {
transform-origin: 0% 0%;
transform: translate3d(100%, 0, 0) rotateY(90deg);
}
.reveal.cube .slides>section>section.past {
transform-origin: 0% 100%;
transform: translate3d(0, -100%, 0) rotateX(90deg);
}
.reveal.cube .slides>section>section.future {
transform-origin: 0% 0%;
transform: translate3d(0, 100%, 0) rotateX(-90deg);
}
/*********************************************
* PAGE TRANSITION
*
* WARNING:
* this is deprecated and will be removed in a
* future version.
*********************************************/
.reveal.page .slides {
perspective-origin: 0% 50%;
perspective: 3000px;
}
.reveal.page .slides section {
padding: 30px;
min-height: 700px;
box-sizing: border-box;
transform-style: preserve-3d;
}
.reveal.page .slides section.past {
z-index: 12;
}
.reveal.page .slides section:not(.stack):before {
content: '';
position: absolute;
display: block;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: rgba(0,0,0,0.1);
transform: translateZ( -20px );
}
.reveal.page .slides section:not(.stack):after {
content: '';
position: absolute;
display: block;
width: 90%;
height: 30px;
left: 5%;
bottom: 0;
background: none;
z-index: 1;
border-radius: 4px;
box-shadow: 0px 95px 25px rgba(0,0,0,0.2);
-webkit-transform: translateZ(-90px) rotateX( 65deg );
}
.reveal.page .slides>section.stack {
padding: 0;
background: none;
}
.reveal.page .slides>section.past {
transform-origin: 0% 0%;
transform: translate3d(-40%, 0, 0) rotateY(-80deg);
}
.reveal.page .slides>section.future {
transform-origin: 100% 0%;
transform: translate3d(0, 0, 0);
}
.reveal.page .slides>section>section.past {
transform-origin: 0% 0%;
transform: translate3d(0, -40%, 0) rotateX(80deg);
}
.reveal.page .slides>section>section.future {
transform-origin: 0% 100%;
transform: translate3d(0, 0, 0);
}
/*********************************************
* FADE TRANSITION
*********************************************/
.reveal .slides section[data-transition=fade],
.reveal.fade .slides section:not([data-transition]),
.reveal.fade .slides>section>section:not([data-transition]) {
transform: none;
transition: opacity 0.5s;
}
.reveal.fade.overview .slides section,
.reveal.fade.overview .slides>section>section {
transition: none;
}
/*********************************************
* NO TRANSITION
*********************************************/
@include transition-global(none) {
transform: none;
transition: none;
}
/*********************************************
* PAUSED MODE
*********************************************/
.reveal .pause-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: black;
visibility: hidden;
opacity: 0;
z-index: 100;
transition: all 1s ease;
}
.reveal .pause-overlay .resume-button {
position: absolute;
bottom: 20px;
right: 20px;
color: #ccc;
border-radius: 2px;
padding: 6px 14px;
border: 2px solid #ccc;
font-size: 16px;
background: transparent;
cursor: pointer;
&:hover {
color: #fff;
border-color: #fff;
}
}
.reveal.paused .pause-overlay {
visibility: visible;
opacity: 1;
}
/*********************************************
* FALLBACK
*********************************************/
.no-transforms {
overflow-y: auto;
}
.no-transforms .reveal .slides {
position: relative;
width: 80%;
height: auto !important;
top: 0;
left: 50%;
margin: 0;
text-align: center;
}
.no-transforms .reveal .controls,
.no-transforms .reveal .progress {
display: none !important;
}
.no-transforms .reveal .slides section {
display: block !important;
opacity: 1 !important;
position: relative !important;
height: auto;
min-height: 0;
top: 0;
left: -50%;
margin: 70px 0;
transform: none;
}
.no-transforms .reveal .slides section section {
left: 0;
}
.reveal .no-transition,
.reveal .no-transition * {
transition: none !important;
}
/*********************************************
* PER-SLIDE BACKGROUNDS
*********************************************/
.reveal .backgrounds {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
perspective: 600px;
}
.reveal .slide-background {
display: none;
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
visibility: hidden;
overflow: hidden;
background-color: rgba( 0, 0, 0, 0 );
transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
.reveal .slide-background-content {
position: absolute;
width: 100%;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
}
.reveal .slide-background.stack {
display: block;
}
.reveal .slide-background.present {
opacity: 1;
visibility: visible;
z-index: 2;
}
.print-pdf .reveal .slide-background {
opacity: 1 !important;
visibility: visible !important;
}
/* Video backgrounds */
.reveal .slide-background video {
position: absolute;
width: 100%;
height: 100%;
max-width: none;
max-height: none;
top: 0;
left: 0;
object-fit: cover;
}
.reveal .slide-background[data-background-size="contain"] video {
object-fit: contain;
}
/* Immediate transition style */
.reveal[data-background-transition=none]>.backgrounds .slide-background,
.reveal>.backgrounds .slide-background[data-background-transition=none] {
transition: none;
}
/* Slide */
.reveal[data-background-transition=slide]>.backgrounds .slide-background,
.reveal>.backgrounds .slide-background[data-background-transition=slide] {
opacity: 1;
backface-visibility: hidden;
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=slide] {
transform: translate(-100%, 0);
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=slide] {
transform: translate(100%, 0);
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=slide] {
transform: translate(0, -100%);
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=slide] {
transform: translate(0, 100%);
}
/* Convex */
.reveal[data-background-transition=convex]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=convex] {
opacity: 0;
transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
}
.reveal[data-background-transition=convex]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=convex] {
opacity: 0;
transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
}
.reveal[data-background-transition=convex]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=convex] {
opacity: 0;
transform: translate3d(0, -100%, 0) rotateX(90deg) translate3d(0, -100%, 0);
}
.reveal[data-background-transition=convex]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=convex] {
opacity: 0;
transform: translate3d(0, 100%, 0) rotateX(-90deg) translate3d(0, 100%, 0);
}
/* Concave */
.reveal[data-background-transition=concave]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=concave] {
opacity: 0;
transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
}
.reveal[data-background-transition=concave]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=concave] {
opacity: 0;
transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
}
.reveal[data-background-transition=concave]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=concave] {
opacity: 0;
transform: translate3d(0, -100%, 0) rotateX(-90deg) translate3d(0, -100%, 0);
}
.reveal[data-background-transition=concave]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=concave] {
opacity: 0;
transform: translate3d(0, 100%, 0) rotateX(90deg) translate3d(0, 100%, 0);
}
/* Zoom */
.reveal[data-background-transition=zoom]>.backgrounds .slide-background,
.reveal>.backgrounds .slide-background[data-background-transition=zoom] {
transition-timing-function: ease;
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(16);
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(0.2);
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(16);
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(0.2);
}
/* Global transition speed settings */
.reveal[data-transition-speed="fast"]>.backgrounds .slide-background {
transition-duration: 400ms;
}
.reveal[data-transition-speed="slow"]>.backgrounds .slide-background {
transition-duration: 1200ms;
}
/*********************************************
* OVERVIEW
*********************************************/
.reveal.overview {
perspective-origin: 50% 50%;
perspective: 700px;
.slides {
// Fixes overview rendering errors in FF48+, not applied to
// other browsers since it degrades performance
-moz-transform-style: preserve-3d;
}
.slides section {
height: 100%;
top: 0 !important;
opacity: 1 !important;
overflow: hidden;
visibility: visible !important;
cursor: pointer;
box-sizing: border-box;
}
.slides section:hover,
.slides section.present {
outline: 10px solid rgba(150,150,150,0.4);
outline-offset: 10px;
}
.slides section .fragment {
opacity: 1;
transition: none;
}
.slides section:after,
.slides section:before {
display: none !important;
}
.slides>section.stack {
padding: 0;
top: 0 !important;
background: none;
outline: none;
overflow: visible;
}
.backgrounds {
perspective: inherit;
// Fixes overview rendering errors in FF48+, not applied to
// other browsers since it degrades performance
-moz-transform-style: preserve-3d;
}
.backgrounds .slide-background {
opacity: 1;
visibility: visible;
// This can't be applied to the slide itself in Safari
outline: 10px solid rgba(150,150,150,0.1);
outline-offset: 10px;
}
.backgrounds .slide-background.stack {
overflow: visible;
}
}
// Disable transitions transitions while we're activating
// or deactivating the overview mode.
.reveal.overview .slides section,
.reveal.overview-deactivating .slides section {
transition: none;
}
.reveal.overview .backgrounds .slide-background,
.reveal.overview-deactivating .backgrounds .slide-background {
transition: none;
}
/*********************************************
* RTL SUPPORT
*********************************************/
.reveal.rtl .slides,
.reveal.rtl .slides h1,
.reveal.rtl .slides h2,
.reveal.rtl .slides h3,
.reveal.rtl .slides h4,
.reveal.rtl .slides h5,
.reveal.rtl .slides h6 {
direction: rtl;
font-family: sans-serif;
}
.reveal.rtl pre,
.reveal.rtl code {
direction: ltr;
}
.reveal.rtl ol,
.reveal.rtl ul {
text-align: right;
}
.reveal.rtl .progress span {
float: right
}
/*********************************************
* PARALLAX BACKGROUND
*********************************************/
.reveal.has-parallax-background .backgrounds {
transition: all 0.8s ease;
}
/* Global transition speed settings */
.reveal.has-parallax-background[data-transition-speed="fast"] .backgrounds {
transition-duration: 400ms;
}
.reveal.has-parallax-background[data-transition-speed="slow"] .backgrounds {
transition-duration: 1200ms;
}
/*********************************************
* LINK PREVIEW OVERLAY
*********************************************/
.reveal .overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1000;
background: rgba( 0, 0, 0, 0.9 );
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.reveal .overlay.visible {
opacity: 1;
visibility: visible;
}
.reveal .overlay .spinner {
position: absolute;
display: block;
top: 50%;
left: 50%;
width: 32px;
height: 32px;
margin: -16px 0 0 -16px;
z-index: 10;
background-image: url(data:image/gif;base64,R0lGODlhIAAgAPMAAJmZmf%2F%2F%2F6%2Bvr8nJybW1tcDAwOjo6Nvb26ioqKOjo7Ozs%2FLy8vz8%2FAAAAAAAAAAAACH%2FC05FVFNDQVBFMi4wAwEAAAAh%2FhpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh%2BQQJCgAAACwAAAAAIAAgAAAE5xDISWlhperN52JLhSSdRgwVo1ICQZRUsiwHpTJT4iowNS8vyW2icCF6k8HMMBkCEDskxTBDAZwuAkkqIfxIQyhBQBFvAQSDITM5VDW6XNE4KagNh6Bgwe60smQUB3d4Rz1ZBApnFASDd0hihh12BkE9kjAJVlycXIg7CQIFA6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YJvpJivxNaGmLHT0VnOgSYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ%2FV%2FnmOM82XiHRLYKhKP1oZmADdEAAAh%2BQQJCgAAACwAAAAAIAAgAAAE6hDISWlZpOrNp1lGNRSdRpDUolIGw5RUYhhHukqFu8DsrEyqnWThGvAmhVlteBvojpTDDBUEIFwMFBRAmBkSgOrBFZogCASwBDEY%2FCZSg7GSE0gSCjQBMVG023xWBhklAnoEdhQEfyNqMIcKjhRsjEdnezB%2BA4k8gTwJhFuiW4dokXiloUepBAp5qaKpp6%2BHo7aWW54wl7obvEe0kRuoplCGepwSx2jJvqHEmGt6whJpGpfJCHmOoNHKaHx61WiSR92E4lbFoq%2BB6QDtuetcaBPnW6%2BO7wDHpIiK9SaVK5GgV543tzjgGcghAgAh%2BQQJCgAAACwAAAAAIAAgAAAE7hDISSkxpOrN5zFHNWRdhSiVoVLHspRUMoyUakyEe8PTPCATW9A14E0UvuAKMNAZKYUZCiBMuBakSQKG8G2FzUWox2AUtAQFcBKlVQoLgQReZhQlCIJesQXI5B0CBnUMOxMCenoCfTCEWBsJColTMANldx15BGs8B5wlCZ9Po6OJkwmRpnqkqnuSrayqfKmqpLajoiW5HJq7FL1Gr2mMMcKUMIiJgIemy7xZtJsTmsM4xHiKv5KMCXqfyUCJEonXPN2rAOIAmsfB3uPoAK%2B%2BG%2Bw48edZPK%2BM6hLJpQg484enXIdQFSS1u6UhksENEQAAIfkECQoAAAAsAAAAACAAIAAABOcQyEmpGKLqzWcZRVUQnZYg1aBSh2GUVEIQ2aQOE%2BG%2BcD4ntpWkZQj1JIiZIogDFFyHI0UxQwFugMSOFIPJftfVAEoZLBbcLEFhlQiqGp1Vd140AUklUN3eCA51C1EWMzMCezCBBmkxVIVHBWd3HHl9JQOIJSdSnJ0TDKChCwUJjoWMPaGqDKannasMo6WnM562R5YluZRwur0wpgqZE7NKUm%2BFNRPIhjBJxKZteWuIBMN4zRMIVIhffcgojwCF117i4nlLnY5ztRLsnOk%2BaV%2BoJY7V7m76PdkS4trKcdg0Zc0tTcKkRAAAIfkECQoAAAAsAAAAACAAIAAABO4QyEkpKqjqzScpRaVkXZWQEximw1BSCUEIlDohrft6cpKCk5xid5MNJTaAIkekKGQkWyKHkvhKsR7ARmitkAYDYRIbUQRQjWBwJRzChi9CRlBcY1UN4g0%2FVNB0AlcvcAYHRyZPdEQFYV8ccwR5HWxEJ02YmRMLnJ1xCYp0Y5idpQuhopmmC2KgojKasUQDk5BNAwwMOh2RtRq5uQuPZKGIJQIGwAwGf6I0JXMpC8C7kXWDBINFMxS4DKMAWVWAGYsAdNqW5uaRxkSKJOZKaU3tPOBZ4DuK2LATgJhkPJMgTwKCdFjyPHEnKxFCDhEAACH5BAkKAAAALAAAAAAgACAAAATzEMhJaVKp6s2nIkolIJ2WkBShpkVRWqqQrhLSEu9MZJKK9y1ZrqYK9WiClmvoUaF8gIQSNeF1Er4MNFn4SRSDARWroAIETg1iVwuHjYB1kYc1mwruwXKC9gmsJXliGxc%2BXiUCby9ydh1sOSdMkpMTBpaXBzsfhoc5l58Gm5yToAaZhaOUqjkDgCWNHAULCwOLaTmzswadEqggQwgHuQsHIoZCHQMMQgQGubVEcxOPFAcMDAYUA85eWARmfSRQCdcMe0zeP1AAygwLlJtPNAAL19DARdPzBOWSm1brJBi45soRAWQAAkrQIykShQ9wVhHCwCQCACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiRMDjI0Fd30%2FiI2UA5GSS5UDj2l6NoqgOgN4gksEBgYFf0FDqKgHnyZ9OX8HrgYHdHpcHQULXAS2qKpENRg7eAMLC7kTBaixUYFkKAzWAAnLC7FLVxLWDBLKCwaKTULgEwbLA4hJtOkSBNqITT3xEgfLpBtzE%2FjiuL04RGEBgwWhShRgQExHBAAh%2BQQJCgAAACwAAAAAIAAgAAAE7xDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfZiCqGk5dTESJeaOAlClzsJsqwiJwiqnFrb2nS9kmIcgEsjQydLiIlHehhpejaIjzh9eomSjZR%2BipslWIRLAgMDOR2DOqKogTB9pCUJBagDBXR6XB0EBkIIsaRsGGMMAxoDBgYHTKJiUYEGDAzHC9EACcUGkIgFzgwZ0QsSBcXHiQvOwgDdEwfFs0sDzt4S6BK4xYjkDOzn0unFeBzOBijIm1Dgmg5YFQwsCMjp1oJ8LyIAACH5BAkKAAAALAAAAAAgACAAAATwEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GGl6NoiPOH16iZKNlH6KmyWFOggHhEEvAwwMA0N9GBsEC6amhnVcEwavDAazGwIDaH1ipaYLBUTCGgQDA8NdHz0FpqgTBwsLqAbWAAnIA4FWKdMLGdYGEgraigbT0OITBcg5QwPT4xLrROZL6AuQAPUS7bxLpoWidY0JtxLHKhwwMJBTHgPKdEQAACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GAULDJCRiXo1CpGXDJOUjY%2BYip9DhToJA4RBLwMLCwVDfRgbBAaqqoZ1XBMHswsHtxtFaH1iqaoGNgAIxRpbFAgfPQSqpbgGBqUD1wBXeCYp1AYZ19JJOYgH1KwA4UBvQwXUBxPqVD9L3sbp2BNk2xvvFPJd%2BMFCN6HAAIKgNggY0KtEBAAh%2BQQJCgAAACwAAAAAIAAgAAAE6BDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfYIDMaAFdTESJeaEDAIMxYFqrOUaNW4E4ObYcCXaiBVEgULe0NJaxxtYksjh2NLkZISgDgJhHthkpU4mW6blRiYmZOlh4JWkDqILwUGBnE6TYEbCgevr0N1gH4At7gHiRpFaLNrrq8HNgAJA70AWxQIH1%2BvsYMDAzZQPC9VCNkDWUhGkuE5PxJNwiUK4UfLzOlD4WvzAHaoG9nxPi5d%2BjYUqfAhhykOFwJWiAAAIfkECQoAAAAsAAAAACAAIAAABPAQyElpUqnqzaciSoVkXVUMFaFSwlpOCcMYlErAavhOMnNLNo8KsZsMZItJEIDIFSkLGQoQTNhIsFehRww2CQLKF0tYGKYSg%2BygsZIuNqJksKgbfgIGepNo2cIUB3V1B3IvNiBYNQaDSTtfhhx0CwVPI0UJe0%2Bbm4g5VgcGoqOcnjmjqDSdnhgEoamcsZuXO1aWQy8KAwOAuTYYGwi7w5h%2BKr0SJ8MFihpNbx%2B4Erq7BYBuzsdiH1jCAzoSfl0rVirNbRXlBBlLX%2BBP0XJLAPGzTkAuAOqb0WT5AH7OcdCm5B8TgRwSRKIHQtaLCwg1RAAAOwAAAAAAAAAAAA%3D%3D);
visibility: visible;
opacity: 0.6;
transition: all 0.3s ease;
}
.reveal .overlay header {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 40px;
z-index: 2;
border-bottom: 1px solid #222;
}
.reveal .overlay header a {
display: inline-block;
width: 40px;
height: 40px;
line-height: 36px;
padding: 0 10px;
float: right;
opacity: 0.6;
box-sizing: border-box;
}
.reveal .overlay header a:hover {
opacity: 1;
}
.reveal .overlay header a .icon {
display: inline-block;
width: 20px;
height: 20px;
background-position: 50% 50%;
background-size: 100%;
background-repeat: no-repeat;
}
.reveal .overlay header a.close .icon {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABkklEQVRYR8WX4VHDMAxG6wnoJrABZQPYBCaBTWAD2g1gE5gg6OOsXuxIlr40d81dfrSJ9V4c2VLK7spHuTJ/5wpM07QXuXc5X0opX2tEJcadjHuV80li/FgxTIEK/5QBCICBD6xEhSMGHgQPgBgLiYVAB1dpSqKDawxTohFw4JSEA3clzgIBPCURwE2JucBR7rhPJJv5OpJwDX+SfDjgx1wACQeJG1aChP9K/IMmdZ8DtESV1WyP3Bt4MwM6sj4NMxMYiqUWHQu4KYA/SYkIjOsm3BXYWMKFDwU2khjCQ4ELJUJ4SmClRArOCmSXGuKma0fYD5CbzHxFpCSGAhfAVSSUGDUk2BWZaff2g6GE15BsBQ9nwmpIGDiyHQddwNTMKkbZaf9fajXQca1EX44puJZUsnY0ObGmITE3GVLCbEhQUjGVt146j6oasWN+49Vph2w1pZ5EansNZqKBm1txbU57iRRcZ86RWMDdWtBJUHBHwoQPi1GV+JCbntmvok7iTX4/Up9mgyTc/FJYDTcndgH/AA5A/CHsyEkVAAAAAElFTkSuQmCC);
}
.reveal .overlay header a.external .icon {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAcElEQVRYR+2WSQoAIQwEzf8f7XiOMkUQxUPlGkM3hVmiQfQR9GYnH1SsAQlI4DiBqkCMoNb9y2e90IAEJPAcgdznU9+engMaeJ7Azh5Y1U67gAho4DqBqmB1buAf0MB1AlVBek83ZPkmJMGc1wAR+AAqod/B97TRpQAAAABJRU5ErkJggg==);
}
.reveal .overlay .viewport {
position: absolute;
display: flex;
top: 40px;
right: 0;
bottom: 0;
left: 0;
}
.reveal .overlay.overlay-preview .viewport iframe {
width: 100%;
height: 100%;
max-width: 100%;
max-height: 100%;
border: 0;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.reveal .overlay.overlay-preview.loaded .viewport iframe {
opacity: 1;
visibility: visible;
}
.reveal .overlay.overlay-preview.loaded .viewport-inner {
position: absolute;
z-index: -1;
left: 0;
top: 45%;
width: 100%;
text-align: center;
letter-spacing: normal;
}
.reveal .overlay.overlay-preview .x-frame-error {
opacity: 0;
transition: opacity 0.3s ease 0.3s;
}
.reveal .overlay.overlay-preview.loaded .x-frame-error {
opacity: 1;
}
.reveal .overlay.overlay-preview.loaded .spinner {
opacity: 0;
visibility: hidden;
transform: scale(0.2);
}
.reveal .overlay.overlay-help .viewport {
overflow: auto;
color: #fff;
}
.reveal .overlay.overlay-help .viewport .viewport-inner {
width: 600px;
margin: auto;
padding: 20px 20px 80px 20px;
text-align: center;
letter-spacing: normal;
}
.reveal .overlay.overlay-help .viewport .viewport-inner .title {
font-size: 20px;
}
.reveal .overlay.overlay-help .viewport .viewport-inner table {
border: 1px solid #fff;
border-collapse: collapse;
font-size: 16px;
}
.reveal .overlay.overlay-help .viewport .viewport-inner table th,
.reveal .overlay.overlay-help .viewport .viewport-inner table td {
width: 200px;
padding: 14px;
border: 1px solid #fff;
vertical-align: middle;
}
.reveal .overlay.overlay-help .viewport .viewport-inner table th {
padding-top: 20px;
padding-bottom: 20px;
}
/*********************************************
* PLAYBACK COMPONENT
*********************************************/
.reveal .playback {
position: absolute;
left: 15px;
bottom: 20px;
z-index: 30;
cursor: pointer;
transition: all 400ms ease;
-webkit-tap-highlight-color: rgba( 0, 0, 0, 0 );
}
.reveal.overview .playback {
opacity: 0;
visibility: hidden;
}
/*********************************************
* ROLLING LINKS
*********************************************/
.reveal .roll {
display: inline-block;
line-height: 1.2;
overflow: hidden;
vertical-align: top;
perspective: 400px;
perspective-origin: 50% 50%;
}
.reveal .roll:hover {
background: none;
text-shadow: none;
}
.reveal .roll span {
display: block;
position: relative;
padding: 0 2px;
pointer-events: none;
transition: all 400ms ease;
transform-origin: 50% 0%;
transform-style: preserve-3d;
backface-visibility: hidden;
}
.reveal .roll:hover span {
background: rgba(0,0,0,0.5);
transform: translate3d( 0px, 0px, -45px ) rotateX( 90deg );
}
.reveal .roll span:after {
content: attr(data-title);
display: block;
position: absolute;
left: 0;
top: 0;
padding: 0 2px;
backface-visibility: hidden;
transform-origin: 50% 0%;
transform: translate3d( 0px, 110%, 0px ) rotateX( -90deg );
}
/*********************************************
* SPEAKER NOTES
*********************************************/
// Hide on-page notes
.reveal aside.notes {
display: none;
}
// An interface element that can optionally be used to show the
// speaker notes to all viewers, on top of the presentation
.reveal .speaker-notes {
display: none;
position: absolute;
width: 25vw;
height: 100%;
top: 0;
left: 100%;
padding: 14px 18px 14px 18px;
z-index: 1;
font-size: 18px;
line-height: 1.4;
border: 1px solid rgba( 0, 0, 0, 0.05 );
color: #222;
background-color: #f5f5f5;
overflow: auto;
box-sizing: border-box;
text-align: left;
font-family: Helvetica, sans-serif;
-webkit-overflow-scrolling: touch;
.notes-placeholder {
color: #ccc;
font-style: italic;
}
&:focus {
outline: none;
}
&:before {
content: 'Speaker notes';
display: block;
margin-bottom: 10px;
opacity: 0.5;
}
}
.reveal.show-notes {
max-width: 75vw;
overflow: visible;
}
.reveal.show-notes .speaker-notes {
display: block;
}
@media screen and (min-width: 1600px) {
.reveal .speaker-notes {
font-size: 20px;
}
}
@media screen and (max-width: 1024px) {
.reveal.show-notes {
border-left: 0;
max-width: none;
max-height: 70%;
overflow: visible;
}
.reveal.show-notes .speaker-notes {
top: 100%;
left: 0;
width: 100%;
height: (30/0.7)*1%;
}
}
@media screen and (max-width: 600px) {
.reveal.show-notes {
max-height: 60%;
}
.reveal.show-notes .speaker-notes {
top: 100%;
height: (40/0.6)*1%;
}
.reveal .speaker-notes {
font-size: 14px;
}
}
/*********************************************
* ZOOM PLUGIN
*********************************************/
.zoomed .reveal *,
.zoomed .reveal *:before,
.zoomed .reveal *:after {
backface-visibility: visible !important;
}
.zoomed .reveal .progress,
.zoomed .reveal .controls {
opacity: 0;
}
.zoomed .reveal .roll span {
background: none;
}
.zoomed .reveal .roll span:after {
visibility: hidden;
}
| 0 | 0.717567 | 1 | 0.717567 | game-dev | MEDIA | 0.533764 | game-dev | 0.542632 | 1 | 0.542632 |
otland/forgottenserver | 41,688 | data/npc/lib/npcsystem/modules.lua | -- Advanced NPC System by Jiddo
if not Modules then
-- default words for greeting and ungreeting the npc. Should be a table containing all such words.
FOCUS_GREETWORDS = {"hi", "hello"}
FOCUS_FAREWELLWORDS = {"bye", "farewell"}
-- The words for requesting trade window.
SHOP_TRADEREQUEST = {"trade"}
-- The word for accepting/declining an offer. CAN ONLY CONTAIN ONE FIELD! Should be a table with a single string value.
SHOP_YESWORD = {"yes"}
SHOP_NOWORD = {"no"}
-- Pattern used to get the amount of an item a player wants to buy/sell.
PATTERN_COUNT = "%d+"
-- Constants used to separate buying from selling.
SHOPMODULE_SELL_ITEM = 1
SHOPMODULE_BUY_ITEM = 2
SHOPMODULE_BUY_ITEM_CONTAINER = 3
-- Constants used for shop mode. Notice: addBuyableItemContainer is working on all modes
SHOPMODULE_MODE_TALK = 1 -- Old system used before client version 8.2: sell/buy item name
SHOPMODULE_MODE_TRADE = 2 -- Trade window system introduced in client version 8.2
SHOPMODULE_MODE_BOTH = 3 -- Both working at one time
-- Used shop mode
SHOPMODULE_MODE = SHOPMODULE_MODE_BOTH
Modules = {
parseableModules = {}
}
StdModule = {}
-- These callback function must be called with parameters.npcHandler = npcHandler in the parameters table or they will not work correctly.
-- Notice: The members of StdModule have not yet been tested. If you find any bugs, please report them to me.
-- Usage:
-- keywordHandler:addKeyword({"offer"}, StdModule.say, {npcHandler = npcHandler, text = "I sell many powerful melee weapons."})
function StdModule.say(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if not npcHandler then
error("StdModule.say called without any npcHandler instance.")
end
local onlyFocus = not parameters.onlyFocus or parameters.onlyFocus
if not npcHandler:isFocused(cid) and onlyFocus then
return false
end
local parseInfo = {[TAG_PLAYERNAME] = Player(cid):getName()}
npcHandler:say(npcHandler:parseMessage(parameters.text or parameters.message, parseInfo), cid, parameters.publicize and true)
if parameters.reset then
npcHandler:resetNpc(cid)
elseif parameters.moveup then
npcHandler.keywordHandler:moveUp(cid, parameters.moveup)
end
return true
end
--Usage:
-- local node1 = keywordHandler:addKeyword({"promot"}, StdModule.say, {npcHandler = npcHandler, text = "I can promote you for 20000 gold coins. Do you want me to promote you?"})
-- node1:addChildKeyword({"yes"}, StdModule.promotePlayer, {npcHandler = npcHandler, cost = 20000, level = 20}, text = "Congratulations! You are now promoted.")
-- node1:addChildKeyword({"no"}, StdModule.say, {npcHandler = npcHandler, text = "Allright then. Come back when you are ready."}, reset = true)
function StdModule.promotePlayer(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if not npcHandler then
error("StdModule.promotePlayer called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
local promotion = player:getVocation():getPromotion()
if player:getStorageValue(PlayerStorageKeys.promotion) == 1 then
npcHandler:say("You are already promoted!", cid)
elseif player:getLevel() < parameters.level then
npcHandler:say("I am sorry, but I can only promote you once you have reached level " .. parameters.level .. ".", cid)
elseif not player:removeTotalMoney(parameters.cost) then
npcHandler:say("You do not have enough money!", cid)
else
npcHandler:say(parameters.text, cid)
player:setVocation(promotion)
player:setStorageValue(PlayerStorageKeys.promotion, 1)
end
else
npcHandler:say("You need a premium account in order to get promoted.", cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.learnSpell(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if not npcHandler then
error("StdModule.learnSpell called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:hasLearnedSpell(parameters.spellName) then
npcHandler:say("You already know this spell.", cid)
elseif not player:canLearnSpell(parameters.spellName) then
npcHandler:say("You cannot learn this spell.", cid)
elseif not player:removeTotalMoney(parameters.price) then
npcHandler:say("You do not have enough money, this spell costs " .. parameters.price .. " gold.", cid)
else
npcHandler:say("You have learned " .. parameters.spellName .. ".", cid)
player:learnSpell(parameters.spellName)
end
else
npcHandler:say("You need a premium account in order to buy " .. parameters.spellName .. ".", cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.bless(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if not npcHandler then
error("StdModule.bless called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) or Game.getWorldType() == WORLD_TYPE_PVP_ENFORCED then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:hasBlessing(parameters.bless) then
npcHandler:say("Gods have already blessed you with this blessing!", cid)
elseif not player:removeTotalMoney(parameters.cost) then
npcHandler:say("You don't have enough money for blessing.", cid)
else
player:addBlessing(parameters.bless)
npcHandler:say("You have been blessed by one of the five gods!", cid)
end
else
npcHandler:say("You need a premium account in order to be blessed.", cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.travel(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if not npcHandler then
error("StdModule.travel called without any npcHandler instance.")
end
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:isPzLocked() then
npcHandler:say("First get rid of those blood stains! You are not going to ruin my vehicle!", cid)
elseif parameters.level and player:getLevel() < parameters.level then
npcHandler:say("You must reach level " .. parameters.level .. " before I can let you go there.", cid)
elseif not player:removeTotalMoney(parameters.cost) then
npcHandler:say("You don't have enough money.", cid)
else
npcHandler:say(parameters.msg or "Set the sails!", cid)
npcHandler:releaseFocus(cid)
local destination = Position(parameters.destination)
local position = player:getPosition()
player:teleportTo(destination)
position:sendMagicEffect(CONST_ME_TELEPORT)
destination:sendMagicEffect(CONST_ME_TELEPORT)
end
else
npcHandler:say("I'm sorry, but you need a premium account in order to travel onboard our ships.", cid)
end
npcHandler:resetNpc(cid)
return true
end
FocusModule = {
npcHandler = nil
}
-- Creates a new instance of FocusModule without an associated NpcHandler.
function FocusModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
-- Inits the module and associates handler to it.
function FocusModule:init(handler)
self.npcHandler = handler
for i, word in pairs(FOCUS_GREETWORDS) do
local obj = {}
obj[#obj + 1] = word
obj.callback = FOCUS_GREETWORDS.callback or FocusModule.messageMatcher
handler.keywordHandler:addKeyword(obj, FocusModule.onGreet, {module = self})
end
for i, word in pairs(FOCUS_FAREWELLWORDS) do
local obj = {}
obj[#obj + 1] = word
obj.callback = FOCUS_FAREWELLWORDS.callback or FocusModule.messageMatcher
handler.keywordHandler:addKeyword(obj, FocusModule.onFarewell, {module = self})
end
return true
end
-- Greeting callback function.
function FocusModule.onGreet(cid, message, keywords, parameters)
return parameters.module.npcHandler:onGreet(cid)
end
-- UnGreeting callback function.
function FocusModule.onFarewell(cid, message, keywords, parameters)
if parameters.module.npcHandler:isFocused(cid) then
parameters.module.npcHandler:onFarewell(cid)
return true
end
return false
end
-- Custom message matching callback function for greeting messages.
function FocusModule.messageMatcher(keywords, message)
for i, word in pairs(keywords) do
if type(word) == "string" then
if string.find(message, word) and not string.find(message, "[%w+]" .. word) and not string.find(message, word .. "[%w+]") then
return true
end
end
end
return false
end
KeywordModule = {
npcHandler = nil
}
-- Add it to the parseable module list.
Modules.parseableModules["module_keywords"] = KeywordModule
function KeywordModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
function KeywordModule:init(handler)
self.npcHandler = handler
return true
end
-- Parses all known parameters.
function KeywordModule:parseParameters()
local ret = NpcSystem.getParameter("keywords")
if ret then
self:parseKeywords(ret)
end
end
function KeywordModule:parseKeywords(data)
local n = 1
for keys in string.gmatch(data, "[^;]+") do
local i = 1
local keywords = {}
for temp in string.gmatch(keys, "[^,]+") do
keywords[#keywords + 1] = temp
i = i + 1
end
if i ~= 1 then
local reply = NpcSystem.getParameter("keyword_reply" .. n)
if reply then
self:addKeyword(keywords, reply)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter '" .. "keyword_reply" .. n .. "' missing. Skipping...")
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "No keywords found for keyword set #" .. n .. ". Skipping...")
end
n = n + 1
end
end
function KeywordModule:addKeyword(keywords, reply)
self.npcHandler.keywordHandler:addKeyword(keywords, StdModule.say, {npcHandler = self.npcHandler, onlyFocus = true, text = reply, reset = true})
end
TravelModule = {
npcHandler = nil,
destinations = nil,
yesNode = nil,
noNode = nil,
}
-- Add it to the parseable module list.
Modules.parseableModules["module_travel"] = TravelModule
function TravelModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
function TravelModule:init(handler)
self.npcHandler = handler
self.yesNode = KeywordNode:new(SHOP_YESWORD, TravelModule.onConfirm, {module = self})
self.noNode = KeywordNode:new(SHOP_NOWORD, TravelModule.onDecline, {module = self})
self.destinations = {}
return true
end
-- Parses all known parameters.
function TravelModule:parseParameters()
local ret = NpcSystem.getParameter("travel_destinations")
if ret then
self:parseDestinations(ret)
self.npcHandler.keywordHandler:addKeyword({"destination"}, TravelModule.listDestinations, {module = self})
self.npcHandler.keywordHandler:addKeyword({"where"}, TravelModule.listDestinations, {module = self})
self.npcHandler.keywordHandler:addKeyword({"travel"}, TravelModule.listDestinations, {module = self})
end
end
function TravelModule:parseDestinations(data)
for destination in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local x = nil
local y = nil
local z = nil
local cost = nil
local premium = false
for temp in string.gmatch(destination, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
x = tonumber(temp)
elseif i == 3 then
y = tonumber(temp)
elseif i == 4 then
z = tonumber(temp)
elseif i == 5 then
cost = tonumber(temp)
elseif i == 6 then
premium = temp == "true"
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in travel destination parameter.", temp, destination)
end
i = i + 1
end
if name and x and y and z and cost then
self:addDestination(name, {x = x, y = y, z = z}, cost, premium)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for travel destination:", name, x, y, z, cost, premium)
end
end
end
function TravelModule:addDestination(name, position, price, premium)
self.destinations[#self.destinations + 1] = name
local parameters = {
cost = price,
destination = position,
premium = premium,
module = self
}
local keywords = {}
keywords[#keywords + 1] = name
local keywords2 = {}
keywords2[#keywords2 + 1] = "bring me to " .. name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, TravelModule.travel, parameters)
self.npcHandler.keywordHandler:addKeyword(keywords2, TravelModule.bringMeTo, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
if not npcs_loaded_travel[getNpcCid()] then
npcs_loaded_travel[getNpcCid()] = getNpcCid()
self.npcHandler.keywordHandler:addKeyword({'yes'}, TravelModule.onConfirm, {module = self})
self.npcHandler.keywordHandler:addKeyword({'no'}, TravelModule.onDecline, {module = self})
end
end
function TravelModule.travel(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
local npcHandler = module.npcHandler
shop_destination[cid] = parameters.destination
shop_cost[cid] = parameters.cost
shop_premium[cid] = parameters.premium
shop_npcuid[cid] = getNpcCid()
local cost = parameters.cost
local destination = parameters.destination
local premium = parameters.premium
module.npcHandler:say("Do you want to travel to " .. keywords[1] .. " for " .. cost .. " gold coins?", cid)
return true
end
function TravelModule.onConfirm(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
if shop_npcuid[cid] ~= Npc().uid then
return false
end
local npcHandler = module.npcHandler
local cost = shop_cost[cid]
local destination = Position(shop_destination[cid])
local player = Player(cid)
if player:isPremium() or not shop_premium[cid] then
if not player:removeTotalMoney(cost) then
npcHandler:say("You do not have enough money!", cid)
elseif player:isPzLocked() then
npcHandler:say("Get out of there with this blood.", cid)
else
npcHandler:say("It was a pleasure doing business with you.", cid)
npcHandler:releaseFocus(cid)
local position = player:getPosition()
player:teleportTo(destination)
position:sendMagicEffect(CONST_ME_TELEPORT)
destination:sendMagicEffect(CONST_ME_TELEPORT)
end
else
npcHandler:say("I can only allow premium players to travel there.", cid)
end
npcHandler:resetNpc(cid)
return true
end
-- onDecline keyword callback function. Generally called when the player sais "no" after wanting to buy an item.
function TravelModule.onDecline(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then
return false
end
local parentParameters = node:getParent():getParameters()
local parseInfo = {[TAG_PLAYERNAME] = Player(cid):getName()}
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_DECLINE), parseInfo)
module.npcHandler:say(msg, cid)
module.npcHandler:resetNpc(cid)
return true
end
function TravelModule.bringMeTo(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
local cost = parameters.cost
local destination = Position(parameters.destination)
local player = Player(cid)
if player:isPremium() or not parameters.premium then
if player:removeTotalMoney(cost) then
local position = player:getPosition()
player:teleportTo(destination)
position:sendMagicEffect(CONST_ME_TELEPORT)
destination:sendMagicEffect(CONST_ME_TELEPORT)
end
end
return true
end
function TravelModule.listDestinations(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
local msg = "I can bring you to "
--local i = 1
local maxn = #module.destinations
for i, destination in pairs(module.destinations) do
msg = msg .. destination
if i == maxn - 1 then
msg = msg .. " and "
elseif i == maxn then
msg = msg .. "."
else
msg = msg .. ", "
end
i = i + 1
end
module.npcHandler:say(msg, cid)
module.npcHandler:resetNpc(cid)
return true
end
ShopModule = {
npcHandler = nil,
yesNode = nil,
noNode = nil,
noText = "",
maxCount = ITEM_STACK_SIZE,
amount = 0
}
-- Add it to the parseable module list.
Modules.parseableModules["module_shop"] = ShopModule
-- Creates a new instance of ShopModule
function ShopModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
-- Parses all known parameters.
function ShopModule:parseParameters()
local ret = NpcSystem.getParameter("shop_buyable")
if ret then
self:parseBuyable(ret)
end
local ret = NpcSystem.getParameter("shop_sellable")
if ret then
self:parseSellable(ret)
end
local ret = NpcSystem.getParameter("shop_buyable_containers")
if ret then
self:parseBuyableContainers(ret)
end
end
-- Parse a string contaning a set of buyable items.
function ShopModule:parseBuyable(data)
local alreadyParsedIds = {}
for item in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local itemid = nil
local cost = nil
local subType = nil
local realName = nil
for temp in string.gmatch(item, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
itemid = tonumber(temp)
elseif i == 3 then
cost = tonumber(temp)
elseif i == 4 then
subType = tonumber(temp)
elseif i == 5 then
realName = temp
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in buyable items parameter.", temp, item)
end
i = i + 1
end
local it = ItemType(itemid)
if it:getId() == 0 then
-- invalid item
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Item id missing (or invalid) for parameter item:", item)
else
if alreadyParsedIds[itemid] then
if table.contains(alreadyParsedIds[itemid], subType or -1) then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Found duplicated item:", item)
else
table.insert(alreadyParsedIds[itemid], subType or -1)
end
else
alreadyParsedIds[itemid] = {subType or -1}
end
end
if not subType and it:getCharges() ~= 0 then
subType = it:getCharges()
end
if SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE then
if itemid and cost then
if not subType and it:isFluidContainer() then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item)
else
self:addBuyableItem(nil, itemid, cost, subType, realName)
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", itemid, cost)
end
else
if name and itemid and cost then
if not subType and it:isFluidContainer() then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item)
else
local names = {}
names[#names + 1] = name
self:addBuyableItem(names, itemid, cost, subType, realName)
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, itemid, cost)
end
end
end
end
-- Parse a string contaning a set of sellable items.
function ShopModule:parseSellable(data)
local alreadyParsedIds = {}
for item in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local itemid = nil
local cost = nil
local realName = nil
local subType = nil
for temp in string.gmatch(item, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
itemid = tonumber(temp)
elseif i == 3 then
cost = tonumber(temp)
elseif i == 4 then
realName = temp
elseif i == 5 then
subType = tonumber(temp)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in sellable items parameter.", temp, item)
end
i = i + 1
end
local it = ItemType(itemid)
if it:getId() == 0 then
-- invalid item
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Item id missing (or invalid) for parameter item:", item)
else
if alreadyParsedIds[itemid] then
if table.contains(alreadyParsedIds[itemid], subType or -1) then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Found duplicated item:", item)
else
table.insert(alreadyParsedIds[itemid], subType or -1)
end
else
alreadyParsedIds[itemid] = {subType or -1}
end
end
if SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE then
if itemid and cost then
self:addSellableItem(nil, itemid, cost, realName, subType)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", itemid, cost)
end
else
if name and itemid and cost then
local names = {}
names[#names + 1] = name
self:addSellableItem(names, itemid, cost, realName, subType)
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, itemid, cost)
end
end
end
end
-- Parse a string contaning a set of buyable items.
function ShopModule:parseBuyableContainers(data)
for item in string.gmatch(data, "[^;]+") do
local i = 1
local name = nil
local container = nil
local itemid = nil
local cost = nil
local subType = nil
local realName = nil
for temp in string.gmatch(item, "[^,]+") do
if i == 1 then
name = temp
elseif i == 2 then
itemid = tonumber(temp)
elseif i == 3 then
itemid = tonumber(temp)
elseif i == 4 then
cost = tonumber(temp)
elseif i == 5 then
subType = tonumber(temp)
elseif i == 6 then
realName = temp
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in buyable items parameter.", temp, item)
end
i = i + 1
end
if name and container and itemid and cost then
if not subType and ItemType(itemid):isFluidContainer() then
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item)
else
local names = {}
names[#names + 1] = name
self:addBuyableItemContainer(names, container, itemid, cost, subType, realName)
end
else
print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, container, itemid, cost)
end
end
end
-- Initializes the module and associates handler to it.
function ShopModule:init(handler)
self.npcHandler = handler
self.yesNode = KeywordNode:new(SHOP_YESWORD, ShopModule.onConfirm, {module = self})
self.noNode = KeywordNode:new(SHOP_NOWORD, ShopModule.onDecline, {module = self})
self.noText = handler:getMessage(MESSAGE_DECLINE)
if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then
for i, word in pairs(SHOP_TRADEREQUEST) do
local obj = {}
obj[#obj + 1] = word
obj.callback = SHOP_TRADEREQUEST.callback or ShopModule.messageMatcher
handler.keywordHandler:addKeyword(obj, ShopModule.requestTrade, {module = self})
end
end
return true
end
-- Custom message matching callback function for requesting trade messages.
function ShopModule.messageMatcher(keywords, message)
for i, word in pairs(keywords) do
if type(word) == "string" then
if string.find(message, word) and not string.find(message, "[%w+]" .. word) and not string.find(message, word .. "[%w+]") then
return true
end
end
end
return false
end
-- Resets the module-specific variables.
function ShopModule:reset()
self.amount = 0
end
-- Function used to match a number value from a string.
function ShopModule:getCount(message)
local ret = 1
local b, e = string.find(message, PATTERN_COUNT)
if b and e then
ret = tonumber(string.sub(message, b, e))
end
if ret <= 0 then
ret = 1
elseif ret > self.maxCount then
ret = self.maxCount
end
return ret
end
-- Adds a new buyable item.
-- names = A table containing one or more strings of alternative names to this item. Used only for old buy/sell system.
-- itemid = The itemid of the buyable item
-- cost = The price of one single item
-- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 1.
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (ItemType(itemId):getName() will be used)
function ShopModule:addBuyableItem(names, itemid, cost, itemSubType, realName)
if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then
if not itemSubType then
itemSubType = 1
end
local it = ItemType(itemid)
if it:getId() ~= 0 then
local shopItem = self:getShopItem(itemid, itemSubType)
if not shopItem then
self.npcHandler.shopItems[#self.npcHandler.shopItems + 1] = {id = itemid, buy = cost, sell = 0, subType = itemSubType, name = realName or it:getName()}
else
if cost < shopItem.sell then
print("[Warning : " .. Npc():getName() .. "] NpcSystem: Buy price lower than sell price: (" .. shopItem.name .. ")")
end
shopItem.buy = cost
end
end
end
if names and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE then
for i, name in pairs(names) do
local parameters = {
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_BUY_ITEM,
module = self,
realName = realName or ItemType(itemid):getName(),
subType = itemSubType or 1
}
keywords = {}
keywords[#keywords + 1] = "buy"
keywords[#keywords + 1] = name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
if not npcs_loaded_shop[getNpcCid()] then
npcs_loaded_shop[getNpcCid()] = getNpcCid()
self.npcHandler.keywordHandler:addKeyword({'yes'}, ShopModule.onConfirm, {module = self})
self.npcHandler.keywordHandler:addKeyword({'no'}, ShopModule.onDecline, {module = self})
end
end
function ShopModule:getShopItem(itemId, itemSubType)
if ItemType(itemId):isFluidContainer() then
for i = 1, #self.npcHandler.shopItems do
local shopItem = self.npcHandler.shopItems[i]
if shopItem.id == itemId and shopItem.subType == itemSubType then
return shopItem
end
end
else
for i = 1, #self.npcHandler.shopItems do
local shopItem = self.npcHandler.shopItems[i]
if shopItem.id == itemId then
return shopItem
end
end
end
return nil
end
-- Adds a new buyable container of items.
-- names = A table containing one or more strings of alternative names to this item.
-- container = Backpack, bag or any other itemid of container where bought items will be stored
-- itemid = The itemid of the buyable item
-- cost = The price of one single item
-- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 1.
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (ItemType(itemId):getName() will be used)
function ShopModule:addBuyableItemContainer(names, container, itemid, cost, subType, realName)
if names then
for i, name in pairs(names) do
local parameters = {
container = container,
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_BUY_ITEM_CONTAINER,
module = self,
realName = realName or ItemType(itemid):getName(),
subType = subType or 1
}
keywords = {}
keywords[#keywords + 1] = "buy"
keywords[#keywords + 1] = name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
end
-- Adds a new sellable item.
-- names = A table containing one or more strings of alternative names to this item. Used only by old buy/sell system.
-- itemid = The itemid of the sellable item
-- cost = The price of one single item
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (ItemType(itemId):getName() will be used)
function ShopModule:addSellableItem(names, itemid, cost, realName, itemSubType)
if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then
if not itemSubType then
itemSubType = 0
end
local it = ItemType(itemid)
if it:getId() ~= 0 then
local shopItem = self:getShopItem(itemid, itemSubType)
if not shopItem then
self.npcHandler.shopItems[#self.npcHandler.shopItems + 1] = {id = itemid, buy = 0, sell = cost, subType = itemSubType, name = realName or it:getName()}
else
if shopItem.buy > 0 and cost > shopItem.buy then
print("[Warning : " .. Npc():getName() .. "] NpcSystem: Sell price higher than buy price: (" .. shopItem.name .. ")")
end
shopItem.sell = cost
end
end
end
if names and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE then
for i, name in pairs(names) do
local parameters = {
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_SELL_ITEM,
module = self,
realName = realName or ItemType(itemid):getName()
}
keywords = {}
keywords[#keywords + 1] = "sell"
keywords[#keywords + 1] = name
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
end
-- onModuleReset callback function. Calls ShopModule:reset()
function ShopModule:callbackOnModuleReset()
self:reset()
return true
end
-- Callback onBuy() function. If you wish, you can change certain Npc to use your onBuy().
function ShopModule:callbackOnBuy(cid, itemid, subType, amount, ignoreCap, inBackpacks)
local shopItem = self:getShopItem(itemid, subType)
if not shopItem then
error("[ShopModule.onBuy] shopItem == nil")
return false
end
if shopItem.buy == 0 then
error("[ShopModule.onSell] attempt to buy a non-buyable item")
return false
end
local totalCost = amount * shopItem.buy
if inBackpacks then
totalCost = ItemType(itemid):isStackable() and totalCost + 20 or totalCost + (math.max(1, math.floor(amount / ItemType(ITEM_SHOPPING_BAG):getCapacity())) * 20)
end
local player = Player(cid)
local parseInfo = {
[TAG_PLAYERNAME] = player:getName(),
[TAG_ITEMCOUNT] = amount,
[TAG_TOTALCOST] = totalCost,
[TAG_ITEMNAME] = shopItem.name
}
if player:getTotalMoney() < totalCost then
local msg = self.npcHandler:getMessage(MESSAGE_NEEDMONEY)
msg = self.npcHandler:parseMessage(msg, parseInfo)
player:sendCancelMessage(msg)
return false
end
local subType = shopItem.subType or 1
local a, b = doNpcSellItem(cid, itemid, amount, subType, ignoreCap, inBackpacks, ITEM_SHOPPING_BAG)
if a < amount then
local msgId = MESSAGE_NEEDMORESPACE
if a == 0 then
msgId = MESSAGE_NEEDSPACE
end
local msg = self.npcHandler:getMessage(msgId)
parseInfo[TAG_ITEMCOUNT] = a
msg = self.npcHandler:parseMessage(msg, parseInfo)
player:sendCancelMessage(msg)
self.npcHandler.talkStart[cid] = os.time()
if a > 0 then
if not player:removeTotalMoney((a * shopItem.buy) + (b * 20)) then
return false
end
return true
end
return false
else
local msg = self.npcHandler:getMessage(MESSAGE_BOUGHT)
msg = self.npcHandler:parseMessage(msg, parseInfo)
player:sendTextMessage(MESSAGE_INFO_DESCR, msg)
if not player:removeTotalMoney(totalCost) then
return false
end
self.npcHandler.talkStart[cid] = os.time()
return true
end
end
-- Callback onSell() function. If you wish, you can change certain Npc to use your onSell().
function ShopModule:callbackOnSell(cid, itemid, subType, amount, ignoreEquipped, _)
local shopItem = self:getShopItem(itemid, subType)
if not shopItem then
error("[ShopModule.onSell] items[itemid] == nil")
return false
end
if shopItem.sell == 0 then
error("[ShopModule.onSell] attempt to sell a non-sellable item")
return false
end
local player = Player(cid)
local parseInfo = {
[TAG_PLAYERNAME] = player:getName(),
[TAG_ITEMCOUNT] = amount,
[TAG_TOTALCOST] = amount * shopItem.sell,
[TAG_ITEMNAME] = shopItem.name
}
if not ItemType(itemid):isFluidContainer() then
subType = -1
end
if player:removeItem(itemid, amount, subType, ignoreEquipped) then
local msg = self.npcHandler:getMessage(MESSAGE_SOLD)
msg = self.npcHandler:parseMessage(msg, parseInfo)
player:sendTextMessage(MESSAGE_INFO_DESCR, msg)
player:addMoney(amount * shopItem.sell)
self.npcHandler.talkStart[cid] = os.time()
return true
end
local msg = self.npcHandler:getMessage(MESSAGE_NEEDITEM)
msg = self.npcHandler:parseMessage(msg, parseInfo)
player:sendCancelMessage(msg)
self.npcHandler.talkStart[cid] = os.time()
return false
end
-- Callback for requesting a trade window with the NPC.
function ShopModule.requestTrade(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
if not module.npcHandler:onTradeRequest(cid) then
return false
end
local itemWindow = {}
for i = 1, #module.npcHandler.shopItems do
itemWindow[#itemWindow + 1] = module.npcHandler.shopItems[i]
end
if not itemWindow[1] then
local parseInfo = {[TAG_PLAYERNAME] = Player(cid):getName()}
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_NOSHOP), parseInfo)
module.npcHandler:say(msg, cid)
return true
end
local parseInfo = {[TAG_PLAYERNAME] = Player(cid):getName()}
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_SENDTRADE), parseInfo)
openShopWindow(cid, itemWindow,
function(cid, itemid, subType, amount, ignoreCap, inBackpacks) module.npcHandler:onBuy(cid, itemid, subType, amount, ignoreCap, inBackpacks) end,
function(cid, itemid, subType, amount, ignoreCap, inBackpacks) module.npcHandler:onSell(cid, itemid, subType, amount, ignoreCap, inBackpacks) end)
module.npcHandler:say(msg, cid)
return true
end
-- onConfirm keyword callback function. Sells/buys the actual item.
function ShopModule.onConfirm(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then
return false
end
shop_npcuid[cid] = 0
local parentParameters = node:getParent():getParameters()
local player = Player(cid)
local parseInfo = {
[TAG_PLAYERNAME] = player:getName(),
[TAG_ITEMCOUNT] = shop_amount[cid],
[TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid],
[TAG_ITEMNAME] = shop_rlname[cid]
}
if shop_eventtype[cid] == SHOPMODULE_SELL_ITEM then
local ret = doPlayerSellItem(cid, shop_itemid[cid], shop_amount[cid], shop_cost[cid] * shop_amount[cid])
if ret then
local msg = module.npcHandler:getMessage(MESSAGE_ONSELL)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
else
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGITEM)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM then
local cost = shop_cost[cid] * shop_amount[cid]
if player:getTotalMoney() < cost then
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
return false
end
local a, b = doNpcSellItem(cid, shop_itemid[cid], shop_amount[cid], shop_subtype[cid], false, false, ITEM_SHOPPING_BAG)
if a < shop_amount[cid] then
local msgId = MESSAGE_NEEDMORESPACE
if a == 0 then
msgId = MESSAGE_NEEDSPACE
end
local msg = module.npcHandler:getMessage(msgId)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
if a > 0 then
if not player:removeTotalMoney(a * shop_cost[cid]) then
return false
end
if shop_itemid[cid] == ITEM_PARCEL then
doNpcSellItem(cid, ITEM_LABEL, shop_amount[cid], shop_subtype[cid], true, false, ITEM_SHOPPING_BAG)
end
return true
end
return false
else
local msg = module.npcHandler:getMessage(MESSAGE_ONBUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
if not player:removeTotalMoney(cost) then
return false
end
if shop_itemid[cid] == ITEM_PARCEL then
doNpcSellItem(cid, ITEM_LABEL, shop_amount[cid], shop_subtype[cid], true, false, ITEM_SHOPPING_BAG)
end
return true
end
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM_CONTAINER then
local ret = doPlayerBuyItemContainer(cid, shop_container[cid], shop_itemid[cid], shop_amount[cid], shop_cost[cid] * shop_amount[cid], shop_subtype[cid])
if ret then
local msg = module.npcHandler:getMessage(MESSAGE_ONBUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
else
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
end
module.npcHandler:resetNpc(cid)
return true
end
-- onDecline keyword callback function. Generally called when the player sais "no" after wanting to buy an item.
function ShopModule.onDecline(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then
return false
end
shop_npcuid[cid] = 0
local parentParameters = node:getParent():getParameters()
local parseInfo = {
[TAG_PLAYERNAME] = Player(cid):getName(),
[TAG_ITEMCOUNT] = shop_amount[cid],
[TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid],
[TAG_ITEMNAME] = shop_rlname[cid]
}
local msg = module.npcHandler:parseMessage(module.noText, parseInfo)
module.npcHandler:say(msg, cid)
module.npcHandler:resetNpc(cid)
return true
end
-- tradeItem callback function. Makes the npc say the message defined by MESSAGE_BUY or MESSAGE_SELL
function ShopModule.tradeItem(cid, message, keywords, parameters, node)
local module = parameters.module
if not module.npcHandler:isFocused(cid) then
return false
end
if not module.npcHandler:onTradeRequest(cid) then
return true
end
local count = module:getCount(message)
module.amount = count
shop_amount[cid] = module.amount
shop_cost[cid] = parameters.cost
shop_rlname[cid] = parameters.realName
shop_itemid[cid] = parameters.itemid
shop_container[cid] = parameters.container
shop_npcuid[cid] = getNpcCid()
shop_eventtype[cid] = parameters.eventType
shop_subtype[cid] = parameters.subType
local parseInfo = {
[TAG_PLAYERNAME] = Player(cid):getName(),
[TAG_ITEMCOUNT] = shop_amount[cid],
[TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid],
[TAG_ITEMNAME] = shop_rlname[cid]
}
if shop_eventtype[cid] == SHOPMODULE_SELL_ITEM then
local msg = module.npcHandler:getMessage(MESSAGE_SELL)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM then
local msg = module.npcHandler:getMessage(MESSAGE_BUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM_CONTAINER then
local msg = module.npcHandler:getMessage(MESSAGE_BUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
return true
end
VoiceModule = {
voices = nil,
voiceCount = 0,
lastVoice = 0,
timeout = nil,
chance = nil
}
-- VoiceModule: makes the NPC say/yell random lines from a table, with delay, chance and yell optional
function VoiceModule:new(voices, timeout, chance)
local obj = {}
setmetatable(obj, self)
self.__index = self
obj.voices = voices
for i = 1, #obj.voices do
local voice = obj.voices[i]
if voice.yell then
voice.yell = nil
voice.talktype = TALKTYPE_YELL
else
voice.talktype = TALKTYPE_SAY
end
end
obj.voiceCount = #voices
obj.timeout = timeout or 10
obj.chance = chance or 10
return obj
end
function VoiceModule:init(handler)
return true
end
function VoiceModule:callbackOnThink()
if self.lastVoice < os.time() then
self.lastVoice = os.time() + self.timeout
if math.random(100) <= self.chance then
local voice = self.voices[math.random(self.voiceCount)]
Npc():say(voice.text, voice.talktype)
end
end
return true
end
end
| 0 | 0.857569 | 1 | 0.857569 | game-dev | MEDIA | 0.908698 | game-dev | 0.911414 | 1 | 0.911414 |
RafaelDeJongh/cap | 10,291 | lua/entities/mini_drone.lua | ENT.Type = "anim";
ENT.Base = "drone";
ENT.PrintName = "Mini Drone";
ENT.Author = "RononDex";
ENT.Spawnable = false;
ENT.AdminSpawnable = false;
if SERVER then
if (StarGate==nil or StarGate.CheckModule==nil or not StarGate.CheckModule("entweapon")) then return end
AddCSLuaFile();
ENT.CAP_NotSave = true;
ENT.Untouchable = true;
ENT.IgnoreTouch = true;
function ENT:Initialize()
self.Entity:SetModel("models/miriam/minidrone/minidrone.mdl");
self.Entity:SetMaterial("materials/miriam/minidrone/yellow_on.vmt");
self.Entity:PhysicsInit(SOLID_VPHYSICS);
self.Entity:SetMoveType(MOVETYPE_VPHYSICS);
self.Entity:SetCollisionGroup(COLLISION_GROUP_PROJECTILE);
self.Entity:DrawShadow(false);
self.LastPosition = self.Entity:GetPos()
self.TrackTime = CurTime()+50;
self.Fuel = StarGate.CFG:Get("mini_drone","distance",10000);
self.CurrentVelocity = 500;
self.MaxVelocity = StarGate.CFG:Get("mini_drone","maxspeed",6000)/6;
self.Created = CurTime();
self.Randomness = math.random(6,14)/10;
self.TrackStart = math.random(5,15)/10;
self.AntiRandomness = 1-self.Randomness;
self.Radius = StarGate.CFG:Get("drone","radius",200)/4;
self.Damage = StarGate.CFG:Get("drone","damage",150)/2;
self.CanTrack = false;
self.Trail = util.SpriteTrail(self.Entity,0,Color(255,230,100,255),true,8,2,0.05,1/12,"sprites/smoke.vmt");
local phys = self.Entity:GetPhysicsObject();
if(phys:IsValid()) then
phys:Wake()
phys:SetMass(20);
phys:EnableGravity(false);
phys:EnableDrag(false);
phys:EnableCollisions(true);
end
end
--################# Removes the trail @aVoN
function ENT:RemoveTrail(unparent)
if(self.Trail and self.Trail:IsValid()) then
self.Entity:SetNetworkedInt("turn_off",CurTime());
-- Only do this when we are in SinglePlayer. In MultiPlayer i have seen the trails gowing into the sky near map-origin which was really ugly
if(unparent) then
if(game.SinglePlayer()) then
self.Trail:SetParent();
self.Trail:SetPos(self.Entity:GetPos());
end
self.Trail:Fire("kill","",1); -- Kill trail
else
self.Trail:Remove();
end
end
end
--################# Calculate Physics for the drone @Zup & aVoN
function ENT:PhysicsUpdate(phys,deltatime)
local time = CurTime();
if((self.LastPhysicsUpdate or 0) + 0.07 >= time) then return end;
self.LastPhysicsUpdate = time;
if(self.Fuel > 0) then
local pos = self.Entity:GetPos();
if(self.CurrentVelocity < self.MaxVelocity) then
self.CurrentVelocity = math.Clamp(self.MaxVelocity*(CurTime()-self.Created)/self.TrackStart,self.CurrentVelocity,self.MaxVelocity);
self.Direction = self.Entity:GetForward()*self.CurrentVelocity;
-- Allow tracking only after the drone reached a critical velocity
if(not self.CanTrack and self.Created+self.TrackStart*0.7 <= CurTime()) then
self.CanTrack = true;
end
end
self.Fuel = self.Fuel-(pos-self.LastPosition):Length(); -- Take fuel accodring to the flown way
if(self.CanTrack and time < self.TrackTime) then
-- This makes it not to look so sloppy in curves
local dir = self:GetVelocity();
if IsValid(self.Ply) then
if self.Ply.Target then
dir = self.Ply.Target-pos;
end
end
local len = dir:Length();
dir:Normalize();
if(len > 250) then
self.Direction = (dir*self.Randomness+self.Entity:GetVelocity():GetNormalized()*self.AntiRandomness)*self.CurrentVelocity;
else
-- We are really near the target. Do not fly around like an electron - Hit it!
self.Direction = dir*self.CurrentVelocity;
if(len < 100) then -- Nearly at the prop's position. Instant explode (Failsafe, or when there is no prop, the drones would collide with each other and lag servers!)
self:StartTouch(game.GetWorld());
end
end
local t={
secondstoarrive = 1,
pos = pos+self.Direction,
maxangular = 50000,
maxangulardamp = 100,
maxspeed = 1000000,
maxspeeddamp = 10000,
dampfactor = 0.2,
teleportdistance = 7000,
angle = dir:Angle(),
deltatime = deltatime,
}
phys:ComputeShadowControl(t);
elseif(self.CurrentVelocity ~= self.MaxVelocity) then -- We havent reached full velocity yet - So constanly add velocity
phys:SetVelocity(self.Direction);
end
self.LastPosition = pos;
else
-- Turn the missile off
local e = self.Entity;
timer.Simple(2,
function()
if(e and e:IsValid()) then
e:SetMaterial("Zup/drone/drone.vmt");
end
end
);
self:RemoveTrail();
-- Remove it's count from the launcher
self:OnRemove();
-- Make it falldown
phys:EnableGravity(true);
phys:EnableDrag(true);
self.Entity:SetCollisionGroup(COLLISION_GROUP_DEBRIS); -- Only collide with world but not players
-- And when the drone does not collide (aka "Lost in space"), we will kill it in 30 seconds anyway
timer.Create("DroneDestroy"..self.Entity:EntIndex(),30,1,
function()
if(e and e:IsValid()) then
e:Remove();
end
end
);
-- Dummy to save resources
self.PhysicsUpdate = function() end;
end
end
--################# What shall happen when we die? @aVoN
function ENT:OnRemove()
local str = "DroneDestroy"..self.Entity:EntIndex();
if(timer.Exists(str)) then
timer.Destroy(str);
end
if(self.Parent and self.Parent:IsValid()) then
if(self.Parent.Drones[self.Entity]) then -- Only decrease, if we haven't already
self.Parent.DroneCount = self.Parent.DroneCount-1; -- Decrease count
self.Parent.Drones[self.Entity] = nil;
self.Parent:ShowOutput();
end
end
end
--################# The blast @aVoN
function ENT:Blast(pos, tr)
-- effect some why removed in new gmod, replace with old from normal drones
/*local fx = EffectData()
fx:SetOrigin( pos );
fx:SetNormal( tr.HitNormal );
util.Effect( "AR2Impact", fx ); */
local fx = EffectData()
fx:SetOrigin( pos );
fx:SetNormal( tr.HitNormal );
util.Effect("Explosion",fx,true,true);
util.Effect("HelicopterMegaBomb",fx,true,true);
local fx = EffectData();
fx:SetScale(1);
fx:SetOrigin(pos);
fx:SetEntity(self.Entity);
fx:SetAngles(Angle(255,200,120));
fx:SetRadius(32);
util.Effect("energy_muzzle",fx,true);
local attacker,owner = StarGate.GetAttackerAndOwner(self.Entity);
StarGate.BlastDamage(attacker,owner,pos,self.Radius,self.Damage);
end
--################# This is a remove function to avoid crashing when hitting the world @aVoN
function ENT:StartRemoving(delay_deletion)
if(delay_deletion) then
self:RemoveTrail();
-- You ask, why a timer? This avoids ugly "Changing collision rules within a callback is likely to cause crashes!" spam in console. Don't ask me why this happens.
-- It also stops crashing
self:SetNoDraw(true); -- Stop drawing us!
local e = self.Entity;
-- Stop collision with us
timer.Simple(0.1,
function()
if(e and e:IsValid()) then
e:SetCollisionGroup(COLLISION_GROUP_DEBRIS);
end
end
);
-- Kill us
timer.Simple(2,
function()
if(e and e:IsValid()) then
e:Remove(); -- It's time kick ass and chew bubble gum. And your all out of gum
end
end
);
else
-- General deletion
self:RemoveTrail(true);
self.Entity:Remove();
end
end
--################# What shall happen, when we collide? @Zup & aVoN
function ENT:StartTouch(e,delay_deletion)
if(e and e.IgnoreTouch) then return end; -- Gloabal for anyone, who want's to make his scripts "drone-passable"
if(e == self.Parent) then return end;
if(e and e:IsValid()) then
local class = e:GetClass();
if(class == "drone" or class == "mini_drone") then return end;
if(class == "ivisgen_collision") then return end; -- Catdaemons Cloaking Field - Never collide with this
local phys = e:GetPhysicsObject();
if(not (phys and phys:IsValid())) then return end; -- Nothing "solid" or physical to collide
end
local vel = self.Entity:GetVelocity();
if(StarGate.CanTouch({BaseVelocity=self.CannonVeloctiy,Velocity=self.Entity:GetVelocity(),Time=self.Created})) then
local pos = self.Entity:GetPos();
vel = vel:GetNormalized()*512;
-- Like the staffweapon blasts, I don't want the drones to explode when they hit the sky
local t = util.TraceLine({start=pos-vel,endpos=pos+vel,filter={self.Entity,self.Trail}});
-- Define dummys: DO NOT CALL THE TOUCH OR THE PHYSICS AGAIN!
self.PhysicsUpdate = function() end;
self.StartTouch = function() end;
if(t.HitSky) then self:StartRemoving(delay_deletion) return end;
-- Need to replace this with a better one!
if(e and self.Fuel > 0) then
if(not e.nocollide) then self:Blast(pos, t) end; -- Do not explode on shields!
self:StartRemoving(delay_deletion);
else
self.Entity:SetNWBool("fade_out",true);
-- Kill after some time
local e = self.Entity;
timer.Simple(5,
function()
if(e and e:IsValid()) then
self.Entity:Remove();
end
end
);
end
end
end
function ENT:PhysicsCollide(data)
-- Only and really only do this when he collides with the world
if(data and data.HitEntity and data.HitEntity:IsWorld()) then
self:StartTouch(data.HitEntity,true);
end
end
end
if CLIENT then
if (StarGate==nil or StarGate.MaterialFromVMT==nil) then return end
ENT.Glow = StarGate.MaterialFromVMT(
"DroneSprite",
[["UnLitGeneric"
{
"$basetexture" "sprites/light_glow01"
"$nocull" 1
"$additive" 1
"$vertexalpha" 1
"$vertexcolor" 1
}]]
);
if (SGLanguage!=nil and SGLanguage.GetMessage!=nil) then
language.Add("mini_drone",SGLanguage.GetMessage("mdrone_kill"));
end
function ENT:Initialize()
self.Created = CurTime();
end
// Draws model
--################# Draw @aVoN
function ENT:Draw()
local pos = self.Entity:GetPos();
self.Size = self.Size or 8;
self.Alpha = self.Alpha or 255;
local time = self.Entity:GetNetworkedInt("turn_off",false);
if(time) then
-- Drone turns off (But only, when the Trail has been removed before)
if(time+1 < CurTime()) then
self.Size = math.Clamp((2-CurTime()+(time+1))*8,0,8);
end
end
if(StarGate.VisualsWeapons("cl_drone_glow")) then
-- The sprite on the drone
render.SetMaterial(self.Glow);
render.DrawSprite(
self.Entity:GetPos(),
self.Size,self.Size,
Color(255,210,100,255)
);
end
-- Drone has to fade out
if(self.Entity:GetNWBool("fade_out")) then
self.Alpha = math.Clamp(self.Alpha-FrameTime()*80,0,255);
self.Entity:SetColor(Color(255,255,255,self.Alpha));
end
self.Entity:DrawModel();
end
end | 0 | 0.923221 | 1 | 0.923221 | game-dev | MEDIA | 0.99087 | game-dev | 0.960413 | 1 | 0.960413 |
egoboo/egoboo | 1,344 | egolib/library/src/egolib/game/GUI/InputListener.cpp | #include "egolib/game/GUI/InputListener.hpp"
namespace Ego {
namespace GUI {
InputListener::~InputListener() {
//dtor
}
bool InputListener::notifyMousePointerMoved(const Events::MousePointerMovedEvent& e) {
// Default: Event is not handled.
return false;
}
bool InputListener::notifyMouseWheelTurned(const Events::MouseWheelTurnedEvent& e) {
// Default: Event is not handled.
return false;
}
bool InputListener::notifyMouseButtonPressed(const Events::MouseButtonPressedEvent& e) {
// Default: Event is not handled.
return false;
}
bool InputListener::notifyMouseButtonReleased(const Events::MouseButtonReleasedEvent& e) {
// Default: Event is not handled.
return false;
}
bool InputListener::notifyMouseButtonClicked(const Events::MouseButtonClickedEvent& e) {
// Default: Event is not handled.
return false;
}
bool InputListener::notifyKeyboardKeyPressed(const Events::KeyboardKeyPressedEvent& e) {
// Default: Event is not handled.
return false;
}
bool InputListener::notifyKeyboardKeyReleased(const Events::KeyboardKeyReleasedEvent& e) {
// Default: Event is not handled.
return false;
}
bool InputListener::notifyKeyboardKeyTyped(const Events::KeyboardKeyTypedEvent& e) {
// Default: Event is not handled.
return false;
}
} // namespace GUI
} // namespace Ego
| 0 | 0.872905 | 1 | 0.872905 | game-dev | MEDIA | 0.459976 | game-dev,desktop-app | 0.735059 | 1 | 0.735059 |
MCreator-Examples/Tale-of-Biomes | 1,907 | src/main/java/net/nwtg/taleofbiomes/procedures/BasicToolTableRecipeHelperRecipeNameScriptProcedure.java | package net.nwtg.taleofbiomes.procedures;
import net.nwtg.taleofbiomes.network.TaleOfBiomesModVariables;
import net.minecraft.world.entity.Entity;
public class BasicToolTableRecipeHelperRecipeNameScriptProcedure {
public static String execute(Entity entity) {
if (entity == null)
return "";
if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 0) {
return "Tool Grip";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 1) {
return "Axe Head";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 2) {
return "Hoe Head";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 3) {
return "Pickaxe Head";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 4) {
return "Shovel Head";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 5) {
return "Sickle Head";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 6) {
return "Sword Head";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 7) {
return "Axe Tool";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 8) {
return "Hoe Tool";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 9) {
return "Pickaxe Tool";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 10) {
return "Shovel Tool";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 11) {
return "Sickle Tool";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 12) {
return "Sword Tool";
} else if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).recipePage == 13) {
return "Cup";
}
return "";
}
}
| 0 | 0.715413 | 1 | 0.715413 | game-dev | MEDIA | 0.934648 | game-dev | 0.613759 | 1 | 0.613759 |
openclonk/openclonk | 8,102 | planet/Experimental.ocf/CableLorrys.ocs/CableCars.ocd/Vehicles.ocd/Lorry.ocd/Script.c | /**
Lorry
Transportation and storage for up to 50 objects.
@authors Maikel
*/
#include Library_ElevatorControl
local drive_anim;
local empty_anim;
/*-- Engine Callbacks --*/
public func Construction()
{
SetProperty("MeshTransformation", Trans_Rotate(13, 0, 1, 0));
}
public func Initialize()
{
drive_anim = PlayAnimation("Drive", 1, Anim_X(0, 0, GetAnimationLength("Drive"), 30), Anim_Const(1000));
empty_anim = PlayAnimation("Empty", 2, Anim_Const(0), Anim_Const(0));
}
public func Hit3()
{
Sound("Hits::Materials::Metal::DullMetalHit?");
}
public func RejectCollect(id object_id, object obj)
{
// Collection maybe blocked if this object was just dumped.
if (!obj->Contained() && GetEffect("BlockCollectionByLorry", obj))
return true;
// Objects can still be collected.
if (ContentsCount() < MaxContentsCount)
{
Sound("Objects::Clonk");
return false;
}
// The object cannot be collected, notify carrier?
if (obj->Contained())
Message("$TxtLorryisfull$");
else
{
// If not carried, objects slide over the lorry.
if (Abs(obj->GetXDir()) > 5)
{
obj->SetYDir(-2);
obj->SetRDir(0);
Sound("Hits::SoftHit*");
}
}
// Reject collection.
return true;
}
// Automatic unloading in buildings.
public func Entrance(object container)
{
// Only in buildings
if (container->GetCategory() & (C4D_StaticBack | C4D_Structure))
// Not if the building prohibits this action.
if (!container->~NoLorryEjection(this))
// Empty lorry.
container->GrabContents(this);
}
public func ContactLeft()
{
if (Stuck() && !Random(5))
SetRDir(RandomX(-7, +7));
}
public func ContactRight()
{
if (Stuck() && !Random(5))
SetRDir(RandomX(-7, +7));
}
public func Damage(int change, int cause, int by_player)
{
// Only explode the lorry on blast damage.
if (cause != FX_Call_DmgBlast)
return _inherited(change, cause, by_player, ...);
// Explode the lorry when it has taken to much damage.
if (GetDamage() > 100)
{
// Only exit objects and parts if this lorry is not contained.
if (!Contained())
{
// First eject the contents in different directions.
for (var obj in FindObjects(Find_Container(this)))
{
var speed = RandomX(3, 5);
var angle = Random(360);
var dx = Cos(angle, speed);
var dy = Sin(angle, speed);
obj->Exit(RandomX(-4, 4), RandomX(-4, 4), Random(360), dx, dy, RandomX(-20, 20));
obj->SetController(by_player);
}
// Toss around some fragments with particles attached.
for (var i = 0; i < 6; i++)
{
var fragment = CreateObject(LorryFragment, RandomX(-4, 4), RandomX(-4, 4), GetOwner());
var speed = RandomX(40, 60);
var angle = Random(360);
var dx = Cos(angle, speed);
var dy = Sin(angle, speed);
fragment->SetXDir(dx, 10);
fragment->SetYDir(dy, 10);
fragment->SetR(360);
fragment->SetRDir(RandomX(-20, 20));
// Set the controller of the fragments to the one causing the blast for kill tracing.
fragment->SetController(by_player);
// Incinerate the fragments.
fragment->Incinerate(100, by_player);
}
}
// Remove the lorry itself, eject possible contents as they might have entered again.
// Or let the engine eject the contents if it is inside a container.
return RemoveObject(true);
}
return _inherited(change, cause, by_player, ...);
}
/*-- Callbacks --*/
public func IsLorry() { return true; }
public func IsVehicle() { return true; }
public func IsContainer() { return true; }
// Called upon arrival at a cable station
public func DropContents(proplist station)
{
// Drop everything in a few seconds
SetAnimationWeight(empty_anim, Anim_Const(1000));
SetAnimationPosition(empty_anim, Anim_Linear(0, 0, GetAnimationLength("Empty"), 35, ANIM_Hold));
ScheduleCall(this, "Empty", 35);
}
public func Empty()
{
// Exit everything at once (as opposed to manual dumping below)
while (Contents())
{
var content = Contents();
AddEffect("BlockCollectionByLorry", content, 100, 16, this);
content->Exit(RandomX(-5, 5), RandomX(-2, 2), Random(360));
}
SetAnimationWeight(empty_anim, Anim_Linear(1000, 1000, 0, 35, ANIM_Hold));
SetAnimationPosition(empty_anim, Anim_Linear(GetAnimationLength("Empty"), GetAnimationLength("Empty"), 0, 35, ANIM_Hold));
}
/*-- Usage --*/
public func HoldingEnabled() { return true; }
public func ControlUseStart(object clonk, int x, int y)
{
var direction = DIR_Left;
if (x > 0)
direction = DIR_Right;
if (!GetEffect("DumpContents", this))
AddEffect("DumpContents", this, 100, 1, this, nil, direction);
return true;
}
public func ControlUseHolding(object clonk, int x, int y)
{
var direction = DIR_Left;
if (x > 0)
direction = DIR_Right;
var effect = GetEffect("DumpContents", this);
if (effect)
effect.dump_dir = direction;
return true;
}
public func ControlUseStop(object clonk, int x, int y)
{
RemoveEffect("DumpContents", this);
return true;
}
public func ControlUseCancel(object clonk, int x, int y)
{
RemoveEffect("DumpContents", this);
return true;
}
public func FxDumpContentsStart(object target, proplist effect, int temp, int direction)
{
if (temp)
return FX_OK;
// The time it takes to dump the contents depends on the mass of the lorry.
effect.dump_strength = BoundBy(1000 / GetMass(), 3, 8);
effect.dump_dir = direction;
// Rotate the lorry into the requested direction.
var rdir = -effect.dump_strength;
if (effect.dump_dir == DIR_Right)
rdir = effect.dump_strength;
SetRDir(rdir);
// Start dump sounds together.
Sound("Objects::Lorry::Dump1", false, 100, nil, +1);
Sound("Objects::Lorry::Dump2", false, 100, nil, +1);
return FX_OK;
}
public func FxDumpContentsTimer(object target, proplist effect, int time)
{
// Rotate the lorry into the requested direction.
var rdir = -effect.dump_strength;
if (effect.dump_dir == DIR_Right)
rdir = effect.dump_strength;
SetRDir(rdir);
// Dump one item every some frames if the angle is above 45 degrees. Only do this if the effect is at least active
// for 10 frames to prevent an accidental click while holding the lorry to dump some of its contents.
if (time >= 10 && ((effect.dump_dir == DIR_Left && GetR() < -45) || (effect.dump_dir == DIR_Right && GetR() > 45)))
{
if (!Random(3))
{
var x = RandomX(6, 8) * Sign(GetR());
var xdir = RandomX(70, 90) * Sign(GetR());
var random_content = FindObjects(Find_Container(this), Sort_Random());
if (GetLength(random_content) >= 1)
{
random_content = random_content[0];
random_content->Exit(x, RandomX(2, 3), Random(360), 0, 0, RandomX(-5, 5));
random_content->SetXDir(xdir, 100);
// Assume the controller of the lorry is also the one dumping the contents.
random_content->SetController(GetController());
AddEffect("BlockCollectionByLorry", random_content, 100, 8, this);
if (random_content->~IsLiquid())
{
random_content->SetPosition(GetX(), GetY());
random_content->Disperse(GetR() + 10 * Sign(GetR()));
}
}
}
}
return FX_OK;
}
public func FxDumpContentsStop(object target, proplist effect, int reason, bool temp)
{
if (temp)
return FX_OK;
// Stop rotating the lorry.
SetRDir(0);
// Stop dump sounds.
Sound("Objects::Lorry::Dump1", false, 100, nil, -1);
Sound("Objects::Lorry::Dump2", false, 100, nil, -1);
return FX_OK;
}
public func FxBlockCollectionByLorryTimer() { return FX_Execute_Kill; }
/*-- Production --*/
public func IsToolProduct() { return true; }
/*-- Actions --*/
local ActMap = {
Drive = {
Prototype = Action,
Name = "Drive",
Procedure = DFA_NONE,
Directions = 2,
FlipDir = 1,
Length = 20,
Delay = 2,
X = 0,
Y = 0,
Wdt = 22,
Hgt = 16,
NextAction = "Drive",
//Animation = "Drive",
},
};
/*-- Display --*/
public func Definition(proplist def)
{
SetProperty("PictureTransformation", Trans_Mul(Trans_Rotate(-25, 1, 0, 0), Trans_Rotate(40, 0, 1, 0)), def);
}
/*-- Properties --*/
local Name = "$Name$";
local Description = "$Description$";
local Touchable = 1;
local BorderBound = C4D_Border_Sides;
local ContactCalls = true;
local Components = {Metal = 2, Wood = 1};
local MaxContentsCount = 50; | 0 | 0.684881 | 1 | 0.684881 | game-dev | MEDIA | 0.717329 | game-dev | 0.943766 | 1 | 0.943766 |
SnoringCatGames/surfacer | 8,459 | src/level/surfacer_level.gd | tool
class_name SurfacerLevel, \
"res://addons/scaffolder/assets/images/editor_icons/scaffolder_level.png"
extends ScaffolderLevel
## The main level class for Surfacer.[br]
## - You should extend this with a sub-class for your specific game.[br]
## - You should then attach your sub-class to each of your level scenes.[br]
## - You should add a SurfacesTilemap child node to each of your level
## scenes, in order to define the collidable surfaces in your level.[br]
var graph_parser: PlatformGraphParser
var surface_store: SurfaceStore
var intro_choreographer: Choreographer
func _init() -> void:
graph_parser = PlatformGraphParser.new()
surface_store = graph_parser.surface_store
add_child(graph_parser)
func _enter_tree() -> void:
Su.space_state = self.get_world_2d().direct_space_state
func _load() -> void:
._load()
Sc.gui.hud.create_inspector()
graph_parser.parse(
Sc.levels.session.id,
Su.is_debug_only_platform_graph_state_included)
_check_on_removing_surface_marks()
func _start() -> void:
._start()
_execute_intro_choreography()
call_deferred("_initialize_annotators")
#func _on_started() -> void:
# ._on_started()
#func _add_default_player_character() -> void:
# ._add_default_player_character()
#func _add_npcs() -> void:
# ._add_npcs()
func _destroy() -> void:
Sc.annotators.on_level_destroyed()
graph_parser.queue_free()
._destroy()
#func quit(
# has_finished: bool,
# immediately: bool) -> void:
# .quit(has_finished, immediately)
#func _update_editor_configuration() -> void
# ._update_editor_configuration()
func _on_initial_input() -> void:
._on_initial_input()
if is_instance_valid(intro_choreographer):
intro_choreographer.on_interaction()
#func pause() -> void:
# .pause()
#func on_unpause() -> void:
# .on_unpause()
func _check_on_removing_surface_marks() -> void:
var should_remove_surface_marks: bool = \
!Engine.editor_hint and \
graph_parser.is_loaded_from_file and \
!Su.are_loaded_surfaces_deeply_validated
if should_remove_surface_marks:
var surface_marks: Array = Sc.utils.get_all_nodes_in_group(
SurfaceMark.GROUP_NAME_SURFACE_MARKS)
for mark in surface_marks:
mark.queue_free()
func _update_editor_configuration() -> void:
._update_editor_configuration()
if !_is_ready or \
_configuration_warning != "":
return
if Sc.utils.get_children_by_type(self, SurfacesTilemap).empty():
_set_configuration_warning(
"Subclasses of SurfacerLevel must include a " +
"SurfacesTilemap child.")
return
_set_configuration_warning("")
# Execute any intro cut-scene or initial navigation.
func _execute_intro_choreography() -> void:
if !is_instance_valid(_active_player_character):
_on_intro_choreography_finished()
return
intro_choreographer = Sc.levels.get_intro_choreographer(
_active_player_character)
if !is_instance_valid(intro_choreographer):
_on_intro_choreography_finished()
return
intro_choreographer.connect(
"finished", self, "_on_intro_choreography_finished")
add_child(intro_choreographer)
intro_choreographer.start()
func _on_intro_choreography_finished() -> void:
if is_instance_valid(_active_player_character):
_active_player_character._log(
"Choreog done",
"",
CharacterLogType.DEFAULT,
false)
if is_instance_valid(intro_choreographer):
intro_choreographer.queue_free()
intro_choreographer = null
_show_welcome_panel()
func _get_default_player_character_spawn_position() -> ScaffolderSpawnPosition:
# If no spawn position was defined for the default character, then start
# them at 0,0.
if !spawn_positions.has(Sc.characters.default_player_character_name):
var spawn_position := ScaffolderSpawnPosition.new()
spawn_position.character_name = \
Sc.characters.default_player_character_name
spawn_position.position = Vector2.ZERO
spawn_position.surface_attachment = "NONE"
register_spawn_position(
Sc.characters.default_player_character_name, spawn_position)
return spawn_positions[Sc.characters.default_player_character_name][0]
func _update_character_spawn_state(
character: ScaffolderCharacter,
position_or_spawn_position) -> void:
if position_or_spawn_position is SurfacerSpawnPosition:
character.set_start_attachment_surface_side_or_position(
position_or_spawn_position.surface_side)
# Move any projected Behaviors into the Character.
var projected_behaviors: Array = Sc.utils.get_children_by_type(
position_or_spawn_position,
Behavior,
false)
for behavior in projected_behaviors:
position_or_spawn_position.remove_child(behavior)
character.add_child(behavior)
else:
# Default to floor attachment.
character.set_start_attachment_surface_side_or_position(
SurfaceSide.FLOOR)
func _initialize_annotators() -> void:
set_tilemap_visibility(false)
set_background_visibility(false)
Sc.annotators.on_level_ready()
for group in [
Sc.characters.GROUP_NAME_PLAYERS,
Sc.characters.GROUP_NAME_NPCS]:
for character in Sc.utils.get_all_nodes_in_group(group):
character._on_annotators_ready()
func set_tilemap_visibility(is_visible: bool) -> void:
var foregrounds: Array = Sc.utils.get_children_by_type(
self,
TileMap)
for foreground in foregrounds:
foreground.visible = is_visible
func set_background_visibility(is_visible: bool) -> void:
var backgrounds: Array = Sc.utils.get_children_by_type(
self,
ParallaxBackground)
for background in backgrounds:
var layers: Array = Sc.utils.get_children_by_type(
background,
ParallaxLayer)
for layer in layers:
layer.visible = is_visible
func get_is_intro_choreography_running() -> bool:
return intro_choreographer != null
func _update_session_in_editor() -> void:
# Override parent behavior.
#._update_session_in_editor()
if !Engine.editor_hint:
return
Sc.levels.session.reset(level_id)
var tilemaps: Array = Sc.utils.get_children_by_type(self, SurfacesTilemap)
Sc.levels.session.config.cell_size = \
Vector2.INF if \
tilemaps.empty() else \
tilemaps[0].cell_size
func _set_level_id(value: String) -> void:
# Override parent.
#._set_level_id(value)
level_id = value
if !Engine.editor_hint and \
!Su.is_precomputing_platform_graphs:
assert(Sc.levels.session.id == level_id)
_update_editor_configuration()
_update_session_in_editor()
func _establish_boundaries() -> void:
level_bounds = _get_combined_surfaces_region()
camera_bounds = level_bounds.grow_individual(
Sc.levels.default_camera_bounds_level_margin.left,
Sc.levels.default_camera_bounds_level_margin.top,
Sc.levels.default_camera_bounds_level_margin.right,
Sc.levels.default_camera_bounds_level_margin.bottom)
character_bounds = level_bounds.grow_individual(
Sc.levels.default_character_bounds_level_margin.left,
Sc.levels.default_character_bounds_level_margin.top,
Sc.levels.default_character_bounds_level_margin.right,
Sc.levels.default_character_bounds_level_margin.bottom)
func _get_combined_surfaces_region() -> Rect2:
var tile_maps := \
get_tree().get_nodes_in_group(SurfacesTilemap.GROUP_NAME_SURFACES)
assert(!tile_maps.empty())
var tile_map: TileMap = tile_maps[0]
var tile_map_region: Rect2 = \
Sc.geometry.get_tilemap_bounds_in_world_coordinates(tile_map)
for i in range(1, tile_maps.size()):
tile_map = tile_maps[i]
tile_map_region = tile_map_region.merge(
Sc.geometry.get_tilemap_bounds_in_world_coordinates(tile_map))
return tile_map_region
| 0 | 0.934153 | 1 | 0.934153 | game-dev | MEDIA | 0.923913 | game-dev | 0.890908 | 1 | 0.890908 |
ProjectIgnis/CardScripts | 2,326 | official/c10286023.lua | --魔救の奇石-ドラガイト
--Adamancipator Crystal - Dragite
--Scripted by Eerie Code
local s,id=GetID()
function s.initial_effect(c)
--decktop other
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCountLimit(1,id)
e1:SetCondition(s.dtcon)
e1:SetTarget(s.dttg)
e1:SetOperation(s.dtop)
c:RegisterEffect(e1)
--to extra
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_TODECK)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,{id,1})
e2:SetTarget(s.tdtg)
e2:SetOperation(s.tdop)
c:RegisterEffect(e2)
end
s.listed_series={SET_ADAMANCIPATOR}
function s.dtcon(e,tp,eg,ep,ev,re,r,rp)
return re and re:GetHandler():IsSetCard(SET_ADAMANCIPATOR)
end
function s.dttg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function s.dtop(e,tp,eg,ep,ev,re,r,rp)
Duel.Draw(tp,1,REASON_EFFECT)
end
function s.tdfilter(c)
return (c:IsFaceup() or c:IsLocation(LOCATION_GRAVE)) and c:IsAttribute(ATTRIBUTE_WATER) and c:IsType(TYPE_SYNCHRO) and c:IsAbleToExtra()
end
function s.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
if chkc then return chkc:IsLocation(LOCATION_MZONE|LOCATION_GRAVE) and chkc:IsControler(tp) and s.tdfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.tdfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,nil) and c:IsAbleToDeck() end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local tc=Duel.SelectTarget(tp,s.tdfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,1,nil):GetFirst()
Duel.SetOperationInfo(0,CATEGORY_TODECK,c,1,tp,LOCATION_GRAVE)
if tc:IsLocation(LOCATION_GRAVE) then
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,tc,1,tp,0)
end
end
function s.tdop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SendtoDeck(tc,nil,SEQ_DECKTOP,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_EXTRA)
and c:IsRelateToEffect(e) and Duel.SendtoDeck(c,nil,SEQ_DECKTOP,REASON_EFFECT)~=0 then
Duel.ConfirmDecktop(tp,1)
end
end | 0 | 0.918595 | 1 | 0.918595 | game-dev | MEDIA | 0.934106 | game-dev | 0.96443 | 1 | 0.96443 |
kbengine/kbengine | 2,075 | kbe/src/server/cellapp/updatables.cpp | // Copyright 2008-2018 Yolo Technologies, Inc. All Rights Reserved. https://www.comblockengine.com
#include "updatables.h"
#include "helper/profile.h"
namespace KBEngine{
//-------------------------------------------------------------------------------------
Updatables::Updatables()
{
}
//-------------------------------------------------------------------------------------
Updatables::~Updatables()
{
clear();
}
//-------------------------------------------------------------------------------------
void Updatables::clear()
{
objects_.clear();
}
//-------------------------------------------------------------------------------------
bool Updatables::add(Updatable* updatable)
{
// ûдȼ̶ȼ
if (objects_.size() == 0)
{
objects_.push_back(std::map<uint32, Updatable*>());
objects_.push_back(std::map<uint32, Updatable*>());
}
KBE_ASSERT(updatable->updatePriority() < objects_.size());
static uint32 idx = 1;
std::map<uint32, Updatable*>& pools = objects_[updatable->updatePriority()];
// ֹظ
while (pools.find(idx) != pools.end())
++idx;
pools[idx] = updatable;
// ¼洢λ
updatable->removeIdx = idx++;
return true;
}
//-------------------------------------------------------------------------------------
bool Updatables::remove(Updatable* updatable)
{
std::map<uint32, Updatable*>& pools = objects_[updatable->updatePriority()];
pools.erase(updatable->removeIdx);
updatable->removeIdx = -1;
return true;
}
//-------------------------------------------------------------------------------------
void Updatables::update()
{
AUTO_SCOPED_PROFILE("callUpdates");
std::vector< std::map<uint32, Updatable*> >::iterator fpIter = objects_.begin();
for (; fpIter != objects_.end(); ++fpIter)
{
std::map<uint32, Updatable*>& pools = (*fpIter);
std::map<uint32, Updatable*>::iterator iter = pools.begin();
for (; iter != pools.end();)
{
if (!iter->second->update())
{
pools.erase(iter++);
}
else
{
++iter;
}
}
}
}
//-------------------------------------------------------------------------------------
}
| 0 | 0.844065 | 1 | 0.844065 | game-dev | MEDIA | 0.399016 | game-dev | 0.769235 | 1 | 0.769235 |
Toxocious/Moonlight | 1,135 | Server/scripts/field/jett_tuto_6_0.py | # Created by MechAviv
# Map ID :: 620100026
# Spaceship : In Front of the Shuttle
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.giveSkill(228, 1, 1)
OBJECT_1 = sm.sendNpcController(9270083, 430, -131)
sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0)
for i in range(3):
sm.spawnMob(9420564, -450, -120, False)
sm.forcedInput(1)
sm.sendDelay(30)
sm.forcedInput(0)
sm.setSpeakerID(9270083)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendNext("The guardsmen are already here! Does this mean our crew is...")
sm.setSpeakerID(9270083)
sm.removeEscapeButton()
sm.setPlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendSay("No... They were good people! I'm innocent! WHY CAN'T YOU SEE THAT?!")
sm.showEffect("Effect/DirectionNewPirate.img/newPirate/balloonMsg1/3", 2000, 0, -80, -2, -2, False, 0)
sm.sendDelay(500)
sm.showEffect("Effect/DirectionNewPirate.img/newPirate/attack_tuto", 3000, 0, -200, -2, -2, False, 0)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(False, True, False, False)
sm.chatScript("Eliminate all Guards.")
sm.startQuestNoCheck(5671) | 0 | 0.608972 | 1 | 0.608972 | game-dev | MEDIA | 0.718635 | game-dev | 0.563092 | 1 | 0.563092 |
lunar-sway/minestuck | 5,004 | src/main/java/com/mraof/minestuck/blockentity/machine/CruxtruderBlockEntity.java | package com.mraof.minestuck.blockentity.machine;
import com.mraof.minestuck.MinestuckConfig;
import com.mraof.minestuck.block.CruxiteDowelBlock;
import com.mraof.minestuck.block.MSBlocks;
import com.mraof.minestuck.blockentity.ItemStackBlockEntity;
import com.mraof.minestuck.blockentity.MSBlockEntityTypes;
import com.mraof.minestuck.item.MSItems;
import com.mraof.minestuck.util.ColorHandler;
import com.mraof.minestuck.util.MSSoundEvents;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.Containers;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.LevelEvent;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Objects;
/**
* Stores raw cruxite and produces uncarved cruxite dowels.
* Core Editmode deployable
*/
@ParametersAreNonnullByDefault
public class CruxtruderBlockEntity extends BlockEntity
{
private static final Logger LOGGER = LogManager.getLogger();
public static final String EMPTY = "block.minestuck.cruxtruder.empty";
private static final int CRUXITE_CAPACITY = 64;
private int color = -1;
private boolean isBroken = false;
private int material = 0;
public CruxtruderBlockEntity(BlockPos pos, BlockState state)
{
super(MSBlockEntityTypes.CRUXTRUDER.get(), pos, state);
}
public int getColor()
{
return color;
}
public void setColor(int Color)
{
color = Color;
}
public void setBroken()
{
this.isBroken = true;
this.setChanged();
}
private void checkIfValid()
{
if(this.isBroken || this.level == null)
return;
if(MSBlocks.CRUXTRUDER.isInvalidFromTube(this.level, this.getBlockPos()))
{
this.setBroken();
LOGGER.warn("Failed to notice a block being changed until afterwards at the cruxtruder at {}", getBlockPos());
}
}
private void setMaterial(int material)
{
this.material = material;
this.setChanged();
}
public void dropItems()
{
if(this.material > 0)
{
BlockPos pos = this.getBlockPos();
Containers.dropItemStack(Objects.requireNonNull(this.level), pos.getX(), pos.getY(), pos.getZ(),
new ItemStack(MSItems.RAW_CRUXITE.get(), this.material));
this.setMaterial(0);
}
}
public void onRightClick(Player player, boolean top)
{
this.checkIfValid();
if(!this.isBroken && level != null)
{
BlockPos pos = getBlockPos().above();
BlockState state = level.getBlockState(pos);
if(top && MinestuckConfig.SERVER.cruxtruderIntake.get() && state.isAir() && -1 < material && material < CRUXITE_CAPACITY)
{
ItemStack stack = player.getMainHandItem();
if(!stack.is(MSItems.RAW_CRUXITE.get()))
stack = player.getOffhandItem();
if(stack.is(MSItems.RAW_CRUXITE.get()))
{
int count = 1;
if(player.isShiftKeyDown()) //Doesn't actually work just yet
count = Math.min(CRUXITE_CAPACITY - material, stack.getCount());
if(!player.isCreative())
stack.shrink(count);
this.setMaterial(this.material + count);
level.playSound(null, pos, MSSoundEvents.CRUXTRUDER_DOWEL.get(), SoundSource.BLOCKS, 1F, 1F);
}
} else if(!top)
{
if(state.is(MSBlocks.EMERGING_CRUXITE_DOWEL.get()))
{
CruxiteDowelBlock.dropDowel(level, pos);
} else if(state.isAir())
{
if(MinestuckConfig.SERVER.cruxtruderIntake.get() && material == 0)
{
level.levelEvent(LevelEvent.SOUND_DISPENSER_FAIL, pos, 0);
player.sendSystemMessage(Component.translatable(EMPTY));
} else
{
level.setBlockAndUpdate(pos, MSBlocks.EMERGING_CRUXITE_DOWEL.get().defaultBlockState());
level.playSound(null, pos, MSSoundEvents.CRUXTRUDER_DOWEL.get(), SoundSource.BLOCKS, 1F, 1.75F);
if(level.getBlockEntity(pos) instanceof ItemStackBlockEntity blockEntity)
ColorHandler.setColor(blockEntity.getStack(), color);
else
LOGGER.warn("Did not find block entity for setting cruxite color after placing cruxtruder dowel at {}", pos);
if(0 < material)
this.setMaterial(this.material - 1);
}
}
}
}
}
@Override
protected void loadAdditional(CompoundTag nbt, HolderLookup.Provider pRegistries)
{
super.loadAdditional(nbt, pRegistries);
if(nbt.contains("color"))
color = nbt.getInt("color");
this.isBroken = nbt.getBoolean("broken");
material = nbt.getInt("material");
}
@Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider)
{
super.saveAdditional(compound, provider);
compound.putInt("color", color);
compound.putBoolean("broken", this.isBroken);
compound.putInt("material", material);
}
} | 0 | 0.951276 | 1 | 0.951276 | game-dev | MEDIA | 0.996307 | game-dev | 0.97562 | 1 | 0.97562 |
osgcc/ryzom | 9,947 | ryzom/tools/leveldesign/world_editor/world_editor_primitive_plugin/primitive_plugin.cpp | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "primitive_plugin.h"
#include "../world_editor/world_editor.h"
#include "../world_editor/display.h"
#include <nel/misc/file.h>
#include <nel/misc/path.h>
#include <nel/georges/u_form_elm.h>
#include <nel/georges/load_form.h>
using namespace std;
using namespace NLMISC;
using namespace NLLIGO;
CFileDisplayer *PrimitivePluginLogDisplayer= NULL;
extern "C"
{
void *createPlugin()
{
return new CPrimitivePlugin();
}
}
CPrimitivePlugin::CPrimitivePlugin()
{
NLMISC::createDebug();
PrimitivePluginLogDisplayer= new CFileDisplayer("world_editor_primitive_plugin.log", true, "WORLD_EDITOR_PRIMITIVE_PLUGIN.LOG");
DebugLog->addDisplayer (PrimitivePluginLogDisplayer);
InfoLog->addDisplayer (PrimitivePluginLogDisplayer);
WarningLog->addDisplayer (PrimitivePluginLogDisplayer);
ErrorLog->addDisplayer (PrimitivePluginLogDisplayer);
AssertLog->addDisplayer (PrimitivePluginLogDisplayer);
nlinfo("Starting primitive plugin...");
_PluginActive = false;
_PluginAccess = NULL;
}
bool CPrimitivePlugin::isActive()
{
return _PluginActive;
}
bool CPrimitivePlugin::activatePlugin()
{
_PluginActive = true;
// TODO : open the 'rebuild npc data' dialog box
return true;
}
bool CPrimitivePlugin::closePlugin()
{
_PluginActive = false;
return true;
}
std::string& CPrimitivePlugin::getName()
{
static string name("Primitive displayer");
return name;
}
void CPrimitivePlugin::TCreatureInfo::readGeorges (const NLMISC::CSmartPtr<NLGEORGES::UForm> &form, const NLMISC::CSheetId &sheetId)
{
const NLGEORGES::UFormElm &item=form->getRootNode();
// the form was found so read the true values from Georges
item.getValueByName(Radius, "Collision.CollisionRadius");
HaveRadius = Radius != 0.0f;
item.getValueByName(Length, "Collision.Length");
item.getValueByName(Width, "Collision.Width");
HaveBox = (Length != 0 && Width != 0);
}
void CPrimitivePlugin::TCreatureInfo::serial (NLMISC::IStream &s)
{
s.serial(HaveRadius);
s.serial(Radius);
s.serial(HaveBox);
s.serial(Width);
s.serial(Length);
}
uint CPrimitivePlugin::TCreatureInfo::getVersion ()
{
return 1;
}
// @{
// \name Overload for IPluginCallback
void CPrimitivePlugin::init(IPluginAccess *pluginAccess)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
AfxEnableControlContainer();
_PluginAccess = pluginAccess;
string packedFileName("primitive_plugin.packed_sheets");
vector<string> paths;
string sheetIdPath;
// add the search path
CConfigFile &cf = pluginAccess->getConfigFile();
CConfigFile::CVar *pv = cf.getVarPtr("PrimitivePluginPath");
if (pv)
{
for (uint i=0; i<pv->size(); ++i)
paths.push_back(pv->asString(i));
}
// add the sheetId file
pv = cf.getVarPtr("PrimitivePluginSheetId");
sheetIdPath = pv->asString();
// Init the sheet id
CPath::addSearchFile(sheetIdPath);
CSheetId::init(false);
// Read the sheets
if (NLMISC::CFile::fileExists(packedFileName))
loadForm("creature", packedFileName, _CreatureInfos, false, false);
else
{
for (uint i=0; i<paths.size(); ++i)
{
CPath::addSearchPath(paths[i], true, false);
}
// build the packed sheet
loadForm("creature", packedFileName, _CreatureInfos, true, false);
}
vector<string> classNames;
classNames.push_back("npc_bot");
_PluginAccess->registerPrimitiveDisplayer(this, classNames);
}
/// The current region has changed.
void CPrimitivePlugin::primitiveChanged(const NLLIGO::IPrimitive *root)
{
}
void CPrimitivePlugin::drawPrimitive(const NLLIGO::IPrimitive *primitive, const TRenderContext &ctx)
{
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
static const float POINT_ARROW_LINE_SIZE = 20.f;
static const float POINT_ARROW_HEAD_SIZE = 8.f;
static const float POINT_DOT_SIZE = 3.f;
static const uint CIRCLE_SEGMENT_SIZE = 20;
static const uint CIRCLE_MIN_SEGMENT_COUNT = 8;
std::string *sheetName;
primitive->getPropertyByName("sheet_client", sheetName);
TCreatureInfo *info = NULL;
if (!sheetName->empty())
{
// two step init of id to remove a flooding NeL warning
CSheetId id;
id.buildSheetId(*sheetName+".creature");
std::map<NLMISC::CSheetId, TCreatureInfo>::iterator it(_CreatureInfos.find(id));
if (it != _CreatureInfos.end())
{
info = &(it->second);
}
}
const CPrimPoint *point = dynamic_cast<const CPrimPoint *>(primitive);
if (point)
{
// Clip ?
if (!ctx.Display->isClipped (&point->Point, 1))
{
// Position in world
CVector center = point->Point;
ctx.Display->worldToPixel (center);
// Dot
CVector dot0, dot1, dot2, dot3;
dot0 = center;
dot0.x += POINT_DOT_SIZE;
dot0.y += POINT_DOT_SIZE;
dot1 = center;
dot1.x -= POINT_DOT_SIZE;
dot1.y += POINT_DOT_SIZE;
dot2 = center;
dot2.x -= POINT_DOT_SIZE;
dot2.y -= POINT_DOT_SIZE;
dot3 = center;
dot3.x += POINT_DOT_SIZE;
dot3.y -= POINT_DOT_SIZE;
// Transform primitive
transformVector (dot0, point->Angle, center);
transformVector (dot1, point->Angle, center);
transformVector (dot2, point->Angle, center);
transformVector (dot3, point->Angle, center);
// In world space
ctx.Display->pixelToWorld (center);
ctx.Display->pixelToWorld (dot0);
ctx.Display->pixelToWorld (dot1);
ctx.Display->pixelToWorld (dot2);
ctx.Display->pixelToWorld (dot3);
// Draw it
ctx.Display->triRenderProxy (ctx.MainColor, dot0, dot1, dot2, ctx.Selected?2:0);
ctx.Display->triRenderProxy (ctx.MainColor, dot2, dot3, dot0, ctx.Selected?2:0);
// Need detail?
if (ctx.ShowDetail)
{
// Prim class available ?
const CPrimitiveClass *primClass = ctx.PrimitiveClass;
if (primClass != NULL)
{
// Draw an arraow ?
if (primClass->ShowArrow)
{
// Position in world
center = point->Point;
ctx.Display->worldToPixel (center);
CVector arrow = center;
CVector arrow0 = center;
arrow.x += POINT_ARROW_LINE_SIZE;
CVector arrow1 = arrow;
CVector arrow2 = arrow;
arrow0.x += POINT_ARROW_LINE_SIZE + POINT_ARROW_HEAD_SIZE;
arrow1.y += POINT_ARROW_HEAD_SIZE;
arrow2.y -= POINT_ARROW_HEAD_SIZE;
// Transform primitive
transformVector (arrow, point->Angle, center);
transformVector (arrow0, point->Angle, center);
transformVector (arrow1, point->Angle, center);
transformVector (arrow2, point->Angle, center);
// In world space
ctx.Display->pixelToWorld (center);
ctx.Display->pixelToWorld (arrow);
ctx.Display->pixelToWorld (arrow0);
ctx.Display->pixelToWorld (arrow1);
ctx.Display->pixelToWorld (arrow2);
// Draw it
ctx.Display->lineRenderProxy (ctx.MainColor, center, arrow, ctx.Selected?2:0);
ctx.Display->triRenderProxy (ctx.ArrowColor, arrow0, arrow1, arrow2, ctx.Selected?2:0);
}
}
// Have bounding info ?
if (info != NULL)
{
if (info->HaveRadius)
{
// Get it
float fRadius = info->Radius;
// Get the perimeter
float perimeter = 2.f*(float)Pi*fRadius;
// Get the perimeter on the screen
perimeter *= (float)ctx.Display->getWidth() / (ctx.Display->_CurViewMax.x - ctx.Display->_CurViewMin.x);
// Get the segement count
perimeter /= (float)CIRCLE_SEGMENT_SIZE;
// Clamp
if (perimeter < CIRCLE_MIN_SEGMENT_COUNT)
perimeter = CIRCLE_MIN_SEGMENT_COUNT;
// Segment count
uint segmentCount = (uint)perimeter;
// Draw a circle
CVector posInit = center;
posInit.x += fRadius;
CVector posPrevious = posInit;
for (uint i=1; i<segmentCount+1; i++)
{
CVector pos = posInit;
transformVector (pos, (float)i*2.f*(float)Pi/(float)segmentCount, center);
ctx.Display->lineRenderProxy (ctx.MainColor, pos, posPrevious, ctx.Selected?2:0);
posPrevious = pos;
}
}
if (info->HaveBox)
{
CVector center = point->Point;
// ctx.Display->worldToPixel (center);
// Dot
CVector dot0, dot1, dot2, dot3;
dot0 = center;
dot0.x += info->Length/2;
dot0.y += info->Width/2;
dot1 = center;
dot1.x -= info->Length/2;
dot1.y += info->Width/2;
dot2 = center;
dot2.x -= info->Length/2;
dot2.y -= info->Width/2;
dot3 = center;
dot3.x += info->Length/2;
dot3.y -= info->Width/2;
// Transform primitive
transformVector (dot0, point->Angle, center);
transformVector (dot1, point->Angle, center);
transformVector (dot2, point->Angle, center);
transformVector (dot3, point->Angle, center);
// In world space
/* ctx.Display->pixelToWorld (center);
ctx.Display->pixelToWorld (dot0);
ctx.Display->pixelToWorld (dot1);
ctx.Display->pixelToWorld (dot2);
ctx.Display->pixelToWorld (dot3);
*/
// Draw it
ctx.Display->lineRenderProxy (ctx.MainColor, dot0, dot1, ctx.Selected?2:0);
ctx.Display->lineRenderProxy (ctx.MainColor, dot1, dot2, ctx.Selected?2:0);
ctx.Display->lineRenderProxy (ctx.MainColor, dot2, dot3, ctx.Selected?2:0);
ctx.Display->lineRenderProxy (ctx.MainColor, dot3, dot0, ctx.Selected?2:0);
}
}
}
}
}
}
| 0 | 0.913687 | 1 | 0.913687 | game-dev | MEDIA | 0.564567 | game-dev | 0.952813 | 1 | 0.952813 |
piruzhaolu/ActionFlow | 6,374 | Packages/lipi.action-flow/Runtime/System/ActionWakeSystem.cs | using UnityEngine;
using System.Collections;
using Unity.Entities;
using Unity.Transforms;
using Unity.Jobs;
using Unity.Collections;
using Unity.Burst;
namespace ActionFlow
{
public class NullSystem : JobComponentSystem
{
private EntityQuery m_GroupTimer;
protected override void OnCreate()
{
m_GroupTimer = GetEntityQuery(typeof(ActionRunState));
}
[BurstCompile]
struct BBJob : IJobForEach<ActionRunState>
{
int a;
public void Execute(ref ActionRunState c0)
{
a++;
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
return new BBJob().Schedule(m_GroupTimer,inputDeps);
}
}
/// <summary>
/// 将睡眠的Action Node 唤醒
/// </summary>
public class ActionWakeSystem : JobComponentSystem
{
private EntityQuery m_Group;
private EntityQuery m_GroupTimer;
protected override void OnCreate()
{
m_Group = GetEntityQuery(typeof(NodeSleeping));
m_GroupTimer = GetEntityQuery(typeof(NodeTimer), typeof(ActionRunState));
}
struct RemoveItem
{
public Entity Entity;
public int NodeIndex;
}
struct WakeItem
{
public int InstanceID;
public int ChunkIndex;
public int NodeIndex;
}
[BurstCompile]
struct WakeJob : IJobChunk
{
public ArchetypeChunkBufferType<NodeSleeping> NodeSleepings;
public NativeQueue<RemoveItem>.ParallelWriter RemoveList;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
var sleepings = chunk.GetBufferAccessor(NodeSleepings);
var chunkComponents = chunk.Archetype.GetComponentTypes(Allocator.Temp);
for (int i = 0; i < chunk.Count; i++)
{
var buffers = sleepings[i];
for (int j = buffers.Length - 1; j >= 0; j--)
{
var sleepingItem = buffers[j];
if (chunkComponents.IndexOf(sleepingItem.ComponentType) == -1)
{
buffers.RemoveAt(j);
RemoveList.Enqueue(new RemoveItem() { Entity = sleepingItem.Entity, NodeIndex = sleepingItem.NodeIndex });
//ActionRunStates[sleepingItem.Entity].State.SetNodeCycle(sleepingItem.NodeIndex, ActionStateData.NodeCycle.Waking);
}
}
}
}
}
[BurstCompile]
struct WakeWithTimerJob : IJobChunk
{
public ArchetypeChunkBufferType<NodeTimer> NodeTimeBufferType;
public ArchetypeChunkComponentType<ActionRunState> ActionRunStateType;
public float dt;
public NativeQueue<WakeItem>.ParallelWriter RemoveList;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
var nodeTimers = chunk.GetBufferAccessor(NodeTimeBufferType);
var states = chunk.GetNativeArray(ActionRunStateType);
for (int i = 0; i < chunk.Count; i++)
{
var buffers = nodeTimers[i];
for (int j = buffers.Length-1; j >=0; j--)
{
var item = buffers[j];
item.Time -= dt;
if (item.Time < 0)
{
RemoveList.Enqueue(new WakeItem()
{
InstanceID = states[i].InstanceID,
ChunkIndex = states[i].ChunkIndex,
NodeIndex = item.NodeIndex
});
buffers.RemoveAt(j);
}
else
{
buffers[j] = item;
}
}
}
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var removeList = new NativeQueue<RemoveItem>(Allocator.TempJob);
var timerRemoveList = new NativeQueue<WakeItem>(Allocator.TempJob);
var job = new WakeJob()
{
NodeSleepings = GetArchetypeChunkBufferType<NodeSleeping>(),
RemoveList = removeList.AsParallelWriter(),
};
var jobTimer = new WakeWithTimerJob()
{
dt = Time.DeltaTime,
NodeTimeBufferType = GetArchetypeChunkBufferType<NodeTimer>(),
ActionRunStateType = GetArchetypeChunkComponentType<ActionRunState>(),
RemoveList = timerRemoveList.AsParallelWriter(),
};
var handle = job.Schedule(m_Group, inputDeps);
var handleTimer = jobTimer.Schedule(m_GroupTimer, inputDeps);
handle.Complete();
handleTimer.Complete();
if (removeList.Count > 0)
{
var actionRunStates = GetComponentDataFromEntity<ActionRunState>();
while (removeList.TryDequeue(out var item))
{
var states = actionRunStates[item.Entity];
var container = ActionStateMapToAsset.Instance.GetContainer(states.InstanceID);
container.SetNodeCycle(new ActionStateIndex() { ChunkIndex = states.ChunkIndex, NodeIndex = item.NodeIndex }, NodeCycle.Waking);
}
}
if (timerRemoveList.Count > 0)
{
while(timerRemoveList.TryDequeue(out var item))
{
var container = ActionStateMapToAsset.Instance.GetContainer(item.InstanceID);
container.SetNodeCycle(new ActionStateIndex() { ChunkIndex = item.ChunkIndex, NodeIndex = item.NodeIndex }, NodeCycle.Waking);
}
}
removeList.Dispose();
timerRemoveList.Dispose();
return inputDeps;
}
}
}
| 0 | 0.942333 | 1 | 0.942333 | game-dev | MEDIA | 0.838697 | game-dev | 0.986589 | 1 | 0.986589 |
Team-EnderIO/EnderIO | 2,064 | enderio/src/main/java/com/enderio/enderio/client/content/machines/gui/screen/FluidTankScreen.java | package com.enderio.enderio.client.content.machines.gui.screen;
import com.enderio.enderio.EnderIO;
import com.enderio.enderio.client.content.machines.gui.screen.base.MachineScreen;
import com.enderio.enderio.client.content.machines.gui.widget.ActivityWidget;
import com.enderio.enderio.client.foundation.widgets.FluidStackWidget;
import com.enderio.enderio.client.foundation.widgets.RedstoneControlPickerWidget;
import com.enderio.enderio.content.storage.fluid_tank.FluidTankMenu;
import com.enderio.enderio.foundation.lang.EIOCommonLang;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
public class FluidTankScreen extends MachineScreen<FluidTankMenu> {
public static final ResourceLocation BG_TEXTURE = EnderIO.rl("textures/gui/screen/tank.png");
private static final int WIDTH = 176;
private static final int HEIGHT = 166;
public FluidTankScreen(FluidTankMenu pMenu, Inventory pPlayerInventory, Component pTitle) {
super(pMenu, pPlayerInventory, pTitle);
imageWidth = WIDTH;
imageHeight = HEIGHT;
}
@Override
protected void init() {
super.init();
addRenderableOnly(new FluidStackWidget(80 + leftPos, 21 + topPos, 16, 47, menu::getFluidTank));
addRenderableWidget(new RedstoneControlPickerWidget(leftPos + imageWidth - 6 - 16, topPos + 6,
menu::getRedstoneControl, menu::setRedstoneControl, EIOCommonLang.REDSTONE_MODE));
addRenderableWidget(new ActivityWidget(leftPos + imageWidth - 6 - 16, topPos + 16 * 4, menu::getMachineStates));
var overlay = addIOConfigOverlay(1, leftPos + 7, topPos + 83, 162, 76);
addIOConfigButton(leftPos + imageWidth - 6 - 16, topPos + 24, overlay);
}
@Override
protected void renderBg(GuiGraphics pGuiGraphics, float pPartialTick, int pMouseX, int pMouseY) {
pGuiGraphics.blit(BG_TEXTURE, leftPos, topPos, 0, 0, imageWidth, imageHeight);
}
}
| 0 | 0.763008 | 1 | 0.763008 | game-dev | MEDIA | 0.783341 | game-dev | 0.927806 | 1 | 0.927806 |
JunjieXian/VRLearnProject | 2,324 | Plugins/AdvancedSessionsPlugin/AdvancedSessions/Source/AdvancedSessions/Private/LogoutUserCallbackProxy.cpp | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "LogoutUserCallbackProxy.h"
#include "Online.h"
//////////////////////////////////////////////////////////////////////////
// ULogoutUserCallbackProxy
ULogoutUserCallbackProxy::ULogoutUserCallbackProxy(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, Delegate(FOnLogoutCompleteDelegate::CreateUObject(this, &ThisClass::OnCompleted))
{
}
ULogoutUserCallbackProxy* ULogoutUserCallbackProxy::LogoutUser(UObject* WorldContextObject, class APlayerController* PlayerController)
{
ULogoutUserCallbackProxy* Proxy = NewObject<ULogoutUserCallbackProxy>();
Proxy->PlayerControllerWeakPtr = PlayerController;
Proxy->WorldContextObject = WorldContextObject;
return Proxy;
}
void ULogoutUserCallbackProxy::Activate()
{
if (!PlayerControllerWeakPtr.IsValid())
{
OnFailure.Broadcast();
return;
}
ULocalPlayer* Player = Cast<ULocalPlayer>(PlayerControllerWeakPtr->Player);
if (!Player)
{
OnFailure.Broadcast();
return;
}
FOnlineSubsystemBPCallHelperAdvanced Helper(TEXT("LogoutUser"), GEngine->GetWorldFromContextObject(WorldContextObject.Get(), EGetWorldErrorMode::LogAndReturnNull));
if (!Helper.OnlineSub)
{
OnFailure.Broadcast();
return;
}
auto Identity = Helper.OnlineSub->GetIdentityInterface();
if (Identity.IsValid())
{
DelegateHandle = Identity->AddOnLogoutCompleteDelegate_Handle(Player->GetControllerId(), Delegate);
Identity->Logout(Player->GetControllerId());
return;
}
// Fail immediately
OnFailure.Broadcast();
}
void ULogoutUserCallbackProxy::OnCompleted(int LocalUserNum, bool bWasSuccessful)
{
if (PlayerControllerWeakPtr.IsValid())
{
ULocalPlayer* Player = Cast<ULocalPlayer>(PlayerControllerWeakPtr->Player);
if (Player)
{
FOnlineSubsystemBPCallHelperAdvanced Helper(TEXT("LogoutUser"), GEngine->GetWorldFromContextObject(WorldContextObject.Get(), EGetWorldErrorMode::LogAndReturnNull));
if (!Helper.OnlineSub)
{
OnFailure.Broadcast();
return;
}
auto Identity = Helper.OnlineSub->GetIdentityInterface();
if (Identity.IsValid())
{
Identity->ClearOnLogoutCompleteDelegate_Handle(Player->GetControllerId(), DelegateHandle);
}
}
}
if (bWasSuccessful)
{
OnSuccess.Broadcast();
}
else
{
OnFailure.Broadcast();
}
}
| 0 | 0.783621 | 1 | 0.783621 | game-dev | MEDIA | 0.848855 | game-dev | 0.932101 | 1 | 0.932101 |
PacktPublishing/Mastering-Cpp-Game-Development | 3,613 | Chapter06/Include/bullet/BulletCollision/BroadphaseCollision/btDispatcher.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_DISPATCHER_H
#define BT_DISPATCHER_H
#include "LinearMath/btScalar.h"
class btCollisionAlgorithm;
struct btBroadphaseProxy;
class btRigidBody;
class btCollisionObject;
class btOverlappingPairCache;
struct btCollisionObjectWrapper;
class btPersistentManifold;
class btPoolAllocator;
struct btDispatcherInfo
{
enum DispatchFunc
{
DISPATCH_DISCRETE = 1,
DISPATCH_CONTINUOUS
};
btDispatcherInfo()
:m_timeStep(btScalar(0.)),
m_stepCount(0),
m_dispatchFunc(DISPATCH_DISCRETE),
m_timeOfImpact(btScalar(1.)),
m_useContinuous(true),
m_debugDraw(0),
m_enableSatConvex(false),
m_enableSPU(true),
m_useEpa(true),
m_allowedCcdPenetration(btScalar(0.04)),
m_useConvexConservativeDistanceUtil(false),
m_convexConservativeDistanceThreshold(0.0f)
{
}
btScalar m_timeStep;
int m_stepCount;
int m_dispatchFunc;
mutable btScalar m_timeOfImpact;
bool m_useContinuous;
class btIDebugDraw* m_debugDraw;
bool m_enableSatConvex;
bool m_enableSPU;
bool m_useEpa;
btScalar m_allowedCcdPenetration;
bool m_useConvexConservativeDistanceUtil;
btScalar m_convexConservativeDistanceThreshold;
};
///The btDispatcher interface class can be used in combination with broadphase to dispatch calculations for overlapping pairs.
///For example for pairwise collision detection, calculating contact points stored in btPersistentManifold or user callbacks (game logic).
class btDispatcher
{
public:
virtual ~btDispatcher() ;
virtual btCollisionAlgorithm* findAlgorithm(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,btPersistentManifold* sharedManifold=0) = 0;
virtual btPersistentManifold* getNewManifold(const btCollisionObject* b0,const btCollisionObject* b1)=0;
virtual void releaseManifold(btPersistentManifold* manifold)=0;
virtual void clearManifold(btPersistentManifold* manifold)=0;
virtual bool needsCollision(const btCollisionObject* body0,const btCollisionObject* body1) = 0;
virtual bool needsResponse(const btCollisionObject* body0,const btCollisionObject* body1)=0;
virtual void dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,const btDispatcherInfo& dispatchInfo,btDispatcher* dispatcher) =0;
virtual int getNumManifolds() const = 0;
virtual btPersistentManifold* getManifoldByIndexInternal(int index) = 0;
virtual btPersistentManifold** getInternalManifoldPointer() = 0;
virtual btPoolAllocator* getInternalManifoldPool() = 0;
virtual const btPoolAllocator* getInternalManifoldPool() const = 0;
virtual void* allocateCollisionAlgorithm(int size) = 0;
virtual void freeCollisionAlgorithm(void* ptr) = 0;
};
#endif //BT_DISPATCHER_H
| 0 | 0.796258 | 1 | 0.796258 | game-dev | MEDIA | 0.958599 | game-dev | 0.798604 | 1 | 0.798604 |
SonicTHI/SaveOurShip2Experimental | 2,967 | Source/1.4/ArrivalAction/CaravanArrivalAction_VisitInsectPillarSite.cs | using System;
using System.Collections.Generic;
using Verse;
namespace RimWorld.Planet
{
public class CaravanArrivalAction_VisitInsectPillarSite : CaravanArrivalAction
{
private MapParent target;
public override string Label
{
get
{
return TranslatorFormattedStringExtensions.Translate("VisitEscapeShip",this.target.Label);
}
}
public override string ReportString
{
get
{
return TranslatorFormattedStringExtensions.Translate("CaravanVisiting",this.target.Label);
}
}
public CaravanArrivalAction_VisitInsectPillarSite()
{
}
public CaravanArrivalAction_VisitInsectPillarSite(InsectPillarSiteComp escapeShip)
{
this.target = (MapParent)escapeShip.parent;
}
public override FloatMenuAcceptanceReport StillValid(Caravan caravan, int destinationTile)
{
FloatMenuAcceptanceReport floatMenuAcceptanceReport = base.StillValid(caravan, destinationTile);
if (!floatMenuAcceptanceReport)
{
return floatMenuAcceptanceReport;
}
if (this.target != null && this.target.Tile != destinationTile)
{
return false;
}
return CaravanArrivalAction_VisitInsectPillarSite.CanVisit(caravan, this.target);
}
public override void Arrived(Caravan caravan)
{
if (!this.target.HasMap)
{
LongEventHandler.QueueLongEvent(delegate
{
this.DoArrivalAction(caravan);
}, "GeneratingMapForNewEncounter", false, null);
}
else
{
this.DoArrivalAction(caravan);
}
}
public override void ExposeData()
{
base.ExposeData();
Scribe_References.Look<MapParent>(ref this.target, "target", false);
}
private void DoArrivalAction(Caravan caravan)
{
bool flag = !this.target.HasMap;
if (flag)
{
this.target.SetFaction(Faction.OfPlayer);
}
Map orGenerateMap = GetOrGenerateMapUtility.GetOrGenerateMap(this.target.Tile, null);
Pawn t = caravan.PawnsListForReading[0];
CaravanEnterMapUtility.Enter(caravan, orGenerateMap, CaravanEnterMode.Edge, CaravanDropInventoryMode.UnloadIndividually, false, null);
Find.LetterStack.ReceiveLetter(TranslatorFormattedStringExtensions.Translate("LetterLabelCaravanEnteredMap",this.target), TranslatorFormattedStringExtensions.Translate("LetterCaravanEnteredMap",caravan.Label, this.target).CapitalizeFirst(), LetterDefOf.NeutralEvent, t, null, null);
}
public static FloatMenuAcceptanceReport CanVisit(Caravan caravan, MapParent escapeShip)
{
return true;
}
public static IEnumerable<FloatMenuOption> GetFloatMenuOptions(Caravan caravan, MapParent escapeShip)
{
return CaravanArrivalActionUtility.GetFloatMenuOptions<CaravanArrivalAction_VisitInsectPillarSite>(() => CaravanArrivalAction_VisitInsectPillarSite.CanVisit(caravan, escapeShip), () => new CaravanArrivalAction_VisitInsectPillarSite(escapeShip.GetComponent<InsectPillarSiteComp>()), TranslatorFormattedStringExtensions.Translate("VisitEscapeShip",escapeShip.Label), caravan, escapeShip.Tile, escapeShip);
}
}
} | 0 | 0.82624 | 1 | 0.82624 | game-dev | MEDIA | 0.81622 | game-dev | 0.683887 | 1 | 0.683887 |
FlaxEngine/FlaxEngine | 27,192 | Source/Editor/Modules/SceneEditingModule.cs | // Copyright (c) Wojciech Figat. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using FlaxEditor.Actions;
using FlaxEditor.SceneGraph;
using FlaxEditor.SceneGraph.Actors;
using FlaxEngine;
namespace FlaxEditor.Modules
{
/// <summary>
/// Editing scenes module. Manages scene objects selection and editing modes.
/// </summary>
/// <seealso cref="FlaxEditor.Modules.EditorModule" />
public sealed class SceneEditingModule : EditorModule
{
/// <summary>
/// The selected objects.
/// </summary>
public readonly List<SceneGraphNode> Selection = new List<SceneGraphNode>(64);
/// <summary>
/// Gets the amount of the selected objects.
/// </summary>
public int SelectionCount => Selection.Count;
/// <summary>
/// Gets a value indicating whether any object is selected.
/// </summary>
public bool HasSthSelected => Selection.Count > 0;
/// <summary>
/// Occurs when selected objects collection gets changed.
/// </summary>
public event Action SelectionChanged;
/// <summary>
/// Occurs before spawning actor to game action.
/// </summary>
public event Action SpawnBegin;
/// <summary>
/// Occurs after spawning actor to game action.
/// </summary>
public event Action SpawnEnd;
/// <summary>
/// Occurs before selection delete action.
/// </summary>
public event Action SelectionDeleteBegin;
/// <summary>
/// Occurs after selection delete action.
/// </summary>
public event Action SelectionDeleteEnd;
internal SceneEditingModule(Editor editor)
: base(editor)
{
}
private void BulkScenesSelectUpdate(bool select = true)
{
// Blank list deselects all
Select(select ? Editor.Scene.Root.ChildNodes : new List<SceneGraphNode>());
}
/// <summary>
/// Selects all scenes.
/// </summary>
public void SelectAllScenes()
{
BulkScenesSelectUpdate(true);
}
/// <summary>
/// Deselects all scenes.
/// </summary>
public void DeselectAllScenes()
{
BulkScenesSelectUpdate(false);
}
/// <summary>
/// Selects the specified actor (finds it's scene graph node).
/// </summary>
/// <param name="actor">The actor.</param>
public void Select(Actor actor)
{
var node = Editor.Scene.GetActorNode(actor);
if (node != null)
Select(node);
}
/// <summary>
/// Selects the specified collection of objects.
/// </summary>
/// <param name="selection">The selection.</param>
/// <param name="additive">if set to <c>true</c> will use additive mode, otherwise will clear previous selection.</param>
public void Select(List<SceneGraphNode> selection, bool additive = false)
{
if (selection == null)
{
Deselect();
return;
}
// Prevent from selecting null nodes
selection.RemoveAll(x => x == null);
// Check if won't change
if (!additive && Selection.Count == selection.Count && Selection.SequenceEqual(selection))
return;
var before = Selection.ToArray();
if (!additive)
Selection.Clear();
Selection.AddRange(selection);
SelectionChange(before);
}
/// <summary>
/// Selects the specified collection of objects.
/// </summary>
/// <param name="selection">The selection.</param>
/// <param name="additive">if set to <c>true</c> will use additive mode, otherwise will clear previous selection.</param>
public void Select(SceneGraphNode[] selection, bool additive = false)
{
if (selection == null)
throw new ArgumentNullException();
Select(selection.ToList(), additive);
}
/// <summary>
/// Selects the specified object.
/// </summary>
/// <param name="selection">The selection.</param>
/// <param name="additive">if set to <c>true</c> will use additive mode, otherwise will clear previous selection.</param>
public void Select(SceneGraphNode selection, bool additive = false)
{
if (selection == null)
throw new ArgumentNullException();
// Check if won't change
if (!additive && Selection.Count == 1 && Selection[0] == selection)
return;
if (additive && Selection.Contains(selection))
return;
var before = Selection.ToArray();
if (!additive)
Selection.Clear();
Selection.Add(selection);
SelectionChange(before);
}
/// <summary>
/// Deselects given object.
/// </summary>
public void Deselect(SceneGraphNode node)
{
if (!Selection.Contains(node))
return;
var before = Selection.ToArray();
Selection.Remove(node);
SelectionChange(before);
}
/// <summary>
/// Clears selected objects collection.
/// </summary>
public void Deselect()
{
// Check if won't change
if (Selection.Count == 0)
return;
var before = Selection.ToArray();
Selection.Clear();
SelectionChange(before);
}
private void SelectionChange(SceneGraphNode[] before)
{
Undo.AddAction(new SelectionChangeAction(before, Selection.ToArray(), OnSelectionUndo));
OnSelectionChanged();
}
private void OnSelectionUndo(SceneGraphNode[] toSelect)
{
Selection.Clear();
if (toSelect != null)
{
for (int i = 0; i < toSelect.Length; i++)
{
if (toSelect[i] != null)
Selection.Add(toSelect[i]);
else
Editor.LogWarning("Null scene graph node to select");
}
}
OnSelectionChanged();
}
private void OnDirty(ActorNode node)
{
var options = Editor.Options.Options;
var isPlayMode = Editor.StateMachine.IsPlayMode;
var actor = node.Actor;
// Auto CSG mesh rebuild
if (!isPlayMode && options.General.AutoRebuildCSG)
{
if (actor is BoxBrush && actor.Scene)
actor.Scene.BuildCSG(options.General.AutoRebuildCSGTimeoutMs);
}
// Auto NavMesh rebuild
if (!isPlayMode && options.General.AutoRebuildNavMesh && actor.Scene && node.AffectsNavigationWithChildren)
{
var bounds = actor.BoxWithChildren;
Navigation.BuildNavMesh(actor.Scene, bounds, options.General.AutoRebuildNavMeshTimeoutMs);
}
}
private static bool SelectActorsUsingAsset(Guid assetId, ref Guid id, Dictionary<Guid, bool> scannedAssets)
{
// Check for asset match or try to use cache
if (assetId == id)
return true;
if (scannedAssets.TryGetValue(id, out var result))
return result;
if (id == Guid.Empty || !FlaxEngine.Content.GetAssetInfo(id, out var assetInfo))
return false;
scannedAssets.Add(id, false);
// Skip scene assets
if (assetInfo.TypeName == "FlaxEngine.SceneAsset")
return false;
// Recursive check if this asset contains direct or indirect reference to the given asset
var asset = FlaxEngine.Content.Load<Asset>(assetInfo.ID, 1000);
if (asset)
{
var references = asset.GetReferences();
for (var i = 0; i < references.Length; i++)
{
if (SelectActorsUsingAsset(assetId, ref references[i], scannedAssets))
{
scannedAssets[id] = true;
return true;
}
}
}
return false;
}
private static void SelectActorsUsingAsset(Guid assetId, SceneGraphNode node, List<SceneGraphNode> selection, Dictionary<Guid, bool> scannedAssets)
{
if (node is ActorNode actorNode && actorNode.Actor)
{
// To detect if this actor uses the given asset simply serialize it to json and check used asset ids
// TODO: check scripts too
var json = actorNode.Actor.ToJson();
JsonAssetBase.GetReferences(json, out var ids);
for (var i = 0; i < ids.Length; i++)
{
if (SelectActorsUsingAsset(assetId, ref ids[i], scannedAssets))
{
selection.Add(actorNode);
break;
}
}
}
// Recursive check for children
for (int i = 0; i < node.ChildNodes.Count; i++)
SelectActorsUsingAsset(assetId, node.ChildNodes[i], selection, scannedAssets);
}
/// <summary>
/// Selects the actors using the given asset.
/// </summary>
/// <param name="assetId">The asset ID.</param>
/// <param name="additive">if set to <c>true</c> will use additive mode, otherwise will clear previous selection.</param>
public void SelectActorsUsingAsset(Guid assetId, bool additive = false)
{
// TODO: make it async action with progress
Profiler.BeginEvent("SelectActorsUsingAsset");
var selection = new List<SceneGraphNode>();
var scannedAssets = new Dictionary<Guid, bool>();
SelectActorsUsingAsset(assetId, Editor.Scene.Root, selection, scannedAssets);
Profiler.EndEvent();
Select(selection, additive);
}
/// <summary>
/// Spawns the specified actor to the game (with undo).
/// </summary>
/// <param name="actor">The actor.</param>
/// <param name="parent">The parent actor. Set null as default.</param>
/// <param name="orderInParent">The order under the parent to put the spawned actor.</param>
/// <param name="autoSelect">True if automatically select the spawned actor, otherwise false.</param>
public void Spawn(Actor actor, Actor parent = null, int orderInParent = -1, bool autoSelect = true)
{
bool isPlayMode = Editor.StateMachine.IsPlayMode;
if (Level.IsAnySceneLoaded == false)
throw new InvalidOperationException("Cannot spawn actor when no scene is loaded.");
SpawnBegin?.Invoke();
// During play in editor mode spawned actors should be dynamic (user can move them)
if (isPlayMode)
actor.StaticFlags = StaticFlags.None;
// Add it
Level.SpawnActor(actor, parent);
// Set order if given
if (orderInParent != -1)
actor.OrderInParent = orderInParent;
// Peek spawned node
var actorNode = Editor.Instance.Scene.GetActorNode(actor);
if (actorNode == null)
throw new InvalidOperationException("Failed to create scene node for the spawned actor.");
// Call post spawn action (can possibly setup custom default values)
actorNode.PostSpawn();
// Create undo action
IUndoAction action = new DeleteActorsAction(actorNode, true);
if (autoSelect)
{
var before = Selection.ToArray();
Selection.Clear();
Selection.Add(actorNode);
OnSelectionChanged();
action = new MultiUndoAction(action, new SelectionChangeAction(before, Selection.ToArray(), OnSelectionUndo));
}
Undo.AddAction(action);
// Mark scene as dirty
Editor.Scene.MarkSceneEdited(actor.Scene);
SpawnEnd?.Invoke();
OnDirty(actorNode);
}
/// <summary>
/// Converts the selected actor to another type.
/// </summary>
/// <param name="to">The type to convert in.</param>
public void Convert(Type to)
{
if (!Editor.SceneEditing.HasSthSelected || !(Editor.SceneEditing.Selection[0] is ActorNode))
return;
if (Level.IsAnySceneLoaded == false)
throw new InvalidOperationException("Cannot spawn actor when no scene is loaded.");
var actionList = new IUndoAction[4];
var oldNode = (ActorNode)Editor.SceneEditing.Selection[0];
var old = oldNode.Actor;
var actor = (Actor)FlaxEngine.Object.New(to);
var parent = old.Parent;
var orderInParent = old.OrderInParent;
// Steps:
// - deselect old actor
// - destroy old actor
// - spawn new actor
// - select new actor
SelectionDeleteBegin?.Invoke();
actionList[0] = new SelectionChangeAction(Selection.ToArray(), new SceneGraphNode[0], OnSelectionUndo);
actionList[0].Do();
actionList[1] = new DeleteActorsAction(oldNode.BuildAllNodes().Where(x => x.CanDelete).ToList());
SelectionDeleteEnd?.Invoke();
SpawnBegin?.Invoke();
// Copy properties
actor.Transform = old.Transform;
actor.StaticFlags = old.StaticFlags;
actor.HideFlags = old.HideFlags;
actor.Layer = old.Layer;
actor.Tags = old.Tags;
actor.Name = old.Name;
actor.IsActive = old.IsActive;
// Spawn actor
Level.SpawnActor(actor, parent);
if (parent != null)
actor.OrderInParent = orderInParent;
if (Editor.StateMachine.IsPlayMode)
actor.StaticFlags = StaticFlags.None;
// Move children
var scripts = old.Scripts;
for (var i = scripts.Length - 1; i >= 0; i--)
scripts[i].Actor = actor;
var children = old.Children;
for (var i = children.Length - 1; i >= 0; i--)
children[i].Parent = actor;
var actorNode = Editor.Instance.Scene.GetActorNode(actor);
if (actorNode == null)
throw new InvalidOperationException("Failed to create scene node for the spawned actor.");
actorNode.PostConvert(oldNode);
actorNode.PostSpawn();
Editor.Scene.MarkSceneEdited(actor.Scene);
actionList[1].Do();
actionList[2] = new DeleteActorsAction(actorNode.BuildAllNodes().Where(x => x.CanDelete).ToList(), true);
actionList[3] = new SelectionChangeAction(new SceneGraphNode[0], new SceneGraphNode[] { actorNode }, OnSelectionUndo);
actionList[3].Do();
Undo.AddAction(new MultiUndoAction(actionList, "Convert actor"));
SpawnEnd?.Invoke();
OnDirty(actorNode);
}
/// <summary>
/// Deletes the selected objects. Supports undo/redo.
/// </summary>
public void Delete()
{
// Peek things that can be removed
var objects = Selection.Where(x => x.CanDelete).ToList().BuildAllNodes().Where(x => x.CanDelete).ToList();
if (objects.Count == 0)
return;
var isSceneTreeFocus = Editor.Windows.SceneWin.ContainsFocus;
SelectionDeleteBegin?.Invoke();
// Change selection
var action1 = new SelectionChangeAction(Selection.ToArray(), new SceneGraphNode[0], OnSelectionUndo);
// Delete objects
var action2 = new DeleteActorsAction(objects);
// Merge two actions and perform them
var action = new MultiUndoAction(new IUndoAction[]
{
action1,
action2
}, action2.ActionString);
action.Do();
Undo.AddAction(action);
SelectionDeleteEnd?.Invoke();
if (isSceneTreeFocus)
{
Editor.Windows.SceneWin.Focus();
}
// fix scene window layout
Editor.Windows.SceneWin.PerformLayout();
Editor.Windows.SceneWin.PerformLayout();
}
/// <summary>
/// Copies the selected objects.
/// </summary>
public void Copy()
{
// Peek things that can be copied (copy all actors)
var objects = Selection.Where(x => x.CanCopyPaste).ToList().BuildAllNodes().Where(x => x.CanCopyPaste && x is ActorNode).ToList();
if (objects.Count == 0)
return;
// Serialize actors
var actors = objects.ConvertAll(x => ((ActorNode)x).Actor);
var data = Actor.ToBytes(actors.ToArray());
if (data == null)
{
Editor.LogError("Failed to copy actors data.");
return;
}
// Copy data
Clipboard.RawData = data;
}
/// <summary>
/// Pastes the copied objects. Supports undo/redo.
/// </summary>
public void Paste()
{
Paste(null);
}
/// <summary>
/// Pastes the copied objects. Supports undo/redo.
/// </summary>
/// <param name="pasteTargetActor">The target actor to paste copied data.</param>
public void Paste(Actor pasteTargetActor)
{
// Get clipboard data
var data = Clipboard.RawData;
// Set paste target if only one actor is selected and no target provided
if (pasteTargetActor == null && SelectionCount == 1 && Selection[0] is ActorNode actorNode)
{
pasteTargetActor = actorNode.Actor.Scene == actorNode.Actor ? actorNode.Actor : actorNode.Actor.Parent;
}
// Create paste action
var pasteAction = PasteActorsAction.Paste(data, pasteTargetActor?.ID ?? Guid.Empty);
if (pasteAction != null)
{
pasteAction.Do(out _, out var nodeParents);
// Select spawned objects (parents only)
var selectAction = new SelectionChangeAction(Selection.ToArray(), nodeParents.Cast<SceneGraphNode>().ToArray(), OnSelectionUndo);
selectAction.Do();
// Build single compound undo action that pastes the actors and selects the created objects (parents only)
Undo.AddAction(new MultiUndoAction(pasteAction, selectAction));
OnSelectionChanged();
}
// Scroll to new selected node while pasting
Editor.Windows.SceneWin.ScrollToSelectedNode();
}
/// <summary>
/// Cuts the selected objects. Supports undo/redo.
/// </summary>
public void Cut()
{
Copy();
Delete();
}
/// <summary>
/// Create parent for selected actors.
/// </summary>
public void CreateParentForSelectedActors()
{
List<SceneGraphNode> selection = Editor.SceneEditing.Selection;
// Get Actors but skip scene node
var actors = selection.Where(x => x is ActorNode and not SceneNode).Select(x => ((ActorNode)x).Actor);
var actorsCount = actors.Count();
if (actorsCount == 0)
return;
Vector3 center = Vector3.Zero;
foreach (var actor in actors)
center += actor.Position;
center /= actorsCount;
Actor parent = new EmptyActor
{
Position = center,
};
Editor.SceneEditing.Spawn(parent, null, -1, false);
using (new UndoMultiBlock(Undo, actors, "Reparent actors"))
{
for (int i = 0; i < selection.Count; i++)
{
if (selection[i] is ActorNode node)
{
if (node.ParentNode != node.ParentScene) // If parent node is not a scene
{
if (selection.Contains(node.ParentNode))
{
continue; // If parent and child nodes selected together, don't touch child nodes
}
// Put created node as child of the Parent Node of node
int parentOrder = node.Actor.OrderInParent;
parent.SetParent(node.Actor.Parent, true, true);
parent.OrderInParent = parentOrder;
}
node.Actor.SetParent(parent, true, false);
}
}
}
Editor.SceneEditing.Select(parent);
Editor.Scene.GetActorNode(parent).TreeNode.StartRenaming(Editor.Windows.SceneWin, Editor.Windows.SceneWin.SceneTreePanel);
}
/// <summary>
/// Duplicates the selected objects. Supports undo/redo.
/// </summary>
public void Duplicate()
{
// Peek things that can be copied (copy all actors)
var nodes = Selection.Where(x => x.CanDuplicate).ToList().BuildAllNodes();
if (nodes.Count == 0)
return;
var actors = new List<Actor>();
var newSelection = new List<SceneGraphNode>();
List<IUndoAction> customUndoActions = null;
foreach (var node in nodes)
{
if (node.CanDuplicate)
{
if (node is ActorNode actorNode)
{
actors.Add(actorNode.Actor);
}
else
{
var customDuplicatedObject = node.Duplicate(out var customUndoAction);
if (customDuplicatedObject != null)
newSelection.Add(customDuplicatedObject);
if (customUndoAction != null)
{
if (customUndoActions == null)
customUndoActions = new List<IUndoAction>();
customUndoActions.Add(customUndoAction);
}
}
}
}
if (actors.Count == 0)
{
// Duplicate custom scene graph nodes only without actors
if (newSelection.Count != 0)
{
// Select spawned objects (parents only)
var selectAction = new SelectionChangeAction(Selection.ToArray(), newSelection.ToArray(), OnSelectionUndo);
selectAction.Do();
// Build a single compound undo action that pastes the actors, pastes custom stuff (scene graph extension) and selects the created objects (parents only)
var customUndoActionsCount = customUndoActions?.Count ?? 0;
var undoActions = new IUndoAction[1 + customUndoActionsCount];
for (int i = 0; i < customUndoActionsCount; i++)
undoActions[i] = customUndoActions[i];
undoActions[undoActions.Length - 1] = selectAction;
Undo.AddAction(new MultiUndoAction(undoActions));
OnSelectionChanged();
}
return;
}
// Serialize actors
var data = Actor.ToBytes(actors.ToArray());
if (data == null)
{
Editor.LogError("Failed to copy actors data.");
return;
}
// Create paste action (with selecting spawned objects)
var pasteAction = PasteActorsAction.Duplicate(data, Guid.Empty);
if (pasteAction != null)
{
pasteAction.Do(out _, out var nodeParents);
// Select spawned objects (parents only)
newSelection.Clear();
newSelection.AddRange(nodeParents);
var selectAction = new SelectionChangeAction(Selection.ToArray(), newSelection.ToArray(), OnSelectionUndo);
selectAction.Do();
// Build a single compound undo action that pastes the actors, pastes custom stuff (scene graph extension) and selects the created objects (parents only)
var customUndoActionsCount = customUndoActions?.Count ?? 0;
var undoActions = new IUndoAction[2 + customUndoActionsCount];
undoActions[0] = pasteAction;
for (int i = 0; i < customUndoActionsCount; i++)
undoActions[i + 1] = customUndoActions[i];
undoActions[undoActions.Length - 1] = selectAction;
Undo.AddAction(new MultiUndoAction(undoActions));
OnSelectionChanged();
}
// Scroll to new selected node while duplicating
Editor.Windows.SceneWin.ScrollToSelectedNode();
}
/// <summary>
/// Called when selection gets changed. Invokes the other events and updates editor. Call it when you manually modify selected objects collection.
/// </summary>
public void OnSelectionChanged()
{
SelectionChanged?.Invoke();
}
/// <inheritdoc />
public override void OnInit()
{
// Deselect actors on remove (and actor child nodes)
Editor.Scene.ActorRemoved += Deselect;
Editor.Scene.Root.ActorChildNodesDispose += OnActorChildNodesDispose;
}
private void OnActorChildNodesDispose(ActorNode node)
{
if (Selection.Count == 0)
return;
// TODO: cache if selection contains any actor child node and skip this loop if no need to iterate
// TODO: or build a hash set with selected nodes for quick O(1) checks (cached until selection changes)
// Deselect child nodes
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (Selection.Contains(node.ChildNodes[i]))
{
Deselect();
return;
}
}
}
}
}
| 0 | 0.825679 | 1 | 0.825679 | game-dev | MEDIA | 0.798686 | game-dev | 0.953853 | 1 | 0.953853 |
Jonazan2/PatBoy | 5,136 | libs/SDL2/src/events/SDL_quit.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
#include "SDL_hints.h"
/* General quit handling code for SDL */
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include "SDL_events.h"
#include "SDL_events_c.h"
#if defined(HAVE_SIGNAL_H) || defined(HAVE_SIGACTION)
#define HAVE_SIGNAL_SUPPORT 1
#endif
#ifdef HAVE_SIGNAL_SUPPORT
static SDL_bool disable_signals = SDL_FALSE;
static SDL_bool send_quit_pending = SDL_FALSE;
#ifdef SDL_BACKGROUNDING_SIGNAL
static SDL_bool send_backgrounding_pending = SDL_FALSE;
#endif
#ifdef SDL_FOREGROUNDING_SIGNAL
static SDL_bool send_foregrounding_pending = SDL_FALSE;
#endif
static void
SDL_HandleSIG(int sig)
{
/* Reset the signal handler */
signal(sig, SDL_HandleSIG);
/* Send a quit event next time the event loop pumps. */
/* We can't send it in signal handler; SDL_malloc() might be interrupted! */
if ((sig == SIGINT) || (sig == SIGTERM)) {
send_quit_pending = SDL_TRUE;
}
#ifdef SDL_BACKGROUNDING_SIGNAL
else if (sig == SDL_BACKGROUNDING_SIGNAL) {
send_backgrounding_pending = SDL_TRUE;
}
#endif
#ifdef SDL_FOREGROUNDING_SIGNAL
else if (sig == SDL_FOREGROUNDING_SIGNAL) {
send_foregrounding_pending = SDL_TRUE;
}
#endif
}
static void
SDL_EventSignal_Init(const int sig)
{
#ifdef HAVE_SIGACTION
struct sigaction action;
sigaction(sig, NULL, &action);
#ifdef HAVE_SA_SIGACTION
if ( action.sa_handler == SIG_DFL && (void (*)(int))action.sa_sigaction == SIG_DFL ) {
#else
if ( action.sa_handler == SIG_DFL ) {
#endif
action.sa_handler = SDL_HandleSIG;
sigaction(sig, &action, NULL);
}
#elif HAVE_SIGNAL_H
void (*ohandler) (int) = signal(sig, SDL_HandleSIG);
if (ohandler != SIG_DFL) {
signal(sig, ohandler);
}
#endif
}
static void
SDL_EventSignal_Quit(const int sig)
{
#ifdef HAVE_SIGACTION
struct sigaction action;
sigaction(sig, NULL, &action);
if ( action.sa_handler == SDL_HandleSIG ) {
action.sa_handler = SIG_DFL;
sigaction(sig, &action, NULL);
}
#elif HAVE_SIGNAL_H
void (*ohandler) (int) = signal(sig, SIG_DFL);
if (ohandler != SDL_HandleSIG) {
signal(sig, ohandler);
}
#endif /* HAVE_SIGNAL_H */
}
/* Public functions */
static int
SDL_QuitInit_Internal(void)
{
/* Both SIGINT and SIGTERM are translated into quit interrupts */
/* and SDL can be built to simulate iOS/Android semantics with arbitrary signals. */
SDL_EventSignal_Init(SIGINT);
SDL_EventSignal_Init(SIGTERM);
#ifdef SDL_BACKGROUNDING_SIGNAL
SDL_EventSignal_Init(SDL_BACKGROUNDING_SIGNAL);
#endif
#ifdef SDL_FOREGROUNDING_SIGNAL
SDL_EventSignal_Init(SDL_FOREGROUNDING_SIGNAL);
#endif
/* That's it! */
return 0;
}
static void
SDL_QuitQuit_Internal(void)
{
SDL_EventSignal_Quit(SIGINT);
SDL_EventSignal_Quit(SIGTERM);
#ifdef SDL_BACKGROUNDING_SIGNAL
SDL_EventSignal_Quit(SDL_BACKGROUNDING_SIGNAL);
#endif
#ifdef SDL_FOREGROUNDING_SIGNAL
SDL_EventSignal_Quit(SDL_FOREGROUNDING_SIGNAL);
#endif
}
#endif
int
SDL_QuitInit(void)
{
#ifdef HAVE_SIGNAL_SUPPORT
if (!SDL_GetHintBoolean(SDL_HINT_NO_SIGNAL_HANDLERS, SDL_FALSE)) {
return SDL_QuitInit_Internal();
}
#endif
return 0;
}
void
SDL_QuitQuit(void)
{
#ifdef HAVE_SIGNAL_SUPPORT
if (!disable_signals) {
SDL_QuitQuit_Internal();
}
#endif
}
void
SDL_SendPendingSignalEvents(void)
{
#ifdef HAVE_SIGNAL_SUPPORT
if (send_quit_pending) {
SDL_SendQuit();
SDL_assert(!send_quit_pending);
}
#ifdef SDL_BACKGROUNDING_SIGNAL
if (send_backgrounding_pending) {
send_backgrounding_pending = SDL_FALSE;
SDL_OnApplicationWillResignActive();
}
#endif
#ifdef SDL_FOREGROUNDING_SIGNAL
if (send_foregrounding_pending) {
send_foregrounding_pending = SDL_FALSE;
SDL_OnApplicationDidBecomeActive();
}
#endif
#endif
}
/* This function returns 1 if it's okay to close the application window */
int
SDL_SendQuit(void)
{
#ifdef HAVE_SIGNAL_SUPPORT
send_quit_pending = SDL_FALSE;
#endif
return SDL_SendAppEvent(SDL_QUIT);
}
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.788128 | 1 | 0.788128 | game-dev | MEDIA | 0.653183 | game-dev | 0.52244 | 1 | 0.52244 |
DenizenScript/Denizen | 4,442 | plugin/src/main/java/com/denizenscript/denizen/events/player/PlayerEditsBookScriptEvent.java | package com.denizenscript.denizen.events.player;
import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizen.scripts.containers.core.BookScriptContainer;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizen.utilities.implementation.BukkitScriptEntryData;
import com.denizenscript.denizen.events.BukkitScriptEvent;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.core.ScriptTag;
import com.denizenscript.denizencore.scripts.ScriptEntryData;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerEditBookEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
public class PlayerEditsBookScriptEvent extends BukkitScriptEvent implements Listener {
// <--[event]
// @Events
// player edits book
// player signs book
//
// @Group Player
//
// @Cancellable true
//
// @Location true
//
// @Triggers when a player edits or signs a book.
//
// @Context
// <context.title> returns the name of the book, if any.
// <context.pages> returns the number of pages in the book.
// <context.book> returns the book item being edited, containing the new page contents.
// <context.old_book> returns the book item being edited, containing the old page contents.
// <context.signing> returns whether the book is about to be signed.
//
// @Determine
// "NOT_SIGNING" to prevent the book from being signed.
// ScriptTag to set the book information to set it to instead.
//
// @Player Always.
//
// -->
public PlayerEditsBookScriptEvent() {
registerCouldMatcher("player edits book");
registerCouldMatcher("player signs book");
this.<PlayerEditsBookScriptEvent>registerTextDetermination("not_signing", (evt) -> {
evt.event.setSigning(false);
});
this.<PlayerEditsBookScriptEvent, ScriptTag>registerOptionalDetermination(null, ScriptTag.class, (evt, context, value) -> {
if (value.getContainer() instanceof BookScriptContainer script) {
ItemTag dBook = script.getBookFrom(context);
BookMeta bookMeta = (BookMeta) dBook.getItemMeta();
if (dBook.getBukkitMaterial() == Material.WRITABLE_BOOK) {
evt.event.setSigning(false);
}
evt.event.setNewBookMeta(bookMeta);
return true;
}
else {
Debug.echoError("Script '" + value + "' is valid, but not of type 'book'!");
return false;
}
});
}
public PlayerEditBookEvent event;
@Override
public boolean matches(ScriptPath path) {
String action = path.eventArgLowerAt(1);
if (!(action.equals("edits") && !event.isSigning()) && !(action.equals("signs") && event.isSigning())) {
return false;
}
if (!runInCheck(path, event.getPlayer().getLocation())) {
return false;
}
return super.matches(path);
}
@Override
public ScriptEntryData getScriptEntryData() {
return new BukkitScriptEntryData(event.getPlayer());
}
@Override
public ObjectTag getContext(String name) {
return switch (name) {
case "signing" -> new ElementTag(event.isSigning());
case "title" -> event.isSigning() ? new ElementTag(event.getNewBookMeta().getTitle(), true) : null;
case "pages" -> new ElementTag(event.getNewBookMeta().getPageCount());
case "book" -> {
ItemStack book = new ItemStack(event.isSigning() ? Material.WRITTEN_BOOK : Material.WRITABLE_BOOK);
book.setItemMeta(event.getNewBookMeta());
yield new ItemTag(book);
}
case "old_book" -> {
ItemStack book = new ItemStack(Material.WRITABLE_BOOK);
book.setItemMeta(event.getPreviousBookMeta());
yield new ItemTag(book);
}
default -> super.getContext(name);
};
}
@EventHandler
public void onPlayerEditsBook(PlayerEditBookEvent event) {
this.event = event;
fire(event);
}
}
| 0 | 0.878131 | 1 | 0.878131 | game-dev | MEDIA | 0.774526 | game-dev | 0.90954 | 1 | 0.90954 |
CombatExtended-Continued/CombatExtended | 5,394 | Source/CombatExtended/CombatExtended/DangerTracker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;
namespace CombatExtended;
public class DangerTracker : MapComponent
{
//private const int DANGER_TICKS = 450;
//private const int DANGER_TICKS_BULLET_STEP = 200;
private const int DANGER_TICKS_SMOKE_STEP = 150;
private const float PROJECTILE_DANGER_FACTOR = 0.5f;
public const int DANGER_TICKS_MAX = 300; // 1s in real life = 60 ticks in game;
//private const float DANGER_BULLET_MAX_DIST = 20f;
private const float WEIGHTS_DIG = 0.8f;
private const float WEIGHTS_COL = 0.5f;
private const float WEIGHTSSUM = WEIGHTS_DIG * 4f + WEIGHTS_COL * 4f + 1f;
private static readonly IntVec3[] AdjCells;
private static readonly float[] AdjWeights;
static DangerTracker()
{
AdjCells = new IntVec3[9];
AdjWeights = new float[9];
AdjCells[0] = new IntVec3(0, 0, 0);
AdjWeights[0] = 1.0f;
AdjCells[1] = new IntVec3(1, 0, 1);
AdjWeights[1] = WEIGHTS_COL;
AdjCells[2] = new IntVec3(-1, 0, 1);
AdjWeights[2] = WEIGHTS_COL;
AdjCells[3] = new IntVec3(1, 0, -1);
AdjWeights[3] = WEIGHTS_COL;
AdjCells[4] = new IntVec3(-1, 0, -1);
AdjWeights[4] = WEIGHTS_COL;
AdjCells[5] = new IntVec3(1, 0, 0);
AdjWeights[5] = WEIGHTS_DIG;
AdjCells[6] = new IntVec3(-1, 0, 0);
AdjWeights[6] = WEIGHTS_DIG;
AdjCells[7] = new IntVec3(0, 0, 1);
AdjWeights[7] = WEIGHTS_DIG;
AdjCells[8] = new IntVec3(0, 0, -1);
AdjWeights[8] = WEIGHTS_DIG;
}
private int[] dangerArray;
public DangerTracker(Map map) : base(map)
{
dangerArray = new int[map.cellIndices.NumGridCells];
}
public void Notify_BulletAt(IntVec3 pos, float dangerAmount)
{
for (int i = 0; i < 9; i++)
{
IntVec3 cell = pos + AdjCells[i];
if (cell.InBounds(map))
{
IncreaseAt(cell, (int)Mathf.Ceil(AdjWeights[i] * dangerAmount * PROJECTILE_DANGER_FACTOR));
}
}
if (Controller.settings.DebugDisplayDangerBuildup)
{
FlashCells(pos);
}
}
public void Notify_DangerRadiusAt(IntVec3 pos, float radius, float dangerAmount, bool reduceOverDistance = true)
{
//var radiusSqrd = radius * radius;
foreach (IntVec3 cell in GenRadial.RadialCellsAround(pos, radius, true))
{
if (!cell.InBounds(map) && !GenSight.LineOfSight(pos, cell, this.map))
{
continue;
}
if (reduceOverDistance)
{
dangerAmount *= Mathf.Clamp01(1 - ((pos.ToVector3() - cell.ToVector3()).sqrMagnitude / (radius * radius)) * 0.1f);
}
IncreaseAt(cell, (int)Mathf.Ceil(dangerAmount));
if (Controller.settings.DebugDisplayDangerBuildup)
{
float value = DangerAt(cell);
if (value > 0f)
{
map.debugDrawer.FlashCell(cell, value, $"{value}");
}
}
}
}
public void Notify_SmokeAt(IntVec3 pos, float concentration)
{
for (int i = 0; i < 9; i++)
{
IntVec3 cell = pos + AdjCells[i];
if (cell.InBounds(map))
{
SetAt(cell, (int)(DANGER_TICKS_SMOKE_STEP * AdjWeights[i] * concentration));
}
}
if (Controller.settings.DebugDisplayDangerBuildup)
{
FlashCells(pos);
}
}
public float DangerAt(IntVec3 pos)
{
if (pos.InBounds(map))
{
return (float)Mathf.Clamp(dangerArray[map.cellIndices.CellToIndex(pos)] - GenTicks.TicksGame, 0, DANGER_TICKS_MAX) / (float)DANGER_TICKS_MAX;
}
return 0f;
}
public float DangerAt(int index)
{
return this.DangerAt(map.cellIndices.IndexToCell(index));
}
public override void ExposeData()
{
base.ExposeData();
List<int> dangerList = dangerArray.ToList();
Scribe_Collections.Look(ref dangerList, "dangerList", LookMode.Value);
if (dangerList == null || dangerList.Count != map.cellIndices.NumGridCells)
{
dangerArray = new int[map.cellIndices.NumGridCells];
}
}
private void FlashCells(IntVec3 pos)
{
for (int i = 0; i < 9; i++)
{
IntVec3 cell = pos + AdjCells[i];
if (cell.InBounds(map))
{
float value = DangerAt(cell);
if (value > 0f)
{
map.debugDrawer.FlashCell(cell, value, $"{value}");
}
}
}
}
private void IncreaseAt(IntVec3 pos, int amount)
{
int index = map.cellIndices.CellToIndex(pos);
int value = dangerArray[index];
int ticks = GenTicks.TicksGame;
dangerArray[index] = Mathf.Clamp(value + amount, ticks + amount, ticks + DANGER_TICKS_MAX);
}
private void SetAt(IntVec3 pos, int amount)
{
int index = map.cellIndices.CellToIndex(pos);
int value = dangerArray[index];
int ticks = GenTicks.TicksGame;
dangerArray[index] = Mathf.Clamp(ticks + amount, value, ticks + DANGER_TICKS_MAX);
}
}
| 0 | 0.880121 | 1 | 0.880121 | game-dev | MEDIA | 0.98986 | game-dev | 0.805964 | 1 | 0.805964 |
shuo-liu16/CS61A | 9,039 | proj/ants/tests/09.py | test = {
'name': 'Problem 9',
'points': 2,
'suites': [
{
'cases': [
{
'answer': 'A TankAnt does damage to all Bees in its place each turn',
'choices': [
'A TankAnt does damage to all Bees in its place each turn',
'A TankAnt has greater health than a BodyguardAnt',
'A TankAnt can contain multiple ants',
'A TankAnt increases the damage of the ant it contains'
],
'hidden': False,
'locked': False,
'multiline': False,
'question': r"""
Besides costing more to place, what is the only difference between a
TankAnt and a BodyguardAnt?
"""
}
],
'scored': False,
'type': 'concept'
},
{
'cases': [
{
'code': r"""
>>> # Testing TankAnt parameters
>>> TankAnt.food_cost
6
>>> TankAnt.damage
1
>>> tank = TankAnt()
>>> tank.health
2
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> # Testing TankAnt action
>>> tank = TankAnt()
>>> place = gamestate.places['tunnel_0_1']
>>> other_place = gamestate.places['tunnel_0_2']
>>> place.add_insect(tank)
>>> for _ in range(3):
... place.add_insect(Bee(3))
>>> other_place.add_insect(Bee(3))
>>> tank.action(gamestate)
>>> [bee.health for bee in place.bees]
[2, 2, 2]
>>> [bee.health for bee in other_place.bees]
[3]
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> # Testing TankAnt container methods
>>> tank = TankAnt()
>>> thrower = ThrowerAnt()
>>> place = gamestate.places['tunnel_0_1']
>>> place.add_insect(thrower)
>>> place.add_insect(tank)
>>> place.ant is tank
True
>>> bee = Bee(3)
>>> place.add_insect(bee)
>>> tank.action(gamestate) # Both ants attack bee
>>> bee.health
1
""",
'hidden': False,
'locked': False,
'multiline': False
}
],
'scored': True,
'setup': r"""
>>> from ants_plans import *
>>> from ants import *
>>> beehive, layout = Hive(make_test_assault_plan()), dry_layout
>>> dimensions = (1, 9)
>>> gamestate = GameState(beehive, ant_types(), layout, dimensions)
>>> #
""",
'teardown': '',
'type': 'doctest'
},
{
'cases': [
{
'code': r"""
>>> # Testing TankAnt action
>>> tank = TankAnt()
>>> place = gamestate.places['tunnel_0_1']
>>> place.add_insect(tank)
>>> for _ in range(3): # Add three bees with 1 health each
... place.add_insect(Bee(1))
>>> tank.action(gamestate)
>>> len(place.bees) # Bees removed from places because of TankAnt damage
0
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> # Testing TankAnt.damage
>>> tank = TankAnt()
>>> tank.damage = 100
>>> place = gamestate.places['tunnel_0_1']
>>> place.add_insect(tank)
>>> for _ in range(3):
... place.add_insect(Bee(100))
>>> tank.action(gamestate)
>>> len(place.bees)
0
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> # Placement of ants
>>> tank = TankAnt()
>>> harvester = HarvesterAnt()
>>> place = gamestate.places['tunnel_0_0']
>>> # Add tank before harvester
>>> place.add_insect(tank)
>>> place.add_insect(harvester)
>>> gamestate.food = 0
>>> tank.action(gamestate)
>>> gamestate.food
1
>>> try:
... place.add_insect(TankAnt())
... except AssertionError:
... print("error!")
error!
>>> place.ant is tank
True
>>> tank.ant_contained is harvester
True
>>> try:
... place.add_insect(HarvesterAnt())
... except AssertionError:
... print("error!")
error!
>>> place.ant is tank
True
>>> tank.ant_contained is harvester
True
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> # Placement of ants
>>> tank = TankAnt()
>>> harvester = HarvesterAnt()
>>> place = gamestate.places['tunnel_0_0']
>>> # Add harvester before tank
>>> place.add_insect(harvester)
>>> place.add_insect(tank)
>>> gamestate.food = 0
>>> tank.action(gamestate)
>>> gamestate.food
1
>>> try:
... place.add_insect(TankAnt())
... except AssertionError:
... print("error!")
error!
>>> place.ant is tank
True
>>> tank.ant_contained is harvester
True
>>> try:
... place.add_insect(HarvesterAnt())
... except AssertionError:
... print("error!")
error!
>>> place.ant is tank
True
>>> tank.ant_contained is harvester
True
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> # Removing ants
>>> tank = TankAnt()
>>> test_ant = Ant()
>>> place = Place('Test')
>>> place.add_insect(tank)
>>> place.add_insect(test_ant)
>>> place.remove_insect(test_ant)
>>> tank.ant_contained is None
True
>>> test_ant.place is None
True
>>> place.remove_insect(tank)
>>> place.ant is None
True
>>> tank.place is None
True
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> tank = TankAnt()
>>> place = Place('Test')
>>> place.add_insect(tank)
>>> tank.action(gamestate) # Action without ant_contained should not error
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> # test proper call to zero-health callback
>>> original_zero_health_callback = Insect.zero_health_callback
>>> Insect.zero_health_callback = lambda x: print("insect died")
>>> place = gamestate.places["tunnel_0_0"]
>>> bee = Bee(3)
>>> tank = TankAnt()
>>> ant = ThrowerAnt()
>>> place.add_insect(bee)
>>> place.add_insect(ant)
>>> place.add_insect(tank)
>>> bee.action(gamestate)
>>> bee.action(gamestate)
insect died
>>> bee.action(gamestate) # if you fail this test you probably didn't correctly call Ant.reduce_health or Insect.reduce_health
insect died
>>> Insect.zero_health_callback = original_zero_health_callback
""",
'hidden': False,
'locked': False,
'multiline': False
}
],
'scored': True,
'setup': r"""
>>> from ants_plans import *
>>> from ants import *
>>> beehive, layout = Hive(make_test_assault_plan()), dry_layout
>>> dimensions = (1, 9)
>>> gamestate = GameState(beehive, ant_types(), layout, dimensions)
>>> #
""",
'teardown': '',
'type': 'doctest'
},
{
'cases': [
{
'code': r"""
>>> from ants import *
>>> TankAnt.implemented
True
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
'code': r"""
>>> from ants import *
>>> # Abstraction tests
>>> original = Ant.__init__
>>> Ant.__init__ = lambda self, health: print("init") #If this errors, you are not calling the parent constructor correctly.
>>> tank = TankAnt()
init
>>> Ant.__init__ = original
>>> tank = TankAnt()
""",
'hidden': False,
'locked': False,
'multiline': False
}
],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'
}
]
}
| 0 | 0.816666 | 1 | 0.816666 | game-dev | MEDIA | 0.957909 | game-dev,testing-qa | 0.628794 | 1 | 0.628794 |
gamestdio/pixi-engine | 2,471 | README.md | # pixi-engine
Provides a minimal engine-like structure for developing games with
[PixiJS](https://github.com/pixijs/pixi.js/).
## Classes
- [Application](#application)
- [Mediator](#mediator)
- [SceneManager](#scenemanager)
- [PlayerPrefs](#playerprefs)
Also, consider using other packages such as [@gamestdio/mathf](https://github.com/gamestdio/mathf) and [@gamestdio/keycode](https://github.com/gamestdio/keycode).
## `Application`
A singleton that extends from `PIXI.Application`. You might not need to use it directly. When switching scenes using [SceneManager](#scenemanager), the `Application` is used under the hood.
## `Mediator`
Mediators are meant for handling business logic in your game.
```typescript
import { Mediator } from "pixi-engine";
class MenuMediator extends Mediator<MenuView> {
initialize () {
console.log(this.view, "has been added.");
}
destroy () {
console.log(this.view, "has been removed.");
}
onButtonClick () {
console.log("Let's handle the click action here!");
}
}
```
```typescript
import { mediate, action } from "pixi-engine";
@mediate(MenuMediator)
class MenuView extends PIXI.Container {
button: PIXI.Sprite = PIXI.Sprite.fromFrame("my-button.png");
@action("onButtonClick")
handleClick () {
// handles the animation of this.button
}
// pixi-engine will call `update` method at every frame
update () {
}
// pixi-engine will call `resize` automatically when the window is resized
resize () {
}
}
```
## `SceneManager`
Inspired by Unity, `SceneManager` handles switching the current active scene. Scenes are instances of `PIXI.Container`.
```typescript
import { SceneManager } from "pixi-engine";
class MyScene extends PIXI.Container {
// definition of your scene
}
// Go-to target scene.
SceneManager.goTo(MyScene);
```
## `PlayerPrefs`
Inspired by Unity, `PlayerPrefs` are meant for storing and retrieving data locally. Currently, it's just a wrapper for `localStorage`. In the future more adapters might be implemented to handle another storage option.
```typescript
import { PlayerPrefs } from "pixi-engine";
// Key-value usage
PlayerPrefs.set("name", "Player Name");
PlayerPrefs.set("accessToken", "1f92h3f928h39f8h2");
// Object usage
PlayerPrefs.set({
name: "Player Name",
accessToken: "1f92h3f928h39f8h2"
});
// Retrieving data
console.log(PlayerPrefs.get("name"));
```
## License
MIT
| 0 | 0.750218 | 1 | 0.750218 | game-dev | MEDIA | 0.715003 | game-dev | 0.627593 | 1 | 0.627593 |
anathema/anathema_legacy | 1,158 | Hero_Charms/src/main/java/net/sf/anathema/hero/charms/display/tooltip/ScreenDisplayInfoContributor.java | package net.sf.anathema.hero.charms.display.tooltip;
import net.sf.anathema.character.magic.basic.Magic;
import net.sf.anathema.lib.gui.ConfigurableTooltip;
import net.sf.anathema.framework.environment.Resources;
public class ScreenDisplayInfoContributor extends MagicInfoStringBuilder implements MagicTooltipContributor {
private Resources resources;
public ScreenDisplayInfoContributor(Resources resources) {
super(resources, new CostStringBuilder(resources, "CharmTreeView.ToolTip.Mote", "CharmTreeView.ToolTip.Motes"),
new CostStringBuilder(resources, "WillpowerType.Name"),
new HealthCostStringBuilder(resources, "CharmTreeView.ToolTip.HealthLevel", "CharmTreeView.ToolTip.HealthLevels"),
new CostStringBuilder(resources, "CharmTreeView.ToolTip.ExperiencePoint", "CharmTreeView.ToolTip.ExperiencePoints"));
this.resources = resources;
}
@Override
public void buildStringForMagic(ConfigurableTooltip tooltip, Magic magic, Object details) {
String label = resources.getString("CharmTreeView.ToolTip.Cost");
String text = createCostString(magic);
tooltip.appendLine(label, text);
}
} | 0 | 0.699036 | 1 | 0.699036 | game-dev | MEDIA | 0.519982 | game-dev,desktop-app | 0.743095 | 1 | 0.743095 |
thomasgoldstein/zabuyaki | 8,671 | src/state/debugState.lua | debugState = {}
local time = 0
local menuState, oldMenuState = 1, -1
local menuParams = {
center = false, -- override
screenWidth = 640,
screenHeight = 480,
menuItem_h = 25,
menuOffset_y = 80,
menuOffset_x = 80,
hintOffset_y = 80,
leftItemOffset = 6,
topItemOffset = 6,
titleOffset_y = 14,
itemWidthMargin = 12,
itemHeightMargin = 10
}
local menuTitle = love.graphics.newText( gfx.font.kimberley, "DEBUGGING OPTIONS" )
local txtItems = {"DEBUGGING", "SHOW FPC/CONTROLS", "UNIT HITBOX", "DEBUG BOXES", "UNIT INFO", "ENEMY AI", "WAVES", "WALKABLE AREA", "START STAGE", "SPAWN", "BACK"}
local menuItems = {
DEBUGGING_ON = 1, SHOW_DEBUG_FPS_CONTROLS = 2, SHOW_DEBUG_UNIT_HITBOX = 3,
SHOW_DEBUG_BOXES = 4, SHOW_DEBUG_UNIT_INFO = 5, SHOW_DEBUG_ENEMY_AI_INFO = 6,
SHOW_DEBUG_WAVES = 7, SHOW_DEBUG_WALKABLE_AREA = 8, DEBUG_STAGE_MAP = 9,
SPAWN_UNIT = 10, BACK = 11}
local menu = fillMenu(txtItems, nil, menuParams)
local stageMaps = { "stage1-1_map", "stage1-2_map", "stage1-3_map" }
local unitsSpawnList = { "gopper", "niko", "sveta", "zeena", "hooch", "beatnik", "satoff" }
local prevGameState = false
local function loadStageMap()
local stageMap = configuration:get("DEBUG_STAGE_MAP")
menu[menuItems.DEBUG_STAGE_MAP].n = 0
if stageMap then
for i = 1, #stageMaps do
if stageMaps[i] == stageMap then
menu[menuItems.DEBUG_STAGE_MAP].n = i
print("found saved map", stageMap, i)
break
end
end
end
end
loadStageMap()
function debugState:enter(prevState)
prevGameState = prevState -- enable SPAWN and other debug functions only for certain states
if prevGameState ~= pauseState then
bgm.pause()
end
-- Prevent double press at start (e.g. auto confirmation)
Controls[1].attack:update()
Controls[1].jump:update()
Controls[1].start:update()
Controls[1].back:update()
end
function debugState:leave()
if prevGameState ~= pauseState then
bgm.resume()
end
end
function debugState:playerInput(controls)
if controls.jump:pressed() or controls.back:pressed() then
return self:confirm(2)
elseif controls.attack:pressed() or controls.start:pressed() then
return self:confirm(1)
end
if controls.horizontal:pressed(-1)then
self:select(-1)
elseif controls.horizontal:pressed(1)then
self:select(1)
elseif controls.vertical:pressed(-1) then
menuState = menuState - 1
elseif controls.vertical:pressed(1) then
menuState = menuState + 1
end
if menuState < 1 then
menuState = #menu
end
if menuState > #menu then
menuState = 1
end
end
function debugState:update(dt)
time = time + dt
self:playerInput(Controls[1])
if menuState ~= oldMenuState then
sfx.play("sfx","menuMove")
oldMenuState = menuState
end
for i = 1, #menu do
local m = menu[i]
if i == menuItems.DEBUGGING_ON then
m.item = "DEBUGGING " .. (isDebugOption(DEBUGGING_ON) and "ON" or "OFF")
elseif i == menuItems.SHOW_DEBUG_FPS_CONTROLS then
m.item = "FPS/PLAYER CONTROLS " .. (isDebugOption(SHOW_DEBUG_FPS_CONTROLS) and "ON" or "OFF")
elseif i == menuItems.SHOW_DEBUG_UNIT_HITBOX then
m.item = "UNIT HITBOX " .. (isDebugOption(SHOW_DEBUG_UNIT_HITBOX) and "ON" or "OFF")
elseif i == menuItems.SHOW_DEBUG_BOXES then
m.item = "ETC BOXES " .. (isDebugOption(SHOW_DEBUG_BOXES) and "ON" or "OFF")
elseif i == menuItems.SHOW_DEBUG_UNIT_INFO then
m.item = "UNIT INFO/ENEMY CONTROLS " .. (isDebugOption(SHOW_DEBUG_UNIT_INFO) and "ON" or "OFF")
elseif i == menuItems.SHOW_DEBUG_ENEMY_AI_INFO then
m.item = "ENEMY AI INFO " .. (isDebugOption(SHOW_DEBUG_ENEMY_AI_INFO) and "ON" or "OFF")
elseif i == menuItems.SHOW_DEBUG_WAVES then
m.item = "WAVES INFO " .. (isDebugOption(SHOW_DEBUG_WAVES) and "ON" or "OFF")
elseif i == menuItems.SHOW_DEBUG_WALKABLE_AREA then
m.item = "WALKABLE AREA " .. (isDebugOption(SHOW_DEBUG_WALKABLE_AREA) and "ON" or "OFF")
elseif i == menuItems.DEBUG_STAGE_MAP then
if menu[i].n > 0 then
m.item = "START FROM MAP " .. stageMaps[ menu[i].n ]
else
m.item = "START FROM MAP DISABLED"
end
m.hint = "USE <- ->"
elseif i == menuItems.SPAWN_UNIT then
m.item = "SPAWN " .. unitsSpawnList[ menu[i].n ]
m.hint = "Use <- or -> and [A] button ~[CTRL]"
else
m.hint = "Use [J] button to exit"
end
end
end
function debugState:draw()
push:start()
love.graphics.setFont(gfx.font.arcade4)
for i = 1, #menu do
local enableMenuElement = true
if i ~= menuItems.DEBUGGING_ON and i ~= menuItems.BACK and not isDebugOption(DEBUGGING_ON) then
enableMenuElement = false
end
if i == menuItems.SPAWN_UNIT then
enableMenuElement = prevGameState == arcadeState and true or false
end
drawMenuItem(menu, i, oldMenuState, enableMenuElement and "white" or "gray")
end
drawMenuTitle(menu, menuTitle)
showDebugIndicator()
push:finish()
end
function debugState:confirm(button)
if (button == 1 and menuState == #menu) or button == 2 then
sfx.play("sfx","menuCancel")
return Gamestate.pop()
end
if button == 1 then
if menuState == menuItems.DEBUGGING_ON then
invertDebugOption(DEBUGGING_ON)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SHOW_DEBUG_FPS_CONTROLS then
invertDebugOption(SHOW_DEBUG_FPS_CONTROLS)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SHOW_DEBUG_UNIT_HITBOX then
invertDebugOption(SHOW_DEBUG_UNIT_HITBOX)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SHOW_DEBUG_BOXES then
invertDebugOption(SHOW_DEBUG_BOXES)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SHOW_DEBUG_UNIT_INFO then
invertDebugOption(SHOW_DEBUG_UNIT_INFO)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SHOW_DEBUG_ENEMY_AI_INFO then
invertDebugOption(SHOW_DEBUG_ENEMY_AI_INFO)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SHOW_DEBUG_WAVES then
invertDebugOption(SHOW_DEBUG_WAVES)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SHOW_DEBUG_WALKABLE_AREA then
invertDebugOption(SHOW_DEBUG_WALKABLE_AREA)
sfx.play("sfx","menuSelect")
elseif menuState == menuItems.SPAWN_UNIT then
if prevGameState ~= arcadeState then
sfx.play("sfx","menuCancel")
return
end
local p = getRegisteredPlayer(1)
local className = unitsSpawnList[ menu[menuItems.SPAWN_UNIT].n ]
local x, y = p.x - 100 + love.math.random(200), p.y - 50 + love.math.random(100)
y = Stage:clampWalkableAreaY( x, y )
local unit = getUnitTypeByName(className):new("*"..className..(GLOBAL_UNIT_ID + 1),
"src/def/char/"..className, x, y, { palette = love.math.random(1, 4) })
if love.keyboard.isScancodeDown( "lctrl", "rctrl" ) then
unit.AI = AIExperimental:new(unit)
end
GLOBAL_UNIT_ID = GLOBAL_UNIT_ID + 1
unit.z = 100
unit:setOnStage(stage)
unit.face = p.face
unit.horizontal = p.horizontal
unit.isActive = true -- actual spawned enemy unit
unit.target = p
sfx.play("sfx","bodyDrop")
end
end
end
function debugState:select(i)
if menuState == menuItems.DEBUG_STAGE_MAP then
menu[menuState].n = menu[menuState].n + i
if menu[menuState].n > #stageMaps then
menu[menuState].n = 0
end
if menu[menuState].n < 0 then
menu[menuState].n = #stageMaps
end
configuration:set("DEBUG_STAGE_MAP", menu[menuState].n > 0 and stageMaps[menu[menuState].n] or false)
return
end
if menuState == menuItems.SPAWN_UNIT then
menu[menuState].n = menu[menuState].n + i
if menu[menuState].n > #unitsSpawnList then
menu[menuState].n = 1
end
if menu[menuState].n < 1 then
menu[menuState].n = #unitsSpawnList
end
return
end
end
| 0 | 0.876513 | 1 | 0.876513 | game-dev | MEDIA | 0.874684 | game-dev | 0.841104 | 1 | 0.841104 |
openharmony/graphic_graphic_2d | 5,492 | rosen/test/render_service/render_service_base/fuzztest/platform/ohos/rsrenderserviceclient006_fuzzer/rsrenderserviceclient006_fuzzer.cpp | /*
* Copyright (c) 2025 Huawei Device Co., Ltd.
* 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 "rsrenderserviceclient006_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include <securec.h>
#include "transaction/rs_render_service_client.h"
#include "command/rs_command.h"
#include "command/rs_node_showing_command.h"
#include "core/transaction/rs_interfaces.h"
#ifdef OHOS_BUILD_ENABLE_MAGICCURSOR
#include "ipc_callbacks/pointer_render/pointer_luminance_callback_stub.h"
#endif
#include "ipc_callbacks/screen_change_callback_stub.h"
#include "platform/ohos/rs_render_service_connect_hub.h"
namespace OHOS {
namespace Rosen {
namespace {
const uint8_t DO_ADD_VIRTUAL_SCREEN_BLACK_LIST = 0;
const uint8_t DO_REMOVE_VIRTUAL_SCREEN_BLACK_LIST = 1;
const uint8_t DO_SET_SCREEN_POWER_STATUS = 2;
const uint8_t DO_GET_BITMAP = 3;
const uint8_t DO_SET_HWCNODE_BOUNDS = 4;
const uint8_t TARGET_SIZE = 5;
sptr<RSIRenderServiceConnection> CONN = nullptr;
const uint8_t* DATA = nullptr;
size_t g_size = 0;
size_t g_pos;
constexpr uint8_t SET_SCREEN_POWER_STATUS = 11;
template<class T>
T GetData()
{
T object {};
size_t objectSize = sizeof(object);
if (DATA == nullptr || objectSize > g_size - g_pos) {
return object;
}
errno_t ret = memcpy_s(&object, objectSize, DATA + g_pos, objectSize);
if (ret != EOK) {
return {};
}
g_pos += objectSize;
return object;
}
bool Init(const uint8_t* data, size_t size)
{
if (data == nullptr) {
return false;
}
DATA = data;
g_size = size;
g_pos = 0;
return true;
}
} // namespace
class DerivedSyncTask : public RSSyncTask {
public:
using RSSyncTask::RSSyncTask;
bool CheckHeader(Parcel& parcel) const override
{
return true;
}
bool ReadFromParcel(Parcel& parcel) override
{
return true;
}
bool Marshalling(Parcel& parcel) const override
{
return true;
}
void Process(RSContext& context) override {}
};
bool DoAddVirtualScreenBlackList()
{
std::shared_ptr<RSRenderServiceClient> client = std::make_shared<RSRenderServiceClient>();
ScreenId id = GetData<ScreenId>();
std::vector<NodeId> blackListVector;
uint8_t blackListSize = GetData<uint8_t>();
for (auto i = 0; i < blackListSize; i++) {
NodeId nodeId = GetData<NodeId>();
blackListVector.push_back(nodeId);
}
client->AddVirtualScreenBlackList(id, blackListVector);
return true;
}
bool DoRemoveVirtualScreenBlackList()
{
std::shared_ptr<RSRenderServiceClient> client = std::make_shared<RSRenderServiceClient>();
ScreenId id = GetData<ScreenId>();
std::vector<NodeId> blackListVector;
uint8_t blackListSize = GetData<uint8_t>();
for (auto i = 0; i < blackListSize; i++) {
NodeId nodeId = GetData<NodeId>();
blackListVector.push_back(nodeId);
}
client->RemoveVirtualScreenBlackList(id, blackListVector);
return true;
}
bool DoSetScreenPowerStatus()
{
std::shared_ptr<RSRenderServiceClient> client = std::make_shared<RSRenderServiceClient>();
ScreenId id = GetData<ScreenId>();
ScreenPowerStatus status = static_cast<ScreenPowerStatus>(GetData<uint8_t>() % SET_SCREEN_POWER_STATUS);
client->SetScreenPowerStatus(id, status);
return true;
}
bool DoGetBitmap()
{
std::shared_ptr<RSRenderServiceClient> client = std::make_shared<RSRenderServiceClient>();
Drawing::Bitmap bm;
NodeId id = GetData<uint64_t>();
client->GetBitmap(id, bm);
return true;
}
bool DoSetHwcNodeBounds()
{
std::shared_ptr<RSRenderServiceClient> client = std::make_shared<RSRenderServiceClient>();
int64_t rsNodeId = GetData<int64_t>();
float positionX = GetData<float>();
float positionY = GetData<float>();
float positionZ = GetData<float>();
float positionW = GetData<float>();
client->SetHwcNodeBounds(rsNodeId, positionX, positionY, positionZ, positionW);
return true;
}
} // namespace Rosen
} // namespace OHOS
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (!OHOS::Rosen::Init(data, size)) {
return -1;
}
uint8_t tarPos = OHOS::Rosen::GetData<uint8_t>() % OHOS::Rosen::TARGET_SIZE;
switch (tarPos) {
case OHOS::Rosen::DO_ADD_VIRTUAL_SCREEN_BLACK_LIST:
OHOS::Rosen::DoAddVirtualScreenBlackList();
break;
case OHOS::Rosen::DO_REMOVE_VIRTUAL_SCREEN_BLACK_LIST:
OHOS::Rosen::DoRemoveVirtualScreenBlackList();
break;
case OHOS::Rosen::DO_SET_SCREEN_POWER_STATUS:
OHOS::Rosen::DoSetScreenPowerStatus();
break;
case OHOS::Rosen::DO_GET_BITMAP:
OHOS::Rosen::DoGetBitmap();
break;
case OHOS::Rosen::DO_SET_HWCNODE_BOUNDS:
OHOS::Rosen::DoSetHwcNodeBounds();
break;
default:
return -1;
}
return 0;
} | 0 | 0.929108 | 1 | 0.929108 | game-dev | MEDIA | 0.18933 | game-dev | 0.912556 | 1 | 0.912556 |
eliasdaler/edbr | 8,782 | edbr/src/TileMap/TiledImporter.cpp | #include <edbr/TileMap/TiledImporter.h>
#include <edbr/Core/JsonFile.h>
#include <edbr/Graphics/GfxDevice.h>
#include <edbr/TileMap/TileMap.h>
namespace
{
const unsigned FLIPPED_HORIZONTALLY_FLAG = 0x80000000;
const unsigned FLIPPED_VERTICALLY_FLAG = 0x40000000;
const unsigned FLIPPED_DIAGONALLY_FLAG = 0x20000000;
const unsigned ROTATED_HEXAGONAL_120_FLAG = 0x10000000;
}
void TiledImporter::loadLevel(
GfxDevice& gfxDevice,
const std::filesystem::path& path,
TileMap& tileMap)
{
JsonFile file(path);
if (!file.isGood()) {
throw std::runtime_error(fmt::format("failed to load level from {}", path.string()));
}
const auto basePath = path.parent_path();
const auto& loader = file.getLoader();
// load tilesets
for (const auto& tilesetLoader : loader.getLoader("tilesets").getVector()) {
std::uint32_t firstGID;
std::filesystem::path tilesetPath;
tilesetLoader.get("firstgid", firstGID);
tilesetLoader.get("source", tilesetPath);
tilesets.push_back(loadTileset(basePath / tilesetPath, firstGID));
}
assert(!tilesets.empty());
// add tilesets to tilemap
for (std::size_t i = 0; i < tilesets.size(); ++i) {
const auto& tiledTS = tilesets[i];
auto tileset = TileMap::Tileset{
.name = tiledTS.name,
.texture = gfxDevice.loadImageFromFile(tiledTS.imagePath),
.textureSize = tiledTS.imageSize,
};
tileset.animations.reserve(tiledTS.animations.size());
for (const auto& anim : tiledTS.animations) {
assert(!anim.tileIds.empty());
auto& animation = tileset.animations[anim.tileIds[0]];
animation.duration = anim.duration;
animation.tileIds.reserve(animation.tileIds.size());
for (const auto& tid : anim.tileIds) {
animation.tileIds.push_back(static_cast<TileMap::TileId>(tid));
}
}
tileMap.addTileset((TileMap::TilesetId)i, std::move(tileset));
}
// load tile layers
for (const auto& layerLoader : loader.getLoader("layers").getVector()) {
std::string layerType;
layerLoader.get("type", layerType);
if (layerType != "tilelayer") {
continue;
}
std::string layerName;
layerLoader.get("name", layerName);
// get layer Z
int layerZ = 0;
for (const auto& propLoader : layerLoader.getLoader("properties").getVector()) {
std::string propName;
propLoader.get("name", propName);
if (propName == "z") {
propLoader.get("value", layerZ);
break;
}
}
auto& layer = tileMap.addLayer(TileMap::TileMapLayer{
.name = layerName,
.z = layerZ,
});
for (const auto& chunkLoader : layerLoader.getLoader("chunks").getVector()) {
int chunkX, chunkY;
chunkLoader.get("x", chunkX);
chunkLoader.get("y", chunkY);
int chunkWidth;
chunkLoader.get("width", chunkWidth);
assert(chunkWidth != 0);
auto& data = chunkLoader.getLoader("data").getJson();
assert(data.is_array());
for (std::size_t arrIdx = 0; arrIdx < data.size(); ++arrIdx) {
std::uint32_t tileGID = data[arrIdx];
bool flippedHorizontally = (tileGID & FLIPPED_HORIZONTALLY_FLAG);
bool flippedVertically = (tileGID & FLIPPED_VERTICALLY_FLAG);
bool flippedDiagonally = (tileGID & FLIPPED_DIAGONALLY_FLAG);
bool rotatedHex120 = (tileGID & ROTATED_HEXAGONAL_120_FLAG);
// Clear all four flags
tileGID &=
~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG |
FLIPPED_DIAGONALLY_FLAG | ROTATED_HEXAGONAL_120_FLAG);
if (tileGID == 0) {
continue;
}
auto tilesetIdx = findTileset(tileGID);
auto tileID = tileGID - tilesets[tilesetIdx].firstGID;
int chunkLocalX = arrIdx % chunkWidth;
int chunkLocalY = arrIdx / chunkWidth;
int tileX = chunkX + chunkLocalX;
int tileY = chunkY + chunkLocalY;
layer.tiles.emplace(
TileMap::TileIndex{tileX, tileY},
TileMap::Tile{
.id = (TileMap::TileId)tileID,
.tilesetId = (TileMap::TilesetId)tilesetIdx,
});
}
}
}
// TODO: move somewhere else?
tileMap.updateAnimatedTileIndices();
// load object layers
for (const auto& layerLoader : loader.getLoader("layers").getVector()) {
std::string layerType;
layerLoader.get("type", layerType);
if (layerType != "objectgroup") {
continue;
}
for (const auto& objectLoader : layerLoader.getLoader("objects").getVector()) {
TiledObject object;
objectLoader.get("x", object.position.x);
objectLoader.get("y", object.position.y);
objectLoader.get("width", object.size.x);
objectLoader.get("height", object.size.y);
objectLoader.get("name", object.name);
objectLoader.get("type", object.className);
if (objectLoader.hasKey("properties")) {
for (const auto& propLoader : objectLoader.getLoader("properties").getVector()) {
std::string propName;
std::string propType;
propLoader.get("name", propName);
propLoader.get("type", propType);
CustomProperty property{.name = propName};
if (propType == "string") {
std::string value;
propLoader.get("value", value);
property.value = std::move(value);
}
object.customProperties.push_back(std::move(property));
}
}
objects.push_back(std::move(object));
}
}
}
TiledImporter::TiledTileset TiledImporter::loadTileset(
const std::filesystem::path& path,
std::uint32_t firstGID)
{
const auto basePath = path.parent_path();
JsonFile file(path);
if (!file.isGood()) {
throw std::runtime_error(fmt::format("failed to load level from {}", path.string()));
}
const auto& loader = file.getLoader();
std::string name;
std::filesystem::path tilesetPath;
int imageWidth, imageHeight;
loader.get("name", name);
loader.get("image", tilesetPath);
loader.get("imagewidth", imageWidth);
loader.get("imageheight", imageHeight);
auto tileset = TiledTileset{
.name = name,
.firstGID = firstGID,
.imagePath = basePath / tilesetPath,
.imageSize = {imageWidth, imageHeight},
};
if (loader.hasKey("tiles")) {
const auto tileAnimLoaders = loader.getLoader("tiles").getVector();
tileset.animations.reserve(tileAnimLoaders.size());
for (const auto& tileAnimLoader : tileAnimLoaders) {
std::uint32_t firstTileId{0};
tileAnimLoader.get("id", firstTileId);
TiledTileset::TileAnimation animation{};
const auto frameLoaders = tileAnimLoader.getLoader("animation").getVector();
animation.tileIds.reserve(frameLoaders.size());
for (const auto& frameLoader : frameLoaders) {
float duration{};
frameLoader.get("duration", duration);
duration /= 1000; // from ms to seconds
std::uint32_t tileId;
frameLoader.get("tileid", tileId);
if (animation.duration == 0) {
animation.duration = duration;
assert(tileId == firstTileId && "first 'tileid' should be equal to 'id'");
} else {
assert(
duration == animation.duration &&
"tile animation should have constant frame duration");
}
animation.tileIds.push_back(tileId);
}
tileset.animations.push_back(std::move(animation));
}
}
return tileset;
}
std::size_t TiledImporter::findTileset(const std::uint32_t tileGID) const
{
assert(!tilesets.empty());
for (int i = static_cast<int>(tilesets.size()) - 1; i >= 0; --i) {
const auto& tileset = tilesets[i];
if (tileset.firstGID <= tileGID) {
return i;
}
}
assert(false);
return 0;
}
| 0 | 0.924399 | 1 | 0.924399 | game-dev | MEDIA | 0.774547 | game-dev,graphics-rendering | 0.961891 | 1 | 0.961891 |
Monkestation/Monkestation2.0 | 2,072 | code/datums/components/connect_mob_behalf.dm | /// This component behaves similar to connect_loc_behalf, but working off clients and mobs instead of loc
/// To be clear, we hook into a signal on a tracked client's mob
/// We retain the ability to react to that signal on a seperate listener, which makes this quite powerful
/datum/component/connect_mob_behalf
dupe_mode = COMPONENT_DUPE_UNIQUE
/// An assoc list of signal -> procpath to register to the mob our client "owns"
var/list/connections
/// The master client we're working with
var/client/tracked
/// The mob we're currently tracking
var/mob/tracked_mob
/datum/component/connect_mob_behalf/Initialize(client/tracked, list/connections)
. = ..()
if (!istype(tracked))
return COMPONENT_INCOMPATIBLE
src.connections = connections
src.tracked = tracked
/datum/component/connect_mob_behalf/RegisterWithParent()
RegisterSignal(tracked, COMSIG_QDELETING, PROC_REF(handle_tracked_qdel))
update_signals()
/datum/component/connect_mob_behalf/UnregisterFromParent()
unregister_signals()
UnregisterSignal(tracked, COMSIG_QDELETING)
tracked = null
tracked_mob = null
/datum/component/connect_mob_behalf/proc/handle_tracked_qdel()
SIGNAL_HANDLER
qdel(src)
/datum/component/connect_mob_behalf/proc/update_signals()
unregister_signals()
// Yes this is a runtime silencer
// We could be in a position where logout is sent to two things, one thing intercepts it, then deletes the client's new mob
// It's rare, and the same check in connect_loc_behalf is more fruitful, but it's still worth doing
if(QDELETED(tracked?.mob))
return
tracked_mob = tracked.mob
RegisterSignal(tracked_mob, COMSIG_MOB_LOGOUT, PROC_REF(on_logout))
for (var/signal in connections)
parent.RegisterSignal(tracked_mob, signal, connections[signal])
/datum/component/connect_mob_behalf/proc/unregister_signals()
if(isnull(tracked_mob))
return
parent.UnregisterSignal(tracked_mob, connections)
UnregisterSignal(tracked_mob, COMSIG_MOB_LOGOUT)
tracked_mob = null
/datum/component/connect_mob_behalf/proc/on_logout(mob/source)
SIGNAL_HANDLER
update_signals()
| 0 | 0.951355 | 1 | 0.951355 | game-dev | MEDIA | 0.561244 | game-dev,networking | 0.977943 | 1 | 0.977943 |
RE-SS3D/SS3D | 2,461 | Assets/Scripts/External/Discord/Plugins/DiscordGameSDK/Editor/ExtendedEditorWindow.cs | #if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
public class ExtendedEditorWindow : EditorWindow
{
protected SerializedObject serializedObject;
protected SerializedProperty currentProperty;
private string selectedPropertyPath;
protected SerializedProperty SelectedProperty;
protected void DrawProperties(SerializedProperty prop , bool drawChildren)
{
string LastPropPath = string.Empty;
foreach (SerializedProperty p in prop)
{
if(p.isArray && p.propertyType == SerializedPropertyType.Generic)
{
EditorGUILayout.BeginHorizontal();
p.isExpanded = EditorGUILayout.Foldout(p.isExpanded , p.displayName);
EditorGUILayout.EndHorizontal();
if(p.isExpanded)
{
EditorGUI.indentLevel++;
DrawProperties(p,drawChildren);
EditorGUI.indentLevel--;
}
}
else
{
if(!string.IsNullOrEmpty(LastPropPath) && p.propertyPath.Contains(LastPropPath)) { continue; }
LastPropPath = p.propertyPath;
EditorGUILayout.PropertyField(p, drawChildren);
}
}
}
protected void DrawSideBar(SerializedProperty prop)
{
foreach (SerializedProperty p in prop)
{
if(GUILayout.Button(p.displayName))
{
selectedPropertyPath = p.propertyPath;
}
}
if(!string.IsNullOrEmpty(selectedPropertyPath))
{
SelectedProperty = serializedObject.FindProperty(selectedPropertyPath);
}
if(GUILayout.Button("Add"))
{
Debug.Log("Added character");
}
}
protected void DrawField(string propName , bool relative )
{
if(relative && currentProperty != null)
{
EditorGUILayout.PropertyField(currentProperty.FindPropertyRelative(propName) , true);
}
else if(!relative && serializedObject != null)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty(propName) , true);
}
}
protected void DrawProp(string _propName)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty(_propName) , true);
}
protected void ApplyChanges()
{
serializedObject.ApplyModifiedProperties();
}
}
#endif | 0 | 0.854354 | 1 | 0.854354 | game-dev | MEDIA | 0.930814 | game-dev | 0.94525 | 1 | 0.94525 |
A3Antistasi/A3-Antistasi | 2,703 | A3-Antistasi/Revive/handleDamageAAF.sqf | private ["_unit","_part","_dam","_injurer","_grupo"];
_dam = _this select 2;
_injurer = _this select 3;
if (side _injurer == buenos) then
{
_unit = _this select 0;
_part = _this select 1;
_grupo = group _unit;
if (time > _grupo getVariable ["movedToCover",0]) then
{
if ((behaviour leader _grupo != "COMBAT") and (behaviour leader _grupo != "STEALTH")) then
{
_grupo setVariable ["movedToCover",time + 120];
{[_x,_injurer] call A3A_fnc_unitGetToCover} forEach units _grupo;
};
};
if (_part == "") then
{
if (_dam >= 1) then
{
if (!(_unit getVariable ["INCAPACITATED",false])) then
{
_unit setVariable ["INCAPACITATED",true,true];
_unit setUnconscious true;
_dam = 0.9;
[_unit,_injurer] spawn A3A_fnc_inconscienteAAF;
}
else
{
_overall = (_unit getVariable ["overallDamage",0]) + (_dam - 1);
if (_overall > 0.5) then
{
_unit removeAllEventHandlers "HandleDamage";
}
else
{
_unit setVariable ["overallDamage",_overall];
_dam = 0.9;
};
};
}
else
{
if (_dam > 0.25) then
{
if (_unit getVariable ["ayudando",false]) then
{
_unit setVariable ["cancelRevive",true];
};
};
if (_dam > 0.6) then {[_unit,_injurer] spawn A3A_fnc_unitGetToCover};
};
}
else
{
if (_dam >= 1) then
{
if !(_part in ["arms","hands","legs"]) then
{
_dam = 0.9;
if (_part == "head") then
{
if (getNumber (configfile >> "CfgWeapons" >> headgear _unit >> "ItemInfo" >> "HitpointsProtectionInfo" >> "Head" >> "armor") > 0) then
{
removeHeadgear _unit;
}
else
{
if !(_unit getVariable ["INCAPACITATED",false]) then
{
_unit setVariable ["INCAPACITATED",true,true];
_unit setUnconscious true;
if (vehicle _unit != _unit) then
{
//_unit action ["getOut", vehicle _unit];
moveOut _unit;
};
if (isPlayer _unit) then {_unit allowDamage false};
if (!isNull _injurer) then {[_unit,_injurer] spawn A3A_fnc_inconscienteAAF} else {[_unit,objNull] spawn A3A_fnc_inconscienteAAF};
};
};
}
else
{
if (_part == "body") then
{
if !(_unit getVariable ["INCAPACITATED",false]) then
{
_unit setVariable ["INCAPACITATED",true,true];
_unit setUnconscious true;
if (vehicle _unit != _unit) then
{
moveOut _unit;
};
if (isPlayer _unit) then {_unit allowDamage false};
if (!isNull _injurer) then {[_unit,_injurer] spawn A3A_fnc_inconscienteAAF} else {[_unit,objNull] spawn A3A_fnc_inconscienteAAF};
};
};
};
};
};
};
};
_dam | 0 | 0.964821 | 1 | 0.964821 | game-dev | MEDIA | 0.930142 | game-dev | 0.932334 | 1 | 0.932334 |
geosolutions-it/MapStore2 | 4,686 | web/client/reducers/__tests__/controls-test.js | /**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import expect from 'expect';
import controls from '../controls';
import {
TOGGLE_CONTROL,
SET_CONTROL_PROPERTY,
SET_CONTROL_PROPERTIES,
RESET_CONTROLS
} from '../../actions/controls';
import {IDENTIFY_IS_MOUNTED} from "../../actions/mapInfo";
describe('Test the controls reducer', () => {
it('default case', () => {
const state = controls({
mycontrol: {
enabled: true
}
}, {});
expect(state.mycontrol).toExist();
expect(state.mycontrol.enabled).toBe(true);
});
it('toggles a control the first time', () => {
const state = controls({}, {
type: TOGGLE_CONTROL,
control: 'mycontrol'
});
expect(state.mycontrol).toExist();
expect(state.mycontrol.enabled).toBe(true);
});
it('toggles a control already initialized', () => {
const state = controls({
mycontrol: {
enabled: true
}
}, {
type: TOGGLE_CONTROL,
control: 'mycontrol'
});
expect(state.mycontrol).toExist();
expect(state.mycontrol.enabled).toBe(false);
});
it('toggles a control using custom property', () => {
const state = controls({
mycontrol: {
custom: false
}
}, {
type: TOGGLE_CONTROL,
control: 'mycontrol',
property: 'custom'
});
expect(state.mycontrol).toExist();
expect(state.mycontrol.custom).toBe(true);
});
it('set a control property', () => {
const state = controls({}, {
type: SET_CONTROL_PROPERTY,
control: 'mycontrol',
property: 'prop',
value: 'val'
});
expect(state.mycontrol).toExist();
expect(state.mycontrol.prop).toBe('val');
});
it('set a control property with toggle', () => {
const state = controls({
mycontrol: {
enabled: true,
prop: "val"
}
}, {
type: SET_CONTROL_PROPERTY,
control: 'mycontrol',
property: 'prop',
value: 'val',
toggle: true
});
expect(state.mycontrol).toExist();
expect(state.mycontrol.prop).toBe(undefined);
});
it('set a list of control properties', () => {
const state = controls({}, {
type: SET_CONTROL_PROPERTIES,
control: 'mycontrol',
properties: {
'prop1': 'val1',
'prop2': 'val2'
}
});
expect(state.mycontrol).toExist();
expect(state.mycontrol.prop1).toBe('val1');
expect(state.mycontrol.prop2).toBe('val2');
});
it('reset the controls without skip ', () => {
const state = controls(
{
c1: { enabled: true},
c2: { enabled: false},
c3: { idonthaveenabledfield: "whatever"}
}, {
type: RESET_CONTROLS,
skip: []
});
expect(state.c1).toExist();
expect(state.c2).toExist();
expect(state.c3).toExist();
expect(state.c1.enabled).toBe(false);
expect(state.c2.enabled).toBe(false);
expect(state.c3.enabled).toNotExist();
expect(state.c3.idonthaveenabledfield).toExist();
expect(state.c3.idonthaveenabledfield).toBe("whatever");
});
it('reset the controls with skip c1,c3', () => {
const state = controls(
{
c1: { enabled: true},
c2: { enabled: true},
c3: { idonthaveenabledfield: "whatever"}
}, {
type: RESET_CONTROLS,
skip: ["c1", "c3"]
});
expect(state.c1).toExist();
expect(state.c2).toExist();
expect(state.c3).toExist();
expect(state.c1.enabled).toBe(true);
expect(state.c2.enabled).toBe(false);
expect(state.c3.enabled).toNotExist();
expect(state.c3.idonthaveenabledfield).toExist();
expect(state.c3.idonthaveenabledfield).toBe("whatever");
});
it('controls reducer: IDENTIFY_IS_MOUNTED', () => {
const initialState = {};
expect(controls(initialState, {
type: IDENTIFY_IS_MOUNTED,
isMounted: true
})).toEqual({info: { available: true}});
});
});
| 0 | 0.841894 | 1 | 0.841894 | game-dev | MEDIA | 0.473605 | game-dev,desktop-app | 0.758322 | 1 | 0.758322 |
tgstation/tgstation | 2,405 | code/modules/events/market_crash.dm | /**
* An event which decreases the station target temporarily, causing the inflation var to increase heavily.
*
* Done by decreasing the station_target by a high value per crew member, resulting in the station total being much higher than the target, and causing artificial inflation.
*/
/datum/round_event_control/market_crash
name = "Market Crash"
typepath = /datum/round_event/market_crash
weight = 10
category = EVENT_CATEGORY_BUREAUCRATIC
description = "Temporarily increases the prices of vending machines."
/datum/round_event/market_crash
/// This counts the number of ticks that the market crash event has been processing, so that we don't call vendor price updates every tick, but we still iterate for other mechanics that use inflation.
var/tick_counter = 1
/datum/round_event/market_crash/setup()
start_when = 1
end_when = rand(100, 50)
announce_when = 2
/datum/round_event/market_crash/announce(fake)
var/list/poss_reasons = list("the alignment of the moon and the sun",\
"some risky housing market outcomes",\
"the B.E.P.I.S. team's untimely downfall",\
"speculative Terragov grants backfiring",\
"greatly exaggerated reports of Nanotrasen accountancy personnel being \"laid off\"",\
"a \"great investment\" into \"non-fungible tokens\" by a \"moron\"",\
"a number of raids from Tiger Cooperative agents",\
"supply chain shortages",\
"the \"Nanotrasen+\" social media network's untimely downfall",\
"the \"Nanotrasen+\" social media network's unfortunate success",\
"uhh, bad luck, we guess"
)
var/reason = pick(poss_reasons)
priority_announce("Due to [reason], prices for on-station vendors will be increased for a short period.", "Nanotrasen Accounting Division")
/datum/round_event/market_crash/start()
. = ..()
SSeconomy.update_vending_prices()
SSeconomy.price_update()
ADD_TRAIT(SSeconomy, TRAIT_MARKET_CRASHING, MARKET_CRASH_EVENT_TRAIT)
/datum/round_event/market_crash/end()
. = ..()
REMOVE_TRAIT(SSeconomy, TRAIT_MARKET_CRASHING, MARKET_CRASH_EVENT_TRAIT)
SSeconomy.price_update()
SSeconomy.update_vending_prices()
priority_announce("Prices for on-station vendors have now stabilized.", "Nanotrasen Accounting Division")
/datum/round_event/market_crash/tick()
. = ..()
tick_counter = tick_counter++
SSeconomy.inflation_value = 5.5*(log(activeFor+1))
if(tick_counter == 5)
tick_counter = 1
SSeconomy.update_vending_prices()
| 0 | 0.747205 | 1 | 0.747205 | game-dev | MEDIA | 0.976806 | game-dev | 0.964634 | 1 | 0.964634 |
Gaby-Station/Gaby-Station | 3,337 | Content.Server/GameTicking/Rules/RoundstartStationVariationRuleSystem.cs | // SPDX-FileCopyrightText: 2024 Kara <lunarautomaton6@gmail.com>
// SPDX-FileCopyrightText: 2024 Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Piras314 <p1r4s@proton.me>
// SPDX-FileCopyrightText: 2024 deltanedas <39013340+deltanedas@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 deltanedas <@deltanedas:kde.org>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Server.GameTicking.Rules.Components;
using Content.Server.Shuttles.Systems;
using Content.Server.Station.Components;
using Content.Server.Station.Events;
using Content.Shared.GameTicking.Components;
using Content.Shared.Storage;
using Robust.Shared.Random;
namespace Content.Server.GameTicking.Rules;
/// <inheritdoc cref="RoundstartStationVariationRuleComponent"/>
public sealed class RoundstartStationVariationRuleSystem : GameRuleSystem<RoundstartStationVariationRuleComponent>
{
[Dependency] private readonly IRobustRandom _random = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<StationPostInitEvent>(OnStationPostInit, after: new []{typeof(ShuttleSystem)});
}
protected override void Added(EntityUid uid, RoundstartStationVariationRuleComponent component, GameRuleComponent gameRule, GameRuleAddedEvent args)
{
var spawns = EntitySpawnCollection.GetSpawns(component.Rules, _random);
foreach (var rule in spawns)
{
GameTicker.AddGameRule(rule);
}
}
private void OnStationPostInit(ref StationPostInitEvent ev)
{
// as long as one is running
if (!GameTicker.IsGameRuleAdded<RoundstartStationVariationRuleComponent>())
return;
// this is unlikely, but could theoretically happen if it was saved and reloaded, so check anyway
if (HasComp<StationVariationHasRunComponent>(ev.Station))
return;
Log.Info($"Running variation rules for station {ToPrettyString(ev.Station)}");
// raise the event on any passes that have been added
var passEv = new StationVariationPassEvent(ev.Station);
var passQuery = EntityQueryEnumerator<StationVariationPassRuleComponent, GameRuleComponent>();
while (passQuery.MoveNext(out var uid, out _, out _))
{
// TODO: for some reason, ending a game rule just gives it a marker comp,
// and doesnt delete it
// so we have to check here that it isnt an ended game rule (which could happen if a preset failed to start
// or it was ended before station maps spawned etc etc etc)
if (HasComp<EndedGameRuleComponent>(uid))
continue;
RaiseLocalEvent(uid, ref passEv);
}
EnsureComp<StationVariationHasRunComponent>(ev.Station);
}
}
/// <summary>
/// Raised directed on game rule entities which are added and marked as <see cref="StationVariationPassRuleComponent"/>
/// when a new station is initialized that should be varied.
/// </summary>
/// <param name="Station">The new station that was added, and its config & grids.</param>
[ByRefEvent]
public readonly record struct StationVariationPassEvent(Entity<StationDataComponent> Station); | 0 | 0.913525 | 1 | 0.913525 | game-dev | MEDIA | 0.867257 | game-dev | 0.888275 | 1 | 0.888275 |
ShuangYu1145/Faiths-Fix | 8,763 | src/main/java/net/minecraft/util/ChatComponentTranslation.java | package net.minecraft.util;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.IllegalFormatException;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChatComponentTranslation extends ChatComponentStyle
{
private final String key;
private final Object[] formatArgs;
private final Object syncLock = new Object();
private long lastTranslationUpdateTimeInMilliseconds = -1L;
List<IChatComponent> children = Lists.<IChatComponent>newArrayList();
public static final Pattern stringVariablePattern = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)");
public ChatComponentTranslation(String translationKey, Object... args)
{
this.key = translationKey;
this.formatArgs = args;
for (Object object : args)
{
if (object instanceof IChatComponent)
{
((IChatComponent)object).getChatStyle().setParentStyle(this.getChatStyle());
}
}
}
/**
* ensures that our children are initialized from the most recent string translation mapping.
*/
synchronized void ensureInitialized()
{
synchronized (this.syncLock)
{
long i = StatCollector.getLastTranslationUpdateTimeInMilliseconds();
if (i == this.lastTranslationUpdateTimeInMilliseconds)
{
return;
}
this.lastTranslationUpdateTimeInMilliseconds = i;
this.children.clear();
}
try
{
this.initializeFromFormat(StatCollector.translateToLocal(this.key));
}
catch (ChatComponentTranslationFormatException chatcomponenttranslationformatexception)
{
this.children.clear();
try
{
this.initializeFromFormat(StatCollector.translateToFallback(this.key));
}
catch (ChatComponentTranslationFormatException var5)
{
throw chatcomponenttranslationformatexception;
}
}
}
/**
* initializes our children from a format string, using the format args to fill in the placeholder variables.
*/
protected void initializeFromFormat(String format)
{
boolean flag = false;
Matcher matcher = stringVariablePattern.matcher(format);
int i = 0;
int j = 0;
try
{
int l;
for (; matcher.find(j); j = l)
{
int k = matcher.start();
l = matcher.end();
if (k > j)
{
ChatComponentText chatcomponenttext = new ChatComponentText(String.format(format.substring(j, k), new Object[0]));
chatcomponenttext.getChatStyle().setParentStyle(this.getChatStyle());
this.children.add(chatcomponenttext);
}
String s2 = matcher.group(2);
String s = format.substring(k, l);
if ("%".equals(s2) && "%%".equals(s))
{
ChatComponentText chatcomponenttext2 = new ChatComponentText("%");
chatcomponenttext2.getChatStyle().setParentStyle(this.getChatStyle());
this.children.add(chatcomponenttext2);
}
else
{
if (!"s".equals(s2))
{
throw new ChatComponentTranslationFormatException(this, "Unsupported format: \'" + s + "\'");
}
String s1 = matcher.group(1);
int i1 = s1 != null ? Integer.parseInt(s1) - 1 : i++;
if (i1 < this.formatArgs.length)
{
this.children.add(this.getFormatArgumentAsComponent(i1));
}
}
}
if (j < format.length())
{
ChatComponentText chatcomponenttext1 = new ChatComponentText(String.format(format.substring(j), new Object[0]));
chatcomponenttext1.getChatStyle().setParentStyle(this.getChatStyle());
this.children.add(chatcomponenttext1);
}
}
catch (IllegalFormatException illegalformatexception)
{
throw new ChatComponentTranslationFormatException(this, illegalformatexception);
}
}
private IChatComponent getFormatArgumentAsComponent(int index)
{
if (index >= this.formatArgs.length)
{
throw new ChatComponentTranslationFormatException(this, index);
}
else
{
Object object = this.formatArgs[index];
IChatComponent ichatcomponent;
if (object instanceof IChatComponent)
{
ichatcomponent = (IChatComponent)object;
}
else
{
ichatcomponent = new ChatComponentText(object == null ? "null" : object.toString());
ichatcomponent.getChatStyle().setParentStyle(this.getChatStyle());
}
return ichatcomponent;
}
}
public IChatComponent setChatStyle(ChatStyle style)
{
super.setChatStyle(style);
for (Object object : this.formatArgs)
{
if (object instanceof IChatComponent)
{
((IChatComponent)object).getChatStyle().setParentStyle(this.getChatStyle());
}
}
if (this.lastTranslationUpdateTimeInMilliseconds > -1L)
{
for (IChatComponent ichatcomponent : this.children)
{
ichatcomponent.getChatStyle().setParentStyle(style);
}
}
return this;
}
public Iterator<IChatComponent> iterator()
{
this.ensureInitialized();
return Iterators.<IChatComponent>concat(createDeepCopyIterator(this.children), createDeepCopyIterator(this.siblings));
}
/**
* Gets the text of this component, without any special formatting codes added, for chat. TODO: why is this two
* different methods?
*/
public String getUnformattedTextForChat()
{
this.ensureInitialized();
StringBuilder stringbuilder = new StringBuilder();
for (IChatComponent ichatcomponent : this.children)
{
stringbuilder.append(ichatcomponent.getUnformattedTextForChat());
}
return stringbuilder.toString();
}
/**
* Creates a copy of this component. Almost a deep copy, except the style is shallow-copied.
*/
public ChatComponentTranslation createCopy()
{
Object[] aobject = new Object[this.formatArgs.length];
for (int i = 0; i < this.formatArgs.length; ++i)
{
if (this.formatArgs[i] instanceof IChatComponent)
{
aobject[i] = ((IChatComponent)this.formatArgs[i]).createCopy();
}
else
{
aobject[i] = this.formatArgs[i];
}
}
ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(this.key, aobject);
chatcomponenttranslation.setChatStyle(this.getChatStyle().createShallowCopy());
for (IChatComponent ichatcomponent : this.getSiblings())
{
chatcomponenttranslation.appendSibling(ichatcomponent.createCopy());
}
return chatcomponenttranslation;
}
public boolean equals(Object p_equals_1_)
{
if (this == p_equals_1_)
{
return true;
}
else if (!(p_equals_1_ instanceof ChatComponentTranslation))
{
return false;
}
else
{
ChatComponentTranslation chatcomponenttranslation = (ChatComponentTranslation)p_equals_1_;
return Arrays.equals(this.formatArgs, chatcomponenttranslation.formatArgs) && this.key.equals(chatcomponenttranslation.key) && super.equals(p_equals_1_);
}
}
public int hashCode()
{
int i = super.hashCode();
i = 31 * i + this.key.hashCode();
i = 31 * i + Arrays.hashCode(this.formatArgs);
return i;
}
public String toString()
{
return "TranslatableComponent{key=\'" + this.key + '\'' + ", args=" + Arrays.toString(this.formatArgs) + ", siblings=" + this.siblings + ", style=" + this.getChatStyle() + '}';
}
public String getKey()
{
return this.key;
}
public Object[] getFormatArgs()
{
return this.formatArgs;
}
}
| 0 | 0.74556 | 1 | 0.74556 | game-dev | MEDIA | 0.283577 | game-dev | 0.770316 | 1 | 0.770316 |
randovania/randovania | 12,961 | randovania/layout/game_patches_serializer.py | from __future__ import annotations
import dataclasses
import typing
from randovania.game_description import default_database
from randovania.game_description.assignment import PickupAssignment, PickupTarget
from randovania.game_description.db.dock_node import DockNode
from randovania.game_description.db.node_identifier import NodeIdentifier
from randovania.game_description.db.pickup_node import PickupNode
from randovania.game_description.game_patches import GamePatches, StartingEquipment
from randovania.game_description.hint import BaseHint
from randovania.game_description.resources.pickup_index import PickupIndex
from randovania.game_description.resources.resource_collection import ResourceCollection
from randovania.game_description.resources.search import find_resource_info_with_long_name
from randovania.generator.pickup_pool import PoolResults, pool_creator
from randovania.layout import filtered_database
if typing.TYPE_CHECKING:
from randovania.game_description.db.area import Area
from randovania.game_description.db.node import Node
from randovania.game_description.db.region_list import RegionList
from randovania.game_description.game_description import GameDescription
from randovania.game_description.pickup.pickup_database import PickupDatabase
from randovania.game_description.pickup.pickup_entry import PickupEntry
from randovania.layout.base.base_configuration import BaseConfiguration
_NOTHING_PICKUP_NAME = "Nothing"
def _pickup_assignment_to_pickup_locations(
region_list: RegionList,
pickup_assignment: PickupAssignment,
current_world: int,
num_worlds: int,
) -> list[dict]:
pickup_locations = []
for region, area, node in region_list.all_regions_areas_nodes:
if not node.is_resource_node or not isinstance(node, PickupNode):
continue
if node.pickup_index in pickup_assignment:
target = pickup_assignment[node.pickup_index]
item_name = target.pickup.name
if num_worlds > 1:
target_world = target.player
else:
target_world = 0
else:
item_name = _NOTHING_PICKUP_NAME
target_world = current_world
pickup_locations.append(
{
"node_identifier": node.identifier.as_json,
"index": node.pickup_index.index,
"pickup": item_name,
"owner": target_world,
}
)
return sorted(
pickup_locations,
key=lambda d: (
d["node_identifier"]["region"],
f"{d['node_identifier']['area']}/{d['node_identifier']['node']}",
),
)
def _find_area_with_teleporter(region_list: RegionList, teleporter: NodeIdentifier) -> Area:
return region_list.area_by_area_location(teleporter.area_identifier)
def serialize_single(world_index: int, num_worlds: int, patches: GamePatches) -> dict:
"""
Encodes a given GamePatches into a JSON-serializable dict.
:param world_index:
:param num_worlds:
:param patches:
:return:
"""
game = filtered_database.game_description_for_layout(patches.configuration)
region_list = game.region_list
dock_weakness_to_type = {}
for dock_type, weaknesses in game.dock_weakness_database.weaknesses.items():
for weakness in weaknesses.values():
dock_weakness_to_type[weakness] = dock_type
equipment_value: dict | list
if isinstance(patches.starting_equipment, ResourceCollection):
equipment_name = "items"
equipment_value = {
resource_info.long_name: quantity
for resource_info, quantity in patches.starting_equipment.as_resource_gain()
}
else:
equipment_name = "pickups"
equipment_value = [pickup.name for pickup in patches.starting_equipment]
result: dict = {
# This field helps schema migrations, if nothing else
"game": patches.configuration.game.value,
"starting_equipment": {
equipment_name: equipment_value,
},
"starting_location": patches.starting_location.as_string,
"dock_connections": {
dock.identifier.as_string: target.identifier.as_string for dock, target in patches.all_dock_connections()
},
"dock_weakness": {
dock.identifier.as_string: {
"type": dock_weakness_to_type[weakness].short_name,
"name": weakness.name,
}
for dock, weakness in patches.all_dock_weaknesses()
},
"locations": _pickup_assignment_to_pickup_locations(
region_list, patches.pickup_assignment, world_index, num_worlds
),
"hints": {identifier.as_string: hint.as_json for identifier, hint in patches.hints.items()},
"game_specific": patches.game_specific,
}
if patches.custom_patcher_data:
result["custom_patcher_data"] = patches.custom_patcher_data
return result
def _find_pickup_with_name(item_pool: list[PickupEntry], pickup_name: str) -> PickupEntry:
for pickup in item_pool:
if pickup.name == pickup_name:
return pickup
names = {pickup.name for pickup in item_pool}
raise ValueError(f"Unable to find a pickup with name {pickup_name}. Possible values: {sorted(names)}")
def _get_pickup_from_pool(pickup_list: list[PickupEntry], name: str) -> PickupEntry:
pickup = _find_pickup_with_name(pickup_list, name)
pickup_list.remove(pickup)
return pickup
def _decode_pickup_assignment(
player_index: int,
all_pools: dict[int, PoolResults],
region_list: RegionList,
locations: dict,
) -> PickupAssignment:
"""Decodes the `locations` key."""
pickup_assignment: PickupAssignment = {}
initial_pickup_assignment = all_pools[player_index].assignment
for location in locations:
pickup_name = location["pickup"]
if pickup_name == _NOTHING_PICKUP_NAME:
continue
target_world = location["owner"]
pickup_index = PickupIndex(location["index"])
node = region_list.node_from_pickup_index(pickup_index)
if node.identifier.as_json != location["node_identifier"]:
raise ValueError(
f"The location {node.identifier.as_string} is specified to have "
f"index {pickup_index} but it should instead be index {node.pickup_index}."
)
pickup: PickupEntry | None
if pickup_index in initial_pickup_assignment:
pickup = initial_pickup_assignment[pickup_index]
if (pickup_name, target_world) != (pickup.name, player_index):
raise ValueError(f"{node.identifier.as_string} should be vanilla based on configuration")
elif pickup_name != _NOTHING_PICKUP_NAME:
pickup = _get_pickup_from_pool(all_pools[target_world].to_place, pickup_name)
else:
pickup = None
if pickup is not None:
if pickup_index in pickup_assignment:
raise ValueError(f"Duplicate entries for pickup index {pickup_index.index}.")
pickup_assignment[pickup_index] = PickupTarget(pickup, target_world)
return pickup_assignment
def decode_single(
player_index: int,
all_pools: dict[int, PoolResults],
game: GameDescription,
game_modifications: dict,
configuration: BaseConfiguration,
all_games: dict[int, GameDescription],
) -> GamePatches:
"""
Decodes a dict created by `serialize` back into a GamePatches.
:param player_index:
:param all_pools:
:param game:
:param game_modifications:
:param configuration:
:param all_games:
:return:
"""
region_list = game.region_list
weakness_db = game.dock_weakness_database
if game_modifications["game"] != game.game.value:
raise ValueError(f"Expected '{game.game.value}', got '{game_modifications['game']}'")
if "custom_patcher_data" in game_modifications:
custom_patcher_data = game_modifications["custom_patcher_data"]
else:
custom_patcher_data = []
game_specific = game_modifications["game_specific"]
# Starting Location
starting_location = NodeIdentifier.from_string(game_modifications["starting_location"])
# Starting Equipment
starting_equipment: StartingEquipment
if "items" in game_modifications["starting_equipment"]:
starting_equipment = ResourceCollection.from_dict(
game,
{
find_resource_info_with_long_name(game.resource_database.item, resource_name): quantity
for resource_name, quantity in game_modifications["starting_equipment"]["items"].items()
},
)
else:
player_pool = all_pools[player_index]
starting_equipment = []
for starting in game_modifications["starting_equipment"]["pickups"]:
try:
pickup = _get_pickup_from_pool(player_pool.starting, starting)
except ValueError:
pickup = _get_pickup_from_pool(player_pool.to_place, starting)
starting_equipment.append(pickup)
# Dock Connection
def get_dock_source(ni: NodeIdentifier) -> DockNode:
return game.region_list.typed_node_by_identifier(ni, DockNode)
def get_dock_target(ni: NodeIdentifier) -> Node:
return game.region_list.node_by_identifier(ni)
dock_connections = [
(
get_dock_source(NodeIdentifier.from_string(source_name)),
get_dock_target(NodeIdentifier.from_string(target_name)),
)
for source_name, target_name in game_modifications["dock_connections"].items()
]
# Dock Weakness
dock_weakness = [
(
get_dock_source(NodeIdentifier.from_string(source_name)),
weakness_db.get_by_weakness(
weakness_data["type"],
weakness_data["name"],
),
)
for source_name, weakness_data in game_modifications["dock_weakness"].items()
]
# Pickups
pickup_assignment = _decode_pickup_assignment(
player_index,
all_pools,
region_list,
game_modifications["locations"],
)
# Hints
hints = {}
for identifier_str, hint in game_modifications["hints"].items():
extra: dict = {}
if hint["hint_type"] == "location":
pickup_db = default_database.pickup_database_for_game(game.game)
def get_target_pickup_db(target: PickupTarget) -> PickupDatabase:
target_game = all_games[target.player]
target_pickup_db = default_database.pickup_database_for_game(target_game.game)
return target_pickup_db
if (relative := hint["precision"].get("relative")) is not None:
if "other_index" in relative:
other_target = pickup_assignment.get(PickupIndex(relative["other_index"]))
if other_target is not None:
extra["other_pickup_db"] = get_target_pickup_db(other_target)
else:
extra["other_pickup_db"] = pickup_db
extra["game"] = game
target = pickup_assignment.get(PickupIndex(hint["target"]))
if target is not None:
extra["pickup_db"] = get_target_pickup_db(target)
else:
extra["pickup_db"] = pickup_db
hints[NodeIdentifier.from_string(identifier_str)] = BaseHint.from_json(hint, **extra)
patches = GamePatches.create_from_game(game, player_index, configuration)
patches = patches.assign_dock_connections(dock_connections)
patches = patches.assign_dock_weakness(dock_weakness)
return dataclasses.replace(
patches,
pickup_assignment=pickup_assignment, # PickupAssignment
starting_equipment=starting_equipment,
starting_location=starting_location, # NodeIdentifier
hints=hints,
custom_patcher_data=custom_patcher_data,
game_specific=game_specific,
)
def decode(
game_modifications: list[dict],
layout_configurations: dict[int, BaseConfiguration],
) -> dict[int, GamePatches]:
all_games = {
index: filtered_database.game_description_for_layout(configuration)
for index, configuration in layout_configurations.items()
}
all_pools = {
index: pool_creator.calculate_pool_results(configuration, all_games[index])
for index, configuration in layout_configurations.items()
}
return {
index: decode_single(index, all_pools, all_games[index], modifications, layout_configurations[index], all_games)
for index, modifications in enumerate(game_modifications)
}
def serialize(all_patches: dict[int, GamePatches]) -> list[dict]:
return [serialize_single(index, len(all_patches), patches) for index, patches in all_patches.items()]
| 0 | 0.939028 | 1 | 0.939028 | game-dev | MEDIA | 0.937819 | game-dev | 0.969562 | 1 | 0.969562 |
MrTJP/ProjectRed | 13,240 | expansion/src/main/java/mrtjp/projectred/expansion/part/BaseTubePart.java | package mrtjp.projectred.expansion.part;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutput;
import codechicken.lib.raytracer.VoxelShapeCache;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.api.MicroMaterial;
import codechicken.microblock.api.SlottedHollowConnect;
import codechicken.microblock.item.ItemMicroBlock;
import codechicken.microblock.util.MicroMaterialRegistry;
import codechicken.multipart.api.MultipartType;
import codechicken.multipart.api.part.BaseMultipart;
import codechicken.multipart.api.part.MultiPart;
import codechicken.multipart.api.part.NormalOcclusionPart;
import codechicken.multipart.api.part.SlottedPart;
import codechicken.multipart.util.MultipartPlaceContext;
import codechicken.multipart.util.PartRayTraceResult;
import com.google.common.collect.ImmutableSet;
import mrtjp.projectred.api.IConnectable;
import mrtjp.projectred.core.Configurator;
import mrtjp.projectred.core.part.IConnectableCenterPart;
import mrtjp.projectred.expansion.TubeType;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;
import javax.annotation.Nullable;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
public abstract class BaseTubePart extends BaseMultipart implements IConnectableCenterPart, NormalOcclusionPart, SlottedPart, SlottedHollowConnect {
public static final Cuboid6[] fOBounds = new Cuboid6[7];
public static final VoxelShape[] fOShapes = new VoxelShape[7];
public static final VoxelShape[] fOShapeStates = new VoxelShape[64];
public static int expandBounds = -1;
static {
double w = 2 / 8D;
fOBounds[6] = new Cuboid6(0.5 - w, 0.5 - w, 0.5 - w, 0.5 + w, 0.5 + w, 0.5 + w);
fOShapes[6] = VoxelShapeCache.getShape(fOBounds[6]);
for (int s = 0; s < 6; s++) {
fOBounds[s] = new Cuboid6(0.5 - w, 0, 0.5 - w, 0.5 + w, 0.5 - w, 0.5 + w).apply(Rotation.sideRotations[s].at(Vector3.CENTER));
fOShapes[s] = VoxelShapeCache.getShape(fOBounds[s]);
}
for (int m = 0; m < 64; m++) {
List<VoxelShape> shapes = new LinkedList<>();
shapes.add(VoxelShapeCache.getShape(fOBounds[6]));
for (int s = 0; s < 6; s++) {
if ((m & (1 << s)) != 0) {
shapes.add(VoxelShapeCache.getShape(fOBounds[s]));
}
}
fOShapeStates[m] = VoxelShapeCache.merge(ImmutableSet.copyOf(shapes));
}
}
protected static final int KEY_UPDATE = 0;
private static final int KEY_CONN_MAP = 1;
private static final int KEY_MATERIAL = 2;
private static final int KEY_REMOVE_MATERIAL = 3;
private final TubeType pipeType;
private int connMap = 0;
private @Nullable MicroMaterial material = null;
public BaseTubePart(TubeType pipeType) {
this.pipeType = pipeType;
}
public @Nullable MicroMaterial getMaterial() {
return material;
}
public TubeType getPipeType() {
return pipeType;
}
//region Trait fields
@Override
public int getConnMap() {
return connMap;
}
@Override
public void setConnMap(int map) {
connMap = map;
}
//endregion
//region TMultiPart overrides
@Override
public void save(CompoundTag tag, HolderLookup.Provider registries) {
tag.putInt("connMap", connMap);
if (material != null) {
tag.putString("mat", Objects.requireNonNull(material.getRegistryName()).toString());
}
}
@Override
public void load(CompoundTag tag, HolderLookup.Provider registries) {
connMap = tag.getInt("connMap");
material = tag.contains("mat") ? MicroMaterialRegistry.getMaterial(tag.getString("mat")) : null;
}
@Override
public void writeDesc(MCDataOutput packet) {
packet.writeByte(packedConnMap());
packet.writeBoolean(material != null);
if (material != null) {
packet.writeRegistryIdDirect(MicroMaterialRegistry.microMaterials(), material);
}
}
@Override
public MultipartType<?> getType() {
return getPipeType().getPartType();
}
protected ItemStack getItem() {
return getPipeType().makeStack();
}
@Override
public ItemStack getCloneStack(PartRayTraceResult hit) {
return getItem();
}
@Override
public void readDesc(MCDataInput packet) {
connMap = packet.readUByte();
if (packet.readBoolean()) {
material = packet.readRegistryIdDirect(MicroMaterialRegistry.microMaterials());
}
}
//endregion
//region Packets
@Override
public final void sendUpdate(Consumer<MCDataOutput> func) {
sendUpdate(KEY_UPDATE, func);
}
@Override
public final void readUpdate(MCDataInput packet) {
read(packet, packet.readUByte());
}
protected final void sendUpdate(int key, Consumer<MCDataOutput> func) {
super.sendUpdate(p -> {
p.writeByte(key);
func.accept(p);
});
}
// Override to handle other keys
protected void read(MCDataInput packet, int key) {
switch (key) {
case KEY_UPDATE -> readDesc(packet);
case KEY_CONN_MAP -> {
connMap = packet.readUByte();
if (useStaticRenderer()) tile().markRender();
}
case KEY_MATERIAL -> {
material = packet.readRegistryIdDirect(MicroMaterialRegistry.microMaterials());
if (useStaticRenderer()) tile().markRender();
}
case KEY_REMOVE_MATERIAL -> {
material = null;
if (useStaticRenderer()) tile().markRender();
}
default -> {
// Unknown
}
}
}
protected void sendConnUpdate() {
sendUpdate(KEY_CONN_MAP, p -> p.writeByte(packedConnMap()));
}
protected void sendMaterialUpdate() {
if (material == null) {
sendUpdate(KEY_REMOVE_MATERIAL, p -> {});
} else {
sendUpdate(KEY_MATERIAL, p -> p.writeRegistryIdDirect(MicroMaterialRegistry.microMaterials(), material));
}
}
//endregion
public int packedConnMap() {
return connMap & 0x3F | connMap >> 6 & 0x3F;
}
public boolean useStaticRenderer() {
return Configurator.staticWires;
}
@OnlyIn(Dist.CLIENT)
public TextureAtlasSprite getIcon() {
return getPipeType().getTextures().get(0);
}
public boolean preparePlacement(MultipartPlaceContext context) {
return true;
}
@Override
public SoundType getPlacementSound(UseOnContext context) {
return SoundType.GLASS;
}
@Override
public void onPartChanged(@Nullable MultiPart part) {
super.onPartChanged(part);
if (!level().isClientSide) {
updateOutward();
}
}
@Override
public void onNeighborBlockChanged(BlockPos from) {
super.onNeighborBlockChanged(from);
if (!level().isClientSide) {
updateOutside();
}
}
@Override
public void onAdded() {
super.onAdded();
if (!level().isClientSide) {
updateInsideAndOutside();
}
}
@Override
public void onRemoved() {
super.onRemoved();
if (!level().isClientSide) {
notifyAllExternals();
}
}
@Override
public float getStrength(Player player, PartRayTraceResult hit) {
if (material != null) {
return Math.min(1.25f / 30f, material.getStrength(player));
}
return 1.25f / 30f;
}
@Override
public Iterable<ItemStack> getDrops() {
List<ItemStack> list = new LinkedList<>();
list.add(getItem());
if (material != null) {
list.add(ItemMicroBlock.create(0, 1, material));
}
return list;
}
@Override
public VoxelShape getShape(CollisionContext context) {
int m = 0;
for (int s = 0; s < 6; s++) {
if (maskConnects(s)) {
m |= 1 << s;
}
}
return fOShapeStates[m];
}
@Override
public VoxelShape getBlockSupportShape() {
return Shapes.empty();
}
//region Occlusion
@Override
public VoxelShape getOcclusionShape() {
return fOShapes[expandBounds >= 0 ? expandBounds : 6];
}
//endregion
@Override
public int getHoleSize(int side) {
return 8;
}
@Override
public int getSlotMask() {
return 1 << 6;
}
@Override
public ItemInteractionResult useItemOn(ItemStack held, Player player, PartRayTraceResult hit, InteractionHand hand) {
return super.useItemOn(held, player, hit, hand);
//TODO Uncomment to deal with material application
// * Implement model generation and rendering in TubeModelRenderer (or rather, move FramedJacketedWireModelBuilder to core)
// * Add a Highlight renderer
// * Don't sync items to client when jacketed (you can't see them anyway)
// if (super.activate(player, hit, held, hand).shouldSwing()) return InteractionResult.SUCCESS;
//
// // Couch + right click with empty hand removes material
// if (held.isEmpty() && player.isCrouching() && material != null) {
// if (!level().isClientSide) {
// if (material != null && !player.isCreative()) {
// PlacementLib.dropTowardsPlayer(level(), pos(), ItemMicroBlock.create(0, 1, material), player);
// }
// material = null;
// sendMaterialUpdate();
// }
// return InteractionResult.SUCCESS;
// }
//
// // Right click with cover Microblock allows adding a cover material
// if (!held.isEmpty() && held.getItem() == CBMicroblockModContent.MICRO_BLOCK_ITEM.get() && ItemMicroBlock.getFactory(held) == CBMicroblockModContent.FACE_MICROBLOCK_PART.get() && ItemMicroBlock.getSize(held) == 1) {
// MicroMaterial newMat = ItemMicroBlock.getMaterialFromStack(held);
// if (newMat != null && (material == null || newMat != material)) {
// if (!level().isClientSide) {
// // Exclude incompatible materials
// if (newMat.isTransparent()) {
// return InteractionResult.PASS;
// }
//
// // Drop old material if player is not in creative
// if (material != null && !player.isCreative()) {
// PlacementLib.dropTowardsPlayer(level(), pos(), ItemMicroBlock.create(0, 1, material), player);
// }
//
// // Swap the material
// material = newMat;
// sendMaterialUpdate();
//
// // Play material sound
// SoundType sound = newMat.getSound();
// if (sound != null) {
// level().playSound(null, pos(), sound.getPlaceSound(), SoundSource.BLOCKS, sound.getVolume() + 1.0F/2.0F, sound.getPitch() * 0.8F);
// }
//
// // Consume item from player if not in creative
// if (!player.isCreative()) {
// held.shrink(1);
// }
// }
// return InteractionResult.SUCCESS;
// }
// }
//
// return InteractionResult.PASS;
}
//region IConnectableCenterPart overrides
@Override
public boolean discoverOpen(int s) {
MultiPart part = tile().getSlottedPart(s);
// If nothing on the face, connection is possible
if (part == null) {
return true;
}
// If a compatible connectable part is on the face, connection is possible
if (part instanceof IConnectable ic && canConnectPart(ic, s)) {
return true;
}
expandBounds = s;
boolean fits = tile().canReplacePart(this, this);
expandBounds = -1;
return fits;
}
@Override
public void maskChangeEvent(boolean internalChange, boolean externalChange) {
if (internalChange || externalChange) {
sendConnUpdate();
}
}
//endregion
}
| 0 | 0.863479 | 1 | 0.863479 | game-dev | MEDIA | 0.640135 | game-dev,graphics-rendering | 0.93094 | 1 | 0.93094 |
AionGermany/aion-germany | 2,157 | AL-Game/src/com/aionemu/gameserver/taskmanager/tasks/TeamEffectUpdater.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 com.aionemu.gameserver.taskmanager.tasks;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.team2.alliance.PlayerAllianceService;
import com.aionemu.gameserver.model.team2.common.legacy.GroupEvent;
import com.aionemu.gameserver.model.team2.common.legacy.PlayerAllianceEvent;
import com.aionemu.gameserver.model.team2.group.PlayerGroupService;
import com.aionemu.gameserver.taskmanager.AbstractIterativePeriodicTaskManager;
/**
* @author Sarynth Supports PlayerGroup and PlayerAlliance movement updating.
*/
public final class TeamEffectUpdater extends AbstractIterativePeriodicTaskManager<Player> {
private static final class SingletonHolder {
private static final TeamEffectUpdater INSTANCE = new TeamEffectUpdater();
}
public static TeamEffectUpdater getInstance() {
return SingletonHolder.INSTANCE;
}
public TeamEffectUpdater() {
super(500);
}
@Override
protected void callTask(Player player) {
if (player.isOnline()) {
if (player.isInGroup2()) {
PlayerGroupService.updateGroup(player, GroupEvent.UPDATE);
}
if (player.isInAlliance2()) {
PlayerAllianceService.updateAlliance(player, PlayerAllianceEvent.UPDATE);
}
}
// Remove task from list. It will be re-added if player effect changes again.
this.stopTask(player);
}
@Override
protected String getCalledMethodName() {
return "teamEffectUpdate()";
}
}
| 0 | 0.783079 | 1 | 0.783079 | game-dev | MEDIA | 0.897586 | game-dev | 0.738789 | 1 | 0.738789 |
EOS-team/EOS | 12,098 | src/embodied-intelligence/src/3D_human_pose_recognition/ios_sdk/UnityDEBUG/ForDebug/Library/PackageCache/com.unity.timeline@1.6.4/Editor/TimelineUtility.cs | using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
#if UNITY_2021_2_OR_NEWER
using UnityEditor.SceneManagement;
#else
using UnityEditor.Experimental.SceneManagement;
#endif
using UnityEngine;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using Object = UnityEngine.Object;
namespace UnityEditor.Timeline
{
static class TimelineUtility
{
public static void ReorderTracks(List<ScriptableObject> allTracks, List<TrackAsset> tracks, ScriptableObject insertAfterAsset, bool up)
{
foreach (var i in tracks)
allTracks.Remove(i);
int index = allTracks.IndexOf(insertAfterAsset);
index = up ? Math.Max(index, 0) : index + 1;
allTracks.InsertRange(index, tracks.OfType<ScriptableObject>());
}
// Gets the track that holds the game object reference for this track.
public static TrackAsset GetSceneReferenceTrack(TrackAsset asset)
{
if (asset == null)
return null;
if (asset.isSubTrack)
return GetSceneReferenceTrack(asset.parent as TrackAsset);
return asset;
}
public static bool TrackHasAnimationCurves(TrackAsset track)
{
if (track.hasCurves)
return true;
var animTrack = track as AnimationTrack;
if (animTrack != null && animTrack.infiniteClip != null && !animTrack.infiniteClip.empty)
return true;
for (int i = 0; i < track.clips.Length; i++)
{
var curveClip = track.clips[i].curves;
var animationClip = track.clips[i].animationClip;
// prune out clip with zero curves
if (curveClip != null && curveClip.empty)
curveClip = null;
if (animationClip != null && animationClip.empty)
animationClip = null;
// prune out clips coming from FBX
if (animationClip != null && ((animationClip.hideFlags & HideFlags.NotEditable) != 0))
animationClip = null;
if (!track.clips[i].recordable)
animationClip = null;
if ((curveClip != null) || (animationClip != null))
return true;
}
return false;
}
// get the game object reference associated with this
public static GameObject GetSceneGameObject(PlayableDirector director, TrackAsset asset)
{
if (director == null || asset == null)
return null;
asset = GetSceneReferenceTrack(asset);
var gameObject = director.GetGenericBinding(asset) as GameObject;
var component = director.GetGenericBinding(asset) as Component;
if (component != null)
gameObject = component.gameObject;
return gameObject;
}
public static PlayableDirector[] GetDirectorsInSceneUsingAsset(PlayableAsset asset)
{
const HideFlags hideFlags =
HideFlags.HideInHierarchy | HideFlags.HideInInspector |
HideFlags.DontSaveInEditor | HideFlags.NotEditable;
var prefabMode = PrefabStageUtility.GetCurrentPrefabStage();
var inScene = new List<PlayableDirector>();
var allDirectors = Resources.FindObjectsOfTypeAll(typeof(PlayableDirector)) as PlayableDirector[];
foreach (var director in allDirectors)
{
if ((director.hideFlags & hideFlags) != 0)
continue;
string assetPath = AssetDatabase.GetAssetPath(director.transform.root.gameObject);
if (!String.IsNullOrEmpty(assetPath))
continue;
if (prefabMode != null && !prefabMode.IsPartOfPrefabContents(director.gameObject))
continue;
if (asset == null || (asset != null && director.playableAsset == asset))
{
inScene.Add(director);
}
}
return inScene.ToArray();
}
public static PlayableDirector GetDirectorComponentForGameObject(GameObject gameObject)
{
return gameObject != null ? gameObject.GetComponent<PlayableDirector>() : null;
}
public static TimelineAsset GetTimelineAssetForDirectorComponent(PlayableDirector director)
{
return director != null ? director.playableAsset as TimelineAsset : null;
}
public static bool IsPrefabOrAsset(Object obj)
{
return EditorUtility.IsPersistent(obj) || (obj.hideFlags & HideFlags.NotEditable) != 0;
}
// TODO -- Need to add this to SerializedProperty so we can get replicate the accuracy that exists
// in the undo system
internal static string PropertyToString(SerializedProperty property)
{
switch (property.propertyType)
{
case SerializedPropertyType.Integer:
return property.intValue.ToString(CultureInfo.InvariantCulture);
case SerializedPropertyType.Float:
return property.floatValue.ToString(CultureInfo.InvariantCulture);
case SerializedPropertyType.String:
return property.stringValue;
case SerializedPropertyType.Boolean:
return property.boolValue ? "1" : "0";
case SerializedPropertyType.Color:
return property.colorValue.ToString();
case SerializedPropertyType.ArraySize:
return property.intValue.ToString(CultureInfo.InvariantCulture);
case SerializedPropertyType.Enum:
return property.intValue.ToString(CultureInfo.InvariantCulture);
case SerializedPropertyType.ObjectReference:
return string.Empty;
case SerializedPropertyType.LayerMask:
return property.intValue.ToString(CultureInfo.InvariantCulture);
case SerializedPropertyType.Character:
return property.intValue.ToString(CultureInfo.InvariantCulture);
case SerializedPropertyType.AnimationCurve:
return property.animationCurveValue.ToString();
case SerializedPropertyType.Gradient:
return property.gradientValue.ToString();
case SerializedPropertyType.Vector3:
return property.vector3Value.ToString();
case SerializedPropertyType.Vector4:
return property.vector4Value.ToString();
case SerializedPropertyType.Vector2:
return property.vector2Value.ToString();
case SerializedPropertyType.Rect:
return property.rectValue.ToString();
case SerializedPropertyType.Bounds:
return property.boundsValue.ToString();
case SerializedPropertyType.Quaternion:
return property.quaternionValue.ToString();
case SerializedPropertyType.Generic:
return string.Empty;
default:
Debug.LogWarning("Unknown Property Type: " + property.propertyType);
return string.Empty;
}
}
// Is this a recordable clip on an animation track.
internal static bool IsRecordableAnimationClip(TimelineClip clip)
{
if (!clip.recordable)
return false;
AnimationPlayableAsset asset = clip.asset as AnimationPlayableAsset;
if (asset == null)
return false;
return true;
}
public static bool HasCustomEditor(TimelineClip clip)
{
var editor = CustomTimelineEditorCache.GetClipEditor(clip);
return editor != CustomTimelineEditorCache.GetDefaultClipEditor();
}
public static IList<PlayableDirector> GetSubTimelines(TimelineClip clip, IExposedPropertyTable director)
{
var editor = CustomTimelineEditorCache.GetClipEditor(clip);
List<PlayableDirector> directors = new List<PlayableDirector>();
try
{
editor.GetSubTimelines(clip, director as PlayableDirector, directors);
}
catch (Exception e)
{
Debug.LogException(e);
}
return directors;
}
public static bool IsAllSubTrackMuted(TrackAsset asset)
{
if (asset is GroupTrack)
return asset.mutedInHierarchy;
foreach (TrackAsset t in asset.GetChildTracks())
{
if (!t.muted)
return false;
var childMuted = IsAllSubTrackMuted(t);
if (!childMuted)
return false;
}
return true;
}
public static bool IsParentMuted(TrackAsset asset)
{
TrackAsset p = asset.parent as TrackAsset;
if (p == null) return false;
return p is GroupTrack ? p.mutedInHierarchy : IsParentMuted(p);
}
public static IEnumerable<PlayableDirector> GetAllDirectorsInHierarchy(PlayableDirector mainDirector)
{
var directors = new HashSet<PlayableDirector> { mainDirector };
GetAllDirectorsInHierarchy(mainDirector, directors);
return directors;
}
static void GetAllDirectorsInHierarchy(PlayableDirector director, ISet<PlayableDirector> directors)
{
var timelineAsset = director.playableAsset as TimelineAsset;
if (timelineAsset == null)
return;
foreach (var track in timelineAsset.GetOutputTracks())
{
foreach (var clip in track.clips)
{
foreach (var subDirector in GetSubTimelines(clip, director))
{
if (!directors.Contains(subDirector))
{
directors.Add(subDirector);
GetAllDirectorsInHierarchy(subDirector, directors);
}
}
}
}
}
public static IEnumerable<T> GetBindingsFromDirectors<T>(IEnumerable<PlayableDirector> directors) where T : Object
{
var bindings = new HashSet<T>();
foreach (var director in directors)
{
if (director.playableAsset == null) continue;
foreach (var output in director.playableAsset.outputs)
{
var binding = director.GetGenericBinding(output.sourceObject) as T;
if (binding != null)
bindings.Add(binding);
}
}
return bindings;
}
public static bool IsLockedFromGroup(TrackAsset asset)
{
TrackAsset p = asset.parent as TrackAsset;
if (p == null) return false;
return p is GroupTrack ? p.lockedInHierarchy : IsLockedFromGroup(p);
}
internal static bool IsCurrentSequenceValid()
{
return TimelineWindow.instance != null
&& TimelineWindow.instance.state != null
&& TimelineWindow.instance.state.editSequence != null;
}
public static TimelineAsset CreateAndSaveTimelineAsset(string path)
{
var newAsset = ScriptableObject.CreateInstance<TimelineAsset>();
newAsset.editorSettings.frameRate = TimelineProjectSettings.instance.defaultFrameRate;
AssetDatabase.CreateAsset(newAsset, path);
return newAsset;
}
}
}
| 0 | 0.938389 | 1 | 0.938389 | game-dev | MEDIA | 0.992946 | game-dev | 0.977551 | 1 | 0.977551 |
ckormanyos/real-time-cpp | 2,008 | examples/chapter12_04/src/util/memory/util_factory.h | ///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2007 - 2013.
// Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef _UTIL_FACTORY_2012_02_19_H_
#define _UTIL_FACTORY_2012_02_19_H_
#include <memory>
#include <util/utility/util_noncopyable.h>
namespace util
{
class factory_product : private util::noncopyable
{
public:
virtual ~factory_product() { }
virtual void init() = 0;
protected:
factory_product() { }
};
template<typename T,
typename alloc = std::allocator<T> >
class factory
{
public:
typedef T value_type;
typedef T* pointer_type;
typedef alloc allocator_type;
static pointer_type make()
{
pointer_type p = new(allocate()) value_type();
static_cast<factory_product*>(p)->init();
return p;
}
template<typename... parameters>
static pointer_type make(parameters... params)
{
pointer_type p = new(allocate()) value_type(params...);
static_cast<factory_product*>(p)->init();
return p;
}
private:
static void* allocate()
{
return allocator_type().allocate(1U, nullptr);
}
};
}
#endif // _UTIL_FACTORY_2012_02_19_H_
/*
#include <util/memory/util_factory.h>
class something : public util::factory_product
{
public:
something() { }
virtual ~something() { }
private:
virtual void init() { }
};
class another : public util::factory_product
{
public:
another(const int m, const int n) : my_m(m),
my_n(n) { }
virtual ~another() { }
private:
const int my_m;
const int my_n;
virtual void init() { }
};
something* p_something = util::factory<something>::make();
another* p_another = util::factory<another >::make(123, 456);
*/
| 0 | 0.889934 | 1 | 0.889934 | game-dev | MEDIA | 0.178283 | game-dev | 0.67437 | 1 | 0.67437 |
quarkusio/quarkus | 4,944 | extensions/amazon-lambda-rest/runtime/src/main/java/io/quarkus/amazon/lambda/http/model/MultiValuedTreeMap.java | package io.quarkus.amazon.lambda.http.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Simple implementation of a multi valued tree map to use for case-insensitive headers
*
* @param <Key> The type for the map key
* @param <Value> The type for the map values
*/
public class MultiValuedTreeMap<Key, Value> implements Map<Key, List<Value>>, Serializable, Cloneable {
private static final long serialVersionUID = 42L;
private final Map<Key, List<Value>> map;
public MultiValuedTreeMap() {
map = new TreeMap<>();
}
public MultiValuedTreeMap(Comparator<Key> comparator) {
map = new TreeMap<>(comparator);
}
public void add(Key key, Value value) {
List<Value> values = findKey(key);
values.add(value);
}
public Value getFirst(Key key) {
List<Value> values = get(key);
if (values == null || values.size() == 0) {
return null;
}
return values.get(0);
}
public void putSingle(Key key, Value value) {
List<Value> values = findKey(key);
values.clear();
values.add(value);
}
@Override
public void clear() {
map.clear();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public Set<Entry<Key, List<Value>>> entrySet() {
return map.entrySet();
}
public boolean equals(Object o) {
return map.equals(o);
}
@Override
public List<Value> get(Object key) {
return map.get(key);
}
public int hashCode() {
return map.hashCode();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public Set<Key> keySet() {
return map.keySet();
}
@Override
public List<Value> put(Key key, List<Value> value) {
return map.put(key, value);
}
@Override
public void putAll(Map<? extends Key, ? extends List<Value>> t) {
map.putAll(t);
}
@Override
public List<Value> remove(Object key) {
return map.remove(key);
}
@Override
public int size() {
return map.size();
}
@Override
public Collection<List<Value>> values() {
return map.values();
}
public void addAll(Key key, Value... newValues) {
for (Value value : newValues) {
add(key, value);
}
}
public void addAll(Key key, List<Value> valueList) {
for (Value value : valueList) {
add(key, value);
}
}
public void addFirst(Key key, Value value) {
List<Value> values = get(key);
if (values == null) {
add(key, value);
return;
} else {
values.add(0, value);
}
}
public boolean equalsIgnoreValueOrder(MultiValuedTreeMap<Key, Value> vmap) {
if (this == vmap) {
return true;
}
if (!keySet().equals(vmap.keySet())) {
return false;
}
for (Entry<Key, List<Value>> e : entrySet()) {
List<Value> olist = vmap.get(e.getKey());
if (e.getValue().size() != olist.size()) {
return false;
}
for (Value v : e.getValue()) {
if (!olist.contains(v)) {
return false;
}
}
}
return true;
}
private List<Value> findKey(Key key) {
List<Value> values = this.get(key);
if (values == null) {
values = new ArrayList<>();
put(key, values);
}
return values;
}
@Override
public MultiValuedTreeMap<Key, Value> clone() {
MultiValuedTreeMap<Key, Value> clone = new MultiValuedTreeMap<>();
for (Key key : keySet()) {
List<Value> value = get(key);
List<Value> newValue = new ArrayList<>(value);
clone.put(key, newValue);
}
return clone;
}
public String toString() {
StringBuilder result = new StringBuilder();
String delim = ",";
for (Object name : keySet()) {
for (Object value : get(name)) {
result.append(delim);
if (name == null) {
result.append("null"); //$NON-NLS-1$
} else {
result.append(name.toString());
}
if (value != null) {
result.append('=');
result.append(value.toString());
}
}
}
return "[" + result.toString() + "]";
}
}
| 0 | 0.839352 | 1 | 0.839352 | game-dev | MEDIA | 0.208299 | game-dev | 0.983633 | 1 | 0.983633 |
Monkestation/Monkestation2.0 | 2,597 | code/modules/procedural_mapping/mapGeneratorModules/helpers.dm | //Helper Modules
// Helper to repressurize the area in case it was run in space
/datum/map_generator_module/bottom_layer/repressurize
spawnableAtoms = list()
spawnableTurfs = list()
/datum/map_generator_module/bottom_layer/repressurize/generate()
if(!mother)
return
var/list/map = mother.map
for(var/turf/T in map)
SSair.remove_from_active(T)
for(var/turf/open/T in map)
if(T.air)
T.air = T.create_gas_mixture()
SSair.add_to_active(T, TRUE)
/datum/map_generator_module/bottom_layer/massdelete
spawnableAtoms = list()
spawnableTurfs = list()
var/deleteturfs = TRUE //separate var for the empty type.
var/list/ignore_typecache
/datum/map_generator_module/bottom_layer/massdelete/generate()
if(!mother)
return
for(var/V in mother.map)
var/turf/T = V
T.empty(deleteturfs? null : T.type, null, ignore_typecache, CHANGETURF_FORCEOP)
/datum/map_generator_module/bottom_layer/massdelete/no_delete_mobs/New()
..()
ignore_typecache = GLOB.typecache_mob
/datum/map_generator_module/bottom_layer/massdelete/leave_turfs
deleteturfs = FALSE
/datum/map_generator_module/bottom_layer/massdelete/regeneration_delete
deleteturfs = FALSE
/datum/map_generator_module/bottom_layer/massdelete/regeneration_delete/New()
..()
ignore_typecache = GLOB.typecache_mob
//Only places atoms/turfs on area borders
/datum/map_generator_module/border
clusterCheckFlags = CLUSTER_CHECK_NONE
/datum/map_generator_module/border/generate()
if(!mother)
return
var/list/map = mother.map
for(var/turf/T in map)
if(is_border(T))
place(T)
/datum/map_generator_module/border/proc/is_border(turf/T)
for(var/direction in list(SOUTH,EAST,WEST,NORTH))
if (get_step(T,direction) in mother.map)
continue
return 1
return 0
/datum/map_generator/repressurize
modules = list(/datum/map_generator_module/bottom_layer/repressurize)
buildmode_name = "Block: Restore Roundstart Air Contents"
/datum/map_generator/massdelete
modules = list(/datum/map_generator_module/bottom_layer/massdelete)
buildmode_name = "Block: Full Mass Deletion"
/datum/map_generator/massdelete/nomob
modules = list(/datum/map_generator_module/bottom_layer/massdelete/no_delete_mobs)
buildmode_name = "Block: Mass Deletion - Leave Mobs"
/datum/map_generator/massdelete/noturf
modules = list(/datum/map_generator_module/bottom_layer/massdelete/leave_turfs)
buildmode_name = "Block: Mass Deletion - Leave Turfs"
/datum/map_generator/massdelete/regen
modules = list(/datum/map_generator_module/bottom_layer/massdelete/regeneration_delete)
buildmode_name = "Block: Mass Deletion - Leave Mobs and Turfs"
| 0 | 0.92938 | 1 | 0.92938 | game-dev | MEDIA | 0.935053 | game-dev | 0.907907 | 1 | 0.907907 |
RedShyGuy/Vapecord-ACNL-Plugin | 3,013 | Sources/Folders/MoneyCodes.cpp | #include "cheats.hpp"
#include "Helpers/Player.hpp"
#include "Helpers/Game.hpp"
#include "Helpers/Wrapper.hpp"
#include "Helpers/Address.hpp"
#include "Helpers/Town.hpp"
namespace CTRPluginFramework {
//Wallet Mod
void wallet(MenuEntry *entry) {
ACNL_Player *player = Player::GetSaveData();
if(!player) {
MessageBox(Language->Get("SAVE_PLAYER_NO")).SetClear(ClearScreen::Top)();
return;
}
u32 money = 0;
if(Wrap::KB<u32>(Language->Get("ENTER_AMOUNT"), false, 5, money, 0))
GameHelper::EncryptValue(&player->PocketMoney, money);
}
//Bank Mod
void bank(MenuEntry *entry) {
ACNL_Player *player = Player::GetSaveData();
if(!player) {
MessageBox(Language->Get("SAVE_PLAYER_NO")).SetClear(ClearScreen::Top)();
return;
}
u32 money = 0;
if(Wrap::KB<u32>(Language->Get("ENTER_AMOUNT"), false, 9, money, 0))
GameHelper::EncryptValue(&player->BankAmount, money);
}
//Meow Coupon Mod
void coupon(MenuEntry *entry) {
ACNL_Player *player = Player::GetSaveData();
if(!player) {
MessageBox(Language->Get("SAVE_PLAYER_NO")).SetClear(ClearScreen::Top)();
return;
}
u32 coupon = 0;
if(Wrap::KB<u32>(Language->Get("ENTER_AMOUNT"), false, 4, coupon, 0))
GameHelper::EncryptValue(&player->MeowCoupons, coupon);
}
//Badges Mod
void badges(MenuEntry *entry) {
ACNL_Player *player = Player::GetSaveData();
if(!player) {
MessageBox(Language->Get("SAVE_PLAYER_NO")).SetClear(ClearScreen::Top)();
return;
}
static const std::vector<std::string> badgesopt = {
Color(0xFFD700FF) << Language->Get("VECTOR_BADGE_GOLD"),
Color(0xC0C0C0FF) << Language->Get("VECTOR_BADGE_SILVER"),
Color(0xCD7F32FF) << Language->Get("VECTOR_BADGE_BRONZE"),
Language->Get("VECTOR_BADGE_NONE")
};
Keyboard optKb(Language->Get("KEY_CHOOSE_OPTION"), badgesopt);
int index = optKb.Open();
if(index < 0)
return;
bool WithStats = MessageBox("Do you want to set the appropiate badge stats?\n(This will edit all badge related game stats)", DialogType::DialogYesNo).SetClear(ClearScreen::Top)();
for(int i = 0; i < 24; ++i)
GameHelper::SetBadges(i, std::abs(index - 3), WithStats);
}
//Medals Mod 32DC51B8 31F2C6BC
void medals(MenuEntry *entry) {
ACNL_Player *player = Player::GetSaveData();
if(!player) {
MessageBox(Language->Get("SAVE_PLAYER_NO")).SetClear(ClearScreen::Top)();
return;
}
u32 medal = 0;
if(Wrap::KB<u32>(Language->Get("ENTER_AMOUNT"), false, 4, medal, 0)) {
GameHelper::EncryptValue(&player->MedalAmount, medal);
}
}
//turnip Mod
void turnips(MenuEntry *entry) {
ACNL_TownData *town = Town::GetSaveData();
if(!town) {
MessageBox(Language->Get("SAVE_PLAYER_NO")).SetClear(ClearScreen::Top)();
return;
}
u32 turnip = 0;
if(Wrap::KB<u32>(Language->Get("ENTER_AMOUNT"), false, 5, turnip, 0)) {
for(int i = 0; i < 6; ++i) {
GameHelper::EncryptValue(&town->TurnipPrices[i], turnip); //AM
GameHelper::EncryptValue(&town->TurnipPrices[i + 6], turnip); //PM
}
}
}
} | 0 | 0.886804 | 1 | 0.886804 | game-dev | MEDIA | 0.902552 | game-dev | 0.892741 | 1 | 0.892741 |
jswigart/omni-bot | 17,010 | Installer/Files/et/nav/snatch3.gm | /*
Updated for new escort goals.
*/
global Map =
{
Barrierpassed =
{
Name="Barrierpassed",
TriggerOnEntity = GetGoal("MOVER_truck").GetEntity(),
OnEnter = function(ent)
{
//Util.MapDebugPrint(GetEntName(ent) + " BarrierPassed");
//Map.RideVehicle.truck.Enabled = true;
SetAvailableMapGoals( TEAM.AXIS, false, "BUILD_Truck_Barrier_1" );
Util.SetGoalPosition( 428.9, 2221.7, 164.125, Map.Plant_Main_Entrance);
},
OnExit = function(ent)
{
Util.MapDebugPrint(GetEntName(ent) + " exited aabb trigger");
Util.DisableGroup( "group5");
Util.DisableGroup( "group4");
Util.EnableGroup( "group7", TEAM.ALLIES);
Util.EnableGroup( "group13", TEAM.AXIS);
//~ SetAvailableMapGoals( TEAM.ALLIES, true, "PLANT_Main_Entrance" );
//~ SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_main.*" );
Util.MapDebugPrint("barrier1 exit");
},
},
def =
{
Name="def",
TriggerOnEntity = GetGoal("MOVER_truck").GetEntity(),
OnEnter = function(ent)
{
//Util.MapDebugPrint(GetEntName(ent) + "BarrierPassed");
//Map.RideVehicle.truck.Enabled = true;
Util.EnableGroup( "group12", TEAM.AXIS);
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_Truck_Barrier_2" );
//~ SetAvailableMapGoals( TEAM.AXIS, true, "PLANT_Bridge" );
//~ SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_MG42" );
},
OnExit = function(ent)
{
Util.MapDebugPrint(GetEntName(ent) + "exited aabb trigger");
Util.DisableGroup( "group13");
//~ SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_main.*" );
Util.MapDebugPrint("def exit");
},
},
barrier2 =
{
Name="barrier2",
TriggerOnEntity = GetGoal("MOVER_truck").GetEntity(),
OnEnter = function(ent)
{
//Util.MapDebugPrint(GetEntName(ent) + "BarrierPassed");
//Map.RideVehicle.truck.Enabled = true;
SetAvailableMapGoals( TEAM.AXIS, false, "PLANT_Bridge" );
SetAvailableMapGoals( TEAM.AXIS, false, "BUILD_MG42" );
SetAvailableMapGoals( TEAM.AXIS, false, "BUILD_Truck_Barrier_2" );
SetAvailableMapGoals( TEAM.AXIS, false, "MOUNTMG42_Balcony_MG" );
Util.EnableGroup( "group14", TEAM.AXIS);
Util.DisableGroup( "group15");
Util.MapDebugPrint("b2 enter");
},
OnExit = function(ent)
{
Util.DisableGroup( "group9");
Util.EnableGroup( "group10", TEAM.ALLIES);
Util.MapDebugPrint(GetEntName(ent) + " exited aabb trigger");
Util.MapDebugPrint("b2 exit");
},
},
shift =
{
Name="shift",
TriggerOnEntity = GetGoal("MOVER_truck").GetEntity(),
OnEnter = function(ent)
{
//Util.MapDebugPrint(GetEntName(ent) + " BarrierPassed");
//Map.RideVehicle.truck.Enabled = true;
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_tp.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "PLANT_Bridge" );
SetAvailableMapGoals( TEAM.ALLIES, false, "BUILD_Allied_Command_Post" );
SetAvailableMapGoals( TEAM.AXIS, true, "MOBILEMORTAR_mtr1" );
Util.DisableGroup( "group12");
Util.DisableGroup( "group8");
Util.EnableGroup( "group9", TEAM.ALLIES);
Util.EnableGroup( "group15", TEAM.AXIS);
Util.MapDebugPrint("shift enter");
},
OnExit = function(ent)
{
SetAvailableMapGoals( TEAM.AXIS, false, "MOUNT_Balcony_MG" );
Util.MapDebugPrint(GetEntName(ent) + " exited aabb trigger");
Util.MapDebugPrint("shift exit");
},
},
fix_truck =
{
Name="fix_truck",
TriggerOnEntity = GetGoal("MOVER_truck").GetEntity(),
OnEnter = function(ent)
{
//Util.MapDebugPrint(GetEntName(ent) + "BarrierPassed");
//Map.RideVehicle.truck.Enabled = true;
//~ Map.EscortVehicle.truck.Enabled = true;
Util.MapDebugPrint("fix it!");
},
OnExit = function(ent)
{
Util.MapDebugPrint(GetEntName(ent) + "exited aabb trigger");
Util.MapDebugPrint("fix exit");
},
},
Quiet = true,
Ammo_Cabinet_north_ammocabinet = "AMMOCAB_north_ammocabinet",
Ammo_Cabinet_south_ammocabinet = "AMMOCAB_south_ammocabinet",
Ammo_Cabinet_steel_ammocabinet = "AMMOCAB_steel_ammocabinet",
Health_Cabinet_north_healthcabinet = "HEALTHCAB_north_healthcabinet",
Health_Cabinet_south_healthcabinet = "HEALTHCAB_south_healthcabinet",
Health_Cabinet_steel_healthcabinet = "HEALTHCAB_steel_healthcabinet",
Call_Artillery_153 = "CALLARTILLERY_153",
Call_Artillery_80 = "CALLARTILLERY_80",
Artillery_D_119 = "ARTILLERY_D_119",
Artillery_D_79 = "ARTILLERY_D_79",
Artillery_S_361 = "ARTILLERY_S_361",
Artillery_S_79 = "ARTILLERY_S_79",
Flag_gold_crate = "FLAG_gold_crate",
Cappoint_53 = "CAPPOINT_53",
Build_Allied_Command_Post = "BUILD_Allied_Command_Post",
Build_Axis_Command_Post = "BUILD_Axis_Command_Post",
Build_Balcony_MG = "BUILD_Balcony_MG",
Build_Bridge = "BUILD_Bridge",
Build_Bridge_1 = "BUILD_Bridge_1",
Build_MG42 = "BUILD_MG42",
Build_Truck = "BUILD_Truck",
Build_Truck_Barrier_1 = "BUILD_Truck_Barrier_1",
Build_Truck_Barrier_2 = "BUILD_Truck_Barrier_2",
Plant_Allied_Command_Post = "PLANT_Allied_Command_Post",
Plant_Axis_Command_Post = "PLANT_Axis_Command_Post",
Plant_Balcony_MG = "PLANT_Balcony_MG",
Plant_Bridge = "PLANT_Bridge",
Plant_Bridge_1 = "PLANT_Bridge_1",
Plant_MG42 = "PLANT_MG42",
Plant_Main_Entrance = "PLANT_Main_Entrance",
Plant_Radio_Wall = "PLANT_Radio_Wall",
Plant_Truck_Barrier_1 = "PLANT_Truck_Barrier_1",
Plant_Truck_Barrier_2 = "PLANT_Truck_Barrier_2",
Mount_Balcony_MG = "MOUNTMG42_Balcony_MG",
Mount_MG42 = "MOUNTMG42_MG42",
Repair_Balcony_MG = "REPAIRMG42_Balcony_MG",
Repair_MG42 = "REPAIRMG42_MG42",
Snipe_354 = "SNIPE_354",
Snipe_SNIPE_2 = "SNIPE_SNIPE_2",
Snipe_SNIPE_3 = "SNIPE_SNIPE_3",
Snipe_SNIPE_9 = "SNIPE_SNIPE_9",
Mover_truck = "MOVER_truck",
Allied_Command_Post_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Allied_Command_Post_Built" );
},
Axis_Command_Post_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Axis_Command_Post_Built" );
},
Balcony_MG_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Balcony_MG_Built" );
},
Bridge_Built = function( trigger )
{
SetAvailableMapGoals( TEAM.ALLIES, false, "BUILD_Bridge" );
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Bridge_1" );
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Allied_Command_Post" );
SetAvailableMapGoals( TEAM.ALLIES, true, "ROUTE_in1" );
Util.MapDebugPrint("bridge built");
},
Bridge_1_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Bridge_1_Built" );
},
MG42_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "MG42_Built" );
},
Truck_Built = function( trigger )
{
Util.SetMaxUsers( 2, "ESCORT_.*" );
Util.MapDebugPrint("truck built");
},
Truck_Barrier_1_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Truck_Barrier_1_Built" );
},
Truck_Barrier_2_Built = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Truck_Barrier_2_Built" );
},
Allied_Command_Post_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Allied_Command_Post_Destroyed" );
},
Axis_Command_Post_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Axis_Command_Post_Destroyed" );
},
Balcony_MG_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Balcony_MG_Destroyed" );
},
Bridge_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Bridge_Destroyed" );
},
Bridge_1_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Bridge_1_Destroyed" );
},
MG42_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "MG42_Destroyed" );
},
Main_Entrance_Destroyed = function( trigger )
{
SetAvailableMapGoals( TEAM.ALLIES, true, "PLANT_Truck_Barrier_2" );
SetAvailableMapGoals( TEAM.AXIS, true, "MOUNT_Balcony_MG" );
Util.DisableGroup( "group7");
Util.EnableGroup( "group8", TEAM.ALLIES);
Util.MapDebugPrint("gate blown");
},
Radio_Wall_Destroyed = function( trigger )
{
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_wall.*" );
Util.DisableGroup( "group16", TEAM.ALLIES);
Util.MapDebugPrint("wall blown");
},
Truck_Barrier_1_Destroyed = function( trigger )
{
Util.MapDebugPrint( "Truck_Barrier_1_Destroyed" );
},
Truck_Barrier_2_Destroyed = function( trigger )
{
if ( TestMap )
{ return; }
Util.MapDebugPrint( "Truck_Barrier_2_Destroyed" );
},
gold_crate_Taken = function( trigger )
{
//~ SetAvailableMapGoals( TEAM.AXIS, true, "ATACK_at.*" );
Util.DisableGroup("group1");
Util.DisableGroup("group2");
Util.EnableGroup( "group3", TEAM.AXIS);
Util.EnableGroup( "group6", TEAM.ALLIES);
SetAvailableMapGoals( TEAM.ALLIES, true, "CAPPOINT_53" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_wall.*" );
Util.MapDebugPrint("gold_crate_Taken");
},
CAPPOINT_53_Captured = function( trigger )
{
Util.DisableGroup("group3");
Util.DisableGroup( "group6");
Util.EnableGroup( "group4", TEAM.ALLIES);
Util.EnableGroup( "group5", TEAM.AXIS);
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_wall.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "PLANT_Truck_Barrier_1" );
SetAvailableMapGoals( TEAM.AXIS, true, "BUILD_Truck_Barrier_1" );
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Truck" );
SetAvailableMapGoals( TEAM.ALLIES, true, "ESCORT_Truck" );
//~ Map.EscortVehicle.truck.Enabled = true;
Util.MapDebugPrint("CAPPOINT_53_Captured");
},
truck_blasted = function( trigger )
{
Util.SetPositionGoal( Map.Build_Truck, Map.Mover_truck );
//~ Map.EscortVehicle.truck.Enabled = false;
SetAvailableMapGoals( TEAM.ALLIES, true, "BUILD_Truck" );
//~ SetAvailableMapGoals( TEAM.ALLIES, false, "ESCORT_Truck" );
Util.SetMaxUsers( 1, "ESCORT_.*" );
Util.MapDebugPrint("truck blasted");
},
gold_crate_returned = function( trigger )
{
Util.EnableGroup( "group1", TEAM.ALLIES);
Util.EnableGroup( "group2", TEAM.AXIS);
Util.DisableGroup( "group3");
Util.DisableGroup( "group6");
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_wall.*" );
Util.MapDebugPrint("crate returned");
},
wall_plant = function( trigger )
{
Util.EnableGroup( "group16", TEAM.ALLIES);
Util.MapDebugPrint("wall plant");
},
wall_defused = function( trigger )
{
Util.DisableGroup( "group16");
Util.MapDebugPrint("wall defused");
},
};
global OnMapLoad = function()
{
if ( TestMapOn )
{ Util.AutoTestMap(); }
OnTrigger( "MISSING_STRING", Map.Allied_Command_Post_Built );
OnTrigger( "MISSING_STRING", Map.Axis_Command_Post_Built );
OnTrigger( "MISSING_STRING", Map.Balcony_MG_Built );
OnTrigger( "Allies have constructed the Bridge!", Map.Bridge_Built );
OnTrigger( "MISSING_STRING", Map.Bridge_1_Built );
OnTrigger( "MISSING_STRING", Map.MG42_Built );
OnTrigger( "The Truck has been repaired!", Map.Truck_Built );
OnTrigger( "MISSING_STRING", Map.Truck_Barrier_1_Built );
OnTrigger( "Truck Barrier #2 has been constructed.", Map.Truck_Barrier_2_Built );
OnTrigger( "MISSING_STRING", Map.Allied_Command_Post_Destroyed );
OnTrigger( "MISSING_STRING", Map.Axis_Command_Post_Destroyed );
OnTrigger( "MISSING_STRING", Map.Balcony_MG_Destroyed );
OnTrigger( "The Bridge has been destroyed!", Map.Bridge_Destroyed );
OnTrigger( "MISSING_STRING", Map.Bridge_1_Destroyed );
OnTrigger( "MISSING_STRING", Map.MG42_Destroyed );
OnTrigger( "the Main Entrance Destroyed.", Map.Main_Entrance_Destroyed );
OnTrigger( "The Radio Room wall has been destroyed!", Map.Radio_Wall_Destroyed );
OnTrigger( "Truck Barrier #1 has been destroyed.", Map.Truck_Barrier_1_Destroyed );
OnTrigger( "MISSING_STRING", Map.Truck_Barrier_2_Destroyed );
OnTrigger( "Allies have stolen The Radar Parts!", Map.gold_crate_Taken );
OnTrigger( "Flag returned gold_crate!", Map.gold_crate_returned );
OnTrigger( "radar_allies_radarw_secured", Map.CAPPOINT_53_Captured );
OnTrigger( "The Truck has been damaged!", Map.truck_blasted );
OnTrigger( "Planted at the Radio Wall.", Map.wall_plant );
OnTrigger( "Defused at the Radio Wall.", Map.wall_defused );
SetAvailableMapGoals( TEAM.AXIS, false, ".*" );
SetAvailableMapGoals( TEAM.ALLIES, false, ".*" );
Util.SetPositionGoal( Map.Build_Truck, Map.Mover_truck );
Util.SetGoalOffset( -28, 0, 0, "PLANT_Main_Entrance" );
Util.SetGoalPosition( -1462.6, 1353.2, 216.787, "PLANT_Truck_Barrier_1" ) ;
Util.SetGoalOffset( -55, -75, 0, "PLANT_Truck_Barrier_2" );
Util.SetGoalPosition( -2188.5, 1307.2, 211.8, "PLANT_Radio_Wall" ) ;
Util.SetGoalOffset( 0, 0, -220, "PLANT_Bridge" );
//~ Util.SetGoalOffset( -55, -55, 0, "PLANT_Truck_Barrier_1" );
//~ Util.SetGoalOffset( 0, -35, -19, "PLANT_Radio_Wall" );
//~ Util.SetGoalOffset( 0, 0, -220, "PLANT_Bridge_1" );
Util.SetMaxUsers( 1, "DEFEND_.*" );
Util.SetMaxUsers( 1, "BUILD_.*" );
Util.SetMaxUsers( 2, "DEFUSE_.*" );
Util.SetMaxUsers( 2, "ESCORT_.*" );
Util.SetMaxUsers( 1, "ATTACK_.*" );
Util.SetMaxUsers( 1, "MOUNTMG42_.*" );
Util.SetMaxUsers( 1, "MOBILEMG42_.*" );
Util.SetMaxUsers( 1, "PLANT_Bridge" );
Util.SetMaxUsers( 1, "REVIVE_.*" );
Util.SetMaxUsers( 1, "AIRSTRIKE_.*" );
Util.SetMaxUsers( 5, "FLAG_gold_crate" );
//~ SetGoalPriority( "MOBILEMORTAR_.*", 0.85, 0, CLASS.SOLDIER );
//~ SetGoalPriority( "PLANT_Command_Post", 0.89, 0, CLASS.COVERTOPS );
//~ SetGoalPriority( "PLANT_Command_Post", 0.0, 0, CLASS.ENGINEER );
SetGoalPriority( "PLANT_Radio_Wall", 0.86, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( "BUILD_Truck", 0.98, TEAM.ALLIES, CLASS.ENGINEER );
SetGoalPriority( "ATTACK_k.*", 0.0, TEAM.ALLIES, CLASS.ENGINEER );
ETUtil.LimitToClass("PLANT_Command_Post", 0, CLASS.COVERTOPS);
ETUtil.LimitToClass("PLANT_Bridge", TEAM.AXIS, CLASS.COVERTOPS);
Wp.SetWaypointFlag( "ass1", "closed", true );
Wp.SetWaypointFlag( "ass2", "closed", false );
Wp.SetWaypointFlag( "ass3", "closed", false );
Wp.SetWaypointFlag( "ass4", "closed", false );
SetMapGoalProperties( "DEFEND_.*", {MinCampTime=30, MaxCampTime=90} );
SetMapGoalProperties( "MOUNT_.*", {MinCampTime=30, MaxCampTime=90} );
SetMapGoalProperties( "MOBILEMG42_.*", {MinCampTime=30, MaxCampTime=90} );
SetMapGoalProperties( "MOUNTMG42_.*", {MinCampTime=30, MaxCampTime=90} );
SetMapGoalProperties( "ATTACK_.*", {MinCampTime=30, MaxCampTime=90} );
OnTriggerRegion(AABB(-1532,1472.5,148.6,-1108,1710,249), Map.Barrierpassed);
OnTriggerRegion(AABB(25.5,1960.6,137,88.7,2428,213), Map.def);
OnTriggerRegion(AABB(1654.5,-1438,-0.875,1811,-882,75.125), Map.barrier2);
OnTriggerRegion(AABB(456.8,97.3,21.9,885.5,203.6,110.8), Map.shift);
OnTriggerRegion(AABB(-1489.5,1120.5,205,-1109,1196.8,288.8), Map.fix_truck);
Util.EnableGroup( "group1", TEAM.ALLIES);
Util.EnableGroup( "group2", TEAM.AXIS);
Util.EnableGroup( "group17"); // routes
Util.EnableGoal("AMMOCAB_.*"); //enables for both teams
Util.EnableGoal("HEALTHCAB_.*"); //enables for both teams
SetAvailableMapGoals( TEAM.ALLIES, false, "ROUTE_in1" );
MapRoutes =
{
CAPPOINT_53 =
{
ROUTE_obj =
{
ROUTE_obj2 =
{
ROUTE_obj1 =
{
ROUTE_obj4 =
{
ROUTE_obj5 =
{
ROUTE_tunnel1 =
{
ROUTE_tunnel2 =
{
},
},
},
ROUTE_tunnel3 =
{
},
},
},
},
},
},
FLAG_gold_crate =
{
ROUTE_spawn3 =
{
ROUTE_in1 =
{
ROUTE_in2 =
{
ROUTE_in3 =
{
ROUTE_in4 =
{
ROUTE_in5 =
{
ROUTE_in6 =
{
ROUTE_in7 =
{
},
},
},
},
},
},
},
},
ROUTE_spawn1 =
{
ROUTE_fs50 =
{
ROUTE_fs51 =
{
ROUTE_fs52 =
{
ROUTE_fs53 =
{
ROUTE_obj1 =
{
},
},
},
},
ROUTE_tunnel2 =
{
ROUTE_tunnel1 =
{
ROUTE_obj4 =
{
ROUTE_obj1 =
{
},
},
},
},
},
},
},
};
MapRoutes.ATTACK_p1 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_p2 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_p3 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_p5 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_p6 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_k1 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_k2 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_k3 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_k4 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_m1 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_m2 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_m3 = MapRoutes.FLAG_gold_crate;
MapRoutes.ATTACK_m4 = MapRoutes.FLAG_gold_crate;
MapRoutes.PLANT_Radio_Wall = MapRoutes.FLAG_gold_crate;
MapRoutes.PLANT_Truck_Barrier_1 = MapRoutes.FLAG_gold_crate;
Util.Routes(MapRoutes);
Util.MapDebugPrint("OnMapLoad");
};
global OnBotJoin = function( bot )
{
bot.TargetBreakableDist = 100.0;
};
| 0 | 0.95663 | 1 | 0.95663 | game-dev | MEDIA | 0.974575 | game-dev | 0.77866 | 1 | 0.77866 |
s-nakaoka/choreonoid | 2,879 | src/BodyPlugin/CollisionSeqItem.cpp | /**
@file
@author Shizuko Hattori
*/
#include "CollisionSeqItem.h"
#include <cnoid/ItemManager>
#include <cnoid/Archive>
#include "gettext.h"
using namespace std;
using namespace std::placeholders;
using namespace cnoid;
namespace {
}
namespace cnoid {
class CollisionSeqItemImpl
{
public:
CollisionSeqItem* self;
CollisionSeqItemImpl(CollisionSeqItem* self);
~CollisionSeqItemImpl();
void initialize();
};
}
static bool fileIoSub(CollisionSeqItem* item, std::ostream& os, bool loaded, bool isLoading)
{
if(!loaded){
os << item->collisionSeq()->seqMessage();
}
return loaded;
}
static bool loadStandardYamlFormat(CollisionSeqItem* item, const std::string& filename, std::ostream& os)
{
return fileIoSub(item, os, item->collisionSeq()->loadStandardYAMLformat(filename), true);
}
static bool saveAsStandardYamlFormat(CollisionSeqItem* item, const std::string& filename, std::ostream& os)
{
return fileIoSub(item, os, item->collisionSeq()->saveAsStandardYAMLformat(filename), false);
}
void CollisionSeqItem::initislizeClass(ExtensionManager* ext)
{
static bool initialized = false;
if(initialized){
return;
}
ItemManager& im = ext->itemManager();
im.registerClass<CollisionSeqItem, AbstractMultiSeqItem>(N_("CollisionSeqItem"));
im.addLoaderAndSaver<CollisionSeqItem>(
_("Collision Data"), "COLLISION-DATA-YAML", "yaml",
std::bind(loadStandardYamlFormat, _1, _2, _3), std::bind(saveAsStandardYamlFormat, _1, _2, _3));
initialized = true;
}
CollisionSeqItem::CollisionSeqItem()
: collisionSeq_(new CollisionSeq(this))
{
impl = new CollisionSeqItemImpl(this);
}
CollisionSeqItem::CollisionSeqItem(const CollisionSeqItem& org)
: AbstractMultiSeqItem(org),
collisionSeq_(new CollisionSeq(this))
{
impl = new CollisionSeqItemImpl(this);
}
CollisionSeqItemImpl::CollisionSeqItemImpl(CollisionSeqItem* self)
:self(self)
{
initialize();
}
void CollisionSeqItemImpl::initialize()
{
}
CollisionSeqItem::~CollisionSeqItem()
{
delete impl;
}
CollisionSeqItemImpl::~CollisionSeqItemImpl()
{
}
std::shared_ptr<AbstractMultiSeq> CollisionSeqItem::abstractMultiSeq()
{
return collisionSeq_;
}
Item* CollisionSeqItem::doDuplicate() const
{
return new CollisionSeqItem(*this);
}
bool CollisionSeqItem::store(Archive& archive)
{
if(overwrite() || !filePath().empty()){
archive.writeRelocatablePath("filename", filePath());
archive.write("format", fileFormat());
return true;
}
return false;
}
bool CollisionSeqItem::restore(const Archive& archive)
{
std::string filename, format;
if(archive.readRelocatablePath("filename", filename) && archive.read("format", format)){
if(load(filename, format)){
return true;
}
}
return false;
}
| 0 | 0.806164 | 1 | 0.806164 | game-dev | MEDIA | 0.656882 | game-dev | 0.700727 | 1 | 0.700727 |
Blood-Asp/GT5-Unofficial | 1,501 | src/main/java/gregtech/common/tools/GT_Tool_Knife.java | package gregtech.common.tools;
import gregtech.api.enums.Textures;
import gregtech.api.interfaces.IIconContainer;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
public class GT_Tool_Knife
extends GT_Tool_Sword {
public int getToolDamagePerBlockBreak() {
return 100;
}
public int getToolDamagePerDropConversion() {
return 100;
}
public int getToolDamagePerContainerCraft() {
return 100;
}
public int getToolDamagePerEntityAttack() {
return 200;
}
public float getBaseDamage() {
return 2.0F;
}
public float getSpeedMultiplier() {
return 0.5F;
}
public float getMaxDurabilityMultiplier() {
return 1.0F;
}
public IIconContainer getIcon(boolean aIsToolHead, ItemStack aStack) {
return aIsToolHead ? Textures.ItemIcons.KNIFE : null;
}
public IChatComponent getDeathMessage(EntityLivingBase aPlayer, EntityLivingBase aEntity) {
return new ChatComponentText("<" + EnumChatFormatting.RED + aEntity.getCommandSenderName() + EnumChatFormatting.WHITE + "> " + EnumChatFormatting.GREEN + aPlayer.getCommandSenderName() + EnumChatFormatting.WHITE + " what are you doing?, " + EnumChatFormatting.GREEN + aPlayer.getCommandSenderName() + EnumChatFormatting.WHITE + "?!? STAHP!!!");
}
}
| 0 | 0.777909 | 1 | 0.777909 | game-dev | MEDIA | 0.99036 | game-dev | 0.946123 | 1 | 0.946123 |
Guayabazo/InfiniteDynamicWaterURP | 3,269 | Assets/Scripts/Floater.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(WaterManager))]
public class Floater : MonoBehaviour
{
public Transform[] floaters;
private bool[] underWaterFloater;
private bool[] wasUnderWaterFloater;
public float floatingPower = 15f;
WaterManager waterManager;
Rigidbody rb;
public bool underwater;
public bool wasOnWater;
public ParticleSystem[] inOut;
public ParticleSystem[] moving;
void Start()
{
rb = GetComponent<Rigidbody>();
waterManager = GetComponent<WaterManager>();
wasUnderWaterFloater = new bool[floaters.Length];
underWaterFloater = new bool[floaters.Length];
}
void FixedUpdate()
{
if (waterManager.oceanMat != null)
{
Vector2 vel = new(rb.velocity.x, rb.velocity.z);
for (int i = 0; i < floaters.Length; i++)
{
ParticleSystem.EmissionModule movingEmission;
if (moving[i]!= null)
movingEmission = moving[i].emission;
float difference = floaters[i].position.y - waterManager.WaterHeightAtPosition(floaters[i].position);
if (difference < 0)
{
underwater = true;
underWaterFloater[i] = true;
float submersion = Mathf.Clamp01(Mathf.Abs(difference));
rb.AddForceAtPosition(Vector3.up * floatingPower * Mathf.Abs(submersion), floaters[i].position, ForceMode.Force);
if (moving[i] != null && !movingEmission.enabled && vel.magnitude > 0.2f)
movingEmission.enabled = true;
}
else
{
underWaterFloater[i] = false;
underwater = false;
for (int j = 0; j < floaters.Length; j++)
{
if (underWaterFloater[j])
{
underwater = true;
break;
}
}
if (moving[i] != null && movingEmission.enabled)
{
movingEmission.enabled = false;
}
}
if (vel.magnitude <= 0.2f && moving[i] != null && movingEmission.enabled)
{
movingEmission.enabled = false;
}
if (underWaterFloater[i] != wasUnderWaterFloater[i] && inOut[i]!= null)
{
ParticleSystem.MainModule displacementPar = inOut[i].main;
float colorMultiplier = Mathf.Abs(rb.velocity.y * 0.1f);
colorMultiplier = Mathf.Clamp(colorMultiplier, 0f, 0.75f);
displacementPar.startColor = Color.white * colorMultiplier;
inOut[i].Play();
}
wasUnderWaterFloater[i] = underWaterFloater[i];
}
}
}
}
| 0 | 0.815463 | 1 | 0.815463 | game-dev | MEDIA | 0.974666 | game-dev | 0.980654 | 1 | 0.980654 |
Gaby-Station/Gaby-Station | 4,023 | Content.Shared/Temperature/Systems/SharedEntityHeaterSystem.cs | using Content.Shared.Examine;
using Content.Shared.Popups;
using Content.Shared.Power;
using Content.Shared.Power.EntitySystems;
using Content.Shared.Temperature.Components;
using Content.Shared.Verbs;
using Robust.Shared.Audio.Systems;
namespace Content.Shared.Temperature.Systems;
/// <summary>
/// Handles <see cref="EntityHeaterComponent"/> events.
/// </summary>
public abstract partial class SharedEntityHeaterSystem : EntitySystem
{
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
[Dependency] private readonly SharedPowerReceiverSystem _receiver = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
private readonly int _settingCount = Enum.GetValues<EntityHeaterSetting>().Length;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<EntityHeaterComponent, ExaminedEvent>(OnExamined);
SubscribeLocalEvent<EntityHeaterComponent, GetVerbsEvent<AlternativeVerb>>(OnGetVerbs);
SubscribeLocalEvent<EntityHeaterComponent, PowerChangedEvent>(OnPowerChanged);
}
private void OnExamined(Entity<EntityHeaterComponent> ent, ref ExaminedEvent args)
{
if (!args.IsInDetailsRange)
return;
args.PushMarkup(Loc.GetString("entity-heater-examined", ("setting", ent.Comp.Setting)));
}
private void OnGetVerbs(Entity<EntityHeaterComponent> ent, ref GetVerbsEvent<AlternativeVerb> args)
{
if (!args.CanAccess || !args.CanInteract)
return;
var nextSettingIndex = ((int)ent.Comp.Setting + 1) % _settingCount;
var nextSetting = (EntityHeaterSetting)nextSettingIndex;
var user = args.User;
args.Verbs.Add(new AlternativeVerb()
{
Text = Loc.GetString("entity-heater-switch-setting", ("setting", nextSetting)),
Act = () =>
{
ChangeSetting(ent, nextSetting, user);
}
});
}
private void OnPowerChanged(Entity<EntityHeaterComponent> ent, ref PowerChangedEvent args)
{
// disable heating element glowing layer if theres no power
// doesn't actually change the setting since that would be annoying
var setting = args.Powered ? ent.Comp.Setting : EntityHeaterSetting.Off;
_appearance.SetData(ent, EntityHeaterVisuals.Setting, setting);
}
protected virtual void ChangeSetting(Entity<EntityHeaterComponent> ent, EntityHeaterSetting setting, EntityUid? user = null)
{
// Still allow changing the setting without power
ent.Comp.Setting = setting;
_audio.PlayPredicted(ent.Comp.SettingSound, ent, user);
_popup.PopupClient(Loc.GetString("entity-heater-switched-setting", ("setting", setting)), ent, user);
Dirty(ent);
// Only show the glowing heating element layer if there's power
if (_receiver.IsPowered(ent.Owner))
_appearance.SetData(ent, EntityHeaterVisuals.Setting, setting);
}
protected float SettingPower(EntityHeaterSetting setting, float max)
{
// Power use while off needs to be non-zero so powernet doesn't consider the device powered
// by an unpowered network while in the off state. Otherwise, when we increase the load,
// the clientside APC receiver will think the device is powered until it gets the next
// update from the server, which will cause the heating element to glow for a moment.
// I spent several hours trying to figure out a better way to do this using PowerDisabled
// or something, but nothing worked as well as this.
// Just think of the load as a little LED, or bad wiring, or something.
return setting switch
{
EntityHeaterSetting.Low => max / 3f,
EntityHeaterSetting.Medium => max * 2f / 3f,
EntityHeaterSetting.High => max,
_ => 0.01f,
};
}
}
| 0 | 0.758765 | 1 | 0.758765 | game-dev | MEDIA | 0.924383 | game-dev | 0.884424 | 1 | 0.884424 |
NeotokyoRebuild/neo | 1,444 | src/game/server/ai_basehumanoid.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef AI_BASEHUMANOID_H
#define AI_BASEHUMANOID_H
#include "ai_behavior.h"
#include "ai_blended_movement.h"
//-----------------------------------------------------------------------------
// CLASS: CAI_BaseHumanoid
//-----------------------------------------------------------------------------
typedef CAI_BlendingHost< CAI_BehaviorHost<CAI_BaseNPC> > CAI_BaseHumanoidBase;
class CAI_BaseHumanoid : public CAI_BaseHumanoidBase
{
DECLARE_CLASS( CAI_BaseHumanoid, CAI_BaseHumanoidBase );
public:
bool HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt);
// Tasks
virtual void StartTask( const Task_t *pTask );
virtual void RunTask( const Task_t *pTask );
virtual void BuildScheduleTestBits( );
// Navigation
bool OnMoveBlocked( AIMoveResult_t *pResult );
// Damage
void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator );
// Various start tasks
virtual void StartTaskRangeAttack1( const Task_t *pTask );
// Various run tasks
virtual void RunTaskRangeAttack1( const Task_t *pTask );
// Purpose: check ammo
virtual void CheckAmmo( void );
};
//-----------------------------------------------------------------------------
#endif
| 0 | 0.93312 | 1 | 0.93312 | game-dev | MEDIA | 0.96149 | game-dev | 0.606481 | 1 | 0.606481 |
hojat72elect/libgdx_games | 6,439 | Color_Shooter/core/src/com/salvai/centrum/screens/LevelChooseScreen.kt | package com.salvai.centrum.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputMultiplexer
import com.badlogic.gdx.ScreenAdapter
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.salvai.centrum.CentrumGameClass
import com.salvai.centrum.enums.GameType
import com.salvai.centrum.input.CatchBackKeyProcessor
import com.salvai.centrum.utils.Constants
class LevelChooseScreen(private val game: CentrumGameClass) : ScreenAdapter() {
private val COLUMNS = 5
private val COLORS = 4
private val SIZE = 0.15f //size of buttons % to screen height
@JvmField
var stage: Stage
var width: Float
var height: Float
private val table: Table
init {
height = Gdx.graphics.height * 0.8f
width = Gdx.graphics.width * 0.9f
stage = Stage()
table = Table(game.skin)
table.setSize(width, height)
table.setPosition(Gdx.graphics.width * 0.5f - width * 0.5f, Gdx.graphics.height * 0.5f - height * 0.5f)
setUpTable()
//.setDebug(true);
val scrollPane = ScrollPane(table, game.skin)
scrollPane.setFadeScrollBars(false)
scrollPane.setSize(width, height)
scrollPane.setPosition(Gdx.graphics.width * 0.5f - width * 0.5f, Gdx.graphics.height * 0.5f - height * 0.5f)
stage.addActor(scrollPane)
Gdx.input.isCatchBackKey = true
val multiplexer = InputMultiplexer()
multiplexer.addProcessor(stage)
multiplexer.addProcessor(CatchBackKeyProcessor(game, this)) // Your screen
Gdx.input.inputProcessor = multiplexer
stage.addAction(Actions.sequence(Actions.alpha(0f), Actions.fadeIn(Constants.FADE_TIME)))
}
private fun setUpTable() {
val endlessButton = Button(game.skin, "infinity")
endlessButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
stage.addAction(Actions.sequence(Actions.fadeOut(Constants.FADE_TIME), Actions.run(object : Runnable {
override fun run() {
game.gameType = GameType.ENDLESS
if (game.showTutorial) game.setScreen(TutorialScreen(game))
else game.setScreen(GameScreen(game))
dispose()
}
})))
}
})
table.add<Button?>(endlessButton).colspan(COLUMNS).pad(width * 0.01f).size(width * SIZE * 3).spaceBottom(width * 0.05f)
table.row()
for (i in 0..<game.levels.size) {
setUpLevelButtons(i, game.levelStars[i])
if ((i + 1) % COLUMNS == 0) setupStarsRow(i, game.levelStars)
}
}
private fun setUpLevelButtons(level: Int, levelStars: Int) {
if (levelStars >= 0) {
val levelButton = TextButton("" + (level + 1), game.skin, "level-" + ((level) % COLORS))
levelButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
stage.addAction(Actions.sequence(Actions.fadeOut(Constants.FADE_TIME), Actions.run(object : Runnable {
override fun run() {
game.level = level
if (game.showTutorial) game.setScreen(TutorialScreen(game))
else game.setScreen(GameScreen(game))
dispose()
}
})))
}
})
table.add<TextButton?>(levelButton).size(width * SIZE).pad(width * 0.01f)
} else { //locked
val levelButton = Button(game.skin, "locked-" + ((level) % COLORS))
table.add<Button?>(levelButton).size(width * SIZE).pad(width * 0.01f)
}
}
private fun setupStarsRow(i: Int, levelStars: IntArray) {
//new row
if ((i + 1) % COLUMNS == 0) {
table.row().padTop(-height * 0.04f).height(height * 0.04f).padBottom(0f) //TODO fix stars
//draw stars
for (j in i - COLUMNS + 1..i) {
if (levelStars[j] >= 0) {
val starsButton: Button?
when (levelStars[j]) {
3 -> starsButton = Button(game.skin, "three-star")
2 -> starsButton = Button(game.skin, "two-star")
1 -> starsButton = Button(game.skin, "one-star")
else -> starsButton = Button(game.skin, "no-star")
}
starsButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
stage.addAction(Actions.sequence(Actions.fadeOut(Constants.FADE_TIME), Actions.run(object : Runnable {
override fun run() {
game.level = i
if (game.showTutorial) game.setScreen(TutorialScreen(game))
else game.setScreen(GameScreen(game))
dispose()
}
})))
}
})
table.add<Button?>(starsButton)
}
}
table.row()
}
}
override fun render(delta: Float) {
setupScreen()
game.batch.begin()
game.drawBackground(delta)
game.batch.end()
stage.act(delta)
stage.draw()
}
private fun setupScreen() {
Gdx.gl.glClearColor(Constants.BACKGROUND_COLOR.r, Constants.BACKGROUND_COLOR.g, Constants.BACKGROUND_COLOR.b, Constants.BACKGROUND_COLOR.a)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
}
override fun dispose() {
stage.dispose()
}
}
| 0 | 0.808584 | 1 | 0.808584 | game-dev | MEDIA | 0.89711 | game-dev | 0.955931 | 1 | 0.955931 |
joergoster/Stockfish-NNUE | 13,541 | src/bitboard.h | /*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2015-2020 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
Stockfish 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.
Stockfish 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 BITBOARD_H_INCLUDED
#define BITBOARD_H_INCLUDED
#include <string>
#include "types.h"
namespace Bitbases {
void init();
bool probe(Square wksq, Square wpsq, Square bksq, Color us);
}
namespace Bitboards {
void init();
const std::string pretty(Bitboard b);
}
constexpr Bitboard AllSquares = ~Bitboard(0);
constexpr Bitboard DarkSquares = 0xAA55AA55AA55AA55ULL;
constexpr Bitboard FileABB = 0x0101010101010101ULL;
constexpr Bitboard FileBBB = FileABB << 1;
constexpr Bitboard FileCBB = FileABB << 2;
constexpr Bitboard FileDBB = FileABB << 3;
constexpr Bitboard FileEBB = FileABB << 4;
constexpr Bitboard FileFBB = FileABB << 5;
constexpr Bitboard FileGBB = FileABB << 6;
constexpr Bitboard FileHBB = FileABB << 7;
constexpr Bitboard Rank1BB = 0xFF;
constexpr Bitboard Rank2BB = Rank1BB << (8 * 1);
constexpr Bitboard Rank3BB = Rank1BB << (8 * 2);
constexpr Bitboard Rank4BB = Rank1BB << (8 * 3);
constexpr Bitboard Rank5BB = Rank1BB << (8 * 4);
constexpr Bitboard Rank6BB = Rank1BB << (8 * 5);
constexpr Bitboard Rank7BB = Rank1BB << (8 * 6);
constexpr Bitboard Rank8BB = Rank1BB << (8 * 7);
constexpr Bitboard QueenSide = FileABB | FileBBB | FileCBB | FileDBB;
constexpr Bitboard CenterFiles = FileCBB | FileDBB | FileEBB | FileFBB;
constexpr Bitboard KingSide = FileEBB | FileFBB | FileGBB | FileHBB;
constexpr Bitboard Center = (FileDBB | FileEBB) & (Rank4BB | Rank5BB);
constexpr Bitboard KingFlank[FILE_NB] = {
QueenSide ^ FileDBB, QueenSide, QueenSide,
CenterFiles, CenterFiles,
KingSide, KingSide, KingSide ^ FileEBB
};
extern uint8_t PopCnt16[1 << 16];
extern uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
extern Bitboard SquareBB[SQUARE_NB];
extern Bitboard LineBB[SQUARE_NB][SQUARE_NB];
extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
extern Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
/// Magic holds all magic bitboards relevant data for a single square
struct Magic {
Bitboard mask;
Bitboard magic;
Bitboard* attacks;
unsigned shift;
// Compute the attack's index using the 'magic bitboards' approach
unsigned index(Bitboard occupied) const {
if (HasPext)
return unsigned(pext(occupied, mask));
if (Is64Bit)
return unsigned(((occupied & mask) * magic) >> shift);
unsigned lo = unsigned(occupied) & unsigned(mask);
unsigned hi = unsigned(occupied >> 32) & unsigned(mask >> 32);
return (lo * unsigned(magic) ^ hi * unsigned(magic >> 32)) >> shift;
}
};
extern Magic RookMagics[SQUARE_NB];
extern Magic BishopMagics[SQUARE_NB];
inline Bitboard square_bb(Square s) {
assert(is_ok(s));
return SquareBB[s];
}
/// Overloads of bitwise operators between a Bitboard and a Square for testing
/// whether a given bit is set in a bitboard, and for setting and clearing bits.
inline Bitboard operator&( Bitboard b, Square s) { return b & square_bb(s); }
inline Bitboard operator|( Bitboard b, Square s) { return b | square_bb(s); }
inline Bitboard operator^( Bitboard b, Square s) { return b ^ square_bb(s); }
inline Bitboard& operator|=(Bitboard& b, Square s) { return b |= square_bb(s); }
inline Bitboard& operator^=(Bitboard& b, Square s) { return b ^= square_bb(s); }
inline Bitboard operator&(Square s, Bitboard b) { return b & s; }
inline Bitboard operator|(Square s, Bitboard b) { return b | s; }
inline Bitboard operator^(Square s, Bitboard b) { return b ^ s; }
inline Bitboard operator|(Square s1, Square s2) { return square_bb(s1) | s2; }
constexpr bool more_than_one(Bitboard b) {
return b & (b - 1);
}
/// Counts the occupation of the bitboard depending on the occupation of SQ_A1
/// as in `b & (1ULL << SQ_A1) ? more_than_two(b) : more_than_one(b)`
constexpr bool conditional_more_than_two(Bitboard b) {
return b & (b - 1) & (b - 2);
}
constexpr bool opposite_colors(Square s1, Square s2) {
return (s1 + rank_of(s1) + s2 + rank_of(s2)) & 1;
}
/// rank_bb() and file_bb() return a bitboard representing all the squares on
/// the given file or rank.
constexpr Bitboard rank_bb(Rank r) {
return Rank1BB << (8 * r);
}
constexpr Bitboard rank_bb(Square s) {
return rank_bb(rank_of(s));
}
constexpr Bitboard file_bb(File f) {
return FileABB << f;
}
constexpr Bitboard file_bb(Square s) {
return file_bb(file_of(s));
}
/// shift() moves a bitboard one or two steps as specified by the direction D
template<Direction D>
constexpr Bitboard shift(Bitboard b) {
return D == NORTH ? b << 8 : D == SOUTH ? b >> 8
: D == NORTH+NORTH? b <<16 : D == SOUTH+SOUTH? b >>16
: D == EAST ? (b & ~FileHBB) << 1 : D == WEST ? (b & ~FileABB) >> 1
: D == NORTH_EAST ? (b & ~FileHBB) << 9 : D == NORTH_WEST ? (b & ~FileABB) << 7
: D == SOUTH_EAST ? (b & ~FileHBB) >> 7 : D == SOUTH_WEST ? (b & ~FileABB) >> 9
: 0;
}
/// pawn_attacks_bb() returns the squares attacked by pawns of the given color
/// from the squares in the given bitboard.
template<Color C>
constexpr Bitboard pawn_attacks_bb(Bitboard b) {
return C == WHITE ? shift<NORTH_WEST>(b) | shift<NORTH_EAST>(b)
: shift<SOUTH_WEST>(b) | shift<SOUTH_EAST>(b);
}
inline Bitboard pawn_attacks_bb(Color c, Square s) {
assert(is_ok(s));
return PawnAttacks[c][s];
}
/// pawn_double_attacks_bb() returns the squares doubly attacked by pawns of the
/// given color from the squares in the given bitboard.
template<Color C>
constexpr Bitboard pawn_double_attacks_bb(Bitboard b) {
return C == WHITE ? shift<NORTH_WEST>(b) & shift<NORTH_EAST>(b)
: shift<SOUTH_WEST>(b) & shift<SOUTH_EAST>(b);
}
/// adjacent_files_bb() returns a bitboard representing all the squares on the
/// adjacent files of a given square.
constexpr Bitboard adjacent_files_bb(Square s) {
return shift<EAST>(file_bb(s)) | shift<WEST>(file_bb(s));
}
/// line_bb() returns a bitboard representing an entire line (from board edge
/// to board edge) that intersects the two given squares. If the given squares
/// are not on a same file/rank/diagonal, the function returns 0. For instance,
/// line_bb(SQ_C4, SQ_F7) will return a bitboard with the A2-G8 diagonal.
inline Bitboard line_bb(Square s1, Square s2) {
assert(is_ok(s1) && is_ok(s2));
return LineBB[s1][s2];
}
/// between_bb() returns a bitboard representing squares that are linearly
/// between the two given squares (excluding the given squares). If the given
/// squares are not on a same file/rank/diagonal, we return 0. For instance,
/// between_bb(SQ_C4, SQ_F7) will return a bitboard with squares D5 and E6.
inline Bitboard between_bb(Square s1, Square s2) {
Bitboard b = line_bb(s1, s2) & ((AllSquares << s1) ^ (AllSquares << s2));
return b & (b - 1); //exclude lsb
}
/// forward_ranks_bb() returns a bitboard representing the squares on the ranks
/// in front of the given one, from the point of view of the given color. For instance,
/// forward_ranks_bb(BLACK, SQ_D3) will return the 16 squares on ranks 1 and 2.
constexpr Bitboard forward_ranks_bb(Color c, Square s) {
return c == WHITE ? ~Rank1BB << 8 * relative_rank(WHITE, s)
: ~Rank8BB >> 8 * relative_rank(BLACK, s);
}
/// forward_file_bb() returns a bitboard representing all the squares along the
/// line in front of the given one, from the point of view of the given color.
constexpr Bitboard forward_file_bb(Color c, Square s) {
return forward_ranks_bb(c, s) & file_bb(s);
}
/// pawn_attack_span() returns a bitboard representing all the squares that can
/// be attacked by a pawn of the given color when it moves along its file, starting
/// from the given square.
constexpr Bitboard pawn_attack_span(Color c, Square s) {
return forward_ranks_bb(c, s) & adjacent_files_bb(s);
}
/// passed_pawn_span() returns a bitboard which can be used to test if a pawn of
/// the given color and on the given square is a passed pawn.
constexpr Bitboard passed_pawn_span(Color c, Square s) {
return pawn_attack_span(c, s) | forward_file_bb(c, s);
}
/// aligned() returns true if the squares s1, s2 and s3 are aligned either on a
/// straight or on a diagonal line.
inline bool aligned(Square s1, Square s2, Square s3) {
return line_bb(s1, s2) & s3;
}
/// distance() functions return the distance between x and y, defined as the
/// number of steps for a king in x to reach y.
template<typename T1 = Square> inline int distance(Square x, Square y);
template<> inline int distance<File>(Square x, Square y) { return std::abs(file_of(x) - file_of(y)); }
template<> inline int distance<Rank>(Square x, Square y) { return std::abs(rank_of(x) - rank_of(y)); }
template<> inline int distance<Square>(Square x, Square y) { return SquareDistance[x][y]; }
inline int edge_distance(File f) { return std::min(f, File(FILE_H - f)); }
inline int edge_distance(Rank r) { return std::min(r, Rank(RANK_8 - r)); }
/// safe_destination() returns the bitboard of target square for the given step
/// from the given square. If the step is off the board, returns empty bitboard.
inline Bitboard safe_destination(Square s, int step)
{
Square to = Square(s + step);
return is_ok(to) && distance(s, to) <= 2 ? square_bb(to) : Bitboard(0);
}
/// attacks_bb(Square) returns the pseudo attacks of the give piece type
/// assuming an empty board.
template<PieceType Pt>
inline Bitboard attacks_bb(Square s) {
assert((Pt != PAWN) && (is_ok(s)));
return PseudoAttacks[Pt][s];
}
/// attacks_bb(Square, Bitboard) returns the attacks by the given piece
/// assuming the board is occupied according to the passed Bitboard.
/// Sliding piece attacks do not continue passed an occupied square.
template<PieceType Pt>
inline Bitboard attacks_bb(Square s, Bitboard occupied) {
assert((Pt != PAWN) && (is_ok(s)));
switch (Pt)
{
case BISHOP: return BishopMagics[s].attacks[BishopMagics[s].index(occupied)];
case ROOK : return RookMagics[s].attacks[ RookMagics[s].index(occupied)];
case QUEEN : return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
default : return PseudoAttacks[Pt][s];
}
}
inline Bitboard attacks_bb(PieceType pt, Square s, Bitboard occupied) {
assert((pt != PAWN) && (is_ok(s)));
switch (pt)
{
case BISHOP: return attacks_bb<BISHOP>(s, occupied);
case ROOK : return attacks_bb< ROOK>(s, occupied);
case QUEEN : return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
default : return PseudoAttacks[pt][s];
}
}
/// popcount() counts the number of non-zero bits in a bitboard
inline int popcount(Bitboard b) {
#ifndef USE_POPCNT
union { Bitboard bb; uint16_t u[4]; } v = { b };
return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]];
#elif defined(_MSC_VER) || defined(__INTEL_COMPILER)
return (int)_mm_popcnt_u64(b);
#else // Assumed gcc or compatible compiler
return __builtin_popcountll(b);
#endif
}
/// lsb() and msb() return the least/most significant bit in a non-zero bitboard
#if defined(__GNUC__) // GCC, Clang, ICC
inline Square lsb(Bitboard b) {
assert(b);
return Square(__builtin_ctzll(b));
}
inline Square msb(Bitboard b) {
assert(b);
return Square(63 ^ __builtin_clzll(b));
}
#elif defined(_MSC_VER) // MSVC
#ifdef _WIN64 // MSVC, WIN64
inline Square lsb(Bitboard b) {
assert(b);
unsigned long idx;
_BitScanForward64(&idx, b);
return (Square) idx;
}
inline Square msb(Bitboard b) {
assert(b);
unsigned long idx;
_BitScanReverse64(&idx, b);
return (Square) idx;
}
#else // MSVC, WIN32
inline Square lsb(Bitboard b) {
assert(b);
unsigned long idx;
if (b & 0xffffffff) {
_BitScanForward(&idx, int32_t(b));
return Square(idx);
} else {
_BitScanForward(&idx, int32_t(b >> 32));
return Square(idx + 32);
}
}
inline Square msb(Bitboard b) {
assert(b);
unsigned long idx;
if (b >> 32) {
_BitScanReverse(&idx, int32_t(b >> 32));
return Square(idx + 32);
} else {
_BitScanReverse(&idx, int32_t(b));
return Square(idx);
}
}
#endif
#else // Compiler is neither GCC nor MSVC compatible
#error "Compiler not supported."
#endif
/// pop_lsb() finds and clears the least significant bit in a non-zero bitboard
inline Square pop_lsb(Bitboard* b) {
assert(*b);
const Square s = lsb(*b);
*b &= *b - 1;
return s;
}
/// frontmost_sq() returns the most advanced square for the given color,
/// requires a non-zero bitboard.
inline Square frontmost_sq(Color c, Bitboard b) {
assert(b);
return c == WHITE ? msb(b) : lsb(b);
}
#endif // #ifndef BITBOARD_H_INCLUDED
| 0 | 0.98616 | 1 | 0.98616 | game-dev | MEDIA | 0.507216 | game-dev | 0.972756 | 1 | 0.972756 |
Tencent/behaviac | 4,491 | integration/unity/Assets/behaviac/workspace/behaviors/node_test/htn/travel/travel_by_air.xml | <?xml version="1.0" encoding="utf-8"?>
<Behavior Version="5">
<Node Class="Behaviac.Design.Nodes.Behavior" AgentType="HTNAgentTravel" Domains="" Enable="true" HasOwnPrefabData="false" Id="-1" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Parameters>
<Parameter Name="ax" Type="System.Int32" DefaultValue="0" DisplayName="ax" Desc="HTNAgentTravel::ax" Display="true" />
<Parameter Name="ay" Type="System.Int32" DefaultValue="0" DisplayName="ay" Desc="HTNAgentTravel::ay" Display="true" />
<Parameter Name="as" Type="System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]" DefaultValue="0:" DisplayName="as" Desc="HTNAgentTravel::as" Display="true" />
<Parameter Name="_$local_task_param_$_0" Type="System.Int32" DefaultValue="0" DisplayName="x" Desc="HTNAgentTravel::_$local_task_param_$_0" Display="false" />
<Parameter Name="_$local_task_param_$_1" Type="System.Int32" DefaultValue="0" DisplayName="y" Desc="HTNAgentTravel::_$local_task_param_$_1" Display="false" />
</Parameters>
<DescriptorRefs value="0:" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Task" Enable="true" HasOwnPrefabData="false" Id="0" PrefabName="" PrefabNodeId="-1" Prototype="Self.HTNAgentTravel::travel_by_air(0,0)">
<Comment Background="NoColor" Text="" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Method" Enable="true" HasOwnPrefabData="false" Id="1" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Attachment Class="PluginBehaviac.Events.Precondition" BinaryOperator="And" Enable="true" Id="2" Operator="Equal" Opl="Self.HTNAgentTravel::exist_airports(int Self.HTNAgentTravel::_$local_task_param_$_0,vector<int> Self.HTNAgentTravel::as)" Opr1="""" Opr2="const bool true" Phase="Enter" PrefabAttachmentId="-1" />
<Attachment Class="PluginBehaviac.Events.Precondition" BinaryOperator="And" Enable="true" Id="3" Operator="Equal" Opl="Self.HTNAgentTravel::exist_airport(int Self.HTNAgentTravel::_$local_task_param_$_1,int Self.HTNAgentTravel::ay)" Opr1="""" Opr2="const bool true" Phase="Enter" PrefabAttachmentId="-1" />
<Connector Identifier="Tasks">
<Node Class="PluginBehaviac.Nodes.DecoratorIterator" DecorateWhenChildEnds="false" Enable="true" HasOwnPrefabData="false" Id="5" Opl="int Self.HTNAgentTravel::ax" Opr="vector<int> Self.HTNAgentTravel::as" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Sequence" Enable="true" HasOwnPrefabData="false" Id="6" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Connector Identifier="GenericChildren">
<Node Class="Behaviac.Design.Nodes.ReferencedBehavior" Enable="true" HasOwnPrefabData="false" Id="8" PrefabName="" PrefabNodeId="-1" ReferenceBehavior="const string "node_test/htn/travel/travel"" Task="Self.HTNAgentTravel::travel(int Self.HTNAgentTravel::_$local_task_param_$_0,int Self.HTNAgentTravel::ax)">
<Comment Background="Gray" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Action" Enable="true" HasOwnPrefabData="false" Id="7" Method="Self.HTNAgentTravel::fly(int Self.HTNAgentTravel::ax,int Self.HTNAgentTravel::ay)" PrefabName="" PrefabNodeId="-1" ResultFunctor="""" ResultOption="BT_SUCCESS">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="Behaviac.Design.Nodes.ReferencedBehavior" Enable="true" HasOwnPrefabData="false" Id="4" PrefabName="" PrefabNodeId="-1" ReferenceBehavior="const string "node_test/htn/travel/travel"" Task="Self.HTNAgentTravel::travel(int Self.HTNAgentTravel::ay,int Self.HTNAgentTravel::_$local_task_param_$_1)">
<Comment Background="Gray" Text="" />
</Node>
</Connector>
</Node>
</Connector>
</Node>
</Connector>
</Node>
</Connector>
</Node>
</Connector>
</Node>
</Behavior> | 0 | 0.878702 | 1 | 0.878702 | game-dev | MEDIA | 0.231582 | game-dev | 0.642408 | 1 | 0.642408 |
magefree/mage | 2,190 | Mage.Sets/src/mage/cards/g/GrondTheGatebreaker.java | package mage.cards.g;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.condition.CompoundCondition;
import mage.abilities.condition.Condition;
import mage.abilities.condition.common.MyTurnCondition;
import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition;
import mage.abilities.decorator.ConditionalContinuousEffect;
import mage.abilities.effects.common.continuous.AddCardTypeSourceEffect;
import mage.abilities.keyword.CrewAbility;
import mage.abilities.keyword.TrampleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.filter.common.FilterControlledPermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class GrondTheGatebreaker extends CardImpl {
private static final Condition condition = new CompoundCondition(
MyTurnCondition.instance, new PermanentsOnTheBattlefieldCondition(new FilterControlledPermanent(SubType.ARMY))
);
public GrondTheGatebreaker(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{3}{B}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.VEHICLE);
this.power = new MageInt(5);
this.toughness = new MageInt(5);
// Trample
this.addAbility(TrampleAbility.getInstance());
// As long as it's your turn and you control an Army, Grond, the Gatebreaker is an artifact creature.
this.addAbility(new SimpleStaticAbility(new ConditionalContinuousEffect(
new AddCardTypeSourceEffect(Duration.WhileOnBattlefield, CardType.ARTIFACT, CardType.CREATURE),
condition, "as long as it's your turn and you control an Army, {this} is an artifact creature"
)));
// Crew 3
this.addAbility(new CrewAbility(3));
}
private GrondTheGatebreaker(final GrondTheGatebreaker card) {
super(card);
}
@Override
public GrondTheGatebreaker copy() {
return new GrondTheGatebreaker(this);
}
}
| 0 | 0.900426 | 1 | 0.900426 | game-dev | MEDIA | 0.962268 | game-dev | 0.99208 | 1 | 0.99208 |
geeksville/arduleader | 4,139 | common/src/main/scala/com/geeksville/mavlink/HeartbeatMonitor.scala | package com.geeksville.mavlink
import com.geeksville.akka.InstrumentedActor
import org.mavlink.messages.MAVLinkMessage
import org.mavlink.messages.ardupilotmega._
import LogIncomingMavlink._
import scala.concurrent._
import scala.concurrent.duration._
import com.geeksville.akka.EventStream
import org.mavlink.messages.MAV_TYPE
import org.mavlink.messages.MAV_MODE_FLAG
import akka.actor.Cancellable
case class MsgHeartbeatLost(id: Int)
case class MsgHeartbeatFound(id: Int)
case class MsgArmChanged(armed: Boolean)
case class MsgSystemStatusChanged(stat: Option[Int])
/**
* Watches for arrival of a heartbeat, if we don't see one we print an error message
*/
trait HeartbeatMonitor extends InstrumentedActor {
import context._
private case object WatchdogExpired
val eventStream = new EventStream
private var timer: Option[Cancellable] = None
private var mySysId: Option[Int] = None
var customMode: Option[Int] = None
var baseMode: Option[Int] = None
var systemStatus: Option[Int] = None
/// A MAV_TYPE vehicle code
var vehicleType: Option[Int] = None
// A MAV_AUTOPILOT autopilot mfg code
var autopilotType: Option[Int] = None
/// Has the vehicle been armed (ever) during this session
var hasBeenArmed = false
def isArmed: Boolean = baseMode.map(isArmed).getOrElse(false)
/// Parse a baseMode to see if we are armed
private def isArmed(m: Int): Boolean = (m & MAV_MODE_FLAG.MAV_MODE_FLAG_SAFETY_ARMED) != 0
def hasHeartbeat = mySysId.isDefined
def heartbeatSysId = mySysId
protected def publishEvent(a: Any) { eventStream.publish(a) }
def onReceive = {
case msg: msg_heartbeat =>
// We don't care about the heartbeats from a GCS
val typ = msg.`type`
if (typ != MAV_TYPE.MAV_TYPE_GCS) {
val oldVal = customMode
val oldBase = baseMode
val newVal = msg.custom_mode.toInt
val oldArmed = isArmed
val oldStatus = systemStatus
customMode = Some(newVal)
baseMode = Some(msg.base_mode)
autopilotType = Some(msg.autopilot)
systemStatus = Some(msg.system_status)
val oldVehicle = vehicleType
vehicleType = Some(typ)
// This will call onHeartbeatChanged
resetWatchdog(msg.sysId)
if (oldVal != customMode || oldVehicle != vehicleType || baseMode != oldBase)
onModeChanged(oldVal, newVal)
if (oldArmed != isArmed)
onArmedChanged(isArmed)
if (systemStatus != oldStatus)
onSystemStatusChanged(systemStatus)
}
//case msg: MAVLinkMessage => log.warn(s"Unknown mavlink msg: ${msg.messageType} $msg")
case WatchdogExpired =>
forceLostHeartbeat()
}
/**
* Declare that we don't have heartbeat anymore (possibly due to some non timer based knowledge)
*/
protected def forceLostHeartbeat() {
cancelWatchdog()
mySysId.foreach { id =>
publishEvent(MsgHeartbeatLost(id))
mySysId = None
systemStatus = None
onHeartbeatLost()
onSystemStatusChanged(systemStatus)
}
}
override def postStop() {
cancelWatchdog()
super.postStop()
}
protected def onArmedChanged(armed: Boolean) {
log.info("Armed changed: " + armed)
if (armed)
hasBeenArmed = true
publishEvent(MsgArmChanged(armed))
}
protected def onModeChanged(old: Option[Int], m: Int) {
log.info(s"Mode change, $old -> $m")
}
protected def onSystemStatusChanged(m: Option[Int]) {
log.error("Received new status: " + m)
publishEvent(MsgSystemStatusChanged(m))
}
protected def onHeartbeatLost() {
log.error("Lost heartbeat")
}
protected def onHeartbeatFound() {
mySysId.foreach { id => log.info("Contact established with sysId " + id) }
}
private def resetWatchdog(sysId: Int) {
if (!mySysId.isDefined) {
mySysId = Some(sysId)
onHeartbeatFound()
publishEvent(MsgHeartbeatFound(sysId))
}
cancelWatchdog()
timer = Some(context.system.scheduler.scheduleOnce(30 seconds, self, WatchdogExpired))
}
private def cancelWatchdog() {
timer.foreach(_.cancel())
timer = None
}
}
| 0 | 0.692115 | 1 | 0.692115 | game-dev | MEDIA | 0.414301 | game-dev | 0.969452 | 1 | 0.969452 |
Kaioru/Edelstein | 4,752 | src/common/Edelstein.Common.Gameplay.Shop/ShopStage.cs | using Edelstein.Common.Gameplay.Handling;
using Edelstein.Common.Gameplay.Models.Characters;
using Edelstein.Common.Utilities.Packets;
using Edelstein.Protocol.Gameplay.Shop;
using Edelstein.Protocol.Gameplay.Shop.Commodities;
namespace Edelstein.Common.Gameplay.Shop;
public class ShopStage : AbstractStage<IShopStageUser>, IShopStage
{
public ShopStage(string id) => ID = id;
public override string ID { get; }
public new async Task Enter(IShopStageUser user)
{
if (user.Account == null || user.AccountWorld == null || user.Character == null)
{
await user.Disconnect();
return;
}
using var packet = new PacketWriter(PacketSendOperations.SetCashShop);
packet.WriteCharacterData(
user.Character,
DbFlags.Character |
DbFlags.Money |
DbFlags.ItemSlotEquip |
DbFlags.ItemSlotConsume |
DbFlags.ItemSlotInstall |
DbFlags.ItemSlotEtc |
DbFlags.ItemSlotCash |
DbFlags.InventorySize
);
packet.WriteBool(true); // CashShopAuthorized
packet.WriteString(user.Account.Username);
var notSale = await user.Context.Managers.NotSale.RetrieveAll();
packet.WriteInt(notSale.Count);
foreach (var commodity in notSale)
packet.WriteInt(commodity.ID);
var modifiedCommodities = await user.Context.Managers.ModifiedCommodity.RetrieveAll();
packet.WriteShort((short)modifiedCommodities.Count);
foreach (var modified in modifiedCommodities)
{
packet.WriteInt(modified.ID);
packet.WriteInt((int)modified.Flags);
if (modified.Flags.HasFlag(CommodityFlags.ItemID))
packet.WriteInt(modified.ItemID ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.Count))
packet.WriteShort(modified.Count ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.Priority))
packet.WriteByte(modified.Priority ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.Price))
packet.WriteInt(modified.Price ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.Bonus))
packet.WriteBool(modified.Bonus ?? false);
if (modified.Flags.HasFlag(CommodityFlags.Period))
packet.WriteShort(modified.Period ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.ReqPOP))
packet.WriteShort(modified.ReqPOP ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.ReqLVL))
packet.WriteShort(modified.ReqLevel ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.MaplePoint))
packet.WriteInt(modified.MaplePoint ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.Meso))
packet.WriteInt(modified.Meso ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.ForPremiumUser))
packet.WriteBool(modified.ForPremiumUser ?? false);
if (modified.Flags.HasFlag(CommodityFlags.CommodityGender))
packet.WriteByte(modified.Gender ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.OnSale))
packet.WriteBool(modified.OnSale ?? false);
if (modified.Flags.HasFlag(CommodityFlags.Class))
packet.WriteByte(modified.Class ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.Limit))
packet.WriteByte(modified.Limit ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.PbCash))
packet.WriteShort(modified.PbCash ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.PbPoint))
packet.WriteShort(modified.PbPoint ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.PbGift))
packet.WriteShort(modified.PbGift ?? 0);
if (modified.Flags.HasFlag(CommodityFlags.PackageSN))
{
packet.WriteByte((byte)(modified.PackageSN?.Count ?? 0));
foreach (var sn in modified.PackageSN ?? new List<int>())
packet.WriteInt(sn);
}
}
packet.WriteBool(false); // v49
packet.WriteBytes(new byte[1080]);
packet.WriteShort(0); // Stock
packet.WriteShort(0); // LimitGoods
packet.WriteShort(0); // ZeroGoods
packet.WriteBool(false); // EventOn
packet.WriteInt(200); // HighestCharacterLevelInThisAccount
await user.Dispatch(packet.Build());
await user.DispatchUpdateLocker();
await user.DispatchUpdateWish();
await user.DispatchUpdateCash();
await base.Enter(user);
}
}
| 0 | 0.7825 | 1 | 0.7825 | game-dev | MEDIA | 0.944496 | game-dev | 0.770003 | 1 | 0.770003 |
CalamityTeam/CalamityModPublic | 1,955 | Items/Weapons/Summon/FrostBlossomStaff.cs | using CalamityMod.Projectiles.Summon;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Weapons.Summon
{
public class FrostBlossomStaff : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Weapons.Summon";
public override void SetDefaults()
{
Item.width = 34;
Item.height = 24;
Item.damage = 10;
Item.mana = 10;
Item.useTime = Item.useAnimation = 35;
Item.useStyle = ItemUseStyleID.Swing;
Item.noMelee = true;
Item.knockBack = 2f;
Item.value = CalamityGlobalItem.RarityBlueBuyPrice;
Item.rare = ItemRarityID.Blue;
Item.UseSound = SoundID.Item28;
Item.shoot = ModContent.ProjectileType<FrostBlossom>();
Item.shootSpeed = 10f;
Item.DamageType = DamageClass.Summon;
}
public override bool CanUseItem(Player player) => player.ownedProjectileCounts[Item.shoot] <= 0;
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
CalamityUtils.KillShootProjectiles(true, type, player);
int p = Projectile.NewProjectile(source, player.Center, Vector2.Zero, type, damage, knockback, player.whoAmI, 0f, 0f);
if (Main.projectile.IndexInRange(p))
Main.projectile[p].originalDamage = Item.damage;
return false;
}
public override void AddRecipes()
{
CreateRecipe().
AddRecipeGroup("AnyIceBlock", 50).
AddIngredient(ItemID.BorealWood, 10).
AddIngredient(ItemID.Shiverthorn, 5).
AddTile(TileID.Anvils).
Register();
}
}
}
| 0 | 0.912669 | 1 | 0.912669 | game-dev | MEDIA | 0.991292 | game-dev | 0.899828 | 1 | 0.899828 |
tankyc/sango_infinity | 23,980 | Project/Assets/Scripts/Extensions/ToLua/ToLua/Core/LuaMatchType.cs | /*
Copyright (c) 2015-2021 topameng(topameng@qq.com)
https://github.com/topameng/tolua
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using UnityEngine;
using System;
using System.Collections;
namespace LuaInterface
{
public class LuaMatchType
{
public bool CheckNumber(IntPtr L, int pos)
{
return LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TNUMBER;
}
#if LUAC_5_3
public bool CheckInteger(IntPtr L, int pos)
{
return LuaDLL.lua_isinteger(L, pos) != 0;
}
#else
public bool CheckInteger(IntPtr L, int pos)
{
return LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TNUMBER;
}
#endif
public bool CheckBool(IntPtr L, int pos)
{
return LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TBOOLEAN;
}
public bool CheckLong(IntPtr L, int pos)
{
#if LUAC_5_3
return LuaDLL.lua_isinteger(L, pos) != 0;
#else
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNUMBER:
return true;
case LuaTypes.LUA_TUSERDATA:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Int64;
default:
return false;
}
#endif
}
public bool CheckULong(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNUMBER:
return LuaDLL.lua_tonumber(L, pos) >= 0;
case LuaTypes.LUA_TUSERDATA:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.UInt64;
default:
return false;
}
}
public bool CheckNullNumber(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TNUMBER || luaType == LuaTypes.LUA_TNIL;
}
#if LUAC_5_3
//需要优化,合并为1个call
public bool CheckNullInteger(IntPtr L, int pos)
{
return LuaDLL.lua_isinteger(L, pos) != 0 || LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TNIL;
}
#else
public bool CheckNullInteger(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TNUMBER || luaType == LuaTypes.LUA_TNIL;
}
#endif
public bool CheckNullBool(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TBOOLEAN || luaType == LuaTypes.LUA_TNIL;
}
public bool CheckNullLong(IntPtr L, int pos)
{
#if LUAC_5_3
//需要优化,合并为1个call
return LuaDLL.lua_isinteger(L, pos) != 0 || LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TNIL;
#else
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TNUMBER:
return true;
case LuaTypes.LUA_TUSERDATA:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Int64;
default:
return false;
}
#endif
}
public bool CheckNullULong(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TNUMBER:
return true;
case LuaTypes.LUA_TUSERDATA:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.UInt64;
default:
return false;
}
}
readonly Type TypeOfString = typeof(string);
public bool CheckString(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TSTRING:
return true;
case LuaTypes.LUA_TUSERDATA:
return CheckClassType(TypeOfString, L, pos);
default:
return false;
}
}
readonly Type TypeOfByteArray = typeof(byte[]);
public bool CheckByteArray(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TSTRING:
return true;
case LuaTypes.LUA_TUSERDATA:
return CheckClassType(TypeOfByteArray, L, pos);
default:
return false;
}
}
readonly Type TypeOfCharArray = typeof(char[]);
public bool CheckCharArray(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TSTRING:
return true;
case LuaTypes.LUA_TUSERDATA:
return CheckClassType(TypeOfCharArray, L, pos);
default:
return false;
}
}
public bool CheckArray(Type t, IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return true;
case LuaTypes.LUA_TUSERDATA:
return CheckClassType(t, L, pos);
default:
return false;
}
}
readonly Type TypeOfBoolArray = typeof(bool[]);
public bool CheckBoolArray(IntPtr L, int pos)
{
return CheckArray(TypeOfBoolArray, L, pos);
}
readonly Type TypeOfSByteArray = typeof(sbyte[]);
public bool CheckSByteArray(IntPtr L, int pos)
{
return CheckArray(TypeOfSByteArray, L, pos);
}
readonly Type TypeOfShortArray = typeof(short[]);
public bool CheckInt16Array(IntPtr L, int pos)
{
return CheckArray(TypeOfShortArray, L, pos);
}
readonly Type TypeOfUShortArray = typeof(ushort[]);
public bool CheckUInt16Array(IntPtr L, int pos)
{
return CheckArray(TypeOfUShortArray, L, pos);
}
readonly Type TypeOfDecimalArray = typeof(decimal[]);
public bool CheckDecimalArray(IntPtr L, int pos)
{
return CheckArray(TypeOfDecimalArray, L, pos);
}
readonly Type TypeOfFloatArray = typeof(float[]);
public bool CheckSingleArray(IntPtr L, int pos)
{
return CheckArray(TypeOfFloatArray, L, pos);
}
readonly Type TypeOfDoubleArray = typeof(double[]);
public bool CheckDoubleArray(IntPtr L, int pos)
{
return CheckArray(TypeOfDoubleArray, L, pos);
}
readonly Type TypeOfIntArray = typeof(int[]);
public bool CheckInt32Array(IntPtr L, int pos)
{
return CheckArray(TypeOfIntArray, L, pos);
}
readonly Type TypeOfUIntArray = typeof(uint[]);
public bool CheckUInt32Array(IntPtr L, int pos)
{
return CheckArray(TypeOfUIntArray, L, pos);
}
readonly Type TypeOfLongArray = typeof(long[]);
public bool CheckInt64Array(IntPtr L, int pos)
{
return CheckArray(TypeOfLongArray, L, pos);
}
readonly Type TypeOfULongArray = typeof(ulong[]);
public bool CheckUInt64Array(IntPtr L, int pos)
{
return CheckArray(TypeOfULongArray, L, pos);
}
readonly Type TypeOfStringArray = typeof(string[]);
public bool CheckStringArray(IntPtr L, int pos)
{
return CheckArray(TypeOfStringArray, L, pos);
}
readonly Type TypeOfTypeArray = typeof(Type[]);
public bool CheckTypeArray(IntPtr L, int pos)
{
return CheckArray(TypeOfTypeArray, L, pos);
}
readonly Type TypeOfObjectArray = typeof(object[]);
public bool CheckObjectArray(IntPtr L, int pos)
{
return CheckArray(TypeOfObjectArray, L, pos);
}
bool CheckValueType(IntPtr L, int pos, int valueType, Type nt)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
int vt = LuaDLL.tolua_getvaluetype(L, pos);
return vt == valueType;
}
return false;
}
public bool CheckVec3(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Vector3;
}
return false;
}
public bool CheckQuat(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Quaternion;
}
return false;
}
public bool CheckVec2(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Vector2;
}
return false;
}
public bool CheckColor(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Color;
}
return false;
}
public bool CheckVec4(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Vector4;
}
return false;
}
public bool CheckRay(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Ray;
}
return false;
}
public bool CheckBounds(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Bounds;
}
return false;
}
public bool CheckTouch(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Touch;
}
return false;
}
public bool CheckLayerMask(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.LayerMask;
}
return false;
}
public bool CheckRaycastHit(IntPtr L, int pos)
{
if (LuaDLL.lua_type(L, pos) == LuaTypes.LUA_TTABLE)
{
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.RaycastHit;
}
return false;
}
public bool CheckNullVec3(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Vector3;
default:
return false;
}
}
public bool CheckNullQuat(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Quaternion;
default:
return false;
}
}
public bool CheckNullVec2(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Vector2;
default:
return false;
}
}
public bool CheckNullColor(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Color;
default:
return false;
}
}
public bool CheckNullVec4(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Vector4;
default:
return false;
}
}
public bool CheckNullRay(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Ray;
default:
return false;
}
}
public bool CheckNullBounds(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Bounds;
default:
return false;
}
}
public bool CheckNullTouch(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.Touch;
default:
return false;
}
}
public bool CheckNullLayerMask(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.LayerMask;
default:
return false;
}
}
public bool CheckNullRaycastHit(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TTABLE:
return LuaDLL.tolua_getvaluetype(L, pos) == LuaValueType.RaycastHit;
default:
return false;
}
}
readonly Type TypeOfVector3Array = typeof(Vector3[]);
public bool CheckVec3Array(IntPtr L, int pos)
{
return CheckArray(TypeOfVector3Array, L, pos);
}
readonly Type TypeOfQuaternionArray = typeof(Quaternion[]);
public bool CheckQuatArray(IntPtr L, int pos)
{
return CheckArray(TypeOfQuaternionArray, L, pos);
}
readonly Type TypeOfVector2Array = typeof(Vector2[]);
public bool CheckVec2Array(IntPtr L, int pos)
{
return CheckArray(TypeOfVector2Array, L, pos);
}
readonly Type TypeOfVector4Array = typeof(Vector4[]);
public bool CheckVec4Array(IntPtr L, int pos)
{
return CheckArray(TypeOfVector4Array, L, pos);
}
readonly Type TypeOfColorArray = typeof(Color[]);
public bool CheckColorArray(IntPtr L, int pos)
{
return CheckArray(TypeOfColorArray, L, pos);
}
public bool CheckPtr(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TLIGHTUSERDATA || luaType == LuaTypes.LUA_TNIL;
}
public bool CheckLuaFunc(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TFUNCTION || luaType == LuaTypes.LUA_TNIL;
}
public bool CheckLuaTable(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TTABLE || luaType == LuaTypes.LUA_TNIL;
}
public bool CheckLuaThread(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TTHREAD || luaType == LuaTypes.LUA_TNIL;
}
public bool CheckLuaBaseRef(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch(luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TFUNCTION:
return true;
case LuaTypes.LUA_TTABLE:
return true;
case LuaTypes.LUA_TTHREAD:
return true;
default:
return false;
}
}
public bool CheckByteBuffer(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
return luaType == LuaTypes.LUA_TSTRING || luaType == LuaTypes.LUA_TNIL;
}
readonly Type TypeOfEventObject = typeof(EventObject);
public bool CheckEventObject(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TUSERDATA:
return CheckClassType(TypeOfEventObject, L, pos);
default:
return false;
}
}
public bool CheckEnumerator(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TUSERDATA:
int udata = LuaDLL.tolua_rawnetobj(L, pos);
if (udata != -1)
{
ObjectTranslator translator = ObjectTranslator.Get(L);
object obj = translator.GetObject(udata);
return obj == null ? true : obj is IEnumerator;
}
return false;
default:
return false;
}
}
//不存在派生类的类型
bool CheckFinalType(Type type, IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TUSERDATA:
return CheckClassType(type, L, pos);
default:
return false;
}
}
readonly Type TypeOfGameObject = typeof(GameObject);
public bool CheckGameObject(IntPtr L, int pos)
{
return CheckFinalType(TypeOfGameObject, L, pos);
}
public bool CheckTransform(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TUSERDATA:
int udata = LuaDLL.tolua_rawnetobj(L, pos);
if (udata != -1)
{
ObjectTranslator translator = ObjectTranslator.Get(L);
object obj = translator.GetObject(udata);
return obj == null ? true : obj is Transform;
}
return false;
default:
return false;
}
}
readonly Type monoType = typeof(Type).GetType();
public bool CheckMonoType(IntPtr L, int pos)
{
LuaTypes luaType = LuaDLL.lua_type(L, pos);
switch (luaType)
{
case LuaTypes.LUA_TNIL:
return true;
case LuaTypes.LUA_TUSERDATA:
return CheckClassType(monoType, L, pos);
default:
return false;
}
}
public bool CheckVariant(IntPtr L, int pos)
{
return true;
}
bool CheckClassType(Type t, IntPtr L, int pos)
{
int udata = LuaDLL.tolua_rawnetobj(L, pos);
if (udata != -1)
{
ObjectTranslator translator = ObjectTranslator.Get(L);
object obj = translator.GetObject(udata);
return obj == null ? true : obj.GetType() == t;
}
return false;
}
}
}
| 0 | 0.800685 | 1 | 0.800685 | game-dev | MEDIA | 0.315721 | game-dev | 0.511057 | 1 | 0.511057 |
copperwater/xNetHack | 33,507 | src/minion.c | /* NetHack 3.7 minion.c $NHDT-Date: 1624322864 2021/06/22 00:47:44 $ $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.60 $ */
/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/*-Copyright (c) Robert Patrick Rankin, 2008. */
/* NetHack may be freely redistributed. See license for details. */
#include "hack.h"
/* used to pick among the four basic elementals without worrying whether
they've been reordered (difficulty reassessment?) or any new ones have
been introduced (hybrid types added to 'E'-class?) */
static const int elementals[4] = {
PM_AIR_ELEMENTAL, PM_FIRE_ELEMENTAL,
PM_EARTH_ELEMENTAL, PM_WATER_ELEMENTAL
};
void
newemin(struct monst *mtmp)
{
if (!mtmp->mextra)
mtmp->mextra = newmextra();
if (!EMIN(mtmp)) {
EMIN(mtmp) = (struct emin *) alloc(sizeof(struct emin));
(void) memset((genericptr_t) EMIN(mtmp), 0, sizeof(struct emin));
EMIN(mtmp)->parentmid = mtmp->m_id;
}
}
void
free_emin(struct monst *mtmp)
{
if (mtmp->mextra && EMIN(mtmp)) {
free((genericptr_t) EMIN(mtmp));
EMIN(mtmp) = (struct emin *) 0;
}
mtmp->isminion = 0;
}
/* count the number of monsters on the level */
int
monster_census(boolean spotted) /* seen|sensed vs all */
{
struct monst *mtmp;
int count = 0;
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (DEADMONSTER(mtmp))
continue;
if (mtmp->isgd && mtmp->mx == 0)
continue;
if (spotted && !canspotmon(mtmp))
continue;
if (spotted && !sensemon(mtmp) && M_AP_TYPE(mtmp) != M_AP_NOTHING
&& M_AP_TYPE(mtmp) != M_AP_MONSTER)
continue; /* concealed mimic */
++count;
}
return count;
}
/* mon summons a monster */
int
msummon(struct monst *mon)
{
struct permonst *ptr;
int dtype = NON_PM, cnt = 0, result = 0, census;
boolean xlight;
aligntyp atyp;
struct monst *mtmp;
if (mon) {
ptr = mon->data;
if (u_wield_art(ART_DEMONBANE) && is_demon(ptr)) {
if (canseemon(mon))
pline("%s looks puzzled for a moment.", Monnam(mon));
return 0;
}
atyp = mon->ispriest ? EPRI(mon)->shralign
: mon->isminion ? EMIN(mon)->min_align
: (ptr->maligntyp == A_NONE) ? A_NONE
: sgn(ptr->maligntyp);
} else {
ptr = &mons[PM_WIZARD_OF_YENDOR];
atyp = (ptr->maligntyp == A_NONE) ? A_NONE : sgn(ptr->maligntyp);
}
if (is_dprince(ptr) || (ptr == &mons[PM_WIZARD_OF_YENDOR])) {
dtype = (!rn2(20)) ? dprince(atyp) : (!rn2(4)) ? dlord(atyp)
: ndemon(atyp);
cnt = !rn2(4) ? 4 : 2;
} else if (is_dlord(ptr)) {
dtype = (!rn2(50)) ? dprince(atyp) : (!rn2(20)) ? dlord(atyp)
: ndemon(atyp);
cnt = !rn2(4) ? rn1(3, 2) : rn1(2, 1);
} else if (ptr == &mons[PM_BONE_DEVIL]) {
dtype = PM_SKELETON;
cnt = 1;
} else if (is_ndemon(ptr)) {
dtype = (!rn2(20)) ? dlord(atyp) : (!rn2(6)) ? ndemon(atyp)
: monsndx(ptr);
cnt = 1;
} else if (is_lminion(mon)) {
dtype = (is_lord(ptr) && !rn2(20))
? llord()
: (is_lord(ptr) || !rn2(6)) ? lminion() : monsndx(ptr);
cnt = ((dtype != NON_PM)
&& !rn2(4) && !is_lord(&mons[dtype])) ? 2 : 1;
} else if (ptr == &mons[PM_ANGEL]) {
/* non-lawful angels can also summon */
if (!rn2(6)) {
switch (atyp) { /* see summon_minion */
case A_NEUTRAL:
dtype = ROLL_FROM(elementals);
break;
case A_CHAOTIC:
case A_NONE:
dtype = ndemon(atyp);
break;
}
} else {
dtype = PM_ANGEL;
}
cnt = ((dtype != NON_PM)
&& !rn2(4) && !is_lord(&mons[dtype])) ? 2 : 1;
}
/* put overrides for specific summoners here, but note they have to check
* for dtype being NON_PM before using it */
if (ptr == &mons[PM_DISPATER]
&& ((svm.mvitals[PM_PIT_FIEND].mvflags & G_GONE) == 0)
&& (dtype == NON_PM || is_ndemon(&mons[dtype])) && !rn2(2)) {
/* Dispater favors pit fiends, despite them being chaotic */
dtype = PM_PIT_FIEND;
}
if (dtype == NON_PM)
return 0;
/* sanity checks */
if (cnt > 1 && (mons[dtype].geno & G_UNIQ) != 0)
cnt = 1;
/*
* If this daemon is unique and being re-summoned (the only way we
* could get this far with an extinct dtype), try another.
*/
if ((svm.mvitals[dtype].mvflags & G_GONE) != 0) {
dtype = ndemon(atyp);
if (dtype == NON_PM)
return 0;
}
/* some candidates can generate a group of monsters, so simple
count of non-null makemon() result is not sufficient */
census = monster_census(FALSE);
xlight = FALSE;
while (cnt > 0) {
mtmp = makemon(&mons[dtype], u.ux, u.uy, MM_EMIN|MM_NOMSG);
if (mtmp) {
result++;
/* an angel's alignment should match the summoner */
if (dtype == PM_ANGEL) {
mtmp->isminion = 1;
EMIN(mtmp)->min_align = atyp;
/* renegade if same alignment but not peaceful
or peaceful but different alignment */
EMIN(mtmp)->renegade =
(atyp != u.ualign.type) ^ !mtmp->mpeaceful;
}
if (mtmp->data->mlet == S_ANGEL && !Blind) {
/* for any 'A', 'cloud of smoke' will be 'flash of light';
if more than one monster is being created, that message
might be skipped for this monster but show 'mtmp' anyway */
show_transient_light((struct obj *) 0, mtmp->mx, mtmp->my);
xlight = TRUE;
/* we don't do this for 'burst of flame' (fire elemental)
because those monsters become their own light source */
}
if (cnt == 1 && canseemon(mtmp)) {
const char *cloud = 0,
*what = msummon_environ(mtmp->data, &cloud);
if (!boss_entrance(mtmp))
pline("%s appears in a %s of %s!", Amonnam(mtmp),
cloud, what);
}
}
cnt--;
}
if (xlight) {
/* Note: if we forced --More-- here, the 'A's would be visible for
long enough to be seen, but like with clairvoyance, some players
would be annoyed at the disruption of having to acknowledge it */
transient_light_cleanup();
}
/* how many monsters exist now compared to before? */
if (result)
result = monster_census(FALSE) - census;
return result;
}
void
summon_minion(aligntyp alignment, boolean talk)
{
struct monst *mon;
int mnum;
switch ((int) alignment) {
case A_LAWFUL:
mnum = lminion();
break;
case A_NEUTRAL:
mnum = ROLL_FROM(elementals);
break;
case A_CHAOTIC:
case A_NONE:
mnum = ndemon(alignment);
break;
default:
impossible("unaligned player?");
mnum = ndemon(A_NONE);
break;
}
if (mnum == NON_PM) {
mon = 0;
} else if (mnum == PM_ANGEL) {
mon = makemon(&mons[mnum], u.ux, u.uy, MM_EMIN|MM_NOMSG);
if (mon) {
mon->isminion = 1;
EMIN(mon)->min_align = alignment;
EMIN(mon)->renegade = FALSE;
}
} else if (mnum != PM_SHOPKEEPER && mnum != PM_GUARD
&& mnum != PM_ALIGNED_CLERIC && mnum != PM_HIGH_CLERIC) {
/* This was mons[mnum].pxlth == 0 but is this restriction
appropriate or necessary now that the structures are separate? */
mon = makemon(&mons[mnum], u.ux, u.uy, MM_EMIN|MM_NOMSG);
if (mon) {
mon->isminion = 1;
EMIN(mon)->min_align = alignment;
EMIN(mon)->renegade = FALSE;
}
} else {
mon = makemon(&mons[mnum], u.ux, u.uy, MM_NOMSG);
}
if (mon) {
if (talk) {
if (!Deaf)
pline_The("voice of %s booms:", align_gname(alignment));
else
You_feel("%s booming voice:",
s_suffix(align_gname(alignment)));
SetVoice(mon, 0, 80, 0);
verbalize("Thou shalt pay for thine indiscretion!");
if (canspotmon(mon))
pline("%s appears before you.", Amonnam(mon));
mon->mstrategy &= ~STRAT_APPEARMSG;
}
mon->mpeaceful = FALSE;
/* don't call set_malign(); player was naughty */
}
}
/* A boss monster (if not yet encountered, as determined by STRAT_APPEARMSG)
* makes a dramatic entrance.
* Might not actually be passed a boss. Return TRUE if it is a boss and we did
* print the dramatic entrance; FALSE otherwise. */
boolean
boss_entrance(struct monst* mtmp)
{
struct permonst* mdat = mtmp->data;
int mondx = monsndx(mdat);
char name_appears[BUFSZ]; /* holds "Foo_appears", as lua key */
char* iter;
if (!(is_archfiend(mdat) || is_rider(mdat)
|| mondx == PM_VLAD_THE_IMPALER || mondx == PM_WIZARD_OF_YENDOR)) {
/* no appearance message exists for this type of monster */
return FALSE;
}
if (mdat->msound == MS_NEMESIS || mdat->msound == MS_LEADER) {
/* this could be a demon quest nemesis/leader, who will have their own
* dialog */
return FALSE;
}
if (svm.mvitals[mondx].died > 0) {
/* Never print entrance message if the player already killed it. */
return FALSE;
}
if (!canspotmon(mtmp)) {
/* Assume the messages depend on you being able to spot it, so no
* dramatic entrance if you can't. */
return FALSE;
}
/* Never print message if this monster isn't marked to give one. */
if ((mtmp->mstrategy & STRAT_APPEARMSG) == 0) {
return FALSE;
}
/* ... and then turn off any other appearance message they were going to
* get. */
mtmp->mstrategy &= ~STRAT_APPEARMSG;
Sprintf(name_appears, "%s_appears", mdat->pmnames[NEUTRAL]);
while ((iter = strstr(name_appears, " ")) != (char*) 0) {
*iter = '_';
}
com_pager((const char*) name_appears);
return TRUE;
}
#define Athome (Inhell && (mtmp->cham == NON_PM))
/* How much is obj worth to demon lord if they demand it as a bribe?
* Return a number whose units are zorkmids (the amount they will take off their
* original bribe amount if given this). This loosely relates to cost, but
* doesn't have to; in particular, the demon lord would rather have rare items
* than more coins, so they may be worth more here than their equivalent if
* bought at a shop.
* Return 0 if the demon doesn't care about this item, or it's ineligible and
* they should never consider taking it. */
static long
demon_value(struct obj *obj)
{
const short otyp = obj->otyp;
long baseval = 0;
/* Ineligible stuff goes first.
* (should cursed welded items be ineligible? or handwave it as the demon
* lord easily removing the curse for free?) */
if (objects[otyp].oc_unique)
return 0;
if (obj == uskin)
return 0;
baseval = objects[otyp].oc_cost * 3; /* baseline */
/* cases with some complexity in calculation */
if (obj->oartifact)
return arti_cost(obj);
else if (Has_contents(obj)) {
struct obj *otmp;
for (otmp = obj->cobj; otmp; otmp = otmp->nobj) {
baseval += demon_value(otmp); /* recurse further into containers */
}
return baseval;
}
else if (obj->oclass == ARMOR_CLASS && objects[otyp].oc_magic) {
if (Is_dragon_scaled_armor(obj))
baseval += (objects[obj->dragonscales].oc_cost * 3);
return baseval;
}
else if (obj->oclass == WEAPON_CLASS && obj->spe >= 6) {
/* baseval is probably pretty low, the high enchantment is the prize
* here */
return baseval + (obj->spe * 50);
}
/* Cases where we want to inflate the value even more than 3 * base cost. */
else if (otyp == WAN_WISHING || otyp == MAGIC_LAMP
|| (In_cocytus(&u.uz) && otyp == RIN_COLD_RESISTANCE))
return baseval * 2;
/* Then, any case where the archfiend is interested in something for the
* plain base value.
* For rings and amulets, they focus on ones the player is wearing rather
* than random ones they may happen to have, on the guess that those are
* more valuable to the player. */
else if ((obj->oclass == SPBOOK_CLASS && objects[otyp].oc_level >= 6)
|| (obj->oclass == WAND_CLASS && obj->spe > 3)
|| otyp == MAGIC_MARKER
|| obj == uleft || obj == uright || obj == uamul)
return baseval;
return 0;
}
/* returns 1 if it won't attack. */
int
demon_talk(struct monst *mtmp)
{
long cash, demand, offer = 0L;
struct obj *otmp, *shiny = (struct obj *) 0;
int items_given = 0;
if (u_wield_art(ART_EXCALIBUR) || u_wield_art(ART_DEMONBANE)) {
if (canspotmon(mtmp))
pline("%s looks very angry.", Amonnam(mtmp));
else
You_feel("tension building.");
mtmp->mpeaceful = mtmp->mtame = 0;
set_malign(mtmp);
newsym(mtmp->mx, mtmp->my);
return 0;
}
if (is_fainted()) {
reset_faint(); /* if fainted - wake up */
} else {
stop_occupation();
if (gm.multi > 0) {
nomul(0);
unmul((char *) 0);
}
}
/* Slight advantage given. */
if (is_dprince(mtmp->data)) {
mtmp->minvis = mtmp->perminvis = 0;
if ((mtmp->mstrategy & STRAT_APPEARMSG) && !boss_entrance(mtmp)) {
/* you still can't see the demon; this can happen if you are blind
* and non-telepathic. */
mtmp->mstrategy &= ~STRAT_APPEARMSG;
}
newsym(mtmp->mx, mtmp->my);
}
if (gy.youmonst.data->mlet == S_DEMON) { /* Won't blackmail their own. */
if (!Deaf)
pline("%s says, \"Good hunting, %s.\"", Amonnam(mtmp),
flags.female ? "Sister" : "Brother");
else if (canseemon(mtmp))
pline("%s says something.", Amonnam(mtmp));
if (!tele_restrict(mtmp))
(void) rloc(mtmp, RLOC_MSG);
return 1;
}
/* Bribable monsters are very greedy, and don't care how much gold you
* appear to be carrying. They are capricious, and may demand truly
* exorbitant amounts; however, it might be risky to challenge a hero who
* has reached them, since they do not want to end up dead. */
demand = d(50,1000);
cash = money_cnt(gi.invent);
verbalize("Mortal, if thou canst pay, I shall not hinder thee %s.",
u.uevent.uamultouch ? "further" : "later");
/* First, they may want some of your valuables more than gold. See if they
* do. */
do {
long total_value = 0;
shiny = (struct obj *) 0;
for (otmp = gi.invent; otmp; otmp = otmp->nobj) {
long value = demon_value(otmp);
if (value < 1)
continue;
total_value += value;
if (rn2(total_value) < value)
shiny = otmp;
}
if (shiny) {
verbalize("I see thou hast %s in thy possession...",
an(xname(shiny)));
if (y_n("Give up your item?") != 'y') {
You("refuse.");
pline("%s gets angry...", Amonnam(mtmp));
mtmp->mpeaceful = 0;
set_malign(mtmp);
newsym(mtmp->mx, mtmp->my);
return 0;
}
if (shiny->owornmask) {
remove_outer_gear(mtmp, shiny);
remove_worn_item(shiny, TRUE);
}
items_given++;
demand -= demon_value(shiny);
freeinv(shiny);
if (shiny->oartifact == ART_DEMONBANE) {
pline("%s seizes it!", Monnam(mtmp));
pline("Laughing evilly, %s engulfs it in flames, melting it.",
mhe(mtmp));
obfree(shiny, (struct obj *) 0);
}
else {
pline("%s greedily takes it.", Monnam(mtmp));
(void) mpickobj(mtmp, shiny); /* could merge and free shiny but
* won't */
}
}
} while (demand > 0 && rn2(4));
if (demand <= 0) { /* forfeited enough items to satisfy mtmp */
verbalize("Very well, mortal. I shall not impede thy quest.");
pline("%s vanishes, laughing to %sself.", Amonnam(mtmp), mhis(mtmp));
livelog_printf(LL_UMONST, "bribed %s with %d items for safe passage",
Amonnam(mtmp), items_given);
/* fall through to mongone() */
}
else if (items_given == 0 && (cash == 0 || gm.multi < 0)) {
/* you have no gold or can't move */
pline("%s roars:", Amonnam(mtmp));
verbalize("Thou bringest me no tribute? Then thou shalt die!");
mtmp->mpeaceful = 0;
set_malign(mtmp);
newsym(mtmp->mx, mtmp->my);
return 0;
} else {
/* make sure that the demand is unmeetable if the monster
has the Amulet, preventing monster from being satisfied
and removed from the game (along with said Amulet...) */
/* [actually the Amulet is safe; it would be dropped when
mongone() gets rid of the monster; force combat anyway;
also make it unmeetable if the player is Deaf, to simplify
handling that case as player-won't-pay] */
if (mon_has_amulet(mtmp) || Deaf)
/* 125: 5*25 in case hero has maximum possible charisma */
demand = cash + (long) rn1(1000, 125);
if (!Deaf)
pline("%s%s demands %ld %s for safe passage.",
Amonnam(mtmp),
(items_given > 0) ? " also" : "",
demand, currency(demand));
else if (canseemon(mtmp))
pline("%s seems to be demanding your money.", Amonnam(mtmp));
if (cash < 1)
pline("But you have no money.");
else
offer = bribe(mtmp);
if (offer >= demand) {
verbalize("Very well, mortal. I shall not impede thy quest.");
pline("%s vanishes, laughing about cowardly mortals.",
Amonnam(mtmp));
livelog_printf(LL_UMONST, "bribed %s with %ld %s for safe passage",
Amonnam(mtmp), offer, currency(offer));
}
else if (offer == cash && offer > 0 && cash >= demand / 2 && !rn2(50)) {
/* monster may rarely take pity on you if you hand over everything
* you have */
pline("%s grudgingly grabs your money bag, then vanishes.",
Amonnam(mtmp));
livelog_printf(LL_UMONST,
"turned out their pockets for %s for safe passage",
Amonnam(mtmp));
}
else if((long) rnd(100 * ACURR(A_CHA)) > (demand - offer)) {
/* monster may also decide that being shortchanged by a small
* amount isn't worth risking their life */
pline("%s scowls at you menacingly, then vanishes.",
Amonnam(mtmp));
livelog_printf(LL_UMONST,
"shortchanged %s with %ld %s for safe passage",
Amonnam(mtmp), offer, currency(offer));
}
else {
pline("%s gets angry...", Amonnam(mtmp));
mtmp->mpeaceful = 0;
set_malign(mtmp);
newsym(mtmp->mx, mtmp->my);
return 0;
}
}
mongone(mtmp);
return 1;
}
long
bribe(struct monst *mtmp)
{
char buf[BUFSZ] = DUMMY;
long offer;
long umoney = money_cnt(gi.invent);
getlin("How much will you offer?", buf);
if (sscanf(buf, "%ld", &offer) != 1)
offer = 0L;
/*Michael Paddon -- fix for negative offer to monster*/
/*JAR880815 - */
if (offer < 0L) {
You("try to shortchange %s, but fumble.", mon_nam(mtmp));
return 0L;
} else if (offer == 0L) {
You("refuse.");
return 0L;
} else if (offer >= umoney) {
You("give %s all your gold.", mon_nam(mtmp));
offer = umoney;
} else if (offer == umoney / 10 && mtmp->ispriest) {
You("pay your tithe to %s.", mon_nam(mtmp));
} else {
You("give %s %ld %s.", mon_nam(mtmp), offer, currency(offer));
}
(void) money2mon(mtmp, offer);
disp.botl = TRUE;
return offer;
}
int
dprince(aligntyp atyp)
{
int tryct, pm;
for (tryct = !In_endgame(&u.uz) ? 20 : 0; tryct > 0; --tryct) {
pm = rn1(PM_DEMOGORGON + 1 - PM_ORCUS, PM_ORCUS);
if (!(svm.mvitals[pm].mvflags & G_GONE)
&& (atyp == A_NONE || sgn(mons[pm].maligntyp) == sgn(atyp)))
return pm;
}
return dlord(atyp); /* approximate */
}
int
dlord(aligntyp atyp)
{
int tryct, pm;
for (tryct = !In_endgame(&u.uz) ? 20 : 0; tryct > 0; --tryct) {
pm = rn1(PM_YEENOGHU + 1 - PM_JUIBLEX, PM_JUIBLEX);
/* This previously checked G_GONE (as dprince still does), but Juiblex
* is weird in that he splits, and in order to split he doesn't get
* G_EXTINCT set. Instead, check the born counter (which also works fine
* for Yeenoghu or any other archfiend since the outcome is the same -
* if they have already been generated, they can't be summoned. */
if (!(svm.mvitals[pm].born)
&& (atyp == A_NONE || sgn(mons[pm].maligntyp) == sgn(atyp)))
return pm;
}
return ndemon(atyp); /* approximate */
}
/* create lawful (good) lord */
int
llord(void)
{
if (!(svm.mvitals[PM_ARCHON].mvflags & G_GONE))
return PM_ARCHON;
return lminion(); /* approximate */
}
int
lminion(void)
{
int tryct;
struct permonst *ptr;
for (tryct = 0; tryct < 20; tryct++) {
ptr = mkclass(S_ANGEL, 0);
if (ptr && !is_lord(ptr))
return monsndx(ptr);
}
return NON_PM;
}
int
ndemon(aligntyp atyp) /* A_NONE is used for 'any alignment' */
{
struct permonst *ptr;
/*
* 3.6.2: [fixed #H2204, 22-Dec-2010, eight years later...]
* pick a correctly aligned demon in one try. This used to
* use mkclass() to choose a random demon type and keep trying
* (up to 20 times) until it got one with the desired alignment.
* mkclass_aligned() skips wrongly aligned potential candidates.
* [The only neutral demons are djinni and mail daemon and
* mkclass() won't pick them, but call it anyway in case either
* aspect of that changes someday.]
*/
#if 0
if (atyp == A_NEUTRAL)
return NON_PM;
#endif
ptr = mkclass_aligned(S_DEMON, 0, atyp);
return (ptr && is_ndemon(ptr)) ? monsndx(ptr) : NON_PM;
}
/* guardian angel has been affected by conflict so is abandoning hero */
void
lose_guardian_angel(
struct monst *mon) /* if Null, angel hasn't been created yet */
{
coord mm;
int i;
if (mon) {
if (canspotmon(mon)) {
if (!Deaf) {
pline("%s rebukes you, saying:", Monnam(mon));
SetVoice(mon, 0, 80, 0);
verbalize("Since you desire conflict, have some more!");
} else {
pline("%s vanishes!", Monnam(mon));
}
}
mongone(mon);
}
/* create 2 to 4 hostile angels to replace the lost guardian */
for (i = rn1(3, 2); i > 0; --i) {
mm.x = u.ux;
mm.y = u.uy;
if (enexto(&mm, mm.x, mm.y, &mons[PM_ANGEL]))
(void) mk_roamer(&mons[PM_ANGEL], u.ualign.type, mm.x, mm.y,
FALSE);
}
}
/* just entered the Astral Plane; receive tame guardian angel if worthy */
void
gain_guardian_angel(void)
{
struct monst *mtmp;
struct obj *otmp;
coord mm;
Hear_again(); /* attempt to cure any deafness now (divine
message will be heard even if that fails) */
if (Conflict) {
if (!Deaf)
pline("A voice booms:");
else
You_feel("a booming voice:");
SetVoice((struct monst *) 0, 0, 80, voice_deity);
verbalize("Thy desire for conflict shall be fulfilled!");
/* send in some hostile angels instead */
lose_guardian_angel((struct monst *) 0);
} else if (u.ualign.record > 8 && u.uconduct.pets) { /* fervent */
/* Too nasty for the game to unexpectedly break petless conduct on
* the final level of the game. If you have been petless thus far, your
* god will respect your decision, and won't send an angel. */
if (!Deaf)
pline("A voice whispers:");
else
You_feel("a soft voice:");
SetVoice((struct monst *) 0, 0, 80, voice_deity);
verbalize("Thou hast been worthy of me!");
mm.x = u.ux;
mm.y = u.uy;
if (enexto(&mm, mm.x, mm.y, &mons[PM_ANGEL])
&& (mtmp = mk_roamer(&mons[PM_ANGEL], u.ualign.type, mm.x, mm.y,
TRUE)) != 0) {
mtmp->mstrategy &= ~STRAT_APPEARMSG;
/* guardian angel -- the one case mtame doesn't imply an
* edog structure, so we don't want to call tamedog().
* [Note: this predates mon->mextra which allows a monster
* to have both emin and edog at the same time.]
*/
mtmp->mtame = 10;
u.uconduct.pets++;
/* for 'hilite_pet'; after making tame, before next message */
newsym(mtmp->mx, mtmp->my);
if (!Blind)
pline("An angel appears near you.");
else
You_feel("the presence of a friendly angel near you.");
/* make him strong enough vs. endgame foes */
mtmp->m_lev = rn1(8, 15);
mtmp->mhp = mtmp->mhpmax =
d((int) mtmp->m_lev, 10) + 30 + rnd(30);
if ((otmp = select_hwep(mtmp)) == 0) {
otmp = mksobj(SABER, FALSE, FALSE);
if (mpickobj(mtmp, otmp))
panic("merged weapon?");
}
bless(otmp);
if (otmp->spe < 4)
otmp->spe += rnd(4);
if ((otmp = which_armor(mtmp, W_ARMS)) == 0
|| otmp->otyp != SHIELD_OF_REFLECTION) {
(void) mongets(mtmp, AMULET_OF_REFLECTION);
m_dowear(mtmp, TRUE);
}
}
}
}
/* special bonus for Geryon towards damage and regeneration on his level, based
* on the number of his herd that is present */
int
geryon_bonus(void)
{
static long lastturncheck = -1;
static int bonus = 0;
struct monst *mtmp;
if (svm.moves == lastturncheck)
return bonus; /* already calculated this turn */
lastturncheck = svm.moves;
bonus = 0;
if (Is_geryon_level(&u.uz)) {
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (mtmp->data->mlet == S_QUADRUPED && !mtmp->mtame) {
bonus++;
}
}
}
else {
/* if he was summoned away from his level, give a middling amount
* (assuming it typically ranges from 40 to 0) */
bonus = 20;
}
return bonus;
}
/* you have ticked off Geryon by killing a member of his herd; assumes caller
* has checked for the conditions like being on his level already */
void
angry_geryon(void)
{
struct monst *geryon;
boolean givemsg = FALSE;
for (geryon = fmon; geryon; geryon = geryon->nmon) {
if (geryon->data == &mons[PM_GERYON]) {
if (geryon->mhp * 5 > geryon->mhpmax
&& !monnear(geryon, u.ux, u.uy)) {
if (geryon->mpeaceful)
givemsg = TRUE;
geryon->mpeaceful = FALSE;
mnexto(geryon, RLOC_NONE);
}
break;
}
}
/* Cases where Geryon comes back mad and should be spawned in, assuming
* he is not present on the level and num_in_dgn is not indicating he's
* somewhere else:
*
* spawn geryon if
* born = 0, died = 0 (never generated)
* born = 1, died = 0 (bribed or escaped dungeon)
* born = X+1, died = X (repeated resurrecting followed by bribe/escape)
*
* DON'T spawn geryon if
* born = 1, died = 1
* born = X, died = X (repeated resurrecting ending with a kill)
*/
if (!geryon && (lookup_fiend(PM_GERYON)->num_in_dgn == 0)
&& (svm.mvitals[PM_GERYON].born == 0
|| svm.mvitals[PM_GERYON].born > svm.mvitals[PM_GERYON].died)) {
/* Geryon hasn't generated yet OR has generated and been bribed
* away, in which case he comes back mad; generate him now */
boolean never_generated = (svm.mvitals[PM_GERYON].born == 0);
geryon = makemon(&mons[PM_GERYON], u.ux, u.uy,
MM_NOMSG | MM_ADJACENTOK);
if (!geryon) {
impossible("Geryon spawning failed");
}
if (never_generated)
boss_entrance(geryon);
geryon->mpeaceful = FALSE;
newsym(geryon->mx, geryon->my); /* remove peaceful symbol */
givemsg = TRUE;
}
if (givemsg) {
verbalize("Thou durst harm my herds, mortal? Die!");
}
}
/* At the start of the game, set up the archfiend structures and randomly select
* which archfiends should have wands of wishing in their lairs. */
#define NUM_ARCHFIEND_WISHES 3
void
init_archfiends(void)
{
int i;
/* first just set the basic constants */
for (i = FIRST_ARCHFIEND; i <= LAST_ARCHFIEND; ++i) {
struct fiend_info *tmpinfo = lookup_fiend(i);
tmpinfo->mndx = i;
tmpinfo->num_in_dgn = 0;
tmpinfo->escaped = FALSE;
}
/* now randomly choose some of them to have wishes
* Juiblex is omitted here because his lair is open and doesn't really have
* anywhere to stash a wand of wishing safely. */
static int elig_fiends[7] = {
PM_YEENOGHU, PM_ORCUS, PM_GERYON, PM_DISPATER, PM_ASMODEUS,
PM_BAALZEBUB, PM_DEMOGORGON
};
shuffle_int_array(elig_fiends, 7);
for (i = 0; i < NUM_ARCHFIEND_WISHES; ++i) {
lookup_fiend(elig_fiends[i])->has_wish = TRUE;
}
}
/* Obtain a pointer to the fiend_info struct that stores data about the
* given archfiend. */
struct fiend_info *
lookup_fiend(int mndx) {
return &svc.context.archfiends[mndx - FIRST_ARCHFIEND];
}
/* Should the given archfiend be giving the player a bad effect?
* Up to the caller to decide what the bad effect is and when it should be
* triggered. This function only tests whether the fiend is out of the picture
* or not, or whether they haven't yet started leaning on the scales. */
boolean
fiend_adversity(int mndx)
{
struct fiend_info *fnd = lookup_fiend(mndx);
if (!u.uevent.uamultouch)
/* this only kicks in after you have obtained the Amulet */
return FALSE;
if (fnd->escaped)
/* they are always going to be exerting their influence and you can't do
* anything about it. It's this way because if them escaping meant they
* wouldn't bother you anymore, it would probably be easier to do that
* than actually dealing with them */
return TRUE;
else if (fnd->num_in_dgn > 0)
/* they are alive and kicking somewhere in the dungeon */
return TRUE;
else if (svm.mvitals[mndx].born == 0)
/* they were never encountered, thus not dealt with */
return TRUE;
/* at this point, we could differentiate bribing from killing if we wanted
* because bribing cases will have born > died, but we don't care because
* either one means they've been dealt with */
return FALSE;
}
/* helper function that returns the number of fiends still in play */
int
active_fiends(void)
{
int mndx;
int num_active = 0;
for (mndx = FIRST_ARCHFIEND; mndx <= LAST_ARCHFIEND; ++mndx) {
if (fiend_adversity(mndx))
num_active++;
}
return num_active;
}
/* When the player first acquires the Amulet of Yendor, un-dealt-with archfiends
* start applying debuffs. Give an indication of this, and take care of any
* debuffs that should trigger immediately. */
void
start_fiend_harassment(void)
{
/* first just see how many fiends are still in play so we can give the
* message first */
int num_active = active_fiends();
if (num_active > 0) {
You("feel the malevolent attention of %s archfiend%s.",
num_active > 3 ? "several"
: num_active > 1 ? "some" : "an",
num_active == 1 ? "" : "s");
pline("An oppressive weight seems to settle on you.");
}
/* now do specific fiend effects or checks that should happen immediately */
if (fiend_adversity(PM_GERYON))
(void) encumber_msg();
}
/*minion.c*/
| 0 | 0.946381 | 1 | 0.946381 | game-dev | MEDIA | 0.625263 | game-dev | 0.996393 | 1 | 0.996393 |
microsoft/referencesource | 40,562 | System.Activities/System/Activities/Statements/InternalState.cs.back | //------------------------------------------------------------------------------
// <copyright file="InternalState.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Activities.Statements
{
using System;
using System.Activities;
using System.Activities.DynamicUpdate;
using System.Activities.Statements.Tracking;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime;
/// <summary>
/// InternalState is internal representation of State.
/// </summary>
sealed class InternalState : NativeActivity<string>
{
// State denotes corresponding State object.
State state;
// internal representation of transitions.
Collection<InternalTransition> internalTransitions;
// number of running triggers
Variable<int> currentRunningTriggers;
Variable<bool> isExiting;
// This bookmark is used to evaluate condition of a transition of this state.
Variable<Bookmark> evaluateConditionBookmark;
// Callback which is called when Entry is completed.
CompletionCallback onEntryComplete;
// Callback which is called when Trigger is completed.
CompletionCallback onTriggerComplete;
// Callback which is called when Condition is completed.
CompletionCallback<bool> onConditionComplete;
// Callback which is called when Exit is completed.
CompletionCallback onExitComplete;
// Callback which is used to start to evaluate Condition of a transition of this state.
BookmarkCallback evaluateConditionCallback;
Dictionary<Activity, InternalTransition> triggerInternalTransitionMapping = new Dictionary<Activity, InternalTransition>();
public InternalState(State state)
{
this.state = state;
this.DisplayName = state.DisplayName;
this.onEntryComplete = new CompletionCallback(this.OnEntryComplete);
this.onTriggerComplete = new CompletionCallback(this.OnTriggerComplete);
this.onConditionComplete = new CompletionCallback<bool>(this.OnConditionComplete);
this.onExitComplete = new CompletionCallback(this.OnExitComplete);
this.evaluateConditionCallback = new BookmarkCallback(this.StartEvaluateCondition);
this.currentRunningTriggers = new Variable<int>();
this.isExiting = new Variable<bool>();
this.evaluateConditionBookmark = new Variable<Bookmark>();
this.internalTransitions = new Collection<InternalTransition>();
this.triggerInternalTransitionMapping = new Dictionary<Activity, InternalTransition>();
}
/// <summary>
/// Gets or sets EventManager is used to globally manage event queue such that triggered events can be processed in order.
/// </summary>
[RequiredArgument]
public InArgument<StateMachineEventManager> EventManager
{
get;
set;
}
/// <summary>
/// Gets Entry activity that will be executed when state is entering.
/// </summary>
public Activity Entry
{
get
{
return this.state.Entry;
}
}
/// <summary>
/// Gets Exit activity that will be executed when state is leaving.
/// </summary>
public Activity Exit
{
get
{
return this.state.Exit;
}
}
/// <summary>
/// Gets a value indicating whether this state is a final state or not.
/// </summary>
[DefaultValue(false)]
public bool IsFinal
{
get
{
return this.state.IsFinal;
}
}
/// <summary>
/// Gets StateId, which is the identifier of a state. It's unique within a StateMachine.
/// </summary>
public string StateId
{
get
{
return this.state.StateId;
}
}
/// <summary>
/// Gets Transitions collection contains transitions on this state.
/// </summary>
public Collection<Transition> Transitions
{
get
{
return this.state.Transitions;
}
}
/// <summary>
/// Gets Variables collection contains Variables on this state.
/// </summary>
public Collection<Variable> Variables
{
get
{
return this.state.Variables;
}
}
/// <summary>
/// Gets the display name of the parent state machine of the state.
/// Used for tracking purpose only.
/// </summary>
public string StateMachineName
{
get
{
return this.state.StateMachineName;
}
}
protected override bool CanInduceIdle
{
get
{
return true;
}
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
this.internalTransitions.Clear();
if (this.Entry != null)
{
metadata.AddChild(this.Entry);
}
if (this.Exit != null)
{
metadata.AddChild(this.Exit);
}
this.ProcessTransitions(metadata);
metadata.SetVariablesCollection(this.Variables);
RuntimeArgument eventManagerArgument = new RuntimeArgument("EventManager", this.EventManager.ArgumentType, ArgumentDirection.In);
metadata.Bind(this.EventManager, eventManagerArgument);
metadata.SetArgumentsCollection(
new Collection<RuntimeArgument>
{
eventManagerArgument
});
metadata.AddImplementationVariable(this.currentRunningTriggers);
metadata.AddImplementationVariable(this.isExiting);
metadata.AddImplementationVariable(this.evaluateConditionBookmark);
}
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0",
Justification = "The context is used by workflow runtime. The parameter should be fine.")]
protected override void Execute(NativeActivityContext context)
{
StateMachineEventManager eventManager = this.EventManager.Get(context);
eventManager.CurrentBeingProcessedEvent = null;
this.isExiting.Set(context, false);
this.ScheduleEntry(context);
}
protected override void Abort(NativeActivityAbortContext context)
{
this.RemoveActiveBookmark(context);
base.Abort(context);
}
protected override void Cancel(NativeActivityContext context)
{
this.RemoveActiveBookmark(context);
base.Cancel(context);
}
protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)
{
InternalState originalInternalState = (InternalState)originalActivity;
// NOTE: State.Entry/Exit are allowed to be removed, because it doesn't change the execution semantics of SM
// if this removed activity was executing, WF runtime would disallow the update.
Activity entryActivityMatch = metadata.GetMatch(this.Entry);
Activity exitActivityMatch = metadata.GetMatch(this.Exit);
if ((null != entryActivityMatch && !object.ReferenceEquals(entryActivityMatch, originalInternalState.Entry)) ||
(null != exitActivityMatch && !object.ReferenceEquals(exitActivityMatch, originalInternalState.Exit)))
{
// original State.Entry/Exit is replaced with another child activities with InternalState
// new State.Entry/Exit is moved from another child activities within InternalState.
metadata.DisallowUpdateInsideThisActivity(SR.MovingActivitiesInStateBlockDU);
return;
}
int originalTriggerInUpdatedDefinition = 0;
foreach (InternalTransition originalTransition in originalInternalState.internalTransitions)
{
if (metadata.IsReferenceToImportedChild(originalTransition.Trigger))
{
metadata.DisallowUpdateInsideThisActivity(SR.TriggerOrConditionIsReferenced);
return;
}
if (!originalTransition.IsUnconditional)
{
// new Trigger activity
foreach (TransitionData transitionData in originalTransition.TransitionDataList)
{
if (metadata.IsReferenceToImportedChild(transitionData.Condition))
{
metadata.DisallowUpdateInsideThisActivity(SR.TriggerOrConditionIsReferenced);
return;
}
}
}
}
foreach (InternalTransition updatedTransition in this.internalTransitions)
{
if (metadata.IsReferenceToImportedChild(updatedTransition.Trigger))
{
// if the trigger is referenced, it might have another save values already.
metadata.DisallowUpdateInsideThisActivity(SR.TriggerOrConditionIsReferenced);
return;
}
Activity triggerMatch = metadata.GetMatch(updatedTransition.Trigger);
if (null != triggerMatch)
{
InternalTransition originalTransition;
if (originalInternalState.triggerInternalTransitionMapping.TryGetValue(triggerMatch, out originalTransition))
{
originalTriggerInUpdatedDefinition++;
if (originalTransition.IsUnconditional)
{
string errorMessage;
bool canTransitionBeUpdated = ValidateDUInUnconditionalTransition(metadata, updatedTransition, originalTransition, out errorMessage);
if (!canTransitionBeUpdated)
{
metadata.DisallowUpdateInsideThisActivity(errorMessage);
return;
}
}
else
{
if (updatedTransition.IsUnconditional)
{
// cannot change the transition from condition to unconditional.
metadata.DisallowUpdateInsideThisActivity(SR.ChangeConditionalTransitionToUnconditionalBlockDU);
return;
}
else
{
string errorMessage;
bool canTransitionBeUpdated = ValidateDUInConditionTransition(metadata, updatedTransition, originalTransition, out errorMessage);
if (!canTransitionBeUpdated)
{
metadata.DisallowUpdateInsideThisActivity(errorMessage);
return;
}
}
}
}
else
{
// the trigger is an child activity moved from elsewhere within the state
metadata.DisallowUpdateInsideThisActivity(SR.MovingActivitiesInStateBlockDU);
return;
}
}
else
{
// new Trigger activity
foreach (TransitionData transitionData in updatedTransition.TransitionDataList)
{
if ((null != transitionData.Condition && null != metadata.GetMatch(transitionData.Condition)) ||
(null != transitionData.Action && null != metadata.GetMatch(transitionData.Action)))
{
// if a new transition is added, it is expected that the Condition/Action
// are newly created.
metadata.DisallowUpdateInsideThisActivity(SR.ChangingTriggerOrUseOriginalConditionActionBlockDU);
return;
}
}
}
}
if (originalTriggerInUpdatedDefinition != originalInternalState.internalTransitions.Count)
{
// NOTE: in general, if the transition is removed when there are pending triggers,
// runtime would be able to detect the missing child activities. However, in cases,
// where the transition is happening already (in between completion of Transition.Action
// callback but before InternalState is completed), the workflow definition can be unloaded
// and updated. The InternalState is unable to trace the original transition that set the
// destination state index. In that case, the update would fail at UpdateInstance.
// To simplify the model, it is more convenient to disallow removing existing transitions
// from an executing InternalState. The only extra restriction it brings, is that it disables
// update even if the InternalState is uploaded at State.Entry. This scenario, however, is uncommon.
metadata.DisallowUpdateInsideThisActivity(SR.RemovingTransitionsBlockDU);
}
}
protected override void UpdateInstance(NativeActivityUpdateContext updateContext)
{
StateMachineEventManager eventManager = updateContext.GetValue(this.EventManager) as StateMachineEventManager;
Fx.Assert(eventManager != null, "eventManager is available in every internalActivity.");
if (eventManager.CurrentBeingProcessedEvent != null || eventManager.Queue.Any())
{
// Updated state is evaluating conditions or transitioning to another state,
// Then we need to update the index of the current evaluated trigger (in case the trigger is moved)
// and the condition index.
// if the state is transitioning already, then we should update destination state id.
bool isUpdateSuccessful = this.UpdateEventManager(updateContext, eventManager);
if (!isUpdateSuccessful)
{
updateContext.DisallowUpdate(SR.DUTriggerOrConditionChangedDuringTransitioning);
return;
}
if (updateContext.GetValue(this.isExiting) != true)
{
this.RescheduleNewlyAddedTriggers(updateContext);
}
}
else if (updateContext.GetValue(this.currentRunningTriggers) > 0)
{
Fx.Assert(updateContext.GetValue(this.isExiting) != true, "No triggers have completed, state should not be transitioning.");
// the state is not transitioning yet and is persisted at trigger.
this.RescheduleNewlyAddedTriggers(updateContext);
}
}
static void AddTransitionData(NativeActivityMetadata metadata, InternalTransition internalTransition, Transition transition)
{
TransitionData transitionData = new TransitionData();
Activity<bool> condition = transition.Condition;
transitionData.Condition = condition;
if (condition != null)
{
metadata.AddChild(condition);
}
Activity action = transition.Action;
transitionData.Action = action;
if (action != null)
{
metadata.AddChild(action);
}
if (transition.To != null)
{
transitionData.To = transition.To.InternalState;
}
internalTransition.TransitionDataList.Add(transitionData);
}
static void ProcessNextTriggerCompletedEvent(NativeActivityContext context, StateMachineEventManager eventManager)
{
eventManager.CurrentBeingProcessedEvent = null;
eventManager.OnTransition = false;
TriggerCompletedEvent completedEvent = eventManager.GetNextCompletedEvent();
if (completedEvent != null)
{
StateMachineExtension extension = context.GetExtension<StateMachineExtension>();
Fx.Assert(extension != null, "Failed to obtain a StateMachineExtension.");
extension.ResumeBookmark(completedEvent.Bookmark);
}
}
private static bool ValidateDUInConditionTransition(NativeActivityUpdateMapMetadata metadata, InternalTransition updatedTransition, InternalTransition originalTransition, out string errorMessage)
{
Fx.Assert(!originalTransition.IsUnconditional, "Transition should be conditional in the original definition.");
errorMessage = string.Empty;
foreach (TransitionData updatedTData in updatedTransition.TransitionDataList)
{
if (metadata.IsReferenceToImportedChild(updatedTData.Condition))
{
// if the trigger is referenced, it might have another save values already.
errorMessage = SR.TriggerOrConditionIsReferenced;
return false;
}
Fx.Assert(null != updatedTData.Condition, "Must be a condition transition.");
Activity conditionMatch = metadata.GetMatch(updatedTData.Condition);
if (null == conditionMatch && null != metadata.GetMatch(updatedTData.Action))
{
// new Transition.Condition with an Transition.Action moved from within the InternalState.
errorMessage = SR.MovingActivitiesInStateBlockDU;
return false;
}
else if (null != conditionMatch)
{
bool foundMatchin----ginalCondition = false;
for (int transitionIndex = 0; transitionIndex < originalTransition.TransitionDataList.Count; transitionIndex++)
{
if (object.ReferenceEquals(originalTransition.TransitionDataList[transitionIndex].Condition, conditionMatch))
{
foundMatchin----ginalCondition = true;
// found the original matching condition in updated transition definition.
TransitionData originalTData = originalTransition.TransitionDataList[transitionIndex];
Activity originalAction = originalTData.Action;
// NOTE: Transition.Action is allowed to be removed, because it doesn't change the execution semantics of SM
// if this removed activity was executing, WF runtime would disallow the update.
Activity actionMatch = metadata.GetMatch(updatedTData.Action);
if (null != actionMatch && !object.ReferenceEquals(originalAction, actionMatch))
{
// Transition.Action is an activity moved from elsewhere within the InternalState
errorMessage = SR.MovingActivitiesInStateBlockDU;
return false;
}
metadata.SaveOriginalValue(updatedTransition.Trigger, originalTransition.InternalTransitionIndex);
metadata.SaveOriginalValue(updatedTData.Condition, transitionIndex);
}
}
if (!foundMatchin----ginalCondition)
{
// another child activity is move to the Transition.Condition.
errorMessage = SR.DUDisallowIfCannotFindingMatchingCondition;
return false;
}
}
}
return true;
}
private static bool ValidateDUInUnconditionalTransition(NativeActivityUpdateMapMetadata metadata, InternalTransition updatedTransition, InternalTransition originalTransition, out string errorMessage)
{
Fx.Assert(originalTransition.IsUnconditional, "Transition should be unconditional in the original definition.");
Activity originalAction = originalTransition.TransitionDataList[0].Action;
foreach (TransitionData transitionData in updatedTransition.TransitionDataList)
{
Activity updatedAction = transitionData.Action;
Activity actionMatch = metadata.GetMatch(updatedAction);
Activity conditionMatch = metadata.GetMatch(transitionData.Condition);
if ((null == originalAction && null != actionMatch) ||
(null != originalAction && null != actionMatch && !object.ReferenceEquals(originalAction, actionMatch)))
{
// Transition.Action is an activity moved from elsewhere within the InternalState
errorMessage = SR.MovingActivitiesInStateBlockDU;
return false;
}
}
errorMessage = string.Empty;
metadata.SaveOriginalValue(updatedTransition.Trigger, originalTransition.InternalTransitionIndex);
return true;
}
private void RescheduleNewlyAddedTriggers(NativeActivityUpdateContext updateContext)
{
// NOTE: triggers are scheduled already, so the state has completed executing State.Entry
Fx.Assert(this.internalTransitions.Count == this.triggerInternalTransitionMapping.Count, "Triggers mappings are correct.");
List<Activity> newTriggers = new List<Activity>();
foreach (InternalTransition transition in this.internalTransitions)
{
if (updateContext.IsNewlyAdded(transition.Trigger))
{
newTriggers.Add(transition.Trigger);
}
// NOTE: all Triggers in triggerInternalTransitionMapping are either new or was previously scheduled
}
foreach (Activity newTrigger in newTriggers)
{
updateContext.ScheduleActivity(newTrigger, this.onTriggerComplete);
}
updateContext.SetValue<int>(this.currentRunningTriggers, updateContext.GetValue(this.currentRunningTriggers) + newTriggers.Count);
}
/// <summary>
/// Used for Dynamic Update: after the instance is updated, if the statemachine is already transitioning, the index of the to-be-scheduled state
/// would need to be updated.
/// </summary>
/// <param name="updateContext">Dynamic Update context</param>
/// <param name="eventManager">Internal StateMachineEventManager</param>
/// <returns>True, 1. if update is successful and the instanced is updated with the new indexes, and 2 all the trigger ID in the queue are updated;
/// false otherwise and the update should fail.</returns>
private bool UpdateEventManager(
NativeActivityUpdateContext updateContext,
StateMachineEventManager eventManager)
{
Fx.Assert(null != eventManager.CurrentBeingProcessedEvent, "The eventManager must have some info that needs to be updated during transition.");
int updatedEventsInQueue = 0;
int originalTriggerId = int.MinValue;
int originalConditionIndex = int.MinValue;
bool updateCurrentEventSucceed = null == eventManager.CurrentBeingProcessedEvent ? true : false;
foreach (InternalTransition transition in this.internalTransitions)
{
object savedTriggerIndex = updateContext.GetSavedOriginalValue(transition.Trigger);
if (savedTriggerIndex != null)
{
Fx.Assert(!updateContext.IsNewlyAdded(transition.Trigger), "the trigger in transition already exist.");
if (null != eventManager.CurrentBeingProcessedEvent &&
eventManager.CurrentBeingProcessedEvent.TriggedId == (int)savedTriggerIndex)
{
// found a match of the running trigger update the current processed event
// Don't match the trigger ID, match only when the Condition is also matched.
if (eventManager.CurrentConditionIndex == -1)
{
if (transition.IsUnconditional)
{
// executing transition before persist is unconditional
originalTriggerId = eventManager.CurrentBeingProcessedEvent.TriggedId;
originalConditionIndex = 0;
eventManager.CurrentBeingProcessedEvent.TriggedId = transition.InternalTransitionIndex;
if (updateContext.GetValue(this.isExiting))
{
Fx.Assert(eventManager.OnTransition, "The state is transitioning.");
updateContext.SetValue(this.Result, GetTo(transition.InternalTransitionIndex));
}
updateCurrentEventSucceed = true;
}
else
{
updateContext.DisallowUpdate(SR.ChangeTransitionTypeDuringTransitioningBlockDU);
return false;
}
}
else if (eventManager.CurrentConditionIndex >= 0)
{
Fx.Assert(!transition.IsUnconditional, "Cannot update a running conditional transition with a unconditional one.");
if (!transition.IsUnconditional)
{
// executing transition before and after are conditional
for (int updatedIndex = 0; updatedIndex < transition.TransitionDataList.Count; updatedIndex++)
{
Activity condition = transition.TransitionDataList[updatedIndex].Condition;
Fx.Assert(null != condition, "Conditional transition must have Condition activity.");
int? savedCondIndex = updateContext.GetSavedOriginalValue(condition) as int?;
if (eventManager.CurrentConditionIndex == savedCondIndex)
{
originalTriggerId = eventManager.CurrentBeingProcessedEvent.TriggedId;
originalConditionIndex = eventManager.CurrentConditionIndex;
eventManager.CurrentBeingProcessedEvent.TriggedId = transition.InternalTransitionIndex;
eventManager.CurrentConditionIndex = updatedIndex;
if (updateContext.GetValue(this.isExiting))
{
Fx.Assert(eventManager.OnTransition, "The state is transitioning.");
updateContext.SetValue(this.Result, this.GetTo(transition.InternalTransitionIndex, (int)updatedIndex));
}
updateCurrentEventSucceed = true;
break;
}
}
}
}
}
foreach (TriggerCompletedEvent completedEvent in eventManager.Queue)
{
if ((int)savedTriggerIndex == completedEvent.TriggedId)
{
completedEvent.TriggedId = transition.InternalTransitionIndex;
updatedEventsInQueue++;
}
}
}
}
return eventManager.Queue.Count() == updatedEventsInQueue ? updateCurrentEventSucceed : false;
}
void ScheduleEntry(NativeActivityContext context)
{
context.Track(new StateMachineStateRecord
{
StateMachineName = this.StateMachineName,
StateName = this.DisplayName,
});
if (this.Entry != null)
{
context.ScheduleActivity(this.Entry, this.onEntryComplete);
}
else
{
this.onEntryComplete(context, null);
}
}
void OnEntryComplete(NativeActivityContext context, ActivityInstance instance)
{
ProcessNextTriggerCompletedEvent(context, this.EventManager.Get(context));
this.ScheduleTriggers(context);
}
void ScheduleTriggers(NativeActivityContext context)
{
if (!this.IsFinal)
{
// Final state need not condition evaluation bookmark.
this.AddEvaluateConditionBookmark(context);
}
if (this.internalTransitions.Count > 0)
{
foreach (InternalTransition transition in this.internalTransitions)
{
context.ScheduleActivity(transition.Trigger, this.onTriggerComplete);
}
this.currentRunningTriggers.Set(context, this.currentRunningTriggers.Get(context) + this.internalTransitions.Count);
}
}
void OnTriggerComplete(NativeActivityContext context, ActivityInstance completedInstance)
{
int runningTriggers = this.currentRunningTriggers.Get(context);
this.currentRunningTriggers.Set(context, --runningTriggers);
bool isOnExit = this.isExiting.Get(context);
if (!context.IsCancellationRequested && runningTriggers == 0 && isOnExit)
{
this.ScheduleExit(context);
}
else if (completedInstance.State == ActivityInstanceState.Closed)
{
InternalTransition internalTransition = null;
this.triggerInternalTransitionMapping.TryGetValue(completedInstance.Activity, out internalTransition);
Fx.Assert(internalTransition != null, "internalTransition should be added into triggerInternalTransitionMapping in CacheMetadata.");
StateMachineEventManager eventManager = this.EventManager.Get(context);
bool canBeProcessedImmediately;
eventManager.RegisterCompletedEvent(
new TriggerCompletedEvent { Bookmark = this.evaluateConditionBookmark.Get(context), TriggedId = internalTransition.InternalTransitionIndex },
out canBeProcessedImmediately);
if (canBeProcessedImmediately)
{
ProcessNextTriggerCompletedEvent(context, eventManager);
}
}
}
void StartEvaluateCondition(NativeActivityContext context, Bookmark bookmark, object value)
{
// Start to evaluate conditions of the trigger which represented by currentTriggerIndex
StateMachineEventManager eventManager = this.EventManager.Get(context);
int triggerId = eventManager.CurrentBeingProcessedEvent.TriggedId;
InternalTransition transition = this.GetInternalTransition(triggerId);
if (transition.IsUnconditional)
{
eventManager.CurrentConditionIndex = -1;
this.TakeTransition(context, eventManager, triggerId);
}
else
{
eventManager.CurrentConditionIndex = 0;
context.ScheduleActivity<bool>(
this.GetCondition(
triggerId,
eventManager.CurrentConditionIndex),
this.onConditionComplete,
null);
}
}
void OnConditionComplete(NativeActivityContext context, ActivityInstance completedInstance, bool result)
{
StateMachineEventManager eventManager = this.EventManager.Get(context);
int triggerId = eventManager.CurrentBeingProcessedEvent.TriggedId;
if (result)
{
this.TakeTransition(context, eventManager, triggerId);
}
else
{
// condition failed: reschedule trigger
int currentConditionIndex = eventManager.CurrentConditionIndex;
Fx.Assert(eventManager.CurrentConditionIndex >= 0, "Conditional Transition must have non-negative index.");
InternalTransition transition = this.GetInternalTransition(triggerId);
currentConditionIndex++;
if (currentConditionIndex < transition.TransitionDataList.Count)
{
eventManager.CurrentConditionIndex = currentConditionIndex;
context.ScheduleActivity<bool>(transition.TransitionDataList[currentConditionIndex].Condition, this.onConditionComplete, null);
}
else
{
// Schedule current trigger again firstly.
context.ScheduleActivity(transition.Trigger, this.onTriggerComplete);
this.currentRunningTriggers.Set(context, this.currentRunningTriggers.Get(context) + 1);
// check whether there is any other trigger completed.
ProcessNextTriggerCompletedEvent(context, eventManager);
}
}
}
void ScheduleExit(NativeActivityContext context)
{
if (this.Exit != null)
{
context.ScheduleActivity(this.Exit, this.onExitComplete);
}
else
{
this.onExitComplete(context, null);
}
}
void OnExitComplete(NativeActivityContext context, ActivityInstance instance)
{
this.ScheduleAction(context);
}
void ScheduleAction(NativeActivityContext context)
{
StateMachineEventManager eventManager = this.EventManager.Get(context);
if (eventManager.IsReferredByBeingProcessedEvent(this.evaluateConditionBookmark.Get(context)))
{
InternalTransition transition = this.GetInternalTransition(eventManager.CurrentBeingProcessedEvent.TriggedId);
Activity action = transition.TransitionDataList[-1 == eventManager.CurrentConditionIndex ? 0 : eventManager.CurrentConditionIndex].Action;
if (action != null)
{
context.ScheduleActivity(action);
}
}
this.RemoveBookmarks(context);
}
void ProcessTransitions(NativeActivityMetadata metadata)
{
for (int i = 0; i < this.Transitions.Count; i++)
{
Transition transition = this.Transitions[i];
InternalTransition internalTransition = null;
Activity triggerActivity = transition.ActiveTrigger;
if (!this.triggerInternalTransitionMapping.TryGetValue(triggerActivity, out internalTransition))
{
metadata.AddChild(triggerActivity);
internalTransition = new InternalTransition
{
Trigger = triggerActivity,
InternalTransitionIndex = this.internalTransitions.Count,
};
this.triggerInternalTransitionMapping.Add(triggerActivity, internalTransition);
this.internalTransitions.Add(internalTransition);
}
AddTransitionData(metadata, internalTransition, transition);
}
}
InternalTransition GetInternalTransition(int triggerIndex)
{
return this.internalTransitions[triggerIndex];
}
Activity<bool> GetCondition(int triggerIndex, int conditionIndex)
{
return this.internalTransitions[triggerIndex].TransitionDataList[conditionIndex].Condition;
}
string GetTo(int triggerIndex, int conditionIndex = 0)
{
return this.internalTransitions[triggerIndex].TransitionDataList[conditionIndex].To.StateId;
}
void AddEvaluateConditionBookmark(NativeActivityContext context)
{
Bookmark bookmark = context.CreateBookmark(this.evaluateConditionCallback, BookmarkOptions.MultipleResume);
this.evaluateConditionBookmark.Set(context, bookmark);
this.EventManager.Get(context).AddActiveBookmark(bookmark);
}
void RemoveBookmarks(NativeActivityContext context)
{
context.RemoveAllBookmarks();
this.RemoveActiveBookmark(context);
}
void RemoveActiveBookmark(ActivityContext context)
{
StateMachineEventManager eventManager = this.EventManager.Get(context);
Bookmark bookmark = this.evaluateConditionBookmark.Get(context);
if (bookmark != null)
{
eventManager.RemoveActiveBookmark(bookmark);
}
}
void TakeTransition(NativeActivityContext context, StateMachineEventManager eventManager, int triggerId)
{
this.EventManager.Get(context).OnTransition = true;
InternalTransition transition = this.GetInternalTransition(triggerId);
if (transition.IsUnconditional)
{
Fx.Assert(-1 == eventManager.CurrentConditionIndex, "CurrentConditionIndex should be -1, if the transition is unconditional.");
this.PrepareForExit(context, this.GetTo(triggerId));
}
else
{
Fx.Assert(-1 != eventManager.CurrentConditionIndex, "CurrentConditionIndex should not be -1, if the transition is conditional.");
this.PrepareForExit(context, this.GetTo(triggerId, eventManager.CurrentConditionIndex));
}
}
void PrepareForExit(NativeActivityContext context, string targetStateId)
{
ReadOnlyCollection<ActivityInstance> children = context.GetChildren();
this.Result.Set(context, targetStateId);
this.isExiting.Set(context, true);
if (children.Count > 0)
{
// Cancel all other pending triggers.
context.CancelChildren();
}
else
{
this.ScheduleExit(context);
}
}
}
}
| 0 | 0.956537 | 1 | 0.956537 | game-dev | MEDIA | 0.288192 | game-dev | 0.90943 | 1 | 0.90943 |
FoxMCTeam/TenacityRecode-master | 11,314 | src/java/net/minecraft/entity/item/EntityFallingBlock.java | package net.minecraft.entity.item;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAnvil;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.world.World;
import java.util.List;
public class EntityFallingBlock extends Entity
{
private IBlockState fallTile;
public int fallTime;
public boolean shouldDropItem = true;
private boolean canSetAsBlock;
private boolean hurtEntities;
private int fallHurtMax = 40;
private float fallHurtAmount = 2.0F;
public NBTTagCompound tileEntityData;
public EntityFallingBlock(World worldIn)
{
super(worldIn);
}
public EntityFallingBlock(World worldIn, double x, double y, double z, IBlockState fallingBlockState)
{
super(worldIn);
this.fallTile = fallingBlockState;
this.preventEntitySpawning = true;
this.setSize(0.98F, 0.98F);
this.setPosition(x, y, z);
this.motionX = 0.0D;
this.motionY = 0.0D;
this.motionZ = 0.0D;
this.prevPosX = x;
this.prevPosY = y;
this.prevPosZ = z;
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to
* prevent them from trampling crops
*/
protected boolean canTriggerWalking()
{
return false;
}
protected void entityInit()
{
}
/**
* Returns true if other Entities should be prevented from moving through this Entity.
*/
public boolean canBeCollidedWith()
{
return !this.isDead;
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
Block block = this.fallTile.getBlock();
if (block.getMaterial() == Material.air)
{
this.setDead();
}
else
{
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
if (this.fallTime++ == 0)
{
BlockPos blockpos = new BlockPos(this);
if (this.worldObj.getBlockState(blockpos).getBlock() == block)
{
this.worldObj.setBlockToAir(blockpos);
}
else if (!this.worldObj.isRemote)
{
this.setDead();
return;
}
}
this.motionY -= 0.03999999910593033D;
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.9800000190734863D;
this.motionY *= 0.9800000190734863D;
this.motionZ *= 0.9800000190734863D;
if (!this.worldObj.isRemote)
{
BlockPos blockpos1 = new BlockPos(this);
if (this.onGround)
{
this.motionX *= 0.699999988079071D;
this.motionZ *= 0.699999988079071D;
this.motionY *= -0.5D;
if (this.worldObj.getBlockState(blockpos1).getBlock() != Blocks.piston_extension)
{
this.setDead();
if (!this.canSetAsBlock)
{
if (this.worldObj.canBlockBePlaced(block, blockpos1, true, EnumFacing.UP, (Entity)null, (ItemStack)null) && !BlockFalling.canFallInto(this.worldObj, blockpos1.down()) && this.worldObj.setBlockState(blockpos1, this.fallTile, 3))
{
if (block instanceof BlockFalling)
{
((BlockFalling)block).onEndFalling(this.worldObj, blockpos1);
}
if (this.tileEntityData != null && block instanceof ITileEntityProvider)
{
TileEntity tileentity = this.worldObj.getTileEntity(blockpos1);
if (tileentity != null)
{
NBTTagCompound nbttagcompound = new NBTTagCompound();
tileentity.writeToNBT(nbttagcompound);
for (String s : this.tileEntityData.getKeySet())
{
NBTBase nbtbase = this.tileEntityData.getTag(s);
if (!s.equals("x") && !s.equals("y") && !s.equals("z"))
{
nbttagcompound.setTag(s, nbtbase.copy());
}
}
tileentity.readFromNBT(nbttagcompound);
tileentity.markDirty();
}
}
}
else if (this.shouldDropItem && this.worldObj.getGameRules().getBoolean("doEntityDrops"))
{
this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F);
}
}
}
}
else if (this.fallTime > 100 && !this.worldObj.isRemote && (blockpos1.getY() < 1 || blockpos1.getY() > 256) || this.fallTime > 600)
{
if (this.shouldDropItem && this.worldObj.getGameRules().getBoolean("doEntityDrops"))
{
this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F);
}
this.setDead();
}
}
}
}
public void fall(float distance, float damageMultiplier)
{
Block block = this.fallTile.getBlock();
if (this.hurtEntities)
{
int i = MathHelper.ceiling_float_int(distance - 1.0F);
if (i > 0)
{
List<Entity> list = Lists.newArrayList(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox()));
boolean flag = block == Blocks.anvil;
DamageSource damagesource = flag ? DamageSource.anvil : DamageSource.fallingBlock;
for (Entity entity : list)
{
entity.attackEntityFrom(damagesource, (float)Math.min(MathHelper.floor_float((float)i * this.fallHurtAmount), this.fallHurtMax));
}
if (flag && (double)this.rand.nextFloat() < 0.05000000074505806D + (double)i * 0.05D)
{
int j = ((Integer)this.fallTile.getValue(BlockAnvil.DAMAGE)).intValue();
++j;
if (j > 2)
{
this.canSetAsBlock = true;
}
else
{
this.fallTile = this.fallTile.withProperty(BlockAnvil.DAMAGE, Integer.valueOf(j));
}
}
}
}
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
protected void writeEntityToNBT(NBTTagCompound tagCompound)
{
Block block = this.fallTile != null ? this.fallTile.getBlock() : Blocks.air;
ResourceLocation resourcelocation = (ResourceLocation)Block.blockRegistry.getNameForObject(block);
tagCompound.setString("Block", resourcelocation == null ? "" : resourcelocation.toString());
tagCompound.setByte("Data", (byte)block.getMetaFromState(this.fallTile));
tagCompound.setByte("Time", (byte)this.fallTime);
tagCompound.setBoolean("DropItem", this.shouldDropItem);
tagCompound.setBoolean("HurtEntities", this.hurtEntities);
tagCompound.setFloat("FallHurtAmount", this.fallHurtAmount);
tagCompound.setInteger("FallHurtMax", this.fallHurtMax);
if (this.tileEntityData != null)
{
tagCompound.setTag("TileEntityData", this.tileEntityData);
}
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
protected void readEntityFromNBT(NBTTagCompound tagCompund)
{
int i = tagCompund.getByte("Data") & 255;
if (tagCompund.hasKey("Block", 8))
{
this.fallTile = Block.getBlockFromName(tagCompund.getString("Block")).getStateFromMeta(i);
}
else if (tagCompund.hasKey("TileID", 99))
{
this.fallTile = Block.getBlockById(tagCompund.getInteger("TileID")).getStateFromMeta(i);
}
else
{
this.fallTile = Block.getBlockById(tagCompund.getByte("Tile") & 255).getStateFromMeta(i);
}
this.fallTime = tagCompund.getByte("Time") & 255;
Block block = this.fallTile.getBlock();
if (tagCompund.hasKey("HurtEntities", 99))
{
this.hurtEntities = tagCompund.getBoolean("HurtEntities");
this.fallHurtAmount = tagCompund.getFloat("FallHurtAmount");
this.fallHurtMax = tagCompund.getInteger("FallHurtMax");
}
else if (block == Blocks.anvil)
{
this.hurtEntities = true;
}
if (tagCompund.hasKey("DropItem", 99))
{
this.shouldDropItem = tagCompund.getBoolean("DropItem");
}
if (tagCompund.hasKey("TileEntityData", 10))
{
this.tileEntityData = tagCompund.getCompoundTag("TileEntityData");
}
if (block == null || block.getMaterial() == Material.air)
{
this.fallTile = Blocks.sand.getDefaultState();
}
}
public World getWorldObj()
{
return this.worldObj;
}
public void setHurtEntities(boolean p_145806_1_)
{
this.hurtEntities = p_145806_1_;
}
/**
* Return whether this entity should be rendered as on fire.
*/
public boolean canRenderOnFire()
{
return false;
}
public void addEntityCrashInfo(CrashReportCategory category)
{
super.addEntityCrashInfo(category);
if (this.fallTile != null)
{
Block block = this.fallTile.getBlock();
category.addCrashSection("Immitating block ID", Integer.valueOf(Block.getIdFromBlock(block)));
category.addCrashSection("Immitating block data", Integer.valueOf(block.getMetaFromState(this.fallTile)));
}
}
public IBlockState getBlock()
{
return this.fallTile;
}
}
| 0 | 0.934292 | 1 | 0.934292 | game-dev | MEDIA | 0.997979 | game-dev | 0.993887 | 1 | 0.993887 |
jinglikeblue/ZeroGameKit | 1,347 | Assets/Examples/PingPong/Client/AI/AICore.cs | using System.Collections.Generic;
namespace PingPong
{
/// <summary>
/// AI核心
/// </summary>
public class AICore
{
/// <summary>
/// 最后一次更新时的GameCore帧数
/// </summary>
ulong _lastUpdateFrame = ulong.MaxValue;
List<PlayerAgent> _agentList;
public bool enabled = true;
/// <summary>
/// AI核心初始化
/// </summary>
public void Init(int[] playerIndexs)
{
_agentList = new List<PlayerAgent>();
foreach (var playerIndex in playerIndexs)
{
_agentList.Add(new PlayerAgent(playerIndex));
}
}
/// <summary>
/// 更新AI核心
/// </summary>
/// <param name="gameCore"></param>
/// <returns>返回是否AI核心进行了更新</returns>
public bool Update(GameCore gameCore)
{
if (_lastUpdateFrame == gameCore.FrameData.elapsedFrames || false == enabled)
{
return false;
}
_lastUpdateFrame = gameCore.FrameData.elapsedFrames;
foreach (var agent in _agentList)
{
agent.Update(gameCore);
}
return true;
}
public PlayerAgent[] GetAgents()
{
return _agentList?.ToArray();
}
}
}
| 0 | 0.725377 | 1 | 0.725377 | game-dev | MEDIA | 0.910153 | game-dev | 0.863625 | 1 | 0.863625 |
jedis/jediacademy | 7,752 | codemp/botlib/be_aas_def.h |
/*****************************************************************************
* name: be_aas_def.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_def.h $
* $Author: osman $
* $Revision: 1.4 $
* $Modtime: 10/05/99 3:32p $
* $Date: 2003/03/15 23:43:54 $
*
*****************************************************************************/
//debugging on
#define AAS_DEBUG
// these are also in q_shared.h - argh (rjr)
#ifdef _XBOX
#define MAX_CLIENTS 16
#else
#define MAX_CLIENTS 32
#endif
#define MAX_RADAR_ENTITIES MAX_GENTITIES
#define MAX_MODELS 512 // these are sent over the net as 8 bits
#define MAX_SOUNDS 256 // so they cannot be blindly increased
// these are also in bg_public.h - argh (rjr)
#define CS_SCORES 32
#define CS_MODELS (CS_SCORES+MAX_CLIENTS)
#define CS_SOUNDS (CS_MODELS+MAX_MODELS)
#define DF_AASENTNUMBER(x) (x - aasworld.entities)
#define DF_NUMBERAASENT(x) (&aasworld.entities[x])
#define DF_AASENTCLIENT(x) (x - aasworld.entities - 1)
#define DF_CLIENTAASENT(x) (&aasworld.entities[x + 1])
#ifndef MAX_PATH
#define MAX_PATH MAX_QPATH
#endif
//string index (for model, sound and image index)
typedef struct aas_stringindex_s
{
int numindexes;
char **index;
} aas_stringindex_t;
//structure to link entities to areas and areas to entities
typedef struct aas_link_s
{
int entnum;
int areanum;
struct aas_link_s *next_ent, *prev_ent;
struct aas_link_s *next_area, *prev_area;
} aas_link_t;
//structure to link entities to leaves and leaves to entities
typedef struct bsp_link_s
{
int entnum;
int leafnum;
struct bsp_link_s *next_ent, *prev_ent;
struct bsp_link_s *next_leaf, *prev_leaf;
} bsp_link_t;
typedef struct bsp_entdata_s
{
vec3_t origin;
vec3_t angles;
vec3_t absmins;
vec3_t absmaxs;
int solid;
int modelnum;
} bsp_entdata_t;
//entity
typedef struct aas_entity_s
{
//entity info
aas_entityinfo_t i;
//links into the AAS areas
aas_link_t *areas;
//links into the BSP leaves
bsp_link_t *leaves;
} aas_entity_t;
typedef struct aas_settings_s
{
vec3_t phys_gravitydirection;
float phys_friction;
float phys_stopspeed;
float phys_gravity;
float phys_waterfriction;
float phys_watergravity;
float phys_maxvelocity;
float phys_maxwalkvelocity;
float phys_maxcrouchvelocity;
float phys_maxswimvelocity;
float phys_walkaccelerate;
float phys_airaccelerate;
float phys_swimaccelerate;
float phys_maxstep;
float phys_maxsteepness;
float phys_maxwaterjump;
float phys_maxbarrier;
float phys_jumpvel;
float phys_falldelta5;
float phys_falldelta10;
float rs_waterjump;
float rs_teleport;
float rs_barrierjump;
float rs_startcrouch;
float rs_startgrapple;
float rs_startwalkoffledge;
float rs_startjump;
float rs_rocketjump;
float rs_bfgjump;
float rs_jumppad;
float rs_aircontrolledjumppad;
float rs_funcbob;
float rs_startelevator;
float rs_falldamage5;
float rs_falldamage10;
float rs_maxfallheight;
float rs_maxjumpfallheight;
} aas_settings_t;
#define CACHETYPE_PORTAL 0
#define CACHETYPE_AREA 1
//routing cache
typedef struct aas_routingcache_s
{
byte type; //portal or area cache
float time; //last time accessed or updated
int size; //size of the routing cache
int cluster; //cluster the cache is for
int areanum; //area the cache is created for
vec3_t origin; //origin within the area
float starttraveltime; //travel time to start with
int travelflags; //combinations of the travel flags
struct aas_routingcache_s *prev, *next;
struct aas_routingcache_s *time_prev, *time_next;
unsigned char *reachabilities; //reachabilities used for routing
unsigned short int traveltimes[1]; //travel time for every area (variable sized)
} aas_routingcache_t;
//fields for the routing algorithm
typedef struct aas_routingupdate_s
{
int cluster;
int areanum; //area number of the update
vec3_t start; //start point the area was entered
unsigned short int tmptraveltime; //temporary travel time
unsigned short int *areatraveltimes; //travel times within the area
qboolean inlist; //true if the update is in the list
struct aas_routingupdate_s *next;
struct aas_routingupdate_s *prev;
} aas_routingupdate_t;
//reversed reachability link
typedef struct aas_reversedlink_s
{
int linknum; //the aas_areareachability_t
int areanum; //reachable from this area
struct aas_reversedlink_s *next; //next link
} aas_reversedlink_t;
//reversed area reachability
typedef struct aas_reversedreachability_s
{
int numlinks;
aas_reversedlink_t *first;
} aas_reversedreachability_t;
//areas a reachability goes through
typedef struct aas_reachabilityareas_s
{
int firstarea, numareas;
} aas_reachabilityareas_t;
typedef struct aas_s
{
int loaded; //true when an AAS file is loaded
int initialized; //true when AAS has been initialized
int savefile; //set true when file should be saved
int bspchecksum;
//current time
float time;
int numframes;
//name of the aas file
char filename[MAX_PATH];
char mapname[MAX_PATH];
//bounding boxes
int numbboxes;
aas_bbox_t *bboxes;
//vertexes
int numvertexes;
aas_vertex_t *vertexes;
//planes
int numplanes;
aas_plane_t *planes;
//edges
int numedges;
aas_edge_t *edges;
//edge index
int edgeindexsize;
aas_edgeindex_t *edgeindex;
//faces
int numfaces;
aas_face_t *faces;
//face index
int faceindexsize;
aas_faceindex_t *faceindex;
//convex areas
int numareas;
aas_area_t *areas;
//convex area settings
int numareasettings;
aas_areasettings_t *areasettings;
//reachablity list
int reachabilitysize;
aas_reachability_t *reachability;
//nodes of the bsp tree
int numnodes;
aas_node_t *nodes;
//cluster portals
int numportals;
aas_portal_t *portals;
//cluster portal index
int portalindexsize;
aas_portalindex_t *portalindex;
//clusters
int numclusters;
aas_cluster_t *clusters;
//
int numreachabilityareas;
float reachabilitytime;
//enities linked in the areas
aas_link_t *linkheap; //heap with link structures
int linkheapsize; //size of the link heap
aas_link_t *freelinks; //first free link
aas_link_t **arealinkedentities; //entities linked into areas
//entities
int maxentities;
int maxclients;
aas_entity_t *entities;
//string indexes
char *configstrings[MAX_CONFIGSTRINGS];
int indexessetup;
//index to retrieve travel flag for a travel type
int travelflagfortype[MAX_TRAVELTYPES];
//travel flags for each area based on contents
int *areacontentstravelflags;
//routing update
aas_routingupdate_t *areaupdate;
aas_routingupdate_t *portalupdate;
//number of routing updates during a frame (reset every frame)
int frameroutingupdates;
//reversed reachability links
aas_reversedreachability_t *reversedreachability;
//travel times within the areas
unsigned short ***areatraveltimes;
//array of size numclusters with cluster cache
aas_routingcache_t ***clusterareacache;
aas_routingcache_t **portalcache;
//cache list sorted on time
aas_routingcache_t *oldestcache; // start of cache list sorted on time
aas_routingcache_t *newestcache; // end of cache list sorted on time
//maximum travel time through portal areas
int *portalmaxtraveltimes;
//areas the reachabilities go through
int *reachabilityareaindex;
aas_reachabilityareas_t *reachabilityareas;
} aas_t;
#define AASINTERN
#ifndef BSPCINCLUDE
#include "be_aas_main.h"
#include "be_aas_entity.h"
#include "be_aas_sample.h"
#include "be_aas_cluster.h"
#include "be_aas_reach.h"
#include "be_aas_route.h"
#include "be_aas_routealt.h"
#include "be_aas_debug.h"
#include "be_aas_file.h"
#include "be_aas_optimize.h"
#include "be_aas_bsp.h"
#include "be_aas_move.h"
#endif //BSPCINCLUDE
| 0 | 0.746778 | 1 | 0.746778 | game-dev | MEDIA | 0.688059 | game-dev | 0.564499 | 1 | 0.564499 |
Ideefixze/TutorialUnityMultiplayer | 2,251 | MultiplayerArchitectureUnity/Library/PackageCache/com.unity.ide.visualstudio@2.0.2/Editor/FileUtility.cs | /*---------------------------------------------------------------------------------------------
* Copyright (c) Unity Technologies.
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Microsoft.Unity.VisualStudio.Editor
{
internal static class FileUtility
{
public const char WinSeparator = '\\';
public const char UnixSeparator = '/';
// Safe for packages as we use packageInfo.resolvedPath, so this should work in library package cache as well
public static string[] FindPackageAssetFullPath(string assetfilter, string filefilter)
{
return AssetDatabase.FindAssets(assetfilter)
.Select(AssetDatabase.GUIDToAssetPath)
.Where(assetPath => assetPath.Contains(filefilter))
.Select(asset =>
{
var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(asset);
return Normalize(packageInfo.resolvedPath + asset.Substring(packageInfo.assetPath.Length));
})
.ToArray();
}
public static string GetAssetFullPath(string asset)
{
var basePath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
return Path.GetFullPath(Path.Combine(basePath, Normalize(asset)));
}
public static string Normalize(string path)
{
if (string.IsNullOrEmpty(path))
return path;
if (Path.DirectorySeparatorChar == WinSeparator)
path = path.Replace(UnixSeparator, WinSeparator);
if (Path.DirectorySeparatorChar == UnixSeparator)
path = path.Replace(WinSeparator, UnixSeparator);
return path.Replace(string.Concat(WinSeparator, WinSeparator), WinSeparator.ToString());
}
internal static bool IsFileInProjectDirectory(string fileName)
{
var basePath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
fileName = Normalize(fileName);
if (!Path.IsPathRooted(fileName))
fileName = Path.Combine(basePath, fileName);
return string.Equals(Path.GetDirectoryName(fileName), basePath, StringComparison.OrdinalIgnoreCase);
}
}
}
| 0 | 0.924889 | 1 | 0.924889 | game-dev | MEDIA | 0.558255 | game-dev | 0.972507 | 1 | 0.972507 |
space-wizards/RobustToolbox | 2,137 | Robust.Shared/Physics/Systems/SharedPhysicsSystem.World.cs | using System.Collections.Generic;
using System.Numerics;
using Robust.Shared.GameObjects;
using Robust.Shared.Maths;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.ViewVariables;
namespace Robust.Shared.Physics.Systems;
public partial class SharedPhysicsSystem
{
[ViewVariables]
public Vector2 Gravity { get; private set; }
public void SetGravity(Vector2 value)
{
if (Gravity.Equals(value))
return;
Gravity = value;
// TODO: Network + datafield
}
// Box2D has a bunch of methods that work on worlds but in our case separate EntityManager instances are
// separate worlds so we can just treat the physics system as the world.
private bool _autoClearForces;
/// <summary>
/// When substepping the client needs to know about the first position to use for lerping.
/// </summary>
protected readonly Dictionary<EntityUid, EntityUid>
LerpData = new();
// TODO:
// - Add test that movebuffer removes entities moved to nullspace.
// Previously we stored the WorldAABB of the proxy being moved and tracked state.
// The issue is that if something moves multiple times in a tick it can add up, plus it's also done on hotpaths such as physics.
// As such we defer it until we actually try and get contacts, then we can run them in parallel.
/// <summary>
/// Keep a buffer of everything that moved in a tick. This will be used to check for physics contacts.
/// </summary>
[ViewVariables]
internal readonly HashSet<FixtureProxy> MoveBuffer = new();
/// <summary>
/// Track moved grids to know if we need to run checks for them driving over entities.
/// </summary>
[ViewVariables]
internal readonly HashSet<EntityUid> MovedGrids = new();
/// <summary>
/// All awake bodies in the game.
/// </summary>
[ViewVariables]
public readonly HashSet<Entity<PhysicsComponent, TransformComponent>> AwakeBodies = new();
/// <summary>
/// Store last tick's invDT
/// </summary>
private float _invDt0;
}
| 0 | 0.761116 | 1 | 0.761116 | game-dev | MEDIA | 0.974154 | game-dev | 0.627668 | 1 | 0.627668 |
Creators-of-Create/Create | 1,247 | src/main/java/com/simibubi/create/foundation/mixin/compat/xaeros/XaeroFullscreenMapMixin.java | package com.simibubi.create.foundation.mixin.compat.xaeros;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.simibubi.create.Create;
import com.simibubi.create.compat.trainmap.XaeroTrainMap;
import net.minecraft.client.gui.GuiGraphics;
import xaero.map.gui.GuiMap;
@Mixin(GuiMap.class)
public abstract class XaeroFullscreenMapMixin {
@Unique
boolean create$failedToRenderTrainMap = false;
@Inject(method = "render(Lnet/minecraft/client/gui/GuiGraphics;IIF)V", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/gui/GuiGraphics;blit(Lnet/minecraft/resources/ResourceLocation;IIIIII)V"), require = 0)
public void create$xaeroMapFullscreenRender(GuiGraphics graphics, int mouseX, int mouseY, float pt, CallbackInfo ci) {
try {
if (!create$failedToRenderTrainMap)
XaeroTrainMap.onRender(graphics, (GuiMap) (Object) this, mouseX, mouseY, pt);
} catch (Exception e) {
Create.LOGGER.error("Failed to render Xaero's World Map train map integration:", e);
create$failedToRenderTrainMap = true;
}
}
}
| 0 | 0.859685 | 1 | 0.859685 | game-dev | MEDIA | 0.937154 | game-dev | 0.502354 | 1 | 0.502354 |
RavEngine/RavEngine | 5,612 | deps/physx/physx/include/extensions/PxParticleClothCooker.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_CLOTH_COOKER_H
#define PX_PARTICLE_CLOTH_COOKER_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
namespace ExtGpu
{
/**
\brief Holds all the information for a particle cloth constraint used in the PxParticleClothCooker.
\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated.
*/
struct PX_DEPRECATED PxParticleClothConstraint
{
enum
{
eTYPE_INVALID_CONSTRAINT = 0,
eTYPE_HORIZONTAL_CONSTRAINT = 1,
eTYPE_VERTICAL_CONSTRAINT = 2,
eTYPE_DIAGONAL_CONSTRAINT = 4,
eTYPE_BENDING_CONSTRAINT = 8,
eTYPE_DIAGONAL_BENDING_CONSTRAINT = 16,
eTYPE_ALL = eTYPE_HORIZONTAL_CONSTRAINT | eTYPE_VERTICAL_CONSTRAINT | eTYPE_DIAGONAL_CONSTRAINT | eTYPE_BENDING_CONSTRAINT | eTYPE_DIAGONAL_BENDING_CONSTRAINT
};
PxU32 particleIndexA; //!< The first particle index of this constraint.
PxU32 particleIndexB; //!< The second particle index of this constraint.
PxReal length; //!< The distance between particle A and B.
PxU32 constraintType; //!< The type of constraint, see the constraint type enum.
};
/*
\brief Generates PxParticleClothConstraint constraints that connect the individual particles of a particle cloth.
\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated.
*/
class PX_DEPRECATED PxParticleClothCooker
{
public:
virtual void release() = 0;
/**
\brief Generate the constraint list and triangle index list.
\param[in] constraints A pointer to an array of PxParticleClothConstraint constraints. If NULL, the cooker will generate all the constraints. Otherwise, the user-provided constraints will be added.
\param[in] numConstraints The number of user-provided PxParticleClothConstraint s.
*/
virtual void cookConstraints(const PxParticleClothConstraint* constraints = NULL, const PxU32 numConstraints = 0) = 0;
virtual PxU32* getTriangleIndices() = 0; //!< \return A pointer to the triangle indices.
virtual PxU32 getTriangleIndicesCount() = 0; //!< \return The number of triangle indices.
virtual PxParticleClothConstraint* getConstraints() = 0; //!< \return A pointer to the PxParticleClothConstraint constraints.
virtual PxU32 getConstraintCount() = 0; //!< \return The number of constraints.
virtual void calculateMeshVolume() = 0; //!< Computes the volume of a closed mesh and the contraintScale. Expects vertices in local space - 'close' to origin.
virtual PxReal getMeshVolume() = 0; //!< \return The mesh volume calculated by PxParticleClothCooker::calculateMeshVolume.
protected:
virtual ~PxParticleClothCooker() {}
};
} // namespace ExtGpu
/**
\brief Creates a PxParticleClothCooker.
\deprecated Particle-cloth, -rigids, -attachments and -volumes have been deprecated.
\param[in] vertexCount The number of vertices of the particle cloth.
\param[in] inVertices The vertex positions of the particle cloth.
\param[in] triangleIndexCount The number of triangles of the cloth mesh.
\param[in] inTriangleIndices The triangle indices of the cloth mesh
\param[in] constraintTypeFlags The types of constraints to generate. See PxParticleClothConstraint.
\param[in] verticalDirection The vertical direction of the cloth mesh. This is needed to generate the correct horizontal and vertical constraints to model shear stiffness.
\param[in] bendingConstraintMaxAngle The maximum angle (in radians) considered in the bending constraints.
\return A pointer to the new PxParticleClothCooker.
*/
PX_DEPRECATED ExtGpu::PxParticleClothCooker* PxCreateParticleClothCooker(PxU32 vertexCount, physx::PxVec4* inVertices, PxU32 triangleIndexCount, PxU32* inTriangleIndices,
PxU32 constraintTypeFlags = ExtGpu::PxParticleClothConstraint::eTYPE_ALL,
PxVec3 verticalDirection = PxVec3(0.0f, 1.0f, 0.0f), PxReal bendingConstraintMaxAngle = 20.0f*PxTwoPi/360.0f
);
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 0 | 0.849665 | 1 | 0.849665 | game-dev | MEDIA | 0.637123 | game-dev | 0.879558 | 1 | 0.879558 |
VynaaValerie/VynaaMD | 8,758 | plugins/rpg-ulartangga.js |
import Jimp from 'jimp';
import axios from 'axios';
class GameSession {
constructor(id, sMsg) {
this.id = id;
this.players = [];
this.game = new SnakeAndLadderGame(sMsg);
}
}
class SnakeAndLadderGame {
constructor(sMsg) {
this.sendMsg = sMsg;
this.players = [];
this.boardSize = 100;
this.snakesAndLadders = [{
start: 29,
end: 7
}, {
start: 24,
end: 12
}, {
start: 15,
end: 37
}, {
start: 23,
end: 41
}, {
start: 72,
end: 36
}, {
start: 49,
end: 86
}, {
start: 90,
end: 56
}, {
start: 75,
end: 64
}, {
start: 74,
end: 95
}, {
start: 91,
end: 72
}, {
start: 97,
end: 78
}];
this.currentPositions = {};
this.currentPlayerIndex = 0;
this.bgImageUrl = 'https://i.pinimg.com/originals/2f/68/a7/2f68a7e1eee18556b055418f7305b3c0.jpg';
this.player1ImageUrl = 'https://i.pinimg.com/originals/75/33/22/7533227c53f6c270a96d364b595d6dd5.jpg';
this.player2ImageUrl = 'https://i.pinimg.com/originals/be/68/13/be6813a6086681070b0f886d33ca4df9.jpg';
this.bgImage = null;
this.player1Image = null;
this.player2Image = null;
this.cellWidth = 40;
this.cellHeight = 40;
this.keyId = null;
this.started = false;
}
initializeGame() {
for (const player of this.players) {
this.currentPositions[player] = 1;
}
this.currentPlayerIndex = 0;
this.started = true;
}
rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
async movePlayer(player, steps) {
if (this.players.length === 0) return;
const currentPosition = this.currentPositions[player];
let newPosition = currentPosition + steps;
for (const otherPlayer of this.players) {
if (otherPlayer !== player && this.currentPositions[otherPlayer] === newPosition) {
const message = `😱 *Oh tidak!* @${player.split('@')[0]} *diinjak oleh* @${otherPlayer.split('@')[0]}.* Kembali ke awal cell.*`;
await m.reply(message, null, {
mentions: [player, otherPlayer]
});
newPosition = 1;
}
}
const snakeOrLadder = this.snakesAndLadders.find(s => s.start === newPosition);
if (snakeOrLadder) newPosition = snakeOrLadder.end;
newPosition = Math.min(newPosition, this.boardSize);
this.currentPositions[player] = newPosition;
}
async fetchImage(url) {
try {
const response = await axios.get(url, {
responseType: 'arraybuffer'
});
return await Jimp.read(Buffer.from(response.data, 'binary'));
} catch (error) {
console.error(`Error fetching image from ${url}:`, error);
throw error;
}
}
async getBoardBuffer() {
const board = new Jimp(420, 420);
this.bgImage.resize(420, 420);
board.composite(this.bgImage, 0, 0);
for (const player of this.players) {
const playerPosition = this.currentPositions[player];
const playerImage = player === this.players[0] ? this.player1Image : this.player2Image;
const playerX = ((playerPosition - 1) % 10) * this.cellWidth + 10;
const playerY = (9 - Math.floor((playerPosition - 1) / 10)) * this.cellHeight + 10;
board.composite(playerImage.clone().resize(this.cellWidth, this.cellHeight), playerX, playerY);
}
return board.getBufferAsync(Jimp.MIME_PNG);
}
async startGame(m, player1Name, player2Name) {
await m.reply(`🐍🎲 *Selamat datang di Permainan Ular Tangga!* 🎲🐍 \n\n@${player1Name.split('@')[0]} vs @${player2Name.split('@')[0]}`, null, {
mentions: [player1Name, player2Name]
});
this.players = [player1Name, player2Name];
this.initializeGame();
if (!this.bgImage) this.bgImage = await this.fetchImage(this.bgImageUrl);
if (!this.player1Image) this.player1Image = await this.fetchImage(this.player1ImageUrl);
if (!this.player2Image) this.player2Image = await this.fetchImage(this.player2ImageUrl);
const boardBuffer = await this.getBoardBuffer();
const {
key
} = await m.reply(boardBuffer);
this.keyId = key;
}
async playTurn(m, player) {
if (!this.players.length) {
await m.reply('🛑 *Tidak ada permainan aktif.* Gunakan "!snake start" untuk memulai permainan baru.');
return;
}
if (player !== this.players[this.currentPlayerIndex]) {
await m.reply(`🕒 *Bukan giliranmu.* \n\nSekarang giliran @${this.players[this.currentPlayerIndex].split('@')[0]}`, null, {
mentions: [this.players[this.currentPlayerIndex]]
});
return;
}
const diceRoll = this.rollDice();
await m.reply(`🎲 @${player.split('@')[0]} *melempar dadu.*\n\n - Dadu: *${diceRoll}*\n - Dari kotak: *${this.currentPositions[player]}*\n - Ke kotak: *${this.currentPositions[player] + diceRoll}*`, null, {
mentions: [player]
});
if (diceRoll !== 6) {
this.movePlayer(player, diceRoll);
const snakeOrLadder = this.snakesAndLadders.find(s => s.start === this.currentPositions[player]);
if (snakeOrLadder) {
const action = snakeOrLadder.end < snakeOrLadder.start ? 'Mundur' : 'Maju';
await m.reply(`🐍 @${player.split('@')[0]} menemukan ${action === 'Mundur' ? 'ular' : 'tangga'}! ${action} *ke kotak ${snakeOrLadder.end}.*`, null, {
mentions: [player]
});
this.currentPositions[player] = snakeOrLadder.end;
}
}
if (diceRoll !== 6) {
this.switchPlayer();
} else {
await m.reply('🎲 Anda mendapat 6, jadi giliran Anda masih berlanjut.');
this.movePlayer(player, diceRoll);
}
if (this.currentPositions[player] === this.boardSize) {
await m.reply(`🎉 @${player.split('@')[0]} menang! Selamat!`, null, {
mentions: [player]
});
this.resetSession();
}
const boardBuffer = await this.getBoardBuffer();
const sendMsg = this.sendMsg;
await sendMsg.sendMessage(m.chat, {
delete: this.keyId
});
const {
key
} = await m.reply(boardBuffer);
this.keyId = key;
return;
}
addPlayer(player) {
if (this.players.length < 2 && !this.players.includes(player) && player !== '') {
this.players.push(player);
return true;
} else {
return false;
}
}
switchPlayer() {
this.currentPlayerIndex = 1 - this.currentPlayerIndex;
}
resetSession() {
this.players = [];
this.currentPositions = {};
this.currentPlayerIndex = 0;
this.started = false;
}
isGameStarted() {
return this.started;
}
}
const handler = async (m, {
args,
usedPrefix,
command
}) => {
conn.ulartangga = conn.ulartangga || {};
const sessions = conn.ulartangga_ = conn.ulartangga_ || {};
const sessionId = m.chat;
const session = sessions[sessionId] || (sessions[sessionId] = new GameSession(sessionId, conn));
const game = session.game;
const {
state
} = conn.ulartangga[m.chat] || {
state: false
};
switch (args[0]) {
case 'join':
if (state) return m.reply('🛑 *Permainan sudah dimulai.* Tidak dapat bergabung.');
const playerName = m.sender;
const joinSuccess = game.addPlayer(playerName);
joinSuccess ? m.reply(`👋 @${playerName.split('@')[0]} *bergabung ke dalam permainan.*`, null, {
mentions: [playerName]
}) : m.reply('*Anda sudah bergabung atau permainan sudah penuh.* Tidak dapat bergabung.');
break;
case 'start':
if (state) return m.reply('🛑 *Permainan sudah dimulai.* Tidak dapat memulai ulang.');
conn.ulartangga[m.chat] = {
...conn.ulartangga[m.chat],
state: true
};
if (game.players.length === 2) {
await game.startGame(m, game.players[0], game.players[1]);
} else {
await m.reply('👥 *Tidak cukup pemain untuk memulai permainan.* Diperlukan minimal 2 pemain.');
}
break;
case 'roll':
if (!state) return m.reply('🛑 *Permainan belum dimulai.* Ketik "!snake start" untuk memulai.');
if (game.isGameStarted()) {
const currentPlayer = game.players[game.currentPlayerIndex];
if (m.sender !== currentPlayer) {
await m.reply(`🕒 *Bukan giliranmu.* \n\nSekarang giliran @${currentPlayer.split('@')[0]}`, null, {
mentions: [currentPlayer]
});
} else {
await game.playTurn(m, currentPlayer);
}
} else {
await m.reply('🛑 *Permainan belum dimulai.* Ketik "!snake start" untuk memulai.');
}
break;
case 'reset':
conn.ulartangga[m.chat] = {
...conn.ulartangga[m.chat],
state: false
};
session.game.resetSession();
delete sessions[sessionId];
await m.reply('🔄 *Sesi permainan direset.*');
break;
case 'help':
await m.reply(`🎲🐍 *Permainan Ular Tangga* 🐍🎲\n\n*Commands:*\n- ${usedPrefix + command} join : Bergabung ke dalam permainan.\n- ${usedPrefix + command} start : Memulai permainan.\n- ${usedPrefix + command} roll : Melempar dadu untuk bergerak.\n- ${usedPrefix + command} reset : Mereset sesi permainan.`);
break;
default:
m.reply(`❓ *Perintah tidak valid.* Gunakan ${usedPrefix + command} help untuk melihat daftar perintah.`);
}
};
handler.help = ['ulartangga'];
handler.tags = ['rpg'];
handler.command = /^(ular(tangga)?|ladders|snak(e)?)$/i;
export default handler; | 0 | 0.757792 | 1 | 0.757792 | game-dev | MEDIA | 0.407744 | game-dev | 0.970695 | 1 | 0.970695 |
Hibiya615/Splatoon_Presets | 16,604 | Raid - 大型任务/Savage - 零式/7.0 Arcadion - 阿卡狄亚登天斗技场/M4S_电牢笼 Splatoon脚本 南雲鉄虎翻译改良.cs | using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Dalamud.Game.ClientState.Objects.Enums;
using Dalamud.Game.ClientState.Objects.SubKinds;
using Dalamud.Game.ClientState.Objects.Types;
using ECommons;
using ECommons.Configuration;
using ECommons.DalamudServices;
using ECommons.GameHelpers;
using ECommons.Hooks.ActionEffectTypes;
using ECommons.ImGuiMethods;
using ECommons.Logging;
using ECommons.MathHelpers;
using ECommons.SimpleGui;
using ImGuiNET;
using NightmareUI.PrimaryUI;
using Splatoon.Memory;
using Splatoon.SplatoonScripting;
using Splatoon.Utility;
namespace SplatoonScriptsOfficial.Duties.Dawntrail;
public class R4S_电牢笼指路_Electrope_Edge : SplatoonScript
{
public enum SidewiseSparkPosition : byte
// 侧方电火花 分摊位置,分为中间脚下、侧面远离、南北四种情况
{
None = 0,
North = 1,
Inside = 2,
South = 3,
Side = 4
}
private readonly uint LeftSidewiseSparkCastActionId = 38381;
private readonly uint RightSidewiseSparkCastActionId = 38380;
private bool IsPairSidewiseSpark = false;
public override HashSet<uint>? ValidTerritories { get; } = [1232];
public override Metadata? Metadata => new(9, "NightmareXIV,南雲鉄虎翻译改良");
List<uint> Hits = [];
List<uint> Longs = [];
uint Debuff = 3999;
IBattleNpc? WickedThunder => Svc.Objects.OfType<IBattleNpc>().FirstOrDefault(x => x.NameId == 13057 && x.IsTargetable);
IBattleNpc? RelativeTile => Svc.Objects.OfType<IBattleNpc>().FirstOrDefault(x => x.DataId == 9020 && x.CastActionId == 38351 && x.IsCasting && x.BaseCastTime - x.CurrentCastTime > 0 && Vector3.Distance(new(100,0,100), x.Position).InRange(15.5f, 17f));
public override void OnSetup()
{
for(int i = 0; i < 8; i++)
{
Controller.RegisterElementFromCode($"Count{i}", "{\"Name\":\"\",\"type\":1,\"Enabled\":false,\"radius\":0.0,\"Filled\":false,\"fillIntensity\":0.5,\"originFillColor\":1677721855,\"endFillColor\":1677721855,\"overlayBGColor\":2768240640,\"overlayTextColor\":4294967295,\"overlayVOffset\":1.4,\"overlayFScale\":1.4,\"overlayPlaceholders\":true,\"thicc\":0.0,\"overlayText\":\"长\\\\n 3\",\"refActorComparisonType\":2,\"refActorTetherTimeMin\":0.0,\"refActorTetherTimeMax\":0.0,\"refActorTetherConnectedWithPlayer\":[]}");
}
Controller.RegisterElementFromCode("Explode", "{\"Name\":\"\",\"refX\":84.21978,\"refY\":100.50559,\"refZ\":0.0010004044,\"radius\":2.0,\"color\":4278255360,\"Filled\":false,\"fillIntensity\":0.2,\"originFillColor\":1677721855,\"endFillColor\":1677721855,\"thicc\":4.0,\"overlayText\":\"放置地点\",\"tether\":true,\"refActorTetherTimeMin\":0.0,\"refActorTetherTimeMax\":0.0,\"refActorTetherConnectedWithPlayer\":[]}");
Controller.RegisterElementFromCode("Safe", "{\"Name\":\"\",\"refX\":84.07532,\"refY\":99.538475,\"refZ\":0.0010004044,\"radius\":2.0,\"color\":4278255360,\"Filled\":false,\"fillIntensity\":0.2,\"originFillColor\":1677721855,\"endFillColor\":1677721855,\"thicc\":4.0,\"tether\":true,\"refActorTetherTimeMin\":0.0,\"refActorTetherTimeMax\":0.0,\"refActorTetherConnectedWithPlayer\":[]}");
}
public override void OnScriptUpdated(uint previousVersion)
{
if(previousVersion < 6)
{
new PopupWindow(() =>
{
ImGuiEx.Text($"""
Warning: Splatoon Script
{this.InternalData.Name}
was updated.
If you were using Sidewise Spark related functions,
you must reconfigure the script.
""");
});
}
}
public override void OnUpdate()
{
Controller.GetRegisteredElements().Each(x => x.Value.Enabled = false);
var longs = Svc.Objects.OfType<IPlayerCharacter>().Where(x => x.StatusList.Any(s => s.StatusId == Debuff && s.RemainingTime > 40)).ToList();
if(longs.Count == 4)
{
Longs = longs.Select(x => x.EntityId).ToList();
}
if(Svc.Objects.OfType<IPlayerCharacter>().Count(x => x.StatusList.Any(s => s.StatusId == Debuff)) < 4)
{
Reset();
}
// 必须留下命中来定义侧方电火花的运行稳定。
// 删除所有计数 Hits.RemoveAll(x => !(x.GetObject() is IPlayerCharacter pc && pc.StatusList.Any(z => z.StatusId == Debuff)));
int i = 0;
foreach(var x in Svc.Objects.OfType<IPlayerCharacter>())
{
bool tooFew = false;
var num = Hits.Count(s => s == x.EntityId);
string tooFewString = "";
if(num > 0 && Controller.TryGetElementByName($"Count{i}", out var e))
{
e.Enabled = true;
var l = Longs.Contains(x.EntityId);
if(l)
{
if(num == 1) tooFew = true;
}
else
{
if(num == 2) tooFew = true;
}
if(tooFew)
{
tooFewString = Controller.GetConfig<Config>().stringFew;
}
else
{
tooFewString = Controller.GetConfig<Config>().stringMuch;
}
e.overlayText = l ? "长" : "短";
e.overlayText += $"\n {num + (Controller.GetConfig<Config>().AddOne && l?1:0)} {(Controller.GetConfig<Config>().showMuchFew? tooFewString:"")}";
e.overlayTextColor = (x.StatusList.FirstOrDefault(x => x.StatusId == Debuff)?.RemainingTime < 16f?EColor.RedBright:EColor.White).ToUint();
e.overlayFScale = x.Address == Player.Object.Address ? 1.4f : 1f;
e.refActorObjectID = x.EntityId;
}
i++;
}
var tile = RelativeTile;
if(tile != null && C.ResolveBox)
{
var rotation = 0;
if(Vector3.Distance(new(84, 0, 100), tile.Position) < 2f) rotation = 90;
if(Vector3.Distance(new(100, 0, 84), tile.Position) < 2f) rotation = 180;
if(Vector3.Distance(new(116, 0, 100), tile.Position) < 2f) rotation = 270;
var doingMechanic = Player.Object.StatusList.FirstOrDefault(x => x.StatusId == Debuff)?.RemainingTime < 15f;
var num = Hits.Count(s => s == Player.Object.EntityId)+ (Longs.Contains(Player.Object.EntityId) ? 1 : 0);
var pos = num == 2 ? C.Position2 : C.Position3;
var posmod = new Vector2((pos.Item2 - 2) * 8, pos.Item1 * 8);
if(!doingMechanic)
{
posmod = new Vector2(0, 0);
}
var basePos = new Vector2(100, 84);
var posRaw = posmod + basePos;
var newPoint = Utils.RotatePoint(100,100, rotation.DegreesToRadians(), new(posRaw.X, posRaw.Y, 0));
//插件日志信息 PluginLog.Information($"Modifier: {posmod}, num: {num}, raw: {posRaw}, new: {newPoint}, rotation: {rotation}, tile: {tile.Position}");
if(Controller.TryGetElementByName(doingMechanic?"Explode":"Safe", out var e))
{
e.Enabled = true;
e.radius = 2f;
e.refX = newPoint.X;
e.refY = newPoint.Y;
}
}
var wickedThunder = WickedThunder;
if (C.ResolveBox && wickedThunder is { IsCasting: true } && IsPairSidewiseSpark &&
wickedThunder.CastActionId.EqualsAny(LeftSidewiseSparkCastActionId, RightSidewiseSparkCastActionId))
{
var isSafeRight = wickedThunder.CastActionId == LeftSidewiseSparkCastActionId;
var isLong = Longs.Contains(Player.Object.EntityId);
var hitCount = Hits.Count(s => s == Player.Object.EntityId);
var safeArea = (isLong, hitCount) switch
{
(false, 2) => GetSidewiseSparkSafeArea(C.SidewiseSpark2Short, isSafeRight),
(false, 3) => GetSidewiseSparkSafeArea(C.SidewiseSpark3Short, isSafeRight),
(true, 1) => GetSidewiseSparkSafeArea(C.SidewiseSpark1Long, isSafeRight),
(true, 2) => GetSidewiseSparkSafeArea(C.SidewiseSpark2Long, isSafeRight),
_ => null
};
if (Controller.TryGetElementByName("Safe", out var e))
{
if (safeArea == null) return;
e.Enabled = true;
e.radius = 1.5f;
e.refX = safeArea.Value.X;
e.refY = safeArea.Value.Y;
}
}
}
public override void OnVFXSpawn(uint target, string vfxPath)
{
if(vfxPath == "vfx/common/eff/m0888_stlp01_c0t1.avfx" && Hits.Count != 0)
{
IsPairSidewiseSpark = true;
}
}
Config C => Controller.GetConfig<Config>();
(int, int)[] Unsafe = [(0,0), (0,1), (0,3), (0,4),
(1,2),
(2,2),
(3,0),(3,2),(3,4),
(4,1),(4,2),(4,3),
];
Dictionary<SidewiseSparkPosition, string> AltRemaps = new()
{
[SidewiseSparkPosition.North] = "1 (North all the way)",
[SidewiseSparkPosition.South] = "2 (North and side)",
[SidewiseSparkPosition.Side] = "4 (South all the way)",
[SidewiseSparkPosition.Inside] = "3 (South and side)",
};
public override void OnSettingsDraw()
{
ImGui.SetNextItemWidth(150f);
ImGui.Checkbox("在长debuff受到伤害后将层数+1", ref C.AddOne);
ImGuiEx.HelpMarker("如果你是长debuff,在分散分摊后将在显示上为其计数+1。它不会影响脚本的实际功能");
ImGui.Checkbox("额外显示 多/少", ref C.showMuchFew);
ImGuiEx.HelpMarker("如果启用此选项,除了短和长之外,还会显示debuff数量的“多”和“少”。此选项主要用于日式打法,因此如果您不知道它的意义,请不要启用");
if(C.showMuchFew)
{
ImGui.Indent();
ImGui.TextWrapped("在显示的文本后面增加 \"多\" 或 \"少\":");
ImGui.SetNextItemWidth(150f);
ImGui.InputText("多", ref C.stringMuch, 100);
ImGui.SetNextItemWidth(150f);
ImGui.InputText("少", ref C.stringFew, 100);
ImGui.Unindent();
}
ImGui.Checkbox("放置雷debuff的正确区域选项", ref C.ResolveBox);
ImGuiEx.HelpMarker("如果选择此选项,当轮到你放置雷debuff时,这些点位将突出显示并指路");
if(C.ResolveBox)
{
new NuiBuilder().
Section("蓄雷装置 - 2 短 / 1 长(Game8攻略为例,TH组勾选右上,DPS组勾选左上):")
.Widget(() =>
{
ImGui.PushID("Pos2");
DrawBox(ref C.Position2);
ImGui.PopID();
})
.Section("蓄雷装置 - 3 短 / 2 长(Game8攻略为例,TH组勾选右下,DPS组勾选左下):")
.Widget(() =>
{
ImGui.PushID("Pos3");
DrawBox(ref C.Position3);
ImGui.PopID();
})
.Section("侧方电火花")
.Widget(() =>
{
ImGui.Text("分摊位置形状");
ImGuiEx.HelpMarker("默认情况下(当使用的是大众解法时,如美服Hector、日服Game8或OQ5),此机制的分摊形状为十字,或一半的“+”符号,多的DPS组站在BOSS目标圈内,少的DPS组站在BOSS的目标圈下方分摊;一些更小众的解法 (例如Rainesama)使用半圆形, 其形状类似于 \"(\"");
ImGuiEx.RadioButtonBool("半圆", "十字", ref C.SidewiseSparkAlt);
var names = C.SidewiseSparkAlt ? AltRemaps : null;
ImGui.Separator();
ImGui.Text("【重要】分摊位置选项");
ImGui.Text("2 短");
ImGui.SameLine();
ImGuiEx.EnumCombo("##SidewiseSpark2Short", ref C.SidewiseSpark2Short, names);
ImGui.Text("3 短");
ImGui.SameLine();
ImGuiEx.EnumCombo("##SidewiseSpark3Short", ref C.SidewiseSpark3Short, names);
ImGui.Text("1 长");
ImGui.SameLine();
ImGuiEx.EnumCombo("##SidewiseSpark1Long", ref C.SidewiseSpark1Long, names);
ImGui.Text("2 长");
ImGui.SameLine();
ImGuiEx.EnumCombo("##SidewiseSpark2Long", ref C.SidewiseSpark2Long, names);
}
)
.Draw();
}
if(ImGui.CollapsingHeader("Debug"))
{
foreach(var x in Svc.Objects.OfType<IPlayerCharacter>())
{
ImGuiEx.Text($"{x.Name}: {Hits.Count(s => s == x.EntityId)}, isLong = {Longs.Contains(x.EntityId)}");
}
if(ImGui.Button("Self long")) Longs.Add(Player.Object.EntityId);
if(ImGui.Button("Self short")) Longs.RemoveAll(x => x == Player.Object.EntityId);
if(ImGui.Button("Self: 3 hits"))
{
Hits.RemoveAll(x => x == Player.Object.EntityId);
Hits.Add(Player.Object.EntityId);
Hits.Add(Player.Object.EntityId);
Hits.Add(Player.Object.EntityId);
}
if(ImGui.Button("Self: 2 hits"))
{
Hits.RemoveAll(x => x == Player.Object.EntityId);
Hits.Add(Player.Object.EntityId);
Hits.Add(Player.Object.EntityId);
}
if(ImGui.Button("Self: 1 hits"))
{
Hits.RemoveAll(x => x == Player.Object.EntityId);
Hits.Add(Player.Object.EntityId);
}
}
}
void DrawBox(ref (int, int) value)
{
for(int i = 0; i < 5; i++)
{
for(int k = 0; k < 5; k++)
{
var dis = Unsafe.Contains((i, k));
if(dis)
{
ImGui.BeginDisabled();
var n = (bool?)null;
ImGuiEx.Checkbox("##null", ref n);
ImGui.EndDisabled();
}
else
{
var c = value == (i, k);
if(ImGui.Checkbox($"##{i}{k}", ref c))
{
if(c) value = (i, k);
}
}
ImGui.SameLine();
}
ImGui.NewLine();
}
}
void Reset()
{
Hits.Clear();
IsPairSidewiseSpark = false;
}
public override void OnActionEffectEvent(ActionEffectSet set)
{
if(set.Action?.RowId == 38790)
{
for(int i = 0; i < set.TargetEffects.Length; i++)
{
var obj = ((uint)set.TargetEffects[i].TargetID).GetObject();
if(obj?.ObjectKind == ObjectKind.Player)
{
PluginLog.Information($"Registered hit on {obj}");
Hits.Add(obj.EntityId);
break;
}
}
}
}
public Vector2? GetSidewiseSparkSafeArea(SidewiseSparkPosition pos, bool isSafeRight = false)
{
var center = new Vector2(100, 100);
if(C.SidewiseSparkAlt)
{
var mod = isSafeRight ? new Vector2(-1f,1f) : new Vector2(1f);
if(pos == SidewiseSparkPosition.North) return center + new Vector2(-1, -8) * mod;
if(pos == SidewiseSparkPosition.Inside) return center + new Vector2(-7, 4) * mod;
if(pos == SidewiseSparkPosition.South) return center + new Vector2(-7, -4) * mod;
if(pos == SidewiseSparkPosition.Side) return center + new Vector2(-1, 8) * mod;
return null;
}
else
{
var offsetX = isSafeRight ? 1.5f : -1.5f;
return pos switch
{
SidewiseSparkPosition.North => center + new Vector2(offsetX, -10),
SidewiseSparkPosition.Inside => center + new Vector2(offsetX, 0),
SidewiseSparkPosition.South => center + new Vector2(offsetX, 10),
SidewiseSparkPosition.Side => center + new Vector2(offsetX * 7f, 0),
_ => null
};
}
}
public class Config : IEzConfig
{
public bool AddOne = false;
public bool showMuchFew = false;
public string stringMuch = "多";
public string stringFew = "少";
public bool ResolveBox = false;
public (int, int) Position2 = (1, 4);
public (int, int) Position3 = (4, 4);
public SidewiseSparkPosition SidewiseSpark2Short = SidewiseSparkPosition.None;
public SidewiseSparkPosition SidewiseSpark1Long = SidewiseSparkPosition.None;
public SidewiseSparkPosition SidewiseSpark3Short = SidewiseSparkPosition.None;
public SidewiseSparkPosition SidewiseSpark2Long = SidewiseSparkPosition.None;
public bool SidewiseSparkAlt = false;
}
}
| 0 | 0.93546 | 1 | 0.93546 | game-dev | MEDIA | 0.822831 | game-dev | 0.979586 | 1 | 0.979586 |
gamingdotme/opensource-casino-v10 | 42,645 | casino/app/Games/ParadiseCQ9/SlotSettings.php | <?php
namespace VanguardLTE\Games\ParadiseCQ9
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $lastEvent = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
private $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
public $shop_id = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->username = $user->username;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->Denominations = \VanguardLTE\Game::$values['denomination'];
$this->CurrentDenom = $this->Denominations[0];
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable['Fish_1'] = [0];
$this->Paytable['Fish_103'] = [0];
$this->Paytable['Fish_0'] = [0];
$this->Paytable['Fish_1'] = [2];
$this->Paytable['Fish_2'] = [2];
$this->Paytable['Fish_3'] = [3];
$this->Paytable['Fish_4'] = [4];
$this->Paytable['Fish_5'] = [5];
$this->Paytable['Fish_6'] = [6];
$this->Paytable['Fish_7'] = [7];
$this->Paytable['Fish_8'] = [20];
$this->Paytable['Fish_9'] = [8];
$this->Paytable['Fish_10'] = [30];
$this->Paytable['Fish_11'] = [10];
$this->Paytable['Fish_12'] = [12];
$this->Paytable['Fish_13'] = [15];
$this->Paytable['Fish_14'] = [18];
$this->Paytable['Fish_15'] = [25];
$this->Paytable['Fish_16'] = [40];
$this->Paytable['Fish_17'] = [50];
$this->Paytable['Fish_18'] = [80];
$this->Paytable['Fish_1901'] = [50];
$this->Paytable['Fish_1902'] = [80];
$this->Paytable['Fish_1903'] = [100];
$this->Paytable['Fish_1904'] = [150];
$this->Paytable['Fish_1905'] = [200];
$this->Paytable['Fish_1906'] = [300];
$this->Paytable['Fish_1907'] = [500];
$this->Paytable['Fish_2001'] = [200];
$this->Paytable['Fish_2002'] = [250];
$this->Paytable['Fish_2003'] = [300];
$this->Paytable['Fish_2004'] = [350];
$this->Paytable['Fish_2005'] = [500];
$this->Paytable['Fish_2006'] = [888];
$this->Paytable['Fish_21'] = [5];
$this->FishDamage = [];
$this->FishDamage['Fish_0'] = [0];
$this->FishDamage['Fish_1'] = [6];
$this->FishDamage['Fish_2'] = [6];
$this->FishDamage['Fish_3'] = [10];
$this->FishDamage['Fish_4'] = [10];
$this->FishDamage['Fish_5'] = [10];
$this->FishDamage['Fish_6'] = [16];
$this->FishDamage['Fish_7'] = [16];
$this->FishDamage['Fish_8'] = [30];
$this->FishDamage['Fish_9'] = [20];
$this->FishDamage['Fish_10'] = [60];
$this->FishDamage['Fish_11'] = [30];
$this->FishDamage['Fish_12'] = [30];
$this->FishDamage['Fish_13'] = [30];
$this->FishDamage['Fish_14'] = [50];
$this->FishDamage['Fish_15'] = [60];
$this->FishDamage['Fish_16'] = [100];
$this->FishDamage['Fish_17'] = [100];
$this->FishDamage['Fish_18'] = [100];
$this->FishDamage['Fish_1901'] = [100];
$this->FishDamage['Fish_1902'] = [200];
$this->FishDamage['Fish_1903'] = [100];
$this->FishDamage['Fish_1904'] = [140];
$this->FishDamage['Fish_1905'] = [140];
$this->FishDamage['Fish_1906'] = [140];
$this->FishDamage['Fish_1907'] = [200];
$this->FishDamage['Fish_2001'] = [200];
$this->FishDamage['Fish_2002'] = [200];
$this->FishDamage['Fish_2003'] = [200];
$this->FishDamage['Fish_2004'] = [300];
$this->FishDamage['Fish_2005'] = [300];
$this->FishDamage['Fish_2006'] = [200];
$this->FishDamage['Fish_21'] = [6];
$this->FishDamage['Fish_103'] = [10000];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
425,
142,
3
],
[
669,
142,
3
],
[
913,
142,
3
],
[
1157,
142,
3
],
[
1401,
142,
3
]
];
$this->slotBonusType = 1;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = false;
$this->slotGamble = false;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 1;
$this->GambleType = 1;
$this->slotFreeCount = 1;
$this->slotFreeMpl = 1;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->slotJackPercent = [];
$this->slotJackpot = [];
for( $jp = 0; $jp < 4; $jp++ )
{
if( $this->jpgs[$jp]->balance != '' )
{
$this->slotJackpot[$jp] = sprintf('%01.4f', $this->jpgs[$jp]->balance);
$this->slotJackpot[$jp] = substr($this->slotJackpot[$jp], 0, strlen($this->slotJackpot[$jp]) - 2);
$this->slotJackPercent[] = $this->jpgs[$jp]->percent;
}
}
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->gameLine = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->Bet = explode(',', $game->bet);
$this->Bet = array_slice($this->Bet, 0, 5);
$this->Balance = $user->balance;
$this->SymbolGame = [
'0',
'1',
2,
3,
4,
5,
6,
7,
8
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
if( $log->str == 'NONE' )
{
return 'NULL';
}
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' && $tmpLog->responseEvent != 'jackpot' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function ClearJackpot($jid)
{
$this->jpgs[$jid]->balance = sprintf('%01.4f', 0);
$this->jpgs[$jid]->save();
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$jsum = [];
$payJack = 0;
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( $count_balance == 0 || $this->jpgPercentZero )
{
$jsum[$i] = $this->jpgs[$i]->balance;
}
else if( $count_balance < $bet )
{
$jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
else
{
$jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 )
{
if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id )
{
}
else
{
$payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom;
$jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum();
$this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom);
if( $this->jpgs[$i]->get_pay_sum() > 0 )
{
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => 0,
'win' => $this->jpgs[$i]->get_pay_sum(),
'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id,
'in_game' => 0,
'in_jpg' => 0,
'in_profit' => 0,
'shop_id' => $this->shop_id,
'date_time' => \Carbon\Carbon::now()
]);
}
}
}
$this->jpgs[$i]->balance = $jsum[$i];
$this->jpgs[$i]->save();
if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') )
{
$summ = $this->jpgs[$i]->get_start_balance();
if( $summ > 0 )
{
$this->jpgs[$i]->add_jpg('add', $summ);
}
}
}
if( $payJack > 0 )
{
$payJack = sprintf('%01.2f', $payJack);
$this->Jackpots['jackPay'] = $payJack;
}
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'bet' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($bet, $lines)
{
$pref = '';
$garantType = 'bet';
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == '7' )
{
if( isset($rp[$i + 1]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i - 1]) && isset($rp[$i - 2]) )
{
array_push($rpResult, $i - 1);
}
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i + 1);
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetReelStrips($winType, $slotEvent)
{
$game = $this->game;
if( $slotEvent == 'freespin' )
{
$reel = new GameReel();
$fArr = $reel->reelsStripBonus;
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
$curReel = array_shift($fArr);
if( count($curReel) )
{
$this->$reelStrip = $curReel;
}
}
}
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip);
$reelsId[] = $index + 1;
}
}
$scattersCnt = rand(3, count($reelsId));
shuffle($reelsId);
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i < $scattersCnt )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$cnt = count($key);
$key[-1] = $key[$cnt - 1];
$key[$cnt] = $key[0];
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = '';
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 0 | 0.575008 | 1 | 0.575008 | game-dev | MEDIA | 0.487084 | game-dev | 0.688552 | 1 | 0.688552 |
Project-GagSpeak/client | 2,065 | ProjectGagSpeak/GameInternals/Addons/AddonHotbar.cs | using FFXIVClientStructs.FFXIV.Client.UI;
using FFXIVClientStructs.FFXIV.Component.GUI;
// Attributions & References:
// --------------------------
// - Control Hotbar Lock Visibility.
// https://github.com/Caraxi/SimpleTweaksPlugin/blob/15a3ac835ece1f54e41af24d133aba9fef476e30/Tweaks/Chat/HideChat.cs#L73
namespace GagSpeak.GameInternals.Addons;
public unsafe static class AddonHotbar
{
private static AddonActionBarBase* _hotbar => (HcTaskUtils.TryGetAddonByName<AtkUnitBase>("_ActionBar", out var a) && HcTaskUtils.IsAddonReady(a))
? (AddonActionBarBase*)a : (AddonActionBarBase*)null;
private static AtkUnitBase* _hotbarBase => (AtkUnitBase*)_hotbar;
// Exposed Properties.
public static bool IsHotbarLocked
{
get
{
if (_hotbar is null)
return false;
// see if the node is locked or not.
return _hotbar->IsLocked;
}
}
// Exposed Methods
public static void LockHotbar()
{
if (!IsHotbarLocked) AtkHelper.GenerateCallback(_hotbarBase, 9, 3, 51u, 0u, true);
}
public static void LockAndHide()
{
if (_hotbarBase is null)
return;
LockHotbar();
var lockNode = _hotbarBase->GetNodeById(21);
if (lockNode is null)
return;
var componentNode = lockNode->GetAsAtkComponentNode();
if (componentNode is null)
return;
componentNode->AtkResNode.ToggleVisibility(false);
}
public static void UnlockHotbar()
{
if (IsHotbarLocked) AtkHelper.GenerateCallback(_hotbarBase, 9, 3, 51u, 0u, false);
}
public static void UnlockAndShow()
{
if (_hotbarBase is null)
return;
UnlockHotbar();
var lockNode = _hotbarBase->GetNodeById(21);
if (lockNode is null)
return;
var componentNode = lockNode->GetAsAtkComponentNode();
if (componentNode is null)
return;
componentNode->AtkResNode.ToggleVisibility(true);
}
}
| 0 | 0.782101 | 1 | 0.782101 | game-dev | MEDIA | 0.870567 | game-dev | 0.637339 | 1 | 0.637339 |
Fewnity/Xenity-Engine | 12,411 | Xenity_Engine/include/bullet/BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#if defined (_WIN32) || defined (__i386__)
#define BT_USE_SSE_IN_API
#endif
#include "BulletCollision/CollisionShapes/btPolyhedralConvexShape.h"
#include "btConvexPolyhedron.h"
#include "LinearMath/btConvexHullComputer.h"
#include <new>
#include "LinearMath/btGeometryUtil.h"
#include "LinearMath/btGrahamScan2dConvexHull.h"
btPolyhedralConvexShape::btPolyhedralConvexShape() :btConvexInternalShape(),
m_polyhedron(0)
{
}
btPolyhedralConvexShape::~btPolyhedralConvexShape()
{
if (m_polyhedron)
{
m_polyhedron->~btConvexPolyhedron();
btAlignedFree(m_polyhedron);
}
}
bool btPolyhedralConvexShape::initializePolyhedralFeatures(int shiftVerticesByMargin)
{
if (m_polyhedron)
{
m_polyhedron->~btConvexPolyhedron();
btAlignedFree(m_polyhedron);
}
void* mem = btAlignedAlloc(sizeof(btConvexPolyhedron),16);
m_polyhedron = new (mem) btConvexPolyhedron;
btAlignedObjectArray<btVector3> orgVertices;
for (int i=0;i<getNumVertices();i++)
{
btVector3& newVertex = orgVertices.expand();
getVertex(i,newVertex);
}
btConvexHullComputer conv;
if (shiftVerticesByMargin)
{
btAlignedObjectArray<btVector3> planeEquations;
btGeometryUtil::getPlaneEquationsFromVertices(orgVertices,planeEquations);
btAlignedObjectArray<btVector3> shiftedPlaneEquations;
for (int p=0;p<planeEquations.size();p++)
{
btVector3 plane = planeEquations[p];
// btScalar margin = getMargin();
plane[3] -= getMargin();
shiftedPlaneEquations.push_back(plane);
}
btAlignedObjectArray<btVector3> tmpVertices;
btGeometryUtil::getVerticesFromPlaneEquations(shiftedPlaneEquations,tmpVertices);
conv.compute(&tmpVertices[0].getX(), sizeof(btVector3),tmpVertices.size(),0.f,0.f);
} else
{
conv.compute(&orgVertices[0].getX(), sizeof(btVector3),orgVertices.size(),0.f,0.f);
}
btAlignedObjectArray<btVector3> faceNormals;
int numFaces = conv.faces.size();
faceNormals.resize(numFaces);
btConvexHullComputer* convexUtil = &conv;
btAlignedObjectArray<btFace> tmpFaces;
tmpFaces.resize(numFaces);
int numVertices = convexUtil->vertices.size();
m_polyhedron->m_vertices.resize(numVertices);
for (int p=0;p<numVertices;p++)
{
m_polyhedron->m_vertices[p] = convexUtil->vertices[p];
}
for (int i=0;i<numFaces;i++)
{
int face = convexUtil->faces[i];
//printf("face=%d\n",face);
const btConvexHullComputer::Edge* firstEdge = &convexUtil->edges[face];
const btConvexHullComputer::Edge* edge = firstEdge;
btVector3 edges[3];
int numEdges = 0;
//compute face normals
do
{
int src = edge->getSourceVertex();
tmpFaces[i].m_indices.push_back(src);
int targ = edge->getTargetVertex();
btVector3 wa = convexUtil->vertices[src];
btVector3 wb = convexUtil->vertices[targ];
btVector3 newEdge = wb-wa;
newEdge.normalize();
if (numEdges<2)
edges[numEdges++] = newEdge;
edge = edge->getNextEdgeOfFace();
} while (edge!=firstEdge);
btScalar planeEq = 1e30f;
if (numEdges==2)
{
faceNormals[i] = edges[0].cross(edges[1]);
faceNormals[i].normalize();
tmpFaces[i].m_plane[0] = faceNormals[i].getX();
tmpFaces[i].m_plane[1] = faceNormals[i].getY();
tmpFaces[i].m_plane[2] = faceNormals[i].getZ();
tmpFaces[i].m_plane[3] = planeEq;
}
else
{
btAssert(0);//degenerate?
faceNormals[i].setZero();
}
for (int v=0;v<tmpFaces[i].m_indices.size();v++)
{
btScalar eq = m_polyhedron->m_vertices[tmpFaces[i].m_indices[v]].dot(faceNormals[i]);
if (planeEq>eq)
{
planeEq=eq;
}
}
tmpFaces[i].m_plane[3] = -planeEq;
}
//merge coplanar faces and copy them to m_polyhedron
btScalar faceWeldThreshold= 0.999f;
btAlignedObjectArray<int> todoFaces;
for (int i=0;i<tmpFaces.size();i++)
todoFaces.push_back(i);
while (todoFaces.size())
{
btAlignedObjectArray<int> coplanarFaceGroup;
int refFace = todoFaces[todoFaces.size()-1];
coplanarFaceGroup.push_back(refFace);
btFace& faceA = tmpFaces[refFace];
todoFaces.pop_back();
btVector3 faceNormalA(faceA.m_plane[0],faceA.m_plane[1],faceA.m_plane[2]);
for (int j=todoFaces.size()-1;j>=0;j--)
{
int i = todoFaces[j];
btFace& faceB = tmpFaces[i];
btVector3 faceNormalB(faceB.m_plane[0],faceB.m_plane[1],faceB.m_plane[2]);
if (faceNormalA.dot(faceNormalB)>faceWeldThreshold)
{
coplanarFaceGroup.push_back(i);
todoFaces.remove(i);
}
}
bool did_merge = false;
if (coplanarFaceGroup.size()>1)
{
//do the merge: use Graham Scan 2d convex hull
btAlignedObjectArray<GrahamVector3> orgpoints;
btVector3 averageFaceNormal(0,0,0);
for (int i=0;i<coplanarFaceGroup.size();i++)
{
// m_polyhedron->m_faces.push_back(tmpFaces[coplanarFaceGroup[i]]);
btFace& face = tmpFaces[coplanarFaceGroup[i]];
btVector3 faceNormal(face.m_plane[0],face.m_plane[1],face.m_plane[2]);
averageFaceNormal+=faceNormal;
for (int f=0;f<face.m_indices.size();f++)
{
int orgIndex = face.m_indices[f];
btVector3 pt = m_polyhedron->m_vertices[orgIndex];
bool found = false;
for (int i=0;i<orgpoints.size();i++)
{
//if ((orgpoints[i].m_orgIndex == orgIndex) || ((rotatedPt-orgpoints[i]).length2()<0.0001))
if (orgpoints[i].m_orgIndex == orgIndex)
{
found=true;
break;
}
}
if (!found)
orgpoints.push_back(GrahamVector3(pt,orgIndex));
}
}
btFace combinedFace;
for (int i=0;i<4;i++)
combinedFace.m_plane[i] = tmpFaces[coplanarFaceGroup[0]].m_plane[i];
btAlignedObjectArray<GrahamVector3> hull;
averageFaceNormal.normalize();
GrahamScanConvexHull2D(orgpoints,hull,averageFaceNormal);
for (int i=0;i<hull.size();i++)
{
combinedFace.m_indices.push_back(hull[i].m_orgIndex);
for(int k = 0; k < orgpoints.size(); k++)
{
if(orgpoints[k].m_orgIndex == hull[i].m_orgIndex)
{
orgpoints[k].m_orgIndex = -1; // invalidate...
break;
}
}
}
// are there rejected vertices?
bool reject_merge = false;
for(int i = 0; i < orgpoints.size(); i++) {
if(orgpoints[i].m_orgIndex == -1)
continue; // this is in the hull...
// this vertex is rejected -- is anybody else using this vertex?
for(int j = 0; j < tmpFaces.size(); j++) {
btFace& face = tmpFaces[j];
// is this a face of the current coplanar group?
bool is_in_current_group = false;
for(int k = 0; k < coplanarFaceGroup.size(); k++) {
if(coplanarFaceGroup[k] == j) {
is_in_current_group = true;
break;
}
}
if(is_in_current_group) // ignore this face...
continue;
// does this face use this rejected vertex?
for(int v = 0; v < face.m_indices.size(); v++) {
if(face.m_indices[v] == orgpoints[i].m_orgIndex) {
// this rejected vertex is used in another face -- reject merge
reject_merge = true;
break;
}
}
if(reject_merge)
break;
}
if(reject_merge)
break;
}
if (!reject_merge)
{
// do this merge!
did_merge = true;
m_polyhedron->m_faces.push_back(combinedFace);
}
}
if(!did_merge)
{
for (int i=0;i<coplanarFaceGroup.size();i++)
{
btFace face = tmpFaces[coplanarFaceGroup[i]];
m_polyhedron->m_faces.push_back(face);
}
}
}
m_polyhedron->initialize();
return true;
}
#ifndef MIN
#define MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b))
#endif
btVector3 btPolyhedralConvexShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
btVector3 supVec(0,0,0);
#ifndef __SPU__
int i;
btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
btVector3 vec = vec0;
btScalar lenSqr = vec.length2();
if (lenSqr < btScalar(0.0001))
{
vec.setValue(1,0,0);
} else
{
btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
vec *= rlen;
}
btVector3 vtx;
btScalar newDot;
for( int k = 0; k < getNumVertices(); k += 128 )
{
btVector3 temp[128];
int inner_count = MIN(getNumVertices() - k, 128);
for( i = 0; i < inner_count; i++ )
getVertex(i,temp[i]);
i = (int) vec.maxDot( temp, inner_count, newDot);
if (newDot > maxDot)
{
maxDot = newDot;
supVec = temp[i];
}
}
#endif //__SPU__
return supVec;
}
void btPolyhedralConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
#ifndef __SPU__
int i;
btVector3 vtx;
btScalar newDot;
for (i=0;i<numVectors;i++)
{
supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT);
}
for (int j=0;j<numVectors;j++)
{
const btVector3& vec = vectors[j];
for( int k = 0; k < getNumVertices(); k += 128 )
{
btVector3 temp[128];
int inner_count = MIN(getNumVertices() - k, 128);
for( i = 0; i < inner_count; i++ )
getVertex(i,temp[i]);
i = (int) vec.maxDot( temp, inner_count, newDot);
if (newDot > supportVerticesOut[j][3])
{
supportVerticesOut[j] = temp[i];
supportVerticesOut[j][3] = newDot;
}
}
}
#endif //__SPU__
}
void btPolyhedralConvexShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
#ifndef __SPU__
//not yet, return box inertia
btScalar margin = getMargin();
btTransform ident;
ident.setIdentity();
btVector3 aabbMin,aabbMax;
getAabb(ident,aabbMin,aabbMax);
btVector3 halfExtents = (aabbMax-aabbMin)*btScalar(0.5);
btScalar lx=btScalar(2.)*(halfExtents.x()+margin);
btScalar ly=btScalar(2.)*(halfExtents.y()+margin);
btScalar lz=btScalar(2.)*(halfExtents.z()+margin);
const btScalar x2 = lx*lx;
const btScalar y2 = ly*ly;
const btScalar z2 = lz*lz;
const btScalar scaledmass = mass * btScalar(0.08333333);
inertia = scaledmass * (btVector3(y2+z2,x2+z2,x2+y2));
#endif //__SPU__
}
void btPolyhedralConvexAabbCachingShape::setLocalScaling(const btVector3& scaling)
{
btConvexInternalShape::setLocalScaling(scaling);
recalcLocalAabb();
}
btPolyhedralConvexAabbCachingShape::btPolyhedralConvexAabbCachingShape()
:btPolyhedralConvexShape(),
m_localAabbMin(1,1,1),
m_localAabbMax(-1,-1,-1),
m_isLocalAabbValid(false)
{
}
void btPolyhedralConvexAabbCachingShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const
{
getNonvirtualAabb(trans,aabbMin,aabbMax,getMargin());
}
void btPolyhedralConvexAabbCachingShape::recalcLocalAabb()
{
m_isLocalAabbValid = true;
#if 1
static const btVector3 _directions[] =
{
btVector3( 1., 0., 0.),
btVector3( 0., 1., 0.),
btVector3( 0., 0., 1.),
btVector3( -1., 0., 0.),
btVector3( 0., -1., 0.),
btVector3( 0., 0., -1.)
};
btVector3 _supporting[] =
{
btVector3( 0., 0., 0.),
btVector3( 0., 0., 0.),
btVector3( 0., 0., 0.),
btVector3( 0., 0., 0.),
btVector3( 0., 0., 0.),
btVector3( 0., 0., 0.)
};
batchedUnitVectorGetSupportingVertexWithoutMargin(_directions, _supporting, 6);
for ( int i = 0; i < 3; ++i )
{
m_localAabbMax[i] = _supporting[i][i] + m_collisionMargin;
m_localAabbMin[i] = _supporting[i + 3][i] - m_collisionMargin;
}
#else
for (int i=0;i<3;i++)
{
btVector3 vec(btScalar(0.),btScalar(0.),btScalar(0.));
vec[i] = btScalar(1.);
btVector3 tmp = localGetSupportingVertex(vec);
m_localAabbMax[i] = tmp[i];
vec[i] = btScalar(-1.);
tmp = localGetSupportingVertex(vec);
m_localAabbMin[i] = tmp[i];
}
#endif
}
| 0 | 0.909613 | 1 | 0.909613 | game-dev | MEDIA | 0.641179 | game-dev | 0.988196 | 1 | 0.988196 |
Dark-Basic-Software-Limited/AGKRepo | 28,209 | AGK/AgkIde/bullet/LinearMath/btQuaternion.h | /*
Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SIMD__QUATERNION_H_
#define BT_SIMD__QUATERNION_H_
#include "btVector3.h"
#include "btQuadWord.h"
#ifdef BT_USE_SSE
//const __m128 ATTRIBUTE_ALIGNED16(vOnes) = {1.0f, 1.0f, 1.0f, 1.0f};
#define vOnes (_mm_set_ps(1.0f, 1.0f, 1.0f, 1.0f))
#endif
#if defined(BT_USE_SSE)
#define vQInv (_mm_set_ps(+0.0f, -0.0f, -0.0f, -0.0f))
#define vPPPM (_mm_set_ps(-0.0f, +0.0f, +0.0f, +0.0f))
#elif defined(BT_USE_NEON)
const btSimdFloat4 ATTRIBUTE_ALIGNED16(vQInv) = {-0.0f, -0.0f, -0.0f, +0.0f};
const btSimdFloat4 ATTRIBUTE_ALIGNED16(vPPPM) = {+0.0f, +0.0f, +0.0f, -0.0f};
#endif
/**@brief The btQuaternion implements quaternion to perform linear algebra rotations in combination with btMatrix3x3, btVector3 and btTransform. */
class btQuaternion : public btQuadWord {
public:
/**@brief No initialization constructor */
btQuaternion() {}
#if (defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE))|| defined(BT_USE_NEON)
// Set Vector
SIMD_FORCE_INLINE btQuaternion(const btSimdFloat4 vec)
{
mVec128 = vec;
}
// Copy constructor
SIMD_FORCE_INLINE btQuaternion(const btQuaternion& rhs)
{
mVec128 = rhs.mVec128;
}
// Assignment Operator
SIMD_FORCE_INLINE btQuaternion&
operator=(const btQuaternion& v)
{
mVec128 = v.mVec128;
return *this;
}
#endif
// template <typename btScalar>
// explicit Quaternion(const btScalar *v) : Tuple4<btScalar>(v) {}
/**@brief Constructor from scalars */
btQuaternion(const btScalar& _x, const btScalar& _y, const btScalar& _z, const btScalar& _w)
: btQuadWord(_x, _y, _z, _w)
{}
/**@brief Axis angle Constructor
* @param axis The axis which the rotation is around
* @param angle The magnitude of the rotation around the angle (Radians) */
btQuaternion(const btVector3& _axis, const btScalar& _angle)
{
setRotation(_axis, _angle);
}
/**@brief Constructor from Euler angles
* @param yaw Angle around Y unless BT_EULER_DEFAULT_ZYX defined then Z
* @param pitch Angle around X unless BT_EULER_DEFAULT_ZYX defined then Y
* @param roll Angle around Z unless BT_EULER_DEFAULT_ZYX defined then X */
btQuaternion(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
{
#ifndef BT_EULER_DEFAULT_ZYX
setEuler(yaw, pitch, roll);
#else
setEulerZYX(yaw, pitch, roll);
#endif
}
/**@brief Set the rotation using axis angle notation
* @param axis The axis around which to rotate
* @param angle The magnitude of the rotation in Radians */
void setRotation(const btVector3& axis, const btScalar& _angle)
{
btScalar d = axis.length();
btAssert(d != btScalar(0.0));
btScalar s = btSin(_angle * btScalar(0.5)) / d;
setValue(axis.x() * s, axis.y() * s, axis.z() * s,
btCos(_angle * btScalar(0.5)));
}
/**@brief Set the quaternion using Euler angles
* @param yaw Angle around Y
* @param pitch Angle around X
* @param roll Angle around Z */
void setEuler(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
{
btScalar halfYaw = btScalar(yaw) * btScalar(0.5);
btScalar halfPitch = btScalar(pitch) * btScalar(0.5);
btScalar halfRoll = btScalar(roll) * btScalar(0.5);
btScalar cosYaw = btCos(halfYaw);
btScalar sinYaw = btSin(halfYaw);
btScalar cosPitch = btCos(halfPitch);
btScalar sinPitch = btSin(halfPitch);
btScalar cosRoll = btCos(halfRoll);
btScalar sinRoll = btSin(halfRoll);
setValue(cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw,
cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw,
sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw,
cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw);
}
/**@brief Set the quaternion using euler angles
* @param yaw Angle around Z
* @param pitch Angle around Y
* @param roll Angle around X */
void setEulerZYX(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
{
btScalar halfYaw = btScalar(yaw) * btScalar(0.5);
btScalar halfPitch = btScalar(pitch) * btScalar(0.5);
btScalar halfRoll = btScalar(roll) * btScalar(0.5);
btScalar cosYaw = btCos(halfYaw);
btScalar sinYaw = btSin(halfYaw);
btScalar cosPitch = btCos(halfPitch);
btScalar sinPitch = btSin(halfPitch);
btScalar cosRoll = btCos(halfRoll);
btScalar sinRoll = btSin(halfRoll);
setValue(sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw, //x
cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, //y
cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw, //z
cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw); //formerly yzx
}
/**@brief Add two quaternions
* @param q The quaternion to add to this one */
SIMD_FORCE_INLINE btQuaternion& operator+=(const btQuaternion& q)
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
mVec128 = _mm_add_ps(mVec128, q.mVec128);
#elif defined(BT_USE_NEON)
mVec128 = vaddq_f32(mVec128, q.mVec128);
#else
m_floats[0] += q.x();
m_floats[1] += q.y();
m_floats[2] += q.z();
m_floats[3] += q.m_floats[3];
#endif
return *this;
}
/**@brief Subtract out a quaternion
* @param q The quaternion to subtract from this one */
btQuaternion& operator-=(const btQuaternion& q)
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
mVec128 = _mm_sub_ps(mVec128, q.mVec128);
#elif defined(BT_USE_NEON)
mVec128 = vsubq_f32(mVec128, q.mVec128);
#else
m_floats[0] -= q.x();
m_floats[1] -= q.y();
m_floats[2] -= q.z();
m_floats[3] -= q.m_floats[3];
#endif
return *this;
}
/**@brief Scale this quaternion
* @param s The scalar to scale by */
btQuaternion& operator*=(const btScalar& s)
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vs = _mm_load_ss(&s); // (S 0 0 0)
vs = bt_pshufd_ps(vs, 0); // (S S S S)
mVec128 = _mm_mul_ps(mVec128, vs);
#elif defined(BT_USE_NEON)
mVec128 = vmulq_n_f32(mVec128, s);
#else
m_floats[0] *= s;
m_floats[1] *= s;
m_floats[2] *= s;
m_floats[3] *= s;
#endif
return *this;
}
/**@brief Multiply this quaternion by q on the right
* @param q The other quaternion
* Equivilant to this = this * q */
btQuaternion& operator*=(const btQuaternion& q)
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vQ2 = q.get128();
__m128 A1 = bt_pshufd_ps(mVec128, BT_SHUFFLE(0,1,2,0));
__m128 B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(3,3,3,0));
A1 = A1 * B1;
__m128 A2 = bt_pshufd_ps(mVec128, BT_SHUFFLE(1,2,0,1));
__m128 B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2,0,1,1));
A2 = A2 * B2;
B1 = bt_pshufd_ps(mVec128, BT_SHUFFLE(2,0,1,2));
B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1,2,0,2));
B1 = B1 * B2; // A3 *= B3
mVec128 = bt_splat_ps(mVec128, 3); // A0
mVec128 = mVec128 * vQ2; // A0 * B0
A1 = A1 + A2; // AB12
mVec128 = mVec128 - B1; // AB03 = AB0 - AB3
A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element
mVec128 = mVec128+ A1; // AB03 + AB12
#elif defined(BT_USE_NEON)
float32x4_t vQ1 = mVec128;
float32x4_t vQ2 = q.get128();
float32x4_t A0, A1, B1, A2, B2, A3, B3;
float32x2_t vQ1zx, vQ2wx, vQ1yz, vQ2zx, vQ2yz, vQ2xz;
{
float32x2x2_t tmp;
tmp = vtrn_f32( vget_high_f32(vQ1), vget_low_f32(vQ1) ); // {z x}, {w y}
vQ1zx = tmp.val[0];
tmp = vtrn_f32( vget_high_f32(vQ2), vget_low_f32(vQ2) ); // {z x}, {w y}
vQ2zx = tmp.val[0];
}
vQ2wx = vext_f32(vget_high_f32(vQ2), vget_low_f32(vQ2), 1);
vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1);
vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1);
vQ2xz = vext_f32(vQ2zx, vQ2zx, 1);
A1 = vcombine_f32(vget_low_f32(vQ1), vQ1zx); // X Y z x
B1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ2), 1), vQ2wx); // W W W X
A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1));
B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1));
A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z
B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z
A1 = vmulq_f32(A1, B1);
A2 = vmulq_f32(A2, B2);
A3 = vmulq_f32(A3, B3); // A3 *= B3
A0 = vmulq_lane_f32(vQ2, vget_high_f32(vQ1), 1); // A0 * B0
A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2
A0 = vsubq_f32(A0, A3); // AB03 = AB0 - AB3
// change the sign of the last element
A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM);
A0 = vaddq_f32(A0, A1); // AB03 + AB12
mVec128 = A0;
#else
setValue(
m_floats[3] * q.x() + m_floats[0] * q.m_floats[3] + m_floats[1] * q.z() - m_floats[2] * q.y(),
m_floats[3] * q.y() + m_floats[1] * q.m_floats[3] + m_floats[2] * q.x() - m_floats[0] * q.z(),
m_floats[3] * q.z() + m_floats[2] * q.m_floats[3] + m_floats[0] * q.y() - m_floats[1] * q.x(),
m_floats[3] * q.m_floats[3] - m_floats[0] * q.x() - m_floats[1] * q.y() - m_floats[2] * q.z());
#endif
return *this;
}
/**@brief Return the dot product between this quaternion and another
* @param q The other quaternion */
btScalar dot(const btQuaternion& q) const
{
#if defined BT_USE_SIMD_VECTOR3 && defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vd;
vd = _mm_mul_ps(mVec128, q.mVec128);
__m128 t = _mm_movehl_ps(vd, vd);
vd = _mm_add_ps(vd, t);
t = _mm_shuffle_ps(vd, vd, 0x55);
vd = _mm_add_ss(vd, t);
return _mm_cvtss_f32(vd);
#elif defined(BT_USE_NEON)
float32x4_t vd = vmulq_f32(mVec128, q.mVec128);
float32x2_t x = vpadd_f32(vget_low_f32(vd), vget_high_f32(vd));
x = vpadd_f32(x, x);
return vget_lane_f32(x, 0);
#else
return m_floats[0] * q.x() +
m_floats[1] * q.y() +
m_floats[2] * q.z() +
m_floats[3] * q.m_floats[3];
#endif
}
/**@brief Return the length squared of the quaternion */
btScalar length2() const
{
return dot(*this);
}
/**@brief Return the length of the quaternion */
btScalar length() const
{
return btSqrt(length2());
}
/**@brief Normalize the quaternion
* Such that x^2 + y^2 + z^2 +w^2 = 1 */
btQuaternion& normalize()
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vd;
vd = _mm_mul_ps(mVec128, mVec128);
__m128 t = _mm_movehl_ps(vd, vd);
vd = _mm_add_ps(vd, t);
t = _mm_shuffle_ps(vd, vd, 0x55);
vd = _mm_add_ss(vd, t);
vd = _mm_sqrt_ss(vd);
vd = _mm_div_ss(vOnes, vd);
vd = bt_pshufd_ps(vd, 0); // splat
mVec128 = _mm_mul_ps(mVec128, vd);
return *this;
#else
return *this /= length();
#endif
}
/**@brief Return a scaled version of this quaternion
* @param s The scale factor */
SIMD_FORCE_INLINE btQuaternion
operator*(const btScalar& s) const
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vs = _mm_load_ss(&s); // (S 0 0 0)
vs = bt_pshufd_ps(vs, 0x00); // (S S S S)
return btQuaternion(_mm_mul_ps(mVec128, vs));
#elif defined(BT_USE_NEON)
return btQuaternion(vmulq_n_f32(mVec128, s));
#else
return btQuaternion(x() * s, y() * s, z() * s, m_floats[3] * s);
#endif
}
/**@brief Return an inversely scaled versionof this quaternion
* @param s The inverse scale factor */
btQuaternion operator/(const btScalar& s) const
{
btAssert(s != btScalar(0.0));
return *this * (btScalar(1.0) / s);
}
/**@brief Inversely scale this quaternion
* @param s The scale factor */
btQuaternion& operator/=(const btScalar& s)
{
btAssert(s != btScalar(0.0));
return *this *= btScalar(1.0) / s;
}
/**@brief Return a normalized version of this quaternion */
btQuaternion normalized() const
{
return *this / length();
}
/**@brief Return the ***half*** angle between this quaternion and the other
* @param q The other quaternion */
btScalar angle(const btQuaternion& q) const
{
btScalar s = btSqrt(length2() * q.length2());
btAssert(s != btScalar(0.0));
return btAcos(dot(q) / s);
}
/**@brief Return the angle between this quaternion and the other along the shortest path
* @param q The other quaternion */
btScalar angleShortestPath(const btQuaternion& q) const
{
btScalar s = btSqrt(length2() * q.length2());
btAssert(s != btScalar(0.0));
if (dot(q) < 0) // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp
return btAcos(dot(-q) / s) * btScalar(2.0);
else
return btAcos(dot(q) / s) * btScalar(2.0);
}
/**@brief Return the angle of rotation represented by this quaternion */
btScalar getAngle() const
{
btScalar s = btScalar(2.) * btAcos(m_floats[3]);
return s;
}
/**@brief Return the angle of rotation represented by this quaternion along the shortest path*/
btScalar getAngleShortestPath() const
{
btScalar s;
if (dot(*this) < 0)
s = btScalar(2.) * btAcos(m_floats[3]);
else
s = btScalar(2.) * btAcos(-m_floats[3]);
return s;
}
/**@brief Return the axis of the rotation represented by this quaternion */
btVector3 getAxis() const
{
btScalar s_squared = 1.f-m_floats[3]*m_floats[3];
if (s_squared < btScalar(10.) * SIMD_EPSILON) //Check for divide by zero
return btVector3(1.0, 0.0, 0.0); // Arbitrary
btScalar s = 1.f/btSqrt(s_squared);
return btVector3(m_floats[0] * s, m_floats[1] * s, m_floats[2] * s);
}
/**@brief Return the inverse of this quaternion */
btQuaternion inverse() const
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
return btQuaternion(_mm_xor_ps(mVec128, vQInv));
#elif defined(BT_USE_NEON)
return btQuaternion((btSimdFloat4)veorq_s32((int32x4_t)mVec128, (int32x4_t)vQInv));
#else
return btQuaternion(-m_floats[0], -m_floats[1], -m_floats[2], m_floats[3]);
#endif
}
/**@brief Return the sum of this quaternion and the other
* @param q2 The other quaternion */
SIMD_FORCE_INLINE btQuaternion
operator+(const btQuaternion& q2) const
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
return btQuaternion(_mm_add_ps(mVec128, q2.mVec128));
#elif defined(BT_USE_NEON)
return btQuaternion(vaddq_f32(mVec128, q2.mVec128));
#else
const btQuaternion& q1 = *this;
return btQuaternion(q1.x() + q2.x(), q1.y() + q2.y(), q1.z() + q2.z(), q1.m_floats[3] + q2.m_floats[3]);
#endif
}
/**@brief Return the difference between this quaternion and the other
* @param q2 The other quaternion */
SIMD_FORCE_INLINE btQuaternion
operator-(const btQuaternion& q2) const
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
return btQuaternion(_mm_sub_ps(mVec128, q2.mVec128));
#elif defined(BT_USE_NEON)
return btQuaternion(vsubq_f32(mVec128, q2.mVec128));
#else
const btQuaternion& q1 = *this;
return btQuaternion(q1.x() - q2.x(), q1.y() - q2.y(), q1.z() - q2.z(), q1.m_floats[3] - q2.m_floats[3]);
#endif
}
/**@brief Return the negative of this quaternion
* This simply negates each element */
SIMD_FORCE_INLINE btQuaternion operator-() const
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
return btQuaternion(_mm_xor_ps(mVec128, btvMzeroMask));
#elif defined(BT_USE_NEON)
return btQuaternion((btSimdFloat4)veorq_s32((int32x4_t)mVec128, (int32x4_t)btvMzeroMask) );
#else
const btQuaternion& q2 = *this;
return btQuaternion( - q2.x(), - q2.y(), - q2.z(), - q2.m_floats[3]);
#endif
}
/**@todo document this and it's use */
SIMD_FORCE_INLINE btQuaternion farthest( const btQuaternion& qd) const
{
btQuaternion diff,sum;
diff = *this - qd;
sum = *this + qd;
if( diff.dot(diff) > sum.dot(sum) )
return qd;
return (-qd);
}
/**@todo document this and it's use */
SIMD_FORCE_INLINE btQuaternion nearest( const btQuaternion& qd) const
{
btQuaternion diff,sum;
diff = *this - qd;
sum = *this + qd;
if( diff.dot(diff) < sum.dot(sum) )
return qd;
return (-qd);
}
/**@brief Return the quaternion which is the result of Spherical Linear Interpolation between this and the other quaternion
* @param q The other quaternion to interpolate with
* @param t The ratio between this and q to interpolate. If t = 0 the result is this, if t=1 the result is q.
* Slerp interpolates assuming constant velocity. */
btQuaternion slerp(const btQuaternion& q, const btScalar& t) const
{
btScalar magnitude = btSqrt(length2() * q.length2());
btAssert(magnitude > btScalar(0));
btScalar product = dot(q) / magnitude;
if (btFabs(product) < btScalar(1))
{
// Take care of long angle case see http://en.wikipedia.org/wiki/Slerp
const btScalar sign = (product < 0) ? btScalar(-1) : btScalar(1);
const btScalar theta = btAcos(sign * product);
const btScalar s1 = btSin(sign * t * theta);
const btScalar d = btScalar(1.0) / btSin(theta);
const btScalar s0 = btSin((btScalar(1.0) - t) * theta);
return btQuaternion(
(m_floats[0] * s0 + q.x() * s1) * d,
(m_floats[1] * s0 + q.y() * s1) * d,
(m_floats[2] * s0 + q.z() * s1) * d,
(m_floats[3] * s0 + q.m_floats[3] * s1) * d);
}
else
{
return *this;
}
}
static const btQuaternion& getIdentity()
{
static const btQuaternion identityQuat(btScalar(0.),btScalar(0.),btScalar(0.),btScalar(1.));
return identityQuat;
}
SIMD_FORCE_INLINE const btScalar& getW() const { return m_floats[3]; }
};
/**@brief Return the product of two quaternions */
SIMD_FORCE_INLINE btQuaternion
operator*(const btQuaternion& q1, const btQuaternion& q2)
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vQ1 = q1.get128();
__m128 vQ2 = q2.get128();
__m128 A0, A1, B1, A2, B2;
A1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(0,1,2,0)); // X Y z x // vtrn
B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(3,3,3,0)); // W W W X // vdup vext
A1 = A1 * B1;
A2 = bt_pshufd_ps(vQ1, BT_SHUFFLE(1,2,0,1)); // Y Z X Y // vext
B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2,0,1,1)); // z x Y Y // vtrn vdup
A2 = A2 * B2;
B1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(2,0,1,2)); // z x Y Z // vtrn vext
B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1,2,0,2)); // Y Z x z // vext vtrn
B1 = B1 * B2; // A3 *= B3
A0 = bt_splat_ps(vQ1, 3); // A0
A0 = A0 * vQ2; // A0 * B0
A1 = A1 + A2; // AB12
A0 = A0 - B1; // AB03 = AB0 - AB3
A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element
A0 = A0 + A1; // AB03 + AB12
return btQuaternion(A0);
#elif defined(BT_USE_NEON)
float32x4_t vQ1 = q1.get128();
float32x4_t vQ2 = q2.get128();
float32x4_t A0, A1, B1, A2, B2, A3, B3;
float32x2_t vQ1zx, vQ2wx, vQ1yz, vQ2zx, vQ2yz, vQ2xz;
{
float32x2x2_t tmp;
tmp = vtrn_f32( vget_high_f32(vQ1), vget_low_f32(vQ1) ); // {z x}, {w y}
vQ1zx = tmp.val[0];
tmp = vtrn_f32( vget_high_f32(vQ2), vget_low_f32(vQ2) ); // {z x}, {w y}
vQ2zx = tmp.val[0];
}
vQ2wx = vext_f32(vget_high_f32(vQ2), vget_low_f32(vQ2), 1);
vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1);
vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1);
vQ2xz = vext_f32(vQ2zx, vQ2zx, 1);
A1 = vcombine_f32(vget_low_f32(vQ1), vQ1zx); // X Y z x
B1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ2), 1), vQ2wx); // W W W X
A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1));
B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1));
A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z
B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z
A1 = vmulq_f32(A1, B1);
A2 = vmulq_f32(A2, B2);
A3 = vmulq_f32(A3, B3); // A3 *= B3
A0 = vmulq_lane_f32(vQ2, vget_high_f32(vQ1), 1); // A0 * B0
A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2
A0 = vsubq_f32(A0, A3); // AB03 = AB0 - AB3
// change the sign of the last element
A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM);
A0 = vaddq_f32(A0, A1); // AB03 + AB12
return btQuaternion(A0);
#else
return btQuaternion(
q1.w() * q2.x() + q1.x() * q2.w() + q1.y() * q2.z() - q1.z() * q2.y(),
q1.w() * q2.y() + q1.y() * q2.w() + q1.z() * q2.x() - q1.x() * q2.z(),
q1.w() * q2.z() + q1.z() * q2.w() + q1.x() * q2.y() - q1.y() * q2.x(),
q1.w() * q2.w() - q1.x() * q2.x() - q1.y() * q2.y() - q1.z() * q2.z());
#endif
}
SIMD_FORCE_INLINE btQuaternion
operator*(const btQuaternion& q, const btVector3& w)
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vQ1 = q.get128();
__m128 vQ2 = w.get128();
__m128 A1, B1, A2, B2, A3, B3;
A1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(3,3,3,0));
B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(0,1,2,0));
A1 = A1 * B1;
A2 = bt_pshufd_ps(vQ1, BT_SHUFFLE(1,2,0,1));
B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2,0,1,1));
A2 = A2 * B2;
A3 = bt_pshufd_ps(vQ1, BT_SHUFFLE(2,0,1,2));
B3 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1,2,0,2));
A3 = A3 * B3; // A3 *= B3
A1 = A1 + A2; // AB12
A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element
A1 = A1 - A3; // AB123 = AB12 - AB3
return btQuaternion(A1);
#elif defined(BT_USE_NEON)
float32x4_t vQ1 = q.get128();
float32x4_t vQ2 = w.get128();
float32x4_t A1, B1, A2, B2, A3, B3;
float32x2_t vQ1wx, vQ2zx, vQ1yz, vQ2yz, vQ1zx, vQ2xz;
vQ1wx = vext_f32(vget_high_f32(vQ1), vget_low_f32(vQ1), 1);
{
float32x2x2_t tmp;
tmp = vtrn_f32( vget_high_f32(vQ2), vget_low_f32(vQ2) ); // {z x}, {w y}
vQ2zx = tmp.val[0];
tmp = vtrn_f32( vget_high_f32(vQ1), vget_low_f32(vQ1) ); // {z x}, {w y}
vQ1zx = tmp.val[0];
}
vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1);
vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1);
vQ2xz = vext_f32(vQ2zx, vQ2zx, 1);
A1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ1), 1), vQ1wx); // W W W X
B1 = vcombine_f32(vget_low_f32(vQ2), vQ2zx); // X Y z x
A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1));
B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1));
A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z
B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z
A1 = vmulq_f32(A1, B1);
A2 = vmulq_f32(A2, B2);
A3 = vmulq_f32(A3, B3); // A3 *= B3
A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2
// change the sign of the last element
A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM);
A1 = vsubq_f32(A1, A3); // AB123 = AB12 - AB3
return btQuaternion(A1);
#else
return btQuaternion(
q.w() * w.x() + q.y() * w.z() - q.z() * w.y(),
q.w() * w.y() + q.z() * w.x() - q.x() * w.z(),
q.w() * w.z() + q.x() * w.y() - q.y() * w.x(),
-q.x() * w.x() - q.y() * w.y() - q.z() * w.z());
#endif
}
SIMD_FORCE_INLINE btQuaternion
operator*(const btVector3& w, const btQuaternion& q)
{
#if defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
__m128 vQ1 = w.get128();
__m128 vQ2 = q.get128();
__m128 A1, B1, A2, B2, A3, B3;
A1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(0,1,2,0)); // X Y z x
B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(3,3,3,0)); // W W W X
A1 = A1 * B1;
A2 = bt_pshufd_ps(vQ1, BT_SHUFFLE(1,2,0,1));
B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2,0,1,1));
A2 = A2 *B2;
A3 = bt_pshufd_ps(vQ1, BT_SHUFFLE(2,0,1,2));
B3 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1,2,0,2));
A3 = A3 * B3; // A3 *= B3
A1 = A1 + A2; // AB12
A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element
A1 = A1 - A3; // AB123 = AB12 - AB3
return btQuaternion(A1);
#elif defined(BT_USE_NEON)
float32x4_t vQ1 = w.get128();
float32x4_t vQ2 = q.get128();
float32x4_t A1, B1, A2, B2, A3, B3;
float32x2_t vQ1zx, vQ2wx, vQ1yz, vQ2zx, vQ2yz, vQ2xz;
{
float32x2x2_t tmp;
tmp = vtrn_f32( vget_high_f32(vQ1), vget_low_f32(vQ1) ); // {z x}, {w y}
vQ1zx = tmp.val[0];
tmp = vtrn_f32( vget_high_f32(vQ2), vget_low_f32(vQ2) ); // {z x}, {w y}
vQ2zx = tmp.val[0];
}
vQ2wx = vext_f32(vget_high_f32(vQ2), vget_low_f32(vQ2), 1);
vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1);
vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1);
vQ2xz = vext_f32(vQ2zx, vQ2zx, 1);
A1 = vcombine_f32(vget_low_f32(vQ1), vQ1zx); // X Y z x
B1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ2), 1), vQ2wx); // W W W X
A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1));
B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1));
A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z
B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z
A1 = vmulq_f32(A1, B1);
A2 = vmulq_f32(A2, B2);
A3 = vmulq_f32(A3, B3); // A3 *= B3
A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2
// change the sign of the last element
A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM);
A1 = vsubq_f32(A1, A3); // AB123 = AB12 - AB3
return btQuaternion(A1);
#else
return btQuaternion(
+w.x() * q.w() + w.y() * q.z() - w.z() * q.y(),
+w.y() * q.w() + w.z() * q.x() - w.x() * q.z(),
+w.z() * q.w() + w.x() * q.y() - w.y() * q.x(),
-w.x() * q.x() - w.y() * q.y() - w.z() * q.z());
#endif
}
/**@brief Calculate the dot product between two quaternions */
SIMD_FORCE_INLINE btScalar
dot(const btQuaternion& q1, const btQuaternion& q2)
{
return q1.dot(q2);
}
/**@brief Return the length of a quaternion */
SIMD_FORCE_INLINE btScalar
length(const btQuaternion& q)
{
return q.length();
}
/**@brief Return the angle between two quaternions*/
SIMD_FORCE_INLINE btScalar
btAngle(const btQuaternion& q1, const btQuaternion& q2)
{
return q1.angle(q2);
}
/**@brief Return the inverse of a quaternion*/
SIMD_FORCE_INLINE btQuaternion
inverse(const btQuaternion& q)
{
return q.inverse();
}
/**@brief Return the result of spherical linear interpolation betwen two quaternions
* @param q1 The first quaternion
* @param q2 The second quaternion
* @param t The ration between q1 and q2. t = 0 return q1, t=1 returns q2
* Slerp assumes constant velocity between positions. */
SIMD_FORCE_INLINE btQuaternion
slerp(const btQuaternion& q1, const btQuaternion& q2, const btScalar& t)
{
return q1.slerp(q2, t);
}
SIMD_FORCE_INLINE btVector3
quatRotate(const btQuaternion& rotation, const btVector3& v)
{
btQuaternion q = rotation * v;
q *= rotation.inverse();
#if defined BT_USE_SIMD_VECTOR3 && defined (BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
return btVector3(_mm_and_ps(q.get128(), btvFFF0fMask));
#elif defined(BT_USE_NEON)
return btVector3((float32x4_t)vandq_s32((int32x4_t)q.get128(), btvFFF0Mask));
#else
return btVector3(q.getX(),q.getY(),q.getZ());
#endif
}
SIMD_FORCE_INLINE btQuaternion
shortestArcQuat(const btVector3& v0, const btVector3& v1) // Game Programming Gems 2.10. make sure v0,v1 are normalized
{
btVector3 c = v0.cross(v1);
btScalar d = v0.dot(v1);
if (d < -1.0 + SIMD_EPSILON)
{
btVector3 n,unused;
btPlaneSpace1(v0,n,unused);
return btQuaternion(n.x(),n.y(),n.z(),0.0f); // just pick any vector that is orthogonal to v0
}
btScalar s = btSqrt((1.0f + d) * 2.0f);
btScalar rs = 1.0f / s;
return btQuaternion(c.getX()*rs,c.getY()*rs,c.getZ()*rs,s * 0.5f);
}
SIMD_FORCE_INLINE btQuaternion
shortestArcQuatNormalize2(btVector3& v0,btVector3& v1)
{
v0.normalize();
v1.normalize();
return shortestArcQuat(v0,v1);
}
#endif //BT_SIMD__QUATERNION_H_
| 0 | 0.92242 | 1 | 0.92242 | game-dev | MEDIA | 0.753535 | game-dev,graphics-rendering | 0.969395 | 1 | 0.969395 |
Arkania/ArkCORE | 14,058 | src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp | /*
* Copyright (C) 2008 - 2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Zulfarrak
SD%Complete: 50
SDComment: Consider it temporary, no instance script made for this instance yet.
SDCategory: Zul'Farrak
EndScriptData */
/* ContentData
npc_sergeant_bly
npc_weegli_blastfuse
EndContentData */
#include "ScriptPCH.h"
#include "zulfarrak.h"
/*######
## npc_sergeant_bly
######*/
enum blyAndCrewFactions
{
FACTION_HOSTILE = 14,
FACTION_FRIENDLY = 35, //while in cages (so the trolls won't attack them while they're caged)
FACTION_FREED = 250 //after release (so they'll be hostile towards trolls)
};
enum blySays
{
SAY_1 = -1209002,
SAY_2 = -1209003
};
enum blySpells
{
SPELL_SHIELD_BASH = 11972,
SPELL_REVENGE = 12170
};
#define GOSSIP_BLY "[PH] In that case, I will take my reward!"
class npc_sergeant_bly : public CreatureScript
{
public:
npc_sergeant_bly() : CreatureScript("npc_sergeant_bly") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*uiSender*/, uint32 uiAction)
{
player->PlayerTalkClass->ClearMenus();
if (uiAction == GOSSIP_ACTION_INFO_DEF+1)
{
player->CLOSE_GOSSIP_MENU();
CAST_AI(npc_sergeant_bly::npc_sergeant_blyAI, creature->AI())->PlayerGUID = player->GetGUID();
creature->AI()->DoAction(0);
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature)
{
if (InstanceScript* instance = creature->GetInstanceScript())
{
if (instance->GetData(EVENT_PYRAMID) == PYRAMID_KILLED_ALL_TROLLS)
{
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BLY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->SEND_GOSSIP_MENU(1517, creature->GetGUID());
}
else
if (instance->GetData(EVENT_PYRAMID) == PYRAMID_NOT_STARTED)
player->SEND_GOSSIP_MENU(1515, creature->GetGUID());
else
player->SEND_GOSSIP_MENU(1516, creature->GetGUID());
return true;
}
return false;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_sergeant_blyAI (creature);
}
struct npc_sergeant_blyAI : public ScriptedAI
{
npc_sergeant_blyAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
postGossipStep = 0;
}
InstanceScript* instance;
uint32 postGossipStep;
uint32 Text_Timer;
uint32 ShieldBash_Timer;
uint32 Revenge_Timer; //this is wrong, spell should never be used unless me->getVictim() dodge, parry or block attack. Trinity support required.
uint64 PlayerGUID;
void Reset()
{
ShieldBash_Timer = 5000;
Revenge_Timer = 8000;
me->setFaction(FACTION_FRIENDLY);
}
void UpdateAI(const uint32 diff)
{
if (postGossipStep>0 && postGossipStep<4)
{
if (Text_Timer<diff)
{
switch (postGossipStep)
{
case 1:
//weegli doesn't fight - he goes & blows up the door
if (Creature* pWeegli = instance->instance->GetCreature(instance->GetData64(ENTRY_WEEGLI)))
pWeegli->AI()->DoAction(0);
DoScriptText(SAY_1, me);
Text_Timer = 5000;
break;
case 2:
DoScriptText(SAY_2, me);
Text_Timer = 5000;
break;
case 3:
me->setFaction(FACTION_HOSTILE);
if (Player* target = Player::GetPlayer(*me, PlayerGUID))
AttackStart(target);
if (instance)
{
switchFactionIfAlive(instance, ENTRY_RAVEN);
switchFactionIfAlive(instance, ENTRY_ORO);
switchFactionIfAlive(instance, ENTRY_MURTA);
}
}
postGossipStep++;
}
else Text_Timer -= diff;
}
if (!UpdateVictim())
return;
if (ShieldBash_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SHIELD_BASH);
ShieldBash_Timer = 15000;
}
else
ShieldBash_Timer -= diff;
if (Revenge_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_REVENGE);
Revenge_Timer = 10000;
}
else
Revenge_Timer -= diff;
DoMeleeAttackIfReady();
}
void DoAction(const int32 /*param*/)
{
postGossipStep=1;
Text_Timer = 0;
}
void switchFactionIfAlive(InstanceScript* instance, uint32 entry)
{
if (Creature* crew = instance->instance->GetCreature(instance->GetData64(entry)))
if (crew->isAlive())
crew->setFaction(FACTION_HOSTILE);
}
};
};
/*######
+## go_troll_cage
+######*/
void initBlyCrewMember(InstanceScript* instance, uint32 entry, float x, float y, float z)
{
if (Creature* crew = instance->instance->GetCreature(instance->GetData64(entry)))
{
crew->SetReactState(REACT_AGGRESSIVE);
crew->AddUnitMovementFlag(MOVEMENTFLAG_WALKING);
crew->SetHomePosition(x, y, z, 0);
crew->GetMotionMaster()->MovePoint(1, x, y, z);
crew->setFaction(FACTION_FREED);
}
}
class go_troll_cage : public GameObjectScript
{
public:
go_troll_cage() : GameObjectScript("go_troll_cage") { }
bool OnGossipHello(Player* /*player*/, GameObject* go)
{
if (InstanceScript* instance = go->GetInstanceScript())
{
instance->SetData(EVENT_PYRAMID, PYRAMID_CAGES_OPEN);
//set bly & co to aggressive & start moving to top of stairs
initBlyCrewMember(instance, ENTRY_BLY, 1884.99f, 1263, 41.52f);
initBlyCrewMember(instance, ENTRY_RAVEN, 1882.5f, 1263, 41.52f);
initBlyCrewMember(instance, ENTRY_ORO, 1886.47f, 1270.68f, 41.68f);
initBlyCrewMember(instance, ENTRY_WEEGLI, 1890, 1263, 41.52f);
initBlyCrewMember(instance, ENTRY_MURTA, 1891.19f, 1272.03f, 41.60f);
}
return false;
}
};
/*######
## npc_weegli_blastfuse
######*/
enum weegliSpells
{
SPELL_BOMB = 8858,
SPELL_GOBLIN_LAND_MINE = 21688,
SPELL_SHOOT = 6660,
SPELL_WEEGLIS_BARREL = 10772
};
enum weegliSays
{
SAY_WEEGLI_OHNO = -1209000,
SAY_WEEGLI_OK_I_GO = -1209001
};
#define GOSSIP_WEEGLI "[PH] Please blow up the door."
class npc_weegli_blastfuse : public CreatureScript
{
public:
npc_weegli_blastfuse() : CreatureScript("npc_weegli_blastfuse") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*uiSender*/, uint32 uiAction)
{
player->PlayerTalkClass->ClearMenus();
if (uiAction == GOSSIP_ACTION_INFO_DEF+1)
{
player->CLOSE_GOSSIP_MENU();
//here we make him run to door, set the charge and run away off to nowhere
creature->AI()->DoAction(0);
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature)
{
if (InstanceScript* instance = creature->GetInstanceScript())
{
switch (instance->GetData(EVENT_PYRAMID))
{
case PYRAMID_KILLED_ALL_TROLLS:
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_WEEGLI, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->SEND_GOSSIP_MENU(1514, creature->GetGUID()); //if event can proceed to end
break;
case PYRAMID_NOT_STARTED:
player->SEND_GOSSIP_MENU(1511, creature->GetGUID()); //if event not started
break;
default:
player->SEND_GOSSIP_MENU(1513, creature->GetGUID()); //if event are in progress
}
return true;
}
return false;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_weegli_blastfuseAI (creature);
}
struct npc_weegli_blastfuseAI : public ScriptedAI
{
npc_weegli_blastfuseAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
destroyingDoor=false;
Bomb_Timer = 10000;
LandMine_Timer = 30000;
}
uint32 Bomb_Timer;
uint32 LandMine_Timer;
bool destroyingDoor;
InstanceScript* instance;
void Reset()
{
/*if (instance)
instance->SetData(0, NOT_STARTED);*/
}
void AttackStart(Unit* victim)
{
AttackStartCaster(victim, 10);//keep back & toss bombs/shoot
}
void JustDied(Unit* /*victim*/)
{
/*if (instance)
instance->SetData(0, DONE);*/
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (Bomb_Timer < diff)
{
DoCast(me->getVictim(), SPELL_BOMB);
Bomb_Timer = 10000;
}
else
Bomb_Timer -= diff;
if (me->isAttackReady() && !me->IsWithinMeleeRange(me->getVictim()))
{
DoCast(me->getVictim(), SPELL_SHOOT);
me->SetSheath(SHEATH_STATE_RANGED);
}
else
{
me->SetSheath(SHEATH_STATE_MELEE);
DoMeleeAttackIfReady();
}
}
void MovementInform(uint32 /*type*/, uint32 /*id*/)
{
if (instance)
{
if (instance->GetData(EVENT_PYRAMID) == PYRAMID_CAGES_OPEN)
{
instance->SetData(EVENT_PYRAMID, PYRAMID_ARRIVED_AT_STAIR);
DoScriptText(SAY_WEEGLI_OHNO, me);
me->SetHomePosition(1882.69f, 1272.28f, 41.87f, 0);
}
else
if (destroyingDoor)
{
instance->DoUseDoorOrButton(instance->GetData64(GO_END_DOOR));
//TODO: leave the area...
me->DespawnOrUnsummon();
};
}
}
void DoAction(const int32 /*param*/)
{
DestroyDoor();
}
void DestroyDoor()
{
if (me->isAlive())
{
me->setFaction(FACTION_FRIENDLY);
me->GetMotionMaster()->MovePoint(0, 1858.57f, 1146.35f, 14.745f);
me->SetHomePosition(1858.57f, 1146.35f, 14.745f, 3.85f); // in case he gets interrupted
DoScriptText(SAY_WEEGLI_OK_I_GO, me);
destroyingDoor=true;
}
}
};
};
/*######
## go_shallow_grave
######*/
enum
{
ZOMBIE = 7286,
DEAD_HERO = 7276,
ZOMBIE_CHANCE = 65,
DEAD_HERO_CHANCE = 10
};
class go_shallow_grave : public GameObjectScript
{
public:
go_shallow_grave() : GameObjectScript("go_shallow_grave") { }
bool OnGossipHello(Player* /*player*/, GameObject* go)
{
// randomly summon a zombie or dead hero the first time a grave is used
if (go->GetUseCount() == 0)
{
uint32 randomchance = urand(0, 100);
if (randomchance < ZOMBIE_CHANCE)
go->SummonCreature(ZOMBIE, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 30000);
else
if ((randomchance-ZOMBIE_CHANCE) < DEAD_HERO_CHANCE)
go->SummonCreature(DEAD_HERO, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 30000);
}
go->AddUse();
return false;
}
};
/*######
## at_zumrah
######*/
enum zumrahConsts
{
ZUMRAH_ID = 7271,
ZUMRAH_HOSTILE_FACTION = 37
};
class at_zumrah : public AreaTriggerScript
{
public:
at_zumrah() : AreaTriggerScript("at_zumrah") { }
bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/)
{
Creature* pZumrah = player->FindNearestCreature(ZUMRAH_ID, 30.0f);
if (!pZumrah)
return false;
pZumrah->setFaction(ZUMRAH_HOSTILE_FACTION);
return true;
}
};
void AddSC_zulfarrak()
{
new npc_sergeant_bly();
new npc_weegli_blastfuse();
new go_shallow_grave();
new at_zumrah();
new go_troll_cage();
}
| 0 | 0.972121 | 1 | 0.972121 | game-dev | MEDIA | 0.98046 | game-dev | 0.957124 | 1 | 0.957124 |
elephantrobotics/agv_pro_ros2 | 2,101 | navigation2/nav2_behavior_tree/include/nav2_behavior_tree/plugins/action/back_up_action.hpp | // Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef NAV2_BEHAVIOR_TREE__PLUGINS__ACTION__BACK_UP_ACTION_HPP_
#define NAV2_BEHAVIOR_TREE__PLUGINS__ACTION__BACK_UP_ACTION_HPP_
#include <string>
#include "nav2_behavior_tree/bt_action_node.hpp"
#include "nav2_msgs/action/back_up.hpp"
namespace nav2_behavior_tree
{
/**
* @brief A nav2_behavior_tree::BtActionNode class that wraps nav2_msgs::action::BackUp
*/
class BackUpAction : public BtActionNode<nav2_msgs::action::BackUp>
{
public:
/**
* @brief A constructor for nav2_behavior_tree::BackUpAction
* @param xml_tag_name Name for the XML tag for this node
* @param action_name Action name this node creates a client for
* @param conf BT node configuration
*/
BackUpAction(
const std::string & xml_tag_name,
const std::string & action_name,
const BT::NodeConfiguration & conf);
/**
* @brief Function to perform some user-defined operation on tick
*/
void on_tick() override;
/**
* @brief Creates list of BT ports
* @return BT::PortsList Containing basic ports along with node-specific ports
*/
static BT::PortsList providedPorts()
{
return providedBasicPorts(
{
BT::InputPort<double>("backup_dist", 0.15, "Distance to backup"),
BT::InputPort<double>("backup_speed", 0.025, "Speed at which to backup"),
BT::InputPort<double>("time_allowance", 10.0, "Allowed time for reversing")
});
}
};
} // namespace nav2_behavior_tree
#endif // NAV2_BEHAVIOR_TREE__PLUGINS__ACTION__BACK_UP_ACTION_HPP_
| 0 | 0.953293 | 1 | 0.953293 | game-dev | MEDIA | 0.177426 | game-dev | 0.943779 | 1 | 0.943779 |
magefree/mage | 1,214 | Mage.Sets/src/mage/cards/a/ArmoredGalleon.java |
package mage.cards.a;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.combat.CantAttackUnlessDefenderControllsPermanent;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.common.FilterLandPermanent;
/**
*
* @author fireshoes
*/
public final class ArmoredGalleon extends CardImpl {
public ArmoredGalleon(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{U}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.PIRATE);
this.power = new MageInt(5);
this.toughness = new MageInt(4);
// Armored Galleon can't attack unless defending player controls an Island.
this.addAbility(new SimpleStaticAbility(new CantAttackUnlessDefenderControllsPermanent(new FilterLandPermanent(SubType.ISLAND,"an Island"))));
}
private ArmoredGalleon(final ArmoredGalleon card) {
super(card);
}
@Override
public ArmoredGalleon copy() {
return new ArmoredGalleon(this);
}
}
| 0 | 0.902771 | 1 | 0.902771 | game-dev | MEDIA | 0.983301 | game-dev | 0.786791 | 1 | 0.786791 |
netdata/netdata | 3,881 | src/daemon/pulse/pulse-string.c | // SPDX-License-Identifier: GPL-3.0-or-later
#define PULSE_INTERNALS 1
#include "pulse-string.h"
void pulse_string_do(bool extended) {
if(!extended) return;
static RRDSET *st_ops = NULL, *st_entries = NULL, *st_mem = NULL;
static RRDDIM *rd_ops_inserts = NULL, *rd_ops_deletes = NULL;
static RRDDIM *rd_entries_entries = NULL;
static RRDDIM *rd_mem = NULL;
static RRDDIM *rd_mem_idx = NULL;
#ifdef NETDATA_INTERNAL_CHECKS
static RRDDIM *rd_entries_refs = NULL, *rd_ops_releases = NULL, *rd_ops_duplications = NULL, *rd_ops_searches = NULL;
#endif
size_t inserts, deletes, searches, entries, references, memory, memory_index, duplications, releases;
string_statistics(&inserts, &deletes, &searches, &entries, &references, &memory, &memory_index, &duplications, &releases);
if (unlikely(!st_ops)) {
st_ops = rrdset_create_localhost(
"netdata"
, "strings_ops"
, NULL
, "strings"
, NULL
, "Strings operations"
, "ops/s"
, "netdata"
, "pulse"
, 910000
, localhost->rrd_update_every
, RRDSET_TYPE_LINE);
rd_ops_inserts = rrddim_add(st_ops, "inserts", NULL, 1, 1, RRD_ALGORITHM_INCREMENTAL);
rd_ops_deletes = rrddim_add(st_ops, "deletes", NULL, -1, 1, RRD_ALGORITHM_INCREMENTAL);
#ifdef NETDATA_INTERNAL_CHECKS
rd_ops_searches = rrddim_add(st_ops, "searches", NULL, 1, 1, RRD_ALGORITHM_INCREMENTAL);
rd_ops_duplications = rrddim_add(st_ops, "duplications", NULL, 1, 1, RRD_ALGORITHM_INCREMENTAL);
rd_ops_releases = rrddim_add(st_ops, "releases", NULL, -1, 1, RRD_ALGORITHM_INCREMENTAL);
#endif
}
rrddim_set_by_pointer(st_ops, rd_ops_inserts, (collected_number)inserts);
rrddim_set_by_pointer(st_ops, rd_ops_deletes, (collected_number)deletes);
#ifdef NETDATA_INTERNAL_CHECKS
rrddim_set_by_pointer(st_ops, rd_ops_searches, (collected_number)searches);
rrddim_set_by_pointer(st_ops, rd_ops_duplications, (collected_number)duplications);
rrddim_set_by_pointer(st_ops, rd_ops_releases, (collected_number)releases);
#endif
rrdset_done(st_ops);
if (unlikely(!st_entries)) {
st_entries = rrdset_create_localhost(
"netdata"
, "strings_entries"
, NULL
, "strings"
, NULL
, "Strings entries"
, "entries"
, "netdata"
, "pulse"
, 910001
, localhost->rrd_update_every
, RRDSET_TYPE_AREA);
rd_entries_entries = rrddim_add(st_entries, "entries", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
#ifdef NETDATA_INTERNAL_CHECKS
rd_entries_refs = rrddim_add(st_entries, "references", NULL, 1, -1, RRD_ALGORITHM_ABSOLUTE);
#endif
}
rrddim_set_by_pointer(st_entries, rd_entries_entries, (collected_number)entries);
#ifdef NETDATA_INTERNAL_CHECKS
rrddim_set_by_pointer(st_entries, rd_entries_refs, (collected_number)references);
#endif
rrdset_done(st_entries);
if (unlikely(!st_mem)) {
st_mem = rrdset_create_localhost(
"netdata"
, "strings_memory"
, NULL
, "strings"
, NULL
, "Strings memory"
, "bytes"
, "netdata"
, "pulse"
, 910001
, localhost->rrd_update_every
, RRDSET_TYPE_STACKED);
rd_mem = rrddim_add(st_mem, "memory", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
rd_mem_idx = rrddim_add(st_mem, "index", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
}
rrddim_set_by_pointer(st_mem, rd_mem, (collected_number)memory);
rrddim_set_by_pointer(st_mem, rd_mem_idx, (collected_number)memory_index);
rrdset_done(st_mem);
}
| 0 | 0.84112 | 1 | 0.84112 | game-dev | MEDIA | 0.384574 | game-dev | 0.861714 | 1 | 0.861714 |
Ragebones/StormCore | 1,986 | src/server/scripts/World/world_script_loader.cpp | /*
* Copyright (C) 2014-2017 StormCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "World.h"
// This is where scripts' loading functions should be declared:
// world
void AddSC_areatrigger_scripts();
void AddSC_emerald_dragons();
void AddSC_generic_creature();
void AddSC_go_scripts();
void AddSC_guards();
void AddSC_item_scripts();
void AddSC_npc_professions();
void AddSC_npc_innkeeper();
void AddSC_npcs_special();
void AddSC_achievement_scripts();
void AddSC_action_ip_logger();
void AddSC_scene_scripts();
// player
void AddSC_chat_log();
void AddSC_duel_reset();
// The name of this function should match:
// void Add${NameOfDirectory}Scripts()
void AddWorldScripts()
{
AddSC_areatrigger_scripts();
AddSC_emerald_dragons();
AddSC_generic_creature();
AddSC_go_scripts();
AddSC_guards();
AddSC_item_scripts();
AddSC_npc_professions();
AddSC_npc_innkeeper();
AddSC_npcs_special();
AddSC_achievement_scripts();
AddSC_chat_log(); // location: scripts\World\chat_log.cpp
AddSC_scene_scripts();
// FIXME: This should be moved in a script validation hook.
// To avoid duplicate code, we check once /*ONLY*/ if logging is permitted or not.
if (sWorld->getBoolConfig(CONFIG_IP_BASED_ACTION_LOGGING))
AddSC_action_ip_logger(); // location: scripts\World\action_ip_logger.cpp
AddSC_duel_reset();
}
| 0 | 0.889527 | 1 | 0.889527 | game-dev | MEDIA | 0.937222 | game-dev | 0.570254 | 1 | 0.570254 |
QuiltMC/quilt-loader | 5,771 | src/main/java/org/quiltmc/loader/api/Version.java | /*
* Copyright 2016 FabricMC
* Copyright 2022-2023 QuiltMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.quiltmc.loader.api;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Collectors;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.quiltmc.loader.impl.metadata.qmj.GenericVersionImpl;
import org.quiltmc.loader.impl.metadata.qmj.SemanticVersionImpl;
/** Representation of a version. <br>
* All implementations either implement {@link Raw} or {@link Semantic}. <br>
* Unfortunately (due to {@link Version.Semantic} already implementing {@link Comparable}) this doesn't implement
* {@link Comparable} directly. Instead you can either use {@link #compareTo(Version)} or {@link #COMPARATOR} for all your comparing needs. */
@ApiStatus.NonExtendable
public interface Version {
/** Calls {@link Version#compareTo(Version)}: this doesn't accept nulls. */
static Comparator<Version> COMPARATOR = Version::compareTo;
static Version of(String raw) {
try {
return Semantic.of(raw);
} catch (VersionFormatException ex) {
return new GenericVersionImpl(raw);
}
}
/** @return The raw string that this version was constructed from.*/
String raw();
default boolean isSemantic() {
return this instanceof Version.Semantic;
}
default Semantic semantic() {
return (Semantic) this;
}
/** If both this and the given version are semantic versions then this compares with the behaviour of
* {@link Semantic#compareTo(Semantic)}. <br>
* Otherwise both versions are compared with their {@link #raw()} strings, using the
* <a href="https://github.com/unascribed/FlexVer/blob/trunk/SPEC.md">FlexVer comparison scheme</a> */
int compareTo(Version other);
/**
* A string version, sorted with {@link String#compareTo(String)}.
*/
@ApiStatus.NonExtendable
interface Raw extends Version, Comparable<Version> {
// No additional method definitions
}
/**
* Representation of a semantic version
*/
@ApiStatus.NonExtendable
interface Semantic extends Version, Comparable<Semantic> {
/** A special value that represents a {@link #preRelease()} which is both empty but still present - for example
* "1.18.0-" (as opposed to "1.18.0", which uses the normal empty string for it's prerelease, due to the missing
* dash").
* <p>
* You can either compare this to {@link #preRelease()} using identity to check, or use
* {@link #isPreReleasePresent()}.
* <p>
* This field exists solely to keep backwards compatibility, since we can't make {@link #preRelease()} return an
* {@link Optional}. */
public static final String EMPTY_BUT_PRESENT_PRERELEASE = new String();
static Semantic of(String raw) throws VersionFormatException {
return SemanticVersionImpl.of(raw);
}
@Deprecated
static Semantic of(int major, int minor, int patch, String preRelease, String buildMetadata) throws VersionFormatException {
return of(new int[] { major, minor, patch }, preRelease, buildMetadata);
}
static Semantic of(int[] components, @Nullable String preRelease, @Nullable String buildMetadata) throws VersionFormatException {
StringBuilder raw = new StringBuilder();
raw.append(Arrays.stream(components).mapToObj(Integer::toString).collect(Collectors.joining("."))); // 1.0.0
if (preRelease != null) {
raw.append('-').append(preRelease);
}
if (buildMetadata != null) {
raw.append('+').append(buildMetadata);
}
// HACK: re-building raw makes sure that everything is verified to be valid
return SemanticVersionImpl.of(raw.toString());
}
/**
* Returns the number of components in this version.
*
* <p>For example, {@code 1.3.x} has 3 components.</p>
*
* @return the number of components
*/
int versionComponentCount();
/**
* Returns the version component at {@code pos}.
* If {@code pos} is greater than or equal to the number of components, then it returns {@code 0}.
* @param pos the position to check
* @return the version component
*/
int versionComponent(int index);
/**
* @return A new array populated with every version component, except for trailing zeros.
*/
int[] versionComponents();
/**
* Must be a positive integer.
*/
default int major() {
return versionComponent(0);
}
/**
* Must be a positive integer.
*/
default int minor() {
return versionComponent(1);
}
/**
* Must be a positive integer.
*/
default int patch() {
return versionComponent(2);
}
/**
* Returns an empty string if not applicable
*/
String preRelease();
/** @return True if the {@link #preRelease()} field is present in this version. This is used to differentiate
* versions with a dash at the end of them (like "1.18.0-", which would return true here), from "1.18.0"
* (which would return false here.
* @see #EMPTY_BUT_PRESENT_PRERELEASE */
default boolean isPreReleasePresent() {
return !preRelease().isEmpty() || preRelease() == EMPTY_BUT_PRESENT_PRERELEASE;
}
/**
* Returns an empty string if not applicable
*/
String buildMetadata();
// TODO: docs
@Override
int compareTo(Version.Semantic o);
}
}
| 0 | 0.698444 | 1 | 0.698444 | game-dev | MEDIA | 0.641249 | game-dev | 0.809034 | 1 | 0.809034 |
ljsimin/MinecraftJoypadSplitscreenMod | 4,615 | src/main/java/com/shiny/joypadmod/event/ControllerInputEvent.java | package com.shiny.joypadmod.event;
import com.shiny.joypadmod.ControllerSettings;
import com.shiny.joypadmod.JoypadMod;
/**
* Input event that encapsulates the button press, pov and axis movement
*
* @author shiny
*/
public abstract class ControllerInputEvent {
protected final EventType type;
protected final int controllerNumber;
protected final int buttonNumber;
protected float threshold;
protected float deadzone;
protected boolean isActive;
protected boolean wasReleased;
// switch whether this has ever been pressed in its lifetime
protected boolean pressedOnce;
public enum EventType {
BUTTON, AXIS, POV
}
public ControllerInputEvent(EventType type, int controllerNumber, int buttonNumber, float threshold, float deadzone) {
JoypadMod.logger.info("ControllerInputEvent constructor params:( type: " + type + ", controllerNumber: "
+ controllerNumber + ", buttonNumber: " + buttonNumber + ", threshhold: " + threshold + ", deadzone: "
+ deadzone + ")");
this.type = type;
this.controllerNumber = controllerNumber;
this.buttonNumber = buttonNumber;
this.threshold = threshold;
this.deadzone = deadzone;
isActive = false;
wasReleased = false;
pressedOnce = false;
}
// subclasses will check the controller event to see if it matches their subclass type
protected abstract boolean isTargetEvent();
// check if axis or button number is valid
public abstract boolean isValid();
public abstract float getAnalogReading();
public abstract String getName();
public abstract String getDescription();
public EventType getEventType() {
return type;
}
public boolean isActive() {
return isActive;
}
public boolean pressedOnce() {
return pressedOnce;
}
public boolean isPressed() {
if (!isActive || !isValid())
return false;
boolean ret = meetsThreshold();
if (!ret) {
wasReleased = true;
isActive = false;
}
return ret;
}
// this should only be called when a Controllers.next call has returned true
public boolean wasPressed() {
if (!isValid())
return false;
boolean bRet = wasPressedRaw() && meetsThreshold();
if (bRet) {
isActive = true;
}
if (isActive && wasReleased) {
JoypadMod.logger.warn("wasPressed returning true prior to the wasReleased being consumed");
wasReleased = false;
}
return bRet;
}
// just checks the event to see if it matches, not using threshold values
public boolean wasPressedRaw() {
if (!isValid())
return false;
if (ControllerSettings.JoypadModInputLibrary.getEventSource().getIndex() == controllerNumber && isTargetEvent()) {
pressedOnce = true;
return true;
}
return false;
}
// signify to the caller that this was just released and needs a release event to be sent
public boolean wasReleased() {
boolean bRet = false;
if (wasReleased) {
if (ControllerSettings.loggingLevel > 1)
JoypadMod.logger.debug("wasReleased returning true for " + getName());
bRet = true;
wasReleased = false;
}
return bRet;
}
protected boolean meetsThreshold() {
return threshold > 0 ? getAnalogReading() >= threshold : getAnalogReading() <= threshold;
}
public int getControllerIndex() {
return controllerNumber;
}
public int getEventIndex() {
return buttonNumber;
}
public float getThreshold() {
return threshold;
}
public void setThreshold(float f) {
threshold = f;
}
public float getDeadZone() {
return deadzone;
}
public void setDeadZone(float f) {
}
public String toConfigFileString() {
return getEventType().toString() + "," + getEventIndex() + "," + getThreshold() + "," + getDeadZone();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
ControllerInputEvent inputEvent = (ControllerInputEvent) obj;
return inputEvent.type == this.type && inputEvent.buttonNumber == this.buttonNumber
&& inputEvent.threshold == this.threshold;
}
}
| 0 | 0.85751 | 1 | 0.85751 | game-dev | MEDIA | 0.595143 | game-dev | 0.950081 | 1 | 0.950081 |
ImLegiitXD/Blossom | 3,964 | src/main/java/net/minecraft/client/gui/GuiUtilRenderComponents.java | package net.minecraft.client.gui;
import com.google.common.collect.Lists;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
public class GuiUtilRenderComponents
{
public static String func_178909_a(String p_178909_0_, boolean p_178909_1_)
{
return !p_178909_1_ && !Minecraft.getMinecraft().gameSettings.chatColours ? EnumChatFormatting.getTextWithoutFormattingCodes(p_178909_0_) : p_178909_0_;
}
public static List<IChatComponent> splitText(IChatComponent p_178908_0_, int p_178908_1_, FontRenderer p_178908_2_, boolean p_178908_3_, boolean p_178908_4_)
{
int i = 0;
IChatComponent ichatcomponent = new ChatComponentText("");
List<IChatComponent> list = Lists.<IChatComponent>newArrayList();
List<IChatComponent> list1 = Lists.newArrayList(p_178908_0_);
for (int j = 0; j < ((List)list1).size(); ++j)
{
IChatComponent ichatcomponent1 = (IChatComponent)list1.get(j);
String s = ichatcomponent1.getUnformattedTextForChat();
boolean flag = false;
if (s.contains("\n"))
{
int k = s.indexOf(10);
String s1 = s.substring(k + 1);
s = s.substring(0, k + 1);
ChatComponentText chatcomponenttext = new ChatComponentText(s1);
chatcomponenttext.setChatStyle(ichatcomponent1.getChatStyle().createShallowCopy());
list1.add(j + 1, chatcomponenttext);
flag = true;
}
String s4 = func_178909_a(ichatcomponent1.getChatStyle().getFormattingCode() + s, p_178908_4_);
String s5 = s4.endsWith("\n") ? s4.substring(0, s4.length() - 1) : s4;
int i1 = p_178908_2_.getStringWidth(s5);
ChatComponentText chatcomponenttext1 = new ChatComponentText(s5);
chatcomponenttext1.setChatStyle(ichatcomponent1.getChatStyle().createShallowCopy());
if (i + i1 > p_178908_1_)
{
String s2 = p_178908_2_.trimStringToWidth(s4, p_178908_1_ - i, false);
String s3 = s2.length() < s4.length() ? s4.substring(s2.length()) : null;
if (s3 != null && s3.length() > 0)
{
int l = s2.lastIndexOf(" ");
if (l >= 0 && p_178908_2_.getStringWidth(s4.substring(0, l)) > 0)
{
s2 = s4.substring(0, l);
if (p_178908_3_)
{
++l;
}
s3 = s4.substring(l);
}
else if (i > 0 && !s4.contains(" "))
{
s2 = "";
s3 = s4;
}
ChatComponentText chatcomponenttext2 = new ChatComponentText(s3);
chatcomponenttext2.setChatStyle(ichatcomponent1.getChatStyle().createShallowCopy());
list1.add(j + 1, chatcomponenttext2);
}
i1 = p_178908_2_.getStringWidth(s2);
chatcomponenttext1 = new ChatComponentText(s2);
chatcomponenttext1.setChatStyle(ichatcomponent1.getChatStyle().createShallowCopy());
flag = true;
}
if (i + i1 <= p_178908_1_)
{
i += i1;
ichatcomponent.appendSibling(chatcomponenttext1);
}
else
{
flag = true;
}
if (flag)
{
list.add(ichatcomponent);
i = 0;
ichatcomponent = new ChatComponentText("");
}
}
list.add(ichatcomponent);
return list;
}
}
| 0 | 0.540015 | 1 | 0.540015 | game-dev | MEDIA | 0.755758 | game-dev | 0.621687 | 1 | 0.621687 |
StrongHold/runescape-667 | 1,709 | runescape/src/main/java/Static187.java | import com.jagex.core.constants.AreaMode;
import com.jagex.game.runetek6.config.vartype.TimedVarDomain;
import org.openrs2.deob.annotation.OriginalMember;
import org.openrs2.deob.annotation.Pc;
import rs2.client.clan.channel.ClanChannel;
import rs2.client.clan.settings.ClanSettings;
public final class Static187 {
@OriginalMember(owner = "client!fp", name = "R", descriptor = "I")
public static int anInt3093 = 0;
@OriginalMember(owner = "client!fp", name = "a", descriptor = "(Z)V")
public static void method2842() {
CutsceneManager.anIntArrayArray265 = null;
CutsceneManager.id = -1;
Static117.areaMode = AreaMode.STATIC_AREA;
Static102.lastAreaMode = 0;
CutsceneManager.state = 0;
CutsceneManager.packet = null;
Static298.method4385();
Static525.areaCenterZ = 0;
WorldMap.areaBaseX = 0;
WorldMap.areaBaseZ = 0;
Static62.areaCenterX = 0;
for (@Pc(34) int local34 = 0; local34 < Static527.hintArrows.length; local34++) {
Static527.hintArrows[local34] = null;
}
Static11.method146();
for (@Pc(48) int local48 = 0; local48 < 2048; local48++) {
PlayerList.highResolutionPlayers[local48] = null;
}
NPCList.size = 0;
NPCList.local.clear();
NPCList.newSize = 0;
Static497.objStacks.clear();
Camera.reset();
VerifyId.reset();
TimedVarDomain.instance.reset();
ClanSettings.listened = null;
ClanSettings.affined = null;
Static211.pingRequest = null;
ClanChannel.affined = null;
ClanChannel.listened = null;
Static675.nextPing = 0L;
}
}
| 0 | 0.525419 | 1 | 0.525419 | game-dev | MEDIA | 0.779747 | game-dev | 0.912502 | 1 | 0.912502 |
open-toontown/open-toontown | 3,772 | toontown/building/TutorialBuildingAI.py | from panda3d.core import *
from direct.directnotify import DirectNotifyGlobal
from . import DistributedDoorAI
from . import DistributedTutorialInteriorAI
from . import FADoorCodes
from . import DoorTypes
from toontown.toon import NPCToons
from toontown.toonbase import TTLocalizer
# This is not a distributed class... It just owns and manages some distributed
# classes.
class TutorialBuildingAI:
def __init__(self, air, exteriorZone, interiorZone, blockNumber):
# While this is not a distributed object, it needs to know about
# the repository.
self.air = air
self.exteriorZone = exteriorZone
self.interiorZone = interiorZone
# This is because we are "pretending" to be a DistributedBuilding.
# The DistributedTutorialInterior takes a peek at savedBy. It really
# should make a function call. Perhaps TutorialBuildingAI and
# DistributedBuildingAI should inherit from each other somehow,
# but I can't see an easy way to do that.
self.savedBy = None
self.setup(blockNumber)
def cleanup(self):
self.interior.requestDelete()
del self.interior
self.door.requestDelete()
del self.door
self.insideDoor.requestDelete()
del self.insideDoor
self.gagShopNPC.requestDelete()
del self.gagShopNPC
return
def setup(self, blockNumber):
# Put an NPC in here. Give him id# 20000. When he has assigned
# his quest, he will unlock the interior door.
self.gagShopNPC = NPCToons.createNPC(
self.air, 20000,
(self.interiorZone,
TTLocalizer.NPCToonNames[20000],
("dll" ,"ms" ,"m" ,"m" ,7 ,0 ,7 ,7 ,2 ,6 ,2 ,6 ,2 ,16), "m", 1, NPCToons.NPC_REGULAR),
self.interiorZone,
questCallback=self.unlockInteriorDoor)
# Flag him as being part of tutorial
self.gagShopNPC.setTutorial(1)
npcId = self.gagShopNPC.getDoId()
# Toon interior (with tutorial flag set to 1)
self.interior=DistributedTutorialInteriorAI.DistributedTutorialInteriorAI(
blockNumber, self.air, self.interiorZone, self, npcId)
self.interior.generateWithRequired(self.interiorZone)
# Outside door:
door=DistributedDoorAI.DistributedDoorAI(self.air, blockNumber,
DoorTypes.EXT_STANDARD,
lockValue=FADoorCodes.DEFEAT_FLUNKY_TOM)
# Inside door. Locked until you get your gags.
insideDoor=DistributedDoorAI.DistributedDoorAI(
self.air,
blockNumber,
DoorTypes.INT_STANDARD,
lockValue=FADoorCodes.TALK_TO_TOM)
# Tell them about each other:
door.setOtherDoor(insideDoor)
insideDoor.setOtherDoor(door)
door.zoneId=self.exteriorZone
insideDoor.zoneId=self.interiorZone
# Now that they both now about each other, generate them:
door.generateWithRequired(self.exteriorZone)
#door.sendUpdate("setDoorIndex", [door.getDoorIndex()])
insideDoor.generateWithRequired(self.interiorZone)
#insideDoor.sendUpdate("setDoorIndex", [door.getDoorIndex()])
# keep track of them:
self.door=door
self.insideDoor=insideDoor
return
def unlockInteriorDoor(self):
self.insideDoor.setDoorLock(FADoorCodes.UNLOCKED)
def battleOverCallback(self):
# There is an if statement here because it is possible for
# the callback to get called after cleanup has already taken
# place.
if hasattr(self, "door"):
self.door.setDoorLock(FADoorCodes.TALK_TO_HQ_TOM) | 0 | 0.843813 | 1 | 0.843813 | game-dev | MEDIA | 0.662858 | game-dev | 0.821416 | 1 | 0.821416 |
BuiltBrokenModding/ICBM-2 | 3,129 | src/main/java/com/builtbroken/icbm/content/blast/potion/BlastRadiation.java | package com.builtbroken.icbm.content.blast.potion;
import com.builtbroken.mc.api.explosive.IExplosiveHandler;
import com.builtbroken.mc.imp.transform.vector.Pos;
import com.builtbroken.mc.framework.explosive.blast.Blast;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MovingObjectPosition;
import java.util.List;
/**
* @see <a href="https://github.com/BuiltBrokenModding/VoltzEngine/blob/development/license.md">License</a> for what you can and can't do with the code.
* Created by Dark(DarkGuardsman, Robert) on 5/18/2017.
*/
public class BlastRadiation extends Blast<BlastRadiation>
{
public BlastRadiation(IExplosiveHandler handler)
{
super(handler);
}
@Override
public int shouldThreadAction()
{
return -1;
}
@Override
public void doEffectOther(boolean beforeBlocksPlaced)
{
super.doEffectOther(beforeBlocksPlaced);
if (beforeBlocksPlaced)
{
final Pos center = toPos();
List<Entity> entityList = oldWorld.getEntitiesWithinAABB(Entity.class, AxisAlignedBB.getBoundingBox(x - size, 0, z - size, x + size, 255, z + size));
for (Entity entity : entityList)
{
if (entity instanceof EntityLivingBase)
{
final Pos pos = new Pos(entity);
double distance = pos.distance(center);
if (distance < size)
{
Pos head = pos.add(0, entity.getEyeHeight(), 0);
MovingObjectPosition hit = head.rayTrace(oldWorld, center);
if (hit != null && hit.typeOfHit != MovingObjectPosition.MovingObjectType.BLOCK)
{
if (distance < size * 0.1)
{
//TODO lethal damage
((EntityLivingBase) entity).addPotionEffect(new PotionEffect(Potion.weakness.getId(), 2000, 2));
((EntityLivingBase) entity).addPotionEffect(new PotionEffect(Potion.wither.getId(), 2000, 2));
}
else if (distance < size * 0.5)
{
//TODO heavy damage
((EntityLivingBase) entity).addPotionEffect(new PotionEffect(Potion.weakness.getId(), 800, 2));
((EntityLivingBase) entity).addPotionEffect(new PotionEffect(Potion.wither.getId(), 800, 1));
}
else
{
//light damage
((EntityLivingBase) entity).addPotionEffect(new PotionEffect(Potion.weakness.getId(), 200, 1));
}
}
}
}
}
}
}
}
| 0 | 0.908467 | 1 | 0.908467 | game-dev | MEDIA | 0.985552 | game-dev | 0.931556 | 1 | 0.931556 |
holycake/mhsj | 9,528 | d/huanggong/npc/pang.c | // created 10/05/1997 by snowcat
#include <ansi.h>
inherit NPC;
#define DEBUG 0
#define MYFILE "/d/huanggong/npc/pang.c"
#define MAXCATEGORY 5
#define MAXPOSITION 3
string *categories = ({
"金榜",
"银榜",
"铜榜",
"铁榜",
"锡榜",
});
string *positions = ({
"状元",
"榜眼",
"探花",
});
int *limits = ({
200000,
100000,
50000,
10000,
1000,
});
#define LEVEL_NONE 0
#define LEVEL_ASKED 1
#define LEVEL_RANKED 2
int interval_set = 0;
int fight_times = 0;
string FST = 0;
void create()
{
set_name("房玄龄", ({ "pang xuanling", "pang", "xuanling" }));
set("title", "大宰相");
set("gender", "男性");
set("age", 60);
set("per", 30);
set("combat_exp", 300000);
set_skill("force", 80);
set_skill("spells", 80);
set_skill("unarmed", 80);
set_skill("dodge", 80);
set_skill("parry", 80);
set("gin", 3000);
set("max_gin", 3000);
set("kee", 3000);
set("max_kee", 3000);
set("sen", 3000);
set("max_sen", 3000);
set("force", 1000);
set("max_force", 1000);
set("mana", 1000);
set("max_mana", 1000);
set("force_factor", 80);
setup();
carry_object("/d/obj/cloth/jinpao")->wear();
}
int execute_help();
int execute_ask();
void init()
{
::init();
add_action("do_fight", "fight");
add_action("do_kill", "kill");
add_action("do_steal", "steal");
add_action("do_cast", "cast");
add_action("do_exert", "exert");
add_action("do_perform", "perform");
add_action("do_bian", "bian");
set("inquiry", ([
"?": (: execute_help() :),
"help": (: execute_help() :),
"fight": (: execute_ask() :),
"投状": (: execute_ask() :),
"状元": (: execute_ask() :),
"武状元": (: execute_ask() :),
"比武": (: execute_ask() :),
]));
if (FST == 0)
{
FST = "/d/huanggong/fst";
}
}
string randomize (string *strs)
{
return strs[random(sizeof(strs))];
}
string get_name (object who)
{
return who->query("name");
}
string get_respect (object who)
{
return "这位"+RANK_D->query_respect(who);
}
void announce (object me, string str)
{
if (DEBUG)
{
object snowcat = find_player ("snowcat");
if (snowcat && wizardp(snowcat))
tell_object (snowcat,"◆ "+str+"\n");
}
else
{
CHANNEL_D->do_channel(me,"chat",str);
}
}
int do_fight(string arg)
{
object who = this_player();
object me = this_object();
if (arg && present(arg,environment(who))==me)
{
message_vision ("$N对$n慌忙示意: "+get_respect(who)+
",宫内岂可动粗!\n",me,who);
return 1;
}
return 0;
}
int do_kill(string arg)
{
object who = this_player();
object me = this_object();
if (arg && present(arg,environment(who))==me)
{
message_vision ("$N对$n慌忙示意: "+get_respect(who)+
",宫内不可妄念杀人!\n",me,who);
return 1;
}
return 0;
}
int do_cast(string arg)
{
object who = this_player();
object me = this_object();
if (arg == "transfer")
return 0;
message_vision ("$N对$n慌忙示意: "+get_respect(who)+
",宫内岂可乱施妖术!\n",me,who);
return 1;
}
int do_exert(string arg)
{
object who = this_player();
object me = this_object();
if (arg != "sheqi pang xuenling" &&
arg != "sheqi pang" &&
arg != "sheqi xuenling")
return 0;
message_vision ("$N对$n慌忙示意: "+get_respect(who)+
",宫内岂可私施邪功!\n",me,who);
return 1;
}
int do_perform(string arg)
{
object who = this_player();
object me = this_object();
message_vision ("$N对$n慌忙示意: "+get_respect(who)+
",宫内岂可私施邪功!\n",me,who);
return 1;
}
int do_steal(string arg)
{
object who = this_player();
object me = this_object();
message_vision ("$N对$n慌忙示意: "+get_respect(who)+
",宫内岂能行窃!\n",me,who);
return 1;
}
int do_bian(string arg)
{
object who = this_player();
object me = this_object();
message_vision ("$N对$n慌忙示意: "+get_respect(who)+
",宫内岂能随便变鬼!\n",me,who);
return 1;
}
int execute_help ()
{
object who = this_player();
object me = this_object();
switch (me->query_temp("huanggong/level"))
{
case LEVEL_NONE:
{
message_vision ("$N对$n说道:"+get_respect(who)+
"入宫应招投状,有何难处请问便是。\n",me,who);
break;
}
case LEVEL_ASKED:
{
message_vision ("$N对$n说道:"+get_respect(who)+
"可凭自身武功高低,先去金榜银榜铜榜铁榜锡榜中选其一榜,"+
"再择状元榜眼探花之一与之挑战。\n",me,who);
break;
}
case LEVEL_RANKED:
{
message_vision ("$N对$n说道:"+get_respect(who)+
"可凭自身武功高低,先去金榜银榜铜榜铁榜锡榜中选其一榜,"+
"再择状元榜眼探花之一与之挑战。\n",me,who);
break;
}
}
return 1;
}
void reset_interval ()
{
interval_set = 0;
fight_times = 0;
}
int execute_ask ()
{
object who = this_player();
object me = this_object();
if (who->query("combat_exp") >= limits[0])
{
message_vision ("$N对$n慌忙摇头:以"+get_respect(who)+
"的武功修为,那里还用的着争这小小的虚名!\n",me,who);
return 1;
}
if (me->query_temp("huanggong/is_busy"))
{
message_vision ("$N对$n摇摇头:"+get_respect(who)+
",老夫正忙得不可开交,恕罪失陪了。\n",me,who);
return 1;
}
if(me->query_temp("huanggong/level") < LEVEL_ASKED)
{
if (interval_set)
{
message_vision ("$N对$n摇摇头:"+get_respect(who)+
",投状时间已过,恕罪恕罪。\n",me,who);
return 1;
}
announce (me,who->query("name")+get_respect(who)+"前来入宫投状!\n");
message_vision ("$N对$n说道:"+get_respect(who)+
",老夫这就启奏陛下,报请恩准天下比武封选武状元!\n",me,who);
message_vision ("$N一甩长袖,风一样离去。\n",me);
//me->set("env/invisibility",9);
me->set_temp("huanggong/reappear",environment(me));
load_object("/obj/empty");
me->move("/obj/empty");
remove_call_out ("make_asked");
call_out ("make_asked",10,me,who);
return 1;
}
// LEVEL_ASKED, LEVEL_RANKED
remove_call_out ("continue_asked");
call_out ("continue_asked",1,me,who);
return 1;
}
void make_asked (object me, object who)
{
if (!who ||
!environment(who) ||
environment(who) != me->query_temp("huanggong/reappear"))
{
me->move(me->query_temp("huanggong/reappear"));
message_vision ("$N甩着长袖,风一样飘了过来。\n",me);
return;
}
announce (me,"陛下恩准天下比武封选武状元!");
announce (me,"五湖四海各路武进士恭请进宫投状!");
interval_set = 1;
fight_times = 0;
call_out ("reset_interval", 14400); // 4h
me->set_temp("no_return",1);
me->set_temp("huanggong/level",LEVEL_ASKED);
//me->set("env/invisibility",0);
me->move(me->query_temp("huanggong/reappear"));
message_vision ("$N甩着长袖,风一样飘了过来。\n",me);
remove_call_out ("continue_asked");
call_out ("continue_asked",1,me,who);
}
void continue_asked (object me, object who)
{
message_vision ("$N对$n说道:"+get_respect(who)+
"带老夫去揭榜挑战。\n",me,who);
message_vision ("$N一甩长袖,紧紧飘在$n后面。\n",me,who);
who->set_leader(me);
me->set_leader(who);
}
int execute_approve_fight(object who, object ob, int position, int category)
{
object me = this_object();
if (who->query("combat_exp") >= limits[0])
{
message_vision ("$N对$n说道:以"+get_respect(who)+
"的武功修为,那里还用的着争这小小的虚名!\n",me,who);
return 0;
}
if (who->query("combat_exp") >= limits[category-1])
{
message_vision ("$N对$n说道:以"+get_respect(who)+
"的武功修为,拜揭"+categories[category-1]+"还不是手到擒来?不用比了,不用比了。\n",me,who);
return 0;
}
if (category < MAXCATEGORY &&
who->query("combat_exp") < limits[category])
{
message_vision ("$N对$n说道:"+get_respect(who)+
"的武功修为似乎还不到拜揭"+categories[category-1]+"的地步,量力而行吧。\n",me,who);
return 0;
}
announce (me,who->query("name")+"前来拜揭"+categories[category-1]+
",与"+ob->query("name")+"比武争夺"+positions[position-1]+"!\n");
me->set_temp("huanggong/is_busy",1);
me->set_leader(0);
call_out("reset_is_busy",60,me);
return 1;
}
int execute_fight_result (object who, object ob, int success)
{
object me = this_object();
int i;
reset_eval_cost();
call_out("reset_is_busy",5,me);
if (! success)
return 1;
if (!ob)
return 1;
if (!present(ob, environment(me)))
return 1;
announce (me,ob->query("name")+environment(me)->query("short")+
"击败"+who->query("name")+"!\n");
announce (me,"陛下有旨,封"+ob->query("name")+"为"+
who->get_honor_str()+"!\n");
i = ob->query("huanggong/wins")+1;
ob->set("huanggong/wins",i);
i = (MAXPOSITION*MAXCATEGORY*9)/i + random(9);
ob->add("combat_exp",i);
/*
y = i/1000;
d = (i - y*1000) / 4;
h = (i - y*1000 - d*4) * 3;
if (y > 0)
tell_object(ob,"你的道行增加了"+chinese_number(y)+"年"+
chinese_number(d)+"天"+chinese_number(h)+"时辰!\n\n");
else if (d > 0)
tell_object(ob,"你的道行增加了"+
chinese_number(d)+"天"+chinese_number(h)+"时辰!\n\n");
else if (h > 0)
tell_object(ob,"你的道行增加了"+
chinese_number(h)+"时辰!\n\n");
*/
tell_object(ob,"你的武学修为增加了"+chinese_number(i)+"点!\n\n");
me->set_temp("huanggong/current_player",ob->query("id"));
me->set_temp("huanggong/level",LEVEL_RANKED);
fight_times++;
if (fight_times > (MAXPOSITION*MAXCATEGORY/2))
{
announce (me,"陛下有旨封选武状元结束各路武进士恭请离宫!\n");
message_vision ("$N甩一甩长袖,风一般飘走了。\n",me);
me->move(FST);
me->set_temp("huanggong/is_busy",0);
me->set_temp("huanggong/level",LEVEL_NONE);
return 1;
}
message_vision ("$N若还有武进士欲继续挑战,"+
"可带老夫去揭榜。\n",me);
message_vision ("$N一甩长袖,飘在$n身后。\n",me,ob);
me->set_leader(ob);
return 1;
}
void reset_is_busy(object me)
{
me->set_temp("huanggong/is_busy",0);
}
| 0 | 0.892551 | 1 | 0.892551 | game-dev | MEDIA | 0.874449 | game-dev | 0.889974 | 1 | 0.889974 |
cfoust/sour | 35,885 | game/src/fpsgame/game.h | #ifndef __GAME_H__
#define __GAME_H__
#include "cube.h"
// console message types
enum
{
CON_CHAT = 1<<8,
CON_TEAMCHAT = 1<<9,
CON_GAMEINFO = 1<<10,
CON_FRAG_SELF = 1<<11,
CON_FRAG_OTHER = 1<<12,
CON_TEAMKILL = 1<<13
};
// network quantization scale
#define DMF 16.0f // for world locations
#define DNF 100.0f // for normalized vectors
#define DVELF 1.0f // for playerspeed based velocity vectors
enum // static entity types
{
NOTUSED = ET_EMPTY, // entity slot not in use in map
LIGHT = ET_LIGHT, // lightsource, attr1 = radius, attr2 = intensity
MAPMODEL = ET_MAPMODEL, // attr1 = angle, attr2 = idx
PLAYERSTART, // attr1 = angle, attr2 = team
ENVMAP = ET_ENVMAP, // attr1 = radius
PARTICLES = ET_PARTICLES,
MAPSOUND = ET_SOUND,
SPOTLIGHT = ET_SPOTLIGHT,
I_SHELLS, I_BULLETS, I_ROCKETS, I_ROUNDS, I_GRENADES, I_CARTRIDGES,
I_HEALTH, I_BOOST,
I_GREENARMOUR, I_YELLOWARMOUR,
I_QUAD,
TELEPORT, // attr1 = idx, attr2 = model, attr3 = tag
TELEDEST, // attr1 = angle, attr2 = idx
MONSTER, // attr1 = angle, attr2 = monstertype
CARROT, // attr1 = tag, attr2 = type
JUMPPAD, // attr1 = zpush, attr2 = ypush, attr3 = xpush
BASE,
RESPAWNPOINT,
BOX, // attr1 = angle, attr2 = idx, attr3 = weight
BARREL, // attr1 = angle, attr2 = idx, attr3 = weight, attr4 = health
PLATFORM, // attr1 = angle, attr2 = idx, attr3 = tag, attr4 = speed
ELEVATOR, // attr1 = angle, attr2 = idx, attr3 = tag, attr4 = speed
FLAG, // attr1 = angle, attr2 = team
MAXENTTYPES
};
enum
{
TRIGGER_RESET = 0,
TRIGGERING,
TRIGGERED,
TRIGGER_RESETTING,
TRIGGER_DISAPPEARED
};
struct fpsentity : extentity
{
int triggerstate, lasttrigger;
fpsentity() : triggerstate(TRIGGER_RESET), lasttrigger(0) {}
};
enum { GUN_FIST = 0, GUN_SG, GUN_CG, GUN_RL, GUN_RIFLE, GUN_GL, GUN_PISTOL, GUN_FIREBALL, GUN_ICEBALL, GUN_SLIMEBALL, GUN_BITE, GUN_BARREL, NUMGUNS };
enum { A_BLUE, A_GREEN, A_YELLOW }; // armour types... take 20/40/60 % off
enum { M_NONE = 0, M_SEARCH, M_HOME, M_ATTACKING, M_PAIN, M_SLEEP, M_AIMING }; // monster states
enum
{
M_TEAM = 1<<0,
M_NOITEMS = 1<<1,
M_NOAMMO = 1<<2,
M_INSTA = 1<<3,
M_EFFICIENCY = 1<<4,
M_TACTICS = 1<<5,
M_CAPTURE = 1<<6,
M_REGEN = 1<<7,
M_CTF = 1<<8,
M_PROTECT = 1<<9,
M_HOLD = 1<<10,
M_EDIT = 1<<12,
M_DEMO = 1<<13,
M_LOCAL = 1<<14,
M_LOBBY = 1<<15,
M_DMSP = 1<<16,
M_CLASSICSP = 1<<17,
M_SLOWMO = 1<<18,
M_COLLECT = 1<<19
};
static struct gamemodeinfo
{
const char *name;
int flags;
const char *info;
} gamemodes[] =
{
{ "SP", M_LOCAL | M_CLASSICSP, NULL },
{ "DMSP", M_LOCAL | M_DMSP, NULL },
{ "demo", M_DEMO | M_LOCAL, NULL},
{ "ffa", M_LOBBY, "Free For All: Collect items for ammo. Frag everyone to score points." },
{ "coop edit", M_EDIT, "Cooperative Editing: Edit maps with multiple players simultaneously." },
{ "teamplay", M_TEAM, "Teamplay: Collect items for ammo. Frag \fs\f3the enemy team\fr to score points for \fs\f1your team\fr." },
{ "instagib", M_NOITEMS | M_INSTA, "Instagib: You spawn with full rifle ammo and die instantly from one shot. There are no items. Frag everyone to score points." },
{ "insta team", M_NOITEMS | M_INSTA | M_TEAM, "Instagib Team: You spawn with full rifle ammo and die instantly from one shot. There are no items. Frag \fs\f3the enemy team\fr to score points for \fs\f1your team\fr." },
{ "efficiency", M_NOITEMS | M_EFFICIENCY, "Efficiency: You spawn with all weapons and armour. There are no items. Frag everyone to score points." },
{ "effic team", M_NOITEMS | M_EFFICIENCY | M_TEAM, "Efficiency Team: You spawn with all weapons and armour. There are no items. Frag \fs\f3the enemy team\fr to score points for \fs\f1your team\fr." },
{ "tactics", M_NOITEMS | M_TACTICS, "Tactics: You spawn with two random weapons and armour. There are no items. Frag everyone to score points." },
{ "tac team", M_NOITEMS | M_TACTICS | M_TEAM, "Tactics Team: You spawn with two random weapons and armour. There are no items. Frag \fs\f3the enemy team\fr to score points for \fs\f1your team\fr." },
{ "capture", M_NOAMMO | M_TACTICS | M_CAPTURE | M_TEAM, "Capture: Capture neutral bases or steal \fs\f3enemy bases\fr by standing next to them. \fs\f1Your team\fr scores points for every 10 seconds it holds a base. You spawn with two random weapons and armour. Collect extra ammo that spawns at \fs\f1your bases\fr. There are no ammo items." },
{ "regen capture", M_NOITEMS | M_CAPTURE | M_REGEN | M_TEAM, "Regen Capture: Capture neutral bases or steal \fs\f3enemy bases\fr by standing next to them. \fs\f1Your team\fr scores points for every 10 seconds it holds a base. Regenerate health and ammo by standing next to \fs\f1your bases\fr. There are no items." },
{ "ctf", M_CTF | M_TEAM, "Capture The Flag: Capture \fs\f3the enemy flag\fr and bring it back to \fs\f1your flag\fr to score points for \fs\f1your team\fr. Collect items for ammo." },
{ "insta ctf", M_NOITEMS | M_INSTA | M_CTF | M_TEAM, "Instagib Capture The Flag: Capture \fs\f3the enemy flag\fr and bring it back to \fs\f1your flag\fr to score points for \fs\f1your team\fr. You spawn with full rifle ammo and die instantly from one shot. There are no items." },
{ "protect", M_CTF | M_PROTECT | M_TEAM, "Protect The Flag: Touch \fs\f3the enemy flag\fr to score points for \fs\f1your team\fr. Pick up \fs\f1your flag\fr to protect it. \fs\f1Your team\fr loses points if a dropped flag resets. Collect items for ammo." },
{ "insta protect", M_NOITEMS | M_INSTA | M_CTF | M_PROTECT | M_TEAM, "Instagib Protect The Flag: Touch \fs\f3the enemy flag\fr to score points for \fs\f1your team\fr. Pick up \fs\f1your flag\fr to protect it. \fs\f1Your team\fr loses points if a dropped flag resets. You spawn with full rifle ammo and die instantly from one shot. There are no items." },
{ "hold", M_CTF | M_HOLD | M_TEAM, "Hold The Flag: Hold \fs\f7the flag\fr for 20 seconds to score points for \fs\f1your team\fr. Collect items for ammo." },
{ "insta hold", M_NOITEMS | M_INSTA | M_CTF | M_HOLD | M_TEAM, "Instagib Hold The Flag: Hold \fs\f7the flag\fr for 20 seconds to score points for \fs\f1your team\fr. You spawn with full rifle ammo and die instantly from one shot. There are no items." },
{ "effic ctf", M_NOITEMS | M_EFFICIENCY | M_CTF | M_TEAM, "Efficiency Capture The Flag: Capture \fs\f3the enemy flag\fr and bring it back to \fs\f1your flag\fr to score points for \fs\f1your team\fr. You spawn with all weapons and armour. There are no items." },
{ "effic protect", M_NOITEMS | M_EFFICIENCY | M_CTF | M_PROTECT | M_TEAM, "Efficiency Protect The Flag: Touch \fs\f3the enemy flag\fr to score points for \fs\f1your team\fr. Pick up \fs\f1your flag\fr to protect it. \fs\f1Your team\fr loses points if a dropped flag resets. You spawn with all weapons and armour. There are no items." },
{ "effic hold", M_NOITEMS | M_EFFICIENCY | M_CTF | M_HOLD | M_TEAM, "Efficiency Hold The Flag: Hold \fs\f7the flag\fr for 20 seconds to score points for \fs\f1your team\fr. You spawn with all weapons and armour. There are no items." },
{ "collect", M_COLLECT | M_TEAM, "Skull Collector: Frag \fs\f3the enemy team\fr to drop \fs\f3skulls\fr. Collect them and bring them to \fs\f3the enemy base\fr to score points for \fs\f1your team\fr or steal back \fs\f1your skulls\fr. Collect items for ammo." },
{ "insta collect", M_NOITEMS | M_INSTA | M_COLLECT | M_TEAM, "Instagib Skull Collector: Frag \fs\f3the enemy team\fr to drop \fs\f3skulls\fr. Collect them and bring them to \fs\f3the enemy base\fr to score points for \fs\f1your team\fr or steal back \fs\f1your skulls\fr. You spawn with full rifle ammo and die instantly from one shot. There are no items." },
{ "effic collect", M_NOITEMS | M_EFFICIENCY | M_COLLECT | M_TEAM, "Efficiency Skull Collector: Frag \fs\f3the enemy team\fr to drop \fs\f3skulls\fr. Collect them and bring them to \fs\f3the enemy base\fr to score points for \fs\f1your team\fr or steal back \fs\f1your skulls\fr. You spawn with all weapons and armour. There are no items." }
};
#define STARTGAMEMODE (-3)
#define NUMGAMEMODES ((int)(sizeof(gamemodes)/sizeof(gamemodes[0])))
#define m_valid(mode) ((mode) >= STARTGAMEMODE && (mode) < STARTGAMEMODE + NUMGAMEMODES)
#define m_check(mode, flag) (m_valid(mode) && gamemodes[(mode) - STARTGAMEMODE].flags&(flag))
#define m_checknot(mode, flag) (m_valid(mode) && !(gamemodes[(mode) - STARTGAMEMODE].flags&(flag)))
#define m_checkall(mode, flag) (m_valid(mode) && (gamemodes[(mode) - STARTGAMEMODE].flags&(flag)) == (flag))
#define m_checkonly(mode, flag, exclude) (m_valid(mode) && (gamemodes[(mode) - STARTGAMEMODE].flags&((flag)|(exclude))) == (flag))
#define m_noitems (m_check(gamemode, M_NOITEMS))
#define m_noammo (m_check(gamemode, M_NOAMMO|M_NOITEMS))
#define m_insta (m_check(gamemode, M_INSTA))
#define m_tactics (m_check(gamemode, M_TACTICS))
#define m_efficiency (m_check(gamemode, M_EFFICIENCY))
#define m_capture (m_check(gamemode, M_CAPTURE))
#define m_capture_only (m_checkonly(gamemode, M_CAPTURE, M_REGEN))
#define m_regencapture (m_checkall(gamemode, M_CAPTURE | M_REGEN))
#define m_ctf (m_check(gamemode, M_CTF))
#define m_ctf_only (m_checkonly(gamemode, M_CTF, M_PROTECT | M_HOLD))
#define m_protect (m_checkall(gamemode, M_CTF | M_PROTECT))
#define m_hold (m_checkall(gamemode, M_CTF | M_HOLD))
#define m_collect (m_check(gamemode, M_COLLECT))
#define m_teammode (m_check(gamemode, M_TEAM))
#define isteam(a,b) (m_teammode && strcmp(a, b)==0)
#define m_demo (m_check(gamemode, M_DEMO))
#define m_edit (m_check(gamemode, M_EDIT))
#define m_lobby (m_check(gamemode, M_LOBBY))
#define m_timed (m_checknot(gamemode, M_DEMO|M_EDIT|M_LOCAL))
#define m_botmode (m_checknot(gamemode, M_DEMO|M_LOCAL))
#define m_mp(mode) (m_checknot(mode, M_LOCAL))
#define m_sp (m_check(gamemode, M_DMSP | M_CLASSICSP))
#define m_dmsp (m_check(gamemode, M_DMSP))
#define m_classicsp (m_check(gamemode, M_CLASSICSP))
enum { MM_AUTH = -1, MM_OPEN = 0, MM_VETO, MM_LOCKED, MM_PRIVATE, MM_PASSWORD, MM_START = MM_AUTH };
static const char * const mastermodenames[] = { "auth", "open", "veto", "locked", "private", "password" };
static const char * const mastermodecolors[] = { "", "\f0", "\f2", "\f2", "\f3", "\f3" };
static const char * const mastermodeicons[] = { "server", "server", "serverlock", "serverlock", "serverpriv", "serverpriv" };
// hardcoded sounds, defined in sounds.cfg
enum
{
S_JUMP = 0, S_LAND, S_RIFLE, S_PUNCH1, S_SG, S_CG,
S_RLFIRE, S_RLHIT, S_WEAPLOAD, S_ITEMAMMO, S_ITEMHEALTH,
S_ITEMARMOUR, S_ITEMPUP, S_ITEMSPAWN, S_TELEPORT, S_NOAMMO, S_PUPOUT,
S_PAIN1, S_PAIN2, S_PAIN3, S_PAIN4, S_PAIN5, S_PAIN6,
S_DIE1, S_DIE2,
S_FLAUNCH, S_FEXPLODE,
S_SPLASH1, S_SPLASH2,
S_GRUNT1, S_GRUNT2, S_RUMBLE,
S_PAINO,
S_PAINR, S_DEATHR,
S_PAINE, S_DEATHE,
S_PAINS, S_DEATHS,
S_PAINB, S_DEATHB,
S_PAINP, S_PIGGR2,
S_PAINH, S_DEATHH,
S_PAIND, S_DEATHD,
S_PIGR1, S_ICEBALL, S_SLIMEBALL,
S_JUMPPAD, S_PISTOL,
S_V_BASECAP, S_V_BASELOST,
S_V_FIGHT,
S_V_BOOST, S_V_BOOST10,
S_V_QUAD, S_V_QUAD10,
S_V_RESPAWNPOINT,
S_FLAGPICKUP,
S_FLAGDROP,
S_FLAGRETURN,
S_FLAGSCORE,
S_FLAGRESET,
S_BURN,
S_CHAINSAW_ATTACK,
S_CHAINSAW_IDLE,
S_HIT,
S_FLAGFAIL
};
// network messages codes, c2s, c2c, s2c
enum { PRIV_NONE = 0, PRIV_MASTER, PRIV_AUTH, PRIV_ADMIN };
enum
{
N_CONNECT = 0, N_SERVINFO, N_WELCOME, N_INITCLIENT, N_POS, N_TEXT, N_SOUND, N_CDIS,
N_SHOOT, N_EXPLODE, N_SUICIDE,
N_DIED, N_DAMAGE, N_HITPUSH, N_SHOTFX, N_EXPLODEFX,
N_TRYSPAWN, N_SPAWNSTATE, N_SPAWN, N_FORCEDEATH,
N_GUNSELECT, N_TAUNT,
N_MAPCHANGE, N_MAPVOTE, N_TEAMINFO, N_ITEMSPAWN, N_ITEMPICKUP, N_ITEMACC, N_TELEPORT, N_JUMPPAD,
N_PING, N_PONG, N_CLIENTPING,
N_TIMEUP, N_FORCEINTERMISSION,
N_SERVMSG, N_ITEMLIST, N_RESUME,
N_EDITMODE, N_EDITENT, N_EDITF, N_EDITT, N_EDITM, N_FLIP, N_COPY, N_PASTE, N_ROTATE, N_REPLACE, N_DELCUBE, N_REMIP, N_EDITVSLOT, N_UNDO, N_REDO, N_NEWMAP, N_GETMAP, N_SENDMAP, N_CLIPBOARD, N_EDITVAR,
N_MASTERMODE, N_KICK, N_CLEARBANS, N_CURRENTMASTER, N_SPECTATOR, N_SETMASTER, N_SETTEAM,
N_BASES, N_BASEINFO, N_BASESCORE, N_REPAMMO, N_BASEREGEN, N_ANNOUNCE,
N_LISTDEMOS, N_SENDDEMOLIST, N_GETDEMO, N_SENDDEMO,
N_DEMOPLAYBACK, N_RECORDDEMO, N_STOPDEMO, N_CLEARDEMOS,
N_TAKEFLAG, N_RETURNFLAG, N_RESETFLAG, N_INVISFLAG, N_TRYDROPFLAG, N_DROPFLAG, N_SCOREFLAG, N_INITFLAGS,
N_SAYTEAM,
N_CLIENT,
N_AUTHTRY, N_AUTHKICK, N_AUTHCHAL, N_AUTHANS, N_REQAUTH,
N_PAUSEGAME, N_GAMESPEED,
N_ADDBOT, N_DELBOT, N_INITAI, N_FROMAI, N_BOTLIMIT, N_BOTBALANCE,
N_MAPCRC, N_CHECKMAPS,
N_SWITCHNAME, N_SWITCHMODEL, N_SWITCHTEAM,
N_INITTOKENS, N_TAKETOKEN, N_EXPIRETOKENS, N_DROPTOKENS, N_DEPOSITTOKENS, N_STEALTOKENS,
N_SERVCMD,
N_DEMOPACKET,
NUMMSG
};
static const int msgsizes[] = // size inclusive message token, 0 for variable or not-checked sizes
{
N_CONNECT, 0, N_SERVINFO, 0, N_WELCOME, 1, N_INITCLIENT, 0, N_POS, 0, N_TEXT, 0, N_SOUND, 2, N_CDIS, 2,
N_SHOOT, 0, N_EXPLODE, 0, N_SUICIDE, 1,
N_DIED, 5, N_DAMAGE, 6, N_HITPUSH, 7, N_SHOTFX, 10, N_EXPLODEFX, 4,
N_TRYSPAWN, 1, N_SPAWNSTATE, 14, N_SPAWN, 3, N_FORCEDEATH, 2,
N_GUNSELECT, 2, N_TAUNT, 1,
N_MAPCHANGE, 0, N_MAPVOTE, 0, N_TEAMINFO, 0, N_ITEMSPAWN, 2, N_ITEMPICKUP, 2, N_ITEMACC, 3,
N_PING, 2, N_PONG, 2, N_CLIENTPING, 2,
N_TIMEUP, 2, N_FORCEINTERMISSION, 1,
N_SERVMSG, 0, N_ITEMLIST, 0, N_RESUME, 0,
N_EDITMODE, 2, N_EDITENT, 11, N_EDITF, 16, N_EDITT, 16, N_EDITM, 16, N_FLIP, 14, N_COPY, 14, N_PASTE, 14, N_ROTATE, 15, N_REPLACE, 17, N_DELCUBE, 14, N_REMIP, 1, N_EDITVSLOT, 16, N_UNDO, 0, N_REDO, 0, N_NEWMAP, 2, N_GETMAP, 1, N_SENDMAP, 0, N_EDITVAR, 0,
N_MASTERMODE, 2, N_KICK, 0, N_CLEARBANS, 1, N_CURRENTMASTER, 0, N_SPECTATOR, 3, N_SETMASTER, 0, N_SETTEAM, 0,
N_BASES, 0, N_BASEINFO, 0, N_BASESCORE, 0, N_REPAMMO, 1, N_BASEREGEN, 6, N_ANNOUNCE, 2,
N_LISTDEMOS, 1, N_SENDDEMOLIST, 0, N_GETDEMO, 3, N_SENDDEMO, 0,
N_DEMOPLAYBACK, 3, N_RECORDDEMO, 2, N_STOPDEMO, 1, N_CLEARDEMOS, 2,
N_TAKEFLAG, 3, N_RETURNFLAG, 4, N_RESETFLAG, 6, N_INVISFLAG, 3, N_TRYDROPFLAG, 1, N_DROPFLAG, 7, N_SCOREFLAG, 10, N_INITFLAGS, 0,
N_SAYTEAM, 0,
N_CLIENT, 0,
N_AUTHTRY, 0, N_AUTHKICK, 0, N_AUTHCHAL, 0, N_AUTHANS, 0, N_REQAUTH, 0,
N_PAUSEGAME, 0, N_GAMESPEED, 0,
N_ADDBOT, 2, N_DELBOT, 1, N_INITAI, 0, N_FROMAI, 2, N_BOTLIMIT, 2, N_BOTBALANCE, 2,
N_MAPCRC, 0, N_CHECKMAPS, 1,
N_SWITCHNAME, 0, N_SWITCHMODEL, 2, N_SWITCHTEAM, 0,
N_INITTOKENS, 0, N_TAKETOKEN, 2, N_EXPIRETOKENS, 0, N_DROPTOKENS, 0, N_DEPOSITTOKENS, 2, N_STEALTOKENS, 0,
N_SERVCMD, 0,
N_DEMOPACKET, 0,
-1
};
#define SAUERBRATEN_LANINFO_PORT 28784
#define SAUERBRATEN_SERVER_PORT 28785
#define SAUERBRATEN_SERVINFO_PORT 28786
#define SAUERBRATEN_MASTER_PORT 28787
#define PROTOCOL_VERSION 260 // bump when protocol changes
#define DEMO_VERSION 1 // bump when demo format changes
#define DEMO_MAGIC "SAUERBRATEN_DEMO"
struct demoheader
{
char magic[16];
int version, protocol;
};
#define MAXNAMELEN 15
#define MAXTEAMLEN 4
enum
{
HICON_BLUE_ARMOUR = 0,
HICON_GREEN_ARMOUR,
HICON_YELLOW_ARMOUR,
HICON_HEALTH,
HICON_FIST,
HICON_SG,
HICON_CG,
HICON_RL,
HICON_RIFLE,
HICON_GL,
HICON_PISTOL,
HICON_QUAD,
HICON_RED_FLAG,
HICON_BLUE_FLAG,
HICON_NEUTRAL_FLAG,
HICON_TOKEN,
HICON_X = 20,
HICON_Y = 1650,
HICON_TEXTY = 1644,
HICON_STEP = 490,
HICON_SIZE = 120,
HICON_SPACE = 40
};
static struct itemstat { int add, max, sound; const char *name; int icon, info; } itemstats[] =
{
{10, 30, S_ITEMAMMO, "SG", HICON_SG, GUN_SG},
{20, 60, S_ITEMAMMO, "CG", HICON_CG, GUN_CG},
{5, 15, S_ITEMAMMO, "RL", HICON_RL, GUN_RL},
{5, 15, S_ITEMAMMO, "RI", HICON_RIFLE, GUN_RIFLE},
{10, 30, S_ITEMAMMO, "GL", HICON_GL, GUN_GL},
{30, 120, S_ITEMAMMO, "PI", HICON_PISTOL, GUN_PISTOL},
{25, 100, S_ITEMHEALTH, "H", HICON_HEALTH, -1},
{100, 200, S_ITEMHEALTH, "MH", HICON_HEALTH, 50},
{100, 100, S_ITEMARMOUR, "GA", HICON_GREEN_ARMOUR, A_GREEN},
{200, 200, S_ITEMARMOUR, "YA", HICON_YELLOW_ARMOUR, A_YELLOW},
{20000, 30000, S_ITEMPUP, "Q", HICON_QUAD, -1},
};
#define MAXRAYS 20
#define EXP_SELFDAMDIV 2
#define EXP_SELFPUSH 2.5f
#define EXP_DISTSCALE 1.5f
static const struct guninfo { int sound, attackdelay, damage, spread, projspeed, kickamount, range, rays, hitpush, exprad, ttl; const char *name, *file; short part; } guns[NUMGUNS] =
{
{ S_PUNCH1, 250, 50, 0, 0, 0, 14, 1, 80, 0, 0, "fist", "fist", 0 },
{ S_SG, 1400, 10, 400, 0, 20, 1024, 20, 80, 0, 0, "shotgun", "shotg", 0 },
{ S_CG, 100, 30, 100, 0, 7, 1024, 1, 80, 0, 0, "chaingun", "chaing", 0 },
{ S_RLFIRE, 800, 120, 0, 320, 10, 1024, 1, 160, 40, 0, "rocketlauncher", "rocket", 0 },
{ S_RIFLE, 1500, 100, 0, 0, 30, 2048, 1, 80, 0, 0, "rifle", "rifle", 0 },
{ S_FLAUNCH, 600, 90, 0, 200, 10, 1024, 1, 250, 45, 1500, "grenadelauncher", "gl", 0 },
{ S_PISTOL, 500, 35, 50, 0, 7, 1024, 1, 80, 0, 0, "pistol", "pistol", 0 },
{ S_FLAUNCH, 200, 20, 0, 200, 1, 1024, 1, 80, 40, 0, "fireball", NULL, PART_FIREBALL1 },
{ S_ICEBALL, 200, 40, 0, 120, 1, 1024, 1, 80, 40, 0, "iceball", NULL, PART_FIREBALL2 },
{ S_SLIMEBALL, 200, 30, 0, 640, 1, 1024, 1, 80, 40, 0, "slimeball", NULL, PART_FIREBALL3 },
{ S_PIGR1, 250, 50, 0, 0, 1, 12, 1, 80, 0, 0, "bite", NULL, 0 },
{ -1, 0, 120, 0, 0, 0, 0, 1, 80, 40, 0, "barrel", NULL, 0 }
};
#include "ai.h"
// inherited by fpsent and server clients
struct fpsstate
{
int health, maxhealth;
int armour, armourtype;
int quadmillis;
int gunselect, gunwait;
int ammo[NUMGUNS];
int aitype, skill;
fpsstate() : maxhealth(100), aitype(AI_NONE), skill(0) {}
void baseammo(int gun, int k = 2, int scale = 1)
{
ammo[gun] = (itemstats[gun-GUN_SG].add*k)/scale;
}
void addammo(int gun, int k = 1, int scale = 1)
{
itemstat &is = itemstats[gun-GUN_SG];
ammo[gun] = min(ammo[gun] + (is.add*k)/scale, is.max);
}
bool hasmaxammo(int type)
{
const itemstat &is = itemstats[type-I_SHELLS];
return ammo[type-I_SHELLS+GUN_SG]>=is.max;
}
bool canpickup(int type)
{
if(type<I_SHELLS || type>I_QUAD) return false;
itemstat &is = itemstats[type-I_SHELLS];
switch(type)
{
case I_BOOST: return maxhealth<is.max || health<maxhealth;
case I_HEALTH: return health<maxhealth;
case I_GREENARMOUR:
// (100h/100g only absorbs 200 damage)
if(armourtype==A_YELLOW && armour>=100) return false;
case I_YELLOWARMOUR: return !armourtype || armour<is.max;
case I_QUAD: return quadmillis<is.max;
default: return ammo[is.info]<is.max;
}
}
void pickup(int type)
{
if(type<I_SHELLS || type>I_QUAD) return;
itemstat &is = itemstats[type-I_SHELLS];
switch(type)
{
case I_BOOST:
maxhealth = min(maxhealth+is.info, is.max);
case I_HEALTH: // boost also adds to health
health = min(health+is.add, maxhealth);
break;
case I_GREENARMOUR:
case I_YELLOWARMOUR:
armour = min(armour+is.add, is.max);
armourtype = is.info;
break;
case I_QUAD:
quadmillis = min(quadmillis+is.add, is.max);
break;
default:
ammo[is.info] = min(ammo[is.info]+is.add, is.max);
break;
}
}
void respawn()
{
maxhealth = 100;
health = maxhealth;
armour = 0;
armourtype = A_BLUE;
quadmillis = 0;
gunselect = GUN_PISTOL;
gunwait = 0;
loopi(NUMGUNS) ammo[i] = 0;
ammo[GUN_FIST] = 1;
}
void spawnstate(int gamemode)
{
if(m_demo)
{
gunselect = GUN_FIST;
}
else if(m_insta)
{
armour = 0;
health = 1;
gunselect = GUN_RIFLE;
ammo[GUN_RIFLE] = 100;
}
else if(m_regencapture)
{
extern int regenbluearmour;
if(regenbluearmour)
{
armourtype = A_BLUE;
armour = 25;
}
gunselect = GUN_PISTOL;
ammo[GUN_PISTOL] = 40;
ammo[GUN_GL] = 1;
}
else if(m_tactics)
{
armourtype = A_GREEN;
armour = 100;
ammo[GUN_PISTOL] = 40;
int spawngun1 = rnd(5)+1, spawngun2;
gunselect = spawngun1;
baseammo(spawngun1, m_noitems ? 2 : 1);
do spawngun2 = rnd(5)+1; while(spawngun1==spawngun2);
baseammo(spawngun2, m_noitems ? 2 : 1);
if(m_noitems) ammo[GUN_GL] += 1;
}
else if(m_efficiency)
{
armourtype = A_GREEN;
armour = 100;
loopi(5) baseammo(i+1);
gunselect = GUN_CG;
ammo[GUN_CG] /= 2;
}
else if(m_ctf || m_collect)
{
armourtype = A_BLUE;
armour = 50;
ammo[GUN_PISTOL] = 40;
ammo[GUN_GL] = 1;
}
else if(m_sp)
{
if(m_dmsp)
{
armourtype = A_BLUE;
armour = 25;
}
ammo[GUN_PISTOL] = 80;
ammo[GUN_GL] = 1;
}
else
{
armourtype = A_BLUE;
armour = 25;
ammo[GUN_PISTOL] = 40;
ammo[GUN_GL] = 1;
}
}
// just subtract damage here, can set death, etc. later in code calling this
int dodamage(int damage)
{
int ad = (damage*(armourtype+1)*25)/100; // let armour absorb when possible
if(ad>armour) ad = armour;
armour -= ad;
damage -= ad;
health -= damage;
return damage;
}
int hasammo(int gun, int exclude = -1)
{
return gun >= 0 && gun <= NUMGUNS && gun != exclude && ammo[gun] > 0;
}
};
struct fpsent : dynent, fpsstate
{
int weight; // affects the effectiveness of hitpush
int clientnum, privilege, lastupdate, plag, ping;
int lifesequence; // sequence id for each respawn, used in damage test
int respawned, suicided;
int lastpain;
int lastaction, lastattackgun;
bool attacking;
int attacksound, attackchan, idlesound, idlechan;
int lasttaunt;
int lastpickup, lastpickupmillis, lastbase, lastrepammo, flagpickup, tokens;
vec lastcollect;
int frags, flags, deaths, totaldamage, totalshots;
editinfo *edit;
float deltayaw, deltapitch, deltaroll, newyaw, newpitch, newroll;
int smoothmillis;
string name, team, info;
int playermodel;
ai::aiinfo *ai;
int ownernum, lastnode;
vec muzzle;
fpsent() : weight(100), clientnum(-1), privilege(PRIV_NONE), lastupdate(0), plag(0), ping(0), lifesequence(0), respawned(-1), suicided(-1), lastpain(0), attacksound(-1), attackchan(-1), idlesound(-1), idlechan(-1), frags(0), flags(0), deaths(0), totaldamage(0), totalshots(0), edit(NULL), smoothmillis(-1), playermodel(-1), ai(NULL), ownernum(-1), muzzle(-1, -1, -1)
{
name[0] = team[0] = info[0] = 0;
respawn();
}
~fpsent()
{
freeeditinfo(edit);
if(attackchan >= 0) stopsound(attacksound, attackchan);
if(idlechan >= 0) stopsound(idlesound, idlechan);
if(ai) delete ai;
}
void hitpush(int damage, const vec &dir, fpsent *actor, int gun)
{
vec push(dir);
push.mul((actor==this && guns[gun].exprad ? EXP_SELFPUSH : 1.0f)*guns[gun].hitpush*damage/weight);
vel.add(push);
}
void stopattacksound()
{
if(attackchan >= 0) stopsound(attacksound, attackchan, 250);
attacksound = attackchan = -1;
}
void stopidlesound()
{
if(idlechan >= 0) stopsound(idlesound, idlechan, 100);
idlesound = idlechan = -1;
}
void respawn()
{
dynent::reset();
fpsstate::respawn();
respawned = suicided = -1;
lastaction = 0;
lastattackgun = gunselect;
attacking = false;
lasttaunt = 0;
lastpickup = -1;
lastpickupmillis = 0;
lastbase = lastrepammo = -1;
flagpickup = 0;
tokens = 0;
lastcollect = vec(-1e10f, -1e10f, -1e10f);
stopattacksound();
lastnode = -1;
}
int respawnwait(int secs, int delay = 0)
{
return max(0, secs - (::lastmillis - lastpain - delay)/1000);
}
};
struct teamscore
{
const char *team;
int score;
teamscore() {}
teamscore(const char *s, int n) : team(s), score(n) {}
static bool compare(const teamscore &x, const teamscore &y)
{
if(x.score > y.score) return true;
if(x.score < y.score) return false;
return strcmp(x.team, y.team) < 0;
}
};
static inline uint hthash(const teamscore &t) { return hthash(t.team); }
static inline bool htcmp(const char *key, const teamscore &t) { return htcmp(key, t.team); }
#define MAXTEAMS 128
struct teaminfo
{
char team[MAXTEAMLEN+1];
int frags;
};
static inline uint hthash(const teaminfo &t) { return hthash(t.team); }
static inline bool htcmp(const char *team, const teaminfo &t) { return !strcmp(team, t.team); }
namespace entities
{
extern vector<extentity *> ents;
extern const char *entmdlname(int type);
extern const char *itemname(int i);
extern int itemicon(int i);
extern void preloadentities();
extern void renderentities();
extern void resettriggers();
extern void checktriggers();
extern void checkitems(fpsent *d);
extern void checkquad(int time, fpsent *d);
extern void resetspawns();
extern void spawnitems(bool force = false);
extern void putitems(packetbuf &p);
extern void setspawn(int i, bool on);
extern void teleport(int n, fpsent *d);
extern void pickupeffects(int n, fpsent *d);
extern void teleporteffects(fpsent *d, int tp, int td, bool local = true);
extern void jumppadeffects(fpsent *d, int jp, bool local = true);
extern void repammo(fpsent *d, int type, bool local = true);
}
namespace game
{
struct clientmode
{
virtual ~clientmode() {}
virtual void preload() {}
virtual int clipconsole(int w, int h) { return 0; }
virtual void drawhud(fpsent *d, int w, int h) {}
virtual void rendergame() {}
virtual void respawned(fpsent *d) {}
virtual void setup() {}
virtual void checkitems(fpsent *d) {}
virtual int respawnwait(fpsent *d, int delay = 0) { return 0; }
virtual int getspawngroup(fpsent *d) { return 0; }
virtual float ratespawn(fpsent *d, const extentity &e) { return 1.0f; }
virtual void senditems(packetbuf &p) {}
virtual void removeplayer(fpsent *d) {}
virtual void died(fpsent *victim, fpsent *actor) {}
virtual void gameover() {}
virtual bool hidefrags() { return false; }
virtual int getteamscore(const char *team) { return 0; }
virtual void getteamscores(vector<teamscore> &scores) {}
virtual void aifind(fpsent *d, ai::aistate &b, vector<ai::interest> &interests) {}
virtual bool aicheck(fpsent *d, ai::aistate &b) { return false; }
virtual bool aidefend(fpsent *d, ai::aistate &b) { return false; }
virtual bool aipursue(fpsent *d, ai::aistate &b) { return false; }
};
extern clientmode *cmode;
extern void setclientmode();
// fps
extern int gamemode, nextmode;
extern string clientmap;
extern bool intermission, sendcrc;
extern int maptime, maprealtime, maplimit;
extern fpsent *player1;
extern vector<fpsent *> players, clients;
extern int lastspawnattempt;
extern int lasthit;
extern int respawnent;
extern int following;
extern int smoothmove, smoothdist;
extern bool clientoption(const char *arg);
extern fpsent *getclient(int cn);
extern fpsent *newclient(int cn);
extern const char *colorname(fpsent *d, const char *name = NULL, const char *prefix = "", const char *suffix = "", const char *alt = NULL);
extern const char *teamcolorname(fpsent *d, const char *alt = "you");
extern const char *teamcolor(const char *name, bool sameteam, const char *alt = NULL);
extern const char *teamcolor(const char *name, const char *team, const char *alt = NULL);
extern void teamsound(bool sameteam, int n, const vec *loc = NULL);
extern void teamsound(fpsent *d, int n, const vec *loc = NULL);
extern fpsent *pointatplayer();
extern fpsent *hudplayer();
extern fpsent *followingplayer(fpsent *fallback = NULL);
extern void stopfollowing();
extern void clientdisconnected(int cn, bool notify = true);
extern void clearclients(bool notify = true);
extern void startgame();
#if __EMSCRIPTEN__
extern void reloadgamemode();
#endif
extern float proximityscore(float x, float lower, float upper);
extern void pickgamespawn(fpsent *d);
extern void spawnplayer(fpsent *d);
extern void deathstate(fpsent *d, bool restore = false);
extern void damaged(int damage, fpsent *d, fpsent *actor, bool local = true);
extern void killed(fpsent *d, fpsent *actor);
extern void timeupdate(int timeremain);
extern void msgsound(int n, physent *d = NULL);
extern void drawicon(int icon, float x, float y, float sz = 120);
const char *mastermodecolor(int n, const char *unknown);
const char *mastermodeicon(int n, const char *unknown);
// client
extern bool connected, remote, demoplayback;
extern string servinfo;
extern vector<uchar> messages;
extern int parseplayer(const char *arg);
extern void ignore(int cn);
extern void unignore(int cn);
extern bool isignored(int cn);
extern bool addmsg(int type, const char *fmt = NULL, ...);
extern void switchname(const char *name);
extern void switchteam(const char *name);
extern void switchplayermodel(int playermodel);
extern void sendmapinfo();
extern void stopdemo();
extern void changemap(const char *name, int mode);
extern void forceintermission();
extern void c2sinfo(bool force = false);
extern void sendposition(fpsent *d, bool reliable = false);
// monster
struct monster;
extern vector<monster *> monsters;
extern void clearmonsters();
extern void preloadmonsters();
extern void stackmonster(monster *d, physent *o);
extern void updatemonsters(int curtime);
extern void rendermonsters();
extern void suicidemonster(monster *m);
extern void hitmonster(int damage, monster *m, fpsent *at, const vec &vel, int gun);
extern void monsterkilled();
extern void endsp(bool allkilled);
extern void spsummary(int accuracy);
// movable
struct movable;
extern vector<movable *> movables;
extern void clearmovables();
extern void stackmovable(movable *d, physent *o);
extern void updatemovables(int curtime);
extern void rendermovables();
extern void suicidemovable(movable *m);
extern void hitmovable(int damage, movable *m, fpsent *at, const vec &vel, int gun);
// weapon
extern int getweapon(const char *name);
extern void shoot(fpsent *d, const vec &targ);
extern void shoteffects(int gun, const vec &from, const vec &to, fpsent *d, bool local, int id, int prevaction);
extern void explode(bool local, fpsent *owner, const vec &v, dynent *safe, int dam, int gun);
extern void explodeeffects(int gun, fpsent *d, bool local, int id = 0);
extern void damageeffect(int damage, fpsent *d, bool thirdperson = true);
extern void gibeffect(int damage, const vec &vel, fpsent *d);
extern float intersectdist;
extern bool intersect(dynent *d, const vec &from, const vec &to, float &dist = intersectdist);
extern dynent *intersectclosest(const vec &from, const vec &to, fpsent *at, float &dist = intersectdist);
extern void clearbouncers();
extern void updatebouncers(int curtime);
extern void removebouncers(fpsent *owner);
extern void renderbouncers();
extern void clearprojectiles();
extern void updateprojectiles(int curtime);
extern void removeprojectiles(fpsent *owner);
extern void renderprojectiles();
extern void preloadbouncers();
extern void removeweapons(fpsent *owner);
extern void updateweapons(int curtime);
extern void gunselect(int gun, fpsent *d);
extern void weaponswitch(fpsent *d);
extern void avoidweapons(ai::avoidset &obstacles, float radius);
// scoreboard
extern void showscores(bool on);
extern void getbestplayers(vector<fpsent *> &best);
extern void getbestteams(vector<const char *> &best);
extern void clearteaminfo();
extern void setteaminfo(const char *team, int frags);
extern int statuscolor(fpsent *d, int color);
// render
struct playermodelinfo
{
const char *ffa, *blueteam, *redteam, *hudguns,
*vwep, *quad, *armour[3],
*ffaicon, *blueicon, *redicon;
bool ragdoll;
};
extern int playermodel, teamskins, testteam;
extern void saveragdoll(fpsent *d);
extern void clearragdolls();
extern void moveragdolls();
extern void changedplayermodel();
extern const playermodelinfo &getplayermodelinfo(fpsent *d);
extern int chooserandomplayermodel(int seed);
extern void swayhudgun(int curtime);
extern vec hudgunorigin(int gun, const vec &from, const vec &to, fpsent *d);
}
namespace server
{
extern const char *modename(int n, const char *unknown = "unknown");
extern const char *mastermodename(int n, const char *unknown = "unknown");
extern void startintermission();
extern void stopdemo();
extern void timeupdate(int secs);
extern const char *getdemofile(const char *file, bool init);
extern void forcemap(const char *map, int mode);
extern void forcepaused(bool paused);
extern void forcegamespeed(int speed);
extern void hashpassword(int cn, int sessionid, const char *pwd, char *result, int maxlen = MAXSTRLEN);
extern int msgsizelookup(int msg);
extern bool serveroption(const char *arg);
extern bool delayspawn(int type);
}
#endif
| 0 | 0.917928 | 1 | 0.917928 | game-dev | MEDIA | 0.96231 | game-dev | 0.894419 | 1 | 0.894419 |
opentibiabr/otservbr-global-archived | 1,110 | data/npc/scripts/ishebad.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
-- Promotion
local promoteKeyword = keywordHandler:addKeyword({'promot'}, StdModule.say, {npcHandler = npcHandler, text = 'Do you want to be promoted in your vocation for 20000 gold?'})
promoteKeyword:addChildKeyword({'yes'}, StdModule.promotePlayer, {npcHandler = npcHandler, level = 20, cost = 20000})
promoteKeyword:addChildKeyword({''}, StdModule.say, {npcHandler = npcHandler, text = 'Ok, whatever.', reset = true})
npcHandler:setMessage(MESSAGE_GREET, 'Be mourned, pilgrim in flesh. Are you looking for a promotion?')
npcHandler:setMessage(MESSAGE_FAREWELL, 'Good bye, |PLAYERNAME|!')
npcHandler:setMessage(MESSAGE_WALKAWAY, 'Good bye, |PLAYERNAME|!')
npcHandler:addModule(FocusModule:new())
| 0 | 0.802571 | 1 | 0.802571 | game-dev | MEDIA | 0.675082 | game-dev | 0.770494 | 1 | 0.770494 |
lilxyzw/lilAvatarUtils | 20,696 | Editor/MainWindow/AbstractTableGUI.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
using Object = UnityEngine.Object;
namespace jp.lilxyzw.avatarutils
{
internal abstract class AbstractTabelGUI
{
private const int GUI_INDENT_WIDTH = 16;
private const int GUI_SPACE_WIDTH = 5;
private const int GUI_FILTER_WIDTH = 50;
private const int GUI_LABEL_MIN_WIDTH = 10;
protected static readonly string[] L_ReferencedFrom = {"Referenced from",""};
public bool[] labelMasks = {};
public float[] rectWidths = {};
public bool applyFilter = false;
protected TableProperties[] libs;
internal GameObject gameObject;
protected bool isModified = false;
protected bool isDescending = true;
protected int sortIndex = -1;
protected Vector2 scrollPosition = new(0,0);
protected Rect rectBase;
protected delegate bool LineGUIOverride(int count, bool[] emphasizes);
protected LineGUIOverride lineGUIOverride = null;
private int rectModifyIndex = -1;
private Event m_event;
internal AvatarUtils m_window;
private float tableWidth = 0;
private bool isScrolling = false;
private int selectedLine = -1;
internal virtual void Draw()
{
if(IsEmptyLibs()) return;
m_event = Event.current;
if(m_event.type == EventType.MouseDown) isScrolling = true;
if(m_event.type == EventType.MouseUp) isScrolling = false;
if(!isScrolling) tableWidth = scrollPosition.x + m_window.position.width + 100;
if(rectWidths == null || rectWidths.Length != libs.Length)
{
rectWidths = libs.Select(lib => lib.rect.width).ToArray();
}
if(labelMasks == null || labelMasks.Length != libs.Length)
{
labelMasks = Enumerable.Repeat(true,libs.Length).ToArray();
}
labelMasks[0] = true;
GUI.enabled = isModified;
var rectButtons = EditorGUILayout.GetControlRect();
var rectButton1 = new Rect(rectButtons.x, rectButtons.y, 100, rectButtons.height);
var rectButton2 = new Rect(rectButton1.xMax + GUI_SPACE_WIDTH, rectButtons.y, 100, rectButtons.height);
if(L10n.Button(rectButton1, "Apply"))
{
ApplyModification();
Set();
m_window.Analyze();
}
if(L10n.Button(rectButton2, "Revert"))
{
Set();
}
GUI.enabled = true;
var rectButton3 = new Rect(rectButton2.xMax + GUI_SPACE_WIDTH, rectButtons.y, 100, rectButtons.height);
rectButton3.xMax = rectButtons.xMax;
ButtonEx(rectButton3);
var rect = EditorGUILayout.GetControlRect();
libs[0].rect = new Rect(
GUI_INDENT_WIDTH + rect.x,
rect.y,
rectWidths[0],
rect.height
);
for(int i = 1; i < libs.Length; i++)
{
libs[i].rect = new Rect(
GUI_SPACE_WIDTH + libs[i-1].rect.xMax,
rect.y,
rectWidths[i],
rect.height
);
if(!labelMasks[i])
{
libs[i].rect.x = libs[i-1].rect.xMax;
libs[i].rect.width = 0;
}
}
SetBaseRect();
var rectShift = GetShiftedRects();
// Toggle labels
if(m_event.type == EventType.MouseDown && m_event.button == 1 && rectBase.Contains(m_event.mousePosition))
{
var labelMenu = new GenericMenu();
for(int j = 1; j < libs.Length; j++)
{
var k = j;
labelMenu.AddItem(new GUIContent(libs[k].label[0].Replace("/"," \u2044 ")), labelMasks[k], () => labelMasks[k] = !labelMasks[k]);
}
labelMenu.ShowAsContext();
}
// Resize
for(int i = 0; i < libs.Length; i++)
{
if(!labelMasks[i]) continue;
var rectHit = new Rect(rectShift[i].xMax+2-5, rectShift[i].y, 11, rectShift[i].height);
var rectLine = new Rect(rectShift[i].xMax+2 , rectShift[i].y, 1, rectShift[i].height);
EditorGUIUtility.AddCursorRect(rectHit, MouseCursor.ResizeHorizontal);
EditorGUI.DrawRect(rectLine, new Color(0.5f, 0.5f, 0.5f, 0.5f));
if(rectModifyIndex == i)
{
rectWidths[i] = Mathf.Max(GUI_LABEL_MIN_WIDTH, m_event.mousePosition.x - rectShift[i].x - 5);
m_window.Repaint();
}
if(m_event.type == EventType.MouseDown && m_event.button == 0 && rectHit.Contains(m_event.mousePosition))
{
rectModifyIndex = i;
}
if(m_event.type == EventType.MouseUp)
{
rectModifyIndex = -1;
}
}
// Labels
for(int i = 0; i < libs.Length; i++)
{
if(!labelMasks[i]) continue;
bool isSorted = sortIndex == i;
if(isSorted) EditorGUI.DrawRect(rectShift[i], new Color(0.5f, 0.5f, 0.5f, 0.2f));
if(L10n.Button(rectShift[i], libs[i].label, EditorStyles.label) && m_event.button == 0)
{
if(isSorted) isDescending = !isDescending;
sortIndex = i;
Sort();
SortLibs();
}
}
// Emphasize
UpdateRects();
rectShift = GetShiftedRects();
var rectFirst = rectShift[0];
var rectEmpFilter = new Rect(
rectFirst.x - GUI_INDENT_WIDTH,
rectFirst.y,
GUI_INDENT_WIDTH,
rectFirst.height
);
applyFilter = EditorGUI.Toggle(rectEmpFilter, applyFilter);
if(rectFirst.width >= 150)
{
var rectEmpPath = new Rect(rectFirst.x, rectFirst.y, GUI_FILTER_WIDTH, rectFirst.height);
var rectEmpPathField = new Rect(rectEmpPath.xMax, rectFirst.y, rectFirst.width-GUI_FILTER_WIDTH, rectFirst.height);
L10n.LabelField(rectEmpPath, "Filters");
EmphasizeField(0, rectEmpPathField);
}
else
{
EmphasizeField(0, rectShift[0]);
}
for(int i = 1; i < libs.Length; i++)
{
if(!labelMasks[i]) continue;
EmphasizeField(i, rectShift[i]);
}
GUIUtils.DrawLine();
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
float UIYBuffer = libs[0].rect.y;
for(int count = 0; count < libs[0].items.Count; count++)
{
LineGUI(count);
}
if(UIYBuffer == libs[0].rect.y) L10n.LabelField("Nothing found. Please turn off the filter or change the conditions.");
EditorGUILayout.EndScrollView();
}
protected virtual void LineGUI(int count)
{
// Check emphasizes
var emphasizes = new bool[libs.Length];
for(int i = 0; i < libs.Length; i++)
{
if(libs[i].emphasizeCondition != null)
{
emphasizes[i] = libs[i].emphasizeCondition.Invoke(i,count);
continue;
}
var obj = libs[i].items[count];
if(libs[i].isMask)
{
if(obj == null)
{
emphasizes[i] = false;
}
else if(obj.GetType().IsEnum)
{
emphasizes[i] = MathHelper.BitMask((int)libs[i].emphasize, (int)obj);
}
else switch(obj)
{
case int val : emphasizes[i] = MathHelper.BitMask((int)libs[i].emphasize, val); break;
case bool val : emphasizes[i] = MathHelper.BitMask((int)libs[i].emphasize, val); break;
default : emphasizes[i] = false; break;
}
}
else if(obj is Object o && !o)
{
emphasizes[i] = FilterString("None", (string)libs[i].emphasize);
}
else if(obj == null)
{
emphasizes[i] = false;
}
else if(obj.GetType().IsEnum)
{
emphasizes[i] = FilterString(obj.ToString(), (string)libs[i].emphasize);
}
else switch(obj)
{
case int val : emphasizes[i] = val >= (int)libs[i].emphasize; break;
case string val : emphasizes[i] = FilterString(val, (string)libs[i].emphasize); break;
case Object val : emphasizes[i] = FilterString(val.name, (string)libs[i].emphasize); break;
default : emphasizes[i] = false; break;
}
}
if(applyFilter && !emphasizes.Any(emp => emp)) return;
// GUI
EditorGUI.BeginChangeCheck();
var rectLine = EditorGUILayout.BeginVertical();
var rectBox = new Rect(rectLine.x, rectLine.y, rectLine.width, rectLine.height+2);
var e = Event.current;
if(e.type == EventType.MouseDown && rectBox.Contains(e.mousePosition))
{
selectedLine = count;
m_window.Repaint();
}
if(selectedLine == count)
{
EditorGUI.DrawRect(rectBox, GUIUtils.colorActive);
}
else
{
if(count % 2 != 0) EditorGUI.DrawRect(rectBox, new Color(0.5f,0.5f,0.5f,0.0f));
else EditorGUI.DrawRect(rectBox, new Color(0.5f,0.5f,0.5f,0.1f));
}
UpdateRects();
if(lineGUIOverride != null && !lineGUIOverride.Invoke(count, emphasizes)) return;
for(int i = 0; i < libs.Length; i++)
{
if(!labelMasks[i]) continue;
if(libs[i].mainGUI != null && !libs[i].mainGUI.Invoke(i, count, emphasizes[i])) continue;
if(libs[i].isEditable)
{
libs[i].items[count] = GUIUtils.AutoField(libs[i].rect, libs[i].items[count], libs[i].type, libs[i].allowSceneObjects, emphasizes[i]);
}
else
{
GUIUtils.AutoLabelField(libs[i].rect, libs[i].items[count], emphasizes[i]);
}
}
GUI.enabled = true;
LineGUIEx(count);
EditorGUILayout.EndVertical();
if(EditorGUI.EndChangeCheck()) isModified = true;
}
protected virtual void ButtonEx(Rect position)
{
}
protected virtual void LineGUIEx(int count)
{
}
internal virtual void Set()
{
}
protected virtual void Sort()
{
}
protected virtual void SortLibs()
{
}
protected virtual void ApplyModification()
{
}
protected void SortLibs(object[] keys)
{
var libsNew = new TableProperties[libs.Length];
for(int i = 0; i < libs.Length; i++)
{
libsNew[i] = TableProperties.CopyWithoutItems(libs[i]);
}
int count = 0;
foreach(var key in keys)
{
int index = libs[0].items.IndexOf(key);
if(index == -1) continue;
for(int i = 0; i < libs.Length; i++)
{
libsNew[i].items.Add(libs[i].items[index]);
}
count++;
}
libs = libsNew;
}
protected bool IsEmptyLibs()
{
if(libs == null || libs.Count() == 0) return true;
foreach(var lib in libs)
{
if(lib.items == null || lib.items.Count == 0) return true;
}
return false;
}
protected void UpdateRects()
{
float width = Mathf.Max(tableWidth, libs[libs.Length-1].rect.xMax - libs[0].rect.x + 16);
rectBase = EditorGUILayout.GetControlRect(GUILayout.Width(width), GUILayout.Height(16));
for(int i = 0; i < libs.Length; i++)
{
libs[i].rect.y = rectBase.y;
}
}
protected void SetBaseRect()
{
rectBase.x = libs[0].rect.x + GUI_INDENT_WIDTH;
rectBase.y = libs[0].rect.y;
rectBase.width = Mathf.Max(tableWidth, libs[libs.Length-1].rect.xMax - libs[0].rect.x + 16);
rectBase.height = 16;
}
protected Rect[] GetShiftedRects()
{
return libs.Select(lib => new Rect(lib.rect.x - scrollPosition.x, lib.rect.y, lib.rect.width, lib.rect.height)).ToArray();
}
protected bool FilterString(string val, string emp)
{
if(string.IsNullOrEmpty(emp)) return false;
else if(emp.StartsWith("!")) return !val.Contains(emp.Substring(1));
else return val.Contains(emp);
}
private void EmphasizeField(int i, Rect rect)
{
if(libs[i].emphasizeGUI != null)
{
libs[i].emphasize = libs[i].emphasizeGUI.Invoke(i, rect);
}
else if(libs[i].isMask)
{
if(libs[i].emphasizeLabels != null) libs[i].emphasize = EditorGUI.MaskField(rect, (int)libs[i].emphasize, libs[i].emphasizeLabels);
else libs[i].emphasize = EditorGUI.MaskField(rect, (int)libs[i].emphasize, GUIUtils.MASK_LABELS_BOOL);
}
else switch(libs[i].emphasize)
{
case int val : libs[i].emphasize = EditorGUI.IntField(rect, val); break;
case string val : libs[i].emphasize = EditorGUI.TextField(rect, val); break;
}
}
internal void ReferencesGUI(Object obj)
{
if(!m_window.refs.TryGetValue(obj, out var parents) || parents.Count == 0) return;
foreach(var parent in parents)
{
GUIByType(parent);
EditorGUI.indentLevel++;
ReferencesGUIInternal(new HashSet<Object>(), parent);
EditorGUI.indentLevel--;
}
}
private void ReferencesGUIInternal(HashSet<Object> showed, Object obj)
{
if(!m_window.refs.TryGetValue(obj, out var parents) || parents.Count == 0) return;
foreach(var parent in parents)
{
if(!showed.Add(parent)) continue;
GUIByType(parent);
EditorGUI.indentLevel++;
ReferencesGUIInternal(showed, parent);
EditorGUI.indentLevel--;
}
}
private void GUIByType(Object obj)
{
if(obj is AnimatorState || obj is AnimatorStateMachine)
{
var machine = GetParent<AnimatorStateMachine>(new HashSet<Object>(), obj);
var controller = GetParent<AnimatorController>(new HashSet<Object>(), obj);
if(machine && controller) LabelFieldWithSelection(controller, machine, obj);
else GUIUtils.LabelFieldWithSelection(obj);
}
else
{
GUIUtils.LabelFieldWithSelection(obj);
}
}
private T GetParent<T>(HashSet<Object> visited, Object obj) where T : Object
{
if(!obj || !visited.Add(obj) || !m_window.refs.TryGetValue(obj, out var parents) || parents.Count == 0) return obj as T;
var first = parents.Select(p => GetParent<T>(visited, p)).FirstOrDefault(p => p);
return first ? first : obj as T;
}
private static void LabelFieldWithSelection(RuntimeAnimatorController controller, AnimatorStateMachine machine, Object target, bool hilight = false)
{
Rect rect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect());
GUIStyle style;
if(hilight) style = GUIUtils.styleRed;
else style = EditorStyles.label;
GUIContent content = EditorGUIUtility.ObjectContent(target, target.GetType());
content.text = $"{target.name} ({target.GetType().Name})";
content.tooltip = AssetDatabase.GetAssetPath(target);
var sizeCopy = EditorGUIUtility.GetIconSize();
EditorGUIUtility.SetIconSize(new Vector2(rect.height-2, rect.height-2));
if(GUIUtils.UnchangeButton(rect, content, style) && target)
{
Selection.activeObject = controller;
if(controller is AnimatorController ac)
{
var index = 0;
foreach(var l in ac.layers)
{
if(l.stateMachine == machine)
{
var type = typeof(UnityEditor.Graphs.AnimationCurveTypeConverter).Assembly.GetType("UnityEditor.Graphs.AnimatorControllerTool");
var window = EditorWindow.GetWindow(type);
type.GetProperty("selectedLayerIndex", BindingFlags.Public | BindingFlags.Instance).SetValue(window, index);
break;
}
index++;
}
}
Selection.activeObject = target;
EditorGUIUtility.PingObject(target);
}
EditorGUIUtility.SetIconSize(sizeCopy);
}
}
internal class TableProperties
{
public delegate object EmphasizeGUI(int i, Rect rect); // Return result
public delegate bool EmphasizeCondition(int i, int count); // Return result
public delegate bool MainGUI(int i, int count, bool emp); // true: Draw Default GUI
public List<object> items;
public string[] label;
public Rect rect;
public bool isEditable;
public Type type;
public bool allowSceneObjects;
public bool isMask;
public object emphasize;
public string[] emphasizeLabels;
public EmphasizeGUI emphasizeGUI;
public EmphasizeCondition emphasizeCondition;
public MainGUI mainGUI;
public TableProperties(
List<object> itemsIn,
string[] labelIn,
Rect rectIn,
bool isEditableIn,
Type typeIn,
bool allowSceneObjectsIn,
bool isMaskIn,
object emphasizeIn,
string[] emphasizeLabelsIn,
EmphasizeGUI emphasizeGUIIn,
EmphasizeCondition emphasizeConditionIn,
MainGUI mainGUIIn
)
{
items = itemsIn;
label = labelIn;
rect = rectIn;
isEditable = isEditableIn;
type = typeIn;
allowSceneObjects = allowSceneObjectsIn;
isMask = isMaskIn;
emphasize = emphasizeIn;
emphasizeLabels = emphasizeLabelsIn;
emphasizeGUI = emphasizeGUIIn;
emphasizeCondition = emphasizeConditionIn;
mainGUI = mainGUIIn;
}
public static TableProperties CopyWithoutItems(TableProperties tp)
{
return new TableProperties(
new List<object>(),
tp.label,
tp.rect,
tp.isEditable,
tp.type,
tp.allowSceneObjects,
tp.isMask,
tp.emphasize,
tp.emphasizeLabels,
tp.emphasizeGUI,
tp.emphasizeCondition,
tp.mainGUI
);
}
}
}
| 0 | 0.946962 | 1 | 0.946962 | game-dev | MEDIA | 0.697319 | game-dev,desktop-app | 0.969707 | 1 | 0.969707 |
pmret/papermario | 2,039 | src/world/dead/area_flo/flo_16/entity.c | #include "flo_16.h"
#include "entity.h"
#define SUPER_BLOCK_MAPVAR MV_SuperBlock
#define SUPER_BLOCK_GAMEFLAG GF_FLO16_SuperBlock
#include "world/common/entity/SuperBlock.inc.c"
EvtScript N(EVS_TetherCameraToPlayer) = {
Label(0)
Call(GetPlayerPos, LVar0, LVar1, LVar2)
Call(SetCamTarget, CAM_DEFAULT, LVar0, LVar1, LVar2)
Wait(1)
Goto(0)
Return
End
};
EvtScript N(EVS_UseSpring) = {
Call(DisablePlayerInput, true)
Call(DisablePlayerPhysics, true)
Call(SetPlayerActionState, ACTION_STATE_LAUNCH)
Wait(2)
Call(GetPlayerPos, LVar7, LVar8, LVar9)
ExecGetTID(N(EVS_TetherCameraToPlayer), LVarA)
Call(SetPlayerJumpscale, Float(0.7))
Call(PlayerJump, 450, 180, -120, 30)
Call(SetPlayerActionState, ACTION_STATE_IDLE)
Call(DisablePlayerPhysics, false)
Call(DisablePlayerInput, false)
Return
End
};
API_CALLABLE(N(IsPlayerPounding)) {
script->varTable[0] = false;
if (gPlayerStatus.actionState == ACTION_STATE_SPIN_POUND || gPlayerStatus.actionState == ACTION_STATE_TORNADO_POUND) {
script->varTable[0] = true;
}
return ApiStatus_DONE2;
}
EvtScript N(EVS_MonitorCeilingPound) = {
IfEq(AF_FLO16_FoundHiddenStarPiece, false)
Call(N(IsPlayerPounding))
IfEq(LVar0, 0)
Return
EndIf
Call(GetPlayerPos, LVar0, LVar1, LVar2)
Switch(LVar0)
CaseRange(620, 660)
Call(MakeItemEntity, ITEM_STAR_PIECE, 640, 145, -100, ITEM_SPAWN_MODE_FALL_NEVER_VANISH, GF_FLO16_Item_StarPiece)
Set(AF_FLO16_FoundHiddenStarPiece, true)
EndSwitch
EndIf
Return
End
};
EvtScript N(EVS_MakeEntities) = {
Set(AF_FLO16_FoundHiddenStarPiece, false)
BindTrigger(Ref(N(EVS_MonitorCeilingPound)), TRIGGER_FLOOR_TOUCH, COLLIDER_o214, 1, 0)
EVT_MAKE_SUPER_BLOCK(350, 240, -100, 0)
Call(MakeEntity, Ref(Entity_ScriptSpring), 472, 100, -100, 0, MAKE_ENTITY_END)
Call(AssignScript, Ref(N(EVS_UseSpring)))
Return
End
};
| 0 | 0.89633 | 1 | 0.89633 | game-dev | MEDIA | 0.966783 | game-dev | 0.942018 | 1 | 0.942018 |
space-wizards/space-station-14 | 1,092 | Content.Shared/Containers/ExitContainerOnMoveSystem.cs | using Content.Shared.Climbing.Systems;
using Content.Shared.Movement.Events;
using Robust.Shared.Containers;
namespace Content.Shared.Containers;
public sealed class ExitContainerOnMoveSystem : EntitySystem
{
[Dependency] private readonly ClimbSystem _climb = default!;
[Dependency] private readonly SharedContainerSystem _container = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ExitContainerOnMoveComponent, ContainerRelayMovementEntityEvent>(OnContainerRelay);
}
private void OnContainerRelay(Entity<ExitContainerOnMoveComponent> ent, ref ContainerRelayMovementEntityEvent args)
{
var (_, comp) = ent;
if (!TryComp<ContainerManagerComponent>(ent, out var containerManager))
return;
if (!_container.TryGetContainer(ent, comp.ContainerId, out var container, containerManager) || !container.Contains(args.Entity))
return;
_climb.ForciblySetClimbing(args.Entity, ent);
_container.RemoveEntity(ent, args.Entity, containerManager);
}
}
| 0 | 0.836688 | 1 | 0.836688 | game-dev | MEDIA | 0.65515 | game-dev | 0.914923 | 1 | 0.914923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.